publishport-opencli 1.0.67 → 1.0.69

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
@@ -52701,6 +52701,13 @@
52701
52701
  "default": false,
52702
52702
  "required": false,
52703
52703
  "help": "Include nested replies (楼中楼)"
52704
+ },
52705
+ {
52706
+ "name": "replies-limit",
52707
+ "type": "int",
52708
+ "default": 3,
52709
+ "required": false,
52710
+ "help": "With --with-replies: max nested replies per top-level comment (default 3, 0 = all). Capped threads show replies_complete=false; read a whole thread with `replies <url> <root-id>`"
52704
52711
  }
52705
52712
  ],
52706
52713
  "columns": [
@@ -619,6 +619,27 @@ var PP = (function () {
619
619
  src = String(src || '');
620
620
  return src.indexOf('data:') === 0 ? 'data#' + src.length + '#' + src.slice(-32) : '';
621
621
  }
622
+ // 单张图片转存的时限与整段转存的总预算。页面内 fetch 没有自己的超时:上行被占满时
623
+ // 一张图能一直挂着,整条发布最终只剩外层「Runtime.evaluate 超时」,看不出卡在哪张图。
624
+ // 到点即把这张记为失败(请求本身无法撤回,迟到的结果直接丢弃),后续沿用「图片失败即
625
+ // 在提交前中止」的既有路径,报错逐张列出卡住的图。总预算给发布请求本身留出时间。
626
+ var IMAGE_TIMEOUT_MS = 40000;
627
+ var IMAGE_BUDGET_MS = 75000;
628
+ function imageDeadline(startedAt) {
629
+ return Math.min(IMAGE_TIMEOUT_MS, IMAGE_BUDGET_MS - (Date.now() - startedAt));
630
+ }
631
+ function withImageTimeout(run, ms) {
632
+ if (ms <= 0) return Promise.reject(new Error('图片转存总时长已超过 ' + Math.round(IMAGE_BUDGET_MS / 1000) + ' 秒,未开始上传这张图(常见原因是本机上行网络拥塞或平台图床无响应)'));
633
+ var timer;
634
+ return Promise.race([
635
+ Promise.resolve().then(run),
636
+ new Promise(function (_, reject) {
637
+ timer = setTimeout(function () {
638
+ reject(new Error('图片转存超时(' + Math.round(ms / 1000) + ' 秒内未完成,常见原因是本机上行网络拥塞或平台图床无响应)'));
639
+ }, ms);
640
+ }),
641
+ ]).then(function (v) { clearTimeout(timer); return v; }, function (e) { clearTimeout(timer); throw e; });
642
+ }
622
643
  function subst(v, src) {
623
644
  if (typeof v === 'string') return v.split('{src}').join(src);
624
645
  if (Array.isArray(v)) return v.map(function (x) { return subst(x, src); });
@@ -635,6 +656,7 @@ var PP = (function () {
635
656
  var xsrf = cookie('_xsrf');
636
657
  var cache = {};
637
658
  var out = content;
659
+ var startedAt = Date.now();
638
660
  for (var i = 0; i < refs.length; i++) {
639
661
  var ref = refs[i], src = ref.src;
640
662
  if (!src) continue;
@@ -643,36 +665,39 @@ var PP = (function () {
643
665
 
644
666
  if (!(src in cache)) {
645
667
  try {
646
- var bt = spec.bodyType || 'form';
647
- var headers = Object.assign({}, spec.headers || {});
648
- if (spec.xsrf && xsrf) headers['x-xsrftoken'] = xsrf;
649
- var body;
650
- if (bt === 'form') {
651
- headers['Content-Type'] = 'application/x-www-form-urlencoded';
652
- body = new URLSearchParams(subst(spec.body || {}, src));
653
- } else if (bt === 'json') {
654
- headers['Content-Type'] = 'application/json';
655
- body = JSON.stringify(subst(spec.body || {}, src));
656
- } else if (bt === 'binary-multipart') {
657
- var blob = await (await fetch(src, { credentials: 'omit' })).blob();
658
- var fd = new FormData();
659
- fd.append(spec.fileField || 'file', blob, uploadFileName(spec.fileName, src, blob.type));
660
- var extra = subst(spec.body || {}, src);
661
- for (var k in extra) if (Object.prototype.hasOwnProperty.call(extra, k)) fd.append(k, String(extra[k]));
662
- body = fd;
663
- } else {
664
- throw new Error('unknown bodyType: ' + bt);
665
- }
666
- var url = subst(spec.url, src);
667
- var resp = await fetch(url, { method: spec.method || 'POST', credentials: 'include', headers: headers, body: body });
668
- var txt = await resp.text();
669
- var json = null; try { json = JSON.parse(txt); } catch (e) {}
670
- if (!resp.ok) throw new Error('HTTP ' + resp.status + ' ' + txt.slice(0, 150));
671
- var biz = bizError(json);
672
- if (biz) throw new Error('图床返回业务错误: ' + biz);
673
- var newUrl = spec.responsePath ? pickPath(json, spec.responsePath) : (json && (json.url || json.src));
674
- if (!newUrl) throw new Error('no url in response: ' + txt.slice(0, 150));
675
- if (!isHttpUrl(newUrl)) throw new Error('图床返回的不是合法 URL: ' + String(newUrl).slice(0, 150));
668
+ var newUrl = await withImageTimeout(async function () {
669
+ var bt = spec.bodyType || 'form';
670
+ var headers = Object.assign({}, spec.headers || {});
671
+ if (spec.xsrf && xsrf) headers['x-xsrftoken'] = xsrf;
672
+ var body;
673
+ if (bt === 'form') {
674
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
675
+ body = new URLSearchParams(subst(spec.body || {}, src));
676
+ } else if (bt === 'json') {
677
+ headers['Content-Type'] = 'application/json';
678
+ body = JSON.stringify(subst(spec.body || {}, src));
679
+ } else if (bt === 'binary-multipart') {
680
+ var blob = await (await fetch(src, { credentials: 'omit' })).blob();
681
+ var fd = new FormData();
682
+ fd.append(spec.fileField || 'file', blob, uploadFileName(spec.fileName, src, blob.type));
683
+ var extra = subst(spec.body || {}, src);
684
+ for (var k in extra) if (Object.prototype.hasOwnProperty.call(extra, k)) fd.append(k, String(extra[k]));
685
+ body = fd;
686
+ } else {
687
+ throw new Error('unknown bodyType: ' + bt);
688
+ }
689
+ var url = subst(spec.url, src);
690
+ var resp = await fetch(url, { method: spec.method || 'POST', credentials: 'include', headers: headers, body: body });
691
+ var txt = await resp.text();
692
+ var json = null; try { json = JSON.parse(txt); } catch (e) {}
693
+ if (!resp.ok) throw new Error('HTTP ' + resp.status + ' ' + txt.slice(0, 150));
694
+ var biz = bizError(json);
695
+ if (biz) throw new Error('图床返回业务错误: ' + biz);
696
+ var newUrl = spec.responsePath ? pickPath(json, spec.responsePath) : (json && (json.url || json.src));
697
+ if (!newUrl) throw new Error('no url in response: ' + txt.slice(0, 150));
698
+ if (!isHttpUrl(newUrl)) throw new Error('图床返回的不是合法 URL: ' + String(newUrl).slice(0, 150));
699
+ return newUrl;
700
+ }, imageDeadline(startedAt));
676
701
  cache[src] = newUrl;
677
702
  report.uploaded.push({ src: src.slice(0, 120), key: refKey(src), url: newUrl });
678
703
  } catch (e) {
@@ -705,6 +730,7 @@ var PP = (function () {
705
730
 
706
731
  var cache = {};
707
732
  var out = content;
733
+ var startedAt = Date.now();
708
734
  for (var i = 0; i < refs.length; i++) {
709
735
  var ref = refs[i], src = ref.src;
710
736
  if (!src) continue;
@@ -713,7 +739,7 @@ var PP = (function () {
713
739
 
714
740
  if (!(src in cache)) {
715
741
  try {
716
- var res = await uploadFn(src);
742
+ var res = await withImageTimeout(function () { return uploadFn(src); }, imageDeadline(startedAt));
717
743
  var url = (res && typeof res === 'object') ? res.url : res;
718
744
  if (!url) throw new Error('uploadFn returned no url');
719
745
  var isRel = String(url).charAt(0) === '/' && String(url).charAt(1) !== '/';
@@ -1 +1 @@
1
- import*as B from"node:fs";import*as N from"node:path";import{cli as L,Strategy as F}from"@jackwener/opencli/registry";import{ArgumentError as w,AuthRequiredError as U,CommandExecutionError as v}from"@jackwener/opencli/errors";import{resolveVideoFile as D,resolveImageFile as z,videoTimeoutArg as J}from"../_shared/video-publish.js";import{setInputFiles as M}from"../_shared/file-inject.js";const O={bda2:{os:"upos",upcdn:"bda2",probe_version:20221109},bldsa:{os:"upos",upcdn:"bldsa",probe_version:20221109},qn:{os:"upos",upcdn:"qn",probe_version:20221109},ws:{os:"upos",upcdn:"ws",probe_version:20221109}},A="bda2",q=["SESSDATA","bili_jct","DedeUserID"],K="https://member.bilibili.com/platform/home",T="__pp_bili_video_input";export async function PP_RESOLVE_AI_STATEMENT(){try{const t=await fetch("https://member.bilibili.com/x/vupre/web/archive/pre?lang=cn",{credentials:"include"}),e=await t.json();if(!t.ok||e?.code!==0)return{error:`读取创作声明失败:HTTP ${t.status} / ${e?.message??e?.code}`};const n=e.data?.neutral_mark?.mark_list;if(!Array.isArray(n))return{error:"当前账号的投稿配置缺少创作声明列表"};const r=n.filter((o)=>o.content==="含AI生成内容");if(r.length!==1||!Number.isSafeInteger(r[0].id)||r[0].id<=0)return{error:"当前账号未返回唯一有效的“含AI生成内容”选项"};return{id:r[0].id,label:r[0].content}}catch(t){return{error:`读取创作声明失败:${t instanceof Error?t.message:String(t)}`}}}function V(t){var e=document.getElementById(t.inputId);if(!e||!e.files||!e.files[0])return{error:"文件未就绪(input 为空)"};var n=e.files[0],r=n.size,o=t.line;return async function(){try{var a=new URLSearchParams({profile:"ugcfx/bup",name:n.name,size:String(r),r:o.os,ssl:"0",version:"2.14.0",build:"2100400",upcdn:o.upcdn,probe_version:String(o.probe_version)}),i=await(await fetch("https://member.bilibili.com/preupload?"+a.toString(),{credentials:"include",headers:{Referer:"https://www.bilibili.com"}})).json();if(i.OK!==1)return{error:"preupload 失败:"+JSON.stringify(i)};var s="https:"+i.endpoint+"/"+String(i.upos_uri).replace(/^upos:\/\//,""),h=new URLSearchParams({uploads:"",output:"json",profile:"ugcfx/bup",filesize:String(r),partsize:String(i.chunk_size),biz_id:String(i.biz_id)}),m=await(await fetch(s+"?"+h.toString(),{method:"POST",headers:{"x-upos-auth":i.auth}})).json();if(m.OK!==1)return{error:"获取 upload_id 失败:"+JSON.stringify(m)};var g=Math.max(1,Math.ceil(r/i.chunk_size));return{url:s,auth:i.auth,uploadId:m.upload_id,chunkSize:i.chunk_size,bizId:i.biz_id,size:r,name:n.name,total:g}}catch(_){return{error:"preupload 异常:"+String(_&&_.message||_)}}}()}function H(t){var e=document.getElementById(t.inputId);if(!e||!e.files||!e.files[0])return{ok:!1,error:"文件丢失(页面可能已导航)"};var n=e.files[0],r=t.idx*t.chunkSize,o=n.slice(r,Math.min(r+t.chunkSize,t.size)),a=o.size,i=new URLSearchParams({partNumber:String(t.idx+1),uploadId:String(t.uploadId),chunk:String(t.idx),chunks:String(t.total),size:String(a),start:String(r),end:String(r+a),total:String(t.size)});return async function(){for(var s=0;s<5;s++){try{var h=await fetch(t.url+"?"+i.toString(),{method:"PUT",headers:{"x-upos-auth":t.auth},body:o});if(h.status<400){var m=await h.text();if(m==="MULTIPART_PUT_SUCCESS"||m==="")return{ok:!0}}}catch(g){}await new Promise(function(g){setTimeout(g,800*(s+1))})}return{ok:!1,error:"分块 "+t.idx+" 多次重试仍失败"}}()}function G(t){var e=[];for(var n=1;n<=t.total;n++)e.push({partNumber:n,eTag:"etag"});var r=new URLSearchParams({output:"json",name:t.name,profile:"ugcfx/bup",uploadId:String(t.uploadId),biz_id:String(t.bizId)});return async function(){try{var o=await(await fetch(t.url+"?"+r.toString(),{method:"POST",headers:{"x-upos-auth":t.auth,"content-type":"application/json; charset=UTF-8"},body:JSON.stringify({parts:e})})).json();if(o.OK!==1)return{error:"complete 失败:"+JSON.stringify(o)};var a=String(o.key).replace(/^\//,"").replace(/\.[^.]+$/,"");return{filename:a,cid:t.bizId}}catch(i){return{error:"complete 异常:"+String(i&&i.message||i)}}}()}function Q(t){return async function(){try{var e=await fetch("https://member.bilibili.com/x/vupre/web/topic/type?type_id="+encodeURIComponent(t.tid)+"&pn=0&ps=200",{credentials:"include"}),n=await e.json();if(!n||n.code!==0||!n.data||!Array.isArray(n.data.topics))return{error:"获取话题列表失败:"+(n&&n.message||"code="+(n&&n.code))};var r=null;for(var o=0;o<n.data.topics.length;o++)if(Number(n.data.topics[o].topic_id)===Number(t.topicId)){r=n.data.topics[o];break}if(!r)return{error:"topic_id "+t.topicId+" 不在分区 "+t.tid+" 的可用话题里(用 bilibili topics --tid "+t.tid+" 查合法值)"};return{topicId:Number(r.topic_id),missionId:r.mission_id!=null?Number(r.mission_id):null,name:r.topic_name||""}}catch(a){return{error:"解析话题异常:"+String(a&&a.message||a)}}}()}function W(t){return async function(){var e=document.cookie.match(/(?:^|;\s*)bili_jct=([^;]+)/);if(!e)return{error:"未找到 bili_jct CSRF token"};var n=decodeURIComponent(e[1]);try{var r=t.dataUri;if(typeof r==="string"&&r.indexOf("data:image/webp")===0){var o=r.indexOf(",");if(o===-1)return{error:"封面 data URI 格式非法"};var a=r.slice(5,o),i=r.slice(o+1),s;if(a.indexOf("base64")!==-1){var h=atob(i);s=new Uint8Array(h.length);for(var m=0;m<h.length;m++)s[m]=h.charCodeAt(m)}else s=new TextEncoder().encode(decodeURIComponent(i));var g=new Blob([s],{type:"image/webp"}),_=await createImageBitmap(g),y=document.createElement("canvas");y.width=_.width;y.height=_.height;var p=y.getContext("2d");p.fillStyle="#ffffff";p.fillRect(0,0,y.width,y.height);p.drawImage(_,0,0);var d=await new Promise(function(u){y.toBlob(u,"image/jpeg",0.92)});if(!d)return{error:"封面 webp 转码 JPEG 失败"};r=await new Promise(function(u,I){var P=new FileReader;P.onload=function(){u(String(P.result))};P.onerror=function(){I(Error("FileReader 读取转码结果失败"))};P.readAsDataURL(d)})}var b=new URLSearchParams;b.append("cover",r);b.append("csrf",n);var f=await(await fetch("https://member.bilibili.com/x/vu/web/cover/up",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:b.toString()})).json();if(!f||f.code!==0||!f.data||!f.data.url)return{error:"封面上传失败:"+(f&&f.message?f.message:JSON.stringify(f))};return{url:f.data.url}}catch(u){return{error:"封面上传异常:"+String(u&&u.message||u)}}}()}function X(t){return async function(){var e=document.cookie.match(/(?:^|;\s*)bili_jct=([^;]+)/);if(!e)return{error:"未找到 bili_jct CSRF token"};var n=decodeURIComponent(e[1]),r=t.meta;for(var o in r)if(r[o]===null||r[o]===void 0)delete r[o];r.csrf=n;try{var a=await fetch("https://member.bilibili.com/x/vu/web/add/v3?csrf="+encodeURIComponent(n)+"&t="+Date.now(),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json;charset=UTF-8"},body:JSON.stringify(r)}),i=await a.json();if(!i||i.code!==0)return{error:"add/v3 提交失败:"+(i&&i.message?i.message:"")+"(code="+(i&&i.code)+" status="+a.status+")"};return{bvid:i.data&&i.data.bvid,aid:i.data&&i.data.aid}}catch(s){return{error:"add/v3 异常:"+String(s&&s.message||s)}}}()}function Y(t){return async function(){var e=document.cookie.match(/(?:^|;\s*)bili_jct=([^;]+)/);if(!e)return{error:"未找到 bili_jct CSRF token"};var n=decodeURIComponent(e[1]),r=t.body;r.csrf=n;try{var o=await fetch("https://member.bilibili.com/x/vupre/web/draft/add?t="+Date.now()+"&csrf="+encodeURIComponent(n),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json;charset=UTF-8"},body:JSON.stringify(r)}),a=await o.json();if(!a||a.code!==0)return{error:"draft/add 保存草稿失败:"+(a&&a.message?a.message:"")+"(code="+(a&&a.code)+" status="+o.status+")"};return{data:a.data}}catch(i){return{error:"draft/add 异常:"+String(i&&i.message||i)}}}()}const S=(t,e,n)=>t.evaluateWithArgs(`(${e.toString()})(a)`,{a:n});function Z(t){const e=z(t),n=N.extname(e).toLowerCase(),r=n===".png"?"image/png":n===".webp"?"image/webp":n===".bmp"?"image/bmp":"image/jpeg",o=B.readFileSync(e).toString("base64");return`data:${r};base64,${o}`}async function k(t){for(let e=0;e<8;e++){await t.goto(K);await t.wait({time:1});let n="";try{n=String(await t.evaluate("location.href")||"")}catch{n=""}if(/^https?:\/\/member\.bilibili\.com\//.test(n)){const r=await t.getCookies({url:"https://member.bilibili.com"}),o=new Map;for(const i of Array.isArray(r)?r:[])if(i&&typeof i.name==="string")o.set(i.name,String(i.value??""));const a=q.filter((i)=>!o.get(i));if(!a.length)return o;throw new U("member.bilibili.com",`缺少 B站登录 cookie(${a.join(", ")})。请先在客户端登录哔哩哔哩。`)}}throw new U("member.bilibili.com","无法进入 B站创作中心(可能未登录或被风控)。请先在客户端登录哔哩哔哩。")}L({site:"bilibili",name:"upload",access:"write",description:"投稿视频到 B站(在真实浏览器登录态里走 web 投稿:preupload→upos 分块→add/v3)。默认仅 dry-run 校验,加 --execute 才真正上传并提交。",domain:"member.bilibili.com",strategy:F.COOKIE,browser:!0,args:[{name:"file",required:!0,positional:!0,help:"视频文件路径"},{name:"title",help:"稿件标题(默认取文件名)"},{name:"tid",type:"number",required:!0,help:"分区 id(B站 typeid,必填,禁止臆造)。合法值用 `bilibili partitions` 列举后取。"},{name:"tag",required:!0,help:"标签,逗号分隔(B站要求至少 1 个)"},{name:"desc",fromFile:"desc-file",help:"简介"},{name:"topic",type:"number",help:"参与话题的 topic_id(重要流量入口)。合法值用 `bilibili topics --tid <tid>` 列举,禁止臆造;mission_id 自动匹配。"},{name:"cover",help:"封面图片路径(不传由 B站自动截取)"},{name:"copyright",type:"number",help:"1=自制 2=转载(默认 1)"},{name:"ai-generated",type:"boolean",help:"声明含 AI 生成内容(发布和草稿均支持;按当前账号可用选项校验,不能与转载同时选择)"},{name:"source",help:"转载来源 URL(copyright=2 时必填)"},{name:"dynamic",help:"同步发布的动态文案(可空)"},{name:"no-reprint",type:"boolean",help:"禁止转载(默认允许)"},{name:"dtime",type:"number",help:"定时发布的 10 位 unix 时间戳(可空=立即)"},{name:"line",help:`上传线路:${Object.keys(O).join("/")}(默认 ${A})`},{name:"concurrency",type:"number",help:"分块并发数(默认 3)"},{name:"draft",type:"boolean",help:"存草稿而非直接发布(上传视频后存到创作中心草稿箱,不公开)"},{name:"execute",type:"boolean",help:"真正发布投稿;不带(也不带 --draft)则只做 dry-run 校验"},J()],columns:["status","title","bvid","url"],func:async(t,e)=>{if(!t)throw new v("bilibili upload 需要浏览器会话");const n=D(String(e.file??"")),r=String(e.title??"").trim()||N.basename(n).replace(/\.[^.]+$/,""),o=String(e.tag??"").split(",").map((c)=>c.trim()).filter(Boolean);if(!o.length)throw new w("B站投稿至少需要 1 个标签,用 --tag 传(逗号分隔)");if(e.tid==null||e.tid===""||!Number.isFinite(Number(e.tid)))throw new w("必须用 --tid 指定分区 id(数字)。合法值用 `bilibili partitions` 列举,禁止臆造。");const a=Number(e.tid),i=e.copyright!=null&&e.copyright!==""?Number(e.copyright):1;if(i!==1&&i!==2)throw new w("--copyright 只能是 1(自制) 或 2(转载)");const s=String(e.source??"").trim();if(i===2&&!s)throw new w("转载(copyright=2)必须用 --source 提供转载来源");if(e["ai-generated"]&&i===2)throw new w("B站当前创作声明只能选一项,--ai-generated 不能与 --copyright 2 同时使用");if(e.cover)z(String(e.cover));const h=String(e.line??A),m=O[h];if(!m)throw new w(`未知上传线路「${h}」,可选:${Object.keys(O).join("/")}`);const g=e.concurrency!=null&&e.concurrency!==""?Number(e.concurrency):3,_=Boolean(e.draft),y=Boolean(e.execute)&&!_;await k(t);let p;if(e["ai-generated"]){p=await S(t,PP_RESOLVE_AI_STATEMENT,{});if(!p||p.error)throw new v(p?.error||"B站创作声明查询未返回结果")}await t.evaluate(`(() => { var id=${JSON.stringify(T)}; var el=document.getElementById(id); if(!el){ el=document.createElement('input'); el.type='file'; el.id=id; el.style.cssText='position:fixed;left:-9999px;top:0;'; document.body.appendChild(el);} el.value=''; return true; })()`);await M(t,`#${T}`,[n]);if(!_&&!y)return{status:"dry-run",title:r,bvid:"",url:`校验通过:登录态有效、视频已注入就绪、分区 ${a}、标签 [${o.join(", ")}]、版权 ${i===1?"自制":"转载"}${p?"、创作声明:"+p.label:""}。加 --execute 发布,或 --draft 存草稿。`};const d=await S(t,V,{inputId:T,line:m});if(!d||d.error)throw new v(`B站 preupload 失败:${d&&d.error||"无返回"}`);for(let c=0;c<d.total;c++){const l=await S(t,H,{inputId:T,url:d.url,auth:d.auth,uploadId:d.uploadId,idx:c,total:d.total,size:d.size,chunkSize:d.chunkSize});if(!l||!l.ok)throw new v(`B站分块上传失败(${c+1}/${d.total}):${l&&l.error||"无返回"}`)}const b=await S(t,G,{url:d.url,auth:d.auth,uploadId:d.uploadId,bizId:d.bizId,name:d.name,total:d.total});if(!b||b.error||!b.filename)throw new v(`B站 complete 失败:${b&&b.error||"未拿到 filename"}`);let f="";if(e.cover){const c=Z(String(e.cover)),l=await S(t,W,{dataUri:c});if(!l||l.error||!l.url)throw new v(`B站封面上传失败:${l&&l.error||"未拿到 url"}`);f=l.url}let u=null,I=null;if(e.topic!=null&&e.topic!==""){if(!Number.isFinite(Number(e.topic)))throw new w("--topic 必须是 topic_id 数字,用 `bilibili topics --tid <tid>` 取合法值");const c=await S(t,Q,{tid:a,topicId:Number(e.topic)});if(!c||c.error)throw new v(`B站话题解析失败:${c&&c.error||"无返回"}`);u=c.topicId;I=c.missionId}if(_){const c={videos:[{filename:b.filename,title:r,desc:"",cid:b.cid,is_4k:!1,is_8k:!1,is_hdr:!1}],cover:f,cover43:f,ai_cover:0,is_ab_cover:0,ab_cover_info:null,title:r,copyright:i,tid:a,tag:o.join(","),desc:String(e.desc??""),recreate:-1,dynamic:String(e.dynamic??""),is_only_self:0,space_hidden:2,watermark:{state:0},no_reprint:e["no-reprint"]?1:0,subtitle:{open:0,lan:""},dolby:0,lossless_music:0,up_selection_reply:!1,up_close_reply:!1,up_close_danmu:!1};if(i===2)c.source=s;if(p)c.creation_statement_id=p.id;if(u!=null){c.topic_id=u;c.topic_detail={from_topic_id:u,from_source:"arc.web.search"};if(I!=null)c.mission_id=I}const l=await S(t,Y,{body:c});if(!l||l.error)throw new v(`B站 ${l&&l.error||"draft/add 无返回"}`);const R=l.data&&(l.data.aid!=null?l.data.aid:l.data.draft_id!=null?l.data.draft_id:l.data.id);return{status:"✅ 草稿已保存",title:r,bvid:R!=null?`draft:${R}`:"",url:"https://member.bilibili.com/platform/upload-manager/article?group=draft"}}const P=e.dtime!=null&&e.dtime!==""?Number(e.dtime):null,C={title:r,copyright:i,tid:a,tag:o.join(","),mission_id:I,topic_id:u,topic_detail:u!=null?{from_topic_id:u,from_source:"arc.web.recommend"}:null,desc_format_id:9999,desc:String(e.desc??""),dtime:P,recreate:-1,dynamic:String(e.dynamic??""),interactive:0,act_reserve_create:0,no_disturbance:0,porder:null,adorder_type:9,no_reprint:e["no-reprint"]?1:0,subtitle:{open:0,lan:""},creation_statement:p?{id:p.id}:null,dolby:0,lossless_music:0,up_selection_reply:!1,up_close_reply:!1,up_close_danmu:!1,web_os:1,source:i===2?s:null,watermark:{state:0},cover:f,videos:[{title:r,desc:"",filename:b.filename,cid:b.cid}]},E=await S(t,X,{meta:C});if(!E||E.error)throw new v(`B站 ${E&&E.error||"add/v3 无返回"}`);const x=E.bvid?String(E.bvid):"";return{status:e.dtime?"✅ 定时投稿已提交":"✅ 投稿成功",title:r,bvid:x,url:x?`https://www.bilibili.com/video/${x}`:"(已提交,稍后在创作中心查看)"}}});
1
+ import*as B from"node:fs";import*as N from"node:path";import{cli as L,Strategy as F}from"@jackwener/opencli/registry";import{ArgumentError as I,AuthRequiredError as U,CommandExecutionError as _}from"@jackwener/opencli/errors";import{resolveVideoFile as D,resolveImageFile as z,videoTimeoutArg as J}from"../_shared/video-publish.js";import{setInputFiles as M}from"../_shared/file-inject.js";const O={bda2:{os:"upos",upcdn:"bda2",probe_version:20221109},bldsa:{os:"upos",upcdn:"bldsa",probe_version:20221109},qn:{os:"upos",upcdn:"qn",probe_version:20221109},ws:{os:"upos",upcdn:"ws",probe_version:20221109}},A="bda2",q=["SESSDATA","bili_jct","DedeUserID"],K="https://member.bilibili.com/platform/home",T="__pp_bili_video_input";export async function PP_RESOLVE_AI_STATEMENT(){try{const t=await fetch("https://member.bilibili.com/x/vupre/web/archive/pre?lang=cn",{credentials:"include"}),e=await t.json();if(!t.ok||e?.code!==0)return{error:`读取创作声明失败:HTTP ${t.status} / ${e?.message??e?.code}`};const o=e.data?.neutral_mark?.mark_list;if(!Array.isArray(o))return{error:"当前账号的投稿配置缺少创作声明列表"};const i=o.filter((n)=>n.content==="含AI生成内容");if(i.length!==1||!Number.isSafeInteger(i[0].id)||i[0].id<=0)return{error:"当前账号未返回唯一有效的“含AI生成内容”选项"};return{id:i[0].id,label:i[0].content}}catch(t){return{error:`读取创作声明失败:${t instanceof Error?t.message:String(t)}`}}}function V(t){var e=document.getElementById(t.inputId);if(!e||!e.files||!e.files[0])return{error:"文件未就绪(input 为空)"};var o=e.files[0],i=o.size,n=t.line;return async function(){try{var a=new URLSearchParams({profile:"ugcfx/bup",name:o.name,size:String(i),r:n.os,ssl:"0",version:"2.14.0",build:"2100400",upcdn:n.upcdn,probe_version:String(n.probe_version)}),r=await(await fetch("https://member.bilibili.com/preupload?"+a.toString(),{credentials:"include",headers:{Referer:"https://www.bilibili.com"}})).json();if(r.OK!==1)return{error:"preupload 失败:"+JSON.stringify(r),code:r.code,voucher:!!r.voucher};var s="https:"+r.endpoint+"/"+String(r.upos_uri).replace(/^upos:\/\//,""),h=new URLSearchParams({uploads:"",output:"json",profile:"ugcfx/bup",filesize:String(i),partsize:String(r.chunk_size),biz_id:String(r.biz_id)}),m=await(await fetch(s+"?"+h.toString(),{method:"POST",headers:{"x-upos-auth":r.auth}})).json();if(m.OK!==1)return{error:"获取 upload_id 失败:"+JSON.stringify(m)};var w=Math.max(1,Math.ceil(i/r.chunk_size));return{url:s,auth:r.auth,uploadId:m.upload_id,chunkSize:r.chunk_size,bizId:r.biz_id,size:i,name:o.name,total:w}}catch(v){return{error:"preupload 异常:"+String(v&&v.message||v)}}}()}function H(t){var e=document.getElementById(t.inputId);if(!e||!e.files||!e.files[0])return{ok:!1,error:"文件丢失(页面可能已导航)"};var o=e.files[0],i=t.idx*t.chunkSize,n=o.slice(i,Math.min(i+t.chunkSize,t.size)),a=n.size,r=new URLSearchParams({partNumber:String(t.idx+1),uploadId:String(t.uploadId),chunk:String(t.idx),chunks:String(t.total),size:String(a),start:String(i),end:String(i+a),total:String(t.size)});return async function(){for(var s=0;s<5;s++){try{var h=await fetch(t.url+"?"+r.toString(),{method:"PUT",headers:{"x-upos-auth":t.auth},body:n});if(h.status<400){var m=await h.text();if(m==="MULTIPART_PUT_SUCCESS"||m==="")return{ok:!0}}}catch(w){}await new Promise(function(w){setTimeout(w,800*(s+1))})}return{ok:!1,error:"分块 "+t.idx+" 多次重试仍失败"}}()}function G(t){var e=[];for(var o=1;o<=t.total;o++)e.push({partNumber:o,eTag:"etag"});var i=new URLSearchParams({output:"json",name:t.name,profile:"ugcfx/bup",uploadId:String(t.uploadId),biz_id:String(t.bizId)});return async function(){try{var n=await(await fetch(t.url+"?"+i.toString(),{method:"POST",headers:{"x-upos-auth":t.auth,"content-type":"application/json; charset=UTF-8"},body:JSON.stringify({parts:e})})).json();if(n.OK!==1)return{error:"complete 失败:"+JSON.stringify(n)};var a=String(n.key).replace(/^\//,"").replace(/\.[^.]+$/,"");return{filename:a,cid:t.bizId}}catch(r){return{error:"complete 异常:"+String(r&&r.message||r)}}}()}function Q(t){return async function(){try{var e=await fetch("https://member.bilibili.com/x/vupre/web/topic/type?type_id="+encodeURIComponent(t.tid)+"&pn=0&ps=200",{credentials:"include"}),o=await e.json();if(!o||o.code!==0||!o.data||!Array.isArray(o.data.topics))return{error:"获取话题列表失败:"+(o&&o.message||"code="+(o&&o.code))};var i=null;for(var n=0;n<o.data.topics.length;n++)if(Number(o.data.topics[n].topic_id)===Number(t.topicId)){i=o.data.topics[n];break}if(!i)return{error:"topic_id "+t.topicId+" 不在分区 "+t.tid+" 的可用话题里(用 bilibili topics --tid "+t.tid+" 查合法值)"};return{topicId:Number(i.topic_id),missionId:i.mission_id!=null?Number(i.mission_id):null,name:i.topic_name||""}}catch(a){return{error:"解析话题异常:"+String(a&&a.message||a)}}}()}function W(t){return async function(){var e=document.cookie.match(/(?:^|;\s*)bili_jct=([^;]+)/);if(!e)return{error:"未找到 bili_jct CSRF token"};var o=decodeURIComponent(e[1]);try{var i=t.dataUri;if(typeof i==="string"&&i.indexOf("data:image/webp")===0){var n=i.indexOf(",");if(n===-1)return{error:"封面 data URI 格式非法"};var a=i.slice(5,n),r=i.slice(n+1),s;if(a.indexOf("base64")!==-1){var h=atob(r);s=new Uint8Array(h.length);for(var m=0;m<h.length;m++)s[m]=h.charCodeAt(m)}else s=new TextEncoder().encode(decodeURIComponent(r));var w=new Blob([s],{type:"image/webp"}),v=await createImageBitmap(w),y=document.createElement("canvas");y.width=v.width;y.height=v.height;var p=y.getContext("2d");p.fillStyle="#ffffff";p.fillRect(0,0,y.width,y.height);p.drawImage(v,0,0);var c=await new Promise(function(u){y.toBlob(u,"image/jpeg",0.92)});if(!c)return{error:"封面 webp 转码 JPEG 失败"};i=await new Promise(function(u,P){var E=new FileReader;E.onload=function(){u(String(E.result))};E.onerror=function(){P(Error("FileReader 读取转码结果失败"))};E.readAsDataURL(c)})}var b=new URLSearchParams;b.append("cover",i);b.append("csrf",o);var f=await(await fetch("https://member.bilibili.com/x/vu/web/cover/up",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:b.toString()})).json();if(!f||f.code!==0||!f.data||!f.data.url)return{error:"封面上传失败:"+(f&&f.message?f.message:JSON.stringify(f))};return{url:f.data.url}}catch(u){return{error:"封面上传异常:"+String(u&&u.message||u)}}}()}function X(t){return async function(){var e=document.cookie.match(/(?:^|;\s*)bili_jct=([^;]+)/);if(!e)return{error:"未找到 bili_jct CSRF token"};var o=decodeURIComponent(e[1]),i=t.meta;for(var n in i)if(i[n]===null||i[n]===void 0)delete i[n];i.csrf=o;try{var a=await fetch("https://member.bilibili.com/x/vu/web/add/v3?csrf="+encodeURIComponent(o)+"&t="+Date.now(),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json;charset=UTF-8"},body:JSON.stringify(i)}),r=await a.json();if(!r||r.code!==0)return{error:"add/v3 提交失败:"+(r&&r.message?r.message:"")+"(code="+(r&&r.code)+" status="+a.status+")",code:r&&r.code};return{bvid:r.data&&r.data.bvid,aid:r.data&&r.data.aid}}catch(s){return{error:"add/v3 异常:"+String(s&&s.message||s)}}}()}function Y(t){return async function(){var e=document.cookie.match(/(?:^|;\s*)bili_jct=([^;]+)/);if(!e)return{error:"未找到 bili_jct CSRF token"};var o=decodeURIComponent(e[1]),i=t.body;i.csrf=o;try{var n=await fetch("https://member.bilibili.com/x/vupre/web/draft/add?t="+Date.now()+"&csrf="+encodeURIComponent(o),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json;charset=UTF-8"},body:JSON.stringify(i)}),a=await n.json();if(!a||a.code!==0)return{error:"draft/add 保存草稿失败:"+(a&&a.message?a.message:"")+"(code="+(a&&a.code)+" status="+n.status+")"};return{data:a.data}}catch(r){return{error:"draft/add 异常:"+String(r&&r.message||r)}}}()}const g=(t,e,o)=>t.evaluateWithArgs(`(${e.toString()})(a)`,{a:o});function Z(t){const e=z(t),o=N.extname(e).toLowerCase(),i=o===".png"?"image/png":o===".webp"?"image/webp":o===".bmp"?"image/bmp":"image/jpeg",n=B.readFileSync(e).toString("base64");return`data:${i};base64,${n}`}async function k(t){for(let e=0;e<8;e++){await t.goto(K);await t.wait({time:1});let o="";try{o=String(await t.evaluate("location.href")||"")}catch{o=""}if(/^https?:\/\/member\.bilibili\.com\//.test(o)){const i=await t.getCookies({url:"https://member.bilibili.com"}),n=new Map;for(const r of Array.isArray(i)?i:[])if(r&&typeof r.name==="string")n.set(r.name,String(r.value??""));const a=q.filter((r)=>!n.get(r));if(!a.length)return n;throw new U("member.bilibili.com",`缺少 B站登录 cookie(${a.join(", ")})。请先在客户端登录哔哩哔哩。`)}}throw new U("member.bilibili.com","无法进入 B站创作中心(可能未登录或被风控)。请先在客户端登录哔哩哔哩。")}L({site:"bilibili",name:"upload",access:"write",description:"投稿视频到 B站(在真实浏览器登录态里走 web 投稿:preupload→upos 分块→add/v3)。默认仅 dry-run 校验,加 --execute 才真正上传并提交。",domain:"member.bilibili.com",strategy:F.COOKIE,browser:!0,args:[{name:"file",required:!0,positional:!0,help:"视频文件路径"},{name:"title",help:"稿件标题(默认取文件名)"},{name:"tid",type:"number",required:!0,help:"分区 id(B站 typeid,必填,禁止臆造)。合法值用 `bilibili partitions` 列举后取。"},{name:"tag",required:!0,help:"标签,逗号分隔(B站要求至少 1 个)"},{name:"desc",fromFile:"desc-file",help:"简介"},{name:"topic",type:"number",help:"参与话题的 topic_id(重要流量入口)。合法值用 `bilibili topics --tid <tid>` 列举,禁止臆造;mission_id 自动匹配。"},{name:"cover",help:"封面图片路径(不传由 B站自动截取)"},{name:"copyright",type:"number",help:"1=自制 2=转载(默认 1)"},{name:"ai-generated",type:"boolean",help:"声明含 AI 生成内容(发布和草稿均支持;按当前账号可用选项校验,不能与转载同时选择)"},{name:"source",help:"转载来源 URL(copyright=2 时必填)"},{name:"dynamic",help:"同步发布的动态文案(可空)"},{name:"no-reprint",type:"boolean",help:"禁止转载(默认允许)"},{name:"dtime",type:"number",help:"定时发布的 10 位 unix 时间戳(可空=立即)"},{name:"line",help:`上传线路:${Object.keys(O).join("/")}(默认 ${A})`},{name:"concurrency",type:"number",help:"分块并发数(默认 3)"},{name:"draft",type:"boolean",help:"存草稿而非直接发布(上传视频后存到创作中心草稿箱,不公开)"},{name:"execute",type:"boolean",help:"真正发布投稿;不带(也不带 --draft)则只做 dry-run 校验"},J()],columns:["status","title","bvid","url"],func:async(t,e)=>{if(!t)throw new _("bilibili upload 需要浏览器会话");const o=D(String(e.file??"")),i=String(e.title??"").trim()||N.basename(o).replace(/\.[^.]+$/,""),n=String(e.tag??"").split(",").map((d)=>d.trim()).filter(Boolean);if(!n.length)throw new I("B站投稿至少需要 1 个标签,用 --tag 传(逗号分隔)");if(e.tid==null||e.tid===""||!Number.isFinite(Number(e.tid)))throw new I("必须用 --tid 指定分区 id(数字)。合法值用 `bilibili partitions` 列举,禁止臆造。");const a=Number(e.tid),r=e.copyright!=null&&e.copyright!==""?Number(e.copyright):1;if(r!==1&&r!==2)throw new I("--copyright 只能是 1(自制) 或 2(转载)");const s=String(e.source??"").trim();if(r===2&&!s)throw new I("转载(copyright=2)必须用 --source 提供转载来源");if(e["ai-generated"]&&r===2)throw new I("B站当前创作声明只能选一项,--ai-generated 不能与 --copyright 2 同时使用");if(e.cover)z(String(e.cover));const h=String(e.line??A),m=O[h];if(!m)throw new I(`未知上传线路「${h}」,可选:${Object.keys(O).join("/")}`);const w=e.concurrency!=null&&e.concurrency!==""?Number(e.concurrency):3,v=Boolean(e.draft),y=Boolean(e.execute)&&!v;await k(t);let p;if(e["ai-generated"]){p=await g(t,PP_RESOLVE_AI_STATEMENT,{});if(!p||p.error)throw new _(p?.error||"B站创作声明查询未返回结果")}await t.evaluate(`(() => { var id=${JSON.stringify(T)}; var el=document.getElementById(id); if(!el){ el=document.createElement('input'); el.type='file'; el.id=id; el.style.cssText='position:fixed;left:-9999px;top:0;'; document.body.appendChild(el);} el.value=''; return true; })()`);await M(t,`#${T}`,[o]);if(!v&&!y)return{status:"dry-run",title:i,bvid:"",url:`校验通过:登录态有效、视频已注入就绪、分区 ${a}、标签 [${n.join(", ")}]、版权 ${r===1?"自制":"转载"}${p?"、创作声明:"+p.label:""}。加 --execute 发布,或 --draft 存草稿。`};const c=await g(t,V,{inputId:T,line:m});if(!c||c.error)throw new _(`B站 preupload 失败:${c&&c.error||"无返回"}`,c&&c.code===601?"code 601 表示平台对本次上传要求额外验证,命令行无法完成。请在同一浏览器环境打开网页投稿页 https://member.bilibili.com/platform/upload/video/frame 手动投稿(网页会弹出验证);不要连续重试命令,重复触发会加重风控。":void 0);for(let d=0;d<c.total;d++){const l=await g(t,H,{inputId:T,url:c.url,auth:c.auth,uploadId:c.uploadId,idx:d,total:c.total,size:c.size,chunkSize:c.chunkSize});if(!l||!l.ok)throw new _(`B站分块上传失败(${d+1}/${c.total}):${l&&l.error||"无返回"}`)}const b=await g(t,G,{url:c.url,auth:c.auth,uploadId:c.uploadId,bizId:c.bizId,name:c.name,total:c.total});if(!b||b.error||!b.filename)throw new _(`B站 complete 失败:${b&&b.error||"未拿到 filename"}`);let f="";if(e.cover){const d=Z(String(e.cover)),l=await g(t,W,{dataUri:d});if(!l||l.error||!l.url)throw new _(`B站封面上传失败:${l&&l.error||"未拿到 url"}`);f=l.url}let u=null,P=null;if(e.topic!=null&&e.topic!==""){if(!Number.isFinite(Number(e.topic)))throw new I("--topic 必须是 topic_id 数字,用 `bilibili topics --tid <tid>` 取合法值");const d=await g(t,Q,{tid:a,topicId:Number(e.topic)});if(!d||d.error)throw new _(`B站话题解析失败:${d&&d.error||"无返回"}`);u=d.topicId;P=d.missionId}if(v){const d={videos:[{filename:b.filename,title:i,desc:"",cid:b.cid,is_4k:!1,is_8k:!1,is_hdr:!1}],cover:f,cover43:f,ai_cover:0,is_ab_cover:0,ab_cover_info:null,title:i,copyright:r,tid:a,tag:n.join(","),desc:String(e.desc??""),recreate:-1,dynamic:String(e.dynamic??""),is_only_self:0,space_hidden:2,watermark:{state:0},no_reprint:e["no-reprint"]?1:0,subtitle:{open:0,lan:""},dolby:0,lossless_music:0,up_selection_reply:!1,up_close_reply:!1,up_close_danmu:!1};if(r===2)d.source=s;if(p)d.creation_statement_id=p.id;if(u!=null){d.topic_id=u;d.topic_detail={from_topic_id:u,from_source:"arc.web.search"};if(P!=null)d.mission_id=P}const l=await g(t,Y,{body:d});if(!l||l.error)throw new _(`B站 ${l&&l.error||"draft/add 无返回"}`);const R=l.data&&(l.data.aid!=null?l.data.aid:l.data.draft_id!=null?l.data.draft_id:l.data.id);return{status:"✅ 草稿已保存",title:i,bvid:R!=null?`draft:${R}`:"",url:"https://member.bilibili.com/platform/upload-manager/article?group=draft"}}const E=e.dtime!=null&&e.dtime!==""?Number(e.dtime):null,C={title:i,copyright:r,tid:a,tag:n.join(","),mission_id:P,topic_id:u,topic_detail:u!=null?{from_topic_id:u,from_source:"arc.web.recommend"}:null,desc_format_id:9999,desc:String(e.desc??""),dtime:E,recreate:-1,dynamic:String(e.dynamic??""),interactive:0,act_reserve_create:0,no_disturbance:0,porder:null,adorder_type:9,no_reprint:e["no-reprint"]?1:0,subtitle:{open:0,lan:""},creation_statement:p?{id:p.id}:null,dolby:0,lossless_music:0,up_selection_reply:!1,up_close_reply:!1,up_close_danmu:!1,web_os:1,source:r===2?s:null,watermark:{state:0},cover:f,videos:[{title:i,desc:"",filename:b.filename,cid:b.cid}]},S=await g(t,X,{meta:C});if(!S||S.error)throw new _(`B站 ${S&&S.error||"add/v3 无返回"}`,S&&S.code===603?"code 603 是平台风控(检测到异常行为),稿件未创建。停止本账号的投稿与其他写操作,先在网页端确认账号仍在登录、无异常提示,冷却至少数小时后再试;不要换参数连续重试。":void 0);const x=S.bvid?String(S.bvid):"";return{status:e.dtime?"✅ 定时投稿已提交":"✅ 投稿成功",title:i,bvid:x,url:x?`https://www.bilibili.com/video/${x}`:"(已提交,稍后在创作中心查看)"}}});
@@ -1,14 +1,16 @@
1
- import g from"node:https";import{ArgumentError as m,AuthRequiredError as d,CommandExecutionError as u,EmptyResultError as b}from"@jackwener/opencli/errors";export function resolveBvid(e){const t=String(e).trim();if(/^BV[A-Za-z0-9]+$/i.test(t))return Promise.resolve(t);try{const i=new URL(t);if(/(\.|^)bilibili\.com$/i.test(i.hostname)){const s=i.pathname.match(/\/(?:video|bangumi\/play)\/(BV[A-Za-z0-9]+)/i);if(s)return Promise.resolve(s[1])}}catch{}const r=t.replace(/^https?:\/\//,"").replace(/^(www\.)?b23\.tv\//,"");if(!/^[A-Za-z0-9]+$/.test(r))return Promise.reject(Error(`Cannot resolve BV ID from invalid b23.tv short code: ${t}`));const n="https://b23.tv/"+r;return new Promise((i,s)=>{const o=g.get(n,(a)=>{const c=a.headers.location;if(c){const f=c.match(/\/video\/(BV[A-Za-z0-9]+)/);if(f){a.resume();i(f[1]);return}}a.resume();s(Error(`Cannot resolve BV ID from short URL: ${t}`))});o.on("error",s);o.setTimeout(4000,()=>{o.destroy();s(Error(`Timeout resolving short URL: ${t}`))})})}export function parsePageArg(e){if(e==null||e==="")return null;if(typeof e==="number"){if(Number.isSafeInteger(e)&&e>=1)return e;throw new m(`--page must be a positive decimal integer, got: ${e}`)}if(typeof e!=="string"||!/^[1-9]\d*$/.test(e))throw new m(`--page must be a positive decimal integer, got: ${String(e)}`);const t=Number(e);if(!Number.isSafeInteger(t))throw new m(`--page is too large: ${e}`);return t}function p(e,t){if(typeof e==="number"&&Number.isSafeInteger(e)&&e>=1)return e;if(typeof e==="string"&&/^[1-9]\d*$/.test(e)){const r=Number(e);if(Number.isSafeInteger(r))return r}throw new u(`Bilibili view API returned a malformed ${t}`)}export function selectVideoPart(e,t){const r=Array.isArray(e?.pages)?e.pages:null;if(!r||r.length===0)throw new u("Bilibili view API did not return pages[] for --page selection");const n=[];for(const s of r){if(!s||typeof s!=="object"||Array.isArray(s))throw new u("Bilibili view API returned a malformed pages[] entry");if(p(s.page,"page number")===t)n.push(s)}if(n.length>1)throw new u(`Bilibili view API returned duplicate page entries for p=${t}`);const i=n[0];if(!i){const s=r.length||e?.videos||1;throw new u(`分P 序号超出范围:p=${t}(该视频共 ${s} 集)`)}p(i.cid,`cid for p=${t}`);return i}const h=[46,47,18,2,53,8,23,32,15,50,10,31,58,3,45,35,27,43,5,49,33,9,42,19,29,28,14,39,12,38,41,13,37,48,7,16,24,55,40,61,26,17,0,1,60,51,30,4,22,25,54,21,56,59,6,63,57,62,11,36,20,34,44,52];export function stripHtml(e){return e.replace(/<[^>]+>/g,"").replace(/&[a-z]+;/gi," ").trim()}export function payloadData(e){return e?.data??e}async function w(e){return e.evaluate(`
1
+ import g from"node:https";import{ArgumentError as m,AuthRequiredError as p,CommandExecutionError as c,EmptyResultError as b}from"@jackwener/opencli/errors";export function resolveBvid(t){const e=String(t).trim();if(/^BV[A-Za-z0-9]+$/i.test(e))return Promise.resolve(e);try{const n=new URL(e);if(/(\.|^)bilibili\.com$/i.test(n.hostname)){const s=n.pathname.match(/\/(?:video|bangumi\/play)\/(BV[A-Za-z0-9]+)/i);if(s)return Promise.resolve(s[1])}}catch{}const r=e.replace(/^https?:\/\//,"").replace(/^(www\.)?b23\.tv\//,"");if(!/^[A-Za-z0-9]+$/.test(r))return Promise.reject(Error(`Cannot resolve BV ID from invalid b23.tv short code: ${e}`));const i="https://b23.tv/"+r;return new Promise((n,s)=>{const o=g.get(i,(u)=>{const a=u.headers.location;if(a){const f=a.match(/\/video\/(BV[A-Za-z0-9]+)/);if(f){u.resume();n(f[1]);return}}u.resume();s(Error(`Cannot resolve BV ID from short URL: ${e}`))});o.on("error",s);o.setTimeout(4000,()=>{o.destroy();s(Error(`Timeout resolving short URL: ${e}`))})})}export function parsePageArg(t){if(t==null||t==="")return null;if(typeof t==="number"){if(Number.isSafeInteger(t)&&t>=1)return t;throw new m(`--page must be a positive decimal integer, got: ${t}`)}if(typeof t!=="string"||!/^[1-9]\d*$/.test(t))throw new m(`--page must be a positive decimal integer, got: ${String(t)}`);const e=Number(t);if(!Number.isSafeInteger(e))throw new m(`--page is too large: ${t}`);return e}function d(t,e){if(typeof t==="number"&&Number.isSafeInteger(t)&&t>=1)return t;if(typeof t==="string"&&/^[1-9]\d*$/.test(t)){const r=Number(t);if(Number.isSafeInteger(r))return r}throw new c(`Bilibili view API returned a malformed ${e}`)}export function selectVideoPart(t,e){const r=Array.isArray(t?.pages)?t.pages:null;if(!r||r.length===0)throw new c("Bilibili view API did not return pages[] for --page selection");const i=[];for(const s of r){if(!s||typeof s!=="object"||Array.isArray(s))throw new c("Bilibili view API returned a malformed pages[] entry");if(d(s.page,"page number")===e)i.push(s)}if(i.length>1)throw new c(`Bilibili view API returned duplicate page entries for p=${e}`);const n=i[0];if(!n){const s=r.length||t?.videos||1;throw new c(`分P 序号超出范围:p=${e}(该视频共 ${s} 集)`)}d(n.cid,`cid for p=${e}`);return n}const h=[46,47,18,2,53,8,23,32,15,50,10,31,58,3,45,35,27,43,5,49,33,9,42,19,29,28,14,39,12,38,41,13,37,48,7,16,24,55,40,61,26,17,0,1,60,51,30,4,22,25,54,21,56,59,6,63,57,62,11,36,20,34,44,52];export function stripHtml(t){return t.replace(/<[^>]+>/g,"").replace(/&[a-z]+;/gi," ").trim()}export function payloadData(t){return t?.data??t}async function w(t){return t.evaluate(`
2
2
  async () => {
3
3
  const res = await fetch('https://api.bilibili.com/x/web-interface/nav', { credentials: 'include' });
4
4
  return await res.json();
5
5
  }
6
- `)}async function y(e){const r=(await w(e))?.data?.wbi_img??{},n=r.img_url??"",i=r.sub_url??"",s=n.split("/").pop()?.split(".")[0]??"",o=i.split("/").pop()?.split(".")[0]??"";return{imgKey:s,subKey:o}}function S(e,t){const r=e+t;return h.map((n)=>r[n]||"").join("").slice(0,32)}async function x(e){const{createHash:t}=await import("node:crypto");return t("md5").update(e).digest("hex")}export async function wbiSign(e,t){const{imgKey:r,subKey:n}=await y(e),i=S(r,n),s=Math.floor(Date.now()/1000),o={},a={...t,wts:String(s)};for(const l of Object.keys(a).sort())o[l]=String(a[l]).replace(/[!'()*]/g,"");const c=new URLSearchParams(o).toString().replace(/\+/g,"%20"),f=await x(c+i);o.w_rid=f;return o}export async function apiGet(e,t,r={}){const n="https://api.bilibili.com";let i=r.params??{};if(r.signed)i=await wbiSign(e,i);const s=new URLSearchParams(Object.fromEntries(Object.entries(i).map(([a,c])=>[a,String(c)]))).toString().replace(/\+/g,"%20"),o=`${n}${t}?${s}`;return fetchJson(e,o)}export async function fetchJson(e,t){const r=JSON.stringify(t);return e.evaluate(`
6
+ `)}async function y(t){const r=(await w(t))?.data?.wbi_img??{},i=r.img_url??"",n=r.sub_url??"",s=i.split("/").pop()?.split(".")[0]??"",o=n.split("/").pop()?.split(".")[0]??"";return{imgKey:s,subKey:o}}function S(t,e){const r=t+e;return h.map((i)=>r[i]||"").join("").slice(0,32)}async function x(t){const{createHash:e}=await import("node:crypto");return e("md5").update(t).digest("hex")}export async function wbiSign(t,e){const{imgKey:r,subKey:i}=await y(t),n=S(r,i),s=Math.floor(Date.now()/1000),o={},u={...e,wts:String(s)};for(const l of Object.keys(u).sort())o[l]=String(u[l]).replace(/[!'()*]/g,"");const a=new URLSearchParams(o).toString().replace(/\+/g,"%20"),f=await x(a+n);o.w_rid=f;return o}export async function apiGet(t,e,r={}){const i="https://api.bilibili.com";let n=r.params??{};if(r.signed)n=await wbiSign(t,n);const s=new URLSearchParams(Object.fromEntries(Object.entries(n).map(([u,a])=>[u,String(a)]))).toString().replace(/\+/g,"%20"),o=`${i}${e}?${s}`;return fetchJson(t,o)}export async function fetchJson(t,e){const r=JSON.stringify(e),i=await t.evaluate(`
7
7
  async () => {
8
8
  const res = await fetch(${r}, { credentials: "include" });
9
- return await res.json();
9
+ const text = await res.text();
10
+ try { return { ok: true, json: JSON.parse(text) }; }
11
+ catch (e) { return { ok: false, status: res.status, head: text.slice(0, 120) }; }
10
12
  }
11
- `)}export function isAuthLikeBilibiliError(e,t){return e===-101||e===-111||e===-403||/csrf|登录|账号|权限|forbidden|permission|login/i.test(String(t??""))}export function requireOkPayload(e,t){if(!e||typeof e!=="object"||Array.isArray(e)||!Object.hasOwn(e,"code"))throw new u(`Bilibili ${t} API returned a malformed payload`);if(e.code!==0){const r=e.message??"unknown error";if(isAuthLikeBilibiliError(e.code,r))throw new d("bilibili.com",`Bilibili ${t} API requires login or permission: ${r} (${e.code})`);throw new u(`Bilibili ${t} API failed: ${r} (${e.code})`)}return e.data}export async function apiPost(e,t,r={}){const n=r.params??{},i=Object.fromEntries(Object.entries(n).map(([a,c])=>[a,String(c)])),s=JSON.stringify(i),o=JSON.stringify(`https://api.bilibili.com${t}`);return e.evaluate(`
13
+ `);if(i&&i.ok===!0)return i.json;const n=String(e).replace(/^https?:\/\/[^/]+/,"").split("?")[0],s=i?.status;if(s===412)throw new c(`B 站接口 ${n} 暂时限流(HTTP 412,返回风控页而非数据)`,"这是平台对该接口的短时限流,通常 5~15 分钟后恢复;不影响已完成的写操作。稍后再读,不要立即重复请求。");throw new c(`B 站接口 ${n} 返回的不是 JSON(HTTP ${s??"未知"}):${String(i?.head??"").replace(/\s+/g," ").trim()}`)}export function isAuthLikeBilibiliError(t,e){return t===-101||t===-111||t===-403||/csrf|登录|账号|权限|forbidden|permission|login/i.test(String(e??""))}export function requireOkPayload(t,e){if(!t||typeof t!=="object"||Array.isArray(t)||!Object.hasOwn(t,"code"))throw new c(`Bilibili ${e} API returned a malformed payload`);if(t.code!==0){const r=t.message??"unknown error";if(isAuthLikeBilibiliError(t.code,r))throw new p("bilibili.com",`Bilibili ${e} API requires login or permission: ${r} (${t.code})`);throw new c(`Bilibili ${e} API failed: ${r} (${t.code})`)}return t.data}export async function apiPost(t,e,r={}){const i=r.params??{},n=Object.fromEntries(Object.entries(i).map(([u,a])=>[u,String(a)])),s=JSON.stringify(n),o=JSON.stringify(`https://api.bilibili.com${e}`);return t.evaluate(`
12
14
  async () => {
13
15
  const csrf = (document.cookie.match(/bili_jct=([^;]+)/) || [])[1] || "";
14
16
  const body = new URLSearchParams(${s});
@@ -28,13 +30,13 @@ import g from"node:https";import{ArgumentError as m,AuthRequiredError as d,Comma
28
30
  return { code: -1, message: "Non-JSON response (HTTP " + res.status + "): " + text.slice(0, 200) };
29
31
  }
30
32
  }
31
- `)}export async function apiPostAbs(e,t,r={}){const n=r.params??{},i=Object.fromEntries(Object.entries(n).map(([c,f])=>[c,String(f)])),s=JSON.stringify(i);let o=t;if(r.query&&Object.keys(r.query).length>0){const c=new URLSearchParams(Object.fromEntries(Object.entries(r.query).map(([f,l])=>[f,String(l)]))).toString().replace(/\+/g,"%20");o=`${t}?${c}`}const a=JSON.stringify(o);return e.evaluate(`
33
+ `)}export async function apiPostAbs(t,e,r={}){const i=r.params??{},n=Object.fromEntries(Object.entries(i).map(([a,f])=>[a,String(f)])),s=JSON.stringify(n);let o=e;if(r.query&&Object.keys(r.query).length>0){const a=new URLSearchParams(Object.fromEntries(Object.entries(r.query).map(([f,l])=>[f,String(l)]))).toString().replace(/\+/g,"%20");o=`${e}?${a}`}const u=JSON.stringify(o);return t.evaluate(`
32
34
  async () => {
33
35
  const csrf = (document.cookie.match(/bili_jct=([^;]+)/) || [])[1] || "";
34
36
  const body = new URLSearchParams(${s});
35
37
  body.set("csrf", csrf);
36
38
  body.set("csrf_token", csrf);
37
- const res = await fetch(${a}, {
39
+ const res = await fetch(${u}, {
38
40
  method: "POST",
39
41
  credentials: "include",
40
42
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
@@ -47,4 +49,4 @@ import g from"node:https";import{ArgumentError as m,AuthRequiredError as d,Comma
47
49
  return { code: -1, message: "Non-JSON response (HTTP " + res.status + "): " + text.slice(0, 200) };
48
50
  }
49
51
  }
50
- `)}export async function resolveVideoIds(e,t){let r;try{r=await resolveBvid(t)}catch(o){throw new m(`Cannot resolve Bilibili BV ID from input: ${String(t??"")}`,o instanceof Error?o.message:String(o))}const n=await apiGet(e,"/x/web-interface/view",{params:{bvid:r}}),s=requireOkPayload(n,"view")?.aid;if(!s)throw new u(`Cannot resolve aid for bvid: ${r}`);return{bvid:r,aid:Number(s)}}export async function getSelfUid(e){const r=(await w(e))?.data?.mid;if(!r)throw new d("bilibili.com");return String(r)}export function readSearchResults(e,t){if(!e||typeof e!=="object"||Array.isArray(e))throw new u(`Bilibili ${t} returned malformed result`);const r=e.data,n=Boolean(r&&typeof r==="object"&&!Array.isArray(r)&&r.v_voucher);if(Object.hasOwn(e,"code")&&e.code!==0||n){const i=e.message??"";if(!n&&isAuthLikeBilibiliError(e.code,i))throw new d("bilibili.com",`Bilibili ${t} requires login or permission: ${i} (${e.code})`);throw new u(`Bilibili ${t} 被平台限流/风控拦截(code=${e.code}${i?`, ${i}`:""}${n?", v_voucher":""})`,"这是搜索接口的频率限制,不是「用户不存在」。停止连续搜索,隔一段时间再试;已知 UID 时直接传数字 UID 可完全绕开搜索。")}if(!r||typeof r!=="object"||Array.isArray(r))throw new u(`Bilibili ${t} returned malformed result`);if(!Object.hasOwn(r,"result")){if(Number(r.numResults)===0)return[];throw new u(`Bilibili ${t} returned malformed result(data 键:${Object.keys(r).join(",")||"空"})`)}if(!Array.isArray(r.result))throw new u(`Bilibili ${t} returned malformed result`);return r.result}export async function resolveUser(e,t){if(/^\d+$/.test(t))return{mid:t,name:"",exact:!0};const r=await apiGet(e,"/x/web-interface/wbi/search/type",{params:{search_type:"bili_user",keyword:t},signed:!0}),n=readSearchResults(r,`user search for ${t}`);if(n.length===0)throw new b(`bilibili user search: ${t}`,"User may not exist or username may have changed.");const i=(c)=>stripHtml(String(c?.uname??"")),s=n.find((c)=>i(c)===t),o=s??n[0],a=String(o?.mid??"").trim();if(!a)throw new u(`Bilibili user search returned malformed mid for ${t}`);return{mid:a,name:i(o),exact:Boolean(s)}}export async function resolveUid(e,t){return(await resolveUser(e,t)).mid}export function formatBeijingTime(e){const t=Number(e);if(!e||!Number.isFinite(t))return"";return new Date((t+28800)*1000).toISOString().slice(0,16).replace("T"," ")}export function sleep(e){return new Promise((t)=>setTimeout(t,e))}export function describeReplyVisibility(e){const t=Number.isInteger(e?.state)?e.state:null,r=Number.isInteger(e?.attr)?e.attr:null;let n="unknown";if(t===0)n="public";else if(t===17)n="self-only";return{state:t,attr:r,visibility:n}}export function parseMsgContent(e){const t=String(e??"");try{const r=JSON.parse(t);if(r&&typeof r==="object"){if(typeof r.content==="string")return r.content;if(typeof r.title==="string"||typeof r.text==="string")return[r.title,r.text].filter(Boolean).join(":");return t}}catch{}return t}export function describeDmMessage(e){const t=Number(e?.msg_type??0),r=String(e?.content??"");let n=null;try{n=JSON.parse(r)}catch{}const i=n&&typeof n==="object"&&!Array.isArray(n)?n:null,s=Number(e?.msg_status??0)===1;if(t===5)return{content:`[撤回了一条消息,被撤回消息 msg_key=${r}]`,image_url:"",recalled:!0};if(t===2&&i&&typeof i.url==="string")return{content:"[图片]",image_url:i.url,recalled:s};if(i&&typeof i.pic_url==="string")return{content:[i.title,i.jump_url].filter((o)=>typeof o==="string"&&o).join(" ")||"[图片]",image_url:i.pic_url,recalled:s};return{content:parseMsgContent(r),image_url:"",recalled:s}}
52
+ `)}export async function resolveVideoIds(t,e){let r;try{r=await resolveBvid(e)}catch(o){throw new m(`Cannot resolve Bilibili BV ID from input: ${String(e??"")}`,o instanceof Error?o.message:String(o))}const i=await apiGet(t,"/x/web-interface/view",{params:{bvid:r}}),s=requireOkPayload(i,"view")?.aid;if(!s)throw new c(`Cannot resolve aid for bvid: ${r}`);return{bvid:r,aid:Number(s)}}export async function getSelfUid(t){const r=(await w(t))?.data?.mid;if(!r)throw new p("bilibili.com");return String(r)}export function readSearchResults(t,e){if(!t||typeof t!=="object"||Array.isArray(t))throw new c(`Bilibili ${e} returned malformed result`);const r=t.data,i=Boolean(r&&typeof r==="object"&&!Array.isArray(r)&&r.v_voucher);if(Object.hasOwn(t,"code")&&t.code!==0||i){const n=t.message??"";if(!i&&isAuthLikeBilibiliError(t.code,n))throw new p("bilibili.com",`Bilibili ${e} requires login or permission: ${n} (${t.code})`);throw new c(`Bilibili ${e} 被平台限流/风控拦截(code=${t.code}${n?`, ${n}`:""}${i?", v_voucher":""})`,"这是搜索接口的频率限制,不是「用户不存在」。停止连续搜索,隔一段时间再试;已知 UID 时直接传数字 UID 可完全绕开搜索。")}if(!r||typeof r!=="object"||Array.isArray(r))throw new c(`Bilibili ${e} returned malformed result`);if(!Object.hasOwn(r,"result")){if(Number(r.numResults)===0)return[];throw new c(`Bilibili ${e} returned malformed result(data 键:${Object.keys(r).join(",")||"空"})`)}if(!Array.isArray(r.result))throw new c(`Bilibili ${e} returned malformed result`);return r.result}export async function resolveUser(t,e){if(/^\d+$/.test(e))return{mid:e,name:"",exact:!0};const r=await apiGet(t,"/x/web-interface/wbi/search/type",{params:{search_type:"bili_user",keyword:e},signed:!0}),i=readSearchResults(r,`user search for ${e}`);if(i.length===0)throw new b(`bilibili user search: ${e}`,"User may not exist or username may have changed.");const n=(a)=>stripHtml(String(a?.uname??"")),s=i.find((a)=>n(a)===e),o=s??i[0],u=String(o?.mid??"").trim();if(!u)throw new c(`Bilibili user search returned malformed mid for ${e}`);return{mid:u,name:n(o),exact:Boolean(s)}}export async function resolveUid(t,e){return(await resolveUser(t,e)).mid}export function formatBeijingTime(t){const e=Number(t);if(!t||!Number.isFinite(e))return"";return new Date((e+28800)*1000).toISOString().slice(0,16).replace("T"," ")}export function sleep(t){return new Promise((e)=>setTimeout(e,t))}export function describeReplyVisibility(t){const e=Number.isInteger(t?.state)?t.state:null,r=Number.isInteger(t?.attr)?t.attr:null;let i="unknown";if(e===0)i="public";else if(e===17)i="self-only";return{state:e,attr:r,visibility:i}}export function parseMsgContent(t){const e=String(t??"");try{const r=JSON.parse(e);if(r&&typeof r==="object"){if(typeof r.content==="string")return r.content;if(typeof r.title==="string"||typeof r.text==="string")return[r.title,r.text].filter(Boolean).join(":");return e}}catch{}return e}export function describeDmMessage(t){const e=Number(t?.msg_type??0),r=String(t?.content??"");let i=null;try{i=JSON.parse(r)}catch{}const n=i&&typeof i==="object"&&!Array.isArray(i)?i:null,s=Number(t?.msg_status??0)===1;if(e===5)return{content:`[撤回了一条消息,被撤回消息 msg_key=${r}]`,image_url:"",recalled:!0};if(e===2&&n&&typeof n.url==="string")return{content:"[图片]",image_url:n.url,recalled:s};if(n&&typeof n.pic_url==="string")return{content:[n.title,n.jump_url].filter((o)=>typeof o==="string"&&o).join(" ")||"[图片]",image_url:n.pic_url,recalled:s};return{content:parseMsgContent(r),image_url:"",recalled:s}}
@@ -1 +1 @@
1
- import{cli as r,Strategy as a}from"@jackwener/opencli/registry";import{WWW_BASE as c,getSession as k,postMultipart as m,requireOk as f,resolvePostTarget as s}from"./utils.js";r({site:"nowcoder",name:"like",access:"write",description:"点赞帖子(幂等:已赞不重复操作;--undo 取消赞;有频控,务必低频)",domain:"www.nowcoder.com",strategy:a.COOKIE,args:[{name:"id",positional:!0,required:!0,help:"帖子 id(18 位讨论帖 id / 动态 uuid / 帖子链接 / 7 位 momentId;momentId 读不到当前状态,不判重也不回读)"},{name:"undo",type:"boolean",default:!1,help:"取消赞(默认是确保已赞)"}],columns:["post_id","status","liked","confirmed","like_count","uid","url","note"],func:async(t,d)=>{const e=!d.undo,n=await k(t),i=await s(t,d.id),u=i.liked!==null;if(u&&i.liked===e)return[{post_id:i.id,status:e?"already_liked":"already_unliked",liked:e,confirmed:!0,like_count:i.likeCount??"",uid:n.uid,url:i.url,note:""}];const l=f(await m(t,`${c}${e?"/sns/like":"/sns/del_like"}?_=${Date.now()}`,{id:i.id,type:String(i.entityType)}),e?"点赞":"取消赞",{id:d.id});if(!u)return[{post_id:i.id,status:e?"liked":"unliked",liked:e,confirmed:!1,like_count:l.count??"",uid:n.uid,url:null,note:"未能回读状态:7 位 momentId 查不到点赞状态,写前未判重、写后未核对。"+"要幂等和回读确认请改传该动态的 uuid 或 /feed/main/detail/<uuid> 链接。"}];const o=await s(t,d.id);return[{post_id:i.id,status:e?"liked":"unliked",liked:e,confirmed:o.liked===e,like_count:l.count??o.likeCount??"",uid:n.uid,url:i.url,note:o.liked===e?"":"接口返回成功,但回读到的状态与预期不一致(可能是读缓存延迟);稍后用 like-status 核对,不要立刻重试。"}]}});
1
+ import{cli as m,Strategy as k}from"@jackwener/opencli/registry";import{CliError as f,CommandExecutionError as p}from"@jackwener/opencli/errors";import{WWW_BASE as _,getSession as w,postMultipart as y,requireOk as E,resolvePostTarget as s}from"./utils.js";m({site:"nowcoder",name:"like",access:"write",description:"点赞帖子(幂等:已赞不重复操作;--undo 取消赞;有频控,务必低频)",domain:"www.nowcoder.com",strategy:k.COOKIE,args:[{name:"id",positional:!0,required:!0,help:"帖子 id(18 位讨论帖 id / 动态 uuid / 帖子链接 / 7 位 momentId;momentId 读不到当前状态,不判重也不回读)"},{name:"undo",type:"boolean",default:!1,help:"取消赞(默认是确保已赞)"}],columns:["post_id","status","liked","confirmed","like_count","uid","url","note"],func:async(d,n)=>{const e=!n.undo,o=await w(d),i=await s(d,n.id),r=i.liked!==null;if(r&&i.liked===e)return[{post_id:i.id,status:e?"already_liked":"already_unliked",liked:e,confirmed:!0,like_count:i.likeCount??"",uid:o.uid,url:i.url,note:""}];const c=e?"/sns/like":"/sns/del_like";let u;try{u=await y(d,`${_}${c}?_=${Date.now()}`,{id:i.id,type:String(i.entityType)})}catch(t){if(t instanceof f)throw t;throw new p(`${e?"点赞":"取消赞"}请求未收到平台响应,结果未知:${t instanceof Error?t.message:String(t)}`,r?"可以直接重跑本命令:写前会读取当前状态,已生效时返回 already_liked / already_unliked,不会反向操作。":"7 位 momentId 读不到点赞状态,重跑前请改传该动态的 uuid 或链接,用 like-status 核对后再决定。")}const a=E(u,e?"点赞":"取消赞",{id:n.id});if(!r)return[{post_id:i.id,status:e?"liked":"unliked",liked:e,confirmed:!1,like_count:a.count??"",uid:o.uid,url:null,note:"未能回读状态:7 位 momentId 查不到点赞状态,写前未判重、写后未核对。"+"要幂等和回读确认请改传该动态的 uuid 或 /feed/main/detail/<uuid> 链接。"}];const l=await s(d,n.id);return[{post_id:i.id,status:e?"liked":"unliked",liked:e,confirmed:l.liked===e,like_count:a.count??l.likeCount??"",uid:o.uid,url:i.url,note:l.liked===e?"":"接口返回成功,但回读到的状态与预期不一致(可能是读缓存延迟);稍后用 like-status 核对,不要立刻重试。"}]}});
@@ -1,8 +1,9 @@
1
- import{cli as h,Strategy as d}from"@jackwener/opencli/registry";import{AuthRequiredError as y,CommandExecutionError as a,EmptyResultError as g}from"@jackwener/opencli/errors";import{parseNoteId as w,buildNoteUrl as x}from"./note-helpers.js";import{readXhsDetailPage as b}from"./risk-control.js";import{readCommentPage as _}from"./_shared/comment-state.js";const k='.author-wrapper a[href*="/user/profile/"], a.name[href*="/user/profile/"], a.user-name[href*="/user/profile/"], a[href*="/user/profile/"]';export function parseXhsProfileHref(r,t="www.xiaohongshu.com"){const e=typeof r==="string"?r.trim():"";if(!e)return"";const o=String(t||"www.xiaohongshu.com").toLowerCase();let s;try{s=new URL(e,`https://${o}`)}catch{return""}if(s.protocol!=="https:")return"";if(s.hostname.toLowerCase()!==o)return"";return s.pathname.match(/^\/user\/profile\/([a-zA-Z0-9]+)\/?$/)?.[1]??""}export function buildXhsProfileUrl(r,t="www.xiaohongshu.com"){const e=parseXhsProfileHref(r,t);if(!e)return"";return`https://${t}/user/profile/${e}`}export function parseCommentLimit(r,t=20){const e=Number(r);if(!Number.isFinite(e))return t;return Math.max(1,Math.min(Math.floor(e),50))}export function parseXhsLikeCountText(r){const t=/^(?:\d+|\d{1,3}(?:[,,]\d{3})+)\+?$/u,e=/^((?:\d+|\d{1,3}(?:[,,]\d{3})+)(?:\.\d+)?)([wWkK万千])\+?$/u,o=String(r??"").replace(/\s+/g,"");if(!o)return 0;if(t.test(o))return Number(o.replace(/[,+,]/g,""));const s=o.match(e);if(!s)return 0;const i=Number(s[1].replace(/[,,]/g,""));if(!Number.isFinite(i))return 0;const l=s[2].toLowerCase();return Math.round(i*(l==="w"||l==="万"?1e4:1000))}function c(r,t,e){if(r==null)return"";if(typeof r!=="string")throw new a(`${e}: malformed comment row ${t}`);return r}export function normalizeCommentImages(r,t){if(r==null)return[];if(!Array.isArray(r))throw new a(`${t}: malformed comment row images`);const e=[];for(const o of r){if(typeof o!=="string")throw new a(`${t}: malformed comment row image URL`);const s=o.trim();let i;try{i=new URL(s)}catch{throw new a(`${t}: malformed comment row image URL`)}if(i.protocol!=="https:"&&i.protocol!=="http:"||i.username||i.password)throw new a(`${t}: malformed comment row image URL`);const l=i.toString();if(!e.includes(l))e.push(l)}return e}export function normalizeCommentRows(r,t="xiaohongshu/comments"){if(r==null)return[];if(!Array.isArray(r))throw new a(`${t}: malformed comments payload`);return r.map((e,o)=>{if(!e||typeof e!=="object"||Array.isArray(e))throw new a(`${t}: malformed comment row at index ${o}`);const s=c(e.text,"text",t);if(!s)throw new a(`${t}: malformed comment row text`);const i=Number(e.likes);if(!Number.isInteger(i)||i<0)throw new a(`${t}: malformed comment row likes`);if(typeof e.is_reply!=="boolean")throw new a(`${t}: malformed comment row is_reply`);return{id:e.id??null,root_id:e.root_id??null,parent_id:e.parent_id??null,liked:e.liked??null,reply_count:e.reply_count??null,replies_complete:e.replies_complete??null,author:c(e.author,"author",t),authorHrefRaw:c(e.authorHrefRaw,"authorHrefRaw",t),text:s,likes:i,time:c(e.time,"time",t),is_reply:e.is_reply,reply_to:c(e.reply_to,"reply_to",t),images:normalizeCommentImages(e.images,t)}})}export function compactCommentRow(r){const t={};for(const[e,o]of Object.entries(r)){if(o===null||o===void 0||o==="")continue;if(Array.isArray(o)&&o.length===0)continue;if(e==="root_id"&&o===r.id)continue;t[e]=o}return t}export function buildCommentsExtractJs(r,t=20,e=null){const o=parseXhsLikeCountText.toString();return`
1
+ import{cli as g,Strategy as w}from"@jackwener/opencli/registry";import{AuthRequiredError as x,CommandExecutionError as l,EmptyResultError as b}from"@jackwener/opencli/errors";import{parseNoteId as _,buildNoteUrl as k}from"./note-helpers.js";import{readXhsDetailPage as S}from"./risk-control.js";import{readCommentPage as R}from"./_shared/comment-state.js";const C='.author-wrapper a[href*="/user/profile/"], a.name[href*="/user/profile/"], a.user-name[href*="/user/profile/"], a[href*="/user/profile/"]';export function parseXhsProfileHref(r,t="www.xiaohongshu.com"){const e=typeof r==="string"?r.trim():"";if(!e)return"";const o=String(t||"www.xiaohongshu.com").toLowerCase();let n;try{n=new URL(e,`https://${o}`)}catch{return""}if(n.protocol!=="https:")return"";if(n.hostname.toLowerCase()!==o)return"";return n.pathname.match(/^\/user\/profile\/([a-zA-Z0-9]+)\/?$/)?.[1]??""}export function buildXhsProfileUrl(r,t="www.xiaohongshu.com"){const e=parseXhsProfileHref(r,t);if(!e)return"";return`https://${t}/user/profile/${e}`}export function parseCommentLimit(r,t=20){const e=Number(r);if(!Number.isFinite(e))return t;return Math.max(1,Math.min(Math.floor(e),50))}export function parseRepliesLimit(r,t=3){if(r===void 0||r===null||r==="")return t;const e=Number(r);if(!Number.isFinite(e)||e<0)return t;return Math.floor(e)}export function parseXhsLikeCountText(r){const t=/^(?:\d+|\d{1,3}(?:[,,]\d{3})+)\+?$/u,e=/^((?:\d+|\d{1,3}(?:[,,]\d{3})+)(?:\.\d+)?)([wWkK万千])\+?$/u,o=String(r??"").replace(/\s+/g,"");if(!o)return 0;if(t.test(o))return Number(o.replace(/[,+,]/g,""));const n=o.match(e);if(!n)return 0;const s=Number(n[1].replace(/[,,]/g,""));if(!Number.isFinite(s))return 0;const a=n[2].toLowerCase();return Math.round(s*(a==="w"||a==="万"?1e4:1000))}function u(r,t,e){if(r==null)return"";if(typeof r!=="string")throw new l(`${e}: malformed comment row ${t}`);return r}export function normalizeCommentImages(r,t){if(r==null)return[];if(!Array.isArray(r))throw new l(`${t}: malformed comment row images`);const e=[];for(const o of r){if(typeof o!=="string")throw new l(`${t}: malformed comment row image URL`);const n=o.trim();let s;try{s=new URL(n)}catch{throw new l(`${t}: malformed comment row image URL`)}if(s.protocol!=="https:"&&s.protocol!=="http:"||s.username||s.password)throw new l(`${t}: malformed comment row image URL`);const a=s.toString();if(!e.includes(a))e.push(a)}return e}export function normalizeCommentRows(r,t="xiaohongshu/comments"){if(r==null)return[];if(!Array.isArray(r))throw new l(`${t}: malformed comments payload`);return r.map((e,o)=>{if(!e||typeof e!=="object"||Array.isArray(e))throw new l(`${t}: malformed comment row at index ${o}`);const n=u(e.text,"text",t);if(!n)throw new l(`${t}: malformed comment row text`);const s=Number(e.likes);if(!Number.isInteger(s)||s<0)throw new l(`${t}: malformed comment row likes`);if(typeof e.is_reply!=="boolean")throw new l(`${t}: malformed comment row is_reply`);return{id:e.id??null,root_id:e.root_id??null,parent_id:e.parent_id??null,liked:e.liked??null,reply_count:e.reply_count??null,replies_complete:e.replies_complete??null,author:u(e.author,"author",t),authorHrefRaw:u(e.authorHrefRaw,"authorHrefRaw",t),text:n,likes:s,time:u(e.time,"time",t),is_reply:e.is_reply,reply_to:u(e.reply_to,"reply_to",t),images:normalizeCommentImages(e.images,t)}})}export function compactCommentRow(r){const t={};for(const[e,o]of Object.entries(r)){if(o===null||o===void 0||o==="")continue;if(Array.isArray(o)&&o.length===0)continue;if(e==="root_id"&&o===r.id)continue;t[e]=o}return t}export function buildCommentsExtractJs(r,t=20,e=null,o=0){const n=parseXhsLikeCountText.toString();return`
2
2
  (async () => {
3
3
  const wait = (ms) => new Promise(r => setTimeout(r, ms))
4
4
  const withReplies = ${r}
5
5
  const targetCount = ${Number(t)||20}
6
+ const repliesCap = ${Math.max(0,Math.floor(Number(o)||0))}
6
7
 
7
8
  // Check login state
8
9
  const bodyText = document.body?.innerText || ''
@@ -48,11 +49,11 @@ import{cli as h,Strategy as d}from"@jackwener/opencli/registry";import{AuthRequi
48
49
  }
49
50
 
50
51
  const clean = (el) => (el?.textContent || '').replace(/\\s+/g, ' ').trim()
51
- const parseLikeCountText = ${o}
52
+ const parseLikeCountText = ${n}
52
53
  const parseLikes = (el) => {
53
54
  return parseLikeCountText(clean(el))
54
55
  }
55
- const HREF_SELECTOR = ${JSON.stringify(k)}
56
+ const HREF_SELECTOR = ${JSON.stringify(C)}
56
57
  const extractAuthorHref = (el) => {
57
58
  if (!el) return ''
58
59
  const anchor = el.querySelector(HREF_SELECTOR)
@@ -80,6 +81,7 @@ import{cli as h,Strategy as d}from"@jackwener/opencli/registry";import{AuthRequi
80
81
  const el = root.querySelector('.show-more')
81
82
  if (!el) break
82
83
  const before = root.querySelectorAll('.comment-item-sub').length
84
+ if (repliesCap > 0 && before >= repliesCap) break
83
85
  el.click()
84
86
  let progressed = false
85
87
  for (let attempt = 0; attempt < 10; attempt++) {
@@ -146,7 +148,7 @@ import{cli as h,Strategy as d}from"@jackwener/opencli/registry";import{AuthRequi
146
148
  }
147
149
 
148
150
  if (${JSON.stringify(e)} !== null && !loginWall && !securityBlock) {
149
- const state = (${_.toString()})(${JSON.stringify(e)})
151
+ const state = (${R.toString()})(${JSON.stringify(e)})
150
152
  if (state.error) return { pageUrl: location.href, securityBlock, loginWall, identityError: state.error }
151
153
  for (const row of results) {
152
154
  const entry = state.rows.find(c => c.id === row.id)
@@ -157,4 +159,4 @@ import{cli as h,Strategy as d}from"@jackwener/opencli/registry";import{AuthRequi
157
159
  }
158
160
  return { pageUrl: location.href, securityBlock, loginWall, results }
159
161
  })()
160
- `}export const command=h({site:"xiaohongshu",name:"comments",access:"read",description:"获取小红书笔记评论(支持楼中楼子回复)",domain:"www.xiaohongshu.com",strategy:d.COOKIE,navigateBefore:!1,args:[{name:"note-id",required:!0,positional:!0,help:"Full Xiaohongshu note URL with xsec_token"},{name:"limit",type:"int",default:20,help:"Number of top-level comments (max 50)"},{name:"with-replies",type:"boolean",default:!1,help:"Include nested replies (楼中楼)"}],columns:["rank","id","root_id","parent_id","author","userId","text","likes","liked","time","is_reply","reply_to","reply_count","replies_complete","images"],func:async(r,t)=>{const e=parseCommentLimit(t.limit),o=Boolean(t["with-replies"]),s=String(t["note-id"]),i=w(s),l=await b(r,{url:x(s,{commandName:"xiaohongshu comments"}),extractJs:buildCommentsExtractJs(o,e,i),securityHelp:/^https?:\/\//.test(s)?"The page may be temporarily restricted. Try again later or from a different session.":"Try using a full URL from search results (with xsec_token) instead of a bare note ID."});if(!l||typeof l!=="object")throw new g("xiaohongshu/comments","Unexpected evaluate response");if(l.loginWall)throw new y("www.xiaohongshu.com","Note comments require login");if(l.identityError)throw new a(`xiaohongshu/comments: ${l.identityError}`);const m=normalizeCommentRows(l.results,"xiaohongshu/comments"),p=(n,u)=>compactCommentRow({rank:u+1,id:n.id,root_id:n.root_id,parent_id:n.parent_id,author:n.author,userId:n.authorHrefRaw?parseXhsProfileHref(n.authorHrefRaw):"",text:n.text,likes:n.likes,liked:n.liked,time:n.time,is_reply:n.is_reply,reply_to:n.reply_to,reply_count:n.reply_count,replies_complete:n.replies_complete,images:n.images??[]});if(o){const n=[];let u=0;for(const f of m){if(!f.is_reply)u++;if(u>e)break;n.push(f)}return n.map(p)}return m.slice(0,e).map(p)}});
162
+ `}export const command=g({site:"xiaohongshu",name:"comments",access:"read",description:"获取小红书笔记评论(支持楼中楼子回复)",domain:"www.xiaohongshu.com",strategy:w.COOKIE,navigateBefore:!1,args:[{name:"note-id",required:!0,positional:!0,help:"Full Xiaohongshu note URL with xsec_token"},{name:"limit",type:"int",default:20,help:"Number of top-level comments (max 50)"},{name:"with-replies",type:"boolean",default:!1,help:"Include nested replies (楼中楼)"},{name:"replies-limit",type:"int",default:3,help:"With --with-replies: max nested replies per top-level comment (default 3, 0 = all). Capped threads show replies_complete=false; read a whole thread with `replies <url> <root-id>`"}],columns:["rank","id","root_id","parent_id","author","userId","text","likes","liked","time","is_reply","reply_to","reply_count","replies_complete","images"],func:async(r,t)=>{const e=parseCommentLimit(t.limit),o=Boolean(t["with-replies"]),n=parseRepliesLimit(t["replies-limit"]),s=String(t["note-id"]),a=_(s),c=await S(r,{url:k(s,{commandName:"xiaohongshu comments"}),extractJs:buildCommentsExtractJs(o,e,a,n),securityHelp:/^https?:\/\//.test(s)?"The page may be temporarily restricted. Try again later or from a different session.":"Try using a full URL from search results (with xsec_token) instead of a bare note ID."});if(!c||typeof c!=="object")throw new b("xiaohongshu/comments","Unexpected evaluate response");if(c.loginWall)throw new x("www.xiaohongshu.com","Note comments require login");if(c.identityError)throw new l(`xiaohongshu/comments: ${c.identityError}`);const d=normalizeCommentRows(c.results,"xiaohongshu/comments"),y=(i,m)=>compactCommentRow({rank:m+1,id:i.id,root_id:i.root_id,parent_id:i.parent_id,author:i.author,userId:i.authorHrefRaw?parseXhsProfileHref(i.authorHrefRaw):"",text:i.text,likes:i.likes,liked:i.liked,time:i.time,is_reply:i.is_reply,reply_to:i.reply_to,reply_count:i.reply_count,replies_complete:i.replies_complete,images:i.images??[]});if(o){const i=[];let m=0,p=null,f=0;for(const h of d){if(!h.is_reply){m++;if(m>e)break;p={...h};f=0;i.push(p);continue}if(n>0&&f>=n){if(p)p.replies_complete=!1;continue}f++;i.push(h)}return i.map(y)}return d.slice(0,e).map(y)}});
@@ -1 +1 @@
1
- import{WebSocket as p}from"ws";import{request as _}from"node:http";import{request as y}from"node:https";import{buildEvaluateExpression as b}from"./utils.js";import{generateStealthJs as E}from"./stealth.js";import{waitForDomStableJs as v,keyEventMetadata as C}from"./dom-helpers.js";import{isRecord as l,saveBase64ToFile as k}from"../utils.js";import{getAllElectronApps as P}from"../electron-apps.js";import{BasePage as S}from"./base-page.js";const I=30000;export const CDP_RESPONSE_BODY_CAPTURE_LIMIT=8388608,CDP_STREAM_FRAME_CAPTURE_LIMIT=262144,STREAM_FRAME_LIMIT=1000;export class CDPBridge{_ws=null;_idCounter=0;_pending=new Map;_eventListeners=new Map;async connect(e){if(this._ws)throw Error("CDPBridge is already connected. Call close() before reconnecting.");const s=e?.cdpEndpoint??process.env.OPENCLI_CDP_ENDPOINT;if(!s)throw Error("CDP endpoint not provided (pass cdpEndpoint or set OPENCLI_CDP_ENDPOINT)");let n=s;if(s.startsWith("http")){const t=await M(`${s.replace(/\/$/,"")}/json`),r=g(t);if(!r||!r.webSocketDebuggerUrl)throw Error("No inspectable targets found at CDP endpoint");n=r.webSocketDebuggerUrl}return new Promise((t,r)=>{const i=new p(n),o=(e?.timeout??10)*1000,d=setTimeout(()=>{this._ws=null;i.close();r(Error("CDP connect timeout"))},o);i.on("open",async()=>{clearTimeout(d);this._ws=i;try{await this.send("Page.enable");this.on("Page.javascriptDialogOpening",(c)=>{if(c?.type==="beforeunload")this.send("Page.handleJavaScriptDialog",{accept:!0}).catch(()=>{})});await this.send("Page.addScriptToEvaluateOnNewDocument",{source:E()});if(e?.initScript)await this.send("Page.addScriptToEvaluateOnNewDocument",{source:e.initScript});if(e?.windowMode==="background")await this.send("Emulation.setFocusEmulationEnabled",{enabled:!0}).catch(()=>{});else if(e?.windowMode==="foreground")await this.send("Page.bringToFront").catch(()=>{});if(e?.proxyAuth){this.on("Fetch.requestPaused",(c)=>{const u=c;if(u.requestId)this.send("Fetch.continueRequest",{requestId:u.requestId}).catch(()=>{})});this.on("Fetch.authRequired",(c)=>{const u=c;if(!u.requestId)return;this.send("Fetch.continueWithAuth",{requestId:u.requestId,authChallengeResponse:{response:"ProvideCredentials",username:e.proxyAuth.username,password:e.proxyAuth.password}}).catch(()=>{})});await this.send("Fetch.enable",{handleAuthRequests:!0})}}catch(c){i.close();r(c instanceof Error?c:Error(String(c)));return}const a=new m(this);if(e?.session)a.session=e.session;if(e?.contextId)a.contextId=e.contextId;t(a)});i.on("error",(a)=>{clearTimeout(d);r(a)});i.on("message",(a)=>{try{const c=JSON.parse(a.toString());if(c.id&&this._pending.has(c.id)){const u=this._pending.get(c.id);clearTimeout(u.timer);this._pending.delete(c.id);if(c.error)u.reject(Error(c.error.message));else u.resolve(c.result)}if(c.method){const u=this._eventListeners.get(c.method);if(u)for(const h of u)h(c.params)}}catch(c){if(process.env.OPENCLI_VERBOSE)console.error("[cdp] Failed to parse WebSocket message:",c instanceof Error?c.message:c)}})})}async close(){if(this._ws){this._ws.close();this._ws=null}for(const e of this._pending.values()){clearTimeout(e.timer);e.reject(Error("CDP connection closed"))}this._pending.clear();this._eventListeners.clear()}async send(e,s={},n=I){if(!this._ws||this._ws.readyState!==p.OPEN)throw Error("CDP connection is not open");const t=++this._idCounter;return new Promise((r,i)=>{const o=setTimeout(()=>{this._pending.delete(t);const d=e.startsWith("Page.")?"(页面可能被 JS 弹窗挡住:试 `ppcli browser dialog accept`;托管 profile 可 `ppcli profile stop <name>` 关闭后重跑命令自动重启会话)":"";i(Error(`CDP command '${e}' timed out after ${n/1000}s${d}`))},n);this._pending.set(t,{resolve:r,reject:i,timer:o});this._ws.send(JSON.stringify({id:t,method:e,params:s}))})}on(e,s){let n=this._eventListeners.get(e);if(!n){n=new Set;this._eventListeners.set(e,n)}n.add(s)}off(e,s){this._eventListeners.get(e)?.delete(s)}waitForEvent(e,s=15000){return new Promise((n,t)=>{const r=setTimeout(()=>{this.off(e,i);t(Error(`Timed out waiting for CDP event '${e}'`))},s),i=(o)=>{clearTimeout(r);this.off(e,i);n(o)};this.on(e,i)})}}class m extends S{bridge;session;contextId;_pageEnabled=!1;_networkCapturing=!1;_networkCapturePattern="";_networkEntries=[];_streamFrames=[];_streamFramesDropped=0;_streamUrls=new Map;_pendingRequests=new Map;_pendingBodyFetches=new Set;_consoleMessages=[];_consoleCapturing=!1;constructor(e){super();this.bridge=e}async goto(e,s){if(!this._pageEnabled){await this.bridge.send("Page.enable");this._pageEnabled=!0}const n=this.bridge.waitForEvent("Page.loadEventFired",30000).catch(()=>{});await this.bridge.send("Page.navigate",{url:e});await n;this._lastUrl=e;if(s?.waitUntil!=="none"){const t=s?.settleMs??1000;await this.evaluate(v(t,Math.min(500,t)))}}async evaluate(e,...s){const n=b(e,s),t=await this.bridge.send("Runtime.evaluate",{expression:n,returnByValue:!0,awaitPromise:!0});if(t.exceptionDetails)throw Error("Evaluate error: "+(t.exceptionDetails.exception?.description||"Unknown exception"));return t.result?.value}async getCookies(e={}){let s;try{const t=await this.bridge.send("Storage.getCookies");s=l(t)&&Array.isArray(t.cookies)?t.cookies:[]}catch{const t=await this.bridge.send("Network.getCookies",e.url?{urls:[e.url]}:{});s=l(t)&&Array.isArray(t.cookies)?t.cookies:[]}const n=e.domain??(e.url?N(e.url):void 0);return n?s.filter((t)=>f(t)&&D(t.domain,n)):s.filter(f)}async screenshot(e={}){const s=e.fullPage===!0,n=e.width&&e.width>0?Math.ceil(e.width):void 0,t=!s&&e.height&&e.height>0?Math.ceil(e.height):void 0,r=n!==void 0||t!==void 0;if(r){if(n!==void 0&&s)await this.bridge.send("Emulation.setDeviceMetricsOverride",{mobile:!1,width:n,height:0,deviceScaleFactor:1});let i=n??0,o=t??0;if(s){const d=await this.bridge.send("Page.getLayoutMetrics"),a=l(d)?d:{},c=l(a.cssContentSize)?a.cssContentSize:void 0,u=l(a.contentSize)?a.contentSize:void 0,h=c??u;if(h&&typeof h.width==="number"&&typeof h.height==="number"){if(i===0)i=Math.ceil(h.width);o=Math.ceil(h.height)}}await this.bridge.send("Emulation.setDeviceMetricsOverride",{mobile:!1,width:i,height:o,deviceScaleFactor:1})}try{const i=await this.bridge.send("Page.captureScreenshot",{format:e.format??"png",quality:e.format==="jpeg"?e.quality??80:void 0,captureBeyondViewport:!r&&s}),o=l(i)&&typeof i.data==="string"?i.data:"";if(e.path)await k(o,e.path);return o}finally{if(r)await this.bridge.send("Emulation.clearDeviceMetricsOverride").catch(()=>{})}}async startNetworkCapture(e=""){this._networkCapturePattern=e;if(!this._networkCapturing){this._networkEntries=[];this._streamFrames=[];this._streamFramesDropped=0;this._streamUrls.clear();this._pendingRequests.clear();this._pendingBodyFetches.clear();await this.bridge.send("Network.enable");this.bridge.on("Network.requestWillBeSent",(n)=>{const t=n;if(!this._networkCapturePattern||t.request.url.includes(this._networkCapturePattern)){const r=this._networkEntries.push({url:t.request.url,method:t.request.method,timestamp:Date.now()})-1;this._pendingRequests.set(t.requestId,r)}});this.bridge.on("Network.responseReceived",(n)=>{const t=n;if(t.requestId&&t.response?.mimeType==="text/event-stream")this._streamUrls.set(t.requestId,String(t.response.url||""));const r=this._pendingRequests.get(t.requestId);if(r!==void 0){this._networkEntries[r].responseStatus=t.response.status;this._networkEntries[r].responseContentType=t.response.mimeType||""}});this.bridge.on("Network.loadingFinished",(n)=>{const t=n,r=this._pendingRequests.get(t.requestId);if(r!==void 0){const i=this.bridge.send("Network.getResponseBody",{requestId:t.requestId}).then((o)=>{const d=o;if(typeof d?.body==="string"){const a=d.body.length,c=a>CDP_RESPONSE_BODY_CAPTURE_LIMIT,u=c?d.body.slice(0,CDP_RESPONSE_BODY_CAPTURE_LIMIT):d.body;this._networkEntries[r].responsePreview=d.base64Encoded?`base64:${u}`:u;this._networkEntries[r].responseBodyFullSize=a;this._networkEntries[r].responseBodyTruncated=c}}).catch((o)=>{if(process.env.OPENCLI_VERBOSE)console.error(`[cdp] getResponseBody failed for ${t.requestId}:`,o instanceof Error?o.message:o)}).finally(()=>{this._pendingBodyFetches.delete(i)});this._pendingBodyFetches.add(i);this._pendingRequests.delete(t.requestId)}});this.bridge.on("Network.webSocketCreated",(n)=>{const t=n;if(t?.requestId)this._streamUrls.set(t.requestId,String(t.url||""))});const s=(n)=>(t)=>{const r=t,i=Number(r?.response?.opcode??1);if(i!==1&&i!==2)return;this._pushStreamFrame(r.requestId,{channel:"websocket",direction:n,payload:String(r?.response?.payloadData||""),binary:i===2})};this.bridge.on("Network.webSocketFrameReceived",s("received"));this.bridge.on("Network.webSocketFrameSent",s("sent"));this.bridge.on("Network.webSocketClosed",(n)=>{const t=n;if(t?.requestId)this._streamUrls.delete(t.requestId)});this.bridge.on("Network.eventSourceMessageReceived",(n)=>{const t=n;this._pushStreamFrame(t.requestId,{channel:"eventsource",direction:"received",payload:String(t?.data||""),eventName:t?.eventName?String(t.eventName):void 0,eventId:t?.eventId?String(t.eventId):void 0})});this._networkCapturing=!0}return!0}_pushStreamFrame(e,s){const n=this._streamUrls.get(e)||`${s.channel==="websocket"?"ws":"sse"}://unknown/${e}`;if(this._networkCapturePattern&&!n.includes(this._networkCapturePattern))return;const t=String(s.payload??""),r=t.length,i=r>CDP_STREAM_FRAME_CAPTURE_LIMIT,o=i?t.slice(0,CDP_STREAM_FRAME_CAPTURE_LIMIT):t,d={url:n,method:s.channel==="websocket"?"WS":"SSE",channel:s.channel,direction:s.direction,responseStatus:200,responseContentType:s.binary?"application/octet-stream":"text/plain",responsePreview:s.binary?`base64:${o}`:o,responseBodyFullSize:r,responseBodyTruncated:i,timestamp:Date.now()};if(s.eventName)d.eventName=s.eventName;if(s.eventId)d.eventId=s.eventId;this._streamFrames.push(d);while(this._streamFrames.length>STREAM_FRAME_LIMIT){this._streamFrames.shift();this._streamFramesDropped++}}async readNetworkCapture(){if(this._pendingBodyFetches.size>0)await Promise.all([...this._pendingBodyFetches]);const e=[...this._networkEntries];this._networkEntries=[];const s=[...this._streamFrames];this._streamFrames=[];if(this._streamFramesDropped){if(process.env.OPENCLI_VERBOSE)console.error(`[cdp] dropped ${this._streamFramesDropped} stream frames over the ${STREAM_FRAME_LIMIT} buffer cap`);this._streamFramesDropped=0}return e.concat(s)}async consoleMessages(e="all"){if(!this._consoleCapturing){await this.bridge.send("Runtime.enable");this.bridge.on("Runtime.consoleAPICalled",(s)=>{const n=s,t=(n.args||[]).map((r)=>r.value!==void 0?String(r.value):r.description||"").join(" ");this._consoleMessages.push({type:n.type,text:t,timestamp:Date.now()});if(this._consoleMessages.length>500)this._consoleMessages.shift()});this.bridge.on("Runtime.exceptionThrown",(s)=>{const n=s,t=n.exceptionDetails?.exception?.description||n.exceptionDetails?.text||"Unknown exception";this._consoleMessages.push({type:"error",text:t,timestamp:Date.now()});if(this._consoleMessages.length>500)this._consoleMessages.shift()});this._consoleCapturing=!0}if(e==="all")return[...this._consoleMessages];if(e==="error")return this._consoleMessages.filter((s)=>s.type==="error"||s.type==="warning");return this._consoleMessages.filter((s)=>s.type===e)}async tabs(){return[]}async selectTab(e){}async cdp(e,s={}){return this.bridge.send(e,s)}async handleJavaScriptDialog(e,s){await this.cdp("Page.handleJavaScriptDialog",{accept:e,...s!==void 0&&{promptText:s}})}async nativeClick(e,s){await this.cdp("Input.dispatchMouseEvent",{type:"mouseMoved",x:e,y:s});await this.cdp("Input.dispatchMouseEvent",{type:"mousePressed",x:e,y:s,button:"left",clickCount:1});await this.cdp("Input.dispatchMouseEvent",{type:"mouseReleased",x:e,y:s,button:"left",clickCount:1})}async nativeType(e){await this.cdp("Input.insertText",{text:e})}async insertText(e){await this.nativeType(e)}async nativeKeyPress(e,s=[]){let n=0;for(const r of s){if(r==="Alt")n|=1;if(r==="Ctrl"||r==="Control")n|=2;if(r==="Meta")n|=4;if(r==="Shift")n|=8}const t=C(e,s);await this.cdp("Input.dispatchKeyEvent",{type:"keyDown",key:e,modifiers:n,...t});await this.cdp("Input.dispatchKeyEvent",{type:"keyUp",key:e,modifiers:n,...t.code?{code:t.code}:{},...t.windowsVirtualKeyCode?{windowsVirtualKeyCode:t.windowsVirtualKeyCode,nativeVirtualKeyCode:t.windowsVirtualKeyCode}:{}})}}function N(e){try{return new URL(e).hostname}catch{return}}function f(e){return l(e)&&typeof e.name==="string"&&typeof e.value==="string"&&typeof e.domain==="string"}function D(e,s){const n=e.replace(/^\./,"").toLowerCase(),t=s.replace(/^\./,"").toLowerCase();return t===n||t.endsWith(`.${n}`)}function g(e){const s=F(process.env.OPENCLI_CDP_TARGET);return e.map((t,r)=>({target:t,index:r,score:w(t,s)})).filter(({score:t})=>Number.isFinite(t)).sort((t,r)=>{if(r.score!==t.score)return r.score-t.score;return t.index-r.index})[0]?.target}function w(e,s){if(!e.webSocketDebuggerUrl)return Number.NEGATIVE_INFINITY;const n=(e.type??"").toLowerCase(),t=(e.url??"").toLowerCase(),r=(e.title??"").toLowerCase(),i=`${r} ${t}`;if(!i.trim()&&!n)return Number.NEGATIVE_INFINITY;if(i.includes("devtools"))return Number.NEGATIVE_INFINITY;if(n==="background_page"||n==="service_worker")return Number.NEGATIVE_INFINITY;let o=0;if(s&&s.test(i))o+=1000;if(n==="app")o+=120;else if(n==="webview")o+=100;else if(n==="page")o+=80;else if(n==="iframe")o+=20;if(t.startsWith("http://localhost")||t.startsWith("https://localhost"))o+=90;if(t.startsWith("file://"))o+=60;if(t.startsWith("http://127.0.0.1")||t.startsWith("https://127.0.0.1"))o+=50;if(t.startsWith("about:blank"))o-=120;if(t===""||t==="about:blank")o-=40;if(r&&r!=="devtools")o+=25;const d=Object.values(P()).map((a)=>(a.displayName??a.processName).toLowerCase());for(const a of d)if(r.includes(a)){o+=120;break}for(const a of d)if(t.includes(a)){o+=100;break}return o}function F(e){const s=e?.trim();if(!s)return;return new RegExp(T(s.toLowerCase()))}function T(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export const __test__={selectCDPTarget:g,scoreCDPTarget:w};function M(e){return new Promise((s,n)=>{const t=new URL(e),r=(t.protocol==="https:"?y:_)(t,(i)=>{const o=i.statusCode??0;if(o<200||o>=300){i.resume();n(Error(`Failed to fetch CDP targets: HTTP ${o}`));return}const d=[];i.on("data",(a)=>d.push(Buffer.isBuffer(a)?a:Buffer.from(a)));i.on("end",()=>{try{s(JSON.parse(Buffer.concat(d).toString("utf8")))}catch(a){n(a instanceof Error?a:Error(String(a)))}})});r.on("error",n);r.setTimeout(1e4,()=>r.destroy(Error("Timed out fetching CDP targets")));r.end()})}
1
+ import{WebSocket as p}from"ws";import{request as _}from"node:http";import{request as y}from"node:https";import{buildEvaluateExpression as b}from"./utils.js";import{generateStealthJs as E}from"./stealth.js";import{waitForDomStableJs as v,keyEventMetadata as C}from"./dom-helpers.js";import{isRecord as l,saveBase64ToFile as k}from"../utils.js";import{getAllElectronApps as P}from"../electron-apps.js";import{BasePage as S}from"./base-page.js";import{pageEvaluateTimeoutMs as I}from"./daemon-client.js";const N=30000;export const CDP_RESPONSE_BODY_CAPTURE_LIMIT=8388608,CDP_STREAM_FRAME_CAPTURE_LIMIT=262144,STREAM_FRAME_LIMIT=1000;export class CDPBridge{_ws=null;_idCounter=0;_pending=new Map;_eventListeners=new Map;async connect(e){if(this._ws)throw Error("CDPBridge is already connected. Call close() before reconnecting.");const s=e?.cdpEndpoint??process.env.OPENCLI_CDP_ENDPOINT;if(!s)throw Error("CDP endpoint not provided (pass cdpEndpoint or set OPENCLI_CDP_ENDPOINT)");let n=s;if(s.startsWith("http")){const t=await q(`${s.replace(/\/$/,"")}/json`),r=g(t);if(!r||!r.webSocketDebuggerUrl)throw Error("No inspectable targets found at CDP endpoint");n=r.webSocketDebuggerUrl}return new Promise((t,r)=>{const i=new p(n),o=(e?.timeout??10)*1000,d=setTimeout(()=>{this._ws=null;i.close();r(Error("CDP connect timeout"))},o);i.on("open",async()=>{clearTimeout(d);this._ws=i;try{await this.send("Page.enable");this.on("Page.javascriptDialogOpening",(c)=>{if(c?.type==="beforeunload")this.send("Page.handleJavaScriptDialog",{accept:!0}).catch(()=>{})});await this.send("Page.addScriptToEvaluateOnNewDocument",{source:E()});if(e?.initScript)await this.send("Page.addScriptToEvaluateOnNewDocument",{source:e.initScript});if(e?.windowMode==="background")await this.send("Emulation.setFocusEmulationEnabled",{enabled:!0}).catch(()=>{});else if(e?.windowMode==="foreground")await this.send("Page.bringToFront").catch(()=>{});if(e?.proxyAuth){this.on("Fetch.requestPaused",(c)=>{const u=c;if(u.requestId)this.send("Fetch.continueRequest",{requestId:u.requestId}).catch(()=>{})});this.on("Fetch.authRequired",(c)=>{const u=c;if(!u.requestId)return;this.send("Fetch.continueWithAuth",{requestId:u.requestId,authChallengeResponse:{response:"ProvideCredentials",username:e.proxyAuth.username,password:e.proxyAuth.password}}).catch(()=>{})});await this.send("Fetch.enable",{handleAuthRequests:!0})}}catch(c){i.close();r(c instanceof Error?c:Error(String(c)));return}const a=new w(this);if(e?.session)a.session=e.session;if(e?.contextId)a.contextId=e.contextId;t(a)});i.on("error",(a)=>{clearTimeout(d);r(a)});i.on("message",(a)=>{try{const c=JSON.parse(a.toString());if(c.id&&this._pending.has(c.id)){const u=this._pending.get(c.id);clearTimeout(u.timer);this._pending.delete(c.id);if(c.error)u.reject(Error(c.error.message));else u.resolve(c.result)}if(c.method){const u=this._eventListeners.get(c.method);if(u)for(const h of u)h(c.params)}}catch(c){if(process.env.OPENCLI_VERBOSE)console.error("[cdp] Failed to parse WebSocket message:",c instanceof Error?c.message:c)}})})}async close(){if(this._ws){this._ws.close();this._ws=null}for(const e of this._pending.values()){clearTimeout(e.timer);e.reject(Error("CDP connection closed"))}this._pending.clear();this._eventListeners.clear()}async send(e,s={},n=N){if(!this._ws||this._ws.readyState!==p.OPEN)throw Error("CDP connection is not open");const t=++this._idCounter;return new Promise((r,i)=>{const o=setTimeout(()=>{this._pending.delete(t);const d=e.startsWith("Page.")?"(页面可能被 JS 弹窗挡住:试 `ppcli browser dialog accept`;托管 profile 可 `ppcli profile stop <name>` 关闭后重跑命令自动重启会话)":"";i(Error(`CDP command '${e}' timed out after ${n/1000}s${d}`))},n);this._pending.set(t,{resolve:r,reject:i,timer:o});this._ws.send(JSON.stringify({id:t,method:e,params:s}))})}on(e,s){let n=this._eventListeners.get(e);if(!n){n=new Set;this._eventListeners.set(e,n)}n.add(s)}off(e,s){this._eventListeners.get(e)?.delete(s)}waitForEvent(e,s=15000){return new Promise((n,t)=>{const r=setTimeout(()=>{this.off(e,i);t(Error(`Timed out waiting for CDP event '${e}'`))},s),i=(o)=>{clearTimeout(r);this.off(e,i);n(o)};this.on(e,i)})}}class w extends S{bridge;session;contextId;_pageEnabled=!1;_networkCapturing=!1;_networkCapturePattern="";_networkEntries=[];_streamFrames=[];_streamFramesDropped=0;_streamUrls=new Map;_pendingRequests=new Map;_pendingBodyFetches=new Set;_consoleMessages=[];_consoleCapturing=!1;constructor(e){super();this.bridge=e}async goto(e,s){if(!this._pageEnabled){await this.bridge.send("Page.enable");this._pageEnabled=!0}const n=this.bridge.waitForEvent("Page.loadEventFired",30000).catch(()=>{});await this.bridge.send("Page.navigate",{url:e});await n;this._lastUrl=e;if(s?.waitUntil!=="none"){const t=s?.settleMs??1000;await this.evaluate(v(t,Math.min(500,t)))}}async evaluate(e,...s){const n=b(e,s),t=await this.bridge.send("Runtime.evaluate",{expression:n,returnByValue:!0,awaitPromise:!0},I());if(t.exceptionDetails)throw Error("Evaluate error: "+(t.exceptionDetails.exception?.description||"Unknown exception"));return t.result?.value}async getCookies(e={}){let s;try{const t=await this.bridge.send("Storage.getCookies");s=l(t)&&Array.isArray(t.cookies)?t.cookies:[]}catch{const t=await this.bridge.send("Network.getCookies",e.url?{urls:[e.url]}:{});s=l(t)&&Array.isArray(t.cookies)?t.cookies:[]}const n=e.domain??(e.url?D(e.url):void 0);return n?s.filter((t)=>f(t)&&F(t.domain,n)):s.filter(f)}async screenshot(e={}){const s=e.fullPage===!0,n=e.width&&e.width>0?Math.ceil(e.width):void 0,t=!s&&e.height&&e.height>0?Math.ceil(e.height):void 0,r=n!==void 0||t!==void 0;if(r){if(n!==void 0&&s)await this.bridge.send("Emulation.setDeviceMetricsOverride",{mobile:!1,width:n,height:0,deviceScaleFactor:1});let i=n??0,o=t??0;if(s){const d=await this.bridge.send("Page.getLayoutMetrics"),a=l(d)?d:{},c=l(a.cssContentSize)?a.cssContentSize:void 0,u=l(a.contentSize)?a.contentSize:void 0,h=c??u;if(h&&typeof h.width==="number"&&typeof h.height==="number"){if(i===0)i=Math.ceil(h.width);o=Math.ceil(h.height)}}await this.bridge.send("Emulation.setDeviceMetricsOverride",{mobile:!1,width:i,height:o,deviceScaleFactor:1})}try{const i=await this.bridge.send("Page.captureScreenshot",{format:e.format??"png",quality:e.format==="jpeg"?e.quality??80:void 0,captureBeyondViewport:!r&&s}),o=l(i)&&typeof i.data==="string"?i.data:"";if(e.path)await k(o,e.path);return o}finally{if(r)await this.bridge.send("Emulation.clearDeviceMetricsOverride").catch(()=>{})}}async startNetworkCapture(e=""){this._networkCapturePattern=e;if(!this._networkCapturing){this._networkEntries=[];this._streamFrames=[];this._streamFramesDropped=0;this._streamUrls.clear();this._pendingRequests.clear();this._pendingBodyFetches.clear();await this.bridge.send("Network.enable");this.bridge.on("Network.requestWillBeSent",(n)=>{const t=n;if(!this._networkCapturePattern||t.request.url.includes(this._networkCapturePattern)){const r=this._networkEntries.push({url:t.request.url,method:t.request.method,timestamp:Date.now()})-1;this._pendingRequests.set(t.requestId,r)}});this.bridge.on("Network.responseReceived",(n)=>{const t=n;if(t.requestId&&t.response?.mimeType==="text/event-stream")this._streamUrls.set(t.requestId,String(t.response.url||""));const r=this._pendingRequests.get(t.requestId);if(r!==void 0){this._networkEntries[r].responseStatus=t.response.status;this._networkEntries[r].responseContentType=t.response.mimeType||""}});this.bridge.on("Network.loadingFinished",(n)=>{const t=n,r=this._pendingRequests.get(t.requestId);if(r!==void 0){const i=this.bridge.send("Network.getResponseBody",{requestId:t.requestId}).then((o)=>{const d=o;if(typeof d?.body==="string"){const a=d.body.length,c=a>CDP_RESPONSE_BODY_CAPTURE_LIMIT,u=c?d.body.slice(0,CDP_RESPONSE_BODY_CAPTURE_LIMIT):d.body;this._networkEntries[r].responsePreview=d.base64Encoded?`base64:${u}`:u;this._networkEntries[r].responseBodyFullSize=a;this._networkEntries[r].responseBodyTruncated=c}}).catch((o)=>{if(process.env.OPENCLI_VERBOSE)console.error(`[cdp] getResponseBody failed for ${t.requestId}:`,o instanceof Error?o.message:o)}).finally(()=>{this._pendingBodyFetches.delete(i)});this._pendingBodyFetches.add(i);this._pendingRequests.delete(t.requestId)}});this.bridge.on("Network.webSocketCreated",(n)=>{const t=n;if(t?.requestId)this._streamUrls.set(t.requestId,String(t.url||""))});const s=(n)=>(t)=>{const r=t,i=Number(r?.response?.opcode??1);if(i!==1&&i!==2)return;this._pushStreamFrame(r.requestId,{channel:"websocket",direction:n,payload:String(r?.response?.payloadData||""),binary:i===2})};this.bridge.on("Network.webSocketFrameReceived",s("received"));this.bridge.on("Network.webSocketFrameSent",s("sent"));this.bridge.on("Network.webSocketClosed",(n)=>{const t=n;if(t?.requestId)this._streamUrls.delete(t.requestId)});this.bridge.on("Network.eventSourceMessageReceived",(n)=>{const t=n;this._pushStreamFrame(t.requestId,{channel:"eventsource",direction:"received",payload:String(t?.data||""),eventName:t?.eventName?String(t.eventName):void 0,eventId:t?.eventId?String(t.eventId):void 0})});this._networkCapturing=!0}return!0}_pushStreamFrame(e,s){const n=this._streamUrls.get(e)||`${s.channel==="websocket"?"ws":"sse"}://unknown/${e}`;if(this._networkCapturePattern&&!n.includes(this._networkCapturePattern))return;const t=String(s.payload??""),r=t.length,i=r>CDP_STREAM_FRAME_CAPTURE_LIMIT,o=i?t.slice(0,CDP_STREAM_FRAME_CAPTURE_LIMIT):t,d={url:n,method:s.channel==="websocket"?"WS":"SSE",channel:s.channel,direction:s.direction,responseStatus:200,responseContentType:s.binary?"application/octet-stream":"text/plain",responsePreview:s.binary?`base64:${o}`:o,responseBodyFullSize:r,responseBodyTruncated:i,timestamp:Date.now()};if(s.eventName)d.eventName=s.eventName;if(s.eventId)d.eventId=s.eventId;this._streamFrames.push(d);while(this._streamFrames.length>STREAM_FRAME_LIMIT){this._streamFrames.shift();this._streamFramesDropped++}}async readNetworkCapture(){if(this._pendingBodyFetches.size>0)await Promise.all([...this._pendingBodyFetches]);const e=[...this._networkEntries];this._networkEntries=[];const s=[...this._streamFrames];this._streamFrames=[];if(this._streamFramesDropped){if(process.env.OPENCLI_VERBOSE)console.error(`[cdp] dropped ${this._streamFramesDropped} stream frames over the ${STREAM_FRAME_LIMIT} buffer cap`);this._streamFramesDropped=0}return e.concat(s)}async consoleMessages(e="all"){if(!this._consoleCapturing){await this.bridge.send("Runtime.enable");this.bridge.on("Runtime.consoleAPICalled",(s)=>{const n=s,t=(n.args||[]).map((r)=>r.value!==void 0?String(r.value):r.description||"").join(" ");this._consoleMessages.push({type:n.type,text:t,timestamp:Date.now()});if(this._consoleMessages.length>500)this._consoleMessages.shift()});this.bridge.on("Runtime.exceptionThrown",(s)=>{const n=s,t=n.exceptionDetails?.exception?.description||n.exceptionDetails?.text||"Unknown exception";this._consoleMessages.push({type:"error",text:t,timestamp:Date.now()});if(this._consoleMessages.length>500)this._consoleMessages.shift()});this._consoleCapturing=!0}if(e==="all")return[...this._consoleMessages];if(e==="error")return this._consoleMessages.filter((s)=>s.type==="error"||s.type==="warning");return this._consoleMessages.filter((s)=>s.type===e)}async tabs(){return[]}async selectTab(e){}async cdp(e,s={}){return this.bridge.send(e,s)}async handleJavaScriptDialog(e,s){await this.cdp("Page.handleJavaScriptDialog",{accept:e,...s!==void 0&&{promptText:s}})}async nativeClick(e,s){await this.cdp("Input.dispatchMouseEvent",{type:"mouseMoved",x:e,y:s});await this.cdp("Input.dispatchMouseEvent",{type:"mousePressed",x:e,y:s,button:"left",clickCount:1});await this.cdp("Input.dispatchMouseEvent",{type:"mouseReleased",x:e,y:s,button:"left",clickCount:1})}async nativeType(e){await this.cdp("Input.insertText",{text:e})}async insertText(e){await this.nativeType(e)}async nativeKeyPress(e,s=[]){let n=0;for(const r of s){if(r==="Alt")n|=1;if(r==="Ctrl"||r==="Control")n|=2;if(r==="Meta")n|=4;if(r==="Shift")n|=8}const t=C(e,s);await this.cdp("Input.dispatchKeyEvent",{type:"keyDown",key:e,modifiers:n,...t});await this.cdp("Input.dispatchKeyEvent",{type:"keyUp",key:e,modifiers:n,...t.code?{code:t.code}:{},...t.windowsVirtualKeyCode?{windowsVirtualKeyCode:t.windowsVirtualKeyCode,nativeVirtualKeyCode:t.windowsVirtualKeyCode}:{}})}}function D(e){try{return new URL(e).hostname}catch{return}}function f(e){return l(e)&&typeof e.name==="string"&&typeof e.value==="string"&&typeof e.domain==="string"}function F(e,s){const n=e.replace(/^\./,"").toLowerCase(),t=s.replace(/^\./,"").toLowerCase();return t===n||t.endsWith(`.${n}`)}function g(e){const s=T(process.env.OPENCLI_CDP_TARGET);return e.map((t,r)=>({target:t,index:r,score:m(t,s)})).filter(({score:t})=>Number.isFinite(t)).sort((t,r)=>{if(r.score!==t.score)return r.score-t.score;return t.index-r.index})[0]?.target}function m(e,s){if(!e.webSocketDebuggerUrl)return Number.NEGATIVE_INFINITY;const n=(e.type??"").toLowerCase(),t=(e.url??"").toLowerCase(),r=(e.title??"").toLowerCase(),i=`${r} ${t}`;if(!i.trim()&&!n)return Number.NEGATIVE_INFINITY;if(i.includes("devtools"))return Number.NEGATIVE_INFINITY;if(n==="background_page"||n==="service_worker")return Number.NEGATIVE_INFINITY;let o=0;if(s&&s.test(i))o+=1000;if(n==="app")o+=120;else if(n==="webview")o+=100;else if(n==="page")o+=80;else if(n==="iframe")o+=20;if(t.startsWith("http://localhost")||t.startsWith("https://localhost"))o+=90;if(t.startsWith("file://"))o+=60;if(t.startsWith("http://127.0.0.1")||t.startsWith("https://127.0.0.1"))o+=50;if(t.startsWith("about:blank"))o-=120;if(t===""||t==="about:blank")o-=40;if(r&&r!=="devtools")o+=25;const d=Object.values(P()).map((a)=>(a.displayName??a.processName).toLowerCase());for(const a of d)if(r.includes(a)){o+=120;break}for(const a of d)if(t.includes(a)){o+=100;break}return o}function T(e){const s=e?.trim();if(!s)return;return new RegExp(M(s.toLowerCase()))}function M(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}export const __test__={selectCDPTarget:g,scoreCDPTarget:m};function q(e){return new Promise((s,n)=>{const t=new URL(e),r=(t.protocol==="https:"?y:_)(t,(i)=>{const o=i.statusCode??0;if(o<200||o>=300){i.resume();n(Error(`Failed to fetch CDP targets: HTTP ${o}`));return}const d=[];i.on("data",(a)=>d.push(Buffer.isBuffer(a)?a:Buffer.from(a)));i.on("end",()=>{try{s(JSON.parse(Buffer.concat(d).toString("utf8")))}catch(a){n(a instanceof Error?a:Error(String(a)))}})});r.on("error",n);r.setTimeout(1e4,()=>r.destroy(Error("Timed out fetching CDP targets")));r.end()})}
@@ -44,6 +44,13 @@ export declare function releaseSiteSessionLease(params: {
44
44
  * gets aborted mid-flight even though the user explicitly allowed more time.
45
45
  */
46
46
  export declare function setDaemonCommandTimeoutSeconds(seconds: number | null): void;
47
+ /**
48
+ * [pp-only] 单次页面脚本执行(Runtime.evaluate)的时限,与扩展侧同一口径:命令时限减 5 秒
49
+ * (extension background.ts 的 `cmd.timeout * 1000 - 5_000`)。托管浏览器环境直连 CDP,
50
+ * 此前固定 30 秒——长文「转存图片 + 发布」在同一次 evaluate 里,图稍多就被截断,
51
+ * 同一条命令在扩展环境能跑 115 秒、在托管环境只有 30 秒。
52
+ */
53
+ export declare function pageEvaluateTimeoutMs(): number;
47
54
  /**
48
55
  * True when a thrown error carries an unknown-outcome code — the browser-side
49
56
  * command may still be running even though the client gave up. Callers use this
@@ -1 +1 @@
1
- import{sleep as b}from"../utils.js";import{BrowserConnectError as g,SessionBusyError as C}from"../errors.js";import{COMMAND_RESULT_UNKNOWN_CODE as l,COMMAND_RESULT_UNKNOWN_HINT as h}from"../daemon-utils.js";import{classifyBrowserError as A}from"./errors.js";import{resolveProfileContextId as v}from"./profile.js";import{DEFAULT_BROWSER_CONNECT_TIMEOUT as P}from"./config.js";import{ensureBrowserBridgeReady as H}from"./daemon-lifecycle.js";import{isPreDispatchError as L}from"./bridge-readiness.js";import{fetchDaemonStatus,getDaemonHealth,requestDaemon as M,requestDaemonShutdown}from"./daemon-transport.js";let S=0;function p(){return`cmd_${process.pid}_${Date.now()}_${++S}`}export function generateRunId(){return`run_${process.pid}_${Date.now()}_${++S}`}let c=null;export function setDaemonRunContext(e){c=e}export function clearDaemonRunContext(e){if(c?.runId===e)c=null}export async function releaseSiteSessionLease(e){try{await M("/command",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:p(),action:"lease-release",runId:e.runId,session:e.session,surface:e.surface}),timeout:2000})}catch{}}const W=120,k=15000,F=1e4;let x=null;export function setDaemonCommandTimeoutSeconds(e){x=typeof e==="number"&&e>0?Math.ceil(e):null}function j(e){const t=x??W;if(typeof e.timeoutMs==="number"&&e.timeoutMs>0)return Math.max(t,Math.ceil((e.timeoutMs+k)/1000));return t}const J="1.1.0";function q(e,t){if(!e)return!1;const n=e.replace(/^v/,"").split("-")[0].split(".").map(Number),r=t.split(".").map(Number);if(n.length<3||n.some(Number.isNaN))return!1;for(let s=0;s<3;s++){const a=n[s]-(r[s]??0);if(a!==0)return a>0}return!0}const D=new Set(["command_result_unknown","command_lost","result_evicted"]);export function isUnknownOutcomeError(e){const t=new Set;let n=e;while(n&&typeof n==="object"&&!t.has(n)){t.add(n);const r=n.code;if(typeof r==="string"&&D.has(r))return!0;n=n.cause}return!1}const B=4,K=new Set(["ECONNREFUSED","UND_ERR_CONNECT_TIMEOUT","EHOSTUNREACH","ENETUNREACH","ENOTFOUND"]);function X(e){const t=[e],n=new Set;while(t.length){const r=t.pop();if(!r||typeof r!=="object"||n.has(r))continue;n.add(r);const{code:s,cause:a,errors:u}=r;if(typeof s==="string"&&K.has(s))return!0;if(a)t.push(a);if(Array.isArray(u))t.push(...u)}return!1}export class BrowserCommandError extends Error{code;hint;constructor(e,t,n){super(e);this.code=t;this.hint=n;this.name="BrowserCommandError"}}export{fetchDaemonStatus,getDaemonHealth,requestDaemonShutdown};async function R(e,t){const n=j(t),r=Date.now()+n*1000,s=process.env.OPENCLI_WINDOW,a=s==="foreground"||s==="background"?s:void 0,u=t.contextId??v(),T=t.windowMode??a,I=e==="navigate";let E=!1,w=p(),m=!1,O=!1,_=null;const f=async()=>{const d=Math.ceil((r-Date.now())/1000),N=await H({timeoutSeconds:Math.max(1,Math.min(P,d)),contextId:u,verbose:!1});_=q(N.health.status?.extensionVersion,J)};for(let d=1;d<=B;d++){if(d>1&&Date.now()>=r)throw new BrowserCommandError("Browser command deadline exhausted across transport retries.",l,h);const N=Math.max(1000,r-Date.now()),U={id:w,action:e,...t,timeout:n,deadlineAt:r,...u&&{contextId:u},...T&&{windowMode:T},...c&&{runId:c.runId,command:c.command,access:c.access}};try{const o=await(await M("/command",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(U),timeout:N+F})).json();if(o.ok)return o;if(o.errorCode==="session_busy")throw new C(o.error??"The site session is busy.",o.errorHint);if(o.errorCode&&D.has(o.errorCode)){if(I&&!E){E=!0;w=p();await f();continue}throw new BrowserCommandError(o.error??"Browser command result is unknown",o.errorCode,o.errorHint)}if(L(o.errorCode)&&!m){m=!0;await f();continue}if(o.errorCode==="daemon_shutting_down"&&!m){m=!0;await f();if(_)continue;throw new BrowserCommandError(o.error??"Daemon shut down mid-command; the command may have already been applied.",l,h)}const y=A(new BrowserCommandError(o.error??"",o.errorCode));if(y.kind==="extension-transient"&&!O){O=!0;w=p();await b(y.delayMs);continue}throw new BrowserCommandError(o.error??"Daemon command failed",o.errorCode,o.errorHint)}catch(i){if(i instanceof BrowserCommandError||i instanceof g||i instanceof C)throw i;if(i instanceof Error&&i.name==="AbortError")throw new BrowserCommandError("Browser command timed out client-side; the page may still have applied it.",l,h);if(i instanceof TypeError){await f();if(_||X(i))continue;throw new BrowserCommandError("Connection to the daemon was lost mid-command; it may have already been applied.",l,h)}throw i}}throw new BrowserCommandError("sendCommand: max attempts exhausted","max_attempts_exhausted")}export async function sendCommand(e,t={}){return(await R(e,t)).data}export async function sendCommandFull(e,t={}){const n=await R(e,t);return{data:n.data,page:n.page}}export async function bindTab(e,t={}){return sendCommand("bind",{session:e,surface:"browser",...t})}
1
+ import{sleep as g}from"../utils.js";import{BrowserConnectError as A,SessionBusyError as C}from"../errors.js";import{COMMAND_RESULT_UNKNOWN_CODE as l,COMMAND_RESULT_UNKNOWN_HINT as p}from"../daemon-utils.js";import{classifyBrowserError as v}from"./errors.js";import{resolveProfileContextId as P}from"./profile.js";import{DEFAULT_BROWSER_CONNECT_TIMEOUT as H}from"./config.js";import{ensureBrowserBridgeReady as L}from"./daemon-lifecycle.js";import{isPreDispatchError as W}from"./bridge-readiness.js";import{fetchDaemonStatus,getDaemonHealth,requestDaemon as S,requestDaemonShutdown}from"./daemon-transport.js";let x=0;function h(){return`cmd_${process.pid}_${Date.now()}_${++x}`}export function generateRunId(){return`run_${process.pid}_${Date.now()}_${++x}`}let c=null;export function setDaemonRunContext(e){c=e}export function clearDaemonRunContext(e){if(c?.runId===e)c=null}export async function releaseSiteSessionLease(e){try{await S("/command",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:h(),action:"lease-release",runId:e.runId,session:e.session,surface:e.surface}),timeout:2000})}catch{}}const D=120,k=15000,F=1e4;let T=null;export function setDaemonCommandTimeoutSeconds(e){T=typeof e==="number"&&e>0?Math.ceil(e):null}export function pageEvaluateTimeoutMs(){return Math.max(1e4,(T??D)*1000-5000)}function j(e){const t=T??D;if(typeof e.timeoutMs==="number"&&e.timeoutMs>0)return Math.max(t,Math.ceil((e.timeoutMs+k)/1000));return t}const J="1.1.0";function q(e,t){if(!e)return!1;const n=e.replace(/^v/,"").split("-")[0].split(".").map(Number),r=t.split(".").map(Number);if(n.length<3||n.some(Number.isNaN))return!1;for(let s=0;s<3;s++){const i=n[s]-(r[s]??0);if(i!==0)return i>0}return!0}const R=new Set(["command_result_unknown","command_lost","result_evicted"]);export function isUnknownOutcomeError(e){const t=new Set;let n=e;while(n&&typeof n==="object"&&!t.has(n)){t.add(n);const r=n.code;if(typeof r==="string"&&R.has(r))return!0;n=n.cause}return!1}const B=4,K=new Set(["ECONNREFUSED","UND_ERR_CONNECT_TIMEOUT","EHOSTUNREACH","ENETUNREACH","ENOTFOUND"]);function X(e){const t=[e],n=new Set;while(t.length){const r=t.pop();if(!r||typeof r!=="object"||n.has(r))continue;n.add(r);const{code:s,cause:i,errors:u}=r;if(typeof s==="string"&&K.has(s))return!0;if(i)t.push(i);if(Array.isArray(u))t.push(...u)}return!1}export class BrowserCommandError extends Error{code;hint;constructor(e,t,n){super(e);this.code=t;this.hint=n;this.name="BrowserCommandError"}}export{fetchDaemonStatus,getDaemonHealth,requestDaemonShutdown};async function I(e,t){const n=j(t),r=Date.now()+n*1000,s=process.env.OPENCLI_WINDOW,i=s==="foreground"||s==="background"?s:void 0,u=t.contextId??P(),E=t.windowMode??i,U=e==="navigate";let O=!1,w=h(),m=!1,y=!1,_=null;const f=async()=>{const d=Math.ceil((r-Date.now())/1000),N=await L({timeoutSeconds:Math.max(1,Math.min(H,d)),contextId:u,verbose:!1});_=q(N.health.status?.extensionVersion,J)};for(let d=1;d<=B;d++){if(d>1&&Date.now()>=r)throw new BrowserCommandError("Browser command deadline exhausted across transport retries.",l,p);const N=Math.max(1000,r-Date.now()),b={id:w,action:e,...t,timeout:n,deadlineAt:r,...u&&{contextId:u},...E&&{windowMode:E},...c&&{runId:c.runId,command:c.command,access:c.access}};try{const o=await(await S("/command",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b),timeout:N+F})).json();if(o.ok)return o;if(o.errorCode==="session_busy")throw new C(o.error??"The site session is busy.",o.errorHint);if(o.errorCode&&R.has(o.errorCode)){if(U&&!O){O=!0;w=h();await f();continue}throw new BrowserCommandError(o.error??"Browser command result is unknown",o.errorCode,o.errorHint)}if(W(o.errorCode)&&!m){m=!0;await f();continue}if(o.errorCode==="daemon_shutting_down"&&!m){m=!0;await f();if(_)continue;throw new BrowserCommandError(o.error??"Daemon shut down mid-command; the command may have already been applied.",l,p)}const M=v(new BrowserCommandError(o.error??"",o.errorCode));if(M.kind==="extension-transient"&&!y){y=!0;w=h();await g(M.delayMs);continue}throw new BrowserCommandError(o.error??"Daemon command failed",o.errorCode,o.errorHint)}catch(a){if(a instanceof BrowserCommandError||a instanceof A||a instanceof C)throw a;if(a instanceof Error&&a.name==="AbortError")throw new BrowserCommandError("Browser command timed out client-side; the page may still have applied it.",l,p);if(a instanceof TypeError){await f();if(_||X(a))continue;throw new BrowserCommandError("Connection to the daemon was lost mid-command; it may have already been applied.",l,p)}throw a}}throw new BrowserCommandError("sendCommand: max attempts exhausted","max_attempts_exhausted")}export async function sendCommand(e,t={}){return(await I(e,t)).data}export async function sendCommandFull(e,t={}){const n=await I(e,t);return{data:n.data,page:n.page}}export async function bindTab(e,t={}){return sendCommand("bind",{session:e,surface:"browser",...t})}
@@ -1 +1 @@
1
- import{DEFAULT_DAEMON_PORT as c,unsupportedDaemonPortEnvMessage as u}from"../constants.js";const f=c,l=`http://127.0.0.1:${f}`,d={"X-OpenCLI":"1"};class o extends Error{constructor(e){super(u(e));this.name="UnsupportedDaemonPortEnvError"}}function m(){const e=process.env.OPENCLI_DAEMON_PORT;if(e!==void 0&&e!=="")throw new o(e)}export async function requestDaemon(e,t){m();const{timeout:n=2000,headers:s,...a}=t??{},r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await fetch(`${l}${e}`,{...a,headers:{...d,...s},signal:r.signal})}finally{clearTimeout(i)}}export async function fetchDaemonStatus(e){try{const t=e?.contextId?`?contextId=${encodeURIComponent(e.contextId)}`:"",n=await requestDaemon(`/status${t}`,{timeout:e?.timeout??2000});if(!n.ok)return null;return await n.json()}catch(t){if(t instanceof o)throw t;return null}}export async function getDaemonHealth(e){const t=await fetchDaemonStatus(e);if(!t)return{state:"stopped",status:null};if(t.profileRequired)return{state:"profile-required",status:t};if(t.profileDisconnected)return{state:"profile-disconnected",status:t};if(!t.extensionConnected)return{state:"no-extension",status:t};return{state:"ready",status:t}}export async function requestDaemonShutdown(e){try{return(await requestDaemon("/shutdown",{method:"POST",timeout:e?.timeout??5000})).ok}catch(t){if(t instanceof o)throw t;return!1}}
1
+ import{DEFAULT_DAEMON_PORT as c,unsupportedDaemonPortEnvMessage as u}from"../constants.js";import{resolveProfileContextId as f}from"./profile.js";const l=c,d=`http://127.0.0.1:${l}`,m={"X-OpenCLI":"1"};class o extends Error{constructor(e){super(u(e));this.name="UnsupportedDaemonPortEnvError"}}function p(){const e=process.env.OPENCLI_DAEMON_PORT;if(e!==void 0&&e!=="")throw new o(e)}export async function requestDaemon(e,t){p();const{timeout:n=2000,headers:s,...a}=t??{},r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await fetch(`${d}${e}`,{...a,headers:{...m,...s},signal:r.signal})}finally{clearTimeout(i)}}export async function fetchDaemonStatus(e){try{const t=e?.contextId?`?contextId=${encodeURIComponent(e.contextId)}`:"",n=await requestDaemon(`/status${t}`,{timeout:e?.timeout??2000});if(!n.ok)return null;return await n.json()}catch(t){if(t instanceof o)throw t;return null}}export async function getDaemonHealth(e){const t=await fetchDaemonStatus({...e,contextId:e?.contextId??f()});if(!t)return{state:"stopped",status:null};if(t.profileRequired)return{state:"profile-required",status:t};if(t.profileDisconnected)return{state:"profile-disconnected",status:t};if(!t.extensionConnected)return{state:"no-extension",status:t};return{state:"ready",status:t}}export async function requestDaemonShutdown(e){try{return(await requestDaemon("/shutdown",{method:"POST",timeout:e?.timeout??5000})).ok}catch(t){if(t instanceof o)throw t;return!1}}
@@ -1 +1 @@
1
- import{fetchDaemonStatus as a,requestDaemonShutdown as u}from"../browser/daemon-transport.js";import{restartDaemon as m}from"../browser/daemon-lifecycle.js";import{formatDuration as f}from"../download/progress.js";import{log as o}from"../logger.js";import{PKG_VERSION as c}from"../version.js";import{formatDaemonVersion as l,isDaemonStale as d}from"../browser/daemon-version.js";import{browserSession as w,getBrowserFactory as x}from"../runtime.js";export async function daemonStatus(s={}){const e=await a();if(s.json){console.log(JSON.stringify(e?{daemon:"running",pid:e.pid,daemonVersion:l(e),stale:d(e,c),uptimeSeconds:Math.round(e.uptime),bridgeReady:!!e.extensionConnected,extensionConnected:!!e.extensionConnected,extensionVersion:e.extensionVersion??null,profileRequired:!!e.profileRequired,profileDisconnected:!!e.profileDisconnected,profiles:(e.profiles??[]).map((t)=>({contextId:t.contextId,extensionVersion:t.extensionVersion??null})),port:e.port}:{daemon:"not_running",bridgeReady:!1},null,2));return}if(!e){console.log("Daemon: not running");return}let r;if(e.extensionConnected)r=e.extensionVersion?`connected (v${e.extensionVersion})`:"connected (version unknown)";else if(e.profileRequired){const t=e.profiles?.length??0;r=`${t} ${t===1?"profile":"profiles"} connected, none selected — run \`ppcli profile use <name>\``}else if(e.profileDisconnected)r="requested profile not connected — run `ppcli profile use <name>`";else r="disconnected";const i=l(e),n=d(e,c);console.log(`Daemon: ${n?"stale":"running"} (PID ${e.pid})`);console.log(`Version: ${i}${n?` (CLI v${c}; run: ppcli daemon restart)`:""}`);console.log(`Uptime: ${f(Math.round(e.uptime*1000))}`);console.log(`Extension: ${r}`);if(e.profiles&&e.profiles.length>0)console.log(`Profiles: ${e.profiles.map((t)=>{const p=t.extensionVersion?` v${t.extensionVersion}`:"";return`${t.contextId}${p}`}).join(", ")}`);console.log(`Memory: ${e.memoryMB} MB`);console.log(`Port: ${e.port}`)}export async function daemonStop(){if(!await a()){o.info("Daemon is not running.");return}if(await u())o.success("Daemon stopped.");else{o.error("Failed to stop daemon.");process.exitCode=1}}export async function daemonRestart(){const s=await a();if(s?.profiles&&s.profiles.length>0)o.warn(`Restarting daemon will disconnect ${s.profiles.length} browser profile(s); the extension should reconnect automatically.`);const e=await m();if(!e.stopped){o.error("Failed to stop daemon before restart.");process.exitCode=1;return}if(!e.status){o.error("Daemon restart timed out before the new daemon reported status.");process.exitCode=1;return}const r=e.previousStatus?"restarted":"started",i=l(e.status);o.success(`Daemon ${r} on port ${e.status.port} (${i}).`);if(e.status.extensionConnected){const n=e.status.profiles?.length??0,t=n>0?`; profiles connected: ${n}`:"";o.status(`Extension connected${t}.`)}else o.warn("Daemon is running, but the Browser Bridge extension has not connected yet.")}export async function daemonWarm(s){const e=await a();if(!e){o.warn("Daemon/extension not ready; skip warm (retry after the browser extension connects).");return}if(!e.extensionConnected){o.warn("Browser extension not connected yet; skip warm.");return}if(e.extensionCapabilities?.includes("chrome-api")){o.status("Extension hosts background tabs in existing windows; nothing to warm.");return}const r=s&&/^https?:\/\//i.test(s)?s:"about:blank",i=x("__warm__");try{await w(i,async(n)=>{await n.goto(r).catch(()=>{})},{session:"site:__warm__",windowMode:"background",surface:"adapter",siteSession:"persistent"});o.success(`Automation window warmed (${r}, kept alive for reuse).`)}catch(n){o.warn(`Warm failed (non-fatal): ${n instanceof Error?n.message:String(n)}`)}}
1
+ import{fetchDaemonStatus as a,requestDaemonShutdown as u}from"../browser/daemon-transport.js";import{resolveProfileContextId as m}from"../browser/profile.js";import{restartDaemon as f}from"../browser/daemon-lifecycle.js";import{formatDuration as x}from"../download/progress.js";import{log as o}from"../logger.js";import{PKG_VERSION as c}from"../version.js";import{formatDaemonVersion as l,isDaemonStale as d}from"../browser/daemon-version.js";import{browserSession as w,getBrowserFactory as g}from"../runtime.js";export async function daemonStatus(s={}){const e=await a({contextId:m()});if(s.json){console.log(JSON.stringify(e?{daemon:"running",pid:e.pid,daemonVersion:l(e),stale:d(e,c),uptimeSeconds:Math.round(e.uptime),bridgeReady:!!e.extensionConnected,extensionConnected:!!e.extensionConnected,extensionVersion:e.extensionVersion??null,profileRequired:!!e.profileRequired,profileDisconnected:!!e.profileDisconnected,profiles:(e.profiles??[]).map((t)=>({contextId:t.contextId,extensionVersion:t.extensionVersion??null})),port:e.port}:{daemon:"not_running",bridgeReady:!1},null,2));return}if(!e){console.log("Daemon: not running");return}let r;if(e.extensionConnected)r=e.extensionVersion?`connected (v${e.extensionVersion})`:"connected (version unknown)";else if(e.profileRequired){const t=e.profiles?.length??0;r=`${t} ${t===1?"profile":"profiles"} connected, none selected — run \`ppcli profile use <name>\``}else if(e.profileDisconnected)r="requested profile not connected — run `ppcli profile use <name>`";else r="disconnected";const i=l(e),n=d(e,c);console.log(`Daemon: ${n?"stale":"running"} (PID ${e.pid})`);console.log(`Version: ${i}${n?` (CLI v${c}; run: ppcli daemon restart)`:""}`);console.log(`Uptime: ${x(Math.round(e.uptime*1000))}`);console.log(`Extension: ${r}`);if(e.profiles&&e.profiles.length>0)console.log(`Profiles: ${e.profiles.map((t)=>{const p=t.extensionVersion?` v${t.extensionVersion}`:"";return`${t.contextId}${p}`}).join(", ")}`);console.log(`Memory: ${e.memoryMB} MB`);console.log(`Port: ${e.port}`)}export async function daemonStop(){if(!await a()){o.info("Daemon is not running.");return}if(await u())o.success("Daemon stopped.");else{o.error("Failed to stop daemon.");process.exitCode=1}}export async function daemonRestart(){const s=await a();if(s?.profiles&&s.profiles.length>0)o.warn(`Restarting daemon will disconnect ${s.profiles.length} browser profile(s); the extension should reconnect automatically.`);const e=await f();if(!e.stopped){o.error("Failed to stop daemon before restart.");process.exitCode=1;return}if(!e.status){o.error("Daemon restart timed out before the new daemon reported status.");process.exitCode=1;return}const r=e.previousStatus?"restarted":"started",i=l(e.status);o.success(`Daemon ${r} on port ${e.status.port} (${i}).`);if(e.status.extensionConnected){const n=e.status.profiles?.length??0,t=n>0?`; profiles connected: ${n}`:"";o.status(`Extension connected${t}.`)}else o.warn("Daemon is running, but the Browser Bridge extension has not connected yet.")}export async function daemonWarm(s){const e=await a();if(!e){o.warn("Daemon/extension not ready; skip warm (retry after the browser extension connects).");return}if(!e.extensionConnected){o.warn("Browser extension not connected yet; skip warm.");return}if(e.extensionCapabilities?.includes("chrome-api")){o.status("Extension hosts background tabs in existing windows; nothing to warm.");return}const r=s&&/^https?:\/\//i.test(s)?s:"about:blank",i=g("__warm__");try{await w(i,async(n)=>{await n.goto(r).catch(()=>{})},{session:"site:__warm__",windowMode:"background",surface:"adapter",siteSession:"persistent"});o.success(`Automation window warmed (${r}, kept alive for reuse).`)}catch(n){o.warn(`Warm failed (non-fatal): ${n instanceof Error?n.message:String(n)}`)}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "publishport-opencli",
3
- "version": "1.0.67",
3
+ "version": "1.0.69",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "provenance": false