Files
jackwener__opencli/clis/tieba/posts.ts
jakevin 4fe9a73ebc refactor: migrate adapter imports to package exports (#795)
* refactor: migrate adapter imports to package exports

Replace all relative imports (../../src/registry.js, ../../browser/cdp.js, etc.)
with package exports (@jackwener/opencli/registry, @jackwener/opencli/errors, etc.)
across all 484 adapter files.

This decouples adapter import resolution from directory structure:
- User CLIs in ~/.opencli/clis/ resolve via node_modules symlink
- Internal adapters resolve via Node.js self-referencing
- No more shim files needed for import resolution

Changes:
- package.json: add sub-path exports for all public modules
- clis/**: replace relative imports with @jackwener/opencli/...
- discovery.ts: simplify ensureUserCliCompatShims to symlink-only
- registry-api.ts: export CommandArgs type
- Remove root-level shim directories (browser/, download/, pipeline/)
- Remove shim entries from tsconfig.json include and package.json files

* test: add regression tests for package exports

Prevents regressions like #788/#791 by:
1. Scanning all adapter files for forbidden relative imports
   (../../src/, ../../browser/, etc.) — fails if any remain
2. Verifying every package.json export maps to an existing source file

18 new test cases.

* fix: use junction on Windows + broaden test patterns

- discovery.ts: use 'junction' symlink type on Windows (no admin required)
- package-exports.test.ts: generalize forbidden patterns to catch any
  depth of ../ traversal (not just ../../ and ../../../)

* fix: update stale vi.mock/importActual paths in adapter tests

Test files still used old relative paths for vi.mock() and
vi.importActual() calls. Updated 5 test files to use package exports.
Also broadened regression test patterns to catch mock/importActual paths.

* fix: use rm instead of unlink for symlink cleanup, add warn on failure

Addresses review feedback from Astro-Han:
- rm() handles both symlinks and stale directories (unlink fails on dirs)
- Log a warning when symlink creation fails instead of silent catch

* docs: update import examples to use package exports

Update all documentation, contributing guides, and skills to use
@jackwener/opencli/registry instead of ../../src/registry.js.

Without this, users following the docs would write adapters with
broken imports since the old shim files are no longer created.
2026-04-05 16:02:17 +08:00

109 lines
3.4 KiB
TypeScript

import { EmptyResultError } from '@jackwener/opencli/errors';
import { cli, Strategy, type CommandArgs } from '@jackwener/opencli/registry';
import type { IPage } from '@jackwener/opencli/types';
import {
buildTiebaPostCardsFromPagePc,
buildTiebaPostItems,
normalizeTiebaLimit,
signTiebaPcParams,
type RawTiebaPagePcFeedEntry,
} from './utils.js';
interface TiebaPagePcResponse {
error_code?: number;
page_data?: {
feed_list?: RawTiebaPagePcFeedEntry[];
};
}
function getForumPageNumber(kwargs: CommandArgs): number {
return Math.max(1, Number(kwargs.page || 1));
}
function getForumUrl(kwargs: CommandArgs): string {
const forum = String(kwargs.forum || '');
return `https://tieba.baidu.com/f?kw=${encodeURIComponent(forum)}&ie=utf-8&pn=${(getForumPageNumber(kwargs) - 1) * 50}`;
}
/**
* Rebuild the signed page_pc request instead of scraping only the visible thread cards.
*/
function buildTiebaPagePcParams(kwargs: CommandArgs, limit: number): Record<string, string> {
return {
kw: encodeURIComponent(String(kwargs.forum || '')),
pn: String(getForumPageNumber(kwargs)),
sort_type: '-1',
is_newfrs: '1',
is_newfeed: '1',
rn: '30',
rn_need: String(Math.min(Math.max(limit + 10, 10), 30)),
tbs: '',
subapp_type: 'pc',
_client_type: '20',
};
}
/**
* Tieba expects the signed forum-list request to be replayed with the browser's cookies.
*/
async function fetchTiebaPagePc(page: IPage, kwargs: CommandArgs, limit: number): Promise<TiebaPagePcResponse> {
await page.goto(getForumUrl(kwargs), { waitUntil: 'none' });
await page.wait(2);
const params = buildTiebaPagePcParams(kwargs, limit);
const cookies = await page.getCookies({ domain: 'tieba.baidu.com' });
const cookieHeader = cookies.map((item) => `${item.name}=${item.value}`).join('; ');
const body = new URLSearchParams({
...params,
sign: signTiebaPcParams(params),
}).toString();
const response = await fetch('https://tieba.baidu.com/c/f/frs/page_pc', {
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
cookie: cookieHeader,
'x-requested-with': 'XMLHttpRequest',
referer: getForumUrl(kwargs),
'user-agent': 'Mozilla/5.0',
},
body,
});
const text = await response.text();
try {
return JSON.parse(text) as TiebaPagePcResponse;
} catch {
return {};
}
}
cli({
site: 'tieba',
name: 'posts',
description: 'Browse posts in a tieba forum',
domain: 'tieba.baidu.com',
strategy: Strategy.COOKIE,
browser: true,
navigateBefore: false,
args: [
{ name: 'forum', positional: true, required: true, type: 'string', help: 'Forum name in Chinese' },
{ name: 'page', type: 'int', default: 1, help: 'Page number' },
{ name: 'limit', type: 'int', default: 20, help: 'Number of items to return' },
],
columns: ['rank', 'title', 'author', 'replies'],
func: async (page, kwargs) => {
const limit = normalizeTiebaLimit(kwargs.limit);
const payload = await fetchTiebaPagePc(page, kwargs, limit);
const rawFeeds = Array.isArray(payload.page_data?.feed_list) ? payload.page_data.feed_list : [];
const rawCards = buildTiebaPostCardsFromPagePc(rawFeeds);
const items = buildTiebaPostItems(rawCards, limit);
if (!items.length || payload.error_code) {
throw new EmptyResultError('tieba posts', 'Tieba may have blocked the forum page, or the DOM structure may have changed');
}
return items;
},
});