Files
jackwener__opencli/clis/tieba/search.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

120 lines
4.9 KiB
TypeScript

import { ArgumentError, EmptyResultError } from '@jackwener/opencli/errors';
import { cli, Strategy, type CommandArgs } from '@jackwener/opencli/registry';
import { buildTiebaSearchItems, type RawTiebaSearchItem, normalizeTiebaLimit } from './utils.js';
const MAX_SUPPORTED_PAGE = '1';
/**
* Extract search result cards from tieba's current desktop search page.
*/
function buildExtractSearchResultsEvaluate(limit: number): string {
return `
(async () => {
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const waitFor = async (predicate, timeoutMs = 5000) => {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (predicate()) return true;
await wait(100);
}
return false;
};
const getVueProps = (element) => {
const vue = element && element.__vue__ ? element.__vue__ : null;
return vue ? (vue._props || vue.$props || {}) : {};
};
await waitFor(() => {
const bodyText = document.body?.innerText || '';
return Boolean(
document.querySelector('.threadcardclass.thread-new3.index-feed-cards')
|| document.querySelector('.search-no-result, .search-nodata, .no-result')
|| /百度安全验证|安全验证|请完成验证/.test(bodyText)
);
});
const items = document.querySelectorAll('.threadcardclass.thread-new3.index-feed-cards');
return Array.from(items).slice(0, ${limit}).map((item) => {
const forum = item.querySelector('.forum-name-text, .forum-name')?.textContent?.trim() || '';
const meta = item.querySelector('.user-forum-info')?.textContent?.replace(/\\s+/g, ' ').trim() || '';
const metaWithoutForum = forum && meta.startsWith(forum)
? meta.slice(forum.length).trim()
: meta;
const metaMatch = metaWithoutForum.match(/^(.*?)\\s*发布于\\s*(.+)$/);
const actionBar = item.querySelector('.action-bar-container.search-action-bar');
const businessInfo = getVueProps(actionBar).businessInfo || {};
const href = item.querySelector('a[href*="/p/"]')?.href || '';
const threadId = String(businessInfo.thread_id || '').trim();
const title = item.querySelector('.title-wrap')?.textContent?.trim()
|| item.querySelector('.title-content-wrap')?.textContent?.trim()
|| '';
const snippet = item.querySelector('.title-content-wrap')?.textContent?.trim()
|| item.querySelector('.abstract-wrap')?.textContent?.trim()
|| '';
return {
title,
forum,
author: metaMatch ? metaMatch[1].trim() : metaWithoutForum,
time: metaMatch ? metaMatch[2].trim() : '',
snippet: snippet.substring(0, 200),
id: threadId,
url: href || (threadId ? 'https://tieba.baidu.com/p/' + threadId : ''),
};
}).filter((item) => item.title);
})()
`;
}
/**
* Normalize CLI args into the concrete search page URL.
*/
function getSearchUrl(kwargs: CommandArgs): string {
const keyword = String(kwargs.keyword || '');
const pageNumber = Number(kwargs.page || 1);
return `https://tieba.baidu.com/f/search/res?qw=${encodeURIComponent(keyword)}&ie=utf-8&pn=${pageNumber}`;
}
/**
* Tieba's current desktop search UI no longer exposes a reliable browser-page transition.
*/
function assertSupportedPage(kwargs: CommandArgs): void {
const pageNumber = String(kwargs.page || 1);
if (pageNumber === MAX_SUPPORTED_PAGE) return;
throw new ArgumentError(
`tieba search currently only supports --page ${MAX_SUPPORTED_PAGE}`,
`Baidu Tieba search no longer exposes stable browser pagination; omit --page or use --page ${MAX_SUPPORTED_PAGE}`,
);
}
cli({
site: 'tieba',
name: 'search',
description: 'Search posts across tieba',
domain: 'tieba.baidu.com',
strategy: Strategy.COOKIE,
browser: true,
navigateBefore: false,
args: [
{ name: 'keyword', positional: true, required: true, type: 'string', help: 'Search keyword' },
// Restrict unsupported pages before the browser session starts.
{ name: 'page', type: 'int', default: 1, choices: ['1'], help: 'Page number (currently only 1 is supported)' },
{ name: 'limit', type: 'int', default: 20, help: 'Number of items to return' },
],
columns: ['rank', 'title', 'forum', 'author', 'time'],
func: async (page, kwargs) => {
assertSupportedPage(kwargs);
const limit = normalizeTiebaLimit(kwargs.limit);
// Use the default browser settle path so we do not read a stale page.
await page.goto(getSearchUrl(kwargs));
const raw = await page.evaluate(buildExtractSearchResultsEvaluate(limit));
const items = buildTiebaSearchItems(Array.isArray(raw) ? raw as RawTiebaSearchItem[] : [], limit);
if (!items.length) {
throw new EmptyResultError('tieba search', 'Tieba may have blocked the result page, or the DOM structure may have changed');
}
return items;
},
});