@doubao-dev/cli 1.0.0-rc.1 → 1.0.0-rc.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/691.js +88 -0
- package/dist/categories.js +1 -1
- package/dist/command.js +9 -3
- package/dist/command~1.js +4 -4
- package/dist/command~2.js +1 -1
- package/dist/command~3.js +1 -1
- package/dist/command~4.js +1 -1
- package/dist/command~5.js +5 -5
- package/dist/dist.js +1 -1
- package/dist/draft.js +2 -2
- package/dist/index.d.ts +12 -3
- package/dist/index.js +1 -1
- package/dist/main.d.ts +12 -3
- package/dist/main.js +1 -1
- package/dist/mcp-apps-inspector.js +1 -0
- package/dist/multipart-parser.js +1 -1
- package/dist/open.js +2 -0
- package/dist/plugin.js +2 -2
- package/dist/preview.js +5 -5
- package/dist/progress.js +1 -1
- package/dist/ratatui-ui.js +1 -1
- package/dist/session.js +1 -1
- package/dist/skills/doubao-plugin-cli/SKILL.md +6 -4
- package/dist/skills/doubao-plugin-cli/references/development.md +4 -4
- package/dist/skills/doubao-plugin-cli/references/project-config.md +6 -3
- package/dist/skills/doubao-plugin-cli/references/upload.md +30 -1
- package/dist/uninstall.js +1 -1
- package/dist/versions~1.js +1 -1
- package/dist/web/index.html +1 -0
- package/dist/web/sandbox-proxy.html +101 -0
- package/dist/web/static/css/index.b3102f16b9.css +1 -0
- package/dist/web/static/js/155.747f5232dc.js +69 -0
- package/dist/web/static/js/async/970.86106314b5.js +1 -0
- package/dist/web/static/js/index.c1186260b9.js +4 -0
- package/dist/web/static/js/lib-react.00514652bf.js +2 -0
- package/dist/web/static/js/lib-react.00514652bf.js.LICENSE.txt +39 -0
- package/dist/xdg-open +1267 -0
- package/package.json +14 -15
- package/dist/21.js +0 -101
- package/dist/schema.js +0 -1
- /package/dist/{21.js.LICENSE.txt → 691.js.LICENSE.txt} +0 -0
package/dist/categories.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{listPluginCategories as
|
|
1
|
+
import{publicationTypeSchema as o,listPluginCategories as t}from"./691.js";import{ensureLogin as i}from"./command~1.js";async function _(r="public"){await i(!1);let a=o.parse(r.toUpperCase()),{items:e=[]}=await t({publication_type:a});console.log(JSON.stringify(e,null,2))}export{_ as runCategories};
|
package/dist/command.js
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
-
import{randomUUID as e}from"node:crypto";import{readFileSync as t}from"node:fs";import{resolve as r}from"node:path";import{
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import{randomUUID as e}from"node:crypto";import{z as i}from"zod";import{readFileSync as t}from"node:fs";import{resolve as r}from"node:path";import{versionSchema as a,VISIBILITY_TYPE_LABELS as o,upsertPluginDraft as l,getApproval as s,log as n,savePluginVersion as u,error_errorMessage as c,dist_he as p,dist_ve as d,dist_xe as m,jsonObjectSchema as _,submitApproval as f,pD as y,readProjectDraft as v,isInteractive as h,listPluginCategories as w}from"./691.js";import{listProjectVersionPages as P}from"./versions~1.js";import{withProgress as $}from"./progress.js";import{ensureLogin as g}from"./command~1.js";let b="请填写有效的 HTTPS 链接",E=i.string({error:({input:e})=>void 0===e?"公开上架提审必填":b}).trim().refine(e=>/^https:\/\/[^/\s]/i.test(e)&&!/[\\\s]/.test(e)&&URL.parse(e)?.protocol==="https:"&&Array.from(e).every(e=>e>=" "&&""!==e),b),C=i.enum(["true","false",""],{error:'只接受字符串 "true" 或 "false"'}).optional(),x=i.object({privacyPolicyUrl:E,isMinorIncluded:C,specialLicenseUrl:E.optional()}),M='plugin.json 的 extensions["com.doubao"]',I="请运行 dbx upload 重新上传,再运行 dbx audit。";async function S(e,i,t){let r=i.form?.compliance,a={privacyPolicyUrl:r?.privacy_url,isMinorIncluded:r?.is_minor_included,specialLicenseUrl:r?.special_license_url},o=L(a);if(0===o.length)return!0;let l=`当前草稿的合规声明缺失或有误:
|
|
2
|
+
${o.join("\n")}`,s=_.parse(e.plugin.extensions?.["com.doubao"]??{}),u=L(s);if(0===u.length)throw Error(`${l}
|
|
3
|
+
本地清单中的声明已填写。${I}`);let c=u.filter(e=>!o.includes(e)),d=c.length?`${l}
|
|
4
|
+
本地清单还需修正:
|
|
5
|
+
${c.join("\n")}`:l;if(!t)throw Error(`${d}
|
|
6
|
+
请修正 ${M}。${I}`);n.warn(`${d}
|
|
7
|
+
以下内容将保存到 ${M}。`);let{privacyPolicyUrl:m=a.privacyPolicyUrl,isMinorIncluded:f=a.isMinorIncluded,specialLicenseUrl:v=a.specialLicenseUrl}=s,h=void 0===m&&void 0===v&&(void 0===s.isMinorIncluded||""===s.isMinorIncluded)&&(void 0===f||""===f||"false"===f),w=E.safeParse(m),P=w.success?w.data:await p({message:"隐私政策链接(必填,HTTPS)",validate:e=>E.safeParse(e).success?void 0:b});if(y(P))return A();let $=C.safeParse(f),g=h||!$.success?await U(!$.success):$.data;if(y(g)||"cancel"===g)return A();let S=x.shape.specialLicenseUrl.safeParse(v),K=h||!S.success?await p({message:"特殊行业资质证明链接(选填,HTTPS)",placeholder:"不涉及特殊行业资质时可留空",validate:e=>!e.trim()||E.safeParse(e).success?void 0:b}):S.data;if(y(K))return A();throw await e.updateManifest(e=>({...e,extensions:{...e.extensions,"com.doubao":{..._.parse(e.extensions?.["com.doubao"]??{}),privacyPolicyUrl:P.trim(),isMinorIncluded:g,specialLicenseUrl:K?.trim()||void 0}}})),Error(`合规声明已保存到 ${M}。${I}`)}function L(e){return(x.safeParse(e).error?.issues??[]).map(({path:e,message:i})=>`- ${String(e[0])}:${i}`)}async function U(e){let i=await d({message:"插件服务的用户是否包含未成年人?",options:[{value:"false",label:e?"不包含":"不包含(默认)"},{value:"true",label:"包含"},...e?[{value:"cancel",label:"暂不选择,停止本次提审"}]:[]],initialValue:e?"cancel":"false"});return"true"===i&&n.info("请确保隐私政策说明未成年人个人信息处理规则。"),i}function A(){return m("已取消审核。"),process.exitCode=130,!1}let K=i.string().trim().min(1,"不能为空"),T=K.regex(/^https?:\/\//i,"请输入 HTTP 或 HTTPS 地址"),j=i.strictObject({evaluation_report_url:T,example_prompts:i.array(K.refine(e=>Buffer.from(e).toString()===e,"请输入合法 UTF-8")).min(5).max(10)}),N=i.strictObject({test_credential:K}),k=i.strictObject({instruction_document_url:T}),H=i.strictObject({type:i.union([i.literal(1),i.literal(2)])}),O=i.strictObject({category_id:K.optional(),visibility_config:H.optional(),modules:i.array(i.strictObject({module_id:K,mcp:N.optional(),mcp_app:i.strictObject({mcp:N}).optional(),skill:j.optional(),mini_app:j.optional(),cli:k.optional()})).default([])});function R(e){return e?.auth_type?.toLowerCase()==="oauth"&&!e.has_test_credential&&!e.masked_test_credential?.trim()}async function V(e){let i=e?.type,t=3===i,r=e=>i===e?"(当前范围)":"";return d({message:"请选择本次申请的可见范围",options:[...t?[{value:"current",label:`${o["3"]}(当前)`}]:[],{value:1,label:`${o["4"]}${r(4)}`},{value:2,label:`${o["2"]}${r(2)}`}],initialValue:t?"current":2===i?2:1})}async function D(e){let i="MCP_APP"===e.type?e.mcp_app?.mcp:e.mcp,t=R(i),r=await p({message:`连接器 ${e.name||e.module_id||"MCP"} 的测试账号或 Key${t?"":"(可留空)"}`,initialValue:i?.masked_test_credential,validate:e=>t?K.safeParse(e).error?.issues[0]?.message:void 0});if(y(r))return r;if(!r.trim()||r.trim()===i?.masked_test_credential?.trim())return;let a={test_credential:r.trim()};return"MCP_APP"===e.type?{module_id:e.module_id,mcp_app:{mcp:a}}:{module_id:e.module_id,mcp:a}}async function z(e){let i="MINI_APP"===e.type?"mini_app":"skill",t=e.name||e.module_id||e.type,r=await p({message:`${t} 的评测报告地址`,initialValue:e[i]?.evaluation_report_url,validate:e=>T.safeParse(e).error?.issues[0]?.message});if(y(r))return r;n.info("请逐条填写 5–10 条覆盖核心场景的示例提示词,仅用于平台审核测试,不会向用户展示。");let a=[];for(let r=0;r<10;r++){let o=await p({message:`${t} 的第 ${r+1} 条示例提示词`,placeholder:r>=5?"留空结束":void 0,initialValue:e[i]?.example_prompts?.[r],validate:e=>{if(!(r>=5)||e.trim())return j.shape.example_prompts.element.safeParse(e).error?.issues[0]?.message}});if(y(o))return o;if(!o?.trim())break;a.push(o.trim())}return{module_id:e.module_id,[i]:{evaluation_report_url:r.trim(),example_prompts:a}}}async function J(e){let i=await p({message:`CLI ${e.name||e.module_id} 的使用说明文档地址`,initialValue:e.cli?.instruction_document_url,validate:e=>T.safeParse(e).error?.issues[0]?.message});return y(i)?i:{module_id:e.module_id,cli:{instruction_document_url:i.trim()}}}async function q(e){switch(e.type){case"MCP":case"MCP_APP":return D(e);case"SKILL":case"MINI_APP":return z(e);case"CLI":return J(e);default:return}}async function B(i,o={}){let s=h()&&void 0===o.input,p=void 0!==o.input?function(e,i){let a=r(e,i);try{return O.parse(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t(a))))}catch(i){let e=i instanceof SyntaxError?"文件不是有效的 JSON":i instanceof Error?i.message:String(i);throw Error(`无法读取审核材料 ${a}:${e}`,{cause:i})}}(i.root,o.input):void 0;await g(!1);let{name:_}=i.plugin;if(void 0!==o.visibility&&p?.visibility_config!==void 0)throw Error("请只通过 --visibility 或 --input 中的 visibility_config 其中一种方式指定范围");let P=void 0!==o.visibility?H.parse({type:"self"===o.visibility?1:"tenant"===o.visibility?2:void 0}):p?.visibility_config,b=await $("查询草稿",()=>v(i)),E={ability_id:b.ability_id,publication_type:b.publication_type},C="ENTERPRISE"===b.publication_type;if(!C&&P)throw Error("可见范围仅适用于企业专属插件");let x=await $("查询审核记录",()=>F(i));if(x){n.info(`应用插件 ${_} 已提交审核,审核 ID:${x}`),P&&n.warn("已有待处理的审核,本次指定的可见范围未生效;如需修改,请先运行 dbx cancel-audit 再重新提交");return}if(s&&C&&!P){let e=await V(b.visibility_config);if(y(e)){m("已取消审核。"),process.exitCode=130;return}P="current"===e?void 0:{type:e}}let{version:M}=b;if(!M)throw Error("服务端未返回当前草稿版本号,无法确认提审目标");if(!a.safeParse(M).success)throw Error(`当前草稿版本号 ${M} 不是 x.y.z 格式,无法确认提审目标`);if(G(b,i.plugin.id,M),n.info(`本次提审版本:${M}(当前草稿)`),!C&&!await S(i,b,s))return;let{items:I=[]}=await $("查询意向分类",()=>w({publication_type:b.publication_type})),L=I.flatMap(({category_id:e,name:i})=>e?[{value:e,label:i||e}]:[]);if(0===L.length)throw Error("服务端未返回可选分类,暂时无法提交审核");let U=p?.category_id?[p.category_id]:(b.form?.categories??[]).flatMap(({category_id:e})=>e?[e]:[]),A=[];if(s){let e=await d({message:"请选择意向分类",options:L,initialValue:L.find(({value:e})=>U.includes(e))?.value});if(y(e)){m("已取消审核。"),process.exitCode=130;return}for(let i of(U=[e],b.modules??[])){let e=await q(i);if(y(e)){m("已取消审核。"),process.exitCode=130;return}e&&A.push(e)}}else{if(!U.length||U.some(e=>!L.some(({value:i})=>i===e)))throw Error(`请先运行 dbx categories${C?" --type enterprise":""} 查询审核类目,再通过 --input <path> 的 category_id 指定有效类目。`);A=function(e,i=[]){let t=new Map;for(let r of i){if(t.has(r.module_id))throw Error(`审核材料中 module_id 重复:${r.module_id}`);let i=e.find(e=>e.module_id===r.module_id);if(!i)throw Error(`草稿中不存在审核材料指定的模块:${r.module_id}`);let a=["mcp","mcp_app","skill","mini_app","cli"].filter(e=>void 0!==r[e]),o="MCP"===i.type||"MCP_APP"===i.type?["mcp","mcp_app"]:[i.type?.toLowerCase()];if(1!==a.length||!o.includes(a[0]))throw Error(`模块 ${r.module_id} 的审核材料须与草稿类型 ${i.type} 一致`);t.set(r.module_id,r)}let r=[];for(let i of e){let e=i.module_id?t.get(i.module_id):void 0,a=i.name||i.module_id;if("MCP"===i.type||"MCP_APP"===i.type){let t="MCP"===i.type?i.mcp:i.mcp_app?.mcp,o=e?.mcp??e?.mcp_app?.mcp;if(!o&&R(t))throw Error(`连接器 ${a} 缺少测试账号或 Key,请通过 --input <path> 提供模块 ${i.module_id} 的测试凭据`);o&&o.test_credential!==t?.masked_test_credential?.trim()&&r.push("MCP"===i.type?{module_id:i.module_id,mcp:o}:{module_id:i.module_id,mcp_app:{mcp:o}})}else if("SKILL"===i.type||"MINI_APP"===i.type){let t="SKILL"===i.type?"skill":"mini_app",o=e?.[t],l=i[t];if(!j.safeParse(o??{evaluation_report_url:l?.evaluation_report_url,example_prompts:l?.example_prompts}).success)throw Error(`模块 ${a} 缺少有效报告地址或 5–10 条示例提示词,请通过 --input <path> 提供模块 ${i.module_id} 的 ${t} 审核材料`);o&&r.push({module_id:i.module_id,[t]:o})}else if("CLI"===i.type){let t=e?.cli;if(!k.safeParse(t??i.cli).success)throw Error(`CLI ${a} 缺少有效使用说明文档地址,请通过 --input <path> 提供模块 ${i.module_id} 的 cli 审核材料`);t&&r.push({module_id:i.module_id,cli:t})}}return r}(b.modules??[],p?.modules)}let K=await $("核对提审版本",()=>v(i));G(K,i.plugin.id,M),C||await S(i,K,!1);let{draft:T}=await $("保存草稿审核材料",()=>l({...E,category_ids:U,modules:A.length>0?A:void 0,...P?{visibility_config:P}:{}}));if(!T)throw Error("审核信息保存失败:服务端未返回草稿");G(T,i.plugin.id,M),C||await S(i,T,!1);let N=await $("保存版本并同步审核材料",()=>u({...E,request_id:e()}));if(N.version!==M)throw Error(`审核材料已保存到当前草稿,但平台保存的版本 ${N.version||"未知"} 与本次提审版本 ${M} 不一致,已停止提审。
|
|
8
|
+
请运行 dbx versions 确认版本状态,确认没有并行上传后重新运行 dbx audit。`);try{let{approval_id:e}=await $("提交审核",()=>f({...E,version:M}));if(!e)throw Error("服务端未返回 approval_id");n.success(`版本 ${M} 提交审核成功,审核 ID:${e}`)}catch(e){throw Error(`提交审核失败:${c(e)}
|
|
9
|
+
应用插件:${_}@${M}`,{cause:e})}}async function F(e){let i=new Set;for await(let{items:t}of P(e))for(let e of t){let t=e.current_approval?.approval_id;if(!t||i.has(t))continue;i.add(t);let{approval:r}=await s(t);if(!r)throw Error(`服务端未返回审核记录:${t}`);if(null==r.handled_at_ms)return t}}function G(e,i,t){if(i&&e?.ability_id!==i)throw Error("当前草稿的应用插件 ID 与项目不一致,请检查 plugin.json 的 id 和 name,已停止提审");let r=e?.version;if(r!==t)throw Error(`当前草稿版本 ${r||"未知"} 与本次提审版本 ${t} 不一致,已停止提审;请确认没有并行上传后重新运行 dbx audit`)}export{B as runAudit};
|
package/dist/command~1.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e
|
|
2
|
-
dbx auth login --complete ${e.deviceCode}`);return}
|
|
3
|
-
授权地址:${
|
|
4
|
-
用户验证码:${
|
|
1
|
+
import{completeLogin as e,runtime as t,login as o,withRequestLog as r,startLogin as i,log as n,whoami as a,logout as c,NotLoggedInError as l,isInteractive as u,getCurrentUser as s,error_errorMessage as f}from"./691.js";import{node_modules_open as g}from"./open.js";function d(){let e=t.auth.fetch??fetch,o=r(e);return o===e?t.auth:{...t.auth,fetch:o}}async function h(){await c(t.auth),n.success("已退出登录")}async function m(){let e,t=await a(d());if(console.log(t.credentialError?.message??(t.loggedIn?"已登录":"尚未登录,请运行 dbx auth login")),t.uid&&console.log(`用户 ID:${t.uid}`),!t.loggedIn)return;try{({is_enterprise:e}=await s())}catch(e){n.warn(`查询账号类型失败:${f(e)}`)}let o=void 0===e?"未知":e?"企业账号":"个人账号";console.log(`账号类型:${o}`)}async function p(e=u()){let t=await a(d());if(t.credentialError)throw Error(t.credentialError.message);if(!t.loggedIn){if(!e)throw new l;await w({})}}async function w(t){if(!u()&&!t.begin&&void 0===t.complete)throw Error("请使用 auth login --begin 发起授权,再使用 --complete <device-code> 完成授权");if(void 0!==t.complete&&!t.complete.trim())throw Error("设备码不能为空");let r=d();if(t.begin){let e=await i(r);_(e),n.step(`完成授权后运行:
|
|
2
|
+
dbx auth login --complete ${e.deviceCode}`);return}n.step(t.complete?"正在等待授权确认…":"正在发起登录…");let{expiresAt:a}=t.complete?await e(t.complete.trim(),r):await o({...r,onVerification(e){_(e),n.step("正在等待浏览器授权…")}});n.success("登录成功"),n.info(`凭证到期时间(本地):${new Date(1e3*a).toLocaleString("zh-CN",{hour12:!1})}`)}function _(e){n.info(`请在浏览器中完成授权(${e.expiresIn} 秒内)
|
|
3
|
+
授权地址:${e.verificationUrl}
|
|
4
|
+
用户验证码:${e.userCode}`),u()&&g(e.verificationUrl).catch(()=>{n.warn("无法自动打开浏览器,请复制上方的授权地址完成授权。")})}export{p as ensureLogin,w as runLogin,h as runLogout,m as runStatus};
|
package/dist/command~2.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{listPluginVersions as r,pluginIdentity as a,withdrawApproval as _,log as i}from"./691.js";import{withProgress as o}from"./progress.js";import{ensureLogin as n}from"./command~1.js";async function t(t){await n(!1);let{name:p}=t.plugin,e=await o("查询审核记录",async()=>{let{items:_=[]}=await r(a(t.plugin));return _.sort((r,a)=>(a.version??"").localeCompare(r.version??"","en",{numeric:!0})).find(r=>r.current_approval?.approval_id)?.current_approval?.approval_id});e?(await o("取消提审",()=>_(e)),i.success(`已取消提审,审核 ID:${e}`)):i.info(`应用插件 ${p} 暂无审核记录`)}export{t as runCancelAudit};
|
package/dist/command~3.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as e,resolve as
|
|
1
|
+
import{join as e,resolve as t}from"node:path";import{Option as i}from"commander";import{STANDARD_TEMPLATE_DIRECTORY as r,publicationTypeSchema as a,TEMPLATES_DIRECTORY as o,log as n,PUBLICATION_TYPE_LABELS as l,error_errorMessage as p,syncProjectSkill as s,TEMPLATE_SUFFIX as c,dist_he as f,dist_xe as u,projectNameSchema as y,collectHooks as m,dist_ve as d,dist_ye as w,PLUGIN_NAME_PLACEHOLDER as _,pD as S,isInteractive as b,getCurrentUser as C}from"./691.js";import{PluginProject as E,copySync as h}from"./plugin.js";import{ensureLogin as g}from"./command~1.js";import*as v from"node:fs";async function P(t,i){let{name:n,directory:l}=t;y.parse(n);let p=a.parse(String(t.options.type??"public").toUpperCase()),f=v.lstatSync(l,{throwIfNoEntry:!1});if(f&&(!f.isDirectory()||v.readdirSync(l).length>0))throw Error(`目标路径已存在且不是空目录:${l}`);let u=[e(import.meta.dirname,o,r)];for(let e of(u.push(...await m(i.prepareTemplates,t)),u))h(e,l);(function t(i,r){for(let a of v.readdirSync(i,{withFileTypes:!0})){let o=e(i,a.name),n=e(i,a.name.replaceAll(_,r));if(a.isDirectory())t(o,r);else if(a.isFile()&&a.name.endsWith(c)){n=n.slice(0,-c.length),v.writeFileSync(n,v.readFileSync(o,"utf8").replaceAll(_,r)),v.unlinkSync(o);continue}n!==o&&v.renameSync(o,n)}})(l,n),v.mkdirSync(e(l,"skills"),{recursive:!0});let d=new E(l);await d.updatePublicationType(p),await s(d,i)}async function N(e,r,a){let o={...r},s=b(),c=!e;if(!e){if(!s)throw Error("请指定项目名称,例如 dbx init my-plugin");let t=await f({message:"项目名称",placeholder:"my-plugin",defaultValue:"my-plugin",validate:e=>y.safeParse(e||"my-plugin").error?.issues[0]?.message});if(S(t)){u("已取消创建。"),process.exitCode=130;return}e=t}void 0===o.type&&!0===o.app&&(o={...o,type:"public"});let m=!0!==o.app&&("enterprise"===o.type||void 0===o.type&&s),_=!1;if(m&&(await g(s),_=(await C()).is_enterprise_publication_access),"enterprise"===o.type&&!0!==o.app&&!_)throw Error("当前账号没有企业插件发布权限,无法创建企业专属插件");if(void 0===o.type&&s&&!_&&(n.info("当前账号没有企业插件发布权限,将创建公开插件"),o={...o,type:"public"}),void 0===o.type&&s){let e=await d({message:"请选择应用插件发布类型,首次创建平台草稿后不可切换",options:[{value:"public",label:l.PUBLIC},{value:"enterprise",label:l.ENTERPRISE}],initialValue:"public"});if(S(e)){u("已取消创建。"),process.exitCode=130;return}o={...o,type:e}}o={...o,type:o.type??"public"};let E=t(e);if(c)for(let{flags:t,prompt:r}of a.initOptions){let a=new i(t).attributeName();if(!r||void 0!==o[a])continue;let n="function"==typeof r?r({name:e,directory:E,options:o}):r;if(!n)continue;let l=await w({message:n,initialValue:!1});if(S(l)){u("已取消创建。"),process.exitCode=130;return}o={...o,[a]:l}}let h={name:e,directory:E,options:o};for(let t of(await P(h,a),n.success(`已创建 ${e}`),n.info(`发布类型:${"enterprise"===o.type?l.ENTERPRISE:l.PUBLIC}`),a.afterCreate))try{await t.callback(h)}catch(e){n.warn(`[${t.pluginName}] 项目已创建,后续处理失败:${p(e)}`)}}export{N as runInit};
|
package/dist/command~4.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log as r}from"./
|
|
1
|
+
import{log as r}from"./691.js";async function t(t){if(void 0===t.mcpServer)throw Error("请指定调试对象,例如 dbx inspect --mcp-server <endpoint>");let e="string"==typeof t.mcpServer?function(r){let t;try{t=new URL(r)}catch{throw Error(`MCP Server 地址无效:${r},仅支持 http:// 或 https://`)}if("http:"!==t.protocol&&"https:"!==t.protocol)throw Error(`MCP Server 地址无效:${r},仅支持 http:// 或 https://`);return r}(t.mcpServer):void 0,o=function(r){let t={};for(let e of r){let r=e.indexOf(":"),o=r>0?e.slice(0,r).trim():"";if(!o)throw Error(`请求头格式应为 "Key: Value":${e}`);t[o]=e.slice(r+1).trim()}return t}(t.header??[]),i=function(r){if(void 0===r)return;let t=Number(r);if(!Number.isInteger(t)||t<1||t>65535)throw Error(`端口无效:${r},应为 1-65535 的整数`);return t}(t.port),n=new AbortController,s=Promise.withResolvers(),p=r=>{process.exitCode=r,n.abort(),s.resolve()},c=()=>p(130),l=()=>p(143);process.on("SIGINT",c),process.on("SIGTERM",l);try{let{startInspector:p}=await import("./mcp-apps-inspector.js"),c=await p({endpoint:e,headers:o,port:i,open:t.open,signal:n.signal,log:r});try{r.success(`MCP 调试界面已启动:${c.url}`),e&&r.info(`正在连接 ${e}`),r.info("按 Ctrl+C 退出"),await s.promise}finally{await c.close()}}catch(r){if(!n.signal.aborted)throw r}finally{process.off("SIGINT",c),process.off("SIGTERM",l)}}export{t as runInspect};
|
package/dist/command~5.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{randomUUID as r}from"node:crypto";import{
|
|
2
|
-
${
|
|
3
|
-
${
|
|
4
|
-
${
|
|
5
|
-
可从上方应用插件版本链接继续处理。`)}}async function m(r,o,e){try{let
|
|
1
|
+
import{randomUUID as r}from"node:crypto";import{versionSchema as o,runtime as e,collectHooks as t,log as i,pluginIdentity as a,savePluginVersion as n,error_errorMessage as s,chalk_source as _}from"./691.js";import{listProjectVersionPages as c}from"./versions~1.js";import{withProgress as f}from"./progress.js";import{ensureLogin as l}from"./command~1.js";import{uploadDraft as p}from"./draft.js";async function d(c,d,u){let w;await l(!1);let $=o.optional().parse(d.version),h={project:c,options:{...d,version:$}},C=await p(h,await t(u.exclude,{project:c},"draft")),{draft:S}=C,U=c.plugin.id?new URL(encodeURIComponent(c.plugin.id),e.consoleUrl):void 0;U?.searchParams.set("tab","versions");let v=U?`应用插件版本列表:${U.href}`:"可从平台版本页继续处理。";try{w=(await f("保存版本",()=>n({...a(c.plugin),request_id:r()}))).version}catch(r){throw Error(`草稿已保存,但版本保存失败:${s(r)}
|
|
2
|
+
${v}`,{cause:r})}if(!w)throw Error(`草稿已保存,但服务端未返回保存的版本号
|
|
3
|
+
${v}`);if(!o.safeParse(w).success)throw Error(`版本已保存,但服务端返回的版本号 ${w} 不是 x.y.z 格式
|
|
4
|
+
${v}`);let K=w,y={...C,version:K};for(let r of(i.success(`应用插件 ${_.cyan.bold(S.name)} 上传成功,版本:${K}`),U&&await m(c,K,U),i.step("提交当前草稿审核:dbx audit"),u.uploadSuccess))try{await r.callback(h,y)}catch(o){i.warn(`[${r.pluginName}] 上传和版本保存已完成,后续处理失败:${s(o)}
|
|
5
|
+
可从上方应用插件版本链接继续处理。`)}}async function m(r,o,e){try{let t=await f("查询版本详情",async()=>{for await(let{items:e}of c(r)){let r=e.find(r=>r.version===o&&r.version_id);if(r?.version_id)return r.version_id}throw Error(`未找到版本 ${o} 对应的版本 ID`)}),a=new URL(`${e.pathname}/versions/${encodeURIComponent(t)}`,e);i.info(`应用插件版本详情(查看版本信息与提审):${a.href}`)}catch(r){i.warn(`版本已保存,但查询版本详情链接失败:${s(r)}`),i.info(`应用插件版本列表(查看版本信息与提审):${e.href}`)}}export{d as runUpload};
|
package/dist/dist.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage as t}from"node:async_hooks";import{randomUUID as e}from"node:crypto";import{performance as s}from"node:perf_hooks";import{createRequire as i}from"node:module";import{existsSync as r}from"node:fs";import{dirname as o,join as n,resolve as a}from"node:path";import{fileURLToPath as l}from"node:url";import"node:os";import{StringDecoder as c}from"node:string_decoder";import{stripVTControlCharacters as d}from"node:util";class h{componentId="markdown-card";states={};props;constructor(t){this.props={text:t}}}class u extends h{componentId="hint"}function p(t){let e=new Set;if(!t||Array.isArray(t)||"object"!=typeof t)throw TypeError("state 必须是 JSON 对象");return!function t(s){if(null!==s&&"string"!=typeof s&&"boolean"!=typeof s&&!("number"==typeof s&&Number.isFinite(s))){if("object"!=typeof s||null===s)throw TypeError("state 只允许 JSON 值");if(e.has(s))throw TypeError("state 不能包含循环引用");if(!Array.isArray(s)&&Object.getPrototypeOf(s)!==Object.prototype&&null!==Object.getPrototypeOf(s))throw TypeError("state 只允许普通 JSON 对象");if(e.add(s),Array.isArray(s))for(let e=0;e<s.length;e+=1)t(s[e]);else{if(Object.getOwnPropertySymbols(s).length)throw TypeError("state 不能包含 Symbol 字段");for(let e of Object.values(s))t(e)}e.delete(s)}}(t),JSON.parse(JSON.stringify(t))}class m{native;constructor(t){this.native=t}createState(t,e){this.native.createState(t,p(e))}setState(t,e){this.native.setState(t,p(e))}disposeState(t){this.native.disposeState(t)}}function f(t){if(!t.trim())return[];if(t.trimStart().startsWith("[")){let e=JSON.parse(t);if(!Array.isArray(e))throw TypeError("命令参数必须是 JSON 数组");return p({args:e}).args}let e=[],s="",i="",r=!1,o=!1;for(let n of t)r?(s+=n,r=!1,o=!0):"\\"===n?(r=!0,o=!0):i?n===i?i="":s+=n:'"'===n||"'"===n?(i=n,o=!0):/\s/.test(n)?o&&(e.push(s),s="",o=!1):(s+=n,o=!0);if(i||r)throw TypeError("命令参数存在未闭合的引号或转义");return o&&e.push(s),e}class g{_groups=new Map;bind(t,s){let i=e(),r=this._groups.get(t)??new Map;return r.set(i,s),this._groups.set(t,r),i}take(t,e){let s=null===e?void 0:this._groups.get(t)?.get(e);return this.release(t),s}release(t){this._groups.delete(t)}clear(){this._groups.clear()}}class w{now;arrivals=[];lastArrival=-1/0;flooding=!1;constructor(t=()=>s.now()){this.now=t}admit(){let t=this.now();return(this.flooding&&t-this.lastArrival>=500&&(this.flooding=!1,this.arrivals=[]),this.lastArrival=t,this.flooding)?"drop":(this.arrivals=this.arrivals.filter(e=>t-e<5e3),this.arrivals.push(t),this.arrivals.length>=500)?(this.flooding=!0,this.arrivals=[],"flood-started"):"accept"}}var v,y,b=JSON.parse('{"macos-arm64":{"target":"aarch64-apple-darwin","library":"libratatui_renderer.dylib","enabled":true},"macos-x64":{"target":"x86_64-apple-darwin","library":"libratatui_renderer.dylib","enabled":true},"windows-x64":{"target":"x86_64-pc-windows-msvc","library":"ratatui_renderer.dll","enabled":true},"linux-alpine":{"target":"x86_64-unknown-linux-musl","library":"libratatui_renderer.so","enabled":false},"linux-x64":{"target":"x86_64-unknown-linux-gnu","library":"libratatui_renderer.so","enabled":false}}');let S=i(import.meta.url),B=new WeakMap,_=new WeakMap;function I(t){let e=B.get(t);if(!e)throw TypeError("只能传递由 RSStateStore 创建的 RSState 对象");if(!e.owner.alive)throw Error("RSState 所属 TUI 已关闭");if(e.disposed)throw Error("RSState 已释放");return e}function E(t){let e=_.get(t);if(!e)throw TypeError("RSStateStore 必须由 TUIManager 创建");if(!e.alive)throw Error("TUI 已关闭");return e}function k(t,e){let s=I(e);if(s.owner!==t)throw TypeError("状态不存在");return s}class T{get(){return p(I(this).value)}set(t){let e=I(this),s=p(t);e.owner.native.setState(e.id,s),e.value=s}dispose(){let t=I(this);t.owner.native.disposeState(t.id),t.disposed=!0,t.value={},t.owner.byId.delete(t.id),t.owner.onDispose(this)}get disposed(){let t=B.get(this);return!t||t.disposed||!t.owner.alive}toJSON(){throw TypeError("RSState 不能序列化;请把 RSState 对象传给 TUIManager")}}class A{createState(t){let s=E(this),i=p(t),r=`rs:${e()}`;s.native.createState(r,i);let o=Object.create(T.prototype);return B.set(o,{id:r,owner:s,value:i,disposed:!1}),s.byId.set(r,o),Object.freeze(o),o}setState(t,e){k(E(this),t),t.set(e)}disposeState(t){k(E(this),t),t.dispose()}}class x{states;done;native;bridge;listeners=new Set;commands=new t;functions=new g;selection;quickActionsBinding;closed=!1;messageThrottler=new w;bottomBarBinding;bottomBarItems=new Map;sceneQueue=Promise.resolve();constructor(t={}){var e,s;let c,d;t.onEvent&&this.listeners.add(t.onEvent),this.native=function(t={}){let e,s,c,{Renderer:d}=S(function(t){let e,s=(e=!1,"linux"===process.platform&&"x64"===process.arch&&(e=!process.report.getReport().header.glibcVersionRuntime),function(t,e,s=!1){let i;if("darwin"===t&&"arm64"===e&&(i="macos-arm64"),"darwin"===t&&"x64"===e&&(i="macos-x64"),"win32"===t&&"x64"===e&&(i="windows-x64"),"linux"===t&&"x64"===e&&(i=s?"linux-alpine":"linux-x64"),i&&b[i].enabled)return i;let r=Object.keys(b).filter(t=>b[t].enabled);throw Error(`当前平台 ${t}-${e} 不支持 DBX TUI。当前支持:${r.join("、")};Linux 暂未启用。可使用 --agent 模式。`)}(process.platform,process.arch,e)),c=`renderer-${s}.node`;if(!t){let t=s.replace("macos-","darwin-").replace("windows-","win32-"),e=`@doubao-dev/cli-tui-${t}`;try{return i(import.meta.url).resolve(e)}catch(t){if("MODULE_NOT_FOUND"!==t.code)throw t}}let d=n(t??a(o(l(import.meta.url)),"../../native"),c);if(!r(d))throw Error(`DBX TUI 原生模块缺失:${d}。请重新构建或安装包含 ${s} 产物的 CLI;安装时请保留 optionalDependencies。也可使用 --agent 模式。`);return d}(t.nativeDirectory));if(!t.headless&&(!process.stdin.isTTY||!process.stdout.isTTY))throw Error("交互模式需要真实终端;无终端验证请使用 npm test。");let h=!1,u=new Set;t.onEvent&&u.add(t.onEvent);let p=new Map,f=()=>{for(let t of p.values())t.abort();p.clear()},g=()=>{if(h)throw Error("renderer 已关闭")},w=new Promise((t,i)=>{e=t,s=i}),v=()=>(h=!0,f(),B.close()),y=()=>{v().catch(s)},B=new d((t,i)=>{if(t){c=t,v().catch(s);return}if("closed"===i.type){h=!0,f(),u.clear(),process.removeListener("SIGINT",y),process.removeListener("SIGTERM",y);let t=c??(i.error?Error(i.error):void 0);t?s(t):e();return}try{for(let t of u)t(i)}catch(t){c=t instanceof Error?t:Error(String(t)),v().catch(s)}},t.headless??!1);process.on("SIGINT",y),process.on("SIGTERM",y);let _=new m({createState(t,e){g(),B.createState(t,e)},setState(t,e){g(),B.setState(t,e)},disposeState(t){g(),B.disposeState(t)}}),I=t=>(e,s)=>{if(h)return;let i=new AbortController;p.set(s.requestId,i),Promise.resolve().then(()=>{if(e)throw e;return t({...s,signal:i.signal})}).catch(t=>{if(!i.signal.aborted&&!h)try{B.commandFailed(s.requestId,t instanceof Error?t.message:String(t))}catch{}}).finally(()=>{p.delete(s.requestId)})};return{stateStore:_,showSelection:(t,e,s)=>(g(),B.showSelection(t,e,s)),cancelSelection:t=>(g(),B.cancelSelection(t)),clearHistory:()=>(g(),B.clearHistory()),clearCommands:()=>(g(),B.clearCommands()),addMessage:t=>(g(),B.addMessage(t)),registerCommand:(t,e,s)=>(g(),B.registerCommand(t,e,I(s))),switchScene:(t,e)=>(g(),B.switchScene(t,I(e))),setBottomBarItems:t=>(g(),B.setBottomBarItems(t)),showQuickActions:t=>(g(),B.showQuickActions(t)),onEvent:t=>(g(),u.add(t),()=>{u.delete(t)}),testInput(t){g(),B.testInput(t)},close:v,done:w}}({headless:t.headless,nativeDirectory:t.nativeDirectory,onEvent:t=>this.event(t)}),this.bridge=(e=this.native.stateStore,s=t=>this.publish({type:"state-disposed",state:t}),c={alive:!0,native:e,byId:new Map,onDispose:s},d=Object.create(A.prototype),_.set(d,c),Object.freeze(d),{store:d,resolve:t=>k(c,t).id,find:t=>c.byId.get(t),invalidate(){for(let t of(c.alive=!1,c.native=void 0,c.byId.values()))B.get(t).value={};c.byId.clear()}}),this.states=this.bridge.store,this.done=this.native.done,this.done.then(()=>this.cleanup(),()=>this.cleanup())}clearHistory(){return this.selection?.settle(null),this.native.clearHistory()}clearCommands(){let t=this.sceneQueue.then(async()=>{await this.native.clearCommands(),this.quickActionsBinding?.dispose(),this.quickActionsBinding=void 0});return this.sceneQueue=t.catch(()=>{}),t}registerCommand(t){let e=t.callback;if("function"!=typeof e)throw TypeError("command.callback 必须是函数");return this.native.registerCommand(t.name,t.description,t=>this.commands.run(t,async()=>{await e(this,t.signal,...t.parameters??f(t.args))}))}component(t){let e=Object.fromEntries(Object.entries(t.states).map(([t,e])=>[t,this.bridge.resolve(e)]));return{type:"component",componentId:t.componentId,states:e,props:p(t.props??{})}}async addMessage(t){this.commands.getStore()?.signal.throwIfAborted();let e=this.messageThrottler.admit();if("accept"!==e){"flood-started"===e&&await this.native.addMessage({type:"log",level:"info",text:"警告:日志过多,5 秒内收到 500 条日志,已暂停展示后续日志;日志静默 500ms 后恢复。"});return}if("markdown"===t.type||"hint"===t.type){let e="hint"===t.type?new u(t.text):new h(t.text);await this.native.addMessage(this.component(e));return}await this.native.addMessage("log"===t.type?{...t,level:t.level??"info"}:this.component(t))}switchScene(t){let e=new Map(t.commands.map(t=>[t.name,{...t}])),s=()=>{let e=t.bottomBarItems;return e&&"get"in e?e.get():e??[]},i={bottomBarItems:this.bottomBarSnapshot(s()),id:t.id,compact:t.compact??!1,commands:[...e.values()].map(({name:t,description:e})=>({name:t,description:e})),headerComponent:t.headerComponent?this.component(t.headerComponent):null,quickActions:structuredClone(t.quickActions.get())},r=this.sceneQueue.then(async()=>{if(i.bottomBarItems=this.bottomBarSnapshot(s()),i.quickActions=structuredClone(t.quickActions.get()),await this.native.switchScene(i,t=>{let s=e.get(t.name);if(!s)throw Error(`未知指令:${t.name}`);return this.commands.run(t,async()=>{await s.callback(this,t.signal,...t.parameters??f(t.args))})}),this.closed)return;this.bottomBarBinding?.dispose(),this.bottomBarBinding=void 0,this.bottomBarItems=new Map(s().map(t=>[t.id,{...t}]));let r=t.bottomBarItems;if(r&&"onStateChange"in r){let t=r.onStateChange(({to:e})=>{let s=e.map(t=>({...t})),i=this.sceneQueue.then(async()=>{this.bottomBarBinding!==t||this.closed||(await this.native.setBottomBarItems(this.bottomBarSnapshot(s)),this.bottomBarItems=new Map(s.map(t=>[t.id,t])))});this.sceneQueue=i.catch(()=>{})});this.bottomBarBinding=t}await this.native.setBottomBarItems(this.bottomBarSnapshot(s())),this.quickActionsBinding?.dispose();let o=t.quickActions.onStateChange(({to:t})=>{let e=structuredClone(t),s=this.sceneQueue.then(async()=>{this.quickActionsBinding!==o||this.closed||await this.native.showQuickActions(e)});this.sceneQueue=s.catch(async t=>{this.closed||await this.native.addMessage({type:"log",level:"error",text:String(t)}).catch(()=>{})})});this.quickActionsBinding=o,JSON.stringify(t.quickActions.get())!==JSON.stringify(i.quickActions)&&await this.native.showQuickActions(structuredClone(t.quickActions.get()))});return this.sceneQueue=r.catch(()=>{}),r}bottomBarSnapshot(t){let e=new Set;return t.map(t=>{if(!t.id.trim()||t.id.startsWith("__rust.")||e.has(t.id)||"string"!=typeof t.text||/[\r\n]/.test(t.text)||void 0!==t.side&&"left"!==t.side&&"right"!==t.side||void 0!==t.color&&!["yellow","green","red","blue","cyan","magenta","white","gray"].includes(t.color)||void 0!==t.click&&"function"!=typeof t.click)throw TypeError("底部栏条目需要唯一 id、text 和可选 click 回调");return e.add(t.id),{id:t.id,text:t.text,side:t.side??"left",color:t.color??null,clickable:!!t.click}})}setBottomBarItems(t){let e=t.map(t=>({...t})),s=this.bottomBarSnapshot(e),i=this.sceneQueue.then(async()=>{await this.native.setBottomBarItems(s),this.bottomBarItems=new Map(e.map(t=>[t.id,t]))});return this.sceneQueue=i.catch(()=>{}),i}upsertBottomBarItem(t){return this.mutateBottomBar(t.id,t)}removeBottomBarItem(t){return this.mutateBottomBar(t)}mutateBottomBar(t,e){let s=e?{...e}:void 0,i=this.sceneQueue.then(async()=>{let e=new Map(this.bottomBarItems);s?e.set(t,s):e.delete(t),await this.native.setBottomBarItems(this.bottomBarSnapshot([...e.values()])),this.bottomBarItems=e});return this.sceneQueue=i.catch(()=>{}),i}showQuickActions(t){return this.native.showQuickActions(structuredClone(t))}async showSelection(t,s={}){let i;if(this.selection)throw Error("已有选择面板");if(!t.length||t.some(t=>!t.label.trim()||"function"!=typeof t.action))throw TypeError("选择项需要 label 和 action");let r=this.commands.getStore();r?.signal.throwIfAborted();let o=e(),n=t.map(t=>({id:this.functions.bind(o,t.action),label:t.label,description:t.description??""})),a=new Promise(t=>{i=t});this.selection={id:o,settle:i};let l=()=>{i(null),this.native.cancelSelection(o).catch(()=>{})};r?.signal.addEventListener("abort",l,{once:!0});try{await this.native.showSelection(o,n,s.title??"请选择");let t=await a,e=this.functions.take(o,t);if(this.selection=void 0,!e)return!1;return r?await this.commands.run(r,e):await e(),!0}finally{r?.signal.removeEventListener("abort",l),this.functions.release(o),this.selection?.id===o&&(this.selection=void 0)}}onEvent(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}testInput(t){this.native.testInput(t)}close(){return this.closed=!0,this.bottomBarBinding?.dispose(),this.bottomBarBinding=void 0,this.quickActionsBinding?.dispose(),this.quickActionsBinding=void 0,this.selection?.settle(null),this.bridge.invalidate(),this.native.close()}event(t){if("bottom-bar-click"===t.type){let e=this.bottomBarItems.get(t.id)?.click;e&&!this.closed&&Promise.resolve().then(()=>e()).catch(t=>{if(!this.closed)return this.addMessage({type:"log",level:"error",text:String(t)}).catch(()=>{})})}else if("selection-result"===t.type)this.selection?.id===t.selectionId&&this.selection.settle(t.optionId);else if("states-detached"===t.type)this.publish({type:"states-detached",states:t.stateIds.flatMap(t=>{let e=this.bridge.find(t);return e?[e]:[]})});else if("rendered"===t.type){let{renderedStateIds:e,...s}=t;this.publish({...s,renderedStateCount:e.length})}else this.publish(t)}publish(t){for(let e of this.listeners)e(t)}cleanup(){this.closed=!0,this.bottomBarBinding?.dispose(),this.bottomBarBinding=void 0,this.quickActionsBinding?.dispose(),this.quickActionsBinding=void 0,this.selection?.settle(null),this.bottomBarItems.clear(),this.functions.clear(),this.bridge.invalidate(),this.listeners.clear()}}(v=y||(y={})).None=()=>({dispose(){}}),v.once=function(t){return(e,s,i)=>{let r=!1,o=t(t=>{if(!r)return r=!0,e.call(s,t)},null,i);return r&&o.dispose(),o}},v.map=function(t,e){return(s,i,r)=>t(t=>s.call(i,e(t)),null,r)},v.filter=function(t,e){return(s,i,r)=>t(t=>e(t)&&s.call(i,t),null,r)},v.debounce=function(t,e,s=100){let i,r,o;return(n,a,l)=>(i=t(t=>{r=e(r,t),clearTimeout(o),o=setTimeout(()=>{let t=r;r=void 0,n.call(a,t)},s)}),{dispose(){i.dispose(),clearTimeout(o)}})};class O{constructor(){this._listeners=new Set,this._disposed=!1,this.event=t=>this._disposed?{dispose(){}}:(this._listeners.add(t),{dispose:()=>{this._listeners.delete(t)}})}fire(t){if(!this._disposed)for(let e of[...this._listeners])try{e(t)}catch{}}dispose(){this._disposed||(this._disposed=!0,this._listeners.clear())}get hasListeners(){return this._listeners.size>0}}class M{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}clear(){if(0===this._toDispose.size)return;let t=this._toDispose.values();for(let e of(this._toDispose.clear(),t))try{e.dispose()}catch{}}add(t){return this._isDisposed?console.warn("Adding to a disposed DisposableStore"):this._toDispose.add(t),t}get size(){return this._toDispose.size}}class C{constructor(){this._store=new M}dispose(){this._store.dispose()}addDispose(t){return this._store.add(t)}}class q extends C{constructor(t,e){super(),this.valueOrFactoryInit=t,this._initialized=!1,this._onStateChangeEmitter=new O,this.onStateChange=this._onStateChangeEmitter.event,this._options={},this._name="AnonymousState",this.addDispose(this._onStateChangeEmitter),this._options=e||{},this._name=e?.name||"AnonymousState"}get(){return this._initialized||("function"==typeof this.valueOrFactoryInit?this.set(this.valueOrFactoryInit()):this.set(this.valueOrFactoryInit)),this._value}waitUntil(t,e={}){let s=this.get();if(t(s))return Promise.resolve(s);let{timeoutMs:i,signal:r}=e;return new Promise((e,s)=>{let o=!1,n=t=>{o||(o=!0,clearTimeout(c),a.dispose(),r?.removeEventListener("abort",l),t())},a=this.onStateChange(({to:s})=>{t(s)&&n(()=>e(s))}),l=()=>{n(()=>s(r?.reason instanceof Error?r.reason:new Q))},c=void 0!==i?setTimeout(()=>n(()=>s(new D(i))),i):void 0;r?.aborted?l():r?.addEventListener("abort",l,{once:!0})})}set(t){if(this._initialized){if(this._equals(this._value,t))return;let e=this._value;this._value=t,this._onStateChangeEmitter.fire({from:e,to:t})}else this._value=t,this._initialized=!0}_equals(t,e){return this._options.equals?.(t,e)||t===e}get name(){return this._name}}class D extends Error{constructor(t){super(`State wait timed out after ${t}ms`),this.name="StateWaitTimeoutError"}}class Q extends Error{constructor(){super("State wait cancelled"),this.name="StateWaitCancelledError"}}function R(t=process.env){return!t.DBX_TUI_NO_BLOCKS&&("vscode"===t.TERM_PROGRAM||"WezTerm"===t.TERM_PROGRAM||"xterm-kitty"===t.TERM||"wezterm"===t.TERM||!!t.WT_SESSION)}function N(t,e=!1){return{componentId:"dev-server-header",states:{status:t},props:{compact:e}}}function j(t){return{componentId:"qr-code-card",states:{qr:t}}}let z=!1;function P(t){if(z)throw Error("终端输出已被 TUI 接管");z=!0;let e=[],s=(s,i)=>{let r=s.write,o=new c("utf8"),n="",a=e=>{let s=d(e);s.trim()&&t.append(i,s)},l=t=>{let e=(n+=t).split(/\r\n|[\r\n]/);for(let t of(n=e.pop()??"",e))a(t);n.length>=8192&&(a(n),n="")},h=(t,e,s)=>{let i="function"==typeof e?e:s,r="string"==typeof t?Buffer.from(t,"string"==typeof e?e:void 0):Buffer.from(t);return l(o.write(r)),"function"==typeof i&&process.nextTick(i),!0};s.write=h,e.push(()=>{s.write===h&&(s.write=r),l(o.end()),a(n),n=""})};s(process.stdout,"info"),s(process.stderr,"warn");let i=!1;return{dispose(){if(!i){i=!0;try{for(let t of e)t()}finally{z=!1}}}}}export{x as TUIManager,P as captureTerminalOutput,N as createDevServerHeader,j as createQRCodeCard,q as state_State,R as terminal_blockGlyphsSafe};
|
|
1
|
+
import{AsyncLocalStorage as t}from"node:async_hooks";import{randomUUID as e}from"node:crypto";import{performance as r}from"node:perf_hooks";import{createRequire as i,syncBuiltinESMExports as s}from"node:module";import{existsSync as o}from"node:fs";import{dirname as n,join as a,resolve as l}from"node:path";import{fileURLToPath as c}from"node:url";import d from"node:child_process";import{StringDecoder as h}from"node:string_decoder";import{stripVTControlCharacters as u}from"node:util";import"./691.js";class p{componentId="markdown-card";states={};props;constructor(t){this.props={text:t}}}class m extends p{componentId="hint"}function f(t){let e=new Set;if(!t||Array.isArray(t)||"object"!=typeof t)throw TypeError("state 必须是 JSON 对象");return!function t(r){if(null!==r&&"string"!=typeof r&&"boolean"!=typeof r&&!("number"==typeof r&&Number.isFinite(r))){if("object"!=typeof r||null===r)throw TypeError("state 只允许 JSON 值");if(e.has(r))throw TypeError("state 不能包含循环引用");if(!Array.isArray(r)&&Object.getPrototypeOf(r)!==Object.prototype&&null!==Object.getPrototypeOf(r))throw TypeError("state 只允许普通 JSON 对象");if(e.add(r),Array.isArray(r))for(let e=0;e<r.length;e+=1)t(r[e]);else{if(Object.getOwnPropertySymbols(r).length)throw TypeError("state 不能包含 Symbol 字段");for(let e of Object.values(r))t(e)}e.delete(r)}}(t),JSON.parse(JSON.stringify(t))}class w{native;constructor(t){this.native=t}createState(t,e){this.native.createState(t,f(e))}setState(t,e){this.native.setState(t,f(e))}disposeState(t){this.native.disposeState(t)}}function g(t){if(!t.trim())return[];if(t.trimStart().startsWith("[")){let e=JSON.parse(t);if(!Array.isArray(e))throw TypeError("命令参数必须是 JSON 数组");return f({args:e}).args}let e=[],r="",i="",s=!1,o=!1;for(let n of t)s?(r+=n,s=!1,o=!0):"\\"===n?(s=!0,o=!0):i?n===i?i="":r+=n:'"'===n||"'"===n?(i=n,o=!0):/\s/.test(n)?o&&(e.push(r),r="",o=!1):(r+=n,o=!0);if(i||s)throw TypeError("命令参数存在未闭合的引号或转义");return o&&e.push(r),e}class v{_groups=new Map;bind(t,r){let i=e(),s=this._groups.get(t)??new Map;return s.set(i,r),this._groups.set(t,s),i}take(t,e){let r=null===e?void 0:this._groups.get(t)?.get(e);return this.release(t),r}release(t){this._groups.delete(t)}clear(){this._groups.clear()}}class y{now;arrivals=[];lastArrival=-1/0;flooding=!1;constructor(t=()=>r.now()){this.now=t}admit(){let t=this.now();return(this.flooding&&t-this.lastArrival>=500&&(this.flooding=!1,this.arrivals=[]),this.lastArrival=t,this.flooding)?"drop":(this.arrivals=this.arrivals.filter(e=>t-e<5e3),this.arrivals.push(t),this.arrivals.length>=500)?(this.flooding=!0,this.arrivals=[],"flood-started"):"accept"}}var b=JSON.parse('{"macos-arm64":{"target":"aarch64-apple-darwin","library":"libratatui_renderer.dylib","enabled":true},"macos-x64":{"target":"x86_64-apple-darwin","library":"libratatui_renderer.dylib","enabled":true},"windows-x64":{"target":"x86_64-pc-windows-msvc","library":"ratatui_renderer.dll","enabled":true},"linux-alpine":{"target":"x86_64-unknown-linux-musl","library":"libratatui_renderer.so","enabled":false},"linux-x64":{"target":"x86_64-unknown-linux-gnu","library":"libratatui_renderer.so","enabled":false}}');function S(){let t=!1;return"linux"===process.platform&&"x64"===process.arch&&(t=!process.report.getReport().header.glibcVersionRuntime),function(t,e,r=!1){let i;if("darwin"===t&&"arm64"===e&&(i="macos-arm64"),"darwin"===t&&"x64"===e&&(i="macos-x64"),"win32"===t&&"x64"===e&&(i="windows-x64"),"linux"===t&&"x64"===e&&(i=r?"linux-alpine":"linux-x64"),i&&b[i].enabled)return i;let s=Object.keys(b).filter(t=>b[t].enabled);throw Error(`当前平台 ${t}-${e} 不支持 DBX TUI。当前支持:${s.join("、")};Linux 暂未启用。可使用 --agent 模式。`)}(process.platform,process.arch,t)}function B(t=S()){let e=t.replace("macos-","darwin-").replace("windows-","win32-");return`@doubao-dev/cli-tui-${e}`}let I=i(import.meta.url),k=new WeakMap,A=new WeakMap;function E(t){let e=k.get(t);if(!e)throw TypeError("只能传递由 RSStateStore 创建的 RSState 对象");if(!e.owner.alive)throw Error("RSState 所属 TUI 已关闭");if(e.disposed)throw Error("RSState 已释放");return e}function x(t){let e=A.get(t);if(!e)throw TypeError("RSStateStore 必须由 TUIManager 创建");if(!e.alive)throw Error("TUI 已关闭");return e}function T(t,e){let r=E(e);if(r.owner!==t)throw TypeError("状态不存在");return r}class O{get(){return f(E(this).value)}set(t){let e=E(this),r=f(t);e.owner.native.setState(e.id,r),e.value=r}dispose(){let t=E(this);t.owner.native.disposeState(t.id),t.disposed=!0,t.value={},t.owner.byId.delete(t.id),t.owner.onDispose(this)}get disposed(){let t=k.get(this);return!t||t.disposed||!t.owner.alive}toJSON(){throw TypeError("RSState 不能序列化;请把 RSState 对象传给 TUIManager")}}class M{createState(t){let r=x(this),i=f(t),s=`rs:${e()}`;r.native.createState(s,i);let o=Object.create(O.prototype);return k.set(o,{id:s,owner:r,value:i,disposed:!1}),r.byId.set(s,o),Object.freeze(o),o}setState(t,e){T(x(this),t),t.set(e)}disposeState(t){T(x(this),t),t.dispose()}}class _{states;done;native;bridge;listeners=new Set;commands=new t;functions=new v;selection;quickActionsBinding;closed=!1;messageThrottler=new y;bottomBarBinding;bottomBarItems=new Map;sceneQueue=Promise.resolve();constructor(t={}){var e,r;let s,d;t.onEvent&&this.listeners.add(t.onEvent),this.native=function(t={}){let e,r,s,{Renderer:d}=I(function(t){let e=S(),r=`renderer-${e}.node`;if(!t)try{return i(import.meta.url).resolve(B(e))}catch(t){if("MODULE_NOT_FOUND"!==t.code)throw t}let s=t??l(n(c(import.meta.url)),"../../native"),d=a(s,r),h=a(s,"renderer.node");if(t&&o(h))return h;if(!o(d))throw Error(`DBX TUI 原生模块缺失:${d}。请重新构建或安装包含 ${e} 产物的 CLI;安装时请保留 optionalDependencies。也可使用 --agent 模式。`);return d}(t.nativeDirectory));if(!t.headless&&(!process.stdin.isTTY||!process.stdout.isTTY))throw Error("交互模式需要真实终端;无终端验证请使用 npm test。");let h=!1,u=new Set;t.onEvent&&u.add(t.onEvent);let p=new Map,m=()=>{for(let t of p.values())t.abort();p.clear()},f=()=>{if(h)throw Error("renderer 已关闭")},g=new Promise((t,i)=>{e=t,r=i}),v=()=>(h=!0,m(),b.close()),y=()=>{v().catch(r)},b=new d((t,i)=>{if(t){s=t,v().catch(r);return}if("closed"===i.type){h=!0,m(),u.clear(),process.removeListener("SIGINT",y),process.removeListener("SIGTERM",y);let t=s??(i.error?Error(i.error):void 0);t?r(t):e();return}try{for(let t of u)t(i)}catch(t){s=t instanceof Error?t:Error(String(t)),v().catch(r)}},t.headless??!1);process.on("SIGINT",y),process.on("SIGTERM",y);let k=new w({createState(t,e){f(),b.createState(t,e)},setState(t,e){f(),b.setState(t,e)},disposeState(t){f(),b.disposeState(t)}}),A=t=>(e,r)=>{if(h)return;let i=new AbortController;p.set(r.requestId,i),Promise.resolve().then(()=>{if(e)throw e;return t({...r,signal:i.signal})}).catch(t=>{if(!i.signal.aborted&&!h)try{b.commandFailed(r.requestId,t instanceof Error?t.message:String(t))}catch{}}).finally(()=>{p.delete(r.requestId)})};return{stateStore:k,showSelection:(t,e,r)=>(f(),b.showSelection(t,e,r)),cancelSelection:t=>(f(),b.cancelSelection(t)),clearHistory:()=>(f(),b.clearHistory()),clearCommands:()=>(f(),b.clearCommands()),addMessage:t=>(f(),b.addMessage(t)),registerCommand:(t,e,r)=>(f(),b.registerCommand(t,e,A(r))),switchScene:(t,e)=>(f(),b.switchScene(t,A(e))),setBottomBarItems:t=>(f(),b.setBottomBarItems(t)),showQuickActions:t=>(f(),b.showQuickActions(t)),onEvent:t=>(f(),u.add(t),()=>{u.delete(t)}),testInput(t){f(),b.testInput(t)},close:v,done:g}}({headless:t.headless,nativeDirectory:t.nativeDirectory,onEvent:t=>this.event(t)}),this.bridge=(e=this.native.stateStore,r=t=>this.publish({type:"state-disposed",state:t}),s={alive:!0,native:e,byId:new Map,onDispose:r},d=Object.create(M.prototype),A.set(d,s),Object.freeze(d),{store:d,resolve:t=>T(s,t).id,find:t=>s.byId.get(t),invalidate(){for(let t of(s.alive=!1,s.native=void 0,s.byId.values()))k.get(t).value={};s.byId.clear()}}),this.states=this.bridge.store,this.done=this.native.done,this.done.then(()=>this.cleanup(),()=>this.cleanup())}clearHistory(){return this.selection?.settle(null),this.native.clearHistory()}clearCommands(){let t=this.sceneQueue.then(async()=>{await this.native.clearCommands(),this.quickActionsBinding?.dispose(),this.quickActionsBinding=void 0});return this.sceneQueue=t.catch(()=>{}),t}registerCommand(t){let e=t.callback;if("function"!=typeof e)throw TypeError("command.callback 必须是函数");return this.native.registerCommand(t.name,t.description,t=>this.commands.run(t,async()=>{await e(this,t.signal,...t.parameters??g(t.args))}))}component(t){let e=Object.fromEntries(Object.entries(t.states).map(([t,e])=>[t,this.bridge.resolve(e)]));return{type:"component",componentId:t.componentId,states:e,props:f(t.props??{})}}async addMessage(t){this.commands.getStore()?.signal.throwIfAborted();let e=this.messageThrottler.admit();if("accept"!==e){"flood-started"===e&&await this.native.addMessage({type:"log",level:"info",text:"警告:日志过多,5 秒内收到 500 条日志,已暂停展示后续日志;日志静默 500ms 后恢复。"});return}if("markdown"===t.type||"hint"===t.type){let e="hint"===t.type?new m(t.text):new p(t.text);await this.native.addMessage(this.component(e));return}await this.native.addMessage("log"===t.type?{...t,level:t.level??"info"}:this.component(t))}switchScene(t){let e=new Map(t.commands.map(t=>[t.name,{...t}])),r=()=>{let e=t.bottomBarItems;return e&&"get"in e?e.get():e??[]},i={bottomBarItems:this.bottomBarSnapshot(r()),id:t.id,compact:t.compact??!1,commands:[...e.values()].map(({name:t,description:e})=>({name:t,description:e})),headerComponent:t.headerComponent?this.component(t.headerComponent):null,quickActions:structuredClone(t.quickActions.get())},s=this.sceneQueue.then(async()=>{if(i.bottomBarItems=this.bottomBarSnapshot(r()),i.quickActions=structuredClone(t.quickActions.get()),await this.native.switchScene(i,t=>{let r=e.get(t.name);if(!r)throw Error(`未知指令:${t.name}`);return this.commands.run(t,async()=>{await r.callback(this,t.signal,...t.parameters??g(t.args))})}),this.closed)return;this.bottomBarBinding?.dispose(),this.bottomBarBinding=void 0,this.bottomBarItems=new Map(r().map(t=>[t.id,{...t}]));let s=t.bottomBarItems;if(s&&"onStateChange"in s){let t=s.onStateChange(({to:e})=>{let r=e.map(t=>({...t})),i=this.sceneQueue.then(async()=>{this.bottomBarBinding!==t||this.closed||(await this.native.setBottomBarItems(this.bottomBarSnapshot(r)),this.bottomBarItems=new Map(r.map(t=>[t.id,t])))});this.sceneQueue=i.catch(()=>{})});this.bottomBarBinding=t}await this.native.setBottomBarItems(this.bottomBarSnapshot(r())),this.quickActionsBinding?.dispose();let o=t.quickActions.onStateChange(({to:t})=>{let e=structuredClone(t),r=this.sceneQueue.then(async()=>{this.quickActionsBinding!==o||this.closed||await this.native.showQuickActions(e)});this.sceneQueue=r.catch(async t=>{this.closed||await this.native.addMessage({type:"log",level:"error",text:String(t)}).catch(()=>{})})});this.quickActionsBinding=o,JSON.stringify(t.quickActions.get())!==JSON.stringify(i.quickActions)&&await this.native.showQuickActions(structuredClone(t.quickActions.get()))});return this.sceneQueue=s.catch(()=>{}),s}bottomBarSnapshot(t){let e=new Set;return t.map(t=>{if(!t.id.trim()||t.id.startsWith("__rust.")||e.has(t.id)||"string"!=typeof t.text||/[\r\n]/.test(t.text)||void 0!==t.side&&"left"!==t.side&&"right"!==t.side||void 0!==t.color&&!["yellow","green","red","blue","cyan","magenta","white","gray"].includes(t.color)||void 0!==t.click&&"function"!=typeof t.click)throw TypeError("底部栏条目需要唯一 id、text 和可选 click 回调");return e.add(t.id),{id:t.id,text:t.text,side:t.side??"left",color:t.color??null,clickable:!!t.click}})}setBottomBarItems(t){let e=t.map(t=>({...t})),r=this.bottomBarSnapshot(e),i=this.sceneQueue.then(async()=>{await this.native.setBottomBarItems(r),this.bottomBarItems=new Map(e.map(t=>[t.id,t]))});return this.sceneQueue=i.catch(()=>{}),i}upsertBottomBarItem(t){return this.mutateBottomBar(t.id,t)}removeBottomBarItem(t){return this.mutateBottomBar(t)}mutateBottomBar(t,e){let r=e?{...e}:void 0,i=this.sceneQueue.then(async()=>{let e=new Map(this.bottomBarItems);r?e.set(t,r):e.delete(t),await this.native.setBottomBarItems(this.bottomBarSnapshot([...e.values()])),this.bottomBarItems=e});return this.sceneQueue=i.catch(()=>{}),i}showQuickActions(t){return this.native.showQuickActions(structuredClone(t))}async showSelection(t,r={}){let i;if(this.selection)throw Error("已有选择面板");if(!t.length||t.some(t=>!t.label.trim()||"function"!=typeof t.action))throw TypeError("选择项需要 label 和 action");let s=this.commands.getStore();s?.signal.throwIfAborted();let o=e(),n=t.map(t=>({id:this.functions.bind(o,t.action),label:t.label,description:t.description??""})),a=new Promise(t=>{i=t});this.selection={id:o,settle:i};let l=()=>{i(null),this.native.cancelSelection(o).catch(()=>{})};s?.signal.addEventListener("abort",l,{once:!0});try{await this.native.showSelection(o,n,r.title??"请选择");let t=await a,e=this.functions.take(o,t);if(this.selection=void 0,!e)return!1;return s?await this.commands.run(s,e):await e(),!0}finally{s?.signal.removeEventListener("abort",l),this.functions.release(o),this.selection?.id===o&&(this.selection=void 0)}}onEvent(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}testInput(t){this.native.testInput(t)}close(){return this.closed=!0,this.bottomBarBinding?.dispose(),this.bottomBarBinding=void 0,this.quickActionsBinding?.dispose(),this.quickActionsBinding=void 0,this.selection?.settle(null),this.bridge.invalidate(),this.native.close()}event(t){if("bottom-bar-click"===t.type){let e=this.bottomBarItems.get(t.id)?.click;e&&!this.closed&&Promise.resolve().then(()=>e()).catch(t=>{if(!this.closed)return this.addMessage({type:"log",level:"error",text:String(t)}).catch(()=>{})})}else if("selection-result"===t.type)this.selection?.id===t.selectionId&&this.selection.settle(t.optionId);else if("states-detached"===t.type)this.publish({type:"states-detached",states:t.stateIds.flatMap(t=>{let e=this.bridge.find(t);return e?[e]:[]})});else if("rendered"===t.type){let{renderedStateIds:e,...r}=t;this.publish({...r,renderedStateCount:e.length})}else this.publish(t)}publish(t){for(let e of this.listeners)e(t)}cleanup(){this.closed=!0,this.bottomBarBinding?.dispose(),this.bottomBarBinding=void 0,this.quickActionsBinding?.dispose(),this.quickActionsBinding=void 0,this.selection?.settle(null),this.bottomBarItems.clear(),this.functions.clear(),this.bridge.invalidate(),this.listeners.clear()}}function C(t,e=!1){return{componentId:"dev-server-header",states:{status:t},props:{compact:e}}}function q(t){return{componentId:"qr-code-card",states:{qr:t}}}let Q=!1;function N(t){if(Q)throw Error("终端输出已被 TUI 接管");Q=!0;let e=[],r=!1,i=e=>{let r=new h("utf8"),i="",s=r=>{let i=u(r);i.trim()&&t.append(e,i)},o=t=>{let e=(i+=t).split(/\r\n|[\r\n]/);for(let t of(i=e.pop()??"",e))s(t);i.length>=8192&&(s(i),i="")};return{write(t){o(r.write(t))},flush(){o(r.end()),s(i),i=""}}},o=(t,r)=>{let s=t.write,o=i(r),n=(t,e,r)=>{let i="function"==typeof e?e:r,s="string"==typeof t?Buffer.from(t,"string"==typeof e?e:void 0):Buffer.from(t);return o.write(s),"function"==typeof i&&process.nextTick(i),!0};t.write=n,e.push(()=>{t.write===n&&(t.write=s),o.flush()})};o(process.stdout,"info"),o(process.stderr,"warn");let n=new Set;e.push(()=>{for(let t of n)t();n.clear()});let a=d.spawn,l=d.fork,c=(t,e,s)=>{if(!t)return;let o=i(s);t.on("data",t=>{r?e.write(t):o.write(t)});let a=()=>o.flush();n.add(a),t.once("close",()=>{n.delete(a),r||a()})},p=(t,e)=>(r,i,s)=>{let o=Array.isArray(i)?i:[],n=(Array.isArray(i)||null==i?s:i)??{},a=n.stdio;("inherit"===a||e&&void 0===a&&!n.silent)&&(a=e?["inherit","inherit","inherit","ipc"]:["inherit","inherit","inherit"]);let l=Array.isArray(a)&&"inherit"===a[1],d=Array.isArray(a)&&"inherit"===a[2];if(!Array.isArray(a)||!l&&!d)return t(r,o,n);let h=[...a];l&&(h[1]="pipe"),d&&(h[2]="pipe");let u=t(r,o,{...n,stdio:h});if(l&&c(u.stdout,process.stdout,"info"),d&&c(u.stderr,process.stderr,"warn"),n.detached)for(let t of[l&&u.stdout,d&&u.stderr])t&&"unref"in t&&t.unref();return u},m=p(a,!1),f=p(l,!0);return d.spawn=m,d.fork=f,s(),e.unshift(()=>{d.spawn===m&&(d.spawn=a),d.fork===f&&(d.fork=l),s()}),{dispose(){if(!r){r=!0;try{for(let t of e)t()}finally{Q=!1}}}}}export{_ as TUIManager,N as captureTerminalOutput,C as createDevServerHeader,q as createQRCodeCard,B as getNativePackageName};
|
package/dist/draft.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{upsertPluginDraft as a,validateMaterial as
|
|
2
|
-
${
|
|
1
|
+
import{upsertPluginDraft as i,VISIBILITY_TYPE_LABELS as a,resolvePublicationType as t,log as e,validateMaterial as r,PUBLICATION_TYPE_LABELS as o,uploadPackage as l,pluginIdentity as n}from"./691.js";import{withProgress as p}from"./progress.js";async function _(_,c){let{project:d,options:s}=_,{name:u,id:w}=d.plugin,y=w?await p("核对发布类型",()=>t(d)):await t(d);e.info(`发布类型:${o[y]}${!w?";首次创建平台草稿后不可切换":""}`);let f={...n(d.plugin),publication_type:y},{version:$}=s,E=await p("打包项目",()=>d.pack({version:$,exclude:c})),g=`${u}-${Date.now()}.zip`,b=await p("上传应用插件包",async()=>{let{package_id:i}=await l(g,E);if(!i)throw Error("上传失败:服务端未返回 package_id");return i});await p("校验物料",async()=>{let i=await r({package_id:b,...f,validate_list:["PACKAGE_PARSE"]});if(!i.passed){let a=i.issues?.map(i=>{let a=[i.path,i.field_path].filter(Boolean).join(":"),t=i.message||i.code||"未知问题";return`- ${a?`${a}:`:""}${t}`}).join("\n");throw Error(`物料校验未通过${a?`
|
|
2
|
+
${a}`:""}`)}});let h=await p("保存草稿",async()=>{let{draft:a}=await i({package_id:b,...f});if(!a?.name||!a.ability_id)throw Error("草稿保存失败:服务端未返回插件名称或 ID");return a});if(h.ability_id){e.success(`应用插件 ID:${h.ability_id}`);try{await d.updatePluginId(h.ability_id),await d.updatePublicationType(y)}catch(i){throw Error(`草稿已保存,但本地关联写入失败,请将 ID ${h.ability_id} 和 publicationType ${y} 保存到 plugin.json`,{cause:i})}}if("ENTERPRISE"===y){let i=h.visibility_config?.type,t=void 0===i?void 0:a[i];e.info(`草稿可见范围:${t??"由平台保存,首次默认仅本人"}`)}return{packageId:b,draft:h}}export{_ as uploadDraft};
|
package/dist/index.d.ts
CHANGED
|
@@ -101,8 +101,8 @@ export declare interface InitContext {
|
|
|
101
101
|
export declare interface InitOption {
|
|
102
102
|
flags: string;
|
|
103
103
|
description: string;
|
|
104
|
-
/** Yes/no question asked in interactive init
|
|
105
|
-
prompt?: string;
|
|
104
|
+
/** Yes/no question asked in interactive init; returning undefined skips the question. */
|
|
105
|
+
prompt?: string | ((ctx: InitContext) => string | undefined);
|
|
106
106
|
}
|
|
107
107
|
|
|
108
108
|
declare type Logger = Record<'info' | 'success' | 'warn' | 'error', (message: string) => void>;
|
|
@@ -156,6 +156,10 @@ declare const pluginManifestSchema: z.ZodObject<{
|
|
|
156
156
|
$schema: z.ZodOptional<z.ZodString>;
|
|
157
157
|
name: z.ZodString;
|
|
158
158
|
id: z.ZodOptional<z.ZodString>;
|
|
159
|
+
publicationType: z.ZodOptional<z.ZodEnum<{
|
|
160
|
+
PUBLIC: "PUBLIC";
|
|
161
|
+
ENTERPRISE: "ENTERPRISE";
|
|
162
|
+
}>>;
|
|
159
163
|
displayName: z.ZodOptional<z.ZodString>;
|
|
160
164
|
description: z.ZodOptional<z.ZodString>;
|
|
161
165
|
extensions: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
@@ -163,11 +167,14 @@ declare const pluginManifestSchema: z.ZodObject<{
|
|
|
163
167
|
|
|
164
168
|
declare class PluginProject {
|
|
165
169
|
readonly root: string;
|
|
166
|
-
readonly plugin: PluginManifest;
|
|
167
170
|
readonly app?: AppProject;
|
|
168
171
|
private readonly pluginManifestPath;
|
|
172
|
+
private manifest;
|
|
169
173
|
constructor(cwd?: string);
|
|
174
|
+
get plugin(): PluginManifest;
|
|
170
175
|
updatePluginId(id: string): Promise<void>;
|
|
176
|
+
updateManifest(update: (manifest: PluginManifest) => PluginManifest): Promise<void>;
|
|
177
|
+
updatePublicationType(publicationType: PublicationType): Promise<void>;
|
|
171
178
|
pack({ version, exclude }?: PackagePlan): Promise<Blob>;
|
|
172
179
|
readSkills(): Skill[];
|
|
173
180
|
get mcpServers(): McpServer[];
|
|
@@ -179,6 +186,8 @@ export declare type ProvideSkillsHook = (ctx: {
|
|
|
179
186
|
project: PluginProject;
|
|
180
187
|
}) => Awaitable<readonly SkillSource[]>;
|
|
181
188
|
|
|
189
|
+
declare type PublicationType = 'PUBLIC' | 'ENTERPRISE';
|
|
190
|
+
|
|
182
191
|
export declare interface RegisteredDevTarget {
|
|
183
192
|
pluginName: string;
|
|
184
193
|
target: DevTarget;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function n(n){return n}export{main as runCLI}from"./
|
|
1
|
+
function n(n){return n}export{main as runCLI}from"./691.js";export{n as definePlugin};
|
package/dist/main.d.ts
CHANGED
|
@@ -99,8 +99,8 @@ declare interface InitContext {
|
|
|
99
99
|
declare interface InitOption {
|
|
100
100
|
flags: string;
|
|
101
101
|
description: string;
|
|
102
|
-
/** Yes/no question asked in interactive init
|
|
103
|
-
prompt?: string;
|
|
102
|
+
/** Yes/no question asked in interactive init; returning undefined skips the question. */
|
|
103
|
+
prompt?: string | ((ctx: InitContext) => string | undefined);
|
|
104
104
|
}
|
|
105
105
|
|
|
106
106
|
declare type Logger = Record<'info' | 'success' | 'warn' | 'error', (message: string) => void>;
|
|
@@ -156,6 +156,10 @@ declare const pluginManifestSchema: z.ZodObject<{
|
|
|
156
156
|
$schema: z.ZodOptional<z.ZodString>;
|
|
157
157
|
name: z.ZodString;
|
|
158
158
|
id: z.ZodOptional<z.ZodString>;
|
|
159
|
+
publicationType: z.ZodOptional<z.ZodEnum<{
|
|
160
|
+
PUBLIC: "PUBLIC";
|
|
161
|
+
ENTERPRISE: "ENTERPRISE";
|
|
162
|
+
}>>;
|
|
159
163
|
displayName: z.ZodOptional<z.ZodString>;
|
|
160
164
|
description: z.ZodOptional<z.ZodString>;
|
|
161
165
|
extensions: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
@@ -163,11 +167,14 @@ declare const pluginManifestSchema: z.ZodObject<{
|
|
|
163
167
|
|
|
164
168
|
declare class PluginProject {
|
|
165
169
|
readonly root: string;
|
|
166
|
-
readonly plugin: PluginManifest;
|
|
167
170
|
readonly app?: AppProject;
|
|
168
171
|
private readonly pluginManifestPath;
|
|
172
|
+
private manifest;
|
|
169
173
|
constructor(cwd?: string);
|
|
174
|
+
get plugin(): PluginManifest;
|
|
170
175
|
updatePluginId(id: string): Promise<void>;
|
|
176
|
+
updateManifest(update: (manifest: PluginManifest) => PluginManifest): Promise<void>;
|
|
177
|
+
updatePublicationType(publicationType: PublicationType): Promise<void>;
|
|
171
178
|
pack({ version, exclude }?: PackagePlan): Promise<Blob>;
|
|
172
179
|
readSkills(): Skill[];
|
|
173
180
|
get mcpServers(): McpServer[];
|
|
@@ -179,6 +186,8 @@ declare type ProvideSkillsHook = (ctx: {
|
|
|
179
186
|
project: PluginProject;
|
|
180
187
|
}) => Awaitable<readonly SkillSource[]>;
|
|
181
188
|
|
|
189
|
+
declare type PublicationType = 'PUBLIC' | 'ENTERPRISE';
|
|
190
|
+
|
|
182
191
|
declare interface RegisteredDevTarget {
|
|
183
192
|
pluginName: string;
|
|
184
193
|
target: DevTarget;
|
package/dist/main.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{main}from"./
|
|
1
|
+
export{main}from"./691.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createReadStream as e,existsSync as t,mkdirSync as r,readFileSync as o}from"node:fs";import n,{createServer as i}from"node:http";import{fileURLToPath as a}from"node:url";import{homedir as s}from"node:os";import c,{join as l}from"node:path";import{Readable as d}from"node:stream";import{stat as f}from"node:fs/promises";import{spawn as p}from"node:child_process";import{node_modules_open as h}from"./open.js";let u="127.0.0.1",m=l(s(),".dbx","mcp-inspector","browser-profile");function w(e,t){return new Promise((r,o)=>{e.once("error",o),e.listen(t,u,()=>{e.off("error",o),r(e.address().port)})})}function g(e){return new Promise(t=>{e.close(()=>t()),e.closeAllConnections()})}let y="x-mcp-target",b=new Set(["host","origin","referer","connection","content-length","accept-encoding","cookie",y]),x=new Set(["content-encoding","content-length","transfer-encoding","connection","keep-alive"]);function E(e,t,r){e.statusCode=t,e.setHeader("content-type","application/json"),e.end(JSON.stringify({error:r}))}async function $(e,t,r){let o,n;if(!e.url?.startsWith("/__mcp_proxy"))return r();let i=e.headers[y],a=Array.isArray(i)?i[0]:i;try{o=new URL(a??"")}catch{return E(t,400,`Invalid ${y} header`)}if("http:"!==o.protocol&&"https:"!==o.protocol)return E(t,400,"Only http(s) MCP endpoints can be proxied");let s=new Headers;for(let[t,r]of Object.entries(e.headers))void 0===r||b.has(t)||s.set(t,Array.isArray(r)?r.join(", "):r);let c=e.method??"GET",l="GET"===c||"HEAD"===c?void 0:await new Promise((t,r)=>{let o=[];e.on("data",e=>o.push(e)),e.on("end",()=>t(Buffer.concat(o))),e.on("error",r)}),f=new AbortController;t.on("close",()=>f.abort());try{n=await fetch(o,{method:c,headers:s,body:l&&l.length>0?new Uint8Array(l):void 0,signal:f.signal,redirect:"manual"})}catch(r){if(f.signal.aborted)return;let e=r instanceof Error?r.cause??r:r;return E(t,502,`Cannot reach ${o.href}: ${String(e)}`)}if(t.statusCode=n.status,t.statusMessage=n.statusText,n.headers.forEach((e,r)=>{x.has(r)||t.setHeader(r,e)}),t.flushHeaders(),!n.body)return t.end();d.fromWeb(n.body).on("error",()=>t.destroy()).pipe(t)}let C="/*INSPECTOR_EMBEDDER_ORIGINS*/ null";function S(e){return[`http://${u}:${e}`,`http://localhost:${e}`]}async function A({htmlPath:e,allowedOrigins:t,port:r=6275}){let n;if(0===t.length||t.some(e=>!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(e)))throw Error("Sandbox requires explicit loopback Inspector origins");let a=o(e,"utf8");if(!a.includes(C))throw Error("Sandbox proxy template is missing its embedder origins marker");let s=a.replace(C,()=>JSON.stringify(t).replace(/</g,"\\u003c")),c=0,l=i((e,r)=>{if(!S(c).some(t=>new URL(t).host===e.headers.host)){r.writeHead(403),r.end("Forbidden");return}if("GET"!==e.method||"/sandbox"!==e.url&&"/sandbox/"!==e.url){r.writeHead(404),r.end("Not Found");return}r.writeHead(200,{"content-type":"text/html; charset=utf-8","cache-control":"no-store","x-content-type-options":"nosniff","content-security-policy":`frame-ancestors ${t.join(" ")}`}),r.end(s)});try{let e=t.some(e=>new URL(e).port===String(r));c=await w(l,e?0:r)}catch(e){if("EADDRINUSE"!==e.code)throw e;c=await w(l,0)}return{url:`http://${u}:${c}/sandbox`,close:()=>n??=g(l)}}let v={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".woff2":"font/woff2",".txt":"text/plain; charset=utf-8"};async function H(e){try{return(await f(e)).isFile()}catch{return!1}}let R=["Google Chrome","Microsoft Edge","Chromium","Brave Browser"],_=["google-chrome","google-chrome-stable","chromium","chromium-browser","microsoft-edge"],P=[`${process.env.ProgramFiles}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env["ProgramFiles(x86)"]}\\Microsoft\\Edge\\Application\\msedge.exe`];function U(e,t){return new Promise(r=>{let o=p(e,t,{stdio:"ignore",detached:!0});o.on("error",()=>r(!1)),o.on("spawn",()=>{o.unref(),r(!0)})})}async function j(e){r(m,{recursive:!0});let o=[`--app=${e}`,`--user-data-dir=${m}`,"--window-size=1440,900","--no-first-run","--no-default-browser-check"];if("darwin"===process.platform){for(let e of R)if(t(`/Applications/${e}.app`))return U("open",["-na",e,"--args",...o])}else if("win32"===process.platform){for(let e of P)if(t(e))return U(e,o)}else for(let e of _)if(await U(e,o))return!0;return!1}let I=a(new URL("./web",import.meta.url));async function D(e,t){let r=t??6274,o=t??6294;for(let t=r;t<=o;t++)try{return await w(e,t)}catch(e){if("EADDRINUSE"!==e.code)throw e}throw Error(void 0===t?`端口 ${r}-${o} 都已被占用,请用 --port 指定其他端口`:`端口 ${t} 已被占用,请换一个端口`)}async function N(r={}){let o,i,s,{endpoint:l,headers:d={},port:f,open:p=!0,signal:m,log:w}=r;if(m?.throwIfAborted(),!t(I))throw Error(`MCP 调试界面资源缺失:${I}`);let y=async(t,r,o)=>{let n;if("GET"!==t.method&&"HEAD"!==t.method)return o();try{n=decodeURIComponent(new URL(t.url??"/","http://localhost").pathname)}catch{return o()}let i=c.join(I,n);if(i!==I&&!i.startsWith(`${I}${c.sep}`))return o();if(!await H(i)){if(c.extname(n))return o();i=c.join(I,"index.html")}if(r.statusCode=200,r.setHeader("content-type",v[c.extname(i)]??"application/octet-stream"),"HEAD"===t.method)return r.end();e(i).on("error",()=>r.destroy()).pipe(r)},b=0,x=n.createServer((e,t)=>{let{host:r}=e.headers;if(r!==`${u}:${b}`&&r!==`localhost:${b}`){t.statusCode=403,t.end("Forbidden");return}if("GET"===e.method&&e.url?.split("?")[0]==="/__inspector/config"){if(!o){t.statusCode=503,t.end("Sandbox is starting");return}t.setHeader("content-type","application/json"),t.setHeader("cache-control","no-store"),t.end(o);return}$(e,t,()=>y(e,t,()=>{t.statusCode=404,t.end()})).catch(()=>{t.headersSent?t.destroy():(t.statusCode=500,t.end())})});b=await D(x,f);try{i=await A({htmlPath:a(new URL("./web/sandbox-proxy.html",import.meta.url)),allowedOrigins:S(b)}),o=JSON.stringify({endpoint:l??null,headers:d,sandboxUrl:i.url})}catch(e){throw await g(x),e}let E=()=>s??=Promise.all([g(x),i.close()]).then(()=>{});m?.aborted&&(await E(),m.throwIfAborted()),m?.addEventListener("abort",()=>void E(),{once:!0});let C=`http://${u}:${b}/`,R=!1;if(p)try{(R=await j(C))||(await h(C),w?.warn("未找到 Chrome / Edge,已用默认浏览器打开调试界面"))}catch(e){w?.warn(`未能打开调试界面,请手动访问 ${C}:${e instanceof Error?e.message:String(e)}`)}return{url:C,appWindow:R,close:E}}export{N as startInspector};
|
package/dist/multipart-parser.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"node:http";import"node:https";import"node:zlib";import"node:stream";import"node:buffer";import"node:util";import"node:url";import"node:net";import"node:fs";import"node:path";import{qn as e,br as t}from"./
|
|
1
|
+
import"node:http";import"node:https";import"node:zlib";import"node:stream";import"node:buffer";import"node:util";import"node:url";import"node:net";import"node:fs";import"node:path";import{qn as e,br as t}from"./691.js";var a=Object.defineProperty,r=(e,t)=>a(e,"name",{value:t,configurable:!0});let n=0,i={START_BOUNDARY:n++,HEADER_FIELD_START:n++,HEADER_FIELD:n++,HEADER_VALUE_START:n++,HEADER_VALUE:n++,HEADER_VALUE_ALMOST_DONE:n++,HEADERS_ALMOST_DONE:n++,PART_DATA_START:n++,PART_DATA:n++,END:n++},o=1,d=2,s=r(e=>32|e,"lower"),E=r(()=>{},"noop"),l=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=E,this.onHeaderField=E,this.onHeadersEnd=E,this.onHeaderValue=E,this.onPartBegin=E,this.onPartData=E,this.onPartEnd=E,this.boundaryChars={};let t=new Uint8Array((e=`\r
|
|
2
2
|
--`+e).length);for(let a=0;a<e.length;a++)t[a]=e.charCodeAt(a),this.boundaryChars[t[a]]=!0;this.boundary=t,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=i.START_BOUNDARY}write(e){let t,a,n=0,E=e.length,l=this.index,{lookbehind:A,boundary:h,boundaryChars:D,index:_,state:f,flags:T}=this,u=this.boundary.length,R=u-1,c=e.length,p=r(e=>{this[e+"Mark"]=n},"mark"),b=r(e=>{delete this[e+"Mark"]},"clear"),H=r((e,t,a,r)=>{(void 0===t||t!==a)&&this[e](r&&r.subarray(t,a))},"callback"),m=r((t,a)=>{let r=t+"Mark";r in this&&(a?(H(t,this[r],n,e),delete this[r]):(H(t,this[r],e.length,e),this[r]=0))},"dataCallback");for(n=0;n<E;n++)switch(t=e[n],f){case i.START_BOUNDARY:if(_===h.length-2){if(45===t)T|=d;else if(13!==t)return;_++;break}if(_-1==h.length-2){if(T&d&&45===t)f=i.END,T=0;else{if(T&d||10!==t)return;_=0,H("onPartBegin"),f=i.HEADER_FIELD_START}break}t!==h[_+2]&&(_=-2),t===h[_+2]&&_++;break;case i.HEADER_FIELD_START:f=i.HEADER_FIELD,p("onHeaderField"),_=0;case i.HEADER_FIELD:if(13===t){b("onHeaderField"),f=i.HEADERS_ALMOST_DONE;break}if(_++,45===t)break;if(58===t){if(1===_)return;m("onHeaderField",!0),f=i.HEADER_VALUE_START;break}if((a=s(t))<97||a>122)return;break;case i.HEADER_VALUE_START:if(32===t)break;p("onHeaderValue"),f=i.HEADER_VALUE;case i.HEADER_VALUE:13===t&&(m("onHeaderValue",!0),H("onHeaderEnd"),f=i.HEADER_VALUE_ALMOST_DONE);break;case i.HEADER_VALUE_ALMOST_DONE:if(10!==t)return;f=i.HEADER_FIELD_START;break;case i.HEADERS_ALMOST_DONE:if(10!==t)return;H("onHeadersEnd"),f=i.PART_DATA_START;break;case i.PART_DATA_START:f=i.PART_DATA,p("onPartData");case i.PART_DATA:if(l=_,0===_){for(n+=R;n<c&&!(e[n]in D);)n+=u;n-=R,t=e[n]}if(_<h.length)h[_]===t?(0===_&&m("onPartData",!0),_++):_=0;else if(_===h.length)_++,13===t?T|=o:45===t?T|=d:_=0;else if(_-1===h.length)if(T&o){if(_=0,10===t){T&=~o,H("onPartEnd"),H("onPartBegin"),f=i.HEADER_FIELD_START;break}}else T&d&&45===t?(H("onPartEnd"),f=i.END,T=0):_=0;_>0?A[_-1]=t:l>0&&(H("onPartData",0,l,new Uint8Array(A.buffer,A.byteOffset,A.byteLength)),l=0,p("onPartData"),n--);break;case i.END:break;default:throw Error(`Unexpected state entered: ${f}`)}m("onHeaderField"),m("onHeaderValue"),m("onPartData"),this.index=_,this.state=f,this.flags=T}end(){if(this.state===i.HEADER_FIELD_START&&0===this.index||this.state===i.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==i.END)throw Error("MultipartParser.end(): stream ended unexpectedly")}};function A(e){let t=e.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!t)return;let a=t[2]||t[3]||"",r=a.slice(a.lastIndexOf("\\")+1);return(r=r.replace(/%22/g,'"')).replace(/&#(\d{4});/g,(e,t)=>String.fromCharCode(t))}async function h(a,n){let i,o,d,s,E,h;if(!/multipart/i.test(n))throw TypeError("Failed to fetch");let D=n.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!D)throw TypeError("no or bad content-type header, no multipart boundary");let _=new l(D[1]||D[2]),f=[],T=new t,u=r(e=>{d+=b.decode(e,{stream:!0})},"onPartData"),R=r(e=>{f.push(e)},"appendToFile"),c=r(()=>{let t=new e(f,h,{type:E});T.append(s,t)},"appendFileToFormData"),p=r(()=>{T.append(s,d)},"appendEntryToFormData"),b=new TextDecoder("utf-8");for await(let e of(b.decode(),_.onPartBegin=function(){_.onPartData=u,_.onPartEnd=p,i="",o="",d="",s="",E="",h=null,f.length=0},_.onHeaderField=function(e){i+=b.decode(e,{stream:!0})},_.onHeaderValue=function(e){o+=b.decode(e,{stream:!0})},_.onHeaderEnd=function(){if(o+=b.decode(),"content-disposition"===(i=i.toLowerCase())){let e=o.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);e&&(s=e[2]||e[3]||""),(h=A(o))&&(_.onPartData=R,_.onPartEnd=c)}else"content-type"===i&&(E=o);o="",i=""},a))_.write(e);return _.end(),T}r(l,"MultipartParser"),r(A,"_fileName"),r(h,"toFormData");export{h as toFormData};
|
package/dist/open.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
let e,r,o,t;import i from"node:process";import{Buffer as n}from"node:buffer";import a from"node:path";import{fileURLToPath as s}from"node:url";import c,{execFile as l}from"node:child_process";import m,{constants as d}from"node:fs/promises";import p from"node:os";import f from"node:fs";import{promisify as u}from"node:util";function g(){return void 0===r&&(r=(()=>{try{return f.statSync("/run/.containerenv"),!0}catch{return!1}})()||(void 0===e&&(e=function(){try{return f.statSync("/.dockerenv"),!0}catch{return!1}}()||function(){try{return f.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}()),e)),r}let w=()=>{if("linux"!==i.platform)return!1;if(p.release().toLowerCase().includes("microsoft"))return!g();try{if(f.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!g()}catch{}return!!(f.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||f.existsSync("/run/WSL"))&&!g()},h=i.env.__IS_WSL_TEST__?w:w();function v(e,r,o){let t=o=>Object.defineProperty(e,r,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){let e=o();return t(e),e},set(e){t(e)}}),e}let x=u(l);async function y(){if("darwin"!==i.platform)throw Error("macOS only");let{stdout:e}=await x("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e),o=r?.groups.id??"com.apple.Safari";return"com.apple.safari"===o?"com.apple.Safari":o}let S=u(l);async function E(e,{humanReadableOutput:r=!0,signal:o}={}){if("darwin"!==i.platform)throw Error("macOS only");let t={};o&&(t.signal=o);let{stdout:n}=await S("osascript",["-e",e,r?[]:["-ss"]],t);return n.trim()}async function b(e){return E(`tell application "Finder" to set app_path to application file id "${e}" as string
|
|
2
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}let C=u(l),P={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}};Object.entries(P);class L extends Error{}async function T(e=C){let r=`${i.env.SYSTEMROOT??i.env.windir??"C:\\Windows"}\\System32\\reg.exe`,{stdout:o}=await e(r,["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(o);if(!t)throw new L(`Cannot find Windows browser in stdout: ${JSON.stringify(o)}`);let{id:n}=t.groups,a=n.lastIndexOf("."),s=n.lastIndexOf("-"),c=-1===a?void 0:n.slice(0,a),l=-1===s?void 0:n.slice(0,s);return P[n]??P[c]??P[l]??{name:n,id:n}}let M=u(l);async function B(){if("darwin"===i.platform){let e=await y();return{name:await b(e),id:e}}if("linux"===i.platform){let{stdout:e}=await M("xdg-mime",["query","default","x-scheme-handler/http"]),r=e.trim();return{name:r.replace(/.desktop$/,"").replace("-"," ").toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase()),id:r}}if("win32"===i.platform)return T();throw Error("Only macOS, Linux, and Windows are supported")}let O=a.dirname(s(import.meta.url)),A=a.join(O,"xdg-open"),{platform:H,arch:_}=i,F=(t="/mnt/",async function(){if(o)return o;let e="/etc/wsl.conf",r=!1;try{await m.access(e,d.F_OK),r=!0}catch{}if(!r)return t;let i=await m.readFile(e,{encoding:"utf8"}),n=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return n?o=(o=n.groups.mountPoint.trim()).endsWith("/")?o:`${o}/`:t}),$=async(e,r)=>{let o;for(let t of e)try{return await r(t)}catch(e){o=e}throw o},W=async e=>{let r;if(Array.isArray((e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e}).app))return $(e.app,r=>W({...e,app:r}));let{name:o,arguments:t=[]}=e.app??{};if(t=[...t],Array.isArray(o))return $(o,r=>W({...e,app:{name:r,arguments:t}}));if("browser"===o||"browserPrivate"===o){let r={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","microsoft-edge.desktop":"edge"},i=await B();if(i.id in r){let n=r[i.id];return"browserPrivate"===o&&t.push({chrome:"--incognito",firefox:"--private-window",edge:"--inPrivate"}[n]),W({...e,app:{name:R[n],arguments:t}})}throw Error(`${i.name} is not supported as a default browser`)}let a=[],s={};if("darwin"===H)r="open",e.wait&&a.push("--wait-apps"),e.background&&a.push("--background"),e.newInstance&&a.push("--new"),o&&a.push("-a",o);else if("win32"!==H&&(!h||g()||o)){if(o)r=o;else{let e=!1;try{await m.access(A,d.X_OK),e=!0}catch{}r=i.versions.electron??("android"===H||!O||"/"===O||!e)?"xdg-open":A}t.length>0&&a.push(...t),e.wait||(s.stdio="ignore",s.detached=!0)}else{let c=await F();r=h?`${c}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`:`${i.env.SYSTEMROOT||i.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell`,a.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),h||(s.windowsVerbatimArguments=!0);let l=["Start"];e.wait&&l.push("-Wait"),o?(l.push(`"\`"${o}\`""`),e.target&&t.push(e.target)):e.target&&l.push(`"${e.target}"`),t.length>0&&l.push("-ArgumentList",(t=t.map(e=>`"\`"${e}\`""`)).join(",")),e.target=n.from(l.join(" "),"utf16le").toString("base64")}"darwin"===H&&t.length>0&&a.push("--args",...t),e.target&&a.push(e.target);let l=c.spawn(r,a,s);return e.wait?new Promise((r,o)=>{l.once("error",o),l.once("close",t=>{!e.allowNonzeroExitCode&&t>0?o(Error(`Exited with code ${t}`)):r(l)})}):(l.unref(),l)};function I(e){if("string"==typeof e||Array.isArray(e))return e;let{[_]:r}=e;if(!r)throw Error(`${_} is not supported`);return r}function k({[H]:e},{wsl:r}){if(r&&h)return I(r);if(!e)throw Error(`${H} is not supported`);return I(e)}let R={};v(R,"chrome",()=>k({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}})),v(R,"firefox",()=>k({darwin:"firefox",win32:"C:\\Program Files\\Mozilla Firefox\\firefox.exe",linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"})),v(R,"edge",()=>k({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"})),v(R,"browser",()=>"browser"),v(R,"browserPrivate",()=>"browserPrivate");let N=(e,r)=>{if("string"!=typeof e)throw TypeError("Expected a `target`");return W({...r,target:e})};export{N as node_modules_open};
|