publishport-opencli 1.0.62 → 1.0.64

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.
@@ -1,4 +1,4 @@
1
- import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/topics.js";import{XHS_PUBLISH_ARGS as wt,validateXhsSettings as gt,setXhsPublishSettings as _t}from"./_shared/publish-settings.js";import*as L from"node:fs";import*as N from"node:path";import{CommandExecutionError as u,ArgumentError as b}from"@jackwener/opencli/errors";import{cli as xt,Strategy as yt}from"@jackwener/opencli/registry";import{assertLiteralContent as vt}from"../_shared/content-guard.js";import{setInputFiles as St}from"../_shared/file-inject.js";import{humanType as H,humanWait as I,humanMoveTo as Tt,elementViewportCenter as kt}from"./human.js";import{loadNoteManagerNotes as Et}from"./_shared/note-manager.js";const $t="https://creator.xiaohongshu.com/publish/publish?from=menu_left&target=image",B=18,X=20,G=3000,Y="|||",k="基础",K=[["基础","默认兜底,万能"],["边框","金句/要点卡"],["备忘","提醒/随手记"],["清新","日常/清单贴士"],["涂写","随笔/碎碎念"],["便签","笔记/提醒"],["光影","情绪/文艺"],["涂鸦","趣味/童话"],["简约","干货/观点"],["手写","日记/情感"],["插图","生活方式/轻松话题"],["美漫","活力/趣味/故事感"],["弥散","弥散光氛围"],["柔和","柔和/温柔金句"],["印刷","印刷海报/排版"],["科技","科技/产品"],["贺卡","节日祝福"],["札记","艺术/水彩氛围"],["书摘","书摘/引用"],["手帐","手帐拼贴"],["几何","醒目/有力主张"]],ae=K.map(([t])=>t),F="文字配图",W="再写一张",Q="生成图片",Z="下一步",U=".tiptap.ProseMirror",At=["_onPublish","onPublish","_onSubmit","_handlePublish"],Ct=["_onSave","_onSaveDraft","_onDraft"],J=['[contenteditable="true"][placeholder*="标题"]','[contenteditable="true"][placeholder*="赞"]','input[placeholder*="标题"]','input[placeholder*="title" i]','[contenteditable="true"][class*="title"]','input[maxlength="20"]','input[class*="title"]',".title-input input",".note-title input","input[maxlength]"],tt=['[contenteditable="true"][class*="content"]','[contenteditable="true"][class*="editor"]','[contenteditable="true"][placeholder*="描述"]','[contenteditable="true"][placeholder*="正文"]','[contenteditable="true"][placeholder*="内容"]','.note-content [contenteditable="true"]','.editor-content [contenteditable="true"]','[contenteditable="true"]:not([placeholder*="标题"]):not([placeholder*="赞"]):not([placeholder*="title" i])'],Mt={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp"};function _(t){if(t&&typeof t==="object"&&typeof t.session==="string"&&Object.prototype.hasOwnProperty.call(t,"data"))return t.data;return t}function Nt(t){return t.map((e)=>{const r=N.resolve(e);if(!L.existsSync(r))throw new b(`Image file not found: ${r}`);const n=N.extname(r).toLowerCase();if(!Mt[n])throw new b(`Unsupported image format "${n}". Supported: jpg, png, gif, webp`);return r})}const et='input[type="file"][accept*="image"],input[type="file"][accept*=".jpg"],input[type="file"][accept*=".jpeg"],input[type="file"][accept*=".png"],input[type="file"][accept*=".gif"],input[type="file"][accept*=".webp"]';async function It(t,e=15000){const r=500,n=Math.max(1,Math.ceil(e/r));for(let o=0;o<n;o++){if(await t.evaluate(`
1
+ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/topics.js";import{XHS_PUBLISH_ARGS as wt,validateXhsSettings as gt,setXhsPublishSettings as _t}from"./_shared/publish-settings.js";import*as O from"node:fs";import*as N from"node:path";import{CommandExecutionError as u,ArgumentError as b}from"@jackwener/opencli/errors";import{cli as xt,Strategy as yt}from"@jackwener/opencli/registry";import{assertLiteralContent as vt}from"../_shared/content-guard.js";import{setInputFiles as St}from"../_shared/file-inject.js";import{humanType as z,humanWait as I,humanMoveTo as Tt,elementViewportCenter as kt}from"./human.js";import{loadNoteManagerNotes as $t}from"./_shared/note-manager.js";const At="https://creator.xiaohongshu.com/publish/publish?from=menu_left&target=image",F=18,H=20,X=3000,G="|||",k="基础",Y=[["基础","默认兜底,万能"],["边框","金句/要点卡"],["备忘","提醒/随手记"],["清新","日常/清单贴士"],["涂写","随笔/碎碎念"],["便签","笔记/提醒"],["光影","情绪/文艺"],["涂鸦","趣味/童话"],["简约","干货/观点"],["手写","日记/情感"],["插图","生活方式/轻松话题"],["美漫","活力/趣味/故事感"],["弥散","弥散光氛围"],["柔和","柔和/温柔金句"],["印刷","印刷海报/排版"],["科技","科技/产品"],["贺卡","节日祝福"],["札记","艺术/水彩氛围"],["书摘","书摘/引用"],["手帐","手帐拼贴"],["几何","醒目/有力主张"]],ae=Y.map(([t])=>t),B="文字配图",K="再写一张",W="生成图片",Q="下一步",U=".tiptap.ProseMirror",Et=["_onPublish","onPublish","_onSubmit","_handlePublish"],Ct=["_onSave","_onSaveDraft","_onDraft"],Z=['[contenteditable="true"][placeholder*="标题"]','[contenteditable="true"][placeholder*="赞"]','input[placeholder*="标题"]','input[placeholder*="title" i]','[contenteditable="true"][class*="title"]','input[maxlength="20"]','input[class*="title"]',".title-input input",".note-title input","input[maxlength]"],tt=['[contenteditable="true"][class*="content"]','[contenteditable="true"][class*="editor"]','[contenteditable="true"][placeholder*="描述"]','[contenteditable="true"][placeholder*="正文"]','[contenteditable="true"][placeholder*="内容"]','.note-content [contenteditable="true"]','.editor-content [contenteditable="true"]','[contenteditable="true"]:not([placeholder*="标题"]):not([placeholder*="赞"]):not([placeholder*="title" i])'],Mt={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp"};function _(t){if(t&&typeof t==="object"&&typeof t.session==="string"&&Object.prototype.hasOwnProperty.call(t,"data"))return t.data;return t}function Nt(t){return t.map((e)=>{const r=N.resolve(e);if(!O.existsSync(r))throw new b(`Image file not found: ${r}`);const n=N.extname(r).toLowerCase();if(!Mt[n])throw new b(`Unsupported image format "${n}". Supported: jpg, png, gif, webp`);return r})}const et='input[type="file"][accept*="image"],input[type="file"][accept*=".jpg"],input[type="file"][accept*=".jpeg"],input[type="file"][accept*=".png"],input[type="file"][accept*=".gif"],input[type="file"][accept*=".webp"]';async function It(t,e=15000){const r=500,n=Math.max(1,Math.ceil(e/r));for(let o=0;o<n;o++){if(await t.evaluate(`
2
2
  (() => {
3
3
  const sels = ${JSON.stringify(et)};
4
4
  return !!document.querySelector(sels);
@@ -117,7 +117,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
117
117
  return { ok: true };
118
118
  })(${JSON.stringify(o.sel)})
