@douyin-minigame/cli 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md
CHANGED
package/dist/cli.js
CHANGED
|
@@ -28,7 +28,7 @@ Expecting one of '${r.join("', '")}'`);let i=`${e}Help`;return this.on(i,e=>{let
|
|
|
28
28
|
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(e=>t.is(e))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}}function U(e){return e.map(e=>{let t,r;if(!e.startsWith("--inspect"))return e;let i="127.0.0.1",u="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])?u=r[3]:i=r[3]):null!==(r=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(t=r[1],i=r[3],u=r[4]),t&&"0"!==u)?`${t}=${i}:${parseInt(u)+1}`:e})}function M(){return!I.env.NO_COLOR&&"0"!==I.env.FORCE_COLOR&&"false"!==I.env.FORCE_COLOR&&(!!I.env.FORCE_COLOR||void 0!==I.env.CLICOLOR_FORCE||void 0)}new $;var q,V,H,z,G,W,J,K,Y,X,Q,Z,ee,et,er,ei,eu,en,eo,es,ea,el,ec,ed,eh,ep,ef,em,eg,eA,eE,ey,eb,e_=((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 eC 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 eD=Object.values(e_);function eF(e){return p(e,eD)&&"string"==typeof e.url}function ev(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 ew(e,t={}){let r,i,u,n,o,{timeoutMs:s=3e4,signal:a,...l}=t;var c,d,h=s,p=e;if(!Number.isInteger(h)||h<=0)throw new eC("timeoutMs must be a positive integer",{code:e_.InvalidArgument,url:p});let f=(c=s,d=a??void 0,r=new AbortController,i=!1,u=!1,n=setTimeout(()=>{u=!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(n),d&&d.removeEventListener("abort",o)},get aborted(){return i},get timedOut(){return u}});try{return await fetch(e,{...l,signal:f.signal})}catch(t){if(f.timedOut)throw new eC(`Request timed out after ${s}ms`,{cause:t,code:e_.Timeout,url:e});if(f.aborted)throw new eC("Request aborted",{cause:t,code:e_.Aborted,url:e});throw new eC("Network request failed",{cause:t,code:e_.Network,url:e})}finally{f.cleanup()}}function eB(e,t,r){let i=typeof t;if("string"!==i&&"number"!==i&&"boolean"!==i)throw new eC(`Invalid query parameter value for "${e}": expected string, number or boolean`,{code:e_.InvalidArgument,url:r})}async function ex(e){try{return await e.text()}catch{return}}async function eS(e,t){if(204===e.status)return;let r=await ex(e)??"";if(0!==r.length)try{return JSON.parse(r)}catch(i){throw new eC("Failed to parse response as JSON",{cause:i,code:e_.InvalidJson,url:t,status:e.status,responseBody:r})}}let eT=async e=>{var t,r,i,u,n,o,s,a,l,c,d,h;let p,f,{request:m}=e,g=(p=function(e){let{url:t}=e;if(/^https?:\/\//i.test(t))return t;let r=e.baseURL?.replace(/\/+$/,"");if(!r)throw new eC("baseURL is required for relative request URLs",{code:e_.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,u]of Object.entries(e))if(null!=u){if(Array.isArray(u)){for(let e of u)null!=e&&(eB(i,e,t),r.append(i,String(e)));continue}eB(i,u,t),r.append(i,String(u))}return r.toString()}(t.params,p),r=p,(i=f)?`${r}${r.includes("?")?"&":"?"}${i}`:r),A=(u=m,u.method?.toUpperCase()??(void 0!==u.data?"POST":"GET")),E=(n=m,"GET"!==(o=A)&&"HEAD"!==o&&void 0!==n.data),b=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)),_=function(e,t,r,i){if(r){var u;if("string"==typeof(u=e.data)||Buffer.isBuffer(u))return e.data;t.has("Content-Type")||t.set("Content-Type","application/json");try{return JSON.stringify(e.data)}catch(e){throw new eC("Failed to serialize request body as JSON",{cause:e,code:e_.InvalidArgument,url:i})}}}(m,b,E,g);(s=b).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 ew(g,{method:A,headers:b,...void 0!==m.timeoutMs?{timeoutMs:m.timeoutMs}:{},...m.signal?{signal:m.signal}:{},...void 0!==m.redirect?{redirect:m.redirect}:{},...void 0!==_?{body:_}:{}});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 ex(t);throw new eC(`Request failed with status ${t.status}`,{code:e_.Status,url:g,status:t.status,responseBody:e})}e.response.data=await eS(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 eC&&l.error.error===e_.Aborted))))throw r;await y((c=m.retry,d=e,h=r,Math.max(0,"function"==typeof c.retryDelayMs?c.retryDelayMs(d,h):c.retryDelayMs??0)))}};class eO{run;constructor(e={}){const t=[...e.middlewares??[],eT];this.run=function(e){return function(t,r){let i=-1;return function u(n){if(n<=i)return Promise.reject(Error("next() called multiple times in middleware"));i=n;let o=n===e.length?void 0:e[n];if(!o)return Promise.resolve(r());try{return Promise.resolve(o(t,()=>u(n+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 eI="dymg",ek="@douyin-minigame/cli",eR="douyin-minigame",ej=`${eI}:oauth`,eL=`${eI} auth login`,eN=`${eL} --no-wait`,eP=`${eL} --resume`,e$=`${eI} auth logout`,eU=(u=new s.AsyncLocalStorage,{run:(e,t)=>u.run({...e},t),update(e){let t=u.getStore();t&&Object.assign(t,e)},get:()=>u.getStore()});function eM(e){eU.update(e)}function eq(){return eU.get()}let eV=[],eH=async(e,t)=>{try{await t()}finally{eM({response:e.response})}},ez=async(e,t)=>{let r=eq()?.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 eG=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isArray.js"),eW=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isFinite.js"),eJ=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isPlainObject.js"),eK=__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isString.js");let eY=require("node:crypto");__webpack_require__("../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isObject.js"),require("node:http"),require("node:net");let eX=require("node:os"),eQ=require("node:fs/promises");class eZ extends Error{constructor(e,t,r,...i){for(const u of(Array.isArray(t)&&(t=t.join(" ").trim()),super(t),void 0!==Error.captureStackTrace&&Error.captureStackTrace(this,eZ),this.code=e,i))for(const e in u){const t=u[e];this[e]=Buffer.isBuffer(t)?t.toString(r.encoding):null==t?t:JSON.parse(JSON.stringify(t))}}}let e1=function(e){let t=[];for(let i=0,u=e.length;i<u;i++){let u=e[i];if(null==u||!1===u)t[i]={disabled:!0};else if("string"==typeof u||"number"==typeof u)t[i]={name:`${u}`};else{var r;if("object"!=typeof(r=u)||null===r||Array.isArray(r))throw new eZ("CSV_INVALID_COLUMN_DEFINITION",["Invalid column definition:","expect a string or a literal object,",`got ${JSON.stringify(u)} at position ${i}`]);if("string"!=typeof u.name)throw new eZ("CSV_OPTION_COLUMNS_MISSING_NAME",["Option columns missing name:",`property "name" is required at position ${i}`,"when column is an object literal"]);t[i]=u}}return t},e2=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}},e0=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 eZ("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 eZ("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 eZ("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 eZ("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=e1(t.columns);else if(void 0===t.columns||null===t.columns||!1===t.columns)t.columns=!1;else throw new eZ("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 eZ("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 eZ("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 eZ("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 eZ("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 eZ("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 eZ("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 eZ("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 eZ("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 eZ("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 eZ("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 eZ("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 eZ("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 eZ("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},e3=function(e){return e.every(e=>null==e||e.toString&&""===e.toString().trim())},e6={utf8:Buffer.from([239,187,191]),utf16le:Buffer.from([255,254])},e4=function(e={}){var t;let r=e0(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 e2(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 e2(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:u,quote:n}=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===u?0:u.length)+n.length:0,o?n.length+a:0)},parse:function(e,t,r,i){let u,n,{bom:o,comment_no_infix:s,encoding:a,from_line:l,ltrim:c,max_record_size:d,raw:h,relax_quotes:p,rtrim:f,skip_empty_lines:m,to:g,to_line:A}=this.options,{comment:E,escape:y,quote:b,record_delimiter:_}=this.options,{bomSkipped:C,previousBuf:D,rawBuffer:F,escapeIsQuote:v}=this.state;if(void 0===D)if(void 0===e)return void i();else u=e;else u=void 0!==D&&void 0===e?D:Buffer.concat([D,e]);if(!1===C)if(!1===o)this.state.bomSkipped=!0;else if(u.length<3){if(!1===t){this.state.previousBuf=u;return}}else{for(let e in e6)if(0===e6[e].compare(u,0,e6[e].length)){let t=e6[e].length;this.state.bufBytesStart+=t,u=u.slice(t);let r=e0({...this.original_options,encoding:e});for(let e in r)this.options[e]=r[e];({comment:E,escape:y,quote:b}=this.options);break}this.state.bomSkipped=!0}let w=u.length;for(n=0;n<w&&!this.__needMoreData(n,w,t);n++){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===_.length&&this.__autoDiscoverRecordDelimiter(u,n)&&(_=this.options.record_delimiter);let e=u[n];if(!0===h&&F.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!==y&&!0===this.state.quoting&&this.__isEscape(u,n,e)&&n+y.length<w)if(v){if(this.__isQuote(u,n+y.length)){this.state.escaping=!0,n+=y.length-1;continue}}else{this.state.escaping=!0,n+=y.length-1;continue}if(!1===this.state.commenting&&this.__isQuote(u,n))if(!0===this.state.quoting){let t=u[n+b.length],r=f&&this.__isCharTrimable(u,n+b.length),i=null!==E&&this.__compareBytes(E,u,n+b.length,t),o=this.__isDelimiter(u,n+b.length,t),s=0===_.length?this.__autoDiscoverRecordDelimiter(u,n+b.length):this.__isRecordDelimiter(t,u,n+b.length);if(null!==y&&this.__isEscape(u,n,e)&&this.__isQuote(u,n+y.length))n+=y.length-1;else if(!t||o||s||i||r){this.state.quoting=!1,this.state.wasQuoting=!0,n+=b.length-1;continue}else if(!1===p){let e=this.__error(new eZ("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(b),n+=b.length-1}else if(0!==this.state.field.length){if(!1===p){let e=this.__infoField(),t=Object.keys(e6).map(e=>!!e6[e].equals(this.state.field.toString())&&e).filter(Boolean)[0],r=this.__error(new eZ("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,n+=b.length-1;continue}if(!1===this.state.quoting){let t=this.__isRecordDelimiter(e,u,n);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(),n+=t-1;continue}if(!0===m&&!1===this.state.wasQuoting&&0===this.state.record.length&&0===this.state.field.length){this.info.empty_lines++,n+=t-1;continue}this.info.bytes=this.state.bufBytesStart+n;let e=this.__onField();if(void 0!==e)return e;this.info.bytes=this.state.bufBytesStart+n+t;let u=this.__onRecord(r);if(void 0!==u)return u;if(-1!==g&&this.info.records>=g){this.state.stop=!0,i();return}}this.state.commenting=!1,n+=t-1;continue}if(this.state.commenting)continue;if(null!==E&&(!1===s||0===this.state.record.length&&0===this.state.field.length)&&0!==this.__compareBytes(E,u,n,e)){this.state.commenting=!0;continue}let o=this.__isDelimiter(u,n,e);if(0!==o){this.info.bytes=this.state.bufBytesStart+n;let e=this.__onField();if(void 0!==e)return e;n+=o-1;continue}}}if(!1===this.state.commenting&&0!==d&&this.state.record_length+this.state.field.length>d)return this.__error(new eZ("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(u,n),o=!1===f||!1===this.state.wasQuoting;if(!0===t&&!0===o)this.state.field.append(e);else{if(!0===f&&!this.__isCharTrimable(u,n))return this.__error(new eZ("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&&(n+=this.__isCharTrimable(u,n)-1);continue}}if(!0===t)if(!0===this.state.quoting){let e=this.__error(new eZ("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+n;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+=n,this.state.previousBuf=u.slice(n);!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:u,from:n,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:h}=this.state;if(!1===d)return this.__resetRecord();let p=h.length;if(!0===t)return!0===c&&e3(h)?void this.__resetRecord():this.__firstLineToColumns(h);if(!1===t&&0===this.info.records&&(this.state.expectedRecordLength=p),p!==this.state.expectedRecordLength){let e=!1===t?new eZ("CSV_RECORD_INCONSISTENT_FIELDS_LENGTH",["Invalid Record Length:",`expect ${this.state.expectedRecordLength},`,`got ${p} on line ${this.info.lines}`],this.options,this.__infoField(),{record:h}):new eZ("CSV_RECORD_INCONSISTENT_COLUMNS",["Invalid Record Length:",`columns length is ${t.length},`,`got ${p} on line ${this.info.lines}`],this.options,this.__infoField(),{record:h});if(!0===o||!0===s&&p<this.state.expectedRecordLength||!0===a&&p>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&&e3(h))return void this.__resetRecord();if(!0===this.state.recordHasError){this.__resetRecord(),this.state.recordHasError=!1;return}if(this.info.records++,1===n||this.info.records>=n){let{objname:n}=this.options;if(!1!==t){let o={};for(let e=0,i=h.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(h[e]):o[t[e].name]=[o[t[e].name],h[e]]:o[t[e].name]=h[e]);if(!0===l||!0===u){let t=Object.assign({record:o},!0===l?{raw:this.state.rawBuffer.toString(i)}:{},!0===u?{info:this.__infoRecord()}:{}),r=this.__push(void 0===n?t:[o[n],t],e);if(r)return r}else{let t=this.__push(void 0===n?o:[o[n],o],e);if(t)return t}}else if(!0===l||!0===u){let t=Object.assign({record:h},!0===l?{raw:this.state.rawBuffer.toString(i)}:{},!0===u?{info:this.__infoRecord()}:{}),r=this.__push(void 0===n?t:[h[n],t],e);if(r)return r}else{let t=this.__push(void 0===n?h:[h[n],h],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 eZ("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=e1(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:u,wasQuoting:n}=this.state;if(!1===u)return this.__resetField();let o=this.state.field.toString(t);if(!0===r&&!1===n&&(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;n:for(let i=0;i<r.length;i++){let u=r[i];for(let r=0;r<u.length;r++)if(u[r]!==e[t+r])continue n;return u.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 u=e.length;for(let i=1;i<u;i++)if(e[i]!==t[r+i])return 0;return u},__isDelimiter:function(e,t,r){let{delimiter:i,ignore_last_delimiters:u}=this.options;if(!0===u&&this.state.record.length===this.options.columns.length-1||!1!==u&&"number"==typeof u&&this.state.record.length===u-1)return 0;n:for(let u=0;u<i.length;u++){let n=i[u];if(n[0]===r){for(let r=1;r<n.length;r++)if(n[r]!==e[t+r])continue n;return n.length}}return 0},__isRecordDelimiter:function(e,t,r){let{record_delimiter:i}=this.options,u=i.length;n:for(let n=0;n<u;n++){let u=i[n],o=u.length;if(u[0]===e){for(let e=1;e<o;e++)if(u[e]!==t[r+e])continue n;return u.length}}return 0},__isEscape:function(e,t,r){let{escape:i}=this.options;if(null===i)return!1;let u=i.length;if(i[0]===r){for(let r=0;r<u;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 u=0;u<i;u++)if(r[u]!==e[t+u])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 u=i[r].length;for(let n=0;n<u;n++)if(i[r][n]!==e[t+n])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,u="string"==typeof e?Error(e):e;if(!i)return u;if(this.state.recordHasError=!0,void 0!==this.options.on_skip)try{this.options.on_skip(u,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}}}},e8=function(e,t={}){"string"==typeof e&&(e=Buffer.from(e));let r=t&&t.objname?{}:[],i=e4(t),u=i.parse(e,!0,e=>{void 0===i.options.objname?r.push(e):r[e[0]]=e[1]},()=>{});if(void 0!==u)throw u;return r},e9=/\\(\\)?/g,e7=RegExp("[^.[\\]]+|\\[(?:([^\"'][^[]*)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))","g"),e5=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,te=/^\w*$/,tt=function(e){var t;let r=typeof e;return"symbol"===r||"object"===r&&e&&"[object Symbol]"===(t=e,Object.prototype.toString.call(t))},tr=function(e,t){if(Array.isArray(e))return!1;let r=typeof e;return!!("number"===r||"symbol"===r||"boolean"===r||!e||tt(e))||te.test(e)||!e5.test(e)||null!=t&&e in Object(t)},ti=function(e){let t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(e7,function(e,r,i,u){let n=e;i?n=u.replace(e9,"$1"):r&&(n=r.trim()),t.push(n)}),t},tu=function(e){if("string"==typeof e||tt(e))return e;let t=`${e}`;return"0"==t&&1/e==-1/0?"-0":t},tn=function(e,t){var r,i;r=t,i=e;let u=0,n=(t=Array.isArray(r)?r:tr(r,i)?[r]:ti(r)).length;for(;null!=e&&u<n;)e=e[tu(t[u++])];return u&&u===n?e:void 0},to=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 ts 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,ts),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 ta=function(e){let t={};for(let r in e)t[r.replace(/([A-Z])/g,function(e,t){return"_"+t.toLowerCase()})]=e[r];if(void 0===t.bom||null===t.bom||!1===t.bom)t.bom=!1;else if(!0!==t.bom)return[new ts("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 ts("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 ts("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 ts("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 ts("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 ts("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 ts("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]=to(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]},tl=Buffer.from([239,187,191]),tc=function(e,t={}){let r=[],[i,u]=ta(t);if(void 0!==i)throw i;let n={options:u,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]=to(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 u=e[r],[n,o]=this.__cast(u,{index:r,column:r,records:this.info.records,header:t});if(n)return[n];i[r]=[o,u]}}else for(let u=0;u<r.length;u++){let n=tn(e,r[u].key),[o,s]=this.__cast(n,{index:u,column:r[u].key,records:this.info.records,header:t});if(o)return[o];i[u]=[s,n]}let u="";for(let e=0;e<i.length;e++){let t,r,[o,s]=i[e];if("string"==typeof o)t=this.options;else{var n;if("object"!=typeof(n=o)||null===n||Array.isArray(n))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]=ta(t),void 0!==r)return[r]}}let{delimiter:a,escape:l,quote:c,quoted:d,quoted_empty:h,quoted_string:p,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===h||!0===p&&!1!==h)&&(o=c+o+c),u+=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,n=p&&"string"==typeof s,h=f&&f.filter(e=>"string"==typeof e?-1!==o.indexOf(e):e.test(o));if(h=h&&h.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||n||h;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),u+=o}else(!0===h||""===s&&!0===p&&!1!==h)&&(u+=c+c);e!==i.length-1&&(u+=a)}return[void 0,u]},bom:function(e){!0===this.options.bom&&e(tl)},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=n.__transform(t,function(e){r.push(e)});if(void 0!==e)throw e}if(0===r.length){n.bom(e=>{r.push(e)});let e=n.headers(e=>{r.push(e)});if(void 0!==e)throw e}return r.join("")};function td(e,t){var r,i;let u,n=(0,T.resolve)(e),o=(0,T.resolve)(n,t);if(r=n,i=o,u=r.endsWith(T.sep)?r:`${r}${T.sep}`,!(i===r||i.startsWith(u)))throw new l(`Storage path escapes baseDir: ${t}`,{error:"INVALID_STORAGE_PATH",details:{baseDir:n,filePath:t,resolvedPath:o}});return o}async function th(e,t){await (0,eQ.mkdir)((0,T.dirname)(e),{recursive:!0,mode:t})}var tp=((V={}).NotFound="ENOENT",V.StorageError="FILE_STORAGE_ERROR",V.InvalidJson="INVALID_JSON",V.InvalidCsv="INVALID_CSV",V),tf=((H={}).ReadText="readText",H.WriteText="writeText",H.Remove="remove",H.ReadJson="readJson",H.WriteJson="writeJson",H.ReadCsv="readCsv",H.WriteCsv="writeCsv",H);class tm extends l{filePath;operation;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="FileStorageError",this.filePath=t.filePath,this.operation=t.operation}}class tg extends tm{constructor(e,t,r){super(`File not found: ${e}`,{cause:r,code:"ENOENT",filePath:e,operation:t}),this.name="FileNotFoundError"}}let tA=Object.values(tp),tE=f("ENOENT");function ty(e,t,r){var i;return p(e,tA)?e:(i=e)instanceof Error&&"string"==typeof i.code&&"ENOENT"===e.code?new tg(t,r,e):new tm(`Failed to ${r} for file: ${t}`,{cause:e,code:"FILE_STORAGE_ERROR",filePath:t,operation:r})}function tb(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 t_(e,t){try{let r=await (0,eQ.stat)(e);Date.now()-r.mtimeMs>t&&await (0,eQ.unlink)(e)}catch(e){if("ENOENT"!==e.code)throw e}}async function tC(e,t,r={}){let{retryMs:i,staleMs:u,timeoutMs:n}=function(e){let t={retryMs:tb(e.retryMs,50,"retryMs"),staleMs:tb(e.staleMs,15e3,"staleMs"),timeoutMs:tb(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()+n;for(await th(o);;)try{let e=await (0,eQ.open)(o,"wx",384);await e.close();break}catch(e){if("EEXIST"!==e.code)throw e;if(await t_(o,u),Date.now()>=s)throw new tm(`Timed out acquiring file lock: ${o}`,{cause:e,code:tp.StorageError,filePath:o,operation:tf.WriteText});await y(i)}try{return await t()}finally{await (0,eQ.unlink)(o).catch(e=>{if("ENOENT"!==e.code)throw e})}}class tD{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,O.mkdirSync)(this.baseDir,{recursive:!0,mode:t}),void 0!==t&&(511&(0,O.statSync)(this.baseDir).mode)!==t&&(0,O.chmodSync)(this.baseDir,t)}}async readText(e,t="utf8"){let r=td(this.baseDir,e);try{return await (0,eQ.readFile)(r,{encoding:t})}catch(e){throw ty(e,r,tf.ReadText)}}async writeText(e,t,r={}){let i=r.encoding??"utf8",{mode:u}=r,n=td(this.baseDir,e),o=(0,T.join)((0,T.dirname)(n),`.${(0,T.basename)(n)}.${(0,eY.randomUUID)()}.tmp`);try{await th(n),await (0,eQ.writeFile)(o,t,{encoding:i,mode:u}),void 0!==u&&await (0,eQ.chmod)(o,u),await (0,eQ.rename)(o,n)}catch(e){throw await (0,eQ.rm)(o,{force:!0}).catch(()=>void 0),ty(e,n,tf.WriteText)}}async remove(e){let t=td(this.baseDir,e);try{await (0,eQ.rm)(t)}catch(e){throw ty(e,t,tf.Remove)}}async readJson(e,t="utf8"){let r=td(this.baseDir,e),i=await this.readText(e,t);try{return JSON.parse(i)}catch(e){throw new tm(`Failed to parse JSON file: ${r}`,{cause:e,code:tp.InvalidJson,filePath:r,operation:tf.ReadJson})}}async writeJson(e,t,r={}){let i=r.encoding??"utf8",u=r.spaces??2,n=`${JSON.stringify(t,null,u)}
|
|
29
29
|
`;await this.writeText(e,n,{encoding:i,mode:r.mode})}async readCsv(e,t={}){let r=td(this.baseDir,e),i=await this.readText(e),u=t.delimiter??",";try{if(!1===t.hasHeader)return e8(i,{bom:!0,delimiter:u,relax_column_count:!0,skip_empty_lines:!0});return e8(i,{bom:!0,columns:!0,delimiter:u,relax_column_count:!0,skip_empty_lines:!0})}catch(e){throw new tm(`Failed to parse CSV file: ${r}`,{cause:e,code:tp.InvalidCsv,filePath:r,operation:tf.ReadCsv})}}async writeCsv(e,t,r={}){let i=r.encoding??"utf8",u=r.delimiter??",";try{let n="";0===t.length?r.header?.length&&(n=tc([],{columns:r.header,delimiter:u,header:!0})):n=Array.isArray(t[0])?tc(t,{delimiter:u}):tc(t,{columns:r.header??Array.from(new Set(t.flatMap(e=>Object.keys(e)))),delimiter:u,header:!0}),await this.writeText(e,n.endsWith("\n")?n:`${n}
|
|
30
30
|
`,{encoding:i,mode:r.mode})}catch(r){if(p(r,tA))throw r;let t=td(this.baseDir,e);throw new tm(`Failed to write CSV file: ${t}`,{cause:r,code:tp.StorageError,filePath:t,operation:tf.WriteCsv})}}}var tF=((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),tv=((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 tw 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 tB extends tw{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 tx extends tw{constructor(e,t,r){super(`Sensitive data not found: ${e}`,{cause:r,code:"DATA_NOT_FOUND",filePath:e,operation:t}),this.name="SensitiveDataNotFoundError"}}class tS extends tw{constructor(e,t,r){super(`Failed to decrypt sensitive data: ${e}`,{cause:r,code:"DECRYPTION_FAILED",filePath:e,operation:t}),this.name="SensitiveDecryptionError"}}class tT extends tw{constructor(e,t,r){super(`Invalid sensitive data envelope: ${e}`,{cause:r,code:"INVALID_ENVELOPE",filePath:e,operation:t}),this.name="SensitiveEnvelopeError"}}class tO extends tw{constructor(e,t){super(e,{cause:t.cause,code:t.code??"KEY_STORAGE_ERROR",filePath:t.filePath,operation:t.operation}),this.name="SensitiveKeyStorageError"}}class tI extends tO{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 tk=f("KEY_NOT_FOUND"),tR=f("DATA_NOT_FOUND");function tj(e){return e?e.split(",").map(e=>e.trim()).filter(e=>""!==e):[]}f("DECRYPTION_FAILED"),f("INVALID_ENVELOPE");let tL=/^\d{4}-\d{2}-\d{2}$/,tN=/^-?(0|[1-9]\d*)$/,tP=/^[1-9]\d*$/;function t$(e){return String(e).padStart(2,"0")}function tU(e){let t=e.getFullYear(),r=t$(e.getMonth()+1),i=t$(e.getDate());return`${t}-${r}-${i}`}function tM(e,t,r){if(void 0!==e&&!r.includes(e))throw new l(`参数 ${t} 取值非法: ${e}`,{error:"INVALID_ENUM",message:`${t} 只能取 ${r.join(" / ")}`})}function tq(e,t,r){if(void 0!==e){for(let i of tj(e))if(!r.includes(i))throw new l(`参数 ${t} 包含非法取值: ${i}`,{error:"INVALID_ENUM",message:`${t} 每一项只能取 ${r.join(" / ")}`})}}function tV(e,t){if(void 0===e)return;let r=new Date(`${e}T00:00:00Z`);if(!tL.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 tH(e,t,r,i){if(void 0===e)return;let u=tN.test(e)?Number(e):NaN;if(!Number.isInteger(u)||u<r||u>i)throw new l(`参数 ${t} 超出范围: ${e}`,{error:"INVALID_RANGE",message:`${t} 必须是 ${r}~${i} 之间的整数`})}function tz(e,t){if(void 0!==e&&!tP.test(e))throw new l(`参数 ${t} 非法: ${e}`,{error:"INVALID_POSITIVE_INT",message:`${t} 必须是正整数`})}function tG(e){let{startDate:t,endDate:r,maxLookbackDays:i,label:u}=e,n=e.startField??"--start-date",o=e.endField??"--end-date";if(tV(t,n),tV(r,o),t&&r&&t>r)throw new l(`${n} 不能晚于 ${o}`,{error:"INVALID_DATE_RANGE",message:`${n}(${t}) 不能晚于 ${o}(${r})`});let s=tU(new Date),a=tU(new Date(Date.now()-864e5*i));for(let[e,c]of[[n,t],[o,r]])if(c){if(c>s)throw new l(`${e} 不能晚于今天`,{error:"INVALID_DATE_RANGE",message:`${e}(${c}) 不能晚于今天(${s})`});if(c<a)throw new l(`${u}仅支持最近 ${i} 天的数据`,{error:"OUT_OF_LOOKBACK",message:`${u}仅支持最近 ${i} 天的数据,${e}(${c}) 已超出范围`})}}function tW(e){let t=tj(e);return t.length>0?t:void 0}function tJ(e){let t=tW(e);if(!t)return;let r=t.map(Number).filter(e=>!Number.isNaN(e));return r.length>0?r:void 0}function tK(e,t){if(void 0===e)return t;let r=tN.test(e)?Number(e):NaN;return Number.isNaN(r)?t:r}function tY(e){if("number"==typeof e&&Number.isInteger(e)&&e>0)return e;if("string"!=typeof e||!tN.test(e))return;let t=Number(e);return t>0?t:void 0}function tX(e){return String(e).padStart(2,"0")}function tQ(e,t={}){if(void 0===e||""===e)return"";let{format:r="datetime",unit:i="s"}=t,u=Number(e);if(!Number.isFinite(u))return String(e);let n=new Date("s"===i?1e3*u:u);if(Number.isNaN(n.getTime()))return String(e);let o=n.getFullYear(),s=tX(n.getMonth()+1),a=tX(n.getDate());if("date"===r)return`${o}-${s}-${a}`;let l=tX(n.getHours()),c=tX(n.getMinutes()),d=tX(n.getSeconds());return`${o}-${s}-${a} ${l}:${c}:${d}`}function tZ(e){return Object.values(e).filter(e=>"number"==typeof e).map(String)}function t1(e,t){let r="number"==typeof t?t:tN.test(t)?Number(t):NaN;return"string"==typeof e[r]?String(e[r]):String(t)}let t2=new Set(["access_denied","expired_token","invalid_client","invalid_grant","unauthorized_client"]);var t0=((W={}).InvalidArgument="INVALID_ARGUMENT",W.PortUnavailable="PORT_UNAVAILABLE",W.CallbackAborted="CALLBACK_ABORTED",W.CallbackTimeout="CALLBACK_TIMEOUT",W.CallbackError="CALLBACK_ERROR",W.RequestAborted="REQUEST_ABORTED",W.RequestTimeout="REQUEST_TIMEOUT",W.NetworkError="NETWORK_ERROR",W.HttpError="HTTP_ERROR",W.InvalidResponse="INVALID_RESPONSE",W.AuthorizationPending="AUTHORIZATION_PENDING",W.SlowDown="SLOW_DOWN",W.AccessDenied="ACCESS_DENIED",W.ExpiredToken="EXPIRED_TOKEN",W),t3=((J={}).GeneratePKCE="generatePKCE",J.GenerateState="generateState",J.BuildAuthUrl="buildAuthUrl",J.BuildLoopbackRedirectUri="buildLoopbackRedirectUri",J.GetAvailablePort="getAvailablePort",J.CreateLocalCallbackHandler="createLocalCallbackHandler",J.HandleLocalCallback="handleLocalCallback",J.ExchangeToken="exchangeToken",J.IntrospectToken="introspectToken",J.RevokeToken="revokeToken",J.FetchAuthorizationServerMetadata="fetchAuthorizationServerMetadata",J.DynamicClientRegistration="dynamicClientRegistration",J.StartDeviceAuthorization="startDeviceAuthorization",J.ExchangeDeviceCodeToken="exchangeDeviceCodeToken",J.PollDeviceToken="pollDeviceToken",J.CreateDeviceFlowSession="createDeviceFlowSession",J);class t6 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 t4 extends t6{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 t8 extends t6{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 t9 extends t6{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 t7 extends t6{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 t5=Object.values(t0);function re(e){if(!p(e,t5)||"exchangeToken"!==e.operation)return!1;let t=e.responseJson,r=t?.error;return"string"==typeof r&&t2.has(r)}var rt=((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),rr=((Y={}).Read="read",Y.Save="save",Y.Clear="clear",Y.Refresh="refresh",Y);class ri extends l{operation;constructor(e,t){super(e,{cause:t.cause,error:t.code}),this.name="OAuthTokenStoreError",this.operation=t.operation}}Object.values(rt);let ru=f("NOT_FOUND");function rn(e){var t;return eJ(e)&&(t=e.auth,!!eJ(t)&&ra(t.accessToken)&&ra(t.refreshToken)&&rs(t.atExpiresAt)&&rs(t.rtExpiresAt)&&eG(t.scopes)&&t.scopes.every(eK))}function ro(e,t,r){if(!r(e))throw new ri("Invalid OAuth token snapshot shape",{code:rt.InvalidShape,operation:t})}function rs(e){return eW(e)&&Number.isInteger(e)&&e>0&&e<1e10}function ra(e){return eK(e)&&""!==e.trim()}function rl(e,t=Date.now()){return e<=Math.floor(t/1e3)}class rc{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??rn}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(ru(e))return;throw e}}async save(e){ro(e,rr.Save,this.validate),this.writeEpoch+=1;try{await this.storage.writeJson(this.fileName,e)}catch(e){throw new ri(`Failed to persist OAuth token snapshot: ${this.fileName}`,{cause:e,code:rt.StorageError,operation:rr.Save})}this.cache={snapshot:e,loadedAt:this.now()}}async clear(){this.writeEpoch+=1;try{try{await this.storage.remove(this.fileName)}catch(e){if(!tR(e))throw e}await this.storage.removeKey()}catch(e){throw new ri(`Failed to clear OAuth token snapshot: ${this.fileName}`,{cause:e,code:rt.StorageError,operation:rr.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 ri("OAuth access token has expired and no refresh function provided",{code:rt.AccessTokenExpired,operation:rr.Refresh});return(await this.refresh(t,e)).auth.accessToken}async refresh(e,t){return!1===this.refreshLockPath?this.refreshCurrent(e,t):tC(this.refreshLockPath,async()=>{this.invalidateCache();let r=await this.tryGet();if(!r)throw new ri(`OAuth token snapshot not found: ${this.fileName}`,{code:rt.NotFound,operation:rr.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 ri("OAuth refresh token has expired, re-login is required",{code:rt.RefreshTokenExpired,operation:rr.Refresh});if(this.refreshInflight)return this.refreshInflight;let r=this.writeEpoch,i=(async()=>{let i;try{i=await t(e)}catch(e){throw new ri("Failed to refresh OAuth tokens",{cause:e,code:rt.RefreshFailed,operation:rr.Refresh})}if(this.writeEpoch!==r)throw new ri("OAuth token refresh result is stale",{code:rt.RefreshFailed,operation:rr.Refresh});return ro(i,rr.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 rl(e.rtExpiresAt,this.now())}async loadFromStorage(){let e,t=this.writeEpoch;try{e=await this.storage.readJson(this.fileName)}catch(e){if(tR(e))throw new ri(`OAuth token snapshot not found: ${this.fileName}`,{cause:e,code:rt.NotFound,operation:rr.Read});throw new ri(`Failed to read OAuth token snapshot: ${this.fileName}`,{cause:e,code:rt.StorageError,operation:rr.Read})}return ro(e,rr.Read,this.validate),this.writeEpoch===t&&(this.cache={snapshot:e,loadedAt:this.now()}),e}}let rd=new eO,rh=new Set(["grant_type","client_id","code","redirect_uri","code_verifier","refresh_token","device_code","scope"]),rp=new Set(["client_id","scope","code_challenge","code_challenge_method"]);function rf(e){return Array.isArray(e)?e.map(e=>e.trim()).filter(Boolean).join(" ")||void 0:e?.trim()||void 0}function rm(e,t,r,i){if(t)for(let[u,n]of Object.entries(t)){if(r.has(u.toLowerCase()))throw new t6(`extraParams cannot override reserved OAuth parameter: ${u}`,{code:t0.InvalidArgument,operation:i});rg(e,u,n)}}function rg(e,t,r){null!=r&&e.set(t,String(r))}function rA(e){if(e.trim())try{let t=JSON.parse(e);if(eJ(t))return t;return}catch{return}}function rE(e){return eF(e)?e.error===e_.Timeout?t0.RequestTimeout:e.error===e_.Aborted?t0.RequestAborted:t0.NetworkError:t0.NetworkError}function ry(e,t,r){try{return new URL(e)}catch(e){throw new t6(`Invalid ${r}`,{cause:e,code:t0.InvalidArgument,operation:t})}}function rb(e,t,r){if(!eK(e)||""===e.trim())throw new t6(`${t} must be a non-empty string`,{code:t0.InvalidArgument,operation:r})}function r_(e,t,r){if(!Number.isInteger(e)||e<=0)throw new t6(`${t} must be a positive integer`,{code:t0.InvalidArgument,operation:r})}async function rC(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??rd).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 t7("OAuth device flow endpoint returned an empty response",{code:t0.InvalidResponse,operation:e.operation});let u=i.status,n=await i.text(),o=rA(n),s=eK(o?.error)?o.error:void 0,a=eK(o?.error_description)?o.error_description:void 0;if(void 0===u)throw new t7("OAuth device flow endpoint returned an invalid response",{code:t0.NetworkError,operation:e.operation,responseBody:n,responseJson:o});if(u>=500)throw new t7(`OAuth device flow endpoint returned HTTP ${u}`,{code:t0.HttpError,operation:e.operation,providerError:s,providerErrorDescription:a,responseBody:n,responseJson:o,status:u});if(s){var r;throw new t7(`OAuth device flow endpoint returned error: ${s}`,{code:(r=s,"authorization_pending"===r?t0.AuthorizationPending:"slow_down"===r?t0.SlowDown:"access_denied"===r?t0.AccessDenied:"expired_token"===r?t0.ExpiredToken:t0.InvalidResponse),operation:e.operation,providerError:s,providerErrorDescription:a,responseBody:n,responseJson:o,status:u})}if(u<200||u>=300)throw new t7(`OAuth device flow endpoint returned HTTP ${u}`,{code:t0.HttpError,operation:e.operation,responseBody:n,responseJson:o,status:u});if(!o)throw new t7("OAuth device flow endpoint returned a non-JSON response",{code:t0.InvalidResponse,operation:e.operation,responseBody:n,status:u});return o}catch(t){if(t instanceof t7)throw t;throw new t7("OAuth device flow request failed",{cause:t,code:rE(t),operation:e.operation})}}function rD(e,t,r){let i=Math.min(e,Math.max(0,t-Date.now()));return i<=0?Promise.resolve():r?.aborted?Promise.reject(new t7("OAuth device token polling was aborted",{code:t0.RequestAborted,operation:t3.PollDeviceToken})):new Promise((e,t)=>{let u=setTimeout(()=>{r?.removeEventListener("abort",n),e()},i),n=()=>{clearTimeout(u),t(new t7("OAuth device token polling was aborted",{code:t0.RequestAborted,operation:t3.PollDeviceToken}))};r?.addEventListener("abort",n,{once:!0})})}function rF(e,t){rb(e.clientId,"clientId",t3.ExchangeDeviceCodeToken),rb(e.deviceCode,"deviceCode",t3.ExchangeDeviceCodeToken),r_(t,"timeoutMs",t3.ExchangeDeviceCodeToken),void 0!==e.codeVerifier&&rb(e.codeVerifier,"codeVerifier",t3.ExchangeDeviceCodeToken)}function rv(e,t){if(!eK(e)||""===e.trim())throw new t7(`${t} must be a non-empty string`,{code:t0.InvalidResponse,operation:t3.StartDeviceAuthorization})}function rw(e,t,r){if(!Number.isInteger(e)||e<=0)throw new t7(`${t} must be a positive integer`,{code:t0.InvalidResponse,operation:t3.StartDeviceAuthorization,responseJson:r})}function rB(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 rx(e){let t=ry(e.deviceAuthorizationEndpoint,t3.StartDeviceAuthorization,"deviceAuthorizationEndpoint"),r=e.timeoutMs??15e3;var i=e,u=r;if(rb(i.clientId,"clientId",t3.StartDeviceAuthorization),r_(u,"timeoutMs",t3.StartDeviceAuthorization),void 0!==i.codeChallenge&&rb(i.codeChallenge,"codeChallenge",t3.StartDeviceAuthorization),void 0!==i.codeChallengeMethod&&rb(i.codeChallengeMethod,"codeChallengeMethod",t3.StartDeviceAuthorization),void 0===i.codeChallenge!=(void 0===i.codeChallengeMethod))throw new t7("codeChallenge and codeChallengeMethod must be provided together",{code:t0.InvalidArgument,operation:t3.StartDeviceAuthorization});let n=new URLSearchParams;n.set("client_id",e.clientId),rg(n,"scope",rf(e.scope)),rg(n,"code_challenge",e.codeChallenge),rg(n,"code_challenge_method",e.codeChallengeMethod),rm(n,e.extraParams,rp,t3.StartDeviceAuthorization);let o=await rC({body:n,endpoint:t,httpClient:e.httpClient,headers:e.headers,operation:t3.StartDeviceAuthorization,signal:e.signal,timeoutMs:r});var s=o;if(rv(s.device_code,"device_code"),rv(s.user_code,"user_code"),rv(s.verification_uri,"verification_uri"),void 0!==s.verification_uri_complete&&rv(s.verification_uri_complete,"verification_uri_complete"),"number"!=typeof s.expires_in)throw new t7("expires_in must be a positive integer",{code:t0.InvalidResponse,operation:t3.StartDeviceAuthorization,responseJson:s});if(rw(s.expires_in,"expires_in",s),void 0!==s.interval){if("number"!=typeof s.interval)throw new t7("interval must be a positive integer",{code:t0.InvalidResponse,operation:t3.StartDeviceAuthorization,responseJson:s});rw(s.interval,"interval",s)}return o}async function rS(e){let t=ry(e.tokenEndpoint,t3.ExchangeDeviceCodeToken,"tokenEndpoint"),r=e.timeoutMs??15e3;rF(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),rg(i,"code_verifier",e.codeVerifier),rm(i,e.extraParams,rh,t3.ExchangeDeviceCodeToken);let u=await rC({body:i,endpoint:t,httpClient:e.httpClient,headers:e.headers,operation:t3.ExchangeDeviceCodeToken,signal:e.signal,timeoutMs:r});if("string"!=typeof u.access_token||""===u.access_token.trim())throw new t7("OAuth device token response is missing access_token",{code:t0.InvalidResponse,operation:t3.ExchangeDeviceCodeToken,responseJson:u});return u}async function rT(e){var t,r,i,u,n;let o=e.intervalSeconds??5;t=e,r=o,rF(t,t.timeoutMs??15e3),r_(r,"intervalSeconds",t3.PollDeviceToken),void 0!==t.expiresInSeconds&&r_(t.expiresInSeconds,"expiresInSeconds",t3.PollDeviceToken),void 0!==t.pollTimeoutMs&&r_(t.pollTimeoutMs,"pollTimeoutMs",t3.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===(u=l)?1/0:i+u,void 0===(n=e.pollTimeoutMs)?i+(void 0===u?6e5:1/0):i+n));for(;Date.now()<c;)try{return await rS(e)}catch(t){if(!(t instanceof t7))throw t;if(t.error===t0.AuthorizationPending){await rD(s,c,e.signal);continue}if(t.error===t0.SlowDown){s+=5e3,await rD(s,c,e.signal);continue}if(t.error===t0.RequestTimeout||t.error===t0.NetworkError){await rD(s,c,e.signal);continue}throw t}throw new t7("Timed out waiting for OAuth device authorization",{code:t0.ExpiredToken,operation:t3.PollDeviceToken,details:{expiresInSeconds:e.expiresInSeconds,pollTimeoutMs:e.pollTimeoutMs}})}async function rO(e){let t=function(e){if(void 0!==e.codeChallenge||void 0!==e.codeChallengeMethod){if(!e.codeChallenge||!e.codeChallengeMethod)throw new t7("codeChallenge and codeChallengeMethod must be provided together",{code:t0.InvalidArgument,operation:t3.CreateDeviceFlowSession});if(!e.codeVerifier)throw new t7("codeVerifier is required when custom PKCE parameters are provided",{code:t0.InvalidArgument,operation:t3.CreateDeviceFlowSession});return{codeVerifier:e.codeVerifier,codeChallenge:e.codeChallenge,codeChallengeMethod:e.codeChallengeMethod}}return function(e={}){let t=e.verifierByteLength??32;var r,i,u=t,n=t3.GeneratePKCE;if(!Number.isInteger(u)||u<32||u>96)throw new t6("verifierByteLength must be an integer between 32 and 96",{code:t0.InvalidArgument,operation:n});let o=(r=t,(0,eY.randomBytes)(r).toString("base64url")),s=(i=o,(0,eY.createHash)("sha256").update(i).digest("base64url"));return{codeVerifier:o,codeChallenge:s,codeChallengeMethod:"S256"}}({verifierByteLength:e.verifierByteLength})}(e),r=await rx({...e,codeChallenge:t.codeChallenge,codeChallengeMethod:t.codeChallengeMethod});return{authorization:r,codeVerifier:t.codeVerifier,codeChallenge:t.codeChallenge,codeChallengeMethod:t.codeChallengeMethod,pollToken:()=>rT({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 rI(e){return e.replace(/[^a-zA-Z0-9]+/g,"")}function rk(e,t,r){let i=e[t];if(eK(i)&&i.trim())return i;throw new t6(`OAuth response is missing ${t}`,{code:t0.InvalidResponse,operation:r,details:{field:t}})}async function rR(e){let t=ry(e.url,e.operation,"url"),r={...e.headers,Accept:"application/json"};void 0!==e.body&&(r["Content-Type"]="application/json");try{let{data:n}=await (e.httpClient??rd).send({url:t.toString(),method:e.method,headers:r,data:e.body,timeoutMs:e.timeoutMs??15e3,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!n)throw new t6("OAuth endpoint returned an empty response",{code:t0.InvalidResponse,operation:e.operation});let o=n.status,s=await n.text(),a=rA(s);if(void 0===o||o<200||o>=300)throw new t6(`OAuth endpoint returned HTTP ${o??"unknown"}`,{code:t0.HttpError,operation:e.operation,status:o,details:{responseBody:s,responseJson:a}});var i=a,u=e.operation;if(eJ(i))return i;throw new t6("OAuth endpoint returned an invalid JSON object",{code:t0.InvalidResponse,operation:u})}catch(t){if(t instanceof t6)throw t;throw new t6("OAuth request failed",{cause:t,code:rE(t),operation:e.operation})}}async function rj(e){let t,r=await rR({url:e.metadataEndpoint,method:"GET",headers:e.headers,timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient,operation:t3.FetchAuthorizationServerMetadata});return{issuer:eK(r.issuer)&&r.issuer.trim()?r.issuer.trim():void 0,tokenEndpoint:rk(r,"token_endpoint",t3.FetchAuthorizationServerMetadata),introspectionEndpoint:rk(r,"introspection_endpoint",t3.FetchAuthorizationServerMetadata),revocationEndpoint:rk(r,"revocation_endpoint",t3.FetchAuthorizationServerMetadata),deviceAuthorizationEndpoint:rk(r,"device_authorization_endpoint",t3.FetchAuthorizationServerMetadata),registrationEndpoint:rk(r,"registration_endpoint",t3.FetchAuthorizationServerMetadata),scopesSupported:(t=r.scopes_supported,eG(t)?t.filter(e=>eK(e)&&""!==e.trim()):[]),raw:r}}async function rL(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 rR({url:e.registrationEndpoint,method:"POST",headers:e.headers,body:JSON.stringify(t),timeoutMs:e.timeoutMs,signal:e.signal,httpClient:e.httpClient,operation:t3.DynamicClientRegistration});return{clientId:rk(r,"client_id",t3.DynamicClientRegistration),raw:r}}async function rN(e){let t=ry(e.tokenEndpoint,t3.ExchangeToken,"tokenEndpoint"),r=e.grantType??"authorization_code",i=e.timeoutMs??15e3;!function(e,t,r){if(rb(e.clientId,"clientId",t3.ExchangeToken),r_(r,"timeoutMs",t3.ExchangeToken),"authorization_code"===t){rb(e.code,"code",t3.ExchangeToken),rb(e.redirectUri,"redirectUri",t3.ExchangeToken),void 0!==e.codeVerifier&&rb(e.codeVerifier,"codeVerifier",t3.ExchangeToken);return}if("refresh_token"===t)return rb(e.refreshToken,"refreshToken",t3.ExchangeToken);throw new t6(`Unsupported OAuth grant type: ${t}`,{code:t0.InvalidArgument,operation:t3.ExchangeToken})}(e,r,i);let u=new URLSearchParams;u.set("grant_type",r),u.set("client_id",e.clientId),"authorization_code"===r?(u.set("code",e.code),u.set("redirect_uri",e.redirectUri),rg(u,"code_verifier",e.codeVerifier)):(u.set("refresh_token",e.refreshToken),rg(u,"scope",rf(e.scope))),rm(u,e.extraParams,rh,t3.ExchangeToken);let n={...e.headers,Accept:"application/json","Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"};try{let{data:r}=await (e.httpClient??rd).send({url:t.toString(),method:"POST",headers:n,data:u.toString(),timeoutMs:i,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!r)throw new t4("OAuth token endpoint returned an empty response",{code:t0.InvalidResponse});let o=r.status,s=await r.text(),a=rA(s),l=eK(a?.error)?a.error:void 0;if(void 0===o||o<200||o>=300)throw new t4(`OAuth token endpoint returned HTTP ${o??"unknown"}`,{code:t0.HttpError,responseBody:s,responseJson:a,status:o});if(l)throw new t4(`OAuth token endpoint returned error: ${l}`,{code:t0.InvalidResponse,responseBody:s,responseJson:a,status:o});if(!a)throw new t4("OAuth token endpoint returned a non-JSON response",{code:t0.InvalidResponse,responseBody:s,status:o});if(!eK(a.access_token)||""===a.access_token.trim())throw new t4("OAuth token response is missing access_token",{code:t0.InvalidResponse,responseBody:s,responseJson:a,status:o});return a}catch(e){if(e instanceof t4)throw e;throw new t4("OAuth token request failed",{cause:e,code:rE(e)})}}async function rP(e){var t,r,i;let u=ry(e.introspectionEndpoint,t3.IntrospectToken,"introspectionEndpoint"),n=e.timeoutMs??15e3;t=e,r=n,rb(t.token,"token",t3.IntrospectToken),rb(t.clientId,"clientId",t3.IntrospectToken),r_(r,"timeoutMs",t3.IntrospectToken),void 0!==t.tokenTypeHint&&rb(t.tokenTypeHint,"tokenTypeHint",t3.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??rd).send({url:u.toString(),method:"POST",headers:s,data:o.toString(),timeoutMs:n,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!t)throw new t8("OAuth token introspection endpoint returned an empty response",{code:t0.InvalidResponse});let r=t.status,a=await t.text(),l=rA(a);if(void 0===r||r<200||r>=300)throw new t8(`OAuth token introspection endpoint returned HTTP ${r??"unknown"}`,{code:t0.HttpError,responseBody:a,responseJson:l,status:r});if(!l||"boolean"!=typeof l.active)throw new t8("OAuth token introspection response is invalid",{code:t0.InvalidResponse,responseBody:a,responseJson:l,status:r});return{active:(i=l).active,scope:rU(i.scope),clientId:rU(i.client_id),clientName:rU(i.client_name),tokenType:rU(i.token_type),exp:rM(i.exp),iat:rM(i.iat),sub:rU(i.sub),raw:i}}catch(e){if(e instanceof t8)throw e;throw new t8("OAuth token introspection request failed",{cause:e,code:rE(e)})}}async function r$(e){var t,r;let i=ry(e.revocationEndpoint,t3.RevokeToken,"revocationEndpoint"),u=e.timeoutMs??15e3;t=e,r=u,rb(t.token,"token",t3.RevokeToken),rb(t.clientId,"clientId",t3.RevokeToken),r_(r,"timeoutMs",t3.RevokeToken),void 0!==t.tokenTypeHint&&rb(t.tokenTypeHint,"tokenTypeHint",t3.RevokeToken);let n=new URLSearchParams({token:e.token,client_id:e.clientId});rg(n,"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??rd).send({url:i.toString(),method:"POST",headers:o,data:n.toString(),timeoutMs:u,signal:e.signal,redirect:"error"},{unwrapData:!1});if(!t)throw new t9("OAuth token revocation endpoint returned an empty response",{code:t0.InvalidResponse});let r=t.status,s=await t.text(),a=rA(s);if(void 0===r||r<200||r>=300)throw new t9(`OAuth token revocation endpoint returned HTTP ${r??"unknown"}`,{code:t0.HttpError,responseBody:s,responseJson:a,status:r})}catch(e){if(e instanceof t9)throw e;throw new t9("OAuth token revocation request failed",{cause:e,code:rE(e)})}}function rU(e){return"string"==typeof e&&e.trim()?e.trim():void 0}function rM(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function rq(e,t){let r=e[t];return r&&r.length>0?r:void 0}function rV(e){var t,r,i,u,n,o,s,a;let c,d,h,p,f=e.appName,m=e.platform??process.platform,g="win32"===m?T.win32:T.posix,A="string"==typeof f?f.trim():"",E=A.split(/[\\/]+/);if(!A||g.isAbsolute(A)||E.includes(".."))throw new l("appName must be a non-empty string",{error:"INVALID_APP_NAME"});let y=e.homeDir??eX.homedir(),b=e.env??process.env;if("darwin"===m)return t=A,r=y,{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(eX.tmpdir(),t)};if("win32"===m){let e,t,r;return i=A,u=y,e=rq(n=b,"APPDATA")??T.join(u,"AppData","Roaming"),t=rq(n,"LOCALAPPDATA")??T.join(u,"AppData","Local"),r=rq(n,"TEMP")??eX.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=y,c=rq(a=b,"XDG_CONFIG_HOME")??T.join(s,".config"),d=rq(a,"XDG_DATA_HOME")??T.join(s,".local","share"),h=rq(a,"XDG_CACHE_HOME")??T.join(s,".cache"),p=rq(a,"XDG_STATE_HOME")??T.join(s,".local","state"),{configDir:T.join(c,o),dataDir:T.join(d,o),cacheDir:T.join(h,o),logDir:T.join(p,o,"logs"),tempDir:T.join(eX.tmpdir(),o)}}function rH(e){let t;function r(){let r,i;return t||(t=new tD((r=e.dir??"dataDir",i=rV(e),{baseDir:e.subDir?td(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 rz(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 rG(e){let t=rz(e.total),r=rz(e.page),i=rz(e.pageSize),u={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(u).some(e=>void 0!==e)?u:void 0}function rW(e){return String(e).padStart(2,"0")}function rJ(e){return e.replace(/[^a-zA-Z0-9_-]+/g,"-")}async function rK(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",u=function(e){var t;let r,i,u,n,o,s,a,c=(r=(t=new Date).getFullYear(),i=rW(t.getMonth()+1),u=rW(t.getDate()),n=rW(t.getHours()),o=rW(t.getMinutes()),s=rW(t.getSeconds()),a=String(t.getMilliseconds()).padStart(3,"0"),`${r}-${i}-${u}_${n}-${o}-${s}_${a}`),d=`${rJ(e.command)}-${c}`;if(e.outputDir){let t=(0,T.resolve)(e.outputDir);if((0,O.existsSync)(t)&&!(0,O.statSync)(t).isDirectory())throw new l(`输出路径不是目录: ${t}`,{error:"INVALID_OUTPUT_DIR",message:`--output-dir 必须是一个目录,但 ${t} 是文件`});return(0,T.resolve)(t,d)}return(0,T.resolve)(process.cwd(),`${rJ(e.appName)}-output`,d)}(e),n=(0,T.resolve)(u,t),o=(0,T.resolve)(u,r),s=(0,T.resolve)(u,i),a=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 th(s);let c=new tD({baseDir:u});await Promise.all([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:n,rawResponse:o}};return await c.writeJson(i,d),{summaryPath:s,csvPath:n,rawPath:o}}let rY="aes-256-gcm";function rX(e,t,r,i=rZ(r)){let u=(0,eY.randomBytes)(12),n=(0,eY.createCipheriv)(rY,t,u);n.setAAD(i);let o=Buffer.concat([n.update(e),n.final()]);return{version:1,algorithm:rY,keyProvider:r,iv:u.toString("base64"),authTag:n.getAuthTag().toString("base64"),ciphertext:o.toString("base64")}}function rQ(e,t,r){if(32!==t.length)throw Error(`Invalid sensitive storage key length: ${t.length}`);let i=(0,eY.createDecipheriv)(rY,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 rZ(e){return Buffer.from([1,rY,e].join(":"),"utf8")}function r1(e,t,r){return Buffer.from([1,rY,"scrypt",e,t,r].join(":"),"utf8")}function r2(e,t,r){return(0,eY.scryptSync)(function(e,t){let{uid:r,gid:i}=function(){try{let e=(0,eX.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}}}(),u=(0,eX.platform)();return["open-game-cli-lib-ssfk-v1",e,t,u,(0,eX.arch)(),r,i].join("\n")}(e,t),r,32)}function r0(e){if(!(e instanceof Error))return!1;let t=e?.code;return!!(eK(t)&&/no\s*entry|not\s*found/i.test(t))||/no\s*entry|not\s*found|notfound|not found/i.test(e?.message)}var r3=((X={}).Auto="auto",X.Keychain="keychain",X.File="file",X),r6=((Q={}).Read="read",Q.Write="write",Q.Remove="remove",Q);let r4=new Map;async function r8(){return await import("@napi-rs/keyring")}async function r9(e,t){let r=r4.get(e)??Promise.resolve(),i=()=>void 0,u=new Promise(e=>{i=e}),n=r.then(()=>u,()=>u);r4.set(e,n),await r.catch(()=>void 0);try{return await t()}finally{i(),r4.get(e)===n&&r4.delete(e)}}class r7{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 tD({baseDir:this.baseDir,baseDirMode:void 0===e.baseDirMode?448:e.baseDirMode}),this.keyStrategy=function(e){if(void 0===e)return r3.File;if(e===r3.Auto||e===r3.Keychain||e===r3.File)return e;throw TypeError(`keyStrategy must be one of: ${r3.File}, ${r3.Keychain}, ${r3.Auto}`)}(e.keyStrategy),this.keychainTimeoutMs=Math.max(0,e.keychainTimeoutMs??5e3),this.onKeychainPrompt=e.onKeychainPrompt,this.fallbackKeyLockPath=void 0===e.fallbackKeyLockPath?td(this.baseDir,`${this.fallbackKeyFile}.lock`):e.fallbackKeyLockPath,this.fallbackKeyLockOptions=e.fallbackKeyLockOptions,this.fallbackKeyScopeId=function(e,t){return(0,eY.createHash)("sha256").update(e).update("\0").update(t).digest("hex").slice(0,32)}(this.service,this.account)}async readText(e,t="utf8"){let r=td(this.baseDir,e);return(await this.readEncryptedData(r,tv.ReadText)).toString(t)}async writeText(e,t,r={}){let i=r.encoding??"utf8",u=td(this.baseDir,e);await this.writeEncryptedData(u,Buffer.from(t,i),tv.WriteText)}async readJson(e,t="utf8"){let r=td(this.baseDir,e),i=await this.readEncryptedData(r,tv.ReadJson);try{return JSON.parse(i.toString(t))}catch(e){throw new tw(`Failed to parse sensitive JSON data: ${r}`,{cause:e,code:tF.InvalidJson,filePath:r,operation:tv.ReadJson})}}async writeJson(e,t,r={}){let i=r.encoding??"utf8",u=r.spaces??2,n=td(this.baseDir,e),o=`${JSON.stringify(t,null,u)}
|
|
31
|
-
`;await this.writeEncryptedData(n,Buffer.from(o,i),tv.WriteJson)}async remove(e){let t=td(this.baseDir,e);try{await this.fileStorage.remove(t)}catch(e){if(tE(e))throw new tx(t,tv.Remove,e);throw new tw(`Failed to remove sensitive data: ${t}`,{cause:e,code:tF.DataStorageError,filePath:t,operation:tv.Remove})}}async removeKey(){let e;if(this.shouldUseKeychainOnRemove())try{let{AsyncEntry:e}=await r8(),t=new e(this.service,this.account);await this.runKeychainCall(()=>t.deleteCredential(),tv.RemoveKey,r6.Remove)}catch(t){t instanceof tI?e=t:r0(t)||(e=new tO("Failed to remove sensitive storage key from keychain",{cause:t,operation:tv.RemoveKey}))}if(this.shouldUseFileOnRemove()){let e=this.getFallbackKeyFilePath();try{await this.fileStorage.remove(e)}catch(t){if(!tE(t))throw new tO(`Failed to remove sensitive storage key file: ${e}`,{cause:t,filePath:e,operation:tv.RemoveKey})}}if(e)throw e}async readEncryptedData(e,t){let r=await this.tryReadEnvelope(e,t);if(!r)throw new tx(e,t);this.assertReadableProvider(r.keyProvider,e,t);let i=await this.readKeyByProvider(r.keyProvider,e,t);try{return rQ(r,i,rZ(r.keyProvider))}catch(r){throw new tS(e,t,r)}}async writeEncryptedData(e,t,r){try{let{key:i,provider:u}=await this.resolveKeyForNewEnvelopeWithLock(e,r),n=rX(t,i,u);await this.fileStorage.writeJson(e,n,{encoding:"utf8",mode:384})}catch(t){if(t instanceof tw)throw t;throw new tw(`Failed to write sensitive data: ${e}`,{cause:t,code:tF.DataStorageError,filePath:e,operation:r})}}async resolveKeyForNewEnvelopeWithLock(e,t){return r9(this.getKeyResolutionLockId(),()=>this.resolveKeyForNewEnvelope(e,t))}getKeyResolutionLockId(){return[this.service,this.account,this.fallbackKeyFile].join("\0")}getFallbackKeyFilePath(){return td(this.baseDir,`${this.fallbackKeyFile}.${this.fallbackKeyScopeId}.json`)}async resolveKeyForNewEnvelope(e,t){if(this.keyStrategy===r3.File){let e=(0,eY.randomBytes)(32);return{key:await this.ensureFileKey(e),provider:"file"}}if(this.keyStrategy===r3.Keychain){let r=await this.tryReadReusableKey("keychain",e,t);if(r)return r;let i=(0,eY.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 u=(0,eY.randomBytes)(32);if(!r)try{return await this.writeKeyToKeychain(u),{key:u,provider:"keychain"}}catch{}return{key:await this.ensureFileKey(u),provider:"file"}}assertReadableProvider(e,t,r){if(this.keyStrategy===r3.Auto)return;let i=this.keyStrategyToProvider();if(e!==i)throw new tO(`Sensitive data key provider mismatch: expected ${i}, got ${e}`,{filePath:t,operation:r})}keyStrategyToProvider(){return this.keyStrategy===r3.Keychain?"keychain":"file"}shouldUseKeychainOnRemove(){return this.keyStrategy===r3.Auto||this.keyStrategy===r3.Keychain}shouldUseFileOnRemove(){return this.keyStrategy===r3.Auto||this.keyStrategy===r3.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(tk(e))return;throw e}}async tryReadEnvelope(e,t){let r;try{r=await this.fileStorage.readText(e,"utf8")}catch(r){if(tE(r))return;throw new tw(`Failed to read sensitive data: ${e}`,{cause:r,code:tF.DataStorageError,filePath:e,operation:t})}try{var i,u=r;let e=JSON.parse(u);if(1!==e.version||e.algorithm!==rY||(i=e.keyProvider,!["keychain","file"].includes(i))||!eK(e.iv)||!eK(e.authTag)||!eK(e.ciphertext))throw Error("Invalid sensitive data envelope");return e}catch(r){throw new tT(e,t,r)}}async ensureFileKey(e){return!1===this.fallbackKeyLockPath?this.createFileKeyIfMissing(e):tC(this.fallbackKeyLockPath,async()=>this.createFileKeyIfMissing(e),this.fallbackKeyLockOptions)}async createFileKeyIfMissing(e){let t=this.getFallbackKeyFilePath();try{return await this.readKeyFromFile(void 0,tv.ReadKey)}catch(e){if(!tk(e))throw e}let r=(0,eY.randomBytes)(16),i=r.toString("base64"),u=rX(e,r2(this.service,this.account,r),"file",r1(this.service,this.account,i)),n={version:1,algorithm:rY,kdf:"scrypt",salt:i,iv:u.iv,authTag:u.authTag,encryptedKey:u.ciphertext};try{await this.fileStorage.writeJson(t,n,{encoding:"utf8",mode:384})}catch(e){throw new tO(`Failed to write sensitive storage key file: ${t}`,{cause:e,filePath:t,operation:tv.WriteKey})}return e}async readKeyFromKeychain(e,t){try{let{AsyncEntry:n}=await r8(),o=new n(this.service,this.account),s=await this.runKeychainCall(()=>o.getPassword(),t,r6.Read);if(!s)throw new tB({filePath:e,operation:t});var r=s,i=e,u=t;let a=Buffer.from(r,"base64");if(32!==a.length)throw new tO(`Invalid sensitive storage key length: ${a.length}`,{filePath:i,operation:u});return a}catch(r){if(r instanceof tw)throw r;if(r0(r))throw new tB({cause:r,filePath:e,operation:t});throw new tO("Failed to read sensitive storage key from keychain",{cause:r,filePath:e,operation:t})}}async writeKeyToKeychain(e){try{let{AsyncEntry:t}=await r8(),r=new t(this.service,this.account);await this.runKeychainCall(()=>r.setPassword(e.toString("base64")),tv.WriteKey,r6.Write)}catch(e){if(e instanceof tw)throw e;throw new tO("Failed to write sensitive storage key to keychain",{cause:e,operation:tv.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 tI(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(tE(r))throw new tB({cause:r,filePath:e??i,operation:t});throw new tO(`Failed to read sensitive storage key file: ${i}`,{cause:p(r,tA)?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!==rY||"scrypt"!==t.kdf||!eK(t.salt)||!eK(t.iv)||!eK(t.authTag)||!eK(t.encryptedKey))throw Error("Invalid sensitive storage key envelope");return t}(r),t=r2(this.service,this.account,Buffer.from(e.salt,"base64")),i=rQ({iv:e.iv,authTag:e.authTag,ciphertext:e.encryptedKey},t,r1(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 tO(`Failed to decrypt sensitive storage key file: ${i}`,{cause:r,filePath:e??i,operation:t})}}}let r5=/^[a-zA-Z0-9_-]+$/,ie=function(){1;return""}();function it(e){return ie?`${e}:${ie}`:e}function ir(){return ie?`auth_${ie}`:"auth"}let ii=rH({appName:"dymg"}),iu=rH({appName:"dymg",subDir:ir()}),io=new Set(["EACCES","EPERM","EROFS"]),is=["读取"];function ia(e){return is.some(t=>e.startsWith(t))}function il(e){return!!function e(t,r=0){if(t&&!(r>8)){var i;if(t instanceof Error&&io.has(t.code??""))return t;if("object"==typeof(i=t)&&null!==i&&"cause"in t)return e(t.cause,r+1)}}(e)}function ic(e,t){var r;if(!il(e))throw e;throw new l(ia(t)?`${t}失败:无法访问或初始化登录态目录`:`${t}失败:登录态目录无写权限`,{cause:e,error:"AUTH_PERMISSION_DENIED",message:ia(r=t)?`${r}失败:当前终端无法访问或初始化登录态目录。`:`${r}失败:当前终端对登录态目录无写权限。`})}let id="client.json",ih=!1;async function ip(){try{var e=await iu.readJson(id);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:tY(e.clientIdIssuedAt),createdAt:D(e.createdAt)??Math.floor(Date.now()/1e3),updatedAt:D(e.updatedAt)??Math.floor(Date.now()/1e3)};throw new l("本地登录信息异常",{error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"})}catch(e){if(tE(e))return;if(h(e,tp.InvalidJson))throw new l("本地登录信息异常",{cause:e,error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"});ic(e,"读取登录配置")}}function im(e){if(e)return{clientId:e.clientId,clientName:e.clientName,clientIdIssuedAt:e.clientIdIssuedAt}}async function ig(){return ih?e:(t||(t=(async()=>{try{let t=await ip(),r=im(t);return e=r,ih=!0,r}finally{t=void 0}})()),t)}async function iA(t){let r=Math.floor(Date.now()/1e3),i=await ip(),u={clientId:t.clientId,clientName:t.clientName??i?.clientName,clientIdIssuedAt:t.clientIdIssuedAt??i?.clientIdIssuedAt,createdAt:i?.createdAt??r,updatedAt:r};try{await iu.writeJson(id,u,{mode:384})}catch(e){ic(e,"保存登录配置")}e=im(u),ih=!0}async function iE(e){let t=await ig(),r=function(e){let t=rI((0,eX.hostname)().split(".")[0]??""),r="";try{r=rI((0,eX.userInfo)().username)}catch{r=rI(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 rL({registrationEndpoint:e.registrationEndpoint,clientName:r,timeoutMs:e.timeoutMs,httpClient:i$});return await iA({clientId:i.clientId,clientName:"string"==typeof i.raw.client_name&&i.raw.client_name.trim()?i.raw.client_name.trim():r,clientIdIssuedAt:tY(i.raw.client_id_issued_at)}),i.clientId}async function iy(e={}){var t,r;let i=await rj({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:i$}),u=(t=i.raw,r=i.scopesSupported,"string"==typeof t.scope&&t.scope.trim()?t.scope.trim():r.length>0?r.join(" "):void 0),n=await iE({registrationEndpoint:i.registrationEndpoint,timeoutMs:e.timeoutMs,enableDynamicClientRegistration:e.enableDynamicClientRegistration});if(!n)throw new l("当前 CLI 配置异常",{error:"MISSING_OAUTH_CLIENT_ID",message:"当前 CLI 配置异常,无法完成登录,请重新安装或重新构建后重试"});return{clientId:n,scope:u,tokenEndpoint:i.tokenEndpoint,introspectionEndpoint:i.introspectionEndpoint,revocationEndpoint:i.revocationEndpoint,deviceAuthorizationEndpoint:i.deviceAuthorizationEndpoint}}let ib="profile.json",i_=function(e){let t;function r(){return t||(t=new rc(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}=rV({appName:"dymg"});return new r7({baseDir:(0,T.join)(e,ir()),service:it(ej),account:it("default")})}(),fileName:"token.json"}));async function iC(){try{var e;let t;return e=await iu.readJson(ib),t=Math.floor(Date.now()/1e3),{uid:C(e?.uid),oauthAppId:C(e?.oauthAppId),oauthAppName:C(e?.oauthAppName),updatedAt:D(e?.updatedAt)??t}}catch(e){if(tE(e))return;throw e}}async function iD(e){try{await iu.writeJson(ib,e,{mode:384})}catch(e){ic(e,"保存登录信息")}}async function iF(e){let t=await iC(),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 iD(r),r):t}async function iv(){try{await iu.remove(ib)}catch(e){tE(e)||ic(e,"清理登录信息")}}function iw(e,t){try{return function(e,t={}){let r,i=Math.floor((t.nowMs??Date.now())/1e3),u=tY(e.expires_in)??t.defaultAccessTokenExpiresInSeconds??3600,n=tY(e.refresh_token_expires_in),o=rU(e.refresh_token),s=o??t.current?.auth.refreshToken,a=void 0===e.scope?t.current?.auth.scopes??[]:(r=rf(e.scope))?r.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[];if(!s)throw new t4("OAuth token response is missing refresh_token",{code:t0.InvalidResponse,responseJson:e});let l=void 0!==n?i+n:t.current&&void 0===o?t.current.auth.rtExpiresAt:i+(t.defaultRefreshTokenExpiresInSeconds??2592e3);return{auth:{accessToken:e.access_token,refreshToken:s,atExpiresAt:i+u,rtExpiresAt:l,scopes:a}}}(e,{current:t})}catch(e){throw new l("登录失败,请重新登录",{cause:e,error:"MISSING_REFRESH_TOKEN",message:`登录失败,请重新执行 ${eL}`})}}async function iB(e){await iF({uid:C(e.uid),oauthAppId:C(e.oauth_app_id),oauthAppName:C(e.oauth_app_name)})}async function ix(e){let t;try{t=await iy({enableDynamicClientRegistration:!1})}catch(e){if(h(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${eL}`});throw e}let r=await rN({tokenEndpoint:t.tokenEndpoint,clientId:t.clientId,grantType:"refresh_token",refreshToken:e.auth.refreshToken,scope:e.auth.scopes,httpClient:i$});return await iB(r).catch(()=>void 0),iw(r,e)}function iS(e){var t;if(il(e)&&ic(e,"刷新登录态"),h(e,"REFRESH_TOKEN_EXPIRED"))throw new l("当前登录已过期,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已过期,请执行 ${eL}`});if(h(t=e,"REFRESH_FAILED")&&re(t.cause)||re(e))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${eL}`});throw e}async function iT(){try{return await i_.tryGet()}catch(e){throw il(e)&&ic(e,"读取登录信息"),new l("本地登录信息异常",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`本地登录信息异常,请先执行 ${e$},再执行 ${eL}`})}}async function iO(){if(await iT())try{return await i_.getAccessToken(ix)}catch(e){iS(e)}}async function iI(){let e=await iT();if(e)try{return(await i_.refresh(e,ix)).auth.accessToken}catch(e){iS(e)}}async function ik(e){let t;if(e){try{t=await iy({enableDynamicClientRegistration:!1})}catch(e){if(h(e,"MISSING_OAUTH_CLIENT_ID"))return;throw e}try{await r$({revocationEndpoint:t.revocationEndpoint,token:e.auth.refreshToken,tokenTypeHint:"refresh_token",clientId:t.clientId,httpClient:i$})}catch(e){throw new l("退出登录失败,请稍后重试",{cause:e,error:"AUTH_LOGOUT_REVOKE_FAILED",message:"退出登录失败,请检查网络后重试"})}}}async function iR(){let e,t,r=await iO();if(!r)return;try{e=await iy({enableDynamicClientRegistration:!1})}catch(e){if(h(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${eL}`});throw e}try{t=await rP({introspectionEndpoint:e.introspectionEndpoint,token:r,tokenTypeHint:"access_token",clientId:e.clientId,httpClient:i$})}catch(e){throw new l("登录态校验失败,请稍后重试或重新登录",{cause:e,error:"AUTH_STATUS_CHECK_FAILED",message:`登录态校验失败,请稍后重试;如问题持续,可执行 ${eL}`})}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:`当前登录已失效,请执行 ${eL}`});return await iF({uid:i.uid,oauthAppId:i.oauthAppId,oauthAppName:i.oauthAppName}).catch(()=>void 0),i}async function ij(e,t){let r=iw(e,t);try{await Promise.all([i_.save(r),iB(e).catch(()=>void 0)])}catch(e){ic(e,"保存登录态")}return r}async function iL(){try{await Promise.all([i_.clear(),iv()])}catch(e){ic(e,"退出登录")}}let iN=new eO,iP=new eO,i$=new eO;function iU(e){return new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:e??`当前命令需要先登录,请先执行 ${eL}`})}function iM(){return new l("当前登录已失效,请重新登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${eL}`})}function iq(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 iV(e){if(e?.trim())try{return iq(JSON.parse(e))}catch{return}}function iH(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?iM():iU();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=iM();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 iz(e){if(!eF(e))throw e;iH(iV(e.responseBody),{status:e.status,cause:e})}function iG(e){let t=iq(e);t&&void 0!==t.error&&0!==t.error&&iH(t)}async function iW(e,t={}){var r,i;let u={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 iP.send(u,{meta:t.meta});return iG(e),e}catch(r){eF(i=r)&&401===i.status||iz(r);let e=eF(r)?iV(r.responseBody):void 0;if(!await iI())throw e?.error===1002?iU():iM();try{let{data:e}=await iP.send(u,{meta:t.meta});return iG(e),e}catch(e){iz(e)}}}let iJ="session.json";async function iK(e){try{await iu.writeJson(iJ,e,{mode:384})}catch(e){ic(e,"保存授权会话")}}async function iY(){try{return function(e){let t=C(e?.clientId),r=C(e?.tokenEndpoint),i=C(e?.deviceCode),u=C(e?.userCode),n=C(e?.verificationUri),o=C(e?.codeVerifier),s=D(e?.createdAt),a=D(e?.expiresAt);if(!t||!r||!i||!u||!n||!o||!s||!a)throw new l("本地授权会话异常",{error:"INVALID_AUTH_SESSION",message:`本地授权会话异常,请重新执行 ${eN}`});return{clientId:t,tokenEndpoint:r,deviceCode:i,userCode:u,verificationUri:n,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 iu.readJson(iJ))}catch(e){if(tE(e))return;ic(e,"读取授权会话")}}async function iX(){try{await iu.remove(iJ)}catch(e){tE(e)||ic(e,"清理授权会话")}}let iQ=["coze","cursor","claude_code","github_copilot","gemini_cli","trae","manus","devin","codex","hermes","openclaw","unknown"];function iZ(e){return iQ.includes(e)}let i1="宿主枚举:1 全部 / 2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山 / 9 皮皮虾",i2="宿主枚举:2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山",i0="操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony / 5 Windows",i3="设备档位枚举:1 全部 / 2 高端 / 3 中端 / 4 低端";function i6(e,t){let{caller:r}=e.optsWithGlobals();return{...t,caller:"string"==typeof r&&iZ(r)?r:"unknown"}}function i4(e){return e.option("--output-dir <dir>","输出根目录,默认 ./dymg-output(会在其下按命令+时间生成子目录,并写入 csv/raw/summary)"),e}async function i8(e){let t=await ig().catch(()=>void 0);return{toolId:e.replaceAll(":"," "),clientId:t?.clientId}}function i9(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>",i1).option("--os <os>",i0).option("--user-type <userType>","用户类型枚举:1 全部 / 2 新增 / 3 活跃 / 4 付费新增 / 5 付费活跃").option("--segment <segment>","用户分群枚举:1 不分组 / 2 侧边栏奖励 / 3 App 活跃")}function i7(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>",i2).requiredOption("--os <os>","操作系统枚举:2 Android / 3 iOS / 4 OpenHarmony").option("--device-level <n>",i3).option("--mp-version <version>","小游戏版本号")}var i5=__webpack_require__("../../node_modules/.pnpm/@dp+tea-sdk-node@3.0.12/node_modules/@dp/tea-sdk-node/lib/index.js"),ue=__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 ut=Number(626386),ur=null;function ui(){let e=eq();if(e?.tool&&void 0!==e.requestParams)return{caller:e.caller,tool:e.tool,requestParams:e.requestParams}}async function uu(e){let t=(void 0===r&&(r=function(){if(!Number.isFinite(ut)||ut<=0)return null;let e=globalThis.fetch?(e,t)=>globalThis.fetch(e,t):void 0,t=new i5.TeaSDK({app_id:ut}),r=(0,ue.httpPlugin)({channel:"cn",...e?{transport:(t,r)=>e(t,r)}:{}});return ur=r,t.use(r),t.config({custom:{cli_name:"dymg"}}),t}()),r);if(!t)return;let[i,u]=await Promise.all([ig().catch(()=>void 0),iC().catch(()=>void 0)]),n=eq(),o=function(e=3e3){let t=ur;return!t||e<=0?Promise.resolve():new Promise(r=>{let i=()=>{clearTimeout(u),r()},u=setTimeout(()=>{t.removeListener("drain",i),r()},e);t.once("drain",i)})}(),s={caller:e.caller,tool:e.tool,cli_version:"0.3.0",appli_id:n?.appId,user_id:u?.uid,oauth_app_id:u?.oauthAppId,oauth_app_name:u?.oauthAppName,client_id:i?.clientId,client_name:i?.clientName,is_success:+!!e.success,duration_ms:e.durationMs,request_params:e.requestParams,logid:n?.response?.logId,error_message:e.errorMessage,error_code:e.errorCode},a={user:u?{user_id:Number(u?.uid),user_unique_id:u?.uid,user_is_login:!!u?.uid}:void 0};t.collect("game_cli_call",s,a),await o}function un(e){return d(e)?e.error:void 0}let uo=["npm","pnpm","yarn","bun"],us=new eO;function ua(e){var t;return(t=e,uo.includes(t))?e:void 0}function ul(e={}){var t;let r=ua(e.input);return void 0!==e.input?r:(t=e.userAgent,ua(t?.split("/")[0])??e.defaultPackageManager)}async function uc(e,t={}){let r=e.trim(),i=t.client??us,u=(t.registryBaseUrl??"https://registry.npmjs.org").trim().replace(/\/+$/,""),n=t.timeoutMs??3e3,o=t.retry??{maxRetries:2,retryDelayMs:e=>1e3*e};if(!r)throw new eC("packageName is required",{code:e_.InvalidArgument,url:u});let s=encodeURIComponent(r).replace("%2F","%2f"),a=`${u}/${s}/latest`,{data:l}=await i.send({url:a,timeoutMs:n,retry:o});if("string"!=typeof l?.version||""===l.version.trim())throw new eC("package registry response missing version",{code:e_.InvalidJson,url:a});return l.version.trim()}let ud="update-check.json";function uh(e){let t=ul({userAgent:process.env.npm_config_user_agent})?"dymg update":`dymg update --package-manager <${uo.join("|")}>`;return[`检测到 ${ek} 新版本 ${e}(当前 0.3.0)。`,`执行 ${t} 可更新 CLI 并同步随包发布的 Skill。`,"如只想手动同步 Skill,可执行 dymg skills install。"]}async function up(){try{return await ii.get().readJson(ud)}catch(e){if(tE(e))return{};throw e}}async function uf(e){await ii.get().writeJson(ud,e)}async function um(){return uc(ek,{client:iN,timeoutMs:1e4})}async function ug(){let e=await um();return{currentVersion:"0.3.0",latestVersion:e,hasUpdate:function(e,t){let r=_(e),i=_(t);if(!r||!i)return e.localeCompare(t);for(let u=0;u<3;u+=1){let n=r.main[u],o=i.main[u];if(void 0===n||void 0===o)return e.localeCompare(t);let s=n-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 u=Math.max(r.prerelease.length,i.prerelease.length);for(let e=0;e<u;e+=1){let t=r.prerelease[e],u=i.prerelease[e];if(void 0===t)return -1;if(void 0===u)return 1;let n=function(e,t){let r=/^\d+$/.test(e),i=/^\d+$/.test(t);if(r&&i){var u,n;let r,i;return u=e,n=t,r=u.replace(/^0+/,"")||"0",i=n.replace(/^0+/,"")||"0",r.length!==i.length?r.length-i.length:r.localeCompare(i)}return r?-1:i?1:e.localeCompare(t)}(t,u);if(0!==n)return n}return 0}(e,"0.3.0")>0}}async function uA(e,t={}){let r=await up(),i=Date.now(),u={...r,lastCheckedAt:i,latestVersion:e.latestVersion};t.notified&&(u.lastNotifiedAt=i,u.lastNotifiedVersion=e.latestVersion),await uf(u)}async function uE(e={}){var t,r,i,u,n,o;let s=e.force??!1,a=e.quiet??!1,l=Date.now(),c=await up();if(t=l,r=c,!s&&!(t-(r.lastCheckedAt??0)>=864e5))return;let d=await ug(),h={...c,lastCheckedAt:l,latestVersion:d.latestVersion};if(d.hasUpdate){i=l,u=c,n=d.latestVersion,(s||(u.lastNotifiedVersion??u.latestVersion)!==n||i-(u.lastNotifiedAt??u.lastPromptedAt??0)>=864e5)&&(o=d.latestVersion,process.stdout.write(["",...uh(o),""].join("\n")),h.lastNotifiedAt=l,h.lastNotifiedVersion=d.latestVersion),await uf(h);return}a||process.stdout.write(`dymg 已是最新版本(0.3.0)
|
|
31
|
+
`;await this.writeEncryptedData(n,Buffer.from(o,i),tv.WriteJson)}async remove(e){let t=td(this.baseDir,e);try{await this.fileStorage.remove(t)}catch(e){if(tE(e))throw new tx(t,tv.Remove,e);throw new tw(`Failed to remove sensitive data: ${t}`,{cause:e,code:tF.DataStorageError,filePath:t,operation:tv.Remove})}}async removeKey(){let e;if(this.shouldUseKeychainOnRemove())try{let{AsyncEntry:e}=await r8(),t=new e(this.service,this.account);await this.runKeychainCall(()=>t.deleteCredential(),tv.RemoveKey,r6.Remove)}catch(t){t instanceof tI?e=t:r0(t)||(e=new tO("Failed to remove sensitive storage key from keychain",{cause:t,operation:tv.RemoveKey}))}if(this.shouldUseFileOnRemove()){let e=this.getFallbackKeyFilePath();try{await this.fileStorage.remove(e)}catch(t){if(!tE(t))throw new tO(`Failed to remove sensitive storage key file: ${e}`,{cause:t,filePath:e,operation:tv.RemoveKey})}}if(e)throw e}async readEncryptedData(e,t){let r=await this.tryReadEnvelope(e,t);if(!r)throw new tx(e,t);this.assertReadableProvider(r.keyProvider,e,t);let i=await this.readKeyByProvider(r.keyProvider,e,t);try{return rQ(r,i,rZ(r.keyProvider))}catch(r){throw new tS(e,t,r)}}async writeEncryptedData(e,t,r){try{let{key:i,provider:u}=await this.resolveKeyForNewEnvelopeWithLock(e,r),n=rX(t,i,u);await this.fileStorage.writeJson(e,n,{encoding:"utf8",mode:384})}catch(t){if(t instanceof tw)throw t;throw new tw(`Failed to write sensitive data: ${e}`,{cause:t,code:tF.DataStorageError,filePath:e,operation:r})}}async resolveKeyForNewEnvelopeWithLock(e,t){return r9(this.getKeyResolutionLockId(),()=>this.resolveKeyForNewEnvelope(e,t))}getKeyResolutionLockId(){return[this.service,this.account,this.fallbackKeyFile].join("\0")}getFallbackKeyFilePath(){return td(this.baseDir,`${this.fallbackKeyFile}.${this.fallbackKeyScopeId}.json`)}async resolveKeyForNewEnvelope(e,t){if(this.keyStrategy===r3.File){let e=(0,eY.randomBytes)(32);return{key:await this.ensureFileKey(e),provider:"file"}}if(this.keyStrategy===r3.Keychain){let r=await this.tryReadReusableKey("keychain",e,t);if(r)return r;let i=(0,eY.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 u=(0,eY.randomBytes)(32);if(!r)try{return await this.writeKeyToKeychain(u),{key:u,provider:"keychain"}}catch{}return{key:await this.ensureFileKey(u),provider:"file"}}assertReadableProvider(e,t,r){if(this.keyStrategy===r3.Auto)return;let i=this.keyStrategyToProvider();if(e!==i)throw new tO(`Sensitive data key provider mismatch: expected ${i}, got ${e}`,{filePath:t,operation:r})}keyStrategyToProvider(){return this.keyStrategy===r3.Keychain?"keychain":"file"}shouldUseKeychainOnRemove(){return this.keyStrategy===r3.Auto||this.keyStrategy===r3.Keychain}shouldUseFileOnRemove(){return this.keyStrategy===r3.Auto||this.keyStrategy===r3.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(tk(e))return;throw e}}async tryReadEnvelope(e,t){let r;try{r=await this.fileStorage.readText(e,"utf8")}catch(r){if(tE(r))return;throw new tw(`Failed to read sensitive data: ${e}`,{cause:r,code:tF.DataStorageError,filePath:e,operation:t})}try{var i,u=r;let e=JSON.parse(u);if(1!==e.version||e.algorithm!==rY||(i=e.keyProvider,!["keychain","file"].includes(i))||!eK(e.iv)||!eK(e.authTag)||!eK(e.ciphertext))throw Error("Invalid sensitive data envelope");return e}catch(r){throw new tT(e,t,r)}}async ensureFileKey(e){return!1===this.fallbackKeyLockPath?this.createFileKeyIfMissing(e):tC(this.fallbackKeyLockPath,async()=>this.createFileKeyIfMissing(e),this.fallbackKeyLockOptions)}async createFileKeyIfMissing(e){let t=this.getFallbackKeyFilePath();try{return await this.readKeyFromFile(void 0,tv.ReadKey)}catch(e){if(!tk(e))throw e}let r=(0,eY.randomBytes)(16),i=r.toString("base64"),u=rX(e,r2(this.service,this.account,r),"file",r1(this.service,this.account,i)),n={version:1,algorithm:rY,kdf:"scrypt",salt:i,iv:u.iv,authTag:u.authTag,encryptedKey:u.ciphertext};try{await this.fileStorage.writeJson(t,n,{encoding:"utf8",mode:384})}catch(e){throw new tO(`Failed to write sensitive storage key file: ${t}`,{cause:e,filePath:t,operation:tv.WriteKey})}return e}async readKeyFromKeychain(e,t){try{let{AsyncEntry:n}=await r8(),o=new n(this.service,this.account),s=await this.runKeychainCall(()=>o.getPassword(),t,r6.Read);if(!s)throw new tB({filePath:e,operation:t});var r=s,i=e,u=t;let a=Buffer.from(r,"base64");if(32!==a.length)throw new tO(`Invalid sensitive storage key length: ${a.length}`,{filePath:i,operation:u});return a}catch(r){if(r instanceof tw)throw r;if(r0(r))throw new tB({cause:r,filePath:e,operation:t});throw new tO("Failed to read sensitive storage key from keychain",{cause:r,filePath:e,operation:t})}}async writeKeyToKeychain(e){try{let{AsyncEntry:t}=await r8(),r=new t(this.service,this.account);await this.runKeychainCall(()=>r.setPassword(e.toString("base64")),tv.WriteKey,r6.Write)}catch(e){if(e instanceof tw)throw e;throw new tO("Failed to write sensitive storage key to keychain",{cause:e,operation:tv.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 tI(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(tE(r))throw new tB({cause:r,filePath:e??i,operation:t});throw new tO(`Failed to read sensitive storage key file: ${i}`,{cause:p(r,tA)?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!==rY||"scrypt"!==t.kdf||!eK(t.salt)||!eK(t.iv)||!eK(t.authTag)||!eK(t.encryptedKey))throw Error("Invalid sensitive storage key envelope");return t}(r),t=r2(this.service,this.account,Buffer.from(e.salt,"base64")),i=rQ({iv:e.iv,authTag:e.authTag,ciphertext:e.encryptedKey},t,r1(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 tO(`Failed to decrypt sensitive storage key file: ${i}`,{cause:r,filePath:e??i,operation:t})}}}let r5=/^[a-zA-Z0-9_-]+$/,ie=function(){1;return""}();function it(e){return ie?`${e}:${ie}`:e}function ir(){return ie?`auth_${ie}`:"auth"}let ii=rH({appName:"dymg"}),iu=rH({appName:"dymg",subDir:ir()}),io=new Set(["EACCES","EPERM","EROFS"]),is=["读取"];function ia(e){return is.some(t=>e.startsWith(t))}function il(e){return!!function e(t,r=0){if(t&&!(r>8)){var i;if(t instanceof Error&&io.has(t.code??""))return t;if("object"==typeof(i=t)&&null!==i&&"cause"in t)return e(t.cause,r+1)}}(e)}function ic(e,t){var r;if(!il(e))throw e;throw new l(ia(t)?`${t}失败:无法访问或初始化登录态目录`:`${t}失败:登录态目录无写权限`,{cause:e,error:"AUTH_PERMISSION_DENIED",message:ia(r=t)?`${r}失败:当前终端无法访问或初始化登录态目录。`:`${r}失败:当前终端对登录态目录无写权限。`})}let id="client.json",ih=!1;async function ip(){try{var e=await iu.readJson(id);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:tY(e.clientIdIssuedAt),createdAt:D(e.createdAt)??Math.floor(Date.now()/1e3),updatedAt:D(e.updatedAt)??Math.floor(Date.now()/1e3)};throw new l("本地登录信息异常",{error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"})}catch(e){if(tE(e))return;if(h(e,tp.InvalidJson))throw new l("本地登录信息异常",{cause:e,error:"INVALID_OAUTH_CLIENT_FILE",message:"本地登录信息异常,请清理本地配置后重新登录"});ic(e,"读取登录配置")}}function im(e){if(e)return{clientId:e.clientId,clientName:e.clientName,clientIdIssuedAt:e.clientIdIssuedAt}}async function ig(){return ih?e:(t||(t=(async()=>{try{let t=await ip(),r=im(t);return e=r,ih=!0,r}finally{t=void 0}})()),t)}async function iA(t){let r=Math.floor(Date.now()/1e3),i=await ip(),u={clientId:t.clientId,clientName:t.clientName??i?.clientName,clientIdIssuedAt:t.clientIdIssuedAt??i?.clientIdIssuedAt,createdAt:i?.createdAt??r,updatedAt:r};try{await iu.writeJson(id,u,{mode:384})}catch(e){ic(e,"保存登录配置")}e=im(u),ih=!0}async function iE(e){let t=await ig(),r=function(e){let t=rI((0,eX.hostname)().split(".")[0]??""),r="";try{r=rI((0,eX.userInfo)().username)}catch{r=rI(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 rL({registrationEndpoint:e.registrationEndpoint,clientName:r,timeoutMs:e.timeoutMs,httpClient:i$});return await iA({clientId:i.clientId,clientName:"string"==typeof i.raw.client_name&&i.raw.client_name.trim()?i.raw.client_name.trim():r,clientIdIssuedAt:tY(i.raw.client_id_issued_at)}),i.clientId}async function iy(e={}){var t,r;let i=await rj({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:i$}),u=(t=i.raw,r=i.scopesSupported,"string"==typeof t.scope&&t.scope.trim()?t.scope.trim():r.length>0?r.join(" "):void 0),n=await iE({registrationEndpoint:i.registrationEndpoint,timeoutMs:e.timeoutMs,enableDynamicClientRegistration:e.enableDynamicClientRegistration});if(!n)throw new l("当前 CLI 配置异常",{error:"MISSING_OAUTH_CLIENT_ID",message:"当前 CLI 配置异常,无法完成登录,请重新安装或重新构建后重试"});return{clientId:n,scope:u,tokenEndpoint:i.tokenEndpoint,introspectionEndpoint:i.introspectionEndpoint,revocationEndpoint:i.revocationEndpoint,deviceAuthorizationEndpoint:i.deviceAuthorizationEndpoint}}let ib="profile.json",i_=function(e){let t;function r(){return t||(t=new rc(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}=rV({appName:"dymg"});return new r7({baseDir:(0,T.join)(e,ir()),service:it(ej),account:it("default")})}(),fileName:"token.json"}));async function iC(){try{var e;let t;return e=await iu.readJson(ib),t=Math.floor(Date.now()/1e3),{uid:C(e?.uid),oauthAppId:C(e?.oauthAppId),oauthAppName:C(e?.oauthAppName),updatedAt:D(e?.updatedAt)??t}}catch(e){if(tE(e))return;throw e}}async function iD(e){try{await iu.writeJson(ib,e,{mode:384})}catch(e){ic(e,"保存登录信息")}}async function iF(e){let t=await iC(),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 iD(r),r):t}async function iv(){try{await iu.remove(ib)}catch(e){tE(e)||ic(e,"清理登录信息")}}function iw(e,t){try{return function(e,t={}){let r,i=Math.floor((t.nowMs??Date.now())/1e3),u=tY(e.expires_in)??t.defaultAccessTokenExpiresInSeconds??3600,n=tY(e.refresh_token_expires_in),o=rU(e.refresh_token),s=o??t.current?.auth.refreshToken,a=void 0===e.scope?t.current?.auth.scopes??[]:(r=rf(e.scope))?r.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[];if(!s)throw new t4("OAuth token response is missing refresh_token",{code:t0.InvalidResponse,responseJson:e});let l=void 0!==n?i+n:t.current&&void 0===o?t.current.auth.rtExpiresAt:i+(t.defaultRefreshTokenExpiresInSeconds??2592e3);return{auth:{accessToken:e.access_token,refreshToken:s,atExpiresAt:i+u,rtExpiresAt:l,scopes:a}}}(e,{current:t})}catch(e){throw new l("登录失败,请重新登录",{cause:e,error:"MISSING_REFRESH_TOKEN",message:`登录失败,请重新执行 ${eL}`})}}async function iB(e){await iF({uid:C(e.uid),oauthAppId:C(e.oauth_app_id),oauthAppName:C(e.oauth_app_name)})}async function ix(e){let t;try{t=await iy({enableDynamicClientRegistration:!1})}catch(e){if(h(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${eL}`});throw e}let r=await rN({tokenEndpoint:t.tokenEndpoint,clientId:t.clientId,grantType:"refresh_token",refreshToken:e.auth.refreshToken,scope:e.auth.scopes,httpClient:i$});return await iB(r).catch(()=>void 0),iw(r,e)}function iS(e){var t;if(il(e)&&ic(e,"刷新登录态"),h(e,"REFRESH_TOKEN_EXPIRED"))throw new l("当前登录已过期,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已过期,请执行 ${eL}`});if(h(t=e,"REFRESH_FAILED")&&re(t.cause)||re(e))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${eL}`});throw e}async function iT(){try{return await i_.tryGet()}catch(e){throw il(e)&&ic(e,"读取登录信息"),new l("本地登录信息异常",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`本地登录信息异常,请先执行 ${e$},再执行 ${eL}`})}}async function iO(){if(await iT())try{return await i_.getAccessToken(ix)}catch(e){iS(e)}}async function iI(){let e=await iT();if(e)try{return(await i_.refresh(e,ix)).auth.accessToken}catch(e){iS(e)}}async function ik(e){let t;if(e){try{t=await iy({enableDynamicClientRegistration:!1})}catch(e){if(h(e,"MISSING_OAUTH_CLIENT_ID"))return;throw e}try{await r$({revocationEndpoint:t.revocationEndpoint,token:e.auth.refreshToken,tokenTypeHint:"refresh_token",clientId:t.clientId,httpClient:i$})}catch(e){throw new l("退出登录失败,请稍后重试",{cause:e,error:"AUTH_LOGOUT_REVOKE_FAILED",message:"退出登录失败,请检查网络后重试"})}}}async function iR(){let e,t,r=await iO();if(!r)return;try{e=await iy({enableDynamicClientRegistration:!1})}catch(e){if(h(e,"MISSING_OAUTH_CLIENT_ID"))throw new l("当前登录已失效,请重新登录",{cause:e,error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${eL}`});throw e}try{t=await rP({introspectionEndpoint:e.introspectionEndpoint,token:r,tokenTypeHint:"access_token",clientId:e.clientId,httpClient:i$})}catch(e){throw new l("登录态校验失败,请稍后重试或重新登录",{cause:e,error:"AUTH_STATUS_CHECK_FAILED",message:`登录态校验失败,请稍后重试;如问题持续,可执行 ${eL}`})}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:`当前登录已失效,请执行 ${eL}`});return await iF({uid:i.uid,oauthAppId:i.oauthAppId,oauthAppName:i.oauthAppName}).catch(()=>void 0),i}async function ij(e,t){let r=iw(e,t);try{await Promise.all([i_.save(r),iB(e).catch(()=>void 0)])}catch(e){ic(e,"保存登录态")}return r}async function iL(){try{await Promise.all([i_.clear(),iv()])}catch(e){ic(e,"退出登录")}}let iN=new eO,iP=new eO,i$=new eO;function iU(e){return new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:e??`当前命令需要先登录,请先执行 ${eL}`})}function iM(){return new l("当前登录已失效,请重新登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前登录已失效,请执行 ${eL}`})}function iq(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 iV(e){if(e?.trim())try{return iq(JSON.parse(e))}catch{return}}function iH(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?iM():iU();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=iM();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 iz(e){if(!eF(e))throw e;iH(iV(e.responseBody),{status:e.status,cause:e})}function iG(e){let t=iq(e);t&&void 0!==t.error&&0!==t.error&&iH(t)}async function iW(e,t={}){var r,i;let u={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 iP.send(u,{meta:t.meta});return iG(e),e}catch(r){eF(i=r)&&401===i.status||iz(r);let e=eF(r)?iV(r.responseBody):void 0;if(!await iI())throw e?.error===1002?iU():iM();try{let{data:e}=await iP.send(u,{meta:t.meta});return iG(e),e}catch(e){iz(e)}}}let iJ="session.json";async function iK(e){try{await iu.writeJson(iJ,e,{mode:384})}catch(e){ic(e,"保存授权会话")}}async function iY(){try{return function(e){let t=C(e?.clientId),r=C(e?.tokenEndpoint),i=C(e?.deviceCode),u=C(e?.userCode),n=C(e?.verificationUri),o=C(e?.codeVerifier),s=D(e?.createdAt),a=D(e?.expiresAt);if(!t||!r||!i||!u||!n||!o||!s||!a)throw new l("本地授权会话异常",{error:"INVALID_AUTH_SESSION",message:`本地授权会话异常,请重新执行 ${eN}`});return{clientId:t,tokenEndpoint:r,deviceCode:i,userCode:u,verificationUri:n,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 iu.readJson(iJ))}catch(e){if(tE(e))return;ic(e,"读取授权会话")}}async function iX(){try{await iu.remove(iJ)}catch(e){tE(e)||ic(e,"清理授权会话")}}let iQ=["coze","cursor","claude_code","github_copilot","gemini_cli","trae","manus","devin","codex","hermes","openclaw","unknown"];function iZ(e){return iQ.includes(e)}let i1="宿主枚举:1 全部 / 2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山 / 9 皮皮虾",i2="宿主枚举:2 抖音 / 3 抖音极速版 / 4 今日头条 / 5 头条极速版 / 6 番茄小说 / 7 番茄畅听 / 8 抖音火山",i0="操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony / 5 Windows",i3="设备档位枚举:1 全部 / 2 高端 / 3 中端 / 4 低端";function i6(e,t){let{caller:r}=e.optsWithGlobals();return{...t,caller:"string"==typeof r&&iZ(r)?r:"unknown"}}function i4(e){return e.option("--output-dir <dir>","输出根目录,默认 ./dymg-output(会在其下按命令+时间生成子目录,并写入 csv/raw/summary)"),e}async function i8(e){let t=await ig().catch(()=>void 0);return{toolId:e.replaceAll(":"," "),clientId:t?.clientId}}function i9(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>",i1).option("--os <os>",i0).option("--user-type <userType>","用户类型枚举:1 全部 / 2 新增 / 3 活跃 / 4 付费新增 / 5 付费活跃").option("--segment <segment>","用户分群枚举:1 不分组 / 2 侧边栏奖励 / 3 App 活跃")}function i7(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>",i2).requiredOption("--os <os>","操作系统枚举:2 Android / 3 iOS / 4 OpenHarmony").option("--device-level <n>",i3).option("--mp-version <version>","小游戏版本号")}var i5=__webpack_require__("../../node_modules/.pnpm/@dp+tea-sdk-node@3.0.12/node_modules/@dp/tea-sdk-node/lib/index.js"),ue=__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 ut=Number(626386),ur=null;function ui(){let e=eq();if(e?.tool&&void 0!==e.requestParams)return{caller:e.caller,tool:e.tool,requestParams:e.requestParams}}async function uu(e){let t=(void 0===r&&(r=function(){if(!Number.isFinite(ut)||ut<=0)return null;let e=globalThis.fetch?(e,t)=>globalThis.fetch(e,t):void 0,t=new i5.TeaSDK({app_id:ut}),r=(0,ue.httpPlugin)({channel:"cn",...e?{transport:(t,r)=>e(t,r)}:{}});return ur=r,t.use(r),t.config({custom:{cli_name:"dymg"}}),t}()),r);if(!t)return;let[i,u]=await Promise.all([ig().catch(()=>void 0),iC().catch(()=>void 0)]),n=eq(),o=function(e=3e3){let t=ur;return!t||e<=0?Promise.resolve():new Promise(r=>{let i=()=>{clearTimeout(u),r()},u=setTimeout(()=>{t.removeListener("drain",i),r()},e);t.once("drain",i)})}(),s={caller:e.caller,tool:e.tool,cli_version:"0.4.0",appli_id:n?.appId,user_id:u?.uid,oauth_app_id:u?.oauthAppId,oauth_app_name:u?.oauthAppName,client_id:i?.clientId,client_name:i?.clientName,is_success:+!!e.success,duration_ms:e.durationMs,request_params:e.requestParams,logid:n?.response?.logId,error_message:e.errorMessage,error_code:e.errorCode},a={user:u?{user_id:Number(u?.uid),user_unique_id:u?.uid,user_is_login:!!u?.uid}:void 0};t.collect("game_cli_call",s,a),await o}function un(e){return d(e)?e.error:void 0}let uo=["npm","pnpm","yarn","bun"],us=new eO;function ua(e){var t;return(t=e,uo.includes(t))?e:void 0}function ul(e={}){var t;let r=ua(e.input);return void 0!==e.input?r:(t=e.userAgent,ua(t?.split("/")[0])??e.defaultPackageManager)}async function uc(e,t={}){let r=e.trim(),i=t.client??us,u=(t.registryBaseUrl??"https://registry.npmjs.org").trim().replace(/\/+$/,""),n=t.timeoutMs??3e3,o=t.retry??{maxRetries:2,retryDelayMs:e=>1e3*e};if(!r)throw new eC("packageName is required",{code:e_.InvalidArgument,url:u});let s=encodeURIComponent(r).replace("%2F","%2f"),a=`${u}/${s}/latest`,{data:l}=await i.send({url:a,timeoutMs:n,retry:o});if("string"!=typeof l?.version||""===l.version.trim())throw new eC("package registry response missing version",{code:e_.InvalidJson,url:a});return l.version.trim()}let ud="update-check.json";function uh(e){let t=ul({userAgent:process.env.npm_config_user_agent})?"dymg update":`dymg update --package-manager <${uo.join("|")}>`;return[`检测到 ${ek} 新版本 ${e}(当前 0.4.0)。`,`执行 ${t} 可更新 CLI 并同步随包发布的 Skill。`,"如只想手动同步 Skill,可执行 dymg skills install。"]}async function up(){try{return await ii.get().readJson(ud)}catch(e){if(tE(e))return{};throw e}}async function uf(e){await ii.get().writeJson(ud,e)}async function um(){return uc(ek,{client:iN,timeoutMs:1e4})}async function ug(){let e=await um();return{currentVersion:"0.4.0",latestVersion:e,hasUpdate:function(e,t){let r=_(e),i=_(t);if(!r||!i)return e.localeCompare(t);for(let u=0;u<3;u+=1){let n=r.main[u],o=i.main[u];if(void 0===n||void 0===o)return e.localeCompare(t);let s=n-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 u=Math.max(r.prerelease.length,i.prerelease.length);for(let e=0;e<u;e+=1){let t=r.prerelease[e],u=i.prerelease[e];if(void 0===t)return -1;if(void 0===u)return 1;let n=function(e,t){let r=/^\d+$/.test(e),i=/^\d+$/.test(t);if(r&&i){var u,n;let r,i;return u=e,n=t,r=u.replace(/^0+/,"")||"0",i=n.replace(/^0+/,"")||"0",r.length!==i.length?r.length-i.length:r.localeCompare(i)}return r?-1:i?1:e.localeCompare(t)}(t,u);if(0!==n)return n}return 0}(e,"0.4.0")>0}}async function uA(e,t={}){let r=await up(),i=Date.now(),u={...r,lastCheckedAt:i,latestVersion:e.latestVersion};t.notified&&(u.lastNotifiedAt=i,u.lastNotifiedVersion=e.latestVersion),await uf(u)}async function uE(e={}){var t,r,i,u,n,o;let s=e.force??!1,a=e.quiet??!1,l=Date.now(),c=await up();if(t=l,r=c,!s&&!(t-(r.lastCheckedAt??0)>=864e5))return;let d=await ug(),h={...c,lastCheckedAt:l,latestVersion:d.latestVersion};if(d.hasUpdate){i=l,u=c,n=d.latestVersion,(s||(u.lastNotifiedVersion??u.latestVersion)!==n||i-(u.lastNotifiedAt??u.lastPromptedAt??0)>=864e5)&&(o=d.latestVersion,process.stdout.write(["",...uh(o),""].join("\n")),h.lastNotifiedAt=l,h.lastNotifiedVersion=d.latestVersion),await uf(h);return}a||process.stdout.write(`dymg 已是最新版本(0.4.0)
|
|
32
32
|
`),await uf(h)}async function uy(){try{await uE({quiet:!0})}catch{}}let ub={request:iW,baseURL:""};ub.genBaseURL=e=>"function"==typeof ub.baseURL?ub.baseURL(e):ub.baseURL+e;var u_=((Z={})[Z.All=1]="All",Z[Z.Douyin=2]="Douyin",Z[Z.DouyinLite=3]="DouyinLite",Z[Z.Toutiao=4]="Toutiao",Z[Z.ToutiaoLite=5]="ToutiaoLite",Z[Z.Fanqie=6]="Fanqie",Z[Z.FanqieChangTing=7]="FanqieChangTing",Z[Z.Hotsoon=8]="Hotsoon",Z[Z.Ppx=9]="Ppx",Z),uC=((ee={})[ee.All=1]="All",ee[ee.Android=2]="Android",ee[ee.IOS=3]="IOS",ee[ee.OpenHarmony=4]="OpenHarmony",ee[ee.Windows=5]="Windows",ee),uD=((et={})[et.None=1]="None",et[et.SidebarReward=2]="SidebarReward",et[et.AppActive=3]="AppActive",et),uF=((er={})[er.All=1]="All",er[er.New=2]="New",er[er.Active=3]="Active",er[er.PayNew=4]="PayNew",er[er.PayActive=5]="PayActive",er),uv=((ei={})[ei.All=1]="All",ei[ei.Sidebar=2]="Sidebar",ei),uw=((eu={})[eu.Model=1]="Model",eu[eu.Brand=2]="Brand",eu[eu.AppVersion=3]="AppVersion",eu[eu.LibVersion=4]="LibVersion",eu);let uB=(e=0)=>t=>`\u001B[${t+e}m`,ux=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,uS=(e=0)=>(t,r,i)=>`\u001B[${38+e};2;${t};${r};${i}m`,uT={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(uT.modifier);let uO=Object.keys(uT.color);[...uO,...Object.keys(uT.bgColor)];let uI=function(){let e=new Map;for(let[t,r]of Object.entries(uT)){for(let[t,i]of Object.entries(r))uT[t]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[t]=uT[t],e.set(i[0],i[1]);Object.defineProperty(uT,t,{value:r,enumerable:!1})}return Object.defineProperty(uT,"codes",{value:e,enumerable:!1}),uT.color.close="\x1b[39m",uT.bgColor.close="\x1b[49m",uT.color.ansi=uB(),uT.color.ansi256=ux(),uT.color.ansi16m=uS(),uT.bgColor.ansi=uB(10),uT.bgColor.ansi256=ux(10),uT.bgColor.ansi16m=uS(10),Object.defineProperties(uT,{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=>uT.rgbToAnsi256(...uT.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 u=(e-=16)%36;t=Math.floor(e/36)/5,r=Math.floor(u/6)/5,i=u%6/5}let u=2*Math.max(t,r,i);if(0===u)return 30;let n=30+(Math.round(i)<<2|Math.round(r)<<1|Math.round(t));return 2===u&&(n+=60),n},enumerable:!1},rgbToAnsi:{value:(e,t,r)=>uT.ansi256ToAnsi(uT.rgbToAnsi256(e,t,r)),enumerable:!1},hexToAnsi:{value:e=>uT.ansi256ToAnsi(uT.hexToAnsi256(e)),enumerable:!1}}),uT}(),uk=require("node:tty");function uR(e,t=globalThis.Deno?globalThis.Deno.args:I.argv){let r=e.startsWith("-")?"":1===e.length?"-":"--",i=t.indexOf(r+e),u=t.indexOf("--");return -1!==i&&(-1===u||i<u)}let{env:uj}=I;function uL(e,t={}){var r;return 0!==(r=function(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let u=function(){if("FORCE_COLOR"in uj)return"true"===uj.FORCE_COLOR?1:"false"===uj.FORCE_COLOR?0:0===uj.FORCE_COLOR.length?1:Math.min(Number.parseInt(uj.FORCE_COLOR,10),3)}();void 0!==u&&(i=u);let n=r?i:u;if(0===n)return 0;if(r){if(uR("color=16m")||uR("color=full")||uR("color=truecolor"))return 3;if(uR("color=256"))return 2}if("TF_BUILD"in uj&&"AGENT_NAME"in uj)return 1;if(e&&!t&&void 0===n)return 0;let o=n||0;if("dumb"===uj.TERM)return o;if("win32"===I.platform){let e=eX.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in uj)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(e=>e in uj)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(e=>e in uj)||"codeship"===uj.CI_NAME?1:o;if("TEAMCITY_VERSION"in uj)return+!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(uj.TEAMCITY_VERSION);if("truecolor"===uj.COLORTERM||"xterm-kitty"===uj.TERM||"xterm-ghostty"===uj.TERM||"wezterm"===uj.TERM)return 3;if("TERM_PROGRAM"in uj){let e=Number.parseInt((uj.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(uj.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(uj.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(uj.TERM)||"COLORTERM"in uj?1:o}(e,{streamIsTTY:e&&e.isTTY,...t}))&&{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}uR("no-color")||uR("no-colors")||uR("color=false")||uR("color=never")?i=0:(uR("color")||uR("colors")||uR("color=true")||uR("color=always"))&&(i=1);let uN={stdout:uL({isTTY:uk.isatty(1)}),stderr:uL({isTTY:uk.isatty(2)})},{stdout:uP,stderr:u$}=uN,uU=Symbol("GENERATOR"),uM=Symbol("STYLER"),uq=Symbol("IS_EMPTY"),uV=["ansi","ansi","ansi256","ansi16m"],uH=Object.create(null);function uz(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=uP?uP.level:0;e.level=void 0===t.level?r:t.level})(r=(...e)=>e.join(" "),t),Object.setPrototypeOf(r,uz.prototype),r}for(let[e,t]of(Object.setPrototypeOf(uz.prototype,Function.prototype),Object.entries(uI)))uH[e]={get(){let r=uK(this,uJ(t.open,t.close,this[uM]),this[uq]);return Object.defineProperty(this,e,{value:r}),r}};uH.visible={get(){let e=uK(this,this[uM],!0);return Object.defineProperty(this,"visible",{value:e}),e}};let uG=(e,t,r,...i)=>"rgb"===e?"ansi16m"===t?uI[r].ansi16m(...i):"ansi256"===t?uI[r].ansi256(uI.rgbToAnsi256(...i)):uI[r].ansi(uI.rgbToAnsi(...i)):"hex"===e?uG("rgb",t,r,...uI.hexToRgb(...i)):uI[r][e](...i);for(let e of["rgb","hex","ansi256"])uH[e]={get(){let{level:t}=this;return function(...r){return uK(this,uJ(uG(e,uV[t],"color",...r),uI.color.close,this[uM]),this[uq])}}},uH["bg"+e[0].toUpperCase()+e.slice(1)]={get(){let{level:t}=this;return function(...r){return uK(this,uJ(uG(e,uV[t],"bgColor",...r),uI.bgColor.close,this[uM]),this[uq])}}};let uW=Object.defineProperties(()=>{},{...uH,level:{enumerable:!0,get(){return this[uU].level},set(e){this[uU].level=e}}}),uJ=(e,t,r)=>{let i,u;return void 0===r?(i=e,u=t):(i=r.openAll+e,u=t+r.closeAll),{open:e,close:t,openAll:i,closeAll:u,parent:r}},uK=(e,t,r)=>{let i=(...e)=>uY(i,1===e.length?""+e[0]:e.join(" "));return Object.setPrototypeOf(i,uW),i[uU]=e,i[uM]=t,i[uq]=r,i},uY=(e,t)=>{if(e.level<=0||!t)return e[uq]?"":t;let r=e[uM];if(void 0===r)return t;let{openAll:i,closeAll:u}=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 u=t.length,n=0,o="";do o+=e.slice(n,i)+t+r,n=i+u,i=e.indexOf(t,n);while(-1!==i);return o+=e.slice(n)}(t,r.close,r.open),r=r.parent;let n=t.indexOf("\n");return -1!==n&&(t=function(e,t,r,i){let u=0,n="";do{let o="\r"===e[i-1];n+=e.slice(u,o?i-1:i)+t+(o?"\r\n":"\n")+r,u=i+1,i=e.indexOf("\n",u)}while(-1!==i);return n+=e.slice(u)}(t,u,i,n)),i+t+u};Object.defineProperties(uz.prototype,uH);let uX=uz();uz({level:u$?u$.level:0});let uQ=(e,t,r,i)=>{if("length"===r||"prototype"===r||"arguments"===r||"caller"===r)return;let u=Object.getOwnPropertyDescriptor(e,r),n=Object.getOwnPropertyDescriptor(t,r);(uZ(u,n)||!i)&&Object.defineProperty(e,r,n)},uZ=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)},u1=(e,t)=>`/* Wrapped ${e}*/
|
|
33
33
|
${t}`,u2=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),u0=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name"),u3=new WeakMap,u6=(e,t={})=>{let r;if("function"!=typeof e)throw TypeError("Expected a function");let i=0,u=e.displayName||e.name||"<anonymous>",n=function(...o){if(u3.set(n,++i),1===i)r=e.apply(this,o),e=void 0;else if(!0===t.throw)throw Error(`Function \`${u}\` can only be called once`);return r};return!function(e,t,{ignoreNonConfigurable:r=!1}={}){var i;let u,{name:n}=e;for(let i of Reflect.ownKeys(t))uQ(e,t,i,r);i=e,(u=Object.getPrototypeOf(t))!==Object.getPrototypeOf(i)&&Object.setPrototypeOf(i,u),((e,t,r)=>{let i=""===r?"":`with ${r.trim()}() `,u=u1.bind(null,i,t.toString());Object.defineProperty(u,"name",u0);let{writable:n,enumerable:o,configurable:s}=u2;Object.defineProperty(e,"toString",{value:u,writable:n,enumerable:o,configurable:s})})(e,t,n)}(n,e),u3.set(n,i),n};u6.callCount=e=>{if(!u3.has(e))throw Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return u3.get(e)};let u4=[];u4.push("SIGHUP","SIGINT","SIGTERM"),"win32"!==process.platform&&u4.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT"),"linux"===process.platform&&u4.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");let u8=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,u9=Symbol.for("signal-exit emitter"),u7=globalThis,u5=Object.defineProperty.bind(Object);class ne{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(u7[u9])return u7[u9];u5(u7,u9,{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 u of this.listeners[e])i=!0===u(t,r)||i;return"exit"===e&&(i=this.emit("afterExit",t,r)||i),i}}class nt{}class nr extends nt{#i="win32"===ni.platform?"SIGINT":"SIGHUP";#u=new ne;#n;#o;#s;#a={};#l=!1;constructor(e){for(const t of(super(),this.#n=e,this.#a={},u4))this.#a[t]=()=>{let r=this.#n.listeners(t),{count:i}=this.#u;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.#u.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(!u8(this.#n))return()=>{};!1===this.#l&&this.load();let r=t?.alwaysLast?"afterExit":"exit";return this.#u.on(r,e),()=>{this.#u.removeListener(r,e),0===this.#u.listeners.exit.length&&0===this.#u.listeners.afterExit.length&&this.unload()}}load(){if(!this.#l){for(let e of(this.#l=!0,this.#u.count+=1,u4))try{let t=this.#a[e];t&&this.#n.on(e,t)}catch(e){}this.#n.emit=(e,...t)=>this.#c(e,...t),this.#n.reallyExit=e=>this.#d(e)}}unload(){this.#l&&(this.#l=!1,u4.forEach(e=>{let t=this.#a[e];if(!t)throw Error("Listener not defined for signal: "+e);try{this.#n.removeListener(e,t)}catch(e){}}),this.#n.emit=this.#o,this.#n.reallyExit=this.#s,this.#u.count-=1)}#d(e){return u8(this.#n)?(this.#n.exitCode=e||0,this.#u.emit("exit",this.#n.exitCode,null),this.#s.call(this.#n,this.#n.exitCode)):0}#c(e,...t){let r=this.#o;if(!("exit"===e&&u8(this.#n)))return r.call(this.#n,e,...t);{"number"==typeof t[0]&&(this.#n.exitCode=t[0]);let i=r.call(this.#n,e,...t);return this.#u.emit("exit",this.#n.exitCode,null),i}}}let ni=globalThis.process,{onExit:nu,load:nn,unload:no}=(n=u8(ni)?new nr(ni):new class extends nt{onExit(){return()=>{}}load(){}unload(){}},{onExit:(e,t)=>n.onExit(e,t),load:()=>n.load(),unload:()=>n.unload()}),ns=I.stderr.isTTY?I.stderr:I.stdout.isTTY?I.stdout:void 0,na=ns?u6(()=>{nu(()=>{ns.write("\x1b[?25h")},{alwaysLast:!0})}):()=>{},nl=!1,nc={};nc.show=(e=I.stderr)=>{e.isTTY&&(nl=!1,e.write("\x1b[?25h"))},nc.hide=(e=I.stderr)=>{e.isTTY&&(na(),nl=!0,e.write("\x1b[?25l"))},nc.toggle=(e,t)=>{void 0!==e&&(nl=e),nl?nc.show(t):nc.hide(t)};var nd=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(nd);let nh=uk?.WriteStream?.prototype?.hasColors?.()??!1,np=(e,t)=>{if(!nh)return e=>e;let r=`\u001B[${e}m`,i=`\u001B[${t}m`;return e=>{let u=e+"",n=u.indexOf(i);if(-1===n)return r+u+i;let o=r,s=0,a=(22===t?i:"")+r;for(;-1!==n;)o+=u.slice(s,n)+a,s=n+i.length,n=u.indexOf(i,s);return o+=u.slice(s)+i}};np(0,0),np(1,22),np(2,22),np(3,23),np(4,24),np(53,55),np(7,27),np(8,28),np(9,29),np(30,39);let nf=np(31,39),nm=np(32,39),ng=np(33,39),nA=np(34,39);function nE(){let{env:e}=I,{TERM:t,TERM_PROGRAM:r}=e;return"win32"!==I.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}np(35,39),np(36,39),np(37,39),np(90,39),np(40,49),np(41,49),np(42,49),np(43,49),np(44,49),np(45,49),np(46,49),np(47,49),np(100,49),np(91,39),np(92,39),np(93,39),np(94,39),np(95,39),np(96,39),np(97,39),np(101,49),np(102,49),np(103,49),np(104,49),np(105,49),np(106,49),np(107,49);let ny=nE(),nb=nA(ny?"ℹ":"i"),n_=nm(ny?"✔":"√"),nC=ng(ny?"⚠":"‼"),nD=nf(ny?"✖":"\xd7"),nF=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")}(),nv=[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],nw=[12288,12288,65281,65376,65504,65510],nB=[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],nx=(e,t)=>{let r=0,i=Math.floor(e.length/2)-1;for(;r<=i;){let u=Math.floor((r+i)/2),n=2*u;if(t<e[n])i=u-1;else{if(!(t>e[n+1]))return!0;r=u+1}}return!1},[nS,nT]=function(e){let t=e[0],r=e[1];for(let i=0;i<e.length;i+=2){let u=e[i],n=e[i+1];if(19968>=u&&19968<=n)return[u,n];n-u>r-t&&(t=u,r=n)}return[t,r]}(nB);function nO(e,{ambiguousAsWide:t=!1}={}){var r,i,u,n=e;if(!Number.isSafeInteger(n))throw TypeError(`Expected a code point, got \`${typeof n}\`.`);return!((r=e)<12288)&&!(r>65510)&&nx(nw,r)||(i=e)>=nS&&i<=nT||!(i<4352)&&!(i>262141)&&nx(nB,i)||t&&!((u=e)<161)&&!(u>1114109)&&nx(nv,u)?2:1}let nI=new Intl.Segmenter,nk=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})+$/v,nR=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,nj=/^\p{RGI_Emoji}$/v,nL=/^[\d#*]\u20E3$/,nN=/\p{Extended_Pictographic}/gu;function nP(e){return e>=4352&&e<=4447||e>=43360&&e<=43388}function n$(e){return e>=4448&&e<=4519||e>=55216&&e<=55238}function nU(e){return e>=4520&&e<=4607||e>=55243&&e<=55291}let nM=Object.freeze(new class{#h=0;#p;#f=!1;#m=!1;#g=e=>{e?.length&&("string"==typeof e?e.codePointAt(0):e[0])===3&&I.kill(I.pid,"SIGINT")};start(){this.#h++,1===this.#h&&this.#A()}stop(){0!==this.#h&&0==--this.#h&&this.#E()}#A(){let{stdin:e}=I;if("win32"===I.platform||!e?.isTTY||"function"!=typeof e.setRawMode){this.#p=void 0;return}this.#p=e,this.#f=e.isPaused(),this.#m=!!e.isRaw,e.setRawMode(!0),e.prependListener("data",this.#g),this.#f&&e.resume()}#E(){if(!this.#p)return;let e=this.#p;e.off("data",this.#g),e.isTTY&&e.setRawMode?.(this.#m),this.#f&&e.pause(),this.#p=void 0,this.#f=!1,this.#m=!1}}),nq=new Map,nV=new Set(["black","red","green","yellow","blue","magenta","cyan","white","gray"]);class nH{#y=0;#b=-1;#_=0;#C;#D;#F;#v;#w=new Map;#B=!1;#x;#S;#T=!1;#O;#I(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)}#j(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)}#P(e,t,r,i){let u=this.#$(r," ");return u+e+("string"==typeof t?(e?" ":"")+t:"")+this.#U(i," ")}constructor(e){if("string"==typeof e&&(e={text:e}),this.#C={color:"cyan",stream:I.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#C.color,this.#F=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.#F})),"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"===I.env.NODE_ENV&&(this._stream=this.#F,this._isEnabled=this.#C.isEnabled,Object.defineProperty(this,"_linesToClear",{get(){return this.#y},set(e){this.#y=e}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#b}}),Object.defineProperty(this,"_lineCount",{get(){let e=this.#F.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.#M(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.#D.interval??100}get spinner(){return this.#D}set spinner(e){if(this.#b=-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.#D=e}else if(nE())if(void 0===e)this.#D=nd.dots;else if("default"!==e&&nd[e])this.#D=nd[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.#D=nd.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.#v}#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)}#U(e=this.#C.suffixText,t=" "){return this.#q(e,t,!0)}#M(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,u=e;if(!i&&(u.includes("\x1b")||u.includes("\x9b"))&&(u=function(e){if("string"!=typeof e)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.includes("\x1b")||e.includes("\x9b")?e.replace(nF,""):e}(u)),0===u.length)return 0;if(/^[\u0020-\u007E]*$/.test(u))return u.length;let n=0,o={ambiguousAsWide:!r};for(let{segment:e}of nI.segment(u)){var s;if(s=e,nk.test(s))continue;if(nj.test(e)||function(e){if(e.length>50)return!1;if(nL.test(e))return!0;if(e.includes("")){let t=e.match(nN);return null!==t&&t.length>=2}return!1}(e)){n+=2;continue}let t=e.replace(nR,""),r=function(e,t){let r=[];for(let t of e)nk.test(t)||r.push(t.codePointAt(0));if(0===r.length)return;let i=0;for(let e=0;e<r.length;e++){var u;let n=r[e];if(!(nP(u=n)||n$(u)||nU(u))){if(0===i)return;for(let u=e;u<r.length;u++)i+=nO(r[u],t);break}if(nP(n)&&n$(r[e+1])){i+=2,e+=nU(r[e+2])?2:1;continue}i+=nO(n,t)}return i}(t,o);if(void 0!==r){n+=r;continue}n+=nO(t.codePointAt(0),o),n+=function(e,t){let r=0,i=!0;for(let u of e){if(i){i=!1;continue}u>=""&&u<=""&&(r+=nO(u.codePointAt(0),t))}return r}(t,o)}return n}(i)/t));return r}get color(){return this.#O}set color(e){if(void 0!==e&&!1!==e&&!nV.has(e))throw Error("The `color` option must be a valid color or `false` to disable");this.#O=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.#b||e-this.#_>=this.interval)&&(this.#b=(this.#b+1)%this.#D.frames.length,this.#_=e);let{frames:t}=this.#D,r=t[this.#b];this.#O&&(r=uX[this.#O](r));let i=this.#$(this.#C.prefixText," "),u="string"==typeof this.text?" "+this.text:"";return i+r+u+this.#U(this.#C.suffixText," ")}clear(){return this.isEnabled&&this.#F.isTTY&&(this.#I(()=>{this.#F.cursorTo(0);for(let e=0;e<this.#y;e++)e>0&&this.#F.moveCursor(0,-1),this.#F.clearLine(1);this.#C.indent&&this.#F.cursorTo(this.#C.indent)}),this.#y=0),this}#V(e){if(!e||this.#w.has(e)||!e.isTTY||"function"!=typeof e.write)return;nq.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),nq.set(e,this),e.write=(r,i,u)=>this.#H(e,t,r,i,u)}#z(){if(this.isEnabled&&!(this.#w.size>0))for(let e of new Set([this.#F,I.stdout,I.stderr]))this.#V(e)}#G(){for(let[e,t]of this.#w)e.write=t,nq.get(e)===this&&nq.delete(e);this.#w.clear()}#H(e,t,r,i,u){if("function"==typeof i&&(u=i,i=void 0),this.#B)return t.call(e,r,i,u);this.clear();let n=this.#R(r,i),o=this.#j(n),s=t.call(e,r,i,u);return o?this.#N():n.length>0&&this.#L(),this.isSpinning&&!this.#S&&this.render(),s}render(){if(!this.isEnabled||this.#x||this.#S)return this;let e=this.#F.isTTY,t=!1;try{e&&(this.#I(()=>this.#F.write("\x1b[?2026h")),t=!0),this.clear();let r=this.frame(),i=this.#F.columns??80,u=this.#M(r,i),n=this.#F.rows;if(n&&n>1&&u>n){let e=r.split("\n");r=[...e.slice(0,n-1),"... (content truncated to fit terminal)"].join("\n")}let o=this.#I(()=>this.#F.write(r));!1===o&&this.#F.isTTY&&(this.#x=()=>{this.#x=void 0,this.#k()},this.#F.once("drain",this.#x)),this.#y=this.#M(r,i)}finally{t&&this.#I(()=>this.#F.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.#P(e,this.text,this.#C.prefixText,this.#C.suffixText);return""!==t.trim()&&this.#I(()=>this.#F.write(t+"\n")),this}return this.isSpinning||(this.#C.hideCursor&&nc.hide(this.#F),this.#C.discardStdin&&I.stdin.isTTY&&(nM.start(),this.#T=!0),this.#z(),this.render(),this.#v=setInterval(this.render.bind(this),this.interval)),this}stop(){return clearInterval(this.#v),this.#v=void 0,this.#b=-1,this.#_=0,this.#N(),this.#G(),this.#x&&(this.#F.removeListener("drain",this.#x),this.#x=void 0),this.isEnabled&&(this.clear(),this.#C.hideCursor&&nc.show(this.#F)),this.#T&&(this.#T=!1,nM.stop()),this}succeed(e){return this.stopAndPersist({symbol:n_,text:e})}fail(e){return this.stopAndPersist({symbol:nD,text:e})}warn(e){return this.stopAndPersist({symbol:nC,text:e})}info(e){return this.stopAndPersist({symbol:nb,text:e})}stopAndPersist(e={}){if(this.isSilent)return this;let t=e.symbol??" ",r=e.text??this.text,i=e.prefixText??this.#C.prefixText,u=e.suffixText??this.#C.suffixText,n=this.#P(t,r,i,u)+"\n";return this.stop(),this.#I(()=>this.#F.write(n)),this}}function nz(e){return new nH(e)}async function nG(e,t,r){return eM({appId:t.appId,caller:t.caller}),(async()=>{let i=nz(`正在执行 ${e} ...`).start();try{let{rawResponse:u,rows:n,csvHeader:o,resultMeta:s}=await r({caller:t.caller}),a=eq()?.response?.logId,{summaryPath:l}=await rK({appName:"dymg",command:e,caller:t.caller,rawResponse:u,rows:n,csvHeader:o,outputDir:t.outputDir,logId:a,resultMeta:s});i.succeed(`${e} 执行完成,已写入 ${n.length} 行数据,summary.json: ${l}`)}catch(u){i.fail(`${e} 执行失败`);let t=d(u)||u instanceof Error?u.message:String(u);eM({errorMessage:t,errorCode:un(u)}),process.stderr.write(`${t}
|
|
34
34
|
`);let r=eq()?.response?.logId;r&&process.stderr.write(`请求日志 ID: ${r}
|
|
@@ -41,18 +41,19 @@ ${t}`,u2=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),u0=Objec
|
|
|
41
41
|
`);await iR();let[t,{profile:r,client:i}]=await Promise.all([iT(),oe()]);ot(t??e,r,i,"当前已登录")}async function os(){let e=nz("正在退出当前登录 ...").start();try{let t,r=await iT().catch(()=>void 0);try{await ik(r)}catch(e){t=e}if(await Promise.all([iL(),iX()]),t)return void e.warn("已清理本地登录态,服务端撤销失败");e.succeed("已退出登录")}catch(t){if(e.fail("退出登录失败"),il(t))throw t;throw new l("退出登录失败",{cause:t,error:"AUTH_LOGOUT_FAILED",message:"退出登录失败,请检查网络或本机登录目录权限后重试"})}}async function oa(){let e=function(){let{dataDir:e}=rV({appName:"dymg"});return(0,T.join)(e,ir())}(),t={writable:!1};try{await (0,eQ.mkdir)(e,{recursive:!0});let r=await (0,eQ.mkdtemp)((0,T.join)(e,".auth-write-test-"));t.writable=!0,t.message="登录态目录可写",await (0,eQ.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)}
|
|
42
42
|
`)}let ol=require("node:readline");var oc=__webpack_require__("../../node_modules/.pnpm/mute-stream@3.0.0/node_modules/mute-stream/lib/index.js"),od=__webpack_require__("../../node_modules/.pnpm/cli-width@4.1.0/node_modules/cli-width/index.js");let oh=(o=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,e=>{let t=0;for(o.lastIndex=0;o.test(e);)t+=1;return e.length-t}),op=e=>12288===e||e>=65281&&e<=65376||e>=65504&&e<=65510,of=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,om=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,og=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,oA=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,oE=/\t{1,1000}/y,oy=/[\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,ob=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,o_=/\p{M}+/gu,oC={limit:1/0,ellipsis:""},oD=(e,t={},r={})=>{let i=t.limit??1/0,u=t.ellipsis??"",n=t?.ellipsisWidth??(u?oD(u,oC,r).width:0),o=r.controlWidth??0,s=r.tabWidth??8,a=r.emojiWidth??2,l=r.regularWidth??1,c=r.wideWidth??2,d=[[ob,l],[om,0],[og,o],[oE,s],[oy,a],[oA,c]],h=0,p=0,f=e.length,m=0,g=!1,A=f,E=Math.max(0,i-n),y=0,b=0,_=0,C=0;s:for(;;){if(b>y||p>=f&&p>h){let t=e.slice(y,b)||e.slice(h,p);for(let e of(m=0,t.replaceAll(o_,""))){let t=e.codePointAt(0)||0;if(_+(C=op(t)?2:of(t)?c:l)>E&&(A=Math.min(A,Math.max(y,h)+m)),_+C>i){g=!0;break s}m+=e.length,_+=C}y=b=0}if(p>=f)break;for(let t=0,r=d.length;t<r;t++){let[r,u]=d[t];if(r.lastIndex=p,r.test(e)){if(_+(C=(m=r===oA?oh(e.slice(p,r.lastIndex)):r===oy?1:r.lastIndex-p)*u)>E&&(A=Math.min(A,p+Math.floor((E-_)/u))),_+C>i){g=!0;break s}_+=C,y=h,b=p,p=h=r.lastIndex;continue s}}p+=1}return{width:g?E:_,index:g?A:f,truncated:g,ellipsed:g&&i>=n}},oF={limit:1/0,ellipsis:"",ellipsisWidth:0},ov=(e,t={})=>oD(e,oF,t).width,ow="]8;;",oB=RegExp(`(?:\\[(?<code>\\d+)m|\\${ow}(?<uri>.*)\u0007)`,"y"),ox=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,oS=e=>`\x1b[${e}m`,oT=e=>`\x1b${ow}${e}\u0007`,oO=(e,t,r)=>{let i=t[Symbol.iterator](),u=!1,n=!1,o=e.at(-1),s=void 0===o?0:ov(o),a=i.next(),l=i.next(),c=0;for(;!a.done;){let o=a.value,d=ov(o);s+d<=r?e[e.length-1]+=o:(e.push(o),s=0),("\x1b"===o||"\x9b"===o)&&(u=!0,n=t.startsWith(ow,c+1)),u?n?"\x07"===o&&(u=!1,n=!1):"m"===o&&(u=!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())},oI=/\r?\n/;class ok extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super(),this.cause=e?.cause}}class oR extends Error{name="CancelPromptError";message="Prompt was canceled"}class oj extends Error{name="ExitPromptError"}class oL extends Error{name="HookError"}class oN extends Error{name="ValidationError"}let oP=new s.AsyncLocalStorage;function o$(){let e=oP.getStore();if(!e)throw new oL("[Inquirer] Hook functions can only be called from within a prompt");return e}function oU(e){return s.AsyncResource.bind((...t)=>{let r=o$(),i=!1,u=r.handleChange;r.handleChange=()=>{i=!0};let n=e(...t);return i&&u(),r.handleChange=u,n})}function oM(e){let t=o$(),{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 oq={queue(e){let t=o$(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let i=e(o$().rl);if(null!=i&&"function"!=typeof i)throw new oN("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=i})},run(){let e=o$();oU(()=>{e.hooksEffect.forEach(e=>{e()}),e.hooksEffect.length=0})()},clearAll(){let e=o$();e.hooksCleanup.forEach(e=>{e?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function oV(e,t){return e.split("\n").flatMap(e=>{var r,i,u;return(r=e,i=t,u={trim:!1,wordWrap:!1},String(r).normalize().split(oI).map(e=>((e,t,r={})=>{let i,u;if(!1!==r.trim&&""===e.trim())return"";let n="",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=ov(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 u=ov(i);if(r.hard&&u>t){let e=1+Math.floor((u-(t-a)-1)/t);Math.floor((u-1)/t)<e&&s.push(""),oO(s,i,t),a=ov(s.at(-1)??"");continue}if(a+u>t&&a&&u){if(!1===r.wordWrap&&a<t){oO(s,i,t),a=ov(s.at(-1)??"");continue}s.push(""),a=0}if(a+u>t&&!1===r.wordWrap){oO(s,i,t),a=ov(s.at(-1)??"");continue}s[s.length-1]+=i,a+=u}!1!==r.trim&&(s=s.map(e=>(e=>{let t=e.split(" "),r=t.length;for(;r&&!ov(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(n+=t,c)c=!1;else if(c=t>="\uD800"&&t<="\uDBFF")continue;if("\x1b"===t||"\x9b"===t){oB.lastIndex=e+1;let t=oB.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&&(u=0===r.uri.length?void 0:r.uri)}if("\n"===l[e+1]){u&&(n+=oT(""));let e=i?ox(i):void 0;i&&e&&(n+=oS(e))}else"\n"===t&&(i&&ox(i)&&(n+=oS(i)),u&&(n+=oT(u)))}return n})(e,i,u)).join("\n")).split("\n").map(e=>e.trimEnd())}).join("\n")}function oH(){return od({defaultWidth:80,output:o$().rl.output})}let oz="\x1b[G",oG=(e=1)=>e>0?`\u001B[${e}A`:"",oW=(e=1)=>e>0?`\u001B[${e}B`:"",oJ=(e,t)=>"number"!=typeof t||Number.isNaN(t)?`\u001B[${e+1}G`:`\u001B[${t+1};${e+1}H`,oK="\x1b[2K",oY=e=>e>0?(oK+oG(1)).repeat(e-1)+oK+oz:"";class oX{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),u=i;this.rl.line.length>0&&(u=u.slice(0,-this.rl.line.length)),this.rl.setPrompt(u),this.cursorPos=this.rl.getCursorPos();let n=oH();e=oV(e,n),t=oV(t,n),i.length%n==0&&(e+="\n");let o=e+(t?"\n"+t:""),s=Math.floor(i.length/n)-this.cursorPos.rows+(t?t.split("\n").length:0);s>0&&(o+=oG(s)),o+=oJ(this.cursorPos.cols),this.write(oW(this.extraLinesUnderPrompt)+oY(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(oJ(e.cols)),this.cursorPos=e)}done({clearContent:e}){this.rl.setPrompt("");let t=oW(this.extraLinesUnderPrompt);t+=e?oY(this.height):"\n",t+="\x1b[G",t+="\x1b[?25h",this.write(t),this.rl.close()}}class oQ extends Promise{static withResolver(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}}}let oZ=globalThis.setImmediate;function o1(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:u=process.stdin,signal:n}=i,o=new Set,a=new oc;a.pipe(i.output??process.stdout);let l=ol.createInterface({terminal:!0,input:u,output:a});a.mute();let c=new oX(l),{promise:d,resolve:h,reject:p}=oQ.withResolver(),f=()=>p(new oR);if(n){let e=()=>p(new ok({cause:n.reason}));if(n.aborted)return e(),Object.assign(d,{cancel:f});n.addEventListener("abort",e),o.add(()=>n.removeEventListener("abort",e))}o.add(nu((e,t)=>{p(new oj(`User force closed the prompt with ${e} ${t}`))}));let m=()=>p(new oj("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 oP.run(A,()=>{var n;let m,g;return n=function(e){A.handleChange=()=>{A.index=0,e()},A.handleChange()},m=s.AsyncResource.bind(()=>oq.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 u=null;n(()=>{let i=!1;try{let n=e(r,e=>{i?h(e):u={value:e}});if(void 0===n){let e=t[1]?.getFileName();throw e&&!e.startsWith("file://")&&(e=T.resolve(e)),Error(`Prompt functions must return a string.
|
|
43
43
|
at ${e}`)}let[o,s]="string"==typeof n?[n]:n;c.render(o,s),oq.run()}catch(e){p(e)}if(i=!0,null!==u){let{value:e}=u;u=null,h(e)}})},"readableFlowing"in u?oZ(g):g(),Object.assign(d.then(e=>(oq.clearAll(),e),e=>{throw oq.clearAll(),e}).finally(()=>{o.forEach(e=>e()),c.done({clearContent:!!i.clearPromptOnDone}),a.end()}).then(()=>d),{cancel:f})})}}let o2={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:"╱"},o0={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:"⅒"},o3={...o2,...o0},o6={...o2,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"},o4=I.platform.startsWith("win")?!!I.env.CI||!!I.env.WT_SESSION||!!I.env.TERMINUS_SUBLIME||"{cmd::Cmder}"===I.env.ConEmuTask||"Terminus-Sublime"===I.env.TERM_PROGRAM||"vscode"===I.env.TERM_PROGRAM||"xterm-256color"===I.env.TERM||"alacritty"===I.env.TERM||"JetBrains-JediTerm"===I.env.TERMINAL_EMULATOR:"linux"!==I.env.TERM,o8=o4?o3:o6;Object.entries(o0);let o9=new Set(["emacs","vim"]);function o7(e){return o9.has(e)}let o5=(e,t=[])=>"up"===e.name||t.includes("vim")&&"k"===e.name||t.includes("emacs")&&e.ctrl&&"p"===e.name,se=(e,t=[])=>"down"===e.name||t.includes("vim")&&"j"===e.name||t.includes("emacs")&&e.ctrl&&"n"===e.name,st=e=>"enter"===e.name||"return"===e.name,sr={prefix:{idle:(0,k.styleText)("blue","?"),done:(0,k.styleText)("green",o8.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 si(e){if("object"!=typeof e||null===e)return!1;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function su(...e){let t;return function e(...t){let r={};for(let i of t)for(let[t,u]of Object.entries(i)){let i=r[t];r[t]=si(i)&&si(u)?e(i,u):u}return r}({...sr,keybindings:(t=process.env.INQUIRER_KEYBINDINGS)?Array.from(new Set(t.toLowerCase().split(/[\s,]+/).filter(o7))):[]},...e.filter(e=>null!=e))}function sn(e){return oM(t=>{let r=s.AsyncResource.bind(function(e){t.get()!==e&&(t.set(e),o$().handleChange())});if(t.initialized)return[t.get(),r];let i="function"==typeof e?e():e;return t.set(i),[i,r]})}function so(e,t){oM(r=>{let i=r.get();(!Array.isArray(i)||t.some((e,t)=>!Object.is(e,i[t])))&&oq.queue(e),r.set(t)})}function ss({status:e="idle",theme:t}){let[r,i]=sn(!1),[u,n]=sn(0),{prefix:o,spinner:s}=su(t);if(so(()=>{if("loading"===e){let e,t=-1,r=setTimeout(()=>{i(!0),e=setInterval(()=>{n((t+=1)%s.frames.length)},s.interval)},300);return()=>{clearTimeout(r),clearInterval(e)}}i(!1)},[e]),r)return s.frames[u];let a="loading"===e?"idle":e;return"string"==typeof o?o:o[a]??o.idle}function sa(e){return sn({current:e})[0]}function sl(e){let t=sa(e);t.current=e,so(e=>{let r=!1,i=oU((i,u)=>{r||t.current(u,e)});return e.input.on("keypress",i),()=>{r=!0,e.input.removeListener("keypress",i)}},[])}let sc={validationFailureMode:"keep"},sd=o1((e,t)=>{let r,{prefill:i="tab"}=e,u=su(sc,e.theme),[n,o]=sn("idle"),[s,a]=sn(String(e.default??"")),[l,c]=sn(),[d,h]=sn(""),p=ss({status:n,theme:u});async function f(t){let{required:r,pattern:i,patternError:u="Invalid input"}=e;return r&&!t?"You must provide a value":i&&!i.test(t)?u:"function"!=typeof e.validate||await e.validate(t)||"You must provide a valid value"}sl(async(e,r)=>{if("idle"===n)if(st(e)){let e=d||s;o("loading");let i=await f(e);!0===i?(h(e),o("done"),t(e)):("clear"===u.validationFailureMode?h(""):r.write(d),c(i),o("idle"))}else"backspace"!==e.name||d?"tab"!==e.name||d?(h(r.line),c(void 0)):(a(""),r.clearLine(0),r.write(s),h(s)):a("")}),so(e=>{"editable"===i&&s&&(e.write(s),h(s))},[]);let m=u.style.message(e.message,n),g=d;"function"==typeof e.transformer?g=e.transformer(d,{isFinal:"done"===n}):"done"===n&&(g=u.style.answer(d)),s&&"done"!==n&&!d&&(r=u.style.defaultAnswer(s));let A="";return l&&(A=u.style.error(l)),[[p,m,r,g].filter(e=>void 0!==e).join(" "),A]});class sh{separator=(0,k.styleText)("dim",Array.from({length:15}).join(o8.line));type="separator";constructor(e){e&&(this.separator=e)}static isSeparator(e){return!!(e&&"object"==typeof e&&"type"in e&&"separator"===e.type)}}function sp(e,t){return oM(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 sf({items:e,active:t,renderItem:r,pageSize:i,loop:u=!0}){let n=oH(),o=t=>(t%e.length+e.length)%e.length,s=e.map((e,i)=>null==e?[]:oV(r({item:e,index:i,isActive:i===t}),n).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 u=sa({lastPointer:e,lastActive:void 0}),{lastPointer:n,lastActive:o}=u.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=n,null!=o&&o<e&&e-o<r&&(c=Math.min(s,1===Math.abs(e-o)?Math.min(n+(t[o]?.length??0),Math.max(l,n)):n+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 u.current.lastPointer=c,u.current.lastActive=e,c}({active:t,renderedItems:s,pageSize:i,loop:u}),d=l(t).slice(0,i),h=c+d.length<=i?c:i-d.length,p=Array.from({length:i});p.splice(h,d.length,...d);let f=new Set([t]),m=h+d.length,g=o(t+1);for(;m<i&&!f.has(g)&&(u&&a>i?g!==t:g>t);){let e=l(g).slice(0,i-m);p.splice(m,e.length,...e),f.add(g),m+=e.length,g=o(g+1)}for(m=h-1,g=o(t-1);m>=0&&!f.has(g)&&(u&&a>i?g!==t:g<t);){let e=l(g),t=e.slice(Math.max(0,e.length-m-1));p.splice(m-t.length+1,t.length,...t),f.add(g),m-=t.length,g=o(g-1)}return p.filter(e=>"string"==typeof e).join("\n")}let sm={icon:{cursor:o8.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 sg(e){return!sh.isSeparator(e)&&!e.disabled}function sA(e){return!sh.isSeparator(e)}let sE=o1((e,t)=>{let{loop:r=!0,pageSize:i=7}=e,u=su(sm,e.theme),{keybindings:n}=u,[o,s]=sn("idle"),a=ss({status:o,theme:u}),l=sa(),c=!n.includes("vim"),d=sp(()=>e.choices.map(e=>{if(sh.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]),h=sp(()=>{let e=d.findIndex(sA),t=d.findLastIndex(sA);if(-1===e)throw new oN("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[d]),p=sp(()=>"default"in e?d.findIndex(t=>sg(t)&&t.value===e.default):-1,[e.default,d]),[f,m]=sn(-1===p?h.first:p),g=d[f];if(null==g||sh.isSeparator(g))throw Error("Active index does not point to a choice");let[A,E]=sn();sl((e,i)=>{if(clearTimeout(l.current),A&&E(void 0),st(e))g.disabled?E(u.i18n.disabledError):(s("done"),t(g.value));else if(o5(e,n)||se(e,n)){if(i.clearLine(0),r||o5(e,n)&&f!==h.first||se(e,n)&&f!==h.last){let t=o5(e,n)?-1:1,r=f;do r=(r+t+d.length)%d.length;while(!sA(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=>!sh.isSeparator(r)&&++t===e),u=d[r];null!=u&&sg(u)&&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=>!sh.isSeparator(t)&&!!sg(t)&&t.name.toLowerCase().startsWith(e));-1!==t&&m(t),l.current=setTimeout(()=>{i.clearLine(0)},700)}}}),so(()=>()=>{clearTimeout(l.current)},[]);let y=u.style.message(e.message,o),b=u.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),_=0,C=sf({items:d,active:f,renderItem({item:e,isActive:t,index:r}){if(sh.isSeparator(e))return _++,` ${e.separator}`;let i=t?u.icon.cursor:" ",n="number"===u.indexMode?`${r+1-_}. `:"";if(e.disabled){let r="string"==typeof e.disabled?e.disabled:"(disabled)",i=t?u.icon.cursor:"-";return u.style.disabled(`${i} ${n}${e.name} ${r}`)}return(t?u.style.highlight:e=>e)(`${i} ${n}${e.name}`)},pageSize:i,loop:r});if("done"===o)return[a,y,u.style.answer(g.short)].filter(Boolean).join(" ");let{description:D}=g,F=[[a,y].filter(Boolean).join(" "),C," ",D?u.style.description(D):"",A?u.style.error(A):"",b].filter(Boolean).join("\n").trimEnd();return`${F}\u001b[?25l`});function sy(e,{min:t,max:r,step:i}){var u,n,o;return!(null==e||Number.isNaN(e))&&(e<t||e>r?`Value must be between ${t} and ${r}`:"any"===i||(u=e,n=i,(1e6*u-(Number.isFinite(o=t)?1e6*o:0))%(1e6*n)==0)||`Value must be a multiple of ${i}${Number.isFinite(t)?` starting from ${t}`:""}`)}let sb=o1((e,t)=>{let r,{validate:i=()=>!0,min:u=-1/0,max:n=1/0,step:o=1,required:s=!1}=e,a=su(e.theme),[l,c]=sn("idle"),[d,h]=sn(""),[p="",f]=sn(!0===sy(e.default,{min:u,max:n,step:o})?e.default?.toString():void 0),[m,g]=sn(),A=ss({status:l,theme:a});sl(async(e,r)=>{if("idle"===l)if(st(e)){let e=d||p,a=""===e?void 0:Number(e);c("loading");let l=!0;(s||null!=a)&&(l=sy(a,{min:u,max:n,step:o})),!0===l&&null!=a&&(l=await i(a)),!0===l?(h(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?(h(r.line),g(void 0)):(f(void 0),r.clearLine(0),r.write(p),h(p)):f(void 0)});let E=a.style.message(e.message,l),y=d;"done"===l&&(y=a.style.answer(d)),p&&"done"!==l&&!d&&(r=a.style.defaultAnswer(p));let b="";return m&&(b=a.style.error(m)),[[A,E,r,y].filter(e=>void 0!==e).join(" "),b]});function s_(e,t){let r=!1!==t;return/^(y|yes)/i.test(e)?r=!0:/^(n|no)/i.test(e)&&(r=!1),r}function sC(e){return e?"Yes":"No"}let sD=o1((e,t)=>{let{transformer:r=sC}=e,[i,u]=sn("idle"),[n,o]=sn(""),s=su(e.theme),a=ss({status:i,theme:s});sl((s,a)=>{if("idle"===i)if(st(s)){let i=s_(n,e.default);o(r(i)),u("done"),t(i)}else if("tab"===s.name){let t=sC(!s_(n,e.default));a.clearLine(0),a.write(t),o(t)}else o(a.line)});let l=n,c="";"done"===i?l=s.style.answer(n):c=` ${s.style.defaultAnswer(!1===e.default?"y/N":"Y/n")}`;let d=s.style.message(e.message,i);return`${a} ${d}${c} ${l}`}),sF=/\d+/,sv={style:{description:e=>(0,k.styleText)("cyan",e)}};function sw(e){return null!=e&&!sh.isSeparator(e)}function sB(e,t){let r,i=t.filter(sw);return!(r=i.find(t=>t.key===e))&&sF.test(e)&&(r=i[Number.parseInt(e,10)-1]),r?[r,t.indexOf(r)]:[void 0,void 0]}let sx=o1((e,t)=>{let{loop:r=!0}=e,i=sp(()=>{var t;let r;return t=e.choices,r=0,t.map(e=>{if(sh.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]),[u,n]=sn("idle"),[o,s]=sn(()=>{let t=null==e.default?void 0:i.find(t=>sw(t)&&t.value===e.default);return t?.key??""}),[a,l]=sn(),c=su(sv,e.theme),{keybindings:d}=c,h=ss({status:u,theme:c}),p=sp(()=>{let e=i.findIndex(sw),t=i.findLastIndex(sw);if(-1===e)throw new oN("[select prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[i]);sl((e,u)=>{if(st(e)){let[e]=sB(o,i);sw(e)?(s(e.short),n("done"),t(e.value)):""===o?l("Please input a value"):l(`"${(0,k.styleText)("red",o)}" isn't an available option`)}else if(o5(e,d)||se(e,d)){u.clearLine(0);let[t,n]=sB(o,i);if(t){if(r||o5(e,d)&&n!==p.first||se(e,d)&&n!==p.last){let t,r=o5(e,d)?-1:1,u=n;do u=(u+r+i.length)%i.length,t=i[u];while(!sw(t));s(t.key)}}else s((se(e,d)?i.find(sw):i.findLast(sw)).key)}else s(u.line),l(void 0)});let f=c.style.message(e.message,u);if("done"===u)return`${h} ${f} ${c.style.answer(o)}`;let m=i.map(e=>{if(sh.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]=sB(o,i),E="";return!a&&A?.description&&(E=c.style.description(A.description)),[`${h} ${f} ${o}`,[m,g,E].filter(Boolean).join("\n")]}),sS={key:"h",name:"Help, list all options",value:void 0},sT=o1((e,t)=>{let{default:r="h"}=e,i=sp(()=>e.choices.map(e=>{if(sh.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]),[u,n]=sn("idle"),[o,s]=sn(""),[a,l]=sn(e.expanded??!1),[c,d]=sn(),h=su(e.theme),p=ss({theme:h,status:u});sl((e,u)=>{if(st(e)){let e=(o||r).toLowerCase();if("h"!==e||a){let r=i.find(t=>!sh.isSeparator(t)&&t.key===e);r?(n("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(u.line),d(void 0)});let f=h.style.message(e.message,u);if("done"===u){let e=i.find(e=>!sh.isSeparator(e)&&e.key===o.toLowerCase());return`${p} ${f} ${h.style.answer(e.name)}`}let m=a?i:[...i,sS],g="",A=m.map(e=>sh.isSeparator(e)?"":e.key===r?e.key.toUpperCase():e.key).join("");A=` ${h.style.defaultAnswer(A)}`,a&&(A="",g=m.map(e=>{if(sh.isSeparator(e))return` ${e.separator}`;let t=` ${e.key}) ${e.name}`;return e.key===o.toLowerCase()?h.style.highlight(t):t}).join("\n"));let E="",y=i.find(e=>!sh.isSeparator(e)&&e.key===o.toLowerCase());y&&(E=`${(0,k.styleText)("cyan",">>")} ${y.name}`);let b="";return c&&(b=h.style.error(c)),[`${p} ${f}${A} ${o}`,[g,E,b].filter(Boolean).join("\n")]}),sO={icon:{checked:(0,k.styleText)("green",o8.circleFilled),unchecked:o8.circle,cursor:o8.pointer,disabledChecked:(0,k.styleText)("green",o8.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 sI(e){return!sh.isSeparator(e)&&!e.disabled}function sk(e){return!sh.isSeparator(e)}function sR(e){return!sh.isSeparator(e)&&e.checked}function sj(e){return sI(e)?{...e,checked:!e.checked}:e}let sL=o1((e,t)=>{let r,{pageSize:i=7,loop:u=!0,required:n,validate:o=()=>!0}=e,s={all:"a",invert:"i",...e.shortcuts},a=su(sO,e.theme),{keybindings:l}=a,[c,d]=sn("idle"),h=ss({status:c,theme:a}),[p,f]=sn(e.choices.map(e=>{if(sh.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=sp(()=>{let e=p.findIndex(sk),t=p.findLastIndex(sk);if(-1===e)throw new oN("[checkbox prompt] No selectable choices. All choices are disabled.");return{first:e,last:t}},[p]),[g,A]=sn(m.first),[E,y]=sn();sl(async e=>{if(st(e)){let e=p.filter(sR),r=await o([...e]);n&&!e.length?y("At least one choice must be selected"):!0===r?(d("done"),t(e.map(e=>e.value))):y(r||"You must select a valid value")}else if(o5(e,l)||se(e,l)){if(E&&y(void 0),u||o5(e,l)&&g!==m.first||se(e,l)&&g!==m.last){let t=o5(e,l)?-1:1,r=g;do r=(r+t+p.length)%p.length;while(!sk(p[r]));A(r)}}else if("space"===e.name){let e=p[g];e&&!sh.isSeparator(e)&&(e.disabled?y(a.i18n.disabledError):(y(void 0),f(p.map((e,t)=>t===g?sj(e):e))))}else if(e.name===s.all){var r;let e=p.some(e=>sI(e)&&!e.checked);f(p.map((r=e,function(e){return sI(e)?{...e,checked:r}:e})))}else if(e.name===s.invert)f(p.map(sj));else{let t;if(t=e,"1234567890".includes(t.name)){let t=Number(e.name)-1,r=-1,i=p.findIndex(e=>!sh.isSeparator(e)&&++r===t),u=p[i];u&&sI(u)&&(A(i),f(p.map((e,t)=>t===i?sj(e):e)))}}});let b=a.style.message(e.message,c),_=sf({items:p,active:g,renderItem({item:e,isActive:t}){if(sh.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 u=e.checked?a.icon.checked:a.icon.unchecked,n=e.checked?e.checkedName:e.name;return(t?a.style.highlight:e=>e)(`${i}${u} ${n}`)},pageSize:i,loop:u});if("done"===c){let e=p.filter(sR);return[h,b,a.style.answer(a.style.renderSelectedChoices(e,p))].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 D=a.style.keysHelpTip(C),F=[[h,b].filter(Boolean).join(" "),_," ",r?a.style.description(r):"",E?a.style.error(E):"",D].filter(Boolean).join("\n").trimEnd();return`${F}\u001b[?25l`}),sN={style:{maskedText:"[input is masked]"}},sP=o1((e,t)=>{let r,{validate:i=()=>!0}=e,u=su(sN,e.theme),[n,o]=sn("idle"),[s,a]=sn(),[l,c]=sn(""),d=ss({status:n,theme:u});sl(async(e,r)=>{if("idle"===n)if(st(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 h=u.style.message(e.message,n),p="";e.mask?p=("string"==typeof e.mask?e.mask:"*").repeat(l.length):"done"!==n&&(r=`${u.style.help(u.style.maskedText)}\u001b[?25l`),"done"===n&&(p=u.style.answer(p));let f="";return s&&(f=u.style.error(s)),[[d,h,e.mask?p:r].join(" "),f]});var s$=__webpack_require__("../../node_modules/.pnpm/chardet@2.1.1/node_modules/chardet/lib/index.js"),sU=__webpack_require__("../../node_modules/.pnpm/iconv-lite@0.7.2/node_modules/iconv-lite/lib/index.js");class sM extends Error{name="CreateFileError";originalError;constructor(e){super(`Failed to create temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class sq extends Error{name="LaunchEditorError";originalError;constructor(e){super(`Failed to launch editor.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class sV extends Error{name="ReadFileError";originalError;constructor(e){super(`Failed to read temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}class sH extends Error{name="RemoveFileError";originalError;constructor(e){super(`Failed to remove temporary file.${e instanceof Error?` ${e.message}`:""}`,{cause:e}),this.originalError=e}}function sz(e){return e?e.replace(/[^a-zA-Z0-9_.-]/g,"_"):""}class sG{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 sq(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 sq(e))}),r.once("exit",t=>{this.lastExitStatus=t??0,e()})}catch(e){t(new sq(e))}}).then(()=>(this.readTemporaryFile(),this.text)).finally(()=>{this.cleanup()});return e&&t.then(t=>e(void 0,t),t=>e(t instanceof Error?t:Error(String(t)),void 0)),t}cleanup(){if(this.tempDir)try{(0,O.rmSync)(this.tempDir,{force:!0,recursive:!0}),this.tempFile="",this.tempDir=""}catch(e){throw new sH(e)}}createTempFile(){try{let e=T.resolve(this.fileOptions.dir??eX.tmpdir());this.tempDir=(0,O.mkdtempSync)(T.join(e,"inquirer-editor-"));let t=(0,eY.randomUUID)(),r=sz(this.fileOptions.prefix),i=sz(this.fileOptions.postfix),u=`${r}${t}${i}`;this.tempFile=T.join(this.tempDir,u);let n={encoding:"utf8",flag:"wx"};Object.prototype.hasOwnProperty.call(this.fileOptions,"mode")&&(n.mode=this.fileOptions.mode),(0,O.writeFileSync)(this.tempFile,this.text,n)}catch(e){throw new sM(e)}}editorArgs(){return[...this.editor.args,this.tempFile]}readTemporaryFile(){try{let e=(0,O.readFileSync)(this.tempFile);if(0===e.length)this.text="";else{let t=(0,s$.detect)(e)??"utf8";sU.encodingExists(t)||(t="utf8"),this.text=sU.decode(e,t)}}catch(e){throw new sV(e)}}}let sW={validationFailureMode:"keep",style:{loadingMessage:()=>"Validating...",waitingMessage:e=>`Press ${e} to launch your preferred editor.`}},sJ=o1((e,t)=>{let{waitForUserInput:r=!0,file:{postfix:i=e.postfix??".txt",...u}={},validate:n=()=>!0}=e,o=su(sW,e.theme),[s,a]=sn("idle"),[l="",c]=sn(e.default),[d,h]=sn(),p=ss({status:s,theme:o});async function f(r){r.pause();try{var s,d,p;let f,m=await (s=l,d={postfix:i,...u},f="function"==typeof d?d:void 0,new sG(s,"function"==typeof d?p:d).runAsync(f));r.resume(),a("loading");let g=await n(m);!0===g?(h(void 0),a("done"),t(m)):("clear"===o.validationFailureMode?c(e.default):c(m),h(g||"You must provide a valid value"),a("idle"))}catch(e){r.resume(),h(String(e))}}so(e=>{r||f(e)},[]),sl((e,t)=>{"idle"===s&&st(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)),[[p,m,g].filter(Boolean).join(" "),A]}),sK={icon:{cursor:o8.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 sY(e){return!sh.isSeparator(e)&&!e.disabled}let sX=o1((e,t)=>{let r,i,{pageSize:u=7,validate:n=()=>!0}=e,o=su(sK,e.theme),[s,a]=sn("loading"),[l,c]=sn(""),[d,h]=sn([]),[p,f]=sn(),m=sa(!1),g=ss({status:s,theme:o}),A=sp(()=>{let e=d.findIndex(sY);return{first:e,last:d.findLastIndex(sY)}},[d]),[E=A.first,y]=sn();so(()=>{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(sh.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=>sY(t)&&t.value===e.default);t=-1===r?void 0:r,m.current=!0}y(t),f(void 0),h(i),a("idle")}}catch(e){!t.signal.aborted&&e instanceof Error&&f(e.message)}})(),()=>{t.abort()}},[l]);let b=d[E];sl(async(e,r)=>{if(st(e))if(b){a("loading");let e=await n(b.value);a("idle"),!0===e?(a("done"),t(b.value)):b.name===l?f(e||"You must provide a valid value"):(r.write(b.name),c(b.name))}else r.write(l);else if("tab"===e.name&&b)r.clearLine(0),r.write(b.name),c(b.name);else if("loading"!==s&&(o5(e)||se(e))){if(r.clearLine(0),o5(e)&&E!==A.first||se(e)&&E!==A.last){let t=o5(e)?-1:1,r=E;do r=(r+t+d.length)%d.length;while(!sY(d[r]));y(r)}}else c(r.line)});let _=o.style.message(e.message,s),C=o.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),D=sf({items:d,active:E,renderItem({item:e,isActive:t}){if(sh.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:u,loop:!1});if(p?r=o.style.error(p):0===d.length&&""!==l&&"idle"===s&&(r=o.style.error("No results found")),"done"===s&&b)return[g,_,o.style.answer(b.short)].filter(Boolean).join(" ").trimEnd();i=o.style.searchTerm(l);let F=b?.description,v=[g,_,i].filter(Boolean).join(" ").trimEnd();return[v,[r??D," ",F?o.style.description(F):"",C].filter(Boolean).join("\n").trimEnd()]});var sQ=__webpack_require__("../../node_modules/.pnpm/run-async@4.0.6/node_modules/run-async/index.js");function sZ(e){queueMicrotask(()=>{throw e})}function s1(e){try{e()}catch(e){sZ(e)}}function s2(){return{closed:!0,unsubscribe(){}}}function s0(e){return e instanceof Error?e:Error(String(e))}function s3(e){"function"==typeof e?e():e?.unsubscribe()}class s6{"@@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,u,n;let o,s=(i=e,u=t,n=r,"function"==typeof i?{next:i,...u?{error:u}:{},...n?{complete:n}:{}}:i??{}),a=!1,l=!1,c={get closed(){return a},unsubscribe(){!a&&(a=!0,l&&s3(o))}},d={next(e){a||s1(()=>s.next?.(e))},error(e){!a&&(a=!0,s.error?s1(()=>s.error?.(e)):sZ(e),l&&s3(o))},complete(){!a&&(a=!0,s1(()=>s.complete?.()),l&&s3(o))}};try{o=this.subscribeFn(d),l=!0,c.closed&&s3(o)}catch(e){d.error?.(e)}return c}[Symbol.asyncIterator](){return s8(this)[Symbol.asyncIterator]()}}let s4=new s6(e=>(e.complete?.(),s2()));function s8(e){return{[Symbol.asyncIterator](){let t,r,i=[],u=[],n=!1,o=!1,s=e=>{for(;u.length>0;)u.shift()?.resolve(e)},a=e=>{for(;u.length>0;)u.shift()?.reject(e)};try{r=e.subscribe({next(e){if(n||o)return;let t=u.shift();t?t.resolve({done:!1,value:e}):i.push({value:e})},error(e){n||o||(i.length=0,o=!0,t=s0(e),a(t),r?.unsubscribe())},complete(){n||o||(n=!0,s({done:!0,value:void 0}))}})}catch(e){i.length=0,o=!0,a(t=s0(e))}return{next(){let e=i.shift();return e?Promise.resolve({done:!1,value:e.value}):o?Promise.reject(t??Error("Observable source failed")):n?Promise.resolve({done:!0,value:void 0}):new Promise((e,t)=>{u.push({resolve:e,reject:t})})},return:()=>(n=!0,i.length=0,r?.unsubscribe(),s({done:!0,value:void 0}),Promise.resolve({done:!0,value:void 0}))}}}}let s9=(e,t="",r)=>{let i=e;t.split(".").forEach((e,t,u)=>{"__proto__"!==e&&"constructor"!==e&&(t===u.length-1?i[e]=r:e in i&&"object"==typeof i[e]||(i[e]={}),i=i[e])})},s7=(e,t="",r)=>{let i=r=>String.prototype.split.call(t,r).filter(Boolean).reduce((e,t)=>null==e?e:e[t],e),u=i(/[,[\]]+?/)||i(/[,.[\]]+?/);return void 0===u||u===e?r:u};async function s5(e,t,r){let i=e[t];return"function"==typeof i?sQ(i)(r):i}class ae 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 at extends Error{name="TTYError";isTtyError=!0}class ar{prompts;answers={};process=s4;abortController=new AbortController;opt;constructor(e,t={}){this.opt=t,this.prompts=e}async run(e,t){let r,i,u,n;this.abortController=new AbortController;let o=(i=new Set,u=!1,n=!1,{observable:new s6(e=>{if(n)return e.error?.(r),s2();if(u)return e.complete?.(),s2();let t={observer:e,subscription:{closed:!1,unsubscribe(){t.subscription.closed=!0,i.delete(t)}}};return i.add(t),t.subscription}),next(e){if(!u&&!n)for(let{observer:t,subscription:r}of i)r.closed||s1(()=>t.next?.(e))},error(e){if(!u&&!n){for(let{observer:t,subscription:u}of(n=!0,r=e,i))u.closed=!0,s1(()=>t.error?.(e));i.clear()}},complete(){if(!u&&!n){for(let{observer:e,subscription:t}of(u=!0,i))t.closed=!0,s1(()=>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);s9(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*s8(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 ae(r,this.prompts);let[i,u,n]=await Promise.all([s5(e,"message",this.answers),s5(e,"default",this.answers),s5(e,"choices",this.answers)]);Array.isArray(n)&&(t=n.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(u)?{checked:u.includes(t.value),...t}:t}));let o=Object.assign({},e,{message:i,default:u,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,u=await this.prepareQuestion(e),n=this.prompts[u.type];if(null==n)throw Error(`Prompt for type ${u.type} not found`);let o=(t=n).prototype&&"run"in t.prototype&&"function"==typeof t.prototype.run?(e,t)=>new Promise((i,u)=>{let{signal:o}=t;if(o.aborted)return void u(new ok({cause:o.reason}));let s=ol.createInterface(function(e){e.skipTTYChecks=void 0===e.skipTTYChecks||e.skipTTYChecks;let t=e.input||process.stdin;if(!e.skipTTYChecks&&!t.isTTY)throw new at("Prompts can not be meaningfully rendered in non-TTY environments");let r=new oc;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 n(e,s,this.answers),c=()=>{process.removeListener("exit",a),s.removeListener("SIGINT",a),s.setPrompt(""),s.output.unmute(),s.output.write("\x1b[?25h"),ol.cursorTo(s.output,0),s.output.end(),s.close(),r?.()},d=()=>{u(new ok({cause:o.reason})),c()};o.addEventListener("abort",d),r=()=>{o.removeEventListener("abort",d),r=void 0},l.run().then(i,u).finally(c)}):n,{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}=u,{signal:l}=this.abortController;return o(u,{...this.opt,signal:l}).then(e=>({name:u.name,answer:a(e,this.answers)})).finally(()=>{r?.(),i?.()})};close=()=>{this.abortController.abort()};shouldRun=async e=>{if(!0!==e.askAnswered&&void 0!==s7(this.answers,e.name))return!1;let{when:t}=e;return"function"==typeof t?!!await sQ(t)(this.answers):!1!==t}}let ai={input:sd,select:sE,number:sb,confirm:sD,rawlist:sx,expand:sT,checkbox:sL,password:sP,editor:sJ,search:sX};function au(e){function t(r,i){let u=new ar(t.prompts,e);return Object.assign(u.run(r,i),{ui:u})}return t.prompts={...ai},t.registerPrompt=function(e,r){return t.prompts[e]=r,this},t.restoreDefaultPrompts=function(){t.prompts={...ai}},t}let an=au(),ao=an;async function as(){let e=function(){let e=(0,T.resolve)(__dirname,"..","skills",eR);if((0,O.existsSync)((0,T.resolve)(e,"SKILL.md")))return e;let t=(0,T.resolve)(__dirname,"..");return(0,O.existsSync)((0,T.resolve)(t,"SKILL.md"))?t:e}(),t=(0,T.resolve)(e,"SKILL.md");if(!(0,O.existsSync)(e))throw new l(`未找到随包发布的 Skill 目录: ${e}`,{error:"SKILL_INSTALL_FAILED"});if(!(0,O.existsSync)(t))throw new l(`随包发布的 Skill 缺少入口文件: ${t}`,{error:"SKILL_INSTALL_FAILED"});let r=nz(`正在同步 ${eR} Skill ...`).start();try{var i;await (i=e,b({command:"npx",args:["--yes","skills","add",i,"--global","--all","--copy"],createSpawnError:e=>new l("未能调用 npx skills:可执行文件不可用",{error:"SKILL_INSTALLER_NOT_FOUND",cause:e}),createNonZeroExitError:e=>new l(`npx skills 安装失败,退出码 ${e??"unknown"}`,{error:"SKILL_INSTALL_FAILED",exitCode:"number"==typeof e&&0!==e?e:1})})),r.succeed(`${eR} Skill 已同步完成`)}catch(e){throw r.fail(`${eR} Skill 同步失败`),e}}async function aa(){try{await as()}catch(e){if(d(e)){eM({errorMessage:e.message,errorCode:un(e)}),process.stderr.write(`${e.message}
|
|
44
|
-
`),process.exitCode=e.exitCode;return}throw e}}let al=new Set(["latest","beta","alpha","next","stable"]);async function ac(e){let t=e?.trim()||"latest";if("latest"===t){let e=nz(`正在解析 ${ek} 最新版本 ...`).start();try{let t=await um();return e.succeed(`最新版本:${t}`),t}catch(t){throw e.fail("解析最新版本失败"),t}}if(!al.has(t)&&!_(t))throw new l(`不支持的目标版本: ${t}`,{error:"INVALID_TARGET_VERSION",message:"--target-version 仅支持 semver 版本号或 latest / beta / alpha / next / stable"});return t}async function ad(e){var t,r,i;let u=await ac(e.targetVersion),n=`${ek}@${u}`,o=function(e){let t=ul({input:e});if(void 0!==e){if(!t)throw new l(`不支持的包管理器: ${e}`,{error:"INVALID_PACKAGE_MANAGER",message:`--package-manager 只能取 ${uo.join(" / ")}`});return t}let r=ul({userAgent:process.env.npm_config_user_agent});if(!r)throw new l("当前环境无法自动识别全局安装所使用的包管理器",{error:"INVALID_PACKAGE_MANAGER",message:`请显式传入 --package-manager,支持 ${uo.join(" / ")}`});return r}(e.packageManager);if("0.
|
|
45
|
-
`),process.exitCode=e.exitCode;return}throw e}}async function ap(e){return(await ao([{type:"list",name:"action",message:`发现新版本 ${e},当前版本 0.
|
|
44
|
+
`),process.exitCode=e.exitCode;return}throw e}}let al=new Set(["latest","beta","alpha","next","stable"]);async function ac(e){let t=e?.trim()||"latest";if("latest"===t){let e=nz(`正在解析 ${ek} 最新版本 ...`).start();try{let t=await um();return e.succeed(`最新版本:${t}`),t}catch(t){throw e.fail("解析最新版本失败"),t}}if(!al.has(t)&&!_(t))throw new l(`不支持的目标版本: ${t}`,{error:"INVALID_TARGET_VERSION",message:"--target-version 仅支持 semver 版本号或 latest / beta / alpha / next / stable"});return t}async function ad(e){var t,r,i;let u=await ac(e.targetVersion),n=`${ek}@${u}`,o=function(e){let t=ul({input:e});if(void 0!==e){if(!t)throw new l(`不支持的包管理器: ${e}`,{error:"INVALID_PACKAGE_MANAGER",message:`--package-manager 只能取 ${uo.join(" / ")}`});return t}let r=ul({userAgent:process.env.npm_config_user_agent});if(!r)throw new l("当前环境无法自动识别全局安装所使用的包管理器",{error:"INVALID_PACKAGE_MANAGER",message:`请显式传入 --package-manager,支持 ${uo.join(" / ")}`});return r}(e.packageManager);if("0.4.0"===u)return(nz("dymg 已是目标版本(0.4.0),跳过 CLI 安装").info(),e.skipSkills)?void nz("已跳过 Skill 同步。如需同步,请执行 dymg skills install").info():void await as();let s=nz(`正在使用 ${o} 安装 ${n} ...`).start();try{let e;await (t=o,r=n,e=function(e,t){switch(e){case"npm":return{command:"npm",args:["install","-g",t],windowsExtension:".cmd"};case"pnpm":return{command:"pnpm",args:["add","-g",t],windowsExtension:".cmd"};case"yarn":return{command:"yarn",args:["global","add",t],windowsExtension:".cmd"};case"bun":return{command:"bun",args:["add","-g",t],windowsExtension:!1};default:throw TypeError(`Unsupported package manager: ${e}`)}}(t,r),b({command:e.command,args:e.args,windowsExtension:e.windowsExtension,createSpawnError:e=>new l(`未能调用 ${t}:可执行文件不可用`,{error:"PACKAGE_MANAGER_NOT_FOUND",cause:e}),createNonZeroExitError:e=>new l(`${t} 安装失败,退出码 ${e??"unknown"}`,{error:"PACKAGE_MANAGER_INSTALL_FAILED",exitCode:"number"==typeof e&&0!==e?e:1})})),s.succeed(`dymg 已更新完成,当前版本:${u}`)}catch(e){throw s.fail(`${o} 安装失败`),e}if(e.skipSkills)return void nz("已跳过 Skill 同步。如需同步,请执行 dymg skills install").info();let a=nz("正在启动更新后的 CLI 同步 Skill ...").start();try{await (i=n,b({command:"npx",args:["--yes",i,"skills","install"],windowsExtension:".cmd",createSpawnError:e=>new l("CLI 已更新,但未能启动新进程同步 Skill",{error:"SKILL_INSTALL_FAILED",cause:e}),createNonZeroExitError:e=>new l(`CLI 已更新,但 Skill 同步失败,退出码 ${e??"unknown"}`,{error:"SKILL_INSTALL_FAILED",exitCode:"number"==typeof e&&0!==e?e:1})})),a.succeed("Skill 已同步完成")}catch(e){throw a.fail("Skill 同步失败"),e}}async function ah(e){try{await ad(e)}catch(e){if(d(e)){eM({errorMessage:e.message,errorCode:un(e)}),process.stderr.write(`${e.message}
|
|
45
|
+
`),process.exitCode=e.exitCode;return}throw e}}async function ap(e){return(await ao([{type:"list",name:"action",message:`发现新版本 ${e},当前版本 0.4.0。是否现在更新并同步 Skill?`,choices:[{name:"现在更新",value:"update"},{name:"暂不更新",value:"skip"}],default:"update"}])).action}async function af(e,t){let r=nz(`正在检查 ${ek} 更新,当前版本:0.4.0`).start();try{let e=await ug();if(r.succeed("更新检查完成"),!e.hasUpdate){await uA(e),nz(`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)||!ul({userAgent:process.env.npm_config_user_agent})){var i;i=e.latestVersion,process.stdout.write(`${uh(i).join("\n")}
|
|
46
46
|
`),await uA(e,{notified:!0});return}let u=await ap(e.latestVersion);if(await uA(e,{notified:!0}),"skip"===u)return void nz("已跳过更新,可执行 dymg update 完成 CLI 和 Skill 同步").info();await ad({targetVersion:e.latestVersion})}catch(t){if(r.isSpinning&&r.fail("检查更新失败"),d(t)){eM({errorMessage:t.message,errorCode:un(t)}),process.stderr.write(`${t.message}
|
|
47
47
|
`),process.exitCode=t.exitCode;return}let e=t instanceof Error?t.message:String(t);eM({errorMessage:e,errorCode:un(t)}),process.stderr.write(`检查更新失败:${e}
|
|
48
|
-
`),process.exitCode=1}}var am=((en={})[en.ActivateDate=1]="ActivateDate",en[en.FirstChannel=2]="FirstChannel",en),ag=((eo={})[eo.Ad=1]="Ad",eo[eo.Star=2]="Star",eo[eo.Pop=3]="Pop",eo[eo.Nature=4]="Nature",eo),aA=((es={})[es.RealTime=1]="RealTime",es[es.Offline=2]="Offline",es),aE=((ea={})[ea.ActivateNewUserNum=1]="ActivateNewUserNum",ea[ea.AdActivateConsumeAverage=2]="AdActivateConsumeAverage",ea[ea.AdConsumeFirstDay=3]="AdConsumeFirstDay",ea[ea.PopConsumeCumulative=4]="PopConsumeCumulative",ea[ea.PopConsumeCumulativeAverage=5]="PopConsumeCumulativeAverage",ea[ea.AdIncomeUserNumDaily=6]="AdIncomeUserNumDaily",ea[ea.ECPMDaily=7]="ECPMDaily",ea[ea.AdShowNumDailyAverage=8]="AdShowNumDailyAverage",ea[ea.AdArpuDaily=9]="AdArpuDaily",ea[ea.AdIncomeCumulative=10]="AdIncomeCumulative",ea[ea.AdLTV=11]="AdLTV",ea[ea.PayUserNumDaily=12]="PayUserNumDaily",ea[ea.PayUserNumCumulative=13]="PayUserNumCumulative",ea[ea.PayNumDailyAverage=14]="PayNumDailyAverage",ea[ea.PayArpuDaily=15]="PayArpuDaily",ea[ea.PayArppuDaily=16]="PayArppuDaily",ea[ea.PayCumulative=17]="PayCumulative",ea[ea.PayLTV=18]="PayLTV",ea[ea.TotalArpuDaily=19]="TotalArpuDaily",ea[ea.TotalIncomeCumulative=20]="TotalIncomeCumulative",ea[ea.TotalLTV=21]="TotalLTV",ea[ea.TotalROI=22]="TotalROI",ea[ea.RetainUserNumDaily=23]="RetainUserNumDaily",ea[ea.RetainUserRateDaily=24]="RetainUserRateDaily",ea[ea.OnlineTimeDailyAverage=25]="OnlineTimeDailyAverage",ea[ea.LaunchNumDailyAverage=26]="LaunchNumDailyAverage",ea[ea.AdPenetrationRateDaily=27]="AdPenetrationRateDaily",ea[ea.PayPenetrationRateDaily=28]="PayPenetrationRateDaily",ea[ea.PayPenetrationRateCumulative=29]="PayPenetrationRateCumulative",ea[ea.TimeToFirstPayAverage=30]="TimeToFirstPayAverage",ea),ay=((el={})[el.Ad=1]="Ad",el[el.StarLive=2]="StarLive",el[el.StarVideo=3]="StarVideo",el[el.PopLive=4]="PopLive",el[el.PopVideo=5]="PopVideo",el[el.NatureVideo=6]="NatureVideo",el[el.NatureSearch=7]="NatureSearch",el[el.NatureHomePageSidebar=8]="NatureHomePageSidebar",el[el.NaturePersonSidebar=9]="NaturePersonSidebar",el[el.NaturePersonOther=10]="NaturePersonOther",el[el.NatureIM=11]="NatureIM",el[el.NatureGameCenter=12]="NatureGameCenter",el[el.NatureCoinGameCenter=13]="NatureCoinGameCenter",el[el.NatureFeedPlay=14]="NatureFeedPlay",el[el.NatureFeedCard=15]="NatureFeedCard",el[el.NatureDesktop=16]="NatureDesktop",el[el.NatureInMp=17]="NatureInMp",el[el.NatureScan=18]="NatureScan",el[el.NatureGameCircle=19]="NatureGameCircle",el[el.NatureLive=20]="NatureLive",el[el.NatureOther=21]="NatureOther",el);let ab=["1","2"],a_=["1","2","3","4","5","6","7","8","9","10","11","12","13","14","30","45","60","75","90","120","150","180"],aC=new Set([aE.ActivateNewUserNum,aE.AdActivateConsumeAverage,aE.AdConsumeFirstDay]),
|
|
48
|
+
`),process.exitCode=1}}var am=((en={})[en.ActivateDate=1]="ActivateDate",en[en.FirstChannel=2]="FirstChannel",en),ag=((eo={})[eo.Ad=1]="Ad",eo[eo.Star=2]="Star",eo[eo.Pop=3]="Pop",eo[eo.Nature=4]="Nature",eo),aA=((es={})[es.RealTime=1]="RealTime",es[es.Offline=2]="Offline",es),aE=((ea={})[ea.ActivateNewUserNum=1]="ActivateNewUserNum",ea[ea.AdActivateConsumeAverage=2]="AdActivateConsumeAverage",ea[ea.AdConsumeFirstDay=3]="AdConsumeFirstDay",ea[ea.PopConsumeCumulative=4]="PopConsumeCumulative",ea[ea.PopConsumeCumulativeAverage=5]="PopConsumeCumulativeAverage",ea[ea.AdIncomeUserNumDaily=6]="AdIncomeUserNumDaily",ea[ea.ECPMDaily=7]="ECPMDaily",ea[ea.AdShowNumDailyAverage=8]="AdShowNumDailyAverage",ea[ea.AdArpuDaily=9]="AdArpuDaily",ea[ea.AdIncomeCumulative=10]="AdIncomeCumulative",ea[ea.AdLTV=11]="AdLTV",ea[ea.PayUserNumDaily=12]="PayUserNumDaily",ea[ea.PayUserNumCumulative=13]="PayUserNumCumulative",ea[ea.PayNumDailyAverage=14]="PayNumDailyAverage",ea[ea.PayArpuDaily=15]="PayArpuDaily",ea[ea.PayArppuDaily=16]="PayArppuDaily",ea[ea.PayCumulative=17]="PayCumulative",ea[ea.PayLTV=18]="PayLTV",ea[ea.TotalArpuDaily=19]="TotalArpuDaily",ea[ea.TotalIncomeCumulative=20]="TotalIncomeCumulative",ea[ea.TotalLTV=21]="TotalLTV",ea[ea.TotalROI=22]="TotalROI",ea[ea.RetainUserNumDaily=23]="RetainUserNumDaily",ea[ea.RetainUserRateDaily=24]="RetainUserRateDaily",ea[ea.OnlineTimeDailyAverage=25]="OnlineTimeDailyAverage",ea[ea.LaunchNumDailyAverage=26]="LaunchNumDailyAverage",ea[ea.AdPenetrationRateDaily=27]="AdPenetrationRateDaily",ea[ea.PayPenetrationRateDaily=28]="PayPenetrationRateDaily",ea[ea.PayPenetrationRateCumulative=29]="PayPenetrationRateCumulative",ea[ea.TimeToFirstPayAverage=30]="TimeToFirstPayAverage",ea),ay=((el={})[el.Ad=1]="Ad",el[el.StarLive=2]="StarLive",el[el.StarVideo=3]="StarVideo",el[el.PopLive=4]="PopLive",el[el.PopVideo=5]="PopVideo",el[el.NatureVideo=6]="NatureVideo",el[el.NatureSearch=7]="NatureSearch",el[el.NatureHomePageSidebar=8]="NatureHomePageSidebar",el[el.NaturePersonSidebar=9]="NaturePersonSidebar",el[el.NaturePersonOther=10]="NaturePersonOther",el[el.NatureIM=11]="NatureIM",el[el.NatureGameCenter=12]="NatureGameCenter",el[el.NatureCoinGameCenter=13]="NatureCoinGameCenter",el[el.NatureFeedPlay=14]="NatureFeedPlay",el[el.NatureFeedCard=15]="NatureFeedCard",el[el.NatureDesktop=16]="NatureDesktop",el[el.NatureInMp=17]="NatureInMp",el[el.NatureScan=18]="NatureScan",el[el.NatureGameCircle=19]="NatureGameCircle",el[el.NatureLive=20]="NatureLive",el[el.NatureOther=21]="NatureOther",el);let ab=["1","2"],a_=["1","2","3","4","5","6","7","8","9","10","11","12","13","14","30","45","60","75","90","120","150","180"],aC=[...Array.from({length:90},(e,t)=>String(t+1)),"120","150","180"],aD=new Set([aE.ActivateNewUserNum,aE.AdActivateConsumeAverage,aE.AdConsumeFirstDay]),aF=["metric","metricName","lifeTime","value"],av={[ag.Ad]:[ay.Ad],[ag.Star]:[ay.StarLive,ay.StarVideo],[ag.Pop]:[ay.PopLive,ay.PopVideo],[ag.Nature]:[ay.NatureVideo,ay.NatureSearch,ay.NatureHomePageSidebar,ay.NaturePersonSidebar,ay.NaturePersonOther,ay.NatureIM,ay.NatureGameCenter,ay.NatureCoinGameCenter,ay.NatureFeedPlay,ay.NatureFeedCard,ay.NatureDesktop,ay.NatureInMp,ay.NatureScan,ay.NatureGameCircle,ay.NatureLive,ay.NatureOther]},aw=`
|
|
49
49
|
参数说明:
|
|
50
50
|
- --dimension / --metric / --first-channel / --second-channel 均支持逗号分隔多值
|
|
51
51
|
- --life-time 可重复传入,格式为 <指标枚举>:<生命周期天数列表>,例如 --life-time 11:7,14,30
|
|
52
52
|
- 指标 1/2/3 可以不传 --life-time;如果传,只能传 1
|
|
53
53
|
- 指标 4-30 必须通过 --life-time 指定生命周期天数
|
|
54
54
|
- 多个指标需要不同生命周期时,重复传入多次 --life-time,例如 --life-time 11:7,14,30 --life-time 21:7,14,30
|
|
55
|
-
- --freshness-type=1 时,--life-time 只支持 1,2
|
|
55
|
+
- --freshness-type=1 时,--life-time 只支持 1,2
|
|
56
|
+
- --freshness-type=2 时,总 ROI(指标 22)支持 1-90,120,150,180;其他指标支持 1-14,30,45,60,75,90,120,150,180
|
|
56
57
|
- 激活日期格式为 YYYY-MM-DD;实时数据最近 2 天,离线数据最近 180 天,结束日期不能晚于今天
|
|
57
58
|
- --second-channel 只能传已选一级渠道下的二级渠道:广告激活(1)->广告(1),星图激活(2)->星图-直播/视频(2,3),发行人激活(3)->发行人-直播/视频(4,5),自然激活(4)->自然各场景(6~21)
|
|
58
59
|
|
|
@@ -123,7 +124,7 @@ ${t}`,u2=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),u0=Objec
|
|
|
123
124
|
|
|
124
125
|
示例:
|
|
125
126
|
$ 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
|
|
126
|
-
$ 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
|
|
127
|
+
$ 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 aB(e,t=[]){return[...t,e]}function ax(e){return e===aA.RealTime?"1,2":"1,3,7"}var aS=((ec={})[ec.HotGame=1]="HotGame",ec[ec.BestSeller=2]="BestSeller",ec[ec.NewGame=3]="NewGame",ec[ec.Pop=4]="Pop",ec),aT=((ed={})[ed.IAA=1]="IAA",ed[ed.IAP=2]="IAP",ed[ed.IAAP=3]="IAAP",ed);let aO=["elementId","elementName","elementType","hotValue","dataStatus","hotspotId","videoId","elementTags","description","heatTrend"],aI=["title","hotValue","topics","hotInsights","jumpUrl","contentId","coverUrl","playUrl","contentTags","gamificationCategories","gamificationMechanics","genderDistribution","ageDistribution","commentSummary","topComments","dataStatus"],ak=["topicId","topicName","parentTopicId","parentTopicName","dataStatus","topicOverview","marketOpportunitySummary","gamificationCategories","gamificationMechanics","genderDistribution","ageDistribution","audiencePreferences","contentPreferences","interactionPreferences","relatedGames","recentHotspots","topVideos","trend7D","trend30D","trend90D"],aR=["all","image","topic","interaction"],aj=[{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 aL(e,t=String){return e?.map(t).join("|")}var aN=((eh={})[eh.All=1]="All",eh[eh.Douyin=2]="Douyin",eh[eh.DouyinLite=3]="DouyinLite",eh[eh.Toutiao=4]="Toutiao",eh[eh.ToutiaoLite=5]="ToutiaoLite",eh[eh.Fanqie=6]="Fanqie",eh[eh.FanqieChangTing=7]="FanqieChangTing",eh[eh.Hotsoon=8]="Hotsoon",eh[eh.Ppx=9]="Ppx",eh),aP=((ep={})[ep.Debug=1]="Debug",ep[ep.Info=2]="Info",ep[ep.Warn=3]="Warn",ep[ep.Error=4]="Error",ep[ep.Fatal=5]="Fatal",ep),a$=((ef={})[ef.All=1]="All",ef[ef.Android=2]="Android",ef[ef.IOS=3]="IOS",ef[ef.OpenHarmony=4]="OpenHarmony",ef[ef.Windows=5]="Windows",ef),aU=((em={})[em.All=1]="All",em[em.High=2]="High",em[em.Mid=3]="Mid",em[em.Low=4]="Low",em),aM=((eg={})[eg.All=1]="All",eg[eg.Android=2]="Android",eg[eg.IOS=3]="IOS",eg[eg.OpenHarmony=4]="OpenHarmony",eg[eg.Windows=5]="Windows",eg),aq=((eA={})[eA.All=1]="All",eA[eA.Android=2]="Android",eA[eA.IOS=3]="IOS",eA[eA.OpenHarmony=4]="OpenHarmony",eA[eA.Windows=5]="Windows",eA),aV=((eE={})[eE.LaunchCostMs=1001]="LaunchCostMs",eE[eE.LaunchRetentionRate=1002]="LaunchRetentionRate",eE[eE.WasmCompileCostMs=1003]="WasmCompileCostMs",eE[eE.CallMainCostMs=1004]="CallMainCostMs",eE[eE.LaunchFPCostMs=1005]="LaunchFPCostMs",eE[eE.LaunchTTICostMs=1006]="LaunchTTICostMs",eE[eE.ResourcePrepareCostMs=1007]="ResourcePrepareCostMs",eE[eE.CodeInjectCostMs=1008]="CodeInjectCostMs",eE[eE.WasmSplitBeforeFPRate=1011]="WasmSplitBeforeFPRate",eE[eE.WasmSplitBeforeFPCostMs=1012]="WasmSplitBeforeFPCostMs",eE[eE.WasmSplitBeforeTTIRate=1013]="WasmSplitBeforeTTIRate",eE[eE.WasmSplitBeforeTTICostMs=1014]="WasmSplitBeforeTTICostMs",eE[eE.FPS=2001]="FPS",eE[eE.StutterRate=2002]="StutterRate",eE[eE.RenderDrawCall=2003]="RenderDrawCall",eE[eE.RenderTriangle=2004]="RenderTriangle",eE[eE.RenderVertex=2005]="RenderVertex",eE[eE.AvgMemoryMB=2011]="AvgMemoryMB",eE[eE.MemoryUsageRate=2012]="MemoryUsageRate",eE[eE.MemoryPeakMB=2013]="MemoryPeakMB",eE[eE.MemoryAbnormalExitRate=2014]="MemoryAbnormalExitRate",eE[eE.CPUUsageRate=2021]="CPUUsageRate",eE[eE.GPUUsageRate=2022]="GPUUsageRate",eE[eE.RequestCostMs=3001]="RequestCostMs",eE[eE.RequestErrorRate=3002]="RequestErrorRate",eE[eE.DownloadFileCostMs=3003]="DownloadFileCostMs",eE[eE.DownloadFileErrorRate=3004]="DownloadFileErrorRate",eE),aH=((ey={})[ey.All=1]="All",ey[ey.Required=2]="Required",ey[ey.NotRequired=3]="NotRequired",ey),az=((eb={})[eb.Trend=1]="Trend",eb[eb.SceneConversion=2]="SceneConversion",eb[eb.LaunchDurationDistribution=3]="LaunchDurationDistribution",eb[eb.LaunchLossDistribution=4]="LaunchLossDistribution",eb[eb.WasmSplit=5]="WasmSplit",eb);let aG={[aN.Douyin]:"1128",[aN.DouyinLite]:"2329",[aN.Toutiao]:"13",[aN.ToutiaoLite]:"35",[aN.Fanqie]:"1967",[aN.FanqieChangTing]:"3040",[aN.Hotsoon]:"8663"},aW=Object.keys(aG),aJ=[aq.Android,aq.IOS,aq.OpenHarmony].map(String),aK=["group","genreName","engine","degradedIndicatorCount","section","indicatorName","metric","os","actualValue","standardValue","delta","unit","suggestion"],aY=["metric","metricName","name","sceneId","aggregation","direction","unit","date","value","sampleCount"],aX=["appId","host","os","appVersion","gameVersion","jssdkVersion","versionType","openId","traceId","logLevel","timestamp","msg"];function aQ(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 aZ(e){return(e??[]).flatMap(e=>(e.points??[]).map(t=>({metric:e.metric,metricName:t1(aV,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 a1(e){tG({startDate:e.startDate,endDate:e.endDate,maxLookbackDays:nQ,label:"性能数据"}),tM(e.host,"--host",aW),tM(e.os,"--os",aJ),tM(e.deviceLevel,"--device-level",tZ(aU)),tq(e.metrics,"--metrics",tZ(aV))}function a2(e){return{startDate:e.startDate,endDate:e.endDate,hostAid:aG[nW(e.host,aN)]??"",os:nW(e.os,aq),mpVersion:e.mpVersion,deviceLevel:nW(e.deviceLevel,aU)}}let a0=new Set(["check-update","skills","update"]);async function a3(e){await uu(e).catch(()=>void 0)}function a6(){process.exit(130)}async function a4(e){var t,r;let i,u,n,o,s;iP=new eO({middlewares:[eH,...eV,ez,function(e){let{getCaller:t,headerName:r="X-Tt-Cli-Caller"}=e;return async(e,i)=>{let u=t();"string"==typeof u&&u.trim()&&(e.request.headers??={},e.request.headers[r]=u.trim()),await i()}}({getCaller:()=>eq()?.caller}),function(e={}){let{getToken:t,missingTokenErrorFactory:r,headerName:i="Authorization",headerValueBuilder:u=e=>`Bearer ${e}`}=e;return async(e,n)=>{if(!t)return void await n();let o=await t();if(!o){if(r)throw r();await n();return}e.request.headers??={},e.request.headers[i]=u(o),await n()}}({getToken:iO,missingTokenErrorFactory:()=>new l("当前命令需要先登录",{error:"AUTH_LOGIN_REQUIRED",message:`当前命令需要先登录,请先执行 ${eL}`})})]}),i$=new eO({middlewares:[eH,...eV]});let a=e.slice(2),c=Date.now(),d=(((t=i=new $).addOption(new j("--caller <agent>","调用方 Agent").choices(iQ).default("unknown")),t).name("dymg").description("抖音小游戏 CLI").version("0.4.0").configureHelp({showGlobalOptions:!0}).showHelpAfterError("(可使用 --help 查看命令说明)").showSuggestionAfterError(!0).addHelpText("after",`
|
|
127
128
|
结果输出约定:
|
|
128
129
|
- 业务数据默认不直接打印到终端
|
|
129
130
|
- 每次执行都会在 command-timestamp 子目录生成 data.csv / raw_response.json / summary.json
|
|
@@ -145,5 +146,5 @@ ${t}`,u2=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),u0=Objec
|
|
|
145
146
|
用法:
|
|
146
147
|
- ${eL}
|
|
147
148
|
- ${eN}
|
|
148
|
-
- ${eP}`).action(oi),u.command("status").description("查看当前登录状态").action(oo),u.command("logout").description("退出当前登录").action(os),u.command("check-dir-writable").description("用于 Agent 测试执行环境中的当前登录态目录是否可写,并输出结构化结果").addHelpText("after","\n示例:\n $ dymg auth check-dir-writable").action(oa),i4(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=i6(t,e);await nG("game:game-list",r,async()=>{var e;let t,i,u;tH(r.pageIndex,"--page-index",1,1e4),tH(r.pageSize,"--page-size",1,100);let n={pageIndex:tK(r.pageIndex,1),pageSize:tK(r.pageSize,20)},o=await (e=n,t=ub.genBaseURL("/platform_openapi/microgame/v1/game/query_game_list"),i={pageIndex:e.pageIndex,pageSize:e.pageSize},u={X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"GET",params:i,headers:u},void 0)),s=ev(o),a=(s?.list??[]).map(e=>({appId:e.appId,appName:e.appName}));return{rawResponse:o,rows:a,csvHeader:["appId","appName"],resultMeta:rG({returnedCount:a.length,total:s?.total,page:n.pageIndex,pageSize:n.pageSize})}})}),n=r.command("insight").description("资讯与榜单"),i4(n.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=i6(t,e);await nG("insight:ranking-list",r,async()=>{var e;let t,i,u;tM(r.rankType,"--rank-type",tZ(ax)),tq(r.gameBusinessList,"--game-business-list",tZ(aS)),tq(r.gameTypeList,"--game-type-list",aR),tz(r.page,"--page"),tH(r.pageSize,"--page-size",1,200);let n=tK(r.page,1),o=tK(r.pageSize,20),s=n*o;if(s>200)throw new l("榜单仅支持查询前 200 名",{error:"OUT_OF_RANK_LIMIT",message:`榜单仅支持前 200 名,当前页末位排名 ${s} 已超出范围`});let a=await (e={gameBusinessList:tJ(r.gameBusinessList),gameTypeList:tW(r.gameTypeList),onlyMyGame:r.onlyMyGame,rankType:tK(r.rankType,0),page:String(n),pageSize:String(o),meta:await i8("insight:ranking-list")},t=ub.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},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),c=ev(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:rG({returnedCount:d.length,total:c?.page?.total,page:c?.page?.page,pageSize:c?.page?.pageSize,hasMore:c?.page?.hasMore,nextCursor:c?.page?.nextSearchAfter})}})}),i4(n.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=i6(t,e);await nG("insight:hotspot-list",r,async()=>{var e;let t,i,u,n;tq(r.gameTypeIds,"--game-type-ids",aR);let o=(e=r,!!(e.keyword?.trim()||tW(e.gameTypeIds)?.length||tW(e.topicIds)?.length));tH(r.topN,"--top-n",1,o?50:100);let s=r.topN??(o?String(50):void 0),a=await (t={gameTypeIds:tW(r.gameTypeIds),keyword:r.keyword?.trim()||void 0,meta:await i8("insight:hotspot-list"),topN:s,topicIds:tW(r.topicIds)},i=ub.genBaseURL("/platform_openapi/microgame/v1/insight/query_douyin_hotspots"),u={gameTypeIds:t.gameTypeIds,keyword:t.keyword,meta:t.meta,topN:t.topN,topicIds:t.topicIds},n={X_Tt_Appid:t.X_Tt_Appid,X_Tt_Userid:t.X_Tt_Userid},ub.request({url:i,method:"POST",data:u,headers:n},void 0)),l=ev(a);return{rawResponse:a,rows:(l?.items??[]).map(e=>({title:e.title,hotValue:e.hotValue,topics:aj(e.topics),hotInsights:e.hotInsights,jumpUrl:e.jumpUrl,contentId:e.contentId,coverUrl:e.coverUrl,playUrl:e.playUrl,contentTags:aj(e.contentTags),gamificationCategories:aj(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:aj(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:aj(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:aj(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),commentSummary:e.commentSummary,topComments:aj(e.topComments,e=>`${e.content??""}:${e.likeCount??""}`),dataStatus:e.dataStatus})),csvHeader:aO}})}),i4(n.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=i6(t,e);await nG("insight:element-list",r,async()=>{let e,t,i;tz(r.hotspotId,"--hotspot-id"),tM(r.elementType,"--element-type",ak),tz(r.page,"--page"),tH(r.pageSize,"--page-size",1,50);let u=tK(r.page,1),n=tK(r.pageSize,20),o=await (e={elementType:r.elementType,hotspotId:r.hotspotId,keyword:r.keyword?.trim()||void 0,page:u,pageSize:n,videoId:r.videoId},t=ub.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},ub.request({url:t,method:"POST",data:i},void 0)),s=ev(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:aj(e.elementTags),description:e.description,heatTrend:aj(e.heatTrend,e=>`${tQ(e.timestamp,{format:"date"})}:${e.hotScore??""}`)}));return{rawResponse:o,rows:a,csvHeader:aT,resultMeta:rG({returnedCount:a.length,total:s?.total,page:s?.page??u,pageSize:s?.pageSize??n,hasMore:s?.hasMore})}})}),i4(n.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=i6(t,e);await nG("insight:theme-list",r,async()=>{let e,t,i;tz(r.page,"--page"),tH(r.pageSize,"--page-size",1,50);let u=tK(r.page,1),n=tK(r.pageSize,20),o=await (e={includeTopVideos:r.includeTopVideos,page:u,pageSize:n,parentTopicId:r.parentTopicId,topicIdList:tW(r.topicIdList)},t=ub.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},ub.request({url:t,method:"POST",data:i},void 0)),s=ev(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:aj(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:aj(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:aj(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:aj(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),audiencePreferences:aj(e.userFeatures?.audiencePreferences,e=>`${e.title??""}:${e.insight??""}`),contentPreferences:aj(e.userFeatures?.contentPreferences,e=>`${e.title??""}:${e.insight??""}`),interactionPreferences:aj(e.userFeatures?.interactionPreferences,e=>`${e.title??""}:${e.insight??""}`),relatedGames:function(e){if(e?.length)return F(e.map(e=>({gameId:e.gameId,gameName:e.gameName,iconUrl:e.iconUrl,jumpUrl:e.jumpUrl,heatValue:e.heatValue})))}(e.relatedGames),recentHotspots:aj(e.recentHotspots,e=>`${e.title??""}:${e.heatValue??""}`),topVideos:aj(e.topVideos,e=>`${e.video?.title??""}:${e.likeCount??""}`),trend7D:aj(e.trend7D,e=>`${tQ(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend30D:aj(e.trend30D,e=>`${tQ(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend90D:aj(e.trend90D,e=>`${tQ(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`)}));return{rawResponse:o,rows:a,csvHeader:aI,resultMeta:rG({returnedCount:a.length,total:s?.total,page:u,pageSize:n,hasMore:s?.hasMore})}})}),o=r.command("analytics").description("用户数据"),i4(i9(o.command("behavior-query").description("查询用户的活跃用户、新增用户、累计用户、启动次数、游戏时长等行为指标,支持 App、操作系统等筛选"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:behavior-query",r,async()=>{var e;let t,i,u;n9(r),n7(r);let n=await (e={X_Tt_Appid:r.appId,filter:n1(r),meta:await i8("analytics:behavior-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_user_behavior"),i={filter:e.filter,meta:e.meta},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n),s=(o?.items??[]).map(e=>({...e,recordType:"data"}));return{rawResponse:n,rows:[...s,...o?.summary?[{...o.summary,recordType:"summary"}]:[]],csvHeader:n2}})}),i4(i9(o.command("realtime-query").description("查询游戏当天的实时访问人数和访问次数"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:realtime-query",r,async()=>{var e;let t,i,u;tG({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:nK,label:"实时数据"}),n7(r);let n=await (e={X_Tt_Appid:r.appId,filter:n1(r),meta:await i8("analytics:realtime-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_realtime_user"),i={filter:e.filter,meta:e.meta},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,rows:(o?.items??[]).map(e=>({hour:e.hour,activeUser:e.activeUser,openTime:e.openTime})),csvHeader:n0}})}),i4(i9(o.command("retention-query").description("查询用户的次日、3 日、14 日、30 日留存率,支持筛选日期、App、操作系统、用户类型等").option("--retention-scene <n>","留存场景:1 全量 / 2 侧边栏"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:retention-query",r,async()=>{var e;let t,i,u;n9(r),n7(r),tM(r.retentionScene,"--retention-scene",tZ(uv));let n=await (e={X_Tt_Appid:r.appId,filter:n1(r),retentionScene:void 0===r.retentionScene?void 0:tK(r.retentionScene,0),meta:await i8("analytics:retention-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_user_retention"),i={filter:e.filter,meta:e.meta,retentionScene:e.retentionScene},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,rows:(o?.items??[]).map(e=>({...e})),csvHeader:n3}})}),i4(i9(o.command("source-query").description("查询不同来源渠道下的活跃用户、新增用户数、启动次数、次均游戏时长等").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:source-query",r,async()=>{var e;let t,i,u;n9(r),n7(r),tH(r.topN,"--top-n",1,100);let n=await (e={X_Tt_Appid:r.appId,filter:n1(r),topN:r.topN,meta:await i8("analytics:source-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_user_source"),i={filter:e.filter,meta:e.meta,topN:e.topN},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,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:n6}})}),i4(i9(o.command("profile-query").description("查询用户的性别、年龄、地域分布,区分不同 App、活跃/新增用户类型"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:profile-query",r,async()=>{var e;let t,i,u;n9(r),n7(r);let n=await (e={X_Tt_Appid:r.appId,filter:n1(r),meta:await i8("analytics:profile-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_user_portrait"),i={filter:e.filter,meta:e.meta},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,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:n4}})}),i4(i9(o.command("device-query").description("查询用户的机型、品牌、客户端版本、基础库版本分布等").requiredOption("--dimension <n>","维度:1 型号 / 2 品牌 / 3 宿主版本 / 4 基础库版本").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:device-query",r,async()=>{var e;let t,i,u;n9(r),n7(r),tM(r.dimension,"--dimension",tZ(uw)),tH(r.topN,"--top-n",1,100);let n=tK(r.dimension,0),o=await (e={X_Tt_Appid:r.appId,dimension:n,filter:n1(r),topN:r.topN,meta:await i8("analytics:device-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_user_terminal"),i={dimension:e.dimension,filter:e.filter,meta:e.meta,topN:e.topN},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),s=ev(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:n8}})}),i4(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",aw,[]).requiredOption("--first-channel <list>","一级渠道枚举,逗号分隔").requiredOption("--freshness-type <n>","数据时效:1 实时 / 2 离线").option("--second-channel <list>","二级渠道枚举,逗号分隔").option("--download","是否返回下载链接",!1).addHelpText("after",av)).action(async(e,t)=>{let r=i6(t,e);await nG("growth:metric-query",r,async()=>{let e,t,i;tq(r.dimension,"--dimension",tZ(am)),tq(r.metric,"--metric",tZ(aE)),tM(r.freshnessType,"--freshness-type",tZ(aA)),tq(r.firstChannel,"--first-channel",tZ(ag)),tq(r.secondChannel,"--second-channel",tZ(ay));let u=tK(r.freshnessType,0),n=u===aA.RealTime;tG({startDate:r.activateStartDate,endDate:r.activateEndDate,maxLookbackDays:n?nY:nX,label:n?"增长实时数据":"增长离线数据",startField:"--activate-start-date",endField:"--activate-end-date"});let o=tJ(r.dimension)??[],s=tJ(r.metric)??[],a=tJ(r.firstChannel)??[],c=tJ(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 u=new Set(t),n=tZ(aE),o=r===aA.RealTime?ab:a_,s=aB(r),a=new Set(o),c=r===aA.RealTime?"实时口径":"离线口径";for(let t of e){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[r,d]=e.map(e=>e.trim());if(!n.includes(r))throw new l("growth:metric-query lifeTime 指标非法",{error:"INVALID_LIFE_TIME",message:`--life-time 中的指标必须是 1-30 的合法指标枚举,当前值为 ${r}`});let h=tK(r,0);if(!u.has(h))throw new l("growth:metric-query lifeTime 指标未出现在 metric 中",{error:"INVALID_LIFE_TIME",message:`--life-time ${r}:... 只能配置已经出现在 --metric 中的指标`});if(i.has(h))throw new l("growth:metric-query lifeTime 指标重复配置",{error:"INVALID_LIFE_TIME",message:`指标 ${r} 的 --life-time 只能配置一次;多个天数请写在同一个参数里,例如 --life-time ${r}:${s}`});let p=tW(d)??[];if(0===p.length)throw new l("growth:metric-query lifeTime 缺少生命周期列表",{error:"INVALID_LIFE_TIME",message:`--life-time ${r}: 缺少生命周期天数列表,例如 --life-time ${r}:${s}`});let f=[],m=new Set;for(let e of p){let t=tY(e);if(void 0===t)throw new l("growth:metric-query lifeTime 含有非法天数",{error:"INVALID_LIFE_TIME",message:`--life-time ${r}:${d} 中的生命周期天数必须是正整数`});let i=String(t);if(m.has(i))throw new l("growth:metric-query lifeTime 含有重复天数",{error:"INVALID_LIFE_TIME",message:`--life-time ${r}:${d} 中的生命周期天数不能重复`});if(!a.has(i))throw new l("growth:metric-query lifeTime 超出当前口径范围",{error:"INVALID_LIFE_TIME",message:`${c}下 --life-time 只支持 ${o.join(",")}`});m.add(i),f.push(i)}i.set(h,f)}return i}(r.lifeTime,s,u);var h,p=s,f=d,m=u;let g=aB(m);for(let e of p){let t=t1(aE,e),r=f.get(e);if(aC.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=>aF[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}}),E=await (h={X_Tt_Appid:r.appId,activateStartDate:r.activateStartDate,activateEndDate:r.activateEndDate,dimension:o,metric:A,freshnessType:u,firstChannel:a,secondChannel:c,download:r.download,meta:await i8("growth:metric-query")},e=ub.genBaseURL("/platform_openapi/microgame/v1/growth/query_growth_spread_sheet"),t={activateEndDate:h.activateEndDate,activateStartDate:h.activateStartDate,dimension:h.dimension,download:h.download,firstChannel:h.firstChannel,freshnessType:h.freshnessType,meta:h.meta,metric:h.metric,secondChannel:h.secondChannel},i={X_Tt_Appid:h.X_Tt_Appid,X_Tt_Userid:h.X_Tt_Userid},ub.request({url:e,method:"POST",data:t,headers:i},void 0)),y=ev(E),b=o.flatMap(e=>e===am.ActivateDate?["activateDate"]:e===am.FirstChannel?["firstChannel"]:[]),_=A.flatMap(({metric:e,lifeTime:t})=>{let r=t1(aE,e);return t?.length?t.map(t=>({metric:e,metricName:r,lifeTime:t})):[{metric:e,metricName:r,lifeTime:""}]});return{rawResponse:E,rows:(y?.results??[]).flatMap(e=>{let t={};return o.forEach((r,i)=>{let u=e.dimensionValue?.[i]??"";if(r===am.ActivateDate){t.activateDate=u;return}r===am.FirstChannel&&(t.firstChannel=u)}),_.map(({metric:r,metricName:i,lifeTime:u},n)=>({...t,metric:r,metricName:i,lifeTime:u,value:e.indicatorValue?.[n]??""}))}),csvHeader:[...b,...aD]}})}),s=r.command("performance").description("性能数据"),i4(s.command("performance-diagnosis-query").description("查询小游戏启动和运行性能诊断结果,包括劣化指标、实际值、标准值、差值及优化建议;当前不提供网络诊断").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--host <host>",i2).option("--date <date>","诊断日期,格式 YYYY-MM-DD").option("--device-level <n>",i3).option("--os <os>","操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony").option("--mp-version <version>","小游戏版本号")).action(async(e,t)=>{let r=i6(t,e);await nG("performance:performance-diagnosis-query",r,async()=>{var e;let t,i,u;tM(r.host,"--host",aG),tM(r.deviceLevel,"--device-level",tZ(a$)),tM(r.os,"--os",tZ(aU)),tV(r.date,"--date");let n=await (e={X_Tt_Appid:r.appId,hostAid:az[tK(r.host,0)]??"",date:r.date,deviceLevel:void 0===r.deviceLevel?void 0:tK(r.deviceLevel,0),os:void 0===r.os?void 0:tK(r.os,0),mpVersion:r.mpVersion,meta:await i8("performance:performance-diagnosis-query")},t=ub.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},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n),s={group:"main",genreName:o?.genreName??"",engine:o?.engine??"",degradedIndicatorCount:o?.degradedIndicatorCount??0};return{rawResponse:n,rows:[...aX(o?.launchItems,s,"launch"),...aX(o?.runtimeItems,s,"runtime"),...(o?.otherGroups??[]).flatMap(e=>{let t={group:"other",genreName:e.genreName,engine:e.engine,degradedIndicatorCount:e.degradedIndicatorCount};return[...aX(e.launchItems,t,"launch"),...aX(e.runtimeItems,t,"runtime")]})],csvHeader:aJ}})}),i4(i7(s.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=i6(t,e);await nG("performance:startup-performance-query",r,async()=>{let e,t,i;aZ(r),tq(r.sections,"--sections",tZ(aH)),tM(r.downloadCode,"--download-code",tZ(aV));var u,n=r.sceneIdList,o="--scene-id-list";if(void 0!==n){for(let e of tj(n))if(!tN.test(e))throw new l(`参数 ${o} 包含非法取值: ${e}`,{error:"INVALID_INT_LIST",message:`${o} 每一项必须是整数,但包含非法值: ${e}`})}let s=await (u={X_Tt_Appid:r.appId,filter:{common:a1(r),entranceForm:r.entranceForm,downloadCode:void 0===r.downloadCode?void 0:tK(r.downloadCode,0),sceneIdList:tW(r.sceneIdList)},metrics:tJ(r.metrics),sections:tJ(r.sections),meta:await i8("performance:startup-performance-query")},e=ub.genBaseURL("/platform_openapi/microgame/v1/performance/query_launch_performance"),t={filter:u.filter,meta:u.meta,metrics:u.metrics,sections:u.sections},i={X_Tt_Appid:u.X_Tt_Appid,X_Tt_Userid:u.X_Tt_Userid},ub.request({url:e,method:"POST",data:t,headers:i},void 0)),a=ev(s);return{rawResponse:s,rows:aQ(a?.series),csvHeader:aK}})}),i4(i7(s.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=i6(t,e);await nG("performance:runtime-performance-query",r,async()=>{var e;let t,i,u;aZ(r);let n=await (e={X_Tt_Appid:r.appId,filter:a1(r),includeDeviceBreakdown:r.includeDeviceBreakdown,includeFpsDistribution:r.includeFpsDistribution,includeMemoryDistribution:r.includeMemoryDistribution,metrics:tJ(r.metrics),meta:await i8("performance:runtime-performance-query")},t=ub.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},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,rows:aQ(o?.series),csvHeader:aK}})}),i4(i7(s.command("network-performance-query").description("查询小游戏网络性能数据,包括 request 和 downloadFile 的请求耗时、错误率等指标").option("--metrics <list>","网络性能指标枚举,逗号分隔;不传返回默认指标集"))).action(async(e,t)=>{let r=i6(t,e);await nG("performance:network-performance-query",r,async()=>{var e;let t,i,u;aZ(r);let n=await (e={X_Tt_Appid:r.appId,filter:a1(r),metrics:tJ(r.metrics),meta:await i8("performance:network-performance-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/performance/query_network_performance"),i={filter:e.filter,meta:e.meta,metrics:e.metrics},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,rows:aQ(o?.series),csvHeader:aK}})}),i4(s.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>",i1).option("--os <os>",i0).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=i6(t,e);await nG("performance:error-log-query",r,async()=>{var e;let t,i,u;tM(r.host,"--host",tZ(aL)),tM(r.os,"--os",tZ(aP)),tq(r.logLevelList,"--log-level-list",tZ(aN)),function(e){let{startTime:t,endTime:r,maxLookbackDays:i,label:u}=e,n=e.startField??"--start-time",o=e.endField??"--end-time",s=e.unit??"milliseconds",a="seconds"===s?"秒级 Unix 时间戳":"毫秒时间戳",c=BigInt(e.lookbackTolerance??0),d=[];for(let[e,i]of[[n,t],[o,r]]){if(void 0===i)continue;if(!tP.test(i))throw new l(`参数 ${e} 时间戳非法: ${i}`,{error:"INVALID_TIMESTAMP",message:`${e} 必须是正整数${a}`});let t=BigInt(i);d.push([e,t])}let h=d.find(([e])=>e===n)?.[1],p=d.find(([e])=>e===o)?.[1];if(void 0!==h&&void 0!==p&&h>p)throw new l(`${n} 不能晚于 ${o}`,{error:"INVALID_TIMESTAMP_RANGE",message:`${n} 不能晚于 ${o}`});let f=BigInt("seconds"===s?Math.floor(Date.now()/1e3):Date.now()),m=f-BigInt(i*("seconds"===s?86400:864e5))-c;for(let[e,t]of d){if(t>f)throw new l(`${e} 不能晚于当前时间`,{error:"INVALID_TIMESTAMP_RANGE",message:`${e} 不能晚于当前时间`});if(t<m)throw new l(`${u}仅支持最近 ${i} 天的数据`,{error:"OUT_OF_LOOKBACK",message:`${u}仅支持最近 ${i} 天的数据,${e} 已超出范围`})}}({startTime:r.startTime,endTime:r.endTime,maxLookbackDays:nZ,label:"错误日志",unit:"seconds"}),tH(r.pageGroupSize,"--page-group-size",1,20);let n=await (e={X_Tt_Appid:r.appId,startTime:r.startTime,endTime:r.endTime,host:void 0===r.host?void 0:tK(r.host,0),os:void 0===r.os?void 0:tK(r.os,0),appVersion:r.appVersion,gameVersion:r.gameVersion,jssdkVersion:r.jssdkVersion,openId:r.openId,traceId:r.traceId,logLevelList:tJ(r.logLevelList),filterMsg:tW(r.filterMsg),pageGroupSize:r.pageGroupSize,searchAfter:r.searchAfter,meta:await i8("performance:error-log-query")},t=ub.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},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,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:aY,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 发布的 ${eR} Skill`).addHelpText("after","\n说明:\n 安装或重新同步本机 Agent Skill\n update 默认会执行同步;需要手动修复 Skill 时再运行本命令\n\n示例:\n $ dymg skills install").action(aa),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(af),r.command("update").description("更新 CLI 并同步 Skill").option("--target-version <version>","安装指定版本或 dist tag,默认 latest").option("--skip-skills","只更新 CLI,跳过 Skill 同步").addOption(new j("--package-manager <packageManager>","指定全局安装使用的包管理器").choices(uo)).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(ah),i),h=!1,p=!1,f=!1,m=()=>{p&&a3(),p=!0,process.exitCode=130;let e=ui();h&&e||a3();let t=setTimeout(()=>{a3()},200);a0({...e,durationMs:Date.now()-c,success:!1,errorMessage:"命令已中断",errorCode:eq()?.errorCode}).finally(()=>{clearTimeout(t),a3()})};process.once("SIGINT",m),process.once("SIGTERM",m),d.hook("preAction",(e,t)=>{var r,i,u;let n,o;h=!0,r=t,f=!a2.has(function(e){let t=e;for(;t.parent&&"dymg"!==t.parent.name();)t=t.parent;return t.name()}(r)),i=t,u=a,n=i.optsWithGlobals(),o=function(e){let t=[],r=e;for(;r&&r.parent;)t.unshift(r.name()),r=r.parent;return t}(i),eM({caller:"string"==typeof n.caller&&iZ(n.caller)?n.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(" "))}(u),requestParams:F(n),errorMessage:void 0,errorCode:void 0})});try{await d.parseAsync(e);let t=ui();if(h&&t){let e=0===Number(process.exitCode??0);await a0({...t,durationMs:Date.now()-c,success:e,errorMessage:e?void 0:eq()?.errorMessage,errorCode:e?void 0:eq()?.errorCode})}h&&f&&0===Number(process.exitCode??0)&&await uy()}catch(r){let e=r instanceof Error?r.message:String(r),t=ui();if(r instanceof v){process.exitCode=r.exitCode,h&&t&&await a0({...t,durationMs:Date.now()-c,success:0===r.exitCode,errorMessage:0===r.exitCode?void 0:e,errorCode:0===r.exitCode?void 0:un(r)});return}throw h&&t&&await a0({...t,durationMs:Date.now()-c,success:!1,errorMessage:e,errorCode:un(r)}),r}finally{process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m)}}(async function(e=process.argv){var t,r;return t={},r=()=>a6(e),eU.run(t,r)})().then(async()=>{await E(Number(process.exitCode??0))}).catch(async e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
|
|
149
|
+
- ${eP}`).action(oi),u.command("status").description("查看当前登录状态").action(oo),u.command("logout").description("退出当前登录").action(os),u.command("check-dir-writable").description("用于 Agent 测试执行环境中的当前登录态目录是否可写,并输出结构化结果").addHelpText("after","\n示例:\n $ dymg auth check-dir-writable").action(oa),i4(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=i6(t,e);await nG("game:game-list",r,async()=>{var e;let t,i,u;tH(r.pageIndex,"--page-index",1,1e4),tH(r.pageSize,"--page-size",1,100);let n={pageIndex:tK(r.pageIndex,1),pageSize:tK(r.pageSize,20)},o=await (e=n,t=ub.genBaseURL("/platform_openapi/microgame/v1/game/query_game_list"),i={pageIndex:e.pageIndex,pageSize:e.pageSize},u={X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"GET",params:i,headers:u},void 0)),s=ev(o),a=(s?.list??[]).map(e=>({appId:e.appId,appName:e.appName}));return{rawResponse:o,rows:a,csvHeader:["appId","appName"],resultMeta:rG({returnedCount:a.length,total:s?.total,page:n.pageIndex,pageSize:n.pageSize})}})}),n=r.command("insight").description("资讯与榜单"),i4(n.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=i6(t,e);await nG("insight:ranking-list",r,async()=>{var e;let t,i,u;tM(r.rankType,"--rank-type",tZ(aS)),tq(r.gameBusinessList,"--game-business-list",tZ(aT)),tq(r.gameTypeList,"--game-type-list",aj),tz(r.page,"--page"),tH(r.pageSize,"--page-size",1,200);let n=tK(r.page,1),o=tK(r.pageSize,20),s=n*o;if(s>200)throw new l("榜单仅支持查询前 200 名",{error:"OUT_OF_RANK_LIMIT",message:`榜单仅支持前 200 名,当前页末位排名 ${s} 已超出范围`});let a=await (e={gameBusinessList:tJ(r.gameBusinessList),gameTypeList:tW(r.gameTypeList),onlyMyGame:r.onlyMyGame,rankType:tK(r.rankType,0),page:String(n),pageSize:String(o),meta:await i8("insight:ranking-list")},t=ub.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},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),c=ev(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:rG({returnedCount:d.length,total:c?.page?.total,page:c?.page?.page,pageSize:c?.page?.pageSize,hasMore:c?.page?.hasMore,nextCursor:c?.page?.nextSearchAfter})}})}),i4(n.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=i6(t,e);await nG("insight:hotspot-list",r,async()=>{var e;let t,i,u,n;tq(r.gameTypeIds,"--game-type-ids",aj);let o=(e=r,!!(e.keyword?.trim()||tW(e.gameTypeIds)?.length||tW(e.topicIds)?.length));tH(r.topN,"--top-n",1,o?50:100);let s=r.topN??(o?String(50):void 0),a=await (t={gameTypeIds:tW(r.gameTypeIds),keyword:r.keyword?.trim()||void 0,meta:await i8("insight:hotspot-list"),topN:s,topicIds:tW(r.topicIds)},i=ub.genBaseURL("/platform_openapi/microgame/v1/insight/query_douyin_hotspots"),u={gameTypeIds:t.gameTypeIds,keyword:t.keyword,meta:t.meta,topN:t.topN,topicIds:t.topicIds},n={X_Tt_Appid:t.X_Tt_Appid,X_Tt_Userid:t.X_Tt_Userid},ub.request({url:i,method:"POST",data:u,headers:n},void 0)),l=ev(a);return{rawResponse:a,rows:(l?.items??[]).map(e=>({title:e.title,hotValue:e.hotValue,topics:aL(e.topics),hotInsights:e.hotInsights,jumpUrl:e.jumpUrl,contentId:e.contentId,coverUrl:e.coverUrl,playUrl:e.playUrl,contentTags:aL(e.contentTags),gamificationCategories:aL(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:aL(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:aL(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:aL(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),commentSummary:e.commentSummary,topComments:aL(e.topComments,e=>`${e.content??""}:${e.likeCount??""}`),dataStatus:e.dataStatus})),csvHeader:aI}})}),i4(n.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=i6(t,e);await nG("insight:element-list",r,async()=>{let e,t,i;tz(r.hotspotId,"--hotspot-id"),tM(r.elementType,"--element-type",aR),tz(r.page,"--page"),tH(r.pageSize,"--page-size",1,50);let u=tK(r.page,1),n=tK(r.pageSize,20),o=await (e={elementType:r.elementType,hotspotId:r.hotspotId,keyword:r.keyword?.trim()||void 0,page:u,pageSize:n,videoId:r.videoId},t=ub.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},ub.request({url:t,method:"POST",data:i},void 0)),s=ev(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:aL(e.elementTags),description:e.description,heatTrend:aL(e.heatTrend,e=>`${tQ(e.timestamp,{format:"date"})}:${e.hotScore??""}`)}));return{rawResponse:o,rows:a,csvHeader:aO,resultMeta:rG({returnedCount:a.length,total:s?.total,page:s?.page??u,pageSize:s?.pageSize??n,hasMore:s?.hasMore})}})}),i4(n.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=i6(t,e);await nG("insight:theme-list",r,async()=>{let e,t,i;tz(r.page,"--page"),tH(r.pageSize,"--page-size",1,50);let u=tK(r.page,1),n=tK(r.pageSize,20),o=await (e={includeTopVideos:r.includeTopVideos,page:u,pageSize:n,parentTopicId:r.parentTopicId,topicIdList:tW(r.topicIdList)},t=ub.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},ub.request({url:t,method:"POST",data:i},void 0)),s=ev(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:aL(e.gamificationReference?.categories,e=>`${e.label??""}:${e.reason??""}`),gamificationMechanics:aL(e.gamificationReference?.mechanics,e=>`${e.label??""}:${e.reason??""}`),genderDistribution:aL(e.genderDistribution,e=>`${e.label??""}:${e.ratio??""}`),ageDistribution:aL(e.ageDistribution,e=>`${e.label??""}:${e.ratio??""}`),audiencePreferences:aL(e.userFeatures?.audiencePreferences,e=>`${e.title??""}:${e.insight??""}`),contentPreferences:aL(e.userFeatures?.contentPreferences,e=>`${e.title??""}:${e.insight??""}`),interactionPreferences:aL(e.userFeatures?.interactionPreferences,e=>`${e.title??""}:${e.insight??""}`),relatedGames:function(e){if(e?.length)return F(e.map(e=>({gameId:e.gameId,gameName:e.gameName,iconUrl:e.iconUrl,jumpUrl:e.jumpUrl,heatValue:e.heatValue})))}(e.relatedGames),recentHotspots:aL(e.recentHotspots,e=>`${e.title??""}:${e.heatValue??""}`),topVideos:aL(e.topVideos,e=>`${e.video?.title??""}:${e.likeCount??""}`),trend7D:aL(e.trend7D,e=>`${tQ(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend30D:aL(e.trend30D,e=>`${tQ(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`),trend90D:aL(e.trend90D,e=>`${tQ(e.timestampMs,{format:"date",unit:"ms"})}:${e.value??""}`)}));return{rawResponse:o,rows:a,csvHeader:ak,resultMeta:rG({returnedCount:a.length,total:s?.total,page:u,pageSize:n,hasMore:s?.hasMore})}})}),o=r.command("analytics").description("用户数据"),i4(i9(o.command("behavior-query").description("查询用户的活跃用户、新增用户、累计用户、启动次数、游戏时长等行为指标,支持 App、操作系统等筛选"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:behavior-query",r,async()=>{var e;let t,i,u;n9(r),n7(r);let n=await (e={X_Tt_Appid:r.appId,filter:n1(r),meta:await i8("analytics:behavior-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_user_behavior"),i={filter:e.filter,meta:e.meta},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n),s=(o?.items??[]).map(e=>({...e,recordType:"data"}));return{rawResponse:n,rows:[...s,...o?.summary?[{...o.summary,recordType:"summary"}]:[]],csvHeader:n2}})}),i4(i9(o.command("realtime-query").description("查询游戏当天的实时访问人数和访问次数"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:realtime-query",r,async()=>{var e;let t,i,u;tG({startDate:r.startDate,endDate:r.endDate,maxLookbackDays:nK,label:"实时数据"}),n7(r);let n=await (e={X_Tt_Appid:r.appId,filter:n1(r),meta:await i8("analytics:realtime-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_realtime_user"),i={filter:e.filter,meta:e.meta},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,rows:(o?.items??[]).map(e=>({hour:e.hour,activeUser:e.activeUser,openTime:e.openTime})),csvHeader:n0}})}),i4(i9(o.command("retention-query").description("查询用户的次日、3 日、14 日、30 日留存率,支持筛选日期、App、操作系统、用户类型等").option("--retention-scene <n>","留存场景:1 全量 / 2 侧边栏"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:retention-query",r,async()=>{var e;let t,i,u;n9(r),n7(r),tM(r.retentionScene,"--retention-scene",tZ(uv));let n=await (e={X_Tt_Appid:r.appId,filter:n1(r),retentionScene:void 0===r.retentionScene?void 0:tK(r.retentionScene,0),meta:await i8("analytics:retention-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_user_retention"),i={filter:e.filter,meta:e.meta,retentionScene:e.retentionScene},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,rows:(o?.items??[]).map(e=>({...e})),csvHeader:n3}})}),i4(i9(o.command("source-query").description("查询不同来源渠道下的活跃用户、新增用户数、启动次数、次均游戏时长等").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:source-query",r,async()=>{var e;let t,i,u;n9(r),n7(r),tH(r.topN,"--top-n",1,100);let n=await (e={X_Tt_Appid:r.appId,filter:n1(r),topN:r.topN,meta:await i8("analytics:source-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_user_source"),i={filter:e.filter,meta:e.meta,topN:e.topN},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,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:n6}})}),i4(i9(o.command("profile-query").description("查询用户的性别、年龄、地域分布,区分不同 App、活跃/新增用户类型"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:profile-query",r,async()=>{var e;let t,i,u;n9(r),n7(r);let n=await (e={X_Tt_Appid:r.appId,filter:n1(r),meta:await i8("analytics:profile-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_user_portrait"),i={filter:e.filter,meta:e.meta},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,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:n4}})}),i4(i9(o.command("device-query").description("查询用户的机型、品牌、客户端版本、基础库版本分布等").requiredOption("--dimension <n>","维度:1 型号 / 2 品牌 / 3 宿主版本 / 4 基础库版本").option("--top-n <n>","返回条数"))).action(async(e,t)=>{let r=i6(t,e);await nG("analytics:device-query",r,async()=>{var e;let t,i,u;n9(r),n7(r),tM(r.dimension,"--dimension",tZ(uw)),tH(r.topN,"--top-n",1,100);let n=tK(r.dimension,0),o=await (e={X_Tt_Appid:r.appId,dimension:n,filter:n1(r),topN:r.topN,meta:await i8("analytics:device-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/user/query_user_terminal"),i={dimension:e.dimension,filter:e.filter,meta:e.meta,topN:e.topN},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),s=ev(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:n8}})}),i4(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",aB,[]).requiredOption("--first-channel <list>","一级渠道枚举,逗号分隔").requiredOption("--freshness-type <n>","数据时效:1 实时 / 2 离线").option("--second-channel <list>","二级渠道枚举,逗号分隔").option("--download","是否返回下载链接",!1).addHelpText("after",aw)).action(async(e,t)=>{let r=i6(t,e);await nG("growth:metric-query",r,async()=>{let e,t,i;tq(r.dimension,"--dimension",tZ(am)),tq(r.metric,"--metric",tZ(aE)),tM(r.freshnessType,"--freshness-type",tZ(aA)),tq(r.firstChannel,"--first-channel",tZ(ag)),tq(r.secondChannel,"--second-channel",tZ(ay));let u=tK(r.freshnessType,0),n=u===aA.RealTime;tG({startDate:r.activateStartDate,endDate:r.activateEndDate,maxLookbackDays:n?nY:nX,label:n?"增长实时数据":"增长离线数据",startField:"--activate-start-date",endField:"--activate-end-date"});let o=tJ(r.dimension)??[],s=tJ(r.metric)??[],a=tJ(r.firstChannel)??[],c=tJ(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 u=new Set(t),n=tZ(aE),o=ax(r),s=r===aA.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,h]=e.map(e=>e.trim());if(!n.includes(d))throw new l("growth:metric-query lifeTime 指标非法",{error:"INVALID_LIFE_TIME",message:`--life-time 中的指标必须是 1-30 的合法指标枚举,当前值为 ${d}`});let p=tK(d,0),f=(a=r,c=p,a===aA.RealTime?ab:c===aE.TotalROI?aC:a_),m=new Set(f);if(!u.has(p))throw new l("growth:metric-query lifeTime 指标未出现在 metric 中",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}:... 只能配置已经出现在 --metric 中的指标`});if(i.has(p))throw new l("growth:metric-query lifeTime 指标重复配置",{error:"INVALID_LIFE_TIME",message:`指标 ${d} 的 --life-time 只能配置一次;多个天数请写在同一个参数里,例如 --life-time ${d}:${o}`});let g=tW(h)??[];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=[],E=new Set;for(let e of g){let t=tY(e);if(void 0===t)throw new l("growth:metric-query lifeTime 含有非法天数",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}:${h} 中的生命周期天数必须是正整数`});let r=String(t);if(E.has(r))throw new l("growth:metric-query lifeTime 含有重复天数",{error:"INVALID_LIFE_TIME",message:`--life-time ${d}:${h} 中的生命周期天数不能重复`});if(!m.has(r))throw new l("growth:metric-query lifeTime 超出当前口径范围",{error:"INVALID_LIFE_TIME",message:`${s}下 --life-time 只支持 ${f.join(",")}`});E.add(r),A.push(r)}i.set(p,A)}return i}(r.lifeTime,s,u);var h,p=s,f=d,m=u;let g=ax(m);for(let e of p){let t=t1(aE,e),r=f.get(e);if(aD.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=>av[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}}),E=await (h={X_Tt_Appid:r.appId,activateStartDate:r.activateStartDate,activateEndDate:r.activateEndDate,dimension:o,metric:A,freshnessType:u,firstChannel:a,secondChannel:c,download:r.download,meta:await i8("growth:metric-query")},e=ub.genBaseURL("/platform_openapi/microgame/v1/growth/query_growth_spread_sheet"),t={activateEndDate:h.activateEndDate,activateStartDate:h.activateStartDate,dimension:h.dimension,download:h.download,firstChannel:h.firstChannel,freshnessType:h.freshnessType,meta:h.meta,metric:h.metric,secondChannel:h.secondChannel},i={X_Tt_Appid:h.X_Tt_Appid,X_Tt_Userid:h.X_Tt_Userid},ub.request({url:e,method:"POST",data:t,headers:i},void 0)),y=ev(E),b=o.flatMap(e=>e===am.ActivateDate?["activateDate"]:e===am.FirstChannel?["firstChannel"]:[]),_=A.flatMap(({metric:e,lifeTime:t})=>{let r=t1(aE,e);return t?.length?t.map(t=>({metric:e,metricName:r,lifeTime:t})):[{metric:e,metricName:r,lifeTime:""}]});return{rawResponse:E,rows:(y?.results??[]).flatMap(e=>{let t={};return o.forEach((r,i)=>{let u=e.dimensionValue?.[i]??"";if(r===am.ActivateDate){t.activateDate=u;return}r===am.FirstChannel&&(t.firstChannel=u)}),_.map(({metric:r,metricName:i,lifeTime:u},n)=>({...t,metric:r,metricName:i,lifeTime:u,value:e.indicatorValue?.[n]??""}))}),csvHeader:[...b,...aF]}})}),s=r.command("performance").description("性能数据"),i4(s.command("performance-diagnosis-query").description("查询小游戏启动和运行性能诊断结果,包括劣化指标、实际值、标准值、差值及优化建议;当前不提供网络诊断").requiredOption("--app-id <appId>","小游戏 appId").requiredOption("--host <host>",i2).option("--date <date>","诊断日期,格式 YYYY-MM-DD").option("--device-level <n>",i3).option("--os <os>","操作系统枚举:1 全部 / 2 Android / 3 iOS / 4 OpenHarmony").option("--mp-version <version>","小游戏版本号")).action(async(e,t)=>{let r=i6(t,e);await nG("performance:performance-diagnosis-query",r,async()=>{var e;let t,i,u;tM(r.host,"--host",aW),tM(r.deviceLevel,"--device-level",tZ(aU)),tM(r.os,"--os",tZ(aM)),tV(r.date,"--date");let n=await (e={X_Tt_Appid:r.appId,hostAid:aG[tK(r.host,0)]??"",date:r.date,deviceLevel:void 0===r.deviceLevel?void 0:tK(r.deviceLevel,0),os:void 0===r.os?void 0:tK(r.os,0),mpVersion:r.mpVersion,meta:await i8("performance:performance-diagnosis-query")},t=ub.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},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n),s={group:"main",genreName:o?.genreName??"",engine:o?.engine??"",degradedIndicatorCount:o?.degradedIndicatorCount??0};return{rawResponse:n,rows:[...aQ(o?.launchItems,s,"launch"),...aQ(o?.runtimeItems,s,"runtime"),...(o?.otherGroups??[]).flatMap(e=>{let t={group:"other",genreName:e.genreName,engine:e.engine,degradedIndicatorCount:e.degradedIndicatorCount};return[...aQ(e.launchItems,t,"launch"),...aQ(e.runtimeItems,t,"runtime")]})],csvHeader:aK}})}),i4(i7(s.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=i6(t,e);await nG("performance:startup-performance-query",r,async()=>{let e,t,i;a1(r),tq(r.sections,"--sections",tZ(az)),tM(r.downloadCode,"--download-code",tZ(aH));var u,n=r.sceneIdList,o="--scene-id-list";if(void 0!==n){for(let e of tj(n))if(!tN.test(e))throw new l(`参数 ${o} 包含非法取值: ${e}`,{error:"INVALID_INT_LIST",message:`${o} 每一项必须是整数,但包含非法值: ${e}`})}let s=await (u={X_Tt_Appid:r.appId,filter:{common:a2(r),entranceForm:r.entranceForm,downloadCode:void 0===r.downloadCode?void 0:tK(r.downloadCode,0),sceneIdList:tW(r.sceneIdList)},metrics:tJ(r.metrics),sections:tJ(r.sections),meta:await i8("performance:startup-performance-query")},e=ub.genBaseURL("/platform_openapi/microgame/v1/performance/query_launch_performance"),t={filter:u.filter,meta:u.meta,metrics:u.metrics,sections:u.sections},i={X_Tt_Appid:u.X_Tt_Appid,X_Tt_Userid:u.X_Tt_Userid},ub.request({url:e,method:"POST",data:t,headers:i},void 0)),a=ev(s);return{rawResponse:s,rows:aZ(a?.series),csvHeader:aY}})}),i4(i7(s.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=i6(t,e);await nG("performance:runtime-performance-query",r,async()=>{var e;let t,i,u;a1(r);let n=await (e={X_Tt_Appid:r.appId,filter:a2(r),includeDeviceBreakdown:r.includeDeviceBreakdown,includeFpsDistribution:r.includeFpsDistribution,includeMemoryDistribution:r.includeMemoryDistribution,metrics:tJ(r.metrics),meta:await i8("performance:runtime-performance-query")},t=ub.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},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,rows:aZ(o?.series),csvHeader:aY}})}),i4(i7(s.command("network-performance-query").description("查询小游戏网络性能数据,包括 request 和 downloadFile 的请求耗时、错误率等指标").option("--metrics <list>","网络性能指标枚举,逗号分隔;不传返回默认指标集"))).action(async(e,t)=>{let r=i6(t,e);await nG("performance:network-performance-query",r,async()=>{var e;let t,i,u;a1(r);let n=await (e={X_Tt_Appid:r.appId,filter:a2(r),metrics:tJ(r.metrics),meta:await i8("performance:network-performance-query")},t=ub.genBaseURL("/platform_openapi/microgame/v1/performance/query_network_performance"),i={filter:e.filter,meta:e.meta,metrics:e.metrics},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,rows:aZ(o?.series),csvHeader:aY}})}),i4(s.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>",i1).option("--os <os>",i0).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=i6(t,e);await nG("performance:error-log-query",r,async()=>{var e;let t,i,u;tM(r.host,"--host",tZ(aN)),tM(r.os,"--os",tZ(a$)),tq(r.logLevelList,"--log-level-list",tZ(aP)),function(e){let{startTime:t,endTime:r,maxLookbackDays:i,label:u}=e,n=e.startField??"--start-time",o=e.endField??"--end-time",s=e.unit??"milliseconds",a="seconds"===s?"秒级 Unix 时间戳":"毫秒时间戳",c=BigInt(e.lookbackTolerance??0),d=[];for(let[e,i]of[[n,t],[o,r]]){if(void 0===i)continue;if(!tP.test(i))throw new l(`参数 ${e} 时间戳非法: ${i}`,{error:"INVALID_TIMESTAMP",message:`${e} 必须是正整数${a}`});let t=BigInt(i);d.push([e,t])}let h=d.find(([e])=>e===n)?.[1],p=d.find(([e])=>e===o)?.[1];if(void 0!==h&&void 0!==p&&h>p)throw new l(`${n} 不能晚于 ${o}`,{error:"INVALID_TIMESTAMP_RANGE",message:`${n} 不能晚于 ${o}`});let f=BigInt("seconds"===s?Math.floor(Date.now()/1e3):Date.now()),m=f-BigInt(i*("seconds"===s?86400:864e5))-c;for(let[e,t]of d){if(t>f)throw new l(`${e} 不能晚于当前时间`,{error:"INVALID_TIMESTAMP_RANGE",message:`${e} 不能晚于当前时间`});if(t<m)throw new l(`${u}仅支持最近 ${i} 天的数据`,{error:"OUT_OF_LOOKBACK",message:`${u}仅支持最近 ${i} 天的数据,${e} 已超出范围`})}}({startTime:r.startTime,endTime:r.endTime,maxLookbackDays:nZ,label:"错误日志",unit:"seconds"}),tH(r.pageGroupSize,"--page-group-size",1,20);let n=await (e={X_Tt_Appid:r.appId,startTime:r.startTime,endTime:r.endTime,host:void 0===r.host?void 0:tK(r.host,0),os:void 0===r.os?void 0:tK(r.os,0),appVersion:r.appVersion,gameVersion:r.gameVersion,jssdkVersion:r.jssdkVersion,openId:r.openId,traceId:r.traceId,logLevelList:tJ(r.logLevelList),filterMsg:tW(r.filterMsg),pageGroupSize:r.pageGroupSize,searchAfter:r.searchAfter,meta:await i8("performance:error-log-query")},t=ub.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},u={X_Tt_Appid:e.X_Tt_Appid,X_Tt_Userid:e.X_Tt_Userid},ub.request({url:t,method:"POST",data:i,headers:u},void 0)),o=ev(n);return{rawResponse:n,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:aX,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 发布的 ${eR} Skill`).addHelpText("after","\n说明:\n 安装或重新同步本机 Agent Skill\n update 默认会执行同步;需要手动修复 Skill 时再运行本命令\n\n示例:\n $ dymg skills install").action(aa),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(af),r.command("update").description("更新 CLI 并同步 Skill").option("--target-version <version>","安装指定版本或 dist tag,默认 latest").option("--skip-skills","只更新 CLI,跳过 Skill 同步").addOption(new j("--package-manager <packageManager>","指定全局安装使用的包管理器").choices(uo)).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(ah),i),h=!1,p=!1,f=!1,m=()=>{p&&a6(),p=!0,process.exitCode=130;let e=ui();h&&e||a6();let t=setTimeout(()=>{a6()},200);a3({...e,durationMs:Date.now()-c,success:!1,errorMessage:"命令已中断",errorCode:eq()?.errorCode}).finally(()=>{clearTimeout(t),a6()})};process.once("SIGINT",m),process.once("SIGTERM",m),d.hook("preAction",(e,t)=>{var r,i,u;let n,o;h=!0,r=t,f=!a0.has(function(e){let t=e;for(;t.parent&&"dymg"!==t.parent.name();)t=t.parent;return t.name()}(r)),i=t,u=a,n=i.optsWithGlobals(),o=function(e){let t=[],r=e;for(;r&&r.parent;)t.unshift(r.name()),r=r.parent;return t}(i),eM({caller:"string"==typeof n.caller&&iZ(n.caller)?n.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(" "))}(u),requestParams:F(n),errorMessage:void 0,errorCode:void 0})});try{await d.parseAsync(e);let t=ui();if(h&&t){let e=0===Number(process.exitCode??0);await a3({...t,durationMs:Date.now()-c,success:e,errorMessage:e?void 0:eq()?.errorMessage,errorCode:e?void 0:eq()?.errorCode})}h&&f&&0===Number(process.exitCode??0)&&await uy()}catch(r){let e=r instanceof Error?r.message:String(r),t=ui();if(r instanceof v){process.exitCode=r.exitCode,h&&t&&await a3({...t,durationMs:Date.now()-c,success:0===r.exitCode,errorMessage:0===r.exitCode?void 0:e,errorCode:0===r.exitCode?void 0:un(r)});return}throw h&&t&&await a3({...t,durationMs:Date.now()-c,success:!1,errorMessage:e,errorCode:un(r)}),r}finally{process.removeListener("SIGINT",m),process.removeListener("SIGTERM",m)}}(async function(e=process.argv){var t,r;return t={},r=()=>a4(e),eU.run(t,r)})().then(async()=>{await E(Number(process.exitCode??0))}).catch(async e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`${t}
|
|
149
150
|
`),await E(1)})})(),__webpack_exports__)exports[__rspack_i]=__webpack_exports__[__rspack_i];Object.defineProperty(exports,"__esModule",{value:!0});
|
package/package.json
CHANGED
|
@@ -83,7 +83,9 @@ dymg growth metric-query \
|
|
|
83
83
|
- 指标 `1`、`2`、`3` 是首日类指标,可以不传 `--life-time`;如果传,只能传 `1`。
|
|
84
84
|
- 指标 `4-30` 是非首日指标,每个指标都必须传非空 `--life-time`。
|
|
85
85
|
- `--freshness-type 1`(实时口径)时,生命周期天数只支持 `1,2`。
|
|
86
|
-
- `--freshness-type 2
|
|
86
|
+
- `--freshness-type 2`(离线口径)时:
|
|
87
|
+
- 总 ROI(指标 `22`)支持 `1-90,120,150,180`。
|
|
88
|
+
- 其他非首日指标支持 `1-14,30,45,60,75,90,120,150,180`。
|
|
87
89
|
|
|
88
90
|
### 日期窗口
|
|
89
91
|
|
|
@@ -119,7 +121,7 @@ dymg growth metric-query \
|
|
|
119
121
|
7. 指标 `1/2/3` 没有传非 `1` 的 `--life-time`。
|
|
120
122
|
8. 指标 `4-30` 每个都传了非空 `--life-time`。
|
|
121
123
|
9. `--freshness-type 1` 时,`--life-time` 只取 `1,2`。
|
|
122
|
-
10. `--freshness-type 2`
|
|
124
|
+
10. `--freshness-type 2` 时,总 ROI(指标 `22`)的 `--life-time` 只取 `1-90,120,150,180`;其他非首日指标只取 `1-14,30,45,60,75,90,120,150,180`。
|
|
123
125
|
11. `--dimension` 非空,且只取 `1` 或 `2`。
|
|
124
126
|
|
|
125
127
|
### `--freshness-type` 合法值
|