{"record":{"id":"fa2dcb9d00374bb7","repo":"jackwener/OpenCLI","slug":"browser-session-required-for-bilibili-subtitle","errorCode":null,"errorMessage":"Browser session required for bilibili subtitle","messagePattern":"Browser session required for bilibili subtitle","errorType":"exception","errorClass":"CommandExecutionError","httpStatus":null,"severity":"error","filePath":"clis/bilibili/subtitle.js","lineNumber":19,"sourceCode":"import { cli, Strategy } from '@jackwener/opencli/registry';\nimport { AuthRequiredError, CommandExecutionError, EmptyResultError } from '@jackwener/opencli/errors';\nimport { apiGet, resolveBvid, parsePageArg, selectVideoPart } from './utils.js';\ncli({\n    site: 'bilibili',\n    name: 'subtitle',\n    access: 'read',\n    description: '获取 Bilibili 视频的字幕',\n    domain: 'www.bilibili.com',\n    strategy: Strategy.COOKIE,\n    args: [\n        { name: 'bvid', required: true, positional: true, help: 'Bilibili 视频 BV ID（如 BV1xx411c7mD），或视频 URL / b23.tv 短链' },\n        { name: 'lang', required: false, help: '字幕语言代码 (如 zh-CN, en-US, ai-zh)，默认取第一个' },\n        { name: 'page', required: false, help: '分P 选集序号（从 1 开始）。多 P 视频取该集字幕；缺省取默认 P1' },\n    ],\n    columns: ['index', 'from', 'to', 'content'],\n    func: async (page, kwargs) => {\n        if (!page)\n            throw new CommandExecutionError('Browser session required for bilibili subtitle');\n        const bvid = await resolveBvid(kwargs.bvid);\n        const selectedPage = parsePageArg(kwargs.page);\n        // 1. 通过 view API 拿 cid。\n        //    以前的实现走 page.goto(/video/<bvid>) + window.__INITIAL_STATE__.videoData.cid，\n        //    bangumi 绑定的 bvid（番剧/纪录片/电影/综艺）页面 state 不在 videoData 而在 epList，\n        //    导致 SELECTOR 错。view API 接受任何 bvid（UGC + PGC 都通），且不依赖 DOM 结构。\n        let view;\n        try {\n            view = await apiGet(page, '/x/web-interface/view', { params: { bvid } });\n        }\n        catch (err) {\n            throw new CommandExecutionError(`获取视频信息失败: ${err?.message || err}`);\n        }\n        if (view?.code !== 0) {\n            throw new CommandExecutionError(`获取视频信息失败: ${view?.message ?? 'unknown'} (${view?.code})`);\n        }\n        // --page 给定时用该集 cid（selectVideoPart 越界抛错）；缺省取整集默认 cid（P1，旧行为）。\n        const cid = selectedPage != null ? selectVideoPart(view?.data, selectedPage).cid : view?.data?.cid;","sourceCodeStart":1,"sourceCodeEnd":37,"githubUrl":"https://github.com/jackwener/OpenCLI/blob/49907e53dc3ade5c223ff0c4c2c2785687cec4e6/clis/bilibili/subtitle.js#L1-L37","documentation":"The bilibili subtitle command uses Strategy.COOKIE and needs a logged-in browser session: it reads cookies and signs Wbi requests through the live page. The func receives `page` from the CLI runner; when no browser session exists (page is null/undefined) it throws this CommandExecutionError before doing anything. It is a precondition guard, not a network failure.","triggerScenarios":"Running `opencli bilibili subtitle <bvid>` without an active/logged-in Chrome session that the CLI can attach to, or invoking the exported func directly with page=null/undefined.","commonSituations":"Chrome not running or not started with the CLI's debugging port; user forgot to log into bilibili.com; running in CI/headless environment with no browser; calling the command programmatically without providing the page argument.","solutions":["Launch/attach a Chrome session the CLI can use (same profile/debug port the CLI expects)","Log in to bilibili.com in that Chrome profile, then re-run the command","If calling func programmatically, pass a valid connected page object instead of null/undefined"],"exampleFix":null,"handlingStrategy":"validation","validationCode":"if (!page) throw new Error('Attach a logged-in Chrome session before calling bilibili subtitle');","typeGuard":"function hasPage(p) { return p != null && typeof p.evaluate === 'function'; }","tryCatchPattern":"try {\n  await run(['bilibili', 'subtitle', bvid]);\n} catch (e) {\n  if (String(e.message).includes('Browser session required')) {\n    // start/attach the CLI's Chrome session and login to bilibili.com, then retry\n  } else throw e;\n}","preventionTips":["Always start the CLI with its expected Chrome debug profile before bilibili commands","Confirm you are logged into bilibili.com in that profile","Don't call the command func directly with a null page in scripts"],"tags":["browser-session","authentication","bilibili","precondition"],"backgroundTag":"missing-browser-session","analyzedSha":"49907e53dc3ade5c223ff0c4c2c2785687cec4e6","analyzedAt":"2026-08-29T08:14:47.543Z","schemaVersion":2},"datasetVersion":"2026-08-29T17:17:51.833Z"}