119
119
  `))?.ok){await t.screenshot({path:`/tmp/xhs_publish_${n}_debug.png`});throw Error(`Could not prepare ${n} input. Debug screenshot: /tmp/xhs_publish_${n}_debug.png`)}await t.wait({time:0.35});try{const s=String(r).split(`
120
- `);for(let d=0;d<s.length;d++){if(d>0)await Pt(t,o.sel,d);if(s[d])await H(t,s[d])}a=await t.evaluate(`
120
+ `);for(let d=0;d<s.length;d++){if(d>0)await Pt(t,o.sel,d);if(s[d])await z(t,s[d])}a=await t.evaluate(`
121
121
  ((selector, expectedText) => {
122
122
  const __opencli_xhs_fill_phase = "verify";
123
123
  const normalize = (value) => (value || '').replace(/\\s+/g, ' ').trim();
@@ -143,7 +143,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
143
143
  })(${JSON.stringify(o.sel)}, ${JSON.stringify(r)})
144
144
  `)}catch(s){if(s instanceof u)throw s;if(String(r).includes(`
145
145
  `))throw new u(`写入${n}失败:${String(s?.message||s)}。`+"正文含换行,不能回退到单段写入方式(那会把多段正文塞进一段),因此中止。"+"⚠️ 编辑器可能已自动保存草稿:请勿直接重试,先用 `ppcli xiaohongshu drafts` 查看。");a=await i()}}else a=await i();if(!a?.ok){await t.screenshot({path:`/tmp/xhs_publish_${n}_debug.png`});const l=typeof a?.actual==="string"?a.actual:"";throw Error(`Failed to set ${n}. ${describeTextMismatch(String(r).replace(/\s+/g," ").trim(),l,typeof a?.blocks==="number"?{expected:String(r).split(`
146
- `).length,actual:a.blocks}:void 0)}`+" ⚠️ 编辑器可能已自动保存草稿:请勿直接重试,先用 `ppcli xiaohongshu drafts` 查看,"+"已存在则改为在该草稿上继续操作或先删除,避免建出重复草稿。"+` Debug screenshot: /tmp/xhs_publish_${n}_debug.png`)}}async function Rt(t){const e=await t.evaluate(`
146
+ `).length,actual:a.blocks}:void 0)}`+" ⚠️ 编辑器可能已自动保存草稿:请勿直接重试,先用 `ppcli xiaohongshu drafts` 查看,"+"已存在则改为在该草稿上继续操作或先删除,避免建出重复草稿。"+` Debug screenshot: /tmp/xhs_publish_${n}_debug.png`)}}async function Dt(t){const e=await t.evaluate(`
147
147
  () => {
148
148
  const isVisible = (el) => {
149
149
  if (!el || el.offsetParent === null) return false;
@@ -192,7 +192,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
192
192
  }
193
193
  return { ok: false, visibleTexts };
194
194
  }
195
- `);if(e?.ok)await t.wait({time:1});return e}async function E(t,e,r=7000){const n=500,o=Math.max(1,Math.ceil(r/n));let i={ok:!1};for(let a=0;a<o;a++){i=_(await t.evaluate(`
195
+ `);if(e?.ok)await t.wait({time:1});return e}async function A(t,e,r=7000){const n=500,o=Math.max(1,Math.ceil(r/n));let i={ok:!1};for(let a=0;a<o;a++){i=_(await t.evaluate(`
196
196
  ((cfg) => {
197
197
  const __opencli_xhs_click_label = { wantLabel: ${JSON.stringify(e)} };
198
198
  const wantLabel = ${JSON.stringify(e)};
@@ -227,7 +227,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
227
227
  }
228
228
  return { ok: false };
229
229
  })()
230
- `));if(i?.ok)return i;await t.wait({time:n/1000})}return i}async function Dt(t){const e=await t.evaluate(`
230
+ `));if(i?.ok)return i;await t.wait({time:n/1000})}return i}async function Rt(t){const e=await t.evaluate(`
231
231
  (() => {
232
232
  const __opencli_xhs_focus_card = true;
233
233
  const sel = ${JSON.stringify(U)};
@@ -262,16 +262,16 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
262
262
  const activeText = active ? (active.innerText || active.textContent || '').trim() : '';
263
263
  return { ok: true, count: editors.length, activeEmpty: !activeText };
264
264
  })()
265
- `);return _(e)}async function Ot(t,e=8000){const r=300,n=Math.ceil(e/r);for(let o=0;o<n;o++){if((await it(t))?.count>=1)return!0;await t.wait({time:r/1000})}return!1}async function Lt(t,e,r=6000){const n=300,o=Math.ceil(r/n);for(let i=0;i<o;i++){const a=await it(t);if(a?.count>=e&&a?.activeEmpty)return!0;await t.wait({time:n/1000})}return!1}async function Bt(t,e,r=4){for(let n=0;n<r;n++){if(!(await E(t,W))?.ok)return!1;if(await Lt(t,e,2500))return!0}return!1}async function Ft(t){const e=await t.evaluate(`
265
+ `);return _(e)}async function Lt(t,e=8000){const r=300,n=Math.ceil(e/r);for(let o=0;o<n;o++){if((await it(t))?.count>=1)return!0;await t.wait({time:r/1000})}return!1}async function Ot(t,e,r=6000){const n=300,o=Math.ceil(r/n);for(let i=0;i<o;i++){const a=await it(t);if(a?.count>=e&&a?.activeEmpty)return!0;await t.wait({time:n/1000})}return!1}async function Ft(t,e,r=4){for(let n=0;n<r;n++){if(!(await A(t,K))?.ok)return!1;if(await Ot(t,e,2500))return!0}return!1}async function Bt(t){const e=await t.evaluate(`
266
266
  (() => {
267
267
  const __opencli_xhs_preview_ready = true;
268
268
  const ready = Array.from(document.querySelectorAll('button'))
269
269
  .some((b) => b.offsetParent !== null && (b.innerText || '').replace(/\\s+/g, '') === '下一步');
270
270
  return { ok: ready };
271
271
  })()
272
- `);return _(e)}async function Ut(t,e=6){const r=400,n=Math.ceil(3000/r);for(let o=0;o<e;o++){if(!(await E(t,Q))?.ok&&o===0)return!1;for(let a=0;a<n;a++){if((await Ft(t))?.ok)return!0;await t.wait({time:r/1000})}}return!1}async function Jt(t,e,r){e=String(e).replace(/\\n/g,`
273
- `);if(!(await Dt(t))?.ok)throw new u(`文字配图: could not focus card editor #${r+1}`);if(typeof t.insertText==="function"){const i=e.split(`
274
- `);for(let a=0;a<i.length;a++){if(a>0&&typeof t.pressKey==="function")await t.pressKey("Enter");if(i[a])await H(t,i[a])}}else await t.evaluate(`(t => document.execCommand('insertText', false, t))(${JSON.stringify(e)})`);await t.wait({time:0.4});if(!(await qt(t))?.ok)throw new u(`文字配图: card editor #${r+1} is empty after typing`)}async function jt(t,e){if(!e||e===k)return k;const r=_(await t.evaluate(`
272
+ `);return _(e)}async function Ut(t,e=6){const r=400,n=Math.ceil(3000/r);for(let o=0;o<e;o++){if(!(await A(t,W))?.ok&&o===0)return!1;for(let a=0;a<n;a++){if((await Bt(t))?.ok)return!0;await t.wait({time:r/1000})}}return!1}async function jt(t,e,r){e=String(e).replace(/\\n/g,`
273
+ `);if(!(await Rt(t))?.ok)throw new u(`文字配图: could not focus card editor #${r+1}`);if(typeof t.insertText==="function"){const i=e.split(`
274
+ `);for(let a=0;a<i.length;a++){if(a>0&&typeof t.pressKey==="function")await t.pressKey("Enter");if(i[a])await z(t,i[a])}}else await t.evaluate(`(t => document.execCommand('insertText', false, t))(${JSON.stringify(e)})`);await t.wait({time:0.4});if(!(await qt(t))?.ok)throw new u(`文字配图: card editor #${r+1} is empty after typing`)}async function Jt(t,e){if(!e||e===k)return k;const r=_(await t.evaluate(`
275
275
  (async () => {
276
276
  const __opencli_xhs_card_styles = true;
277
277
  const want = ${JSON.stringify(e)};
@@ -300,39 +300,20 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
300
300
  }
301
301
  return { ok: seen.length > 0, styles: seen, found: false };
302
302
  })()
303
- `));if(!r?.found)throw new u(`文字配图: requested style "${e}" is not available for this content (options: ${(r?.styles||[]).join(" / ")||"none"}). Choose an available style or omit --card-style to use ${k}.`);if(!(await E(t,e))?.ok)throw new u(`文字配图: could not click requested style "${e}".`);await t.wait({time:0.6});return e}async function at(t){const e=await t.evaluate(`
303
+ `));if(!r?.found)throw new u(`文字配图: requested style "${e}" is not available for this content (options: ${(r?.styles||[]).join(" / ")||"none"}). Choose an available style or omit --card-style to use ${k}.`);if(!(await A(t,e))?.ok)throw new u(`文字配图: could not click requested style "${e}".`);await t.wait({time:0.6});return e}async function at(t){const e=await t.evaluate(`
304
304
  (() => {
305
305
  const __opencli_xhs_composer_media_count = true;
306
- const visibleBox = (el) => {
306
+ const visible = (el) => {
307
307
  if (!el || el.offsetParent === null) return false;
308
308
  const r = el.getBoundingClientRect();
309
- return r.width > 0 && r.height > 0;
310
- };
311
- const visibleMedia = (el) => {
312
- if (!visibleBox(el)) return false;
313
- const r = el.getBoundingClientRect();
314
309
  return r.width >= 48 && r.height >= 48;
315
310
  };
316
- const titleSelectors = ${JSON.stringify(J)};
317
- const titleEl = titleSelectors
318
- .map((sel) => Array.from(document.querySelectorAll(sel)))
319
- .flat()
320
- .find((el) => visibleBox(el));
321
- const root = titleEl?.closest('form, [class*="publish"], [class*="editor"], [class*="note"]') || document.body;
322
- const seen = new Set();
323
- let count = 0;
324
- for (const el of Array.from(root.querySelectorAll('img, video, canvas, [style*="background-image"]'))) {
325
- if (!visibleMedia(el)) continue;
326
- const rect = el.getBoundingClientRect();
327
- const src = el.currentSrc || el.src || el.getAttribute('src') || el.style?.backgroundImage || '';
328
- const key = src || String(Math.round(rect.left)) + ':' + String(Math.round(rect.top));
329
- if (seen.has(key)) continue;
330
- seen.add(key);
331
- count += 1;
332
- }
311
+ const count = Array.from(document.querySelectorAll('.img-container'))
312
+ .filter((card) => Array.from(card.querySelectorAll('img')).some(visible))
313
+ .length;
333
314
  return { ok: true, count };
334
315
  })()
335
- `);return _(e)}async function st(t,e,r){const n=await at(t);if(!n||typeof n.count!=="number")throw new u(`${r}: could not verify current composer media count`);if(n.count<e){await t.screenshot({path:"/tmp/xhs_publish_media_debug.png"});throw new u(`${r}: expected at least ${e} visible media item(s), got ${n.count}. Debug screenshot: /tmp/xhs_publish_media_debug.png`)}}async function Vt(t,e,r){if(!(await E(t,F))?.ok){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: could not click "${F}" entry. Debug: /tmp/xhs_publish_textimage_debug.png`)}if(!await Ot(t)){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: 写文字 card editor did not appear after clicking "${F}". Debug: /tmp/xhs_publish_textimage_debug.png`)}for(let l=0;l<e.length;l++){if(l>0){if(!await Bt(t,l+1)){await t.screenshot({path:"/tmp/xhs_publish_addcard_debug.png"});throw new u(`文字配图: new card editor #${l+1} did not render after "${W}". Debug: /tmp/xhs_publish_addcard_debug.png`)}}await Jt(t,e[l],l)}if(!await Ut(t)){await t.screenshot({path:"/tmp/xhs_publish_generate_debug.png"});throw new u(`文字配图: "${Q}" did not advance to the 预览图片 step. `+"Debug: /tmp/xhs_publish_generate_debug.png")}const i=await jt(t,r);if(!(await E(t,Z))?.ok){await t.screenshot({path:"/tmp/xhs_publish_next_debug.png"});throw new u(`文字配图: could not click "${Z}". Debug: /tmp/xhs_publish_next_debug.png`)}await t.wait({time:2});return i}async function lt(t){return t.evaluate(`
316
+ `);return _(e)}async function st(t,e,r){const n=await at(t);if(!n||typeof n.count!=="number")throw new u(`${r}: could not verify current composer media count`);if(n.count<e){await t.screenshot({path:"/tmp/xhs_publish_media_debug.png"});throw new u(`${r}: expected at least ${e} visible media item(s), got ${n.count}. Debug screenshot: /tmp/xhs_publish_media_debug.png`)}}async function Vt(t,e,r){if(!(await A(t,B))?.ok){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: could not click "${B}" entry. Debug: /tmp/xhs_publish_textimage_debug.png`)}if(!await Lt(t)){await t.screenshot({path:"/tmp/xhs_publish_textimage_debug.png"});throw new u(`文字配图: 写文字 card editor did not appear after clicking "${B}". Debug: /tmp/xhs_publish_textimage_debug.png`)}for(let l=0;l<e.length;l++){if(l>0){if(!await Ft(t,l+1)){await t.screenshot({path:"/tmp/xhs_publish_addcard_debug.png"});throw new u(`文字配图: new card editor #${l+1} did not render after "${K}". Debug: /tmp/xhs_publish_addcard_debug.png`)}}await jt(t,e[l],l)}if(!await Ut(t)){await t.screenshot({path:"/tmp/xhs_publish_generate_debug.png"});throw new u(`文字配图: "${W}" did not advance to the 预览图片 step. `+"Debug: /tmp/xhs_publish_generate_debug.png")}const i=await Jt(t,r);if(!(await A(t,Q))?.ok){await t.screenshot({path:"/tmp/xhs_publish_next_debug.png"});throw new u(`文字配图: could not click "${Q}". Debug: /tmp/xhs_publish_next_debug.png`)}await t.wait({time:2});return i}async function lt(t){return t.evaluate(`
336
317
  () => {
337
318
  const text = (document.body?.innerText || '').replace(/s+/g, ' ').trim();
338
319
  const hasTitleInput = !!Array.from(document.querySelectorAll('input, textarea')).find((el) => {
@@ -364,7 +345,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
364
345
  }
365
346
  `)}async function zt(t,e=5000){const r=500,n=Math.max(1,Math.ceil(e/r));let o=await lt(t);for(let i=0;i<n;i++){if(o.state!=="video_surface")return o;if(i<n-1){await t.wait({time:r/1000});o=await lt(t)}}return o}async function Ht(t,e=1e4){const r=1000,n=Math.ceil(e/r);for(let o=0;o<n;o++){if(await t.evaluate(`
366
347
  (() => {
367
- const sels = ${JSON.stringify(J)};
348
+ const sels = ${JSON.stringify(Z)};
368
349
  for (const sel of sels) {
369
350
  const el = document.querySelector(sel);
370
351
  if (el && el.offsetParent !== null) return true;
@@ -408,7 +389,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
408
389
  }
409
390
  return removed;
410
391
  })(${JSON.stringify(e)})
411
- `));return Number(r)||0}function Gt(t){const e=String(t&&(t.url||t.key)||""),r=String(t&&t.method||"").toUpperCase(),n=Number(t&&t.status||0);if(r!=="PUT")return null;if(!/ros-upload[^/]*\/spectrum\//.test(e))return null;if(n<200||n>=300)return null;const o=e.match(/\/spectrum\/([^?#]+)/);return o?o[1]:e}function ut(t){return Math.min(45,6+t*4)}async function dt(t,e,r,n=90000){if(e<=0)return{ok:!0,completed:0};if(!r||typeof t.readNetworkCapture!=="function"){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}const o=1500,a=Math.ceil(9000/o),l=Math.ceil(n/o),s=new Set;for(let d=0;d<l;d++){const w=await t.readNetworkCapture().catch(()=>[]);for(const v of Array.isArray(w)?w:[]){const m=Gt(v);if(m)s.add(m)}if(s.size>=e)return{ok:!0,completed:s.size};if(d>=a&&s.size===0){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}await t.wait({time:o/1000})}return{ok:!1,completed:s.size}}const j=3;export function pickPublishedNote(t,e,r=Date.now()){const n=String(e||"").trim();return(Array.isArray(t)?t:[]).filter((i)=>!i.sticky).slice(0,j).find((i)=>{const a=String(i.title||"").trim();if(!a||!(a===n||a.startsWith(n)||n.startsWith(a)))return!1;const l=String(i.time||"").match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/);if(!l)return!0;const s=Date.UTC(Number(l[1]),Number(l[2])-1,Number(l[3]),Number(l[4]),Number(l[5]))-28800000;return Math.abs(r-s)<=93600000})??null}async function Yt(t,e,r){let n="";for(let o=0;o<r;o++){if(o>0)await t.wait({time:3});let i;try{i=await Et(t,{tab:"all",limit:j+5})}catch(l){return{note:null,reason:`创作者后台笔记列表读取出错:${l?.message??String(l)}`}}const a=pickPublishedNote(i.notes,e);if(a)return{note:a,reason:""};n=i.notes.length===0?"创作者后台笔记列表为空":`创作者后台最新 ${Math.min(i.notes.length,j)} 条笔记里没有同标题笔记`}return{note:null,reason:n}}xt({site:"xiaohongshu",name:"publish",access:"write",description:"小红书发布图文笔记 (creator center UI automation)",domain:"creator.xiaohongshu.com",strategy:yt.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"content",required:!1,positional:!0,help:"笔记正文(字面文本,不会展开 @文件 引用;长正文建议用 --file)"},{name:"file",required:!1,help:"从本机文件读取笔记正文(UTF-8),与位置参数 <content> 二选一"},{name:"title",required:!0,help:"笔记标题 (最多20字)"},{name:"images",required:!1,help:`图片路径,逗号分隔,最多${B}张 (jpg/png/gif/webp)`},{name:"card-text",required:!1,help:`文字配图卡片文字,多张卡片用 ${Y} 分隔,卡内换行用 \\n`},{name:"card-style",required:!1,help:`文字配图卡片样式,运行时按页面实际选项匹配;找不到会失败。省略时使用${k}。可选: ${K.map(([t,e])=>`${t}(${e})`).join(" ")}`},{name:"topics",required:!1,help:"话题名称,逗号分隔,最多10个;先用 topics 查询。无法准确选中时停止提交"},mt,{name:"draft",type:"bool",default:!1,help:"保存为草稿,不直接发布"},{name:"timeout",type:"int",default:300,help:"整段发布流程的等待预算(秒);超时后先用 creator-notes 回查,勿直接重复发布"},{name:"ai-generated",type:"boolean",help:"声明内容由 AI 生成(发布和草稿均支持;设置失败时停止提交)"},...wt],columns:["status","detail","url"],func:async(t,e)=>{gt(e);if(!t)throw Error("Browser page required");const r=String(e.title??"").trim(),n=e.file?String(e.file).trim():"";let o=String(e.content??"").trim();if(n){if(o)throw new b("正文位置参数和 --file 只能二选一,不能同时给");const c=N.resolve(n);if(!L.existsSync(c))throw new b(`--file 指向的文件不存在: ${c}`);o=L.readFileSync(c,"utf-8").trim();if(!o)throw new b(`--file 指向的文件内容为空: ${c}`)}const i=e.images?String(e.images).split(",").map((c)=>c.trim()).filter(Boolean):[],a=pt(e),l=a.map((c)=>c.name),s=Boolean(e.draft),d=e["card-text"]?String(e["card-text"]):"",w=d?d.split(Y).map((c)=>c.trim()).filter(Boolean):[],v=e["card-style"]?String(e["card-style"]).trim():"",m=w.length>0;if(!r)throw new b("--title is required");if(r.length>X)throw new b(`Title is ${r.length} chars — must be ≤ ${X}`);if(!o)throw new b("缺少笔记正文:给位置参数 <content>(字面文本),或用 --file <本机文件路径>");vt(o,{fileFlag:"--file"});if(!m&&i.length===0)throw new b("Provide --card-text (text-image mode) or --images (upload mode); neither was given.");if(i.length>B)throw new b(`Too many images: ${i.length} (max ${B})`);if(m&&i.some((c)=>N.extname(c).toLowerCase()===".gif"))throw new b("文字配图模式追加的图片不支持 .gif(编辑器图片入口只接受 jpg/jpeg/png/webp)");const f=Nt(i);await t.goto($t);await t.wait({time:1});await t.evaluate("() => { try { window.onbeforeunload = null; } catch (e) {} location.reload(); }").catch(()=>{return});let x="";for(let c=0;c<30;c++){await t.wait({time:0.5});x=await t.evaluate("() => location.href");if(x.includes("creator.xiaohongshu.com"))break}if(!x.includes("creator.xiaohongshu.com")){await t.screenshot({path:"/tmp/xhs_publish_redirect_debug.png"});throw Error(`Redirected away from creator center (landed on ${x}) — session may have expired. `+"Re-capture browser login via: ppcli xiaohongshu creator-profile. Debug screenshot: /tmp/xhs_publish_redirect_debug.png")}const S=await Rt(t);if((await zt(t,S?.ok?5000:2000)).state==="video_surface"){await t.screenshot({path:"/tmp/xhs_publish_tab_debug.png"});const c=S?.ok?`clicked "${S.text}"`:`visible candidates: ${(S?.visibleTexts||[]).join(" | ")||"none"}`;throw Error("Still on the video publish page after trying to select 图文. "+`Details: ${c}. Debug screenshot: /tmp/xhs_publish_tab_debug.png`)}const A=await Xt(t);let C=v;if(m)C=await Vt(t,w,v);else{const c=typeof t.startNetworkCapture==="function"?await t.startNetworkCapture("").catch(()=>!1):!1,g=await nt(t,f);if(!g.ok){await t.screenshot({path:"/tmp/xhs_publish_upload_debug.png"});throw new u(`图片注入失败:${g.error??"unknown"}。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_upload_debug.png")}await t.wait({time:G/1000});const y=await dt(t,f.length,c);if(!y.ok){await t.screenshot({path:"/tmp/xhs_publish_upload_debug.png"});throw new u(`图片上传未全部完成:只确认 ${y.completed}/${f.length} 张传到小红书 CDN,`+"继续发布会丢图(通常只剩封面)。直接重新运行本 publish 命令即可(会自动重置发布页重传);"+"请勿手动修改当前页面。Debug: /tmp/xhs_publish_upload_debug.png")}await rt(t);if(A.length){await ct(t,A);await t.wait({time:0.5})}const M=await at(t);if(M&&typeof M.count==="number"&&M.count>f.length){await t.screenshot({path:"/tmp/xhs_publish_dup_debug.png"});throw new u(`清掉恢复态旧图后编辑器内仍有 ${M.count} 张图,超过本次注入的 ${f.length} 张。`+"直接重新运行本 publish 命令即可(会自动重置发布页);请勿手动修改当前页面。Debug: /tmp/xhs_publish_dup_debug.png")}}if(!await Ht(t)){await t.screenshot({path:"/tmp/xhs_publish_form_debug.png"});throw new u("Editing form did not appear after image acquisition. The page layout may have changed. Debug screenshot: /tmp/xhs_publish_form_debug.png")}if(m)await st(t,w.length,"文字配图 generated images");if(m&&f.length>0){const c=typeof t.startNetworkCapture==="function"?await t.startNetworkCapture("").catch(()=>!1):!1,g=await nt(t,f);if(!g.ok){await t.screenshot({path:"/tmp/xhs_publish_append_debug.png"});throw new u(`追加图片失败:${g.error??"unknown"}。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_append_debug.png")}await t.wait({time:G/1000});const y=await dt(t,f.length,c);if(!y.ok){await t.screenshot({path:"/tmp/xhs_publish_append_debug.png"});throw new u(`追加图片上传未全部完成:只确认 ${y.completed}/${f.length} 张传到小红书 CDN。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_append_debug.png")}await rt(t);await st(t,w.length+f.length,"文字配图 appended images")}if(m&&A.length){await ct(t,A);await t.wait({time:0.5})}await ot(t,J,r,"title");await I(t,0.6);await ot(t,tt,o,"content");await I(t,0.6);let P=[];if(l.length)P=await bt(t,tt,a);await _t(t,e);await I(t,1,0.6);const R=await kt(t,["xhs-publish-btn"]);if(R){await Tt(t,R.x,R.y);await I(t,0.4)}const V=s?["暂存离开","存草稿"]:["发布","发布笔记"],h=await t.evaluate(`
392
+ `));return Number(r)||0}function Gt(t){const e=String(t&&(t.url||t.key)||""),r=String(t&&t.method||"").toUpperCase(),n=Number(t&&t.status||0);if(r!=="PUT")return null;if(!/ros-upload[^/]*\/spectrum\//.test(e))return null;if(n<200||n>=300)return null;const o=e.match(/\/spectrum\/([^?#]+)/);return o?o[1]:e}function ut(t){return Math.min(45,6+t*4)}async function dt(t,e,r,n=90000){if(e<=0)return{ok:!0,completed:0};if(!r||typeof t.readNetworkCapture!=="function"){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}const o=1500,a=Math.ceil(9000/o),l=Math.ceil(n/o),s=new Set;for(let d=0;d<l;d++){const w=await t.readNetworkCapture().catch(()=>[]);for(const v of Array.isArray(w)?w:[]){const m=Gt(v);if(m)s.add(m)}if(s.size>=e)return{ok:!0,completed:s.size};if(d>=a&&s.size===0){await t.wait({time:ut(e)});return{ok:!0,completed:null,viaFallback:!0}}await t.wait({time:o/1000})}return{ok:!1,completed:s.size}}const j=3;export function pickPublishedNote(t,e,r=Date.now()){const n=String(e||"").trim();return(Array.isArray(t)?t:[]).filter((i)=>!i.sticky).slice(0,j).find((i)=>{const a=String(i.title||"").trim();if(!a||!(a===n||a.startsWith(n)||n.startsWith(a)))return!1;const l=String(i.time||"").match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/);if(!l)return!0;const s=Date.UTC(Number(l[1]),Number(l[2])-1,Number(l[3]),Number(l[4]),Number(l[5]))-28800000;return Math.abs(r-s)<=93600000})??null}async function Yt(t,e,r){let n="";for(let o=0;o<r;o++){if(o>0)await t.wait({time:3});let i;try{i=await $t(t,{tab:"all",limit:j+5})}catch(l){return{note:null,reason:`创作者后台笔记列表读取出错:${l?.message??String(l)}`}}const a=pickPublishedNote(i.notes,e);if(a)return{note:a,reason:""};n=i.notes.length===0?"创作者后台笔记列表为空":`创作者后台最新 ${Math.min(i.notes.length,j)} 条笔记里没有同标题笔记`}return{note:null,reason:n}}xt({site:"xiaohongshu",name:"publish",access:"write",description:"小红书发布图文笔记 (creator center UI automation)",domain:"creator.xiaohongshu.com",strategy:yt.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"content",required:!1,positional:!0,help:"笔记正文(字面文本,不会展开 @文件 引用;长正文建议用 --file)"},{name:"file",required:!1,help:"从本机文件读取笔记正文(UTF-8),与位置参数 <content> 二选一"},{name:"title",required:!0,help:"笔记标题 (最多20字)"},{name:"images",required:!1,help:`图片路径,逗号分隔,最多${F}张 (jpg/png/gif/webp)`},{name:"card-text",required:!1,help:`文字配图卡片文字,多张卡片用 ${G} 分隔,卡内换行用 \\n`},{name:"card-style",required:!1,help:`文字配图卡片样式,运行时按页面实际选项匹配;找不到会失败。省略时使用${k}。可选: ${Y.map(([t,e])=>`${t}(${e})`).join(" ")}`},{name:"topics",required:!1,help:"话题名称,逗号分隔,最多10个;先用 topics 查询。无法准确选中时停止提交"},mt,{name:"draft",type:"bool",default:!1,help:"保存为草稿,不直接发布"},{name:"timeout",type:"int",default:300,help:"整段发布流程的等待预算(秒);超时后先用 creator-notes 回查,勿直接重复发布"},{name:"ai-generated",type:"boolean",help:"声明内容由 AI 生成(发布和草稿均支持;设置失败时停止提交)"},...wt],columns:["status","detail","url"],func:async(t,e)=>{gt(e);if(!t)throw Error("Browser page required");const r=String(e.title??"").trim(),n=e.file?String(e.file).trim():"";let o=String(e.content??"").trim();if(n){if(o)throw new b("正文位置参数和 --file 只能二选一,不能同时给");const c=N.resolve(n);if(!O.existsSync(c))throw new b(`--file 指向的文件不存在: ${c}`);o=O.readFileSync(c,"utf-8").trim();if(!o)throw new b(`--file 指向的文件内容为空: ${c}`)}const i=e.images?String(e.images).split(",").map((c)=>c.trim()).filter(Boolean):[],a=pt(e),l=a.map((c)=>c.name),s=Boolean(e.draft),d=e["card-text"]?String(e["card-text"]):"",w=d?d.split(G).map((c)=>c.trim()).filter(Boolean):[],v=e["card-style"]?String(e["card-style"]).trim():"",m=w.length>0;if(!r)throw new b("--title is required");if(r.length>H)throw new b(`Title is ${r.length} chars — must be ≤ ${H}`);if(!o)throw new b("缺少笔记正文:给位置参数 <content>(字面文本),或用 --file <本机文件路径>");vt(o,{fileFlag:"--file"});if(!m&&i.length===0)throw new b("Provide --card-text (text-image mode) or --images (upload mode); neither was given.");if(i.length>F)throw new b(`Too many images: ${i.length} (max ${F})`);if(m&&i.some((c)=>N.extname(c).toLowerCase()===".gif"))throw new b("文字配图模式追加的图片不支持 .gif(编辑器图片入口只接受 jpg/jpeg/png/webp)");const f=Nt(i);await t.goto(At);await t.wait({time:1});await t.evaluate("() => { try { window.onbeforeunload = null; } catch (e) {} location.reload(); }").catch(()=>{return});let x="";for(let c=0;c<30;c++){await t.wait({time:0.5});x=await t.evaluate("() => location.href");if(x.includes("creator.xiaohongshu.com"))break}if(!x.includes("creator.xiaohongshu.com")){await t.screenshot({path:"/tmp/xhs_publish_redirect_debug.png"});throw Error(`Redirected away from creator center (landed on ${x}) — session may have expired. `+"Re-capture browser login via: ppcli xiaohongshu creator-profile. Debug screenshot: /tmp/xhs_publish_redirect_debug.png")}const S=await Dt(t);if((await zt(t,S?.ok?5000:2000)).state==="video_surface"){await t.screenshot({path:"/tmp/xhs_publish_tab_debug.png"});const c=S?.ok?`clicked "${S.text}"`:`visible candidates: ${(S?.visibleTexts||[]).join(" | ")||"none"}`;throw Error("Still on the video publish page after trying to select 图文. "+`Details: ${c}. Debug screenshot: /tmp/xhs_publish_tab_debug.png`)}const E=await Xt(t);let C=v;if(m)C=await Vt(t,w,v);else{const c=typeof t.startNetworkCapture==="function"?await t.startNetworkCapture("").catch(()=>!1):!1,g=await nt(t,f);if(!g.ok){await t.screenshot({path:"/tmp/xhs_publish_upload_debug.png"});throw new u(`图片注入失败:${g.error??"unknown"}。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_upload_debug.png")}await t.wait({time:X/1000});const y=await dt(t,f.length,c);if(!y.ok){await t.screenshot({path:"/tmp/xhs_publish_upload_debug.png"});throw new u(`图片上传未全部完成:只确认 ${y.completed}/${f.length} 张传到小红书 CDN,`+"继续发布会丢图(通常只剩封面)。直接重新运行本 publish 命令即可(会自动重置发布页重传);"+"请勿手动修改当前页面。Debug: /tmp/xhs_publish_upload_debug.png")}await rt(t);if(E.length){await ct(t,E);await t.wait({time:0.5})}const M=await at(t);if(M&&typeof M.count==="number"&&M.count>f.length){await t.screenshot({path:"/tmp/xhs_publish_dup_debug.png"});throw new u(`清掉恢复态旧图后编辑器内仍有 ${M.count} 张图,超过本次注入的 ${f.length} 张。`+"直接重新运行本 publish 命令即可(会自动重置发布页);请勿手动修改当前页面。Debug: /tmp/xhs_publish_dup_debug.png")}}if(!await Ht(t)){await t.screenshot({path:"/tmp/xhs_publish_form_debug.png"});throw new u("Editing form did not appear after image acquisition. The page layout may have changed. Debug screenshot: /tmp/xhs_publish_form_debug.png")}if(m)await st(t,w.length,"文字配图 generated images");if(m&&f.length>0){const c=typeof t.startNetworkCapture==="function"?await t.startNetworkCapture("").catch(()=>!1):!1,g=await nt(t,f);if(!g.ok){await t.screenshot({path:"/tmp/xhs_publish_append_debug.png"});throw new u(`追加图片失败:${g.error??"unknown"}。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_append_debug.png")}await t.wait({time:X/1000});const y=await dt(t,f.length,c);if(!y.ok){await t.screenshot({path:"/tmp/xhs_publish_append_debug.png"});throw new u(`追加图片上传未全部完成:只确认 ${y.completed}/${f.length} 张传到小红书 CDN。`+"直接重新运行本 publish 命令即可(会自动重置发布页重传);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_append_debug.png")}await rt(t);await st(t,w.length+f.length,"文字配图 appended images")}if(m&&E.length){await ct(t,E);await t.wait({time:0.5})}await ot(t,Z,r,"title");await I(t,0.6);await ot(t,tt,o,"content");await I(t,0.6);let P=[];if(l.length)P=await bt(t,tt,a);await _t(t,e);await I(t,1,0.6);const D=await kt(t,["xhs-publish-btn"]);if(D){await Tt(t,D.x,D.y);await I(t,0.4)}const J=s?["暂存离开","存草稿"]:["发布","发布笔记"],h=await t.evaluate(`
412
393
  (cfg => {
413
394
  const { isDraftMode, publishNames, draftNames, labels } = cfg;
414
395
  const isVisible = (el) => {
@@ -447,7 +428,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
447
428
  }
448
429
  }
449
430
  return { ok: false, via: 'none', hosts: hosts.length, lastMethodError };
450
- })(${JSON.stringify({isDraftMode:s,publishNames:At,draftNames:Ct,labels:V})})
431
+ })(${JSON.stringify({isDraftMode:s,publishNames:Et,draftNames:Ct,labels:J})})
451
432
  `);if(!h?.ok){if(s){if(await t.evaluate(`
452
433
  (() => {
453
434
  const labels = ['返回', '关闭', '取消', '离开'];
@@ -486,7 +467,7 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
486
467
  }
487
468
  return false;
488
469
  }
489
- `)){h.ok=!0;h.via="auto-save"}}}}if(!h?.ok){await t.screenshot({path:"/tmp/xhs_publish_submit_debug.png"});const c=h?.via?` (via=${h.via})`:"",g=h?.error?`, error=${h.error}`:"",y=h?.lastMethodError?`, lastMethodError=${h.lastMethodError}`:"";throw Error(`未能触发「${V[0]}」按钮${c}${g}${y}。`+"直接重新运行本 publish 命令即可(会自动重置发布页);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_submit_debug.png")}await t.wait({time:4});const T=await t.evaluate("() => location.href"),ft=s?["草稿已保存","暂存成功","保存成功","保存于","图文笔记("]:["发布成功","上传成功"],z=await t.evaluate(`
470
+ `)){h.ok=!0;h.via="auto-save"}}}}if(!h?.ok){await t.screenshot({path:"/tmp/xhs_publish_submit_debug.png"});const c=h?.via?` (via=${h.via})`:"",g=h?.error?`, error=${h.error}`:"",y=h?.lastMethodError?`, lastMethodError=${h.lastMethodError}`:"";throw Error(`未能触发「${J[0]}」按钮${c}${g}${y}。`+"直接重新运行本 publish 命令即可(会自动重置发布页);请勿手动修改当前页面。"+"Debug: /tmp/xhs_publish_submit_debug.png")}await t.wait({time:4});const T=await t.evaluate("() => location.href"),ft=s?["草稿已保存","暂存成功","保存成功","保存于","图文笔记("]:["发布成功","上传成功"],V=await t.evaluate(`
490
471
  (markers => {
491
472
  for (const el of document.querySelectorAll('*')) {
492
473
  if (el.tagName === 'STYLE' || el.tagName === 'SCRIPT') continue;
@@ -496,4 +477,4 @@ import{TOPIC_ID_ARG as mt,parseTopics as pt,attachTopics as bt}from"./_shared/to
496
477
  }
497
478
  return '';
498
479
  })(${JSON.stringify(ft)})
499
- `),ht=!T.includes("/publish/publish");let D=z.length>0||ht;const q=s?"暂存成功":"发布成功";let p=null,O="";if(!s){const c=await Yt(t,r,D?2:4);p=c.note;O=c.reason;if(p)D=!0}if(!D){if(s)throw new u(`${q}无法确认:未观察到成功提示或提交后跳转。`+(T?`当前 URL: ${T}。`:"当前 URL 为空。")+"先用 `xiaohongshu drafts` 查草稿箱确认是否已存上;确认没有再重新运行本命令,避免堆出重复草稿。");throw new u(`${q}无法确认:未观察到成功提示或提交后跳转,创作者后台也暂未查到同标题笔记(${O||"未回查到"})。`+(T?`当前 URL: ${T}。`:"")+"注意:发布按钮已被触发,笔记仍可能延迟入库。禁止立即重发——请等 1-2 分钟后用 `xiaohongshu creator-notes` 回查本篇标题是否已出现;确认不存在后才重新运行本 publish 命令,否则会重复发布。")}return[{status:`✅ ${q}`,detail:[`"${r}"`,m?`${w.length}张文字配图${f.length?` + ${f.length}张图片`:""}${C&&C!==k?` (${C})`:""}`:`${f.length}张图片`,P.length?`话题: ${P.join(" ")}`:"",p?.id?`笔记ID: ${p.id}`:"",z||(p?"已在创作者后台确认":"")||T||"",p?.id?p.noteUrl?"链接需登录小红书后打开":"链接为创作者后台数据页,需登录":"",!s&&!p?.id?`未回查到笔记ID(${O||"未回查到"}),稍后用 creator-notes 按标题查`:""].filter(Boolean).join(" · "),url:p?.id?p.noteUrl||`https://creator.xiaohongshu.com/statistics/note-detail?noteId=${p.id}`:""}]}});
480
+ `),ht=!T.includes("/publish/publish");let R=V.length>0||ht;const q=s?"暂存成功":"发布成功";let p=null,L="";if(!s){const c=await Yt(t,r,R?2:4);p=c.note;L=c.reason;if(p)R=!0}if(!R){if(s)throw new u(`${q}无法确认:未观察到成功提示或提交后跳转。`+(T?`当前 URL: ${T}。`:"当前 URL 为空。")+"先用 `xiaohongshu drafts` 查草稿箱确认是否已存上;确认没有再重新运行本命令,避免堆出重复草稿。");throw new u(`${q}无法确认:未观察到成功提示或提交后跳转,创作者后台也暂未查到同标题笔记(${L||"未回查到"})。`+(T?`当前 URL: ${T}。`:"")+"注意:发布按钮已被触发,笔记仍可能延迟入库。禁止立即重发——请等 1-2 分钟后用 `xiaohongshu creator-notes` 回查本篇标题是否已出现;确认不存在后才重新运行本 publish 命令,否则会重复发布。")}return[{status:`✅ ${q}`,detail:[`"${r}"`,m?`${w.length}张文字配图${f.length?` + ${f.length}张图片`:""}${C&&C!==k?` (${C})`:""}`:`${f.length}张图片`,P.length?`话题: ${P.join(" ")}`:"",p?.id?`笔记ID: ${p.id}`:"",V||(p?"已在创作者后台确认":"")||T||"",p?.id?p.noteUrl?"链接需登录小红书后打开":"链接为创作者后台数据页,需登录":"",!s&&!p?.id?`未回查到笔记ID(${L||"未回查到"}),稍后用 creator-notes 按标题查`:""].filter(Boolean).join(" · "),url:p?.id?p.noteUrl||`https://creator.xiaohongshu.com/statistics/note-detail?noteId=${p.id}`:""}]}});
@@ -48,6 +48,8 @@ export interface RunExtractOptions {
48
48
  selector: string | null;
49
49
  start: number;
50
50
  chunkSize: number;
51
+ /** Keep only markdown lines matching this case-insensitive regex (before chunking). */
52
+ grep?: string | null;
51
53
  }
