@sovovs/bycli 2.1.33 → 2.1.35

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.
package/cli-manifest.json CHANGED
@@ -28292,8 +28292,9 @@
28292
28292
  {
28293
28293
  "site": "weixin",
28294
28294
  "name": "create-draft",
28295
- "description": "创建微信公众号图文草稿",
28295
+ "description": "创建微信公众号草稿(支持浏览器富文本或官方 API)",
28296
28296
  "access": "write",
28297
+ "example": "bycli weixin create-draft --title \"文章标题\" --content-file article.html --content-format html --cover-image cover.jpg",
28297
28298
  "domain": "mp.weixin.qq.com",
28298
28299
  "strategy": "cookie",
28299
28300
  "browser": true,
@@ -28302,39 +28303,76 @@
28302
28303
  "name": "title",
28303
28304
  "type": "str",
28304
28305
  "required": true,
28305
- "help": "文章标题 (最长64字)"
28306
+ "help": "文章标题(最长 64 字)"
28306
28307
  },
28307
28308
  {
28308
28309
  "name": "content",
28309
28310
  "type": "str",
28310
- "required": true,
28311
+ "required": false,
28311
28312
  "positional": true,
28312
- "help": "文章正文"
28313
+ "help": "正文文本;也可用 --content-file 读取 HTML 文件"
28314
+ },
28315
+ {
28316
+ "name": "content-file",
28317
+ "type": "str",
28318
+ "required": false,
28319
+ "help": "正文文件路径;HTML 模式支持本地图片"
28320
+ },
28321
+ {
28322
+ "name": "content-format",
28323
+ "type": "str",
28324
+ "default": "text",
28325
+ "required": false,
28326
+ "help": "正文格式:text=纯文本,html=富文本,html-text=保留段落但忽略样式",
28327
+ "choices": [
28328
+ "text",
28329
+ "html",
28330
+ "html-text"
28331
+ ]
28313
28332
  },
28314
28333
  {
28315
28334
  "name": "author",
28316
28335
  "type": "str",
28317
28336
  "required": false,
28318
- "help": "作者名 (最长8字)"
28337
+ "help": "作者名(最长 8 字)"
28319
28338
  },
28320
28339
  {
28321
28340
  "name": "cover-image",
28322
28341
  "type": "str",
28323
28342
  "required": false,
28324
- "help": "封面图片路径 (会先上传到正文再设为封面)"
28343
+ "help": "封面图路径;API 模式必填,浏览器模式会上传后设为封面"
28325
28344
  },
28326
28345
  {
28327
28346
  "name": "summary",
28328
28347
  "type": "str",
28329
28348
  "required": false,
28330
- "help": "文章摘要"
28349
+ "help": "文章摘要;API 模式对应 digest"
28350
+ },
28351
+ {
28352
+ "name": "appid",
28353
+ "type": "str",
28354
+ "required": false,
28355
+ "help": "公众号 AppID;与 --appsecret 同传时走官方 API,不打开浏览器"
28356
+ },
28357
+ {
28358
+ "name": "appsecret",
28359
+ "type": "str",
28360
+ "required": false,
28361
+ "help": "公众号 AppSecret;请勿提交到 shell 历史或日志"
28362
+ },
28363
+ {
28364
+ "name": "dry-run",
28365
+ "type": "boolean",
28366
+ "default": false,
28367
+ "required": false,
28368
+ "help": "浏览器模式:填充并验证正文后停止,不会保存草稿"
28331
28369
  },
28332
28370
  {
28333
28371
  "name": "timeout",
28334
28372
  "type": "int",
28335
28373
  "default": 180,
28336
28374
  "required": false,
28337
- "help": "Max seconds for the overall command (default: 180)"
28375
+ "help": "命令总超时时间(秒,默认 180"
28338
28376
  }
28339
28377
  ],
28340
28378
  "columns": [
@@ -28455,7 +28493,15 @@
28455
28493
  "markdownSize",
28456
28494
  "dataPath",
28457
28495
  "dataSize",
28458
- "error"
28496
+ "error",
28497
+ "listReads",
28498
+ "listShares",
28499
+ "listLikes",
28500
+ "listComments",
28501
+ "detailReadUsers",
28502
+ "detailShares",
28503
+ "detailLikes",
28504
+ "detailComments"
28459
28505
  ],
28460
28506
  "type": "js",
28461
28507
  "modulePath": "weixin/download-publish-data.js",
