@douyin-minigame/cli 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -25,28 +25,28 @@ Expecting one of '${r.join("', '")}'`);return this._lifeCycleHooks[e]?this._life
25
25
  `):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 O.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()}`,O.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new L(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=j(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=j(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}
26
26
  `),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=>x(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=T.basename(e,T.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(O.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.
27
27
  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}
28
- `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function M(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 U(){return!O.env.NO_COLOR&&"0"!==O.env.FORCE_COLOR&&"false"!==O.env.FORCE_COLOR&&(!!O.env.FORCE_COLOR||void 0!==O.env.CLICOLOR_FORCE||void 0)}new $;var q,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,eC,ev,eD,eF,ew,eB,ex,eS,eT,eI,eO,ek,eR,eP,eL,eN,ej,e$,eM,eU,eq,eV,eH,ez=((q={}).Timeout="HTTP_TIMEOUT",q.Aborted="HTTP_ABORTED",q.Network="HTTP_NETWORK",q.Status="HTTP_STATUS",q.InvalidJson="HTTP_INVALID_JSON",q.InvalidArgument="HTTP_INVALID_ARGUMENT",q);class eG 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 eW=Object.values(ez);function eJ(e){return h(e,eW)&&"string"==typeof e.url}function eY(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 eK(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 eG("timeoutMs must be a positive integer",{code:ez.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 eG(`Request timed out after ${s}ms`,{cause:t,code:ez.Timeout,url:e});if(f.aborted)throw new eG("Request aborted",{cause:t,code:ez.Aborted,url:e});throw new eG("Network request failed",{cause:t,code:ez.Network,url:e})}finally{f.cleanup()}}function eX(e,t,r){let i=typeof t;if("string"!==i&&"number"!==i&&"boolean"!==i)throw new eG(`Invalid query parameter value for "${e}": expected string, number or boolean`,{code:ez.InvalidArgument,url:r})}async function eQ(e){try{return await e.text()}catch{return}}async function eZ(e,t){if(204===e.status)return;let r=await eQ(e)??"";if(0!==r.length)try{return JSON.parse(r)}catch(i){throw new eG("Failed to parse response as JSON",{cause:i,code:ez.InvalidJson,url:t,status:e.status,responseBody:r})}}let e1=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 eG("baseURL is required for relative request URLs",{code:ez.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&&(eX(i,e,t),r.append(i,String(e)));continue}eX(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),_=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 eG("Failed to serialize request body as JSON",{cause:e,code:ez.InvalidArgument,url:i})}}}(m,_,y,g);(s=_).has("Accept")||s.set("Accept","application/json");let C=Math.max(0,m.retry?.maxRetries??0);for(let t=0;;t+=1)try{let t=await eK(g,{method:A,headers:_,...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 eQ(t);throw new eG(`Request failed with status ${t.status}`,{code:ez.Status,url:g,status:t.status,responseBody:e})}e.response.data=await eZ(t,g);return}catch(r){let e=t+1;if(!(e<=C&&(m.retry?.shouldRetry?.({request:m,attempt:e,error:r})??!((l={request:m,attempt:e,error:r}).error instanceof eG&&l.error.error===ez.Aborted))))throw r;await E((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??[],e1];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 e2="dymg",e3="@douyin-minigame/cli",e6="douyin-minigame",e4=`${e2}:oauth`,e8=`${e2} auth login`,e9=`${e8} --no-wait`,e7=`${e8} --resume`,e5=`${e2} auth logout`,te=(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 tt(e){te.update(e)}function tr(){return te.get()}let ti=[],tn=async(e,t)=>{try{await t()}finally{tt({response:e.response})}},tu=async(e,t)=>{let r=tr()?.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 to=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArray.js"),ts=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isFinite.js"),ta=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isPlainObject.js"),tl=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isString.js");let tc=require("node:crypto");__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObject.js"),require("node:http"),require("node:net");let td=require("node:os"),tp=require("node:fs/promises");class th 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,th),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 tf=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 th("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 th("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},tm=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}},tg=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 th("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 th("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 th("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 th("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=tf(t.columns);else if(void 0===t.columns||null===t.columns||!1===t.columns)t.columns=!1;else throw new th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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},tA=function(e){return e.every(e=>null==e||e.toString&&""===e.toString().trim())},ty={utf8:Buffer.from([239,187,191]),utf16le:Buffer.from([255,254])},tE=function(e={}){var t;let r=tg(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 tm(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 tm(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:C,previousBuf:v,rawBuffer:D,escapeIsQuote:F}=this.state;if(void 0===v)if(void 0===e)return void i();else n=e;else n=void 0!==v&&void 0===e?v:Buffer.concat([v,e]);if(!1===C)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 ty)if(0===ty[e].compare(n,0,ty[e].length)){let t=ty[e].length;this.state.bufBytesStart+=t,n=n.slice(t);let r=tg({...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 th("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(ty).map(e=>!!ty[e].equals(this.state.field.toString())&&e).filter(Boolean)[0],r=this.__error(new th("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 th("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 th("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 th("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&&tA(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 th("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 th("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&&tA(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 th("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=tf(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}}}},t_=function(e,t={}){"string"==typeof e&&(e=Buffer.from(e));let r=t&&t.objname?{}:[],i=tE(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},tb=/\\(\\)?/g,tC=RegExp("[^.[\\]]+|\\[(?:([^\"'][^[]*)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))","g"),tv=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,tD=/^\w*$/,tF=function(e){var t;let r=typeof e;return"symbol"===r||"object"===r&&e&&"[object Symbol]"===(t=e,Object.prototype.toString.call(t))},tw=function(e,t){if(Array.isArray(e))return!1;let r=typeof e;return!!("number"===r||"symbol"===r||"boolean"===r||!e||tF(e))||tD.test(e)||!tv.test(e)||null!=t&&e in Object(t)},tB=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(tb,"$1"):r&&(u=r.trim()),t.push(u)}),t},tx=function(e){if("string"==typeof e||tF(e))return e;let t=`${e}`;return"0"==t&&1/e==-1/0?"-0":t},tS=function(e,t){var r,i;r=t,i=e;let n=0,u=(t=Array.isArray(r)?r:tw(r,i)?[r]:tB(r)).length;for(;null!=e&&n<u;)e=e[tx(t[n++])];return n&&n===u?e:void 0},tT=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 tI 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,tI),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 tO=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 tI("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 tI("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 tI("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 tI("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 tI("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 tI("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 tI("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]=tT(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]},tk=Buffer.from([239,187,191]),tR=function(e,t={}){let r=[],[i,n]=tO(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]=tT(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=tS(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]=tO(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(tk)},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 tP(e,t){var r,i;let n,u=(0,T.resolve)(e),o=(0,T.resolve)(u,t);if(r=u,i=o,n=r.endsWith(T.sep)?r:`${r}${T.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 tL(e,t){await (0,tp.mkdir)((0,T.dirname)(e),{recursive:!0,mode:t})}var tN=((V={}).NotFound="ENOENT",V.StorageError="FILE_STORAGE_ERROR",V.InvalidJson="INVALID_JSON",V.InvalidCsv="INVALID_CSV",V),tj=((H={}).ReadText="readText",H.WriteText="writeText",H.Remove="remove",H.ReadJson="readJson",H.WriteJson="writeJson",H.ReadCsv="readCsv",H.WriteCsv="writeCsv",H);class t$ 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 tM extends t${constructor(e,t,r){super(`File not found: ${e}`,{cause:r,code:"ENOENT",filePath:e,operation:t}),this.name="FileNotFoundError"}}let tU=Object.values(tN),tq=f("ENOENT");function tV(e,t,r){var i;return h(e,tU)?e:(i=e)instanceof Error&&"string"==typeof i.code&&"ENOENT"===e.code?new tM(t,r,e):new t$(`Failed to ${r} for file: ${t}`,{cause:e,code:"FILE_STORAGE_ERROR",filePath:t,operation:r})}function tH(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 tz(e,t){try{let r=await (0,tp.stat)(e);Date.now()-r.mtimeMs>t&&await (0,tp.unlink)(e)}catch(e){if("ENOENT"!==e.code)throw e}}async function tG(e,t,r={}){let{retryMs:i,staleMs:n,timeoutMs:u}=function(e){let t={retryMs:tH(e.retryMs,50,"retryMs"),staleMs:tH(e.staleMs,15e3,"staleMs"),timeoutMs:tH(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,T.resolve)(e),s=Date.now()+u;for(await tL(o);;)try{let e=await (0,tp.open)(o,"wx",384);await e.close();break}catch(e){if("EEXIST"!==e.code)throw e;if(await tz(o,n),Date.now()>=s)throw new t$(`Timed out acquiring file lock: ${o}`,{cause:e,code:tN.StorageError,filePath:o,operation:tj.WriteText});await E(i)}try{return await t()}finally{await (0,tp.unlink)(o).catch(e=>{if("ENOENT"!==e.code)throw e})}}class tW{baseDir;constructor(e){if(this.baseDir=(0,T.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,I.mkdirSync)(this.baseDir,{recursive:!0,mode:t}),void 0!==t&&(511&(0,I.statSync)(this.baseDir).mode)!==t&&(0,I.chmodSync)(this.baseDir,t)}}async readText(e,t="utf8"){let r=tP(this.baseDir,e);try{return await (0,tp.readFile)(r,{encoding:t})}catch(e){throw tV(e,r,tj.ReadText)}}async writeText(e,t,r={}){let i=r.encoding??"utf8",{mode:n}=r,u=tP(this.baseDir,e),o=(0,T.join)((0,T.dirname)(u),`.${(0,T.basename)(u)}.${(0,tc.randomUUID)()}.tmp`);try{await tL(u),await (0,tp.writeFile)(o,t,{encoding:i,mode:n}),void 0!==n&&await (0,tp.chmod)(o,n),await (0,tp.rename)(o,u)}catch(e){throw await (0,tp.rm)(o,{force:!0}).catch(()=>void 0),tV(e,u,tj.WriteText)}}async remove(e){let t=tP(this.baseDir,e);try{await (0,tp.rm)(t)}catch(e){throw tV(e,t,tj.Remove)}}async readJson(e,t="utf8"){let r=tP(this.baseDir,e),i=await this.readText(e,t);try{return JSON.parse(i)}catch(e){throw new t$(`Failed to parse JSON file: ${r}`,{cause:e,code:tN.InvalidJson,filePath:r,operation:tj.ReadJson})}}async writeJson(e,t,r={}){let i=r.encoding??"utf8",n=r.spaces??2,u=`${JSON.stringify(t,null,n)}
28
+ `)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function M(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 U(){return!O.env.NO_COLOR&&"0"!==O.env.FORCE_COLOR&&"false"!==O.env.FORCE_COLOR&&(!!O.env.FORCE_COLOR||void 0!==O.env.CLICOLOR_FORCE||void 0)}new $;var q,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,eC,ev,eD,eF,ew,eB,ex,eS,eT,eI,eO,ek,eR,eP,eL,eN,ej,e$,eM,eU,eq,eV,eH,ez=((q={}).Timeout="HTTP_TIMEOUT",q.Aborted="HTTP_ABORTED",q.Network="HTTP_NETWORK",q.Status="HTTP_STATUS",q.InvalidJson="HTTP_INVALID_JSON",q.InvalidArgument="HTTP_INVALID_ARGUMENT",q);class eG 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 eW=Object.values(ez);function eJ(e){return h(e,eW)&&"string"==typeof e.url}function eY(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 eK(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 eG("timeoutMs must be a positive integer",{code:ez.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 eG(`Request timed out after ${s}ms`,{cause:t,code:ez.Timeout,url:e});if(f.aborted)throw new eG("Request aborted",{cause:t,code:ez.Aborted,url:e});throw new eG("Network request failed",{cause:t,code:ez.Network,url:e})}finally{f.cleanup()}}function eX(e,t,r){let i=typeof t;if("string"!==i&&"number"!==i&&"boolean"!==i)throw new eG(`Invalid query parameter value for "${e}": expected string, number or boolean`,{code:ez.InvalidArgument,url:r})}async function eQ(e){try{return await e.text()}catch{return}}async function eZ(e,t){if(204===e.status)return;let r=await eQ(e)??"";if(0!==r.length)try{return JSON.parse(r)}catch(i){throw new eG("Failed to parse response as JSON",{cause:i,code:ez.InvalidJson,url:t,status:e.status,responseBody:r})}}let e1=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 eG("baseURL is required for relative request URLs",{code:ez.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&&(eX(i,e,t),r.append(i,String(e)));continue}eX(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),_=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 eG("Failed to serialize request body as JSON",{cause:e,code:ez.InvalidArgument,url:i})}}}(m,_,y,g);(s=_).has("Accept")||s.set("Accept","application/json");let C=Math.max(0,m.retry?.maxRetries??0);for(let t=0;;t+=1)try{let t=await eK(g,{method:A,headers:_,...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 eQ(t);throw new eG(`Request failed with status ${t.status}`,{code:ez.Status,url:g,status:t.status,responseBody:e})}e.response.data=await eZ(t,g);return}catch(r){let e=t+1;if(!(e<=C&&(m.retry?.shouldRetry?.({request:m,attempt:e,error:r})??!((l={request:m,attempt:e,error:r}).error instanceof eG&&l.error.error===ez.Aborted))))throw r;await E((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??[],e1];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 e0="dymg",e3="@douyin-minigame/cli",e6="douyin-minigame",e4=`${e0}:oauth`,e8=`${e0} auth login`,e9=`${e8} --no-wait`,e7=`${e8} --resume`,e5=`${e0} auth logout`,te=(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 tt(e){te.update(e)}function tr(){return te.get()}let ti=[],tn=async(e,t)=>{try{await t()}finally{tt({response:e.response})}},tu=async(e,t)=>{let r=tr()?.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 to=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArray.js"),ts=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isFinite.js"),ta=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isPlainObject.js"),tl=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isString.js");let tc=require("node:crypto");__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObject.js"),require("node:http"),require("node:net");let td=require("node:os"),tp=require("node:fs/promises");class th 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,th),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 tf=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 th("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 th("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},tm=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}},tg=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 th("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 th("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 th("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 th("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=tf(t.columns);else if(void 0===t.columns||null===t.columns||!1===t.columns)t.columns=!1;else throw new th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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 th("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},tA=function(e){return e.every(e=>null==e||e.toString&&""===e.toString().trim())},ty={utf8:Buffer.from([239,187,191]),utf16le:Buffer.from([255,254])},tE=function(e={}){var t;let r=tg(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 tm(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 tm(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:C,previousBuf:v,rawBuffer:D,escapeIsQuote:F}=this.state;if(void 0===v)if(void 0===e)return void i();else n=e;else n=void 0!==v&&void 0===e?v:Buffer.concat([v,e]);if(!1===C)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 ty)if(0===ty[e].compare(n,0,ty[e].length)){let t=ty[e].length;this.state.bufBytesStart+=t,n=n.slice(t);let r=tg({...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 th("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(ty).map(e=>!!ty[e].equals(this.state.field.toString())&&e).filter(Boolean)[0],r=this.__error(new th("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 th("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 th("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 th("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&&tA(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 th("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 th("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&&tA(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 th("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=tf(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}}}},t_=function(e,t={}){"string"==typeof e&&(e=Buffer.from(e));let r=t&&t.objname?{}:[],i=tE(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},tb=/\\(\\)?/g,tC=RegExp("[^.[\\]]+|\\[(?:([^\"'][^[]*)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))","g"),tv=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,tD=/^\w*$/,tF=function(e){var t;let r=typeof e;return"symbol"===r||"object"===r&&e&&"[object Symbol]"===(t=e,Object.prototype.toString.call(t))},tw=function(e,t){if(Array.isArray(e))return!1;let r=typeof e;return!!("number"===r||"symbol"===r||"boolean"===r||!e||tF(e))||tD.test(e)||!tv.test(e)||null!=t&&e in Object(t)},tB=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(tb,"$1"):r&&(u=r.trim()),t.push(u)}),t},tx=function(e){if("string"==typeof e||tF(e))return e;let t=`${e}`;return"0"==t&&1/e==-1/0?"-0":t},tS=function(e,t){var r,i;r=t,i=e;let n=0,u=(t=Array.isArray(r)?r:tw(r,i)?[r]:tB(r)).length;for(;null!=e&&n<u;)e=e[tx(t[n++])];return n&&n===u?e:void 0},tT=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 tI 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,tI),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 tO=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 tI("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 tI("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 tI("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 tI("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 tI("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 tI("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 tI("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]=tT(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]},tk=Buffer.from([239,187,191]),tR=function(e,t={}){let r=[],[i,n]=tO(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]=tT(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=tS(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]=tO(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(tk)},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 tP(e,t){var r,i;let n,u=(0,T.resolve)(e),o=(0,T.resolve)(u,t);if(r=u,i=o,n=r.endsWith(T.sep)?r:`${r}${T.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 tL(e,t){await (0,tp.mkdir)((0,T.dirname)(e),{recursive:!0,mode:t})}var tN=((V={}).NotFound="ENOENT",V.StorageError="FILE_STORAGE_ERROR",V.InvalidJson="INVALID_JSON",V.InvalidCsv="INVALID_CSV",V),tj=((H={}).ReadText="readText",H.WriteText="writeText",H.Remove="remove",H.ReadJson="readJson",H.WriteJson="writeJson",H.ReadCsv="readCsv",H.WriteCsv="writeCsv",H);class t$ 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 tM extends t${constructor(e,t,r){super(`File not found: ${e}`,{cause:r,code:"ENOENT",filePath:e,operation:t}),this.name="FileNotFoundError"}}let tU=Object.values(tN),tq=f("ENOENT");function tV(e,t,r){var i;return h(e,tU)?e:(i=e)instanceof Error&&"string"==typeof i.code&&"ENOENT"===e.code?new tM(t,r,e):new t$(`Failed to ${r} for file: ${t}`,{cause:e,code:"FILE_STORAGE_ERROR",filePath:t,operation:r})}function tH(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 tz(e,t){try{let r=await (0,tp.stat)(e);Date.now()-r.mtimeMs>t&&await (0,tp.unlink)(e)}catch(e){if("ENOENT"!==e.code)throw e}}async function tG(e,t,r={}){let{retryMs:i,staleMs:n,timeoutMs:u}=function(e){let t={retryMs:tH(e.retryMs,50,"retryMs"),staleMs:tH(e.staleMs,15e3,"staleMs"),timeoutMs:tH(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,T.resolve)(e),s=Date.now()+u;for(await tL(o);;)try{let e=await (0,tp.open)(o,"wx",384);await e.close();break}catch(e){if("EEXIST"!==e.code)throw e;if(await tz(o,n),Date.now()>=s)throw new t$(`Timed out acquiring file lock: ${o}`,{cause:e,code:tN.StorageError,filePath:o,operation:tj.WriteText});await E(i)}try{return await t()}finally{await (0,tp.unlink)(o).catch(e=>{if("ENOENT"!==e.code)throw e})}}class tW{baseDir;constructor(e){if(this.baseDir=(0,T.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,I.mkdirSync)(this.baseDir,{recursive:!0,mode:t}),void 0!==t&&(511&(0,I.statSync)(this.baseDir).mode)!==t&&(0,I.chmodSync)(this.baseDir,t)}}async readText(e,t="utf8"){let r=tP(this.baseDir,e);try{return await (0,tp.readFile)(r,{encoding:t})}catch(e){throw tV(e,r,tj.ReadText)}}async writeText(e,t,r={}){let i=r.encoding??"utf8",{mode:n}=r,u=tP(this.baseDir,e),o=(0,T.join)((0,T.dirname)(u),`.${(0,T.basename)(u)}.${(0,tc.randomUUID)()}.tmp`);try{await tL(u),await (0,tp.writeFile)(o,t,{encoding:i,mode:n}),void 0!==n&&await (0,tp.chmod)(o,n),await (0,tp.rename)(o,u)}catch(e){throw await (0,tp.rm)(o,{force:!0}).catch(()=>void 0),tV(e,u,tj.WriteText)}}async remove(e){let t=tP(this.baseDir,e);try{await (0,tp.rm)(t)}catch(e){throw tV(e,t,tj.Remove)}}async readJson(e,t="utf8"){let r=tP(this.baseDir,e),i=await this.readText(e,t);try{return JSON.parse(i)}catch(e){throw new t$(`Failed to parse JSON file: ${r}`,{cause:e,code:tN.InvalidJson,filePath:r,operation:tj.ReadJson})}}async writeJson(e,t,r={}){let i=r.encoding??"utf8",n=r.spaces??2,u=`${JSON.stringify(t,null,n)}
29
29
  `;await this.writeText(e,u,{encoding:i,mode:r.mode})}async readCsv(e,t={}){let r=tP(this.baseDir,e),i=await this.readText(e),n=t.delimiter??",";try{if(!1===t.hasHeader)return t_(i,{bom:!0,delimiter:n,relax_column_count:!0,skip_empty_lines:!0});return t_(i,{bom:!0,columns:!0,delimiter:n,relax_column_count:!0,skip_empty_lines:!0})}catch(e){throw new t$(`Failed to parse CSV file: ${r}`,{cause:e,code:tN.InvalidCsv,filePath:r,operation:tj.ReadCsv})}}async writeCsv(e,t,r={}){let i=r.encoding??"utf8",n=r.delimiter??",";try{let u="";0===t.length?r.header?.length&&(u=tR([],{columns:r.header,delimiter:n,header:!0})):u=Array.isArray(t[0])?tR(t,{delimiter:n}):tR(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}
30
- `,{encoding:i,mode:r.mode})}catch(r){if(h(r,tU))throw r;let t=tP(this.baseDir,e);throw new t$(`Failed to write CSV file: ${t}`,{cause:r,code:tN.StorageError,filePath:t,operation:tj.WriteCsv})}}}var tJ=((z={}).KeyNotFound="KEY_NOT_FOUND",z.DataNotFound="DATA_NOT_FOUND",z.DecryptionFailed="DECRYPTION_FAILED",z.KeyStorageError="KEY_STORAGE_ERROR",z.DataStorageError="DATA_STORAGE_ERROR",z.InvalidJson="INVALID_JSON",z.InvalidEnvelope="INVALID_ENVELOPE",z.KeychainTimeout="KEYCHAIN_TIMEOUT",z),tY=((G={}).ReadText="readText",G.WriteText="writeText",G.ReadJson="readJson",G.WriteJson="writeJson",G.Remove="remove",G.Clear="clear",G.ReadKey="readKey",G.WriteKey="writeKey",G.RemoveKey="removeKey",G);class tK 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 tX extends tK{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 tQ extends tK{constructor(e,t,r){super(`Sensitive data not found: ${e}`,{cause:r,code:"DATA_NOT_FOUND",filePath:e,operation:t}),this.name="SensitiveDataNotFoundError"}}class tZ extends tK{constructor(e,t,r){super(`Failed to decrypt sensitive data: ${e}`,{cause:r,code:"DECRYPTION_FAILED",filePath:e,operation:t}),this.name="SensitiveDecryptionError"}}class t1 extends tK{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 tK{constructor(e,t){super(e,{cause:t.cause,code:t.code??"KEY_STORAGE_ERROR",filePath:t.filePath,operation:t.operation}),this.name="SensitiveKeyStorageError"}}class t2 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 t3=f("KEY_NOT_FOUND"),t6=f("DATA_NOT_FOUND");function t4(e){return e?e.split(",").map(e=>e.trim()).filter(e=>""!==e):[]}f("DECRYPTION_FAILED"),f("INVALID_ENVELOPE");let t8=/^\d{4}-\d{2}-\d{2}$/,t9=/^\d{4}(0[1-9]|1[0-2])$/,t7=/^-?(0|[1-9]\d*)$/,t5=/^[1-9]\d*$/;var re=((W={}).InvalidEnum="INVALID_ENUM",W.InvalidIntList="INVALID_INT_LIST",W.InvalidDate="INVALID_DATE",W.InvalidRange="INVALID_RANGE",W.InvalidPositiveInt="INVALID_POSITIVE_INT",W.InvalidDateRange="INVALID_DATE_RANGE",W.OutOfLookback="OUT_OF_LOOKBACK",W.InvalidTimestamp="INVALID_TIMESTAMP",W.InvalidTimestampRange="INVALID_TIMESTAMP_RANGE",W);function rt(e){return String(e).padStart(2,"0")}function rr(e){let t=e.getFullYear(),r=rt(e.getMonth()+1),i=rt(e.getDate());return`${t}-${r}-${i}`}function ri(e,t,r){if(void 0!==e&&!r.includes(e))throw new l(`参数 ${t} 取值非法: ${e}`,{error:"INVALID_ENUM",message:`${t} 只能取 ${r.join(" / ")}`})}function rn(e,t,r){if(void 0!==e){for(let i of t4(e))if(!r.includes(i))throw new l(`参数 ${t} 包含非法取值: ${i}`,{error:"INVALID_ENUM",message:`${t} 每一项只能取 ${r.join(" / ")}`})}}function ru(e,t){if(void 0!==e){for(let r of t4(e))if(!t7.test(r))throw new l(`参数 ${t} 包含非法取值: ${r}`,{error:"INVALID_INT_LIST",message:`${t} 每一项必须是整数,但包含非法值: ${r}`})}}function ro(e,t){if(void 0===e)return;let r=new Date(`${e}T00:00:00Z`);if(!t8.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 rs(e,t,r,i){if(void 0===e)return;let n=t7.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 ra(e,t){if(void 0!==e&&!t5.test(e))throw new l(`参数 ${t} 非法: ${e}`,{error:"INVALID_POSITIVE_INT",message:`${t} 必须是正整数`})}function rl(e){let{startDate:t,endDate:r}=e,i=e.startField??"--start-date",n=e.endField??"--end-date";if(ro(t,i),ro(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=rr(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 rc(e){let{startDate:t,endDate:r,maxLookbackDays:i,label:n,latestDateOffsetDays:u=0}=e,o=e.startField??"--start-date",s=e.endField??"--end-date";rl(e);let a=rr(new Date(Date.now()-864e5*u)),c=rr(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 rd(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(!t5.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 rp(e){let t=rd(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 rh(e){let t=t4(e);return t.length>0?t:void 0}function rf(e){let t=rh(e);if(!t)return;let r=t.map(Number).filter(e=>!Number.isNaN(e));return r.length>0?r:void 0}function rm(e,t,r){let i=rh(e),n=String(r);if(!i||1===i.length&&i[0]===n)return;if(i.includes(n))throw new l(`${t} 的全部选项 ${n} 不能与其他枚举值同时使用`,{error:re.InvalidEnum,message:`${t} 的枚举值 ${n} 表示全部,必须单独使用`});let u=i.find(e=>!t7.test(e));if(void 0!==u)throw new l(`参数 ${t} 包含非法取值: ${u}`,{error:re.InvalidIntList,message:`${t} 每一项必须是整数,但包含非法值: ${u}`});return i.map(Number)}function rg(e,t){if(void 0===e)return t;let r=t7.test(e)?Number(e):NaN;return Number.isNaN(r)?t:r}function rA(e){if(null==e)return;let t=String(e).trim();if("number"==typeof e&&!Number.isSafeInteger(e)||!t7.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 ry(e){if("number"==typeof e&&Number.isInteger(e)&&e>0)return e;if("string"!=typeof e||!t7.test(e))return;let t=Number(e);return t>0?t:void 0}function rE(e){return String(e).padStart(2,"0")}function r_(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=rE(u.getMonth()+1),a=rE(u.getDate());if("date"===r)return`${o}-${s}-${a}`;let l=rE(u.getHours()),c=rE(u.getMinutes()),d=rE(u.getSeconds());return`${o}-${s}-${a} ${l}:${c}:${d}`}function rb(e){return Object.values(e).filter(e=>"number"==typeof e).map(String)}function rC(e,t){let r=function(e){if(void 0===e||!t7.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 rv(e,t){let r="number"==typeof t?t:t7.test(t)?Number(t):NaN;return"string"==typeof e[r]?String(e[r]):String(t)}let rD=new Set(["access_denied","expired_token","invalid_client","invalid_grant","unauthorized_client"]);var rF=((J={}).InvalidArgument="INVALID_ARGUMENT",J.PortUnavailable="PORT_UNAVAILABLE",J.CallbackAborted="CALLBACK_ABORTED",J.CallbackTimeout="CALLBACK_TIMEOUT",J.CallbackError="CALLBACK_ERROR",J.RequestAborted="REQUEST_ABORTED",J.RequestTimeout="REQUEST_TIMEOUT",J.NetworkError="NETWORK_ERROR",J.HttpError="HTTP_ERROR",J.InvalidResponse="INVALID_RESPONSE",J.AuthorizationPending="AUTHORIZATION_PENDING",J.SlowDown="SLOW_DOWN",J.AccessDenied="ACCESS_DENIED",J.ExpiredToken="EXPIRED_TOKEN",J),rw=((Y={}).GeneratePKCE="generatePKCE",Y.GenerateState="generateState",Y.BuildAuthUrl="buildAuthUrl",Y.BuildLoopbackRedirectUri="buildLoopbackRedirectUri",Y.GetAvailablePort="getAvailablePort",Y.CreateLocalCallbackHandler="createLocalCallbackHandler",Y.HandleLocalCallback="handleLocalCallback",Y.ExchangeToken="exchangeToken",Y.IntrospectToken="introspectToken",Y.RevokeToken="revokeToken",Y.FetchAuthorizationServerMetadata="fetchAuthorizationServerMetadata",Y.DynamicClientRegistration="dynamicClientRegistration",Y.StartDeviceAuthorization="startDeviceAuthorization",Y.ExchangeDeviceCodeToken="exchangeDeviceCodeToken",Y.PollDeviceToken="pollDeviceToken",Y.CreateDeviceFlowSession="createDeviceFlowSession",Y);class rB 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 rx extends rB{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 rS extends rB{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 rT extends rB{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 rI extends rB{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 rO=Object.values(rF);function rk(e){if(!h(e,rO)||"exchangeToken"!==e.operation)return!1;let t=e.responseJson,r=t?.error;return"string"==typeof r&&rD.has(r)}var rR=((K={}).NotFound="NOT_FOUND",K.InvalidShape="INVALID_SHAPE",K.AccessTokenExpired="ACCESS_TOKEN_EXPIRED",K.RefreshTokenExpired="REFRESH_TOKEN_EXPIRED",K.RefreshFailed="REFRESH_FAILED",K.StorageError="STORAGE_ERROR",K),rP=((X={}).Read="read",X.Save="save",X.Clear="clear",X.Refresh="refresh",X);class rL extends l{operation;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="OAuthTokenStoreError",this.operation=t.operation}}Object.values(rR);let rN=f("NOT_FOUND");function rj(e){var t;return ta(e)&&(t=e.auth,!!ta(t)&&rU(t.accessToken)&&rU(t.refreshToken)&&rM(t.atExpiresAt)&&rM(t.rtExpiresAt)&&to(t.scopes)&&t.scopes.every(tl))}function r$(e,t,r){if(!r(e))throw new rL("Invalid OAuth token snapshot shape",{code:rR.InvalidShape,operation:t})}function rM(e){return ts(e)&&Number.isInteger(e)&&e>0&&e<1e10}function rU(e){return tl(e)&&""!==e.trim()}function rq(e,t=Date.now()){return e<=Math.floor(t/1e3)}class rV{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,T.join)(this.storage.baseDir,`${this.fileName}.refresh.lock`):e.refreshLockPath,this.refreshLockOptions=e.refreshLockOptions,this.now=e.now??(()=>Date.now()),this.validate=e.validate??rj}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(rN(e))return;throw e}}async save(e){r$(e,rP.Save,this.validate),this.writeEpoch+=1;try{await this.storage.writeJson(this.fileName,e)}catch(e){throw new rL(`Failed to persist OAuth token snapshot: ${this.fileName}`,{cause:e,code:rR.StorageError,operation:rP.Save})}this.cache={snapshot:e,loadedAt:this.now()}}async clear(){this.writeEpoch+=1;try{try{await this.storage.remove(this.fileName)}catch(e){if(!t6(e))throw e}await this.storage.removeKey()}catch(e){throw new rL(`Failed to clear OAuth token snapshot: ${this.fileName}`,{cause:e,code:rR.StorageError,operation:rP.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 rL("OAuth access token has expired and no refresh function provided",{code:rR.AccessTokenExpired,operation:rP.Refresh});return(await this.refresh(t,e)).auth.accessToken}async refresh(e,t){return!1===this.refreshLockPath?this.refreshCurrent(e,t):tG(this.refreshLockPath,async()=>{this.invalidateCache();let r=await this.tryGet();if(!r)throw new rL(`OAuth token snapshot not found: ${this.fileName}`,{code:rR.NotFound,operation:rP.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 rL("OAuth refresh token has expired, re-login is required",{code:rR.RefreshTokenExpired,operation:rP.Refresh});if(this.refreshInflight)return this.refreshInflight;let r=this.writeEpoch,i=(async()=>{let i;try{i=await t(e)}catch(e){throw new rL("Failed to refresh OAuth tokens",{cause:e,code:rR.RefreshFailed,operation:rP.Refresh})}if(this.writeEpoch!==r)throw new rL("OAuth token refresh result is stale",{code:rR.RefreshFailed,operation:rP.Refresh});return r$(i,rP.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 rq(e.rtExpiresAt,this.now())}async loadFromStorage(){let e,t=this.writeEpoch;try{e=await this.storage.readJson(this.fileName)}catch(e){if(t6(e))throw new rL(`OAuth token snapshot not found: ${this.fileName}`,{cause:e,code:rR.NotFound,operation:rP.Read});throw new rL(`Failed to read OAuth token snapshot: ${this.fileName}`,{cause:e,code:rR.StorageError,operation:rP.Read})}return r$(e,rP.Read,this.validate),this.writeEpoch===t&&(this.cache={snapshot:e,loadedAt:this.now()}),e}}let rH=new e0,rz=new Set(["grant_type","client_id","code","redirect_uri","code_verifier","refresh_token","device_code","scope"]),rG=new Set(["client_id","scope","code_challenge","code_challenge_method"]);function rW(e){return Array.isArray(e)?e.map(e=>e.trim()).filter(Boolean).join(" ")||void 0:e?.trim()||void 0}function rJ(e,t,r,i){if(t)for(let[n,u]of Object.entries(t)){if(r.has(n.toLowerCase()))throw new rB(`extraParams cannot override reserved OAuth parameter: ${n}`,{code:rF.InvalidArgument,operation:i});rY(e,n,u)}}function rY(e,t,r){null!=r&&e.set(t,String(r))}function rK(e){if(e.trim())try{let t=JSON.parse(e);if(ta(t))return t;return}catch{return}}function rX(e){return eJ(e)?e.error===ez.Timeout?rF.RequestTimeout:e.error===ez.Aborted?rF.RequestAborted:rF.NetworkError:rF.NetworkError}function rQ(e,t,r){try{return new URL(e)}catch(e){throw new rB(`Invalid ${r}`,{cause:e,code:rF.InvalidArgument,operation:t})}}function rZ(e,t,r){if(!tl(e)||""===e.trim())throw new rB(`${t} must be a non-empty string`,{code:rF.InvalidArgument,operation:r})}function r1(e,t,r){if(!Number.isInteger(e)||e<=0)throw new rB(`${t} must be a positive integer`,{code:rF.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??rH).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 rI("OAuth device flow endpoint returned an empty response",{code:rF.InvalidResponse,operation:e.operation});let n=i.status,u=await i.text(),o=rK(u),s=tl(o?.error)?o.error:void 0,a=tl(o?.error_description)?o.error_description:void 0;if(void 0===n)throw new rI("OAuth device flow endpoint returned an invalid response",{code:rF.NetworkError,operation:e.operation,responseBody:u,responseJson:o});if(n>=500)throw new rI(`OAuth device flow endpoint returned HTTP ${n}`,{code:rF.HttpError,operation:e.operation,providerError:s,providerErrorDescription:a,responseBody:u,responseJson:o,status:n});if(s){var r;throw new rI(`OAuth device flow endpoint returned error: ${s}`,{code:(r=s,"authorization_pending"===r?rF.AuthorizationPending:"slow_down"===r?rF.SlowDown:"access_denied"===r?rF.AccessDenied:"expired_token"===r?rF.ExpiredToken:rF.InvalidResponse),operation:e.operation,providerError:s,providerErrorDescription:a,responseBody:u,responseJson:o,status:n})}if(n<200||n>=300)throw new rI(`OAuth device flow endpoint returned HTTP ${n}`,{code:rF.HttpError,operation:e.operation,responseBody:u,responseJson:o,status:n});if(!o)throw new rI("OAuth device flow endpoint returned a non-JSON response",{code:rF.InvalidResponse,operation:e.operation,responseBody:u,status:n});return o}catch(t){if(t instanceof rI)throw t;throw new rI("OAuth device flow request failed",{cause:t,code:rX(t),operation:e.operation})}}function r2(e,t,r){let i=Math.min(e,Math.max(0,t-Date.now()));return i<=0?Promise.resolve():r?.aborted?Promise.reject(new rI("OAuth device token polling was aborted",{code:rF.RequestAborted,operation:rw.PollDeviceToken})):new Promise((e,t)=>{let n=setTimeout(()=>{r?.removeEventListener("abort",u),e()},i),u=()=>{clearTimeout(n),t(new rI("OAuth device token polling was aborted",{code:rF.RequestAborted,operation:rw.PollDeviceToken}))};r?.addEventListener("abort",u,{once:!0})})}function r3(e,t){rZ(e.clientId,"clientId",rw.ExchangeDeviceCodeToken),rZ(e.deviceCode,"deviceCode",rw.ExchangeDeviceCodeToken),r1(t,"timeoutMs",rw.ExchangeDeviceCodeToken),void 0!==e.codeVerifier&&rZ(e.codeVerifier,"codeVerifier",rw.ExchangeDeviceCodeToken)}function r6(e,t){if(!tl(e)||""===e.trim())throw new rI(`${t} must be a non-empty string`,{code:rF.InvalidResponse,operation:rw.StartDeviceAuthorization})}function r4(e,t,r){if(!Number.isInteger(e)||e<=0)throw new rI(`${t} must be a positive integer`,{code:rF.InvalidResponse,operation:rw.StartDeviceAuthorization,responseJson:r})}function r8(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 r9(e){let t=rQ(e.deviceAuthorizationEndpoint,rw.StartDeviceAuthorization,"deviceAuthorizationEndpoint"),r=e.timeoutMs??15e3;var i=e,n=r;if(rZ(i.clientId,"clientId",rw.StartDeviceAuthorization),r1(n,"timeoutMs",rw.StartDeviceAuthorization),void 0!==i.codeChallenge&&rZ(i.codeChallenge,"codeChallenge",rw.StartDeviceAuthorization),void 0!==i.codeChallengeMethod&&rZ(i.codeChallengeMethod,"codeChallengeMethod",rw.StartDeviceAuthorization),void 0===i.codeChallenge!=(void 0===i.codeChallengeMethod))throw new rI("codeChallenge and codeChallengeMethod must be provided together",{code:rF.InvalidArgument,operation:rw.StartDeviceAuthorization});let u=new URLSearchParams;u.set("client_id",e.clientId),rY(u,"scope",rW(e.scope)),rY(u,"code_challenge",e.codeChallenge),rY(u,"code_challenge_method",e.codeChallengeMethod),rJ(u,e.extraParams,rG,rw.StartDeviceAuthorization);let o=await r0({body:u,endpoint:t,httpClient:e.httpClient,headers:e.headers,operation:rw.StartDeviceAuthorization,signal:e.signal,timeoutMs:r});var s=o;if(r6(s.device_code,"device_code"),r6(s.user_code,"user_code"),r6(s.verification_uri,"verification_uri"),void 0!==s.verification_uri_complete&&r6(s.verification_uri_complete,"verification_uri_complete"),"number"!=typeof s.expires_in)throw new rI("expires_in must be a positive integer",{code:rF.InvalidResponse,operation:rw.StartDeviceAuthorization,responseJson:s});if(r4(s.expires_in,"expires_in",s),void 0!==s.interval){if("number"!=typeof s.interval)throw new rI("interval must be a positive integer",{code:rF.InvalidResponse,operation:rw.StartDeviceAuthorization,responseJson:s});r4(s.interval,"interval",s)}return o}async function r7(e){let t=rQ(e.tokenEndpoint,rw.ExchangeDeviceCodeToken,"tokenEndpoint"),r=e.timeoutMs??15e3;r3(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),rY(i,"code_verifier",e.codeVerifier),rJ(i,e.extraParams,rz,rw.ExchangeDeviceCodeToken);let n=await r0({body:i,endpoint:t,httpClient:e.httpClient,headers:e.headers,operation:rw.ExchangeDeviceCodeToken,signal:e.signal,timeoutMs:r});if("string"!=typeof n.access_token||""===n.access_token.trim())throw new rI("OAuth device token response is missing access_token",{code:rF.InvalidResponse,operation:rw.ExchangeDeviceCodeToken,responseJson:n});return n}async function r5(e){var t,r,i,n,u;let o=e.intervalSeconds??5;t=e,r=o,r3(t,t.timeoutMs??15e3),r1(r,"intervalSeconds",rw.PollDeviceToken),void 0!==t.expiresInSeconds&&r1(t.expiresInSeconds,"expiresInSeconds",rw.PollDeviceToken),void 0!==t.pollTimeoutMs&&r1(t.pollTimeoutMs,"pollTimeoutMs",rw.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 r7(e)}catch(t){if(!(t instanceof rI))throw t;if(t.error===rF.AuthorizationPending){await r2(s,c,e.signal);continue}if(t.error===rF.SlowDown){s+=5e3,await r2(s,c,e.signal);continue}if(t.error===rF.RequestTimeout||t.error===rF.NetworkError){await r2(s,c,e.signal);continue}throw t}throw new rI("Timed out waiting for OAuth device authorization",{code:rF.ExpiredToken,operation:rw.PollDeviceToken,details:{expiresInSeconds:e.expiresInSeconds,pollTimeoutMs:e.pollTimeoutMs}})}async function ie(e){let t=function(e){if(void 0!==e.codeChallenge||void 0!==e.codeChallengeMethod){if(!e.codeChallenge||!e.codeChallengeMethod)throw new rI("codeChallenge and codeChallengeMethod must be provided together",{code:rF.InvalidArgument,operation:rw.CreateDeviceFlowSession});if(!e.codeVerifier)throw new rI("codeVerifier is required when custom PKCE parameters are provided",{code:rF.InvalidArgument,operation:rw.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=rw.GeneratePKCE;if(!Number.isInteger(n)||n<32||n>96)throw new rB("verifierByteLength must be an integer between 32 and 96",{code:rF.InvalidArgument,operation:u});let o=(r=t,(0,tc.randomBytes)(r).toString("base64url")),s=(i=o,(0,tc.createHash)("sha256").update(i).digest("base64url"));return{codeVerifier:o,codeChallenge:s,codeChallengeMethod:"S256"}}({verifierByteLength:e.verifierByteLength})}(e),r=await r9({...e,codeChallenge:t.codeChallenge,codeChallengeMethod:t.codeChallengeMethod});return{authorization:r,codeVerifier:t.codeVerifier,codeChallenge:t.codeChallenge,codeChallengeMethod:t.codeChallengeMethod,pollToken:()=>r5({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 it(e){return e.replace(/[^a-zA-Z0-9]+/g,"")}function ir(e,t,r){let i=e[t];if(tl(i)&&i.trim())return i;throw new rB(`OAuth response is missing ${t}`,{code:rF.InvalidResponse,operation:r,details:{field:t}})}async function ii(e){let t=rQ(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??rH).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 rB("OAuth endpoint returned an empty response",{code:rF.InvalidResponse,operation:e.operation});let o=u.status,s=await u.text(),a=rK(s);if(void 0===o||o<200||o>=300)throw new rB(`OAuth endpoint returned HTTP ${o??"unknown"}`,{code:rF.HttpError,operation:e.operation,status:o,details:{responseBody:s,responseJson:a}});var i=a,n=e.operation;if(ta(i))return i;throw new rB("OAuth endpoint returned an invalid JSON object",{code:rF.InvalidResponse,operation:n})}catch(t){if(t instanceof rB)throw t;throw new rB("OAuth request failed",{cause:t,code:rX(t),operation:e.operation})}}async function iu(e){let t,r=await ii({url:e.metadataEndpoint,method:"GET",headers:e.headers,timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient,operation:rw.FetchAuthorizationServerMetadata});return{issuer:tl(r.issuer)&&r.issuer.trim()?r.issuer.trim():void 0,tokenEndpoint:ir(r,"token_endpoint",rw.FetchAuthorizationServerMetadata),introspectionEndpoint:ir(r,"introspection_endpoint",rw.FetchAuthorizationServerMetadata),revocationEndpoint:ir(r,"revocation_endpoint",rw.FetchAuthorizationServerMetadata),deviceAuthorizationEndpoint:ir(r,"device_authorization_endpoint",rw.FetchAuthorizationServerMetadata),registrationEndpoint:ir(r,"registration_endpoint",rw.FetchAuthorizationServerMetadata),scopesSupported:(t=r.scopes_supported,to(t)?t.filter(e=>tl(e)&&""!==e.trim()):[]),raw:r}}async function io(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 ii({url:e.registrationEndpoint,method:"POST",headers:e.headers,body:JSON.stringify(t),timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient,operation:rw.DynamicClientRegistration});return{clientId:ir(r,"client_id",rw.DynamicClientRegistration),raw:r}}async function is(e){let t=rQ(e.tokenEndpoint,rw.ExchangeToken,"tokenEndpoint"),r=e.grantType??"authorization_code",i=e.timeoutMs??15e3;!function(e,t,r){if(rZ(e.clientId,"clientId",rw.ExchangeToken),r1(r,"timeoutMs",rw.ExchangeToken),"authorization_code"===t){rZ(e.code,"code",rw.ExchangeToken),rZ(e.redirectUri,"redirectUri",rw.ExchangeToken),void 0!==e.codeVerifier&&rZ(e.codeVerifier,"codeVerifier",rw.ExchangeToken);return}if("refresh_token"===t)return rZ(e.refreshToken,"refreshToken",rw.ExchangeToken);throw new rB(`Unsupported OAuth grant type: ${t}`,{code:rF.InvalidArgument,operation:rw.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),rY(n,"code_verifier",e.codeVerifier)):(n.set("refresh_token",e.refreshToken),rY(n,"scope",rW(e.scope))),rJ(n,e.extraParams,rz,rw.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??rH).send({url:t.toString(),method:"POST",headers:u,data:n.toString(),timeoutMs:i,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!r)throw new rx("OAuth token endpoint returned an empty response",{code:rF.InvalidResponse});let o=r.status,s=await r.text(),a=rK(s),l=tl(a?.error)?a.error:void 0;if(void 0===o||o<200||o>=300)throw new rx(`OAuth token endpoint returned HTTP ${o??"unknown"}`,{code:rF.HttpError,responseBody:s,responseJson:a,status:o});if(l)throw new rx(`OAuth token endpoint returned error: ${l}`,{code:rF.InvalidResponse,responseBody:s,responseJson:a,status:o});if(!a)throw new rx("OAuth token endpoint returned a non-JSON response",{code:rF.InvalidResponse,responseBody:s,status:o});if(!tl(a.access_token)||""===a.access_token.trim())throw new rx("OAuth token response is missing access_token",{code:rF.InvalidResponse,responseBody:s,responseJson:a,status:o});return a}catch(e){if(e instanceof rx)throw e;throw new rx("OAuth token request failed",{cause:e,code:rX(e)})}}async function ia(e){var t,r,i;let n=rQ(e.introspectionEndpoint,rw.IntrospectToken,"introspectionEndpoint"),u=e.timeoutMs??15e3;t=e,r=u,rZ(t.token,"token",rw.IntrospectToken),rZ(t.clientId,"clientId",rw.IntrospectToken),r1(r,"timeoutMs",rw.IntrospectToken),void 0!==t.tokenTypeHint&&rZ(t.tokenTypeHint,"tokenTypeHint",rw.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??rH).send({url:n.toString(),method:"POST",headers:s,data:o.toString(),timeoutMs:u,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!t)throw new rS("OAuth token introspection endpoint returned an empty response",{code:rF.InvalidResponse});let r=t.status,a=await t.text(),l=rK(a);if(void 0===r||r<200||r>=300)throw new rS(`OAuth token introspection endpoint returned HTTP ${r??"unknown"}`,{code:rF.HttpError,responseBody:a,responseJson:l,status:r});if(!l||"boolean"!=typeof l.active)throw new rS("OAuth token introspection response is invalid",{code:rF.InvalidResponse,responseBody:a,responseJson:l,status:r});return{active:(i=l).active,scope:ic(i.scope),clientId:ic(i.client_id),clientName:ic(i.client_name),tokenType:ic(i.token_type),exp:id(i.exp),iat:id(i.iat),sub:ic(i.sub),raw:i}}catch(e){if(e instanceof rS)throw e;throw new rS("OAuth token introspection request failed",{cause:e,code:rX(e)})}}async function il(e){var t,r;let i=rQ(e.revocationEndpoint,rw.RevokeToken,"revocationEndpoint"),n=e.timeoutMs??15e3;t=e,r=n,rZ(t.token,"token",rw.RevokeToken),rZ(t.clientId,"clientId",rw.RevokeToken),r1(r,"timeoutMs",rw.RevokeToken),void 0!==t.tokenTypeHint&&rZ(t.tokenTypeHint,"tokenTypeHint",rw.RevokeToken);let u=new URLSearchParams({token:e.token,client_id:e.clientId});rY(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??rH).send({url:i.toString(),method:"POST",headers:o,data:u.toString(),timeoutMs:n,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!t)throw new rT("OAuth token revocation endpoint returned an empty response",{code:rF.InvalidResponse});let r=t.status,s=await t.text(),a=rK(s);if(void 0===r||r<200||r>=300)throw new rT(`OAuth token revocation endpoint returned HTTP ${r??"unknown"}`,{code:rF.HttpError,responseBody:s,responseJson:a,status:r})}catch(e){if(e instanceof rT)throw e;throw new rT("OAuth token revocation request failed",{cause:e,code:rX(e)})}}function ic(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function id(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function ip(e,t){let r=e[t];return r&&r.length>0?r:void 0}function ih(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?T.win32:T.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??td.homedir(),_=e.env??process.env;if("darwin"===m)return t=A,r=E,{configDir:T.join(r,"Library","Preferences",t),dataDir:T.join(r,"Library","Application Support",t),cacheDir:T.join(r,"Library","Caches",t),logDir:T.join(r,"Library","Logs",t),tempDir:T.join(td.tmpdir(),t)};if("win32"===m){let e,t,r;return i=A,n=E,e=ip(u=_,"APPDATA")??T.join(n,"AppData","Roaming"),t=ip(u,"LOCALAPPDATA")??T.join(n,"AppData","Local"),r=ip(u,"TEMP")??td.tmpdir(),{configDir:T.join(e,i,"Config"),dataDir:T.join(e,i,"Data"),cacheDir:T.join(t,i,"Cache"),logDir:T.join(t,i,"Log"),tempDir:T.join(r,i)}}return o=A,s=E,c=ip(a=_,"XDG_CONFIG_HOME")??T.join(s,".config"),d=ip(a,"XDG_DATA_HOME")??T.join(s,".local","share"),p=ip(a,"XDG_CACHE_HOME")??T.join(s,".cache"),h=ip(a,"XDG_STATE_HOME")??T.join(s,".local","state"),{configDir:T.join(c,o),dataDir:T.join(d,o),cacheDir:T.join(p,o),logDir:T.join(h,o,"logs"),tempDir:T.join(td.tmpdir(),o)}}function im(e){let t;function r(){let r,i;return t||(t=new tW((r=e.dir??"dataDir",i=ih(e),{baseDir:e.subDir?tP(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 ig(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 iA(e){let t=ig(e.total),r=ig(e.page),i=ig(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 iy(e){return String(e).padStart(2,"0")}function iE(e){return e.replace(/[^a-zA-Z0-9_-]+/g,"-")}async function i_(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=iy(t.getMonth()+1),n=iy(t.getDate()),u=iy(t.getHours()),o=iy(t.getMinutes()),s=iy(t.getSeconds()),a=String(t.getMilliseconds()).padStart(3,"0"),`${r}-${i}-${n}_${u}-${o}-${s}_${a}`),d=`${iE(e.command)}-${c}`;if(e.outputDir){let t=(0,T.resolve)(e.outputDir);if((0,I.existsSync)(t)&&!(0,I.statSync)(t).isDirectory())throw new l(`输出路径不是目录: ${t}`,{error:"INVALID_OUTPUT_DIR",message:`--output-dir 必须是一个目录,但 ${t} 是文件`});return(0,T.resolve)(t,d)}return(0,T.resolve)(process.cwd(),`${iE(e.appName)}-output`,d)}(e),u=(0,T.resolve)(n,t),o=(0,T.resolve)(n,r),s=(0,T.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 tL(s);let c=new tW({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 ib="aes-256-gcm";function iC(e,t,r,i=iD(r)){let n=(0,tc.randomBytes)(12),u=(0,tc.createCipheriv)(ib,t,n);u.setAAD(i);let o=Buffer.concat([u.update(e),u.final()]);return{version:1,algorithm:ib,keyProvider:r,iv:n.toString("base64"),authTag:u.getAuthTag().toString("base64"),ciphertext:o.toString("base64")}}function iv(e,t,r){if(32!==t.length)throw Error(`Invalid sensitive storage key length: ${t.length}`);let i=(0,tc.createDecipheriv)(ib,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 iD(e){return Buffer.from([1,ib,e].join(":"),"utf8")}function iF(e,t,r){return Buffer.from([1,ib,"scrypt",e,t,r].join(":"),"utf8")}function iw(e,t,r){return(0,tc.scryptSync)(function(e,t){let{uid:r,gid:i}=function(){try{let e=(0,td.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,td.platform)();return["open-game-cli-lib-ssfk-v1",e,t,n,(0,td.arch)(),r,i].join("\n")}(e,t),r,32)}function iB(e){if(!(e instanceof Error))return!1;let t=e?.code;return!!(tl(t)&&/no\s*entry|not\s*found/i.test(t))||/no\s*entry|not\s*found|notfound|not found/i.test(e?.message)}var ix=((Q={}).Auto="auto",Q.Keychain="keychain",Q.File="file",Q),iS=((Z={}).Read="read",Z.Write="write",Z.Remove="remove",Z);let iT=new Map;async function iI(){return await import("@napi-rs/keyring")}async function iO(e,t){let r=iT.get(e)??Promise.resolve(),i=()=>void 0,n=new Promise(e=>{i=e}),u=r.then(()=>n,()=>n);iT.set(e,u),await r.catch(()=>void 0);try{return await t()}finally{i(),iT.get(e)===u&&iT.delete(e)}}class ik{baseDir;service;account;fallbackKeyFile;fileStorage;keyStrategy;keychainTimeoutMs;onKeychainPrompt;fallbackKeyLockPath;fallbackKeyLockOptions;fallbackKeyScopeId;constructor(e){this.baseDir=(0,T.resolve)(e.baseDir),this.service=e.service,this.account=e.account,this.fallbackKeyFile=e.fallbackKeyFile??".sensitive-storage-key",this.fileStorage=new tW({baseDir:this.baseDir,baseDirMode:void 0===e.baseDirMode?448:e.baseDirMode}),this.keyStrategy=function(e){if(void 0===e)return ix.File;if(e===ix.Auto||e===ix.Keychain||e===ix.File)return e;throw TypeError(`keyStrategy must be one of: ${ix.File}, ${ix.Keychain}, ${ix.Auto}`)}(e.keyStrategy),this.keychainTimeoutMs=Math.max(0,e.keychainTimeoutMs??5e3),this.onKeychainPrompt=e.onKeychainPrompt,this.fallbackKeyLockPath=void 0===e.fallbackKeyLockPath?tP(this.baseDir,`${this.fallbackKeyFile}.lock`):e.fallbackKeyLockPath,this.fallbackKeyLockOptions=e.fallbackKeyLockOptions,this.fallbackKeyScopeId=function(e,t){return(0,tc.createHash)("sha256").update(e).update("\0").update(t).digest("hex").slice(0,32)}(this.service,this.account)}async readText(e,t="utf8"){let r=tP(this.baseDir,e);return(await this.readEncryptedData(r,tY.ReadText)).toString(t)}async writeText(e,t,r={}){let i=r.encoding??"utf8",n=tP(this.baseDir,e);await this.writeEncryptedData(n,Buffer.from(t,i),tY.WriteText)}async readJson(e,t="utf8"){let r=tP(this.baseDir,e),i=await this.readEncryptedData(r,tY.ReadJson);try{return JSON.parse(i.toString(t))}catch(e){throw new tK(`Failed to parse sensitive JSON data: ${r}`,{cause:e,code:tJ.InvalidJson,filePath:r,operation:tY.ReadJson})}}async writeJson(e,t,r={}){let i=r.encoding??"utf8",n=r.spaces??2,u=tP(this.baseDir,e),o=`${JSON.stringify(t,null,n)}
31
- `;await this.writeEncryptedData(u,Buffer.from(o,i),tY.WriteJson)}async remove(e){let t=tP(this.baseDir,e);try{await this.fileStorage.remove(t)}catch(e){if(tq(e))throw new tQ(t,tY.Remove,e);throw new tK(`Failed to remove sensitive data: ${t}`,{cause:e,code:tJ.DataStorageError,filePath:t,operation:tY.Remove})}}async removeKey(){let e;if(this.shouldUseKeychainOnRemove())try{let{AsyncEntry:e}=await iI(),t=new e(this.service,this.account);await this.runKeychainCall(()=>t.deleteCredential(),tY.RemoveKey,iS.Remove)}catch(t){t instanceof t2?e=t:iB(t)||(e=new t0("Failed to remove sensitive storage key from keychain",{cause:t,operation:tY.RemoveKey}))}if(this.shouldUseFileOnRemove()){let e=this.getFallbackKeyFilePath();try{await this.fileStorage.remove(e)}catch(t){if(!tq(t))throw new t0(`Failed to remove sensitive storage key file: ${e}`,{cause:t,filePath:e,operation:tY.RemoveKey})}}if(e)throw e}async readEncryptedData(e,t){let r=await this.tryReadEnvelope(e,t);if(!r)throw new tQ(e,t);this.assertReadableProvider(r.keyProvider,e,t);let i=await this.readKeyByProvider(r.keyProvider,e,t);try{return iv(r,i,iD(r.keyProvider))}catch(r){throw new tZ(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 tK)throw t;throw new tK(`Failed to write sensitive data: ${e}`,{cause:t,code:tJ.DataStorageError,filePath:e,operation:r})}}async resolveKeyForNewEnvelopeWithLock(e,t){return iO(this.getKeyResolutionLockId(),()=>this.resolveKeyForNewEnvelope(e,t))}getKeyResolutionLockId(){return[this.service,this.account,this.fallbackKeyFile].join("\0")}getFallbackKeyFilePath(){return tP(this.baseDir,`${this.fallbackKeyFile}.${this.fallbackKeyScopeId}.json`)}async resolveKeyForNewEnvelope(e,t){if(this.keyStrategy===ix.File){let e=(0,tc.randomBytes)(32);return{key:await this.ensureFileKey(e),provider:"file"}}if(this.keyStrategy===ix.Keychain){let r=await this.tryReadReusableKey("keychain",e,t);if(r)return r;let i=(0,tc.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,tc.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===ix.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===ix.Keychain?"keychain":"file"}shouldUseKeychainOnRemove(){return this.keyStrategy===ix.Auto||this.keyStrategy===ix.Keychain}shouldUseFileOnRemove(){return this.keyStrategy===ix.Auto||this.keyStrategy===ix.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(t3(e))return;throw e}}async tryReadEnvelope(e,t){let r;try{r=await this.fileStorage.readText(e,"utf8")}catch(r){if(tq(r))return;throw new tK(`Failed to read sensitive data: ${e}`,{cause:r,code:tJ.DataStorageError,filePath:e,operation:t})}try{var i,n=r;let e=JSON.parse(n);if(1!==e.version||e.algorithm!==ib||(i=e.keyProvider,!["keychain","file"].includes(i))||!tl(e.iv)||!tl(e.authTag)||!tl(e.ciphertext))throw Error("Invalid sensitive data envelope");return e}catch(r){throw new t1(e,t,r)}}async ensureFileKey(e){return!1===this.fallbackKeyLockPath?this.createFileKeyIfMissing(e):tG(this.fallbackKeyLockPath,async()=>this.createFileKeyIfMissing(e),this.fallbackKeyLockOptions)}async createFileKeyIfMissing(e){let t=this.getFallbackKeyFilePath();try{return await this.readKeyFromFile(void 0,tY.ReadKey)}catch(e){if(!t3(e))throw e}let r=(0,tc.randomBytes)(16),i=r.toString("base64"),n=iC(e,iw(this.service,this.account,r),"file",iF(this.service,this.account,i)),u={version:1,algorithm:ib,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:tY.WriteKey})}return e}async readKeyFromKeychain(e,t){try{let{AsyncEntry:u}=await iI(),o=new u(this.service,this.account),s=await this.runKeychainCall(()=>o.getPassword(),t,iS.Read);if(!s)throw new tX({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 tK)throw r;if(iB(r))throw new tX({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 iI(),r=new t(this.service,this.account);await this.runKeychainCall(()=>r.setPassword(e.toString("base64")),tY.WriteKey,iS.Write)}catch(e){if(e instanceof tK)throw e;throw new t0("Failed to write sensitive storage key to keychain",{cause:e,operation:tY.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 t2(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(tq(r))throw new tX({cause:r,filePath:e??i,operation:t});throw new t0(`Failed to read sensitive storage key file: ${i}`,{cause:h(r,tU)?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!==ib||"scrypt"!==t.kdf||!tl(t.salt)||!tl(t.iv)||!tl(t.authTag)||!tl(t.encryptedKey))throw Error("Invalid sensitive storage key envelope");return t}(r),t=iw(this.service,this.account,Buffer.from(e.salt,"base64")),i=iv({iv:e.iv,authTag:e.authTag,ciphertext:e.encryptedKey},t,iF(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 iR=/^[a-zA-Z0-9_-]+$/,iP=function(){1;return""}();function iL(e){return iP?`${e}:${iP}`:e}function iN(){return iP?`auth_${iP}`:"auth"}let ij=im({appName:"dymg"}),i$=im({appName:"dymg",subDir:iN()}),iM=new Set(["EACCES","EPERM","EROFS"]),iU=["读取"];function iq(e){return iU.some(t=>e.startsWith(t))}function iV(e){return!!function e(t,r=0){if(t&&!(r>8)){var i;if(t instanceof Error&&iM.has(t.code??""))return t;if("object"==typeof(i=t)&&null!==i&&"cause"in t)return e(t.cause,r+1)}}(e)}function iH(e,t){var r;if(!iV(e))throw e;throw new l(iq(t)?`${t}失败:无法访问或初始化登录态目录`:`${t}失败:登录态目录无写权限`,{cause:e,error:"AUTH_PERMISSION_DENIED",message:iq(r=t)?`${r}失败:当前终端无法访问或初始化登录态目录。`:`${r}失败:当前终端对登录态目录无写权限。`})}let iz="client.json",iG=!1;async function iW(){try{var e=await i$.readJson(iz);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:ry(e.clientIdIssuedAt),createdAt:v(e.createdAt)??Math.floor(Date.now()/1e3),updatedAt:v(e.updatedAt)??Math.floor(Date.now()/1e3)};throw new l("本地登录信息异常",{error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"})}catch(e){if(tq(e))return;if(p(e,tN.InvalidJson))throw new l("本地登录信息异常",{cause:e,error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"});iH(e,"读取登录配置")}}function iJ(e){if(e)return{clientId:e.clientId,clientName:e.clientName,clientIdIssuedAt:e.clientIdIssuedAt}}async function iY(){return iG?e:(t||(t=(async()=>{try{let t=await iW(),r=iJ(t);return e=r,iG=!0,r}finally{t=void 0}})()),t)}async function iK(t){let r=Math.floor(Date.now()/1e3),i=await iW(),n={clientId:t.clientId,clientName:t.clientName??i?.clientName,clientIdIssuedAt:t.clientIdIssuedAt??i?.clientIdIssuedAt,createdAt:i?.createdAt??r,updatedAt:r};try{await i$.writeJson(iz,n,{mode:384})}catch(e){iH(e,"保存登录配置")}e=iJ(n),iG=!0}async function iX(e){let t=await iY(),r=function(e){let t=it((0,td.hostname)().split(".")[0]??""),r="";try{r=it((0,td.userInfo)().username)}catch{r=it(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 io({registrationEndpoint:e.registrationEndpoint,clientName:r,timeoutMs:e.timeoutMs,httpClient:na});return await iK({clientId:i.clientId,clientName:"string"==typeof i.raw.client_name&&i.raw.client_name.trim()?i.raw.client_name.trim():r,clientIdIssuedAt:ry(i.raw.client_id_issued_at)}),i.clientId}async function iQ(e={}){var t,r;let i=await iu({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:na}),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 iX({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 iZ="profile.json",i1=function(e){let t;function r(){return t||(t=new rV(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}=ih({appName:"dymg"});return new ik({baseDir:(0,T.join)(e,iN()),service:iL(e4),account:iL("default")})}(),fileName:"token.json"}));async function i0(){try{var e;let t;return e=await i$.readJson(iZ),t=Math.floor(Date.now()/1e3),{uid:C(e?.uid),oauthAppId:C(e?.oauthAppId),oauthAppName:C(e?.oauthAppName),updatedAt:v(e?.updatedAt)??t}}catch(e){if(tq(e))return;throw e}}async function i2(e){try{await i$.writeJson(iZ,e,{mode:384})}catch(e){iH(e,"保存登录信息")}}async function i3(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 i2(r),r):t}async function i6(){try{await i$.remove(iZ)}catch(e){tq(e)||iH(e,"清理登录信息")}}function i4(e,t){try{return function(e,t={}){let r,i=Math.floor((t.nowMs??Date.now())/1e3),n=ry(e.expires_in)??t.defaultAccessTokenExpiresInSeconds??3600,u=ry(e.refresh_token_expires_in),o=ic(e.refresh_token),s=o??t.current?.auth.refreshToken,a=void 0===e.scope?t.current?.auth.scopes??[]:(r=rW(e.scope))?r.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[];if(!s)throw new rx("OAuth token response is missing refresh_token",{code:rF.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:`登录失败,请重新执行 ${e8}`})}}async function i8(e){await i3({uid:C(e.uid),oauthAppId:C(e.oauth_app_id),oauthAppName:C(e.oauth_app_name)})}async function i9(e){let t;try{t=await iQ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e8}`});throw e}let r=await is({tokenEndpoint:t.tokenEndpoint,clientId:t.clientId,grantType:"refresh_token",refreshToken:e.auth.refreshToken,scope:e.auth.scopes,httpClient:na});return await i8(r).catch(()=>void 0),i4(r,e)}function i7(e){var t;if(iV(e)&&iH(e,"刷新登录态"),p(e,"REFRESH_TOKEN_EXPIRED"))throw new l("当前登录已过期,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已过期,请执行 ${e8}`});if(p(t=e,"REFRESH_FAILED")&&rk(t.cause)||rk(e))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e8}`});throw e}async function i5(){try{return await i1.tryGet()}catch(e){throw iV(e)&&iH(e,"读取登录信息"),new l("本地登录信息异常",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`本地登录信息异常,请先执行 ${e5},再执行 ${e8}`})}}async function ne(){if(await i5())try{return await i1.getAccessToken(i9)}catch(e){i7(e)}}async function nt(){let e=await i5();if(e)try{return(await i1.refresh(e,i9)).auth.accessToken}catch(e){i7(e)}}async function nr(e){let t;if(e){try{t=await iQ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))return;throw e}try{await il({revocationEndpoint:t.revocationEndpoint,token:e.auth.refreshToken,tokenTypeHint:"refresh_token",clientId:t.clientId,httpClient:na})}catch(e){throw new l("退出登录失败,请稍后重试",{cause:e,error:"AUTH_LOGOUT_REVOKE_FAILED",message:"退出登录失败,请检查网络后重试"})}}}async function ni(){let e,t,r=await ne();if(!r)return;try{e=await iQ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e8}`});throw e}try{t=await ia({introspectionEndpoint:e.introspectionEndpoint,token:r,tokenTypeHint:"access_token",clientId:e.clientId,httpClient:na})}catch(e){throw new l("登录态校验失败,请稍后重试或重新登录",{cause:e,error:"AUTH_STATUS_CHECK_FAILED",message:`登录态校验失败,请稍后重试;如问题持续,可执行 ${e8}`})}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:`当前登录已失效,请执行 ${e8}`});return await i3({uid:i.uid,oauthAppId:i.oauthAppId,oauthAppName:i.oauthAppName}).catch(()=>void 0),i}async function nn(e,t){let r=i4(e,t);try{await Promise.all([i1.save(r),i8(e).catch(()=>void 0)])}catch(e){iH(e,"保存登录态")}return r}async function nu(){try{await Promise.all([i1.clear(),i6()])}catch(e){iH(e,"退出登录")}}let no=new e0,ns=new e0,na=new e0;function nl(e){return new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:e??`当前命令需要先登录,请先执行 ${e8}`})}function nc(){return new l("当前登录已失效,请重新登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e8}`})}function nd(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 np(e){if(e?.trim())try{return nd(JSON.parse(e))}catch{return}}function nh(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?nc():nl();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=nc();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 nf(e){if(!eJ(e))throw e;nh(np(e.responseBody),{status:e.status,cause:e})}function nm(e){let t=nd(e);t&&void 0!==t.error&&0!==t.error&&nh(t)}async function ng(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 ns.send(n,{meta:t.meta});return nm(e),e}catch(r){eJ(i=r)&&401===i.status||nf(r);let e=eJ(r)?np(r.responseBody):void 0;if(!await nt())throw e?.error===1002?nl():nc();try{let{data:e}=await ns.send(n,{meta:t.meta});return nm(e),e}catch(e){nf(e)}}}let nA="session.json";async function ny(e){try{await i$.writeJson(nA,e,{mode:384})}catch(e){iH(e,"保存授权会话")}}async function nE(){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=v(e?.createdAt),a=v(e?.expiresAt);if(!t||!r||!i||!n||!u||!o||!s||!a)throw new l("本地授权会话异常",{error:"INVALID_AUTH_SESSION",message:`本地授权会话异常,请重新执行 ${e9}`});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 i$.readJson(nA))}catch(e){if(tq(e))return;iH(e,"读取授权会话")}}async function n_(){try{await i$.remove(nA)}catch(e){tq(e)||iH(e,"清理授权会话")}}let nb=["coze","cursor","claude_code","github_copilot","gemini_cli","trae","manus","devin","codex","hermes","openclaw","unknown"];function nC(e){return nb.includes(e)}let nv="宿主枚举:1 全部 / 2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山 / 9 皮皮虾",nD="宿主枚举:2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山",nF="操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony / 5 Windows",nw="设备档位枚举:1 全部 / 2 高端 / 3 中端 / 4 低端";function nB(e,t){let{caller:r}=e.optsWithGlobals();return{...t,caller:"string"==typeof r&&nC(r)?r:"unknown"}}function nx(e){return e.option("--output-dir <dir>","输出根目录,默认 ./dymg-output(会在其下按命令+时间生成子目录,并按命令类型写入结果文件)"),e}async function nS(e){let t=await iY().catch(()=>void 0);return{toolId:e.replaceAll(":"," "),clientId:t?.clientId}}function nT(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>",nv).option("--os <os>",nF).option("--user-type <userType>","用户类型枚举:1 全部 / 2 新增 / 3 活跃 / 4 付费新增 / 5 付费活跃").option("--segment <segment>","用户分群枚举:1 不分组 / 2 侧边栏奖励 / 3 App 活跃")}function nI(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>",nD).requiredOption("--os <os>","操作系统枚举:2 Android / 3 iOS / 4 OpenHarmony").option("--device-level <n>",nw).option("--mp-version <version>","小游戏版本号")}var nO=__webpack_require__("../../node_modules/.pnpm/@dp+tea-sdk-node@3.0.12/node_modules/@dp/tea-sdk-node/lib/index.js"),nk=__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 nR=Number(626386),nP=null;function nL(){let e=tr();if(e?.tool&&void 0!==e.requestParams)return{caller:e.caller,tool:e.tool,requestParams:e.requestParams}}async function nN(e){let t=(void 0===r&&(r=function(){if(!Number.isFinite(nR)||nR<=0)return null;let e=globalThis.fetch?(e,t)=>globalThis.fetch(e,t):void 0,t=new nO.TeaSDK({app_id:nR}),r=(0,nk.httpPlugin)({channel:"cn",...e?{transport:(t,r)=>e(t,r)}:{}});return nP=r,t.use(r),t.config({custom:{cli_name:"dymg"}}),t}()),r);if(!t)return;let[i,n]=await Promise.all([iY().catch(()=>void 0),i0().catch(()=>void 0)]),u=tr(),o=function(e=3e3){let t=nP;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.5.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 nj(e){return d(e)?e.error:void 0}let n$=["npm","pnpm","yarn","bun"],nM=new e0;function nU(e){var t;return(t=e,n$.includes(t))?e:void 0}function nq(e={}){var t;let r=nU(e.input);return void 0!==e.input?r:(t=e.userAgent,nU(t?.split("/")[0])??e.defaultPackageManager)}async function nV(e,t={}){let r=e.trim(),i=t.client??nM,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 eG("packageName is required",{code:ez.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 eG("package registry response missing version",{code:ez.InvalidJson,url:a});return l.version.trim()}let nH="update-check.json";function nz(e){let t=nq({userAgent:process.env.npm_config_user_agent})?"dymg update":`dymg update --package-manager <${n$.join("|")}>`;return[`检测到 ${e3} 新版本 ${e}(当前 0.5.0)。`,`执行 ${t} 可更新 CLI 并同步随包发布的 Skill。`,"如只想手动同步 Skill,可执行 dymg skills install。"]}async function nG(){try{return await ij.get().readJson(nH)}catch(e){if(tq(e))return{};throw e}}async function nW(e){await ij.get().writeJson(nH,e)}async function nJ(){return nV(e3,{client:no,timeoutMs:1e4})}async function nY(){let e=await nJ();return{currentVersion:"0.5.0",latestVersion:e,hasUpdate:function(e,t){let r=b(e),i=b(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.5.0")>0}}async function nK(e,t={}){let r=await nG(),i=Date.now(),n={...r,lastCheckedAt:i,latestVersion:e.latestVersion};t.notified&&(n.lastNotifiedAt=i,n.lastNotifiedVersion=e.latestVersion),await nW(n)}async function nX(e={}){var t,r,i,n,u,o;let s=e.force??!1,a=e.quiet??!1,l=Date.now(),c=await nG();if(t=l,r=c,!s&&!(t-(r.lastCheckedAt??0)>=864e5))return;let d=await nY(),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(["",...nz(o),""].join("\n")),p.lastNotifiedAt=l,p.lastNotifiedVersion=d.latestVersion),await nW(p);return}a||process.stdout.write(`dymg 已是最新版本(0.5.0)
32
- `),await nW(p)}async function nQ(){try{await nX({quiet:!0})}catch{}}let nZ={request:ng,baseURL:""};nZ.genBaseURL=e=>"function"==typeof nZ.baseURL?nZ.baseURL(e):nZ.baseURL+e;let n1=(e=0)=>t=>`\u001B[${t+e}m`,n0=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,n2=(e=0)=>(t,r,i)=>`\u001B[${38+e};2;${t};${r};${i}m`,n3={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(n3.modifier);let n6=Object.keys(n3.color);[...n6,...Object.keys(n3.bgColor)];let n4=function(){let e=new Map;for(let[t,r]of Object.entries(n3)){for(let[t,i]of Object.entries(r))n3[t]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[t]=n3[t],e.set(i[0],i[1]);Object.defineProperty(n3,t,{value:r,enumerable:!1})}return Object.defineProperty(n3,"codes",{value:e,enumerable:!1}),n3.color.close="\x1b[39m",n3.bgColor.close="\x1b[49m",n3.color.ansi=n1(),n3.color.ansi256=n0(),n3.color.ansi16m=n2(),n3.bgColor.ansi=n1(10),n3.bgColor.ansi256=n0(10),n3.bgColor.ansi16m=n2(10),Object.defineProperties(n3,{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=>n3.rgbToAnsi256(...n3.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)=>n3.ansi256ToAnsi(n3.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>n3.ansi256ToAnsi(n3.hexToAnsi256(e)),enumerable:!1}}),n3}(),n8=require("node:tty");function n9(e,t=globalThis.Deno?globalThis.Deno.args:O.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:n7}=O;function n5(e,t={}){var r;return 0!==(r=function(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let n=function(){if("FORCE_COLOR"in n7)return"true"===n7.FORCE_COLOR?1:"false"===n7.FORCE_COLOR?0:0===n7.FORCE_COLOR.length?1:Math.min(Number.parseInt(n7.FORCE_COLOR,10),3)}();void 0!==n&&(i=n);let u=r?i:n;if(0===u)return 0;if(r){if(n9("color=16m")||n9("color=full")||n9("color=truecolor"))return 3;if(n9("color=256"))return 2}if("TF_BUILD"in n7&&"AGENT_NAME"in n7)return 1;if(e&&!t&&void 0===u)return 0;let o=u||0;if("dumb"===n7.TERM)return o;if("win32"===O.platform){let e=td.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in n7)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in n7)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in n7)||"codeship"===n7.CI_NAME?1:o;if("TEAMCITY_VERSION"in n7)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n7.TEAMCITY_VERSION);if("truecolor"===n7.COLORTERM||"xterm-kitty"===n7.TERM||"xterm-ghostty"===n7.TERM||"wezterm"===n7.TERM)return 3;if("TERM_PROGRAM"in n7){let e=Number.parseInt((n7.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n7.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(n7.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n7.TERM)||"COLORTERM"in n7?1:o}(e,{streamIsTTY:e&&e.isTTY,...t}))&&{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}n9("no-color")||n9("no-colors")||n9("color=false")||n9("color=never")?i=0:(n9("color")||n9("colors")||n9("color=true")||n9("color=always"))&&(i=1);let ue={stdout:n5({isTTY:n8.isatty(1)}),stderr:n5({isTTY:n8.isatty(2)})},{stdout:ut,stderr:ur}=ue,ui=Symbol("GENERATOR"),un=Symbol("STYLER"),uu=Symbol("IS_EMPTY"),uo=["ansi","ansi","ansi256","ansi16m"],us=Object.create(null);function ua(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=ut?ut.level:0;e.level=void 0===t.level?r:t.level})(r=(...e)=>e.join(" "),t),Object.setPrototypeOf(r,ua.prototype),r}for(let[e,t]of(Object.setPrototypeOf(ua.prototype,Function.prototype),Object.entries(n4)))us[e]={get(){let r=up(this,ud(t.open,t.close,this[un]),this[uu]);return Object.defineProperty(this,e,{value:r}),r}};us.visible={get(){let e=up(this,this[un],!0);return Object.defineProperty(this,"visible",{value:e}),e}};let ul=(e,t,r,...i)=>"rgb"===e?"ansi16m"===t?n4[r].ansi16m(...i):"ansi256"===t?n4[r].ansi256(n4.rgbToAnsi256(...i)):n4[r].ansi(n4.rgbToAnsi(...i)):"hex"===e?ul("rgb",t,r,...n4.hexToRgb(...i)):n4[r][e](...i);for(let e of["rgb","hex","ansi256"])us[e]={get(){let{level:t}=this;return function(...r){return up(this,ud(ul(e,uo[t],"color",...r),n4.color.close,this[un]),this[uu])}}},us["bg"+e[0].toUpperCase()+e.slice(1)]={get(){let{level:t}=this;return function(...r){return up(this,ud(ul(e,uo[t],"bgColor",...r),n4.bgColor.close,this[un]),this[uu])}}};let uc=Object.defineProperties(()=>{},{...us,level:{enumerable:!0,get(){return this[ui].level},set(e){this[ui].level=e}}}),ud=(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}},up=(e,t,r)=>{let i=(...e)=>uh(i,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(i,uc),i[ui]=e,i[un]=t,i[uu]=r,i},uh=(e,t)=>{if(e.level<=0||!t)return e[uu]?"":t;let r=e[un];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(ua.prototype,us);let uf=ua();ua({level:ur?ur.level:0});let um=(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);(ug(n,u)||!i)&&Object.defineProperty(e,r,u)},ug=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)},uA=(e,t)=>`/* Wrapped ${e}*/
33
- ${t}`,uy=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),uE=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),u_=new WeakMap,ub=(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(u_.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))um(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=uA.bind(null,i,t.toString());Object.defineProperty(n,"name",uE);let{writable:u,enumerable:o,configurable:s}=uy;Object.defineProperty(e,"toString",{value:n,writable:u,enumerable:o,configurable:s})})(e,t,u)}(u,e),u_.set(u,i),u};ub.callCount=e=>{if(!u_.has(e))throw Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return u_.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 uv=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,uD=Symbol.for("signal-exit emitter"),uF=globalThis,uw=Object.defineProperty.bind(Object);class uB{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(uF[uD])return uF[uD];uw(uF,uD,{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 ux{}class uS extends ux{#i="win32"===uT.platform?"SIGINT":"SIGHUP";#n=new uB;#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(!uv(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 uv(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&&uv(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 uT=globalThis.process,{onExit:uI,load:uO,unload:uk}=(u=uv(uT)?new uS(uT):new class extends ux{onExit(){return()=>{}}load(){}unload(){}},{onExit:(e,t)=>u.onExit(e,t),load:()=>u.load(),unload:()=>u.unload()}),uR=O.stderr.isTTY?O.stderr:O.stdout.isTTY?O.stdout:void 0,uP=uR?ub(()=>{uI(()=>{uR.write("\x1b[?25h")},{alwaysLast:!0})}):()=>{},uL=!1,uN={};uN.show=(e=O.stderr)=>{e.isTTY&&(uL=!1,e.write("\x1b[?25h"))},uN.hide=(e=O.stderr)=>{e.isTTY&&(uP(),uL=!0,e.write("\x1b[?25l"))},uN.toggle=(e,t)=>{void 0!==e&&(uL=e),uL?uN.show(t):uN.hide(t)};var uj=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(uj);let u$=n8?.WriteStream?.prototype?.hasColors?.()??!1,uM=(e,t)=>{if(!u$)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}};uM(0,0),uM(1,22),uM(2,22),uM(3,23),uM(4,24),uM(53,55),uM(7,27),uM(8,28),uM(9,29),uM(30,39);let uU=uM(31,39),uq=uM(32,39),uV=uM(33,39),uH=uM(34,39);function uz(){let{env:e}=O,{TERM:t,TERM_PROGRAM:r}=e;return"win32"!==O.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}uM(35,39),uM(36,39),uM(37,39),uM(90,39),uM(40,49),uM(41,49),uM(42,49),uM(43,49),uM(44,49),uM(45,49),uM(46,49),uM(47,49),uM(100,49),uM(91,39),uM(92,39),uM(93,39),uM(94,39),uM(95,39),uM(96,39),uM(97,39),uM(101,49),uM(102,49),uM(103,49),uM(104,49),uM(105,49),uM(106,49),uM(107,49);let uG=uz(),uW=uH(uG?"ℹ":"i"),uJ=uq(uG?"✔":"√"),uY=uV(uG?"⚠":"‼"),uK=uU(uG?"✖":"\xd7"),uX=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")}(),uQ=[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],uZ=[12288,12288,65281,65376,65504,65510],u1=[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},[u2,u3]=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]}(u1);function u6(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(uZ,r)||(i=e)>=u2&&i<=u3||!(i<4352)&&!(i>262141)&&u0(u1,i)||t&&!((n=e)<161)&&!(n>1114109)&&u0(uQ,n)?2:1}let u4=new Intl.Segmenter,u8=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,u9=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,u7=/^\p{RGI_Emoji}$/v,u5=/^[\d#*]\u20E3$/,oe=/\p{Extended_Pictographic}/gu;function ot(e){return e>=4352&&e<=4447||e>=43360&&e<=43388}function or(e){return e>=4448&&e<=4519||e>=55216&&e<=55238}function oi(e){return e>=4520&&e<=4607||e>=55243&&e<=55291}let on=Object.freeze(new class{#p=0;#h;#f=!1;#m=!1;#g=e=>{e?.length&&("string"==typeof e?e.codePointAt(0):e[0])===3&&O.kill(O.pid,"SIGINT")};start(){this.#p++,1===this.#p&&this.#A()}stop(){0!==this.#p&&0==--this.#p&&this.#y()}#A(){let{stdin:e}=O;if("win32"===O.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}}),ou=new Map,oo=new Set(["black","red","green","yellow","blue","magenta","cyan","white","gray"]);class os{#E=0;#_=-1;#b=0;#C;#v;#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.#C={color:"cyan",stream:O.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#C.color,this.#D=this.#C.stream,"boolean"!=typeof this.#C.isEnabled&&(this.#C.isEnabled=function({stream:e=process.stdout}={}){return!!(e&&e.isTTY&&"dumb"!==process.env.TERM&&!("CI"in process.env))}({stream:this.#D})),"boolean"!=typeof this.#C.isSilent&&(this.#C.isSilent=!1),void 0!==this.#C.interval&&!(Number.isInteger(this.#C.interval)&&this.#C.interval>0))throw Error("The `interval` option must be a positive integer");const t=this.#C.interval;this.spinner=this.#C.spinner,this.#C.interval=t,this.text=this.#C.text,this.prefixText=this.#C.prefixText,this.suffixText=this.#C.suffixText,this.indent=this.#C.indent,"test"===O.env.NODE_ENV&&(this._stream=this.#D,this._isEnabled=this.#C.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.#C.prefixText?"":this.#C.prefixText,r="function"==typeof this.#C.suffixText?"":this.#C.suffixText,i=" ".repeat(this.#C.indent)+("string"==typeof t&&""!==t?t+" ":"")+"-"+("string"==typeof this.#C.text?" "+this.#C.text:"")+("string"==typeof r&&""!==r?" "+r:"");return this.#U(i,e)}}))}get indent(){return this.#C.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.#C.indent=e}get interval(){return this.#C.interval??this.#v.interval??100}get spinner(){return this.#v}set spinner(e){if(this.#_=-1,this.#C.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.#v=e}else if(uz())if(void 0===e)this.#v=uj.dots;else if("default"!==e&&uj[e])this.#v=uj[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.#v=uj.line}get text(){return this.#C.text}set text(e=""){this.#C.text=e}get prefixText(){return this.#C.prefixText}set prefixText(e=""){this.#C.prefixText=e}get suffixText(){return this.#C.suffixText}set suffixText(e=""){this.#C.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.#C.prefixText,t=" "){return this.#q(e,t,!1)}#M(e=this.#C.suffixText,t=" "){return this.#q(e,t,!0)}#U(e,t){let r=0;for(let i of(0,k.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(uX,""):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 u4.segment(n)){var s;if(s=e,u8.test(s))continue;if(u7.test(e)||function(e){if(e.length>50)return!1;if(u5.test(e))return!0;if(e.includes("‍")){let t=e.match(oe);return null!==t&&t.length>=2}return!1}(e)){u+=2;continue}let t=e.replace(u9,""),r=function(e,t){let r=[];for(let t of e)u8.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(!(ot(n=u)||or(n)||oi(n))){if(0===i)return;for(let n=e;n<r.length;n++)i+=u6(r[n],t);break}if(ot(u)&&or(r[e+1])){i+=2,e+=oi(r[e+2])?2:1;continue}i+=u6(u,t)}return i}(t,o);if(void 0!==r){u+=r;continue}u+=u6(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+=u6(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&&!oo.has(e))throw Error("The `color` option must be a valid color or `false` to disable");this.#I=e}get isEnabled(){return this.#C.isEnabled&&!this.#C.isSilent}set isEnabled(e){if("boolean"!=typeof e)throw TypeError("The `isEnabled` option must be a boolean");this.#C.isEnabled=e}get isSilent(){return this.#C.isSilent}set isSilent(e){if("boolean"!=typeof e)throw TypeError("The `isSilent` option must be a boolean");this.#C.isSilent=e}frame(){let e=Date.now();(-1===this.#_||e-this.#b>=this.interval)&&(this.#_=(this.#_+1)%this.#v.frames.length,this.#b=e);let{frames:t}=this.#v,r=t[this.#_];this.#I&&(r=uf[this.#I](r));let i=this.#$(this.#C.prefixText," "),n="string"==typeof this.text?" "+this.text:"";return i+r+n+this.#M(this.#C.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.#C.indent&&this.#D.cursorTo(this.#C.indent)}),this.#E=0),this}#V(e){if(!e||this.#w.has(e)||!e.isTTY||"function"!=typeof e.write)return;ou.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),ou.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,O.stdout,O.stderr]))this.#V(e)}#G(){for(let[e,t]of this.#w)e.write=t,ou.get(e)===this&&ou.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.#C.indent)+this.#j(e,this.text,this.#C.prefixText,this.#C.suffixText);return""!==t.trim()&&this.#O(()=>this.#D.write(t+"\n")),this}return this.isSpinning||(this.#C.hideCursor&&uN.hide(this.#D),this.#C.discardStdin&&O.stdin.isTTY&&(on.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.#C.hideCursor&&uN.show(this.#D)),this.#T&&(this.#T=!1,on.stop()),this}succeed(e){return this.stopAndPersist({symbol:uJ,text:e})}fail(e){return this.stopAndPersist({symbol:uK,text:e})}warn(e){return this.stopAndPersist({symbol:uY,text:e})}info(e){return this.stopAndPersist({symbol:uW,text:e})}stopAndPersist(e={}){if(this.isSilent)return this;let t=e.symbol??" ",r=e.text??this.text,i=e.prefixText??this.#C.prefixText,n=e.suffixText??this.#C.suffixText,u=this.#j(t,r,i,n)+"\n";return this.stop(),this.#O(()=>this.#D.write(u)),this}}function oa(e){return new os(e)}async function ol(e,t,r){return tt({appId:t.appId,caller:t.caller}),(async()=>{let i=oa(`正在执行 ${e} ...`).start();try{let{rawResponse:n,rows:u,csvHeader:o,resultMeta:s}=await r({caller:t.caller}),a=tr()?.response?.logId,{summaryPath:l}=await i_({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);tt({errorMessage:t,errorCode:nj(n)}),process.stderr.write(`${t}
30
+ `,{encoding:i,mode:r.mode})}catch(r){if(h(r,tU))throw r;let t=tP(this.baseDir,e);throw new t$(`Failed to write CSV file: ${t}`,{cause:r,code:tN.StorageError,filePath:t,operation:tj.WriteCsv})}}}var tJ=((z={}).KeyNotFound="KEY_NOT_FOUND",z.DataNotFound="DATA_NOT_FOUND",z.DecryptionFailed="DECRYPTION_FAILED",z.KeyStorageError="KEY_STORAGE_ERROR",z.DataStorageError="DATA_STORAGE_ERROR",z.InvalidJson="INVALID_JSON",z.InvalidEnvelope="INVALID_ENVELOPE",z.KeychainTimeout="KEYCHAIN_TIMEOUT",z),tY=((G={}).ReadText="readText",G.WriteText="writeText",G.ReadJson="readJson",G.WriteJson="writeJson",G.Remove="remove",G.Clear="clear",G.ReadKey="readKey",G.WriteKey="writeKey",G.RemoveKey="removeKey",G);class tK 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 tX extends tK{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 tQ extends tK{constructor(e,t,r){super(`Sensitive data not found: ${e}`,{cause:r,code:"DATA_NOT_FOUND",filePath:e,operation:t}),this.name="SensitiveDataNotFoundError"}}class tZ extends tK{constructor(e,t,r){super(`Failed to decrypt sensitive data: ${e}`,{cause:r,code:"DECRYPTION_FAILED",filePath:e,operation:t}),this.name="SensitiveDecryptionError"}}class t1 extends tK{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 tK{constructor(e,t){super(e,{cause:t.cause,code:t.code??"KEY_STORAGE_ERROR",filePath:t.filePath,operation:t.operation}),this.name="SensitiveKeyStorageError"}}class t0 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 t3=f("KEY_NOT_FOUND"),t6=f("DATA_NOT_FOUND");function t4(e){return e?e.split(",").map(e=>e.trim()).filter(e=>""!==e):[]}f("DECRYPTION_FAILED"),f("INVALID_ENVELOPE");let t8=/^\d{4}-\d{2}-\d{2}$/,t9=/^\d{4}(0[1-9]|1[0-2])$/,t7=/^-?(0|[1-9]\d*)$/,t5=/^[1-9]\d*$/;var re=((W={}).InvalidEnum="INVALID_ENUM",W.InvalidIntList="INVALID_INT_LIST",W.InvalidDate="INVALID_DATE",W.InvalidRange="INVALID_RANGE",W.InvalidPositiveInt="INVALID_POSITIVE_INT",W.InvalidDateRange="INVALID_DATE_RANGE",W.OutOfLookback="OUT_OF_LOOKBACK",W.InvalidTimestamp="INVALID_TIMESTAMP",W.InvalidTimestampRange="INVALID_TIMESTAMP_RANGE",W);function rt(e){return String(e).padStart(2,"0")}function rr(e){let t=e.getFullYear(),r=rt(e.getMonth()+1),i=rt(e.getDate());return`${t}-${r}-${i}`}function ri(e,t,r){if(void 0!==e&&!r.includes(e))throw new l(`参数 ${t} 取值非法: ${e}`,{error:"INVALID_ENUM",message:`${t} 只能取 ${r.join(" / ")}`})}function rn(e,t,r){if(void 0!==e){for(let i of t4(e))if(!r.includes(i))throw new l(`参数 ${t} 包含非法取值: ${i}`,{error:"INVALID_ENUM",message:`${t} 每一项只能取 ${r.join(" / ")}`})}}function ru(e,t){if(void 0!==e){for(let r of t4(e))if(!t7.test(r))throw new l(`参数 ${t} 包含非法取值: ${r}`,{error:"INVALID_INT_LIST",message:`${t} 每一项必须是整数,但包含非法值: ${r}`})}}function ro(e,t){if(void 0===e)return;let r=new Date(`${e}T00:00:00Z`);if(!t8.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 rs(e,t,r,i){if(void 0===e)return;let n=t7.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 ra(e,t){if(void 0!==e&&!t5.test(e))throw new l(`参数 ${t} 非法: ${e}`,{error:"INVALID_POSITIVE_INT",message:`${t} 必须是正整数`})}function rl(e){let{startDate:t,endDate:r}=e,i=e.startField??"--start-date",n=e.endField??"--end-date";if(ro(t,i),ro(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=rr(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 rc(e){let{startDate:t,endDate:r,maxLookbackDays:i,label:n,latestDateOffsetDays:u=0}=e,o=e.startField??"--start-date",s=e.endField??"--end-date";rl(e);let a=rr(new Date(Date.now()-864e5*u)),c=rr(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 rd(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(!t5.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 rp(e){let t=rd(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 rh(e){let t=t4(e);return t.length>0?t:void 0}function rf(e){let t=rh(e);if(!t)return;let r=t.map(Number).filter(e=>!Number.isNaN(e));return r.length>0?r:void 0}function rm(e,t,r){let i=rh(e),n=String(r);if(!i||1===i.length&&i[0]===n)return;if(i.includes(n))throw new l(`${t} 的全部选项 ${n} 不能与其他枚举值同时使用`,{error:re.InvalidEnum,message:`${t} 的枚举值 ${n} 表示全部,必须单独使用`});let u=i.find(e=>!t7.test(e));if(void 0!==u)throw new l(`参数 ${t} 包含非法取值: ${u}`,{error:re.InvalidIntList,message:`${t} 每一项必须是整数,但包含非法值: ${u}`});return i.map(Number)}function rg(e,t){if(void 0===e)return t;let r=t7.test(e)?Number(e):NaN;return Number.isNaN(r)?t:r}function rA(e){if(null==e)return;let t=String(e).trim();if("number"==typeof e&&!Number.isSafeInteger(e)||!t7.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 ry(e){if("number"==typeof e&&Number.isInteger(e)&&e>0)return e;if("string"!=typeof e||!t7.test(e))return;let t=Number(e);return t>0?t:void 0}function rE(e){return String(e).padStart(2,"0")}function r_(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=rE(u.getMonth()+1),a=rE(u.getDate());if("date"===r)return`${o}-${s}-${a}`;let l=rE(u.getHours()),c=rE(u.getMinutes()),d=rE(u.getSeconds());return`${o}-${s}-${a} ${l}:${c}:${d}`}function rb(e){return Object.values(e).filter(e=>"number"==typeof e).map(String)}function rC(e,t){let r=function(e){if(void 0===e||!t7.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 rv(e,t){let r="number"==typeof t?t:t7.test(t)?Number(t):NaN;return"string"==typeof e[r]?String(e[r]):String(t)}let rD=new Set(["access_denied","expired_token","invalid_client","invalid_grant","unauthorized_client"]);var rF=((J={}).InvalidArgument="INVALID_ARGUMENT",J.PortUnavailable="PORT_UNAVAILABLE",J.CallbackAborted="CALLBACK_ABORTED",J.CallbackTimeout="CALLBACK_TIMEOUT",J.CallbackError="CALLBACK_ERROR",J.RequestAborted="REQUEST_ABORTED",J.RequestTimeout="REQUEST_TIMEOUT",J.NetworkError="NETWORK_ERROR",J.HttpError="HTTP_ERROR",J.InvalidResponse="INVALID_RESPONSE",J.AuthorizationPending="AUTHORIZATION_PENDING",J.SlowDown="SLOW_DOWN",J.AccessDenied="ACCESS_DENIED",J.ExpiredToken="EXPIRED_TOKEN",J),rw=((Y={}).GeneratePKCE="generatePKCE",Y.GenerateState="generateState",Y.BuildAuthUrl="buildAuthUrl",Y.BuildLoopbackRedirectUri="buildLoopbackRedirectUri",Y.GetAvailablePort="getAvailablePort",Y.CreateLocalCallbackHandler="createLocalCallbackHandler",Y.HandleLocalCallback="handleLocalCallback",Y.ExchangeToken="exchangeToken",Y.IntrospectToken="introspectToken",Y.RevokeToken="revokeToken",Y.FetchAuthorizationServerMetadata="fetchAuthorizationServerMetadata",Y.DynamicClientRegistration="dynamicClientRegistration",Y.StartDeviceAuthorization="startDeviceAuthorization",Y.ExchangeDeviceCodeToken="exchangeDeviceCodeToken",Y.PollDeviceToken="pollDeviceToken",Y.CreateDeviceFlowSession="createDeviceFlowSession",Y);class rB 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 rx extends rB{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 rS extends rB{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 rT extends rB{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 rI extends rB{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 rO=Object.values(rF);function rk(e){if(!h(e,rO)||"exchangeToken"!==e.operation)return!1;let t=e.responseJson,r=t?.error;return"string"==typeof r&&rD.has(r)}var rR=((K={}).NotFound="NOT_FOUND",K.InvalidShape="INVALID_SHAPE",K.AccessTokenExpired="ACCESS_TOKEN_EXPIRED",K.RefreshTokenExpired="REFRESH_TOKEN_EXPIRED",K.RefreshFailed="REFRESH_FAILED",K.StorageError="STORAGE_ERROR",K),rP=((X={}).Read="read",X.Save="save",X.Clear="clear",X.Refresh="refresh",X);class rL extends l{operation;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="OAuthTokenStoreError",this.operation=t.operation}}Object.values(rR);let rN=f("NOT_FOUND");function rj(e){var t;return ta(e)&&(t=e.auth,!!ta(t)&&rU(t.accessToken)&&rU(t.refreshToken)&&rM(t.atExpiresAt)&&rM(t.rtExpiresAt)&&to(t.scopes)&&t.scopes.every(tl))}function r$(e,t,r){if(!r(e))throw new rL("Invalid OAuth token snapshot shape",{code:rR.InvalidShape,operation:t})}function rM(e){return ts(e)&&Number.isInteger(e)&&e>0&&e<1e10}function rU(e){return tl(e)&&""!==e.trim()}function rq(e,t=Date.now()){return e<=Math.floor(t/1e3)}class rV{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,T.join)(this.storage.baseDir,`${this.fileName}.refresh.lock`):e.refreshLockPath,this.refreshLockOptions=e.refreshLockOptions,this.now=e.now??(()=>Date.now()),this.validate=e.validate??rj}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(rN(e))return;throw e}}async save(e){r$(e,rP.Save,this.validate),this.writeEpoch+=1;try{await this.storage.writeJson(this.fileName,e)}catch(e){throw new rL(`Failed to persist OAuth token snapshot: ${this.fileName}`,{cause:e,code:rR.StorageError,operation:rP.Save})}this.cache={snapshot:e,loadedAt:this.now()}}async clear(){this.writeEpoch+=1;try{try{await this.storage.remove(this.fileName)}catch(e){if(!t6(e))throw e}await this.storage.removeKey()}catch(e){throw new rL(`Failed to clear OAuth token snapshot: ${this.fileName}`,{cause:e,code:rR.StorageError,operation:rP.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 rL("OAuth access token has expired and no refresh function provided",{code:rR.AccessTokenExpired,operation:rP.Refresh});return(await this.refresh(t,e)).auth.accessToken}async refresh(e,t){return!1===this.refreshLockPath?this.refreshCurrent(e,t):tG(this.refreshLockPath,async()=>{this.invalidateCache();let r=await this.tryGet();if(!r)throw new rL(`OAuth token snapshot not found: ${this.fileName}`,{code:rR.NotFound,operation:rP.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 rL("OAuth refresh token has expired, re-login is required",{code:rR.RefreshTokenExpired,operation:rP.Refresh});if(this.refreshInflight)return this.refreshInflight;let r=this.writeEpoch,i=(async()=>{let i;try{i=await t(e)}catch(e){throw new rL("Failed to refresh OAuth tokens",{cause:e,code:rR.RefreshFailed,operation:rP.Refresh})}if(this.writeEpoch!==r)throw new rL("OAuth token refresh result is stale",{code:rR.RefreshFailed,operation:rP.Refresh});return r$(i,rP.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 rq(e.rtExpiresAt,this.now())}async loadFromStorage(){let e,t=this.writeEpoch;try{e=await this.storage.readJson(this.fileName)}catch(e){if(t6(e))throw new rL(`OAuth token snapshot not found: ${this.fileName}`,{cause:e,code:rR.NotFound,operation:rP.Read});throw new rL(`Failed to read OAuth token snapshot: ${this.fileName}`,{cause:e,code:rR.StorageError,operation:rP.Read})}return r$(e,rP.Read,this.validate),this.writeEpoch===t&&(this.cache={snapshot:e,loadedAt:this.now()}),e}}let rH=new e2,rz=new Set(["grant_type","client_id","code","redirect_uri","code_verifier","refresh_token","device_code","scope"]),rG=new Set(["client_id","scope","code_challenge","code_challenge_method"]);function rW(e){return Array.isArray(e)?e.map(e=>e.trim()).filter(Boolean).join(" ")||void 0:e?.trim()||void 0}function rJ(e,t,r,i){if(t)for(let[n,u]of Object.entries(t)){if(r.has(n.toLowerCase()))throw new rB(`extraParams cannot override reserved OAuth parameter: ${n}`,{code:rF.InvalidArgument,operation:i});rY(e,n,u)}}function rY(e,t,r){null!=r&&e.set(t,String(r))}function rK(e){if(e.trim())try{let t=JSON.parse(e);if(ta(t))return t;return}catch{return}}function rX(e){return eJ(e)?e.error===ez.Timeout?rF.RequestTimeout:e.error===ez.Aborted?rF.RequestAborted:rF.NetworkError:rF.NetworkError}function rQ(e,t,r){try{return new URL(e)}catch(e){throw new rB(`Invalid ${r}`,{cause:e,code:rF.InvalidArgument,operation:t})}}function rZ(e,t,r){if(!tl(e)||""===e.trim())throw new rB(`${t} must be a non-empty string`,{code:rF.InvalidArgument,operation:r})}function r1(e,t,r){if(!Number.isInteger(e)||e<=0)throw new rB(`${t} must be a positive integer`,{code:rF.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??rH).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 rI("OAuth device flow endpoint returned an empty response",{code:rF.InvalidResponse,operation:e.operation});let n=i.status,u=await i.text(),o=rK(u),s=tl(o?.error)?o.error:void 0,a=tl(o?.error_description)?o.error_description:void 0;if(void 0===n)throw new rI("OAuth device flow endpoint returned an invalid response",{code:rF.NetworkError,operation:e.operation,responseBody:u,responseJson:o});if(n>=500)throw new rI(`OAuth device flow endpoint returned HTTP ${n}`,{code:rF.HttpError,operation:e.operation,providerError:s,providerErrorDescription:a,responseBody:u,responseJson:o,status:n});if(s){var r;throw new rI(`OAuth device flow endpoint returned error: ${s}`,{code:(r=s,"authorization_pending"===r?rF.AuthorizationPending:"slow_down"===r?rF.SlowDown:"access_denied"===r?rF.AccessDenied:"expired_token"===r?rF.ExpiredToken:rF.InvalidResponse),operation:e.operation,providerError:s,providerErrorDescription:a,responseBody:u,responseJson:o,status:n})}if(n<200||n>=300)throw new rI(`OAuth device flow endpoint returned HTTP ${n}`,{code:rF.HttpError,operation:e.operation,responseBody:u,responseJson:o,status:n});if(!o)throw new rI("OAuth device flow endpoint returned a non-JSON response",{code:rF.InvalidResponse,operation:e.operation,responseBody:u,status:n});return o}catch(t){if(t instanceof rI)throw t;throw new rI("OAuth device flow request failed",{cause:t,code:rX(t),operation:e.operation})}}function r0(e,t,r){let i=Math.min(e,Math.max(0,t-Date.now()));return i<=0?Promise.resolve():r?.aborted?Promise.reject(new rI("OAuth device token polling was aborted",{code:rF.RequestAborted,operation:rw.PollDeviceToken})):new Promise((e,t)=>{let n=setTimeout(()=>{r?.removeEventListener("abort",u),e()},i),u=()=>{clearTimeout(n),t(new rI("OAuth device token polling was aborted",{code:rF.RequestAborted,operation:rw.PollDeviceToken}))};r?.addEventListener("abort",u,{once:!0})})}function r3(e,t){rZ(e.clientId,"clientId",rw.ExchangeDeviceCodeToken),rZ(e.deviceCode,"deviceCode",rw.ExchangeDeviceCodeToken),r1(t,"timeoutMs",rw.ExchangeDeviceCodeToken),void 0!==e.codeVerifier&&rZ(e.codeVerifier,"codeVerifier",rw.ExchangeDeviceCodeToken)}function r6(e,t){if(!tl(e)||""===e.trim())throw new rI(`${t} must be a non-empty string`,{code:rF.InvalidResponse,operation:rw.StartDeviceAuthorization})}function r4(e,t,r){if(!Number.isInteger(e)||e<=0)throw new rI(`${t} must be a positive integer`,{code:rF.InvalidResponse,operation:rw.StartDeviceAuthorization,responseJson:r})}function r8(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 r9(e){let t=rQ(e.deviceAuthorizationEndpoint,rw.StartDeviceAuthorization,"deviceAuthorizationEndpoint"),r=e.timeoutMs??15e3;var i=e,n=r;if(rZ(i.clientId,"clientId",rw.StartDeviceAuthorization),r1(n,"timeoutMs",rw.StartDeviceAuthorization),void 0!==i.codeChallenge&&rZ(i.codeChallenge,"codeChallenge",rw.StartDeviceAuthorization),void 0!==i.codeChallengeMethod&&rZ(i.codeChallengeMethod,"codeChallengeMethod",rw.StartDeviceAuthorization),void 0===i.codeChallenge!=(void 0===i.codeChallengeMethod))throw new rI("codeChallenge and codeChallengeMethod must be provided together",{code:rF.InvalidArgument,operation:rw.StartDeviceAuthorization});let u=new URLSearchParams;u.set("client_id",e.clientId),rY(u,"scope",rW(e.scope)),rY(u,"code_challenge",e.codeChallenge),rY(u,"code_challenge_method",e.codeChallengeMethod),rJ(u,e.extraParams,rG,rw.StartDeviceAuthorization);let o=await r2({body:u,endpoint:t,httpClient:e.httpClient,headers:e.headers,operation:rw.StartDeviceAuthorization,signal:e.signal,timeoutMs:r});var s=o;if(r6(s.device_code,"device_code"),r6(s.user_code,"user_code"),r6(s.verification_uri,"verification_uri"),void 0!==s.verification_uri_complete&&r6(s.verification_uri_complete,"verification_uri_complete"),"number"!=typeof s.expires_in)throw new rI("expires_in must be a positive integer",{code:rF.InvalidResponse,operation:rw.StartDeviceAuthorization,responseJson:s});if(r4(s.expires_in,"expires_in",s),void 0!==s.interval){if("number"!=typeof s.interval)throw new rI("interval must be a positive integer",{code:rF.InvalidResponse,operation:rw.StartDeviceAuthorization,responseJson:s});r4(s.interval,"interval",s)}return o}async function r7(e){let t=rQ(e.tokenEndpoint,rw.ExchangeDeviceCodeToken,"tokenEndpoint"),r=e.timeoutMs??15e3;r3(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),rY(i,"code_verifier",e.codeVerifier),rJ(i,e.extraParams,rz,rw.ExchangeDeviceCodeToken);let n=await r2({body:i,endpoint:t,httpClient:e.httpClient,headers:e.headers,operation:rw.ExchangeDeviceCodeToken,signal:e.signal,timeoutMs:r});if("string"!=typeof n.access_token||""===n.access_token.trim())throw new rI("OAuth device token response is missing access_token",{code:rF.InvalidResponse,operation:rw.ExchangeDeviceCodeToken,responseJson:n});return n}async function r5(e){var t,r,i,n,u;let o=e.intervalSeconds??5;t=e,r=o,r3(t,t.timeoutMs??15e3),r1(r,"intervalSeconds",rw.PollDeviceToken),void 0!==t.expiresInSeconds&&r1(t.expiresInSeconds,"expiresInSeconds",rw.PollDeviceToken),void 0!==t.pollTimeoutMs&&r1(t.pollTimeoutMs,"pollTimeoutMs",rw.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 r7(e)}catch(t){if(!(t instanceof rI))throw t;if(t.error===rF.AuthorizationPending){await r0(s,c,e.signal);continue}if(t.error===rF.SlowDown){s+=5e3,await r0(s,c,e.signal);continue}if(t.error===rF.RequestTimeout||t.error===rF.NetworkError){await r0(s,c,e.signal);continue}throw t}throw new rI("Timed out waiting for OAuth device authorization",{code:rF.ExpiredToken,operation:rw.PollDeviceToken,details:{expiresInSeconds:e.expiresInSeconds,pollTimeoutMs:e.pollTimeoutMs}})}async function ie(e){let t=function(e){if(void 0!==e.codeChallenge||void 0!==e.codeChallengeMethod){if(!e.codeChallenge||!e.codeChallengeMethod)throw new rI("codeChallenge and codeChallengeMethod must be provided together",{code:rF.InvalidArgument,operation:rw.CreateDeviceFlowSession});if(!e.codeVerifier)throw new rI("codeVerifier is required when custom PKCE parameters are provided",{code:rF.InvalidArgument,operation:rw.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=rw.GeneratePKCE;if(!Number.isInteger(n)||n<32||n>96)throw new rB("verifierByteLength must be an integer between 32 and 96",{code:rF.InvalidArgument,operation:u});let o=(r=t,(0,tc.randomBytes)(r).toString("base64url")),s=(i=o,(0,tc.createHash)("sha256").update(i).digest("base64url"));return{codeVerifier:o,codeChallenge:s,codeChallengeMethod:"S256"}}({verifierByteLength:e.verifierByteLength})}(e),r=await r9({...e,codeChallenge:t.codeChallenge,codeChallengeMethod:t.codeChallengeMethod});return{authorization:r,codeVerifier:t.codeVerifier,codeChallenge:t.codeChallenge,codeChallengeMethod:t.codeChallengeMethod,pollToken:()=>r5({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 it(e){return e.replace(/[^a-zA-Z0-9]+/g,"")}function ir(e,t,r){let i=e[t];if(tl(i)&&i.trim())return i;throw new rB(`OAuth response is missing ${t}`,{code:rF.InvalidResponse,operation:r,details:{field:t}})}async function ii(e){let t=rQ(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??rH).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 rB("OAuth endpoint returned an empty response",{code:rF.InvalidResponse,operation:e.operation});let o=u.status,s=await u.text(),a=rK(s);if(void 0===o||o<200||o>=300)throw new rB(`OAuth endpoint returned HTTP ${o??"unknown"}`,{code:rF.HttpError,operation:e.operation,status:o,details:{responseBody:s,responseJson:a}});var i=a,n=e.operation;if(ta(i))return i;throw new rB("OAuth endpoint returned an invalid JSON object",{code:rF.InvalidResponse,operation:n})}catch(t){if(t instanceof rB)throw t;throw new rB("OAuth request failed",{cause:t,code:rX(t),operation:e.operation})}}async function iu(e){let t,r=await ii({url:e.metadataEndpoint,method:"GET",headers:e.headers,timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient,operation:rw.FetchAuthorizationServerMetadata});return{issuer:tl(r.issuer)&&r.issuer.trim()?r.issuer.trim():void 0,tokenEndpoint:ir(r,"token_endpoint",rw.FetchAuthorizationServerMetadata),introspectionEndpoint:ir(r,"introspection_endpoint",rw.FetchAuthorizationServerMetadata),revocationEndpoint:ir(r,"revocation_endpoint",rw.FetchAuthorizationServerMetadata),deviceAuthorizationEndpoint:ir(r,"device_authorization_endpoint",rw.FetchAuthorizationServerMetadata),registrationEndpoint:ir(r,"registration_endpoint",rw.FetchAuthorizationServerMetadata),scopesSupported:(t=r.scopes_supported,to(t)?t.filter(e=>tl(e)&&""!==e.trim()):[]),raw:r}}async function io(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 ii({url:e.registrationEndpoint,method:"POST",headers:e.headers,body:JSON.stringify(t),timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient,operation:rw.DynamicClientRegistration});return{clientId:ir(r,"client_id",rw.DynamicClientRegistration),raw:r}}async function is(e){let t=rQ(e.tokenEndpoint,rw.ExchangeToken,"tokenEndpoint"),r=e.grantType??"authorization_code",i=e.timeoutMs??15e3;!function(e,t,r){if(rZ(e.clientId,"clientId",rw.ExchangeToken),r1(r,"timeoutMs",rw.ExchangeToken),"authorization_code"===t){rZ(e.code,"code",rw.ExchangeToken),rZ(e.redirectUri,"redirectUri",rw.ExchangeToken),void 0!==e.codeVerifier&&rZ(e.codeVerifier,"codeVerifier",rw.ExchangeToken);return}if("refresh_token"===t)return rZ(e.refreshToken,"refreshToken",rw.ExchangeToken);throw new rB(`Unsupported OAuth grant type: ${t}`,{code:rF.InvalidArgument,operation:rw.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),rY(n,"code_verifier",e.codeVerifier)):(n.set("refresh_token",e.refreshToken),rY(n,"scope",rW(e.scope))),rJ(n,e.extraParams,rz,rw.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??rH).send({url:t.toString(),method:"POST",headers:u,data:n.toString(),timeoutMs:i,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!r)throw new rx("OAuth token endpoint returned an empty response",{code:rF.InvalidResponse});let o=r.status,s=await r.text(),a=rK(s),l=tl(a?.error)?a.error:void 0;if(void 0===o||o<200||o>=300)throw new rx(`OAuth token endpoint returned HTTP ${o??"unknown"}`,{code:rF.HttpError,responseBody:s,responseJson:a,status:o});if(l)throw new rx(`OAuth token endpoint returned error: ${l}`,{code:rF.InvalidResponse,responseBody:s,responseJson:a,status:o});if(!a)throw new rx("OAuth token endpoint returned a non-JSON response",{code:rF.InvalidResponse,responseBody:s,status:o});if(!tl(a.access_token)||""===a.access_token.trim())throw new rx("OAuth token response is missing access_token",{code:rF.InvalidResponse,responseBody:s,responseJson:a,status:o});return a}catch(e){if(e instanceof rx)throw e;throw new rx("OAuth token request failed",{cause:e,code:rX(e)})}}async function ia(e){var t,r,i;let n=rQ(e.introspectionEndpoint,rw.IntrospectToken,"introspectionEndpoint"),u=e.timeoutMs??15e3;t=e,r=u,rZ(t.token,"token",rw.IntrospectToken),rZ(t.clientId,"clientId",rw.IntrospectToken),r1(r,"timeoutMs",rw.IntrospectToken),void 0!==t.tokenTypeHint&&rZ(t.tokenTypeHint,"tokenTypeHint",rw.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??rH).send({url:n.toString(),method:"POST",headers:s,data:o.toString(),timeoutMs:u,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!t)throw new rS("OAuth token introspection endpoint returned an empty response",{code:rF.InvalidResponse});let r=t.status,a=await t.text(),l=rK(a);if(void 0===r||r<200||r>=300)throw new rS(`OAuth token introspection endpoint returned HTTP ${r??"unknown"}`,{code:rF.HttpError,responseBody:a,responseJson:l,status:r});if(!l||"boolean"!=typeof l.active)throw new rS("OAuth token introspection response is invalid",{code:rF.InvalidResponse,responseBody:a,responseJson:l,status:r});return{active:(i=l).active,scope:ic(i.scope),clientId:ic(i.client_id),clientName:ic(i.client_name),tokenType:ic(i.token_type),exp:id(i.exp),iat:id(i.iat),sub:ic(i.sub),raw:i}}catch(e){if(e instanceof rS)throw e;throw new rS("OAuth token introspection request failed",{cause:e,code:rX(e)})}}async function il(e){var t,r;let i=rQ(e.revocationEndpoint,rw.RevokeToken,"revocationEndpoint"),n=e.timeoutMs??15e3;t=e,r=n,rZ(t.token,"token",rw.RevokeToken),rZ(t.clientId,"clientId",rw.RevokeToken),r1(r,"timeoutMs",rw.RevokeToken),void 0!==t.tokenTypeHint&&rZ(t.tokenTypeHint,"tokenTypeHint",rw.RevokeToken);let u=new URLSearchParams({token:e.token,client_id:e.clientId});rY(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??rH).send({url:i.toString(),method:"POST",headers:o,data:u.toString(),timeoutMs:n,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!t)throw new rT("OAuth token revocation endpoint returned an empty response",{code:rF.InvalidResponse});let r=t.status,s=await t.text(),a=rK(s);if(void 0===r||r<200||r>=300)throw new rT(`OAuth token revocation endpoint returned HTTP ${r??"unknown"}`,{code:rF.HttpError,responseBody:s,responseJson:a,status:r})}catch(e){if(e instanceof rT)throw e;throw new rT("OAuth token revocation request failed",{cause:e,code:rX(e)})}}function ic(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function id(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function ip(e,t){let r=e[t];return r&&r.length>0?r:void 0}function ih(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?T.win32:T.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??td.homedir(),_=e.env??process.env;if("darwin"===m)return t=A,r=E,{configDir:T.join(r,"Library","Preferences",t),dataDir:T.join(r,"Library","Application Support",t),cacheDir:T.join(r,"Library","Caches",t),logDir:T.join(r,"Library","Logs",t),tempDir:T.join(td.tmpdir(),t)};if("win32"===m){let e,t,r;return i=A,n=E,e=ip(u=_,"APPDATA")??T.join(n,"AppData","Roaming"),t=ip(u,"LOCALAPPDATA")??T.join(n,"AppData","Local"),r=ip(u,"TEMP")??td.tmpdir(),{configDir:T.join(e,i,"Config"),dataDir:T.join(e,i,"Data"),cacheDir:T.join(t,i,"Cache"),logDir:T.join(t,i,"Log"),tempDir:T.join(r,i)}}return o=A,s=E,c=ip(a=_,"XDG_CONFIG_HOME")??T.join(s,".config"),d=ip(a,"XDG_DATA_HOME")??T.join(s,".local","share"),p=ip(a,"XDG_CACHE_HOME")??T.join(s,".cache"),h=ip(a,"XDG_STATE_HOME")??T.join(s,".local","state"),{configDir:T.join(c,o),dataDir:T.join(d,o),cacheDir:T.join(p,o),logDir:T.join(h,o,"logs"),tempDir:T.join(td.tmpdir(),o)}}function im(e){let t;function r(){let r,i;return t||(t=new tW((r=e.dir??"dataDir",i=ih(e),{baseDir:e.subDir?tP(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 ig(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 iA(e){let t=ig(e.total),r=ig(e.page),i=ig(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 iy(e){return String(e).padStart(2,"0")}function iE(e){return e.replace(/[^a-zA-Z0-9_-]+/g,"-")}async function i_(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=iy(t.getMonth()+1),n=iy(t.getDate()),u=iy(t.getHours()),o=iy(t.getMinutes()),s=iy(t.getSeconds()),a=String(t.getMilliseconds()).padStart(3,"0"),`${r}-${i}-${n}_${u}-${o}-${s}_${a}`),d=`${iE(e.command)}-${c}`;if(e.outputDir){let t=(0,T.resolve)(e.outputDir);if((0,I.existsSync)(t)&&!(0,I.statSync)(t).isDirectory())throw new l(`输出路径不是目录: ${t}`,{error:"INVALID_OUTPUT_DIR",message:`--output-dir 必须是一个目录,但 ${t} 是文件`});return(0,T.resolve)(t,d)}return(0,T.resolve)(process.cwd(),`${iE(e.appName)}-output`,d)}(e),u=(0,T.resolve)(n,t),o=(0,T.resolve)(n,r),s=(0,T.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 tL(s);let c=new tW({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 ib="aes-256-gcm";function iC(e,t,r,i=iD(r)){let n=(0,tc.randomBytes)(12),u=(0,tc.createCipheriv)(ib,t,n);u.setAAD(i);let o=Buffer.concat([u.update(e),u.final()]);return{version:1,algorithm:ib,keyProvider:r,iv:n.toString("base64"),authTag:u.getAuthTag().toString("base64"),ciphertext:o.toString("base64")}}function iv(e,t,r){if(32!==t.length)throw Error(`Invalid sensitive storage key length: ${t.length}`);let i=(0,tc.createDecipheriv)(ib,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 iD(e){return Buffer.from([1,ib,e].join(":"),"utf8")}function iF(e,t,r){return Buffer.from([1,ib,"scrypt",e,t,r].join(":"),"utf8")}function iw(e,t,r){return(0,tc.scryptSync)(function(e,t){let{uid:r,gid:i}=function(){try{let e=(0,td.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,td.platform)();return["open-game-cli-lib-ssfk-v1",e,t,n,(0,td.arch)(),r,i].join("\n")}(e,t),r,32)}function iB(e){if(!(e instanceof Error))return!1;let t=e?.code;return!!(tl(t)&&/no\s*entry|not\s*found/i.test(t))||/no\s*entry|not\s*found|notfound|not found/i.test(e?.message)}var ix=((Q={}).Auto="auto",Q.Keychain="keychain",Q.File="file",Q),iS=((Z={}).Read="read",Z.Write="write",Z.Remove="remove",Z);let iT=new Map;async function iI(){return await import("@napi-rs/keyring")}async function iO(e,t){let r=iT.get(e)??Promise.resolve(),i=()=>void 0,n=new Promise(e=>{i=e}),u=r.then(()=>n,()=>n);iT.set(e,u),await r.catch(()=>void 0);try{return await t()}finally{i(),iT.get(e)===u&&iT.delete(e)}}class ik{baseDir;service;account;fallbackKeyFile;fileStorage;keyStrategy;keychainTimeoutMs;onKeychainPrompt;fallbackKeyLockPath;fallbackKeyLockOptions;fallbackKeyScopeId;constructor(e){this.baseDir=(0,T.resolve)(e.baseDir),this.service=e.service,this.account=e.account,this.fallbackKeyFile=e.fallbackKeyFile??".sensitive-storage-key",this.fileStorage=new tW({baseDir:this.baseDir,baseDirMode:void 0===e.baseDirMode?448:e.baseDirMode}),this.keyStrategy=function(e){if(void 0===e)return ix.File;if(e===ix.Auto||e===ix.Keychain||e===ix.File)return e;throw TypeError(`keyStrategy must be one of: ${ix.File}, ${ix.Keychain}, ${ix.Auto}`)}(e.keyStrategy),this.keychainTimeoutMs=Math.max(0,e.keychainTimeoutMs??5e3),this.onKeychainPrompt=e.onKeychainPrompt,this.fallbackKeyLockPath=void 0===e.fallbackKeyLockPath?tP(this.baseDir,`${this.fallbackKeyFile}.lock`):e.fallbackKeyLockPath,this.fallbackKeyLockOptions=e.fallbackKeyLockOptions,this.fallbackKeyScopeId=function(e,t){return(0,tc.createHash)("sha256").update(e).update("\0").update(t).digest("hex").slice(0,32)}(this.service,this.account)}async readText(e,t="utf8"){let r=tP(this.baseDir,e);return(await this.readEncryptedData(r,tY.ReadText)).toString(t)}async writeText(e,t,r={}){let i=r.encoding??"utf8",n=tP(this.baseDir,e);await this.writeEncryptedData(n,Buffer.from(t,i),tY.WriteText)}async readJson(e,t="utf8"){let r=tP(this.baseDir,e),i=await this.readEncryptedData(r,tY.ReadJson);try{return JSON.parse(i.toString(t))}catch(e){throw new tK(`Failed to parse sensitive JSON data: ${r}`,{cause:e,code:tJ.InvalidJson,filePath:r,operation:tY.ReadJson})}}async writeJson(e,t,r={}){let i=r.encoding??"utf8",n=r.spaces??2,u=tP(this.baseDir,e),o=`${JSON.stringify(t,null,n)}
31
+ `;await this.writeEncryptedData(u,Buffer.from(o,i),tY.WriteJson)}async remove(e){let t=tP(this.baseDir,e);try{await this.fileStorage.remove(t)}catch(e){if(tq(e))throw new tQ(t,tY.Remove,e);throw new tK(`Failed to remove sensitive data: ${t}`,{cause:e,code:tJ.DataStorageError,filePath:t,operation:tY.Remove})}}async removeKey(){let e;if(this.shouldUseKeychainOnRemove())try{let{AsyncEntry:e}=await iI(),t=new e(this.service,this.account);await this.runKeychainCall(()=>t.deleteCredential(),tY.RemoveKey,iS.Remove)}catch(t){t instanceof t0?e=t:iB(t)||(e=new t2("Failed to remove sensitive storage key from keychain",{cause:t,operation:tY.RemoveKey}))}if(this.shouldUseFileOnRemove()){let e=this.getFallbackKeyFilePath();try{await this.fileStorage.remove(e)}catch(t){if(!tq(t))throw new t2(`Failed to remove sensitive storage key file: ${e}`,{cause:t,filePath:e,operation:tY.RemoveKey})}}if(e)throw e}async readEncryptedData(e,t){let r=await this.tryReadEnvelope(e,t);if(!r)throw new tQ(e,t);this.assertReadableProvider(r.keyProvider,e,t);let i=await this.readKeyByProvider(r.keyProvider,e,t);try{return iv(r,i,iD(r.keyProvider))}catch(r){throw new tZ(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 tK)throw t;throw new tK(`Failed to write sensitive data: ${e}`,{cause:t,code:tJ.DataStorageError,filePath:e,operation:r})}}async resolveKeyForNewEnvelopeWithLock(e,t){return iO(this.getKeyResolutionLockId(),()=>this.resolveKeyForNewEnvelope(e,t))}getKeyResolutionLockId(){return[this.service,this.account,this.fallbackKeyFile].join("\0")}getFallbackKeyFilePath(){return tP(this.baseDir,`${this.fallbackKeyFile}.${this.fallbackKeyScopeId}.json`)}async resolveKeyForNewEnvelope(e,t){if(this.keyStrategy===ix.File){let e=(0,tc.randomBytes)(32);return{key:await this.ensureFileKey(e),provider:"file"}}if(this.keyStrategy===ix.Keychain){let r=await this.tryReadReusableKey("keychain",e,t);if(r)return r;let i=(0,tc.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,tc.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===ix.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===ix.Keychain?"keychain":"file"}shouldUseKeychainOnRemove(){return this.keyStrategy===ix.Auto||this.keyStrategy===ix.Keychain}shouldUseFileOnRemove(){return this.keyStrategy===ix.Auto||this.keyStrategy===ix.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(t3(e))return;throw e}}async tryReadEnvelope(e,t){let r;try{r=await this.fileStorage.readText(e,"utf8")}catch(r){if(tq(r))return;throw new tK(`Failed to read sensitive data: ${e}`,{cause:r,code:tJ.DataStorageError,filePath:e,operation:t})}try{var i,n=r;let e=JSON.parse(n);if(1!==e.version||e.algorithm!==ib||(i=e.keyProvider,!["keychain","file"].includes(i))||!tl(e.iv)||!tl(e.authTag)||!tl(e.ciphertext))throw Error("Invalid sensitive data envelope");return e}catch(r){throw new t1(e,t,r)}}async ensureFileKey(e){return!1===this.fallbackKeyLockPath?this.createFileKeyIfMissing(e):tG(this.fallbackKeyLockPath,async()=>this.createFileKeyIfMissing(e),this.fallbackKeyLockOptions)}async createFileKeyIfMissing(e){let t=this.getFallbackKeyFilePath();try{return await this.readKeyFromFile(void 0,tY.ReadKey)}catch(e){if(!t3(e))throw e}let r=(0,tc.randomBytes)(16),i=r.toString("base64"),n=iC(e,iw(this.service,this.account,r),"file",iF(this.service,this.account,i)),u={version:1,algorithm:ib,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:tY.WriteKey})}return e}async readKeyFromKeychain(e,t){try{let{AsyncEntry:u}=await iI(),o=new u(this.service,this.account),s=await this.runKeychainCall(()=>o.getPassword(),t,iS.Read);if(!s)throw new tX({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 tK)throw r;if(iB(r))throw new tX({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 iI(),r=new t(this.service,this.account);await this.runKeychainCall(()=>r.setPassword(e.toString("base64")),tY.WriteKey,iS.Write)}catch(e){if(e instanceof tK)throw e;throw new t2("Failed to write sensitive storage key to keychain",{cause:e,operation:tY.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 t0(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(tq(r))throw new tX({cause:r,filePath:e??i,operation:t});throw new t2(`Failed to read sensitive storage key file: ${i}`,{cause:h(r,tU)?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!==ib||"scrypt"!==t.kdf||!tl(t.salt)||!tl(t.iv)||!tl(t.authTag)||!tl(t.encryptedKey))throw Error("Invalid sensitive storage key envelope");return t}(r),t=iw(this.service,this.account,Buffer.from(e.salt,"base64")),i=iv({iv:e.iv,authTag:e.authTag,ciphertext:e.encryptedKey},t,iF(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 iR=/^[a-zA-Z0-9_-]+$/,iP=function(){1;return""}();function iL(e){return iP?`${e}:${iP}`:e}function iN(){return iP?`auth_${iP}`:"auth"}let ij=im({appName:"dymg"}),i$=im({appName:"dymg",subDir:iN()}),iM=new Set(["EACCES","EPERM","EROFS"]),iU=["读取"];function iq(e){return iU.some(t=>e.startsWith(t))}function iV(e){return!!function e(t,r=0){if(t&&!(r>8)){var i;if(t instanceof Error&&iM.has(t.code??""))return t;if("object"==typeof(i=t)&&null!==i&&"cause"in t)return e(t.cause,r+1)}}(e)}function iH(e,t){var r;if(!iV(e))throw e;throw new l(iq(t)?`${t}失败:无法访问或初始化登录态目录`:`${t}失败:登录态目录无写权限`,{cause:e,error:"AUTH_PERMISSION_DENIED",message:iq(r=t)?`${r}失败:当前终端无法访问或初始化登录态目录。`:`${r}失败:当前终端对登录态目录无写权限。`})}let iz="client.json",iG=!1;async function iW(){try{var e=await i$.readJson(iz);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:ry(e.clientIdIssuedAt),createdAt:v(e.createdAt)??Math.floor(Date.now()/1e3),updatedAt:v(e.updatedAt)??Math.floor(Date.now()/1e3)};throw new l("本地登录信息异常",{error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"})}catch(e){if(tq(e))return;if(p(e,tN.InvalidJson))throw new l("本地登录信息异常",{cause:e,error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"});iH(e,"读取登录配置")}}function iJ(e){if(e)return{clientId:e.clientId,clientName:e.clientName,clientIdIssuedAt:e.clientIdIssuedAt}}async function iY(){return iG?e:(t||(t=(async()=>{try{let t=await iW(),r=iJ(t);return e=r,iG=!0,r}finally{t=void 0}})()),t)}async function iK(t){let r=Math.floor(Date.now()/1e3),i=await iW(),n={clientId:t.clientId,clientName:t.clientName??i?.clientName,clientIdIssuedAt:t.clientIdIssuedAt??i?.clientIdIssuedAt,createdAt:i?.createdAt??r,updatedAt:r};try{await i$.writeJson(iz,n,{mode:384})}catch(e){iH(e,"保存登录配置")}e=iJ(n),iG=!0}async function iX(e){let t=await iY(),r=function(e){let t=it((0,td.hostname)().split(".")[0]??""),r="";try{r=it((0,td.userInfo)().username)}catch{r=it(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 io({registrationEndpoint:e.registrationEndpoint,clientName:r,timeoutMs:e.timeoutMs,httpClient:na});return await iK({clientId:i.clientId,clientName:"string"==typeof i.raw.client_name&&i.raw.client_name.trim()?i.raw.client_name.trim():r,clientIdIssuedAt:ry(i.raw.client_id_issued_at)}),i.clientId}async function iQ(e={}){var t,r;let i=await iu({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:na}),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 iX({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 iZ="profile.json",i1=function(e){let t;function r(){return t||(t=new rV(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}=ih({appName:"dymg"});return new ik({baseDir:(0,T.join)(e,iN()),service:iL(e4),account:iL("default")})}(),fileName:"token.json"}));async function i2(){try{var e;let t;return e=await i$.readJson(iZ),t=Math.floor(Date.now()/1e3),{uid:C(e?.uid),oauthAppId:C(e?.oauthAppId),oauthAppName:C(e?.oauthAppName),updatedAt:v(e?.updatedAt)??t}}catch(e){if(tq(e))return;throw e}}async function i0(e){try{await i$.writeJson(iZ,e,{mode:384})}catch(e){iH(e,"保存登录信息")}}async function i3(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 i0(r),r):t}async function i6(){try{await i$.remove(iZ)}catch(e){tq(e)||iH(e,"清理登录信息")}}function i4(e,t){try{return function(e,t={}){let r,i=Math.floor((t.nowMs??Date.now())/1e3),n=ry(e.expires_in)??t.defaultAccessTokenExpiresInSeconds??3600,u=ry(e.refresh_token_expires_in),o=ic(e.refresh_token),s=o??t.current?.auth.refreshToken,a=void 0===e.scope?t.current?.auth.scopes??[]:(r=rW(e.scope))?r.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[];if(!s)throw new rx("OAuth token response is missing refresh_token",{code:rF.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:`登录失败,请重新执行 ${e8}`})}}async function i8(e){await i3({uid:C(e.uid),oauthAppId:C(e.oauth_app_id),oauthAppName:C(e.oauth_app_name)})}async function i9(e){let t;try{t=await iQ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e8}`});throw e}let r=await is({tokenEndpoint:t.tokenEndpoint,clientId:t.clientId,grantType:"refresh_token",refreshToken:e.auth.refreshToken,scope:e.auth.scopes,httpClient:na});return await i8(r).catch(()=>void 0),i4(r,e)}function i7(e){var t;if(iV(e)&&iH(e,"刷新登录态"),p(e,"REFRESH_TOKEN_EXPIRED"))throw new l("当前登录已过期,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已过期,请执行 ${e8}`});if(p(t=e,"REFRESH_FAILED")&&rk(t.cause)||rk(e))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e8}`});throw e}async function i5(){try{return await i1.tryGet()}catch(e){throw iV(e)&&iH(e,"读取登录信息"),new l("本地登录信息异常",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`本地登录信息异常,请先执行 ${e5},再执行 ${e8}`})}}async function ne(){if(await i5())try{return await i1.getAccessToken(i9)}catch(e){i7(e)}}async function nt(){let e=await i5();if(e)try{return(await i1.refresh(e,i9)).auth.accessToken}catch(e){i7(e)}}async function nr(e){let t;if(e){try{t=await iQ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))return;throw e}try{await il({revocationEndpoint:t.revocationEndpoint,token:e.auth.refreshToken,tokenTypeHint:"refresh_token",clientId:t.clientId,httpClient:na})}catch(e){throw new l("退出登录失败,请稍后重试",{cause:e,error:"AUTH_LOGOUT_REVOKE_FAILED",message:"退出登录失败,请检查网络后重试"})}}}async function ni(){let e,t,r=await ne();if(!r)return;try{e=await iQ({enableDynamicClientRegistration:!1})}catch(e){if(p(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e8}`});throw e}try{t=await ia({introspectionEndpoint:e.introspectionEndpoint,token:r,tokenTypeHint:"access_token",clientId:e.clientId,httpClient:na})}catch(e){throw new l("登录态校验失败,请稍后重试或重新登录",{cause:e,error:"AUTH_STATUS_CHECK_FAILED",message:`登录态校验失败,请稍后重试;如问题持续,可执行 ${e8}`})}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:`当前登录已失效,请执行 ${e8}`});return await i3({uid:i.uid,oauthAppId:i.oauthAppId,oauthAppName:i.oauthAppName}).catch(()=>void 0),i}async function nn(e,t){let r=i4(e,t);try{await Promise.all([i1.save(r),i8(e).catch(()=>void 0)])}catch(e){iH(e,"保存登录态")}return r}async function nu(){try{await Promise.all([i1.clear(),i6()])}catch(e){iH(e,"退出登录")}}let no=new e2,ns=new e2,na=new e2;function nl(e){return new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:e??`当前命令需要先登录,请先执行 ${e8}`})}function nc(){return new l("当前登录已失效,请重新登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${e8}`})}function nd(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 np(e){if(e?.trim())try{return nd(JSON.parse(e))}catch{return}}function nh(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?nc():nl();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=nc();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 nf(e){if(!eJ(e))throw e;nh(np(e.responseBody),{status:e.status,cause:e})}function nm(e){let t=nd(e);t&&void 0!==t.error&&0!==t.error&&nh(t)}async function ng(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 ns.send(n,{meta:t.meta});return nm(e),e}catch(r){eJ(i=r)&&401===i.status||nf(r);let e=eJ(r)?np(r.responseBody):void 0;if(!await nt())throw e?.error===1002?nl():nc();try{let{data:e}=await ns.send(n,{meta:t.meta});return nm(e),e}catch(e){nf(e)}}}let nA="session.json";async function ny(e){try{await i$.writeJson(nA,e,{mode:384})}catch(e){iH(e,"保存授权会话")}}async function nE(){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=v(e?.createdAt),a=v(e?.expiresAt);if(!t||!r||!i||!n||!u||!o||!s||!a)throw new l("本地授权会话异常",{error:"INVALID_AUTH_SESSION",message:`本地授权会话异常,请重新执行 ${e9}`});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 i$.readJson(nA))}catch(e){if(tq(e))return;iH(e,"读取授权会话")}}async function n_(){try{await i$.remove(nA)}catch(e){tq(e)||iH(e,"清理授权会话")}}let nb=["coze","cursor","claude_code","github_copilot","gemini_cli","trae","manus","devin","codex","hermes","openclaw","unknown"];function nC(e){return nb.includes(e)}let nv="宿主枚举:1 全部 / 2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山 / 9 皮皮虾",nD="宿主枚举:2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山",nF="操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony / 5 Windows",nw="设备档位枚举:1 全部 / 2 高端 / 3 中端 / 4 低端";function nB(e,t){let{caller:r}=e.optsWithGlobals();return{...t,caller:"string"==typeof r&&nC(r)?r:"unknown"}}function nx(e){return e.option("--output-dir <dir>","输出根目录,默认 ./dymg-output(会在其下按命令+时间生成子目录,并按命令类型写入结果文件)"),e}async function nS(e){let t=await iY().catch(()=>void 0);return{toolId:e.replaceAll(":"," "),clientId:t?.clientId}}function nT(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>",nv).option("--os <os>",nF).option("--user-type <userType>","用户类型枚举:1 全部 / 2 新增 / 3 活跃 / 4 付费新增 / 5 付费活跃").option("--segment <segment>","用户分群枚举:1 不分组 / 2 侧边栏奖励 / 3 App 活跃")}function nI(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>",nD).requiredOption("--os <os>","操作系统枚举:2 Android / 3 iOS / 4 OpenHarmony").option("--device-level <n>",nw).option("--mp-version <version>","小游戏版本号")}var nO=__webpack_require__("../../node_modules/.pnpm/@dp+tea-sdk-node@3.0.12/node_modules/@dp/tea-sdk-node/lib/index.js"),nk=__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 nR=Number(626386),nP=null;function nL(){let e=tr();if(e?.tool&&void 0!==e.requestParams)return{caller:e.caller,tool:e.tool,requestParams:e.requestParams}}async function nN(e){let t=(void 0===r&&(r=function(){if(!Number.isFinite(nR)||nR<=0)return null;let e=globalThis.fetch?(e,t)=>globalThis.fetch(e,t):void 0,t=new nO.TeaSDK({app_id:nR}),r=(0,nk.httpPlugin)({channel:"cn",...e?{transport:(t,r)=>e(t,r)}:{}});return nP=r,t.use(r),t.config({custom:{cli_name:"dymg"}}),t}()),r);if(!t)return;let[i,n]=await Promise.all([iY().catch(()=>void 0),i2().catch(()=>void 0)]),u=tr(),o=function(e=3e3){let t=nP;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.5.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 nj(e){return d(e)?e.error:void 0}let n$=["npm","pnpm","yarn","bun"],nM=new e2;function nU(e){var t;return(t=e,n$.includes(t))?e:void 0}function nq(e={}){var t;let r=nU(e.input);return void 0!==e.input?r:(t=e.userAgent,nU(t?.split("/")[0])??e.defaultPackageManager)}async function nV(e,t={}){let r=e.trim(),i=t.client??nM,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 eG("packageName is required",{code:ez.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 eG("package registry response missing version",{code:ez.InvalidJson,url:a});return l.version.trim()}let nH="update-check.json";function nz(e){let t=nq({userAgent:process.env.npm_config_user_agent})?"dymg update":`dymg update --package-manager <${n$.join("|")}>`;return[`检测到 ${e3} 新版本 ${e}(当前 0.5.1)。`,`执行 ${t} 可更新 CLI 并同步随包发布的 Skill。`,"如只想手动同步 Skill,可执行 dymg skills install。"]}async function nG(){try{return await ij.get().readJson(nH)}catch(e){if(tq(e))return{};throw e}}async function nW(e){await ij.get().writeJson(nH,e)}async function nJ(){return nV(e3,{client:no,timeoutMs:1e4})}async function nY(){let e=await nJ();return{currentVersion:"0.5.1",latestVersion:e,hasUpdate:function(e,t){let r=b(e),i=b(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.5.1")>0}}async function nK(e,t={}){let r=await nG(),i=Date.now(),n={...r,lastCheckedAt:i,latestVersion:e.latestVersion};t.notified&&(n.lastNotifiedAt=i,n.lastNotifiedVersion=e.latestVersion),await nW(n)}async function nX(e={}){var t,r,i,n,u,o;let s=e.force??!1,a=e.quiet??!1,l=Date.now(),c=await nG();if(t=l,r=c,!s&&!(t-(r.lastCheckedAt??0)>=864e5))return;let d=await nY(),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(["",...nz(o),""].join("\n")),p.lastNotifiedAt=l,p.lastNotifiedVersion=d.latestVersion),await nW(p);return}a||process.stdout.write(`dymg 已是最新版本(0.5.1)
32
+ `),await nW(p)}async function nQ(){try{await nX({quiet:!0})}catch{}}let nZ={request:ng,baseURL:""};nZ.genBaseURL=e=>"function"==typeof nZ.baseURL?nZ.baseURL(e):nZ.baseURL+e;let n1=(e=0)=>t=>`\u001B[${t+e}m`,n2=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,n0=(e=0)=>(t,r,i)=>`\u001B[${38+e};2;${t};${r};${i}m`,n3={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(n3.modifier);let n6=Object.keys(n3.color);[...n6,...Object.keys(n3.bgColor)];let n4=function(){let e=new Map;for(let[t,r]of Object.entries(n3)){for(let[t,i]of Object.entries(r))n3[t]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[t]=n3[t],e.set(i[0],i[1]);Object.defineProperty(n3,t,{value:r,enumerable:!1})}return Object.defineProperty(n3,"codes",{value:e,enumerable:!1}),n3.color.close="\x1b[39m",n3.bgColor.close="\x1b[49m",n3.color.ansi=n1(),n3.color.ansi256=n2(),n3.color.ansi16m=n0(),n3.bgColor.ansi=n1(10),n3.bgColor.ansi256=n2(10),n3.bgColor.ansi16m=n0(10),Object.defineProperties(n3,{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=>n3.rgbToAnsi256(...n3.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)=>n3.ansi256ToAnsi(n3.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>n3.ansi256ToAnsi(n3.hexToAnsi256(e)),enumerable:!1}}),n3}(),n8=require("node:tty");function n9(e,t=globalThis.Deno?globalThis.Deno.args:O.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:n7}=O;function n5(e,t={}){var r;return 0!==(r=function(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let n=function(){if("FORCE_COLOR"in n7)return"true"===n7.FORCE_COLOR?1:"false"===n7.FORCE_COLOR?0:0===n7.FORCE_COLOR.length?1:Math.min(Number.parseInt(n7.FORCE_COLOR,10),3)}();void 0!==n&&(i=n);let u=r?i:n;if(0===u)return 0;if(r){if(n9("color=16m")||n9("color=full")||n9("color=truecolor"))return 3;if(n9("color=256"))return 2}if("TF_BUILD"in n7&&"AGENT_NAME"in n7)return 1;if(e&&!t&&void 0===u)return 0;let o=u||0;if("dumb"===n7.TERM)return o;if("win32"===O.platform){let e=td.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in n7)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in n7)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in n7)||"codeship"===n7.CI_NAME?1:o;if("TEAMCITY_VERSION"in n7)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n7.TEAMCITY_VERSION);if("truecolor"===n7.COLORTERM||"xterm-kitty"===n7.TERM||"xterm-ghostty"===n7.TERM||"wezterm"===n7.TERM)return 3;if("TERM_PROGRAM"in n7){let e=Number.parseInt((n7.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n7.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(n7.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n7.TERM)||"COLORTERM"in n7?1:o}(e,{streamIsTTY:e&&e.isTTY,...t}))&&{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}n9("no-color")||n9("no-colors")||n9("color=false")||n9("color=never")?i=0:(n9("color")||n9("colors")||n9("color=true")||n9("color=always"))&&(i=1);let ue={stdout:n5({isTTY:n8.isatty(1)}),stderr:n5({isTTY:n8.isatty(2)})},{stdout:ut,stderr:ur}=ue,ui=Symbol("GENERATOR"),un=Symbol("STYLER"),uu=Symbol("IS_EMPTY"),uo=["ansi","ansi","ansi256","ansi16m"],us=Object.create(null);function ua(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=ut?ut.level:0;e.level=void 0===t.level?r:t.level})(r=(...e)=>e.join(" "),t),Object.setPrototypeOf(r,ua.prototype),r}for(let[e,t]of(Object.setPrototypeOf(ua.prototype,Function.prototype),Object.entries(n4)))us[e]={get(){let r=up(this,ud(t.open,t.close,this[un]),this[uu]);return Object.defineProperty(this,e,{value:r}),r}};us.visible={get(){let e=up(this,this[un],!0);return Object.defineProperty(this,"visible",{value:e}),e}};let ul=(e,t,r,...i)=>"rgb"===e?"ansi16m"===t?n4[r].ansi16m(...i):"ansi256"===t?n4[r].ansi256(n4.rgbToAnsi256(...i)):n4[r].ansi(n4.rgbToAnsi(...i)):"hex"===e?ul("rgb",t,r,...n4.hexToRgb(...i)):n4[r][e](...i);for(let e of["rgb","hex","ansi256"])us[e]={get(){let{level:t}=this;return function(...r){return up(this,ud(ul(e,uo[t],"color",...r),n4.color.close,this[un]),this[uu])}}},us["bg"+e[0].toUpperCase()+e.slice(1)]={get(){let{level:t}=this;return function(...r){return up(this,ud(ul(e,uo[t],"bgColor",...r),n4.bgColor.close,this[un]),this[uu])}}};let uc=Object.defineProperties(()=>{},{...us,level:{enumerable:!0,get(){return this[ui].level},set(e){this[ui].level=e}}}),ud=(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}},up=(e,t,r)=>{let i=(...e)=>uh(i,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(i,uc),i[ui]=e,i[un]=t,i[uu]=r,i},uh=(e,t)=>{if(e.level<=0||!t)return e[uu]?"":t;let r=e[un];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(ua.prototype,us);let uf=ua();ua({level:ur?ur.level:0});let um=(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);(ug(n,u)||!i)&&Object.defineProperty(e,r,u)},ug=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)},uA=(e,t)=>`/* Wrapped ${e}*/
33
+ ${t}`,uy=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),uE=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),u_=new WeakMap,ub=(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(u_.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))um(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=uA.bind(null,i,t.toString());Object.defineProperty(n,"name",uE);let{writable:u,enumerable:o,configurable:s}=uy;Object.defineProperty(e,"toString",{value:n,writable:u,enumerable:o,configurable:s})})(e,t,u)}(u,e),u_.set(u,i),u};ub.callCount=e=>{if(!u_.has(e))throw Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return u_.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 uv=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,uD=Symbol.for("signal-exit emitter"),uF=globalThis,uw=Object.defineProperty.bind(Object);class uB{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(uF[uD])return uF[uD];uw(uF,uD,{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 ux{}class uS extends ux{#i="win32"===uT.platform?"SIGINT":"SIGHUP";#n=new uB;#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(!uv(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 uv(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&&uv(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 uT=globalThis.process,{onExit:uI,load:uO,unload:uk}=(u=uv(uT)?new uS(uT):new class extends ux{onExit(){return()=>{}}load(){}unload(){}},{onExit:(e,t)=>u.onExit(e,t),load:()=>u.load(),unload:()=>u.unload()}),uR=O.stderr.isTTY?O.stderr:O.stdout.isTTY?O.stdout:void 0,uP=uR?ub(()=>{uI(()=>{uR.write("\x1b[?25h")},{alwaysLast:!0})}):()=>{},uL=!1,uN={};uN.show=(e=O.stderr)=>{e.isTTY&&(uL=!1,e.write("\x1b[?25h"))},uN.hide=(e=O.stderr)=>{e.isTTY&&(uP(),uL=!0,e.write("\x1b[?25l"))},uN.toggle=(e,t)=>{void 0!==e&&(uL=e),uL?uN.show(t):uN.hide(t)};var uj=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(uj);let u$=n8?.WriteStream?.prototype?.hasColors?.()??!1,uM=(e,t)=>{if(!u$)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}};uM(0,0),uM(1,22),uM(2,22),uM(3,23),uM(4,24),uM(53,55),uM(7,27),uM(8,28),uM(9,29),uM(30,39);let uU=uM(31,39),uq=uM(32,39),uV=uM(33,39),uH=uM(34,39);function uz(){let{env:e}=O,{TERM:t,TERM_PROGRAM:r}=e;return"win32"!==O.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}uM(35,39),uM(36,39),uM(37,39),uM(90,39),uM(40,49),uM(41,49),uM(42,49),uM(43,49),uM(44,49),uM(45,49),uM(46,49),uM(47,49),uM(100,49),uM(91,39),uM(92,39),uM(93,39),uM(94,39),uM(95,39),uM(96,39),uM(97,39),uM(101,49),uM(102,49),uM(103,49),uM(104,49),uM(105,49),uM(106,49),uM(107,49);let uG=uz(),uW=uH(uG?"ℹ":"i"),uJ=uq(uG?"✔":"√"),uY=uV(uG?"⚠":"‼"),uK=uU(uG?"✖":"\xd7"),uX=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")}(),uQ=[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],uZ=[12288,12288,65281,65376,65504,65510],u1=[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},[u0,u3]=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]}(u1);function u6(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(uZ,r)||(i=e)>=u0&&i<=u3||!(i<4352)&&!(i>262141)&&u2(u1,i)||t&&!((n=e)<161)&&!(n>1114109)&&u2(uQ,n)?2:1}let u4=new Intl.Segmenter,u8=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,u9=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,u7=/^\p{RGI_Emoji}$/v,u5=/^[\d#*]\u20E3$/,oe=/\p{Extended_Pictographic}/gu;function ot(e){return e>=4352&&e<=4447||e>=43360&&e<=43388}function or(e){return e>=4448&&e<=4519||e>=55216&&e<=55238}function oi(e){return e>=4520&&e<=4607||e>=55243&&e<=55291}let on=Object.freeze(new class{#p=0;#h;#f=!1;#m=!1;#g=e=>{e?.length&&("string"==typeof e?e.codePointAt(0):e[0])===3&&O.kill(O.pid,"SIGINT")};start(){this.#p++,1===this.#p&&this.#A()}stop(){0!==this.#p&&0==--this.#p&&this.#y()}#A(){let{stdin:e}=O;if("win32"===O.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}}),ou=new Map,oo=new Set(["black","red","green","yellow","blue","magenta","cyan","white","gray"]);class os{#E=0;#_=-1;#b=0;#C;#v;#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.#C={color:"cyan",stream:O.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#C.color,this.#D=this.#C.stream,"boolean"!=typeof this.#C.isEnabled&&(this.#C.isEnabled=function({stream:e=process.stdout}={}){return!!(e&&e.isTTY&&"dumb"!==process.env.TERM&&!("CI"in process.env))}({stream:this.#D})),"boolean"!=typeof this.#C.isSilent&&(this.#C.isSilent=!1),void 0!==this.#C.interval&&!(Number.isInteger(this.#C.interval)&&this.#C.interval>0))throw Error("The `interval` option must be a positive integer");const t=this.#C.interval;this.spinner=this.#C.spinner,this.#C.interval=t,this.text=this.#C.text,this.prefixText=this.#C.prefixText,this.suffixText=this.#C.suffixText,this.indent=this.#C.indent,"test"===O.env.NODE_ENV&&(this._stream=this.#D,this._isEnabled=this.#C.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.#C.prefixText?"":this.#C.prefixText,r="function"==typeof this.#C.suffixText?"":this.#C.suffixText,i=" ".repeat(this.#C.indent)+("string"==typeof t&&""!==t?t+" ":"")+"-"+("string"==typeof this.#C.text?" "+this.#C.text:"")+("string"==typeof r&&""!==r?" "+r:"");return this.#U(i,e)}}))}get indent(){return this.#C.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.#C.indent=e}get interval(){return this.#C.interval??this.#v.interval??100}get spinner(){return this.#v}set spinner(e){if(this.#_=-1,this.#C.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.#v=e}else if(uz())if(void 0===e)this.#v=uj.dots;else if("default"!==e&&uj[e])this.#v=uj[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.#v=uj.line}get text(){return this.#C.text}set text(e=""){this.#C.text=e}get prefixText(){return this.#C.prefixText}set prefixText(e=""){this.#C.prefixText=e}get suffixText(){return this.#C.suffixText}set suffixText(e=""){this.#C.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.#C.prefixText,t=" "){return this.#q(e,t,!1)}#M(e=this.#C.suffixText,t=" "){return this.#q(e,t,!0)}#U(e,t){let r=0;for(let i of(0,k.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(uX,""):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 u4.segment(n)){var s;if(s=e,u8.test(s))continue;if(u7.test(e)||function(e){if(e.length>50)return!1;if(u5.test(e))return!0;if(e.includes("‍")){let t=e.match(oe);return null!==t&&t.length>=2}return!1}(e)){u+=2;continue}let t=e.replace(u9,""),r=function(e,t){let r=[];for(let t of e)u8.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(!(ot(n=u)||or(n)||oi(n))){if(0===i)return;for(let n=e;n<r.length;n++)i+=u6(r[n],t);break}if(ot(u)&&or(r[e+1])){i+=2,e+=oi(r[e+2])?2:1;continue}i+=u6(u,t)}return i}(t,o);if(void 0!==r){u+=r;continue}u+=u6(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+=u6(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&&!oo.has(e))throw Error("The `color` option must be a valid color or `false` to disable");this.#I=e}get isEnabled(){return this.#C.isEnabled&&!this.#C.isSilent}set isEnabled(e){if("boolean"!=typeof e)throw TypeError("The `isEnabled` option must be a boolean");this.#C.isEnabled=e}get isSilent(){return this.#C.isSilent}set isSilent(e){if("boolean"!=typeof e)throw TypeError("The `isSilent` option must be a boolean");this.#C.isSilent=e}frame(){let e=Date.now();(-1===this.#_||e-this.#b>=this.interval)&&(this.#_=(this.#_+1)%this.#v.frames.length,this.#b=e);let{frames:t}=this.#v,r=t[this.#_];this.#I&&(r=uf[this.#I](r));let i=this.#$(this.#C.prefixText," "),n="string"==typeof this.text?" "+this.text:"";return i+r+n+this.#M(this.#C.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.#C.indent&&this.#D.cursorTo(this.#C.indent)}),this.#E=0),this}#V(e){if(!e||this.#w.has(e)||!e.isTTY||"function"!=typeof e.write)return;ou.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),ou.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,O.stdout,O.stderr]))this.#V(e)}#G(){for(let[e,t]of this.#w)e.write=t,ou.get(e)===this&&ou.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.#C.indent)+this.#j(e,this.text,this.#C.prefixText,this.#C.suffixText);return""!==t.trim()&&this.#O(()=>this.#D.write(t+"\n")),this}return this.isSpinning||(this.#C.hideCursor&&uN.hide(this.#D),this.#C.discardStdin&&O.stdin.isTTY&&(on.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.#C.hideCursor&&uN.show(this.#D)),this.#T&&(this.#T=!1,on.stop()),this}succeed(e){return this.stopAndPersist({symbol:uJ,text:e})}fail(e){return this.stopAndPersist({symbol:uK,text:e})}warn(e){return this.stopAndPersist({symbol:uY,text:e})}info(e){return this.stopAndPersist({symbol:uW,text:e})}stopAndPersist(e={}){if(this.isSilent)return this;let t=e.symbol??" ",r=e.text??this.text,i=e.prefixText??this.#C.prefixText,n=e.suffixText??this.#C.suffixText,u=this.#j(t,r,i,n)+"\n";return this.stop(),this.#O(()=>this.#D.write(u)),this}}function oa(e){return new os(e)}async function ol(e,t,r){return tt({appId:t.appId,caller:t.caller}),(async()=>{let i=oa(`正在执行 ${e} ...`).start();try{let{rawResponse:n,rows:u,csvHeader:o,resultMeta:s}=await r({caller:t.caller}),a=tr()?.response?.logId,{summaryPath:l}=await i_({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);tt({errorMessage:t,errorCode:nj(n)}),process.stderr.write(`${t}
34
34
  `);let r=tr()?.response?.logId;r&&process.stderr.write(`请求日志 ID: ${r}
35
35
  `),process.exitCode=d(n)?n.exitCode:1}})()}var oc=((ee={})[ee.All=1]="All",ee[ee.Douyin=2]="Douyin",ee[ee.DouyinLite=3]="DouyinLite",ee[ee.Toutiao=4]="Toutiao",ee[ee.ToutiaoLite=5]="ToutiaoLite",ee[ee.Fanqie=6]="Fanqie",ee[ee.FanqieChangTing=7]="FanqieChangTing",ee[ee.Hotsoon=8]="Hotsoon",ee[ee.Ppx=9]="Ppx",ee),od=((et={})[et.All=1]="All",et[et.Android=2]="Android",et[et.IOS=3]="IOS",et[et.OpenHarmony=4]="OpenHarmony",et[et.Windows=5]="Windows",et),op=((er={})[er.None=1]="None",er[er.SidebarReward=2]="SidebarReward",er[er.AppActive=3]="AppActive",er),oh=((ei={})[ei.All=1]="All",ei[ei.New=2]="New",ei[ei.Active=3]="Active",ei[ei.PayNew=4]="PayNew",ei[ei.PayActive=5]="PayActive",ei),of=((en={})[en.All=1]="All",en[en.Sidebar=2]="Sidebar",en),om=((eu={})[eu.Model=1]="Model",eu[eu.Brand=2]="Brand",eu[eu.AppVersion=3]="AppVersion",eu[eu.LibVersion=4]="LibVersion",eu);let og=90,oA=0,oy=2,oE=180,o_=365,ob=30,oC=7;function ov(e){return{startDate:e.startDate,endDate:e.endDate,host:rC(e.host,oc),os:rC(e.os,od),userType:rC(e.userType,oh),segment:rC(e.segment,op)}}let oD=["recordType","date","activeUser","newUser","totalUser","openTime","perUserOpenTime","avgStayTime","avgStayTimeStr","perUserStayTime","perUserStayTimeStr","sharePv","shareUv","shareTime","shareActivateUv"],oF=["hour","activeUser","openTime"],ow=["date","activeUser","permeability","r1","r2","r3","r4","r5","r6","r7","r14","r30"],oB=["sceneId","sceneName","date","uv","newUv","openTime","stayPv","avgStayTime","avgStayTimeStr","totalUv","totalNewUv","totalOpenTime","totalStayPv","totalAvgStayTime","totalAvgStayTimeStr"],ox=["dimension","name","value","ratio","total"],oS=["dimension","name","value","ratio","total"];function oT(e){rc({startDate:e.startDate,endDate:e.endDate,maxLookbackDays:og,label:"用户分析"})}function oI(e){ri(e.host,"--host",rb(oc)),ri(e.os,"--os",rb(od)),ri(e.userType,"--user-type",rb(oh)),ri(e.segment,"--segment",rb(op))}function oO(e){process.stdout.write(`${e.join("\n")}
36
36
  `)}function ok(e){process.stdout.write(`${JSON.stringify(e,null,2)}
37
- `)}function oR(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 oP(){let[e,t]=await Promise.all([i0(),iY().catch(()=>void 0)]);return{profile:e,client:t}}function oL(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(",")||"-"}`,` 登录有效期至: ${r_(n.auth.rtExpiresAt)}`]).join("\n")}
37
+ `)}function oR(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 oP(){let[e,t]=await Promise.all([i2(),iY().catch(()=>void 0)]);return{profile:e,client:t}}function oL(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(",")||"-"}`,` 登录有效期至: ${r_(n.auth.rtExpiresAt)}`]).join("\n")}
38
38
  `)}async function oN(e=!1){let t;try{t=await i5()}catch(e){if(!p(e,"AUTH_LOGIN_REQUIRED"))throw e}if(t&&!rq(t.auth.rtExpiresAt))try{await ni();let[r,{profile:i,client:n}]=await Promise.all([i5(),oP()]),u=r??t;return e?ok(oR(u,i,n,"当前已登录,无需重新登录")):oL(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 oj(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 o$();let i=await oN(e.json);if(i.isLoggedIn)return;let n=await iQ(),u=await ie({deviceAuthorizationEndpoint:n.deviceAuthorizationEndpoint,tokenEndpoint:n.tokenEndpoint,clientId:n.clientId,scope:n.scope,httpClient:na}),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});(await ny(o),!1===e.wait)?e.json?ok({success:!0,state:"authorization_pending",message:`完成授权后,请执行 ${e7} 继续完成登录。`,verificationUri:o.verificationUriComplete??o.verificationUri,userCode:o.userCode,expiresAt:o.expiresAt}):oO(r8(u.authorization,{waitingMessage:`完成授权后,请执行 ${e7} 继续完成登录。`})):(oO(r8(u.authorization,{waitingMessage:"授权完成前请保持当前命令运行,CLI 会自动继续。"})),await oM({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 o$(){let e=await nE();if(!e){let e=await i5();if(e&&!rq(e.auth.rtExpiresAt)){await ni();let[t,{profile:r,client:i}]=await Promise.all([i5(),oP()]);oL(t??e,r,i,"当前已登录,无需继续授权");return}throw new l("未找到待完成授权",{error:"AUTH_LOGIN_REQUIRED",message:`未找到待完成授权,请先执行 ${e8}`})}let t=Math.ceil(e.expiresAt-Date.now()/1e3);if(t<=0)throw await n_(),new l("授权已过期,请重新登录",{error:"AUTH_LOGIN_REQUIRED",message:`授权已过期,请重新执行 ${e8}`});let r=await i5().catch(e=>{if(!p(e,"AUTH_LOGIN_REQUIRED"))throw e});await oM({clientId:e.clientId,tokenEndpoint:e.tokenEndpoint,deviceCode:e.deviceCode,codeVerifier:e.codeVerifier,expiresInSeconds:t,intervalSeconds:e.intervalSeconds,current:r,clearSessionOnSuccess:!0})}async function oM(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=oa("正在完成登录授权 ...").start();let i=await r5({tokenEndpoint:e.tokenEndpoint,clientId:e.clientId,deviceCode:e.deviceCode,codeVerifier:e.codeVerifier,expiresInSeconds:e.expiresInSeconds,intervalSeconds:e.intervalSeconds,httpClient:na,signal:r.signal});await nn(i,e.current),e.clearSessionOnSuccess&&await n_(),t.succeed("登录完成")}catch(e){if(e instanceof rI&&e.error===rF.RequestAborted){t?.stop(),process.exitCode=130;return}t?.fail("登录未完成"),e instanceof rI&&e.error===rF.ExpiredToken&&await n_();var o=e,s={retryCommand:e8};if(!(o instanceof rI))throw o;if(o.error===rF.AccessDenied)throw new l(`授权已取消,请重新执行 ${s.retryCommand}`,{cause:o,error:"AUTH_ACCESS_DENIED",message:`授权已取消,请重新执行 ${s.retryCommand}`});if(o.error===rF.ExpiredToken)throw new l(`授权等待已超时,请重新执行 ${s.retryCommand}`,{cause:o,error:"AUTH_LOGIN_TIMEOUT",message:`授权等待已超时,请重新执行 ${s.retryCommand}`});if(o.error===rF.RequestAborted)throw new l(`授权流程已中断,请重新执行 ${s.retryCommand}`,{cause:o,error:"AUTH_LOGIN_ABORTED",message:`授权流程已中断,请重新执行 ${s.retryCommand}`});if(o.error===rF.RequestTimeout||o.error===rF.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 oU(e){let t=await i5();if(!t){let t=`当前未登录,请先执行 ${e8}`;e.json?ok({success:!0,state:"logged_out",message:t}):process.stdout.write(`当前未登录。
39
39
  请先执行 ${e8}
40
40
  `);return}if(rq(t.auth.rtExpiresAt)){let r=`当前登录已过期,请先执行 ${e8}`;e.json?ok({success:!0,state:"expired",message:r,expiresAt:t.auth.rtExpiresAt}):process.stdout.write(`当前登录已过期。
41
41
  请先执行 ${e8}
42
42
  `);return}await ni();let[r,{profile:i,client:n}]=await Promise.all([i5(),oP()]),u=r??t;e.json?ok(oR(u,i,n,"当前已登录")):oL(u,i,n,"当前已登录")}async function oq(){let e=oa("正在退出当前登录 ...").start();try{let t,r=await i5().catch(()=>void 0);try{await nr(r)}catch(e){t=e}if(await Promise.all([nu(),n_()]),t)return void e.warn("已清理本地登录态,服务端撤销失败");e.succeed("已退出登录")}catch(t){if(e.fail("退出登录失败"),iV(t))throw t;throw new l("退出登录失败",{cause:t,error:"AUTH_LOGOUT_FAILED",message:"退出登录失败,请检查网络或本机登录目录权限后重试"})}}async function oV(){let e=function(){let{dataDir:e}=ih({appName:"dymg"});return(0,T.join)(e,iN())}(),t={writable:!1};try{await (0,tp.mkdir)(e,{recursive:!0});let r=await (0,tp.mkdtemp)((0,T.join)(e,".auth-write-test-"));t.writable=!0,t.message="登录态目录可写",await (0,tp.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)}
43
- `)}let oH=require("node:readline");var oz=__webpack_require__("../../node_modules/.pnpm/mute-stream@3.0.0/node_modules/mute-stream/lib/index.js"),oG=__webpack_require__("../../node_modules/.pnpm/cli-width@4.1.0/node_modules/cli-width/index.js");let oW=(o=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,e=>{let t=0;for(o.lastIndex=0;o.test(e);)t+=1;return e.length-t}),oJ=e=>12288===e||e>=65281&&e<=65376||e>=65504&&e<=65510,oY=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,oK=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,oX=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,oQ=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,oZ=/\t{1,1000}/y,o1=/[\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,o0=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,o2=/\p{M}+/gu,o3={limit:1/0,ellipsis:""},o6=(e,t={},r={})=>{let i=t.limit??1/0,n=t.ellipsis??"",u=t?.ellipsisWidth??(n?o6(n,o3,r).width:0),o=r.controlWidth??0,s=r.tabWidth??8,a=r.emojiWidth??2,l=r.regularWidth??1,c=r.wideWidth??2,d=[[o0,l],[oK,0],[oX,o],[oZ,s],[o1,a],[oQ,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,C=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(o2,""))){let t=e.codePointAt(0)||0;if(b+(C=oJ(t)?2:oY(t)?c:l)>y&&(A=Math.min(A,Math.max(E,p)+m)),b+C>i){g=!0;break s}m+=e.length,b+=C}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+(C=(m=r===oQ?oW(e.slice(h,r.lastIndex)):r===o1?1:r.lastIndex-h)*n)>y&&(A=Math.min(A,h+Math.floor((y-b)/n))),b+C>i){g=!0;break s}b+=C,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}},o4={limit:1/0,ellipsis:"",ellipsisWidth:0},o8=(e,t={})=>o6(e,o4,t).width,o9="]8;;",o7=RegExp(`(?:\\[(?<code>\\d+)m|\\${o9}(?<uri>.*)\u0007)`,"y"),o5=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,se=e=>`\x1b[${e}m`,st=e=>`\x1b${o9}${e}\u0007`,sr=(e,t,r)=>{let i=t[Symbol.iterator](),n=!1,u=!1,o=e.at(-1),s=void 0===o?0:o8(o),a=i.next(),l=i.next(),c=0;for(;!a.done;){let o=a.value,d=o8(o);s+d<=r?e[e.length-1]+=o:(e.push(o),s=0),("\x1b"===o||"\x9b"===o)&&(n=!0,u=t.startsWith(o9,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())},si=/\r?\n/;class sn extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}}class su extends Error{name="CancelPromptError";message="Prompt was canceled"}class so extends Error{name="ExitPromptError"}class ss extends Error{name="HookError"}class sa extends Error{name="ValidationError"}let sl=new s.AsyncLocalStorage;function sc(){let e=sl.getStore();if(!e)throw new ss("[Inquirer] Hook functions can only be called from within a prompt");return e}function sd(e){return s.AsyncResource.bind((...t)=>{let r=sc(),i=!1,n=r.handleChange;r.handleChange=()=>{i=!0};let u=e(...t);return i&&n(),r.handleChange=n,u})}function sp(e){let t=sc(),{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 sh={queue(e){let t=sc(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(sc().rl);if(null!=i&&"function"!=typeof i)throw new sa("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=sc();sd(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=sc();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function sf(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(si).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=o8(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=o8(i);if(r.hard&&n>t){let e=1+Math.floor((n-(t-a)-1)/t);Math.floor((n-1)/t)<e&&s.push(""),sr(s,i,t),a=o8(s.at(-1)??"");continue}if(a+n>t&&a&&n){if(!1===r.wordWrap&&a<t){sr(s,i,t),a=o8(s.at(-1)??"");continue}s.push(""),a=0}if(a+n>t&&!1===r.wordWrap){sr(s,i,t),a=o8(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&&!o8(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){o7.lastIndex=e+1;let t=o7.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+=st(""));let e=i?o5(i):void 0;i&&e&&(u+=se(e))}else"\n"===t&&(i&&o5(i)&&(u+=se(i)),n&&(u+=st(n)))}return u})(e,i,n)).join("\n")).split("\n").map(e=>e.trimEnd())}).join("\n")}function sm(){return oG({defaultWidth:80,output:sc().rl.output})}let sg="\x1b[G",sA=(e=1)=>e>0?`\u001B[${e}A`:"",sy=(e=1)=>e>0?`\u001B[${e}B`:"",sE=(e,t)=>"number"!=typeof t||Number.isNaN(t)?`\u001B[${e+1}G`:`\u001B[${t+1};${e+1}H`,s_="\x1b[2K",sb=e=>e>0?(s_+sA(1)).repeat(e-1)+s_+sg:"";class sC{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,k.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=sm();e=sf(e,u),t=sf(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+=sA(s)),o+=sE(this.cursorPos.cols),this.write(sy(this.extraLinesUnderPrompt)+sb(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(sE(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt("");let t=sy(this.extraLinesUnderPrompt);t+=e?sb(this.height):"\n",t+="\x1b[G",t+="\x1b[?25h",this.write(t),this.rl.close()}}class sv extends Promise{static withResolver(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}}}let sD=globalThis.setImmediate;function sF(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 oz;a.pipe(i.output??process.stdout);let l=oH.createInterface({terminal:!0,input:n,output:a});a.mute();let c=new sC(l),{promise:d,resolve:p,reject:h}=sv.withResolver(),f=()=>h(new su);if(u){let e=()=>h(new sn({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(uI((e,t)=>{h(new so(`User force closed the prompt with ${e} ${t}`))}));let m=()=>h(new so("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 sl.run(A,()=>{var u;let m,g;return u=function(e){A.handleChange=()=>{A.index=0,e()},A.handleChange()},m=s.AsyncResource.bind(()=>sh.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=T.resolve(e)),Error(`Prompt functions must return a string.
44
- at ${e}`)}let[o,s]="string"==typeof u?[u]:u;c.render(o,s),sh.run()}catch(e){h(e)}if(i=!0,null!==n){let{value:e}=n;n=null,p(e)}})},"readableFlowing"in n?sD(g):g(),Object.assign(d.then(e=>(sh.clearAll(),e),e=>{throw sh.clearAll(),e}).finally(()=>{o.forEach(e=>e()),c.done({clearContent:!!i.clearPromptOnDone}),a.end()}).then(()=>d),{cancel:f})})}}let sw={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:"╱"},sB={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:"⅒"},sx={...sw,...sB},sS={...sw,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"},sT=O.platform.startsWith("win")?!!O.env.CI||!!O.env.WT_SESSION||!!O.env.TERMINUS_SUBLIME||"{cmd::Cmder}"===O.env.ConEmuTask||"Terminus-Sublime"===O.env.TERM_PROGRAM||"vscode"===O.env.TERM_PROGRAM||"xterm-256color"===O.env.TERM||"alacritty"===O.env.TERM||"JetBrains-JediTerm"===O.env.TERMINAL_EMULATOR:"linux"!==O.env.TERM,sI=sT?sx:sS;Object.entries(sB);let sO=new Set(["emacs","vim"]);function sk(e){return sO.has(e)}let sR=(e,t=[])=>"up"===e.name||t.includes("vim")&&"k"===e.name||t.includes("emacs")&&e.ctrl&&"p"===e.name,sP=(e,t=[])=>"down"===e.name||t.includes("vim")&&"j"===e.name||t.includes("emacs")&&e.ctrl&&"n"===e.name,sL=e=>"enter"===e.name||"return"===e.name,sN={prefix:{idle:(0,k.styleText)("blue","?"),done:(0,k.styleText)("green",sI.tick)},spinner:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"].map(e=>(0,k.styleText)("yellow",e))},keybindings:[],style:{answer:e=>(0,k.styleText)("cyan",e),message:e=>(0,k.styleText)("bold",e),error:e=>(0,k.styleText)("red",`> ${e}`),defaultAnswer:e=>(0,k.styleText)("dim",`(${e})`),help:e=>(0,k.styleText)("dim",e),highlight:e=>(0,k.styleText)("cyan",e),key:e=>(0,k.styleText)("cyan",(0,k.styleText)("bold",`<${e}>`))}};function sj(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 s$(...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]=sj(i)&&sj(n)?e(i,n):n}return r}({...sN,keybindings:(t=process.env.INQUIRER_KEYBINDINGS)?Array.from(new Set(t.toLowerCase().split(/[\s,]+/).filter(sk))):[]},...e.filter(e=>null!=e))}function sM(e){return sp(t=>{let r=s.AsyncResource.bind(function(e){t.get()!==e&&(t.set(e),sc().handleChange())});if(t.initialized)return[t.get(),r];let i="function"==typeof e?e():e;return t.set(i),[i,r]})}function sU(e,t){sp(r=>{let i=r.get();(!Array.isArray(i)||t.some((e,t)=>!Object.is(e,i[t])))&&sh.queue(e),r.set(t)})}function sq({status:e="idle",theme:t}){let[r,i]=sM(!1),[n,u]=sM(0),{prefix:o,spinner:s}=s$(t);if(sU(()=>{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 sV(e){return sM({current:e})[0]}function sH(e){let t=sV(e);t.current=e,sU(e=>{let r=!1,i=sd((i,n)=>{r||t.current(n,e)});return e.input.on("keypress",i),()=>{r=!0,e.input.removeListener("keypress",i)}},[])}let sz={validationFailureMode:"keep"},sG=sF((e,t)=>{let r,{prefill:i="tab"}=e,n=s$(sz,e.theme),[u,o]=sM("idle"),[s,a]=sM(String(e.default??"")),[l,c]=sM(),[d,p]=sM(""),h=sq({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"}sH(async(e,r)=>{if("idle"===u)if(sL(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("")}),sU(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 sW{separator=(0,k.styleText)("dim",Array.from({length:15}).join(sI.line));type="separator";constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&"object"==typeof e&&"type"in e&&"separator"===e.type)}}function sJ(e,t){return sp(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 sY({items:e,active:t,renderItem:r,pageSize:i,loop:n=!0}){let u=sm(),o=t=>(t%e.length+e.length)%e.length,s=e.map((e,i)=>null==e?[]:sf(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=sV({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 sK={icon:{cursor:sI.pointer},style:{disabled:e=>(0,k.styleText)("dim",e),description:e=>(0,k.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,k.styleText)("bold",e)} ${(0,k.styleText)("dim",t)}`).join((0,k.styleText)("dim"," • "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function sX(e){return!sW.isSeparator(e)&&!e.disabled}function sQ(e){return!sW.isSeparator(e)}let sZ=sF((e,t)=>{let{loop:r=!0,pageSize:i=7}=e,n=s$(sK,e.theme),{keybindings:u}=n,[o,s]=sM("idle"),a=sq({status:o,theme:n}),l=sV(),c=!u.includes("vim"),d=sJ(()=>e.choices.map(e=>{if(sW.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=sJ(()=>{let e=d.findIndex(sQ),t=d.findLastIndex(sQ);if(-1===e)throw new sa("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[d]),h=sJ(()=>"default"in e?d.findIndex(t=>sX(t)&&t.value===e.default):-1,[e.default,d]),[f,m]=sM(-1===h?p.first:h),g=d[f];if(null==g||sW.isSeparator(g))throw Error("Active index does not point to a choice");let[A,y]=sM();sH((e,i)=>{if(clearTimeout(l.current),A&&y(void 0),sL(e))g.disabled?y(n.i18n.disabledError):(s("done"),t(g.value));else if(sR(e,u)||sP(e,u)){if(i.clearLine(0),r||sR(e,u)&&f!==p.first||sP(e,u)&&f!==p.last){let t=sR(e,u)?-1:1,r=f;do r=(r+t+d.length)%d.length;while(!sQ(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=>!sW.isSeparator(r)&&++t===e),n=d[r];null!=n&&sX(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=>!sW.isSeparator(t)&&!!sX(t)&&t.name.toLowerCase().startsWith(e));-1!==t&&m(t),l.current=setTimeout(()=>{i.clearLine(0)},700)}}}),sU(()=>()=>{clearTimeout(l.current)},[]);let E=n.style.message(e.message,o),_=n.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),b=0,C=sY({items:d,active:f,renderItem({item:e,isActive:t,index:r}){if(sW.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:v}=g,D=[[a,E].filter(Boolean).join(" "),C," ",v?n.style.description(v):"",A?n.style.error(A):"",_].filter(Boolean).join("\n").trimEnd();return`${D}\u001b[?25l`});function s1(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 s0=sF((e,t)=>{let r,{validate:i=()=>!0,min:n=-1/0,max:u=1/0,step:o=1,required:s=!1}=e,a=s$(e.theme),[l,c]=sM("idle"),[d,p]=sM(""),[h="",f]=sM(!0===s1(e.default,{min:n,max:u,step:o})?e.default?.toString():void 0),[m,g]=sM(),A=sq({status:l,theme:a});sH(async(e,r)=>{if("idle"===l)if(sL(e)){let e=d||h,a=""===e?void 0:Number(e);c("loading");let l=!0;(s||null!=a)&&(l=s1(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 s2(e,t){let r=!1!==t;return/^(y|yes)/i.test(e)?r=!0:/^(n|no)/i.test(e)&&(r=!1),r}function s3(e){return e?"Yes":"No"}let s6=sF((e,t)=>{let{transformer:r=s3}=e,[i,n]=sM("idle"),[u,o]=sM(""),s=s$(e.theme),a=sq({status:i,theme:s});sH((s,a)=>{if("idle"===i)if(sL(s)){let i=s2(u,e.default);o(r(i)),n("done"),t(i)}else if("tab"===s.name){let t=s3(!s2(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}`}),s4=/\d+/,s8={style:{description:e=>(0,k.styleText)("cyan",e)}};function s9(e){return null!=e&&!sW.isSeparator(e)}function s7(e,t){let r,i=t.filter(s9);return!(r=i.find(t=>t.key===e))&&s4.test(e)&&(r=i[Number.parseInt(e,10)-1]),r?[r,t.indexOf(r)]:[void 0,void 0]}let s5=sF((e,t)=>{let{loop:r=!0}=e,i=sJ(()=>{var t;let r;return t=e.choices,r=0,t.map(e=>{if(sW.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]=sM("idle"),[o,s]=sM(()=>{let t=null==e.default?void 0:i.find(t=>s9(t)&&t.value===e.default);return t?.key??""}),[a,l]=sM(),c=s$(s8,e.theme),{keybindings:d}=c,p=sq({status:n,theme:c}),h=sJ(()=>{let e=i.findIndex(s9),t=i.findLastIndex(s9);if(-1===e)throw new sa("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[i]);sH((e,n)=>{if(sL(e)){let[e]=s7(o,i);s9(e)?(s(e.short),u("done"),t(e.value)):""===o?l("Please input a value"):l(`"${(0,k.styleText)("red",o)}" isn't an available option`)}else if(sR(e,d)||sP(e,d)){n.clearLine(0);let[t,u]=s7(o,i);if(t){if(r||sR(e,d)&&u!==h.first||sP(e,d)&&u!==h.last){let t,r=sR(e,d)?-1:1,n=u;do n=(n+r+i.length)%i.length,t=i[n];while(!s9(t));s(t.key)}}else s((sP(e,d)?i.find(s9):i.findLast(s9)).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(sW.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]=s7(o,i),y="";return!a&&A?.description&&(y=c.style.description(A.description)),[`${p} ${f} ${o}`,[m,g,y].filter(Boolean).join("\n")]}),ae={key:"h",name:"Help, list all options",value:void 0},at=sF((e,t)=>{let{default:r="h"}=e,i=sJ(()=>e.choices.map(e=>{if(sW.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]=sM("idle"),[o,s]=sM(""),[a,l]=sM(e.expanded??!1),[c,d]=sM(),p=s$(e.theme),h=sq({theme:p,status:n});sH((e,n)=>{if(sL(e)){let e=(o||r).toLowerCase();if("h"!==e||a){let r=i.find(t=>!sW.isSeparator(t)&&t.key===e);r?(u("done"),s(e),t(r.value)):""===o?d("Please input a value"):d(`"${(0,k.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=>!sW.isSeparator(e)&&e.key===o.toLowerCase());return`${h} ${f} ${p.style.answer(e.name)}`}let m=a?i:[...i,ae],g="",A=m.map(e=>sW.isSeparator(e)?"":e.key===r?e.key.toUpperCase():e.key).join("");A=` ${p.style.defaultAnswer(A)}`,a&&(A="",g=m.map(e=>{if(sW.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=>!sW.isSeparator(e)&&e.key===o.toLowerCase());E&&(y=`${(0,k.styleText)("cyan",">>")} ${E.name}`);let _="";return c&&(_=p.style.error(c)),[`${h} ${f}${A} ${o}`,[g,y,_].filter(Boolean).join("\n")]}),ar={icon:{checked:(0,k.styleText)("green",sI.circleFilled),unchecked:sI.circle,cursor:sI.pointer,disabledChecked:(0,k.styleText)("green",sI.circleDouble),disabledUnchecked:"-"},style:{disabled:e=>(0,k.styleText)("dim",e),renderSelectedChoices:e=>e.map(e=>e.short).join(", "),description:e=>(0,k.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,k.styleText)("bold",e)} ${(0,k.styleText)("dim",t)}`).join((0,k.styleText)("dim"," • "))},i18n:{disabledError:"This option is disabled and cannot be toggled."}};function ai(e){return!sW.isSeparator(e)&&!e.disabled}function an(e){return!sW.isSeparator(e)}function au(e){return!sW.isSeparator(e)&&e.checked}function ao(e){return ai(e)?{...e,checked:!e.checked}:e}let as=sF((e,t)=>{let r,{pageSize:i=7,loop:n=!0,required:u,validate:o=()=>!0}=e,s={all:"a",invert:"i",...e.shortcuts},a=s$(ar,e.theme),{keybindings:l}=a,[c,d]=sM("idle"),p=sq({status:c,theme:a}),[h,f]=sM(e.choices.map(e=>{if(sW.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=sJ(()=>{let e=h.findIndex(an),t=h.findLastIndex(an);if(-1===e)throw new sa("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[h]),[g,A]=sM(m.first),[y,E]=sM();sH(async e=>{if(sL(e)){let e=h.filter(au),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(sR(e,l)||sP(e,l)){if(y&&E(void 0),n||sR(e,l)&&g!==m.first||sP(e,l)&&g!==m.last){let t=sR(e,l)?-1:1,r=g;do r=(r+t+h.length)%h.length;while(!an(h[r]));A(r)}}else if("space"===e.name){let e=h[g];e&&!sW.isSeparator(e)&&(e.disabled?E(a.i18n.disabledError):(E(void 0),f(h.map((e,t)=>t===g?ao(e):e))))}else if(e.name===s.all){var r;let e=h.some(e=>ai(e)&&!e.checked);f(h.map((r=e,function(e){return ai(e)?{...e,checked:r}:e})))}else if(e.name===s.invert)f(h.map(ao));else{let t;if(t=e,"1234567890".includes(t.name)){let t=Number(e.name)-1,r=-1,i=h.findIndex(e=>!sW.isSeparator(e)&&++r===t),n=h[i];n&&ai(n)&&(A(i),f(h.map((e,t)=>t===i?ao(e):e)))}}});let _=a.style.message(e.message,c),b=sY({items:h,active:g,renderItem({item:e,isActive:t}){if(sW.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(au);return[p,_,a.style.answer(a.style.renderSelectedChoices(e,h))].filter(Boolean).join(" ")}let C=[["↑↓","navigate"],["space","select"]];s.all&&C.push([s.all,"all"]),s.invert&&C.push([s.invert,"invert"]),C.push(["⏎","submit"]);let v=a.style.keysHelpTip(C),D=[[p,_].filter(Boolean).join(" "),b," ",r?a.style.description(r):"",y?a.style.error(y):"",v].filter(Boolean).join("\n").trimEnd();return`${D}\u001b[?25l`}),aa={style:{maskedText:"[input is masked]"}},al=sF((e,t)=>{let r,{validate:i=()=>!0}=e,n=s$(aa,e.theme),[u,o]=sM("idle"),[s,a]=sM(),[l,c]=sM(""),d=sq({status:u,theme:n});sH(async(e,r)=>{if("idle"===u)if(sL(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 ac=__webpack_require__("../../node_modules/.pnpm/chardet@2.1.1/node_modules/chardet/lib/index.js"),ad=__webpack_require__("../../node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/index.js");class ap extends Error{name="CreateFileError";originalError;constructor(e){super(`Failed to create temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class ah extends Error{name="LaunchEditorError";originalError;constructor(e){super(`Failed to launch editor.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class af extends Error{name="ReadFileError";originalError;constructor(e){super(`Failed to read temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class am extends Error{name="RemoveFileError";originalError;constructor(e){super(`Failed to remove temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}function ag(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}class aA{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 ah(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 ah(e))}),r.once("exit",t=>{this.lastExitStatus=t??0,e()})}catch(e){t(new ah(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,I.rmSync)(this.tempDir,{force:!0,recursive:!0}),this.tempFile="",this.tempDir=""}catch(e){throw new am(e)}}createTempFile(){try{let e=T.resolve(this.fileOptions.dir??td.tmpdir());this.tempDir=(0,I.mkdtempSync)(T.join(e,"inquirer-editor-"));let t=(0,tc.randomUUID)(),r=ag(this.fileOptions.prefix),i=ag(this.fileOptions.postfix),n=`${r}${t}${i}`;this.tempFile=T.join(this.tempDir,n);let u={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(u.mode=this.fileOptions.mode),(0,I.writeFileSync)(this.tempFile,this.text,u)}catch(e){throw new ap(e)}}editorArgs(){return[...this.editor.args,this.tempFile]}readTemporaryFile(){try{let e=(0,I.readFileSync)(this.tempFile);if(0===e.length)this.text="";else{let t=(0,ac.detect)(e)??"utf8";ad.encodingExists(t)||(t="utf8"),this.text=ad.decode(e,t)}}catch(e){throw new af(e)}}}let ay={validationFailureMode:"keep",style:{loadingMessage:()=>"Validating...",waitingMessage:e=>`Press ${e} to launch your preferred editor.`}},aE=sF((e,t)=>{let{waitForUserInput:r=!0,file:{postfix:i=e.postfix??".txt",...n}={},validate:u=()=>!0}=e,o=s$(ay,e.theme),[s,a]=sM("idle"),[l="",c]=sM(e.default),[d,p]=sM(),h=sq({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 aA(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))}}sU(e=>{r||f(e)},[]),sH((e,t)=>{"idle"===s&&sL(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]}),a_={icon:{cursor:sI.pointer},style:{disabled:e=>(0,k.styleText)("dim",`- ${e}`),searchTerm:e=>(0,k.styleText)("cyan",e),description:e=>(0,k.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,k.styleText)("bold",e)} ${(0,k.styleText)("dim",t)}`).join((0,k.styleText)("dim"," • "))}};function ab(e){return!sW.isSeparator(e)&&!e.disabled}let aC=sF((e,t)=>{let r,i,{pageSize:n=7,validate:u=()=>!0}=e,o=s$(a_,e.theme),[s,a]=sM("loading"),[l,c]=sM(""),[d,p]=sM([]),[h,f]=sM(),m=sV(!1),g=sq({status:s,theme:o}),A=sJ(()=>{let e=d.findIndex(ab);return{first:e,last:d.findLastIndex(ab)}},[d]),[y=A.first,E]=sM();sU(()=>{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(sW.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=>ab(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];sH(async(e,r)=>{if(sL(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&&(sR(e)||sP(e))){if(r.clearLine(0),sR(e)&&y!==A.first||sP(e)&&y!==A.last){let t=sR(e)?-1:1,r=y;do r=(r+t+d.length)%d.length;while(!ab(d[r]));E(r)}}else c(r.line)});let b=o.style.message(e.message,s),C=o.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),v=sY({items:d,active:y,renderItem({item:e,isActive:t}){if(sW.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??v," ",D?o.style.description(D):"",C].filter(Boolean).join("\n").trimEnd()]});var av=__webpack_require__("../../node_modules/.pnpm/run-async@4.0.6/node_modules/run-async/index.js");function aD(e){queueMicrotask(()=>{throw e})}function aF(e){try{e()}catch(e){aD(e)}}function aw(){return{closed:!0,unsubscribe(){}}}function aB(e){return e instanceof Error?e:Error(String(e))}function ax(e){"function"==typeof e?e():e?.unsubscribe()}class aS{"@@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&&ax(o))}},d={next(e){a||aF(()=>s.next?.(e))},error(e){!a&&(a=!0,s.error?aF(()=>s.error?.(e)):aD(e),l&&ax(o))},complete(){!a&&(a=!0,aF(()=>s.complete?.()),l&&ax(o))}};try{o=this.subscribeFn(d),l=!0,c.closed&&ax(o)}catch(e){d.error?.(e)}return c}[Symbol.asyncIterator](){return aI(this)[Symbol.asyncIterator]()}}let aT=new aS(e=>(e.complete?.(),aw()));function aI(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=aB(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=aB(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 aO=(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])})},ak=(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 aR(e,t,r){let i=e[t];return"function"==typeof i?av(i)(r):i}class aP 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 aL extends Error{name="TTYError";isTtyError=!0}class aN{prompts;answers={};process=aT;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 aS(e=>{if(u)return e.error?.(r),aw();if(n)return e.complete?.(),aw();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||aF(()=>t.next?.(e))},error(e){if(!n&&!u){for(let{observer:t,subscription:n}of(u=!0,r=e,i))n.closed=!0,aF(()=>t.error?.(e));i.clear()}},complete(){if(!n&&!u){for(let{observer:e,subscription:t}of(n=!0,i))t.closed=!0,aF(()=>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);aO(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*aI(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 aP(r,this.prompts);let[i,n,u]=await Promise.all([aR(e,"message",this.answers),aR(e,"default",this.answers),aR(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 sn({cause:o.reason}));let s=oH.createInterface(function(e){e.skipTTYChecks=void 0===e.skipTTYChecks||e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY)throw new aL("Prompts can not be meaningfully rendered in non-TTY environments");let r=new oz;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"),oH.cursorTo(s.output,0),s.output.end(),s.close(),r?.()},d=()=>{n(new sn({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!==ak(this.answers,e.name))return!1;let{when:t}=e;return"function"==typeof t?!!await av(t)(this.answers):!1!==t}}let aj={input:sG,select:sZ,number:s0,confirm:s6,rawlist:s5,expand:at,checkbox:as,password:al,editor:aE,search:aC};function a$(e){function t(r,i){let n=new aN(t.prompts,e);return Object.assign(n.run(r,i),{ui:n})}return t.prompts={...aj},t.registerPrompt=function(e,r){return t.prompts[e]=r,this},t.restoreDefaultPrompts=function(){t.prompts={...aj}},t}let aM=a$(),aU=aM;async function aq(){let e=function(){let e=(0,T.resolve)(__dirname,"..","skills",e6);if((0,I.existsSync)((0,T.resolve)(e,"SKILL.md")))return e;let t=(0,T.resolve)(__dirname,"..");return(0,I.existsSync)((0,T.resolve)(t,"SKILL.md"))?t:e}(),t=(0,T.resolve)(e,"SKILL.md");if(!(0,I.existsSync)(e))throw new l(`未找到随包发布的 Skill 目录: ${e}`,{error:"SKILL_INSTALL_FAILED"});if(!(0,I.existsSync)(t))throw new l(`随包发布的 Skill 缺少入口文件: ${t}`,{error:"SKILL_INSTALL_FAILED"});let r=oa(`正在同步 ${e6} Skill ...`).start();try{var i;await (i=e,_({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(`${e6} Skill 已同步完成`)}catch(e){throw r.fail(`${e6} Skill 同步失败`),e}}async function aV(){try{await aq()}catch(e){if(d(e)){tt({errorMessage:e.message,errorCode:nj(e)}),process.stderr.write(`${e.message}
45
- `),process.exitCode=e.exitCode;return}throw e}}let aH=new Set(["latest","beta","alpha","next","stable"]);async function az(e){let t=e?.trim()||"latest";if("latest"===t){let e=oa(`正在解析 ${e3} 最新版本 ...`).start();try{let t=await nJ();return e.succeed(`最新版本:${t}`),t}catch(t){throw e.fail("解析最新版本失败"),t}}if(!aH.has(t)&&!b(t))throw new l(`不支持的目标版本: ${t}`,{error:"INVALID_TARGET_VERSION",message:"--target-version 仅支持 semver 版本号或 latest / beta / alpha / next / stable"});return t}async function aG(e){var t,r,i;let n=await az(e.targetVersion),u=`${e3}@${n}`,o=function(e){let t=nq({input:e});if(void 0!==e){if(!t)throw new l(`不支持的包管理器: ${e}`,{error:"INVALID_PACKAGE_MANAGER",message:`--package-manager 只能取 ${n$.join(" / ")}`});return t}let r=nq({userAgent:process.env.npm_config_user_agent});if(!r)throw new l("当前环境无法自动识别全局安装所使用的包管理器",{error:"INVALID_PACKAGE_MANAGER",message:`请显式传入 --package-manager,支持 ${n$.join(" / ")}`});return r}(e.packageManager);if("0.5.0"===n)return(oa("dymg 已是目标版本(0.5.0),跳过 CLI 安装").info(),e.skipSkills)?void oa("已跳过 Skill 同步。如需同步,请执行 dymg skills install").info():void await aq();let s=oa(`正在使用 ${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),_({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 oa("已跳过 Skill 同步。如需同步,请执行 dymg skills install").info();let a=oa("正在启动更新后的 CLI 同步 Skill ...").start();try{await (i=u,_({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 aW(e){try{await aG(e)}catch(e){if(d(e)){tt({errorMessage:e.message,errorCode:nj(e)}),process.stderr.write(`${e.message}
46
- `),process.exitCode=e.exitCode;return}throw e}}async function aJ(e){return(await aU([{type:"list",name:"action",message:`发现新版本 ${e},当前版本 0.5.0。是否现在更新并同步 Skill?`,choices:[{name:"现在更新",value:"update"},{name:"暂不更新",value:"skip"}],default:"update"}])).action}async function aY(e,t){let r=oa(`正在检查 ${e3} 更新,当前版本:0.5.0`).start();try{let e=await nY();if(r.succeed("更新检查完成"),!e.hasUpdate){await nK(e),oa(`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)||!nq({userAgent:process.env.npm_config_user_agent})){var i;i=e.latestVersion,process.stdout.write(`${nz(i).join("\n")}
43
+ `)}let oH=require("node:readline");var oz=__webpack_require__("../../node_modules/.pnpm/mute-stream@3.0.0/node_modules/mute-stream/lib/index.js"),oG=__webpack_require__("../../node_modules/.pnpm/cli-width@4.1.0/node_modules/cli-width/index.js");let oW=(o=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,e=>{let t=0;for(o.lastIndex=0;o.test(e);)t+=1;return e.length-t}),oJ=e=>12288===e||e>=65281&&e<=65376||e>=65504&&e<=65510,oY=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,oK=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,oX=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,oQ=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,oZ=/\t{1,1000}/y,o1=/[\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,o2=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,o0=/\p{M}+/gu,o3={limit:1/0,ellipsis:""},o6=(e,t={},r={})=>{let i=t.limit??1/0,n=t.ellipsis??"",u=t?.ellipsisWidth??(n?o6(n,o3,r).width:0),o=r.controlWidth??0,s=r.tabWidth??8,a=r.emojiWidth??2,l=r.regularWidth??1,c=r.wideWidth??2,d=[[o2,l],[oK,0],[oX,o],[oZ,s],[o1,a],[oQ,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,C=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(o0,""))){let t=e.codePointAt(0)||0;if(b+(C=oJ(t)?2:oY(t)?c:l)>y&&(A=Math.min(A,Math.max(E,p)+m)),b+C>i){g=!0;break s}m+=e.length,b+=C}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+(C=(m=r===oQ?oW(e.slice(h,r.lastIndex)):r===o1?1:r.lastIndex-h)*n)>y&&(A=Math.min(A,h+Math.floor((y-b)/n))),b+C>i){g=!0;break s}b+=C,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}},o4={limit:1/0,ellipsis:"",ellipsisWidth:0},o8=(e,t={})=>o6(e,o4,t).width,o9="]8;;",o7=RegExp(`(?:\\[(?<code>\\d+)m|\\${o9}(?<uri>.*)\u0007)`,"y"),o5=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,se=e=>`\x1b[${e}m`,st=e=>`\x1b${o9}${e}\u0007`,sr=(e,t,r)=>{let i=t[Symbol.iterator](),n=!1,u=!1,o=e.at(-1),s=void 0===o?0:o8(o),a=i.next(),l=i.next(),c=0;for(;!a.done;){let o=a.value,d=o8(o);s+d<=r?e[e.length-1]+=o:(e.push(o),s=0),("\x1b"===o||"\x9b"===o)&&(n=!0,u=t.startsWith(o9,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())},si=/\r?\n/;class sn extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}}class su extends Error{name="CancelPromptError";message="Prompt was canceled"}class so extends Error{name="ExitPromptError"}class ss extends Error{name="HookError"}class sa extends Error{name="ValidationError"}let sl=new s.AsyncLocalStorage;function sc(){let e=sl.getStore();if(!e)throw new ss("[Inquirer] Hook functions can only be called from within a prompt");return e}function sd(e){return s.AsyncResource.bind((...t)=>{let r=sc(),i=!1,n=r.handleChange;r.handleChange=()=>{i=!0};let u=e(...t);return i&&n(),r.handleChange=n,u})}function sp(e){let t=sc(),{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 sh={queue(e){let t=sc(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(sc().rl);if(null!=i&&"function"!=typeof i)throw new sa("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=sc();sd(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=sc();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function sf(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(si).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=o8(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=o8(i);if(r.hard&&n>t){let e=1+Math.floor((n-(t-a)-1)/t);Math.floor((n-1)/t)<e&&s.push(""),sr(s,i,t),a=o8(s.at(-1)??"");continue}if(a+n>t&&a&&n){if(!1===r.wordWrap&&a<t){sr(s,i,t),a=o8(s.at(-1)??"");continue}s.push(""),a=0}if(a+n>t&&!1===r.wordWrap){sr(s,i,t),a=o8(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&&!o8(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){o7.lastIndex=e+1;let t=o7.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+=st(""));let e=i?o5(i):void 0;i&&e&&(u+=se(e))}else"\n"===t&&(i&&o5(i)&&(u+=se(i)),n&&(u+=st(n)))}return u})(e,i,n)).join("\n")).split("\n").map(e=>e.trimEnd())}).join("\n")}function sm(){return oG({defaultWidth:80,output:sc().rl.output})}let sg="\x1b[G",sA=(e=1)=>e>0?`\u001B[${e}A`:"",sy=(e=1)=>e>0?`\u001B[${e}B`:"",sE=(e,t)=>"number"!=typeof t||Number.isNaN(t)?`\u001B[${e+1}G`:`\u001B[${t+1};${e+1}H`,s_="\x1b[2K",sb=e=>e>0?(s_+sA(1)).repeat(e-1)+s_+sg:"";class sC{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,k.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=sm();e=sf(e,u),t=sf(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+=sA(s)),o+=sE(this.cursorPos.cols),this.write(sy(this.extraLinesUnderPrompt)+sb(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(sE(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt("");let t=sy(this.extraLinesUnderPrompt);t+=e?sb(this.height):"\n",t+="\x1b[G",t+="\x1b[?25h",this.write(t),this.rl.close()}}class sv extends Promise{static withResolver(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}}}let sD=globalThis.setImmediate;function sF(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 oz;a.pipe(i.output??process.stdout);let l=oH.createInterface({terminal:!0,input:n,output:a});a.mute();let c=new sC(l),{promise:d,resolve:p,reject:h}=sv.withResolver(),f=()=>h(new su);if(u){let e=()=>h(new sn({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(uI((e,t)=>{h(new so(`User force closed the prompt with ${e} ${t}`))}));let m=()=>h(new so("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 sl.run(A,()=>{var u;let m,g;return u=function(e){A.handleChange=()=>{A.index=0,e()},A.handleChange()},m=s.AsyncResource.bind(()=>sh.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=T.resolve(e)),Error(`Prompt functions must return a string.
44
+ at ${e}`)}let[o,s]="string"==typeof u?[u]:u;c.render(o,s),sh.run()}catch(e){h(e)}if(i=!0,null!==n){let{value:e}=n;n=null,p(e)}})},"readableFlowing"in n?sD(g):g(),Object.assign(d.then(e=>(sh.clearAll(),e),e=>{throw sh.clearAll(),e}).finally(()=>{o.forEach(e=>e()),c.done({clearContent:!!i.clearPromptOnDone}),a.end()}).then(()=>d),{cancel:f})})}}let sw={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:"╱"},sB={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:"⅒"},sx={...sw,...sB},sS={...sw,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"},sT=O.platform.startsWith("win")?!!O.env.CI||!!O.env.WT_SESSION||!!O.env.TERMINUS_SUBLIME||"{cmd::Cmder}"===O.env.ConEmuTask||"Terminus-Sublime"===O.env.TERM_PROGRAM||"vscode"===O.env.TERM_PROGRAM||"xterm-256color"===O.env.TERM||"alacritty"===O.env.TERM||"JetBrains-JediTerm"===O.env.TERMINAL_EMULATOR:"linux"!==O.env.TERM,sI=sT?sx:sS;Object.entries(sB);let sO=new Set(["emacs","vim"]);function sk(e){return sO.has(e)}let sR=(e,t=[])=>"up"===e.name||t.includes("vim")&&"k"===e.name||t.includes("emacs")&&e.ctrl&&"p"===e.name,sP=(e,t=[])=>"down"===e.name||t.includes("vim")&&"j"===e.name||t.includes("emacs")&&e.ctrl&&"n"===e.name,sL=e=>"enter"===e.name||"return"===e.name,sN={prefix:{idle:(0,k.styleText)("blue","?"),done:(0,k.styleText)("green",sI.tick)},spinner:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"].map(e=>(0,k.styleText)("yellow",e))},keybindings:[],style:{answer:e=>(0,k.styleText)("cyan",e),message:e=>(0,k.styleText)("bold",e),error:e=>(0,k.styleText)("red",`> ${e}`),defaultAnswer:e=>(0,k.styleText)("dim",`(${e})`),help:e=>(0,k.styleText)("dim",e),highlight:e=>(0,k.styleText)("cyan",e),key:e=>(0,k.styleText)("cyan",(0,k.styleText)("bold",`<${e}>`))}};function sj(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 s$(...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]=sj(i)&&sj(n)?e(i,n):n}return r}({...sN,keybindings:(t=process.env.INQUIRER_KEYBINDINGS)?Array.from(new Set(t.toLowerCase().split(/[\s,]+/).filter(sk))):[]},...e.filter(e=>null!=e))}function sM(e){return sp(t=>{let r=s.AsyncResource.bind(function(e){t.get()!==e&&(t.set(e),sc().handleChange())});if(t.initialized)return[t.get(),r];let i="function"==typeof e?e():e;return t.set(i),[i,r]})}function sU(e,t){sp(r=>{let i=r.get();(!Array.isArray(i)||t.some((e,t)=>!Object.is(e,i[t])))&&sh.queue(e),r.set(t)})}function sq({status:e="idle",theme:t}){let[r,i]=sM(!1),[n,u]=sM(0),{prefix:o,spinner:s}=s$(t);if(sU(()=>{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 sV(e){return sM({current:e})[0]}function sH(e){let t=sV(e);t.current=e,sU(e=>{let r=!1,i=sd((i,n)=>{r||t.current(n,e)});return e.input.on("keypress",i),()=>{r=!0,e.input.removeListener("keypress",i)}},[])}let sz={validationFailureMode:"keep"},sG=sF((e,t)=>{let r,{prefill:i="tab"}=e,n=s$(sz,e.theme),[u,o]=sM("idle"),[s,a]=sM(String(e.default??"")),[l,c]=sM(),[d,p]=sM(""),h=sq({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"}sH(async(e,r)=>{if("idle"===u)if(sL(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("")}),sU(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 sW{separator=(0,k.styleText)("dim",Array.from({length:15}).join(sI.line));type="separator";constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&"object"==typeof e&&"type"in e&&"separator"===e.type)}}function sJ(e,t){return sp(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 sY({items:e,active:t,renderItem:r,pageSize:i,loop:n=!0}){let u=sm(),o=t=>(t%e.length+e.length)%e.length,s=e.map((e,i)=>null==e?[]:sf(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=sV({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 sK={icon:{cursor:sI.pointer},style:{disabled:e=>(0,k.styleText)("dim",e),description:e=>(0,k.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,k.styleText)("bold",e)} ${(0,k.styleText)("dim",t)}`).join((0,k.styleText)("dim"," • "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function sX(e){return!sW.isSeparator(e)&&!e.disabled}function sQ(e){return!sW.isSeparator(e)}let sZ=sF((e,t)=>{let{loop:r=!0,pageSize:i=7}=e,n=s$(sK,e.theme),{keybindings:u}=n,[o,s]=sM("idle"),a=sq({status:o,theme:n}),l=sV(),c=!u.includes("vim"),d=sJ(()=>e.choices.map(e=>{if(sW.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=sJ(()=>{let e=d.findIndex(sQ),t=d.findLastIndex(sQ);if(-1===e)throw new sa("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[d]),h=sJ(()=>"default"in e?d.findIndex(t=>sX(t)&&t.value===e.default):-1,[e.default,d]),[f,m]=sM(-1===h?p.first:h),g=d[f];if(null==g||sW.isSeparator(g))throw Error("Active index does not point to a choice");let[A,y]=sM();sH((e,i)=>{if(clearTimeout(l.current),A&&y(void 0),sL(e))g.disabled?y(n.i18n.disabledError):(s("done"),t(g.value));else if(sR(e,u)||sP(e,u)){if(i.clearLine(0),r||sR(e,u)&&f!==p.first||sP(e,u)&&f!==p.last){let t=sR(e,u)?-1:1,r=f;do r=(r+t+d.length)%d.length;while(!sQ(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=>!sW.isSeparator(r)&&++t===e),n=d[r];null!=n&&sX(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=>!sW.isSeparator(t)&&!!sX(t)&&t.name.toLowerCase().startsWith(e));-1!==t&&m(t),l.current=setTimeout(()=>{i.clearLine(0)},700)}}}),sU(()=>()=>{clearTimeout(l.current)},[]);let E=n.style.message(e.message,o),_=n.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),b=0,C=sY({items:d,active:f,renderItem({item:e,isActive:t,index:r}){if(sW.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:v}=g,D=[[a,E].filter(Boolean).join(" "),C," ",v?n.style.description(v):"",A?n.style.error(A):"",_].filter(Boolean).join("\n").trimEnd();return`${D}\u001b[?25l`});function s1(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 s2=sF((e,t)=>{let r,{validate:i=()=>!0,min:n=-1/0,max:u=1/0,step:o=1,required:s=!1}=e,a=s$(e.theme),[l,c]=sM("idle"),[d,p]=sM(""),[h="",f]=sM(!0===s1(e.default,{min:n,max:u,step:o})?e.default?.toString():void 0),[m,g]=sM(),A=sq({status:l,theme:a});sH(async(e,r)=>{if("idle"===l)if(sL(e)){let e=d||h,a=""===e?void 0:Number(e);c("loading");let l=!0;(s||null!=a)&&(l=s1(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 s0(e,t){let r=!1!==t;return/^(y|yes)/i.test(e)?r=!0:/^(n|no)/i.test(e)&&(r=!1),r}function s3(e){return e?"Yes":"No"}let s6=sF((e,t)=>{let{transformer:r=s3}=e,[i,n]=sM("idle"),[u,o]=sM(""),s=s$(e.theme),a=sq({status:i,theme:s});sH((s,a)=>{if("idle"===i)if(sL(s)){let i=s0(u,e.default);o(r(i)),n("done"),t(i)}else if("tab"===s.name){let t=s3(!s0(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}`}),s4=/\d+/,s8={style:{description:e=>(0,k.styleText)("cyan",e)}};function s9(e){return null!=e&&!sW.isSeparator(e)}function s7(e,t){let r,i=t.filter(s9);return!(r=i.find(t=>t.key===e))&&s4.test(e)&&(r=i[Number.parseInt(e,10)-1]),r?[r,t.indexOf(r)]:[void 0,void 0]}let s5=sF((e,t)=>{let{loop:r=!0}=e,i=sJ(()=>{var t;let r;return t=e.choices,r=0,t.map(e=>{if(sW.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]=sM("idle"),[o,s]=sM(()=>{let t=null==e.default?void 0:i.find(t=>s9(t)&&t.value===e.default);return t?.key??""}),[a,l]=sM(),c=s$(s8,e.theme),{keybindings:d}=c,p=sq({status:n,theme:c}),h=sJ(()=>{let e=i.findIndex(s9),t=i.findLastIndex(s9);if(-1===e)throw new sa("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[i]);sH((e,n)=>{if(sL(e)){let[e]=s7(o,i);s9(e)?(s(e.short),u("done"),t(e.value)):""===o?l("Please input a value"):l(`"${(0,k.styleText)("red",o)}" isn't an available option`)}else if(sR(e,d)||sP(e,d)){n.clearLine(0);let[t,u]=s7(o,i);if(t){if(r||sR(e,d)&&u!==h.first||sP(e,d)&&u!==h.last){let t,r=sR(e,d)?-1:1,n=u;do n=(n+r+i.length)%i.length,t=i[n];while(!s9(t));s(t.key)}}else s((sP(e,d)?i.find(s9):i.findLast(s9)).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(sW.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]=s7(o,i),y="";return!a&&A?.description&&(y=c.style.description(A.description)),[`${p} ${f} ${o}`,[m,g,y].filter(Boolean).join("\n")]}),ae={key:"h",name:"Help, list all options",value:void 0},at=sF((e,t)=>{let{default:r="h"}=e,i=sJ(()=>e.choices.map(e=>{if(sW.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]=sM("idle"),[o,s]=sM(""),[a,l]=sM(e.expanded??!1),[c,d]=sM(),p=s$(e.theme),h=sq({theme:p,status:n});sH((e,n)=>{if(sL(e)){let e=(o||r).toLowerCase();if("h"!==e||a){let r=i.find(t=>!sW.isSeparator(t)&&t.key===e);r?(u("done"),s(e),t(r.value)):""===o?d("Please input a value"):d(`"${(0,k.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=>!sW.isSeparator(e)&&e.key===o.toLowerCase());return`${h} ${f} ${p.style.answer(e.name)}`}let m=a?i:[...i,ae],g="",A=m.map(e=>sW.isSeparator(e)?"":e.key===r?e.key.toUpperCase():e.key).join("");A=` ${p.style.defaultAnswer(A)}`,a&&(A="",g=m.map(e=>{if(sW.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=>!sW.isSeparator(e)&&e.key===o.toLowerCase());E&&(y=`${(0,k.styleText)("cyan",">>")} ${E.name}`);let _="";return c&&(_=p.style.error(c)),[`${h} ${f}${A} ${o}`,[g,y,_].filter(Boolean).join("\n")]}),ar={icon:{checked:(0,k.styleText)("green",sI.circleFilled),unchecked:sI.circle,cursor:sI.pointer,disabledChecked:(0,k.styleText)("green",sI.circleDouble),disabledUnchecked:"-"},style:{disabled:e=>(0,k.styleText)("dim",e),renderSelectedChoices:e=>e.map(e=>e.short).join(", "),description:e=>(0,k.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,k.styleText)("bold",e)} ${(0,k.styleText)("dim",t)}`).join((0,k.styleText)("dim"," • "))},i18n:{disabledError:"This option is disabled and cannot be toggled."}};function ai(e){return!sW.isSeparator(e)&&!e.disabled}function an(e){return!sW.isSeparator(e)}function au(e){return!sW.isSeparator(e)&&e.checked}function ao(e){return ai(e)?{...e,checked:!e.checked}:e}let as=sF((e,t)=>{let r,{pageSize:i=7,loop:n=!0,required:u,validate:o=()=>!0}=e,s={all:"a",invert:"i",...e.shortcuts},a=s$(ar,e.theme),{keybindings:l}=a,[c,d]=sM("idle"),p=sq({status:c,theme:a}),[h,f]=sM(e.choices.map(e=>{if(sW.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=sJ(()=>{let e=h.findIndex(an),t=h.findLastIndex(an);if(-1===e)throw new sa("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[h]),[g,A]=sM(m.first),[y,E]=sM();sH(async e=>{if(sL(e)){let e=h.filter(au),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(sR(e,l)||sP(e,l)){if(y&&E(void 0),n||sR(e,l)&&g!==m.first||sP(e,l)&&g!==m.last){let t=sR(e,l)?-1:1,r=g;do r=(r+t+h.length)%h.length;while(!an(h[r]));A(r)}}else if("space"===e.name){let e=h[g];e&&!sW.isSeparator(e)&&(e.disabled?E(a.i18n.disabledError):(E(void 0),f(h.map((e,t)=>t===g?ao(e):e))))}else if(e.name===s.all){var r;let e=h.some(e=>ai(e)&&!e.checked);f(h.map((r=e,function(e){return ai(e)?{...e,checked:r}:e})))}else if(e.name===s.invert)f(h.map(ao));else{let t;if(t=e,"1234567890".includes(t.name)){let t=Number(e.name)-1,r=-1,i=h.findIndex(e=>!sW.isSeparator(e)&&++r===t),n=h[i];n&&ai(n)&&(A(i),f(h.map((e,t)=>t===i?ao(e):e)))}}});let _=a.style.message(e.message,c),b=sY({items:h,active:g,renderItem({item:e,isActive:t}){if(sW.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(au);return[p,_,a.style.answer(a.style.renderSelectedChoices(e,h))].filter(Boolean).join(" ")}let C=[["↑↓","navigate"],["space","select"]];s.all&&C.push([s.all,"all"]),s.invert&&C.push([s.invert,"invert"]),C.push(["⏎","submit"]);let v=a.style.keysHelpTip(C),D=[[p,_].filter(Boolean).join(" "),b," ",r?a.style.description(r):"",y?a.style.error(y):"",v].filter(Boolean).join("\n").trimEnd();return`${D}\u001b[?25l`}),aa={style:{maskedText:"[input is masked]"}},al=sF((e,t)=>{let r,{validate:i=()=>!0}=e,n=s$(aa,e.theme),[u,o]=sM("idle"),[s,a]=sM(),[l,c]=sM(""),d=sq({status:u,theme:n});sH(async(e,r)=>{if("idle"===u)if(sL(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 ac=__webpack_require__("../../node_modules/.pnpm/chardet@2.1.1/node_modules/chardet/lib/index.js"),ad=__webpack_require__("../../node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/index.js");class ap extends Error{name="CreateFileError";originalError;constructor(e){super(`Failed to create temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class ah extends Error{name="LaunchEditorError";originalError;constructor(e){super(`Failed to launch editor.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class af extends Error{name="ReadFileError";originalError;constructor(e){super(`Failed to read temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class am extends Error{name="RemoveFileError";originalError;constructor(e){super(`Failed to remove temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}function ag(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}class aA{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 ah(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 ah(e))}),r.once("exit",t=>{this.lastExitStatus=t??0,e()})}catch(e){t(new ah(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,I.rmSync)(this.tempDir,{force:!0,recursive:!0}),this.tempFile="",this.tempDir=""}catch(e){throw new am(e)}}createTempFile(){try{let e=T.resolve(this.fileOptions.dir??td.tmpdir());this.tempDir=(0,I.mkdtempSync)(T.join(e,"inquirer-editor-"));let t=(0,tc.randomUUID)(),r=ag(this.fileOptions.prefix),i=ag(this.fileOptions.postfix),n=`${r}${t}${i}`;this.tempFile=T.join(this.tempDir,n);let u={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(u.mode=this.fileOptions.mode),(0,I.writeFileSync)(this.tempFile,this.text,u)}catch(e){throw new ap(e)}}editorArgs(){return[...this.editor.args,this.tempFile]}readTemporaryFile(){try{let e=(0,I.readFileSync)(this.tempFile);if(0===e.length)this.text="";else{let t=(0,ac.detect)(e)??"utf8";ad.encodingExists(t)||(t="utf8"),this.text=ad.decode(e,t)}}catch(e){throw new af(e)}}}let ay={validationFailureMode:"keep",style:{loadingMessage:()=>"Validating...",waitingMessage:e=>`Press ${e} to launch your preferred editor.`}},aE=sF((e,t)=>{let{waitForUserInput:r=!0,file:{postfix:i=e.postfix??".txt",...n}={},validate:u=()=>!0}=e,o=s$(ay,e.theme),[s,a]=sM("idle"),[l="",c]=sM(e.default),[d,p]=sM(),h=sq({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 aA(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))}}sU(e=>{r||f(e)},[]),sH((e,t)=>{"idle"===s&&sL(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]}),a_={icon:{cursor:sI.pointer},style:{disabled:e=>(0,k.styleText)("dim",`- ${e}`),searchTerm:e=>(0,k.styleText)("cyan",e),description:e=>(0,k.styleText)("cyan",e),keysHelpTip:e=>e.map(([e,t])=>`${(0,k.styleText)("bold",e)} ${(0,k.styleText)("dim",t)}`).join((0,k.styleText)("dim"," • "))}};function ab(e){return!sW.isSeparator(e)&&!e.disabled}let aC=sF((e,t)=>{let r,i,{pageSize:n=7,validate:u=()=>!0}=e,o=s$(a_,e.theme),[s,a]=sM("loading"),[l,c]=sM(""),[d,p]=sM([]),[h,f]=sM(),m=sV(!1),g=sq({status:s,theme:o}),A=sJ(()=>{let e=d.findIndex(ab);return{first:e,last:d.findLastIndex(ab)}},[d]),[y=A.first,E]=sM();sU(()=>{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(sW.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=>ab(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];sH(async(e,r)=>{if(sL(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&&(sR(e)||sP(e))){if(r.clearLine(0),sR(e)&&y!==A.first||sP(e)&&y!==A.last){let t=sR(e)?-1:1,r=y;do r=(r+t+d.length)%d.length;while(!ab(d[r]));E(r)}}else c(r.line)});let b=o.style.message(e.message,s),C=o.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),v=sY({items:d,active:y,renderItem({item:e,isActive:t}){if(sW.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??v," ",D?o.style.description(D):"",C].filter(Boolean).join("\n").trimEnd()]});var av=__webpack_require__("../../node_modules/.pnpm/run-async@4.0.6/node_modules/run-async/index.js");function aD(e){queueMicrotask(()=>{throw e})}function aF(e){try{e()}catch(e){aD(e)}}function aw(){return{closed:!0,unsubscribe(){}}}function aB(e){return e instanceof Error?e:Error(String(e))}function ax(e){"function"==typeof e?e():e?.unsubscribe()}class aS{"@@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&&ax(o))}},d={next(e){a||aF(()=>s.next?.(e))},error(e){!a&&(a=!0,s.error?aF(()=>s.error?.(e)):aD(e),l&&ax(o))},complete(){!a&&(a=!0,aF(()=>s.complete?.()),l&&ax(o))}};try{o=this.subscribeFn(d),l=!0,c.closed&&ax(o)}catch(e){d.error?.(e)}return c}[Symbol.asyncIterator](){return aI(this)[Symbol.asyncIterator]()}}let aT=new aS(e=>(e.complete?.(),aw()));function aI(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=aB(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=aB(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 aO=(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])})},ak=(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 aR(e,t,r){let i=e[t];return"function"==typeof i?av(i)(r):i}class aP 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 aL extends Error{name="TTYError";isTtyError=!0}class aN{prompts;answers={};process=aT;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 aS(e=>{if(u)return e.error?.(r),aw();if(n)return e.complete?.(),aw();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||aF(()=>t.next?.(e))},error(e){if(!n&&!u){for(let{observer:t,subscription:n}of(u=!0,r=e,i))n.closed=!0,aF(()=>t.error?.(e));i.clear()}},complete(){if(!n&&!u){for(let{observer:e,subscription:t}of(n=!0,i))t.closed=!0,aF(()=>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);aO(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*aI(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 aP(r,this.prompts);let[i,n,u]=await Promise.all([aR(e,"message",this.answers),aR(e,"default",this.answers),aR(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 sn({cause:o.reason}));let s=oH.createInterface(function(e){e.skipTTYChecks=void 0===e.skipTTYChecks||e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY)throw new aL("Prompts can not be meaningfully rendered in non-TTY environments");let r=new oz;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"),oH.cursorTo(s.output,0),s.output.end(),s.close(),r?.()},d=()=>{n(new sn({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!==ak(this.answers,e.name))return!1;let{when:t}=e;return"function"==typeof t?!!await av(t)(this.answers):!1!==t}}let aj={input:sG,select:sZ,number:s2,confirm:s6,rawlist:s5,expand:at,checkbox:as,password:al,editor:aE,search:aC};function a$(e){function t(r,i){let n=new aN(t.prompts,e);return Object.assign(n.run(r,i),{ui:n})}return t.prompts={...aj},t.registerPrompt=function(e,r){return t.prompts[e]=r,this},t.restoreDefaultPrompts=function(){t.prompts={...aj}},t}let aM=a$(),aU=aM;async function aq(){let e=function(){let e=(0,T.resolve)(__dirname,"..","skills",e6);if((0,I.existsSync)((0,T.resolve)(e,"SKILL.md")))return e;let t=(0,T.resolve)(__dirname,"..");return(0,I.existsSync)((0,T.resolve)(t,"SKILL.md"))?t:e}(),t=(0,T.resolve)(e,"SKILL.md");if(!(0,I.existsSync)(e))throw new l(`未找到随包发布的 Skill 目录: ${e}`,{error:"SKILL_INSTALL_FAILED"});if(!(0,I.existsSync)(t))throw new l(`随包发布的 Skill 缺少入口文件: ${t}`,{error:"SKILL_INSTALL_FAILED"});let r=oa(`正在同步 ${e6} Skill ...`).start();try{var i;await (i=e,_({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(`${e6} Skill 已同步完成`)}catch(e){throw r.fail(`${e6} Skill 同步失败`),e}}async function aV(){try{await aq()}catch(e){if(d(e)){tt({errorMessage:e.message,errorCode:nj(e)}),process.stderr.write(`${e.message}
45
+ `),process.exitCode=e.exitCode;return}throw e}}let aH=new Set(["latest","beta","alpha","next","stable"]);async function az(e){let t=e?.trim()||"latest";if("latest"===t){let e=oa(`正在解析 ${e3} 最新版本 ...`).start();try{let t=await nJ();return e.succeed(`最新版本:${t}`),t}catch(t){throw e.fail("解析最新版本失败"),t}}if(!aH.has(t)&&!b(t))throw new l(`不支持的目标版本: ${t}`,{error:"INVALID_TARGET_VERSION",message:"--target-version 仅支持 semver 版本号或 latest / beta / alpha / next / stable"});return t}async function aG(e){var t,r,i;let n=await az(e.targetVersion),u=`${e3}@${n}`,o=function(e){let t=nq({input:e});if(void 0!==e){if(!t)throw new l(`不支持的包管理器: ${e}`,{error:"INVALID_PACKAGE_MANAGER",message:`--package-manager 只能取 ${n$.join(" / ")}`});return t}let r=nq({userAgent:process.env.npm_config_user_agent});if(!r)throw new l("当前环境无法自动识别全局安装所使用的包管理器",{error:"INVALID_PACKAGE_MANAGER",message:`请显式传入 --package-manager,支持 ${n$.join(" / ")}`});return r}(e.packageManager);if("0.5.1"===n)return(oa("dymg 已是目标版本(0.5.1),跳过 CLI 安装").info(),e.skipSkills)?void oa("已跳过 Skill 同步。如需同步,请执行 dymg skills install").info():void await aq();let s=oa(`正在使用 ${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),_({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 oa("已跳过 Skill 同步。如需同步,请执行 dymg skills install").info();let a=oa("正在启动更新后的 CLI 同步 Skill ...").start();try{await (i=u,_({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 aW(e){try{await aG(e)}catch(e){if(d(e)){tt({errorMessage:e.message,errorCode:nj(e)}),process.stderr.write(`${e.message}
46
+ `),process.exitCode=e.exitCode;return}throw e}}async function aJ(e){return(await aU([{type:"list",name:"action",message:`发现新版本 ${e},当前版本 0.5.1。是否现在更新并同步 Skill?`,choices:[{name:"现在更新",value:"update"},{name:"暂不更新",value:"skip"}],default:"update"}])).action}async function aY(e,t){let r=oa(`正在检查 ${e3} 更新,当前版本:0.5.1`).start();try{let e=await nY();if(r.succeed("更新检查完成"),!e.hasUpdate){await nK(e),oa(`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)||!nq({userAgent:process.env.npm_config_user_agent})){var i;i=e.latestVersion,process.stdout.write(`${nz(i).join("\n")}
47
47
  `),await nK(e,{notified:!0});return}let n=await aJ(e.latestVersion);if(await nK(e,{notified:!0}),"skip"===n)return void oa("已跳过更新,可执行 dymg update 完成 CLI 和 Skill 同步").info();await aG({targetVersion:e.latestVersion})}catch(t){if(r.isSpinning&&r.fail("检查更新失败"),d(t)){tt({errorMessage:t.message,errorCode:nj(t)}),process.stderr.write(`${t.message}
48
48
  `),process.exitCode=t.exitCode;return}let e=t instanceof Error?t.message:String(t);tt({errorMessage:e,errorCode:nj(t)}),process.stderr.write(`检查更新失败:${e}
49
- `),process.exitCode=1}}var aK=((eo={})[eo.Todo=0]="Todo",eo[eo.Overtime=1]="Overtime",eo[eo.Dealt=2]="Dealt",eo[eo.Solving=3]="Solving",eo[eo.NoNeed=100]="NoNeed",eo),aX=((es={})[es.CreateTime=1]="CreateTime",es[es.DdlTime=2]="DdlTime",es);let aQ=["feedbackId","openId","content","createTime","dealtStatus","dealtAction","dealtComment","dealtTime","dealtDdl","hasReply","isImportant","isRead","appVersion","microAppVersion","libraryVersion","platform","device","deviceId","osVersion","labelName","label1Name","isRefund","imageUrlList","logDownloadUrl"],aZ=["3","4"];function a1(e,t){for(let r of(ru(e,t),rh(e)??[]))ra(r,t)}var a0=((ea={})[ea.NONE=0]="NONE",ea[ea.UNRESOLVED=1]="UNRESOLVED",ea[ea.RESOLVED=2]="RESOLVED",ea);let a2=["ticketId","openId","content","createTime","updateTime","deadlineTime","resolveDuration","auditStatus","auditStatusText","minorRefundStatus","minorRefundStatusText","devReplyText","userHasMoreRefund","ageRange","orderList","imageList","rejectReasonList","logUrl"];var a3=((el={})[el.ActivateDate=1]="ActivateDate",el[el.FirstChannel=2]="FirstChannel",el),a6=((ec={})[ec.Ad=1]="Ad",ec[ec.Star=2]="Star",ec[ec.Pop=3]="Pop",ec[ec.Nature=4]="Nature",ec),a4=((ed={})[ed.RealTime=1]="RealTime",ed[ed.Offline=2]="Offline",ed),a8=((ep={})[ep.ActivateNewUserNum=1]="ActivateNewUserNum",ep[ep.AdActivateConsumeAverage=2]="AdActivateConsumeAverage",ep[ep.AdConsumeFirstDay=3]="AdConsumeFirstDay",ep[ep.PopConsumeCumulative=4]="PopConsumeCumulative",ep[ep.PopConsumeCumulativeAverage=5]="PopConsumeCumulativeAverage",ep[ep.AdIncomeUserNumDaily=6]="AdIncomeUserNumDaily",ep[ep.ECPMDaily=7]="ECPMDaily",ep[ep.AdShowNumDailyAverage=8]="AdShowNumDailyAverage",ep[ep.AdArpuDaily=9]="AdArpuDaily",ep[ep.AdIncomeCumulative=10]="AdIncomeCumulative",ep[ep.AdLTV=11]="AdLTV",ep[ep.PayUserNumDaily=12]="PayUserNumDaily",ep[ep.PayUserNumCumulative=13]="PayUserNumCumulative",ep[ep.PayNumDailyAverage=14]="PayNumDailyAverage",ep[ep.PayArpuDaily=15]="PayArpuDaily",ep[ep.PayArppuDaily=16]="PayArppuDaily",ep[ep.PayCumulative=17]="PayCumulative",ep[ep.PayLTV=18]="PayLTV",ep[ep.TotalArpuDaily=19]="TotalArpuDaily",ep[ep.TotalIncomeCumulative=20]="TotalIncomeCumulative",ep[ep.TotalLTV=21]="TotalLTV",ep[ep.TotalROI=22]="TotalROI",ep[ep.RetainUserNumDaily=23]="RetainUserNumDaily",ep[ep.RetainUserRateDaily=24]="RetainUserRateDaily",ep[ep.OnlineTimeDailyAverage=25]="OnlineTimeDailyAverage",ep[ep.LaunchNumDailyAverage=26]="LaunchNumDailyAverage",ep[ep.AdPenetrationRateDaily=27]="AdPenetrationRateDaily",ep[ep.PayPenetrationRateDaily=28]="PayPenetrationRateDaily",ep[ep.PayPenetrationRateCumulative=29]="PayPenetrationRateCumulative",ep[ep.TimeToFirstPayAverage=30]="TimeToFirstPayAverage",ep),a9=((eh={})[eh.Ad=1]="Ad",eh[eh.StarLive=2]="StarLive",eh[eh.StarVideo=3]="StarVideo",eh[eh.PopLive=4]="PopLive",eh[eh.PopVideo=5]="PopVideo",eh[eh.NatureVideo=6]="NatureVideo",eh[eh.NatureSearch=7]="NatureSearch",eh[eh.NatureHomePageSidebar=8]="NatureHomePageSidebar",eh[eh.NaturePersonSidebar=9]="NaturePersonSidebar",eh[eh.NaturePersonOther=10]="NaturePersonOther",eh[eh.NatureIM=11]="NatureIM",eh[eh.NatureGameCenter=12]="NatureGameCenter",eh[eh.NatureCoinGameCenter=13]="NatureCoinGameCenter",eh[eh.NatureFeedPlay=14]="NatureFeedPlay",eh[eh.NatureFeedCard=15]="NatureFeedCard",eh[eh.NatureDesktop=16]="NatureDesktop",eh[eh.NatureInMp=17]="NatureInMp",eh[eh.NatureScan=18]="NatureScan",eh[eh.NatureGameCircle=19]="NatureGameCircle",eh[eh.NatureLive=20]="NatureLive",eh[eh.NatureOther=21]="NatureOther",eh);let a7=["1","2"],a5=["1","2","3","4","5","6","7","8","9","10","11","12","13","14","30","45","60","75","90","120","150","180"],le=[...Array.from({length:90},(e,t)=>String(t+1)),"120","150","180"],lt=new Set([a8.ActivateNewUserNum,a8.AdActivateConsumeAverage,a8.AdConsumeFirstDay]),lr=["metric","metricName","lifeTime","value"],li={[a6.Ad]:[a9.Ad],[a6.Star]:[a9.StarLive,a9.StarVideo],[a6.Pop]:[a9.PopLive,a9.PopVideo],[a6.Nature]:[a9.NatureVideo,a9.NatureSearch,a9.NatureHomePageSidebar,a9.NaturePersonSidebar,a9.NaturePersonOther,a9.NatureIM,a9.NatureGameCenter,a9.NatureCoinGameCenter,a9.NatureFeedPlay,a9.NatureFeedCard,a9.NatureDesktop,a9.NatureInMp,a9.NatureScan,a9.NatureGameCircle,a9.NatureLive,a9.NatureOther]},ln=`
49
+ `),process.exitCode=1}}var aK=((eo={})[eo.Todo=0]="Todo",eo[eo.Overtime=1]="Overtime",eo[eo.Dealt=2]="Dealt",eo[eo.Solving=3]="Solving",eo[eo.NoNeed=100]="NoNeed",eo),aX=((es={})[es.CreateTime=1]="CreateTime",es[es.DdlTime=2]="DdlTime",es);let aQ=["feedbackId","openId","content","createTime","dealtStatus","dealtAction","dealtComment","dealtTime","dealtDdl","hasReply","isImportant","isRead","appVersion","microAppVersion","libraryVersion","platform","device","deviceId","osVersion","labelName","label1Name","isRefund","imageUrlList","logDownloadUrl"],aZ=["3","4"];function a1(e,t){for(let r of(ru(e,t),rh(e)??[]))ra(r,t)}var a2=((ea={})[ea.NONE=0]="NONE",ea[ea.UNRESOLVED=1]="UNRESOLVED",ea[ea.RESOLVED=2]="RESOLVED",ea);let a0=["ticketId","openId","content","createTime","updateTime","deadlineTime","resolveDuration","auditStatus","auditStatusText","minorRefundStatus","minorRefundStatusText","devReplyText","userHasMoreRefund","ageRange","orderList","imageList","rejectReasonList","logUrl"];var a3=((el={})[el.ActivateDate=1]="ActivateDate",el[el.FirstChannel=2]="FirstChannel",el),a6=((ec={})[ec.Ad=1]="Ad",ec[ec.Star=2]="Star",ec[ec.Pop=3]="Pop",ec[ec.Nature=4]="Nature",ec),a4=((ed={})[ed.RealTime=1]="RealTime",ed[ed.Offline=2]="Offline",ed),a8=((ep={})[ep.ActivateNewUserNum=1]="ActivateNewUserNum",ep[ep.AdActivateConsumeAverage=2]="AdActivateConsumeAverage",ep[ep.AdConsumeFirstDay=3]="AdConsumeFirstDay",ep[ep.PopConsumeCumulative=4]="PopConsumeCumulative",ep[ep.PopConsumeCumulativeAverage=5]="PopConsumeCumulativeAverage",ep[ep.AdIncomeUserNumDaily=6]="AdIncomeUserNumDaily",ep[ep.ECPMDaily=7]="ECPMDaily",ep[ep.AdShowNumDailyAverage=8]="AdShowNumDailyAverage",ep[ep.AdArpuDaily=9]="AdArpuDaily",ep[ep.AdIncomeCumulative=10]="AdIncomeCumulative",ep[ep.AdLTV=11]="AdLTV",ep[ep.PayUserNumDaily=12]="PayUserNumDaily",ep[ep.PayUserNumCumulative=13]="PayUserNumCumulative",ep[ep.PayNumDailyAverage=14]="PayNumDailyAverage",ep[ep.PayArpuDaily=15]="PayArpuDaily",ep[ep.PayArppuDaily=16]="PayArppuDaily",ep[ep.PayCumulative=17]="PayCumulative",ep[ep.PayLTV=18]="PayLTV",ep[ep.TotalArpuDaily=19]="TotalArpuDaily",ep[ep.TotalIncomeCumulative=20]="TotalIncomeCumulative",ep[ep.TotalLTV=21]="TotalLTV",ep[ep.TotalROI=22]="TotalROI",ep[ep.RetainUserNumDaily=23]="RetainUserNumDaily",ep[ep.RetainUserRateDaily=24]="RetainUserRateDaily",ep[ep.OnlineTimeDailyAverage=25]="OnlineTimeDailyAverage",ep[ep.LaunchNumDailyAverage=26]="LaunchNumDailyAverage",ep[ep.AdPenetrationRateDaily=27]="AdPenetrationRateDaily",ep[ep.PayPenetrationRateDaily=28]="PayPenetrationRateDaily",ep[ep.PayPenetrationRateCumulative=29]="PayPenetrationRateCumulative",ep[ep.TimeToFirstPayAverage=30]="TimeToFirstPayAverage",ep),a9=((eh={})[eh.Ad=1]="Ad",eh[eh.StarLive=2]="StarLive",eh[eh.StarVideo=3]="StarVideo",eh[eh.PopLive=4]="PopLive",eh[eh.PopVideo=5]="PopVideo",eh[eh.NatureVideo=6]="NatureVideo",eh[eh.NatureSearch=7]="NatureSearch",eh[eh.NatureHomePageSidebar=8]="NatureHomePageSidebar",eh[eh.NaturePersonSidebar=9]="NaturePersonSidebar",eh[eh.NaturePersonOther=10]="NaturePersonOther",eh[eh.NatureIM=11]="NatureIM",eh[eh.NatureGameCenter=12]="NatureGameCenter",eh[eh.NatureCoinGameCenter=13]="NatureCoinGameCenter",eh[eh.NatureFeedPlay=14]="NatureFeedPlay",eh[eh.NatureFeedCard=15]="NatureFeedCard",eh[eh.NatureDesktop=16]="NatureDesktop",eh[eh.NatureInMp=17]="NatureInMp",eh[eh.NatureScan=18]="NatureScan",eh[eh.NatureGameCircle=19]="NatureGameCircle",eh[eh.NatureLive=20]="NatureLive",eh[eh.NatureOther=21]="NatureOther",eh);let a7=["1","2"],a5=["1","2","3","4","5","6","7","8","9","10","11","12","13","14","30","45","60","75","90","120","150","180"],le=[...Array.from({length:90},(e,t)=>String(t+1)),"120","150","180"],lt=new Set([a8.ActivateNewUserNum,a8.AdActivateConsumeAverage,a8.AdConsumeFirstDay]),lr=["metric","metricName","lifeTime","value"],li={[a6.Ad]:[a9.Ad],[a6.Star]:[a9.StarLive,a9.StarVideo],[a6.Pop]:[a9.PopLive,a9.PopVideo],[a6.Nature]:[a9.NatureVideo,a9.NatureSearch,a9.NatureHomePageSidebar,a9.NaturePersonSidebar,a9.NaturePersonOther,a9.NatureIM,a9.NatureGameCenter,a9.NatureCoinGameCenter,a9.NatureFeedPlay,a9.NatureFeedCard,a9.NatureDesktop,a9.NatureInMp,a9.NatureScan,a9.NatureGameCircle,a9.NatureLive,a9.NatureOther]},ln=`
50
50
  参数说明:
51
51
  - --dimension / --metric / --first-channel / --second-channel 均支持逗号分隔多值
52
52
  - --life-time 可重复传入,格式为 <指标枚举>:<生命周期天数列表>,例如 --life-time 11:7,14,30
@@ -125,7 +125,7 @@ ${t}`,uy=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),uE=Objec
125
125
 
126
126
  示例:
127
127
  $ 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
128
- $ 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 lu(e,t=[]){return[...t,e]}function lo(e){return e===a4.RealTime?"1,2":"1,3,7"}var ls=((ef={})[ef.HotGame=1]="HotGame",ef[ef.BestSeller=2]="BestSeller",ef[ef.NewGame=3]="NewGame",ef[ef.Pop=4]="Pop",ef),la=((em={})[em.IAA=1]="IAA",em[em.IAP=2]="IAP",em[em.IAAP=3]="IAAP",em);let ll=["elementId","elementName","elementType","hotValue","dataStatus","hotspotId","videoId","elementTags","description","heatTrend"],lc=["title","hotValue","topics","hotInsights","jumpUrl","contentId","coverUrl","playUrl","contentTags","gamificationCategories","gamificationMechanics","genderDistribution","ageDistribution","commentSummary","topComments","dataStatus"],ld=["topicId","topicName","parentTopicId","parentTopicName","dataStatus","topicOverview","marketOpportunitySummary","gamificationCategories","gamificationMechanics","genderDistribution","ageDistribution","audiencePreferences","contentPreferences","interactionPreferences","relatedGames","recentHotspots","topVideos","trend7D","trend30D","trend90D"],lp=["all","image","topic","interaction"],lh=[{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 lf(e,t=String){return e?.map(t).join("|")}var lm=((eg={})[eg.All=1]="All",eg[eg.Douyin=2]="Douyin",eg[eg.DouyinLite=3]="DouyinLite",eg[eg.Toutiao=4]="Toutiao",eg[eg.ToutiaoLite=5]="ToutiaoLite",eg[eg.Fanqie=6]="Fanqie",eg[eg.FanqieChangTing=7]="FanqieChangTing",eg[eg.Hotsoon=8]="Hotsoon",eg[eg.Ppx=9]="Ppx",eg),lg=((eA={})[eA.Debug=1]="Debug",eA[eA.Info=2]="Info",eA[eA.Warn=3]="Warn",eA[eA.Error=4]="Error",eA[eA.Fatal=5]="Fatal",eA),lA=((ey={})[ey.All=1]="All",ey[ey.Android=2]="Android",ey[ey.IOS=3]="IOS",ey[ey.OpenHarmony=4]="OpenHarmony",ey[ey.Windows=5]="Windows",ey),ly=((eE={})[eE.All=1]="All",eE[eE.High=2]="High",eE[eE.Mid=3]="Mid",eE[eE.Low=4]="Low",eE),lE=((e_={})[e_.All=1]="All",e_[e_.Android=2]="Android",e_[e_.IOS=3]="IOS",e_[e_.OpenHarmony=4]="OpenHarmony",e_[e_.Windows=5]="Windows",e_),l_=((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),lb=((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),lC=((ev={})[ev.All=1]="All",ev[ev.Required=2]="Required",ev[ev.NotRequired=3]="NotRequired",ev),lv=((eD={})[eD.Trend=1]="Trend",eD[eD.SceneConversion=2]="SceneConversion",eD[eD.LaunchDurationDistribution=3]="LaunchDurationDistribution",eD[eD.LaunchLossDistribution=4]="LaunchLossDistribution",eD[eD.WasmSplit=5]="WasmSplit",eD);let lD={[lm.Douyin]:"1128",[lm.DouyinLite]:"2329",[lm.Toutiao]:"13",[lm.ToutiaoLite]:"35",[lm.Fanqie]:"1967",[lm.FanqieChangTing]:"3040",[lm.Hotsoon]:"8663"},lF=Object.keys(lD),lw=Object.values(lD),lB=[l_.Android,l_.IOS,l_.OpenHarmony].map(String),lx=["group","genreName","engine","degradedIndicatorCount","section","indicatorName","metric","os","actualValue","standardValue","delta","unit","suggestion"],lS=["metric","metricName","name","sceneId","aggregation","direction","unit","date","value","sampleCount"],lT=["appId","host","os","appVersion","gameVersion","jssdkVersion","versionType","openId","traceId","logLevel","timestamp","msg"];function lI(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 lO(e){return(e??[]).flatMap(e=>(e.points??[]).map(t=>({metric:e.metric,metricName:rv(lb,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 lk(e){rc({startDate:e.startDate,endDate:e.endDate,maxLookbackDays:ob,label:"性能数据"}),ri(e.host,"--host",lF),ri(e.os,"--os",lB),ri(e.deviceLevel,"--device-level",rb(ly)),rn(e.metrics,"--metrics",rb(lb))}function lR(e){return{startDate:e.startDate,endDate:e.endDate,hostAid:lD[rC(e.host,lm)]??"",os:rC(e.os,l_),mpVersion:e.mpVersion,deviceLevel:rC(e.deviceLevel,ly)}}var lP=((eF={})[eF.Invalid=0]="Invalid",eF[eF.CpaDauV2=1]="CpaDauV2",eF[eF.CpaDauV3=2]="CpaDauV3",eF[eF.CpaReservation=3]="CpaReservation",eF[eF.CpaActivate=4]="CpaActivate",eF[eF.CpaAndroidDownload=5]="CpaAndroidDownload",eF[eF.CpmFeedVv=6]="CpmFeedVv",eF[eF.Cps=7]="Cps",eF[eF.Fix=8]="Fix",eF[eF.CpsV2=9]="CpsV2",eF[eF.Revenues=10]="Revenues",eF[eF.AuthorPurchase=11]="AuthorPurchase",eF[eF.CpsRevenues=12]="CpsRevenues",eF[eF.CpaReserveAndDownload=13]="CpaReserveAndDownload",eF[eF.CpaMultiReserve=14]="CpaMultiReserve",eF[eF.CpmUvAll=15]="CpmUvAll",eF[eF.Ocpm=16]="Ocpm",eF[eF.OcpmUvAll=17]="OcpmUvAll",eF[eF.CpmFeedVvMultiOs=18]="CpmFeedVvMultiOs",eF[eF.CpmUvAllMultiOs=19]="CpmUvAllMultiOs",eF[eF.CpaActivateMultiOs=20]="CpaActivateMultiOs",eF[eF.CpaReserveAndDownloadMultiOs=21]="CpaReserveAndDownloadMultiOs",eF[eF.CpaDauV2MultiOs=22]="CpaDauV2MultiOs",eF[eF.CpaDauV3MultiOs=23]="CpaDauV3MultiOs",eF[eF.CpaUnionAndroidDownload=24]="CpaUnionAndroidDownload",eF[eF.CpaMixedActivate=25]="CpaMixedActivate",eF[eF.CpsLongPeriod=26]="CpsLongPeriod",eF[eF.CpsMicroGame2022=27]="CpsMicroGame2022",eF[eF.CpaDauV2AndCps=28]="CpaDauV2AndCps",eF[eF.CpaDauV2AndCpsMicroGame2022=29]="CpaDauV2AndCpsMicroGame2022",eF[eF.CpsV3=30]="CpsV3",eF[eF.MaxSize=31]="MaxSize",eF),lL=((ew={})[ew.Video=1]="Video",ew[ew.Live=2]="Live",ew[ew.All=100]="All",ew),lN=((eB={})[eB.MicroGame=0]="MicroGame",eB[eB.MicroTerminal=1]="MicroTerminal",eB[eB.All=100]="All",eB),lj=((ex={})[ex.Min=0]="Min",ex[ex.Pending=1]="Pending",ex[ex.Passed=2]="Passed",ex[ex.Rejected=3]="Rejected",ex[ex.Cancelled=4]="Cancelled",ex[ex.ToStart=5]="ToStart",ex[ex.Paused=6]="Paused",ex[ex.Processing=7]="Processing",ex[ex.Completed=8]="Completed",ex[ex.Max=10]="Max",ex);let l$=["0","1","2"],lM=[lL.Video,lL.Live,lL.All].map(String),lU=[lP.CpaDauV2,lP.CpmFeedVv,lP.Fix,lP.CpaDauV2MultiOs,lP.CpsMicroGame2022,lP.CpaDauV2AndCps,lP.CpaDauV2AndCpsMicroGame2022,lP.CpsV3].map(String),lq=["mpId","mpName","mpCategory","taskId","taskName","taskType","factionId","factionName","contentType","bidType","effectiveTime","dayCnt","metrics","extraIncentive","dataUpdateTime","readyDate","readyTs"],lV=["1","2"],lH=["1","2"];var lz=((eS={})[eS.Video=1]="Video",eS[eS.Live=2]="Live",eS[eS.All=100]="All",eS),lG=((eT={})[eT.TotalConsumptionAmount=1]="TotalConsumptionAmount",eT[eT.TotalRevenueAmount=2]="TotalRevenueAmount",eT[eT.NewActivationCount=3]="NewActivationCount",eT[eT.ComponentClickCount=4]="ComponentClickCount",eT);let lW=["date","mediaType","totalConsumptionAmount","totalRevenueAmount","newActivationCount","firstActiveCount","componentExposureCount","componentClickCount","componentClickThroughRate","conversionBillingConsumptionAmount","revenueBillingConsumptionAmount","revenueUserCount","iaaRevenueAmount","iapRevenueAmount"],lJ=rb(lG),lY=["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"],lK=["date","taskId","taskType","expense","totalIncome","cpaExpense","cpsExpense","adIncomeSettle","adIncomeLongTail","orderIncomeSettle","orderIncomeLongTail","newRegisterCnt","videoPost","videoPostUcnt","videoPlaySettle","videoPlayLongTail","liveRoomCnt","liveRoomUcnt","liveViewCnt","liveViewUcnt","frozenAmount","breakdownAmount","yesterdayDataReady"],lX=[lj.Pending,lj.Passed,lj.Rejected,lj.Cancelled,lj.ToStart,lj.Paused,lj.Processing,lj.Completed].map(String);var lQ=((eI={})[eI.Banner=1]="Banner",eI[eI.RewardedVideo=2]="RewardedVideo",eI[eI.Interstitial=3]="Interstitial",eI[eI.ECommerce=4]="ECommerce",eI),lZ=((eO={})[eO.All=1]="All",eO[eO.Douyin=2]="Douyin",eO[eO.DouyinLite=3]="DouyinLite",eO[eO.Toutiao=4]="Toutiao",eO[eO.ToutiaoLite=5]="ToutiaoLite",eO[eO.Fanqie=6]="Fanqie",eO[eO.FanqieChangTing=7]="FanqieChangTing",eO[eO.Hotsoon=8]="Hotsoon",eO[eO.Ppx=9]="Ppx",eO),l1=((ek={})[ek.All=1]="All",ek[ek.Android=2]="Android",ek[ek.IOS=3]="IOS",ek[ek.OpenHarmony=4]="OpenHarmony",ek[ek.Windows=5]="Windows",ek),l0=((eR={})[eR.Ad=1]="Ad",eR[eR.Star=2]="Star",eR[eR.Publisher=3]="Publisher",eR[eR.Natural=4]="Natural",eR),l2=((eP={})[eP.Banner=1]="Banner",eP[eP.RewardedVideo=2]="RewardedVideo",eP[eP.Interstitial=3]="Interstitial",eP[eP.ECommerce=4]="ECommerce",eP),l3=((eL={})[eL.All=1]="All",eL[eL.Douyin=2]="Douyin",eL[eL.DouyinLite=3]="DouyinLite",eL[eL.Toutiao=4]="Toutiao",eL[eL.ToutiaoLite=5]="ToutiaoLite",eL[eL.Fanqie=6]="Fanqie",eL[eL.FanqieChangTing=7]="FanqieChangTing",eL[eL.Hotsoon=8]="Hotsoon",eL[eL.Ppx=9]="Ppx",eL),l6=((eN={})[eN.All=1]="All",eN[eN.Android=2]="Android",eN[eN.IOS=3]="IOS",eN[eN.OpenHarmony=4]="OpenHarmony",eN[eN.Windows=5]="Windows",eN),l4=((ej={})[ej.Ad=1]="Ad",ej[ej.Star=2]="Star",ej[ej.Publisher=3]="Publisher",ej[ej.Natural=4]="Natural",ej);let l8=["recordType","date","requestCount","showCount","clickCount","clickRate","ecpm","incomeAfterShare","incomeBeforeShare"],l9=["date","ritId","ritName","hostName","requestCount","showCount","clickCount","clickRate","ecpm","incomeAfterShare","incomeBeforeShare"];var l7=((e$={})[e$.AD=1]="AD",e$[e$.Star=2]="Star",e$[e$.Pop=3]="Pop",e$[e$.Nature=4]="Nature",e$),l5=((eM={})[eM.Microgame=1]="Microgame",eM[eM.App=2]="App",eM),ce=((eU={})[eU.Cash=1]="Cash",eU[eU.CommonGood=2]="CommonGood",eU),ct=((eq={})[eq.CNY=1]="CNY",eq[eq.Diamond=2]="Diamond",eq),cr=((eV={})[eV.AD=1]="AD",eV[eV.Star=2]="Star",eV[eV.Pop=3]="Pop",eV[eV.Nature=4]="Nature",eV),ci=((eH={})[eH.Microgame=1]="Microgame",eH[eH.App=2]="App",eH);let cn=["ios","android","open_harmony","windows"],cu=["recordType","date","payPerson","payTimes","arppu","payMoney","payMoneyAfterShare","payMoneyAfterReduceShare","refundFee","refundFeeBeforeShare","refundFeeAfterShare","payMoneyAfterShareDataReady","payMoneyAfterReduceShareDataReady"],co=["payTime","transactionNo","merchantNo","openId","payStatus","changeType","goodType","orderType","activateType","amount","rechargeAmount","isOpenPlatformRefund","refundFee","refundFeeBeforeShare","refundFeeAfterShare","refundRemark"],cs=[10,11];function ca(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 cl(e){let t,r,i,n=await (t={X_Tt_Appid:e},r=nZ.genBaseURL("/platform_openapi/microgame/v1/payment/query_permission"),i={X_Tt_Appid:t.X_Tt_Appid,X_Tt_Userid:t.X_Tt_Userid},nZ.request({url:r,method:"GET",headers:i},void 0));return eY(n),{...n,data:n.data?{...n.data,callbackToken:n.data.callbackToken?"[REDACTED]":void 0}:void 0}}async function cc(e){return Promise.all(cs.map(async t=>{var r;let i,n,u,o=await (r={X_Tt_Appid:e,scene:t},i=nZ.genBaseURL("/platform_openapi/microgame/v1/payment/query_protocol_sign_status"),n={scene:r.scene},u={X_Tt_Appid:r.X_Tt_Appid},nZ.request({url:i,method:"GET",params:n,headers:u},void 0));return eY(o),{response:o,scene:t}}))}function cd(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 cp=new Set(["auth","check-update","skills","update"]);async function ch(e){await nN(e).catch(()=>void 0)}function cf(){process.exit(130)}async function cm(e){var t,r,i,n,u,o,s,a;let c,d,p,h,f,m,g,A,y;ns=new e0({middlewares:[tn,...ti,tu,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:()=>tr()?.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:ne,missingTokenErrorFactory:()=>new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前命令需要先登录,请先执行 ${e8}`})})]}),na=new e0({middlewares:[tn,...ti]});let E=e.slice(2),_=Date.now(),b=(((t=c=new $).addOption(new P("--caller <agent>","调用方 Agent").choices(nb).default("unknown")),t).name("dymg").description("抖音小游戏 CLI").version("0.5.0").configureHelp({showGlobalOptions:!0}).showHelpAfterError("(可使用 --help 查看命令说明)").showSuggestionAfterError(!0).addHelpText("after",`
128
+ $ 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 lu(e,t=[]){return[...t,e]}function lo(e){return e===a4.RealTime?"1,2":"1,3,7"}var ls=((ef={})[ef.HotGame=1]="HotGame",ef[ef.BestSeller=2]="BestSeller",ef[ef.NewGame=3]="NewGame",ef[ef.Pop=4]="Pop",ef),la=((em={})[em.IAA=1]="IAA",em[em.IAP=2]="IAP",em[em.IAAP=3]="IAAP",em);let ll=["elementId","elementName","elementType","hotValue","dataStatus","hotspotId","videoId","elementTags","description","heatTrend"],lc=["title","hotValue","topics","hotInsights","jumpUrl","contentId","coverUrl","playUrl","contentTags","gamificationCategories","gamificationMechanics","genderDistribution","ageDistribution","commentSummary","topComments","dataStatus"],ld=["topicId","topicName","parentTopicId","parentTopicName","dataStatus","topicOverview","marketOpportunitySummary","gamificationCategories","gamificationMechanics","genderDistribution","ageDistribution","audiencePreferences","contentPreferences","interactionPreferences","relatedGames","recentHotspots","topVideos","trend7D","trend30D","trend90D"],lp=["all","image","topic","interaction"],lh=[{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 lf(e,t=String){return e?.map(t).join("|")}var lm=((eg={})[eg.All=1]="All",eg[eg.Douyin=2]="Douyin",eg[eg.DouyinLite=3]="DouyinLite",eg[eg.Toutiao=4]="Toutiao",eg[eg.ToutiaoLite=5]="ToutiaoLite",eg[eg.Fanqie=6]="Fanqie",eg[eg.FanqieChangTing=7]="FanqieChangTing",eg[eg.Hotsoon=8]="Hotsoon",eg[eg.Ppx=9]="Ppx",eg),lg=((eA={})[eA.Debug=1]="Debug",eA[eA.Info=2]="Info",eA[eA.Warn=3]="Warn",eA[eA.Error=4]="Error",eA[eA.Fatal=5]="Fatal",eA),lA=((ey={})[ey.All=1]="All",ey[ey.Android=2]="Android",ey[ey.IOS=3]="IOS",ey[ey.OpenHarmony=4]="OpenHarmony",ey[ey.Windows=5]="Windows",ey),ly=((eE={})[eE.All=1]="All",eE[eE.High=2]="High",eE[eE.Mid=3]="Mid",eE[eE.Low=4]="Low",eE),lE=((e_={})[e_.All=1]="All",e_[e_.Android=2]="Android",e_[e_.IOS=3]="IOS",e_[e_.OpenHarmony=4]="OpenHarmony",e_[e_.Windows=5]="Windows",e_),l_=((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),lb=((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),lC=((ev={})[ev.All=1]="All",ev[ev.Required=2]="Required",ev[ev.NotRequired=3]="NotRequired",ev),lv=((eD={})[eD.Trend=1]="Trend",eD[eD.SceneConversion=2]="SceneConversion",eD[eD.LaunchDurationDistribution=3]="LaunchDurationDistribution",eD[eD.LaunchLossDistribution=4]="LaunchLossDistribution",eD[eD.WasmSplit=5]="WasmSplit",eD);let lD={[lm.Douyin]:"1128",[lm.DouyinLite]:"2329",[lm.Toutiao]:"13",[lm.ToutiaoLite]:"35",[lm.Fanqie]:"1967",[lm.FanqieChangTing]:"3040",[lm.Hotsoon]:"8663"},lF=Object.keys(lD),lw=Object.values(lD),lB=[l_.Android,l_.IOS,l_.OpenHarmony].map(String),lx=["group","genreName","engine","degradedIndicatorCount","section","indicatorName","metric","os","actualValue","standardValue","delta","unit","suggestion"],lS=["metric","metricName","name","sceneId","aggregation","direction","unit","date","value","sampleCount"],lT=["appId","host","os","appVersion","gameVersion","jssdkVersion","versionType","openId","traceId","logLevel","timestamp","msg"];function lI(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 lO(e){return(e??[]).flatMap(e=>(e.points??[]).map(t=>({metric:e.metric,metricName:rv(lb,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 lk(e){rc({startDate:e.startDate,endDate:e.endDate,maxLookbackDays:ob,label:"性能数据"}),ri(e.host,"--host",lF),ri(e.os,"--os",lB),ri(e.deviceLevel,"--device-level",rb(ly)),rn(e.metrics,"--metrics",rb(lb))}function lR(e){return{startDate:e.startDate,endDate:e.endDate,hostAid:lD[rC(e.host,lm)]??"",os:rC(e.os,l_),mpVersion:e.mpVersion,deviceLevel:rC(e.deviceLevel,ly)}}var lP=((eF={})[eF.Invalid=0]="Invalid",eF[eF.CpaDauV2=1]="CpaDauV2",eF[eF.CpaDauV3=2]="CpaDauV3",eF[eF.CpaReservation=3]="CpaReservation",eF[eF.CpaActivate=4]="CpaActivate",eF[eF.CpaAndroidDownload=5]="CpaAndroidDownload",eF[eF.CpmFeedVv=6]="CpmFeedVv",eF[eF.Cps=7]="Cps",eF[eF.Fix=8]="Fix",eF[eF.CpsV2=9]="CpsV2",eF[eF.Revenues=10]="Revenues",eF[eF.AuthorPurchase=11]="AuthorPurchase",eF[eF.CpsRevenues=12]="CpsRevenues",eF[eF.CpaReserveAndDownload=13]="CpaReserveAndDownload",eF[eF.CpaMultiReserve=14]="CpaMultiReserve",eF[eF.CpmUvAll=15]="CpmUvAll",eF[eF.Ocpm=16]="Ocpm",eF[eF.OcpmUvAll=17]="OcpmUvAll",eF[eF.CpmFeedVvMultiOs=18]="CpmFeedVvMultiOs",eF[eF.CpmUvAllMultiOs=19]="CpmUvAllMultiOs",eF[eF.CpaActivateMultiOs=20]="CpaActivateMultiOs",eF[eF.CpaReserveAndDownloadMultiOs=21]="CpaReserveAndDownloadMultiOs",eF[eF.CpaDauV2MultiOs=22]="CpaDauV2MultiOs",eF[eF.CpaDauV3MultiOs=23]="CpaDauV3MultiOs",eF[eF.CpaUnionAndroidDownload=24]="CpaUnionAndroidDownload",eF[eF.CpaMixedActivate=25]="CpaMixedActivate",eF[eF.CpsLongPeriod=26]="CpsLongPeriod",eF[eF.CpsMicroGame2022=27]="CpsMicroGame2022",eF[eF.CpaDauV2AndCps=28]="CpaDauV2AndCps",eF[eF.CpaDauV2AndCpsMicroGame2022=29]="CpaDauV2AndCpsMicroGame2022",eF[eF.CpsV3=30]="CpsV3",eF[eF.MaxSize=31]="MaxSize",eF),lL=((ew={})[ew.Video=1]="Video",ew[ew.Live=2]="Live",ew[ew.All=100]="All",ew),lN=((eB={})[eB.MicroGame=0]="MicroGame",eB[eB.MicroTerminal=1]="MicroTerminal",eB[eB.All=100]="All",eB),lj=((ex={})[ex.Min=0]="Min",ex[ex.Pending=1]="Pending",ex[ex.Passed=2]="Passed",ex[ex.Rejected=3]="Rejected",ex[ex.Cancelled=4]="Cancelled",ex[ex.ToStart=5]="ToStart",ex[ex.Paused=6]="Paused",ex[ex.Processing=7]="Processing",ex[ex.Completed=8]="Completed",ex[ex.Max=10]="Max",ex);let l$=["0","1","2"],lM=[lL.Video,lL.Live,lL.All].map(String),lU=[lP.CpaDauV2,lP.CpmFeedVv,lP.Fix,lP.CpaDauV2MultiOs,lP.CpsMicroGame2022,lP.CpaDauV2AndCps,lP.CpaDauV2AndCpsMicroGame2022,lP.CpsV3].map(String),lq=["mpId","mpName","mpCategory","taskId","taskName","taskType","factionId","factionName","contentType","bidType","effectiveTime","dayCnt","metrics","extraIncentive","dataUpdateTime","readyDate","readyTs"],lV=["1","2"],lH=["1","2"];var lz=((eS={})[eS.Video=1]="Video",eS[eS.Live=2]="Live",eS[eS.All=100]="All",eS),lG=((eT={})[eT.TotalConsumptionAmount=1]="TotalConsumptionAmount",eT[eT.TotalRevenueAmount=2]="TotalRevenueAmount",eT[eT.NewActivationCount=3]="NewActivationCount",eT[eT.ComponentClickCount=4]="ComponentClickCount",eT);let lW=["date","mediaType","totalConsumptionAmount","totalRevenueAmount","newActivationCount","firstActiveCount","componentExposureCount","componentClickCount","componentClickThroughRate","conversionBillingConsumptionAmount","revenueBillingConsumptionAmount","revenueUserCount","iaaRevenueAmount","iapRevenueAmount"],lJ=rb(lG),lY=["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"],lK=["date","taskId","taskType","expense","totalIncome","cpaExpense","cpsExpense","adIncomeSettle","adIncomeLongTail","orderIncomeSettle","orderIncomeLongTail","newRegisterCnt","videoPost","videoPostUcnt","videoPlaySettle","videoPlayLongTail","liveRoomCnt","liveRoomUcnt","liveViewCnt","liveViewUcnt","frozenAmount","breakdownAmount","yesterdayDataReady"],lX=[lj.Pending,lj.Passed,lj.Rejected,lj.Cancelled,lj.ToStart,lj.Paused,lj.Processing,lj.Completed].map(String);var lQ=((eI={})[eI.Banner=1]="Banner",eI[eI.RewardedVideo=2]="RewardedVideo",eI[eI.Interstitial=3]="Interstitial",eI[eI.ECommerce=4]="ECommerce",eI),lZ=((eO={})[eO.All=1]="All",eO[eO.Douyin=2]="Douyin",eO[eO.DouyinLite=3]="DouyinLite",eO[eO.Toutiao=4]="Toutiao",eO[eO.ToutiaoLite=5]="ToutiaoLite",eO[eO.Fanqie=6]="Fanqie",eO[eO.FanqieChangTing=7]="FanqieChangTing",eO[eO.Hotsoon=8]="Hotsoon",eO[eO.Ppx=9]="Ppx",eO),l1=((ek={})[ek.All=1]="All",ek[ek.Android=2]="Android",ek[ek.IOS=3]="IOS",ek[ek.OpenHarmony=4]="OpenHarmony",ek[ek.Windows=5]="Windows",ek),l2=((eR={})[eR.Ad=1]="Ad",eR[eR.Star=2]="Star",eR[eR.Publisher=3]="Publisher",eR[eR.Natural=4]="Natural",eR),l0=((eP={})[eP.Banner=1]="Banner",eP[eP.RewardedVideo=2]="RewardedVideo",eP[eP.Interstitial=3]="Interstitial",eP[eP.ECommerce=4]="ECommerce",eP),l3=((eL={})[eL.All=1]="All",eL[eL.Douyin=2]="Douyin",eL[eL.DouyinLite=3]="DouyinLite",eL[eL.Toutiao=4]="Toutiao",eL[eL.ToutiaoLite=5]="ToutiaoLite",eL[eL.Fanqie=6]="Fanqie",eL[eL.FanqieChangTing=7]="FanqieChangTing",eL[eL.Hotsoon=8]="Hotsoon",eL[eL.Ppx=9]="Ppx",eL),l6=((eN={})[eN.All=1]="All",eN[eN.Android=2]="Android",eN[eN.IOS=3]="IOS",eN[eN.OpenHarmony=4]="OpenHarmony",eN[eN.Windows=5]="Windows",eN),l4=((ej={})[ej.Ad=1]="Ad",ej[ej.Star=2]="Star",ej[ej.Publisher=3]="Publisher",ej[ej.Natural=4]="Natural",ej);let l8=["recordType","date","requestCount","showCount","clickCount","clickRate","ecpm","incomeAfterShare","incomeBeforeShare"],l9=["date","ritId","ritName","hostName","requestCount","showCount","clickCount","clickRate","ecpm","incomeAfterShare","incomeBeforeShare"];var l7=((e$={})[e$.AD=1]="AD",e$[e$.Star=2]="Star",e$[e$.Pop=3]="Pop",e$[e$.Nature=4]="Nature",e$),l5=((eM={})[eM.Microgame=1]="Microgame",eM[eM.App=2]="App",eM),ce=((eU={})[eU.Cash=1]="Cash",eU[eU.CommonGood=2]="CommonGood",eU),ct=((eq={})[eq.CNY=1]="CNY",eq[eq.Diamond=2]="Diamond",eq),cr=((eV={})[eV.AD=1]="AD",eV[eV.Star=2]="Star",eV[eV.Pop=3]="Pop",eV[eV.Nature=4]="Nature",eV),ci=((eH={})[eH.Microgame=1]="Microgame",eH[eH.App=2]="App",eH);let cn=["ios","android","open_harmony","windows"],cu=["recordType","date","payPerson","payTimes","arppu","payMoney","payMoneyAfterShare","payMoneyAfterReduceShare","refundFee","refundFeeBeforeShare","refundFeeAfterShare","payMoneyAfterShareDataReady","payMoneyAfterReduceShareDataReady"],co=["payTime","transactionNo","merchantNo","openId","payStatus","changeType","goodType","orderType","activateType","amount","rechargeAmount","isOpenPlatformRefund","refundFee","refundFeeBeforeShare","refundFeeAfterShare","refundRemark"],cs=[10,11];function ca(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 cl(e){let t,r,i,n=await (t={X_Tt_Appid:e},r=nZ.genBaseURL("/platform_openapi/microgame/v1/payment/query_permission"),i={X_Tt_Appid:t.X_Tt_Appid,X_Tt_Userid:t.X_Tt_Userid},nZ.request({url:r,method:"GET",headers:i},void 0));return eY(n),{...n,data:n.data?{...n.data,callbackToken:n.data.callbackToken?"[REDACTED]":void 0}:void 0}}async function cc(e){return Promise.all(cs.map(async t=>{var r;let i,n,u,o=await (r={X_Tt_Appid:e,scene:t},i=nZ.genBaseURL("/platform_openapi/microgame/v1/payment/query_protocol_sign_status"),n={scene:r.scene},u={X_Tt_Appid:r.X_Tt_Appid},nZ.request({url:i,method:"GET",params:n,headers:u},void 0));return eY(o),{response:o,scene:t}}))}function cd(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 cp=new Set(["auth","check-update","skills","update"]);async function ch(e){await nN(e).catch(()=>void 0)}function cf(){process.exit(130)}async function cm(e){var t,r,i,n,u,o,s,a;let c,d,p,h,f,m,g,A,y;ns=new e2({middlewares:[tn,...ti,tu,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:()=>tr()?.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:ne,missingTokenErrorFactory:()=>new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前命令需要先登录,请先执行 ${e8}`})})]}),na=new e2({middlewares:[tn,...ti]});let E=e.slice(2),_=Date.now(),b=(((t=c=new $).addOption(new P("--caller <agent>","调用方 Agent").choices(nb).default("unknown")),t).name("dymg").description("抖音小游戏 CLI").version("0.5.1").configureHelp({showGlobalOptions:!0}).showHelpAfterError("(可使用 --help 查看命令说明)").showSuggestionAfterError(!0).addHelpText("after",`
129
129
  结果输出约定:
130
130
  - 业务数据默认不直接打印到终端
131
131
  - 数据查询生成 data.csv / raw_response.json / summary.json;非数据查询不生成 data.csv
@@ -147,5 +147,5 @@ ${t}`,uy=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),uE=Objec
147
147
  用法:
148
148
  - ${e8}
149
149
  - ${e9}
150
- - ${e7}`).action(oj),d.command("status").description("查看当前登录状态").option("--json","以 JSON 输出登录状态").action(oU),d.command("logout").description("退出当前登录").action(oq),d.command("check-dir-writable").description("用于 Agent 测试执行环境中的当前登录态目录是否可写,并输出结构化结果").addHelpText("after","\n示例:\n $ dymg auth check-dir-writable").action(oV),nx(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=nB(t,e);await ol("game:game-list",r,async()=>{var e;let t,i,n;rs(r.pageIndex,"--page-index",1,1e4),rs(r.pageSize,"--page-size",1,100);let u={pageIndex:rg(r.pageIndex,1),pageSize:rg(r.pageSize,20)},o=await (e=u,t=nZ.genBaseURL("/platform_openapi/microgame/v1/game/query_game_list"),i={pageIndex:e.pageIndex,pageSize:e.pageSize},n={X_Tt_Userid:e.X_Tt_Userid},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),s=eY(o),a=(s?.list??[]).map(e=>({appId:e.appId,appName:e.appName}));return{rawResponse:o,rows:a,csvHeader:["appId","appName"],resultMeta:iA({returnedCount:a.length,total:s?.total,page:u.pageIndex,pageSize:u.pageSize})}})}),p=r.command("insight").description("资讯与榜单"),nx(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=nB(t,e);await ol("insight:ranking-list",r,async()=>{var e;let t,i,n;ri(r.rankType,"--rank-type",rb(ls)),rn(r.gameBusinessList,"--game-business-list",rb(la)),rn(r.gameTypeList,"--game-type-list",lh),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,200);let u=rg(r.page,1),o=rg(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:rf(r.gameBusinessList),gameTypeList:rh(r.gameTypeList),onlyMyGame:r.onlyMyGame,rankType:rg(r.rankType,0),page:String(u),pageSize:String(o),meta:await nS("insight:ranking-list")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),c=eY(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:iA({returnedCount:d.length,total:c?.page?.total,page:c?.page?.page,pageSize:c?.page?.pageSize,hasMore:c?.page?.hasMore,nextCursor:c?.page?.nextSearchAfter})}})}),nx(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=nB(t,e);await ol("insight:hotspot-list",r,async()=>{var e;let t,i,n,u;rn(r.gameTypeIds,"--game-type-ids",lh);let o=(e=r,!!(e.keyword?.trim()||rh(e.gameTypeIds)?.length||rh(e.topicIds)?.length));rs(r.topN,"--top-n",1,o?50:100);let s=r.topN??(o?String(50):void 0),a=await (t={gameTypeIds:rh(r.gameTypeIds),keyword:r.keyword?.trim()||void 0,meta:await nS("insight:hotspot-list"),topN:s,topicIds:rh(r.topicIds)},i=nZ.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},nZ.request({url:i,method:"POST",data:n,headers:u},void 0)),l=eY(a);return{rawResponse:a,rows:(l?.items??[]).map(e=>({title:e.title,hotValue:e.hotValue,topics:lf(e.topics),hotInsights:e.hotInsights,jumpUrl:e.jumpUrl,contentId:e.contentId,coverUrl:e.coverUrl,playUrl:e.playUrl,contentTags:lf(e.contentTags),gamificationCategories:lf(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:lf(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:lf(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:lf(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),commentSummary:e.commentSummary,topComments:lf(e.topComments,e=>`${e.content??""}:${e.likeCount??""}`),dataStatus:e.dataStatus})),csvHeader:lc}})}),nx(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=nB(t,e);await ol("insight:element-list",r,async()=>{let e,t,i;ra(r.hotspotId,"--hotspot-id"),ri(r.elementType,"--element-type",lp),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,50);let n=rg(r.page,1),u=rg(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=nZ.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},nZ.request({url:t,method:"POST",data:i},void 0)),s=eY(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:lf(e.elementTags),description:e.description,heatTrend:lf(e.heatTrend,e=>`${r_(e.timestamp,{format:"date"})}:${e.hotScore??""}`)}));return{rawResponse:o,rows:a,csvHeader:ll,resultMeta:iA({returnedCount:a.length,total:s?.total,page:s?.page??n,pageSize:s?.pageSize??u,hasMore:s?.hasMore})}})}),nx(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=nB(t,e);await ol("insight:theme-list",r,async()=>{let e,t,i;ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,50);let n=rg(r.page,1),u=rg(r.pageSize,20),o=await (e={includeTopVideos:r.includeTopVideos,page:n,pageSize:u,parentTopicId:r.parentTopicId,topicIdList:rh(r.topicIdList)},t=nZ.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},nZ.request({url:t,method:"POST",data:i},void 0)),s=eY(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:lf(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:lf(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:lf(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:lf(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),audiencePreferences:lf(e.userFeatures?.audiencePreferences,e=>`${e.title??""}:${e.insight??""}`),contentPreferences:lf(e.userFeatures?.contentPreferences,e=>`${e.title??""}:${e.insight??""}`),interactionPreferences:lf(e.userFeatures?.interactionPreferences,e=>`${e.title??""}:${e.insight??""}`),relatedGames:function(e){if(e?.length)return D(e.map(e=>({gameId:e.gameId,gameName:e.gameName,iconUrl:e.iconUrl,jumpUrl:e.jumpUrl,heatValue:e.heatValue})))}(e.relatedGames),recentHotspots:lf(e.recentHotspots,e=>`${e.title??""}:${e.heatValue??""}`),topVideos:lf(e.topVideos,e=>`${e.video?.title??""}:${e.likeCount??""}`),trend7D:lf(e.trend7D,e=>`${r_(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend30D:lf(e.trend30D,e=>`${r_(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend90D:lf(e.trend90D,e=>`${r_(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`)}));return{rawResponse:o,rows:a,csvHeader:ld,resultMeta:iA({returnedCount:a.length,total:s?.total,page:n,pageSize:u,hasMore:s?.hasMore})}})}),h=r.command("analytics").description("用户数据"),nx(nT(h.command("behavior-query").description("查询用户的活跃用户、新增用户、累计用户、启动次数、游戏时长等行为指标,支持 App、操作系统等筛选"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:behavior-query",r,async()=>{var e;let t,i,n;oT(r),oI(r);let u=await (e={X_Tt_Appid:r.appId,filter:ov(r),meta:await nS("analytics:behavior-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u),s=(o?.items??[]).map(e=>({...e,recordType:"data"}));return{rawResponse:u,rows:[...s,...o?.summary?[{...o.summary,recordType:"summary"}]:[]],csvHeader:oD}})}),nx(nT(h.command("realtime-query").description("查询游戏当天的实时访问人数和访问次数"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:realtime-query",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:oA,label:"实时数据"}),oI(r);let u=await (e={X_Tt_Appid:r.appId,filter:ov(r),meta:await nS("analytics:realtime-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:(o?.items??[]).map(e=>({hour:e.hour,activeUser:e.activeUser,openTime:e.openTime})),csvHeader:oF}})}),nx(nT(h.command("retention-query").description("查询用户的次日、3 日、14 日、30 日留存率,支持筛选日期、App、操作系统、用户类型等").option("--retention-scene <n>","留存场景:1 全量 / 2 侧边栏"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:retention-query",r,async()=>{var e;let t,i,n;oT(r),oI(r),ri(r.retentionScene,"--retention-scene",rb(of));let u=await (e={X_Tt_Appid:r.appId,filter:ov(r),retentionScene:void 0===r.retentionScene?void 0:rg(r.retentionScene,0),meta:await nS("analytics:retention-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:(o?.items??[]).map(e=>({...e})),csvHeader:ow}})}),nx(nT(h.command("source-query").description("查询不同来源渠道下的活跃用户、新增用户数、启动次数、次均游戏时长等").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:source-query",r,async()=>{var e;let t,i,n;oT(r),oI(r),rs(r.topN,"--top-n",1,100);let u=await (e={X_Tt_Appid:r.appId,filter:ov(r),topN:r.topN,meta:await nS("analytics:source-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(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:oB}})}),nx(nT(h.command("profile-query").description("查询用户的性别、年龄、地域分布,区分不同 App、活跃/新增用户类型"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:profile-query",r,async()=>{var e;let t,i,n;oT(r),oI(r);let u=await (e={X_Tt_Appid:r.appId,filter:ov(r),meta:await nS("analytics:profile-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(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:ox}})}),nx(nT(h.command("device-query").description("查询用户的机型、品牌、客户端版本、基础库版本分布等").requiredOption("--dimension <n>","维度:1 型号 / 2 品牌 / 3 宿主版本 / 4 基础库版本").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:device-query",r,async()=>{var e;let t,i,n;oT(r),oI(r),ri(r.dimension,"--dimension",rb(om)),rs(r.topN,"--top-n",1,100);let u=rg(r.dimension,0),o=await (e={X_Tt_Appid:r.appId,dimension:u,filter:ov(r),topN:r.topN,meta:await nS("analytics:device-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),s=eY(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:oS}})}),nx(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",lu,[]).requiredOption("--first-channel <list>","一级渠道枚举,逗号分隔").requiredOption("--freshness-type <n>","数据时效:1 实时 / 2 离线").option("--second-channel <list>","二级渠道枚举,逗号分隔").option("--download","是否返回下载链接",!1).addHelpText("after",ln)).action(async(e,t)=>{let r=nB(t,e);await ol("growth:metric-query",r,async()=>{let e,t,i;rn(r.dimension,"--dimension",rb(a3)),rn(r.metric,"--metric",rb(a8)),ri(r.freshnessType,"--freshness-type",rb(a4)),rn(r.firstChannel,"--first-channel",rb(a6)),rn(r.secondChannel,"--second-channel",rb(a9));let n=rg(r.freshnessType,0),u=n===a4.RealTime;rc({startDate:r.activateStartDate,endDate:r.activateEndDate,maxLookbackDays:u?oy:oE,label:u?"增长实时数据":"增长离线数据",startField:"--activate-start-date",endField:"--activate-end-date"});let o=rf(r.dimension)??[],s=rf(r.metric)??[],a=rf(r.firstChannel)??[],c=rf(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=rb(a8),o=lo(r),s=r===a4.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=rg(d,0),f=(a=r,c=h,a===a4.RealTime?a7:c===a8.TotalROI?le:a5),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=rh(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=ry(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=lo(m);for(let e of h){let t=rv(a8,e),r=f.get(e);if(lt.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=>li[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 nS("growth:metric-query")},e=nZ.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},nZ.request({url:e,method:"POST",data:t,headers:i},void 0)),E=eY(y),_=o.flatMap(e=>e===a3.ActivateDate?["activateDate"]:e===a3.FirstChannel?["firstChannel"]:[]),b=A.flatMap(({metric:e,lifeTime:t})=>{let r=rv(a8,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===a3.ActivateDate){t.activateDate=n;return}r===a3.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:[..._,...lr]}})}),A=r.command("feedback").description("用户反馈与未成年人退款工单"),nx(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=nB(t,e);await ol("feedback:refund-list",r,async()=>{var e;let t,i,n;rp({startTime:r.startTime,endTime:r.endTime,unit:"seconds",allowFuture:!1}),ri(r.resolveStatus,"--resolve-status",[String(a0.UNRESOLVED),String(a0.RESOLVED)]),ra(r.ticketId,"--ticket-id"),ra(r.page,"--page"),rs(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,a0),openId:r.openId,ticketId:r.ticketId,page:u,limit:o},t=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eY(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:D((e.orderList??[]).map(e=>({createTime:e.createTime,orderId:e.orderId,orderName:e.orderName,orderPrice:rA(e.orderPriceCny),orderPriceDiamond:e.orderPriceDiamond,refund:rA(e.refundCny),refundDiamond:e.refundDiamond}))),imageList:D(e.imageList??[]),rejectReasonList:D(e.rejectReasonList??[]),logUrl:e.logUrl}));return{rawResponse:s,rows:l,csvHeader:a2,resultMeta:iA({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nx(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=nB(t,e);await ol("feedback:feedback-list",r,async()=>{var e;let t,i,n,u;rp({startTime:r.startTime,endTime:r.endTime,unit:"seconds",allowFuture:!1}),rn(r.dealtStatusList,"--dealt-status-list",rb(aK)),a1(r.labelIdList,"--label-id-list"),a1(r.aidList,"--aid-list"),ri(r.markStatus,"--mark-status",aZ),ra(r.feedbackId,"--feedback-id"),ri(r.orderRule,"--order-rule",rb(aX)),ra(r.currentPage,"--current-page"),rs(r.pageSize,"--page-size",1,100);let o=rg(r.currentPage,1),s=rg(r.pageSize,20),a=await (e={X_Tt_Appid:r.appId,startTime:void 0===r.startTime?void 0:rg(r.startTime,0),endTime:void 0===r.endTime?void 0:rg(r.endTime,0),dealtStatusList:rf(r.dealtStatusList),labelIdList:rf(r.labelIdList),aidList:rf(r.aidList),appVersion:rh(r.appVersion),markStatus:void 0===r.markStatus?void 0:rg(r.markStatus,0),feedbackId:r.feedbackId,openId:r.openId,searchContent:r.searchContent,orderRule:rC(r.orderRule,aX),currentPage:o,pageSize:s},t=nZ.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},nZ.request({url:t,method:"POST",data:i,params:n,headers:u},void 0)),l=eY(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:D(e.imageUrlList),logDownloadUrl:e.logDownloadUrl}));return{rawResponse:a,rows:c,csvHeader:aQ,resultMeta:iA({returnedCount:c.length,total:l?.total,page:o,pageSize:s})}})}),f=r.command("revenue").description("商业化"),nx((i=f).command("traffic-status").description("检查小游戏是否具备开通流量主的权限、签约和主体资质").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nB(t,e);await ol("revenue:traffic-status",r,async()=>{var e;let t,i,n=await (e={X_Tt_Appid:r.appId},t=nZ.genBaseURL("/platform_openapi/microgame/v1/ad/query_traffic_status"),i={X_Tt_Appid:(e||{}).X_Tt_Appid},nZ.request({url:t,method:"GET",headers:i},void 0));return eY(n),{rawResponse:n}})}),nx(i.command("placement-list").description("查询当前小游戏的广告位及其类型、开关和封禁状态").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nB(t,e);await ol("revenue:placement-list",r,async()=>{var e;let t,i,n=await (e={X_Tt_Appid:r.appId},t=nZ.genBaseURL("/platform_openapi/microgame/v1/ad/query_placement"),i={X_Tt_Appid:(e||{}).X_Tt_Appid},nZ.request({url:t,method:"GET",headers:i},void 0)),u=eY(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"]}})}),nx((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=nB(t,e);await ol("revenue:ad-income-query",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:o_,latestDateOffsetDays:1,label:"广告收入"}),rn(r.adPositionTypes,"--ad-position-types",rb(lQ)),rn(r.hosts,"--hosts",rb(lZ)),ri(r.os,"--os",rb(l1)),ri(r.activateType,"--activate-type",rb(l0));let u=await (e={X_Tt_Appid:r.appId,startDate:r.startDate,endDate:r.endDate,adPositionTypes:rf(r.adPositionTypes),hosts:rm(r.hosts,"--hosts",lZ.All),os:rC(r.os,l1),activateType:rC(r.activateType,l0),fromAppPlatform:1,meta:await nS("revenue:ad-income-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(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:l8}})}),nx(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=nB(t,e);await ol("revenue:ad-income-detail",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:o_,latestDateOffsetDays:1,label:"广告收入"}),rn(r.adPositionTypes,"--ad-position-types",rb(l2)),rn(r.hosts,"--hosts",rb(l3)),ri(r.os,"--os",rb(l6)),ri(r.activateType,"--activate-type",rb(l4)),ra(r.page,"--page"),rs(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:rf(r.adPositionTypes),hosts:rm(r.hosts,"--hosts",l3.All),os:rC(r.os,l6),activateType:rC(r.activateType,l4),fromAppPlatform:1,meta:await nS("revenue:ad-income-detail"),page:u,pageSize:o},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),a=eY(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:l9,resultMeta:iA({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})}})}),nx((u=f).command("payment-status").description("查询虚拟支付权限及钻石支付、担保支付协议状态").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nB(t,e);await ol("revenue:payment-status",r,async()=>{let[e,t]=await Promise.all([cl(r.appId),cc(r.appId)]);return{rawResponse:{permission:e,protocols:t.map(({response:e,scene:t})=>({scene:t,...e}))}}})}),nx(cd(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=nB(t,e);await ol("revenue:payment-order-list",r,async()=>{var e;let t,i,n;if(rl({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),ri(r.host,"--host",["-1",...lw]),ri(r.os,"--os",cn),ri(r.activateType,"--activate-type",rb(l7)),ri(r.fromAppPlatform,"--from-app-platform",rb(l5)),ri(r.goodType,"--good-type",rb(ce)),ri(r.paymentChannel,"--payment-channel",rb(ct)),ri(r.paymentStatus,"--payment-status",["done","canceled"]),ri(r.transactionType,"--transaction-type",["recharge","pay","add","refund"]),rs(r.keywordType,"--keyword-type",1,3),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,100),!!r.keyword!=!!r.keywordType)throw new l("--keyword-type 与 --keyword 必须同时提供",{error:re.InvalidRange,message:"--keyword-type 与 --keyword 必须同时提供"});let u=r.page??"1",o=r.pageSize??"20",s=ca(r.startDate,r.endDate)?void 0:rC(r.activateType,l7),a=r.keyword&&r.keywordType?{[rg(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,l5),payStatus:r.paymentStatus,changeType:r.transactionType,keyword:a,goodType:rC(r.goodType,ce),orderType:rC(r.paymentChannel,ct),pageNo:u,pageSize:o},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),d=eY(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:rA(e.rechargeAmountFen),isOpenPlatformRefund:e.isOpenPlatformRefund,refundFee:e.refundFee,refundFeeBeforeShare:e.refundFeeBeforeShare,refundFeeAfterShare:e.refundFeeAfterShare,refundRemark:e.refundRemark}));return{rawResponse:c,rows:h,csvHeader:co,resultMeta:iA({returnedCount:h.length,total:p?.totalNum,page:u,pageSize:o})}})}),nx(cd(u.command("payment-income-query").description("查询虚拟支付收入总览、分成、退款和 ARPPU"))).action(async(e,t)=>{let r=nB(t,e);await ol("revenue:payment-income-query",r,async()=>{var e;let t,i,n;rl({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),ri(r.host,"--host",["-1",...lw]),ri(r.os,"--os",cn),ri(r.activateType,"--activate-type",rb(cr)),ri(r.fromAppPlatform,"--from-app-platform",rb(ci));let u=ca(r.startDate,r.endDate)?void 0:rC(r.activateType,cr),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,ci)},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),s=eY(o),a=s?.result?.[0],l=(e,t)=>({recordType:t,date:e?.date,payPerson:e?.payPerson,payTimes:e?.payTimes,arppu:e?.arppu,payMoney:rA(e?.payMoneyFen),payMoneyAfterShare:e?.payMoneyAfterShareDataReady?rA(e.payMoneyAfterShareFen):void 0,payMoneyAfterReduceShare:e?.payMoneyAfterReduceShareDataReady?rA(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:cu}})}),y=r.command("publisher").description("发行人计划"),nx((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=nB(t,e);await ol("publisher:task-list",r,async()=>{let e,t,i,n;rl({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),ra(r.taskId,"--task-id"),ri(r.taskType,"--task-type",rb(lN)),ri(r.mediaType,"--media-type",lM),ri(r.webStatus,"--web-status",lX),ri(r.biddingMethod,"--bidding-method",lU),ri(r.taskCategory,"--task-category",l$),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,100);let u=rg(r.page,1),o=rg(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,lN),mediaType:rC(r.mediaType,lL),webStatus:rC(r.webStatus,lj),biddingMethod:rC(r.biddingMethod,lP),taskCategory:void 0===r.taskCategory?void 0:rg(r.taskCategory,0),asc:r.asc,offset:String((u-1)*o),limit:String(o)},t=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eY(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:rA(t?.budget),prepaidFreezeAmount:rA(e.prepaidFreezeAmount),securityBudget:rA(t?.securityBudget),totalExpectedNum:t?.totalExpectedNum,expense:rA(e.expense),totalIncome:rA(e.totalIncome),cpaExpense:rA(e.cpaExpense),cpsExpense:rA(e.cpsExpense),adIncomeSettle:rA(e.adIncomeSettle),orderIncomeSettle:rA(e.orderIncomeSettle),newRegisterCnt:e.newRegisterCnt,videoPost:e.videoPost,liveRoomCnt:e.liveRoomCnt,dataProductionDate:e.dataProductionDate,bidCollections:D(t?.bidCollections??[])}});return{rawResponse:s,rows:l,csvHeader:lY,resultMeta:iA({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nx(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=nB(t,e);await ol("publisher:task-detail-query",r,async()=>{let e,t,i,n;rl({startDate:r.startDate,endDate:r.endDate}),ra(r.taskId,"--task-id"),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,100);let u=rg(r.page,1),o=rg(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=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eY(s),l=(a?.detailStats??[]).map(e=>({date:e.date,taskId:e.taskId,taskType:e.taskType,expense:rA(e.expense),totalIncome:rA(e.totalIncome),cpaExpense:rA(e.cpaExpense),cpsExpense:rA(e.cpsExpense),adIncomeSettle:rA(e.adIncomeSettle),adIncomeLongTail:rA(e.adIncomeLongTail),orderIncomeSettle:rA(e.orderIncomeSettle),orderIncomeLongTail:rA(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:rA(e.frozenAmount),breakdownAmount:rA(e.breakdownAmount),yesterdayDataReady:a?.yesterdayDataReady}));return{rawResponse:s,rows:l,csvHeader:lK,resultMeta:iA({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nx((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=nB(t,e);await ol("publisher:promotion-query",r,async()=>{var e;let t,i,n;rl({startDate:r.startDate,endDate:r.endDate}),ri(r.mediaType,"--media-type",rb(lz));let[u,o]=function(e){rn(e,"--metrics",lJ);let t=rf(e);if(!t||t.length<1||t.length>2)throw new l("--metrics 必须包含一个或两个趋势指标",{error:re.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,lz)},t=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eY(s);return{rawResponse:s,rows:(a?.list??[]).map(e=>({date:e.date,totalConsumptionAmount:rA(e.totalConsumptionAmount),totalRevenueAmount:rA(e.totalRevenueAmount),newActivationCount:e.newActivationCount,componentClickCount:e.componentClickCount})),csvHeader:["date","totalConsumptionAmount","totalRevenueAmount","newActivationCount","componentClickCount"]}})}),nx(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=nB(t,e);await ol("publisher:promotion-detail-list",r,async()=>{var e;let t,i,n;rl({startDate:r.startDate,endDate:r.endDate}),ri(r.mediaType,"--media-type",rb(lz)),ra(r.page,"--page"),rs(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,lz),pageNo:u,pageSize:o},t=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eY(s),l=(a?.settleDetailList??[]).map(e=>({date:e.date,mediaType:e.mediaType,totalConsumptionAmount:rA(e.totalConsumptionAmount),totalRevenueAmount:rA(e.totalRevenueAmount),newActivationCount:e.newActivationCount,firstActiveCount:e.firstActiveCount,componentExposureCount:e.componentExposureCount,componentClickCount:e.componentClickCount,componentClickThroughRate:e.componentClickThroughRate,conversionBillingConsumptionAmount:rA(e.conversionBillingConsumptionAmount),revenueBillingConsumptionAmount:rA(e.revenueBillingConsumptionAmount),revenueUserCount:e.revenueUserCount,iaaRevenueAmount:rA(e.iaaRevenueAmount),iapRevenueAmount:rA(e.iapRevenueAmount)}));return{rawResponse:s,rows:l,csvHeader:lW,resultMeta:iA({returnedCount:l.length,total:a?.totalCount,page:u,pageSize:o})}})}),nx(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=nB(t,e);await ol("publisher:faction-incentive-list",r,async()=>{let e,t,i,n;for(let e of(ra(r.factionId,"--faction-id"),rh(r.taskIds)??[]))ra(e,"--task-ids");ri(r.orderType,"--order-type",lH),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,100),rn(r.taskTypes,"--task-types",l$),rn(r.taskStatuses,"--task-statuses",lV),rn(r.contentTypes,"--content-types",lM),rn(r.bidTypes,"--bid-types",["-1",...lU]),function(e,t){var r=e,i=t;if(void 0!==r){for(let e of t4(r))if(!t9.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 t4(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:rh(r.taskIds),taskTypes:rm(r.taskTypes,"--task-types",0),taskStatuses:rf(r.taskStatuses),statMonths:rf(r.statMonths),contentTypes:rm(r.contentTypes,"--content-types",100),bidTypes:rm(r.bidTypes,"--bid-types",-1),orderField:r.orderField,orderType:void 0===r.orderType?void 0:rg(r.orderType,0),pageNum:u,pageSize:o},t=nZ.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},nZ.request({url:t,method:"POST",params:i,headers:n},void 0)),a=eY(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:D(e),extraIncentive:D(e.extraIncentive),dataUpdateTime:a?.dataUpdateTime,readyDate:a?.extra?.readyDate,readyTs:a?.extra?.readyTs}));return{rawResponse:s,rows:c,csvHeader:lq,resultMeta:iA({returnedCount:c.length,total:a?.total,page:a?.pageNum??u,pageSize:o})}})}),nx((a=r.command("ability").description("能力中心")).command("customer-service-status-query").description("查询新版抖音客服平台的开通状态").requiredOption("--app-id <appId>","小游戏 appId").addOption(new P("--type <type>","客服类型:im 抖音 IM / platform 抖音客服平台").choices(["im","platform"]))).action(async(e,t)=>{let r=nB(t,e);await ol("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=nZ.genBaseURL("/platform_openapi/microgame/v1/ability/query_im_customer_service_status"),n={X_Tt_Appid:(e||{}).X_Tt_Appid},nZ.request({url:i,method:"GET",headers:n},void 0)).then(e=>(eY(e),["im",e]))),r.type&&"platform"!==r.type||s.push((t={X_Tt_Appid:r.appId},u=nZ.genBaseURL("/platform_openapi/microgame/v1/ability/query_customer_service_status"),o={X_Tt_Appid:t.X_Tt_Appid},nZ.request({url:u,method:"GET",headers:o},void 0)).then(e=>(eY(e),["platform",e]))),{rawResponse:Object.fromEntries(await Promise.all(s))}})}),nx(a.command("rank-list-query").description("查询当前小游戏已有的排行榜配置").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nB(t,e);await ol("ability:rank-list-query",r,async()=>{let e,t,i,n,u=await (e={X_Tt_Appid:r.appId},t=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:o?.rankInfo??[],csvHeader:["uniqueFlag","shortName","updateFrequency","dataType","sortType","dataSuffix","enumValues","isDefault","updateTime"]}})}),nx(a.command("share-template-query").description("查询当前小游戏在分享设置配置的分享模板、审核状态、默认标记和驳回原因").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nB(t,e);await ol("ability:share-template-query",r,async()=>{var e;let t,i,n=await (e={appIdStr:r.appId,newTemplate:!0},t=nZ.genBaseURL("/platform_openapi/microgame/v1/ability/query_share_setting"),i={appIdStr:e.appIdStr,newTemplate:e.newTemplate},nZ.request({url:t,method:"GET",params:i},void 0)),u=eY(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("性能数据"),nx(g.command("performance-diagnosis-query").description("查询小游戏启动和运行性能诊断结果,包括劣化指标、实际值、标准值、差值及优化建议;当前不提供网络诊断").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--host <host>",nD).option("--date <date>","诊断日期,格式 YYYY-MM-DD").option("--device-level <n>",nw).option("--os <os>","操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony").option("--mp-version <version>","小游戏版本号")).action(async(e,t)=>{let r=nB(t,e);await ol("performance:performance-diagnosis-query",r,async()=>{var e;let t,i,n;ri(r.host,"--host",lF),ri(r.deviceLevel,"--device-level",rb(ly)),ri(r.os,"--os",rb(lE)),ro(r.date,"--date");let u=await (e={X_Tt_Appid:r.appId,hostAid:lD[rg(r.host,0)]??"",date:r.date,deviceLevel:void 0===r.deviceLevel?void 0:rg(r.deviceLevel,0),os:void 0===r.os?void 0:rg(r.os,0),mpVersion:r.mpVersion,meta:await nS("performance:performance-diagnosis-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u),s={group:"main",genreName:o?.genreName??"",engine:o?.engine??"",degradedIndicatorCount:o?.degradedIndicatorCount??0};return{rawResponse:u,rows:[...lI(o?.launchItems,s,"launch"),...lI(o?.runtimeItems,s,"runtime"),...(o?.otherGroups??[]).flatMap(e=>{let t={group:"other",genreName:e.genreName,engine:e.engine,degradedIndicatorCount:e.degradedIndicatorCount};return[...lI(e.launchItems,t,"launch"),...lI(e.runtimeItems,t,"runtime")]})],csvHeader:lx}})}),nx(nI(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=nB(t,e);await ol("performance:startup-performance-query",r,async()=>{var e;let t,i,n;lk(r),rn(r.sections,"--sections",rb(lv)),ri(r.downloadCode,"--download-code",rb(lC)),ru(r.sceneIdList,"--scene-id-list");let u=await (e={X_Tt_Appid:r.appId,filter:{common:lR(r),entranceForm:r.entranceForm,downloadCode:void 0===r.downloadCode?void 0:rg(r.downloadCode,0),sceneIdList:rh(r.sceneIdList)},metrics:rf(r.metrics),sections:rf(r.sections),meta:await nS("performance:startup-performance-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:lO(o?.series),csvHeader:lS}})}),nx(nI(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=nB(t,e);await ol("performance:runtime-performance-query",r,async()=>{var e;let t,i,n;lk(r);let u=await (e={X_Tt_Appid:r.appId,filter:lR(r),includeDeviceBreakdown:r.includeDeviceBreakdown,includeFpsDistribution:r.includeFpsDistribution,includeMemoryDistribution:r.includeMemoryDistribution,metrics:rf(r.metrics),meta:await nS("performance:runtime-performance-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:lO(o?.series),csvHeader:lS}})}),nx(nI(g.command("network-performance-query").description("查询小游戏网络性能数据,包括 request 和 downloadFile 的请求耗时、错误率等指标").option("--metrics <list>","网络性能指标枚举,逗号分隔;不传返回默认指标集"))).action(async(e,t)=>{let r=nB(t,e);await ol("performance:network-performance-query",r,async()=>{var e;let t,i,n;lk(r);let u=await (e={X_Tt_Appid:r.appId,filter:lR(r),metrics:rf(r.metrics),meta:await nS("performance:network-performance-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:lO(o?.series),csvHeader:lS}})}),nx(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>",nv).option("--os <os>",nF).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=nB(t,e);await ol("performance:error-log-query",r,async()=>{var e;let t,i,n;ri(r.host,"--host",rb(lm)),ri(r.os,"--os",rb(lA)),rn(r.logLevelList,"--log-level-list",rb(lg)),function(e){let{maxLookbackDays:t,label:r}=e,i=e.unit??"milliseconds",n=BigInt(e.lookbackTolerance??0),u=rd(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"}),rs(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:rg(r.host,0),os:void 0===r.os?void 0:rg(r.os,0),appVersion:r.appVersion,gameVersion:r.gameVersion,jssdkVersion:r.jssdkVersion,openId:r.openId,traceId:r.traceId,logLevelList:rf(r.logLevelList),filterMsg:rh(r.filterMsg),pageGroupSize:r.pageGroupSize,searchAfter:r.searchAfter,meta:await nS("performance:error-log-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(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:lT,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 发布的 ${e6} Skill`).addHelpText("after","\n说明:\n 安装或重新同步本机 Agent Skill\n update 默认会执行同步;需要手动修复 Skill 时再运行本命令\n\n示例:\n $ dymg skills install").action(aV),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(aY),r.command("update").description("更新 CLI 并同步 Skill").option("--target-version <version>","安装指定版本或 dist tag,默认 latest").option("--skip-skills","只更新 CLI,跳过 Skill 同步").addOption(new P("--package-manager <packageManager>","指定全局安装使用的包管理器").choices(n$)).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(aW),c),C=!1,v=!1,w=!1,B=()=>{v&&cf(),v=!0,process.exitCode=130;let e=nL();C&&e||cf();let t=setTimeout(()=>{cf()},200);ch({...e,durationMs:Date.now()-_,success:!1,errorMessage:"命令已中断",errorCode:tr()?.errorCode}).finally(()=>{clearTimeout(t),cf()})};process.once("SIGINT",B),process.once("SIGTERM",B),b.hook("preAction",(e,t)=>{var r,i,n;let u,o;C=!0,r=t,w=!cp.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),tt({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:D(u),errorMessage:void 0,errorCode:void 0})});try{await b.parseAsync(e);let t=nL();if(C&&t){let e=0===Number(process.exitCode??0);await ch({...t,durationMs:Date.now()-_,success:e,errorMessage:e?void 0:tr()?.errorMessage,errorCode:e?void 0:tr()?.errorCode})}C&&w&&0===Number(process.exitCode??0)&&await nQ()}catch(r){let e=r instanceof Error?r.message:String(r),t=nL();if(r instanceof F){process.exitCode=r.exitCode,C&&t&&await ch({...t,durationMs:Date.now()-_,success:0===r.exitCode,errorMessage:0===r.exitCode?void 0:e,errorCode:0===r.exitCode?void 0:nj(r)});return}throw C&&t&&await ch({...t,durationMs:Date.now()-_,success:!1,errorMessage:e,errorCode:nj(r)}),r}finally{process.removeListener("SIGINT",B),process.removeListener("SIGTERM",B)}}(async function(e=process.argv){var t,r;return t={},r=()=>cm(e),te.run(t,r)})().then(async()=>{await y(Number(process.exitCode??0))}).catch(async e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
150
+ - ${e7}`).action(oj),d.command("status").description("查看当前登录状态").option("--json","以 JSON 输出登录状态").action(oU),d.command("logout").description("退出当前登录").action(oq),d.command("check-dir-writable").description("用于 Agent 测试执行环境中的当前登录态目录是否可写,并输出结构化结果").addHelpText("after","\n示例:\n $ dymg auth check-dir-writable").action(oV),nx(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=nB(t,e);await ol("game:game-list",r,async()=>{var e;let t,i,n;rs(r.pageIndex,"--page-index",1,1e4),rs(r.pageSize,"--page-size",1,100);let u={pageIndex:rg(r.pageIndex,1),pageSize:rg(r.pageSize,20)},o=await (e=u,t=nZ.genBaseURL("/platform_openapi/microgame/v1/game/query_game_list"),i={pageIndex:e.pageIndex,pageSize:e.pageSize},n={X_Tt_Userid:e.X_Tt_Userid},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),s=eY(o),a=(s?.list??[]).map(e=>({appId:e.appId,appName:e.appName}));return{rawResponse:o,rows:a,csvHeader:["appId","appName"],resultMeta:iA({returnedCount:a.length,total:s?.total,page:u.pageIndex,pageSize:u.pageSize})}})}),p=r.command("insight").description("资讯与榜单"),nx(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=nB(t,e);await ol("insight:ranking-list",r,async()=>{var e;let t,i,n;ri(r.rankType,"--rank-type",rb(ls)),rn(r.gameBusinessList,"--game-business-list",rb(la)),rn(r.gameTypeList,"--game-type-list",lh),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,200);let u=rg(r.page,1),o=rg(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:rf(r.gameBusinessList),gameTypeList:rh(r.gameTypeList),onlyMyGame:r.onlyMyGame,rankType:rg(r.rankType,0),page:String(u),pageSize:String(o),meta:await nS("insight:ranking-list")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),c=eY(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:iA({returnedCount:d.length,total:c?.page?.total,page:c?.page?.page,pageSize:c?.page?.pageSize,hasMore:c?.page?.hasMore,nextCursor:c?.page?.nextSearchAfter})}})}),nx(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=nB(t,e);await ol("insight:hotspot-list",r,async()=>{var e;let t,i,n,u;rn(r.gameTypeIds,"--game-type-ids",lh);let o=(e=r,!!(e.keyword?.trim()||rh(e.gameTypeIds)?.length||rh(e.topicIds)?.length));rs(r.topN,"--top-n",1,o?50:100);let s=r.topN??(o?String(50):void 0),a=await (t={gameTypeIds:rh(r.gameTypeIds),keyword:r.keyword?.trim()||void 0,meta:await nS("insight:hotspot-list"),topN:s,topicIds:rh(r.topicIds)},i=nZ.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},nZ.request({url:i,method:"POST",data:n,headers:u},void 0)),l=eY(a);return{rawResponse:a,rows:(l?.items??[]).map(e=>({title:e.title,hotValue:e.hotValue,topics:lf(e.topics),hotInsights:e.hotInsights,jumpUrl:e.jumpUrl,contentId:e.contentId,coverUrl:e.coverUrl,playUrl:e.playUrl,contentTags:lf(e.contentTags),gamificationCategories:lf(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:lf(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:lf(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:lf(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),commentSummary:e.commentSummary,topComments:lf(e.topComments,e=>`${e.content??""}:${e.likeCount??""}`),dataStatus:e.dataStatus})),csvHeader:lc}})}),nx(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=nB(t,e);await ol("insight:element-list",r,async()=>{let e,t,i;ra(r.hotspotId,"--hotspot-id"),ri(r.elementType,"--element-type",lp),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,50);let n=rg(r.page,1),u=rg(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=nZ.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},nZ.request({url:t,method:"POST",data:i},void 0)),s=eY(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:lf(e.elementTags),description:e.description,heatTrend:lf(e.heatTrend,e=>`${r_(e.timestamp,{format:"date"})}:${e.hotScore??""}`)}));return{rawResponse:o,rows:a,csvHeader:ll,resultMeta:iA({returnedCount:a.length,total:s?.total,page:s?.page??n,pageSize:s?.pageSize??u,hasMore:s?.hasMore})}})}),nx(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=nB(t,e);await ol("insight:theme-list",r,async()=>{let e,t,i;ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,50);let n=rg(r.page,1),u=rg(r.pageSize,20),o=await (e={includeTopVideos:r.includeTopVideos,page:n,pageSize:u,parentTopicId:r.parentTopicId,topicIdList:rh(r.topicIdList)},t=nZ.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},nZ.request({url:t,method:"POST",data:i},void 0)),s=eY(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:lf(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:lf(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:lf(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:lf(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),audiencePreferences:lf(e.userFeatures?.audiencePreferences,e=>`${e.title??""}:${e.insight??""}`),contentPreferences:lf(e.userFeatures?.contentPreferences,e=>`${e.title??""}:${e.insight??""}`),interactionPreferences:lf(e.userFeatures?.interactionPreferences,e=>`${e.title??""}:${e.insight??""}`),relatedGames:function(e){if(e?.length)return D(e.map(e=>({gameId:e.gameId,gameName:e.gameName,iconUrl:e.iconUrl,jumpUrl:e.jumpUrl,heatValue:e.heatValue})))}(e.relatedGames),recentHotspots:lf(e.recentHotspots,e=>`${e.title??""}:${e.heatValue??""}`),topVideos:lf(e.topVideos,e=>`${e.video?.title??""}:${e.likeCount??""}`),trend7D:lf(e.trend7D,e=>`${r_(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend30D:lf(e.trend30D,e=>`${r_(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend90D:lf(e.trend90D,e=>`${r_(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`)}));return{rawResponse:o,rows:a,csvHeader:ld,resultMeta:iA({returnedCount:a.length,total:s?.total,page:n,pageSize:u,hasMore:s?.hasMore})}})}),h=r.command("analytics").description("用户数据"),nx(nT(h.command("behavior-query").description("查询用户的活跃用户、新增用户、累计用户、启动次数、游戏时长等行为指标,支持 App、操作系统等筛选"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:behavior-query",r,async()=>{var e;let t,i,n;oT(r),oI(r);let u=await (e={X_Tt_Appid:r.appId,filter:ov(r),meta:await nS("analytics:behavior-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u),s=(o?.items??[]).map(e=>({...e,recordType:"data"}));return{rawResponse:u,rows:[...s,...o?.summary?[{...o.summary,recordType:"summary"}]:[]],csvHeader:oD}})}),nx(nT(h.command("realtime-query").description("查询游戏当天的实时访问人数和访问次数"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:realtime-query",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:oA,label:"实时数据"}),oI(r);let u=await (e={X_Tt_Appid:r.appId,filter:ov(r),meta:await nS("analytics:realtime-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:(o?.items??[]).map(e=>({hour:e.hour,activeUser:e.activeUser,openTime:e.openTime})),csvHeader:oF}})}),nx(nT(h.command("retention-query").description("查询用户的次日、3 日、14 日、30 日留存率,支持筛选日期、App、操作系统、用户类型等").option("--retention-scene <n>","留存场景:1 全量 / 2 侧边栏"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:retention-query",r,async()=>{var e;let t,i,n;oT(r),oI(r),ri(r.retentionScene,"--retention-scene",rb(of));let u=await (e={X_Tt_Appid:r.appId,filter:ov(r),retentionScene:void 0===r.retentionScene?void 0:rg(r.retentionScene,0),meta:await nS("analytics:retention-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:(o?.items??[]).map(e=>({...e})),csvHeader:ow}})}),nx(nT(h.command("source-query").description("查询不同来源渠道下的活跃用户、新增用户数、启动次数、次均游戏时长等").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:source-query",r,async()=>{var e;let t,i,n;oT(r),oI(r),rs(r.topN,"--top-n",1,100);let u=await (e={X_Tt_Appid:r.appId,filter:ov(r),topN:r.topN,meta:await nS("analytics:source-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(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:oB}})}),nx(nT(h.command("profile-query").description("查询用户的性别、年龄、地域分布,区分不同 App、活跃/新增用户类型"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:profile-query",r,async()=>{var e;let t,i,n;oT(r),oI(r);let u=await (e={X_Tt_Appid:r.appId,filter:ov(r),meta:await nS("analytics:profile-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(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:ox}})}),nx(nT(h.command("device-query").description("查询用户的机型、品牌、客户端版本、基础库版本分布等").requiredOption("--dimension <n>","维度:1 型号 / 2 品牌 / 3 宿主版本 / 4 基础库版本").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=nB(t,e);await ol("analytics:device-query",r,async()=>{var e;let t,i,n;oT(r),oI(r),ri(r.dimension,"--dimension",rb(om)),rs(r.topN,"--top-n",1,100);let u=rg(r.dimension,0),o=await (e={X_Tt_Appid:r.appId,dimension:u,filter:ov(r),topN:r.topN,meta:await nS("analytics:device-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),s=eY(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:oS}})}),nx(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",lu,[]).requiredOption("--first-channel <list>","一级渠道枚举,逗号分隔").requiredOption("--freshness-type <n>","数据时效:1 实时 / 2 离线").option("--second-channel <list>","二级渠道枚举,逗号分隔").option("--download","是否返回下载链接",!1).addHelpText("after",ln)).action(async(e,t)=>{let r=nB(t,e);await ol("growth:metric-query",r,async()=>{let e,t,i;rn(r.dimension,"--dimension",rb(a3)),rn(r.metric,"--metric",rb(a8)),ri(r.freshnessType,"--freshness-type",rb(a4)),rn(r.firstChannel,"--first-channel",rb(a6)),rn(r.secondChannel,"--second-channel",rb(a9));let n=rg(r.freshnessType,0),u=n===a4.RealTime;rc({startDate:r.activateStartDate,endDate:r.activateEndDate,maxLookbackDays:u?oy:oE,label:u?"增长实时数据":"增长离线数据",startField:"--activate-start-date",endField:"--activate-end-date"});let o=rf(r.dimension)??[],s=rf(r.metric)??[],a=rf(r.firstChannel)??[],c=rf(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=rb(a8),o=lo(r),s=r===a4.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=rg(d,0),f=(a=r,c=h,a===a4.RealTime?a7:c===a8.TotalROI?le:a5),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=rh(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=ry(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=lo(m);for(let e of h){let t=rv(a8,e),r=f.get(e);if(lt.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=>li[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 nS("growth:metric-query")},e=nZ.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},nZ.request({url:e,method:"POST",data:t,headers:i},void 0)),E=eY(y),_=o.flatMap(e=>e===a3.ActivateDate?["activateDate"]:e===a3.FirstChannel?["firstChannel"]:[]),b=A.flatMap(({metric:e,lifeTime:t})=>{let r=rv(a8,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===a3.ActivateDate){t.activateDate=n;return}r===a3.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:[..._,...lr]}})}),A=r.command("feedback").description("用户反馈与未成年人退款工单"),nx(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=nB(t,e);await ol("feedback:refund-list",r,async()=>{var e;let t,i,n;rp({startTime:r.startTime,endTime:r.endTime,unit:"seconds",allowFuture:!1}),ri(r.resolveStatus,"--resolve-status",[String(a2.UNRESOLVED),String(a2.RESOLVED)]),ra(r.ticketId,"--ticket-id"),ra(r.page,"--page"),rs(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,a2),openId:r.openId,ticketId:r.ticketId,page:u,limit:o},t=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eY(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:D((e.orderList??[]).map(e=>({createTime:e.createTime,orderId:e.orderId,orderName:e.orderName,orderPrice:rA(e.orderPriceCny),orderPriceDiamond:e.orderPriceDiamond,refund:rA(e.refundCny),refundDiamond:e.refundDiamond}))),imageList:D(e.imageList??[]),rejectReasonList:D(e.rejectReasonList??[]),logUrl:e.logUrl}));return{rawResponse:s,rows:l,csvHeader:a0,resultMeta:iA({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nx(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=nB(t,e);await ol("feedback:feedback-list",r,async()=>{var e;let t,i,n,u;rp({startTime:r.startTime,endTime:r.endTime,unit:"seconds",allowFuture:!1}),rn(r.dealtStatusList,"--dealt-status-list",rb(aK)),a1(r.labelIdList,"--label-id-list"),a1(r.aidList,"--aid-list"),ri(r.markStatus,"--mark-status",aZ),ra(r.feedbackId,"--feedback-id"),ri(r.orderRule,"--order-rule",rb(aX)),ra(r.currentPage,"--current-page"),rs(r.pageSize,"--page-size",1,100);let o=rg(r.currentPage,1),s=rg(r.pageSize,20),a=await (e={X_Tt_Appid:r.appId,startTime:void 0===r.startTime?void 0:rg(r.startTime,0),endTime:void 0===r.endTime?void 0:rg(r.endTime,0),dealtStatusList:rf(r.dealtStatusList),labelIdList:rf(r.labelIdList),aidList:rf(r.aidList),appVersion:rh(r.appVersion),markStatus:void 0===r.markStatus?void 0:rg(r.markStatus,0),feedbackId:r.feedbackId,openId:r.openId,searchContent:r.searchContent,orderRule:rC(r.orderRule,aX),currentPage:o,pageSize:s},t=nZ.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},nZ.request({url:t,method:"POST",data:i,params:n,headers:u},void 0)),l=eY(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:D(e.imageUrlList),logDownloadUrl:e.logDownloadUrl}));return{rawResponse:a,rows:c,csvHeader:aQ,resultMeta:iA({returnedCount:c.length,total:l?.total,page:o,pageSize:s})}})}),f=r.command("revenue").description("商业化"),nx((i=f).command("traffic-status").description("检查小游戏是否具备开通流量主的权限、签约和主体资质").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nB(t,e);await ol("revenue:traffic-status",r,async()=>{var e;let t,i,n=await (e={X_Tt_Appid:r.appId},t=nZ.genBaseURL("/platform_openapi/microgame/v1/ad/query_traffic_status"),i={X_Tt_Appid:(e||{}).X_Tt_Appid},nZ.request({url:t,method:"GET",headers:i},void 0));return eY(n),{rawResponse:n}})}),nx(i.command("placement-list").description("查询当前小游戏的广告位及其类型、开关和封禁状态").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nB(t,e);await ol("revenue:placement-list",r,async()=>{var e;let t,i,n=await (e={X_Tt_Appid:r.appId},t=nZ.genBaseURL("/platform_openapi/microgame/v1/ad/query_placement"),i={X_Tt_Appid:(e||{}).X_Tt_Appid},nZ.request({url:t,method:"GET",headers:i},void 0)),u=eY(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"]}})}),nx((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=nB(t,e);await ol("revenue:ad-income-query",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:o_,latestDateOffsetDays:1,label:"广告收入"}),rn(r.adPositionTypes,"--ad-position-types",rb(lQ)),rn(r.hosts,"--hosts",rb(lZ)),ri(r.os,"--os",rb(l1)),ri(r.activateType,"--activate-type",rb(l2));let u=await (e={X_Tt_Appid:r.appId,startDate:r.startDate,endDate:r.endDate,adPositionTypes:rf(r.adPositionTypes),hosts:rm(r.hosts,"--hosts",lZ.All),os:rC(r.os,l1),activateType:rC(r.activateType,l2),fromAppPlatform:1,meta:await nS("revenue:ad-income-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(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:l8}})}),nx(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=nB(t,e);await ol("revenue:ad-income-detail",r,async()=>{var e;let t,i,n;rc({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:o_,latestDateOffsetDays:1,label:"广告收入"}),rn(r.adPositionTypes,"--ad-position-types",rb(l0)),rn(r.hosts,"--hosts",rb(l3)),ri(r.os,"--os",rb(l6)),ri(r.activateType,"--activate-type",rb(l4)),ra(r.page,"--page"),rs(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:rf(r.adPositionTypes),hosts:rm(r.hosts,"--hosts",l3.All),os:rC(r.os,l6),activateType:rC(r.activateType,l4),fromAppPlatform:1,meta:await nS("revenue:ad-income-detail"),page:u,pageSize:o},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),a=eY(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:l9,resultMeta:iA({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})}})}),nx((u=f).command("payment-status").description("查询虚拟支付权限及钻石支付、担保支付协议状态").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nB(t,e);await ol("revenue:payment-status",r,async()=>{let[e,t]=await Promise.all([cl(r.appId),cc(r.appId)]);return{rawResponse:{permission:e,protocols:t.map(({response:e,scene:t})=>({scene:t,...e}))}}})}),nx(cd(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=nB(t,e);await ol("revenue:payment-order-list",r,async()=>{var e;let t,i,n;if(rl({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),ri(r.host,"--host",["-1",...lw]),ri(r.os,"--os",cn),ri(r.activateType,"--activate-type",rb(l7)),ri(r.fromAppPlatform,"--from-app-platform",rb(l5)),ri(r.goodType,"--good-type",rb(ce)),ri(r.paymentChannel,"--payment-channel",rb(ct)),ri(r.paymentStatus,"--payment-status",["done","canceled"]),ri(r.transactionType,"--transaction-type",["recharge","pay","add","refund"]),rs(r.keywordType,"--keyword-type",1,3),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,100),!!r.keyword!=!!r.keywordType)throw new l("--keyword-type 与 --keyword 必须同时提供",{error:re.InvalidRange,message:"--keyword-type 与 --keyword 必须同时提供"});let u=r.page??"1",o=r.pageSize??"20",s=ca(r.startDate,r.endDate)?void 0:rC(r.activateType,l7),a=r.keyword&&r.keywordType?{[rg(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,l5),payStatus:r.paymentStatus,changeType:r.transactionType,keyword:a,goodType:rC(r.goodType,ce),orderType:rC(r.paymentChannel,ct),pageNo:u,pageSize:o},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),d=eY(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:rA(e.rechargeAmountFen),isOpenPlatformRefund:e.isOpenPlatformRefund,refundFee:e.refundFee,refundFeeBeforeShare:e.refundFeeBeforeShare,refundFeeAfterShare:e.refundFeeAfterShare,refundRemark:e.refundRemark}));return{rawResponse:c,rows:h,csvHeader:co,resultMeta:iA({returnedCount:h.length,total:p?.totalNum,page:u,pageSize:o})}})}),nx(cd(u.command("payment-income-query").description("查询虚拟支付收入总览、分成、退款和 ARPPU"))).action(async(e,t)=>{let r=nB(t,e);await ol("revenue:payment-income-query",r,async()=>{var e;let t,i,n;rl({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),ri(r.host,"--host",["-1",...lw]),ri(r.os,"--os",cn),ri(r.activateType,"--activate-type",rb(cr)),ri(r.fromAppPlatform,"--from-app-platform",rb(ci));let u=ca(r.startDate,r.endDate)?void 0:rC(r.activateType,cr),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,ci)},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),s=eY(o),a=s?.result?.[0],l=(e,t)=>({recordType:t,date:e?.date,payPerson:e?.payPerson,payTimes:e?.payTimes,arppu:e?.arppu,payMoney:rA(e?.payMoneyFen),payMoneyAfterShare:e?.payMoneyAfterShareDataReady?rA(e.payMoneyAfterShareFen):void 0,payMoneyAfterReduceShare:e?.payMoneyAfterReduceShareDataReady?rA(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:cu}})}),y=r.command("publisher").description("发行人计划"),nx((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=nB(t,e);await ol("publisher:task-list",r,async()=>{let e,t,i,n;rl({startDate:r.startDate,endDate:r.endDate,allowFuture:!1}),ra(r.taskId,"--task-id"),ri(r.taskType,"--task-type",rb(lN)),ri(r.mediaType,"--media-type",lM),ri(r.webStatus,"--web-status",lX),ri(r.biddingMethod,"--bidding-method",lU),ri(r.taskCategory,"--task-category",l$),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,100);let u=rg(r.page,1),o=rg(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,lN),mediaType:rC(r.mediaType,lL),webStatus:rC(r.webStatus,lj),biddingMethod:rC(r.biddingMethod,lP),taskCategory:void 0===r.taskCategory?void 0:rg(r.taskCategory,0),asc:r.asc,offset:String((u-1)*o),limit:String(o)},t=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eY(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:rA(t?.budget),prepaidFreezeAmount:rA(e.prepaidFreezeAmount),securityBudget:rA(t?.securityBudget),totalExpectedNum:t?.totalExpectedNum,expense:rA(e.expense),totalIncome:rA(e.totalIncome),cpaExpense:rA(e.cpaExpense),cpsExpense:rA(e.cpsExpense),adIncomeSettle:rA(e.adIncomeSettle),orderIncomeSettle:rA(e.orderIncomeSettle),newRegisterCnt:e.newRegisterCnt,videoPost:e.videoPost,liveRoomCnt:e.liveRoomCnt,dataProductionDate:e.dataProductionDate,bidCollections:D(t?.bidCollections??[])}});return{rawResponse:s,rows:l,csvHeader:lY,resultMeta:iA({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nx(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=nB(t,e);await ol("publisher:task-detail-query",r,async()=>{let e,t,i,n;rl({startDate:r.startDate,endDate:r.endDate}),ra(r.taskId,"--task-id"),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,100);let u=rg(r.page,1),o=rg(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=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eY(s),l=(a?.detailStats??[]).map(e=>({date:e.date,taskId:e.taskId,taskType:e.taskType,expense:rA(e.expense),totalIncome:rA(e.totalIncome),cpaExpense:rA(e.cpaExpense),cpsExpense:rA(e.cpsExpense),adIncomeSettle:rA(e.adIncomeSettle),adIncomeLongTail:rA(e.adIncomeLongTail),orderIncomeSettle:rA(e.orderIncomeSettle),orderIncomeLongTail:rA(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:rA(e.frozenAmount),breakdownAmount:rA(e.breakdownAmount),yesterdayDataReady:a?.yesterdayDataReady}));return{rawResponse:s,rows:l,csvHeader:lK,resultMeta:iA({returnedCount:l.length,total:a?.total,page:u,pageSize:o})}})}),nx((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=nB(t,e);await ol("publisher:promotion-query",r,async()=>{var e;let t,i,n;rl({startDate:r.startDate,endDate:r.endDate}),ri(r.mediaType,"--media-type",rb(lz));let[u,o]=function(e){rn(e,"--metrics",lJ);let t=rf(e);if(!t||t.length<1||t.length>2)throw new l("--metrics 必须包含一个或两个趋势指标",{error:re.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,lz)},t=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eY(s);return{rawResponse:s,rows:(a?.list??[]).map(e=>({date:e.date,totalConsumptionAmount:rA(e.totalConsumptionAmount),totalRevenueAmount:rA(e.totalRevenueAmount),newActivationCount:e.newActivationCount,componentClickCount:e.componentClickCount})),csvHeader:["date","totalConsumptionAmount","totalRevenueAmount","newActivationCount","componentClickCount"]}})}),nx(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=nB(t,e);await ol("publisher:promotion-detail-list",r,async()=>{var e;let t,i,n;rl({startDate:r.startDate,endDate:r.endDate}),ri(r.mediaType,"--media-type",rb(lz)),ra(r.page,"--page"),rs(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,lz),pageNo:u,pageSize:o},t=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),a=eY(s),l=(a?.settleDetailList??[]).map(e=>({date:e.date,mediaType:e.mediaType,totalConsumptionAmount:rA(e.totalConsumptionAmount),totalRevenueAmount:rA(e.totalRevenueAmount),newActivationCount:e.newActivationCount,firstActiveCount:e.firstActiveCount,componentExposureCount:e.componentExposureCount,componentClickCount:e.componentClickCount,componentClickThroughRate:e.componentClickThroughRate,conversionBillingConsumptionAmount:rA(e.conversionBillingConsumptionAmount),revenueBillingConsumptionAmount:rA(e.revenueBillingConsumptionAmount),revenueUserCount:e.revenueUserCount,iaaRevenueAmount:rA(e.iaaRevenueAmount),iapRevenueAmount:rA(e.iapRevenueAmount)}));return{rawResponse:s,rows:l,csvHeader:lW,resultMeta:iA({returnedCount:l.length,total:a?.totalCount,page:u,pageSize:o})}})}),nx(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=nB(t,e);await ol("publisher:faction-incentive-list",r,async()=>{let e,t,i,n;for(let e of(ra(r.factionId,"--faction-id"),rh(r.taskIds)??[]))ra(e,"--task-ids");ri(r.orderType,"--order-type",lH),ra(r.page,"--page"),rs(r.pageSize,"--page-size",1,100),rn(r.taskTypes,"--task-types",l$),rn(r.taskStatuses,"--task-statuses",lV),rn(r.contentTypes,"--content-types",lM),rn(r.bidTypes,"--bid-types",["-1",...lU]),function(e,t){var r=e,i=t;if(void 0!==r){for(let e of t4(r))if(!t9.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 t4(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:rh(r.taskIds),taskTypes:rm(r.taskTypes,"--task-types",0),taskStatuses:rf(r.taskStatuses),statMonths:rf(r.statMonths),contentTypes:rm(r.contentTypes,"--content-types",100),bidTypes:rm(r.bidTypes,"--bid-types",-1),orderField:r.orderField,orderType:void 0===r.orderType?void 0:rg(r.orderType,0),pageNum:u,pageSize:o},t=nZ.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},nZ.request({url:t,method:"POST",params:i,headers:n},void 0)),a=eY(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:D(e),extraIncentive:D(e.extraIncentive),dataUpdateTime:a?.dataUpdateTime,readyDate:a?.extra?.readyDate,readyTs:a?.extra?.readyTs}));return{rawResponse:s,rows:c,csvHeader:lq,resultMeta:iA({returnedCount:c.length,total:a?.total,page:a?.pageNum??u,pageSize:o})}})}),nx((a=r.command("ability").description("能力中心")).command("customer-service-status-query").description("查询新版抖音客服平台的开通状态").requiredOption("--app-id <appId>","小游戏 appId").addOption(new P("--type <type>","客服类型:im 抖音 IM / platform 抖音客服平台").choices(["im","platform"]))).action(async(e,t)=>{let r=nB(t,e);await ol("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=nZ.genBaseURL("/platform_openapi/microgame/v1/ability/query_im_customer_service_status"),n={X_Tt_Appid:(e||{}).X_Tt_Appid},nZ.request({url:i,method:"GET",headers:n},void 0)).then(e=>(eY(e),["im",e]))),r.type&&"platform"!==r.type||s.push((t={X_Tt_Appid:r.appId},u=nZ.genBaseURL("/platform_openapi/microgame/v1/ability/query_customer_service_status"),o={X_Tt_Appid:t.X_Tt_Appid},nZ.request({url:u,method:"GET",headers:o},void 0)).then(e=>(eY(e),["platform",e]))),{rawResponse:Object.fromEntries(await Promise.all(s))}})}),nx(a.command("rank-list-query").description("查询当前小游戏已有的排行榜配置").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nB(t,e);await ol("ability:rank-list-query",r,async()=>{let e,t,i,n,u=await (e={X_Tt_Appid:r.appId},t=nZ.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},nZ.request({url:t,method:"GET",params:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:o?.rankInfo??[],csvHeader:["uniqueFlag","shortName","updateFrequency","dataType","sortType","dataSuffix","enumValues","isDefault","updateTime"]}})}),nx(a.command("share-template-query").description("查询当前小游戏在分享设置配置的分享模板、审核状态、默认标记和驳回原因").requiredOption("--app-id <appId>","小游戏 appId")).action(async(e,t)=>{let r=nB(t,e);await ol("ability:share-template-query",r,async()=>{var e;let t,i,n=await (e={appIdStr:r.appId,newTemplate:!0},t=nZ.genBaseURL("/platform_openapi/microgame/v1/ability/query_share_setting"),i={appIdStr:e.appIdStr,newTemplate:e.newTemplate},nZ.request({url:t,method:"GET",params:i},void 0)),u=eY(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("性能数据"),nx(g.command("performance-diagnosis-query").description("查询小游戏启动和运行性能诊断结果,包括劣化指标、实际值、标准值、差值及优化建议;当前不提供网络诊断").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--host <host>",nD).option("--date <date>","诊断日期,格式 YYYY-MM-DD").option("--device-level <n>",nw).option("--os <os>","操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony").option("--mp-version <version>","小游戏版本号")).action(async(e,t)=>{let r=nB(t,e);await ol("performance:performance-diagnosis-query",r,async()=>{var e;let t,i,n;ri(r.host,"--host",lF),ri(r.deviceLevel,"--device-level",rb(ly)),ri(r.os,"--os",rb(lE)),ro(r.date,"--date");let u=await (e={X_Tt_Appid:r.appId,hostAid:lD[rg(r.host,0)]??"",date:r.date,deviceLevel:void 0===r.deviceLevel?void 0:rg(r.deviceLevel,0),os:void 0===r.os?void 0:rg(r.os,0),mpVersion:r.mpVersion,meta:await nS("performance:performance-diagnosis-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u),s={group:"main",genreName:o?.genreName??"",engine:o?.engine??"",degradedIndicatorCount:o?.degradedIndicatorCount??0};return{rawResponse:u,rows:[...lI(o?.launchItems,s,"launch"),...lI(o?.runtimeItems,s,"runtime"),...(o?.otherGroups??[]).flatMap(e=>{let t={group:"other",genreName:e.genreName,engine:e.engine,degradedIndicatorCount:e.degradedIndicatorCount};return[...lI(e.launchItems,t,"launch"),...lI(e.runtimeItems,t,"runtime")]})],csvHeader:lx}})}),nx(nI(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=nB(t,e);await ol("performance:startup-performance-query",r,async()=>{var e;let t,i,n;lk(r),rn(r.sections,"--sections",rb(lv)),ri(r.downloadCode,"--download-code",rb(lC)),ru(r.sceneIdList,"--scene-id-list");let u=await (e={X_Tt_Appid:r.appId,filter:{common:lR(r),entranceForm:r.entranceForm,downloadCode:void 0===r.downloadCode?void 0:rg(r.downloadCode,0),sceneIdList:rh(r.sceneIdList)},metrics:rf(r.metrics),sections:rf(r.sections),meta:await nS("performance:startup-performance-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:lO(o?.series),csvHeader:lS}})}),nx(nI(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=nB(t,e);await ol("performance:runtime-performance-query",r,async()=>{var e;let t,i,n;lk(r);let u=await (e={X_Tt_Appid:r.appId,filter:lR(r),includeDeviceBreakdown:r.includeDeviceBreakdown,includeFpsDistribution:r.includeFpsDistribution,includeMemoryDistribution:r.includeMemoryDistribution,metrics:rf(r.metrics),meta:await nS("performance:runtime-performance-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:lO(o?.series),csvHeader:lS}})}),nx(nI(g.command("network-performance-query").description("查询小游戏网络性能数据,包括 request 和 downloadFile 的请求耗时、错误率等指标").option("--metrics <list>","网络性能指标枚举,逗号分隔;不传返回默认指标集"))).action(async(e,t)=>{let r=nB(t,e);await ol("performance:network-performance-query",r,async()=>{var e;let t,i,n;lk(r);let u=await (e={X_Tt_Appid:r.appId,filter:lR(r),metrics:rf(r.metrics),meta:await nS("performance:network-performance-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(u);return{rawResponse:u,rows:lO(o?.series),csvHeader:lS}})}),nx(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>",nv).option("--os <os>",nF).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=nB(t,e);await ol("performance:error-log-query",r,async()=>{var e;let t,i,n;ri(r.host,"--host",rb(lm)),ri(r.os,"--os",rb(lA)),rn(r.logLevelList,"--log-level-list",rb(lg)),function(e){let{maxLookbackDays:t,label:r}=e,i=e.unit??"milliseconds",n=BigInt(e.lookbackTolerance??0),u=rd(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"}),rs(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:rg(r.host,0),os:void 0===r.os?void 0:rg(r.os,0),appVersion:r.appVersion,gameVersion:r.gameVersion,jssdkVersion:r.jssdkVersion,openId:r.openId,traceId:r.traceId,logLevelList:rf(r.logLevelList),filterMsg:rh(r.filterMsg),pageGroupSize:r.pageGroupSize,searchAfter:r.searchAfter,meta:await nS("performance:error-log-query")},t=nZ.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},nZ.request({url:t,method:"POST",data:i,headers:n},void 0)),o=eY(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:lT,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 发布的 ${e6} Skill`).addHelpText("after","\n说明:\n 安装或重新同步本机 Agent Skill\n update 默认会执行同步;需要手动修复 Skill 时再运行本命令\n\n示例:\n $ dymg skills install").action(aV),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(aY),r.command("update").description("更新 CLI 并同步 Skill").option("--target-version <version>","安装指定版本或 dist tag,默认 latest").option("--skip-skills","只更新 CLI,跳过 Skill 同步").addOption(new P("--package-manager <packageManager>","指定全局安装使用的包管理器").choices(n$)).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(aW),c),C=!1,v=!1,w=!1,B=()=>{v&&cf(),v=!0,process.exitCode=130;let e=nL();C&&e||cf();let t=setTimeout(()=>{cf()},200);ch({...e,durationMs:Date.now()-_,success:!1,errorMessage:"命令已中断",errorCode:tr()?.errorCode}).finally(()=>{clearTimeout(t),cf()})};process.once("SIGINT",B),process.once("SIGTERM",B),b.hook("preAction",(e,t)=>{var r,i,n;let u,o;C=!0,r=t,w=!cp.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),tt({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:D(u),errorMessage:void 0,errorCode:void 0})});try{await b.parseAsync(e);let t=nL();if(C&&t){let e=0===Number(process.exitCode??0);await ch({...t,durationMs:Date.now()-_,success:e,errorMessage:e?void 0:tr()?.errorMessage,errorCode:e?void 0:tr()?.errorCode})}C&&w&&0===Number(process.exitCode??0)&&await nQ()}catch(r){let e=r instanceof Error?r.message:String(r),t=nL();if(r instanceof F){process.exitCode=r.exitCode,C&&t&&await ch({...t,durationMs:Date.now()-_,success:0===r.exitCode,errorMessage:0===r.exitCode?void 0:e,errorCode:0===r.exitCode?void 0:nj(r)});return}throw C&&t&&await ch({...t,durationMs:Date.now()-_,success:!1,errorMessage:e,errorCode:nj(r)}),r}finally{process.removeListener("SIGINT",B),process.removeListener("SIGTERM",B)}}(async function(e=process.argv){var t,r;return t={},r=()=>cm(e),te.run(t,r)})().then(async()=>{await y(Number(process.exitCode??0))}).catch(async e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
151
151
  `),await y(1)})})(),__webpack_exports__)exports[__rspack_i]=__webpack_exports__[__rspack_i];Object.defineProperty(exports,"__esModule",{value:!0});