bailian-cli-runtime 1.15.0 → 1.15.1
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/dist/index.mjs +1 -1
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -47,7 +47,7 @@ ${tn()}\nRun: ${L} auth status — to check credentials.`,{cause:e}),L);if(e ins
|
|
|
47
47
|
`),e.forEach((e,n)=>{process.stderr.write(`${t.dim(String(n+1))} ${e}\n`)}),process.stderr.write(`
|
|
48
48
|
`)}function mn(e){return N(ae(),`plugins`,e.npmPackage)}function hn(e){return N(mn(e),`package.json`)}function gn(e,t){return N(mn(e),`node_modules`,...t.split(`/`))}async function _n(e){try{return JSON.parse(await Be(e,`utf8`))}catch(t){throw new m(`Could not parse JSON file: ${e}`,b.GENERAL,`Repair or remove the invalid file and try again.`,{cause:t})}}async function vn(e){let t=hn(e);return Ie(t)?_n(t):{dependencies:{}}}async function yn(e,t){return bn(gn(e,t))}async function bn(e){return _n(N(e,`package.json`))}const xn=new Set([`none`,`apiKey`,`console`,`openapi`]),Sn=/^[a-z0-9][a-z0-9-]*$/;function Cn(e,t,n){if(t.name!==e)throw Error(`Package name mismatch: expected "${e}", received "${t.name??``}".`);let r=t.bailianCli;if(!r||r.type!==`command-pack`)throw Error(`Package "${e}" is missing bailianCli.type="command-pack".`);if(r.apiVersion!==h)throw Error(`Command Pack API ${r.apiVersion} is not supported; this CLI supports API ${h}.`);if(r.minCliVersion&&Dt(n.version,r.minCliVersion)<0)throw Error(`Command Pack requires ${n.npmPackage} ${r.minCliVersion} or newer; current version is ${n.version}.`);if(!r.entry||Ge(r.entry))throw Error(`Command Pack "${e}" must declare a relative bailianCli.entry.`);return r}function wn(e,t){let n=e.split(/\s+/).filter(Boolean).join(` `);if(!e||e!==n||!e.split(` `).every(e=>Sn.test(e)))throw Error(`Invalid command path "${e}".`);if(!t.commandPrefixes.some(t=>e===t||e.startsWith(`${t} `)))throw Error(`Command "${e}" is outside the allowed prefixes: ${t.commandPrefixes.join(`, `)}.`)}function Tn(e,t){if(!t||typeof t!=`object`)throw Error(`Command "${e}" must export an object.`);let n=t;if(!n.description||typeof n.description!=`string`)throw Error(`Command "${e}" is missing a description.`);if(!n.auth||!xn.has(n.auth))throw Error(`Command "${e}" has an invalid auth requirement.`);if(typeof n.run!=`function`)throw Error(`Command "${e}" is missing run(ctx).`)}function En(e,t,n){return Object.fromEntries(Object.entries(t).map(([t,r])=>[t,{description:r.description,auth:r.auth,usageArgs:r.usageArgs,exampleArgs:r.exampleArgs,notes:r.notes,flags:r.flags,validate:r.validate,run:i=>{let a={identity:i.identity,settings:i.settings,flags:i.flags,client:i.client,output:{result(e,t){let n=i.settings.output===`text`&&t?.text!==void 0?t.text:ie(e,i.settings.output);process.stdout.write(`${n}\n`)},line(e){process.stdout.write(`${e}\n`)},write(e){process.stdout.write(e)}},errors:{general(e,t){return new m(e,b.GENERAL,t?.hint,{cause:t?.cause})},usage(e,t){return new w(e,t)},timeout(e=`Request timed out.`,t){return new m(e,b.TIMEOUT,t?.hint,{cause:t?.cause})}},credentials:{apiKey(){if(!n.credentialAccess?.includes(`apiKey`))throw new m(`Command Pack "${e}" is not allowed to access API-key credentials.`,b.GENERAL);if(r.auth!==`apiKey`)throw new m(`Command "${t}" must declare auth="apiKey" before accessing API-key credentials.`,b.GENERAL);let a=i.authStore.describe().apiKey;if(!a)throw new m(`No API key available to the Command Pack.`,b.AUTH);return a}}};return r.run(a)}}]))}async function Dn(e,t,n,r,i=gn(r,e)){let a=Cn(e,t,r),o=await Ve(i),s=await Ve(qe(o,a.entry)),c=Ke(o,s);if(!c||c.startsWith(`..`)||Ge(c))throw Error(`Command Pack entry must stay inside the package root: ${a.entry}`);let l=(await import(Je(s).href)).default;if(!l||typeof l!=`object`||Array.isArray(l))throw Error(`Command Pack "${e}" must default-export a command map.`);let u=Object.entries(l);if(u.length===0)throw Error(`Command Pack "${e}" does not export any commands.`);for(let[e,t]of u)wn(e,n),Tn(e,t);let d=En(e,l,n);return new mt(d,r.binName),d}function On(e){return e.startsWith(`file:`)?`linked`:`installed`}async function kn(e,t,n){let r={...e},i=[],a;try{a=await vn(t)}catch(e){return{commands:r,reports:[{name:`(plugin sandbox)`,source:`installed`,status:`failed`,commands:[],error:e instanceof Error?e.message:String(e)}]}}for(let[e,o]of Object.entries(a.dependencies??{}).sort(([e],[t])=>e.localeCompare(t))){let a=On(o),s=n.supported[e];if(!s){i.push({name:e,source:a,status:`failed`,commands:[],error:`Command Pack "${e}" is not supported by ${t.binName}.`});continue}try{let n=await yn(t,e),o=await Dn(e,n,s,t),c=Object.keys(o).filter(e=>e in r);if(c.length>0)throw Error(`Command conflicts: ${c.join(`, `)}.`);Object.assign(r,o),i.push({name:e,version:n.version,source:a,status:`loaded`,commands:Object.keys(o).sort()})}catch(t){i.push({name:e,source:a,status:`failed`,commands:[],error:t instanceof Error?t.message:String(t)})}}return{commands:r,reports:i}}const An={name:`bailian-cli-command-packs`,private:!0,dependencies:{}},jn=new Set(`PATH.HOME.USER.LOGNAME.SHELL.TMPDIR.TEMP.TMP.LANG.TERM.NODE.NODE_PATH.NODE_OPTIONS.FORCE_COLOR.NO_COLOR.NPM_TOKEN.NODE_AUTH_TOKEN.HTTP_PROXY.HTTPS_PROXY.NO_PROXY.http_proxy.https_proxy.no_proxy.SystemRoot.ComSpec.APPDATA.PATHEXT`.split(`.`)),Mn=new Set([`registry`,`userconfig`,`globalconfig`,`cache`,`proxy`,`https_proxy`,`noproxy`,`strict_ssl`,`ca`,`cafile`]);function Nn(e){let t=/^(?:npm_config_|NPM_CONFIG_)(.+)$/.exec(e);return!!t&&Mn.has(t[1].toLowerCase())}function Pn(e,t){let n=Object.keys(t.supported);return n.length>0?`Allowed packages: ${n.join(`, `)}`:`${e.binName} does not currently support any Command Packs.`}function Fn(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(jn.has(n)||n.startsWith(`LC_`)||Nn(n))&&(t[n]=r);return t}async function In(e){await Re(e,{recursive:!0,mode:448});let t=N(e,`package.json`);Ie(t)||await We(t,`${JSON.stringify(An,null,2)}\n`,{mode:384})}async function Ln(e,t){if(Xe(`npm`,[`--version`],{encoding:`utf-8`}).status!==0){let e=se()?"Command Packs need a local npm. Install Node.js, or use `npm install -g bailian-cli` instead of the binary install.":`Install Node.js / npm and retry.`;throw new m(`npm is required to install, link, or remove Command Packs, but was not found on PATH.`,b.GENERAL,e)}await new Promise((n,r)=>{let i=Ye(`npm`,e,{cwd:t,env:Fn(),stdio:[`inherit`,`pipe`,`pipe`]});i.stdout.on(`data`,e=>process.stderr.write(e)),i.stderr.on(`data`,e=>process.stderr.write(e)),i.once(`error`,r),i.once(`close`,(t,i)=>{if(t===0){n();return}r(new m(`npm ${e[0]} failed${i?` with signal ${i}`:` with exit code ${t}`}.`,b.GENERAL))})})}async function Rn(e){let t=mn(e);await In(t);let n=N(t,`.lock`);for(let e=0;e<2;e++)try{let e=await ze(n,`wx`,384);return await e.writeFile(`${process.pid} ${Date.now()}\n`),await e.close(),async()=>{try{await Ue(n)}catch{}}}catch(e){if(e.code!==`EEXIST`)throw e;try{let e=await He(n);if(Date.now()-e.mtimeMs>6e5){await Ue(n);continue}}catch{continue}throw new m(`Another Command Pack install, link, or remove operation is already running.`,b.GENERAL,`Wait for it to finish and try again.`)}throw new m(`Could not acquire the Command Pack operation lock.`,b.GENERAL)}async function zn(e,t){let n=await Rn(e);try{return await t()}finally{await n()}}function Bn(e,t,n){let r=e.trim(),i=/^(@[^/\s]+\/[^@/\s]+)(?:@([a-zA-Z0-9][a-zA-Z0-9._-]*))?$/.exec(r);if(!i)throw new m(`Unsupported Command Pack package spec: "${e}".`,b.USAGE,`Use an allowlisted scoped package name with an optional version or tag.`);let a=i[1];if(!n.supported[a])throw new m(`Command Pack "${a}" is not allowlisted for ${t.binName}.`,b.USAGE,Pn(t,n));return{name:a,requested:r}}async function Vn(e,t,n,r){let i=r.supported[e],a=await bn(t);return{pjson:a,commands:await Dn(e,a,i,n,t)}}function Hn(e,t){return t.startsWith(`file:`)?t:`${e}@${t}`}async function Un(e,t,n){if(t){await Ln([`install`,Hn(e,t),`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],n);return}await Ln([`uninstall`,e,`--ignore-scripts`,`--no-fund`,`--no-audit`],n)}async function Wn(e,t,n){let{name:r,requested:i}=Bn(e,t,n);return zn(t,async()=>{let e=mn(t),a=(await vn(t)).dependencies?.[r];try{await Ln([`install`,i,`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],e);let a=await Vn(r,gn(t,r),t,n);if(!a.pjson.version)throw new m(`Command Pack "${r}" has no package version.`,b.USAGE);return{name:r,version:a.pjson.version,commands:Object.keys(a.commands).sort()}}catch(t){try{await Un(r,a,e)}catch{}throw t}})}async function Gn(e,t,n){let r=qe(e);if(!Ie(N(r,`package.json`)))throw new m(`Command Pack path does not exist: ${r}`,b.USAGE);let i=(await bn(r)).name;if(!i||!n.supported[i])throw new m(`Local package "${i??`(unnamed)`}" is not an allowlisted Command Pack for ${t.binName}.`,b.USAGE,Pn(t,n));let a=await Vn(i,r,t,n);return zn(t,async()=>{await Ln([`install`,`file:${r}`,`--save-exact`,`--ignore-scripts`,`--no-fund`,`--no-audit`],mn(t));let e=await Vn(i,gn(t,i),t,n);return{name:i,version:e.pjson.version??a.pjson.version,commands:Object.keys(e.commands).sort()}})}async function Kn(e,t,n){if(!n.supported[e])throw new m(`Command Pack "${e}" is not allowlisted for ${t.binName}.`,b.USAGE,Pn(t,n));if(!(e in((await vn(t)).dependencies??{})))throw new m(`Command Pack "${e}" is not installed.`,b.USAGE);await zn(t,()=>Ln([`uninstall`,e,`--ignore-scripts`,`--no-fund`,`--no-audit`],mn(t)))}async function qn(e,t){return(await kn({},e,t)).reports}function Jn(e,t){return{install:n=>Wn(n,e,t),link:n=>Gn(n,e,t),list:()=>qn(e,t),remove:n=>Kn(n,e,t)}}function Yn(e,t){let n={};for(let r of t)r in e&&(n[r]=e[r]);return n}function Xn(e){try{qt()}catch(t){z(t,e)}process.on(`SIGINT`,()=>{process.stderr.write(`
|
|
49
49
|
Interrupted. Exiting.
|
|
50
|
-
`),re(500).finally(()=>process.exit(130))}),process.stdout.on(`error`,e=>{if(e.code===`EPIPE`)process.exit(0);else throw e})}function Zn(e,t){let{binName:n,version:r,npmPackage:i,clientName:a}=t,o={binName:n,version:r,npmPackage:i,clientName:a},s=t.commandPacks??{supported:{}},c=Jn(o,s),l;Xn(n);let u=Bt([Ut,Ht,Vt,Wt]);function d(){return l||=kn(e,o,s).then(e=>new mt(e.commands,n)),l}function f(e,r,i){if(e.printHelp(r,process.stderr),r.length>0)return;let a=!1;try{let e=te(D(ct(i,{...x,...S,...g,...C})));a=!!(e.apiKey||e.console)}catch{}a?t.quickStartTasks?.length&&pn(t.quickStartTasks):fn(n)}async function p(e,t){let i=ht(t,e);switch(i.kind){case`version`:process.stdout.write(`${n} ${r}\n`);return;case`help`:f(e,i.path,t);return;case`usageError`:z(i.error,n);return;case`run`:try{let e=A(i.command),t=ct(i.rest,{...x,...e,...i.command.flags}),n=Yn(t,[...Object.keys(x),...Object.keys(e)]),r=Yn(t,Object.keys(i.command.flags??{})),a=i.command.validate?.(r);if(a)throw new w(a);let s=D(n),l=E(s);await u({identity:o,path:i.path,command:i.command,flags:r,settings:l,sources:s,configStore:le(s.configName),authStore:ce(s),commandPacks:c,client:new _({identity:o,settings:l,baseUrl:_e(s)})}),await re(1e3)}catch(t){if(t instanceof w&&i.rest.length===0){e.printHelp(i.path,process.stderr);return}await re(1e3),z(t,n)}return}}return{run(e=process.argv.slice(2)){return d().then(t=>p(t,e)).catch(e=>re(1e3).finally(()=>z(e,n)))}}}const Qn=`1.15.
|
|
50
|
+
`),re(500).finally(()=>process.exit(130))}),process.stdout.on(`error`,e=>{if(e.code===`EPIPE`)process.exit(0);else throw e})}function Zn(e,t){let{binName:n,version:r,npmPackage:i,clientName:a}=t,o={binName:n,version:r,npmPackage:i,clientName:a},s=t.commandPacks??{supported:{}},c=Jn(o,s),l;Xn(n);let u=Bt([Ut,Ht,Vt,Wt]);function d(){return l||=kn(e,o,s).then(e=>new mt(e.commands,n)),l}function f(e,r,i){if(e.printHelp(r,process.stderr),r.length>0)return;let a=!1;try{let e=te(D(ct(i,{...x,...S,...g,...C})));a=!!(e.apiKey||e.console)}catch{}a?t.quickStartTasks?.length&&pn(t.quickStartTasks):fn(n)}async function p(e,t){let i=ht(t,e);switch(i.kind){case`version`:process.stdout.write(`${n} ${r}\n`);return;case`help`:f(e,i.path,t);return;case`usageError`:z(i.error,n);return;case`run`:try{let e=A(i.command),t=ct(i.rest,{...x,...e,...i.command.flags}),n=Yn(t,[...Object.keys(x),...Object.keys(e)]),r=Yn(t,Object.keys(i.command.flags??{})),a=i.command.validate?.(r);if(a)throw new w(a);let s=D(n),l=E(s);await u({identity:o,path:i.path,command:i.command,flags:r,settings:l,sources:s,configStore:le(s.configName),authStore:ce(s),commandPacks:c,client:new _({identity:o,settings:l,baseUrl:_e(s)})}),await re(1e3)}catch(t){if(t instanceof w&&i.rest.length===0){e.printHelp(i.path,process.stderr);return}await re(1e3),z(t,n)}return}}return{run(e=process.argv.slice(2)){return d().then(t=>p(t,e)).catch(e=>re(1e3).finally(()=>z(e,n)))}}}const Qn=`1.15.1`;function $n(e,t){process.stdout.write(ie(e,t)+`
|
|
51
51
|
`)}function er(e){process.stdout.write(e+`
|
|
52
52
|
`)}function tr(e,t){!e||t||process.stderr.write(`request_id: ${e}\n`)}function nr(e,t,{gap:n=2}={}){let r=e.map((e,n)=>{let r=e.length;for(let e of t){let t=e[n]??``;t.length>r&&(r=t.length)}return r}),i=` `.repeat(n),a=e=>e.map((e,t)=>(e??``).padEnd(r[t])).join(i),o=[];o.push(a(e));for(let e of t)o.push(a(e));return o}function rr(e){return e>=11904&&e<=40959||e>=63744&&e<=64255||e>=65072&&e<=65103||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=131072&&e<=195103}function B(e){let t=0;for(let n of e){let e=n.codePointAt(0)??0;t+=rr(e)?2:1}return t}function ir(e,t){let n=t-B(e);return n>0?e+` `.repeat(n):e}const ar=` │ `,or=[0,150,160],sr=[176,205,250],cr=[160,160,170];function lr(e){if(`NO_COLOR`in process.env)return 0;let t=process.env.FORCE_COLOR;if(t!=null){if(t===`0`||t===`false`)return 0;if(t===`3`||t===`truecolor`)return 3;if(t===`2`)return 2;if(t===`1`||t===`true`||t===``)return 1}if(!ut(e))return 0;let n=process.env.COLORTERM;if(n===`truecolor`||n===`24bit`)return 3;let r=process.env.TERM??``;return r===`dumb`?1:/-256(color)?$/i.test(r)?2:1}function ur(e,t,n){return e===t&&t===n?e<8?16:e>248?231:232+Math.round((e-8)/247*24):16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)}function dr(e,t,n,r){let i=Math.max(e,t,n)>127,a=i?128:64;return(r===48?i?100:40:i?90:30)+(e>=a|(t>=a?2:0)|(n>=a?4:0))}function fr(e,t,n,r,i=38){return e>=3?`${i};2;${t};${n};${r}`:e===2?`${i};5;${ur(t,n,r)}`:String(dr(t,n,r,i))}function pr(e,[t,n,r],i){return e<=0?i:`\x1b[${fr(e,t,n,r)}m${i}\x1b[0m`}function mr(e,t,n){return t<=0?e:`\x1b[1;${fr(t,255,255,255,38)};${fr(t,n[0],n[1],n[2],48)}m${e}\x1b[0m`}function hr(e,t){let n=t-B(e);return n>0?` `.repeat(n)+e:e}function gr(e,t,n=20,r=process.stdout){return _r(e,t,n,lr(r))}function _r(e,t,n,r){let i=e==null?0:Math.max(0,Math.min(100,e)),a=e!=null,o=a?Math.round(i/100*n):0,s=``,c=``;for(let e=0;e<n;e++)a&&e<o?(s+=`█`,c+=pr(r,or,`█`)):(s+=` `,c+=` `);let l=a?sr:cr;return s+=` ${t}`,c+=` ${pr(r,l,t)}`,{plain:s,colored:c}}function vr(e){let t=lr(e.out??process.stdout),n=e.align??[],r=e.barColumns??[],i=e.headers.length,a={};for(let n of r){let r=n.width??20,i=[];for(let a=0;a<e.rows.length;a++){let e=n.percents[a]??null,o=n.labels?.[a]??(e==null?`-`:`${Number.isInteger(e)?e:e.toFixed(1)}%`);i.push(_r(e,o,r,t))}a[n.index]=i}let o=(t,n)=>a[n]?a[n][t].plain:e.rows[t][n]??``,s=e.headers.map((t,n)=>{let r=B(t);for(let t=0;t<e.rows.length;t++){let e=B(o(t,n));e>r&&(r=e)}return r}),c=[],l=e.headers.map((e,t)=>n[t]===`right`?hr(e,s[t]):ir(e,s[t])).join(ar),u=Math.max(B(l),...e.rows.map((e,t)=>B(Array.from({length:i},(e,n)=>o(t,n)).join(ar))));c.push(mr(` ${ir(l,u)} `,t,or));let d=` ${pr(t,or,`│`)} `;for(let t=0;t<e.rows.length;t++){let r=[];for(let o=0;o<i;o++){let i=s[o];if(a[o]){let e=a[o][t],n=i-B(e.plain);r.push(n>0?e.colored+` `.repeat(n):e.colored);continue}let c=e.rows[t][o]??``,l=e.cellColor?.(t,o,c),u=n[o]===`right`?hr(c,i):ir(c,i);l?r.push(n[o]===`right`?u.slice(0,u.length-c.length)+l:l+u.slice(c.length)):r.push(u)}let o=` `;for(let e=0;e<i;e++)o+=r[e],e<i-1&&(o+=d);c.push(o)}return c}const yr=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`];function br(e){let t=process.stderr.isTTY,n=0,r=null,i=e;return{start(){t&&(r=setInterval(()=>{process.stderr.write(`\r${yr[n%yr.length]} ${i}`),n++},80))},update(e){i=e},stop(e){r&&=(clearInterval(r),null),t&&(process.stderr.write(`\r\x1B[K`),e&&process.stderr.write(`${e}\n`))}}}function xr(e,t=``){let n=process.stderr.isTTY;return{update(r){if(!n)return;let i=Math.min(1,r/e),a=Math.round(30*i),o=30-a,s=`█`.repeat(a)+`░`.repeat(o),c=`${Math.round(i*100)}%`;process.stderr.write(`\r${t} ${s} ${c}`)},finish(){n&&process.stderr.write(`
|
|
53
53
|
`)}}}async function Sr(e,t,n){let r=Date.now()+n.timeoutSec*1e3,i=br(`Polling...`);t.quiet||i.start();try{for(;Date.now()<r;){let r=await e.requestJson({path:n.url});if(n.getStatus&&!t.quiet&&i.update(`Status: ${n.getStatus(r)}`),n.isComplete(r))return i.stop(`Done.`),r;if(n.isFailed(r)){i.stop(`Failed.`),t.verbose&&process.stderr.write(`[verbose] Task response: ${JSON.stringify(r,null,2)}\n`);let e=n.getErrorMessage?.(r);throw new m(e?`Task failed: ${e}`:`Task failed.`,b.GENERAL,e?void 0:`Use --verbose to see full API response details.`)}await new Promise(e=>setTimeout(e,n.intervalSec*1e3))}}finally{i.stop()}throw new m(`Polling timed out.`,b.TIMEOUT,`Try increasing --timeout or check task status manually.`)}async function Cr(e,t,n){let r=await fetch(e);if(!r.ok)throw new m(`Download failed: HTTP ${r.status}`,b.GENERAL);let i=Number(r.headers.get(`content-length`)||0),a=r.body?.getReader();if(!a)throw new m(`No response body`,b.GENERAL);Ae(De(t),{recursive:!0});let o=ke(t),s=i>0&&!n?.quiet?xr(i,`Downloading`):null,c=0,l=!1;try{let e=new Promise((e,t)=>{o.on(`error`,t)});for(;;){let{done:t,value:n}=await Promise.race([a.read(),e]);if(t)break;o.write(n)||await new Promise(e=>o.once(`drain`,()=>e())),c+=n.byteLength,s?.update(c)}l=!0}finally{if(a.releaseLock(),s?.finish(),await new Promise((e,t)=>{o.on(`finish`,e),o.on(`error`,t),o.end()}),!l)try{Me(t)}catch{}}return{size:c}}function wr(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Tr(e){return Math.max(1,e.concurrent??1)}async function Er(e,t,n,r=`requests`){if(e<=1)return[await n(0)];t.quiet||process.stderr.write(`[Concurrent: ${e} ${r}]\n`);let i=Array.from({length:e},(e,t)=>n(t));return Promise.all(i)}async function Dr(e,t,n){return Promise.all(e.map(({url:e,destPath:r})=>t(e,r,n).then(()=>r)))}const Or={"qwen-image-2.0":{"16:9":`2688*1536`,"9:16":`1536*2688`,"1:1":`2048*2048`,"4:3":`2368*1728`,"3:4":`1728*2368`},"qwen-image-fixed":{"16:9":`1664*928`,"4:3":`1472*1104`,"1:1":`1328*1328`,"3:4":`1104*1472`,"9:16":`928*1664`},wan27:{"16:9":`2688*1536`,"9:16":`1536*2688`,"1:1":`2048*2048`,"4:3":`2368*1728`,"3:4":`1728*2368`},"z-image":{"1:1":`1024*1024`,"16:9":`1280*720`,"9:16":`720*1280`,"4:3":`1152*864`,"3:4":`864*1152`,"3:2":`1248*832`,"2:3":`832*1248`},wan26:{"1:1":`1280*1280`,"16:9":`1696*960`,"9:16":`960*1696`,"4:3":`1472*1104`,"3:4":`1104*1472`},"wan-legacy":{"1:1":`1024*1024`,"16:9":`1280*720`,"9:16":`720*1280`,"3:4":`768*1152`,"4:3":`1152*768`},"wanx-v1":{"1:1":`1024*1024`,"9:16":`720*1280`,"3:4":`768*1152`,"16:9":`1280*720`},"wan25-i2i":{"1:1":`1280*1280`,"16:9":`1280*720`,"9:16":`720*1280`,"4:3":`1152*864`,"3:4":`864*1152`}};function kr(e,t){if(e)return Or[typeof t==`boolean`?t?`qwen-image-2.0`:`qwen-image-fixed`:t][e]??e}const Ar=`Enable watermark (true/false). Omit flag to use CLI default (true).`,jr=`Enable prompt extend (true/false). Omit flag to use CLI default (true).`,Mr=`Enable prompt extend (true/false). Omit flag: true for qwen-image sync; parameter omitted on async models (API default).`,Nr=`Enable prompt extend (true/false). Omit flag to omit the parameter (DashScope default).`;var V=class extends Error{code;step;details;constructor(e,t,n){super(t),this.name=`PipelineError`,this.code=e,this.step=n?.step,this.details=n?.details}toJSON(){return{code:this.code,message:this.message,...this.step?{step:this.step}:{},...this.details?{details:this.details}:{}}}};function Pr(e,t){return e instanceof V?e:new V(`step_execution_error`,e instanceof Error?e.message:String(e),{step:t})}var Fr=class{handlers=new Map;outputSchemas=new Map;registerStep(e,t,n){this.handlers.set(e,t),n&&this.outputSchemas.set(e,n)}executeStep(e,t,n){let r=this.handlers.get(e);if(!r)throw new V(`unknown_step`,`Unknown step type: ${e}`,{details:{available:this.listSteps()}});return r(t,n)}hasStep(e){return this.handlers.has(e)}listSteps(){return Array.from(this.handlers.keys()).sort()}getOutputSchema(e){return this.outputSchemas.get(e)}};const Ir=new Fr;function Lr(){return Ir}function Rr(e,t,n,r){let i,a;n instanceof Fr?(i=n,a=r):(i=Ir,a=n??r),i.registerStep(e,t,a)}function zr(){let e=D({}),t={...E(e),output:`json`,outputExplicit:!0,quiet:!0},n={binName:`bl`,version:`0.0.0-dev`,npmPackage:`bailian-cli`,clientName:`bailian-cli`},r;try{r=de(e)}catch{}return{client:new _({identity:n,settings:t,baseUrl:_e(e),apiCred:r}),settings:t}}const Br=[`download`,`out-dir`,`output`];function Vr(e){return e.startsWith(`./`)||e.startsWith(`../`)}function Hr(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))typeof a==`string`&&Vr(a)?(n[i]=qe(t,a),r.push(i)):n[i]=a;return{input:n,resolvedKeys:r}}async function Ur(e,t,n){let r=[];for(let i of t){let t=e[i];typeof t==`string`&&(await Le(t).then(()=>!0,()=>!1)||r.push(`Step "${n}" input "${i}" references file that does not exist: ${t}`))}return r}function Wr(e){if(e===void 0)return;if(typeof e==`number`)return Number.isFinite(e)&&e>0?e:void 0;let t=e.match(/^(\d+(?:\.\d+)?)(ms|s|m)?$/);if(!t)return;let n=Number(t[1]);if(!Number.isFinite(n)||n<=0)return;let r=t[2]??`s`;return r===`ms`?n/1e3:r===`m`?n*60:n}function H(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function U(e,t){if(Array.isArray(e)){e.forEach(e=>U(e,t));return}if(H(e)){`$from`in e&&typeof e.$from==`string`&&t.add(e.$from);for(let n of Object.values(e))U(n,t)}}async function Gr(e,t){let n=[];for(let r of e)for(let[e,i]of Object.entries(r.input)){if(Br.includes(e)||typeof i!=`string`||!Vr(i))continue;let a=qe(t,i);await Le(a).then(()=>!0,()=>!1)||n.push(`Step "${r.id}" input "${e}" references file that does not exist: ${a}`)}return n}async function Kr(e,t,n){if(!t.message)throw new V(`missing_input`,`text/chat requires 'message' input`,{step:`text/chat`});let r=t.model||`qwen3.8-max`,i=[];t.system&&i.push({role:`system`,content:t.system}),i.push({role:`user`,content:t.message});let a={model:r,messages:i,max_tokens:t[`max-tokens`]??4096,stream:!1};t.temperature!==void 0&&(a.temperature=t.temperature),t[`top-p`]!==void 0&&(a.top_p=t[`top-p`]),t[`enable-thinking`]&&(a.enable_thinking=!0,t[`thinking-budget`]!==void 0&&(a.thinking_budget=t[`thinking-budget`]));let o=O();return await e.client.requestJson({path:o,method:`POST`,body:a,timeout:n.blRequestTimeoutSeconds,signal:n.signal})}async function qr(e,t,n){let r=t.model||`qwen3-vl-plus`,i=Array.isArray(t.image)?t.image:t.image?[t.image]:[],a=t.video?`Describe the video.`:`Describe the image.`,o=t.prompt||a,s=[];if(t.video){let i=t.video;M(i)&&(i=await e.client.uploadFile(i,r,{signal:n.signal})),s.push({type:`video_url`,video_url:{url:i}})}for(let t of i){let i=t;M(t)&&(i=await e.client.uploadFile(t,r,{signal:n.signal})),s.push({type:`image_url`,image_url:{url:i}})}s.push({type:`text`,text:o});let c={model:r,messages:[{role:`user`,content:s}]},l=O();return await e.client.requestJson({path:l,method:`POST`,body:c,signal:n.signal})}async function Jr(e,t,n){if(!t.prompt)throw new V(`missing_input`,`image/generate requires 'prompt' input`,{step:`image/generate`});let r=t.model||`qwen-image-3.0`,i=ge(r),a=t.n??1,o=pe(t[`prompt-extend`],i.promptExtendDefault,`prompt-extend`),s={size:kr(t.size,i.sizeProfile),n:a,seed:t.seed,prompt_extend:o,watermark:ye(t.watermark)},c=i.inputStyle===`prompt`?{model:r,input:{prompt:t.prompt,negative_prompt:t[`negative-prompt`]||void 0},parameters:s}:{model:r,input:{messages:[{role:`user`,content:[{text:t.prompt}]}]},parameters:{...s,negative_prompt:t[`negative-prompt`]||void 0}};if(i.useSync){let r=await e.client.requestJson({path:i.path,method:`POST`,body:c,signal:n.signal}),a=r.output.choices.flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean),o=await Xr(a,t[`out-dir`],t[`out-prefix`]);return{urls:a,request_id:r.request_id,...o?{saved:o}:{}}}let l=(await e.client.requestJson({path:i.path,method:`POST`,body:c,async:!0,signal:n.signal})).output.task_id,u=await ti(e,l,n),d=await Xr(Array.isArray(u.urls)?u.urls:[],t[`out-dir`],t[`out-prefix`]);return d&&(u.saved=d),u}async function Yr(e,t,n){if(!t.prompt)throw new V(`missing_input`,`image/edit requires 'prompt' input`,{step:`image/edit`});let r=Array.isArray(t.image)?t.image:t.image?[t.image]:[],i=t.model||`qwen-image-3.0`,a=he(i),o=t.n??1,s=pe(t[`prompt-extend`],a.promptExtendDefault,`prompt-extend`),c=[];for(let t of r){let r=t;M(t)&&(r=await e.client.uploadFile(t,i,{signal:n.signal})),c.push(r)}let l={size:kr(t.size,a.sizeProfile),n:o,seed:t.seed,prompt_extend:s,watermark:ye(t.watermark)},u;if(a.inputStyle===`function-base-image`){let e=c[0];if(!e)throw new V(`missing_input`,`image/edit with wanx*-imageedit requires at least one image`,{step:`image/edit`});u={model:i,input:{function:t.function||`description_edit`,prompt:t.prompt,base_image_url:e},parameters:l}}else if(a.inputStyle===`prompt-images`)u={model:i,input:{prompt:t.prompt,images:c,negative_prompt:t[`negative-prompt`]||void 0},parameters:l};else{let e=c.map(e=>({image:e}));e.push({text:t.prompt}),u={model:i,input:{messages:[{role:`user`,content:e}]},parameters:{...l,negative_prompt:t[`negative-prompt`]||void 0}}}if(a.useSync){let r=await e.client.requestJson({path:a.path,method:`POST`,body:u,signal:n.signal}),i=r.output.choices.flatMap(e=>e.message?.content||[]).map(e=>e.image).filter(Boolean),o=await Xr(i,t[`out-dir`],t[`out-prefix`]);return{urls:i,request_id:r.request_id,...o?{saved:o}:{}}}let d=(await e.client.requestJson({path:a.path,method:`POST`,body:u,async:!0,signal:n.signal})).output.task_id,f=await ti(e,d,n),p=await Xr(Array.isArray(f.urls)?f.urls:[],t[`out-dir`],t[`out-prefix`]);return p&&(f.saved=p),f}async function Xr(e,t,n){if(!t||e.length===0)return;await Re(t,{recursive:!0});let r=n&&n.length>0?n:`image`,i=e.length===1?[{url:e[0],destPath:N(t,`${r}.png`)}]:e.map((e,n)=>({url:e,destPath:N(t,`${r}_${String(n+1).padStart(3,`0`)}.png`)})),a=[];for(let{url:e,destPath:t}of i)await Cr(e,t,{quiet:!0}),a.push(t);return a}async function Zr(e,t,n){if(!t.prompt)throw new V(`missing_input`,`video/generate requires 'prompt' input`,{step:`video/generate`});let r=t.model||(t.image?`happyhorse-1.1-i2v`:`happyhorse-1.1-t2v`),i;t.image&&(i=M(t.image)?await e.client.uploadFile(t.image,r,{signal:n.signal}):t.image);let a={model:r,input:{prompt:t.prompt,negative_prompt:t[`negative-prompt`]||void 0,...i?{media:[{type:`first_frame`,url:i}]}:{}},parameters:{resolution:t.resolution||void 0,ratio:t.ratio||void 0,duration:t.duration,prompt_extend:pe(t[`prompt-extend`],void 0,`prompt-extend`),watermark:ye(t.watermark),seed:t.seed}};Se(a.parameters);let o=Te(),s=(await e.client.requestJson({path:o,method:`POST`,body:a,async:!0,signal:n.signal})).output.task_id;return await ri(e,s,(t[`poll-interval`]??10)*1e3,(n.timeoutSeconds??900)*1e3,n)}async function Qr(e,t,n){let r=t.text;if(!r&&t[`text-file`]){let{readFileSync:e}=await import(`node:fs`);r=e(t[`text-file`],`utf-8`).trim()}if(!r)throw new V(`missing_input`,`speech/synthesize requires 'text' input`,{step:`speech/synthesize`});let i=t.model||`cosyvoice-v3-flash`,a={model:i,input:{text:r,voice:t.voice,format:t.format,sample_rate:t[`sample-rate`],volume:t.volume,rate:t.rate,pitch:t.pitch,seed:t.seed,language_hints:t.language?[t.language]:void 0,instruction:t.instruction,enable_ssml:t[`enable-ssml`]}};Se(a.input);let o=xe(),s=await e.client.requestJson({path:o,method:`POST`,body:a,signal:n.signal});return{audio_url:s.output.audio.url,url_expires_at:s.output.audio.expires_at,model:i,voice:t.voice,request_id:s.request_id}}async function $r(e,t,n){let r=Array.isArray(t.url)?t.url:t.url?[t.url]:[];if(r.length===0)throw new V(`missing_input`,`speech/recognize requires 'url' input`,{step:`speech/recognize`});let i=t.model||`fun-asr`,a=fe(i);if(a.kind===`unsupported`)throw new V(`invalid_input`,a.unsupportedReason??`Unsupported ASR model: ${i}`,{step:`speech/recognize`});if(a.kind===`sync-flash`){if(r.length!==1)throw new V(`invalid_input`,`Model "${i}" is a sync Flash ASR model and accepts exactly one url (got ${r.length})`,{step:`speech/recognize`});let e=[];if(t.diarization&&e.push(`diarization`),t[`speaker-count`]!==void 0&&e.push(`speaker-count`),a.flashFamily===`qwen3`&&t[`vocabulary-id`]!==void 0&&e.push(`vocabulary-id`),t[`channel-id`]!==void 0&&e.push(`channel-id`),e.length>0)throw new V(`invalid_input`,`Model "${i}" uses sync Flash ASR and does not support: ${e.join(`, `)}`,{step:`speech/recognize`})}if(a.kind===`async-filetrans`&&a.asyncInputStyle===`file_url`&&r.length!==1)throw new V(`invalid_input`,`Model "${i}" accepts exactly one url (got ${r.length})`,{step:`speech/recognize`});let o=[];for(let t of r)M(t)?o.push(await e.client.uploadFile(t,i,{signal:n.signal})):o.push(t);if(a.kind===`sync-flash`){let r=a.flashFamily,s=T({model:i,audioUrl:o[0],language:t.language,vocabularyId:t[`vocabulary-id`],flashFamily:r}),c=await e.client.requestJson({path:a.path,method:`POST`,headers:{"X-DashScope-SSE":`disable`},body:s,signal:n.signal});return{text:ne(c,r),model:i,mode:`sync`,raw:c}}let s=ee(a.asyncLanguageStyle??`language_hints`,t.language),c={model:i,input:a.asyncInputStyle===`file_url`?{file_url:o[0]}:{file_urls:o},parameters:{channel_id:t[`channel-id`]===void 0?void 0:[t[`channel-id`]],...s,diarization_enabled:t.diarization,speaker_count:t[`speaker-count`],vocabulary_id:t[`vocabulary-id`]}};Se(c.parameters);let l=(await e.client.requestJson({path:be(),method:`POST`,body:c,async:!0,signal:n.signal})).output.task_id,u=await ii(e,l,(t[`poll-interval`]??2)*1e3,(n.timeoutSeconds??300)*1e3,n),d=k(u.output),f={task_id:u.output.task_id,task_status:u.output.task_status,request_id:u.request_id,mode:`async`,model:i};if(u.output.results&&(f.results=u.output.results),u.output.result&&(f.result=u.output.result,typeof u.output.result.transcription_url==`string`&&(f.transcription_url=u.output.result.transcription_url)),u.output.task_metrics&&(f.task_metrics=u.output.task_metrics),u.usage&&(f.usage=u.usage),d.length===0)return f;let p=[],m=[];for(let e of d){if(!e.transcription_url)continue;let t=await fetch(e.transcription_url,{signal:n.signal});if(!t.ok)throw new V(`async_task_failed`,`Failed to download transcription: HTTP ${t.status}`,{step:`speech/recognize`,details:{taskId:l,url:e.transcription_url}});let r=await t.json();m.push(r);let i=r.transcripts;if(i?.length)for(let e of i)if(e.sentences?.length)for(let t of e.sentences)t.text&&p.push(t.text);else e.text&&p.push(e.text)}return{...f,text:p.join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bailian-cli-runtime",
|
|
3
|
-
"version": "1.15.
|
|
3
|
+
"version": "1.15.1",
|
|
4
4
|
"description": "Runtime framework for bailian-cli (createCli, registry, args, output, pipeline). See https://www.npmjs.com/package/bailian-cli for usage.",
|
|
5
5
|
"homepage": "https://bailian.console.aliyun.com/cli",
|
|
6
6
|
"bugs": {
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"boxen": "^8.0.1",
|
|
31
31
|
"chalk": "^5.6.2",
|
|
32
32
|
"undici": "^6.27.0",
|
|
33
|
-
"bailian-cli-core": "1.15.
|
|
33
|
+
"bailian-cli-core": "1.15.1"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@clack/prompts": "^0.7.0",
|