@douyin-minigame/cli 0.6.1 → 0.7.0
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/CHANGELOG.md +6 -0
- package/README.md +1 -1
- package/dist/cli.js +13 -13
- package/package.json +1 -1
- package/skills/douyin-minigame/SKILL.md +1 -1
- package/skills/douyin-minigame/references/parameters.md +32 -0
package/dist/cli.js
CHANGED
|
@@ -27,28 +27,28 @@ Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
|
|
|
27
27
|
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr("\n"),this.outputHelp({error:!0}));let r=t||{},i=r.exitCode||1,n=r.code||"commander.error";this._exit(i,n,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in k.env){let t=e.attributeName();(void 0===this.getOptionValue(t)||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,k.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new N(this.options),t=e=>void 0!==this.getOptionValue(e)&&!["default","implied"].includes(this.getOptionValueSource(e));this.options.filter(r=>void 0!==r.implied&&t(r.attributeName())&&e.valueFromOption(this.getOptionValue(r.attributeName()),r)).forEach(e=>{Object.keys(e.implied).filter(e=>!t(e)).forEach(t=>{this.setOptionValueWithSource(t,e.implied[t],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let r=e=>{let t=e.attributeName(),r=this.getOptionValue(t),i=this.options.find(e=>e.negate&&t===e.attributeName()),n=this.options.find(e=>!e.negate&&t===e.attributeName());return i&&(void 0===i.presetArg&&!1===r||void 0!==i.presetArg&&r===i.presetArg)?i:n||e},i=e=>{let t=r(e),i=t.attributeName();return"env"===this.getOptionValueSource(i)?`environment variable '${t.envVar}'`:`option '${t.flags}'`},n=`error: ${i(e)} cannot be used with ${i(t)}`;this.error(n,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],i=this;do{let e=i.createHelp().visibleOptions(i).filter(e=>e.long).map(e=>e.long);r=r.concat(e),i=i.parent}while(i&&!i._enablePositionalOptions);t=$(e,r)}let r=`error: unknown option '${e}'${t}`;this.error(r,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,r=e.length,i=this.parent?` for '${this.name()}'`:"",n=e.join(", "),u=`error: too many arguments${i}. Expected ${t} argument${1===t?"":"s"} but got ${r}: ${n}.`;this.error(u,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach(e=>{r.push(e.name()),e.alias()&&r.push(e.alias())}),t=$(e,r)}let r=`error: unknown command '${e}'${t}`;this.error(r,{code:"commander.unknownCommand"})}version(e,t,r){if(void 0===e)return this._version;this._version=e,t=t||"-V, --version",r=r||"output the version number";let i=this.createOption(t,r);return this._versionOptionName=i.attributeName(),this._registerOption(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
28
28
|
`),this._exit(0,"commander.version",e)}),this}description(e,t){return void 0===e&&void 0===t?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return void 0===e?this._summary:(this._summary=e,this)}alias(e){if(void 0===e)return this._aliases[0];let t=this;if(0!==this.commands.length&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw Error("Command alias can't be the same as its name");let r=this.parent?._findCommand(e);if(r){let t=[r.name()].concat(r.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${t}'`)}return t._aliases.push(e),this}aliases(e){return void 0===e?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(void 0===e){if(this._usage)return this._usage;let e=this.registeredArguments.map(e=>S(e));return[].concat(this.options.length||null!==this._helpOption?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=e,this}name(e){return void 0===e?this._name:(this._name=e,this)}helpGroup(e){return void 0===e?this._helpGroupHeading??"":(this._helpGroupHeading=e,this)}commandsGroup(e){return void 0===e?this._defaultCommandGroup??"":(this._defaultCommandGroup=e,this)}optionsGroup(e){return void 0===e?this._defaultOptionGroup??"":(this._defaultOptionGroup=e,this)}_initOptionGroup(e){this._defaultOptionGroup&&!e.helpGroupHeading&&e.helpGroup(this._defaultOptionGroup)}_initCommandGroup(e){this._defaultCommandGroup&&!e.helpGroup()&&e.helpGroup(this._defaultCommandGroup)}nameFromFilename(e){return this._name=I.basename(e,I.extname(e)),this}executableDir(e){return void 0===e?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp(),r=this._getOutputContext(e);t.prepareContext({error:r.error,helpWidth:r.helpWidth,outputHasColors:r.hasColors});let i=t.formatHelp(this,t);return r.hasColors?i:this._outputConfiguration.stripColor(i)}_getOutputContext(e){let t,r,i,n=!!(e=e||{}).error;return n?(t=e=>this._outputConfiguration.writeErr(e),r=this._outputConfiguration.getErrHasColors(),i=this._outputConfiguration.getErrHelpWidth()):(t=e=>this._outputConfiguration.writeOut(e),r=this._outputConfiguration.getOutHasColors(),i=this._outputConfiguration.getOutHelpWidth()),{error:n,write:e=>(r||(e=this._outputConfiguration.stripColor(e)),t(e)),hasColors:r,helpWidth:i}}outputHelp(e){let t;"function"==typeof e&&(t=e,e=void 0);let r=this._getOutputContext(e),i={error:r.error,write:r.write,command:this};this._getCommandAndAncestors().reverse().forEach(e=>e.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let n=this.helpInformation({error:r.error});if(t&&"string"!=typeof(n=t(n))&&!Buffer.isBuffer(n))throw Error("outputHelp callback must return a string or a Buffer");r.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(e=>e.emit("afterAllHelp",i))}helpOption(e,t){return"boolean"==typeof e?e?(null===this._helpOption&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null:(this._helpOption=this.createOption(e??"-h, --help",t??"display help for command"),(e||t)&&this._initOptionGroup(this._helpOption)),this}_getHelpOption(){return void 0===this._helpOption&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this._initOptionGroup(e),this}help(e){this.outputHelp(e);let t=Number(k.exitCode??0);0===t&&e&&"function"!=typeof e&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let r=["beforeAll","before","after","afterAll"];if(!r.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
29
29
|
Expecting one of '${r.join("', '")}'`);let i=`${e}Help`;return this.on(i,e=>{let r;(r="function"==typeof t?t({error:e.error,command:e.command}):t)&&e.write(`${r}
|
|
30
|
-
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function U(e){return e.map(e=>{let t,r;if(!e.startsWith("--inspect"))return e;let i="127.0.0.1",n="9229";return(null!==(r=e.match(/^(--inspect(-brk)?)$/))?t=r[1]:null!==(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))?(t=r[1],/^\d+$/.test(r[3])?n=r[3]:i=r[3]):null!==(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(t=r[1],i=r[3],n=r[4]),t&&"0"!==n)?`${t}=${i}:${parseInt(n)+1}`:e})}function q(){return!k.env.NO_COLOR&&"0"!==k.env.FORCE_COLOR&&"false"!==k.env.FORCE_COLOR&&(!!k.env.FORCE_COLOR||void 0!==k.env.CLICOLOR_FORCE||void 0)}new M;var V,H,z,G,W,J,Y,K,X,Q,Z,ee,et,er,ei,en,eu,eo,es,ea,el,ec,ed,ep,eh,ef,em,eg,eA,ey,eE,e_,eb,ev,eC,eD,eF,ew,eB,ex,eS,eT,eI,eO,ek,eR,eP,eL,eN,ej,e$,eM,eU,eq,eV,eH,ez,eG=((V={}).Timeout="HTTP_TIMEOUT",V.Aborted="HTTP_ABORTED",V.Network="HTTP_NETWORK",V.Status="HTTP_STATUS",V.InvalidJson="HTTP_INVALID_JSON",V.InvalidArgument="HTTP_INVALID_ARGUMENT",V);class eW extends l{url;status;responseBody;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="HttpError",this.url=t.url,this.status=t.status,this.responseBody=t.responseBody}}let eJ=Object.values(eG);function eY(e){return h(e,eJ)&&"string"==typeof e.url}function eK(e){if(!e)throw new l("接口无响应",{error:"EMPTY_RESPONSE",message:"接口未返回任何数据"});if(0!==e.error)throw new l("接口调用失败",{error:"API_ERROR",message:e.message||"接口调用失败",details:{error:e.error}});return e.data}async function eX(e,t={}){let r,i,n,u,o,{timeoutMs:s=3e4,signal:a,...l}=t;var c,d,p=s,h=e;if(!Number.isInteger(p)||p<=0)throw new eW("timeoutMs must be a positive integer",{code:eG.InvalidArgument,url:h});let f=(c=s,d=a??void 0,r=new AbortController,i=!1,n=!1,u=setTimeout(()=>{n=!0,r.abort()},c),o=()=>{i=!0,r.abort(d?.reason)},d&&(d.aborted?o():d.addEventListener("abort",o,{once:!0})),{signal:r.signal,cleanup(){clearTimeout(u),d&&d.removeEventListener("abort",o)},get aborted(){return i},get timedOut(){return n}});try{return await fetch(e,{...l,signal:f.signal})}catch(t){if(f.timedOut)throw new eW(`Request timed out after ${s}ms`,{cause:t,code:eG.Timeout,url:e});if(f.aborted)throw new eW("Request aborted",{cause:t,code:eG.Aborted,url:e});throw new eW("Network request failed",{cause:t,code:eG.Network,url:e})}finally{f.cleanup()}}function eQ(e,t,r){let i=typeof t;if("string"!==i&&"number"!==i&&"boolean"!==i)throw new eW(`Invalid query parameter value for "${e}": expected string, number or boolean`,{code:eG.InvalidArgument,url:r})}async function eZ(e){try{return await e.text()}catch{return}}async function e1(e,t){if(204===e.status)return;let r=await eZ(e)??"";if(0!==r.length)try{return JSON.parse(r)}catch(i){throw new eW("Failed to parse response as JSON",{cause:i,code:eG.InvalidJson,url:t,status:e.status,responseBody:r})}}let e2=async e=>{var t,r,i,n,u,o,s,a,l,c,d,p;let h,f,{request:m}=e,g=(h=function(e){let{url:t}=e;if(/^https?:\/\//i.test(t))return t;let r=e.baseURL?.replace(/\/+$/,"");if(!r)throw new eW("baseURL is required for relative request URLs",{code:eG.InvalidArgument,url:t});let i=t.startsWith("/")?t:`/${t}`;return`${r}${i}`}(t=m),f=function(e,t){if(!e)return"";let r=new URLSearchParams;for(let[i,n]of Object.entries(e))if(null!=n){if(Array.isArray(n)){for(let e of n)null!=e&&(eQ(i,e,t),r.append(i,String(e)));continue}eQ(i,n,t),r.append(i,String(n))}return r.toString()}(t.params,h),r=h,(i=f)?`${r}${r.includes("?")?"&":"?"}${i}`:r),A=(n=m,n.method?.toUpperCase()??(void 0!==n.data?"POST":"GET")),y=(u=m,"GET"!==(o=A)&&"HEAD"!==o&&void 0!==u.data),E=new Headers(function(e){if(!e)return;let t=Object.entries(e).flatMap(([e,t])=>"string"!=typeof t||""===t.trim()?[]:[[e,t]]);return t.length>0?Object.fromEntries(t):void 0}(m.headers)),b=function(e,t,r,i){if(r){var n;if("string"==typeof(n=e.data)||Buffer.isBuffer(n))return e.data;t.has("Content-Type")||t.set("Content-Type","application/json");try{return JSON.stringify(e.data)}catch(e){throw new eW("Failed to serialize request body as JSON",{cause:e,code:eG.InvalidArgument,url:i})}}}(m,E,y,g);(s=E).has("Accept")||s.set("Accept","application/json");let v=Math.max(0,m.retry?.maxRetries??0);for(let t=0;;t+=1)try{let t=await eX(g,{method:A,headers:E,...void 0!==m.timeoutMs?{timeoutMs:m.timeoutMs}:{},...m.signal?{signal:m.signal}:{},...void 0!==m.redirect?{redirect:m.redirect}:{},...void 0!==b?{body:b}:{}});if(e.response={status:t.status,headers:t.headers,logId:t.headers.get("X-Tt-Logid")??void 0},!e.unwrapData){e.response.data=t;return}if(!((a=t.status)>=200&&a<300)){let e=await eZ(t);throw new eW(`Request failed with status ${t.status}`,{code:eG.Status,url:g,status:t.status,responseBody:e})}e.response.data=await e1(t,g);return}catch(r){let e=t+1;if(!(e<=v&&(m.retry?.shouldRetry?.({request:m,attempt:e,error:r})??!((l={request:m,attempt:e,error:r}).error instanceof eW&&l.error.error===eG.Aborted))))throw r;await _((c=m.retry,d=e,p=r,Math.max(0,"function"==typeof c.retryDelayMs?c.retryDelayMs(d,p):c.retryDelayMs??0)))}};class e0{run;constructor(e={}){const t=[...e.middlewares??[],e2];this.run=function(e){return function(t,r){let i=-1;return function n(u){if(u<=i)return Promise.reject(Error("next() called multiple times in middleware"));i=u;let o=u===e.length?void 0:e[u];if(!o)return Promise.resolve(r());try{return Promise.resolve(o(t,()=>n(u+1)))}catch(e){return Promise.reject(e)}}(0)}}(t)}async send(e,t={}){let r={request:e,meta:{...t.meta??{}},unwrapData:t.unwrapData??!0};return await this.run(r,()=>Promise.resolve()),r.response??{}}}let e3="dymg",e6="@douyin-minigame/cli",e4="douyin-minigame",e8=`${e3}:oauth`,e9=`${e3} auth login`,e7=`${e9} --no-wait`,e5=`${e9} --resume`,te=`${e3} auth logout`,tt=(n=new s.AsyncLocalStorage,{run:(e,t)=>n.run({...e},t),update(e){let t=n.getStore();t&&Object.assign(t,e)},get:()=>n.getStore()});function tr(e){tt.update(e)}function ti(){return tt.get()}let tn=[],tu=async(e,t)=>{try{await t()}finally{tr({response:e.response})}},to=async(e,t)=>{let r=ti()?.appId?.trim(),i=e.request.headers?.X_Tt_Appid?.trim()||r;i&&(e.request.headers??={},e.request.headers["X-Tt-Appid"]=i),await t()};var ts=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArray.js"),ta=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isFinite.js"),tl=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isPlainObject.js"),tc=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isString.js");let td=require("node:crypto");__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObject.js"),require("node:http"),require("node:net");let tp=require("node:os"),th=require("node:fs/promises");class tf extends Error{constructor(e,t,r,...i){for(const n of(Array.isArray(t)&&(t=t.join(" ").trim()),super(t),void 0!==Error.captureStackTrace&&Error.captureStackTrace(this,tf),this.code=e,i))for(const e in n){const t=n[e];this[e]=Buffer.isBuffer(t)?t.toString(r.encoding):null==t?t:JSON.parse(JSON.stringify(t))}}}let tm=function(e){let t=[];for(let i=0,n=e.length;i<n;i++){let n=e[i];if(null==n||!1===n)t[i]={disabled:!0};else if("string"==typeof n||"number"==typeof n)t[i]={name:`${n}`};else{var r;if("object"!=typeof(r=n)||null===r||Array.isArray(r))throw new tf("CSV_INVALID_COLUMN_DEFINITION",["Invalid column definition:","expect a string or a literal object,",`got ${JSON.stringify(n)} at position ${i}`]);if("string"!=typeof n.name)throw new tf("CSV_OPTION_COLUMNS_MISSING_NAME",["Option columns missing name:",`property "name" is required at position ${i}`,"when column is an object literal"]);t[i]=n}}return t},tg=class{constructor(e=100){this.size=e,this.length=0,this.buf=Buffer.allocUnsafe(e)}prepend(e){if(Buffer.isBuffer(e)){let t=this.length+e.length;if(t>=this.size&&(this.resize(),t>=this.size))throw Error("INVALID_BUFFER_STATE");let r=this.buf;this.buf=Buffer.allocUnsafe(this.size),e.copy(this.buf,0),r.copy(this.buf,e.length),this.length+=e.length}else{let t=this.length++;t===this.size&&this.resize();let r=this.clone();this.buf[0]=e,r.copy(this.buf,1,0,t)}}append(e){let t=this.length++;t===this.size&&this.resize(),this.buf[t]=e}clone(){return Buffer.from(this.buf.slice(0,this.length))}resize(){let e=this.length;this.size=2*this.size;let t=Buffer.allocUnsafe(this.size);this.buf.copy(t,0,0,e),this.buf=t}toString(e){return e?this.buf.slice(0,this.length).toString(e):Uint8Array.prototype.slice.call(this.buf.slice(0,this.length))}toJSON(){return this.toString("utf8")}reset(){this.length=0}},tA=function(e){let t={};for(let r in e)t[r.replace(/([A-Z])/g,function(e,t){return"_"+t.toLowerCase()})]=e[r];if(void 0===t.encoding||!0===t.encoding)t.encoding="utf8";else if(null===t.encoding||!1===t.encoding)t.encoding=null;else if("string"!=typeof t.encoding&&null!==t.encoding)throw new tf("CSV_INVALID_OPTION_ENCODING",["Invalid option encoding:","encoding must be a string or null to return a buffer,",`got ${JSON.stringify(t.encoding)}`],t);if(void 0===t.bom||null===t.bom||!1===t.bom)t.bom=!1;else if(!0!==t.bom)throw new tf("CSV_INVALID_OPTION_BOM",["Invalid option bom:","bom must be true,",`got ${JSON.stringify(t.bom)}`],t);if(t.cast_function=null,void 0===t.cast||null===t.cast||!1===t.cast||""===t.cast)t.cast=void 0;else if("function"==typeof t.cast)t.cast_function=t.cast,t.cast=!0;else if(!0!==t.cast)throw new tf("CSV_INVALID_OPTION_CAST",["Invalid option cast:","cast must be true or a function,",`got ${JSON.stringify(t.cast)}`],t);if(void 0===t.cast_date||null===t.cast_date||!1===t.cast_date||""===t.cast_date)t.cast_date=!1;else if(!0===t.cast_date)t.cast_date=function(e){let t=Date.parse(e);return isNaN(t)?e:new Date(t)};else if("function"!=typeof t.cast_date)throw new tf("CSV_INVALID_OPTION_CAST_DATE",["Invalid option cast_date:","cast_date must be true or a function,",`got ${JSON.stringify(t.cast_date)}`],t);if(t.cast_first_line_to_header=void 0,!0===t.columns)t.cast_first_line_to_header=void 0;else if("function"==typeof t.columns)t.cast_first_line_to_header=t.columns,t.columns=!0;else if(Array.isArray(t.columns))t.columns=tm(t.columns);else if(void 0===t.columns||null===t.columns||!1===t.columns)t.columns=!1;else throw new tf("CSV_INVALID_OPTION_COLUMNS",["Invalid option columns:","expect an array, a function or true,",`got ${JSON.stringify(t.columns)}`],t);if(void 0===t.group_columns_by_name||null===t.group_columns_by_name||!1===t.group_columns_by_name)t.group_columns_by_name=!1;else if(!0!==t.group_columns_by_name)throw new tf("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",["Invalid option group_columns_by_name:","expect an boolean,",`got ${JSON.stringify(t.group_columns_by_name)}`],t);else if(!1===t.columns)throw new tf("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",["Invalid option group_columns_by_name:","the `columns` mode must be activated."],t);if(void 0===t.comment||null===t.comment||!1===t.comment||""===t.comment)t.comment=null;else if("string"==typeof t.comment&&(t.comment=Buffer.from(t.comment,t.encoding)),!Buffer.isBuffer(t.comment))throw new tf("CSV_INVALID_OPTION_COMMENT",["Invalid option comment:","comment must be a buffer or a string,",`got ${JSON.stringify(t.comment)}`],t);if(void 0===t.comment_no_infix||null===t.comment_no_infix||!1===t.comment_no_infix)t.comment_no_infix=!1;else if(!0!==t.comment_no_infix)throw new tf("CSV_INVALID_OPTION_COMMENT",["Invalid option comment_no_infix:","value must be a boolean,",`got ${JSON.stringify(t.comment_no_infix)}`],t);let r=JSON.stringify(t.delimiter);if(Array.isArray(t.delimiter)||(t.delimiter=[t.delimiter]),0===t.delimiter.length)throw new tf("CSV_INVALID_OPTION_DELIMITER",["Invalid option delimiter:","delimiter must be a non empty string or buffer or array of string|buffer,",`got ${r}`],t);if(t.delimiter=t.delimiter.map(function(e){if(null==e||!1===e)return Buffer.from(",",t.encoding);if("string"==typeof e&&(e=Buffer.from(e,t.encoding)),!Buffer.isBuffer(e)||0===e.length)throw new tf("CSV_INVALID_OPTION_DELIMITER",["Invalid option delimiter:","delimiter must be a non empty string or buffer or array of string|buffer,",`got ${r}`],t);return e}),void 0===t.escape||!0===t.escape?t.escape=Buffer.from('"',t.encoding):"string"==typeof t.escape?t.escape=Buffer.from(t.escape,t.encoding):(null===t.escape||!1===t.escape)&&(t.escape=null),null!==t.escape&&!Buffer.isBuffer(t.escape))throw Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(t.escape)}`);if(void 0===t.from||null===t.from)t.from=1;else if("string"==typeof t.from&&/\d+/.test(t.from)&&(t.from=parseInt(t.from)),Number.isInteger(t.from)){if(t.from<0)throw Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(e.from)}`)}else throw Error(`Invalid Option: from must be an integer, got ${JSON.stringify(t.from)}`);if(void 0===t.from_line||null===t.from_line)t.from_line=1;else if("string"==typeof t.from_line&&/\d+/.test(t.from_line)&&(t.from_line=parseInt(t.from_line)),Number.isInteger(t.from_line)){if(t.from_line<=0)throw Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(e.from_line)}`)}else throw Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(e.from_line)}`);if(void 0===t.ignore_last_delimiters||null===t.ignore_last_delimiters)t.ignore_last_delimiters=!1;else if("number"==typeof t.ignore_last_delimiters)t.ignore_last_delimiters=Math.floor(t.ignore_last_delimiters),0===t.ignore_last_delimiters&&(t.ignore_last_delimiters=!1);else if("boolean"!=typeof t.ignore_last_delimiters)throw new tf("CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS",["Invalid option `ignore_last_delimiters`:","the value must be a boolean value or an integer,",`got ${JSON.stringify(t.ignore_last_delimiters)}`],t);if(!0===t.ignore_last_delimiters&&!1===t.columns)throw new tf("CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS",["The option `ignore_last_delimiters`","requires the activation of the `columns` option"],t);if(void 0===t.info||null===t.info||!1===t.info)t.info=!1;else if(!0!==t.info)throw Error(`Invalid Option: info must be true, got ${JSON.stringify(t.info)}`);if(void 0===t.max_record_size||null===t.max_record_size||!1===t.max_record_size)t.max_record_size=0;else if(Number.isInteger(t.max_record_size)&&t.max_record_size>=0);else if("string"==typeof t.max_record_size&&/\d+/.test(t.max_record_size))t.max_record_size=parseInt(t.max_record_size);else throw Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(t.max_record_size)}`);if(void 0===t.objname||null===t.objname||!1===t.objname)t.objname=void 0;else if(Buffer.isBuffer(t.objname)){if(0===t.objname.length)throw Error("Invalid Option: objname must be a non empty buffer");null===t.encoding||(t.objname=t.objname.toString(t.encoding))}else if("string"==typeof t.objname){if(0===t.objname.length)throw Error("Invalid Option: objname must be a non empty string")}else if("number"==typeof t.objname);else throw Error(`Invalid Option: objname must be a string or a buffer, got ${t.objname}`);if(void 0!==t.objname){if("number"==typeof t.objname){if(!1!==t.columns)throw Error("Invalid Option: objname index cannot be combined with columns or be defined as a field")}else if(!1===t.columns)throw Error("Invalid Option: objname field must be combined with columns or be defined as an index")}if(void 0===t.on_record||null===t.on_record)t.on_record=void 0;else if("function"!=typeof t.on_record)throw new tf("CSV_INVALID_OPTION_ON_RECORD",["Invalid option `on_record`:","expect a function,",`got ${JSON.stringify(t.on_record)}`],t);if(void 0!==t.on_skip&&null!==t.on_skip&&"function"!=typeof t.on_skip)throw Error(`Invalid Option: on_skip must be a function, got ${JSON.stringify(t.on_skip)}`);if(null===t.quote||!1===t.quote||""===t.quote)t.quote=null;else if(void 0===t.quote||!0===t.quote?t.quote=Buffer.from('"',t.encoding):"string"==typeof t.quote&&(t.quote=Buffer.from(t.quote,t.encoding)),!Buffer.isBuffer(t.quote))throw Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(t.quote)}`);if(void 0===t.raw||null===t.raw||!1===t.raw)t.raw=!1;else if(!0!==t.raw)throw Error(`Invalid Option: raw must be true, got ${JSON.stringify(t.raw)}`);if(void 0===t.record_delimiter)t.record_delimiter=[];else if("string"==typeof t.record_delimiter||Buffer.isBuffer(t.record_delimiter)){if(0===t.record_delimiter.length)throw new tf("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a non empty string or buffer,",`got ${JSON.stringify(t.record_delimiter)}`],t);t.record_delimiter=[t.record_delimiter]}else if(!Array.isArray(t.record_delimiter))throw new tf("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a string, a buffer or array of string|buffer,",`got ${JSON.stringify(t.record_delimiter)}`],t);if(t.record_delimiter=t.record_delimiter.map(function(e,r){if("string"==typeof e||Buffer.isBuffer(e)){if(0===e.length)throw new tf("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a non empty string or buffer",`at index ${r},`,`got ${JSON.stringify(e)}`],t)}else throw new tf("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a string, a buffer or array of string|buffer",`at index ${r},`,`got ${JSON.stringify(e)}`],t);return"string"==typeof e&&(e=Buffer.from(e,t.encoding)),e}),"boolean"==typeof t.relax_column_count);else if(void 0===t.relax_column_count||null===t.relax_column_count)t.relax_column_count=!1;else throw Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(t.relax_column_count)}`);if("boolean"==typeof t.relax_column_count_less);else if(void 0===t.relax_column_count_less||null===t.relax_column_count_less)t.relax_column_count_less=!1;else throw Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(t.relax_column_count_less)}`);if("boolean"==typeof t.relax_column_count_more);else if(void 0===t.relax_column_count_more||null===t.relax_column_count_more)t.relax_column_count_more=!1;else throw Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(t.relax_column_count_more)}`);if("boolean"==typeof t.relax_quotes);else if(void 0===t.relax_quotes||null===t.relax_quotes)t.relax_quotes=!1;else throw Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(t.relax_quotes)}`);if("boolean"==typeof t.skip_empty_lines);else if(void 0===t.skip_empty_lines||null===t.skip_empty_lines)t.skip_empty_lines=!1;else throw Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(t.skip_empty_lines)}`);if("boolean"==typeof t.skip_records_with_empty_values);else if(void 0===t.skip_records_with_empty_values||null===t.skip_records_with_empty_values)t.skip_records_with_empty_values=!1;else throw Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(t.skip_records_with_empty_values)}`);if("boolean"==typeof t.skip_records_with_error);else if(void 0===t.skip_records_with_error||null===t.skip_records_with_error)t.skip_records_with_error=!1;else throw Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(t.skip_records_with_error)}`);if(void 0===t.rtrim||null===t.rtrim||!1===t.rtrim)t.rtrim=!1;else if(!0!==t.rtrim)throw Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(t.rtrim)}`);if(void 0===t.ltrim||null===t.ltrim||!1===t.ltrim)t.ltrim=!1;else if(!0!==t.ltrim)throw Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(t.ltrim)}`);if(void 0===t.trim||null===t.trim||!1===t.trim)t.trim=!1;else if(!0!==t.trim)throw Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(t.trim)}`);if(!0===t.trim&&!1!==e.ltrim?t.ltrim=!0:!0!==t.ltrim&&(t.ltrim=!1),!0===t.trim&&!1!==e.rtrim?t.rtrim=!0:!0!==t.rtrim&&(t.rtrim=!1),void 0===t.to||null===t.to)t.to=-1;else if(-1!==t.to)if("string"==typeof t.to&&/\d+/.test(t.to)&&(t.to=parseInt(t.to)),Number.isInteger(t.to)){if(t.to<=0)throw Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(e.to)}`)}else throw Error(`Invalid Option: to must be an integer, got ${JSON.stringify(e.to)}`);if(void 0===t.to_line||null===t.to_line)t.to_line=-1;else if(-1!==t.to_line)if("string"==typeof t.to_line&&/\d+/.test(t.to_line)&&(t.to_line=parseInt(t.to_line)),Number.isInteger(t.to_line)){if(t.to_line<=0)throw Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(e.to_line)}`)}else throw Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(e.to_line)}`);return t},ty=function(e){return e.every(e=>null==e||e.toString&&""===e.toString().trim())},tE={utf8:Buffer.from([239,187,191]),utf16le:Buffer.from([255,254])},t_=function(e={}){var t;let r=tA(e);return{info:{bytes:0,bytes_records:0,comment_lines:0,empty_lines:0,invalid_field_length:0,lines:1,records:0},original_options:e,options:r,state:{bomSkipped:!1,bufBytesStart:0,castField:(t=r).cast_function,commenting:!1,error:void 0,enabled:1===t.from_line,escaping:!1,escapeIsQuote:Buffer.isBuffer(t.escape)&&Buffer.isBuffer(t.quote)&&0===Buffer.compare(t.escape,t.quote),expectedRecordLength:Array.isArray(t.columns)?t.columns.length:void 0,field:new tg(20),firstLineToHeaders:t.cast_first_line_to_header,needMoreDataSize:Math.max(null!==t.comment?t.comment.length:0,...t.delimiter.map(e=>e.length),null!==t.quote?t.quote.length:0),previousBuf:void 0,quoting:!1,stop:!1,rawBuffer:new tg(100),record:[],recordHasError:!1,record_length:0,recordDelimiterMaxLength:0===t.record_delimiter.length?0:Math.max(...t.record_delimiter.map(e=>e.length)),trimChars:[Buffer.from(" ",t.encoding)[0],Buffer.from(" ",t.encoding)[0]],wasQuoting:!1,wasRowDelimiter:!1,timchars:[Buffer.from(Buffer.from([13],"utf8").toString(),t.encoding),Buffer.from(Buffer.from([10],"utf8").toString(),t.encoding),Buffer.from(Buffer.from([12],"utf8").toString(),t.encoding),Buffer.from(Buffer.from([32],"utf8").toString(),t.encoding),Buffer.from(Buffer.from([9],"utf8").toString(),t.encoding)]},__needMoreData:function(e,t,r){if(r)return!1;let{encoding:i,escape:n,quote:u}=this.options,{quoting:o,needMoreDataSize:s,recordDelimiterMaxLength:a}=this.state;return t-e-1<Math.max(s,0===a?Buffer.from("\r\n",i).length:a,o?(null===n?0:n.length)+u.length:0,o?u.length+a:0)},parse:function(e,t,r,i){let n,u,{bom:o,comment_no_infix:s,encoding:a,from_line:l,ltrim:c,max_record_size:d,raw:p,relax_quotes:h,rtrim:f,skip_empty_lines:m,to:g,to_line:A}=this.options,{comment:y,escape:E,quote:_,record_delimiter:b}=this.options,{bomSkipped:v,previousBuf:C,rawBuffer:D,escapeIsQuote:F}=this.state;if(void 0===C)if(void 0===e)return void i();else n=e;else n=void 0!==C&&void 0===e?C:Buffer.concat([C,e]);if(!1===v)if(!1===o)this.state.bomSkipped=!0;else if(n.length<3){if(!1===t){this.state.previousBuf=n;return}}else{for(let e in tE)if(0===tE[e].compare(n,0,tE[e].length)){let t=tE[e].length;this.state.bufBytesStart+=t,n=n.slice(t);let r=tA({...this.original_options,encoding:e});for(let e in r)this.options[e]=r[e];({comment:y,escape:E,quote:_}=this.options);break}this.state.bomSkipped=!0}let w=n.length;for(u=0;u<w&&!this.__needMoreData(u,w,t);u++){if(!0===this.state.wasRowDelimiter&&(this.info.lines++,this.state.wasRowDelimiter=!1),-1!==A&&this.info.lines>A){this.state.stop=!0,i();return}!1===this.state.quoting&&0===b.length&&this.__autoDiscoverRecordDelimiter(n,u)&&(b=this.options.record_delimiter);let e=n[u];if(!0===p&&D.append(e),(13===e||10===e)&&!1===this.state.wasRowDelimiter&&(this.state.wasRowDelimiter=!0),!0===this.state.escaping)this.state.escaping=!1;else{if(null!==E&&!0===this.state.quoting&&this.__isEscape(n,u,e)&&u+E.length<w)if(F){if(this.__isQuote(n,u+E.length)){this.state.escaping=!0,u+=E.length-1;continue}}else{this.state.escaping=!0,u+=E.length-1;continue}if(!1===this.state.commenting&&this.__isQuote(n,u))if(!0===this.state.quoting){let t=n[u+_.length],r=f&&this.__isCharTrimable(n,u+_.length),i=null!==y&&this.__compareBytes(y,n,u+_.length,t),o=this.__isDelimiter(n,u+_.length,t),s=0===b.length?this.__autoDiscoverRecordDelimiter(n,u+_.length):this.__isRecordDelimiter(t,n,u+_.length);if(null!==E&&this.__isEscape(n,u,e)&&this.__isQuote(n,u+E.length))u+=E.length-1;else if(!t||o||s||i||r){this.state.quoting=!1,this.state.wasQuoting=!0,u+=_.length-1;continue}else if(!1===h){let e=this.__error(new tf("CSV_INVALID_CLOSING_QUOTE",["Invalid Closing Quote:",`got "${String.fromCharCode(t)}"`,`at line ${this.info.lines}`,"instead of delimiter, record delimiter, trimable character","(if activated) or comment"],this.options,this.__infoField()));if(void 0!==e)return e}else this.state.quoting=!1,this.state.wasQuoting=!0,this.state.field.prepend(_),u+=_.length-1}else if(0!==this.state.field.length){if(!1===h){let e=this.__infoField(),t=Object.keys(tE).map(e=>!!tE[e].equals(this.state.field.toString())&&e).filter(Boolean)[0],r=this.__error(new tf("INVALID_OPENING_QUOTE",["Invalid Opening Quote:",`a quote is found on field ${JSON.stringify(e.column)} at line ${e.lines}, value is ${JSON.stringify(this.state.field.toString(a))}`,t?`(${t} bom)`:void 0],this.options,e,{field:this.state.field}));if(void 0!==r)return r}}else{this.state.quoting=!0,u+=_.length-1;continue}if(!1===this.state.quoting){let t=this.__isRecordDelimiter(e,n,u);if(0!==t){if(this.state.commenting&&!1===this.state.wasQuoting&&0===this.state.record.length&&0===this.state.field.length)this.info.comment_lines++;else{if(!1===this.state.enabled&&this.info.lines+ +(!0===this.state.wasRowDelimiter)>=l){this.state.enabled=!0,this.__resetField(),this.__resetRecord(),u+=t-1;continue}if(!0===m&&!1===this.state.wasQuoting&&0===this.state.record.length&&0===this.state.field.length){this.info.empty_lines++,u+=t-1;continue}this.info.bytes=this.state.bufBytesStart+u;let e=this.__onField();if(void 0!==e)return e;this.info.bytes=this.state.bufBytesStart+u+t;let n=this.__onRecord(r);if(void 0!==n)return n;if(-1!==g&&this.info.records>=g){this.state.stop=!0,i();return}}this.state.commenting=!1,u+=t-1;continue}if(this.state.commenting)continue;if(null!==y&&(!1===s||0===this.state.record.length&&0===this.state.field.length)&&0!==this.__compareBytes(y,n,u,e)){this.state.commenting=!0;continue}let o=this.__isDelimiter(n,u,e);if(0!==o){this.info.bytes=this.state.bufBytesStart+u;let e=this.__onField();if(void 0!==e)return e;u+=o-1;continue}}}if(!1===this.state.commenting&&0!==d&&this.state.record_length+this.state.field.length>d)return this.__error(new tf("CSV_MAX_RECORD_SIZE",["Max Record Size:","record exceed the maximum number of tolerated bytes",`of ${d}`,`at line ${this.info.lines}`],this.options,this.__infoField()));let t=!1===c||!0===this.state.quoting||0!==this.state.field.length||!this.__isCharTrimable(n,u),o=!1===f||!1===this.state.wasQuoting;if(!0===t&&!0===o)this.state.field.append(e);else{if(!0===f&&!this.__isCharTrimable(n,u))return this.__error(new tf("CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE",["Invalid Closing Quote:","found non trimable byte after quote",`at line ${this.info.lines}`],this.options,this.__infoField()));!1===t&&(u+=this.__isCharTrimable(n,u)-1);continue}}if(!0===t)if(!0===this.state.quoting){let e=this.__error(new tf("CSV_QUOTE_NOT_CLOSED",["Quote Not Closed:",`the parsing is finished with an opening quote at line ${this.info.lines}`],this.options,this.__infoField()));if(void 0!==e)return e}else if(!0===this.state.wasQuoting||0!==this.state.record.length||0!==this.state.field.length){this.info.bytes=this.state.bufBytesStart+u;let e=this.__onField();if(void 0!==e)return e;let t=this.__onRecord(r);if(void 0!==t)return t}else!0===this.state.wasRowDelimiter?this.info.empty_lines++:!0===this.state.commenting&&this.info.comment_lines++;else this.state.bufBytesStart+=u,this.state.previousBuf=n.slice(u);!0===this.state.wasRowDelimiter&&(this.info.lines++,this.state.wasRowDelimiter=!1)},__onRecord:function(e){let{columns:t,group_columns_by_name:r,encoding:i,info:n,from:u,relax_column_count:o,relax_column_count_less:s,relax_column_count_more:a,raw:l,skip_records_with_empty_values:c}=this.options,{enabled:d,record:p}=this.state;if(!1===d)return this.__resetRecord();let h=p.length;if(!0===t)return!0===c&&ty(p)?void this.__resetRecord():this.__firstLineToColumns(p);if(!1===t&&0===this.info.records&&(this.state.expectedRecordLength=h),h!==this.state.expectedRecordLength){let e=!1===t?new tf("CSV_RECORD_INCONSISTENT_FIELDS_LENGTH",["Invalid Record Length:",`expect ${this.state.expectedRecordLength},`,`got ${h} on line ${this.info.lines}`],this.options,this.__infoField(),{record:p}):new tf("CSV_RECORD_INCONSISTENT_COLUMNS",["Invalid Record Length:",`columns length is ${t.length},`,`got ${h} on line ${this.info.lines}`],this.options,this.__infoField(),{record:p});if(!0===o||!0===s&&h<this.state.expectedRecordLength||!0===a&&h>this.state.expectedRecordLength)this.info.invalid_field_length++,this.state.error=e;else{let t=this.__error(e);if(t)return t}}if(!0===c&&ty(p))return void this.__resetRecord();if(!0===this.state.recordHasError){this.__resetRecord(),this.state.recordHasError=!1;return}if(this.info.records++,1===u||this.info.records>=u){let{objname:u}=this.options;if(!1!==t){let o={};for(let e=0,i=p.length;e<i;e++)void 0===t[e]||t[e].disabled||(!0===r&&void 0!==o[t[e].name]?Array.isArray(o[t[e].name])?o[t[e].name]=o[t[e].name].concat(p[e]):o[t[e].name]=[o[t[e].name],p[e]]:o[t[e].name]=p[e]);if(!0===l||!0===n){let t=Object.assign({record:o},!0===l?{raw:this.state.rawBuffer.toString(i)}:{},!0===n?{info:this.__infoRecord()}:{}),r=this.__push(void 0===u?t:[o[u],t],e);if(r)return r}else{let t=this.__push(void 0===u?o:[o[u],o],e);if(t)return t}}else if(!0===l||!0===n){let t=Object.assign({record:p},!0===l?{raw:this.state.rawBuffer.toString(i)}:{},!0===n?{info:this.__infoRecord()}:{}),r=this.__push(void 0===u?t:[p[u],t],e);if(r)return r}else{let t=this.__push(void 0===u?p:[p[u],p],e);if(t)return t}}this.__resetRecord()},__firstLineToColumns:function(e){let{firstLineToHeaders:t}=this.state;try{let r=void 0===t?e:t.call(null,e);if(!Array.isArray(r))return this.__error(new tf("CSV_INVALID_COLUMN_MAPPING",["Invalid Column Mapping:","expect an array from column function,",`got ${JSON.stringify(r)}`],this.options,this.__infoField(),{headers:r}));let i=tm(r);this.state.expectedRecordLength=i.length,this.options.columns=i,this.__resetRecord();return}catch(e){return e}},__resetRecord:function(){!0===this.options.raw&&this.state.rawBuffer.reset(),this.state.error=void 0,this.state.record=[],this.state.record_length=0},__onField:function(){let{cast:e,encoding:t,rtrim:r,max_record_size:i}=this.options,{enabled:n,wasQuoting:u}=this.state;if(!1===n)return this.__resetField();let o=this.state.field.toString(t);if(!0===r&&!1===u&&(o=o.trimRight()),!0===e){let[e,t]=this.__cast(o);if(void 0!==e)return e;o=t}this.state.record.push(o),0!==i&&"string"==typeof o&&(this.state.record_length+=o.length),this.__resetField()},__resetField:function(){this.state.field.reset(),this.state.wasQuoting=!1},__push:function(e,t){let{on_record:r}=this.options;if(void 0!==r){let t=this.__infoRecord();try{e=r.call(null,e,t)}catch(e){return e}if(null==e)return}this.info.bytes_records+=this.info.bytes,t(e)},__cast:function(e){let{columns:t,relax_column_count:r}=this.options;if(!0===Array.isArray(t)&&r&&this.options.columns.length<=this.state.record.length)return[void 0,void 0];if(null!==this.state.castField)try{let t=this.__infoField();return[void 0,this.state.castField.call(null,e,t)]}catch(e){return[e]}if(this.__isFloat(e))return[void 0,parseFloat(e)];if(!1!==this.options.cast_date){let t=this.__infoField();return[void 0,this.options.cast_date.call(null,e,t)]}return[void 0,e]},__isCharTrimable:function(e,t){return((e,t)=>{let{timchars:r}=this.state;u:for(let i=0;i<r.length;i++){let n=r[i];for(let r=0;r<n.length;r++)if(n[r]!==e[t+r])continue u;return n.length}return 0})(e,t)},__isFloat:function(e){return e-parseFloat(e)+1>=0},__compareBytes:function(e,t,r,i){if(e[0]!==i)return 0;let n=e.length;for(let i=1;i<n;i++)if(e[i]!==t[r+i])return 0;return n},__isDelimiter:function(e,t,r){let{delimiter:i,ignore_last_delimiters:n}=this.options;if(!0===n&&this.state.record.length===this.options.columns.length-1||!1!==n&&"number"==typeof n&&this.state.record.length===n-1)return 0;u:for(let n=0;n<i.length;n++){let u=i[n];if(u[0]===r){for(let r=1;r<u.length;r++)if(u[r]!==e[t+r])continue u;return u.length}}return 0},__isRecordDelimiter:function(e,t,r){let{record_delimiter:i}=this.options,n=i.length;u:for(let u=0;u<n;u++){let n=i[u],o=n.length;if(n[0]===e){for(let e=1;e<o;e++)if(n[e]!==t[r+e])continue u;return n.length}}return 0},__isEscape:function(e,t,r){let{escape:i}=this.options;if(null===i)return!1;let n=i.length;if(i[0]===r){for(let r=0;r<n;r++)if(i[r]!==e[t+r])return!1;return!0}return!1},__isQuote:function(e,t){let{quote:r}=this.options;if(null===r)return!1;let i=r.length;for(let n=0;n<i;n++)if(r[n]!==e[t+n])return!1;return!0},__autoDiscoverRecordDelimiter:function(e,t){let{encoding:r}=this.options,i=[Buffer.from("\r\n",r),Buffer.from("\n",r),Buffer.from("\r",r)];o:for(let r=0;r<i.length;r++){let n=i[r].length;for(let u=0;u<n;u++)if(i[r][u]!==e[t+u])continue o;return this.options.record_delimiter.push(i[r]),this.state.recordDelimiterMaxLength=i[r].length,i[r].length}return 0},__error:function(e){let{encoding:t,raw:r,skip_records_with_error:i}=this.options,n="string"==typeof e?Error(e):e;if(!i)return n;if(this.state.recordHasError=!0,void 0!==this.options.on_skip)try{this.options.on_skip(n,r?this.state.rawBuffer.toString(t):void 0)}catch(e){return e}},__infoDataSet:function(){return{...this.info,columns:this.options.columns}},__infoRecord:function(){let{columns:e,raw:t,encoding:r}=this.options;return{...this.__infoDataSet(),bytes_records:this.info.bytes,error:this.state.error,header:!0===e,index:this.state.record.length,raw:t?this.state.rawBuffer.toString(r):void 0}},__infoField:function(){let{columns:e}=this.options,t=Array.isArray(e),r=this.info.bytes_records;return{...this.__infoRecord(),bytes_records:r,column:!0===t?e.length>this.state.record.length?e[this.state.record.length].name:null:this.state.record.length,quoting:this.state.wasQuoting}}}},tb=function(e,t={}){"string"==typeof e&&(e=Buffer.from(e));let r=t&&t.objname?{}:[],i=t_(t),n=i.parse(e,!0,e=>{void 0===i.options.objname?r.push(e):r[e[0]]=e[1]},()=>{});if(void 0!==n)throw n;return r},tv=/\\(\\)?/g,tC=RegExp("[^.[\\]]+|\\[(?:([^\"'][^[]*)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))","g"),tD=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,tF=/^\w*$/,tw=function(e){var t;let r=typeof e;return"symbol"===r||"object"===r&&e&&"[object Symbol]"===(t=e,Object.prototype.toString.call(t))},tB=function(e,t){if(Array.isArray(e))return!1;let r=typeof e;return!!("number"===r||"symbol"===r||"boolean"===r||!e||tw(e))||tF.test(e)||!tD.test(e)||null!=t&&e in Object(t)},tx=function(e){let t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(tC,function(e,r,i,n){let u=e;i?u=n.replace(tv,"$1"):r&&(u=r.trim()),t.push(u)}),t},tS=function(e){if("string"==typeof e||tw(e))return e;let t=`${e}`;return"0"==t&&1/e==-1/0?"-0":t},tT=function(e,t){var r,i;r=t,i=e;let n=0,u=(t=Array.isArray(r)?r:tB(r,i)?[r]:tx(r)).length;for(;null!=e&&n<u;)e=e[tS(t[n++])];return n&&n===u?e:void 0},tI=function(e){if(null==e)return[void 0,void 0];if("object"!=typeof e)return[Error('Invalid option "columns": expect an array or an object')];if(Array.isArray(e)){let t=[];for(let r of e)if("string"==typeof r)t.push({key:r,header:r});else{if("object"!=typeof r||null===r||Array.isArray(r))return[Error("Invalid column definition: expect a string or an object")];if(!r.key)return[Error('Invalid column definition: property "key" is required')];void 0===r.header&&(r.header=r.key),t.push(r)}e=t}else{let t=[];for(let r in e)t.push({key:r,header:e[r]});e=t}return[void 0,e]};class tO extends Error{constructor(e,t,...r){for(const i of(Array.isArray(t)&&(t=t.join(" ")),super(t),void 0!==Error.captureStackTrace&&Error.captureStackTrace(this,tO),this.code=e,r))for(const e in i){const t=i[e];this[e]=Buffer.isBuffer(t)?t.toString():null==t?t:JSON.parse(JSON.stringify(t))}}}let tk=function(e){let t={};for(let r in e)t[r.replace(/([A-Z])/g,function(e,t){return"_"+t.toLowerCase()})]=e[r];if(void 0===t.bom||null===t.bom||!1===t.bom)t.bom=!1;else if(!0!==t.bom)return[new tO("CSV_OPTION_BOOLEAN_INVALID_TYPE",["option `bom` is optional and must be a boolean value,",`got ${JSON.stringify(t.bom)}`])];if(void 0===t.delimiter||null===t.delimiter)t.delimiter=",";else if(Buffer.isBuffer(t.delimiter))t.delimiter=t.delimiter.toString();else if("string"!=typeof t.delimiter)return[new tO("CSV_OPTION_DELIMITER_INVALID_TYPE",["option `delimiter` must be a buffer or a string,",`got ${JSON.stringify(t.delimiter)}`])];if(void 0===t.quote||null===t.quote)t.quote='"';else if(!0===t.quote)t.quote='"';else if(!1===t.quote)t.quote="";else if(Buffer.isBuffer(t.quote))t.quote=t.quote.toString();else if("string"!=typeof t.quote)return[new tO("CSV_OPTION_QUOTE_INVALID_TYPE",["option `quote` must be a boolean, a buffer or a string,",`got ${JSON.stringify(t.quote)}`])];if((void 0===t.quoted||null===t.quoted)&&(t.quoted=!1),void 0===t.escape_formulas||null===t.escape_formulas)t.escape_formulas=!1;else if("boolean"!=typeof t.escape_formulas)return[new tO("CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE",["option `escape_formulas` must be a boolean,",`got ${JSON.stringify(t.escape_formulas)}`])];if((void 0===t.quoted_empty||null===t.quoted_empty)&&(t.quoted_empty=void 0),void 0===t.quoted_match||null===t.quoted_match||!1===t.quoted_match?t.quoted_match=null:Array.isArray(t.quoted_match)||(t.quoted_match=[t.quoted_match]),t.quoted_match)for(let e of t.quoted_match){let r="string"==typeof e,i=e instanceof RegExp;if(!r&&!i)return[new tO("CSV_OPTION_QUOTED_MATCH",["option `quoted_match` must be a string or a regex,",`got ${JSON.stringify(t.quoted_match)}`])]}if((void 0===t.quoted_string||null===t.quoted_string)&&(t.quoted_string=!1),(void 0===t.eof||null===t.eof)&&(t.eof=!0),void 0===t.escape||null===t.escape)t.escape='"';else if(Buffer.isBuffer(t.escape))t.escape=t.escape.toString();else if("string"!=typeof t.escape)return[Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(t.escape)}`)];if(t.escape.length>1)return[Error(`Invalid Option: escape must be one character, got ${t.escape.length} characters`)];if(void 0===t.header||null===t.header||!1===t.header)t.header=!1;else if(!0!==t.header)throw new tO("CSV_INVALID_OPTION_HEADER",["option `header` is expected to be a boolean,",`got ${JSON.stringify(t.header)}`],t);if(void 0===t.header_as_comment||null===t.header_as_comment||!1===t.header_as_comment)t.header_as_comment=!1;else if(!0===t.header_as_comment)t.header_as_comment="#";else if(Buffer.isBuffer(t.header_as_comment))t.header_as_comment=t.header_as_comment.toString();else if("string"!=typeof t.header_as_comment)throw new tO("CSV_INVALID_OPTION_HEADER_AS_COMMENT",["option `header_as_comment` must be a boolean, a string or a buffer,",`got ${JSON.stringify(t.header_as_comment)}`],t);let[r,i]=tI(t.columns);if(void 0!==r)return[r];if(t.columns=i,(void 0===t.quoted||null===t.quoted)&&(t.quoted=!1),(void 0===t.cast||null===t.cast)&&(t.cast={}),(void 0===t.cast.bigint||null===t.cast.bigint)&&(t.cast.bigint=e=>""+e),(void 0===t.cast.boolean||null===t.cast.boolean)&&(t.cast.boolean=e=>e?"1":""),(void 0===t.cast.date||null===t.cast.date)&&(t.cast.date=e=>""+e.getTime()),(void 0===t.cast.number||null===t.cast.number)&&(t.cast.number=e=>""+e),(void 0===t.cast.object||null===t.cast.object)&&(t.cast.object=e=>JSON.stringify(e)),(void 0===t.cast.string||null===t.cast.string)&&(t.cast.string=function(e){return e}),void 0!==t.on_record&&"function"!=typeof t.on_record)return[Error('Invalid Option: "on_record" must be a function.')];if(void 0===t.record_delimiter||null===t.record_delimiter)t.record_delimiter="\n";else if(Buffer.isBuffer(t.record_delimiter))t.record_delimiter=t.record_delimiter.toString();else if("string"!=typeof t.record_delimiter)return[Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(t.record_delimiter)}`)];switch(t.record_delimiter){case"unix":t.record_delimiter="\n";break;case"mac":t.record_delimiter="\r";break;case"windows":t.record_delimiter="\r\n";break;case"ascii":t.record_delimiter="\x1e";break;case"unicode":t.record_delimiter="\u2028"}return[void 0,t]},tR=Buffer.from([239,187,191]),tP=function(e,t={}){let r=[],[i,n]=tk(t);if(void 0!==i)throw i;let u={options:n,state:{stop:!1},info:{records:0},__transform:function(e,t){let r,i;if(!Array.isArray(e)&&"object"!=typeof e)return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(e)}`);if(0===this.info.records){if(Array.isArray(e)){if(!0===this.options.header&&void 0===this.options.columns)return Error("Undiscoverable Columns: header option requires column option or object records")}else if(void 0===this.options.columns){let[t,r]=tI(Object.keys(e));if(t)return;this.options.columns=r}}if(0===this.info.records){this.bom(t);let e=this.headers(t);if(e)return e}try{this.options.on_record&&this.options.on_record(e,this.info.records)}catch(e){return e}if(this.options.eof){if([r,i]=this.stringify(e),r)return r;if(void 0===i)return;i+=this.options.record_delimiter}else{if([r,i]=this.stringify(e),r)return r;if(void 0===i)return;(this.options.header||this.info.records)&&(i=this.options.record_delimiter+i)}this.info.records++,t(i)},stringify:function(e,t=!1){if("object"!=typeof e)return[void 0,e];let{columns:r}=this.options,i=[];if(Array.isArray(e)){r&&e.splice(r.length);for(let r=0;r<e.length;r++){let n=e[r],[u,o]=this.__cast(n,{index:r,column:r,records:this.info.records,header:t});if(u)return[u];i[r]=[o,n]}}else for(let n=0;n<r.length;n++){let u=tT(e,r[n].key),[o,s]=this.__cast(u,{index:n,column:r[n].key,records:this.info.records,header:t});if(o)return[o];i[n]=[s,u]}let n="";for(let e=0;e<i.length;e++){let t,r,[o,s]=i[e];if("string"==typeof o)t=this.options;else{var u;if("object"!=typeof(u=o)||null===u||Array.isArray(u))if(null!=o)return[Error(`Invalid Casting Value: returned value must return a string, an object, null or undefined, got ${JSON.stringify(o)}`)];else t=this.options;else{if(o=(t=o).value,delete t.value,"string"!=typeof o&&null!=o&&r)return[Error(`Invalid Casting Value: returned value must return a string, null or undefined, got ${JSON.stringify(o)}`)];if(t={...this.options,...t},[r,t]=tk(t),void 0!==r)return[r]}}let{delimiter:a,escape:l,quote:c,quoted:d,quoted_empty:p,quoted_string:h,quoted_match:f,record_delimiter:m,escape_formulas:g}=t;if(""===o&&""===s){let e=f&&f.filter(e=>"string"==typeof e?-1!==o.indexOf(e):e.test(o));!0===((e=e&&e.length>0)||!0===p||!0===h&&!1!==p)&&(o=c+o+c),n+=o}else if(o){if("string"!=typeof o)return[Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(o)}`)];let e=a.length&&o.indexOf(a)>=0,t=""!==c&&o.indexOf(c)>=0,r=o.indexOf(l)>=0&&l!==c,i=o.indexOf(m)>=0,u=h&&"string"==typeof s,p=f&&f.filter(e=>"string"==typeof e?-1!==o.indexOf(e):e.test(o));if(p=p&&p.length>0,g)switch(o[0]){case"=":case"+":case"-":case"@":case" ":case"\r":case"=":case"+":case"-":case"@":o=`'${o}`}let A=!0===t||e||i||d||u||p;if(!0===A&&!0===r){let e="\\"===l?RegExp(l+l,"g"):RegExp(l,"g");o=o.replace(e,l+l)}if(!0===t){let e=RegExp(c,"g");o=o.replace(e,l+c)}!0===A&&(o=c+o+c),n+=o}else(!0===p||""===s&&!0===h&&!1!==p)&&(n+=c+c);e!==i.length-1&&(n+=a)}return[void 0,n]},bom:function(e){!0===this.options.bom&&e(tR)},headers:function(e){let t;if(!1===this.options.header||void 0===this.options.columns)return;let r=this.options.columns.map(e=>e.header);if(this.options.eof?([t,r]=this.stringify(r,!0),r+=this.options.record_delimiter):[t,r]=this.stringify(r),t)return t;this.options.header_as_comment&&(r=this.options.header_as_comment+" "+r),e(r)},__cast:function(e,t){let r=typeof e;try{if("string"===r)return[void 0,this.options.cast.string(e,t)];if("bigint"===r)return[void 0,this.options.cast.bigint(e,t)];if("number"===r)return[void 0,this.options.cast.number(e,t)];else if("boolean"===r)return[void 0,this.options.cast.boolean(e,t)];else if(e instanceof Date)return[void 0,this.options.cast.date(e,t)];else if("object"===r&&null!==e)return[void 0,this.options.cast.object(e,t)];else return[void 0,e,e]}catch(e){return[e]}}};for(let t of e){let e=u.__transform(t,function(e){r.push(e)});if(void 0!==e)throw e}if(0===r.length){u.bom(e=>{r.push(e)});let e=u.headers(e=>{r.push(e)});if(void 0!==e)throw e}return r.join("")};function tL(e,t){var r,i;let n,u=(0,I.resolve)(e),o=(0,I.resolve)(u,t);if(r=u,i=o,n=r.endsWith(I.sep)?r:`${r}${I.sep}`,!(i===r||i.startsWith(n)))throw new l(`Storage path escapes baseDir: ${t}`,{error:"INVALID_STORAGE_PATH",details:{baseDir:u,filePath:t,resolvedPath:o}});return o}async function tN(e,t){await (0,th.mkdir)((0,I.dirname)(e),{recursive:!0,mode:t})}var tj=((H={}).NotFound="ENOENT",H.StorageError="FILE_STORAGE_ERROR",H.InvalidJson="INVALID_JSON",H.InvalidCsv="INVALID_CSV",H),t$=((z={}).ReadText="readText",z.WriteText="writeText",z.Remove="remove",z.ReadJson="readJson",z.WriteJson="writeJson",z.ReadCsv="readCsv",z.WriteCsv="writeCsv",z);class tM extends l{filePath;operation;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="FileStorageError",this.filePath=t.filePath,this.operation=t.operation}}class tU extends tM{constructor(e,t,r){super(`File not found: ${e}`,{cause:r,code:"ENOENT",filePath:e,operation:t}),this.name="FileNotFoundError"}}let tq=Object.values(tj),tV=f("ENOENT");function tH(e,t,r){var i;return h(e,tq)?e:(i=e)instanceof Error&&"string"==typeof i.code&&"ENOENT"===e.code?new tU(t,r,e):new tM(`Failed to ${r} for file: ${t}`,{cause:e,code:"FILE_STORAGE_ERROR",filePath:t,operation:r})}function tz(e,t,r){let i=e??t;if(!Number.isInteger(i)||i<=0)throw TypeError(`${r} must be a positive integer`);return i}async function tG(e,t){try{let r=await (0,th.stat)(e);Date.now()-r.mtimeMs>t&&await (0,th.unlink)(e)}catch(e){if("ENOENT"!==e.code)throw e}}async function tW(e,t,r={}){let{retryMs:i,staleMs:n,timeoutMs:u}=function(e){let t={retryMs:tz(e.retryMs,50,"retryMs"),staleMs:tz(e.staleMs,15e3,"staleMs"),timeoutMs:tz(e.timeoutMs,2e4,"timeoutMs")};if(t.staleMs>t.timeoutMs)throw TypeError("staleMs must be less than or equal to timeoutMs");return t}(r),o=(0,I.resolve)(e),s=Date.now()+u;for(await tN(o);;)try{let e=await (0,th.open)(o,"wx",384);await e.close();break}catch(e){if("EEXIST"!==e.code)throw e;if(await tG(o,n),Date.now()>=s)throw new tM(`Timed out acquiring file lock: ${o}`,{cause:e,code:tj.StorageError,filePath:o,operation:t$.WriteText});await _(i)}try{return await t()}finally{await (0,th.unlink)(o).catch(e=>{if("ENOENT"!==e.code)throw e})}}class tJ{baseDir;constructor(e){if(this.baseDir=(0,I.resolve)(e.baseDir),!1!==e.baseDirMode){const t=e.baseDirMode;if(void 0!==t&&!function(e){return"number"==typeof e&&Number.isInteger(e)&&e>=0}(t))throw TypeError("baseDirMode must be a non-negative integer");(0,O.mkdirSync)(this.baseDir,{recursive:!0,mode:t}),void 0!==t&&(511&(0,O.statSync)(this.baseDir).mode)!==t&&(0,O.chmodSync)(this.baseDir,t)}}async readText(e,t="utf8"){let r=tL(this.baseDir,e);try{return await (0,th.readFile)(r,{encoding:t})}catch(e){throw tH(e,r,t$.ReadText)}}async writeText(e,t,r={}){let i=r.encoding??"utf8",{mode:n}=r,u=tL(this.baseDir,e),o=(0,I.join)((0,I.dirname)(u),`.${(0,I.basename)(u)}.${(0,td.randomUUID)()}.tmp`);try{await tN(u),await (0,th.writeFile)(o,t,{encoding:i,mode:n}),void 0!==n&&await (0,th.chmod)(o,n),await (0,th.rename)(o,u)}catch(e){throw await (0,th.rm)(o,{force:!0}).catch(()=>void 0),tH(e,u,t$.WriteText)}}async remove(e){let t=tL(this.baseDir,e);try{await (0,th.rm)(t)}catch(e){throw tH(e,t,t$.Remove)}}async readJson(e,t="utf8"){let r=tL(this.baseDir,e),i=await this.readText(e,t);try{return JSON.parse(i)}catch(e){throw new tM(`Failed to parse JSON file: ${r}`,{cause:e,code:tj.InvalidJson,filePath:r,operation:t$.ReadJson})}}async writeJson(e,t,r={}){let i=r.encoding??"utf8",n=r.spaces??2,u=`${JSON.stringify(t,null,n)}
|
|
30
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function U(e){return e.map(e=>{let t,r;if(!e.startsWith("--inspect"))return e;let i="127.0.0.1",n="9229";return(null!==(r=e.match(/^(--inspect(-brk)?)$/))?t=r[1]:null!==(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))?(t=r[1],/^\d+$/.test(r[3])?n=r[3]:i=r[3]):null!==(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(t=r[1],i=r[3],n=r[4]),t&&"0"!==n)?`${t}=${i}:${parseInt(n)+1}`:e})}function q(){return!k.env.NO_COLOR&&"0"!==k.env.FORCE_COLOR&&"false"!==k.env.FORCE_COLOR&&(!!k.env.FORCE_COLOR||void 0!==k.env.CLICOLOR_FORCE||void 0)}new M;var V,H,z,G,W,J,Y,K,X,Q,Z,ee,et,er,ei,en,eu,eo,es,ea,el,ec,ed,ep,eh,ef,em,eg,eA,ey,eE,e_,eb,ev,eC,eD,eF,ew,eB,ex,eS,eT,eI,eO,ek,eR,eP,eL,eN,ej,e$,eM,eU,eq,eV,eH,ez,eG=((V={}).Timeout="HTTP_TIMEOUT",V.Aborted="HTTP_ABORTED",V.Network="HTTP_NETWORK",V.Status="HTTP_STATUS",V.InvalidJson="HTTP_INVALID_JSON",V.InvalidArgument="HTTP_INVALID_ARGUMENT",V);class eW extends l{url;status;responseBody;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="HttpError",this.url=t.url,this.status=t.status,this.responseBody=t.responseBody}}let eJ=Object.values(eG);function eY(e){return h(e,eJ)&&"string"==typeof e.url}function eK(e){if(!e)throw new l("接口无响应",{error:"EMPTY_RESPONSE",message:"接口未返回任何数据"});if(0!==e.error)throw new l("接口调用失败",{error:"API_ERROR",message:e.message||"接口调用失败",details:{error:e.error}});return e.data}async function eX(e,t={}){let r,i,n,u,o,{timeoutMs:s=3e4,signal:a,...l}=t;var c,d,p=s,h=e;if(!Number.isInteger(p)||p<=0)throw new eW("timeoutMs must be a positive integer",{code:eG.InvalidArgument,url:h});let f=(c=s,d=a??void 0,r=new AbortController,i=!1,n=!1,u=setTimeout(()=>{n=!0,r.abort()},c),o=()=>{i=!0,r.abort(d?.reason)},d&&(d.aborted?o():d.addEventListener("abort",o,{once:!0})),{signal:r.signal,cleanup(){clearTimeout(u),d&&d.removeEventListener("abort",o)},get aborted(){return i},get timedOut(){return n}});try{return await fetch(e,{...l,signal:f.signal})}catch(t){if(f.timedOut)throw new eW(`Request timed out after ${s}ms`,{cause:t,code:eG.Timeout,url:e});if(f.aborted)throw new eW("Request aborted",{cause:t,code:eG.Aborted,url:e});throw new eW("Network request failed",{cause:t,code:eG.Network,url:e})}finally{f.cleanup()}}function eQ(e,t,r){let i=typeof t;if("string"!==i&&"number"!==i&&"boolean"!==i)throw new eW(`Invalid query parameter value for "${e}": expected string, number or boolean`,{code:eG.InvalidArgument,url:r})}async function eZ(e){try{return await e.text()}catch{return}}async function e1(e,t){if(204===e.status)return;let r=await eZ(e)??"";if(0!==r.length)try{return JSON.parse(r)}catch(i){throw new eW("Failed to parse response as JSON",{cause:i,code:eG.InvalidJson,url:t,status:e.status,responseBody:r})}}let e0=async e=>{var t,r,i,n,u,o,s,a,l,c,d,p;let h,f,{request:m}=e,g=(h=function(e){let{url:t}=e;if(/^https?:\/\//i.test(t))return t;let r=e.baseURL?.replace(/\/+$/,"");if(!r)throw new eW("baseURL is required for relative request URLs",{code:eG.InvalidArgument,url:t});let i=t.startsWith("/")?t:`/${t}`;return`${r}${i}`}(t=m),f=function(e,t){if(!e)return"";let r=new URLSearchParams;for(let[i,n]of Object.entries(e))if(null!=n){if(Array.isArray(n)){for(let e of n)null!=e&&(eQ(i,e,t),r.append(i,String(e)));continue}eQ(i,n,t),r.append(i,String(n))}return r.toString()}(t.params,h),r=h,(i=f)?`${r}${r.includes("?")?"&":"?"}${i}`:r),A=(n=m,n.method?.toUpperCase()??(void 0!==n.data?"POST":"GET")),y=(u=m,"GET"!==(o=A)&&"HEAD"!==o&&void 0!==u.data),E=new Headers(function(e){if(!e)return;let t=Object.entries(e).flatMap(([e,t])=>"string"!=typeof t||""===t.trim()?[]:[[e,t]]);return t.length>0?Object.fromEntries(t):void 0}(m.headers)),b=function(e,t,r,i){if(r){var n;if("string"==typeof(n=e.data)||Buffer.isBuffer(n))return e.data;t.has("Content-Type")||t.set("Content-Type","application/json");try{return JSON.stringify(e.data)}catch(e){throw new eW("Failed to serialize request body as JSON",{cause:e,code:eG.InvalidArgument,url:i})}}}(m,E,y,g);(s=E).has("Accept")||s.set("Accept","application/json");let v=Math.max(0,m.retry?.maxRetries??0);for(let t=0;;t+=1)try{let t=await eX(g,{method:A,headers:E,...void 0!==m.timeoutMs?{timeoutMs:m.timeoutMs}:{},...m.signal?{signal:m.signal}:{},...void 0!==m.redirect?{redirect:m.redirect}:{},...void 0!==b?{body:b}:{}});if(e.response={status:t.status,headers:t.headers,logId:t.headers.get("X-Tt-Logid")??void 0},!e.unwrapData){e.response.data=t;return}if(!((a=t.status)>=200&&a<300)){let e=await eZ(t);throw new eW(`Request failed with status ${t.status}`,{code:eG.Status,url:g,status:t.status,responseBody:e})}e.response.data=await e1(t,g);return}catch(r){let e=t+1;if(!(e<=v&&(m.retry?.shouldRetry?.({request:m,attempt:e,error:r})??!((l={request:m,attempt:e,error:r}).error instanceof eW&&l.error.error===eG.Aborted))))throw r;await _((c=m.retry,d=e,p=r,Math.max(0,"function"==typeof c.retryDelayMs?c.retryDelayMs(d,p):c.retryDelayMs??0)))}};class e2{run;constructor(e={}){const t=[...e.middlewares??[],e0];this.run=function(e){return function(t,r){let i=-1;return function n(u){if(u<=i)return Promise.reject(Error("next() called multiple times in middleware"));i=u;let o=u===e.length?void 0:e[u];if(!o)return Promise.resolve(r());try{return Promise.resolve(o(t,()=>n(u+1)))}catch(e){return Promise.reject(e)}}(0)}}(t)}async send(e,t={}){let r={request:e,meta:{...t.meta??{}},unwrapData:t.unwrapData??!0};return await this.run(r,()=>Promise.resolve()),r.response??{}}}let e3="dymg",e6="@douyin-minigame/cli",e4="douyin-minigame",e8=`${e3}:oauth`,e9=`${e3} auth login`,e7=`${e9} --no-wait`,e5=`${e9} --resume`,te=`${e3} auth logout`,tt=(n=new s.AsyncLocalStorage,{run:(e,t)=>n.run({...e},t),update(e){let t=n.getStore();t&&Object.assign(t,e)},get:()=>n.getStore()});function tr(e){tt.update(e)}function ti(){return tt.get()}let tn=[],tu=async(e,t)=>{try{await t()}finally{tr({response:e.response})}},to=async(e,t)=>{let r=ti()?.appId?.trim(),i=e.request.headers?.X_Tt_Appid?.trim()||r;i&&(e.request.headers??={},e.request.headers["X-Tt-Appid"]=i),await t()};var ts=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArray.js"),ta=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isFinite.js"),tl=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isPlainObject.js"),tc=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isString.js");let td=require("node:crypto");__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObject.js"),require("node:http"),require("node:net");let tp=require("node:os"),th=require("node:fs/promises");class tf extends Error{constructor(e,t,r,...i){for(const n of(Array.isArray(t)&&(t=t.join(" ").trim()),super(t),void 0!==Error.captureStackTrace&&Error.captureStackTrace(this,tf),this.code=e,i))for(const e in n){const t=n[e];this[e]=Buffer.isBuffer(t)?t.toString(r.encoding):null==t?t:JSON.parse(JSON.stringify(t))}}}let tm=function(e){let t=[];for(let i=0,n=e.length;i<n;i++){let n=e[i];if(null==n||!1===n)t[i]={disabled:!0};else if("string"==typeof n||"number"==typeof n)t[i]={name:`${n}`};else{var r;if("object"!=typeof(r=n)||null===r||Array.isArray(r))throw new tf("CSV_INVALID_COLUMN_DEFINITION",["Invalid column definition:","expect a string or a literal object,",`got ${JSON.stringify(n)} at position ${i}`]);if("string"!=typeof n.name)throw new tf("CSV_OPTION_COLUMNS_MISSING_NAME",["Option columns missing name:",`property "name" is required at position ${i}`,"when column is an object literal"]);t[i]=n}}return t},tg=class{constructor(e=100){this.size=e,this.length=0,this.buf=Buffer.allocUnsafe(e)}prepend(e){if(Buffer.isBuffer(e)){let t=this.length+e.length;if(t>=this.size&&(this.resize(),t>=this.size))throw Error("INVALID_BUFFER_STATE");let r=this.buf;this.buf=Buffer.allocUnsafe(this.size),e.copy(this.buf,0),r.copy(this.buf,e.length),this.length+=e.length}else{let t=this.length++;t===this.size&&this.resize();let r=this.clone();this.buf[0]=e,r.copy(this.buf,1,0,t)}}append(e){let t=this.length++;t===this.size&&this.resize(),this.buf[t]=e}clone(){return Buffer.from(this.buf.slice(0,this.length))}resize(){let e=this.length;this.size=2*this.size;let t=Buffer.allocUnsafe(this.size);this.buf.copy(t,0,0,e),this.buf=t}toString(e){return e?this.buf.slice(0,this.length).toString(e):Uint8Array.prototype.slice.call(this.buf.slice(0,this.length))}toJSON(){return this.toString("utf8")}reset(){this.length=0}},tA=function(e){let t={};for(let r in e)t[r.replace(/([A-Z])/g,function(e,t){return"_"+t.toLowerCase()})]=e[r];if(void 0===t.encoding||!0===t.encoding)t.encoding="utf8";else if(null===t.encoding||!1===t.encoding)t.encoding=null;else if("string"!=typeof t.encoding&&null!==t.encoding)throw new tf("CSV_INVALID_OPTION_ENCODING",["Invalid option encoding:","encoding must be a string or null to return a buffer,",`got ${JSON.stringify(t.encoding)}`],t);if(void 0===t.bom||null===t.bom||!1===t.bom)t.bom=!1;else if(!0!==t.bom)throw new tf("CSV_INVALID_OPTION_BOM",["Invalid option bom:","bom must be true,",`got ${JSON.stringify(t.bom)}`],t);if(t.cast_function=null,void 0===t.cast||null===t.cast||!1===t.cast||""===t.cast)t.cast=void 0;else if("function"==typeof t.cast)t.cast_function=t.cast,t.cast=!0;else if(!0!==t.cast)throw new tf("CSV_INVALID_OPTION_CAST",["Invalid option cast:","cast must be true or a function,",`got ${JSON.stringify(t.cast)}`],t);if(void 0===t.cast_date||null===t.cast_date||!1===t.cast_date||""===t.cast_date)t.cast_date=!1;else if(!0===t.cast_date)t.cast_date=function(e){let t=Date.parse(e);return isNaN(t)?e:new Date(t)};else if("function"!=typeof t.cast_date)throw new tf("CSV_INVALID_OPTION_CAST_DATE",["Invalid option cast_date:","cast_date must be true or a function,",`got ${JSON.stringify(t.cast_date)}`],t);if(t.cast_first_line_to_header=void 0,!0===t.columns)t.cast_first_line_to_header=void 0;else if("function"==typeof t.columns)t.cast_first_line_to_header=t.columns,t.columns=!0;else if(Array.isArray(t.columns))t.columns=tm(t.columns);else if(void 0===t.columns||null===t.columns||!1===t.columns)t.columns=!1;else throw new tf("CSV_INVALID_OPTION_COLUMNS",["Invalid option columns:","expect an array, a function or true,",`got ${JSON.stringify(t.columns)}`],t);if(void 0===t.group_columns_by_name||null===t.group_columns_by_name||!1===t.group_columns_by_name)t.group_columns_by_name=!1;else if(!0!==t.group_columns_by_name)throw new tf("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",["Invalid option group_columns_by_name:","expect an boolean,",`got ${JSON.stringify(t.group_columns_by_name)}`],t);else if(!1===t.columns)throw new tf("CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME",["Invalid option group_columns_by_name:","the `columns` mode must be activated."],t);if(void 0===t.comment||null===t.comment||!1===t.comment||""===t.comment)t.comment=null;else if("string"==typeof t.comment&&(t.comment=Buffer.from(t.comment,t.encoding)),!Buffer.isBuffer(t.comment))throw new tf("CSV_INVALID_OPTION_COMMENT",["Invalid option comment:","comment must be a buffer or a string,",`got ${JSON.stringify(t.comment)}`],t);if(void 0===t.comment_no_infix||null===t.comment_no_infix||!1===t.comment_no_infix)t.comment_no_infix=!1;else if(!0!==t.comment_no_infix)throw new tf("CSV_INVALID_OPTION_COMMENT",["Invalid option comment_no_infix:","value must be a boolean,",`got ${JSON.stringify(t.comment_no_infix)}`],t);let r=JSON.stringify(t.delimiter);if(Array.isArray(t.delimiter)||(t.delimiter=[t.delimiter]),0===t.delimiter.length)throw new tf("CSV_INVALID_OPTION_DELIMITER",["Invalid option delimiter:","delimiter must be a non empty string or buffer or array of string|buffer,",`got ${r}`],t);if(t.delimiter=t.delimiter.map(function(e){if(null==e||!1===e)return Buffer.from(",",t.encoding);if("string"==typeof e&&(e=Buffer.from(e,t.encoding)),!Buffer.isBuffer(e)||0===e.length)throw new tf("CSV_INVALID_OPTION_DELIMITER",["Invalid option delimiter:","delimiter must be a non empty string or buffer or array of string|buffer,",`got ${r}`],t);return e}),void 0===t.escape||!0===t.escape?t.escape=Buffer.from('"',t.encoding):"string"==typeof t.escape?t.escape=Buffer.from(t.escape,t.encoding):(null===t.escape||!1===t.escape)&&(t.escape=null),null!==t.escape&&!Buffer.isBuffer(t.escape))throw Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(t.escape)}`);if(void 0===t.from||null===t.from)t.from=1;else if("string"==typeof t.from&&/\d+/.test(t.from)&&(t.from=parseInt(t.from)),Number.isInteger(t.from)){if(t.from<0)throw Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(e.from)}`)}else throw Error(`Invalid Option: from must be an integer, got ${JSON.stringify(t.from)}`);if(void 0===t.from_line||null===t.from_line)t.from_line=1;else if("string"==typeof t.from_line&&/\d+/.test(t.from_line)&&(t.from_line=parseInt(t.from_line)),Number.isInteger(t.from_line)){if(t.from_line<=0)throw Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(e.from_line)}`)}else throw Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(e.from_line)}`);if(void 0===t.ignore_last_delimiters||null===t.ignore_last_delimiters)t.ignore_last_delimiters=!1;else if("number"==typeof t.ignore_last_delimiters)t.ignore_last_delimiters=Math.floor(t.ignore_last_delimiters),0===t.ignore_last_delimiters&&(t.ignore_last_delimiters=!1);else if("boolean"!=typeof t.ignore_last_delimiters)throw new tf("CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS",["Invalid option `ignore_last_delimiters`:","the value must be a boolean value or an integer,",`got ${JSON.stringify(t.ignore_last_delimiters)}`],t);if(!0===t.ignore_last_delimiters&&!1===t.columns)throw new tf("CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS",["The option `ignore_last_delimiters`","requires the activation of the `columns` option"],t);if(void 0===t.info||null===t.info||!1===t.info)t.info=!1;else if(!0!==t.info)throw Error(`Invalid Option: info must be true, got ${JSON.stringify(t.info)}`);if(void 0===t.max_record_size||null===t.max_record_size||!1===t.max_record_size)t.max_record_size=0;else if(Number.isInteger(t.max_record_size)&&t.max_record_size>=0);else if("string"==typeof t.max_record_size&&/\d+/.test(t.max_record_size))t.max_record_size=parseInt(t.max_record_size);else throw Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(t.max_record_size)}`);if(void 0===t.objname||null===t.objname||!1===t.objname)t.objname=void 0;else if(Buffer.isBuffer(t.objname)){if(0===t.objname.length)throw Error("Invalid Option: objname must be a non empty buffer");null===t.encoding||(t.objname=t.objname.toString(t.encoding))}else if("string"==typeof t.objname){if(0===t.objname.length)throw Error("Invalid Option: objname must be a non empty string")}else if("number"==typeof t.objname);else throw Error(`Invalid Option: objname must be a string or a buffer, got ${t.objname}`);if(void 0!==t.objname){if("number"==typeof t.objname){if(!1!==t.columns)throw Error("Invalid Option: objname index cannot be combined with columns or be defined as a field")}else if(!1===t.columns)throw Error("Invalid Option: objname field must be combined with columns or be defined as an index")}if(void 0===t.on_record||null===t.on_record)t.on_record=void 0;else if("function"!=typeof t.on_record)throw new tf("CSV_INVALID_OPTION_ON_RECORD",["Invalid option `on_record`:","expect a function,",`got ${JSON.stringify(t.on_record)}`],t);if(void 0!==t.on_skip&&null!==t.on_skip&&"function"!=typeof t.on_skip)throw Error(`Invalid Option: on_skip must be a function, got ${JSON.stringify(t.on_skip)}`);if(null===t.quote||!1===t.quote||""===t.quote)t.quote=null;else if(void 0===t.quote||!0===t.quote?t.quote=Buffer.from('"',t.encoding):"string"==typeof t.quote&&(t.quote=Buffer.from(t.quote,t.encoding)),!Buffer.isBuffer(t.quote))throw Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(t.quote)}`);if(void 0===t.raw||null===t.raw||!1===t.raw)t.raw=!1;else if(!0!==t.raw)throw Error(`Invalid Option: raw must be true, got ${JSON.stringify(t.raw)}`);if(void 0===t.record_delimiter)t.record_delimiter=[];else if("string"==typeof t.record_delimiter||Buffer.isBuffer(t.record_delimiter)){if(0===t.record_delimiter.length)throw new tf("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a non empty string or buffer,",`got ${JSON.stringify(t.record_delimiter)}`],t);t.record_delimiter=[t.record_delimiter]}else if(!Array.isArray(t.record_delimiter))throw new tf("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a string, a buffer or array of string|buffer,",`got ${JSON.stringify(t.record_delimiter)}`],t);if(t.record_delimiter=t.record_delimiter.map(function(e,r){if("string"==typeof e||Buffer.isBuffer(e)){if(0===e.length)throw new tf("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a non empty string or buffer",`at index ${r},`,`got ${JSON.stringify(e)}`],t)}else throw new tf("CSV_INVALID_OPTION_RECORD_DELIMITER",["Invalid option `record_delimiter`:","value must be a string, a buffer or array of string|buffer",`at index ${r},`,`got ${JSON.stringify(e)}`],t);return"string"==typeof e&&(e=Buffer.from(e,t.encoding)),e}),"boolean"==typeof t.relax_column_count);else if(void 0===t.relax_column_count||null===t.relax_column_count)t.relax_column_count=!1;else throw Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(t.relax_column_count)}`);if("boolean"==typeof t.relax_column_count_less);else if(void 0===t.relax_column_count_less||null===t.relax_column_count_less)t.relax_column_count_less=!1;else throw Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(t.relax_column_count_less)}`);if("boolean"==typeof t.relax_column_count_more);else if(void 0===t.relax_column_count_more||null===t.relax_column_count_more)t.relax_column_count_more=!1;else throw Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(t.relax_column_count_more)}`);if("boolean"==typeof t.relax_quotes);else if(void 0===t.relax_quotes||null===t.relax_quotes)t.relax_quotes=!1;else throw Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(t.relax_quotes)}`);if("boolean"==typeof t.skip_empty_lines);else if(void 0===t.skip_empty_lines||null===t.skip_empty_lines)t.skip_empty_lines=!1;else throw Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(t.skip_empty_lines)}`);if("boolean"==typeof t.skip_records_with_empty_values);else if(void 0===t.skip_records_with_empty_values||null===t.skip_records_with_empty_values)t.skip_records_with_empty_values=!1;else throw Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(t.skip_records_with_empty_values)}`);if("boolean"==typeof t.skip_records_with_error);else if(void 0===t.skip_records_with_error||null===t.skip_records_with_error)t.skip_records_with_error=!1;else throw Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(t.skip_records_with_error)}`);if(void 0===t.rtrim||null===t.rtrim||!1===t.rtrim)t.rtrim=!1;else if(!0!==t.rtrim)throw Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(t.rtrim)}`);if(void 0===t.ltrim||null===t.ltrim||!1===t.ltrim)t.ltrim=!1;else if(!0!==t.ltrim)throw Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(t.ltrim)}`);if(void 0===t.trim||null===t.trim||!1===t.trim)t.trim=!1;else if(!0!==t.trim)throw Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(t.trim)}`);if(!0===t.trim&&!1!==e.ltrim?t.ltrim=!0:!0!==t.ltrim&&(t.ltrim=!1),!0===t.trim&&!1!==e.rtrim?t.rtrim=!0:!0!==t.rtrim&&(t.rtrim=!1),void 0===t.to||null===t.to)t.to=-1;else if(-1!==t.to)if("string"==typeof t.to&&/\d+/.test(t.to)&&(t.to=parseInt(t.to)),Number.isInteger(t.to)){if(t.to<=0)throw Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(e.to)}`)}else throw Error(`Invalid Option: to must be an integer, got ${JSON.stringify(e.to)}`);if(void 0===t.to_line||null===t.to_line)t.to_line=-1;else if(-1!==t.to_line)if("string"==typeof t.to_line&&/\d+/.test(t.to_line)&&(t.to_line=parseInt(t.to_line)),Number.isInteger(t.to_line)){if(t.to_line<=0)throw Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(e.to_line)}`)}else throw Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(e.to_line)}`);return t},ty=function(e){return e.every(e=>null==e||e.toString&&""===e.toString().trim())},tE={utf8:Buffer.from([239,187,191]),utf16le:Buffer.from([255,254])},t_=function(e={}){var t;let r=tA(e);return{info:{bytes:0,bytes_records:0,comment_lines:0,empty_lines:0,invalid_field_length:0,lines:1,records:0},original_options:e,options:r,state:{bomSkipped:!1,bufBytesStart:0,castField:(t=r).cast_function,commenting:!1,error:void 0,enabled:1===t.from_line,escaping:!1,escapeIsQuote:Buffer.isBuffer(t.escape)&&Buffer.isBuffer(t.quote)&&0===Buffer.compare(t.escape,t.quote),expectedRecordLength:Array.isArray(t.columns)?t.columns.length:void 0,field:new tg(20),firstLineToHeaders:t.cast_first_line_to_header,needMoreDataSize:Math.max(null!==t.comment?t.comment.length:0,...t.delimiter.map(e=>e.length),null!==t.quote?t.quote.length:0),previousBuf:void 0,quoting:!1,stop:!1,rawBuffer:new tg(100),record:[],recordHasError:!1,record_length:0,recordDelimiterMaxLength:0===t.record_delimiter.length?0:Math.max(...t.record_delimiter.map(e=>e.length)),trimChars:[Buffer.from(" ",t.encoding)[0],Buffer.from(" ",t.encoding)[0]],wasQuoting:!1,wasRowDelimiter:!1,timchars:[Buffer.from(Buffer.from([13],"utf8").toString(),t.encoding),Buffer.from(Buffer.from([10],"utf8").toString(),t.encoding),Buffer.from(Buffer.from([12],"utf8").toString(),t.encoding),Buffer.from(Buffer.from([32],"utf8").toString(),t.encoding),Buffer.from(Buffer.from([9],"utf8").toString(),t.encoding)]},__needMoreData:function(e,t,r){if(r)return!1;let{encoding:i,escape:n,quote:u}=this.options,{quoting:o,needMoreDataSize:s,recordDelimiterMaxLength:a}=this.state;return t-e-1<Math.max(s,0===a?Buffer.from("\r\n",i).length:a,o?(null===n?0:n.length)+u.length:0,o?u.length+a:0)},parse:function(e,t,r,i){let n,u,{bom:o,comment_no_infix:s,encoding:a,from_line:l,ltrim:c,max_record_size:d,raw:p,relax_quotes:h,rtrim:f,skip_empty_lines:m,to:g,to_line:A}=this.options,{comment:y,escape:E,quote:_,record_delimiter:b}=this.options,{bomSkipped:v,previousBuf:C,rawBuffer:D,escapeIsQuote:F}=this.state;if(void 0===C)if(void 0===e)return void i();else n=e;else n=void 0!==C&&void 0===e?C:Buffer.concat([C,e]);if(!1===v)if(!1===o)this.state.bomSkipped=!0;else if(n.length<3){if(!1===t){this.state.previousBuf=n;return}}else{for(let e in tE)if(0===tE[e].compare(n,0,tE[e].length)){let t=tE[e].length;this.state.bufBytesStart+=t,n=n.slice(t);let r=tA({...this.original_options,encoding:e});for(let e in r)this.options[e]=r[e];({comment:y,escape:E,quote:_}=this.options);break}this.state.bomSkipped=!0}let w=n.length;for(u=0;u<w&&!this.__needMoreData(u,w,t);u++){if(!0===this.state.wasRowDelimiter&&(this.info.lines++,this.state.wasRowDelimiter=!1),-1!==A&&this.info.lines>A){this.state.stop=!0,i();return}!1===this.state.quoting&&0===b.length&&this.__autoDiscoverRecordDelimiter(n,u)&&(b=this.options.record_delimiter);let e=n[u];if(!0===p&&D.append(e),(13===e||10===e)&&!1===this.state.wasRowDelimiter&&(this.state.wasRowDelimiter=!0),!0===this.state.escaping)this.state.escaping=!1;else{if(null!==E&&!0===this.state.quoting&&this.__isEscape(n,u,e)&&u+E.length<w)if(F){if(this.__isQuote(n,u+E.length)){this.state.escaping=!0,u+=E.length-1;continue}}else{this.state.escaping=!0,u+=E.length-1;continue}if(!1===this.state.commenting&&this.__isQuote(n,u))if(!0===this.state.quoting){let t=n[u+_.length],r=f&&this.__isCharTrimable(n,u+_.length),i=null!==y&&this.__compareBytes(y,n,u+_.length,t),o=this.__isDelimiter(n,u+_.length,t),s=0===b.length?this.__autoDiscoverRecordDelimiter(n,u+_.length):this.__isRecordDelimiter(t,n,u+_.length);if(null!==E&&this.__isEscape(n,u,e)&&this.__isQuote(n,u+E.length))u+=E.length-1;else if(!t||o||s||i||r){this.state.quoting=!1,this.state.wasQuoting=!0,u+=_.length-1;continue}else if(!1===h){let e=this.__error(new tf("CSV_INVALID_CLOSING_QUOTE",["Invalid Closing Quote:",`got "${String.fromCharCode(t)}"`,`at line ${this.info.lines}`,"instead of delimiter, record delimiter, trimable character","(if activated) or comment"],this.options,this.__infoField()));if(void 0!==e)return e}else this.state.quoting=!1,this.state.wasQuoting=!0,this.state.field.prepend(_),u+=_.length-1}else if(0!==this.state.field.length){if(!1===h){let e=this.__infoField(),t=Object.keys(tE).map(e=>!!tE[e].equals(this.state.field.toString())&&e).filter(Boolean)[0],r=this.__error(new tf("INVALID_OPENING_QUOTE",["Invalid Opening Quote:",`a quote is found on field ${JSON.stringify(e.column)} at line ${e.lines}, value is ${JSON.stringify(this.state.field.toString(a))}`,t?`(${t} bom)`:void 0],this.options,e,{field:this.state.field}));if(void 0!==r)return r}}else{this.state.quoting=!0,u+=_.length-1;continue}if(!1===this.state.quoting){let t=this.__isRecordDelimiter(e,n,u);if(0!==t){if(this.state.commenting&&!1===this.state.wasQuoting&&0===this.state.record.length&&0===this.state.field.length)this.info.comment_lines++;else{if(!1===this.state.enabled&&this.info.lines+ +(!0===this.state.wasRowDelimiter)>=l){this.state.enabled=!0,this.__resetField(),this.__resetRecord(),u+=t-1;continue}if(!0===m&&!1===this.state.wasQuoting&&0===this.state.record.length&&0===this.state.field.length){this.info.empty_lines++,u+=t-1;continue}this.info.bytes=this.state.bufBytesStart+u;let e=this.__onField();if(void 0!==e)return e;this.info.bytes=this.state.bufBytesStart+u+t;let n=this.__onRecord(r);if(void 0!==n)return n;if(-1!==g&&this.info.records>=g){this.state.stop=!0,i();return}}this.state.commenting=!1,u+=t-1;continue}if(this.state.commenting)continue;if(null!==y&&(!1===s||0===this.state.record.length&&0===this.state.field.length)&&0!==this.__compareBytes(y,n,u,e)){this.state.commenting=!0;continue}let o=this.__isDelimiter(n,u,e);if(0!==o){this.info.bytes=this.state.bufBytesStart+u;let e=this.__onField();if(void 0!==e)return e;u+=o-1;continue}}}if(!1===this.state.commenting&&0!==d&&this.state.record_length+this.state.field.length>d)return this.__error(new tf("CSV_MAX_RECORD_SIZE",["Max Record Size:","record exceed the maximum number of tolerated bytes",`of ${d}`,`at line ${this.info.lines}`],this.options,this.__infoField()));let t=!1===c||!0===this.state.quoting||0!==this.state.field.length||!this.__isCharTrimable(n,u),o=!1===f||!1===this.state.wasQuoting;if(!0===t&&!0===o)this.state.field.append(e);else{if(!0===f&&!this.__isCharTrimable(n,u))return this.__error(new tf("CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE",["Invalid Closing Quote:","found non trimable byte after quote",`at line ${this.info.lines}`],this.options,this.__infoField()));!1===t&&(u+=this.__isCharTrimable(n,u)-1);continue}}if(!0===t)if(!0===this.state.quoting){let e=this.__error(new tf("CSV_QUOTE_NOT_CLOSED",["Quote Not Closed:",`the parsing is finished with an opening quote at line ${this.info.lines}`],this.options,this.__infoField()));if(void 0!==e)return e}else if(!0===this.state.wasQuoting||0!==this.state.record.length||0!==this.state.field.length){this.info.bytes=this.state.bufBytesStart+u;let e=this.__onField();if(void 0!==e)return e;let t=this.__onRecord(r);if(void 0!==t)return t}else!0===this.state.wasRowDelimiter?this.info.empty_lines++:!0===this.state.commenting&&this.info.comment_lines++;else this.state.bufBytesStart+=u,this.state.previousBuf=n.slice(u);!0===this.state.wasRowDelimiter&&(this.info.lines++,this.state.wasRowDelimiter=!1)},__onRecord:function(e){let{columns:t,group_columns_by_name:r,encoding:i,info:n,from:u,relax_column_count:o,relax_column_count_less:s,relax_column_count_more:a,raw:l,skip_records_with_empty_values:c}=this.options,{enabled:d,record:p}=this.state;if(!1===d)return this.__resetRecord();let h=p.length;if(!0===t)return!0===c&&ty(p)?void this.__resetRecord():this.__firstLineToColumns(p);if(!1===t&&0===this.info.records&&(this.state.expectedRecordLength=h),h!==this.state.expectedRecordLength){let e=!1===t?new tf("CSV_RECORD_INCONSISTENT_FIELDS_LENGTH",["Invalid Record Length:",`expect ${this.state.expectedRecordLength},`,`got ${h} on line ${this.info.lines}`],this.options,this.__infoField(),{record:p}):new tf("CSV_RECORD_INCONSISTENT_COLUMNS",["Invalid Record Length:",`columns length is ${t.length},`,`got ${h} on line ${this.info.lines}`],this.options,this.__infoField(),{record:p});if(!0===o||!0===s&&h<this.state.expectedRecordLength||!0===a&&h>this.state.expectedRecordLength)this.info.invalid_field_length++,this.state.error=e;else{let t=this.__error(e);if(t)return t}}if(!0===c&&ty(p))return void this.__resetRecord();if(!0===this.state.recordHasError){this.__resetRecord(),this.state.recordHasError=!1;return}if(this.info.records++,1===u||this.info.records>=u){let{objname:u}=this.options;if(!1!==t){let o={};for(let e=0,i=p.length;e<i;e++)void 0===t[e]||t[e].disabled||(!0===r&&void 0!==o[t[e].name]?Array.isArray(o[t[e].name])?o[t[e].name]=o[t[e].name].concat(p[e]):o[t[e].name]=[o[t[e].name],p[e]]:o[t[e].name]=p[e]);if(!0===l||!0===n){let t=Object.assign({record:o},!0===l?{raw:this.state.rawBuffer.toString(i)}:{},!0===n?{info:this.__infoRecord()}:{}),r=this.__push(void 0===u?t:[o[u],t],e);if(r)return r}else{let t=this.__push(void 0===u?o:[o[u],o],e);if(t)return t}}else if(!0===l||!0===n){let t=Object.assign({record:p},!0===l?{raw:this.state.rawBuffer.toString(i)}:{},!0===n?{info:this.__infoRecord()}:{}),r=this.__push(void 0===u?t:[p[u],t],e);if(r)return r}else{let t=this.__push(void 0===u?p:[p[u],p],e);if(t)return t}}this.__resetRecord()},__firstLineToColumns:function(e){let{firstLineToHeaders:t}=this.state;try{let r=void 0===t?e:t.call(null,e);if(!Array.isArray(r))return this.__error(new tf("CSV_INVALID_COLUMN_MAPPING",["Invalid Column Mapping:","expect an array from column function,",`got ${JSON.stringify(r)}`],this.options,this.__infoField(),{headers:r}));let i=tm(r);this.state.expectedRecordLength=i.length,this.options.columns=i,this.__resetRecord();return}catch(e){return e}},__resetRecord:function(){!0===this.options.raw&&this.state.rawBuffer.reset(),this.state.error=void 0,this.state.record=[],this.state.record_length=0},__onField:function(){let{cast:e,encoding:t,rtrim:r,max_record_size:i}=this.options,{enabled:n,wasQuoting:u}=this.state;if(!1===n)return this.__resetField();let o=this.state.field.toString(t);if(!0===r&&!1===u&&(o=o.trimRight()),!0===e){let[e,t]=this.__cast(o);if(void 0!==e)return e;o=t}this.state.record.push(o),0!==i&&"string"==typeof o&&(this.state.record_length+=o.length),this.__resetField()},__resetField:function(){this.state.field.reset(),this.state.wasQuoting=!1},__push:function(e,t){let{on_record:r}=this.options;if(void 0!==r){let t=this.__infoRecord();try{e=r.call(null,e,t)}catch(e){return e}if(null==e)return}this.info.bytes_records+=this.info.bytes,t(e)},__cast:function(e){let{columns:t,relax_column_count:r}=this.options;if(!0===Array.isArray(t)&&r&&this.options.columns.length<=this.state.record.length)return[void 0,void 0];if(null!==this.state.castField)try{let t=this.__infoField();return[void 0,this.state.castField.call(null,e,t)]}catch(e){return[e]}if(this.__isFloat(e))return[void 0,parseFloat(e)];if(!1!==this.options.cast_date){let t=this.__infoField();return[void 0,this.options.cast_date.call(null,e,t)]}return[void 0,e]},__isCharTrimable:function(e,t){return((e,t)=>{let{timchars:r}=this.state;u:for(let i=0;i<r.length;i++){let n=r[i];for(let r=0;r<n.length;r++)if(n[r]!==e[t+r])continue u;return n.length}return 0})(e,t)},__isFloat:function(e){return e-parseFloat(e)+1>=0},__compareBytes:function(e,t,r,i){if(e[0]!==i)return 0;let n=e.length;for(let i=1;i<n;i++)if(e[i]!==t[r+i])return 0;return n},__isDelimiter:function(e,t,r){let{delimiter:i,ignore_last_delimiters:n}=this.options;if(!0===n&&this.state.record.length===this.options.columns.length-1||!1!==n&&"number"==typeof n&&this.state.record.length===n-1)return 0;u:for(let n=0;n<i.length;n++){let u=i[n];if(u[0]===r){for(let r=1;r<u.length;r++)if(u[r]!==e[t+r])continue u;return u.length}}return 0},__isRecordDelimiter:function(e,t,r){let{record_delimiter:i}=this.options,n=i.length;u:for(let u=0;u<n;u++){let n=i[u],o=n.length;if(n[0]===e){for(let e=1;e<o;e++)if(n[e]!==t[r+e])continue u;return n.length}}return 0},__isEscape:function(e,t,r){let{escape:i}=this.options;if(null===i)return!1;let n=i.length;if(i[0]===r){for(let r=0;r<n;r++)if(i[r]!==e[t+r])return!1;return!0}return!1},__isQuote:function(e,t){let{quote:r}=this.options;if(null===r)return!1;let i=r.length;for(let n=0;n<i;n++)if(r[n]!==e[t+n])return!1;return!0},__autoDiscoverRecordDelimiter:function(e,t){let{encoding:r}=this.options,i=[Buffer.from("\r\n",r),Buffer.from("\n",r),Buffer.from("\r",r)];o:for(let r=0;r<i.length;r++){let n=i[r].length;for(let u=0;u<n;u++)if(i[r][u]!==e[t+u])continue o;return this.options.record_delimiter.push(i[r]),this.state.recordDelimiterMaxLength=i[r].length,i[r].length}return 0},__error:function(e){let{encoding:t,raw:r,skip_records_with_error:i}=this.options,n="string"==typeof e?Error(e):e;if(!i)return n;if(this.state.recordHasError=!0,void 0!==this.options.on_skip)try{this.options.on_skip(n,r?this.state.rawBuffer.toString(t):void 0)}catch(e){return e}},__infoDataSet:function(){return{...this.info,columns:this.options.columns}},__infoRecord:function(){let{columns:e,raw:t,encoding:r}=this.options;return{...this.__infoDataSet(),bytes_records:this.info.bytes,error:this.state.error,header:!0===e,index:this.state.record.length,raw:t?this.state.rawBuffer.toString(r):void 0}},__infoField:function(){let{columns:e}=this.options,t=Array.isArray(e),r=this.info.bytes_records;return{...this.__infoRecord(),bytes_records:r,column:!0===t?e.length>this.state.record.length?e[this.state.record.length].name:null:this.state.record.length,quoting:this.state.wasQuoting}}}},tb=function(e,t={}){"string"==typeof e&&(e=Buffer.from(e));let r=t&&t.objname?{}:[],i=t_(t),n=i.parse(e,!0,e=>{void 0===i.options.objname?r.push(e):r[e[0]]=e[1]},()=>{});if(void 0!==n)throw n;return r},tv=/\\(\\)?/g,tC=RegExp("[^.[\\]]+|\\[(?:([^\"'][^[]*)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))","g"),tD=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,tF=/^\w*$/,tw=function(e){var t;let r=typeof e;return"symbol"===r||"object"===r&&e&&"[object Symbol]"===(t=e,Object.prototype.toString.call(t))},tB=function(e,t){if(Array.isArray(e))return!1;let r=typeof e;return!!("number"===r||"symbol"===r||"boolean"===r||!e||tw(e))||tF.test(e)||!tD.test(e)||null!=t&&e in Object(t)},tx=function(e){let t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(tC,function(e,r,i,n){let u=e;i?u=n.replace(tv,"$1"):r&&(u=r.trim()),t.push(u)}),t},tS=function(e){if("string"==typeof e||tw(e))return e;let t=`${e}`;return"0"==t&&1/e==-1/0?"-0":t},tT=function(e,t){var r,i;r=t,i=e;let n=0,u=(t=Array.isArray(r)?r:tB(r,i)?[r]:tx(r)).length;for(;null!=e&&n<u;)e=e[tS(t[n++])];return n&&n===u?e:void 0},tI=function(e){if(null==e)return[void 0,void 0];if("object"!=typeof e)return[Error('Invalid option "columns": expect an array or an object')];if(Array.isArray(e)){let t=[];for(let r of e)if("string"==typeof r)t.push({key:r,header:r});else{if("object"!=typeof r||null===r||Array.isArray(r))return[Error("Invalid column definition: expect a string or an object")];if(!r.key)return[Error('Invalid column definition: property "key" is required')];void 0===r.header&&(r.header=r.key),t.push(r)}e=t}else{let t=[];for(let r in e)t.push({key:r,header:e[r]});e=t}return[void 0,e]};class tO extends Error{constructor(e,t,...r){for(const i of(Array.isArray(t)&&(t=t.join(" ")),super(t),void 0!==Error.captureStackTrace&&Error.captureStackTrace(this,tO),this.code=e,r))for(const e in i){const t=i[e];this[e]=Buffer.isBuffer(t)?t.toString():null==t?t:JSON.parse(JSON.stringify(t))}}}let tk=function(e){let t={};for(let r in e)t[r.replace(/([A-Z])/g,function(e,t){return"_"+t.toLowerCase()})]=e[r];if(void 0===t.bom||null===t.bom||!1===t.bom)t.bom=!1;else if(!0!==t.bom)return[new tO("CSV_OPTION_BOOLEAN_INVALID_TYPE",["option `bom` is optional and must be a boolean value,",`got ${JSON.stringify(t.bom)}`])];if(void 0===t.delimiter||null===t.delimiter)t.delimiter=",";else if(Buffer.isBuffer(t.delimiter))t.delimiter=t.delimiter.toString();else if("string"!=typeof t.delimiter)return[new tO("CSV_OPTION_DELIMITER_INVALID_TYPE",["option `delimiter` must be a buffer or a string,",`got ${JSON.stringify(t.delimiter)}`])];if(void 0===t.quote||null===t.quote)t.quote='"';else if(!0===t.quote)t.quote='"';else if(!1===t.quote)t.quote="";else if(Buffer.isBuffer(t.quote))t.quote=t.quote.toString();else if("string"!=typeof t.quote)return[new tO("CSV_OPTION_QUOTE_INVALID_TYPE",["option `quote` must be a boolean, a buffer or a string,",`got ${JSON.stringify(t.quote)}`])];if((void 0===t.quoted||null===t.quoted)&&(t.quoted=!1),void 0===t.escape_formulas||null===t.escape_formulas)t.escape_formulas=!1;else if("boolean"!=typeof t.escape_formulas)return[new tO("CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE",["option `escape_formulas` must be a boolean,",`got ${JSON.stringify(t.escape_formulas)}`])];if((void 0===t.quoted_empty||null===t.quoted_empty)&&(t.quoted_empty=void 0),void 0===t.quoted_match||null===t.quoted_match||!1===t.quoted_match?t.quoted_match=null:Array.isArray(t.quoted_match)||(t.quoted_match=[t.quoted_match]),t.quoted_match)for(let e of t.quoted_match){let r="string"==typeof e,i=e instanceof RegExp;if(!r&&!i)return[new tO("CSV_OPTION_QUOTED_MATCH",["option `quoted_match` must be a string or a regex,",`got ${JSON.stringify(t.quoted_match)}`])]}if((void 0===t.quoted_string||null===t.quoted_string)&&(t.quoted_string=!1),(void 0===t.eof||null===t.eof)&&(t.eof=!0),void 0===t.escape||null===t.escape)t.escape='"';else if(Buffer.isBuffer(t.escape))t.escape=t.escape.toString();else if("string"!=typeof t.escape)return[Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(t.escape)}`)];if(t.escape.length>1)return[Error(`Invalid Option: escape must be one character, got ${t.escape.length} characters`)];if(void 0===t.header||null===t.header||!1===t.header)t.header=!1;else if(!0!==t.header)throw new tO("CSV_INVALID_OPTION_HEADER",["option `header` is expected to be a boolean,",`got ${JSON.stringify(t.header)}`],t);if(void 0===t.header_as_comment||null===t.header_as_comment||!1===t.header_as_comment)t.header_as_comment=!1;else if(!0===t.header_as_comment)t.header_as_comment="#";else if(Buffer.isBuffer(t.header_as_comment))t.header_as_comment=t.header_as_comment.toString();else if("string"!=typeof t.header_as_comment)throw new tO("CSV_INVALID_OPTION_HEADER_AS_COMMENT",["option `header_as_comment` must be a boolean, a string or a buffer,",`got ${JSON.stringify(t.header_as_comment)}`],t);let[r,i]=tI(t.columns);if(void 0!==r)return[r];if(t.columns=i,(void 0===t.quoted||null===t.quoted)&&(t.quoted=!1),(void 0===t.cast||null===t.cast)&&(t.cast={}),(void 0===t.cast.bigint||null===t.cast.bigint)&&(t.cast.bigint=e=>""+e),(void 0===t.cast.boolean||null===t.cast.boolean)&&(t.cast.boolean=e=>e?"1":""),(void 0===t.cast.date||null===t.cast.date)&&(t.cast.date=e=>""+e.getTime()),(void 0===t.cast.number||null===t.cast.number)&&(t.cast.number=e=>""+e),(void 0===t.cast.object||null===t.cast.object)&&(t.cast.object=e=>JSON.stringify(e)),(void 0===t.cast.string||null===t.cast.string)&&(t.cast.string=function(e){return e}),void 0!==t.on_record&&"function"!=typeof t.on_record)return[Error('Invalid Option: "on_record" must be a function.')];if(void 0===t.record_delimiter||null===t.record_delimiter)t.record_delimiter="\n";else if(Buffer.isBuffer(t.record_delimiter))t.record_delimiter=t.record_delimiter.toString();else if("string"!=typeof t.record_delimiter)return[Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(t.record_delimiter)}`)];switch(t.record_delimiter){case"unix":t.record_delimiter="\n";break;case"mac":t.record_delimiter="\r";break;case"windows":t.record_delimiter="\r\n";break;case"ascii":t.record_delimiter="\x1e";break;case"unicode":t.record_delimiter="\u2028"}return[void 0,t]},tR=Buffer.from([239,187,191]),tP=function(e,t={}){let r=[],[i,n]=tk(t);if(void 0!==i)throw i;let u={options:n,state:{stop:!1},info:{records:0},__transform:function(e,t){let r,i;if(!Array.isArray(e)&&"object"!=typeof e)return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(e)}`);if(0===this.info.records){if(Array.isArray(e)){if(!0===this.options.header&&void 0===this.options.columns)return Error("Undiscoverable Columns: header option requires column option or object records")}else if(void 0===this.options.columns){let[t,r]=tI(Object.keys(e));if(t)return;this.options.columns=r}}if(0===this.info.records){this.bom(t);let e=this.headers(t);if(e)return e}try{this.options.on_record&&this.options.on_record(e,this.info.records)}catch(e){return e}if(this.options.eof){if([r,i]=this.stringify(e),r)return r;if(void 0===i)return;i+=this.options.record_delimiter}else{if([r,i]=this.stringify(e),r)return r;if(void 0===i)return;(this.options.header||this.info.records)&&(i=this.options.record_delimiter+i)}this.info.records++,t(i)},stringify:function(e,t=!1){if("object"!=typeof e)return[void 0,e];let{columns:r}=this.options,i=[];if(Array.isArray(e)){r&&e.splice(r.length);for(let r=0;r<e.length;r++){let n=e[r],[u,o]=this.__cast(n,{index:r,column:r,records:this.info.records,header:t});if(u)return[u];i[r]=[o,n]}}else for(let n=0;n<r.length;n++){let u=tT(e,r[n].key),[o,s]=this.__cast(u,{index:n,column:r[n].key,records:this.info.records,header:t});if(o)return[o];i[n]=[s,u]}let n="";for(let e=0;e<i.length;e++){let t,r,[o,s]=i[e];if("string"==typeof o)t=this.options;else{var u;if("object"!=typeof(u=o)||null===u||Array.isArray(u))if(null!=o)return[Error(`Invalid Casting Value: returned value must return a string, an object, null or undefined, got ${JSON.stringify(o)}`)];else t=this.options;else{if(o=(t=o).value,delete t.value,"string"!=typeof o&&null!=o&&r)return[Error(`Invalid Casting Value: returned value must return a string, null or undefined, got ${JSON.stringify(o)}`)];if(t={...this.options,...t},[r,t]=tk(t),void 0!==r)return[r]}}let{delimiter:a,escape:l,quote:c,quoted:d,quoted_empty:p,quoted_string:h,quoted_match:f,record_delimiter:m,escape_formulas:g}=t;if(""===o&&""===s){let e=f&&f.filter(e=>"string"==typeof e?-1!==o.indexOf(e):e.test(o));!0===((e=e&&e.length>0)||!0===p||!0===h&&!1!==p)&&(o=c+o+c),n+=o}else if(o){if("string"!=typeof o)return[Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(o)}`)];let e=a.length&&o.indexOf(a)>=0,t=""!==c&&o.indexOf(c)>=0,r=o.indexOf(l)>=0&&l!==c,i=o.indexOf(m)>=0,u=h&&"string"==typeof s,p=f&&f.filter(e=>"string"==typeof e?-1!==o.indexOf(e):e.test(o));if(p=p&&p.length>0,g)switch(o[0]){case"=":case"+":case"-":case"@":case" ":case"\r":case"=":case"+":case"-":case"@":o=`'${o}`}let A=!0===t||e||i||d||u||p;if(!0===A&&!0===r){let e="\\"===l?RegExp(l+l,"g"):RegExp(l,"g");o=o.replace(e,l+l)}if(!0===t){let e=RegExp(c,"g");o=o.replace(e,l+c)}!0===A&&(o=c+o+c),n+=o}else(!0===p||""===s&&!0===h&&!1!==p)&&(n+=c+c);e!==i.length-1&&(n+=a)}return[void 0,n]},bom:function(e){!0===this.options.bom&&e(tR)},headers:function(e){let t;if(!1===this.options.header||void 0===this.options.columns)return;let r=this.options.columns.map(e=>e.header);if(this.options.eof?([t,r]=this.stringify(r,!0),r+=this.options.record_delimiter):[t,r]=this.stringify(r),t)return t;this.options.header_as_comment&&(r=this.options.header_as_comment+" "+r),e(r)},__cast:function(e,t){let r=typeof e;try{if("string"===r)return[void 0,this.options.cast.string(e,t)];if("bigint"===r)return[void 0,this.options.cast.bigint(e,t)];if("number"===r)return[void 0,this.options.cast.number(e,t)];else if("boolean"===r)return[void 0,this.options.cast.boolean(e,t)];else if(e instanceof Date)return[void 0,this.options.cast.date(e,t)];else if("object"===r&&null!==e)return[void 0,this.options.cast.object(e,t)];else return[void 0,e,e]}catch(e){return[e]}}};for(let t of e){let e=u.__transform(t,function(e){r.push(e)});if(void 0!==e)throw e}if(0===r.length){u.bom(e=>{r.push(e)});let e=u.headers(e=>{r.push(e)});if(void 0!==e)throw e}return r.join("")};function tL(e,t){var r,i;let n,u=(0,I.resolve)(e),o=(0,I.resolve)(u,t);if(r=u,i=o,n=r.endsWith(I.sep)?r:`${r}${I.sep}`,!(i===r||i.startsWith(n)))throw new l(`Storage path escapes baseDir: ${t}`,{error:"INVALID_STORAGE_PATH",details:{baseDir:u,filePath:t,resolvedPath:o}});return o}async function tN(e,t){await (0,th.mkdir)((0,I.dirname)(e),{recursive:!0,mode:t})}var tj=((H={}).NotFound="ENOENT",H.StorageError="FILE_STORAGE_ERROR",H.InvalidJson="INVALID_JSON",H.InvalidCsv="INVALID_CSV",H),t$=((z={}).ReadText="readText",z.WriteText="writeText",z.Remove="remove",z.ReadJson="readJson",z.WriteJson="writeJson",z.ReadCsv="readCsv",z.WriteCsv="writeCsv",z);class tM extends l{filePath;operation;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="FileStorageError",this.filePath=t.filePath,this.operation=t.operation}}class tU extends tM{constructor(e,t,r){super(`File not found: ${e}`,{cause:r,code:"ENOENT",filePath:e,operation:t}),this.name="FileNotFoundError"}}let tq=Object.values(tj),tV=f("ENOENT");function tH(e,t,r){var i;return h(e,tq)?e:(i=e)instanceof Error&&"string"==typeof i.code&&"ENOENT"===e.code?new tU(t,r,e):new tM(`Failed to ${r} for file: ${t}`,{cause:e,code:"FILE_STORAGE_ERROR",filePath:t,operation:r})}function tz(e,t,r){let i=e??t;if(!Number.isInteger(i)||i<=0)throw TypeError(`${r} must be a positive integer`);return i}async function tG(e,t){try{let r=await (0,th.stat)(e);Date.now()-r.mtimeMs>t&&await (0,th.unlink)(e)}catch(e){if("ENOENT"!==e.code)throw e}}async function tW(e,t,r={}){let{retryMs:i,staleMs:n,timeoutMs:u}=function(e){let t={retryMs:tz(e.retryMs,50,"retryMs"),staleMs:tz(e.staleMs,15e3,"staleMs"),timeoutMs:tz(e.timeoutMs,2e4,"timeoutMs")};if(t.staleMs>t.timeoutMs)throw TypeError("staleMs must be less than or equal to timeoutMs");return t}(r),o=(0,I.resolve)(e),s=Date.now()+u;for(await tN(o);;)try{let e=await (0,th.open)(o,"wx",384);await e.close();break}catch(e){if("EEXIST"!==e.code)throw e;if(await tG(o,n),Date.now()>=s)throw new tM(`Timed out acquiring file lock: ${o}`,{cause:e,code:tj.StorageError,filePath:o,operation:t$.WriteText});await _(i)}try{return await t()}finally{await (0,th.unlink)(o).catch(e=>{if("ENOENT"!==e.code)throw e})}}class tJ{baseDir;constructor(e){if(this.baseDir=(0,I.resolve)(e.baseDir),!1!==e.baseDirMode){const t=e.baseDirMode;if(void 0!==t&&!function(e){return"number"==typeof e&&Number.isInteger(e)&&e>=0}(t))throw TypeError("baseDirMode must be a non-negative integer");(0,O.mkdirSync)(this.baseDir,{recursive:!0,mode:t}),void 0!==t&&(511&(0,O.statSync)(this.baseDir).mode)!==t&&(0,O.chmodSync)(this.baseDir,t)}}async readText(e,t="utf8"){let r=tL(this.baseDir,e);try{return await (0,th.readFile)(r,{encoding:t})}catch(e){throw tH(e,r,t$.ReadText)}}async writeText(e,t,r={}){let i=r.encoding??"utf8",{mode:n}=r,u=tL(this.baseDir,e),o=(0,I.join)((0,I.dirname)(u),`.${(0,I.basename)(u)}.${(0,td.randomUUID)()}.tmp`);try{await tN(u),await (0,th.writeFile)(o,t,{encoding:i,mode:n}),void 0!==n&&await (0,th.chmod)(o,n),await (0,th.rename)(o,u)}catch(e){throw await (0,th.rm)(o,{force:!0}).catch(()=>void 0),tH(e,u,t$.WriteText)}}async remove(e){let t=tL(this.baseDir,e);try{await (0,th.rm)(t)}catch(e){throw tH(e,t,t$.Remove)}}async readJson(e,t="utf8"){let r=tL(this.baseDir,e),i=await this.readText(e,t);try{return JSON.parse(i)}catch(e){throw new tM(`Failed to parse JSON file: ${r}`,{cause:e,code:tj.InvalidJson,filePath:r,operation:t$.ReadJson})}}async writeJson(e,t,r={}){let i=r.encoding??"utf8",n=r.spaces??2,u=`${JSON.stringify(t,null,n)}
|
|
31
31
|
`;await this.writeText(e,u,{encoding:i,mode:r.mode})}async readCsv(e,t={}){let r=tL(this.baseDir,e),i=await this.readText(e),n=t.delimiter??",";try{if(!1===t.hasHeader)return tb(i,{bom:!0,delimiter:n,relax_column_count:!0,skip_empty_lines:!0});return tb(i,{bom:!0,columns:!0,delimiter:n,relax_column_count:!0,skip_empty_lines:!0})}catch(e){throw new tM(`Failed to parse CSV file: ${r}`,{cause:e,code:tj.InvalidCsv,filePath:r,operation:t$.ReadCsv})}}async writeCsv(e,t,r={}){let i=r.encoding??"utf8",n=r.delimiter??",";try{let u="";0===t.length?r.header?.length&&(u=tP([],{columns:r.header,delimiter:n,header:!0})):u=Array.isArray(t[0])?tP(t,{delimiter:n}):tP(t,{columns:r.header??Array.from(new Set(t.flatMap(e=>Object.keys(e)))),delimiter:n,header:!0}),await this.writeText(e,u.endsWith("\n")?u:`${u}
|
|
32
|
-
`,{encoding:i,mode:r.mode})}catch(r){if(h(r,tq))throw r;let t=tL(this.baseDir,e);throw new tM(`Failed to write CSV file: ${t}`,{cause:r,code:tj.StorageError,filePath:t,operation:t$.WriteCsv})}}}var tY=((G={}).KeyNotFound="KEY_NOT_FOUND",G.DataNotFound="DATA_NOT_FOUND",G.DecryptionFailed="DECRYPTION_FAILED",G.KeyStorageError="KEY_STORAGE_ERROR",G.DataStorageError="DATA_STORAGE_ERROR",G.InvalidJson="INVALID_JSON",G.InvalidEnvelope="INVALID_ENVELOPE",G.KeychainTimeout="KEYCHAIN_TIMEOUT",G),tK=((W={}).ReadText="readText",W.WriteText="writeText",W.ReadJson="readJson",W.WriteJson="writeJson",W.Remove="remove",W.Clear="clear",W.ReadKey="readKey",W.WriteKey="writeKey",W.RemoveKey="removeKey",W);class tX extends l{filePath;operation;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="SensitiveStorageError",this.filePath=t.filePath,this.operation=t.operation}}class tQ extends tX{constructor(e={}){super("Sensitive storage key not found",{cause:e.cause,code:"KEY_NOT_FOUND",filePath:e.filePath,operation:e.operation??"readKey"}),this.name="SensitiveKeyNotFoundError"}}class tZ extends tX{constructor(e,t,r){super(`Sensitive data not found: ${e}`,{cause:r,code:"DATA_NOT_FOUND",filePath:e,operation:t}),this.name="SensitiveDataNotFoundError"}}class t1 extends tX{constructor(e,t,r){super(`Failed to decrypt sensitive data: ${e}`,{cause:r,code:"DECRYPTION_FAILED",filePath:e,operation:t}),this.name="SensitiveDecryptionError"}}class t2 extends tX{constructor(e,t,r){super(`Invalid sensitive data envelope: ${e}`,{cause:r,code:"INVALID_ENVELOPE",filePath:e,operation:t}),this.name="SensitiveEnvelopeError"}}class t0 extends tX{constructor(e,t){super(e,{cause:t.cause,code:t.code??"KEY_STORAGE_ERROR",filePath:t.filePath,operation:t.operation}),this.name="SensitiveKeyStorageError"}}class t3 extends t0{timeoutMs;constructor(e,t,r){super(`Keychain access timed out after ${t}ms`,{cause:r,code:"KEYCHAIN_TIMEOUT",operation:e}),this.name="KeychainTimeoutError",this.timeoutMs=t}}f("KEYCHAIN_TIMEOUT");let t6=f("KEY_NOT_FOUND"),t4=f("DATA_NOT_FOUND");function t8(e){return e?e.split(",").map(e=>e.trim()).filter(e=>""!==e):[]}f("DECRYPTION_FAILED"),f("INVALID_ENVELOPE");let t9=/^\d{4}-\d{2}-\d{2}$/,t7=/^\d{4}(0[1-9]|1[0-2])$/,t5=/^-?(0|[1-9]\d*)$/,re=/^[1-9]\d*$/;var rt=((J={}).InvalidEnum="INVALID_ENUM",J.InvalidIntList="INVALID_INT_LIST",J.InvalidDate="INVALID_DATE",J.InvalidRange="INVALID_RANGE",J.InvalidPositiveInt="INVALID_POSITIVE_INT",J.InvalidDateRange="INVALID_DATE_RANGE",J.OutOfLookback="OUT_OF_LOOKBACK",J.InvalidTimestamp="INVALID_TIMESTAMP",J.InvalidTimestampRange="INVALID_TIMESTAMP_RANGE",J);function rr(e){return String(e).padStart(2,"0")}function ri(e){let t=e.getFullYear(),r=rr(e.getMonth()+1),i=rr(e.getDate());return`${t}-${r}-${i}`}function rn(e,t,r){if(void 0!==e&&!r.includes(e))throw new l(`参数 ${t} 取值非法: ${e}`,{error:"INVALID_ENUM",message:`${t} 只能取 ${r.join(" / ")}`})}function ru(e,t,r){if(void 0!==e){for(let i of t8(e))if(!r.includes(i))throw new l(`参数 ${t} 包含非法取值: ${i}`,{error:"INVALID_ENUM",message:`${t} 每一项只能取 ${r.join(" / ")}`})}}function ro(e,t){if(void 0!==e){for(let r of t8(e))if(!t5.test(r))throw new l(`参数 ${t} 包含非法取值: ${r}`,{error:"INVALID_INT_LIST",message:`${t} 每一项必须是整数,但包含非法值: ${r}`})}}function rs(e,t){if(void 0===e)return;let r=new Date(`${e}T00:00:00Z`);if(!t9.test(e)||Number.isNaN(r.getTime())||r.toISOString().slice(0,10)!==e)throw new l(`参数 ${t} 日期格式非法: ${e}`,{error:"INVALID_DATE",message:`${t} 必须为 YYYY-MM-DD 格式`})}function ra(e,t,r,i){if(void 0===e)return;let n=t5.test(e)?Number(e):NaN;if(!Number.isInteger(n)||n<r||n>i)throw new l(`参数 ${t} 超出范围: ${e}`,{error:"INVALID_RANGE",message:`${t} 必须是 ${r}~${i} 之间的整数`})}function rl(e,t){if(void 0!==e&&!re.test(e))throw new l(`参数 ${t} 非法: ${e}`,{error:"INVALID_POSITIVE_INT",message:`${t} 必须是正整数`})}function rc(e){let{startDate:t,endDate:r}=e,i=e.startField??"--start-date",n=e.endField??"--end-date";if(rs(t,i),rs(r,n),t&&r&&t>r)throw new l(`${i} 不能晚于 ${n}`,{error:"INVALID_DATE_RANGE",message:`${i}(${t}) 不能晚于 ${n}(${r})`});if(!1===e.allowFuture){let e=ri(new Date);for(let[u,o]of[[i,t],[n,r]])if(o&&o>e)throw new l(`${u} 不能晚于今天`,{error:"INVALID_DATE_RANGE",message:`${u}(${o}) 不能晚于今天(${e})`})}}function rd(e){let{startDate:t,endDate:r,maxLookbackDays:i,label:n,latestDateOffsetDays:u=0}=e,o=e.startField??"--start-date",s=e.endField??"--end-date";rc(e);let a=ri(new Date(Date.now()-864e5*u)),c=ri(new Date(Date.now()-864e5*i));for(let[e,d]of[[o,t],[s,r]])if(d){if(d>a){let t=0===u?"今天":a;throw new l(`${e} 不能晚于${t}`,{error:"INVALID_DATE_RANGE",message:`${e}(${d}) 不能晚于${t}`})}if(d<c)throw new l(`${n}仅支持最近 ${i} 天的数据`,{error:"OUT_OF_LOOKBACK",message:`${n}仅支持最近 ${i} 天的数据,${e}(${d}) 已超出范围`})}}function rp(e){let{startTime:t,endTime:r}=e,i=e.startField??"--start-time",n=e.endField??"--end-time",u="seconds"===(e.unit??"milliseconds")?"秒级 Unix 时间戳":"毫秒时间戳",o=[];for(let[e,s]of[[i,t],[n,r]])if(void 0!==s){if(!re.test(s))throw new l(`参数 ${e} 时间戳非法: ${s}`,{error:"INVALID_TIMESTAMP",message:`${e} 必须是正整数${u}`});o.push([e,BigInt(s)])}let s=o.find(([e])=>e===i)?.[1],a=o.find(([e])=>e===n)?.[1];if(void 0!==s&&void 0!==a&&s>a)throw new l(`${i} 不能晚于 ${n}`,{error:"INVALID_TIMESTAMP_RANGE",message:`${i} 不能晚于 ${n}`});return o}function rh(e){let t=rp(e);if(!1===e.allowFuture){let r=BigInt("seconds"===e.unit?Math.floor(Date.now()/1e3):Date.now());for(let[e,i]of t)if(i>r)throw new l(`${e} 不能晚于当前时间`,{error:"INVALID_TIMESTAMP_RANGE",message:`${e} 不能晚于当前时间`})}}function rf(e){let t=t8(e);return t.length>0?t:void 0}function rm(e){let t=rf(e);if(!t)return;let r=t.map(Number).filter(e=>!Number.isNaN(e));return r.length>0?r:void 0}function rg(e,t,r){let i=rf(e),n=String(r);if(!i||1===i.length&&i[0]===n)return;if(i.includes(n))throw new l(`${t} 的全部选项 ${n} 不能与其他枚举值同时使用`,{error:rt.InvalidEnum,message:`${t} 的枚举值 ${n} 表示全部,必须单独使用`});let u=i.find(e=>!t5.test(e));if(void 0!==u)throw new l(`参数 ${t} 包含非法取值: ${u}`,{error:rt.InvalidIntList,message:`${t} 每一项必须是整数,但包含非法值: ${u}`});return i.map(Number)}function rA(e,t){if(void 0===e)return t;let r=t5.test(e)?Number(e):NaN;return Number.isNaN(r)?t:r}function ry(e){if(null==e)return;let t=String(e).trim();if("number"==typeof e&&!Number.isSafeInteger(e)||!t5.test(t))return;let r=BigInt(t),i=r<0n?-r:r,n=String(i%100n).padStart(2,"0");return`${r<0n?"-":""}${i/100n}.${n}`}function rE(e){if("number"==typeof e&&Number.isInteger(e)&&e>0)return e;if("string"!=typeof e||!t5.test(e))return;let t=Number(e);return t>0?t:void 0}function r_(e){return String(e).padStart(2,"0")}function rb(e,t={}){if(void 0===e||""===e)return"";let{format:r="datetime",unit:i="s"}=t,n=Number(e);if(!Number.isFinite(n))return String(e);let u=new Date("s"===i?1e3*n:n);if(Number.isNaN(u.getTime()))return String(e);let o=u.getFullYear(),s=r_(u.getMonth()+1),a=r_(u.getDate());if("date"===r)return`${o}-${s}-${a}`;let l=r_(u.getHours()),c=r_(u.getMinutes()),d=r_(u.getSeconds());return`${o}-${s}-${a} ${l}:${c}:${d}`}function rv(e){return Object.values(e).filter(e=>"number"==typeof e).map(String)}function rC(e,t){let r=function(e){if(void 0===e||!t5.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0}(e);if(void 0!==r)return Object.values(t).filter(e=>"number"==typeof e).includes(r)?r:void 0}function rD(e,t){let r="number"==typeof t?t:t5.test(t)?Number(t):NaN;return"string"==typeof e[r]?String(e[r]):String(t)}let rF=new Set(["access_denied","expired_token","invalid_client","invalid_grant","unauthorized_client"]);var rw=((Y={}).InvalidArgument="INVALID_ARGUMENT",Y.PortUnavailable="PORT_UNAVAILABLE",Y.CallbackAborted="CALLBACK_ABORTED",Y.CallbackTimeout="CALLBACK_TIMEOUT",Y.CallbackError="CALLBACK_ERROR",Y.RequestAborted="REQUEST_ABORTED",Y.RequestTimeout="REQUEST_TIMEOUT",Y.NetworkError="NETWORK_ERROR",Y.HttpError="HTTP_ERROR",Y.InvalidResponse="INVALID_RESPONSE",Y.AuthorizationPending="AUTHORIZATION_PENDING",Y.SlowDown="SLOW_DOWN",Y.AccessDenied="ACCESS_DENIED",Y.ExpiredToken="EXPIRED_TOKEN",Y),rB=((K={}).GeneratePKCE="generatePKCE",K.GenerateState="generateState",K.BuildAuthUrl="buildAuthUrl",K.BuildLoopbackRedirectUri="buildLoopbackRedirectUri",K.GetAvailablePort="getAvailablePort",K.CreateLocalCallbackHandler="createLocalCallbackHandler",K.HandleLocalCallback="handleLocalCallback",K.ExchangeToken="exchangeToken",K.IntrospectToken="introspectToken",K.RevokeToken="revokeToken",K.FetchAuthorizationServerMetadata="fetchAuthorizationServerMetadata",K.DynamicClientRegistration="dynamicClientRegistration",K.StartDeviceAuthorization="startDeviceAuthorization",K.ExchangeDeviceCodeToken="exchangeDeviceCodeToken",K.PollDeviceToken="pollDeviceToken",K.CreateDeviceFlowSession="createDeviceFlowSession",K);class rx extends l{operation;status;constructor(e,t){super(e,{cause:t.cause,error:t.code,details:t.details}),this.name="OAuthError",this.operation=t.operation,this.status=t.status}}class rS extends rx{responseBody;responseJson;constructor(e,t={}){super(e,{cause:t.cause,code:t.code??"HTTP_ERROR",operation:"exchangeToken",status:t.status,details:t.details}),this.name="OAuthTokenExchangeError",this.responseBody=t.responseBody,this.responseJson=t.responseJson}}class rT extends rx{responseBody;responseJson;constructor(e,t={}){super(e,{cause:t.cause,code:t.code??"HTTP_ERROR",operation:"introspectToken",status:t.status,details:t.details}),this.name="OAuthTokenIntrospectionError",this.responseBody=t.responseBody,this.responseJson=t.responseJson}}class rI extends rx{responseBody;responseJson;constructor(e,t={}){super(e,{cause:t.cause,code:t.code??"HTTP_ERROR",operation:"revokeToken",status:t.status,details:t.details}),this.name="OAuthTokenRevocationError",this.responseBody=t.responseBody,this.responseJson=t.responseJson}}class rO extends rx{providerError;providerErrorDescription;responseBody;responseJson;constructor(e,t={}){super(e,{cause:t.cause,code:t.code??"HTTP_ERROR",operation:t.operation??"pollDeviceToken",status:t.status,details:t.details}),this.name="OAuthDeviceFlowError",this.providerError=t.providerError,this.providerErrorDescription=t.providerErrorDescription,this.responseBody=t.responseBody,this.responseJson=t.responseJson}}let rk=Object.values(rw);function rR(e){if(!h(e,rk)||"exchangeToken"!==e.operation)return!1;let t=e.responseJson,r=t?.error;return"string"==typeof r&&rF.has(r)}var rP=((X={}).NotFound="NOT_FOUND",X.InvalidShape="INVALID_SHAPE",X.AccessTokenExpired="ACCESS_TOKEN_EXPIRED",X.RefreshTokenExpired="REFRESH_TOKEN_EXPIRED",X.RefreshFailed="REFRESH_FAILED",X.StorageError="STORAGE_ERROR",X),rL=((Q={}).Read="read",Q.Save="save",Q.Clear="clear",Q.Refresh="refresh",Q);class rN extends l{operation;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="OAuthTokenStoreError",this.operation=t.operation}}Object.values(rP);let rj=f("NOT_FOUND");function r$(e){var t;return tl(e)&&(t=e.auth,!!tl(t)&&rq(t.accessToken)&&rq(t.refreshToken)&&rU(t.atExpiresAt)&&rU(t.rtExpiresAt)&&ts(t.scopes)&&t.scopes.every(tc))}function rM(e,t,r){if(!r(e))throw new rN("Invalid OAuth token snapshot shape",{code:rP.InvalidShape,operation:t})}function rU(e){return ta(e)&&Number.isInteger(e)&&e>0&&e<1e10}function rq(e){return tc(e)&&""!==e.trim()}function rV(e,t=Date.now()){return e<=Math.floor(t/1e3)}class rH{storage;fileName;expiryLeewaySec;refreshLockPath;refreshLockOptions;now;validate;cache;readInflight;refreshInflight;writeEpoch=0;constructor(e){this.storage=e.storage,this.fileName=e.fileName??"auth.json",this.expiryLeewaySec=e.expiryLeewaySec??60,this.refreshLockPath=void 0===e.refreshLockPath?(0,I.join)(this.storage.baseDir,`${this.fileName}.refresh.lock`):e.refreshLockPath,this.refreshLockOptions=e.refreshLockOptions,this.now=e.now??(()=>Date.now()),this.validate=e.validate??r$}async get(){return this.cache?this.cache.snapshot:(this.readInflight||(this.readInflight=this.loadFromStorage().finally(()=>{this.readInflight=void 0})),this.readInflight)}async tryGet(){try{return await this.get()}catch(e){if(rj(e))return;throw e}}async save(e){rM(e,rL.Save,this.validate),this.writeEpoch+=1;try{await this.storage.writeJson(this.fileName,e)}catch(e){throw new rN(`Failed to persist OAuth token snapshot: ${this.fileName}`,{cause:e,code:rP.StorageError,operation:rL.Save})}this.cache={snapshot:e,loadedAt:this.now()}}async clear(){this.writeEpoch+=1;try{try{await this.storage.remove(this.fileName)}catch(e){if(!t4(e))throw e}await this.storage.removeKey()}catch(e){throw new rN(`Failed to clear OAuth token snapshot: ${this.fileName}`,{cause:e,code:rP.StorageError,operation:rL.Clear})}this.cache=void 0,this.readInflight=void 0,this.refreshInflight=void 0,this.writeEpoch+=1}async getAccessToken(e){let t=await this.get();if(!this.isAccessTokenExpired(t.auth))return t.auth.accessToken;if(!e)throw new rN("OAuth access token has expired and no refresh function provided",{code:rP.AccessTokenExpired,operation:rL.Refresh});return(await this.refresh(t,e)).auth.accessToken}async refresh(e,t){return!1===this.refreshLockPath?this.refreshCurrent(e,t):tW(this.refreshLockPath,async()=>{this.invalidateCache();let r=await this.tryGet();if(!r)throw new rN(`OAuth token snapshot not found: ${this.fileName}`,{code:rP.NotFound,operation:rL.Read});return r.auth.accessToken!==e.auth.accessToken?r:this.refreshCurrent(r,t)},this.refreshLockOptions)}async refreshCurrent(e,t){if(this.isRefreshTokenExpired(e.auth))throw new rN("OAuth refresh token has expired, re-login is required",{code:rP.RefreshTokenExpired,operation:rL.Refresh});if(this.refreshInflight)return this.refreshInflight;let r=this.writeEpoch,i=(async()=>{let i;try{i=await t(e)}catch(e){throw new rN("Failed to refresh OAuth tokens",{cause:e,code:rP.RefreshFailed,operation:rL.Refresh})}if(this.writeEpoch!==r)throw new rN("OAuth token refresh result is stale",{code:rP.RefreshFailed,operation:rL.Refresh});return rM(i,rL.Refresh,this.validate),await this.save(i),i})().finally(()=>{this.refreshInflight===i&&(this.refreshInflight=void 0)});return this.refreshInflight=i,i}invalidateCache(){this.cache=void 0}isAccessTokenExpired(e){let t=Math.floor(this.now()/1e3);return e.atExpiresAt-this.expiryLeewaySec<=t}isRefreshTokenExpired(e){return rV(e.rtExpiresAt,this.now())}async loadFromStorage(){let e,t=this.writeEpoch;try{e=await this.storage.readJson(this.fileName)}catch(e){if(t4(e))throw new rN(`OAuth token snapshot not found: ${this.fileName}`,{cause:e,code:rP.NotFound,operation:rL.Read});throw new rN(`Failed to read OAuth token snapshot: ${this.fileName}`,{cause:e,code:rP.StorageError,operation:rL.Read})}return rM(e,rL.Read,this.validate),this.writeEpoch===t&&(this.cache={snapshot:e,loadedAt:this.now()}),e}}let rz=new e0,rG=new Set(["grant_type","client_id","code","redirect_uri","code_verifier","refresh_token","device_code","scope"]),rW=new Set(["client_id","scope","code_challenge","code_challenge_method"]);function rJ(e){return Array.isArray(e)?e.map(e=>e.trim()).filter(Boolean).join(" ")||void 0:e?.trim()||void 0}function rY(e,t,r,i){if(t)for(let[n,u]of Object.entries(t)){if(r.has(n.toLowerCase()))throw new rx(`extraParams cannot override reserved OAuth parameter: ${n}`,{code:rw.InvalidArgument,operation:i});rK(e,n,u)}}function rK(e,t,r){null!=r&&e.set(t,String(r))}function rX(e){if(e.trim())try{let t=JSON.parse(e);if(tl(t))return t;return}catch{return}}function rQ(e){return eY(e)?e.error===eG.Timeout?rw.RequestTimeout:e.error===eG.Aborted?rw.RequestAborted:rw.NetworkError:rw.NetworkError}function rZ(e,t,r){try{return new URL(e)}catch(e){throw new rx(`Invalid ${r}`,{cause:e,code:rw.InvalidArgument,operation:t})}}function r1(e,t,r){if(!tc(e)||""===e.trim())throw new rx(`${t} must be a non-empty string`,{code:rw.InvalidArgument,operation:r})}function r2(e,t,r){if(!Number.isInteger(e)||e<=0)throw new rx(`${t} must be a positive integer`,{code:rw.InvalidArgument,operation:r})}async function r0(e){let t={...e.headers,Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"};try{let{data:i}=await (e.httpClient??rz).send({url:e.endpoint.toString(),method:"POST",headers:t,data:e.body.toString(),timeoutMs:e.timeoutMs,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!i)throw new rO("OAuth device flow endpoint returned an empty response",{code:rw.InvalidResponse,operation:e.operation});let n=i.status,u=await i.text(),o=rX(u),s=tc(o?.error)?o.error:void 0,a=tc(o?.error_description)?o.error_description:void 0;if(void 0===n)throw new rO("OAuth device flow endpoint returned an invalid response",{code:rw.NetworkError,operation:e.operation,responseBody:u,responseJson:o});if(n>=500)throw new rO(`OAuth device flow endpoint returned HTTP ${n}`,{code:rw.HttpError,operation:e.operation,providerError:s,providerErrorDescription:a,responseBody:u,responseJson:o,status:n});if(s){var r;throw new rO(`OAuth device flow endpoint returned error: ${s}`,{code:(r=s,"authorization_pending"===r?rw.AuthorizationPending:"slow_down"===r?rw.SlowDown:"access_denied"===r?rw.AccessDenied:"expired_token"===r?rw.ExpiredToken:rw.InvalidResponse),operation:e.operation,providerError:s,providerErrorDescription:a,responseBody:u,responseJson:o,status:n})}if(n<200||n>=300)throw new rO(`OAuth device flow endpoint returned HTTP ${n}`,{code:rw.HttpError,operation:e.operation,responseBody:u,responseJson:o,status:n});if(!o)throw new rO("OAuth device flow endpoint returned a non-JSON response",{code:rw.InvalidResponse,operation:e.operation,responseBody:u,status:n});return o}catch(t){if(t instanceof rO)throw t;throw new rO("OAuth device flow request failed",{cause:t,code:rQ(t),operation:e.operation})}}function r3(e,t,r){let i=Math.min(e,Math.max(0,t-Date.now()));return i<=0?Promise.resolve():r?.aborted?Promise.reject(new rO("OAuth device token polling was aborted",{code:rw.RequestAborted,operation:rB.PollDeviceToken})):new Promise((e,t)=>{let n=setTimeout(()=>{r?.removeEventListener("abort",u),e()},i),u=()=>{clearTimeout(n),t(new rO("OAuth device token polling was aborted",{code:rw.RequestAborted,operation:rB.PollDeviceToken}))};r?.addEventListener("abort",u,{once:!0})})}function r6(e,t){r1(e.clientId,"clientId",rB.ExchangeDeviceCodeToken),r1(e.deviceCode,"deviceCode",rB.ExchangeDeviceCodeToken),r2(t,"timeoutMs",rB.ExchangeDeviceCodeToken),void 0!==e.codeVerifier&&r1(e.codeVerifier,"codeVerifier",rB.ExchangeDeviceCodeToken)}function r4(e,t){if(!tc(e)||""===e.trim())throw new rO(`${t} must be a non-empty string`,{code:rw.InvalidResponse,operation:rB.StartDeviceAuthorization})}function r8(e,t,r){if(!Number.isInteger(e)||e<=0)throw new rO(`${t} must be a positive integer`,{code:rw.InvalidResponse,operation:rB.StartDeviceAuthorization,responseJson:r})}function r9(e,t={}){let r=e.verification_uri_complete??e.verification_uri,i=[t.title??"请在浏览器中完成授权:",` ${t.authorizationUrlLabel??"授权地址"}: ${r}`];return e.verification_uri_complete||i.push(` ${t.userCodeLabel??"授权码"}: ${e.user_code}`),i.push("",t.waitingMessage??"授权完成前请保持当前命令运行,CLI 会自动继续。"),i}async function r7(e){let t=rZ(e.deviceAuthorizationEndpoint,rB.StartDeviceAuthorization,"deviceAuthorizationEndpoint"),r=e.timeoutMs??15e3;var i=e,n=r;if(r1(i.clientId,"clientId",rB.StartDeviceAuthorization),r2(n,"timeoutMs",rB.StartDeviceAuthorization),void 0!==i.codeChallenge&&r1(i.codeChallenge,"codeChallenge",rB.StartDeviceAuthorization),void 0!==i.codeChallengeMethod&&r1(i.codeChallengeMethod,"codeChallengeMethod",rB.StartDeviceAuthorization),void 0===i.codeChallenge!=(void 0===i.codeChallengeMethod))throw new rO("codeChallenge and codeChallengeMethod must be provided together",{code:rw.InvalidArgument,operation:rB.StartDeviceAuthorization});let u=new URLSearchParams;u.set("client_id",e.clientId),rK(u,"scope",rJ(e.scope)),rK(u,"code_challenge",e.codeChallenge),rK(u,"code_challenge_method",e.codeChallengeMethod),rY(u,e.extraParams,rW,rB.StartDeviceAuthorization);let o=await r0({body:u,endpoint:t,httpClient:e.httpClient,headers:e.headers,operation:rB.StartDeviceAuthorization,signal:e.signal,timeoutMs:r});var s=o;if(r4(s.device_code,"device_code"),r4(s.user_code,"user_code"),r4(s.verification_uri,"verification_uri"),void 0!==s.verification_uri_complete&&r4(s.verification_uri_complete,"verification_uri_complete"),"number"!=typeof s.expires_in)throw new rO("expires_in must be a positive integer",{code:rw.InvalidResponse,operation:rB.StartDeviceAuthorization,responseJson:s});if(r8(s.expires_in,"expires_in",s),void 0!==s.interval){if("number"!=typeof s.interval)throw new rO("interval must be a positive integer",{code:rw.InvalidResponse,operation:rB.StartDeviceAuthorization,responseJson:s});r8(s.interval,"interval",s)}return o}async function r5(e){let t=rZ(e.tokenEndpoint,rB.ExchangeDeviceCodeToken,"tokenEndpoint"),r=e.timeoutMs??15e3;r6(e,r);let i=new URLSearchParams;i.set("grant_type","urn:ietf:params:oauth:grant-type:device_code"),i.set("client_id",e.clientId),i.set("device_code",e.deviceCode),rK(i,"code_verifier",e.codeVerifier),rY(i,e.extraParams,rG,rB.ExchangeDeviceCodeToken);let n=await r0({body:i,endpoint:t,httpClient:e.httpClient,headers:e.headers,operation:rB.ExchangeDeviceCodeToken,signal:e.signal,timeoutMs:r});if("string"!=typeof n.access_token||""===n.access_token.trim())throw new rO("OAuth device token response is missing access_token",{code:rw.InvalidResponse,operation:rB.ExchangeDeviceCodeToken,responseJson:n});return n}async function ie(e){var t,r,i,n,u;let o=e.intervalSeconds??5;t=e,r=o,r6(t,t.timeoutMs??15e3),r2(r,"intervalSeconds",rB.PollDeviceToken),void 0!==t.expiresInSeconds&&r2(t.expiresInSeconds,"expiresInSeconds",rB.PollDeviceToken),void 0!==t.pollTimeoutMs&&r2(t.pollTimeoutMs,"pollTimeoutMs",rB.PollDeviceToken);let s=1e3*o,a=Date.now(),l=void 0===e.expiresInSeconds?void 0:1e3*e.expiresInSeconds,c=(i=a,Math.min(void 0===(n=l)?1/0:i+n,void 0===(u=e.pollTimeoutMs)?i+(void 0===n?6e5:1/0):i+u));for(;Date.now()<c;)try{return await r5(e)}catch(t){if(!(t instanceof rO))throw t;if(t.error===rw.AuthorizationPending){await r3(s,c,e.signal);continue}if(t.error===rw.SlowDown){s+=5e3,await r3(s,c,e.signal);continue}if(t.error===rw.RequestTimeout||t.error===rw.NetworkError){await r3(s,c,e.signal);continue}throw t}throw new rO("Timed out waiting for OAuth device authorization",{code:rw.ExpiredToken,operation:rB.PollDeviceToken,details:{expiresInSeconds:e.expiresInSeconds,pollTimeoutMs:e.pollTimeoutMs}})}async function it(e){let t=function(e){if(void 0!==e.codeChallenge||void 0!==e.codeChallengeMethod){if(!e.codeChallenge||!e.codeChallengeMethod)throw new rO("codeChallenge and codeChallengeMethod must be provided together",{code:rw.InvalidArgument,operation:rB.CreateDeviceFlowSession});if(!e.codeVerifier)throw new rO("codeVerifier is required when custom PKCE parameters are provided",{code:rw.InvalidArgument,operation:rB.CreateDeviceFlowSession});return{codeVerifier:e.codeVerifier,codeChallenge:e.codeChallenge,codeChallengeMethod:e.codeChallengeMethod}}return function(e={}){let t=e.verifierByteLength??32;var r,i,n=t,u=rB.GeneratePKCE;if(!Number.isInteger(n)||n<32||n>96)throw new rx("verifierByteLength must be an integer between 32 and 96",{code:rw.InvalidArgument,operation:u});let o=(r=t,(0,td.randomBytes)(r).toString("base64url")),s=(i=o,(0,td.createHash)("sha256").update(i).digest("base64url"));return{codeVerifier:o,codeChallenge:s,codeChallengeMethod:"S256"}}({verifierByteLength:e.verifierByteLength})}(e),r=await r7({...e,codeChallenge:t.codeChallenge,codeChallengeMethod:t.codeChallengeMethod});return{authorization:r,codeVerifier:t.codeVerifier,codeChallenge:t.codeChallenge,codeChallengeMethod:t.codeChallengeMethod,pollToken:()=>ie({tokenEndpoint:e.tokenEndpoint,clientId:e.clientId,deviceCode:r.device_code,codeVerifier:t.codeVerifier,expiresInSeconds:r.expires_in,intervalSeconds:r.interval,extraParams:e.extraParams,headers:e.headers,timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient})}}function ir(e){return e.replace(/[^a-zA-Z0-9]+/g,"")}function ii(e,t,r){let i=e[t];if(tc(i)&&i.trim())return i;throw new rx(`OAuth response is missing ${t}`,{code:rw.InvalidResponse,operation:r,details:{field:t}})}async function iu(e){let t=rZ(e.url,e.operation,"url"),r={...e.headers,Accept:"application/json"};void 0!==e.body&&(r["Content-Type"]="application/json");try{let{data:u}=await (e.httpClient??rz).send({url:t.toString(),method:e.method,headers:r,data:e.body,timeoutMs:e.timeoutMs??15e3,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!u)throw new rx("OAuth endpoint returned an empty response",{code:rw.InvalidResponse,operation:e.operation});let o=u.status,s=await u.text(),a=rX(s);if(void 0===o||o<200||o>=300)throw new rx(`OAuth endpoint returned HTTP ${o??"unknown"}`,{code:rw.HttpError,operation:e.operation,status:o,details:{responseBody:s,responseJson:a}});var i=a,n=e.operation;if(tl(i))return i;throw new rx("OAuth endpoint returned an invalid JSON object",{code:rw.InvalidResponse,operation:n})}catch(t){if(t instanceof rx)throw t;throw new rx("OAuth request failed",{cause:t,code:rQ(t),operation:e.operation})}}async function io(e){let t,r=await iu({url:e.metadataEndpoint,method:"GET",headers:e.headers,timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient,operation:rB.FetchAuthorizationServerMetadata});return{issuer:tc(r.issuer)&&r.issuer.trim()?r.issuer.trim():void 0,tokenEndpoint:ii(r,"token_endpoint",rB.FetchAuthorizationServerMetadata),introspectionEndpoint:ii(r,"introspection_endpoint",rB.FetchAuthorizationServerMetadata),revocationEndpoint:ii(r,"revocation_endpoint",rB.FetchAuthorizationServerMetadata),deviceAuthorizationEndpoint:ii(r,"device_authorization_endpoint",rB.FetchAuthorizationServerMetadata),registrationEndpoint:ii(r,"registration_endpoint",rB.FetchAuthorizationServerMetadata),scopesSupported:(t=r.scopes_supported,ts(t)?t.filter(e=>tc(e)&&""!==e.trim()):[]),raw:r}}async function is(e){let t={...e.extraParams,client_name:e.clientName,grant_types:e.grantTypes??["urn:ietf:params:oauth:grant-type:device_code","refresh_token"],token_endpoint_auth_method:e.tokenEndpointAuthMethod??"none"};e.responseTypes&&(t.response_types=e.responseTypes);let r=await iu({url:e.registrationEndpoint,method:"POST",headers:e.headers,body:JSON.stringify(t),timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient,operation:rB.DynamicClientRegistration});return{clientId:ii(r,"client_id",rB.DynamicClientRegistration),raw:r}}async function ia(e){let t=rZ(e.tokenEndpoint,rB.ExchangeToken,"tokenEndpoint"),r=e.grantType??"authorization_code",i=e.timeoutMs??15e3;!function(e,t,r){if(r1(e.clientId,"clientId",rB.ExchangeToken),r2(r,"timeoutMs",rB.ExchangeToken),"authorization_code"===t){r1(e.code,"code",rB.ExchangeToken),r1(e.redirectUri,"redirectUri",rB.ExchangeToken),void 0!==e.codeVerifier&&r1(e.codeVerifier,"codeVerifier",rB.ExchangeToken);return}if("refresh_token"===t)return r1(e.refreshToken,"refreshToken",rB.ExchangeToken);throw new rx(`Unsupported OAuth grant type: ${t}`,{code:rw.InvalidArgument,operation:rB.ExchangeToken})}(e,r,i);let n=new URLSearchParams;n.set("grant_type",r),n.set("client_id",e.clientId),"authorization_code"===r?(n.set("code",e.code),n.set("redirect_uri",e.redirectUri),rK(n,"code_verifier",e.codeVerifier)):(n.set("refresh_token",e.refreshToken),rK(n,"scope",rJ(e.scope))),rY(n,e.extraParams,rG,rB.ExchangeToken);let u={...e.headers,Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"};try{let{data:r}=await (e.httpClient??rz).send({url:t.toString(),method:"POST",headers:u,data:n.toString(),timeoutMs:i,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!r)throw new rS("OAuth token endpoint returned an empty response",{code:rw.InvalidResponse});let o=r.status,s=await r.text(),a=rX(s),l=tc(a?.error)?a.error:void 0;if(void 0===o||o<200||o>=300)throw new rS(`OAuth token endpoint returned HTTP ${o??"unknown"}`,{code:rw.HttpError,responseBody:s,responseJson:a,status:o});if(l)throw new rS(`OAuth token endpoint returned error: ${l}`,{code:rw.InvalidResponse,responseBody:s,responseJson:a,status:o});if(!a)throw new rS("OAuth token endpoint returned a non-JSON response",{code:rw.InvalidResponse,responseBody:s,status:o});if(!tc(a.access_token)||""===a.access_token.trim())throw new rS("OAuth token response is missing access_token",{code:rw.InvalidResponse,responseBody:s,responseJson:a,status:o});return a}catch(e){if(e instanceof rS)throw e;throw new rS("OAuth token request failed",{cause:e,code:rQ(e)})}}async function il(e){var t,r,i;let n=rZ(e.introspectionEndpoint,rB.IntrospectToken,"introspectionEndpoint"),u=e.timeoutMs??15e3;t=e,r=u,r1(t.token,"token",rB.IntrospectToken),r1(t.clientId,"clientId",rB.IntrospectToken),r2(r,"timeoutMs",rB.IntrospectToken),void 0!==t.tokenTypeHint&&r1(t.tokenTypeHint,"tokenTypeHint",rB.IntrospectToken);let o=new URLSearchParams({token:e.token,token_type_hint:e.tokenTypeHint??"access_token",client_id:e.clientId}),s={...e.headers,Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"};try{let{data:t}=await (e.httpClient??rz).send({url:n.toString(),method:"POST",headers:s,data:o.toString(),timeoutMs:u,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!t)throw new rT("OAuth token introspection endpoint returned an empty response",{code:rw.InvalidResponse});let r=t.status,a=await t.text(),l=rX(a);if(void 0===r||r<200||r>=300)throw new rT(`OAuth token introspection endpoint returned HTTP ${r??"unknown"}`,{code:rw.HttpError,responseBody:a,responseJson:l,status:r});if(!l||"boolean"!=typeof l.active)throw new rT("OAuth token introspection response is invalid",{code:rw.InvalidResponse,responseBody:a,responseJson:l,status:r});return{active:(i=l).active,scope:id(i.scope),clientId:id(i.client_id),clientName:id(i.client_name),tokenType:id(i.token_type),exp:ip(i.exp),iat:ip(i.iat),sub:id(i.sub),raw:i}}catch(e){if(e instanceof rT)throw e;throw new rT("OAuth token introspection request failed",{cause:e,code:rQ(e)})}}async function ic(e){var t,r;let i=rZ(e.revocationEndpoint,rB.RevokeToken,"revocationEndpoint"),n=e.timeoutMs??15e3;t=e,r=n,r1(t.token,"token",rB.RevokeToken),r1(t.clientId,"clientId",rB.RevokeToken),r2(r,"timeoutMs",rB.RevokeToken),void 0!==t.tokenTypeHint&&r1(t.tokenTypeHint,"tokenTypeHint",rB.RevokeToken);let u=new URLSearchParams({token:e.token,client_id:e.clientId});rK(u,"token_type_hint",e.tokenTypeHint);let o={...e.headers,Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"};try{let{data:t}=await (e.httpClient??rz).send({url:i.toString(),method:"POST",headers:o,data:u.toString(),timeoutMs:n,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!t)throw new rI("OAuth token revocation endpoint returned an empty response",{code:rw.InvalidResponse});let r=t.status,s=await t.text(),a=rX(s);if(void 0===r||r<200||r>=300)throw new rI(`OAuth token revocation endpoint returned HTTP ${r??"unknown"}`,{code:rw.HttpError,responseBody:s,responseJson:a,status:r})}catch(e){if(e instanceof rI)throw e;throw new rI("OAuth token revocation request failed",{cause:e,code:rQ(e)})}}function id(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function ip(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function ih(e,t){let r=e[t];return r&&r.length>0?r:void 0}function im(e){var t,r,i,n,u,o,s,a;let c,d,p,h,f=e.appName,m=e.platform??process.platform,g="win32"===m?I.win32:I.posix,A="string"==typeof f?f.trim():"",y=A.split(/[\\/]+/);if(!A||g.isAbsolute(A)||y.includes(".."))throw new l("appName must be a non-empty string",{error:"INVALID_APP_NAME"});let E=e.homeDir??tp.homedir(),_=e.env??process.env;if("darwin"===m)return t=A,r=E,{configDir:I.join(r,"Library","Preferences",t),dataDir:I.join(r,"Library","Application Support",t),cacheDir:I.join(r,"Library","Caches",t),logDir:I.join(r,"Library","Logs",t),tempDir:I.join(tp.tmpdir(),t)};if("win32"===m){let e,t,r;return i=A,n=E,e=ih(u=_,"APPDATA")??I.join(n,"AppData","Roaming"),t=ih(u,"LOCALAPPDATA")??I.join(n,"AppData","Local"),r=ih(u,"TEMP")??tp.tmpdir(),{configDir:I.join(e,i,"Config"),dataDir:I.join(e,i,"Data"),cacheDir:I.join(t,i,"Cache"),logDir:I.join(t,i,"Log"),tempDir:I.join(r,i)}}return o=A,s=E,c=ih(a=_,"XDG_CONFIG_HOME")??I.join(s,".config"),d=ih(a,"XDG_DATA_HOME")??I.join(s,".local","share"),p=ih(a,"XDG_CACHE_HOME")??I.join(s,".cache"),h=ih(a,"XDG_STATE_HOME")??I.join(s,".local","state"),{configDir:I.join(c,o),dataDir:I.join(d,o),cacheDir:I.join(p,o),logDir:I.join(h,o,"logs"),tempDir:I.join(tp.tmpdir(),o)}}function ig(e){let t;function r(){let r,i;return t||(t=new tJ((r=e.dir??"dataDir",i=im(e),{baseDir:e.subDir?tL(i[r],e.subDir):i[r],baseDirMode:e.baseDirMode??448}))),t}return{get:r,readText:(e,t)=>r().readText(e,t),writeText:(e,t,i)=>r().writeText(e,t,i),remove:e=>r().remove(e),readJson:(e,t)=>r().readJson(e,t),writeJson:(e,t,i)=>r().writeJson(e,t,i),readCsv:(e,t)=>r().readCsv(e,t),writeCsv:(e,t,i)=>r().writeCsv(e,t,i)}}function iA(e){if(void 0===e)return;if("number"==typeof e)return Number.isSafeInteger(e)?e:void 0;if(!/^[+-]?\d+$/.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0}function iy(e){let t=iA(e.total),r=iA(e.page),i=iA(e.pageSize),n={unit:e.unit,returnedCount:e.returnedCount,total:t,page:r,pageSize:i,hasMore:e.hasMore??function(e,t,r){if(void 0!==e&&void 0!==t&&void 0!==r)return t*r<e}(t,r,i),nextCursor:e.nextCursor};return Object.values(n).some(e=>void 0!==e)?n:void 0}function iE(e){return String(e).padStart(2,"0")}function i_(e){return e.replace(/[^a-zA-Z0-9_-]+/g,"-")}async function ib(e){if(""===e.command.trim())throw new l("command must be a non-empty string",{error:"INVALID_COMMAND",message:"command 必须是非空字符串"});let t="data.csv",r="raw_response.json",i="summary.json",n=function(e){var t;let r,i,n,u,o,s,a,c=(r=(t=new Date).getFullYear(),i=iE(t.getMonth()+1),n=iE(t.getDate()),u=iE(t.getHours()),o=iE(t.getMinutes()),s=iE(t.getSeconds()),a=String(t.getMilliseconds()).padStart(3,"0"),`${r}-${i}-${n}_${u}-${o}-${s}_${a}`),d=`${i_(e.command)}-${c}`;if(e.outputDir){let t=(0,I.resolve)(e.outputDir);if((0,O.existsSync)(t)&&!(0,O.statSync)(t).isDirectory())throw new l(`输出路径不是目录: ${t}`,{error:"INVALID_OUTPUT_DIR",message:`--output-dir 必须是一个目录,但 ${t} 是文件`});return(0,I.resolve)(t,d)}return(0,I.resolve)(process.cwd(),`${i_(e.appName)}-output`,d)}(e),u=(0,I.resolve)(n,t),o=(0,I.resolve)(n,r),s=(0,I.resolve)(n,i),a=void 0===e.rows?void 0:function(e=[]){return e.map(e=>{let t={};for(let[r,i]of Object.entries(e))t[r]=null==i?"":String(i);return t})}(e.rows);await tN(s);let c=new tJ({baseDir:n});await Promise.all([...void 0===a?[]:[c.writeCsv(t,a,{header:e.csvHeader})],c.writeJson(r,e.rawResponse)]);let d={command:e.command,caller:e.caller,logId:e.logId,generatedAt:new Date().toISOString(),rowCount:a?.length,resultMeta:e.resultMeta,files:{csv:void 0===a?void 0:u,rawResponse:o}};return await c.writeJson(i,d),{summaryPath:s,csvPath:void 0===a?void 0:u,rawPath:o}}let iv="aes-256-gcm";function iC(e,t,r,i=iF(r)){let n=(0,td.randomBytes)(12),u=(0,td.createCipheriv)(iv,t,n);u.setAAD(i);let o=Buffer.concat([u.update(e),u.final()]);return{version:1,algorithm:iv,keyProvider:r,iv:n.toString("base64"),authTag:u.getAuthTag().toString("base64"),ciphertext:o.toString("base64")}}function iD(e,t,r){if(32!==t.length)throw Error(`Invalid sensitive storage key length: ${t.length}`);let i=(0,td.createDecipheriv)(iv,t,Buffer.from(e.iv,"base64"));return i.setAAD(r),i.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([i.update(Buffer.from(e.ciphertext,"base64")),i.final()])}function iF(e){return Buffer.from([1,iv,e].join(":"),"utf8")}function iw(e,t,r){return Buffer.from([1,iv,"scrypt",e,t,r].join(":"),"utf8")}function iB(e,t,r){return(0,td.scryptSync)(function(e,t){let{uid:r,gid:i}=function(){try{let e=(0,tp.userInfo)();return{uid:String(e.uid),gid:String(e.gid)}}catch{let e="unknown-uid",t="unknown-gid";try{e=String(process.getuid?.()??e)}catch{}try{t=String(process.getgid?.()??t)}catch{}return{uid:e,gid:t}}}(),n=(0,tp.platform)();return["open-game-cli-lib-ssfk-v1",e,t,n,(0,tp.arch)(),r,i].join("\n")}(e,t),r,32)}function ix(e){if(!(e instanceof Error))return!1;let t=e?.code;return!!(tc(t)&&/no\s*entry|not\s*found/i.test(t))||/no\s*entry|not\s*found|notfound|not found/i.test(e?.message)}var iS=((Z={}).Auto="auto",Z.Keychain="keychain",Z.File="file",Z),iT=((ee={}).Read="read",ee.Write="write",ee.Remove="remove",ee);let iI=new Map;async function iO(){return await import("@napi-rs/keyring")}async function ik(e,t){let r=iI.get(e)??Promise.resolve(),i=()=>void 0,n=new Promise(e=>{i=e}),u=r.then(()=>n,()=>n);iI.set(e,u),await r.catch(()=>void 0);try{return await t()}finally{i(),iI.get(e)===u&&iI.delete(e)}}class iR{baseDir;service;account;fallbackKeyFile;fileStorage;keyStrategy;keychainTimeoutMs;onKeychainPrompt;fallbackKeyLockPath;fallbackKeyLockOptions;fallbackKeyScopeId;constructor(e){this.baseDir=(0,I.resolve)(e.baseDir),this.service=e.service,this.account=e.account,this.fallbackKeyFile=e.fallbackKeyFile??".sensitive-storage-key",this.fileStorage=new tJ({baseDir:this.baseDir,baseDirMode:void 0===e.baseDirMode?448:e.baseDirMode}),this.keyStrategy=function(e){if(void 0===e)return iS.File;if(e===iS.Auto||e===iS.Keychain||e===iS.File)return e;throw TypeError(`keyStrategy must be one of: ${iS.File}, ${iS.Keychain}, ${iS.Auto}`)}(e.keyStrategy),this.keychainTimeoutMs=Math.max(0,e.keychainTimeoutMs??5e3),this.onKeychainPrompt=e.onKeychainPrompt,this.fallbackKeyLockPath=void 0===e.fallbackKeyLockPath?tL(this.baseDir,`${this.fallbackKeyFile}.lock`):e.fallbackKeyLockPath,this.fallbackKeyLockOptions=e.fallbackKeyLockOptions,this.fallbackKeyScopeId=function(e,t){return(0,td.createHash)("sha256").update(e).update("\0").update(t).digest("hex").slice(0,32)}(this.service,this.account)}async readText(e,t="utf8"){let r=tL(this.baseDir,e);return(await this.readEncryptedData(r,tK.ReadText)).toString(t)}async writeText(e,t,r={}){let i=r.encoding??"utf8",n=tL(this.baseDir,e);await this.writeEncryptedData(n,Buffer.from(t,i),tK.WriteText)}async readJson(e,t="utf8"){let r=tL(this.baseDir,e),i=await this.readEncryptedData(r,tK.ReadJson);try{return JSON.parse(i.toString(t))}catch(e){throw new tX(`Failed to parse sensitive JSON data: ${r}`,{cause:e,code:tY.InvalidJson,filePath:r,operation:tK.ReadJson})}}async writeJson(e,t,r={}){let i=r.encoding??"utf8",n=r.spaces??2,u=tL(this.baseDir,e),o=`${JSON.stringify(t,null,n)}
|
|
33
|
-
`;await this.writeEncryptedData(u,Buffer.from(o,i),tK.WriteJson)}async remove(e){let t=tL(this.baseDir,e);try{await this.fileStorage.remove(t)}catch(e){if(tV(e))throw new tZ(t,tK.Remove,e);throw new tX(`Failed to remove sensitive data: ${t}`,{cause:e,code:tY.DataStorageError,filePath:t,operation:tK.Remove})}}async removeKey(){let e;if(this.shouldUseKeychainOnRemove())try{let{AsyncEntry:e}=await iO(),t=new e(this.service,this.account);await this.runKeychainCall(()=>t.deleteCredential(),tK.RemoveKey,iT.Remove)}catch(t){t instanceof t3?e=t:ix(t)||(e=new t0("Failed to remove sensitive storage key from keychain",{cause:t,operation:tK.RemoveKey}))}if(this.shouldUseFileOnRemove()){let e=this.getFallbackKeyFilePath();try{await this.fileStorage.remove(e)}catch(t){if(!tV(t))throw new t0(`Failed to remove sensitive storage key file: ${e}`,{cause:t,filePath:e,operation:tK.RemoveKey})}}if(e)throw e}async readEncryptedData(e,t){let r=await this.tryReadEnvelope(e,t);if(!r)throw new tZ(e,t);this.assertReadableProvider(r.keyProvider,e,t);let i=await this.readKeyByProvider(r.keyProvider,e,t);try{return iD(r,i,iF(r.keyProvider))}catch(r){throw new t1(e,t,r)}}async writeEncryptedData(e,t,r){try{let{key:i,provider:n}=await this.resolveKeyForNewEnvelopeWithLock(e,r),u=iC(t,i,n);await this.fileStorage.writeJson(e,u,{encoding:"utf8",mode:384})}catch(t){if(t instanceof tX)throw t;throw new tX(`Failed to write sensitive data: ${e}`,{cause:t,code:tY.DataStorageError,filePath:e,operation:r})}}async resolveKeyForNewEnvelopeWithLock(e,t){return ik(this.getKeyResolutionLockId(),()=>this.resolveKeyForNewEnvelope(e,t))}getKeyResolutionLockId(){return[this.service,this.account,this.fallbackKeyFile].join("\0")}getFallbackKeyFilePath(){return tL(this.baseDir,`${this.fallbackKeyFile}.${this.fallbackKeyScopeId}.json`)}async resolveKeyForNewEnvelope(e,t){if(this.keyStrategy===iS.File){let e=(0,td.randomBytes)(32);return{key:await this.ensureFileKey(e),provider:"file"}}if(this.keyStrategy===iS.Keychain){let r=await this.tryReadReusableKey("keychain",e,t);if(r)return r;let i=(0,td.randomBytes)(32);return await this.writeKeyToKeychain(i),{key:i,provider:"keychain"}}let r=!1;try{let r=await this.tryReadReusableKey("keychain",e,t);if(r)return r}catch{r=!0}let i=await this.tryReadReusableKey("file",e,t);if(i)return i;let n=(0,td.randomBytes)(32);if(!r)try{return await this.writeKeyToKeychain(n),{key:n,provider:"keychain"}}catch{}return{key:await this.ensureFileKey(n),provider:"file"}}assertReadableProvider(e,t,r){if(this.keyStrategy===iS.Auto)return;let i=this.keyStrategyToProvider();if(e!==i)throw new t0(`Sensitive data key provider mismatch: expected ${i}, got ${e}`,{filePath:t,operation:r})}keyStrategyToProvider(){return this.keyStrategy===iS.Keychain?"keychain":"file"}shouldUseKeychainOnRemove(){return this.keyStrategy===iS.Auto||this.keyStrategy===iS.Keychain}shouldUseFileOnRemove(){return this.keyStrategy===iS.Auto||this.keyStrategy===iS.File}async readKeyByProvider(e,t,r){return"keychain"===e?await this.readKeyFromKeychain(t,r):await this.readKeyFromFile(t,r)}async tryReadReusableKey(e,t,r){try{return{key:await this.readKeyByProvider(e,t,r),provider:e}}catch(e){if(t6(e))return;throw e}}async tryReadEnvelope(e,t){let r;try{r=await this.fileStorage.readText(e,"utf8")}catch(r){if(tV(r))return;throw new tX(`Failed to read sensitive data: ${e}`,{cause:r,code:tY.DataStorageError,filePath:e,operation:t})}try{var i,n=r;let e=JSON.parse(n);if(1!==e.version||e.algorithm!==iv||(i=e.keyProvider,!["keychain","file"].includes(i))||!tc(e.iv)||!tc(e.authTag)||!tc(e.ciphertext))throw Error("Invalid sensitive data envelope");return e}catch(r){throw new t2(e,t,r)}}async ensureFileKey(e){return!1===this.fallbackKeyLockPath?this.createFileKeyIfMissing(e):tW(this.fallbackKeyLockPath,async()=>this.createFileKeyIfMissing(e),this.fallbackKeyLockOptions)}async createFileKeyIfMissing(e){let t=this.getFallbackKeyFilePath();try{return await this.readKeyFromFile(void 0,tK.ReadKey)}catch(e){if(!t6(e))throw e}let r=(0,td.randomBytes)(16),i=r.toString("base64"),n=iC(e,iB(this.service,this.account,r),"file",iw(this.service,this.account,i)),u={version:1,algorithm:iv,kdf:"scrypt",salt:i,iv:n.iv,authTag:n.authTag,encryptedKey:n.ciphertext};try{await this.fileStorage.writeJson(t,u,{encoding:"utf8",mode:384})}catch(e){throw new t0(`Failed to write sensitive storage key file: ${t}`,{cause:e,filePath:t,operation:tK.WriteKey})}return e}async readKeyFromKeychain(e,t){try{let{AsyncEntry:u}=await iO(),o=new u(this.service,this.account),s=await this.runKeychainCall(()=>o.getPassword(),t,iT.Read);if(!s)throw new tQ({filePath:e,operation:t});var r=s,i=e,n=t;let a=Buffer.from(r,"base64");if(32!==a.length)throw new t0(`Invalid sensitive storage key length: ${a.length}`,{filePath:i,operation:n});return a}catch(r){if(r instanceof tX)throw r;if(ix(r))throw new tQ({cause:r,filePath:e,operation:t});throw new t0("Failed to read sensitive storage key from keychain",{cause:r,filePath:e,operation:t})}}async writeKeyToKeychain(e){try{let{AsyncEntry:t}=await iO(),r=new t(this.service,this.account);await this.runKeychainCall(()=>r.setPassword(e.toString("base64")),tK.WriteKey,iT.Write)}catch(e){if(e instanceof tX)throw e;throw new t0("Failed to write sensitive storage key to keychain",{cause:e,operation:tK.WriteKey})}}async runKeychainCall(e,t,r){let i;if(this.onKeychainPrompt?.({operation:r,service:this.service,account:this.account,timeoutMs:this.keychainTimeoutMs}),this.keychainTimeoutMs<=0)return e();try{return await Promise.race([e(),new Promise((e,r)=>{i=setTimeout(()=>{r(new t3(t,this.keychainTimeoutMs))},this.keychainTimeoutMs),i.unref?.()})])}finally{i&&clearTimeout(i)}}async readKeyFromFile(e,t){let r,i=this.getFallbackKeyFilePath();try{r=await this.fileStorage.readText(i,"utf8")}catch(r){if(tV(r))throw new tQ({cause:r,filePath:e??i,operation:t});throw new t0(`Failed to read sensitive storage key file: ${i}`,{cause:h(r,tq)?r.cause??r:r,filePath:e??i,operation:t})}try{let e=function(e){let t=JSON.parse(e);if(1!==t.version||t.algorithm!==iv||"scrypt"!==t.kdf||!tc(t.salt)||!tc(t.iv)||!tc(t.authTag)||!tc(t.encryptedKey))throw Error("Invalid sensitive storage key envelope");return t}(r),t=iB(this.service,this.account,Buffer.from(e.salt,"base64")),i=iD({iv:e.iv,authTag:e.authTag,ciphertext:e.encryptedKey},t,iw(this.service,this.account,e.salt));if(32!==i.length)throw Error(`Invalid sensitive storage key length: ${i.length}`);return i}catch(r){throw new t0(`Failed to decrypt sensitive storage key file: ${i}`,{cause:r,filePath:e??i,operation:t})}}}let iP=/^[a-zA-Z0-9_-]+$/,iL=function(){1;return""}();function iN(e){return iL?`${e}:${iL}`:e}function ij(){return iL?`auth_${iL}`:"auth"}let i$=ig({appName:"dymg"}),iM=ig({appName:"dymg",subDir:ij()}),iU=new Set(["EACCES","EPERM","EROFS"]),iq=["读取"];function iV(e){return iq.some(t=>e.startsWith(t))}function iH(e){return!!function e(t,r=0){if(t&&!(r>8)){var i;if(t instanceof Error&&iU.has(t.code??""))return t;if("object"==typeof(i=t)&&null!==i&&"cause"in t)return e(t.cause,r+1)}}(e)}function iz(e,t){var r;if(!iH(e))throw e;throw new l(iV(t)?`${t}失败:无法访问或初始化登录态目录`:`${t}失败:登录态目录无写权限`,{cause:e,error:"AUTH_PERMISSION_DENIED",message:iV(r=t)?`${r}失败:当前终端无法访问或初始化登录态目录。`:`${r}失败:当前终端对登录态目录无写权限。`})}let iG="client.json",iW=!1;async function iJ(){try{var e=await iM.readJson(iG);if("string"==typeof e?.clientId&&e.clientId.trim())return{clientId:e.clientId.trim(),clientName:"string"==typeof e.clientName&&e.clientName.trim()?e.clientName.trim():void 0,clientIdIssuedAt:rE(e.clientIdIssuedAt),createdAt:D(e.createdAt)??Math.floor(Date.now()/1e3),updatedAt:D(e.updatedAt)??Math.floor(Date.now()/1e3)};throw new l("本地登录信息异常",{error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"})}catch(e){if(tV(e))return;if(p(e,tj.InvalidJson))throw new l("本地登录信息异常",{cause:e,error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"});iz(e,"读取登录配置")}}function iY(e){if(e)return{clientId:e.clientId,clientName:e.clientName,clientIdIssuedAt:e.clientIdIssuedAt}}async function iK(){return iW?e:(t||(t=(async()=>{try{let t=await iJ(),r=iY(t);return e=r,iW=!0,r}finally{t=void 0}})()),t)}async function iX(t){let r=Math.floor(Date.now()/1e3),i=await iJ(),n={clientId:t.clientId,clientName:t.clientName??i?.clientName,clientIdIssuedAt:t.clientIdIssuedAt??i?.clientIdIssuedAt,createdAt:i?.createdAt??r,updatedAt:r};try{await iM.writeJson(iG,n,{mode:384})}catch(e){iz(e,"保存登录配置")}e=iY(n),iW=!0}async function iQ(e){let t=await iK(),r=function(e){let t=ir((0,tp.hostname)().split(".")[0]??""),r="";try{r=ir((0,tp.userInfo)().username)}catch{r=ir(process.env.USER??process.env.USERNAME??"")}return t&&r?`${t}_${r}`:t||r||e}("dymg");if(t?.clientId)return t.clientId;if(!1===e.enableDynamicClientRegistration)return;let i=await is({registrationEndpoint:e.registrationEndpoint,clientName:r,timeoutMs:e.timeoutMs,httpClient:nl});return await iX({clientId:i.clientId,clientName:"string"==typeof i.raw.client_name&&i.raw.client_name.trim()?i.raw.client_name.trim():r,clientIdIssuedAt:rE(i.raw.client_id_issued_at)}),i.clientId}async function iZ(e={}){var t,r;let i=await io({metadataEndpoint:`${function(){let e="https://developer.open-douyin.com";if(!e)throw new l("当前 CLI 配置异常",{error:"MISSING_BASE_URL",message:"当前 CLI 配置异常,无法完成登录,请重新安装或重新构建后重试"});return e.replace(/\/+$/,"")}()}/mgplatform/api/apps/oauth/.well-known/oauth-authorization-server`,timeoutMs:e.timeoutMs,httpClient:nl}),n=(t=i.raw,r=i.scopesSupported,"string"==typeof t.scope&&t.scope.trim()?t.scope.trim():r.length>0?r.join(" "):void 0),u=await iQ({registrationEndpoint:i.registrationEndpoint,timeoutMs:e.timeoutMs,enableDynamicClientRegistration:e.enableDynamicClientRegistration});if(!u)throw new l("当前 CLI 配置异常",{error:"MISSING_OAUTH_CLIENT_ID",message:"当前 CLI 配置异常,无法完成登录,请重新安装或重新构建后重试"});return{clientId:u,scope:n,tokenEndpoint:i.tokenEndpoint,introspectionEndpoint:i.introspectionEndpoint,revocationEndpoint:i.revocationEndpoint,deviceAuthorizationEndpoint:i.deviceAuthorizationEndpoint}}let i1="profile.json",i2=function(e){let t;function r(){return t||(t=new rH(e())),t}return{get:()=>r().get(),tryGet:()=>r().tryGet(),save:e=>r().save(e),clear:()=>r().clear(),refresh:(e,t)=>r().refresh(e,t),getAccessToken:e=>r().getAccessToken(e),invalidateCache(){r().invalidateCache()},isAccessTokenExpired:e=>r().isAccessTokenExpired(e),isRefreshTokenExpired:e=>r().isRefreshTokenExpired(e)}}(()=>({storage:function(){let{dataDir:e}=im({appName:"dymg"});return new iR({baseDir:(0,I.join)(e,ij()),service:iN(e8),account:iN("default")})}(),fileName:"token.json"}));async function i0(){try{var e;let t;return e=await iM.readJson(i1),t=Math.floor(Date.now()/1e3),{uid:C(e?.uid),oauthAppId:C(e?.oauthAppId),oauthAppName:C(e?.oauthAppName),updatedAt:D(e?.updatedAt)??t}}catch(e){if(tV(e))return;throw e}}async function i3(e){try{await iM.writeJson(i1,e,{mode:384})}catch(e){iz(e,"保存登录信息")}}async function i6(e){let t=await i0(),r=function(e,t){let r={uid:t.uid??e?.uid,oauthAppId:t.oauthAppId??e?.oauthAppId,oauthAppName:t.oauthAppName??e?.oauthAppName,updatedAt:Math.floor(Date.now()/1e3)};if(r.uid||r.oauthAppId||r.oauthAppName)return r}(t,e);return r?(await i3(r),r):t}async function i4(){try{await iM.remove(i1)}catch(e){tV(e)||iz(e,"清理登录信息")}}function i8(e,t){try{return function(e,t={}){let r,i=Math.floor((t.nowMs??Date.now())/1e3),n=rE(e.expires_in)??t.defaultAccessTokenExpiresInSeconds??3600,u=rE(e.refresh_token_expires_in),o=id(e.refresh_token),s=o??t.current?.auth.refreshToken,a=void 0===e.scope?t.current?.auth.scopes??[]:(r=rJ(e.scope))?r.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[];if(!s)throw new rS("OAuth token response is missing refresh_token",{code:rw.InvalidResponse,responseJson:e});let l=void 0!==u?i+u:t.current&&void 0===o?t.current.auth.rtExpiresAt:i+(t.defaultRefreshTokenExpiresInSeconds??2592e3);return{auth:{accessToken:e.access_token,refreshToken:s,atExpiresAt:i+n,rtExpiresAt:l,scopes:a}}}(e,{current:t})}catch(e){throw new l("登录失败,请重新登录",{cause:e,error:"MISSING_REFRESH_TOKEN",message:`登录失败,请重新执行 ${e9}`})}}async function i9(e){await i6({uid:C(e.uid),oauthAppId:C(e.oauth_app_id),oauthAppName:C(e.oauth_app_name)})}async function i7(e){let t;try{t=await iZ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e9}`});throw e}let r=await ia({tokenEndpoint:t.tokenEndpoint,clientId:t.clientId,grantType:"refresh_token",refreshToken:e.auth.refreshToken,scope:e.auth.scopes,httpClient:nl});return await i9(r).catch(()=>void 0),i8(r,e)}function i5(e){var t;if(iH(e)&&iz(e,"刷新登录态"),p(e,"REFRESH_TOKEN_EXPIRED"))throw new l("当前登录已过期,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已过期,请执行 ${e9}`});if(p(t=e,"REFRESH_FAILED")&&rR(t.cause)||rR(e))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e9}`});throw e}async function ne(){try{return await i2.tryGet()}catch(e){throw iH(e)&&iz(e,"读取登录信息"),new l("本地登录信息异常",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`本地登录信息异常,请先执行 ${te},再执行 ${e9}`})}}async function nt(){if(await ne())try{return await i2.getAccessToken(i7)}catch(e){i5(e)}}async function nr(){let e=await ne();if(e)try{return(await i2.refresh(e,i7)).auth.accessToken}catch(e){i5(e)}}async function ni(e){let t;if(e){try{t=await iZ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))return;throw e}try{await ic({revocationEndpoint:t.revocationEndpoint,token:e.auth.refreshToken,tokenTypeHint:"refresh_token",clientId:t.clientId,httpClient:nl})}catch(e){throw new l("退出登录失败,请稍后重试",{cause:e,error:"AUTH_LOGOUT_REVOKE_FAILED",message:"退出登录失败,请检查网络后重试"})}}}async function nn(){let e,t,r=await nt();if(!r)return;try{e=await iZ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e9}`});throw e}try{t=await il({introspectionEndpoint:e.introspectionEndpoint,token:r,tokenTypeHint:"access_token",clientId:e.clientId,httpClient:nl})}catch(e){throw new l("登录态校验失败,请稍后重试或重新登录",{cause:e,error:"AUTH_STATUS_CHECK_FAILED",message:`登录态校验失败,请稍后重试;如问题持续,可执行 ${e9}`})}let i=function(e){let{raw:t}=e;return{...e,uid:C(t.uid),oauthAppId:C(t.oauth_app_id),oauthAppName:C(t.oauth_app_name)}}(t);if(!i.active)throw new l("当前登录已失效,请重新登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e9}`});return await i6({uid:i.uid,oauthAppId:i.oauthAppId,oauthAppName:i.oauthAppName}).catch(()=>void 0),i}async function nu(e,t){let r=i8(e,t);try{await Promise.all([i2.save(r),i9(e).catch(()=>void 0)])}catch(e){iz(e,"保存登录态")}return r}async function no(){try{await Promise.all([i2.clear(),i4()])}catch(e){iz(e,"退出登录")}}let ns=new e0,na=new e0,nl=new e0;function nc(e){return new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:e??`当前命令需要先登录,请先执行 ${e9}`})}function nd(){return new l("当前登录已失效,请重新登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e9}`})}function np(e){if("object"!=typeof e||null===e)return;let t=e.error,r=C(e.message);return{error:"number"==typeof t&&Number.isInteger(t)?t:void 0,message:r}}function nh(e){if(e?.trim())try{return np(JSON.parse(e))}catch{return}}function nf(e,t){let r={...t?.status!==void 0?{status:t.status}:{},...e?.error!==void 0?{error:e.error}:{}};if(e?.error===1002){let e=t?.unauthorizedAsExpired?nd():nc();throw new l(e.message,{cause:t?.cause,error:e.error,message:e.message,details:r})}if(e?.error===1004)throw new l("当前功能尚未开放",{cause:t?.cause,error:"FEATURE_UNAVAILABLE",message:e.message??"当前功能尚未开放,敬请期待",details:r});if(e?.error===1001)throw new l("当前账号暂无权限",{cause:t?.cause,error:"AUTH_PERMISSION_DENIED",message:e.message??"暂无权限,请联系超级管理员/管理员授权",details:r});if(t?.status===401){let e=nd();throw new l(e.message,{cause:t.cause,error:e.error,message:e.message,details:r})}if(t?.status===403)throw new l("当前账号暂无权限",{cause:t.cause,error:"AUTH_PERMISSION_DENIED",message:e?.message??"当前请求被拒绝,请确认权限后重试",details:r});if(e?.message)throw new l("接口调用失败",{cause:t?.cause,error:"API_REQUEST_FAILED",message:e.message,details:r});throw t?.cause??Error("Unknown gateway error")}function nm(e){if(!eY(e))throw e;nf(nh(e.responseBody),{status:e.status,cause:e})}function ng(e){let t=np(e);t&&void 0!==t.error&&0!==t.error&&nf(t)}async function nA(e,t={}){var r,i;let n={url:(r=e).url,method:r.method,params:r.params,data:r.data,headers:r.headers,baseURL:r.baseURL??"https://developer.open-douyin.com",timeoutMs:r.timeoutMs,signal:r.signal};try{let{data:e}=await na.send(n,{meta:t.meta});return ng(e),e}catch(r){eY(i=r)&&401===i.status||nm(r);let e=eY(r)?nh(r.responseBody):void 0;if(!await nr())throw e?.error===1002?nc():nd();try{let{data:e}=await na.send(n,{meta:t.meta});return ng(e),e}catch(e){nm(e)}}}let ny="session.json";async function nE(e){try{await iM.writeJson(ny,e,{mode:384})}catch(e){iz(e,"保存授权会话")}}async function n_(){try{return function(e){let t=C(e?.clientId),r=C(e?.tokenEndpoint),i=C(e?.deviceCode),n=C(e?.userCode),u=C(e?.verificationUri),o=C(e?.codeVerifier),s=D(e?.createdAt),a=D(e?.expiresAt);if(!t||!r||!i||!n||!u||!o||!s||!a)throw new l("本地授权会话异常",{error:"INVALID_AUTH_SESSION",message:`本地授权会话异常,请重新执行 ${e7}`});return{clientId:t,tokenEndpoint:r,deviceCode:i,userCode:n,verificationUri:u,verificationUriComplete:C(e?.verificationUriComplete),codeVerifier:o,intervalSeconds:function(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<=0))return e}(e?.intervalSeconds),createdAt:s,expiresAt:a}}(await iM.readJson(ny))}catch(e){if(tV(e))return;iz(e,"读取授权会话")}}async function nb(){try{await iM.remove(ny)}catch(e){tV(e)||iz(e,"清理授权会话")}}let nv=["coze","cursor","claude_code","github_copilot","gemini_cli","trae","manus","devin","codex","hermes","openclaw","unknown"];function nC(e){return nv.includes(e)}let nD="宿主枚举:1 全部 / 2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山 / 9 皮皮虾",nF="宿主枚举:2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山",nw="操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony / 5 Windows",nB="设备档位枚举:1 全部 / 2 高端 / 3 中端 / 4 低端";function nx(e,t){let{caller:r}=e.optsWithGlobals();return{...t,caller:"string"==typeof r&&nC(r)?r:"unknown"}}function nS(e){return e.option("--output-dir <dir>","输出根目录,默认 ./dymg-output(会在其下按命令+时间生成子目录,并按命令类型写入结果文件)"),e}async function nT(e){let t=await iK().catch(()=>void 0);return{toolId:e.replaceAll(":"," "),clientId:t?.clientId}}function nI(e){return e.requiredOption("--app-id <appId>","小游戏 appId").option("--start-date <date>","开始日期,格式 YYYY-MM-DD").option("--end-date <date>","结束日期,格式 YYYY-MM-DD").option("--host <host>",nD).option("--os <os>",nw).option("--user-type <userType>","用户类型枚举:1 全部 / 2 新增 / 3 活跃 / 4 付费新增 / 5 付费活跃").option("--segment <segment>","用户分群枚举:1 不分组 / 2 侧边栏奖励 / 3 App 活跃")}function nO(e){return e.requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD").requiredOption("--host <host>",nF).requiredOption("--os <os>","操作系统枚举:2 Android / 3 iOS / 4 OpenHarmony").option("--device-level <n>",nB).option("--mp-version <version>","小游戏版本号")}var nk=__webpack_require__("../../node_modules/.pnpm/@dp+tea-sdk-node@3.0.12/node_modules/@dp/tea-sdk-node/lib/index.js"),nR=__webpack_require__("../../node_modules/.pnpm/@logsdk+node-plugin-http@4.0.11_encoding@0.1.13/node_modules/@logsdk/node-plugin-http/lib/index.js");let nP=Number(626386),nL=null;function nN(){let e=ti();if(e?.tool&&void 0!==e.requestParams)return{caller:e.caller,tool:e.tool,requestParams:e.requestParams}}async function nj(e){let t=(void 0===r&&(r=function(){if(!Number.isFinite(nP)||nP<=0)return null;let e=globalThis.fetch?(e,t)=>globalThis.fetch(e,t):void 0,t=new nk.TeaSDK({app_id:nP}),r=(0,nR.httpPlugin)({channel:"cn",...e?{transport:(t,r)=>e(t,r)}:{}});return nL=r,t.use(r),t.config({custom:{cli_name:"dymg"}}),t}()),r);if(!t)return;let[i,n]=await Promise.all([iK().catch(()=>void 0),i0().catch(()=>void 0)]),u=ti(),o=function(e=3e3){let t=nL;return!t||e<=0?Promise.resolve():new Promise(r=>{let i=()=>{clearTimeout(n),r()},n=setTimeout(()=>{t.removeListener("drain",i),r()},e);t.once("drain",i)})}(),s={caller:e.caller,tool:e.tool,cli_version:"0.6.1",appli_id:u?.appId,user_id:n?.uid,oauth_app_id:n?.oauthAppId,oauth_app_name:n?.oauthAppName,client_id:i?.clientId,client_name:i?.clientName,is_success:+!!e.success,duration_ms:e.durationMs,request_params:e.requestParams,logid:u?.response?.logId,error_message:e.errorMessage,error_code:e.errorCode},a={user:n?{user_id:Number(n?.uid),user_unique_id:n?.uid,user_is_login:!!n?.uid}:void 0};t.collect("game_cli_call",s,a),await o}function n$(e){return d(e)?e.error:void 0}let nM=["npm","pnpm","yarn","bun"],nU=new e0;function nq(e){var t;return(t=e,nM.includes(t))?e:void 0}function nV(e={}){var t;let r=nq(e.input);return void 0!==e.input?r:(t=e.userAgent,nq(t?.split("/")[0])??e.defaultPackageManager)}async function nH(e,t={}){let r=e.trim(),i=t.client??nU,n=(t.registryBaseUrl??"https://registry.npmjs.org").trim().replace(/\/+$/,""),u=t.timeoutMs??3e3,o=t.retry??{maxRetries:2,retryDelayMs:e=>1e3*e};if(!r)throw new eW("packageName is required",{code:eG.InvalidArgument,url:n});let s=encodeURIComponent(r).replace("%2F","%2f"),a=`${n}/${s}/latest`,{data:l}=await i.send({url:a,timeoutMs:u,retry:o});if("string"!=typeof l?.version||""===l.version.trim())throw new eW("package registry response missing version",{code:eG.InvalidJson,url:a});return l.version.trim()}let nz="update-check.json";function nG(e){let t=nV({userAgent:process.env.npm_config_user_agent})?"dymg update":`dymg update --package-manager <${nM.join("|")}>`;return[`检测到 ${e6} 新版本 ${e}(当前 0.6.1)。`,`执行 ${t} 可更新 CLI 并同步随包发布的 Skill。`,"如只想手动同步 Skill,可执行 dymg skills install。"]}async function nW(){try{return await i$.get().readJson(nz)}catch(e){if(tV(e))return{};throw e}}async function nJ(e){await i$.get().writeJson(nz,e)}async function nY(){return nH(e6,{client:ns,timeoutMs:1e4})}async function nK(){let e=await nY();return{currentVersion:"0.6.1",latestVersion:e,hasUpdate:function(e,t){let r=v(e),i=v(t);if(!r||!i)return e.localeCompare(t);for(let n=0;n<3;n+=1){let u=r.main[n],o=i.main[n];if(void 0===u||void 0===o)return e.localeCompare(t);let s=u-o;if(0!==s)return s}if(0===r.prerelease.length&&i.prerelease.length>0)return 1;if(r.prerelease.length>0&&0===i.prerelease.length)return -1;let n=Math.max(r.prerelease.length,i.prerelease.length);for(let e=0;e<n;e+=1){let t=r.prerelease[e],n=i.prerelease[e];if(void 0===t)return -1;if(void 0===n)return 1;let u=function(e,t){let r=/^\d+$/.test(e),i=/^\d+$/.test(t);if(r&&i){var n,u;let r,i;return n=e,u=t,r=n.replace(/^0+/,"")||"0",i=u.replace(/^0+/,"")||"0",r.length!==i.length?r.length-i.length:r.localeCompare(i)}return r?-1:i?1:e.localeCompare(t)}(t,n);if(0!==u)return u}return 0}(e,"0.6.1")>0}}async function nX(e,t={}){let r=await nW(),i=Date.now(),n={...r,lastCheckedAt:i,latestVersion:e.latestVersion};t.notified&&(n.lastNotifiedAt=i,n.lastNotifiedVersion=e.latestVersion),await nJ(n)}async function nQ(e={}){var t,r,i,n,u,o;let s=e.force??!1,a=e.quiet??!1,l=Date.now(),c=await nW();if(t=l,r=c,!s&&!(t-(r.lastCheckedAt??0)>=864e5))return;let d=await nK(),p={...c,lastCheckedAt:l,latestVersion:d.latestVersion};if(d.hasUpdate){i=l,n=c,u=d.latestVersion,(s||(n.lastNotifiedVersion??n.latestVersion)!==u||i-(n.lastNotifiedAt??n.lastPromptedAt??0)>=864e5)&&(o=d.latestVersion,process.stdout.write(["",...nG(o),""].join("\n")),p.lastNotifiedAt=l,p.lastNotifiedVersion=d.latestVersion),await nJ(p);return}a||process.stdout.write(`dymg 已是最新版本(0.6.1)
|
|
34
|
-
`),await nJ(p)}async function nZ(){try{await nQ({quiet:!0})}catch{}}let n1={request:nA,baseURL:""};n1.genBaseURL=e=>"function"==typeof n1.baseURL?n1.baseURL(e):n1.baseURL+e;let
|
|
35
|
-
${t}`,uE=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),u_=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),ub=new WeakMap,uv=(e,t={})=>{let r;if("function"!=typeof e)throw TypeError("Expected a function");let i=0,n=e.displayName||e.name||"<anonymous>",u=function(...o){if(ub.set(u,++i),1===i)r=e.apply(this,o),e=void 0;else if(!0===t.throw)throw Error(`Function \`${n}\` can only be called once`);return r};return!function(e,t,{ignoreNonConfigurable:r=!1}={}){var i;let n,{name:u}=e;for(let i of Reflect.ownKeys(t))ug(e,t,i,r);i=e,(n=Object.getPrototypeOf(t))!==Object.getPrototypeOf(i)&&Object.setPrototypeOf(i,n),((e,t,r)=>{let i=""===r?"":`with ${r.trim()}() `,n=uy.bind(null,i,t.toString());Object.defineProperty(n,"name",u_);let{writable:u,enumerable:o,configurable:s}=uE;Object.defineProperty(e,"toString",{value:n,writable:u,enumerable:o,configurable:s})})(e,t,u)}(u,e),ub.set(u,i),u};uv.callCount=e=>{if(!ub.has(e))throw Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return ub.get(e)};let uC=[];uC.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&uC.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&uC.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");let uD=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,uF=Symbol.for("signal-exit emitter"),uw=globalThis,uB=Object.defineProperty.bind(Object);class ux{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(uw[uF])return uw[uF];uB(uw,uF,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let r=this.listeners[e],i=r.indexOf(t);-1!==i&&(0===i&&1===r.length?r.length=0:r.splice(i,1))}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let n of this.listeners[e])i=!0===n(t,r)||i;return"exit"===e&&(i=this.emit("afterExit",t,r)||i),i}}class uS{}class uT extends uS{#i="win32"===uI.platform?"SIGINT":"SIGHUP";#n=new ux;#u;#o;#s;#a={};#l=!1;constructor(e){for(const t of(super(),this.#u=e,this.#a={},uC))this.#a[t]=()=>{let r=this.#u.listeners(t),{count:i}=this.#n;if("object"==typeof e.__signal_exit_emitter__&&"number"==typeof e.__signal_exit_emitter__.count&&(i+=e.__signal_exit_emitter__.count),r.length===i){this.unload();let r=this.#n.emit("exit",null,t),i="SIGHUP"===t?this.#i:t;r||e.kill(e.pid,i)}};this.#s=e.reallyExit,this.#o=e.emit}onExit(e,t){if(!uD(this.#u))return()=>{};!1===this.#l&&this.load();let r=t?.alwaysLast?"afterExit":"exit";return this.#n.on(r,e),()=>{this.#n.removeListener(r,e),0===this.#n.listeners.exit.length&&0===this.#n.listeners.afterExit.length&&this.unload()}}load(){if(!this.#l){for(let e of(this.#l=!0,this.#n.count+=1,uC))try{let t=this.#a[e];t&&this.#u.on(e,t)}catch(e){}this.#u.emit=(e,...t)=>this.#c(e,...t),this.#u.reallyExit=e=>this.#d(e)}}unload(){this.#l&&(this.#l=!1,uC.forEach(e=>{let t=this.#a[e];if(!t)throw Error("Listener not defined for signal: "+e);try{this.#u.removeListener(e,t)}catch(e){}}),this.#u.emit=this.#o,this.#u.reallyExit=this.#s,this.#n.count-=1)}#d(e){return uD(this.#u)?(this.#u.exitCode=e||0,this.#n.emit("exit",this.#u.exitCode,null),this.#s.call(this.#u,this.#u.exitCode)):0}#c(e,...t){let r=this.#o;if(!("exit"===e&&uD(this.#u)))return r.call(this.#u,e,...t);{"number"==typeof t[0]&&(this.#u.exitCode=t[0]);let i=r.call(this.#u,e,...t);return this.#n.emit("exit",this.#u.exitCode,null),i}}}let uI=globalThis.process,{onExit:uO,load:uk,unload:uR}=(u=uD(uI)?new uT(uI):new class extends uS{onExit(){return()=>{}}load(){}unload(){}},{onExit:(e,t)=>u.onExit(e,t),load:()=>u.load(),unload:()=>u.unload()}),uP=k.stderr.isTTY?k.stderr:k.stdout.isTTY?k.stdout:void 0,uL=uP?uv(()=>{uO(()=>{uP.write("\x1b[?25h")},{alwaysLast:!0})}):()=>{},uN=!1,uj={};uj.show=(e=k.stderr)=>{e.isTTY&&(uN=!1,e.write("\x1b[?25h"))},uj.hide=(e=k.stderr)=>{e.isTTY&&(uL(),uN=!0,e.write("\x1b[?25l"))},uj.toggle=(e,t)=>{void 0!==e&&(uN=e),uN?uj.show(t):uj.hide(t)};var u$=JSON.parse('{"dots":{"interval":80,"frames":["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},"dots2":{"interval":80,"frames":["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},"dots3":{"interval":80,"frames":["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},"dots4":{"interval":80,"frames":["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},"dots5":{"interval":80,"frames":["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},"dots6":{"interval":80,"frames":["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},"dots7":{"interval":80,"frames":["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},"dots8":{"interval":80,"frames":["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},"dots9":{"interval":80,"frames":["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},"dots10":{"interval":80,"frames":["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},"dots11":{"interval":100,"frames":["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},"dots12":{"interval":80,"frames":["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},"dots13":{"interval":80,"frames":["⣼","⣹","⢻","⠿","⡟","⣏","⣧","⣶"]},"dots14":{"interval":80,"frames":["⠉⠉","⠈⠙","⠀⠹","⠀⢸","⠀⣰","⢀⣠","⣀⣀","⣄⡀","⣆⠀","⡇⠀","⠏⠀","⠋⠁"]},"dots8Bit":{"interval":80,"frames":["⠀","⠁","⠂","⠃","⠄","⠅","⠆","⠇","⡀","⡁","⡂","⡃","⡄","⡅","⡆","⡇","⠈","⠉","⠊","⠋","⠌","⠍","⠎","⠏","⡈","⡉","⡊","⡋","⡌","⡍","⡎","⡏","⠐","⠑","⠒","⠓","⠔","⠕","⠖","⠗","⡐","⡑","⡒","⡓","⡔","⡕","⡖","⡗","⠘","⠙","⠚","⠛","⠜","⠝","⠞","⠟","⡘","⡙","⡚","⡛","⡜","⡝","⡞","⡟","⠠","⠡","⠢","⠣","⠤","⠥","⠦","⠧","⡠","⡡","⡢","⡣","⡤","⡥","⡦","⡧","⠨","⠩","⠪","⠫","⠬","⠭","⠮","⠯","⡨","⡩","⡪","⡫","⡬","⡭","⡮","⡯","⠰","⠱","⠲","⠳","⠴","⠵","⠶","⠷","⡰","⡱","⡲","⡳","⡴","⡵","⡶","⡷","⠸","⠹","⠺","⠻","⠼","⠽","⠾","⠿","⡸","⡹","⡺","⡻","⡼","⡽","⡾","⡿","⢀","⢁","⢂","⢃","⢄","⢅","⢆","⢇","⣀","⣁","⣂","⣃","⣄","⣅","⣆","⣇","⢈","⢉","⢊","⢋","⢌","⢍","⢎","⢏","⣈","⣉","⣊","⣋","⣌","⣍","⣎","⣏","⢐","⢑","⢒","⢓","⢔","⢕","⢖","⢗","⣐","⣑","⣒","⣓","⣔","⣕","⣖","⣗","⢘","⢙","⢚","⢛","⢜","⢝","⢞","⢟","⣘","⣙","⣚","⣛","⣜","⣝","⣞","⣟","⢠","⢡","⢢","⢣","⢤","⢥","⢦","⢧","⣠","⣡","⣢","⣣","⣤","⣥","⣦","⣧","⢨","⢩","⢪","⢫","⢬","⢭","⢮","⢯","⣨","⣩","⣪","⣫","⣬","⣭","⣮","⣯","⢰","⢱","⢲","⢳","⢴","⢵","⢶","⢷","⣰","⣱","⣲","⣳","⣴","⣵","⣶","⣷","⢸","⢹","⢺","⢻","⢼","⢽","⢾","⢿","⣸","⣹","⣺","⣻","⣼","⣽","⣾","⣿"]},"dotsCircle":{"interval":80,"frames":["⢎ ","⠎⠁","⠊⠑","⠈⠱"," ⡱","⢀⡰","⢄⡠","⢆⡀"]},"sand":{"interval":80,"frames":["⠁","⠂","⠄","⡀","⡈","⡐","⡠","⣀","⣁","⣂","⣄","⣌","⣔","⣤","⣥","⣦","⣮","⣶","⣷","⣿","⡿","⠿","⢟","⠟","⡛","⠛","⠫","⢋","⠋","⠍","⡉","⠉","⠑","⠡","⢁"]},"line":{"interval":130,"frames":["-","\\\\","|","/"]},"line2":{"interval":100,"frames":["⠂","-","–","—","–","-"]},"rollingLine":{"interval":80,"frames":["/ "," - "," \\\\ "," |"," |"," \\\\ "," - ","/ "]},"pipe":{"interval":100,"frames":["┤","┘","┴","└","├","┌","┬","┐"]},"simpleDots":{"interval":400,"frames":[". ",".. ","..."," "]},"simpleDotsScrolling":{"interval":200,"frames":[". ",".. ","..."," .."," ."," "]},"star":{"interval":70,"frames":["✶","✸","✹","✺","✹","✷"]},"star2":{"interval":80,"frames":["+","x","*"]},"flip":{"interval":70,"frames":["_","_","_","-","`","`","\'","\xb4","-","_","_","_"]},"hamburger":{"interval":100,"frames":["☱","☲","☴"]},"growVertical":{"interval":120,"frames":["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},"growHorizontal":{"interval":120,"frames":["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},"balloon":{"interval":140,"frames":[" ",".","o","O","@","*"," "]},"balloon2":{"interval":120,"frames":[".","o","O","\xb0","O","o","."]},"noise":{"interval":100,"frames":["▓","▒","░"]},"bounce":{"interval":120,"frames":["⠁","⠂","⠄","⠂"]},"boxBounce":{"interval":120,"frames":["▖","▘","▝","▗"]},"boxBounce2":{"interval":100,"frames":["▌","▀","▐","▄"]},"triangle":{"interval":50,"frames":["◢","◣","◤","◥"]},"binary":{"interval":80,"frames":["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},"arc":{"interval":100,"frames":["◜","◠","◝","◞","◡","◟"]},"circle":{"interval":120,"frames":["◡","⊙","◠"]},"squareCorners":{"interval":180,"frames":["◰","◳","◲","◱"]},"circleQuarters":{"interval":120,"frames":["◴","◷","◶","◵"]},"circleHalves":{"interval":50,"frames":["◐","◓","◑","◒"]},"squish":{"interval":100,"frames":["╫","╪"]},"toggle":{"interval":250,"frames":["⊶","⊷"]},"toggle2":{"interval":80,"frames":["▫","▪"]},"toggle3":{"interval":120,"frames":["□","■"]},"toggle4":{"interval":100,"frames":["■","□","▪","▫"]},"toggle5":{"interval":100,"frames":["▮","▯"]},"toggle6":{"interval":300,"frames":["ဝ","၀"]},"toggle7":{"interval":80,"frames":["⦾","⦿"]},"toggle8":{"interval":100,"frames":["◍","◌"]},"toggle9":{"interval":100,"frames":["◉","◎"]},"toggle10":{"interval":100,"frames":["㊂","㊀","㊁"]},"toggle11":{"interval":50,"frames":["⧇","⧆"]},"toggle12":{"interval":120,"frames":["☗","☖"]},"toggle13":{"interval":80,"frames":["=","*","-"]},"arrow":{"interval":100,"frames":["←","↖","↑","↗","→","↘","↓","↙"]},"arrow2":{"interval":80,"frames":["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},"arrow3":{"interval":120,"frames":["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},"bouncingBar":{"interval":80,"frames":["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},"bouncingBall":{"interval":80,"frames":["( ● )","( ● )","( ● )","( ● )","( ●)","( ● )","( ● )","( ● )","( ● )","(● )"]},"smiley":{"interval":200,"frames":["\uD83D\uDE04 ","\uD83D\uDE1D "]},"monkey":{"interval":300,"frames":["\uD83D\uDE48 ","\uD83D\uDE48 ","\uD83D\uDE49 ","\uD83D\uDE4A "]},"hearts":{"interval":100,"frames":["\uD83D\uDC9B ","\uD83D\uDC99 ","\uD83D\uDC9C ","\uD83D\uDC9A ","\uD83D\uDC97 "]},"clock":{"interval":100,"frames":["\uD83D\uDD5B ","\uD83D\uDD50 ","\uD83D\uDD51 ","\uD83D\uDD52 ","\uD83D\uDD53 ","\uD83D\uDD54 ","\uD83D\uDD55 ","\uD83D\uDD56 ","\uD83D\uDD57 ","\uD83D\uDD58 ","\uD83D\uDD59 ","\uD83D\uDD5A "]},"earth":{"interval":180,"frames":["\uD83C\uDF0D ","\uD83C\uDF0E ","\uD83C\uDF0F "]},"material":{"interval":17,"frames":["█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███████▁▁▁▁▁▁▁▁▁▁▁▁▁","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","██████████▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","█████████████▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁██████████████▁▁▁▁","▁▁▁██████████████▁▁▁","▁▁▁▁█████████████▁▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁▁▁████████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","██████▁▁▁▁▁▁▁▁▁▁▁▁▁█","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁▁█████████████▁▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁▁███████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁▁█████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁"]},"moon":{"interval":80,"frames":["\uD83C\uDF11 ","\uD83C\uDF12 ","\uD83C\uDF13 ","\uD83C\uDF14 ","\uD83C\uDF15 ","\uD83C\uDF16 ","\uD83C\uDF17 ","\uD83C\uDF18 "]},"runner":{"interval":140,"frames":["\uD83D\uDEB6 ","\uD83C\uDFC3 "]},"pong":{"interval":80,"frames":["▐⠂ ▌","▐⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂▌","▐ ⠠▌","▐ ⡀▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐⠠ ▌"]},"shark":{"interval":120,"frames":["▐|\\\\____________▌","▐_|\\\\___________▌","▐__|\\\\__________▌","▐___|\\\\_________▌","▐____|\\\\________▌","▐_____|\\\\_______▌","▐______|\\\\______▌","▐_______|\\\\_____▌","▐________|\\\\____▌","▐_________|\\\\___▌","▐__________|\\\\__▌","▐___________|\\\\_▌","▐____________|\\\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},"dqpb":{"interval":100,"frames":["d","q","p","b"]},"weather":{"interval":100,"frames":["☀️ ","☀️ ","☀️ ","\uD83C\uDF24 ","⛅️ ","\uD83C\uDF25 ","☁️ ","\uD83C\uDF27 ","\uD83C\uDF28 ","\uD83C\uDF27 ","\uD83C\uDF28 ","\uD83C\uDF27 ","\uD83C\uDF28 ","⛈ ","\uD83C\uDF28 ","\uD83C\uDF27 ","\uD83C\uDF28 ","☁️ ","\uD83C\uDF25 ","⛅️ ","\uD83C\uDF24 ","☀️ ","☀️ "]},"christmas":{"interval":400,"frames":["\uD83C\uDF32","\uD83C\uDF84"]},"grenade":{"interval":80,"frames":["، ","′ "," \xb4 "," ‾ "," ⸌"," ⸊"," |"," ⁎"," ⁕"," ෴ "," ⁓"," "," "," "]},"point":{"interval":125,"frames":["∙∙∙","●∙∙","∙●∙","∙∙●","∙∙∙"]},"layer":{"interval":150,"frames":["-","=","≡"]},"betaWave":{"interval":80,"frames":["ρββββββ","βρβββββ","ββρββββ","βββρβββ","ββββρββ","βββββρβ","ββββββρ"]},"fingerDance":{"interval":160,"frames":["\uD83E\uDD18 ","\uD83E\uDD1F ","\uD83D\uDD96 ","✋ ","\uD83E\uDD1A ","\uD83D\uDC46 "]},"fistBump":{"interval":80,"frames":["\uD83E\uDD1C \uD83E\uDD1B ","\uD83E\uDD1C \uD83E\uDD1B ","\uD83E\uDD1C \uD83E\uDD1B "," \uD83E\uDD1C \uD83E\uDD1B "," \uD83E\uDD1C\uD83E\uDD1B "," \uD83E\uDD1C✨\uD83E\uDD1B ","\uD83E\uDD1C ✨ \uD83E\uDD1B "]},"soccerHeader":{"interval":80,"frames":[" \uD83E\uDDD1⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️\uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 "]},"mindblown":{"interval":160,"frames":["\uD83D\uDE10 ","\uD83D\uDE10 ","\uD83D\uDE2E ","\uD83D\uDE2E ","\uD83D\uDE26 ","\uD83D\uDE26 ","\uD83D\uDE27 ","\uD83D\uDE27 ","\uD83E\uDD2F ","\uD83D\uDCA5 ","✨ "," "," "," "]},"speaker":{"interval":160,"frames":["\uD83D\uDD08 ","\uD83D\uDD09 ","\uD83D\uDD0A ","\uD83D\uDD09 "]},"orangePulse":{"interval":100,"frames":["\uD83D\uDD38 ","\uD83D\uDD36 ","\uD83D\uDFE0 ","\uD83D\uDFE0 ","\uD83D\uDD36 "]},"bluePulse":{"interval":100,"frames":["\uD83D\uDD39 ","\uD83D\uDD37 ","\uD83D\uDD35 ","\uD83D\uDD35 ","\uD83D\uDD37 "]},"orangeBluePulse":{"interval":100,"frames":["\uD83D\uDD38 ","\uD83D\uDD36 ","\uD83D\uDFE0 ","\uD83D\uDFE0 ","\uD83D\uDD36 ","\uD83D\uDD39 ","\uD83D\uDD37 ","\uD83D\uDD35 ","\uD83D\uDD35 ","\uD83D\uDD37 "]},"timeTravel":{"interval":100,"frames":["\uD83D\uDD5B ","\uD83D\uDD5A ","\uD83D\uDD59 ","\uD83D\uDD58 ","\uD83D\uDD57 ","\uD83D\uDD56 ","\uD83D\uDD55 ","\uD83D\uDD54 ","\uD83D\uDD53 ","\uD83D\uDD52 ","\uD83D\uDD51 ","\uD83D\uDD50 "]},"aesthetic":{"interval":80,"frames":["▰▱▱▱▱▱▱","▰▰▱▱▱▱▱","▰▰▰▱▱▱▱","▰▰▰▰▱▱▱","▰▰▰▰▰▱▱","▰▰▰▰▰▰▱","▰▰▰▰▰▰▰","▰▱▱▱▱▱▱"]},"dwarfFortress":{"interval":80,"frames":[" ██████\xa3\xa3\xa3 ","☺██████\xa3\xa3\xa3 ","☺██████\xa3\xa3\xa3 ","☺▓█████\xa3\xa3\xa3 ","☺▓█████\xa3\xa3\xa3 ","☺▒█████\xa3\xa3\xa3 ","☺▒█████\xa3\xa3\xa3 ","☺░█████\xa3\xa3\xa3 ","☺░█████\xa3\xa3\xa3 ","☺ █████\xa3\xa3\xa3 "," ☺█████\xa3\xa3\xa3 "," ☺█████\xa3\xa3\xa3 "," ☺▓████\xa3\xa3\xa3 "," ☺▓████\xa3\xa3\xa3 "," ☺▒████\xa3\xa3\xa3 "," ☺▒████\xa3\xa3\xa3 "," ☺░████\xa3\xa3\xa3 "," ☺░████\xa3\xa3\xa3 "," ☺ ████\xa3\xa3\xa3 "," ☺████\xa3\xa3\xa3 "," ☺████\xa3\xa3\xa3 "," ☺▓███\xa3\xa3\xa3 "," ☺▓███\xa3\xa3\xa3 "," ☺▒███\xa3\xa3\xa3 "," ☺▒███\xa3\xa3\xa3 "," ☺░███\xa3\xa3\xa3 "," ☺░███\xa3\xa3\xa3 "," ☺ ███\xa3\xa3\xa3 "," ☺███\xa3\xa3\xa3 "," ☺███\xa3\xa3\xa3 "," ☺▓██\xa3\xa3\xa3 "," ☺▓██\xa3\xa3\xa3 "," ☺▒██\xa3\xa3\xa3 "," ☺▒██\xa3\xa3\xa3 "," ☺░██\xa3\xa3\xa3 "," ☺░██\xa3\xa3\xa3 "," ☺ ██\xa3\xa3\xa3 "," ☺██\xa3\xa3\xa3 "," ☺██\xa3\xa3\xa3 "," ☺▓█\xa3\xa3\xa3 "," ☺▓█\xa3\xa3\xa3 "," ☺▒█\xa3\xa3\xa3 "," ☺▒█\xa3\xa3\xa3 "," ☺░█\xa3\xa3\xa3 "," ☺░█\xa3\xa3\xa3 "," ☺ █\xa3\xa3\xa3 "," ☺█\xa3\xa3\xa3 "," ☺█\xa3\xa3\xa3 "," ☺▓\xa3\xa3\xa3 "," ☺▓\xa3\xa3\xa3 "," ☺▒\xa3\xa3\xa3 "," ☺▒\xa3\xa3\xa3 "," ☺░\xa3\xa3\xa3 "," ☺░\xa3\xa3\xa3 "," ☺ \xa3\xa3\xa3 "," ☺\xa3\xa3\xa3 "," ☺\xa3\xa3\xa3 "," ☺▓\xa3\xa3 "," ☺▓\xa3\xa3 "," ☺▒\xa3\xa3 "," ☺▒\xa3\xa3 "," ☺░\xa3\xa3 "," ☺░\xa3\xa3 "," ☺ \xa3\xa3 "," ☺\xa3\xa3 "," ☺\xa3\xa3 "," ☺▓\xa3 "," ☺▓\xa3 "," ☺▒\xa3 "," ☺▒\xa3 "," ☺░\xa3 "," ☺░\xa3 "," ☺ \xa3 "," ☺\xa3 "," ☺\xa3 "," ☺▓ "," ☺▓ "," ☺▒ "," ☺▒ "," ☺░ "," ☺░ "," ☺ "," ☺ &"," ☺ ☼&"," ☺ ☼ &"," ☺☼ &"," ☺☼ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & ","‼ & "," & "," & "," & ░ "," & ▒ "," & ▓ "," & \xa3 "," & ░\xa3 "," & ▒\xa3 "," & ▓\xa3 "," & \xa3\xa3 "," & ░\xa3\xa3 "," & ▒\xa3\xa3 ","& ▓\xa3\xa3 ","& \xa3\xa3\xa3 "," ░\xa3\xa3\xa3 "," ▒\xa3\xa3\xa3 "," ▓\xa3\xa3\xa3 "," █\xa3\xa3\xa3 "," ░█\xa3\xa3\xa3 "," ▒█\xa3\xa3\xa3 "," ▓█\xa3\xa3\xa3 "," ██\xa3\xa3\xa3 "," ░██\xa3\xa3\xa3 "," ▒██\xa3\xa3\xa3 "," ▓██\xa3\xa3\xa3 "," ███\xa3\xa3\xa3 "," ░███\xa3\xa3\xa3 "," ▒███\xa3\xa3\xa3 "," ▓███\xa3\xa3\xa3 "," ████\xa3\xa3\xa3 "," ░████\xa3\xa3\xa3 "," ▒████\xa3\xa3\xa3 "," ▓████\xa3\xa3\xa3 "," █████\xa3\xa3\xa3 "," ░█████\xa3\xa3\xa3 "," ▒█████\xa3\xa3\xa3 "," ▓█████\xa3\xa3\xa3 "," ██████\xa3\xa3\xa3 "," ██████\xa3\xa3\xa3 "]},"fish":{"interval":80,"frames":["~~~~~~~~~~~~~~~~~~~~","> ~~~~~~~~~~~~~~~~~~","\xba> ~~~~~~~~~~~~~~~~~","(\xba> ~~~~~~~~~~~~~~~~","((\xba> ~~~~~~~~~~~~~~~","<((\xba> ~~~~~~~~~~~~~~","><((\xba> ~~~~~~~~~~~~~"," ><((\xba> ~~~~~~~~~~~~","~ ><((\xba> ~~~~~~~~~~~","~~ <>((\xba> ~~~~~~~~~~","~~~ ><((\xba> ~~~~~~~~~","~~~~ <>((\xba> ~~~~~~~~","~~~~~ ><((\xba> ~~~~~~~","~~~~~~ <>((\xba> ~~~~~~","~~~~~~~ ><((\xba> ~~~~~","~~~~~~~~ <>((\xba> ~~~~","~~~~~~~~~ ><((\xba> ~~~","~~~~~~~~~~ <>((\xba> ~~","~~~~~~~~~~~ ><((\xba> ~","~~~~~~~~~~~~ <>((\xba> ","~~~~~~~~~~~~~ ><((\xba>","~~~~~~~~~~~~~~ <>((\xba","~~~~~~~~~~~~~~~ ><((","~~~~~~~~~~~~~~~~ <>(","~~~~~~~~~~~~~~~~~ ><","~~~~~~~~~~~~~~~~~~ <","~~~~~~~~~~~~~~~~~~~~"]}}');Object.keys(u$);let uM=n9?.WriteStream?.prototype?.hasColors?.()??!1,uU=(e,t)=>{if(!uM)return e=>e;let r=`\u001B[${e}m`,i=`\u001B[${t}m`;return e=>{let n=e+"",u=n.indexOf(i);if(-1===u)return r+n+i;let o=r,s=0,a=(22===t?i:"")+r;for(;-1!==u;)o+=n.slice(s,u)+a,s=u+i.length,u=n.indexOf(i,s);return o+=n.slice(s)+i}};uU(0,0),uU(1,22),uU(2,22),uU(3,23),uU(4,24),uU(53,55),uU(7,27),uU(8,28),uU(9,29),uU(30,39);let uq=uU(31,39),uV=uU(32,39),uH=uU(33,39),uz=uU(34,39);function uG(){let{env:e}=k,{TERM:t,TERM_PROGRAM:r}=e;return"win32"!==k.platform?"linux"!==t:!!e.WT_SESSION||!!e.TERMINUS_SUBLIME||"{cmd::Cmder}"===e.ConEmuTask||"Terminus-Sublime"===r||"vscode"===r||"xterm-256color"===t||"alacritty"===t||"rxvt-unicode"===t||"rxvt-unicode-256color"===t||"JetBrains-JediTerm"===e.TERMINAL_EMULATOR}uU(35,39),uU(36,39),uU(37,39),uU(90,39),uU(40,49),uU(41,49),uU(42,49),uU(43,49),uU(44,49),uU(45,49),uU(46,49),uU(47,49),uU(100,49),uU(91,39),uU(92,39),uU(93,39),uU(94,39),uU(95,39),uU(96,39),uU(97,39),uU(101,49),uU(102,49),uU(103,49),uU(104,49),uU(105,49),uU(106,49),uU(107,49);let uW=uG(),uJ=uz(uW?"ℹ":"i"),uY=uV(uW?"✔":"√"),uK=uH(uW?"⚠":"‼"),uX=uq(uW?"✖":"\xd7"),uQ=function({onlyFirst:e=!1}={}){let t="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))";return RegExp(`${t}|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,e?void 0:"g")}(),uZ=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],u1=[12288,12288,65281,65376,65504,65510],u2=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141],u0=(e,t)=>{let r=0,i=Math.floor(e.length/2)-1;for(;r<=i;){let n=Math.floor((r+i)/2),u=2*n;if(t<e[u])i=n-1;else{if(!(t>e[u+1]))return!0;r=n+1}}return!1},[u3,u6]=function(e){let t=e[0],r=e[1];for(let i=0;i<e.length;i+=2){let n=e[i],u=e[i+1];if(19968>=n&&19968<=u)return[n,u];u-n>r-t&&(t=n,r=u)}return[t,r]}(u2);function u4(e,{ambiguousAsWide:t=!1}={}){var r,i,n,u=e;if(!Number.isSafeInteger(u))throw TypeError(`Expected a code point, got \`${typeof u}\`.`);return!((r=e)<12288)&&!(r>65510)&&u0(u1,r)||(i=e)>=u3&&i<=u6||!(i<4352)&&!(i>262141)&&u0(u2,i)||t&&!((n=e)<161)&&!(n>1114109)&&u0(uZ,n)?2:1}let u8=new Intl.Segmenter,u9=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,u7=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,u5=/^\p{RGI_Emoji}$/v,oe=/^[\d#*]\u20E3$/,ot=/\p{Extended_Pictographic}/gu;function or(e){return e>=4352&&e<=4447||e>=43360&&e<=43388}function oi(e){return e>=4448&&e<=4519||e>=55216&&e<=55238}function on(e){return e>=4520&&e<=4607||e>=55243&&e<=55291}let ou=Object.freeze(new class{#p=0;#h;#f=!1;#m=!1;#g=e=>{e?.length&&("string"==typeof e?e.codePointAt(0):e[0])===3&&k.kill(k.pid,"SIGINT")};start(){this.#p++,1===this.#p&&this.#A()}stop(){0!==this.#p&&0==--this.#p&&this.#y()}#A(){let{stdin:e}=k;if("win32"===k.platform||!e?.isTTY||"function"!=typeof e.setRawMode){this.#h=void 0;return}this.#h=e,this.#f=e.isPaused(),this.#m=!!e.isRaw,e.setRawMode(!0),e.prependListener("data",this.#g),this.#f&&e.resume()}#y(){if(!this.#h)return;let e=this.#h;e.off("data",this.#g),e.isTTY&&e.setRawMode?.(this.#m),this.#f&&e.pause(),this.#h=void 0,this.#f=!1,this.#m=!1}}),oo=new Map,os=new Set(["black","red","green","yellow","blue","magenta","cyan","white","gray"]);class oa{#E=0;#_=-1;#b=0;#v;#C;#D;#F;#w=new Map;#B=!1;#x;#S;#T=!1;#I;#O(e){this.#B=!0;try{return e()}finally{this.#B=!1}}#k(){this.isSpinning&&this.render()}#R(e,t){return null==e?"":"string"==typeof e?e:Buffer.isBuffer(e)||ArrayBuffer.isView(e)?Buffer.from(e).toString("string"==typeof t&&t&&"buffer"!==t?t:"utf8"):String(e)}#P(e){if(!e)return!1;let t=e.at(-1);return"\n"===t||"\r"===t}#L(){this.#S||(this.#S=setTimeout(()=>{this.#S=void 0,this.isSpinning&&this.#k()},200),"function"==typeof this.#S?.unref&&this.#S.unref())}#N(){this.#S&&(clearTimeout(this.#S),this.#S=void 0)}#j(e,t,r,i){let n=this.#$(r," ");return n+e+("string"==typeof t?(e?" ":"")+t:"")+this.#M(i," ")}constructor(e){if("string"==typeof e&&(e={text:e}),this.#v={color:"cyan",stream:k.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#v.color,this.#D=this.#v.stream,"boolean"!=typeof this.#v.isEnabled&&(this.#v.isEnabled=function({stream:e=process.stdout}={}){return!!(e&&e.isTTY&&"dumb"!==process.env.TERM&&!("CI"in process.env))}({stream:this.#D})),"boolean"!=typeof this.#v.isSilent&&(this.#v.isSilent=!1),void 0!==this.#v.interval&&!(Number.isInteger(this.#v.interval)&&this.#v.interval>0))throw Error("The `interval` option must be a positive integer");const t=this.#v.interval;this.spinner=this.#v.spinner,this.#v.interval=t,this.text=this.#v.text,this.prefixText=this.#v.prefixText,this.suffixText=this.#v.suffixText,this.indent=this.#v.indent,"test"===k.env.NODE_ENV&&(this._stream=this.#D,this._isEnabled=this.#v.isEnabled,Object.defineProperty(this,"_linesToClear",{get(){return this.#E},set(e){this.#E=e}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#_}}),Object.defineProperty(this,"_lineCount",{get(){let e=this.#D.columns??80,t="function"==typeof this.#v.prefixText?"":this.#v.prefixText,r="function"==typeof this.#v.suffixText?"":this.#v.suffixText,i=" ".repeat(this.#v.indent)+("string"==typeof t&&""!==t?t+" ":"")+"-"+("string"==typeof this.#v.text?" "+this.#v.text:"")+("string"==typeof r&&""!==r?" "+r:"");return this.#U(i,e)}}))}get indent(){return this.#v.indent}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw Error("The `indent` option must be an integer from 0 and up");this.#v.indent=e}get interval(){return this.#v.interval??this.#C.interval??100}get spinner(){return this.#C}set spinner(e){if(this.#_=-1,this.#v.interval=void 0,"object"==typeof e){if(!Array.isArray(e.frames)||0===e.frames.length||e.frames.some(e=>"string"!=typeof e))throw Error("The given spinner must have a non-empty `frames` array of strings");if(void 0!==e.interval&&!(Number.isInteger(e.interval)&&e.interval>0))throw Error("`spinner.interval` must be a positive integer if provided");this.#C=e}else if(uG())if(void 0===e)this.#C=u$.dots;else if("default"!==e&&u$[e])this.#C=u$[e];else throw Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`);else this.#C=u$.line}get text(){return this.#v.text}set text(e=""){this.#v.text=e}get prefixText(){return this.#v.prefixText}set prefixText(e=""){this.#v.prefixText=e}get suffixText(){return this.#v.suffixText}set suffixText(e=""){this.#v.suffixText=e}get isSpinning(){return void 0!==this.#F}#q(e,t,r=!1){let i="function"==typeof e?e():e;return"string"==typeof i&&""!==i?r?t+i:i+t:""}#$(e=this.#v.prefixText,t=" "){return this.#q(e,t,!1)}#M(e=this.#v.suffixText,t=" "){return this.#q(e,t,!0)}#U(e,t){let r=0;for(let i of(0,R.stripVTControlCharacters)(e).split("\n"))r+=Math.max(1,Math.ceil(function(e,t={}){if("string"!=typeof e||0===e.length)return 0;let{ambiguousIsNarrow:r=!0,countAnsiEscapeCodes:i=!1}=t,n=e;if(!i&&(n.includes("\x1b")||n.includes("\x9b"))&&(n=function(e){if("string"!=typeof e)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.includes("\x1b")||e.includes("\x9b")?e.replace(uQ,""):e}(n)),0===n.length)return 0;if(/^[\u0020-\u007E]*$/.test(n))return n.length;let u=0,o={ambiguousAsWide:!r};for(let{segment:e}of u8.segment(n)){var s;if(s=e,u9.test(s))continue;if(u5.test(e)||function(e){if(e.length>50)return!1;if(oe.test(e))return!0;if(e.includes("")){let t=e.match(ot);return null!==t&&t.length>=2}return!1}(e)){u+=2;continue}let t=e.replace(u7,""),r=function(e,t){let r=[];for(let t of e)u9.test(t)||r.push(t.codePointAt(0));if(0===r.length)return;let i=0;for(let e=0;e<r.length;e++){var n;let u=r[e];if(!(or(n=u)||oi(n)||on(n))){if(0===i)return;for(let n=e;n<r.length;n++)i+=u4(r[n],t);break}if(or(u)&&oi(r[e+1])){i+=2,e+=on(r[e+2])?2:1;continue}i+=u4(u,t)}return i}(t,o);if(void 0!==r){u+=r;continue}u+=u4(t.codePointAt(0),o),u+=function(e,t){let r=0,i=!0;for(let n of e){if(i){i=!1;continue}n>=""&&n<=""&&(r+=u4(n.codePointAt(0),t))}return r}(t,o)}return u}(i)/t));return r}get color(){return this.#I}set color(e){if(void 0!==e&&!1!==e&&!os.has(e))throw Error("The `color` option must be a valid color or `false` to disable");this.#I=e}get isEnabled(){return this.#v.isEnabled&&!this.#v.isSilent}set isEnabled(e){if("boolean"!=typeof e)throw TypeError("The `isEnabled` option must be a boolean");this.#v.isEnabled=e}get isSilent(){return this.#v.isSilent}set isSilent(e){if("boolean"!=typeof e)throw TypeError("The `isSilent` option must be a boolean");this.#v.isSilent=e}frame(){let e=Date.now();(-1===this.#_||e-this.#b>=this.interval)&&(this.#_=(this.#_+1)%this.#C.frames.length,this.#b=e);let{frames:t}=this.#C,r=t[this.#_];this.#I&&(r=um[this.#I](r));let i=this.#$(this.#v.prefixText," "),n="string"==typeof this.text?" "+this.text:"";return i+r+n+this.#M(this.#v.suffixText," ")}clear(){return this.isEnabled&&this.#D.isTTY&&(this.#O(()=>{this.#D.cursorTo(0);for(let e=0;e<this.#E;e++)e>0&&this.#D.moveCursor(0,-1),this.#D.clearLine(1);this.#v.indent&&this.#D.cursorTo(this.#v.indent)}),this.#E=0),this}#V(e){if(!e||this.#w.has(e)||!e.isTTY||"function"!=typeof e.write)return;oo.has(e)&&console.warn("[ora] Multiple concurrent spinners detected. This may cause visual corruption. Use one spinner at a time.");let t=e.write;this.#w.set(e,t),oo.set(e,this),e.write=(r,i,n)=>this.#H(e,t,r,i,n)}#z(){if(this.isEnabled&&!(this.#w.size>0))for(let e of new Set([this.#D,k.stdout,k.stderr]))this.#V(e)}#G(){for(let[e,t]of this.#w)e.write=t,oo.get(e)===this&&oo.delete(e);this.#w.clear()}#H(e,t,r,i,n){if("function"==typeof i&&(n=i,i=void 0),this.#B)return t.call(e,r,i,n);this.clear();let u=this.#R(r,i),o=this.#P(u),s=t.call(e,r,i,n);return o?this.#N():u.length>0&&this.#L(),this.isSpinning&&!this.#S&&this.render(),s}render(){if(!this.isEnabled||this.#x||this.#S)return this;let e=this.#D.isTTY,t=!1;try{e&&(this.#O(()=>this.#D.write("\x1b[?2026h")),t=!0),this.clear();let r=this.frame(),i=this.#D.columns??80,n=this.#U(r,i),u=this.#D.rows;if(u&&u>1&&n>u){let e=r.split("\n");r=[...e.slice(0,u-1),"... (content truncated to fit terminal)"].join("\n")}let o=this.#O(()=>this.#D.write(r));!1===o&&this.#D.isTTY&&(this.#x=()=>{this.#x=void 0,this.#k()},this.#D.once("drain",this.#x)),this.#E=this.#U(r,i)}finally{t&&this.#O(()=>this.#D.write("\x1b[?2026l"))}return this}start(e){if(e&&(this.text=e),this.isSilent)return this;if(!this.isEnabled){let e=this.text?"-":"",t=" ".repeat(this.#v.indent)+this.#j(e,this.text,this.#v.prefixText,this.#v.suffixText);return""!==t.trim()&&this.#O(()=>this.#D.write(t+"\n")),this}return this.isSpinning||(this.#v.hideCursor&&uj.hide(this.#D),this.#v.discardStdin&&k.stdin.isTTY&&(ou.start(),this.#T=!0),this.#z(),this.render(),this.#F=setInterval(this.render.bind(this),this.interval)),this}stop(){return clearInterval(this.#F),this.#F=void 0,this.#_=-1,this.#b=0,this.#N(),this.#G(),this.#x&&(this.#D.removeListener("drain",this.#x),this.#x=void 0),this.isEnabled&&(this.clear(),this.#v.hideCursor&&uj.show(this.#D)),this.#T&&(this.#T=!1,ou.stop()),this}succeed(e){return this.stopAndPersist({symbol:uY,text:e})}fail(e){return this.stopAndPersist({symbol:uX,text:e})}warn(e){return this.stopAndPersist({symbol:uK,text:e})}info(e){return this.stopAndPersist({symbol:uJ,text:e})}stopAndPersist(e={}){if(this.isSilent)return this;let t=e.symbol??" ",r=e.text??this.text,i=e.prefixText??this.#v.prefixText,n=e.suffixText??this.#v.suffixText,u=this.#j(t,r,i,n)+"\n";return this.stop(),this.#O(()=>this.#D.write(u)),this}}function ol(e){return new oa(e)}async function oc(e,t,r){return tr({appId:t.appId,caller:t.caller}),(async()=>{let i=ol(`正在执行 ${e} ...`).start();try{let{rawResponse:n,rows:u,csvHeader:o,resultMeta:s}=await r({caller:t.caller}),a=ti()?.response?.logId,{summaryPath:l}=await ib({appName:"dymg",command:e,caller:t.caller,rawResponse:n,rows:u,csvHeader:o,outputDir:t.outputDir,logId:a,resultMeta:s});i.succeed(void 0===u?`${e} 执行完成,已写入原始响应,summary.json: ${l}`:`${e} 执行完成,已写入 ${u.length} 行数据,summary.json: ${l}`)}catch(n){i.fail(`${e} 执行失败`);let t=d(n)||n instanceof Error?n.message:String(n);tr({errorMessage:t,errorCode:n$(n)}),process.stderr.write(`${t}
|
|
32
|
+
`,{encoding:i,mode:r.mode})}catch(r){if(h(r,tq))throw r;let t=tL(this.baseDir,e);throw new tM(`Failed to write CSV file: ${t}`,{cause:r,code:tj.StorageError,filePath:t,operation:t$.WriteCsv})}}}var tY=((G={}).KeyNotFound="KEY_NOT_FOUND",G.DataNotFound="DATA_NOT_FOUND",G.DecryptionFailed="DECRYPTION_FAILED",G.KeyStorageError="KEY_STORAGE_ERROR",G.DataStorageError="DATA_STORAGE_ERROR",G.InvalidJson="INVALID_JSON",G.InvalidEnvelope="INVALID_ENVELOPE",G.KeychainTimeout="KEYCHAIN_TIMEOUT",G),tK=((W={}).ReadText="readText",W.WriteText="writeText",W.ReadJson="readJson",W.WriteJson="writeJson",W.Remove="remove",W.Clear="clear",W.ReadKey="readKey",W.WriteKey="writeKey",W.RemoveKey="removeKey",W);class tX extends l{filePath;operation;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="SensitiveStorageError",this.filePath=t.filePath,this.operation=t.operation}}class tQ extends tX{constructor(e={}){super("Sensitive storage key not found",{cause:e.cause,code:"KEY_NOT_FOUND",filePath:e.filePath,operation:e.operation??"readKey"}),this.name="SensitiveKeyNotFoundError"}}class tZ extends tX{constructor(e,t,r){super(`Sensitive data not found: ${e}`,{cause:r,code:"DATA_NOT_FOUND",filePath:e,operation:t}),this.name="SensitiveDataNotFoundError"}}class t1 extends tX{constructor(e,t,r){super(`Failed to decrypt sensitive data: ${e}`,{cause:r,code:"DECRYPTION_FAILED",filePath:e,operation:t}),this.name="SensitiveDecryptionError"}}class t0 extends tX{constructor(e,t,r){super(`Invalid sensitive data envelope: ${e}`,{cause:r,code:"INVALID_ENVELOPE",filePath:e,operation:t}),this.name="SensitiveEnvelopeError"}}class t2 extends tX{constructor(e,t){super(e,{cause:t.cause,code:t.code??"KEY_STORAGE_ERROR",filePath:t.filePath,operation:t.operation}),this.name="SensitiveKeyStorageError"}}class t3 extends t2{timeoutMs;constructor(e,t,r){super(`Keychain access timed out after ${t}ms`,{cause:r,code:"KEYCHAIN_TIMEOUT",operation:e}),this.name="KeychainTimeoutError",this.timeoutMs=t}}f("KEYCHAIN_TIMEOUT");let t6=f("KEY_NOT_FOUND"),t4=f("DATA_NOT_FOUND");function t8(e){return e?e.split(",").map(e=>e.trim()).filter(e=>""!==e):[]}f("DECRYPTION_FAILED"),f("INVALID_ENVELOPE");let t9=/^\d{4}-\d{2}-\d{2}$/,t7=/^\d{4}(0[1-9]|1[0-2])$/,t5=/^-?(0|[1-9]\d*)$/,re=/^[1-9]\d*$/;var rt=((J={}).InvalidEnum="INVALID_ENUM",J.InvalidIntList="INVALID_INT_LIST",J.InvalidDate="INVALID_DATE",J.InvalidRange="INVALID_RANGE",J.InvalidPositiveInt="INVALID_POSITIVE_INT",J.InvalidDateRange="INVALID_DATE_RANGE",J.OutOfLookback="OUT_OF_LOOKBACK",J.InvalidTimestamp="INVALID_TIMESTAMP",J.InvalidTimestampRange="INVALID_TIMESTAMP_RANGE",J);function rr(e){return String(e).padStart(2,"0")}function ri(e){let t=e.getFullYear(),r=rr(e.getMonth()+1),i=rr(e.getDate());return`${t}-${r}-${i}`}function rn(e,t,r){if(void 0!==e&&!r.includes(e))throw new l(`参数 ${t} 取值非法: ${e}`,{error:"INVALID_ENUM",message:`${t} 只能取 ${r.join(" / ")}`})}function ru(e,t,r){if(void 0!==e){for(let i of t8(e))if(!r.includes(i))throw new l(`参数 ${t} 包含非法取值: ${i}`,{error:"INVALID_ENUM",message:`${t} 每一项只能取 ${r.join(" / ")}`})}}function ro(e,t){if(void 0!==e){for(let r of t8(e))if(!t5.test(r))throw new l(`参数 ${t} 包含非法取值: ${r}`,{error:"INVALID_INT_LIST",message:`${t} 每一项必须是整数,但包含非法值: ${r}`})}}function rs(e,t){if(void 0===e)return;let r=new Date(`${e}T00:00:00Z`);if(!t9.test(e)||Number.isNaN(r.getTime())||r.toISOString().slice(0,10)!==e)throw new l(`参数 ${t} 日期格式非法: ${e}`,{error:"INVALID_DATE",message:`${t} 必须为 YYYY-MM-DD 格式`})}function ra(e,t,r,i){if(void 0===e)return;let n=t5.test(e)?Number(e):NaN;if(!Number.isInteger(n)||n<r||n>i)throw new l(`参数 ${t} 超出范围: ${e}`,{error:"INVALID_RANGE",message:`${t} 必须是 ${r}~${i} 之间的整数`})}function rl(e,t){if(void 0!==e&&!re.test(e))throw new l(`参数 ${t} 非法: ${e}`,{error:"INVALID_POSITIVE_INT",message:`${t} 必须是正整数`})}function rc(e){let{startDate:t,endDate:r}=e,i=e.startField??"--start-date",n=e.endField??"--end-date";if(rs(t,i),rs(r,n),t&&r&&t>r)throw new l(`${i} 不能晚于 ${n}`,{error:"INVALID_DATE_RANGE",message:`${i}(${t}) 不能晚于 ${n}(${r})`});if(!1===e.allowFuture){let e=ri(new Date);for(let[u,o]of[[i,t],[n,r]])if(o&&o>e)throw new l(`${u} 不能晚于今天`,{error:"INVALID_DATE_RANGE",message:`${u}(${o}) 不能晚于今天(${e})`})}}function rd(e){let{startDate:t,endDate:r,maxLookbackDays:i,label:n,latestDateOffsetDays:u=0}=e,o=e.startField??"--start-date",s=e.endField??"--end-date";rc(e);let a=ri(new Date(Date.now()-864e5*u)),c=ri(new Date(Date.now()-864e5*i));for(let[e,d]of[[o,t],[s,r]])if(d){if(d>a){let t=0===u?"今天":a;throw new l(`${e} 不能晚于${t}`,{error:"INVALID_DATE_RANGE",message:`${e}(${d}) 不能晚于${t}`})}if(d<c)throw new l(`${n}仅支持最近 ${i} 天的数据`,{error:"OUT_OF_LOOKBACK",message:`${n}仅支持最近 ${i} 天的数据,${e}(${d}) 已超出范围`})}}function rp(e){let{startTime:t,endTime:r}=e,i=e.startField??"--start-time",n=e.endField??"--end-time",u="seconds"===(e.unit??"milliseconds")?"秒级 Unix 时间戳":"毫秒时间戳",o=[];for(let[e,s]of[[i,t],[n,r]])if(void 0!==s){if(!re.test(s))throw new l(`参数 ${e} 时间戳非法: ${s}`,{error:"INVALID_TIMESTAMP",message:`${e} 必须是正整数${u}`});o.push([e,BigInt(s)])}let s=o.find(([e])=>e===i)?.[1],a=o.find(([e])=>e===n)?.[1];if(void 0!==s&&void 0!==a&&s>a)throw new l(`${i} 不能晚于 ${n}`,{error:"INVALID_TIMESTAMP_RANGE",message:`${i} 不能晚于 ${n}`});return o}function rh(e){let t=rp(e);if(!1===e.allowFuture){let r=BigInt("seconds"===e.unit?Math.floor(Date.now()/1e3):Date.now());for(let[e,i]of t)if(i>r)throw new l(`${e} 不能晚于当前时间`,{error:"INVALID_TIMESTAMP_RANGE",message:`${e} 不能晚于当前时间`})}}function rf(e){let t=t8(e);return t.length>0?t:void 0}function rm(e){let t=rf(e);if(!t)return;let r=t.map(Number).filter(e=>!Number.isNaN(e));return r.length>0?r:void 0}function rg(e,t,r){let i=rf(e),n=String(r);if(!i||1===i.length&&i[0]===n)return;if(i.includes(n))throw new l(`${t} 的全部选项 ${n} 不能与其他枚举值同时使用`,{error:rt.InvalidEnum,message:`${t} 的枚举值 ${n} 表示全部,必须单独使用`});let u=i.find(e=>!t5.test(e));if(void 0!==u)throw new l(`参数 ${t} 包含非法取值: ${u}`,{error:rt.InvalidIntList,message:`${t} 每一项必须是整数,但包含非法值: ${u}`});return i.map(Number)}function rA(e,t){if(void 0===e)return t;let r=t5.test(e)?Number(e):NaN;return Number.isNaN(r)?t:r}function ry(e){if(null==e)return;let t=String(e).trim();if("number"==typeof e&&!Number.isSafeInteger(e)||!t5.test(t))return;let r=BigInt(t),i=r<0n?-r:r,n=String(i%100n).padStart(2,"0");return`${r<0n?"-":""}${i/100n}.${n}`}function rE(e){if("number"==typeof e&&Number.isInteger(e)&&e>0)return e;if("string"!=typeof e||!t5.test(e))return;let t=Number(e);return t>0?t:void 0}function r_(e){return String(e).padStart(2,"0")}function rb(e,t={}){if(void 0===e||""===e)return"";let{format:r="datetime",unit:i="s"}=t,n=Number(e);if(!Number.isFinite(n))return String(e);let u=new Date("s"===i?1e3*n:n);if(Number.isNaN(u.getTime()))return String(e);let o=u.getFullYear(),s=r_(u.getMonth()+1),a=r_(u.getDate());if("date"===r)return`${o}-${s}-${a}`;let l=r_(u.getHours()),c=r_(u.getMinutes()),d=r_(u.getSeconds());return`${o}-${s}-${a} ${l}:${c}:${d}`}function rv(e){return Object.values(e).filter(e=>"number"==typeof e).map(String)}function rC(e,t){let r=function(e){if(void 0===e||!t5.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0}(e);if(void 0!==r)return Object.values(t).filter(e=>"number"==typeof e).includes(r)?r:void 0}function rD(e,t){let r="number"==typeof t?t:t5.test(t)?Number(t):NaN;return"string"==typeof e[r]?String(e[r]):String(t)}let rF=new Set(["access_denied","expired_token","invalid_client","invalid_grant","unauthorized_client"]);var rw=((Y={}).InvalidArgument="INVALID_ARGUMENT",Y.PortUnavailable="PORT_UNAVAILABLE",Y.CallbackAborted="CALLBACK_ABORTED",Y.CallbackTimeout="CALLBACK_TIMEOUT",Y.CallbackError="CALLBACK_ERROR",Y.RequestAborted="REQUEST_ABORTED",Y.RequestTimeout="REQUEST_TIMEOUT",Y.NetworkError="NETWORK_ERROR",Y.HttpError="HTTP_ERROR",Y.InvalidResponse="INVALID_RESPONSE",Y.AuthorizationPending="AUTHORIZATION_PENDING",Y.SlowDown="SLOW_DOWN",Y.AccessDenied="ACCESS_DENIED",Y.ExpiredToken="EXPIRED_TOKEN",Y),rB=((K={}).GeneratePKCE="generatePKCE",K.GenerateState="generateState",K.BuildAuthUrl="buildAuthUrl",K.BuildLoopbackRedirectUri="buildLoopbackRedirectUri",K.GetAvailablePort="getAvailablePort",K.CreateLocalCallbackHandler="createLocalCallbackHandler",K.HandleLocalCallback="handleLocalCallback",K.ExchangeToken="exchangeToken",K.IntrospectToken="introspectToken",K.RevokeToken="revokeToken",K.FetchAuthorizationServerMetadata="fetchAuthorizationServerMetadata",K.DynamicClientRegistration="dynamicClientRegistration",K.StartDeviceAuthorization="startDeviceAuthorization",K.ExchangeDeviceCodeToken="exchangeDeviceCodeToken",K.PollDeviceToken="pollDeviceToken",K.CreateDeviceFlowSession="createDeviceFlowSession",K);class rx extends l{operation;status;constructor(e,t){super(e,{cause:t.cause,error:t.code,details:t.details}),this.name="OAuthError",this.operation=t.operation,this.status=t.status}}class rS extends rx{responseBody;responseJson;constructor(e,t={}){super(e,{cause:t.cause,code:t.code??"HTTP_ERROR",operation:"exchangeToken",status:t.status,details:t.details}),this.name="OAuthTokenExchangeError",this.responseBody=t.responseBody,this.responseJson=t.responseJson}}class rT extends rx{responseBody;responseJson;constructor(e,t={}){super(e,{cause:t.cause,code:t.code??"HTTP_ERROR",operation:"introspectToken",status:t.status,details:t.details}),this.name="OAuthTokenIntrospectionError",this.responseBody=t.responseBody,this.responseJson=t.responseJson}}class rI extends rx{responseBody;responseJson;constructor(e,t={}){super(e,{cause:t.cause,code:t.code??"HTTP_ERROR",operation:"revokeToken",status:t.status,details:t.details}),this.name="OAuthTokenRevocationError",this.responseBody=t.responseBody,this.responseJson=t.responseJson}}class rO extends rx{providerError;providerErrorDescription;responseBody;responseJson;constructor(e,t={}){super(e,{cause:t.cause,code:t.code??"HTTP_ERROR",operation:t.operation??"pollDeviceToken",status:t.status,details:t.details}),this.name="OAuthDeviceFlowError",this.providerError=t.providerError,this.providerErrorDescription=t.providerErrorDescription,this.responseBody=t.responseBody,this.responseJson=t.responseJson}}let rk=Object.values(rw);function rR(e){if(!h(e,rk)||"exchangeToken"!==e.operation)return!1;let t=e.responseJson,r=t?.error;return"string"==typeof r&&rF.has(r)}var rP=((X={}).NotFound="NOT_FOUND",X.InvalidShape="INVALID_SHAPE",X.AccessTokenExpired="ACCESS_TOKEN_EXPIRED",X.RefreshTokenExpired="REFRESH_TOKEN_EXPIRED",X.RefreshFailed="REFRESH_FAILED",X.StorageError="STORAGE_ERROR",X),rL=((Q={}).Read="read",Q.Save="save",Q.Clear="clear",Q.Refresh="refresh",Q);class rN extends l{operation;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="OAuthTokenStoreError",this.operation=t.operation}}Object.values(rP);let rj=f("NOT_FOUND");function r$(e){var t;return tl(e)&&(t=e.auth,!!tl(t)&&rq(t.accessToken)&&rq(t.refreshToken)&&rU(t.atExpiresAt)&&rU(t.rtExpiresAt)&&ts(t.scopes)&&t.scopes.every(tc))}function rM(e,t,r){if(!r(e))throw new rN("Invalid OAuth token snapshot shape",{code:rP.InvalidShape,operation:t})}function rU(e){return ta(e)&&Number.isInteger(e)&&e>0&&e<1e10}function rq(e){return tc(e)&&""!==e.trim()}function rV(e,t=Date.now()){return e<=Math.floor(t/1e3)}class rH{storage;fileName;expiryLeewaySec;refreshLockPath;refreshLockOptions;now;validate;cache;readInflight;refreshInflight;writeEpoch=0;constructor(e){this.storage=e.storage,this.fileName=e.fileName??"auth.json",this.expiryLeewaySec=e.expiryLeewaySec??60,this.refreshLockPath=void 0===e.refreshLockPath?(0,I.join)(this.storage.baseDir,`${this.fileName}.refresh.lock`):e.refreshLockPath,this.refreshLockOptions=e.refreshLockOptions,this.now=e.now??(()=>Date.now()),this.validate=e.validate??r$}async get(){return this.cache?this.cache.snapshot:(this.readInflight||(this.readInflight=this.loadFromStorage().finally(()=>{this.readInflight=void 0})),this.readInflight)}async tryGet(){try{return await this.get()}catch(e){if(rj(e))return;throw e}}async save(e){rM(e,rL.Save,this.validate),this.writeEpoch+=1;try{await this.storage.writeJson(this.fileName,e)}catch(e){throw new rN(`Failed to persist OAuth token snapshot: ${this.fileName}`,{cause:e,code:rP.StorageError,operation:rL.Save})}this.cache={snapshot:e,loadedAt:this.now()}}async clear(){this.writeEpoch+=1;try{try{await this.storage.remove(this.fileName)}catch(e){if(!t4(e))throw e}await this.storage.removeKey()}catch(e){throw new rN(`Failed to clear OAuth token snapshot: ${this.fileName}`,{cause:e,code:rP.StorageError,operation:rL.Clear})}this.cache=void 0,this.readInflight=void 0,this.refreshInflight=void 0,this.writeEpoch+=1}async getAccessToken(e){let t=await this.get();if(!this.isAccessTokenExpired(t.auth))return t.auth.accessToken;if(!e)throw new rN("OAuth access token has expired and no refresh function provided",{code:rP.AccessTokenExpired,operation:rL.Refresh});return(await this.refresh(t,e)).auth.accessToken}async refresh(e,t){return!1===this.refreshLockPath?this.refreshCurrent(e,t):tW(this.refreshLockPath,async()=>{this.invalidateCache();let r=await this.tryGet();if(!r)throw new rN(`OAuth token snapshot not found: ${this.fileName}`,{code:rP.NotFound,operation:rL.Read});return r.auth.accessToken!==e.auth.accessToken?r:this.refreshCurrent(r,t)},this.refreshLockOptions)}async refreshCurrent(e,t){if(this.isRefreshTokenExpired(e.auth))throw new rN("OAuth refresh token has expired, re-login is required",{code:rP.RefreshTokenExpired,operation:rL.Refresh});if(this.refreshInflight)return this.refreshInflight;let r=this.writeEpoch,i=(async()=>{let i;try{i=await t(e)}catch(e){throw new rN("Failed to refresh OAuth tokens",{cause:e,code:rP.RefreshFailed,operation:rL.Refresh})}if(this.writeEpoch!==r)throw new rN("OAuth token refresh result is stale",{code:rP.RefreshFailed,operation:rL.Refresh});return rM(i,rL.Refresh,this.validate),await this.save(i),i})().finally(()=>{this.refreshInflight===i&&(this.refreshInflight=void 0)});return this.refreshInflight=i,i}invalidateCache(){this.cache=void 0}isAccessTokenExpired(e){let t=Math.floor(this.now()/1e3);return e.atExpiresAt-this.expiryLeewaySec<=t}isRefreshTokenExpired(e){return rV(e.rtExpiresAt,this.now())}async loadFromStorage(){let e,t=this.writeEpoch;try{e=await this.storage.readJson(this.fileName)}catch(e){if(t4(e))throw new rN(`OAuth token snapshot not found: ${this.fileName}`,{cause:e,code:rP.NotFound,operation:rL.Read});throw new rN(`Failed to read OAuth token snapshot: ${this.fileName}`,{cause:e,code:rP.StorageError,operation:rL.Read})}return rM(e,rL.Read,this.validate),this.writeEpoch===t&&(this.cache={snapshot:e,loadedAt:this.now()}),e}}let rz=new e2,rG=new Set(["grant_type","client_id","code","redirect_uri","code_verifier","refresh_token","device_code","scope"]),rW=new Set(["client_id","scope","code_challenge","code_challenge_method"]);function rJ(e){return Array.isArray(e)?e.map(e=>e.trim()).filter(Boolean).join(" ")||void 0:e?.trim()||void 0}function rY(e,t,r,i){if(t)for(let[n,u]of Object.entries(t)){if(r.has(n.toLowerCase()))throw new rx(`extraParams cannot override reserved OAuth parameter: ${n}`,{code:rw.InvalidArgument,operation:i});rK(e,n,u)}}function rK(e,t,r){null!=r&&e.set(t,String(r))}function rX(e){if(e.trim())try{let t=JSON.parse(e);if(tl(t))return t;return}catch{return}}function rQ(e){return eY(e)?e.error===eG.Timeout?rw.RequestTimeout:e.error===eG.Aborted?rw.RequestAborted:rw.NetworkError:rw.NetworkError}function rZ(e,t,r){try{return new URL(e)}catch(e){throw new rx(`Invalid ${r}`,{cause:e,code:rw.InvalidArgument,operation:t})}}function r1(e,t,r){if(!tc(e)||""===e.trim())throw new rx(`${t} must be a non-empty string`,{code:rw.InvalidArgument,operation:r})}function r0(e,t,r){if(!Number.isInteger(e)||e<=0)throw new rx(`${t} must be a positive integer`,{code:rw.InvalidArgument,operation:r})}async function r2(e){let t={...e.headers,Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"};try{let{data:i}=await (e.httpClient??rz).send({url:e.endpoint.toString(),method:"POST",headers:t,data:e.body.toString(),timeoutMs:e.timeoutMs,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!i)throw new rO("OAuth device flow endpoint returned an empty response",{code:rw.InvalidResponse,operation:e.operation});let n=i.status,u=await i.text(),o=rX(u),s=tc(o?.error)?o.error:void 0,a=tc(o?.error_description)?o.error_description:void 0;if(void 0===n)throw new rO("OAuth device flow endpoint returned an invalid response",{code:rw.NetworkError,operation:e.operation,responseBody:u,responseJson:o});if(n>=500)throw new rO(`OAuth device flow endpoint returned HTTP ${n}`,{code:rw.HttpError,operation:e.operation,providerError:s,providerErrorDescription:a,responseBody:u,responseJson:o,status:n});if(s){var r;throw new rO(`OAuth device flow endpoint returned error: ${s}`,{code:(r=s,"authorization_pending"===r?rw.AuthorizationPending:"slow_down"===r?rw.SlowDown:"access_denied"===r?rw.AccessDenied:"expired_token"===r?rw.ExpiredToken:rw.InvalidResponse),operation:e.operation,providerError:s,providerErrorDescription:a,responseBody:u,responseJson:o,status:n})}if(n<200||n>=300)throw new rO(`OAuth device flow endpoint returned HTTP ${n}`,{code:rw.HttpError,operation:e.operation,responseBody:u,responseJson:o,status:n});if(!o)throw new rO("OAuth device flow endpoint returned a non-JSON response",{code:rw.InvalidResponse,operation:e.operation,responseBody:u,status:n});return o}catch(t){if(t instanceof rO)throw t;throw new rO("OAuth device flow request failed",{cause:t,code:rQ(t),operation:e.operation})}}function r3(e,t,r){let i=Math.min(e,Math.max(0,t-Date.now()));return i<=0?Promise.resolve():r?.aborted?Promise.reject(new rO("OAuth device token polling was aborted",{code:rw.RequestAborted,operation:rB.PollDeviceToken})):new Promise((e,t)=>{let n=setTimeout(()=>{r?.removeEventListener("abort",u),e()},i),u=()=>{clearTimeout(n),t(new rO("OAuth device token polling was aborted",{code:rw.RequestAborted,operation:rB.PollDeviceToken}))};r?.addEventListener("abort",u,{once:!0})})}function r6(e,t){r1(e.clientId,"clientId",rB.ExchangeDeviceCodeToken),r1(e.deviceCode,"deviceCode",rB.ExchangeDeviceCodeToken),r0(t,"timeoutMs",rB.ExchangeDeviceCodeToken),void 0!==e.codeVerifier&&r1(e.codeVerifier,"codeVerifier",rB.ExchangeDeviceCodeToken)}function r4(e,t){if(!tc(e)||""===e.trim())throw new rO(`${t} must be a non-empty string`,{code:rw.InvalidResponse,operation:rB.StartDeviceAuthorization})}function r8(e,t,r){if(!Number.isInteger(e)||e<=0)throw new rO(`${t} must be a positive integer`,{code:rw.InvalidResponse,operation:rB.StartDeviceAuthorization,responseJson:r})}function r9(e,t={}){let r=e.verification_uri_complete??e.verification_uri,i=[t.title??"请在浏览器中完成授权:",` ${t.authorizationUrlLabel??"授权地址"}: ${r}`];return e.verification_uri_complete||i.push(` ${t.userCodeLabel??"授权码"}: ${e.user_code}`),i.push("",t.waitingMessage??"授权完成前请保持当前命令运行,CLI 会自动继续。"),i}async function r7(e){let t=rZ(e.deviceAuthorizationEndpoint,rB.StartDeviceAuthorization,"deviceAuthorizationEndpoint"),r=e.timeoutMs??15e3;var i=e,n=r;if(r1(i.clientId,"clientId",rB.StartDeviceAuthorization),r0(n,"timeoutMs",rB.StartDeviceAuthorization),void 0!==i.codeChallenge&&r1(i.codeChallenge,"codeChallenge",rB.StartDeviceAuthorization),void 0!==i.codeChallengeMethod&&r1(i.codeChallengeMethod,"codeChallengeMethod",rB.StartDeviceAuthorization),void 0===i.codeChallenge!=(void 0===i.codeChallengeMethod))throw new rO("codeChallenge and codeChallengeMethod must be provided together",{code:rw.InvalidArgument,operation:rB.StartDeviceAuthorization});let u=new URLSearchParams;u.set("client_id",e.clientId),rK(u,"scope",rJ(e.scope)),rK(u,"code_challenge",e.codeChallenge),rK(u,"code_challenge_method",e.codeChallengeMethod),rY(u,e.extraParams,rW,rB.StartDeviceAuthorization);let o=await r2({body:u,endpoint:t,httpClient:e.httpClient,headers:e.headers,operation:rB.StartDeviceAuthorization,signal:e.signal,timeoutMs:r});var s=o;if(r4(s.device_code,"device_code"),r4(s.user_code,"user_code"),r4(s.verification_uri,"verification_uri"),void 0!==s.verification_uri_complete&&r4(s.verification_uri_complete,"verification_uri_complete"),"number"!=typeof s.expires_in)throw new rO("expires_in must be a positive integer",{code:rw.InvalidResponse,operation:rB.StartDeviceAuthorization,responseJson:s});if(r8(s.expires_in,"expires_in",s),void 0!==s.interval){if("number"!=typeof s.interval)throw new rO("interval must be a positive integer",{code:rw.InvalidResponse,operation:rB.StartDeviceAuthorization,responseJson:s});r8(s.interval,"interval",s)}return o}async function r5(e){let t=rZ(e.tokenEndpoint,rB.ExchangeDeviceCodeToken,"tokenEndpoint"),r=e.timeoutMs??15e3;r6(e,r);let i=new URLSearchParams;i.set("grant_type","urn:ietf:params:oauth:grant-type:device_code"),i.set("client_id",e.clientId),i.set("device_code",e.deviceCode),rK(i,"code_verifier",e.codeVerifier),rY(i,e.extraParams,rG,rB.ExchangeDeviceCodeToken);let n=await r2({body:i,endpoint:t,httpClient:e.httpClient,headers:e.headers,operation:rB.ExchangeDeviceCodeToken,signal:e.signal,timeoutMs:r});if("string"!=typeof n.access_token||""===n.access_token.trim())throw new rO("OAuth device token response is missing access_token",{code:rw.InvalidResponse,operation:rB.ExchangeDeviceCodeToken,responseJson:n});return n}async function ie(e){var t,r,i,n,u;let o=e.intervalSeconds??5;t=e,r=o,r6(t,t.timeoutMs??15e3),r0(r,"intervalSeconds",rB.PollDeviceToken),void 0!==t.expiresInSeconds&&r0(t.expiresInSeconds,"expiresInSeconds",rB.PollDeviceToken),void 0!==t.pollTimeoutMs&&r0(t.pollTimeoutMs,"pollTimeoutMs",rB.PollDeviceToken);let s=1e3*o,a=Date.now(),l=void 0===e.expiresInSeconds?void 0:1e3*e.expiresInSeconds,c=(i=a,Math.min(void 0===(n=l)?1/0:i+n,void 0===(u=e.pollTimeoutMs)?i+(void 0===n?6e5:1/0):i+u));for(;Date.now()<c;)try{return await r5(e)}catch(t){if(!(t instanceof rO))throw t;if(t.error===rw.AuthorizationPending){await r3(s,c,e.signal);continue}if(t.error===rw.SlowDown){s+=5e3,await r3(s,c,e.signal);continue}if(t.error===rw.RequestTimeout||t.error===rw.NetworkError){await r3(s,c,e.signal);continue}throw t}throw new rO("Timed out waiting for OAuth device authorization",{code:rw.ExpiredToken,operation:rB.PollDeviceToken,details:{expiresInSeconds:e.expiresInSeconds,pollTimeoutMs:e.pollTimeoutMs}})}async function it(e){let t=function(e){if(void 0!==e.codeChallenge||void 0!==e.codeChallengeMethod){if(!e.codeChallenge||!e.codeChallengeMethod)throw new rO("codeChallenge and codeChallengeMethod must be provided together",{code:rw.InvalidArgument,operation:rB.CreateDeviceFlowSession});if(!e.codeVerifier)throw new rO("codeVerifier is required when custom PKCE parameters are provided",{code:rw.InvalidArgument,operation:rB.CreateDeviceFlowSession});return{codeVerifier:e.codeVerifier,codeChallenge:e.codeChallenge,codeChallengeMethod:e.codeChallengeMethod}}return function(e={}){let t=e.verifierByteLength??32;var r,i,n=t,u=rB.GeneratePKCE;if(!Number.isInteger(n)||n<32||n>96)throw new rx("verifierByteLength must be an integer between 32 and 96",{code:rw.InvalidArgument,operation:u});let o=(r=t,(0,td.randomBytes)(r).toString("base64url")),s=(i=o,(0,td.createHash)("sha256").update(i).digest("base64url"));return{codeVerifier:o,codeChallenge:s,codeChallengeMethod:"S256"}}({verifierByteLength:e.verifierByteLength})}(e),r=await r7({...e,codeChallenge:t.codeChallenge,codeChallengeMethod:t.codeChallengeMethod});return{authorization:r,codeVerifier:t.codeVerifier,codeChallenge:t.codeChallenge,codeChallengeMethod:t.codeChallengeMethod,pollToken:()=>ie({tokenEndpoint:e.tokenEndpoint,clientId:e.clientId,deviceCode:r.device_code,codeVerifier:t.codeVerifier,expiresInSeconds:r.expires_in,intervalSeconds:r.interval,extraParams:e.extraParams,headers:e.headers,timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient})}}function ir(e){return e.replace(/[^a-zA-Z0-9]+/g,"")}function ii(e,t,r){let i=e[t];if(tc(i)&&i.trim())return i;throw new rx(`OAuth response is missing ${t}`,{code:rw.InvalidResponse,operation:r,details:{field:t}})}async function iu(e){let t=rZ(e.url,e.operation,"url"),r={...e.headers,Accept:"application/json"};void 0!==e.body&&(r["Content-Type"]="application/json");try{let{data:u}=await (e.httpClient??rz).send({url:t.toString(),method:e.method,headers:r,data:e.body,timeoutMs:e.timeoutMs??15e3,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!u)throw new rx("OAuth endpoint returned an empty response",{code:rw.InvalidResponse,operation:e.operation});let o=u.status,s=await u.text(),a=rX(s);if(void 0===o||o<200||o>=300)throw new rx(`OAuth endpoint returned HTTP ${o??"unknown"}`,{code:rw.HttpError,operation:e.operation,status:o,details:{responseBody:s,responseJson:a}});var i=a,n=e.operation;if(tl(i))return i;throw new rx("OAuth endpoint returned an invalid JSON object",{code:rw.InvalidResponse,operation:n})}catch(t){if(t instanceof rx)throw t;throw new rx("OAuth request failed",{cause:t,code:rQ(t),operation:e.operation})}}async function io(e){let t,r=await iu({url:e.metadataEndpoint,method:"GET",headers:e.headers,timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient,operation:rB.FetchAuthorizationServerMetadata});return{issuer:tc(r.issuer)&&r.issuer.trim()?r.issuer.trim():void 0,tokenEndpoint:ii(r,"token_endpoint",rB.FetchAuthorizationServerMetadata),introspectionEndpoint:ii(r,"introspection_endpoint",rB.FetchAuthorizationServerMetadata),revocationEndpoint:ii(r,"revocation_endpoint",rB.FetchAuthorizationServerMetadata),deviceAuthorizationEndpoint:ii(r,"device_authorization_endpoint",rB.FetchAuthorizationServerMetadata),registrationEndpoint:ii(r,"registration_endpoint",rB.FetchAuthorizationServerMetadata),scopesSupported:(t=r.scopes_supported,ts(t)?t.filter(e=>tc(e)&&""!==e.trim()):[]),raw:r}}async function is(e){let t={...e.extraParams,client_name:e.clientName,grant_types:e.grantTypes??["urn:ietf:params:oauth:grant-type:device_code","refresh_token"],token_endpoint_auth_method:e.tokenEndpointAuthMethod??"none"};e.responseTypes&&(t.response_types=e.responseTypes);let r=await iu({url:e.registrationEndpoint,method:"POST",headers:e.headers,body:JSON.stringify(t),timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient,operation:rB.DynamicClientRegistration});return{clientId:ii(r,"client_id",rB.DynamicClientRegistration),raw:r}}async function ia(e){let t=rZ(e.tokenEndpoint,rB.ExchangeToken,"tokenEndpoint"),r=e.grantType??"authorization_code",i=e.timeoutMs??15e3;!function(e,t,r){if(r1(e.clientId,"clientId",rB.ExchangeToken),r0(r,"timeoutMs",rB.ExchangeToken),"authorization_code"===t){r1(e.code,"code",rB.ExchangeToken),r1(e.redirectUri,"redirectUri",rB.ExchangeToken),void 0!==e.codeVerifier&&r1(e.codeVerifier,"codeVerifier",rB.ExchangeToken);return}if("refresh_token"===t)return r1(e.refreshToken,"refreshToken",rB.ExchangeToken);throw new rx(`Unsupported OAuth grant type: ${t}`,{code:rw.InvalidArgument,operation:rB.ExchangeToken})}(e,r,i);let n=new URLSearchParams;n.set("grant_type",r),n.set("client_id",e.clientId),"authorization_code"===r?(n.set("code",e.code),n.set("redirect_uri",e.redirectUri),rK(n,"code_verifier",e.codeVerifier)):(n.set("refresh_token",e.refreshToken),rK(n,"scope",rJ(e.scope))),rY(n,e.extraParams,rG,rB.ExchangeToken);let u={...e.headers,Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"};try{let{data:r}=await (e.httpClient??rz).send({url:t.toString(),method:"POST",headers:u,data:n.toString(),timeoutMs:i,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!r)throw new rS("OAuth token endpoint returned an empty response",{code:rw.InvalidResponse});let o=r.status,s=await r.text(),a=rX(s),l=tc(a?.error)?a.error:void 0;if(void 0===o||o<200||o>=300)throw new rS(`OAuth token endpoint returned HTTP ${o??"unknown"}`,{code:rw.HttpError,responseBody:s,responseJson:a,status:o});if(l)throw new rS(`OAuth token endpoint returned error: ${l}`,{code:rw.InvalidResponse,responseBody:s,responseJson:a,status:o});if(!a)throw new rS("OAuth token endpoint returned a non-JSON response",{code:rw.InvalidResponse,responseBody:s,status:o});if(!tc(a.access_token)||""===a.access_token.trim())throw new rS("OAuth token response is missing access_token",{code:rw.InvalidResponse,responseBody:s,responseJson:a,status:o});return a}catch(e){if(e instanceof rS)throw e;throw new rS("OAuth token request failed",{cause:e,code:rQ(e)})}}async function il(e){var t,r,i;let n=rZ(e.introspectionEndpoint,rB.IntrospectToken,"introspectionEndpoint"),u=e.timeoutMs??15e3;t=e,r=u,r1(t.token,"token",rB.IntrospectToken),r1(t.clientId,"clientId",rB.IntrospectToken),r0(r,"timeoutMs",rB.IntrospectToken),void 0!==t.tokenTypeHint&&r1(t.tokenTypeHint,"tokenTypeHint",rB.IntrospectToken);let o=new URLSearchParams({token:e.token,token_type_hint:e.tokenTypeHint??"access_token",client_id:e.clientId}),s={...e.headers,Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"};try{let{data:t}=await (e.httpClient??rz).send({url:n.toString(),method:"POST",headers:s,data:o.toString(),timeoutMs:u,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!t)throw new rT("OAuth token introspection endpoint returned an empty response",{code:rw.InvalidResponse});let r=t.status,a=await t.text(),l=rX(a);if(void 0===r||r<200||r>=300)throw new rT(`OAuth token introspection endpoint returned HTTP ${r??"unknown"}`,{code:rw.HttpError,responseBody:a,responseJson:l,status:r});if(!l||"boolean"!=typeof l.active)throw new rT("OAuth token introspection response is invalid",{code:rw.InvalidResponse,responseBody:a,responseJson:l,status:r});return{active:(i=l).active,scope:id(i.scope),clientId:id(i.client_id),clientName:id(i.client_name),tokenType:id(i.token_type),exp:ip(i.exp),iat:ip(i.iat),sub:id(i.sub),raw:i}}catch(e){if(e instanceof rT)throw e;throw new rT("OAuth token introspection request failed",{cause:e,code:rQ(e)})}}async function ic(e){var t,r;let i=rZ(e.revocationEndpoint,rB.RevokeToken,"revocationEndpoint"),n=e.timeoutMs??15e3;t=e,r=n,r1(t.token,"token",rB.RevokeToken),r1(t.clientId,"clientId",rB.RevokeToken),r0(r,"timeoutMs",rB.RevokeToken),void 0!==t.tokenTypeHint&&r1(t.tokenTypeHint,"tokenTypeHint",rB.RevokeToken);let u=new URLSearchParams({token:e.token,client_id:e.clientId});rK(u,"token_type_hint",e.tokenTypeHint);let o={...e.headers,Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"};try{let{data:t}=await (e.httpClient??rz).send({url:i.toString(),method:"POST",headers:o,data:u.toString(),timeoutMs:n,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!t)throw new rI("OAuth token revocation endpoint returned an empty response",{code:rw.InvalidResponse});let r=t.status,s=await t.text(),a=rX(s);if(void 0===r||r<200||r>=300)throw new rI(`OAuth token revocation endpoint returned HTTP ${r??"unknown"}`,{code:rw.HttpError,responseBody:s,responseJson:a,status:r})}catch(e){if(e instanceof rI)throw e;throw new rI("OAuth token revocation request failed",{cause:e,code:rQ(e)})}}function id(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function ip(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function ih(e,t){let r=e[t];return r&&r.length>0?r:void 0}function im(e){var t,r,i,n,u,o,s,a;let c,d,p,h,f=e.appName,m=e.platform??process.platform,g="win32"===m?I.win32:I.posix,A="string"==typeof f?f.trim():"",y=A.split(/[\\/]+/);if(!A||g.isAbsolute(A)||y.includes(".."))throw new l("appName must be a non-empty string",{error:"INVALID_APP_NAME"});let E=e.homeDir??tp.homedir(),_=e.env??process.env;if("darwin"===m)return t=A,r=E,{configDir:I.join(r,"Library","Preferences",t),dataDir:I.join(r,"Library","Application Support",t),cacheDir:I.join(r,"Library","Caches",t),logDir:I.join(r,"Library","Logs",t),tempDir:I.join(tp.tmpdir(),t)};if("win32"===m){let e,t,r;return i=A,n=E,e=ih(u=_,"APPDATA")??I.join(n,"AppData","Roaming"),t=ih(u,"LOCALAPPDATA")??I.join(n,"AppData","Local"),r=ih(u,"TEMP")??tp.tmpdir(),{configDir:I.join(e,i,"Config"),dataDir:I.join(e,i,"Data"),cacheDir:I.join(t,i,"Cache"),logDir:I.join(t,i,"Log"),tempDir:I.join(r,i)}}return o=A,s=E,c=ih(a=_,"XDG_CONFIG_HOME")??I.join(s,".config"),d=ih(a,"XDG_DATA_HOME")??I.join(s,".local","share"),p=ih(a,"XDG_CACHE_HOME")??I.join(s,".cache"),h=ih(a,"XDG_STATE_HOME")??I.join(s,".local","state"),{configDir:I.join(c,o),dataDir:I.join(d,o),cacheDir:I.join(p,o),logDir:I.join(h,o,"logs"),tempDir:I.join(tp.tmpdir(),o)}}function ig(e){let t;function r(){let r,i;return t||(t=new tJ((r=e.dir??"dataDir",i=im(e),{baseDir:e.subDir?tL(i[r],e.subDir):i[r],baseDirMode:e.baseDirMode??448}))),t}return{get:r,readText:(e,t)=>r().readText(e,t),writeText:(e,t,i)=>r().writeText(e,t,i),remove:e=>r().remove(e),readJson:(e,t)=>r().readJson(e,t),writeJson:(e,t,i)=>r().writeJson(e,t,i),readCsv:(e,t)=>r().readCsv(e,t),writeCsv:(e,t,i)=>r().writeCsv(e,t,i)}}function iA(e){if(void 0===e)return;if("number"==typeof e)return Number.isSafeInteger(e)?e:void 0;if(!/^[+-]?\d+$/.test(e))return;let t=Number(e);return Number.isSafeInteger(t)?t:void 0}function iy(e){let t=iA(e.total),r=iA(e.page),i=iA(e.pageSize),n={unit:e.unit,returnedCount:e.returnedCount,total:t,page:r,pageSize:i,hasMore:e.hasMore??function(e,t,r){if(void 0!==e&&void 0!==t&&void 0!==r)return t*r<e}(t,r,i),nextCursor:e.nextCursor};return Object.values(n).some(e=>void 0!==e)?n:void 0}function iE(e){return String(e).padStart(2,"0")}function i_(e){return e.replace(/[^a-zA-Z0-9_-]+/g,"-")}async function ib(e){if(""===e.command.trim())throw new l("command must be a non-empty string",{error:"INVALID_COMMAND",message:"command 必须是非空字符串"});let t="data.csv",r="raw_response.json",i="summary.json",n=function(e){var t;let r,i,n,u,o,s,a,c=(r=(t=new Date).getFullYear(),i=iE(t.getMonth()+1),n=iE(t.getDate()),u=iE(t.getHours()),o=iE(t.getMinutes()),s=iE(t.getSeconds()),a=String(t.getMilliseconds()).padStart(3,"0"),`${r}-${i}-${n}_${u}-${o}-${s}_${a}`),d=`${i_(e.command)}-${c}`;if(e.outputDir){let t=(0,I.resolve)(e.outputDir);if((0,O.existsSync)(t)&&!(0,O.statSync)(t).isDirectory())throw new l(`输出路径不是目录: ${t}`,{error:"INVALID_OUTPUT_DIR",message:`--output-dir 必须是一个目录,但 ${t} 是文件`});return(0,I.resolve)(t,d)}return(0,I.resolve)(process.cwd(),`${i_(e.appName)}-output`,d)}(e),u=(0,I.resolve)(n,t),o=(0,I.resolve)(n,r),s=(0,I.resolve)(n,i),a=void 0===e.rows?void 0:function(e=[]){return e.map(e=>{let t={};for(let[r,i]of Object.entries(e))t[r]=null==i?"":String(i);return t})}(e.rows);await tN(s);let c=new tJ({baseDir:n});await Promise.all([...void 0===a?[]:[c.writeCsv(t,a,{header:e.csvHeader})],c.writeJson(r,e.rawResponse)]);let d={command:e.command,caller:e.caller,logId:e.logId,generatedAt:new Date().toISOString(),rowCount:a?.length,resultMeta:e.resultMeta,files:{csv:void 0===a?void 0:u,rawResponse:o}};return await c.writeJson(i,d),{summaryPath:s,csvPath:void 0===a?void 0:u,rawPath:o}}let iv="aes-256-gcm";function iC(e,t,r,i=iF(r)){let n=(0,td.randomBytes)(12),u=(0,td.createCipheriv)(iv,t,n);u.setAAD(i);let o=Buffer.concat([u.update(e),u.final()]);return{version:1,algorithm:iv,keyProvider:r,iv:n.toString("base64"),authTag:u.getAuthTag().toString("base64"),ciphertext:o.toString("base64")}}function iD(e,t,r){if(32!==t.length)throw Error(`Invalid sensitive storage key length: ${t.length}`);let i=(0,td.createDecipheriv)(iv,t,Buffer.from(e.iv,"base64"));return i.setAAD(r),i.setAuthTag(Buffer.from(e.authTag,"base64")),Buffer.concat([i.update(Buffer.from(e.ciphertext,"base64")),i.final()])}function iF(e){return Buffer.from([1,iv,e].join(":"),"utf8")}function iw(e,t,r){return Buffer.from([1,iv,"scrypt",e,t,r].join(":"),"utf8")}function iB(e,t,r){return(0,td.scryptSync)(function(e,t){let{uid:r,gid:i}=function(){try{let e=(0,tp.userInfo)();return{uid:String(e.uid),gid:String(e.gid)}}catch{let e="unknown-uid",t="unknown-gid";try{e=String(process.getuid?.()??e)}catch{}try{t=String(process.getgid?.()??t)}catch{}return{uid:e,gid:t}}}(),n=(0,tp.platform)();return["open-game-cli-lib-ssfk-v1",e,t,n,(0,tp.arch)(),r,i].join("\n")}(e,t),r,32)}function ix(e){if(!(e instanceof Error))return!1;let t=e?.code;return!!(tc(t)&&/no\s*entry|not\s*found/i.test(t))||/no\s*entry|not\s*found|notfound|not found/i.test(e?.message)}var iS=((Z={}).Auto="auto",Z.Keychain="keychain",Z.File="file",Z),iT=((ee={}).Read="read",ee.Write="write",ee.Remove="remove",ee);let iI=new Map;async function iO(){return await import("@napi-rs/keyring")}async function ik(e,t){let r=iI.get(e)??Promise.resolve(),i=()=>void 0,n=new Promise(e=>{i=e}),u=r.then(()=>n,()=>n);iI.set(e,u),await r.catch(()=>void 0);try{return await t()}finally{i(),iI.get(e)===u&&iI.delete(e)}}class iR{baseDir;service;account;fallbackKeyFile;fileStorage;keyStrategy;keychainTimeoutMs;onKeychainPrompt;fallbackKeyLockPath;fallbackKeyLockOptions;fallbackKeyScopeId;constructor(e){this.baseDir=(0,I.resolve)(e.baseDir),this.service=e.service,this.account=e.account,this.fallbackKeyFile=e.fallbackKeyFile??".sensitive-storage-key",this.fileStorage=new tJ({baseDir:this.baseDir,baseDirMode:void 0===e.baseDirMode?448:e.baseDirMode}),this.keyStrategy=function(e){if(void 0===e)return iS.File;if(e===iS.Auto||e===iS.Keychain||e===iS.File)return e;throw TypeError(`keyStrategy must be one of: ${iS.File}, ${iS.Keychain}, ${iS.Auto}`)}(e.keyStrategy),this.keychainTimeoutMs=Math.max(0,e.keychainTimeoutMs??5e3),this.onKeychainPrompt=e.onKeychainPrompt,this.fallbackKeyLockPath=void 0===e.fallbackKeyLockPath?tL(this.baseDir,`${this.fallbackKeyFile}.lock`):e.fallbackKeyLockPath,this.fallbackKeyLockOptions=e.fallbackKeyLockOptions,this.fallbackKeyScopeId=function(e,t){return(0,td.createHash)("sha256").update(e).update("\0").update(t).digest("hex").slice(0,32)}(this.service,this.account)}async readText(e,t="utf8"){let r=tL(this.baseDir,e);return(await this.readEncryptedData(r,tK.ReadText)).toString(t)}async writeText(e,t,r={}){let i=r.encoding??"utf8",n=tL(this.baseDir,e);await this.writeEncryptedData(n,Buffer.from(t,i),tK.WriteText)}async readJson(e,t="utf8"){let r=tL(this.baseDir,e),i=await this.readEncryptedData(r,tK.ReadJson);try{return JSON.parse(i.toString(t))}catch(e){throw new tX(`Failed to parse sensitive JSON data: ${r}`,{cause:e,code:tY.InvalidJson,filePath:r,operation:tK.ReadJson})}}async writeJson(e,t,r={}){let i=r.encoding??"utf8",n=r.spaces??2,u=tL(this.baseDir,e),o=`${JSON.stringify(t,null,n)}
|
|
33
|
+
`;await this.writeEncryptedData(u,Buffer.from(o,i),tK.WriteJson)}async remove(e){let t=tL(this.baseDir,e);try{await this.fileStorage.remove(t)}catch(e){if(tV(e))throw new tZ(t,tK.Remove,e);throw new tX(`Failed to remove sensitive data: ${t}`,{cause:e,code:tY.DataStorageError,filePath:t,operation:tK.Remove})}}async removeKey(){let e;if(this.shouldUseKeychainOnRemove())try{let{AsyncEntry:e}=await iO(),t=new e(this.service,this.account);await this.runKeychainCall(()=>t.deleteCredential(),tK.RemoveKey,iT.Remove)}catch(t){t instanceof t3?e=t:ix(t)||(e=new t2("Failed to remove sensitive storage key from keychain",{cause:t,operation:tK.RemoveKey}))}if(this.shouldUseFileOnRemove()){let e=this.getFallbackKeyFilePath();try{await this.fileStorage.remove(e)}catch(t){if(!tV(t))throw new t2(`Failed to remove sensitive storage key file: ${e}`,{cause:t,filePath:e,operation:tK.RemoveKey})}}if(e)throw e}async readEncryptedData(e,t){let r=await this.tryReadEnvelope(e,t);if(!r)throw new tZ(e,t);this.assertReadableProvider(r.keyProvider,e,t);let i=await this.readKeyByProvider(r.keyProvider,e,t);try{return iD(r,i,iF(r.keyProvider))}catch(r){throw new t1(e,t,r)}}async writeEncryptedData(e,t,r){try{let{key:i,provider:n}=await this.resolveKeyForNewEnvelopeWithLock(e,r),u=iC(t,i,n);await this.fileStorage.writeJson(e,u,{encoding:"utf8",mode:384})}catch(t){if(t instanceof tX)throw t;throw new tX(`Failed to write sensitive data: ${e}`,{cause:t,code:tY.DataStorageError,filePath:e,operation:r})}}async resolveKeyForNewEnvelopeWithLock(e,t){return ik(this.getKeyResolutionLockId(),()=>this.resolveKeyForNewEnvelope(e,t))}getKeyResolutionLockId(){return[this.service,this.account,this.fallbackKeyFile].join("\0")}getFallbackKeyFilePath(){return tL(this.baseDir,`${this.fallbackKeyFile}.${this.fallbackKeyScopeId}.json`)}async resolveKeyForNewEnvelope(e,t){if(this.keyStrategy===iS.File){let e=(0,td.randomBytes)(32);return{key:await this.ensureFileKey(e),provider:"file"}}if(this.keyStrategy===iS.Keychain){let r=await this.tryReadReusableKey("keychain",e,t);if(r)return r;let i=(0,td.randomBytes)(32);return await this.writeKeyToKeychain(i),{key:i,provider:"keychain"}}let r=!1;try{let r=await this.tryReadReusableKey("keychain",e,t);if(r)return r}catch{r=!0}let i=await this.tryReadReusableKey("file",e,t);if(i)return i;let n=(0,td.randomBytes)(32);if(!r)try{return await this.writeKeyToKeychain(n),{key:n,provider:"keychain"}}catch{}return{key:await this.ensureFileKey(n),provider:"file"}}assertReadableProvider(e,t,r){if(this.keyStrategy===iS.Auto)return;let i=this.keyStrategyToProvider();if(e!==i)throw new t2(`Sensitive data key provider mismatch: expected ${i}, got ${e}`,{filePath:t,operation:r})}keyStrategyToProvider(){return this.keyStrategy===iS.Keychain?"keychain":"file"}shouldUseKeychainOnRemove(){return this.keyStrategy===iS.Auto||this.keyStrategy===iS.Keychain}shouldUseFileOnRemove(){return this.keyStrategy===iS.Auto||this.keyStrategy===iS.File}async readKeyByProvider(e,t,r){return"keychain"===e?await this.readKeyFromKeychain(t,r):await this.readKeyFromFile(t,r)}async tryReadReusableKey(e,t,r){try{return{key:await this.readKeyByProvider(e,t,r),provider:e}}catch(e){if(t6(e))return;throw e}}async tryReadEnvelope(e,t){let r;try{r=await this.fileStorage.readText(e,"utf8")}catch(r){if(tV(r))return;throw new tX(`Failed to read sensitive data: ${e}`,{cause:r,code:tY.DataStorageError,filePath:e,operation:t})}try{var i,n=r;let e=JSON.parse(n);if(1!==e.version||e.algorithm!==iv||(i=e.keyProvider,!["keychain","file"].includes(i))||!tc(e.iv)||!tc(e.authTag)||!tc(e.ciphertext))throw Error("Invalid sensitive data envelope");return e}catch(r){throw new t0(e,t,r)}}async ensureFileKey(e){return!1===this.fallbackKeyLockPath?this.createFileKeyIfMissing(e):tW(this.fallbackKeyLockPath,async()=>this.createFileKeyIfMissing(e),this.fallbackKeyLockOptions)}async createFileKeyIfMissing(e){let t=this.getFallbackKeyFilePath();try{return await this.readKeyFromFile(void 0,tK.ReadKey)}catch(e){if(!t6(e))throw e}let r=(0,td.randomBytes)(16),i=r.toString("base64"),n=iC(e,iB(this.service,this.account,r),"file",iw(this.service,this.account,i)),u={version:1,algorithm:iv,kdf:"scrypt",salt:i,iv:n.iv,authTag:n.authTag,encryptedKey:n.ciphertext};try{await this.fileStorage.writeJson(t,u,{encoding:"utf8",mode:384})}catch(e){throw new t2(`Failed to write sensitive storage key file: ${t}`,{cause:e,filePath:t,operation:tK.WriteKey})}return e}async readKeyFromKeychain(e,t){try{let{AsyncEntry:u}=await iO(),o=new u(this.service,this.account),s=await this.runKeychainCall(()=>o.getPassword(),t,iT.Read);if(!s)throw new tQ({filePath:e,operation:t});var r=s,i=e,n=t;let a=Buffer.from(r,"base64");if(32!==a.length)throw new t2(`Invalid sensitive storage key length: ${a.length}`,{filePath:i,operation:n});return a}catch(r){if(r instanceof tX)throw r;if(ix(r))throw new tQ({cause:r,filePath:e,operation:t});throw new t2("Failed to read sensitive storage key from keychain",{cause:r,filePath:e,operation:t})}}async writeKeyToKeychain(e){try{let{AsyncEntry:t}=await iO(),r=new t(this.service,this.account);await this.runKeychainCall(()=>r.setPassword(e.toString("base64")),tK.WriteKey,iT.Write)}catch(e){if(e instanceof tX)throw e;throw new t2("Failed to write sensitive storage key to keychain",{cause:e,operation:tK.WriteKey})}}async runKeychainCall(e,t,r){let i;if(this.onKeychainPrompt?.({operation:r,service:this.service,account:this.account,timeoutMs:this.keychainTimeoutMs}),this.keychainTimeoutMs<=0)return e();try{return await Promise.race([e(),new Promise((e,r)=>{i=setTimeout(()=>{r(new t3(t,this.keychainTimeoutMs))},this.keychainTimeoutMs),i.unref?.()})])}finally{i&&clearTimeout(i)}}async readKeyFromFile(e,t){let r,i=this.getFallbackKeyFilePath();try{r=await this.fileStorage.readText(i,"utf8")}catch(r){if(tV(r))throw new tQ({cause:r,filePath:e??i,operation:t});throw new t2(`Failed to read sensitive storage key file: ${i}`,{cause:h(r,tq)?r.cause??r:r,filePath:e??i,operation:t})}try{let e=function(e){let t=JSON.parse(e);if(1!==t.version||t.algorithm!==iv||"scrypt"!==t.kdf||!tc(t.salt)||!tc(t.iv)||!tc(t.authTag)||!tc(t.encryptedKey))throw Error("Invalid sensitive storage key envelope");return t}(r),t=iB(this.service,this.account,Buffer.from(e.salt,"base64")),i=iD({iv:e.iv,authTag:e.authTag,ciphertext:e.encryptedKey},t,iw(this.service,this.account,e.salt));if(32!==i.length)throw Error(`Invalid sensitive storage key length: ${i.length}`);return i}catch(r){throw new t2(`Failed to decrypt sensitive storage key file: ${i}`,{cause:r,filePath:e??i,operation:t})}}}let iP=/^[a-zA-Z0-9_-]+$/,iL=function(){1;return""}();function iN(e){return iL?`${e}:${iL}`:e}function ij(){return iL?`auth_${iL}`:"auth"}let i$=ig({appName:"dymg"}),iM=ig({appName:"dymg",subDir:ij()}),iU=new Set(["EACCES","EPERM","EROFS"]),iq=["读取"];function iV(e){return iq.some(t=>e.startsWith(t))}function iH(e){return!!function e(t,r=0){if(t&&!(r>8)){var i;if(t instanceof Error&&iU.has(t.code??""))return t;if("object"==typeof(i=t)&&null!==i&&"cause"in t)return e(t.cause,r+1)}}(e)}function iz(e,t){var r;if(!iH(e))throw e;throw new l(iV(t)?`${t}失败:无法访问或初始化登录态目录`:`${t}失败:登录态目录无写权限`,{cause:e,error:"AUTH_PERMISSION_DENIED",message:iV(r=t)?`${r}失败:当前终端无法访问或初始化登录态目录。`:`${r}失败:当前终端对登录态目录无写权限。`})}let iG="client.json",iW=!1;async function iJ(){try{var e=await iM.readJson(iG);if("string"==typeof e?.clientId&&e.clientId.trim())return{clientId:e.clientId.trim(),clientName:"string"==typeof e.clientName&&e.clientName.trim()?e.clientName.trim():void 0,clientIdIssuedAt:rE(e.clientIdIssuedAt),createdAt:D(e.createdAt)??Math.floor(Date.now()/1e3),updatedAt:D(e.updatedAt)??Math.floor(Date.now()/1e3)};throw new l("本地登录信息异常",{error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"})}catch(e){if(tV(e))return;if(p(e,tj.InvalidJson))throw new l("本地登录信息异常",{cause:e,error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"});iz(e,"读取登录配置")}}function iY(e){if(e)return{clientId:e.clientId,clientName:e.clientName,clientIdIssuedAt:e.clientIdIssuedAt}}async function iK(){return iW?e:(t||(t=(async()=>{try{let t=await iJ(),r=iY(t);return e=r,iW=!0,r}finally{t=void 0}})()),t)}async function iX(t){let r=Math.floor(Date.now()/1e3),i=await iJ(),n={clientId:t.clientId,clientName:t.clientName??i?.clientName,clientIdIssuedAt:t.clientIdIssuedAt??i?.clientIdIssuedAt,createdAt:i?.createdAt??r,updatedAt:r};try{await iM.writeJson(iG,n,{mode:384})}catch(e){iz(e,"保存登录配置")}e=iY(n),iW=!0}async function iQ(e){let t=await iK(),r=function(e){let t=ir((0,tp.hostname)().split(".")[0]??""),r="";try{r=ir((0,tp.userInfo)().username)}catch{r=ir(process.env.USER??process.env.USERNAME??"")}return t&&r?`${t}_${r}`:t||r||e}("dymg");if(t?.clientId)return t.clientId;if(!1===e.enableDynamicClientRegistration)return;let i=await is({registrationEndpoint:e.registrationEndpoint,clientName:r,timeoutMs:e.timeoutMs,httpClient:nl});return await iX({clientId:i.clientId,clientName:"string"==typeof i.raw.client_name&&i.raw.client_name.trim()?i.raw.client_name.trim():r,clientIdIssuedAt:rE(i.raw.client_id_issued_at)}),i.clientId}async function iZ(e={}){var t,r;let i=await io({metadataEndpoint:`${function(){let e="https://developer.open-douyin.com";if(!e)throw new l("当前 CLI 配置异常",{error:"MISSING_BASE_URL",message:"当前 CLI 配置异常,无法完成登录,请重新安装或重新构建后重试"});return e.replace(/\/+$/,"")}()}/mgplatform/api/apps/oauth/.well-known/oauth-authorization-server`,timeoutMs:e.timeoutMs,httpClient:nl}),n=(t=i.raw,r=i.scopesSupported,"string"==typeof t.scope&&t.scope.trim()?t.scope.trim():r.length>0?r.join(" "):void 0),u=await iQ({registrationEndpoint:i.registrationEndpoint,timeoutMs:e.timeoutMs,enableDynamicClientRegistration:e.enableDynamicClientRegistration});if(!u)throw new l("当前 CLI 配置异常",{error:"MISSING_OAUTH_CLIENT_ID",message:"当前 CLI 配置异常,无法完成登录,请重新安装或重新构建后重试"});return{clientId:u,scope:n,tokenEndpoint:i.tokenEndpoint,introspectionEndpoint:i.introspectionEndpoint,revocationEndpoint:i.revocationEndpoint,deviceAuthorizationEndpoint:i.deviceAuthorizationEndpoint}}let i1="profile.json",i0=function(e){let t;function r(){return t||(t=new rH(e())),t}return{get:()=>r().get(),tryGet:()=>r().tryGet(),save:e=>r().save(e),clear:()=>r().clear(),refresh:(e,t)=>r().refresh(e,t),getAccessToken:e=>r().getAccessToken(e),invalidateCache(){r().invalidateCache()},isAccessTokenExpired:e=>r().isAccessTokenExpired(e),isRefreshTokenExpired:e=>r().isRefreshTokenExpired(e)}}(()=>({storage:function(){let{dataDir:e}=im({appName:"dymg"});return new iR({baseDir:(0,I.join)(e,ij()),service:iN(e8),account:iN("default")})}(),fileName:"token.json"}));async function i2(){try{var e;let t;return e=await iM.readJson(i1),t=Math.floor(Date.now()/1e3),{uid:C(e?.uid),oauthAppId:C(e?.oauthAppId),oauthAppName:C(e?.oauthAppName),updatedAt:D(e?.updatedAt)??t}}catch(e){if(tV(e))return;throw e}}async function i3(e){try{await iM.writeJson(i1,e,{mode:384})}catch(e){iz(e,"保存登录信息")}}async function i6(e){let t=await i2(),r=function(e,t){let r={uid:t.uid??e?.uid,oauthAppId:t.oauthAppId??e?.oauthAppId,oauthAppName:t.oauthAppName??e?.oauthAppName,updatedAt:Math.floor(Date.now()/1e3)};if(r.uid||r.oauthAppId||r.oauthAppName)return r}(t,e);return r?(await i3(r),r):t}async function i4(){try{await iM.remove(i1)}catch(e){tV(e)||iz(e,"清理登录信息")}}function i8(e,t){try{return function(e,t={}){let r,i=Math.floor((t.nowMs??Date.now())/1e3),n=rE(e.expires_in)??t.defaultAccessTokenExpiresInSeconds??3600,u=rE(e.refresh_token_expires_in),o=id(e.refresh_token),s=o??t.current?.auth.refreshToken,a=void 0===e.scope?t.current?.auth.scopes??[]:(r=rJ(e.scope))?r.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[];if(!s)throw new rS("OAuth token response is missing refresh_token",{code:rw.InvalidResponse,responseJson:e});let l=void 0!==u?i+u:t.current&&void 0===o?t.current.auth.rtExpiresAt:i+(t.defaultRefreshTokenExpiresInSeconds??2592e3);return{auth:{accessToken:e.access_token,refreshToken:s,atExpiresAt:i+n,rtExpiresAt:l,scopes:a}}}(e,{current:t})}catch(e){throw new l("登录失败,请重新登录",{cause:e,error:"MISSING_REFRESH_TOKEN",message:`登录失败,请重新执行 ${e9}`})}}async function i9(e){await i6({uid:C(e.uid),oauthAppId:C(e.oauth_app_id),oauthAppName:C(e.oauth_app_name)})}async function i7(e){let t;try{t=await iZ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e9}`});throw e}let r=await ia({tokenEndpoint:t.tokenEndpoint,clientId:t.clientId,grantType:"refresh_token",refreshToken:e.auth.refreshToken,scope:e.auth.scopes,httpClient:nl});return await i9(r).catch(()=>void 0),i8(r,e)}function i5(e){var t;if(iH(e)&&iz(e,"刷新登录态"),p(e,"REFRESH_TOKEN_EXPIRED"))throw new l("当前登录已过期,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已过期,请执行 ${e9}`});if(p(t=e,"REFRESH_FAILED")&&rR(t.cause)||rR(e))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e9}`});throw e}async function ne(){try{return await i0.tryGet()}catch(e){throw iH(e)&&iz(e,"读取登录信息"),new l("本地登录信息异常",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`本地登录信息异常,请先执行 ${te},再执行 ${e9}`})}}async function nt(){if(await ne())try{return await i0.getAccessToken(i7)}catch(e){i5(e)}}async function nr(){let e=await ne();if(e)try{return(await i0.refresh(e,i7)).auth.accessToken}catch(e){i5(e)}}async function ni(e){let t;if(e){try{t=await iZ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))return;throw e}try{await ic({revocationEndpoint:t.revocationEndpoint,token:e.auth.refreshToken,tokenTypeHint:"refresh_token",clientId:t.clientId,httpClient:nl})}catch(e){throw new l("退出登录失败,请稍后重试",{cause:e,error:"AUTH_LOGOUT_REVOKE_FAILED",message:"退出登录失败,请检查网络后重试"})}}}async function nn(){let e,t,r=await nt();if(!r)return;try{e=await iZ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e9}`});throw e}try{t=await il({introspectionEndpoint:e.introspectionEndpoint,token:r,tokenTypeHint:"access_token",clientId:e.clientId,httpClient:nl})}catch(e){throw new l("登录态校验失败,请稍后重试或重新登录",{cause:e,error:"AUTH_STATUS_CHECK_FAILED",message:`登录态校验失败,请稍后重试;如问题持续,可执行 ${e9}`})}let i=function(e){let{raw:t}=e;return{...e,uid:C(t.uid),oauthAppId:C(t.oauth_app_id),oauthAppName:C(t.oauth_app_name)}}(t);if(!i.active)throw new l("当前登录已失效,请重新登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e9}`});return await i6({uid:i.uid,oauthAppId:i.oauthAppId,oauthAppName:i.oauthAppName}).catch(()=>void 0),i}async function nu(e,t){let r=i8(e,t);try{await Promise.all([i0.save(r),i9(e).catch(()=>void 0)])}catch(e){iz(e,"保存登录态")}return r}async function no(){try{await Promise.all([i0.clear(),i4()])}catch(e){iz(e,"退出登录")}}let ns=new e2,na=new e2,nl=new e2;function nc(e){return new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:e??`当前命令需要先登录,请先执行 ${e9}`})}function nd(){return new l("当前登录已失效,请重新登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e9}`})}function np(e){if("object"!=typeof e||null===e)return;let t=e.error,r=C(e.message);return{error:"number"==typeof t&&Number.isInteger(t)?t:void 0,message:r}}function nh(e){if(e?.trim())try{return np(JSON.parse(e))}catch{return}}function nf(e,t){let r={...t?.status!==void 0?{status:t.status}:{},...e?.error!==void 0?{error:e.error}:{}};if(e?.error===1002){let e=t?.unauthorizedAsExpired?nd():nc();throw new l(e.message,{cause:t?.cause,error:e.error,message:e.message,details:r})}if(e?.error===1004)throw new l("当前功能尚未开放",{cause:t?.cause,error:"FEATURE_UNAVAILABLE",message:e.message??"当前功能尚未开放,敬请期待",details:r});if(e?.error===1001)throw new l("当前账号暂无权限",{cause:t?.cause,error:"AUTH_PERMISSION_DENIED",message:e.message??"暂无权限,请联系超级管理员/管理员授权",details:r});if(t?.status===401){let e=nd();throw new l(e.message,{cause:t.cause,error:e.error,message:e.message,details:r})}if(t?.status===403)throw new l("当前账号暂无权限",{cause:t.cause,error:"AUTH_PERMISSION_DENIED",message:e?.message??"当前请求被拒绝,请确认权限后重试",details:r});if(e?.message)throw new l("接口调用失败",{cause:t?.cause,error:"API_REQUEST_FAILED",message:e.message,details:r});throw t?.cause??Error("Unknown gateway error")}function nm(e){if(!eY(e))throw e;nf(nh(e.responseBody),{status:e.status,cause:e})}function ng(e){let t=np(e);t&&void 0!==t.error&&0!==t.error&&nf(t)}async function nA(e,t={}){var r,i;let n={url:(r=e).url,method:r.method,params:r.params,data:r.data,headers:r.headers,baseURL:r.baseURL??"https://developer.open-douyin.com",timeoutMs:r.timeoutMs,signal:r.signal};try{let{data:e}=await na.send(n,{meta:t.meta});return ng(e),e}catch(r){eY(i=r)&&401===i.status||nm(r);let e=eY(r)?nh(r.responseBody):void 0;if(!await nr())throw e?.error===1002?nc():nd();try{let{data:e}=await na.send(n,{meta:t.meta});return ng(e),e}catch(e){nm(e)}}}let ny="session.json";async function nE(e){try{await iM.writeJson(ny,e,{mode:384})}catch(e){iz(e,"保存授权会话")}}async function n_(){try{return function(e){let t=C(e?.clientId),r=C(e?.tokenEndpoint),i=C(e?.deviceCode),n=C(e?.userCode),u=C(e?.verificationUri),o=C(e?.codeVerifier),s=D(e?.createdAt),a=D(e?.expiresAt);if(!t||!r||!i||!n||!u||!o||!s||!a)throw new l("本地授权会话异常",{error:"INVALID_AUTH_SESSION",message:`本地授权会话异常,请重新执行 ${e7}`});return{clientId:t,tokenEndpoint:r,deviceCode:i,userCode:n,verificationUri:u,verificationUriComplete:C(e?.verificationUriComplete),codeVerifier:o,intervalSeconds:function(e){if("number"==typeof e&&Number.isFinite(e)&&!(e<=0))return e}(e?.intervalSeconds),createdAt:s,expiresAt:a}}(await iM.readJson(ny))}catch(e){if(tV(e))return;iz(e,"读取授权会话")}}async function nb(){try{await iM.remove(ny)}catch(e){tV(e)||iz(e,"清理授权会话")}}let nv=["coze","doubao","cursor","claude_code","github_copilot","gemini_cli","trae","trae_work","workbuddy","qwen_work","qoder_work","wukong","kimi_work","grok","codebuddy","qwen_code","kimi_code","minimax_code","zcode","mavis","qoder","iflow","lingma","windsurf","cline","roo_code","kiro","opencode","openhands","amp","aider","continue","goose","replit","augment","junie","manus","devin","codex","hermes","openclaw","unknown"];function nC(e){return nv.includes(e)}let nD="宿主枚举:1 全部 / 2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山 / 9 皮皮虾",nF="宿主枚举:2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山",nw="操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony / 5 Windows",nB="设备档位枚举:1 全部 / 2 高端 / 3 中端 / 4 低端";function nx(e,t){let{caller:r}=e.optsWithGlobals();return{...t,caller:"string"==typeof r&&nC(r)?r:"unknown"}}function nS(e){return e.option("--output-dir <dir>","输出根目录,默认 ./dymg-output(会在其下按命令+时间生成子目录,并按命令类型写入结果文件)"),e}async function nT(e){let t=await iK().catch(()=>void 0);return{toolId:e.replaceAll(":"," "),clientId:t?.clientId}}function nI(e){return e.requiredOption("--app-id <appId>","小游戏 appId").option("--start-date <date>","开始日期,格式 YYYY-MM-DD").option("--end-date <date>","结束日期,格式 YYYY-MM-DD").option("--host <host>",nD).option("--os <os>",nw).option("--user-type <userType>","用户类型枚举:1 全部 / 2 新增 / 3 活跃 / 4 付费新增 / 5 付费活跃").option("--segment <segment>","用户分群枚举:1 不分组 / 2 侧边栏奖励 / 3 App 活跃")}function nO(e){return e.requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD").requiredOption("--host <host>",nF).requiredOption("--os <os>","操作系统枚举:2 Android / 3 iOS / 4 OpenHarmony").option("--device-level <n>",nB).option("--mp-version <version>","小游戏版本号")}var nk=__webpack_require__("../../node_modules/.pnpm/@dp+tea-sdk-node@3.0.12/node_modules/@dp/tea-sdk-node/lib/index.js"),nR=__webpack_require__("../../node_modules/.pnpm/@logsdk+node-plugin-http@4.0.11_encoding@0.1.13/node_modules/@logsdk/node-plugin-http/lib/index.js");let nP=Number(626386),nL=null;function nN(){let e=ti();if(e?.tool&&void 0!==e.requestParams)return{caller:e.caller,tool:e.tool,requestParams:e.requestParams}}async function nj(e){let t=(void 0===r&&(r=function(){if(!Number.isFinite(nP)||nP<=0)return null;let e=globalThis.fetch?(e,t)=>globalThis.fetch(e,t):void 0,t=new nk.TeaSDK({app_id:nP}),r=(0,nR.httpPlugin)({channel:"cn",...e?{transport:(t,r)=>e(t,r)}:{}});return nL=r,t.use(r),t.config({custom:{cli_name:"dymg"}}),t}()),r);if(!t)return;let[i,n]=await Promise.all([iK().catch(()=>void 0),i2().catch(()=>void 0)]),u=ti(),o=function(e=3e3){let t=nL;return!t||e<=0?Promise.resolve():new Promise(r=>{let i=()=>{clearTimeout(n),r()},n=setTimeout(()=>{t.removeListener("drain",i),r()},e);t.once("drain",i)})}(),s={caller:e.caller,tool:e.tool,cli_version:"0.7.0",appli_id:u?.appId,user_id:n?.uid,oauth_app_id:n?.oauthAppId,oauth_app_name:n?.oauthAppName,client_id:i?.clientId,client_name:i?.clientName,is_success:+!!e.success,duration_ms:e.durationMs,request_params:e.requestParams,logid:u?.response?.logId,error_message:e.errorMessage,error_code:e.errorCode},a={user:n?{user_id:Number(n?.uid),user_unique_id:n?.uid,user_is_login:!!n?.uid}:void 0};t.collect("game_cli_call",s,a),await o}function n$(e){return d(e)?e.error:void 0}let nM=["npm","pnpm","yarn","bun"],nU=new e2;function nq(e){var t;return(t=e,nM.includes(t))?e:void 0}function nV(e={}){var t;let r=nq(e.input);return void 0!==e.input?r:(t=e.userAgent,nq(t?.split("/")[0])??e.defaultPackageManager)}async function nH(e,t={}){let r=e.trim(),i=t.client??nU,n=(t.registryBaseUrl??"https://registry.npmjs.org").trim().replace(/\/+$/,""),u=t.timeoutMs??3e3,o=t.retry??{maxRetries:2,retryDelayMs:e=>1e3*e};if(!r)throw new eW("packageName is required",{code:eG.InvalidArgument,url:n});let s=encodeURIComponent(r).replace("%2F","%2f"),a=`${n}/${s}/latest`,{data:l}=await i.send({url:a,timeoutMs:u,retry:o});if("string"!=typeof l?.version||""===l.version.trim())throw new eW("package registry response missing version",{code:eG.InvalidJson,url:a});return l.version.trim()}let nz="update-check.json";function nG(e){let t=nV({userAgent:process.env.npm_config_user_agent})?"dymg update":`dymg update --package-manager <${nM.join("|")}>`;return[`检测到 ${e6} 新版本 ${e}(当前 0.7.0)。`,`执行 ${t} 可更新 CLI 并同步随包发布的 Skill。`,"如只想手动同步 Skill,可执行 dymg skills install。"]}async function nW(){try{return await i$.get().readJson(nz)}catch(e){if(tV(e))return{};throw e}}async function nJ(e){await i$.get().writeJson(nz,e)}async function nY(){return nH(e6,{client:ns,timeoutMs:1e4})}async function nK(){let e=await nY();return{currentVersion:"0.7.0",latestVersion:e,hasUpdate:function(e,t){let r=v(e),i=v(t);if(!r||!i)return e.localeCompare(t);for(let n=0;n<3;n+=1){let u=r.main[n],o=i.main[n];if(void 0===u||void 0===o)return e.localeCompare(t);let s=u-o;if(0!==s)return s}if(0===r.prerelease.length&&i.prerelease.length>0)return 1;if(r.prerelease.length>0&&0===i.prerelease.length)return -1;let n=Math.max(r.prerelease.length,i.prerelease.length);for(let e=0;e<n;e+=1){let t=r.prerelease[e],n=i.prerelease[e];if(void 0===t)return -1;if(void 0===n)return 1;let u=function(e,t){let r=/^\d+$/.test(e),i=/^\d+$/.test(t);if(r&&i){var n,u;let r,i;return n=e,u=t,r=n.replace(/^0+/,"")||"0",i=u.replace(/^0+/,"")||"0",r.length!==i.length?r.length-i.length:r.localeCompare(i)}return r?-1:i?1:e.localeCompare(t)}(t,n);if(0!==u)return u}return 0}(e,"0.7.0")>0}}async function nX(e,t={}){let r=await nW(),i=Date.now(),n={...r,lastCheckedAt:i,latestVersion:e.latestVersion};t.notified&&(n.lastNotifiedAt=i,n.lastNotifiedVersion=e.latestVersion),await nJ(n)}async function nQ(e={}){var t,r,i,n,u,o;let s=e.force??!1,a=e.quiet??!1,l=Date.now(),c=await nW();if(t=l,r=c,!s&&!(t-(r.lastCheckedAt??0)>=864e5))return;let d=await nK(),p={...c,lastCheckedAt:l,latestVersion:d.latestVersion};if(d.hasUpdate){i=l,n=c,u=d.latestVersion,(s||(n.lastNotifiedVersion??n.latestVersion)!==u||i-(n.lastNotifiedAt??n.lastPromptedAt??0)>=864e5)&&(o=d.latestVersion,process.stdout.write(["",...nG(o),""].join("\n")),p.lastNotifiedAt=l,p.lastNotifiedVersion=d.latestVersion),await nJ(p);return}a||process.stdout.write(`dymg 已是最新版本(0.7.0)
|
|
34
|
+
`),await nJ(p)}async function nZ(){try{await nQ({quiet:!0})}catch{}}let n1={request:nA,baseURL:""};n1.genBaseURL=e=>"function"==typeof n1.baseURL?n1.baseURL(e):n1.baseURL+e;let n0=(e=0)=>t=>`\u001B[${t+e}m`,n2=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,n3=(e=0)=>(t,r,i)=>`\u001B[${38+e};2;${t};${r};${i}m`,n6={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(n6.modifier);let n4=Object.keys(n6.color);[...n4,...Object.keys(n6.bgColor)];let n8=function(){let e=new Map;for(let[t,r]of Object.entries(n6)){for(let[t,i]of Object.entries(r))n6[t]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[t]=n6[t],e.set(i[0],i[1]);Object.defineProperty(n6,t,{value:r,enumerable:!1})}return Object.defineProperty(n6,"codes",{value:e,enumerable:!1}),n6.color.close="\x1b[39m",n6.bgColor.close="\x1b[49m",n6.color.ansi=n0(),n6.color.ansi256=n2(),n6.color.ansi16m=n3(),n6.bgColor.ansi=n0(10),n6.bgColor.ansi256=n2(10),n6.bgColor.ansi16m=n3(10),Object.defineProperties(n6,{rgbToAnsi256:{value:(e,t,r)=>e===t&&t===r?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(r/255*5),enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[r]=t;3===r.length&&(r=[...r].map(e=>e+e).join(""));let i=Number.parseInt(r,16);return[i>>16&255,i>>8&255,255&i]},enumerable:!1},hexToAnsi256:{value:e=>n6.rgbToAnsi256(...n6.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){let t,r,i;if(e<8)return 30+e;if(e<16)return 90+(e-8);if(e>=232)r=t=((e-232)*10+8)/255,i=t;else{let n=(e-=16)%36;t=Math.floor(e/36)/5,r=Math.floor(n/6)/5,i=n%6/5}let n=2*Math.max(t,r,i);if(0===n)return 30;let u=30+(Math.round(i)<<2|Math.round(r)<<1|Math.round(t));return 2===n&&(u+=60),u},enumerable:!1},rgbToAnsi:{value:(e,t,r)=>n6.ansi256ToAnsi(n6.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>n6.ansi256ToAnsi(n6.hexToAnsi256(e)),enumerable:!1}}),n6}(),n9=require("node:tty");function n7(e,t=globalThis.Deno?globalThis.Deno.args:k.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",i=t.indexOf(r+e),n=t.indexOf("--");return -1!==i&&(-1===n||i<n)}let{env:n5}=k;function ue(e,t={}){var r;return 0!==(r=function(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let n=function(){if("FORCE_COLOR"in n5)return"true"===n5.FORCE_COLOR?1:"false"===n5.FORCE_COLOR?0:0===n5.FORCE_COLOR.length?1:Math.min(Number.parseInt(n5.FORCE_COLOR,10),3)}();void 0!==n&&(i=n);let u=r?i:n;if(0===u)return 0;if(r){if(n7("color=16m")||n7("color=full")||n7("color=truecolor"))return 3;if(n7("color=256"))return 2}if("TF_BUILD"in n5&&"AGENT_NAME"in n5)return 1;if(e&&!t&&void 0===u)return 0;let o=u||0;if("dumb"===n5.TERM)return o;if("win32"===k.platform){let e=tp.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in n5)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in n5)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in n5)||"codeship"===n5.CI_NAME?1:o;if("TEAMCITY_VERSION"in n5)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n5.TEAMCITY_VERSION);if("truecolor"===n5.COLORTERM||"xterm-kitty"===n5.TERM||"xterm-ghostty"===n5.TERM||"wezterm"===n5.TERM)return 3;if("TERM_PROGRAM"in n5){let e=Number.parseInt((n5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n5.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(n5.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n5.TERM)||"COLORTERM"in n5?1:o}(e,{streamIsTTY:e&&e.isTTY,...t}))&&{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}n7("no-color")||n7("no-colors")||n7("color=false")||n7("color=never")?i=0:(n7("color")||n7("colors")||n7("color=true")||n7("color=always"))&&(i=1);let ut={stdout:ue({isTTY:n9.isatty(1)}),stderr:ue({isTTY:n9.isatty(2)})},{stdout:ur,stderr:ui}=ut,un=Symbol("GENERATOR"),uu=Symbol("STYLER"),uo=Symbol("IS_EMPTY"),us=["ansi","ansi","ansi256","ansi16m"],ua=Object.create(null);function ul(e){var t;let r;return t=e,((e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let r=ur?ur.level:0;e.level=void 0===t.level?r:t.level})(r=(...e)=>e.join(" "),t),Object.setPrototypeOf(r,ul.prototype),r}for(let[e,t]of(Object.setPrototypeOf(ul.prototype,Function.prototype),Object.entries(n8)))ua[e]={get(){let r=uh(this,up(t.open,t.close,this[uu]),this[uo]);return Object.defineProperty(this,e,{value:r}),r}};ua.visible={get(){let e=uh(this,this[uu],!0);return Object.defineProperty(this,"visible",{value:e}),e}};let uc=(e,t,r,...i)=>"rgb"===e?"ansi16m"===t?n8[r].ansi16m(...i):"ansi256"===t?n8[r].ansi256(n8.rgbToAnsi256(...i)):n8[r].ansi(n8.rgbToAnsi(...i)):"hex"===e?uc("rgb",t,r,...n8.hexToRgb(...i)):n8[r][e](...i);for(let e of["rgb","hex","ansi256"])ua[e]={get(){let{level:t}=this;return function(...r){return uh(this,up(uc(e,us[t],"color",...r),n8.color.close,this[uu]),this[uo])}}},ua["bg"+e[0].toUpperCase()+e.slice(1)]={get(){let{level:t}=this;return function(...r){return uh(this,up(uc(e,us[t],"bgColor",...r),n8.bgColor.close,this[uu]),this[uo])}}};let ud=Object.defineProperties(()=>{},{...ua,level:{enumerable:!0,get(){return this[un].level},set(e){this[un].level=e}}}),up=(e,t,r)=>{let i,n;return void 0===r?(i=e,n=t):(i=r.openAll+e,n=t+r.closeAll),{open:e,close:t,openAll:i,closeAll:n,parent:r}},uh=(e,t,r)=>{let i=(...e)=>uf(i,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(i,ud),i[un]=e,i[uu]=t,i[uo]=r,i},uf=(e,t)=>{if(e.level<=0||!t)return e[uo]?"":t;let r=e[uu];if(void 0===r)return t;let{openAll:i,closeAll:n}=r;if(t.includes("\x1b"))for(;void 0!==r;)t=function(e,t,r){let i=e.indexOf(t);if(-1===i)return e;let n=t.length,u=0,o="";do o+=e.slice(u,i)+t+r,u=i+n,i=e.indexOf(t,u);while(-1!==i);return o+=e.slice(u)}(t,r.close,r.open),r=r.parent;let u=t.indexOf("\n");return -1!==u&&(t=function(e,t,r,i){let n=0,u="";do{let o="\r"===e[i-1];u+=e.slice(n,o?i-1:i)+t+(o?"\r\n":"\n")+r,n=i+1,i=e.indexOf("\n",n)}while(-1!==i);return u+=e.slice(n)}(t,n,i,u)),i+t+n};Object.defineProperties(ul.prototype,ua);let um=ul();ul({level:ui?ui.level:0});let ug=(e,t,r,i)=>{if("length"===r||"prototype"===r||"arguments"===r||"caller"===r)return;let n=Object.getOwnPropertyDescriptor(e,r),u=Object.getOwnPropertyDescriptor(t,r);(uA(n,u)||!i)&&Object.defineProperty(e,r,u)},uA=function(e,t){return void 0===e||e.configurable||e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable&&(e.writable||e.value===t.value)},uy=(e,t)=>`/* Wrapped ${e}*/
|
|
35
|
+
${t}`,uE=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),u_=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),ub=new WeakMap,uv=(e,t={})=>{let r;if("function"!=typeof e)throw TypeError("Expected a function");let i=0,n=e.displayName||e.name||"<anonymous>",u=function(...o){if(ub.set(u,++i),1===i)r=e.apply(this,o),e=void 0;else if(!0===t.throw)throw Error(`Function \`${n}\` can only be called once`);return r};return!function(e,t,{ignoreNonConfigurable:r=!1}={}){var i;let n,{name:u}=e;for(let i of Reflect.ownKeys(t))ug(e,t,i,r);i=e,(n=Object.getPrototypeOf(t))!==Object.getPrototypeOf(i)&&Object.setPrototypeOf(i,n),((e,t,r)=>{let i=""===r?"":`with ${r.trim()}() `,n=uy.bind(null,i,t.toString());Object.defineProperty(n,"name",u_);let{writable:u,enumerable:o,configurable:s}=uE;Object.defineProperty(e,"toString",{value:n,writable:u,enumerable:o,configurable:s})})(e,t,u)}(u,e),ub.set(u,i),u};uv.callCount=e=>{if(!ub.has(e))throw Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return ub.get(e)};let uC=[];uC.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&uC.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&uC.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");let uD=e=>!!e&&"object"==typeof e&&"function"==typeof e.removeListener&&"function"==typeof e.emit&&"function"==typeof e.reallyExit&&"function"==typeof e.listeners&&"function"==typeof e.kill&&"number"==typeof e.pid&&"function"==typeof e.on,uF=Symbol.for("signal-exit emitter"),uw=globalThis,uB=Object.defineProperty.bind(Object);class ux{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(uw[uF])return uw[uF];uB(uw,uF,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let r=this.listeners[e],i=r.indexOf(t);-1!==i&&(0===i&&1===r.length?r.length=0:r.splice(i,1))}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let i=!1;for(let n of this.listeners[e])i=!0===n(t,r)||i;return"exit"===e&&(i=this.emit("afterExit",t,r)||i),i}}class uS{}class uT extends uS{#i="win32"===uI.platform?"SIGINT":"SIGHUP";#n=new ux;#u;#o;#s;#a={};#l=!1;constructor(e){for(const t of(super(),this.#u=e,this.#a={},uC))this.#a[t]=()=>{let r=this.#u.listeners(t),{count:i}=this.#n;if("object"==typeof e.__signal_exit_emitter__&&"number"==typeof e.__signal_exit_emitter__.count&&(i+=e.__signal_exit_emitter__.count),r.length===i){this.unload();let r=this.#n.emit("exit",null,t),i="SIGHUP"===t?this.#i:t;r||e.kill(e.pid,i)}};this.#s=e.reallyExit,this.#o=e.emit}onExit(e,t){if(!uD(this.#u))return()=>{};!1===this.#l&&this.load();let r=t?.alwaysLast?"afterExit":"exit";return this.#n.on(r,e),()=>{this.#n.removeListener(r,e),0===this.#n.listeners.exit.length&&0===this.#n.listeners.afterExit.length&&this.unload()}}load(){if(!this.#l){for(let e of(this.#l=!0,this.#n.count+=1,uC))try{let t=this.#a[e];t&&this.#u.on(e,t)}catch(e){}this.#u.emit=(e,...t)=>this.#c(e,...t),this.#u.reallyExit=e=>this.#d(e)}}unload(){this.#l&&(this.#l=!1,uC.forEach(e=>{let t=this.#a[e];if(!t)throw Error("Listener not defined for signal: "+e);try{this.#u.removeListener(e,t)}catch(e){}}),this.#u.emit=this.#o,this.#u.reallyExit=this.#s,this.#n.count-=1)}#d(e){return uD(this.#u)?(this.#u.exitCode=e||0,this.#n.emit("exit",this.#u.exitCode,null),this.#s.call(this.#u,this.#u.exitCode)):0}#c(e,...t){let r=this.#o;if(!("exit"===e&&uD(this.#u)))return r.call(this.#u,e,...t);{"number"==typeof t[0]&&(this.#u.exitCode=t[0]);let i=r.call(this.#u,e,...t);return this.#n.emit("exit",this.#u.exitCode,null),i}}}let uI=globalThis.process,{onExit:uO,load:uk,unload:uR}=(u=uD(uI)?new uT(uI):new class extends uS{onExit(){return()=>{}}load(){}unload(){}},{onExit:(e,t)=>u.onExit(e,t),load:()=>u.load(),unload:()=>u.unload()}),uP=k.stderr.isTTY?k.stderr:k.stdout.isTTY?k.stdout:void 0,uL=uP?uv(()=>{uO(()=>{uP.write("\x1b[?25h")},{alwaysLast:!0})}):()=>{},uN=!1,uj={};uj.show=(e=k.stderr)=>{e.isTTY&&(uN=!1,e.write("\x1b[?25h"))},uj.hide=(e=k.stderr)=>{e.isTTY&&(uL(),uN=!0,e.write("\x1b[?25l"))},uj.toggle=(e,t)=>{void 0!==e&&(uN=e),uN?uj.show(t):uj.hide(t)};var u$=JSON.parse('{"dots":{"interval":80,"frames":["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},"dots2":{"interval":80,"frames":["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},"dots3":{"interval":80,"frames":["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},"dots4":{"interval":80,"frames":["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},"dots5":{"interval":80,"frames":["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},"dots6":{"interval":80,"frames":["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},"dots7":{"interval":80,"frames":["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},"dots8":{"interval":80,"frames":["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},"dots9":{"interval":80,"frames":["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},"dots10":{"interval":80,"frames":["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},"dots11":{"interval":100,"frames":["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},"dots12":{"interval":80,"frames":["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},"dots13":{"interval":80,"frames":["⣼","⣹","⢻","⠿","⡟","⣏","⣧","⣶"]},"dots14":{"interval":80,"frames":["⠉⠉","⠈⠙","⠀⠹","⠀⢸","⠀⣰","⢀⣠","⣀⣀","⣄⡀","⣆⠀","⡇⠀","⠏⠀","⠋⠁"]},"dots8Bit":{"interval":80,"frames":["⠀","⠁","⠂","⠃","⠄","⠅","⠆","⠇","⡀","⡁","⡂","⡃","⡄","⡅","⡆","⡇","⠈","⠉","⠊","⠋","⠌","⠍","⠎","⠏","⡈","⡉","⡊","⡋","⡌","⡍","⡎","⡏","⠐","⠑","⠒","⠓","⠔","⠕","⠖","⠗","⡐","⡑","⡒","⡓","⡔","⡕","⡖","⡗","⠘","⠙","⠚","⠛","⠜","⠝","⠞","⠟","⡘","⡙","⡚","⡛","⡜","⡝","⡞","⡟","⠠","⠡","⠢","⠣","⠤","⠥","⠦","⠧","⡠","⡡","⡢","⡣","⡤","⡥","⡦","⡧","⠨","⠩","⠪","⠫","⠬","⠭","⠮","⠯","⡨","⡩","⡪","⡫","⡬","⡭","⡮","⡯","⠰","⠱","⠲","⠳","⠴","⠵","⠶","⠷","⡰","⡱","⡲","⡳","⡴","⡵","⡶","⡷","⠸","⠹","⠺","⠻","⠼","⠽","⠾","⠿","⡸","⡹","⡺","⡻","⡼","⡽","⡾","⡿","⢀","⢁","⢂","⢃","⢄","⢅","⢆","⢇","⣀","⣁","⣂","⣃","⣄","⣅","⣆","⣇","⢈","⢉","⢊","⢋","⢌","⢍","⢎","⢏","⣈","⣉","⣊","⣋","⣌","⣍","⣎","⣏","⢐","⢑","⢒","⢓","⢔","⢕","⢖","⢗","⣐","⣑","⣒","⣓","⣔","⣕","⣖","⣗","⢘","⢙","⢚","⢛","⢜","⢝","⢞","⢟","⣘","⣙","⣚","⣛","⣜","⣝","⣞","⣟","⢠","⢡","⢢","⢣","⢤","⢥","⢦","⢧","⣠","⣡","⣢","⣣","⣤","⣥","⣦","⣧","⢨","⢩","⢪","⢫","⢬","⢭","⢮","⢯","⣨","⣩","⣪","⣫","⣬","⣭","⣮","⣯","⢰","⢱","⢲","⢳","⢴","⢵","⢶","⢷","⣰","⣱","⣲","⣳","⣴","⣵","⣶","⣷","⢸","⢹","⢺","⢻","⢼","⢽","⢾","⢿","⣸","⣹","⣺","⣻","⣼","⣽","⣾","⣿"]},"dotsCircle":{"interval":80,"frames":["⢎ ","⠎⠁","⠊⠑","⠈⠱"," ⡱","⢀⡰","⢄⡠","⢆⡀"]},"sand":{"interval":80,"frames":["⠁","⠂","⠄","⡀","⡈","⡐","⡠","⣀","⣁","⣂","⣄","⣌","⣔","⣤","⣥","⣦","⣮","⣶","⣷","⣿","⡿","⠿","⢟","⠟","⡛","⠛","⠫","⢋","⠋","⠍","⡉","⠉","⠑","⠡","⢁"]},"line":{"interval":130,"frames":["-","\\\\","|","/"]},"line2":{"interval":100,"frames":["⠂","-","–","—","–","-"]},"rollingLine":{"interval":80,"frames":["/ "," - "," \\\\ "," |"," |"," \\\\ "," - ","/ "]},"pipe":{"interval":100,"frames":["┤","┘","┴","└","├","┌","┬","┐"]},"simpleDots":{"interval":400,"frames":[". ",".. ","..."," "]},"simpleDotsScrolling":{"interval":200,"frames":[". ",".. ","..."," .."," ."," "]},"star":{"interval":70,"frames":["✶","✸","✹","✺","✹","✷"]},"star2":{"interval":80,"frames":["+","x","*"]},"flip":{"interval":70,"frames":["_","_","_","-","`","`","\'","\xb4","-","_","_","_"]},"hamburger":{"interval":100,"frames":["☱","☲","☴"]},"growVertical":{"interval":120,"frames":["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},"growHorizontal":{"interval":120,"frames":["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},"balloon":{"interval":140,"frames":[" ",".","o","O","@","*"," "]},"balloon2":{"interval":120,"frames":[".","o","O","\xb0","O","o","."]},"noise":{"interval":100,"frames":["▓","▒","░"]},"bounce":{"interval":120,"frames":["⠁","⠂","⠄","⠂"]},"boxBounce":{"interval":120,"frames":["▖","▘","▝","▗"]},"boxBounce2":{"interval":100,"frames":["▌","▀","▐","▄"]},"triangle":{"interval":50,"frames":["◢","◣","◤","◥"]},"binary":{"interval":80,"frames":["010010","001100","100101","111010","111101","010111","101011","111000","110011","110101"]},"arc":{"interval":100,"frames":["◜","◠","◝","◞","◡","◟"]},"circle":{"interval":120,"frames":["◡","⊙","◠"]},"squareCorners":{"interval":180,"frames":["◰","◳","◲","◱"]},"circleQuarters":{"interval":120,"frames":["◴","◷","◶","◵"]},"circleHalves":{"interval":50,"frames":["◐","◓","◑","◒"]},"squish":{"interval":100,"frames":["╫","╪"]},"toggle":{"interval":250,"frames":["⊶","⊷"]},"toggle2":{"interval":80,"frames":["▫","▪"]},"toggle3":{"interval":120,"frames":["□","■"]},"toggle4":{"interval":100,"frames":["■","□","▪","▫"]},"toggle5":{"interval":100,"frames":["▮","▯"]},"toggle6":{"interval":300,"frames":["ဝ","၀"]},"toggle7":{"interval":80,"frames":["⦾","⦿"]},"toggle8":{"interval":100,"frames":["◍","◌"]},"toggle9":{"interval":100,"frames":["◉","◎"]},"toggle10":{"interval":100,"frames":["㊂","㊀","㊁"]},"toggle11":{"interval":50,"frames":["⧇","⧆"]},"toggle12":{"interval":120,"frames":["☗","☖"]},"toggle13":{"interval":80,"frames":["=","*","-"]},"arrow":{"interval":100,"frames":["←","↖","↑","↗","→","↘","↓","↙"]},"arrow2":{"interval":80,"frames":["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},"arrow3":{"interval":120,"frames":["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},"bouncingBar":{"interval":80,"frames":["[ ]","[= ]","[== ]","[=== ]","[====]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},"bouncingBall":{"interval":80,"frames":["( ● )","( ● )","( ● )","( ● )","( ●)","( ● )","( ● )","( ● )","( ● )","(● )"]},"smiley":{"interval":200,"frames":["\uD83D\uDE04 ","\uD83D\uDE1D "]},"monkey":{"interval":300,"frames":["\uD83D\uDE48 ","\uD83D\uDE48 ","\uD83D\uDE49 ","\uD83D\uDE4A "]},"hearts":{"interval":100,"frames":["\uD83D\uDC9B ","\uD83D\uDC99 ","\uD83D\uDC9C ","\uD83D\uDC9A ","\uD83D\uDC97 "]},"clock":{"interval":100,"frames":["\uD83D\uDD5B ","\uD83D\uDD50 ","\uD83D\uDD51 ","\uD83D\uDD52 ","\uD83D\uDD53 ","\uD83D\uDD54 ","\uD83D\uDD55 ","\uD83D\uDD56 ","\uD83D\uDD57 ","\uD83D\uDD58 ","\uD83D\uDD59 ","\uD83D\uDD5A "]},"earth":{"interval":180,"frames":["\uD83C\uDF0D ","\uD83C\uDF0E ","\uD83C\uDF0F "]},"material":{"interval":17,"frames":["█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁","███████▁▁▁▁▁▁▁▁▁▁▁▁▁","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","██████████▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","█████████████▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁██████████████▁▁▁▁","▁▁▁██████████████▁▁▁","▁▁▁▁█████████████▁▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁██████████████▁▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁██████████████▁","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁██████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁█████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁████████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁███████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁██████████","▁▁▁▁▁▁▁▁▁▁▁▁████████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","██████▁▁▁▁▁▁▁▁▁▁▁▁▁█","████████▁▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","█████████▁▁▁▁▁▁▁▁▁▁▁","███████████▁▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","████████████▁▁▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","██████████████▁▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁██████████████▁▁▁▁▁","▁▁▁█████████████▁▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁████████████▁▁▁","▁▁▁▁▁▁███████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁█████████▁▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁█████████▁▁","▁▁▁▁▁▁▁▁▁▁█████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁████████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁███████▁","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁███████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁","▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁"]},"moon":{"interval":80,"frames":["\uD83C\uDF11 ","\uD83C\uDF12 ","\uD83C\uDF13 ","\uD83C\uDF14 ","\uD83C\uDF15 ","\uD83C\uDF16 ","\uD83C\uDF17 ","\uD83C\uDF18 "]},"runner":{"interval":140,"frames":["\uD83D\uDEB6 ","\uD83C\uDFC3 "]},"pong":{"interval":80,"frames":["▐⠂ ▌","▐⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂▌","▐ ⠠▌","▐ ⡀▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐⠠ ▌"]},"shark":{"interval":120,"frames":["▐|\\\\____________▌","▐_|\\\\___________▌","▐__|\\\\__________▌","▐___|\\\\_________▌","▐____|\\\\________▌","▐_____|\\\\_______▌","▐______|\\\\______▌","▐_______|\\\\_____▌","▐________|\\\\____▌","▐_________|\\\\___▌","▐__________|\\\\__▌","▐___________|\\\\_▌","▐____________|\\\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},"dqpb":{"interval":100,"frames":["d","q","p","b"]},"weather":{"interval":100,"frames":["☀️ ","☀️ ","☀️ ","\uD83C\uDF24 ","⛅️ ","\uD83C\uDF25 ","☁️ ","\uD83C\uDF27 ","\uD83C\uDF28 ","\uD83C\uDF27 ","\uD83C\uDF28 ","\uD83C\uDF27 ","\uD83C\uDF28 ","⛈ ","\uD83C\uDF28 ","\uD83C\uDF27 ","\uD83C\uDF28 ","☁️ ","\uD83C\uDF25 ","⛅️ ","\uD83C\uDF24 ","☀️ ","☀️ "]},"christmas":{"interval":400,"frames":["\uD83C\uDF32","\uD83C\uDF84"]},"grenade":{"interval":80,"frames":["، ","′ "," \xb4 "," ‾ "," ⸌"," ⸊"," |"," ⁎"," ⁕"," ෴ "," ⁓"," "," "," "]},"point":{"interval":125,"frames":["∙∙∙","●∙∙","∙●∙","∙∙●","∙∙∙"]},"layer":{"interval":150,"frames":["-","=","≡"]},"betaWave":{"interval":80,"frames":["ρββββββ","βρβββββ","ββρββββ","βββρβββ","ββββρββ","βββββρβ","ββββββρ"]},"fingerDance":{"interval":160,"frames":["\uD83E\uDD18 ","\uD83E\uDD1F ","\uD83D\uDD96 ","✋ ","\uD83E\uDD1A ","\uD83D\uDC46 "]},"fistBump":{"interval":80,"frames":["\uD83E\uDD1C \uD83E\uDD1B ","\uD83E\uDD1C \uD83E\uDD1B ","\uD83E\uDD1C \uD83E\uDD1B "," \uD83E\uDD1C \uD83E\uDD1B "," \uD83E\uDD1C\uD83E\uDD1B "," \uD83E\uDD1C✨\uD83E\uDD1B ","\uD83E\uDD1C ✨ \uD83E\uDD1B "]},"soccerHeader":{"interval":80,"frames":[" \uD83E\uDDD1⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️\uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 ","\uD83E\uDDD1 ⚽️ \uD83E\uDDD1 "]},"mindblown":{"interval":160,"frames":["\uD83D\uDE10 ","\uD83D\uDE10 ","\uD83D\uDE2E ","\uD83D\uDE2E ","\uD83D\uDE26 ","\uD83D\uDE26 ","\uD83D\uDE27 ","\uD83D\uDE27 ","\uD83E\uDD2F ","\uD83D\uDCA5 ","✨ "," "," "," "]},"speaker":{"interval":160,"frames":["\uD83D\uDD08 ","\uD83D\uDD09 ","\uD83D\uDD0A ","\uD83D\uDD09 "]},"orangePulse":{"interval":100,"frames":["\uD83D\uDD38 ","\uD83D\uDD36 ","\uD83D\uDFE0 ","\uD83D\uDFE0 ","\uD83D\uDD36 "]},"bluePulse":{"interval":100,"frames":["\uD83D\uDD39 ","\uD83D\uDD37 ","\uD83D\uDD35 ","\uD83D\uDD35 ","\uD83D\uDD37 "]},"orangeBluePulse":{"interval":100,"frames":["\uD83D\uDD38 ","\uD83D\uDD36 ","\uD83D\uDFE0 ","\uD83D\uDFE0 ","\uD83D\uDD36 ","\uD83D\uDD39 ","\uD83D\uDD37 ","\uD83D\uDD35 ","\uD83D\uDD35 ","\uD83D\uDD37 "]},"timeTravel":{"interval":100,"frames":["\uD83D\uDD5B ","\uD83D\uDD5A ","\uD83D\uDD59 ","\uD83D\uDD58 ","\uD83D\uDD57 ","\uD83D\uDD56 ","\uD83D\uDD55 ","\uD83D\uDD54 ","\uD83D\uDD53 ","\uD83D\uDD52 ","\uD83D\uDD51 ","\uD83D\uDD50 "]},"aesthetic":{"interval":80,"frames":["▰▱▱▱▱▱▱","▰▰▱▱▱▱▱","▰▰▰▱▱▱▱","▰▰▰▰▱▱▱","▰▰▰▰▰▱▱","▰▰▰▰▰▰▱","▰▰▰▰▰▰▰","▰▱▱▱▱▱▱"]},"dwarfFortress":{"interval":80,"frames":[" ██████\xa3\xa3\xa3 ","☺██████\xa3\xa3\xa3 ","☺██████\xa3\xa3\xa3 ","☺▓█████\xa3\xa3\xa3 ","☺▓█████\xa3\xa3\xa3 ","☺▒█████\xa3\xa3\xa3 ","☺▒█████\xa3\xa3\xa3 ","☺░█████\xa3\xa3\xa3 ","☺░█████\xa3\xa3\xa3 ","☺ █████\xa3\xa3\xa3 "," ☺█████\xa3\xa3\xa3 "," ☺█████\xa3\xa3\xa3 "," ☺▓████\xa3\xa3\xa3 "," ☺▓████\xa3\xa3\xa3 "," ☺▒████\xa3\xa3\xa3 "," ☺▒████\xa3\xa3\xa3 "," ☺░████\xa3\xa3\xa3 "," ☺░████\xa3\xa3\xa3 "," ☺ ████\xa3\xa3\xa3 "," ☺████\xa3\xa3\xa3 "," ☺████\xa3\xa3\xa3 "," ☺▓███\xa3\xa3\xa3 "," ☺▓███\xa3\xa3\xa3 "," ☺▒███\xa3\xa3\xa3 "," ☺▒███\xa3\xa3\xa3 "," ☺░███\xa3\xa3\xa3 "," ☺░███\xa3\xa3\xa3 "," ☺ ███\xa3\xa3\xa3 "," ☺███\xa3\xa3\xa3 "," ☺███\xa3\xa3\xa3 "," ☺▓██\xa3\xa3\xa3 "," ☺▓██\xa3\xa3\xa3 "," ☺▒██\xa3\xa3\xa3 "," ☺▒██\xa3\xa3\xa3 "," ☺░██\xa3\xa3\xa3 "," ☺░██\xa3\xa3\xa3 "," ☺ ██\xa3\xa3\xa3 "," ☺██\xa3\xa3\xa3 "," ☺██\xa3\xa3\xa3 "," ☺▓█\xa3\xa3\xa3 "," ☺▓█\xa3\xa3\xa3 "," ☺▒█\xa3\xa3\xa3 "," ☺▒█\xa3\xa3\xa3 "," ☺░█\xa3\xa3\xa3 "," ☺░█\xa3\xa3\xa3 "," ☺ █\xa3\xa3\xa3 "," ☺█\xa3\xa3\xa3 "," ☺█\xa3\xa3\xa3 "," ☺▓\xa3\xa3\xa3 "," ☺▓\xa3\xa3\xa3 "," ☺▒\xa3\xa3\xa3 "," ☺▒\xa3\xa3\xa3 "," ☺░\xa3\xa3\xa3 "," ☺░\xa3\xa3\xa3 "," ☺ \xa3\xa3\xa3 "," ☺\xa3\xa3\xa3 "," ☺\xa3\xa3\xa3 "," ☺▓\xa3\xa3 "," ☺▓\xa3\xa3 "," ☺▒\xa3\xa3 "," ☺▒\xa3\xa3 "," ☺░\xa3\xa3 "," ☺░\xa3\xa3 "," ☺ \xa3\xa3 "," ☺\xa3\xa3 "," ☺\xa3\xa3 "," ☺▓\xa3 "," ☺▓\xa3 "," ☺▒\xa3 "," ☺▒\xa3 "," ☺░\xa3 "," ☺░\xa3 "," ☺ \xa3 "," ☺\xa3 "," ☺\xa3 "," ☺▓ "," ☺▓ "," ☺▒ "," ☺▒ "," ☺░ "," ☺░ "," ☺ "," ☺ &"," ☺ ☼&"," ☺ ☼ &"," ☺☼ &"," ☺☼ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & "," ‼ & "," ☺ & ","‼ & "," & "," & "," & ░ "," & ▒ "," & ▓ "," & \xa3 "," & ░\xa3 "," & ▒\xa3 "," & ▓\xa3 "," & \xa3\xa3 "," & ░\xa3\xa3 "," & ▒\xa3\xa3 ","& ▓\xa3\xa3 ","& \xa3\xa3\xa3 "," ░\xa3\xa3\xa3 "," ▒\xa3\xa3\xa3 "," ▓\xa3\xa3\xa3 "," █\xa3\xa3\xa3 "," ░█\xa3\xa3\xa3 "," ▒█\xa3\xa3\xa3 "," ▓█\xa3\xa3\xa3 "," ██\xa3\xa3\xa3 "," ░██\xa3\xa3\xa3 "," ▒██\xa3\xa3\xa3 "," ▓██\xa3\xa3\xa3 "," ███\xa3\xa3\xa3 "," ░███\xa3\xa3\xa3 "," ▒███\xa3\xa3\xa3 "," ▓███\xa3\xa3\xa3 "," ████\xa3\xa3\xa3 "," ░████\xa3\xa3\xa3 "," ▒████\xa3\xa3\xa3 "," ▓████\xa3\xa3\xa3 "," █████\xa3\xa3\xa3 "," ░█████\xa3\xa3\xa3 "," ▒█████\xa3\xa3\xa3 "," ▓█████\xa3\xa3\xa3 "," ██████\xa3\xa3\xa3 "," ██████\xa3\xa3\xa3 "]},"fish":{"interval":80,"frames":["~~~~~~~~~~~~~~~~~~~~","> ~~~~~~~~~~~~~~~~~~","\xba> ~~~~~~~~~~~~~~~~~","(\xba> ~~~~~~~~~~~~~~~~","((\xba> ~~~~~~~~~~~~~~~","<((\xba> ~~~~~~~~~~~~~~","><((\xba> ~~~~~~~~~~~~~"," ><((\xba> ~~~~~~~~~~~~","~ ><((\xba> ~~~~~~~~~~~","~~ <>((\xba> ~~~~~~~~~~","~~~ ><((\xba> ~~~~~~~~~","~~~~ <>((\xba> ~~~~~~~~","~~~~~ ><((\xba> ~~~~~~~","~~~~~~ <>((\xba> ~~~~~~","~~~~~~~ ><((\xba> ~~~~~","~~~~~~~~ <>((\xba> ~~~~","~~~~~~~~~ ><((\xba> ~~~","~~~~~~~~~~ <>((\xba> ~~","~~~~~~~~~~~ ><((\xba> ~","~~~~~~~~~~~~ <>((\xba> ","~~~~~~~~~~~~~ ><((\xba>","~~~~~~~~~~~~~~ <>((\xba","~~~~~~~~~~~~~~~ ><((","~~~~~~~~~~~~~~~~ <>(","~~~~~~~~~~~~~~~~~ ><","~~~~~~~~~~~~~~~~~~ <","~~~~~~~~~~~~~~~~~~~~"]}}');Object.keys(u$);let uM=n9?.WriteStream?.prototype?.hasColors?.()??!1,uU=(e,t)=>{if(!uM)return e=>e;let r=`\u001B[${e}m`,i=`\u001B[${t}m`;return e=>{let n=e+"",u=n.indexOf(i);if(-1===u)return r+n+i;let o=r,s=0,a=(22===t?i:"")+r;for(;-1!==u;)o+=n.slice(s,u)+a,s=u+i.length,u=n.indexOf(i,s);return o+=n.slice(s)+i}};uU(0,0),uU(1,22),uU(2,22),uU(3,23),uU(4,24),uU(53,55),uU(7,27),uU(8,28),uU(9,29),uU(30,39);let uq=uU(31,39),uV=uU(32,39),uH=uU(33,39),uz=uU(34,39);function uG(){let{env:e}=k,{TERM:t,TERM_PROGRAM:r}=e;return"win32"!==k.platform?"linux"!==t:!!e.WT_SESSION||!!e.TERMINUS_SUBLIME||"{cmd::Cmder}"===e.ConEmuTask||"Terminus-Sublime"===r||"vscode"===r||"xterm-256color"===t||"alacritty"===t||"rxvt-unicode"===t||"rxvt-unicode-256color"===t||"JetBrains-JediTerm"===e.TERMINAL_EMULATOR}uU(35,39),uU(36,39),uU(37,39),uU(90,39),uU(40,49),uU(41,49),uU(42,49),uU(43,49),uU(44,49),uU(45,49),uU(46,49),uU(47,49),uU(100,49),uU(91,39),uU(92,39),uU(93,39),uU(94,39),uU(95,39),uU(96,39),uU(97,39),uU(101,49),uU(102,49),uU(103,49),uU(104,49),uU(105,49),uU(106,49),uU(107,49);let uW=uG(),uJ=uz(uW?"ℹ":"i"),uY=uV(uW?"✔":"√"),uK=uH(uW?"⚠":"‼"),uX=uq(uW?"✖":"\xd7"),uQ=function({onlyFirst:e=!1}={}){let t="(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))";return RegExp(`${t}|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,e?void 0:"g")}(),uZ=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],u1=[12288,12288,65281,65376,65504,65510],u0=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141],u2=(e,t)=>{let r=0,i=Math.floor(e.length/2)-1;for(;r<=i;){let n=Math.floor((r+i)/2),u=2*n;if(t<e[u])i=n-1;else{if(!(t>e[u+1]))return!0;r=n+1}}return!1},[u3,u6]=function(e){let t=e[0],r=e[1];for(let i=0;i<e.length;i+=2){let n=e[i],u=e[i+1];if(19968>=n&&19968<=u)return[n,u];u-n>r-t&&(t=n,r=u)}return[t,r]}(u0);function u4(e,{ambiguousAsWide:t=!1}={}){var r,i,n,u=e;if(!Number.isSafeInteger(u))throw TypeError(`Expected a code point, got \`${typeof u}\`.`);return!((r=e)<12288)&&!(r>65510)&&u2(u1,r)||(i=e)>=u3&&i<=u6||!(i<4352)&&!(i>262141)&&u2(u0,i)||t&&!((n=e)<161)&&!(n>1114109)&&u2(uZ,n)?2:1}let u8=new Intl.Segmenter,u9=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,u7=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,u5=/^\p{RGI_Emoji}$/v,oe=/^[\d#*]\u20E3$/,ot=/\p{Extended_Pictographic}/gu;function or(e){return e>=4352&&e<=4447||e>=43360&&e<=43388}function oi(e){return e>=4448&&e<=4519||e>=55216&&e<=55238}function on(e){return e>=4520&&e<=4607||e>=55243&&e<=55291}let ou=Object.freeze(new class{#p=0;#h;#f=!1;#m=!1;#g=e=>{e?.length&&("string"==typeof e?e.codePointAt(0):e[0])===3&&k.kill(k.pid,"SIGINT")};start(){this.#p++,1===this.#p&&this.#A()}stop(){0!==this.#p&&0==--this.#p&&this.#y()}#A(){let{stdin:e}=k;if("win32"===k.platform||!e?.isTTY||"function"!=typeof e.setRawMode){this.#h=void 0;return}this.#h=e,this.#f=e.isPaused(),this.#m=!!e.isRaw,e.setRawMode(!0),e.prependListener("data",this.#g),this.#f&&e.resume()}#y(){if(!this.#h)return;let e=this.#h;e.off("data",this.#g),e.isTTY&&e.setRawMode?.(this.#m),this.#f&&e.pause(),this.#h=void 0,this.#f=!1,this.#m=!1}}),oo=new Map,os=new Set(["black","red","green","yellow","blue","magenta","cyan","white","gray"]);class oa{#E=0;#_=-1;#b=0;#v;#C;#D;#F;#w=new Map;#B=!1;#x;#S;#T=!1;#I;#O(e){this.#B=!0;try{return e()}finally{this.#B=!1}}#k(){this.isSpinning&&this.render()}#R(e,t){return null==e?"":"string"==typeof e?e:Buffer.isBuffer(e)||ArrayBuffer.isView(e)?Buffer.from(e).toString("string"==typeof t&&t&&"buffer"!==t?t:"utf8"):String(e)}#P(e){if(!e)return!1;let t=e.at(-1);return"\n"===t||"\r"===t}#L(){this.#S||(this.#S=setTimeout(()=>{this.#S=void 0,this.isSpinning&&this.#k()},200),"function"==typeof this.#S?.unref&&this.#S.unref())}#N(){this.#S&&(clearTimeout(this.#S),this.#S=void 0)}#j(e,t,r,i){let n=this.#$(r," ");return n+e+("string"==typeof t?(e?" ":"")+t:"")+this.#M(i," ")}constructor(e){if("string"==typeof e&&(e={text:e}),this.#v={color:"cyan",stream:k.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#v.color,this.#D=this.#v.stream,"boolean"!=typeof this.#v.isEnabled&&(this.#v.isEnabled=function({stream:e=process.stdout}={}){return!!(e&&e.isTTY&&"dumb"!==process.env.TERM&&!("CI"in process.env))}({stream:this.#D})),"boolean"!=typeof this.#v.isSilent&&(this.#v.isSilent=!1),void 0!==this.#v.interval&&!(Number.isInteger(this.#v.interval)&&this.#v.interval>0))throw Error("The `interval` option must be a positive integer");const t=this.#v.interval;this.spinner=this.#v.spinner,this.#v.interval=t,this.text=this.#v.text,this.prefixText=this.#v.prefixText,this.suffixText=this.#v.suffixText,this.indent=this.#v.indent,"test"===k.env.NODE_ENV&&(this._stream=this.#D,this._isEnabled=this.#v.isEnabled,Object.defineProperty(this,"_linesToClear",{get(){return this.#E},set(e){this.#E=e}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#_}}),Object.defineProperty(this,"_lineCount",{get(){let e=this.#D.columns??80,t="function"==typeof this.#v.prefixText?"":this.#v.prefixText,r="function"==typeof this.#v.suffixText?"":this.#v.suffixText,i=" ".repeat(this.#v.indent)+("string"==typeof t&&""!==t?t+" ":"")+"-"+("string"==typeof this.#v.text?" "+this.#v.text:"")+("string"==typeof r&&""!==r?" "+r:"");return this.#U(i,e)}}))}get indent(){return this.#v.indent}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw Error("The `indent` option must be an integer from 0 and up");this.#v.indent=e}get interval(){return this.#v.interval??this.#C.interval??100}get spinner(){return this.#C}set spinner(e){if(this.#_=-1,this.#v.interval=void 0,"object"==typeof e){if(!Array.isArray(e.frames)||0===e.frames.length||e.frames.some(e=>"string"!=typeof e))throw Error("The given spinner must have a non-empty `frames` array of strings");if(void 0!==e.interval&&!(Number.isInteger(e.interval)&&e.interval>0))throw Error("`spinner.interval` must be a positive integer if provided");this.#C=e}else if(uG())if(void 0===e)this.#C=u$.dots;else if("default"!==e&&u$[e])this.#C=u$[e];else throw Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`);else this.#C=u$.line}get text(){return this.#v.text}set text(e=""){this.#v.text=e}get prefixText(){return this.#v.prefixText}set prefixText(e=""){this.#v.prefixText=e}get suffixText(){return this.#v.suffixText}set suffixText(e=""){this.#v.suffixText=e}get isSpinning(){return void 0!==this.#F}#q(e,t,r=!1){let i="function"==typeof e?e():e;return"string"==typeof i&&""!==i?r?t+i:i+t:""}#$(e=this.#v.prefixText,t=" "){return this.#q(e,t,!1)}#M(e=this.#v.suffixText,t=" "){return this.#q(e,t,!0)}#U(e,t){let r=0;for(let i of(0,R.stripVTControlCharacters)(e).split("\n"))r+=Math.max(1,Math.ceil(function(e,t={}){if("string"!=typeof e||0===e.length)return 0;let{ambiguousIsNarrow:r=!0,countAnsiEscapeCodes:i=!1}=t,n=e;if(!i&&(n.includes("\x1b")||n.includes("\x9b"))&&(n=function(e){if("string"!=typeof e)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.includes("\x1b")||e.includes("\x9b")?e.replace(uQ,""):e}(n)),0===n.length)return 0;if(/^[\u0020-\u007E]*$/.test(n))return n.length;let u=0,o={ambiguousAsWide:!r};for(let{segment:e}of u8.segment(n)){var s;if(s=e,u9.test(s))continue;if(u5.test(e)||function(e){if(e.length>50)return!1;if(oe.test(e))return!0;if(e.includes("")){let t=e.match(ot);return null!==t&&t.length>=2}return!1}(e)){u+=2;continue}let t=e.replace(u7,""),r=function(e,t){let r=[];for(let t of e)u9.test(t)||r.push(t.codePointAt(0));if(0===r.length)return;let i=0;for(let e=0;e<r.length;e++){var n;let u=r[e];if(!(or(n=u)||oi(n)||on(n))){if(0===i)return;for(let n=e;n<r.length;n++)i+=u4(r[n],t);break}if(or(u)&&oi(r[e+1])){i+=2,e+=on(r[e+2])?2:1;continue}i+=u4(u,t)}return i}(t,o);if(void 0!==r){u+=r;continue}u+=u4(t.codePointAt(0),o),u+=function(e,t){let r=0,i=!0;for(let n of e){if(i){i=!1;continue}n>=""&&n<=""&&(r+=u4(n.codePointAt(0),t))}return r}(t,o)}return u}(i)/t));return r}get color(){return this.#I}set color(e){if(void 0!==e&&!1!==e&&!os.has(e))throw Error("The `color` option must be a valid color or `false` to disable");this.#I=e}get isEnabled(){return this.#v.isEnabled&&!this.#v.isSilent}set isEnabled(e){if("boolean"!=typeof e)throw TypeError("The `isEnabled` option must be a boolean");this.#v.isEnabled=e}get isSilent(){return this.#v.isSilent}set isSilent(e){if("boolean"!=typeof e)throw TypeError("The `isSilent` option must be a boolean");this.#v.isSilent=e}frame(){let e=Date.now();(-1===this.#_||e-this.#b>=this.interval)&&(this.#_=(this.#_+1)%this.#C.frames.length,this.#b=e);let{frames:t}=this.#C,r=t[this.#_];this.#I&&(r=um[this.#I](r));let i=this.#$(this.#v.prefixText," "),n="string"==typeof this.text?" "+this.text:"";return i+r+n+this.#M(this.#v.suffixText," ")}clear(){return this.isEnabled&&this.#D.isTTY&&(this.#O(()=>{this.#D.cursorTo(0);for(let e=0;e<this.#E;e++)e>0&&this.#D.moveCursor(0,-1),this.#D.clearLine(1);this.#v.indent&&this.#D.cursorTo(this.#v.indent)}),this.#E=0),this}#V(e){if(!e||this.#w.has(e)||!e.isTTY||"function"!=typeof e.write)return;oo.has(e)&&console.warn("[ora] Multiple concurrent spinners detected. This may cause visual corruption. Use one spinner at a time.");let t=e.write;this.#w.set(e,t),oo.set(e,this),e.write=(r,i,n)=>this.#H(e,t,r,i,n)}#z(){if(this.isEnabled&&!(this.#w.size>0))for(let e of new Set([this.#D,k.stdout,k.stderr]))this.#V(e)}#G(){for(let[e,t]of this.#w)e.write=t,oo.get(e)===this&&oo.delete(e);this.#w.clear()}#H(e,t,r,i,n){if("function"==typeof i&&(n=i,i=void 0),this.#B)return t.call(e,r,i,n);this.clear();let u=this.#R(r,i),o=this.#P(u),s=t.call(e,r,i,n);return o?this.#N():u.length>0&&this.#L(),this.isSpinning&&!this.#S&&this.render(),s}render(){if(!this.isEnabled||this.#x||this.#S)return this;let e=this.#D.isTTY,t=!1;try{e&&(this.#O(()=>this.#D.write("\x1b[?2026h")),t=!0),this.clear();let r=this.frame(),i=this.#D.columns??80,n=this.#U(r,i),u=this.#D.rows;if(u&&u>1&&n>u){let e=r.split("\n");r=[...e.slice(0,u-1),"... (content truncated to fit terminal)"].join("\n")}let o=this.#O(()=>this.#D.write(r));!1===o&&this.#D.isTTY&&(this.#x=()=>{this.#x=void 0,this.#k()},this.#D.once("drain",this.#x)),this.#E=this.#U(r,i)}finally{t&&this.#O(()=>this.#D.write("\x1b[?2026l"))}return this}start(e){if(e&&(this.text=e),this.isSilent)return this;if(!this.isEnabled){let e=this.text?"-":"",t=" ".repeat(this.#v.indent)+this.#j(e,this.text,this.#v.prefixText,this.#v.suffixText);return""!==t.trim()&&this.#O(()=>this.#D.write(t+"\n")),this}return this.isSpinning||(this.#v.hideCursor&&uj.hide(this.#D),this.#v.discardStdin&&k.stdin.isTTY&&(ou.start(),this.#T=!0),this.#z(),this.render(),this.#F=setInterval(this.render.bind(this),this.interval)),this}stop(){return clearInterval(this.#F),this.#F=void 0,this.#_=-1,this.#b=0,this.#N(),this.#G(),this.#x&&(this.#D.removeListener("drain",this.#x),this.#x=void 0),this.isEnabled&&(this.clear(),this.#v.hideCursor&&uj.show(this.#D)),this.#T&&(this.#T=!1,ou.stop()),this}succeed(e){return this.stopAndPersist({symbol:uY,text:e})}fail(e){return this.stopAndPersist({symbol:uX,text:e})}warn(e){return this.stopAndPersist({symbol:uK,text:e})}info(e){return this.stopAndPersist({symbol:uJ,text:e})}stopAndPersist(e={}){if(this.isSilent)return this;let t=e.symbol??" ",r=e.text??this.text,i=e.prefixText??this.#v.prefixText,n=e.suffixText??this.#v.suffixText,u=this.#j(t,r,i,n)+"\n";return this.stop(),this.#O(()=>this.#D.write(u)),this}}function ol(e){return new oa(e)}async function oc(e,t,r){return tr({appId:t.appId,caller:t.caller}),(async()=>{let i=ol(`正在执行 ${e} ...`).start();try{let{rawResponse:n,rows:u,csvHeader:o,resultMeta:s}=await r({caller:t.caller}),a=ti()?.response?.logId,{summaryPath:l}=await ib({appName:"dymg",command:e,caller:t.caller,rawResponse:n,rows:u,csvHeader:o,outputDir:t.outputDir,logId:a,resultMeta:s});i.succeed(void 0===u?`${e} 执行完成,已写入原始响应,summary.json: ${l}`:`${e} 执行完成,已写入 ${u.length} 行数据,summary.json: ${l}`)}catch(n){i.fail(`${e} 执行失败`);let t=d(n)||n instanceof Error?n.message:String(n);tr({errorMessage:t,errorCode:n$(n)}),process.stderr.write(`${t}
|
|
36
36
|
`);let r=ti()?.response?.logId;r&&process.stderr.write(`请求日志 ID: ${r}
|
|
37
37
|
`),process.exitCode=d(n)?n.exitCode:1}})()}var od=((et={})[et.All=1]="All",et[et.Douyin=2]="Douyin",et[et.DouyinLite=3]="DouyinLite",et[et.Toutiao=4]="Toutiao",et[et.ToutiaoLite=5]="ToutiaoLite",et[et.Fanqie=6]="Fanqie",et[et.FanqieChangTing=7]="FanqieChangTing",et[et.Hotsoon=8]="Hotsoon",et[et.Ppx=9]="Ppx",et),op=((er={})[er.All=1]="All",er[er.Android=2]="Android",er[er.IOS=3]="IOS",er[er.OpenHarmony=4]="OpenHarmony",er[er.Windows=5]="Windows",er),oh=((ei={})[ei.None=1]="None",ei[ei.SidebarReward=2]="SidebarReward",ei[ei.AppActive=3]="AppActive",ei),of=((en={})[en.All=1]="All",en[en.New=2]="New",en[en.Active=3]="Active",en[en.PayNew=4]="PayNew",en[en.PayActive=5]="PayActive",en),om=((eu={})[eu.All=1]="All",eu[eu.Sidebar=2]="Sidebar",eu),og=((eo={})[eo.Model=1]="Model",eo[eo.Brand=2]="Brand",eo[eo.AppVersion=3]="AppVersion",eo[eo.LibVersion=4]="LibVersion",eo);let oA=90,oy=0,oE=2,o_=180,ob=365,ov=30,oC=7;function oD(e){return{startDate:e.startDate,endDate:e.endDate,host:rC(e.host,od),os:rC(e.os,op),userType:rC(e.userType,of),segment:rC(e.segment,oh)}}let oF=["recordType","date","activeUser","newUser","totalUser","openTime","perUserOpenTime","avgStayTime","avgStayTimeStr","perUserStayTime","perUserStayTimeStr","sharePv","shareUv","shareTime","shareActivateUv"],ow=["hour","activeUser","openTime"],oB=["date","activeUser","permeability","r1","r2","r3","r4","r5","r6","r7","r14","r30"],ox=["sceneId","sceneName","date","uv","newUv","openTime","stayPv","avgStayTime","avgStayTimeStr","totalUv","totalNewUv","totalOpenTime","totalStayPv","totalAvgStayTime","totalAvgStayTimeStr"],oS=["dimension","name","value","ratio","total"],oT=["dimension","name","value","ratio","total"];function oI(e){rd({startDate:e.startDate,endDate:e.endDate,maxLookbackDays:oA,label:"用户分析"})}function oO(e){rn(e.host,"--host",rv(od)),rn(e.os,"--os",rv(op)),rn(e.userType,"--user-type",rv(of)),rn(e.segment,"--segment",rv(oh))}function ok(e){process.stdout.write(`${e.join("\n")}
|
|
38
38
|
`)}function oR(e){process.stdout.write(`${JSON.stringify(e,null,2)}
|
|
39
|
-
`)}async function oP(e,t=!1){if(t)try{await m(e)}catch{process.stderr.write("无法自动打开浏览器,请手动打开授权链接。\n")}}function oL(e,t,r,i){return{success:!0,state:"logged_in",message:i,clientId:r?.clientId,clientName:r?.clientName,uid:t?.uid,oauthAppId:t?.oauthAppId,oauthAppName:t?.oauthAppName,scopes:e.auth.scopes,expiresAt:e.auth.rtExpiresAt}}async function oN(){let[e,t]=await Promise.all([
|
|
39
|
+
`)}async function oP(e,t=!1){if(t)try{await m(e)}catch{process.stderr.write("无法自动打开浏览器,请手动打开授权链接。\n")}}function oL(e,t,r,i){return{success:!0,state:"logged_in",message:i,clientId:r?.clientId,clientName:r?.clientName,uid:t?.uid,oauthAppId:t?.oauthAppId,oauthAppName:t?.oauthAppName,scopes:e.auth.scopes,expiresAt:e.auth.rtExpiresAt}}async function oN(){let[e,t]=await Promise.all([i2(),iK().catch(()=>void 0)]);return{profile:e,client:t}}function oj(e,t,r,i){var n,u,o;process.stdout.write(`${(n=e,u=t,o=r,[i,` clientId: ${o?.clientId??"-"}`,` clientName: ${o?.clientName??"-"}`,` 用户 UID: ${u?.uid??"-"}`,` 应用 ID: ${u?.oauthAppId??"-"}`,` 应用名称: ${u?.oauthAppName??"-"}`,` 授权范围: ${n.auth.scopes.join(",")||"-"}`,` 登录有效期至: ${rb(n.auth.rtExpiresAt)}`]).join("\n")}
|
|
40
40
|
`)}async function o$(e=!1){let t;try{t=await ne()}catch(e){if(!p(e,"AUTH_LOGIN_REQUIRED"))throw e}if(t&&!rV(t.auth.rtExpiresAt))try{await nn();let[r,{profile:i,client:n}]=await Promise.all([ne(),oN()]),u=r??t;return e?oR(oL(u,i,n,"当前已登录,无需重新登录")):oj(u,i,n,"当前已登录,无需重新登录"),{current:r??t,isLoggedIn:!0}}catch(e){if(!p(e,"AUTH_LOGIN_REQUIRED"))throw e;t=void 0}return{current:t,isLoggedIn:!1}}async function oM(e){var t;let r;if(e.resume&&!1===e.wait)throw new l("参数冲突",{error:"INVALID_AUTH_SESSION",message:"参数冲突:--no-wait 与 --resume 不能同时使用"});if(e.json&&(!1!==e.wait||e.resume))throw new l("参数冲突",{error:"INVALID_AUTH_SESSION",message:"参数冲突:--json 仅可与 --no-wait 一起使用"});if(e.resume)return void await oU(e);let i=await o$(e.json);if(i.isLoggedIn)return;let n=await iZ(),u=await it({deviceAuthorizationEndpoint:n.deviceAuthorizationEndpoint,tokenEndpoint:n.tokenEndpoint,clientId:n.clientId,scope:n.scope,httpClient:nl}),o=(t={clientId:n.clientId,tokenEndpoint:n.tokenEndpoint,authorization:u.authorization,codeVerifier:u.codeVerifier},r=Math.floor(Date.now()/1e3),{clientId:t.clientId,tokenEndpoint:t.tokenEndpoint,deviceCode:t.authorization.device_code,userCode:t.authorization.user_code,verificationUri:t.authorization.verification_uri,verificationUriComplete:t.authorization.verification_uri_complete,codeVerifier:t.codeVerifier,intervalSeconds:t.authorization.interval,createdAt:r,expiresAt:r+t.authorization.expires_in});if(await nE(o),!1===e.wait){e.json?oR({success:!0,state:"authorization_pending",message:`完成授权后,请执行 ${e5} 继续完成登录。`,verificationUri:o.verificationUriComplete??o.verificationUri,userCode:o.userCode,expiresAt:o.expiresAt}):ok(r9(u.authorization,{waitingMessage:`完成授权后,请执行 ${e5} 继续完成登录。`})),await oP(o.verificationUriComplete??o.verificationUri,e.openBrowser);return}ok(r9(u.authorization,{waitingMessage:"授权完成前请保持当前命令运行,CLI 会自动继续。"})),await oP(o.verificationUriComplete??o.verificationUri,e.openBrowser),await oq({clientId:n.clientId,tokenEndpoint:n.tokenEndpoint,deviceCode:u.authorization.device_code,codeVerifier:u.codeVerifier,expiresInSeconds:u.authorization.expires_in,intervalSeconds:u.authorization.interval,current:i.current,clearSessionOnSuccess:!0})}async function oU(e){let t=await n_();if(!t){let e=await ne();if(e&&!rV(e.auth.rtExpiresAt)){await nn();let[t,{profile:r,client:i}]=await Promise.all([ne(),oN()]);oj(t??e,r,i,"当前已登录,无需继续授权");return}throw new l("未找到待完成授权",{error:"AUTH_LOGIN_REQUIRED",message:`未找到待完成授权,请先执行 ${e9}`})}let r=Math.ceil(t.expiresAt-Date.now()/1e3);if(r<=0)throw await nb(),new l("授权已过期,请重新登录",{error:"AUTH_LOGIN_REQUIRED",message:`授权已过期,请重新执行 ${e9}`});let i=await ne().catch(e=>{if(!p(e,"AUTH_LOGIN_REQUIRED"))throw e});e.openBrowser&&(ok(r9({verification_uri:t.verificationUri,verification_uri_complete:t.verificationUriComplete,user_code:t.userCode,device_code:t.deviceCode,expires_in:r})),await oP(t.verificationUriComplete??t.verificationUri,e.openBrowser)),await oq({clientId:t.clientId,tokenEndpoint:t.tokenEndpoint,deviceCode:t.deviceCode,codeVerifier:t.codeVerifier,expiresInSeconds:r,intervalSeconds:t.intervalSeconds,current:i,clearSessionOnSuccess:!0})}async function oq(e){let t,r=new AbortController,i=!1,n=()=>{i&&process.exit(130),i=!0,r.abort(),t?.stop(),process.exitCode=130};process.once("SIGINT",n),process.once("SIGTERM",n);let u=function(e,t={}){let r=t.stdin??process.stdin;if(!0!==r.isTTY||"function"!=typeof r.setRawMode)return;let i=!0!==r.isRaw,n=r.isPaused(),u=t=>{var r;("string"==typeof(r=t)?r.includes("\x03"):r.includes(3))&&e()};return i&&r.setRawMode(!0),r.resume(),r.on("data",u),()=>{r.off("data",u),i&&r.setRawMode(!1),n&&r.pause()}}(n);try{t=ol("正在完成登录授权 ...").start();let i=await ie({tokenEndpoint:e.tokenEndpoint,clientId:e.clientId,deviceCode:e.deviceCode,codeVerifier:e.codeVerifier,expiresInSeconds:e.expiresInSeconds,intervalSeconds:e.intervalSeconds,httpClient:nl,signal:r.signal});await nu(i,e.current),e.clearSessionOnSuccess&&await nb(),t.succeed("登录完成")}catch(e){if(e instanceof rO&&e.error===rw.RequestAborted){t?.stop(),process.exitCode=130;return}t?.fail("登录未完成"),e instanceof rO&&e.error===rw.ExpiredToken&&await nb();var o=e,s={retryCommand:e9};if(!(o instanceof rO))throw o;if(o.error===rw.AccessDenied)throw new l(`授权已取消,请重新执行 ${s.retryCommand}`,{cause:o,error:"AUTH_ACCESS_DENIED",message:`授权已取消,请重新执行 ${s.retryCommand}`});if(o.error===rw.ExpiredToken)throw new l(`授权等待已超时,请重新执行 ${s.retryCommand}`,{cause:o,error:"AUTH_LOGIN_TIMEOUT",message:`授权等待已超时,请重新执行 ${s.retryCommand}`});if(o.error===rw.RequestAborted)throw new l(`授权流程已中断,请重新执行 ${s.retryCommand}`,{cause:o,error:"AUTH_LOGIN_ABORTED",message:`授权流程已中断,请重新执行 ${s.retryCommand}`});if(o.error===rw.RequestTimeout||o.error===rw.NetworkError)throw new l("授权请求失败,请检查网络后重试",{cause:o,error:"AUTH_LOGIN_NETWORK_ERROR",message:"授权请求失败,请检查网络后重试"});throw o}finally{u?.(),process.removeListener("SIGINT",n),process.removeListener("SIGTERM",n)}}async function oV(e){let t=await ne();if(!t){let t=`当前未登录,请先执行 ${e9}`;e.json?oR({success:!0,state:"logged_out",message:t}):process.stdout.write(`当前未登录。
|
|
41
41
|
请先执行 ${e9}
|
|
42
42
|
`);return}if(rV(t.auth.rtExpiresAt)){let r=`当前登录已过期,请先执行 ${e9}`;e.json?oR({success:!0,state:"expired",message:r,expiresAt:t.auth.rtExpiresAt}):process.stdout.write(`当前登录已过期。
|
|
43
43
|
请先执行 ${e9}
|
|
44
44
|
`);return}await nn();let[r,{profile:i,client:n}]=await Promise.all([ne(),oN()]),u=r??t;e.json?oR(oL(u,i,n,"当前已登录")):oj(u,i,n,"当前已登录")}async function oH(){let e=ol("正在退出当前登录 ...").start();try{let t,r=await ne().catch(()=>void 0);try{await ni(r)}catch(e){t=e}if(await Promise.all([no(),nb()]),t)return void e.warn("已清理本地登录态,服务端撤销失败");e.succeed("已退出登录")}catch(t){if(e.fail("退出登录失败"),iH(t))throw t;throw new l("退出登录失败",{cause:t,error:"AUTH_LOGOUT_FAILED",message:"退出登录失败,请检查网络或本机登录目录权限后重试"})}}async function oz(){let e=function(){let{dataDir:e}=im({appName:"dymg"});return(0,I.join)(e,ij())}(),t={writable:!1};try{await (0,th.mkdir)(e,{recursive:!0});let r=await (0,th.mkdtemp)((0,I.join)(e,".auth-write-test-"));t.writable=!0,t.message="登录态目录可写",await (0,th.rm)(r,{recursive:!0,force:!0})}catch(e){t.errorCode=e.code,["EACCES","EPERM","EROFS"].includes(e.code??"")?t.message="登录态目录不可写或无权限访问":t.message="登录态目录初始化或写入测试失败"}process.stdout.write(`${JSON.stringify(t,null,2)}
|
|
45
|
-
`)}let oG=require("node:readline");var oW=__webpack_require__("../../node_modules/.pnpm/mute-stream@3.0.0/node_modules/mute-stream/lib/index.js"),oJ=__webpack_require__("../../node_modules/.pnpm/cli-width@4.1.0/node_modules/cli-width/index.js");let oY=(o=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,e=>{let t=0;for(o.lastIndex=0;o.test(e);)t+=1;return e.length-t}),oK=e=>12288===e||e>=65281&&e<=65376||e>=65504&&e<=65510,oX=e=>8987===e||9001===e||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,oQ=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,oZ=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,o1=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,
|
|
46
|
-
at ${e}`)}let[o,s]="string"==typeof u?[u]:u;c.render(o,s),sm.run()}catch(e){h(e)}if(i=!0,null!==n){let{value:e}=n;n=null,p(e)}})},"readableFlowing"in n?sw(g):g(),Object.assign(d.then(e=>(sm.clearAll(),e),e=>{throw sm.clearAll(),e}).finally(()=>{o.forEach(e=>e()),c.done({clearContent:!!i.clearPromptOnDone}),a.end()}).then(()=>d),{cancel:f})})}}let sx={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"█",squareDarkShade:"▓",squareMediumShade:"▒",squareLightShade:"░",squareTop:"▀",squareBottom:"▄",squareLeft:"▌",squareRight:"▐",squareCenter:"■",bullet:"●",dot:"․",ellipsis:"…",pointerSmall:"›",triangleUp:"▲",triangleUpSmall:"▴",triangleDown:"▼",triangleDownSmall:"▾",triangleLeftSmall:"◂",triangleRightSmall:"▸",home:"⌂",heart:"♥",musicNote:"♪",musicNoteBeamed:"♫",arrowUp:"↑",arrowDown:"↓",arrowLeft:"←",arrowRight:"→",arrowLeftRight:"↔",arrowUpDown:"↕",almostEqual:"≈",notEqual:"≠",lessOrEqual:"≤",greaterOrEqual:"≥",identical:"≡",infinity:"∞",subscriptZero:"₀",subscriptOne:"₁",subscriptTwo:"₂",subscriptThree:"₃",subscriptFour:"₄",subscriptFive:"₅",subscriptSix:"₆",subscriptSeven:"₇",subscriptEight:"₈",subscriptNine:"₉",oneHalf:"\xbd",oneThird:"⅓",oneQuarter:"\xbc",oneFifth:"⅕",oneSixth:"⅙",oneEighth:"⅛",twoThirds:"⅔",twoFifths:"⅖",threeQuarters:"\xbe",threeFifths:"⅗",threeEighths:"⅜",fourFifths:"⅘",fiveSixths:"⅚",fiveEighths:"⅝",sevenEighths:"⅞",line:"─",lineBold:"━",lineDouble:"═",lineDashed0:"┄",lineDashed1:"┅",lineDashed2:"┈",lineDashed3:"┉",lineDashed4:"╌",lineDashed5:"╍",lineDashed6:"╴",lineDashed7:"╶",lineDashed8:"╸",lineDashed9:"╺",lineDashed10:"╼",lineDashed11:"╾",lineDashed12:"−",lineDashed13:"–",lineDashed14:"‐",lineDashed15:"⁃",lineVertical:"│",lineVerticalBold:"┃",lineVerticalDouble:"║",lineVerticalDashed0:"┆",lineVerticalDashed1:"┇",lineVerticalDashed2:"┊",lineVerticalDashed3:"┋",lineVerticalDashed4:"╎",lineVerticalDashed5:"╏",lineVerticalDashed6:"╵",lineVerticalDashed7:"╷",lineVerticalDashed8:"╹",lineVerticalDashed9:"╻",lineVerticalDashed10:"╽",lineVerticalDashed11:"╿",lineDownLeft:"┐",lineDownLeftArc:"╮",lineDownBoldLeftBold:"┓",lineDownBoldLeft:"┒",lineDownLeftBold:"┑",lineDownDoubleLeftDouble:"╗",lineDownDoubleLeft:"╖",lineDownLeftDouble:"╕",lineDownRight:"┌",lineDownRightArc:"╭",lineDownBoldRightBold:"┏",lineDownBoldRight:"┎",lineDownRightBold:"┍",lineDownDoubleRightDouble:"╔",lineDownDoubleRight:"╓",lineDownRightDouble:"╒",lineUpLeft:"┘",lineUpLeftArc:"╯",lineUpBoldLeftBold:"┛",lineUpBoldLeft:"┚",lineUpLeftBold:"┙",lineUpDoubleLeftDouble:"╝",lineUpDoubleLeft:"╜",lineUpLeftDouble:"╛",lineUpRight:"└",lineUpRightArc:"╰",lineUpBoldRightBold:"┗",lineUpBoldRight:"┖",lineUpRightBold:"┕",lineUpDoubleRightDouble:"╚",lineUpDoubleRight:"╙",lineUpRightDouble:"╘",lineUpDownLeft:"┤",lineUpBoldDownBoldLeftBold:"┫",lineUpBoldDownBoldLeft:"┨",lineUpDownLeftBold:"┥",lineUpBoldDownLeftBold:"┩",lineUpDownBoldLeftBold:"┪",lineUpDownBoldLeft:"┧",lineUpBoldDownLeft:"┦",lineUpDoubleDownDoubleLeftDouble:"╣",lineUpDoubleDownDoubleLeft:"╢",lineUpDownLeftDouble:"╡",lineUpDownRight:"├",lineUpBoldDownBoldRightBold:"┣",lineUpBoldDownBoldRight:"┠",lineUpDownRightBold:"┝",lineUpBoldDownRightBold:"┡",lineUpDownBoldRightBold:"┢",lineUpDownBoldRight:"┟",lineUpBoldDownRight:"┞",lineUpDoubleDownDoubleRightDouble:"╠",lineUpDoubleDownDoubleRight:"╟",lineUpDownRightDouble:"╞",lineDownLeftRight:"┬",lineDownBoldLeftBoldRightBold:"┳",lineDownLeftBoldRightBold:"┯",lineDownBoldLeftRight:"┰",lineDownBoldLeftBoldRight:"┱",lineDownBoldLeftRightBold:"┲",lineDownLeftRightBold:"┮",lineDownLeftBoldRight:"┭",lineDownDoubleLeftDoubleRightDouble:"╦",lineDownDoubleLeftRight:"╥",lineDownLeftDoubleRightDouble:"╤",lineUpLeftRight:"┴",lineUpBoldLeftBoldRightBold:"┻",lineUpLeftBoldRightBold:"┷",lineUpBoldLeftRight:"┸",lineUpBoldLeftBoldRight:"┹",lineUpBoldLeftRightBold:"┺",lineUpLeftRightBold:"┶",lineUpLeftBoldRight:"┵",lineUpDoubleLeftDoubleRightDouble:"╩",lineUpDoubleLeftRight:"╨",lineUpLeftDoubleRightDouble:"╧",lineUpDownLeftRight:"┼",lineUpBoldDownBoldLeftBoldRightBold:"╋",lineUpDownBoldLeftBoldRightBold:"╈",lineUpBoldDownLeftBoldRightBold:"╇",lineUpBoldDownBoldLeftRightBold:"╊",lineUpBoldDownBoldLeftBoldRight:"╉",lineUpBoldDownLeftRight:"╀",lineUpDownBoldLeftRight:"╁",lineUpDownLeftBoldRight:"┽",lineUpDownLeftRightBold:"┾",lineUpBoldDownBoldLeftRight:"╂",lineUpDownLeftBoldRightBold:"┿",lineUpBoldDownLeftBoldRight:"╃",lineUpBoldDownLeftRightBold:"╄",lineUpDownBoldLeftBoldRight:"╅",lineUpDownBoldLeftRightBold:"╆",lineUpDoubleDownDoubleLeftDoubleRightDouble:"╬",lineUpDoubleDownDoubleLeftRight:"╫",lineUpDownLeftDoubleRightDouble:"╪",lineCross:"╳",lineBackslash:"╲",lineSlash:"╱"},sS={tick:"✔",info:"ℹ",warning:"⚠",cross:"✘",squareSmall:"◻",squareSmallFilled:"◼",circle:"◯",circleFilled:"◉",circleDotted:"◌",circleDouble:"◎",circleCircle:"ⓞ",circleCross:"ⓧ",circlePipe:"Ⓘ",radioOn:"◉",radioOff:"◯",checkboxOn:"☒",checkboxOff:"☐",checkboxCircleOn:"ⓧ",checkboxCircleOff:"Ⓘ",pointer:"❯",triangleUpOutline:"△",triangleLeft:"◀",triangleRight:"▶",lozenge:"◆",lozengeOutline:"◇",hamburger:"☰",smiley:"㋡",mustache:"෴",star:"★",play:"▶",nodejs:"⬢",oneSeventh:"⅐",oneNinth:"⅑",oneTenth:"⅒"},sT={...sx,...sS},sI={...sx,tick:"√",info:"i",warning:"‼",cross:"\xd7",squareSmall:"□",squareSmallFilled:"■",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(○)",circleCross:"(\xd7)",circlePipe:"(│)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xd7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xd7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"∆",triangleLeft:"◄",triangleRight:"►",lozenge:"♦",lozengeOutline:"◊",hamburger:"≡",smiley:"☺",mustache:"┌─┐",star:"✶",play:"►",nodejs:"♦",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},sO=k.platform.startsWith("win")?!!k.env.CI||!!k.env.WT_SESSION||!!k.env.TERMINUS_SUBLIME||"{cmd::Cmder}"===k.env.ConEmuTask||"Terminus-Sublime"===k.env.TERM_PROGRAM||"vscode"===k.env.TERM_PROGRAM||"xterm-256color"===k.env.TERM||"alacritty"===k.env.TERM||"JetBrains-JediTerm"===k.env.TERMINAL_EMULATOR:"linux"!==k.env.TERM,sk=sO?sT:sI;Object.entries(sS);let sR=new Set(["emacs","vim"]);function sP(e){return sR.has(e)}let sL=(e,t=[])=>"up"===e.name||t.includes("vim")&&"k"===e.name||t.includes("emacs")&&e.ctrl&&"p"===e.name,sN=(e,t=[])=>"down"===e.name||t.includes("vim")&&"j"===e.name||t.includes("emacs")&&e.ctrl&&"n"===e.name,sj=e=>"enter"===e.name||"return"===e.name,s$={prefix:{idle:(0,R.styleText)("blue","?"),done:(0,R.styleText)("green",sk.tick)},spinner:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"].map(e=>(0,R.styleText)("yellow",e))},keybindings:[],style:{answer:e=>(0,R.styleText)("cyan",e),message:e=>(0,R.styleText)("bold",e),error:e=>(0,R.styleText)("red",`> ${e}`),defaultAnswer:e=>(0,R.styleText)("dim",`(${e})`),help:e=>(0,R.styleText)("dim",e),highlight:e=>(0,R.styleText)("cyan",e),key:e=>(0,R.styleText)("cyan",(0,R.styleText)("bold",`<${e}>`))}};function sM(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function sU(...e){let t;return function e(...t){let r={};for(let i of t)for(let[t,n]of Object.entries(i)){let i=r[t];r[t]=sM(i)&&sM(n)?e(i,n):n}return r}({...s$,keybindings:(t=process.env.INQUIRER_KEYBINDINGS)?Array.from(new Set(t.toLowerCase().split(/[\s,]+/).filter(sP))):[]},...e.filter(e=>null!=e))}function sq(e){return sf(t=>{let r=s.AsyncResource.bind(function(e){t.get()!==e&&(t.set(e),sp().handleChange())});if(t.initialized)return[t.get(),r];let i="function"==typeof e?e():e;return t.set(i),[i,r]})}function sV(e,t){sf(r=>{let i=r.get();(!Array.isArray(i)||t.some((e,t)=>!Object.is(e,i[t])))&&sm.queue(e),r.set(t)})}function sH({status:e="idle",theme:t}){let[r,i]=sq(!1),[n,u]=sq(0),{prefix:o,spinner:s}=sU(t);if(sV(()=>{if("loading"===e){let e,t=-1,r=setTimeout(()=>{i(!0),e=setInterval(()=>{u((t+=1)%s.frames.length)},s.interval)},300);return()=>{clearTimeout(r),clearInterval(e)}}i(!1)},[e]),r)return s.frames[n];let a="loading"===e?"idle":e;return"string"==typeof o?o:o[a]??o.idle}function sz(e){return sq({current:e})[0]}function sG(e){let t=sz(e);t.current=e,sV(e=>{let r=!1,i=sh((i,n)=>{r||t.current(n,e)});return e.input.on("keypress",i),()=>{r=!0,e.input.removeListener("keypress",i)}},[])}let sW={validationFailureMode:"keep"},sJ=sB((e,t)=>{let r,{prefill:i="tab"}=e,n=sU(sW,e.theme),[u,o]=sq("idle"),[s,a]=sq(String(e.default??"")),[l,c]=sq(),[d,p]=sq(""),h=sH({status:u,theme:n});async function f(t){let{required:r,pattern:i,patternError:n="Invalid input"}=e;return r&&!t?"You must provide a value":i&&!i.test(t)?n:"function"!=typeof e.validate||await e.validate(t)||"You must provide a valid value"}sG(async(e,r)=>{if("idle"===u)if(sj(e)){let e=d||s;o("loading");let i=await f(e);!0===i?(p(e),o("done"),t(e)):("clear"===n.validationFailureMode?p(""):r.write(d),c(i),o("idle"))}else"backspace"!==e.name||d?"tab"!==e.name||d?(p(r.line),c(void 0)):(a(""),r.clearLine(0),r.write(s),p(s)):a("")}),sV(e=>{"editable"===i&&s&&(e.write(s),p(s))},[]);let m=n.style.message(e.message,u),g=d;"function"==typeof e.transformer?g=e.transformer(d,{isFinal:"done"===u}):"done"===u&&(g=n.style.answer(d)),s&&"done"!==u&&!d&&(r=n.style.defaultAnswer(s));let A="";return l&&(A=n.style.error(l)),[[h,m,r,g].filter(e=>void 0!==e).join(" "),A]});class sY{separator=(0,R.styleText)("dim",Array.from({length:15}).join(sk.line));type="separator";constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&"object"==typeof e&&"type"in e&&"separator"===e.type)}}function sK(e,t){return sf(r=>{let i=r.get();if(!i||i.dependencies.length!==t.length||i.dependencies.some((e,r)=>e!==t[r])){let i=e();return r.set({value:i,dependencies:t}),i}return i.value})}function sX({items:e,active:t,renderItem:r,pageSize:i,loop:n=!0}){let u=sA(),o=t=>(t%e.length+e.length)%e.length,s=e.map((e,i)=>null==e?[]:sg(r({item:e,index:i,isActive:i===t}),u).split("\n")),a=s.reduce((e,t)=>e+t.length,0),l=e=>s[e]??[],c=function({active:e,renderedItems:t,pageSize:r,loop:i}){let n=sz({lastPointer:e,lastActive:void 0}),{lastPointer:u,lastActive:o}=n.current,s=Math.floor(r/2),a=t.reduce((e,t)=>e+t.length,0),l=t.slice(0,e).reduce((e,t)=>e+t.length,0),c=l;if(a>r)if(i)c=u,null!=o&&o<e&&e-o<r&&(c=Math.min(s,1===Math.abs(e-o)?Math.min(u+(t[o]?.length??0),Math.max(l,u)):u+e-o));else{let i=t.slice(e).reduce((e,t)=>e+t.length,0);c=i<r-s?r-i:Math.min(l,s)}return n.current.lastPointer=c,n.current.lastActive=e,c}({active:t,renderedItems:s,pageSize:i,loop:n}),d=l(t).slice(0,i),p=c+d.length<=i?c:i-d.length,h=Array.from({length:i});h.splice(p,d.length,...d);let f=new Set([t]),m=p+d.length,g=o(t+1);for(;m<i&&!f.has(g)&&(n&&a>i?g!==t:g>t);){let e=l(g).slice(0,i-m);h.splice(m,e.length,...e),f.add(g),m+=e.length,g=o(g+1)}for(m=p-1,g=o(t-1);m>=0&&!f.has(g)&&(n&&a>i?g!==t:g<t);){let e=l(g),t=e.slice(Math.max(0,e.length-m-1));h.splice(m-t.length+1,t.length,...t),f.add(g),m-=t.length,g=o(g-1)}return h.filter(e=>"string"==typeof e).join("\n")}let sQ={icon:{cursor:sk.pointer},style:{disabled:e=>(0,R.styleText)("dim",e),description:e=>(0,R.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,R.styleText)("bold",e)} ${(0,R.styleText)("dim",t)}`).join((0,R.styleText)("dim"," • "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function sZ(e){return!sY.isSeparator(e)&&!e.disabled}function s1(e){return!sY.isSeparator(e)}let s2=sB((e,t)=>{let{loop:r=!0,pageSize:i=7}=e,n=sU(sQ,e.theme),{keybindings:u}=n,[o,s]=sq("idle"),a=sH({status:o,theme:n}),l=sz(),c=!u.includes("vim"),d=sK(()=>e.choices.map(e=>{if(sY.isSeparator(e))return e;if("object"!=typeof e||null===e||!("value"in e)){let t=String(e);return{value:e,name:t,short:t,disabled:!1}}let t=e.name??String(e.value),r={value:e.value,name:t,short:e.short??t,disabled:e.disabled??!1};return e.description&&(r.description=e.description),r}),[e.choices]),p=sK(()=>{let e=d.findIndex(s1),t=d.findLastIndex(s1);if(-1===e)throw new sc("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[d]),h=sK(()=>"default"in e?d.findIndex(t=>sZ(t)&&t.value===e.default):-1,[e.default,d]),[f,m]=sq(-1===h?p.first:h),g=d[f];if(null==g||sY.isSeparator(g))throw Error("Active index does not point to a choice");let[A,y]=sq();sG((e,i)=>{if(clearTimeout(l.current),A&&y(void 0),sj(e))g.disabled?y(n.i18n.disabledError):(s("done"),t(g.value));else if(sL(e,u)||sN(e,u)){if(i.clearLine(0),r||sL(e,u)&&f!==p.first||sN(e,u)&&f!==p.last){let t=sL(e,u)?-1:1,r=f;do r=(r+t+d.length)%d.length;while(!s1(d[r]));m(r)}}else{let t;if(t=e,"1234567890".includes(t.name)&&!Number.isNaN(Number(i.line))){let e=Number(i.line)-1,t=-1,r=d.findIndex(r=>!sY.isSeparator(r)&&++t===e),n=d[r];null!=n&&sZ(n)&&m(r),l.current=setTimeout(()=>{i.clearLine(0)},700)}else if("backspace"===e.name)i.clearLine(0);else if(c){let e=i.line.toLowerCase(),t=d.findIndex(t=>!sY.isSeparator(t)&&!!sZ(t)&&t.name.toLowerCase().startsWith(e));-1!==t&&m(t),l.current=setTimeout(()=>{i.clearLine(0)},700)}}}),sV(()=>()=>{clearTimeout(l.current)},[]);let E=n.style.message(e.message,o),_=n.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),b=0,v=sX({items:d,active:f,renderItem({item:e,isActive:t,index:r}){if(sY.isSeparator(e))return b++,` ${e.separator}`;let i=t?n.icon.cursor:" ",u="number"===n.indexMode?`${r+1-b}. `:"";if(e.disabled){let r="string"==typeof e.disabled?e.disabled:"(disabled)",i=t?n.icon.cursor:"-";return n.style.disabled(`${i} ${u}${e.name} ${r}`)}return(t?n.style.highlight:e=>e)(`${i} ${u}${e.name}`)},pageSize:i,loop:r});if("done"===o)return[a,E,n.style.answer(g.short)].filter(Boolean).join(" ");let{description:C}=g,D=[[a,E].filter(Boolean).join(" "),v," ",C?n.style.description(C):"",A?n.style.error(A):"",_].filter(Boolean).join("\n").trimEnd();return`${D}\u001b[?25l`});function s0(e,{min:t,max:r,step:i}){var n,u,o;return!(null==e||Number.isNaN(e))&&(e<t||e>r?`Value must be between ${t} and ${r}`:"any"===i||(n=e,u=i,(1e6*n-(Number.isFinite(o=t)?1e6*o:0))%(1e6*u)==0)||`Value must be a multiple of ${i}${Number.isFinite(t)?` starting from ${t}`:""}`)}let s3=sB((e,t)=>{let r,{validate:i=()=>!0,min:n=-1/0,max:u=1/0,step:o=1,required:s=!1}=e,a=sU(e.theme),[l,c]=sq("idle"),[d,p]=sq(""),[h="",f]=sq(!0===s0(e.default,{min:n,max:u,step:o})?e.default?.toString():void 0),[m,g]=sq(),A=sH({status:l,theme:a});sG(async(e,r)=>{if("idle"===l)if(sj(e)){let e=d||h,a=""===e?void 0:Number(e);c("loading");let l=!0;(s||null!=a)&&(l=s0(a,{min:n,max:u,step:o})),!0===l&&null!=a&&(l=await i(a)),!0===l?(p(String(a??"")),c("done"),t(a)):(r.write(d),g(l||"You must provide a valid numeric value"),c("idle"))}else"backspace"!==e.name||d?"tab"!==e.name||d?(p(r.line),g(void 0)):(f(void 0),r.clearLine(0),r.write(h),p(h)):f(void 0)});let y=a.style.message(e.message,l),E=d;"done"===l&&(E=a.style.answer(d)),h&&"done"!==l&&!d&&(r=a.style.defaultAnswer(h));let _="";return m&&(_=a.style.error(m)),[[A,y,r,E].filter(e=>void 0!==e).join(" "),_]});function s6(e,t){let r=!1!==t;return/^(y|yes)/i.test(e)?r=!0:/^(n|no)/i.test(e)&&(r=!1),r}function s4(e){return e?"Yes":"No"}let s8=sB((e,t)=>{let{transformer:r=s4}=e,[i,n]=sq("idle"),[u,o]=sq(""),s=sU(e.theme),a=sH({status:i,theme:s});sG((s,a)=>{if("idle"===i)if(sj(s)){let i=s6(u,e.default);o(r(i)),n("done"),t(i)}else if("tab"===s.name){let t=s4(!s6(u,e.default));a.clearLine(0),a.write(t),o(t)}else o(a.line)});let l=u,c="";"done"===i?l=s.style.answer(u):c=` ${s.style.defaultAnswer(!1===e.default?"y/N":"Y/n")}`;let d=s.style.message(e.message,i);return`${a} ${d}${c} ${l}`}),s9=/\d+/,s7={style:{description:e=>(0,R.styleText)("cyan",e)}};function s5(e){return null!=e&&!sY.isSeparator(e)}function ae(e,t){let r,i=t.filter(s5);return!(r=i.find(t=>t.key===e))&&s9.test(e)&&(r=i[Number.parseInt(e,10)-1]),r?[r,t.indexOf(r)]:[void 0,void 0]}let at=sB((e,t)=>{let{loop:r=!0}=e,i=sK(()=>{var t;let r;return t=e.choices,r=0,t.map(e=>{if(sY.isSeparator(e))return e;if(r+=1,"object"!=typeof e||null===e||!("value"in e)){let t=String(e);return{value:e,name:t,short:t,key:String(r)}}let t=e.name??String(e.value);return{value:e.value,name:t,short:e.short??t,key:e.key??String(r),description:e.description}})},[e.choices]),[n,u]=sq("idle"),[o,s]=sq(()=>{let t=null==e.default?void 0:i.find(t=>s5(t)&&t.value===e.default);return t?.key??""}),[a,l]=sq(),c=sU(s7,e.theme),{keybindings:d}=c,p=sH({status:n,theme:c}),h=sK(()=>{let e=i.findIndex(s5),t=i.findLastIndex(s5);if(-1===e)throw new sc("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[i]);sG((e,n)=>{if(sj(e)){let[e]=ae(o,i);s5(e)?(s(e.short),u("done"),t(e.value)):""===o?l("Please input a value"):l(`"${(0,R.styleText)("red",o)}" isn't an available option`)}else if(sL(e,d)||sN(e,d)){n.clearLine(0);let[t,u]=ae(o,i);if(t){if(r||sL(e,d)&&u!==h.first||sN(e,d)&&u!==h.last){let t,r=sL(e,d)?-1:1,n=u;do n=(n+r+i.length)%i.length,t=i[n];while(!s5(t));s(t.key)}}else s((sN(e,d)?i.find(s5):i.findLast(s5)).key)}else s(n.line),l(void 0)});let f=c.style.message(e.message,n);if("done"===n)return`${p} ${f} ${c.style.answer(o)}`;let m=i.map(e=>{if(sY.isSeparator(e))return` ${e.separator}`;let t=` ${e.key}) ${e.name}`;return e.key===o?c.style.highlight(t):t}).join("\n"),g="";a&&(g=c.style.error(a));let[A]=ae(o,i),y="";return!a&&A?.description&&(y=c.style.description(A.description)),[`${p} ${f} ${o}`,[m,g,y].filter(Boolean).join("\n")]}),ar={key:"h",name:"Help, list all options",value:void 0},ai=sB((e,t)=>{let{default:r="h"}=e,i=sK(()=>e.choices.map(e=>{if(sY.isSeparator(e))return e;let t="name"in e?e.name:String(e.value);return{value:"value"in e?e.value:t,name:t,key:e.key}}),[e.choices]),[n,u]=sq("idle"),[o,s]=sq(""),[a,l]=sq(e.expanded??!1),[c,d]=sq(),p=sU(e.theme),h=sH({theme:p,status:n});sG((e,n)=>{if(sj(e)){let e=(o||r).toLowerCase();if("h"!==e||a){let r=i.find(t=>!sY.isSeparator(t)&&t.key===e);r?(u("done"),s(e),t(r.value)):""===o?d("Please input a value"):d(`"${(0,R.styleText)("red",o)}" isn't an available option`)}else l(!0)}else s(n.line),d(void 0)});let f=p.style.message(e.message,n);if("done"===n){let e=i.find(e=>!sY.isSeparator(e)&&e.key===o.toLowerCase());return`${h} ${f} ${p.style.answer(e.name)}`}let m=a?i:[...i,ar],g="",A=m.map(e=>sY.isSeparator(e)?"":e.key===r?e.key.toUpperCase():e.key).join("");A=` ${p.style.defaultAnswer(A)}`,a&&(A="",g=m.map(e=>{if(sY.isSeparator(e))return` ${e.separator}`;let t=` ${e.key}) ${e.name}`;return e.key===o.toLowerCase()?p.style.highlight(t):t}).join("\n"));let y="",E=i.find(e=>!sY.isSeparator(e)&&e.key===o.toLowerCase());E&&(y=`${(0,R.styleText)("cyan",">>")} ${E.name}`);let _="";return c&&(_=p.style.error(c)),[`${h} ${f}${A} ${o}`,[g,y,_].filter(Boolean).join("\n")]}),an={icon:{checked:(0,R.styleText)("green",sk.circleFilled),unchecked:sk.circle,cursor:sk.pointer,disabledChecked:(0,R.styleText)("green",sk.circleDouble),disabledUnchecked:"-"},style:{disabled:e=>(0,R.styleText)("dim",e),renderSelectedChoices:e=>e.map(e=>e.short).join(", "),description:e=>(0,R.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,R.styleText)("bold",e)} ${(0,R.styleText)("dim",t)}`).join((0,R.styleText)("dim"," • "))},i18n:{disabledError:"This option is disabled and cannot be toggled."}};function au(e){return!sY.isSeparator(e)&&!e.disabled}function ao(e){return!sY.isSeparator(e)}function as(e){return!sY.isSeparator(e)&&e.checked}function aa(e){return au(e)?{...e,checked:!e.checked}:e}let al=sB((e,t)=>{let r,{pageSize:i=7,loop:n=!0,required:u,validate:o=()=>!0}=e,s={all:"a",invert:"i",...e.shortcuts},a=sU(an,e.theme),{keybindings:l}=a,[c,d]=sq("idle"),p=sH({status:c,theme:a}),[h,f]=sq(e.choices.map(e=>{if(sY.isSeparator(e))return e;if("object"!=typeof e||null===e||!("value"in e)){let t=String(e);return{value:e,name:t,short:t,checkedName:t,disabled:!1,checked:!1}}let t=e.name??String(e.value),r={value:e.value,name:t,short:e.short??t,checkedName:e.checkedName??t,disabled:e.disabled??!1,checked:e.checked??!1};return e.description&&(r.description=e.description),r})),m=sK(()=>{let e=h.findIndex(ao),t=h.findLastIndex(ao);if(-1===e)throw new sc("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[h]),[g,A]=sq(m.first),[y,E]=sq();sG(async e=>{if(sj(e)){let e=h.filter(as),r=await o([...e]);u&&!e.length?E("At least one choice must be selected"):!0===r?(d("done"),t(e.map(e=>e.value))):E(r||"You must select a valid value")}else if(sL(e,l)||sN(e,l)){if(y&&E(void 0),n||sL(e,l)&&g!==m.first||sN(e,l)&&g!==m.last){let t=sL(e,l)?-1:1,r=g;do r=(r+t+h.length)%h.length;while(!ao(h[r]));A(r)}}else if("space"===e.name){let e=h[g];e&&!sY.isSeparator(e)&&(e.disabled?E(a.i18n.disabledError):(E(void 0),f(h.map((e,t)=>t===g?aa(e):e))))}else if(e.name===s.all){var r;let e=h.some(e=>au(e)&&!e.checked);f(h.map((r=e,function(e){return au(e)?{...e,checked:r}:e})))}else if(e.name===s.invert)f(h.map(aa));else{let t;if(t=e,"1234567890".includes(t.name)){let t=Number(e.name)-1,r=-1,i=h.findIndex(e=>!sY.isSeparator(e)&&++r===t),n=h[i];n&&au(n)&&(A(i),f(h.map((e,t)=>t===i?aa(e):e)))}}});let _=a.style.message(e.message,c),b=sX({items:h,active:g,renderItem({item:e,isActive:t}){if(sY.isSeparator(e))return` ${e.separator}`;let i=t?a.icon.cursor:" ";if(e.disabled){let t="string"==typeof e.disabled?e.disabled:"(disabled)",r=e.checked?a.icon.disabledChecked:a.icon.disabledUnchecked;return a.style.disabled(`${i}${r} ${e.name} ${t}`)}t&&(r=e.description);let n=e.checked?a.icon.checked:a.icon.unchecked,u=e.checked?e.checkedName:e.name;return(t?a.style.highlight:e=>e)(`${i}${n} ${u}`)},pageSize:i,loop:n});if("done"===c){let e=h.filter(as);return[p,_,a.style.answer(a.style.renderSelectedChoices(e,h))].filter(Boolean).join(" ")}let v=[["↑↓","navigate"],["space","select"]];s.all&&v.push([s.all,"all"]),s.invert&&v.push([s.invert,"invert"]),v.push(["⏎","submit"]);let C=a.style.keysHelpTip(v),D=[[p,_].filter(Boolean).join(" "),b," ",r?a.style.description(r):"",y?a.style.error(y):"",C].filter(Boolean).join("\n").trimEnd();return`${D}\u001b[?25l`}),ac={style:{maskedText:"[input is masked]"}},ad=sB((e,t)=>{let r,{validate:i=()=>!0}=e,n=sU(ac,e.theme),[u,o]=sq("idle"),[s,a]=sq(),[l,c]=sq(""),d=sH({status:u,theme:n});sG(async(e,r)=>{if("idle"===u)if(sj(e)){o("loading");let e=await i(l);!0===e?(c(l),o("done"),t(l)):(r.write(l),a(e||"You must provide a valid value"),o("idle"))}else c(r.line),a(void 0)});let p=n.style.message(e.message,u),h="";e.mask?h=("string"==typeof e.mask?e.mask:"*").repeat(l.length):"done"!==u&&(r=`${n.style.help(n.style.maskedText)}\u001b[?25l`),"done"===u&&(h=n.style.answer(h));let f="";return s&&(f=n.style.error(s)),[[d,p,e.mask?h:r].join(" "),f]});var ap=__webpack_require__("../../node_modules/.pnpm/chardet@2.1.1/node_modules/chardet/lib/index.js"),ah=__webpack_require__("../../node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/index.js");class af extends Error{name="CreateFileError";originalError;constructor(e){super(`Failed to create temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class am extends Error{name="LaunchEditorError";originalError;constructor(e){super(`Failed to launch editor.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class ag extends Error{name="ReadFileError";originalError;constructor(e){super(`Failed to read temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class aA extends Error{name="RemoveFileError";originalError;constructor(e){super(`Failed to remove temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}function ay(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}class aE{editor;lastExitStatus=0;text="";tempFile="";tempDir="";fileOptions={};constructor(e="",t={}){this.text=e,this.fileOptions=t,this.editor=function(e){let t,r;if(e.startsWith('"')){let i=e.indexOf('"',1);-1===i?(t=e.slice(1),r=""):(t=e.substring(1,i),r=e.substring(i+1).trim())}else{let i=e.indexOf(" ");-1===i?(t=e,r=""):(t=e.substring(0,i),r=e.substring(i+1).trim())}return{bin:t,args:r?r.split(/\s+/):[]}}(process.env.VISUAL??process.env.EDITOR??(process.platform.startsWith("win")?"notepad":"vim"))}run(){this.createTempFile();try{try{let e=(0,a.spawnSync)(this.editor.bin,this.editorArgs(),{shell:!1,stdio:"inherit"});if(e.error)throw e.error;this.lastExitStatus=e.status??0}catch(e){throw new am(e)}return this.readTemporaryFile(),this.text}finally{this.cleanup()}}runAsync(e){this.createTempFile();let t=new Promise((e,t)=>{try{let r=(0,a.spawn)(this.editor.bin,this.editorArgs(),{shell:!1,stdio:"inherit"});r.once("error",e=>{t(new am(e))}),r.once("exit",t=>{this.lastExitStatus=t??0,e()})}catch(e){t(new am(e))}}).then(()=>(this.readTemporaryFile(),this.text)).finally(()=>{this.cleanup()});return e&&t.then(t=>e(void 0,t),t=>e(t instanceof Error?t:Error(String(t)),void 0)),t}cleanup(){if(this.tempDir)try{(0,O.rmSync)(this.tempDir,{force:!0,recursive:!0}),this.tempFile="",this.tempDir=""}catch(e){throw new aA(e)}}createTempFile(){try{let e=I.resolve(this.fileOptions.dir??tp.tmpdir());this.tempDir=(0,O.mkdtempSync)(I.join(e,"inquirer-editor-"));let t=(0,td.randomUUID)(),r=ay(this.fileOptions.prefix),i=ay(this.fileOptions.postfix),n=`${r}${t}${i}`;this.tempFile=I.join(this.tempDir,n);let u={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(u.mode=this.fileOptions.mode),(0,O.writeFileSync)(this.tempFile,this.text,u)}catch(e){throw new af(e)}}editorArgs(){return[...this.editor.args,this.tempFile]}readTemporaryFile(){try{let e=(0,O.readFileSync)(this.tempFile);if(0===e.length)this.text="";else{let t=(0,ap.detect)(e)??"utf8";ah.encodingExists(t)||(t="utf8"),this.text=ah.decode(e,t)}}catch(e){throw new ag(e)}}}let a_={validationFailureMode:"keep",style:{loadingMessage:()=>"Validating...",waitingMessage:e=>`Press ${e} to launch your preferred editor.`}},ab=sB((e,t)=>{let{waitForUserInput:r=!0,file:{postfix:i=e.postfix??".txt",...n}={},validate:u=()=>!0}=e,o=sU(a_,e.theme),[s,a]=sq("idle"),[l="",c]=sq(e.default),[d,p]=sq(),h=sH({status:s,theme:o});async function f(r){r.pause();try{var s,d,h;let f,m=await (s=l,d={postfix:i,...n},f="function"==typeof d?d:void 0,new aE(s,"function"==typeof d?h:d).runAsync(f));r.resume(),a("loading");let g=await u(m);!0===g?(p(void 0),a("done"),t(m)):("clear"===o.validationFailureMode?c(e.default):c(m),p(g||"You must provide a valid value"),a("idle"))}catch(e){r.resume(),p(String(e))}}sV(e=>{r||f(e)},[]),sG((e,t)=>{"idle"===s&&sj(e)&&f(t)});let m=o.style.message(e.message,s),g="";if("loading"===s)g=o.style.help(o.style.loadingMessage());else if("idle"===s){let e=o.style.key("enter");g=o.style.help(o.style.waitingMessage(e))}let A="";return d&&(A=o.style.error(d)),[[h,m,g].filter(Boolean).join(" "),A]}),av={icon:{cursor:sk.pointer},style:{disabled:e=>(0,R.styleText)("dim",`- ${e}`),searchTerm:e=>(0,R.styleText)("cyan",e),description:e=>(0,R.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,R.styleText)("bold",e)} ${(0,R.styleText)("dim",t)}`).join((0,R.styleText)("dim"," • "))}};function aC(e){return!sY.isSeparator(e)&&!e.disabled}let aD=sB((e,t)=>{let r,i,{pageSize:n=7,validate:u=()=>!0}=e,o=sU(av,e.theme),[s,a]=sq("loading"),[l,c]=sq(""),[d,p]=sq([]),[h,f]=sq(),m=sz(!1),g=sH({status:s,theme:o}),A=sK(()=>{let e=d.findIndex(aC);return{first:e,last:d.findLastIndex(aC)}},[d]),[y=A.first,E]=sq();sV(()=>{let t=new AbortController;return a("loading"),f(void 0),(async()=>{try{let r=await e.source(l||void 0,{signal:t.signal});if(!t.signal.aborted){let t,i=r.map(e=>{if(sY.isSeparator(e))return e;if("object"!=typeof e||null===e||!("value"in e)){let t=String(e);return{value:e,name:t,short:t,disabled:!1}}let t=e.name??String(e.value),r={value:e.value,name:t,short:e.short??t,disabled:e.disabled??!1};return e.description&&(r.description=e.description),r});if(!m.current&&"default"in e){let r=i.findIndex(t=>aC(t)&&t.value===e.default);t=-1===r?void 0:r,m.current=!0}E(t),f(void 0),p(i),a("idle")}}catch(e){!t.signal.aborted&&e instanceof Error&&f(e.message)}})(),()=>{t.abort()}},[l]);let _=d[y];sG(async(e,r)=>{if(sj(e))if(_){a("loading");let e=await u(_.value);a("idle"),!0===e?(a("done"),t(_.value)):_.name===l?f(e||"You must provide a valid value"):(r.write(_.name),c(_.name))}else r.write(l);else if("tab"===e.name&&_)r.clearLine(0),r.write(_.name),c(_.name);else if("loading"!==s&&(sL(e)||sN(e))){if(r.clearLine(0),sL(e)&&y!==A.first||sN(e)&&y!==A.last){let t=sL(e)?-1:1,r=y;do r=(r+t+d.length)%d.length;while(!aC(d[r]));E(r)}}else c(r.line)});let b=o.style.message(e.message,s),v=o.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),C=sX({items:d,active:y,renderItem({item:e,isActive:t}){if(sY.isSeparator(e))return` ${e.separator}`;if(e.disabled){let t="string"==typeof e.disabled?e.disabled:"(disabled)";return o.style.disabled(`${e.name} ${t}`)}let r=t?o.style.highlight:e=>e,i=t?o.icon.cursor:" ";return r(`${i} ${e.name}`)},pageSize:n,loop:!1});if(h?r=o.style.error(h):0===d.length&&""!==l&&"idle"===s&&(r=o.style.error("No results found")),"done"===s&&_)return[g,b,o.style.answer(_.short)].filter(Boolean).join(" ").trimEnd();i=o.style.searchTerm(l);let D=_?.description,F=[g,b,i].filter(Boolean).join(" ").trimEnd();return[F,[r??C," ",D?o.style.description(D):"",v].filter(Boolean).join("\n").trimEnd()]});var aF=__webpack_require__("../../node_modules/.pnpm/run-async@4.0.6/node_modules/run-async/index.js");function aw(e){queueMicrotask(()=>{throw e})}function aB(e){try{e()}catch(e){aw(e)}}function ax(){return{closed:!0,unsubscribe(){}}}function aS(e){return e instanceof Error?e:Error(String(e))}function aT(e){"function"==typeof e?e():e?.unsubscribe()}class aI{"@@observable"=()=>this;subscribeFn;constructor(e){this.subscribeFn=e,Object.defineProperty(this,function(){let e=Symbol;return"symbol"==typeof e.observable?e.observable:"@@observable"}(),{configurable:!0,value:()=>this})}subscribe(e,t,r){var i,n,u;let o,s=(i=e,n=t,u=r,"function"==typeof i?{next:i,...n?{error:n}:{},...u?{complete:u}:{}}:i??{}),a=!1,l=!1,c={get closed(){return a},unsubscribe(){!a&&(a=!0,l&&aT(o))}},d={next(e){a||aB(()=>s.next?.(e))},error(e){!a&&(a=!0,s.error?aB(()=>s.error?.(e)):aw(e),l&&aT(o))},complete(){!a&&(a=!0,aB(()=>s.complete?.()),l&&aT(o))}};try{o=this.subscribeFn(d),l=!0,c.closed&&aT(o)}catch(e){d.error?.(e)}return c}[Symbol.asyncIterator](){return ak(this)[Symbol.asyncIterator]()}}let aO=new aI(e=>(e.complete?.(),ax()));function ak(e){return{[Symbol.asyncIterator](){let t,r,i=[],n=[],u=!1,o=!1,s=e=>{for(;n.length>0;)n.shift()?.resolve(e)},a=e=>{for(;n.length>0;)n.shift()?.reject(e)};try{r=e.subscribe({next(e){if(u||o)return;let t=n.shift();t?t.resolve({done:!1,value:e}):i.push({value:e})},error(e){u||o||(i.length=0,o=!0,t=aS(e),a(t),r?.unsubscribe())},complete(){u||o||(u=!0,s({done:!0,value:void 0}))}})}catch(e){i.length=0,o=!0,a(t=aS(e))}return{next(){let e=i.shift();return e?Promise.resolve({done:!1,value:e.value}):o?Promise.reject(t??Error("Observable source failed")):u?Promise.resolve({done:!0,value:void 0}):new Promise((e,t)=>{n.push({resolve:e,reject:t})})},return:()=>(u=!0,i.length=0,r?.unsubscribe(),s({done:!0,value:void 0}),Promise.resolve({done:!0,value:void 0}))}}}}let aR=(e,t="",r)=>{let i=e;t.split(".").forEach((e,t,n)=>{"__proto__"!==e&&"constructor"!==e&&(t===n.length-1?i[e]=r:e in i&&"object"==typeof i[e]||(i[e]={}),i=i[e])})},aP=(e,t="",r)=>{let i=r=>String.prototype.split.call(t,r).filter(Boolean).reduce((e,t)=>null==e?e:e[t],e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return void 0===n||n===e?r:n};async function aL(e,t,r){let i=e[t];return"function"==typeof i?aF(i)(r):i}class aN extends Error{name="UnknownPromptTypeError";constructor(e,t){const r=Object.keys(t).toSorted().join(", ");super(`Prompt type "${e}" is not registered. Available prompt types: ${r}`)}}class aj extends Error{name="TTYError";isTtyError=!0}class a${prompts;answers={};process=aO;abortController=new AbortController;opt;constructor(e,t={}){this.opt=t,this.prompts=e}async run(e,t){let r,i,n,u;this.abortController=new AbortController;let o=(i=new Set,n=!1,u=!1,{observable:new aI(e=>{if(u)return e.error?.(r),ax();if(n)return e.complete?.(),ax();let t={observer:e,subscription:{closed:!1,unsubscribe(){t.subscription.closed=!0,i.delete(t)}}};return i.add(t),t.subscription}),next(e){if(!n&&!u)for(let{observer:t,subscription:r}of i)r.closed||aB(()=>t.next?.(e))},error(e){if(!n&&!u){for(let{observer:t,subscription:n}of(u=!0,r=e,i))n.closed=!0,aB(()=>t.error?.(e));i.clear()}},complete(){if(!n&&!u){for(let{observer:e,subscription:t}of(n=!0,i))t.closed=!0,aB(()=>e.complete?.());i.clear()}}});this.process=o.observable,this.answers="object"==typeof t?{...t}:{};try{for await(let t of this.getQuestions(e))if(await this.shouldRun(t)){let e=await this.fetchAnswer(t);aR(this.answers,e.name,e.answer),o.next(e)}return o.complete(),this.answers}catch(e){throw o.error(e),e}finally{this.close()}}async *getQuestions(e){if(Array.isArray(e))yield*e;else{var t;if(("object"==typeof(t=e)||"function"==typeof t)&&null!=t&&"subscribe"in t&&"function"==typeof t.subscribe)yield*ak(e);else if(Object.values(e).every(e=>"object"==typeof e&&!Array.isArray(e)&&null!=e))for(let[t,r]of Object.entries(e))yield Object.assign({},r,{name:t});else yield e}}prepareQuestion=async e=>{let t,r=e.type??"input";if(!Object.hasOwn(this.prompts,r))throw new aN(r,this.prompts);let[i,n,u]=await Promise.all([aL(e,"message",this.answers),aL(e,"default",this.answers),aL(e,"choices",this.answers)]);Array.isArray(u)&&(t=u.map(e=>{let t="object"!=typeof e||null==e?{name:e,value:e}:{...e,value:"value"in e?e.value:"name"in e?e.name:void 0};return"value"in t&&Array.isArray(n)?{checked:n.includes(t.value),...t}:t}));let o=Object.assign({},e,{message:i,default:n,choices:t,type:r});if(e.validate){let t=e.validate;o.validate=e=>t(e,this.answers)}return o};fetchAnswer=async e=>{var t;let r,i,n=await this.prepareQuestion(e),u=this.prompts[n.type];if(null==u)throw Error(`Prompt for type ${n.type} not found`);let o=(t=u).prototype&&"run"in t.prototype&&"function"==typeof t.prototype.run?(e,t)=>new Promise((i,n)=>{let{signal:o}=t;if(o.aborted)return void n(new so({cause:o.reason}));let s=oG.createInterface(function(e){e.skipTTYChecks=void 0===e.skipTTYChecks||e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY)throw new aj("Prompts can not be meaningfully rendered in non-TTY environments");let r=new oW;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}(t)),a=()=>{this.close(),process.kill(process.pid,"SIGINT"),console.log("")};process.on("exit",a),s.on("SIGINT",a);let l=new u(e,s,this.answers),c=()=>{process.removeListener("exit",a),s.removeListener("SIGINT",a),s.setPrompt(""),s.output.unmute(),s.output.write("\x1b[?25h"),oG.cursorTo(s.output,0),s.output.end(),s.close(),r?.()},d=()=>{n(new so({cause:o.reason})),c()};o.addEventListener("abort",d),r=()=>{o.removeEventListener("abort",d),r=void 0},l.run().then(i,n).finally(c)}):u,{signal:s}=this.opt;if(s?.aborted)this.abortController.abort(s.reason);else if(s){let e=()=>this.abortController.abort(s.reason);s.addEventListener("abort",e),i=()=>{s.removeEventListener("abort",e)}}let{filter:a=e=>e}=n,{signal:l}=this.abortController;return o(n,{...this.opt,signal:l}).then(e=>({name:n.name,answer:a(e,this.answers)})).finally(()=>{r?.(),i?.()})};close=()=>{this.abortController.abort()};shouldRun=async e=>{if(!0!==e.askAnswered&&void 0!==aP(this.answers,e.name))return!1;let{when:t}=e;return"function"==typeof t?!!await aF(t)(this.answers):!1!==t}}let aM={input:sJ,select:s2,number:s3,confirm:s8,rawlist:at,expand:ai,checkbox:al,password:ad,editor:ab,search:aD};function aU(e){function t(r,i){let n=new a$(t.prompts,e);return Object.assign(n.run(r,i),{ui:n})}return t.prompts={...aM},t.registerPrompt=function(e,r){return t.prompts[e]=r,this},t.restoreDefaultPrompts=function(){t.prompts={...aM}},t}let aq=aU(),aV=aq;async function aH(){let e=function(){let e=(0,I.resolve)(__dirname,"..","skills",e4);if((0,O.existsSync)((0,I.resolve)(e,"SKILL.md")))return e;let t=(0,I.resolve)(__dirname,"..");return(0,O.existsSync)((0,I.resolve)(t,"SKILL.md"))?t:e}(),t=(0,I.resolve)(e,"SKILL.md");if(!(0,O.existsSync)(e))throw new l(`未找到随包发布的 Skill 目录: ${e}`,{error:"SKILL_INSTALL_FAILED"});if(!(0,O.existsSync)(t))throw new l(`随包发布的 Skill 缺少入口文件: ${t}`,{error:"SKILL_INSTALL_FAILED"});let r=ol(`正在同步 ${e4} Skill ...`).start();try{var i;await (i=e,b({command:"npx",args:["--yes","skills","add",i,"--global","--all","--copy"],createSpawnError:e=>new l("未能调用 npx skills:可执行文件不可用",{error:"SKILL_INSTALLER_NOT_FOUND",cause:e}),createNonZeroExitError:e=>new l(`npx skills 安装失败,退出码 ${e??"unknown"}`,{error:"SKILL_INSTALL_FAILED",exitCode:"number"==typeof e&&0!==e?e:1})})),r.succeed(`${e4} Skill 已同步完成`)}catch(e){throw r.fail(`${e4} Skill 同步失败`),e}}async function az(){try{await aH()}catch(e){if(d(e)){tr({errorMessage:e.message,errorCode:n$(e)}),process.stderr.write(`${e.message}
|
|
47
|
-
`),process.exitCode=e.exitCode;return}throw e}}let aG=new Set(["latest","beta","alpha","next","stable"]);async function aW(e){let t=e?.trim()||"latest";if("latest"===t){let e=ol(`正在解析 ${e6} 最新版本 ...`).start();try{let t=await nY();return e.succeed(`最新版本:${t}`),t}catch(t){throw e.fail("解析最新版本失败"),t}}if(!aG.has(t)&&!v(t))throw new l(`不支持的目标版本: ${t}`,{error:"INVALID_TARGET_VERSION",message:"--target-version 仅支持 semver 版本号或 latest / beta / alpha / next / stable"});return t}async function aJ(e){var t,r,i;let n=await aW(e.targetVersion),u=`${e6}@${n}`,o=function(e){let t=nV({input:e});if(void 0!==e){if(!t)throw new l(`不支持的包管理器: ${e}`,{error:"INVALID_PACKAGE_MANAGER",message:`--package-manager 只能取 ${nM.join(" / ")}`});return t}let r=nV({userAgent:process.env.npm_config_user_agent});if(!r)throw new l("当前环境无法自动识别全局安装所使用的包管理器",{error:"INVALID_PACKAGE_MANAGER",message:`请显式传入 --package-manager,支持 ${nM.join(" / ")}`});return r}(e.packageManager);if("0.
|
|
48
|
-
`),process.exitCode=e.exitCode;return}throw e}}async function aK(e){return(await aV([{type:"list",name:"action",message:`发现新版本 ${e},当前版本 0.
|
|
45
|
+
`)}let oG=require("node:readline");var oW=__webpack_require__("../../node_modules/.pnpm/mute-stream@3.0.0/node_modules/mute-stream/lib/index.js"),oJ=__webpack_require__("../../node_modules/.pnpm/cli-width@4.1.0/node_modules/cli-width/index.js");let oY=(o=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,e=>{let t=0;for(o.lastIndex=0;o.test(e);)t+=1;return e.length-t}),oK=e=>12288===e||e>=65281&&e<=65376||e>=65504&&e<=65510,oX=e=>8987===e||9001===e||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141,oQ=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,oZ=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,o1=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,o0=/\t{1,1000}/y,o2=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,o3=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,o6=/\p{M}+/gu,o4={limit:1/0,ellipsis:""},o8=(e,t={},r={})=>{let i=t.limit??1/0,n=t.ellipsis??"",u=t?.ellipsisWidth??(n?o8(n,o4,r).width:0),o=r.controlWidth??0,s=r.tabWidth??8,a=r.emojiWidth??2,l=r.regularWidth??1,c=r.wideWidth??2,d=[[o3,l],[oQ,0],[oZ,o],[o0,s],[o2,a],[o1,c]],p=0,h=0,f=e.length,m=0,g=!1,A=f,y=Math.max(0,i-u),E=0,_=0,b=0,v=0;s:for(;;){if(_>E||h>=f&&h>p){let t=e.slice(E,_)||e.slice(p,h);for(let e of(m=0,t.replaceAll(o6,""))){let t=e.codePointAt(0)||0;if(b+(v=oK(t)?2:oX(t)?c:l)>y&&(A=Math.min(A,Math.max(E,p)+m)),b+v>i){g=!0;break s}m+=e.length,b+=v}E=_=0}if(h>=f)break;for(let t=0,r=d.length;t<r;t++){let[r,n]=d[t];if(r.lastIndex=h,r.test(e)){if(b+(v=(m=r===o1?oY(e.slice(h,r.lastIndex)):r===o2?1:r.lastIndex-h)*n)>y&&(A=Math.min(A,h+Math.floor((y-b)/n))),b+v>i){g=!0;break s}b+=v,E=p,_=h,h=p=r.lastIndex;continue s}}h+=1}return{width:g?y:b,index:g?A:f,truncated:g,ellipsed:g&&i>=u}},o9={limit:1/0,ellipsis:"",ellipsisWidth:0},o7=(e,t={})=>o8(e,o9,t).width,o5="]8;;",se=RegExp(`(?:\\[(?<code>\\d+)m|\\${o5}(?<uri>.*)\u0007)`,"y"),st=e=>e>=30&&e<=37||e>=90&&e<=97?39:e>=40&&e<=47||e>=100&&e<=107?49:1===e||2===e?22:3===e?23:4===e?24:7===e?27:8===e?28:9===e?29:0===e?0:void 0,sr=e=>`\x1b[${e}m`,si=e=>`\x1b${o5}${e}\u0007`,sn=(e,t,r)=>{let i=t[Symbol.iterator](),n=!1,u=!1,o=e.at(-1),s=void 0===o?0:o7(o),a=i.next(),l=i.next(),c=0;for(;!a.done;){let o=a.value,d=o7(o);s+d<=r?e[e.length-1]+=o:(e.push(o),s=0),("\x1b"===o||"\x9b"===o)&&(n=!0,u=t.startsWith(o5,c+1)),n?u?"\x07"===o&&(n=!1,u=!1):"m"===o&&(n=!1):(s+=d)!==r||l.done||(e.push(""),s=0),a=l,l=i.next(),c+=o.length}o=e.at(-1),!s&&void 0!==o&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},su=/\r?\n/;class so extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}}class ss extends Error{name="CancelPromptError";message="Prompt was canceled"}class sa extends Error{name="ExitPromptError"}class sl extends Error{name="HookError"}class sc extends Error{name="ValidationError"}let sd=new s.AsyncLocalStorage;function sp(){let e=sd.getStore();if(!e)throw new sl("[Inquirer] Hook functions can only be called from within a prompt");return e}function sh(e){return s.AsyncResource.bind((...t)=>{let r=sp(),i=!1,n=r.handleChange;r.handleChange=()=>{i=!0};let u=e(...t);return i&&n(),r.handleChange=n,u})}function sf(e){let t=sp(),{index:r}=t,i=e({get:()=>t.hooks[r],set(e){t.hooks[r]=e},initialized:r in t.hooks});return t.index++,i}let sm={queue(e){let t=sp(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(sp().rl);if(null!=i&&"function"!=typeof i)throw new sc("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=sp();sh(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=sp();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function sg(e,t){return e.split("\n").flatMap(e=>{var r,i,n;return(r=e,i=t,n={trim:!1,wordWrap:!1},String(r).normalize().split(su).map(e=>((e,t,r={})=>{let i,n;if(!1!==r.trim&&""===e.trim())return"";let u="",o=e.split(" "),s=[""],a=0;for(let e=0;e<o.length;e++){let i=o[e];if(!1!==r.trim){let e=s.at(-1)??"",t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,a=o7(t))}0!==e&&(a>=t&&(!1===r.wordWrap||!1===r.trim)&&(s.push(""),a=0),(a||!1===r.trim)&&(s[s.length-1]+=" ",a++));let n=o7(i);if(r.hard&&n>t){let e=1+Math.floor((n-(t-a)-1)/t);Math.floor((n-1)/t)<e&&s.push(""),sn(s,i,t),a=o7(s.at(-1)??"");continue}if(a+n>t&&a&&n){if(!1===r.wordWrap&&a<t){sn(s,i,t),a=o7(s.at(-1)??"");continue}s.push(""),a=0}if(a+n>t&&!1===r.wordWrap){sn(s,i,t),a=o7(s.at(-1)??"");continue}s[s.length-1]+=i,a+=n}!1!==r.trim&&(s=s.map(e=>(e=>{let t=e.split(" "),r=t.length;for(;r&&!o7(t[r-1]);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")})(e)));let l=s.join("\n"),c=!1;for(let e=0;e<l.length;e++){let t=l[e];if(u+=t,c)c=!1;else if(c=t>="\uD800"&&t<="\uDBFF")continue;if("\x1b"===t||"\x9b"===t){se.lastIndex=e+1;let t=se.exec(l),r=t?.groups;if(r?.code!==void 0){let e=Number.parseFloat(r.code);i=39===e?void 0:e}else r?.uri!==void 0&&(n=0===r.uri.length?void 0:r.uri)}if("\n"===l[e+1]){n&&(u+=si(""));let e=i?st(i):void 0;i&&e&&(u+=sr(e))}else"\n"===t&&(i&&st(i)&&(u+=sr(i)),n&&(u+=si(n)))}return u})(e,i,n)).join("\n")).split("\n").map(e=>e.trimEnd())}).join("\n")}function sA(){return oJ({defaultWidth:80,output:sp().rl.output})}let sy="\x1b[G",sE=(e=1)=>e>0?`\u001B[${e}A`:"",s_=(e=1)=>e>0?`\u001B[${e}B`:"",sb=(e,t)=>"number"!=typeof t||Number.isNaN(t)?`\u001B[${e+1}G`:`\u001B[${t+1};${e+1}H`,sv="\x1b[2K",sC=e=>e>0?(sv+sE(1)).repeat(e-1)+sv+sy:"";class sD{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=""){let r=e.split("\n").pop()??"",i=(0,R.stripVTControlCharacters)(r),n=i;this.rl.line.length>0&&(n=n.slice(0,-this.rl.line.length)),this.rl.setPrompt(n),this.cursorPos=this.rl.getCursorPos();let u=sA();e=sg(e,u),t=sg(t,u),i.length%u==0&&(e+="\n");let o=e+(t?"\n"+t:""),s=Math.floor(i.length/u)-this.cursorPos.rows+(t?t.split("\n").length:0);s>0&&(o+=sE(s)),o+=sb(this.cursorPos.cols),this.write(s_(this.extraLinesUnderPrompt)+sC(this.height)+o),this.extraLinesUnderPrompt=s,this.height=o.split("\n").length}checkCursorPos(){let e=this.rl.getCursorPos();e.cols!==this.cursorPos.cols&&(this.write(sb(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt("");let t=s_(this.extraLinesUnderPrompt);t+=e?sC(this.height):"\n",t+="\x1b[G",t+="\x1b[?25h",this.write(t),this.rl.close()}}class sF extends Promise{static withResolver(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}}}let sw=globalThis.setImmediate;function sB(e){let t=function(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(e,r)=>{let i=r.slice(1);return t=i,i},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}();return(r,i={})=>{let{input:n=process.stdin,signal:u}=i,o=new Set,a=new oW;a.pipe(i.output??process.stdout);let l=oG.createInterface({terminal:!0,input:n,output:a});a.mute();let c=new sD(l),{promise:d,resolve:p,reject:h}=sF.withResolver(),f=()=>h(new ss);if(u){let e=()=>h(new so({cause:u.reason}));if(u.aborted)return e(),Object.assign(d,{cancel:f});u.addEventListener("abort",e),o.add(()=>u.removeEventListener("abort",e))}o.add(uO((e,t)=>{h(new sa(`User force closed the prompt with ${e} ${t}`))}));let m=()=>h(new sa("User force closed the prompt with SIGINT"));l.on("SIGINT",m),o.add(()=>l.removeListener("SIGINT",m));var g=l;let A={rl:g,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}};return sd.run(A,()=>{var u;let m,g;return u=function(e){A.handleChange=()=>{A.index=0,e()},A.handleChange()},m=s.AsyncResource.bind(()=>sm.clearAll()),l.on("close",m),o.add(()=>l.removeListener("close",m)),g=()=>{let i=()=>c.checkCursorPos();l.input.on("keypress",i),o.add(()=>l.input.removeListener("keypress",i));let n=null;u(()=>{let i=!1;try{let u=e(r,e=>{i?p(e):n={value:e}});if(void 0===u){let e=t[1]?.getFileName();throw e&&!e.startsWith("file://")&&(e=I.resolve(e)),Error(`Prompt functions must return a string.
|
|
46
|
+
at ${e}`)}let[o,s]="string"==typeof u?[u]:u;c.render(o,s),sm.run()}catch(e){h(e)}if(i=!0,null!==n){let{value:e}=n;n=null,p(e)}})},"readableFlowing"in n?sw(g):g(),Object.assign(d.then(e=>(sm.clearAll(),e),e=>{throw sm.clearAll(),e}).finally(()=>{o.forEach(e=>e()),c.done({clearContent:!!i.clearPromptOnDone}),a.end()}).then(()=>d),{cancel:f})})}}let sx={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"█",squareDarkShade:"▓",squareMediumShade:"▒",squareLightShade:"░",squareTop:"▀",squareBottom:"▄",squareLeft:"▌",squareRight:"▐",squareCenter:"■",bullet:"●",dot:"․",ellipsis:"…",pointerSmall:"›",triangleUp:"▲",triangleUpSmall:"▴",triangleDown:"▼",triangleDownSmall:"▾",triangleLeftSmall:"◂",triangleRightSmall:"▸",home:"⌂",heart:"♥",musicNote:"♪",musicNoteBeamed:"♫",arrowUp:"↑",arrowDown:"↓",arrowLeft:"←",arrowRight:"→",arrowLeftRight:"↔",arrowUpDown:"↕",almostEqual:"≈",notEqual:"≠",lessOrEqual:"≤",greaterOrEqual:"≥",identical:"≡",infinity:"∞",subscriptZero:"₀",subscriptOne:"₁",subscriptTwo:"₂",subscriptThree:"₃",subscriptFour:"₄",subscriptFive:"₅",subscriptSix:"₆",subscriptSeven:"₇",subscriptEight:"₈",subscriptNine:"₉",oneHalf:"\xbd",oneThird:"⅓",oneQuarter:"\xbc",oneFifth:"⅕",oneSixth:"⅙",oneEighth:"⅛",twoThirds:"⅔",twoFifths:"⅖",threeQuarters:"\xbe",threeFifths:"⅗",threeEighths:"⅜",fourFifths:"⅘",fiveSixths:"⅚",fiveEighths:"⅝",sevenEighths:"⅞",line:"─",lineBold:"━",lineDouble:"═",lineDashed0:"┄",lineDashed1:"┅",lineDashed2:"┈",lineDashed3:"┉",lineDashed4:"╌",lineDashed5:"╍",lineDashed6:"╴",lineDashed7:"╶",lineDashed8:"╸",lineDashed9:"╺",lineDashed10:"╼",lineDashed11:"╾",lineDashed12:"−",lineDashed13:"–",lineDashed14:"‐",lineDashed15:"⁃",lineVertical:"│",lineVerticalBold:"┃",lineVerticalDouble:"║",lineVerticalDashed0:"┆",lineVerticalDashed1:"┇",lineVerticalDashed2:"┊",lineVerticalDashed3:"┋",lineVerticalDashed4:"╎",lineVerticalDashed5:"╏",lineVerticalDashed6:"╵",lineVerticalDashed7:"╷",lineVerticalDashed8:"╹",lineVerticalDashed9:"╻",lineVerticalDashed10:"╽",lineVerticalDashed11:"╿",lineDownLeft:"┐",lineDownLeftArc:"╮",lineDownBoldLeftBold:"┓",lineDownBoldLeft:"┒",lineDownLeftBold:"┑",lineDownDoubleLeftDouble:"╗",lineDownDoubleLeft:"╖",lineDownLeftDouble:"╕",lineDownRight:"┌",lineDownRightArc:"╭",lineDownBoldRightBold:"┏",lineDownBoldRight:"┎",lineDownRightBold:"┍",lineDownDoubleRightDouble:"╔",lineDownDoubleRight:"╓",lineDownRightDouble:"╒",lineUpLeft:"┘",lineUpLeftArc:"╯",lineUpBoldLeftBold:"┛",lineUpBoldLeft:"┚",lineUpLeftBold:"┙",lineUpDoubleLeftDouble:"╝",lineUpDoubleLeft:"╜",lineUpLeftDouble:"╛",lineUpRight:"└",lineUpRightArc:"╰",lineUpBoldRightBold:"┗",lineUpBoldRight:"┖",lineUpRightBold:"┕",lineUpDoubleRightDouble:"╚",lineUpDoubleRight:"╙",lineUpRightDouble:"╘",lineUpDownLeft:"┤",lineUpBoldDownBoldLeftBold:"┫",lineUpBoldDownBoldLeft:"┨",lineUpDownLeftBold:"┥",lineUpBoldDownLeftBold:"┩",lineUpDownBoldLeftBold:"┪",lineUpDownBoldLeft:"┧",lineUpBoldDownLeft:"┦",lineUpDoubleDownDoubleLeftDouble:"╣",lineUpDoubleDownDoubleLeft:"╢",lineUpDownLeftDouble:"╡",lineUpDownRight:"├",lineUpBoldDownBoldRightBold:"┣",lineUpBoldDownBoldRight:"┠",lineUpDownRightBold:"┝",lineUpBoldDownRightBold:"┡",lineUpDownBoldRightBold:"┢",lineUpDownBoldRight:"┟",lineUpBoldDownRight:"┞",lineUpDoubleDownDoubleRightDouble:"╠",lineUpDoubleDownDoubleRight:"╟",lineUpDownRightDouble:"╞",lineDownLeftRight:"┬",lineDownBoldLeftBoldRightBold:"┳",lineDownLeftBoldRightBold:"┯",lineDownBoldLeftRight:"┰",lineDownBoldLeftBoldRight:"┱",lineDownBoldLeftRightBold:"┲",lineDownLeftRightBold:"┮",lineDownLeftBoldRight:"┭",lineDownDoubleLeftDoubleRightDouble:"╦",lineDownDoubleLeftRight:"╥",lineDownLeftDoubleRightDouble:"╤",lineUpLeftRight:"┴",lineUpBoldLeftBoldRightBold:"┻",lineUpLeftBoldRightBold:"┷",lineUpBoldLeftRight:"┸",lineUpBoldLeftBoldRight:"┹",lineUpBoldLeftRightBold:"┺",lineUpLeftRightBold:"┶",lineUpLeftBoldRight:"┵",lineUpDoubleLeftDoubleRightDouble:"╩",lineUpDoubleLeftRight:"╨",lineUpLeftDoubleRightDouble:"╧",lineUpDownLeftRight:"┼",lineUpBoldDownBoldLeftBoldRightBold:"╋",lineUpDownBoldLeftBoldRightBold:"╈",lineUpBoldDownLeftBoldRightBold:"╇",lineUpBoldDownBoldLeftRightBold:"╊",lineUpBoldDownBoldLeftBoldRight:"╉",lineUpBoldDownLeftRight:"╀",lineUpDownBoldLeftRight:"╁",lineUpDownLeftBoldRight:"┽",lineUpDownLeftRightBold:"┾",lineUpBoldDownBoldLeftRight:"╂",lineUpDownLeftBoldRightBold:"┿",lineUpBoldDownLeftBoldRight:"╃",lineUpBoldDownLeftRightBold:"╄",lineUpDownBoldLeftBoldRight:"╅",lineUpDownBoldLeftRightBold:"╆",lineUpDoubleDownDoubleLeftDoubleRightDouble:"╬",lineUpDoubleDownDoubleLeftRight:"╫",lineUpDownLeftDoubleRightDouble:"╪",lineCross:"╳",lineBackslash:"╲",lineSlash:"╱"},sS={tick:"✔",info:"ℹ",warning:"⚠",cross:"✘",squareSmall:"◻",squareSmallFilled:"◼",circle:"◯",circleFilled:"◉",circleDotted:"◌",circleDouble:"◎",circleCircle:"ⓞ",circleCross:"ⓧ",circlePipe:"Ⓘ",radioOn:"◉",radioOff:"◯",checkboxOn:"☒",checkboxOff:"☐",checkboxCircleOn:"ⓧ",checkboxCircleOff:"Ⓘ",pointer:"❯",triangleUpOutline:"△",triangleLeft:"◀",triangleRight:"▶",lozenge:"◆",lozengeOutline:"◇",hamburger:"☰",smiley:"㋡",mustache:"෴",star:"★",play:"▶",nodejs:"⬢",oneSeventh:"⅐",oneNinth:"⅑",oneTenth:"⅒"},sT={...sx,...sS},sI={...sx,tick:"√",info:"i",warning:"‼",cross:"\xd7",squareSmall:"□",squareSmallFilled:"■",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(○)",circleCross:"(\xd7)",circlePipe:"(│)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xd7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xd7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"∆",triangleLeft:"◄",triangleRight:"►",lozenge:"♦",lozengeOutline:"◊",hamburger:"≡",smiley:"☺",mustache:"┌─┐",star:"✶",play:"►",nodejs:"♦",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},sO=k.platform.startsWith("win")?!!k.env.CI||!!k.env.WT_SESSION||!!k.env.TERMINUS_SUBLIME||"{cmd::Cmder}"===k.env.ConEmuTask||"Terminus-Sublime"===k.env.TERM_PROGRAM||"vscode"===k.env.TERM_PROGRAM||"xterm-256color"===k.env.TERM||"alacritty"===k.env.TERM||"JetBrains-JediTerm"===k.env.TERMINAL_EMULATOR:"linux"!==k.env.TERM,sk=sO?sT:sI;Object.entries(sS);let sR=new Set(["emacs","vim"]);function sP(e){return sR.has(e)}let sL=(e,t=[])=>"up"===e.name||t.includes("vim")&&"k"===e.name||t.includes("emacs")&&e.ctrl&&"p"===e.name,sN=(e,t=[])=>"down"===e.name||t.includes("vim")&&"j"===e.name||t.includes("emacs")&&e.ctrl&&"n"===e.name,sj=e=>"enter"===e.name||"return"===e.name,s$={prefix:{idle:(0,R.styleText)("blue","?"),done:(0,R.styleText)("green",sk.tick)},spinner:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"].map(e=>(0,R.styleText)("yellow",e))},keybindings:[],style:{answer:e=>(0,R.styleText)("cyan",e),message:e=>(0,R.styleText)("bold",e),error:e=>(0,R.styleText)("red",`> ${e}`),defaultAnswer:e=>(0,R.styleText)("dim",`(${e})`),help:e=>(0,R.styleText)("dim",e),highlight:e=>(0,R.styleText)("cyan",e),key:e=>(0,R.styleText)("cyan",(0,R.styleText)("bold",`<${e}>`))}};function sM(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function sU(...e){let t;return function e(...t){let r={};for(let i of t)for(let[t,n]of Object.entries(i)){let i=r[t];r[t]=sM(i)&&sM(n)?e(i,n):n}return r}({...s$,keybindings:(t=process.env.INQUIRER_KEYBINDINGS)?Array.from(new Set(t.toLowerCase().split(/[\s,]+/).filter(sP))):[]},...e.filter(e=>null!=e))}function sq(e){return sf(t=>{let r=s.AsyncResource.bind(function(e){t.get()!==e&&(t.set(e),sp().handleChange())});if(t.initialized)return[t.get(),r];let i="function"==typeof e?e():e;return t.set(i),[i,r]})}function sV(e,t){sf(r=>{let i=r.get();(!Array.isArray(i)||t.some((e,t)=>!Object.is(e,i[t])))&&sm.queue(e),r.set(t)})}function sH({status:e="idle",theme:t}){let[r,i]=sq(!1),[n,u]=sq(0),{prefix:o,spinner:s}=sU(t);if(sV(()=>{if("loading"===e){let e,t=-1,r=setTimeout(()=>{i(!0),e=setInterval(()=>{u((t+=1)%s.frames.length)},s.interval)},300);return()=>{clearTimeout(r),clearInterval(e)}}i(!1)},[e]),r)return s.frames[n];let a="loading"===e?"idle":e;return"string"==typeof o?o:o[a]??o.idle}function sz(e){return sq({current:e})[0]}function sG(e){let t=sz(e);t.current=e,sV(e=>{let r=!1,i=sh((i,n)=>{r||t.current(n,e)});return e.input.on("keypress",i),()=>{r=!0,e.input.removeListener("keypress",i)}},[])}let sW={validationFailureMode:"keep"},sJ=sB((e,t)=>{let r,{prefill:i="tab"}=e,n=sU(sW,e.theme),[u,o]=sq("idle"),[s,a]=sq(String(e.default??"")),[l,c]=sq(),[d,p]=sq(""),h=sH({status:u,theme:n});async function f(t){let{required:r,pattern:i,patternError:n="Invalid input"}=e;return r&&!t?"You must provide a value":i&&!i.test(t)?n:"function"!=typeof e.validate||await e.validate(t)||"You must provide a valid value"}sG(async(e,r)=>{if("idle"===u)if(sj(e)){let e=d||s;o("loading");let i=await f(e);!0===i?(p(e),o("done"),t(e)):("clear"===n.validationFailureMode?p(""):r.write(d),c(i),o("idle"))}else"backspace"!==e.name||d?"tab"!==e.name||d?(p(r.line),c(void 0)):(a(""),r.clearLine(0),r.write(s),p(s)):a("")}),sV(e=>{"editable"===i&&s&&(e.write(s),p(s))},[]);let m=n.style.message(e.message,u),g=d;"function"==typeof e.transformer?g=e.transformer(d,{isFinal:"done"===u}):"done"===u&&(g=n.style.answer(d)),s&&"done"!==u&&!d&&(r=n.style.defaultAnswer(s));let A="";return l&&(A=n.style.error(l)),[[h,m,r,g].filter(e=>void 0!==e).join(" "),A]});class sY{separator=(0,R.styleText)("dim",Array.from({length:15}).join(sk.line));type="separator";constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&"object"==typeof e&&"type"in e&&"separator"===e.type)}}function sK(e,t){return sf(r=>{let i=r.get();if(!i||i.dependencies.length!==t.length||i.dependencies.some((e,r)=>e!==t[r])){let i=e();return r.set({value:i,dependencies:t}),i}return i.value})}function sX({items:e,active:t,renderItem:r,pageSize:i,loop:n=!0}){let u=sA(),o=t=>(t%e.length+e.length)%e.length,s=e.map((e,i)=>null==e?[]:sg(r({item:e,index:i,isActive:i===t}),u).split("\n")),a=s.reduce((e,t)=>e+t.length,0),l=e=>s[e]??[],c=function({active:e,renderedItems:t,pageSize:r,loop:i}){let n=sz({lastPointer:e,lastActive:void 0}),{lastPointer:u,lastActive:o}=n.current,s=Math.floor(r/2),a=t.reduce((e,t)=>e+t.length,0),l=t.slice(0,e).reduce((e,t)=>e+t.length,0),c=l;if(a>r)if(i)c=u,null!=o&&o<e&&e-o<r&&(c=Math.min(s,1===Math.abs(e-o)?Math.min(u+(t[o]?.length??0),Math.max(l,u)):u+e-o));else{let i=t.slice(e).reduce((e,t)=>e+t.length,0);c=i<r-s?r-i:Math.min(l,s)}return n.current.lastPointer=c,n.current.lastActive=e,c}({active:t,renderedItems:s,pageSize:i,loop:n}),d=l(t).slice(0,i),p=c+d.length<=i?c:i-d.length,h=Array.from({length:i});h.splice(p,d.length,...d);let f=new Set([t]),m=p+d.length,g=o(t+1);for(;m<i&&!f.has(g)&&(n&&a>i?g!==t:g>t);){let e=l(g).slice(0,i-m);h.splice(m,e.length,...e),f.add(g),m+=e.length,g=o(g+1)}for(m=p-1,g=o(t-1);m>=0&&!f.has(g)&&(n&&a>i?g!==t:g<t);){let e=l(g),t=e.slice(Math.max(0,e.length-m-1));h.splice(m-t.length+1,t.length,...t),f.add(g),m-=t.length,g=o(g-1)}return h.filter(e=>"string"==typeof e).join("\n")}let sQ={icon:{cursor:sk.pointer},style:{disabled:e=>(0,R.styleText)("dim",e),description:e=>(0,R.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,R.styleText)("bold",e)} ${(0,R.styleText)("dim",t)}`).join((0,R.styleText)("dim"," • "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function sZ(e){return!sY.isSeparator(e)&&!e.disabled}function s1(e){return!sY.isSeparator(e)}let s0=sB((e,t)=>{let{loop:r=!0,pageSize:i=7}=e,n=sU(sQ,e.theme),{keybindings:u}=n,[o,s]=sq("idle"),a=sH({status:o,theme:n}),l=sz(),c=!u.includes("vim"),d=sK(()=>e.choices.map(e=>{if(sY.isSeparator(e))return e;if("object"!=typeof e||null===e||!("value"in e)){let t=String(e);return{value:e,name:t,short:t,disabled:!1}}let t=e.name??String(e.value),r={value:e.value,name:t,short:e.short??t,disabled:e.disabled??!1};return e.description&&(r.description=e.description),r}),[e.choices]),p=sK(()=>{let e=d.findIndex(s1),t=d.findLastIndex(s1);if(-1===e)throw new sc("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[d]),h=sK(()=>"default"in e?d.findIndex(t=>sZ(t)&&t.value===e.default):-1,[e.default,d]),[f,m]=sq(-1===h?p.first:h),g=d[f];if(null==g||sY.isSeparator(g))throw Error("Active index does not point to a choice");let[A,y]=sq();sG((e,i)=>{if(clearTimeout(l.current),A&&y(void 0),sj(e))g.disabled?y(n.i18n.disabledError):(s("done"),t(g.value));else if(sL(e,u)||sN(e,u)){if(i.clearLine(0),r||sL(e,u)&&f!==p.first||sN(e,u)&&f!==p.last){let t=sL(e,u)?-1:1,r=f;do r=(r+t+d.length)%d.length;while(!s1(d[r]));m(r)}}else{let t;if(t=e,"1234567890".includes(t.name)&&!Number.isNaN(Number(i.line))){let e=Number(i.line)-1,t=-1,r=d.findIndex(r=>!sY.isSeparator(r)&&++t===e),n=d[r];null!=n&&sZ(n)&&m(r),l.current=setTimeout(()=>{i.clearLine(0)},700)}else if("backspace"===e.name)i.clearLine(0);else if(c){let e=i.line.toLowerCase(),t=d.findIndex(t=>!sY.isSeparator(t)&&!!sZ(t)&&t.name.toLowerCase().startsWith(e));-1!==t&&m(t),l.current=setTimeout(()=>{i.clearLine(0)},700)}}}),sV(()=>()=>{clearTimeout(l.current)},[]);let E=n.style.message(e.message,o),_=n.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),b=0,v=sX({items:d,active:f,renderItem({item:e,isActive:t,index:r}){if(sY.isSeparator(e))return b++,` ${e.separator}`;let i=t?n.icon.cursor:" ",u="number"===n.indexMode?`${r+1-b}. `:"";if(e.disabled){let r="string"==typeof e.disabled?e.disabled:"(disabled)",i=t?n.icon.cursor:"-";return n.style.disabled(`${i} ${u}${e.name} ${r}`)}return(t?n.style.highlight:e=>e)(`${i} ${u}${e.name}`)},pageSize:i,loop:r});if("done"===o)return[a,E,n.style.answer(g.short)].filter(Boolean).join(" ");let{description:C}=g,D=[[a,E].filter(Boolean).join(" "),v," ",C?n.style.description(C):"",A?n.style.error(A):"",_].filter(Boolean).join("\n").trimEnd();return`${D}\u001b[?25l`});function s2(e,{min:t,max:r,step:i}){var n,u,o;return!(null==e||Number.isNaN(e))&&(e<t||e>r?`Value must be between ${t} and ${r}`:"any"===i||(n=e,u=i,(1e6*n-(Number.isFinite(o=t)?1e6*o:0))%(1e6*u)==0)||`Value must be a multiple of ${i}${Number.isFinite(t)?` starting from ${t}`:""}`)}let s3=sB((e,t)=>{let r,{validate:i=()=>!0,min:n=-1/0,max:u=1/0,step:o=1,required:s=!1}=e,a=sU(e.theme),[l,c]=sq("idle"),[d,p]=sq(""),[h="",f]=sq(!0===s2(e.default,{min:n,max:u,step:o})?e.default?.toString():void 0),[m,g]=sq(),A=sH({status:l,theme:a});sG(async(e,r)=>{if("idle"===l)if(sj(e)){let e=d||h,a=""===e?void 0:Number(e);c("loading");let l=!0;(s||null!=a)&&(l=s2(a,{min:n,max:u,step:o})),!0===l&&null!=a&&(l=await i(a)),!0===l?(p(String(a??"")),c("done"),t(a)):(r.write(d),g(l||"You must provide a valid numeric value"),c("idle"))}else"backspace"!==e.name||d?"tab"!==e.name||d?(p(r.line),g(void 0)):(f(void 0),r.clearLine(0),r.write(h),p(h)):f(void 0)});let y=a.style.message(e.message,l),E=d;"done"===l&&(E=a.style.answer(d)),h&&"done"!==l&&!d&&(r=a.style.defaultAnswer(h));let _="";return m&&(_=a.style.error(m)),[[A,y,r,E].filter(e=>void 0!==e).join(" "),_]});function s6(e,t){let r=!1!==t;return/^(y|yes)/i.test(e)?r=!0:/^(n|no)/i.test(e)&&(r=!1),r}function s4(e){return e?"Yes":"No"}let s8=sB((e,t)=>{let{transformer:r=s4}=e,[i,n]=sq("idle"),[u,o]=sq(""),s=sU(e.theme),a=sH({status:i,theme:s});sG((s,a)=>{if("idle"===i)if(sj(s)){let i=s6(u,e.default);o(r(i)),n("done"),t(i)}else if("tab"===s.name){let t=s4(!s6(u,e.default));a.clearLine(0),a.write(t),o(t)}else o(a.line)});let l=u,c="";"done"===i?l=s.style.answer(u):c=` ${s.style.defaultAnswer(!1===e.default?"y/N":"Y/n")}`;let d=s.style.message(e.message,i);return`${a} ${d}${c} ${l}`}),s9=/\d+/,s7={style:{description:e=>(0,R.styleText)("cyan",e)}};function s5(e){return null!=e&&!sY.isSeparator(e)}function ae(e,t){let r,i=t.filter(s5);return!(r=i.find(t=>t.key===e))&&s9.test(e)&&(r=i[Number.parseInt(e,10)-1]),r?[r,t.indexOf(r)]:[void 0,void 0]}let at=sB((e,t)=>{let{loop:r=!0}=e,i=sK(()=>{var t;let r;return t=e.choices,r=0,t.map(e=>{if(sY.isSeparator(e))return e;if(r+=1,"object"!=typeof e||null===e||!("value"in e)){let t=String(e);return{value:e,name:t,short:t,key:String(r)}}let t=e.name??String(e.value);return{value:e.value,name:t,short:e.short??t,key:e.key??String(r),description:e.description}})},[e.choices]),[n,u]=sq("idle"),[o,s]=sq(()=>{let t=null==e.default?void 0:i.find(t=>s5(t)&&t.value===e.default);return t?.key??""}),[a,l]=sq(),c=sU(s7,e.theme),{keybindings:d}=c,p=sH({status:n,theme:c}),h=sK(()=>{let e=i.findIndex(s5),t=i.findLastIndex(s5);if(-1===e)throw new sc("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[i]);sG((e,n)=>{if(sj(e)){let[e]=ae(o,i);s5(e)?(s(e.short),u("done"),t(e.value)):""===o?l("Please input a value"):l(`"${(0,R.styleText)("red",o)}" isn't an available option`)}else if(sL(e,d)||sN(e,d)){n.clearLine(0);let[t,u]=ae(o,i);if(t){if(r||sL(e,d)&&u!==h.first||sN(e,d)&&u!==h.last){let t,r=sL(e,d)?-1:1,n=u;do n=(n+r+i.length)%i.length,t=i[n];while(!s5(t));s(t.key)}}else s((sN(e,d)?i.find(s5):i.findLast(s5)).key)}else s(n.line),l(void 0)});let f=c.style.message(e.message,n);if("done"===n)return`${p} ${f} ${c.style.answer(o)}`;let m=i.map(e=>{if(sY.isSeparator(e))return` ${e.separator}`;let t=` ${e.key}) ${e.name}`;return e.key===o?c.style.highlight(t):t}).join("\n"),g="";a&&(g=c.style.error(a));let[A]=ae(o,i),y="";return!a&&A?.description&&(y=c.style.description(A.description)),[`${p} ${f} ${o}`,[m,g,y].filter(Boolean).join("\n")]}),ar={key:"h",name:"Help, list all options",value:void 0},ai=sB((e,t)=>{let{default:r="h"}=e,i=sK(()=>e.choices.map(e=>{if(sY.isSeparator(e))return e;let t="name"in e?e.name:String(e.value);return{value:"value"in e?e.value:t,name:t,key:e.key}}),[e.choices]),[n,u]=sq("idle"),[o,s]=sq(""),[a,l]=sq(e.expanded??!1),[c,d]=sq(),p=sU(e.theme),h=sH({theme:p,status:n});sG((e,n)=>{if(sj(e)){let e=(o||r).toLowerCase();if("h"!==e||a){let r=i.find(t=>!sY.isSeparator(t)&&t.key===e);r?(u("done"),s(e),t(r.value)):""===o?d("Please input a value"):d(`"${(0,R.styleText)("red",o)}" isn't an available option`)}else l(!0)}else s(n.line),d(void 0)});let f=p.style.message(e.message,n);if("done"===n){let e=i.find(e=>!sY.isSeparator(e)&&e.key===o.toLowerCase());return`${h} ${f} ${p.style.answer(e.name)}`}let m=a?i:[...i,ar],g="",A=m.map(e=>sY.isSeparator(e)?"":e.key===r?e.key.toUpperCase():e.key).join("");A=` ${p.style.defaultAnswer(A)}`,a&&(A="",g=m.map(e=>{if(sY.isSeparator(e))return` ${e.separator}`;let t=` ${e.key}) ${e.name}`;return e.key===o.toLowerCase()?p.style.highlight(t):t}).join("\n"));let y="",E=i.find(e=>!sY.isSeparator(e)&&e.key===o.toLowerCase());E&&(y=`${(0,R.styleText)("cyan",">>")} ${E.name}`);let _="";return c&&(_=p.style.error(c)),[`${h} ${f}${A} ${o}`,[g,y,_].filter(Boolean).join("\n")]}),an={icon:{checked:(0,R.styleText)("green",sk.circleFilled),unchecked:sk.circle,cursor:sk.pointer,disabledChecked:(0,R.styleText)("green",sk.circleDouble),disabledUnchecked:"-"},style:{disabled:e=>(0,R.styleText)("dim",e),renderSelectedChoices:e=>e.map(e=>e.short).join(", "),description:e=>(0,R.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,R.styleText)("bold",e)} ${(0,R.styleText)("dim",t)}`).join((0,R.styleText)("dim"," • "))},i18n:{disabledError:"This option is disabled and cannot be toggled."}};function au(e){return!sY.isSeparator(e)&&!e.disabled}function ao(e){return!sY.isSeparator(e)}function as(e){return!sY.isSeparator(e)&&e.checked}function aa(e){return au(e)?{...e,checked:!e.checked}:e}let al=sB((e,t)=>{let r,{pageSize:i=7,loop:n=!0,required:u,validate:o=()=>!0}=e,s={all:"a",invert:"i",...e.shortcuts},a=sU(an,e.theme),{keybindings:l}=a,[c,d]=sq("idle"),p=sH({status:c,theme:a}),[h,f]=sq(e.choices.map(e=>{if(sY.isSeparator(e))return e;if("object"!=typeof e||null===e||!("value"in e)){let t=String(e);return{value:e,name:t,short:t,checkedName:t,disabled:!1,checked:!1}}let t=e.name??String(e.value),r={value:e.value,name:t,short:e.short??t,checkedName:e.checkedName??t,disabled:e.disabled??!1,checked:e.checked??!1};return e.description&&(r.description=e.description),r})),m=sK(()=>{let e=h.findIndex(ao),t=h.findLastIndex(ao);if(-1===e)throw new sc("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[h]),[g,A]=sq(m.first),[y,E]=sq();sG(async e=>{if(sj(e)){let e=h.filter(as),r=await o([...e]);u&&!e.length?E("At least one choice must be selected"):!0===r?(d("done"),t(e.map(e=>e.value))):E(r||"You must select a valid value")}else if(sL(e,l)||sN(e,l)){if(y&&E(void 0),n||sL(e,l)&&g!==m.first||sN(e,l)&&g!==m.last){let t=sL(e,l)?-1:1,r=g;do r=(r+t+h.length)%h.length;while(!ao(h[r]));A(r)}}else if("space"===e.name){let e=h[g];e&&!sY.isSeparator(e)&&(e.disabled?E(a.i18n.disabledError):(E(void 0),f(h.map((e,t)=>t===g?aa(e):e))))}else if(e.name===s.all){var r;let e=h.some(e=>au(e)&&!e.checked);f(h.map((r=e,function(e){return au(e)?{...e,checked:r}:e})))}else if(e.name===s.invert)f(h.map(aa));else{let t;if(t=e,"1234567890".includes(t.name)){let t=Number(e.name)-1,r=-1,i=h.findIndex(e=>!sY.isSeparator(e)&&++r===t),n=h[i];n&&au(n)&&(A(i),f(h.map((e,t)=>t===i?aa(e):e)))}}});let _=a.style.message(e.message,c),b=sX({items:h,active:g,renderItem({item:e,isActive:t}){if(sY.isSeparator(e))return` ${e.separator}`;let i=t?a.icon.cursor:" ";if(e.disabled){let t="string"==typeof e.disabled?e.disabled:"(disabled)",r=e.checked?a.icon.disabledChecked:a.icon.disabledUnchecked;return a.style.disabled(`${i}${r} ${e.name} ${t}`)}t&&(r=e.description);let n=e.checked?a.icon.checked:a.icon.unchecked,u=e.checked?e.checkedName:e.name;return(t?a.style.highlight:e=>e)(`${i}${n} ${u}`)},pageSize:i,loop:n});if("done"===c){let e=h.filter(as);return[p,_,a.style.answer(a.style.renderSelectedChoices(e,h))].filter(Boolean).join(" ")}let v=[["↑↓","navigate"],["space","select"]];s.all&&v.push([s.all,"all"]),s.invert&&v.push([s.invert,"invert"]),v.push(["⏎","submit"]);let C=a.style.keysHelpTip(v),D=[[p,_].filter(Boolean).join(" "),b," ",r?a.style.description(r):"",y?a.style.error(y):"",C].filter(Boolean).join("\n").trimEnd();return`${D}\u001b[?25l`}),ac={style:{maskedText:"[input is masked]"}},ad=sB((e,t)=>{let r,{validate:i=()=>!0}=e,n=sU(ac,e.theme),[u,o]=sq("idle"),[s,a]=sq(),[l,c]=sq(""),d=sH({status:u,theme:n});sG(async(e,r)=>{if("idle"===u)if(sj(e)){o("loading");let e=await i(l);!0===e?(c(l),o("done"),t(l)):(r.write(l),a(e||"You must provide a valid value"),o("idle"))}else c(r.line),a(void 0)});let p=n.style.message(e.message,u),h="";e.mask?h=("string"==typeof e.mask?e.mask:"*").repeat(l.length):"done"!==u&&(r=`${n.style.help(n.style.maskedText)}\u001b[?25l`),"done"===u&&(h=n.style.answer(h));let f="";return s&&(f=n.style.error(s)),[[d,p,e.mask?h:r].join(" "),f]});var ap=__webpack_require__("../../node_modules/.pnpm/chardet@2.1.1/node_modules/chardet/lib/index.js"),ah=__webpack_require__("../../node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/index.js");class af extends Error{name="CreateFileError";originalError;constructor(e){super(`Failed to create temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class am extends Error{name="LaunchEditorError";originalError;constructor(e){super(`Failed to launch editor.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class ag extends Error{name="ReadFileError";originalError;constructor(e){super(`Failed to read temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class aA extends Error{name="RemoveFileError";originalError;constructor(e){super(`Failed to remove temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}function ay(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}class aE{editor;lastExitStatus=0;text="";tempFile="";tempDir="";fileOptions={};constructor(e="",t={}){this.text=e,this.fileOptions=t,this.editor=function(e){let t,r;if(e.startsWith('"')){let i=e.indexOf('"',1);-1===i?(t=e.slice(1),r=""):(t=e.substring(1,i),r=e.substring(i+1).trim())}else{let i=e.indexOf(" ");-1===i?(t=e,r=""):(t=e.substring(0,i),r=e.substring(i+1).trim())}return{bin:t,args:r?r.split(/\s+/):[]}}(process.env.VISUAL??process.env.EDITOR??(process.platform.startsWith("win")?"notepad":"vim"))}run(){this.createTempFile();try{try{let e=(0,a.spawnSync)(this.editor.bin,this.editorArgs(),{shell:!1,stdio:"inherit"});if(e.error)throw e.error;this.lastExitStatus=e.status??0}catch(e){throw new am(e)}return this.readTemporaryFile(),this.text}finally{this.cleanup()}}runAsync(e){this.createTempFile();let t=new Promise((e,t)=>{try{let r=(0,a.spawn)(this.editor.bin,this.editorArgs(),{shell:!1,stdio:"inherit"});r.once("error",e=>{t(new am(e))}),r.once("exit",t=>{this.lastExitStatus=t??0,e()})}catch(e){t(new am(e))}}).then(()=>(this.readTemporaryFile(),this.text)).finally(()=>{this.cleanup()});return e&&t.then(t=>e(void 0,t),t=>e(t instanceof Error?t:Error(String(t)),void 0)),t}cleanup(){if(this.tempDir)try{(0,O.rmSync)(this.tempDir,{force:!0,recursive:!0}),this.tempFile="",this.tempDir=""}catch(e){throw new aA(e)}}createTempFile(){try{let e=I.resolve(this.fileOptions.dir??tp.tmpdir());this.tempDir=(0,O.mkdtempSync)(I.join(e,"inquirer-editor-"));let t=(0,td.randomUUID)(),r=ay(this.fileOptions.prefix),i=ay(this.fileOptions.postfix),n=`${r}${t}${i}`;this.tempFile=I.join(this.tempDir,n);let u={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(u.mode=this.fileOptions.mode),(0,O.writeFileSync)(this.tempFile,this.text,u)}catch(e){throw new af(e)}}editorArgs(){return[...this.editor.args,this.tempFile]}readTemporaryFile(){try{let e=(0,O.readFileSync)(this.tempFile);if(0===e.length)this.text="";else{let t=(0,ap.detect)(e)??"utf8";ah.encodingExists(t)||(t="utf8"),this.text=ah.decode(e,t)}}catch(e){throw new ag(e)}}}let a_={validationFailureMode:"keep",style:{loadingMessage:()=>"Validating...",waitingMessage:e=>`Press ${e} to launch your preferred editor.`}},ab=sB((e,t)=>{let{waitForUserInput:r=!0,file:{postfix:i=e.postfix??".txt",...n}={},validate:u=()=>!0}=e,o=sU(a_,e.theme),[s,a]=sq("idle"),[l="",c]=sq(e.default),[d,p]=sq(),h=sH({status:s,theme:o});async function f(r){r.pause();try{var s,d,h;let f,m=await (s=l,d={postfix:i,...n},f="function"==typeof d?d:void 0,new aE(s,"function"==typeof d?h:d).runAsync(f));r.resume(),a("loading");let g=await u(m);!0===g?(p(void 0),a("done"),t(m)):("clear"===o.validationFailureMode?c(e.default):c(m),p(g||"You must provide a valid value"),a("idle"))}catch(e){r.resume(),p(String(e))}}sV(e=>{r||f(e)},[]),sG((e,t)=>{"idle"===s&&sj(e)&&f(t)});let m=o.style.message(e.message,s),g="";if("loading"===s)g=o.style.help(o.style.loadingMessage());else if("idle"===s){let e=o.style.key("enter");g=o.style.help(o.style.waitingMessage(e))}let A="";return d&&(A=o.style.error(d)),[[h,m,g].filter(Boolean).join(" "),A]}),av={icon:{cursor:sk.pointer},style:{disabled:e=>(0,R.styleText)("dim",`- ${e}`),searchTerm:e=>(0,R.styleText)("cyan",e),description:e=>(0,R.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,R.styleText)("bold",e)} ${(0,R.styleText)("dim",t)}`).join((0,R.styleText)("dim"," • "))}};function aC(e){return!sY.isSeparator(e)&&!e.disabled}let aD=sB((e,t)=>{let r,i,{pageSize:n=7,validate:u=()=>!0}=e,o=sU(av,e.theme),[s,a]=sq("loading"),[l,c]=sq(""),[d,p]=sq([]),[h,f]=sq(),m=sz(!1),g=sH({status:s,theme:o}),A=sK(()=>{let e=d.findIndex(aC);return{first:e,last:d.findLastIndex(aC)}},[d]),[y=A.first,E]=sq();sV(()=>{let t=new AbortController;return a("loading"),f(void 0),(async()=>{try{let r=await e.source(l||void 0,{signal:t.signal});if(!t.signal.aborted){let t,i=r.map(e=>{if(sY.isSeparator(e))return e;if("object"!=typeof e||null===e||!("value"in e)){let t=String(e);return{value:e,name:t,short:t,disabled:!1}}let t=e.name??String(e.value),r={value:e.value,name:t,short:e.short??t,disabled:e.disabled??!1};return e.description&&(r.description=e.description),r});if(!m.current&&"default"in e){let r=i.findIndex(t=>aC(t)&&t.value===e.default);t=-1===r?void 0:r,m.current=!0}E(t),f(void 0),p(i),a("idle")}}catch(e){!t.signal.aborted&&e instanceof Error&&f(e.message)}})(),()=>{t.abort()}},[l]);let _=d[y];sG(async(e,r)=>{if(sj(e))if(_){a("loading");let e=await u(_.value);a("idle"),!0===e?(a("done"),t(_.value)):_.name===l?f(e||"You must provide a valid value"):(r.write(_.name),c(_.name))}else r.write(l);else if("tab"===e.name&&_)r.clearLine(0),r.write(_.name),c(_.name);else if("loading"!==s&&(sL(e)||sN(e))){if(r.clearLine(0),sL(e)&&y!==A.first||sN(e)&&y!==A.last){let t=sL(e)?-1:1,r=y;do r=(r+t+d.length)%d.length;while(!aC(d[r]));E(r)}}else c(r.line)});let b=o.style.message(e.message,s),v=o.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),C=sX({items:d,active:y,renderItem({item:e,isActive:t}){if(sY.isSeparator(e))return` ${e.separator}`;if(e.disabled){let t="string"==typeof e.disabled?e.disabled:"(disabled)";return o.style.disabled(`${e.name} ${t}`)}let r=t?o.style.highlight:e=>e,i=t?o.icon.cursor:" ";return r(`${i} ${e.name}`)},pageSize:n,loop:!1});if(h?r=o.style.error(h):0===d.length&&""!==l&&"idle"===s&&(r=o.style.error("No results found")),"done"===s&&_)return[g,b,o.style.answer(_.short)].filter(Boolean).join(" ").trimEnd();i=o.style.searchTerm(l);let D=_?.description,F=[g,b,i].filter(Boolean).join(" ").trimEnd();return[F,[r??C," ",D?o.style.description(D):"",v].filter(Boolean).join("\n").trimEnd()]});var aF=__webpack_require__("../../node_modules/.pnpm/run-async@4.0.6/node_modules/run-async/index.js");function aw(e){queueMicrotask(()=>{throw e})}function aB(e){try{e()}catch(e){aw(e)}}function ax(){return{closed:!0,unsubscribe(){}}}function aS(e){return e instanceof Error?e:Error(String(e))}function aT(e){"function"==typeof e?e():e?.unsubscribe()}class aI{"@@observable"=()=>this;subscribeFn;constructor(e){this.subscribeFn=e,Object.defineProperty(this,function(){let e=Symbol;return"symbol"==typeof e.observable?e.observable:"@@observable"}(),{configurable:!0,value:()=>this})}subscribe(e,t,r){var i,n,u;let o,s=(i=e,n=t,u=r,"function"==typeof i?{next:i,...n?{error:n}:{},...u?{complete:u}:{}}:i??{}),a=!1,l=!1,c={get closed(){return a},unsubscribe(){!a&&(a=!0,l&&aT(o))}},d={next(e){a||aB(()=>s.next?.(e))},error(e){!a&&(a=!0,s.error?aB(()=>s.error?.(e)):aw(e),l&&aT(o))},complete(){!a&&(a=!0,aB(()=>s.complete?.()),l&&aT(o))}};try{o=this.subscribeFn(d),l=!0,c.closed&&aT(o)}catch(e){d.error?.(e)}return c}[Symbol.asyncIterator](){return ak(this)[Symbol.asyncIterator]()}}let aO=new aI(e=>(e.complete?.(),ax()));function ak(e){return{[Symbol.asyncIterator](){let t,r,i=[],n=[],u=!1,o=!1,s=e=>{for(;n.length>0;)n.shift()?.resolve(e)},a=e=>{for(;n.length>0;)n.shift()?.reject(e)};try{r=e.subscribe({next(e){if(u||o)return;let t=n.shift();t?t.resolve({done:!1,value:e}):i.push({value:e})},error(e){u||o||(i.length=0,o=!0,t=aS(e),a(t),r?.unsubscribe())},complete(){u||o||(u=!0,s({done:!0,value:void 0}))}})}catch(e){i.length=0,o=!0,a(t=aS(e))}return{next(){let e=i.shift();return e?Promise.resolve({done:!1,value:e.value}):o?Promise.reject(t??Error("Observable source failed")):u?Promise.resolve({done:!0,value:void 0}):new Promise((e,t)=>{n.push({resolve:e,reject:t})})},return:()=>(u=!0,i.length=0,r?.unsubscribe(),s({done:!0,value:void 0}),Promise.resolve({done:!0,value:void 0}))}}}}let aR=(e,t="",r)=>{let i=e;t.split(".").forEach((e,t,n)=>{"__proto__"!==e&&"constructor"!==e&&(t===n.length-1?i[e]=r:e in i&&"object"==typeof i[e]||(i[e]={}),i=i[e])})},aP=(e,t="",r)=>{let i=r=>String.prototype.split.call(t,r).filter(Boolean).reduce((e,t)=>null==e?e:e[t],e),n=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return void 0===n||n===e?r:n};async function aL(e,t,r){let i=e[t];return"function"==typeof i?aF(i)(r):i}class aN extends Error{name="UnknownPromptTypeError";constructor(e,t){const r=Object.keys(t).toSorted().join(", ");super(`Prompt type "${e}" is not registered. Available prompt types: ${r}`)}}class aj extends Error{name="TTYError";isTtyError=!0}class a${prompts;answers={};process=aO;abortController=new AbortController;opt;constructor(e,t={}){this.opt=t,this.prompts=e}async run(e,t){let r,i,n,u;this.abortController=new AbortController;let o=(i=new Set,n=!1,u=!1,{observable:new aI(e=>{if(u)return e.error?.(r),ax();if(n)return e.complete?.(),ax();let t={observer:e,subscription:{closed:!1,unsubscribe(){t.subscription.closed=!0,i.delete(t)}}};return i.add(t),t.subscription}),next(e){if(!n&&!u)for(let{observer:t,subscription:r}of i)r.closed||aB(()=>t.next?.(e))},error(e){if(!n&&!u){for(let{observer:t,subscription:n}of(u=!0,r=e,i))n.closed=!0,aB(()=>t.error?.(e));i.clear()}},complete(){if(!n&&!u){for(let{observer:e,subscription:t}of(n=!0,i))t.closed=!0,aB(()=>e.complete?.());i.clear()}}});this.process=o.observable,this.answers="object"==typeof t?{...t}:{};try{for await(let t of this.getQuestions(e))if(await this.shouldRun(t)){let e=await this.fetchAnswer(t);aR(this.answers,e.name,e.answer),o.next(e)}return o.complete(),this.answers}catch(e){throw o.error(e),e}finally{this.close()}}async *getQuestions(e){if(Array.isArray(e))yield*e;else{var t;if(("object"==typeof(t=e)||"function"==typeof t)&&null!=t&&"subscribe"in t&&"function"==typeof t.subscribe)yield*ak(e);else if(Object.values(e).every(e=>"object"==typeof e&&!Array.isArray(e)&&null!=e))for(let[t,r]of Object.entries(e))yield Object.assign({},r,{name:t});else yield e}}prepareQuestion=async e=>{let t,r=e.type??"input";if(!Object.hasOwn(this.prompts,r))throw new aN(r,this.prompts);let[i,n,u]=await Promise.all([aL(e,"message",this.answers),aL(e,"default",this.answers),aL(e,"choices",this.answers)]);Array.isArray(u)&&(t=u.map(e=>{let t="object"!=typeof e||null==e?{name:e,value:e}:{...e,value:"value"in e?e.value:"name"in e?e.name:void 0};return"value"in t&&Array.isArray(n)?{checked:n.includes(t.value),...t}:t}));let o=Object.assign({},e,{message:i,default:n,choices:t,type:r});if(e.validate){let t=e.validate;o.validate=e=>t(e,this.answers)}return o};fetchAnswer=async e=>{var t;let r,i,n=await this.prepareQuestion(e),u=this.prompts[n.type];if(null==u)throw Error(`Prompt for type ${n.type} not found`);let o=(t=u).prototype&&"run"in t.prototype&&"function"==typeof t.prototype.run?(e,t)=>new Promise((i,n)=>{let{signal:o}=t;if(o.aborted)return void n(new so({cause:o.reason}));let s=oG.createInterface(function(e){e.skipTTYChecks=void 0===e.skipTTYChecks||e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY)throw new aj("Prompts can not be meaningfully rendered in non-TTY environments");let r=new oW;return r.pipe(e.output||process.stdout),{terminal:!0,...e,input:t,output:r}}(t)),a=()=>{this.close(),process.kill(process.pid,"SIGINT"),console.log("")};process.on("exit",a),s.on("SIGINT",a);let l=new u(e,s,this.answers),c=()=>{process.removeListener("exit",a),s.removeListener("SIGINT",a),s.setPrompt(""),s.output.unmute(),s.output.write("\x1b[?25h"),oG.cursorTo(s.output,0),s.output.end(),s.close(),r?.()},d=()=>{n(new so({cause:o.reason})),c()};o.addEventListener("abort",d),r=()=>{o.removeEventListener("abort",d),r=void 0},l.run().then(i,n).finally(c)}):u,{signal:s}=this.opt;if(s?.aborted)this.abortController.abort(s.reason);else if(s){let e=()=>this.abortController.abort(s.reason);s.addEventListener("abort",e),i=()=>{s.removeEventListener("abort",e)}}let{filter:a=e=>e}=n,{signal:l}=this.abortController;return o(n,{...this.opt,signal:l}).then(e=>({name:n.name,answer:a(e,this.answers)})).finally(()=>{r?.(),i?.()})};close=()=>{this.abortController.abort()};shouldRun=async e=>{if(!0!==e.askAnswered&&void 0!==aP(this.answers,e.name))return!1;let{when:t}=e;return"function"==typeof t?!!await aF(t)(this.answers):!1!==t}}let aM={input:sJ,select:s0,number:s3,confirm:s8,rawlist:at,expand:ai,checkbox:al,password:ad,editor:ab,search:aD};function aU(e){function t(r,i){let n=new a$(t.prompts,e);return Object.assign(n.run(r,i),{ui:n})}return t.prompts={...aM},t.registerPrompt=function(e,r){return t.prompts[e]=r,this},t.restoreDefaultPrompts=function(){t.prompts={...aM}},t}let aq=aU(),aV=aq;async function aH(){let e=function(){let e=(0,I.resolve)(__dirname,"..","skills",e4);if((0,O.existsSync)((0,I.resolve)(e,"SKILL.md")))return e;let t=(0,I.resolve)(__dirname,"..");return(0,O.existsSync)((0,I.resolve)(t,"SKILL.md"))?t:e}(),t=(0,I.resolve)(e,"SKILL.md");if(!(0,O.existsSync)(e))throw new l(`未找到随包发布的 Skill 目录: ${e}`,{error:"SKILL_INSTALL_FAILED"});if(!(0,O.existsSync)(t))throw new l(`随包发布的 Skill 缺少入口文件: ${t}`,{error:"SKILL_INSTALL_FAILED"});let r=ol(`正在同步 ${e4} Skill ...`).start();try{var i;await (i=e,b({command:"npx",args:["--yes","skills","add",i,"--global","--all","--copy"],createSpawnError:e=>new l("未能调用 npx skills:可执行文件不可用",{error:"SKILL_INSTALLER_NOT_FOUND",cause:e}),createNonZeroExitError:e=>new l(`npx skills 安装失败,退出码 ${e??"unknown"}`,{error:"SKILL_INSTALL_FAILED",exitCode:"number"==typeof e&&0!==e?e:1})})),r.succeed(`${e4} Skill 已同步完成`)}catch(e){throw r.fail(`${e4} Skill 同步失败`),e}}async function az(){try{await aH()}catch(e){if(d(e)){tr({errorMessage:e.message,errorCode:n$(e)}),process.stderr.write(`${e.message}
|
|
47
|
+
`),process.exitCode=e.exitCode;return}throw e}}let aG=new Set(["latest","beta","alpha","next","stable"]);async function aW(e){let t=e?.trim()||"latest";if("latest"===t){let e=ol(`正在解析 ${e6} 最新版本 ...`).start();try{let t=await nY();return e.succeed(`最新版本:${t}`),t}catch(t){throw e.fail("解析最新版本失败"),t}}if(!aG.has(t)&&!v(t))throw new l(`不支持的目标版本: ${t}`,{error:"INVALID_TARGET_VERSION",message:"--target-version 仅支持 semver 版本号或 latest / beta / alpha / next / stable"});return t}async function aJ(e){var t,r,i;let n=await aW(e.targetVersion),u=`${e6}@${n}`,o=function(e){let t=nV({input:e});if(void 0!==e){if(!t)throw new l(`不支持的包管理器: ${e}`,{error:"INVALID_PACKAGE_MANAGER",message:`--package-manager 只能取 ${nM.join(" / ")}`});return t}let r=nV({userAgent:process.env.npm_config_user_agent});if(!r)throw new l("当前环境无法自动识别全局安装所使用的包管理器",{error:"INVALID_PACKAGE_MANAGER",message:`请显式传入 --package-manager,支持 ${nM.join(" / ")}`});return r}(e.packageManager);if("0.7.0"===n)return(ol("dymg 已是目标版本(0.7.0),跳过 CLI 安装").info(),e.skipSkills)?void ol("已跳过 Skill 同步。如需同步,请执行 dymg skills install").info():void await aH();let s=ol(`正在使用 ${o} 安装 ${u} ...`).start();try{let e;await (t=o,r=u,e=function(e,t){switch(e){case"npm":return{command:"npm",args:["install","-g",t],windowsExtension:".cmd"};case"pnpm":return{command:"pnpm",args:["add","-g",t],windowsExtension:".cmd"};case"yarn":return{command:"yarn",args:["global","add",t],windowsExtension:".cmd"};case"bun":return{command:"bun",args:["add","-g",t],windowsExtension:!1};default:throw TypeError(`Unsupported package manager: ${e}`)}}(t,r),b({command:e.command,args:e.args,windowsExtension:e.windowsExtension,createSpawnError:e=>new l(`未能调用 ${t}:可执行文件不可用`,{error:"PACKAGE_MANAGER_NOT_FOUND",cause:e}),createNonZeroExitError:e=>new l(`${t} 安装失败,退出码 ${e??"unknown"}`,{error:"PACKAGE_MANAGER_INSTALL_FAILED",exitCode:"number"==typeof e&&0!==e?e:1})})),s.succeed(`dymg 已更新完成,当前版本:${n}`)}catch(e){throw s.fail(`${o} 安装失败`),e}if(e.skipSkills)return void ol("已跳过 Skill 同步。如需同步,请执行 dymg skills install").info();let a=ol("正在启动更新后的 CLI 同步 Skill ...").start();try{await (i=u,b({command:"npx",args:["--yes",i,"skills","install"],windowsExtension:".cmd",createSpawnError:e=>new l("CLI 已更新,但未能启动新进程同步 Skill",{error:"SKILL_INSTALL_FAILED",cause:e}),createNonZeroExitError:e=>new l(`CLI 已更新,但 Skill 同步失败,退出码 ${e??"unknown"}`,{error:"SKILL_INSTALL_FAILED",exitCode:"number"==typeof e&&0!==e?e:1})})),a.succeed("Skill 已同步完成")}catch(e){throw a.fail("Skill 同步失败"),e}}async function aY(e){try{await aJ(e)}catch(e){if(d(e)){tr({errorMessage:e.message,errorCode:n$(e)}),process.stderr.write(`${e.message}
|
|
48
|
+
`),process.exitCode=e.exitCode;return}throw e}}async function aK(e){return(await aV([{type:"list",name:"action",message:`发现新版本 ${e},当前版本 0.7.0。是否现在更新并同步 Skill?`,choices:[{name:"现在更新",value:"update"},{name:"暂不更新",value:"skip"}],default:"update"}])).action}async function aX(e,t){let r=ol(`正在检查 ${e6} 更新,当前版本:0.7.0`).start();try{let e=await nK();if(r.succeed("更新检查完成"),!e.hasUpdate){await nX(e),ol(`dymg 已是最新版本(${e.currentVersion})`).info();return}if(!function(e){let{caller:t}=e.optsWithGlobals();return!0===process.stdin.isTTY&&!0===process.stdout.isTTY&&"true"!==process.env.CI&&(void 0===t||"unknown"===t)}(t)||!nV({userAgent:process.env.npm_config_user_agent})){var i;i=e.latestVersion,process.stdout.write(`${nG(i).join("\n")}
|
|
49
49
|
`),await nX(e,{notified:!0});return}let n=await aK(e.latestVersion);if(await nX(e,{notified:!0}),"skip"===n)return void ol("已跳过更新,可执行 dymg update 完成 CLI 和 Skill 同步").info();await aJ({targetVersion:e.latestVersion})}catch(t){if(r.isSpinning&&r.fail("检查更新失败"),d(t)){tr({errorMessage:t.message,errorCode:n$(t)}),process.stderr.write(`${t.message}
|
|
50
50
|
`),process.exitCode=t.exitCode;return}let e=t instanceof Error?t.message:String(t);tr({errorMessage:e,errorCode:n$(t)}),process.stderr.write(`检查更新失败:${e}
|
|
51
|
-
`),process.exitCode=1}}var aQ=((es={})[es.Todo=0]="Todo",es[es.Overtime=1]="Overtime",es[es.Dealt=2]="Dealt",es[es.Solving=3]="Solving",es[es.NoNeed=100]="NoNeed",es),aZ=((ea={})[ea.CreateTime=1]="CreateTime",ea[ea.DdlTime=2]="DdlTime",ea);let a1=["feedbackId","openId","content","createTime","dealtStatus","dealtAction","dealtComment","dealtTime","dealtDdl","hasReply","isImportant","isRead","appVersion","microAppVersion","libraryVersion","platform","device","deviceId","osVersion","labelName","label1Name","isRefund","imageUrlList","logDownloadUrl"],
|
|
51
|
+
`),process.exitCode=1}}var aQ=((es={})[es.Todo=0]="Todo",es[es.Overtime=1]="Overtime",es[es.Dealt=2]="Dealt",es[es.Solving=3]="Solving",es[es.NoNeed=100]="NoNeed",es),aZ=((ea={})[ea.CreateTime=1]="CreateTime",ea[ea.DdlTime=2]="DdlTime",ea);let a1=["feedbackId","openId","content","createTime","dealtStatus","dealtAction","dealtComment","dealtTime","dealtDdl","hasReply","isImportant","isRead","appVersion","microAppVersion","libraryVersion","platform","device","deviceId","osVersion","labelName","label1Name","isRefund","imageUrlList","logDownloadUrl"],a0=["3","4"];function a2(e,t){for(let r of(ro(e,t),rf(e)??[]))rl(r,t)}var a3=((el={})[el.NONE=0]="NONE",el[el.UNRESOLVED=1]="UNRESOLVED",el[el.RESOLVED=2]="RESOLVED",el);let a6=["ticketId","openId","content","createTime","updateTime","deadlineTime","resolveDuration","auditStatus","auditStatusText","minorRefundStatus","minorRefundStatusText","devReplyText","userHasMoreRefund","ageRange","orderList","imageList","rejectReasonList","logUrl"];var a4=((ec={})[ec.ActivateDate=1]="ActivateDate",ec[ec.FirstChannel=2]="FirstChannel",ec),a8=((ed={})[ed.Ad=1]="Ad",ed[ed.Star=2]="Star",ed[ed.Pop=3]="Pop",ed[ed.Nature=4]="Nature",ed),a9=((ep={})[ep.RealTime=1]="RealTime",ep[ep.Offline=2]="Offline",ep),a7=((eh={})[eh.ActivateNewUserNum=1]="ActivateNewUserNum",eh[eh.AdActivateConsumeAverage=2]="AdActivateConsumeAverage",eh[eh.AdConsumeFirstDay=3]="AdConsumeFirstDay",eh[eh.PopConsumeCumulative=4]="PopConsumeCumulative",eh[eh.PopConsumeCumulativeAverage=5]="PopConsumeCumulativeAverage",eh[eh.AdIncomeUserNumDaily=6]="AdIncomeUserNumDaily",eh[eh.ECPMDaily=7]="ECPMDaily",eh[eh.AdShowNumDailyAverage=8]="AdShowNumDailyAverage",eh[eh.AdArpuDaily=9]="AdArpuDaily",eh[eh.AdIncomeCumulative=10]="AdIncomeCumulative",eh[eh.AdLTV=11]="AdLTV",eh[eh.PayUserNumDaily=12]="PayUserNumDaily",eh[eh.PayUserNumCumulative=13]="PayUserNumCumulative",eh[eh.PayNumDailyAverage=14]="PayNumDailyAverage",eh[eh.PayArpuDaily=15]="PayArpuDaily",eh[eh.PayArppuDaily=16]="PayArppuDaily",eh[eh.PayCumulative=17]="PayCumulative",eh[eh.PayLTV=18]="PayLTV",eh[eh.TotalArpuDaily=19]="TotalArpuDaily",eh[eh.TotalIncomeCumulative=20]="TotalIncomeCumulative",eh[eh.TotalLTV=21]="TotalLTV",eh[eh.TotalROI=22]="TotalROI",eh[eh.RetainUserNumDaily=23]="RetainUserNumDaily",eh[eh.RetainUserRateDaily=24]="RetainUserRateDaily",eh[eh.OnlineTimeDailyAverage=25]="OnlineTimeDailyAverage",eh[eh.LaunchNumDailyAverage=26]="LaunchNumDailyAverage",eh[eh.AdPenetrationRateDaily=27]="AdPenetrationRateDaily",eh[eh.PayPenetrationRateDaily=28]="PayPenetrationRateDaily",eh[eh.PayPenetrationRateCumulative=29]="PayPenetrationRateCumulative",eh[eh.TimeToFirstPayAverage=30]="TimeToFirstPayAverage",eh),a5=((ef={})[ef.Ad=1]="Ad",ef[ef.StarLive=2]="StarLive",ef[ef.StarVideo=3]="StarVideo",ef[ef.PopLive=4]="PopLive",ef[ef.PopVideo=5]="PopVideo",ef[ef.NatureVideo=6]="NatureVideo",ef[ef.NatureSearch=7]="NatureSearch",ef[ef.NatureHomePageSidebar=8]="NatureHomePageSidebar",ef[ef.NaturePersonSidebar=9]="NaturePersonSidebar",ef[ef.NaturePersonOther=10]="NaturePersonOther",ef[ef.NatureIM=11]="NatureIM",ef[ef.NatureGameCenter=12]="NatureGameCenter",ef[ef.NatureCoinGameCenter=13]="NatureCoinGameCenter",ef[ef.NatureFeedPlay=14]="NatureFeedPlay",ef[ef.NatureFeedCard=15]="NatureFeedCard",ef[ef.NatureDesktop=16]="NatureDesktop",ef[ef.NatureInMp=17]="NatureInMp",ef[ef.NatureScan=18]="NatureScan",ef[ef.NatureGameCircle=19]="NatureGameCircle",ef[ef.NatureLive=20]="NatureLive",ef[ef.NatureOther=21]="NatureOther",ef);let le=["1","2"],lt=["1","2","3","4","5","6","7","8","9","10","11","12","13","14","30","45","60","75","90","120","150","180"],lr=[...Array.from({length:90},(e,t)=>String(t+1)),"120","150","180"],li=new Set([a7.ActivateNewUserNum,a7.AdActivateConsumeAverage,a7.AdConsumeFirstDay]),ln=["metric","metricName","lifeTime","value"],lu={[a8.Ad]:[a5.Ad],[a8.Star]:[a5.StarLive,a5.StarVideo],[a8.Pop]:[a5.PopLive,a5.PopVideo],[a8.Nature]:[a5.NatureVideo,a5.NatureSearch,a5.NatureHomePageSidebar,a5.NaturePersonSidebar,a5.NaturePersonOther,a5.NatureIM,a5.NatureGameCenter,a5.NatureCoinGameCenter,a5.NatureFeedPlay,a5.NatureFeedCard,a5.NatureDesktop,a5.NatureInMp,a5.NatureScan,a5.NatureGameCircle,a5.NatureLive,a5.NatureOther]},lo=`
|
|
52
52
|
参数说明:
|
|
53
53
|
- --dimension / --metric / --first-channel / --second-channel 均支持逗号分隔多值
|
|
54
54
|
- --life-time 可重复传入,格式为 <指标枚举>:<生命周期天数列表>,例如 --life-time 11:7,14,30
|
|
@@ -127,7 +127,7 @@ ${t}`,uE=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),u_=Objec
|
|
|
127
127
|
|
|
128
128
|
示例:
|
|
129
129
|
$ dymg growth metric-query --app-id <app-id> --activate-start-date 2026-07-07 --activate-end-date 2026-07-08 --dimension 1,2 --metric 1,24 --life-time 24:1,2 --first-channel 1 --freshness-type 1
|
|
130
|
-
$ dymg growth metric-query --app-id <app-id> --activate-start-date 2026-06-01 --activate-end-date 2026-06-07 --dimension 1 --metric 11,21 --life-time 11:7,14,30 --life-time 21:7,14,30 --first-channel 1,2,3,4 --freshness-type 2`;function ls(e,t=[]){return[...t,e]}function la(e){return e===a9.RealTime?"1,2":"1,3,7"}var ll=((em={})[em.HotGame=1]="HotGame",em[em.BestSeller=2]="BestSeller",em[em.NewGame=3]="NewGame",em[em.Pop=4]="Pop",em),lc=((eg={})[eg.IAA=1]="IAA",eg[eg.IAP=2]="IAP",eg[eg.IAAP=3]="IAAP",eg);let ld=["elementId","elementName","elementType","hotValue","dataStatus","hotspotId","videoId","elementTags","description","heatTrend"],lp=["title","hotValue","topics","hotInsights","jumpUrl","contentId","coverUrl","playUrl","contentTags","gamificationCategories","gamificationMechanics","genderDistribution","ageDistribution","commentSummary","topComments","dataStatus"],lh=["topicId","topicName","parentTopicId","parentTopicName","dataStatus","topicOverview","marketOpportunitySummary","gamificationCategories","gamificationMechanics","genderDistribution","ageDistribution","audiencePreferences","contentPreferences","interactionPreferences","relatedGames","recentHotspots","topVideos","trend7D","trend30D","trend90D"],lf=["all","image","topic","interaction"],lm=[{id:"30000",name:"生存"},{id:"30001",name:"动作"},{id:"30002",name:"割草"},{id:"30003",name:"冒险"},{id:"30004",name:"放置挂机"},{id:"30005",name:"MMO"},{id:"30006",name:"修仙"},{id:"30100",name:"找茬"},{id:"30101",name:"解谜"},{id:"30102",name:"寻物"},{id:"30103",name:"消除"},{id:"30104",name:"合成"},{id:"30105",name:"换装"},{id:"30106",name:"派对游戏"},{id:"30107",name:"大乱斗"},{id:"30108",name:"答题"},{id:"30109",name:"超休闲"},{id:"30200",name:"射击"},{id:"30201",name:"格斗"},{id:"30202",name:"竞速"},{id:"30203",name:"节奏"},{id:"30204",name:"跑酷"},{id:"30205",name:"飞行射击"},{id:"30206",name:"体育竞技"},{id:"30207",name:"MOBA"},{id:"30300",name:"模拟养成"},{id:"30301",name:"模拟经营"},{id:"30302",name:"模拟器"},{id:"30303",name:"收纳整理"},{id:"30304",name:"沙盒建造"},{id:"30400",name:"塔防"},{id:"30401",name:"即时战斗"},{id:"30402",name:"回合战斗"},{id:"30403",name:"自走棋"},{id:"30404",name:"SLG"},{id:"30500",name:"五子棋"},{id:"30501",name:"军旗"},{id:"30502",name:"围棋"},{id:"30503",name:"象棋"},{id:"30504",name:"麻将"},{id:"30505",name:"扑克牌"},{id:"30506",name:"经典桌游"},{id:"30507",name:"聚会游戏"},{id:"30508",name:"其他棋牌"}].map(e=>e.id);function lg(e,t=String){return e?.map(t).join("|")}var lA=((eA={})[eA.All=1]="All",eA[eA.Douyin=2]="Douyin",eA[eA.DouyinLite=3]="DouyinLite",eA[eA.Toutiao=4]="Toutiao",eA[eA.ToutiaoLite=5]="ToutiaoLite",eA[eA.Fanqie=6]="Fanqie",eA[eA.FanqieChangTing=7]="FanqieChangTing",eA[eA.Hotsoon=8]="Hotsoon",eA[eA.Ppx=9]="Ppx",eA),ly=((ey={})[ey.Debug=1]="Debug",ey[ey.Info=2]="Info",ey[ey.Warn=3]="Warn",ey[ey.Error=4]="Error",ey[ey.Fatal=5]="Fatal",ey),lE=((eE={})[eE.All=1]="All",eE[eE.Android=2]="Android",eE[eE.IOS=3]="IOS",eE[eE.OpenHarmony=4]="OpenHarmony",eE[eE.Windows=5]="Windows",eE),l_=((e_={})[e_.All=1]="All",e_[e_.High=2]="High",e_[e_.Mid=3]="Mid",e_[e_.Low=4]="Low",e_),lb=((eb={})[eb.All=1]="All",eb[eb.Android=2]="Android",eb[eb.IOS=3]="IOS",eb[eb.OpenHarmony=4]="OpenHarmony",eb[eb.Windows=5]="Windows",eb),lv=((ev={})[ev.All=1]="All",ev[ev.Android=2]="Android",ev[ev.IOS=3]="IOS",ev[ev.OpenHarmony=4]="OpenHarmony",ev[ev.Windows=5]="Windows",ev),lC=((eC={})[eC.LaunchCostMs=1001]="LaunchCostMs",eC[eC.LaunchRetentionRate=1002]="LaunchRetentionRate",eC[eC.WasmCompileCostMs=1003]="WasmCompileCostMs",eC[eC.CallMainCostMs=1004]="CallMainCostMs",eC[eC.LaunchFPCostMs=1005]="LaunchFPCostMs",eC[eC.LaunchTTICostMs=1006]="LaunchTTICostMs",eC[eC.ResourcePrepareCostMs=1007]="ResourcePrepareCostMs",eC[eC.CodeInjectCostMs=1008]="CodeInjectCostMs",eC[eC.WasmSplitBeforeFPRate=1011]="WasmSplitBeforeFPRate",eC[eC.WasmSplitBeforeFPCostMs=1012]="WasmSplitBeforeFPCostMs",eC[eC.WasmSplitBeforeTTIRate=1013]="WasmSplitBeforeTTIRate",eC[eC.WasmSplitBeforeTTICostMs=1014]="WasmSplitBeforeTTICostMs",eC[eC.FPS=2001]="FPS",eC[eC.StutterRate=2002]="StutterRate",eC[eC.RenderDrawCall=2003]="RenderDrawCall",eC[eC.RenderTriangle=2004]="RenderTriangle",eC[eC.RenderVertex=2005]="RenderVertex",eC[eC.AvgMemoryMB=2011]="AvgMemoryMB",eC[eC.MemoryUsageRate=2012]="MemoryUsageRate",eC[eC.MemoryPeakMB=2013]="MemoryPeakMB",eC[eC.MemoryAbnormalExitRate=2014]="MemoryAbnormalExitRate",eC[eC.CPUUsageRate=2021]="CPUUsageRate",eC[eC.GPUUsageRate=2022]="GPUUsageRate",eC[eC.RequestCostMs=3001]="RequestCostMs",eC[eC.RequestErrorRate=3002]="RequestErrorRate",eC[eC.DownloadFileCostMs=3003]="DownloadFileCostMs",eC[eC.DownloadFileErrorRate=3004]="DownloadFileErrorRate",eC),lD=((eD={})[eD.All=1]="All",eD[eD.Required=2]="Required",eD[eD.NotRequired=3]="NotRequired",eD),lF=((eF={})[eF.Trend=1]="Trend",eF[eF.SceneConversion=2]="SceneConversion",eF[eF.LaunchDurationDistribution=3]="LaunchDurationDistribution",eF[eF.LaunchLossDistribution=4]="LaunchLossDistribution",eF[eF.WasmSplit=5]="WasmSplit",eF);let lw={[lA.Douyin]:"1128",[lA.DouyinLite]:"2329",[lA.Toutiao]:"13",[lA.ToutiaoLite]:"35",[lA.Fanqie]:"1967",[lA.FanqieChangTing]:"3040",[lA.Hotsoon]:"8663"},lB=Object.keys(lw),lx=Object.values(lw),lS=[lv.Android,lv.IOS,lv.OpenHarmony].map(String),lT=["group","genreName","engine","degradedIndicatorCount","section","indicatorName","metric","os","actualValue","standardValue","delta","unit","suggestion"],lI=["metric","metricName","name","sceneId","aggregation","direction","unit","date","value","sampleCount"],lO=["appId","host","os","appVersion","gameVersion","jssdkVersion","versionType","openId","traceId","logLevel","timestamp","msg"];function lk(e,t,r){return(e??[]).map(e=>({...t,section:r,indicatorName:e.indicatorName,metric:e.metric,os:e.os,actualValue:e.actualValue,standardValue:e.standardValue,delta:e.delta,unit:e.unit,suggestion:e.suggestion}))}function lR(e){return(e??[]).flatMap(e=>(e.points??[]).map(t=>({metric:e.metric,metricName:rD(lC,e.metric),name:e.name,sceneId:e.sceneId,aggregation:e.aggregation,direction:e.direction,unit:e.unit,date:t.date,value:t.value,sampleCount:t.sampleCount})))}function lP(e){rd({startDate:e.startDate,endDate:e.endDate,maxLookbackDays:ov,label:"性能数据"}),rn(e.host,"--host",lB),rn(e.os,"--os",lS),rn(e.deviceLevel,"--device-level",rv(l_)),ru(e.metrics,"--metrics",rv(lC))}function lL(e){return{startDate:e.startDate,endDate:e.endDate,hostAid:lw[rC(e.host,lA)]??"",os:rC(e.os,lv),mpVersion:e.mpVersion,deviceLevel:rC(e.deviceLevel,l_)}}var lN=((ew={})[ew.Invalid=0]="Invalid",ew[ew.CpaDauV2=1]="CpaDauV2",ew[ew.CpaDauV3=2]="CpaDauV3",ew[ew.CpaReservation=3]="CpaReservation",ew[ew.CpaActivate=4]="CpaActivate",ew[ew.CpaAndroidDownload=5]="CpaAndroidDownload",ew[ew.CpmFeedVv=6]="CpmFeedVv",ew[ew.Cps=7]="Cps",ew[ew.Fix=8]="Fix",ew[ew.CpsV2=9]="CpsV2",ew[ew.Revenues=10]="Revenues",ew[ew.AuthorPurchase=11]="AuthorPurchase",ew[ew.CpsRevenues=12]="CpsRevenues",ew[ew.CpaReserveAndDownload=13]="CpaReserveAndDownload",ew[ew.CpaMultiReserve=14]="CpaMultiReserve",ew[ew.CpmUvAll=15]="CpmUvAll",ew[ew.Ocpm=16]="Ocpm",ew[ew.OcpmUvAll=17]="OcpmUvAll",ew[ew.CpmFeedVvMultiOs=18]="CpmFeedVvMultiOs",ew[ew.CpmUvAllMultiOs=19]="CpmUvAllMultiOs",ew[ew.CpaActivateMultiOs=20]="CpaActivateMultiOs",ew[ew.CpaReserveAndDownloadMultiOs=21]="CpaReserveAndDownloadMultiOs",ew[ew.CpaDauV2MultiOs=22]="CpaDauV2MultiOs",ew[ew.CpaDauV3MultiOs=23]="CpaDauV3MultiOs",ew[ew.CpaUnionAndroidDownload=24]="CpaUnionAndroidDownload",ew[ew.CpaMixedActivate=25]="CpaMixedActivate",ew[ew.CpsLongPeriod=26]="CpsLongPeriod",ew[ew.CpsMicroGame2022=27]="CpsMicroGame2022",ew[ew.CpaDauV2AndCps=28]="CpaDauV2AndCps",ew[ew.CpaDauV2AndCpsMicroGame2022=29]="CpaDauV2AndCpsMicroGame2022",ew[ew.CpsV3=30]="CpsV3",ew[ew.MaxSize=31]="MaxSize",ew),lj=((eB={})[eB.Video=1]="Video",eB[eB.Live=2]="Live",eB[eB.All=100]="All",eB),l$=((ex={})[ex.MicroGame=0]="MicroGame",ex[ex.MicroTerminal=1]="MicroTerminal",ex[ex.All=100]="All",ex),lM=((eS={})[eS.Min=0]="Min",eS[eS.Pending=1]="Pending",eS[eS.Passed=2]="Passed",eS[eS.Rejected=3]="Rejected",eS[eS.Cancelled=4]="Cancelled",eS[eS.ToStart=5]="ToStart",eS[eS.Paused=6]="Paused",eS[eS.Processing=7]="Processing",eS[eS.Completed=8]="Completed",eS[eS.Max=10]="Max",eS);let lU=["0","1","2"],lq=[lj.Video,lj.Live,lj.All].map(String),lV=[lN.CpaDauV2,lN.CpmFeedVv,lN.Fix,lN.CpaDauV2MultiOs,lN.CpsMicroGame2022,lN.CpaDauV2AndCps,lN.CpaDauV2AndCpsMicroGame2022,lN.CpsV3].map(String),lH=["mpId","mpName","mpCategory","taskId","taskName","taskType","factionId","factionName","contentType","bidType","effectiveTime","dayCnt","metrics","extraIncentive","dataUpdateTime","readyDate","readyTs"],lz=["1","2"],lG=["1","2"];var lW=((eT={})[eT.Video=1]="Video",eT[eT.Live=2]="Live",eT[eT.All=100]="All",eT),lJ=((eI={})[eI.TotalConsumptionAmount=1]="TotalConsumptionAmount",eI[eI.TotalRevenueAmount=2]="TotalRevenueAmount",eI[eI.NewActivationCount=3]="NewActivationCount",eI[eI.ComponentClickCount=4]="ComponentClickCount",eI);let lY=["date","mediaType","totalConsumptionAmount","totalRevenueAmount","newActivationCount","firstActiveCount","componentExposureCount","componentClickCount","componentClickThroughRate","conversionBillingConsumptionAmount","revenueBillingConsumptionAmount","revenueUserCount","iaaRevenueAmount","iapRevenueAmount"],lK=rv(lJ),lX=["taskId","taskName","taskType","taskCategory","taskStatus","webStatus","mediaType","startTime","endTime","createTime","realEndTime","budget","prepaidFreezeAmount","securityBudget","totalExpectedNum","expense","totalIncome","cpaExpense","cpsExpense","adIncomeSettle","orderIncomeSettle","newRegisterCnt","videoPost","liveRoomCnt","dataProductionDate","bidCollections"],lQ=["date","taskId","taskType","expense","totalIncome","cpaExpense","cpsExpense","adIncomeSettle","adIncomeLongTail","orderIncomeSettle","orderIncomeLongTail","newRegisterCnt","videoPost","videoPostUcnt","videoPlaySettle","videoPlayLongTail","liveRoomCnt","liveRoomUcnt","liveViewCnt","liveViewUcnt","frozenAmount","breakdownAmount","yesterdayDataReady"],lZ=[lM.Pending,lM.Passed,lM.Rejected,lM.Cancelled,lM.ToStart,lM.Paused,lM.Processing,lM.Completed].map(String);var l1=((eO={})[eO.Banner=1]="Banner",eO[eO.RewardedVideo=2]="RewardedVideo",eO[eO.Interstitial=3]="Interstitial",eO[eO.ECommerce=4]="ECommerce",eO),l2=((ek={})[ek.All=1]="All",ek[ek.Douyin=2]="Douyin",ek[ek.DouyinLite=3]="DouyinLite",ek[ek.Toutiao=4]="Toutiao",ek[ek.ToutiaoLite=5]="ToutiaoLite",ek[ek.Fanqie=6]="Fanqie",ek[ek.FanqieChangTing=7]="FanqieChangTing",ek[ek.Hotsoon=8]="Hotsoon",ek[ek.Ppx=9]="Ppx",ek),l0=((eR={})[eR.All=1]="All",eR[eR.Android=2]="Android",eR[eR.IOS=3]="IOS",eR[eR.OpenHarmony=4]="OpenHarmony",eR[eR.Windows=5]="Windows",eR),l3=((eP={})[eP.Ad=1]="Ad",eP[eP.Star=2]="Star",eP[eP.Publisher=3]="Publisher",eP[eP.Natural=4]="Natural",eP),l6=((eL={})[eL.Banner=1]="Banner",eL[eL.RewardedVideo=2]="RewardedVideo",eL[eL.Interstitial=3]="Interstitial",eL[eL.ECommerce=4]="ECommerce",eL),l4=((eN={})[eN.All=1]="All",eN[eN.Douyin=2]="Douyin",eN[eN.DouyinLite=3]="DouyinLite",eN[eN.Toutiao=4]="Toutiao",eN[eN.ToutiaoLite=5]="ToutiaoLite",eN[eN.Fanqie=6]="Fanqie",eN[eN.FanqieChangTing=7]="FanqieChangTing",eN[eN.Hotsoon=8]="Hotsoon",eN[eN.Ppx=9]="Ppx",eN),l8=((ej={})[ej.All=1]="All",ej[ej.Android=2]="Android",ej[ej.IOS=3]="IOS",ej[ej.OpenHarmony=4]="OpenHarmony",ej[ej.Windows=5]="Windows",ej),l9=((e$={})[e$.Ad=1]="Ad",e$[e$.Star=2]="Star",e$[e$.Publisher=3]="Publisher",e$[e$.Natural=4]="Natural",e$);let l7=["recordType","date","requestCount","showCount","clickCount","clickRate","ecpm","incomeAfterShare","incomeBeforeShare"],l5=["date","ritId","ritName","hostName","requestCount","showCount","clickCount","clickRate","ecpm","incomeAfterShare","incomeBeforeShare"];var ce=((eM={})[eM.AD=1]="AD",eM[eM.Star=2]="Star",eM[eM.Pop=3]="Pop",eM[eM.Nature=4]="Nature",eM),ct=((eU={})[eU.Microgame=1]="Microgame",eU[eU.App=2]="App",eU),cr=((eq={})[eq.Cash=1]="Cash",eq[eq.CommonGood=2]="CommonGood",eq),ci=((eV={})[eV.CNY=1]="CNY",eV[eV.Diamond=2]="Diamond",eV),cn=((eH={})[eH.AD=1]="AD",eH[eH.Star=2]="Star",eH[eH.Pop=3]="Pop",eH[eH.Nature=4]="Nature",eH),cu=((ez={})[ez.Microgame=1]="Microgame",ez[ez.App=2]="App",ez);let co=["ios","android","open_harmony","windows"],cs=["recordType","date","payPerson","payTimes","arppu","payMoney","payMoneyAfterShare","payMoneyAfterReduceShare","refundFee","refundFeeBeforeShare","refundFeeAfterShare","payMoneyAfterShareDataReady","payMoneyAfterReduceShareDataReady"],ca=["payTime","transactionNo","merchantNo","openId","payStatus","changeType","goodType","orderType","activateType","amount","rechargeAmount","isOpenPlatformRefund","refundFee","refundFeeBeforeShare","refundFeeAfterShare","refundRemark"],cl=[10,11];function cc(e,t){let r=new Date,i=[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-");return e<=i&&i<=t}async function cd(e){let t,r,i,n=await (t={X_Tt_Appid:e},r=n1.genBaseURL("/platform_openapi/microgame/v1/payment/query_permission"),i={X_Tt_Appid:t.X_Tt_Appid,X_Tt_Userid:t.X_Tt_Userid},n1.request({url:r,method:"GET",headers:i},void 0));return eK(n),{...n,data:n.data?{...n.data,callbackToken:n.data.callbackToken?"[REDACTED]":void 0}:void 0}}async function cp(e){return Promise.all(cl.map(async t=>{var r;let i,n,u,o=await (r={X_Tt_Appid:e,scene:t},i=n1.genBaseURL("/platform_openapi/microgame/v1/payment/query_protocol_sign_status"),n={scene:r.scene},u={X_Tt_Appid:r.X_Tt_Appid},n1.request({url:i,method:"GET",params:n,headers:u},void 0));return eK(o),{response:o,scene:t}}))}function ch(e){return e.requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD,不能晚于今天").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD,不能晚于今天").option("--host <aid>","宿主 AID,-1 表示全部;支持 -1 / 1128 抖音 / 2329 抖音极速版 / 13 今日头条 / 35 头条极速版 / 1967 番茄小说 / 3040 番茄畅听 / 8663 抖音火山","-1").option("--os <os>","操作系统:ios / android / windows / open_harmony").option("--activate-type <n>","归因类型:1 广告 / 2 星图 / 3 发行人 / 4 自然").option("--from-app-platform <n>","经营端:1 小游戏 / 2 App")}let cf=new Set(["auth","check-update","skills","update"]);async function cm(e){await nj(e).catch(()=>void 0)}function cg(){process.exit(130)}async function cA(e){var t,r,i,n,u,o,s,a;let c,d,p,h,f,m,g,A,y;na=new e0({middlewares:[tu,...tn,to,function(e){let{getCaller:t,headerName:r="X-Tt-Cli-Caller"}=e;return async(e,i)=>{let n=t();"string"==typeof n&&n.trim()&&(e.request.headers??={},e.request.headers[r]=n.trim()),await i()}}({getCaller:()=>ti()?.caller}),function(e={}){let{getToken:t,missingTokenErrorFactory:r,headerName:i="Authorization",headerValueBuilder:n=e=>`Bearer ${e}`}=e;return async(e,u)=>{if(!t)return void await u();let o=await t();if(!o){if(r)throw r();await u();return}e.request.headers??={},e.request.headers[i]=n(o),await u()}}({getToken:nt,missingTokenErrorFactory:()=>new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前命令需要先登录,请先执行 ${e9}`})})]}),nl=new e0({middlewares:[tu,...tn]});let E=e.slice(2),_=Date.now(),b=(((t=c=new M).addOption(new L("--caller <agent>","调用方 Agent").choices(nv).default("unknown")),t).name("dymg").description("抖音小游戏 CLI").version("0.6.1").configureHelp({showGlobalOptions:!0}).showHelpAfterError("(可使用 --help 查看命令说明)").showSuggestionAfterError(!0).addHelpText("after",`
|
|
130
|
+
$ dymg growth metric-query --app-id <app-id> --activate-start-date 2026-06-01 --activate-end-date 2026-06-07 --dimension 1 --metric 11,21 --life-time 11:7,14,30 --life-time 21:7,14,30 --first-channel 1,2,3,4 --freshness-type 2`;function ls(e,t=[]){return[...t,e]}function la(e){return e===a9.RealTime?"1,2":"1,3,7"}var ll=((em={})[em.HotGame=1]="HotGame",em[em.BestSeller=2]="BestSeller",em[em.NewGame=3]="NewGame",em[em.Pop=4]="Pop",em),lc=((eg={})[eg.IAA=1]="IAA",eg[eg.IAP=2]="IAP",eg[eg.IAAP=3]="IAAP",eg);let ld=["elementId","elementName","elementType","hotValue","dataStatus","hotspotId","videoId","elementTags","description","heatTrend"],lp=["title","hotValue","topics","hotInsights","jumpUrl","contentId","coverUrl","playUrl","contentTags","gamificationCategories","gamificationMechanics","genderDistribution","ageDistribution","commentSummary","topComments","dataStatus"],lh=["topicId","topicName","parentTopicId","parentTopicName","dataStatus","topicOverview","marketOpportunitySummary","gamificationCategories","gamificationMechanics","genderDistribution","ageDistribution","audiencePreferences","contentPreferences","interactionPreferences","relatedGames","recentHotspots","topVideos","trend7D","trend30D","trend90D"],lf=["all","image","topic","interaction"],lm=[{id:"30000",name:"生存"},{id:"30001",name:"动作"},{id:"30002",name:"割草"},{id:"30003",name:"冒险"},{id:"30004",name:"放置挂机"},{id:"30005",name:"MMO"},{id:"30006",name:"修仙"},{id:"30100",name:"找茬"},{id:"30101",name:"解谜"},{id:"30102",name:"寻物"},{id:"30103",name:"消除"},{id:"30104",name:"合成"},{id:"30105",name:"换装"},{id:"30106",name:"派对游戏"},{id:"30107",name:"大乱斗"},{id:"30108",name:"答题"},{id:"30109",name:"超休闲"},{id:"30200",name:"射击"},{id:"30201",name:"格斗"},{id:"30202",name:"竞速"},{id:"30203",name:"节奏"},{id:"30204",name:"跑酷"},{id:"30205",name:"飞行射击"},{id:"30206",name:"体育竞技"},{id:"30207",name:"MOBA"},{id:"30300",name:"模拟养成"},{id:"30301",name:"模拟经营"},{id:"30302",name:"模拟器"},{id:"30303",name:"收纳整理"},{id:"30304",name:"沙盒建造"},{id:"30400",name:"塔防"},{id:"30401",name:"即时战斗"},{id:"30402",name:"回合战斗"},{id:"30403",name:"自走棋"},{id:"30404",name:"SLG"},{id:"30500",name:"五子棋"},{id:"30501",name:"军旗"},{id:"30502",name:"围棋"},{id:"30503",name:"象棋"},{id:"30504",name:"麻将"},{id:"30505",name:"扑克牌"},{id:"30506",name:"经典桌游"},{id:"30507",name:"聚会游戏"},{id:"30508",name:"其他棋牌"}].map(e=>e.id);function lg(e,t=String){return e?.map(t).join("|")}var lA=((eA={})[eA.All=1]="All",eA[eA.Douyin=2]="Douyin",eA[eA.DouyinLite=3]="DouyinLite",eA[eA.Toutiao=4]="Toutiao",eA[eA.ToutiaoLite=5]="ToutiaoLite",eA[eA.Fanqie=6]="Fanqie",eA[eA.FanqieChangTing=7]="FanqieChangTing",eA[eA.Hotsoon=8]="Hotsoon",eA[eA.Ppx=9]="Ppx",eA),ly=((ey={})[ey.Debug=1]="Debug",ey[ey.Info=2]="Info",ey[ey.Warn=3]="Warn",ey[ey.Error=4]="Error",ey[ey.Fatal=5]="Fatal",ey),lE=((eE={})[eE.All=1]="All",eE[eE.Android=2]="Android",eE[eE.IOS=3]="IOS",eE[eE.OpenHarmony=4]="OpenHarmony",eE[eE.Windows=5]="Windows",eE),l_=((e_={})[e_.All=1]="All",e_[e_.High=2]="High",e_[e_.Mid=3]="Mid",e_[e_.Low=4]="Low",e_),lb=((eb={})[eb.All=1]="All",eb[eb.Android=2]="Android",eb[eb.IOS=3]="IOS",eb[eb.OpenHarmony=4]="OpenHarmony",eb[eb.Windows=5]="Windows",eb),lv=((ev={})[ev.All=1]="All",ev[ev.Android=2]="Android",ev[ev.IOS=3]="IOS",ev[ev.OpenHarmony=4]="OpenHarmony",ev[ev.Windows=5]="Windows",ev),lC=((eC={})[eC.LaunchCostMs=1001]="LaunchCostMs",eC[eC.LaunchRetentionRate=1002]="LaunchRetentionRate",eC[eC.WasmCompileCostMs=1003]="WasmCompileCostMs",eC[eC.CallMainCostMs=1004]="CallMainCostMs",eC[eC.LaunchFPCostMs=1005]="LaunchFPCostMs",eC[eC.LaunchTTICostMs=1006]="LaunchTTICostMs",eC[eC.ResourcePrepareCostMs=1007]="ResourcePrepareCostMs",eC[eC.CodeInjectCostMs=1008]="CodeInjectCostMs",eC[eC.WasmSplitBeforeFPRate=1011]="WasmSplitBeforeFPRate",eC[eC.WasmSplitBeforeFPCostMs=1012]="WasmSplitBeforeFPCostMs",eC[eC.WasmSplitBeforeTTIRate=1013]="WasmSplitBeforeTTIRate",eC[eC.WasmSplitBeforeTTICostMs=1014]="WasmSplitBeforeTTICostMs",eC[eC.FPS=2001]="FPS",eC[eC.StutterRate=2002]="StutterRate",eC[eC.RenderDrawCall=2003]="RenderDrawCall",eC[eC.RenderTriangle=2004]="RenderTriangle",eC[eC.RenderVertex=2005]="RenderVertex",eC[eC.AvgMemoryMB=2011]="AvgMemoryMB",eC[eC.MemoryUsageRate=2012]="MemoryUsageRate",eC[eC.MemoryPeakMB=2013]="MemoryPeakMB",eC[eC.MemoryAbnormalExitRate=2014]="MemoryAbnormalExitRate",eC[eC.CPUUsageRate=2021]="CPUUsageRate",eC[eC.GPUUsageRate=2022]="GPUUsageRate",eC[eC.RequestCostMs=3001]="RequestCostMs",eC[eC.RequestErrorRate=3002]="RequestErrorRate",eC[eC.DownloadFileCostMs=3003]="DownloadFileCostMs",eC[eC.DownloadFileErrorRate=3004]="DownloadFileErrorRate",eC),lD=((eD={})[eD.All=1]="All",eD[eD.Required=2]="Required",eD[eD.NotRequired=3]="NotRequired",eD),lF=((eF={})[eF.Trend=1]="Trend",eF[eF.SceneConversion=2]="SceneConversion",eF[eF.LaunchDurationDistribution=3]="LaunchDurationDistribution",eF[eF.LaunchLossDistribution=4]="LaunchLossDistribution",eF[eF.WasmSplit=5]="WasmSplit",eF);let lw={[lA.Douyin]:"1128",[lA.DouyinLite]:"2329",[lA.Toutiao]:"13",[lA.ToutiaoLite]:"35",[lA.Fanqie]:"1967",[lA.FanqieChangTing]:"3040",[lA.Hotsoon]:"8663"},lB=Object.keys(lw),lx=Object.values(lw),lS=[lv.Android,lv.IOS,lv.OpenHarmony].map(String),lT=["group","genreName","engine","degradedIndicatorCount","section","indicatorName","metric","os","actualValue","standardValue","delta","unit","suggestion"],lI=["metric","metricName","name","sceneId","aggregation","direction","unit","date","value","sampleCount"],lO=["appId","host","os","appVersion","gameVersion","jssdkVersion","versionType","openId","traceId","logLevel","timestamp","msg"];function lk(e,t,r){return(e??[]).map(e=>({...t,section:r,indicatorName:e.indicatorName,metric:e.metric,os:e.os,actualValue:e.actualValue,standardValue:e.standardValue,delta:e.delta,unit:e.unit,suggestion:e.suggestion}))}function lR(e){return(e??[]).flatMap(e=>(e.points??[]).map(t=>({metric:e.metric,metricName:rD(lC,e.metric),name:e.name,sceneId:e.sceneId,aggregation:e.aggregation,direction:e.direction,unit:e.unit,date:t.date,value:t.value,sampleCount:t.sampleCount})))}function lP(e){rd({startDate:e.startDate,endDate:e.endDate,maxLookbackDays:ov,label:"性能数据"}),rn(e.host,"--host",lB),rn(e.os,"--os",lS),rn(e.deviceLevel,"--device-level",rv(l_)),ru(e.metrics,"--metrics",rv(lC))}function lL(e){return{startDate:e.startDate,endDate:e.endDate,hostAid:lw[rC(e.host,lA)]??"",os:rC(e.os,lv),mpVersion:e.mpVersion,deviceLevel:rC(e.deviceLevel,l_)}}var lN=((ew={})[ew.Invalid=0]="Invalid",ew[ew.CpaDauV2=1]="CpaDauV2",ew[ew.CpaDauV3=2]="CpaDauV3",ew[ew.CpaReservation=3]="CpaReservation",ew[ew.CpaActivate=4]="CpaActivate",ew[ew.CpaAndroidDownload=5]="CpaAndroidDownload",ew[ew.CpmFeedVv=6]="CpmFeedVv",ew[ew.Cps=7]="Cps",ew[ew.Fix=8]="Fix",ew[ew.CpsV2=9]="CpsV2",ew[ew.Revenues=10]="Revenues",ew[ew.AuthorPurchase=11]="AuthorPurchase",ew[ew.CpsRevenues=12]="CpsRevenues",ew[ew.CpaReserveAndDownload=13]="CpaReserveAndDownload",ew[ew.CpaMultiReserve=14]="CpaMultiReserve",ew[ew.CpmUvAll=15]="CpmUvAll",ew[ew.Ocpm=16]="Ocpm",ew[ew.OcpmUvAll=17]="OcpmUvAll",ew[ew.CpmFeedVvMultiOs=18]="CpmFeedVvMultiOs",ew[ew.CpmUvAllMultiOs=19]="CpmUvAllMultiOs",ew[ew.CpaActivateMultiOs=20]="CpaActivateMultiOs",ew[ew.CpaReserveAndDownloadMultiOs=21]="CpaReserveAndDownloadMultiOs",ew[ew.CpaDauV2MultiOs=22]="CpaDauV2MultiOs",ew[ew.CpaDauV3MultiOs=23]="CpaDauV3MultiOs",ew[ew.CpaUnionAndroidDownload=24]="CpaUnionAndroidDownload",ew[ew.CpaMixedActivate=25]="CpaMixedActivate",ew[ew.CpsLongPeriod=26]="CpsLongPeriod",ew[ew.CpsMicroGame2022=27]="CpsMicroGame2022",ew[ew.CpaDauV2AndCps=28]="CpaDauV2AndCps",ew[ew.CpaDauV2AndCpsMicroGame2022=29]="CpaDauV2AndCpsMicroGame2022",ew[ew.CpsV3=30]="CpsV3",ew[ew.MaxSize=31]="MaxSize",ew),lj=((eB={})[eB.Video=1]="Video",eB[eB.Live=2]="Live",eB[eB.All=100]="All",eB),l$=((ex={})[ex.MicroGame=0]="MicroGame",ex[ex.MicroTerminal=1]="MicroTerminal",ex[ex.All=100]="All",ex),lM=((eS={})[eS.Min=0]="Min",eS[eS.Pending=1]="Pending",eS[eS.Passed=2]="Passed",eS[eS.Rejected=3]="Rejected",eS[eS.Cancelled=4]="Cancelled",eS[eS.ToStart=5]="ToStart",eS[eS.Paused=6]="Paused",eS[eS.Processing=7]="Processing",eS[eS.Completed=8]="Completed",eS[eS.Max=10]="Max",eS);let lU=["0","1","2"],lq=[lj.Video,lj.Live,lj.All].map(String),lV=[lN.CpaDauV2,lN.CpmFeedVv,lN.Fix,lN.CpaDauV2MultiOs,lN.CpsMicroGame2022,lN.CpaDauV2AndCps,lN.CpaDauV2AndCpsMicroGame2022,lN.CpsV3].map(String),lH=["mpId","mpName","mpCategory","taskId","taskName","taskType","factionId","factionName","contentType","bidType","effectiveTime","dayCnt","metrics","extraIncentive","dataUpdateTime","readyDate","readyTs"],lz=["1","2"],lG=["1","2"];var lW=((eT={})[eT.Video=1]="Video",eT[eT.Live=2]="Live",eT[eT.All=100]="All",eT),lJ=((eI={})[eI.TotalConsumptionAmount=1]="TotalConsumptionAmount",eI[eI.TotalRevenueAmount=2]="TotalRevenueAmount",eI[eI.NewActivationCount=3]="NewActivationCount",eI[eI.ComponentClickCount=4]="ComponentClickCount",eI);let lY=["date","mediaType","totalConsumptionAmount","totalRevenueAmount","newActivationCount","firstActiveCount","componentExposureCount","componentClickCount","componentClickThroughRate","conversionBillingConsumptionAmount","revenueBillingConsumptionAmount","revenueUserCount","iaaRevenueAmount","iapRevenueAmount"],lK=rv(lJ),lX=["taskId","taskName","taskType","taskCategory","taskStatus","webStatus","mediaType","startTime","endTime","createTime","realEndTime","budget","prepaidFreezeAmount","securityBudget","totalExpectedNum","expense","totalIncome","cpaExpense","cpsExpense","adIncomeSettle","orderIncomeSettle","newRegisterCnt","videoPost","liveRoomCnt","dataProductionDate","bidCollections"],lQ=["date","taskId","taskType","expense","totalIncome","cpaExpense","cpsExpense","adIncomeSettle","adIncomeLongTail","orderIncomeSettle","orderIncomeLongTail","newRegisterCnt","videoPost","videoPostUcnt","videoPlaySettle","videoPlayLongTail","liveRoomCnt","liveRoomUcnt","liveViewCnt","liveViewUcnt","frozenAmount","breakdownAmount","yesterdayDataReady"],lZ=[lM.Pending,lM.Passed,lM.Rejected,lM.Cancelled,lM.ToStart,lM.Paused,lM.Processing,lM.Completed].map(String);var l1=((eO={})[eO.Banner=1]="Banner",eO[eO.RewardedVideo=2]="RewardedVideo",eO[eO.Interstitial=3]="Interstitial",eO[eO.ECommerce=4]="ECommerce",eO),l0=((ek={})[ek.All=1]="All",ek[ek.Douyin=2]="Douyin",ek[ek.DouyinLite=3]="DouyinLite",ek[ek.Toutiao=4]="Toutiao",ek[ek.ToutiaoLite=5]="ToutiaoLite",ek[ek.Fanqie=6]="Fanqie",ek[ek.FanqieChangTing=7]="FanqieChangTing",ek[ek.Hotsoon=8]="Hotsoon",ek[ek.Ppx=9]="Ppx",ek),l2=((eR={})[eR.All=1]="All",eR[eR.Android=2]="Android",eR[eR.IOS=3]="IOS",eR[eR.OpenHarmony=4]="OpenHarmony",eR[eR.Windows=5]="Windows",eR),l3=((eP={})[eP.Ad=1]="Ad",eP[eP.Star=2]="Star",eP[eP.Publisher=3]="Publisher",eP[eP.Natural=4]="Natural",eP),l6=((eL={})[eL.Banner=1]="Banner",eL[eL.RewardedVideo=2]="RewardedVideo",eL[eL.Interstitial=3]="Interstitial",eL[eL.ECommerce=4]="ECommerce",eL),l4=((eN={})[eN.All=1]="All",eN[eN.Douyin=2]="Douyin",eN[eN.DouyinLite=3]="DouyinLite",eN[eN.Toutiao=4]="Toutiao",eN[eN.ToutiaoLite=5]="ToutiaoLite",eN[eN.Fanqie=6]="Fanqie",eN[eN.FanqieChangTing=7]="FanqieChangTing",eN[eN.Hotsoon=8]="Hotsoon",eN[eN.Ppx=9]="Ppx",eN),l8=((ej={})[ej.All=1]="All",ej[ej.Android=2]="Android",ej[ej.IOS=3]="IOS",ej[ej.OpenHarmony=4]="OpenHarmony",ej[ej.Windows=5]="Windows",ej),l9=((e$={})[e$.Ad=1]="Ad",e$[e$.Star=2]="Star",e$[e$.Publisher=3]="Publisher",e$[e$.Natural=4]="Natural",e$);let l7=["recordType","date","requestCount","showCount","clickCount","clickRate","ecpm","incomeAfterShare","incomeBeforeShare"],l5=["date","ritId","ritName","hostName","requestCount","showCount","clickCount","clickRate","ecpm","incomeAfterShare","incomeBeforeShare"];var ce=((eM={})[eM.AD=1]="AD",eM[eM.Star=2]="Star",eM[eM.Pop=3]="Pop",eM[eM.Nature=4]="Nature",eM),ct=((eU={})[eU.Microgame=1]="Microgame",eU[eU.App=2]="App",eU),cr=((eq={})[eq.Cash=1]="Cash",eq[eq.CommonGood=2]="CommonGood",eq),ci=((eV={})[eV.CNY=1]="CNY",eV[eV.Diamond=2]="Diamond",eV),cn=((eH={})[eH.AD=1]="AD",eH[eH.Star=2]="Star",eH[eH.Pop=3]="Pop",eH[eH.Nature=4]="Nature",eH),cu=((ez={})[ez.Microgame=1]="Microgame",ez[ez.App=2]="App",ez);let co=["ios","android","open_harmony","windows"],cs=["recordType","date","payPerson","payTimes","arppu","payMoney","payMoneyAfterShare","payMoneyAfterReduceShare","refundFee","refundFeeBeforeShare","refundFeeAfterShare","payMoneyAfterShareDataReady","payMoneyAfterReduceShareDataReady"],ca=["payTime","transactionNo","merchantNo","openId","payStatus","changeType","goodType","orderType","activateType","amount","rechargeAmount","isOpenPlatformRefund","refundFee","refundFeeBeforeShare","refundFeeAfterShare","refundRemark"],cl=[10,11];function cc(e,t){let r=new Date,i=[r.getFullYear(),String(r.getMonth()+1).padStart(2,"0"),String(r.getDate()).padStart(2,"0")].join("-");return e<=i&&i<=t}async function cd(e){let t,r,i,n=await (t={X_Tt_Appid:e},r=n1.genBaseURL("/platform_openapi/microgame/v1/payment/query_permission"),i={X_Tt_Appid:t.X_Tt_Appid,X_Tt_Userid:t.X_Tt_Userid},n1.request({url:r,method:"GET",headers:i},void 0));return eK(n),{...n,data:n.data?{...n.data,callbackToken:n.data.callbackToken?"[REDACTED]":void 0}:void 0}}async function cp(e){return Promise.all(cl.map(async t=>{var r;let i,n,u,o=await (r={X_Tt_Appid:e,scene:t},i=n1.genBaseURL("/platform_openapi/microgame/v1/payment/query_protocol_sign_status"),n={scene:r.scene},u={X_Tt_Appid:r.X_Tt_Appid},n1.request({url:i,method:"GET",params:n,headers:u},void 0));return eK(o),{response:o,scene:t}}))}function ch(e){return e.requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD,不能晚于今天").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD,不能晚于今天").option("--host <aid>","宿主 AID,-1 表示全部;支持 -1 / 1128 抖音 / 2329 抖音极速版 / 13 今日头条 / 35 头条极速版 / 1967 番茄小说 / 3040 番茄畅听 / 8663 抖音火山","-1").option("--os <os>","操作系统:ios / android / windows / open_harmony").option("--activate-type <n>","归因类型:1 广告 / 2 星图 / 3 发行人 / 4 自然").option("--from-app-platform <n>","经营端:1 小游戏 / 2 App")}let cf=new Set(["auth","check-update","skills","update"]);async function cm(e){await nj(e).catch(()=>void 0)}function cg(){process.exit(130)}async function cA(e){var t,r,i,n,u,o,s,a;let c,d,p,h,f,m,g,A,y;na=new e2({middlewares:[tu,...tn,to,function(e){let{getCaller:t,headerName:r="X-Tt-Cli-Caller"}=e;return async(e,i)=>{let n=t();"string"==typeof n&&n.trim()&&(e.request.headers??={},e.request.headers[r]=n.trim()),await i()}}({getCaller:()=>ti()?.caller}),function(e={}){let{getToken:t,missingTokenErrorFactory:r,headerName:i="Authorization",headerValueBuilder:n=e=>`Bearer ${e}`}=e;return async(e,u)=>{if(!t)return void await u();let o=await t();if(!o){if(r)throw r();await u();return}e.request.headers??={},e.request.headers[i]=n(o),await u()}}({getToken:nt,missingTokenErrorFactory:()=>new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前命令需要先登录,请先执行 ${e9}`})})]}),nl=new e2({middlewares:[tu,...tn]});let E=e.slice(2),_=Date.now(),b=(((t=c=new M).addOption(new L("--caller <agent>","调用方 Agent").choices(nv).default("unknown")),t).name("dymg").description("抖音小游戏 CLI").version("0.7.0").configureHelp({showGlobalOptions:!0}).showHelpAfterError("(可使用 --help 查看命令说明)").showSuggestionAfterError(!0).addHelpText("after",`
|
|
131
131
|
结果输出约定:
|
|
132
132
|
- 业务数据默认不直接打印到终端
|
|
133
133
|
- 数据查询生成 data.csv / raw_response.json / summary.json;非数据查询不生成 data.csv
|
|
@@ -153,5 +153,5 @@ ${t}`,uE=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),u_=Objec
|
|
|
153
153
|
- ${e7}
|
|
154
154
|
- ${e7} --json --open-browser
|
|
155
155
|
- ${e5}
|
|
156
|
-
- ${e5} --open-browser`).action(oM),d.command("status").description("查看当前登录状态").option("--json","以 JSON 输出登录状态").action(oV),d.command("logout").description("退出当前登录").action(oH),d.command("check-dir-writable").description("用于 Agent 测试执行环境中的当前登录态目录是否可写,并输出结构化结果").addHelpText("after","\n示例:\n $ dymg auth check-dir-writable").action(oz),nS(r.command("game").description("游戏基础信息").command("game-list").description("查询有权限的游戏列表,包括 App ID、游戏名称").option("--page-index <n>","页码,从 1 开始","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("game:game-list",r,async()=>{var e;let t,i,n;ra(r.pageIndex,"--page-index",1,1e4),ra(r.pageSize,"--page-size",1,100);let u={pageIndex:rA(r.pageIndex,1),pageSize:rA(r.pageSize,20)},o=await (e=u,t=n1.genBaseURL("/platform_openapi/microgame/v1/game/query_game_list"),i={pageIndex:e.pageIndex,pageSize:e.pageSize},n={X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),s=eK(o),a=(s?.list??[]).map(e=>({appId:e.appId,appName:e.appName}));return{rawResponse:o,rows:a,csvHeader:["appId","appName"],resultMeta:iy({returnedCount:a.length,total:s?.total,page:u.pageIndex,pageSize:u.pageSize})}})}),p=r.command("insight").description("资讯与榜单"),nS(p.command("ranking-list").description("查询小游戏排行榜:榜单 Top N、排名、变化趋势、品类、标签等").requiredOption("--rank-type <n>","榜单类型:1 热门 / 2 畅销 / 3 新游 / 4 发行人热度榜").option("--game-business-list <list>","变现类型列表,逗号分隔:1 IAA / 2 IAP / 3 IAAP").option("--game-type-list <list>","游戏类型/分类标签 ID 列表,逗号分隔").option("--only-my-game","是否只查询当前账号有权限的游戏",!1).option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("insight:ranking-list",r,async()=>{var e;let t,i,n;rn(r.rankType,"--rank-type",rv(ll)),ru(r.gameBusinessList,"--game-business-list",rv(lc)),ru(r.gameTypeList,"--game-type-list",lm),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,200);let u=rA(r.page,1),o=rA(r.pageSize,20),s=u*o;if(s>200)throw new l("榜单仅支持查询前 200 名",{error:"OUT_OF_RANK_LIMIT",message:`榜单仅支持前 200 名,当前页末位排名 ${s} 已超出范围`});let a=await (e={gameBusinessList:rm(r.gameBusinessList),gameTypeList:rf(r.gameTypeList),onlyMyGame:r.onlyMyGame,rankType:rA(r.rankType,0),page:String(u),pageSize:String(o),meta:await nT("insight:ranking-list")},t=n1.genBaseURL("/platform_openapi/microgame/v1/insight/query_game_rank"),i={gameBusinessList:e.gameBusinessList,gameTypeList:e.gameTypeList,meta:e.meta,onlyMyGame:e.onlyMyGame,page:e.page,pageSize:e.pageSize,rankType:e.rankType},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),c=eK(a),d=(c?.items??[]).map(e=>({index:e.index,name:e.name,category:e.category,rankingChange:e.rankingChange}));return{rawResponse:a,rows:d,csvHeader:["index","name","category","rankingChange"],resultMeta:iy({returnedCount:d.length,total:c?.page?.total,page:c?.page?.page,pageSize:c?.page?.pageSize,hasMore:c?.page?.hasMore,nextCursor:c?.page?.nextSearchAfter})}})}),nS(p.command("hotspot-list").description("查询适合游戏化的热点信息,包括热点词、关联视频链接、热度值、热点洞察等").option("--game-type-ids <list>","游戏类型/分类标签 ID 列表,逗号分隔").option("--keyword <keyword>","关键词筛选").option("--top-n <n>","返回条数").option("--topic-ids <list>","题材 ID 列表,逗号分隔")).action(async(e,t)=>{let r=nx(t,e);await oc("insight:hotspot-list",r,async()=>{var e;let t,i,n,u;ru(r.gameTypeIds,"--game-type-ids",lm);let o=(e=r,!!(e.keyword?.trim()||rf(e.gameTypeIds)?.length||rf(e.topicIds)?.length));ra(r.topN,"--top-n",1,o?50:100);let s=r.topN??(o?String(50):void 0),a=await (t={gameTypeIds:rf(r.gameTypeIds),keyword:r.keyword?.trim()||void 0,meta:await nT("insight:hotspot-list"),topN:s,topicIds:rf(r.topicIds)},i=n1.genBaseURL("/platform_openapi/microgame/v1/insight/query_douyin_hotspots"),n={gameTypeIds:t.gameTypeIds,keyword:t.keyword,meta:t.meta,topN:t.topN,topicIds:t.topicIds},u={X_Tt_Appid:t.X_Tt_Appid,X_Tt_Userid:t.X_Tt_Userid},n1.request({url:i,method:"POST",data:n,headers:u},void 0)),l=eK(a);return{rawResponse:a,rows:(l?.items??[]).map(e=>({title:e.title,hotValue:e.hotValue,topics:lg(e.topics),hotInsights:e.hotInsights,jumpUrl:e.jumpUrl,contentId:e.contentId,coverUrl:e.coverUrl,playUrl:e.playUrl,contentTags:lg(e.contentTags),gamificationCategories:lg(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:lg(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:lg(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:lg(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),commentSummary:e.commentSummary,topComments:lg(e.topComments,e=>`${e.content??""}:${e.likeCount??""}`),dataStatus:e.dataStatus})),csvHeader:lp}})}),nS(p.command("element-list").description("查询热门元素,包括元素名称、标签、热度、关联热点和视频信息").option("--element-type <type>","元素类型筛选").option("--hotspot-id <id>","热点 ID").option("--keyword <keyword>","关键词筛选").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20").option("--video-id <id>","视频 ID")).action(async(e,t)=>{let r=nx(t,e);await oc("insight:element-list",r,async()=>{let e,t,i;rl(r.hotspotId,"--hotspot-id"),rn(r.elementType,"--element-type",lf),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,50);let n=rA(r.page,1),u=rA(r.pageSize,20),o=await (e={elementType:r.elementType,hotspotId:r.hotspotId,keyword:r.keyword?.trim()||void 0,page:n,pageSize:u,videoId:r.videoId},t=n1.genBaseURL("/platform_openapi/microgame/v1/insight/query_hot_elements"),i={elementType:e.elementType,hotspotId:e.hotspotId,keyword:e.keyword,page:e.page,pageSize:e.pageSize,recommendedUse:e.recommendedUse,suitableGenre:e.suitableGenre,videoId:e.videoId},n1.request({url:t,method:"POST",data:i},void 0)),s=eK(o),a=(s?.items??[]).map(e=>({elementId:e.elementId,elementName:e.elementName,elementType:e.elementType,hotValue:e.hotValue,dataStatus:e.dataStatus,hotspotId:e.hotspotId,videoId:e.videoId,elementTags:lg(e.elementTags),description:e.description,heatTrend:lg(e.heatTrend,e=>`${rb(e.timestamp,{format:"date"})}:${e.hotScore??""}`)}));return{rawResponse:o,rows:a,csvHeader:ld,resultMeta:iy({returnedCount:a.length,total:s?.total,page:s?.page??n,pageSize:s?.pageSize??u,hasMore:s?.hasMore})}})}),nS(p.command("theme-list").description("查询热门题材,包括题材概览、市场机会、关联游戏、近期热点和趋势信息").option("--include-top-videos","是否返回头部视频信息",!1).option("--page <n>","页码","1").option("--page-size <n>","每页条数","20").option("--parent-topic-id <id>","父题材 ID").option("--topic-id-list <list>","题材 ID 列表,逗号分隔")).action(async(e,t)=>{let r=nx(t,e);await oc("insight:theme-list",r,async()=>{let e,t,i;rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,50);let n=rA(r.page,1),u=rA(r.pageSize,20),o=await (e={includeTopVideos:r.includeTopVideos,page:n,pageSize:u,parentTopicId:r.parentTopicId,topicIdList:rf(r.topicIdList)},t=n1.genBaseURL("/platform_openapi/microgame/v1/insight/query_hot_topics"),i={includeTopVideos:e.includeTopVideos,page:e.page,pageSize:e.pageSize,parentTopicId:e.parentTopicId,topicIdList:e.topicIdList},n1.request({url:t,method:"POST",data:i},void 0)),s=eK(o),a=(s?.items??[]).map(e=>({topicId:e.topicId,topicName:e.topicName,parentTopicId:e.parentTopicId,parentTopicName:e.parentTopicName,dataStatus:e.dataStatus,topicOverview:e.topicOverview,marketOpportunitySummary:e.marketOpportunity?.summary,gamificationCategories:lg(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:lg(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:lg(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:lg(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),audiencePreferences:lg(e.userFeatures?.audiencePreferences,e=>`${e.title??""}:${e.insight??""}`),contentPreferences:lg(e.userFeatures?.contentPreferences,e=>`${e.title??""}:${e.insight??""}`),interactionPreferences:lg(e.userFeatures?.interactionPreferences,e=>`${e.title??""}:${e.insight??""}`),relatedGames:function(e){if(e?.length)return F(e.map(e=>({gameId:e.gameId,gameName:e.gameName,iconUrl:e.iconUrl,jumpUrl:e.jumpUrl,heatValue:e.heatValue})))}(e.relatedGames),recentHotspots:lg(e.recentHotspots,e=>`${e.title??""}:${e.heatValue??""}`),topVideos:lg(e.topVideos,e=>`${e.video?.title??""}:${e.likeCount??""}`),trend7D:lg(e.trend7D,e=>`${rb(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend30D:lg(e.trend30D,e=>`${rb(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend90D:lg(e.trend90D,e=>`${rb(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`)}));return{rawResponse:o,rows:a,csvHeader:lh,resultMeta:iy({returnedCount:a.length,total:s?.total,page:n,pageSize:u,hasMore:s?.hasMore})}})}),h=r.command("analytics").description("用户数据"),nS(nI(h.command("behavior-query").description("查询用户的活跃用户、新增用户、累计用户、启动次数、游戏时长等行为指标,支持 App、操作系统等筛选"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:behavior-query",r,async()=>{var e;let t,i,n;oI(r),oO(r);let u=await (e={X_Tt_Appid:r.appId,filter:oD(r),meta:await nT("analytics:behavior-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_user_behavior"),i={filter:e.filter,meta:e.meta},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u),s=(o?.items??[]).map(e=>({...e,recordType:"data"}));return{rawResponse:u,rows:[...s,...o?.summary?[{...o.summary,recordType:"summary"}]:[]],csvHeader:oF}})}),nS(nI(h.command("realtime-query").description("查询游戏当天的实时访问人数和访问次数"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:realtime-query",r,async()=>{var e;let t,i,n;rd({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:oy,label:"实时数据"}),oO(r);let u=await (e={X_Tt_Appid:r.appId,filter:oD(r),meta:await nT("analytics:realtime-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_realtime_user"),i={filter:e.filter,meta:e.meta},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:(o?.items??[]).map(e=>({hour:e.hour,activeUser:e.activeUser,openTime:e.openTime})),csvHeader:ow}})}),nS(nI(h.command("retention-query").description("查询用户的次日、3 日、14 日、30 日留存率,支持筛选日期、App、操作系统、用户类型等").option("--retention-scene <n>","留存场景:1 全量 / 2 侧边栏"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:retention-query",r,async()=>{var e;let t,i,n;oI(r),oO(r),rn(r.retentionScene,"--retention-scene",rv(om));let u=await (e={X_Tt_Appid:r.appId,filter:oD(r),retentionScene:void 0===r.retentionScene?void 0:rA(r.retentionScene,0),meta:await nT("analytics:retention-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_user_retention"),i={filter:e.filter,meta:e.meta,retentionScene:e.retentionScene},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:(o?.items??[]).map(e=>({...e})),csvHeader:oB}})}),nS(nI(h.command("source-query").description("查询不同来源渠道下的活跃用户、新增用户数、启动次数、次均游戏时长等").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:source-query",r,async()=>{var e;let t,i,n;oI(r),oO(r),ra(r.topN,"--top-n",1,100);let u=await (e={X_Tt_Appid:r.appId,filter:oD(r),topN:r.topN,meta:await nT("analytics:source-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_user_source"),i={filter:e.filter,meta:e.meta,topN:e.topN},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:(o?.items??[]).flatMap(e=>{let t=e.dates??[];return(t.length>0?t:[""]).map((t,r)=>({sceneId:e.sceneId,sceneName:e.sceneName,date:t,uv:e.uvData?.[r],newUv:e.newUvData?.[r],openTime:e.openTimeData?.[r],stayPv:e.stayPvData?.[r],avgStayTime:e.avgStayTimeData?.[r],avgStayTimeStr:e.avgStayTimeStrData?.[r],totalUv:e.uv,totalNewUv:e.newUv,totalOpenTime:e.openTime,totalStayPv:e.stayPv,totalAvgStayTime:e.avgStayTime,totalAvgStayTimeStr:e.avgStayTimeStr}))}),csvHeader:ox}})}),nS(nI(h.command("profile-query").description("查询用户的性别、年龄、地域分布,区分不同 App、活跃/新增用户类型"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:profile-query",r,async()=>{var e;let t,i,n;oI(r),oO(r);let u=await (e={X_Tt_Appid:r.appId,filter:oD(r),meta:await nT("analytics:profile-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_user_portrait"),i={filter:e.filter,meta:e.meta},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:[{dimension:"age",items:o?.age},{dimension:"city",items:o?.city},{dimension:"gender",items:o?.gender},{dimension:"province",items:o?.province}].flatMap(({dimension:e,items:t})=>(t??[]).map(t=>({dimension:e,name:t.name,value:t.value,ratio:t.ratio,total:o?.total}))),csvHeader:oS}})}),nS(nI(h.command("device-query").description("查询用户的机型、品牌、客户端版本、基础库版本分布等").requiredOption("--dimension <n>","维度:1 型号 / 2 品牌 / 3 宿主版本 / 4 基础库版本").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:device-query",r,async()=>{var e;let t,i,n;oI(r),oO(r),rn(r.dimension,"--dimension",rv(og)),ra(r.topN,"--top-n",1,100);let u=rA(r.dimension,0),o=await (e={X_Tt_Appid:r.appId,dimension:u,filter:oD(r),topN:r.topN,meta:await nT("analytics:device-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_user_terminal"),i={dimension:e.dimension,filter:e.filter,meta:e.meta,topN:e.topN},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),s=eK(o);return{rawResponse:o,rows:(s?.items??[]).map(e=>({dimension:s?.dimension,name:e.name,value:e.value,ratio:e.ratio,total:s?.total})),csvHeader:oT}})}),nS(r.command("growth").description("增长数据").command("metric-query").description("查询分渠道的新增激活用户数据及其对应的后效指标(变现人数、ECPM、收入、成本等);区分离线与实时口径").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--activate-start-date <date>","激活开始日期 YYYY-MM-DD").requiredOption("--activate-end-date <date>","激活结束日期 YYYY-MM-DD").requiredOption("--dimension <list>","维度枚举,逗号分隔").requiredOption("--metric <list>","指标枚举,逗号分隔").option("--life-time <rule>","生命周期配置,可重复传入;格式为 <指标枚举>:<生命周期天数列表>,例如 11:7,14,30",ls,[]).requiredOption("--first-channel <list>","一级渠道枚举,逗号分隔").requiredOption("--freshness-type <n>","数据时效:1 实时 / 2 离线").option("--second-channel <list>","二级渠道枚举,逗号分隔").option("--download","是否返回下载链接",!1).addHelpText("after",lo)).action(async(e,t)=>{let r=nx(t,e);await oc("growth:metric-query",r,async()=>{let e,t,i;ru(r.dimension,"--dimension",rv(a4)),ru(r.metric,"--metric",rv(a7)),rn(r.freshnessType,"--freshness-type",rv(a9)),ru(r.firstChannel,"--first-channel",rv(a8)),ru(r.secondChannel,"--second-channel",rv(a5));let n=rA(r.freshnessType,0),u=n===a9.RealTime;rd({startDate:r.activateStartDate,endDate:r.activateEndDate,maxLookbackDays:u?oE:o_,label:u?"增长实时数据":"增长离线数据",startField:"--activate-start-date",endField:"--activate-end-date"});let o=rm(r.dimension)??[],s=rm(r.metric)??[],a=rm(r.firstChannel)??[],c=rm(r.secondChannel);if(0===o.length)throw new l("growth:metric-query 缺少有效维度",{error:"INVALID_DIMENSION",message:"--dimension 至少需要传入一个有效的维度枚举值"});if(0===s.length)throw new l("growth:metric-query 缺少有效指标",{error:"INVALID_METRIC",message:"--metric 至少需要传入一个有效的指标枚举值"});if(0===a.length)throw new l("growth:metric-query 缺少有效一级渠道",{error:"INVALID_FIRST_CHANNEL",message:"--first-channel 至少需要传入一个有效的一级渠道枚举值"});let d=function(e,t,r){let i=new Map;if(!e||0===e.length)return i;let n=new Set(t),u=rv(a7),o=la(r),s=r===a9.RealTime?"实时口径":"离线口径";for(let t of e){var a,c;let e=t.split(":");if(2!==e.length)throw new l("growth:metric-query lifeTime 格式非法",{error:"INVALID_LIFE_TIME",message:"--life-time 格式必须为 <指标枚举>:<生命周期天数列表>,例如 --life-time 11:7,14,30"});let[d,p]=e.map(e=>e.trim());if(!u.includes(d))throw new l("growth:metric-query lifeTime 指标非法",{error:"INVALID_LIFE_TIME",message:`--life-time 中的指标必须是 1-30 的合法指标枚举,当前值为 ${d}`});let h=rA(d,0),f=(a=r,c=h,a===a9.RealTime?le:c===a7.TotalROI?lr:lt),m=new Set(f);if(!n.has(h))throw new l("growth:metric-query lifeTime 指标未出现在 metric 中",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}:... 只能配置已经出现在 --metric 中的指标`});if(i.has(h))throw new l("growth:metric-query lifeTime 指标重复配置",{error:"INVALID_LIFE_TIME",message:`指标 ${d} 的 --life-time 只能配置一次;多个天数请写在同一个参数里,例如 --life-time ${d}:${o}`});let g=rf(p)??[];if(0===g.length)throw new l("growth:metric-query lifeTime 缺少生命周期列表",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}: 缺少生命周期天数列表,例如 --life-time ${d}:${o}`});let A=[],y=new Set;for(let e of g){let t=rE(e);if(void 0===t)throw new l("growth:metric-query lifeTime 含有非法天数",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}:${p} 中的生命周期天数必须是正整数`});let r=String(t);if(y.has(r))throw new l("growth:metric-query lifeTime 含有重复天数",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}:${p} 中的生命周期天数不能重复`});if(!m.has(r))throw new l("growth:metric-query lifeTime 超出当前口径范围",{error:"INVALID_LIFE_TIME",message:`${s}下 --life-time 只支持 ${f.join(",")}`});y.add(r),A.push(r)}i.set(h,A)}return i}(r.lifeTime,s,n);var p,h=s,f=d,m=n;let g=la(m);for(let e of h){let t=rD(a7,e),r=f.get(e);if(li.has(e)){if(r&&(1!==r.length||"1"!==r[0]))throw new l("growth:metric-query 首日指标 lifeTime 非法",{error:"INVALID_LIFE_TIME",message:`指标 ${e}(${t}) 是首日指标,可以不传 --life-time;如果传,只能写 --life-time ${e}:1`});continue}if(!r||0===r.length)throw new l("growth:metric-query 非首日指标缺少 lifeTime",{error:"INVALID_LIFE_TIME",message:`指标 ${e}(${t}) 需要生命周期天数,请补充 --life-time ${e}:${g}`})}!function(e,t){if(!t||0===t.length)return;let r=new Set(e.flatMap(e=>lu[e]??[])),i=t.filter(e=>!r.has(e));if(0!==i.length)throw new l("growth:metric-query 二级渠道与一级渠道不匹配",{error:"INVALID_SECOND_CHANNEL",message:`--second-channel ${i.join(",")} 与 --first-channel 不匹配;广告激活(1) 只对应广告(1),星图激活(2) 对应星图-直播/视频(2,3),发行人激活(3) 对应发行人-直播/视频(4,5),自然激活(4) 对应自然各场景(6~21)`})}(a,c);let A=s.map(e=>{let t=d.get(e);return t?{metric:e,lifeTime:t}:{metric:e}}),y=await (p={X_Tt_Appid:r.appId,activateStartDate:r.activateStartDate,activateEndDate:r.activateEndDate,dimension:o,metric:A,freshnessType:n,firstChannel:a,secondChannel:c,download:r.download,meta:await nT("growth:metric-query")},e=n1.genBaseURL("/platform_openapi/microgame/v1/growth/query_growth_spread_sheet"),t={activateEndDate:p.activateEndDate,activateStartDate:p.activateStartDate,dimension:p.dimension,download:p.download,firstChannel:p.firstChannel,freshnessType:p.freshnessType,meta:p.meta,metric:p.metric,secondChannel:p.secondChannel},i={X_Tt_Appid:p.X_Tt_Appid,X_Tt_Userid:p.X_Tt_Userid},n1.request({url:e,method:"POST",data:t,headers:i},void 0)),E=eK(y),_=o.flatMap(e=>e===a4.ActivateDate?["activateDate"]:e===a4.FirstChannel?["firstChannel"]:[]),b=A.flatMap(({metric:e,lifeTime:t})=>{let r=rD(a7,e);return t?.length?t.map(t=>({metric:e,metricName:r,lifeTime:t})):[{metric:e,metricName:r,lifeTime:""}]});return{rawResponse:y,rows:(E?.results??[]).flatMap(e=>{let t={};return o.forEach((r,i)=>{let n=e.dimensionValue?.[i]??"";if(r===a4.ActivateDate){t.activateDate=n;return}r===a4.FirstChannel&&(t.firstChannel=n)}),b.map(({metric:r,metricName:i,lifeTime:n},u)=>({...t,metric:r,metricName:i,lifeTime:n,value:e.indicatorValue?.[u]??""}))}),csvHeader:[..._,...ln]}})}),A=r.command("feedback").description("用户反馈与未成年人退款工单"),nS(A.command("refund-list").description("查询未成年人退款工单、处理状态、截止时间和订单信息").requiredOption("--app-id <appId>","小游戏 appId").option("--start-time <ts>","开始时间,秒级 Unix 时间戳,不能晚于当前时间").option("--end-time <ts>","结束时间,秒级 Unix 时间戳,不能晚于当前时间").option("--resolve-status <n>","处理状态:1 未处理 / 2 已处理").option("--open-id <openId>","用户 OpenID").option("--ticket-id <id>","退款工单 ID").option("--page <n>","页码","1").option("--limit <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("feedback:refund-list",r,async()=>{var e;let t,i,n;rh({startTime:r.startTime,endTime:r.endTime,unit:"seconds",allowFuture:!1}),rn(r.resolveStatus,"--resolve-status",[String(a3.UNRESOLVED),String(a3.RESOLVED)]),rl(r.ticketId,"--ticket-id"),rl(r.page,"--page"),ra(r.limit,"--limit",1,100);let u=r.page??"1",o=r.limit??"20",s=await (e={X_Tt_Appid:r.appId,startTime:r.startTime,endTime:r.endTime,resolveStatus:rC(r.resolveStatus,a3),openId:r.openId,ticketId:r.ticketId,page:u,limit:o},t=n1.genBaseURL("/platform_openapi/microgame/v1/feedback/query_refund"),i={endTime:e.endTime,limit:e.limit,openId:e.openId,page:e.page,resolveStatus:e.resolveStatus,startTime:e.startTime,ticketId:e.ticketId},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eK(s),l=(a?.list??[]).map(e=>({ticketId:e.ticketId,openId:e.openId,content:e.content,createTime:e.createTime,updateTime:e.updateTime,deadlineTime:e.deadlineTime,resolveDuration:e.resolveDuration,auditStatus:e.auditStatus,auditStatusText:e.auditStatusText,minorRefundStatus:e.minorRefundStatus,minorRefundStatusText:e.minorRefundStatusText,devReplyText:e.devReplyText,userHasMoreRefund:e.userHasMoreRefund,ageRange:e.ageRange,orderList:F((e.orderList??[]).map(e=>({createTime:e.createTime,orderId:e.orderId,orderName:e.orderName,orderPrice:ry(e.orderPriceCny),orderPriceDiamond:e.orderPriceDiamond,refund:ry(e.refundCny),refundDiamond:e.refundDiamond}))),imageList:F(e.imageList??[]),rejectReasonList:F(e.rejectReasonList??[]),logUrl:e.logUrl}));return{rawResponse:s,rows:l,csvHeader:a6,resultMeta:iy({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nS(A.command("feedback-list").description("按时间、类型、运行平台、客户端版本、状态、用户或内容查询用户反馈").requiredOption("--app-id <appId>","小游戏 appId").option("--start-time <ts>","开始时间,秒级 Unix 时间戳,不能晚于当前时间").option("--end-time <ts>","结束时间,秒级 Unix 时间戳,不能晚于当前时间").option("--dealt-status-list <list>","处理状态列表,逗号分隔:0 待处理 / 1 超时 / 2 已解决 / 3 处理中 / 100 无需处理").option("--label-id-list <list>","反馈类型 ID 列表,逗号分隔").option("--aid-list <list>","运行平台 ID 列表,逗号分隔").option("--app-version <list>","客户端版本列表,逗号分隔").option("--mark-status <n>","重要反馈状态:3 重要 / 4 非重要").option("--feedback-id <id>","反馈 ID").option("--open-id <openId>","用户 OpenID").option("--search-content <text>","反馈内容关键词").option("--order-rule <n>","排序字段:1 提交时间 / 2 超时时间").option("--current-page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("feedback:feedback-list",r,async()=>{var e;let t,i,n,u;rh({startTime:r.startTime,endTime:r.endTime,unit:"seconds",allowFuture:!1}),ru(r.dealtStatusList,"--dealt-status-list",rv(aQ)),a0(r.labelIdList,"--label-id-list"),a0(r.aidList,"--aid-list"),rn(r.markStatus,"--mark-status",a2),rl(r.feedbackId,"--feedback-id"),rn(r.orderRule,"--order-rule",rv(aZ)),rl(r.currentPage,"--current-page"),ra(r.pageSize,"--page-size",1,100);let o=rA(r.currentPage,1),s=rA(r.pageSize,20),a=await (e={X_Tt_Appid:r.appId,startTime:void 0===r.startTime?void 0:rA(r.startTime,0),endTime:void 0===r.endTime?void 0:rA(r.endTime,0),dealtStatusList:rm(r.dealtStatusList),labelIdList:rm(r.labelIdList),aidList:rm(r.aidList),appVersion:rf(r.appVersion),markStatus:void 0===r.markStatus?void 0:rA(r.markStatus,0),feedbackId:r.feedbackId,openId:r.openId,searchContent:r.searchContent,orderRule:rC(r.orderRule,aZ),currentPage:o,pageSize:s},t=n1.genBaseURL("/platform_openapi/microgame/v1/feedback/query_feedback"),i={appVersion:e.appVersion,did:e.did,os:e.os},n={aid:e.aid,aidList:e.aidList,currentPage:e.currentPage,dealtStatus:e.dealtStatus,dealtStatusList:e.dealtStatusList,endTime:e.endTime,feedbackId:e.feedbackId,feedbackIdList:e.feedbackIdList,isAsc:e.isAsc,isNeedReply:e.isNeedReply,isValidLabel:e.isValidLabel,label1Id:e.label1Id,labelId:e.labelId,labelIdList:e.labelIdList,markStatus:e.markStatus,needChildId:e.needChildId,onlyParentId:e.onlyParentId,openId:e.openId,orderRule:e.orderRule,pageSize:e.pageSize,searchContent:e.searchContent,startTime:e.startTime},u={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",data:i,params:n,headers:u},void 0)),l=eK(a),c=(l?.feedbackList??[]).map(e=>({feedbackId:e.feedbackId,openId:e.openId,content:e.content,createTime:e.createTime,dealtStatus:e.dealtStatus,dealtAction:e.dealtAction,dealtComment:e.dealtComment,dealtTime:e.dealtTime,dealtDdl:e.dealtDdl,hasReply:e.hasReply,isImportant:e.isImportant,isRead:e.isRead,appVersion:e.appVersion,microAppVersion:e.microAppVersion,libraryVersion:e.libraryVersion,platform:e.platform,device:e.device,deviceId:e.deviceId,osVersion:e.osVersion,labelName:e.labelName,label1Name:e.label1Name,isRefund:e.isRefund,imageUrlList:F(e.imageUrlList),logDownloadUrl:e.logDownloadUrl}));return{rawResponse:a,rows:c,csvHeader:a1,resultMeta:iy({returnedCount:c.length,total:l?.total,page:o,pageSize:s})}})}),f=r.command("revenue").description("商业化"),nS((i=f).command("traffic-status").description("检查小游戏是否具备开通流量主的权限、签约和主体资质").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:traffic-status",r,async()=>{var e;let t,i,n=await (e={X_Tt_Appid:r.appId},t=n1.genBaseURL("/platform_openapi/microgame/v1/ad/query_traffic_status"),i={X_Tt_Appid:(e||{}).X_Tt_Appid},n1.request({url:t,method:"GET",headers:i},void 0));return eK(n),{rawResponse:n}})}),nS(i.command("placement-list").description("查询当前小游戏的广告位及其类型、开关和封禁状态").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:placement-list",r,async()=>{var e;let t,i,n=await (e={X_Tt_Appid:r.appId},t=n1.genBaseURL("/platform_openapi/microgame/v1/ad/query_placement"),i={X_Tt_Appid:(e||{}).X_Tt_Appid},n1.request({url:t,method:"GET",headers:i},void 0)),u=eK(n);return{rawResponse:n,rows:(u?.ads??[]).map(e=>({adId:e.adId,name:e.name,type:e.type,adStatus:e.adStatus,adBanStatus:e.adBanStatus})),csvHeader:["adId","name","type","adStatus","adBanStatus"]}})}),nS((n=f).command("ad-income-query").description("查询流量主广告收入总览和按日趋势").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD,最早为最近 365 天").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD,最晚为昨天").option("--ad-position-types <list>","广告位类型:1 Banner / 2 激励视频 / 3 插屏 / 4 游戏化电商").option("--hosts <list>","宿主:1 全部 / 2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山 / 9 皮皮虾").option("--os <n>","操作系统:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony / 5 Windows").option("--activate-type <n>","归因类型:1 广告 / 2 星图 / 3 发行人 / 4 自然")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:ad-income-query",r,async()=>{var e;let t,i,n;rd({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:ob,latestDateOffsetDays:1,label:"广告收入"}),ru(r.adPositionTypes,"--ad-position-types",rv(l1)),ru(r.hosts,"--hosts",rv(l2)),rn(r.os,"--os",rv(l0)),rn(r.activateType,"--activate-type",rv(l3));let u=await (e={X_Tt_Appid:r.appId,startDate:r.startDate,endDate:r.endDate,adPositionTypes:rm(r.adPositionTypes),hosts:rg(r.hosts,"--hosts",l2.All),os:rC(r.os,l0),activateType:rC(r.activateType,l3),fromAppPlatform:1,meta:await nT("revenue:ad-income-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/ad/query_income_overview"),i={activateType:e.activateType,adPositionTypes:e.adPositionTypes,endDate:e.endDate,fromAppPlatform:e.fromAppPlatform,hosts:e.hosts,meta:e.meta,os:e.os,startDate:e.startDate},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u),s=(e,t)=>({recordType:t,date:e?.date,requestCount:e?.requestCount,showCount:e?.showCount,clickCount:e?.clickCount,clickRate:e?.clickRate,ecpm:e?.ecpm,incomeAfterShare:e?.incomeAfterShare,incomeBeforeShare:e?.incomeBeforeShare}),a=(o?.items??[]).map(e=>s(e,"daily"));return o?.summary&&a.push(s(o.summary,"summary")),{rawResponse:u,rows:a,csvHeader:l7}})}),nS(n.command("ad-income-detail").description("按广告位和宿主分页查询流量主广告经营明细").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD,最早为最近 365 天").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD,最晚为昨天").option("--ad-position-types <list>","广告位类型:1 Banner / 2 激励视频 / 3 插屏 / 4 游戏化电商").option("--hosts <list>","宿主:1 全部 / 2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山 / 9 皮皮虾").option("--os <n>","操作系统:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony / 5 Windows").option("--activate-type <n>","归因类型:1 广告 / 2 星图 / 3 发行人 / 4 自然").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:ad-income-detail",r,async()=>{var e;let t,i,n;rd({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:ob,latestDateOffsetDays:1,label:"广告收入"}),ru(r.adPositionTypes,"--ad-position-types",rv(l6)),ru(r.hosts,"--hosts",rv(l4)),rn(r.os,"--os",rv(l8)),rn(r.activateType,"--activate-type",rv(l9)),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100);let u=r.page??"1",o=r.pageSize??"20",s=await (e={X_Tt_Appid:r.appId,startDate:r.startDate,endDate:r.endDate,adPositionTypes:rm(r.adPositionTypes),hosts:rg(r.hosts,"--hosts",l4.All),os:rC(r.os,l8),activateType:rC(r.activateType,l9),fromAppPlatform:1,meta:await nT("revenue:ad-income-detail"),page:u,pageSize:o},t=n1.genBaseURL("/platform_openapi/microgame/v1/ad/query_income_detail"),i={activateType:e.activateType,adPositionTypes:e.adPositionTypes,endDate:e.endDate,fromAppPlatform:e.fromAppPlatform,hosts:e.hosts,meta:e.meta,os:e.os,page:e.page,pageSize:e.pageSize,startDate:e.startDate},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),a=eK(s),l=(a?.items??[]).map(e=>({date:e.date,ritId:e.ritId,ritName:e.ritName,hostName:e.hostName,requestCount:e.requestCount,showCount:e.showCount,clickCount:e.clickCount,clickRate:e.clickRate,ecpm:e.ecpm,incomeAfterShare:e.incomeAfterShare,incomeBeforeShare:e.incomeBeforeShare}));return{rawResponse:s,rows:l,csvHeader:l5,resultMeta:iy({returnedCount:l.length,total:a?.page.total,page:a?.page.page??u,pageSize:a?.page.pageSize??o,hasMore:a?.page.hasMore,nextCursor:a?.page.nextSearchAfter})}})}),nS((u=f).command("payment-status").description("查询虚拟支付权限及钻石支付、担保支付协议状态").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:payment-status",r,async()=>{let[e,t]=await Promise.all([cd(r.appId),cp(r.appId)]);return{rawResponse:{permission:e,protocols:t.map(({response:e,scene:t})=>({scene:t,...e}))}}})}),nS(ch(u.command("payment-order-list").description("按交易、订单、商品或 OpenID 查询虚拟支付流水明细")).option("--payment-status <status>","支付状态:done 完成 / canceled 取消").option("--transaction-type <type>","流水类型:recharge 充值 / pay 消费 / add 赠送 / refund 退款").option("--keyword-type <n>","关键词类型:1 交易单号 / 2 商户单号 / 3 OpenID").option("--keyword <text>","查询关键词").option("--good-type <n>","交易类型:1 游戏币 / 2 道具直购").option("--payment-channel <n>","支付渠道:1 现金 / 2 抖音钻石").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:payment-order-list",r,async()=>{var e;let t,i,n;if(rc({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),rn(r.host,"--host",["-1",...lx]),rn(r.os,"--os",co),rn(r.activateType,"--activate-type",rv(ce)),rn(r.fromAppPlatform,"--from-app-platform",rv(ct)),rn(r.goodType,"--good-type",rv(cr)),rn(r.paymentChannel,"--payment-channel",rv(ci)),rn(r.paymentStatus,"--payment-status",["done","canceled"]),rn(r.transactionType,"--transaction-type",["recharge","pay","add","refund"]),ra(r.keywordType,"--keyword-type",1,3),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100),!!r.keyword!=!!r.keywordType)throw new l("--keyword-type 与 --keyword 必须同时提供",{error:rt.InvalidRange,message:"--keyword-type 与 --keyword 必须同时提供"});let u=r.page??"1",o=r.pageSize??"20",s=cc(r.startDate,r.endDate)?void 0:rC(r.activateType,ce),a=r.keyword&&r.keywordType?{[rA(r.keywordType,1)]:r.keyword}:void 0,c=await (e={X_Tt_Appid:r.appId,startTime:r.startDate,endTime:r.endDate,hostId:r.host??"-1",os:r.os,activateType:s,fromAppPlatform:rC(r.fromAppPlatform,ct),payStatus:r.paymentStatus,changeType:r.transactionType,keyword:a,goodType:rC(r.goodType,cr),orderType:rC(r.paymentChannel,ci),pageNo:u,pageSize:o},t=n1.genBaseURL("/platform_openapi/microgame/v1/payment/query_order"),i={activateType:e.activateType,changeType:e.changeType,endTime:e.endTime,fromAppPlatform:e.fromAppPlatform,goodType:e.goodType,hostId:e.hostId,keyword:e.keyword,orderType:e.orderType,os:e.os,pageNo:e.pageNo,pageSize:e.pageSize,payStatus:e.payStatus,startTime:e.startTime},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),d=eK(c),p=d?.result?.[0],h=(p?.payDetail??[]).map(e=>({payTime:e.payTime,transactionNo:e.transactionNo,merchantNo:e.merchantNo,openId:e.openId,payStatus:e.payStatus,changeType:e.changeType,goodType:e.goodType,orderType:e.orderType,activateType:e.activateType,amount:e.amount,rechargeAmount:ry(e.rechargeAmountFen),isOpenPlatformRefund:e.isOpenPlatformRefund,refundFee:e.refundFee,refundFeeBeforeShare:e.refundFeeBeforeShare,refundFeeAfterShare:e.refundFeeAfterShare,refundRemark:e.refundRemark}));return{rawResponse:c,rows:h,csvHeader:ca,resultMeta:iy({returnedCount:h.length,total:p?.totalNum,page:u,pageSize:o})}})}),nS(ch(u.command("payment-income-query").description("查询虚拟支付收入总览、分成、退款和 ARPPU"))).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:payment-income-query",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),rn(r.host,"--host",["-1",...lx]),rn(r.os,"--os",co),rn(r.activateType,"--activate-type",rv(cn)),rn(r.fromAppPlatform,"--from-app-platform",rv(cu));let u=cc(r.startDate,r.endDate)?void 0:rC(r.activateType,cn),o=await (e={X_Tt_Appid:r.appId,startTime:r.startDate,endTime:r.endDate,hostId:r.host??"-1",os:r.os,activateType:u,fromAppPlatform:rC(r.fromAppPlatform,cu)},t=n1.genBaseURL("/platform_openapi/microgame/v1/payment/query_income"),i={activateType:e.activateType,endTime:e.endTime,fromAppPlatform:e.fromAppPlatform,hostId:e.hostId,os:e.os,startTime:e.startTime},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),s=eK(o),a=s?.result?.[0],l=(e,t)=>({recordType:t,date:e?.date,payPerson:e?.payPerson,payTimes:e?.payTimes,arppu:e?.arppu,payMoney:ry(e?.payMoneyFen),payMoneyAfterShare:e?.payMoneyAfterShareDataReady?ry(e.payMoneyAfterShareFen):void 0,payMoneyAfterReduceShare:e?.payMoneyAfterReduceShareDataReady?ry(e.payMoneyAfterReduceShareFen):void 0,refundFee:e?.refundFee,refundFeeBeforeShare:e?.refundFeeBeforeShare,refundFeeAfterShare:e?.refundFeeAfterShare,payMoneyAfterShareDataReady:e?.payMoneyAfterShareDataReady,payMoneyAfterReduceShareDataReady:e?.payMoneyAfterReduceShareDataReady}),c=(a?.payOverview??[]).map(e=>l(e,"daily"));return a?.payOverviewSum&&c.push(l(a.payOverviewSum,"summary")),{rawResponse:o,rows:c,csvHeader:cs}})}),y=r.command("publisher").description("发行人计划"),nS((o=y).command("task-list").description("查询发行人推广任务列表,包括任务名称、任务状态、总消耗等").requiredOption("--app-id <appId>","小游戏 appId").option("--start-date <date>","开始日期,格式 YYYY-MM-DD,不能晚于今天").option("--end-date <date>","结束日期,格式 YYYY-MM-DD,不能晚于今天").option("--task-id <id>","任务 ID").option("--task-type <n>","任务类型:0 小游戏 / 1 微端 / 100 全部").option("--media-type <n>","内容类型:1 短视频 / 2 直播 / 100 全部").option("--web-status <n>","任务状态:1 待审核 / 2 通过 / 3 驳回 / 4 取消 / 5 预热 / 6 暂停 / 7 进行中 / 8 完成").option("--bidding-method <n>","出价方式:1 短视频 CPA / 6 CPM / 8 一口价 / 22 直播 CPA / 27 CPS / 28 CPA+CPS / 29 短视频 CPA+CPS / 30 直播 CPS").option("--task-category <n>","任务分类:0 全部 / 1 普通任务 / 2 指派任务").option("--asc","是否升序",!1).option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("publisher:task-list",r,async()=>{let e,t,i,n;rc({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),rl(r.taskId,"--task-id"),rn(r.taskType,"--task-type",rv(l$)),rn(r.mediaType,"--media-type",lq),rn(r.webStatus,"--web-status",lZ),rn(r.biddingMethod,"--bidding-method",lV),rn(r.taskCategory,"--task-category",lU),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100);let u=rA(r.page,1),o=rA(r.pageSize,20),s=await (e={X_Tt_Appid:r.appId,startDate:r.startDate?.replaceAll("-",""),endDate:r.endDate?.replaceAll("-",""),taskId:r.taskId,taskType:rC(r.taskType,l$),mediaType:rC(r.mediaType,lj),webStatus:rC(r.webStatus,lM),biddingMethod:rC(r.biddingMethod,lN),taskCategory:void 0===r.taskCategory?void 0:rA(r.taskCategory,0),asc:r.asc,offset:String((u-1)*o),limit:String(o)},t=n1.genBaseURL("/platform_openapi/microgame/v1/publisher/query_task"),i={asc:e.asc,biddingMethod:e.biddingMethod,endDate:e.endDate,limit:e.limit,mediaType:e.mediaType,offset:e.offset,orderBy:e.orderBy,startDate:e.startDate,taskCategory:e.taskCategory,taskId:e.taskId,taskType:e.taskType,webStatus:e.webStatus},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eK(s),l=(a?.summaryStats??[]).map(e=>{let t=e.taskId?a?.taskInfoMap?.[e.taskId]:void 0;return{taskId:e.taskId,taskName:t?.taskName,taskType:e.taskType,taskCategory:t?.taskCategory,taskStatus:t?.taskStatus,webStatus:t?.webStatus,mediaType:t?.mediaType,startTime:t?.startTime,endTime:t?.endTime,createTime:t?.createTime,realEndTime:t?.realEndTime,budget:ry(t?.budget),prepaidFreezeAmount:ry(e.prepaidFreezeAmount),securityBudget:ry(t?.securityBudget),totalExpectedNum:t?.totalExpectedNum,expense:ry(e.expense),totalIncome:ry(e.totalIncome),cpaExpense:ry(e.cpaExpense),cpsExpense:ry(e.cpsExpense),adIncomeSettle:ry(e.adIncomeSettle),orderIncomeSettle:ry(e.orderIncomeSettle),newRegisterCnt:e.newRegisterCnt,videoPost:e.videoPost,liveRoomCnt:e.liveRoomCnt,dataProductionDate:e.dataProductionDate,bidCollections:F(t?.bidCollections??[])}});return{rawResponse:s,rows:l,csvHeader:lX,resultMeta:iy({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nS(o.command("task-detail-query").description("查询发行人任务的详情,包括总消耗数据、总收入数据、视频投稿数等").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--task-id <id>","任务 ID").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("publisher:task-detail-query",r,async()=>{let e,t,i,n;rc({startDate:r.startDate,endDate:r.endDate}),rl(r.taskId,"--task-id"),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100);let u=rA(r.page,1),o=rA(r.pageSize,20),s=await (e={X_Tt_Appid:r.appId,taskId:r.taskId,rangeStart:r.startDate.replaceAll("-",""),rangeEnd:r.endDate.replaceAll("-",""),offset:String((u-1)*o),limit:String(o)},t=n1.genBaseURL("/platform_openapi/microgame/v1/publisher/query_task_daily"),i={limit:e.limit,offset:e.offset,rangeEnd:e.rangeEnd,rangeStart:e.rangeStart,taskId:e.taskId},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eK(s),l=(a?.detailStats??[]).map(e=>({date:e.date,taskId:e.taskId,taskType:e.taskType,expense:ry(e.expense),totalIncome:ry(e.totalIncome),cpaExpense:ry(e.cpaExpense),cpsExpense:ry(e.cpsExpense),adIncomeSettle:ry(e.adIncomeSettle),adIncomeLongTail:ry(e.adIncomeLongTail),orderIncomeSettle:ry(e.orderIncomeSettle),orderIncomeLongTail:ry(e.orderIncomeLongTail),newRegisterCnt:e.newRegisterCnt,videoPost:e.videoPost,videoPostUcnt:e.videoPostUcnt,videoPlaySettle:e.videoPlaySettle,videoPlayLongTail:e.videoPlayLongTail,liveRoomCnt:e.liveRoomCnt,liveRoomUcnt:e.liveRoomUcnt,liveViewCnt:e.liveViewCnt,liveViewUcnt:e.liveViewUcnt,frozenAmount:ry(e.frozenAmount),breakdownAmount:ry(e.breakdownAmount),yesterdayDataReady:a?.yesterdayDataReady}));return{rawResponse:s,rows:l,csvHeader:lQ,resultMeta:iy({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nS((s=y).command("promotion-query").description("查询推广消耗、收入、新增激活用户数、新增激活用户成本等明细").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD").option("--metrics <list>","查询一个或两个趋势指标:1 总消耗 / 2 总收入 / 3 新增激活 / 4 组件点击","1,2").option("--media-type <n>","媒体类型:1 短视频 / 2 直播 / 100 全部")).action(async(e,t)=>{let r=nx(t,e);await oc("publisher:promotion-query",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate}),rn(r.mediaType,"--media-type",rv(lW));let[u,o]=function(e){ru(e,"--metrics",lK);let t=rm(e);if(!t||t.length<1||t.length>2)throw new l("--metrics 必须包含一个或两个趋势指标",{error:rt.InvalidEnum,message:"--metrics 必须传入一个或两个枚举值,例如 1 或 1,2"});return[t[0],t[1]??t[0]]}(r.metrics),s=await (e={X_Tt_Appid:r.appId,startDate:r.startDate,endDate:r.endDate,leftType:u,rightType:o,mediaType:rC(r.mediaType,lW)},t=n1.genBaseURL("/platform_openapi/microgame/v1/publisher/query_promotion_trend"),i={endDate:e.endDate,leftType:e.leftType,mediaType:e.mediaType,rightType:e.rightType,startDate:e.startDate},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eK(s);return{rawResponse:s,rows:(a?.list??[]).map(e=>({date:e.date,totalConsumptionAmount:ry(e.totalConsumptionAmount),totalRevenueAmount:ry(e.totalRevenueAmount),newActivationCount:e.newActivationCount,componentClickCount:e.componentClickCount})),csvHeader:["date","totalConsumptionAmount","totalRevenueAmount","newActivationCount","componentClickCount"]}})}),nS(s.command("promotion-detail-list").description("查询发行人计划各内容类型的推广费用、收入及转化明细,按日期和内容类型分页").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD").option("--media-type <n>","媒体类型:1 短视频 / 2 直播 / 100 全部").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("publisher:promotion-detail-list",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate}),rn(r.mediaType,"--media-type",rv(lW)),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100);let u=r.page??"1",o=r.pageSize??"20",s=await (e={X_Tt_Appid:r.appId,startDate:r.startDate,endDate:r.endDate,mediaType:rC(r.mediaType,lW),pageNo:u,pageSize:o},t=n1.genBaseURL("/platform_openapi/microgame/v1/publisher/query_promotion_detail"),i={endDate:e.endDate,mediaType:e.mediaType,pageNo:e.pageNo,pageSize:e.pageSize,startDate:e.startDate},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eK(s),l=(a?.settleDetailList??[]).map(e=>({date:e.date,mediaType:e.mediaType,totalConsumptionAmount:ry(e.totalConsumptionAmount),totalRevenueAmount:ry(e.totalRevenueAmount),newActivationCount:e.newActivationCount,firstActiveCount:e.firstActiveCount,componentExposureCount:e.componentExposureCount,componentClickCount:e.componentClickCount,componentClickThroughRate:e.componentClickThroughRate,conversionBillingConsumptionAmount:ry(e.conversionBillingConsumptionAmount),revenueBillingConsumptionAmount:ry(e.revenueBillingConsumptionAmount),revenueUserCount:e.revenueUserCount,iaaRevenueAmount:ry(e.iaaRevenueAmount),iapRevenueAmount:ry(e.iapRevenueAmount)}));return{rawResponse:s,rows:l,csvHeader:lY,resultMeta:iy({returnedCount:l.length,total:a?.totalCount,page:u,pageSize:o})}})}),nS(y.command("faction-incentive-list").description("查询公会任务的详情数据,包括各任务的出价、流水、激励比例等").requiredOption("--app-id <appId>","小游戏 appId").option("--faction-id <id>","公会 ID").option("--task-ids <list>","任务 ID 列表,逗号分隔").option("--task-types <list>","任务类型列表:0 全部 / 1 普通任务 / 2 指派任务").option("--task-statuses <list>","任务状态列表:1 进行中 / 2 已完成").option("--stat-months <list>","任务月份列表,当前月及之前 71 个月,逗号分隔",(m=new Date,`${m.getFullYear()}${String(m.getMonth()+1).padStart(2,"0")}`)).option("--content-types <list>","内容类型列表:1 短视频 / 2 直播 / 100 全部").option("--bid-types <list>","出价方式列表:-1 全部 / 1 短视频 CPA / 6 CPM / 8 一口价 / 22 直播 CPA / 27 CPS / 28 CPA+CPS / 29 短视频 CPA+CPS / 30 直播 CPS").option("--order-field <field>","排序字段").option("--order-type <n>","排序方向:1 升序 / 2 降序").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("publisher:faction-incentive-list",r,async()=>{let e,t,i,n;for(let e of(rl(r.factionId,"--faction-id"),rf(r.taskIds)??[]))rl(e,"--task-ids");rn(r.orderType,"--order-type",lG),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100),ru(r.taskTypes,"--task-types",lU),ru(r.taskStatuses,"--task-statuses",lz),ru(r.contentTypes,"--content-types",lq),ru(r.bidTypes,"--bid-types",["-1",...lV]),function(e,t){var r=e,i=t;if(void 0!==r){for(let e of t8(r))if(!t7.test(e))throw new l(`参数 ${i} 包含非法月份: ${e}`,{error:"INVALID_DATE",message:`${i} 每一项必须为 YYYYMM 格式,且月份范围为 01~12`})}if(void 0===e)return;let n=new Date,u=12*n.getFullYear()+n.getMonth(),o=u-72+1;for(let r of t8(e)){let e=Number(r.slice(0,4)),i=12*e+Number(r.slice(4,6))-1;if(i>u||i<o)throw new l(`参数 ${t} 包含超出范围的月份: ${r}`,{error:"OUT_OF_LOOKBACK",message:`${t} 每一项必须位于当前月及之前 71 个月内`})}}(r.statMonths,"--stat-months");let u=r.page??"1",o=r.pageSize??"20",s=await (e={X_Tt_Appid:r.appId,factionId:r.factionId,taskIDs:rf(r.taskIds),taskTypes:rg(r.taskTypes,"--task-types",0),taskStatuses:rm(r.taskStatuses),statMonths:rm(r.statMonths),contentTypes:rg(r.contentTypes,"--content-types",100),bidTypes:rg(r.bidTypes,"--bid-types",-1),orderField:r.orderField,orderType:void 0===r.orderType?void 0:rA(r.orderType,0),pageNum:u,pageSize:o},t=n1.genBaseURL("/platform_openapi/microgame/v1/publisher/query_faction_incentive"),i={bidTypes:e.bidTypes,contentTypes:e.contentTypes,factionId:e.factionId,orderField:e.orderField,orderType:e.orderType,pageNum:e.pageNum,pageSize:e.pageSize,statMonths:e.statMonths,taskIDs:e.taskIDs,taskId:e.taskId,taskMonths:e.taskMonths,taskStatuses:e.taskStatuses,taskTypes:e.taskTypes},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",params:i,headers:n},void 0)),a=eK(s),c=(a?.series??[]).map(e=>({mpId:e.mpId,mpName:e.mpName,mpCategory:e.mpCategory,taskId:e.taskId,taskName:e.taskName,taskType:e.taskType,factionId:e.factionId,factionName:e.factionName,contentType:e.contentType,bidType:e.bidType,effectiveTime:e.effectiveTime,dayCnt:e.dayCnt,metrics:F(e),extraIncentive:F(e.extraIncentive),dataUpdateTime:a?.dataUpdateTime,readyDate:a?.extra?.readyDate,readyTs:a?.extra?.readyTs}));return{rawResponse:s,rows:c,csvHeader:lH,resultMeta:iy({returnedCount:c.length,total:a?.total,page:a?.pageNum??u,pageSize:o})}})}),nS((a=r.command("ability").description("能力中心")).command("customer-service-status-query").description("查询新版抖音客服平台的开通状态").requiredOption("--app-id <appId>","小游戏 appId").addOption(new L("--type <type>","客服类型:im 抖音 IM / platform 抖音客服平台").choices(["im","platform"]))).action(async(e,t)=>{let r=nx(t,e);await oc("ability:customer-service-status-query",r,async()=>{var e,t;let i,n,u,o,s=[];return r.type&&"im"!==r.type||s.push((e={X_Tt_Appid:r.appId},i=n1.genBaseURL("/platform_openapi/microgame/v1/ability/query_im_customer_service_status"),n={X_Tt_Appid:(e||{}).X_Tt_Appid},n1.request({url:i,method:"GET",headers:n},void 0)).then(e=>(eK(e),["im",e]))),r.type&&"platform"!==r.type||s.push((t={X_Tt_Appid:r.appId},u=n1.genBaseURL("/platform_openapi/microgame/v1/ability/query_customer_service_status"),o={X_Tt_Appid:t.X_Tt_Appid},n1.request({url:u,method:"GET",headers:o},void 0)).then(e=>(eK(e),["platform",e]))),{rawResponse:Object.fromEntries(await Promise.all(s))}})}),nS(a.command("rank-list-query").description("查询当前小游戏已有的排行榜配置").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nx(t,e);await oc("ability:rank-list-query",r,async()=>{let e,t,i,n,u=await (e={X_Tt_Appid:r.appId},t=n1.genBaseURL("/platform_openapi/microgame/v1/ability/query_game_rank_components"),i={isDefault:e.isDefault,uniqueFlag:e.uniqueFlag},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:o?.rankInfo??[],csvHeader:["uniqueFlag","shortName","updateFrequency","dataType","sortType","dataSuffix","enumValues","isDefault","updateTime"]}})}),nS(a.command("share-template-query").description("查询当前小游戏在分享设置配置的分享模板、审核状态、默认标记和驳回原因").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nx(t,e);await oc("ability:share-template-query",r,async()=>{var e;let t,i,n=await (e={appIdStr:r.appId,newTemplate:!0},t=n1.genBaseURL("/platform_openapi/microgame/v1/ability/query_share_setting"),i={appIdStr:e.appIdStr,newTemplate:e.newTemplate},n1.request({url:t,method:"GET",params:i},void 0)),u=eK(n);return{rawResponse:n,rows:(u?.shareInfoList??[]).map(e=>({shareId:e.shareId,title:e.title,description:e.description,cardType:e.cardType,auditState:e.auditState,isDefault:e.isDefault,platform:e.platform,icon:e.icon,iconUri:e.iconUri,reason:e.reason,modifyRemainTimes:e.modifyRemainTimes,ctime:e.ctime,mtime:e.mtime,needRemind:u?.needRemind})),csvHeader:["shareId","title","description","cardType","auditState","isDefault","platform","icon","iconUri","reason","modifyRemainTimes","ctime","mtime","needRemind"]}})}),g=r.command("performance").description("性能数据"),nS(g.command("performance-diagnosis-query").description("查询小游戏启动和运行性能诊断结果,包括劣化指标、实际值、标准值、差值及优化建议;当前不提供网络诊断").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--host <host>",nF).option("--date <date>","诊断日期,格式 YYYY-MM-DD").option("--device-level <n>",nB).option("--os <os>","操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony").option("--mp-version <version>","小游戏版本号")).action(async(e,t)=>{let r=nx(t,e);await oc("performance:performance-diagnosis-query",r,async()=>{var e;let t,i,n;rn(r.host,"--host",lB),rn(r.deviceLevel,"--device-level",rv(l_)),rn(r.os,"--os",rv(lb)),rs(r.date,"--date");let u=await (e={X_Tt_Appid:r.appId,hostAid:lw[rA(r.host,0)]??"",date:r.date,deviceLevel:void 0===r.deviceLevel?void 0:rA(r.deviceLevel,0),os:void 0===r.os?void 0:rA(r.os,0),mpVersion:r.mpVersion,meta:await nT("performance:performance-diagnosis-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/performance/query_performance_diagnosis"),i={date:e.date,deviceLevel:e.deviceLevel,hostAid:e.hostAid,meta:e.meta,mpVersion:e.mpVersion,os:e.os},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u),s={group:"main",genreName:o?.genreName??"",engine:o?.engine??"",degradedIndicatorCount:o?.degradedIndicatorCount??0};return{rawResponse:u,rows:[...lk(o?.launchItems,s,"launch"),...lk(o?.runtimeItems,s,"runtime"),...(o?.otherGroups??[]).flatMap(e=>{let t={group:"other",genreName:e.genreName,engine:e.engine,degradedIndicatorCount:e.degradedIndicatorCount};return[...lk(e.launchItems,t,"launch"),...lk(e.runtimeItems,t,"runtime")]})],csvHeader:lT}})}),nS(nO(g.command("startup-performance-query").description("查询小游戏启动性能数据,包括启动耗时、首帧耗时、TTI 耗时、Wasm 编译耗时、启动留存率、启动场景转化、启动耗时分布和启动流失分布等").option("--metrics <list>","启动性能指标枚举,逗号分隔;不传返回默认指标集").option("--sections <list>","启动分析板块枚举,逗号分隔:1 趋势 / 2 场景转化 / 3 耗时分布 / 4 流失分布 / 5 分包").option("--entrance-form <form>","启动入口形态:all 不区分 / 视频 / 侧边栏 / 广告 / 搜索 / 游戏中心 / 直播 / 桌面 / 私信 / 首页 / 直玩 / 其他").option("--download-code <n>","下载代码枚举:1 全部 / 2 需要 / 3 不需要").option("--scene-id-list <list>","场景 ID 列表,逗号分隔"))).action(async(e,t)=>{let r=nx(t,e);await oc("performance:startup-performance-query",r,async()=>{var e;let t,i,n;lP(r),ru(r.sections,"--sections",rv(lF)),rn(r.downloadCode,"--download-code",rv(lD)),ro(r.sceneIdList,"--scene-id-list");let u=await (e={X_Tt_Appid:r.appId,filter:{common:lL(r),entranceForm:r.entranceForm,downloadCode:void 0===r.downloadCode?void 0:rA(r.downloadCode,0),sceneIdList:rf(r.sceneIdList)},metrics:rm(r.metrics),sections:rm(r.sections),meta:await nT("performance:startup-performance-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/performance/query_launch_performance"),i={filter:e.filter,meta:e.meta,metrics:e.metrics,sections:e.sections},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:lR(o?.series),csvHeader:lI}})}),nS(nO(g.command("runtime-performance-query").description("查询小游戏运行时性能数据,包括 FPS、卡顿率、渲染 DrawCall、三角面数、顶点数、平均内存、内存峰值、内存异常退出率、CPU 使用率、GPU 使用率等").option("--metrics <list>","运行时性能指标枚举,逗号分隔;不传返回默认指标集").option("--include-device-breakdown","是否返回机型分布",!1).option("--include-fps-distribution","是否返回 FPS 分布",!1).option("--include-memory-distribution","是否返回内存分布",!1))).action(async(e,t)=>{let r=nx(t,e);await oc("performance:runtime-performance-query",r,async()=>{var e;let t,i,n;lP(r);let u=await (e={X_Tt_Appid:r.appId,filter:lL(r),includeDeviceBreakdown:r.includeDeviceBreakdown,includeFpsDistribution:r.includeFpsDistribution,includeMemoryDistribution:r.includeMemoryDistribution,metrics:rm(r.metrics),meta:await nT("performance:runtime-performance-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/performance/query_runtime_performance"),i={filter:e.filter,includeDeviceBreakdown:e.includeDeviceBreakdown,includeFpsDistribution:e.includeFpsDistribution,includeMemoryDistribution:e.includeMemoryDistribution,meta:e.meta,metrics:e.metrics},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:lR(o?.series),csvHeader:lI}})}),nS(nO(g.command("network-performance-query").description("查询小游戏网络性能数据,包括 request 和 downloadFile 的请求耗时、错误率等指标").option("--metrics <list>","网络性能指标枚举,逗号分隔;不传返回默认指标集"))).action(async(e,t)=>{let r=nx(t,e);await oc("performance:network-performance-query",r,async()=>{var e;let t,i,n;lP(r);let u=await (e={X_Tt_Appid:r.appId,filter:lL(r),metrics:rm(r.metrics),meta:await nT("performance:network-performance-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/performance/query_network_performance"),i={filter:e.filter,meta:e.meta,metrics:e.metrics},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:lR(o?.series),csvHeader:lI}})}),nS(g.command("error-log-query").description("查询小游戏错误日志列表,支持按时间、App、操作系统、JSSDK 版本、宿主版本、小游戏版本、OpenID、TraceID、日志等级等条件筛选").requiredOption("--app-id <appId>","小游戏 appId").option("--start-time <ts>","开始时间,秒级 Unix 时间戳;缺省为结束时间前 1 小时").option("--end-time <ts>","结束时间,秒级 Unix 时间戳;缺省为当前时间").option("--host <host>",nD).option("--os <os>",nw).option("--app-version <version>","宿主版本号").option("--game-version <version>","小游戏版本号").option("--jssdk-version <version>","JSSDK 版本号").option("--open-id <openId>","用户 OpenID").option("--trace-id <traceId>","日志 TraceID").option("--log-level-list <list>","日志等级枚举,逗号分隔:1 Debug / 2 Info / 3 Warn / 4 Error / 5 Fatal").option("--filter-msg <list>","日志内容过滤关键词,逗号分隔").option("--page-group-size <n>","每页日志分组数").option("--search-after <cursor>","游标,用于翻页续查")).action(async(e,t)=>{let r=nx(t,e);await oc("performance:error-log-query",r,async()=>{var e;let t,i,n;rn(r.host,"--host",rv(lA)),rn(r.os,"--os",rv(lE)),ru(r.logLevelList,"--log-level-list",rv(ly)),function(e){let{maxLookbackDays:t,label:r}=e,i=e.unit??"milliseconds",n=BigInt(e.lookbackTolerance??0),u=rp(e),o=BigInt("seconds"===i?Math.floor(Date.now()/1e3):Date.now()),s=o-BigInt(t*("seconds"===i?86400:864e5))-n;for(let[e,i]of u){if(i>o)throw new l(`${e} 不能晚于当前时间`,{error:"INVALID_TIMESTAMP_RANGE",message:`${e} 不能晚于当前时间`});if(i<s)throw new l(`${r}仅支持最近 ${t} 天的数据`,{error:"OUT_OF_LOOKBACK",message:`${r}仅支持最近 ${t} 天的数据,${e} 已超出范围`})}}({startTime:r.startTime,endTime:r.endTime,maxLookbackDays:oC,label:"错误日志",unit:"seconds"}),ra(r.pageGroupSize,"--page-group-size",1,20);let u=await (e={X_Tt_Appid:r.appId,startTime:r.startTime,endTime:r.endTime,host:void 0===r.host?void 0:rA(r.host,0),os:void 0===r.os?void 0:rA(r.os,0),appVersion:r.appVersion,gameVersion:r.gameVersion,jssdkVersion:r.jssdkVersion,openId:r.openId,traceId:r.traceId,logLevelList:rm(r.logLevelList),filterMsg:rf(r.filterMsg),pageGroupSize:r.pageGroupSize,searchAfter:r.searchAfter,meta:await nT("performance:error-log-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/performance/query_error_logs"),i={appVersion:e.appVersion,endTime:e.endTime,filterMsg:e.filterMsg,gameVersion:e.gameVersion,host:e.host,jssdkVersion:e.jssdkVersion,logLevelList:e.logLevelList,meta:e.meta,openId:e.openId,os:e.os,pageGroupSize:e.pageGroupSize,searchAfter:e.searchAfter,startTime:e.startTime,traceId:e.traceId},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:(o?.logList??[]).flatMap(e=>(e.logList??[]).map(t=>({appId:e.appId,host:e.host,os:e.os,appVersion:e.appVersion,gameVersion:e.gameVersion,jssdkVersion:e.jssdkVersion,versionType:e.versionType,openId:e.openId,traceId:e.traceId,logLevel:t.logLevel,timestamp:t.timestamp,msg:t.msg}))),csvHeader:lO,resultMeta:{unit:"logGroup",returnedCount:o?.logList?.length,total:o?.page?.total===void 0?void 0:Number(o.page.total),hasMore:o?.page?.hasMore,nextCursor:o?.page?.nextSearchAfter}}})}),r.command("skills").description("管理随 CLI 发布的 Agent Skill").command("install").description(`同步随 CLI 发布的 ${e4} Skill`).addHelpText("after","\n说明:\n 安装或重新同步本机 Agent Skill\n update 默认会执行同步;需要手动修复 Skill 时再运行本命令\n\n示例:\n $ dymg skills install").action(az),r.command("check-update").description("检查 CLI 更新").addHelpText("after","\n说明:\n 查询 npm registry 的 latest 版本\n 发现新版本时,按提示执行 update 更新 CLI 并同步 Skill\n\n示例:\n $ dymg check-update\n $ dymg update").action(aX),r.command("update").description("更新 CLI 并同步 Skill").option("--target-version <version>","安装指定版本或 dist tag,默认 latest").option("--skip-skills","只更新 CLI,跳过 Skill 同步").addOption(new L("--package-manager <packageManager>","指定全局安装使用的包管理器").choices(nM)).addHelpText("after","\n说明:\n 默认安装 latest;目标版本与当前版本一致时会跳过 CLI 安装\n 默认同步随包发布的 Skill;只想更新 CLI 时使用 --skip-skills\n 未指定包管理器时,会根据当前环境识别;识别失败时需显式传入 --package-manager\n\n示例:\n $ dymg update\n $ dymg update --target-version 1.2.3\n $ dymg update --package-manager pnpm\n $ dymg update --skip-skills").action(aY),c),v=!1,C=!1,D=!1,B=()=>{C&&cg(),C=!0,process.exitCode=130;let e=nN();v&&e||cg();let t=setTimeout(()=>{cg()},200);cm({...e,durationMs:Date.now()-_,success:!1,errorMessage:"命令已中断",errorCode:ti()?.errorCode}).finally(()=>{clearTimeout(t),cg()})};process.once("SIGINT",B),process.once("SIGTERM",B),b.hook("preAction",(e,t)=>{var r,i,n;let u,o;v=!0,r=t,D=!cf.has(function(e){let t=e;for(;t.parent&&"dymg"!==t.parent.name();)t=t.parent;return t.name()}(r)),i=t,n=E,u=i.optsWithGlobals(),o=function(e){let t=[],r=e;for(;r&&r.parent;)t.unshift(r.name()),r=r.parent;return t}(i),tr({caller:"string"==typeof u.caller&&nC(u.caller)?u.caller:"unknown",tool:o.join(" ")||function(e){if(e.includes("-V")||e.includes("--version"))return"version";let t=e.filter(e=>!e.startsWith("-"));return 0===t.length?e.some(e=>"-h"===e||"--help"===e)?"help":"root":(t[0],t.slice(0,2).join(" "))}(n),requestParams:F(u),errorMessage:void 0,errorCode:void 0})});try{await b.parseAsync(e);let t=nN();if(v&&t){let e=0===Number(process.exitCode??0);await cm({...t,durationMs:Date.now()-_,success:e,errorMessage:e?void 0:ti()?.errorMessage,errorCode:e?void 0:ti()?.errorCode})}v&&D&&0===Number(process.exitCode??0)&&await nZ()}catch(r){let e=r instanceof Error?r.message:String(r),t=nN();if(r instanceof w){process.exitCode=r.exitCode,v&&t&&await cm({...t,durationMs:Date.now()-_,success:0===r.exitCode,errorMessage:0===r.exitCode?void 0:e,errorCode:0===r.exitCode?void 0:n$(r)});return}throw v&&t&&await cm({...t,durationMs:Date.now()-_,success:!1,errorMessage:e,errorCode:n$(r)}),r}finally{process.removeListener("SIGINT",B),process.removeListener("SIGTERM",B)}}(async function(e=process.argv){var t,r;return t={},r=()=>cA(e),tt.run(t,r)})().then(async()=>{await E(Number(process.exitCode??0))}).catch(async e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
|
|
156
|
+
- ${e5} --open-browser`).action(oM),d.command("status").description("查看当前登录状态").option("--json","以 JSON 输出登录状态").action(oV),d.command("logout").description("退出当前登录").action(oH),d.command("check-dir-writable").description("用于 Agent 测试执行环境中的当前登录态目录是否可写,并输出结构化结果").addHelpText("after","\n示例:\n $ dymg auth check-dir-writable").action(oz),nS(r.command("game").description("游戏基础信息").command("game-list").description("查询有权限的游戏列表,包括 App ID、游戏名称").option("--page-index <n>","页码,从 1 开始","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("game:game-list",r,async()=>{var e;let t,i,n;ra(r.pageIndex,"--page-index",1,1e4),ra(r.pageSize,"--page-size",1,100);let u={pageIndex:rA(r.pageIndex,1),pageSize:rA(r.pageSize,20)},o=await (e=u,t=n1.genBaseURL("/platform_openapi/microgame/v1/game/query_game_list"),i={pageIndex:e.pageIndex,pageSize:e.pageSize},n={X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),s=eK(o),a=(s?.list??[]).map(e=>({appId:e.appId,appName:e.appName}));return{rawResponse:o,rows:a,csvHeader:["appId","appName"],resultMeta:iy({returnedCount:a.length,total:s?.total,page:u.pageIndex,pageSize:u.pageSize})}})}),p=r.command("insight").description("资讯与榜单"),nS(p.command("ranking-list").description("查询小游戏排行榜:榜单 Top N、排名、变化趋势、品类、标签等").requiredOption("--rank-type <n>","榜单类型:1 热门 / 2 畅销 / 3 新游 / 4 发行人热度榜").option("--game-business-list <list>","变现类型列表,逗号分隔:1 IAA / 2 IAP / 3 IAAP").option("--game-type-list <list>","游戏类型/分类标签 ID 列表,逗号分隔").option("--only-my-game","是否只查询当前账号有权限的游戏",!1).option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("insight:ranking-list",r,async()=>{var e;let t,i,n;rn(r.rankType,"--rank-type",rv(ll)),ru(r.gameBusinessList,"--game-business-list",rv(lc)),ru(r.gameTypeList,"--game-type-list",lm),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,200);let u=rA(r.page,1),o=rA(r.pageSize,20),s=u*o;if(s>200)throw new l("榜单仅支持查询前 200 名",{error:"OUT_OF_RANK_LIMIT",message:`榜单仅支持前 200 名,当前页末位排名 ${s} 已超出范围`});let a=await (e={gameBusinessList:rm(r.gameBusinessList),gameTypeList:rf(r.gameTypeList),onlyMyGame:r.onlyMyGame,rankType:rA(r.rankType,0),page:String(u),pageSize:String(o),meta:await nT("insight:ranking-list")},t=n1.genBaseURL("/platform_openapi/microgame/v1/insight/query_game_rank"),i={gameBusinessList:e.gameBusinessList,gameTypeList:e.gameTypeList,meta:e.meta,onlyMyGame:e.onlyMyGame,page:e.page,pageSize:e.pageSize,rankType:e.rankType},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),c=eK(a),d=(c?.items??[]).map(e=>({index:e.index,name:e.name,category:e.category,rankingChange:e.rankingChange}));return{rawResponse:a,rows:d,csvHeader:["index","name","category","rankingChange"],resultMeta:iy({returnedCount:d.length,total:c?.page?.total,page:c?.page?.page,pageSize:c?.page?.pageSize,hasMore:c?.page?.hasMore,nextCursor:c?.page?.nextSearchAfter})}})}),nS(p.command("hotspot-list").description("查询适合游戏化的热点信息,包括热点词、关联视频链接、热度值、热点洞察等").option("--game-type-ids <list>","游戏类型/分类标签 ID 列表,逗号分隔").option("--keyword <keyword>","关键词筛选").option("--top-n <n>","返回条数").option("--topic-ids <list>","题材 ID 列表,逗号分隔")).action(async(e,t)=>{let r=nx(t,e);await oc("insight:hotspot-list",r,async()=>{var e;let t,i,n,u;ru(r.gameTypeIds,"--game-type-ids",lm);let o=(e=r,!!(e.keyword?.trim()||rf(e.gameTypeIds)?.length||rf(e.topicIds)?.length));ra(r.topN,"--top-n",1,o?50:100);let s=r.topN??(o?String(50):void 0),a=await (t={gameTypeIds:rf(r.gameTypeIds),keyword:r.keyword?.trim()||void 0,meta:await nT("insight:hotspot-list"),topN:s,topicIds:rf(r.topicIds)},i=n1.genBaseURL("/platform_openapi/microgame/v1/insight/query_douyin_hotspots"),n={gameTypeIds:t.gameTypeIds,keyword:t.keyword,meta:t.meta,topN:t.topN,topicIds:t.topicIds},u={X_Tt_Appid:t.X_Tt_Appid,X_Tt_Userid:t.X_Tt_Userid},n1.request({url:i,method:"POST",data:n,headers:u},void 0)),l=eK(a);return{rawResponse:a,rows:(l?.items??[]).map(e=>({title:e.title,hotValue:e.hotValue,topics:lg(e.topics),hotInsights:e.hotInsights,jumpUrl:e.jumpUrl,contentId:e.contentId,coverUrl:e.coverUrl,playUrl:e.playUrl,contentTags:lg(e.contentTags),gamificationCategories:lg(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:lg(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:lg(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:lg(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),commentSummary:e.commentSummary,topComments:lg(e.topComments,e=>`${e.content??""}:${e.likeCount??""}`),dataStatus:e.dataStatus})),csvHeader:lp}})}),nS(p.command("element-list").description("查询热门元素,包括元素名称、标签、热度、关联热点和视频信息").option("--element-type <type>","元素类型筛选").option("--hotspot-id <id>","热点 ID").option("--keyword <keyword>","关键词筛选").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20").option("--video-id <id>","视频 ID")).action(async(e,t)=>{let r=nx(t,e);await oc("insight:element-list",r,async()=>{let e,t,i;rl(r.hotspotId,"--hotspot-id"),rn(r.elementType,"--element-type",lf),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,50);let n=rA(r.page,1),u=rA(r.pageSize,20),o=await (e={elementType:r.elementType,hotspotId:r.hotspotId,keyword:r.keyword?.trim()||void 0,page:n,pageSize:u,videoId:r.videoId},t=n1.genBaseURL("/platform_openapi/microgame/v1/insight/query_hot_elements"),i={elementType:e.elementType,hotspotId:e.hotspotId,keyword:e.keyword,page:e.page,pageSize:e.pageSize,recommendedUse:e.recommendedUse,suitableGenre:e.suitableGenre,videoId:e.videoId},n1.request({url:t,method:"POST",data:i},void 0)),s=eK(o),a=(s?.items??[]).map(e=>({elementId:e.elementId,elementName:e.elementName,elementType:e.elementType,hotValue:e.hotValue,dataStatus:e.dataStatus,hotspotId:e.hotspotId,videoId:e.videoId,elementTags:lg(e.elementTags),description:e.description,heatTrend:lg(e.heatTrend,e=>`${rb(e.timestamp,{format:"date"})}:${e.hotScore??""}`)}));return{rawResponse:o,rows:a,csvHeader:ld,resultMeta:iy({returnedCount:a.length,total:s?.total,page:s?.page??n,pageSize:s?.pageSize??u,hasMore:s?.hasMore})}})}),nS(p.command("theme-list").description("查询热门题材,包括题材概览、市场机会、关联游戏、近期热点和趋势信息").option("--include-top-videos","是否返回头部视频信息",!1).option("--page <n>","页码","1").option("--page-size <n>","每页条数","20").option("--parent-topic-id <id>","父题材 ID").option("--topic-id-list <list>","题材 ID 列表,逗号分隔")).action(async(e,t)=>{let r=nx(t,e);await oc("insight:theme-list",r,async()=>{let e,t,i;rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,50);let n=rA(r.page,1),u=rA(r.pageSize,20),o=await (e={includeTopVideos:r.includeTopVideos,page:n,pageSize:u,parentTopicId:r.parentTopicId,topicIdList:rf(r.topicIdList)},t=n1.genBaseURL("/platform_openapi/microgame/v1/insight/query_hot_topics"),i={includeTopVideos:e.includeTopVideos,page:e.page,pageSize:e.pageSize,parentTopicId:e.parentTopicId,topicIdList:e.topicIdList},n1.request({url:t,method:"POST",data:i},void 0)),s=eK(o),a=(s?.items??[]).map(e=>({topicId:e.topicId,topicName:e.topicName,parentTopicId:e.parentTopicId,parentTopicName:e.parentTopicName,dataStatus:e.dataStatus,topicOverview:e.topicOverview,marketOpportunitySummary:e.marketOpportunity?.summary,gamificationCategories:lg(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:lg(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:lg(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:lg(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),audiencePreferences:lg(e.userFeatures?.audiencePreferences,e=>`${e.title??""}:${e.insight??""}`),contentPreferences:lg(e.userFeatures?.contentPreferences,e=>`${e.title??""}:${e.insight??""}`),interactionPreferences:lg(e.userFeatures?.interactionPreferences,e=>`${e.title??""}:${e.insight??""}`),relatedGames:function(e){if(e?.length)return F(e.map(e=>({gameId:e.gameId,gameName:e.gameName,iconUrl:e.iconUrl,jumpUrl:e.jumpUrl,heatValue:e.heatValue})))}(e.relatedGames),recentHotspots:lg(e.recentHotspots,e=>`${e.title??""}:${e.heatValue??""}`),topVideos:lg(e.topVideos,e=>`${e.video?.title??""}:${e.likeCount??""}`),trend7D:lg(e.trend7D,e=>`${rb(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend30D:lg(e.trend30D,e=>`${rb(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend90D:lg(e.trend90D,e=>`${rb(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`)}));return{rawResponse:o,rows:a,csvHeader:lh,resultMeta:iy({returnedCount:a.length,total:s?.total,page:n,pageSize:u,hasMore:s?.hasMore})}})}),h=r.command("analytics").description("用户数据"),nS(nI(h.command("behavior-query").description("查询用户的活跃用户、新增用户、累计用户、启动次数、游戏时长等行为指标,支持 App、操作系统等筛选"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:behavior-query",r,async()=>{var e;let t,i,n;oI(r),oO(r);let u=await (e={X_Tt_Appid:r.appId,filter:oD(r),meta:await nT("analytics:behavior-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_user_behavior"),i={filter:e.filter,meta:e.meta},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u),s=(o?.items??[]).map(e=>({...e,recordType:"data"}));return{rawResponse:u,rows:[...s,...o?.summary?[{...o.summary,recordType:"summary"}]:[]],csvHeader:oF}})}),nS(nI(h.command("realtime-query").description("查询游戏当天的实时访问人数和访问次数"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:realtime-query",r,async()=>{var e;let t,i,n;rd({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:oy,label:"实时数据"}),oO(r);let u=await (e={X_Tt_Appid:r.appId,filter:oD(r),meta:await nT("analytics:realtime-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_realtime_user"),i={filter:e.filter,meta:e.meta},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:(o?.items??[]).map(e=>({hour:e.hour,activeUser:e.activeUser,openTime:e.openTime})),csvHeader:ow}})}),nS(nI(h.command("retention-query").description("查询用户的次日、3 日、14 日、30 日留存率,支持筛选日期、App、操作系统、用户类型等").option("--retention-scene <n>","留存场景:1 全量 / 2 侧边栏"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:retention-query",r,async()=>{var e;let t,i,n;oI(r),oO(r),rn(r.retentionScene,"--retention-scene",rv(om));let u=await (e={X_Tt_Appid:r.appId,filter:oD(r),retentionScene:void 0===r.retentionScene?void 0:rA(r.retentionScene,0),meta:await nT("analytics:retention-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_user_retention"),i={filter:e.filter,meta:e.meta,retentionScene:e.retentionScene},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:(o?.items??[]).map(e=>({...e})),csvHeader:oB}})}),nS(nI(h.command("source-query").description("查询不同来源渠道下的活跃用户、新增用户数、启动次数、次均游戏时长等").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:source-query",r,async()=>{var e;let t,i,n;oI(r),oO(r),ra(r.topN,"--top-n",1,100);let u=await (e={X_Tt_Appid:r.appId,filter:oD(r),topN:r.topN,meta:await nT("analytics:source-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_user_source"),i={filter:e.filter,meta:e.meta,topN:e.topN},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:(o?.items??[]).flatMap(e=>{let t=e.dates??[];return(t.length>0?t:[""]).map((t,r)=>({sceneId:e.sceneId,sceneName:e.sceneName,date:t,uv:e.uvData?.[r],newUv:e.newUvData?.[r],openTime:e.openTimeData?.[r],stayPv:e.stayPvData?.[r],avgStayTime:e.avgStayTimeData?.[r],avgStayTimeStr:e.avgStayTimeStrData?.[r],totalUv:e.uv,totalNewUv:e.newUv,totalOpenTime:e.openTime,totalStayPv:e.stayPv,totalAvgStayTime:e.avgStayTime,totalAvgStayTimeStr:e.avgStayTimeStr}))}),csvHeader:ox}})}),nS(nI(h.command("profile-query").description("查询用户的性别、年龄、地域分布,区分不同 App、活跃/新增用户类型"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:profile-query",r,async()=>{var e;let t,i,n;oI(r),oO(r);let u=await (e={X_Tt_Appid:r.appId,filter:oD(r),meta:await nT("analytics:profile-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_user_portrait"),i={filter:e.filter,meta:e.meta},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:[{dimension:"age",items:o?.age},{dimension:"city",items:o?.city},{dimension:"gender",items:o?.gender},{dimension:"province",items:o?.province}].flatMap(({dimension:e,items:t})=>(t??[]).map(t=>({dimension:e,name:t.name,value:t.value,ratio:t.ratio,total:o?.total}))),csvHeader:oS}})}),nS(nI(h.command("device-query").description("查询用户的机型、品牌、客户端版本、基础库版本分布等").requiredOption("--dimension <n>","维度:1 型号 / 2 品牌 / 3 宿主版本 / 4 基础库版本").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=nx(t,e);await oc("analytics:device-query",r,async()=>{var e;let t,i,n;oI(r),oO(r),rn(r.dimension,"--dimension",rv(og)),ra(r.topN,"--top-n",1,100);let u=rA(r.dimension,0),o=await (e={X_Tt_Appid:r.appId,dimension:u,filter:oD(r),topN:r.topN,meta:await nT("analytics:device-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/user/query_user_terminal"),i={dimension:e.dimension,filter:e.filter,meta:e.meta,topN:e.topN},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),s=eK(o);return{rawResponse:o,rows:(s?.items??[]).map(e=>({dimension:s?.dimension,name:e.name,value:e.value,ratio:e.ratio,total:s?.total})),csvHeader:oT}})}),nS(r.command("growth").description("增长数据").command("metric-query").description("查询分渠道的新增激活用户数据及其对应的后效指标(变现人数、ECPM、收入、成本等);区分离线与实时口径").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--activate-start-date <date>","激活开始日期 YYYY-MM-DD").requiredOption("--activate-end-date <date>","激活结束日期 YYYY-MM-DD").requiredOption("--dimension <list>","维度枚举,逗号分隔").requiredOption("--metric <list>","指标枚举,逗号分隔").option("--life-time <rule>","生命周期配置,可重复传入;格式为 <指标枚举>:<生命周期天数列表>,例如 11:7,14,30",ls,[]).requiredOption("--first-channel <list>","一级渠道枚举,逗号分隔").requiredOption("--freshness-type <n>","数据时效:1 实时 / 2 离线").option("--second-channel <list>","二级渠道枚举,逗号分隔").option("--download","是否返回下载链接",!1).addHelpText("after",lo)).action(async(e,t)=>{let r=nx(t,e);await oc("growth:metric-query",r,async()=>{let e,t,i;ru(r.dimension,"--dimension",rv(a4)),ru(r.metric,"--metric",rv(a7)),rn(r.freshnessType,"--freshness-type",rv(a9)),ru(r.firstChannel,"--first-channel",rv(a8)),ru(r.secondChannel,"--second-channel",rv(a5));let n=rA(r.freshnessType,0),u=n===a9.RealTime;rd({startDate:r.activateStartDate,endDate:r.activateEndDate,maxLookbackDays:u?oE:o_,label:u?"增长实时数据":"增长离线数据",startField:"--activate-start-date",endField:"--activate-end-date"});let o=rm(r.dimension)??[],s=rm(r.metric)??[],a=rm(r.firstChannel)??[],c=rm(r.secondChannel);if(0===o.length)throw new l("growth:metric-query 缺少有效维度",{error:"INVALID_DIMENSION",message:"--dimension 至少需要传入一个有效的维度枚举值"});if(0===s.length)throw new l("growth:metric-query 缺少有效指标",{error:"INVALID_METRIC",message:"--metric 至少需要传入一个有效的指标枚举值"});if(0===a.length)throw new l("growth:metric-query 缺少有效一级渠道",{error:"INVALID_FIRST_CHANNEL",message:"--first-channel 至少需要传入一个有效的一级渠道枚举值"});let d=function(e,t,r){let i=new Map;if(!e||0===e.length)return i;let n=new Set(t),u=rv(a7),o=la(r),s=r===a9.RealTime?"实时口径":"离线口径";for(let t of e){var a,c;let e=t.split(":");if(2!==e.length)throw new l("growth:metric-query lifeTime 格式非法",{error:"INVALID_LIFE_TIME",message:"--life-time 格式必须为 <指标枚举>:<生命周期天数列表>,例如 --life-time 11:7,14,30"});let[d,p]=e.map(e=>e.trim());if(!u.includes(d))throw new l("growth:metric-query lifeTime 指标非法",{error:"INVALID_LIFE_TIME",message:`--life-time 中的指标必须是 1-30 的合法指标枚举,当前值为 ${d}`});let h=rA(d,0),f=(a=r,c=h,a===a9.RealTime?le:c===a7.TotalROI?lr:lt),m=new Set(f);if(!n.has(h))throw new l("growth:metric-query lifeTime 指标未出现在 metric 中",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}:... 只能配置已经出现在 --metric 中的指标`});if(i.has(h))throw new l("growth:metric-query lifeTime 指标重复配置",{error:"INVALID_LIFE_TIME",message:`指标 ${d} 的 --life-time 只能配置一次;多个天数请写在同一个参数里,例如 --life-time ${d}:${o}`});let g=rf(p)??[];if(0===g.length)throw new l("growth:metric-query lifeTime 缺少生命周期列表",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}: 缺少生命周期天数列表,例如 --life-time ${d}:${o}`});let A=[],y=new Set;for(let e of g){let t=rE(e);if(void 0===t)throw new l("growth:metric-query lifeTime 含有非法天数",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}:${p} 中的生命周期天数必须是正整数`});let r=String(t);if(y.has(r))throw new l("growth:metric-query lifeTime 含有重复天数",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}:${p} 中的生命周期天数不能重复`});if(!m.has(r))throw new l("growth:metric-query lifeTime 超出当前口径范围",{error:"INVALID_LIFE_TIME",message:`${s}下 --life-time 只支持 ${f.join(",")}`});y.add(r),A.push(r)}i.set(h,A)}return i}(r.lifeTime,s,n);var p,h=s,f=d,m=n;let g=la(m);for(let e of h){let t=rD(a7,e),r=f.get(e);if(li.has(e)){if(r&&(1!==r.length||"1"!==r[0]))throw new l("growth:metric-query 首日指标 lifeTime 非法",{error:"INVALID_LIFE_TIME",message:`指标 ${e}(${t}) 是首日指标,可以不传 --life-time;如果传,只能写 --life-time ${e}:1`});continue}if(!r||0===r.length)throw new l("growth:metric-query 非首日指标缺少 lifeTime",{error:"INVALID_LIFE_TIME",message:`指标 ${e}(${t}) 需要生命周期天数,请补充 --life-time ${e}:${g}`})}!function(e,t){if(!t||0===t.length)return;let r=new Set(e.flatMap(e=>lu[e]??[])),i=t.filter(e=>!r.has(e));if(0!==i.length)throw new l("growth:metric-query 二级渠道与一级渠道不匹配",{error:"INVALID_SECOND_CHANNEL",message:`--second-channel ${i.join(",")} 与 --first-channel 不匹配;广告激活(1) 只对应广告(1),星图激活(2) 对应星图-直播/视频(2,3),发行人激活(3) 对应发行人-直播/视频(4,5),自然激活(4) 对应自然各场景(6~21)`})}(a,c);let A=s.map(e=>{let t=d.get(e);return t?{metric:e,lifeTime:t}:{metric:e}}),y=await (p={X_Tt_Appid:r.appId,activateStartDate:r.activateStartDate,activateEndDate:r.activateEndDate,dimension:o,metric:A,freshnessType:n,firstChannel:a,secondChannel:c,download:r.download,meta:await nT("growth:metric-query")},e=n1.genBaseURL("/platform_openapi/microgame/v1/growth/query_growth_spread_sheet"),t={activateEndDate:p.activateEndDate,activateStartDate:p.activateStartDate,dimension:p.dimension,download:p.download,firstChannel:p.firstChannel,freshnessType:p.freshnessType,meta:p.meta,metric:p.metric,secondChannel:p.secondChannel},i={X_Tt_Appid:p.X_Tt_Appid,X_Tt_Userid:p.X_Tt_Userid},n1.request({url:e,method:"POST",data:t,headers:i},void 0)),E=eK(y),_=o.flatMap(e=>e===a4.ActivateDate?["activateDate"]:e===a4.FirstChannel?["firstChannel"]:[]),b=A.flatMap(({metric:e,lifeTime:t})=>{let r=rD(a7,e);return t?.length?t.map(t=>({metric:e,metricName:r,lifeTime:t})):[{metric:e,metricName:r,lifeTime:""}]});return{rawResponse:y,rows:(E?.results??[]).flatMap(e=>{let t={};return o.forEach((r,i)=>{let n=e.dimensionValue?.[i]??"";if(r===a4.ActivateDate){t.activateDate=n;return}r===a4.FirstChannel&&(t.firstChannel=n)}),b.map(({metric:r,metricName:i,lifeTime:n},u)=>({...t,metric:r,metricName:i,lifeTime:n,value:e.indicatorValue?.[u]??""}))}),csvHeader:[..._,...ln]}})}),A=r.command("feedback").description("用户反馈与未成年人退款工单"),nS(A.command("refund-list").description("查询未成年人退款工单、处理状态、截止时间和订单信息").requiredOption("--app-id <appId>","小游戏 appId").option("--start-time <ts>","开始时间,秒级 Unix 时间戳,不能晚于当前时间").option("--end-time <ts>","结束时间,秒级 Unix 时间戳,不能晚于当前时间").option("--resolve-status <n>","处理状态:1 未处理 / 2 已处理").option("--open-id <openId>","用户 OpenID").option("--ticket-id <id>","退款工单 ID").option("--page <n>","页码","1").option("--limit <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("feedback:refund-list",r,async()=>{var e;let t,i,n;rh({startTime:r.startTime,endTime:r.endTime,unit:"seconds",allowFuture:!1}),rn(r.resolveStatus,"--resolve-status",[String(a3.UNRESOLVED),String(a3.RESOLVED)]),rl(r.ticketId,"--ticket-id"),rl(r.page,"--page"),ra(r.limit,"--limit",1,100);let u=r.page??"1",o=r.limit??"20",s=await (e={X_Tt_Appid:r.appId,startTime:r.startTime,endTime:r.endTime,resolveStatus:rC(r.resolveStatus,a3),openId:r.openId,ticketId:r.ticketId,page:u,limit:o},t=n1.genBaseURL("/platform_openapi/microgame/v1/feedback/query_refund"),i={endTime:e.endTime,limit:e.limit,openId:e.openId,page:e.page,resolveStatus:e.resolveStatus,startTime:e.startTime,ticketId:e.ticketId},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eK(s),l=(a?.list??[]).map(e=>({ticketId:e.ticketId,openId:e.openId,content:e.content,createTime:e.createTime,updateTime:e.updateTime,deadlineTime:e.deadlineTime,resolveDuration:e.resolveDuration,auditStatus:e.auditStatus,auditStatusText:e.auditStatusText,minorRefundStatus:e.minorRefundStatus,minorRefundStatusText:e.minorRefundStatusText,devReplyText:e.devReplyText,userHasMoreRefund:e.userHasMoreRefund,ageRange:e.ageRange,orderList:F((e.orderList??[]).map(e=>({createTime:e.createTime,orderId:e.orderId,orderName:e.orderName,orderPrice:ry(e.orderPriceCny),orderPriceDiamond:e.orderPriceDiamond,refund:ry(e.refundCny),refundDiamond:e.refundDiamond}))),imageList:F(e.imageList??[]),rejectReasonList:F(e.rejectReasonList??[]),logUrl:e.logUrl}));return{rawResponse:s,rows:l,csvHeader:a6,resultMeta:iy({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nS(A.command("feedback-list").description("按时间、类型、运行平台、客户端版本、状态、用户或内容查询用户反馈").requiredOption("--app-id <appId>","小游戏 appId").option("--start-time <ts>","开始时间,秒级 Unix 时间戳,不能晚于当前时间").option("--end-time <ts>","结束时间,秒级 Unix 时间戳,不能晚于当前时间").option("--dealt-status-list <list>","处理状态列表,逗号分隔:0 待处理 / 1 超时 / 2 已解决 / 3 处理中 / 100 无需处理").option("--label-id-list <list>","反馈类型 ID 列表,逗号分隔").option("--aid-list <list>","运行平台 ID 列表,逗号分隔").option("--app-version <list>","客户端版本列表,逗号分隔").option("--mark-status <n>","重要反馈状态:3 重要 / 4 非重要").option("--feedback-id <id>","反馈 ID").option("--open-id <openId>","用户 OpenID").option("--search-content <text>","反馈内容关键词").option("--order-rule <n>","排序字段:1 提交时间 / 2 超时时间").option("--current-page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("feedback:feedback-list",r,async()=>{var e;let t,i,n,u;rh({startTime:r.startTime,endTime:r.endTime,unit:"seconds",allowFuture:!1}),ru(r.dealtStatusList,"--dealt-status-list",rv(aQ)),a2(r.labelIdList,"--label-id-list"),a2(r.aidList,"--aid-list"),rn(r.markStatus,"--mark-status",a0),rl(r.feedbackId,"--feedback-id"),rn(r.orderRule,"--order-rule",rv(aZ)),rl(r.currentPage,"--current-page"),ra(r.pageSize,"--page-size",1,100);let o=rA(r.currentPage,1),s=rA(r.pageSize,20),a=await (e={X_Tt_Appid:r.appId,startTime:void 0===r.startTime?void 0:rA(r.startTime,0),endTime:void 0===r.endTime?void 0:rA(r.endTime,0),dealtStatusList:rm(r.dealtStatusList),labelIdList:rm(r.labelIdList),aidList:rm(r.aidList),appVersion:rf(r.appVersion),markStatus:void 0===r.markStatus?void 0:rA(r.markStatus,0),feedbackId:r.feedbackId,openId:r.openId,searchContent:r.searchContent,orderRule:rC(r.orderRule,aZ),currentPage:o,pageSize:s},t=n1.genBaseURL("/platform_openapi/microgame/v1/feedback/query_feedback"),i={appVersion:e.appVersion,did:e.did,os:e.os},n={aid:e.aid,aidList:e.aidList,currentPage:e.currentPage,dealtStatus:e.dealtStatus,dealtStatusList:e.dealtStatusList,endTime:e.endTime,feedbackId:e.feedbackId,feedbackIdList:e.feedbackIdList,isAsc:e.isAsc,isNeedReply:e.isNeedReply,isValidLabel:e.isValidLabel,label1Id:e.label1Id,labelId:e.labelId,labelIdList:e.labelIdList,markStatus:e.markStatus,needChildId:e.needChildId,onlyParentId:e.onlyParentId,openId:e.openId,orderRule:e.orderRule,pageSize:e.pageSize,searchContent:e.searchContent,startTime:e.startTime},u={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",data:i,params:n,headers:u},void 0)),l=eK(a),c=(l?.feedbackList??[]).map(e=>({feedbackId:e.feedbackId,openId:e.openId,content:e.content,createTime:e.createTime,dealtStatus:e.dealtStatus,dealtAction:e.dealtAction,dealtComment:e.dealtComment,dealtTime:e.dealtTime,dealtDdl:e.dealtDdl,hasReply:e.hasReply,isImportant:e.isImportant,isRead:e.isRead,appVersion:e.appVersion,microAppVersion:e.microAppVersion,libraryVersion:e.libraryVersion,platform:e.platform,device:e.device,deviceId:e.deviceId,osVersion:e.osVersion,labelName:e.labelName,label1Name:e.label1Name,isRefund:e.isRefund,imageUrlList:F(e.imageUrlList),logDownloadUrl:e.logDownloadUrl}));return{rawResponse:a,rows:c,csvHeader:a1,resultMeta:iy({returnedCount:c.length,total:l?.total,page:o,pageSize:s})}})}),f=r.command("revenue").description("商业化"),nS((i=f).command("traffic-status").description("检查小游戏是否具备开通流量主的权限、签约和主体资质").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:traffic-status",r,async()=>{var e;let t,i,n=await (e={X_Tt_Appid:r.appId},t=n1.genBaseURL("/platform_openapi/microgame/v1/ad/query_traffic_status"),i={X_Tt_Appid:(e||{}).X_Tt_Appid},n1.request({url:t,method:"GET",headers:i},void 0));return eK(n),{rawResponse:n}})}),nS(i.command("placement-list").description("查询当前小游戏的广告位及其类型、开关和封禁状态").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:placement-list",r,async()=>{var e;let t,i,n=await (e={X_Tt_Appid:r.appId},t=n1.genBaseURL("/platform_openapi/microgame/v1/ad/query_placement"),i={X_Tt_Appid:(e||{}).X_Tt_Appid},n1.request({url:t,method:"GET",headers:i},void 0)),u=eK(n);return{rawResponse:n,rows:(u?.ads??[]).map(e=>({adId:e.adId,name:e.name,type:e.type,adStatus:e.adStatus,adBanStatus:e.adBanStatus})),csvHeader:["adId","name","type","adStatus","adBanStatus"]}})}),nS((n=f).command("ad-income-query").description("查询流量主广告收入总览和按日趋势").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD,最早为最近 365 天").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD,最晚为昨天").option("--ad-position-types <list>","广告位类型:1 Banner / 2 激励视频 / 3 插屏 / 4 游戏化电商").option("--hosts <list>","宿主:1 全部 / 2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山 / 9 皮皮虾").option("--os <n>","操作系统:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony / 5 Windows").option("--activate-type <n>","归因类型:1 广告 / 2 星图 / 3 发行人 / 4 自然")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:ad-income-query",r,async()=>{var e;let t,i,n;rd({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:ob,latestDateOffsetDays:1,label:"广告收入"}),ru(r.adPositionTypes,"--ad-position-types",rv(l1)),ru(r.hosts,"--hosts",rv(l0)),rn(r.os,"--os",rv(l2)),rn(r.activateType,"--activate-type",rv(l3));let u=await (e={X_Tt_Appid:r.appId,startDate:r.startDate,endDate:r.endDate,adPositionTypes:rm(r.adPositionTypes),hosts:rg(r.hosts,"--hosts",l0.All),os:rC(r.os,l2),activateType:rC(r.activateType,l3),fromAppPlatform:1,meta:await nT("revenue:ad-income-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/ad/query_income_overview"),i={activateType:e.activateType,adPositionTypes:e.adPositionTypes,endDate:e.endDate,fromAppPlatform:e.fromAppPlatform,hosts:e.hosts,meta:e.meta,os:e.os,startDate:e.startDate},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u),s=(e,t)=>({recordType:t,date:e?.date,requestCount:e?.requestCount,showCount:e?.showCount,clickCount:e?.clickCount,clickRate:e?.clickRate,ecpm:e?.ecpm,incomeAfterShare:e?.incomeAfterShare,incomeBeforeShare:e?.incomeBeforeShare}),a=(o?.items??[]).map(e=>s(e,"daily"));return o?.summary&&a.push(s(o.summary,"summary")),{rawResponse:u,rows:a,csvHeader:l7}})}),nS(n.command("ad-income-detail").description("按广告位和宿主分页查询流量主广告经营明细").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD,最早为最近 365 天").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD,最晚为昨天").option("--ad-position-types <list>","广告位类型:1 Banner / 2 激励视频 / 3 插屏 / 4 游戏化电商").option("--hosts <list>","宿主:1 全部 / 2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山 / 9 皮皮虾").option("--os <n>","操作系统:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony / 5 Windows").option("--activate-type <n>","归因类型:1 广告 / 2 星图 / 3 发行人 / 4 自然").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:ad-income-detail",r,async()=>{var e;let t,i,n;rd({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:ob,latestDateOffsetDays:1,label:"广告收入"}),ru(r.adPositionTypes,"--ad-position-types",rv(l6)),ru(r.hosts,"--hosts",rv(l4)),rn(r.os,"--os",rv(l8)),rn(r.activateType,"--activate-type",rv(l9)),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100);let u=r.page??"1",o=r.pageSize??"20",s=await (e={X_Tt_Appid:r.appId,startDate:r.startDate,endDate:r.endDate,adPositionTypes:rm(r.adPositionTypes),hosts:rg(r.hosts,"--hosts",l4.All),os:rC(r.os,l8),activateType:rC(r.activateType,l9),fromAppPlatform:1,meta:await nT("revenue:ad-income-detail"),page:u,pageSize:o},t=n1.genBaseURL("/platform_openapi/microgame/v1/ad/query_income_detail"),i={activateType:e.activateType,adPositionTypes:e.adPositionTypes,endDate:e.endDate,fromAppPlatform:e.fromAppPlatform,hosts:e.hosts,meta:e.meta,os:e.os,page:e.page,pageSize:e.pageSize,startDate:e.startDate},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),a=eK(s),l=(a?.items??[]).map(e=>({date:e.date,ritId:e.ritId,ritName:e.ritName,hostName:e.hostName,requestCount:e.requestCount,showCount:e.showCount,clickCount:e.clickCount,clickRate:e.clickRate,ecpm:e.ecpm,incomeAfterShare:e.incomeAfterShare,incomeBeforeShare:e.incomeBeforeShare}));return{rawResponse:s,rows:l,csvHeader:l5,resultMeta:iy({returnedCount:l.length,total:a?.page.total,page:a?.page.page??u,pageSize:a?.page.pageSize??o,hasMore:a?.page.hasMore,nextCursor:a?.page.nextSearchAfter})}})}),nS((u=f).command("payment-status").description("查询虚拟支付权限及钻石支付、担保支付协议状态").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:payment-status",r,async()=>{let[e,t]=await Promise.all([cd(r.appId),cp(r.appId)]);return{rawResponse:{permission:e,protocols:t.map(({response:e,scene:t})=>({scene:t,...e}))}}})}),nS(ch(u.command("payment-order-list").description("按交易、订单、商品或 OpenID 查询虚拟支付流水明细")).option("--payment-status <status>","支付状态:done 完成 / canceled 取消").option("--transaction-type <type>","流水类型:recharge 充值 / pay 消费 / add 赠送 / refund 退款").option("--keyword-type <n>","关键词类型:1 交易单号 / 2 商户单号 / 3 OpenID").option("--keyword <text>","查询关键词").option("--good-type <n>","交易类型:1 游戏币 / 2 道具直购").option("--payment-channel <n>","支付渠道:1 现金 / 2 抖音钻石").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:payment-order-list",r,async()=>{var e;let t,i,n;if(rc({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),rn(r.host,"--host",["-1",...lx]),rn(r.os,"--os",co),rn(r.activateType,"--activate-type",rv(ce)),rn(r.fromAppPlatform,"--from-app-platform",rv(ct)),rn(r.goodType,"--good-type",rv(cr)),rn(r.paymentChannel,"--payment-channel",rv(ci)),rn(r.paymentStatus,"--payment-status",["done","canceled"]),rn(r.transactionType,"--transaction-type",["recharge","pay","add","refund"]),ra(r.keywordType,"--keyword-type",1,3),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100),!!r.keyword!=!!r.keywordType)throw new l("--keyword-type 与 --keyword 必须同时提供",{error:rt.InvalidRange,message:"--keyword-type 与 --keyword 必须同时提供"});let u=r.page??"1",o=r.pageSize??"20",s=cc(r.startDate,r.endDate)?void 0:rC(r.activateType,ce),a=r.keyword&&r.keywordType?{[rA(r.keywordType,1)]:r.keyword}:void 0,c=await (e={X_Tt_Appid:r.appId,startTime:r.startDate,endTime:r.endDate,hostId:r.host??"-1",os:r.os,activateType:s,fromAppPlatform:rC(r.fromAppPlatform,ct),payStatus:r.paymentStatus,changeType:r.transactionType,keyword:a,goodType:rC(r.goodType,cr),orderType:rC(r.paymentChannel,ci),pageNo:u,pageSize:o},t=n1.genBaseURL("/platform_openapi/microgame/v1/payment/query_order"),i={activateType:e.activateType,changeType:e.changeType,endTime:e.endTime,fromAppPlatform:e.fromAppPlatform,goodType:e.goodType,hostId:e.hostId,keyword:e.keyword,orderType:e.orderType,os:e.os,pageNo:e.pageNo,pageSize:e.pageSize,payStatus:e.payStatus,startTime:e.startTime},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),d=eK(c),p=d?.result?.[0],h=(p?.payDetail??[]).map(e=>({payTime:e.payTime,transactionNo:e.transactionNo,merchantNo:e.merchantNo,openId:e.openId,payStatus:e.payStatus,changeType:e.changeType,goodType:e.goodType,orderType:e.orderType,activateType:e.activateType,amount:e.amount,rechargeAmount:ry(e.rechargeAmountFen),isOpenPlatformRefund:e.isOpenPlatformRefund,refundFee:e.refundFee,refundFeeBeforeShare:e.refundFeeBeforeShare,refundFeeAfterShare:e.refundFeeAfterShare,refundRemark:e.refundRemark}));return{rawResponse:c,rows:h,csvHeader:ca,resultMeta:iy({returnedCount:h.length,total:p?.totalNum,page:u,pageSize:o})}})}),nS(ch(u.command("payment-income-query").description("查询虚拟支付收入总览、分成、退款和 ARPPU"))).action(async(e,t)=>{let r=nx(t,e);await oc("revenue:payment-income-query",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),rn(r.host,"--host",["-1",...lx]),rn(r.os,"--os",co),rn(r.activateType,"--activate-type",rv(cn)),rn(r.fromAppPlatform,"--from-app-platform",rv(cu));let u=cc(r.startDate,r.endDate)?void 0:rC(r.activateType,cn),o=await (e={X_Tt_Appid:r.appId,startTime:r.startDate,endTime:r.endDate,hostId:r.host??"-1",os:r.os,activateType:u,fromAppPlatform:rC(r.fromAppPlatform,cu)},t=n1.genBaseURL("/platform_openapi/microgame/v1/payment/query_income"),i={activateType:e.activateType,endTime:e.endTime,fromAppPlatform:e.fromAppPlatform,hostId:e.hostId,os:e.os,startTime:e.startTime},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),s=eK(o),a=s?.result?.[0],l=(e,t)=>({recordType:t,date:e?.date,payPerson:e?.payPerson,payTimes:e?.payTimes,arppu:e?.arppu,payMoney:ry(e?.payMoneyFen),payMoneyAfterShare:e?.payMoneyAfterShareDataReady?ry(e.payMoneyAfterShareFen):void 0,payMoneyAfterReduceShare:e?.payMoneyAfterReduceShareDataReady?ry(e.payMoneyAfterReduceShareFen):void 0,refundFee:e?.refundFee,refundFeeBeforeShare:e?.refundFeeBeforeShare,refundFeeAfterShare:e?.refundFeeAfterShare,payMoneyAfterShareDataReady:e?.payMoneyAfterShareDataReady,payMoneyAfterReduceShareDataReady:e?.payMoneyAfterReduceShareDataReady}),c=(a?.payOverview??[]).map(e=>l(e,"daily"));return a?.payOverviewSum&&c.push(l(a.payOverviewSum,"summary")),{rawResponse:o,rows:c,csvHeader:cs}})}),y=r.command("publisher").description("发行人计划"),nS((o=y).command("task-list").description("查询发行人推广任务列表,包括任务名称、任务状态、总消耗等").requiredOption("--app-id <appId>","小游戏 appId").option("--start-date <date>","开始日期,格式 YYYY-MM-DD,不能晚于今天").option("--end-date <date>","结束日期,格式 YYYY-MM-DD,不能晚于今天").option("--task-id <id>","任务 ID").option("--task-type <n>","任务类型:0 小游戏 / 1 微端 / 100 全部").option("--media-type <n>","内容类型:1 短视频 / 2 直播 / 100 全部").option("--web-status <n>","任务状态:1 待审核 / 2 通过 / 3 驳回 / 4 取消 / 5 预热 / 6 暂停 / 7 进行中 / 8 完成").option("--bidding-method <n>","出价方式:1 短视频 CPA / 6 CPM / 8 一口价 / 22 直播 CPA / 27 CPS / 28 CPA+CPS / 29 短视频 CPA+CPS / 30 直播 CPS").option("--task-category <n>","任务分类:0 全部 / 1 普通任务 / 2 指派任务").option("--asc","是否升序",!1).option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("publisher:task-list",r,async()=>{let e,t,i,n;rc({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),rl(r.taskId,"--task-id"),rn(r.taskType,"--task-type",rv(l$)),rn(r.mediaType,"--media-type",lq),rn(r.webStatus,"--web-status",lZ),rn(r.biddingMethod,"--bidding-method",lV),rn(r.taskCategory,"--task-category",lU),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100);let u=rA(r.page,1),o=rA(r.pageSize,20),s=await (e={X_Tt_Appid:r.appId,startDate:r.startDate?.replaceAll("-",""),endDate:r.endDate?.replaceAll("-",""),taskId:r.taskId,taskType:rC(r.taskType,l$),mediaType:rC(r.mediaType,lj),webStatus:rC(r.webStatus,lM),biddingMethod:rC(r.biddingMethod,lN),taskCategory:void 0===r.taskCategory?void 0:rA(r.taskCategory,0),asc:r.asc,offset:String((u-1)*o),limit:String(o)},t=n1.genBaseURL("/platform_openapi/microgame/v1/publisher/query_task"),i={asc:e.asc,biddingMethod:e.biddingMethod,endDate:e.endDate,limit:e.limit,mediaType:e.mediaType,offset:e.offset,orderBy:e.orderBy,startDate:e.startDate,taskCategory:e.taskCategory,taskId:e.taskId,taskType:e.taskType,webStatus:e.webStatus},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eK(s),l=(a?.summaryStats??[]).map(e=>{let t=e.taskId?a?.taskInfoMap?.[e.taskId]:void 0;return{taskId:e.taskId,taskName:t?.taskName,taskType:e.taskType,taskCategory:t?.taskCategory,taskStatus:t?.taskStatus,webStatus:t?.webStatus,mediaType:t?.mediaType,startTime:t?.startTime,endTime:t?.endTime,createTime:t?.createTime,realEndTime:t?.realEndTime,budget:ry(t?.budget),prepaidFreezeAmount:ry(e.prepaidFreezeAmount),securityBudget:ry(t?.securityBudget),totalExpectedNum:t?.totalExpectedNum,expense:ry(e.expense),totalIncome:ry(e.totalIncome),cpaExpense:ry(e.cpaExpense),cpsExpense:ry(e.cpsExpense),adIncomeSettle:ry(e.adIncomeSettle),orderIncomeSettle:ry(e.orderIncomeSettle),newRegisterCnt:e.newRegisterCnt,videoPost:e.videoPost,liveRoomCnt:e.liveRoomCnt,dataProductionDate:e.dataProductionDate,bidCollections:F(t?.bidCollections??[])}});return{rawResponse:s,rows:l,csvHeader:lX,resultMeta:iy({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nS(o.command("task-detail-query").description("查询发行人任务的详情,包括总消耗数据、总收入数据、视频投稿数等").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--task-id <id>","任务 ID").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("publisher:task-detail-query",r,async()=>{let e,t,i,n;rc({startDate:r.startDate,endDate:r.endDate}),rl(r.taskId,"--task-id"),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100);let u=rA(r.page,1),o=rA(r.pageSize,20),s=await (e={X_Tt_Appid:r.appId,taskId:r.taskId,rangeStart:r.startDate.replaceAll("-",""),rangeEnd:r.endDate.replaceAll("-",""),offset:String((u-1)*o),limit:String(o)},t=n1.genBaseURL("/platform_openapi/microgame/v1/publisher/query_task_daily"),i={limit:e.limit,offset:e.offset,rangeEnd:e.rangeEnd,rangeStart:e.rangeStart,taskId:e.taskId},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eK(s),l=(a?.detailStats??[]).map(e=>({date:e.date,taskId:e.taskId,taskType:e.taskType,expense:ry(e.expense),totalIncome:ry(e.totalIncome),cpaExpense:ry(e.cpaExpense),cpsExpense:ry(e.cpsExpense),adIncomeSettle:ry(e.adIncomeSettle),adIncomeLongTail:ry(e.adIncomeLongTail),orderIncomeSettle:ry(e.orderIncomeSettle),orderIncomeLongTail:ry(e.orderIncomeLongTail),newRegisterCnt:e.newRegisterCnt,videoPost:e.videoPost,videoPostUcnt:e.videoPostUcnt,videoPlaySettle:e.videoPlaySettle,videoPlayLongTail:e.videoPlayLongTail,liveRoomCnt:e.liveRoomCnt,liveRoomUcnt:e.liveRoomUcnt,liveViewCnt:e.liveViewCnt,liveViewUcnt:e.liveViewUcnt,frozenAmount:ry(e.frozenAmount),breakdownAmount:ry(e.breakdownAmount),yesterdayDataReady:a?.yesterdayDataReady}));return{rawResponse:s,rows:l,csvHeader:lQ,resultMeta:iy({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nS((s=y).command("promotion-query").description("查询推广消耗、收入、新增激活用户数、新增激活用户成本等明细").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD").option("--metrics <list>","查询一个或两个趋势指标:1 总消耗 / 2 总收入 / 3 新增激活 / 4 组件点击","1,2").option("--media-type <n>","媒体类型:1 短视频 / 2 直播 / 100 全部")).action(async(e,t)=>{let r=nx(t,e);await oc("publisher:promotion-query",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate}),rn(r.mediaType,"--media-type",rv(lW));let[u,o]=function(e){ru(e,"--metrics",lK);let t=rm(e);if(!t||t.length<1||t.length>2)throw new l("--metrics 必须包含一个或两个趋势指标",{error:rt.InvalidEnum,message:"--metrics 必须传入一个或两个枚举值,例如 1 或 1,2"});return[t[0],t[1]??t[0]]}(r.metrics),s=await (e={X_Tt_Appid:r.appId,startDate:r.startDate,endDate:r.endDate,leftType:u,rightType:o,mediaType:rC(r.mediaType,lW)},t=n1.genBaseURL("/platform_openapi/microgame/v1/publisher/query_promotion_trend"),i={endDate:e.endDate,leftType:e.leftType,mediaType:e.mediaType,rightType:e.rightType,startDate:e.startDate},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eK(s);return{rawResponse:s,rows:(a?.list??[]).map(e=>({date:e.date,totalConsumptionAmount:ry(e.totalConsumptionAmount),totalRevenueAmount:ry(e.totalRevenueAmount),newActivationCount:e.newActivationCount,componentClickCount:e.componentClickCount})),csvHeader:["date","totalConsumptionAmount","totalRevenueAmount","newActivationCount","componentClickCount"]}})}),nS(s.command("promotion-detail-list").description("查询发行人计划各内容类型的推广费用、收入及转化明细,按日期和内容类型分页").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--start-date <date>","开始日期,格式 YYYY-MM-DD").requiredOption("--end-date <date>","结束日期,格式 YYYY-MM-DD").option("--media-type <n>","媒体类型:1 短视频 / 2 直播 / 100 全部").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("publisher:promotion-detail-list",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate}),rn(r.mediaType,"--media-type",rv(lW)),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100);let u=r.page??"1",o=r.pageSize??"20",s=await (e={X_Tt_Appid:r.appId,startDate:r.startDate,endDate:r.endDate,mediaType:rC(r.mediaType,lW),pageNo:u,pageSize:o},t=n1.genBaseURL("/platform_openapi/microgame/v1/publisher/query_promotion_detail"),i={endDate:e.endDate,mediaType:e.mediaType,pageNo:e.pageNo,pageSize:e.pageSize,startDate:e.startDate},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eK(s),l=(a?.settleDetailList??[]).map(e=>({date:e.date,mediaType:e.mediaType,totalConsumptionAmount:ry(e.totalConsumptionAmount),totalRevenueAmount:ry(e.totalRevenueAmount),newActivationCount:e.newActivationCount,firstActiveCount:e.firstActiveCount,componentExposureCount:e.componentExposureCount,componentClickCount:e.componentClickCount,componentClickThroughRate:e.componentClickThroughRate,conversionBillingConsumptionAmount:ry(e.conversionBillingConsumptionAmount),revenueBillingConsumptionAmount:ry(e.revenueBillingConsumptionAmount),revenueUserCount:e.revenueUserCount,iaaRevenueAmount:ry(e.iaaRevenueAmount),iapRevenueAmount:ry(e.iapRevenueAmount)}));return{rawResponse:s,rows:l,csvHeader:lY,resultMeta:iy({returnedCount:l.length,total:a?.totalCount,page:u,pageSize:o})}})}),nS(y.command("faction-incentive-list").description("查询公会任务的详情数据,包括各任务的出价、流水、激励比例等").requiredOption("--app-id <appId>","小游戏 appId").option("--faction-id <id>","公会 ID").option("--task-ids <list>","任务 ID 列表,逗号分隔").option("--task-types <list>","任务类型列表:0 全部 / 1 普通任务 / 2 指派任务").option("--task-statuses <list>","任务状态列表:1 进行中 / 2 已完成").option("--stat-months <list>","任务月份列表,当前月及之前 71 个月,逗号分隔",(m=new Date,`${m.getFullYear()}${String(m.getMonth()+1).padStart(2,"0")}`)).option("--content-types <list>","内容类型列表:1 短视频 / 2 直播 / 100 全部").option("--bid-types <list>","出价方式列表:-1 全部 / 1 短视频 CPA / 6 CPM / 8 一口价 / 22 直播 CPA / 27 CPS / 28 CPA+CPS / 29 短视频 CPA+CPS / 30 直播 CPS").option("--order-field <field>","排序字段").option("--order-type <n>","排序方向:1 升序 / 2 降序").option("--page <n>","页码","1").option("--page-size <n>","每页条数","20")).action(async(e,t)=>{let r=nx(t,e);await oc("publisher:faction-incentive-list",r,async()=>{let e,t,i,n;for(let e of(rl(r.factionId,"--faction-id"),rf(r.taskIds)??[]))rl(e,"--task-ids");rn(r.orderType,"--order-type",lG),rl(r.page,"--page"),ra(r.pageSize,"--page-size",1,100),ru(r.taskTypes,"--task-types",lU),ru(r.taskStatuses,"--task-statuses",lz),ru(r.contentTypes,"--content-types",lq),ru(r.bidTypes,"--bid-types",["-1",...lV]),function(e,t){var r=e,i=t;if(void 0!==r){for(let e of t8(r))if(!t7.test(e))throw new l(`参数 ${i} 包含非法月份: ${e}`,{error:"INVALID_DATE",message:`${i} 每一项必须为 YYYYMM 格式,且月份范围为 01~12`})}if(void 0===e)return;let n=new Date,u=12*n.getFullYear()+n.getMonth(),o=u-72+1;for(let r of t8(e)){let e=Number(r.slice(0,4)),i=12*e+Number(r.slice(4,6))-1;if(i>u||i<o)throw new l(`参数 ${t} 包含超出范围的月份: ${r}`,{error:"OUT_OF_LOOKBACK",message:`${t} 每一项必须位于当前月及之前 71 个月内`})}}(r.statMonths,"--stat-months");let u=r.page??"1",o=r.pageSize??"20",s=await (e={X_Tt_Appid:r.appId,factionId:r.factionId,taskIDs:rf(r.taskIds),taskTypes:rg(r.taskTypes,"--task-types",0),taskStatuses:rm(r.taskStatuses),statMonths:rm(r.statMonths),contentTypes:rg(r.contentTypes,"--content-types",100),bidTypes:rg(r.bidTypes,"--bid-types",-1),orderField:r.orderField,orderType:void 0===r.orderType?void 0:rA(r.orderType,0),pageNum:u,pageSize:o},t=n1.genBaseURL("/platform_openapi/microgame/v1/publisher/query_faction_incentive"),i={bidTypes:e.bidTypes,contentTypes:e.contentTypes,factionId:e.factionId,orderField:e.orderField,orderType:e.orderType,pageNum:e.pageNum,pageSize:e.pageSize,statMonths:e.statMonths,taskIDs:e.taskIDs,taskId:e.taskId,taskMonths:e.taskMonths,taskStatuses:e.taskStatuses,taskTypes:e.taskTypes},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"POST",params:i,headers:n},void 0)),a=eK(s),c=(a?.series??[]).map(e=>({mpId:e.mpId,mpName:e.mpName,mpCategory:e.mpCategory,taskId:e.taskId,taskName:e.taskName,taskType:e.taskType,factionId:e.factionId,factionName:e.factionName,contentType:e.contentType,bidType:e.bidType,effectiveTime:e.effectiveTime,dayCnt:e.dayCnt,metrics:F(e),extraIncentive:F(e.extraIncentive),dataUpdateTime:a?.dataUpdateTime,readyDate:a?.extra?.readyDate,readyTs:a?.extra?.readyTs}));return{rawResponse:s,rows:c,csvHeader:lH,resultMeta:iy({returnedCount:c.length,total:a?.total,page:a?.pageNum??u,pageSize:o})}})}),nS((a=r.command("ability").description("能力中心")).command("customer-service-status-query").description("查询新版抖音客服平台的开通状态").requiredOption("--app-id <appId>","小游戏 appId").addOption(new L("--type <type>","客服类型:im 抖音 IM / platform 抖音客服平台").choices(["im","platform"]))).action(async(e,t)=>{let r=nx(t,e);await oc("ability:customer-service-status-query",r,async()=>{var e,t;let i,n,u,o,s=[];return r.type&&"im"!==r.type||s.push((e={X_Tt_Appid:r.appId},i=n1.genBaseURL("/platform_openapi/microgame/v1/ability/query_im_customer_service_status"),n={X_Tt_Appid:(e||{}).X_Tt_Appid},n1.request({url:i,method:"GET",headers:n},void 0)).then(e=>(eK(e),["im",e]))),r.type&&"platform"!==r.type||s.push((t={X_Tt_Appid:r.appId},u=n1.genBaseURL("/platform_openapi/microgame/v1/ability/query_customer_service_status"),o={X_Tt_Appid:t.X_Tt_Appid},n1.request({url:u,method:"GET",headers:o},void 0)).then(e=>(eK(e),["platform",e]))),{rawResponse:Object.fromEntries(await Promise.all(s))}})}),nS(a.command("rank-list-query").description("查询当前小游戏已有的排行榜配置").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nx(t,e);await oc("ability:rank-list-query",r,async()=>{let e,t,i,n,u=await (e={X_Tt_Appid:r.appId},t=n1.genBaseURL("/platform_openapi/microgame/v1/ability/query_game_rank_components"),i={isDefault:e.isDefault,uniqueFlag:e.uniqueFlag},n={X_Tt_Appid:e.X_Tt_Appid},n1.request({url:t,method:"GET",params:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:o?.rankInfo??[],csvHeader:["uniqueFlag","shortName","updateFrequency","dataType","sortType","dataSuffix","enumValues","isDefault","updateTime"]}})}),nS(a.command("share-template-query").description("查询当前小游戏在分享设置配置的分享模板、审核状态、默认标记和驳回原因").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nx(t,e);await oc("ability:share-template-query",r,async()=>{var e;let t,i,n=await (e={appIdStr:r.appId,newTemplate:!0},t=n1.genBaseURL("/platform_openapi/microgame/v1/ability/query_share_setting"),i={appIdStr:e.appIdStr,newTemplate:e.newTemplate},n1.request({url:t,method:"GET",params:i},void 0)),u=eK(n);return{rawResponse:n,rows:(u?.shareInfoList??[]).map(e=>({shareId:e.shareId,title:e.title,description:e.description,cardType:e.cardType,auditState:e.auditState,isDefault:e.isDefault,platform:e.platform,icon:e.icon,iconUri:e.iconUri,reason:e.reason,modifyRemainTimes:e.modifyRemainTimes,ctime:e.ctime,mtime:e.mtime,needRemind:u?.needRemind})),csvHeader:["shareId","title","description","cardType","auditState","isDefault","platform","icon","iconUri","reason","modifyRemainTimes","ctime","mtime","needRemind"]}})}),g=r.command("performance").description("性能数据"),nS(g.command("performance-diagnosis-query").description("查询小游戏启动和运行性能诊断结果,包括劣化指标、实际值、标准值、差值及优化建议;当前不提供网络诊断").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--host <host>",nF).option("--date <date>","诊断日期,格式 YYYY-MM-DD").option("--device-level <n>",nB).option("--os <os>","操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony").option("--mp-version <version>","小游戏版本号")).action(async(e,t)=>{let r=nx(t,e);await oc("performance:performance-diagnosis-query",r,async()=>{var e;let t,i,n;rn(r.host,"--host",lB),rn(r.deviceLevel,"--device-level",rv(l_)),rn(r.os,"--os",rv(lb)),rs(r.date,"--date");let u=await (e={X_Tt_Appid:r.appId,hostAid:lw[rA(r.host,0)]??"",date:r.date,deviceLevel:void 0===r.deviceLevel?void 0:rA(r.deviceLevel,0),os:void 0===r.os?void 0:rA(r.os,0),mpVersion:r.mpVersion,meta:await nT("performance:performance-diagnosis-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/performance/query_performance_diagnosis"),i={date:e.date,deviceLevel:e.deviceLevel,hostAid:e.hostAid,meta:e.meta,mpVersion:e.mpVersion,os:e.os},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u),s={group:"main",genreName:o?.genreName??"",engine:o?.engine??"",degradedIndicatorCount:o?.degradedIndicatorCount??0};return{rawResponse:u,rows:[...lk(o?.launchItems,s,"launch"),...lk(o?.runtimeItems,s,"runtime"),...(o?.otherGroups??[]).flatMap(e=>{let t={group:"other",genreName:e.genreName,engine:e.engine,degradedIndicatorCount:e.degradedIndicatorCount};return[...lk(e.launchItems,t,"launch"),...lk(e.runtimeItems,t,"runtime")]})],csvHeader:lT}})}),nS(nO(g.command("startup-performance-query").description("查询小游戏启动性能数据,包括启动耗时、首帧耗时、TTI 耗时、Wasm 编译耗时、启动留存率、启动场景转化、启动耗时分布和启动流失分布等").option("--metrics <list>","启动性能指标枚举,逗号分隔;不传返回默认指标集").option("--sections <list>","启动分析板块枚举,逗号分隔:1 趋势 / 2 场景转化 / 3 耗时分布 / 4 流失分布 / 5 分包").option("--entrance-form <form>","启动入口形态:all 不区分 / 视频 / 侧边栏 / 广告 / 搜索 / 游戏中心 / 直播 / 桌面 / 私信 / 首页 / 直玩 / 其他").option("--download-code <n>","下载代码枚举:1 全部 / 2 需要 / 3 不需要").option("--scene-id-list <list>","场景 ID 列表,逗号分隔"))).action(async(e,t)=>{let r=nx(t,e);await oc("performance:startup-performance-query",r,async()=>{var e;let t,i,n;lP(r),ru(r.sections,"--sections",rv(lF)),rn(r.downloadCode,"--download-code",rv(lD)),ro(r.sceneIdList,"--scene-id-list");let u=await (e={X_Tt_Appid:r.appId,filter:{common:lL(r),entranceForm:r.entranceForm,downloadCode:void 0===r.downloadCode?void 0:rA(r.downloadCode,0),sceneIdList:rf(r.sceneIdList)},metrics:rm(r.metrics),sections:rm(r.sections),meta:await nT("performance:startup-performance-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/performance/query_launch_performance"),i={filter:e.filter,meta:e.meta,metrics:e.metrics,sections:e.sections},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:lR(o?.series),csvHeader:lI}})}),nS(nO(g.command("runtime-performance-query").description("查询小游戏运行时性能数据,包括 FPS、卡顿率、渲染 DrawCall、三角面数、顶点数、平均内存、内存峰值、内存异常退出率、CPU 使用率、GPU 使用率等").option("--metrics <list>","运行时性能指标枚举,逗号分隔;不传返回默认指标集").option("--include-device-breakdown","是否返回机型分布",!1).option("--include-fps-distribution","是否返回 FPS 分布",!1).option("--include-memory-distribution","是否返回内存分布",!1))).action(async(e,t)=>{let r=nx(t,e);await oc("performance:runtime-performance-query",r,async()=>{var e;let t,i,n;lP(r);let u=await (e={X_Tt_Appid:r.appId,filter:lL(r),includeDeviceBreakdown:r.includeDeviceBreakdown,includeFpsDistribution:r.includeFpsDistribution,includeMemoryDistribution:r.includeMemoryDistribution,metrics:rm(r.metrics),meta:await nT("performance:runtime-performance-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/performance/query_runtime_performance"),i={filter:e.filter,includeDeviceBreakdown:e.includeDeviceBreakdown,includeFpsDistribution:e.includeFpsDistribution,includeMemoryDistribution:e.includeMemoryDistribution,meta:e.meta,metrics:e.metrics},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:lR(o?.series),csvHeader:lI}})}),nS(nO(g.command("network-performance-query").description("查询小游戏网络性能数据,包括 request 和 downloadFile 的请求耗时、错误率等指标").option("--metrics <list>","网络性能指标枚举,逗号分隔;不传返回默认指标集"))).action(async(e,t)=>{let r=nx(t,e);await oc("performance:network-performance-query",r,async()=>{var e;let t,i,n;lP(r);let u=await (e={X_Tt_Appid:r.appId,filter:lL(r),metrics:rm(r.metrics),meta:await nT("performance:network-performance-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/performance/query_network_performance"),i={filter:e.filter,meta:e.meta,metrics:e.metrics},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:lR(o?.series),csvHeader:lI}})}),nS(g.command("error-log-query").description("查询小游戏错误日志列表,支持按时间、App、操作系统、JSSDK 版本、宿主版本、小游戏版本、OpenID、TraceID、日志等级等条件筛选").requiredOption("--app-id <appId>","小游戏 appId").option("--start-time <ts>","开始时间,秒级 Unix 时间戳;缺省为结束时间前 1 小时").option("--end-time <ts>","结束时间,秒级 Unix 时间戳;缺省为当前时间").option("--host <host>",nD).option("--os <os>",nw).option("--app-version <version>","宿主版本号").option("--game-version <version>","小游戏版本号").option("--jssdk-version <version>","JSSDK 版本号").option("--open-id <openId>","用户 OpenID").option("--trace-id <traceId>","日志 TraceID").option("--log-level-list <list>","日志等级枚举,逗号分隔:1 Debug / 2 Info / 3 Warn / 4 Error / 5 Fatal").option("--filter-msg <list>","日志内容过滤关键词,逗号分隔").option("--page-group-size <n>","每页日志分组数").option("--search-after <cursor>","游标,用于翻页续查")).action(async(e,t)=>{let r=nx(t,e);await oc("performance:error-log-query",r,async()=>{var e;let t,i,n;rn(r.host,"--host",rv(lA)),rn(r.os,"--os",rv(lE)),ru(r.logLevelList,"--log-level-list",rv(ly)),function(e){let{maxLookbackDays:t,label:r}=e,i=e.unit??"milliseconds",n=BigInt(e.lookbackTolerance??0),u=rp(e),o=BigInt("seconds"===i?Math.floor(Date.now()/1e3):Date.now()),s=o-BigInt(t*("seconds"===i?86400:864e5))-n;for(let[e,i]of u){if(i>o)throw new l(`${e} 不能晚于当前时间`,{error:"INVALID_TIMESTAMP_RANGE",message:`${e} 不能晚于当前时间`});if(i<s)throw new l(`${r}仅支持最近 ${t} 天的数据`,{error:"OUT_OF_LOOKBACK",message:`${r}仅支持最近 ${t} 天的数据,${e} 已超出范围`})}}({startTime:r.startTime,endTime:r.endTime,maxLookbackDays:oC,label:"错误日志",unit:"seconds"}),ra(r.pageGroupSize,"--page-group-size",1,20);let u=await (e={X_Tt_Appid:r.appId,startTime:r.startTime,endTime:r.endTime,host:void 0===r.host?void 0:rA(r.host,0),os:void 0===r.os?void 0:rA(r.os,0),appVersion:r.appVersion,gameVersion:r.gameVersion,jssdkVersion:r.jssdkVersion,openId:r.openId,traceId:r.traceId,logLevelList:rm(r.logLevelList),filterMsg:rf(r.filterMsg),pageGroupSize:r.pageGroupSize,searchAfter:r.searchAfter,meta:await nT("performance:error-log-query")},t=n1.genBaseURL("/platform_openapi/microgame/v1/performance/query_error_logs"),i={appVersion:e.appVersion,endTime:e.endTime,filterMsg:e.filterMsg,gameVersion:e.gameVersion,host:e.host,jssdkVersion:e.jssdkVersion,logLevelList:e.logLevelList,meta:e.meta,openId:e.openId,os:e.os,pageGroupSize:e.pageGroupSize,searchAfter:e.searchAfter,startTime:e.startTime,traceId:e.traceId},n={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},n1.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eK(u);return{rawResponse:u,rows:(o?.logList??[]).flatMap(e=>(e.logList??[]).map(t=>({appId:e.appId,host:e.host,os:e.os,appVersion:e.appVersion,gameVersion:e.gameVersion,jssdkVersion:e.jssdkVersion,versionType:e.versionType,openId:e.openId,traceId:e.traceId,logLevel:t.logLevel,timestamp:t.timestamp,msg:t.msg}))),csvHeader:lO,resultMeta:{unit:"logGroup",returnedCount:o?.logList?.length,total:o?.page?.total===void 0?void 0:Number(o.page.total),hasMore:o?.page?.hasMore,nextCursor:o?.page?.nextSearchAfter}}})}),r.command("skills").description("管理随 CLI 发布的 Agent Skill").command("install").description(`同步随 CLI 发布的 ${e4} Skill`).addHelpText("after","\n说明:\n 安装或重新同步本机 Agent Skill\n update 默认会执行同步;需要手动修复 Skill 时再运行本命令\n\n示例:\n $ dymg skills install").action(az),r.command("check-update").description("检查 CLI 更新").addHelpText("after","\n说明:\n 查询 npm registry 的 latest 版本\n 发现新版本时,按提示执行 update 更新 CLI 并同步 Skill\n\n示例:\n $ dymg check-update\n $ dymg update").action(aX),r.command("update").description("更新 CLI 并同步 Skill").option("--target-version <version>","安装指定版本或 dist tag,默认 latest").option("--skip-skills","只更新 CLI,跳过 Skill 同步").addOption(new L("--package-manager <packageManager>","指定全局安装使用的包管理器").choices(nM)).addHelpText("after","\n说明:\n 默认安装 latest;目标版本与当前版本一致时会跳过 CLI 安装\n 默认同步随包发布的 Skill;只想更新 CLI 时使用 --skip-skills\n 未指定包管理器时,会根据当前环境识别;识别失败时需显式传入 --package-manager\n\n示例:\n $ dymg update\n $ dymg update --target-version 1.2.3\n $ dymg update --package-manager pnpm\n $ dymg update --skip-skills").action(aY),c),v=!1,C=!1,D=!1,B=()=>{C&&cg(),C=!0,process.exitCode=130;let e=nN();v&&e||cg();let t=setTimeout(()=>{cg()},200);cm({...e,durationMs:Date.now()-_,success:!1,errorMessage:"命令已中断",errorCode:ti()?.errorCode}).finally(()=>{clearTimeout(t),cg()})};process.once("SIGINT",B),process.once("SIGTERM",B),b.hook("preAction",(e,t)=>{var r,i,n;let u,o;v=!0,r=t,D=!cf.has(function(e){let t=e;for(;t.parent&&"dymg"!==t.parent.name();)t=t.parent;return t.name()}(r)),i=t,n=E,u=i.optsWithGlobals(),o=function(e){let t=[],r=e;for(;r&&r.parent;)t.unshift(r.name()),r=r.parent;return t}(i),tr({caller:"string"==typeof u.caller&&nC(u.caller)?u.caller:"unknown",tool:o.join(" ")||function(e){if(e.includes("-V")||e.includes("--version"))return"version";let t=e.filter(e=>!e.startsWith("-"));return 0===t.length?e.some(e=>"-h"===e||"--help"===e)?"help":"root":(t[0],t.slice(0,2).join(" "))}(n),requestParams:F(u),errorMessage:void 0,errorCode:void 0})});try{await b.parseAsync(e);let t=nN();if(v&&t){let e=0===Number(process.exitCode??0);await cm({...t,durationMs:Date.now()-_,success:e,errorMessage:e?void 0:ti()?.errorMessage,errorCode:e?void 0:ti()?.errorCode})}v&&D&&0===Number(process.exitCode??0)&&await nZ()}catch(r){let e=r instanceof Error?r.message:String(r),t=nN();if(r instanceof w){process.exitCode=r.exitCode,v&&t&&await cm({...t,durationMs:Date.now()-_,success:0===r.exitCode,errorMessage:0===r.exitCode?void 0:e,errorCode:0===r.exitCode?void 0:n$(r)});return}throw v&&t&&await cm({...t,durationMs:Date.now()-_,success:!1,errorMessage:e,errorCode:n$(r)}),r}finally{process.removeListener("SIGINT",B),process.removeListener("SIGTERM",B)}}(async function(e=process.argv){var t,r;return t={},r=()=>cA(e),tt.run(t,r)})().then(async()=>{await E(Number(process.exitCode??0))}).catch(async e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
|
|
157
157
|
`),await E(1)})})(),__webpack_exports__)exports[__rspack_i]=__webpack_exports__[__rspack_i];Object.defineProperty(exports,"__esModule",{value:!0});
|