publishport-opencli 1.0.54 → 1.0.57

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.
Files changed (43) hide show
  1. package/cli-manifest.json +8 -1
  2. package/clis/_shared/article/images.js +5 -5
  3. package/clis/_shared/article/page-runtime.js +13 -4
  4. package/clis/_shared/article/publish.js +11 -11
  5. package/clis/baijiahao/article.js +2 -2
  6. package/clis/bilibili/article.js +1 -1
  7. package/clis/bilibili/comment.js +1 -1
  8. package/clis/cnblogs/article.js +1 -1
  9. package/clis/csdn/article.js +5 -5
  10. package/clis/cto51/article.js +1 -1
  11. package/clis/douyin/publish.js +8 -8
  12. package/clis/eastmoney/article.js +1 -1
  13. package/clis/imooc/article.js +3 -3
  14. package/clis/infoq/article.js +2 -2
  15. package/clis/jianshu/article.js +1 -1
  16. package/clis/juejin/article.js +4 -4
  17. package/clis/medium/article.js +4 -4
  18. package/clis/oschina/article.js +1 -1
  19. package/clis/segmentfault/article.js +3 -3
  20. package/clis/sohu/article.js +1 -1
  21. package/clis/sohu/attributes.js +1 -1
  22. package/clis/sohu/categories.js +1 -1
  23. package/clis/sohu/channels.js +1 -1
  24. package/clis/sohu/columns.js +1 -1
  25. package/clis/sohu/mpbp.js +1 -1
  26. package/clis/sohu/stats.js +5 -17
  27. package/clis/sohu/topics.js +1 -1
  28. package/clis/toutiao/article.js +1 -1
  29. package/clis/wechat-channels/publish.js +111 -22
  30. package/clis/weibo/article.js +1 -1
  31. package/clis/weixin/article.js +1 -1
  32. package/clis/woshipm/article.js +1 -1
  33. package/clis/xianyu/im.js +1 -1
  34. package/clis/xiaohongshu/human.js +2 -2
  35. package/clis/xiaohongshu/publish.js +21 -19
  36. package/clis/xueqiu/article.js +2 -2
  37. package/clis/yuque/article.js +1 -1
  38. package/clis/zhihu/answer.js +1 -1
  39. package/clis/zhihu/article.js +1 -1
  40. package/clis/zhihu/write-shared.js +3 -3
  41. package/dist/src/execution.d.ts +9 -0
  42. package/dist/src/execution.js +2 -2
  43. package/package.json +1 -1