52
54
  export interface RunExtractResult {
53
55
  url: string;
@@ -59,6 +61,11 @@ export interface RunExtractResult {
59
61
  end: number;
60
62
  next_start_char: number | null;
61
63
  content: string;
64
+ /** Present only with `--grep`: the pattern, matched / total line counts, and the unfiltered page length. */
65
+ grep?: string;
66
+ matched_lines?: number;
67
+ total_lines?: number;
68
+ page_chars?: number;
62
69
  }
63
70
  /** End-to-end host-side pipeline: HTML → markdown → chunked envelope. */
64
71
  export declare function runExtractFromHtml(opts: RunExtractOptions): RunExtractResult;
@@ -1,5 +1,5 @@
1
- import{htmlToMarkdown as f}from"../utils.js";const u=20000,d=100,m=200000,S=0.15;export function buildExtractHtmlJs(e){return`(() => {
2
- const sel = ${e?JSON.stringify(e):"null"};
1
+ import{htmlToMarkdown as f}from"../utils.js";const d=20000,h=100,m=200000,g=0.15;export function buildExtractHtmlJs(t){return`(() => {
2
+ const sel = ${t?JSON.stringify(t):"null"};
3
3
  let root = null;
4
4
  if (sel) {
5
5
  try { root = document.querySelector(sel); }
@@ -36,7 +36,9 @@ import{htmlToMarkdown as f}from"../utils.js";const u=20000,d=100,m=200000,S=0.15
36
36
  n = walker.nextNode();
37
37
  }
38
38
  return { ok: true, url: location.href, title: document.title || '', html: clone.outerHTML || '' };
39
- })()`}export function chunkMarkdown(e){const{content:n,start:t}=e,l=Math.max(d,Math.min(m,e.chunkSize));if(t>=n.length)return{content:"",start:t,end:t,nextStartChar:null};const r=Math.min(n.length,t+l);if(r===n.length)return{content:n.slice(t,r),start:t,end:r,nextStartChar:null};const h=Math.max(1,Math.floor(l*S)),a=Math.max(t+1,r-h),c=n.slice(a,r),s=c.lastIndexOf(`
39
+ })()`}export function chunkMarkdown(t){const{content:r,start:e}=t,a=Math.max(h,Math.min(m,t.chunkSize));if(e>=r.length)return{content:"",start:e,end:e,nextStartChar:null};const n=Math.min(r.length,e+a);if(n===r.length)return{content:r.slice(e,n),start:e,end:n,nextStartChar:null};const s=Math.max(1,Math.floor(a*g)),o=Math.max(e+1,n-s),c=r.slice(o,n),l=c.lastIndexOf(`
40
40
 
