@sovovs/bycli 2.1.12 → 2.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -87,6 +87,27 @@ export interface BrowserProfileStatus {
87
87
  pending: number;
88
88
  lastSeenAt?: number;
89
89
  }
90
+ export type DaemonStatusProbe = {
91
+ kind: 'status';
92
+ status: DaemonStatus;
93
+ } | {
94
+ kind: 'stopped';
95
+ } | {
96
+ kind: 'timeout';
97
+ } | {
98
+ kind: 'http_error';
99
+ statusCode: number;
100
+ } | {
101
+ kind: 'invalid_response';
102
+ } | {
103
+ kind: 'config_error';
104
+ } | {
105
+ kind: 'network_error';
106
+ };
107
+ export declare function probeDaemonStatus(opts?: {
108
+ timeout?: number;
109
+ contextId?: string;
110
+ }): Promise<DaemonStatusProbe>;
90
111
  export declare function fetchDaemonStatus(opts?: {
91
112
  timeout?: number;
92
113
  contextId?: string;
@@ -3,12 +3,10 @@
3
3
  *
4
4
  * Provides a typed send() function that posts a Command and returns a Result.
5
5
  */
6
- import { DEFAULT_DAEMON_PORT } from '../constants.js';
7
6
  import { sleep } from '../utils.js';
7
+ import { resolveDaemonPort } from './daemon-config.js';
8
8
  import { classifyBrowserError } from './errors.js';
9
9
  import { resolveProfileContextId } from './profile.js';
10
- const DAEMON_PORT = parseInt(process.env.BYCLI_DAEMON_PORT ?? String(DEFAULT_DAEMON_PORT), 10);
11
- const DAEMON_URL = `http://127.0.0.1:${DAEMON_PORT}`;
12
10
  const BYCLI_HEADERS = { 'X-byCLI': '1' };
13
11
  let _idCounter = 0;
14
12
  function generateId() {
@@ -24,32 +22,69 @@ export class BrowserCommandError extends Error {
24
22
  this.name = 'BrowserCommandError';
25
23
  }
26
24
  }
27
- async function requestDaemon(pathname, init) {
25
+ async function consumeDaemonResponse(pathname, init, consume, port) {
28
26
  const { timeout = 2000, headers, ...rest } = init ?? {};
27
+ const portResolution = port === undefined ? resolveDaemonPort() : { ok: true, port };
28
+ if (!portResolution.ok)
29
+ throw new Error('Invalid BYCLI_DAEMON_PORT configuration');
29
30
  const controller = new AbortController();
30
31
  const timer = setTimeout(() => controller.abort(), timeout);
31
32
  try {
32
- return await fetch(`${DAEMON_URL}${pathname}`, {
33
+ const response = await fetch(`http://127.0.0.1:${portResolution.port}${pathname}`, {
33
34
  ...rest,
34
35
  headers: { ...BYCLI_HEADERS, ...headers },
35
36
  signal: controller.signal,
36
37
  });
38
+ return await consume(response);
37
39
  }
38
40
  finally {
39
41
  clearTimeout(timer);
40
42
  }
41
43
  }
42
- export async function fetchDaemonStatus(opts) {
44
+ async function requestDaemon(pathname, init) {
45
+ return consumeDaemonResponse(pathname, init, async (response) => response);
46
+ }
47
+ function errorCode(error) {
48
+ if (!error || typeof error !== 'object')
49
+ return undefined;
50
+ const candidate = error;
51
+ if (typeof candidate.code === 'string')
52
+ return candidate.code;
53
+ return errorCode(candidate.cause);
54
+ }
55
+ export async function probeDaemonStatus(opts) {
56
+ const portResolution = resolveDaemonPort();
57
+ if (!portResolution.ok)
58
+ return { kind: 'config_error' };
43
59
  try {
44
60
  const params = opts?.contextId ? `?contextId=${encodeURIComponent(opts.contextId)}` : '';
45
- const res = await requestDaemon(`/status${params}`, { timeout: opts?.timeout ?? 2000 });
46
- if (!res.ok)
47
- return null;
48
- return await res.json();
61
+ return await consumeDaemonResponse(`/status${params}`, { timeout: opts?.timeout ?? 2000 }, async (res) => {
62
+ if (!res.ok)
63
+ return { kind: 'http_error', statusCode: res.status };
64
+ try {
65
+ return { kind: 'status', status: await res.json() };
66
+ }
67
+ catch (error) {
68
+ if (error instanceof Error && error.name === 'AbortError')
69
+ throw error;
70
+ return { kind: 'invalid_response' };
71
+ }
72
+ }, portResolution.port);
49
73
  }
50
- catch {
74
+ catch (error) {
75
+ if (error instanceof Error && error.name === 'AbortError')
76
+ return { kind: 'timeout' };
77
+ if (errorCode(error) === 'ECONNREFUSED')
78
+ return { kind: 'stopped' };
79
+ return { kind: 'network_error' };
80
+ }
81
+ }
82
+ export async function fetchDaemonStatus(opts) {
83
+ const result = await probeDaemonStatus(opts);
84
+ if (result.kind !== 'status') {
51
85
  return null;
52
86
  }
87
+ return result.status;
53
88
  }
54
89
  /**
55
90
  * Unified daemon health check — single entry point for all status queries.
@@ -0,0 +1,9 @@
1
+ import { DEFAULT_DAEMON_PORT } from '../constants.js';
2
+ export type DaemonPortResolution = {
3
+ ok: true;
4
+ port: number;
5
+ } | {
6
+ ok: false;
7
+ port: typeof DEFAULT_DAEMON_PORT;
8
+ };
9
+ export declare function resolveDaemonPort(raw?: string | undefined): DaemonPortResolution;
@@ -0,0 +1,12 @@
1
+ import { DEFAULT_DAEMON_PORT } from '../constants.js';
2
+ export function resolveDaemonPort(raw = process.env.BYCLI_DAEMON_PORT) {
3
+ if (raw === undefined)
4
+ return { ok: true, port: DEFAULT_DAEMON_PORT };
5
+ if (!/^\d+$/.test(raw))
6
+ return { ok: false, port: DEFAULT_DAEMON_PORT };
7
+ const port = Number(raw);
8
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
9
+ return { ok: false, port: DEFAULT_DAEMON_PORT };
10
+ }
11
+ return { ok: true, port };
12
+ }
package/dist/src/cli.js CHANGED
@@ -2958,7 +2958,9 @@ cli({
2958
2958
  daemonCmd
2959
2959
  .command('status')
2960
2960
  .description('Show daemon status')
2961
- .action(async () => { await daemonStatus(); });
2961
+ .option('--json', 'Output stable machine-readable JSON')
2962
+ .option('--verbose', 'Include process and profile diagnostics in JSON output')
2963
+ .action(async (opts) => { await daemonStatus(opts); });
2962
2964
  daemonCmd
2963
2965
  .command('stop')
2964
2966
  .description('Stop the daemon')
@@ -0,0 +1,60 @@
1
+ import type { DaemonStatusProbe } from '../browser/daemon-client.js';
2
+ export declare const DAEMON_STATUS_SCHEMA_VERSION: "1.0";
3
+ export type DaemonStatusState = 'stopped' | 'daemon_stale' | 'extension_disconnected' | 'profile_required' | 'profile_disconnected' | 'ready' | 'degraded';
4
+ export interface DaemonStatusIssue {
5
+ code: string;
6
+ severity: 'info' | 'warning' | 'error';
7
+ message: string;
8
+ remediation?: {
9
+ type: 'command';
10
+ command: string[];
11
+ };
12
+ }
13
+ export interface DaemonStatusReport {
14
+ schemaVersion: typeof DAEMON_STATUS_SCHEMA_VERSION;
15
+ command: 'daemon.status';
16
+ ok: boolean;
17
+ state: DaemonStatusState;
18
+ cli: {
19
+ version: string;
20
+ };
21
+ daemon: {
22
+ state: 'stopped' | 'running' | 'unknown';
23
+ version: string | null;
24
+ port: number;
25
+ stale: boolean;
26
+ pid?: number;
27
+ uptimeSeconds?: number;
28
+ memoryMB?: number;
29
+ };
30
+ extension: {
31
+ state: 'unknown' | 'disconnected' | 'connected';
32
+ version: string | null;
33
+ compatibility: 'unknown' | 'compatible' | 'incompatible';
34
+ };
35
+ profiles: {
36
+ connectedCount: number;
37
+ selectionRequired: boolean;
38
+ selectedContextId?: string | null;
39
+ items?: Array<{
40
+ contextId: string;
41
+ alias?: string;
42
+ selected: boolean;
43
+ extensionVersion: string | null;
44
+ }>;
45
+ };
46
+ issues: DaemonStatusIssue[];
47
+ error?: {
48
+ code: string;
49
+ message: string;
50
+ };
51
+ }
52
+ export interface DaemonStatusReportOptions {
53
+ cliVersion: string;
54
+ port: number;
55
+ verbose?: boolean;
56
+ /** Profile aliases in the persisted alias -> contextId form. */
57
+ profileAliases?: Record<string, string>;
58
+ }
59
+ export declare function buildDaemonStatusErrorReport(options: DaemonStatusReportOptions, code: string, message: string): DaemonStatusReport;
60
+ export declare function buildDaemonStatusReport(probe: DaemonStatusProbe, options: DaemonStatusReportOptions): DaemonStatusReport;
@@ -0,0 +1,195 @@
1
+ import { isDaemonStale } from '../browser/daemon-version.js';
2
+ import { satisfiesRange } from '../plugin-manifest.js';
3
+ export const DAEMON_STATUS_SCHEMA_VERSION = '1.0';
4
+ function baseReport(options) {
5
+ return {
6
+ schemaVersion: DAEMON_STATUS_SCHEMA_VERSION,
7
+ command: 'daemon.status',
8
+ ok: true,
9
+ state: 'stopped',
10
+ cli: { version: options.cliVersion },
11
+ daemon: { state: 'stopped', version: null, port: options.port, stale: false },
12
+ extension: { state: 'unknown', version: null, compatibility: 'unknown' },
13
+ profiles: { connectedCount: 0, selectionRequired: false },
14
+ issues: [],
15
+ };
16
+ }
17
+ function failureReport(options, code, message) {
18
+ const result = baseReport(options);
19
+ result.ok = false;
20
+ result.state = 'degraded';
21
+ result.daemon.state = 'unknown';
22
+ result.error = { code, message };
23
+ return result;
24
+ }
25
+ export function buildDaemonStatusErrorReport(options, code, message) {
26
+ return failureReport(options, code, message);
27
+ }
28
+ function isOptionalString(value) {
29
+ return value === undefined || typeof value === 'string';
30
+ }
31
+ function isOptionalBoolean(value) {
32
+ return value === undefined || typeof value === 'boolean';
33
+ }
34
+ function isFiniteNumber(value) {
35
+ return typeof value === 'number' && Number.isFinite(value);
36
+ }
37
+ function isProfileStatus(value) {
38
+ if (!value || typeof value !== 'object')
39
+ return false;
40
+ const profile = value;
41
+ return typeof profile.contextId === 'string'
42
+ && typeof profile.extensionConnected === 'boolean'
43
+ && isFiniteNumber(profile.pending)
44
+ && isOptionalString(profile.extensionVersion)
45
+ && isOptionalString(profile.extensionCompatRange);
46
+ }
47
+ function isDaemonStatus(value) {
48
+ if (!value || typeof value !== 'object')
49
+ return false;
50
+ const status = value;
51
+ return status.ok === true
52
+ && isFiniteNumber(status.pid)
53
+ && isFiniteNumber(status.uptime)
54
+ && typeof status.extensionConnected === 'boolean'
55
+ && isFiniteNumber(status.pending)
56
+ && isFiniteNumber(status.memoryMB)
57
+ && isFiniteNumber(status.port)
58
+ && isOptionalString(status.daemonVersion)
59
+ && isOptionalString(status.extensionVersion)
60
+ && isOptionalString(status.extensionCompatRange)
61
+ && isOptionalString(status.contextId)
62
+ && isOptionalBoolean(status.profileRequired)
63
+ && isOptionalBoolean(status.profileDisconnected)
64
+ && (status.profiles === undefined
65
+ || (Array.isArray(status.profiles) && status.profiles.every(isProfileStatus)));
66
+ }
67
+ function compatibilityOf(status, cliVersion) {
68
+ if (!status.extensionConnected || !status.extensionVersion || !status.extensionCompatRange) {
69
+ return 'unknown';
70
+ }
71
+ return satisfiesRange(cliVersion, status.extensionCompatRange) ? 'compatible' : 'incompatible';
72
+ }
73
+ function aliasForContextId(aliases, contextId) {
74
+ return Object.entries(aliases).find(([, id]) => id === contextId)?.[0];
75
+ }
76
+ function probeFailure(probe) {
77
+ switch (probe.kind) {
78
+ case 'timeout':
79
+ return { code: 'daemon_status_timeout', message: 'Timed out while requesting daemon status.' };
80
+ case 'http_error':
81
+ return { code: 'daemon_http_error', message: `Daemon status request failed with HTTP ${probe.statusCode}.` };
82
+ case 'invalid_response':
83
+ return { code: 'invalid_daemon_response', message: 'The daemon returned an invalid status response.' };
84
+ case 'config_error':
85
+ return { code: 'invalid_daemon_config', message: 'BYCLI_DAEMON_PORT must be an integer from 1 to 65535.' };
86
+ case 'network_error':
87
+ return { code: 'daemon_unreachable', message: 'The daemon status endpoint could not be reached.' };
88
+ }
89
+ }
90
+ export function buildDaemonStatusReport(probe, options) {
91
+ if (probe.kind === 'stopped')
92
+ return baseReport(options);
93
+ if (probe.kind !== 'status') {
94
+ const failure = probeFailure(probe);
95
+ return failureReport(options, failure.code, failure.message);
96
+ }
97
+ if (!isDaemonStatus(probe.status)) {
98
+ return failureReport(options, 'invalid_daemon_response', 'The daemon returned an invalid status response.');
99
+ }
100
+ const status = probe.status;
101
+ const result = baseReport(options);
102
+ const stale = isDaemonStale(status, options.cliVersion);
103
+ const compatibility = compatibilityOf(status, options.cliVersion);
104
+ const connectedProfiles = status.profiles?.filter((profile) => profile.extensionConnected) ?? [];
105
+ result.daemon = {
106
+ state: 'running',
107
+ version: status.daemonVersion ?? null,
108
+ port: status.port,
109
+ stale,
110
+ ...(options.verbose && {
111
+ pid: status.pid,
112
+ uptimeSeconds: status.uptime,
113
+ memoryMB: status.memoryMB,
114
+ }),
115
+ };
116
+ result.extension = {
117
+ state: status.extensionConnected ? 'connected' : 'disconnected',
118
+ version: status.extensionVersion ?? null,
119
+ compatibility,
120
+ };
121
+ result.profiles = {
122
+ connectedCount: connectedProfiles.length,
123
+ selectionRequired: status.profileRequired === true,
124
+ ...(options.verbose && {
125
+ selectedContextId: status.contextId ?? null,
126
+ items: (status.profiles ?? []).map((profile) => {
127
+ const alias = aliasForContextId(options.profileAliases ?? {}, profile.contextId);
128
+ return {
129
+ contextId: profile.contextId,
130
+ ...(alias !== undefined && { alias }),
131
+ selected: profile.contextId === status.contextId,
132
+ extensionVersion: profile.extensionVersion ?? null,
133
+ };
134
+ }),
135
+ }),
136
+ };
137
+ if (stale) {
138
+ result.issues.push({
139
+ code: 'daemon_stale',
140
+ severity: 'warning',
141
+ message: 'The daemon version does not match the CLI version.',
142
+ remediation: { type: 'command', command: ['bycli', 'daemon', 'restart'] },
143
+ });
144
+ }
145
+ if (!status.extensionConnected) {
146
+ result.issues.push({
147
+ code: 'extension_disconnected',
148
+ severity: 'warning',
149
+ message: 'The Browser Bridge extension is not connected.',
150
+ });
151
+ }
152
+ else if (!status.extensionVersion) {
153
+ result.issues.push({
154
+ code: 'extension_version_missing',
155
+ severity: 'warning',
156
+ message: 'The connected Browser Bridge extension did not report its version.',
157
+ });
158
+ }
159
+ if (compatibility === 'incompatible') {
160
+ result.issues.push({
161
+ code: 'extension_incompatible',
162
+ severity: 'warning',
163
+ message: 'The CLI version is incompatible with the Browser Bridge extension.',
164
+ });
165
+ }
166
+ if (status.profileRequired) {
167
+ result.issues.push({
168
+ code: 'profile_selection_required',
169
+ severity: 'warning',
170
+ message: 'Multiple Browser Bridge profiles are connected and no profile is selected.',
171
+ remediation: { type: 'command', command: ['bycli', 'profile', 'list'] },
172
+ });
173
+ }
174
+ if (status.profileDisconnected) {
175
+ result.issues.push({
176
+ code: 'selected_profile_disconnected',
177
+ severity: 'warning',
178
+ message: 'The selected Browser Bridge profile is disconnected.',
179
+ remediation: { type: 'command', command: ['bycli', 'profile', 'list'] },
180
+ });
181
+ }
182
+ if (stale)
183
+ result.state = 'daemon_stale';
184
+ else if (status.profileRequired)
185
+ result.state = 'profile_required';
186
+ else if (status.profileDisconnected)
187
+ result.state = 'profile_disconnected';
188
+ else if (!status.extensionConnected)
189
+ result.state = 'extension_disconnected';
190
+ else if (compatibility === 'incompatible')
191
+ result.state = 'degraded';
192
+ else
193
+ result.state = 'ready';
194
+ return result;
195
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -4,6 +4,12 @@
4
4
  * bycli daemon stop — graceful shutdown
5
5
  * bycli daemon restart — graceful shutdown, then start a fresh daemon
6
6
  */
7
- export declare function daemonStatus(): Promise<void>;
7
+ export interface DaemonStatusOptions {
8
+ json?: boolean;
9
+ verbose?: boolean;
10
+ /** Pre-validated fast-path usage failure; keeps --json output machine-readable. */
11
+ usageError?: string;
12
+ }
13
+ export declare function daemonStatus(options?: DaemonStatusOptions): Promise<void>;
8
14
  export declare function daemonStop(): Promise<void>;
9
15
  export declare function daemonRestart(): Promise<void>;
@@ -4,13 +4,57 @@
4
4
  * bycli daemon stop — graceful shutdown
5
5
  * bycli daemon restart — graceful shutdown, then start a fresh daemon
6
6
  */
7
- import { fetchDaemonStatus, requestDaemonShutdown } from '../browser/daemon-client.js';
7
+ import { fetchDaemonStatus, probeDaemonStatus, requestDaemonShutdown } from '../browser/daemon-client.js';
8
+ import { resolveDaemonPort } from '../browser/daemon-config.js';
8
9
  import { restartDaemon } from '../browser/daemon-lifecycle.js';
10
+ import { loadProfileConfig } from '../browser/profile.js';
9
11
  import { formatDuration } from '../download/progress.js';
12
+ import { EXIT_CODES } from '../errors.js';
10
13
  import { log } from '../logger.js';
11
14
  import { PKG_VERSION } from '../version.js';
12
15
  import { formatDaemonVersion, isDaemonStale } from '../browser/daemon-version.js';
13
- export async function daemonStatus() {
16
+ import { buildDaemonStatusErrorReport, buildDaemonStatusReport } from './daemon-status.js';
17
+ function configuredDaemonPort() {
18
+ return resolveDaemonPort().port;
19
+ }
20
+ function jsonStatusExitCode(errorCode) {
21
+ if (!errorCode)
22
+ return EXIT_CODES.SUCCESS;
23
+ if (errorCode === 'daemon_status_timeout')
24
+ return EXIT_CODES.TEMPFAIL;
25
+ if (errorCode === 'invalid_daemon_response' || errorCode === 'invalid_daemon_config') {
26
+ return EXIT_CODES.CONFIG_ERROR;
27
+ }
28
+ return EXIT_CODES.GENERIC_ERROR;
29
+ }
30
+ export async function daemonStatus(options = {}) {
31
+ if (options.verbose && !options.json) {
32
+ console.error('Error: --verbose requires --json.');
33
+ process.exitCode = EXIT_CODES.USAGE_ERROR;
34
+ return;
35
+ }
36
+ if (options.json) {
37
+ if (options.usageError) {
38
+ const report = buildDaemonStatusErrorReport({
39
+ cliVersion: PKG_VERSION,
40
+ port: configuredDaemonPort(),
41
+ }, 'invalid_arguments', options.usageError);
42
+ console.log(JSON.stringify(report));
43
+ process.exitCode = EXIT_CODES.USAGE_ERROR;
44
+ return;
45
+ }
46
+ const probe = await probeDaemonStatus();
47
+ const profileConfig = loadProfileConfig();
48
+ const report = buildDaemonStatusReport(probe, {
49
+ cliVersion: PKG_VERSION,
50
+ port: configuredDaemonPort(),
51
+ verbose: options.verbose,
52
+ profileAliases: profileConfig.aliases,
53
+ });
54
+ console.log(JSON.stringify(report));
55
+ process.exitCode = jsonStatusExitCode(report.error?.code);
56
+ return;
57
+ }
14
58
  const status = await fetchDaemonStatus();
15
59
  if (!status) {
16
60
  console.log('Daemon: not running');
@@ -0,0 +1 @@
1
+ export {};
package/dist/src/main.js CHANGED
@@ -39,6 +39,29 @@ if (typeof globalThis.Bun === 'undefined' && !isSupportedNodeVersion(process.ver
39
39
  ].join('\n'));
40
40
  process.exit(EXIT_CODES.CONFIG_ERROR);
41
41
  }
42
+ // Fast path: passive machine-readable daemon status. Keep this before discovery,
43
+ // hooks, proxy installation, and update checks so stdout/stderr remain API-safe
44
+ // and the only network operation is the loopback daemon status request.
45
+ const daemonStatusArgs = argv.slice(2);
46
+ if (argv[0] === 'daemon'
47
+ && argv[1] === 'status'
48
+ && daemonStatusArgs.includes('--json')) {
49
+ const unsupportedArgs = daemonStatusArgs.filter((arg) => arg !== '--json' && arg !== '--verbose');
50
+ const { daemonStatus } = await import('./commands/daemon.js');
51
+ await daemonStatus({
52
+ json: true,
53
+ verbose: daemonStatusArgs.includes('--verbose'),
54
+ ...(unsupportedArgs.length > 0 && {
55
+ usageError: `Unsupported daemon status argument(s): ${unsupportedArgs.join(', ')}`,
56
+ }),
57
+ });
58
+ // console.log() may still be buffered when stdout is piped. An empty queued
59
+ // write completes only after the preceding JSON line has drained.
60
+ await new Promise((resolve, reject) => {
61
+ process.stdout.write('', (error) => error ? reject(error) : resolve());
62
+ });
63
+ process.exit(process.exitCode ?? EXIT_CODES.SUCCESS);
64
+ }
42
65
  // Fast path: --version (only when it's the top-level intent, not passed to a subcommand)
43
66
  // e.g. `bycli --version` or `bycli -V`, but NOT `bycli gh --version`
44
67
  if (argv[0] === '--version' || argv[0] === '-V') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sovovs/bycli",
3
- "version": "2.1.12",
3
+ "version": "2.1.14",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -90,7 +90,7 @@
90
90
  "dependencies": {
91
91
  "@mozilla/readability": "^0.6.0",
92
92
  "@sovovs/bycli-recorder-core": "^0.1.0",
93
- "@sovovs/wechat-article-crawler": "^1.1.0",
93
+ "@sovovs/wechat-article-crawler": "^1.1.3",
94
94
  "cli-table3": "^0.6.5",
95
95
  "commander": "^14.0.3",
96
96
  "js-yaml": "^4.1.0",
@@ -59,14 +59,14 @@ try {
59
59
  project, 'node_modules/@sovovs/bycli/package.json',
60
60
  ), 'utf8'));
61
61
  assert.equal(mainManifest.dependencies?.['@sovovs/bycli-recorder-core'], '^0.1.0');
62
- assert.equal(mainManifest.dependencies?.['@sovovs/wechat-article-crawler'], '^1.1.0');
62
+ assert.equal(mainManifest.dependencies?.['@sovovs/wechat-article-crawler'], '^1.1.3');
63
63
 
64
64
  const coreDirectory = join(project, 'node_modules/@sovovs/bycli-recorder-core');
65
65
  const crawlerDirectoryInstalled = join(project, 'node_modules/@sovovs/wechat-article-crawler');
66
66
  const crawlerManifest = JSON.parse(readFileSync(
67
67
  join(crawlerDirectoryInstalled, 'package.json'), 'utf8',
68
68
  ));
69
- assert.equal(crawlerManifest.version, '1.1.2');
69
+ assert.equal(crawlerManifest.version, '1.1.3');
70
70
  const projectRequire = createRequire(join(project, 'package.json'));
71
71
  const crawlerEntry = projectRequire.resolve('@sovovs/wechat-article-crawler');
72
72
  const crawlerModule = await import(pathToFileURL(crawlerEntry).href);
@@ -1,186 +0,0 @@
1
- #!/usr/bin/env bash
2
- # 录制三端管理脚本
3
- # daemon : 浏览器底座(19825),由 bycli 管理;扩展连这口
4
- # be : Recorder Local Service(19826),同源托管真实工作台 UI(dashboard/dist)
5
- # web : Umi dev server(8000),mock 模式,仅前端开发用(无真实录制)
6
- #
7
- # 用法:
8
- # scripts/recorder.sh start [daemon|be|all] # 默认=真实录制环境(daemon+be,自动停 mock)
9
- # scripts/recorder.sh start --mock # 仅此参数才起 mock 前端(web :8000,假数据)
10
- # scripts/recorder.sh stop [daemon|be|web|all]
11
- # scripts/recorder.sh restart [daemon|be|vnc|all] # restart all=daemon+be(不含 mock);改了 .env/dist 后用;vnc=删旧容器换新镜像
12
- # scripts/recorder.sh status # 看三端
13
- # scripts/recorder.sh build [core|be|ui|ext|all] # 重建 dist(改源码后;all 含扩展,需手动重载)
14
- #
15
- # 真实录制(带 LLM)启动:scripts/recorder.sh start → 打开 http://127.0.0.1:19826/workbench
16
- #
17
- # embedded_iframe 录制模式(P2,公开站页内嵌入;**本机默认开**):起 be 默认带 flag——
18
- # EMBEDDED=0 scripts/recorder.sh start # 显式关闭页内嵌入模式
19
- # IFRAME_FRAME_SRC=https://juejin.cn scripts/recorder.sh restart be # 只放该 origin(hardened)
20
- # inline env 经 `env VAR=…` 注入,优先级高于 --env-file(.env 不覆盖已存在的 process env)。
21
- #
22
- # vnc 录制模式(容器内 Chromium+扩展+daemon,noVNC 投画面;**本机默认开**,需 podman + 镜像):
23
- # scripts/recorder.sh build vnc # 构建容器镜像 bycli-verify:latest(需先 build ext + npm run build)
24
- # scripts/recorder.sh restart vnc # 重启镜像:删旧容器(bycli-vnc),be 下次 bind 用新镜像重建(改镜像后用)
25
- # VNC=0 scripts/recorder.sh restart be # 显式关闭 vnc 模式
26
- # 选 VNC 模式后 be 自动 podman run 起容器、前端 iframe 投 noVNC 画面;录的数据走容器网关→be→合成链。
27
- set -uo pipefail
28
-
29
- ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
30
- RUN="$ROOT/.recorder-run"; mkdir -p "$RUN"
31
- DAEMON_PORT=19825; BE_PORT=19826; WEB_PORT=8000
32
-
33
- port_pid() { lsof -ti "tcp:$1" -sTCP:LISTEN 2>/dev/null | head -1; }
34
- alive() { [ -n "${1:-}" ] && kill -0 "$1" 2>/dev/null; }
35
-
36
- # ───────────────────────── daemon(交给 bycli 管) ─────────────────────────
37
- need_bycli() { command -v bycli >/dev/null || { echo "✗ bycli 不在 PATH(在仓库根 npm link)"; return 1; }; }
38
- daemon_start() { need_bycli || return 1; bycli daemon start 2>&1 | tail -1; }
39
- daemon_stop() { need_bycli && { bycli daemon stop 2>&1 | tail -1; } || true; }
40
- daemon_restart() { need_bycli || return 1; bycli daemon restart 2>&1 | tail -1; }
41
- daemon_status() { local p; p="$(port_pid $DAEMON_PORT)"; [ -n "$p" ] && echo "● daemon RUNNING :$DAEMON_PORT pid=$p" || echo "○ daemon stopped :$DAEMON_PORT"; }
42
-
43
- # ───────────────────────── vnc(podman 容器,be 自动编排) ────────────────
44
- # 容器名与 vncOrchestrator.ts 保持一致(BYCLI_VNC_CONTAINER 覆盖,默认 bycli-vnc)。
45
- VNC_CONTAINER="${BYCLI_VNC_CONTAINER:-bycli-vnc}"
46
- VNC_IMAGE="${BYCLI_VNC_IMAGE:-bycli-verify:latest}"
47
- need_podman() { command -v podman >/dev/null || { echo "✗ podman 不在 PATH(VNC 模式需 podman)"; return 1; }; }
48
- # 重启镜像:删旧容器,be 下次 bind 时用当前镜像重建(build vnc 换镜像后调用)。
49
- vnc_restart() {
50
- need_podman || return 1
51
- [ -n "$(podman images -q "$VNC_IMAGE" 2>/dev/null)" ] || { echo "✗ 镜像 $VNC_IMAGE 不存在 → scripts/recorder.sh build vnc"; return 1; }
52
- if [ -n "$(podman ps -aq -f "name=^${VNC_CONTAINER}$" 2>/dev/null)" ]; then
53
- podman rm -f "$VNC_CONTAINER" >/dev/null 2>&1 && echo "✓ 已删旧容器 $VNC_CONTAINER(be 下次 bind 用新镜像 $VNC_IMAGE 重建)"
54
- else
55
- echo "○ 容器 $VNC_CONTAINER 未运行(be 下次 bind 会用新镜像 $VNC_IMAGE 新建)"
56
- fi
57
- }
58
- vnc_stop() {
59
- need_podman || return 1
60
- if [ -n "$(podman ps -aq -f "name=^${VNC_CONTAINER}$" 2>/dev/null)" ]; then
61
- podman rm -f "$VNC_CONTAINER" >/dev/null 2>&1 && echo "✓ vnc 容器 $VNC_CONTAINER 已删"
62
- else echo "○ vnc 容器未运行"; fi
63
- }
64
- vnc_status() {
65
- command -v podman >/dev/null || { echo "○ vnc (podman 未装)"; return; }
66
- local st; st="$(podman inspect "$VNC_CONTAINER" --format '{{.State.Status}}' 2>/dev/null)"
67
- [ -n "$st" ] && echo "● vnc $st container=$VNC_CONTAINER image=$VNC_IMAGE" || echo "○ vnc no container ($VNC_CONTAINER)"
68
- }
69
-
70
- # ───────────────────────── be(node 进程,PID 文件) ──────────────────────
71
- be_start() {
72
- [ -f "$ROOT/dashboard-be/dist/server.js" ] || { echo "✗ be 未构建 → scripts/recorder.sh build be"; return 1; }
73
- [ -f "$ROOT/dashboard-be/.env" ] || { echo "✗ 缺 dashboard-be/.env → cp dashboard-be/.env.example dashboard-be/.env 并填值"; return 1; }
74
- [ -d "$ROOT/dashboard/dist" ] || echo "⚠ dashboard/dist 不存在,be 将 API-only(无 UI)→ scripts/recorder.sh build ui"
75
- if [ -n "$(port_pid $BE_PORT)" ]; then echo "● be 已在 :$BE_PORT(先 stop/restart)"; return 0; fi
76
- # embedded_iframe 模式(P2):EMBEDDED=1 → 注入 flag 开 frame-src + 前端模式选项。
77
- # 经 `env VAR=…` 内联注入,优先级高于 --env-file(.env 不覆盖已存在的 process env)。
78
- # 三种录制模式默认全开(本机录制工作台);显式 EMBEDDED=0 / VNC=0 可单独关。
79
- # 注:只在本机 be 启动注入,不动 recorder-core 的 fail-closed 发布默认(全局 CSP 安全底线不变)。
80
- local envv=()
81
- if [ "${EMBEDDED:-1}" = 1 ]; then
82
- envv+=(FEATURE_EMBEDDED_IFRAME_RECORDING=1)
83
- [ -n "${IFRAME_FRAME_SRC:-}" ] && envv+=("RECORDER_IFRAME_FRAME_SRC=$IFRAME_FRAME_SRC")
84
- echo " ⚙ embedded_iframe 模式 ON${IFRAME_FRAME_SRC:+(frame-src=$IFRAME_FRAME_SRC)}"
85
- fi
86
- if [ "${VNC:-1}" = 1 ]; then
87
- envv+=(FEATURE_VNC_RECORDING=1)
88
- echo " ⚙ vnc 容器模式 ON(be 自动 podman run bycli-verify:latest;需先 build vnc)"
89
- fi
90
- ( cd "$ROOT" && nohup env ${envv[@]+"${envv[@]}"} node --env-file=dashboard-be/.env dashboard-be/dist/server.js >"$RUN/be.log" 2>&1 & echo $! >"$RUN/be.pid" )
91
- sleep 1; be_status; echo " 日志: $RUN/be.log"
92
- }
93
- be_stop() {
94
- # 端口权威:pid 文件 + 实际占 19826 的进程都杀(防重复实例残留)
95
- local stopped=0 pf; pf="$(cat "$RUN/be.pid" 2>/dev/null)"
96
- for pid in "$pf" "$(port_pid $BE_PORT)"; do
97
- if alive "$pid"; then kill "$pid" 2>/dev/null; echo "✓ be 已停(pid=$pid)"; stopped=1; fi
98
- done
99
- [ "$stopped" = 0 ] && echo "○ be 未运行"
100
- rm -f "$RUN/be.pid"
101
- }
102
- be_restart() { be_stop; sleep 1; be_start; }
103
- be_status() { local p; p="$(port_pid $BE_PORT)"; [ -n "$p" ] && echo "● be RUNNING http://127.0.0.1:$BE_PORT/workbench pid=$p" || echo "○ be stopped :$BE_PORT"; }
104
-
105
- # ───────────────────────── web(Umi dev,mock) ───────────────────────────
106
- web_start() {
107
- if [ -n "$(port_pid $WEB_PORT)" ]; then echo "● web 已在 :$WEB_PORT"; return 0; fi
108
- ( cd "$ROOT/dashboard" && nohup npm run dev >"$RUN/web.log" 2>&1 & echo $! >"$RUN/web.pid" )
109
- echo "✓ web 启动中(mock,http://127.0.0.1:$WEB_PORT) 日志: $RUN/web.log"
110
- }
111
- web_stop() {
112
- local pid; pid="$(cat "$RUN/web.pid" 2>/dev/null)"; [ -z "$pid" ] && pid="$(port_pid $WEB_PORT)"
113
- if alive "$pid"; then pkill -P "$pid" 2>/dev/null; kill "$pid" 2>/dev/null; echo "✓ web 已停"; else echo "○ web 未运行"; fi
114
- rm -f "$RUN/web.pid"
115
- }
116
- web_restart() { web_stop; sleep 1; web_start; }
117
- web_status() { local p; p="$(port_pid $WEB_PORT)"; [ -n "$p" ] && echo "● web RUNNING http://127.0.0.1:$WEB_PORT (mock) pid=$p" || echo "○ web stopped :$WEB_PORT (mock dev)"; }
118
-
119
- # ───────────────────────── build ────────────────────────────────────────
120
- do_build() {
121
- case "${1:-all}" in
122
- core) npm --prefix "$ROOT/packages/recorder-core" run build ;;
123
- be) npm --prefix "$ROOT/dashboard-be" run build ;;
124
- ui) ( cd "$ROOT/dashboard" && npm run build ) ;;
125
- ext) ( cd "$ROOT/extension" && npm run build ) ;;
126
- vnc) # VNC 录制模式容器镜像(Chromium+扩展+daemon+x11vnc+websockify+网关);be 起容器时复用 bycli-verify:latest。
127
- command -v podman >/dev/null || { echo "✗ podman 不在 PATH(VNC 模式需 podman)"; return 1; }
128
- [ -f "$ROOT/extension/dist/background.js" ] || { echo "✗ 扩展未构建 → scripts/recorder.sh build ext"; return 1; }
129
- [ -f "$ROOT/dist/src/daemon.js" ] || { echo "✗ dist 未构建 → npm run build"; return 1; }
130
- echo "▶ 构建 VNC 容器镜像 bycli-verify:latest(首次装 chromium 较慢)…"
131
- ( cd "$ROOT" && podman build -f podman-verify/Dockerfile -t bycli-verify:latest . ) ;;
132
- all) npm --prefix "$ROOT/packages/recorder-core" run build \
133
- && npm --prefix "$ROOT/dashboard-be" run build \
134
- && ( cd "$ROOT/dashboard" && npm run build ) \
135
- && ( cd "$ROOT/extension" && npm run build ) \
136
- && echo "↻ 扩展已重建 → chrome://extensions 重载 byCLI(确认版本号刷新)" ;;
137
- *) echo "build: core|be|ui|ext|vnc|all"; return 1 ;;
138
- esac
139
- }
140
-
141
- # ───────────────────────── dispatch ─────────────────────────────────────
142
- action="${1:-}"; shift || true
143
- case "$action" in
144
- start)
145
- # mock 仅在显式 --mock 时启动;其余参数视作服务名
146
- mock=0; svcs=()
147
- for a in "$@"; do if [ "$a" = "--mock" ]; then mock=1; else svcs+=("$a"); fi; done
148
- if [ "$mock" = 1 ]; then
149
- echo "▶ 启动【mock 前端】(web :$WEB_PORT,假数据,无真实录制)"
150
- web_start
151
- elif [ ${#svcs[@]} -eq 0 ]; then
152
- # 默认 = 真实录制环境:停掉 mock web(防 :8000 误测)→ 起 daemon + be
153
- echo "▶ 启动【真实录制环境】(daemon + be);mock web 若在跑将被停掉以免混淆"
154
- [ -n "$(port_pid $WEB_PORT)" ] && web_stop
155
- daemon_start; be_start
156
- echo; echo "✅ 真实录制 → http://127.0.0.1:$BE_PORT/workbench(mock 需 start --mock)"
157
- else
158
- [ "${svcs[0]}" = "all" ] && svcs=(daemon be)
159
- for t in "${svcs[@]}"; do
160
- case "$t" in
161
- daemon|be) "${t}_start" ;;
162
- web) echo "✗ web 是 mock,请用:scripts/recorder.sh start --mock" ;;
163
- *) echo "未知服务: $t(daemon|be|all,mock 用 --mock)" ;;
164
- esac
165
- done
166
- fi ;;
167
- stop|restart)
168
- # all 语义:restart 只起真实环境(daemon+be,不复活 mock,与 start 默认一致);
169
- # stop 则全停(含 mock web,teardown)。mock 启停一律显式 web/--mock。
170
- if [ $# -eq 0 ]; then targets=(daemon be)
171
- elif [ "${1:-}" = all ]; then
172
- [ "$action" = stop ] && targets=(daemon be web) || targets=(daemon be)
173
- else targets=("$@"); fi
174
- [ "$action" = stop ] && targets=($(printf '%s\n' "${targets[@]}" | tail -r 2>/dev/null || printf '%s\n' "${targets[@]}"))
175
- for t in "${targets[@]}"; do
176
- case "$t" in daemon|be|web|vnc) "${t}_${action}" ;; *) echo "未知服务: $t(daemon|be|web|vnc|all)";; esac
177
- done ;;
178
- status)
179
- daemon_status; be_status; web_status; vnc_status ;;
180
- build)
181
- do_build "${1:-all}" ;;
182
- ""|-h|--help|help)
183
- awk 'NR>1 && /^#/{sub(/^# ?/,"");print;next} NR>1{exit}' "${BASH_SOURCE[0]}" ;;
184
- *)
185
- echo "未知命令: $action(start|stop|restart|status|build)"; exit 1 ;;
186
- esac