bailian-cli-core 1.13.0 → 1.13.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 +1 -1
package/dist/index.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import{createRequire as e}from"node:module";import{appendFileSync as t,createRea
|
|
|
4
4
|
`,c=o.join(`;`),l=e.queryString??``,u=[t,e.pathname,l,s,c,i].join(`
|
|
5
5
|
`),d=`ACS3-HMAC-SHA256`,f=`${d}\n${ut(u)}`,p=dt(e.accessKeySecret,f);return a.authorization=`${d} Credential=${e.accessKeyId},SignedHeaders=${c},Signature=${p}`,a}function lt(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function ut(e){return v(`sha256`).update(e,`utf8`).digest(`hex`)}function dt(e,t){return ee(`sha256`,e).update(t,`utf8`).digest(`hex`)}const ft=`${be.cn}/api/v1/uploads`;async function pt(e,t,n){let r=`${ft}?action=getPolicy&model=${encodeURIComponent(t)}`,i=xt(15e3,n),a=await fetch(r,{headers:{Authorization:`Bearer ${e}`,"Content-Type":`application/json`,...U()},signal:i.signal}).finally(i.cleanup);if(!a.ok){let e=await a.text().catch(()=>``);throw new A(`Failed to get upload policy (HTTP ${a.status}): ${e}`,k.GENERAL)}return(await a.json()).data}async function mt(e,t,n){let r=m(t),i=`${e.upload_dir}/${r}`,a=o(t),s=new FormData;s.append(`OSSAccessKeyId`,e.oss_access_key_id),s.append(`Signature`,e.signature),s.append(`policy`,e.policy),s.append(`x-oss-object-acl`,e.x_oss_object_acl),s.append(`x-oss-forbid-overwrite`,e.x_oss_forbid_overwrite),s.append(`key`,i),s.append(`success_action_status`,`200`),s.append(`file`,new Blob([a]),r);let c=xt(12e4,n),l=await fetch(e.upload_host,{method:`POST`,headers:{...U()},body:s,signal:c.signal}).finally(c.cleanup);if(!l.ok){let e=await l.text().catch(()=>``);throw new A(`Failed to upload file to OSS (HTTP ${l.status}): ${e}`,k.GENERAL)}return`oss://${i}`}const ht={".bmp":`image/bmp`,".heic":`image/heic`,".jpe":`image/jpeg`,".jpeg":`image/jpeg`,".jpg":`image/jpeg`,".png":`image/png`,".tif":`image/tiff`,".tiff":`image/tiff`,".webp":`image/webp`};function gt(e){if(!i(e))throw new A(`File not found: ${e}`,k.USAGE);if(!l(e).isFile())throw new A(`Not a file: ${e}`,k.USAGE);let t=h(e).toLowerCase(),n=ht[t];if(!n)throw new A(`Unsupported image format "${t||`unknown`}".`,k.USAGE,`Use an image file with a recognized extension.`);return`data:${n};base64,${o(e).toString(`base64`)}`}function _t(e){let t=/^data:([^;,]+);base64,/i.exec(e);return t?`data:${t[1]};base64,<omitted>`:e}async function vt(e){let{apiKey:t,model:n,filePath:r,signal:a}=e;if(!i(r))throw new A(`File not found: ${r}`,k.USAGE);if(!l(r).isFile())throw new A(`Not a file: ${r}`,k.USAGE);return mt(await pt(t,n,a),r,a)}function yt(e){return e.startsWith(`http://`)||e.startsWith(`https://`)||e.startsWith(`oss://`)||e.startsWith(`data:`)?!1:i(e)}async function bt(e,t,n,r={}){return yt(e)?vt({apiKey:t,model:n,filePath:e,signal:r.signal}):e}function xt(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),e),i=()=>n.abort(t?.reason),a=()=>{clearTimeout(r),t?.removeEventListener(`abort`,i)};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),n.signal.addEventListener(`abort`,a,{once:!0}),{signal:n.signal,cleanup:a}}function St(e){return`/api/v1/mcps/${e}/mcp`}var Ct=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new A(`This command needs a model-domain API key.`,k.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n={jsonrpc:`2.0`,id:this.nextId++,method:e,...t?{params:t}:{}},r=await(await this.send(n)).json();if(r.error)throw new A(`MCP error (${r.error.code}): ${r.error.message}`,k.GENERAL);return r.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...U()};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new A(e,k.GENERAL)}return r}};const wt={"cn-beijing":{domestic:{csGateway:`bailian-cs.console.aliyun.com`,action:`BroadScopeAspnGateway`},international:{csGateway:`bailian-cs.console.alibabacloud.com`,action:`BroadScopeAspnGateway`}},"ap-southeast-1":{domestic:{csGateway:`modelstudio-cs.console.aliyun.com`,action:`IntlBroadScopeAspnGateway`},international:{csGateway:`bailian-singapore-cs.alibabacloud.com`,action:`IntlBroadScopeAspnGateway`}}};function Tt(e,t){return wt[e]?.[t]??wt[`cn-beijing`][t]}function Et(e){let t=e.consoleRegion??`cn-beijing`,n=e.consoleSite??`domestic`,r=e.consoleSwitchAgent;return r==null?{consoleRegion:t,consoleSite:n}:{consoleRegion:t,consoleSite:n,consoleSwitchAgent:r}}function Dt(e,t,n){return JSON.stringify({Api:e,V:`1.0`,Data:{...t,cornerstoneParam:{protocol:`V2`,console:`ONE_CONSOLE`,productCode:`p_efm`,switchUserType:3,consoleSite:`BAILIAN_ALIYUN`,...n==null?{}:{switchAgent:n},...typeof t.cornerstoneParam==`object`&&t.cornerstoneParam!==null?t.cornerstoneParam:{}}}})}async function W(e,t,{api:n,data:r},i){let a=Tt(e.region,e.site),o=`https://${a.csGateway}`,s=a.action,c=Dt(n,r,e.switchAgent),l=new URLSearchParams({params:c,region:e.region}),u=t*1e3,d={Accept:`*/*`,"Content-Type":`application/x-www-form-urlencoded`};e.token&&(d.Authorization=`Bearer ${e.token}`);let f=`${o}/cli/api.json?action=${s}&product=sfm_bailian&api=${encodeURIComponent(n)}`;i?.verbose&&(process.stderr.write(`> POST ${f}\n`),process.stderr.write(`> payload ${JSON.stringify({params:JSON.parse(c),region:e.region},null,2)}\n`));let p=await fetch(f,{method:`POST`,headers:d,body:l.toString(),signal:AbortSignal.timeout(u)});if(i?.verbose&&process.stderr.write(`< ${p.status} ${p.statusText}\n`),!p.ok){let e=await p.text().catch(()=>``);throw new A(`Console CLI gateway failed: HTTP ${p.status} ${p.statusText}`,k.GENERAL,e.slice(0,500))}let m=await p.json(),h=m.data;if(h?.success===!1&&h.errorCode){let e=JSON.stringify(m),t=h.errorCode,n=typeof t==`string`?t:JSON.stringify(t),r=n.includes(`NotLogined`);throw new A(r?`Console session is not logged in or has expired.`:`Console gateway error: ${n}`,r?k.AUTH:k.GENERAL,r?"Run `bl auth login --console` to sign in or refresh your console session.":void 0,{rawResponse:e})}return m}var Ot=class{constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new A(`This command needs a model-domain API key.`,k.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new A(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,k.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}exportApiCredential(){return this.deps.apiCred}url(e){return this.baseUrl+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return it(this.http,this.toOpts(e))}requestJson(e){return ot(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return yt(e)?bt(e,this.requireApi().token,t,n):Promise.resolve(e)}resolveImageInput(e,t,n={}){return yt(e)?this.usesTokenPlanEndpoint()?Promise.resolve(gt(e)):this.uploadFile(e,t,{signal:n.signal}):Promise.resolve(e)}usesTokenPlanEndpoint(){if(this.deps.settings.configName===`token-plan`)return!0;try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Ct(this.http,t,this.deps.apiCred?.token)}async console(e,t){if(!this.deps.consoleCred)throw new A(`This command needs a console access token.`,k.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await W(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof A)||e.exitCode!==k.AUTH||!e.message.includes(`not logged in`))throw e;let t=await Nt({identity:this.deps.identity,settings:this.deps.settings,baseUrl:this.deps.baseUrl});if(!t)throw e;return await W({...this.deps.consoleCred,token:t},r,n,this.deps.settings)}}openApiQueryJson(e){return this.openApiJson(e)}async openApiJson(e){let t=this.requireOpenApi(),n=e.body===void 0?``:JSON.stringify(e.body),r=e.queryParams?st(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=ct({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${H(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${H(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await fetch(i,{method:e.method,headers:{...a,...U()},body:n||void 0,signal:AbortSignal.timeout(o)}),c=await s.text();this.deps.settings.verbose&&(process.stderr.write(`< ${s.status} ${s.statusText}\n`),process.stderr.write(`< ${c}\n`));let l;try{l=JSON.parse(c)}catch{throw new A(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,k.GENERAL)}if(!s.ok||l.Success===!1)throw new A(`${l.Code||s.status} - ${l.Message||s.statusText}`,k.GENERAL);return l}};const kt={cn:`modelstudio.cn-beijing.aliyuncs.com`,intl:`modelstudio.ap-southeast-1.aliyuncs.com`};function At(e){for(let[t,n]of Object.entries(be))if(e===n||e.startsWith(`${n}/`))return t;return`cn`}function jt(e){return kt[At(e)]??kt.cn}async function Mt(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Ot({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=jt(r);return s.openApiQueryJson({host:c,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}})}async function Nt(e){let t=e.settings.configName,n=B(t),r=n.access_key_id,i=n.access_key_secret;if(!r||!i)return null;e.settings.verbose&&process.stderr.write(`Refreshing access token...
|
|
6
6
|
`);let a=(await Mt({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i})).cliAccessToken;if(!a)return null;let o=B(t);return o.access_token=a,await V(o,t),a}function Pt(){return`/compatible-mode/v1/chat/completions`}function Ft(){return`/api/v1/services/aigc/image-generation/generation`}function It(){return`/api/v1/services/aigc/multimodal-generation/generation`}function Lt(){return`/api/v1/services/aigc/text2image/image-synthesis`}function Rt(){return`/api/v1/services/aigc/image2image/image-synthesis`}function zt(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function Bt(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function Vt(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function Ht(){return`/api/v2/apps/memory/add`}function Ut(){return`/api/v2/apps/memory/memory_nodes/search`}function Wt(){return`/api/v2/apps/memory/memory_nodes`}function Gt(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function Kt(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function qt(){return`/api/v1/services/audio/asr/transcription`}function Jt(){return`/api/v2/apps/memory/profile_schemas`}function Yt(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}/profiles`}function Xt(){return`/api/v1/indices/rag/index/retrieve`}function Zt(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v1/indices/knowledge/search`}function Qt(e){return`https://${e}.cn-beijing.maas.aliyuncs.com/api/v2/apps/knowledge/chat`}function $t(){return`/api/v1/mcps/WebSearch/mcp`}function en(){return`/compatible-mode/v1/files`}function tn(){return`/api/v1/files`}function nn(e){return`/api/v1/files/${encodeURIComponent(e)}`}function rn(){return`/api/v1/fine-tunes`}function an(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function on(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function sn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function cn(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function ln(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function un(){return`/api/v1/deployments`}function dn(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function fn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/scale`}function pn(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function mn(){return`/api/v1/deployments/models`}const hn=[`qwen-image`,`wan2.7-image`,`z-image`],gn=[`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function _n(e,t){return t.some(t=>e.startsWith(t))}function vn(e){return _n(e,hn)||e.startsWith(`wan2.6-image`)}function yn(e){return _n(e,hn)}function bn(e){return _n(e,gn)}function xn(e){return/^wanx-v1(?:-|$)/i.test(e)}function Sn(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||yn(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||xn(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function Cn(e){return/wan2\.5-i2i/i.test(e)}function wn(e){return/imageedit/i.test(e)}function Tn(e){return e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-edit`)?`qwen-image-2.0`:e.startsWith(`qwen-image`)?`qwen-image-fixed`:e.startsWith(`wan2.7-image`)?`wan27`:e.startsWith(`z-image`)?`z-image`:e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||e.startsWith(`wan2.5-t2i`)?`wan26`:xn(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:Sn(e)?`wan-legacy`:`wan26`}function En(e){if(e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function G(e,t){return{...e,sizeProfile:Tn(t),promptExtendDefault:En(t)}}function Dn(e){return yn(e)?G({kind:`sync-multimodal`,path:It(),useSync:!0,inputStyle:`messages`},e):Sn(e)?G({kind:`async-text2image`,path:Lt(),useSync:!1,inputStyle:`prompt`},e):G({kind:`async-image-generation`,path:Ft(),useSync:!1,inputStyle:`messages`},e)}function On(e){return bn(e)?G({kind:`sync-multimodal`,path:It(),useSync:!0,inputStyle:`messages`},e):wn(e)?G({kind:`async-image2image`,path:Rt(),useSync:!1,inputStyle:`function-base-image`},e):Cn(e)?G({kind:`async-image2image`,path:Rt(),useSync:!1,inputStyle:`prompt-images`},e):G({kind:`async-image-generation`,path:Ft(),useSync:!1,inputStyle:`messages`},e)}function kn(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function An(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function jn(e){return async(t,n={})=>{let r=An(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),kn(r))for(let[e,t]of Object.entries(U()))i.set(e,t);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${H(e.replace(/^Bearer /,``))}`)}let a=await fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const Mn=`2024-08-16`;function Nn(e){return`bailiancontrol.${e}.aliyuncs.com`}function Pn(e){return new Ot({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function Fn(e){return Pn(e).openApiJson({host:Nn(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Mn,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function In(e){return Pn(e).openApiJson({host:Nn(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Mn,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function Ln(e){return Pn(e).openApiJson({host:Nn(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Mn,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}async function*Rn(e){let t=e.body?.getReader();if(!t)return;let n=new TextDecoder,r=``,i=16*1024*1024;try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(r+=n.decode(a,{stream:!0}),r.length>i)throw new A(`SSE stream exceeded the maximum buffer size.`,k.GENERAL);let o=r.split(`
|
|
7
|
-
`);r=o.pop()||``;let s={};for(let e of o){if(e===``){s.data!==void 0&&(yield{data:s.data,event:s.event,id:s.id}),s={};continue}if(e.startsWith(`:`))continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t),r=e.slice(t+1).trimStart();switch(n){case`data`:if(s.data=s.data===void 0?r:`${s.data}\n${r}`,s.data.length>i)throw new A(`SSE event exceeded the maximum buffer size.`,k.GENERAL);break;case`event`:s.event=r;break;case`id`:s.id=r;break}}}if(r.trim()&&r.includes(`data:`)){let e=r.indexOf(`:`);e!==-1&&(yield{data:r.slice(e+1).trimStart()})}}finally{t.releaseLock()}}const zn=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Bn=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function Vn(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function Hn(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=Vn(await e(zn,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function Un(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=Vn(await e(zn,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function Wn(e,t){return(Vn(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const Gn=[`name`,`key`,`default`,`tip`,`range`];function Kn(e){return e.map(e=>{let t={};for(let n of Gn)e[n]!==void 0&&(t[n]=e[n]);return t})}async function qn(e,t){let n=Vn(await e(Bn,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Kn(e):null}catch{return null}return Array.isArray(n)?Kn(n):null}function Jn(e){return{read:()=>B(e),async write(t){let n=B(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?j(String(r)):r;await V(n,e)},async unset(t){let n=B(e);for(let e of t)delete n[e];await V(n,e)},profiles:()=>Ge(),activate:e=>Je(e),validateActivation:e=>qe(e),get path(){return F()}}}const Yn={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max-preview`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`}};function Xn(e){return e?Yn[e]:void 0}async function Zn(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=re.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:en(),method:`POST`,body:d,signal:a});if(f.id)return{file_id:f.id,name:f.filename??s,size:f.bytes??o.size,purpose:f.purpose??i,gmt_create:f.created_at?new Date(f.created_at*1e3).toISOString():void 0};let p=f.data?.failed_uploads;if(Array.isArray(p)&&p.length>0){let e=p[0]??{};throw new A(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,k.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new A(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,k.GENERAL,`The platform accepted the request but did not allocate a file_id. Retry the upload; if it recurs, contact platform support with the request id.`)}async function Qn(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=tn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function $n(e,t,n){return e.requestJson({path:nn(t),method:`GET`,signal:n})}async function er(e,t,n){let r=await e.request({path:nn(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const tr=300*1024*1024,nr=1024*1024*1024;function rr(e,t=tr){if(!i(e))throw new A(`File not found: ${e}`,k.USAGE);let n=l(e);if(!n.isFile())throw new A(`Not a regular file: ${e}`,k.USAGE);if(n.size===0)throw new A(`File is empty: ${e}`,k.USAGE);if(n.size>t)throw new A(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,k.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function K(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function ir(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`tts`||t===`image`||t===`video`)return t;throw new A(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,k.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function ar(e,t=50,n=100,r=10){if(e<=0)return[];if(e<=t+r)return Array.from({length:e},(e,t)=>t+1);let i=new Set;for(let n=1;n<=Math.min(t,e);n++)i.add(n);for(let t=0;t<r;t++)i.add(e-t);let a=Math.max(1,Math.ceil(e/n));for(let n=t+1;n<=e-r;n+=a)i.add(n);return[...i].filter(t=>t>=1&&t<=e).sort((e,t)=>e-t)}const or=new Set([`system`,`user`,`assistant`]);function sr(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(K(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role,o=i.content;return(typeof a!=`string`||!or.has(a))&&r.push(K(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant.`,{line:t,path:`${n}.role`})),typeof o!=`string`&&r.push(K(`error`,`INVALID_CONTENT`,`"content" must be a string (got ${typeof o}).`,{line:t,path:`${n}.content`})),r}function cr(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(K(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(K(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a;for(let e=0;e<r.length;e++){let o=r[e],s=`messages[${e}]`;n.push(...sr(o,t,s));let c=o?.role;c===`system`&&(e!==0&&n.push(K(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${s}.role`})),i=!0),a===c&&(c===`user`||c===`assistant`)&&n.push(K(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${c} messages — user/assistant turns should typically alternate.`,{line:t,path:`${s}.role`})),typeof c==`string`&&(a=c)}return r.some(e=>e.role===`user`)||n.push(K(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(K(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`})),n}const lr={name:`chatml`,detect:()=>!0,inspect:cr};function ur(e,t){let n=[];if(!(`text`in e))return n.push(K(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(K(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(K(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const dr={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:ur};function fr(e,t){let n=cr(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=`chosen`in e,a=`rejected`in e;if(i||n.push(K(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),a||n.push(K(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),i){n.push(...sr(e.chosen,t,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(K(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(a){n.push(...sr(e.rejected,t,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(K(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const pr={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:fr};function mr(e,t){let n=[];if(!(`wav_fn`in e))n.push(K(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(K(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(K(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(K(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(K(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(K(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(K(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(K(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const hr={name:`tts`,detect:e=>`wav_fn`in e,inspect:mr},gr=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`,`.tiff`]);function _r(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function vr(e){return/^[\x20-\x7E]+$/.test(e)}function yr(e,t){let n=[];if(!(`prompt`in e))n.push(K(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(K(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(K(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(K(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(K(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(K(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=_r(r);gr.has(e)||n.push(K(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...gr].join(`, `)}.`,{line:t,path:`img_path`})),vr(r)||n.push(K(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(K(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(K(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=_r(r);gr.has(e)||n.push(K(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...gr].join(`, `)}.`,{line:t,path:`input_img`})),vr(r)||n.push(K(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const br={name:`image`,detect:e=>`img_path`in e,inspect:yr},xr=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Sr=new Set([`.mp4`,`.mov`]);function Cr(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function wr(e){return/^[\x20-\x7E]+$/.test(e)}function Tr(e,t,n,r,i,a){if(!(n in t)){r&&e.push(K(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(K(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(K(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=Cr(o);i.has(s)||e.push(K(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),wr(o)||e.push(K(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Er(e,t){let n=[];if(!(`prompt`in e))n.push(K(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(K(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(K(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return Tr(n,e,`first_frame_path`,!0,xr,t),Tr(n,e,`last_frame_path`,!1,xr,t),Tr(n,e,`video_path`,!1,Sr,t),n}const Dr=[hr,br,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Er},pr,dr,lr];function Or(e,t){return t===void 0?Dr.find(t=>t.detect(e))??lr:Dr.find(e=>e.name===t)||lr}async function kr(e,t){let r=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0,o=0;for await(let e of r){if(t?.aborted)break;a++;let n=e.trim();if(n.length===0){o++;continue}i.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&i.push(K(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:a}))}return{totalLines:a,blankLines:o,issues:i}}async function Ar(e,t,r,i,a){let o=r?null:new Set(ar(t)),s=[],c=0,l=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),u=0;for await(let e of l){if(a?.aborted)break;if(u++,o&&!o.has(u))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(K(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...jr(n,u,i))}return{sampled:c,issues:s}}function jr(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[K(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Or(r,n).inspect(r,t)}const Mr={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await kr(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[K(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await Ar(e,r.totalLines,!!t.fullValidate,t.schema,t.signal),a=i.issues.filter(e=>e.severity===`error`),o=i.issues.filter(e=>e.severity===`warning`);return{valid:a.length===0,format:`jsonl`,filePath:e,errors:a,warnings:o,stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:i.sampled,durationMs:Date.now()-n}}}};function Nr(e,t){return new Promise((n,r)=>{ae.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function Pr(e){return new Promise((t,n)=>{ae.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}async function Fr(e,t,n){let{entry:i,zipfile:a}=await Nr(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??Error(`Failed to open entry stream`));return}ie(o,r(n)).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function Ir(e,t=100){let r=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0;for await(let e of r){if(a++,i.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&i.push(e.wav_fn),typeof e.img_path==`string`&&i.push(e.img_path),typeof e.input_img==`string`&&i.push(e.input_img),typeof e.first_frame_path==`string`&&i.push(e.first_frame_path),typeof e.last_frame_path==`string`&&i.push(e.last_frame_path),typeof e.video_path==`string`&&i.push(e.video_path),typeof e.image_fn==`string`&&i.push(e.image_fn),typeof e.video_fn==`string`&&i.push(e.video_fn)}catch{}}return{refs:i,totalLines:a}}const Lr={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await Pr(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[K(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[K(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`));s||r.push(K(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav) to their labels.`));let l=t.schema===`image`,u=t.schema===`video`,d=o.some(e=>e===`train/`||e.startsWith(`train/`)),f=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!d&&!l&&!u&&f&&i.push(K(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),l){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return gr.has(n)});e.length<25&&r.push(K(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let m=o.find(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`)),h=g(p(),`bl-zip-${te(6).toString(`hex`)}`);a(h,{recursive:!0});let _=g(h,`data.jsonl`);try{await Fr(e,m,_)}catch(t){return r.push(K(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(h,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let v=await Mr.validate(_,t);if(r.push(...v.errors),i.push(...v.warnings),v.valid){let{refs:e}=await Ir(_),t=new Set(o),n=m.lastIndexOf(`/`),i=n>=0?m.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(K(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(h,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:v.stats.totalRecords??o.length,sampledRecords:v.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Rr(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return zr(e);if(t===`.zip`)return Br(e);throw new A(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,k.USAGE)}async function zr(e){let t=await Hr(e);if(!t)throw new A(`JSONL file is empty or contains only blank lines: ${e}`,k.USAGE);let n=Vr(t);return n===`unknown`?`text`:n}async function Br(e){let t=await Ur(e,`data.jsonl`);if(!t)throw new A(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,k.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=Vr(t);if(n===`unknown`)throw new A(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,k.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function Vr(e){let t;try{t=JSON.parse(e)}catch{throw new A(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,k.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new A(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,k.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function Hr(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=y({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function Ur(e,t){return Nr(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new A(`Failed to read "${t}" from ZIP: ${e?.message}`,k.USAGE));return}let o=y({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const Wr=[Mr,Lr];function Gr(e){let t=h(e).toLowerCase(),n=Wr.find(e=>e.extensions.includes(t));if(!n){let e=Wr.flatMap(e=>e.extensions).join(`, `);throw new A(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,k.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function Kr(e){Wr.some(t=>t.format===e.format)||Wr.push(e)}async function q(e,t={}){let{bytes:n}=rr(e,t.maxBytes??314572800),r=await Gr(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function qr(){return Wr.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Jr(e){let t=[];e.line!==void 0&&t.push(`line ${e.line}`),e.path&&t.push(e.path);let n=t.length?` [${t.join(` · `)}]`:``;return` ${e.severity.toUpperCase()} ${e.code}${n}: ${e.message}`}async function Yr(e,t,n){return e.requestJson({path:rn(),method:`POST`,body:t,signal:n})}async function Xr(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status);let r=rn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Zr(e,t,n){return e.requestJson({path:an(t),method:`GET`,signal:n})}async function Qr(e,t,n){return e.requestJson({path:on(t),method:`POST`,signal:n})}async function $r(e,t,n){return e.requestJson({path:an(t),method:`DELETE`,signal:n})}async function ei(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize));let i=sn(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function ti(e,t,n){return e.requestJson({path:cn(t),method:`GET`,signal:n})}async function ni(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${ln(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const ri={sft:{server:`sft`,method:`sft`,variant:`full`},"sft-lora":{server:`efficient_sft`,method:`sft`,variant:`lora`},dpo:{server:`dpo_full`,method:`dpo`,variant:`full`},"dpo-lora":{server:`dpo_lora`,method:`dpo`,variant:`lora`},cpt:{server:`cpt`,method:`cpt`,variant:`full`}},ii=Object.keys(ri),ai=`sft-lora`;function oi(e){return e in ri}function si(e){let{method:t,variant:n}=ri[e];return{method:t,variant:n}}function ci(e,t){if(!e)return!1;let{method:n,variant:r}=ri[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function li(e){return e?ii.filter(t=>ci(e,t)):[]}async function ui(e,t){let n=Et(e);return(await Hn((t,r)=>W({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:t,data:r}),{name:t,pageSize:20})).models.find(e=>e.model===t)??null}const di=`INSUFFICIENT_SAMPLES`;function fi(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:di,message:`Training dataset has ${t} sample(s), which is not greater than batch_size (${n}).`},hint:[`The platform requires the number of training samples to exceed batch_size.`,`Options:`,` • add more data (recommended: comfortably more than batch_size, since the`,` platform also holds back a default 0.9 train split),`,` • lower --batch-size (server clamps to a minimum of 8).`].join(`
|
|
7
|
+
`);r=o.pop()||``;let s={};for(let e of o){if(e===``){s.data!==void 0&&(yield{data:s.data,event:s.event,id:s.id}),s={};continue}if(e.startsWith(`:`))continue;let t=e.indexOf(`:`);if(t===-1)continue;let n=e.slice(0,t),r=e.slice(t+1).trimStart();switch(n){case`data`:if(s.data=s.data===void 0?r:`${s.data}\n${r}`,s.data.length>i)throw new A(`SSE event exceeded the maximum buffer size.`,k.GENERAL);break;case`event`:s.event=r;break;case`id`:s.id=r;break}}}if(r.trim()&&r.includes(`data:`)){let e=r.indexOf(`:`);e!==-1&&(yield{data:r.slice(e+1).trimStart()})}}finally{t.releaseLock()}}const zn=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Bn=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function Vn(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function Hn(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=Vn(await e(zn,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function Un(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=Vn(await e(zn,{input:u}));return{total:d.total??0,groups:d.list??[]}}async function Wn(e,t){return(Vn(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const Gn=[`name`,`key`,`default`,`tip`,`range`];function Kn(e){return e.map(e=>{let t={};for(let n of Gn)e[n]!==void 0&&(t[n]=e[n]);return t})}async function qn(e,t){let n=Vn(await e(Bn,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?Kn(e):null}catch{return null}return Array.isArray(n)?Kn(n):null}function Jn(e){return{read:()=>B(e),async write(t){let n=B(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?j(String(r)):r;await V(n,e)},async unset(t){let n=B(e);for(let e of t)delete n[e];await V(n,e)},profiles:()=>Ge(),activate:e=>Je(e),validateActivation:e=>qe(e),get path(){return F()}}}const Yn={"token-plan":{baseUrl:`https://token-plan.cn-beijing.maas.aliyuncs.com`,defaultTextModel:`qwen3.8-max`,defaultVideoModel:`happyhorse-1.1-t2v`,defaultImageToVideoModel:`happyhorse-1.1-i2v`,defaultReferenceToVideoModel:`happyhorse-1.1-r2v`,defaultImageModel:`wan2.7-image`}};function Xn(e){return e?Yn[e]:void 0}async function Zn(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=re.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:en(),method:`POST`,body:d,signal:a});if(f.id)return{file_id:f.id,name:f.filename??s,size:f.bytes??o.size,purpose:f.purpose??i,gmt_create:f.created_at?new Date(f.created_at*1e3).toISOString():void 0};let p=f.data?.failed_uploads;if(Array.isArray(p)&&p.length>0){let e=p[0]??{};throw new A(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,k.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new A(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,k.GENERAL,`The platform accepted the request but did not allocate a file_id. Retry the upload; if it recurs, contact platform support with the request id.`)}async function Qn(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=tn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function $n(e,t,n){return e.requestJson({path:nn(t),method:`GET`,signal:n})}async function er(e,t,n){let r=await e.request({path:nn(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const tr=300*1024*1024,nr=1024*1024*1024;function rr(e,t=tr){if(!i(e))throw new A(`File not found: ${e}`,k.USAGE);let n=l(e);if(!n.isFile())throw new A(`Not a regular file: ${e}`,k.USAGE);if(n.size===0)throw new A(`File is empty: ${e}`,k.USAGE);if(n.size>t)throw new A(`File too large: ${(n.size/(1024*1024)).toFixed(1)}MB exceeds the ${(t/(1024*1024)).toFixed(0)}MB dataset upload cap.`,k.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function K(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function ir(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`tts`||t===`image`||t===`video`)return t;throw new A(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, tts, image.`,k.USAGE,`Omit --schema to auto-detect per record (chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, else ChatML).`)}function ar(e,t=50,n=100,r=10){if(e<=0)return[];if(e<=t+r)return Array.from({length:e},(e,t)=>t+1);let i=new Set;for(let n=1;n<=Math.min(t,e);n++)i.add(n);for(let t=0;t<r;t++)i.add(e-t);let a=Math.max(1,Math.ceil(e/n));for(let n=t+1;n<=e-r;n+=a)i.add(n);return[...i].filter(t=>t>=1&&t<=e).sort((e,t)=>e-t)}const or=new Set([`system`,`user`,`assistant`]);function sr(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(K(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role,o=i.content;return(typeof a!=`string`||!or.has(a))&&r.push(K(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant.`,{line:t,path:`${n}.role`})),typeof o!=`string`&&r.push(K(`error`,`INVALID_CONTENT`,`"content" must be a string (got ${typeof o}).`,{line:t,path:`${n}.content`})),r}function cr(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(K(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(K(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a;for(let e=0;e<r.length;e++){let o=r[e],s=`messages[${e}]`;n.push(...sr(o,t,s));let c=o?.role;c===`system`&&(e!==0&&n.push(K(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${s}.role`})),i=!0),a===c&&(c===`user`||c===`assistant`)&&n.push(K(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${c} messages — user/assistant turns should typically alternate.`,{line:t,path:`${s}.role`})),typeof c==`string`&&(a=c)}return r.some(e=>e.role===`user`)||n.push(K(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(K(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`})),n}const lr={name:`chatml`,detect:()=>!0,inspect:cr};function ur(e,t){let n=[];if(!(`text`in e))return n.push(K(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(K(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(K(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const dr={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:ur};function fr(e,t){let n=cr(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=`chosen`in e,a=`rejected`in e;if(i||n.push(K(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),a||n.push(K(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),i){n.push(...sr(e.chosen,t,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(K(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(a){n.push(...sr(e.rejected,t,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(K(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const pr={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:fr};function mr(e,t){let n=[];if(!(`wav_fn`in e))n.push(K(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(K(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(K(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(K(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(K(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(K(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(K(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(K(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const hr={name:`tts`,detect:e=>`wav_fn`in e,inspect:mr},gr=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`,`.tiff`]);function _r(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function vr(e){return/^[\x20-\x7E]+$/.test(e)}function yr(e,t){let n=[];if(!(`prompt`in e))n.push(K(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(K(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(K(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(K(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(K(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(K(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=_r(r);gr.has(e)||n.push(K(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...gr].join(`, `)}.`,{line:t,path:`img_path`})),vr(r)||n.push(K(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(K(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(K(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=_r(r);gr.has(e)||n.push(K(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...gr].join(`, `)}.`,{line:t,path:`input_img`})),vr(r)||n.push(K(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const br={name:`image`,detect:e=>`img_path`in e,inspect:yr},xr=new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),Sr=new Set([`.mp4`,`.mov`]);function Cr(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function wr(e){return/^[\x20-\x7E]+$/.test(e)}function Tr(e,t,n,r,i,a){if(!(n in t)){r&&e.push(K(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(K(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(K(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=Cr(o);i.has(s)||e.push(K(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),wr(o)||e.push(K(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function Er(e,t){let n=[];if(!(`prompt`in e))n.push(K(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(K(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(K(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return Tr(n,e,`first_frame_path`,!0,xr,t),Tr(n,e,`last_frame_path`,!1,xr,t),Tr(n,e,`video_path`,!1,Sr,t),n}const Dr=[hr,br,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:Er},pr,dr,lr];function Or(e,t){return t===void 0?Dr.find(t=>t.detect(e))??lr:Dr.find(e=>e.name===t)||lr}async function kr(e,t){let r=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0,o=0;for await(let e of r){if(t?.aborted)break;a++;let n=e.trim();if(n.length===0){o++;continue}i.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&i.push(K(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:a}))}return{totalLines:a,blankLines:o,issues:i}}async function Ar(e,t,r,i,a){let o=r?null:new Set(ar(t)),s=[],c=0,l=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),u=0;for await(let e of l){if(a?.aborted)break;if(u++,o&&!o.has(u))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(K(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:u}));continue}s.push(...jr(n,u,i))}return{sampled:c,issues:s}}function jr(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[K(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return Or(r,n).inspect(r,t)}const Mr={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await kr(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[K(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await Ar(e,r.totalLines,!!t.fullValidate,t.schema,t.signal),a=i.issues.filter(e=>e.severity===`error`),o=i.issues.filter(e=>e.severity===`warning`);return{valid:a.length===0,format:`jsonl`,filePath:e,errors:a,warnings:o,stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:i.sampled,durationMs:Date.now()-n}}}};function Nr(e,t){return new Promise((n,r)=>{ae.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function Pr(e){return new Promise((t,n)=>{ae.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}async function Fr(e,t,n){let{entry:i,zipfile:a}=await Nr(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??Error(`Failed to open entry stream`));return}ie(o,r(n)).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function Ir(e,t=100){let r=y({input:n(e,{encoding:`utf8`}),crlfDelay:1/0}),i=[],a=0;for await(let e of r){if(a++,i.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&i.push(e.wav_fn),typeof e.img_path==`string`&&i.push(e.img_path),typeof e.input_img==`string`&&i.push(e.input_img),typeof e.first_frame_path==`string`&&i.push(e.first_frame_path),typeof e.last_frame_path==`string`&&i.push(e.last_frame_path),typeof e.video_path==`string`&&i.push(e.video_path),typeof e.image_fn==`string`&&i.push(e.image_fn),typeof e.video_fn==`string`&&i.push(e.video_fn)}catch{}}return{refs:i,totalLines:a}}const Lr={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await Pr(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[K(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[K(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`));s||r.push(K(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav) to their labels.`));let l=t.schema===`image`,u=t.schema===`video`,d=o.some(e=>e===`train/`||e.startsWith(`train/`)),f=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!d&&!l&&!u&&f&&i.push(K(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),l){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return gr.has(n)});e.length<25&&r.push(K(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let m=o.find(e=>e===`data.jsonl`||e.endsWith(`/data.jsonl`)),h=g(p(),`bl-zip-${te(6).toString(`hex`)}`);a(h,{recursive:!0});let _=g(h,`data.jsonl`);try{await Fr(e,m,_)}catch(t){return r.push(K(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(h,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let v=await Mr.validate(_,t);if(r.push(...v.errors),i.push(...v.warnings),v.valid){let{refs:e}=await Ir(_),t=new Set(o),n=m.lastIndexOf(`/`),i=n>=0?m.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(K(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(h,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:v.stats.totalRecords??o.length,sampledRecords:v.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Rr(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return zr(e);if(t===`.zip`)return Br(e);throw new A(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,k.USAGE)}async function zr(e){let t=await Hr(e);if(!t)throw new A(`JSONL file is empty or contains only blank lines: ${e}`,k.USAGE);let n=Vr(t);return n===`unknown`?`text`:n}async function Br(e){let t=await Ur(e,`data.jsonl`);if(!t)throw new A(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,k.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=Vr(t);if(n===`unknown`)throw new A(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,k.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function Vr(e){let t;try{t=JSON.parse(e)}catch{throw new A(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,k.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new A(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,k.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function Hr(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=y({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function Ur(e,t){return Nr(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new A(`Failed to read "${t}" from ZIP: ${e?.message}`,k.USAGE));return}let o=y({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const Wr=[Mr,Lr];function Gr(e){let t=h(e).toLowerCase(),n=Wr.find(e=>e.extensions.includes(t));if(!n){let e=Wr.flatMap(e=>e.extensions).join(`, `);throw new A(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,k.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function Kr(e){Wr.some(t=>t.format===e.format)||Wr.push(e)}async function q(e,t={}){let{bytes:n}=rr(e,t.maxBytes??314572800),r=await Gr(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function qr(){return Wr.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Jr(e){let t=[];e.line!==void 0&&t.push(`line ${e.line}`),e.path&&t.push(e.path);let n=t.length?` [${t.join(` · `)}]`:``;return` ${e.severity.toUpperCase()} ${e.code}${n}: ${e.message}`}async function Yr(e,t,n){return e.requestJson({path:rn(),method:`POST`,body:t,signal:n})}async function Xr(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status);let r=rn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Zr(e,t,n){return e.requestJson({path:an(t),method:`GET`,signal:n})}async function Qr(e,t,n){return e.requestJson({path:on(t),method:`POST`,signal:n})}async function $r(e,t,n){return e.requestJson({path:an(t),method:`DELETE`,signal:n})}async function ei(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize));let i=sn(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function ti(e,t,n){return e.requestJson({path:cn(t),method:`GET`,signal:n})}async function ni(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${ln(t,n)}?${a.toString()}`,method:`GET`,signal:i})}const ri={sft:{server:`sft`,method:`sft`,variant:`full`},"sft-lora":{server:`efficient_sft`,method:`sft`,variant:`lora`},dpo:{server:`dpo_full`,method:`dpo`,variant:`full`},"dpo-lora":{server:`dpo_lora`,method:`dpo`,variant:`lora`},cpt:{server:`cpt`,method:`cpt`,variant:`full`}},ii=Object.keys(ri),ai=`sft-lora`;function oi(e){return e in ri}function si(e){let{method:t,variant:n}=ri[e];return{method:t,variant:n}}function ci(e,t){if(!e)return!1;let{method:n,variant:r}=ri[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function li(e){return e?ii.filter(t=>ci(e,t)):[]}async function ui(e,t){let n=Et(e);return(await Hn((t,r)=>W({region:n.consoleRegion,site:n.consoleSite,switchAgent:n.consoleSwitchAgent},e.timeout,{api:t,data:r}),{name:t,pageSize:20})).models.find(e=>e.model===t)??null}const di=`INSUFFICIENT_SAMPLES`;function fi(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:di,message:`Training dataset has ${t} sample(s), which is not greater than batch_size (${n}).`},hint:[`The platform requires the number of training samples to exceed batch_size.`,`Options:`,` • add more data (recommended: comfortably more than batch_size, since the`,` platform also holds back a default 0.9 train split),`,` • lower --batch-size (server clamps to a minimum of 8).`].join(`
|
|
8
8
|
`)}}function pi(e){let t={};if(t.n_epochs=e.nEpochs===void 0?3:e.nEpochs,e.learningRate!==void 0&&(t.learning_rate=e.learningRate),e.maxLength!==void 0&&(t.max_length=e.maxLength),e.batchSize!==void 0){let n=e.batchSize;n<8&&(n=8),n>1024&&(n=1024),t.batch_size=n}return t}function mi(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return q(e,{...r,schema:n})},resolveHyperParameters(e,t){return pi(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const hi=mi(`sft`,`sft`,`chatml`),gi={lm_max_epoch:60,lm_step:5,lm_num:3,lm_batch_size:1e3,fm_max_epoch:100,fm_step:10,fm_num:3,fm_batch_size:2e3},_i={learning_rate:`3e-5`,max_steps:800,eval_steps:200,max_token_length:`1k`,gradient_clip:.5,weight_decay:.02,max_pixels:`2k`,val_img_size:`2k`,generation_type:`t2i`,lora_rank:32,save_total_limit:10,split:.9},vi={..._i,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},yi={n_epochs:400,learning_rate:`2e-5`,split:.9,max_split_val_dataset_sample:5,eval_epochs:50,save_total_limit:10,lora_rank:32,lora_alpha:32};function bi(e){return e===`image`||e===`image-i2i`}function xi(e){return e===`video`||e===`video-kf2v`}function Si(e){return typeof e==`string`&&/wan2\.5/i.test(e)}const Ci=[hi,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return q(e,{...n,schema:`tts`});if(bi(t))return q(e,{...n,schema:`image`,maxBytes:nr});if(xi(t)){let r=await q(e,{...n,schema:`video`,maxBytes:nr});if(typeof n.model==`string`&&n.model.length>0){let e=/kf2v/i.test(n.model),i=t===`video-kf2v`;e&&!i?r.errors.push(K(`error`,`KF2V_DATA_MISMATCH`,`Model "${n.model}" is a first+last-frame (kf2v) model but the data has no "last_frame_path". kf2v training data must include a last frame per record.`)):!e&&i&&r.warnings.push(K(`warning`,`I2V_LAST_FRAME_IGNORED`,`Model "${n.model}" is a first-frame (i2v) model but the data includes "last_frame_path"; the last frame will be ignored during training.`))}return r.valid=r.errors.length===0,r}return q(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...gi};if(bi(e)){let n={...e===`image-i2i`?vi:_i};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(xi(e)){let e=Si(t.model),n={...yi,batch_size:4,max_pixels:e?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return pi(t)},shouldSkipGate(e,t){return!!((t===`audio`||bi(t)||xi(t))&&e===`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||bi(e)||xi(e)}},mi(`dpo`,`dpo_full`,`dpo`),mi(`dpo-lora`,`dpo_lora`,`dpo`),mi(`cpt`,`cpt`,`cpt`)];function wi(e){let t=Ci.find(t=>t.clientTrainingType===e);if(!t){let t=Ci.map(e=>e.clientTrainingType).join(`, `);throw new A(`Unknown training type "${e}".`,k.USAGE,`Supported training types: ${t}.`)}return t}function Ti(){return Ci.map(e=>e.clientTrainingType)}async function Ei(e,t,n){return e.requestJson({path:un(),method:`POST`,body:t,signal:n})}async function Di(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status);let r=un(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Oi(e,t,n){return e.requestJson({path:dn(t),method:`GET`,signal:n})}async function ki(e,t,n){return e.requestJson({path:dn(t),method:`DELETE`,signal:n})}async function Ai(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.version&&n.set(`version`,t.version),t.modelSource&&n.set(`model_source`,t.modelSource);let r=mn(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ji(e,t,n,r){return e.requestJson({path:fn(t),method:`PUT`,body:n,signal:r})}async function Mi(e,t,n,r){return e.requestJson({path:pn(t),method:`PUT`,body:n,signal:r})}const J={LORA:`lora`,PTU:`ptu`,MU:`mu`},Ni=J.LORA;function Pi(e){return e===`audio`?J.MU:Ni}const Fi={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},Ii=Fi.POST_PAY,Li={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`},Ri={name:J.LORA,validateFlags(){},async resolve(){return{body:{capacity:1}}}},zi={name:J.PTU,validateFlags(e){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm are required for plan=ptu.`},async resolve(e){let t={input_tpm:e.flags.inputTpm,output_tpm:e.flags.outputTpm};return e.flags.thinkingOutputTpm!==void 0&&(t.thinking_output_tpm=e.flags.thinkingOutputTpm),{body:{ptu_capacity:t}}}},Bi={name:J.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||Ii,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new A(`No mu-plan template found for model "${e.model}". Run \`${e.binName} deploy models --source base\` to inspect available models, or pass --deploy-spec explicitly.`,k.USAGE);try{let a=await Ai(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===J.MU)?.templates??[];if(o.length===0)throw i();let s=t===Fi.POST_PAY?Li.POST_PAID:Li.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof A?e:new A(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,k.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},Vi={[J.LORA]:Ri,[J.PTU]:zi,[J.MU]:Bi};function Hi(e){let t=Vi[e];if(!t)throw new A(`Unsupported plan "${e}". Supported plans: ${Object.keys(Vi).join(`, `)}.`,k.USAGE);return t}const Ui={output:{type:`string`,valueHint:`<format>`,description:`Output format: text, json`},timeout:{type:`number`,valueHint:`<seconds>`,description:`Request timeout`},quiet:{type:`switch`,description:`Suppress non-essential output`},verbose:{type:`switch`,description:`Print HTTP request/response details`},dryRun:{type:`switch`,description:`Dry run mode`},config:{type:`string`,valueHint:`<name>`,description:`Use a config profile for this command`},help:{type:`switch`,description:`Show help`},version:{type:`switch`,description:`Print version`}},Wi={concurrent:{type:`number`,valueHint:`<n>`,description:`Run N parallel requests (default: 1)`}},Gi={async:{type:`switch`,description:`Return async task id without waiting`}},Ki={apiKey:{type:`string`,valueHint:`<key>`,description:`API key`},baseUrl:{type:`string`,valueHint:`<url>`,description:`API base URL`}},qi={consoleRegion:{type:`string`,valueHint:`<region>`,description:`Console gateway region (e.g. cn-beijing, ap-southeast-1)`},consoleSite:{type:`string`,valueHint:`<site>`,description:`Console site: domestic, international`},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:`Switch agent UID for delegated access`},workspaceId:{type:`string`,valueHint:`<id>`,description:`Workspace ID (env: BAILIAN_WORKSPACE_ID)`}},Ji={accessKeyId:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`},accessKeySecret:{type:`string`,valueHint:`<key>`,description:`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`},securityToken:{type:`string`,valueHint:`<token>`,description:`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`}};function Yi(e){return e.auth===`apiKey`?Ki:e.auth===`console`?qi:e.auth===`openapi`?Ji:{}}function Xi(e){return e}const Zi=1;function Qi(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function $i(e,t){return`${Qi(e||`image`,`image`)}_${Qi((t||``).substring(0,20),`untitled`)}_${Date.now()}`}const ea=()=>g(f(),`bailian-output`);function ta(e,t){let n=t?.flagDir||e.outputDir||ea(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function na(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function ra(e){return o(e===`-`?0:e,`utf-8`)}function ia(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new A(`Invalid ${t} value "${String(e)}". Use true or false.`,k.USAGE)}function aa(e,t=`boolean`){if(e!=null)return ia(e,t)}function oa(e,t,n=`boolean`){let r=aa(e,n);return r===void 0?t:r}function sa(e){return aa(e,`watermark`)??!0}function ca(e){let t={command:e.command,timestamp:new Date().toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform};return e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function la(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function ua(e){let{command:t,params:n,...r}=e,i={et:`EXP`,ext:r,c1:n,c2:e.success?`success`:`failure`};return e.httpStatus!==void 0&&(i.c3=String(e.httpStatus)),e.errorMessage&&(i.c4=la(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let da;function fa(){return da||(process.env.NODE_ENV===`development`?(da=`dev`,da):(da=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,da))}var pa=me(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,`__esModule`,{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,`default`,{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=8)})([function(e,t){e.exports=he(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=he(`dns`)},function(e,t){e.exports=he(`util`)},function(e,t){e.exports=he(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},ee=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ne=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},C=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},se=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},fe=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},pe=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},me=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},D=new Map,O=new Map;D.set(`Baiduspider-render`,i),D.set(`Baiduspider+`,i),D.set(`Baiduspider-image+`,i),D.set(`360Spider`,a),D.set(`360Spider-Image`,a),D.set(`bingbot`,o),D.set(`Googlebot`,s),D.set(`YandexRenderResourcesBot`,c),D.set(`spider`,l),D.set(`Dataprovider.com`,u),D.set(`AhrefsBot`,d),D.set(`BitSightBot`,f),D.set(`oBot`,p),D.set(`Cincraw`,m),D.set(`DingTalkBot-LinkService`,h),D.set(`YisouSpider`,g),D.set(`Bytespider`,_),D.set(`ev-crawler`,v),D.set(`bitdiscovery`,ee),D.set(`Spider`,te),D.set(`Ai2Bot-Dolma`,ne),D.set(`dianjing_ad_spider`,re),O.set(`Baiduspider-render`,y),O.set(`Baiduspider+`,y),O.set(`Baiduspider-image+`,y),O.set(`360Spider`,ie),O.set(`360Spider-Image`,ie),O.set(`bingbot`,ae),O.set(`Googlebot`,b),O.set(`YandexRenderResourcesBot`,x),O.set(`spider`,S),O.set(`Dataprovider.com`,C),O.set(`AhrefsBot`,oe),O.set(`BitSightBot`,se),O.set(`oBot`,w),O.set(`Cincraw`,T),O.set(`DingTalkBot-LinkService`,ce),O.set(`YisouSpider`,le),O.set(`Bytespider`,ue),O.set(`ev-crawler`,de),O.set(`bitdiscovery`,fe),O.set(`Spider`,E),O.set(`Ai2Bot-Dolma`,pe),O.set(`dianjing_ad_spider`,me);let he={productHandlerMap:D,commentHandlerMap:O,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,he),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,`DEFAULT_MODEL_HANDLER_KEY`,{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,`createUAInfo`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,`runTask`,{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function ee(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:new Date().getTimezoneOffset()},e&&(this._config=c(this._config,e))}ee.prototype={constructor:ee,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||new Date().getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var te=ee,ne=n(3),re=n.n(ne),y=n(4),ie=n(5),ae=n.n(ie);function b(e){return(b=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e})(e)}function x(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function S(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?x(Object(n),!0).forEach(function(t){C(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):x(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function C(e,t,n){return(t=(function(e){var t=(function(e,t){if(b(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(b(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return b(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function oe(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=w(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
9
9
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function se(e,t){return(function(e){if(Array.isArray(e))return e})(e)||(function(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}})(e,t)||w(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
10
10
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function w(e,t){if(e){if(typeof e==`string`)return T(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?T(e,t):void 0}}function T(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ce(){for(var e=/(?:[0]{1,2}[:-]){5}[0]{1,2}/,t=i.a.networkInterfaces(),n=0,r=Object.entries(t);n<r.length;n++){var a=se(r[n],2),o=(a[0],a[1]);if(o){var s,c=oe(o);try{for(c.s();!(s=c.n()).done;){var l=s.value;if(!1===e.test(l.mac))return l.mac}}catch(e){c.e(e)}finally{c.f()}}}return`00:00:00:00:00:00`}var le,ue,de=(le=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:le,device_id:ae.a.createHash(`md5`).update(ce()).digest(`hex`),platform:`node`}),fe=(0,y.promisify)(re.a.resolve);function E(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,te.call(this,S(S({},de),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}E.prototype=((ue=function(){}).prototype=te.prototype,new ue),E.prototype.constructor=E,E.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,fe(t)).then(function(t){return n._offlineQueue.forEach(function(e){n.send(e)}),n._offlineQueue=[],n._print(`send`,e),o()(n._config.endpoint_url,{method:`POST`,keepalive:!0,body:JSON.stringify({gokey:encodeURIComponent(e),gmkey:`EXP`})}).catch(function(){})}).catch(function(t){n._offlineQueue.length>500&&n._offlineQueue.shift(),n._offlineQueue.push(e)})},t.default=E}]).default})),ma=me(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,`__esModule`,{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,`default`,{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=0)})([function(e,t,n){n.r(t);var r=[`ec`,`ea`,`el`,`et`],i=function(e,t){var n=function(e){var n=e.ec,r=e.ea,i=e.el,a=e.et,o=a===void 0?`CLK`:a,s=e.xpath;delete e.ec,delete e.ea,delete e.el,delete e.et,delete e.xpath,e.p1=n,e.p2=r,e.p3=i,e.p4=o,e.p5=s;try{t.log(`event`,e)}catch{}};return function(){var t=arguments,i={};if(t.length!==0){for(var a=0;a<t.length;a++){var o,s,c=t[a];if(a!==0&&typeof c==`object`&&a!==t.length-1)return void(e==null||(o=e.console)==null||(s=o.warn)==null||s.call(o,`Only the last argument can be object type`));if(typeof c==`string`||typeof c==`number`)i[r[a]]=c;else if(typeof c==`object`&&a===t.length-1)for(var l in c)c.hasOwnProperty(l)&&(i[l]=c[l])}n(i)}else{var u,d;(u=e.console)==null||(d=u.warn)==null||d.call(u,`At lease one augument`)}}};t.default=function(e,t){return i(global,e)}}]).default})),ha=O(pa(),1),ga=O(ma(),1);const _a=()=>g(P(),`telemetry.jsonl`);let va;const ya=new Set;let ba;try{let e=new ha.default({pid:`bailian-cli-node`,env:fa()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;ya.add(e),e.finally(()=>ya.delete(e))}return n},ba=e,va=e.use(ga.default)}catch{}async function xa(e=1e3){try{if(ba)try{typeof ba._sendAll==`function`&&ba._sendAll()}catch{}if(ya.size===0)return;let t=[...ya].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function Sa(e){try{await Fe();let n=_a();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
|
package/package.json
CHANGED