41
- `);let o=r;if(s>=0)o=a+s+2;else{const i=c.lastIndexOf(`
42
- `);if(i>=0)o=a+i+1}return{content:n.slice(t,o),start:t,end:o,nextStartChar:o}}export function runExtractFromHtml(e){const n=f(e.html),t=chunkMarkdown({content:n,start:Math.max(0,e.start),chunkSize:e.chunkSize||u});return{url:e.url,title:e.title,selector:e.selector,total_chars:n.length,chunk_size:t.end-t.start,start:t.start,end:t.end,next_start_char:t.nextStartChar,content:t.content}}export const __extractInternals={DEFAULT_CHUNK_SIZE:u,MIN_CHUNK_SIZE:d,MAX_CHUNK_SIZE:m};
41
+ `);let i=n;if(l>=0)i=o+l+2;else{const u=c.lastIndexOf(`
42
+ `);if(u>=0)i=o+u+1}return{content:r.slice(e,i),start:e,end:i,nextStartChar:i}}export function runExtractFromHtml(t){const r=f(t.html);let e=r,a={};if(t.grep){const s=new RegExp(t.grep,"i"),o=r.split(`
43
+ `).filter((l)=>l.trim().length>0),c=o.filter((l)=>s.test(l));e=c.join(`
44
+ `);a={grep:t.grep,matched_lines:c.length,total_lines:o.length,page_chars:r.length}}const n=chunkMarkdown({content:e,start:Math.max(0,t.start),chunkSize:t.chunkSize||d});return{url:t.url,title:t.title,selector:t.selector,total_chars:e.length,chunk_size:n.end-n.start,start:n.start,end:n.end,next_start_char:n.nextStartChar,content:n.content,...a}}export const __extractInternals={DEFAULT_CHUNK_SIZE:d,MIN_CHUNK_SIZE:h,MAX_CHUNK_SIZE:m};