@@ -1 +1 @@
1
- import{CliError as u,CommandExecutionError as R}from"@jackwener/opencli/errors";import{cli as D,Strategy as L}from"@jackwener/opencli/registry";import{publishArticle as O,gotoWritePage as x}from"../_shared/article/publish.js";import{SOHU_MPBP_HEADERS_JS as C}from"./mpbp.js";function M(){const s="0123456789abcdef";let n="";for(let t=0;t<32;t++)n+=s[Math.floor(Math.random()*s.length)];return n}export const sohuProfile={home:"https://mp.sohu.com/mpfe/v3/main/first/page?newsType=1",outputFormat:"html",preprocessConfig:{},checkAuth:async(s)=>{try{const t=await(await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"})).json();if(t.code!==2000000||!t.data?.data?.length)return{isAuthenticated:!1};const o=[];for(const a of t.data.data)if(a.accounts)o.push(...a.accounts);if(!o.length)return{isAuthenticated:!1};const e=o[0],c=o.length>1?e.nickName+"(共"+o.length+"个子账号)":e.nickName;return{isAuthenticated:!0,userId:String(e.id),username:c,avatar:e.avatar||""}}catch(n){return{isAuthenticated:!1,error:String(n&&n.message||n)}}},image:{skip:["sohu.com"],uploadFn:async(s,n)=>{const o=await(await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"})).json();if(o.code!==2000000||!o.data?.data?.length)throw Error("获取搜狐账号信息失败,请确认已登录搜狐号");const e=[];for(const f of o.data.data)if(f.accounts)e.push(...f.accounts);if(!e.length)throw Error("搜狐号子账号列表为空");const c=String(e[0].id),a=await fetch(s,{credentials:"omit"});if(!a.ok)throw Error("图片下载失败("+a.status+"):"+s);const r=await a.blob(),l=new FormData;l.append("file",r,"image.jpg");l.append("accountId",c);const p=await(await fetch("https://mp.sohu.com/commons/front/outerUpload/image/file?accountId="+c,{method:"POST",credentials:"include",body:l})).json();if(!p.url)throw Error("搜狐图片上传失败:"+(p.msg||JSON.stringify(p).slice(0,100)));return{url:p.url}}},publish:async(s,n)=>{const t=s.params||{},o=await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"}),e=await o.json();if(e.code!==2000000||!e.data?.data?.length)return{ok:!1,stage:"auth",status:o.status,message:"获取搜狐账号信息失败,请确认已登录搜狐号"};const c=[];for(const d of e.data.data)if(d.accounts)c.push(...d.accounts);if(!c.length)return{ok:!1,stage:"auth",status:0,message:"搜狐号子账号列表为空"};const a=Number(c[0].id),r="0123456789abcdef";let l="";for(let d=0;d<32;d++)l+=r[Math.floor(Math.random()*r.length)];const m="100-"+Date.now()+"-"+l,p=Number(t.channelId);if(!Number.isFinite(p)||p<=0)return{ok:!1,stage:"params",status:0,message:"缺少合法 channelId(频道 id),请先用 `sohu channels` 取值"};const f=t.categoryId==null||t.categoryId===""?-1:Number(t.categoryId),g={title:s.title,brief:typeof t.brief==="string"?t.brief:"",content:s.content,channelId:p,categoryId:f,id:0,userColumnId:t.userColumnId==null||t.userColumnId==-1?0:Number(t.userColumnId),columnNewsIds:Array.isArray(t.columnNewsIds)?t.columnNewsIds:[],businessCode:0,declareOriginal:Boolean(t.declareOriginal),cover:typeof t.cover==="string"?t.cover:"",topicIds:Array.isArray(t.topicIds)?t.topicIds:[],isAd:0,userLabels:"[]",reprint:!1,customTags:typeof t.customTags==="string"?t.customTags:"",infoResource:0,sourceUrl:"",visibleToLoginedUsers:0,attrIds:Array.isArray(t.attrIds)?t.attrIds:[],accountId:a};if(s.draftOnly){const d=Object.assign({},g,{auto:!0}),h=await fetch("https://mp.sohu.com/mpbp/bp/news/v4/news/draft/v2?accountId="+a,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest","dv-id":l,"sp-cm":m},body:JSON.stringify(d)}),S=await h.text();let y=null;try{y=JSON.parse(S)}catch(F){}if(!h.ok||!y||!y.success)return{ok:!1,stage:"draft",status:h.status,message:y&&y.msg||S.slice(0,300)};const _=String(y.data),U="https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus=2&id="+_;return{ok:!0,id:_,url:U,draft:!0}}const I=await fetch("https://mp.sohu.com/mpbp/bp/news/v4/news/publish/v2?accountId="+a,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest","dv-id":l,"sp-cm":m},body:JSON.stringify(g)}),T=await I.text();let i=null;try{i=JSON.parse(T)}catch(d){}if(!I.ok||!i||i.code!==2000000){let d=i&&(i.msg||i.message)||"";if(!d){const h=[];if(f!==-1)h.push("--category");if(Array.isArray(t.topicIds)&&t.topicIds.length>0)h.push("--topics");if(g.cover)h.push("--cover");d="搜狐发布接口返回非 JSON 错误页(HTTP "+I.status+")。"+(h.length?"实测该 500 多由可选参数触发——去掉 "+h.join(" / ")+"、只保留必填 --channel 重试即可。":"稍后重试;若持续失败,用 `sohu stats` 确认是否已产生重复内容。")}return{ok:!1,stage:"publish",status:I.status,message:d}}if(i.data!=null&&Object.prototype.toString.call(i.data)==="[object Object]")return{ok:!1,stage:"origin_check",status:I.status,message:"声明原创触发了原创校验(需在搜狐后台完成原创确认):"+JSON.stringify(i.data).slice(0,200)};const w=String(i.data),b="https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus=1&id="+w,A="https://www.sohu.com/a/"+w+"_"+a;return{ok:!0,id:w,url:b,publicUrl:A,draft:!1}}},sohuAuthProfile={home:sohuProfile.home,checkAuth:sohuProfile.checkAuth};function v(s){if(!s.execute)throw new u("INVALID_INPUT","此命令需要 --execute 才会真正写入。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function P(s){const n=typeof s.text==="string"?s.text:void 0,t=typeof s.file==="string"?s.file:void 0;if(n&&t)throw new u("INVALID_INPUT","text 和 --file 只能二选一");let o=n??"";if(t){const{readFile:e,stat:c}=await import("node:fs/promises");let a;try{a=await c(t)}catch{throw new u("INVALID_INPUT","文件不存在:"+t)}if(!a.isFile())throw new u("INVALID_INPUT","路径不是可读文本文件:"+t);let r;try{r=await e(t)}catch{throw new u("INVALID_INPUT","文件读取失败:"+t)}try{o=new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{throw new u("INVALID_INPUT","文件不是合法 UTF-8 编码:"+t)}}if(!o.trim())throw new u("INVALID_INPUT","正文不能为空");return o}function j(s,n,t,o,e={}){return[{status:"success",outcome:o,message:s,target_type:n,target:t,...e}]}async function N(s,n,t){const o="(async () => {try {"+C+"const r = await fetch("+JSON.stringify(n)+', { method: "GET", credentials: "include", headers: HDRS });const t = await r.text();let j = null; try { j = JSON.parse(t); } catch (e) {}return { ok: r.ok, status: r.status, json: j, text: t.slice(0, 300) };} catch (e) { return { ok: false, status: 0, json: null, text: String((e && e.message) || e) }; }})()',e=await s.evaluate(o);if(!e||!e.ok||!e.json)throw new u("INVALID_INPUT","搜狐"+t+"接口请求失败(HTTP "+(e?e.status:"?")+"):"+(e?e.text:""));if(e.json.success===!1||e.json.code!=null&&e.json.code!==2000000&&e.json.code!==2000)throw new u("INVALID_INPUT","搜狐"+t+"接口返回错误:"+(e.json.msg||e.json.message||"未登录或无权限"));return e.json}async function V(s){const n=await N(s,"https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),"账号列表"),t=n.data&&n.data.data||[],o=[];for(const e of t)if(e.accounts)o.push(...e.accounts);if(!o.length)throw new u("INVALID_INPUT","搜狐号子账号列表为空,请确认已登录搜狐号");return String(o[0].id)}async function E(s,n,t){const o=await N(s,"https://mp.sohu.com/mpbp/bp/account/common/channels-data-api?status=1&accountId="+encodeURIComponent(n),"频道列举"),e=Array.isArray(o)?o:o.data||[],c=e.find((a)=>String(a.name)===String(t));if(!c)throw new u("INVALID_INPUT","未找到频道「"+t+"」,可选:"+(e.map((a)=>a.name).join(" / ")||"(空)")+"。用 `sohu channels` 查看完整列表。");return Number(c.id!=null?c.id:c.channelId)}async function H(s,n,t,o){const e=await N(s,"https://mp.sohu.com/mpbp/bp/account/common/channels/"+t+"/categories?accountId="+encodeURIComponent(n),"分类列举"),c=Array.isArray(e)?e:e.data||[],a=c.find((r)=>String(r.name)===String(o));if(!a)throw new u("INVALID_INPUT","频道(id="+t+")下未找到分类「"+o+"」,可选:"+(c.map((r)=>r.name).join(" / ")||"(该频道无分类)")+"。用 `sohu categories --channel <频道名>` 查看。");return Number(a.id)}async function J(s,n,t){const o=await N(s,"https://mp.sohu.com/mpbp/bp/account/column/v2/list?accountId="+encodeURIComponent(n)+"&page=1&size=100","专栏列举"),e=Array.isArray(o)?o:o.data&&(o.data.data||o.data)||o.data||[],c=Array.isArray(e)?e:[],a=c.find((r)=>String(r.name)===String(t));if(!a)throw new u("INVALID_INPUT","未找到专栏「"+t+"」,可选:"+(c.map((r)=>r.name).join(" / ")||"(你还没有任何专栏)")+"。用 `sohu columns` 查看。");return Number(a.id)}async function k(s,n,t){const o=t.split(",").map((c)=>c.trim()).filter(Boolean);if(!o.length)return[];const e=[];for(const c of o){const a=await N(s,"https://mp.sohu.com/mpbp/bp/news/v4/label/topic/search?accountId="+n+"&keyword="+encodeURIComponent(c),"话题搜索"),l=(Array.isArray(a)?a:a.data||[]).find((m)=>String(m.name)===String(c));if(!l)throw new u("INVALID_INPUT","未找到话题「"+c+"」,请用 `sohu topics --keyword "+c+"` 搜索确认确切名称。");e.push(l.id)}return e}D({site:"sohu",name:"article",access:"write",description:"发布文章到搜狐号(HTML 格式,外链图片自动转存到搜狐图床)。默认正式发布,加 --draft 仅存草稿。频道必填,合法值用 `sohu channels` 取。",domain:"mp.sohu.com",strategy:L.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"文章正文(默认 Markdown,传 --html 则视为 HTML)"},{name:"file",help:"正文文件路径(UTF-8,Markdown 或 HTML)"},{name:"html",type:"boolean",help:"将正文视为原始 HTML 而非 Markdown"},{name:"channel",help:"频道名(精确匹配,必填),合法值用 `sohu channels` 列举"},{name:"category",help:"分类名(精确匹配,依赖所选频道),合法值用 `sohu categories --channel <频道名>` 列举;不传=不限"},{name:"column",help:"专栏名(精确匹配),合法值用 `sohu columns` 列举;不传=不归属专栏"},{name:"topics",help:"话题名,逗号分隔(每个精确匹配),用 `sohu topics` 搜索取确切名"},{name:"cover",help:"封面图 URL(须为搜狐图床地址);可空"},{name:"brief",help:"文章摘要;可空"},{name:"declare-original",type:"boolean",help:"声明原创(会触发搜狐原创校验,发布将被拦到原创确认流程)"},{name:"draft",type:"boolean",help:"仅保存草稿,不正式发布"},{name:"execute",type:"boolean",help:"实际执行写入操作;不加此参数则拒绝写入(干跑保护)"}],columns:["status","outcome","message","target_type","target","created_target","created_url","public_url"],func:async(s,n)=>{if(!s)throw new R("搜狐号文章发布需要浏览器会话");v(n);const t=String(n.title??"").trim();if(!t)throw new u("INVALID_INPUT","文章标题不能为空");const o=await P(n),e=Boolean(n.draft),c=typeof n.channel==="string"?n.channel.trim():"";if(!c)throw new u("INVALID_INPUT","缺少 --channel(频道名)。请先运行 `sohu channels` 取合法频道名再传入,不提供默认值。");await x(s,sohuProfile.home);const a=await V(s),r=await E(s,a,c);let l=-1;const m=typeof n.category==="string"?n.category.trim():"";if(m)l=await H(s,a,r,m);let p=0;const f=typeof n.column==="string"?n.column.trim():"";if(f)p=await J(s,a,f);let g=[];const I=typeof n.topics==="string"?n.topics.trim():"";if(I)g=await k(s,a,I);const T={channelId:r,categoryId:l,userColumnId:p,topicIds:g,cover:typeof n.cover==="string"?n.cover.trim():"",brief:typeof n.brief==="string"?n.brief:"",declareOriginal:Boolean(n["declare-original"])},i=await O(s,{title:t,body:o,format:n.html?"html":"markdown",draftOnly:e,profile:sohuProfile,publishParams:T}),w=i.images.uploaded.length|0,b=i.images.failed.length|0;let A=i.draft?"已保存搜狐号草稿":"已正式发布到搜狐号";if(w||b)A+=`;图片:${w} 张已转存${b?`,${b} 张失败`:""}`;return j(A,"article","",i.draft?"draft":"created",{created_target:(i.draft?"draft:":"article:")+i.id,created_url:i.url,public_url:i.publicUrl||""})}});export const __test__={sohuProfile,requireExecute:v,buildResultRow:j,resolvePayload:P,generateDeviceId:M};
1
+ import{CliError as i,CommandExecutionError as v}from"@jackwener/opencli/errors";import{cli as U,Strategy as D}from"@jackwener/opencli/registry";import{formatImageReport as R,publishArticle as O,gotoWritePage as x}from"../_shared/article/publish.js";import{SOHU_MPBP_HEADERS_JS as L,readSohuMpbpHeaders as C,sohuMpbpMessage as M}from"./mpbp.js";import{rememberArticleFile as V}from"../_shared/article/images.js";function E(){const a="0123456789abcdef";let o="";for(let t=0;t<32;t++)o+=a[Math.floor(Math.random()*a.length)];return o}export const sohuProfile={home:"https://mp.sohu.com/mpfe/v3/main/first/page?newsType=1",outputFormat:"html",preprocessConfig:{},checkAuth:async(a)=>{try{const t=await(await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"})).json();if(t.code!==2000000||!t.data?.data?.length)return{isAuthenticated:!1};const n=[];for(const s of t.data.data)if(s.accounts)n.push(...s.accounts);if(!n.length)return{isAuthenticated:!1};const e=n[0],r=n.length>1?e.nickName+"(共"+n.length+"个子账号)":e.nickName;return{isAuthenticated:!0,userId:String(e.id),username:r,avatar:e.avatar||""}}catch(o){return{isAuthenticated:!1,error:String(o&&o.message||o)}}},image:{skip:["sohu.com"],uploadFn:async(a,o)=>{const n=await(await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"})).json();if(n.code!==2000000||!n.data?.data?.length)throw Error("获取搜狐账号信息失败,请确认已登录搜狐号");const e=[];for(const h of n.data.data)if(h.accounts)e.push(...h.accounts);if(!e.length)throw Error("搜狐号子账号列表为空");const r=String(e[0].id),s=await fetch(a,{credentials:"omit"});if(!s.ok)throw Error("图片下载失败("+s.status+"):"+a);const c=await s.blob(),u=new FormData;u.append("file",c,"image.jpg");u.append("accountId",r);const m=await(await fetch("https://mp.sohu.com/commons/front/outerUpload/image/file?accountId="+r,{method:"POST",credentials:"include",body:u})).json();if(!m.url)throw Error("搜狐图片上传失败:"+(m.msg||JSON.stringify(m).slice(0,100)));return{url:m.url}}},publish:async(a,o)=>{const t=a.params||{},n=await fetch("https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),{method:"GET",credentials:"include"}),e=await n.json();if(e.code!==2000000||!e.data?.data?.length)return{ok:!1,stage:"auth",status:n.status,message:"获取搜狐账号信息失败,请确认已登录搜狐号"};const r=[];for(const d of e.data.data)if(d.accounts)r.push(...d.accounts);if(!r.length)return{ok:!1,stage:"auth",status:0,message:"搜狐号子账号列表为空"};const s=Number(r[0].id),c=t.headers;if(!c||!c["sp-cm"])return{ok:!1,stage:"params",status:0,message:"缺少搜狐客户端请求头(P.headers),请由 Node 侧 readSohuMpbpHeaders 取值后传入"};const u=Number(t.channelId);if(!Number.isFinite(u)||u<=0)return{ok:!1,stage:"params",status:0,message:"缺少合法 channelId(频道 id),请先用 `sohu channels` 取值"};const I=t.categoryId==null||t.categoryId===""?-1:Number(t.categoryId),m={title:a.title,brief:typeof t.brief==="string"?t.brief:"",content:a.content,channelId:u,categoryId:I,id:0,userColumnId:t.userColumnId==null||t.userColumnId==-1?0:Number(t.userColumnId),columnNewsIds:Array.isArray(t.columnNewsIds)?t.columnNewsIds:[],businessCode:0,declareOriginal:Boolean(t.declareOriginal),cover:typeof t.cover==="string"?t.cover:"",topicIds:Array.isArray(t.topicIds)?t.topicIds:[],isAd:0,userLabels:"[]",reprint:!1,customTags:typeof t.customTags==="string"?t.customTags:"",infoResource:0,sourceUrl:"",visibleToLoginedUsers:0,attrIds:Array.isArray(t.attrIds)?t.attrIds:[],accountId:s};if(a.draftOnly){const d=Object.assign({},m,{auto:!0}),p=await fetch("https://mp.sohu.com/mpbp/bp/news/v4/news/draft/v2?accountId="+s,{method:"POST",credentials:"include",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify(d)}),A=await p.text();let g=null;try{g=JSON.parse(A)}catch(G){}if(!p.ok||!g||!g.success)return{ok:!1,stage:"draft",status:p.status,message:g&&g.msg||A.slice(0,300)};const T=String(g.data),j="https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus=2&id="+T;return{ok:!0,id:T,url:j,draft:!0}}const h=await fetch("https://mp.sohu.com/mpbp/bp/news/v4/news/publish/v2?accountId="+s,{method:"POST",credentials:"include",headers:{...c,"Content-Type":"application/json"},body:JSON.stringify(m)}),b=await h.text();let l=null;try{l=JSON.parse(b)}catch(d){}if(!h.ok||!l||l.code!==2000000){let d=l&&(l.msg||l.message)||"";if(!d){const p=[];if(I!==-1)p.push("--category");if(Array.isArray(t.topicIds)&&t.topicIds.length>0)p.push("--topics");if(m.cover)p.push("--cover");d="搜狐发布接口返回非 JSON 错误页(HTTP "+h.status+")。"+(p.length?"实测该 500 多由可选参数触发——去掉 "+p.join(" / ")+"、只保留必填 --channel 重试即可。":"稍后重试;若持续失败,用 `sohu stats` 确认是否已产生重复内容。")}return{ok:!1,stage:"publish",status:h.status,message:d}}if(l.data!=null&&Object.prototype.toString.call(l.data)==="[object Object]")return{ok:!1,stage:"origin_check",status:h.status,message:"声明原创触发了原创校验(需在搜狐后台完成原创确认):"+JSON.stringify(l.data).slice(0,200)};const w=String(l.data),f="https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus=1&id="+w,N="https://www.sohu.com/a/"+w+"_"+s;return{ok:!0,id:w,url:f,publicUrl:N,draft:!1}}},sohuAuthProfile={home:sohuProfile.home,checkAuth:sohuProfile.checkAuth};function S(a){if(!a.execute)throw new i("INVALID_INPUT","此命令需要 --execute 才会真正写入。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function _(a){const o=typeof a.text==="string"?a.text:void 0,t=typeof a.file==="string"?a.file:void 0;if(o&&t)throw new i("INVALID_INPUT","text 和 --file 只能二选一");let n=o??"";if(t){V(t);const{readFile:e,stat:r}=await import("node:fs/promises");let s;try{s=await r(t)}catch{throw new i("INVALID_INPUT","文件不存在:"+t)}if(!s.isFile())throw new i("INVALID_INPUT","路径不是可读文本文件:"+t);let c;try{c=await e(t)}catch{throw new i("INVALID_INPUT","文件读取失败:"+t)}try{n=new TextDecoder("utf-8",{fatal:!0}).decode(c)}catch{throw new i("INVALID_INPUT","文件不是合法 UTF-8 编码:"+t)}}if(!n.trim())throw new i("INVALID_INPUT","正文不能为空");return n}function P(a,o,t,n,e={}){return[{status:"success",outcome:n,message:a,target_type:o,target:t,...e}]}async function y(a,o,t){const n="(async () => {try {"+L+"const r = await fetch("+JSON.stringify(o)+', { method: "GET", credentials: "include", headers: HDRS });const t = await r.text();let j = null; try { j = JSON.parse(t); } catch (e) {}return { ok: r.ok, status: r.status, json: j, text: t.slice(0, 300) };} catch (e) { return { ok: false, status: 0, json: null, text: String((e && e.message) || e) }; }})()',e=await a.evaluate(n);if(!e||!e.ok||!e.json)throw new i("INVALID_INPUT","搜狐"+t+"接口请求失败(HTTP "+(e?e.status:"?")+"):"+(e?e.text:""));if(e.json.success===!1||e.json.code!=null&&e.json.code!==2000000&&e.json.code!==2000)throw new i("INVALID_INPUT","搜狐"+t+"接口返回错误:"+M(e.json));return e.json}async function H(a){const o=await y(a,"https://mp.sohu.com/mpbp/bp/account/list?_="+Date.now(),"账号列表"),t=o.data&&o.data.data||[],n=[];for(const e of t)if(e.accounts)n.push(...e.accounts);if(!n.length)throw new i("INVALID_INPUT","搜狐号子账号列表为空,请确认已登录搜狐号");return String(n[0].id)}async function J(a,o,t){const n=await y(a,"https://mp.sohu.com/mpbp/bp/account/common/channels-data-api?status=1&accountId="+encodeURIComponent(o),"频道列举"),e=Array.isArray(n)?n:n.data||[],r=e.find((s)=>String(s.name)===String(t));if(!r)throw new i("INVALID_INPUT","未找到频道「"+t+"」,可选:"+(e.map((s)=>s.name).join(" / ")||"(空)")+"。用 `sohu channels` 查看完整列表。");return Number(r.id!=null?r.id:r.channelId)}async function k(a,o,t,n){const e=await y(a,"https://mp.sohu.com/mpbp/bp/account/common/channels/"+t+"/categories?accountId="+encodeURIComponent(o),"分类列举"),r=Array.isArray(e)?e:e.data||[],s=r.find((c)=>String(c.name)===String(n));if(!s)throw new i("INVALID_INPUT","频道(id="+t+")下未找到分类「"+n+"」,可选:"+(r.map((c)=>c.name).join(" / ")||"(该频道无分类)")+"。用 `sohu categories --channel <频道名>` 查看。");return Number(s.id)}async function F(a,o,t){const n=await y(a,"https://mp.sohu.com/mpbp/bp/account/column/v2/list?accountId="+encodeURIComponent(o)+"&page=1&size=100","专栏列举"),e=Array.isArray(n)?n:n.data&&(n.data.data||n.data)||n.data||[],r=Array.isArray(e)?e:[],s=r.find((c)=>String(c.name)===String(t));if(!s)throw new i("INVALID_INPUT","未找到专栏「"+t+"」,可选:"+(r.map((c)=>c.name).join(" / ")||"(你还没有任何专栏)")+"。用 `sohu columns` 查看。");return Number(s.id)}async function B(a,o,t){const n=t.split(",").map((r)=>r.trim()).filter(Boolean);if(!n.length)return[];const e=[];for(const r of n){const s=await y(a,"https://mp.sohu.com/mpbp/bp/news/v4/label/topic/search?accountId="+o+"&keyword="+encodeURIComponent(r),"话题搜索"),u=(Array.isArray(s)?s:s.data||[]).find((I)=>String(I.name)===String(r));if(!u)throw new i("INVALID_INPUT","未找到话题「"+r+"」,请用 `sohu topics --keyword "+r+"` 搜索确认确切名称。");e.push(u.id)}return e}U({site:"sohu",name:"article",access:"write",description:"发布文章到搜狐号(HTML 格式,外链图片自动转存到搜狐图床)。默认正式发布,加 --draft 仅存草稿。频道必填,合法值用 `sohu channels` 取。",domain:"mp.sohu.com",strategy:D.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题"},{name:"text",positional:!0,help:"文章正文(默认 Markdown,传 --html 则视为 HTML)"},{name:"file",help:"正文文件路径(UTF-8,Markdown 或 HTML)"},{name:"html",type:"boolean",help:"将正文视为原始 HTML 而非 Markdown"},{name:"channel",help:"频道名(精确匹配,必填),合法值用 `sohu channels` 列举"},{name:"category",help:"分类名(精确匹配,依赖所选频道),合法值用 `sohu categories --channel <频道名>` 列举;不传=不限"},{name:"column",help:"专栏名(精确匹配),合法值用 `sohu columns` 列举;不传=不归属专栏"},{name:"topics",help:"话题名,逗号分隔(每个精确匹配),用 `sohu topics` 搜索取确切名"},{name:"cover",help:"封面图 URL(须为搜狐图床地址);可空"},{name:"brief",help:"文章摘要;可空"},{name:"declare-original",type:"boolean",help:"声明原创(会触发搜狐原创校验,发布将被拦到原创确认流程)"},{name:"draft",type:"boolean",help:"仅保存草稿,不正式发布"},{name:"execute",type:"boolean",help:"实际执行写入操作;不加此参数则拒绝写入(干跑保护)"}],columns:["status","outcome","message","target_type","target","created_target","created_url","public_url"],func:async(a,o)=>{if(!a)throw new v("搜狐号文章发布需要浏览器会话");S(o);const t=String(o.title??"").trim();if(!t)throw new i("INVALID_INPUT","文章标题不能为空");const n=await _(o),e=Boolean(o.draft),r=typeof o.channel==="string"?o.channel.trim():"";if(!r)throw new i("INVALID_INPUT","缺少 --channel(频道名)。请先运行 `sohu channels` 取合法频道名再传入,不提供默认值。");await x(a,sohuProfile.home);const s=await H(a),c=await J(a,s,r);let u=-1;const I=typeof o.category==="string"?o.category.trim():"";if(I)u=await k(a,s,c,I);let m=0;const h=typeof o.column==="string"?o.column.trim():"";if(h)m=await F(a,s,h);let b=[];const l=typeof o.topics==="string"?o.topics.trim():"";if(l)b=await B(a,s,l);const w={channelId:c,categoryId:u,userColumnId:m,topicIds:b,cover:typeof o.cover==="string"?o.cover.trim():"",brief:typeof o.brief==="string"?o.brief:"",declareOriginal:Boolean(o["declare-original"]),headers:await C(a)},f=await O(a,{title:t,body:n,format:o.html?"html":"markdown",draftOnly:e,profile:sohuProfile,publishParams:w}),N=f.images.uploaded.length|0,d=f.images.failed.length|0;let p=f.draft?"已保存搜狐号草稿":"已正式发布到搜狐号";if(N||d)p+=`;图片:${N} 张已转存${d?`,${d} 张失败`:""}`;p+=R(f.images);return P(p,"article","",f.draft?"draft":"created",{created_target:(f.draft?"draft:":"article:")+f.id,created_url:f.url,public_url:f.publicUrl||""})}});export const __test__={sohuProfile,requireExecute:S,buildResultRow:P,resolvePayload:_,generateDeviceId:E};
@@ -1 +1 @@
1
- import{cli as a,Strategy as o}from"@jackwener/opencli/registry";import{CommandExecutionError as s}from"@jackwener/opencli/errors";import{gotoWritePage as e}from"../_shared/article/publish.js";import{sohuProfile as i}from"./article.js";a({site:"sohu",name:"attributes",access:"read",description:"列出搜狐号文章属性候选(id + 名称),供发布时选择文章属性。",domain:"mp.sohu.com",strategy:o.COOKIE,browser:!0,columns:["attr_id","attr_name"],func:async(r)=>{if(!r)throw new s("搜狐号文章属性列举需要浏览器会话");await e(r,i.home);const t=await r.evaluate("(async () => {const r = await fetch('https://mp.sohu.com/mpbp/bp/news/v4/news/attribute', { method: 'GET', credentials: 'include' });const j = await r.json();"+"if (!j || j.success === false) throw new Error('文章属性列举失败:' + ((j && j.msg) || '未登录或无权限'));"+"const raw = (j && j.data) || [];const list = Array.isArray(raw) ? raw : (Array.isArray(raw.data) ? raw.data : []);return list.map(a => ({ attr_id: String(a.id), attr_name: a.name || a.attrName || '' }));})()");return Array.isArray(t)?t:[]}});
1
+ import{cli as a,Strategy as o}from"@jackwener/opencli/registry";import{CommandExecutionError as s}from"@jackwener/opencli/errors";import{gotoWritePage as e}from"../_shared/article/publish.js";import{sohuProfile as i}from"./article.js";import{SOHU_MPBP_HEADERS_JS as m}from"./mpbp.js";a({site:"sohu",name:"attributes",access:"read",description:"列出搜狐号文章属性候选(id + 名称),供发布时选择文章属性。",domain:"mp.sohu.com",strategy:o.COOKIE,browser:!0,columns:["attr_id","attr_name"],func:async(r)=>{if(!r)throw new s("搜狐号文章属性列举需要浏览器会话");await e(r,i.home);const t=await r.evaluate("(async () => {"+m+"const r = await fetch('https://mp.sohu.com/mpbp/bp/news/v4/news/attribute', { method: 'GET', credentials: 'include', headers: HDRS });const j = await r.json();"+"if (!j || j.success === false) throw new Error('文章属性列举失败:' + __sohuMsg(j));"+"const raw = (j && j.data) || [];const list = Array.isArray(raw) ? raw : (Array.isArray(raw.data) ? raw.data : []);return list.map(a => ({ attr_id: String(a.id), attr_name: a.name || a.attrName || '' }));})()");return Array.isArray(t)?t:[]}});
@@ -1 +1 @@
1
- import{cli as r,Strategy as o}from"@jackwener/opencli/registry";import{CliError as e,CommandExecutionError as s}from"@jackwener/opencli/errors";import{gotoWritePage as i}from"../_shared/article/publish.js";import{sohuProfile as h}from"./article.js";import{SOHU_MPBP_HEADERS_JS as d}from"./mpbp.js";r({site:"sohu",name:"categories",access:"read",description:"列出某个搜狐号频道下的分类(id + 名称),供 `sohu article --category` 取合法分类名。须用 --channel 指定频道名。",domain:"mp.sohu.com",strategy:o.COOKIE,browser:!0,args:[{name:"channel",required:!0,help:"频道名(精确匹配),合法值用 `sohu channels` 列举"}],columns:["category_id","category_name"],func:async(a,n)=>{if(!a)throw new s("搜狐号分类列举需要浏览器会话");const c=String(n.channel??"").trim();if(!c)throw new e("INVALID_INPUT","请用 --channel 指定频道名");await i(a,h.home);const t=await a.evaluate("(async () => {"+d+"const ar = await fetch('https://mp.sohu.com/mpbp/bp/account/list?_=' + Date.now(), { method: 'GET', credentials: 'include', headers: HDRS });const aj = await ar.json();"+"if (!aj || aj.code !== 2000000 || !(aj.data && aj.data.data && aj.data.data.length)) throw new Error('获取搜狐账号失败,请确认已登录搜狐号');"+"let accountId = '';for (const g of aj.data.data) { if (g.accounts && g.accounts.length) { accountId = String(g.accounts[0].id); break; } }"+"if (!accountId) throw new Error('搜狐号子账号列表为空');"+"const cr = await fetch('https://mp.sohu.com/mpbp/bp/account/common/channels-data-api?status=1&accountId=' + accountId, { method: 'GET', credentials: 'include', headers: HDRS });const cj = await cr.json();"+"if (!cj || cj.success === false) throw new Error('频道列举失败:' + ((cj && cj.msg) || '未登录或无权限'));"+"const channels = Array.isArray(cj) ? cj : ((cj && cj.data) || []);const ch = channels.find(c => String(c.name) === "+JSON.stringify(c)+");"+"if (!ch) throw new Error('未找到频道「"+c.replace(/"/g,"\\\"")+"」,可选:' + (channels.map(c => c.name).join(' / ') || '(空)'));"+"const channelId = ch.id != null ? ch.id : ch.channelId;const r = await fetch('https://mp.sohu.com/mpbp/bp/account/common/channels/' + channelId + '/categories?accountId=' + accountId, { method: 'GET', credentials: 'include', headers: HDRS });const j = await r.json();"+"if (!j || j.success === false) throw new Error('分类列举失败:' + ((j && j.msg) || '未登录或无权限'));"+"const list = Array.isArray(j) ? j : ((j && j.data) || []);return list.map(c => ({ category_id: String(c.id), category_name: c.name || '' }));})()");return Array.isArray(t)?t:[]}});
1
+ import{cli as o,Strategy as r}from"@jackwener/opencli/registry";import{CliError as e,CommandExecutionError as s}from"@jackwener/opencli/errors";import{gotoWritePage as i}from"../_shared/article/publish.js";import{sohuProfile as h}from"./article.js";import{SOHU_MPBP_HEADERS_JS as d}from"./mpbp.js";o({site:"sohu",name:"categories",access:"read",description:"列出某个搜狐号频道下的分类(id + 名称),供 `sohu article --category` 取合法分类名。须用 --channel 指定频道名。",domain:"mp.sohu.com",strategy:r.COOKIE,browser:!0,args:[{name:"channel",required:!0,help:"频道名(精确匹配),合法值用 `sohu channels` 列举"}],columns:["category_id","category_name"],func:async(a,n)=>{if(!a)throw new s("搜狐号分类列举需要浏览器会话");const c=String(n.channel??"").trim();if(!c)throw new e("INVALID_INPUT","请用 --channel 指定频道名");await i(a,h.home);const t=await a.evaluate("(async () => {"+d+"const ar = await fetch('https://mp.sohu.com/mpbp/bp/account/list?_=' + Date.now(), { method: 'GET', credentials: 'include', headers: HDRS });const aj = await ar.json();"+"if (!aj || aj.code !== 2000000 || !(aj.data && aj.data.data && aj.data.data.length)) throw new Error('获取搜狐账号失败,请确认已登录搜狐号');"+"let accountId = '';for (const g of aj.data.data) { if (g.accounts && g.accounts.length) { accountId = String(g.accounts[0].id); break; } }"+"if (!accountId) throw new Error('搜狐号子账号列表为空');"+"const cr = await fetch('https://mp.sohu.com/mpbp/bp/account/common/channels-data-api?status=1&accountId=' + accountId, { method: 'GET', credentials: 'include', headers: HDRS });const cj = await cr.json();"+"if (!cj || cj.success === false) throw new Error('频道列举失败:' + __sohuMsg(cj));"+"const channels = Array.isArray(cj) ? cj : ((cj && cj.data) || []);const ch = channels.find(c => String(c.name) === "+JSON.stringify(c)+");"+"if (!ch) throw new Error('未找到频道「"+c.replace(/"/g,"\\\"")+"」,可选:' + (channels.map(c => c.name).join(' / ') || '(空)'));"+"const channelId = ch.id != null ? ch.id : ch.channelId;const r = await fetch('https://mp.sohu.com/mpbp/bp/account/common/channels/' + channelId + '/categories?accountId=' + accountId, { method: 'GET', credentials: 'include', headers: HDRS });const j = await r.json();"+"if (!j || j.success === false) throw new Error('分类列举失败:' + __sohuMsg(j));"+"const list = Array.isArray(j) ? j : ((j && j.data) || []);return list.map(c => ({ category_id: String(c.id), category_name: c.name || '' }));})()");return Array.isArray(t)?t:[]}});
@@ -1 +1 @@
1
- import{cli as n,Strategy as o}from"@jackwener/opencli/registry";import{CommandExecutionError as c}from"@jackwener/opencli/errors";import{gotoWritePage as r}from"../_shared/article/publish.js";import{sohuProfile as e}from"./article.js";import{SOHU_MPBP_HEADERS_JS as s}from"./mpbp.js";n({site:"sohu",name:"channels",access:"read",description:"列出当前搜狐号可发布的频道(id + 名称),供 `sohu article --channel` 取合法频道名。",domain:"mp.sohu.com",strategy:o.COOKIE,browser:!0,columns:["channel_id","channel_name"],func:async(a)=>{if(!a)throw new c("搜狐号频道列举需要浏览器会话");await r(a,e.home);const t=await a.evaluate("(async () => {"+s+"const ar = await fetch('https://mp.sohu.com/mpbp/bp/account/list?_=' + Date.now(), { method: 'GET', credentials: 'include', headers: HDRS });const aj = await ar.json();"+"if (!aj || aj.code !== 2000000 || !(aj.data && aj.data.data && aj.data.data.length)) throw new Error('获取搜狐账号失败,请确认已登录搜狐号');"+"let accountId = '';for (const g of aj.data.data) { if (g.accounts && g.accounts.length) { accountId = String(g.accounts[0].id); break; } }"+"if (!accountId) throw new Error('搜狐号子账号列表为空');"+"const r = await fetch('https://mp.sohu.com/mpbp/bp/account/common/channels-data-api?status=1&accountId=' + accountId, { method: 'GET', credentials: 'include', headers: HDRS });const j = await r.json();"+"if (!j || j.success === false) throw new Error('频道列举失败:' + ((j && j.msg) || '未登录或无权限'));"+"const list = Array.isArray(j) ? j : ((j && j.data) || []);return list.map(c => ({ channel_id: String(c.id != null ? c.id : c.channelId), channel_name: c.name || '' }));})()");return Array.isArray(t)?t:[]}});
1
+ import{cli as o,Strategy as n}from"@jackwener/opencli/registry";import{CommandExecutionError as c}from"@jackwener/opencli/errors";import{gotoWritePage as r}from"../_shared/article/publish.js";import{sohuProfile as e}from"./article.js";import{SOHU_MPBP_HEADERS_JS as s}from"./mpbp.js";o({site:"sohu",name:"channels",access:"read",description:"列出当前搜狐号可发布的频道(id + 名称),供 `sohu article --channel` 取合法频道名。",domain:"mp.sohu.com",strategy:n.COOKIE,browser:!0,columns:["channel_id","channel_name"],func:async(a)=>{if(!a)throw new c("搜狐号频道列举需要浏览器会话");await r(a,e.home);const t=await a.evaluate("(async () => {"+s+"const ar = await fetch('https://mp.sohu.com/mpbp/bp/account/list?_=' + Date.now(), { method: 'GET', credentials: 'include', headers: HDRS });const aj = await ar.json();"+"if (!aj || aj.code !== 2000000 || !(aj.data && aj.data.data && aj.data.data.length)) throw new Error('获取搜狐账号失败,请确认已登录搜狐号');"+"let accountId = '';for (const g of aj.data.data) { if (g.accounts && g.accounts.length) { accountId = String(g.accounts[0].id); break; } }"+"if (!accountId) throw new Error('搜狐号子账号列表为空');"+"const r = await fetch('https://mp.sohu.com/mpbp/bp/account/common/channels-data-api?status=1&accountId=' + accountId, { method: 'GET', credentials: 'include', headers: HDRS });const j = await r.json();"+"if (!j || j.success === false) throw new Error('频道列举失败:' + __sohuMsg(j));"+"const list = Array.isArray(j) ? j : ((j && j.data) || []);return list.map(c => ({ channel_id: String(c.id != null ? c.id : c.channelId), channel_name: c.name || '' }));})()");return Array.isArray(t)?t:[]}});
@@ -1 +1 @@
1
- import{cli as r,Strategy as o}from"@jackwener/opencli/registry";import{CommandExecutionError as c}from"@jackwener/opencli/errors";import{gotoWritePage as n}from"../_shared/article/publish.js";import{sohuProfile as s}from"./article.js";import{SOHU_MPBP_HEADERS_JS as e}from"./mpbp.js";r({site:"sohu",name:"columns",access:"read",description:"列出当前搜狐号的专栏(id + 名称),供 `sohu article --column` 取合法专栏名。",domain:"mp.sohu.com",strategy:o.COOKIE,browser:!0,columns:["column_id","column_name"],func:async(a)=>{if(!a)throw new c("搜狐号专栏列举需要浏览器会话");await n(a,s.home);const t=await a.evaluate("(async () => {"+e+"const ar = await fetch('https://mp.sohu.com/mpbp/bp/account/list?_=' + Date.now(), { method: 'GET', credentials: 'include', headers: HDRS });const aj = await ar.json();"+"if (!aj || aj.code !== 2000000 || !(aj.data && aj.data.data && aj.data.data.length)) throw new Error('获取搜狐账号失败,请确认已登录搜狐号');"+"let accountId = '';for (const g of aj.data.data) { if (g.accounts && g.accounts.length) { accountId = String(g.accounts[0].id); break; } }"+"if (!accountId) throw new Error('搜狐号子账号列表为空');"+"const r = await fetch('https://mp.sohu.com/mpbp/bp/account/column/v2/list?accountId=' + accountId + '&page=1&size=100', { method: 'GET', credentials: 'include', headers: HDRS });const j = await r.json();"+"if (!j || j.success === false) throw new Error('专栏列举失败:' + ((j && j.msg) || '未登录或无权限'));"+"const raw = Array.isArray(j) ? j : ((j && j.data) || []);const list = Array.isArray(raw) ? raw : (Array.isArray(raw.data) ? raw.data : []);return list.map(c => ({ column_id: String(c.id), column_name: c.name || '' }));})()");return Array.isArray(t)?t:[]}});
1
+ import{cli as r,Strategy as o}from"@jackwener/opencli/registry";import{CommandExecutionError as c}from"@jackwener/opencli/errors";import{gotoWritePage as n}from"../_shared/article/publish.js";import{sohuProfile as s}from"./article.js";import{SOHU_MPBP_HEADERS_JS as e}from"./mpbp.js";r({site:"sohu",name:"columns",access:"read",description:"列出当前搜狐号的专栏(id + 名称),供 `sohu article --column` 取合法专栏名。",domain:"mp.sohu.com",strategy:o.COOKIE,browser:!0,columns:["column_id","column_name"],func:async(a)=>{if(!a)throw new c("搜狐号专栏列举需要浏览器会话");await n(a,s.home);const t=await a.evaluate("(async () => {"+e+"const ar = await fetch('https://mp.sohu.com/mpbp/bp/account/list?_=' + Date.now(), { method: 'GET', credentials: 'include', headers: HDRS });const aj = await ar.json();"+"if (!aj || aj.code !== 2000000 || !(aj.data && aj.data.data && aj.data.data.length)) throw new Error('获取搜狐账号失败,请确认已登录搜狐号');"+"let accountId = '';for (const g of aj.data.data) { if (g.accounts && g.accounts.length) { accountId = String(g.accounts[0].id); break; } }"+"if (!accountId) throw new Error('搜狐号子账号列表为空');"+"const r = await fetch('https://mp.sohu.com/mpbp/bp/account/column/v2/list?accountId=' + accountId + '&page=1&size=100', { method: 'GET', credentials: 'include', headers: HDRS });const j = await r.json();"+"if (!j || j.success === false) throw new Error('专栏列举失败:' + __sohuMsg(j));"+"const raw = Array.isArray(j) ? j : ((j && j.data) || []);const list = Array.isArray(raw) ? raw : (Array.isArray(raw.data) ? raw.data : []);return list.map(c => ({ column_id: String(c.id), column_name: c.name || '' }));})()");return Array.isArray(t)?t:[]}});
package/clis/sohu/mpbp.js CHANGED
@@ -1 +1 @@
1
- export const SOHU_MPBP_HEADERS_JS="let __dvId = '', __spCm = '';try { __dvId = localStorage.getItem('preview-dv-id') || ''; __spCm = localStorage.getItem('preview-sp-cm') || ''; } catch (e) {}if (!__dvId || !__spCm) { const __chars = '0123456789abcdef'; let __gen = ''; for (let __i = 0; __i < 32; __i++) __gen += __chars[Math.floor(Math.random() * 16)]; if (!__dvId) __dvId = __gen; if (!__spCm) __spCm = '100-' + Date.now() + '-' + __gen;}const HDRS = { 'X-Requested-With': 'XMLHttpRequest', 'dv-id': __dvId, 'sp-cm': __spCm };";
1
+ async function d(){const t=(o)=>{const n=document.cookie.match(new RegExp("(?:^|; )"+o+"=([^;]*)"));return n?decodeURIComponent(n[1]):""};let e={};const s=t("mpToken");if(s)e.mpToken=s;const i=window.ClientSignIns&&window.ClientSignIns.tools;if(i&&typeof i.setHeader==="function")e=await i.setHeader(e)||e;if(!e["dv-id"]||!e["sp-cm"]){let o="",n="";try{o=sessionStorage.getItem("dv-id")||localStorage.getItem("preview-dv-id")||"";n=localStorage.getItem("preview-sp-cm")||""}catch(r){}if(!n)n=t("mp-cv");if(!o||!n){const r="0123456789abcdef";let c="";for(let a=0;a<32;a++)c+=r[Math.floor(Math.random()*16)];if(!o)o=c;if(!n)n="100-"+Date.now()+"-"+c}if(!e["dv-id"])e["dv-id"]=o;if(!e["sp-cm"])e["sp-cm"]=n}e["X-Requested-With"]="XMLHttpRequest";return e}export function sohuMpbpMessage(t,e){const s=t&&(t.msg||t.message)||"";if(t&&(t.code===1300||s.indexOf("未授权客户端")!==-1))return"搜狐号要求当前浏览器先完成短信安全验证("+(s||"未授权客户端")+")。"+"需要账号本人在 PublishPort 使用的这个浏览器中打开搜狐号写文章页 "+"https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle ,"+"按「安全中心」页面提示选择手机号、填写短信验证码,显示「验证通过」后重试;"+"在其他浏览器或手机上验证对该浏览器无效。";return s||e||"未登录或无权限"}export const SOHU_MPBP_HEADERS_JS="const HDRS = await ("+d.toString()+")();const __sohuMsg = ("+sohuMpbpMessage.toString()+");";export async function readSohuMpbpHeaders(t){return t.evaluate("(async () => {"+SOHU_MPBP_HEADERS_JS+"return HDRS; })()")}
@@ -1,20 +1,8 @@
1
- import{cli as I,Strategy as b}from"@jackwener/opencli/registry";import{CommandExecutionError as g,EmptyResultError as S}from"@jackwener/opencli/errors";import{gotoWritePage as j}from"../_shared/article/publish.js";const v="https://mp.sohu.com/mpfe/v4/contentManagement/news/articlelist",C=10;function f(c){if(!c)return"";const a=new Date(c+28800000),n=(i)=>String(i).padStart(2,"0");return`${a.getUTCFullYear()}-${n(a.getUTCMonth()+1)}-${n(a.getUTCDate())} ${n(a.getUTCHours())}:${n(a.getUTCMinutes())}`}function w(c){const a=new Date(Date.now()+28800000-c*86400000),n=(i)=>String(i).padStart(2,"0");return`${a.getUTCFullYear()}-${n(a.getUTCMonth()+1)}-${n(a.getUTCDate())}`}I({site:"sohu",name:"stats",access:"read",description:"搜狐号文章数据(每篇阅读/评论/播放等全量运营指标;点赞/分享/投票仅覆盖最近30天已发布内容)",domain:"mp.sohu.com",strategy:b.COOKIE,browser:!0,args:[{name:"limit",type:"number",default:20,help:"返回条数"}],columns:["id","type","title","url","public_url","published_at","status","views","likes","comments","collects","shares","video_plays","votes","extra"],func:async(c,a)=>{if(!c)throw new g("搜狐号文章数据需要浏览器会话");const n=Number(a.limit)>0?Math.floor(Number(a.limit)):20;await j(c,v);const i={limit:n,pageSize:C,startDate:w(30),endDate:w(0)},e=await c.evaluate(`(async () => {
1
+ import{cli as b,Strategy as S}from"@jackwener/opencli/registry";import{CommandExecutionError as g,EmptyResultError as j}from"@jackwener/opencli/errors";import{gotoWritePage as I}from"../_shared/article/publish.js";import{SOHU_MPBP_HEADERS_JS as _}from"./mpbp.js";const T="https://mp.sohu.com/mpfe/v4/contentManagement/news/articlelist",C=10;function f(c){if(!c)return"";const a=new Date(c+28800000),n=(i)=>String(i).padStart(2,"0");return`${a.getUTCFullYear()}-${n(a.getUTCMonth()+1)}-${n(a.getUTCDate())} ${n(a.getUTCHours())}:${n(a.getUTCMinutes())}`}function w(c){const a=new Date(Date.now()+28800000-c*86400000),n=(i)=>String(i).padStart(2,"0");return`${a.getUTCFullYear()}-${n(a.getUTCMonth()+1)}-${n(a.getUTCDate())}`}b({site:"sohu",name:"stats",access:"read",description:"搜狐号文章数据(每篇阅读/评论/播放等全量运营指标;点赞/分享/投票仅覆盖最近30天已发布内容)",domain:"mp.sohu.com",strategy:S.COOKIE,browser:!0,args:[{name:"limit",type:"number",default:20,help:"返回条数"}],columns:["id","type","title","url","public_url","published_at","status","views","likes","comments","collects","shares","video_plays","votes","extra"],func:async(c,a)=>{if(!c)throw new g("搜狐号文章数据需要浏览器会话");const n=Number(a.limit)>0?Math.floor(Number(a.limit)):20;await I(c,T);const i={limit:n,pageSize:C,startDate:w(30),endDate:w(0)},e=await c.evaluate(`(async () => {
2
2
  const P = ${JSON.stringify(i)};
3
3
 
4
- // ── 请求头:dv-id / sp-cm 优先取页面自己存的值,逐字复刻 ──
5
- let dvId = '', spCm = '';
6
- try {
7
- dvId = localStorage.getItem('preview-dv-id') || '';
8
- spCm = localStorage.getItem('preview-sp-cm') || '';
9
- } catch (e) {}
10
- if (!dvId || !spCm) {
11
- const chars = '0123456789abcdef';
12
- let gen = '';
13
- for (let i = 0; i < 32; i++) gen += chars[Math.floor(Math.random() * chars.length)];
14
- if (!dvId) dvId = gen;
15
- if (!spCm) spCm = '100-' + Date.now() + '-' + gen;
16
- }
17
- const HDRS = { 'X-Requested-With': 'XMLHttpRequest', 'dv-id': dvId, 'sp-cm': spCm };
4
+ // ── 请求头与报错文案:与其他搜狐命令同一来源(mpbp.js)──
5
+ ${_}
18
6
 
19
7
  const getJson = async (url) => {
20
8
  const r = await fetch(url, { method: 'GET', credentials: 'include', headers: HDRS });
@@ -22,7 +10,7 @@ import{cli as I,Strategy as b}from"@jackwener/opencli/registry";import{CommandEx
22
10
  let j = null;
23
11
  try { j = JSON.parse(t); } catch (e) {}
24
12
  if (!r.ok || !j || j.success === false || (j.code != null && j.code !== 2000000)) {
25
- throw new Error('HTTP ' + r.status + ' ' + ((j && (j.msg || j.message)) || t.slice(0, 150)));
13
+ throw new Error('HTTP ' + r.status + ' ' + __sohuMsg(j, t.slice(0, 150)));
26
14
  }
27
15
  return j;
28
16
  };
@@ -105,4 +93,4 @@ import{cli as I,Strategy as b}from"@jackwener/opencli/registry";import{CommandEx
105
93
  }
106
94
 
107
95
  return { accountId, news: news.slice(0, P.limit), totalCount: total, publishedIds, statRows, statError, channelMap };
108
- })()`);if(!e||e.err)throw new g(e&&e.err||"搜狐号文章数据获取失败:页面未返回任何数据(请确认已登录 mp.sohu.com)");const d=Array.isArray(e.news)?e.news:[];if(!d.length)throw new S("sohu stats","该搜狐号名下没有任何内容(或列表接口返回为空)。请先在 mp.sohu.com 发布内容后再查数据。");const p=new Map,m=new Map;for(const t of Array.isArray(e.statRows)?e.statRows:[]){if(t&&t.id!=null)p.set(String(t.id),t);if(t&&typeof t.title==="string"&&t.title)m.set(t.title,t)}const l=(t,o)=>{if(!t)return"";for(const r of o)if(typeof t[r]==="number")return t[r];return""},y=new Set(Array.isArray(e.publishedIds)?e.publishedIds:[]);return d.map((t)=>{const o=t.id!=null?String(t.id):"",r=p.get(o)||m.get(t.title||"")||null,u=y.has(o),s={};if(t.auditStatus!=null)s.audit_status=t.auditStatus;if(t.status!=null)s.status_raw=t.status;if(t.rejectReason)s.reject_reason=t.rejectReason;if(t.original!=null)s.original=t.original;if(t.star!=null)s.star=t.star;if(t.secureScore!=null)s.secure_score=t.secureScore;if(t.channelId!=null){const h=e.channelMap&&e.channelMap[String(t.channelId)]||"";s.display_channel=h?h+"("+t.channelId+")":String(t.channelId);s.display_channel_note="搜狐后台按内容自动归类的展示频道,可能与发布时 --channel 所选不同"}if(t.modifiedTime)s.modified_at=f(t.modifiedTime);if(t.brief)s.brief=String(t.brief).slice(0,80);if(r)s.stat=r;if(e.statError)s.stat_error="单篇统计接口失败:"+e.statError;return{id:o,type:t.type!=null?String(t.type):"",title:t.title||t.mobileTitle||"",url:o?"https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus="+(u?1:2)+"&id="+o:"",public_url:o&&u&&e.accountId?"https://www.sohu.com/a/"+o+"_"+e.accountId:"",published_at:f(t.postTime||t.createdTime),status:u?"已发布":"未发布",views:typeof t.pv==="number"?t.pv:"",likes:l(r,["digg","diggCount","like","likeCount","praise","zan"]),comments:typeof t.cmt==="number"?t.cmt:l(r,["cmt","comment","commentCount"]),collects:"",shares:l(r,["share","shareCount","forward","forwardCount"]),video_plays:typeof t.videoPlayPv==="number"?t.videoPlayPv:"",votes:l(r,["vote","voteCount"]),extra:Object.keys(s).length?JSON.stringify(s):""}})}});
96
+ })()`);if(!e||e.err)throw new g(e&&e.err||"搜狐号文章数据获取失败:页面未返回任何数据(请确认已登录 mp.sohu.com)");const p=Array.isArray(e.news)?e.news:[];if(!p.length)throw new j("sohu stats","该搜狐号名下没有任何内容(或列表接口返回为空)。请先在 mp.sohu.com 发布内容后再查数据。");const d=new Map,m=new Map;for(const t of Array.isArray(e.statRows)?e.statRows:[]){if(t&&t.id!=null)d.set(String(t.id),t);if(t&&typeof t.title==="string"&&t.title)m.set(t.title,t)}const l=(t,o)=>{if(!t)return"";for(const r of o)if(typeof t[r]==="number")return t[r];return""},y=new Set(Array.isArray(e.publishedIds)?e.publishedIds:[]);return p.map((t)=>{const o=t.id!=null?String(t.id):"",r=d.get(o)||m.get(t.title||"")||null,u=y.has(o),s={};if(t.auditStatus!=null)s.audit_status=t.auditStatus;if(t.status!=null)s.status_raw=t.status;if(t.rejectReason)s.reject_reason=t.rejectReason;if(t.original!=null)s.original=t.original;if(t.star!=null)s.star=t.star;if(t.secureScore!=null)s.secure_score=t.secureScore;if(t.channelId!=null){const h=e.channelMap&&e.channelMap[String(t.channelId)]||"";s.display_channel=h?h+"("+t.channelId+")":String(t.channelId);s.display_channel_note="搜狐后台按内容自动归类的展示频道,可能与发布时 --channel 所选不同"}if(t.modifiedTime)s.modified_at=f(t.modifiedTime);if(t.brief)s.brief=String(t.brief).slice(0,80);if(r)s.stat=r;if(e.statError)s.stat_error="单篇统计接口失败:"+e.statError;return{id:o,type:t.type!=null?String(t.type):"",title:t.title||t.mobileTitle||"",url:o?"https://mp.sohu.com/mpfe/v4/contentManagement/news/addarticle?spm=smmp.articlelist.0.0&contentStatus="+(u?1:2)+"&id="+o:"",public_url:o&&u&&e.accountId?"https://www.sohu.com/a/"+o+"_"+e.accountId:"",published_at:f(t.postTime||t.createdTime),status:u?"已发布":"未发布",views:typeof t.pv==="number"?t.pv:"",likes:l(r,["digg","diggCount","like","likeCount","praise","zan"]),comments:typeof t.cmt==="number"?t.cmt:l(r,["cmt","comment","commentCount"]),collects:"",shares:l(r,["share","shareCount","forward","forwardCount"]),video_plays:typeof t.videoPlayPv==="number"?t.videoPlayPv:"",votes:l(r,["vote","voteCount"]),extra:Object.keys(s).length?JSON.stringify(s):""}})}});
@@ -1 +1 @@
1
- import{cli as c,Strategy as e}from"@jackwener/opencli/registry";import{CommandExecutionError as n}from"@jackwener/opencli/errors";import{gotoWritePage as i}from"../_shared/article/publish.js";import{sohuProfile as s}from"./article.js";import{SOHU_MPBP_HEADERS_JS as d}from"./mpbp.js";c({site:"sohu",name:"topics",access:"read",description:"列举/搜索搜狐号话题(id + 名称 + 类型),供 `sohu article --topics` 取确切话题名。不传 --keyword 为推荐话题,传则按关键词搜索。",domain:"mp.sohu.com",strategy:e.COOKIE,browser:!0,args:[{name:"keyword",help:"搜索关键词;不传则返回推荐话题列表"}],columns:["topic_id","topic_name","topic_type"],func:async(t,o)=>{if(!t)throw new n("搜狐号话题列举需要浏览器会话");const r=typeof o.keyword==="string"?o.keyword.trim():"";await i(t,s.home);const a=await t.evaluate("(async () => {"+d+"const ar = await fetch('https://mp.sohu.com/mpbp/bp/account/list?_=' + Date.now(), { method: 'GET', credentials: 'include', headers: HDRS });const aj = await ar.json();"+"if (!aj || aj.code !== 2000000 || !(aj.data && aj.data.data && aj.data.data.length)) throw new Error('获取搜狐账号失败,请确认已登录搜狐号');"+"let accountId = '';for (const g of aj.data.data) { if (g.accounts && g.accounts.length) { accountId = String(g.accounts[0].id); break; } }"+"if (!accountId) throw new Error('搜狐号子账号列表为空');"+"const kw = "+JSON.stringify(r)+";const url = kw ? 'https://mp.sohu.com/mpbp/bp/news/v4/label/topic/search?accountId=' + accountId + '&keyword=' + encodeURIComponent(kw) : 'https://mp.sohu.com/mpbp/bp/news/v4/label/topic/list?accountId=' + accountId;const r = await fetch(url, { method: 'GET', credentials: 'include', headers: HDRS });const j = await r.json();"+"if (!j || j.success === false) throw new Error('话题接口失败:' + ((j && j.msg) || '未登录或无权限'));"+"const list = Array.isArray(j) ? j : ((j && j.data) || []);return list.map(t => ({ topic_id: String(t.id), topic_name: t.name || '', topic_type: t.type != null ? String(t.type) : '' }));})()");return Array.isArray(a)?a:[]}});
1
+ import{cli as c,Strategy as e}from"@jackwener/opencli/registry";import{CommandExecutionError as n}from"@jackwener/opencli/errors";import{gotoWritePage as i}from"../_shared/article/publish.js";import{sohuProfile as s}from"./article.js";import{SOHU_MPBP_HEADERS_JS as d}from"./mpbp.js";c({site:"sohu",name:"topics",access:"read",description:"列举/搜索搜狐号话题(id + 名称 + 类型),供 `sohu article --topics` 取确切话题名。不传 --keyword 为推荐话题,传则按关键词搜索。",domain:"mp.sohu.com",strategy:e.COOKIE,browser:!0,args:[{name:"keyword",help:"搜索关键词;不传则返回推荐话题列表"}],columns:["topic_id","topic_name","topic_type"],func:async(t,o)=>{if(!t)throw new n("搜狐号话题列举需要浏览器会话");const r=typeof o.keyword==="string"?o.keyword.trim():"";await i(t,s.home);const a=await t.evaluate("(async () => {"+d+"const ar = await fetch('https://mp.sohu.com/mpbp/bp/account/list?_=' + Date.now(), { method: 'GET', credentials: 'include', headers: HDRS });const aj = await ar.json();"+"if (!aj || aj.code !== 2000000 || !(aj.data && aj.data.data && aj.data.data.length)) throw new Error('获取搜狐账号失败,请确认已登录搜狐号');"+"let accountId = '';for (const g of aj.data.data) { if (g.accounts && g.accounts.length) { accountId = String(g.accounts[0].id); break; } }"+"if (!accountId) throw new Error('搜狐号子账号列表为空');"+"const kw = "+JSON.stringify(r)+";const url = kw ? 'https://mp.sohu.com/mpbp/bp/news/v4/label/topic/search?accountId=' + accountId + '&keyword=' + encodeURIComponent(kw) : 'https://mp.sohu.com/mpbp/bp/news/v4/label/topic/list?accountId=' + accountId;const r = await fetch(url, { method: 'GET', credentials: 'include', headers: HDRS });const j = await r.json();"+"if (!j || j.success === false) throw new Error('话题接口失败:' + __sohuMsg(j));"+"const list = Array.isArray(j) ? j : ((j && j.data) || []);return list.map(t => ({ topic_id: String(t.id), topic_name: t.name || '', topic_type: t.type != null ? String(t.type) : '' }));})()");return Array.isArray(a)?a:[]}});
@@ -1 +1 @@
1
- import{CliError as m,CommandExecutionError as D}from"@jackwener/opencli/errors";import{cli as j,Strategy as V}from"@jackwener/opencli/registry";import{publishArticle as F}from"../_shared/article/publish.js";import{readFile as M,stat as O}from"node:fs/promises";function R(c){if(!c.execute)throw new m("INVALID_INPUT","此头条号写操作需要 --execute 参数才能真正发布。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function H(c){const a=typeof c.text==="string"?c.text:void 0,t=typeof c.file==="string"?c.file:void 0;if(a&&t)throw new m("INVALID_INPUT","正文和 --file 只能选一个");let i=a??"";if(t){let d;try{d=await O(t)}catch{throw new m("INVALID_INPUT",`找不到文件: ${t}`)}if(!d.isFile())throw new m("INVALID_INPUT",`--file 必须是可读文本文件: ${t}`);let p;try{p=await M(t)}catch{throw new m("INVALID_INPUT",`文件无法读取: ${t}`)}try{i=new TextDecoder("utf-8",{fatal:!0}).decode(p)}catch{throw new m("INVALID_INPUT",`文件必须是 UTF-8 编码: ${t}`)}}if(!i.trim())throw new m("INVALID_INPUT","正文不能为空");return i}function q(c,a,t,i,d={}){return[{status:"success",outcome:i,message:c,target_type:a,target:t,...d}]}export const toutiaoProfile={home:"https://mp.toutiao.com/profile_v3/graphic/publish",outputFormat:"html",preprocessConfig:{},publish:async(c,a)=>{const t=c.params||{},i=[],d=[];async function p(e,l){const s="/spice/image?upload_source="+l+"&need_enhance=true&aid=1231&device_platform=web",r=new FormData;let o;if(/^https?:/i.test(e)){r.append("imageUrl",e);o=await fetch(s+"&scene=paste",{method:"POST",credentials:"include",body:r})}else{const w=await fetch(e,{credentials:"omit"});if(!w.ok)throw Error("图片下载失败 HTTP "+w.status+":"+e.slice(0,80));const P=await w.blob(),k=((P.type||"").split("/")[1]||"jpg").split("+")[0].split(";")[0]||"jpg";r.append("image",P,"image."+k);o=await fetch(s,{method:"POST",credentials:"include",body:r})}const u=await o.json(),_=u&&u.data;if(!u||u.code!==0||!_||!_.image_uri)throw Error((u&&u.message||"图片上传失败")+(u&&u.code!=null?"(接口 code "+u.code+")":""));return{uri:_.image_uri,url:_.image_url,width:_.image_width,height:_.image_height}}async function y(e){const l=new FormData;l.append("imageUrl",e);const r=await(await fetch("/spice/image?upload_source=20020003&aid=1231&device_platform=web&need_cover_url=1",{method:"POST",credentials:"include",body:l})).json(),o=r&&r.data;if(!r||r.code!==0||!o||!o.image_uri)throw Error((r&&r.message||"封面图生成失败")+(r&&r.code!=null?"(接口 code "+r.code+")":""));return{uri:o.image_uri,url:o.image_url,width:o.image_width,height:o.image_height}}const g=document.createElement("div");g.innerHTML=c.content;const b=Array.prototype.slice.call(g.querySelectorAll("img"));let h=null;for(const e of b){const l=e.getAttribute("src")||"";if(!l){e.remove();continue}let s;try{s=await p(l,20020002)}catch(w){d.push({src:l.slice(0,120),error:String(w&&w.message||w)});e.remove();continue}i.push({src:l.slice(0,120),url:s.url});if(!h)h=s;const r=document.createElement("div");r.className="pgc-img";const o=document.createElement("img");o.setAttribute("src",s.url);o.setAttribute("class","");o.setAttribute("image_type","");o.setAttribute("mime_type","");o.setAttribute("web_uri",s.uri);o.setAttribute("img_width",String(s.width));o.setAttribute("img_height",String(s.height));const u=document.createElement("p");u.className="pgc-img-caption";r.appendChild(o);r.appendChild(u);(e.parentElement||g).replaceChild(r,e)}const U=g.innerHTML,T=[];let f=null,I="";if(t.cover&&String(t.cover).trim())try{f=await p(String(t.cover),20020002)}catch(e){return{ok:!1,stage:"cover",message:"封面图转存失败:"+String(e&&e.message||e),uploaded:i,failed:d}}else if(h){f=h;I=h.uri}if(f){let e;try{e=await y(f.url)}catch(s){return{ok:!1,stage:"cover",message:"封面图生成失败:"+String(s&&s.message||s),uploaded:i,failed:d}}const l={url:e.url,uri:e.uri,width:e.width,height:e.height,thumb_width:e.width,thumb_height:e.height,natural_width:f.width,natural_height:f.height,back_up_url:f.url,need_check:!1,paste:!1,auto_upload:!1,show_optimize_icon:!1,ic:!1,id:0,pos:0};if(I)l.extra={from_content:"1",from_content_uri:I};T.push(l)}await fetch("https://mp.toutiao.com/profile_v4/graphic/publish",{credentials:"include"});function x(){const e=document.cookie.match(/passport_csrf_token=([^;]+)/);return e?e[1]:""}const S=x(),L=new URLSearchParams({title:c.title,article_ad_type:"2",article_type:"0",from_diagnosis:"0",origin_debut_check_pgc_normal:"0",tree_plan_article:"0",save:"1",pgc_id:"0",content:U,pgc_feed_covers:JSON.stringify(T)}),A={"Content-Type":"application/x-www-form-urlencoded"};if(S)A["X-CSRFToken"]=S;const N=await fetch("https://mp.toutiao.com/mp/agw/article/publish?source=mp&type=article&aid=1231",{method:"POST",credentials:"include",headers:A,body:L});let n=null;try{n=await N.json()}catch(e){}const C=n&&(n.code===0||n.err_no===0),v=n&&n.data&&n.data.pgc_id;if(!C||!v||String(v)==="0"){let e=n&&(n.message||n.reason)||"头条号发布失败";if(n&&(n.code===7112||n.err_no===7112))e+="(code 7112「图片URI异常」:正文图或封面图不是头条编辑器图床里的资源。"+"若本次有图片转存失败(见 failed 列表),先解决那张图再发)";if(n&&(n.code===7050||n.err_no===7050))e+="(code 7050「保存失败」:内容可能被风控拦截或账号被平台限制发文,"+"请登录 mp.toutiao.com 查看站内通知)";return{ok:!1,stage:"publish",status:N.status,message:e,detail:n,uploaded:i,failed:d}}const E="https://www.toutiao.com/article/"+String(v)+"/";return{ok:!0,id:String(v),url:E,editUrl:"https://mp.toutiao.com/profile_v4/graphic/publish?pgc_id="+String(v),draft:!1,uploaded:i,failed:d}},checkAuth:async(c)=>{try{const t=await(await fetch("https://mp.toutiao.com/mp/agw/media/get_media_info",{credentials:"include"})).json(),i=t&&t.data&&t.data.user;if(t&&t.code===0&&i&&i.id)return{isAuthenticated:!0,userId:String(i.id),username:i.screen_name||i.name||"",avatar:i.https_avatar_url||i.avatar_url||""};return{isAuthenticated:!1}}catch(a){return{isAuthenticated:!1,error:String(a&&a.message||a)}}}};j({site:"toutiao",name:"article",access:"write",description:"正式发布头条号图文文章(会立即公开,头条无可靠的存草稿接口,故不支持草稿)。正文默认 Markdown,图片自动转存到头条图床。标题需 2~30 字;封面可选(--cover,不传则头条自动从正文图选封面)。",domain:"mp.toutiao.com",strategy:V.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(2~30 字)"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;传 --html 则视为原始 HTML)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"将正文视为原始 HTML 而非 Markdown"},{name:"cover",help:"封面图 URL 或本机路径(可选;会先转存到头条图床)"},{name:"execute",type:"boolean",help:"真正执行写操作。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(c,a)=>{if(!c)throw new D("头条号文章发布需要浏览器会话");R(a);const t=String(a.title??"").trim();if(!t)throw new m("INVALID_INPUT","文章标题不能为空");if(t.length<2||t.length>30)throw new m("INVALID_INPUT",`头条号标题需 2~30 字,当前 ${t.length} 字`);const i=await H(a),p={cover:typeof a.cover==="string"?a.cover.trim():""},y=await F(c,{title:t,body:i,format:a.html?"html":"markdown",profile:toutiaoProfile,publishParams:p}),g=y.images.uploaded.length|0,b=y.images.failed.length|0;let h="已正式发布头条号文章";if(g||b)h+=`(图片:${g} 张已转存${b?`,${b} 张失败`:""})`;return q(h,"article","","created",{created_target:"article:"+y.id,created_url:y.url})}});
1
+ import{CliError as p,CommandExecutionError as D}from"@jackwener/opencli/errors";import{cli as j,Strategy as F}from"@jackwener/opencli/registry";import{formatImageReport as V,publishArticle as M}from"../_shared/article/publish.js";import{readFile as O,stat as R}from"node:fs/promises";import{rememberArticleFile as H}from"../_shared/article/images.js";function q(n){if(!n.execute)throw new p("INVALID_INPUT","此头条号写操作需要 --execute 参数才能真正发布。注意:本报错仅表示缺少 --execute,并未校验其余参数,不能当 dry-run 预览用")}async function K(n){const i=typeof n.text==="string"?n.text:void 0,t=typeof n.file==="string"?n.file:void 0;if(i&&t)throw new p("INVALID_INPUT","正文和 --file 只能选一个");let r=i??"";if(t){H(t);let d;try{d=await R(t)}catch{throw new p("INVALID_INPUT",`找不到文件: ${t}`)}if(!d.isFile())throw new p("INVALID_INPUT",`--file 必须是可读文本文件: ${t}`);let g;try{g=await O(t)}catch{throw new p("INVALID_INPUT",`文件无法读取: ${t}`)}try{r=new TextDecoder("utf-8",{fatal:!0}).decode(g)}catch{throw new p("INVALID_INPUT",`文件必须是 UTF-8 编码: ${t}`)}}if(!r.trim())throw new p("INVALID_INPUT","正文不能为空");return r}function z(n,i,t,r,d={}){return[{status:"success",outcome:r,message:n,target_type:i,target:t,...d}]}export const toutiaoProfile={home:"https://mp.toutiao.com/profile_v3/graphic/publish",outputFormat:"html",preprocessConfig:{},publish:async(n,i)=>{const t=n.params||{},r=[],d=[];async function g(e,l){const s="/spice/image?upload_source="+l+"&need_enhance=true&aid=1231&device_platform=web",o=new FormData;let a;if(/^https?:/i.test(e)){o.append("imageUrl",e);a=await fetch(s+"&scene=paste",{method:"POST",credentials:"include",body:o})}else{const y=await fetch(e,{credentials:"omit"});if(!y.ok)throw Error("图片下载失败 HTTP "+y.status+":"+e.slice(0,80));const U=await y.blob(),E=((U.type||"").split("/")[1]||"jpg").split("+")[0].split(";")[0]||"jpg";o.append("image",U,"image."+E);a=await fetch(s,{method:"POST",credentials:"include",body:o})}const u=await a.json(),w=u&&u.data;if(!u||u.code!==0||!w||!w.image_uri)throw Error((u&&u.message||"图片上传失败")+(u&&u.code!=null?"(接口 code "+u.code+")":""));return{uri:w.image_uri,url:w.image_url,width:w.image_width,height:w.image_height}}async function f(e){const l=new FormData;l.append("imageUrl",e);const o=await(await fetch("/spice/image?upload_source=20020003&aid=1231&device_platform=web&need_cover_url=1",{method:"POST",credentials:"include",body:l})).json(),a=o&&o.data;if(!o||o.code!==0||!a||!a.image_uri)throw Error((o&&o.message||"封面图生成失败")+(o&&o.code!=null?"(接口 code "+o.code+")":""));return{uri:a.image_uri,url:a.image_url,width:a.image_width,height:a.image_height}}const _=document.createElement("div");_.innerHTML=n.content;const b=Array.prototype.slice.call(_.querySelectorAll("img"));let m=null;for(const e of b){const l=e.getAttribute("src")||"";if(!l){e.remove();continue}let s;try{s=await g(l,20020002)}catch(y){d.push({src:l.slice(0,120),key:i.refKey(l),error:String(y&&y.message||y)});e.remove();continue}r.push({src:l.slice(0,120),key:i.refKey(l),url:s.url});if(!m)m=s;const o=document.createElement("div");o.className="pgc-img";const a=document.createElement("img");a.setAttribute("src",s.url);a.setAttribute("class","");a.setAttribute("image_type","");a.setAttribute("mime_type","");a.setAttribute("web_uri",s.uri);a.setAttribute("img_width",String(s.width));a.setAttribute("img_height",String(s.height));const u=document.createElement("p");u.className="pgc-img-caption";o.appendChild(a);o.appendChild(u);(e.parentElement||_).replaceChild(o,e)}const P=_.innerHTML,S=[];let h=null,I="";if(t.cover&&String(t.cover).trim())try{h=await g(String(t.cover),20020002);r.push({src:String(t.cover).slice(0,120),key:i.refKey(String(t.cover)),url:h.url})}catch(e){return{ok:!1,stage:"cover",message:"封面图转存失败:"+String(e&&e.message||e),uploaded:r,failed:d}}else if(m){h=m;I=m.uri}if(h){let e;try{e=await f(h.url)}catch(s){return{ok:!1,stage:"cover",message:"封面图生成失败:"+String(s&&s.message||s),uploaded:r,failed:d}}const l={url:e.url,uri:e.uri,width:e.width,height:e.height,thumb_width:e.width,thumb_height:e.height,natural_width:h.width,natural_height:h.height,back_up_url:h.url,need_check:!1,paste:!1,auto_upload:!1,show_optimize_icon:!1,ic:!1,id:0,pos:0};if(I)l.extra={from_content:"1",from_content_uri:I};S.push(l)}await fetch("https://mp.toutiao.com/profile_v4/graphic/publish",{credentials:"include"});function k(){const e=document.cookie.match(/passport_csrf_token=([^;]+)/);return e?e[1]:""}const T=k(),x=new URLSearchParams({title:n.title,article_ad_type:"2",article_type:"0",from_diagnosis:"0",origin_debut_check_pgc_normal:"0",tree_plan_article:"0",save:"1",pgc_id:"0",content:P,pgc_feed_covers:JSON.stringify(S)}),A={"Content-Type":"application/x-www-form-urlencoded"};if(T)A["X-CSRFToken"]=T;const N=await fetch("https://mp.toutiao.com/mp/agw/article/publish?source=mp&type=article&aid=1231",{method:"POST",credentials:"include",headers:A,body:x});let c=null;try{c=await N.json()}catch(e){}const L=c&&(c.code===0||c.err_no===0),v=c&&c.data&&c.data.pgc_id;if(!L||!v||String(v)==="0"){let e=c&&(c.message||c.reason)||"头条号发布失败";if(c&&(c.code===7112||c.err_no===7112))e+="(code 7112「图片URI异常」:正文图或封面图不是头条编辑器图床里的资源。"+"若本次有图片转存失败(见 failed 列表),先解决那张图再发)";if(c&&(c.code===7050||c.err_no===7050))e+="(code 7050「保存失败」:内容可能被风控拦截或账号被平台限制发文,"+"请登录 mp.toutiao.com 查看站内通知)";return{ok:!1,stage:"publish",status:N.status,message:e,detail:c,uploaded:r,failed:d}}const C="https://www.toutiao.com/article/"+String(v)+"/";return{ok:!0,id:String(v),url:C,editUrl:"https://mp.toutiao.com/profile_v4/graphic/publish?pgc_id="+String(v),draft:!1,uploaded:r,failed:d}},checkAuth:async(n)=>{try{const t=await(await fetch("https://mp.toutiao.com/mp/agw/media/get_media_info",{credentials:"include"})).json(),r=t&&t.data&&t.data.user;if(t&&t.code===0&&r&&r.id)return{isAuthenticated:!0,userId:String(r.id),username:r.screen_name||r.name||"",avatar:r.https_avatar_url||r.avatar_url||""};return{isAuthenticated:!1}}catch(i){return{isAuthenticated:!1,error:String(i&&i.message||i)}}}};j({site:"toutiao",name:"article",access:"write",description:"正式发布头条号图文文章(会立即公开,头条无可靠的存草稿接口,故不支持草稿)。正文默认 Markdown,图片自动转存到头条图床。标题需 2~30 字;封面可选(--cover,不传则头条自动从正文图选封面)。",domain:"mp.toutiao.com",strategy:F.COOKIE,browser:!0,args:[{name:"title",positional:!0,required:!0,help:"文章标题(2~30 字)"},{name:"text",positional:!0,help:"文章正文(默认 Markdown;传 --html 则视为原始 HTML)"},{name:"file",help:"正文文件路径(UTF-8,默认 Markdown)"},{name:"html",type:"boolean",help:"将正文视为原始 HTML 而非 Markdown"},{name:"cover",help:"封面图 URL 或本机路径(可选;会先转存到头条图床)"},{name:"execute",type:"boolean",help:"真正执行写操作。不加此参数时命令拒绝写入。"}],columns:["status","outcome","message","target_type","target","created_target","created_url"],func:async(n,i)=>{if(!n)throw new D("头条号文章发布需要浏览器会话");q(i);const t=String(i.title??"").trim();if(!t)throw new p("INVALID_INPUT","文章标题不能为空");if(t.length<2||t.length>30)throw new p("INVALID_INPUT",`头条号标题需 2~30 字,当前 ${t.length} 字`);const r=await K(i),g={cover:typeof i.cover==="string"?i.cover.trim():""},f=await M(n,{title:t,body:r,format:i.html?"html":"markdown",profile:toutiaoProfile,publishParams:g}),_=f.images.uploaded.length|0,b=f.images.failed.length|0;let m="已正式发布头条号文章";if(_||b)m+=`(图片:${_} 张已转存${b?`,${b} 张失败`:""})`;m+=V(f.images);return z(m,"article","","created",{created_target:"article:"+f.id,created_url:f.url})}});
@@ -1,4 +1,4 @@
1
- import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy as ne}from"@jackwener/opencli/registry";import{ArgumentError as f,AuthRequiredError as ie,CommandExecutionError as c}from"@jackwener/opencli/errors";import{injectInputFiles as ae}from"../_shared/file-inject.js";const M="https://channels.weixin.qq.com/platform/post/create",le=[".post-short-title-wrap input",'input[placeholder*="短标题"]','input[placeholder*="填写短标题"]','input.weui-desktop-form__input[placeholder*="短标题"]',"input.weui-desktop-form__input"],oe=[".post-desc-box .input-editor",'div[contenteditable][data-placeholder="添加描述"]','div.input-editor[contenteditable=""][data-placeholder="添加描述"]','div[data-placeholder*="描述"][contenteditable]',"div.input-editor[contenteditable]"],se=["span.add-icon.weui-icon-outlined-add","div.upload-content",".finder-video-upload-btn"],ue=new Set([".mp4",".mov",".avi",".webm"]),ce=['.post-upload-wrap input[type="file"]','input[type="file"][accept*="video"]','input[type="file"]'],A="https://channels.weixin.qq.com/platform/post/list",j=/^[\u2103\u4E00-\u9FA5A-Za-z0-9《》""“”::+??%\s]+$/,q=16,F=6;function R(e){if(!e)return;if(e.length>q)throw new f(`短标题超过 ${q} 字限制(当前 ${e.length} 字)`);if(e.length<F)throw new f(`短标题至少 ${F} 个字(当前 ${e.length} 字)`);if(!j.test(e)){const t=Array.from(new Set(Array.from(e).filter((i)=>!j.test(i)))).join(" ");throw new f(`短标题包含平台不接受的字符: ${t}`,"短标题只能用中文、英文字母、数字、空格,符号仅支持书名号、引号、冒号、加号、问号、百分号、摄氏度;逗号请改用空格")}}function de(e){if(e&&typeof e==="object"&&"data"in e&&"session"in e)return e.data;return e}async function d(e,t){return de(await e.evaluate(t))}function P(e,t,i){const n=D.resolve(String(e));let r;try{r=te.statSync(n)}catch{throw new f(`${t}文件不存在: ${n}`)}if(!r.isFile())throw new f(`${t}路径不是文件: ${n}`);const a=D.extname(n).toLowerCase();if(!i.has(a))throw new f(`不支持的${t}格式: ${a}(支持 ${Array.from(i).join("/")})`);return n}function Q(e){const t=e==null||e===""?600:Number(e);if(!Number.isInteger(t)||t<30)throw new f("--timeout must be an integer >= 30 seconds");return t}function L(e){if(!e)return null;const t=typeof e==="number"?new Date(e<1000000000000?e*1000:e):new Date(String(e));if(Number.isNaN(t.getTime()))throw new f(`无法解析定时时间: ${e}`);if(t.getTime()<=Date.now())throw new f("定时时间必须晚于当前时间");t.setSeconds(0,0);return t}function O(e){return e===!0||e==="true"||e==="1"||e===1}function fe(e,t){const i=e-Date.now();if(i<=0)throw new c(`${t}超时,请增加 --timeout 后重试`);return i}function U({isDraft:e,finalUrl:t,successMsg:i}){const n=String(i||"");if(e)return/已保存|暂存成功|保存成功/.test(n);if(/已发表|发布成功|发表成功|审核中/.test(n))return!0;const r=String(t||"");return/\/platform\/post\/list\b/.test(r)}const p=`
1
+ import*as ae from"node:fs";import*as C from"node:path";import{cli as oe,Strategy as le}from"@jackwener/opencli/registry";import{ArgumentError as f,AuthRequiredError as se,CommandExecutionError as c}from"@jackwener/opencli/errors";import{injectInputFiles as ue}from"../_shared/file-inject.js";const I="https://channels.weixin.qq.com/platform/post/create",ce=[".post-short-title-wrap input",'input[placeholder*="短标题"]','input[placeholder*="填写短标题"]','input.weui-desktop-form__input[placeholder*="短标题"]',"input.weui-desktop-form__input"],de=[".post-desc-box .input-editor",'div[contenteditable][data-placeholder="添加描述"]','div.input-editor[contenteditable=""][data-placeholder="添加描述"]','div[data-placeholder*="描述"][contenteditable]',"div.input-editor[contenteditable]"],fe=["span.add-icon.weui-icon-outlined-add","div.upload-content",".finder-video-upload-btn"],pe=new Set([".mp4",".mov",".avi",".webm"]),me=['.post-upload-wrap input[type="file"]','input[type="file"][accept*="video"]','input[type="file"]'],T="https://channels.weixin.qq.com/platform/post/list",j=/^[\u2103\u4E00-\u9FA5A-Za-z0-9《》""“”::+??%\s]+$/,F=16,L=6;function Q(e){if(!e)return;if(e.length>F)throw new f(`短标题超过 ${F} 字限制(当前 ${e.length} 字)`);if(e.length<L)throw new f(`短标题至少 ${L} 个字(当前 ${e.length} 字)`);if(!j.test(e)){const t=Array.from(new Set(Array.from(e).filter((i)=>!j.test(i)))).join(" ");throw new f(`短标题包含平台不接受的字符: ${t}`,"短标题只能用中文、英文字母、数字、空格,符号仅支持书名号、引号、冒号、加号、问号、百分号、摄氏度;逗号请改用空格")}}function he(e){if(e&&typeof e==="object"&&"data"in e&&"session"in e)return e.data;return e}async function d(e,t){return he(await e.evaluate(t))}function B(e,t,i){const n=C.resolve(String(e));let r;try{r=ae.statSync(n)}catch{throw new f(`${t}文件不存在: ${n}`)}if(!r.isFile())throw new f(`${t}路径不是文件: ${n}`);const a=C.extname(n).toLowerCase();if(!i.has(a))throw new f(`不支持的${t}格式: ${a}(支持 ${Array.from(i).join("/")})`);return n}function H(e){const t=e==null||e===""?600:Number(e);if(!Number.isInteger(t)||t<30)throw new f("--timeout must be an integer >= 30 seconds");return t}function U(e){if(!e)return null;const t=typeof e==="number"?new Date(e<1000000000000?e*1000:e):new Date(String(e));if(Number.isNaN(t.getTime()))throw new f(`无法解析定时时间: ${e}`);if(t.getTime()<=Date.now())throw new f("定时时间必须晚于当前时间");t.setSeconds(0,0);return t}function O(e){return e===!0||e==="true"||e==="1"||e===1}function we(e,t){const i=e-Date.now();if(i<=0)throw new c(`${t}超时,请增加 --timeout 后重试`);return i}function J({isDraft:e,finalUrl:t,successMsg:i}){const n=String(i||"");if(e)return/已保存|暂存成功|保存成功/.test(n);if(/已发表|发布成功|发表成功|审核中/.test(n))return!0;const r=String(t||"");return/\/platform\/post\/list\b/.test(r)}const p=`
2
2
  function wujieRoot() {
3
3
  var w = document.querySelector('wujie-app');
4
4
  return (w && w.shadowRoot) || null;
@@ -25,7 +25,27 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
25
25
  var rect = el.getBoundingClientRect();
26
26
  return rect.width > 0 && rect.height > 0;
27
27
  }
28
- `,E=`
28
+ `,V=`
29
+ function oTextOf(el) { return (el && (el.innerText || el.textContent) || '').replace(/\\s+/g, ''); }
30
+ function oButtons(scope, label) {
31
+ var list = scope ? Array.prototype.slice.call(scope.querySelectorAll('button')) : deepQueryAll('button');
32
+ return list.filter(function (b) { return isVisible(b) && oTextOf(b) === label; });
33
+ }
34
+ function findOriginalDialog() {
35
+ var direct = oButtons(null, '直接发表');
36
+ for (var i = 0; i < direct.length; i++) {
37
+ var node = direct[i].parentNode;
38
+ while (node && node.nodeType === 1 && !oButtons(node, '声明原创').length) node = node.parentNode;
39
+ if (!node || node.nodeType !== 1) continue;
40
+ // 两个按钮的共同祖先可能只是弹窗底栏;往上找到带说明文案(分成 / 须知)的弹窗本体,不越过发布表单。
41
+ for (var up = node; up && up.nodeType === 1 && !up.querySelector('.form-btns'); up = up.parentNode) {
42
+ if (/分成|须知|权益/.test(oTextOf(up))) return up;
43
+ }
44
+ return node;
45
+ }
46
+ return null;
47
+ }
48
+ `,A=`
29
49
  function vmOf(el) {
30
50
  while (el) {
31
51
  if (el.__vue__) return el.__vue__;
@@ -77,6 +97,7 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
77
97
  isPosting: pv ? safe(function () { return !!pv.isPosting; }) : null,
78
98
  isCaching: pv ? safe(function () { return !!pv.isCaching; }) : null,
79
99
  originalIntercept: pv ? safe(function () { return !!pv.visibleOriginalIntercept; }) : null,
100
+ originalDialog: typeof findOriginalDialog === 'function' ? !!findOriginalDialog() : null,
80
101
  draftObjectId: pv ? safe(function () { return String(pv.draftStore.objectId || ''); }) : null,
81
102
  files: files,
82
103
  schedule: sv ? {
@@ -89,10 +110,10 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
89
110
  titleError: titleErrEl ? (titleErrEl.innerText || titleErrEl.textContent || '').trim() : '',
90
111
  };
91
112
  }
92
- `;async function x(e){return d(e,`(() => { ${p} ${E} return readFormState(); })()`)}function H(e){if(!e)return{known:!1,seconds:null};const t=e.effectiveTime,i=t===null||typeof t==="number",n=i&&t?t:null,r=e.schedule,a=!!r&&Number.isFinite(r.time);let l=null;if(a&&r.checked&&r.time){const o=Number.isFinite(r.minTime)?Math.max(r.time,r.minTime):r.time;l=Math.floor(o/1000)}if(i&&a&&n!==l)return{known:!0,conflict:!0,seconds:n??l,formSeconds:n,pickerSeconds:l};if(i)return{known:!0,seconds:n};if(a)return{known:!0,seconds:l};return{known:!1,seconds:null}}function g(e){const t=new Date(e*1000),i=(n)=>String(n).padStart(2,"0");return`${t.getFullYear()}-${i(t.getMonth()+1)}-${i(t.getDate())} ${i(t.getHours())}:${i(t.getMinutes())}`}function N(e,{targetSeconds:t,isDraft:i}){if(e?.titleError)return`平台拒绝了短标题: ${e.titleError}`;if(Array.isArray(e?.files)){if(e.files.length===0)return"视频上传失败:上传区是空的,文件没有进入页面的上传队列";if(e.files.some((a)=>a.status==="error"))return"视频上传失败:页面把文件标记为上传出错";const r=e.files.filter((a)=>a.status!=="done");if(r.length)return`视频还没上传完成(状态 ${r.map((a)=>`${a.status||"未知"} ${a.percent}%`).join(", ")})`}const n=H(e);if(n.conflict){const r=(a)=>a?g(a):"不定时";return`表单内部的定时值互相矛盾(表单 ${r(n.formSeconds)} / 时间选择器 ${r(n.pickerSeconds)}),为避免错时发布已中止`}if(t){if(!n.known)return"无法回读表单里的定时发表时间,为避免错时发布已中止";if(n.seconds!==t)return`表单里的定时发表时间与目标不一致:目标 ${g(t)},表单实际 ${n.seconds?g(n.seconds):"不定时"},为避免错时发布已中止`;if(e.isEffectiveTimeValid===!1)return"页面判定定时发表时间不合法,已中止"}else if(n.known&&n.seconds)return`表单处于定时发表状态(${g(n.seconds)}),但本次没有指定 --schedule,已中止`;if(i&&e?.isPostByTime)return"定时发表状态下平台不允许保存草稿";return null}async function pe(e){return await d(e,`
113
+ `;async function M(e){return d(e,`(() => { ${p} ${V} ${A} return readFormState(); })()`)}function G(e){if(!e)return{known:!1,seconds:null};const t=e.effectiveTime,i=t===null||typeof t==="number",n=i&&t?t:null,r=e.schedule,a=!!r&&Number.isFinite(r.time);let o=null;if(a&&r.checked&&r.time){const l=Number.isFinite(r.minTime)?Math.max(r.time,r.minTime):r.time;o=Math.floor(l/1000)}if(i&&a&&n!==o)return{known:!0,conflict:!0,seconds:n??o,formSeconds:n,pickerSeconds:o};if(i)return{known:!0,seconds:n};if(a)return{known:!0,seconds:o};return{known:!1,seconds:null}}function _(e){const t=new Date(e*1000),i=(n)=>String(n).padStart(2,"0");return`${t.getFullYear()}-${i(t.getMonth()+1)}-${i(t.getDate())} ${i(t.getHours())}:${i(t.getMinutes())}`}function q(e,{targetSeconds:t,isDraft:i}){if(e?.titleError)return`平台拒绝了短标题: ${e.titleError}`;if(Array.isArray(e?.files)){if(e.files.length===0)return"视频上传失败:上传区是空的,文件没有进入页面的上传队列";if(e.files.some((a)=>a.status==="error"))return"视频上传失败:页面把文件标记为上传出错";const r=e.files.filter((a)=>a.status!=="done");if(r.length)return`视频还没上传完成(状态 ${r.map((a)=>`${a.status||"未知"} ${a.percent}%`).join(", ")})`}const n=G(e);if(n.conflict){const r=(a)=>a?_(a):"不定时";return`表单内部的定时值互相矛盾(表单 ${r(n.formSeconds)} / 时间选择器 ${r(n.pickerSeconds)}),为避免错时发布已中止`}if(t){if(!n.known)return"无法回读表单里的定时发表时间,为避免错时发布已中止";if(n.seconds!==t)return`表单里的定时发表时间与目标不一致:目标 ${_(t)},表单实际 ${n.seconds?_(n.seconds):"不定时"},为避免错时发布已中止`;if(e.isEffectiveTimeValid===!1)return"页面判定定时发表时间不合法,已中止"}else if(n.known&&n.seconds)return`表单处于定时发表状态(${_(n.seconds)}),但本次没有指定 --schedule,已中止`;if(i&&e?.isPostByTime)return"定时发表状态下平台不允许保存草稿";return null}async function ve(e){return await d(e,`
93
114
  (() => {
94
115
  ${p}
95
- var sels = ${JSON.stringify(se)};
116
+ var sels = ${JSON.stringify(fe)};
96
117
  for (var i = 0; i < sels.length; i++) {
97
118
  var el = deepQuery(sels[i]);
98
119
  if (el && isVisible(el)) {
@@ -102,7 +123,7 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
102
123
  }
103
124
  return { ok: false };
104
125
  })()
105
- `)}async function me(e,t=15000){const i=500,n=Math.max(1,Math.ceil(t/i));for(let r=0;r<n;r++){if(await d(e,`
126
+ `)}async function be(e,t=15000){const i=500,n=Math.max(1,Math.ceil(t/i));for(let r=0;r<n;r++){if(await d(e,`
106
127
  (() => {
107
128
  ${p}
108
129
  var inputSels = ['input[type="file"][accept*="video"]', 'input[type="file"]'];
@@ -111,7 +132,7 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
111
132
  }
112
133
  return false;
113
134
  })()
114
- `))return!0;if(r<n-1)await e.wait({time:i/1000})}return!1}const B=`((sel) => {
135
+ `))return!0;if(r<n-1)await e.wait({time:i/1000})}return!1}const Y=`((sel) => {
115
136
  ${p}
116
137
  var real = deepQuery(sel);
117
138
  if (!real) return null;
@@ -141,11 +162,11 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
141
162
  return real.dispatchEvent(new win.Event(ev.type, { bubbles: true }));
142
163
  },
143
164
  };
144
- })`;async function he(e,t){await pe(e);await e.wait({time:1});await me(e);let i;for(const n of ce)try{await ae(e,n,[t],{findInputJs:B});const r=await d(e,"(() => { var r = window.__ppWxInject || null; delete window.__ppWxInject; return r; })()");if(!r||r.error||r.count!==1||!r.realm)throw new c(`文件没能交给页面的上传控件: ${r?.error||`count=${r?.count??"未知"} realm=${r?.realm??"未知"}`}`);return}catch(r){i=r;if(!(r instanceof Error?r.message:String(r)).includes("未找到文件上传输入框"))break}await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c(`视频文件注入失败: ${i instanceof Error?i.message:String(i)}
145
- 截图已保存到 /tmp/wechat-channels_publish_upload_debug.png`)}function J(e){if(!Array.isArray(e))return"unknown";if(e.length===0)return"empty";if(e.some((t)=>t.status==="error"))return"error";return e.every((t)=>t.status==="done")?"done":"pending"}async function we(e,t,i=180000){const n=3000,r=Math.ceil(i/n),a=Math.ceil(20000/n);let l=0;for(let o=0;o<r;o++){let s;try{s=await d(e,`
165
+ })`;async function ge(e,t){await ve(e);await e.wait({time:1});await be(e);let i;for(const n of me)try{await ue(e,n,[t],{findInputJs:Y});const r=await d(e,"(() => { var r = window.__ppWxInject || null; delete window.__ppWxInject; return r; })()");if(!r||r.error||r.count!==1||!r.realm)throw new c(`文件没能交给页面的上传控件: ${r?.error||`count=${r?.count??"未知"} realm=${r?.realm??"未知"}`}`);return}catch(r){i=r;if(!(r instanceof Error?r.message:String(r)).includes("未找到文件上传输入框"))break}await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c(`视频文件注入失败: ${i instanceof Error?i.message:String(i)}
166
+ 截图已保存到 /tmp/wechat-channels_publish_upload_debug.png`)}function W(e){if(!Array.isArray(e))return"unknown";if(e.length===0)return"empty";if(e.some((t)=>t.status==="error"))return"error";return e.every((t)=>t.status==="done")?"done":"pending"}async function _e(e,t,i=180000){const n=3000,r=Math.ceil(i/n),a=Math.ceil(20000/n);let o=0;for(let l=0;l<r;l++){let s;try{s=await d(e,`
146
167
  ((fileName) => {
147
168
  ${p}
148
- ${E}
169
+ ${A}
149
170
  var files = readFormState().files;
150
171
  if (Array.isArray(files)) return { files: files };
151
172
 
@@ -164,8 +185,8 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
164
185
  var hasFileEvidence = fileName && bodyText.indexOf(fileName) >= 0;
165
186
  return { done: !uploading && (preview || hasFileEvidence), failed: false };
166
187
  })(${JSON.stringify(t)})
167
- `)}catch(u){const h=u instanceof Error?u.message:String(u);if(h.includes("ECONNRESET")||h.includes("fetch failed")){process.stderr.write(` [retry] bridge reconnecting after page re-render (${o+1}/${r})...
168
- `);await e.wait({time:n/1000});continue}throw u}const m=J(s?.files);if(m==="error"||s?.failed){await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c("视频上传失败:页面把文件标记为上传出错,请检查文件格式和网络连接","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试")}if(m==="done"||m==="unknown"&&s?.done)return;if(m==="empty"){l+=1;if(l>=a){await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c("视频上传失败:文件已注入但页面上传区仍为空,页面没有收下这个文件","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试;反复出现说明视频号上传控件改版")}}else l=0;await e.wait({time:n/1000})}throw new c(`视频上传/转码超时(${Math.ceil(i/1000)}秒),请检查网络或稍后重试`)}async function Y(e,t,i,n){const r=30;let a;for(let l=0;l<r;l++){a=await d(e,`
188
+ `)}catch(u){const h=u instanceof Error?u.message:String(u);if(h.includes("ECONNRESET")||h.includes("fetch failed")){process.stderr.write(` [retry] bridge reconnecting after page re-render (${l+1}/${r})...
189
+ `);await e.wait({time:n/1000});continue}throw u}const m=W(s?.files);if(m==="error"||s?.failed){await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c("视频上传失败:页面把文件标记为上传出错,请检查文件格式和网络连接","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试")}if(m==="done"||m==="unknown"&&s?.done)return;if(m==="empty"){o+=1;if(o>=a){await e.screenshot({path:"/tmp/wechat-channels_publish_upload_debug.png"});throw new c("视频上传失败:文件已注入但页面上传区仍为空,页面没有收下这个文件","截图: /tmp/wechat-channels_publish_upload_debug.png。本次没有提交任何内容,可以直接重试;反复出现说明视频号上传控件改版")}}else o=0;await e.wait({time:n/1000})}throw new c(`视频上传/转码超时(${Math.ceil(i/1000)}秒),请检查网络或稍后重试`)}async function K(e,t,i,n){const r=30;let a;for(let o=0;o<r;o++){a=await d(e,`
169
190
  (function(selectors, text) {
170
191
  ${p}
171
192
 
@@ -212,10 +233,10 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
212
233
  el.blur();
213
234
  return { ok: actual.indexOf(text) >= 0, sel: foundSel, actual: actual };
214
235
  })(${JSON.stringify(t)}, ${JSON.stringify(i)})
215
- `);if(a?.ok)break;if(l<r-1)await e.wait({time:0.5})}if(!a?.ok){await e.screenshot({path:`/tmp/wechat-channels_publish_${n}_debug.png`});throw new c(`找不到 ${n} 输入框,截图已保存到 /tmp/wechat-channels_publish_${n}_debug.png`)}}const G=`
236
+ `);if(a?.ok)break;if(o<r-1)await e.wait({time:0.5})}if(!a?.ok){await e.screenshot({path:`/tmp/wechat-channels_publish_${n}_debug.png`});throw new c(`找不到 ${n} 输入框,截图已保存到 /tmp/wechat-channels_publish_${n}_debug.png`)}}const X=`
216
237
  (async function(TY, TM, TD, TH, TMin, TARGET_MS) {
217
238
  ${p}
218
- ${E}
239
+ ${A}
219
240
  function sleep(ms) { return new Promise(function(r) { setTimeout(r, ms); }); }
220
241
  function click(el) {
221
242
  el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
@@ -364,8 +385,8 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
364
385
  var inp = dateDl.querySelector('dt input') || deepQuery('input[placeholder*="发表时间"]');
365
386
  return { ok: true, value: inp ? inp.value : null, pick: pickOf(), commit: commit.join('+'), state: readFormState() };
366
387
  })
367
- `;async function ve(e,t){const i=t.getFullYear(),n=t.getMonth()+1,r=t.getDate(),a=t.getHours(),l=t.getMinutes(),o=(v)=>String(v).padStart(2,"0"),s=t.getTime(),m=Math.floor(s/1000),u=await d(e,`${G}(${i}, ${n}, ${r}, ${a}, ${l}, ${s})`);if(!u?.ok){await e.screenshot({path:"/tmp/wechat-channels_schedule_debug.png"});const v=u?.reason?String(u.reason):"empty picker result";if(v==="timezone-mismatch")throw new c("定时设置失败:浏览器与命令行所在时区不一致,无法按钟点可靠地选中目标时刻,已中止");throw new c(`定时设置失败 (${v}),截图: /tmp/wechat-channels_schedule_debug.png`)}const h=`${i}-${o(n)}-${o(r)} ${o(a)}:${o(l)}`,w=[];if(!String(u.value||"").includes(h))w.push(`显示框=${u.value||"空"}`);if(u.pick!=null&&Math.floor(u.pick/1000)!==m)w.push(`时间选择器选中=${g(Math.floor(u.pick/1000))}`);const y=N({...u.state,files:null,titleError:""},{targetSeconds:m,isDraft:!1});if(y)w.push(y);if(w.length){await e.screenshot({path:"/tmp/wechat-channels_schedule_debug.png"});throw new c(`定时设置未验证成功: 目标=${h};${w.join(";")}`,"本次没有提交任何内容。截图: /tmp/wechat-channels_schedule_debug.png")}process.stderr.write(` 定时设置完成: ${u.value||h}(表单回读一致)
368
- `)}const W=`
388
+ `;async function ye(e,t){const i=t.getFullYear(),n=t.getMonth()+1,r=t.getDate(),a=t.getHours(),o=t.getMinutes(),l=(y)=>String(y).padStart(2,"0"),s=t.getTime(),m=Math.floor(s/1000),u=await d(e,`${X}(${i}, ${n}, ${r}, ${a}, ${o}, ${s})`);if(!u?.ok){await e.screenshot({path:"/tmp/wechat-channels_schedule_debug.png"});const y=u?.reason?String(u.reason):"empty picker result";if(y==="timezone-mismatch")throw new c("定时设置失败:浏览器与命令行所在时区不一致,无法按钟点可靠地选中目标时刻,已中止");throw new c(`定时设置失败 (${y}),截图: /tmp/wechat-channels_schedule_debug.png`)}const h=`${i}-${l(n)}-${l(r)} ${l(a)}:${l(o)}`,w=[];if(!String(u.value||"").includes(h))w.push(`显示框=${u.value||"空"}`);if(u.pick!=null&&Math.floor(u.pick/1000)!==m)w.push(`时间选择器选中=${_(Math.floor(u.pick/1000))}`);const k=q({...u.state,files:null,titleError:""},{targetSeconds:m,isDraft:!1});if(k)w.push(k);if(w.length){await e.screenshot({path:"/tmp/wechat-channels_schedule_debug.png"});throw new c(`定时设置未验证成功: 目标=${h};${w.join(";")}`,"本次没有提交任何内容。截图: /tmp/wechat-channels_schedule_debug.png")}process.stderr.write(` 定时设置完成: ${u.value||h}(表单回读一致)
389
+ `)}const z=`
369
390
  (function(isDraft, labels) {
370
391
  ${p}
371
392
  function isDisabled(btn) {
@@ -405,19 +426,87 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
405
426
  target.click();
406
427
  return { ok: true, how: how, text: (target.innerText || target.textContent || '').trim() };
407
428
  })
408
- `;async function be(e,t){const i=t?["保存草稿","存草稿","草稿"]:["发表","发布"],n=t?"保存草稿":"发表",r=30;let a;for(let l=0;l<r;l++){a=await d(e,`${W}(${JSON.stringify(t)}, ${JSON.stringify(i)})`);if(a?.ok)break;if(l<r-1)await e.wait({time:0.5})}if(!a?.ok){await e.screenshot({path:"/tmp/wechat-channels_publish_submit_debug.png"});const l=await x(e).catch(()=>null),o=a?.found?`「${n}」按钮一直是禁用状态${l?.disabledTip?`,页面给出的原因: ${l.disabledTip}`:""}`:`页面上没有「${n}」按钮`;throw new c(`${o}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}return a}re({site:"wechat-channels",name:"publish",access:"write",description:"发布视频到视频号",domain:"channels.weixin.qq.com",strategy:ne.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"video",required:!0,positional:!0,help:"视频文件路径 (.mp4/.mov/.avi/.webm)"},{name:"title",required:!1,help:"短标题(6-16 字;只能用中文/字母/数字/空格和 《》“”:+?% ℃,逗号请用空格代替)"},{name:"caption",fromFile:!0,required:!1,help:"描述内容,支持直接写 #话题(如:日常生活 #搞笑 #生活)"},{name:"schedule",required:!1,help:'定时发布时间(ISO8601 或 Unix 秒,如 "2026-05-20 10:00",精确到分钟;不能与 --draft 同用)'},{name:"draft",type:"bool",default:!1,help:"保存为草稿(平台不允许定时稿存草稿)"},{name:"manual",type:"bool",default:!1,help:"填完所有字段后不自动发布,由用户手动点击发表(务必同时传 --site-session persistent,否则表单页约 30 秒后会被重置为空白页)"},{name:"timeout",type:"int",required:!1,default:600,help:"命令整体超时秒数(含登录等待 + 上传转码,默认 600)"}],columns:["status","title","detail","id","manage_url"],func:async(e,t)=>{if(!e)throw new c("需要浏览器页面");const i=Q(t.timeout),n=Date.now()+i*1000,r=P(t.video,"视频",ue),a=String(t.title??"").trim(),l=String(t.caption??"").trim(),o=L(t.schedule||null),s=O(t.draft),m=O(t.manual);R(a);if(s&&o)throw new f("--draft 不能与 --schedule 同用:视频号在定时发表状态下禁用保存草稿");const u=o?Math.floor(o.getTime()/1000):0;await e.goto(M);await e.wait({time:4});{const b=(T)=>typeof T==="string"&&T.includes("/platform/post/create"),I=await d(e,"() => location.href");if(!b(I)){process.stderr.write(`
429
+ `,Z=`
430
+ (async function(choice) {
431
+ ${p}
432
+ ${V}
433
+ function sleep(ms) { return new Promise(function (r) { setTimeout(r, ms); }); }
434
+ function fire(el) {
435
+ var r = el.getBoundingClientRect();
436
+ var opts = { bubbles: true, cancelable: true, composed: true, view: window, button: 0,
437
+ clientX: r.left + r.width / 2, clientY: r.top + r.height / 2 };
438
+ var P = typeof PointerEvent === 'function' ? PointerEvent : MouseEvent;
439
+ el.dispatchEvent(new P('pointerdown', opts));
440
+ el.dispatchEvent(new MouseEvent('mousedown', opts));
441
+ el.dispatchEvent(new P('pointerup', opts));
442
+ el.dispatchEvent(new MouseEvent('mouseup', opts));
443
+ el.dispatchEvent(new MouseEvent('click', opts));
444
+ }
445
+ function btnDisabled(b) {
446
+ return b.disabled || b.getAttribute('disabled') !== null || /disabled/.test(b.className || '');
447
+ }
448
+ // 须知勾选框:优先 .original-proto-wrapper;没有这层时取框内文案像「须知 / 条款 / 同意」的勾选框,
449
+ // 绝不碰「不再提醒」那个(勾了会改账号设置)。
450
+ function termsBoxes(dialog) {
451
+ var scope = dialog.querySelector('.original-proto-wrapper');
452
+ var inputs = Array.prototype.slice.call((scope || dialog).querySelectorAll('input[type="checkbox"]'));
453
+ return inputs.map(function (input) {
454
+ var wrap = input.closest('.ant-checkbox-wrapper, label') || input.parentNode;
455
+ return { input: input, wrap: wrap, text: oTextOf(wrap.parentNode || wrap) };
456
+ }).filter(function (b) {
457
+ if (b.text.indexOf('不再提醒') >= 0 && !scope) return false;
458
+ return scope ? true : /须知|条款|同意|阅读|权益/.test(b.text);
459
+ });
460
+ }
461
+ function boxChecked(b) {
462
+ return !!(b.input.checked
463
+ || (b.wrap.classList && b.wrap.classList.contains('ant-checkbox-wrapper-checked'))
464
+ || b.wrap.querySelector('.ant-checkbox-checked'));
465
+ }
466
+ var dialog = findOriginalDialog();
467
+ if (!dialog) return { ok: false, reason: 'dialog-not-found' };
468
+ var dialogText = oTextOf(dialog).slice(0, 200);
469
+ var label = choice === 'original' ? '声明原创' : '直接发表';
470
+ var terms = [];
471
+ if (choice === 'original') {
472
+ terms = termsBoxes(dialog);
473
+ for (var t = 0; t < terms.length; t++) {
474
+ if (!boxChecked(terms[t])) fire(terms[t].input.getBoundingClientRect().width ? terms[t].input : terms[t].wrap);
475
+ }
476
+ for (var w = 0; w < 15 && terms.some(function (b) { return !boxChecked(b); }); w++) await sleep(200);
477
+ if (terms.some(function (b) { return !boxChecked(b); })) {
478
+ return { ok: false, reason: 'terms-unchecked', dialogText: dialogText };
479
+ }
480
+ }
481
+ var btn = null;
482
+ for (var a = 0; a < 15; a++) {
483
+ btn = oButtons(dialog, label)[0] || null;
484
+ if (btn && !btnDisabled(btn)) break;
485
+ await sleep(200);
486
+ }
487
+ if (!btn) return { ok: false, reason: 'button-not-found', label: label, dialogText: dialogText };
488
+ if (btnDisabled(btn)) return { ok: false, reason: 'button-disabled', label: label, termsCount: terms.length, dialogText: dialogText };
489
+ fire(btn);
490
+ for (var c = 0; c < 25; c++) {
491
+ await sleep(200);
492
+ if (!findOriginalDialog()) return { ok: true, label: label, termsCount: terms.length };
493
+ }
494
+ return { ok: false, reason: 'dialog-still-open', label: label, termsCount: terms.length, dialogText: dialogText };
495
+ })
496
+ `,ke={"dialog-not-found":"页面状态显示被原创确认框拦下,但没找到含「直接发表 / 声明原创」按钮的弹窗(平台可能改版)","terms-unchecked":"勾选原创权益须知后回读仍未勾上","button-not-found":"确认框里没有找到对应按钮","button-disabled":"确认框里的按钮一直是禁用状态(--original 时多半是须知没勾上,或账号当前不能声明原创)","dialog-still-open":"点了按钮后确认框没有关闭"};async function Te(e,t){const n=await d(e,`${Z}(${JSON.stringify(t?"original":"direct")})`);if(!n?.ok){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});const r=ke[n?.reason]||`确认框响应异常: ${JSON.stringify(n)}`;throw new c(`发表被平台的原创声明确认框拦下,自动选择「${t?"声明原创":"直接发表"}」失败:${r},作品尚未发出`,`先到 ${T} 确认作品列表里没有这条再重试;也可以换 ${t?"不带 --original(直接发表)":"--original(声明原创)"} 重试,`+"或加 --manual --site-session persistent 后在浏览器里手动选择。截图: /tmp/wechat-channels_publish_result_debug.png"+(n?.dialogText?`;弹窗文字: ${n.dialogText}`:""))}process.stderr.write(` 原创确认框: 已选择「${n.label}」${t?`(须知勾选框 ${n.termsCount} 个,已回读勾上)`:""}
497
+ `);return n}async function Se(e,t){const i=t?["保存草稿","存草稿","草稿"]:["发表","发布"],n=t?"保存草稿":"发表",r=30;let a;for(let o=0;o<r;o++){a=await d(e,`${z}(${JSON.stringify(t)}, ${JSON.stringify(i)})`);if(a?.ok)break;if(o<r-1)await e.wait({time:0.5})}if(!a?.ok){await e.screenshot({path:"/tmp/wechat-channels_publish_submit_debug.png"});const o=await M(e).catch(()=>null),l=a?.found?`「${n}」按钮一直是禁用状态${o?.disabledTip?`,页面给出的原因: ${o.disabledTip}`:""}`:`页面上没有「${n}」按钮`;throw new c(`${l}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}return a}oe({site:"wechat-channels",name:"publish",access:"write",description:"发布视频到视频号",domain:"channels.weixin.qq.com",strategy:le.COOKIE,browser:!0,navigateBefore:!1,args:[{name:"video",required:!0,positional:!0,help:"视频文件路径 (.mp4/.mov/.avi/.webm)"},{name:"title",required:!1,help:"短标题(6-16 字;只能用中文/字母/数字/空格和 《》“”:+?% ℃,逗号请用空格代替)"},{name:"caption",fromFile:!0,required:!1,help:"描述内容,支持直接写 #话题(如:日常生活 #搞笑 #生活)"},{name:"schedule",required:!1,help:'定时发布时间(ISO8601 或 Unix 秒,如 "2026-05-20 10:00",精确到分钟;不能与 --draft 同用)'},{name:"draft",type:"bool",default:!1,help:"保存为草稿(平台不允许定时稿存草稿)"},{name:"manual",type:"bool",default:!1,help:"填完所有字段后不自动发布,由用户手动点击发表(务必同时传 --site-session persistent,否则表单页约 30 秒后会被重置为空白页)"},{name:"timeout",type:"int",required:!1,default:600,help:"命令整体超时秒数(含登录等待 + 上传转码,默认 600)"},{name:"original",type:"bool",default:!1,help:"创作分成计划账号发表时会弹「声明原创的视频有机会获得广告分成」确认框:默认自动点「直接发表」;传 --original 则勾选原创权益须知并点「声明原创」。不弹框的账号此参数无效果"}],columns:["status","title","detail","id","manage_url"],func:async(e,t)=>{if(!e)throw new c("需要浏览器页面");const i=H(t.timeout),n=Date.now()+i*1000,r=B(t.video,"视频",pe),a=String(t.title??"").trim(),o=String(t.caption??"").trim(),l=U(t.schedule||null),s=O(t.draft),m=O(t.manual),u=O(t.original);Q(a);if(u&&(s||m))throw new f("--original 只在自动发表时生效:原创确认框在点「发表」后才出现,不能与 --draft / --manual 同用");if(s&&l)throw new f("--draft 不能与 --schedule 同用:视频号在定时发表状态下禁用保存草稿");const h=l?Math.floor(l.getTime()/1000):0;await e.goto(I);await e.wait({time:4});{const v=(D)=>typeof D==="string"&&D.includes("/platform/post/create"),E=await d(e,"() => location.href");if(!v(E)){process.stderr.write(`
409
498
  ⚠️ 未登录视频号(已被重定向离开发布页)。请在 Chrome 中扫码登录...
410
- `+" 当前地址: "+I+`
499
+ `+" 当前地址: "+E+`
411
500
  `+` 登录完成后将自动继续发布。
412
501
 
413
- `);const T=Math.min(n,Date.now()+120000);let V=!1;while(Date.now()<T){await e.wait({time:3});await e.goto(M);await e.wait({time:2});const ee=await d(e,"() => location.href");if(b(ee)){V=!0;break}process.stderr.write(` 等待扫码中...
414
- `)}if(!V)throw new ie("channels.weixin.qq.com","登录超时(2分钟),请手动登录后重试");process.stderr.write(`✅ 登录成功,继续发布...
502
+ `);const D=Math.min(n,Date.now()+120000);let P=!1;while(Date.now()<D){await e.wait({time:3});await e.goto(I);await e.wait({time:2});const ie=await d(e,"() => location.href");if(v(ie)){P=!0;break}process.stderr.write(` 等待扫码中...
503
+ `)}if(!P)throw new se("channels.weixin.qq.com","登录超时(2分钟),请手动登录后重试");process.stderr.write(`✅ 登录成功,继续发布...
415
504
 
416
- `);await e.wait({time:3});await e.goto(M);await e.wait({time:5})}}await he(e,r);await e.wait({time:2});await we(e,D.basename(r),Math.min(180000,fe(n,"视频上传/转码")));await e.wait({time:1});if(a){await Y(e,le,a,"title");await e.wait({time:0.5});const b=await x(e);if(b?.titleError)throw new c(`平台拒绝了短标题: ${b.titleError}`,"本次没有提交任何内容,修改 --title 后重试")}if(l){await Y(e,oe,l,"caption");await e.wait({time:0.5})}if(o){await ve(e,o);await e.wait({time:0.5})}if(m){process.stderr.write(`
505
+ `);await e.wait({time:3});await e.goto(I);await e.wait({time:5})}}await ge(e,r);await e.wait({time:2});await _e(e,C.basename(r),Math.min(180000,we(n,"视频上传/转码")));await e.wait({time:1});if(a){await K(e,ce,a,"title");await e.wait({time:0.5});const v=await M(e);if(v?.titleError)throw new c(`平台拒绝了短标题: ${v.titleError}`,"本次没有提交任何内容,修改 --title 后重试")}if(o){await K(e,de,o,"caption");await e.wait({time:0.5})}if(l){await ye(e,l);await e.wait({time:0.5})}if(m){process.stderr.write(`
417
506
  ℹ️ 手动模式:表单已填好,请在浏览器中检查并点击「发表」。
418
507
  `+` 若未加 --site-session persistent,此标签页约 30 秒后会被重置为空白页。
419
508
 
420
- `);return[{status:"⏸️ 已填写完毕,请在浏览器中手动点击发表",title:a||"",detail:[o?`定时: ${g(u)}(已回读表单确认)`:null].filter(Boolean).join(" · ")||"表单已就绪",id:"",manage_url:A}]}const h=await x(e),w=N(h,{targetSeconds:u,isDraft:s});if(w){await e.screenshot({path:"/tmp/wechat-channels_publish_submit_debug.png"});throw new c(`${w}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}await be(e,s);await e.wait({time:s?1:4});const y=s?["已保存","暂存成功","保存成功"]:["已发表","发布成功","发表成功","审核中"];let v="",k="",S=!1,C="",_=null;const K=h?.draftObjectId||"";for(let b=0;b<30;b++){_=await x(e).catch(()=>null);if(s&&!K&&_?.draftObjectId&&_.isCaching===!1){C=_.draftObjectId;S=!0;break}if(!s&&_?.originalIntercept){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});throw new c("发表被平台的原创声明确认框拦下,作品尚未发出","需要在浏览器里人工确认是否声明原创后再发表。截图: /tmp/wechat-channels_publish_result_debug.png")}v=await d(e,"() => location.href");k=await d(e,`
509
+ `);return[{status:"⏸️ 已填写完毕,请在浏览器中手动点击发表",title:a||"",detail:[l?`定时: ${_(h)}(已回读表单确认)`:null].filter(Boolean).join(" · ")||"表单已就绪",id:"",manage_url:T}]}const w=await M(e),k=q(w,{targetSeconds:h,isDraft:s});if(k){await e.screenshot({path:"/tmp/wechat-channels_publish_submit_debug.png"});throw new c(`${k}。本次没有提交任何内容`,"截图: /tmp/wechat-channels_publish_submit_debug.png")}await Se(e,s);await e.wait({time:s?1:4});const y=s?["已保存","暂存成功","保存成功"]:["已发表","发布成功","发表成功","审核中"];let N="",S="",x=!1,R="",b=null;const ee=w?.draftObjectId||"";let g=null;for(let v=0;v<30;v++){b=await M(e).catch(()=>null);if(s&&!ee&&b?.draftObjectId&&b.isCaching===!1){R=b.draftObjectId;x=!0;break}const E=g?b?.originalDialog:b?.originalIntercept||b?.originalDialog;if(!s&&E){if(g){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});throw new c(`已在原创确认框里选择「${g.label}」,但确认框再次出现,作品尚未发出`,`先到 ${T} 确认作品列表里没有这条,再加 --manual --site-session persistent 后在浏览器里手动处理。截图: /tmp/wechat-channels_publish_result_debug.png`)}g=await Te(e,u);await e.wait({time:1});continue}N=await d(e,"() => location.href");S=await d(e,`
421
510
  (function(markers) {
422
511
  ${p}
423
512
  var all = deepQueryAll('*');
@@ -432,4 +521,4 @@ import*as te from"node:fs";import*as D from"node:path";import{cli as re,Strategy
432
521
  }
433
522
  return '';
434
523
  })(${JSON.stringify(y)})
435
- `);S=U({isDraft:s,finalUrl:v,successMsg:k});if(S)break;await e.wait({time:0.5})}if(!S){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});throw new c(`已点击${s?"保存草稿":"发表"},但未能确认是否成功(结果未知)`,`不要直接重试,先到 ${A} 核对${s?"草稿箱":"作品列表"}里是否已有这条,避免重复发布。`+`截图: /tmp/wechat-channels_publish_result_debug.png;url=${v||""} message=${k||""}`)}const z=s?"草稿已保存":o?"定时发表已提交":"发布成功",X=[o?`定时: ${g(u)}(已回读表单确认)`:null,k||null,s?"草稿不公开,到管理页的草稿箱继续编辑":o?"定时稿到点前没有公开链接,到管理页核对计划时间":"平台提交后不返回作品链接,到管理页查看"].filter(Boolean),Z=[{status:`✅ ${z}`,title:a||"",detail:X.join(" · "),id:C,manage_url:A}];await e.goto("https://channels.weixin.qq.com/platform/post/list",{waitUntil:"none"}).catch(()=>{});return Z}});export const __test__={parseTimeoutSeconds:Q,parseScheduleDate:L,parseBooleanFlag:O,requireFilePath:P,submitSucceeded:U,validateShortTitle:R,submittedScheduleSeconds:H,preSubmitBlocker:N,uploadProgress:J,DEEP_QUERY_FN:p,FORM_STATE_FN:E,REALM_FILE_INPUT_JS:B,SCHEDULE_PICK_JS:G,SUBMIT_CLICK_JS:W};
524
+ `);x=J({isDraft:s,finalUrl:N,successMsg:S});if(x)break;await e.wait({time:0.5})}if(!x){await e.screenshot({path:"/tmp/wechat-channels_publish_result_debug.png"});throw new c(`已点击${s?"保存草稿":"发表"},但未能确认是否成功(结果未知)`,`不要直接重试,先到 ${T} 核对${s?"草稿箱":"作品列表"}里是否已有这条,避免重复发布。`+`截图: /tmp/wechat-channels_publish_result_debug.png;url=${N||""} message=${S||""}`)}const te=s?"草稿已保存":l?"定时发表已提交":"发布成功",ne=[l?`定时: ${_(h)}(已回读表单确认)`:null,g?`原创确认框: 已选「${g.label}」`:null,u&&!g?"平台未弹原创确认框,未声明原创(账号可能不在创作分成计划内)":null,S||null,s?"草稿不公开,到管理页的草稿箱继续编辑":l?"定时稿到点前没有公开链接,到管理页核对计划时间":"平台提交后不返回作品链接,到管理页查看"].filter(Boolean),re=[{status:`✅ ${te}`,title:a||"",detail:ne.join(" · "),id:R,manage_url:T}];await e.goto("https://channels.weixin.qq.com/platform/post/list",{waitUntil:"none"}).catch(()=>{});return re}});export const __test__={parseTimeoutSeconds:H,parseScheduleDate:U,parseBooleanFlag:O,requireFilePath:B,submitSucceeded:J,validateShortTitle:Q,submittedScheduleSeconds:G,preSubmitBlocker:q,uploadProgress:W,DEEP_QUERY_FN:p,FORM_STATE_FN:A,REALM_FILE_INPUT_JS:Y,SCHEDULE_PICK_JS:X,SUBMIT_CLICK_JS:z,ORIGINAL_DIALOG_FN:V,ORIGINAL_ANSWER_JS:Z};