@@ -0,0 +1,114 @@
1
+ import * as nodeFs from 'node:fs/promises';
2
+ import * as nodePath from 'node:path';
3
+ import { CommandExecutionError } from '@sovovs/bycli/errors';
4
+ import { prepareHtmlContent } from './draft-content.js';
5
+
6
+ const API_BASE = 'https://api.weixin.qq.com/cgi-bin';
7
+
8
+ function apiError(context, payload) {
9
+ const code = payload?.errcode == null ? 'unknown' : payload.errcode;
10
+ const message = payload?.errmsg || 'unknown error';
11
+ return new CommandExecutionError(`${context} failed (${code}): ${message}`);
12
+ }
13
+
14
+ async function readJsonResponse(response, context) {
15
+ let payload;
16
+ try {
17
+ payload = await response.json();
18
+ } catch (error) {
19
+ throw new CommandExecutionError(`${context} returned invalid JSON: ${error?.message ?? error}`);
20
+ }
21
+ if (!response.ok) throw new CommandExecutionError(`${context} returned HTTP ${response.status}`);
22
+ if (payload?.errcode != null && payload.errcode !== 0) throw apiError(context, payload);
23
+ return payload;
24
+ }
25
+
26
+ async function getAccessToken(appid, appsecret, fetchImpl) {
27
+ const url = new URL(`${API_BASE}/token`);
28
+ url.searchParams.set('grant_type', 'client_credential');
29
+ url.searchParams.set('appid', appid);
30
+ url.searchParams.set('secret', appsecret);
31
+ const response = await fetchImpl(url.toString(), { method: 'GET' });
32
+ const payload = await readJsonResponse(response, '获取 access_token');
33
+ if (!payload.access_token) throw new CommandExecutionError('获取 access_token failed: response did not contain access_token');
34
+ return payload.access_token;
35
+ }
36
+
37
+ function mimeType(filePath) {
38
+ const extension = nodePath.extname(filePath).toLowerCase();
39
+ if (extension === '.png') return 'image/png';
40
+ if (extension === '.gif') return 'image/gif';
41
+ if (extension === '.webp') return 'image/webp';
42
+ return 'image/jpeg';
43
+ }
44
+
45
+ async function uploadImage(filePath, token, fetchImpl) {
46
+ const data = await nodeFs.readFile(filePath);
47
+ const form = new FormData();
48
+ form.append('media', new Blob([data], { type: mimeType(filePath) }), nodePath.basename(filePath));
49
+ const url = new URL(`${API_BASE}/material/add_material`);
50
+ url.searchParams.set('access_token', token);
51
+ url.searchParams.set('type', 'image');
52
+ const response = await fetchImpl(url.toString(), { method: 'POST', body: form });
53
+ const payload = await readJsonResponse(response, '上传图片');
54
+ if (!payload.media_id) throw new CommandExecutionError('上传图片 failed: response did not contain media_id');
55
+ return payload;
56
+ }
57
+
58
+ function removeCoverImage(html) {
59
+ return String(html ?? '').replace(/<img\b[^>]*(?:alt|title)=["'][^"']*封面[^"']*["'][^>]*>\s*/giu, '');
60
+ }
61
+
62
+ export async function createDraftViaApi({
63
+ appid,
64
+ appsecret,
65
+ title,
66
+ author = '',
67
+ digest = '',
68
+ coverImage,
69
+ html,
70
+ baseDir = process.cwd(),
71
+ fetchImpl = globalThis.fetch,
72
+ } = {}) {
73
+ if (!String(appid ?? '').trim() || !String(appsecret ?? '').trim()) {
74
+ throw new CommandExecutionError('API mode requires both appid and appsecret');
75
+ }
76
+ if (typeof fetchImpl !== 'function') throw new CommandExecutionError('API mode requires fetch support');
77
+ if (!coverImage) throw new CommandExecutionError('API mode requires cover-image');
78
+
79
+ const token = await getAccessToken(String(appid).trim(), String(appsecret).trim(), fetchImpl);
80
+ const cover = await uploadImage(nodePath.resolve(coverImage), token, fetchImpl);
81
+ const prepared = await prepareHtmlContent(removeCoverImage(html), {
82
+ baseDir,
83
+ resolveImage: async imagePath => {
84
+ const uploaded = await uploadImage(imagePath, token, fetchImpl);
85
+ return uploaded.url || uploaded.media_id;
86
+ },
87
+ });
88
+
89
+ const url = new URL(`${API_BASE}/draft/add`);
90
+ url.searchParams.set('access_token', token);
91
+ const body = {
92
+ articles: [{
93
+ title: String(title ?? ''),
94
+ author: String(author ?? ''),
95
+ digest: String(digest || title || ''),
96
+ content: prepared.html,
97
+ content_source_url: '',
98
+ thumb_media_id: cover.media_id,
99
+ show_cover_pic: 1,
100
+ need_open_comment: 0,
101
+ only_fans_can_comment: 0,
102
+ }],
103
+ };
104
+ const response = await fetchImpl(url.toString(), {
105
+ method: 'POST',
106
+ headers: { 'Content-Type': 'application/json; charset=utf-8' },
107
+ body: JSON.stringify(body),
108
+ });
109
+ const payload = await readJsonResponse(response, '创建草稿');
110
+ if (!payload.media_id) throw new CommandExecutionError('创建草稿 failed: response did not contain media_id');
111
+ return { mediaId: payload.media_id };
112
+ }
113
+
114
+ export { removeCoverImage };
@@ -0,0 +1,208 @@
1
+ import * as nodeFs from 'node:fs';
2
+ import * as nodePath from 'node:path';
3
+ import { ArgumentError, CommandExecutionError } from '@sovovs/bycli/errors';
4
+ import { parseWechatHtmlFragment, serializeWechatHtml } from '@sovovs/bycli/download/article-download';
5
+
6
+ const DROP_TAGS = new Set(['base', 'embed', 'form', 'iframe', 'link', 'meta', 'object', 'script', 'style', 'template']);
7
+ const ALLOWED_TAGS = new Set([
8
+ 'a', 'b', 'blockquote', 'br', 'code', 'div', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
9
+ 'i', 'img', 'li', 'ol', 'p', 'pre', 'section', 'span', 'strong', 'table', 'tbody', 'td',
10
+ 'tfoot', 'th', 'thead', 'tr', 'u', 'ul',
11
+ ]);
12
+ const IMPORTANT_STYLE_PROPERTIES = new Set([
13
+ 'background', 'background-color', 'border', 'border-radius', 'color', 'display',
14
+ 'font-size', 'line-height', 'margin', 'margin-bottom', 'padding', 'text-align', 'text-indent',
15
+ 'vertical-align',
16
+ ]);
17
+
18
+ export function htmlToPlainText(html) {
19
+ return String(html ?? '')
20
+ .replace(/<(?:br)\b[^>]*>/giu, '\n')
21
+ .replace(/<\/(?:p|div|section|h[1-6]|li|tr|blockquote|table)>/giu, '\n')
22
+ .replace(/<[^>]*>/gu, '')
23
+ .replace(/&nbsp;/giu, ' ')
24
+ .replace(/&amp;/giu, '&')
25
+ .replace(/&lt;/giu, '<')
26
+ .replace(/&gt;/giu, '>')
27
+ .replace(/[\t \f\v]+/gu, ' ')
28
+ .replace(/ *\n */gu, '\n')
29
+ .replace(/\n{3,}/gu, '\n\n')
30
+ .trim();
31
+ }
32
+
33
+ function attributes(node) {
34
+ return Array.isArray(node.attrs) ? node.attrs : [];
35
+ }
36
+
37
+ function setAttribute(node, name, value) {
38
+ const attr = attributes(node).find(item => item.name === name);
39
+ if (attr) attr.value = value;
40
+ else node.attrs.push({ name, value });
41
+ }
42
+
43
+ function removeAttribute(node, name) {
44
+ node.attrs = attributes(node).filter(attr => attr.name !== name);
45
+ }
46
+
47
+ function normalizeStyle(value) {
48
+ return String(value ?? '')
49
+ .replace(/box-shadow\s*:[^;]+;?/giu, '')
50
+ .replace(/text-shadow\s*:[^;]+;?/giu, '')
51
+ .replace(/background\s*:\s*linear-gradient\([^;]+\);?/giu, '')
52
+ .replace(/background\s*:\s*([#a-z0-9(),.%\s-]+);/giu, 'background-color: $1;')
53
+ .split(';')
54
+ .map(declaration => declaration.trim())
55
+ .filter(Boolean)
56
+ .map(declaration => {
57
+ const separator = declaration.indexOf(':');
58
+ if (separator < 0) return '';
59
+ const property = declaration.slice(0, separator).trim().toLowerCase();
60
+ let valuePart = declaration.slice(separator + 1).trim();
61
+ if (property === 'text-indent') valuePart = '0';
62
+ if (IMPORTANT_STYLE_PROPERTIES.has(property) && !/!important$/iu.test(valuePart)) {
63
+ valuePart += ' !important';
64
+ }
65
+ return `${property}: ${valuePart}`;
66
+ })
67
+ .filter(Boolean)
68
+ .join('; ');
69
+ }
70
+
71
+ function convertBackgroundSection(node) {
72
+ const tag = String(node.tagName ?? node.nodeName ?? '').toLowerCase();
73
+ if (tag !== 'section' && tag !== 'div') return;
74
+ const styleAttr = attributes(node).find(attr => attr.name === 'style');
75
+ const style = String(styleAttr?.value ?? '');
76
+ if (!style || !/background(?:-color)?\s*:/iu.test(style) || /font-family\s*:/iu.test(style)) return;
77
+
78
+ const children = node.childNodes ?? [];
79
+ const td = {
80
+ nodeName: 'td', tagName: 'td', namespaceURI: 'http://www.w3.org/1999/xhtml',
81
+ attrs: [{ name: 'style', value: normalizeStyle(style) }], childNodes: children,
82
+ };
83
+ const tr = {
84
+ nodeName: 'tr', tagName: 'tr', namespaceURI: 'http://www.w3.org/1999/xhtml',
85
+ attrs: [], childNodes: [td],
86
+ };
87
+ node.nodeName = 'table';
88
+ node.tagName = 'table';
89
+ node.attrs = [{
90
+ name: 'style',
91
+ value: 'width: 100% !important; border-collapse: separate !important; border-spacing: 0 !important; border-radius: 10px !important; overflow: hidden !important',
92
+ }];
93
+ node.childNodes = [tr];
94
+ }
95
+
96
+ function safeUrl(value, { image = false } = {}) {
97
+ const raw = String(value ?? '').trim();
98
+ if (!raw || raw.startsWith('javascript:') || raw.startsWith('data:')) return null;
99
+ if (image && raw.startsWith('blob:')) return null;
100
+ if (!image && !/^(?:https?:|mailto:)/iu.test(raw)) return null;
101
+ return raw;
102
+ }
103
+
104
+ function sanitizeAttributes(node) {
105
+ for (const attr of [...attributes(node)]) {
106
+ const name = attr.name.toLowerCase();
107
+ if (name.startsWith('on') || name === 'id' || name === 'class' || name === 'srcset') {
108
+ removeAttribute(node, attr.name);
109
+ continue;
110
+ }
111
+ if (name === 'style') {
112
+ const style = normalizeStyle(String(attr.value ?? '')
113
+ .replace(/url\s*\([^)]*\)/giu, '')
114
+ .replace(/expression\s*\([^)]*\)/giu, '')
115
+ .replace(/-moz-binding\s*:[^;]+;?/giu, ''));
116
+ if (style) setAttribute(node, 'style', style);
117
+ else removeAttribute(node, attr.name);
118
+ continue;
119
+ }
120
+ if (name === 'href') {
121
+ const url = safeUrl(attr.value);
122
+ if (url) setAttribute(node, 'href', url);
123
+ else removeAttribute(node, attr.name);
124
+ continue;
125
+ }
126
+ if (name === 'src' && node.tagName === 'img') continue;
127
+ if (name !== 'alt' && name !== 'title' && name !== 'target' && name !== 'rel') {
128
+ removeAttribute(node, attr.name);
129
+ }
130
+ }
131
+ }
132
+
133
+ async function sanitizeNode(node, options) {
134
+ if (!node || typeof node !== 'object') return;
135
+ if (node.nodeName === '#text') return;
136
+ if (node.nodeName === '#comment') {
137
+ node.nodeName = '#text';
138
+ node.value = '';
139
+ delete node.data;
140
+ return;
141
+ }
142
+
143
+ const tag = String(node.tagName ?? node.nodeName ?? '').toLowerCase();
144
+ if (DROP_TAGS.has(tag)) {
145
+ node.childNodes = [];
146
+ node.tagName = 'div';
147
+ node.nodeName = 'div';
148
+ node.attrs = [];
149
+ } else if (!ALLOWED_TAGS.has(tag)) {
150
+ node.tagName = 'span';
151
+ node.nodeName = 'span';
152
+ sanitizeAttributes(node);
153
+ } else {
154
+ sanitizeAttributes(node);
155
+ }
156
+
157
+ convertBackgroundSection(node);
158
+
159
+ if (tag === 'img') {
160
+ const source = attributes(node).find(attr => attr.name === 'src')?.value;
161
+ const url = safeUrl(source, { image: true });
162
+ if (!url) throw new CommandExecutionError('HTML contains an unsupported image source');
163
+ const isRemote = /^https?:\/\//iu.test(url);
164
+ const resolved = isRemote ? url : await options.resolveImage(url);
165
+ if (!resolved) throw new CommandExecutionError(`Could not upload HTML image: ${url}`);
166
+ setAttribute(node, 'src', resolved);
167
+ }
168
+
169
+ for (const child of node.childNodes ?? []) await sanitizeNode(child, options);
170
+ }
171
+
172
+ export function loadDraftContent({ content, contentFile, contentFormat = 'text' }) {
173
+ const format = String(contentFormat ?? 'text').toLowerCase();
174
+ if (!['html', 'html-text', 'text'].includes(format)) throw new ArgumentError('content-format must be html, html-text, or text');
175
+ if (contentFile) {
176
+ const filePath = nodePath.resolve(String(contentFile));
177
+ let fileContent;
178
+ try {
179
+ fileContent = nodeFs.readFileSync(filePath, 'utf8');
180
+ } catch {
181
+ throw new ArgumentError(`content-file must be a readable file: ${filePath}`);
182
+ }
183
+ if (!fileContent.trim()) throw new ArgumentError('content-file must not be empty');
184
+ return {
185
+ format: format === 'html-text' ? 'text' : format,
186
+ content: format === 'html-text' ? htmlToPlainText(fileContent) : fileContent,
187
+ filePath,
188
+ };
189
+ }
190
+ const value = String(content ?? '');
191
+ if (!value.trim()) throw new ArgumentError('content or content-file must not be empty');
192
+ return {
193
+ format: format === 'html-text' ? 'text' : format,
194
+ content: format === 'html-text' ? htmlToPlainText(value) : value,
195
+ filePath: null,
196
+ };
197
+ }
198
+
199
+ export async function prepareHtmlContent(html, { baseDir = process.cwd(), resolveImage } = {}) {
200
+ if (typeof resolveImage !== 'function') throw new ArgumentError('resolveImage is required for HTML content');
201
+ const fragment = parseWechatHtmlFragment(String(html ?? ''));
202
+ const imageResolver = async source => {
203
+ const absolute = /^https?:\/\//iu.test(source) ? source : nodePath.resolve(baseDir, source);
204
+ return resolveImage(absolute);
205
+ };
206
+ await Promise.all((fragment.childNodes ?? []).map(node => sanitizeNode(node, { resolveImage: imageResolver })));
207
+ return { html: serializeWechatHtml(fragment) };
208
+ }
@@ -0,0 +1,141 @@
1
+ import { CommandExecutionError } from '@sovovs/bycli/errors';
2
+
3
+ const RICH_NODE_PATTERN = /<(?:p|h[1-6]|strong|em|a|ul|ol|table|img|div|section|span)\b/i;
4
+
5
+ function plainTextFromHtml(html) {
6
+ return String(html ?? '')
7
+ .replace(/<br\s*\/?>/giu, '\n')
8
+ .replace(/<[^>]*>/gu, ' ')
9
+ .replace(/&nbsp;/giu, ' ')
10
+ .replace(/&amp;/giu, '&')
11
+ .replace(/&lt;/giu, '<')
12
+ .replace(/&gt;/giu, '>')
13
+ .replace(/\s+/gu, ' ')
14
+ .trim();
15
+ }
16
+
17
+ function clipboardWriteScript(html, text) {
18
+ return `(() => {
19
+ const html = ${JSON.stringify(html)};
20
+ const text = ${JSON.stringify(text)};
21
+ if (!navigator.clipboard || typeof navigator.clipboard.write !== 'function' || typeof ClipboardItem !== 'function') {
22
+ return { ok: false, reason: 'Clipboard API is unavailable' };
23
+ }
24
+ const item = new ClipboardItem({
25
+ 'text/html': new Blob([html], { type: 'text/html' }),
26
+ 'text/plain': new Blob([text], { type: 'text/plain' }),
27
+ });
28
+ return navigator.clipboard.write([item])
29
+ .then(() => ({ ok: true }))
30
+ .catch(error => ({ ok: false, reason: error && error.message ? error.message : String(error) }));
31
+ })()`;
32
+ }
33
+
34
+ function editorReadScript() {
35
+ return `(() => {
36
+ const ueditor = document.querySelector('#ueditor_0');
37
+ const iframeBody = ueditor?.tagName === 'IFRAME' ? ueditor.contentDocument?.body : null;
38
+ const scopedEditors = [...document.querySelectorAll('#js_ueditor [contenteditable="true"], #js_editor [contenteditable="true"]')];
39
+ const visibleEditors = scopedEditors.filter(node => node.offsetParent !== null);
40
+ const editor = iframeBody || (ueditor?.matches?.('[contenteditable="true"]') ? ueditor : null)
41
+ || visibleEditors[visibleEditors.length - 1];
42
+ if (!editor) return { ok: false, reason: 'contenteditable editor not found' };
43
+ const warning = [...document.querySelectorAll('.weui-desktop-dialog__wrp, .weui-desktop-dialog')]
44
+ .some(dialog => {
45
+ const wrap = dialog.closest('.weui-desktop-dialog__wrp') || dialog;
46
+ return window.getComputedStyle(wrap).display !== 'none'
47
+ && wrap.offsetHeight > 0
48
+ && (dialog.innerText || '').includes('\u5b89\u5168\u9690\u60a3');
49
+ });
50
+ return { ok: true, warning, html: editor.innerHTML || '', text: editor.innerText || editor.textContent || '' };
51
+ })()`;
52
+ }
53
+
54
+ export async function pasteHtmlThroughClipboard(page, html, {
55
+ origin = 'https://mp.weixin.qq.com',
56
+ platform = process.platform,
57
+ } = {}) {
58
+ if (typeof page?.cdp !== 'function') {
59
+ throw new CommandExecutionError('Rich HTML paste requires Browser Bridge CDP support');
60
+ }
61
+ if (typeof page?.evaluate !== 'function' || typeof page?.nativeKeyPress !== 'function' || typeof page?.nativeClick !== 'function') {
62
+ throw new CommandExecutionError('Rich HTML paste requires page evaluation and native key support');
63
+ }
64
+
65
+ const source = String(html ?? '');
66
+ if (!source.trim()) throw new CommandExecutionError('Rich HTML content must not be empty');
67
+
68
+ if (typeof page.focusWindow === 'function') {
69
+ try { await page.focusWindow(); } catch { /* the native paste will report focus failures */ }
70
+ }
71
+
72
+ try {
73
+ await page.cdp('Browser.grantPermissions', {
74
+ origin,
75
+ permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
76
+ });
77
+ } catch (error) {
78
+ const message = String(error?.message ?? error);
79
+ if (!message.includes('CDP method not permitted: Browser.grantPermissions')) {
80
+ throw new CommandExecutionError(`Could not grant clipboard permission: ${message}`);
81
+ }
82
+ }
83
+
84
+ const editorLocation = await page.evaluate(`(() => {
85
+ const ueditor = document.querySelector('#ueditor_0');
86
+ const iframeBody = ueditor?.tagName === 'IFRAME' ? ueditor.contentDocument?.body : null;
87
+ const scopedEditors = [...document.querySelectorAll('#js_ueditor [contenteditable="true"], #js_editor [contenteditable="true"]')];
88
+ const visibleEditors = scopedEditors.filter(node => node.offsetParent !== null);
89
+ const editor = iframeBody || (ueditor?.matches?.('[contenteditable="true"]') ? ueditor : null)
90
+ || visibleEditors[visibleEditors.length - 1];
91
+ if (!editor) return { ok: false, reason: 'contenteditable editor not found' };
92
+ const rect = (ueditor?.tagName === 'IFRAME' ? ueditor : editor).getBoundingClientRect();
93
+ return {
94
+ ok: rect.width > 0 && rect.height > 0,
95
+ rect: { x: rect.left, y: rect.top, width: rect.width, height: rect.height },
96
+ };
97
+ })()`);
98
+ if (!editorLocation?.ok) throw new CommandExecutionError(`Could not locate rich-text editor: ${editorLocation?.reason ?? 'unknown error'}`);
99
+
100
+ if (typeof page.focusWindow === 'function') {
101
+ try { await page.focusWindow(); } catch { /* the clipboard write reports the actionable error */ }
102
+ }
103
+ const x = Math.round(editorLocation.rect.x + editorLocation.rect.width / 2);
104
+ const y = Math.round(editorLocation.rect.y + editorLocation.rect.height / 2);
105
+ await page.nativeClick(x, y);
106
+
107
+ const written = await page.evaluate(clipboardWriteScript(source, plainTextFromHtml(source)));
108
+ if (!written?.ok) throw new CommandExecutionError(`Could not write HTML to clipboard: ${written?.reason ?? 'unknown error'}`);
109
+
110
+ const shortcut = platform === 'darwin' ? ['Meta'] : ['Ctrl'];
111
+ try {
112
+ await page.nativeKeyPress('v', shortcut);
113
+ } catch {
114
+ const modifiers = platform === 'darwin' ? 4 : 2;
115
+ await page.cdp('Input.dispatchKeyEvent', {
116
+ type: 'keyDown', key: 'v', code: 'KeyV', modifiers,
117
+ windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86,
118
+ });
119
+ await page.cdp('Input.dispatchKeyEvent', {
120
+ type: 'keyUp', key: 'v', code: 'KeyV', modifiers,
121
+ windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86,
122
+ });
123
+ }
124
+ if (typeof page.wait === 'function') await page.wait(1);
125
+
126
+ const result = await page.evaluate(editorReadScript());
127
+ if (result?.warning) {
128
+ throw new CommandExecutionError('WeChat displayed its editor-integrity warning after rich HTML paste; the draft was not saved');
129
+ }
130
+ if (!result?.ok || !String(result.text ?? '').trim() || !RICH_NODE_PATTERN.test(String(result.html ?? ''))) {
131
+ const actualHtml = String(result?.html ?? '');
132
+ const actualText = String(result?.text ?? '');
133
+ const tags = [...actualHtml.matchAll(/<([a-z0-9]+)/giu)].map(match => match[1].toLowerCase());
134
+ throw new CommandExecutionError(
135
+ `rich HTML content was not retained by the editor (htmlLength=${actualHtml.length}, textLength=${actualText.length}, tags=${tags.join(',') || 'none'})`,
136
+ );
137
+ }
138
+ return { html: result.html, text: result.text };
139
+ }
140
+
141
+ export { plainTextFromHtml };
@@ -2,6 +2,9 @@ import * as nodeFs from 'node:fs';
2
2
  import * as nodePath from 'node:path';
3
3
  import { cli, Strategy } from '@sovovs/bycli/registry';
4
4
  import { ArgumentError, AuthRequiredError, CommandExecutionError } from '@sovovs/bycli/errors';
5
+ import { loadDraftContent, prepareHtmlContent } from './_wechat/draft-content.js';
6
+ import { pasteHtmlThroughClipboard } from './_wechat/html-clipboard.js';
7
+ import { createDraftViaApi } from './_wechat/api-draft.js';
5
8
 
6
9
  const WEIXIN_DOMAIN = 'mp.weixin.qq.com';
7
10
  const WEIXIN_HOME = 'https://mp.weixin.qq.com/';
@@ -40,7 +43,6 @@ function validateCoverImage(value) {
40
43
 
41
44
  function normalizeCreateDraftArgs(kwargs) {
42
45
  const title = requiredText(kwargs.title, 'title');
43
- requiredText(kwargs.content, 'content');
44
46
  if (codePointLength(title) > MAX_TITLE_LENGTH) {
45
47
  throw new ArgumentError(`title must be at most ${MAX_TITLE_LENGTH} characters`);
46
48
  }
@@ -48,12 +50,25 @@ function normalizeCreateDraftArgs(kwargs) {
48
50
  if (author && codePointLength(author) > MAX_AUTHOR_LENGTH) {
49
51
  throw new ArgumentError(`author must be at most ${MAX_AUTHOR_LENGTH} characters`);
50
52
  }
53
+ const draftContent = loadDraftContent({
54
+ content: kwargs.content,
55
+ contentFile: kwargs['content-file'],
56
+ contentFormat: kwargs['content-format'],
57
+ });
58
+ const appid = kwargs.appid == null ? '' : String(kwargs.appid).trim();
59
+ const appsecret = kwargs.appsecret == null ? '' : String(kwargs.appsecret).trim();
60
+ if (Boolean(appid) !== Boolean(appsecret)) {
61
+ throw new ArgumentError('appid and appsecret must be provided together');
62
+ }
51
63
  return {
52
64
  title,
53
- content: String(kwargs.content),
65
+ ...draftContent,
54
66
  author,
55
67
  summary: kwargs.summary == null ? null : String(kwargs.summary).trim(),
56
68
  coverImage: validateCoverImage(kwargs['cover-image']),
69
+ dryRun: kwargs['dry-run'] === true,
70
+ appid: appid || null,
71
+ appsecret: appsecret || null,
57
72
  };
58
73
  }
59
74
 
@@ -225,19 +240,31 @@ async function uploadContentImage(page, imagePath) {
225
240
 
226
241
  for (let attempt = 0; attempt < 15; attempt++) {
227
242
  await page.wait(1);
228
- const cdnCount = await page.evaluate(`(() => {
243
+ const uploaded = await page.evaluate(`(() => {
229
244
  var editors = document.querySelectorAll('#ueditor_0, div[contenteditable="true"]');
230
- var count = 0;
245
+ var sources = [];
231
246
  editors.forEach(function(editor) {
232
- count += editor.querySelectorAll('img[src*="mmbiz"], img[data-src*="mmbiz"]').length;
247
+ editor.querySelectorAll('img[src*="mmbiz"], img[data-src*="mmbiz"]').forEach(function(image) {
248
+ var src = image.getAttribute('src') || image.getAttribute('data-src') || '';
249
+ if (src && !sources.includes(src)) sources.push(src);
250
+ });
233
251
  });
234
- return count;
252
+ return sources;
235
253
  })()`);
236
- if (cdnCount > 0) return;
254
+ if (Array.isArray(uploaded) && uploaded.length > 0) return uploaded[uploaded.length - 1];
255
+ if (typeof uploaded === 'string' && uploaded) return uploaded;
256
+ if (typeof uploaded === 'number' && uploaded > 0) return true;
237
257
  }
238
258
  throw new CommandExecutionError('Image did not upload to WeChat CDN');
239
259
  }
240
260
 
261
+ async function removeTemporaryInsertedImage(page) {
262
+ if (typeof page.nativeKeyPress !== 'function') return;
263
+ await page.nativeKeyPress('Backspace', []);
264
+ await page.nativeKeyPress('Backspace', []);
265
+ if (typeof page.wait === 'function') await page.wait(1);
266
+ }
267
+
241
268
  async function selectCoverFromContent(page) {
242
269
  await page.evaluate('document.querySelector("#js_cover_description_area")?.scrollIntoView()');
243
270
  await page.wait(1);
@@ -330,23 +357,46 @@ export const createDraftCommand = cli({
330
357
  site: 'weixin',
331
358
  name: 'create-draft',
332
359
  access: 'write',
333
- description: '创建微信公众号图文草稿',
360
+ description: '创建微信公众号草稿(支持浏览器富文本或官方 API)',
361
+ example: 'bycli weixin create-draft --title "文章标题" --content-file article.html --content-format html --cover-image cover.jpg',
334
362
  domain: WEIXIN_DOMAIN,
335
363
  strategy: Strategy.COOKIE,
336
364
  browser: true,
337
365
  navigateBefore: false,
338
366
  args: [
339
- { name: 'title', required: true, help: '文章标题 (最长64字)' },
340
- { name: 'content', required: true, positional: true, help: '文章正文' },
341
- { name: 'author', help: '作者名 (最长8字)' },
342
- { name: 'cover-image', help: '封面图片路径 (会先上传到正文再设为封面)' },
343
- { name: 'summary', help: '文章摘要' },
344
- { name: 'timeout', type: 'int', required: false, default: 180, help: 'Max seconds for the overall command (default: 180)' },
367
+ { name: 'title', required: true, help: '文章标题(最长 64 字)' },
368
+ { name: 'content', required: false, positional: true, help: '正文文本;也可用 --content-file 读取 HTML 文件' },
369
+ { name: 'content-file', help: '正文文件路径;HTML 模式支持本地图片' },
370
+ { name: 'content-format', choices: ['text', 'html', 'html-text'], default: 'text', help: '正文格式:text=纯文本,html=富文本,html-text=保留段落但忽略样式' },
371
+ { name: 'author', help: '作者名(最长 8 字)' },
372
+ { name: 'cover-image', help: '封面图路径;API 模式必填,浏览器模式会上传后设为封面' },
373
+ { name: 'summary', help: '文章摘要;API 模式对应 digest' },
374
+ { name: 'appid', help: '公众号 AppID;与 --appsecret 同传时走官方 API,不打开浏览器' },
375
+ { name: 'appsecret', help: '公众号 AppSecret;请勿提交到 shell 历史或日志' },
376
+ { name: 'dry-run', type: 'boolean', default: false, help: '浏览器模式:填充并验证正文后停止,不会保存草稿' },
377
+ { name: 'timeout', type: 'int', required: false, default: 180, help: '命令总超时时间(秒,默认 180)' },
345
378
  ],
346
379
  columns: ['status', 'detail'],
347
380
 
348
381
  func: async (page, kwargs) => {
349
382
  const args = normalizeCreateDraftArgs(kwargs);
383
+ if (args.appid && args.appsecret) {
384
+ const baseDir = args.filePath ? nodePath.dirname(args.filePath) : process.cwd();
385
+ const result = await createDraftViaApi({
386
+ appid: args.appid,
387
+ appsecret: args.appsecret,
388
+ title: args.title,
389
+ author: args.author ?? '',
390
+ digest: args.summary ?? '',
391
+ coverImage: args.coverImage,
392
+ html: args.content,
393
+ baseDir,
394
+ });
395
+ return [{
396
+ status: 'draft created',
397
+ detail: `"${args.title}" (media_id: ${result.mediaId})`,
398
+ }];
399
+ }
350
400
  await navigateToEditor(page);
351
401
 
352
402
 
@@ -360,8 +410,29 @@ export const createDraftCommand = cli({
360
410
 
361
411
  await page.wait(10);
362
412
 
363
- const contentResult = await fillContent(page, args.content);
364
- requirePageResult(contentResult, 'content');
413
+ let content = args.content;
414
+ if (args.format === 'html') {
415
+ const baseDir = args.filePath ? nodePath.dirname(args.filePath) : process.cwd();
416
+ const prepared = await prepareHtmlContent(content, {
417
+ baseDir,
418
+ resolveImage: async imagePath => {
419
+ const uploaded = await uploadContentImage(page, imagePath);
420
+ await removeTemporaryInsertedImage(page);
421
+ return uploaded;
422
+ },
423
+ });
424
+ await pasteHtmlThroughClipboard(page, prepared.html, { origin: `https://${WEIXIN_DOMAIN}` });
425
+ } else {
426
+ const contentResult = await fillContent(page, content);
427
+ requirePageResult(contentResult, 'content');
428
+ }
429
+
430
+ if (args.dryRun) {
431
+ return [{
432
+ status: 'draft ready',
433
+ detail: `"${args.title}" (dry-run)`,
434
+ }];
435
+ }
365
436
 
366
437
  if (args.coverImage) {
367
438
  await uploadContentImage(page, args.coverImage);
@@ -25,6 +25,8 @@ const COLUMNS = [
25
25
  'title', 'publishedAt', 'url', 'status',
26
26
  ...METRIC_COLUMNS,
27
27
  'markdownPath', 'markdownSize', 'dataPath', 'dataSize', 'error',
28
+ 'listReads', 'listShares', 'listLikes', 'listComments',
29
+ 'detailReadUsers', 'detailShares', 'detailLikes', 'detailComments',
28
30
  ];
29
31
 
30
32
  function sanitizedError(error, secrets, fallback) {
@@ -135,17 +137,43 @@ export const downloadPublishDataCommand = cli({
135
137
  const status = dataResult && markdownResult ? 'downloaded'
136
138
  : dataResult || markdownResult ? 'partial' : 'failed';
137
139
  const metrics = markdownResult?.metrics ?? null;
140
+
141
+ // Use published list data as the authoritative source for overlapping fields.
142
+ // Detail page metrics are only used for fields exclusive to the detail page.
143
+ const mergedMetrics = {
144
+ readUsers: record.reads,
145
+ avgReadMinutes: metrics?.avgReadMinutes ?? null,
146
+ finishedReadRatio: metrics?.finishedReadRatio ?? null,
147
+ newFollowers: metrics?.newFollowers ?? null,
148
+ listenUsers: metrics?.listenUsers ?? null,
149
+ shares: record.shares,
150
+ zaikan: metrics?.zaikan ?? null,
151
+ likes: record.likes,
152
+ rewardYuan: metrics?.rewardYuan ?? null,
153
+ comments: record.comments,
154
+ collections: metrics?.collections ?? null,
155
+ };
156
+
138
157
  return [{
139
158
  title: record.title,
140
159
  publishedAt: record.publishedAt,
141
160
  url: record.url,
142
161
  status,
143
- ...Object.fromEntries(METRIC_COLUMNS.map(key => [key, metrics?.[key] ?? null])),
162
+ ...mergedMetrics,
144
163
  markdownPath: markdownResult?.path ?? null,
145
164
  markdownSize: markdownResult?.size ?? null,
146
165
  dataPath: dataResult?.path ?? null,
147
166
  dataSize: dataResult?.size ?? null,
148
167
  error: errors.length > 0 ? errors.join('; ') : null,
168
+ // Data source transparency: show raw values from both sources
169
+ listReads: record.reads,
170
+ listShares: record.shares,
171
+ listLikes: record.likes,
172
+ listComments: record.comments,
173
+ detailReadUsers: metrics?.readUsers ?? null,
174
+ detailShares: metrics?.shares ?? null,
175
+ detailLikes: metrics?.likes ?? null,
176
+ detailComments: metrics?.comments ?? null,
149
177
  }];
150
178
  },
151
179
  });
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import TurndownService from 'turndown';
9
9
  export { extractWechatArticleHtml } from './wechat-article.js';
10
+ export { parseFragment as parseWechatHtmlFragment, serialize as serializeWechatHtml } from 'parse5';
10
11
  export interface ArticleData {
11
12
  title: string;
12
13
  author?: string;
@@ -13,6 +13,7 @@ import { gfm } from 'turndown-plugin-gfm';
13
13
  import { httpDownload, sanitizeFilename } from './index.js';
14
14
  import { formatBytes } from './progress.js';
15
15
  export { extractWechatArticleHtml } from './wechat-article.js';
16
+ export { parseFragment as parseWechatHtmlFragment, serialize as serializeWechatHtml } from 'parse5';
16
17
  const IMAGE_CONCURRENCY = 5;
17
18
  const DEFAULT_LABELS = {
18
19
  author: '作者',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sovovs/bycli",
3
- "version": "2.1.33",
3
+ "version": "2.1.35",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -95,14 +95,6 @@
95
95
  "text": "const count = Math.min(kwargs.limit || 20, 50);",
96
96
  "occurrence": 0
97
97
  },
98
- {
99
- "rule": "silent-clamp",
100
- "command": "bilibili/comments",
101
- "file": "clis/bilibili/comments.js",
102
- "line": 21,
103
- "text": "const limit = Math.min(Number(kwargs.limit) || 20, 50);",
104
- "occurrence": 0
105
- },
106
98
  {
107
99
  "rule": "silent-clamp",
108
100
  "command": "bilibili/favorite",
@@ -271,6 +263,14 @@
271
263
  "text": "return Math.max(1, Math.min(parsed, MAX_LIMIT));",
272
264
  "occurrence": 0
273
265
  },
266
+ {
267
+ "rule": "silent-clamp",
268
+ "command": "github/search",
269
+ "file": "clis/github/search.js",
270
+ "line": 238,
271
+ "text": "url.searchParams.set('per_page', String(Math.min(perPage, MAX_LIMIT)));",
272
+ "occurrence": 0
273
+ },
274
274
  {
275
275
  "rule": "silent-clamp",
276
276
  "command": "google/news",
@@ -419,7 +419,7 @@
419
419
  "rule": "silent-clamp",
420
420
  "command": "linkedin/timeline",
421
421
  "file": "clis/linkedin/timeline.js",
422
- "line": 473,
422
+ "line": 479,
423
423
  "text": "const limit = Math.max(1, Math.min(kwargs.limit ?? 20, 100));",
424
424
  "occurrence": 0
425
425
  },
@@ -635,7 +635,7 @@
635
635
  "rule": "silent-clamp",
636
636
  "command": "twitter/following",
637
637
  "file": "clis/twitter/following.js",
638
- "line": 227,
638
+ "line": 228,
639
639
  "text": "const fetchCount = Math.min(50, limit - allUsers.length + 10);",
640
640
  "occurrence": 0
641
641
  },
@@ -643,7 +643,7 @@
643
643
  "rule": "silent-clamp",
644
644
  "command": "twitter/likes",
645
645
  "file": "clis/twitter/likes.js",
646
- "line": 207,
646
+ "line": 208,
647
647
  "text": "const fetchCount = Math.min(100, limit - allTweets.length + 10);",
648
648
  "occurrence": 0
649
649
  },
@@ -651,7 +651,7 @@
651
651
  "rule": "silent-clamp",
652
652
  "command": "twitter/list-tweets",
653
653
  "file": "clis/twitter/list-tweets.js",
654
- "line": 176,
654
+ "line": 178,
655
655
  "text": "const fetchCount = Math.min(100, limit - allTweets.length + 10);",
656
656
  "occurrence": 0
657
657
  },
@@ -659,7 +659,7 @@
659
659
  "rule": "silent-clamp",
660
660
  "command": "twitter/timeline",
661
661
  "file": "clis/twitter/timeline.js",
662
- "line": 183,
662
+ "line": 185,
663
663
  "text": "const fetchCount = Math.min(40, limit - allTweets.length + 5); // over-fetch slightly for promoted filtering",
664
664
  "occurrence": 0
665
665
  },
@@ -819,7 +819,7 @@
819
819
  "rule": "silent-clamp",
820
820
  "command": "zhihu/collection",
821
821
  "file": "clis/zhihu/collection.js",
822
- "line": 154,
822
+ "line": 142,
823
823
  "text": "const currentFetchLimit = Math.min(pageLimit, requestedLimit - collected.length);",
824
824
  "occurrence": 0
825
825
  },
@@ -827,7 +827,7 @@
827
827
  "rule": "silent-clamp",
828
828
  "command": "zhihu/collection",
829
829
  "file": "clis/zhihu/collection.js",
830
- "line": 143,
830
+ "line": 131,
831
831
  "text": "const pageLimit = Math.min(requestedLimit, 20); // 知乎 API 限制每页最大 20",
832
832
  "occurrence": 0
833
833
  },
@@ -1003,7 +1003,7 @@
1003
1003
  "rule": "silent-sentinel",
1004
1004
  "command": "twitter/search",
1005
1005
  "file": "clis/twitter/search.js",
1006
- "line": 217,
1006
+ "line": 218,
1007
1007
  "text": "author: tweetUser?.core?.screen_name || tweetUser?.legacy?.screen_name || 'unknown',",
1008
1008
  "occurrence": 0
1009
1009
  },
@@ -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