ezllm 0.0.31 → 0.0.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +27 -31
- package/dist/daemon.js +15 -19
- package/dist/server.js +94 -82
- package/dist/web-ui/assets/{DashboardView-upcGoFpc.js → DashboardView-G5UgfzzO.js} +1 -1
- package/dist/web-ui/assets/{LayoutView-CruZSfjc.css → LayoutView-BLjO8ed9.css} +1 -1
- package/dist/web-ui/assets/{LayoutView-DtXN7Xi_.js → LayoutView-CwDRqFye.js} +1 -1
- package/dist/web-ui/assets/{LoginView-CUe0fqRV.js → LoginView-CdCs2Ukh.js} +1 -1
- package/dist/web-ui/assets/LogsView-CAszK0sY.js +5 -0
- package/dist/web-ui/assets/LogsView-D7FTeaYQ.css +1 -0
- package/dist/web-ui/assets/{ManagedServicesView-BEoMqaxE.js → ManagedServicesView-C7L56_Tq.js} +4 -4
- package/dist/web-ui/assets/{ManagedServicesView-Bi180Qjf.css → ManagedServicesView-D29NyvP6.css} +1 -1
- package/dist/web-ui/assets/{ProvidersView-5-nXXTf1.css → ProvidersView-DIlimMSR.css} +1 -1
- package/dist/web-ui/assets/{ProvidersView-BaddfTOz.js → ProvidersView-Du8ZqQ7C.js} +3 -3
- package/dist/web-ui/assets/{ServiceStatusView-RjFNR9tF.js → ServiceStatusView-BTa1U_mq.js} +1 -1
- package/dist/web-ui/assets/{SettingsView-CQ7lvwL9.js → SettingsView-C-lQq_Fn.js} +1 -1
- package/dist/web-ui/assets/SetupView-BLl-ZFOA.css +1 -0
- package/dist/web-ui/assets/SetupView-Oop8FC0p.js +1 -0
- package/dist/web-ui/assets/{config-MgmZ-7E2.js → config-a3WGd94V.js} +1 -1
- package/dist/web-ui/assets/format-BwEbbkjl.js +1 -0
- package/dist/web-ui/assets/index-DPq2QylL.js +49 -0
- package/dist/web-ui/assets/message-C5ZFfxcO.js +2 -0
- package/dist/web-ui/assets/{providers-D_WDYn62.js → providers-CmBRlVkF.js} +1 -1
- package/dist/web-ui/assets/router-DvvoEPD-.js +6 -0
- package/dist/web-ui/assets/{useCopyToast-CO6fr7kf.js → useCopyToast-BNDnj8jd.js} +1 -1
- package/dist/web-ui/assets/{useManagerApi-CCQ0LO2A.js → useManagerApi-CqT4wuBt.js} +1 -1
- package/dist/web-ui/assets/{useQuickRangeFilter-DOA0bSoV.js → useQuickRangeFilter-DPujpXE5.js} +1 -1
- package/dist/web-ui/assets/useToast-DeKoozwQ.js +1 -0
- package/dist/web-ui/index.html +3 -3
- package/package.json +2 -2
- package/dist/web-ui/assets/LogsView-CHp-pVu3.css +0 -1
- package/dist/web-ui/assets/LogsView-D31Tc6MJ.js +0 -5
- package/dist/web-ui/assets/SetupView-BDyHouba.css +0 -1
- package/dist/web-ui/assets/SetupView-Cm7iSrjI.js +0 -1
- package/dist/web-ui/assets/format-lzQY461O.js +0 -1
- package/dist/web-ui/assets/index-BCZqYZB7.js +0 -49
- package/dist/web-ui/assets/message-B4CpctQv.js +0 -2
- package/dist/web-ui/assets/router-B8DYHNvS.js +0 -6
- package/dist/web-ui/assets/useToast-C7Ey6ket.js +0 -1
package/dist/server.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as e}from"node:module";import{homedir as t,networkInterfaces as n,platform as r}from"node:os";import{createServer as i}from"http";import{Http2ServerRequest as a,constants as o}from"http2";import{Readable as s}from"stream";import c from"crypto";import{copyFileSync as l,createWriteStream as u,existsSync as d,mkdirSync as f,readFileSync as p,readdirSync as m,renameSync as h,rmSync as g,rmdirSync as _,statSync as v,unlinkSync as y,writeFileSync as b}from"node:fs";import{basename as x,delimiter as S,dirname as C,join as w,resolve as T}from"node:path";import{cwd as E}from"node:process";import{fileURLToPath as D,pathToFileURL as O}from"node:url";import{createHash as k,randomBytes as A,randomUUID as j}from"node:crypto";import{Readable as M}from"node:stream";import{mkdir as N,readFile as P,rename as F,writeFile as I}from"node:fs/promises";import{DatabaseSync as ee}from"node:sqlite";import{brotliCompressSync as te,brotliDecompressSync as ne,constants as re}from"node:zlib";import{createReadStream as ie,existsSync as ae,statSync as oe}from"fs";import{join as se}from"path";import{execFileSync as ce,spawn as le,spawnSync as ue}from"node:child_process";import{pipeline as de}from"node:stream/promises";import{versions as fe}from"process";var pe=Object.create,me=Object.defineProperty,he=Object.getOwnPropertyDescriptor,ge=Object.getOwnPropertyNames,_e=Object.getPrototypeOf,ve=Object.prototype.hasOwnProperty,L=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ye=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ge(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ve.call(e,s)&&s!==n&&me(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=he(t,s))||r.enumerable});return e},be=(e,t,n)=>(n=e==null?{}:pe(_e(e)),ye(t||!e||!e.__esModule||!ve.call(e,`default`)?me(n,`default`,{value:e,enumerable:!0}):n,e)),R=e(import.meta.url),xe=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Se=e=>e instanceof xe?e:new xe(e.message,{cause:e}),Ce=global.Request,we=class extends Ce{constructor(e,t){typeof e==`object`&&Oe in e&&(e=e[Oe]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Te=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},Ee=Symbol(`wrapBodyStream`),De=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new we(t,a);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[Ee]){let e;a.body=new ReadableStream({async pull(t){try{e||=s.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=s.toWeb(r)}return new we(t,a)},Oe=Symbol(`getRequestCache`),ke=Symbol(`requestCache`),Ae=Symbol(`incomingKey`),je=Symbol(`urlKey`),Me=Symbol(`headersKey`),Ne=Symbol(`abortControllerKey`),Pe={get method(){return this[Ae].method||`GET`},get url(){return this[je]},get headers(){return this[Me]||=Te(this[Ae])},[Symbol(`getAbortController`)](){return this[Oe](),this[Ne]},[Oe](){return this[Ne]||=new AbortController,this[ke]||=De(this.method,this[je],this.headers,this[Ae],this[Ne])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(Pe,e,{get(){return this[Oe]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Pe,e,{value:function(){return this[Oe]()[e]()}})}),Object.defineProperty(Pe,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[ke]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Pe,we.prototype);var Fe=(e,t)=>{let n=Object.create(Pe);n[Ae]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof a)throw new xe(`Absolute URL for :path is not allowed in HTTP/2`);try{n[je]=new URL(r).href}catch(e){throw new xe(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof a?e.authority:e.headers.host)||t;if(!i)throw new xe(`Missing host header`);let o;if(e instanceof a){if(o=e.scheme,o!==`http`&&o!==`https`)throw new xe(`Unsupported scheme`)}else o=e.socket&&e.socket.encrypted?`https`:`http`;let s=new URL(`${o}://${i}${r}`);if(s.hostname.length!==i.length&&s.hostname!==i.replace(/:\d+$/,``))throw new xe(`Invalid host header`);return n[je]=s.href,n},Ie=Symbol(`responseCache`),Le=Symbol(`getResponseCache`),Re=Symbol(`cache`),ze=global.Response,Be=class e{#e;#t;[Le](){return delete this[Re],this[Ie]||=new ze(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[Ie];if(e){this.#t=e,this[Le]();return}this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[Re]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[Re];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[Le]().headers}get status(){return this[Re]?.[0]??this[Le]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Be.prototype,e,{get(){return this[Le]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Be.prototype,e,{value:function(){return this[Le]()[e]()}})}),Object.defineProperty(Be.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Ie]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Be,ze),Object.setPrototypeOf(Be.prototype,ze.prototype);async function Ve(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function He(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function Ue(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);if(!t.destroyed)return He(e.getReader(),t)}var We=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,i]of e)r===`set-cookie`?n.push(i):t[r]=i;return n.length>0&&(t[`set-cookie`]=n),t[`content-type`]??=`text/plain; charset=UTF-8`,t},Ge=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=c);var Ke=Symbol(`outgoingEnded`),qe=Symbol(`incomingDraining`),Je=500,Ye=67108864,Xe=e=>{let t=e;if(e.destroyed||t[qe])return;if(t[qe]=!0,e instanceof a){try{e.stream?.close?.(o.NGHTTP2_NO_ERROR)}catch{}return}let n=0,r=()=>{clearTimeout(s),e.off(`data`,c),e.off(`end`,r),e.off(`error`,r)},i=()=>{r();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},s=setTimeout(i,Je);s.unref?.();let c=e=>{n+=e.length,n>Ye&&i()};e.on(`data`,c),e.on(`end`,r),e.on(`error`,r),e.resume()},Ze=()=>new Response(null,{status:400}),Qe=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),$e=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},et=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},tt=async(e,t)=>{let[n,r,i]=e[Re],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=We(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=We(e)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(et(t),await Ue(r,t)?.catch(e=>$e(e,t))),t[Ke]?.()},nt=e=>typeof e.then==`function`,rt=async(e,t,n={})=>{if(nt(e)){if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(Qe)}if(Re in e)return tt(e,t);let r=We(e.headers);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await Ve(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&et(t),await He(n,t,o))}else r[Ge]||(t.writeHead(e.status,r),t.end());t[Ke]?.()},it=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==we&&(Object.defineProperty(global,"Request",{value:we}),Object.defineProperty(global,"Response",{value:Be})),async(r,i)=>{let o,s;try{s=Fe(r,t.hostname);let c=!n||r.method===`GET`||r.method===`HEAD`;if(c||(r[Ee]=!0,r.on(`end`,()=>{c=!0}),r instanceof a&&(i[Ke]=()=>{c||setTimeout(()=>{c||setTimeout(()=>{Xe(r)})})}),i.on(`finish`,()=>{c||Xe(r)})),i.on(`close`,()=>{s[Ne]&&(r.errored?s[Ne].abort(r.errored.toString()):i.writableFinished||s[Ne].abort(`Client connection prematurely closed.`)),c||setTimeout(()=>{c||setTimeout(()=>{Xe(r)})})}),o=e(s,{incoming:r,outgoing:i}),Re in o)return tt(o,i)}catch(e){if(o)return $e(e,i);if(t.errorHandler){if(o=await t.errorHandler(s?e:Se(e)),!o)return}else o=s?Qe(e):Ze()}try{return await rt(o,i,t)}catch(e){return $e(e,i)}}},at=e=>{let t=e.fetch,n=it(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||i)(e.serverOptions||{},n)},ot=(e,t)=>{let n=at(e);return n.listen(e?.port??3e3,e.hostname,()=>{let e=n.address();t&&t(e)}),n};function st(e){if(e===void 0)return;let t=e.trim();return t===``?void 0:t}function ct(e){return st(process.env[e])}function lt(e){let t=st(e);if(t===void 0)return;let n=Number(t);return Number.isInteger(n)&&n>0?n:void 0}var ut={APP_DIR:ct(`ELLM_APP_DIR`),PORT:lt(ct(`ELLM_PORT`))};function z(e,...t){console.log(e,...t)}function dt(e,...t){console.warn(e,...t)}function B(e,...t){console.error(e,...t)}var ft=C(D(import.meta.url)),pt;function mt(){return w(t(),`.ezllm`)}function ht(){return pt===void 0&&(pt=T(E(),ut.APP_DIR??mt())),pt}function gt(){return T(ht(),`data`)}function _t(){return T(ht(),`ezllm.config.json`)}function vt(){return T(gt(),`ipinfo.json`)}function yt(){return T(gt(),`updater.json`)}var bt=[`hook.cjs`,`hook.mjs`,`hook.js`];function xt(){return bt.map(e=>w(ht(),e))}function St(){return T(ht(),`node`)}function Ct(e){return e.find(e=>d(e))}function wt(){let e=St(),t=[w(e,`node_modules`,`ezllm`),w(e,`lib`,`node_modules`,`ezllm`)];return Ct(t)??t[0]}function Tt(e){try{return JSON.parse(p(w(e,`package.json`),`utf-8`))}catch{return null}}function Et(e,t){let n=ft;for(let r=0;r<t;r++){if(Tt(n)?.name===e)return n;n=C(n)}return null}var Dt=Et(`ezllm`,5)??T(ft,`..`),Ot=Et(`ellm`,6);function kt(){return Tt(Dt)?.name===`ezllm`}function At(){let e=Tt(Dt);return e?.name===`ezllm`?e.version??`0.0.0`:`0.0.0`}function jt(){let e=gt();d(e)||f(e,{recursive:!0})}function Mt(e){return Ct([T(wt(),`dist`,e),w(Dt,`dist`,e),...Ot?[w(Ot,`app`,`cli`,`dist`,e)]:[]])??w(Dt,`dist`,e)}function Nt(){return Mt(`daemon.js`)}function Pt(e,t){let n=`${e}.${`${process.pid}.${A(6).toString(`hex`)}`}.tmp`;try{b(n,JSON.stringify(t,null,2)+`
|
|
3
|
-
`,`utf-8`),h(n,e)}finally{try{g(n,{force:!0})}catch{}}}function Ft(e){return e instanceof Error?e.message:String(e)}function It(e){jt();let t=T(gt(),e),n=()=>{if(!d(t))return null;try{return JSON.parse(p(t,`utf-8`))}catch(e){return B(`[store] 读取 ${t} 失败,按空数据处理(原内容将在下次写入时被覆盖):`,Ft(e)),null}},r=null,i=()=>(r===null&&(r=n()??{}),r),a=Promise.resolve(),o=()=>{a=a.then(()=>{Pt(t,{...i()})}).catch(e=>{B(`[store] 写入 ${t} 失败:`,Ft(e))})};return{get(e){return i()[e]},set(e,t){i()[e]=t,o()},getAll(){return{...i()}},setAll(e){r={...e},o()},filePath:t,flush(){return a}}}function Lt(){try{let e=JSON.parse(p(yt(),`utf-8`));return typeof e!=`object`||!e||Array.isArray(e)?{}:e}catch{return{}}}function Rt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:null}function zt(e,t){return Rt(typeof e==`function`?e():e)??t}function Bt(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}function Vt(e){let t=e.now??Date.now,n=e.log??z,r=e.maxArmMs??6e4,i=e.onError??((e,t,r)=>{n(`[scheduler] 作业 ${e.name} 失败(${String(Math.round(r/6e4))} 分钟后重试):${t.message}`)}),a=e.jobs.map(e=>({job:e,nextAt:t()+(e.firstDelayMs??zt(e.everyMs,r)),running:!1})),o=null,s=!1;function c(){if(s||o!==null)return;let e=t(),n=1/0;for(let t of a){if(t.running)continue;let r=Math.max(0,t.nextAt-e);r<n&&(n=r)}Number.isFinite(n)&&(o=setTimeout(l,Math.min(n,r)),o.unref())}function l(){if(o=null,s)return;let e=t();for(let t of a)!t.running&&e>=t.nextAt&&d(t);c()}function u(e,n,a){e.running=!1;let o=zt(e.job.retryMs??e.job.everyMs,r),s=n??zt(e.job.everyMs,r);e.nextAt=t()+(a===null?s:o),a!==null&&i(e.job,a,o),c()}function d(e){e.running=!0;let t;try{t=e.job.run({log:n})}catch(t){u(e,null,t instanceof Error?t:Error(String(t)));return}if(!Bt(t)){u(e,Rt(t),null);return}t.then(t=>{u(e,Rt(t),null)},t=>{u(e,null,t instanceof Error?t:Error(String(t)))})}return c(),{stop(){s=!0,o!==null&&(clearTimeout(o),o=null)}}}var Ht=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},Ut=Symbol(),Wt=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),Gt=32,Kt=1e4,qt=e=>`headers`in e,Jt=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(qt(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?Yt(e,{all:n,dot:r}):{}};async function Yt(e,t){if(!qt(e)&&e.bodyCache.formData)return Xt(await e.bodyCache.formData,t);let n=qt(e)?e.headers:e.raw.headers,r=Wt(await e.arrayBuffer(),n.get(`Content-Type`)||``);qt(e)||(e.bodyCache.formData=r);let i=await r;return i?Xt(i,t):{}}function Xt(e,t){let n=Object.create(null),r={count:0};return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?Zt(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(Qt(n,e,t,r),delete n[e])}),n}var Zt=(e,t,n)=>{e[t]===void 0?e[t]=t.endsWith(`[]`)?[n]:n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},Qt=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,a=t.split(`.`,Gt+2);a.length>Gt+1&&$t(),a.forEach((e,t)=>{t===a.length-1?i[e]=n:((!i[e]||typeof i[e]!=`object`||Array.isArray(i[e])||i[e]instanceof File)&&(r.count++>=Kt&&$t(),i[e]=Object.create(null)),i=i[e])})},$t=()=>{throw Error(`Nesting limit exceeded`)},en=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},tn=e=>{let{groups:t,path:n}=nn(e);return rn(en(n),t)},nn=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},rn=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},an={},on=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return an[r]||(an[r]=n[2]?t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:[e,n[1],!0]),an[r]}return null},sn=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},cn=e=>sn(e,decodeURI),ln=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.indexOf(`#`,r),a=e===-1?i===-1?void 0:i:i===-1?e:Math.min(e,i),o=t.slice(n,a);return cn(o.includes(`%25`)?o.replace(/%25/g,`%2525`):o)}if(e===63||e===35)break}return t.slice(n,r)},un=e=>{let t=ln(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},dn=(e,t,...n)=>(n.length&&(t=dn(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),fn=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e)){if(e.charCodeAt(e.length-1)===63){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.slice(0,-1);r+=`/`+t,n.push(r)}else r+=`/`+e}}),n.filter((e,t,n)=>n.indexOf(e)===t)},pn=e=>e.indexOf(`%`)===-1?e:sn(e,vn),mn=e=>(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),pn(e)),hn=(e,t,n)=>{let r=e.indexOf(`#`,8);r!==-1&&(e=e.slice(0,r));let i;if(!n&&t&&t.indexOf(`%`)===-1&&t.indexOf(`+`)===-1){let n=e.indexOf(`?`,8);if(n===-1)return;for(e.startsWith(t,n+1)||(n=e.indexOf(`&${t}`,n+1));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return mn(e.slice(r,i===-1?void 0:i))}if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(i=/[%+]/.test(e),!i)return}let a=Object.create(null);i??=/[%+]/.test(e);let o=e.indexOf(`?`,8);for(;o!==-1;){let t=e.indexOf(`&`,o+1),r=e.indexOf(`=`,o);r>t&&t!==-1&&(r=-1);let s=e.slice(o+1,r===-1?t===-1?void 0:t:r);if(i&&(s=mn(s)),o=t,s===``)continue;let c;r===-1?c=``:(c=e.slice(r+1,t===-1?void 0:t),i&&(c=mn(c))),n?(a[s]&&Array.isArray(a[s])||(a[s]=[]),a[s].push(c)):a[s]??=c}return t?a[t]:a},gn=hn,_n=(e,t)=>hn(e,t,!0),vn=decodeURIComponent,yn=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#r()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#i(t);return n&&pn(n)}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=pn(t))}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return gn(this.url,e)}queries(e){return _n(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return Jt(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let n in t)return t[n].then(t=>(n===`json`&&(t=JSON.stringify(t)),new Response(t)[e]()));return t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`formData`)}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ut](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},bn={Stringify:1,BeforeStream:2,Stream:3},xn=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},Sn=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>Sn(e,t,!1,r,i))).then(()=>i[0]));return n?xn(await o,a):o},Cn=`text/plain; charset=UTF-8`,wn=(e,t)=>({"Content-Type":e,...t}),Tn=(e,t)=>new Response(e,t),En=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new yn(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=Tn(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=Tn(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`){if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=Tn(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l;if(typeof t==`object`&&t.headers){r??=new Headers;for(let[e,n]of new Headers(t.headers))e===`set-cookie`?r.append(e,n):r.set(e,n)}if(n){if(!r){let e=0;for(let t in n)if(++e>1||typeof n[t]!=`string`){r=new Headers;break}}if(r)for(let e in n){let t=n[e];if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}}}return Tn(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r??n})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,wn(Cn,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,wn(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,wn(`text/html; charset=UTF-8`,n));return typeof e==`object`?Sn(e,bn.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>Tn(),this.#c(this))},Dn=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],On=`Can not add a route since the matcher is already built.`,kn=class extends Error{},An=`__COMPOSED_HANDLER`,jn=e=>e.text(`404 Not Found`,404),Mn=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},Nn=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...Dn,`all`].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#e=t:this.#r(e,this.#e,t),n.forEach(t=>{this.#r(e,this.#e,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat())n.map(e=>{this.#r(t.toUpperCase(),this.#e,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??ln:un}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=jn;errorHandler=Mn;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Mn?r=e.handler:(r=async(n,r)=>(await Ht([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[An]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=dn(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=dn(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})(),this.#r(`ALL`,dn(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#r(e,t,n,r){e=e.toUpperCase(),t=dn(this._basePath,t);let i={basePath:r===void 0?this._basePath:dn(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new En(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#n(o)})}catch(e){return this.#i(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#n(o))).catch(e=>this.#i(e,o)):e??this.#n(o)}let s=Ht(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,o)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${dn(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},Pn=()=>Object.create(null),Fn=[];function In(e,t){let n=this.buildAllMatchers(),r=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],Fn];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var Ln=`[^/]+`,Rn=`(?:|/.*)`,zn=Symbol(),Bn=new Set(`.\\+*[^]$()`);function Vn(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===`.*`||e===`(?:|/.*)`?t===`(?:|/.*)`?-1:1:t===`.*`||t===`(?:|/.*)`?-1:e===`[^/]+`?1:t===`[^/]+`?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Hn=class e{#e;#t;#n=Pn();insert(t,n,r,i,a){let o=this;for(let n=0,a=t.length;n<a;n++){let s=t[n],c=s.length===1?s===`*`?n===a-1?[``,``,`.*`]:[``,``,Ln]:null:s===`/*`?[``,``,Rn]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let t=c[1],n=c[2]||`[^/]+`;if(t&&c[2]&&(n===`.*`||(n=n.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(n))||n.length===1&&Bn.has(n)))throw zn;if(l=o.#n[n],!l){if(n!==`.*`&&n!==`(?:|/.*)`){for(let e in o.#n)if((n.length>1||e.length>1)&&e!==`.*`&&e!==`(?:|/.*)`)throw zn}l=o.#n[n]=new e}t!==``&&(l.#t??=i.varIndex++,r.push([t,l.#t]))}else if(l=o.#n[s],!l){for(let e in o.#n)if(e.length>1&&e!==`.*`&&e!==`(?:|/.*)`)throw zn;l=o.#n[s]=new e}o=l}if(o.#e!==void 0)throw zn;o.#e=a?-1:n}buildRegExpStr(){let e=Object.keys(this.#n).sort(Vn).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Bn.has(e)?`\\${e}`:e)+n}).filter(Boolean);return typeof this.#e==`number`&&this.#e!==-1&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},Un=class{#e={varIndex:0};#t=new Hn;#n=0;paths=Pn();insert(e,t){if(t){this.#t.insert(e.split(``),0,[],this.#e,!0);return}let n=[],r=[],i=e;for(let e=0;;){let t=!1;if(i=i.replace(/\{[^}]+\}/g,n=>{let i=`@\\${e}`;return r[e]=[i,n],e++,t=!0,i}),!t)break}let a=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=r.length-1;e>=0;e--){let[t]=r[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,r[e][1]);break}}this.#t.insert(a,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},Wn=Pn();function Gn(e){return Wn[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?Rn:e===`*`?`.*`:`/:${Ln}`)}$`)}function Kn(e,t){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(Gn(n).test(t))return[...e[n]]}var qn=class{name=`RegExpRouter`;#e;#t;#n;constructor(){this.#e={ALL:Pn()},this.#t={ALL:Pn()},this.#n={ALL:new Un}}#r(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===zn?new kn(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(On);if(!r[e]){this.#n[e]=new Un;for(let t of[r,i]){t[e]=Pn();for(let n in t.ALL)t[e][n]=[...t.ALL[n]],this.#r(e,n)}}t===`/*`&&(t=`*`);let a=e===`ALL`?Object.keys(r):[e];if(/\*$/.test(t)){let e=Gn(t);for(let e of a)r[e][t]||(this.#r(e,t),r[e][t]=Kn(r[e],t)||Kn(r.ALL,t)||[]);for(let o of[r,i])for(let r of a)for(let i in o[r])e.test(i)&&o[r][i].push([n,t]);return}let o=fn(t)||[t];for(let e of o)for(let t of a)i[t][e]||(this.#r(t,e),i[t][e]=Kn(r[t],e)||Kn(r.ALL,e)||[]),i[t][e].push([n,e])}match=In;buildAllMatchers(){let e=Pn();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,Wn=Pn(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=Pn(),a=[],[o,s,c]=r.buildRegExp();for(let e of[t,n])for(let t in e){let n=e[t],o=r.paths[t];if(!o){i[t]=[n.map(([e])=>[e,Pn()]),Fn];continue}a[o[0]]=n.map(([e,t])=>[e,r.paths[t][1].reduceRight((e,[t],n)=>(e[t]=c[o[1][n][1]],e),Pn())])}return[o,s.map(e=>a[e]),i]}},Jn=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(On);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof kn)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},Yn=Pn(),Xn=0,Zn=class e{#e=[];#t=Pn();#n=[];#r;#i=Yn;insert(t,n,r){let i=this,a=tn(n),o=new Set,s=0;for(let t of a){let n=a[++s],r=on(t,n)||(n===void 0&&t&&t.indexOf(`*`)===t.length-1?t:null),c=Array.isArray(r),l=c?r[0]:r||t,u=i.#t[l]||=new e;r&&!u.#r&&(u.#r=r,i.#n.push(u)),i=u,c&&o.add(r[1])}i.#e.push({[t]:{handler:r,possibleKeys:[...o],score:++Xn}})}#a(e,t,n,r,i){for(let a=0,o=t.#e.length;a<o;a++){let o=t.#e[a],s=o[n]||o.ALL;if(s){s.params=Pn(),e.push(s);for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e];s.params[t]=i?.[t]&&!e?i[t]:r[t]??i?.[t]}}}}search(e,t){let n=[];this.#i=Yn;let r=[this],i=en(t),a=[],o=i.length,s=null;for(let c=0;c<o;c++){let l=i[c],u=c===o-1,d=[];for(let f=0,p=r.length;f<p;f++){let p=r[f],m=p.#t[l];m&&(m.#i=p.#i,u?(m.#t[`*`]&&this.#a(n,m.#t[`*`],e,p.#i),this.#a(n,m,e,p.#i)):d.push(m));for(let r of p.#n){let f=r.#r,m=p.#i===Yn?{}:{...p.#i};if(typeof f==`string`){(f===`*`||l.startsWith(f.slice(0,-1)))&&(this.#a(n,r,e,p.#i),f===`*`&&(r.#i=m,d.push(r)));continue}let[,h,g]=f;if(l||g!==!0){if(g!==!0){if(!s){s=[];let e=+(t[0]===`/`);for(let t=0;t<o;t++)s[t]=e,e+=i[t].length+1}let l=t.slice(s[c]),u=g.exec(l);if(u){m[h]=u[0],this.#a(n,r,e,p.#i,m),u[0].length===l.length&&r.#t[`*`]&&this.#a(n,r.#t[`*`],e,p.#i,m);for(let e in r.#t){r.#i=m;let e=u[0].match(/\//g)?.length??0;(a[e]||=[]).push(r);break}continue}}(g===!0||g.test(l))&&(m[h]=l,u?(this.#a(n,r,e,m,p.#i),r.#t[`*`]&&this.#a(n,r.#t[`*`],e,m,p.#i)):(r.#i=m,d.push(r)))}}}let f=a.shift();r=f?d.concat(f):d}return n[1]&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},Qn=class{name=`TrieRouter`;#e=new Zn;add(e,t,n){for(let r of fn(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}},$n=class extends Nn{constructor(e={}){super(e),this.router=e.router??new Jn({routers:[new qn,new Qn]})}},er=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function tr(e){return{error:{message:`The model \`${e}\` does not exist or you do not have access to it.`,type:`invalid_request_error`,code:`model_not_found`}}}function nr(e){return{byName:new Map(e.map(e=>[e.name,e])),names:e.map(e=>e.name)}}function rr(e,t){return typeof t!=`string`||t===``?null:e.byName.get(t)??null}function V(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ir(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function ar(e){return e instanceof Error?e.message:String(e)}function or(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}var sr=[`openai`,`anthropic`,`openai-responses`],cr=class extends Error{issues;constructor(e){super(`配置校验失败:\n - ${e.join(`
|
|
4
|
-
- `)}`),this.name=`ConfigValidationError`,this.issues=e}};function
|
|
5
|
-
`)===-1&&e.indexOf(`\r`)===-1){if(c<
|
|
6
|
-
`),r=t===-1?n:n===-1||t<n?t:n;return r===-1?``:r===e.length-1&&e.charCodeAt(r)===
|
|
2
|
+
import{createRequire as e}from"node:module";import{homedir as t,networkInterfaces as n,platform as r}from"node:os";import{createServer as i}from"http";import{Http2ServerRequest as a,constants as o}from"http2";import{Readable as s}from"stream";import c from"crypto";import{closeSync as l,copyFileSync as u,createWriteStream as d,existsSync as f,mkdirSync as p,openSync as m,readFileSync as h,readdirSync as g,renameSync as _,rmSync as v,rmdirSync as y,statSync as b,unlinkSync as x,writeFileSync as S}from"node:fs";import{basename as C,delimiter as w,dirname as T,join as E,resolve as D,sep as O}from"node:path";import{cwd as k}from"node:process";import{fileURLToPath as A,pathToFileURL as j}from"node:url";import{createHash as M,randomBytes as N,randomUUID as P}from"node:crypto";import{Readable as F}from"node:stream";import{mkdir as ee,readFile as te,rename as ne,writeFile as re}from"node:fs/promises";import{DatabaseSync as ie}from"node:sqlite";import{brotliCompressSync as ae,brotliDecompressSync as oe,constants as se}from"node:zlib";import{createReadStream as ce,existsSync as le,statSync as ue}from"fs";import{join as de}from"path";import{execFileSync as fe,spawn as pe,spawnSync as me}from"node:child_process";import{pipeline as he}from"node:stream/promises";import{versions as ge}from"process";var _e=Object.create,ve=Object.defineProperty,ye=Object.getOwnPropertyDescriptor,be=Object.getOwnPropertyNames,xe=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty,I=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ce=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=be(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Se.call(e,s)&&s!==n&&ve(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ye(t,s))||r.enumerable});return e},we=(e,t,n)=>(n=e==null?{}:_e(xe(e)),Ce(t||!e||!e.__esModule||!Se.call(e,`default`)?ve(n,`default`,{value:e,enumerable:!0}):n,e)),Te=e(import.meta.url),Ee=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},De=e=>e instanceof Ee?e:new Ee(e.message,{cause:e}),Oe=global.Request,ke=class extends Oe{constructor(e,t){typeof e==`object`&&Ne in e&&(e=e[Ne]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Ae=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},je=Symbol(`wrapBodyStream`),Me=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new ke(t,a);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[je]){let e;a.body=new ReadableStream({async pull(t){try{e||=s.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=s.toWeb(r)}return new ke(t,a)},Ne=Symbol(`getRequestCache`),Pe=Symbol(`requestCache`),Fe=Symbol(`incomingKey`),Ie=Symbol(`urlKey`),Le=Symbol(`headersKey`),Re=Symbol(`abortControllerKey`),ze={get method(){return this[Fe].method||`GET`},get url(){return this[Ie]},get headers(){return this[Le]||=Ae(this[Fe])},[Symbol(`getAbortController`)](){return this[Ne](),this[Re]},[Ne](){return this[Re]||=new AbortController,this[Pe]||=Me(this.method,this[Ie],this.headers,this[Fe],this[Re])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(ze,e,{get(){return this[Ne]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(ze,e,{value:function(){return this[Ne]()[e]()}})}),Object.defineProperty(ze,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[Pe]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(ze,ke.prototype);var Be=(e,t)=>{let n=Object.create(ze);n[Fe]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof a)throw new Ee(`Absolute URL for :path is not allowed in HTTP/2`);try{n[Ie]=new URL(r).href}catch(e){throw new Ee(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof a?e.authority:e.headers.host)||t;if(!i)throw new Ee(`Missing host header`);let o;if(e instanceof a){if(o=e.scheme,o!==`http`&&o!==`https`)throw new Ee(`Unsupported scheme`)}else o=e.socket&&e.socket.encrypted?`https`:`http`;let s=new URL(`${o}://${i}${r}`);if(s.hostname.length!==i.length&&s.hostname!==i.replace(/:\d+$/,``))throw new Ee(`Invalid host header`);return n[Ie]=s.href,n},Ve=Symbol(`responseCache`),He=Symbol(`getResponseCache`),Ue=Symbol(`cache`),We=global.Response,Ge=class e{#e;#t;[He](){return delete this[Ue],this[Ve]||=new We(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[Ve];if(e){this.#t=e,this[He]();return}this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[Ue]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[Ue];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[He]().headers}get status(){return this[Ue]?.[0]??this[He]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Ge.prototype,e,{get(){return this[He]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Ge.prototype,e,{value:function(){return this[He]()[e]()}})}),Object.defineProperty(Ge.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[Ve]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Ge,We),Object.setPrototypeOf(Ge.prototype,We.prototype);async function Ke(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function qe(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function Je(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);if(!t.destroyed)return qe(e.getReader(),t)}var Ye=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,i]of e)r===`set-cookie`?n.push(i):t[r]=i;return n.length>0&&(t[`set-cookie`]=n),t[`content-type`]??=`text/plain; charset=UTF-8`,t},Xe=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=c);var Ze=Symbol(`outgoingEnded`),Qe=Symbol(`incomingDraining`),$e=500,et=67108864,tt=e=>{let t=e;if(e.destroyed||t[Qe])return;if(t[Qe]=!0,e instanceof a){try{e.stream?.close?.(o.NGHTTP2_NO_ERROR)}catch{}return}let n=0,r=()=>{clearTimeout(s),e.off(`data`,c),e.off(`end`,r),e.off(`error`,r)},i=()=>{r();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},s=setTimeout(i,$e);s.unref?.();let c=e=>{n+=e.length,n>et&&i()};e.on(`data`,c),e.on(`end`,r),e.on(`error`,r),e.resume()},nt=()=>new Response(null,{status:400}),rt=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),it=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},at=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},ot=async(e,t)=>{let[n,r,i]=e[Ue],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=Ye(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=Ye(e)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(at(t),await Je(r,t)?.catch(e=>it(e,t))),t[Ze]?.()},st=e=>typeof e.then==`function`,ct=async(e,t,n={})=>{if(st(e)){if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(rt)}if(Ue in e)return ot(e,t);let r=Ye(e.headers);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await Ke(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&at(t),await qe(n,t,o))}else r[Xe]||(t.writeHead(e.status,r),t.end());t[Ze]?.()},lt=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==ke&&(Object.defineProperty(global,"Request",{value:ke}),Object.defineProperty(global,"Response",{value:Ge})),async(r,i)=>{let o,s;try{s=Be(r,t.hostname);let c=!n||r.method===`GET`||r.method===`HEAD`;if(c||(r[je]=!0,r.on(`end`,()=>{c=!0}),r instanceof a&&(i[Ze]=()=>{c||setTimeout(()=>{c||setTimeout(()=>{tt(r)})})}),i.on(`finish`,()=>{c||tt(r)})),i.on(`close`,()=>{s[Re]&&(r.errored?s[Re].abort(r.errored.toString()):i.writableFinished||s[Re].abort(`Client connection prematurely closed.`)),c||setTimeout(()=>{c||setTimeout(()=>{tt(r)})})}),o=e(s,{incoming:r,outgoing:i}),Ue in o)return ot(o,i)}catch(e){if(o)return it(e,i);if(t.errorHandler){if(o=await t.errorHandler(s?e:De(e)),!o)return}else o=s?rt(e):nt()}try{return await ct(o,i,t)}catch(e){return it(e,i)}}},ut=e=>{let t=e.fetch,n=lt(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||i)(e.serverOptions||{},n)},dt=(e,t)=>{let n=ut(e);return n.listen(e?.port??3e3,e.hostname,()=>{let e=n.address();t&&t(e)}),n};function ft(e){if(e===void 0)return;let t=e.trim();return t===``?void 0:t}function pt(e){return ft(process.env[e])}function mt(e){let t=ft(e);if(t===void 0)return;let n=Number(t);return Number.isInteger(n)&&n>0?n:void 0}var ht={APP_DIR:pt(`ELLM_APP_DIR`),PORT:mt(pt(`ELLM_PORT`)),NODE_MIRROR:pt(`ELLM_NODE_MIRROR`),NODE_BIN:pt(`ELLM_NODE_BIN`)};function L(e,...t){console.log(e,...t)}function gt(e,...t){console.warn(e,...t)}function R(e,...t){console.error(e,...t)}var _t=T(A(import.meta.url)),vt;function yt(){return vt===void 0&&(vt=D(k(),ht.APP_DIR??E(t(),`.ezllm`))),vt}function bt(){return D(yt(),`data`)}function xt(){return D(yt(),`ezllm.config.json`)}function St(){return D(bt(),`ipinfo.json`)}function Ct(){return D(yt(),`logs`)}function wt(){return D(bt(),`updater.json`)}var Tt=[`hook.cjs`,`hook.mjs`,`hook.js`];function Et(){return Tt.map(e=>E(yt(),e))}function Dt(){return D(yt(),`node`)}function Ot(e){return e.find(e=>f(e))}function kt(){let e=Dt(),t=[E(e,`node_modules`,`ezllm`),E(e,`lib`,`node_modules`,`ezllm`)];return Ot(t)??t[0]}function At(e){try{return JSON.parse(h(E(e,`package.json`),`utf-8`))}catch{return null}}function jt(e,t){let n=_t;for(let r=0;r<t;r++){if(At(n)?.name===e)return n;n=T(n)}return null}var Mt=jt(`ezllm`,5)??D(_t,`..`),Nt=jt(`ellm`,6);function Pt(){return At(Mt)?.name===`ezllm`}function Ft(){let e=At(Mt);return e?.name===`ezllm`?e.version??`0.0.0`:`0.0.0`}function It(){let e=bt();f(e)||p(e,{recursive:!0})}function Lt(e){return Ot([D(kt(),`dist`,e),E(Mt,`dist`,e),...Nt?[E(Nt,`app`,`cli`,`dist`,e)]:[]])??E(Mt,`dist`,e)}function Rt(){return Lt(`daemon.js`)}function zt(e,t){let n=`${e}.${`${process.pid}.${N(6).toString(`hex`)}`}.tmp`;try{S(n,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,`utf-8`),_(n,e)}finally{try{v(n,{force:!0})}catch{}}}function Bt(e){It();let t=D(bt(),e),n=e=>e instanceof Error?e.message:String(e),r=()=>{if(!f(t))return null;try{return JSON.parse(h(t,`utf-8`))}catch(e){return R(`[store] 读取 ${t} 失败,按空数据处理(原内容将在下次写入时被覆盖):`,n(e)),null}},i=null,a=()=>(i===null&&(i=r()??{}),i),o=Promise.resolve(),s=()=>{o=o.then(()=>{zt(t,{...a()})}).catch(e=>{R(`[store] 写入 ${t} 失败:`,n(e))})};return{get(e){return a()[e]},set(e,t){a()[e]=t,s()},getAll(){return{...a()}},setAll(e){i={...e},s()},filePath:t,flush(){return o}}}function Vt(){try{let e=JSON.parse(h(wt(),`utf-8`));return typeof e!=`object`||!e||Array.isArray(e)?{}:e}catch{return{}}}function Ht(e){let t=e.now??Date.now,n=e.log??L,r=e.maxArmMs??6e4,i=e.onError??((e,t,r)=>{n(`[scheduler] 作业 ${e.name} 失败(${String(Math.round(r/6e4))} 分钟后重试):${t.message}`)}),a=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?e:null,o=(e,t)=>a(typeof e==`function`?e():e)??t,s=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,c=e.jobs.map(e=>({job:e,nextAt:t()+(e.firstDelayMs??o(e.everyMs,r)),running:!1})),l=null,u=!1;function d(){if(u||l!==null)return;let e=t(),n=1/0;for(let t of c){if(t.running)continue;let r=Math.max(0,t.nextAt-e);r<n&&(n=r)}Number.isFinite(n)&&(l=setTimeout(f,Math.min(n,r)),l.unref())}function f(){if(l=null,u)return;let e=t();for(let t of c)!t.running&&e>=t.nextAt&&m(t);d()}function p(e,n,a){e.running=!1;let s=o(e.job.retryMs??e.job.everyMs,r),c=n??o(e.job.everyMs,r);e.nextAt=t()+(a===null?c:s),a!==null&&i(e.job,a,s),d()}function m(e){e.running=!0;let t;try{t=e.job.run({log:n})}catch(t){p(e,null,t instanceof Error?t:Error(String(t)));return}if(!s(t)){p(e,a(t),null);return}t.then(t=>{p(e,a(t),null)},t=>{p(e,null,t instanceof Error?t:Error(String(t)))})}return d(),{stop(){u=!0,l!==null&&(clearTimeout(l),l=null)}}}var Ut=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},Wt=Symbol(),Gt=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),Kt=32,qt=1e4,Jt=e=>`headers`in e,Yt=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(Jt(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?Xt(e,{all:n,dot:r}):{}};async function Xt(e,t){if(!Jt(e)&&e.bodyCache.formData)return Zt(await e.bodyCache.formData,t);let n=Jt(e)?e.headers:e.raw.headers,r=Gt(await e.arrayBuffer(),n.get(`Content-Type`)||``);Jt(e)||(e.bodyCache.formData=r);let i=await r;return i?Zt(i,t):{}}function Zt(e,t){let n=Object.create(null),r={count:0};return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?Qt(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&($t(n,e,t,r),delete n[e])}),n}var Qt=(e,t,n)=>{e[t]===void 0?e[t]=t.endsWith(`[]`)?[n]:n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},$t=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,a=t.split(`.`,Kt+2);a.length>Kt+1&&en(),a.forEach((e,t)=>{t===a.length-1?i[e]=n:((!i[e]||typeof i[e]!=`object`||Array.isArray(i[e])||i[e]instanceof File)&&(r.count++>=qt&&en(),i[e]=Object.create(null)),i=i[e])})},en=()=>{throw Error(`Nesting limit exceeded`)},tn=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},nn=e=>{let{groups:t,path:n}=rn(e);return an(tn(n),t)},rn=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},an=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},on={},sn=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return on[r]||(on[r]=n[2]?t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:[e,n[1],!0]),on[r]}return null},cn=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},ln=e=>cn(e,decodeURI),un=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.indexOf(`#`,r),a=e===-1?i===-1?void 0:i:i===-1?e:Math.min(e,i),o=t.slice(n,a);return ln(o.includes(`%25`)?o.replace(/%25/g,`%2525`):o)}if(e===63||e===35)break}return t.slice(n,r)},dn=e=>{let t=un(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},fn=(e,t,...n)=>(n.length&&(t=fn(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),pn=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e)){if(e.charCodeAt(e.length-1)===63){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.slice(0,-1);r+=`/`+t,n.push(r)}else r+=`/`+e}}),n.filter((e,t,n)=>n.indexOf(e)===t)},mn=e=>e.indexOf(`%`)===-1?e:cn(e,yn),hn=e=>(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),mn(e)),gn=(e,t,n)=>{let r=e.indexOf(`#`,8);r!==-1&&(e=e.slice(0,r));let i;if(!n&&t&&t.indexOf(`%`)===-1&&t.indexOf(`+`)===-1){let n=e.indexOf(`?`,8);if(n===-1)return;for(e.startsWith(t,n+1)||(n=e.indexOf(`&${t}`,n+1));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return hn(e.slice(r,i===-1?void 0:i))}if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(i=/[%+]/.test(e),!i)return}let a=Object.create(null);i??=/[%+]/.test(e);let o=e.indexOf(`?`,8);for(;o!==-1;){let t=e.indexOf(`&`,o+1),r=e.indexOf(`=`,o);r>t&&t!==-1&&(r=-1);let s=e.slice(o+1,r===-1?t===-1?void 0:t:r);if(i&&(s=hn(s)),o=t,s===``)continue;let c;r===-1?c=``:(c=e.slice(r+1,t===-1?void 0:t),i&&(c=hn(c))),n?(a[s]&&Array.isArray(a[s])||(a[s]=[]),a[s].push(c)):a[s]??=c}return t?a[t]:a},_n=gn,vn=(e,t)=>gn(e,t,!0),yn=decodeURIComponent,bn=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#t=n}param(e){return e?this.#n(e):this.#r()}#n(e){let t=this.#t[0][this.routeIndex]?.[1][e],n=this.#i(t);return n&&mn(n)}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex]?.[1]??{});for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=mn(t))}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return _n(this.url,e)}queries(e){return vn(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return Yt(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;for(let n in t)return t[n].then(t=>(n===`json`&&(t=JSON.stringify(t)),new Response(t)[e]()));return t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`formData`)}addValidatedData(e,t){(this.#e??={})[e]=t}valid(e){return this.#e?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Wt](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},xn={Stringify:1,BeforeStream:2,Stream:3},Sn=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},Cn=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>Cn(e,t,!1,r,i))).then(()=>i[0]));return n?Sn(await o,a):o},wn=`text/plain; charset=UTF-8`,Tn=(e,t)=>({"Content-Type":e,...t}),En=(e,t)=>new Response(e,t),Dn=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new bn(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=En(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=En(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`){if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=En(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l;if(typeof t==`object`&&t.headers){r??=new Headers;for(let[e,n]of new Headers(t.headers))e===`set-cookie`?r.append(e,n):r.set(e,n)}if(n){if(!r){let e=0;for(let t in n)if(++e>1||typeof n[t]!=`string`){r=new Headers;break}}if(r)for(let e in n){let t=n[e];if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}}}return En(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r??n})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,Tn(wn,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,Tn(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,Tn(`text/html; charset=UTF-8`,n));return typeof e==`object`?Cn(e,xn.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>En(),this.#c(this))},On=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],kn=`Can not add a route since the matcher is already built.`,An=class extends Error{},jn=`__COMPOSED_HANDLER`,Mn=e=>e.text(`404 Not Found`,404),Nn=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},Pn=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...On,`all`].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#e=t:this.#r(e,this.#e,t),n.forEach(t=>{this.#r(e,this.#e,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat())n.map(e=>{this.#r(t.toUpperCase(),this.#e,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??un:dn}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=Mn;errorHandler=Nn;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Nn?r=e.handler:(r=async(n,r)=>(await Ut([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[jn]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=fn(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=fn(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})(),this.#r(`ALL`,fn(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#r(e,t,n,r){e=e.toUpperCase(),t=fn(this._basePath,t);let i={basePath:r===void 0?this._basePath:fn(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new Dn(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#n(o)})}catch(e){return this.#i(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#n(o))).catch(e=>this.#i(e,o)):e??this.#n(o)}let s=Ut(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,o)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${fn(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},Fn=()=>Object.create(null),In=[];function Ln(e,t){let n=this.buildAllMatchers(),r=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],In];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var Rn=`[^/]+`,zn=`(?:|/.*)`,Bn=Symbol(),Vn=new Set(`.\\+*[^]$()`);function Hn(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===`.*`||e===`(?:|/.*)`?t===`(?:|/.*)`?-1:1:t===`.*`||t===`(?:|/.*)`?-1:e===`[^/]+`?1:t===`[^/]+`?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var Un=class e{#e;#t;#n=Fn();insert(t,n,r,i,a){let o=this;for(let n=0,a=t.length;n<a;n++){let s=t[n],c=s.length===1?s===`*`?n===a-1?[``,``,`.*`]:[``,``,Rn]:null:s===`/*`?[``,``,zn]:s.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let t=c[1],n=c[2]||`[^/]+`;if(t&&c[2]&&(n===`.*`||(n=n.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(n))||n.length===1&&Vn.has(n)))throw Bn;if(l=o.#n[n],!l){if(n!==`.*`&&n!==`(?:|/.*)`){for(let e in o.#n)if((n.length>1||e.length>1)&&e!==`.*`&&e!==`(?:|/.*)`)throw Bn}l=o.#n[n]=new e}t!==``&&(l.#t??=i.varIndex++,r.push([t,l.#t]))}else if(l=o.#n[s],!l){for(let e in o.#n)if(e.length>1&&e!==`.*`&&e!==`(?:|/.*)`)throw Bn;l=o.#n[s]=new e}o=l}if(o.#e!==void 0)throw Bn;o.#e=a?-1:n}buildRegExpStr(){let e=Object.keys(this.#n).sort(Hn).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Vn.has(e)?`\\${e}`:e)+n}).filter(Boolean);return typeof this.#e==`number`&&this.#e!==-1&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},Wn=class{#e={varIndex:0};#t=new Un;#n=0;paths=Fn();insert(e,t){if(t){this.#t.insert(e.split(``),0,[],this.#e,!0);return}let n=[],r=[],i=e;for(let e=0;;){let t=!1;if(i=i.replace(/\{[^}]+\}/g,n=>{let i=`@\\${e}`;return r[e]=[i,n],e++,t=!0,i}),!t)break}let a=i.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=r.length-1;e>=0;e--){let[t]=r[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,r[e][1]);break}}this.#t.insert(a,this.#n,n,this.#e,!1),this.paths[e]=[this.#n++,n]}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},Gn=Fn();function Kn(e){return Gn[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?zn:e===`*`?`.*`:`/:${Rn}`)}$`)}function qn(e,t){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(Kn(n).test(t))return[...e[n]]}var Jn=class{name=`RegExpRouter`;#e;#t;#n;constructor(){this.#e={ALL:Fn()},this.#t={ALL:Fn()},this.#n={ALL:new Wn}}#r(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===Bn?new An(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(kn);if(!r[e]){this.#n[e]=new Wn;for(let t of[r,i]){t[e]=Fn();for(let n in t.ALL)t[e][n]=[...t.ALL[n]],this.#r(e,n)}}t===`/*`&&(t=`*`);let a=e===`ALL`?Object.keys(r):[e];if(/\*$/.test(t)){let e=Kn(t);for(let e of a)r[e][t]||(this.#r(e,t),r[e][t]=qn(r[e],t)||qn(r.ALL,t)||[]);for(let o of[r,i])for(let r of a)for(let i in o[r])e.test(i)&&o[r][i].push([n,t]);return}let o=pn(t)||[t];for(let e of o)for(let t of a)i[t][e]||(this.#r(t,e),i[t][e]=qn(r[t],e)||qn(r.ALL,e)||[]),i[t][e].push([n,e])}match=Ln;buildAllMatchers(){let e=Fn();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,Gn=Fn(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=Fn(),a=[],[o,s,c]=r.buildRegExp();for(let e of[t,n])for(let t in e){let n=e[t],o=r.paths[t];if(!o){i[t]=[n.map(([e])=>[e,Fn()]),In];continue}a[o[0]]=n.map(([e,t])=>[e,r.paths[t][1].reduceRight((e,[t],n)=>(e[t]=c[o[1][n][1]],e),Fn())])}return[o,s.map(e=>a[e]),i]}},Yn=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(kn);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof An)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},Xn=Fn(),Zn=0,Qn=class e{#e=[];#t=Fn();#n=[];#r;#i=Xn;insert(t,n,r){let i=this,a=nn(n),o=new Set,s=0;for(let t of a){let n=a[++s],r=sn(t,n)||(n===void 0&&t&&t.indexOf(`*`)===t.length-1?t:null),c=Array.isArray(r),l=c?r[0]:r||t,u=i.#t[l]||=new e;r&&!u.#r&&(u.#r=r,i.#n.push(u)),i=u,c&&o.add(r[1])}i.#e.push({[t]:{handler:r,possibleKeys:[...o],score:++Zn}})}#a(e,t,n,r,i){for(let a=0,o=t.#e.length;a<o;a++){let o=t.#e[a],s=o[n]||o.ALL;if(s){s.params=Fn(),e.push(s);for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e];s.params[t]=i?.[t]&&!e?i[t]:r[t]??i?.[t]}}}}search(e,t){let n=[];this.#i=Xn;let r=[this],i=tn(t),a=[],o=i.length,s=null;for(let c=0;c<o;c++){let l=i[c],u=c===o-1,d=[];for(let f=0,p=r.length;f<p;f++){let p=r[f],m=p.#t[l];m&&(m.#i=p.#i,u?(m.#t[`*`]&&this.#a(n,m.#t[`*`],e,p.#i),this.#a(n,m,e,p.#i)):d.push(m));for(let r of p.#n){let f=r.#r,m=p.#i===Xn?{}:{...p.#i};if(typeof f==`string`){(f===`*`||l.startsWith(f.slice(0,-1)))&&(this.#a(n,r,e,p.#i),f===`*`&&(r.#i=m,d.push(r)));continue}let[,h,g]=f;if(l||g!==!0){if(g!==!0){if(!s){s=[];let e=+(t[0]===`/`);for(let t=0;t<o;t++)s[t]=e,e+=i[t].length+1}let l=t.slice(s[c]),u=g.exec(l);if(u){m[h]=u[0],this.#a(n,r,e,p.#i,m),u[0].length===l.length&&r.#t[`*`]&&this.#a(n,r.#t[`*`],e,p.#i,m);for(let e in r.#t){r.#i=m;let e=u[0].match(/\//g)?.length??0;(a[e]||=[]).push(r);break}continue}}(g===!0||g.test(l))&&(m[h]=l,u?(this.#a(n,r,e,m,p.#i),r.#t[`*`]&&this.#a(n,r.#t[`*`],e,m,p.#i)):(r.#i=m,d.push(r)))}}}let f=a.shift();r=f?d.concat(f):d}return n[1]&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},$n=class{name=`TrieRouter`;#e=new Qn;add(e,t,n){for(let r of pn(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}},er=class extends Pn{constructor(e={}){super(e),this.router=e.router??new Yn({routers:[new Jn,new $n]})}},tr=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function nr(e){return{error:{message:`The model \`${e}\` does not exist or you do not have access to it.`,type:`invalid_request_error`,code:`model_not_found`}}}function rr(e){return{byName:new Map(e.map(e=>[e.name,e])),names:e.map(e=>e.name)}}function ir(e,t){return typeof t!=`string`||t===``?null:e.byName.get(t)??null}function z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ar(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function or(e){return e instanceof Error?e.message:String(e)}function sr(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}var cr=[`openai`,`anthropic`,`openai-responses`],lr=class extends Error{issues;constructor(e){super(`配置校验失败:\n - ${e.join(`
|
|
4
|
+
- `)}`),this.name=`ConfigValidationError`,this.issues=e}};function ur(e){let t=(e,t,n,r)=>{e!==void 0&&typeof e!=`string`&&r.push(`${t}.${n} 必须是字符串,当前为 ${String(e)}`)},n=(e,t)=>{if(e===void 0)return[];if(!z(e))return[`${t}.headers 必须是键值均为字符串的对象`];let n=[];for(let[r,i]of Object.entries(e))typeof i!=`string`&&n.push(`${t}.headers["${r}"] 必须是字符串,当前为 ${String(i)}`);return n},r=(e,t)=>{let n={};for(let r of[e,t])if(z(r))for(let[e,t]of Object.entries(r))typeof t==`string`&&(n[e]=t);return n},i=[],a=[];if(typeof e!=`object`||!e||!Array.isArray(e.providers))throw new lr([`providers 必须是数组`]);e.providers.length===0&&i.push(`providers 不能为空(至少配置一个供应商)`),e.port!==void 0&&(!Number.isInteger(e.port)||e.port<1||e.port>65535)&&i.push(`port 必须是 1-65535 的整数,当前为 ${String(e.port)}`);let o=new Set,s=new Map,c=new Map,l=[];for(let[u,d]of e.providers.entries()){let e=d?.name??`providers[${String(u)}]`;typeof d?.name!=`string`||d.name===``?i.push(`providers[${String(u)}].name 必须是非空字符串`):o.has(d.name)?i.push(`供应商名重复:${d.name}`):o.add(d.name);let f=d?.enabled!==!1;if(d?.enabled!==void 0&&typeof d.enabled!=`boolean`&&i.push(`${e}.enabled 必须是布尔值,当前为 ${String(d.enabled)}`),d?.alias!==void 0){if(typeof d.alias!=`string`||d.alias.trim()===``)i.push(`${e}.alias 若设置必须是非空字符串`);else{let t=d.alias.trim();if(f){let n=s.get(t);n===void 0?s.set(t,e):i.push(`供应商别名 "${t}" 重复(${n} 与 ${e})`)}}}let p=d?.customLlmProvider,m=cr.includes(p);m||i.push(`${e}.customLlmProvider 必须是 "openai" | "anthropic" | "openai-responses" 之一,当前为 ${String(p)}`);let h=m?p:`openai`;if(!Array.isArray(d?.models)||d.models.length===0){i.push(`${e}.models 必须是非空数组(至少配置一个模型)`);continue}d?.autoV1!==void 0&&typeof d.autoV1!=`boolean`&&i.push(`${e}.autoV1 必须是布尔值,当前为 ${String(d.autoV1)}`),t(d?.apiKey,e,`apiKey`,i),t(d?.apiBase,e,`apiBase`,i),i.push(...n(d?.headers,e));for(let[o,s]of d.models.entries()){let u=`${e}.models[${String(o)}]`;if(typeof s?.modelName!=`string`||s.modelName===``){i.push(`${u}.modelName 必须是非空字符串`);continue}if(f){let t=c.get(s.modelName);t===void 0?c.set(s.modelName,e):i.push(`模型名 "${s.modelName}" 重复(${t} 与 ${e}):模型名必须全局唯一`)}if(typeof s?.model!=`string`||s.model===``){i.push(`${u}.model 必须是非空字符串`);continue}s.rawPassthrough!==void 0&&typeof s.rawPassthrough!=`boolean`&&i.push(`${u}.rawPassthrough 必须是布尔值,当前为 ${String(s.rawPassthrough)}`);let p=s.customLlmProvider===void 0?h:s.customLlmProvider;cr.includes(p)||i.push(`${u}.customLlmProvider 必须是 "openai" | "anthropic" | "openai-responses" 之一`),t(s.apiKey,u,`apiKey`,i),t(s.apiBase,u,`apiBase`,i),i.push(...n(s.headers,u));let m=dr(s.apiKey??d.apiKey,a,u),g=s.apiBase??d.apiBase,_=s.autoV1??d.autoV1;_!==void 0&&typeof _!=`boolean`&&i.push(`${u}.autoV1 必须是布尔值,当前为 ${String(_)}`);let v=r(d?.headers,s.headers),y=s.maxReasoningEffort??d.maxReasoningEffort;y!==void 0&&!tr.includes(y)&&i.push(`${u}.maxReasoningEffort 必须是 ${tr.join(` | `)} 之一,当前为 ${String(y)}`);let b=s.thinkingGuardMaxChars??d.thinkingGuardMaxChars;b!==void 0&&(!Number.isInteger(b)||b<0)&&i.push(`${u}.thinkingGuardMaxChars 必须是非负整数,当前为 ${String(b)}`),f&&l.push({name:s.modelName,provider:p,modelName:s.model,apiKey:m,apiBase:g,autoV1:_,headers:Object.keys(v).length>0?v:void 0,maxReasoningEffort:y,thinkingGuardMaxChars:b,rawPassthrough:s.rawPassthrough})}}if(i.length>0)throw new lr(i);return{deployments:rr(l),port:e.port??29770,warnings:a}}function dr(e,t,n){if(e===void 0||typeof e!=`string`)return;if(!e.startsWith(`os.environ/`))return e;let r=e.slice(11),i=process.env[r];if(i===void 0||i===``){t.push(`${n}:环境变量 "${r}" 为空或不存在`);return}return i}function fr(e){return{kind:`ok`,value:e}}function pr(e,t){return{kind:`error`,status:e,message:t}}var mr=class extends Error{status;constructor(e,t){super(e),this.name=`ProtocolError`,t?.status!==void 0&&(this.status=t.status)}};function hr(e){return e instanceof mr&&e.status!==void 0?e.status:void 0}function gr(e){return typeof e.then==`function`}function _r(e){return e instanceof Error?e.message:String(e)}var vr=class{#e;constructor(e){this.#e=e}run(e,t){let n=-1,r=(e,i)=>{if(e<=n)return pr(500,`next() called multiple times`);n=e;let a=this.#e[e];if(a===void 0)return t(i);let o;try{o=a(i,t=>r(e+1,t))}catch(e){return pr(500,_r(e))}return gr(o)?o.then(void 0,e=>pr(500,_r(e))):o};return r(0,e)}};function yr(e,t){return e===`anthropic`?[{type:`error`,error:{type:t.status===429||t.status===529?`overloaded_error`:t.status!==void 0&&t.status>=400&&t.status<500?`invalid_request_error`:`api_error`,message:t.message}}]:e===`openai-responses`?[{type:`error`,error:{type:`InternalServerError`,code:String(t.status??500),message:t.message}}]:[{object:`chat.completion.chunk`,choices:[],error:{message:t.message,code:t.status??null}}]}function br(e){return e===`openai`}var xr=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},Sr=10,Cr=13,wr=32,Tr=6;function Er(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{maxBufferSize:t,onComment:n,onError:r,onEvent:i,onId:a,onRetry:o}=e,s=[],c=0,l=!0,u,d=``,f=0,p,m=!1,h=!1,g=!1;function _(e){if(m)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,e.charCodeAt(0)===65279?e=e.slice(1):e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),(h||g)&&(e=v(e),!e))return;if(!s.length){let t=S(e);t!==``&&y(t),x();return}if(e.indexOf(`
|
|
5
|
+
`)===-1&&e.indexOf(`\r`)===-1){if(c<Tr&&!b(s.join(``)+e.slice(0,Tr-c))){s.length=0,c=0,h=!0;return}s.push(e),c+=e.length,x();return}s.push(e);let t=s.join(``);s.length=0,c=0,y(S(t)),x()}function v(e){if(e.length===0)return e;if(g)return g=!1,e.charCodeAt(0)===Sr?e.slice(1):e;let t=e.indexOf(`\r`),n=e.indexOf(`
|
|
6
|
+
`),r=t===-1?n:n===-1||t<n?t:n;return r===-1?``:r===e.length-1&&e.charCodeAt(r)===Cr?(h=!1,g=!0,``):(h=!1,e.slice(r+(e.charCodeAt(r)===Cr&&e.charCodeAt(r+1)===Sr?2:1)))}function y(e){if(e){if(e.charCodeAt(e.length-1)===Cr){C(e,0,e.length-1),g=!0;return}if(b(e)){s.push(e),c=e.length;return}h=!0}}function b(e){let t=e.charCodeAt(0);return t===58&&!!n||t===100&&kr(e,`data`)||t===101&&kr(e,`event`)||t===105&&kr(e,`id`)||t===114&&kr(e,`retry`)}function x(){t!==void 0&&(c+d.length<=t||(m=!0,s.length=0,c=0,u=void 0,d=``,f=0,p=void 0,h=!1,g=!1,r?.(new xr(`Buffered data exceeded max buffer size of ${t} characters`,{type:`max-buffer-size-exceeded`}))))}function S(e){let t=0;if(e.indexOf(`\r`)===-1){let n=e.indexOf(`
|
|
7
7
|
`,t);for(;n!==-1;){if(t===n){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0,t=n+1,n=e.indexOf(`
|
|
8
|
-
`,t);continue}let r=e.charCodeAt(t);if(
|
|
9
|
-
`,t);continue}d=f===0?o:`${d}\n${o}`,f++}else
|
|
8
|
+
`,t);continue}let r=e.charCodeAt(t);if(Dr(e,t,r)){let r=e.charCodeAt(t+5)===wr?t+6:t+5,o=e.slice(r,n);if(f===0&&e.charCodeAt(n+1)===Sr){u!==void 0&&a?.(u),i?.({id:u,event:p,data:o}),u=void 0,d=``,p=void 0,t=n+2,n=e.indexOf(`
|
|
9
|
+
`,t);continue}d=f===0?o:`${d}\n${o}`,f++}else Or(e,t,r)?p=e.slice(e.charCodeAt(t+6)===wr?t+7:t+6,n)||void 0:C(e,t,n);t=n+1,n=e.indexOf(`
|
|
10
10
|
`,t)}return e.slice(t)}for(;t<e.length;){let n=e.indexOf(`\r`,t),r=e.indexOf(`
|
|
11
|
-
`,t),i=-1;if(n!==-1&&r!==-1?i=n<r?n:r:n===-1?r!==-1&&(i=r):i=n===e.length-1?-1:n,i===-1)break;C(e,t,i),t=i+1,e.charCodeAt(t-1)===
|
|
11
|
+
`,t),i=-1;if(n!==-1&&r!==-1?i=n<r?n:r:n===-1?r!==-1&&(i=r):i=n===e.length-1?-1:n,i===-1)break;C(e,t,i),t=i+1,e.charCodeAt(t-1)===Cr&&e.charCodeAt(t)===Sr&&t++}return e.slice(t)}function C(e,t,r){if(t===r){T();return}let i=e.charCodeAt(t);if(Dr(e,t,i)){let n=e.charCodeAt(t+5)===wr?t+6:t+5,i=e.slice(n,r);d=f===0?i:`${d}\n${i}`,f++;return}if(Or(e,t,i)){p=e.slice(e.charCodeAt(t+6)===wr?t+7:t+6,r)||void 0;return}if(i===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let n=e.slice(e.charCodeAt(t+3)===wr?t+4:t+3,r);n.includes(`\0`)||(u=n);return}if(i===58){if(n){let i=e.slice(t,r);n(i.slice(e.charCodeAt(t+1)===wr?2:1))}return}let a=e.slice(t,r),o=a.indexOf(`:`);if(o===-1){w(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===wr?2:1;w(s,a.slice(o+c),a)}function w(e,t,n){switch(e){case`event`:p=t||void 0;break;case`data`:d=f===0?t:`${d}\n${t}`,f++;break;case`id`:t.includes(`\0`)||(u=t);break;case`retry`:/^\d+$/.test(t)?o?.(parseInt(t,10)):r?.(new xr(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:n}));break;default:r?.(new xr(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:`unknown-field`,field:e,value:t,line:n}))}}function T(){u!==void 0&&a?.(u),f>0&&i?.({id:u,event:p,data:d}),u=void 0,d=``,f=0,p=void 0}function E(e={}){if(e.consume&&s.length>0){let e=s.join(``);C(e,0,e.length)}l=!0,u=void 0,d=``,f=0,p=void 0,s.length=0,c=0,m=!1,h=!1,g=!1}return{feed:_,reset:E}}function Dr(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Or(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}function kr(e,t){let n=1;for(;n<e.length&&n<t.length;){if(e.charCodeAt(n)!==t.charCodeAt(n))return!1;n++}return e.length<=t.length||e.charCodeAt(t.length)===58}var Ar=`[DONE]`,jr=``,Mr=class{parser;collected=[];sawFirstChunk=!1;constructor(){this.parser=Er({onEvent:e=>{e.data!==``&&this.collected.push({event:e.event||null,data:e.data})}})}push(e){let t=e;return this.sawFirstChunk||(this.sawFirstChunk=!0,t.startsWith(jr)&&(t=t.slice(1))),this.parser.feed(t),this.take()}flush(){return this.parser.feed(`
|
|
12
12
|
|
|
13
|
-
`),this.take()}take(){let e=this.collected;return this.collected=[],e}},
|
|
14
|
-
`))n.push(`data: ${e}`);return
|
|
15
|
-
`)}\n\n`)}function Ir(e,t={}){let n=e.type;return Fr((t.protocol===void 0||t.protocol===`anthropic`)&&typeof n==`string`?n:null,JSON.stringify(e))}function Lr(){return Fr(null,jr)}async function*Rr(e,t){let n=e.getReader(),r=new TextDecoder,i=new Nr,a=!1;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;for(let e of i.push(r.decode(a,{stream:!0}))){let n=zr(e,t);if(yield n,n.done)return}}for(let e of i.push(r.decode())){let n=zr(e,t);if(yield n,n.done)return}for(let e of i.flush()){let n=zr(e,t);if(yield n,n.done)return}a=!0}finally{a||n.cancel().catch(()=>{})}}function zr(e,t){return{event:e.event,data:e.data,done:t!==`anthropic`&&e.data===`[DONE]`}}function Br(e){let t;try{t=JSON.parse(e.data)}catch{return null}return typeof t!=`object`||!t||Array.isArray(t)?null:t}function Vr(e,t){return Ir(e,{protocol:t})}function Hr(e,t){let n=[],r=[];if(e.request!==void 0){let r=e.request;n.push((e,n)=>r(e,n,t))}if(e.clientRequest!==void 0){let r=e.clientRequest;n.push((e,n)=>n(r(e,t)))}if(e.upstreamRequest!==void 0){let r=e.upstreamRequest;n.push((e,n)=>{let i=n(e);return _r(i)?i.then(a):a(i);function a(e){return e.kind===`error`?e:mr(r(e.value,t))}})}if(e.response!==void 0){let n=e.response;r.push((e,r)=>n(e,r,t))}if(e.upstreamResponse!==void 0){let n=e.upstreamResponse;r.push((e,r)=>{let i=e;return r({...i,body:Ur(i.body,n,t.pair.upstream,t)})})}if(e.clientResponse!==void 0){let n=e.clientResponse;r.push((e,r)=>{let i=r(e);return _r(i)?i.then(e=>Wr(e,n,t.pair.inbound,t)):Wr(i,n,t.pair.inbound,t)})}return{requestLayers:n,responseLayers:r}}function Ur(e,t,n,r){return e instanceof ReadableStream?e.pipeThrough(Gr(t,n,`upstream`,r)):e===null?null:t(e,r)}function Wr(e,t,n,r){if(e.kind===`error`)return e;let i=e.value;if(`stream`in i)return mr({...i,stream:i.stream.pipeThrough(Gr(t,n,`client`,r))});if(i.body===null||typeof i.body!=`object`)return e;let a=t(i.body,r);return mr(a===null?{...i,body:null}:{...i,body:a})}function Gr(e,t,n,r){let i=new Nr,a=new TextDecoder,o=!1,s=(i,a)=>{if(t!==`anthropic`&&i.data===`[DONE]`){a.enqueue(Lr());return}let s=Br({event:i.event,data:i.data,done:!1});if(s===null){a.enqueue(Fr(i.event,i.data));return}let c;try{c=e(s,r)}catch(e){if(o=!0,n===`upstream`){a.error(e);return}for(let n of br(t,{message:vr(e)}))a.enqueue(Ir(n,{protocol:t}));a.terminate();return}c!==null&&a.enqueue(Ir(c,{protocol:t}))};return new TransformStream({transform(e,t){if(!o){for(let n of i.push(a.decode(e,{stream:!0})))if(s(n,t),o)return}},flush(e){if(!o){for(let t of i.push(a.decode()))if(s(t,e),o)return;for(let t of i.flush())if(s(t,e),o)return}}})}function Kr(e,t){return new yr([...t.specs.flatMap(e=>Hr(e,t).requestLayers),qr(t)]).run(e,e=>mr(e))}function qr(e){return(t,n)=>{let r;try{r=e.options.translate===!1?t.body:e.pair.translateRequest(t.body,e.options)}catch(e){return hr(gr(e)??500,vr(e))}let i={"content-type":`application/json`},a=r.stream===!0;return n({headers:i,body:r,stream:a})}}var Jr=class{stream;collectUsage=()=>this.#t;#e;#t=null;#n;#r;#i=!1;constructor(e){this.#e=e,this.#n=e.bridge(this.#a())[Symbol.asyncIterator](),this.#r=this.#o()[Symbol.asyncIterator]();let t=new M({objectMode:!0,highWaterMark:0,read:()=>{this.#r.next().then(e=>{e.done?t.push(null):t.push(e.value)},e=>{t.destroy(e instanceof Error?e:Error(String(e)))})},destroy:(e,t)=>{Promise.resolve(this.#r.return?.()).catch(()=>{}).then(()=>t())}});this.stream=M.toWeb(t)}async*#a(){for await(let e of Rr(this.#e.upstreamBytes,this.#e.upstreamProtocol)){if(e.done){this.#i=!0;return}let t=Br(e);t!==null&&(yield t)}}async*#o(){try{for(;;){let e=await this.#n.next();if(e.done){if(this.#e.upstreamProtocol===`openai`&&!this.#i){for(let e of br(this.#e.inboundProtocol,{status:502,message:`upstream stream ended before the [DONE] sentinel (truncated)`}))yield Vr(e,this.#e.inboundProtocol);return}xr(this.#e.inboundProtocol)&&(yield Lr());return}let t=e.value,n=this.#e.usageFromFrame;if(n!==void 0){let e=n(t);e!==null&&(this.#t={...this.#t??{},...e})}yield Vr(t,this.#e.inboundProtocol)}}catch(e){let t=vr(e);for(let n of br(this.#e.inboundProtocol,{status:gr(e),message:t}))yield Vr(n,this.#e.inboundProtocol)}finally{await this.#n.return?.().catch(()=>{})}}};function Yr(e){let t={};if(e instanceof Headers)return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t;for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}async function Xr(e,t){let n=Yr(e.headers),r=(n[`content-type`]??``).includes(`text/event-stream`);return e.status<200||e.status>299||!r?Zr(e,t,n):Qr(e,t,n)}async function Zr(e,t,n){let r;try{r=await e.text()}catch(e){return hr(502,`failed to read upstream response body: ${vr(e)}`)}let i;try{let e=JSON.parse(r);if(typeof e!=`object`||!e)return hr(502,`upstream response is not a valid JSON object`);i=e}catch{return hr(502,`upstream response is not valid JSON`)}return new yr([...t.specs.flatMap(e=>Hr(e,t).responseLayers),$r(t)]).run({status:e.status,headers:n,body:i},e=>mr(e))}function Qr(e,t,n){return e.body===null?hr(502,`streaming response has no body`):new yr([...t.specs.flatMap(e=>Hr(e,t).responseLayers),ei(t)]).run({status:e.status,headers:n,body:e.body},e=>mr(e))}function $r(e){return(t,n)=>{let r=t,i;try{i=r.status<200||r.status>299?e.pair.errorEnvelope(r.status,r.body):e.options.translate===!1?r.body:e.pair.translateResponse(r.body,e.options)}catch(e){return hr(gr(e)??500,vr(e))}return n({status:r.status,headers:r.headers,body:i})}}function ei(e){return(t,n)=>{let r=t,i=new Jr({upstreamBytes:r.body,upstreamProtocol:e.pair.upstream,inboundProtocol:e.pair.inbound,bridge:e.options.translate===!1?e=>e:t=>e.pair.bridgeFrames(t,e.options,e.inboundBody??void 0),usageFromFrame:e.pair.usageFromFrame});return n({status:r.status,headers:r.headers,stream:i.stream,collectUsage:i.collectUsage})}}var ti=[],ni=class{chainName;pair;options;state=new Map;getState(e){return this.state.get(e)}setState(e,t){this.state.set(e,t)}#e=null;#t=ti;#n=null;#r=!1;#i=!1;#a;constructor(e){this.chainName=e.chainName,this.pair=e.pair,this.options=Object.freeze({...e.options}),this.#a=e.snapshot}get specs(){return this.#t}get inbound(){return this.#e}get inboundBody(){return this.#e===null?null:this.#e.body}get upstreamRequest(){return this.#n}request(e){if(this.#r)return hr(500,`RequestContext: request() can only be called once (one container per round trip)`);this.#r=!0,this.#e=e,this.#t=ri(this.#a,e,this);let t=Kr(e,this);return _r(t)?t.then(e=>(e.kind===`ok`&&(this.#n=e.value),e)):(t.kind===`ok`&&(this.#n=t.value),t)}response(e){if(this.#i)return Promise.resolve(hr(500,`RequestContext: response() can only be called once`));if(this.#i=!0,!this.#r){let e=[];for(let t of this.#a)t!==null&&t.runWhen===void 0&&e.push(t);this.#t=e}return Xr(e,this)}};function ri(e,t,n){let r=[];for(let i of e)i!==null&&(i.runWhen===void 0||i.runWhen(t,n)===!0)&&r.push(i);return r}var ii=class{#e=[];register(e){let t=this.#e.length;return this.#e.push(e),t}unregister(e){this.#e[e]=null}snapshot(){return[...this.#e]}},ai=class{#e;#t;#n;#r=new ii;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}get name(){return this.#n}intercept(e){return this.#r.register(e)}unregister(e){this.#r.unregister(e)}begin(){return new ni({chainName:this.#n,pair:this.#e,options:Object.freeze({...this.#t}),snapshot:this.#r.snapshot()})}};function U(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function W(e){return U(e)?e:{}}function G(e){return Array.isArray(e)?e:[]}function K(e){return typeof e==`string`?e:null}function q(e){return typeof e==`string`?e:``}function oi(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function si(e){return typeof e!=`number`||!Number.isFinite(e)?0:Math.max(0,Math.trunc(e))}function ci(){return crypto.randomUUID()}function li(){return Math.floor(Date.now()/1e3)}function ui(...e){for(let t of e){let e=si(t);if(e>0)return e}return 0}function di(e){let t=W(e.prompt_tokens_details);return{cacheRead:ui(e.cache_read_input_tokens,e.prompt_cache_hit_tokens,t.cached_tokens),cacheCreation:ui(e.cache_creation_input_tokens,t.cache_creation_tokens,t.cache_write_tokens)}}function fi(e,t,n,r){let i={input_tokens:Math.max(e-n-r,0),output_tokens:t};return r>0&&(i.cache_creation_input_tokens=r),n>0&&(i.cache_read_input_tokens=n),i}var pi=new Set([`end_turn`,`max_tokens`,`stop_sequence`,`tool_use`,`refusal`]),mi=new Set([`stop`,`length`,`tool_calls`,`function_call`,`content_filter`]);function hi(e){return{stop:`end_turn`,length:`max_tokens`,tool_calls:`tool_use`}[e]??`end_turn`}function gi(e){let t=K(e)??``;return pi.has(t)?t:hi(t)}function _i(e){let t=K(e.stop_reason),n=K(W(e.provider_specific_fields).stop_reason),r=t??n;return r===null||r===``||pi.has(r)||mi.has(r)?null:r}function vi(e){let t=K(e.refusal);if(t!==null&&t!==``)return t;let n=K(W(e.provider_specific_fields).refusal);return n!==null&&n!==``?n:null}var yi={400:`invalid_request_error`,401:`authentication_error`,403:`permission_error`,404:`not_found_error`,413:`request_too_large`,429:`rate_limit_error`,500:`api_error`,529:`overloaded_error`};function bi(e){return yi[e]??`api_error`}function xi(e){let t=U(e)?e.code:void 0;return typeof t==`number`&&Number.isInteger(t)&&t>=400&&t<600?t:500}function Si(e){if(!U(e))return!1;let t=e.type===`error`?e.error:void 0;return U(t)&&typeof t.type==`string`&&typeof t.message==`string`}function Ci(e,t){if(U(t)){let e=t.error;if(U(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(U(n)&&typeof n.message==`string`)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;if(typeof i==`string`&&i!==``)return i;let a=JSON.stringify(t);if(a!==void 0&&a!==``)return a}return typeof t==`string`&&t!==``?t:`upstream error (HTTP ${e})`}function wi(e,t){return Si(t)?t:{type:`error`,error:{type:bi(e),message:Ci(e,t)}}}function Ti(e){let t=W(e);if(t.type===`message_start`){let e=W(t.message).usage;return U(e)?e:null}if(t.type===`message_delta`){let e=t.usage;return U(e)?e:null}return null}function Ei(e){if(typeof e!=`object`||!e||Array.isArray(e))return String(e);let t=W(e),n=t.message;return typeof n==`string`&&n!==``?n:JSON.stringify(t)}var Di=class{#e=0;#t=null;#n=null;#r=null;#i=0;#a=0;#o=0;#s=0;#c=!1;#l=!1;#u=null;#d=null;#f=``;#p=``;translateFrame(e){if(this.#l)return[];let t=e.error;if(t!=null)throw new H(Ei(t),{status:xi(t)});let n=W(G(e.choices)[0]),r=W(n.delta),i=[];if(!this.#c){this.#c=!0;let t=e.id;this.#p=typeof t==`string`&&t!==``?t:ci(),i.push(this.#m(K(e.model)))}let a=r.content;typeof a==`string`&&a!==``&&(i.push(...this.#h(`text`)),i.push(this.#_({type:`text_delta`,text:a})));let o=vi(r);o!==null&&(this.#f+=o,i.push(...this.#h(`text`)),i.push(this.#_({type:`text_delta`,text:o})));let s=r.reasoning_content===void 0?r.reasoning:r.reasoning_content;typeof s==`string`&&s!==``&&(i.push(...this.#h(`thinking`,{type:`thinking`,thinking:``,signature:``})),i.push(this.#_({type:`thinking_delta`,thinking:s})));for(let e of G(r.thinking_blocks)){let t=K(W(e).signature);t!==null&&t!==``&&(i.push(...this.#h(`thinking`,{type:`thinking`,thinking:``,signature:``})),i.push(this.#_({type:`signature_delta`,signature:t})))}for(let[e,t]of G(r.tool_calls).entries()){let n=W(t),r=W(n.function),a=typeof n.index==`number`?n.index:e,o=K(n.id)??``;(this.#t!==`tool_use`||this.#n!==a||o!==``&&this.#r!==null&&this.#r!==o)&&this.#t===`tool_use`&&i.push(...this.#g()),i.push(...this.#h(`tool_use`,{type:`tool_use`,id:o,name:K(r.name)??``,input:{}})),this.#n=a,o!==``&&(this.#r=o);let s=r.arguments;typeof s==`string`&&s!==``&&i.push(this.#_({type:`input_json_delta`,partial_json:s}))}let c=W(e.usage),l=si(c.prompt_tokens),u=si(c.completion_tokens);if(l>0){this.#i=l;let e=di(c);this.#o=e.cacheRead,this.#s=e.cacheCreation}u>0&&(this.#a=u);let d=n.finish_reason;typeof d==`string`&&d!==``&&(this.#u=d);let f=_i(n);return f!==null&&(this.#d=f),i}flush(){if(!this.#c||this.#l)return[];this.#l=!0;let e=[...this.#g()],t=this.#d===null?this.#u==null?`end_turn`:gi(this.#u):`stop_sequence`,n=this.#f!==``&&t!==`max_tokens`;return e.push({type:`message_delta`,delta:n?{stop_reason:`refusal`,stop_sequence:this.#d,stop_details:{type:`refusal`}}:{stop_reason:t,stop_sequence:this.#d},usage:fi(this.#i,this.#a,this.#o,this.#s)}),e.push({type:`message_stop`}),e}#m(e){return{type:`message_start`,message:{id:this.#p,type:`message`,role:`assistant`,...e===null?{}:{model:e},content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}}#h(e,t){if(this.#t===e)return[];let n=this.#g();this.#t=e;let r=t??{type:`text`,text:``},i=[...n,{type:`content_block_start`,index:this.#e,content_block:r}];return this.#e+=1,i}#g(){if(this.#t===null)return[];let e=this.#e-1;return this.#t=null,this.#n=null,this.#r=null,[{type:`content_block_stop`,index:e}]}#_(e){return{type:`content_block_delta`,index:this.#e-1,delta:e}}};async function*Oi(e){let t=new Di;for await(let n of e)for(let e of t.translateFrame(W(n)))yield e;for(let e of t.flush())yield e}var ki=4096;function Ai(e){return e.map(e=>{if(!U(e))return W(e);let t=!1,n={};for(let[r,i]of Object.entries(e)){if(r===`provider_specific_fields`){t=!0;continue}if(r===`content`&&Array.isArray(i)){let e=i.map(e=>{if(!U(e)||!(`provider_specific_fields`in e))return e;let{provider_specific_fields:t,...n}=e;return n});(e.length!==i.length||e.some((e,t)=>e!==i[t]))&&(t=!0),n[r]=e;continue}n[r]=i}return t?n:e})}function ji(e,t){let n=!1;for(let t of e){let e=t.content;if(Array.isArray(e)){for(let t of e)if(W(t).type===`container_upload`){n=!0;break}}if(n)break}if(!n)return t;for(let e of t){let n=e.type;if(typeof n==`string`&&n.startsWith(`code_execution`))return t}return[...t,{name:`code_execution`,type:`code_execution_20250522`}]}function Mi(e){if(!U(e.metadata))return;let t=W(e.metadata).user_id;t==null?delete e.metadata:e.metadata={user_id:t}}function Ni(e){let t=e.output_config;if(!U(t))return;let n=t.effort;if(typeof n==`string`&&n!==``&&![`high`,`medium`,`low`,`xhigh`,`max`].includes(n))throw new H(`Invalid effort value: ${JSON.stringify(n)}. Must be one of: 'high', 'medium', 'low', 'xhigh', 'max'`,{status:400})}function Pi(e){let t=W(e),n=Ai(G(t.messages)),r=G(t.tools).map(W),i=ji(n,r),a={...t,messages:n};return i!==r&&(a.tools=i),`max_tokens`in a||(a.max_tokens=ki),Mi(a),delete a.is_vertex_request,delete a.client_metadata,Ni(a),a}function Fi(e){return typeof e==`number`&&Number.isFinite(e)?Math.floor(e):0}function Ii(e){let t=Fi(e.input_tokens??0),n=Fi(e.output_tokens??0),r=0,i=0,a=e.iterations,o=Array.isArray(a)?a.map(W):null;o!==null&&o.length>0&&(t=o.reduce((e,t)=>e+Fi(t.input_tokens??0),0),n=o.reduce((e,t)=>e+Fi(t.output_tokens??0),0),r=o.reduce((e,t)=>e+Fi(t.cache_creation_input_tokens??0),0),i=o.reduce((e,t)=>e+Fi(t.cache_read_input_tokens??0),0),t+=r+i),o===null&&(`cache_creation_input_tokens`in e&&e.cache_creation_input_tokens!==null&&typeof e.cache_creation_input_tokens==`number`&&(r=e.cache_creation_input_tokens,t+=r),`cache_read_input_tokens`in e&&e.cache_read_input_tokens!==null&&typeof e.cache_read_input_tokens==`number`&&(i=e.cache_read_input_tokens,t+=i));let s={cached_tokens:i,cache_creation_tokens:r,cache_write_tokens:r};return{prompt_tokens:t,completion_tokens:n,total_tokens:t+n,prompt_tokens_details:s,cache_creation_input_tokens:r,cache_read_input_tokens:i}}var Li=/^<(?:think|thinking|budget:thinking)>([\s\S]*?)<\/(?:think|thinking|budget:thinking)>([\s\S]*)/;function Ri(e){if(!e)return{reasoningContent:null,content:e};let t=Li.exec(e);return t===null?{reasoningContent:null,content:e}:{reasoningContent:t[1]??null,content:t[2]??null}}function zi(e){let t=e.content,n=K(t);return`reasoning_content`in e?{reasoningContent:K(e.reasoning_content),content:n}:`reasoning`in e?{reasoningContent:K(e.reasoning),content:n}:typeof t==`string`?Ri(t):{reasoningContent:null,content:n}}function Bi(e){let t=W(e),n=t.arguments,r;if(n==null){let e=t.parameters;r=U(e)?JSON.stringify(e):``}else r=U(n)?JSON.stringify(n):String(n);return{arguments:r,name:K(t.name)}}function Vi(e){return e.type===`custom`||e.custom!=null}function Hi(e){return Vi(e)?Object.fromEntries(Object.entries(e).filter(([e,t])=>e!==`function`&&e!==`type`||t!=null)):{id:e.id==null?ci():String(e.id),type:e.type==null?`function`:String(e.type),function:Bi(e.function)}}function Ui(e){let t=new Map;for(let[n,r]of e.entries()){if(Vi(r))continue;let e=W(r.function),i=e.name,a=JSON.parse(typeof e.arguments==`string`?e.arguments:``);if(i!==`multi_tool_use.parallel`)continue;let o=W(a),s=(Array.isArray(o.tool_uses)?o.tool_uses:[]).map((e,t)=>{let n=W(e),i=String(n.recipient_name).replace(/^functions\./,``);return{id:`${String(r.id)}_${String(t)}`,type:`function`,function:{name:i,arguments:JSON.stringify(n.parameters)}}});t.set(n,s)}return t}function Wi(e){try{let t=Ui(e),n=0,r=[...e];for(let[e,i]of t)r.splice(e+n,1,...i),n+=i.length;return r}catch{return e}}function Gi(e){return Array.isArray(e.tool_calls)?Wi(e.tool_calls.map(e=>Hi(W(e)))):[]}function Ki(e){if(typeof e!=`string`||e===``)return{};try{return W(JSON.parse(e))}catch{return{}}}function qi(e){let t=[];for(let n of e.thinkingBlocks){let e=W(n);e.type===`thinking`?t.push({type:`thinking`,thinking:K(e.thinking)??``,signature:K(e.signature)}):e.type===`redacted_thinking`&&t.push({type:`redacted_thinking`,data:K(e.data)??``})}e.thinkingBlocks.length===0&&typeof e.reasoningContent==`string`&&e.reasoningContent!==``&&t.push({type:`thinking`,thinking:e.reasoningContent,signature:null}),typeof e.content==`string`&&e.content!==``&&t.push({type:`text`,text:e.content}),e.refusal!==null&&t.push({type:`text`,text:e.refusal});for(let n of e.toolCalls){let e=W(n),r=W(e.function);t.push({type:`tool_use`,id:K(e.id)??``,name:K(r.name)??``,input:Ki(r.arguments)})}return t}function Ji(e){let{cacheRead:t,cacheCreation:n}=di(e);return fi(si(e.prompt_tokens),si(e.completion_tokens),t,n)}function Yi(e){let t=W(e),n=t.error;if(n!=null){let e=W(n);throw new H(typeof e.message==`string`?e.message:JSON.stringify(n),{status:xi(n)})}let r=G(t.choices);if(r.length===0)throw Error(`upstream returned a response with no 'choices'. Raw keys: ${Object.keys(t).join(`, `)}`);let i=W(r[0]),a=W(i.message),o=Gi(a),{reasoningContent:s,content:c}=zi(a),l=G(a.thinking_blocks),u=vi(a),d=K(i.finish_reason)??`stop`;d===`stop`&&o.length>0&&(d=`tool_calls`);let f=_i(i),p=f===null?gi(d):`stop_sequence`,m=u!==null&&p!==`max_tokens`;return m&&(p=`refusal`),{id:t.id,type:`message`,role:`assistant`,...t.model===void 0?{}:{model:t.model},content:qi({thinkingBlocks:l,reasoningContent:s,content:c,refusal:u,toolCalls:o}),stop_reason:p,...m?{stop_details:{type:`refusal`}}:{},stop_sequence:f,usage:Ji(W(t.usage))}}function Xi(e){return e===null?`None`:e===!0?`True`:e===!1?`False`:typeof e==`number`?String(e):typeof e==`string`?`'${e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`:Array.isArray(e)?`[${e.map(e=>Xi(e)).join(`, `)}]`:U(e)?`{${Object.entries(e).map(([e,t])=>`'${e}': ${Xi(t)}`).join(`, `)}}`:String(e)}function Zi(e){let t=``,n=[],r=null,i=[];if((Array.isArray(e.content)?e.content:[]).forEach((e,r)=>{let a=W(e),o=typeof a.type==`string`?a.type:``;if(o===`text`)t+=typeof a.text==`string`?a.text:``;else if(o===`tool_use`||o===`server_tool_use`){let e={id:a.id,type:`function`,function:{name:a.name,arguments:JSON.stringify(a.input??{})},index:r};i.push(e)}else(o===`thinking`||o===`redacted_thinking`)&&n.push(a)}),n.length>0){r=``;for(let e of n){let t=e.thinking;typeof t==`string`&&(r+=t)}}return{textContent:t,thinkingBlocks:n,reasoningContent:r,toolCalls:i}}function Qi(e){let t=[];for(let n of e){let e=W(n),r=typeof e.type==`string`?e.type:``;(r===`tool_use`||r===`server_tool_use`)&&t.push(e.caller)}return t}function $i(e,t){let n=Qi(Array.isArray(t.content)?t.content:[]),r=Array.isArray(e.content)?e.content:[],i=0;for(let e of r){let t=W(e);if(t.type!==`tool_use`)continue;let r=n[i];i+=1,r!==void 0&&(t.caller=r)}}function ea(e){let t=W(e);if(`error`in t&&t.error!==null&&t.error!==void 0)throw new H(Xi(t.error));let n=Zi(t),r={role:`assistant`,content:n.textContent===``?null:n.textContent,tool_calls:n.toolCalls.length>0?n.toolCalls:null};n.reasoningContent!==null&&(r.reasoning_content=n.reasoningContent),n.thinkingBlocks.length>0&&(r.thinking_blocks=n.thinkingBlocks);let i=W(Yi({id:ci(),object:`chat.completion`,...t.model===void 0?{}:{model:t.model},choices:[{index:0,finish_reason:K(t.stop_reason),message:r}],usage:Ii(W(t.usage))}));return $i(i,t),{...i,...t.container===void 0?{}:{container:t.container},...`stop_details`in i?{stop_details:i.stop_details}:t.stop_details===void 0?{}:{stop_details:t.stop_details},...t.diagnostics===void 0?{}:{diagnostics:t.diagnostics}}}var ta=class{contentBlocks=[];toolIndex=-1;currentContentBlockType=null;cumulativeUsage={};parse(e){let t=K(e.type)??``,n=``,r=null,i=``,a=null,o=null,s=null,c=null;if(t===`content_block_delta`){let t=W(e.delta);if(this.contentBlocks.push(e),typeof t.text==`string`)n=t.text;else if(`partial_json`in t)(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`)&&(r={id:null,type:`function`,function:{name:null,arguments:typeof t.partial_json==`string`?t.partial_json:``},index:this.toolIndex});else if(!(`citation`in t)&&(`thinking`in t||`signature`in t)){let e=t.thinking;typeof e==`string`&&e!==``&&(o=e,s=[{type:`thinking`,thinking:e}]);let n=t.signature;typeof n==`string`&&n!==``&&(s=[{type:`thinking`,thinking:this.contentBlocks.map(e=>W(e.delta)).filter(e=>typeof e.thinking==`string`).map(e=>e.thinking).join(``),signature:n}])}}else if(t===`content_block_start`){let t=W(e.content_block);if(this.contentBlocks.length=0,this.currentContentBlockType=K(t.type)??``,this.currentContentBlockType===`text`)n=typeof t.text==`string`?t.text:``;else if(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`){this.toolIndex+=1;let e=K(t.name)??``;r={id:K(t.id),type:`function`,function:{name:e,arguments:``},index:this.toolIndex}}else this.currentContentBlockType===`redacted_thinking`&&(s=[{type:`redacted_thinking`,data:t.data}])}else if(t===`content_block_stop`)(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`)&&this.contentBlocks.map(e=>W(e.delta)).filter(e=>e.type===`input_json_delta`).map(e=>typeof e.partial_json==`string`?e.partial_json:``).join(``)===``&&(r={id:null,type:`function`,function:{name:null,arguments:`{}`},index:this.toolIndex}),this.currentContentBlockType=null;else if(t===`message_delta`)i=K(W(e.delta).stop_reason)??``,`usage`in e&&(a=Ii(this.#e(e.usage)));else if(t===`message_start`){let t=W(e.message);c=K(t.model),`usage`in t&&(a=Ii(this.#e(t.usage)))}else if(t===`error`){let t=W(e.error);throw new H(typeof t.message==`string`&&t.message!==``?t.message:JSON.stringify(e),{status:500})}else return null;let l={content:n,tool_calls:r===null?null:[r]};o!==null&&(l.reasoning_content=o),s!==null&&(l.thinking_blocks=s);let u={choices:[{index:0,finish_reason:i===``?null:i,delta:l}]};return c!==null&&(u.model=c),a!==null&&(u.usage=a),u}#e(e){return this.cumulativeUsage={...this.cumulativeUsage,...W(e)},this.cumulativeUsage}},na=class{inbound=`anthropic`;upstream=`anthropic`;translateRequest(e){return Pi(e)}translateResponse(e){return ea(e)}async*bridgeFrames(e){let t=new ta,n=new Di;for await(let r of e){let e=t.parse(W(r));if(e!==null)for(let t of n.translateFrame(e))yield t}for(let e of n.flush())yield e}usageFromFrame(e){return Ti(e)}errorEnvelope(e,t){return wi(e,t)}},ra=`Operator note (not from the user): the following was originally a mid-conversation system-role reminder.`;function ia(e){let t=e.role;return t===`system`?`system`:t===`tool`||t===`function`?`tool`:t===`user`?`user`:`other`}function aa(e){let t=e.content;if(typeof t==`string`)return t===``?[]:[{type:`text`,text:t}];let n=[];for(let e of G(t)){let t=W(e);if(t.type!==`text`)continue;let r=K(t.text)??``;r!==``&&n.push({type:`text`,text:r})}return n}function oa(e){return{role:`user`,content:[{type:`text`,text:ra},...aa(e)]}}function sa(e){return e.filter(e=>aa(e).length>0).map(oa)}function ca(e){let t=[],n=null,r=[];for(let i of e){let e=ia(i);e!==n&&(r.length>0&&t.push(r),r=[],n=e),r.push(i)}return r.length>0&&t.push(r),t}function la(e){let t=ca(e),n=[];for(let e=0;e<t.length;e++){let r=t[e]??[],i=ia(r[0]??{}),a=t[e+1],o=a===void 0?null:ia(a[0]??{});if(i===`system`){o!==`tool`&&n.push(...sa(r));continue}let s=e>0?t[e-1]:void 0;if(i===`tool`&&s!==void 0&&ia(s[0]??{})===`system`){n.push(...r,...sa(s));continue}n.push(...r)}return n}function ua(e){if(!e.some(e=>e.role===`system`))return e;let t=e.findIndex(e=>e.role!==`system`);return t===-1?e:[...e.slice(0,t),...la(e.slice(t))]}var da=new Set([`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`not`,`propertyNames`,`then`,`unevaluatedItems`,`unevaluatedProperties`]),fa=new Set([`allOf`,`anyOf`,`items`,`oneOf`,`prefixItems`]),pa=new Set([`$defs`,`definitions`,`dependentSchemas`,`patternProperties`,`properties`]),ma=1024;function ha(e){if(e.includes(`\\p{`)||e.includes(`\\p<`))return!1;try{new RegExp(e)}catch{return!1}return!0}function ga(e,t){let n={},r=!1;for(let[i,a]of Object.entries(e)){if(i===`pattern`&&typeof a==`string`&&!ha(a)){r=!0;continue}let e=_a(i,a,t);e!==a&&(r=!0),i===`__proto__`?Object.defineProperty(n,i,{value:e,enumerable:!0,writable:!0,configurable:!0}):n[i]=e}return r?n:e}function _a(e,t,n){if(fa.has(e)&&Array.isArray(t)){let e=t.map(e=>U(e)?n.get(e)??e:e);return e.every((e,n)=>e===t[n])?t:e}if(!U(t))return t;if(pa.has(e)){let r={},i=!1;for(let[a,o]of Object.entries(t)){if(e===`patternProperties`&&typeof a==`string`&&!ha(a)){i=!0;continue}if(U(o)){let e=n.get(o)??o;e!==o&&(i=!0),a===`__proto__`?Object.defineProperty(r,a,{value:e,enumerable:!0,writable:!0,configurable:!0}):r[a]=e}else r[a]=o}return i?r:t}return da.has(e)?n.get(t)??t:t}function va(e,t){for(let[n,r]of Object.entries(e))if(pa.has(n)&&U(r))for(let e of Object.values(r))U(e)&&t.push(e);else if(fa.has(n)&&Array.isArray(r))for(let e of r)U(e)&&t.push(e);else da.has(n)&&U(r)&&t.push(r)}function ya(e){let t=new Map,n=[],r=[e];for(;r.length>0&&n.length<ma;){n.push(r);let e=[];for(let t of r)va(t,e);r=e}for(let e of n.reverse())for(let n of e){let e=ga(n,t);e!==n&&t.set(n,e)}return t.get(e)??e}function ba(e){if(U(e))return e;if(typeof e!=`string`)return null;try{let t=JSON.parse(e);return U(t)?t:null}catch{return null}}function xa(e,t){if(typeof e==`string`)return e===``?null:e;let n=[];for(let r of G(e)){let e=W(r);if(e.type!==`text`)continue;let i=K(e.text)??``;(i!==``||t)&&n.push({type:`text`,text:i})}return n.length>0?n:null}function Sa(e){let t=xa(e,!0);return t===null?[]:[{role:`system`,content:t}]}function Ca(e){return e.flatMap(e=>{let t=W(e),n=t.content;if(t.role===`system`){let e=xa(n,!1);return e===null?[]:[{role:`system`,content:e}]}return t.role===`user`?wa(n):t.role===`assistant`?Oa(n):[]})}function wa(e){if(typeof e==`string`)return[{role:`user`,content:e}];let t=[],n=[];for(let r of G(e)){let e=W(r);if(e.type===`text`)t.push({type:`text`,text:K(e.text)??``});else if(e.type===`image`){let n=Ea(e.source);n!==null&&t.push({type:`image_url`,image_url:{url:n}})}else e.type===`tool_result`&&n.push({role:`tool`,content:Ta(e.content),tool_call_id:K(e.tool_use_id)??``})}let r=t.length>0?t:``;return n.length>0&&t.length===0?n:[...n,{role:`user`,content:r}]}function Ta(e){return typeof e==`string`?e:G(e).map(e=>K(W(e).text)??``).join(``)}function Ea(e){let t=W(e);return t.type===`base64`&&typeof t.data==`string`&&t.data!==``?`data:${typeof t.media_type==`string`?t.media_type:`image/jpeg`};base64,${t.data}`:t.type===`url`?K(t.url):null}function Da(e){return e.map(e=>e.type===`thinking`?K(e.thinking)??``:``).filter(e=>e!==``).join(`
|
|
16
|
-
`)}function Oa(e){if(typeof e==`string`)return[{role:`assistant`,content:e}];let t=[],n=[],r=[];for(let i of G(e)){let e=W(i);e.type===`text`?t.push(K(e.text)??``):e.type===`tool_use`?n.push({id:K(e.id)??``,type:`function`,function:{name:K(e.name)??``,arguments:JSON.stringify(e.input??{})}}):e.type===`thinking`?r.push({type:`thinking`,thinking:K(e.thinking)??``,signature:K(e.signature)??``}):e.type===`redacted_thinking`&&r.push({type:`redacted_thinking`,data:K(e.data)??``})}let i=Da(r);return[{role:`assistant`,content:t.length>0?t.join(``):null,...n.length>0?{tool_calls:n}:{},...r.length>0?{thinking_blocks:r}:{},...i===``?{}:{reasoning_content:i}}]}var ka=64;function Aa(e){if(typeof e!=`string`)return null;let t;try{t=JSON.parse(e)}catch{return null}let n=W(t).session_id;if(typeof n!=`string`)return null;let r=n.slice(0,ka);return r===``?null:r}function ja(e,t){let n=new Set([`max_tokens`,`temperature`,`top_p`,`stop_sequences`,`stream`,`metadata`,`tool_choice`,`tools`,`thinking`,`reasoning_effort`,`system`,`context_management`,`output_config`]);t.topK!==`preserve`&&n.add(`top_k`);let r=Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e))),i=(e,t,n)=>{n&&(r[e]=t)},a=e.max_tokens;i(`max_tokens`,a,typeof a==`number`);let o=e.temperature;i(`temperature`,o,typeof o==`number`);let s=e.top_p;i(`top_p`,s,typeof s==`number`);let c=e.stop_sequences;i(`stop`,c,Array.isArray(c)&&c.length>0),i(`stream`,!0,e.stream===!0);let l=Aa(W(e.metadata).user_id);i(`prompt_cache_key`,l,l!==null);let u=Ma(e.tool_choice);i(`tool_choice`,u,u!==null);let d=e.tools;i(`tools`,G(d).map(Na),G(d).length>0);let f=Pa(e.thinking,e.output_config);return i(`reasoning_effort`,f,f!==null),r}function Ma(e){let t=W(e);return t.type===`auto`?`auto`:t.type===`any`?`required`:t.type===`none`?`none`:t.type===`tool`&&typeof t.name==`string`?{type:`function`,function:{name:t.name}}:null}function Na(e){let t=W(e),n=t.input_schema,r=ba(n);if(r===null&&n!=null)throw new H(`Invalid type for tools[${String(t.name??``)}].input_schema: expected an object, but got ${typeof n} instead.`,{status:400});return{type:`function`,function:{name:t.name??``,description:t.description,parameters:ya(r!==null&&Object.keys(r).length>0?r:{type:`object`,properties:{}})}}}function Pa(e,t=void 0){let n=W(e),r=K(n.type)??``;if(r===`disabled`)return null;if(r===`adaptive`)return K(W(n.output_config).effort)??K(W(t).effort)??null;if(r!==`enabled`)return null;let i=n.budget_tokens;return typeof i==`number`?i<=1024?`low`:i<=2048?`medium`:`high`:`medium`}function Fa(e,t){let n=W(e),r=ua([...Sa(n.system),...Ca(G(n.messages))]),i=ja(n,t);if(i.messages=r,i.reasoning_effort===`none`){let e={...i};delete e.reasoning_effort,i=e}return i}var Ia=class{inbound=`anthropic`;upstream=`openai`;translateRequest(e,t){return Fa(e,t)}translateResponse(e){return Yi(e)}bridgeFrames(e){return Oi(e)}usageFromFrame(e){return Ti(e)}errorEnvelope(e,t){return wi(e,t)}},La={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`};function Ra(e){let t=La[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t}function za(e,t){if(typeof t==`string`&&t!==``)return t;if(U(t)){let e=t.message;if(typeof e==`string`&&e!==``)return e;let n=JSON.stringify(t);if(n!==void 0&&n!==``)return n}return`upstream error (HTTP ${e})`}function Ba(e,t){return U(t)&&U(t.error)?t:{error:{message:za(e,t),type:Ra(e),param:null,code:String(e)}}}function Va(){return`chatcmpl-${ci()}`}var Ha={stop_sequence:`stop`,end_turn:`stop`,max_tokens:`length`,tool_use:`tool_calls`,refusal:`content_filter`,compaction:`length`,content_filtered:`content_filter`,stop:`stop`,length:`length`,tool_calls:`tool_calls`,function_call:`function_call`,content_filter:`content_filter`};function Ua(e){return Ha[K(e)??``]??`stop`}function Wa(e,t){let n=e.iterations,r=null;if(Array.isArray(n)&&n.length>0){let e=n.map(e=>{let t=W(W(e).output_tokens_details).thinking_tokens;return typeof t==`number`&&Number.isFinite(t)?t:null});r=e.every(e=>e!==null)?e.reduce((e,t)=>e+(t??0),0):null}if(r===null){let t=W(e.output_tokens_details).thinking_tokens;typeof t==`number`&&Number.isFinite(t)&&(r=t)}if(r===null)return{reasoning_tokens:0,text_tokens:t};let i=Math.min(Math.max(0,r),t);return{reasoning_tokens:i,text_tokens:t-i}}function Ga(e,t={}){let n=si(e.input_tokens),r=si(e.output_tokens),i=si(e.cache_creation_input_tokens),a=si(e.cache_read_input_tokens),o=n+i+a,s={cached_tokens:a,text_tokens:n,cache_write_tokens:i,cache_creation_tokens:i};if(U(e.cache_creation)){let t=e.cache_creation,n={};for(let e of[`ephemeral_5m_input_tokens`,`ephemeral_1h_input_tokens`]){let r=t[e];typeof r==`number`&&(n[e]=si(r))}s.cache_creation_token_details=n}let c={completion_tokens:r,prompt_tokens:o,total_tokens:o+r,completion_tokens_details:Wa(e,r),prompt_tokens_details:s,cache_creation_input_tokens:i,cache_read_input_tokens:a},l=K(e.inference_geo);l!==null&&(c.inference_geo=l);let u=K(e.speed);if(u!==null&&(c.speed=u),t.fromStreamBuilder!==!0){let t=K(e.service_tier);t!==null&&(c.service_tier=t)}return c}function Ka(e,t){return{...e??{},...t}}function qa(e){return/claude-[a-z]+-(?:4[-._](?:[6-9]|[1-9]\d)(?!\d)|[5-9](?!\d)(?:[-._]\d{1,2}(?!\d))?)/.test(e)}function Ja(e){return/claude-[a-z]+-4[-._]6(?!\d)/.test(e)}function Ya(e){let t=e.toLowerCase();return![`fable`,`opus-4-7`,`opus_4_7`,`opus-4.7`,`opus_4.7`,`opus-4-8`,`opus_4_8`,`opus-4.8`,`opus_4.8`].some(e=>t.includes(e))}function Xa(e,t){if(typeof t==`string`&&t!==``)return t;if(U(t)){let e=t.error;if(U(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(U(n)&&typeof n.message==`string`&&n.message!==``)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;if(typeof i==`string`&&i!==``)return i;let a=JSON.stringify(t);if(a!==void 0&&a!==``)return a}return`upstream error (HTTP ${e})`}function Za(e,t){if(U(t)){let e=t.error;if(U(e)&&t.type!==`error`&&typeof e.message==`string`)return t}return{error:{message:Xa(e,t),type:Ra(e),param:null,code:String(e)}}}var Qa={low:1024,medium:2048,high:4096,xhigh:8192,max:16384,minimal:1024},$a={low:`low`,minimal:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:`max`},eo=4096,to=1024,no=`[System: Empty message content sanitised to satisfy protocol]`,ro=new Set([`type`,`properties`,`additionalProperties`,`required`,`$defs`,`strict`]);function io(e,t){if(e==null)return{type:`object`,properties:{}};if(!U(e))throw new H(`Invalid input_schema for tool "${t}": expected an object, got ${typeof e}`,{status:400});let n={};for(let[t,r]of Object.entries(e))ro.has(t)&&(n[t]=r);return n.type!==`object`&&(n.type=`object`),n.properties===void 0&&(n.properties={}),n}function ao(e){let t=W(e),n=W(t.function),r=t.type;if(r!==`function`&&r!==`custom`)throw new H(`Unsupported tool type: ${String(r)}`,{status:400});let i=K(n.name)??``,a={name:i,input_schema:io(n.parameters,i),type:`custom`},o=n.description;o!=null&&(a.description=o);let s=t.eager_input_streaming??n.eager_input_streaming;typeof s==`boolean`&&(a.eager_input_streaming=s);let c=t.cache_control??n.cache_control;U(c)&&(a.cache_control=c);let l=t.defer_loading??n.defer_loading;typeof l==`boolean`&&(a.defer_loading=l);let u=t.allowed_callers??n.allowed_callers;Array.isArray(u)&&(a.allowed_callers=u);let d=t.input_examples??n.input_examples;return Array.isArray(d)&&(a.input_examples=d),a}function oo(e){return e.map(e=>{let t=W(e);return t.input_schema===void 0?ao(e):t})}var so={name:`dummy_tool`,input_schema:{type:`object`,properties:{}},type:`custom`,description:`This is a dummy tool call`};function co(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`)||`tool_use_id`}function lo(e,t){if(typeof e!=`string`||e.trim()===``)return{};try{return JSON.parse(e)}catch(e){throw new H(`Failed to parse tool call arguments for tool '${t}': ${e instanceof Error?e.message:String(e)}`,{status:400})}}function uo(e){if(!U(e))return!1;let t=e.type,n=t===`thinking`?e.signature:t===`redacted_thinking`?e.data:void 0;if(typeof n==`string`&&n.startsWith(`litellm_encrypted_reasoning:`))return!0;if(t!==`thinking`)return!1;let r=e.signature;if(typeof r!=`string`||r.length===0)return!0;let i=e.thinking;return!(typeof i==`string`&&i.trim().length>0)}function fo(e){let t=e.cache_control;return U(t)?t:void 0}function po(e,t){return e===``?null:t===void 0?{type:`text`,text:e}:{type:`text`,text:e,cache_control:t}}function mo(e){let t=typeof e==`string`?e:K(W(e).url)??``,n=typeof e==`string`?null:K(W(e).format);if(t.startsWith(`https://`)||t.startsWith(`http://`))return{type:`image`,source:{type:`url`,url:t}};let r=/^data:([^;,]*);base64,(.*)$/s.exec(t);if(r===null)throw new H(`Image url not in expected format. Example Expected input - "image_url": "data:image/jpeg;base64,{base64_image}". Supported formats - ['image/jpeg', 'image/png', 'image/gif', 'image/webp']. Error: unsupported image url`,{status:400});return{type:`image`,source:{type:`base64`,media_type:n??(r[1]??``).replace(/\\\//g,`/`),data:r[2]??``}}}function ho(e){let t=e.content,n=``;if(typeof t==`string`)n=t;else if(Array.isArray(t)){let e=[];for(let n of t){let t=W(n);if(t.type===`text`)e.push({type:`text`,text:K(t.text)??``});else if(t.type===`image_url`){let n=mo(t.image_url),r=fo(t);r!==void 0&&(n.cache_control=r),e.push(n)}}n=e}let r={type:`tool_result`,tool_use_id:co(K(e.tool_call_id)??ci()),content:n},i=fo(e);return i!==void 0&&(r.cache_control=i),r}function go(e){let t=e.role;if(t!==`user`&&t!==`assistant`)return e;let n=e.content;if(typeof n==`string`)return n.trim()===``?{...e,content:no}:e;if(!Array.isArray(n))return e;let r=!1,i=n.map(e=>{let t=W(e);if(t.type!==`text`)return e;let n=t.text;return typeof n==`string`&&n.trim()!==``?e:(r=!0,{...t,text:no})});return r?{...e,content:i}:e}function _o(e){let t=[];for(let n of e){let e=n.role;if(e===`tool`||e===`function`){t.push(ho(n));continue}let r=n.content;if(typeof r==`string`){let e=po(r,void 0);e!==null&&t.push(e);continue}for(let e of G(r)){let n=W(e),r=fo(n);if(n.type===`text`){let e=po(K(n.text)??``,r);e!==null&&t.push(e)}else if(n.type===`image_url`){let e=mo(n.image_url);r!==void 0&&(e.cache_control=r),t.push(e)}else n.type===`document`&&t.push(r===void 0?n:{...n,cache_control:r})}}return t.length>0?{role:`user`,content:t}:null}function vo(e){let t=[],n=new Set;for(let r of e){let e=r.content,i=Array.isArray(e)?e:null,a=i!==null&&i.some(e=>{let t=W(e).type;return t===`thinking`||t===`redacted_thinking`}),o=r.thinking_blocks;if(Array.isArray(o)&&!a)for(let e of o)uo(e)||t.push(W(e));if(i!==null)for(let e of i){let n=W(e),r=n.type;if(r===`thinking`){let e=n.thinking;typeof e==`string`&&e!==``&&!uo(n)&&t.push(n)}else if(r===`text`){let e=po(K(n.text)??``,fo(n));e!==null&&t.push(e)}else(r===`server_tool_use`||typeof r==`string`&&r.endsWith(`_tool_result`))&&t.push(n)}else if(typeof e==`string`){let n=po(e,fo(r));n!==null&&t.push(n)}let s=r.tool_calls;if(Array.isArray(s))for(let e of s){let r=W(e);if(r.type!==`function`)continue;let i=W(r.function),a=K(i.name)??``,o=co(K(r.id)??ci());if(n.has(o))continue;n.add(o);let s={type:`tool_use`,id:o,name:a,input:lo(i.arguments,a)},c=fo(r);c!==void 0&&(s.cache_control=c),t.push(s)}}return t.length>0?{role:`assistant`,content:t}:null}function yo(e){let t=e.map(e=>go(W(e))),n=[],r=0;for(;r<t.length;){let e=t[r]?.role;if(e===`user`||e===`tool`||e===`function`){let e=[];for(;r<t.length;){let n=t[r]?.role;if(n!==`user`&&n!==`tool`&&n!==`function`)break;e.push(t[r]),r+=1}let i=_o(e);i!==null&&n.push(i);continue}if(e===`assistant`){let e=[];for(;r<t.length&&t[r]?.role===`assistant`;)e.push(t[r]),r+=1;let i=vo(e);i!==null&&n.push(i);continue}r+=1}let i=n[n.length-1];if(i!==void 0&&i.role===`assistant`&&Array.isArray(i.content))for(let e of i.content)e.type===`text`&&typeof e.text==`string`&&(e.text=e.text.trimEnd());return n}function bo(e){let t=[];for(let n of e){let e=n.content;if(typeof e==`string`){let r=po(e,fo(n));r!==null&&t.push(r);continue}for(let n of G(e)){let e=W(n);if(e.type!==`text`)continue;let r=po(K(e.text)??``,fo(e));r!==null&&t.push(r)}}return t}var xo=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,So=/^\+?[\d\s()-]{7,}$/;function Co(e){return!xo.test(e)&&!So.test(e)}function wo(e){return typeof e!=`number`||!Number.isFinite(e)?null:Number.isInteger(e)?e:Math.max(1,Math.round(e))}function To(e){let t=typeof e==`string`?[e]:G(e),n=[];for(let e of t)typeof e==`string`&&e.trim()!==``&&n.push(e);return n.length>0?n:null}function Eo(e,t){let n=null;if(e===`auto`)n={type:`auto`};else if(e===`required`)n={type:`any`};else if(e===`none`)n={type:`none`};else if(U(e)){let t=e.type;if(t===`auto`)n={type:`auto`};else if(t===`required`||t===`any`)n={type:`any`};else if(t===`none`)n={type:`none`};else{let t=W(e.function).name;typeof t==`string`&&(n={type:`tool`,name:t})}}if(t!=null){if(e===`none`)return n;let r=t!==!0;n===null?n={type:`auto`,disable_parallel_tool_use:r}:n.disable_parallel_tool_use=r}return n}function Do(e,t){let n=qa(e)&&!Ja(e);return t>=8192&&n?`xhigh`:t>=4096?`high`:t>=2048?`medium`:`low`}function Oo(e,t){if(!qa(e)||Ja(e))return;let n=W(t.thinking);if(n.type!==`enabled`)return;let r=n.budget_tokens,i=Do(e,typeof r==`number`?r:0);t.thinking={type:`adaptive`};let a=t.output_config;t.output_config={effort:i,...U(a)?a:{}}}function ko(e,t){let n=e.budget_tokens;return typeof t!=`number`||typeof n!=`number`?e:t<=to?null:n<t?e:{type:e.type??`enabled`,budget_tokens:t-1}}function Ao(e,t){if(qa(t))return{type:`adaptive`,display:`summarized`};let n=Qa[e];if(n===void 0)throw new H(`Unmapped reasoning effort: '${e}'. Must be one of: 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'none'.`,{status:400});return{type:`enabled`,budget_tokens:n}}function jo(e,t,n,r){if(W(n).type===`adaptive`&&!qa(r)){let n=e.max_completion_tokens??e.max_tokens,r=ko({type:`enabled`,budget_tokens:Qa.medium??2048},n);r!==null&&(t.thinking=r);return}t.thinking=n,Oo(r,t)}function Mo(e,t,n){let r=typeof t==`string`?t:K(W(t).effort);if(r!==null){if(r===`none`){delete e.thinking,delete e.output_config;return}if(e.thinking=Ao(r,n),qa(n)){let t=$a[r];if(t===void 0)throw new H(`Invalid reasoning_effort: '${r}'. Must be one of: 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'none'`,{status:400});e.output_config={effort:t}}}}var No=new Set([`model`,`messages`,`tools`,`tool_choice`,`parallel_tool_calls`,`max_tokens`,`max_completion_tokens`,`temperature`,`top_p`,`top_k`,`stop`,`stream`,`stream_options`,`thinking`,`reasoning_effort`,`user`,`metadata`,`extra_headers`,`cache_control`,`response_format`,`web_search_options`,`context_management`,`speed`]);function Po(e,t){let n=K(e.model)??``,r={};for(let[t,i]of Object.entries(e)){if(!No.has(t)){r[t]=i;continue}switch(t){case`model`:r.model=i;break;case`max_tokens`:case`max_completion_tokens`:{let e=wo(i);e!==null&&(r.max_tokens=e);break}case`tools`:G(i).length>0&&(r.tools=oo(G(i)));break;case`tool_choice`:case`parallel_tool_calls`:{let t=Eo(e.tool_choice,e.parallel_tool_calls);t===null?delete r.tool_choice:r.tool_choice=t;break}case`stream`:i===!0&&(r.stream=!0);break;case`stream_options`:break;case`stop`:{let e=To(i);e!==null&&(r.stop_sequences=e);break}case`temperature`:case`top_p`:(Ya(n)||t===`temperature`&&i===1)&&(r[t]=i);break;case`top_k`:Ya(n)&&(r.top_k=i);break;case`thinking`:jo(e,r,i,n);break;case`reasoning_effort`:Mo(r,i,n);break;case`user`:{let e=K(i);e!==null&&Co(e)&&(r.metadata={user_id:e});break}case`metadata`:U(i)&&i.user_id!==null&&i.user_id!==void 0&&(r.metadata={user_id:i.user_id});break;case`cache_control`:U(i)&&(r.cache_control=i)}}return r.messages=t,r.tools===void 0&&Fo(e)&&(r.tools=[so]),r}function Fo(e){return G(e.messages).some(e=>`tool_calls`in W(e))}function Io(e){let t=W(e),n=G(t.messages),r=0;for(;r<n.length&&W(n[r]).role===`system`;)r+=1;let i=n.slice(0,r).map(e=>W(e)),a=Po(t,yo(ua(n.slice(r).map(e=>W(e))))),o=bo(i);if(o.length>0&&(a.system=o),a.max_tokens===void 0){let e=W(a.thinking).budget_tokens;a.max_tokens=typeof e==`number`?e+eo:eo}return a}function Lo(e){let t=``,n=[],r=null;for(let[i,a]of e.entries()){let e=W(a),o=K(e.type)??``;if(o===`text`)t+=K(e.text)??``;else if(o===`tool_use`||o===`server_tool_use`){let t={id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.input??{})},index:i};U(e.caller)&&(t.caller=e.caller),n.push(t)}else(o===`thinking`||o===`redacted_thinking`)&&(r??=[],r.push(e))}let i=null;if(r!==null){i=``;for(let e of r){let t=e.thinking;typeof t==`string`&&(i+=t)}}return{content:t===``?null:t,role:`assistant`,...n.length>0?{tool_calls:n}:{},provider_specific_fields:{citations:null,thinking_blocks:r},...r===null?{}:{thinking_blocks:r},...i===null?{}:{reasoning_content:i}}}function Ro(e){let t=W(e),n=t.error;if(n!=null)throw new H(K(W(n).message)??JSON.stringify(n)??String(n),{status:xi(n)});let r=t.content;if(!Array.isArray(r))throw Error(`upstream returned a response with no 'content' array. Raw keys: ${Object.keys(t).join(`, `)}`);return{id:Va(),created:li(),...t.model===void 0?{}:{model:t.model},object:`chat.completion`,choices:[{finish_reason:Ua(t.stop_reason),index:0,message:Lo(G(r))}],usage:Ga(W(t.usage))}}var zo=class{#e;#t;#n=null;#r=null;#i=!1;#a=!1;#o=!1;#s=!1;#c=null;#l=-1;#u=``;#d=``;constructor(){this.#e=Va(),this.#t=li()}translateFrame(e){if(this.#o)return[];switch(K(e.type)??``){case`message_start`:return this.#f(e);case`content_block_start`:return this.#p(e);case`content_block_delta`:return this.#m(e);case`content_block_stop`:return this.#h();case`message_delta`:return this.#g(e);case`message_stop`:return this.#o=!0,[];case`error`:throw new H(K(W(e.error).message)??JSON.stringify(e),{status:500});default:return[]}}flush(){return this.#s||(this.#s=!0,this.#r===null||this.#i)?[]:(this.#i=!0,[this.#_({},{usage:Ga(this.#r,{fromStreamBuilder:!0})})])}#f(e){let t=W(e.message),n=K(t.model);n!==null&&(this.#n=n);let r=t.usage;return U(r)&&(this.#r=Ka(this.#r,r)),[]}#p(e){let t=W(e.content_block),n=K(t.type)??``;if(this.#c=n,this.#u=``,this.#d=``,n===`text`){let e=K(t.text)??``;return e===``?[]:[this.#_({content:e})]}if(n===`tool_use`||n===`server_tool_use`){this.#l+=1;let e={id:t.id,function:{arguments:``,name:t.name},type:`function`,index:this.#l};return U(t.caller)&&(e.caller=t.caller),[this.#_({content:``,tool_calls:[e]})]}if(n===`redacted_thinking`){let e=[{type:`redacted_thinking`,data:t.data}];return[this.#_({content:``,thinking_blocks:e,provider_specific_fields:{thinking_blocks:e}})]}return[]}#m(e){let t=W(e.delta),n=K(t.type)??``;if(n===`text_delta`){let e=K(t.text)??``;return e===``?[]:[this.#_({content:e})]}if(n===`thinking_delta`){let e=K(t.thinking)??``;if(e===``)return[];this.#d+=e;let n=[{type:`thinking`,thinking:e}];return[this.#_({reasoning_content:e,thinking_blocks:n,provider_specific_fields:{thinking_blocks:n},content:``})]}if(n===`signature_delta`){let e=K(t.signature)??``;if(e===``)return[];let n=[{type:`thinking`,thinking:this.#d,signature:e}];return[this.#_({reasoning_content:``,thinking_blocks:n,provider_specific_fields:{thinking_blocks:n},content:``})]}if(n===`input_json_delta`){if(this.#c!==`tool_use`&&this.#c!==`server_tool_use`)return[];let e=K(t.partial_json)??``;return this.#u+=e,[this.#_({content:``,tool_calls:[{function:{arguments:e},type:`function`,index:this.#l}]})]}return[]}#h(){let e=(this.#c===`tool_use`||this.#c===`server_tool_use`)&&this.#u===``;return this.#c=null,e?[this.#_({content:``,tool_calls:[{function:{arguments:`{}`},type:`function`,index:this.#l}]})]:[]}#g(e){let t=e.usage;U(t)&&(this.#r=Ka(this.#r,t));let n=Ua(W(e.delta).stop_reason??`stop`);return[this.#_({},{finishReason:n})]}#_(e,t={}){let n=this.#a?{...e}:{...e,role:`assistant`};this.#a=!0;let r={index:0,delta:n};t.finishReason!==void 0&&(r.finish_reason=t.finishReason);let i={id:this.#e,object:`chat.completion.chunk`,created:this.#t,...this.#n===null?{}:{model:this.#n},choices:[r]};return t.usage!==void 0&&(i.usage=t.usage),i}};async function*Bo(e){let t=new zo;for await(let n of e)for(let e of t.translateFrame(W(n)))yield e;for(let e of t.flush())yield e}var Vo=class{inbound=`openai`;upstream=`anthropic`;translateRequest(e){return Io(e)}translateResponse(e){return Ro(e)}bridgeFrames(e){return Bo(e)}usageFromFrame(e){let t=e.usage;return U(t)?t:null}errorEnvelope(e,t){return Za(e,t)}},Ho=class{inbound=`openai`;upstream=`openai`;translateRequest(e){return e}translateResponse(e){return e}async*bridgeFrames(e){for await(let t of e)yield t}usageFromFrame(e){let t=e.usage;return U(t)?t:null}errorEnvelope(e,t){return Ba(e,t)}};function Uo(e){let t=e;if(U(t.usage))return t.usage;let n=t.response;return U(n)&&U(n.usage)?n.usage:null}var Wo=new Set([`text`,`image_url`,`input_audio`,`audio_url`,`document`,`guarded_text`,`grounding_source`,`query`,`video_url`,`file`,`thinking`,`redacted_thinking`]),Go=new Set([`encrypted_content`,`redacted_thinking`]),Ko=new Set;function qo(e){return typeof e==`string`?e:G(e).flatMap(e=>{if(typeof e==`string`)return[e];let t=W(e);if(t.type===`input_file`){let e={},n=t.file_id||t.file_url;n!=null&&(e.file_id=n),t.file_data!=null&&(e.file_data=t.file_data);let r={type:`file`,file:e};return`cache_control`in t&&(r.cache_control=t.cache_control),[r]}if(t.type===`input_image`){let e={type:`image_url`,image_url:{url:q(t.image_url),detail:t.detail??`auto`}};return`cache_control`in t&&(e.cache_control=t.cache_control),[e]}if(t.type===`encrypted_content`)return t.encrypted_content==null?[]:[{type:`text`,text:String(t.encrypted_content)}];let n=t.text;if(n==null)return[];let r={type:Jo(q(t.type)),text:n};return`cache_control`in t&&(r.cache_control=t.cache_control),[r]})}function Jo(e){if(e.startsWith(`input_`)){let t=e.slice(6);return t===`audio`?`input_audio`:Wo.has(t)?t:`text`}return e===`tool_result`||e===`output_text`?`text`:Wo.has(e)?e:`text`}function Yo(e){let t=e.arguments;if(!t&&e.type===`custom_tool_call`){let n=q(e.input);t=n===``?``:JSON.stringify({content:n})}return[{role:`assistant`,content:null,tool_calls:[{id:q(e.call_id??e.id),type:`function`,function:{name:q(e.name),arguments:String(t??``)},index:0}]}]}function Xo(e){let t=q(e.call_id);return t===``?[]:[{role:`tool`,content:Zo(e.output),tool_call_id:t}]}function Zo(e){if(e==null)return``;if(typeof e==`string`)return e;if(Array.isArray(e)){let t=[],n=[];for(let r of e){let e=W(r),i=e.type;if(i===`input_text`||i===`output_text`||i===`text`){let r=e.text;typeof r==`string`&&r!==``&&(n.push(r),t.push({type:`text`,text:r}))}else if(i===`input_image`||i===`image_url`){let n=e.image_url??e.url;if(U(n)){let e=n.url;typeof e==`string`&&e!==``&&t.push({type:`image_url`,image_url:{url:e}})}else typeof n==`string`&&n!==``&&t.push({type:`image_url`,image_url:{url:n}})}}if(t.some(e=>W(e).type===`image_url`))return t;if(n.length>0)return n.join(``)}try{return JSON.stringify(e)}catch{return String(e)}}function Qo(e){return[`function_call_output`,`custom_tool_call_output`,`web_search_call`,`computer_call_output`,`tool_result`].includes(q(e.type))}function $o(e){return q(e.type)===`function_call`||q(e.type)===`custom_tool_call`}function es(e,t){let n=[];if(typeof t==`string`&&t!==``&&n.push({role:`system`,content:t}),typeof e==`string`)return n.push({role:`user`,content:e}),n;for(let t of G(e)){let e=W(t);if($o(e)){let t=Yo(e),r=n[n.length-1];if(r!==void 0&&r.role===`assistant`){n[n.length-1]={...r,tool_calls:[...Array.isArray(r.tool_calls)?r.tool_calls:[],...t[0]?.tool_calls]};continue}n.push(...t);continue}if(Qo(e)){n.push(...Xo(e));continue}if(e.type===`reasoning`){n.push(...cs(e));continue}let r=e.content;if(r==null)continue;let i=ns(e),a=i,o=qo(r),s=n[n.length-1];i===`assistant`&&s?.role===`assistant`&&Array.isArray(s.tool_calls)?n[n.length-1]={...s,content:ts(s.content,o)}:n.push({role:a,content:o})}return fs(n)}function ts(e,t){if(e==null||e===``)return t;if(t==null||t===``)return e;if(typeof e==`string`&&typeof t==`string`)return e+t;let n=typeof e==`string`?[{type:`text`,text:e}]:G(e),r=typeof t==`string`?[{type:`text`,text:t}]:G(t);return[...n,...r]}function ns(e){return q(e.role)===``?`user`:q(e.role)}function rs(e){return as(e.content)??os(e.summary)}function is(e,t){let n=e.flatMap(e=>{let n=W(e);if(t.has(q(n.type)))return[];let r=n.text;return typeof r==`string`&&r.trim()!==``?[r.trim()]:[]});return n.length>0?n.join(`
|
|
17
|
-
`):null}function
|
|
18
|
-
`):null,a=t.flatMap(e=>G(e.thinking_blocks));return{...e,...i===null?{}:{reasoning_content:i},...a.length>0?{thinking_blocks:[...a,...G(e.thinking_blocks)]}:{}}}function fs(e){let t=[],n=[];for(let r of e){if(us(r)){n.push(r);continue}if(n.length>0){if(r.role===`assistant`){t.push(ds(r,n)),n=[];continue}t.push(...n),n=[]}t.push(r)}return t.push(...n),t}function ps(e){if(e==null)return null;if(typeof e==`string`)return e;let t=W(e),n=W(t.function);if(U(t.function)&&q(n.name)!==``)return t;let r=q(t.type);if(r===`auto`)return`auto`;if(r===`none`)return`none`;if(r===`required`||r===`tool`||r===`any`)return`required`;if(r===`function`){let e=q(t.name);return e===``?`required`:{type:`function`,function:{name:e}}}if(r===`custom`){let e=W(t.custom),n=q(t.name)===``?q(e.name):q(t.name);return n===``?`required`:{type:`function`,function:{name:n}}}return e}function ms(e){let t=[],n=null,r=G(e);for(let e=0;e<r.length;e++){let i=W(r[e]),a=q(i.type);if(a===`mcp`)t.push(i);else if(a===`web_search_preview`||a===`web_search`)n={...i.search_context_size==null?{}:{search_context_size:i.search_context_size},...i.user_location==null?{}:{user_location:i.user_location}};else if(a===`function`){let n=i.parameters,r=ba(n);if(r===null&&n!=null)throw new H(`Invalid type for tools[${String(e)}].parameters: expected an object, but got ${typeof n} instead.`,{status:400});let a=r??{type:`object`};t.push({type:`function`,function:{name:q(i.name),description:q(i.description),parameters:ya(Object.keys(a).length>0&&`type`in a?a:{...a,type:`object`}),strict:i.strict===!0},...Object.fromEntries([`cache_control`,`defer_loading`,`allowed_callers`,`input_examples`].filter(e=>e in i).map(e=>[e,i[e]])),...i.eager_input_streaming!==null&&i.eager_input_streaming!==void 0?{eager_input_streaming:i.eager_input_streaming}:{}})}}return{tools:t,webSearchOptions:n}}function hs(e){let t=W(W(e).format);return q(t.type)===`json_schema`?{type:`json_schema`,json_schema:{name:t.name??`response_schema`,schema:t.schema??{},strict:t.strict??!1}}:q(t.type)===`json_object`?{type:`json_object`}:null}function gs(e){let t=e,{tools:n,webSearchOptions:r}=ms(t.tools??[]),i=hs(t.text),a=W(t.reasoning).effort,o=typeof a==`string`?a:null,s={messages:es(t.input,t.instructions),model:t.model??null,tool_choice:ps(t.tool_choice),tools:n,top_p:t.top_p??null,user:t.user??null,temperature:t.temperature??null,parallel_tool_calls:t.parallel_tool_calls??null,max_tokens:t.max_output_tokens??null,stream:t.stream===!0,safety_identifier:t.safety_identifier??null,web_search_options:r,response_format:i,reasoning_effort:o},c=Object.fromEntries(Object.entries(s).filter(([,e])=>e!==null));return G(c.tools).length===0?Object.fromEntries(Object.entries(c).filter(([e])=>e!==`tool_choice`&&e!==`tools`&&e!==`parallel_tool_calls`)):c}var _s={stop_sequence:`stop`,end_turn:`stop`,max_tokens:`length`,tool_use:`tool_calls`,refusal:`content_filter`,compaction:`length`,COMPLETE:`stop`,ERROR_TOXIC:`content_filter`,ERROR:`stop`,eos_token:`stop`,eos:`stop`,STOP:`stop`,MAX_TOKENS:`length`,SAFETY:`content_filter`,RECITATION:`content_filter`,FINISH_REASON_UNSPECIFIED:`stop`,MALFORMED_FUNCTION_CALL:`stop`,LANGUAGE:`content_filter`,OTHER:`content_filter`,BLOCKLIST:`content_filter`,PROHIBITED_CONTENT:`content_filter`,SPII:`content_filter`,IMAGE_SAFETY:`content_filter`,IMAGE_PROHIBITED_CONTENT:`content_filter`,TOO_MANY_TOOL_CALLS:`stop`,MALFORMED_RESPONSE:`stop`,NO_IMAGE:`content_filter`,IMAGE_RECITATION:`content_filter`,IMAGE_OTHER:`content_filter`,ESCALATION:`content_filter`,UNEXPECTED_TOOL_CALL:`stop`,MISSING_THOUGHT_SIGNATURE:`stop`,network_error:`stop`,sensitive:`content_filter`,guardrail_intervened:`content_filter`,stop:`stop`,length:`length`,tool_calls:`tool_calls`,function_call:`function_call`,content_filter:`content_filter`,content_filtered:`content_filter`,error:`stop`};function vs(e,t=()=>{}){let n=_s[e];return n===void 0?(t(e),`stop`):n}function ys(e){let t=W(e.message),n=Array.isArray(t.tool_calls)?t.tool_calls.map(e=>Hi(W(e))):null;n!==null&&(n=Wi(n));let{reasoningContent:r,content:i}=zi(t),a={content:i,role:t.role==null?`assistant`:String(t.role),tool_calls:n};r!==null&&(a.reasoning_content=r);let o=K(e.finish_reason);if(o===null){let t=e.finish_details;o=typeof t==`string`&&t!==``?t:`stop`}return o===`stop`&&n!==null&&n.length>0&&(o=`tool_calls`),{finish_reason:vs(o),message:a}}function bs(e){let t=W(e),n=e=>typeof e==`number`&&Number.isFinite(e)?e:null,r=n(t.completion_tokens)??0,i=n(t.prompt_tokens)??0,a=n(t.total_tokens)??0,o=U(t.completion_tokens_details)?{...t.completion_tokens_details}:null,s=n(t.reasoning_tokens);if(s!==null&&(o===null&&(o={}),n(o.reasoning_tokens)===null&&(o.reasoning_tokens=s),n(o.text_tokens)===null&&n(t.completion_tokens)!==null)){let e=r-s;o.image_tokens&&(e-=Number(o.image_tokens)),o.audio_tokens&&(e-=Number(o.audio_tokens)),o.text_tokens=Math.max(0,e)}let c=U(t.prompt_tokens_details)?{...t.prompt_tokens_details}:null,l=t.prompt_cache_hit_tokens,u=t.cache_read_input_tokens,d=typeof l==`number`?l:typeof u==`number`?u:null;if(d!==null&&(c===null&&(c={}),c.cached_tokens=d),c!==null)for(let e of[`audio_tokens`,`text_tokens`,`image_tokens`,`video_tokens`])c[e]===void 0&&(c[e]=null);if(o!==null)for(let e of[`text_tokens`,`image_tokens`,`video_tokens`,`accepted_prediction_tokens`,`rejected_prediction_tokens`])o[e]===void 0&&(o[e]=null);let f={completion_tokens:r,prompt_tokens:i,total_tokens:a,completion_tokens_details:o,prompt_tokens_details:c},p=new Set([`prompt_tokens`,`completion_tokens`,`total_tokens`,`reasoning_tokens`,`prompt_tokens_details`,`completion_tokens_details`,`server_tool_use`,`cost`]);for(let[e,n]of Object.entries(t))p.has(e)||(f[e]=n);let m=t.server_tool_use;m!=null&&(f.server_tool_use=m);let h=t.cost;return h!=null&&(f.cost=h),f}function xs(e){let t=e.error;if(t!=null){let e=W(t);throw new H(typeof e.message==`string`?e.message:JSON.stringify(t),{status:xi(t)})}let n=e.choices;if(!Array.isArray(n)||n.length===0)throw Error(`LiteLLM: provider returned a response with no 'choices'. Raw keys: ${Object.keys(e).join(`, `)}`);let r={choices:n.map(e=>ys(W(e)))};return e.usage!=null&&(r.usage=bs(e.usage)),r}function Ss(e){return e===`length`||e===`max_tokens`||e===`content_filter`?`incomplete`:`completed`}function Cs(e){return e===`content_filter`?`content_filter`:`max_output_tokens`}function ws(e){return typeof e==`string`?e:G(e).map(e=>typeof e==`string`?e:K(W(e).text)??``).join(``)}function Ts(e){if(!U(e))return null;let t=oi(e.prompt_tokens)??0,n=oi(e.completion_tokens)??0,r=oi(e.total_tokens)??t+n,i=W(e.prompt_tokens_details),a={},o=oi(i.cached_tokens);o!==null&&(a.cached_tokens=o);let s=oi(i.text_tokens);s!==null&&(a.text_tokens=s);let c=W(e.completion_tokens_details),l={},u=oi(c.reasoning_tokens);return u!==null&&u>0&&(l.reasoning_tokens=u),{input_tokens:t,...Object.keys(a).length>0?{input_tokens_details:a}:{},output_tokens:n,...Object.keys(l).length>0?{output_tokens_details:l}:{},total_tokens:r}}function Es(e,t){let n=W(e.function);return{type:`function_call`,id:t,call_id:K(e.id)??`call_${ci()}`,name:K(n.name)??``,arguments:K(n.arguments)??``,status:`completed`,namespace:null}}function Ds(e,t,n,r,i){let a=t===`in_progress`,o=e.requestEcho??{};return{id:e.id,created_at:e.created,error:null,incomplete_details:t===`incomplete`?{reason:Cs(i)}:null,instructions:a?o.instructions??null:null,metadata:a?null:{},...e.model===void 0?{}:{model:e.model},object:`response`,output:n,parallel_tool_calls:a,temperature:a?o.temperature??null:0,tool_choice:`auto`,tools:a&&Array.isArray(o.tools)?o.tools:[],top_p:a?o.top_p??1:null,max_output_tokens:null,previous_response_id:null,reasoning:a?{effort:null,summary:null}:null,status:t,text:a?o.text??null:{},truncation:a?o.truncation??null:null,usage:r,user:a?o.user??null:null,store:a?!0:null}}function Os(e,t){let n=W(G(e.choices)[0]),r=W(n.message),i=K(n.finish_reason),a=ws(r.content),o=G(r.tool_calls),s=K(r.reasoning_content),c=[];s!==null&&s!==``&&c.push({type:`reasoning`,id:`rs_${ci()}`,status:Ss(i),role:`assistant`,content:[{type:`output_text`,text:s,annotations:[]}],phase:null}),r.content!==null&&r.content!==void 0&&c.push({type:`message`,id:`msg_${ci()}`,status:Ss(i),role:`assistant`,content:[{type:`output_text`,text:a,annotations:[]}],phase:null});for(let e of o)c.push(Es(W(e),`fc_${ci()}`));return Ds(t,Ss(i),c,Ts(e.usage),i)}function ks(e){let t=W(e),n=K(t.model);return Os(xs(t),{id:`resp_${ci()}`,created:li(),...n===null?{}:{model:n}})}function As(e){let t=e.error;if(t)throw new H(typeof t!=`object`||!t||Array.isArray(t)?String(t):typeof W(t).message==`string`?W(t).message:JSON.stringify(t),{status:xi(t)});let n={choices:(Array.isArray(e.choices)?e.choices:[]).map(e=>{let t=W(e),n=t.finish_reason,r=W(t.delta);return{finish_reason:n?vs(String(n)):null,index:typeof t.index==`number`?t.index:0,delta:{content:r.content==null?null:String(r.content),role:r.role==null?null:String(r.role),...r.reasoning_content==null?{}:{reasoning_content:String(r.reasoning_content)},tool_calls:Array.isArray(r.tool_calls)?r.tool_calls.map((e,t)=>{let n={...W(e)};return n.index===void 0&&(n.index=t),n.type===void 0&&(n.type=`function`),n}):null}}})};return typeof e.model==`string`&&(n.model=e.model),`usage`in e&&e.usage!=null&&(n.usage=e.usage),n}var js=10;function Ms(e){let t={};for(let[n,r]of Object.entries(e))r!==null&&(t[n]=r);return t}function Ns(e){if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var Ps=class{#e=0;#t=!1;#n=!1;#r=`msg_${ci()}`;#i=0;#a=``;#o=1;#s=new Map;#c=null;#l=null;#u=null;#d=``;#f;#p=null;constructor(e){this.#f=e}#m(){return this.#p===null?this.#f:{...this.#f,model:this.#p}}translateFrame(e){if(this.#n)return[];let t=K(e.model);t!==null&&(this.#p=t);let n=[];if(!this.#t){this.#t=!0;let e=Ds(this.#m(),`in_progress`,[],null,null);n.push(this.#S({type:`response.created`,response:e})),n.push(this.#S({type:`response.in_progress`,response:e})),n.push(...this.#h())}U(e.usage)&&(this.#l=e.usage);let r=W(G(e.choices)[0]),i=W(r.delta),a=i.reasoning_content,o=typeof a==`string`&&a!==``?a:null;if(o!==null){n.push(...this.#g(o));let e=i.content;typeof e==`string`&&e!==``&&(this.#a+=e);let t=K(r.finish_reason);return t!==null&&t!==``&&(this.#c=t),n}let s=i.content;typeof s==`string`&&s!==``&&(this.#a+=s,n.push(this.#S({type:`response.output_text.delta`,item_id:this.#r,output_index:this.#i,content_index:0,delta:s})));for(let e of G(i.tool_calls))n.push(...this.#_(W(e)));let c=K(r.finish_reason);return c!==null&&c!==``&&(this.#c=c),n}flush(){if(!this.#t||this.#n)return[];this.#n=!0;let e=[];for(let t of this.#b())e.push(...this.#y(t));e.push(...this.#v());let t=Ss(this.#c);return e.push(this.#S({type:`response.completed`,response:Ds(this.#m(),t,this.#x(),Ts(this.#l),this.#c)})),e}#h(){return[this.#S({type:`response.output_item.added`,output_index:this.#i,item:{type:`message`,id:this.#r,status:`in_progress`,role:`assistant`,content:[]}}),this.#S({type:`response.content_part.added`,item_id:this.#r,output_index:this.#i,content_index:0,part:{type:`output_text`,text:``,annotations:[]}})]}#g(e){return this.#u===null&&(this.#u=`rs_${ci()}`),this.#d+=e,[this.#S({type:`response.reasoning_summary_text.delta`,item_id:this.#u,output_index:0,delta:e})]}#_(e){let t=oi(e.index)??0,n=W(e.function),r=this.#s.get(t),i=[];if(r===void 0){let a=K(e.id)??`call_${ci()}`;r={itemId:`fc_${a}`,outputIndex:this.#o,callId:a,name:K(n.name)??``,args:``},this.#o+=1,this.#s.set(t,r),i.push(this.#S({type:`response.output_item.added`,output_index:r.outputIndex,item:{type:`function_call`,id:r.itemId,call_id:r.callId,name:r.name,arguments:``,status:`in_progress`}}))}let a=K(n.name);a!==null&&a!==``&&r.name===``&&(r.name=a);let o=Ns(n.arguments);if(o!==``){r.args+=o;for(let e=0;e<o.length;e+=js)i.push(this.#S({type:`response.function_call_arguments.delta`,item_id:r.itemId,output_index:r.outputIndex,delta:o.slice(e,e+js)}))}return i}#v(){let e=this.#r,t=this.#i,n={type:`output_text`,text:this.#a,annotations:[]};return[this.#S({type:`response.output_text.done`,item_id:e,output_index:t,content_index:0,text:this.#a}),this.#S({type:`response.content_part.done`,item_id:e,output_index:t,content_index:0,part:n}),this.#S({type:`response.output_item.done`,output_index:t,item:{type:`message`,id:e,status:`completed`,role:`assistant`,content:[n]}})]}#y(e){return[this.#S({type:`response.function_call_arguments.done`,item_id:e.itemId,output_index:e.outputIndex,arguments:e.args}),this.#S({type:`response.output_item.done`,output_index:e.outputIndex,item:{type:`function_call`,id:e.itemId,call_id:e.callId,name:e.name,arguments:e.args,status:`completed`}})]}#b(){return[...this.#s.values()].sort((e,t)=>e.outputIndex-t.outputIndex)}#x(){let e=[];this.#u!==null&&e.push({type:`reasoning`,id:this.#u,status:Ss(this.#c),role:`assistant`,content:[{type:`output_text`,text:this.#d,annotations:[]}]}),this.#a!==``&&e.push({type:`message`,id:this.#r,status:`completed`,role:`assistant`,content:[{type:`output_text`,text:this.#a,annotations:[]}]});for(let t of this.#b())e.push({type:`function_call`,id:t.itemId,call_id:t.callId,name:t.name,arguments:t.args,status:`completed`});return e}#S(e){this.#e+=1;let t={...e,sequence_number:this.#e};return e.response!==void 0&&(t.response=Ms(e.response)),t}},Fs=class{inbound=`openai-responses`;upstream=`openai`;translateRequest(e){return gs(e)}translateResponse(e){return ks(e)}async*bridgeFrames(e,t,n){let r=new Ps({id:`resp_${ci()}`,created:li(),...U(n)?{requestEcho:n}:{}});for await(let t of e)for(let e of r.translateFrame(As(t)))yield e;for(let e of r.flush())yield e}usageFromFrame(e){return Uo(e)}errorEnvelope(e,t){return Ba(e,t)}};function Is(e){return Array.isArray(e)?e.map(e=>{if(!U(e)||e.type!==`reasoning`||`summary`in e)return e;let t=e.content,n=typeof t==`string`?t:``;return{...e,summary:n.length>100?n.slice(0,100):n}}):e}function Ls(e){let t=e;return{...t,input:Is(t.input)}}var Rs=[`error`,`incomplete_details`,`instructions`,`metadata`,`model`,`object`,`parallel_tool_calls`,`temperature`,`tool_choice`,`tools`,`top_p`,`max_output_tokens`,`previous_response_id`,`reasoning`,`status`,`text`,`truncation`,`usage`,`user`,`store`],zs=[`input_tokens_details`,`output_tokens_details`,`cost`],Bs={audio_tokens:null,cached_tokens:0,cached_tokens_details:null,image_tokens:null,text_tokens:null,video_tokens:null},Vs={audio_tokens:null,reasoning_tokens:null,text_tokens:null};function Hs(e,t){let n={...e};for(let[e,r]of Object.entries(t))e in n||(n[e]=r);return n}function Us(e){let t=e.usage;if(!U(t))return;let n={...t};for(let e of zs)e in n||(n[e]=null);let r=n.input_tokens_details;U(r)&&(n.input_tokens_details=Hs(r,Bs));let i=n.output_tokens_details;U(i)&&(n.output_tokens_details=Hs(i,Vs)),e.usage=n}function Ws(e){let t=e.tools;if(!Array.isArray(t))return;let n=null;for(let[e,r]of t.entries()){if(!U(r)||r.type!==`function`)continue;let i=!(`strict`in r),a=!(`defer_loading`in r);if(!i&&!a)continue;let o={...r,...i?{strict:null}:{},...a?{defer_loading:null}:{}};(n??=[...t])[e]=o}n!==null&&(e.tools=n)}function Gs(e){let t=e.output;if(!Array.isArray(t))return;let n=null;for(let[e,r]of t.entries()){if(!U(r))continue;let i=r.type===`function_call`&&!(`namespace`in r)?`namespace`:r.type===`message`&&!(`phase`in r)?`phase`:null;i!==null&&((n??=[...t])[e]={...r,[i]:null})}n!==null&&(e.output=n)}function Ks(e){for(let t of Rs)t in e||(e[t]=null);return Ws(e),Gs(e),Us(e),e}function qs(e){return Ks({...e})}function Js(e){let t=e.error;if(U(t)&&t.code===null)return{...e,error:{...t,code:`unknown_error`}};let n=e.response;if(U(n)){let t=n.error;if(U(t)&&t.code===null)return{...e,response:{...n,error:{...t,code:`unknown_error`}}}}return null}function Ys(e){if(!U(e))return e;let t=!1;for(let n of Object.values(e))if(n===null){t=!0;break}if(!t)return e;let n={};for(let[t,r]of Object.entries(e))r!==null&&(n[t]=r);return n}function Xs(e){let t=e.response;if(!U(t))return e;let n={...t},r=!1;for(let[e,i]of Object.entries(t))i===null&&(delete n[e],r=!0);let i=n.tools;if(Array.isArray(i)){let e=i.map(Ys);e.some((e,t)=>e!==i[t])&&(n.tools=e,r=!0)}return r?{...e,response:n}:e}var Zs=class{inbound=`openai-responses`;upstream=`openai-responses`;translateRequest(e){return Ls(e)}translateResponse(e){return qs(e)}async*bridgeFrames(e){for await(let t of e){let e=t;yield Xs(Js(e)??e)}}usageFromFrame(e){return Uo(e)}errorEnvelope(e,t){return Ba(e,t)}},Qs={anthropicToAnthropic:new na,anthropicToChatCompletions:new Ia,chatCompletionsToAnthropic:new Vo,chatCompletionsToChatCompletions:new Ho,responsesToResponses:new Zs,responsesToChatCompletions:new Fs},$s=class{anthropicToAnthropic(e){return this.#e(`anthropicToAnthropic`,e)}anthropicToChatCompletions(e){return this.#e(`anthropicToChatCompletions`,e)}chatCompletionsToAnthropic(e){return this.#e(`chatCompletionsToAnthropic`,e)}chatCompletionsToChatCompletions(e){return this.#e(`chatCompletionsToChatCompletions`,e)}responsesToResponses(e){return this.#e(`responsesToResponses`,e)}responsesToChatCompletions(e){return this.#e(`responsesToChatCompletions`,e)}#e(e,t){return new ai(Qs[e],t??{},e)}};function ec(){return new $s}var tc={400:`invalid_request_error`,401:`authentication_error`,403:`permission_error`,404:`not_found_error`,413:`request_too_large`,429:`rate_limit_error`,500:`api_error`,529:`overloaded_error`},nc={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`},rc=new Set([204,205,304]);function ic(e){return tc[e]??`api_error`}function ac(e){let t=nc[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t}function oc(e){let t;try{t=JSON.parse(e)}catch{return null}return V(t)?t:null}function sc(e){let t=e.type===`error`?e.error:void 0;return V(t)&&typeof t.type==`string`&&typeof t.message==`string`}function cc(e){let t=oc(e);if(t===null)return e;if(sc(t))return String(t.error.message);let n=t.detail;if(V(n)&&typeof n.message==`string`)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;return typeof i==`string`&&i!==``?i:e}function lc(e,t,n){let r=t===``||rc.has(e)?null:t;return new Response(r,{status:e,headers:{"content-type":n}})}function uc(e,t,n){let r=oc(t),i;if(r!==null&&sc(r))i={...r},n!==void 0&&r.request_id===void 0&&(i.request_id=n);else{let r={type:`error`,error:{type:ic(e),message:cc(t)}};n!==void 0&&(r.request_id=n),i=r}return lc(e,JSON.stringify(i),`application/json`)}function dc(e,t){let n={error:{message:cc(t),type:ac(e),param:null,code:String(e)}};return lc(e,JSON.stringify(n),`application/json`)}function fc(e,t,n,r){return e===`anthropic`?uc(t,n,r):dc(t,n)}function pc(e,t,n,r){return e===`anthropic`?uc(t,n,r):dc(t,n)}var mc={openai:`chat/completions`,anthropic:`messages`,"openai-responses":`responses`},hc={openai:`https://api.openai.com`,anthropic:`https://api.anthropic.com`,"openai-responses":`https://api.openai.com`};function gc(e){let t=e.provider,n=(e.apiBase??hc[t]).replace(/\/+$/,``),r=mc[t];return t===`anthropic`?n.endsWith(`/v1/messages`)?n:e.autoV1!==!1&&!/\/v\d+$/i.test(n)?`${n}/v1/${r}`:`${n}/${r}`:n.includes(r)?n:e.autoV1!==!1&&!/\/v\d+$/i.test(n)?`${n}/v1/${r}`:`${n}/${r}`}var _c=6e5,vc=12e4,yc=65536,bc=4096,xc=class{#e;#t;#n;#r;#i;#a;#o=new AbortController;#s=new AbortController;#c=null;constructor(e,t){this.#e=e,this.#t=t.inbound,this.#n=t.requestId,this.#r=t.fetchFn??fetch,this.#i=t.timeouts?.firstByteMs??_c,this.#a=t.timeouts?.idleMs??vc;let n=t.signal;n!==void 0&&(n.aborted?this.#o.abort():n.addEventListener(`abort`,()=>this.#o.abort(),{once:!0}))}abort(){this.#o.abort()}async send(){let e;try{this.#u(this.#i),e=await this.#r(this.#e.url,{method:`POST`,headers:this.#e.headers,body:JSON.stringify(this.#e.body),signal:AbortSignal.any([this.#o.signal,this.#s.signal])})}catch(e){if(this.#l(),this.#s.signal.aborted&&!this.#o.signal.aborted){let e=`upstream timeout: no response headers within ${String(this.#i)}ms`;return this.#f(504,e)}return this.#f(502,ar(e))}let t=e.body;if(t===null?this.#l():(this.#u(this.#a),t=this.#p(t)),!e.ok){let n=await Cc(t,yc),r=n.length<=bc?n:n.slice(0,bc);return{kind:`error`,status:e.status,response:fc(this.#t,e.status,r,this.#n)}}return{kind:`ok`,transport:{status:e.status,headers:or(e.headers),stream:t,text:()=>t===null?e.text():new Response(t).text()}}}#l(){this.#c!==null&&(clearTimeout(this.#c),this.#c=null)}#u(e){this.#l(),this.#c=setTimeout(()=>{this.#c=null,this.#s.abort()},e),this.#c.unref()}#d(){return new H(`upstream timeout: no data for ${String(this.#a)}ms`,{status:504})}#f(e,t){return{kind:`error`,status:e,response:pc(this.#t,e,t,this.#n)}}#p(e){let t=null;return new ReadableStream({start:async n=>{let r=e.getReader();t=r;let i=!1,a=()=>{try{n.close()}catch{}},o=e=>{try{n.error(e)}catch{}},s=e=>{i||(i=!0,this.#l(),o(e),r.cancel().catch(()=>{}))};if(this.#s.signal.aborted){s(this.#d());return}let c=()=>s(this.#d());this.#s.signal.addEventListener(`abort`,c,{once:!0});try{for(;;){let{done:e,value:t}=await r.read();if(i)return;if(e){this.#l(),a();return}this.#u(this.#a),n.enqueue(t)}}catch(e){this.#l(),i||o(e)}finally{this.#s.signal.removeEventListener(`abort`,c)}},cancel:e=>{this.#l(),t!==null&&t.cancel(e).catch(()=>{})}})}};function Sc(e){e!==null&&e.cancel().catch(()=>{})}async function Cc(e,t){if(e===null)return``;let n=e.getReader(),r=new TextDecoder(`utf-8`),i=``,a=0;try{for(;a<t;){let{done:e,value:t}=await n.read();if(e)break;a+=t.byteLength,i+=r.decode(t,{stream:!0})}return i+r.decode()}catch{return i}finally{n.cancel().catch(()=>{})}}var wc=new Set([`authorization`,`x-api-key`,`cookie`,`proxy-authorization`,`host`,`content-length`,`content-type`,`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`te`,`trailer`,`upgrade`,`expect`,`accept-encoding`,`x-real-ip`]),Tc=`sk-ant-oat`,Ec=`oauth-2025-04-20`,Dc="Missing Anthropic API Key - A call is being made to anthropic but no key is set either in the environment variables or via params. Please set `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in your environment vars";function Oc(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();wc.has(e)||e.startsWith(`proxy-`)||e.startsWith(`x-forwarded-`)||(t[n]=r)}return t}function kc(e,t){return e===void 0?t:e.split(`,`).map(e=>e.trim()).includes(t)?e:`${e}, ${t}`}function Ac(e,t){let n={...e},r=t,i=Object.keys(n).find(e=>e.toLowerCase()===`authorization`),a=i===void 0?``:n[i]??``;if(a.startsWith(`Bearer ${Tc}`)){r=a.replace(/^Bearer /,``);for(let e of Object.keys(n))(e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`)&&delete n[e];n.authorization=a,n[`anthropic-beta`]=kc(n[`anthropic-beta`],Ec),n[`anthropic-dangerous-direct-browser-access`]=`true`}if(r===void 0)throw new H(Dc,{status:401});let o=r.startsWith(Tc),s={"anthropic-version":`2023-06-01`,accept:`application/json`,"content-type":`application/json`};return o?s.authorization=`Bearer ${r}`:s[`x-api-key`]=r,{...n,...s}}function jc(e,t){let n={...e};return t!==void 0&&(n={...n,Authorization:`Bearer ${t}`}),!(`content-type`in n)&&!(`Content-Type`in n)&&(n={...n,"Content-Type":`application/json`}),n}function Mc(e,t,n){let r={...Oc(n),...t.headers??{}};return e===`anthropic`?Ac(r,t.apiKey):jc(r,t.apiKey)}var Nc=/<invoke\s+name=/g,Pc=2;function Fc(e,t){let n=Mc(e.provider,e,t??{});return{upstreamRequest:e=>({...e,headers:n})}}function Ic(e){return{clientRequest:t=>V(t.body)?{...t,body:{...t.body,model:e.modelName}}:t}}function Lc(e){return V(e.error)}function Rc(e,t){let n=t.name||t.modelName;switch(e){case`anthropicToChatCompletions`:return{clientResponse:e=>{let t=e;if(t.type===`message_start`){let r=t.message;return V(r)?{...t,message:{...r,model:n}}:e}return t.type===`message`?{...t,model:n}:e}};case`chatCompletionsToAnthropic`:return{clientResponse:e=>{let t=e;return Lc(t)?e:{...t,model:n}}};case`chatCompletionsToChatCompletions`:return{clientResponse:e=>{let t=e;return t.object===`chat.completion.chunk`?e:{...t,model:n}}};case`responsesToChatCompletions`:case`responsesToResponses`:return{clientResponse:e=>{let t=e;return Lc(t)?e:{...t,model:n}}}}}function zc(e,t){let n=er.indexOf(e),r=er.indexOf(t);return n<0||r<0||n<=r?e:t}function Bc(e){return{upstreamRequest:t=>{if(!V(t.body))return t;let n=t.body.reasoning_effort;if(typeof n!=`string`)return t;let r=zc(n,e);return r===n?t:{...t,body:{...t.body,reasoning_effort:r}}}}}function Vc(e){let t=0,n=0;return{clientResponse:r=>{let i=r;if(i.type!==`content_block_delta`)return r;let a=i.delta;if(!V(a)||a.type!==`thinking_delta`)return r;let o=a.thinking;if(typeof o!=`string`||o===``)return r;t+=o.length,Nc.lastIndex=0;for(let e=Nc.exec(o);e!==null;e=Nc.exec(o))n+=1;if(t>e&&n>=Pc)throw new H(`Upstream reasoning degraded: ${String(t)} reasoning chars containing ${String(n)} hand-written tool invocations and no tool_use block; stream aborted to avoid a long stall.`);return r}}}function Hc(){return{upstreamRequest:e=>{if(!e.stream||!V(e.body))return e;let t=e.body.stream_options;if(V(t)&&t.include_usage===!0)return e;let n={...V(t)?t:{},include_usage:!0};return{...e,body:{...e.body,stream_options:n}}}}}function Uc(){return{upstreamRequest:e=>{if(!V(e.body))return e;let t=e.body.tools;if(!Array.isArray(t)||t.length===0)return e;let n=!1,r=t.map(e=>{if(!V(e)||e.type!==`custom`)return e;let{type:t,...r}=e;return n=!0,r});return n?{...e,body:{...e.body,tools:r}}:e}}}function Wc(e,t){let n=[];(e===`anthropicToChatCompletions`||e===`chatCompletionsToChatCompletions`||e===`responsesToChatCompletions`)&&n.push(Hc()),e===`chatCompletionsToAnthropic`&&n.push(Uc()),e===`anthropicToChatCompletions`&&t.maxReasoningEffort!==void 0&&n.push(Bc(t.maxReasoningEffort));let r=t.thinkingGuardMaxChars??0;return(e===`anthropicToAnthropic`||e===`anthropicToChatCompletions`)&&r>0&&n.push(Vc(r)),n}function Gc(e){if(!V(e))return null;let t=ir(e.prompt_tokens),n=ir(e.completion_tokens);if(t===null&&n===null)return null;let r=V(e.prompt_tokens_details)?e.prompt_tokens_details:{};return{inputTokens:t??0,outputTokens:n??0,cacheReadInputTokens:ir(r.cached_tokens)??0,cacheCreationInputTokens:ir(r.cache_creation_tokens)??ir(e.cache_creation_input_tokens)??0}}function Kc(e){if(!V(e))return null;let t=ir(e.input_tokens),n=ir(e.output_tokens);if(t===null&&n===null)return null;let r=V(e.input_tokens_details)?e.input_tokens_details:{};return{inputTokens:t??0,outputTokens:n??0,cacheReadInputTokens:ir(r.cached_tokens)??0,cacheCreationInputTokens:0}}function qc(e){let t=ir(e.input_tokens),n=ir(e.output_tokens);if(t===null&&n===null)return null;let r=ir(e.cache_read_input_tokens),i=ir(e.cache_creation_input_tokens);return{inputTokens:(t??0)+(r??0)+(i??0),outputTokens:n??0,cacheReadInputTokens:r??0,cacheCreationInputTokens:i??0}}function Jc(e){return V(e)?e.prompt_tokens!==void 0||e.completion_tokens!==void 0?Gc(e):e.input_tokens_details!==void 0||e.output_tokens_details!==void 0?Kc(e):qc(e):null}var Yc=ec();function Xc(e){let t=null;try{t=new URL(gc(e)).hostname}catch{t=null}return t===null||t===``?`drop`:t!==`openai.com`&&!t.endsWith(`.openai.com`)?`preserve`:`drop`}function Zc(e,t,n){let r=t.rawPassthrough===!0,i=Yc[e]({...r?{translate:!1}:{},...e===`anthropicToChatCompletions`?{topK:Xc(t)}:{}});if(i.intercept(Fc(t,n)),i.intercept(Ic(t)),!r){e!==`anthropicToAnthropic`&&i.intercept(Rc(e,t));for(let n of Wc(e,t))i.intercept(n)}return i}async function Qc(e,t,n,r,i){let a;try{a=Zc(t,n,i.inboundHeaders)}catch(t){let n=gr(t)??500;return{kind:`error`,status:n,response:pc(e,n,ar(t),i.requestId)}}let o=a.begin(),s=await o.request({body:r});if(s.kind===`error`)return{kind:`error`,status:s.status,response:pc(e,s.status,s.message,i.requestId)};let c=await new xc({url:gc(n),...s.value},{inbound:e,requestId:i.requestId,signal:i.signal,timeouts:i.timeouts,fetchFn:i.fetchFn}).send();if(c.kind===`error`)return c;let l=c.transport;if(!$c(c.transport))try{let e=await c.transport.text();l={...c.transport,stream:null,text:()=>Promise.resolve(e)}}catch(t){let n=gr(t)??502;return{kind:`error`,status:n,response:pc(e,n,ar(t),i.requestId)}}let u;try{u=await o.response({status:l.status,headers:l.headers,body:l.stream,text:l.text})}catch(t){return Sc(l.stream),{kind:`error`,status:500,response:pc(e,500,ar(t),i.requestId)}}if(u.kind===`error`)return Sc(l.stream),{kind:`error`,status:u.status,response:pc(e,u.status,u.message,i.requestId)};let d=u.value;return`stream`in d?{kind:`ok`,sse:!0,stream:d.stream,collectUsage:()=>Jc(d.collectUsage())}:{kind:`ok`,sse:!1,body:d.body,usage:Jc(V(d.body)?d.body.usage:void 0)}}function $c(e){return(e.headers[`content-type`]??``).includes(`text/event-stream`)}function el(e,t,n){return n?e===`anthropic`?t===`anthropic`?`anthropicToAnthropic`:null:e===`openai-responses`?t===`openai-responses`?`responsesToResponses`:null:t===`openai`?`chatCompletionsToChatCompletions`:null:e===`anthropic`?t===`anthropic`?`anthropicToAnthropic`:t===`openai`?`anthropicToChatCompletions`:null:e===`openai-responses`?t===`openai`?`responsesToChatCompletions`:t===`openai-responses`?`responsesToResponses`:null:t===`openai`?`chatCompletionsToChatCompletions`:t===`anthropic`?`chatCompletionsToAnthropic`:null}function tl(e,t){return el(e,t.provider,t.rawPassthrough===!0)!==null}function nl(e){return e===`anthropic`?`Anthropic Messages`:e===`openai-responses`?`OpenAI Responses`:`OpenAI Chat Completions`}async function rl(e,t,n){return al(e,t,n,t.inbound_format===`anthropic`?`anthropic`:`openai`)}async function il(e,t,n){return al(e,t,n,`openai-responses`)}async function al(e,t,n,r){try{return await ol(e,t,n,r)}catch(e){return cl(e,r,n.requestId)}}async function ol(e,t,n,r){let i=e.rawPassthrough===!0,a=el(r,e.provider,i);if(a===null){let t=e.name||e.modelName;return{kind:`error`,status:400,response:pc(r,400,i?`Model '${t}' has rawPassthrough enabled (upstream '${e.provider}'): ${nl(r)} inbound requests cannot be forwarded as-is. Use a matching protocol or turn rawPassthrough off.`:`Model '${t}' (upstream '${e.provider}') does not accept ${nl(r)} inbound requests`,n.requestId)}}let o=await Qc(r,a,e,r===`anthropic`?sl(t,`inbound_format`):t,{signal:n.signal,requestId:n.requestId,inboundHeaders:n.inboundHeaders,timeouts:n.timeouts,fetchFn:n.deps.fetchFn});return o.kind===`error`?{kind:`error`,status:o.status,response:o.response}:o.sse?{kind:`ok`,status:200,sse:!0,body:o.stream,stream:o.stream,usage:null,collectUsage:o.collectUsage}:{kind:`ok`,status:200,sse:!1,body:o.body,usage:o.usage}}function sl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function cl(e,t,n){let r=gr(e)??500;return{kind:`error`,status:r,response:pc(t,r,ar(e),n)}}var ll=[`x-litellm-trace-id`,`x-litellm-session-id`],ul=new Set(ll),dl=/^x-.+-session-id$/,fl=[`thread-id`,`conversation_id`],pl=/^codex[-_ /]/i,ml=/^[a-zA-Z0-9_-]{8,}$/,hl=/^[a-zA-Z0-9_-]+$/,gl=`_session_`;function _l(e){let t=new Map;e.forEach((e,n)=>t.set(n.toLowerCase(),e));for(let e of ll){let n=t.get(e);if(n!==void 0&&ml.test(n))return n}let n=ul;for(let[e,r]of t)if(!n.has(e)&&dl.test(e)&&ml.test(r))return r;let r=t.get(`x-session-id`);if(r!==void 0&&ml.test(r))return r;for(let e of[`session-id`,`session_id`]){let n=t.get(e);if(n!==void 0&&ml.test(n))return n}let i=t.get(`user-agent`);if(i!==void 0&&pl.test(i))for(let e of fl){let n=t.get(e);if(n!==void 0&&ml.test(n))return n}return``}function vl(e){if(!V(e))return null;let t=e.metadata;return V(t)?bl(t.user_id):null}function yl(e,t){if(!V(e))return null;let n=e[t];return typeof n==`string`&&hl.test(n)?n:null}function bl(e){if(V(e))return yl(e,`session_id`);if(typeof e!=`string`)return null;if(e.startsWith(`{`))try{let t=yl(JSON.parse(e),`session_id`);if(t!==null)return t}catch{}let t=e.lastIndexOf(gl);return t===-1?null:yl({session_id:e.slice(t+9)},`session_id`)}var xl=10485760;function Sl(e){try{return JSON.parse(e)}catch{return e}}function Cl(e){for(let t of e.split(`
|
|
19
|
-
`)){let e=t.trim();if(!e.startsWith(`data: `))continue;let n;try{n=JSON.parse(e.slice(6))}catch{continue}let r=n.error;if(typeof r==`object`&&r&&typeof r.message==`string`)return{message:r.message,status:typeof r.status==`number`?r.status:200};if(typeof n.message==`string`&&typeof n.code==`string`&&!(`choices`in n)&&!(`type`in n))return{message:n.message,status:typeof n.status==`number`?n.status:200}}return null}var
|
|
13
|
+
`),this.take()}take(){let e=this.collected;return this.collected=[],e}},Nr=new TextEncoder;function Pr(e,t){let n=[];e!==null&&n.push(`event: ${e}`);for(let e of t.split(`
|
|
14
|
+
`))n.push(`data: ${e}`);return Nr.encode(`${n.join(`
|
|
15
|
+
`)}\n\n`)}function Fr(e,t={}){let n=e.type;return Pr((t.protocol===void 0||t.protocol===`anthropic`)&&typeof n==`string`?n:null,JSON.stringify(e))}function Ir(){return Pr(null,Ar)}async function*Lr(e,t){let n=(e,t)=>({event:e.event,data:e.data,done:t!==`anthropic`&&e.data===`[DONE]`}),r=e.getReader(),i=new TextDecoder,a=new Mr,o=!1;try{for(;;){let{done:e,value:o}=await r.read();if(e)break;for(let e of a.push(i.decode(o,{stream:!0}))){let r=n(e,t);if(yield r,r.done)return}}for(let e of a.push(i.decode())){let r=n(e,t);if(yield r,r.done)return}for(let e of a.flush()){let r=n(e,t);if(yield r,r.done)return}o=!0}finally{o||r.cancel().catch(()=>{})}}function Rr(e){let t;try{t=JSON.parse(e.data)}catch{return null}return typeof t!=`object`||!t||Array.isArray(t)?null:t}function zr(e,t){return Fr(e,{protocol:t})}function Br(e,t){let n=(e,t,n,r)=>e instanceof ReadableStream?e.pipeThrough(i(t,n,`upstream`,r)):e===null?null:t(e,r),r=(e,t,n,r)=>{if(e.kind===`error`)return e;let a=e.value;if(`stream`in a)return fr({...a,stream:a.stream.pipeThrough(i(t,n,`client`,r))});if(a.body===null||typeof a.body!=`object`)return e;let o=t(a.body,r);return fr(o===null?{...a,body:null}:{...a,body:o})},i=(e,t,n,r)=>{let i=new Mr,a=new TextDecoder,o=!1,s=(i,a)=>{if(t!==`anthropic`&&i.data===`[DONE]`){a.enqueue(Ir());return}let s=Rr({event:i.event,data:i.data,done:!1});if(s===null){a.enqueue(Pr(i.event,i.data));return}let c;try{c=e(s,r)}catch(e){if(o=!0,n===`upstream`){a.error(e);return}for(let n of yr(t,{message:_r(e)}))a.enqueue(Fr(n,{protocol:t}));a.terminate();return}c!==null&&a.enqueue(Fr(c,{protocol:t}))};return new TransformStream({transform(e,t){if(!o){for(let n of i.push(a.decode(e,{stream:!0})))if(s(n,t),o)return}},flush(e){if(!o){for(let t of i.push(a.decode()))if(s(t,e),o)return;for(let t of i.flush())if(s(t,e),o)return}}})},a=[],o=[];if(e.request!==void 0){let n=e.request;a.push((e,r)=>n(e,r,t))}if(e.clientRequest!==void 0){let n=e.clientRequest;a.push((e,r)=>r(n(e,t)))}if(e.upstreamRequest!==void 0){let n=e.upstreamRequest;a.push((e,r)=>{let i=r(e);return gr(i)?i.then(a):a(i);function a(e){return e.kind===`error`?e:fr(n(e.value,t))}})}if(e.response!==void 0){let n=e.response;o.push((e,r)=>n(e,r,t))}if(e.upstreamResponse!==void 0){let r=e.upstreamResponse;o.push((e,i)=>{let a=e;return i({...a,body:n(a.body,r,t.pair.upstream,t)})})}if(e.clientResponse!==void 0){let n=e.clientResponse;o.push((e,i)=>{let a=i(e);return gr(a)?a.then(e=>r(e,n,t.pair.inbound,t)):r(a,n,t.pair.inbound,t)})}return{requestLayers:a,responseLayers:o}}function Vr(e,t){let n=e=>(t,n)=>{let r;try{r=e.options.translate===!1?t.body:e.pair.translateRequest(t.body,e.options)}catch(e){return pr(hr(e)??500,_r(e))}let i={"content-type":`application/json`},a=r.stream===!0;return n({headers:i,body:r,stream:a})};return new vr([...t.specs.flatMap(e=>Br(e,t).requestLayers),n(t)]).run(e,e=>fr(e))}var Hr=class{stream;collectUsage=()=>this.#t;#e;#t=null;#n;#r;#i=!1;constructor(e){this.#e=e,this.#n=e.bridge(this.#a())[Symbol.asyncIterator](),this.#r=this.#o()[Symbol.asyncIterator]();let t=new F({objectMode:!0,highWaterMark:0,read:()=>{this.#r.next().then(e=>{e.done?t.push(null):t.push(e.value)},e=>{t.destroy(e instanceof Error?e:Error(String(e)))})},destroy:(e,t)=>{Promise.resolve(this.#r.return?.()).catch(()=>{}).then(()=>t())}});this.stream=F.toWeb(t)}async*#a(){for await(let e of Lr(this.#e.upstreamBytes,this.#e.upstreamProtocol)){if(e.done){this.#i=!0;return}let t=Rr(e);t!==null&&(yield t)}}async*#o(){try{for(;;){let e=await this.#n.next();if(e.done){if(this.#e.upstreamProtocol===`openai`&&!this.#i){for(let e of yr(this.#e.inboundProtocol,{status:502,message:`upstream stream ended before the [DONE] sentinel (truncated)`}))yield zr(e,this.#e.inboundProtocol);return}br(this.#e.inboundProtocol)&&(yield Ir());return}let t=e.value,n=this.#e.usageFromFrame;if(n!==void 0){let e=n(t);e!==null&&(this.#t={...this.#t??{},...e})}yield zr(t,this.#e.inboundProtocol)}}catch(e){let t=_r(e);for(let n of yr(this.#e.inboundProtocol,{status:hr(e),message:t}))yield zr(n,this.#e.inboundProtocol)}finally{await this.#n.return?.().catch(()=>{})}}};async function Ur(e,t){let n=e=>{let t={};if(e instanceof Headers)return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t;for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t},r=async(e,t,n)=>{let r=e=>(t,n)=>{let r=t,i;try{i=r.status<200||r.status>299?e.pair.errorEnvelope(r.status,r.body):e.options.translate===!1?r.body:e.pair.translateResponse(r.body,e.options)}catch(e){return pr(hr(e)??500,_r(e))}return n({status:r.status,headers:r.headers,body:i})},i;try{i=await e.text()}catch(e){return pr(502,`failed to read upstream response body: ${_r(e)}`)}let a;try{let e=JSON.parse(i);if(typeof e!=`object`||!e)return pr(502,`upstream response is not a valid JSON object`);a=e}catch{return pr(502,`upstream response is not valid JSON`)}return new vr([...t.specs.flatMap(e=>Br(e,t).responseLayers),r(t)]).run({status:e.status,headers:n,body:a},e=>fr(e))},i=(e,t,n)=>{let r=e=>(t,n)=>{let r=t,i=new Hr({upstreamBytes:r.body,upstreamProtocol:e.pair.upstream,inboundProtocol:e.pair.inbound,bridge:e.options.translate===!1?e=>e:t=>e.pair.bridgeFrames(t,e.options,e.inboundBody??void 0),usageFromFrame:e.pair.usageFromFrame});return n({status:r.status,headers:r.headers,stream:i.stream,collectUsage:i.collectUsage})};return e.body===null?pr(502,`streaming response has no body`):new vr([...t.specs.flatMap(e=>Br(e,t).responseLayers),r(t)]).run({status:e.status,headers:n,body:e.body},e=>fr(e))},a=n(e.headers),o=(a[`content-type`]??``).includes(`text/event-stream`);return e.status<200||e.status>299||!o?r(e,t,a):i(e,t,a)}var Wr=[],Gr=class{chainName;pair;options;state=new Map;getState(e){return this.state.get(e)}setState(e,t){this.state.set(e,t)}#e=null;#t=Wr;#n=null;#r=!1;#i=!1;#a;constructor(e){this.chainName=e.chainName,this.pair=e.pair,this.options=Object.freeze({...e.options}),this.#a=e.snapshot}get specs(){return this.#t}get inbound(){return this.#e}get inboundBody(){return this.#e===null?null:this.#e.body}get upstreamRequest(){return this.#n}request(e){if(this.#r)return pr(500,`RequestContext: request() can only be called once (one container per round trip)`);this.#r=!0,this.#e=e,this.#t=Kr(this.#a,e,this);let t=Vr(e,this);return gr(t)?t.then(e=>(e.kind===`ok`&&(this.#n=e.value),e)):(t.kind===`ok`&&(this.#n=t.value),t)}response(e){if(this.#i)return Promise.resolve(pr(500,`RequestContext: response() can only be called once`));if(this.#i=!0,!this.#r){let e=[];for(let t of this.#a)t!==null&&t.runWhen===void 0&&e.push(t);this.#t=e}return Ur(e,this)}};function Kr(e,t,n){let r=[];for(let i of e)i!==null&&(i.runWhen===void 0||i.runWhen(t,n)===!0)&&r.push(i);return r}var qr=class{#e=[];register(e){let t=this.#e.length;return this.#e.push(e),t}unregister(e){this.#e[e]=null}snapshot(){return[...this.#e]}},Jr=class{#e;#t;#n;#r=new qr;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}get name(){return this.#n}intercept(e){return this.#r.register(e)}unregister(e){this.#r.unregister(e)}begin(){return new Gr({chainName:this.#n,pair:this.#e,options:Object.freeze({...this.#t}),snapshot:this.#r.snapshot()})}};function B(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function V(e){return B(e)?e:{}}function H(e){return Array.isArray(e)?e:[]}function U(e){return typeof e==`string`?e:null}function W(e){return typeof e==`string`?e:``}function Yr(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Xr(e){return typeof e!=`number`||!Number.isFinite(e)?0:Math.max(0,Math.trunc(e))}function Zr(){return crypto.randomUUID()}function Qr(){return Math.floor(Date.now()/1e3)}function $r(...e){for(let t of e){let e=Xr(t);if(e>0)return e}return 0}function ei(e){let t=V(e.prompt_tokens_details);return{cacheRead:$r(e.cache_read_input_tokens,e.prompt_cache_hit_tokens,t.cached_tokens),cacheCreation:$r(e.cache_creation_input_tokens,t.cache_creation_tokens,t.cache_write_tokens)}}function ti(e,t,n,r){let i={input_tokens:Math.max(e-n-r,0),output_tokens:t};return r>0&&(i.cache_creation_input_tokens=r),n>0&&(i.cache_read_input_tokens=n),i}var ni=new Set([`end_turn`,`max_tokens`,`stop_sequence`,`tool_use`,`refusal`]),ri=new Set([`stop`,`length`,`tool_calls`,`function_call`,`content_filter`]);function ii(e){return{stop:`end_turn`,length:`max_tokens`,tool_calls:`tool_use`}[e]??`end_turn`}function ai(e){let t=U(e)??``;return ni.has(t)?t:ii(t)}function oi(e){let t=U(e.stop_reason),n=U(V(e.provider_specific_fields).stop_reason),r=t??n;return r===null||r===``||ni.has(r)||ri.has(r)?null:r}function si(e){let t=U(e.refusal);if(t!==null&&t!==``)return t;let n=U(V(e.provider_specific_fields).refusal);return n!==null&&n!==``?n:null}var ci={400:`invalid_request_error`,401:`authentication_error`,403:`permission_error`,404:`not_found_error`,413:`request_too_large`,429:`rate_limit_error`,500:`api_error`,529:`overloaded_error`};function li(e){return ci[e]??`api_error`}function ui(e){let t=B(e)?e.code:void 0;return typeof t==`number`&&Number.isInteger(t)&&t>=400&&t<600?t:500}function di(e){if(!B(e))return!1;let t=e.type===`error`?e.error:void 0;return B(t)&&typeof t.type==`string`&&typeof t.message==`string`}function fi(e,t){if(B(t)){let e=t.error;if(B(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(B(n)&&typeof n.message==`string`)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;if(typeof i==`string`&&i!==``)return i;let a=JSON.stringify(t);if(a!==void 0&&a!==``)return a}return typeof t==`string`&&t!==``?t:`upstream error (HTTP ${e})`}function pi(e,t){return di(t)?t:{type:`error`,error:{type:li(e),message:fi(e,t)}}}function mi(e){let t=V(e);if(t.type===`message_start`){let e=V(t.message).usage;return B(e)?e:null}if(t.type===`message_delta`){let e=t.usage;return B(e)?e:null}return null}function hi(e){if(typeof e!=`object`||!e||Array.isArray(e))return String(e);let t=V(e),n=t.message;return typeof n==`string`&&n!==``?n:JSON.stringify(t)}var gi=class{#e=0;#t=null;#n=null;#r=null;#i=0;#a=0;#o=0;#s=0;#c=!1;#l=!1;#u=null;#d=null;#f=``;#p=``;translateFrame(e){if(this.#l)return[];let t=e.error;if(t!=null)throw new mr(hi(t),{status:ui(t)});let n=V(H(e.choices)[0]),r=V(n.delta),i=[];if(!this.#c){this.#c=!0;let t=e.id;this.#p=typeof t==`string`&&t!==``?t:Zr(),i.push(this.#m(U(e.model)))}let a=r.content;typeof a==`string`&&a!==``&&(i.push(...this.#h(`text`)),i.push(this.#_({type:`text_delta`,text:a})));let o=si(r);o!==null&&(this.#f+=o,i.push(...this.#h(`text`)),i.push(this.#_({type:`text_delta`,text:o})));let s=r.reasoning_content===void 0?r.reasoning:r.reasoning_content;typeof s==`string`&&s!==``&&(i.push(...this.#h(`thinking`,{type:`thinking`,thinking:``,signature:``})),i.push(this.#_({type:`thinking_delta`,thinking:s})));for(let e of H(r.thinking_blocks)){let t=U(V(e).signature);t!==null&&t!==``&&(i.push(...this.#h(`thinking`,{type:`thinking`,thinking:``,signature:``})),i.push(this.#_({type:`signature_delta`,signature:t})))}for(let[e,t]of H(r.tool_calls).entries()){let n=V(t),r=V(n.function),a=typeof n.index==`number`?n.index:e,o=U(n.id)??``;(this.#t!==`tool_use`||this.#n!==a||o!==``&&this.#r!==null&&this.#r!==o)&&this.#t===`tool_use`&&i.push(...this.#g()),i.push(...this.#h(`tool_use`,{type:`tool_use`,id:o,name:U(r.name)??``,input:{}})),this.#n=a,o!==``&&(this.#r=o);let s=r.arguments;typeof s==`string`&&s!==``&&i.push(this.#_({type:`input_json_delta`,partial_json:s}))}let c=V(e.usage),l=Xr(c.prompt_tokens),u=Xr(c.completion_tokens);if(l>0){this.#i=l;let e=ei(c);this.#o=e.cacheRead,this.#s=e.cacheCreation}u>0&&(this.#a=u);let d=n.finish_reason;typeof d==`string`&&d!==``&&(this.#u=d);let f=oi(n);return f!==null&&(this.#d=f),i}flush(){if(!this.#c||this.#l)return[];this.#l=!0;let e=[...this.#g()],t=this.#d===null?this.#u==null?`end_turn`:ai(this.#u):`stop_sequence`,n=this.#f!==``&&t!==`max_tokens`;return e.push({type:`message_delta`,delta:n?{stop_reason:`refusal`,stop_sequence:this.#d,stop_details:{type:`refusal`}}:{stop_reason:t,stop_sequence:this.#d},usage:ti(this.#i,this.#a,this.#o,this.#s)}),e.push({type:`message_stop`}),e}#m(e){return{type:`message_start`,message:{id:this.#p,type:`message`,role:`assistant`,...e===null?{}:{model:e},content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0}}}}#h(e,t){if(this.#t===e)return[];let n=this.#g();this.#t=e;let r=t??{type:`text`,text:``},i=[...n,{type:`content_block_start`,index:this.#e,content_block:r}];return this.#e+=1,i}#g(){if(this.#t===null)return[];let e=this.#e-1;return this.#t=null,this.#n=null,this.#r=null,[{type:`content_block_stop`,index:e}]}#_(e){return{type:`content_block_delta`,index:this.#e-1,delta:e}}};async function*_i(e){let t=new gi;for await(let n of e)for(let e of t.translateFrame(V(n)))yield e;for(let e of t.flush())yield e}var vi=4096;function yi(e){return e.map(e=>{if(!B(e))return V(e);let t=!1,n={};for(let[r,i]of Object.entries(e)){if(r===`provider_specific_fields`){t=!0;continue}if(r===`content`&&Array.isArray(i)){let e=i.map(e=>{if(!B(e)||!(`provider_specific_fields`in e))return e;let{provider_specific_fields:t,...n}=e;return n});(e.length!==i.length||e.some((e,t)=>e!==i[t]))&&(t=!0),n[r]=e;continue}n[r]=i}return t?n:e})}function bi(e,t){let n=!1;for(let t of e){let e=t.content;if(Array.isArray(e)){for(let t of e)if(V(t).type===`container_upload`){n=!0;break}}if(n)break}if(!n)return t;for(let e of t){let n=e.type;if(typeof n==`string`&&n.startsWith(`code_execution`))return t}return[...t,{name:`code_execution`,type:`code_execution_20250522`}]}function xi(e){if(!B(e.metadata))return;let t=V(e.metadata).user_id;t==null?delete e.metadata:e.metadata={user_id:t}}function Si(e){let t=e.output_config;if(!B(t))return;let n=t.effort;if(typeof n==`string`&&n!==``&&![`high`,`medium`,`low`,`xhigh`,`max`].includes(n))throw new mr(`Invalid effort value: ${JSON.stringify(n)}. Must be one of: 'high', 'medium', 'low', 'xhigh', 'max'`,{status:400})}function Ci(e){let t=V(e),n=yi(H(t.messages)),r=H(t.tools).map(V),i=bi(n,r),a={...t,messages:n};return i!==r&&(a.tools=i),`max_tokens`in a||(a.max_tokens=vi),xi(a),delete a.is_vertex_request,delete a.client_metadata,Si(a),a}function wi(e){return typeof e==`number`&&Number.isFinite(e)?Math.floor(e):0}function Ti(e){let t=wi(e.input_tokens??0),n=wi(e.output_tokens??0),r=0,i=0,a=e.iterations,o=Array.isArray(a)?a.map(V):null;o!==null&&o.length>0&&(t=o.reduce((e,t)=>e+wi(t.input_tokens??0),0),n=o.reduce((e,t)=>e+wi(t.output_tokens??0),0),r=o.reduce((e,t)=>e+wi(t.cache_creation_input_tokens??0),0),i=o.reduce((e,t)=>e+wi(t.cache_read_input_tokens??0),0),t+=r+i),o===null&&(`cache_creation_input_tokens`in e&&e.cache_creation_input_tokens!==null&&typeof e.cache_creation_input_tokens==`number`&&(r=e.cache_creation_input_tokens,t+=r),`cache_read_input_tokens`in e&&e.cache_read_input_tokens!==null&&typeof e.cache_read_input_tokens==`number`&&(i=e.cache_read_input_tokens,t+=i));let s={cached_tokens:i,cache_creation_tokens:r,cache_write_tokens:r};return{prompt_tokens:t,completion_tokens:n,total_tokens:t+n,prompt_tokens_details:s,cache_creation_input_tokens:r,cache_read_input_tokens:i}}var Ei=/^<(?:think|thinking|budget:thinking)>([\s\S]*?)<\/(?:think|thinking|budget:thinking)>([\s\S]*)/;function Di(e){if(!e)return{reasoningContent:null,content:e};let t=Ei.exec(e);return t===null?{reasoningContent:null,content:e}:{reasoningContent:t[1]??null,content:t[2]??null}}function Oi(e){let t=e.content,n=U(t);return`reasoning_content`in e?{reasoningContent:U(e.reasoning_content),content:n}:`reasoning`in e?{reasoningContent:U(e.reasoning),content:n}:typeof t==`string`?Di(t):{reasoningContent:null,content:n}}function ki(e){let t=V(e),n=t.arguments,r;if(n==null){let e=t.parameters;r=B(e)?JSON.stringify(e):``}else r=B(n)?JSON.stringify(n):String(n);return{arguments:r,name:U(t.name)}}function Ai(e){return e.type===`custom`||e.custom!=null}function ji(e){return Ai(e)?Object.fromEntries(Object.entries(e).filter(([e,t])=>e!==`function`&&e!==`type`||t!=null)):{id:e.id==null?Zr():String(e.id),type:e.type==null?`function`:String(e.type),function:ki(e.function)}}function Mi(e){let t=new Map;for(let[n,r]of e.entries()){if(Ai(r))continue;let e=V(r.function),i=e.name,a=JSON.parse(typeof e.arguments==`string`?e.arguments:``);if(i!==`multi_tool_use.parallel`)continue;let o=V(a),s=(Array.isArray(o.tool_uses)?o.tool_uses:[]).map((e,t)=>{let n=V(e),i=String(n.recipient_name).replace(/^functions\./,``);return{id:`${String(r.id)}_${String(t)}`,type:`function`,function:{name:i,arguments:JSON.stringify(n.parameters)}}});t.set(n,s)}return t}function Ni(e){try{let t=Mi(e),n=0,r=[...e];for(let[e,i]of t)r.splice(e+n,1,...i),n+=i.length;return r}catch{return e}}function Pi(e){return Array.isArray(e.tool_calls)?Ni(e.tool_calls.map(e=>ji(V(e)))):[]}function Fi(e){if(typeof e!=`string`||e===``)return{};try{return V(JSON.parse(e))}catch{return{}}}function Ii(e){let t=[];for(let n of e.thinkingBlocks){let e=V(n);e.type===`thinking`?t.push({type:`thinking`,thinking:U(e.thinking)??``,signature:U(e.signature)}):e.type===`redacted_thinking`&&t.push({type:`redacted_thinking`,data:U(e.data)??``})}e.thinkingBlocks.length===0&&typeof e.reasoningContent==`string`&&e.reasoningContent!==``&&t.push({type:`thinking`,thinking:e.reasoningContent,signature:null}),typeof e.content==`string`&&e.content!==``&&t.push({type:`text`,text:e.content}),e.refusal!==null&&t.push({type:`text`,text:e.refusal});for(let n of e.toolCalls){let e=V(n),r=V(e.function);t.push({type:`tool_use`,id:U(e.id)??``,name:U(r.name)??``,input:Fi(r.arguments)})}return t}function Li(e){let{cacheRead:t,cacheCreation:n}=ei(e);return ti(Xr(e.prompt_tokens),Xr(e.completion_tokens),t,n)}function Ri(e){let t=V(e),n=t.error;if(n!=null){let e=V(n);throw new mr(typeof e.message==`string`?e.message:JSON.stringify(n),{status:ui(n)})}let r=H(t.choices);if(r.length===0)throw Error(`upstream returned a response with no 'choices'. Raw keys: ${Object.keys(t).join(`, `)}`);let i=V(r[0]),a=V(i.message),o=Pi(a),{reasoningContent:s,content:c}=Oi(a),l=H(a.thinking_blocks),u=si(a),d=U(i.finish_reason)??`stop`;d===`stop`&&o.length>0&&(d=`tool_calls`);let f=oi(i),p=f===null?ai(d):`stop_sequence`,m=u!==null&&p!==`max_tokens`;return m&&(p=`refusal`),{id:t.id,type:`message`,role:`assistant`,...t.model===void 0?{}:{model:t.model},content:Ii({thinkingBlocks:l,reasoningContent:s,content:c,refusal:u,toolCalls:o}),stop_reason:p,...m?{stop_details:{type:`refusal`}}:{},stop_sequence:f,usage:Li(V(t.usage))}}function zi(e){return e===null?`None`:e===!0?`True`:e===!1?`False`:typeof e==`number`?String(e):typeof e==`string`?`'${e.replaceAll(`\\`,`\\\\`).replaceAll(`'`,`\\'`)}'`:Array.isArray(e)?`[${e.map(e=>zi(e)).join(`, `)}]`:B(e)?`{${Object.entries(e).map(([e,t])=>`'${e}': ${zi(t)}`).join(`, `)}}`:String(e)}function Bi(e){let t=``,n=[],r=null,i=[];if((Array.isArray(e.content)?e.content:[]).forEach((e,r)=>{let a=V(e),o=typeof a.type==`string`?a.type:``;if(o===`text`)t+=typeof a.text==`string`?a.text:``;else if(o===`tool_use`||o===`server_tool_use`){let e={id:a.id,type:`function`,function:{name:a.name,arguments:JSON.stringify(a.input??{})},index:r};i.push(e)}else(o===`thinking`||o===`redacted_thinking`)&&n.push(a)}),n.length>0){r=``;for(let e of n){let t=e.thinking;typeof t==`string`&&(r+=t)}}return{textContent:t,thinkingBlocks:n,reasoningContent:r,toolCalls:i}}function Vi(e){let t=[];for(let n of e){let e=V(n),r=typeof e.type==`string`?e.type:``;(r===`tool_use`||r===`server_tool_use`)&&t.push(e.caller)}return t}function Hi(e,t){let n=Vi(Array.isArray(t.content)?t.content:[]),r=Array.isArray(e.content)?e.content:[],i=0;for(let e of r){let t=V(e);if(t.type!==`tool_use`)continue;let r=n[i];i+=1,r!==void 0&&(t.caller=r)}}function Ui(e){let t=V(e);if(`error`in t&&t.error!==null&&t.error!==void 0)throw new mr(zi(t.error));let n=Bi(t),r={role:`assistant`,content:n.textContent===``?null:n.textContent,tool_calls:n.toolCalls.length>0?n.toolCalls:null};n.reasoningContent!==null&&(r.reasoning_content=n.reasoningContent),n.thinkingBlocks.length>0&&(r.thinking_blocks=n.thinkingBlocks);let i=V(Ri({id:Zr(),object:`chat.completion`,...t.model===void 0?{}:{model:t.model},choices:[{index:0,finish_reason:U(t.stop_reason),message:r}],usage:Ti(V(t.usage))}));return Hi(i,t),{...i,...t.container===void 0?{}:{container:t.container},...`stop_details`in i?{stop_details:i.stop_details}:t.stop_details===void 0?{}:{stop_details:t.stop_details},...t.diagnostics===void 0?{}:{diagnostics:t.diagnostics}}}var Wi=class{contentBlocks=[];toolIndex=-1;currentContentBlockType=null;cumulativeUsage={};parse(e){let t=U(e.type)??``,n=``,r=null,i=``,a=null,o=null,s=null,c=null;if(t===`content_block_delta`){let t=V(e.delta);if(this.contentBlocks.push(e),typeof t.text==`string`)n=t.text;else if(`partial_json`in t)(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`)&&(r={id:null,type:`function`,function:{name:null,arguments:typeof t.partial_json==`string`?t.partial_json:``},index:this.toolIndex});else if(!(`citation`in t)&&(`thinking`in t||`signature`in t)){let e=t.thinking;typeof e==`string`&&e!==``&&(o=e,s=[{type:`thinking`,thinking:e}]);let n=t.signature;typeof n==`string`&&n!==``&&(s=[{type:`thinking`,thinking:this.contentBlocks.map(e=>V(e.delta)).filter(e=>typeof e.thinking==`string`).map(e=>e.thinking).join(``),signature:n}])}}else if(t===`content_block_start`){let t=V(e.content_block);if(this.contentBlocks.length=0,this.currentContentBlockType=U(t.type)??``,this.currentContentBlockType===`text`)n=typeof t.text==`string`?t.text:``;else if(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`){this.toolIndex+=1;let e=U(t.name)??``;r={id:U(t.id),type:`function`,function:{name:e,arguments:``},index:this.toolIndex}}else this.currentContentBlockType===`redacted_thinking`&&(s=[{type:`redacted_thinking`,data:t.data}])}else if(t===`content_block_stop`)(this.currentContentBlockType===`tool_use`||this.currentContentBlockType===`server_tool_use`)&&this.contentBlocks.map(e=>V(e.delta)).filter(e=>e.type===`input_json_delta`).map(e=>typeof e.partial_json==`string`?e.partial_json:``).join(``)===``&&(r={id:null,type:`function`,function:{name:null,arguments:`{}`},index:this.toolIndex}),this.currentContentBlockType=null;else if(t===`message_delta`)i=U(V(e.delta).stop_reason)??``,`usage`in e&&(a=Ti(this.#e(e.usage)));else if(t===`message_start`){let t=V(e.message);c=U(t.model),`usage`in t&&(a=Ti(this.#e(t.usage)))}else if(t===`error`){let t=V(e.error);throw new mr(typeof t.message==`string`&&t.message!==``?t.message:JSON.stringify(e),{status:500})}else return null;let l={content:n,tool_calls:r===null?null:[r]};o!==null&&(l.reasoning_content=o),s!==null&&(l.thinking_blocks=s);let u={choices:[{index:0,finish_reason:i===``?null:i,delta:l}]};return c!==null&&(u.model=c),a!==null&&(u.usage=a),u}#e(e){return this.cumulativeUsage={...this.cumulativeUsage,...V(e)},this.cumulativeUsage}},Gi=class{inbound=`anthropic`;upstream=`anthropic`;translateRequest(e){return Ci(e)}translateResponse(e){return Ui(e)}async*bridgeFrames(e){let t=new Wi,n=new gi;for await(let r of e){let e=t.parse(V(r));if(e!==null)for(let t of n.translateFrame(e))yield t}for(let e of n.flush())yield e}usageFromFrame(e){return mi(e)}errorEnvelope(e,t){return pi(e,t)}},Ki=`Operator note (not from the user): the following was originally a mid-conversation system-role reminder.`;function qi(e){let t=e.role;return t===`system`?`system`:t===`tool`||t===`function`?`tool`:t===`user`?`user`:`other`}function Ji(e){let t=e.content;if(typeof t==`string`)return t===``?[]:[{type:`text`,text:t}];let n=[];for(let e of H(t)){let t=V(e);if(t.type!==`text`)continue;let r=U(t.text)??``;r!==``&&n.push({type:`text`,text:r})}return n}function Yi(e){return{role:`user`,content:[{type:`text`,text:Ki},...Ji(e)]}}function Xi(e){return e.filter(e=>Ji(e).length>0).map(Yi)}function Zi(e){let t=[],n=null,r=[];for(let i of e){let e=qi(i);e!==n&&(r.length>0&&t.push(r),r=[],n=e),r.push(i)}return r.length>0&&t.push(r),t}function Qi(e){let t=Zi(e),n=[];for(let e=0;e<t.length;e++){let r=t[e]??[],i=qi(r[0]??{}),a=t[e+1],o=a===void 0?null:qi(a[0]??{});if(i===`system`){o!==`tool`&&n.push(...Xi(r));continue}let s=e>0?t[e-1]:void 0;if(i===`tool`&&s!==void 0&&qi(s[0]??{})===`system`){n.push(...r,...Xi(s));continue}n.push(...r)}return n}function $i(e){if(!e.some(e=>e.role===`system`))return e;let t=e.findIndex(e=>e.role!==`system`);return t===-1?e:[...e.slice(0,t),...Qi(e.slice(t))]}var ea=new Set([`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`not`,`propertyNames`,`then`,`unevaluatedItems`,`unevaluatedProperties`]),ta=new Set([`allOf`,`anyOf`,`items`,`oneOf`,`prefixItems`]),na=new Set([`$defs`,`definitions`,`dependentSchemas`,`patternProperties`,`properties`]),ra=1024;function ia(e){if(e.includes(`\\p{`)||e.includes(`\\p<`))return!1;try{new RegExp(e)}catch{return!1}return!0}function aa(e,t){let n={},r=!1;for(let[i,a]of Object.entries(e)){if(i===`pattern`&&typeof a==`string`&&!ia(a)){r=!0;continue}let e=oa(i,a,t);e!==a&&(r=!0),i===`__proto__`?Object.defineProperty(n,i,{value:e,enumerable:!0,writable:!0,configurable:!0}):n[i]=e}return r?n:e}function oa(e,t,n){if(ta.has(e)&&Array.isArray(t)){let e=t.map(e=>B(e)?n.get(e)??e:e);return e.every((e,n)=>e===t[n])?t:e}if(!B(t))return t;if(na.has(e)){let r={},i=!1;for(let[a,o]of Object.entries(t)){if(e===`patternProperties`&&typeof a==`string`&&!ia(a)){i=!0;continue}if(B(o)){let e=n.get(o)??o;e!==o&&(i=!0),a===`__proto__`?Object.defineProperty(r,a,{value:e,enumerable:!0,writable:!0,configurable:!0}):r[a]=e}else r[a]=o}return i?r:t}return ea.has(e)?n.get(t)??t:t}function sa(e,t){for(let[n,r]of Object.entries(e))if(na.has(n)&&B(r))for(let e of Object.values(r))B(e)&&t.push(e);else if(ta.has(n)&&Array.isArray(r))for(let e of r)B(e)&&t.push(e);else ea.has(n)&&B(r)&&t.push(r)}function ca(e){let t=new Map,n=[],r=[e];for(;r.length>0&&n.length<ra;){n.push(r);let e=[];for(let t of r)sa(t,e);r=e}for(let e of n.reverse())for(let n of e){let e=aa(n,t);e!==n&&t.set(n,e)}return t.get(e)??e}function la(e){if(B(e))return e;if(typeof e!=`string`)return null;try{let t=JSON.parse(e);return B(t)?t:null}catch{return null}}function ua(e,t){if(typeof e==`string`)return e===``?null:e;let n=[];for(let r of H(e)){let e=V(r);if(e.type!==`text`)continue;let i=U(e.text)??``;(i!==``||t)&&n.push({type:`text`,text:i})}return n.length>0?n:null}function da(e){let t=ua(e,!0);return t===null?[]:[{role:`system`,content:t}]}function fa(e){return e.flatMap(e=>{let t=V(e),n=t.content;if(t.role===`system`){let e=ua(n,!1);return e===null?[]:[{role:`system`,content:e}]}return t.role===`user`?pa(n):t.role===`assistant`?_a(n):[]})}function pa(e){if(typeof e==`string`)return[{role:`user`,content:e}];let t=[],n=[];for(let r of H(e)){let e=V(r);if(e.type===`text`)t.push({type:`text`,text:U(e.text)??``});else if(e.type===`image`){let n=ha(e.source);n!==null&&t.push({type:`image_url`,image_url:{url:n}})}else e.type===`tool_result`&&n.push({role:`tool`,content:ma(e.content),tool_call_id:U(e.tool_use_id)??``})}let r=t.length>0?t:``;return n.length>0&&t.length===0?n:[...n,{role:`user`,content:r}]}function ma(e){return typeof e==`string`?e:H(e).map(e=>U(V(e).text)??``).join(``)}function ha(e){let t=V(e);return t.type===`base64`&&typeof t.data==`string`&&t.data!==``?`data:${typeof t.media_type==`string`?t.media_type:`image/jpeg`};base64,${t.data}`:t.type===`url`?U(t.url):null}function ga(e){return e.map(e=>e.type===`thinking`?U(e.thinking)??``:``).filter(e=>e!==``).join(`
|
|
16
|
+
`)}function _a(e){if(typeof e==`string`)return[{role:`assistant`,content:e}];let t=[],n=[],r=[];for(let i of H(e)){let e=V(i);e.type===`text`?t.push(U(e.text)??``):e.type===`tool_use`?n.push({id:U(e.id)??``,type:`function`,function:{name:U(e.name)??``,arguments:JSON.stringify(e.input??{})}}):e.type===`thinking`?r.push({type:`thinking`,thinking:U(e.thinking)??``,signature:U(e.signature)??``}):e.type===`redacted_thinking`&&r.push({type:`redacted_thinking`,data:U(e.data)??``})}let i=ga(r);return[{role:`assistant`,content:t.length>0?t.join(``):null,...n.length>0?{tool_calls:n}:{},...r.length>0?{thinking_blocks:r}:{},...i===``?{}:{reasoning_content:i}}]}var va=64;function ya(e){if(typeof e!=`string`)return null;let t;try{t=JSON.parse(e)}catch{return null}let n=V(t).session_id;if(typeof n!=`string`)return null;let r=n.slice(0,va);return r===``?null:r}function ba(e,t){let n=new Set([`max_tokens`,`temperature`,`top_p`,`stop_sequences`,`stream`,`metadata`,`tool_choice`,`tools`,`thinking`,`reasoning_effort`,`system`,`context_management`,`output_config`]);t.topK!==`preserve`&&n.add(`top_k`);let r=Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e))),i=(e,t,n)=>{n&&(r[e]=t)},a=e.max_tokens;i(`max_tokens`,a,typeof a==`number`);let o=e.temperature;i(`temperature`,o,typeof o==`number`);let s=e.top_p;i(`top_p`,s,typeof s==`number`);let c=e.stop_sequences;i(`stop`,c,Array.isArray(c)&&c.length>0),i(`stream`,!0,e.stream===!0);let l=ya(V(e.metadata).user_id);i(`prompt_cache_key`,l,l!==null);let u=xa(e.tool_choice);i(`tool_choice`,u,u!==null);let d=e.tools;i(`tools`,H(d).map(Sa),H(d).length>0);let f=Ca(e.thinking,e.output_config);return i(`reasoning_effort`,f,f!==null),r}function xa(e){let t=V(e);return t.type===`auto`?`auto`:t.type===`any`?`required`:t.type===`none`?`none`:t.type===`tool`&&typeof t.name==`string`?{type:`function`,function:{name:t.name}}:null}function Sa(e){let t=V(e),n=t.input_schema,r=la(n);if(r===null&&n!=null)throw new mr(`Invalid type for tools[${String(t.name??``)}].input_schema: expected an object, but got ${typeof n} instead.`,{status:400});return{type:`function`,function:{name:t.name??``,description:t.description,parameters:ca(r!==null&&Object.keys(r).length>0?r:{type:`object`,properties:{}})}}}function Ca(e,t=void 0){let n=V(e),r=U(n.type)??``;if(r===`disabled`)return null;if(r===`adaptive`)return U(V(n.output_config).effort)??U(V(t).effort)??null;if(r!==`enabled`)return null;let i=n.budget_tokens;return typeof i==`number`?i<=1024?`low`:i<=2048?`medium`:`high`:`medium`}function wa(e,t){let n=V(e),r=$i([...da(n.system),...fa(H(n.messages))]),i=ba(n,t);if(i.messages=r,i.reasoning_effort===`none`){let e={...i};delete e.reasoning_effort,i=e}return i}var Ta=class{inbound=`anthropic`;upstream=`openai`;translateRequest(e,t){return wa(e,t)}translateResponse(e){return Ri(e)}bridgeFrames(e){return _i(e)}usageFromFrame(e){return mi(e)}errorEnvelope(e,t){return pi(e,t)}},Ea={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`};function Da(e){let t=Ea[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t}function Oa(e,t){if(typeof t==`string`&&t!==``)return t;if(B(t)){let e=t.message;if(typeof e==`string`&&e!==``)return e;let n=JSON.stringify(t);if(n!==void 0&&n!==``)return n}return`upstream error (HTTP ${e})`}function ka(e,t){return B(t)&&B(t.error)?t:{error:{message:Oa(e,t),type:Da(e),param:null,code:String(e)}}}function Aa(){return`chatcmpl-${Zr()}`}var ja={stop_sequence:`stop`,end_turn:`stop`,max_tokens:`length`,tool_use:`tool_calls`,refusal:`content_filter`,compaction:`length`,content_filtered:`content_filter`,stop:`stop`,length:`length`,tool_calls:`tool_calls`,function_call:`function_call`,content_filter:`content_filter`};function Ma(e){return ja[U(e)??``]??`stop`}function Na(e,t){let n=e.iterations,r=null;if(Array.isArray(n)&&n.length>0){let e=n.map(e=>{let t=V(V(e).output_tokens_details).thinking_tokens;return typeof t==`number`&&Number.isFinite(t)?t:null});r=e.every(e=>e!==null)?e.reduce((e,t)=>e+(t??0),0):null}if(r===null){let t=V(e.output_tokens_details).thinking_tokens;typeof t==`number`&&Number.isFinite(t)&&(r=t)}if(r===null)return{reasoning_tokens:0,text_tokens:t};let i=Math.min(Math.max(0,r),t);return{reasoning_tokens:i,text_tokens:t-i}}function Pa(e,t={}){let n=Xr(e.input_tokens),r=Xr(e.output_tokens),i=Xr(e.cache_creation_input_tokens),a=Xr(e.cache_read_input_tokens),o=n+i+a,s={cached_tokens:a,text_tokens:n,cache_write_tokens:i,cache_creation_tokens:i};if(B(e.cache_creation)){let t=e.cache_creation,n={};for(let e of[`ephemeral_5m_input_tokens`,`ephemeral_1h_input_tokens`]){let r=t[e];typeof r==`number`&&(n[e]=Xr(r))}s.cache_creation_token_details=n}let c={completion_tokens:r,prompt_tokens:o,total_tokens:o+r,completion_tokens_details:Na(e,r),prompt_tokens_details:s,cache_creation_input_tokens:i,cache_read_input_tokens:a},l=U(e.inference_geo);l!==null&&(c.inference_geo=l);let u=U(e.speed);if(u!==null&&(c.speed=u),t.fromStreamBuilder!==!0){let t=U(e.service_tier);t!==null&&(c.service_tier=t)}return c}function Fa(e,t){return{...e??{},...t}}function Ia(e){return/claude-[a-z]+-(?:4[-._](?:[6-9]|[1-9]\d)(?!\d)|[5-9](?!\d)(?:[-._]\d{1,2}(?!\d))?)/.test(e)}function La(e){return/claude-[a-z]+-4[-._]6(?!\d)/.test(e)}function Ra(e){let t=e.toLowerCase();return![`fable`,`opus-4-7`,`opus_4_7`,`opus-4.7`,`opus_4.7`,`opus-4-8`,`opus_4_8`,`opus-4.8`,`opus_4.8`].some(e=>t.includes(e))}function za(e,t){if(typeof t==`string`&&t!==``)return t;if(B(t)){let e=t.error;if(B(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(B(n)&&typeof n.message==`string`&&n.message!==``)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;if(typeof i==`string`&&i!==``)return i;let a=JSON.stringify(t);if(a!==void 0&&a!==``)return a}return`upstream error (HTTP ${e})`}function Ba(e,t){if(B(t)){let e=t.error;if(B(e)&&t.type!==`error`&&typeof e.message==`string`)return t}return{error:{message:za(e,t),type:Da(e),param:null,code:String(e)}}}var Va={low:1024,medium:2048,high:4096,xhigh:8192,max:16384,minimal:1024},Ha={low:`low`,minimal:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:`max`},Ua=4096,Wa=1024,Ga=`[System: Empty message content sanitised to satisfy protocol]`,Ka=new Set([`type`,`properties`,`additionalProperties`,`required`,`$defs`,`strict`]);function qa(e,t){if(e==null)return{type:`object`,properties:{}};if(!B(e))throw new mr(`Invalid input_schema for tool "${t}": expected an object, got ${typeof e}`,{status:400});let n={};for(let[t,r]of Object.entries(e))Ka.has(t)&&(n[t]=r);return n.type!==`object`&&(n.type=`object`),n.properties===void 0&&(n.properties={}),n}function Ja(e){let t=V(e),n=V(t.function),r=t.type;if(r!==`function`&&r!==`custom`)throw new mr(`Unsupported tool type: ${String(r)}`,{status:400});let i=U(n.name)??``,a={name:i,input_schema:qa(n.parameters,i),type:`custom`},o=n.description;o!=null&&(a.description=o);let s=t.eager_input_streaming??n.eager_input_streaming;typeof s==`boolean`&&(a.eager_input_streaming=s);let c=t.cache_control??n.cache_control;B(c)&&(a.cache_control=c);let l=t.defer_loading??n.defer_loading;typeof l==`boolean`&&(a.defer_loading=l);let u=t.allowed_callers??n.allowed_callers;Array.isArray(u)&&(a.allowed_callers=u);let d=t.input_examples??n.input_examples;return Array.isArray(d)&&(a.input_examples=d),a}function Ya(e){return e.map(e=>{let t=V(e);return t.input_schema===void 0?Ja(e):t})}var Xa={name:`dummy_tool`,input_schema:{type:`object`,properties:{}},type:`custom`,description:`This is a dummy tool call`};function Za(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`)||`tool_use_id`}function Qa(e,t){if(typeof e!=`string`||e.trim()===``)return{};try{return JSON.parse(e)}catch(e){throw new mr(`Failed to parse tool call arguments for tool '${t}': ${e instanceof Error?e.message:String(e)}`,{status:400})}}function $a(e){if(!B(e))return!1;let t=e.type,n=t===`thinking`?e.signature:t===`redacted_thinking`?e.data:void 0;if(typeof n==`string`&&n.startsWith(`litellm_encrypted_reasoning:`))return!0;if(t!==`thinking`)return!1;let r=e.signature;if(typeof r!=`string`||r.length===0)return!0;let i=e.thinking;return!(typeof i==`string`&&i.trim().length>0)}function eo(e){let t=e.cache_control;return B(t)?t:void 0}function to(e,t){return e===``?null:t===void 0?{type:`text`,text:e}:{type:`text`,text:e,cache_control:t}}function no(e){let t=typeof e==`string`?e:U(V(e).url)??``,n=typeof e==`string`?null:U(V(e).format);if(t.startsWith(`https://`)||t.startsWith(`http://`))return{type:`image`,source:{type:`url`,url:t}};let r=/^data:([^;,]*);base64,(.*)$/s.exec(t);if(r===null)throw new mr(`Image url not in expected format. Example Expected input - "image_url": "data:image/jpeg;base64,{base64_image}". Supported formats - ['image/jpeg', 'image/png', 'image/gif', 'image/webp']. Error: unsupported image url`,{status:400});return{type:`image`,source:{type:`base64`,media_type:n??(r[1]??``).replace(/\\\//g,`/`),data:r[2]??``}}}function ro(e){let t=e.content,n=``;if(typeof t==`string`)n=t;else if(Array.isArray(t)){let e=[];for(let n of t){let t=V(n);if(t.type===`text`)e.push({type:`text`,text:U(t.text)??``});else if(t.type===`image_url`){let n=no(t.image_url),r=eo(t);r!==void 0&&(n.cache_control=r),e.push(n)}}n=e}let r={type:`tool_result`,tool_use_id:Za(U(e.tool_call_id)??Zr()),content:n},i=eo(e);return i!==void 0&&(r.cache_control=i),r}function io(e){let t=e.role;if(t!==`user`&&t!==`assistant`)return e;let n=e.content;if(typeof n==`string`)return n.trim()===``?{...e,content:Ga}:e;if(!Array.isArray(n))return e;let r=!1,i=n.map(e=>{let t=V(e);if(t.type!==`text`)return e;let n=t.text;return typeof n==`string`&&n.trim()!==``?e:(r=!0,{...t,text:Ga})});return r?{...e,content:i}:e}function ao(e){let t=[];for(let n of e){let e=n.role;if(e===`tool`||e===`function`){t.push(ro(n));continue}let r=n.content;if(typeof r==`string`){let e=to(r,void 0);e!==null&&t.push(e);continue}for(let e of H(r)){let n=V(e),r=eo(n);if(n.type===`text`){let e=to(U(n.text)??``,r);e!==null&&t.push(e)}else if(n.type===`image_url`){let e=no(n.image_url);r!==void 0&&(e.cache_control=r),t.push(e)}else n.type===`document`&&t.push(r===void 0?n:{...n,cache_control:r})}}return t.length>0?{role:`user`,content:t}:null}function oo(e){let t=[],n=new Set;for(let r of e){let e=r.content,i=Array.isArray(e)?e:null,a=i!==null&&i.some(e=>{let t=V(e).type;return t===`thinking`||t===`redacted_thinking`}),o=r.thinking_blocks;if(Array.isArray(o)&&!a)for(let e of o)$a(e)||t.push(V(e));if(i!==null)for(let e of i){let n=V(e),r=n.type;if(r===`thinking`){let e=n.thinking;typeof e==`string`&&e!==``&&!$a(n)&&t.push(n)}else if(r===`text`){let e=to(U(n.text)??``,eo(n));e!==null&&t.push(e)}else(r===`server_tool_use`||typeof r==`string`&&r.endsWith(`_tool_result`))&&t.push(n)}else if(typeof e==`string`){let n=to(e,eo(r));n!==null&&t.push(n)}let s=r.tool_calls;if(Array.isArray(s))for(let e of s){let r=V(e);if(r.type!==`function`)continue;let i=V(r.function),a=U(i.name)??``,o=Za(U(r.id)??Zr());if(n.has(o))continue;n.add(o);let s={type:`tool_use`,id:o,name:a,input:Qa(i.arguments,a)},c=eo(r);c!==void 0&&(s.cache_control=c),t.push(s)}}return t.length>0?{role:`assistant`,content:t}:null}function so(e){let t=e.map(e=>io(V(e))),n=[],r=0;for(;r<t.length;){let e=t[r]?.role;if(e===`user`||e===`tool`||e===`function`){let e=[];for(;r<t.length;){let n=t[r]?.role;if(n!==`user`&&n!==`tool`&&n!==`function`)break;e.push(t[r]),r+=1}let i=ao(e);i!==null&&n.push(i);continue}if(e===`assistant`){let e=[];for(;r<t.length&&t[r]?.role===`assistant`;)e.push(t[r]),r+=1;let i=oo(e);i!==null&&n.push(i);continue}r+=1}let i=n[n.length-1];if(i!==void 0&&i.role===`assistant`&&Array.isArray(i.content))for(let e of i.content)e.type===`text`&&typeof e.text==`string`&&(e.text=e.text.trimEnd());return n}function co(e){let t=[];for(let n of e){let e=n.content;if(typeof e==`string`){let r=to(e,eo(n));r!==null&&t.push(r);continue}for(let n of H(e)){let e=V(n);if(e.type!==`text`)continue;let r=to(U(e.text)??``,eo(e));r!==null&&t.push(r)}}return t}var lo=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,uo=/^\+?[\d\s()-]{7,}$/;function fo(e){return!lo.test(e)&&!uo.test(e)}function po(e){return typeof e!=`number`||!Number.isFinite(e)?null:Number.isInteger(e)?e:Math.max(1,Math.round(e))}function mo(e){let t=typeof e==`string`?[e]:H(e),n=[];for(let e of t)typeof e==`string`&&e.trim()!==``&&n.push(e);return n.length>0?n:null}function ho(e,t){let n=null;if(e===`auto`)n={type:`auto`};else if(e===`required`)n={type:`any`};else if(e===`none`)n={type:`none`};else if(B(e)){let t=e.type;if(t===`auto`)n={type:`auto`};else if(t===`required`||t===`any`)n={type:`any`};else if(t===`none`)n={type:`none`};else{let t=V(e.function).name;typeof t==`string`&&(n={type:`tool`,name:t})}}if(t!=null){if(e===`none`)return n;let r=t!==!0;n===null?n={type:`auto`,disable_parallel_tool_use:r}:n.disable_parallel_tool_use=r}return n}function go(e,t){let n=Ia(e)&&!La(e);return t>=8192&&n?`xhigh`:t>=4096?`high`:t>=2048?`medium`:`low`}function _o(e,t){if(!Ia(e)||La(e))return;let n=V(t.thinking);if(n.type!==`enabled`)return;let r=n.budget_tokens,i=go(e,typeof r==`number`?r:0);t.thinking={type:`adaptive`};let a=t.output_config;t.output_config={effort:i,...B(a)?a:{}}}function vo(e,t){let n=e.budget_tokens;return typeof t!=`number`||typeof n!=`number`?e:t<=Wa?null:n<t?e:{type:e.type??`enabled`,budget_tokens:t-1}}function yo(e,t){if(Ia(t))return{type:`adaptive`,display:`summarized`};let n=Va[e];if(n===void 0)throw new mr(`Unmapped reasoning effort: '${e}'. Must be one of: 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'none'.`,{status:400});return{type:`enabled`,budget_tokens:n}}function bo(e,t,n,r){if(V(n).type===`adaptive`&&!Ia(r)){let n=e.max_completion_tokens??e.max_tokens,r=vo({type:`enabled`,budget_tokens:Va.medium??2048},n);r!==null&&(t.thinking=r);return}t.thinking=n,_o(r,t)}function xo(e,t,n){let r=typeof t==`string`?t:U(V(t).effort);if(r!==null){if(r===`none`){delete e.thinking,delete e.output_config;return}if(e.thinking=yo(r,n),Ia(n)){let t=Ha[r];if(t===void 0)throw new mr(`Invalid reasoning_effort: '${r}'. Must be one of: 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'none'`,{status:400});e.output_config={effort:t}}}}var So=new Set([`model`,`messages`,`tools`,`tool_choice`,`parallel_tool_calls`,`max_tokens`,`max_completion_tokens`,`temperature`,`top_p`,`top_k`,`stop`,`stream`,`stream_options`,`thinking`,`reasoning_effort`,`user`,`metadata`,`extra_headers`,`cache_control`,`response_format`,`web_search_options`,`context_management`,`speed`]);function Co(e,t){let n=U(e.model)??``,r={};for(let[t,i]of Object.entries(e)){if(!So.has(t)){r[t]=i;continue}switch(t){case`model`:r.model=i;break;case`max_tokens`:case`max_completion_tokens`:{let e=po(i);e!==null&&(r.max_tokens=e);break}case`tools`:H(i).length>0&&(r.tools=Ya(H(i)));break;case`tool_choice`:case`parallel_tool_calls`:{let t=ho(e.tool_choice,e.parallel_tool_calls);t===null?delete r.tool_choice:r.tool_choice=t;break}case`stream`:i===!0&&(r.stream=!0);break;case`stream_options`:break;case`stop`:{let e=mo(i);e!==null&&(r.stop_sequences=e);break}case`temperature`:case`top_p`:(Ra(n)||t===`temperature`&&i===1)&&(r[t]=i);break;case`top_k`:Ra(n)&&(r.top_k=i);break;case`thinking`:bo(e,r,i,n);break;case`reasoning_effort`:xo(r,i,n);break;case`user`:{let e=U(i);e!==null&&fo(e)&&(r.metadata={user_id:e});break}case`metadata`:B(i)&&i.user_id!==null&&i.user_id!==void 0&&(r.metadata={user_id:i.user_id});break;case`cache_control`:B(i)&&(r.cache_control=i)}}return r.messages=t,r.tools===void 0&&wo(e)&&(r.tools=[Xa]),r}function wo(e){return H(e.messages).some(e=>`tool_calls`in V(e))}function To(e){let t=V(e),n=H(t.messages),r=0;for(;r<n.length&&V(n[r]).role===`system`;)r+=1;let i=n.slice(0,r).map(e=>V(e)),a=Co(t,so($i(n.slice(r).map(e=>V(e))))),o=co(i);if(o.length>0&&(a.system=o),a.max_tokens===void 0){let e=V(a.thinking).budget_tokens;a.max_tokens=typeof e==`number`?e+Ua:Ua}return a}function Eo(e){let t=``,n=[],r=null;for(let[i,a]of e.entries()){let e=V(a),o=U(e.type)??``;if(o===`text`)t+=U(e.text)??``;else if(o===`tool_use`||o===`server_tool_use`){let t={id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.input??{})},index:i};B(e.caller)&&(t.caller=e.caller),n.push(t)}else(o===`thinking`||o===`redacted_thinking`)&&(r??=[],r.push(e))}let i=null;if(r!==null){i=``;for(let e of r){let t=e.thinking;typeof t==`string`&&(i+=t)}}return{content:t===``?null:t,role:`assistant`,...n.length>0?{tool_calls:n}:{},provider_specific_fields:{citations:null,thinking_blocks:r},...r===null?{}:{thinking_blocks:r},...i===null?{}:{reasoning_content:i}}}function Do(e){let t=V(e),n=t.error;if(n!=null)throw new mr(U(V(n).message)??JSON.stringify(n)??String(n),{status:ui(n)});let r=t.content;if(!Array.isArray(r))throw Error(`upstream returned a response with no 'content' array. Raw keys: ${Object.keys(t).join(`, `)}`);return{id:Aa(),created:Qr(),...t.model===void 0?{}:{model:t.model},object:`chat.completion`,choices:[{finish_reason:Ma(t.stop_reason),index:0,message:Eo(H(r))}],usage:Pa(V(t.usage))}}var Oo=class{#e;#t;#n=null;#r=null;#i=!1;#a=!1;#o=!1;#s=!1;#c=null;#l=-1;#u=``;#d=``;constructor(){this.#e=Aa(),this.#t=Qr()}translateFrame(e){if(this.#o)return[];switch(U(e.type)??``){case`message_start`:return this.#f(e);case`content_block_start`:return this.#p(e);case`content_block_delta`:return this.#m(e);case`content_block_stop`:return this.#h();case`message_delta`:return this.#g(e);case`message_stop`:return this.#o=!0,[];case`error`:throw new mr(U(V(e.error).message)??JSON.stringify(e),{status:500});default:return[]}}flush(){return this.#s||(this.#s=!0,this.#r===null||this.#i)?[]:(this.#i=!0,[this.#_({},{usage:Pa(this.#r,{fromStreamBuilder:!0})})])}#f(e){let t=V(e.message),n=U(t.model);n!==null&&(this.#n=n);let r=t.usage;return B(r)&&(this.#r=Fa(this.#r,r)),[]}#p(e){let t=V(e.content_block),n=U(t.type)??``;if(this.#c=n,this.#u=``,this.#d=``,n===`text`){let e=U(t.text)??``;return e===``?[]:[this.#_({content:e})]}if(n===`tool_use`||n===`server_tool_use`){this.#l+=1;let e={id:t.id,function:{arguments:``,name:t.name},type:`function`,index:this.#l};return B(t.caller)&&(e.caller=t.caller),[this.#_({content:``,tool_calls:[e]})]}if(n===`redacted_thinking`){let e=[{type:`redacted_thinking`,data:t.data}];return[this.#_({content:``,thinking_blocks:e,provider_specific_fields:{thinking_blocks:e}})]}return[]}#m(e){let t=V(e.delta),n=U(t.type)??``;if(n===`text_delta`){let e=U(t.text)??``;return e===``?[]:[this.#_({content:e})]}if(n===`thinking_delta`){let e=U(t.thinking)??``;if(e===``)return[];this.#d+=e;let n=[{type:`thinking`,thinking:e}];return[this.#_({reasoning_content:e,thinking_blocks:n,provider_specific_fields:{thinking_blocks:n},content:``})]}if(n===`signature_delta`){let e=U(t.signature)??``;if(e===``)return[];let n=[{type:`thinking`,thinking:this.#d,signature:e}];return[this.#_({reasoning_content:``,thinking_blocks:n,provider_specific_fields:{thinking_blocks:n},content:``})]}if(n===`input_json_delta`){if(this.#c!==`tool_use`&&this.#c!==`server_tool_use`)return[];let e=U(t.partial_json)??``;return this.#u+=e,[this.#_({content:``,tool_calls:[{function:{arguments:e},type:`function`,index:this.#l}]})]}return[]}#h(){let e=(this.#c===`tool_use`||this.#c===`server_tool_use`)&&this.#u===``;return this.#c=null,e?[this.#_({content:``,tool_calls:[{function:{arguments:`{}`},type:`function`,index:this.#l}]})]:[]}#g(e){let t=e.usage;B(t)&&(this.#r=Fa(this.#r,t));let n=Ma(V(e.delta).stop_reason??`stop`);return[this.#_({},{finishReason:n})]}#_(e,t={}){let n=this.#a?{...e}:{...e,role:`assistant`};this.#a=!0;let r={index:0,delta:n};t.finishReason!==void 0&&(r.finish_reason=t.finishReason);let i={id:this.#e,object:`chat.completion.chunk`,created:this.#t,...this.#n===null?{}:{model:this.#n},choices:[r]};return t.usage!==void 0&&(i.usage=t.usage),i}};async function*ko(e){let t=new Oo;for await(let n of e)for(let e of t.translateFrame(V(n)))yield e;for(let e of t.flush())yield e}var Ao=class{inbound=`openai`;upstream=`anthropic`;translateRequest(e){return To(e)}translateResponse(e){return Do(e)}bridgeFrames(e){return ko(e)}usageFromFrame(e){let t=e.usage;return B(t)?t:null}errorEnvelope(e,t){return Ba(e,t)}},jo=class{inbound=`openai`;upstream=`openai`;translateRequest(e){return e}translateResponse(e){return e}async*bridgeFrames(e){for await(let t of e)yield t}usageFromFrame(e){let t=e.usage;return B(t)?t:null}errorEnvelope(e,t){return ka(e,t)}};function Mo(e){let t=e;if(B(t.usage))return t.usage;let n=t.response;return B(n)&&B(n.usage)?n.usage:null}var No=new Set([`text`,`image_url`,`input_audio`,`audio_url`,`document`,`guarded_text`,`grounding_source`,`query`,`video_url`,`file`,`thinking`,`redacted_thinking`]),Po=new Set([`encrypted_content`,`redacted_thinking`]),Fo=new Set;function Io(e){return typeof e==`string`?e:H(e).flatMap(e=>{if(typeof e==`string`)return[e];let t=V(e);if(t.type===`input_file`){let e={},n=t.file_id||t.file_url;n!=null&&(e.file_id=n),t.file_data!=null&&(e.file_data=t.file_data);let r={type:`file`,file:e};return`cache_control`in t&&(r.cache_control=t.cache_control),[r]}if(t.type===`input_image`){let e={type:`image_url`,image_url:{url:W(t.image_url),detail:t.detail??`auto`}};return`cache_control`in t&&(e.cache_control=t.cache_control),[e]}if(t.type===`encrypted_content`)return t.encrypted_content==null?[]:[{type:`text`,text:String(t.encrypted_content)}];let n=t.text;if(n==null)return[];let r={type:Lo(W(t.type)),text:n};return`cache_control`in t&&(r.cache_control=t.cache_control),[r]})}function Lo(e){if(e.startsWith(`input_`)){let t=e.slice(6);return t===`audio`?`input_audio`:No.has(t)?t:`text`}return e===`tool_result`||e===`output_text`?`text`:No.has(e)?e:`text`}function Ro(e){let t=e.arguments;if(!t&&e.type===`custom_tool_call`){let n=W(e.input);t=n===``?``:JSON.stringify({content:n})}return[{role:`assistant`,content:null,tool_calls:[{id:W(e.call_id??e.id),type:`function`,function:{name:W(e.name),arguments:String(t??``)},index:0}]}]}function zo(e){let t=W(e.call_id);return t===``?[]:[{role:`tool`,content:Bo(e.output),tool_call_id:t}]}function Bo(e){if(e==null)return``;if(typeof e==`string`)return e;if(Array.isArray(e)){let t=[],n=[];for(let r of e){let e=V(r),i=e.type;if(i===`input_text`||i===`output_text`||i===`text`){let r=e.text;typeof r==`string`&&r!==``&&(n.push(r),t.push({type:`text`,text:r}))}else if(i===`input_image`||i===`image_url`){let n=e.image_url??e.url;if(B(n)){let e=n.url;typeof e==`string`&&e!==``&&t.push({type:`image_url`,image_url:{url:e}})}else typeof n==`string`&&n!==``&&t.push({type:`image_url`,image_url:{url:n}})}}if(t.some(e=>V(e).type===`image_url`))return t;if(n.length>0)return n.join(``)}try{return JSON.stringify(e)}catch{return String(e)}}function Vo(e){return[`function_call_output`,`custom_tool_call_output`,`web_search_call`,`computer_call_output`,`tool_result`].includes(W(e.type))}function Ho(e){return W(e.type)===`function_call`||W(e.type)===`custom_tool_call`}function Uo(e,t){let n=[];if(typeof t==`string`&&t!==``&&n.push({role:`system`,content:t}),typeof e==`string`)return n.push({role:`user`,content:e}),n;for(let t of H(e)){let e=V(t);if(Ho(e)){let t=Ro(e),r=n[n.length-1];if(r!==void 0&&r.role===`assistant`){n[n.length-1]={...r,tool_calls:[...Array.isArray(r.tool_calls)?r.tool_calls:[],...t[0]?.tool_calls]};continue}n.push(...t);continue}if(Vo(e)){n.push(...zo(e));continue}if(e.type===`reasoning`){n.push(...Zo(e));continue}let r=e.content;if(r==null)continue;let i=Go(e),a=i,o=Io(r),s=n[n.length-1];i===`assistant`&&s?.role===`assistant`&&Array.isArray(s.tool_calls)?n[n.length-1]={...s,content:Wo(s.content,o)}:n.push({role:a,content:o})}return ts(n)}function Wo(e,t){if(e==null||e===``)return t;if(t==null||t===``)return e;if(typeof e==`string`&&typeof t==`string`)return e+t;let n=typeof e==`string`?[{type:`text`,text:e}]:H(e),r=typeof t==`string`?[{type:`text`,text:t}]:H(t);return[...n,...r]}function Go(e){return W(e.role)===``?`user`:W(e.role)}function Ko(e){return Jo(e.content)??Yo(e.summary)}function qo(e,t){let n=e.flatMap(e=>{let n=V(e);if(t.has(W(n.type)))return[];let r=n.text;return typeof r==`string`&&r.trim()!==``?[r.trim()]:[]});return n.length>0?n.join(`
|
|
17
|
+
`):null}function Jo(e){return typeof e==`string`&&e.trim()!==``?e:Array.isArray(e)?qo(e,Po):null}function Yo(e){return Array.isArray(e)?qo(e,Fo):null}function Xo(e){let t=e.encrypted_content;if(typeof t!=`string`||t.trim()===``)return null;let n;try{n=JSON.parse(t)}catch{return null}if(!Array.isArray(n))return null;let r=n.filter(e=>{let t=V(e);return t.type===`thinking`?!!t.signature:t.type===`redacted_thinking`&&!!t.data});return r.length>0?r:null}function Zo(e){let t=Ko(e),n=Xo(e);return t===null&&n===null?[]:[{role:`assistant`,content:null,...t===null?{}:{reasoning_content:t},...n===null?{}:{thinking_blocks:n}}]}function Qo(e){return typeof e==`string`&&e!==``}function $o(e){return e.role===`assistant`&&e.content===null&&H(e.tool_calls).length===0&&(Qo(e.reasoning_content)||H(e.thinking_blocks).length>0)}function es(e,t){let n=t.map(e=>e.reasoning_content).filter(Qo),r=e.reasoning_content,i=n.length>0?[...n,...Qo(r)?[r]:[]].join(`
|
|
18
|
+
`):null,a=t.flatMap(e=>H(e.thinking_blocks));return{...e,...i===null?{}:{reasoning_content:i},...a.length>0?{thinking_blocks:[...a,...H(e.thinking_blocks)]}:{}}}function ts(e){let t=[],n=[];for(let r of e){if($o(r)){n.push(r);continue}if(n.length>0){if(r.role===`assistant`){t.push(es(r,n)),n=[];continue}t.push(...n),n=[]}t.push(r)}return t.push(...n),t}function ns(e){if(e==null)return null;if(typeof e==`string`)return e;let t=V(e),n=V(t.function);if(B(t.function)&&W(n.name)!==``)return t;let r=W(t.type);if(r===`auto`)return`auto`;if(r===`none`)return`none`;if(r===`required`||r===`tool`||r===`any`)return`required`;if(r===`function`){let e=W(t.name);return e===``?`required`:{type:`function`,function:{name:e}}}if(r===`custom`){let e=V(t.custom),n=W(t.name)===``?W(e.name):W(t.name);return n===``?`required`:{type:`function`,function:{name:n}}}return e}function rs(e){let t=[],n=null,r=H(e);for(let e=0;e<r.length;e++){let i=V(r[e]),a=W(i.type);if(a===`mcp`)t.push(i);else if(a===`web_search_preview`||a===`web_search`)n={...i.search_context_size==null?{}:{search_context_size:i.search_context_size},...i.user_location==null?{}:{user_location:i.user_location}};else if(a===`function`){let n=i.parameters,r=la(n);if(r===null&&n!=null)throw new mr(`Invalid type for tools[${String(e)}].parameters: expected an object, but got ${typeof n} instead.`,{status:400});let a=r??{type:`object`};t.push({type:`function`,function:{name:W(i.name),description:W(i.description),parameters:ca(Object.keys(a).length>0&&`type`in a?a:{...a,type:`object`}),strict:i.strict===!0},...Object.fromEntries([`cache_control`,`defer_loading`,`allowed_callers`,`input_examples`].filter(e=>e in i).map(e=>[e,i[e]])),...i.eager_input_streaming!==null&&i.eager_input_streaming!==void 0?{eager_input_streaming:i.eager_input_streaming}:{}})}}return{tools:t,webSearchOptions:n}}function is(e){let t=V(V(e).format);return W(t.type)===`json_schema`?{type:`json_schema`,json_schema:{name:t.name??`response_schema`,schema:t.schema??{},strict:t.strict??!1}}:W(t.type)===`json_object`?{type:`json_object`}:null}function as(e){let t=e,{tools:n,webSearchOptions:r}=rs(t.tools??[]),i=is(t.text),a=V(t.reasoning).effort,o=typeof a==`string`?a:null,s={messages:Uo(t.input,t.instructions),model:t.model??null,tool_choice:ns(t.tool_choice),tools:n,top_p:t.top_p??null,user:t.user??null,temperature:t.temperature??null,parallel_tool_calls:t.parallel_tool_calls??null,max_tokens:t.max_output_tokens??null,stream:t.stream===!0,safety_identifier:t.safety_identifier??null,web_search_options:r,response_format:i,reasoning_effort:o},c=Object.fromEntries(Object.entries(s).filter(([,e])=>e!==null));return H(c.tools).length===0?Object.fromEntries(Object.entries(c).filter(([e])=>e!==`tool_choice`&&e!==`tools`&&e!==`parallel_tool_calls`)):c}var os={stop_sequence:`stop`,end_turn:`stop`,max_tokens:`length`,tool_use:`tool_calls`,refusal:`content_filter`,compaction:`length`,COMPLETE:`stop`,ERROR_TOXIC:`content_filter`,ERROR:`stop`,eos_token:`stop`,eos:`stop`,STOP:`stop`,MAX_TOKENS:`length`,SAFETY:`content_filter`,RECITATION:`content_filter`,FINISH_REASON_UNSPECIFIED:`stop`,MALFORMED_FUNCTION_CALL:`stop`,LANGUAGE:`content_filter`,OTHER:`content_filter`,BLOCKLIST:`content_filter`,PROHIBITED_CONTENT:`content_filter`,SPII:`content_filter`,IMAGE_SAFETY:`content_filter`,IMAGE_PROHIBITED_CONTENT:`content_filter`,TOO_MANY_TOOL_CALLS:`stop`,MALFORMED_RESPONSE:`stop`,NO_IMAGE:`content_filter`,IMAGE_RECITATION:`content_filter`,IMAGE_OTHER:`content_filter`,ESCALATION:`content_filter`,UNEXPECTED_TOOL_CALL:`stop`,MISSING_THOUGHT_SIGNATURE:`stop`,network_error:`stop`,sensitive:`content_filter`,guardrail_intervened:`content_filter`,stop:`stop`,length:`length`,tool_calls:`tool_calls`,function_call:`function_call`,content_filter:`content_filter`,content_filtered:`content_filter`,error:`stop`};function ss(e,t=()=>{}){let n=os[e];return n===void 0?(t(e),`stop`):n}function cs(e){let t=V(e.message),n=Array.isArray(t.tool_calls)?t.tool_calls.map(e=>ji(V(e))):null;n!==null&&(n=Ni(n));let{reasoningContent:r,content:i}=Oi(t),a={content:i,role:t.role==null?`assistant`:String(t.role),tool_calls:n};r!==null&&(a.reasoning_content=r);let o=U(e.finish_reason);if(o===null){let t=e.finish_details;o=typeof t==`string`&&t!==``?t:`stop`}return o===`stop`&&n!==null&&n.length>0&&(o=`tool_calls`),{finish_reason:ss(o),message:a}}function ls(e){let t=V(e),n=e=>typeof e==`number`&&Number.isFinite(e)?e:null,r=n(t.completion_tokens)??0,i=n(t.prompt_tokens)??0,a=n(t.total_tokens)??0,o=B(t.completion_tokens_details)?{...t.completion_tokens_details}:null,s=n(t.reasoning_tokens);if(s!==null&&(o===null&&(o={}),n(o.reasoning_tokens)===null&&(o.reasoning_tokens=s),n(o.text_tokens)===null&&n(t.completion_tokens)!==null)){let e=r-s;o.image_tokens&&(e-=Number(o.image_tokens)),o.audio_tokens&&(e-=Number(o.audio_tokens)),o.text_tokens=Math.max(0,e)}let c=B(t.prompt_tokens_details)?{...t.prompt_tokens_details}:null,l=t.prompt_cache_hit_tokens,u=t.cache_read_input_tokens,d=typeof l==`number`?l:typeof u==`number`?u:null;if(d!==null&&(c===null&&(c={}),c.cached_tokens=d),c!==null)for(let e of[`audio_tokens`,`text_tokens`,`image_tokens`,`video_tokens`])c[e]===void 0&&(c[e]=null);if(o!==null)for(let e of[`text_tokens`,`image_tokens`,`video_tokens`,`accepted_prediction_tokens`,`rejected_prediction_tokens`])o[e]===void 0&&(o[e]=null);let f={completion_tokens:r,prompt_tokens:i,total_tokens:a,completion_tokens_details:o,prompt_tokens_details:c},p=new Set([`prompt_tokens`,`completion_tokens`,`total_tokens`,`reasoning_tokens`,`prompt_tokens_details`,`completion_tokens_details`,`server_tool_use`,`cost`]);for(let[e,n]of Object.entries(t))p.has(e)||(f[e]=n);let m=t.server_tool_use;m!=null&&(f.server_tool_use=m);let h=t.cost;return h!=null&&(f.cost=h),f}function us(e){let t=e.error;if(t!=null){let e=V(t);throw new mr(typeof e.message==`string`?e.message:JSON.stringify(t),{status:ui(t)})}let n=e.choices;if(!Array.isArray(n)||n.length===0)throw Error(`LiteLLM: provider returned a response with no 'choices'. Raw keys: ${Object.keys(e).join(`, `)}`);let r={choices:n.map(e=>cs(V(e)))};return e.usage!=null&&(r.usage=ls(e.usage)),r}function ds(e){return e===`length`||e===`max_tokens`||e===`content_filter`?`incomplete`:`completed`}function fs(e){return e===`content_filter`?`content_filter`:`max_output_tokens`}function ps(e){return typeof e==`string`?e:H(e).map(e=>typeof e==`string`?e:U(V(e).text)??``).join(``)}function ms(e){if(!B(e))return null;let t=Yr(e.prompt_tokens)??0,n=Yr(e.completion_tokens)??0,r=Yr(e.total_tokens)??t+n,i=V(e.prompt_tokens_details),a={},o=Yr(i.cached_tokens);o!==null&&(a.cached_tokens=o);let s=Yr(i.text_tokens);s!==null&&(a.text_tokens=s);let c=V(e.completion_tokens_details),l={},u=Yr(c.reasoning_tokens);return u!==null&&u>0&&(l.reasoning_tokens=u),{input_tokens:t,...Object.keys(a).length>0?{input_tokens_details:a}:{},output_tokens:n,...Object.keys(l).length>0?{output_tokens_details:l}:{},total_tokens:r}}function hs(e,t){let n=V(e.function);return{type:`function_call`,id:t,call_id:U(e.id)??`call_${Zr()}`,name:U(n.name)??``,arguments:U(n.arguments)??``,status:`completed`,namespace:null}}function gs(e,t,n,r,i){let a=t===`in_progress`,o=e.requestEcho??{};return{id:e.id,created_at:e.created,error:null,incomplete_details:t===`incomplete`?{reason:fs(i)}:null,instructions:a?o.instructions??null:null,metadata:a?null:{},...e.model===void 0?{}:{model:e.model},object:`response`,output:n,parallel_tool_calls:a,temperature:a?o.temperature??null:0,tool_choice:`auto`,tools:a&&Array.isArray(o.tools)?o.tools:[],top_p:a?o.top_p??1:null,max_output_tokens:null,previous_response_id:null,reasoning:a?{effort:null,summary:null}:null,status:t,text:a?o.text??null:{},truncation:a?o.truncation??null:null,usage:r,user:a?o.user??null:null,store:a?!0:null}}function _s(e,t){let n=V(H(e.choices)[0]),r=V(n.message),i=U(n.finish_reason),a=ps(r.content),o=H(r.tool_calls),s=U(r.reasoning_content),c=[];s!==null&&s!==``&&c.push({type:`reasoning`,id:`rs_${Zr()}`,status:ds(i),role:`assistant`,content:[{type:`output_text`,text:s,annotations:[]}],phase:null}),r.content!==null&&r.content!==void 0&&c.push({type:`message`,id:`msg_${Zr()}`,status:ds(i),role:`assistant`,content:[{type:`output_text`,text:a,annotations:[]}],phase:null});for(let e of o)c.push(hs(V(e),`fc_${Zr()}`));return gs(t,ds(i),c,ms(e.usage),i)}function vs(e){let t=V(e),n=U(t.model);return _s(us(t),{id:`resp_${Zr()}`,created:Qr(),...n===null?{}:{model:n}})}function ys(e){let t=e.error;if(t)throw new mr(typeof t!=`object`||!t||Array.isArray(t)?String(t):typeof V(t).message==`string`?V(t).message:JSON.stringify(t),{status:ui(t)});let n={choices:(Array.isArray(e.choices)?e.choices:[]).map(e=>{let t=V(e),n=t.finish_reason,r=V(t.delta);return{finish_reason:n?ss(String(n)):null,index:typeof t.index==`number`?t.index:0,delta:{content:r.content==null?null:String(r.content),role:r.role==null?null:String(r.role),...r.reasoning_content==null?{}:{reasoning_content:String(r.reasoning_content)},tool_calls:Array.isArray(r.tool_calls)?r.tool_calls.map((e,t)=>{let n={...V(e)};return n.index===void 0&&(n.index=t),n.type===void 0&&(n.type=`function`),n}):null}}})};return typeof e.model==`string`&&(n.model=e.model),`usage`in e&&e.usage!=null&&(n.usage=e.usage),n}var bs=10;function xs(e){let t={};for(let[n,r]of Object.entries(e))r!==null&&(t[n]=r);return t}function Ss(e){if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var Cs=class{#e=0;#t=!1;#n=!1;#r=`msg_${Zr()}`;#i=0;#a=``;#o=1;#s=new Map;#c=null;#l=null;#u=null;#d=``;#f;#p=null;constructor(e){this.#f=e}#m(){return this.#p===null?this.#f:{...this.#f,model:this.#p}}translateFrame(e){if(this.#n)return[];let t=U(e.model);t!==null&&(this.#p=t);let n=[];if(!this.#t){this.#t=!0;let e=gs(this.#m(),`in_progress`,[],null,null);n.push(this.#S({type:`response.created`,response:e})),n.push(this.#S({type:`response.in_progress`,response:e})),n.push(...this.#h())}B(e.usage)&&(this.#l=e.usage);let r=V(H(e.choices)[0]),i=V(r.delta),a=i.reasoning_content,o=typeof a==`string`&&a!==``?a:null;if(o!==null){n.push(...this.#g(o));let e=i.content;typeof e==`string`&&e!==``&&(this.#a+=e);let t=U(r.finish_reason);return t!==null&&t!==``&&(this.#c=t),n}let s=i.content;typeof s==`string`&&s!==``&&(this.#a+=s,n.push(this.#S({type:`response.output_text.delta`,item_id:this.#r,output_index:this.#i,content_index:0,delta:s})));for(let e of H(i.tool_calls))n.push(...this.#_(V(e)));let c=U(r.finish_reason);return c!==null&&c!==``&&(this.#c=c),n}flush(){if(!this.#t||this.#n)return[];this.#n=!0;let e=[];for(let t of this.#b())e.push(...this.#y(t));e.push(...this.#v());let t=ds(this.#c);return e.push(this.#S({type:`response.completed`,response:gs(this.#m(),t,this.#x(),ms(this.#l),this.#c)})),e}#h(){return[this.#S({type:`response.output_item.added`,output_index:this.#i,item:{type:`message`,id:this.#r,status:`in_progress`,role:`assistant`,content:[]}}),this.#S({type:`response.content_part.added`,item_id:this.#r,output_index:this.#i,content_index:0,part:{type:`output_text`,text:``,annotations:[]}})]}#g(e){return this.#u===null&&(this.#u=`rs_${Zr()}`),this.#d+=e,[this.#S({type:`response.reasoning_summary_text.delta`,item_id:this.#u,output_index:0,delta:e})]}#_(e){let t=Yr(e.index)??0,n=V(e.function),r=this.#s.get(t),i=[];if(r===void 0){let a=U(e.id)??`call_${Zr()}`;r={itemId:`fc_${a}`,outputIndex:this.#o,callId:a,name:U(n.name)??``,args:``},this.#o+=1,this.#s.set(t,r),i.push(this.#S({type:`response.output_item.added`,output_index:r.outputIndex,item:{type:`function_call`,id:r.itemId,call_id:r.callId,name:r.name,arguments:``,status:`in_progress`}}))}let a=U(n.name);a!==null&&a!==``&&r.name===``&&(r.name=a);let o=Ss(n.arguments);if(o!==``){r.args+=o;for(let e=0;e<o.length;e+=bs)i.push(this.#S({type:`response.function_call_arguments.delta`,item_id:r.itemId,output_index:r.outputIndex,delta:o.slice(e,e+bs)}))}return i}#v(){let e=this.#r,t=this.#i,n={type:`output_text`,text:this.#a,annotations:[]};return[this.#S({type:`response.output_text.done`,item_id:e,output_index:t,content_index:0,text:this.#a}),this.#S({type:`response.content_part.done`,item_id:e,output_index:t,content_index:0,part:n}),this.#S({type:`response.output_item.done`,output_index:t,item:{type:`message`,id:e,status:`completed`,role:`assistant`,content:[n]}})]}#y(e){return[this.#S({type:`response.function_call_arguments.done`,item_id:e.itemId,output_index:e.outputIndex,arguments:e.args}),this.#S({type:`response.output_item.done`,output_index:e.outputIndex,item:{type:`function_call`,id:e.itemId,call_id:e.callId,name:e.name,arguments:e.args,status:`completed`}})]}#b(){return[...this.#s.values()].sort((e,t)=>e.outputIndex-t.outputIndex)}#x(){let e=[];this.#u!==null&&e.push({type:`reasoning`,id:this.#u,status:ds(this.#c),role:`assistant`,content:[{type:`output_text`,text:this.#d,annotations:[]}]}),this.#a!==``&&e.push({type:`message`,id:this.#r,status:`completed`,role:`assistant`,content:[{type:`output_text`,text:this.#a,annotations:[]}]});for(let t of this.#b())e.push({type:`function_call`,id:t.itemId,call_id:t.callId,name:t.name,arguments:t.args,status:`completed`});return e}#S(e){this.#e+=1;let t={...e,sequence_number:this.#e};return e.response!==void 0&&(t.response=xs(e.response)),t}},ws=class{inbound=`openai-responses`;upstream=`openai`;translateRequest(e){return as(e)}translateResponse(e){return vs(e)}async*bridgeFrames(e,t,n){let r=new Cs({id:`resp_${Zr()}`,created:Qr(),...B(n)?{requestEcho:n}:{}});for await(let t of e)for(let e of r.translateFrame(ys(t)))yield e;for(let e of r.flush())yield e}usageFromFrame(e){return Mo(e)}errorEnvelope(e,t){return ka(e,t)}};function Ts(e){return Array.isArray(e)?e.map(e=>{if(!B(e)||e.type!==`reasoning`||`summary`in e)return e;let t=e.content,n=typeof t==`string`?t:``;return{...e,summary:n.length>100?n.slice(0,100):n}}):e}function Es(e){let t=e;return{...t,input:Ts(t.input)}}var Ds=[`error`,`incomplete_details`,`instructions`,`metadata`,`model`,`object`,`parallel_tool_calls`,`temperature`,`tool_choice`,`tools`,`top_p`,`max_output_tokens`,`previous_response_id`,`reasoning`,`status`,`text`,`truncation`,`usage`,`user`,`store`],Os=[`input_tokens_details`,`output_tokens_details`,`cost`],ks={audio_tokens:null,cached_tokens:0,cached_tokens_details:null,image_tokens:null,text_tokens:null,video_tokens:null},As={audio_tokens:null,reasoning_tokens:null,text_tokens:null};function js(e,t){let n={...e};for(let[e,r]of Object.entries(t))e in n||(n[e]=r);return n}function Ms(e){let t=e.usage;if(!B(t))return;let n={...t};for(let e of Os)e in n||(n[e]=null);let r=n.input_tokens_details;B(r)&&(n.input_tokens_details=js(r,ks));let i=n.output_tokens_details;B(i)&&(n.output_tokens_details=js(i,As)),e.usage=n}function Ns(e){let t=e.tools;if(!Array.isArray(t))return;let n=null;for(let[e,r]of t.entries()){if(!B(r)||r.type!==`function`)continue;let i=!(`strict`in r),a=!(`defer_loading`in r);if(!i&&!a)continue;let o={...r,...i?{strict:null}:{},...a?{defer_loading:null}:{}};(n??=[...t])[e]=o}n!==null&&(e.tools=n)}function Ps(e){let t=e.output;if(!Array.isArray(t))return;let n=null;for(let[e,r]of t.entries()){if(!B(r))continue;let i=r.type===`function_call`&&!(`namespace`in r)?`namespace`:r.type===`message`&&!(`phase`in r)?`phase`:null;i!==null&&((n??=[...t])[e]={...r,[i]:null})}n!==null&&(e.output=n)}function Fs(e){for(let t of Ds)t in e||(e[t]=null);return Ns(e),Ps(e),Ms(e),e}function Is(e){return Fs({...e})}function Ls(e){let t=e.error;if(B(t)&&t.code===null)return{...e,error:{...t,code:`unknown_error`}};let n=e.response;if(B(n)){let t=n.error;if(B(t)&&t.code===null)return{...e,response:{...n,error:{...t,code:`unknown_error`}}}}return null}function Rs(e){if(!B(e))return e;let t=!1;for(let n of Object.values(e))if(n===null){t=!0;break}if(!t)return e;let n={};for(let[t,r]of Object.entries(e))r!==null&&(n[t]=r);return n}function zs(e){let t=e.response;if(!B(t))return e;let n={...t},r=!1;for(let[e,i]of Object.entries(t))i===null&&(delete n[e],r=!0);let i=n.tools;if(Array.isArray(i)){let e=i.map(Rs);e.some((e,t)=>e!==i[t])&&(n.tools=e,r=!0)}return r?{...e,response:n}:e}var Bs=class{inbound=`openai-responses`;upstream=`openai-responses`;translateRequest(e){return Es(e)}translateResponse(e){return Is(e)}async*bridgeFrames(e){for await(let t of e){let e=t;yield zs(Ls(e)??e)}}usageFromFrame(e){return Mo(e)}errorEnvelope(e,t){return ka(e,t)}},Vs={anthropicToAnthropic:new Gi,anthropicToChatCompletions:new Ta,chatCompletionsToAnthropic:new Ao,chatCompletionsToChatCompletions:new jo,responsesToResponses:new Bs,responsesToChatCompletions:new ws},Hs=class{anthropicToAnthropic(e){return this.#e(`anthropicToAnthropic`,e)}anthropicToChatCompletions(e){return this.#e(`anthropicToChatCompletions`,e)}chatCompletionsToAnthropic(e){return this.#e(`chatCompletionsToAnthropic`,e)}chatCompletionsToChatCompletions(e){return this.#e(`chatCompletionsToChatCompletions`,e)}responsesToResponses(e){return this.#e(`responsesToResponses`,e)}responsesToChatCompletions(e){return this.#e(`responsesToChatCompletions`,e)}#e(e,t){return new Jr(Vs[e],t??{},e)}};function Us(){return new Hs}var Ws={400:`invalid_request_error`,401:`authentication_error`,403:`permission_error`,404:`not_found_error`,413:`request_too_large`,429:`rate_limit_error`,500:`api_error`,529:`overloaded_error`},Gs={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`},Ks=new Set([204,205,304]);function qs(e){let t;try{t=JSON.parse(e)}catch{return null}return z(t)?t:null}function Js(e){let t=e.type===`error`?e.error:void 0;return z(t)&&typeof t.type==`string`&&typeof t.message==`string`}function Ys(e){let t=qs(e);if(t===null)return e;if(Js(t))return String(t.error.message);let n=t.detail;if(z(n)&&typeof n.message==`string`)return n.message;let r=t.Message;if(typeof r==`string`&&r!==``)return r;let i=t.message;return typeof i==`string`&&i!==``?i:e}function Xs(e,t,n){let r=t===``||Ks.has(e)?null:t;return new Response(r,{status:e,headers:{"content-type":n}})}function Zs(e,t,n){let r=e=>Ws[e]??`api_error`,i=qs(t),a;if(i!==null&&Js(i))a={...i},n!==void 0&&i.request_id===void 0&&(a.request_id=n);else{let i={type:`error`,error:{type:r(e),message:Ys(t)}};n!==void 0&&(i.request_id=n),a=i}return Xs(e,JSON.stringify(a),`application/json`)}function Qs(e,t){let n={error:{message:Ys(t),type:(e=>{let t=Gs[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t})(e),param:null,code:String(e)}};return Xs(e,JSON.stringify(n),`application/json`)}function $s(e,t,n,r){return e===`anthropic`?Zs(t,n,r):Qs(t,n)}function ec(e,t,n,r){return e===`anthropic`?Zs(t,n,r):Qs(t,n)}var tc={openai:`chat/completions`,anthropic:`messages`,"openai-responses":`responses`},nc={openai:`https://api.openai.com`,anthropic:`https://api.anthropic.com`,"openai-responses":`https://api.openai.com`};function rc(e){let t=e.provider,n=(e.apiBase??nc[t]).replace(/\/+$/,``),r=tc[t];return t===`anthropic`?n.endsWith(`/v1/messages`)?n:e.autoV1!==!1&&!/\/v\d+$/i.test(n)?`${n}/v1/${r}`:`${n}/${r}`:n.includes(r)?n:e.autoV1!==!1&&!/\/v\d+$/i.test(n)?`${n}/v1/${r}`:`${n}/${r}`}var ic=6e5,ac=12e4,oc=65536,sc=4096,cc=class{#e;#t;#n;#r;#i;#a;#o=new AbortController;#s=new AbortController;#c=null;constructor(e,t){this.#e=e,this.#t=t.inbound,this.#n=t.requestId,this.#r=t.fetchFn??fetch,this.#i=t.timeouts?.firstByteMs??ic,this.#a=t.timeouts?.idleMs??ac;let n=t.signal;n!==void 0&&(n.aborted?this.#o.abort():n.addEventListener(`abort`,()=>this.#o.abort(),{once:!0}))}abort(){this.#o.abort()}async send(){let e;try{this.#u(this.#i),e=await this.#r(this.#e.url,{method:`POST`,headers:this.#e.headers,body:JSON.stringify(this.#e.body),signal:AbortSignal.any([this.#o.signal,this.#s.signal])})}catch(e){if(this.#l(),this.#s.signal.aborted&&!this.#o.signal.aborted){let e=`upstream timeout: no response headers within ${String(this.#i)}ms`;return this.#f(504,e)}return this.#f(502,or(e))}let t=e.body;if(t===null?this.#l():(this.#u(this.#a),t=this.#p(t)),!e.ok){let n=await uc(t,oc),r=n.length<=sc?n:n.slice(0,sc);return{kind:`error`,status:e.status,response:$s(this.#t,e.status,r,this.#n)}}return{kind:`ok`,transport:{status:e.status,headers:sr(e.headers),stream:t,text:()=>t===null?e.text():new Response(t).text()}}}#l(){this.#c!==null&&(clearTimeout(this.#c),this.#c=null)}#u(e){this.#l(),this.#c=setTimeout(()=>{this.#c=null,this.#s.abort()},e),this.#c.unref()}#d(){return new mr(`upstream timeout: no data for ${String(this.#a)}ms`,{status:504})}#f(e,t){return{kind:`error`,status:e,response:ec(this.#t,e,t,this.#n)}}#p(e){let t=null;return new ReadableStream({start:async n=>{let r=e.getReader();t=r;let i=!1,a=()=>{try{n.close()}catch{}},o=e=>{try{n.error(e)}catch{}},s=e=>{i||(i=!0,this.#l(),o(e),r.cancel().catch(()=>{}))};if(this.#s.signal.aborted){s(this.#d());return}let c=()=>s(this.#d());this.#s.signal.addEventListener(`abort`,c,{once:!0});try{for(;;){let{done:e,value:t}=await r.read();if(i)return;if(e){this.#l(),a();return}this.#u(this.#a),n.enqueue(t)}}catch(e){this.#l(),i||o(e)}finally{this.#s.signal.removeEventListener(`abort`,c)}},cancel:e=>{this.#l(),t!==null&&t.cancel(e).catch(()=>{})}})}};function lc(e){e!==null&&e.cancel().catch(()=>{})}async function uc(e,t){if(e===null)return``;let n=e.getReader(),r=new TextDecoder(`utf-8`),i=``,a=0;try{for(;a<t;){let{done:e,value:t}=await n.read();if(e)break;a+=t.byteLength,i+=r.decode(t,{stream:!0})}return i+r.decode()}catch{return i}finally{n.cancel().catch(()=>{})}}var dc=new Set([`authorization`,`x-api-key`,`cookie`,`proxy-authorization`,`host`,`content-length`,`content-type`,`connection`,`keep-alive`,`proxy-connection`,`transfer-encoding`,`te`,`trailer`,`upgrade`,`expect`,`accept-encoding`,`x-real-ip`]),fc=`sk-ant-oat`,pc=`oauth-2025-04-20`,mc="Missing Anthropic API Key - A call is being made to anthropic but no key is set either in the environment variables or via params. Please set `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` in your environment vars";function hc(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();dc.has(e)||e.startsWith(`proxy-`)||e.startsWith(`x-forwarded-`)||(t[n]=r)}return t}function gc(e,t,n){let r=(e,t)=>e===void 0?t:e.split(`,`).map(e=>e.trim()).includes(t)?e:`${e}, ${t}`,i=(e,t)=>{let n={...e},i=t,a=Object.keys(n).find(e=>e.toLowerCase()===`authorization`),o=a===void 0?``:n[a]??``;if(o.startsWith(`Bearer ${fc}`)){i=o.replace(/^Bearer /,``);for(let e of Object.keys(n))(e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`)&&delete n[e];n.authorization=o,n[`anthropic-beta`]=r(n[`anthropic-beta`],pc),n[`anthropic-dangerous-direct-browser-access`]=`true`}if(i===void 0)throw new mr(mc,{status:401});let s=i.startsWith(fc),c={"anthropic-version":`2023-06-01`,accept:`application/json`,"content-type":`application/json`};return s?c.authorization=`Bearer ${i}`:c[`x-api-key`]=i,{...n,...c}},a=(e,t)=>{let n={...e};return t!==void 0&&(n={...n,Authorization:`Bearer ${t}`}),!(`content-type`in n)&&!(`Content-Type`in n)&&(n={...n,"Content-Type":`application/json`}),n},o={...hc(n),...t.headers??{}};return e===`anthropic`?i(o,t.apiKey):a(o,t.apiKey)}var _c=/<invoke\s+name=/g,vc=2;function yc(e,t){let n=gc(e.provider,e,t??{});return{upstreamRequest:e=>({...e,headers:n})}}function bc(e){return{clientRequest:t=>z(t.body)?{...t,body:{...t.body,model:e.modelName}}:t}}function xc(e,t){let n=e=>z(e.error),r=t.name||t.modelName;switch(e){case`anthropicToChatCompletions`:return{clientResponse:e=>{let t=e;if(t.type===`message_start`){let n=t.message;return z(n)?{...t,message:{...n,model:r}}:e}return t.type===`message`?{...t,model:r}:e}};case`chatCompletionsToAnthropic`:return{clientResponse:e=>{let t=e;return n(t)?e:{...t,model:r}}};case`chatCompletionsToChatCompletions`:return{clientResponse:e=>{let t=e;return t.object===`chat.completion.chunk`?e:{...t,model:r}}};case`responsesToChatCompletions`:case`responsesToResponses`:return{clientResponse:e=>{let t=e;return n(t)?e:{...t,model:r}}}}}function Sc(e){let t=(e,t)=>{let n=tr.indexOf(e),r=tr.indexOf(t);return n<0||r<0||n<=r?e:t};return{upstreamRequest:n=>{if(!z(n.body))return n;let r=n.body.reasoning_effort;if(typeof r!=`string`)return n;let i=t(r,e);return i===r?n:{...n,body:{...n.body,reasoning_effort:i}}}}}function Cc(e){let t=0,n=0;return{clientResponse:r=>{let i=r;if(i.type!==`content_block_delta`)return r;let a=i.delta;if(!z(a)||a.type!==`thinking_delta`)return r;let o=a.thinking;if(typeof o!=`string`||o===``)return r;t+=o.length,_c.lastIndex=0;for(let e=_c.exec(o);e!==null;e=_c.exec(o))n+=1;if(t>e&&n>=vc)throw new mr(`Upstream reasoning degraded: ${String(t)} reasoning chars containing ${String(n)} hand-written tool invocations and no tool_use block; stream aborted to avoid a long stall.`);return r}}}function wc(e,t){let n=()=>({upstreamRequest:e=>{if(!e.stream||!z(e.body))return e;let t=e.body.stream_options;if(z(t)&&t.include_usage===!0)return e;let n={...z(t)?t:{},include_usage:!0};return{...e,body:{...e.body,stream_options:n}}}}),r=()=>({upstreamRequest:e=>{if(!z(e.body))return e;let t=e.body.tools;if(!Array.isArray(t)||t.length===0)return e;let n=!1,r=t.map(e=>{if(!z(e)||e.type!==`custom`)return e;let{type:t,...r}=e;return n=!0,r});return n?{...e,body:{...e.body,tools:r}}:e}}),i=[];(e===`anthropicToChatCompletions`||e===`chatCompletionsToChatCompletions`||e===`responsesToChatCompletions`)&&i.push(n()),e===`chatCompletionsToAnthropic`&&i.push(r()),e===`anthropicToChatCompletions`&&t.maxReasoningEffort!==void 0&&i.push(Sc(t.maxReasoningEffort));let a=t.thinkingGuardMaxChars??0;return(e===`anthropicToAnthropic`||e===`anthropicToChatCompletions`)&&a>0&&i.push(Cc(a)),i}function Tc(e){if(!z(e))return null;let t=ar(e.prompt_tokens),n=ar(e.completion_tokens);if(t===null&&n===null)return null;let r=z(e.prompt_tokens_details)?e.prompt_tokens_details:{};return{inputTokens:t??0,outputTokens:n??0,cacheReadInputTokens:ar(r.cached_tokens)??0,cacheCreationInputTokens:ar(r.cache_creation_tokens)??ar(e.cache_creation_input_tokens)??0}}function Ec(e){if(!z(e))return null;let t=ar(e.input_tokens),n=ar(e.output_tokens);if(t===null&&n===null)return null;let r=z(e.input_tokens_details)?e.input_tokens_details:{};return{inputTokens:t??0,outputTokens:n??0,cacheReadInputTokens:ar(r.cached_tokens)??0,cacheCreationInputTokens:0}}function Dc(e){return z(e)?e.prompt_tokens!==void 0||e.completion_tokens!==void 0?Tc(e):e.input_tokens_details!==void 0||e.output_tokens_details!==void 0?Ec(e):(e=>{let t=ar(e.input_tokens),n=ar(e.output_tokens);if(t===null&&n===null)return null;let r=ar(e.cache_read_input_tokens),i=ar(e.cache_creation_input_tokens);return{inputTokens:(t??0)+(r??0)+(i??0),outputTokens:n??0,cacheReadInputTokens:r??0,cacheCreationInputTokens:i??0}})(e):null}var Oc=Us();async function kc(e,t,n,r,i){let a=(e,t,n)=>{let r=e=>{let t=null;try{t=new URL(rc(e)).hostname}catch{t=null}return t===null||t===``?`drop`:t!==`openai.com`&&!t.endsWith(`.openai.com`)?`preserve`:`drop`},i=t.rawPassthrough===!0,a=Oc[e]({...i?{translate:!1}:{},...e===`anthropicToChatCompletions`?{topK:r(t)}:{}});if(a.intercept(yc(t,n)),a.intercept(bc(t)),!i){e!==`anthropicToAnthropic`&&a.intercept(xc(e,t));for(let n of wc(e,t))a.intercept(n)}return a},o=e=>(e.headers[`content-type`]??``).includes(`text/event-stream`),s;try{s=a(t,n,i.inboundHeaders)}catch(t){let n=hr(t)??500;return{kind:`error`,status:n,response:ec(e,n,or(t),i.requestId)}}let c=s.begin(),l=await c.request({body:r});if(l.kind===`error`)return{kind:`error`,status:l.status,response:ec(e,l.status,l.message,i.requestId)};let u=await new cc({url:rc(n),...l.value},{inbound:e,requestId:i.requestId,signal:i.signal,timeouts:i.timeouts,fetchFn:i.fetchFn}).send();if(u.kind===`error`)return u;let d=u.transport;if(!o(u.transport))try{let e=await u.transport.text();d={...u.transport,stream:null,text:()=>Promise.resolve(e)}}catch(t){let n=hr(t)??502;return{kind:`error`,status:n,response:ec(e,n,or(t),i.requestId)}}let f;try{f=await c.response({status:d.status,headers:d.headers,body:d.stream,text:d.text})}catch(t){return lc(d.stream),{kind:`error`,status:500,response:ec(e,500,or(t),i.requestId)}}if(f.kind===`error`)return lc(d.stream),{kind:`error`,status:f.status,response:ec(e,f.status,f.message,i.requestId)};let p=f.value;return`stream`in p?{kind:`ok`,sse:!0,stream:p.stream,collectUsage:()=>Dc(p.collectUsage())}:{kind:`ok`,sse:!1,body:p.body,usage:Dc(z(p.body)?p.body.usage:void 0)}}function Ac(e,t,n){return n?e===`anthropic`?t===`anthropic`?`anthropicToAnthropic`:null:e===`openai-responses`?t===`openai-responses`?`responsesToResponses`:null:t===`openai`?`chatCompletionsToChatCompletions`:null:e===`anthropic`?t===`anthropic`?`anthropicToAnthropic`:t===`openai`?`anthropicToChatCompletions`:null:e===`openai-responses`?t===`openai`?`responsesToChatCompletions`:t===`openai-responses`?`responsesToResponses`:null:t===`openai`?`chatCompletionsToChatCompletions`:t===`anthropic`?`chatCompletionsToAnthropic`:null}function jc(e,t){return Ac(e,t.provider,t.rawPassthrough===!0)!==null}async function Mc(e,t,n){return Pc(e,t,n,t.inbound_format===`anthropic`?`anthropic`:`openai`)}async function Nc(e,t,n){return Pc(e,t,n,`openai-responses`)}async function Pc(e,t,n,r){let i=(e,t,n)=>{let r=hr(e)??500;return{kind:`error`,status:r,response:ec(t,r,or(e),n)}};try{return await Fc(e,t,n,r)}catch(e){return i(e,r,n.requestId)}}async function Fc(e,t,n,r){let i=e=>e===`anthropic`?`Anthropic Messages`:e===`openai-responses`?`OpenAI Responses`:`OpenAI Chat Completions`,a=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),o=e.rawPassthrough===!0,s=Ac(r,e.provider,o);if(s===null){let t=e.name||e.modelName;return{kind:`error`,status:400,response:ec(r,400,o?`Model '${t}' has rawPassthrough enabled (upstream '${e.provider}'): ${i(r)} inbound requests cannot be forwarded as-is. Use a matching protocol or turn rawPassthrough off.`:`Model '${t}' (upstream '${e.provider}') does not accept ${i(r)} inbound requests`,n.requestId)}}let c=await kc(r,s,e,r===`anthropic`?a(t,`inbound_format`):t,{signal:n.signal,requestId:n.requestId,inboundHeaders:n.inboundHeaders,timeouts:n.timeouts,fetchFn:n.deps.fetchFn});return c.kind===`error`?{kind:`error`,status:c.status,response:c.response}:c.sse?{kind:`ok`,status:200,sse:!0,body:c.stream,stream:c.stream,usage:null,collectUsage:c.collectUsage}:{kind:`ok`,status:200,sse:!1,body:c.body,usage:c.usage}}var Ic=[`x-litellm-trace-id`,`x-litellm-session-id`],Lc=new Set(Ic),Rc=/^x-.+-session-id$/,zc=/^x-.+-conversation-id$/,Bc=[`thread-id`,`conversation_id`],Vc=/^codex[-_ /]/i,Hc=/^[a-zA-Z0-9_-]{8,}$/,Uc=/^[a-zA-Z0-9_-]+$/,Wc=`_session_`;function Gc(e){let t=new Map;e.forEach((e,n)=>t.set(n.toLowerCase(),e));for(let e of Ic){let n=t.get(e);if(n!==void 0&&Hc.test(n))return n}let n=Lc;for(let[e,r]of t)if(!n.has(e)&&(Rc.test(e)||zc.test(e))&&Hc.test(r))return r;for(let e of[`x-session-id`,`x-conversation-id`]){let n=t.get(e);if(n!==void 0&&Hc.test(n))return n}for(let e of[`session-id`,`session_id`]){let n=t.get(e);if(n!==void 0&&Hc.test(n))return n}let r=t.get(`user-agent`);if(r!==void 0&&Vc.test(r))for(let e of Bc){let n=t.get(e);if(n!==void 0&&Hc.test(n))return n}return``}function Kc(e){let t=e=>{let t=(e,t)=>{if(!z(e))return null;let n=e[t];return typeof n==`string`&&Uc.test(n)?n:null};if(z(e))return t(e,`session_id`);if(typeof e!=`string`)return null;if(e.startsWith(`{`))try{let n=t(JSON.parse(e),`session_id`);if(n!==null)return n}catch{}let n=e.lastIndexOf(Wc);return n===-1?null:t({session_id:e.slice(n+9)},`session_id`)};if(!z(e))return null;let n=e.metadata;return z(n)?t(n.user_id):null}var qc=10485760;function Jc(e){try{return JSON.parse(e)}catch{return e}}function Yc(e){for(let t of e.split(`
|
|
19
|
+
`)){let e=t.trim();if(!e.startsWith(`data: `))continue;let n;try{n=JSON.parse(e.slice(6))}catch{continue}let r=n.error;if(typeof r==`object`&&r&&typeof r.message==`string`)return{message:r.message,status:typeof r.status==`number`?r.status:200};if(typeof n.message==`string`&&typeof n.code==`string`&&!(`choices`in n)&&!(`type`in n))return{message:n.message,status:typeof n.status==`number`?n.status:200}}return null}var Xc=class{#e=0;#t;#n=!1;constructor(e){this.#t=e}get truncated(){return this.#n}append(e,t){return this.#n?e:this.#e+t.length>this.#t?(this.#n=!0,e):(this.#e+=t.length,(e??``)+t)}},Zc=class{text=null;#e;constructor(e){this.#e=e}add(e){this.text=this.#e.append(this.text,e)}},Qc=class{bodyText=null;streamText=null;#e;constructor(e){this.#e=e}addBody(e){this.bodyText=this.#e.append(this.bodyText,e)}addStream(e){this.streamText=this.#e.append(this.streamText,e)}},$c=class{requestId;capture;startedAt=Date.now();http={method:``,url:``,path:``,clientIp:``,sessionId:``,userAgent:``};inboundHeaders=null;inboundBody=void 0;upstreamUrl=null;upstreamRequestHeaders=null;upstreamStatus=null;upstreamResponseHeaders=null;upstreamLatencyMs=null;upstreamTotalMs=null;upstreamHeadAt=0;clientStatus=null;clientResponseHeaders=null;clientBody=void 0;clientError=null;#e;#t;#n;#r;#i;pending=[];constructor(e){this.requestId=e.requestId,this.capture=e.capture,this.#e=new Xc(e.maxBytes??qc),this.#t=new Zc(this.#e),this.#n=new Zc(this.#e),this.#r=new Zc(this.#e),this.#i=new Qc(this.#e)}get inboundBodyText(){return this.#t.text}get upstreamRequestBody(){return this.#n.text}get upstreamResponseText(){return this.#r.text}get clientBodyText(){return this.#i.bodyText}get clientStreamText(){return this.#i.streamText}get truncated(){return this.#e.truncated}setHttpMeta(e){this.http=e}setSessionIdFallback(e){this.http.sessionId===``&&e!==null&&(this.http={...this.http,sessionId:e})}setInbound(e,t){this.capture&&(this.inboundHeaders=e,this.#t.add(t));try{return this.inboundBody=JSON.parse(t),this.setSessionIdFallback(Kc(this.inboundBody)),{body:this.inboundBody,parseError:null}}catch(e){return this.inboundBody={},{body:this.inboundBody,parseError:`invalid JSON body: ${e.message}`}}}setInboundHeaders(e){this.capture&&(this.inboundHeaders=e)}setUpstreamRequest(e,t,n){this.capture&&(this.upstreamUrl=e,this.upstreamRequestHeaders=t,n!==null&&this.#n.add(n))}setUpstreamResponseHead(e,t){this.upstreamHeadAt=Date.now(),this.upstreamStatus=e,this.upstreamResponseHeaders=t,this.upstreamLatencyMs=this.upstreamHeadAt-this.startedAt}markUpstreamDrained(){this.upstreamTotalMs===null&&(this.upstreamTotalMs=Date.now()-this.upstreamHeadAt)}tapUpstreamStream(){let e=this,t=new TextDecoder;return new TransformStream({transform(n,r){r.enqueue(n),e.capture&&e.#r.add(t.decode(n,{stream:!0}))},flush(){e.upstreamTotalMs=Date.now()-e.upstreamHeadAt}})}captureClientBody(e){let t=this;this.pending.push((async()=>{let n=await el(e);t.#i.addBody(n),t.clientBody=Jc(t.#i.bodyText??``)})().catch(()=>{}))}tapClientStream(){let e=this,t=new TextDecoder;return new TransformStream({transform(n,r){if(r.enqueue(n),!e.capture)return;let i=t.decode(n,{stream:!0});e.#i.addStream(i),e.clientError===null&&(i.includes(`"error"`)||i.includes(`"code"`))&&(e.clientError=Yc(i))}})}setClientResponse(e,t){this.clientStatus=e,this.clientResponseHeaders=t}async settle(){this.pending.length>0&&await Promise.all(this.pending)}upstreamFetch(e){return async(t,n)=>{let r=typeof t==`string`?t:t instanceof URL?t.href:t.url,i=n?.headers===void 0?{}:sr(new Headers(n.headers)),a=n?.body,o=typeof a==`string`?a:a==null?null:String(a);this.setUpstreamRequest(r,i,o);let s=await e(t,n);if(this.setUpstreamResponseHead(s.status,sr(s.headers)),s.body===null)return this.markUpstreamDrained(),s;let c=s.body.pipeThrough(this.tapUpstreamStream());return new Response(c,{status:s.status,statusText:s.statusText,headers:s.headers})}}toContentCapture(e){if(!this.capture)return null;let t=e=>e===null?null:e.split(`
|
|
20
20
|
|
|
21
|
-
`).filter(e=>e.trim()!==``);return{inboundRequest:this.truncated?null:this.inboundBody,upstreamRequest:this.upstreamUrl===null?null:{url:this.upstreamUrl,headers:this.upstreamRequestHeaders??{},body:Sl(this.upstreamRequestBody??``)},upstreamResponseText:e?null:this.upstreamResponseText,upstreamStreamFrames:e?t(this.upstreamResponseText):null,clientResponse:e?void 0:this.clientBody,clientStreamFrames:e?t(this.clientStreamText):null,truncated:this.truncated}}toTrace(e){let t=e.hookCtx?.model!==null&&e.hookCtx?.model!==void 0?{name:e.hookCtx.model.name,provider:e.hookCtx.model.provider,upstreamModel:e.hookCtx.model.upstreamModel,apiBase:e.hookCtx.model.apiBase}:null;return{requestId:this.requestId,time:new Date().toISOString(),durationMs:Date.now()-this.startedAt,status:e.status,streaming:e.streaming,http:this.http,route:t,inbound:{headers:this.inboundHeaders,bodyText:this.inboundBodyText,body:this.truncated?null:this.inboundBody},upstream:{url:this.upstreamUrl,requestHeaders:this.upstreamRequestHeaders,requestBody:this.upstreamRequestBody,status:this.upstreamStatus,responseHeaders:this.upstreamResponseHeaders,responseText:this.upstreamResponseText,latencyMs:this.upstreamLatencyMs,totalMs:this.upstreamTotalMs},client:{status:this.clientStatus,headers:this.clientResponseHeaders,body:this.clientBody,streamText:this.clientStreamText},usage:e.usage,stopReason:null,error:e.error,truncated:this.truncated}}};async function Ol(e){let t=new TextDecoder,n=``,r=e.getReader();for(;;){let{done:e,value:i}=await r.read();if(e)break;n+=t.decode(i,{stream:!0})}return n+=t.decode(),n}var kl=[`onAuthorize`,`onModelList`,`onModel`,`onModelNotFound`,`onModelRequest`,`onModelResponse`];function Al(e){return{requestId:e.requestId,inboundProtocol:e.inboundProtocol,requestModel:e.requestModel,startedAt:e.startedAt,userAgent:e.userAgent??``,values:{},principal:void 0,model:null}}var jl=class{registry=new Map;addHook(e,t){let n=this.registry.get(e)??[];return n.push(t),this.registry.set(e,n),this}addAll(e){if(e===void 0)return this;for(let t of Object.keys(e)){let n=e[t];n!==void 0&&this.addHook(t,n)}return this}has(e){return(this.registry.get(e)?.length??0)>0}async run(e,t){let n=this.registry.get(e);if(n===void 0)return;let r=!kl.includes(e),i;for(let a of n)try{i=await a(t)}catch(t){if(!r)throw t;dt(`[gateway] hook ${e} threw, ignored:`,t)}return i}},Ml=67108864;function Nl(e){let t=e.get(`content-length`);if(t===null)return null;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:null}var Pl=class{#e=!1;#t;#n;#r;#i;constructor(e,t,n){this.#t=e,this.#n=e.session,this.#r=t,this.#i=n}async finish(e){if(this.#e)return;this.#e=!0,await this.#n.settle();let t=this.#t.hookCtx??Al({requestId:this.#n.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:this.#n.startedAt,userAgent:this.#n.http.userAgent}),n=e.error??(this.#n.clientError===null?null:{stage:`stream`,message:this.#n.clientError.message,status:this.#n.clientError.status}),r={ctx:t,finishedAt:Date.now(),durationMs:Date.now()-this.#n.startedAt,streaming:e.streaming,status:e.status,stopReason:null,usage:e.usage,error:n===null?null:{message:n.message,status:n.status},capture:this.#n.toContentCapture(e.streaming)};if(n!==null&&await this.#r.run(`onError`,{error:n,ctx:t}),await this.#r.run(`onFinish`,r),this.#i.traceSink!==void 0)try{await this.#i.traceSink.write(this.#n.toTrace({status:e.status,streaming:e.streaming,error:n,usage:e.usage,hookCtx:t}))}catch(e){dt(`[observability] trace sink failed:`,e)}}finishStream(e,t=null){this.#e||this.finish({status:e,streaming:!0,error:t,usage:this.#t.collectUsage===null?this.#t.traceUsage:this.#t.collectUsage()})}};function Fl(e,t){return async(n,r)=>{let i=n.get(`gctx`),a=i.session,o=new Pl(i,e,t),s=new URL(n.req.url);a.setHttpMeta({method:n.req.method,url:s.toString(),path:s.pathname,clientIp:Ll(n.req.raw.headers),sessionId:_l(n.req.raw.headers),userAgent:n.req.header(`user-agent`)??``});let c=null;if(n.req.method===`POST`){let e=t.maxBodyBytes??Ml,r=Nl(n.req.raw.headers),s=r!==null&&r>e?r:null;if(s===null)try{let t=await Il(n.req.raw,e);if(t.kind===`tooLarge`)s=t.totalBytes;else{let{body:e,parseError:r}=a.setInbound(or(n.req.raw.headers),t.text);c=r,i.inboundBody=e,n.req.bodyCache.text=t.text}}catch(e){i.inboundBody={},c=`invalid request body: ${e.message}`}if(s!==null){let t=`request body too large: ${String(s)} bytes exceeds limit ${String(e)}`;return n.header(`x-request-id`,i.requestId),await o.finish({status:413,streaming:!1,error:{stage:`route`,message:t,status:413},usage:null}),n.json({error:{message:t,type:`RequestTooLarge`,code:`413`}},413)}}else a.setInboundHeaders(or(n.req.raw.headers));i.parseError=c;try{await r()}catch(e){throw await o.finish({status:500,streaming:!1,error:{stage:`handler`,message:ar(e),status:500},usage:null}),e}if(n.header(`x-request-id`,i.requestId),(n.res.headers.get(`content-type`)??``).includes(`text/event-stream`)&&n.res.body!==null){a.setClientResponse(n.res.status,or(n.res.headers));let e=(a.capture?n.res.body.pipeThrough(a.tapClientStream()):n.res.body).pipeThrough(new TransformStream({flush(){o.finishStream(200)}})).getReader(),t=new ReadableStream({async pull(t){try{let{done:n,value:r}=await e.read();if(n){try{t.close()}catch{}o.finishStream(200);return}try{t.enqueue(r)}catch{}}catch(e){try{t.close()}catch{}o.finishStream(200,{stage:`upstream`,message:`upstream stream interrupted: ${ar(e)}`,status:200})}},cancel(){e.cancel().catch(()=>{}),o.finishStream(499)}},{highWaterMark:0});return n.res=new Response(t,{status:n.res.status,statusText:n.res.statusText,headers:n.res.headers}),n.res}if(a.capture&&n.res.body!==null){let[e,t]=n.res.body.tee();a.captureClientBody(t),n.res=new Response(e,{status:n.res.status,statusText:n.res.statusText,headers:n.res.headers})}let l=i.traceError??(c===null?null:{stage:`handler`,message:c,status:n.res.status});return await o.finish({status:n.res.status,streaming:!1,error:l,usage:i.traceUsage}),n.res}}async function Il(e,t){let n=e.body;if(n===null)return{kind:`ok`,text:``};let r=n.getReader(),i=new TextDecoder,a=``,o=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(o+=n.byteLength,o>t)return r.cancel().catch(()=>{}),{kind:`tooLarge`,totalBytes:o};a+=i.decode(n,{stream:!0})}return{kind:`ok`,text:a+i.decode()}}function Ll(e){let t=e.get(`x-forwarded-for`)?.split(`,`)[0]?.trim();return t!==void 0&&t!==``?t.replace(/^::ffff:/,``):``}var Rl=3.5,zl=8,Bl=24;function Vl(e,t=0){if(e==null||t>32)return 0;if(typeof e==`string`)return e.length;if(typeof e==`number`||typeof e==`boolean`)return String(e).length;if(Array.isArray(e)){let n=0;for(let r of e)n+=Vl(r,t+1);return n}if(typeof e==`object`){let n=0;for(let[r,i]of Object.entries(e))n+=r.length+Vl(i,t+1);return n}return 0}function Hl(e){return e<=0?0:Math.max(1,Math.ceil(e/Rl))}function Ul(e,t){if(Array.isArray(e)){let n=0;for(let r of e)n+=Vl(r)+t;return n}return e===void 0?0:Vl(e)}function Wl(e){let t=0;return t+=Ul(e.messages,zl),t+=Vl(e.system),t+=Vl(e.thinking),t+=Vl(e.output_config),t+=Ul(e.tools,Bl),{input_tokens:Hl(t)}}var Gl=class{requestId;deployments;runner;dispatchCtx;session;inboundBody=void 0;parseError=null;hookCtx=null;traceError=null;traceUsage=null;collectUsage=null;constructor(e){this.requestId=e.requestId,this.deployments=e.deployments,this.runner=e.runner,this.dispatchCtx=e.dispatchCtx,this.session=e.session}},Kl={"content-type":`text/event-stream; charset=utf-8`,"cache-control":`no-cache`,connection:`keep-alive`,"x-accel-buffering":`no`};function ql(e){let t=new $n,n=e.runner??new jl().addAll(e.hooks),r=e.captureContent===!0,i=e.maxBodyBytes;return t.use(`*`,async(t,i)=>{let a=e.deps?.randomId?.()??j(),o=new Dl({requestId:a,capture:r}),s=r?{...e.deps,fetchFn:o.upstreamFetch(e.deps?.fetchFn??fetch)}:e.deps??{},c={};t.req.raw.headers.forEach((e,t)=>c[t]=e),c[`x-request-id`]=a,t.set(`gctx`,new Gl({requestId:a,deployments:e.deployments,runner:n,session:o,dispatchCtx:{deps:s,requestId:a,inboundHeaders:Oc(c),signal:t.req.raw.signal,timeouts:void 0}})),await i()}),t.use(`*`,Fl(n,{traceSink:e.traceSink,maxBodyBytes:i})),t.onError((e,t)=>{let n=typeof e?.status==`number`?e.status:500,r=ar(e),i=e instanceof Error?e.name:`InternalServerError`;return t.get(`gctx`).traceError={stage:`handler`,message:r,status:n},t.json({error:{message:r,type:i,code:String(n)}},n)}),t.post(`/v1/chat/completions`,e=>$l(e,`openai`)),t.post(`/v1/messages`,e=>$l(e,`anthropic`)),t.post(`/v1/responses`,e=>Zl(e)),t.post(`/v1/messages/count_tokens`,e=>Ql(e)),t.post(`/responses`,e=>Zl(e)),t.post(`/chat/completions`,e=>$l(e,`openai`)),t.post(`/messages`,e=>$l(e,`anthropic`)),t.post(`/messages/count_tokens`,e=>Ql(e)),t.get(`/v1/models`,e=>Yl(e)),t.get(`/models`,e=>Yl(e)),t}async function Jl(e,t,n){let{response:r,reason:i}=await uu(t,n,e.req.header(`authorization`));return r===null?null:(e.get(`gctx`).traceError={stage:`auth`,message:`Unauthorized: ${i??`rejected`}`,status:401},r)}async function Yl(e){let t=e.get(`gctx`),n=t.runner,r=Math.floor(Date.now()/1e3),i=t.deployments.names.map(e=>({id:e,object:`model`,created:r,owned_by:`litellm-ts`}));if(n.has(`onModelList`)||n.has(`onAuthorize`)){let r=Object.assign(Al({requestId:t.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{models:i});t.hookCtx=r;let a=await Jl(e,n,r);if(a!==null)return a;await n.run(`onModelList`,r)}return e.json({object:`list`,data:i})}async function Xl(e,t){let n=e.get(`gctx`),r=n.runner,i={...n.inboundBody},a=typeof i.model==`string`?i.model:void 0,o=null;if(t.hookCtxWhen===`always`||r.has(`onAuthorize`)){o=Al({requestId:n.requestId,inboundProtocol:t.hookProtocol,requestModel:a??``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),n.hookCtx=o;let i=await Jl(e,r,o);if(i!==null)return i}let s=au(e);if(s!==null)return s;let c=rr(n.deployments,a);if(c===null){let s=await cu(e,r,o,a??``,t.routableAs);s!==null&&(a=s,i.model=s,c=rr(n.deployments,s))}return c===null?ru(e,a??``):(o!==null&&o.model===null&&(o.model=nu(a??``,c)),{body:i,model:a,deployment:c,hookCtx:o})}async function Zl(e){let t=e.get(`gctx`),n=await Xl(e,{hookProtocol:`openai`,routableAs:`openai-responses`,hookCtxWhen:`always`});if(n instanceof Response)return n;let{body:r,deployment:i}=n;return eu(e,await il(i,su(r),t.dispatchCtx))}async function Ql(e){let t=await Xl(e,{hookProtocol:`anthropic`,routableAs:`anthropic`,hookCtxWhen:`ifAuthorize`});if(t instanceof Response)return t;let{body:n}=t;return e.json(Wl(n))}async function $l(e,t){let n=e.get(`gctx`),r=n.runner,i=await Xl(e,{hookProtocol:t,routableAs:t,hookCtxWhen:`always`});if(i instanceof Response)return i;let{body:a,deployment:o}=i,s=i.hookCtx,c=i.model,l=o;if(r.has(`onModel`)){let e=nu(c??``,l),i={...e},a=Object.assign(s,{model:e}),o=await r.run(`onModel`,a),u=a.model??e,d=typeof o==`string`&&o!==``?o:u.name;if(d!==(c??``)){let e=rr(n.deployments,d);e!==null&&tl(t,e)?(c=d,l=e):dt(`[gateway] onModel redirected "${i.name}" -> "${d}" but the target is missing from the deployment table or unroutable for ${t} inbound; keeping the original deployment`)}let f=u.provider===i.provider?l.provider:u.provider,p=u.upstreamModel===i.upstreamModel?l.modelName:u.upstreamModel,m=u.apiBase===i.apiBase?l.apiBase:u.apiBase;l={...l,provider:f,modelName:p,apiBase:m},s.model={name:c??l.name,provider:f,upstreamModel:p,apiBase:m}}if(r.has(`onModelRequest`)||r.has(`onModelResponse`)){let i=s.model,o=Object.assign(s,{model:i,request:{body:a,headers:{...e.req.header(`authorization`)?{authorization:e.req.header(`authorization`)}:{}}}});await r.run(`onModelRequest`,o);let c=n.dispatchCtx,u={...c,inboundHeaders:{...c.inboundHeaders,...o.request.headers}};return eu(e,await rl(l,ou(o.request.body,t),u),{runner:r,hookCtx:s})}let u=ou(a,t);return eu(e,await rl(l,u,n.dispatchCtx))}async function eu(e,t,n){let r=e.get(`gctx`);if(t.kind===`error`)return r.traceError={stage:`upstream`,...await lu(t.response)},t.response;if(t.sse){if(r.collectUsage=t.collectUsage??null,n!==void 0){let e=Object.assign(n.hookCtx,{model:n.hookCtx.model,response:{status:200,headers:{},streaming:!0,body:null}});await n.runner.run(`onModelResponse`,e)}return tu(t)}r.traceUsage=t.usage??null;let i=t.body;if(n!==void 0){let e=Object.assign(n.hookCtx,{model:n.hookCtx.model,response:{status:200,headers:{},streaming:!1,body:i}});await n.runner.run(`onModelResponse`,e),i=e.response.body}return e.json(i)}function tu(e){return new Response(e.stream??e.body,{status:200,headers:{...Kl}})}function nu(e,t){return{name:e,provider:t.provider,upstreamModel:t.modelName,apiBase:t.apiBase}}function ru(e,t){let n=tr(t);return e.get(`gctx`).traceError={stage:`route`,message:n.error.message,status:404},e.json(n,404)}function iu(e,t){return e.get(`gctx`).traceError={stage:`route`,message:t,status:400},e.json({error:{message:t,type:`invalid_request_error`,code:`400`}},400)}function au(e){let t=e.get(`gctx`).parseError;return t===null?null:iu(e,t)}function ou(e,t){return t===`anthropic`?{...e,inbound_format:`anthropic`}:su(e)}function su(e){let{inbound_format:t,...n}=e;return n}async function cu(e,t,n,r,i){if(!t.has(`onModelNotFound`))return null;let a=Object.assign(n??Al({requestId:e.get(`gctx`).requestId,inboundProtocol:i===`anthropic`?`anthropic`:`openai`,requestModel:r,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{requestedModel:r}),o=await t.run(`onModelNotFound`,a);if(typeof o!=`string`||o===``)return null;let s=rr(e.get(`gctx`).deployments,o);return s===null||!tl(i,s)?null:o}async function lu(e){let t=e.status,n=``;try{n=await e.clone().text()}catch{return{message:`upstream responded ${String(t)}`,status:t}}let r;try{r=JSON.parse(n)}catch{r=null}let i=r;return{message:typeof i==`object`&&i?typeof i.error?.message==`string`?i.error.message:typeof i.message==`string`?i.message:n.slice(0,500):n.slice(0,500),status:t}}async function uu(e,t,n){if(!e.has(`onAuthorize`))return{response:null,reason:null};let r=null,i={requestId:t.requestId,inboundProtocol:t.inboundProtocol,headers:n===void 0?{}:{authorization:n},principal:void 0,reject:e=>{r=e}};try{await e.run(`onAuthorize`,i)}catch(e){r=ar(e)}return t.principal=i.principal,r===null?{response:null,reason:null}:{response:Response.json({error:{message:`Unauthorized: ${r}`,type:`authentication_error`,code:`401`}},{status:401}),reason:r}}var du=class{hookRunner;_expanded;options;constructor(e){this.options=e,this._expanded=lr(e.config),fu(this._expanded.warnings),this.hookRunner=new jl().addAll(e.hooks)}get expanded(){return this._expanded}reload(e){return this._expanded=lr(e),fu(this._expanded.warnings),this.options={...this.options,config:e},this}addHook(e,t){return this.hookRunner.addHook(e,t),this}async plugin(e,t){await e(this,t)}build(){let e=new $n;return e.get(`/healthz`,e=>e.json({status:`ok`})),e.route(`/`,ql({deployments:this.expanded.deployments,runner:this.hookRunner,deps:this.options.deps,captureContent:!0,traceSink:this.options.traceSink})),e}static get ConfigError(){return cr}};function fu(e){for(let t of e)dt(`[ezllm] ${t}`)}var pu=`重启服务(CLI 会重新生成默认配置)`,mu=class extends Error{constructor(e,t=_t(),n=pu){super(`配置文件解析失败:${t}(${e})。文件可能被截断或损坏,请修复文件内容,或备份后删除该文件并${n}`),this.name=`ConfigParseError`}};function hu(){let e=_t();if(!d(e))return null;let t;try{t=JSON.parse(p(e,`utf-8`))}catch(t){throw new mu(t.message,e)}if(typeof t!=`object`||!t||Array.isArray(t))throw new mu(`顶层必须是 JSON 对象`,e);return t}function gu(){try{return hu()}catch(e){throw e instanceof mu&&(B(`[ezllm] ${e.message}`),process.exit(1)),e}}function _u(e){Pt(_t(),e)}function vu(e){let{masterKey:t,"web-ui":n,logs:r,setup:i,autoUpdate:a,allowLan:o,latencyTest:s,...c}=e;return c}function yu(e){return lr(vu(e))}var bu=`0.0.0.0`,xu=`127.0.0.1`,Su=`监听相关配置已变更,需重启服务后生效;当前仍按启动时的地址与端口运行`;function Cu(e){let t=e?.masterKey;return typeof t==`string`?t.trim():``}function wu(){return Cu(hu())}function Tu(){try{return{config:hu(),broken:!1}}catch(e){if(!(e instanceof mu))throw e;return{config:null,broken:!0}}}function Eu(e){let t=e?.[`web-ui`]?.[`login-account`],n=typeof t?.username==`string`?t.username.trim():``,r=typeof t?.password==`string`?t.password:``;if(n!==``&&r!==``)return{username:n,password:r}}function Du(){let{config:e,broken:t}=Tu(),n=Eu(e);return n===void 0?t?{required:!0,configBroken:!0,username:``,password:``}:{required:!1,configBroken:!1,username:``,password:``}:{required:!0,configBroken:!1,username:n.username,password:n.password}}function Ou(){let{config:e,broken:t}=Tu();if(t)return{completed:!1,deployment:void 0};let n=e?.setup;return n===void 0?{completed:!0,deployment:void 0}:{completed:n.completed===!0,deployment:n.deployment===`server`?`server`:`local`}}function ku(e){return e?.allowLan!==!1}function Au(e){return Cu(e)!==``||Eu(e)!==void 0}function ju(e){return Au(e)?{hostname:ku(e)?bu:xu,source:`config`}:{hostname:xu,source:`credentials`}}function Mu(){try{return ju(hu())}catch{return ju(null)}}function Nu(e,t){return ju(e).hostname!==ju(t).hostname||e?.port!==t.port}function Pu(){return hu()?.logs}function Fu(e){return typeof e==`number`&&Number.isFinite(e)}function Iu(){let e=Pu(),t=(e,t)=>Fu(e)&&e>=0?Math.floor(e):t;return{detailDays:t(e?.[`detail-retention-days`],0),rowDays:t(e?.[`row-retention-days`],0)}}function Lu(){let e=Pu(),t=(e,t)=>Fu(e)&&e>0?e:t,n=t(e?.[`payload-quality`],9),r=Math.min(11,Math.max(5,Math.round(n)));return{syncIntervalMs:Math.floor(t(e?.[`spool-sync-interval-ms`],5e3)),maxBytes:Math.floor(t(e?.[`spool-max-mb`],256))*1024*1024,payloadQuality:r===10?9:r}}var Ru=`__blob`,zu=[`%chat/completions%`,`%/messages%`,`%/embeddings%`,`%/responses%`,`%/models%`,`%model/info%`],Bu=1e3,Vu=134217728;function Hu(e){return new Date(Date.parse(e)+288e5).toISOString().slice(0,10)}function Uu(e){return e instanceof Error?e.message:String(e)}function Wu(){return w(gt(),`spool`)}var Gu=/^(\d+)\.jsonl$/,Ku=`.tmp`,qu=268435456;function Ju(){return new Promise(e=>setImmediate(e))}function Yu(e){return w(Wu(),`${String(e)}.jsonl`)}function Xu(e){return Yu(e)+Ku}function Zu(){jt(),f(Wu(),{recursive:!0})}function Qu(){try{return m(Wu()).map(e=>Gu.exec(e)).filter(e=>e!==null).map(e=>Number(e[1])).sort((e,t)=>e-t)}catch{return[]}}function $u(e){let t;try{t=p(Yu(e),`utf-8`)}catch{return{kind:`missing`}}try{return{kind:`ok`,entry:JSON.parse(t)}}catch{return{kind:`corrupt`}}}function ed(){let e=0;try{for(let t of m(Wu()))if(t.endsWith(Ku))try{y(w(Wu(),t)),e++}catch{}}catch{return 0}return e}var td=class{#e;#t=0;#n=-1;#r=[];#i=Promise.resolve();#a=0;constructor(e={}){let t=e.maxBytes;this.#e=typeof t==`number`&&Number.isFinite(t)&&t>0?t:qu}totalBytes(){if(this.#n>=0)return this.#n;let e=0;try{for(let t of m(Wu()))if(Gu.test(t))try{e+=v(w(Wu(),t)).size}catch{}}catch{e=0}return this.#n=e,e}resetTotalBytes(){this.#n=-1}get droppedCount(){return this.#t}resetDroppedCount(){this.#t=0}listIds(){return Qu()}readRecord(e){return $u(e)}deleteFile(e){try{let t=v(Yu(e)).size;y(Yu(e)),this.#o(-t)}catch{}}#o(e){this.#n>=0&&(this.#n+=e)}#s(e){Zu();let t=Xu(e.id);b(t,e.line,`utf-8`),h(t,Yu(e.id)),this.#o(Buffer.byteLength(e.line))}async#c(e){await N(Wu(),{recursive:!0});let t=Xu(e.id);await I(t,e.line,`utf-8`),await F(t,Yu(e.id)),this.#o(Buffer.byteLength(e.line))}async#l(e){try{await this.#c(e)}catch(e){B(`[spool] 写入失败:`,Uu(e))}}#u(){this.#r.length===0||this.#a>0||(this.#a++,this.#i=this.#i.then(()=>Ju()).then(async()=>{for(this.#a--;this.#r.length>0;)await this.#l(this.#r.shift())}))}write(e,t){let n=JSON.stringify(t);if(this.totalBytes()+Buffer.byteLength(n)>this.#e){this.#t++,(this.#t===1||this.#t%100==0)&&dt(`[spool] 已达磁盘上界(${String(Math.round(this.#e/1024/1024))}MB),累计丢弃 ${String(this.#t)} 条——日志入库可能长期失败`);return}this.#r.push({id:e,line:n}),this.#u()}async flush(){for(;this.#r.length>0||this.#a>0;)this.#u(),await Promise.race([this.#i,Ju()]);await this.#i}flushSync(){for(;this.#r.length>0;){let e=this.#r.shift();try{this.#s(e)}catch(e){B(`[spool] 崩溃前写入失败:`,Uu(e))}}}};function nd(e){let t=$u(e);if(t.kind!==`ok`)return null;let n=t.entry,{response:r,time:i,method:a,path:o,model:s,status:c,stream:l,error:u,ip:d,session_id:f}=n;return{detail:{...n,response:r??null},meta:{_id:e,_spool:`${String(e)}.jsonl`,time:i??null,model:s??``,method:a??null,path:o??null,status:c??null,stream:!!l,error:u??null,ip:d??null,session_id:f??null,input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,cache_read_tokens:n.cache_read_tokens??0,cache_creation_tokens:n.cache_creation_tokens??0,duration:n.duration??0}}}function rd(e){return typeof e==`boolean`?+!!e:e===void 0?null:e}function id(e){return e.map(rd)}function ad(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.text==`string`&&Array.isArray(t.values)}function od(e){return{text:e,values:[]}}function sd(e,...t){let n=``,r=[];for(let i=0;i<e.length;i+=1)if(n+=e[i],i<t.length){let e=t[i];ad(e)?(n+=e.text,r.push(...e.values)):(n+=`?`,r.push(e))}return{text:n,values:r}}var cd=Object.assign(sd,{raw:od}),ld=Symbol(`ezllm-db:table`);function ud(e){return e[ld]}function dd(e){return`"${e.replaceAll(`"`,`""`)}"`}function fd(e){return e.map(e=>dd(e)).join(`, `)}function pd(e){let t={kind:e,notNull:!1,primaryKey:!1,autoIncrement:!1,unique:!1,hasDefault:!1,defaultValue:null,name:``,table:``},n={meta:t,notNull(){return t.notNull=!0,n},primaryKey(r){if(r?.autoIncrement){if(e!==`integer`)throw Error(`SQLite 的 AUTOINCREMENT 只支持 INTEGER 主键,当前列类型为 ${e.toUpperCase()}`);t.autoIncrement=!0}return t.primaryKey=!0,n},default(e){return t.hasDefault=!0,t.defaultValue=e,n},unique(){return t.unique=!0,n}};return n}function md(){return pd(`text`)}function hd(){return pd(`integer`)}function gd(){return pd(`blob`)}function _d(e){return{on(...t){return{name:e,columns:t}}}}function vd(e,t,n=[],r={}){for(let[n,r]of Object.entries(t)){let t=r.meta.table===``&&r.meta.name===``?null:`${r.meta.table}.${r.meta.name}`;if(t!==null&&t!==`${e}.${n}`)throw Error(`表 ${e} 的列 ${n} 复用了已登记给 ${t} 的列 builder;一个列 builder 只能用于一张表的一列,请为每列单独调用 text()/integer() 等创建`);r.meta.name=n,r.meta.table=e}for(let r of n)for(let n of r.columns)if(!(n in t))throw Error(`索引 ${r.name} 引用了表 ${e} 中不存在的列:${n}`);let i=r.primaryKey;if(i!==void 0){if(i.length<2)throw Error(`表 ${e} 的表级主键至少需要两列(单列请用列级 .primaryKey())`);if(Object.values(t).some(e=>e.meta.primaryKey))throw Error(`表 ${e} 同时声明了列级主键与表级复合主键,二者只能取其一`);for(let n of i)if(!(n in t))throw Error(`表 ${e} 的复合主键引用了不存在的列:${n}`)}return{...t,[ld]:{name:e,columns:t,indexes:n,tablePrimaryKey:i}}}function yd(e){return e===null?`NULL`:typeof e==`boolean`?e?`1`:`0`:typeof e==`number`?String(e):`'${e.replaceAll(`'`,`''`)}'`}function bd(e,t){let n=[dd(e),t.kind.toUpperCase()];return t.primaryKey&&t.autoIncrement?n.push(`PRIMARY KEY AUTOINCREMENT`):t.primaryKey&&n.push(`PRIMARY KEY`),t.notNull&&n.push(`NOT NULL`),t.hasDefault&&n.push(`DEFAULT`,yd(t.defaultValue)),n.join(` `)}function xd(e){let t=ud(e),n=[],r=[];for(let[e,i]of Object.entries(t.columns))n.push(` ${bd(e,i.meta)}`),i.meta.unique&&r.push(` UNIQUE (${dd(e)})`);let i=[...n,...r].join(`,
|
|
22
|
-
`),
|
|
23
|
-
`)}
|
|
24
|
-
`)}function
|
|
25
|
-
`).filter(e=>e.startsWith(`data: `)&&e.slice(6).trimEnd()!==`[DONE]`);if(t.length>0)try{let e=JSON.parse(t[0].slice(6)).choices?.[0]?.delta;return e?.content||e?.reasoning_content||`(SSE)`}catch{return`(SSE `+e.length+` chars)`}return`(SSE `+e.length+` chars)`}let t=e;if(t.error)return`错误: `+(t.error.message||JSON.stringify(t.error));let n=t.choices?.[0];return n?n.message?.content?.slice(0,100)||n.delta?.content||`(流式)`:JSON.stringify(e).slice(0,100)}function
|
|
21
|
+
`).filter(e=>e.trim()!==``);return{inboundRequest:this.truncated?null:this.inboundBody,upstreamRequest:this.upstreamUrl===null?null:{url:this.upstreamUrl,headers:this.upstreamRequestHeaders??{},body:Jc(this.upstreamRequestBody??``)},upstreamResponseText:e?null:this.upstreamResponseText,upstreamStreamFrames:e?t(this.upstreamResponseText):null,clientResponse:e?void 0:this.clientBody,clientStreamFrames:e?t(this.clientStreamText):null,truncated:this.truncated}}toTrace(e){let t=e.hookCtx?.model!==null&&e.hookCtx?.model!==void 0?{name:e.hookCtx.model.name,provider:e.hookCtx.model.provider,upstreamModel:e.hookCtx.model.upstreamModel,apiBase:e.hookCtx.model.apiBase}:null;return{requestId:this.requestId,time:new Date().toISOString(),durationMs:Date.now()-this.startedAt,status:e.status,streaming:e.streaming,http:this.http,route:t,inbound:{headers:this.inboundHeaders,bodyText:this.inboundBodyText,body:this.truncated?null:this.inboundBody},upstream:{url:this.upstreamUrl,requestHeaders:this.upstreamRequestHeaders,requestBody:this.upstreamRequestBody,status:this.upstreamStatus,responseHeaders:this.upstreamResponseHeaders,responseText:this.upstreamResponseText,latencyMs:this.upstreamLatencyMs,totalMs:this.upstreamTotalMs},client:{status:this.clientStatus,headers:this.clientResponseHeaders,body:this.clientBody,streamText:this.clientStreamText},usage:e.usage,stopReason:null,error:e.error,truncated:this.truncated}}};async function el(e){let t=new TextDecoder,n=``,r=e.getReader();for(;;){let{done:e,value:i}=await r.read();if(e)break;n+=t.decode(i,{stream:!0})}return n+=t.decode(),n}var tl=[`onAuthorize`,`onModelList`,`onModel`,`onModelNotFound`,`onModelRequest`,`onModelResponse`];function nl(e){return{requestId:e.requestId,inboundProtocol:e.inboundProtocol,requestModel:e.requestModel,startedAt:e.startedAt,userAgent:e.userAgent??``,values:{},principal:void 0,model:null}}var rl=class{registry=new Map;addHook(e,t){let n=this.registry.get(e)??[];return n.push(t),this.registry.set(e,n),this}addAll(e){if(e===void 0)return this;for(let t of Object.keys(e)){let n=e[t];n!==void 0&&this.addHook(t,n)}return this}has(e){return(this.registry.get(e)?.length??0)>0}async run(e,t){let n=this.registry.get(e);if(n===void 0)return;let r=!tl.includes(e),i;for(let a of n)try{i=await a(t)}catch(t){if(!r)throw t;gt(`[gateway] hook ${e} threw, ignored:`,t)}return i}},il=67108864,al=class{#e=!1;#t;#n;#r;#i;constructor(e,t,n){this.#t=e,this.#n=e.session,this.#r=t,this.#i=n}async finish(e){if(this.#e)return;this.#e=!0,await this.#n.settle();let t=this.#t.hookCtx??nl({requestId:this.#n.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:this.#n.startedAt,userAgent:this.#n.http.userAgent}),n=e.error??(this.#n.clientError===null?null:{stage:`stream`,message:this.#n.clientError.message,status:this.#n.clientError.status}),r={ctx:t,finishedAt:Date.now(),durationMs:Date.now()-this.#n.startedAt,streaming:e.streaming,status:e.status,stopReason:null,usage:e.usage,error:n===null?null:{message:n.message,status:n.status},capture:this.#n.toContentCapture(e.streaming)};if(n!==null&&await this.#r.run(`onError`,{error:n,ctx:t}),await this.#r.run(`onFinish`,r),this.#i.traceSink!==void 0)try{await this.#i.traceSink.write(this.#n.toTrace({status:e.status,streaming:e.streaming,error:n,usage:e.usage,hookCtx:t}))}catch(e){gt(`[observability] trace sink failed:`,e)}}finishStream(e,t=null){this.#e||this.finish({status:e,streaming:!0,error:t,usage:this.#t.collectUsage===null?this.#t.traceUsage:this.#t.collectUsage()})}};function ol(e,t){return async(n,r)=>{let i=e=>{let t=e.get(`content-length`);if(t===null)return null;let n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:null},a=async(e,t)=>{let n=e.body;if(n===null)return{kind:`ok`,text:``};let r=n.getReader(),i=new TextDecoder,a=``,o=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(o+=n.byteLength,o>t)return r.cancel().catch(()=>{}),{kind:`tooLarge`,totalBytes:o};a+=i.decode(n,{stream:!0})}return{kind:`ok`,text:a+i.decode()}},o=e=>{let t=e.get(`x-forwarded-for`)?.split(`,`)[0]?.trim();return t!==void 0&&t!==``?t.replace(/^::ffff:/,``):``},s=n.get(`gctx`),c=s.session,l=new al(s,e,t),u=new URL(n.req.url);c.setHttpMeta({method:n.req.method,url:u.toString(),path:u.pathname,clientIp:o(n.req.raw.headers),sessionId:Gc(n.req.raw.headers),userAgent:n.req.header(`user-agent`)??``});let d=null;if(n.req.method===`POST`){let e=t.maxBodyBytes??il,r=i(n.req.raw.headers),o=r!==null&&r>e?r:null;if(o===null)try{let t=await a(n.req.raw,e);if(t.kind===`tooLarge`)o=t.totalBytes;else{let{body:e,parseError:r}=c.setInbound(sr(n.req.raw.headers),t.text);d=r,s.inboundBody=e,n.req.bodyCache.text=t.text}}catch(e){s.inboundBody={},d=`invalid request body: ${e.message}`}if(o!==null){let t=`request body too large: ${String(o)} bytes exceeds limit ${String(e)}`;return n.header(`x-request-id`,s.requestId),await l.finish({status:413,streaming:!1,error:{stage:`route`,message:t,status:413},usage:null}),n.json({error:{message:t,type:`RequestTooLarge`,code:`413`}},413)}}else c.setInboundHeaders(sr(n.req.raw.headers));s.parseError=d;try{await r()}catch(e){throw await l.finish({status:500,streaming:!1,error:{stage:`handler`,message:or(e),status:500},usage:null}),e}if(n.header(`x-request-id`,s.requestId),(n.res.headers.get(`content-type`)??``).includes(`text/event-stream`)&&n.res.body!==null){c.setClientResponse(n.res.status,sr(n.res.headers));let e=(c.capture?n.res.body.pipeThrough(c.tapClientStream()):n.res.body).pipeThrough(new TransformStream({flush(){l.finishStream(200)}})).getReader(),t=new ReadableStream({async pull(t){try{let{done:n,value:r}=await e.read();if(n){try{t.close()}catch{}l.finishStream(200);return}try{t.enqueue(r)}catch{}}catch(e){try{t.close()}catch{}l.finishStream(200,{stage:`upstream`,message:`upstream stream interrupted: ${or(e)}`,status:200})}},cancel(){e.cancel().catch(()=>{}),l.finishStream(499)}},{highWaterMark:0});return n.res=new Response(t,{status:n.res.status,statusText:n.res.statusText,headers:n.res.headers}),n.res}if(c.capture&&n.res.body!==null){let[e,t]=n.res.body.tee();c.captureClientBody(t),n.res=new Response(e,{status:n.res.status,statusText:n.res.statusText,headers:n.res.headers})}let f=s.traceError??(d===null?null:{stage:`handler`,message:d,status:n.res.status});return await l.finish({status:n.res.status,streaming:!1,error:f,usage:s.traceUsage}),n.res}}var sl=3.5,cl=8,ll=24;function ul(e){let t=(e,n=0)=>{if(e==null||n>32)return 0;if(typeof e==`string`)return e.length;if(typeof e==`number`||typeof e==`boolean`)return String(e).length;if(Array.isArray(e)){let r=0;for(let i of e)r+=t(i,n+1);return r}if(typeof e==`object`){let r=0;for(let[i,a]of Object.entries(e))r+=i.length+t(a,n+1);return r}return 0},n=e=>e<=0?0:Math.max(1,Math.ceil(e/sl)),r=(e,n)=>{if(Array.isArray(e)){let r=0;for(let i of e)r+=t(i)+n;return r}return e===void 0?0:t(e)},i=0;return i+=r(e.messages,cl),i+=t(e.system),i+=t(e.thinking),i+=t(e.output_config),i+=r(e.tools,ll),{input_tokens:n(i)}}var dl=class{requestId;deployments;runner;dispatchCtx;session;inboundBody=void 0;parseError=null;hookCtx=null;traceError=null;traceUsage=null;collectUsage=null;constructor(e){this.requestId=e.requestId,this.deployments=e.deployments,this.runner=e.runner,this.dispatchCtx=e.dispatchCtx,this.session=e.session}},fl={"content-type":`text/event-stream; charset=utf-8`,"cache-control":`no-cache`,connection:`keep-alive`,"x-accel-buffering":`no`};function pl(e){let t=new er,n=e.runner??new rl().addAll(e.hooks),r=e.captureContent===!0,i=e.maxBodyBytes;return t.use(`*`,async(t,i)=>{let a=e.deps?.randomId?.()??P(),o=new $c({requestId:a,capture:r}),s=r?{...e.deps,fetchFn:o.upstreamFetch(e.deps?.fetchFn??fetch)}:e.deps??{},c={};t.req.raw.headers.forEach((e,t)=>c[t]=e),c[`x-request-id`]=a,t.set(`gctx`,new dl({requestId:a,deployments:e.deployments,runner:n,session:o,dispatchCtx:{deps:s,requestId:a,inboundHeaders:hc(c),signal:t.req.raw.signal,timeouts:void 0}})),await i()}),t.use(`*`,ol(n,{traceSink:e.traceSink,maxBodyBytes:i})),t.onError((e,t)=>{let n=typeof e?.status==`number`?e.status:500,r=or(e),i=e instanceof Error?e.name:`InternalServerError`;return t.get(`gctx`).traceError={stage:`handler`,message:r,status:n},t.json({error:{message:r,type:i,code:String(n)}},n)}),t.post(`/v1/chat/completions`,e=>yl(e,`openai`)),t.post(`/v1/messages`,e=>yl(e,`anthropic`)),t.post(`/v1/responses`,e=>_l(e)),t.post(`/v1/messages/count_tokens`,e=>vl(e)),t.post(`/responses`,e=>_l(e)),t.post(`/chat/completions`,e=>yl(e,`openai`)),t.post(`/messages`,e=>yl(e,`anthropic`)),t.post(`/messages/count_tokens`,e=>vl(e)),t.get(`/v1/models`,e=>hl(e)),t.get(`/models`,e=>hl(e)),t}async function ml(e,t,n){let{response:r,reason:i}=await(async(e,t,n)=>{if(!e.has(`onAuthorize`))return{response:null,reason:null};let r=null,i={requestId:t.requestId,inboundProtocol:t.inboundProtocol,headers:n===void 0?{}:{authorization:n},principal:void 0,reject:e=>{r=e}};try{await e.run(`onAuthorize`,i)}catch(e){r=or(e)}return t.principal=i.principal,r===null?{response:null,reason:null}:{response:Response.json({error:{message:`Unauthorized: ${r}`,type:`authentication_error`,code:`401`}},{status:401}),reason:r}})(t,n,e.req.header(`authorization`));return r===null?null:(e.get(`gctx`).traceError={stage:`auth`,message:`Unauthorized: ${i??`rejected`}`,status:401},r)}async function hl(e){let t=e.get(`gctx`),n=t.runner,r=Math.floor(Date.now()/1e3),i=t.deployments.names.map(e=>({id:e,object:`model`,created:r,owned_by:`litellm-ts`}));if(n.has(`onModelList`)||n.has(`onAuthorize`)){let r=Object.assign(nl({requestId:t.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{models:i});t.hookCtx=r;let a=await ml(e,n,r);if(a!==null)return a;await n.run(`onModelList`,r)}return e.json({object:`list`,data:i})}async function gl(e,t){let n=(e,t)=>{let n=nr(t);return e.get(`gctx`).traceError={stage:`route`,message:n.error.message,status:404},e.json(n,404)},r=e=>{let t=(e,t)=>(e.get(`gctx`).traceError={stage:`route`,message:t,status:400},e.json({error:{message:t,type:`invalid_request_error`,code:`400`}},400)),n=e.get(`gctx`).parseError;return n===null?null:t(e,n)},i=async(e,t,n,r,i)=>{if(!t.has(`onModelNotFound`))return null;let a=Object.assign(n??nl({requestId:e.get(`gctx`).requestId,inboundProtocol:i===`anthropic`?`anthropic`:`openai`,requestModel:r,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{requestedModel:r}),o=await t.run(`onModelNotFound`,a);if(typeof o!=`string`||o===``)return null;let s=ir(e.get(`gctx`).deployments,o);return s===null||!jc(i,s)?null:o},a=e.get(`gctx`),o=a.runner,s={...a.inboundBody},c=typeof s.model==`string`?s.model:void 0,l=null;if(t.hookCtxWhen===`always`||o.has(`onAuthorize`)){l=nl({requestId:a.requestId,inboundProtocol:t.hookProtocol,requestModel:c??``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),a.hookCtx=l;let n=await ml(e,o,l);if(n!==null)return n}let u=r(e);if(u!==null)return u;let d=ir(a.deployments,c);if(d===null){let n=await i(e,o,l,c??``,t.routableAs);n!==null&&(c=n,s.model=n,d=ir(a.deployments,n))}return d===null?n(e,c??``):(l!==null&&l.model===null&&(l.model=xl(c??``,d)),{body:s,model:c,deployment:d,hookCtx:l})}async function _l(e){let t=e.get(`gctx`),n=await gl(e,{hookProtocol:`openai`,routableAs:`openai-responses`,hookCtxWhen:`always`});if(n instanceof Response)return n;let{body:r,deployment:i}=n;return bl(e,await Nc(i,Sl(r),t.dispatchCtx))}async function vl(e){let t=await gl(e,{hookProtocol:`anthropic`,routableAs:`anthropic`,hookCtxWhen:`ifAuthorize`});if(t instanceof Response)return t;let{body:n}=t;return e.json(ul(n))}async function yl(e,t){let n=(e,t)=>t===`anthropic`?{...e,inbound_format:`anthropic`}:Sl(e),r=e.get(`gctx`),i=r.runner,a=await gl(e,{hookProtocol:t,routableAs:t,hookCtxWhen:`always`});if(a instanceof Response)return a;let{body:o,deployment:s}=a,c=a.hookCtx,l=a.model,u=s;if(i.has(`onModel`)){let e=xl(l??``,u),n={...e},a=Object.assign(c,{model:e}),o=await i.run(`onModel`,a),s=a.model??e,d=typeof o==`string`&&o!==``?o:s.name;if(d!==(l??``)){let e=ir(r.deployments,d);e!==null&&jc(t,e)?(l=d,u=e):gt(`[gateway] onModel redirected "${n.name}" -> "${d}" but the target is missing from the deployment table or unroutable for ${t} inbound; keeping the original deployment`)}let f=s.provider===n.provider?u.provider:s.provider,p=s.upstreamModel===n.upstreamModel?u.modelName:s.upstreamModel,m=s.apiBase===n.apiBase?u.apiBase:s.apiBase;u={...u,provider:f,modelName:p,apiBase:m},c.model={name:l??u.name,provider:f,upstreamModel:p,apiBase:m}}if(i.has(`onModelRequest`)||i.has(`onModelResponse`)){let a=c.model,s=Object.assign(c,{model:a,request:{body:o,headers:{...e.req.header(`authorization`)?{authorization:e.req.header(`authorization`)}:{}}}});await i.run(`onModelRequest`,s);let l=r.dispatchCtx,d={...l,inboundHeaders:{...l.inboundHeaders,...s.request.headers}};return bl(e,await Mc(u,n(s.request.body,t),d),{runner:i,hookCtx:c})}let d=n(o,t);return bl(e,await Mc(u,d,r.dispatchCtx))}async function bl(e,t,n){let r=async e=>{let t=e.status,n=``;try{n=await e.clone().text()}catch{return{message:`upstream responded ${String(t)}`,status:t}}let r;try{r=JSON.parse(n)}catch{r=null}let i=r;return{message:typeof i==`object`&&i?typeof i.error?.message==`string`?i.error.message:typeof i.message==`string`?i.message:n.slice(0,500):n.slice(0,500),status:t}},i=e=>new Response(e.stream??e.body,{status:200,headers:{...fl}}),a=e.get(`gctx`);if(t.kind===`error`)return a.traceError={stage:`upstream`,...await r(t.response)},t.response;if(t.sse){if(a.collectUsage=t.collectUsage??null,n!==void 0){let e=Object.assign(n.hookCtx,{model:n.hookCtx.model,response:{status:200,headers:{},streaming:!0,body:null}});await n.runner.run(`onModelResponse`,e)}return i(t)}a.traceUsage=t.usage??null;let o=t.body;if(n!==void 0){let e=Object.assign(n.hookCtx,{model:n.hookCtx.model,response:{status:200,headers:{},streaming:!1,body:o}});await n.runner.run(`onModelResponse`,e),o=e.response.body}return e.json(o)}function xl(e,t){return{name:e,provider:t.provider,upstreamModel:t.modelName,apiBase:t.apiBase}}function Sl(e){let{inbound_format:t,...n}=e;return n}var Cl=class{hookRunner;_expanded;options;constructor(e){this.options=e,this._expanded=ur(e.config),wl(this._expanded.warnings),this.hookRunner=new rl().addAll(e.hooks)}get expanded(){return this._expanded}reload(e){return this._expanded=ur(e),wl(this._expanded.warnings),this.options={...this.options,config:e},this}addHook(e,t){return this.hookRunner.addHook(e,t),this}async plugin(e,t){await e(this,t)}build(){let e=new er;return e.get(`/healthz`,e=>e.json({status:`ok`})),e.route(`/`,pl({deployments:this.expanded.deployments,runner:this.hookRunner,deps:this.options.deps,captureContent:!0,traceSink:this.options.traceSink})),e}static get ConfigError(){return lr}};function wl(e){for(let t of e)gt(`[ezllm] ${t}`)}var Tl=`重启服务(CLI 会重新生成默认配置)`,El=class extends Error{constructor(e,t=xt(),n=Tl){super(`配置文件解析失败:${t}(${e})。文件可能被截断或损坏,请修复文件内容,或备份后删除该文件并${n}`),this.name=`ConfigParseError`}};function Dl(){let e=xt();if(!f(e))return null;let t;try{t=JSON.parse(h(e,`utf-8`))}catch(t){throw new El(t.message,e)}if(typeof t!=`object`||!t||Array.isArray(t))throw new El(`顶层必须是 JSON 对象`,e);return t}function Ol(){try{return Dl()}catch(e){throw e instanceof El&&(R(`[ezllm] ${e.message}`),process.exit(1)),e}}function kl(e){zt(xt(),e)}function Al(e){let{masterKey:t,"web-ui":n,logs:r,setup:i,autoUpdate:a,allowLan:o,latencyTest:s,...c}=e;return c}function jl(e){return ur(Al(e))}var Ml=`0.0.0.0`,Nl=`127.0.0.1`,Pl=`监听相关配置已变更,需重启服务后生效;当前仍按启动时的地址与端口运行`;function Fl(e){let t=e?.masterKey;return typeof t==`string`?t.trim():``}function Il(){return Fl(Dl())}function Ll(){try{return{config:Dl(),broken:!1}}catch(e){if(!(e instanceof El))throw e;return{config:null,broken:!0}}}function Rl(e){let t=e?.[`web-ui`]?.[`login-account`],n=typeof t?.username==`string`?t.username.trim():``,r=typeof t?.password==`string`?t.password:``;if(n!==``&&r!==``)return{username:n,password:r}}function zl(){let{config:e,broken:t}=Ll(),n=Rl(e);return n===void 0?t?{required:!0,configBroken:!0,username:``,password:``}:{required:!1,configBroken:!1,username:``,password:``}:{required:!0,configBroken:!1,username:n.username,password:n.password}}function Bl(){let{config:e,broken:t}=Ll();if(t)return{completed:!1,deployment:void 0};let n=e?.setup;return n===void 0?{completed:!0,deployment:void 0}:{completed:n.completed===!0,deployment:n.deployment===`server`?`server`:`local`}}function Vl(e){return(e=>Fl(e)!==``||Rl(e)!==void 0)(e)?{hostname:(e=>e?.allowLan!==!1)(e)?Ml:Nl,source:`config`}:{hostname:Nl,source:`credentials`}}function Hl(){try{return Vl(Dl())}catch{return Vl(null)}}function Ul(e,t){return Vl(e).hostname!==Vl(t).hostname||e?.port!==t.port}function Wl(){return Dl()?.logs}function Gl(e){return typeof e==`number`&&Number.isFinite(e)}function Kl(){let e=Wl(),t=(e,t)=>Gl(e)&&e>=0?Math.floor(e):t;return{detailDays:t(e?.[`detail-retention-days`],0),rowDays:t(e?.[`row-retention-days`],0)}}function ql(){let e=Wl(),t=(e,t)=>Gl(e)&&e>0?e:t,n=t(e?.[`payload-quality`],9),r=Math.min(11,Math.max(5,Math.round(n)));return{syncIntervalMs:Math.floor(t(e?.[`spool-sync-interval-ms`],5e3)),maxBytes:Math.floor(t(e?.[`spool-max-mb`],256))*1024*1024,payloadQuality:r===10?9:r}}var Jl=`__blob`,Yl=[`%chat/completions%`,`%/messages%`,`%/embeddings%`,`%/responses%`,`%/models%`,`%model/info%`],Xl=1e3,Zl=134217728;function Ql(e){return new Date(Date.parse(e)+288e5).toISOString().slice(0,10)}function $l(e){return e instanceof Error?e.message:String(e)}var eu=`CASE WHEN json_valid(headers) THEN json_extract(headers, '$.user-agent') END`;function tu(e){if(typeof e!=`string`||e===``)return``;let t;try{t=JSON.parse(e)}catch{return``}if(typeof t!=`object`||!t||Array.isArray(t))return``;for(let[e,n]of Object.entries(t))if(e.toLowerCase()===`user-agent`&&typeof n==`string`)return n;return``}function nu(){return E(bt(),`spool`)}var ru=/^(\d+)\.jsonl$/,iu=`.tmp`,au=268435456;function ou(){return new Promise(e=>setImmediate(e))}function su(e){return E(nu(),`${String(e)}.jsonl`)}function cu(e){return su(e)+iu}function lu(){It(),p(nu(),{recursive:!0})}function uu(){try{return g(nu()).map(e=>ru.exec(e)).filter(e=>e!==null).map(e=>Number(e[1])).sort((e,t)=>e-t)}catch{return[]}}function du(e){let t;try{t=h(su(e),`utf-8`)}catch{return{kind:`missing`}}try{return{kind:`ok`,entry:JSON.parse(t)}}catch{return{kind:`corrupt`}}}function fu(){let e=0;try{for(let t of g(nu()))if(t.endsWith(iu))try{x(E(nu(),t)),e++}catch{}}catch{return 0}return e}var pu=class{#e;#t=0;#n=-1;#r=[];#i=Promise.resolve();#a=0;constructor(e={}){let t=e.maxBytes;this.#e=typeof t==`number`&&Number.isFinite(t)&&t>0?t:au}totalBytes(){if(this.#n>=0)return this.#n;let e=0;try{for(let t of g(nu()))if(ru.test(t))try{e+=b(E(nu(),t)).size}catch{}}catch{e=0}return this.#n=e,e}resetTotalBytes(){this.#n=-1}get droppedCount(){return this.#t}resetDroppedCount(){this.#t=0}listIds(){return uu()}readRecord(e){return du(e)}deleteFile(e){try{let t=b(su(e)).size;x(su(e)),this.#o(-t)}catch{}}#o(e){this.#n>=0&&(this.#n+=e)}#s(e){lu();let t=cu(e.id);S(t,e.line,`utf-8`),_(t,su(e.id)),this.#o(Buffer.byteLength(e.line))}async#c(e){await ee(nu(),{recursive:!0});let t=cu(e.id);await re(t,e.line,`utf-8`),await ne(t,su(e.id)),this.#o(Buffer.byteLength(e.line))}async#l(e){try{await this.#c(e)}catch(e){R(`[spool] 写入失败:`,$l(e))}}#u(){this.#r.length===0||this.#a>0||(this.#a++,this.#i=this.#i.then(()=>ou()).then(async()=>{for(this.#a--;this.#r.length>0;)await this.#l(this.#r.shift())}))}write(e,t){let n=JSON.stringify(t);if(this.totalBytes()+Buffer.byteLength(n)>this.#e){this.#t++,(this.#t===1||this.#t%100==0)&>(`[spool] 已达磁盘上界(${String(Math.round(this.#e/1024/1024))}MB),累计丢弃 ${String(this.#t)} 条——日志入库可能长期失败`);return}this.#r.push({id:e,line:n}),this.#u()}async flush(){for(;this.#r.length>0||this.#a>0;)this.#u(),await Promise.race([this.#i,ou()]);await this.#i}flushSync(){for(;this.#r.length>0;){let e=this.#r.shift();try{this.#s(e)}catch(e){R(`[spool] 崩溃前写入失败:`,$l(e))}}}};function mu(e){let t=du(e);if(t.kind!==`ok`)return null;let n=t.entry,{response:r,time:i,method:a,path:o,model:s,status:c,stream:l,error:u,ip:d,session_id:f}=n;return{detail:{...n,response:r??null},meta:{_id:e,_spool:`${String(e)}.jsonl`,time:i??null,model:s??``,method:a??null,path:o??null,status:c??null,stream:!!l,error:u??null,ip:d??null,session_id:f??null,headers:n.headers??null,client:n.client??null,input_tokens:n.input_tokens??0,output_tokens:n.output_tokens??0,cache_read_tokens:n.cache_read_tokens??0,cache_creation_tokens:n.cache_creation_tokens??0,duration:n.duration??0}}}function hu(e){return typeof e==`boolean`?+!!e:e===void 0?null:e}function gu(e){return e.map(hu)}function _u(e){return{text:e,values:[]}}function vu(e,...t){let n=e=>{if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.text==`string`&&Array.isArray(t.values)},r=``,i=[];for(let a=0;a<e.length;a+=1)if(r+=e[a],a<t.length){let e=t[a];n(e)?(r+=e.text,i.push(...e.values)):(r+=`?`,i.push(e))}return{text:r,values:i}}var yu=Object.assign(vu,{raw:_u}),bu=Symbol(`ezllm-db:table`);function xu(e){return e[bu]}function Su(e){return`"${e.replaceAll(`"`,`""`)}"`}function Cu(e){return e.map(e=>Su(e)).join(`, `)}function wu(e){let t={kind:e,notNull:!1,primaryKey:!1,autoIncrement:!1,unique:!1,hasDefault:!1,defaultValue:null,name:``,table:``},n={meta:t,notNull(){return t.notNull=!0,n},primaryKey(r){if(r?.autoIncrement){if(e!==`integer`)throw Error(`SQLite 的 AUTOINCREMENT 只支持 INTEGER 主键,当前列类型为 ${e.toUpperCase()}`);t.autoIncrement=!0}return t.primaryKey=!0,n},default(e){return t.hasDefault=!0,t.defaultValue=e,n},unique(){return t.unique=!0,n}};return n}function Tu(){return wu(`text`)}function Eu(){return wu(`integer`)}function Du(){return wu(`blob`)}function Ou(e){return{on(...t){return{name:e,columns:t}}}}function ku(e,t,n=[],r={}){for(let[n,r]of Object.entries(t)){let t=r.meta.table===``&&r.meta.name===``?null:`${r.meta.table}.${r.meta.name}`;if(t!==null&&t!==`${e}.${n}`)throw Error(`表 ${e} 的列 ${n} 复用了已登记给 ${t} 的列 builder;一个列 builder 只能用于一张表的一列,请为每列单独调用 text()/integer() 等创建`);r.meta.name=n,r.meta.table=e}for(let r of n)for(let n of r.columns)if(!(n in t))throw Error(`索引 ${r.name} 引用了表 ${e} 中不存在的列:${n}`);let i=r.primaryKey;if(i!==void 0){if(i.length<2)throw Error(`表 ${e} 的表级主键至少需要两列(单列请用列级 .primaryKey())`);if(Object.values(t).some(e=>e.meta.primaryKey))throw Error(`表 ${e} 同时声明了列级主键与表级复合主键,二者只能取其一`);for(let n of i)if(!(n in t))throw Error(`表 ${e} 的复合主键引用了不存在的列:${n}`)}return{...t,[bu]:{name:e,columns:t,indexes:n,tablePrimaryKey:i}}}function Au(e){return e.map(e=>{let t=(e,t)=>{let n=e=>e===null?`NULL`:typeof e==`boolean`?e?`1`:`0`:typeof e==`number`?String(e):`'${e.replaceAll(`'`,`''`)}'`,r=[Su(e),t.kind.toUpperCase()];return t.primaryKey&&t.autoIncrement?r.push(`PRIMARY KEY AUTOINCREMENT`):t.primaryKey&&r.push(`PRIMARY KEY`),t.notNull&&r.push(`NOT NULL`),t.hasDefault&&r.push(`DEFAULT`,n(t.defaultValue)),r.join(` `)},n=(e,t)=>{let n=Cu(t.columns);return`CREATE INDEX IF NOT EXISTS ${Su(t.name)} ON ${Su(e)} (${n})`},r=xu(e),i=[],a=[];for(let[e,n]of Object.entries(r.columns))i.push(` ${t(e,n.meta)}`),n.meta.unique&&a.push(` UNIQUE (${Su(e)})`);let o=[...i,...a].join(`,
|
|
22
|
+
`),s=o;r.tablePrimaryKey!==void 0&&(s=`${o},\n PRIMARY KEY (${Cu(r.tablePrimaryKey)})`);let c=[`CREATE TABLE IF NOT EXISTS ${Su(r.name)} (\n${s}\n)`];for(let e of r.indexes)c.push(n(r.name,e));return c.map(e=>`${e};`).join(`
|
|
23
|
+
`)}).join(`
|
|
24
|
+
`)}function ju(e){return`${Su(e.meta.table)}.${Su(e.meta.name)}`}function Mu(e,t){return{kind:`condition`,text:e,values:t}}function Nu(e,t){return Mu(`${ju(e)} = ?`,[t])}function Pu(e,t){return Mu(`${ju(e)} <> ?`,[t])}function Fu(e,t){return Mu(`${ju(e)} > ?`,[t])}function Iu(e,t){return Mu(`${ju(e)} >= ?`,[t])}function Lu(e,t){return Mu(`${ju(e)} < ?`,[t])}function Ru(e,t){return Mu(`${ju(e)} <= ?`,[t])}function zu(e,t){return Mu(`${ju(e)} LIKE ?`,[t])}function Bu(e,t){if(t.length===0)return Mu(`0 = 1`,[]);let n=t.map(()=>`?`).join(`, `);return Mu(`${ju(e)} IN (${n})`,t)}function Vu(e){return Mu(`${ju(e)} IS NULL`,[])}function Hu(e){return Mu(`${ju(e)} IS NOT NULL`,[])}function Uu(e,t,n){return e.length===0?Mu(n,[]):Mu(e.map(e=>`(${e.text})`).join(` ${t} `),e.flatMap(e=>e.values))}function Wu(...e){return Uu(e,`AND`,`1 = 1`)}function Gu(...e){return Uu(e,`OR`,`1 = 0`)}function Ku(e){return Mu(`NOT (${e.text})`,e.values)}function qu(e,t){return{kind:`sort`,text:`${ju(e)} ${t}`,values:[]}}function Ju(e){return qu(e,`ASC`)}function Yu(e){return qu(e,`DESC`)}function Xu(e){return{kind:`aggregation`,text:e,values:[]}}function Zu(e,t){return Xu(`${e}(${ju(t)})`)}function Qu(e){return Zu(`SUM`,e)}function $u(e){return Zu(`MIN`,e)}function ed(e){return Zu(`MAX`,e)}function td(e){return e?Zu(`COUNT`,e):Xu(`COUNT(*)`)}var G={eq:Nu,ne:Pu,gt:Fu,gte:Iu,lt:Lu,lte:Ru,like:zu,in:Bu,isNull:Vu,isNotNull:Hu,and:Wu,or:Gu,not:Ku,asc:Ju,desc:Yu,sum:Qu,count:td,min:$u,max:ed},nd=class{executor;table;constructor(e,t){this.executor=e,this.table=t}get tableName(){return xu(this.table).name}get tableColumns(){return xu(this.table).columns}get quotedTable(){return Su(this.tableName)}},rd=class extends nd{conds=[];where(e){return this.conds.push(e),this}appendWhere(e,t){if(this.conds.length===0)return e;let n=Wu(...this.conds);return t.push(...n.values),`${e} WHERE ${n.text}`}},id=class extends rd{allowAllRows=!1;allRows(){return this.allowAllRows=!0,this}assertWhereOrAllRows(e,t){if(this.conds.length===0&&!this.allowAllRows)throw Error(`${e} ${this.tableName}:无 where 条件会${t}全表;确需全表${t}请显式调用 .allRows()`)}};function ad(e,t){return typeof e==`bigint`||typeof t==`bigint`?BigInt(e)+BigInt(t):e+t}var od=class extends nd{rows=[];conflictMode=``;orIgnore(){return this.conflictMode=` OR IGNORE`,this}orReplace(){return this.conflictMode=` OR REPLACE`,this}values(e){let t=Array.isArray(e)?e:[e];return this.rows=[...this.rows,...t],this}run(){if(this.rows.length===0)throw Error(`insert ${this.tableName}:未提供数据,请先调用 .values(...)`);let e=Object.keys(this.tableColumns),t=new Map;for(let n of this.rows){let r=e.filter(e=>n[e]!==void 0);if(r.length===0)throw Error(`insert ${this.tableName}:.values(...) 的行不含任何 schema 列`);let i=JSON.stringify(r),a=t.get(i);a===void 0?t.set(i,{columns:r,rows:[n]}):a.rows.push(n)}let n=0,r=0;for(let e of t.values()){let t=[],i=e.rows.map(n=>`(${e.columns.map(e=>(t.push(hu(n[e])),`?`)).join(`, `)})`),a=`INSERT${this.conflictMode} INTO ${this.quotedTable} (${Cu(e.columns)}) VALUES ${i.join(`, `)}`,o=this.executor.run({text:a,values:t});n=ad(n,o.changes),r=o.lastInsertRowid}return{changes:n,lastInsertRowid:r}}},sd=class extends rd{orders=[];groupCols=[];projection={kind:`all`};limitValue;offsetValue;orderBy(...e){return this.orders.push(...e),this}limit(e){return this.limitValue=e,this}offset(e){return this.offsetValue=e,this}groupBy(...e){return this.groupCols.push(...e),this}columns(e){if(Array.isArray(e)){let t=e;if(t.length===0)throw Error(`select ${this.tableName}:columns([]) 至少要指定一列`);for(let e of t)if(!(e in this.tableColumns))throw Error(`select ${this.tableName}:columns 引用了不存在的列 ${String(e)}`);this.projection={kind:`subset`,columns:t}}else{let t=Object.entries(e);if(t.length===0)throw Error(`select ${this.tableName}:columns({}) 至少要有一个聚合表达式`);this.projection={kind:`aggregate`,entries:t}}return this}build(){let e;switch(this.projection.kind){case`subset`:e=Cu(this.projection.columns);break;case`aggregate`:e=this.projection.entries.map(([e,t])=>`${t.text} AS ${Su(e)}`).join(`, `);break;default:e=Cu(Object.keys(this.tableColumns))}let t=[];if(e.length===0)throw Error(`select ${this.tableName}:该表没有声明任何列,无法生成 SELECT 列清单`);let n=this.appendWhere(`SELECT ${e} FROM ${this.quotedTable}`,t);if(this.groupCols.length>0&&(n+=` GROUP BY ${this.groupCols.map(e=>ju(e)).join(`, `)}`),this.orders.length>0){n+=` ORDER BY ${this.orders.map(e=>e.text).join(`, `)}`;for(let e of this.orders)t.push(...e.values)}return this.limitValue!==void 0&&(n+=` LIMIT ?`,t.push(this.limitValue)),this.offsetValue!==void 0&&(this.limitValue===void 0&&(n+=` LIMIT -1`),n+=` OFFSET ?`,t.push(this.offsetValue)),{text:n,values:t}}all(){return this.executor.all(this.build())}get(){return this.executor.get(this.build())}values(){return this.executor.values(this.build())}},cd=class extends id{patchEntries=[];set(e){return this.patchEntries=Object.entries(e),this}run(){if(this.patchEntries.length===0)throw Error(`update ${this.tableName}:缺少 set(...),没有要写入的列`);this.assertWhereOrAllRows(`update`,`更新`);let e=[],t=this.tableColumns,n=this.patchEntries.map(([n,r])=>{if(!Object.hasOwn(t,n))throw Error(`update ${this.tableName}:set({ ${n}: ... }) 的 \`${n}\` 不是该表的列`);return e.push(hu(r)),`${Su(n)} = ?`}).join(`, `),r=this.appendWhere(`UPDATE ${this.quotedTable} SET ${n}`,e);return this.executor.run({text:r,values:e})}},ld=class extends id{run(){this.assertWhereOrAllRows(`delete`,`删除`);let e=[],t=this.appendWhere(`DELETE FROM ${this.quotedTable}`,e);return this.executor.run({text:t,values:e})}},ud=new Map,dd=class{name;native;statements=new Map;closed=!1;constructor(e,t){this.name=e,this.native=t}stmt(e){let t=this.statements.get(e);if(t!==void 0)return t;let n=this.native.prepare(e);return this.statements.set(e,n),n}runPrepared(e,t){return{...e.run(...gu(t))}}getPrepared(e,t){return e.get(...gu(t))}allPrepared(e,t){return e.all(...gu(t))}all(e){return this.allPrepared(this.stmt(e.text),e.values)}get(e){return this.getPrepared(this.stmt(e.text),e.values)}values(e){let t=this.stmt(e.text);t.setReturnArrays(!0);try{return this.allPrepared(t,e.values)}finally{t.setReturnArrays(!1)}}run(e){return this.runPrepared(this.stmt(e.text),e.values)}exec(e){this.native.exec(e)}createTables(e){e.length!==0&&this.native.exec(Au(e))}insert(e){return new od(this,e)}select(e){return new sd(this,e)}update(e){return new cd(this,e)}delete(e){return new ld(this,e)}transaction(e){if(this.inTransaction)throw Error(`transaction ${this.name}:不支持嵌套事务`);this.native.exec(`BEGIN`),this.inTransaction=!0;try{let t=e(this.txView);return this.native.exec(`COMMIT`),t}catch(e){try{this.native.exec(`ROLLBACK`)}catch{}throw e}finally{this.inTransaction=!1}}inTransaction=!1;txViewValue=null;get txView(){if(this.txViewValue===null){let e=this;this.txViewValue={insert:t=>e.insert(t),select:t=>e.select(t),update:t=>e.update(t),delete:t=>e.delete(t),all:t=>e.all(t),get:t=>e.get(t),values:t=>e.values(t),run:t=>e.run(t),exec:t=>e.exec(t)}}return this.txViewValue}prepare(e){let t=this.stmt(e);return{run:(...e)=>this.runPrepared(t,e),get:(...e)=>this.getPrepared(t,e),all:(...e)=>this.allPrepared(t,e)}}close(){this.closed||(this.closed=!0,this.statements.clear(),this.native.close(),ud.get(this.name)===this&&ud.delete(this.name))}};function fd(e){let t=ud.get(e);if(t!==void 0)return t;It();let n=new ie(E(bt(),`${e}.db`));try{n.exec(`PRAGMA busy_timeout = 5000`),n.exec(`PRAGMA journal_mode = WAL`),n.exec(`PRAGMA journal_size_limit = 67108864`)}catch(e){throw n.close(),e}let r=new dd(e,n);return ud.set(e,r),r}var K=ku(`logs`,{id:Eu().primaryKey({autoIncrement:!0}),time:Tu().notNull(),date:Tu().notNull(),method:Tu(),path:Tu(),model:Tu(),status:Eu(),stream:Eu(),error:Tu(),preview:Tu(),input_tokens:Eu().default(0),output_tokens:Eu().default(0),cache_read_tokens:Eu().default(0),cache_creation_tokens:Eu().default(0),ip:Tu(),session_id:Tu(),duration:Eu().default(0),headers:Tu(),client:Tu()},[Ou(`idx_logs_date`).on(`date`),Ou(`idx_logs_time`).on(`time`),Ou(`idx_logs_model`).on(`model`),Ou(`idx_logs_session`).on(`session_id`),Ou(`idx_logs_client`).on(`client`)]),pd=ku(`log_details`,{log_id:Eu().primaryKey(),detail:Du().notNull()}),md=ku(`log_blobs`,{hash:Tu().primaryKey(),content:Du().notNull()}),hd=ku(`log_id_alloc`,{next_id:Eu().notNull()}),gd=ku(`client_names`,{ua:Tu().primaryKey(),client:Tu(),source:Tu(),attempts:Eu().notNull().default(0),created_at:Tu().notNull(),updated_at:Tu().notNull()}),_d=[K,hd,gd],vd=[pd,md],yd=[[`headers`,`TEXT`],[`client`,`TEXT`]],bd=[`CREATE INDEX IF NOT EXISTS idx_logs_ua ON logs (${eu})`];function xd(e){let t=e.native.prepare(`PRAGMA table_info(logs)`).all();if(t.length===0)return;let n=new Set(t.map(e=>String(e.name)));for(let[t,r]of yd)n.has(t)||e.exec(`ALTER TABLE logs ADD COLUMN ${t} ${r}`)}function Sd(e){for(let t of bd)e.exec(t)}var Cd=null;function wd(){return Td().native}function Td(){if(Cd!==null)return Cd;let e=fd(`logs`);return xd(e),e.createTables(_d),Sd(e),Cd=e,e}function q(){return Td()}function Ed(e){return q().transaction(e)}var Dd=1e3,Od=!1,kd=0,Ad=0;function jd(){let e=e=>{let t=e.get(yu`SELECT seq FROM sqlite_sequence WHERE name = 'logs'`);return t===void 0?0:Number(t.seq)},t=(t,n)=>{if(e(t)>=n)return;let r=t.run(yu`UPDATE sqlite_sequence SET seq = ${n} WHERE name = 'logs'`);Number(r.changes)===0&&t.run(yu`INSERT INTO sqlite_sequence (name, seq) VALUES ('logs', ${n})`)},n=t=>{if(t.select(hd).columns([`next_id`]).limit(1).get()!==void 0)return;let n=t.select(K).columns({m:G.max(K.id)}).get(),r=Math.max(Number(n?.m??0),e(t))+1;t.insert(hd).values({next_id:r}).run()};if(kd>=Ad){let e=q();Ed(()=>{Od||=(n(e),!0);let r=e.select(hd).columns([`next_id`]).limit(1).get();kd=Number(r.next_id),Ad=kd+Dd,e.update(hd).set({next_id:Ad}).allRows().run(),t(e,Ad-1)})}return kd++}function Md(e){return ae(e,{params:{[se.BROTLI_PARAM_QUALITY]:9}})}function Nd(e){if(!e)return`-`;if(typeof e==`string`){let t=e.split(`
|
|
25
|
+
`).filter(e=>e.startsWith(`data: `)&&e.slice(6).trimEnd()!==`[DONE]`);if(t.length>0)try{let e=JSON.parse(t[0].slice(6)).choices?.[0]?.delta;return e?.content||e?.reasoning_content||`(SSE)`}catch{return`(SSE `+e.length+` chars)`}return`(SSE `+e.length+` chars)`}let t=e;if(t.error)return`错误: `+(t.error.message||JSON.stringify(t.error));let n=t.choices?.[0];return n?n.message?.content?.slice(0,100)||n.delta?.content||`(流式)`:JSON.stringify(e).slice(0,100)}function Pd(e,t,n=9){let r=(e,t=9)=>{let n=ae(Buffer.from(e,`utf-8`),{params:{[se.BROTLI_PARAM_QUALITY]:t}});return Buffer.concat([Buffer.from([2]),n])},i=e=>M(`sha256`).update(e,`utf-8`).digest(`hex`),a=(e,t)=>{if(typeof e==`string`){if(e.length<8192)return e;let n=i(e);return t.has(n)||t.set(n,e),{[Jl]:n}}if(Array.isArray(e))return e.map(e=>a(e,t));if(typeof e==`object`&&e){let n={};for(let[r,i]of Object.entries(e))n[r]=a(i,t);return n}return e},o=e.time||new Date().toISOString(),s=new Map,c=a(e,s);return{id:t,time:o,date:Ql(o),preview:Nd(e.response),detail:r(JSON.stringify(c),n),blobs:s,entry:e}}function Fd(e){return{method:e.method||null,path:e.path||null,model:e.model||null,status:e.status??null,stream:+!!e.stream,error:e.error||null,input_tokens:e.input_tokens||0,output_tokens:e.output_tokens||0,cache_read_tokens:e.cache_read_tokens||0,cache_creation_tokens:e.cache_creation_tokens||0,ip:e.ip||null,session_id:e.session_id||null,duration:e.duration||0,headers:e.headers||null,client:e.client||null}}function Id(e,t){let n=t.time||new Date().toISOString(),r=Ql(n),i=q();return Ed(()=>{i.insert(K).values({id:e,time:n,date:r,preview:Nd(t.response),...Fd(t)}).run()}),e}var Ld=4,Rd=/^logs-(\d{4})(\d{2})(\d{2})\.db$/,zd=/^\d{6}$/;function Bd(){return E(bt(),`details`)}function Vd(e){return E(Bd(),e.slice(0,7).replace(/-/g,``))}function Hd(e){let t=e.replace(/-/g,``);return`details/${t.slice(0,6)}/logs-${t}`}function Ud(e){return E(Vd(e),`logs-${e.replace(/-/g,``)}.db`)}var Wd=new class{#e=new Map;#t(e,t){let n=this.#e.get(e);if(n!==void 0)return this.#e.delete(e),this.#e.set(e,n),n;if(t.create)p(Vd(e),{recursive:!0});else if(!f(Ud(e)))return null;let r=fd(Hd(e));return r.createTables(vd),this.#n(e,r)}#n(e,t){for(this.#e.set(e,t);this.#e.size>Ld;){let e=this.#e.keys().next().value;this.#r(e)}return t}#r(e){let t=this.#e.get(e);if(t!==void 0){this.#e.delete(e);try{t.close()}catch{}}}open(e){return this.#t(e,{create:!0})}openIfExists(e){return this.#t(e,{create:!1})}closeAll(){for(let e of[...this.#e.keys()])this.#r(e)}listDetailDates(){let e;try{e=g(Bd())}catch{return[]}let t=[];for(let n of e){if(!zd.test(n))continue;let e;try{e=g(E(Bd(),n))}catch{continue}for(let n of e){let e=Rd.exec(n);e!==null&&t.push(`${e[1]}-${e[2]}-${e[3]}`)}}return t.sort()}deleteDetailDb(e){this.#r(e);let t=Ud(e),n=!1;f(t)&&(v(t,{force:!0}),n=!0);for(let e of[`-wal`,`-shm`])v(t+e,{force:!0});try{y(Vd(e))}catch{}return n}};function Gd(e){if(e.length===0)return 0;let t=new Map;for(let n of e){let e=t.get(n.date);e===void 0?t.set(n.date,[n]):e.push(n)}let n=q();for(let[e,r]of t){Ed(()=>{for(let e of r)n.insert(K).values({id:e.id,time:e.time,date:e.date,preview:e.preview,...Fd(e.entry)}).orIgnore().run()});let t=Wd.open(e);t.transaction(()=>{for(let e of r){t.insert(pd).values({log_id:e.id,detail:e.detail}).orReplace().run();for(let[n,r]of e.blobs)t.insert(md).values({hash:n,content:Md(Buffer.from(r,`utf-8`))}).orIgnore().run()}})}return e.length}function Kd(e){return oe(Buffer.from(e)).toString(`utf-8`)}function qd(e){if(e.length>0&&e[0]===2)return oe(Buffer.from(e.subarray(1)));throw Error(`详情 BLOB 格式非法:缺少 brotli 标记字节(历史 gzip 格式已不再支持)`)}function Jd(e){let t=Object.keys(e);if(t.length!==1||t[0]!==`__blob`)return null;let n=e[Jl];return typeof n==`string`?n:null}function Yd(e,t){if(Array.isArray(e))return e.map(e=>Yd(e,t));if(typeof e==`object`&&e){let n=e,r=Jd(n);if(r!==null){let n=t.get(r);return n===void 0?e:n}let i={};for(let[e,r]of Object.entries(n))i[e]=Yd(r,t);return i}return e}function Xd(e,t){if(Array.isArray(e)){for(let n of e)Xd(n,t);return}if(typeof e==`object`&&e){let n=e,r=Jd(n);if(r!==null){t.add(r);return}for(let e of Object.values(n))Xd(e,t)}}function Zd(e,t){let n=new Map,r=[...e];if(r.length===0)return n;for(let e=0;e<r.length;e+=400){let i=r.slice(e,e+400),a=t.select(md).columns([`hash`,`content`]).where(G.in(md.hash,i)).all();for(let e of a)n.set(e.hash,Kd(e.content))}return n}function Qd(e){let t=q().select(K).where(G.eq(K.id,Number(e))).get();if(t===void 0)return null;let n=Wd.openIfExists(t.date);if(n===null)return null;let r=null,i=n.select(pd).columns([`detail`]).where(G.eq(pd.log_id,t.id)).get();if(i&&i.detail!=null&&i.detail.length>0)try{let e=JSON.parse(qd(i.detail).toString(`utf-8`)),t=new Set;Xd(e,t),r=Yd(e,Zd(t,n))}catch(e){R(`[logs] 详情 ${String(t.id)} 解析失败,按无详情处理:`,$l(e))}return r===null?null:{detail:r,meta:{_id:t.id,time:t.time,model:t.model||``,method:t.method||null,path:t.path||null,status:t.status??null,stream:!!t.stream,error:t.error||null,ip:t.ip||null,session_id:t.session_id||null,headers:t.headers||null,client:t.client||null,input_tokens:t.input_tokens??0,output_tokens:t.output_tokens??0,cache_read_tokens:t.cache_read_tokens??0,cache_creation_tokens:t.cache_creation_tokens??0,duration:t.duration??0}}}function $d(e,t,n){let r=(e,t)=>e>=400||t!=null&&t!==``;if(!t)return!0;if(String(t)===`err`)return r(e,n);let i=/^([1-5])xx$/i.exec(String(t));if(i&&i[1]){let t=Number(i[1])*100;return e>=t&&e<t+100}return!/^\d+$/.test(String(t))||e===Number(t)}function ef(e,t){if(!t)return!0;let n=Yl.some(t=>RegExp(`^`+t.replace(/%/g,`.*`)+`$`).test(e||``));return t===`model`?n:!n}function tf(e){let t=[];if(e.startDate&&t.push(G.gte(K.date,e.startDate)),e.endDate&&t.push(G.lte(K.date,e.endDate)),e.model&&t.push(G.like(K.model,`%${e.model}%`)),e.sessionId){let n=e.sessionId.trim();n&&t.push(G.and(G.gte(K.session_id,n),G.lt(K.session_id,`${n}\uffff`)))}return e.noSession&&t.push(G.or(G.isNull(K.session_id),G.eq(K.session_id,``))),e.client&&t.push(G.eq(K.client,e.client)),t.length===0?null:G.and(...t)}function nf(e){let t=[],n=tf(e);if(n!==null&&t.push(n),e.pathGroup){let n=G.or(...Yl.map(e=>G.like(K.path,e)));e.pathGroup===`model`?t.push(n):e.pathGroup===`other`&&t.push(G.or(G.isNull(K.path),G.not(n)))}if(e.status){if(String(e.status)===`err`)t.push(G.or(G.gte(K.status,400),G.and(G.isNotNull(K.error),G.ne(K.error,``))));else{let n=/^([1-5])xx$/i.exec(String(e.status));if(n&&n[1]){let e=Number(n[1]);t.push(G.and(G.gte(K.status,e*100),G.lt(K.status,(e+1)*100)))}else/^\d+$/.test(String(e.status))&&t.push(G.eq(K.status,Number(e.status)))}}if(e.keyword){let n=`%${e.keyword}%`;t.push(G.or(G.like(K.model,n),G.like(K.method,n),G.like(K.path,n),G.like(K.preview,n),G.like(K.error,n),G.like(K.time,n)))}return t.length===0?null:G.and(...t)}function rf(e,t){return t===null?e:e.where(t)}function af(e){return{p:Math.max(parseInt(String(e.page))||1,1),ps:Math.min(Math.max(parseInt(String(e.pageSize))||50,1),500)}}function of(e){return e===`model`||e===`status`||e===`stream`?e:`time`}var sf={model:K.model,status:K.status,stream:K.stream,time:K.time},cf=[`id`,`time`,`method`,`path`,`model`,`status`,`stream`,`error`,`preview`,`input_tokens`,`output_tokens`,`cache_read_tokens`,`cache_creation_tokens`,`ip`,`session_id`,`duration`,`headers`,`client`];function lf(e){let t=e=>{let t=sf[of(e.sort)];return e.order===`asc`?G.asc(t):G.desc(t)},{p:n,ps:r}=af(e),i=nf(e),a=q(),o=rf(a.select(K).columns({c:G.count()}),i).get();return{total:o?Number(o.c):0,page:n,pageSize:r,items:rf(a.select(K).columns(cf),i).orderBy(t(e)).limit(r).offset((n-1)*r).all().map(e=>({...e}))}}function uf(e={}){let t=[G.and(G.isNotNull(K.model),G.ne(K.model,``)),G.eq(K.status,200),G.or(...Yl.map(e=>G.like(K.path,e)))];e.startDate&&t.push(G.gte(K.date,e.startDate)),e.endDate&&t.push(G.lte(K.date,e.endDate)),e.model&&t.push(G.eq(K.model,e.model));let n=G.and(...t),r=q().all(yu`
|
|
26
26
|
SELECT model,
|
|
27
27
|
COUNT(*) AS calls,
|
|
28
28
|
SUM(input_tokens) AS input_tokens,
|
|
@@ -34,83 +34,93 @@ import{createRequire as e}from"node:module";import{homedir as t,networkInterface
|
|
|
34
34
|
WHERE ${n}
|
|
35
35
|
GROUP BY model
|
|
36
36
|
ORDER BY calls DESC
|
|
37
|
-
`).map(e=>{let t=Number(e.input_tokens),n=Number(e.output_tokens),r=Number(e.cache_read_tokens);return{model:e.model||`unknown`,calls:Number(e.calls),input_tokens:t,output_tokens:n,total_tokens:t+n,cache_read_tokens:r,cache_creation_tokens:Number(e.cache_creation_tokens),cache_rate:t>0?Math.round(r/t*1e3)/10:null,avg_duration:e.avg_duration==null?null:Math.round(Number(e.avg_duration))}}),i=r.reduce((e,t)=>e+t.input_tokens,0),a=r.reduce((e,t)=>e+t.output_tokens,0),o=r.reduce((e,t)=>e+t.cache_read_tokens,0);return{total:{calls:r.reduce((e,t)=>e+t.calls,0),input_tokens:i,output_tokens:a,total_tokens:i+a,cache_read_tokens:o,cache_creation_tokens:r.reduce((e,t)=>e+t.cache_creation_tokens,0),cache_rate:i>0?Math.round(o/i*1e3)/10:null,avg_duration:(()=>{let e=r.filter(e=>e.avg_duration!=null);if(!e.length)return null;let t=e.reduce((e,t)=>e+(t.avg_duration??0)*t.calls,0),n=e.reduce((e,t)=>e+t.calls,0);return n>0?Math.round(t/n):null})()},models:r}}function
|
|
37
|
+
`).map(e=>{let t=Number(e.input_tokens),n=Number(e.output_tokens),r=Number(e.cache_read_tokens);return{model:e.model||`unknown`,calls:Number(e.calls),input_tokens:t,output_tokens:n,total_tokens:t+n,cache_read_tokens:r,cache_creation_tokens:Number(e.cache_creation_tokens),cache_rate:t>0?Math.round(r/t*1e3)/10:null,avg_duration:e.avg_duration==null?null:Math.round(Number(e.avg_duration))}}),i=r.reduce((e,t)=>e+t.input_tokens,0),a=r.reduce((e,t)=>e+t.output_tokens,0),o=r.reduce((e,t)=>e+t.cache_read_tokens,0);return{total:{calls:r.reduce((e,t)=>e+t.calls,0),input_tokens:i,output_tokens:a,total_tokens:i+a,cache_read_tokens:o,cache_creation_tokens:r.reduce((e,t)=>e+t.cache_creation_tokens,0),cache_rate:i>0?Math.round(o/i*1e3)/10:null,avg_duration:(()=>{let e=r.filter(e=>e.avg_duration!=null);if(!e.length)return null;let t=e.reduce((e,t)=>e+(t.avg_duration??0)*t.calls,0),n=e.reduce((e,t)=>e+t.calls,0);return n>0?Math.round(t/n):null})()},models:r}}function df(){return q().select(K).columns([`date`]).groupBy(K.date).orderBy(G.desc(K.date)).all().map(e=>e.date)}function ff(){return q().select(K).columns([`client`]).where(G.and(G.isNotNull(K.client),G.ne(K.client,``))).groupBy(K.client).orderBy(G.asc(K.client)).all().map(e=>e.client)}var pf=yu.raw(`
|
|
38
38
|
COUNT(*) AS calls,
|
|
39
39
|
MIN(time) AS first_time,
|
|
40
40
|
MAX(time) AS last_time,
|
|
41
41
|
GROUP_CONCAT(DISTINCT model) AS models,
|
|
42
|
+
GROUP_CONCAT(DISTINCT client) AS clients,
|
|
42
43
|
SUM(CASE WHEN status >= 400 OR (error IS NOT NULL AND error <> '') THEN 1 ELSE 0 END) AS errors,
|
|
43
44
|
SUM(input_tokens) AS input_tokens,
|
|
44
45
|
SUM(output_tokens) AS output_tokens,
|
|
45
46
|
SUM(cache_read_tokens) AS cache_read_tokens,
|
|
46
47
|
SUM(cache_creation_tokens) AS cache_creation_tokens,
|
|
47
|
-
SUM(duration) AS duration`);function
|
|
48
|
-
SELECT session_id, ${
|
|
48
|
+
SUM(duration) AS duration`);function mf(e){let t=e=>({session_id:e.session_id==null?``:String(e.session_id),calls:Number(e.calls??0),first_time:String(e.first_time??``),last_time:String(e.last_time??``),models:e.models==null?null:String(e.models),clients:e.clients==null?null:String(e.clients),errors:Number(e.errors??0),input_tokens:Number(e.input_tokens??0),output_tokens:Number(e.output_tokens??0),cache_read_tokens:Number(e.cache_read_tokens??0),cache_creation_tokens:Number(e.cache_creation_tokens??0),duration:Number(e.duration??0)}),{p:n,ps:r}=af(e),i=nf(e),a=G.and(G.isNotNull(K.session_id),G.ne(K.session_id,``)),o=G.or(G.isNull(K.session_id),G.eq(K.session_id,``)),s=i===null?a:G.and(i,a),c=i===null?o:G.and(i,o),l=q(),u=l.all(yu`
|
|
49
|
+
SELECT session_id, ${pf}
|
|
49
50
|
FROM logs
|
|
50
|
-
WHERE ${
|
|
51
|
+
WHERE ${s}
|
|
51
52
|
GROUP BY session_id
|
|
52
53
|
ORDER BY last_time DESC
|
|
53
|
-
LIMIT ${
|
|
54
|
-
`).map(
|
|
55
|
-
SELECT ${
|
|
54
|
+
LIMIT ${r} OFFSET ${(n-1)*r}
|
|
55
|
+
`).map(t),d=l.get(yu`
|
|
56
|
+
SELECT ${pf}
|
|
56
57
|
FROM logs
|
|
57
|
-
WHERE ${
|
|
58
|
-
`),d
|
|
59
|
-
SELECT COUNT(DISTINCT session_id) AS c FROM logs WHERE ${
|
|
60
|
-
`),
|
|
61
|
-
SELECT COUNT(*) AS c FROM logs WHERE ${
|
|
62
|
-
`);return{total:Number(
|
|
58
|
+
WHERE ${c}
|
|
59
|
+
`),f=d&&Number(d.calls??0)>0?t(d):null,p=l.get(yu`
|
|
60
|
+
SELECT COUNT(DISTINCT session_id) AS c FROM logs WHERE ${s}
|
|
61
|
+
`),m=l.get(yu`
|
|
62
|
+
SELECT COUNT(*) AS c FROM logs WHERE ${i??G.and()}
|
|
63
|
+
`);return{total:Number(p?.c??0),rowsTotal:Number(m?.c??0),page:n,pageSize:r,groups:u,noSession:f}}var hf=[`id`,`time`,`date`,`model`,`status`,`stream`,`error`,`preview`];function gf(e,t=Xl,n=Zl){let{p:r,ps:i}=af(e),a=String(e.keyword??``).toLowerCase(),o=Math.max(0,Math.floor(t));if(!a)return{total:0,page:r,pageSize:i,items:[],truncated:!1,scanLimit:o};let s=rf(q().select(K).columns(hf),tf(e)).orderBy(G.desc(K.time)).limit(o+1).all(),c=s.length>o,l=s.slice(0,o),u=new Map;for(let e of l){let t=String(e.date),n=u.get(t);n===void 0?u.set(t,[Number(e.id)]):n.push(Number(e.id))}let d=new Map,f=new Map;for(let[e,t]of u){let n=Wd.openIfExists(e);if(n!==null){f.set(e,n);for(let e=0;e<t.length;e+=400){let r=t.slice(e,e+400),i=n.select(pd).columns([`log_id`,`detail`]).where(G.in(pd.log_id,r)).all();for(let e of i)d.set(Number(e.log_id),e.detail)}}}let p=[],m=new Map,h=0,g=!1;for(let e of l){let t=d.get(Number(e.id));if(!t||t.length===0)continue;if(h>=n){g=!0;break}let r=String(e.date),i;try{let e=qd(t).toString(`utf-8`);h+=Buffer.byteLength(e),i=JSON.parse(e)}catch{continue}let a=m.get(r);if(a===void 0){let e=new Set;Xd(i,e),m.set(r,e)}else Xd(i,a);p.push({r:e,date:r,raw:i})}let _=c||g,v=new Map;for(let[e,t]of m){let n=f.get(e);n!==void 0&&v.set(e,Zd(t,n))}let y=[];for(let{r:t,date:n,raw:r}of p){let i=Yd(r,v.get(n)??new Map);JSON.stringify(i).toLowerCase().includes(a)&&(!e.model||String(i.model??``).includes(e.model))&&(!e.status||$d(Number(i.status??0),e.status,i.error))&&ef(i.path,e.pathGroup)&&y.push({time:t.time,method:i.method||null,path:i.path||null,model:i.model||``,status:i.status,stream:!!i.stream,error:i.error||null,preview:t.preview,id:t.id})}let b=of(e.sort),x=e.order===`asc`?1:-1;return y.sort((e,t)=>{let n=e[b]??``,r=t[b]??``;return n>r?x:n<r?-x:0}),{total:y.length,page:r,pageSize:i,items:y.slice((r-1)*i,(r-1)*i+i),truncated:_,scanLimit:o}}function _f(e){let t=Wd.open(e),n=new Set,r=0,i=0,a=t.select(pd).columns([`detail`]).all();for(let e of a){r++;try{Xd(JSON.parse(qd(e.detail).toString(`utf-8`)),n)}catch{i++}}if(i>0)return gt(`[logs] 详情库 ${e} 有 ${String(i)} 条详情解析失败,跳过本次 blob 回收(避免误删仍被引用的内容)`),{scanned:r,blobsDeleted:0,skipped:!0};let o=t.select(md).columns([`hash`]).all().map(e=>e.hash).filter(e=>!n.has(e));if(o.length===0)return{scanned:r,blobsDeleted:0,skipped:!1};let s=0;return t.transaction(()=>{for(let e=0;e<o.length;e+=400){let n=t.delete(md).where(G.in(md.hash,o.slice(e,e+400))).run();s+=Number(n.changes)}}),{scanned:r,blobsDeleted:s,skipped:!1}}function vf(e){let t=q(),n=nf(e),r=rf(t.select(K).columns({c:G.count()}),n).get(),i=r?Number(r.c):0,a;if(i>0)a=rf(t.select(K).columns([`id`]),n).all().map(e=>Number(e.id));else if(e.keyword){a=[];let t=!1;for(let n=1;;n++){let r=gf({...e,page:n,pageSize:500,sort:`time`,order:`desc`});if(a.push(...r.items.map(e=>Number(e.id))),t||=r.truncated,r.items.length===0||a.length>=r.total)break}t&>(`[logs] 详情扫描达到上限,仅清理最近扫描窗口内的命中条目(更早的命中未参与匹配)`)}else return 0;if(a.length===0)return 0;let o=new Map;for(let e=0;e<a.length;e+=400){let n=t.select(K).columns([`id`,`date`]).where(G.in(K.id,a.slice(e,e+400))).all();for(let e of n){let t=o.get(e.date);t===void 0?o.set(e.date,[Number(e.id)]):t.push(Number(e.id))}}for(let[e,t]of o){let n=Wd.open(e);n.transaction(()=>{for(let e=0;e<t.length;e+=400)n.delete(pd).where(G.in(pd.log_id,t.slice(e,e+400))).run()})}Ed(()=>{for(let e=0;e<a.length;e+=400)t.delete(K).where(G.in(K.id,a.slice(e,e+400))).run()});for(let e of o.keys())try{_f(e)}catch(t){gt(`[logs] 详情库 ${e} 的 blob 回收失败:`,$l(t))}return a.length}function yf(e,t){let n=e=>Ql(new Date(Date.now()-e*86400*1e3).toISOString());if(e<=0&&t<=0)return{detailsDeleted:0,rowsDeleted:0};let r=0;if(e>0){let t=n(e);for(let e of Wd.listDetailDates())e<t&&Wd.deleteDetailDb(e)&&r++}let i=0;if(t>0){let e=n(t),r=Ed(()=>q().delete(K).where(G.lt(K.date,e)).run());i=Number(r.changes)}return{detailsDeleted:r,rowsDeleted:i}}var bf={syncIntervalMs:5e3,payloadQuality:9},xf=2e3,Sf=1e3,Cf=1e3;function wf(e){return q().select(K).columns([`id`]).where(G.eq(K.id,e)).get()!==void 0}var Tf=class{#e;#t;#n=null;#r=!1;#i=0;constructor(e){this.#e=e.spool,this.#t=e.getConfig}runScheduledRound(){this.#r||this.#n!==null||(this.#r=!0,this.syncOnce().then(e=>{(e.inserted>0||e.poisoned>0)&&L(`[ezllm] spool 入库: 详情 ${String(e.inserted)} 条`)}).catch(e=>{R(`[ezllm] spool 入库失败:`,$l(e))}).finally(()=>{this.#r=!1}))}async syncOnce(e={}){let t=e.budgetMs??xf,n=Date.now()+t,r={inserted:0,poisoned:0,anchorFilled:0,filesDone:[]},i=this.#t(),a=this.#e.listIds();for(let e of a){if(Date.now()>=n)break;let t=this.#e.readRecord(e);if(t.kind!==`missing`){if(t.kind===`corrupt`){gt(`[spool] 丢弃不可解析的记录 ${String(e)}.jsonl`),this.#e.deleteFile(e),r.poisoned++;continue}try{let n=Pd(t.entry,e,i.payloadQuality),a=wf(e);Gd([n]),a||r.anchorFilled++,r.inserted++}catch(t){R(`[spool] 记录 ${String(e)} 入库失败:`,$l(t));continue}this.#e.deleteFile(e),r.filesDone.push(e),await ou()}}return r}async syncNow(){if(this.#n!==null){await this.#n;return}if(!this.#r&&!(Date.now()-this.#i<Cf)){this.#i=Date.now(),this.#n=this.syncOnce({budgetMs:500});try{await this.#n}finally{this.#n=null}}}async recover(){if(this.#n!==null){await this.#n;return}let e=this.syncOnce({budgetMs:3e4});this.#n=e;try{let t=await e;t.inserted>0&&L(`[ezllm] spool 启动恢复:补录 ${String(t.inserted)} 条日志详情`)}catch(e){R(`[ezllm] spool 启动恢复失败:`,$l(e))}finally{this.#n=null}}async drain(e=6e4){let t={inserted:0,poisoned:0,anchorFilled:0,filesDone:[]},n=Date.now()+e;for(;;){let e=await this.syncOnce({budgetMs:Math.min(5e3,Math.max(0,n-Date.now()))});if(t.inserted+=e.inserted,t.poisoned+=e.poisoned,t.anchorFilled+=e.anchorFilled,t.filesDone.push(...e.filesDone),this.#e.listIds().length===0||Date.now()>=n)break}return t}},Ef=null;function Df(e){return Ef===null&&(Ef=e===void 0?new Tf({spool:new pu,getConfig:()=>bf}):new Tf(e)),Ef}function Of(e){let t=Df(e);return{name:`spoolSync`,everyMs:()=>e.getConfig().syncIntervalMs,firstDelayMs:Sf,run:()=>{t.runScheduledRound()}}}async function kf(){await Df().syncNow()}async function Af(){await Df().recover()}async function jf(e=6e4){return Df().drain(e)}var Mf=216e5,Nf=3e4;function Pf(e){return{name:`logPrune`,everyMs:Mf,firstDelayMs:Nf,run:()=>{try{let{detailDays:t,rowDays:n}=e.getRetention(),r=yf(t,n);(r.detailsDeleted>0||r.rowsDeleted>0)&&L(`[ezllm] 日志清理: 详情库 -${String(r.detailsDeleted)} 天, 摘要 -${String(r.rowsDeleted)} 条 (详情${t>0?` ${String(t)}天`:`永久`}, 摘要${n>0?` ${String(n)}天`:`永久`})`)}catch(e){R(`[ezllm] 日志清理失败:`,$l(e))}}}}var Ff=3,If=`fallback`;function Lf(){return new Date().toISOString()}function Rf(e){return q().select(gd).columns([`client`]).where(G.eq(gd.ua,e)).get()}function zf(e){if(e.length===0)return 0;let t=Lf(),n=q(),r=0;return Ed(()=>{for(let i of e){let e=n.insert(gd).values({ua:i,client:null,source:null,attempts:0,created_at:t,updated_at:t}).orIgnore().run();r+=Number(e.changes)}}),r}function Bf(){return q().select(gd).columns([`ua`,`client`]).where(G.isNotNull(gd.client)).all().filter(e=>e.client!==null&&e.client!==``)}function Vf(e,t){if(e===``||t===``)return 0;let n=q().run(yu`
|
|
64
|
+
UPDATE logs SET client = ${t}
|
|
65
|
+
WHERE client IS NULL AND ${yu.raw(eu)} = ${e}
|
|
66
|
+
`);return Number(n.changes)}function Hf(e){return q().select(gd).columns([`ua`]).where(G.and(G.isNull(gd.client),G.lt(gd.attempts,Ff))).orderBy(G.asc(gd.created_at)).limit(e).all().map(e=>e.ua)}function Uf(e,t){if(e.size===0)return 0;let n=Lf(),r=q(),i=0;return Ed(()=>{for(let[a,o]of e){let e=r.update(gd).set({client:o,source:t,updated_at:n}).where(G.eq(gd.ua,a)).run();i+=Number(e.changes)}}),i}function Wf(e){if(e.length===0)return[];let t=q(),n=t.select(gd).columns([`ua`,`attempts`,`client`]).where(G.in(gd.ua,[...e])).all(),r=[],i=Lf();return Ed(()=>{for(let e of n){if(e.client!==null)continue;let n=e.attempts+1;t.update(gd).set({attempts:n,updated_at:i}).where(G.eq(gd.ua,e.ua)).run(),n>=Ff&&r.push(e.ua)}}),r}var Gf=new Map,Kf=new Set;function qf(e){let t=e.trim();if(t===``)return null;if(Gf.has(t))return Gf.get(t)??null;let n=Rf(t);return n===void 0?(Gf.set(t,null),Kf.add(t),null):(Gf.set(t,n.client),n.client)}function Jf(e){return(()=>{if(Kf.size===0)return 0;let e=zf([...Kf]);return Kf.clear(),e})(),Hf(e)}function Yf(e,t){if(e.size===0)return 0;let n=Uf(e,t);for(let[t,n]of e)Vf(t,n),Gf.set(t,n),Kf.delete(t);return n}function Xf(e){return Wf(e)}var Zf=100,Qf=67108864,$f=new Set([`authorization`,`proxy-authorization`,`x-api-key`,`api-key`,`x-goog-api-key`,`cookie`,`set-cookie`]),ep=new Set([`key`,`apikey`,`accesskey`,`accesstoken`,`token`,`authtoken`,`sig`,`signature`,`secret`,`password`]);function tp(e){let t=e=>e===null?null:e.split(`
|
|
63
67
|
|
|
64
|
-
`).filter(e=>e.trim()!==``)}function Lp(e){return`***redacted(${String(e)})***`}function Rp(e){if(e===null)return null;try{return JSON.parse(e)}catch{return e}}function zp(e){if(!e)return e;let t=!1,n={};for(let[r,i]of Object.entries(e))Pp.has(r.toLowerCase())?(n[r]=Lp(i.length),t=!0):n[r]=i;return t?n:e}function Bp(e){return e.toLowerCase().replace(/[-_]/g,``)}function Vp(e){let t;try{t=new URL(e)}catch{return e}let n=!1;for(let[e,r]of Array.from(t.searchParams.entries()))Fp.has(Bp(e))&&(t.searchParams.set(e,Lp(r.length)),n=!0);return n?t.toString():e}function Hp(e){let t=e.streaming,n=e.upstream,r=e.inbound.bodyText!==null||n.url!==null||n.responseText!==null||e.client.body!==void 0||e.client.streamText!==null;return{time:e.time,method:e.http.method||void 0,path:e.http.path||void 0,model:e.route?.name||void 0,status:e.status,stream:t,error:e.error?.message??null,response:r?{_capture:!0,inbound_request:{url:Vp(e.http.url),headers:zp(e.inbound.headers),body:e.inbound.body??null},upstream_request:n.url?{url:Vp(n.url),headers:zp(n.requestHeaders),body:Rp(n.requestBody)}:null,upstream_response_text:t?null:n.responseText,upstream_stream_frames:t?Ip(n.responseText):null,client_response:t?void 0:e.client.body,client_stream_frames:t?Ip(e.client.streamText):null,truncated:e.truncated}:null,input_tokens:e.usage?.inputTokens??0,output_tokens:e.usage?.outputTokens??0,cache_read_tokens:e.usage?.cacheReadInputTokens??0,cache_creation_tokens:e.usage?.cacheCreationInputTokens??0,ip:e.http.clientIp||null,session_id:e.http.sessionId||null,duration:e.durationMs}}function Up(e,t){let n=Hp(t),r=Number(t.requestId),i=Number.isSafeInteger(r)&&r>0?r:wf();e.write(i,n),Mf(i,n),z(`[ezllm] ${t.requestId} ${t.route?.name??t.http.path} -> ${String(t.status)} ${String(t.durationMs)}ms streaming=${String(t.streaming)}`+(t.error===null?``:` error=${t.error.stage}: ${t.error.message}`))}var Wp=class{#e;#t;#n;#r=[];#i=0;#a=!1;constructor(e={}){this.#e=e.spool??new td,this.#t=e.queueCapacity??Mp,this.#n=e.queueMaxBytes??Np}#o(){let e=this.#r.shift();return this.#i-=Gp(e),e}async#s(){if(!this.#a){this.#a=!0;try{for(;this.#r.length>0;){await Ju();try{Up(this.#e,this.#o())}catch(e){B(`[ezllm] trace 落盘失败:`,Uu(e))}}}finally{this.#a=!1}}}write(e){for(;this.#r.length>=this.#t||this.#i>=this.#n&&this.#r.length>0;)this.#o(),dt(`[ezllm] trace 队列已满(${String(this.#t)} 条 / ${String(Math.round(this.#n/1024/1024))}MB),丢弃最旧一条`);this.#r.push(e),this.#i+=Gp(e),this.#s()}async flush(){for(;this.#r.length>0||this.#a;)await Ju();await this.#e.flush()}flushSync(){for(;this.#r.length>0;)try{Up(this.#e,this.#o())}catch(e){B(`[ezllm] trace 崩溃前落盘失败:`,Uu(e))}this.#e.flushSync()}};function Gp(e){return(e.inbound.bodyText?.length??0)+(e.upstream.requestBody?.length??0)+(e.upstream.responseText?.length??0)+(e.client.streamText?.length??0)+4096}function Kp(){for(let e of xt())if(d(e))return e;return null}function qp(e,t){if(typeof e!=`object`||!e)return null;let n=e,r=n.default??n[`module.exports`]??n;if(typeof r!=`object`||!r)return null;let i=r;return typeof i.onModelRequest==`function`?{onModelRequest:i.onModelRequest}:(dt(`[ezllm] ${t} 未导出 onModelRequest 函数,已忽略(不挂任何钩子)`),null)}async function Jp(e){let t=Kp();if(t===null)return;let n;try{n=await import(O(t).href)}catch(e){B(`[ezllm] 加载用户钩子失败,本次按无钩子运行:${t}`),B(`[ezllm] 原因:${e instanceof Error?e.message:String(e)}`),B(`[ezllm] 提示:模块写法与文件扩展名不匹配。CJS 内容(module.exports)请用 hook.cjs,ESM 内容(export default)请用 hook.mjs——这两个扩展名强制解析模式,不受任何 package.json 的 type 影响`);return}let r=qp(n,t);r?.onModelRequest!==void 0&&(e.addHook(`onModelRequest`,r.onModelRequest),z(`[ezllm] 已加载用户钩子:${t}(onModelRequest)`))}function Yp(e){return ut.PORT??e.port}async function Xp(e,t,n={}){let r=new du({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(wf())}});t.register(r),await Jp(r);let i={current:r,port:r.expanded.port,rebuild(e){i.current.reload(e),i.port=i.current.expanded.port;let t=i.current.expanded.deployments.names.length,n=e.providers.filter(e=>e.enabled===!1).length,r=n>0?`(${String(n)} 个已停用)`:``;z(`[gateway] 配置已热更新: ${String(e.providers.length)} 个供应商${r} / ${String(t)} 个模型`)},proxy:new $n},a=async e=>{let t=new URL(e.req.url),n=new Headers(e.req.raw.headers);if(!n.has(`x-forwarded-for`)){let t=e.env?.incoming?.socket?.remoteAddress??``;t!==``&&n.set(`x-forwarded-for`,t)}if(!n.has(`authorization`)&&n.has(`x-api-key`)){let e=n.get(`x-api-key`)??``;e!==``&&n.set(`authorization`,`Bearer ${e}`)}return i.current.build().fetch(new Request(t.toString(),{method:e.req.raw.method,headers:n,body:e.req.raw.body,duplex:`half`}))};return i.proxy.use(`/v1/models`,async(e,n)=>{let r=e.req.header(`authorization`)??(e.req.header(`x-api-key`)===null?``:`Bearer ${e.req.header(`x-api-key`)}`);if(!await t.authorize(r))return Response.json({error:{message:`Unauthorized: invalid api key`,type:`authentication_error`,code:`401`}},{status:401});await n()}),i.proxy.all(`/v1/*`,e=>a(e)),i.proxy.all(`/v1`,e=>a(e)),i.proxy.all(`/responses`,e=>a(e)),i.proxy.all(`/chat/completions`,e=>a(e)),i.proxy.all(`/messages`,e=>a(e)),i.proxy.all(`/messages/count_tokens`,e=>a(e)),i.proxy.all(`/models`,e=>a(e)),i.proxy.all(`/healthz`,e=>a(e)),i}var Zp=64;function Qp(e){return e.trim()}function $p(e,t={}){let n=new Map;function r(e,t){for(n.delete(e),n.set(e,t);n.size>Zp;){let e=n.keys().next().value;if(e===void 0)break;n.delete(e)}}function i(){return new Set(t.knownModelNames?t.knownModelNames():e.expanded.deployments.names)}e.plugin(e=>{e.addHook(`onFinish`,e=>{if(e.status!==200||e.ctx.model===null)return;let t=Qp(e.ctx.userAgent);t!==``&&r(t,e.ctx.model.name)}),e.addHook(`onModelNotFound`,t=>{if(i().has(t.requestedModel))return;let r=Qp(t.userAgent);if(r===``)return;let a=n.get(r);if(a!==void 0){if(!e.expanded.deployments.byName.has(a)){n.delete(r);return}return a}})})}var em=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`,`QUERY`],allowHeaders:[],exposeHeaders:[],...e},n=t.exposeHeaders?.length?t.exposeHeaders.join(`,`):void 0,r=t.allowHeaders?.length?t.allowHeaders.join(`,`):void 0,i=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),a=(e=>{if(typeof e==`function`)return async(t,n)=>(await e(t,n)).join(`,`);if(Array.isArray(e)){let t=e.join(`,`);return()=>t}return()=>``})(t.allowMethods);return async function(e,o){function s(t,n){e.res.headers.set(t,n)}let c=await i(e.req.header(`origin`)||``,e);if(c&&s(`Access-Control-Allow-Origin`,c),t.credentials&&s(`Access-Control-Allow-Credentials`,`true`),n&&s(`Access-Control-Expose-Headers`,n),e.req.method===`OPTIONS`){t.origin!==`*`&&e.res.headers.append(`Vary`,`Origin`),t.maxAge!=null&&s(`Access-Control-Max-Age`,t.maxAge.toString());let n=await a(e.req.header(`origin`)||``,e);n&&s(`Access-Control-Allow-Methods`,n);let i=r;if(!i){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(`,`).map(e=>e.trim()).join(`,`))}return i&&(s(`Access-Control-Allow-Headers`,i),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await o(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}};async function tm(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var nm=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,rm=new $n;function im(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}rm.post(`/login`,async e=>{let t=Du();if(t.configBroken)return e.json({error:nm},503);if(!t.required)return e.json({error:`当前未设置登录账号,管理台免登录访问(如需启用请先设置账号)`},400);let n=await tm(e);if(n===null)return e.json({error:`请求体格式错误`},400);let{username:r,password:i}=n;return(r??``).trim()!==t.username||i!==t.password?e.json({error:`用户名或密码错误`},401):e.json({token:im(t)})});async function am(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=Du();if(!n.required)return await t();if(n.configBroken)return e.json({error:nm},401);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==im(n))return e.json({error:`token 无效或已过期`},401);await t()}var om=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function sm(e,t){return e instanceof om?(e.status>=500&&B(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e.message),t.json({error:e.message},e.status)):(B(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e instanceof Error?e.message:e),t.json({ok:!1,error:e instanceof Error?e.message:String(e)},500))}function cm(e){return async t=>{try{return await e(t)}catch(e){throw new om(500,e.message)}}}var lm=8,um=6;function dm(){let e=hu();if(e===null)throw new om(500,`配置文件不存在`);return e}function fm(){let e=new $n;return e.onError(sm),e.use(`*`,async(e,t)=>{if(e.req.method===`GET`)return t();let n=e.req.header(`sec-fetch-site`);if(n===`same-origin`||n===`none`)return t();let r=e.req.header(`origin`);return r===void 0||r.toLowerCase()===new URL(e.req.url).origin.toLowerCase()?t():e.json({error:`已拒绝跨站写请求`},403)}),e.get(`/status`,e=>{let t=Ou(),n=!1;try{n=wu()!==``}catch(e){if(!(e instanceof mu))throw e}return e.json({initialized:t.completed,deployment:t.deployment,masterKeySet:n,authRequired:Du().required,version:At()})}),e.post(`/master-key`,async e=>{if(Ou().completed)return e.json({error:`已完成初始化,请到设置页修改主密钥`},403);let t=await tm(e);if(t===null)return e.json({error:`请求体格式错误`},400);let n;if(t.mode===`generate`)n=A(32).toString(`base64url`);else if(t.mode===`custom`){if(n=(t.masterKey??``).trim(),n.length<lm)return e.json({error:`主密钥至少 ${String(lm)} 位`},400)}else return e.json({error:`mode 必须是 generate 或 custom`},400);let r=dm(),i={...r,masterKey:n};return _u(i),e.json({masterKey:n,...Nu(r,i)?{restartHint:Su}:{}})}),e.post(`/finish`,async e=>{if(Ou().completed)return e.json({error:`已完成初始化,请到设置页修改`},403);let t=await tm(e);if(t===null)return e.json({error:`请求体格式错误`},400);let n=t.deployment;if(n!==`local`&&n!==`server`)return e.json({error:`deployment 必须是 local 或 server`},400);if(n===`server`&&wu()===``)return e.json({error:`服务器部署必须设置主密钥,防止 /v1 网关被他人盗用`},400);let r=(t.username??``).trim(),i=t.password??``,a=r!==``||i!==``;if(a){if(r===``||i===``)return e.json({error:`用户名和密码需同时提供`},400);if(i.length<um)return e.json({error:`密码至少 ${String(um)} 位`},400)}else if(n===`server`)return e.json({error:`服务器部署必须设置登录账号密码,防止管理台被陌生人登录`},400);let o=dm(),s={...o,setup:{completed:!0,deployment:n},allowLan:n===`server`,...a?{"web-ui":{...o[`web-ui`],"login-account":{username:r,password:i}}}:{}};return _u(s),e.json({message:a?`初始化完成,请使用新账号登录`:`初始化完成`,...Nu(o,s)?{restartHint:Su}:{}})}),e}function pm(e){let t=new $n;return t.onError(sm),t.get(`/`,cm(e=>{let t=hu();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,cm(async t=>{let n=await t.req.json();if(typeof n!=`object`||!n||!Array.isArray(n.providers))return t.json({error:`配置格式错误:providers 必须是数组`},400);try{yu(n)}catch(e){if(e instanceof cr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let r=null;try{r=hu()}catch{r=null}return _u(n),e.runtime.rebuild(vu(n)),t.json({message:`配置已保存并生效`,...Nu(r,n)?{restartHint:Su}:{}})})),t}var mm=`直接回复我 ok,不要思考不要解释`;function hm(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function gm(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function _m(e){let t=new $n;t.onError(sm);let n=It(`test-results.json`),r=It(`models-cache.json`);function i(e,t=`openai`,n=!0){let r=e.replace(/\/+$/,``);return t===`anthropic`&&r.endsWith(`/anthropic`)&&(r=r.slice(0,-10)),`${hm(r,n)}/models`}function a(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();if(e.includes(`authorization`)||e.includes(`api-key`)||e.includes(`token`)){let e=String(r);t[n]=e.length>8?`${e.slice(0,3)}****${e.slice(-4)}`:`****`}else t[n]=r}return t}async function o(e,t,n,r){return fetch(i(e,n,r),{headers:gm(t,n),signal:AbortSignal.timeout(1e4)})}async function s(e,t){if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`});let n=await o(t.api_base,t.api_key,t.protocol??`openai`,t.autoV1??!0);return n.ok?await n.json():e.json({status:`error`,message:`HTTP ${String(n.status)}`})}function c(e){let{response:t,data:n,latency:r,url:i,headers:o,payload:s}=e;if(t.ok&&(n.choices!==void 0||n.output!==void 0||n.content!==void 0))return{status:`ok`,message:`${String(n.usage?.completion_tokens??n.usage?.output_tokens??0)} tokens`,latency:r,request:{method:`POST`,url:i,headers:a(o),body:s},response:{status:t.status,body:n}};let c=typeof n.error==`object`&&n.error!==null&&`message`in n.error?String(n.error.message):typeof n.error==`string`?n.error:`HTTP ${String(t.status)}`;return{status:`error`,message:l(typeof c==`string`?c:JSON.stringify(c)),latency:r,request:{method:`POST`,url:i,headers:a(o),body:s},response:{status:t.status,body:n}}}function l(e){let t=e;for(let[e,n]of[[/Weekly usage limit reached/i,`每周使用限额已达上限`],[/Resets in (\d+) day/i,`$1 天后重置`],[/RateLimitError:?\s*OpenAIException\s*-?\s*/gi,``],[/RateLimitError/g,`频率限制`],[/Rate limit/gi,`请求频率超限`],[/Invalid.*api.?key/i,`API Key 无效`],[/Unauthorized/i,`认证失败`],[/Not found/i,`模型或端点不存在`],[/Timeout/i,`请求超时`],[/Connection refused/i,`连接被拒绝`],[/ECONNREFUSED/i,`连接被拒绝`],[/ENOTFOUND/i,`域名无法解析`],[/model.*not.*found/i,`模型不存在`],[/context length exceeded/i,`上下文长度超限`],[/maximum context length/i,`超过最大上下文长度`],[/overloaded/i,`服务过载`],[/internal server error/i,`服务器内部错误`],[/bad gateway/i,`网关错误`],[/OpenAIException\s*-?\s*/i,``],[/To continue using[\s\S]*$/i,``],[/Received Model Group[\s\S]*$/i,``],[/Available Model Group[\s\S]*$/i,``],[/HTTP (\d+)/,`HTTP 错误 $1`]])t=t.replace(e,n);return t=t.replace(/\s+/g,` `).replace(/^[.:;\s-]+|[.:;\s-]+$/g,``).trim(),t||=e,t.length>120&&(t=t.substring(0,120)+`...`),t}t.get(`/results`,cm(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,cm(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,cm(async e=>{let{keyId:t,models:n}=await e.req.json();return!t||!Array.isArray(n)?e.json({error:`缺少必要参数: keyId, models`},400):(r.set(t,n),e.json({message:`模型缓存已更新`,keyId:t,count:n.length}))})),t.post(`/`,async e=>{try{let t=await s(e,await e.req.json());return t instanceof Response?t:e.json({status:`ok`,models:t.data?.length||0,protocol:`openai`})}catch(t){return e.json({status:`error`,message:t.message})}}),t.post(`/fetch-models`,async e=>{try{let t=await e.req.json(),n=await s(e,t);if(n instanceof Response)return n;let i=(n.data||[]).map(e=>e.id||e.name).filter(e=>!!e);if(t.keyId){let e=r.get(t.keyId)??[],n=[...new Set([...e,...i])];r.set(t.keyId,n)}return e.json({status:`ok`,models:i})}catch(t){return e.json({status:`error`,message:t.message})}});function u(e,t){return t===`anthropic`?{model:e,messages:[{role:`user`,content:mm}],max_tokens:16}:t===`openai-responses`?{model:e,input:mm}:{model:e,messages:[{role:`user`,content:mm}]}}async function d(e){let t=e.protocol||`openai`,n=e.autoV1??!0,r=e.api_base.replace(/\/+$/,``);if(!r)throw Error(`api_base 不能为空`);let i={"Content-Type":`application/json`,...gm(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${hm(r,n)}${a}`,s=u(e.model,t),l=Date.now(),d=await fetch(o,{method:`POST`,headers:i,body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)}),f=Date.now()-l;return c({response:d,data:await d.json().catch(()=>({})),latency:f,url:o,headers:i,payload:s})}function f(e){let t=hu();for(let n of t?.providers??[]){let t=n.models?.find(t=>t?.modelName===e);if(t)return t.customLlmProvider??n.customLlmProvider??`openai`}return`openai`}async function p(t,n){let r=wu(),i=Yp(e),a=`http://127.0.0.1:${String(i)}`,o={"Content-Type":`application/json`};r&&(o.Authorization=`Bearer ${r}`);let s=`${a}${n===`anthropic`?`/v1/messages`:n===`openai-responses`?`/v1/responses`:`/v1/chat/completions`}`,l=u(t,n),d=Date.now(),f;try{f=await fetch(s,{method:`POST`,headers:o,body:JSON.stringify(l),signal:AbortSignal.timeout(3e4)})}catch(e){let t=e;throw B(`[test] 网关自调用失败:`,t.message,`cause:`,t.cause?.message??`n/a`),e}let p=Date.now()-d,m=await f.json().catch(()=>({}));return c({response:f,data:m,latency:p,url:s,headers:o,payload:l})}return t.post(`/model`,async e=>{try{let t=await e.req.json(),r=t.model;if(!r)return e.json({status:`error`,message:`缺少 model 参数`},400);if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`},400);let i;try{i=await d({model:r,api_base:t.api_base,api_key:t.api_key,protocol:t.protocol,autoV1:t.autoV1})}catch(e){i={status:`error`,message:l(e.message),latency:0}}return n.set(r,{...i,time:new Date().toISOString()}),e.json(i)}catch(t){return e.json({status:`error`,message:l(t.message)})}}),t.post(`/proxy`,async e=>{try{let t=(await e.req.json()).model;if(!t)return e.json({status:`error`,message:`缺少 model 参数`},400);let r=await p(t,f(t));return n.set(t,{...r,time:new Date().toISOString()}),e.json(r)}catch(t){return e.json({status:`error`,message:l(t.message)})}}),t}var vm=vd(`latency_probes`,{id:hd().primaryKey({autoIncrement:!0}),model:md().notNull(),time:hd().notNull(),latency_ms:hd().notNull(),ok:hd().notNull(),error:md()},[_d(`idx_latency_probes_model_time`).on(`model`,`time`),_d(`idx_latency_probes_time`).on(`time`)]),ym=2592e6,bm=null;function xm(){let e=bm;if(e!==null)return e;let t=of(`latency`);return t.createTables([vm]),bm=t,t}function Sm(){return xm().native}function Cm(e){if(e.length!==0)try{xm().insert(vm).values(e.map(e=>({model:e.model,time:e.time,latency_ms:e.latencyMs,ok:+!!e.ok,error:e.error??null}))).run()}catch(e){B(`[latency] 探测记录写入失败:`,e instanceof Error?e.message:String(e))}}function wm(){let e=Date.now()-ym;return xm().select(vm).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(J.gt(vm.time,e)).orderBy(J.asc(vm.time)).all().map(e=>({model:e.model,time:Number(e.time),latencyMs:Number(e.latency_ms),ok:e.ok===1,error:e.error??void 0}))}function Tm(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=xm().select(vm).columns([`time`,`latency_ms`,`ok`]).where(J.and(J.eq(vm.model,e),J.gt(vm.time,a),J.lte(vm.time,r))).all();if(o.length===0)return[];let s=e=>{let n=new Date(e);return t===`hour`?new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()).getTime():new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime()},c=[];for(let e=s(r);e>=s(a);e-=i)c.unshift(e);let l=new Map;for(let e of c)l.set(e,{total:0,success:0,latencySum:0});for(let e of o){let t=l.get(s(Number(e.time)));t&&(t.total+=1,e.ok===1&&(t.success+=1,t.latencySum+=Number(e.latency_ms)))}return c.map(e=>{let t=l.get(e);return{bucketStart:e,total:t.total,success:t.success,failed:t.total-t.success,successRate:t.total===0?null:Math.round(t.success/t.total*1e3)/10,avgLatencyMs:t.success===0?null:Math.round(t.latencySum/t.success)}})}function Em(){let e=xm().select(vm).columns({t:J.max(vm.time)}).get();return e?.t==null?null:Number(e.t)}function Dm(e){try{let t=Date.now()-e;xm().delete(vm).where(J.lte(vm.time,t)).run()}catch(e){B(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var Om=3e4,km=4,Am=!1;function jm(){return Am}async function Mm(e){let t=hm((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?gm(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:mm}],max_tokens:1}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:mm,max_output_tokens:16}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:mm}],max_tokens:1});let a=Date.now();try{let t=await fetch(r,{method:`POST`,headers:n,body:JSON.stringify(i),signal:AbortSignal.timeout(Om)}),o=Date.now()-a;if(!t.ok){let n=await t.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,120)).catch(()=>``);return{model:e.name,time:a,latencyMs:0,ok:!1,error:n?`HTTP ${String(t.status)}: ${n}`:`HTTP ${String(t.status)}`}}return await t.arrayBuffer().catch(()=>void 0),{model:e.name,time:a,latencyMs:o,ok:!0}}catch(t){return{model:e.name,time:a,latencyMs:0,ok:!1,error:t.message}}}async function Nm(e){let t=[],n=0,r=Array.from({length:Math.max(1,Math.min(km,e.length))},async()=>{for(;;){let r=n++;if(r>=e.length)return;t.push(await Mm(e[r]))}});return await Promise.all(r),t}function Pm(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function Fm(e){if(Am)return!1;Am=!0;try{let t=await Nm(Pm(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));Cm(t),Dm(ym);let n=t.filter(e=>e.ok).length;return z(`[latency] 测试完成: ${String(t.length)} 个模型(成功 ${String(n)}),数据已入库 latency.db`),!0}catch(e){return B(`[latency] 测试执行失败:`,e instanceof Error?e.message:String(e)),!0}finally{Am=!1}}function Im(e){return Pm(e).length}var Lm=[{key:`avg10m`,ms:6e5},{key:`avg30m`,ms:18e5},{key:`avg1h`,ms:36e5},{key:`avg2h`,ms:72e5},{key:`avg5h`,ms:18e6},{key:`avg8h`,ms:288e5},{key:`avg12h`,ms:432e5},{key:`avg24h`,ms:864e5}];function Rm(e,t,n){return n.map(n=>{let r=e.filter(e=>e.model===n),i={model:n,avg10m:null,avg30m:null,avg1h:null,avg2h:null,avg5h:null,avg8h:null,avg12h:null,avg24h:null,lastTestAt:null,lastOk:null,lastLatencyMs:null,lastError:null},a=r.reduce((e,t)=>e===null||t.time>e.time?t:e,null);a!==null&&(i.lastTestAt=a.time,i.lastOk=a.ok,a.ok&&(i.lastLatencyMs=a.latencyMs),a.ok||(i.lastError=a.error??null));for(let{key:e,ms:n}of Lm){let a=r.filter(e=>e.ok&&e.time>t-n&&e.time<=t);a.length!==0&&(i[e]=Math.round(a.reduce((e,t)=>e+t.latencyMs,0)/a.length))}return i})}function zm(e){let t=new $n;return t.get(`/history`,t=>{let n=wm(),r=Date.now();return t.json({running:jm(),lastRunAt:Em(),models:Rm(n,r,e.current.expanded.deployments.names)})}),t.get(`/trend`,e=>{let t=e.req.query(`model`);if(!t)return e.json({ok:!1,error:`缺少 model 参数`},400);let n=e.req.query(`granularity`)===`day`?`day`:`hour`,r=Tm(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>jm()?t.json({ok:!1,error:`测试进行中,请稍候`},409):Im(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(Fm(e),t.json({ok:!0,running:!0}))),t}function Bm(e){let t=0;if(!d(e))return 0;for(let n of m(e)){let r=w(e,n),i;try{i=v(r)}catch{continue}i.isDirectory()?t+=Bm(r):t+=i.size}return t}function Vm(){return Math.round(Bm(gt())/1024/1024*10)/10}function Hm(){let e=new $n;return e.onError(sm),e.get(`/`,cm(e=>{let t=e.req.query(),n=sp({startDate:t.startDate,endDate:t.endDate,model:t.model});return e.json({...n,logStorageMB:Vm()})})),e}function X(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Z(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Um(e){return typeof e==`string`?e:null}function Wm(e,t){let n=t;for(;n<e.length&&/\s/.test(e[n]);)n+=1;return n}function Gm(e,t){let n=e[t];if(n!==`"`&&n!==`'`&&n!=="`")return null;let r=t+1,i=``;for(;r<e.length;){let t=e[r];if(t===`\\`){i+=e[r+1]??``,r+=2;continue}if(t===n)return{value:i,end:r+1};i+=t,r+=1}return null}function Km(e,t){if(e[t]!==`{`)return null;let n=0,r=t;for(;r<e.length;){let i=e[r];if(i===`"`||i===`'`||i==="`"){let t=Gm(e,r);if(t===null)return null;r=t.end;continue}if(i===`{`)n+=1;else if(i===`}`&&(--n,n===0))return{raw:e.slice(t,r+1),end:r+1};r+=1}return null}function qm(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===`"`||r===`'`||r==="`"){let r=Gm(e,n);if(r===null){t+=e.slice(n);break}t+=e.slice(n,r.end),n=r.end;continue}if(r===`,`){let t=n+1;for(;t<e.length&&/\s/.test(e[t]);)t+=1;let r=e[t];if(r===`}`||r===`]`){n+=1;continue}}t+=r,n+=1}return t}function Jm(e){let t;try{t=JSON.parse(qm(e))}catch{return null}let n=X(t);if(n===null)return null;let r={},i=X(n.headers);if(i!==null)for(let[e,t]of Object.entries(i))typeof t==`string`&&(r[e]=t);return{method:typeof n.method==`string`?n.method.toUpperCase():`GET`,headers:r,body:typeof n.body==`string`?n.body:null}}function Ym(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function Xm(e,t){let n=Ym(e,t);return n===void 0?void 0:e[n]}function Zm(e,t){if(e===void 0)return null;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e!==-1&&n.slice(0,e).trim()===t)return n.slice(e+1).trim()}return null}function Qm(e){let t=new Map;for(let n of e){let e=Ym(n.headers,`cookie`);if(e===void 0)continue;let r=$m(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if(Ym(e.headers,`cookie`)!==void 0)return e;let n=$m(e.url),r=n===``?void 0:t.get(n);return r===void 0?e:{...e,headers:{...e.headers,[r.key]:r.value}}})}function $m(e){try{return new URL(e).hostname.toLowerCase()}catch{return``}}function eh(e,t){let n=Gm(e,Wm(e,t));if(n===null)return null;let r=n.value,i=Wm(e,n.end);if(e[i]!==`,`)return{url:r,method:`GET`,headers:{},body:null};let a=Km(e,Wm(e,i+1));if(a===null)return{url:r,method:`GET`,headers:{},body:null};let o=Jm(a.raw);if(o===null)throw Error(`无法解析 fetch 的 options 对象(可能复制不完整,请重新复制完整的 fetch 调用)`);return{url:r,method:o.method,headers:o.headers,body:o.body}}function th(e){let t=[],n=/\bfetch\s*\(/g,r;for(;(r=n.exec(e))!==null;){let n=eh(e,r.index+r[0].length);n!==null&&t.push(n)}return Qm(t)}function nh(e){return e.some(e=>Ym(e.headers,`cookie`)!==void 0)}var rh=0xe8d4a51000,ih=3e4;function ah(e){let t={...e};for(let e of Object.keys(t)){let n=e.toLowerCase();(n===`content-length`||n===`host`||n===`connection`)&&delete t[e]}return t}async function oh(e,t){let n=await fetch(e,{...t,headers:ah(t.headers),signal:AbortSignal.timeout(ih)});if(!n.ok){let e=await n.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,160)).catch(()=>``);throw Error(`HTTP ${String(n.status)}${e===``?``:`: ${e}`}`)}let r=X(await n.json());if(r===null)throw Error(`响应不是 JSON 对象`);return r}function sh(e){return e===null||e<=0?null:Math.round(e<rh?e*1e3:e)}function ch(e){return Math.round(e*100)/100}function lh(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function uh(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function dh(e,t){let n=X(e);if(n===null)return null;let r=Z(n[t.used])??0,i=Z(n[t.cap]),a=t.exceeded!==void 0&&n[t.exceeded]===!0||i!==null&&r>=i;return{used:r,cap:i,resetAt:t.resetAt===void 0?null:sh(Z(n[t.resetAt])),exceeded:a}}var fh=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await oh(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await oh(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},ph=`https://api.commandcode.ai`,mh=`/alpha/billing/credits`,hh=`/alpha/usage/summary`,gh=`/alpha/billing/subscriptions`,_h={"individual-pro-v1":80,"individual-goat":70},vh=/^user_[A-Za-z0-9_-]+$/,yh={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function bh(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:lh(t)}]}function xh(e){let t=Um(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var Sh=class extends fh{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=vh;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!vh.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super(ph,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(hh),this.get(mh),this.get(gh).catch(()=>null)]),r=X(t.windowLimits),i=X(t.credits),a=n===null?null:X(n.data),o=a===null?null:Um(a.planId),s=o===null?null:_h[o]??null,c=i===null?null:Z(i.monthlyCredits),l=s===null||c===null?null:{used:ch(Math.max(0,s-c)),cap:s,resetAt:a===null?null:xh(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:dh(r.fiveHour,yh),weekly:r===null?null:dh(r.weekly,yh),monthly:l,totalTokens:Z(e.totalTokens),totalRuns:Z(e.totalCount),voucherBalance:null,balance:null,extraStats:bh(l,c)}}},Ch=`platform.deepseek.com`,wh=`/api/v0/users/get_user_summary`,Th=`/api/v0/usage/by_api_key/cost`,Eh=`/api/v0/usage/by_api_key/amount`,Dh=86400;function Oh(e){let t=Z(e);if(t!==null)return t;let n=Um(e);if(n!==null&&n.trim()!==``){let e=Number(n);if(Number.isFinite(e))return e}return null}function kh(e){if(e.size===0)return null;if(e.size===1){let[t,n]=[...e.entries()][0];return{amount:n,currency:t}}let t=e.has(`CNY`)?`CNY`:[...e.keys()].sort()[0];return{amount:e.get(t),currency:t}}function Ah(e){let t=new Date,n=-t.getTimezoneOffset()*60,r=new Date(t.getFullYear(),t.getMonth(),t.getDate()+e),i=Math.floor(r.getTime()/1e3);return{start:String(i),end:String(i+Dh),tz:String(n)}}function jh(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){let e=X(n);if(e===null)continue;let r=Oh(e.balance)??Oh(e.amount),i=Um(e.currency);r!==null&&i!==null&&i!==``&&t.set(i,(t.get(i)??0)+r)}return t}var Mh=class extends fh{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static hosts=[Ch];static apiHosts=[`api.deepseek.com`];static credentialSource=`fetchText`;constructor(e){let t=th(e).find(e=>$m(e.url)===Ch);if(t===void 0)throw Error(`未找到 DeepSeek 平台请求:请在已登录的 DeepSeek 开放平台(platform.deepseek.com)的用量页面里复制接口请求的 fetch 调用粘贴进来`);if(Xm(t.headers,`cookie`)===void 0&&Xm(t.headers,`authorization`)===void 0)throw Error(`复制的请求里没有登录凭据(cookie 或 authorization 头)——请在用量页的 Network 面板里右键 /api/v0/ 开头的接口请求 → 复制 → 以 fetch (Node.js) 格式复制(该格式自带凭据),而不是复制浏览器地址栏的页面请求`);super(new URL(t.url).origin,t.headers)}envelope(e){let t=e.code;if(typeof t==`number`&&t!==0){let n=Um(e.msg)??``;throw Error(`上游业务错误 ${String(t)}${n===``?``:`: ${n}`}(多为登录凭据失效,请在用量页重新复制接口请求)`)}let n=X(e.data);if(n===null)throw Error(`响应缺少 data 字段`);return n}async#e(e){let t=Ah(e);try{let e=X((await this.get(Th,`start=${t.start}&end=${t.end}&tz=${t.tz}`)).biz_data),n=e===null?null:e.data;if(!Array.isArray(n))return null;let r=new Map;for(let e of n){let t=X(e),n=t===null?null:Um(t.currency);if(t===null||n===null||n===``)continue;let i=t.series;if(Array.isArray(i))for(let e of i){let t=X(e),i=t===null?null:t.buckets;if(Array.isArray(i))for(let e of i){let t=X(e),i=t===null?null:Oh(t.cost);i!==null&&r.set(n,(r.get(n)??0)+i)}}}let i=kh(r);return i===null?null:{cost:ch(i.amount),currency:i.currency}}catch{return null}}async#t(e){let t=Ah(e);try{let e=X((await this.get(Eh,`start=${t.start}&end=${t.end}&tz=${t.tz}`)).biz_data),n=e===null?null:e.series;if(!Array.isArray(n))return null;let r=0;for(let e of n){let t=X(e),n=t===null?null:t.buckets;if(Array.isArray(n))for(let e of n){let t=X(e),n=t===null?null:X(t.usage),i=n===null?null:Oh(n.REQUEST);i!==null&&(r+=i)}}return r}catch{return null}}#n(e,t){return e===null&&t===null?null:{cost:e===null?null:e.cost,currency:e===null?null:e.currency,requests:t}}async fetchQuota(){let[e,t,n,r,i]=await Promise.all([this.get(wh).catch(()=>null),this.#e(0),this.#e(-1),this.#t(0),this.#t(-1)]),a=null,o=null,s=null;if(e!==null){let t=X(e.biz_data);if(t!==null){let e=kh(jh(t.normal_wallets));e!==null&&(a=ch(e.amount));let n=kh(jh(t.total_costs));n!==null&&(o=ch(n.amount),s=n.currency)}}let c=this.#n(t,r),l=this.#n(n,i);if(a===null&&o===null&&c===null&&l===null)throw Error(`上游未返回任何额度数据(该账号可能未登录,或平台接口已变更)`);return{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:a,totalCost:o,totalCostCurrency:s,today:c,yesterday:l}}},Nh=`/api/user/self`,Ph=`/api/user/subscription/current_cycle`,Fh={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function Ih(e,t){let n=e.usage_infos;if(!Array.isArray(n))return null;for(let e of n){let n=X(e);if(n!==null&&n.key===t)return n}return null}function Lh(e){return e===null||Z(e.total_count)===null?null:dh(e,Fh)}function Rh(e){let t=X(e.account_info),n=t===null?null:t.vouchers;if(!Array.isArray(n))return null;let r=0,i=!1;for(let e of n){let t=X(e),n=t===null?null:Z(t.available);n!==null&&(r+=n,i=!0)}return i?r/1e6:null}function zh(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var Bh=class extends fh{static vendorId=`sense-audio`;static vendorLabel=`SenseAudio`;static hosts=[`platform.senseaudio.cn`];static apiHosts=[`api.senseaudio.cn`];static credentialSource=`fetchText`;constructor(e){let t=th(e),n=zh(t,Nh),r=zh(t,Ph);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>Xm(e.headers,`authorization`)!==void 0))throw Error(`复制的请求里没有 authorization 头(登录凭据在它里面)——请从已登录的 senseaudio.cn 页面重新复制 fetch 调用`);let i=n??r;super(new URL(i.url).origin,i.headers)}async fetchQuota(){let[e,t]=await Promise.all([this.get(Nh),this.get(Ph).catch(()=>null)]),n=Lh(Ih(e,`credit_5h_limit`)),r=Lh(Ih(e,`credit_7d_limit`)),i=Lh(Ih(e,`credit_30d_limit`));if(i===null&&t!==null){let e=Z(t.plan_points),n=Z(t.plan_point_remains);e!==null&&n!==null&&(i={used:e-n,cap:e,resetAt:sh(Z(t.plan_points_reset_at)),exceeded:e-n>=e})}if(n===null&&r===null&&i===null)throw Error(`上游未返回任何额度窗口(该账号可能尚未登录或未订阅套餐)`);return{fiveHour:n,weekly:r,monthly:i,totalTokens:null,totalRuns:null,voucherBalance:Rh(e),balance:null}}},Vh=`GetAgentPlanAFPUsage`,Hh=`GetAgentPlanUsageDetails`,Uh=`console.volcengine.com`,Wh=`2024-01-01`,Gh=`cn-beijing`,Kh={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function qh(e){return e.find(e=>e.url.includes(Vh))}function Jh(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??Gh}/${Wh}`:t}function Yh(e){return e.find(e=>$m(e.url)===Uh)}var Xh=class extends fh{static vendorId=`volc-ark`;static vendorLabel=`火山方舟`;static hosts=[`console.volcengine.com`];static apiHosts=[`ark.cn-beijing.volces.com`];static credentialSource=`fetchText`;#e;#t;constructor(e){let t=th(e),n=qh(t)??Yh(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!nh(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==Uh)throw Error(`非方舟控制台域`);r=e.origin,i=Jh(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=Zm(Xm(n.headers,`cookie`),`csrfToken`)??Xm(n.headers,`x-csrf-token`)??null;if(a===null)throw Error(`缺少 CSRF 凭据:请求头需含 x-csrf-token,或 Cookie 里需有 csrfToken (两者都来自已登录的控制台会话,请在登录页面上重新复制)`);super(r,{...n.headers,"x-csrf-token":a}),this.#e=`${i}/${Vh}`,this.#t=`${i}/${Hh}`}envelope(e){let t=X(e.ResponseMetadata),n=t===null?null:X(t.Error);if(n!==null){let e=Um(n.Code)??`Unknown`,t=Um(n.Message)??``;throw Error(`上游业务错误 ${e}${t===``?``:`: ${t}`}(多为 Cookie 或 CSRF 凭据失效,请在控制台重新复制)`)}return e}async fetchQuota(){let e=X((await this.post(this.#e,{})).Result);if(e===null)throw Error(`响应缺少 Result 字段`);let t=dh(e.AFPFiveHour,Kh),n=dh(e.AFPWeekly,Kh),r=dh(e.AFPMonthly,Kh);if(t===null&&n===null&&r===null)throw Error(`上游未返回任何 AFP 窗口(该账号可能尚未订阅 Agent Plan 套餐)`);let i=X(e.AFPMonthly),a=i===null?null:Z(i.SubscribeTime);return{fiveHour:t,weekly:n,monthly:r,totalTokens:await this.#n(a),totalRuns:null,voucherBalance:null,balance:null}}async#n(e){let t=Date.now(),n=e!==null&&e>0?e:t-2592e6;try{let e=X((await this.post(this.#t,{Filter:{StartTime:uh(new Date(n)),EndTime:uh(new Date(t)),ObjectType:1,BillingType:[`WithinPlan`]},QueryInterval:`Day`})).Result),r=e===null?null:e.Details;return Array.isArray(r)?r.reduce((e,t)=>{let n=X(t);return n===null||n.Unit!==`Tokens`?e:e+(Z(n.Usage)??0)},0):null}catch{return null}}},Zh=`/api/biz/account/query-customer-account-report`,Qh=`/api/finance/expenseBill/expenseBillListByDay`,$h=200,eg=`bigmodel_token_production`;function tg(e){let t=Zm(Xm(e.headers,`cookie`),eg);if(t!==null&&t.trim()!==``)return t.trim();let n=Xm(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var ng=class extends fh{static vendorId=`zhipu-bigmodel`;static vendorLabel=`智谱 BigModel`;static hosts=[`bigmodel.cn`];static apiHosts=[`open.bigmodel.cn`];static credentialSource=`fetchText`;constructor(e){let t=th(e);if(t.length===0)throw Error(`未找到可用的智谱请求:请在已登录的 bigmodel.cn(财务中心 / 资源包 / 任意控制台页面)里复制任意请求的 fetch 调用粘贴进来,额度端点会自动换算`);let n=t[0],r;try{r=new URL(n.url).origin}catch{throw Error(`粘贴的请求 URL 不是绝对地址,无法换算出额度接口——请粘贴浏览器里完整的 fetch(https://…)`)}let i=tg(n);if(i===null)throw Error(`复制的请求里没有登录凭据(需要 Cookie 里的 bigmodel_token_production,或显式的 authorization 头)——请从已登录的 bigmodel.cn 页面用「以 fetch (Node.js) 格式复制」重新复制`);let a={...n.headers,authorization:i.toLowerCase().startsWith(`bearer `)?i:`Bearer ${i}`};super(r,a)}envelope(e){let t=Z(e.code);if(t!==200){let n=Um(e.msg)??`未知错误`;throw Error(`上游业务错误 ${n}(code ${t===null?`未知`:String(t)})——多为登录凭据失效,请在 bigmodel.cn 重新登录后复制`)}return e}async#e(){let e=new Date,t=uh(e).slice(0,7),n=uh(new Date(e.getFullYear(),e.getMonth(),e.getDate()-(e.getDay()+6)%7));try{let e=1,r=0,i=0,a=1/0,o=[];for(;o.length<a;){let s=await this.get(Qh,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String($h)}`),c=s.rows,l=s.total;if(!Array.isArray(c))return null;a=Z(l)??o.length,o=o.concat(c);for(let e of c){let t=X(e);if(t===null)continue;let a=Z(t.originalAmount),o=Um(t.billingDate);a!==null&&o!==null&&(r+=a,o>=n&&(i+=a))}if(e+=1,c.length===0)break}return{weekly:{used:i,cap:null,resetAt:null,exceeded:!1},monthly:{used:r,cap:null,resetAt:null,exceeded:!1}}}catch{return null}}async fetchQuota(){let[e,t]=await Promise.all([this.get(Zh),this.#e()]),n=X(e.data),r=(n===null?null:Z(n.availableBalance))??(n===null?null:Z(n.balance));if(n===null||r===null)throw Error(`响应缺少余额字段(data.availableBalance)`);let i=Z(n.totalSpendAmount);return{fiveHour:null,weekly:t?.weekly??null,monthly:t?.monthly??null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:r,totalCost:i,totalCostCurrency:i===null?null:`CNY`,extraStats:ig(n)}}};function rg(e){return`${lh(e)} 元`}function ig(e){let t=[],n=Z(e.rechargeAmount);n!==null&&t.push({label:`累计充值`,value:rg(n)});let r=Z(e.giveAmount);r!==null&&t.push({label:`赠送金额`,value:rg(r)});let i=Z(e.creditBalance);return i===null?e.creditStatus===`NOT_OPEN`&&t.push({label:`信用余额`,value:`未开通`}):t.push({label:`信用余额`,value:rg(i)}),t}var ag=[Sh,Mh,Bh,Xh,ng];function og(){return ag}function sg(e){let t=new Set;for(let n of th(e)){let e=$m(n.url);e!==``&&t.add(e)}return t}function cg(e){if(e===void 0)return null;let t=$m(e);if(t===``)return null;for(let e of ag)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function lg(e,t){let n=cg(t);if(n===null)throw Error(`该供应商未支持用 API key 自动查询额度(apiBase 未命中已支持的接口域名)`);let r=e.trim();if(r===``)throw Error(`该供应商的 apiKey 为空,无法查询额度——请在供应商配置里填入 API key`);if(n.apiKeyPattern?.test(r)===!1)throw Error(`配置里的 apiKey 不是 ${n.vendorLabel} 的 API key 形态——请检查该供应商配置的 apiKey 字段`);return{vendorId:n.vendorId,vendor:new n(r)}}function ug(e,t){let n=e.trim();for(let e of ag)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(n)===!0)return e;if(t!==void 0){let e=$m(t);if(e!==``){for(let t of ag)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let r=sg(e);for(let e of ag)if(e.credentialSource===`fetchText`&&e.hosts?.some(e=>r.has(e))===!0)return e;return null}function dg(e,t){if(e.trim()===``)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);let n=ug(e,t);if(n===null){let e=ag.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=ag.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=cg(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:n.vendorId,vendor:new n(e)}}var fg=It(`quota.json`);function pg(e){let t=X(e);if(t===null)return null;let n=t.used;if(typeof n!=`number`||!Number.isFinite(n))return null;let r=t.cap,i=t.resetAt;return{used:n,cap:typeof r==`number`&&Number.isFinite(r)?r:null,resetAt:typeof i==`number`&&Number.isFinite(i)?i:null,exceeded:t.exceeded===!0}}function mg(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null}function hg(e){let t=X(e);if(t===null)return null;let n=mg(t.cost),r=mg(t.requests);if(n===null&&r===null)return null;let i=t.currency;return{cost:n,currency:typeof i==`string`&&i!==``?i:null,requests:r}}function gg(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){let e=X(n);if(e===null)continue;let r=e.label,i=e.value;typeof r==`string`&&r!==``&&typeof i==`string`&&i!==``&&t.push({label:r,value:i})}return t.length>0?t:null}function _g(e){let t=X(e);if(t===null)return null;let n=t.totalTokens,r=t.totalRuns,i=t.voucherBalance,a=t.balance,o=t.totalCost,s=t.totalCostCurrency;return{fiveHour:pg(t.fiveHour),weekly:pg(t.weekly),monthly:pg(t.monthly),totalTokens:typeof n==`number`&&Number.isFinite(n)?n:null,totalRuns:typeof r==`number`&&Number.isFinite(r)?r:null,voucherBalance:typeof i==`number`&&Number.isFinite(i)?i:null,balance:typeof a==`number`&&Number.isFinite(a)?a:null,totalCost:mg(o),totalCostCurrency:typeof s==`string`&&s!==``?s:null,today:hg(t.today),yesterday:hg(t.yesterday),extraStats:gg(t.extraStats)}}function vg(e){let t=X(fg.get(e));if(t===null)return null;let n=t.fetchText,r=t.vendorId,i=t.fetchedAt,a=t.error;return{fetchText:typeof n==`string`&&n.trim()!==``?n:void 0,vendorId:typeof r==`string`?r:void 0,snapshot:_g(t.snapshot)??void 0,fetchedAt:typeof i==`number`&&Number.isFinite(i)?i:void 0,error:typeof a==`string`&&a!==``?a:void 0}}function yg(e,t){fg.set(e,t)}function bg(e){fg.get(e)!==void 0&&fg.set(e,void 0)}function xg(){let e=fg.getAll(),t={};for(let n of Object.keys(e)){let e=vg(n);e!==null&&(t[n]=e)}return t}function Sg(e,t,n,r){yg(e,{fetchText:vg(e)?.fetchText,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function Cg(e,t){let n=vg(e);if(n===null){yg(e,{error:t});return}yg(e,{...n,error:t})}var wg=!1;function Tg(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function Eg(e){if(!e.startsWith(`os.environ/`))return e;let t=process.env[e.slice(11)];return t===void 0||t===``?void 0:t}function Dg(e){let t=typeof e==`object`&&e?e:{},n=typeof t.apiBase==`string`&&t.apiBase.trim()!==``?t.apiBase:void 0,r=typeof t.apiKey==`string`&&t.apiKey.trim()!==``?t.apiKey:void 0;return{apiBase:n,apiKey:r===void 0?void 0:Eg(r)}}function Og(){try{let e=hu();if(e===null||!Array.isArray(e.providers))return null;let t=new Map;for(let n of e.providers){let e=typeof n==`object`&&n?n.name:void 0;typeof e==`string`&&e!==``&&t.set(e,Dg(n))}return t}catch{return null}}function kg(e){return Og()?.get(e)??null}async function Ag(e){try{let t=kg(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(cg(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=lg(t.apiKey,t.apiBase))}else{let i=vg(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=dg(i,t.apiBase))}let i=await r.fetchQuota();Sg(e,n,i,Date.now())}catch(t){Cg(e,Tg(t))}return vg(e)}function jg(){let e=Og();return e===null?null:new Set(e.keys())}async function Mg(){if(!wg){wg=!0;try{let e=Og(),t=e===null?[]:[...e.entries()].filter(([,e])=>cg(e.apiBase)!==null).map(([e])=>e);for(let e of t)await Ag(e);let n=jg();for(let[e,r]of Object.entries(xg()))if(r.fetchText!==void 0){if(n!==null&&!n.has(e)){bg(e);continue}t.includes(e)||await Ag(e)}}catch(e){B(`[quota] 刷新失败:`,Tg(e))}finally{wg=!1}}}async function Ng(e){let t=(await tm(e))?.fetchText;return typeof t==`string`?t:null}function Pg(){return og().map(e=>({vendorId:e.vendorId,vendorLabel:e.vendorLabel,hosts:e.hosts??[],apiHosts:e.apiHosts??[],credentialSource:e.credentialSource}))}function Fg(){let e=new $n;return e.get(`/`,e=>e.json({ok:!0,vendors:Pg(),providers:xg()})),e.get(`/vendors`,e=>e.json({ok:!0,vendors:Pg()})),e.put(`/:provider`,async e=>{let t=e.req.param(`provider`);if(cg(kg(t)?.apiBase)!==null)return e.json({ok:!1,error:`该供应商自动使用配置里的 apiKey 查询额度,无需手动配置`},400);let n=await Ng(e);if(n===null)return e.json({ok:!1,error:`请求体需为 {"fetchText": "..."}`},400);let r=vg(t);yg(t,{fetchText:n,vendorId:r?.vendorId,snapshot:r?.snapshot,fetchedAt:r?.fetchedAt,error:void 0});let i=await Ag(t);return e.json({ok:!0,entry:i})}),e.delete(`/:provider`,e=>(bg(e.req.param(`provider`)),e.json({ok:!0}))),e.post(`/:provider/refresh`,async e=>{let t=await Ag(e.req.param(`provider`));return e.json({ok:!0,entry:t})}),e}function Ig(e,t){let n=new $n;return n.get(`/`,n=>n.json({listenPort:Yp(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},masterKeySet:wu()!==``})),n}var Lg=864e5,Rg=3e5,zg=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,Bg=new Map;try{let e=p(vt(),`utf-8`),t=JSON.parse(e);for(let[e,n]of Object.entries(t)){let{_ts:t,...r}=n;Bg.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function Vg(){try{let e={};for(let[t,{value:n,at:r}]of Bg)e[t]={...n,_ts:r};b(vt(),JSON.stringify(e))}catch(e){B(`保存 IP 缓存失败:`,e.message)}}function Hg(e){let t=Bg.get(e);if(!t)return null;let n=t.value.error===void 0?Lg:Rg;return Date.now()-t.at>=n?(Bg.delete(e),null):t.value}async function Ug(e){let t=Hg(e);if(t)return t;let n=await(await fetch(zg.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(n.status!==`success`){let t={error:n.message||`查询失败`};return Bg.set(e,{value:t,at:Date.now()}),t}let r={country:n.country,region:n.regionName,city:n.city,isp:n.isp};return Bg.set(e,{value:r,at:Date.now()}),Vg(),r}function Wg(e){return{model:e.model,sessionId:e.sessionId,noSession:e.noSession===`1`||void 0,startDate:e.startDate||e.date,endDate:e.endDate||e.date,status:e.status,pathGroup:e.pathGroup,keyword:e.keyword}}function Gg(){let e=new $n;return e.onError(sm),e.get(`/dates`,e=>{let t=cp();return e.json({dates:t})}),e.get(`/ipinfo`,async e=>{let t=e.req.query(`ip`)||``;if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return e.json({error:`invalid ip`},400);try{let n=await Ug(t);return e.json({ip:t,...n})}catch(e){throw new om(502,e.message)}}),e.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=Jf(t);return n||=(await Ep(),Jf(t)??nd(Number(t))),n?e.json(n):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),e.get(`/`,cm(async e=>{let t=e.req.query(),n=op({...Wg(t),sort:t.sort,order:t.order,page:t.page,pageSize:t.pageSize}),r=(t.keyword??``).trim();return r.length>=2&&n.total===0&&(n=pp({...Wg(t),keyword:r,sort:t.sort,order:t.order,page:t.page,pageSize:t.pageSize})),e.json(n)})),e.get(`/sessions`,cm(e=>{let t=e.req.query(),n=dp({...Wg(t),page:t.page,pageSize:t.pageSize});return e.json(n)})),e.post(`/clear`,cm(async e=>{await Op();let t=Qu().length;t>0&&dt(`[logs] 清空前 spool 仍有 ${String(t)} 条未入库,这些记录可能在入库后重现`);let n=e.req.query(),r=hp(Wg(n));return z(`[logs] 已清理筛选日志 ${r} 条(筛选: ${JSON.stringify(n)})`),e.json({deleted:r})})),e}var Kg=L(((e,t)=>{var n=R(`child_process`).spawn;function r(e,t,r,i){typeof r==`function`&&(i=r,r=void 0);let a=!1,o=n(e,t,r),s=``,c=``;o.stdout.on(`data`,function(e){s+=e.toString()}),o.stderr.on(`data`,function(e){c+=e.toString()}),o.on(`error`,function(e){a||(a=!0,i(Error(e)))}),o.on(`close`,function(e,t){if(!a){if(a=!0,c)return i(Error(c));i(null,s,e)}})}t.exports=r})),qg=L(((e,t)=>{var n=6e4,r={},i={},a={},o=0,s=null;function c(e,t){if(!(t<=0))return i[e]!==void 0&&(r[e]=Date.now()+(t||n)),i[e]}function l(e,t,s,c){t===void 0||s<=0||(r[e]=Date.now()+(s||n),i[e]===void 0&&(o++,u(s)),i[e]=t,c&&(a[e]=c))}function u(e){if(o>0){s===null&&(s=setInterval(d,(e||n)/2),typeof s.unref==`function`&&s.unref());return}s!==null&&(clearInterval(s),s=null)}function d(){let e=Date.now(),t=Object.keys(r);for(let n=0;n<t.length;n++){let s=t[n];r[s]<e&&(o--,a[s]&&a[s](i[s]),delete i[s],delete r[s],delete a[s])}u()}function f(e){for(let t in e)delete e[t]}function p(){s!==null&&(clearInterval(s),s=null),f(i),f(r),f(a)}t.exports={get:c,set:l,clear:p}})),Jg=L(((e,t)=>{var n=R(`os`),r=Kg(),i=qg(),a=n.platform();function o(e,t){let n=0,r=e.split(/-|:|\./),i=r.length-1;return i>=0&&t&&a===`darwin`&&(n+=parseInt(r[i--],10)*10),i>=0&&(n+=parseInt(r[i--],10)*1e3),i>=0&&(n+=parseInt(r[i--],10)*6e4),i>=0&&(n+=parseInt(r[i--],10)*36e5),i>=0&&(n+=parseInt(r[i--],10)*864e5),n}function s(e,t,s){let c=e.join(`,`),l=[`-o`,`etime,pid,ppid,pcpu,rss,time`,`-p`,c];(a===`aix`||a===`os400`)&&(l=[`-o`,`etime,pid,ppid,pcpu,rssize,time`,`-p`,c]),r(`ps`,l,function(e,r,c){if(e)return a===`os390`&&/no matching processes found/.test(e)&&(e=Error(`No matching pid found`),e.code=`ENOENT`),s(e);if(c===1){let e=Error(`No matching pid found`);return e.code=`ENOENT`,s(e)}if(c!==0)return s(Error(`pidusage ps command exited with code `+c));let l=Date.now();r=r.split(n.EOL);let u={};for(let e=1;e<r.length;e++){let n=r[e].trim().split(/\s+/);if(!n||n.length!==6)continue;let a=parseInt(n[1],10),s=i.get(a,t.maxage);s===void 0&&(s={});let c=parseInt(n[2],10),d=parseInt(n[4],10)*1024,f=o(n[0]),p=o(n[5],!0),m=p-(s.ctime||0),h=Math.abs(s.elapsed===void 0?f:f-s.elapsed);u[a]={cpu:h>0?m/h*100:0,memory:d,ppid:c,pid:a,ctime:p,elapsed:f,timestamp:l},i.set(a,u[a],t.maxage)}s(null,u)})}t.exports=s})),Yg=L(((e,t)=>{function n(e,t,n){typeof t==`function`&&(n=t,t={});let r;Array.isArray(e)||(r=Object.keys(e));let i=r?r.length:e.length,a=i,o=r?{}:[];function s(e,r,s){o[e]=s,(--a===0||r&&!t.graceful)&&(t.graceful&&r&&i>1&&(r=null),n&&n(r,o),n=null)}r?r.forEach(function(t){e[t](function(e,n){s(t,e,n)})}):e.forEach(function(e,t){e(function(e,n){s(t,e,n)})})}t.exports=n})),Xg=L(((e,t)=>{var n=R(`os`),r=R(`fs`),i=R(`child_process`).exec,a=Yg();function o(e,t){if(e!==null){s(function(n,r){if(n)return t(n);e.uptime=r,t(null,e)});return}a([c,s],function(n,r){if(n)return t(n);e={clockTick:r[0].clockTick,pageSize:r[0].pageSize,uptime:r[1]},t(null,e)})}t.exports=o;function s(e){r.readFile(`/proc/uptime`,`utf8`,function(t,r){return t||r===void 0?(process.env.PIDUSAGE_SILENT||console.warn(`[pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value`),e(null,n.uptime()||new Date/1e3)):e(null,parseFloat(r.split(` `)[0]))})}function c(e){a([function(e){l(`CLK_TCK`,{default:100},e)},function(e){l(`PAGESIZE`,{default:4096},e)}],function(t,n){if(t)return e(t);e(null,{clockTick:n[0],pageSize:n[1]})})}function l(e,t,n){typeof t==`function`&&(n=t,t={default:``}),i(`getconf `+e,function(r,i,a){return r===null?(i=parseInt(i),isNaN(i)?n(null,t.default):n(null,i)):(process.env.PIDUSAGE_SILENT||console.error(`Error while calling "getconf `+e+`"`,r),n(null,t.default))})}})),Zg=L(((e,t)=>{var n=R(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),Qg=L(((e,t)=>{var n=R(`fs`),r=R(`path`),i=Xg(),a=Yg(),o=qg(),s=null,c=Zg().Buffer,l=1024;function u(){}function d(e,t,r){if(t.fd)return r(null,t.fd);n.open(e,`r`,r)}function f(e){e.fd&&n.close(e.fd,u)}function p(e,t,r){let i=!1;typeof t==`function`&&(r=t,t=c.alloc(l),i=!0),n.read(e,t,0,l,0,function(n,a,o){if(n){r(n);return}let s=c.concat([t,o],i?a:t.length+a);if(a===l){p(e,s,r);return}r(null,t)})}function m(e,t,n){let i=o.get(e,t.maxage),a=!1;i===void 0&&(a=!0,i={}),d(r.join(`/proc`,``+e,`stat`),i,function(r,c){if(r)return r.code===`ENOENT`&&(r.message=`No matching pid found`),n(r,null);if(r)return n(r);p(c,function(r,l){if(r)return n(r);let u=l.toString(`utf8`),d=Date.now(),p=u.lastIndexOf(`)`);u=u.substr(p+2).split(` `);let h={ppid:parseInt(u[1]),utime:parseFloat(u[11])*1e3/s.clockTick,stime:parseFloat(u[12])*1e3/s.clockTick,cutime:parseFloat(u[13])*1e3/s.clockTick,cstime:parseFloat(u[14])*1e3/s.clockTick,start:parseFloat(u[19])*1e3/s.clockTick,rss:parseFloat(u[21]),uptime:s.uptime*1e3,fd:c},g=h.rss*s.pageSize,_=t.childrens?h.cutime+h.cstime:0,v=h.stime-(i.stime||0)+h.utime-(i.utime||0)+_,y=Math.abs(i.uptime===void 0?h.start-h.uptime:h.uptime-i.uptime),b=y>0?v/y*100:0;return o.set(e,h,t.maxage,f),a?m(e,t,n):n(null,{cpu:b,memory:g,ctime:h.utime+h.stime,elapsed:h.uptime-h.start,timestamp:d,pid:e,ppid:h.ppid})})})}function h(e,t,n){i(s,function(r,i){if(r)return n(r);s=i;let o={};e.forEach(function(e,n){o[e]=function(n){m(e,t,n)}}),a(o,{graceful:!0},n)})}t.exports=h})),$g=L(((e,t)=>{var n=R(`os`),r=Kg(),i=qg();function a(e){let t=e.substring(0,4),n=e.substring(4,6),r=e.substring(6,8),i=e.substring(8,10),a=e.substring(10,12),o=e.substring(12,14),s=e.substring(15,21),c=e.substring(21,22),l=parseInt(e.substring(22,25),10),u=Math.floor(l/60),d=l%60;return new Date(t+`-`+n+`-`+r+`T`+i+`:`+a+`:`+o+`.`+s+c+(u>9?u:`0`+u)+(d>9?d:`0`+d))}function o(e,t,s){let c=`ProcessId=`+e[0];for(let t=1;t<e.length;t++)c+=` or ProcessId=`+e[t];r(`wmic`,[`PROCESS`,`where`,`"`+c+`"`,`get`,`CreationDate,KernelModeTime,ParentProcessId,ProcessId,UserModeTime,WorkingSetSize`],{windowsHide:!0,windowsVerbatimArguments:!0},function(r,c,l){if(r){if(r.message.indexOf(`No Instance(s) Available.`)!==-1){let e=Error(`No matching pid found`);return e.code=`ENOENT`,s(e)}return s(r)}if(l!==0)return s(Error(`pidusage wmic command exited with code `+l));let u=Date.now(),d=Math.floor(n.uptime()||u/1e3);c=c.split(n.EOL);let f=!1,p={};for(let e=1;e<c.length;e++){let n=c[e].trim().split(/\s+/);if(!n||n.length!==6)continue;let r=a(n[0]),o=parseInt(n[2],10),s=parseInt(n[3],10),l=Math.round(parseInt(n[1],10)/1e4),m=Math.round(parseInt(n[4],10)/1e4),h=parseInt(n[5],10),g=i.get(s,t.maxage);g===void 0&&(f=!0,g={ctime:l+m,uptime:d});let _=(l+m-g.ctime)/1e3,v=d-g.uptime,y=v>0?_/v*100:0;i.set(s,{ctime:m+l,uptime:d},t.maxage),p[s]={cpu:y,memory:h,ppid:o,pid:s,ctime:m+l,elapsed:u-r.getTime(),timestamp:u}}if(f)return o(e,t,function(e,t){if(e)return s(e);s(null,Object.assign(p,t))});s(null,p)})}t.exports=o})),e_=L(((e,t)=>{var n=R(`os`),r=Kg(),i=qg();function a(e){let t=e.substring(0,4),n=e.substring(4,6),r=e.substring(6,8),i=e.substring(8,10),a=e.substring(10,12),o=e.substring(12,14),s=e.substring(15,21),c=e.substring(21,22),l=parseInt(e.substring(22,25),10),u=Math.floor(l/60),d=l%60;return new Date(t+`-`+n+`-`+r+`T`+i+`:`+a+`:`+o+`.`+s+c+(u>9?u:`0`+u)+(d>9?d:`0`+d))}function o(e,t,s){let c=`ProcessId=`+e[0];for(let t=1;t<e.length;t++)c+=` or ProcessId=`+e[t];r(`gwmi`,[`win32_process`,`-Filter`,`'`+c+`'`,`| select CreationDate,KernelModeTime,ParentProcessId,ProcessId,UserModeTime,WorkingSetSize`,`| format-table`],{windowsHide:!0,windowsVerbatimArguments:!0,shell:`powershell.exe`},function(r,c,l){if(r){if(r.message.indexOf(`No Instance(s) Available.`)!==-1){let e=Error(`No matching pid found`);return e.code=`ENOENT`,s(e)}return s(r)}if(l!==0)return s(Error(`pidusage gwmi command exited with code `+l));let u=Date.now(),d=Math.floor(n.uptime()||u/1e3);c=c.split(n.EOL).slice(1);let f=c.findIndex(e=>!!e);if(c=c.slice(f+2),!c.length){let e=Error(`No matching pid found`);return e.code=`ENOENT`,s(e)}let p=!1,m={};for(let e=0;e<c.length;e++){let n=c[e].trim().split(/\s+/);if(!n||n.length===1)continue;let r=a(n[0]),o=parseInt(n[2],10),s=parseInt(n[3],10),l=Math.round(parseInt(n[1],10)/1e4),f=Math.round(parseInt(n[4],10)/1e4),h=parseInt(n[5],10),g=i.get(s,t.maxage);g===void 0&&(p=!0,g={ctime:l+f,uptime:d});let _=(l+f-g.ctime)/1e3,v=d-g.uptime,y=v>0?_/v*100:0;i.set(s,{ctime:f+l,uptime:d},t.maxage),m[s]={cpu:y,memory:h,ppid:o,pid:s,ctime:f+l,elapsed:u-r.getTime(),timestamp:u}}if(p)return o(e,t,function(e,t){if(e)return s(e);s(null,Object.assign(m,t))});s(null,m)})}t.exports=o})),t_=L(((e,t)=>{var n=R(`fs`),r=R(`os`),i=R(`child_process`).spawn,a={ps:()=>Jg(),procfile:()=>Qg(),wmic:()=>$g(),gwmi:()=>e_()},o={aix:`ps`,os400:`ps`,android:`procfile`,alpine:`procfile`,darwin:`ps`,freebsd:`ps`,os390:`ps`,linux:`procfile`,netbsd:`procfile`,openbsd:`ps`,sunos:`ps`,win:`wmic`},s=r.platform();n.existsSync(`/etc/alpine-release`)&&(s=`alpine`),s.match(/^win/)&&(s=`win`);var c;try{c=a[o[s]]()}catch{}function l(e,t,n){let o=c;if(s!==`win`&&t.usePs===!0&&(o=a.ps()),s===`win`){let e;try{e=i(`wmic`,function(e){if(e)throw Error(e)})}catch{o=a.gwmi()}finally{e&&e.kill()}}if(o===void 0)return n(Error(r.platform()+` is not supported yet, please open an issue (https://github.com/soyuka/pidusage)`));let l=!1;if(Array.isArray(e)||(l=!0,e=[e]),e.length===0)return n(TypeError(`You must provide at least one pid`));for(let t=0;t<e.length;t++)if(e[t]=parseInt(e[t],10),isNaN(e[t])||e[t]<0)return n(TypeError(`One of the pids provided is invalid`));o(e,t,function(t,r){if(t)return n(t);l?n(null,r[e[0]]):n(null,r)})}t.exports=l})),n_=be(L(((e,t)=>{var n=t_();function r(e,t,r){if(typeof t==`function`&&(r=t,t={}),t===void 0&&(t={}),t=Object.assign({usePs:/^true$/i.test(process.env.PIDUSAGE_USE_PS),maxage:process.env.PIDUSAGE_MAXAGE},t),typeof r==`function`){n(e,t,r);return}return new Promise(function(r,i){n(e,t,function(e,t){if(e)return i(e);r(t)})})}t.exports=r,t.exports.clear=qg().clear}))(),1);function r_(e){return`http://127.0.0.1:${String(e.port)}`}function i_(e){let t=e.port??null;return{role:`main`,pid:e.pid??null,status:e.status??`stopped`,port:t,address:t?`http://127.0.0.1:${String(t)}`:null,startedAt:e.startedAt??null,memory:e.memory??null,cpu:e.cpu??null,restarts:null}}async function a_(e){try{let t=await(0,n_.default)(e);return{memory:t.memory??null,cpu:t.cpu==null?null:Math.round(t.cpu*10)/10}}catch{return{memory:null,cpu:null}}}function o_(e){let t=new $n;return t.get(`/status`,async t=>t.json({ok:!0,running:!0,pid:process.pid,status:`online`,uptime:e.startedAt,gatewayBase:r_(e)})),t.get(`/processes`,async t=>{let n=await a_(process.pid);return t.json({ok:!0,processes:[i_({pid:process.pid,status:`online`,port:e.port,startedAt:e.startedAt,memory:n.memory,cpu:n.cpu})]})}),t}var s_=`ezllm-autostart.vbs`,c_=`ezllm-autostart.cmd`,l_=`com.ezllm.autostart`,u_=`ezllm.service`,d_=`autostart.opt-out`,f_=`ezllm-v2`,p_=`Auto-generated by "ezllm autostart on" (${f_}). Disable with "ezllm autostart off".`,m_=`ELLM_`,h_=new Set([`WEBUI_USERNAME`,`WEBUI_PASSWORD`,`HOST`]);function g_(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(n.startsWith(m_)||h_.has(n))&&(t[n]=r);return t}function __(e){return w(e,d_)}function v_(){let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return w(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)}function y_(){return w(v_(),s_)}function b_(){return w(t(),`Library`,`LaunchAgents`,`${l_}.plist`)}function x_(){return w(t(),`.config`,`systemd`,`user`,u_)}function S_(e,t){return new Promise(n=>{let r=le(e,t,{stdio:`ignore`,shell:!1});r.on(`error`,()=>n(127)),r.on(`exit`,e=>n(e??1))})}var C_={win32:{itemPath:y_,on:I_,off:z_},darwin:{itemPath:b_,on:L_,off:B_},linux:{itemPath:x_,on:R_,off:V_}};function w_(e){return C_[e]??null}function T_(e){let t=w_(e);if(!t)throw Error(`暂不支持的平台: ${e}。`);return t}function E_(){return w_(r())?.itemPath()??null}function D_(e,t){return[e,t.entryJs,...t.args??[]]}function O_(e){return w(e,`logs`,`autostart.log`)}function k_(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function A_(e,t){let n=/["%\r\n]/;if(n.test(e)||n.test(t))throw Error(`环境变量 ${e} 的键/值含 cmd 无法安全转义的字符(" % 或换行),已拒绝写入自启项;请调整该变量后重试 ezllm autostart on`)}function j_(e,t){let n=O_(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${p_}`,...Object.entries(t.env).map(([e,t])=>(A_(e,t),`set "${e}=${t}"`)),`>> "${n}" echo [%date% %time%] autostart launching.`,`${D_(e,t).map(e=>`"${e}"`).join(` `)} >> "${n}" 2>&1`,``].join(`\r
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
`),
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
`)}async function F_(e,t,n=S_){try{b(e,t,`utf16le`);return}catch(r){if(await n(`powershell`,[`-NoProfile`,`-Command`,`$bytes=[Convert]::FromBase64String('${Buffer.from(t,`utf16le`).toString(`base64`)}');[IO.File]::WriteAllBytes('${e.replace(/'/g,`''`)}', $bytes)`])!==0)throw r}}async function I_(e,t){let n=y_(),r=w(t.appDir,c_);return b(r,j_(e,t),`utf-8`),await F_(n,`\uFEFF${M_(r)}`),n}async function L_(e,t){let n=b_();b(n,N_(e,t),`utf-8`),await S_(`launchctl`,[`unload`,n]);let r=await S_(`launchctl`,[`load`,n]);if(r!==0)throw Error(`launchctl load 失败(退出码 ${String(r)})。请手动执行: launchctl load "${n}"`);return n}async function R_(e,t){let n=x_();f(C(n),{recursive:!0}),b(n,P_(e,t),`utf-8`);let r=await S_(`systemctl`,[`--user`,`daemon-reload`]);if(r!==0)throw Error(`systemctl --user daemon-reload 失败(退出码 ${String(r)})。当前环境可能无 systemd(WSL/容器),请手动启用或删除: ${n}`);let i=await S_(`systemctl`,[`--user`,`enable`,u_]);if(i!==0)throw Error(`systemctl --user enable 失败(退出码 ${String(i)})。请手动执行: systemctl --user enable ${u_}`);return n}async function z_(e){let t=y_(),n=d(t);return g(t,{force:!0}),g(w(e,c_),{force:!0}),n}async function B_(){let e=b_();return d(e)?(await S_(`launchctl`,[`unload`,e]),g(e,{force:!0}),!0):!1}async function V_(){let e=x_();return d(e)?(await S_(`systemctl`,[`--user`,`disable`,u_]),g(e,{force:!0}),await S_(`systemctl`,[`--user`,`daemon-reload`]),!0):!1}function H_(e){let t=p(e);return t.length>=2&&t[0]===255&&t[1]===254?t.toString(`utf16le`).slice(1):t.toString(`utf-8`)}function U_(e){let t=E_(),n=!1;if(t&&d(t))try{n=H_(t).includes(f_)}catch{}return{platform:r(),enabled:n,itemPath:t,optOut:d(__(e))}}async function W_(e){let t=T_(r());f(w(e.appDir,`logs`),{recursive:!0});let n=await t.on(e.nodePath,e);return g(__(e.appDir),{force:!0}),{itemPath:n}}async function G_(e){let t=await T_(r()).off(e.appDir);return f(e.appDir,{recursive:!0}),b(__(e.appDir),new Date().toISOString(),`utf-8`),{removed:t}}var K_=L(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`Float64Array`,`BigInt64Array`,`BigUint64Array`];function r(e){return n.includes(e)}var i=[`Function`,`Generator`,`AsyncGenerator`,`GeneratorFunction`,`AsyncGeneratorFunction`,`AsyncFunction`,`Observable`,`Array`,`Buffer`,`Blob`,`Object`,`RegExp`,`Date`,`Error`,`Map`,`Set`,`WeakMap`,`WeakSet`,`ArrayBuffer`,`SharedArrayBuffer`,`DataView`,`Promise`,`URL`,`FormData`,`URLSearchParams`,`HTMLElement`,...n];function a(e){return i.includes(e)}var o=[`null`,`undefined`,`string`,`number`,`bigint`,`boolean`,`symbol`];function s(e){return o.includes(e)}function c(e){return t=>typeof t===e}var{toString:l}=Object.prototype,u=e=>{let t=l.call(e).slice(8,-1);if(/HTML\w+Element/.test(t)&&f.domElement(e))return`HTMLElement`;if(a(t))return t},d=e=>t=>u(t)===e;function f(e){if(e===null)return`null`;switch(typeof e){case`undefined`:return`undefined`;case`string`:return`string`;case`number`:return`number`;case`boolean`:return`boolean`;case`function`:return`Function`;case`bigint`:return`bigint`;case`symbol`:return`symbol`}if(f.observable(e))return`Observable`;if(f.array(e))return`Array`;if(f.buffer(e))return`Buffer`;let t=u(e);if(t)return t;if(e instanceof String||e instanceof Boolean||e instanceof Number)throw TypeError(`Please don't use object wrappers for primitive types`);return`Object`}f.undefined=c(`undefined`),f.string=c(`string`);var p=c(`number`);f.number=e=>p(e)&&!f.nan(e),f.bigint=c(`bigint`),f.function_=c(`function`),f.null_=e=>e===null,f.class_=e=>f.function_(e)&&e.toString().startsWith(`class `),f.boolean=e=>e===!0||e===!1,f.symbol=c(`symbol`),f.numericString=e=>f.string(e)&&!f.emptyStringOrWhitespace(e)&&!Number.isNaN(Number(e)),f.array=(e,t)=>Array.isArray(e)?!f.function_(t)||e.every(t):!1,f.buffer=e=>{var t;return((t=e?.constructor)?.isBuffer)?.call(t,e)??!1},f.blob=e=>d(`Blob`)(e),f.nullOrUndefined=e=>f.null_(e)||f.undefined(e),f.object=e=>!f.null_(e)&&(typeof e==`object`||f.function_(e)),f.iterable=e=>f.function_(e?.[Symbol.iterator]),f.asyncIterable=e=>f.function_(e?.[Symbol.asyncIterator]),f.generator=e=>f.iterable(e)&&f.function_(e?.next)&&f.function_(e?.throw),f.asyncGenerator=e=>f.asyncIterable(e)&&f.function_(e.next)&&f.function_(e.throw),f.nativePromise=e=>d(`Promise`)(e);var m=e=>f.function_(e?.then)&&f.function_(e?.catch);f.promise=e=>f.nativePromise(e)||m(e),f.generatorFunction=d(`GeneratorFunction`),f.asyncGeneratorFunction=e=>u(e)===`AsyncGeneratorFunction`,f.asyncFunction=e=>u(e)===`AsyncFunction`,f.boundFunction=e=>f.function_(e)&&!e.hasOwnProperty(`prototype`),f.regExp=d(`RegExp`),f.date=d(`Date`),f.error=d(`Error`),f.map=e=>d(`Map`)(e),f.set=e=>d(`Set`)(e),f.weakMap=e=>d(`WeakMap`)(e),f.weakSet=e=>d(`WeakSet`)(e),f.int8Array=d(`Int8Array`),f.uint8Array=d(`Uint8Array`),f.uint8ClampedArray=d(`Uint8ClampedArray`),f.int16Array=d(`Int16Array`),f.uint16Array=d(`Uint16Array`),f.int32Array=d(`Int32Array`),f.uint32Array=d(`Uint32Array`),f.float32Array=d(`Float32Array`),f.float64Array=d(`Float64Array`),f.bigInt64Array=d(`BigInt64Array`),f.bigUint64Array=d(`BigUint64Array`),f.arrayBuffer=d(`ArrayBuffer`),f.sharedArrayBuffer=d(`SharedArrayBuffer`),f.dataView=d(`DataView`),f.enumCase=(e,t)=>Object.values(t).includes(e),f.directInstanceOf=(e,t)=>Object.getPrototypeOf(e)===t.prototype,f.urlInstance=e=>d(`URL`)(e),f.urlString=e=>{if(!f.string(e))return!1;try{return new URL(e),!0}catch{return!1}},f.truthy=e=>!!e,f.falsy=e=>!e,f.nan=e=>Number.isNaN(e),f.primitive=e=>f.null_(e)||s(typeof e),f.integer=e=>Number.isInteger(e),f.safeInteger=e=>Number.isSafeInteger(e),f.plainObject=e=>{if(l.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.getPrototypeOf({})},f.typedArray=e=>r(u(e));var h=e=>f.safeInteger(e)&&e>=0;f.arrayLike=e=>!f.nullOrUndefined(e)&&!f.function_(e)&&h(e.length),f.inRange=(e,t)=>{if(f.number(t))return e>=Math.min(0,t)&&e<=Math.max(t,0);if(f.array(t)&&t.length===2)return e>=Math.min(...t)&&e<=Math.max(...t);throw TypeError(`Invalid range: ${JSON.stringify(t)}`)};var g=1,_=[`innerHTML`,`ownerDocument`,`style`,`attributes`,`nodeValue`];f.domElement=e=>f.object(e)&&e.nodeType===g&&f.string(e.nodeName)&&!f.plainObject(e)&&_.every(t=>t in e),f.observable=e=>{var t,n;return e?e===(t=e)[Symbol.observable]?.call(t)||e===(n=e)[`@@observable`]?.call(n):!1},f.nodeStream=e=>f.object(e)&&f.function_(e.pipe)&&!f.observable(e),f.infinite=e=>e===1/0||e===-1/0;var v=e=>t=>f.integer(t)&&Math.abs(t%2)===e;f.evenInteger=v(0),f.oddInteger=v(1),f.emptyArray=e=>f.array(e)&&e.length===0,f.nonEmptyArray=e=>f.array(e)&&e.length>0,f.emptyString=e=>f.string(e)&&e.length===0;var y=e=>f.string(e)&&!/\S/.test(e);f.emptyStringOrWhitespace=e=>f.emptyString(e)||y(e),f.nonEmptyString=e=>f.string(e)&&e.length>0,f.nonEmptyStringAndNotWhitespace=e=>f.string(e)&&!f.emptyStringOrWhitespace(e),f.emptyObject=e=>f.object(e)&&!f.map(e)&&!f.set(e)&&Object.keys(e).length===0,f.nonEmptyObject=e=>f.object(e)&&!f.map(e)&&!f.set(e)&&Object.keys(e).length>0,f.emptySet=e=>f.set(e)&&e.size===0,f.nonEmptySet=e=>f.set(e)&&e.size>0,f.emptyMap=e=>f.map(e)&&e.size===0,f.nonEmptyMap=e=>f.map(e)&&e.size>0,f.propertyKey=e=>f.any([f.string,f.number,f.symbol],e),f.formData=e=>d(`FormData`)(e),f.urlSearchParams=e=>d(`URLSearchParams`)(e);var b=(e,t,n)=>{if(!f.function_(t))throw TypeError(`Invalid predicate: ${JSON.stringify(t)}`);if(n.length===0)throw TypeError(`Invalid number of values`);return e.call(n,t)};f.any=(e,...t)=>(f.array(e)?e:[e]).some(e=>b(Array.prototype.some,e,t)),f.all=(e,...t)=>b(Array.prototype.every,e,t);var x=(e,t,n,r={})=>{if(!e){let{multipleValues:e}=r,i=e?`received values of types ${[...new Set(n.map(e=>`\`${f(e)}\``))].join(`, `)}`:`received value of type \`${f(n)}\``;throw TypeError(`Expected value which is \`${t}\`, ${i}.`)}};e.assert={undefined:e=>x(f.undefined(e),`undefined`,e),string:e=>x(f.string(e),`string`,e),number:e=>x(f.number(e),`number`,e),bigint:e=>x(f.bigint(e),`bigint`,e),function_:e=>x(f.function_(e),`Function`,e),null_:e=>x(f.null_(e),`null`,e),class_:e=>x(f.class_(e),`Class`,e),boolean:e=>x(f.boolean(e),`boolean`,e),symbol:e=>x(f.symbol(e),`symbol`,e),numericString:e=>x(f.numericString(e),`string with a number`,e),array:(e,t)=>{x(f.array(e),`Array`,e),t&&e.forEach(t)},buffer:e=>x(f.buffer(e),`Buffer`,e),blob:e=>x(f.blob(e),`Blob`,e),nullOrUndefined:e=>x(f.nullOrUndefined(e),`null or undefined`,e),object:e=>x(f.object(e),`Object`,e),iterable:e=>x(f.iterable(e),`Iterable`,e),asyncIterable:e=>x(f.asyncIterable(e),`AsyncIterable`,e),generator:e=>x(f.generator(e),`Generator`,e),asyncGenerator:e=>x(f.asyncGenerator(e),`AsyncGenerator`,e),nativePromise:e=>x(f.nativePromise(e),`native Promise`,e),promise:e=>x(f.promise(e),`Promise`,e),generatorFunction:e=>x(f.generatorFunction(e),`GeneratorFunction`,e),asyncGeneratorFunction:e=>x(f.asyncGeneratorFunction(e),`AsyncGeneratorFunction`,e),asyncFunction:e=>x(f.asyncFunction(e),`AsyncFunction`,e),boundFunction:e=>x(f.boundFunction(e),`Function`,e),regExp:e=>x(f.regExp(e),`RegExp`,e),date:e=>x(f.date(e),`Date`,e),error:e=>x(f.error(e),`Error`,e),map:e=>x(f.map(e),`Map`,e),set:e=>x(f.set(e),`Set`,e),weakMap:e=>x(f.weakMap(e),`WeakMap`,e),weakSet:e=>x(f.weakSet(e),`WeakSet`,e),int8Array:e=>x(f.int8Array(e),`Int8Array`,e),uint8Array:e=>x(f.uint8Array(e),`Uint8Array`,e),uint8ClampedArray:e=>x(f.uint8ClampedArray(e),`Uint8ClampedArray`,e),int16Array:e=>x(f.int16Array(e),`Int16Array`,e),uint16Array:e=>x(f.uint16Array(e),`Uint16Array`,e),int32Array:e=>x(f.int32Array(e),`Int32Array`,e),uint32Array:e=>x(f.uint32Array(e),`Uint32Array`,e),float32Array:e=>x(f.float32Array(e),`Float32Array`,e),float64Array:e=>x(f.float64Array(e),`Float64Array`,e),bigInt64Array:e=>x(f.bigInt64Array(e),`BigInt64Array`,e),bigUint64Array:e=>x(f.bigUint64Array(e),`BigUint64Array`,e),arrayBuffer:e=>x(f.arrayBuffer(e),`ArrayBuffer`,e),sharedArrayBuffer:e=>x(f.sharedArrayBuffer(e),`SharedArrayBuffer`,e),dataView:e=>x(f.dataView(e),`DataView`,e),enumCase:(e,t)=>x(f.enumCase(e,t),`EnumCase`,e),urlInstance:e=>x(f.urlInstance(e),`URL`,e),urlString:e=>x(f.urlString(e),`string with a URL`,e),truthy:e=>x(f.truthy(e),`truthy`,e),falsy:e=>x(f.falsy(e),`falsy`,e),nan:e=>x(f.nan(e),`NaN`,e),primitive:e=>x(f.primitive(e),`primitive`,e),integer:e=>x(f.integer(e),`integer`,e),safeInteger:e=>x(f.safeInteger(e),`integer`,e),plainObject:e=>x(f.plainObject(e),`plain object`,e),typedArray:e=>x(f.typedArray(e),`TypedArray`,e),arrayLike:e=>x(f.arrayLike(e),`array-like`,e),domElement:e=>x(f.domElement(e),`HTMLElement`,e),observable:e=>x(f.observable(e),`Observable`,e),nodeStream:e=>x(f.nodeStream(e),`Node.js Stream`,e),infinite:e=>x(f.infinite(e),`infinite number`,e),emptyArray:e=>x(f.emptyArray(e),`empty array`,e),nonEmptyArray:e=>x(f.nonEmptyArray(e),`non-empty array`,e),emptyString:e=>x(f.emptyString(e),`empty string`,e),emptyStringOrWhitespace:e=>x(f.emptyStringOrWhitespace(e),`empty string or whitespace`,e),nonEmptyString:e=>x(f.nonEmptyString(e),`non-empty string`,e),nonEmptyStringAndNotWhitespace:e=>x(f.nonEmptyStringAndNotWhitespace(e),`non-empty string and not whitespace`,e),emptyObject:e=>x(f.emptyObject(e),`empty object`,e),nonEmptyObject:e=>x(f.nonEmptyObject(e),`non-empty object`,e),emptySet:e=>x(f.emptySet(e),`empty set`,e),nonEmptySet:e=>x(f.nonEmptySet(e),`non-empty set`,e),emptyMap:e=>x(f.emptyMap(e),`empty map`,e),nonEmptyMap:e=>x(f.nonEmptyMap(e),`non-empty map`,e),propertyKey:e=>x(f.propertyKey(e),`PropertyKey`,e),formData:e=>x(f.formData(e),`FormData`,e),urlSearchParams:e=>x(f.urlSearchParams(e),`URLSearchParams`,e),evenInteger:e=>x(f.evenInteger(e),`even integer`,e),oddInteger:e=>x(f.oddInteger(e),`odd integer`,e),directInstanceOf:(e,t)=>x(f.directInstanceOf(e,t),`T`,e),inRange:(e,t)=>x(f.inRange(e,t),`in range`,e),any:(e,...t)=>x(f.any(e,...t),`predicate returns truthy for any value`,t,{multipleValues:!0}),all:(e,...t)=>x(f.all(e,...t),`predicate returns truthy for all values`,t,{multipleValues:!0})},Object.defineProperties(f,{class:{value:f.class_},function:{value:f.function_},null:{value:f.null_}}),Object.defineProperties(e.assert,{class:{value:e.assert.class_},function:{value:e.assert.function_},null:{value:e.assert.null_}}),e.default=f,t.exports=f,t.exports.default=f,t.exports.assert=e.assert})),q_=L(((e,t)=>{var n=class extends Error{constructor(e){super(e||`Promise was canceled`),this.name=`CancelError`}get isCanceled(){return!0}},r=class e{static fn(t){return(...n)=>new e((e,r,i)=>{n.push(i),t(...n).then(e,r)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((t,n)=>{this._reject=n;let r=e=>{(!this._isCanceled||!a.shouldReject)&&(this._isPending=!1,t(e))},i=e=>{this._isPending=!1,n(e)},a=e=>{if(!this._isPending)throw Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(e)};return Object.defineProperties(a,{shouldReject:{get:()=>this._rejectOnCancel,set:e=>{this._rejectOnCancel=e}}}),e(r,i,a)})}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(this._isPending&&!this._isCanceled){if(this._isCanceled=!0,this._cancelHandlers.length>0)try{for(let e of this._cancelHandlers)e()}catch(e){this._reject(e);return}this._rejectOnCancel&&this._reject(new n(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(r.prototype,Promise.prototype),t.exports=r,t.exports.CancelError=n})),J_=L(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});function n(e){return e.encrypted}var r=(e,t)=>{let r;r=typeof t==`function`?{connect:t}:t;let i=typeof r.connect==`function`,a=typeof r.secureConnect==`function`,o=typeof r.close==`function`,s=()=>{i&&r.connect(),n(e)&&a&&(e.authorized?r.secureConnect():e.authorizationError||e.once(`secureConnect`,r.secureConnect)),o&&e.once(`close`,r.close)};e.writable&&!e.connecting?s():e.connecting?e.once(`connect`,s):e.destroyed&&o&&r.close(e._hadError)};e.default=r,t.exports=r,t.exports.default=r})),Y_=L(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=J_(),r=R(`util`),i=Number(process.versions.node.split(`.`)[0]),a=e=>{if(e.timings)return e.timings;let t={start:Date.now(),socket:void 0,lookup:void 0,connect:void 0,secureConnect:void 0,upload:void 0,response:void 0,end:void 0,error:void 0,abort:void 0,phases:{wait:void 0,dns:void 0,tcp:void 0,tls:void 0,request:void 0,firstByte:void 0,download:void 0,total:void 0}};e.timings=t;let a=e=>{let n=e.emit.bind(e);e.emit=(r,...i)=>(r===`error`&&(t.error=Date.now(),t.phases.total=t.error-t.start,e.emit=n),n(r,...i))};a(e);let o=()=>{t.abort=Date.now(),(!t.response||i>=13)&&(t.phases.total=Date.now()-t.start)};e.prependOnceListener(`abort`,o);let s=e=>{if(t.socket=Date.now(),t.phases.wait=t.socket-t.start,r.types.isProxy(e))return;let i=()=>{t.lookup=Date.now(),t.phases.dns=t.lookup-t.socket};e.prependOnceListener(`lookup`,i),n.default(e,{connect:()=>{t.connect=Date.now(),t.lookup===void 0&&(e.removeListener(`lookup`,i),t.lookup=t.connect,t.phases.dns=t.lookup-t.socket),t.phases.tcp=t.connect-t.lookup},secureConnect:()=>{t.secureConnect=Date.now(),t.phases.tls=t.secureConnect-t.connect}})};e.socket?s(e.socket):e.prependOnceListener(`socket`,s);let c=()=>{t.upload=Date.now(),t.phases.request=t.upload-(t.secureConnect??t.connect)};return(typeof e.writableFinished==`boolean`?e.writableFinished:e.finished&&e.outputSize===0&&(!e.socket||e.socket.writableLength===0))?c():e.prependOnceListener(`finish`,c),e.prependOnceListener(`response`,e=>{t.response=Date.now(),t.phases.firstByte=t.response-t.upload,e.timings=t,a(e),e.prependOnceListener(`end`,()=>{t.end=Date.now(),t.phases.download=t.end-t.response,t.phases.total=t.end-t.start}),e.prependOnceListener(`aborted`,o)}),t};e.default=a,t.exports=a,t.exports.default=a})),X_=L(((e,t)=>{var{V4MAPPED:n,ADDRCONFIG:r,ALL:i,promises:{Resolver:a},lookup:o}=R(`dns`),{promisify:s}=R(`util`),c=R(`os`),l=Symbol(`cacheableLookupCreateConnection`),u=Symbol(`cacheableLookupInstance`),d=Symbol(`expires`),f=typeof i==`number`,p=e=>{if(!(e&&typeof e.createConnection==`function`))throw Error(`Expected an Agent instance as the first argument`)},m=e=>{for(let t of e)t.family!==6&&(t.address=`::ffff:${t.address}`,t.family=6)},h=()=>{let e=!1,t=!1;for(let n of Object.values(c.networkInterfaces()))for(let r of n)if(!r.internal&&(r.family===`IPv6`?t=!0:e=!0,e&&t))return{has4:e,has6:t};return{has4:e,has6:t}},g=e=>Symbol.iterator in e,_={ttl:!0},v={all:!0},y=class{constructor({cache:e=new Map,maxTtl:t=1/0,fallbackDuration:n=3600,errorTtl:r=.15,resolver:i=new a,lookup:c=o}={}){if(this.maxTtl=t,this.errorTtl=r,this._cache=e,this._resolver=i,this._dnsLookup=s(c),this._resolver instanceof a?(this._resolve4=this._resolver.resolve4.bind(this._resolver),this._resolve6=this._resolver.resolve6.bind(this._resolver)):(this._resolve4=s(this._resolver.resolve4.bind(this._resolver)),this._resolve6=s(this._resolver.resolve6.bind(this._resolver))),this._iface=h(),this._pending={},this._nextRemovalTime=!1,this._hostnamesToFallback=new Set,n<1)this._fallback=!1;else{this._fallback=!0;let e=setInterval(()=>{this._hostnamesToFallback.clear()},n*1e3);e.unref&&e.unref()}this.lookup=this.lookup.bind(this),this.lookupAsync=this.lookupAsync.bind(this)}set servers(e){this.clear(),this._resolver.setServers(e)}get servers(){return this._resolver.getServers()}lookup(e,t,n){if(typeof t==`function`?(n=t,t={}):typeof t==`number`&&(t={family:t}),!n)throw Error(`Callback must be a function.`);this.lookupAsync(e,t).then(e=>{t.all?n(null,e):n(null,e.address,e.family,e.expires,e.ttl)},n)}async lookupAsync(e,t={}){typeof t==`number`&&(t={family:t});let a=await this.query(e);if(t.family===6){let e=a.filter(e=>e.family===6);t.hints&n&&(f&&t.hints&i||e.length===0)?m(a):a=e}else t.family===4&&(a=a.filter(e=>e.family===4));if(t.hints&r){let{_iface:e}=this;a=a.filter(t=>t.family===6?e.has6:e.has4)}if(a.length===0){let t=Error(`cacheableLookup ENOTFOUND ${e}`);throw t.code=`ENOTFOUND`,t.hostname=e,t}return t.all?a:a[0]}async query(e){let t=await this._cache.get(e);if(!t){let n=this._pending[e];if(n)t=await n;else{let n=this.queryAndCache(e);this._pending[e]=n;try{t=await n}finally{delete this._pending[e]}}}return t=t.map(e=>({...e})),t}async _resolve(e){let t=async e=>{try{return await e}catch(e){if(e.code===`ENODATA`||e.code===`ENOTFOUND`)return[];throw e}},[n,r]=await Promise.all([this._resolve4(e,_),this._resolve6(e,_)].map(e=>t(e))),i=0,a=0,o=0,s=Date.now();for(let e of n)e.family=4,e.expires=s+e.ttl*1e3,i=Math.max(i,e.ttl);for(let e of r)e.family=6,e.expires=s+e.ttl*1e3,a=Math.max(a,e.ttl);return o=n.length>0?r.length>0?Math.min(i,a):i:a,{entries:[...n,...r],cacheTtl:o}}async _lookup(e){try{return{entries:await this._dnsLookup(e,{all:!0}),cacheTtl:0}}catch{return{entries:[],cacheTtl:0}}}async _set(e,t,n){if(this.maxTtl>0&&n>0){n=Math.min(n,this.maxTtl)*1e3,t[d]=Date.now()+n;try{await this._cache.set(e,t,n)}catch(e){this.lookupAsync=async()=>{let t=Error(`Cache Error. Please recreate the CacheableLookup instance.`);throw t.cause=e,t}}g(this._cache)&&this._tick(n)}}async queryAndCache(e){if(this._hostnamesToFallback.has(e))return this._dnsLookup(e,v);let t=await this._resolve(e);t.entries.length===0&&this._fallback&&(t=await this._lookup(e),t.entries.length!==0&&this._hostnamesToFallback.add(e));let n=t.entries.length===0?this.errorTtl:t.cacheTtl;return await this._set(e,t.entries,n),t.entries}_tick(e){let t=this._nextRemovalTime;(!t||e<t)&&(clearTimeout(this._removalTimeout),this._nextRemovalTime=e,this._removalTimeout=setTimeout(()=>{this._nextRemovalTime=!1;let e=1/0,t=Date.now();for(let[n,r]of this._cache){let i=r[d];t>=i?this._cache.delete(n):i<e&&(e=i)}e!==1/0&&this._tick(e-t)},e),this._removalTimeout.unref&&this._removalTimeout.unref())}install(e){if(p(e),l in e)throw Error(`CacheableLookup has been already installed`);e[l]=e.createConnection,e[u]=this,e.createConnection=(t,n)=>(`lookup`in t||(t.lookup=this.lookup),e[l](t,n))}uninstall(e){if(p(e),e[l]){if(e[u]!==this)throw Error(`The agent is not owned by this CacheableLookup instance`);e.createConnection=e[l],delete e[l],delete e[u]}}updateInterfaceInfo(){let{_iface:e}=this;this._iface=h(),(e.has4&&!this._iface.has4||e.has6&&!this._iface.has6)&&this._cache.clear()}clear(e){if(e){this._cache.delete(e);return}this._cache.clear()}};t.exports=y,t.exports.default=y})),Z_=L(((e,t)=>{var n=(e,t)=>t.some(t=>t instanceof RegExp?t.test(e):t===e),r=(e,{stripHash:t})=>{let n=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(e);if(!n)throw Error(`Invalid URL: ${e}`);let{type:r,data:i,hash:a}=n.groups,o=r.split(`;`);a=t?``:a;let s=!1;o[o.length-1]===`base64`&&(o.pop(),s=!0);let c=(o.shift()||``).toLowerCase(),l=[...o.map(e=>{let[t,n=``]=e.split(`=`).map(e=>e.trim());return t===`charset`&&(n=n.toLowerCase(),n===`us-ascii`)?``:`${t}${n?`=${n}`:``}`}).filter(Boolean)];return s&&l.push(`base64`),(l.length!==0||c&&c!==`text/plain`)&&l.unshift(c),`data:${l.join(`;`)},${s?i.trim():i}${a?`#${a}`:``}`};t.exports=(e,t)=>{if(t={defaultProtocol:`http:`,normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...t},e=e.trim(),/^data:/i.test(e))return r(e,t);if(/^view-source:/i.test(e))throw Error("`view-source:` is not supported as it is a non-standard protocol");let i=e.startsWith(`//`);(i||!/^\.*\//.test(e))&&(e=e.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,t.defaultProtocol));let a=new URL(e);if(t.forceHttp&&t.forceHttps)throw Error("The `forceHttp` and `forceHttps` options cannot be used together");if(t.forceHttp&&a.protocol===`https:`&&(a.protocol=`http:`),t.forceHttps&&a.protocol===`http:`&&(a.protocol=`https:`),t.stripAuthentication&&(a.username=``,a.password=``),t.stripHash?a.hash=``:t.stripTextFragment&&(a.hash=a.hash.replace(/#?:~:text.*?$/i,``)),a.pathname&&=a.pathname.replace(/(?<!\b(?:[a-z][a-z\d+\-.]{1,50}:))\/{2,}/g,`/`),a.pathname)try{a.pathname=decodeURI(a.pathname)}catch{}if(t.removeDirectoryIndex===!0&&(t.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(t.removeDirectoryIndex)&&t.removeDirectoryIndex.length>0){let e=a.pathname.split(`/`),r=e[e.length-1];n(r,t.removeDirectoryIndex)&&(e=e.slice(0,e.length-1),a.pathname=e.slice(1).join(`/`)+`/`)}if(a.hostname&&(a.hostname=a.hostname.replace(/\.$/,``),t.stripWWW&&/^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(a.hostname)&&(a.hostname=a.hostname.replace(/^www\./,``))),Array.isArray(t.removeQueryParameters))for(let e of[...a.searchParams.keys()])n(e,t.removeQueryParameters)&&a.searchParams.delete(e);t.removeQueryParameters===!0&&(a.search=``),t.sortQueryParameters&&a.searchParams.sort(),t.removeTrailingSlash&&(a.pathname=a.pathname.replace(/\/$/,``));let o=e;return e=a.toString(),!t.removeSingleSlash&&a.pathname===`/`&&!o.endsWith(`/`)&&a.hash===``&&(e=e.replace(/\/$/,``)),(t.removeTrailingSlash||a.pathname===`/`)&&a.hash===``&&t.removeSingleSlash&&(e=e.replace(/\/$/,``)),i&&!t.normalizeProtocol&&(e=e.replace(/^http:\/\//,`//`)),t.stripProtocol&&(e=e.replace(/^(?:https?:)?\/\//,``)),e}})),Q_=L(((e,t)=>{t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){r[t]=e[t]}),r;function r(){for(var t=Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),i=t[t.length-1];return typeof r==`function`&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}})),$_=L(((e,t)=>{var n=Q_();t.exports=n(r),t.exports.strict=n(i),r.proto=r(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return i(this)},configurable:!0})});function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),ev=L(((e,t)=>{var n=$_(),r=function(){},i=global.Bare?queueMicrotask:process.nextTick.bind(process),a=function(e){return e.setHeader&&typeof e.abort==`function`},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},s=function(e,t,c){if(typeof t==`function`)return s(e,null,t);t||={},c=n(c||r);var l=e._writableState,u=e._readableState,d=t.readable||t.readable!==!1&&e.readable,f=t.writable||t.writable!==!1&&e.writable,p=!1,m=function(){e.writable||h()},h=function(){f=!1,d||c.call(e)},g=function(){d=!1,f||c.call(e)},_=function(t){c.call(e,t?Error(`exited with error code: `+t):null)},v=function(t){c.call(e,t)},y=function(){i(b)},b=function(){if(!p&&(d&&!(u&&u.ended&&!u.destroyed)||f&&!(l&&l.ended&&!l.destroyed)))return c.call(e,Error(`premature close`))},x=function(){e.req.on(`finish`,h)};return a(e)?(e.on(`complete`,h),e.on(`abort`,y),e.req?x():e.on(`request`,x)):f&&!l&&(e.on(`end`,m),e.on(`close`,m)),o(e)&&e.on(`exit`,_),e.on(`end`,g),e.on(`finish`,h),t.error!==!1&&e.on(`error`,v),e.on(`close`,y),function(){p=!0,e.removeListener(`complete`,h),e.removeListener(`abort`,y),e.removeListener(`request`,x),e.req&&e.req.removeListener(`finish`,h),e.removeListener(`end`,m),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`exit`,_),e.removeListener(`end`,g),e.removeListener(`error`,v),e.removeListener(`close`,y)}};t.exports=s})),tv=L(((e,t)=>{var n=$_(),r=ev(),i;try{i=R(`fs`)}catch{}var a=function(){},o=typeof process>`u`?!1:/^v?\.0/.test(process.version),s=function(e){return typeof e==`function`},c=function(e){return!o||!i?!1:(e instanceof(i.ReadStream||a)||e instanceof(i.WriteStream||a))&&s(e.close)},l=function(e){return e.setHeader&&s(e.abort)},u=function(e,t,i,o){o=n(o);var u=!1;e.on(`close`,function(){u=!0}),r(e,{readable:t,writable:i},function(e){if(e)return o(e);u=!0,o()});var d=!1;return function(t){if(!u&&!d){if(d=!0,c(e))return e.close(a);if(l(e))return e.abort();if(s(e.destroy))return e.destroy();o(t||Error(`stream was destroyed`))}}},d=function(e){e()},f=function(e,t){return e.pipe(t)};t.exports=function(){var e=Array.prototype.slice.call(arguments),t=s(e[e.length-1]||a)&&e.pop()||a;if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw Error(`pump requires two streams per minimum`);var n,r=e.map(function(i,a){var o=a<e.length-1;return u(i,o,a>0,function(e){n||=e,e&&r.forEach(d),!o&&(r.forEach(d),t(n))})});return e.reduce(f)}})),nv=L(((e,t)=>{var{PassThrough:n}=R(`stream`);t.exports=e=>{e={...e};let{array:t}=e,{encoding:r}=e,i=r===`buffer`,a=!1;t?a=!(r||i):r||=`utf8`,i&&(r=null);let o=new n({objectMode:a});r&&o.setEncoding(r);let s=0,c=[];return o.on(`data`,e=>{c.push(e),a?s=c.length:s+=e.length}),o.getBufferedValue=()=>t?c:i?Buffer.concat(c,s):c.join(``),o.getBufferedLength=()=>s,o}})),rv=L(((e,t)=>{var{constants:n}=R(`buffer`),r=tv(),i=nv(),a=class extends Error{constructor(){super(`maxBuffer exceeded`),this.name=`MaxBufferError`}};async function o(e,t){if(!e)return Promise.reject(Error(`Expected a stream`));t={maxBuffer:1/0,...t};let{maxBuffer:o}=t,s;return await new Promise((c,l)=>{let u=e=>{e&&s.getBufferedLength()<=n.MAX_LENGTH&&(e.bufferedData=s.getBufferedValue()),l(e)};s=r(e,i(t),e=>{if(e){u(e);return}c()}),s.on(`data`,()=>{s.getBufferedLength()>o&&u(new a)})}),s.getBufferedValue()}t.exports=o,t.exports.default=o,t.exports.buffer=(e,t)=>o(e,{...t,encoding:`buffer`}),t.exports.array=(e,t)=>o(e,{...t,array:!0}),t.exports.MaxBufferError=a})),iv=L(((e,t)=>{var n=new Set([200,203,204,206,300,301,308,404,405,410,414,501]),r=new Set([200,203,204,300,301,302,303,307,308,404,405,410,414,501]),i=new Set([500,502,503,504]),a={date:!0,connection:!0,"keep-alive":!0,"proxy-authenticate":!0,"proxy-authorization":!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0},o={"content-length":!0,"content-encoding":!0,"transfer-encoding":!0,"content-range":!0};function s(e){let t=parseInt(e,10);return isFinite(t)?t:0}function c(e){return!e||i.has(e.status)}function l(e){let t={};if(!e)return t;let n=e.trim().split(/,/);for(let e of n){let[n,r]=e.split(/=/,2);t[n.trim()]=r===void 0||r.trim().replace(/^"|"$/g,``)}return t}function u(e){let t=[];for(let n in e){let r=e[n];t.push(r===!0?n:n+`=`+r)}if(t.length)return t.join(`, `)}t.exports=class{constructor(e,t,{shared:n,cacheHeuristic:r,immutableMinTimeToLive:i,ignoreCargoCult:a,_fromObject:o}={}){if(o){this._fromObject(o);return}if(!t||!t.headers)throw Error(`Response headers missing`);this._assertRequestHasHeaders(e),this._responseTime=this.now(),this._isShared=n!==!1,this._ignoreCargoCult=!!a,this._cacheHeuristic=r===void 0?.1:r,this._immutableMinTtl=i===void 0?864e5:i,this._status=`status`in t?t.status:200,this._resHeaders=t.headers,this._rescc=l(t.headers[`cache-control`]),this._method=`method`in e?e.method:`GET`,this._url=e.url,this._host=e.headers.host,this._noAuthorization=!e.headers.authorization,this._reqHeaders=t.headers.vary?e.headers:null,this._reqcc=l(e.headers[`cache-control`]),this._ignoreCargoCult&&`pre-check`in this._rescc&&`post-check`in this._rescc&&(delete this._rescc[`pre-check`],delete this._rescc[`post-check`],delete this._rescc[`no-cache`],delete this._rescc[`no-store`],delete this._rescc[`must-revalidate`],this._resHeaders=Object.assign({},this._resHeaders,{"cache-control":u(this._rescc)}),delete this._resHeaders.expires,delete this._resHeaders.pragma),t.headers[`cache-control`]==null&&/no-cache/.test(t.headers.pragma)&&(this._rescc[`no-cache`]=!0)}now(){return Date.now()}storable(){return!!(!this._reqcc[`no-store`]&&(this._method===`GET`||this._method===`HEAD`||this._method===`POST`&&this._hasExplicitExpiration())&&r.has(this._status)&&!this._rescc[`no-store`]&&(!this._isShared||!this._rescc.private)&&(!this._isShared||this._noAuthorization||this._allowsStoringAuthenticated())&&(this._resHeaders.expires||this._rescc[`max-age`]||this._isShared&&this._rescc[`s-maxage`]||this._rescc.public||n.has(this._status)))}_hasExplicitExpiration(){return!!(this._isShared&&this._rescc[`s-maxage`]||this._rescc[`max-age`]||this._resHeaders.expires)}_assertRequestHasHeaders(e){if(!e||!e.headers)throw Error(`Request headers missing`)}satisfiesWithoutRevalidation(e){return!this.evaluateRequest(e).revalidation}_evaluateRequestHitResult(e){return{response:{headers:this.responseHeaders()},revalidation:e}}_evaluateRequestRevalidation(e,t){return{synchronous:t,headers:this.revalidationHeaders(e)}}_evaluateRequestMissResult(e){return{response:void 0,revalidation:this._evaluateRequestRevalidation(e,!0)}}evaluateRequest(e){if(this._assertRequestHasHeaders(e),this._rescc[`must-revalidate`]||!this._requestMatches(e,!1))return this._evaluateRequestMissResult(e);let t=l(e.headers[`cache-control`]);return t[`no-cache`]||/no-cache/.test(e.headers.pragma)||t[`max-age`]&&this.age()>s(t[`max-age`])||t[`min-fresh`]&&this.maxAge()-this.age()<s(t[`min-fresh`])?this._evaluateRequestMissResult(e):this.stale()?`max-stale`in t&&(!0===t[`max-stale`]||t[`max-stale`]>this.age()-this.maxAge())?this._evaluateRequestHitResult(void 0):this.useStaleWhileRevalidate()?this._evaluateRequestHitResult(this._evaluateRequestRevalidation(e,!1)):this._evaluateRequestMissResult(e):this._evaluateRequestHitResult(void 0)}_requestMatches(e,t){return!(this._url&&this._url!==e.url||this._host!==e.headers.host||e.method&&this._method!==e.method&&(!t||e.method!==`HEAD`)||!this._varyMatches(e))}_allowsStoringAuthenticated(){return!!(this._rescc[`must-revalidate`]||this._rescc.public||this._rescc[`s-maxage`])}_varyMatches(e){if(!this._resHeaders.vary)return!0;if(this._resHeaders.vary===`*`)return!1;let t=this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);for(let n of t)if(e.headers[n]!==this._reqHeaders[n])return!1;return!0}_copyWithoutHopByHopHeaders(e){let t={};for(let n in e)a[n]||(t[n]=e[n]);if(e.connection){let n=e.connection.trim().split(/\s*,\s*/);for(let e of n)delete t[e]}if(t.warning){let e=t.warning.split(/,/).filter(e=>!/^\s*1[0-9][0-9]/.test(e));e.length?t.warning=e.join(`,`).trim():delete t.warning}return t}responseHeaders(){let e=this._copyWithoutHopByHopHeaders(this._resHeaders),t=this.age();return t>86400&&!this._hasExplicitExpiration()&&this.maxAge()>86400&&(e.warning=(e.warning?`${e.warning}, `:``)+`113 - "rfc7234 5.5.4"`),e.age=`${Math.round(t)}`,e.date=new Date(this.now()).toUTCString(),e}date(){let e=Date.parse(this._resHeaders.date);return isFinite(e)?e:this._responseTime}age(){return this._ageValue()+(this.now()-this._responseTime)/1e3}_ageValue(){return s(this._resHeaders.age)}maxAge(){if(!this.storable()||this._rescc[`no-cache`]||this._isShared&&this._resHeaders[`set-cookie`]&&!this._rescc.public&&!this._rescc.immutable||this._resHeaders.vary===`*`)return 0;if(this._isShared){if(this._rescc[`proxy-revalidate`])return 0;if(this._rescc[`s-maxage`])return s(this._rescc[`s-maxage`])}if(this._rescc[`max-age`])return s(this._rescc[`max-age`]);let e=this._rescc.immutable?this._immutableMinTtl:0,t=this.date();if(this._resHeaders.expires){let n=Date.parse(this._resHeaders.expires);return Number.isNaN(n)||n<t?0:Math.max(e,(n-t)/1e3)}if(this._resHeaders[`last-modified`]){let n=Date.parse(this._resHeaders[`last-modified`]);if(isFinite(n)&&t>n)return Math.max(e,(t-n)/1e3*this._cacheHeuristic)}return e}timeToLive(){let e=this.maxAge()-this.age(),t=e+s(this._rescc[`stale-if-error`]),n=e+s(this._rescc[`stale-while-revalidate`]);return Math.round(Math.max(0,e,t,n)*1e3)}stale(){return this.maxAge()<=this.age()}_useStaleIfError(){return this.maxAge()+s(this._rescc[`stale-if-error`])>this.age()}useStaleWhileRevalidate(){let e=s(this._rescc[`stale-while-revalidate`]);return e>0&&this.maxAge()+e>this.age()}static fromObject(e){return new this(void 0,void 0,{_fromObject:e})}_fromObject(e){if(this._responseTime)throw Error(`Reinitialized`);if(!e||e.v!==1)throw Error(`Invalid serialization`);this._responseTime=e.t,this._isShared=e.sh,this._cacheHeuristic=e.ch,this._immutableMinTtl=e.imm===void 0?864e5:e.imm,this._ignoreCargoCult=!!e.icc,this._status=e.st,this._resHeaders=e.resh,this._rescc=e.rescc,this._method=e.m,this._url=e.u,this._host=e.h,this._noAuthorization=e.a,this._reqHeaders=e.reqh,this._reqcc=e.reqcc}toObject(){return{v:1,t:this._responseTime,sh:this._isShared,ch:this._cacheHeuristic,imm:this._immutableMinTtl,icc:this._ignoreCargoCult,st:this._status,resh:this._resHeaders,rescc:this._rescc,m:this._method,u:this._url,h:this._host,a:this._noAuthorization,reqh:this._reqHeaders,reqcc:this._reqcc}}revalidationHeaders(e){this._assertRequestHasHeaders(e);let t=this._copyWithoutHopByHopHeaders(e.headers);if(delete t[`if-range`],!this._requestMatches(e,!0)||!this.storable())return delete t[`if-none-match`],delete t[`if-modified-since`],t;if(this._resHeaders.etag&&(t[`if-none-match`]=t[`if-none-match`]?`${t[`if-none-match`]}, ${this._resHeaders.etag}`:this._resHeaders.etag),t[`accept-ranges`]||t[`if-match`]||t[`if-unmodified-since`]||this._method&&this._method!=`GET`){if(delete t[`if-modified-since`],t[`if-none-match`]){let e=t[`if-none-match`].split(/,/).filter(e=>!/^\s*W\//.test(e));e.length?t[`if-none-match`]=e.join(`,`).trim():delete t[`if-none-match`]}}else this._resHeaders[`last-modified`]&&!t[`if-modified-since`]&&(t[`if-modified-since`]=this._resHeaders[`last-modified`]);return t}revalidatedPolicy(e,t){if(this._assertRequestHasHeaders(e),this._useStaleIfError()&&c(t))return{policy:this,modified:!1,matches:!0};if(!t||!t.headers)throw Error(`Response headers missing`);let n=!1;t.status!==void 0&&t.status!=304?n=!1:t.headers.etag&&!/^\s*W\//.test(t.headers.etag)?n=this._resHeaders.etag&&this._resHeaders.etag.replace(/^\s*W\//,``)===t.headers.etag:this._resHeaders.etag&&t.headers.etag?n=this._resHeaders.etag.replace(/^\s*W\//,``)===t.headers.etag.replace(/^\s*W\//,``):this._resHeaders[`last-modified`]?n=this._resHeaders[`last-modified`]===t.headers[`last-modified`]:!this._resHeaders.etag&&!this._resHeaders[`last-modified`]&&!t.headers.etag&&!t.headers[`last-modified`]&&(n=!0);let r={shared:this._isShared,cacheHeuristic:this._cacheHeuristic,immutableMinTimeToLive:this._immutableMinTtl,ignoreCargoCult:this._ignoreCargoCult};if(!n)return{policy:new this.constructor(e,t,r),modified:t.status!=304,matches:!1};let i={};for(let e in this._resHeaders)i[e]=e in t.headers&&!o[e]?t.headers[e]:this._resHeaders[e];let a=Object.assign({},t,{status:this._status,method:this._method,headers:i});return{policy:new this.constructor(e,a,r),modified:!1,matches:!0}}}})),av=L(((e,t)=>{t.exports=e=>{let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}})),ov=L(((e,t)=>{var n=R(`stream`).Readable,r=av();t.exports=class extends n{constructor(e,t,n,i){if(typeof e!=`number`)throw TypeError("Argument `statusCode` should be a number");if(typeof t!=`object`)throw TypeError("Argument `headers` should be an object");if(!(n instanceof Buffer))throw TypeError("Argument `body` should be a buffer");if(typeof i!=`string`)throw TypeError("Argument `url` should be a string");super(),this.statusCode=e,this.headers=r(t),this.body=n,this.url=i}_read(){this.push(this.body),this.push(null)}}})),sv=L(((e,t)=>{var n=[`destroy`,`setTimeout`,`socket`,`headers`,`trailers`,`rawHeaders`,`statusCode`,`httpVersion`,`httpVersionMinor`,`httpVersionMajor`,`rawTrailers`,`statusMessage`];t.exports=(e,t)=>{let r=new Set(Object.keys(e).concat(n));for(let n of r)n in t||(t[n]=typeof e[n]==`function`?e[n].bind(e):e[n])}})),cv=L(((e,t)=>{var n=R(`stream`).PassThrough,r=sv();t.exports=e=>{if(!(e&&e.pipe))throw TypeError("Parameter `response` must be a response stream.");let t=new n;return r(e,t),e.pipe(t)}})),lv=L((e=>{e.stringify=function e(t){if(t===void 0)return t;if(t&&Buffer.isBuffer(t))return JSON.stringify(`:base64:`+t.toString(`base64`));if(t&&t.toJSON&&(t=t.toJSON()),t&&typeof t==`object`){var n=``,r=Array.isArray(t);n=r?`[`:`{`;var i=!0;for(var a in t){var o=typeof t[a]==`function`||!r&&t[a]===void 0;Object.hasOwnProperty.call(t,a)&&!o&&(i||(n+=`,`),i=!1,r?t[a]==null?n+=`null`:n+=e(t[a]):t[a]!==void 0&&(n+=e(a)+`:`+e(t[a])))}return n+=r?`]`:`}`,n}return typeof t==`string`?JSON.stringify(/^:/.test(t)?`:`+t:t):t===void 0?`null`:JSON.stringify(t)},e.parse=function(e){return JSON.parse(e,function(e,t){return typeof t==`string`?/^:base64:/.test(t)?Buffer.from(t.substring(8),`base64`):/^:/.test(t)?t.substring(1):t:t})}})),uv=L(((e,t)=>{var n=R(`events`),r=lv(),i=e=>e.adapter||e.uri?new(R({redis:`@keyv/redis`,rediss:`@keyv/redis`,mongodb:`@keyv/mongo`,mongo:`@keyv/mongo`,sqlite:`@keyv/sqlite`,postgresql:`@keyv/postgres`,postgres:`@keyv/postgres`,mysql:`@keyv/mysql`,etcd:`@keyv/etcd`,offline:`@keyv/offline`,tiered:`@keyv/tiered`}[e.adapter||/^[^:+]*/.exec(e.uri)[0]]))(e):new Map,a=[`sqlite`,`postgres`,`mysql`,`mongo`,`redis`,`tiered`];t.exports=class extends n{constructor(e,{emitErrors:t=!0,...n}={}){if(super(),this.opts={namespace:`keyv`,serialize:r.stringify,deserialize:r.parse,...typeof e==`string`?{uri:e}:e,...n},!this.opts.store){let e={...this.opts};this.opts.store=i(e)}if(this.opts.compression){let e=this.opts.compression;this.opts.serialize=e.serialize.bind(e),this.opts.deserialize=e.deserialize.bind(e)}typeof this.opts.store.on==`function`&&t&&this.opts.store.on(`error`,e=>this.emit(`error`,e)),this.opts.store.namespace=this.opts.namespace;let a=e=>async function*(){for await(let[t,n]of typeof e==`function`?e(this.opts.store.namespace):e){let e=await this.opts.deserialize(n);if(!this.opts.store.namespace||t.includes(this.opts.store.namespace)){if(typeof e.expires==`number`&&Date.now()>e.expires){this.delete(t);continue}yield[this._getKeyUnprefix(t),e.value]}}};typeof this.opts.store[Symbol.iterator]==`function`&&this.opts.store instanceof Map?this.iterator=a(this.opts.store):typeof this.opts.store.iterator==`function`&&this.opts.store.opts&&this._checkIterableAdaptar()&&(this.iterator=a(this.opts.store.iterator.bind(this.opts.store)))}_checkIterableAdaptar(){return a.includes(this.opts.store.opts.dialect)||a.findIndex(e=>this.opts.store.opts.url.includes(e))>=0}_getKeyPrefix(e){return`${this.opts.namespace}:${e}`}_getKeyPrefixArray(e){return e.map(e=>`${this.opts.namespace}:${e}`)}_getKeyUnprefix(e){return e.split(`:`).splice(1).join(`:`)}get(e,t){let{store:n}=this.opts,r=Array.isArray(e),i=r?this._getKeyPrefixArray(e):this._getKeyPrefix(e);if(r&&n.getMany===void 0){let e=[];for(let r of i)e.push(Promise.resolve().then(()=>n.get(r)).then(e=>typeof e==`string`||this.opts.compression?this.opts.deserialize(e):e).then(e=>{if(e!=null)return typeof e.expires==`number`&&Date.now()>e.expires?this.delete(r).then(()=>void 0):t&&t.raw?e:e.value}));return Promise.allSettled(e).then(e=>{let t=[];for(let n of e)t.push(n.value);return t})}return Promise.resolve().then(()=>r?n.getMany(i):n.get(i)).then(e=>typeof e==`string`||this.opts.compression?this.opts.deserialize(e):e).then(n=>{if(n!=null)return r?n.map((n,r)=>{if(typeof n==`string`&&(n=this.opts.deserialize(n)),n!=null){if(typeof n.expires==`number`&&Date.now()>n.expires){this.delete(e[r]).then(()=>void 0);return}return t&&t.raw?n:n.value}}):typeof n.expires==`number`&&Date.now()>n.expires?this.delete(e).then(()=>void 0):t&&t.raw?n:n.value})}set(e,t,n){let r=this._getKeyPrefix(e);n===void 0&&(n=this.opts.ttl),n===0&&(n=void 0);let{store:i}=this.opts;return Promise.resolve().then(()=>{let e=typeof n==`number`?Date.now()+n:null;return typeof t==`symbol`&&this.emit(`error`,`symbol cannot be serialized`),t={value:t,expires:e},this.opts.serialize(t)}).then(e=>i.set(r,e,n)).then(()=>!0)}delete(e){let{store:t}=this.opts;if(Array.isArray(e)){let n=this._getKeyPrefixArray(e);if(t.deleteMany===void 0){let e=[];for(let r of n)e.push(t.delete(r));return Promise.allSettled(e).then(e=>e.every(e=>e.value===!0))}return Promise.resolve().then(()=>t.deleteMany(n))}let n=this._getKeyPrefix(e);return Promise.resolve().then(()=>t.delete(n))}clear(){let{store:e}=this.opts;return Promise.resolve().then(()=>e.clear())}has(e){let t=this._getKeyPrefix(e),{store:n}=this.opts;return Promise.resolve().then(async()=>typeof n.has==`function`?n.has(t):await n.get(t)!==void 0)}disconnect(){let{store:e}=this.opts;if(typeof e.disconnect==`function`)return e.disconnect()}}})),dv=L(((e,t)=>{var n=R(`events`),r=R(`url`),i=Z_(),a=rv(),o=iv(),s=ov(),c=av(),l=cv(),u=uv(),d=class e{constructor(e,t){if(typeof e!=`function`)throw TypeError("Parameter `request` must be a function");return this.cache=new u({uri:typeof t==`string`&&t,store:typeof t!=`string`&&t,namespace:`cacheable-request`}),this.createCacheableRequest(e)}createCacheableRequest(t){return(u,d)=>{let m;if(typeof u==`string`)m=p(r.parse(u)),u={};else if(u instanceof r.URL)m=p(r.parse(u.toString())),u={};else{let[e,...t]=(u.path||``).split(`?`),n=t.length>0?`?${t.join(`?`)}`:``;m=p({...u,pathname:e,search:n})}u={headers:{},method:`GET`,cache:!0,strictTtl:!1,automaticFailover:!1,...u,...f(m)},u.headers=c(u.headers);let h=new n,g=i(r.format(m),{stripWWW:!1,removeTrailingSlash:!1,stripAuthentication:!1}),_=`${u.method}:${g}`,v=!1,y=!1,b=n=>{y=!0;let r=!1,i,c=new Promise(e=>{i=()=>{r||(r=!0,e())}}),u=t=>{if(v&&!n.forceRefresh){t.status=t.statusCode;let e=o.fromObject(v.cachePolicy).revalidatedPolicy(n,t);if(!e.modified){let n=e.policy.responseHeaders();t=new s(v.statusCode,n,v.body,v.url),t.cachePolicy=e.policy,t.fromCache=!0}}t.fromCache||(t.cachePolicy=new o(n,t,n),t.fromCache=!1);let i;n.cache&&t.cachePolicy.storable()?(i=l(t),(async()=>{try{let e=a.buffer(t);if(await Promise.race([c,new Promise(e=>t.once(`end`,e))]),r)return;let i=await e,o={cachePolicy:t.cachePolicy.toObject(),url:t.url,statusCode:t.fromCache?v.statusCode:t.statusCode,body:i},s=n.strictTtl?t.cachePolicy.timeToLive():void 0;n.maxTtl&&(s=s?Math.min(s,n.maxTtl):n.maxTtl),await this.cache.set(_,o,s)}catch(t){h.emit(`error`,new e.CacheError(t))}})()):n.cache&&v&&(async()=>{try{await this.cache.delete(_)}catch(t){h.emit(`error`,new e.CacheError(t))}})(),h.emit(`response`,i||t),typeof d==`function`&&d(i||t)};try{let e=t(n,u);e.once(`error`,i),e.once(`abort`,i),h.emit(`request`,e)}catch(t){h.emit(`error`,new e.RequestError(t))}};return(async()=>{let t=async e=>{await Promise.resolve();let t=e.cache?await this.cache.get(_):void 0;if(t===void 0)return b(e);let n=o.fromObject(t.cachePolicy);if(n.satisfiesWithoutRevalidation(e)&&!e.forceRefresh){let e=n.responseHeaders(),r=new s(t.statusCode,e,t.body,t.url);r.cachePolicy=n,r.fromCache=!0,h.emit(`response`,r),typeof d==`function`&&d(r)}else v=t,e.headers=n.revalidationHeaders(e),b(e)},n=t=>h.emit(`error`,new e.CacheError(t));this.cache.once(`error`,n),h.on(`response`,()=>this.cache.removeListener(`error`,n));try{await t(u)}catch(t){u.automaticFailover&&!y&&b(u),h.emit(`error`,new e.CacheError(t))}})(),h}}};function f(e){let t={...e};return t.path=`${e.pathname||`/`}${e.search||``}`,delete t.pathname,delete t.search,t}function p(e){return{protocol:e.protocol,auth:e.auth,hostname:e.hostname||e.host||`localhost`,port:e.port,pathname:e.pathname,search:e.search}}d.RequestError=class extends Error{constructor(e){super(e.message),this.name=`RequestError`,Object.assign(this,e)}},d.CacheError=class extends Error{constructor(e){super(e.message),this.name=`CacheError`,Object.assign(this,e)}},t.exports=d})),fv=L(((e,t)=>{var n=[`aborted`,`complete`,`headers`,`httpVersion`,`httpVersionMinor`,`httpVersionMajor`,`method`,`rawHeaders`,`rawTrailers`,`setTimeout`,`socket`,`statusCode`,`statusMessage`,`trailers`,`url`];t.exports=(e,t)=>{if(t._readableState.autoDestroy)throw Error("The second stream must have the `autoDestroy` option set to `false`");let r=new Set(Object.keys(e).concat(n)),i={};for(let n of r)n in t||(i[n]={get(){let t=e[n];return typeof t==`function`?t.bind(e):t},set(t){e[n]=t},enumerable:!0,configurable:!1});return Object.defineProperties(t,i),e.once(`aborted`,()=>{t.destroy(),t.emit(`aborted`)}),e.once(`close`,()=>{e.complete&&t.readable?t.once(`end`,()=>{t.emit(`close`)}):t.emit(`close`)}),t}})),pv=L(((e,t)=>{var{Transform:n,PassThrough:r}=R(`stream`),i=R(`zlib`),a=fv();t.exports=e=>{let t=(e.headers[`content-encoding`]||``).toLowerCase();if(![`gzip`,`deflate`,`br`].includes(t))return e;let o=t===`br`;if(o&&typeof i.createBrotliDecompress!=`function`)return e.destroy(Error(`Brotli is not supported on Node.js < 12`)),e;let s=!0,c=new n({transform(e,t,n){s=!1,n(null,e)},flush(e){e()}}),l=new r({autoDestroy:!1,destroy(t,n){e.destroy(),n(t)}}),u=o?i.createBrotliDecompress():i.createUnzip();return u.once(`error`,t=>{if(s&&!e.readable){l.end();return}l.destroy(t)}),a(e,l),e.pipe(c).pipe(u).pipe(l),l}})),mv=L(((e,t)=>{t.exports=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");this.maxSize=e.maxSize,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_set(e,t){if(this.cache.set(e,t),this._size++,this._size>=this.maxSize){if(this._size=0,typeof this.onEviction==`function`)for(let[e,t]of this.oldCache.entries())this.onEviction(e,t);this.oldCache=this.cache,this.cache=new Map}}get(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){let t=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,t),t}}set(e,t){return this.cache.has(e)?this.cache.set(e,t):this._set(e,t),this}has(e){return this.cache.has(e)||this.oldCache.has(e)}peek(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e))return this.oldCache.get(e)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache)yield e;for(let e of this.oldCache){let[t]=e;this.cache.has(t)||(yield e)}}get size(){let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}}})),hv=L(((e,t)=>{var n=R(`events`),r=R(`tls`),i=R(`http2`),a=mv(),o=Symbol(`currentStreamsCount`),s=Symbol(`request`),c=Symbol(`cachedOriginSet`),l=Symbol(`gracefullyClosing`),u=`maxDeflateDynamicTableSize.maxSessionMemory.maxHeaderListPairs.maxOutstandingPings.maxReservedRemoteStreams.maxSendHeaderBlockLength.paddingStrategy.localAddress.path.rejectUnauthorized.minDHSize.ca.cert.clientCertEngine.ciphers.key.pfx.servername.minVersion.maxVersion.secureProtocol.crl.honorCipherOrder.ecdhCurve.dhparam.secureOptions.sessionIdContext`.split(`.`),d=(e,t,n)=>{let r=0,i=e.length;for(;r<i;){let a=r+i>>>1;n(e[a],t)?r=a+1:i=a}return r},f=(e,t)=>e.remoteSettings.maxConcurrentStreams>t.remoteSettings.maxConcurrentStreams,p=(e,t)=>{for(let n of e)n[c].length<t[c].length&&n[c].every(e=>t[c].includes(e))&&n[o]+t[o]<=t.remoteSettings.maxConcurrentStreams&&g(n)},m=(e,t)=>{for(let n of e)t[c].length<n[c].length&&t[c].every(e=>n[c].includes(e))&&t[o]+n[o]<=n.remoteSettings.maxConcurrentStreams&&g(t)},h=({agent:e,isFree:t})=>{let n={};for(let r in e.sessions){let i=e.sessions[r].filter(e=>{let n=e[_.kCurrentStreamsCount]<e.remoteSettings.maxConcurrentStreams;return t?n:!n});i.length!==0&&(n[r]=i)}return n},g=e=>{e[l]=!0,e[o]===0&&e.close()},_=class e extends n{constructor({timeout:e=6e4,maxSessions:t=1/0,maxFreeSessions:n=10,maxCachedTlsSessions:r=100}={}){super(),this.sessions={},this.queue={},this.timeout=e,this.maxSessions=t,this.maxFreeSessions=n,this._freeSessionsCount=0,this._sessionsCount=0,this.settings={enablePush:!1},this.tlsSessionCache=new a({maxSize:r})}static normalizeOrigin(e,t){return typeof e==`string`&&(e=new URL(e)),t&&e.hostname!==t&&(e.hostname=t),e.origin}normalizeOptions(e){let t=``;if(e)for(let n of u)e[n]&&(t+=`:${e[n]}`);return t}_tryToCreateNewSession(e,t){if(!(e in this.queue)||!(t in this.queue[e]))return;let n=this.queue[e][t];this._sessionsCount<this.maxSessions&&!n.completed&&(n.completed=!0,n())}getSession(t,n,r){return new Promise((a,u)=>{Array.isArray(r)?(r=[...r],a()):r=[{resolve:a,reject:u}];let h=this.normalizeOptions(n),g=e.normalizeOrigin(t,n&&n.servername);if(g===void 0){for(let{reject:e}of r)e(TypeError("The `origin` argument needs to be a string or an URL object"));return}if(h in this.sessions){let e=this.sessions[h],t=-1,n=-1,i;for(let r of e){let e=r.remoteSettings.maxConcurrentStreams;if(e<t)break;if(r[c].includes(g)){let a=r[o];if(a>=e||r[l]||r.destroyed)continue;i||(t=e),a>n&&(i=r,n=a)}}if(i){if(r.length!==1){for(let{reject:e}of r)e(Error(`Expected the length of listeners to be 1, got ${r.length}.\nPlease report this to https://github.com/szmarczak/http2-wrapper/`));return}r[0].resolve(i);return}}if(h in this.queue){if(g in this.queue[h]){this.queue[h][g].listeners.push(...r),this._tryToCreateNewSession(h,g);return}}else this.queue[h]={};let _=()=>{h in this.queue&&this.queue[h][g]===v&&(delete this.queue[h][g],Object.keys(this.queue[h]).length===0&&delete this.queue[h])},v=()=>{let e=`${g}:${h}`,a=!1;try{let u=i.connect(t,{createConnection:this.createConnection,settings:this.settings,session:this.tlsSessionCache.get(e),...n});u[o]=0,u[l]=!1;let y=()=>u[o]<u.remoteSettings.maxConcurrentStreams,b=!0;u.socket.once(`session`,t=>{this.tlsSessionCache.set(e,t)}),u.once(`error`,t=>{for(let{reject:e}of r)e(t);this.tlsSessionCache.delete(e)}),u.setTimeout(this.timeout,()=>{u.destroy()}),u.once(`close`,()=>{if(a){b&&this._freeSessionsCount--,this._sessionsCount--;let e=this.sessions[h];e.splice(e.indexOf(u),1),e.length===0&&delete this.sessions[h]}else{let e=Error(`Session closed without receiving a SETTINGS frame`);e.code=`HTTP2WRAPPER_NOSETTINGS`;for(let{reject:t}of r)t(e);_()}this._tryToCreateNewSession(h,g)});let x=()=>{if(h in this.queue&&y()){for(let e of u[c])if(e in this.queue[h]){let{listeners:t}=this.queue[h][e];for(;t.length!==0&&y();)t.shift().resolve(u);let n=this.queue[h];if(n[e].listeners.length===0&&(delete n[e],Object.keys(n).length===0)){delete this.queue[h];break}if(!y())break}}};u.on(`origin`,()=>{u[c]=u.originSet,y()&&(x(),p(this.sessions[h],u))}),u.once(`remoteSettings`,()=>{if(u.ref(),u.unref(),this._sessionsCount++,v.destroyed){let e=Error(`Agent has been destroyed`);for(let t of r)t.reject(e);u.destroy();return}u[c]=u.originSet;{let e=this.sessions;if(h in e){let t=e[h];t.splice(d(t,u,f),0,u)}else e[h]=[u]}this._freeSessionsCount+=1,a=!0,this.emit(`session`,u),x(),_(),u[o]===0&&this._freeSessionsCount>this.maxFreeSessions&&u.close(),r.length!==0&&(this.getSession(g,n,r),r.length=0),u.on(`remoteSettings`,()=>{x(),p(this.sessions[h],u)})}),u[s]=u.request,u.request=(e,t)=>{if(u[l])throw Error(`The session is gracefully closing. No new streams are allowed.`);let n=u[s](e,t);return u.ref(),++u[o],u[o]===u.remoteSettings.maxConcurrentStreams&&this._freeSessionsCount--,n.once(`close`,()=>{if(b=y(),--u[o],!u.destroyed&&!u.closed&&(m(this.sessions[h],u),y()&&!u.closed)){b||=(this._freeSessionsCount++,!0);let e=u[o]===0;e&&u.unref(),e&&(this._freeSessionsCount>this.maxFreeSessions||u[l])?u.close():(p(this.sessions[h],u),x())}}),n}}catch(e){for(let t of r)t.reject(e);_()}};v.listeners=r,v.completed=!1,v.destroyed=!1,this.queue[h][g]=v,this._tryToCreateNewSession(h,g)})}request(e,t,n,r){return new Promise((i,a)=>{this.getSession(e,t,[{reject:a,resolve:e=>{try{i(e.request(n,r))}catch(e){a(e)}}}])})}createConnection(t,n){return e.connect(t,n)}static connect(e,t){t.ALPNProtocols=[`h2`];let n=e.port||443,i=e.hostname||e.host;return t.servername===void 0&&(t.servername=i),r.connect(n,i,t)}closeFreeSessions(){for(let e of Object.values(this.sessions))for(let t of e)t[o]===0&&t.close()}destroy(e){for(let t of Object.values(this.sessions))for(let n of t)n.destroy(e);for(let e of Object.values(this.queue))for(let t of Object.values(e))t.destroyed=!0;this.queue={}}get freeSessions(){return h({agent:this,isFree:!0})}get busySessions(){return h({agent:this,isFree:!1})}};_.kCurrentStreamsCount=o,_.kGracefullyClosing=l,t.exports={Agent:_,globalAgent:new _}})),gv=L(((e,t)=>{var{Readable:n}=R(`stream`);t.exports=class extends n{constructor(e,t){super({highWaterMark:t,autoDestroy:!1}),this.statusCode=null,this.statusMessage=``,this.httpVersion=`2.0`,this.httpVersionMajor=2,this.httpVersionMinor=0,this.headers={},this.trailers={},this.req=null,this.aborted=!1,this.complete=!1,this.upgrade=null,this.rawHeaders=[],this.rawTrailers=[],this.socket=e,this.connection=e,this._dumped=!1}_destroy(e){this.req._request.destroy(e)}setTimeout(e,t){return this.req.setTimeout(e,t),this}_dump(){this._dumped||(this._dumped=!0,this.removeAllListeners(`data`),this.resume())}_read(){this.req&&this.req._request.resume()}}})),_v=L(((e,t)=>{t.exports=e=>{let t={protocol:e.protocol,hostname:typeof e.hostname==`string`&&e.hostname.startsWith(`[`)?e.hostname.slice(1,-1):e.hostname,host:e.host,hash:e.hash,search:e.search,pathname:e.pathname,href:e.href,path:`${e.pathname||``}${e.search||``}`};return typeof e.port==`string`&&e.port.length!==0&&(t.port=Number(e.port)),(e.username||e.password)&&(t.auth=`${e.username||``}:${e.password||``}`),t}})),vv=L(((e,t)=>{t.exports=(e,t,n)=>{for(let r of n)e.on(r,(...e)=>t.emit(r,...e))}})),yv=L(((e,t)=>{t.exports=e=>{switch(e){case`:method`:case`:scheme`:case`:authority`:case`:path`:return!0;default:return!1}}})),bv=L(((e,t)=>{var n=(e,n,r)=>{t.exports[n]=class extends e{constructor(...e){super(typeof r==`string`?r:r(e)),this.name=`${super.name} [${n}]`,this.code=n}}};n(TypeError,`ERR_INVALID_ARG_TYPE`,e=>{let t=e[0].includes(`.`)?`property`:`argument`,n=e[1],r=Array.isArray(n);return r&&(n=`${n.slice(0,-1).join(`, `)} or ${n.slice(-1)}`),`The "${e[0]}" ${t} must be ${r?`one of`:`of`} type ${n}. Received ${typeof e[2]}`}),n(TypeError,`ERR_INVALID_PROTOCOL`,e=>`Protocol "${e[0]}" not supported. Expected "${e[1]}"`),n(Error,`ERR_HTTP_HEADERS_SENT`,e=>`Cannot ${e[0]} headers after they are sent to the client`),n(TypeError,`ERR_INVALID_HTTP_TOKEN`,e=>`${e[0]} must be a valid HTTP token [${e[1]}]`),n(TypeError,`ERR_HTTP_INVALID_HEADER_VALUE`,e=>`Invalid value "${e[0]} for header "${e[1]}"`),n(TypeError,`ERR_INVALID_CHAR`,e=>`Invalid character in ${e[0]} [${e[1]}]`)})),xv=L(((e,t)=>{var n=R(`http2`),{Writable:r}=R(`stream`),{Agent:i,globalAgent:a}=hv(),o=gv(),s=_v(),c=vv(),l=yv(),{ERR_INVALID_ARG_TYPE:u,ERR_INVALID_PROTOCOL:d,ERR_HTTP_HEADERS_SENT:f,ERR_INVALID_HTTP_TOKEN:p,ERR_HTTP_INVALID_HEADER_VALUE:m,ERR_INVALID_CHAR:h}=bv(),{HTTP2_HEADER_STATUS:g,HTTP2_HEADER_METHOD:_,HTTP2_HEADER_PATH:v,HTTP2_METHOD_CONNECT:y}=n.constants,b=Symbol(`headers`),x=Symbol(`origin`),S=Symbol(`session`),C=Symbol(`options`),w=Symbol(`flushedHeaders`),T=Symbol(`jobs`),E=/^[\^`\-\w!#$%&*+.|~]+$/,D=/[^\t\u0020-\u007E\u0080-\u00FF]/;t.exports=class extends r{constructor(e,t,n){super({autoDestroy:!1});let r=typeof e==`string`||e instanceof URL;if(r&&(e=s(e instanceof URL?e:new URL(e))),typeof t==`function`||t===void 0?(n=t,t=r?e:{...e}):t={...e,...t},t.h2session)this[S]=t.h2session;else if(t.agent===!1)this.agent=new i({maxFreeSessions:0});else if(t.agent===void 0||t.agent===null)typeof t.createConnection==`function`?(this.agent=new i({maxFreeSessions:0}),this.agent.createConnection=t.createConnection):this.agent=a;else if(typeof t.agent.request==`function`)this.agent=t.agent;else throw new u(`options.agent`,[`Agent-like Object`,`undefined`,`false`],t.agent);if(t.protocol&&t.protocol!==`https:`)throw new d(t.protocol,`https:`);let o=t.port||t.defaultPort||this.agent&&this.agent.defaultPort||443,c=t.hostname||t.host||`localhost`;delete t.hostname,delete t.host,delete t.port;let{timeout:l}=t;if(t.timeout=void 0,this[b]=Object.create(null),this[T]=[],this.socket=null,this.connection=null,this.method=t.method||`GET`,this.path=t.path,this.res=null,this.aborted=!1,this.reusedSocket=!1,t.headers)for(let[e,n]of Object.entries(t.headers))this.setHeader(e,n);t.auth&&!(`authorization`in this[b])&&(this[b].authorization=`Basic `+Buffer.from(t.auth).toString(`base64`)),t.session=t.tlsSession,t.path=t.socketPath,this[C]=t,o===443?(this[x]=`https://${c}`,`:authority`in this[b]||(this[b][`:authority`]=c)):(this[x]=`https://${c}:${o}`,`:authority`in this[b]||(this[b][`:authority`]=`${c}:${o}`)),l&&this.setTimeout(l),n&&this.once(`response`,n),this[w]=!1}get method(){return this[b][_]}set method(e){e&&(this[b][_]=e.toUpperCase())}get path(){return this[b][v]}set path(e){e&&(this[b][v]=e)}get _mustNotHaveABody(){return this.method===`GET`||this.method===`HEAD`||this.method===`DELETE`}_write(e,t,n){if(this._mustNotHaveABody){n(Error(`The GET, HEAD and DELETE methods must NOT have a body`));return}this.flushHeaders();let r=()=>this._request.write(e,t,n);this._request?r():this[T].push(r)}_final(e){if(this.destroyed)return;this.flushHeaders();let t=()=>{if(this._mustNotHaveABody){e();return}this._request.end(e)};this._request?t():this[T].push(t)}abort(){this.res&&this.res.complete||(this.aborted||process.nextTick(()=>this.emit(`abort`)),this.aborted=!0,this.destroy())}_destroy(e,t){this.res&&this.res._dump(),this._request&&this._request.destroy(),t(e)}async flushHeaders(){if(this[w]||this.destroyed)return;this[w]=!0;let e=this.method===y,t=t=>{if(this._request=t,this.destroyed){t.destroy();return}e||c(t,this,[`timeout`,`continue`,`close`,`error`]);let n=e=>(...t)=>{!this.writable&&!this.destroyed?e(...t):this.once(`finish`,()=>{e(...t)})};t.once(`response`,n((n,r,i)=>{let a=new o(this.socket,t.readableHighWaterMark);this.res=a,a.req=this,a.statusCode=n[g],a.headers=n,a.rawHeaders=i,a.once(`end`,()=>{this.aborted?(a.aborted=!0,a.emit(`aborted`)):(a.complete=!0,a.socket=null,a.connection=null)}),e?(a.upgrade=!0,this.emit(`connect`,a,t,Buffer.alloc(0))?this.emit(`close`):t.destroy()):(t.on(`data`,e=>{!a._dumped&&!a.push(e)&&t.pause()}),t.once(`end`,()=>{a.push(null)}),this.emit(`response`,a)||a._dump())})),t.once(`headers`,n(e=>this.emit(`information`,{statusCode:e[g]}))),t.once(`trailers`,n((e,t,n)=>{let{res:r}=this;r.trailers=e,r.rawTrailers=n}));let{socket:r}=t.session;this.socket=r,this.connection=r;for(let e of this[T])e();this.emit(`socket`,this.socket)};if(this[S])try{t(this[S].request(this[b]))}catch(e){this.emit(`error`,e)}else{this.reusedSocket=!0;try{t(await this.agent.request(this[x],this[C],this[b]))}catch(e){this.emit(`error`,e)}}}getHeader(e){if(typeof e!=`string`)throw new u(`name`,`string`,e);return this[b][e.toLowerCase()]}get headersSent(){return this[w]}removeHeader(e){if(typeof e!=`string`)throw new u(`name`,`string`,e);if(this.headersSent)throw new f(`remove`);delete this[b][e.toLowerCase()]}setHeader(e,t){if(this.headersSent)throw new f(`set`);if(typeof e!=`string`||!E.test(e)&&!l(e))throw new p(`Header name`,e);if(t===void 0)throw new m(t,e);if(D.test(t))throw new h(`header content`,e);this[b][e.toLowerCase()]=t}setNoDelay(){}setSocketKeepAlive(){}setTimeout(e,t){let n=()=>this._request.setTimeout(e,t);return this._request?n():this[T].push(n),this}get maxHeadersCount(){if(!this.destroyed&&this._request)return this._request.session.localSettings.maxHeaderListSize}set maxHeadersCount(e){}}})),Sv=L(((e,t)=>{var n=R(`tls`);t.exports=(e={},t=n.connect)=>new Promise((n,r)=>{let i=!1,a,o=async()=>{await c,a.off(`timeout`,s),a.off(`error`,r),e.resolveSocket?(n({alpnProtocol:a.alpnProtocol,socket:a,timeout:i}),i&&(await Promise.resolve(),a.emit(`timeout`))):(a.destroy(),n({alpnProtocol:a.alpnProtocol,timeout:i}))},s=async()=>{i=!0,o()},c=(async()=>{try{a=await t(e,o),a.on(`error`,r),a.once(`timeout`,s)}catch(e){r(e)}})()})})),Cv=L(((e,t)=>{var n=R(`net`);t.exports=e=>{let t=e.host,r=e.headers&&e.headers.host;return r&&(t=r.startsWith(`[`)?r.indexOf(`]`)===-1?r:r.slice(1,-1):r.split(`:`,1)[0]),n.isIP(t)?``:t}})),wv=L(((e,t)=>{var n=R(`http`),r=R(`https`),i=Sv(),a=mv(),o=xv(),s=Cv(),c=_v(),l=new a({maxSize:100}),u=new Map,d=(e,t,n)=>{t._httpMessage={shouldKeepAlive:!0};let r=()=>{e.emit(`free`,t,n)};t.on(`free`,r);let i=()=>{e.removeSocket(t,n)};t.on(`close`,i);let a=()=>{e.removeSocket(t,n),t.off(`close`,i),t.off(`free`,r),t.off(`agentRemove`,a)};t.on(`agentRemove`,a),e.emit(`free`,t,n)},f=async e=>{let t=`${e.host}:${e.port}:${e.ALPNProtocols.sort()}`;if(!l.has(t)){if(u.has(t))return(await u.get(t)).alpnProtocol;let{path:n,agent:a}=e;e.path=e.socketPath;let o=i(e);u.set(t,o);try{let{socket:i,alpnProtocol:s}=await o;if(l.set(t,s),e.path=n,s===`h2`)i.destroy();else{let{globalAgent:t}=r,n=r.Agent.prototype.createConnection;a?a.createConnection===n?d(a,i,e):i.destroy():t.createConnection===n?d(t,i,e):i.destroy()}return u.delete(t),s}catch(e){throw u.delete(t),e}}return l.get(t)};t.exports=async(e,t,i)=>{if((typeof e==`string`||e instanceof URL)&&(e=c(new URL(e))),typeof t==`function`&&(i=t,t=void 0),t={ALPNProtocols:[`h2`,`http/1.1`],...e,...t,resolveSocket:!0},!Array.isArray(t.ALPNProtocols)||t.ALPNProtocols.length===0)throw Error("The `ALPNProtocols` option must be an Array with at least one entry");t.protocol=t.protocol||`https:`;let a=t.protocol===`https:`;t.host=t.hostname||t.host||`localhost`,t.session=t.tlsSession,t.servername=t.servername||s(t),t.port=t.port||(a?443:80),t._defaultAgent=a?r.globalAgent:n.globalAgent;let l=t.agent;if(l){if(l.addRequest)throw Error("The `options.agent` object can contain only `http`, `https` or `http2` properties");t.agent=l[a?`https`:`http`]}return a&&await f(t)===`h2`?(l&&(t.agent=l.http2),new o(t,i)):n.request(t,i)},t.exports.protocolCache=l})),Tv=L(((e,t)=>{var n=R(`http2`),r=hv(),i=xv(),a=gv(),o=wv(),s=(e,t,n)=>new i(e,t,n),c=(e,t,n)=>{let r=new i(e,t,n);return r.end(),r};t.exports={...n,ClientRequest:i,IncomingMessage:a,...r,request:s,get:c,auto:o}})),Ev=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=K_();e.default=e=>t.default.nodeStream(e)&&t.default.function_(e.getBoundary)})),Dv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=R(`fs`),n=R(`util`),r=K_(),i=Ev(),a=n.promisify(t.stat);e.default=async(e,o)=>{if(o&&`content-length`in o)return Number(o[`content-length`]);if(!e)return 0;if(r.default.string(e))return Buffer.byteLength(e);if(r.default.buffer(e))return e.length;if(i.default(e))return n.promisify(e.getLength.bind(e))();if(e instanceof t.ReadStream){let{size:t}=await a(e.path);return t===0?void 0:t}}})),Ov=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e,t,n){let r={};for(let i of n)r[i]=(...e)=>{t.emit(i,...e)},e.on(i,r[i]);return()=>{for(let t of n)e.off(t,r[t])}}e.default=t})),kv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=()=>{let e=[];return{once(t,n,r){t.once(n,r),e.push({origin:t,event:n,fn:r})},unhandleAll(){for(let t of e){let{origin:e,event:n,fn:r}=t;e.removeListener(n,r)}e.length=0}}}})),Av=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TimeoutError=void 0;var t=R(`net`),n=kv(),r=Symbol(`reentry`),i=()=>{},a=class extends Error{constructor(e,t){super(`Timeout awaiting '${t}' for ${e}ms`),this.event=t,this.name=`TimeoutError`,this.code=`ETIMEDOUT`}};e.TimeoutError=a,e.default=(e,o,s)=>{if(r in e)return i;e[r]=!0;let c=[],{once:l,unhandleAll:u}=n.default(),d=(e,t,n)=>{var r;let i=setTimeout(t,e,e,n);(r=i.unref)==null||r.call(i);let a=()=>{clearTimeout(i)};return c.push(a),a},{host:f,hostname:p}=s,m=(t,n)=>{e.destroy(new a(t,n))},h=()=>{for(let e of c)e();u()};if(e.once(`error`,t=>{if(h(),e.listenerCount(`error`)===0)throw t}),e.once(`close`,h),l(e,`response`,e=>{l(e,`end`,h)}),o.request!==void 0&&d(o.request,m,`request`),o.socket!==void 0){let t=()=>{m(o.socket,`socket`)};e.setTimeout(o.socket,t),c.push(()=>{e.removeListener(`timeout`,t)})}return l(e,`socket`,n=>{let{socketPath:r}=e;if(n.connecting){let e=!!(r??t.isIP(p??f??``)!==0);if(o.lookup!==void 0&&!e&&n.address().address===void 0){let e=d(o.lookup,m,`lookup`);l(n,`lookup`,e)}if(o.connect!==void 0){let t=()=>d(o.connect,m,`connect`);e?l(n,`connect`,t()):l(n,`lookup`,e=>{e===null&&l(n,`connect`,t())})}o.secureConnect!==void 0&&s.protocol===`https:`&&l(n,`connect`,()=>{let e=d(o.secureConnect,m,`secureConnect`);l(n,`secureConnect`,e)})}if(o.send!==void 0){let t=()=>d(o.send,m,`send`);n.connecting?l(n,`connect`,()=>{l(e,`upload-complete`,t())}):l(e,`upload-complete`,t())}}),o.response!==void 0&&l(e,`upload-complete`,()=>{let t=d(o.response,m,`response`);l(e,`response`,t)}),h}})),jv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=K_();e.default=e=>{e=e;let n={protocol:e.protocol,hostname:t.default.string(e.hostname)&&e.hostname.startsWith(`[`)?e.hostname.slice(1,-1):e.hostname,host:e.host,hash:e.hash,search:e.search,pathname:e.pathname,href:e.href,path:`${e.pathname||``}${e.search||``}`};return t.default.string(e.port)&&e.port.length>0&&(n.port=Number(e.port)),(e.username||e.password)&&(n.auth=`${e.username||``}:${e.password||``}`),n}})),Mv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=R(`url`),n=[`protocol`,`host`,`hostname`,`port`,`pathname`,`search`];e.default=(e,r)=>{if(r.path){if(r.pathname)throw TypeError("Parameters `path` and `pathname` are mutually exclusive.");if(r.search)throw TypeError("Parameters `path` and `search` are mutually exclusive.");if(r.searchParams)throw TypeError("Parameters `path` and `searchParams` are mutually exclusive.")}if(r.search&&r.searchParams)throw TypeError("Parameters `search` and `searchParams` are mutually exclusive.");if(!e){if(!r.protocol)throw TypeError(`No URL protocol specified`);e=`${r.protocol}//${r.hostname??r.host??``}`}let i=new t.URL(e);if(r.path){let e=r.path.indexOf(`?`);e===-1?r.pathname=r.path:(r.pathname=r.path.slice(0,e),r.search=r.path.slice(e+1)),delete r.path}for(let e of n)r[e]&&(i[e]=r[e].toString());return i}})),Nv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class{constructor(){this.weakMap=new WeakMap,this.map=new Map}set(e,t){typeof e==`object`?this.weakMap.set(e,t):this.map.set(e,t)}get(e){return typeof e==`object`?this.weakMap.get(e):this.map.get(e)}has(e){return typeof e==`object`?this.weakMap.has(e):this.map.has(e)}}})),Pv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=async e=>{let t=[],n=0;for await(let r of e)t.push(r),n+=Buffer.byteLength(r);return Buffer.isBuffer(t[0])?Buffer.concat(t,n):Buffer.from(t.join(``))}})),Fv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dnsLookupIpVersionToFamily=e.isDnsLookupIpVersion=void 0;var t={auto:0,ipv4:4,ipv6:6};e.isDnsLookupIpVersion=e=>e in t,e.dnsLookupIpVersionToFamily=n=>{if(e.isDnsLookupIpVersion(n))return t[n];throw Error(`Invalid DNS lookup IP version`)}})),Iv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isResponseOk=void 0,e.isResponseOk=e=>{let{statusCode:t}=e,n=e.request.options.followRedirect?299:399;return t>=200&&t<=n||t===304}})),Lv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=new Set;e.default=e=>{t.has(e)||(t.add(e),process.emitWarning(`Got: ${e}`,{type:`DeprecationWarning`}))}})),Rv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=K_();e.default=(e,n)=>{if(t.default.null_(e.encoding))throw TypeError("To get a Buffer, set `options.responseType` to `buffer` instead");t.assert.any([t.default.string,t.default.undefined],e.encoding),t.assert.any([t.default.boolean,t.default.undefined],e.resolveBodyOnly),t.assert.any([t.default.boolean,t.default.undefined],e.methodRewriting),t.assert.any([t.default.boolean,t.default.undefined],e.isStream),t.assert.any([t.default.string,t.default.undefined],e.responseType),e.responseType===void 0&&(e.responseType=`text`);let{retry:r}=e;if(e.retry=n?{...n.retry}:{calculateDelay:e=>e.computedValue,limit:0,methods:[],statusCodes:[],errorCodes:[],maxRetryAfter:void 0},t.default.object(r)?(e.retry={...e.retry,...r},e.retry.methods=[...new Set(e.retry.methods.map(e=>e.toUpperCase()))],e.retry.statusCodes=[...new Set(e.retry.statusCodes)],e.retry.errorCodes=[...new Set(e.retry.errorCodes)]):t.default.number(r)&&(e.retry.limit=r),t.default.undefined(e.retry.maxRetryAfter)&&(e.retry.maxRetryAfter=Math.min(...[e.timeout.request,e.timeout.connect].filter(t.default.number))),t.default.object(e.pagination)){n&&(e.pagination={...n.pagination,...e.pagination});let{pagination:r}=e;if(!t.default.function_(r.transform))throw Error("`options.pagination.transform` must be implemented");if(!t.default.function_(r.shouldContinue))throw Error("`options.pagination.shouldContinue` must be implemented");if(!t.default.function_(r.filter))throw TypeError("`options.pagination.filter` must be implemented");if(!t.default.function_(r.paginate))throw Error("`options.pagination.paginate` must be implemented")}return e.responseType===`json`&&e.headers.accept===void 0&&(e.headers.accept=`application/json`),e}})),zv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.retryAfterStatusCodes=void 0,e.retryAfterStatusCodes=new Set([413,429,503]),e.default=({attemptCount:e,retryOptions:t,error:n,retryAfter:r})=>{if(e>t.limit)return 0;let i=t.methods.includes(n.options.method),a=t.errorCodes.includes(n.code),o=n.response&&t.statusCodes.includes(n.response.statusCode);if(!i||!a&&!o)return 0;if(n.response){if(r)return t.maxRetryAfter===void 0||r>t.maxRetryAfter?0:r;if(n.response.statusCode===413)return 0}let s=Math.random()*100;return 2**(e-1)*1e3+s}})),Bv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.UnsupportedProtocolError=e.ReadError=e.TimeoutError=e.UploadError=e.CacheError=e.HTTPError=e.MaxRedirectsError=e.RequestError=e.setNonEnumerableProperties=e.knownHookEvents=e.withoutBody=e.kIsNormalizedAlready=void 0;var t=R(`util`),n=R(`stream`),r=R(`fs`),i=R(`url`),a=R(`http`),o=R(`http`),s=R(`https`),c=Y_(),l=X_(),u=dv(),d=pv(),f=Tv(),p=av(),m=K_(),h=Dv(),g=Ev(),_=Ov(),v=Av(),y=jv(),b=Mv(),x=Nv(),S=Pv(),C=Fv(),w=Iv(),T=Lv(),E=Rv(),D=zv(),O,k=Symbol(`request`),A=Symbol(`response`),j=Symbol(`responseSize`),M=Symbol(`downloadedSize`),N=Symbol(`bodySize`),P=Symbol(`uploadedSize`),F=Symbol(`serverResponsesPiped`),I=Symbol(`unproxyEvents`),ee=Symbol(`isFromCache`),te=Symbol(`cancelTimeouts`),ne=Symbol(`startedReading`),re=Symbol(`stopReading`),ie=Symbol(`triggerRead`),ae=Symbol(`body`),oe=Symbol(`jobs`),se=Symbol(`originalResponse`),ce=Symbol(`retryTimeout`);e.kIsNormalizedAlready=Symbol(`isNormalizedAlready`);var le=m.default.string(process.versions.brotli);e.withoutBody=new Set([`GET`,`HEAD`]),e.knownHookEvents=[`init`,`beforeRequest`,`beforeRedirect`,`beforeError`,`beforeRetry`,`afterResponse`];function ue(e){for(let t in e){let n=e[t];if(!m.default.string(n)&&!m.default.number(n)&&!m.default.boolean(n)&&!m.default.null_(n)&&!m.default.undefined(n))throw TypeError(`The \`searchParams\` value '${String(n)}' must be a string, number, boolean or null`)}}function de(e){return m.default.object(e)&&!(`statusCode`in e)}var fe=new x.default,pe=async e=>new Promise((t,n)=>{let r=e=>{n(e)};e.pending||t(),e.once(`error`,r),e.once(`ready`,()=>{e.off(`error`,r),t()})}),me=new Set([300,301,302,303,304,307,308]),he=[`context`,`body`,`json`,`form`];e.setNonEnumerableProperties=(e,t)=>{let n={};for(let t of e)if(t)for(let e of he)e in t&&(n[e]={writable:!0,configurable:!0,enumerable:!1,value:t[e]});Object.defineProperties(t,n)};var ge=class extends Error{constructor(e,t,n){if(super(e),Error.captureStackTrace(this,this.constructor),this.name=`RequestError`,this.code=t.code??`ERR_GOT_REQUEST_ERROR`,n instanceof we?(Object.defineProperty(this,"request",{enumerable:!1,value:n}),Object.defineProperty(this,"response",{enumerable:!1,value:n[A]}),Object.defineProperty(this,"options",{enumerable:!1,value:n.options})):Object.defineProperty(this,"options",{enumerable:!1,value:n}),this.timings=this.request?.timings,m.default.string(t.stack)&&m.default.string(this.stack)){let e=this.stack.indexOf(this.message)+this.message.length,n=this.stack.slice(e).split(`
|
|
68
|
+
`).filter(e=>e.trim()!==``),n=e=>`***redacted(${String(e)})***`,r=e=>e.toLowerCase().replace(/[-_]/g,``),i=e=>{if(e===null)return null;try{return JSON.parse(e)}catch{return e}},a=e=>{if(!e)return e;let t=!1,r={};for(let[i,a]of Object.entries(e))$f.has(i.toLowerCase())?(r[i]=n(a.length),t=!0):r[i]=a;return t?r:e},o=e=>{let t;try{t=new URL(e)}catch{return e}let i=!1;for(let[e,a]of Array.from(t.searchParams.entries()))ep.has(r(e))&&(t.searchParams.set(e,n(a.length)),i=!0);return i?t.toString():e},s=e.streaming,c=e.upstream,l=e.inbound.bodyText!==null||c.url!==null||c.responseText!==null||e.client.body!==void 0||e.client.streamText!==null,u=a(e.inbound.headers);return{time:e.time,method:e.http.method||void 0,path:e.http.path||void 0,model:e.route?.name||void 0,status:e.status,stream:s,error:e.error?.message??null,response:l?{_capture:!0,inbound_request:{url:o(e.http.url),headers:u,body:e.inbound.body??null},upstream_request:c.url?{url:o(c.url),headers:a(c.requestHeaders),body:i(c.requestBody)}:null,upstream_response_text:s?null:c.responseText,upstream_stream_frames:s?t(c.responseText):null,client_response:s?void 0:e.client.body,client_stream_frames:s?t(e.client.streamText):null,truncated:e.truncated}:null,input_tokens:e.usage?.inputTokens??0,output_tokens:e.usage?.outputTokens??0,cache_read_tokens:e.usage?.cacheReadInputTokens??0,cache_creation_tokens:e.usage?.cacheCreationInputTokens??0,ip:e.http.clientIp||null,session_id:e.http.sessionId||null,duration:e.durationMs,headers:u===null?null:JSON.stringify(u),client:qf(e.http.userAgent)}}function np(e,t){let n=tp(t),r=Number(t.requestId),i=Number.isSafeInteger(r)&&r>0?r:jd();e.write(i,n),Id(i,n),L(`[ezllm] ${t.requestId} ${t.route?.name??t.http.path} -> ${String(t.status)} ${String(t.durationMs)}ms streaming=${String(t.streaming)}`+(t.error===null?``:` error=${t.error.stage}: ${t.error.message}`))}var rp=class{#e;#t;#n;#r=[];#i=0;#a=!1;constructor(e={}){this.#e=e.spool??new pu,this.#t=e.queueCapacity??Zf,this.#n=e.queueMaxBytes??Qf}#o(){let e=this.#r.shift();return this.#i-=ip(e),e}async#s(){if(!this.#a){this.#a=!0;try{for(;this.#r.length>0;){await ou();try{np(this.#e,this.#o())}catch(e){R(`[ezllm] trace 落盘失败:`,$l(e))}}}finally{this.#a=!1}}}write(e){for(;this.#r.length>=this.#t||this.#i>=this.#n&&this.#r.length>0;)this.#o(),gt(`[ezllm] trace 队列已满(${String(this.#t)} 条 / ${String(Math.round(this.#n/1024/1024))}MB),丢弃最旧一条`);this.#r.push(e),this.#i+=ip(e),this.#s()}async flush(){for(;this.#r.length>0||this.#a;)await ou();await this.#e.flush()}flushSync(){for(;this.#r.length>0;)try{np(this.#e,this.#o())}catch(e){R(`[ezllm] trace 崩溃前落盘失败:`,$l(e))}this.#e.flushSync()}};function ip(e){return(e.inbound.bodyText?.length??0)+(e.upstream.requestBody?.length??0)+(e.upstream.responseText?.length??0)+(e.client.streamText?.length??0)+4096}var ap=48;function op(e){let t=e.trim();if(t===``)return``;let n=t.split(/\s+/)[0]??t;return n.length>ap?n.slice(0,ap):n}var sp=500;function cp(e={}){let t=e=>{let t=e.headers;if(typeof t==`string`&&t!==``)return t;let n=e.response;if(typeof n!=`object`||!n)return null;let r=n.inbound_request;if(typeof r!=`object`||!r)return null;let i=r.headers;return typeof i!=`object`||!i||Array.isArray(i)||Object.entries(i).length===0?null:JSON.stringify(i)},n=(e,t)=>{let n=e.get(yu`SELECT detail FROM log_details WHERE log_id = ${t}`);if(n===void 0)return null;try{return JSON.parse(qd(n.detail).toString(`utf-8`))}catch{return null}},r=q(),i={days:0,scanned:0,filled:0,skipped:0,uas:0,clientsAssigned:0},a=Wd.listDetailDates();for(let o of a){let a=r.all(yu`SELECT id FROM logs WHERE date = ${o} AND headers IS NULL`).map(e=>Number(e.id));if(a.length===0)continue;i.days++;let s=Wd.openIfExists(o);if(s===null){i.skipped+=a.length,e.onProgress?.(`${o}: 详情库不存在,跳过 ${String(a.length)} 行`);continue}let c=new Set,l=[],u=()=>{if(l.length===0)return;let e=l;l=[],Ed(()=>{for(let t of e)r.run(yu`UPDATE logs SET headers = ${t.headers} WHERE id = ${t.id} AND headers IS NULL`)})};for(let e of a){i.scanned++;let r=n(s,e),a=r===null?null:t(r);if(a===null){i.skipped++;continue}l.push({id:e,headers:a}),i.filled++;let o=tu(a);o!==``&&c.add(o),l.length>=sp&&u()}u(),c.size>0&&(i.uas+=zf([...c])),e.onProgress?.(`${o}: 扫描 ${String(a.length)} 行,回填 ${String(i.filled)} 行(累计)`)}if(a.length>0){let e=r.select(K).columns({n:G.count()}).where(G.and(G.isNull(K.headers),G.not(G.in(K.date,a)))).get();i.skipped+=Number(e?.n??0)}for(let e of Bf())i.clientsAssigned+=Vf(e.ua,e.client);return i}var lp=2e3,up=500;function dp(e={}){let t=e=>{let t;try{t=JSON.parse(e)}catch{return``}if(typeof t!=`object`||!t||Array.isArray(t))return``;try{let e=new Headers;for(let[n,r]of Object.entries(t))typeof r==`string`&&e.set(n,r);return Gc(e)}catch{return``}},n=(e,t)=>{t.length!==0&&Ed(()=>{for(let n of t)e.run(yu`
|
|
69
|
+
UPDATE logs SET session_id = ${n.sessionId}
|
|
70
|
+
WHERE id = ${n.id} AND (session_id IS NULL OR session_id = '')
|
|
71
|
+
`)})},r=q(),i={scanned:0,filled:0},a=0;for(;;){let o=r.all(yu`
|
|
72
|
+
SELECT id, headers FROM logs
|
|
73
|
+
WHERE id > ${a}
|
|
74
|
+
AND (session_id IS NULL OR session_id = '')
|
|
75
|
+
AND headers IS NOT NULL
|
|
76
|
+
ORDER BY id
|
|
77
|
+
LIMIT ${lp}
|
|
78
|
+
`);if(o.length===0)break;let s=[];for(let e of o){a=Number(e.id),i.scanned++;let o=t(e.headers);o!==``&&(s.push({id:Number(e.id),sessionId:o}),i.filled++,s.length>=up&&(n(r,s),s.length=0))}n(r,s),e.onProgress?.(`已扫描到 id ${String(a)}:写入 ${String(i.filled)} 行(累计)`)}return i}async function fp(e){let t=()=>{for(let e of Et())if(f(e))return e;return null},n=(e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=n.default??n[`module.exports`]??n;if(typeof r!=`object`||!r)return null;let i=r;return typeof i.onModelRequest==`function`?{onModelRequest:i.onModelRequest}:(gt(`[ezllm] ${t} 未导出 onModelRequest 函数,已忽略(不挂任何钩子)`),null)},r=t();if(r===null)return;let i;try{i=await import(j(r).href)}catch(e){R(`[ezllm] 加载用户钩子失败,本次按无钩子运行:${r}`),R(`[ezllm] 原因:${e instanceof Error?e.message:String(e)}`),R(`[ezllm] 提示:模块写法与文件扩展名不匹配。CJS 内容(module.exports)请用 hook.cjs,ESM 内容(export default)请用 hook.mjs——这两个扩展名强制解析模式,不受任何 package.json 的 type 影响`);return}let a=n(i,r);a?.onModelRequest!==void 0&&(e.addHook(`onModelRequest`,a.onModelRequest),L(`[ezllm] 已加载用户钩子:${r}(onModelRequest)`))}function pp(e){return ht.PORT??e.port}async function mp(e,t,n={}){let r=new Cl({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(jd())}});t.register(r),await fp(r);let i={current:r,port:r.expanded.port,rebuild(e){i.current.reload(e),i.port=i.current.expanded.port;let t=i.current.expanded.deployments.names.length,n=e.providers.filter(e=>e.enabled===!1).length,r=n>0?`(${String(n)} 个已停用)`:``;L(`[gateway] 配置已热更新: ${String(e.providers.length)} 个供应商${r} / ${String(t)} 个模型`)},proxy:new er},a=async e=>{let t=new URL(e.req.url),n=new Headers(e.req.raw.headers);if(!n.has(`x-forwarded-for`)){let t=e.env?.incoming?.socket?.remoteAddress??``;t!==``&&n.set(`x-forwarded-for`,t)}if(!n.has(`authorization`)&&n.has(`x-api-key`)){let e=n.get(`x-api-key`)??``;e!==``&&n.set(`authorization`,`Bearer ${e}`)}return i.current.build().fetch(new Request(t.toString(),{method:e.req.raw.method,headers:n,body:e.req.raw.body,duplex:`half`}))};return i.proxy.use(`/v1/models`,async(e,n)=>{let r=e.req.header(`authorization`)??(e.req.header(`x-api-key`)===null?``:`Bearer ${e.req.header(`x-api-key`)}`);if(!await t.authorize(r))return Response.json({error:{message:`Unauthorized: invalid api key`,type:`authentication_error`,code:`401`}},{status:401});await n()}),i.proxy.all(`/v1/*`,e=>a(e)),i.proxy.all(`/v1`,e=>a(e)),i.proxy.all(`/responses`,e=>a(e)),i.proxy.all(`/chat/completions`,e=>a(e)),i.proxy.all(`/messages`,e=>a(e)),i.proxy.all(`/messages/count_tokens`,e=>a(e)),i.proxy.all(`/models`,e=>a(e)),i.proxy.all(`/healthz`,e=>a(e)),i}var hp=64;function gp(e,t={}){let n=e=>e.trim(),r=new Map;function i(e,t){for(r.delete(e),r.set(e,t);r.size>hp;){let e=r.keys().next().value;if(e===void 0)break;r.delete(e)}}function a(){return new Set(t.knownModelNames?t.knownModelNames():e.expanded.deployments.names)}e.plugin(e=>{e.addHook(`onFinish`,e=>{if(e.status!==200||e.ctx.model===null)return;let t=n(e.ctx.userAgent);t!==``&&i(t,e.ctx.model.name)}),e.addHook(`onModelNotFound`,t=>{if(a().has(t.requestedModel))return;let i=n(t.userAgent);if(i===``)return;let o=r.get(i);if(o!==void 0){if(!e.expanded.deployments.byName.has(o)){r.delete(i);return}return o}})})}var _p=e=>{let t={origin:`*`,allowMethods:[`GET`,`HEAD`,`PUT`,`POST`,`DELETE`,`PATCH`,`QUERY`],allowHeaders:[],exposeHeaders:[],...e},n=t.exposeHeaders?.length?t.exposeHeaders.join(`,`):void 0,r=t.allowHeaders?.length?t.allowHeaders.join(`,`):void 0,i=(e=>typeof e==`string`?e===`*`?()=>e:t=>e===t?t:null:typeof e==`function`?e:t=>e.includes(t)?t:null)(t.origin),a=(e=>{if(typeof e==`function`)return async(t,n)=>(await e(t,n)).join(`,`);if(Array.isArray(e)){let t=e.join(`,`);return()=>t}return()=>``})(t.allowMethods);return async function(e,o){function s(t,n){e.res.headers.set(t,n)}let c=await i(e.req.header(`origin`)||``,e);if(c&&s(`Access-Control-Allow-Origin`,c),t.credentials&&s(`Access-Control-Allow-Credentials`,`true`),n&&s(`Access-Control-Expose-Headers`,n),e.req.method===`OPTIONS`){t.origin!==`*`&&e.res.headers.append(`Vary`,`Origin`),t.maxAge!=null&&s(`Access-Control-Max-Age`,t.maxAge.toString());let n=await a(e.req.header(`origin`)||``,e);n&&s(`Access-Control-Allow-Methods`,n);let i=r;if(!i){let t=e.req.header(`Access-Control-Request-Headers`);t&&(i=t.split(`,`).map(e=>e.trim()).join(`,`))}return i&&(s(`Access-Control-Allow-Headers`,i),e.res.headers.append(`Vary`,`Access-Control-Request-Headers`)),e.res.headers.delete(`Content-Length`),e.res.headers.delete(`Content-Type`),new Response(null,{headers:e.res.headers,status:204,statusText:`No Content`})}await o(),t.origin!==`*`&&e.header(`Vary`,`Origin`,{append:!0})}};async function vp(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var yp=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,bp=new er;function xp(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}bp.post(`/login`,async e=>{let t=zl();if(t.configBroken)return e.json({error:yp},503);if(!t.required)return e.json({error:`当前未设置登录账号,管理台免登录访问(如需启用请先设置账号)`},400);let n=await vp(e);if(n===null)return e.json({error:`请求体格式错误`},400);let{username:r,password:i}=n;return(r??``).trim()!==t.username||i!==t.password?e.json({error:`用户名或密码错误`},401):e.json({token:xp(t)})});async function Sp(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=zl();if(!n.required)return await t();if(n.configBroken)return e.json({error:yp},401);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==xp(n))return e.json({error:`token 无效或已过期`},401);await t()}var Cp=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function wp(e,t){return e instanceof Cp?(e.status>=500&&R(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e.message),t.json({error:e.message},e.status)):(R(`[ezllm] ${t.req.method} ${t.req.path} 失败:`,e instanceof Error?e.message:e),t.json({ok:!1,error:e instanceof Error?e.message:String(e)},500))}function Tp(e){return async t=>{try{return await e(t)}catch(e){throw new Cp(500,e.message)}}}var Ep=8,Dp=6;function Op(){let e=()=>{let e=Dl();if(e===null)throw new Cp(500,`配置文件不存在`);return e},t=new er;return t.onError(wp),t.use(`*`,async(e,t)=>{if(e.req.method===`GET`)return t();let n=e.req.header(`sec-fetch-site`);if(n===`same-origin`||n===`none`)return t();let r=e.req.header(`origin`);return r===void 0||r.toLowerCase()===new URL(e.req.url).origin.toLowerCase()?t():e.json({error:`已拒绝跨站写请求`},403)}),t.get(`/status`,e=>{let t=Bl(),n=!1;try{n=Il()!==``}catch(e){if(!(e instanceof El))throw e}return e.json({initialized:t.completed,deployment:t.deployment,masterKeySet:n,authRequired:zl().required,version:Ft()})}),t.post(`/master-key`,async t=>{if(Bl().completed)return t.json({error:`已完成初始化,请到设置页修改主密钥`},403);let n=await vp(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r;if(n.mode===`generate`)r=N(32).toString(`base64url`);else if(n.mode===`custom`){if(r=(n.masterKey??``).trim(),r.length<Ep)return t.json({error:`主密钥至少 ${String(Ep)} 位`},400)}else return t.json({error:`mode 必须是 generate 或 custom`},400);let i=e(),a={...i,masterKey:r};return kl(a),t.json({masterKey:r,...Ul(i,a)?{restartHint:Pl}:{}})}),t.post(`/finish`,async t=>{if(Bl().completed)return t.json({error:`已完成初始化,请到设置页修改`},403);let n=await vp(t);if(n===null)return t.json({error:`请求体格式错误`},400);let r=n.deployment;if(r!==`local`&&r!==`server`)return t.json({error:`deployment 必须是 local 或 server`},400);if(r===`server`&&Il()===``)return t.json({error:`服务器部署必须设置主密钥,防止 /v1 网关被他人盗用`},400);let i=(n.username??``).trim(),a=n.password??``,o=i!==``||a!==``;if(o){if(i===``||a===``)return t.json({error:`用户名和密码需同时提供`},400);if(a.length<Dp)return t.json({error:`密码至少 ${String(Dp)} 位`},400)}else if(r===`server`)return t.json({error:`服务器部署必须设置登录账号密码,防止管理台被陌生人登录`},400);let s=e(),c={...s,setup:{completed:!0,deployment:r},allowLan:r===`server`,...o?{"web-ui":{...s[`web-ui`],"login-account":{username:i,password:a}}}:{}};return kl(c),t.json({message:o?`初始化完成,请使用新账号登录`:`初始化完成`,...Ul(s,c)?{restartHint:Pl}:{}})}),t}function kp(e){let t=new er;return t.onError(wp),t.get(`/`,Tp(e=>{let t=Dl();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,Tp(async t=>{let n=await t.req.json();if(typeof n!=`object`||!n||!Array.isArray(n.providers))return t.json({error:`配置格式错误:providers 必须是数组`},400);try{jl(n)}catch(e){if(e instanceof lr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let r=null;try{r=Dl()}catch{r=null}return kl(n),e.runtime.rebuild(Al(n)),t.json({message:`配置已保存并生效`,...Ul(r,n)?{restartHint:Pl}:{}})})),t}var Ap=`直接回复我 ok,不要思考不要解释`;function jp(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function Mp(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function Np(e){let t=new er;t.onError(wp);let n=Bt(`test-results.json`),r=Bt(`models-cache.json`);function i(e,t=`openai`,n=!0){let r=e.replace(/\/+$/,``);return t===`anthropic`&&r.endsWith(`/anthropic`)&&(r=r.slice(0,-10)),`${jp(r,n)}/models`}function a(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();if(e.includes(`authorization`)||e.includes(`api-key`)||e.includes(`token`)){let e=String(r);t[n]=e.length>8?`${e.slice(0,3)}****${e.slice(-4)}`:`****`}else t[n]=r}return t}async function o(e,t,n,r){return fetch(i(e,n,r),{headers:Mp(t,n),signal:AbortSignal.timeout(1e4)})}async function s(e,t){if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`});let n=await o(t.api_base,t.api_key,t.protocol??`openai`,t.autoV1??!0);return n.ok?await n.json():e.json({status:`error`,message:`HTTP ${String(n.status)}`})}function c(e){let{response:t,data:n,latency:r,url:i,headers:o,payload:s}=e;if(t.ok&&(n.choices!==void 0||n.output!==void 0||n.content!==void 0))return{status:`ok`,message:`${String(n.usage?.completion_tokens??n.usage?.output_tokens??0)} tokens`,latency:r,request:{method:`POST`,url:i,headers:a(o),body:s},response:{status:t.status,body:n}};let c=typeof n.error==`object`&&n.error!==null&&`message`in n.error?String(n.error.message):typeof n.error==`string`?n.error:`HTTP ${String(t.status)}`;return{status:`error`,message:l(typeof c==`string`?c:JSON.stringify(c)),latency:r,request:{method:`POST`,url:i,headers:a(o),body:s},response:{status:t.status,body:n}}}function l(e){let t=e;for(let[e,n]of[[/Weekly usage limit reached/i,`每周使用限额已达上限`],[/Resets in (\d+) day/i,`$1 天后重置`],[/RateLimitError:?\s*OpenAIException\s*-?\s*/gi,``],[/RateLimitError/g,`频率限制`],[/Rate limit/gi,`请求频率超限`],[/Invalid.*api.?key/i,`API Key 无效`],[/Unauthorized/i,`认证失败`],[/Not found/i,`模型或端点不存在`],[/Timeout/i,`请求超时`],[/Connection refused/i,`连接被拒绝`],[/ECONNREFUSED/i,`连接被拒绝`],[/ENOTFOUND/i,`域名无法解析`],[/model.*not.*found/i,`模型不存在`],[/context length exceeded/i,`上下文长度超限`],[/maximum context length/i,`超过最大上下文长度`],[/overloaded/i,`服务过载`],[/internal server error/i,`服务器内部错误`],[/bad gateway/i,`网关错误`],[/OpenAIException\s*-?\s*/i,``],[/To continue using[\s\S]*$/i,``],[/Received Model Group[\s\S]*$/i,``],[/Available Model Group[\s\S]*$/i,``],[/HTTP (\d+)/,`HTTP 错误 $1`]])t=t.replace(e,n);return t=t.replace(/\s+/g,` `).replace(/^[.:;\s-]+|[.:;\s-]+$/g,``).trim(),t||=e,t.length>120&&(t=t.substring(0,120)+`...`),t}t.get(`/results`,Tp(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,Tp(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,Tp(async e=>{let{keyId:t,models:n}=await e.req.json();return!t||!Array.isArray(n)?e.json({error:`缺少必要参数: keyId, models`},400):(r.set(t,n),e.json({message:`模型缓存已更新`,keyId:t,count:n.length}))})),t.post(`/`,async e=>{try{let t=await s(e,await e.req.json());return t instanceof Response?t:e.json({status:`ok`,models:t.data?.length||0,protocol:`openai`})}catch(t){return e.json({status:`error`,message:t.message})}}),t.post(`/fetch-models`,async e=>{try{let t=await e.req.json(),n=await s(e,t);if(n instanceof Response)return n;let i=(n.data||[]).map(e=>e.id||e.name).filter(e=>!!e);if(t.keyId){let e=r.get(t.keyId)??[],n=[...new Set([...e,...i])];r.set(t.keyId,n)}return e.json({status:`ok`,models:i})}catch(t){return e.json({status:`error`,message:t.message})}});function u(e,t){return t===`anthropic`?{model:e,messages:[{role:`user`,content:Ap}],max_tokens:16}:t===`openai-responses`?{model:e,input:Ap}:{model:e,messages:[{role:`user`,content:Ap}]}}async function d(e){let t=e.protocol||`openai`,n=e.autoV1??!0,r=e.api_base.replace(/\/+$/,``);if(!r)throw Error(`api_base 不能为空`);let i={"Content-Type":`application/json`,...Mp(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${jp(r,n)}${a}`,s=u(e.model,t),l=Date.now(),d=await fetch(o,{method:`POST`,headers:i,body:JSON.stringify(s),signal:AbortSignal.timeout(3e4)}),f=Date.now()-l;return c({response:d,data:await d.json().catch(()=>({})),latency:f,url:o,headers:i,payload:s})}function f(e){let t=Dl();for(let n of t?.providers??[]){let t=n.models?.find(t=>t?.modelName===e);if(t)return t.customLlmProvider??n.customLlmProvider??`openai`}return`openai`}async function p(t,n){let r=Il(),i=pp(e),a=`http://127.0.0.1:${String(i)}`,o={"Content-Type":`application/json`};r&&(o.Authorization=`Bearer ${r}`);let s=`${a}${n===`anthropic`?`/v1/messages`:n===`openai-responses`?`/v1/responses`:`/v1/chat/completions`}`,l=u(t,n),d=Date.now(),f;try{f=await fetch(s,{method:`POST`,headers:o,body:JSON.stringify(l),signal:AbortSignal.timeout(3e4)})}catch(e){let t=e;throw R(`[test] 网关自调用失败:`,t.message,`cause:`,t.cause?.message??`n/a`),e}let p=Date.now()-d,m=await f.json().catch(()=>({}));return c({response:f,data:m,latency:p,url:s,headers:o,payload:l})}return t.post(`/model`,async e=>{try{let t=await e.req.json(),r=t.model;if(!r)return e.json({status:`error`,message:`缺少 model 参数`},400);if(!t.api_base||!t.api_key)return e.json({status:`error`,message:`缺少 api_base 或 api_key 参数`},400);let i;try{i=await d({model:r,api_base:t.api_base,api_key:t.api_key,protocol:t.protocol,autoV1:t.autoV1})}catch(e){i={status:`error`,message:l(e.message),latency:0}}return n.set(r,{...i,time:new Date().toISOString()}),e.json(i)}catch(t){return e.json({status:`error`,message:l(t.message)})}}),t.post(`/proxy`,async e=>{try{let t=(await e.req.json()).model;if(!t)return e.json({status:`error`,message:`缺少 model 参数`},400);let r=await p(t,f(t));return n.set(t,{...r,time:new Date().toISOString()}),e.json(r)}catch(t){return e.json({status:`error`,message:l(t.message)})}}),t}var Pp=ku(`latency_probes`,{id:Eu().primaryKey({autoIncrement:!0}),model:Tu().notNull(),time:Eu().notNull(),latency_ms:Eu().notNull(),ok:Eu().notNull(),error:Tu()},[Ou(`idx_latency_probes_model_time`).on(`model`,`time`),Ou(`idx_latency_probes_time`).on(`time`)]),Fp=2592e6,Ip=null;function Lp(){let e=Ip;if(e!==null)return e;let t=fd(`latency`);return t.createTables([Pp]),Ip=t,t}function Rp(){return Lp().native}function zp(e){if(e.length!==0)try{Lp().insert(Pp).values(e.map(e=>({model:e.model,time:e.time,latency_ms:e.latencyMs,ok:+!!e.ok,error:e.error??null}))).run()}catch(e){R(`[latency] 探测记录写入失败:`,e instanceof Error?e.message:String(e))}}function Bp(){let e=Date.now()-Fp;return Lp().select(Pp).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(G.gt(Pp.time,e)).orderBy(G.asc(Pp.time)).all().map(e=>({model:e.model,time:Number(e.time),latencyMs:Number(e.latency_ms),ok:e.ok===1,error:e.error??void 0}))}function Vp(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=Lp().select(Pp).columns([`time`,`latency_ms`,`ok`]).where(G.and(G.eq(Pp.model,e),G.gt(Pp.time,a),G.lte(Pp.time,r))).all();if(o.length===0)return[];let s=e=>{let n=new Date(e);return t===`hour`?new Date(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours()).getTime():new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime()},c=[];for(let e=s(r);e>=s(a);e-=i)c.unshift(e);let l=new Map;for(let e of c)l.set(e,{total:0,success:0,latencySum:0});for(let e of o){let t=l.get(s(Number(e.time)));t&&(t.total+=1,e.ok===1&&(t.success+=1,t.latencySum+=Number(e.latency_ms)))}return c.map(e=>{let t=l.get(e);return{bucketStart:e,total:t.total,success:t.success,failed:t.total-t.success,successRate:t.total===0?null:Math.round(t.success/t.total*1e3)/10,avgLatencyMs:t.success===0?null:Math.round(t.latencySum/t.success)}})}function Hp(){let e=Lp().select(Pp).columns({t:G.max(Pp.time)}).get();return e?.t==null?null:Number(e.t)}function Up(e){try{let t=Date.now()-e;Lp().delete(Pp).where(G.lte(Pp.time,t)).run()}catch(e){R(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var Wp=3e4,Gp=4,Kp=!1;function qp(){return Kp}function Jp(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function Yp(e){let t=async e=>{let t=jp((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?Mp(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:Ap}],max_tokens:1}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:Ap,max_output_tokens:16}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:Ap}],max_tokens:1});let a=Date.now();try{let t=await fetch(r,{method:`POST`,headers:n,body:JSON.stringify(i),signal:AbortSignal.timeout(Wp)}),o=Date.now()-a;if(!t.ok){let n=await t.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,120)).catch(()=>``);return{model:e.name,time:a,latencyMs:0,ok:!1,error:n?`HTTP ${String(t.status)}: ${n}`:`HTTP ${String(t.status)}`}}return await t.arrayBuffer().catch(()=>void 0),{model:e.name,time:a,latencyMs:o,ok:!0}}catch(t){return{model:e.name,time:a,latencyMs:0,ok:!1,error:t.message}}},n=async e=>{let n=[],r=0,i=Array.from({length:Math.max(1,Math.min(Gp,e.length))},async()=>{for(;;){let i=r++;if(i>=e.length)return;n.push(await t(e[i]))}});return await Promise.all(i),n};if(Kp)return!1;Kp=!0;try{let t=await n(Jp(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));zp(t),Up(Fp);let r=t.filter(e=>e.ok).length;return L(`[latency] 测试完成: ${String(t.length)} 个模型(成功 ${String(r)}),数据已入库 latency.db`),!0}catch(e){return R(`[latency] 测试执行失败:`,e instanceof Error?e.message:String(e)),!0}finally{Kp=!1}}function Xp(e){return Jp(e).length}var Zp=[{key:`avg10m`,ms:6e5},{key:`avg30m`,ms:18e5},{key:`avg1h`,ms:36e5},{key:`avg2h`,ms:72e5},{key:`avg5h`,ms:18e6},{key:`avg8h`,ms:288e5},{key:`avg12h`,ms:432e5},{key:`avg24h`,ms:864e5}];function Qp(e,t,n){return n.map(n=>{let r=e.filter(e=>e.model===n),i={model:n,avg10m:null,avg30m:null,avg1h:null,avg2h:null,avg5h:null,avg8h:null,avg12h:null,avg24h:null,lastTestAt:null,lastOk:null,lastLatencyMs:null,lastError:null},a=r.reduce((e,t)=>e===null||t.time>e.time?t:e,null);a!==null&&(i.lastTestAt=a.time,i.lastOk=a.ok,a.ok&&(i.lastLatencyMs=a.latencyMs),a.ok||(i.lastError=a.error??null));for(let{key:e,ms:n}of Zp){let a=r.filter(e=>e.ok&&e.time>t-n&&e.time<=t);a.length!==0&&(i[e]=Math.round(a.reduce((e,t)=>e+t.latencyMs,0)/a.length))}return i})}function $p(e){let t=new er;return t.get(`/history`,t=>{let n=Bp(),r=Date.now();return t.json({running:qp(),lastRunAt:Hp(),models:Qp(n,r,e.current.expanded.deployments.names)})}),t.get(`/trend`,e=>{let t=e.req.query(`model`);if(!t)return e.json({ok:!1,error:`缺少 model 参数`},400);let n=e.req.query(`granularity`)===`day`?`day`:`hour`,r=Vp(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>qp()?t.json({ok:!1,error:`测试进行中,请稍候`},409):Xp(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(Yp(e),t.json({ok:!0,running:!0}))),t}function em(){let e=t=>{let n=0;if(!f(t))return 0;for(let r of g(t)){let i=E(t,r),a;try{a=b(i)}catch{continue}a.isDirectory()?n+=e(i):n+=a.size}return n},t=()=>Math.round(e(bt())/1024/1024*10)/10,n=new er;return n.onError(wp),n.get(`/`,Tp(e=>{let n=e.req.query(),r=uf({startDate:n.startDate,endDate:n.endDate,model:n.model});return e.json({...r,logStorageMB:t()})})),n}function J(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Y(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function tm(e){return typeof e==`string`?e:null}function nm(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function rm(e,t){let n=nm(e,t);return n===void 0?void 0:e[n]}function im(e,t){if(e===void 0)return null;for(let n of e.split(`;`)){let e=n.indexOf(`=`);if(e!==-1&&n.slice(0,e).trim()===t)return n.slice(e+1).trim()}return null}function am(e){try{return new URL(e).hostname.toLowerCase()}catch{return``}}function om(e){let t=(e,t)=>{let n=e[t];if(n!==`"`&&n!==`'`&&n!=="`")return null;let r=t+1,i=``;for(;r<e.length;){let t=e[r];if(t===`\\`){i+=e[r+1]??``,r+=2;continue}if(t===n)return{value:i,end:r+1};i+=t,r+=1}return null},n=(e,n)=>{let r=(e,t)=>{let n=t;for(;n<e.length&&/\s/.test(e[n]);)n+=1;return n},i=(e,n)=>{if(e[n]!==`{`)return null;let r=0,i=n;for(;i<e.length;){let a=e[i];if(a===`"`||a===`'`||a==="`"){let n=t(e,i);if(n===null)return null;i=n.end;continue}if(a===`{`)r+=1;else if(a===`}`&&(--r,r===0))return{raw:e.slice(n,i+1),end:i+1};i+=1}return null},a=e=>{let n=e=>{let n=``,r=0;for(;r<e.length;){let i=e[r];if(i===`"`||i===`'`||i==="`"){let i=t(e,r);if(i===null){n+=e.slice(r);break}n+=e.slice(r,i.end),r=i.end;continue}if(i===`,`){let t=r+1;for(;t<e.length&&/\s/.test(e[t]);)t+=1;let n=e[t];if(n===`}`||n===`]`){r+=1;continue}}n+=i,r+=1}return n},r;try{r=JSON.parse(n(e))}catch{return null}let i=J(r);if(i===null)return null;let a={},o=J(i.headers);if(o!==null)for(let[e,t]of Object.entries(o))typeof t==`string`&&(a[e]=t);return{method:typeof i.method==`string`?i.method.toUpperCase():`GET`,headers:a,body:typeof i.body==`string`?i.body:null}},o=r(e,n),s=t(e,o);if(s===null)return null;let c=s.value,l=r(e,s.end);if(e[l]!==`,`)return{url:c,method:`GET`,headers:{},body:null};let u=i(e,r(e,l+1));if(u===null)return{url:c,method:`GET`,headers:{},body:null};let d=a(u.raw);if(d===null)throw Error(`无法解析 fetch 的 options 对象(可能复制不完整,请重新复制完整的 fetch 调用)`);return{url:c,method:d.method,headers:d.headers,body:d.body}},r=e=>{let t=new Map;for(let n of e){let e=nm(n.headers,`cookie`);if(e===void 0)continue;let r=am(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if(nm(e.headers,`cookie`)!==void 0)return e;let n=am(e.url),r=n===``?void 0:t.get(n);return r===void 0?e:{...e,headers:{...e.headers,[r.key]:r.value}}})},i=[],a=/\bfetch\s*\(/g,o;for(;(o=a.exec(e))!==null;){let t=n(e,o.index+o[0].length);t!==null&&i.push(t)}return r(i)}function sm(e){return e.some(e=>nm(e.headers,`cookie`)!==void 0)}var cm=0xe8d4a51000,lm=3e4;async function um(e,t){let n=e=>{let t={...e};for(let e of Object.keys(t)){let n=e.toLowerCase();(n===`content-length`||n===`host`||n===`connection`)&&delete t[e]}return t},r=await fetch(e,{...t,headers:n(t.headers),signal:AbortSignal.timeout(lm)});if(!r.ok){let e=await r.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,160)).catch(()=>``);throw Error(`HTTP ${String(r.status)}${e===``?``:`: ${e}`}`)}let i=J(await r.json());if(i===null)throw Error(`响应不是 JSON 对象`);return i}function dm(e){return e===null||e<=0?null:Math.round(e<cm?e*1e3:e)}function fm(e){return Math.round(e*100)/100}function pm(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function mm(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function hm(e,t){let n=J(e);if(n===null)return null;let r=Y(n[t.used])??0,i=Y(n[t.cap]),a=t.exceeded!==void 0&&n[t.exceeded]===!0||i!==null&&r>=i;return{used:r,cap:i,resetAt:t.resetAt===void 0?null:dm(Y(n[t.resetAt])),exceeded:a}}var gm=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await um(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await um(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},_m=`https://api.commandcode.ai`,vm=`/alpha/billing/credits`,ym=`/alpha/usage/summary`,bm=`/alpha/billing/subscriptions`,xm={"individual-pro-v1":80,"individual-goat":70},Sm=/^user_[A-Za-z0-9_-]+$/,Cm={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function wm(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:pm(t)}]}function Tm(e){let t=tm(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var Em=class extends gm{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=Sm;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!Sm.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super(_m,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(ym),this.get(vm),this.get(bm).catch(()=>null)]),r=J(t.windowLimits),i=J(t.credits),a=n===null?null:J(n.data),o=a===null?null:tm(a.planId),s=o===null?null:xm[o]??null,c=i===null?null:Y(i.monthlyCredits),l=s===null||c===null?null:{used:fm(Math.max(0,s-c)),cap:s,resetAt:a===null?null:Tm(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:hm(r.fiveHour,Cm),weekly:r===null?null:hm(r.weekly,Cm),monthly:l,totalTokens:Y(e.totalTokens),totalRuns:Y(e.totalCount),voucherBalance:null,balance:null,extraStats:wm(l,c)}}},Dm=`platform.deepseek.com`,Om=`/api/v0/users/get_user_summary`,km=`/api/v0/usage/by_api_key/cost`,Am=`/api/v0/usage/by_api_key/amount`,jm=86400;function Mm(e){let t=Y(e);if(t!==null)return t;let n=tm(e);if(n!==null&&n.trim()!==``){let e=Number(n);if(Number.isFinite(e))return e}return null}function Nm(e){if(e.size===0)return null;if(e.size===1){let[t,n]=[...e.entries()][0];return{amount:n,currency:t}}let t=e.has(`CNY`)?`CNY`:[...e.keys()].sort()[0];return{amount:e.get(t),currency:t}}function Pm(e){let t=new Date,n=-t.getTimezoneOffset()*60,r=new Date(t.getFullYear(),t.getMonth(),t.getDate()+e),i=Math.floor(r.getTime()/1e3);return{start:String(i),end:String(i+jm),tz:String(n)}}function Fm(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){let e=J(n);if(e===null)continue;let r=Mm(e.balance)??Mm(e.amount),i=tm(e.currency);r!==null&&i!==null&&i!==``&&t.set(i,(t.get(i)??0)+r)}return t}var Im=class extends gm{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static hosts=[Dm];static apiHosts=[`api.deepseek.com`];static credentialSource=`fetchText`;constructor(e){let t=om(e).find(e=>am(e.url)===Dm);if(t===void 0)throw Error(`未找到 DeepSeek 平台请求:请在已登录的 DeepSeek 开放平台(platform.deepseek.com)的用量页面里复制接口请求的 fetch 调用粘贴进来`);if(rm(t.headers,`cookie`)===void 0&&rm(t.headers,`authorization`)===void 0)throw Error(`复制的请求里没有登录凭据(cookie 或 authorization 头)——请在用量页的 Network 面板里右键 /api/v0/ 开头的接口请求 → 复制 → 以 fetch (Node.js) 格式复制(该格式自带凭据),而不是复制浏览器地址栏的页面请求`);super(new URL(t.url).origin,t.headers)}envelope(e){let t=e.code;if(typeof t==`number`&&t!==0){let n=tm(e.msg)??``;throw Error(`上游业务错误 ${String(t)}${n===``?``:`: ${n}`}(多为登录凭据失效,请在用量页重新复制接口请求)`)}let n=J(e.data);if(n===null)throw Error(`响应缺少 data 字段`);return n}async#e(e){let t=Pm(e);try{let e=J((await this.get(km,`start=${t.start}&end=${t.end}&tz=${t.tz}`)).biz_data),n=e===null?null:e.data;if(!Array.isArray(n))return null;let r=new Map;for(let e of n){let t=J(e),n=t===null?null:tm(t.currency);if(t===null||n===null||n===``)continue;let i=t.series;if(Array.isArray(i))for(let e of i){let t=J(e),i=t===null?null:t.buckets;if(Array.isArray(i))for(let e of i){let t=J(e),i=t===null?null:Mm(t.cost);i!==null&&r.set(n,(r.get(n)??0)+i)}}}let i=Nm(r);return i===null?null:{cost:fm(i.amount),currency:i.currency}}catch{return null}}async#t(e){let t=Pm(e);try{let e=J((await this.get(Am,`start=${t.start}&end=${t.end}&tz=${t.tz}`)).biz_data),n=e===null?null:e.series;if(!Array.isArray(n))return null;let r=0;for(let e of n){let t=J(e),n=t===null?null:t.buckets;if(Array.isArray(n))for(let e of n){let t=J(e),n=t===null?null:J(t.usage),i=n===null?null:Mm(n.REQUEST);i!==null&&(r+=i)}}return r}catch{return null}}#n(e,t){return e===null&&t===null?null:{cost:e===null?null:e.cost,currency:e===null?null:e.currency,requests:t}}async fetchQuota(){let[e,t,n,r,i]=await Promise.all([this.get(Om).catch(()=>null),this.#e(0),this.#e(-1),this.#t(0),this.#t(-1)]),a=null,o=null,s=null;if(e!==null){let t=J(e.biz_data);if(t!==null){let e=Nm(Fm(t.normal_wallets));e!==null&&(a=fm(e.amount));let n=Nm(Fm(t.total_costs));n!==null&&(o=fm(n.amount),s=n.currency)}}let c=this.#n(t,r),l=this.#n(n,i);if(a===null&&o===null&&c===null&&l===null)throw Error(`上游未返回任何额度数据(该账号可能未登录,或平台接口已变更)`);return{fiveHour:null,weekly:null,monthly:null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:a,totalCost:o,totalCostCurrency:s,today:c,yesterday:l}}},Lm=`/api/user/self`,Rm=`/api/user/subscription/current_cycle`,zm={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function Bm(e,t){let n=e.usage_infos;if(!Array.isArray(n))return null;for(let e of n){let n=J(e);if(n!==null&&n.key===t)return n}return null}function Vm(e){return e===null||Y(e.total_count)===null?null:hm(e,zm)}function Hm(e){let t=J(e.account_info),n=t===null?null:t.vouchers;if(!Array.isArray(n))return null;let r=0,i=!1;for(let e of n){let t=J(e),n=t===null?null:Y(t.available);n!==null&&(r+=n,i=!0)}return i?r/1e6:null}function Um(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var Wm=class extends gm{static vendorId=`sense-audio`;static vendorLabel=`SenseAudio`;static hosts=[`platform.senseaudio.cn`];static apiHosts=[`api.senseaudio.cn`];static credentialSource=`fetchText`;constructor(e){let t=om(e),n=Um(t,Lm),r=Um(t,Rm);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>rm(e.headers,`authorization`)!==void 0))throw Error(`复制的请求里没有 authorization 头(登录凭据在它里面)——请从已登录的 senseaudio.cn 页面重新复制 fetch 调用`);let i=n??r;super(new URL(i.url).origin,i.headers)}async fetchQuota(){let[e,t]=await Promise.all([this.get(Lm),this.get(Rm).catch(()=>null)]),n=Vm(Bm(e,`credit_5h_limit`)),r=Vm(Bm(e,`credit_7d_limit`)),i=Vm(Bm(e,`credit_30d_limit`));if(i===null&&t!==null){let e=Y(t.plan_points),n=Y(t.plan_point_remains);e!==null&&n!==null&&(i={used:e-n,cap:e,resetAt:dm(Y(t.plan_points_reset_at)),exceeded:e-n>=e})}if(n===null&&r===null&&i===null)throw Error(`上游未返回任何额度窗口(该账号可能尚未登录或未订阅套餐)`);return{fiveHour:n,weekly:r,monthly:i,totalTokens:null,totalRuns:null,voucherBalance:Hm(e),balance:null}}},Gm=`GetAgentPlanAFPUsage`,Km=`GetAgentPlanUsageDetails`,qm=`console.volcengine.com`,Jm=`2024-01-01`,Ym=`cn-beijing`,Xm={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function Zm(e){return e.find(e=>e.url.includes(Gm))}function Qm(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??Ym}/${Jm}`:t}function $m(e){return e.find(e=>am(e.url)===qm)}var eh=class extends gm{static vendorId=`volc-ark`;static vendorLabel=`火山方舟`;static hosts=[`console.volcengine.com`];static apiHosts=[`ark.cn-beijing.volces.com`];static credentialSource=`fetchText`;#e;#t;constructor(e){let t=om(e),n=Zm(t)??$m(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!sm(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==qm)throw Error(`非方舟控制台域`);r=e.origin,i=Qm(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=im(rm(n.headers,`cookie`),`csrfToken`)??rm(n.headers,`x-csrf-token`)??null;if(a===null)throw Error(`缺少 CSRF 凭据:请求头需含 x-csrf-token,或 Cookie 里需有 csrfToken (两者都来自已登录的控制台会话,请在登录页面上重新复制)`);super(r,{...n.headers,"x-csrf-token":a}),this.#e=`${i}/${Gm}`,this.#t=`${i}/${Km}`}envelope(e){let t=J(e.ResponseMetadata),n=t===null?null:J(t.Error);if(n!==null){let e=tm(n.Code)??`Unknown`,t=tm(n.Message)??``;throw Error(`上游业务错误 ${e}${t===``?``:`: ${t}`}(多为 Cookie 或 CSRF 凭据失效,请在控制台重新复制)`)}return e}async fetchQuota(){let e=J((await this.post(this.#e,{})).Result);if(e===null)throw Error(`响应缺少 Result 字段`);let t=hm(e.AFPFiveHour,Xm),n=hm(e.AFPWeekly,Xm),r=hm(e.AFPMonthly,Xm);if(t===null&&n===null&&r===null)throw Error(`上游未返回任何 AFP 窗口(该账号可能尚未订阅 Agent Plan 套餐)`);let i=J(e.AFPMonthly),a=i===null?null:Y(i.SubscribeTime);return{fiveHour:t,weekly:n,monthly:r,totalTokens:await this.#n(a),totalRuns:null,voucherBalance:null,balance:null}}async#n(e){let t=Date.now(),n=e!==null&&e>0?e:t-2592e6;try{let e=J((await this.post(this.#t,{Filter:{StartTime:mm(new Date(n)),EndTime:mm(new Date(t)),ObjectType:1,BillingType:[`WithinPlan`]},QueryInterval:`Day`})).Result),r=e===null?null:e.Details;return Array.isArray(r)?r.reduce((e,t)=>{let n=J(t);return n===null||n.Unit!==`Tokens`?e:e+(Y(n.Usage)??0)},0):null}catch{return null}}},th=`/api/biz/account/query-customer-account-report`,nh=`/api/finance/expenseBill/expenseBillListByDay`,rh=200,ih=`bigmodel_token_production`;function ah(e){let t=im(rm(e.headers,`cookie`),ih);if(t!==null&&t.trim()!==``)return t.trim();let n=rm(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var oh=class extends gm{static vendorId=`zhipu-bigmodel`;static vendorLabel=`智谱 BigModel`;static hosts=[`bigmodel.cn`];static apiHosts=[`open.bigmodel.cn`];static credentialSource=`fetchText`;constructor(e){let t=om(e);if(t.length===0)throw Error(`未找到可用的智谱请求:请在已登录的 bigmodel.cn(财务中心 / 资源包 / 任意控制台页面)里复制任意请求的 fetch 调用粘贴进来,额度端点会自动换算`);let n=t[0],r;try{r=new URL(n.url).origin}catch{throw Error(`粘贴的请求 URL 不是绝对地址,无法换算出额度接口——请粘贴浏览器里完整的 fetch(https://…)`)}let i=ah(n);if(i===null)throw Error(`复制的请求里没有登录凭据(需要 Cookie 里的 bigmodel_token_production,或显式的 authorization 头)——请从已登录的 bigmodel.cn 页面用「以 fetch (Node.js) 格式复制」重新复制`);let a={...n.headers,authorization:i.toLowerCase().startsWith(`bearer `)?i:`Bearer ${i}`};super(r,a)}envelope(e){let t=Y(e.code);if(t!==200){let n=tm(e.msg)??`未知错误`;throw Error(`上游业务错误 ${n}(code ${t===null?`未知`:String(t)})——多为登录凭据失效,请在 bigmodel.cn 重新登录后复制`)}return e}async#e(){let e=new Date,t=mm(e).slice(0,7),n=mm(new Date(e.getFullYear(),e.getMonth(),e.getDate()-(e.getDay()+6)%7));try{let e=1,r=0,i=0,a=1/0,o=[];for(;o.length<a;){let s=await this.get(nh,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String(rh)}`),c=s.rows,l=s.total;if(!Array.isArray(c))return null;a=Y(l)??o.length,o=o.concat(c);for(let e of c){let t=J(e);if(t===null)continue;let a=Y(t.originalAmount),o=tm(t.billingDate);a!==null&&o!==null&&(r+=a,o>=n&&(i+=a))}if(e+=1,c.length===0)break}return{weekly:{used:i,cap:null,resetAt:null,exceeded:!1},monthly:{used:r,cap:null,resetAt:null,exceeded:!1}}}catch{return null}}async fetchQuota(){let[e,t]=await Promise.all([this.get(th),this.#e()]),n=J(e.data),r=(n===null?null:Y(n.availableBalance))??(n===null?null:Y(n.balance));if(n===null||r===null)throw Error(`响应缺少余额字段(data.availableBalance)`);let i=Y(n.totalSpendAmount);return{fiveHour:null,weekly:t?.weekly??null,monthly:t?.monthly??null,totalTokens:null,totalRuns:null,voucherBalance:null,balance:r,totalCost:i,totalCostCurrency:i===null?null:`CNY`,extraStats:sh(n)}}};function sh(e){let t=e=>`${pm(e)} 元`,n=[],r=Y(e.rechargeAmount);r!==null&&n.push({label:`累计充值`,value:t(r)});let i=Y(e.giveAmount);i!==null&&n.push({label:`赠送金额`,value:t(i)});let a=Y(e.creditBalance);return a===null?e.creditStatus===`NOT_OPEN`&&n.push({label:`信用余额`,value:`未开通`}):n.push({label:`信用余额`,value:t(a)}),n}var ch=[Em,Im,Wm,eh,oh];function lh(){return ch}function uh(e){if(e===void 0)return null;let t=am(e);if(t===``)return null;for(let e of ch)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function dh(e,t){let n=uh(t);if(n===null)throw Error(`该供应商未支持用 API key 自动查询额度(apiBase 未命中已支持的接口域名)`);let r=e.trim();if(r===``)throw Error(`该供应商的 apiKey 为空,无法查询额度——请在供应商配置里填入 API key`);if(n.apiKeyPattern?.test(r)===!1)throw Error(`配置里的 apiKey 不是 ${n.vendorLabel} 的 API key 形态——请检查该供应商配置的 apiKey 字段`);return{vendorId:n.vendorId,vendor:new n(r)}}function fh(e,t){let n=(e,t)=>{let n=e=>{let t=new Set;for(let n of om(e)){let e=am(n.url);e!==``&&t.add(e)}return t},r=e.trim();for(let e of ch)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(r)===!0)return e;if(t!==void 0){let e=am(t);if(e!==``){for(let t of ch)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let i=n(e);for(let e of ch)if(e.credentialSource===`fetchText`&&e.hosts?.some(e=>i.has(e))===!0)return e;return null};if(e.trim()===``)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);let r=n(e,t);if(r===null){let e=ch.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=ch.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=uh(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:r.vendorId,vendor:new r(e)}}var ph=Bt(`quota.json`);function mh(e){let t=e=>{let t=e=>{let t=J(e);if(t===null)return null;let n=t.used;if(typeof n!=`number`||!Number.isFinite(n))return null;let r=t.cap,i=t.resetAt;return{used:n,cap:typeof r==`number`&&Number.isFinite(r)?r:null,resetAt:typeof i==`number`&&Number.isFinite(i)?i:null,exceeded:t.exceeded===!0}},n=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);if(Number.isFinite(t))return t}return null},r=e=>{let t=J(e);if(t===null)return null;let r=n(t.cost),i=n(t.requests);if(r===null&&i===null)return null;let a=t.currency;return{cost:r,currency:typeof a==`string`&&a!==``?a:null,requests:i}},i=e=>{if(!Array.isArray(e))return null;let t=[];for(let n of e){let e=J(n);if(e===null)continue;let r=e.label,i=e.value;typeof r==`string`&&r!==``&&typeof i==`string`&&i!==``&&t.push({label:r,value:i})}return t.length>0?t:null},a=J(e);if(a===null)return null;let o=a.totalTokens,s=a.totalRuns,c=a.voucherBalance,l=a.balance,u=a.totalCost,d=a.totalCostCurrency;return{fiveHour:t(a.fiveHour),weekly:t(a.weekly),monthly:t(a.monthly),totalTokens:typeof o==`number`&&Number.isFinite(o)?o:null,totalRuns:typeof s==`number`&&Number.isFinite(s)?s:null,voucherBalance:typeof c==`number`&&Number.isFinite(c)?c:null,balance:typeof l==`number`&&Number.isFinite(l)?l:null,totalCost:n(u),totalCostCurrency:typeof d==`string`&&d!==``?d:null,today:r(a.today),yesterday:r(a.yesterday),extraStats:i(a.extraStats)}},n=J(ph.get(e));if(n===null)return null;let r=n.fetchText,i=n.vendorId,a=n.fetchedAt,o=n.error;return{fetchText:typeof r==`string`&&r.trim()!==``?r:void 0,vendorId:typeof i==`string`?i:void 0,snapshot:t(n.snapshot)??void 0,fetchedAt:typeof a==`number`&&Number.isFinite(a)?a:void 0,error:typeof o==`string`&&o!==``?o:void 0}}function hh(e,t){ph.set(e,t)}function gh(e){ph.get(e)!==void 0&&ph.set(e,void 0)}function _h(){let e=ph.getAll(),t={};for(let n of Object.keys(e)){let e=mh(n);e!==null&&(t[n]=e)}return t}function vh(e,t,n,r){hh(e,{fetchText:mh(e)?.fetchText,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function yh(e,t){let n=mh(e);if(n===null){hh(e,{error:t});return}hh(e,{...n,error:t})}var bh=!1;function xh(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function Sh(){let e=e=>{if(!e.startsWith(`os.environ/`))return e;let t=process.env[e.slice(11)];return t===void 0||t===``?void 0:t},t=t=>{let n=typeof t==`object`&&t?t:{},r=typeof n.apiBase==`string`&&n.apiBase.trim()!==``?n.apiBase:void 0,i=typeof n.apiKey==`string`&&n.apiKey.trim()!==``?n.apiKey:void 0;return{apiBase:r,apiKey:i===void 0?void 0:e(i)}};try{let e=Dl();if(e===null||!Array.isArray(e.providers))return null;let n=new Map;for(let r of e.providers){let e=typeof r==`object`&&r?r.name:void 0;typeof e==`string`&&e!==``&&n.set(e,t(r))}return n}catch{return null}}function Ch(e){return Sh()?.get(e)??null}async function wh(e){try{let t=Ch(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(uh(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=dh(t.apiKey,t.apiBase))}else{let i=mh(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=fh(i,t.apiBase))}let i=await r.fetchQuota();vh(e,n,i,Date.now())}catch(t){yh(e,xh(t))}return mh(e)}async function Th(){let e=()=>{let e=Sh();return e===null?null:new Set(e.keys())};if(!bh){bh=!0;try{let t=Sh(),n=t===null?[]:[...t.entries()].filter(([,e])=>uh(e.apiBase)!==null).map(([e])=>e);for(let e of n)await wh(e);let r=e();for(let[e,t]of Object.entries(_h()))if(t.fetchText!==void 0){if(r!==null&&!r.has(e)){gh(e);continue}n.includes(e)||await wh(e)}}catch(e){R(`[quota] 刷新失败:`,xh(e))}finally{bh=!1}}}function Eh(){let e=async e=>{let t=(await vp(e))?.fetchText;return typeof t==`string`?t:null},t=()=>lh().map(e=>({vendorId:e.vendorId,vendorLabel:e.vendorLabel,hosts:e.hosts??[],apiHosts:e.apiHosts??[],credentialSource:e.credentialSource})),n=new er;return n.get(`/`,e=>e.json({ok:!0,vendors:t(),providers:_h()})),n.get(`/vendors`,e=>e.json({ok:!0,vendors:t()})),n.put(`/:provider`,async t=>{let n=t.req.param(`provider`);if(uh(Ch(n)?.apiBase)!==null)return t.json({ok:!1,error:`该供应商自动使用配置里的 apiKey 查询额度,无需手动配置`},400);let r=await e(t);if(r===null)return t.json({ok:!1,error:`请求体需为 {"fetchText": "..."}`},400);let i=mh(n);hh(n,{fetchText:r,vendorId:i?.vendorId,snapshot:i?.snapshot,fetchedAt:i?.fetchedAt,error:void 0});let a=await wh(n);return t.json({ok:!0,entry:a})}),n.delete(`/:provider`,e=>(gh(e.req.param(`provider`)),e.json({ok:!0}))),n.post(`/:provider/refresh`,async e=>{let t=await wh(e.req.param(`provider`));return e.json({ok:!0,entry:t})}),n}function Dh(e,t){let n=new er;return n.get(`/`,n=>n.json({listenPort:pp(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},masterKeySet:Il()!==``})),n}var Oh=864e5,kh=3e5,Ah=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,jh=new Map;try{let e=h(St(),`utf-8`),t=JSON.parse(e);for(let[e,n]of Object.entries(t)){let{_ts:t,...r}=n;jh.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function Mh(){let e=e=>({model:e.model,client:e.client,sessionId:e.sessionId,noSession:e.noSession===`1`||void 0,startDate:e.startDate||e.date,endDate:e.endDate||e.date,status:e.status,pathGroup:e.pathGroup,keyword:e.keyword}),t=e=>{let t=jh.get(e);if(!t)return null;let n=t.value.error===void 0?Oh:kh;return Date.now()-t.at>=n?(jh.delete(e),null):t.value},n=()=>{try{let e={};for(let[t,{value:n,at:r}]of jh)e[t]={...n,_ts:r};S(St(),JSON.stringify(e))}catch(e){R(`保存 IP 缓存失败:`,e.message)}},r=async e=>{let r=t(e);if(r)return r;let i=await(await fetch(Ah.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(i.status!==`success`){let t={error:i.message||`查询失败`};return jh.set(e,{value:t,at:Date.now()}),t}let a={country:i.country,region:i.regionName,city:i.city,isp:i.isp};return jh.set(e,{value:a,at:Date.now()}),n(),a},i=new er;return i.onError(wp),i.get(`/dates`,e=>{let t=df();return e.json({dates:t})}),i.get(`/clients`,e=>{let t=ff();return e.json({clients:t})}),i.get(`/ipinfo`,async e=>{let t=e.req.query(`ip`)||``;if(!/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return e.json({error:`invalid ip`},400);try{let n=await r(t);return e.json({ip:t,...n})}catch(e){throw new Cp(502,e.message)}}),i.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=Qd(t);return n||=(await kf(),Qd(t)??mu(Number(t))),n?e.json(n):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),i.get(`/`,Tp(async t=>{let n=t.req.query(),r=lf({...e(n),sort:n.sort,order:n.order,page:n.page,pageSize:n.pageSize}),i=(n.keyword??``).trim();return i.length>=2&&r.total===0&&(r=gf({...e(n),keyword:i,sort:n.sort,order:n.order,page:n.page,pageSize:n.pageSize})),t.json({...r,items:r.items.map(e=>({...e,user_agent:tu(e.headers)}))})})),i.get(`/sessions`,Tp(t=>{let n=t.req.query(),r=mf({...e(n),page:n.page,pageSize:n.pageSize});return t.json(r)})),i.post(`/clear`,Tp(async t=>{await jf();let n=uu().length;n>0&>(`[logs] 清空前 spool 仍有 ${String(n)} 条未入库,这些记录可能在入库后重现`);let r=t.req.query(),i=vf(e(r));return L(`[logs] 已清理筛选日志 ${i} 条(筛选: ${JSON.stringify(r)})`),t.json({deleted:i})})),i}var Nh=I(((e,t)=>{var n=Te(`child_process`).spawn;function r(e,t,r,i){typeof r==`function`&&(i=r,r=void 0);let a=!1,o=n(e,t,r),s=``,c=``;o.stdout.on(`data`,function(e){s+=e.toString()}),o.stderr.on(`data`,function(e){c+=e.toString()}),o.on(`error`,function(e){a||(a=!0,i(Error(e)))}),o.on(`close`,function(e,t){if(!a){if(a=!0,c)return i(Error(c));i(null,s,e)}})}t.exports=r})),Ph=I(((e,t)=>{var n=6e4,r={},i={},a={},o=0,s=null;function c(e,t){if(!(t<=0))return i[e]!==void 0&&(r[e]=Date.now()+(t||n)),i[e]}function l(e,t,s,c){t===void 0||s<=0||(r[e]=Date.now()+(s||n),i[e]===void 0&&(o++,u(s)),i[e]=t,c&&(a[e]=c))}function u(e){if(o>0){s===null&&(s=setInterval(d,(e||n)/2),typeof s.unref==`function`&&s.unref());return}s!==null&&(clearInterval(s),s=null)}function d(){let e=Date.now(),t=Object.keys(r);for(let n=0;n<t.length;n++){let s=t[n];r[s]<e&&(o--,a[s]&&a[s](i[s]),delete i[s],delete r[s],delete a[s])}u()}function f(e){for(let t in e)delete e[t]}function p(){s!==null&&(clearInterval(s),s=null),f(i),f(r),f(a)}t.exports={get:c,set:l,clear:p}})),Fh=I(((e,t)=>{var n=Te(`os`),r=Nh(),i=Ph(),a=n.platform();function o(e,t){let n=0,r=e.split(/-|:|\./),i=r.length-1;return i>=0&&t&&a===`darwin`&&(n+=parseInt(r[i--],10)*10),i>=0&&(n+=parseInt(r[i--],10)*1e3),i>=0&&(n+=parseInt(r[i--],10)*6e4),i>=0&&(n+=parseInt(r[i--],10)*36e5),i>=0&&(n+=parseInt(r[i--],10)*864e5),n}function s(e,t,s){let c=e.join(`,`),l=[`-o`,`etime,pid,ppid,pcpu,rss,time`,`-p`,c];(a===`aix`||a===`os400`)&&(l=[`-o`,`etime,pid,ppid,pcpu,rssize,time`,`-p`,c]),r(`ps`,l,function(e,r,c){if(e)return a===`os390`&&/no matching processes found/.test(e)&&(e=Error(`No matching pid found`),e.code=`ENOENT`),s(e);if(c===1){let e=Error(`No matching pid found`);return e.code=`ENOENT`,s(e)}if(c!==0)return s(Error(`pidusage ps command exited with code `+c));let l=Date.now();r=r.split(n.EOL);let u={};for(let e=1;e<r.length;e++){let n=r[e].trim().split(/\s+/);if(!n||n.length!==6)continue;let a=parseInt(n[1],10),s=i.get(a,t.maxage);s===void 0&&(s={});let c=parseInt(n[2],10),d=parseInt(n[4],10)*1024,f=o(n[0]),p=o(n[5],!0),m=p-(s.ctime||0),h=Math.abs(s.elapsed===void 0?f:f-s.elapsed);u[a]={cpu:h>0?m/h*100:0,memory:d,ppid:c,pid:a,ctime:p,elapsed:f,timestamp:l},i.set(a,u[a],t.maxage)}s(null,u)})}t.exports=s})),Ih=I(((e,t)=>{function n(e,t,n){typeof t==`function`&&(n=t,t={});let r;Array.isArray(e)||(r=Object.keys(e));let i=r?r.length:e.length,a=i,o=r?{}:[];function s(e,r,s){o[e]=s,(--a===0||r&&!t.graceful)&&(t.graceful&&r&&i>1&&(r=null),n&&n(r,o),n=null)}r?r.forEach(function(t){e[t](function(e,n){s(t,e,n)})}):e.forEach(function(e,t){e(function(e,n){s(t,e,n)})})}t.exports=n})),Lh=I(((e,t)=>{var n=Te(`os`),r=Te(`fs`),i=Te(`child_process`).exec,a=Ih();function o(e,t){if(e!==null){s(function(n,r){if(n)return t(n);e.uptime=r,t(null,e)});return}a([c,s],function(n,r){if(n)return t(n);e={clockTick:r[0].clockTick,pageSize:r[0].pageSize,uptime:r[1]},t(null,e)})}t.exports=o;function s(e){r.readFile(`/proc/uptime`,`utf8`,function(t,r){return t||r===void 0?(process.env.PIDUSAGE_SILENT||console.warn(`[pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value`),e(null,n.uptime()||new Date/1e3)):e(null,parseFloat(r.split(` `)[0]))})}function c(e){a([function(e){l(`CLK_TCK`,{default:100},e)},function(e){l(`PAGESIZE`,{default:4096},e)}],function(t,n){if(t)return e(t);e(null,{clockTick:n[0],pageSize:n[1]})})}function l(e,t,n){typeof t==`function`&&(n=t,t={default:``}),i(`getconf `+e,function(r,i,a){return r===null?(i=parseInt(i),isNaN(i)?n(null,t.default):n(null,i)):(process.env.PIDUSAGE_SILENT||console.error(`Error while calling "getconf `+e+`"`,r),n(null,t.default))})}})),Rh=I(((e,t)=>{var n=Te(`buffer`),r=n.Buffer;function i(e,t){for(var n in e)t[n]=e[n]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?t.exports=n:(i(n,e),e.Buffer=a);function a(e,t,n){return r(e,t,n)}a.prototype=Object.create(r.prototype),i(r,a),a.from=function(e,t,n){if(typeof e==`number`)throw TypeError(`Argument must not be a number`);return r(e,t,n)},a.alloc=function(e,t,n){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);var i=r(e);return t===void 0?i.fill(0):typeof n==`string`?i.fill(t,n):i.fill(t),i},a.allocUnsafe=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return r(e)},a.allocUnsafeSlow=function(e){if(typeof e!=`number`)throw TypeError(`Argument must be a number`);return n.SlowBuffer(e)}})),zh=I(((e,t)=>{var n=Te(`fs`),r=Te(`path`),i=Lh(),a=Ih(),o=Ph(),s=null,c=Rh().Buffer,l=1024;function u(){}function d(e,t,r){if(t.fd)return r(null,t.fd);n.open(e,`r`,r)}function f(e){e.fd&&n.close(e.fd,u)}function p(e,t,r){let i=!1;typeof t==`function`&&(r=t,t=c.alloc(l),i=!0),n.read(e,t,0,l,0,function(n,a,o){if(n){r(n);return}let s=c.concat([t,o],i?a:t.length+a);if(a===l){p(e,s,r);return}r(null,t)})}function m(e,t,n){let i=o.get(e,t.maxage),a=!1;i===void 0&&(a=!0,i={}),d(r.join(`/proc`,``+e,`stat`),i,function(r,c){if(r)return r.code===`ENOENT`&&(r.message=`No matching pid found`),n(r,null);if(r)return n(r);p(c,function(r,l){if(r)return n(r);let u=l.toString(`utf8`),d=Date.now(),p=u.lastIndexOf(`)`);u=u.substr(p+2).split(` `);let h={ppid:parseInt(u[1]),utime:parseFloat(u[11])*1e3/s.clockTick,stime:parseFloat(u[12])*1e3/s.clockTick,cutime:parseFloat(u[13])*1e3/s.clockTick,cstime:parseFloat(u[14])*1e3/s.clockTick,start:parseFloat(u[19])*1e3/s.clockTick,rss:parseFloat(u[21]),uptime:s.uptime*1e3,fd:c},g=h.rss*s.pageSize,_=t.childrens?h.cutime+h.cstime:0,v=h.stime-(i.stime||0)+h.utime-(i.utime||0)+_,y=Math.abs(i.uptime===void 0?h.start-h.uptime:h.uptime-i.uptime),b=y>0?v/y*100:0;return o.set(e,h,t.maxage,f),a?m(e,t,n):n(null,{cpu:b,memory:g,ctime:h.utime+h.stime,elapsed:h.uptime-h.start,timestamp:d,pid:e,ppid:h.ppid})})})}function h(e,t,n){i(s,function(r,i){if(r)return n(r);s=i;let o={};e.forEach(function(e,n){o[e]=function(n){m(e,t,n)}}),a(o,{graceful:!0},n)})}t.exports=h})),Bh=I(((e,t)=>{var n=Te(`os`),r=Nh(),i=Ph();function a(e){let t=e.substring(0,4),n=e.substring(4,6),r=e.substring(6,8),i=e.substring(8,10),a=e.substring(10,12),o=e.substring(12,14),s=e.substring(15,21),c=e.substring(21,22),l=parseInt(e.substring(22,25),10),u=Math.floor(l/60),d=l%60;return new Date(t+`-`+n+`-`+r+`T`+i+`:`+a+`:`+o+`.`+s+c+(u>9?u:`0`+u)+(d>9?d:`0`+d))}function o(e,t,s){let c=`ProcessId=`+e[0];for(let t=1;t<e.length;t++)c+=` or ProcessId=`+e[t];r(`wmic`,[`PROCESS`,`where`,`"`+c+`"`,`get`,`CreationDate,KernelModeTime,ParentProcessId,ProcessId,UserModeTime,WorkingSetSize`],{windowsHide:!0,windowsVerbatimArguments:!0},function(r,c,l){if(r){if(r.message.indexOf(`No Instance(s) Available.`)!==-1){let e=Error(`No matching pid found`);return e.code=`ENOENT`,s(e)}return s(r)}if(l!==0)return s(Error(`pidusage wmic command exited with code `+l));let u=Date.now(),d=Math.floor(n.uptime()||u/1e3);c=c.split(n.EOL);let f=!1,p={};for(let e=1;e<c.length;e++){let n=c[e].trim().split(/\s+/);if(!n||n.length!==6)continue;let r=a(n[0]),o=parseInt(n[2],10),s=parseInt(n[3],10),l=Math.round(parseInt(n[1],10)/1e4),m=Math.round(parseInt(n[4],10)/1e4),h=parseInt(n[5],10),g=i.get(s,t.maxage);g===void 0&&(f=!0,g={ctime:l+m,uptime:d});let _=(l+m-g.ctime)/1e3,v=d-g.uptime,y=v>0?_/v*100:0;i.set(s,{ctime:m+l,uptime:d},t.maxage),p[s]={cpu:y,memory:h,ppid:o,pid:s,ctime:m+l,elapsed:u-r.getTime(),timestamp:u}}if(f)return o(e,t,function(e,t){if(e)return s(e);s(null,Object.assign(p,t))});s(null,p)})}t.exports=o})),Vh=I(((e,t)=>{var n=Te(`os`),r=Nh(),i=Ph();function a(e){let t=e.substring(0,4),n=e.substring(4,6),r=e.substring(6,8),i=e.substring(8,10),a=e.substring(10,12),o=e.substring(12,14),s=e.substring(15,21),c=e.substring(21,22),l=parseInt(e.substring(22,25),10),u=Math.floor(l/60),d=l%60;return new Date(t+`-`+n+`-`+r+`T`+i+`:`+a+`:`+o+`.`+s+c+(u>9?u:`0`+u)+(d>9?d:`0`+d))}function o(e,t,s){let c=`ProcessId=`+e[0];for(let t=1;t<e.length;t++)c+=` or ProcessId=`+e[t];r(`gwmi`,[`win32_process`,`-Filter`,`'`+c+`'`,`| select CreationDate,KernelModeTime,ParentProcessId,ProcessId,UserModeTime,WorkingSetSize`,`| format-table`],{windowsHide:!0,windowsVerbatimArguments:!0,shell:`powershell.exe`},function(r,c,l){if(r){if(r.message.indexOf(`No Instance(s) Available.`)!==-1){let e=Error(`No matching pid found`);return e.code=`ENOENT`,s(e)}return s(r)}if(l!==0)return s(Error(`pidusage gwmi command exited with code `+l));let u=Date.now(),d=Math.floor(n.uptime()||u/1e3);c=c.split(n.EOL).slice(1);let f=c.findIndex(e=>!!e);if(c=c.slice(f+2),!c.length){let e=Error(`No matching pid found`);return e.code=`ENOENT`,s(e)}let p=!1,m={};for(let e=0;e<c.length;e++){let n=c[e].trim().split(/\s+/);if(!n||n.length===1)continue;let r=a(n[0]),o=parseInt(n[2],10),s=parseInt(n[3],10),l=Math.round(parseInt(n[1],10)/1e4),f=Math.round(parseInt(n[4],10)/1e4),h=parseInt(n[5],10),g=i.get(s,t.maxage);g===void 0&&(p=!0,g={ctime:l+f,uptime:d});let _=(l+f-g.ctime)/1e3,v=d-g.uptime,y=v>0?_/v*100:0;i.set(s,{ctime:f+l,uptime:d},t.maxage),m[s]={cpu:y,memory:h,ppid:o,pid:s,ctime:f+l,elapsed:u-r.getTime(),timestamp:u}}if(p)return o(e,t,function(e,t){if(e)return s(e);s(null,Object.assign(m,t))});s(null,m)})}t.exports=o})),Hh=I(((e,t)=>{var n=Te(`fs`),r=Te(`os`),i=Te(`child_process`).spawn,a={ps:()=>Fh(),procfile:()=>zh(),wmic:()=>Bh(),gwmi:()=>Vh()},o={aix:`ps`,os400:`ps`,android:`procfile`,alpine:`procfile`,darwin:`ps`,freebsd:`ps`,os390:`ps`,linux:`procfile`,netbsd:`procfile`,openbsd:`ps`,sunos:`ps`,win:`wmic`},s=r.platform();n.existsSync(`/etc/alpine-release`)&&(s=`alpine`),s.match(/^win/)&&(s=`win`);var c;try{c=a[o[s]]()}catch{}function l(e,t,n){let o=c;if(s!==`win`&&t.usePs===!0&&(o=a.ps()),s===`win`){let e;try{e=i(`wmic`,function(e){if(e)throw Error(e)})}catch{o=a.gwmi()}finally{e&&e.kill()}}if(o===void 0)return n(Error(r.platform()+` is not supported yet, please open an issue (https://github.com/soyuka/pidusage)`));let l=!1;if(Array.isArray(e)||(l=!0,e=[e]),e.length===0)return n(TypeError(`You must provide at least one pid`));for(let t=0;t<e.length;t++)if(e[t]=parseInt(e[t],10),isNaN(e[t])||e[t]<0)return n(TypeError(`One of the pids provided is invalid`));o(e,t,function(t,r){if(t)return n(t);l?n(null,r[e[0]]):n(null,r)})}t.exports=l})),Uh=we(I(((e,t)=>{var n=Hh();function r(e,t,r){if(typeof t==`function`&&(r=t,t={}),t===void 0&&(t={}),t=Object.assign({usePs:/^true$/i.test(process.env.PIDUSAGE_USE_PS),maxage:process.env.PIDUSAGE_MAXAGE},t),typeof r==`function`){n(e,t,r);return}return new Promise(function(r,i){n(e,t,function(e,t){if(e)return i(e);r(t)})})}t.exports=r,t.exports.clear=Ph().clear}))(),1);function Wh(e){return`http://127.0.0.1:${String(e.port)}`}function Gh(e){let t=e=>{let t=e.port??null;return{role:`main`,pid:e.pid??null,status:e.status??`stopped`,port:t,address:t?`http://127.0.0.1:${String(t)}`:null,startedAt:e.startedAt??null,memory:e.memory??null,cpu:e.cpu??null,restarts:null}},n=async e=>{try{let t=await(0,Uh.default)(e);return{memory:t.memory??null,cpu:t.cpu==null?null:Math.round(t.cpu*10)/10}}catch{return{memory:null,cpu:null}}},r=new er;return r.get(`/status`,async t=>t.json({ok:!0,running:!0,pid:process.pid,status:`online`,uptime:e.startedAt,gatewayBase:Wh(e)})),r.get(`/processes`,async r=>{let i=await n(process.pid);return r.json({ok:!0,processes:[t({pid:process.pid,status:`online`,port:e.port,startedAt:e.startedAt,memory:i.memory,cpu:i.cpu})]})}),r}var Kh=`ezllm-autostart.vbs`,qh=`ezllm-autostart.cmd`,Jh=`com.ezllm.autostart`,Yh=`ezllm.service`,Xh=`autostart.opt-out`,Zh=`ezllm-v2`,Qh=`Auto-generated by "ezllm autostart on" (${Zh}). Disable with "ezllm autostart off".`,$h=`ELLM_`,eg=new Set([`WEBUI_USERNAME`,`WEBUI_PASSWORD`,`HOST`]);function tg(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(n.startsWith($h)||eg.has(n))&&(t[n]=r);return t}function ng(e){return E(e,Xh)}function rg(){return E((()=>{let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return E(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)})(),Kh)}function ig(){return E(t(),`Library`,`LaunchAgents`,`${Jh}.plist`)}function ag(){return E(t(),`.config`,`systemd`,`user`,Yh)}function og(e,t){return new Promise(n=>{let r=pe(e,t,{stdio:`ignore`,shell:!1});r.on(`error`,()=>n(127)),r.on(`exit`,e=>n(e??1))})}var sg={win32:{itemPath:rg,on:pg,off:gg},darwin:{itemPath:ig,on:mg,off:_g},linux:{itemPath:ag,on:hg,off:vg}};function cg(e){return sg[e]??null}function lg(e){let t=cg(e);if(!t)throw Error(`暂不支持的平台: ${e}。`);return t}function ug(e,t){return[e,t.entryJs,...t.args??[]]}function dg(e){return E(e,`logs`,`autostart.log`)}async function fg(e,t,n=og){try{S(e,t,`utf16le`);return}catch(r){if(await n(`powershell`,[`-NoProfile`,`-Command`,`$bytes=[Convert]::FromBase64String('${Buffer.from(t,`utf16le`).toString(`base64`)}');[IO.File]::WriteAllBytes('${e.replace(/'/g,`''`)}', $bytes)`])!==0)throw r}}async function pg(e,t){let n=(e,t)=>{let n=/["%\r\n]/;if(n.test(e)||n.test(t))throw Error(`环境变量 ${e} 的键/值含 cmd 无法安全转义的字符(" % 或换行),已拒绝写入自启项;请调整该变量后重试 ezllm autostart on`)},r=(e,t)=>{let r=dg(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${Qh}`,...Object.entries(t.env).map(([e,t])=>(n(e,t),`set "${e}=${t}"`)),`>> "${r}" echo [%date% %time%] autostart launching.`,`${ug(e,t).map(e=>`"${e}"`).join(` `)} >> "${r}" 2>&1`,``].join(`\r
|
|
79
|
+
`)},i=e=>[`' ${Qh}`,`CreateObject("WScript.Shell").Run """${e}""", 0, False`,``].join(`\r
|
|
80
|
+
`),a=rg(),o=E(t.appDir,qh);return S(o,r(e,t),`utf-8`),await fg(a,`\uFEFF${i(o)}`),a}async function mg(e,t){let n=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`),r=(e,t)=>{let r=dg(t.appDir),i=Object.entries(t.env).map(([e,t])=>` <string>${n(e)}</string>\n <string>${n(t)}</string>`).join(`
|
|
81
|
+
`),a=ug(e,t).map(e=>` <string>${n(e)}</string>`).join(`
|
|
82
|
+
`);return[`<?xml version="1.0" encoding="UTF-8"?>`,`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">`,`<!-- ${Zh}: launch daemon -->`,`<plist version="1.0">`,`<dict>`,` <key>Label</key><string>${n(Jh)}</string>`,` <key>ProgramArguments</key>`,` <array>`,a,` </array>`,` <key>EnvironmentVariables</key>`,` <dict>`,i,` </dict>`,` <key>RunAtLoad</key><true/>`,` <key>StandardOutPath</key><string>${n(r)}</string>`,` <key>StandardErrorPath</key><string>${n(r)}</string>`,`</dict>`,`</plist>`,``].join(`
|
|
83
|
+
`)},i=ig();S(i,r(e,t),`utf-8`),await og(`launchctl`,[`unload`,i]);let a=await og(`launchctl`,[`load`,i]);if(a!==0)throw Error(`launchctl load 失败(退出码 ${String(a)})。请手动执行: launchctl load "${i}"`);return i}async function hg(e,t){let n=(e,t)=>{let n=Object.entries(t.env).map(([e,t])=>`Environment="${e}=${t.replace(/"/g,`\\"`)}"`).join(`
|
|
84
|
+
`),r=ug(e,t).map(e=>`"${e.replace(/"/g,`\\"`)}"`).join(` `);return[`[Unit]`,`Description=ezllm autostart (${Zh}, launch daemon)`,`After=default.target`,``,`[Service]`,`Type=simple`,`ExecStart=${r}`,n,`Restart=on-failure`,`RestartSec=3`,``,`[Install]`,`WantedBy=default.target`,``].join(`
|
|
85
|
+
`)},r=ag();p(T(r),{recursive:!0}),S(r,n(e,t),`utf-8`);let i=await og(`systemctl`,[`--user`,`daemon-reload`]);if(i!==0)throw Error(`systemctl --user daemon-reload 失败(退出码 ${String(i)})。当前环境可能无 systemd(WSL/容器),请手动启用或删除: ${r}`);let a=await og(`systemctl`,[`--user`,`enable`,Yh]);if(a!==0)throw Error(`systemctl --user enable 失败(退出码 ${String(a)})。请手动执行: systemctl --user enable ${Yh}`);return r}async function gg(e){let t=rg(),n=f(t);return v(t,{force:!0}),v(E(e,qh),{force:!0}),n}async function _g(){let e=ig();return f(e)?(await og(`launchctl`,[`unload`,e]),v(e,{force:!0}),!0):!1}async function vg(){let e=ag();return f(e)?(await og(`systemctl`,[`--user`,`disable`,Yh]),v(e,{force:!0}),await og(`systemctl`,[`--user`,`daemon-reload`]),!0):!1}function yg(e){let t=()=>cg(r())?.itemPath()??null,n=e=>{let t=h(e);return t.length>=2&&t[0]===255&&t[1]===254?t.toString(`utf16le`).slice(1):t.toString(`utf-8`)},i=t(),a=!1;if(i&&f(i))try{a=n(i).includes(Zh)}catch{}return{platform:r(),enabled:a,itemPath:i,optOut:f(ng(e))}}async function bg(e){let t=lg(r());p(E(e.appDir,`logs`),{recursive:!0});let n=await t.on(e.nodePath,e);return v(ng(e.appDir),{force:!0}),{itemPath:n}}async function xg(e){let t=await lg(r()).off(e.appDir);return p(e.appDir,{recursive:!0}),S(ng(e.appDir),new Date().toISOString(),`utf-8`),{removed:t}}var Sg=Object.create,Cg=Object.defineProperty,wg=Object.getOwnPropertyDescriptor,Tg=Object.getOwnPropertyNames,Eg=Object.getPrototypeOf,Dg=Object.prototype.hasOwnProperty,X=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Og=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Tg(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Dg.call(e,s)&&s!==n&&Cg(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=wg(t,s))||r.enumerable});return e},kg=(e,t,n)=>(n=e==null?{}:Sg(Eg(e)),Og(t||!e||!e.__esModule||!Dg.call(e,`default`)?Cg(n,`default`,{value:e,enumerable:!0}):n,e)),Z=e(import.meta.url),Ag=X(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`Float64Array`,`BigInt64Array`,`BigUint64Array`];function r(e){return n.includes(e)}var i=[`Function`,`Generator`,`AsyncGenerator`,`GeneratorFunction`,`AsyncGeneratorFunction`,`AsyncFunction`,`Observable`,`Array`,`Buffer`,`Blob`,`Object`,`RegExp`,`Date`,`Error`,`Map`,`Set`,`WeakMap`,`WeakSet`,`ArrayBuffer`,`SharedArrayBuffer`,`DataView`,`Promise`,`URL`,`FormData`,`URLSearchParams`,`HTMLElement`,...n];function a(e){return i.includes(e)}var o=[`null`,`undefined`,`string`,`number`,`bigint`,`boolean`,`symbol`];function s(e){return o.includes(e)}function c(e){return t=>typeof t===e}var{toString:l}=Object.prototype,u=e=>{let t=l.call(e).slice(8,-1);if(/HTML\w+Element/.test(t)&&f.domElement(e))return`HTMLElement`;if(a(t))return t},d=e=>t=>u(t)===e;function f(e){if(e===null)return`null`;switch(typeof e){case`undefined`:return`undefined`;case`string`:return`string`;case`number`:return`number`;case`boolean`:return`boolean`;case`function`:return`Function`;case`bigint`:return`bigint`;case`symbol`:return`symbol`}if(f.observable(e))return`Observable`;if(f.array(e))return`Array`;if(f.buffer(e))return`Buffer`;let t=u(e);if(t)return t;if(e instanceof String||e instanceof Boolean||e instanceof Number)throw TypeError(`Please don't use object wrappers for primitive types`);return`Object`}f.undefined=c(`undefined`),f.string=c(`string`);var p=c(`number`);f.number=e=>p(e)&&!f.nan(e),f.bigint=c(`bigint`),f.function_=c(`function`),f.null_=e=>e===null,f.class_=e=>f.function_(e)&&e.toString().startsWith(`class `),f.boolean=e=>e===!0||e===!1,f.symbol=c(`symbol`),f.numericString=e=>f.string(e)&&!f.emptyStringOrWhitespace(e)&&!Number.isNaN(Number(e)),f.array=(e,t)=>Array.isArray(e)?!f.function_(t)||e.every(t):!1,f.buffer=e=>{var t;return((t=e?.constructor)?.isBuffer)?.call(t,e)??!1},f.blob=e=>d(`Blob`)(e),f.nullOrUndefined=e=>f.null_(e)||f.undefined(e),f.object=e=>!f.null_(e)&&(typeof e==`object`||f.function_(e)),f.iterable=e=>f.function_(e?.[Symbol.iterator]),f.asyncIterable=e=>f.function_(e?.[Symbol.asyncIterator]),f.generator=e=>f.iterable(e)&&f.function_(e?.next)&&f.function_(e?.throw),f.asyncGenerator=e=>f.asyncIterable(e)&&f.function_(e.next)&&f.function_(e.throw),f.nativePromise=e=>d(`Promise`)(e);var m=e=>f.function_(e?.then)&&f.function_(e?.catch);f.promise=e=>f.nativePromise(e)||m(e),f.generatorFunction=d(`GeneratorFunction`),f.asyncGeneratorFunction=e=>u(e)===`AsyncGeneratorFunction`,f.asyncFunction=e=>u(e)===`AsyncFunction`,f.boundFunction=e=>f.function_(e)&&!e.hasOwnProperty(`prototype`),f.regExp=d(`RegExp`),f.date=d(`Date`),f.error=d(`Error`),f.map=e=>d(`Map`)(e),f.set=e=>d(`Set`)(e),f.weakMap=e=>d(`WeakMap`)(e),f.weakSet=e=>d(`WeakSet`)(e),f.int8Array=d(`Int8Array`),f.uint8Array=d(`Uint8Array`),f.uint8ClampedArray=d(`Uint8ClampedArray`),f.int16Array=d(`Int16Array`),f.uint16Array=d(`Uint16Array`),f.int32Array=d(`Int32Array`),f.uint32Array=d(`Uint32Array`),f.float32Array=d(`Float32Array`),f.float64Array=d(`Float64Array`),f.bigInt64Array=d(`BigInt64Array`),f.bigUint64Array=d(`BigUint64Array`),f.arrayBuffer=d(`ArrayBuffer`),f.sharedArrayBuffer=d(`SharedArrayBuffer`),f.dataView=d(`DataView`),f.enumCase=(e,t)=>Object.values(t).includes(e),f.directInstanceOf=(e,t)=>Object.getPrototypeOf(e)===t.prototype,f.urlInstance=e=>d(`URL`)(e),f.urlString=e=>{if(!f.string(e))return!1;try{return new URL(e),!0}catch{return!1}},f.truthy=e=>!!e,f.falsy=e=>!e,f.nan=e=>Number.isNaN(e),f.primitive=e=>f.null_(e)||s(typeof e),f.integer=e=>Number.isInteger(e),f.safeInteger=e=>Number.isSafeInteger(e),f.plainObject=e=>{if(l.call(e)!==`[object Object]`)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.getPrototypeOf({})},f.typedArray=e=>r(u(e));var h=e=>f.safeInteger(e)&&e>=0;f.arrayLike=e=>!f.nullOrUndefined(e)&&!f.function_(e)&&h(e.length),f.inRange=(e,t)=>{if(f.number(t))return e>=Math.min(0,t)&&e<=Math.max(t,0);if(f.array(t)&&t.length===2)return e>=Math.min(...t)&&e<=Math.max(...t);throw TypeError(`Invalid range: ${JSON.stringify(t)}`)};var g=1,_=[`innerHTML`,`ownerDocument`,`style`,`attributes`,`nodeValue`];f.domElement=e=>f.object(e)&&e.nodeType===g&&f.string(e.nodeName)&&!f.plainObject(e)&&_.every(t=>t in e),f.observable=e=>{var t,n;return e?e===(t=e)[Symbol.observable]?.call(t)||e===(n=e)[`@@observable`]?.call(n):!1},f.nodeStream=e=>f.object(e)&&f.function_(e.pipe)&&!f.observable(e),f.infinite=e=>e===1/0||e===-1/0;var v=e=>t=>f.integer(t)&&Math.abs(t%2)===e;f.evenInteger=v(0),f.oddInteger=v(1),f.emptyArray=e=>f.array(e)&&e.length===0,f.nonEmptyArray=e=>f.array(e)&&e.length>0,f.emptyString=e=>f.string(e)&&e.length===0;var y=e=>f.string(e)&&!/\S/.test(e);f.emptyStringOrWhitespace=e=>f.emptyString(e)||y(e),f.nonEmptyString=e=>f.string(e)&&e.length>0,f.nonEmptyStringAndNotWhitespace=e=>f.string(e)&&!f.emptyStringOrWhitespace(e),f.emptyObject=e=>f.object(e)&&!f.map(e)&&!f.set(e)&&Object.keys(e).length===0,f.nonEmptyObject=e=>f.object(e)&&!f.map(e)&&!f.set(e)&&Object.keys(e).length>0,f.emptySet=e=>f.set(e)&&e.size===0,f.nonEmptySet=e=>f.set(e)&&e.size>0,f.emptyMap=e=>f.map(e)&&e.size===0,f.nonEmptyMap=e=>f.map(e)&&e.size>0,f.propertyKey=e=>f.any([f.string,f.number,f.symbol],e),f.formData=e=>d(`FormData`)(e),f.urlSearchParams=e=>d(`URLSearchParams`)(e);var b=(e,t,n)=>{if(!f.function_(t))throw TypeError(`Invalid predicate: ${JSON.stringify(t)}`);if(n.length===0)throw TypeError(`Invalid number of values`);return e.call(n,t)};f.any=(e,...t)=>(f.array(e)?e:[e]).some(e=>b(Array.prototype.some,e,t)),f.all=(e,...t)=>b(Array.prototype.every,e,t);var x=(e,t,n,r={})=>{if(!e){let{multipleValues:e}=r,i=e?`received values of types ${[...new Set(n.map(e=>`\`${f(e)}\``))].join(`, `)}`:`received value of type \`${f(n)}\``;throw TypeError(`Expected value which is \`${t}\`, ${i}.`)}};e.assert={undefined:e=>x(f.undefined(e),`undefined`,e),string:e=>x(f.string(e),`string`,e),number:e=>x(f.number(e),`number`,e),bigint:e=>x(f.bigint(e),`bigint`,e),function_:e=>x(f.function_(e),`Function`,e),null_:e=>x(f.null_(e),`null`,e),class_:e=>x(f.class_(e),`Class`,e),boolean:e=>x(f.boolean(e),`boolean`,e),symbol:e=>x(f.symbol(e),`symbol`,e),numericString:e=>x(f.numericString(e),`string with a number`,e),array:(e,t)=>{x(f.array(e),`Array`,e),t&&e.forEach(t)},buffer:e=>x(f.buffer(e),`Buffer`,e),blob:e=>x(f.blob(e),`Blob`,e),nullOrUndefined:e=>x(f.nullOrUndefined(e),`null or undefined`,e),object:e=>x(f.object(e),`Object`,e),iterable:e=>x(f.iterable(e),`Iterable`,e),asyncIterable:e=>x(f.asyncIterable(e),`AsyncIterable`,e),generator:e=>x(f.generator(e),`Generator`,e),asyncGenerator:e=>x(f.asyncGenerator(e),`AsyncGenerator`,e),nativePromise:e=>x(f.nativePromise(e),`native Promise`,e),promise:e=>x(f.promise(e),`Promise`,e),generatorFunction:e=>x(f.generatorFunction(e),`GeneratorFunction`,e),asyncGeneratorFunction:e=>x(f.asyncGeneratorFunction(e),`AsyncGeneratorFunction`,e),asyncFunction:e=>x(f.asyncFunction(e),`AsyncFunction`,e),boundFunction:e=>x(f.boundFunction(e),`Function`,e),regExp:e=>x(f.regExp(e),`RegExp`,e),date:e=>x(f.date(e),`Date`,e),error:e=>x(f.error(e),`Error`,e),map:e=>x(f.map(e),`Map`,e),set:e=>x(f.set(e),`Set`,e),weakMap:e=>x(f.weakMap(e),`WeakMap`,e),weakSet:e=>x(f.weakSet(e),`WeakSet`,e),int8Array:e=>x(f.int8Array(e),`Int8Array`,e),uint8Array:e=>x(f.uint8Array(e),`Uint8Array`,e),uint8ClampedArray:e=>x(f.uint8ClampedArray(e),`Uint8ClampedArray`,e),int16Array:e=>x(f.int16Array(e),`Int16Array`,e),uint16Array:e=>x(f.uint16Array(e),`Uint16Array`,e),int32Array:e=>x(f.int32Array(e),`Int32Array`,e),uint32Array:e=>x(f.uint32Array(e),`Uint32Array`,e),float32Array:e=>x(f.float32Array(e),`Float32Array`,e),float64Array:e=>x(f.float64Array(e),`Float64Array`,e),bigInt64Array:e=>x(f.bigInt64Array(e),`BigInt64Array`,e),bigUint64Array:e=>x(f.bigUint64Array(e),`BigUint64Array`,e),arrayBuffer:e=>x(f.arrayBuffer(e),`ArrayBuffer`,e),sharedArrayBuffer:e=>x(f.sharedArrayBuffer(e),`SharedArrayBuffer`,e),dataView:e=>x(f.dataView(e),`DataView`,e),enumCase:(e,t)=>x(f.enumCase(e,t),`EnumCase`,e),urlInstance:e=>x(f.urlInstance(e),`URL`,e),urlString:e=>x(f.urlString(e),`string with a URL`,e),truthy:e=>x(f.truthy(e),`truthy`,e),falsy:e=>x(f.falsy(e),`falsy`,e),nan:e=>x(f.nan(e),`NaN`,e),primitive:e=>x(f.primitive(e),`primitive`,e),integer:e=>x(f.integer(e),`integer`,e),safeInteger:e=>x(f.safeInteger(e),`integer`,e),plainObject:e=>x(f.plainObject(e),`plain object`,e),typedArray:e=>x(f.typedArray(e),`TypedArray`,e),arrayLike:e=>x(f.arrayLike(e),`array-like`,e),domElement:e=>x(f.domElement(e),`HTMLElement`,e),observable:e=>x(f.observable(e),`Observable`,e),nodeStream:e=>x(f.nodeStream(e),`Node.js Stream`,e),infinite:e=>x(f.infinite(e),`infinite number`,e),emptyArray:e=>x(f.emptyArray(e),`empty array`,e),nonEmptyArray:e=>x(f.nonEmptyArray(e),`non-empty array`,e),emptyString:e=>x(f.emptyString(e),`empty string`,e),emptyStringOrWhitespace:e=>x(f.emptyStringOrWhitespace(e),`empty string or whitespace`,e),nonEmptyString:e=>x(f.nonEmptyString(e),`non-empty string`,e),nonEmptyStringAndNotWhitespace:e=>x(f.nonEmptyStringAndNotWhitespace(e),`non-empty string and not whitespace`,e),emptyObject:e=>x(f.emptyObject(e),`empty object`,e),nonEmptyObject:e=>x(f.nonEmptyObject(e),`non-empty object`,e),emptySet:e=>x(f.emptySet(e),`empty set`,e),nonEmptySet:e=>x(f.nonEmptySet(e),`non-empty set`,e),emptyMap:e=>x(f.emptyMap(e),`empty map`,e),nonEmptyMap:e=>x(f.nonEmptyMap(e),`non-empty map`,e),propertyKey:e=>x(f.propertyKey(e),`PropertyKey`,e),formData:e=>x(f.formData(e),`FormData`,e),urlSearchParams:e=>x(f.urlSearchParams(e),`URLSearchParams`,e),evenInteger:e=>x(f.evenInteger(e),`even integer`,e),oddInteger:e=>x(f.oddInteger(e),`odd integer`,e),directInstanceOf:(e,t)=>x(f.directInstanceOf(e,t),`T`,e),inRange:(e,t)=>x(f.inRange(e,t),`in range`,e),any:(e,...t)=>x(f.any(e,...t),`predicate returns truthy for any value`,t,{multipleValues:!0}),all:(e,...t)=>x(f.all(e,...t),`predicate returns truthy for all values`,t,{multipleValues:!0})},Object.defineProperties(f,{class:{value:f.class_},function:{value:f.function_},null:{value:f.null_}}),Object.defineProperties(e.assert,{class:{value:e.assert.class_},function:{value:e.assert.function_},null:{value:e.assert.null_}}),e.default=f,t.exports=f,t.exports.default=f,t.exports.assert=e.assert})),jg=X(((e,t)=>{var n=class extends Error{constructor(e){super(e||`Promise was canceled`),this.name=`CancelError`}get isCanceled(){return!0}},r=class e{static fn(t){return(...n)=>new e((e,r,i)=>{n.push(i),t(...n).then(e,r)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((t,n)=>{this._reject=n;let r=e=>{(!this._isCanceled||!a.shouldReject)&&(this._isPending=!1,t(e))},i=e=>{this._isPending=!1,n(e)},a=e=>{if(!this._isPending)throw Error("The `onCancel` handler was attached after the promise settled.");this._cancelHandlers.push(e)};return Object.defineProperties(a,{shouldReject:{get:()=>this._rejectOnCancel,set:e=>{this._rejectOnCancel=e}}}),e(r,i,a)})}then(e,t){return this._promise.then(e,t)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(this._isPending&&!this._isCanceled){if(this._isCanceled=!0,this._cancelHandlers.length>0)try{for(let e of this._cancelHandlers)e()}catch(e){this._reject(e);return}this._rejectOnCancel&&this._reject(new n(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(r.prototype,Promise.prototype),t.exports=r,t.exports.CancelError=n})),Mg=X(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});function n(e){return e.encrypted}var r=(e,t)=>{let r;r=typeof t==`function`?{connect:t}:t;let i=typeof r.connect==`function`,a=typeof r.secureConnect==`function`,o=typeof r.close==`function`,s=()=>{i&&r.connect(),n(e)&&a&&(e.authorized?r.secureConnect():e.authorizationError||e.once(`secureConnect`,r.secureConnect)),o&&e.once(`close`,r.close)};e.writable&&!e.connecting?s():e.connecting?e.once(`connect`,s):e.destroyed&&o&&r.close(e._hadError)};e.default=r,t.exports=r,t.exports.default=r})),Ng=X(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=Mg(),r=Z(`util`),i=Number(process.versions.node.split(`.`)[0]),a=e=>{if(e.timings)return e.timings;let t={start:Date.now(),socket:void 0,lookup:void 0,connect:void 0,secureConnect:void 0,upload:void 0,response:void 0,end:void 0,error:void 0,abort:void 0,phases:{wait:void 0,dns:void 0,tcp:void 0,tls:void 0,request:void 0,firstByte:void 0,download:void 0,total:void 0}};e.timings=t;let a=e=>{let n=e.emit.bind(e);e.emit=(r,...i)=>(r===`error`&&(t.error=Date.now(),t.phases.total=t.error-t.start,e.emit=n),n(r,...i))};a(e);let o=()=>{t.abort=Date.now(),(!t.response||i>=13)&&(t.phases.total=Date.now()-t.start)};e.prependOnceListener(`abort`,o);let s=e=>{if(t.socket=Date.now(),t.phases.wait=t.socket-t.start,r.types.isProxy(e))return;let i=()=>{t.lookup=Date.now(),t.phases.dns=t.lookup-t.socket};e.prependOnceListener(`lookup`,i),n.default(e,{connect:()=>{t.connect=Date.now(),t.lookup===void 0&&(e.removeListener(`lookup`,i),t.lookup=t.connect,t.phases.dns=t.lookup-t.socket),t.phases.tcp=t.connect-t.lookup},secureConnect:()=>{t.secureConnect=Date.now(),t.phases.tls=t.secureConnect-t.connect}})};e.socket?s(e.socket):e.prependOnceListener(`socket`,s);let c=()=>{t.upload=Date.now(),t.phases.request=t.upload-(t.secureConnect??t.connect)};return(typeof e.writableFinished==`boolean`?e.writableFinished:e.finished&&e.outputSize===0&&(!e.socket||e.socket.writableLength===0))?c():e.prependOnceListener(`finish`,c),e.prependOnceListener(`response`,e=>{t.response=Date.now(),t.phases.firstByte=t.response-t.upload,e.timings=t,a(e),e.prependOnceListener(`end`,()=>{t.end=Date.now(),t.phases.download=t.end-t.response,t.phases.total=t.end-t.start}),e.prependOnceListener(`aborted`,o)}),t};e.default=a,t.exports=a,t.exports.default=a})),Pg=X(((e,t)=>{var{V4MAPPED:n,ADDRCONFIG:r,ALL:i,promises:{Resolver:a},lookup:o}=Z(`dns`),{promisify:s}=Z(`util`),c=Z(`os`),l=Symbol(`cacheableLookupCreateConnection`),u=Symbol(`cacheableLookupInstance`),d=Symbol(`expires`),f=typeof i==`number`,p=e=>{if(!(e&&typeof e.createConnection==`function`))throw Error(`Expected an Agent instance as the first argument`)},m=e=>{for(let t of e)t.family!==6&&(t.address=`::ffff:${t.address}`,t.family=6)},h=()=>{let e=!1,t=!1;for(let n of Object.values(c.networkInterfaces()))for(let r of n)if(!r.internal&&(r.family===`IPv6`?t=!0:e=!0,e&&t))return{has4:e,has6:t};return{has4:e,has6:t}},g=e=>Symbol.iterator in e,_={ttl:!0},v={all:!0},y=class{constructor({cache:e=new Map,maxTtl:t=1/0,fallbackDuration:n=3600,errorTtl:r=.15,resolver:i=new a,lookup:c=o}={}){if(this.maxTtl=t,this.errorTtl=r,this._cache=e,this._resolver=i,this._dnsLookup=s(c),this._resolver instanceof a?(this._resolve4=this._resolver.resolve4.bind(this._resolver),this._resolve6=this._resolver.resolve6.bind(this._resolver)):(this._resolve4=s(this._resolver.resolve4.bind(this._resolver)),this._resolve6=s(this._resolver.resolve6.bind(this._resolver))),this._iface=h(),this._pending={},this._nextRemovalTime=!1,this._hostnamesToFallback=new Set,n<1)this._fallback=!1;else{this._fallback=!0;let e=setInterval(()=>{this._hostnamesToFallback.clear()},n*1e3);e.unref&&e.unref()}this.lookup=this.lookup.bind(this),this.lookupAsync=this.lookupAsync.bind(this)}set servers(e){this.clear(),this._resolver.setServers(e)}get servers(){return this._resolver.getServers()}lookup(e,t,n){if(typeof t==`function`?(n=t,t={}):typeof t==`number`&&(t={family:t}),!n)throw Error(`Callback must be a function.`);this.lookupAsync(e,t).then(e=>{t.all?n(null,e):n(null,e.address,e.family,e.expires,e.ttl)},n)}async lookupAsync(e,t={}){typeof t==`number`&&(t={family:t});let a=await this.query(e);if(t.family===6){let e=a.filter(e=>e.family===6);t.hints&n&&(f&&t.hints&i||e.length===0)?m(a):a=e}else t.family===4&&(a=a.filter(e=>e.family===4));if(t.hints&r){let{_iface:e}=this;a=a.filter(t=>t.family===6?e.has6:e.has4)}if(a.length===0){let t=Error(`cacheableLookup ENOTFOUND ${e}`);throw t.code=`ENOTFOUND`,t.hostname=e,t}return t.all?a:a[0]}async query(e){let t=await this._cache.get(e);if(!t){let n=this._pending[e];if(n)t=await n;else{let n=this.queryAndCache(e);this._pending[e]=n;try{t=await n}finally{delete this._pending[e]}}}return t=t.map(e=>({...e})),t}async _resolve(e){let t=async e=>{try{return await e}catch(e){if(e.code===`ENODATA`||e.code===`ENOTFOUND`)return[];throw e}},[n,r]=await Promise.all([this._resolve4(e,_),this._resolve6(e,_)].map(e=>t(e))),i=0,a=0,o=0,s=Date.now();for(let e of n)e.family=4,e.expires=s+e.ttl*1e3,i=Math.max(i,e.ttl);for(let e of r)e.family=6,e.expires=s+e.ttl*1e3,a=Math.max(a,e.ttl);return o=n.length>0?r.length>0?Math.min(i,a):i:a,{entries:[...n,...r],cacheTtl:o}}async _lookup(e){try{return{entries:await this._dnsLookup(e,{all:!0}),cacheTtl:0}}catch{return{entries:[],cacheTtl:0}}}async _set(e,t,n){if(this.maxTtl>0&&n>0){n=Math.min(n,this.maxTtl)*1e3,t[d]=Date.now()+n;try{await this._cache.set(e,t,n)}catch(e){this.lookupAsync=async()=>{let t=Error(`Cache Error. Please recreate the CacheableLookup instance.`);throw t.cause=e,t}}g(this._cache)&&this._tick(n)}}async queryAndCache(e){if(this._hostnamesToFallback.has(e))return this._dnsLookup(e,v);let t=await this._resolve(e);t.entries.length===0&&this._fallback&&(t=await this._lookup(e),t.entries.length!==0&&this._hostnamesToFallback.add(e));let n=t.entries.length===0?this.errorTtl:t.cacheTtl;return await this._set(e,t.entries,n),t.entries}_tick(e){let t=this._nextRemovalTime;(!t||e<t)&&(clearTimeout(this._removalTimeout),this._nextRemovalTime=e,this._removalTimeout=setTimeout(()=>{this._nextRemovalTime=!1;let e=1/0,t=Date.now();for(let[n,r]of this._cache){let i=r[d];t>=i?this._cache.delete(n):i<e&&(e=i)}e!==1/0&&this._tick(e-t)},e),this._removalTimeout.unref&&this._removalTimeout.unref())}install(e){if(p(e),l in e)throw Error(`CacheableLookup has been already installed`);e[l]=e.createConnection,e[u]=this,e.createConnection=(t,n)=>(`lookup`in t||(t.lookup=this.lookup),e[l](t,n))}uninstall(e){if(p(e),e[l]){if(e[u]!==this)throw Error(`The agent is not owned by this CacheableLookup instance`);e.createConnection=e[l],delete e[l],delete e[u]}}updateInterfaceInfo(){let{_iface:e}=this;this._iface=h(),(e.has4&&!this._iface.has4||e.has6&&!this._iface.has6)&&this._cache.clear()}clear(e){e?this._cache.delete(e):this._cache.clear()}};t.exports=y,t.exports.default=y})),Fg=X(((e,t)=>{var n=(e,t)=>t.some(t=>t instanceof RegExp?t.test(e):t===e),r=(e,{stripHash:t})=>{let n=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(e);if(!n)throw Error(`Invalid URL: ${e}`);let{type:r,data:i,hash:a}=n.groups,o=r.split(`;`);a=t?``:a;let s=!1;o[o.length-1]===`base64`&&(o.pop(),s=!0);let c=(o.shift()||``).toLowerCase(),l=[...o.map(e=>{let[t,n=``]=e.split(`=`).map(e=>e.trim());return t===`charset`&&(n=n.toLowerCase(),n===`us-ascii`)?``:`${t}${n?`=${n}`:``}`}).filter(Boolean)];return s&&l.push(`base64`),(l.length!==0||c&&c!==`text/plain`)&&l.unshift(c),`data:${l.join(`;`)},${s?i.trim():i}${a?`#${a}`:``}`};t.exports=(e,t)=>{if(t={defaultProtocol:`http:`,normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...t},e=e.trim(),/^data:/i.test(e))return r(e,t);if(/^view-source:/i.test(e))throw Error("`view-source:` is not supported as it is a non-standard protocol");let i=e.startsWith(`//`);(i||!/^\.*\//.test(e))&&(e=e.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,t.defaultProtocol));let a=new URL(e);if(t.forceHttp&&t.forceHttps)throw Error("The `forceHttp` and `forceHttps` options cannot be used together");if(t.forceHttp&&a.protocol===`https:`&&(a.protocol=`http:`),t.forceHttps&&a.protocol===`http:`&&(a.protocol=`https:`),t.stripAuthentication&&(a.username=``,a.password=``),t.stripHash?a.hash=``:t.stripTextFragment&&(a.hash=a.hash.replace(/#?:~:text.*?$/i,``)),a.pathname&&=a.pathname.replace(/(?<!\b(?:[a-z][a-z\d+\-.]{1,50}:))\/{2,}/g,`/`),a.pathname)try{a.pathname=decodeURI(a.pathname)}catch{}if(t.removeDirectoryIndex===!0&&(t.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(t.removeDirectoryIndex)&&t.removeDirectoryIndex.length>0){let e=a.pathname.split(`/`),r=e[e.length-1];n(r,t.removeDirectoryIndex)&&(e=e.slice(0,e.length-1),a.pathname=e.slice(1).join(`/`)+`/`)}if(a.hostname&&(a.hostname=a.hostname.replace(/\.$/,``),t.stripWWW&&/^www\.(?!www\.)(?:[a-z\-\d]{1,63})\.(?:[a-z.\-\d]{2,63})$/.test(a.hostname)&&(a.hostname=a.hostname.replace(/^www\./,``))),Array.isArray(t.removeQueryParameters))for(let e of[...a.searchParams.keys()])n(e,t.removeQueryParameters)&&a.searchParams.delete(e);t.removeQueryParameters===!0&&(a.search=``),t.sortQueryParameters&&a.searchParams.sort(),t.removeTrailingSlash&&(a.pathname=a.pathname.replace(/\/$/,``));let o=e;return e=a.toString(),!t.removeSingleSlash&&a.pathname===`/`&&!o.endsWith(`/`)&&a.hash===``&&(e=e.replace(/\/$/,``)),(t.removeTrailingSlash||a.pathname===`/`)&&a.hash===``&&t.removeSingleSlash&&(e=e.replace(/\/$/,``)),i&&!t.normalizeProtocol&&(e=e.replace(/^http:\/\//,`//`)),t.stripProtocol&&(e=e.replace(/^(?:https?:)?\/\//,``)),e}})),Ig=X(((e,t)=>{t.exports=n;function n(e,t){if(e&&t)return n(e)(t);if(typeof e!=`function`)throw TypeError(`need wrapper function`);return Object.keys(e).forEach(function(t){r[t]=e[t]}),r;function r(){for(var t=Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),i=t[t.length-1];return typeof r==`function`&&r!==i&&Object.keys(i).forEach(function(e){r[e]=i[e]}),r}}})),Lg=X(((e,t)=>{var n=Ig();t.exports=n(r),t.exports.strict=n(i),r.proto=r(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return r(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return i(this)},configurable:!0})});function r(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function i(e){var t=function(){if(t.called)throw Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)};return t.onceError=(e.name||"Function wrapped with `once`")+` shouldn't be called more than once`,t.called=!1,t}})),Rg=X(((e,t)=>{var n=Lg(),r=function(){},i=global.Bare?queueMicrotask:process.nextTick.bind(process),a=function(e){return e.setHeader&&typeof e.abort==`function`},o=function(e){return e.stdio&&Array.isArray(e.stdio)&&e.stdio.length===3},s=function(e,t,c){if(typeof t==`function`)return s(e,null,t);t||={},c=n(c||r);var l=e._writableState,u=e._readableState,d=t.readable||t.readable!==!1&&e.readable,f=t.writable||t.writable!==!1&&e.writable,p=!1,m=function(){e.writable||h()},h=function(){f=!1,d||c.call(e)},g=function(){d=!1,f||c.call(e)},_=function(t){c.call(e,t?Error(`exited with error code: `+t):null)},v=function(t){c.call(e,t)},y=function(){i(b)},b=function(){if(!p&&(d&&!(u&&u.ended&&!u.destroyed)||f&&!(l&&l.ended&&!l.destroyed)))return c.call(e,Error(`premature close`))},x=function(){e.req.on(`finish`,h)};return a(e)?(e.on(`complete`,h),e.on(`abort`,y),e.req?x():e.on(`request`,x)):f&&!l&&(e.on(`end`,m),e.on(`close`,m)),o(e)&&e.on(`exit`,_),e.on(`end`,g),e.on(`finish`,h),t.error!==!1&&e.on(`error`,v),e.on(`close`,y),function(){p=!0,e.removeListener(`complete`,h),e.removeListener(`abort`,y),e.removeListener(`request`,x),e.req&&e.req.removeListener(`finish`,h),e.removeListener(`end`,m),e.removeListener(`close`,m),e.removeListener(`finish`,h),e.removeListener(`exit`,_),e.removeListener(`end`,g),e.removeListener(`error`,v),e.removeListener(`close`,y)}};t.exports=s})),zg=X(((e,t)=>{var n=Lg(),r=Rg(),i;try{i=Z(`fs`)}catch{}var a=function(){},o=typeof process>`u`?!1:/^v?\.0/.test(process.version),s=function(e){return typeof e==`function`},c=function(e){return!o||!i?!1:(e instanceof(i.ReadStream||a)||e instanceof(i.WriteStream||a))&&s(e.close)},l=function(e){return e.setHeader&&s(e.abort)},u=function(e,t,i,o){o=n(o);var u=!1;e.on(`close`,function(){u=!0}),r(e,{readable:t,writable:i},function(e){if(e)return o(e);u=!0,o()});var d=!1;return function(t){if(!u&&!d){if(d=!0,c(e))return e.close(a);if(l(e))return e.abort();if(s(e.destroy))return e.destroy();o(t||Error(`stream was destroyed`))}}},d=function(e){e()},f=function(e,t){return e.pipe(t)};t.exports=function(){var e=Array.prototype.slice.call(arguments),t=s(e[e.length-1]||a)&&e.pop()||a;if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw Error(`pump requires two streams per minimum`);var n,r=e.map(function(i,a){var o=a<e.length-1;return u(i,o,a>0,function(e){n||=e,e&&r.forEach(d),!o&&(r.forEach(d),t(n))})});return e.reduce(f)}})),Bg=X(((e,t)=>{var{PassThrough:n}=Z(`stream`);t.exports=e=>{e={...e};let{array:t}=e,{encoding:r}=e,i=r===`buffer`,a=!1;t?a=!(r||i):r||=`utf8`,i&&(r=null);let o=new n({objectMode:a});r&&o.setEncoding(r);let s=0,c=[];return o.on(`data`,e=>{c.push(e),a?s=c.length:s+=e.length}),o.getBufferedValue=()=>t?c:i?Buffer.concat(c,s):c.join(``),o.getBufferedLength=()=>s,o}})),Vg=X(((e,t)=>{var{constants:n}=Z(`buffer`),r=zg(),i=Bg(),a=class extends Error{constructor(){super(`maxBuffer exceeded`),this.name=`MaxBufferError`}};async function o(e,t){if(!e)return Promise.reject(Error(`Expected a stream`));t={maxBuffer:1/0,...t};let{maxBuffer:o}=t,s;return await new Promise((c,l)=>{let u=e=>{e&&s.getBufferedLength()<=n.MAX_LENGTH&&(e.bufferedData=s.getBufferedValue()),l(e)};s=r(e,i(t),e=>{e?u(e):c()}),s.on(`data`,()=>{s.getBufferedLength()>o&&u(new a)})}),s.getBufferedValue()}t.exports=o,t.exports.default=o,t.exports.buffer=(e,t)=>o(e,{...t,encoding:`buffer`}),t.exports.array=(e,t)=>o(e,{...t,array:!0}),t.exports.MaxBufferError=a})),Hg=X(((e,t)=>{var n=new Set([200,203,204,206,300,301,308,404,405,410,414,501]),r=new Set([200,203,204,300,301,302,303,307,308,404,405,410,414,501]),i=new Set([500,502,503,504]),a={date:!0,connection:!0,"keep-alive":!0,"proxy-authenticate":!0,"proxy-authorization":!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0},o={"content-length":!0,"content-encoding":!0,"transfer-encoding":!0,"content-range":!0};function s(e){let t=parseInt(e,10);return isFinite(t)?t:0}function c(e){return!e||i.has(e.status)}function l(e){let t={};if(!e)return t;let n=e.trim().split(/,/);for(let e of n){let[n,r]=e.split(/=/,2);t[n.trim()]=r===void 0||r.trim().replace(/^"|"$/g,``)}return t}function u(e){let t=[];for(let n in e){let r=e[n];t.push(r===!0?n:n+`=`+r)}if(t.length)return t.join(`, `)}t.exports=class{constructor(e,t,{shared:n,cacheHeuristic:r,immutableMinTimeToLive:i,ignoreCargoCult:a,_fromObject:o}={}){if(o)this._fromObject(o);else{if(!t||!t.headers)throw Error(`Response headers missing`);this._assertRequestHasHeaders(e),this._responseTime=this.now(),this._isShared=n!==!1,this._ignoreCargoCult=!!a,this._cacheHeuristic=r===void 0?.1:r,this._immutableMinTtl=i===void 0?864e5:i,this._status=`status`in t?t.status:200,this._resHeaders=t.headers,this._rescc=l(t.headers[`cache-control`]),this._method=`method`in e?e.method:`GET`,this._url=e.url,this._host=e.headers.host,this._noAuthorization=!e.headers.authorization,this._reqHeaders=t.headers.vary?e.headers:null,this._reqcc=l(e.headers[`cache-control`]),this._ignoreCargoCult&&`pre-check`in this._rescc&&`post-check`in this._rescc&&(delete this._rescc[`pre-check`],delete this._rescc[`post-check`],delete this._rescc[`no-cache`],delete this._rescc[`no-store`],delete this._rescc[`must-revalidate`],this._resHeaders=Object.assign({},this._resHeaders,{"cache-control":u(this._rescc)}),delete this._resHeaders.expires,delete this._resHeaders.pragma),t.headers[`cache-control`]==null&&/no-cache/.test(t.headers.pragma)&&(this._rescc[`no-cache`]=!0)}}now(){return Date.now()}storable(){return!!(!this._reqcc[`no-store`]&&(this._method===`GET`||this._method===`HEAD`||this._method===`POST`&&this._hasExplicitExpiration())&&r.has(this._status)&&!this._rescc[`no-store`]&&(!this._isShared||!this._rescc.private)&&(!this._isShared||this._noAuthorization||this._allowsStoringAuthenticated())&&(this._resHeaders.expires||this._rescc[`max-age`]||this._isShared&&this._rescc[`s-maxage`]||this._rescc.public||n.has(this._status)))}_hasExplicitExpiration(){return!!(this._isShared&&this._rescc[`s-maxage`]||this._rescc[`max-age`]||this._resHeaders.expires)}_assertRequestHasHeaders(e){if(!e||!e.headers)throw Error(`Request headers missing`)}satisfiesWithoutRevalidation(e){return!this.evaluateRequest(e).revalidation}_evaluateRequestHitResult(e){return{response:{headers:this.responseHeaders()},revalidation:e}}_evaluateRequestRevalidation(e,t){return{synchronous:t,headers:this.revalidationHeaders(e)}}_evaluateRequestMissResult(e){return{response:void 0,revalidation:this._evaluateRequestRevalidation(e,!0)}}evaluateRequest(e){if(this._assertRequestHasHeaders(e),this._rescc[`must-revalidate`]||!this._requestMatches(e,!1))return this._evaluateRequestMissResult(e);let t=l(e.headers[`cache-control`]);return t[`no-cache`]||/no-cache/.test(e.headers.pragma)||t[`max-age`]&&this.age()>s(t[`max-age`])||t[`min-fresh`]&&this.maxAge()-this.age()<s(t[`min-fresh`])?this._evaluateRequestMissResult(e):this.stale()?`max-stale`in t&&(!0===t[`max-stale`]||t[`max-stale`]>this.age()-this.maxAge())?this._evaluateRequestHitResult(void 0):this.useStaleWhileRevalidate()?this._evaluateRequestHitResult(this._evaluateRequestRevalidation(e,!1)):this._evaluateRequestMissResult(e):this._evaluateRequestHitResult(void 0)}_requestMatches(e,t){return!(this._url&&this._url!==e.url||this._host!==e.headers.host||e.method&&this._method!==e.method&&(!t||e.method!==`HEAD`)||!this._varyMatches(e))}_allowsStoringAuthenticated(){return!!(this._rescc[`must-revalidate`]||this._rescc.public||this._rescc[`s-maxage`])}_varyMatches(e){if(!this._resHeaders.vary)return!0;if(this._resHeaders.vary===`*`)return!1;let t=this._resHeaders.vary.trim().toLowerCase().split(/\s*,\s*/);for(let n of t)if(e.headers[n]!==this._reqHeaders[n])return!1;return!0}_copyWithoutHopByHopHeaders(e){let t={};for(let n in e)a[n]||(t[n]=e[n]);if(e.connection){let n=e.connection.trim().split(/\s*,\s*/);for(let e of n)delete t[e]}if(t.warning){let e=t.warning.split(/,/).filter(e=>!/^\s*1[0-9][0-9]/.test(e));e.length?t.warning=e.join(`,`).trim():delete t.warning}return t}responseHeaders(){let e=this._copyWithoutHopByHopHeaders(this._resHeaders),t=this.age();return t>86400&&!this._hasExplicitExpiration()&&this.maxAge()>86400&&(e.warning=(e.warning?`${e.warning}, `:``)+`113 - "rfc7234 5.5.4"`),e.age=`${Math.round(t)}`,e.date=new Date(this.now()).toUTCString(),e}date(){let e=Date.parse(this._resHeaders.date);return isFinite(e)?e:this._responseTime}age(){return this._ageValue()+(this.now()-this._responseTime)/1e3}_ageValue(){return s(this._resHeaders.age)}maxAge(){if(!this.storable()||this._rescc[`no-cache`]||this._isShared&&this._resHeaders[`set-cookie`]&&!this._rescc.public&&!this._rescc.immutable||this._resHeaders.vary===`*`)return 0;if(this._isShared){if(this._rescc[`proxy-revalidate`])return 0;if(this._rescc[`s-maxage`])return s(this._rescc[`s-maxage`])}if(this._rescc[`max-age`])return s(this._rescc[`max-age`]);let e=this._rescc.immutable?this._immutableMinTtl:0,t=this.date();if(this._resHeaders.expires){let n=Date.parse(this._resHeaders.expires);return Number.isNaN(n)||n<t?0:Math.max(e,(n-t)/1e3)}if(this._resHeaders[`last-modified`]){let n=Date.parse(this._resHeaders[`last-modified`]);if(isFinite(n)&&t>n)return Math.max(e,(t-n)/1e3*this._cacheHeuristic)}return e}timeToLive(){let e=this.maxAge()-this.age(),t=e+s(this._rescc[`stale-if-error`]),n=e+s(this._rescc[`stale-while-revalidate`]);return Math.round(Math.max(0,e,t,n)*1e3)}stale(){return this.maxAge()<=this.age()}_useStaleIfError(){return this.maxAge()+s(this._rescc[`stale-if-error`])>this.age()}useStaleWhileRevalidate(){let e=s(this._rescc[`stale-while-revalidate`]);return e>0&&this.maxAge()+e>this.age()}static fromObject(e){return new this(void 0,void 0,{_fromObject:e})}_fromObject(e){if(this._responseTime)throw Error(`Reinitialized`);if(!e||e.v!==1)throw Error(`Invalid serialization`);this._responseTime=e.t,this._isShared=e.sh,this._cacheHeuristic=e.ch,this._immutableMinTtl=e.imm===void 0?864e5:e.imm,this._ignoreCargoCult=!!e.icc,this._status=e.st,this._resHeaders=e.resh,this._rescc=e.rescc,this._method=e.m,this._url=e.u,this._host=e.h,this._noAuthorization=e.a,this._reqHeaders=e.reqh,this._reqcc=e.reqcc}toObject(){return{v:1,t:this._responseTime,sh:this._isShared,ch:this._cacheHeuristic,imm:this._immutableMinTtl,icc:this._ignoreCargoCult,st:this._status,resh:this._resHeaders,rescc:this._rescc,m:this._method,u:this._url,h:this._host,a:this._noAuthorization,reqh:this._reqHeaders,reqcc:this._reqcc}}revalidationHeaders(e){this._assertRequestHasHeaders(e);let t=this._copyWithoutHopByHopHeaders(e.headers);if(delete t[`if-range`],!this._requestMatches(e,!0)||!this.storable())return delete t[`if-none-match`],delete t[`if-modified-since`],t;if(this._resHeaders.etag&&(t[`if-none-match`]=t[`if-none-match`]?`${t[`if-none-match`]}, ${this._resHeaders.etag}`:this._resHeaders.etag),t[`accept-ranges`]||t[`if-match`]||t[`if-unmodified-since`]||this._method&&this._method!=`GET`){if(delete t[`if-modified-since`],t[`if-none-match`]){let e=t[`if-none-match`].split(/,/).filter(e=>!/^\s*W\//.test(e));e.length?t[`if-none-match`]=e.join(`,`).trim():delete t[`if-none-match`]}}else this._resHeaders[`last-modified`]&&!t[`if-modified-since`]&&(t[`if-modified-since`]=this._resHeaders[`last-modified`]);return t}revalidatedPolicy(e,t){if(this._assertRequestHasHeaders(e),this._useStaleIfError()&&c(t))return{policy:this,modified:!1,matches:!0};if(!t||!t.headers)throw Error(`Response headers missing`);let n=!1;t.status!==void 0&&t.status!=304?n=!1:t.headers.etag&&!/^\s*W\//.test(t.headers.etag)?n=this._resHeaders.etag&&this._resHeaders.etag.replace(/^\s*W\//,``)===t.headers.etag:this._resHeaders.etag&&t.headers.etag?n=this._resHeaders.etag.replace(/^\s*W\//,``)===t.headers.etag.replace(/^\s*W\//,``):this._resHeaders[`last-modified`]?n=this._resHeaders[`last-modified`]===t.headers[`last-modified`]:!this._resHeaders.etag&&!this._resHeaders[`last-modified`]&&!t.headers.etag&&!t.headers[`last-modified`]&&(n=!0);let r={shared:this._isShared,cacheHeuristic:this._cacheHeuristic,immutableMinTimeToLive:this._immutableMinTtl,ignoreCargoCult:this._ignoreCargoCult};if(!n)return{policy:new this.constructor(e,t,r),modified:t.status!=304,matches:!1};let i={};for(let e in this._resHeaders)i[e]=e in t.headers&&!o[e]?t.headers[e]:this._resHeaders[e];let a=Object.assign({},t,{status:this._status,method:this._method,headers:i});return{policy:new this.constructor(e,a,r),modified:!1,matches:!0}}}})),Ug=X(((e,t)=>{t.exports=e=>{let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}})),Wg=X(((e,t)=>{var n=Z(`stream`).Readable,r=Ug();t.exports=class extends n{constructor(e,t,n,i){if(typeof e!=`number`)throw TypeError("Argument `statusCode` should be a number");if(typeof t!=`object`)throw TypeError("Argument `headers` should be an object");if(!(n instanceof Buffer))throw TypeError("Argument `body` should be a buffer");if(typeof i!=`string`)throw TypeError("Argument `url` should be a string");super(),this.statusCode=e,this.headers=r(t),this.body=n,this.url=i}_read(){this.push(this.body),this.push(null)}}})),Gg=X(((e,t)=>{var n=[`destroy`,`setTimeout`,`socket`,`headers`,`trailers`,`rawHeaders`,`statusCode`,`httpVersion`,`httpVersionMinor`,`httpVersionMajor`,`rawTrailers`,`statusMessage`];t.exports=(e,t)=>{let r=new Set(Object.keys(e).concat(n));for(let n of r)n in t||(t[n]=typeof e[n]==`function`?e[n].bind(e):e[n])}})),Kg=X(((e,t)=>{var n=Z(`stream`).PassThrough,r=Gg();t.exports=e=>{if(!(e&&e.pipe))throw TypeError("Parameter `response` must be a response stream.");let t=new n;return r(e,t),e.pipe(t)}})),qg=X((e=>{e.stringify=function e(t){if(t===void 0)return t;if(t&&Buffer.isBuffer(t))return JSON.stringify(`:base64:`+t.toString(`base64`));if(t&&t.toJSON&&(t=t.toJSON()),t&&typeof t==`object`){var n=``,r=Array.isArray(t);n=r?`[`:`{`;var i=!0;for(var a in t){var o=typeof t[a]==`function`||!r&&t[a]===void 0;Object.hasOwnProperty.call(t,a)&&!o&&(i||(n+=`,`),i=!1,r?t[a]==null?n+=`null`:n+=e(t[a]):t[a]!==void 0&&(n+=e(a)+`:`+e(t[a])))}return n+=r?`]`:`}`,n}return typeof t==`string`?JSON.stringify(/^:/.test(t)?`:`+t:t):t===void 0?`null`:JSON.stringify(t)},e.parse=function(e){return JSON.parse(e,function(e,t){return typeof t==`string`?/^:base64:/.test(t)?Buffer.from(t.substring(8),`base64`):/^:/.test(t)?t.substring(1):t:t})}})),Jg=X(((e,t)=>{var n=Z(`events`),r=qg(),i=e=>e.adapter||e.uri?new(Z({redis:`@keyv/redis`,rediss:`@keyv/redis`,mongodb:`@keyv/mongo`,mongo:`@keyv/mongo`,sqlite:`@keyv/sqlite`,postgresql:`@keyv/postgres`,postgres:`@keyv/postgres`,mysql:`@keyv/mysql`,etcd:`@keyv/etcd`,offline:`@keyv/offline`,tiered:`@keyv/tiered`}[e.adapter||/^[^:+]*/.exec(e.uri)[0]]))(e):new Map,a=[`sqlite`,`postgres`,`mysql`,`mongo`,`redis`,`tiered`];t.exports=class extends n{constructor(e,{emitErrors:t=!0,...n}={}){if(super(),this.opts={namespace:`keyv`,serialize:r.stringify,deserialize:r.parse,...typeof e==`string`?{uri:e}:e,...n},!this.opts.store){let e={...this.opts};this.opts.store=i(e)}if(this.opts.compression){let e=this.opts.compression;this.opts.serialize=e.serialize.bind(e),this.opts.deserialize=e.deserialize.bind(e)}typeof this.opts.store.on==`function`&&t&&this.opts.store.on(`error`,e=>this.emit(`error`,e)),this.opts.store.namespace=this.opts.namespace;let a=e=>async function*(){for await(let[t,n]of typeof e==`function`?e(this.opts.store.namespace):e){let e=await this.opts.deserialize(n);(!this.opts.store.namespace||t.includes(this.opts.store.namespace))&&(typeof e.expires==`number`&&Date.now()>e.expires?this.delete(t):yield[this._getKeyUnprefix(t),e.value])}};typeof this.opts.store[Symbol.iterator]==`function`&&this.opts.store instanceof Map?this.iterator=a(this.opts.store):typeof this.opts.store.iterator==`function`&&this.opts.store.opts&&this._checkIterableAdaptar()&&(this.iterator=a(this.opts.store.iterator.bind(this.opts.store)))}_checkIterableAdaptar(){return a.includes(this.opts.store.opts.dialect)||a.findIndex(e=>this.opts.store.opts.url.includes(e))>=0}_getKeyPrefix(e){return`${this.opts.namespace}:${e}`}_getKeyPrefixArray(e){return e.map(e=>`${this.opts.namespace}:${e}`)}_getKeyUnprefix(e){return e.split(`:`).splice(1).join(`:`)}get(e,t){let{store:n}=this.opts,r=Array.isArray(e),i=r?this._getKeyPrefixArray(e):this._getKeyPrefix(e);if(r&&n.getMany===void 0){let e=[];for(let r of i)e.push(Promise.resolve().then(()=>n.get(r)).then(e=>typeof e==`string`||this.opts.compression?this.opts.deserialize(e):e).then(e=>{if(e!=null)return typeof e.expires==`number`&&Date.now()>e.expires?this.delete(r).then(()=>void 0):t&&t.raw?e:e.value}));return Promise.allSettled(e).then(e=>{let t=[];for(let n of e)t.push(n.value);return t})}return Promise.resolve().then(()=>r?n.getMany(i):n.get(i)).then(e=>typeof e==`string`||this.opts.compression?this.opts.deserialize(e):e).then(n=>{if(n!=null)return r?n.map((n,r)=>{if(typeof n==`string`&&(n=this.opts.deserialize(n)),n!=null){if(typeof n.expires==`number`&&Date.now()>n.expires)this.delete(e[r]).then(()=>void 0);else return t&&t.raw?n:n.value}}):typeof n.expires==`number`&&Date.now()>n.expires?this.delete(e).then(()=>void 0):t&&t.raw?n:n.value})}set(e,t,n){let r=this._getKeyPrefix(e);n===void 0&&(n=this.opts.ttl),n===0&&(n=void 0);let{store:i}=this.opts;return Promise.resolve().then(()=>{let e=typeof n==`number`?Date.now()+n:null;return typeof t==`symbol`&&this.emit(`error`,`symbol cannot be serialized`),t={value:t,expires:e},this.opts.serialize(t)}).then(e=>i.set(r,e,n)).then(()=>!0)}delete(e){let{store:t}=this.opts;if(Array.isArray(e)){let n=this._getKeyPrefixArray(e);if(t.deleteMany===void 0){let e=[];for(let r of n)e.push(t.delete(r));return Promise.allSettled(e).then(e=>e.every(e=>e.value===!0))}return Promise.resolve().then(()=>t.deleteMany(n))}let n=this._getKeyPrefix(e);return Promise.resolve().then(()=>t.delete(n))}clear(){let{store:e}=this.opts;return Promise.resolve().then(()=>e.clear())}has(e){let t=this._getKeyPrefix(e),{store:n}=this.opts;return Promise.resolve().then(async()=>typeof n.has==`function`?n.has(t):await n.get(t)!==void 0)}disconnect(){let{store:e}=this.opts;if(typeof e.disconnect==`function`)return e.disconnect()}}})),Yg=X(((e,t)=>{var n=Z(`events`),r=Z(`url`),i=Fg(),a=Vg(),o=Hg(),s=Wg(),c=Ug(),l=Kg(),u=Jg(),d=class e{constructor(e,t){if(typeof e!=`function`)throw TypeError("Parameter `request` must be a function");return this.cache=new u({uri:typeof t==`string`&&t,store:typeof t!=`string`&&t,namespace:`cacheable-request`}),this.createCacheableRequest(e)}createCacheableRequest(t){return(u,d)=>{let m;if(typeof u==`string`)m=p(r.parse(u)),u={};else if(u instanceof r.URL)m=p(r.parse(u.toString())),u={};else{let[e,...t]=(u.path||``).split(`?`),n=t.length>0?`?${t.join(`?`)}`:``;m=p({...u,pathname:e,search:n})}u={headers:{},method:`GET`,cache:!0,strictTtl:!1,automaticFailover:!1,...u,...f(m)},u.headers=c(u.headers);let h=new n,g=i(r.format(m),{stripWWW:!1,removeTrailingSlash:!1,stripAuthentication:!1}),_=`${u.method}:${g}`,v=!1,y=!1,b=n=>{y=!0;let r=!1,i,c=new Promise(e=>{i=()=>{r||(r=!0,e())}}),u=t=>{if(v&&!n.forceRefresh){t.status=t.statusCode;let e=o.fromObject(v.cachePolicy).revalidatedPolicy(n,t);if(!e.modified){let n=e.policy.responseHeaders();t=new s(v.statusCode,n,v.body,v.url),t.cachePolicy=e.policy,t.fromCache=!0}}t.fromCache||(t.cachePolicy=new o(n,t,n),t.fromCache=!1);let i;n.cache&&t.cachePolicy.storable()?(i=l(t),(async()=>{try{let e=a.buffer(t);if(await Promise.race([c,new Promise(e=>t.once(`end`,e))]),r)return;let i=await e,o={cachePolicy:t.cachePolicy.toObject(),url:t.url,statusCode:t.fromCache?v.statusCode:t.statusCode,body:i},s=n.strictTtl?t.cachePolicy.timeToLive():void 0;n.maxTtl&&(s=s?Math.min(s,n.maxTtl):n.maxTtl),await this.cache.set(_,o,s)}catch(t){h.emit(`error`,new e.CacheError(t))}})()):n.cache&&v&&(async()=>{try{await this.cache.delete(_)}catch(t){h.emit(`error`,new e.CacheError(t))}})(),h.emit(`response`,i||t),typeof d==`function`&&d(i||t)};try{let e=t(n,u);e.once(`error`,i),e.once(`abort`,i),h.emit(`request`,e)}catch(t){h.emit(`error`,new e.RequestError(t))}};return(async()=>{let t=async e=>{await Promise.resolve();let t=e.cache?await this.cache.get(_):void 0;if(t===void 0)return b(e);let n=o.fromObject(t.cachePolicy);if(n.satisfiesWithoutRevalidation(e)&&!e.forceRefresh){let e=n.responseHeaders(),r=new s(t.statusCode,e,t.body,t.url);r.cachePolicy=n,r.fromCache=!0,h.emit(`response`,r),typeof d==`function`&&d(r)}else v=t,e.headers=n.revalidationHeaders(e),b(e)},n=t=>h.emit(`error`,new e.CacheError(t));this.cache.once(`error`,n),h.on(`response`,()=>this.cache.removeListener(`error`,n));try{await t(u)}catch(t){u.automaticFailover&&!y&&b(u),h.emit(`error`,new e.CacheError(t))}})(),h}}};function f(e){let t={...e};return t.path=`${e.pathname||`/`}${e.search||``}`,delete t.pathname,delete t.search,t}function p(e){return{protocol:e.protocol,auth:e.auth,hostname:e.hostname||e.host||`localhost`,port:e.port,pathname:e.pathname,search:e.search}}d.RequestError=class extends Error{constructor(e){super(e.message),this.name=`RequestError`,Object.assign(this,e)}},d.CacheError=class extends Error{constructor(e){super(e.message),this.name=`CacheError`,Object.assign(this,e)}},t.exports=d})),Xg=X(((e,t)=>{var n=[`aborted`,`complete`,`headers`,`httpVersion`,`httpVersionMinor`,`httpVersionMajor`,`method`,`rawHeaders`,`rawTrailers`,`setTimeout`,`socket`,`statusCode`,`statusMessage`,`trailers`,`url`];t.exports=(e,t)=>{if(t._readableState.autoDestroy)throw Error("The second stream must have the `autoDestroy` option set to `false`");let r=new Set(Object.keys(e).concat(n)),i={};for(let n of r)n in t||(i[n]={get(){let t=e[n];return typeof t==`function`?t.bind(e):t},set(t){e[n]=t},enumerable:!0,configurable:!1});return Object.defineProperties(t,i),e.once(`aborted`,()=>{t.destroy(),t.emit(`aborted`)}),e.once(`close`,()=>{e.complete&&t.readable?t.once(`end`,()=>{t.emit(`close`)}):t.emit(`close`)}),t}})),Zg=X(((e,t)=>{var{Transform:n,PassThrough:r}=Z(`stream`),i=Z(`zlib`),a=Xg();t.exports=e=>{let t=(e.headers[`content-encoding`]||``).toLowerCase();if(![`gzip`,`deflate`,`br`].includes(t))return e;let o=t===`br`;if(o&&typeof i.createBrotliDecompress!=`function`)return e.destroy(Error(`Brotli is not supported on Node.js < 12`)),e;let s=!0,c=new n({transform(e,t,n){s=!1,n(null,e)},flush(e){e()}}),l=new r({autoDestroy:!1,destroy(t,n){e.destroy(),n(t)}}),u=o?i.createBrotliDecompress():i.createUnzip();return u.once(`error`,t=>{s&&!e.readable?l.end():l.destroy(t)}),a(e,l),e.pipe(c).pipe(u).pipe(l),l}})),Qg=X(((e,t)=>{t.exports=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");this.maxSize=e.maxSize,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_set(e,t){if(this.cache.set(e,t),this._size++,this._size>=this.maxSize){if(this._size=0,typeof this.onEviction==`function`)for(let[e,t]of this.oldCache.entries())this.onEviction(e,t);this.oldCache=this.cache,this.cache=new Map}}get(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){let t=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,t),t}}set(e,t){return this.cache.has(e)?this.cache.set(e,t):this._set(e,t),this}has(e){return this.cache.has(e)||this.oldCache.has(e)}peek(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e))return this.oldCache.get(e)}delete(e){let t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache)yield e;for(let e of this.oldCache){let[t]=e;this.cache.has(t)||(yield e)}}get size(){let e=0;for(let t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}}})),$g=X(((e,t)=>{var n=Z(`events`),r=Z(`tls`),i=Z(`http2`),a=Qg(),o=Symbol(`currentStreamsCount`),s=Symbol(`request`),c=Symbol(`cachedOriginSet`),l=Symbol(`gracefullyClosing`),u=`maxDeflateDynamicTableSize.maxSessionMemory.maxHeaderListPairs.maxOutstandingPings.maxReservedRemoteStreams.maxSendHeaderBlockLength.paddingStrategy.localAddress.path.rejectUnauthorized.minDHSize.ca.cert.clientCertEngine.ciphers.key.pfx.servername.minVersion.maxVersion.secureProtocol.crl.honorCipherOrder.ecdhCurve.dhparam.secureOptions.sessionIdContext`.split(`.`),d=(e,t,n)=>{let r=0,i=e.length;for(;r<i;){let a=r+i>>>1;n(e[a],t)?r=a+1:i=a}return r},f=(e,t)=>e.remoteSettings.maxConcurrentStreams>t.remoteSettings.maxConcurrentStreams,p=(e,t)=>{for(let n of e)n[c].length<t[c].length&&n[c].every(e=>t[c].includes(e))&&n[o]+t[o]<=t.remoteSettings.maxConcurrentStreams&&g(n)},m=(e,t)=>{for(let n of e)t[c].length<n[c].length&&t[c].every(e=>n[c].includes(e))&&t[o]+n[o]<=n.remoteSettings.maxConcurrentStreams&&g(t)},h=({agent:e,isFree:t})=>{let n={};for(let r in e.sessions){let i=e.sessions[r].filter(e=>{let n=e[_.kCurrentStreamsCount]<e.remoteSettings.maxConcurrentStreams;return t?n:!n});i.length!==0&&(n[r]=i)}return n},g=e=>{e[l]=!0,e[o]===0&&e.close()},_=class e extends n{constructor({timeout:e=6e4,maxSessions:t=1/0,maxFreeSessions:n=10,maxCachedTlsSessions:r=100}={}){super(),this.sessions={},this.queue={},this.timeout=e,this.maxSessions=t,this.maxFreeSessions=n,this._freeSessionsCount=0,this._sessionsCount=0,this.settings={enablePush:!1},this.tlsSessionCache=new a({maxSize:r})}static normalizeOrigin(e,t){return typeof e==`string`&&(e=new URL(e)),t&&e.hostname!==t&&(e.hostname=t),e.origin}normalizeOptions(e){let t=``;if(e)for(let n of u)e[n]&&(t+=`:${e[n]}`);return t}_tryToCreateNewSession(e,t){if(!(e in this.queue)||!(t in this.queue[e]))return;let n=this.queue[e][t];this._sessionsCount<this.maxSessions&&!n.completed&&(n.completed=!0,n())}getSession(t,n,r){return new Promise((a,u)=>{Array.isArray(r)?(r=[...r],a()):r=[{resolve:a,reject:u}];let h=this.normalizeOptions(n),g=e.normalizeOrigin(t,n&&n.servername);if(g===void 0){for(let{reject:e}of r)e(TypeError("The `origin` argument needs to be a string or an URL object"));return}if(h in this.sessions){let e=this.sessions[h],t=-1,n=-1,i;for(let r of e){let e=r.remoteSettings.maxConcurrentStreams;if(e<t)break;if(r[c].includes(g)){let a=r[o];if(a>=e||r[l]||r.destroyed)continue;i||(t=e),a>n&&(i=r,n=a)}}if(i){if(r.length!==1){for(let{reject:e}of r)e(Error(`Expected the length of listeners to be 1, got ${r.length}.\nPlease report this to https://github.com/szmarczak/http2-wrapper/`));return}r[0].resolve(i);return}}if(h in this.queue){if(g in this.queue[h]){this.queue[h][g].listeners.push(...r),this._tryToCreateNewSession(h,g);return}}else this.queue[h]={};let _=()=>{h in this.queue&&this.queue[h][g]===v&&(delete this.queue[h][g],Object.keys(this.queue[h]).length===0&&delete this.queue[h])},v=()=>{let e=`${g}:${h}`,a=!1;try{let u=i.connect(t,{createConnection:this.createConnection,settings:this.settings,session:this.tlsSessionCache.get(e),...n});u[o]=0,u[l]=!1;let y=()=>u[o]<u.remoteSettings.maxConcurrentStreams,b=!0;u.socket.once(`session`,t=>{this.tlsSessionCache.set(e,t)}),u.once(`error`,t=>{for(let{reject:e}of r)e(t);this.tlsSessionCache.delete(e)}),u.setTimeout(this.timeout,()=>{u.destroy()}),u.once(`close`,()=>{if(a){b&&this._freeSessionsCount--,this._sessionsCount--;let e=this.sessions[h];e.splice(e.indexOf(u),1),e.length===0&&delete this.sessions[h]}else{let e=Error(`Session closed without receiving a SETTINGS frame`);e.code=`HTTP2WRAPPER_NOSETTINGS`;for(let{reject:t}of r)t(e);_()}this._tryToCreateNewSession(h,g)});let x=()=>{if(h in this.queue&&y()){for(let e of u[c])if(e in this.queue[h]){let{listeners:t}=this.queue[h][e];for(;t.length!==0&&y();)t.shift().resolve(u);let n=this.queue[h];if(n[e].listeners.length===0&&(delete n[e],Object.keys(n).length===0)){delete this.queue[h];break}if(!y())break}}};u.on(`origin`,()=>{u[c]=u.originSet,y()&&(x(),p(this.sessions[h],u))}),u.once(`remoteSettings`,()=>{if(u.ref(),u.unref(),this._sessionsCount++,v.destroyed){let e=Error(`Agent has been destroyed`);for(let t of r)t.reject(e);u.destroy()}else{u[c]=u.originSet;{let e=this.sessions;if(h in e){let t=e[h];t.splice(d(t,u,f),0,u)}else e[h]=[u]}this._freeSessionsCount+=1,a=!0,this.emit(`session`,u),x(),_(),u[o]===0&&this._freeSessionsCount>this.maxFreeSessions&&u.close(),r.length!==0&&(this.getSession(g,n,r),r.length=0),u.on(`remoteSettings`,()=>{x(),p(this.sessions[h],u)})}}),u[s]=u.request,u.request=(e,t)=>{if(u[l])throw Error(`The session is gracefully closing. No new streams are allowed.`);let n=u[s](e,t);return u.ref(),++u[o],u[o]===u.remoteSettings.maxConcurrentStreams&&this._freeSessionsCount--,n.once(`close`,()=>{if(b=y(),--u[o],!u.destroyed&&!u.closed&&(m(this.sessions[h],u),y()&&!u.closed)){b||=(this._freeSessionsCount++,!0);let e=u[o]===0;e&&u.unref(),e&&(this._freeSessionsCount>this.maxFreeSessions||u[l])?u.close():(p(this.sessions[h],u),x())}}),n}}catch(e){for(let t of r)t.reject(e);_()}};v.listeners=r,v.completed=!1,v.destroyed=!1,this.queue[h][g]=v,this._tryToCreateNewSession(h,g)})}request(e,t,n,r){return new Promise((i,a)=>{this.getSession(e,t,[{reject:a,resolve:e=>{try{i(e.request(n,r))}catch(e){a(e)}}}])})}createConnection(t,n){return e.connect(t,n)}static connect(e,t){t.ALPNProtocols=[`h2`];let n=e.port||443,i=e.hostname||e.host;return t.servername===void 0&&(t.servername=i),r.connect(n,i,t)}closeFreeSessions(){for(let e of Object.values(this.sessions))for(let t of e)t[o]===0&&t.close()}destroy(e){for(let t of Object.values(this.sessions))for(let n of t)n.destroy(e);for(let e of Object.values(this.queue))for(let t of Object.values(e))t.destroyed=!0;this.queue={}}get freeSessions(){return h({agent:this,isFree:!0})}get busySessions(){return h({agent:this,isFree:!1})}};_.kCurrentStreamsCount=o,_.kGracefullyClosing=l,t.exports={Agent:_,globalAgent:new _}})),e_=X(((e,t)=>{var{Readable:n}=Z(`stream`);t.exports=class extends n{constructor(e,t){super({highWaterMark:t,autoDestroy:!1}),this.statusCode=null,this.statusMessage=``,this.httpVersion=`2.0`,this.httpVersionMajor=2,this.httpVersionMinor=0,this.headers={},this.trailers={},this.req=null,this.aborted=!1,this.complete=!1,this.upgrade=null,this.rawHeaders=[],this.rawTrailers=[],this.socket=e,this.connection=e,this._dumped=!1}_destroy(e){this.req._request.destroy(e)}setTimeout(e,t){return this.req.setTimeout(e,t),this}_dump(){this._dumped||(this._dumped=!0,this.removeAllListeners(`data`),this.resume())}_read(){this.req&&this.req._request.resume()}}})),t_=X(((e,t)=>{t.exports=e=>{let t={protocol:e.protocol,hostname:typeof e.hostname==`string`&&e.hostname.startsWith(`[`)?e.hostname.slice(1,-1):e.hostname,host:e.host,hash:e.hash,search:e.search,pathname:e.pathname,href:e.href,path:`${e.pathname||``}${e.search||``}`};return typeof e.port==`string`&&e.port.length!==0&&(t.port=Number(e.port)),(e.username||e.password)&&(t.auth=`${e.username||``}:${e.password||``}`),t}})),n_=X(((e,t)=>{t.exports=(e,t,n)=>{for(let r of n)e.on(r,(...e)=>t.emit(r,...e))}})),r_=X(((e,t)=>{t.exports=e=>{switch(e){case`:method`:case`:scheme`:case`:authority`:case`:path`:return!0;default:return!1}}})),i_=X(((e,t)=>{var n=(e,n,r)=>{t.exports[n]=class extends e{constructor(...e){super(typeof r==`string`?r:r(e)),this.name=`${super.name} [${n}]`,this.code=n}}};n(TypeError,`ERR_INVALID_ARG_TYPE`,e=>{let t=e[0].includes(`.`)?`property`:`argument`,n=e[1],r=Array.isArray(n);return r&&(n=`${n.slice(0,-1).join(`, `)} or ${n.slice(-1)}`),`The "${e[0]}" ${t} must be ${r?`one of`:`of`} type ${n}. Received ${typeof e[2]}`}),n(TypeError,`ERR_INVALID_PROTOCOL`,e=>`Protocol "${e[0]}" not supported. Expected "${e[1]}"`),n(Error,`ERR_HTTP_HEADERS_SENT`,e=>`Cannot ${e[0]} headers after they are sent to the client`),n(TypeError,`ERR_INVALID_HTTP_TOKEN`,e=>`${e[0]} must be a valid HTTP token [${e[1]}]`),n(TypeError,`ERR_HTTP_INVALID_HEADER_VALUE`,e=>`Invalid value "${e[0]} for header "${e[1]}"`),n(TypeError,`ERR_INVALID_CHAR`,e=>`Invalid character in ${e[0]} [${e[1]}]`)})),a_=X(((e,t)=>{var n=Z(`http2`),{Writable:r}=Z(`stream`),{Agent:i,globalAgent:a}=$g(),o=e_(),s=t_(),c=n_(),l=r_(),{ERR_INVALID_ARG_TYPE:u,ERR_INVALID_PROTOCOL:d,ERR_HTTP_HEADERS_SENT:f,ERR_INVALID_HTTP_TOKEN:p,ERR_HTTP_INVALID_HEADER_VALUE:m,ERR_INVALID_CHAR:h}=i_(),{HTTP2_HEADER_STATUS:g,HTTP2_HEADER_METHOD:_,HTTP2_HEADER_PATH:v,HTTP2_METHOD_CONNECT:y}=n.constants,b=Symbol(`headers`),x=Symbol(`origin`),S=Symbol(`session`),C=Symbol(`options`),w=Symbol(`flushedHeaders`),T=Symbol(`jobs`),E=/^[\^`\-\w!#$%&*+.|~]+$/,D=/[^\t\u0020-\u007E\u0080-\u00FF]/;t.exports=class extends r{constructor(e,t,n){super({autoDestroy:!1});let r=typeof e==`string`||e instanceof URL;if(r&&(e=s(e instanceof URL?e:new URL(e))),typeof t==`function`||t===void 0?(n=t,t=r?e:{...e}):t={...e,...t},t.h2session)this[S]=t.h2session;else if(t.agent===!1)this.agent=new i({maxFreeSessions:0});else if(t.agent===void 0||t.agent===null)typeof t.createConnection==`function`?(this.agent=new i({maxFreeSessions:0}),this.agent.createConnection=t.createConnection):this.agent=a;else if(typeof t.agent.request==`function`)this.agent=t.agent;else throw new u(`options.agent`,[`Agent-like Object`,`undefined`,`false`],t.agent);if(t.protocol&&t.protocol!==`https:`)throw new d(t.protocol,`https:`);let o=t.port||t.defaultPort||this.agent&&this.agent.defaultPort||443,c=t.hostname||t.host||`localhost`;delete t.hostname,delete t.host,delete t.port;let{timeout:l}=t;if(t.timeout=void 0,this[b]=Object.create(null),this[T]=[],this.socket=null,this.connection=null,this.method=t.method||`GET`,this.path=t.path,this.res=null,this.aborted=!1,this.reusedSocket=!1,t.headers)for(let[e,n]of Object.entries(t.headers))this.setHeader(e,n);t.auth&&!(`authorization`in this[b])&&(this[b].authorization=`Basic `+Buffer.from(t.auth).toString(`base64`)),t.session=t.tlsSession,t.path=t.socketPath,this[C]=t,o===443?(this[x]=`https://${c}`,`:authority`in this[b]||(this[b][`:authority`]=c)):(this[x]=`https://${c}:${o}`,`:authority`in this[b]||(this[b][`:authority`]=`${c}:${o}`)),l&&this.setTimeout(l),n&&this.once(`response`,n),this[w]=!1}get method(){return this[b][_]}set method(e){e&&(this[b][_]=e.toUpperCase())}get path(){return this[b][v]}set path(e){e&&(this[b][v]=e)}get _mustNotHaveABody(){return this.method===`GET`||this.method===`HEAD`||this.method===`DELETE`}_write(e,t,n){if(this._mustNotHaveABody){n(Error(`The GET, HEAD and DELETE methods must NOT have a body`));return}this.flushHeaders();let r=()=>this._request.write(e,t,n);this._request?r():this[T].push(r)}_final(e){if(this.destroyed)return;this.flushHeaders();let t=()=>{this._mustNotHaveABody?e():this._request.end(e)};this._request?t():this[T].push(t)}abort(){this.res&&this.res.complete||(this.aborted||process.nextTick(()=>this.emit(`abort`)),this.aborted=!0,this.destroy())}_destroy(e,t){this.res&&this.res._dump(),this._request&&this._request.destroy(),t(e)}async flushHeaders(){if(this[w]||this.destroyed)return;this[w]=!0;let e=this.method===y,t=t=>{if(this._request=t,this.destroyed){t.destroy();return}e||c(t,this,[`timeout`,`continue`,`close`,`error`]);let n=e=>(...t)=>{!this.writable&&!this.destroyed?e(...t):this.once(`finish`,()=>{e(...t)})};t.once(`response`,n((n,r,i)=>{let a=new o(this.socket,t.readableHighWaterMark);this.res=a,a.req=this,a.statusCode=n[g],a.headers=n,a.rawHeaders=i,a.once(`end`,()=>{this.aborted?(a.aborted=!0,a.emit(`aborted`)):(a.complete=!0,a.socket=null,a.connection=null)}),e?(a.upgrade=!0,this.emit(`connect`,a,t,Buffer.alloc(0))?this.emit(`close`):t.destroy()):(t.on(`data`,e=>{!a._dumped&&!a.push(e)&&t.pause()}),t.once(`end`,()=>{a.push(null)}),this.emit(`response`,a)||a._dump())})),t.once(`headers`,n(e=>this.emit(`information`,{statusCode:e[g]}))),t.once(`trailers`,n((e,t,n)=>{let{res:r}=this;r.trailers=e,r.rawTrailers=n}));let{socket:r}=t.session;this.socket=r,this.connection=r;for(let e of this[T])e();this.emit(`socket`,this.socket)};if(this[S])try{t(this[S].request(this[b]))}catch(e){this.emit(`error`,e)}else{this.reusedSocket=!0;try{t(await this.agent.request(this[x],this[C],this[b]))}catch(e){this.emit(`error`,e)}}}getHeader(e){if(typeof e!=`string`)throw new u(`name`,`string`,e);return this[b][e.toLowerCase()]}get headersSent(){return this[w]}removeHeader(e){if(typeof e!=`string`)throw new u(`name`,`string`,e);if(this.headersSent)throw new f(`remove`);delete this[b][e.toLowerCase()]}setHeader(e,t){if(this.headersSent)throw new f(`set`);if(typeof e!=`string`||!E.test(e)&&!l(e))throw new p(`Header name`,e);if(t===void 0)throw new m(t,e);if(D.test(t))throw new h(`header content`,e);this[b][e.toLowerCase()]=t}setNoDelay(){}setSocketKeepAlive(){}setTimeout(e,t){let n=()=>this._request.setTimeout(e,t);return this._request?n():this[T].push(n),this}get maxHeadersCount(){if(!this.destroyed&&this._request)return this._request.session.localSettings.maxHeaderListSize}set maxHeadersCount(e){}}})),o_=X(((e,t)=>{var n=Z(`tls`);t.exports=(e={},t=n.connect)=>new Promise((n,r)=>{let i=!1,a,o=async()=>{await c,a.off(`timeout`,s),a.off(`error`,r),e.resolveSocket?(n({alpnProtocol:a.alpnProtocol,socket:a,timeout:i}),i&&(await Promise.resolve(),a.emit(`timeout`))):(a.destroy(),n({alpnProtocol:a.alpnProtocol,timeout:i}))},s=async()=>{i=!0,o()},c=(async()=>{try{a=await t(e,o),a.on(`error`,r),a.once(`timeout`,s)}catch(e){r(e)}})()})})),s_=X(((e,t)=>{var n=Z(`net`);t.exports=e=>{let t=e.host,r=e.headers&&e.headers.host;return r&&(t=r.startsWith(`[`)?r.indexOf(`]`)===-1?r:r.slice(1,-1):r.split(`:`,1)[0]),n.isIP(t)?``:t}})),c_=X(((e,t)=>{var n=Z(`http`),r=Z(`https`),i=o_(),a=Qg(),o=a_(),s=s_(),c=t_(),l=new a({maxSize:100}),u=new Map,d=(e,t,n)=>{t._httpMessage={shouldKeepAlive:!0};let r=()=>{e.emit(`free`,t,n)};t.on(`free`,r);let i=()=>{e.removeSocket(t,n)};t.on(`close`,i);let a=()=>{e.removeSocket(t,n),t.off(`close`,i),t.off(`free`,r),t.off(`agentRemove`,a)};t.on(`agentRemove`,a),e.emit(`free`,t,n)},f=async e=>{let t=`${e.host}:${e.port}:${e.ALPNProtocols.sort()}`;if(!l.has(t)){if(u.has(t))return(await u.get(t)).alpnProtocol;let{path:n,agent:a}=e;e.path=e.socketPath;let o=i(e);u.set(t,o);try{let{socket:i,alpnProtocol:s}=await o;if(l.set(t,s),e.path=n,s===`h2`)i.destroy();else{let{globalAgent:t}=r,n=r.Agent.prototype.createConnection;a?a.createConnection===n?d(a,i,e):i.destroy():t.createConnection===n?d(t,i,e):i.destroy()}return u.delete(t),s}catch(e){throw u.delete(t),e}}return l.get(t)};t.exports=async(e,t,i)=>{if((typeof e==`string`||e instanceof URL)&&(e=c(new URL(e))),typeof t==`function`&&(i=t,t=void 0),t={ALPNProtocols:[`h2`,`http/1.1`],...e,...t,resolveSocket:!0},!Array.isArray(t.ALPNProtocols)||t.ALPNProtocols.length===0)throw Error("The `ALPNProtocols` option must be an Array with at least one entry");t.protocol=t.protocol||`https:`;let a=t.protocol===`https:`;t.host=t.hostname||t.host||`localhost`,t.session=t.tlsSession,t.servername=t.servername||s(t),t.port=t.port||(a?443:80),t._defaultAgent=a?r.globalAgent:n.globalAgent;let l=t.agent;if(l){if(l.addRequest)throw Error("The `options.agent` object can contain only `http`, `https` or `http2` properties");t.agent=l[a?`https`:`http`]}return a&&await f(t)===`h2`?(l&&(t.agent=l.http2),new o(t,i)):n.request(t,i)},t.exports.protocolCache=l})),l_=X(((e,t)=>{var n=Z(`http2`),r=$g(),i=a_(),a=e_(),o=c_(),s=(e,t,n)=>new i(e,t,n),c=(e,t,n)=>{let r=new i(e,t,n);return r.end(),r};t.exports={...n,ClientRequest:i,IncomingMessage:a,...r,request:s,get:c,auto:o}})),u_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Ag();e.default=e=>t.default.nodeStream(e)&&t.default.function_(e.getBoundary)})),d_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Z(`fs`),n=Z(`util`),r=Ag(),i=u_(),a=n.promisify(t.stat);e.default=async(e,o)=>{if(o&&`content-length`in o)return Number(o[`content-length`]);if(!e)return 0;if(r.default.string(e))return Buffer.byteLength(e);if(r.default.buffer(e))return e.length;if(i.default(e))return n.promisify(e.getLength.bind(e))();if(e instanceof t.ReadStream){let{size:t}=await a(e.path);return t===0?void 0:t}}})),f_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e,t,n){let r={};for(let i of n)r[i]=(...e)=>{t.emit(i,...e)},e.on(i,r[i]);return()=>{for(let t of n)e.off(t,r[t])}}e.default=t})),p_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=()=>{let e=[];return{once(t,n,r){t.once(n,r),e.push({origin:t,event:n,fn:r})},unhandleAll(){for(let t of e){let{origin:e,event:n,fn:r}=t;e.removeListener(n,r)}e.length=0}}}})),m_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TimeoutError=void 0;var t=Z(`net`),n=p_(),r=Symbol(`reentry`),i=()=>{},a=class extends Error{constructor(e,t){super(`Timeout awaiting '${t}' for ${e}ms`),this.event=t,this.name=`TimeoutError`,this.code=`ETIMEDOUT`}};e.TimeoutError=a,e.default=(e,o,s)=>{if(r in e)return i;e[r]=!0;let c=[],{once:l,unhandleAll:u}=n.default(),d=(e,t,n)=>{var r;let i=setTimeout(t,e,e,n);(r=i.unref)==null||r.call(i);let a=()=>{clearTimeout(i)};return c.push(a),a},{host:f,hostname:p}=s,m=(t,n)=>{e.destroy(new a(t,n))},h=()=>{for(let e of c)e();u()};if(e.once(`error`,t=>{if(h(),e.listenerCount(`error`)===0)throw t}),e.once(`close`,h),l(e,`response`,e=>{l(e,`end`,h)}),o.request!==void 0&&d(o.request,m,`request`),o.socket!==void 0){let t=()=>{m(o.socket,`socket`)};e.setTimeout(o.socket,t),c.push(()=>{e.removeListener(`timeout`,t)})}return l(e,`socket`,n=>{let{socketPath:r}=e;if(n.connecting){let e=!!(r??t.isIP(p??f??``)!==0);if(o.lookup!==void 0&&!e&&n.address().address===void 0){let e=d(o.lookup,m,`lookup`);l(n,`lookup`,e)}if(o.connect!==void 0){let t=()=>d(o.connect,m,`connect`);e?l(n,`connect`,t()):l(n,`lookup`,e=>{e===null&&l(n,`connect`,t())})}o.secureConnect!==void 0&&s.protocol===`https:`&&l(n,`connect`,()=>{let e=d(o.secureConnect,m,`secureConnect`);l(n,`secureConnect`,e)})}if(o.send!==void 0){let t=()=>d(o.send,m,`send`);n.connecting?l(n,`connect`,()=>{l(e,`upload-complete`,t())}):l(e,`upload-complete`,t())}}),o.response!==void 0&&l(e,`upload-complete`,()=>{let t=d(o.response,m,`response`);l(e,`response`,t)}),h}})),h_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Ag();e.default=e=>{e=e;let n={protocol:e.protocol,hostname:t.default.string(e.hostname)&&e.hostname.startsWith(`[`)?e.hostname.slice(1,-1):e.hostname,host:e.host,hash:e.hash,search:e.search,pathname:e.pathname,href:e.href,path:`${e.pathname||``}${e.search||``}`};return t.default.string(e.port)&&e.port.length>0&&(n.port=Number(e.port)),(e.username||e.password)&&(n.auth=`${e.username||``}:${e.password||``}`),n}})),g_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Z(`url`),n=[`protocol`,`host`,`hostname`,`port`,`pathname`,`search`];e.default=(e,r)=>{if(r.path){if(r.pathname)throw TypeError("Parameters `path` and `pathname` are mutually exclusive.");if(r.search)throw TypeError("Parameters `path` and `search` are mutually exclusive.");if(r.searchParams)throw TypeError("Parameters `path` and `searchParams` are mutually exclusive.")}if(r.search&&r.searchParams)throw TypeError("Parameters `search` and `searchParams` are mutually exclusive.");if(!e){if(!r.protocol)throw TypeError(`No URL protocol specified`);e=`${r.protocol}//${r.hostname??r.host??``}`}let i=new t.URL(e);if(r.path){let e=r.path.indexOf(`?`);e===-1?r.pathname=r.path:(r.pathname=r.path.slice(0,e),r.search=r.path.slice(e+1)),delete r.path}for(let e of n)r[e]&&(i[e]=r[e].toString());return i}})),__=X((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class{constructor(){this.weakMap=new WeakMap,this.map=new Map}set(e,t){typeof e==`object`?this.weakMap.set(e,t):this.map.set(e,t)}get(e){return typeof e==`object`?this.weakMap.get(e):this.map.get(e)}has(e){return typeof e==`object`?this.weakMap.has(e):this.map.has(e)}}})),v_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=async e=>{let t=[],n=0;for await(let r of e)t.push(r),n+=Buffer.byteLength(r);return Buffer.isBuffer(t[0])?Buffer.concat(t,n):Buffer.from(t.join(``))}})),y_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.dnsLookupIpVersionToFamily=e.isDnsLookupIpVersion=void 0;var t={auto:0,ipv4:4,ipv6:6};e.isDnsLookupIpVersion=e=>e in t,e.dnsLookupIpVersionToFamily=n=>{if(e.isDnsLookupIpVersion(n))return t[n];throw Error(`Invalid DNS lookup IP version`)}})),b_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isResponseOk=void 0,e.isResponseOk=e=>{let{statusCode:t}=e,n=e.request.options.followRedirect?299:399;return t>=200&&t<=n||t===304}})),x_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=new Set;e.default=e=>{t.has(e)||(t.add(e),process.emitWarning(`Got: ${e}`,{type:`DeprecationWarning`}))}})),S_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Ag();e.default=(e,n)=>{if(t.default.null_(e.encoding))throw TypeError("To get a Buffer, set `options.responseType` to `buffer` instead");t.assert.any([t.default.string,t.default.undefined],e.encoding),t.assert.any([t.default.boolean,t.default.undefined],e.resolveBodyOnly),t.assert.any([t.default.boolean,t.default.undefined],e.methodRewriting),t.assert.any([t.default.boolean,t.default.undefined],e.isStream),t.assert.any([t.default.string,t.default.undefined],e.responseType),e.responseType===void 0&&(e.responseType=`text`);let{retry:r}=e;if(e.retry=n?{...n.retry}:{calculateDelay:e=>e.computedValue,limit:0,methods:[],statusCodes:[],errorCodes:[],maxRetryAfter:void 0},t.default.object(r)?(e.retry={...e.retry,...r},e.retry.methods=[...new Set(e.retry.methods.map(e=>e.toUpperCase()))],e.retry.statusCodes=[...new Set(e.retry.statusCodes)],e.retry.errorCodes=[...new Set(e.retry.errorCodes)]):t.default.number(r)&&(e.retry.limit=r),t.default.undefined(e.retry.maxRetryAfter)&&(e.retry.maxRetryAfter=Math.min(...[e.timeout.request,e.timeout.connect].filter(t.default.number))),t.default.object(e.pagination)){n&&(e.pagination={...n.pagination,...e.pagination});let{pagination:r}=e;if(!t.default.function_(r.transform))throw Error("`options.pagination.transform` must be implemented");if(!t.default.function_(r.shouldContinue))throw Error("`options.pagination.shouldContinue` must be implemented");if(!t.default.function_(r.filter))throw TypeError("`options.pagination.filter` must be implemented");if(!t.default.function_(r.paginate))throw Error("`options.pagination.paginate` must be implemented")}return e.responseType===`json`&&e.headers.accept===void 0&&(e.headers.accept=`application/json`),e}})),C_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.retryAfterStatusCodes=void 0,e.retryAfterStatusCodes=new Set([413,429,503]),e.default=({attemptCount:e,retryOptions:t,error:n,retryAfter:r})=>{if(e>t.limit)return 0;let i=t.methods.includes(n.options.method),a=t.errorCodes.includes(n.code),o=n.response&&t.statusCodes.includes(n.response.statusCode);if(!i||!a&&!o)return 0;if(n.response){if(r)return t.maxRetryAfter===void 0||r>t.maxRetryAfter?0:r;if(n.response.statusCode===413)return 0}let s=Math.random()*100;return 2**(e-1)*1e3+s}})),w_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.UnsupportedProtocolError=e.ReadError=e.TimeoutError=e.UploadError=e.CacheError=e.HTTPError=e.MaxRedirectsError=e.RequestError=e.setNonEnumerableProperties=e.knownHookEvents=e.withoutBody=e.kIsNormalizedAlready=void 0;var t=Z(`util`),n=Z(`stream`),r=Z(`fs`),i=Z(`url`),a=Z(`http`),o=Z(`http`),s=Z(`https`),c=Ng(),l=Pg(),u=Yg(),d=Zg(),f=l_(),p=Ug(),m=Ag(),h=d_(),g=u_(),_=f_(),v=m_(),y=h_(),b=g_(),x=__(),S=v_(),C=y_(),w=b_(),T=x_(),E=S_(),D=C_(),O,k=Symbol(`request`),A=Symbol(`response`),j=Symbol(`responseSize`),M=Symbol(`downloadedSize`),N=Symbol(`bodySize`),P=Symbol(`uploadedSize`),F=Symbol(`serverResponsesPiped`),ee=Symbol(`unproxyEvents`),te=Symbol(`isFromCache`),ne=Symbol(`cancelTimeouts`),re=Symbol(`startedReading`),ie=Symbol(`stopReading`),ae=Symbol(`triggerRead`),oe=Symbol(`body`),se=Symbol(`jobs`),ce=Symbol(`originalResponse`),le=Symbol(`retryTimeout`);e.kIsNormalizedAlready=Symbol(`isNormalizedAlready`);var ue=m.default.string(process.versions.brotli);e.withoutBody=new Set([`GET`,`HEAD`]),e.knownHookEvents=[`init`,`beforeRequest`,`beforeRedirect`,`beforeError`,`beforeRetry`,`afterResponse`];function de(e){for(let t in e){let n=e[t];if(!m.default.string(n)&&!m.default.number(n)&&!m.default.boolean(n)&&!m.default.null_(n)&&!m.default.undefined(n))throw TypeError(`The \`searchParams\` value '${String(n)}' must be a string, number, boolean or null`)}}function fe(e){return m.default.object(e)&&!(`statusCode`in e)}var pe=new x.default,me=async e=>new Promise((t,n)=>{let r=e=>{n(e)};e.pending||t(),e.once(`error`,r),e.once(`ready`,()=>{e.off(`error`,r),t()})}),he=new Set([300,301,302,303,304,307,308]),ge=[`context`,`body`,`json`,`form`];e.setNonEnumerableProperties=(e,t)=>{let n={};for(let t of e)if(t)for(let e of ge)e in t&&(n[e]={writable:!0,configurable:!0,enumerable:!1,value:t[e]});Object.defineProperties(t,n)};var _e=class extends Error{constructor(e,t,n){if(super(e),Error.captureStackTrace(this,this.constructor),this.name=`RequestError`,this.code=t.code??`ERR_GOT_REQUEST_ERROR`,n instanceof Te?(Object.defineProperty(this,"request",{enumerable:!1,value:n}),Object.defineProperty(this,"response",{enumerable:!1,value:n[A]}),Object.defineProperty(this,"options",{enumerable:!1,value:n.options})):Object.defineProperty(this,"options",{enumerable:!1,value:n}),this.timings=this.request?.timings,m.default.string(t.stack)&&m.default.string(this.stack)){let e=this.stack.indexOf(this.message)+this.message.length,n=this.stack.slice(e).split(`
|
|
72
86
|
`).reverse(),r=t.stack.slice(t.stack.indexOf(t.message)+t.message.length).split(`
|
|
73
87
|
`).reverse();for(;r.length!==0&&r[0]===n[0];)n.shift();this.stack=`${this.stack.slice(0,e)}${n.reverse().join(`
|
|
74
88
|
`)}${r.reverse().join(`
|
|
75
|
-
`)}`}}};e.RequestError=ge;var _e=class extends ge{constructor(e){super(`Redirected ${e.options.maxRedirects} times. Aborting.`,{},e),this.name=`MaxRedirectsError`,this.code=`ERR_TOO_MANY_REDIRECTS`}};e.MaxRedirectsError=_e;var ve=class extends ge{constructor(e){super(`Response code ${e.statusCode} (${e.statusMessage})`,{},e.request),this.name=`HTTPError`,this.code=`ERR_NON_2XX_3XX_RESPONSE`}};e.HTTPError=ve;var L=class extends ge{constructor(e,t){super(e.message,e,t),this.name=`CacheError`,this.code=this.code===`ERR_GOT_REQUEST_ERROR`?`ERR_CACHE_ACCESS`:this.code}};e.CacheError=L;var ye=class extends ge{constructor(e,t){super(e.message,e,t),this.name=`UploadError`,this.code=this.code===`ERR_GOT_REQUEST_ERROR`?`ERR_UPLOAD`:this.code}};e.UploadError=ye;var be=class extends ge{constructor(e,t,n){super(e.message,e,n),this.name=`TimeoutError`,this.event=e.event,this.timings=t}};e.TimeoutError=be;var xe=class extends ge{constructor(e,t){super(e.message,e,t),this.name=`ReadError`,this.code=this.code===`ERR_GOT_REQUEST_ERROR`?`ERR_READING_RESPONSE_STREAM`:this.code}};e.ReadError=xe;var Se=class extends ge{constructor(e){super(`Unsupported protocol "${e.url.protocol}"`,{},e),this.name=`UnsupportedProtocolError`,this.code=`ERR_UNSUPPORTED_PROTOCOL`}};e.UnsupportedProtocolError=Se;var Ce=[`socket`,`connect`,`continue`,`information`,`upgrade`,`timeout`],we=class extends n.Duplex{constructor(t,n={},i){super({autoDestroy:!1,highWaterMark:0}),this[M]=0,this[P]=0,this.requestInitialized=!1,this[F]=new Set,this.redirects=[],this[re]=!1,this[ie]=!1,this[oe]=[],this.retryCount=0,this._progressCallbacks=[];let a=()=>this._unlockWrite(),s=()=>this._lockWrite();this.on(`pipe`,e=>{e.prependListener(`data`,a),e.on(`data`,s),e.prependListener(`end`,a),e.on(`end`,s)}),this.on(`unpipe`,e=>{e.off(`data`,a),e.off(`data`,s),e.off(`end`,a),e.off(`end`,s)}),this.on(`pipe`,e=>{e instanceof o.IncomingMessage&&(this.options.headers={...e.headers,...this.options.headers})});let{json:c,body:l,form:u}=n;if((c||l||u)&&this._lockWrite(),e.kIsNormalizedAlready in n)this.options=n;else try{this.options=this.constructor.normalizeArguments(t,n,i)}catch(e){m.default.nodeStream(n.body)&&n.body.destroy(),this.destroy(e);return}(async()=>{var e;try{this.options.body instanceof r.ReadStream&&await pe(this.options.body);let{url:t}=this.options;if(!t)throw TypeError("Missing `url` property");if(this.requestUrl=t.toString(),decodeURI(this.requestUrl),await this._finalizeBody(),await this._makeRequest(),this.destroyed){(e=this[k])==null||e.destroy();return}for(let e of this[oe])e();this[oe].length=0,this.requestInitialized=!0}catch(e){if(e instanceof ge){this._beforeError(e);return}this.destroyed||this.destroy(e)}})()}static normalizeArguments(n,r,a){var o;let s=r;if(m.default.object(n)&&!m.default.urlInstance(n))r={...a,...n,...r};else{if(n&&r&&r.url!==void 0)throw TypeError("The `url` option is mutually exclusive with the `input` argument");r={...a,...r},n!==void 0&&(r.url=n),m.default.urlInstance(r.url)&&(r.url=new i.URL(r.url.toString()))}if(r.cache===!1&&(r.cache=void 0),r.dnsCache===!1&&(r.dnsCache=void 0),m.assert.any([m.default.string,m.default.undefined],r.method),m.assert.any([m.default.object,m.default.undefined],r.headers),m.assert.any([m.default.string,m.default.urlInstance,m.default.undefined],r.prefixUrl),m.assert.any([m.default.object,m.default.undefined],r.cookieJar),m.assert.any([m.default.object,m.default.string,m.default.undefined],r.searchParams),m.assert.any([m.default.object,m.default.string,m.default.undefined],r.cache),m.assert.any([m.default.object,m.default.number,m.default.undefined],r.timeout),m.assert.any([m.default.object,m.default.undefined],r.context),m.assert.any([m.default.object,m.default.undefined],r.hooks),m.assert.any([m.default.boolean,m.default.undefined],r.decompress),m.assert.any([m.default.boolean,m.default.undefined],r.ignoreInvalidCookies),m.assert.any([m.default.boolean,m.default.undefined],r.followRedirect),m.assert.any([m.default.number,m.default.undefined],r.maxRedirects),m.assert.any([m.default.boolean,m.default.undefined],r.throwHttpErrors),m.assert.any([m.default.boolean,m.default.undefined],r.http2),m.assert.any([m.default.boolean,m.default.undefined],r.allowGetBody),m.assert.any([m.default.string,m.default.undefined],r.localAddress),m.assert.any([C.isDnsLookupIpVersion,m.default.undefined],r.dnsLookupIpVersion),m.assert.any([m.default.object,m.default.undefined],r.https),m.assert.any([m.default.boolean,m.default.undefined],r.rejectUnauthorized),r.https&&(m.assert.any([m.default.boolean,m.default.undefined],r.https.rejectUnauthorized),m.assert.any([m.default.function_,m.default.undefined],r.https.checkServerIdentity),m.assert.any([m.default.string,m.default.object,m.default.array,m.default.undefined],r.https.certificateAuthority),m.assert.any([m.default.string,m.default.object,m.default.array,m.default.undefined],r.https.key),m.assert.any([m.default.string,m.default.object,m.default.array,m.default.undefined],r.https.certificate),m.assert.any([m.default.string,m.default.undefined],r.https.passphrase),m.assert.any([m.default.string,m.default.buffer,m.default.array,m.default.undefined],r.https.pfx)),m.assert.any([m.default.object,m.default.undefined],r.cacheOptions),m.default.string(r.method)?r.method=r.method.toUpperCase():r.method=`GET`,r.headers===a?.headers?r.headers={...r.headers}:r.headers=p({...a?.headers,...r.headers}),`slashes`in r)throw TypeError("The legacy `url.Url` has been deprecated. Use `URL` instead.");if(`auth`in r)throw TypeError("Parameter `auth` is deprecated. Use `username` / `password` instead.");if(`searchParams`in r&&r.searchParams&&r.searchParams!==a?.searchParams){let e;if(m.default.string(r.searchParams)||r.searchParams instanceof i.URLSearchParams)e=new i.URLSearchParams(r.searchParams);else{ue(r.searchParams),e=new i.URLSearchParams;for(let t in r.searchParams){let n=r.searchParams[t];n===null?e.append(t,``):n!==void 0&&e.append(t,n)}}(o=a?.searchParams)==null||o.forEach((t,n)=>{e.has(n)||e.append(n,t)}),r.searchParams=e}if(r.username=r.username??``,r.password=r.password??``,m.default.undefined(r.prefixUrl)?r.prefixUrl=a?.prefixUrl??``:(r.prefixUrl=r.prefixUrl.toString(),r.prefixUrl!==``&&!r.prefixUrl.endsWith(`/`)&&(r.prefixUrl+=`/`)),m.default.string(r.url)){if(r.url.startsWith(`/`))throw Error("`input` must not start with a slash when using `prefixUrl`");r.url=b.default(r.prefixUrl+r.url,r)}else(m.default.undefined(r.url)&&r.prefixUrl!==``||r.protocol)&&(r.url=b.default(r.prefixUrl,r));if(r.url){`port`in r&&delete r.port;let{prefixUrl:e}=r;Object.defineProperty(r,"prefixUrl",{set:t=>{let n=r.url;if(!n.href.startsWith(t))throw Error(`Cannot change \`prefixUrl\` from ${e} to ${t}: ${n.href}`);r.url=new i.URL(t+n.href.slice(e.length)),e=t},get:()=>e});let{protocol:t}=r.url;if(t===`unix:`&&(t=`http:`,r.url=new i.URL(`http://unix${r.url.pathname}${r.url.search}`)),r.searchParams&&(r.url.search=r.searchParams.toString()),t!==`http:`&&t!==`https:`)throw new Se(r);r.username===``?r.username=r.url.username:r.url.username=r.username,r.password===``?r.password=r.url.password:r.url.password=r.password}let{cookieJar:c}=r;if(c){let{setCookie:e,getCookieString:n}=c;m.assert.function_(e),m.assert.function_(n),e.length===4&&n.length===0&&(e=t.promisify(e.bind(r.cookieJar)),n=t.promisify(n.bind(r.cookieJar)),r.cookieJar={setCookie:e,getCookieString:n})}let{cache:d}=r;if(d&&(fe.has(d)||fe.set(d,new u(((e,t)=>{let n=e[k](e,t);return m.default.promise(n)&&(n.once=(e,t)=>{if(e===`error`)n.catch(t);else if(e===`abort`)(async()=>{try{(await n).once(`abort`,t)}catch{}})();else throw Error(`Unknown HTTP2 promise event: ${e}`);return n}),n}),d))),r.cacheOptions={...r.cacheOptions},r.dnsCache===!0)O||=new l.default,r.dnsCache=O;else if(!m.default.undefined(r.dnsCache)&&!r.dnsCache.lookup)throw TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${m.default(r.dnsCache)}`);m.default.number(r.timeout)?r.timeout={request:r.timeout}:a&&r.timeout!==a.timeout?r.timeout={...a.timeout,...r.timeout}:r.timeout={...r.timeout},r.context||(r.context={});let f=r.hooks===a?.hooks;r.hooks={...r.hooks};for(let t of e.knownHookEvents)if(t in r.hooks){if(m.default.array(r.hooks[t]))r.hooks[t]=[...r.hooks[t]];else throw TypeError(`Parameter \`${t}\` must be an Array, got ${m.default(r.hooks[t])}`)}else r.hooks[t]=[];if(a&&!f)for(let t of e.knownHookEvents)a.hooks[t].length>0&&(r.hooks[t]=[...a.hooks[t],...r.hooks[t]]);if(`family`in r&&T.default(`"options.family" was never documented, please use "options.dnsLookupIpVersion"`),a?.https&&(r.https={...a.https,...r.https}),`rejectUnauthorized`in r&&T.default(`"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"`),`checkServerIdentity`in r&&T.default(`"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"`),`ca`in r&&T.default(`"options.ca" was never documented, please use "options.https.certificateAuthority"`),`key`in r&&T.default(`"options.key" was never documented, please use "options.https.key"`),`cert`in r&&T.default(`"options.cert" was never documented, please use "options.https.certificate"`),`passphrase`in r&&T.default(`"options.passphrase" was never documented, please use "options.https.passphrase"`),`pfx`in r&&T.default(`"options.pfx" was never documented, please use "options.https.pfx"`),`followRedirects`in r)throw TypeError("The `followRedirects` option does not exist. Use `followRedirect` instead.");if(r.agent){for(let e in r.agent)if(e!==`http`&&e!==`https`&&e!==`http2`)throw TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${e}\``)}return r.maxRedirects=r.maxRedirects??0,e.setNonEnumerableProperties([a,s],r),E.default(r,a)}_lockWrite(){let e=()=>{throw TypeError(`The payload has been already provided`)};this.write=e,this.end=e}_unlockWrite(){this.write=super.write,this.end=super.end}async _finalizeBody(){let{options:t}=this,{headers:r}=t,a=!m.default.undefined(t.form),o=!m.default.undefined(t.json),s=!m.default.undefined(t.body),c=a||o||s,l=e.withoutBody.has(t.method)&&!(t.method===`GET`&&t.allowGetBody);if(this._cannotHaveBody=l,c){if(l)throw TypeError(`The \`${t.method}\` method cannot be used with a body`);if([s,a,o].filter(e=>e).length>1)throw TypeError("The `body`, `json` and `form` options are mutually exclusive");if(s&&!(t.body instanceof n.Readable)&&!m.default.string(t.body)&&!m.default.buffer(t.body)&&!g.default(t.body))throw TypeError("The `body` option must be a stream.Readable, string or Buffer");if(a&&!m.default.object(t.form))throw TypeError("The `form` option must be an Object");{let e=!m.default.string(r[`content-type`]);s?(g.default(t.body)&&e&&(r[`content-type`]=`multipart/form-data; boundary=${t.body.getBoundary()}`),this[ae]=t.body):a?(e&&(r[`content-type`]=`application/x-www-form-urlencoded`),this[ae]=new i.URLSearchParams(t.form).toString()):(e&&(r[`content-type`]=`application/json`),this[ae]=t.stringifyJson(t.json));let n=await h.default(this[ae],t.headers);m.default.undefined(r[`content-length`])&&m.default.undefined(r[`transfer-encoding`])&&!l&&!m.default.undefined(n)&&(r[`content-length`]=String(n))}}else l?this._lockWrite():this._unlockWrite();this[N]=Number(r[`content-length`])||void 0}async _onResponseBase(e){let{options:t}=this,{url:n}=t;this[se]=e,t.decompress&&(e=d(e));let r=e.statusCode,o=e;o.statusMessage=o.statusMessage?o.statusMessage:a.STATUS_CODES[r],o.url=t.url.toString(),o.requestUrl=this.requestUrl,o.redirectUrls=this.redirects,o.request=this,o.isFromCache=e.fromCache||!1,o.ip=this.ip,o.retryCount=this.retryCount,this[ee]=o.isFromCache,this[j]=Number(e.headers[`content-length`])||void 0,this[A]=e,e.once(`end`,()=>{this[j]=this[M],this.emit(`downloadProgress`,this.downloadProgress)}),e.once(`error`,t=>{e.destroy(),this._beforeError(new xe(t,this))}),e.once(`aborted`,()=>{this._beforeError(new xe({name:`Error`,message:`The server aborted pending request`,code:`ECONNRESET`},this))}),this.emit(`downloadProgress`,this.downloadProgress);let s=e.headers[`set-cookie`];if(m.default.object(t.cookieJar)&&s){let e=s.map(async e=>t.cookieJar.setCookie(e,n.toString()));t.ignoreInvalidCookies&&(e=e.map(async e=>e.catch(()=>{})));try{await Promise.all(e)}catch(e){this._beforeError(e);return}}if(t.followRedirect&&e.headers.location&&me.has(r)){if(e.resume(),this[k]&&(this[te](),delete this[k],this[I]()),(r===303&&t.method!==`GET`&&t.method!==`HEAD`||!t.methodRewriting)&&(t.method=`GET`,`body`in t&&delete t.body,`json`in t&&delete t.json,`form`in t&&delete t.form,this[ae]=void 0,delete t.headers[`content-length`]),this.redirects.length>=t.maxRedirects){this._beforeError(new _e(this));return}try{let r=Buffer.from(e.headers.location,`binary`).toString(),a=new i.URL(r,n),s=a.toString();function c(e){return e.protocol===`unix:`||e.hostname===`unix`}if(!c(n)&&c(a)){this._beforeError(new ge(`Cannot redirect to UNIX socket`,{},this));return}a.hostname!==n.hostname||a.port!==n.port?(`host`in t.headers&&delete t.headers.host,`cookie`in t.headers&&delete t.headers.cookie,`authorization`in t.headers&&delete t.headers.authorization,(t.username||t.password)&&(t.username=``,t.password=``)):(a.username=t.username,a.password=t.password),this.redirects.push(s),t.url=a;for(let e of t.hooks.beforeRedirect)await e(t,o);this.emit(`redirect`,o,t),await this._makeRequest()}catch(e){this._beforeError(e);return}return}if(t.isStream&&t.throwHttpErrors&&!w.isResponseOk(o)){this._beforeError(new ve(o));return}e.on(`readable`,()=>{this[ie]&&this._read()}),this.on(`resume`,()=>{e.resume()}),this.on(`pause`,()=>{e.pause()}),e.once(`end`,()=>{this.push(null)}),this.emit(`response`,e);for(let n of this[F])if(!n.headersSent){for(let r in e.headers){let i=!t.decompress||r!==`content-encoding`,a=e.headers[r];i&&n.setHeader(r,a)}n.statusCode=r}}async _onResponse(e){try{await this._onResponseBase(e)}catch(e){this._beforeError(e)}}_onRequest(e){let{options:t}=this,{timeout:n,url:r}=t;c.default(e),this[te]=v.default(e,n,r);let i=t.cache?`cacheableResponse`:`response`;e.once(i,e=>{this._onResponse(e)}),e.once(`error`,t=>{var n;e.destroy(),(n=e.res)==null||n.removeAllListeners(`end`),t=t instanceof v.TimeoutError?new be(t,this.timings,this):new ge(t.message,t,this),this._beforeError(t)}),this[I]=_.default(e,this,Ce),this[k]=e,this.emit(`uploadProgress`,this.uploadProgress);let a=this[ae],o=this.redirects.length===0?this:e;m.default.nodeStream(a)?(a.pipe(o),a.once(`error`,e=>{this._beforeError(new ye(e,this))})):(this._unlockWrite(),m.default.undefined(a)?(this._cannotHaveBody||this._noPipe)&&(o.end(),this._lockWrite()):(this._writeRequest(a,void 0,()=>{}),o.end(),this._lockWrite())),this.emit(`request`,e)}async _createCacheableRequest(e,t){return new Promise((n,r)=>{Object.assign(t,y.default(e)),delete t.url;let i,a=fe.get(t.cache)(t,async e=>{e._readableState.autoDestroy=!1,i&&(await i).emit(`cacheableResponse`,e),n(e)});t.url=e,a.once(`error`,r),a.once(`request`,async e=>{i=e,n(i)})})}async _makeRequest(){let{options:e}=this,{headers:t}=e;for(let e in t)if(m.default.undefined(t[e]))delete t[e];else if(m.default.null_(t[e]))throw TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${e}\` header`);if(e.decompress&&m.default.undefined(t[`accept-encoding`])&&(t[`accept-encoding`]=le?`gzip, deflate, br`:`gzip, deflate`),e.cookieJar){let t=await e.cookieJar.getCookieString(e.url.toString());m.default.nonEmptyString(t)&&(e.headers.cookie=t)}for(let t of e.hooks.beforeRequest){let n=await t(e);if(!m.default.undefined(n)){e.request=()=>n;break}}e.body&&this[ae]!==e.body&&(this[ae]=e.body);let{agent:n,request:r,timeout:i,url:o}=e;if(e.dnsCache&&!(`lookup`in e)&&(e.lookup=e.dnsCache.lookup),o.hostname===`unix`){let t=/(?<socketPath>.+?):(?<path>.+)/.exec(`${o.pathname}${o.search}`);if(t?.groups){let{socketPath:n,path:r}=t.groups;Object.assign(e,{socketPath:n,path:r,host:``})}}let c=o.protocol===`https:`,l;l=e.http2?f.auto:c?s.request:a.request;let d=e.request??l,p=e.cache?this._createCacheableRequest:d;n&&!e.http2&&(e.agent=n[c?`https`:`http`]),e[k]=d,delete e.request,delete e.timeout;let h=e;if(h.shared=e.cacheOptions?.shared,h.cacheHeuristic=e.cacheOptions?.cacheHeuristic,h.immutableMinTimeToLive=e.cacheOptions?.immutableMinTimeToLive,h.ignoreCargoCult=e.cacheOptions?.ignoreCargoCult,e.dnsLookupIpVersion!==void 0)try{h.family=C.dnsLookupIpVersionToFamily(e.dnsLookupIpVersion)}catch{throw Error("Invalid `dnsLookupIpVersion` option value")}e.https&&(`rejectUnauthorized`in e.https&&(h.rejectUnauthorized=e.https.rejectUnauthorized),e.https.checkServerIdentity&&(h.checkServerIdentity=e.https.checkServerIdentity),e.https.certificateAuthority&&(h.ca=e.https.certificateAuthority),e.https.certificate&&(h.cert=e.https.certificate),e.https.key&&(h.key=e.https.key),e.https.passphrase&&(h.passphrase=e.https.passphrase),e.https.pfx&&(h.pfx=e.https.pfx));try{let t=await p(o,h);m.default.undefined(t)&&(t=l(o,h)),e.request=r,e.timeout=i,e.agent=n,e.https&&(`rejectUnauthorized`in e.https&&delete h.rejectUnauthorized,e.https.checkServerIdentity&&delete h.checkServerIdentity,e.https.certificateAuthority&&delete h.ca,e.https.certificate&&delete h.cert,e.https.key&&delete h.key,e.https.passphrase&&delete h.passphrase,e.https.pfx&&delete h.pfx),de(t)?this._onRequest(t):this.writable?(this.once(`finish`,()=>{this._onResponse(t)}),this._unlockWrite(),this.end(),this._lockWrite()):this._onResponse(t)}catch(e){throw e instanceof u.CacheError?new L(e,this):new ge(e.message,e,this)}}async _error(e){try{for(let t of this.options.hooks.beforeError)e=await t(e)}catch(t){e=new ge(t.message,t,this)}this.destroy(e)}_beforeError(e){if(this[re])return;let{options:t}=this,n=this.retryCount+1;this[re]=!0,e instanceof ge||(e=new ge(e.message,e,this));let r=e,{response:i}=r;(async()=>{if(i&&!i.body){i.setEncoding(this._readableState.encoding);try{i.rawBody=await S.default(i),i.body=i.rawBody.toString()}catch{}}if(this.listenerCount(`retry`)!==0){let a;try{let e;i&&`retry-after`in i.headers&&(e=Number(i.headers[`retry-after`]),Number.isNaN(e)?(e=Date.parse(i.headers[`retry-after`])-Date.now(),e<=0&&(e=1)):e*=1e3),a=await t.retry.calculateDelay({attemptCount:n,retryOptions:t.retry,error:r,retryAfter:e,computedValue:D.default({attemptCount:n,retryOptions:t.retry,error:r,retryAfter:e,computedValue:0})})}catch(e){this._error(new ge(e.message,e,this));return}if(a){let t=async()=>{try{for(let e of this.options.hooks.beforeRetry)await e(this.options,r,n)}catch(t){this._error(new ge(t.message,e,this));return}this.destroyed||(this.destroy(),this.emit(`retry`,n,e))};this[ce]=setTimeout(t,a);return}}this._error(r)})()}_read(){this[ie]=!0;let e=this[A];if(e&&!this[re]){e.readableLength&&(this[ie]=!1);let t;for(;(t=e.read())!==null;){this[M]+=t.length,this[ne]=!0;let e=this.downloadProgress;e.percent<1&&this.emit(`downloadProgress`,e),this.push(t)}}}_write(e,t,n){let r=()=>{this._writeRequest(e,t,n)};this.requestInitialized?r():this[oe].push(r)}_writeRequest(e,t,n){this[k].destroyed||(this._progressCallbacks.push(()=>{this[P]+=Buffer.byteLength(e,t);let n=this.uploadProgress;n.percent<1&&this.emit(`uploadProgress`,n)}),this[k].write(e,t,e=>{!e&&this._progressCallbacks.length>0&&this._progressCallbacks.shift()(),n(e)}))}_final(e){let t=()=>{for(;this._progressCallbacks.length!==0;)this._progressCallbacks.shift()();if(!(k in this)){e();return}if(this[k].destroyed){e();return}this[k].end(t=>{t||(this[N]=this[P],this.emit(`uploadProgress`,this.uploadProgress),this[k].emit(`upload-complete`)),e(t)})};this.requestInitialized?t():this[oe].push(t)}_destroy(e,t){this[re]=!0,clearTimeout(this[ce]),k in this&&(this[te](),this[A]?.complete||this[k].destroy()),e!==null&&!m.default.undefined(e)&&!(e instanceof ge)&&(e=new ge(e.message,e,this)),t(e)}get _isAboutToError(){return this[re]}get ip(){return this.socket?.remoteAddress}get aborted(){return(this[k]?.destroyed??this.destroyed)&&!this[se]?.complete}get socket(){return this[k]?.socket??void 0}get downloadProgress(){let e;return e=this[j]?this[M]/this[j]:+(this[j]===this[M]),{percent:e,transferred:this[M],total:this[j]}}get uploadProgress(){let e;return e=this[N]?this[P]/this[N]:+(this[N]===this[P]),{percent:e,transferred:this[P],total:this[N]}}get timings(){return this[k]?.timings}get isFromCache(){return this[ee]}pipe(e,t){if(this[ne])throw Error(`Failed to pipe. The response has been emitted already.`);return e instanceof o.ServerResponse&&this[F].add(e),super.pipe(e,t)}unpipe(e){return e instanceof o.ServerResponse&&this[F].delete(e),super.unpipe(e),this}};e.default=we})),Vv=L((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.CancelError=e.ParseError=void 0;var r=Bv();e.ParseError=class extends r.RequestError{constructor(e,t){let{options:n}=t.request;super(`${e.message} in "${n.url.toString()}"`,e,t.request),this.name=`ParseError`,this.code=this.code===`ERR_GOT_REQUEST_ERROR`?`ERR_BODY_PARSE_FAILURE`:this.code}},e.CancelError=class extends r.RequestError{constructor(e){super(`Promise was canceled`,{},e),this.name=`CancelError`,this.code=`ERR_CANCELED`}get isCanceled(){return!0}},n(Bv(),e)})),Hv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Vv();e.default=(e,n,r,i)=>{let{rawBody:a}=e;try{if(n===`text`)return a.toString(i);if(n===`json`)return a.length===0?``:r(a.toString());if(n===`buffer`)return a;throw new t.ParseError({message:`Unknown body type '${n}'`,name:`Error`},e)}catch(n){throw new t.ParseError(n,e)}}})),Uv=L((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0});var r=R(`events`),i=K_(),a=q_(),o=Vv(),s=Hv(),c=Bv(),l=Ov(),u=Pv(),d=Iv(),f=[`request`,`response`,`redirect`,`uploadProgress`,`downloadProgress`];function p(e){let t,n,m=new r.EventEmitter,h=new a((r,a,g)=>{let _=v=>{let y=new c.default(void 0,e);y.retryCount=v,y._noPipe=!0,g(()=>y.destroy()),g.shouldReject=!1,g(()=>a(new o.CancelError(y))),t=y,y.once(`response`,async e=>{if(e.retryCount=v,e.request.aborted)return;let t;try{t=await u.default(y),e.rawBody=t}catch{return}if(y._isAboutToError)return;let i=(e.headers[`content-encoding`]??``).toLowerCase(),a=[`gzip`,`deflate`,`br`].includes(i),{options:l}=y;if(a&&!l.decompress)e.body=t;else try{e.body=s.default(e,l.responseType,l.parseJson,l.encoding)}catch(n){if(e.body=t.toString(),d.isResponseOk(e)){y._beforeError(n);return}}try{for(let[t,n]of l.hooks.afterResponse.entries())e=await n(e,async e=>{let n=c.default.normalizeArguments(void 0,{...e,retry:{calculateDelay:()=>0},throwHttpErrors:!1,resolveBodyOnly:!1},l);n.hooks.afterResponse=n.hooks.afterResponse.slice(0,t);for(let e of n.hooks.beforeRetry)await e(n);let r=p(n);return g(()=>{r.catch(()=>{}),r.cancel()}),r})}catch(e){y._beforeError(new o.RequestError(e.message,e,y));return}if(n=e,!d.isResponseOk(e)){y._beforeError(new o.HTTPError(e));return}y.destroy(),r(y.options.resolveBodyOnly?e.body:e)});let b=e=>{if(h.isCanceled)return;let{options:t}=y;if(e instanceof o.HTTPError&&!t.throwHttpErrors){let{response:t}=e;r(y.options.resolveBodyOnly?t.body:t);return}a(e)};y.once(`error`,b);let x=y.options.body;y.once(`retry`,(e,t)=>{if(x===t.request?.options.body&&i.default.nodeStream(t.request?.options.body)){b(t);return}_(e)}),l.default(y,m,f)};_(0)});h.on=(e,t)=>(m.on(e,t),h);let g=e=>{let t=(async()=>{await h;let{options:t}=n.request;return s.default(n,e,t.parseJson,t.encoding)})();return Object.defineProperties(t,Object.getOwnPropertyDescriptors(h)),t};return h.json=()=>{let{headers:e}=t.options;return!t.writableFinished&&e.accept===void 0&&(e.accept=`application/json`),g(`json`)},h.buffer=()=>g(`buffer`),h.text=()=>g(`text`),h}e.default=p,n(Vv(),e)})),Wv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Vv();function n(e,...n){let r=(async()=>{if(e instanceof t.RequestError)try{for(let t of n)if(t)for(let n of t)e=await n(e)}catch(t){e=t}throw e})(),i=()=>r;return r.json=i,r.text=i,r.buffer=i,r.on=i,r}e.default=n})),Gv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=K_();function n(e){for(let r of Object.values(e))(t.default.plainObject(r)||t.default.array(r))&&n(r);return Object.freeze(e)}e.default=n})),Kv=L((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),qv=L((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.defaultHandler=void 0;var r=K_(),i=Uv(),a=Wv(),o=Bv(),s=Gv(),c={RequestError:i.RequestError,CacheError:i.CacheError,ReadError:i.ReadError,HTTPError:i.HTTPError,MaxRedirectsError:i.MaxRedirectsError,TimeoutError:i.TimeoutError,ParseError:i.ParseError,CancelError:i.CancelError,UnsupportedProtocolError:i.UnsupportedProtocolError,UploadError:i.UploadError},l=async e=>new Promise(t=>{setTimeout(t,e)}),{normalizeArguments:u}=o.default,d=(...e)=>{let t;for(let n of e)t=u(void 0,n,t);return t},f=e=>e.isStream?new o.default(void 0,e):i.default(e),p=e=>`defaults`in e&&`options`in e.defaults,m=[`get`,`post`,`put`,`patch`,`head`,`delete`];e.defaultHandler=(e,t)=>t(e);var h=(e,t)=>{if(e)for(let n of e)n(t)},g=t=>{t._rawHandlers=t.handlers,t.handlers=t.handlers.map(e=>((t,n)=>{let r,i=e(t,e=>(r=n(e),r));if(i!==r&&!t.isStream&&r){let e=i,{then:t,catch:n,finally:a}=e;Object.setPrototypeOf(e,Object.getPrototypeOf(r)),Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)),e.then=t,e.catch=n,e.finally=a}return i}));let n=((e,n={},s)=>{let c=0,l=e=>t.handlers[c++](e,c===t.handlers.length?f:l);if(r.default.plainObject(e)){let t={...e,...n};o.setNonEnumerableProperties([e,n],t),n=t,e=void 0}try{let r;try{h(t.options.hooks.init,n),h(n.hooks?.init,n)}catch(e){r=e}let a=u(e,n,s??t.options);if(a[o.kIsNormalizedAlready]=!0,r)throw new i.RequestError(r.message,r,a);return l(a)}catch(e){if(n.isStream)throw e;return a.default(e,t.options.hooks.beforeError,n.hooks?.beforeError)}});n.extend=(...n)=>{let r=[t.options],i=[...t._rawHandlers],a;for(let e of n)p(e)?(r.push(e.defaults.options),i.push(...e.defaults._rawHandlers),a=e.defaults.mutableDefaults):(r.push(e),`handlers`in e&&i.push(...e.handlers),a=e.mutableDefaults);return i=i.filter(t=>t!==e.defaultHandler),i.length===0&&i.push(e.defaultHandler),g({options:d(...r),handlers:i,mutableDefaults:!!a})};let _=(async function*(e,i){let a=u(e,i,t.options);a.resolveBodyOnly=!1;let o=a.pagination;if(!r.default.object(o))throw TypeError("`options.pagination` must be implemented");let s=[],{countLimit:c}=o,d=0;for(;d<o.requestLimit;){d!==0&&await l(o.backoff);let e=await n(void 0,void 0,a),t=await o.transform(e),r=[];for(let e of t)if(o.filter(e,s,r)&&(!o.shouldContinue(e,s,r)||(yield e,o.stackAllItems&&s.push(e),r.push(e),--c<=0)))return;let i=o.paginate(e,s,r);if(i===!1)return;i===e.request.options?a=e.request.options:i!==void 0&&(a=u(void 0,i,a)),d++}});n.paginate=_,n.paginate.all=(async(e,t)=>{let n=[];for await(let r of _(e,t))n.push(r);return n}),n.paginate.each=_,n.stream=((e,t)=>n(e,{...t,isStream:!0}));for(let e of m)n[e]=((t,r)=>n(t,{...r,method:e})),n.stream[e]=((t,r)=>n(t,{...r,method:e,isStream:!0}));return Object.assign(n,c),Object.defineProperty(n,"defaults",{value:t.mutableDefaults?t:s.default(t),writable:t.mutableDefaults,configurable:t.mutableDefaults,enumerable:!0}),n.mergeOptions=d,n};e.default=g,n(Kv(),e)})),Jv=L(((e,t)=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)};Object.defineProperty(e,"__esModule",{value:!0});var i=R(`url`),a=qv(),o={options:{method:`GET`,retry:{limit:2,methods:[`GET`,`PUT`,`HEAD`,`DELETE`,`OPTIONS`,`TRACE`],statusCodes:[408,413,429,500,502,503,504,521,522,524],errorCodes:[`ETIMEDOUT`,`ECONNRESET`,`EADDRINUSE`,`ECONNREFUSED`,`EPIPE`,`ENOTFOUND`,`ENETUNREACH`,`EAI_AGAIN`],maxRetryAfter:void 0,calculateDelay:({computedValue:e})=>e},timeout:{},headers:{"user-agent":`got (https://github.com/sindresorhus/got)`},hooks:{init:[],beforeRequest:[],beforeRedirect:[],beforeRetry:[],beforeError:[],afterResponse:[]},cache:void 0,dnsCache:void 0,decompress:!0,throwHttpErrors:!0,followRedirect:!0,isStream:!1,responseType:`text`,resolveBodyOnly:!1,maxRedirects:10,prefixUrl:``,methodRewriting:!0,ignoreInvalidCookies:!1,context:{},http2:!1,allowGetBody:!1,https:void 0,pagination:{transform:e=>e.request.options.responseType===`json`?e.body:JSON.parse(e.body),paginate:e=>{if(!Reflect.has(e.headers,`link`))return!1;let t=e.headers.link.split(`,`),n;for(let e of t){let t=e.split(`;`);if(t[1].includes(`next`)){n=t[0].trimStart().trim(),n=n.slice(1,-1);break}}return n?{url:new i.URL(n)}:!1},filter:()=>!0,shouldContinue:()=>!0,countLimit:1/0,backoff:0,requestLimit:1e4,stackAllItems:!0},parseJson:e=>JSON.parse(e),stringifyJson:e=>JSON.stringify(e),cacheOptions:{}},handlers:[a.defaultHandler],mutableDefaults:!1},s=a.default(o);e.default=s,t.exports=s,t.exports.default=s,t.exports.__esModule=!0,r(qv(),e),r(Uv(),e)})),Yv=L(((e,t)=>{var n=new Map([[`C`,`cwd`],[`f`,`file`],[`z`,`gzip`],[`P`,`preservePaths`],[`U`,`unlink`],[`strip-components`,`strip`],[`stripComponents`,`strip`],[`keep-newer`,`newer`],[`keepNewer`,`newer`],[`keep-newer-files`,`newer`],[`keepNewerFiles`,`newer`],[`k`,`keep`],[`keep-existing`,`keep`],[`keepExisting`,`keep`],[`m`,`noMtime`],[`no-mtime`,`noMtime`],[`p`,`preserveOwner`],[`L`,`follow`],[`h`,`follow`]]);t.exports=e=>e?Object.keys(e).map(t=>[n.has(t)?n.get(t):t,e[t]]).reduce((e,t)=>(e[t[0]]=t[1],e),Object.create(null)):{}})),Xv=L((e=>{var t=typeof process==`object`&&process?process:{stdout:null,stderr:null},n=R(`events`),r=R(`stream`),i=R(`string_decoder`).StringDecoder,a=Symbol(`EOF`),o=Symbol(`maybeEmitEnd`),s=Symbol(`emittedEnd`),c=Symbol(`emittingEnd`),l=Symbol(`emittedError`),u=Symbol(`closed`),d=Symbol(`read`),f=Symbol(`flush`),p=Symbol(`flushChunk`),m=Symbol(`encoding`),h=Symbol(`decoder`),g=Symbol(`flowing`),_=Symbol(`paused`),v=Symbol(`resume`),y=Symbol(`buffer`),b=Symbol(`pipes`),x=Symbol(`bufferLength`),S=Symbol(`bufferPush`),C=Symbol(`bufferShift`),w=Symbol(`objectMode`),T=Symbol(`destroyed`),E=Symbol(`error`),D=Symbol(`emitData`),O=Symbol(`emitEnd`),k=Symbol(`emitEnd2`),A=Symbol(`async`),j=Symbol(`abort`),M=Symbol(`aborted`),N=Symbol(`signal`),P=e=>Promise.resolve().then(e),F=global._MP_NO_ITERATOR_SYMBOLS_!==`1`,I=F&&Symbol.asyncIterator||Symbol(`asyncIterator not implemented`),ee=F&&Symbol.iterator||Symbol(`iterator not implemented`),te=e=>e===`end`||e===`finish`||e===`prefinish`,ne=e=>e instanceof ArrayBuffer||typeof e==`object`&&e.constructor&&e.constructor.name===`ArrayBuffer`&&e.byteLength>=0,re=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),ie=class{constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[v](),t.on(`drain`,this.ondrain)}unpipe(){this.dest.removeListener(`drain`,this.ondrain)}proxyErrors(){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},ae=class extends ie{unpipe(){this.src.removeListener(`error`,this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=e=>t.emit(`error`,e),e.on(`error`,this.proxyErrors)}};e.Minipass=class e extends r{constructor(e){super(),this[g]=!1,this[_]=!1,this[b]=[],this[y]=[],this[w]=e&&e.objectMode||!1,this[m]=this[w]?null:e&&e.encoding||null,this[m]===`buffer`&&(this[m]=null),this[A]=e&&!!e.async||!1,this[h]=this[m]?new i(this[m]):null,this[a]=!1,this[s]=!1,this[c]=!1,this[u]=!1,this[l]=null,this.writable=!0,this.readable=!0,this[x]=0,this[T]=!1,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[y]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[b]}),this[N]=e&&e.signal,this[M]=!1,this[N]&&(this[N].addEventListener(`abort`,()=>this[j]()),this[N].aborted&&this[j]())}get bufferLength(){return this[x]}get encoding(){return this[m]}set encoding(e){if(this[w])throw Error(`cannot set encoding in objectMode`);if(this[m]&&e!==this[m]&&(this[h]&&this[h].lastNeed||this[x]))throw Error(`cannot change encoding`);this[m]!==e&&(this[h]=e?new i(e):null,this[y].length&&(this[y]=this[y].map(e=>this[h].write(e)))),this[m]=e}setEncoding(e){this.encoding=e}get objectMode(){return this[w]}set objectMode(e){this[w]=this[w]||!!e}get async(){return this[A]}set async(e){this[A]=this[A]||!!e}[j](){this[M]=!0,this.emit(`abort`,this[N].reason),this.destroy(this[N].reason)}get aborted(){return this[M]}set aborted(e){}write(e,t,n){if(this[M])return!1;if(this[a])throw Error(`write after end`);if(this[T])return this.emit(`error`,Object.assign(Error(`Cannot call write after a stream was destroyed`),{code:`ERR_STREAM_DESTROYED`})),!0;typeof t==`function`&&(n=t,t=`utf8`),t||=`utf8`;let r=this[A]?P:e=>e();return!this[w]&&!Buffer.isBuffer(e)&&(re(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):ne(e)?e=Buffer.from(e):typeof e!=`string`&&(this.objectMode=!0)),this[w]?(this.flowing&&this[x]!==0&&this[f](!0),this.flowing?this.emit(`data`,e):this[S](e),this[x]!==0&&this.emit(`readable`),n&&r(n),this.flowing):e.length?(typeof e==`string`&&(t!==this[m]||this[h].lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[m]&&(e=this[h].write(e)),this.flowing&&this[x]!==0&&this[f](!0),this.flowing?this.emit(`data`,e):this[S](e),this[x]!==0&&this.emit(`readable`),n&&r(n),this.flowing):(this[x]!==0&&this.emit(`readable`),n&&r(n),this.flowing)}read(e){if(this[T])return null;if(this[x]===0||e===0||e>this[x])return this[o](),null;this[w]&&(e=null),this[y].length>1&&!this[w]&&(this[y]=this.encoding?[this[y].join(``)]:[Buffer.concat(this[y],this[x])]);let t=this[d](e||null,this[y][0]);return this[o](),t}[d](e,t){return e===t.length||e===null?this[C]():(this[y][0]=t.slice(e),t=t.slice(0,e),this[x]-=e),this.emit(`data`,t),!this[y].length&&!this[a]&&this.emit(`drain`),t}end(e,t,n){return typeof e==`function`&&(n=e,e=null),typeof t==`function`&&(n=t,t=`utf8`),e&&this.write(e,t),n&&this.once(`end`,n),this[a]=!0,this.writable=!1,(this.flowing||!this[_])&&this[o](),this}[v](){this[T]||(this[_]=!1,this[g]=!0,this.emit(`resume`),this[y].length?this[f]():this[a]?this[o]():this.emit(`drain`))}resume(){return this[v]()}pause(){this[g]=!1,this[_]=!0}get destroyed(){return this[T]}get flowing(){return this[g]}get paused(){return this[_]}[S](e){this[w]?this[x]+=1:this[x]+=e.length,this[y].push(e)}[C](){return this[w]?--this[x]:this[x]-=this[y][0].length,this[y].shift()}[f](e){do;while(this[p](this[C]())&&this[y].length);!e&&!this[y].length&&!this[a]&&this.emit(`drain`)}[p](e){return this.emit(`data`,e),this.flowing}pipe(e,n){if(this[T])return;let r=this[s];return n||={},e===t.stdout||e===t.stderr?n.end=!1:n.end=n.end!==!1,n.proxyErrors=!!n.proxyErrors,r?n.end&&e.end():(this[b].push(n.proxyErrors?new ae(this,e,n):new ie(this,e,n)),this[A]?P(()=>this[v]()):this[v]()),e}unpipe(e){let t=this[b].find(t=>t.dest===e);t&&(this[b].splice(this[b].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);return e===`data`&&!this[b].length&&!this.flowing?this[v]():e===`readable`&&this[x]!==0?super.emit(`readable`):te(e)&&this[s]?(super.emit(e),this.removeAllListeners(e)):e===`error`&&this[l]&&(this[A]?P(()=>t.call(this,this[l])):t.call(this,this[l])),n}get emittedEnd(){return this[s]}[o](){!this[c]&&!this[s]&&!this[T]&&this[y].length===0&&this[a]&&(this[c]=!0,this.emit(`end`),this.emit(`prefinish`),this.emit(`finish`),this[u]&&this.emit(`close`),this[c]=!1)}emit(e,t,...n){if(e!==`error`&&e!==`close`&&e!==T&&this[T])return;if(e===`data`)return!this[w]&&!t?!1:this[A]?P(()=>this[D](t)):this[D](t);if(e===`end`)return this[O]();if(e===`close`){if(this[u]=!0,!this[s]&&!this[T])return;let e=super.emit(`close`);return this.removeAllListeners(`close`),e}if(e===`error`){this[l]=t,super.emit(E,t);let e=!this[N]||this.listeners(`error`).length?super.emit(`error`,t):!1;return this[o](),e}if(e===`resume`){let e=super.emit(`resume`);return this[o](),e}if(e===`finish`||e===`prefinish`){let t=super.emit(e);return this.removeAllListeners(e),t}let r=super.emit(e,t,...n);return this[o](),r}[D](e){for(let t of this[b])t.dest.write(e)===!1&&this.pause();let t=super.emit(`data`,e);return this[o](),t}[O](){this[s]||(this[s]=!0,this.readable=!1,this[A]?P(()=>this[k]()):this[k]())}[k](){if(this[h]){let e=this[h].end();if(e){for(let t of this[b])t.dest.write(e);super.emit(`data`,e)}}for(let e of this[b])e.end();let e=super.emit(`end`);return this.removeAllListeners(`end`),e}collect(){let e=[];this[w]||(e.dataLength=0);let t=this.promise();return this.on(`data`,t=>{e.push(t),this[w]||(e.dataLength+=t.length)}),t.then(()=>e)}concat(){return this[w]?Promise.reject(Error(`cannot concat in objectMode`)):this.collect().then(e=>this[w]?Promise.reject(Error(`cannot concat in objectMode`)):this[m]?e.join(``):Buffer.concat(e,e.dataLength))}promise(){return new Promise((e,t)=>{this.on(T,()=>t(Error(`stream destroyed`))),this.on(`error`,e=>t(e)),this.on(`end`,()=>e())})}[I](){let e=!1,t=()=>(this.pause(),e=!0,Promise.resolve({done:!0}));return{next:()=>{if(e)return t();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[a])return t();let r=null,i=null,o=e=>{this.removeListener(`data`,s),this.removeListener(`end`,c),this.removeListener(T,l),t(),i(e)},s=e=>{this.removeListener(`error`,o),this.removeListener(`end`,c),this.removeListener(T,l),this.pause(),r({value:e,done:!!this[a]})},c=()=>{this.removeListener(`error`,o),this.removeListener(`data`,s),this.removeListener(T,l),t(),r({done:!0})},l=()=>o(Error(`stream destroyed`));return new Promise((e,t)=>{i=t,r=e,this.once(T,l),this.once(`error`,o),this.once(`end`,c),this.once(`data`,s)})},throw:t,return:t,[I](){return this}}}[ee](){let e=!1,t=()=>(this.pause(),this.removeListener(E,t),this.removeListener(T,t),this.removeListener(`end`,t),e=!0,{done:!0});return this.once(`end`,t),this.once(E,t),this.once(T,t),{next:()=>{if(e)return t();let n=this.read();return n===null?t():{value:n}},throw:t,return:t,[ee](){return this}}}destroy(e){return this[T]?(e?this.emit(`error`,e):this.emit(T),this):(this[T]=!0,this[y].length=0,this[x]=0,typeof this.close==`function`&&!this[u]&&this.close(),e?this.emit(`error`,e):this.emit(T),this)}static isStream(t){return!!t&&(t instanceof e||t instanceof r||t instanceof n&&(typeof t.pipe==`function`||typeof t.write==`function`&&typeof t.end==`function`))}}})),Zv=L(((e,t)=>{var n=R(`zlib`).constants||{ZLIB_VERNUM:4736};t.exports=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},n))})),Qv=L(((e,t)=>{var n=typeof process==`object`&&process?process:{stdout:null,stderr:null},r=R(`events`),i=R(`stream`),a=R(`string_decoder`).StringDecoder,o=Symbol(`EOF`),s=Symbol(`maybeEmitEnd`),c=Symbol(`emittedEnd`),l=Symbol(`emittingEnd`),u=Symbol(`emittedError`),d=Symbol(`closed`),f=Symbol(`read`),p=Symbol(`flush`),m=Symbol(`flushChunk`),h=Symbol(`encoding`),g=Symbol(`decoder`),_=Symbol(`flowing`),v=Symbol(`paused`),y=Symbol(`resume`),b=Symbol(`bufferLength`),x=Symbol(`bufferPush`),S=Symbol(`bufferShift`),C=Symbol(`objectMode`),w=Symbol(`destroyed`),T=Symbol(`emitData`),E=Symbol(`emitEnd`),D=Symbol(`emitEnd2`),O=Symbol(`async`),k=e=>Promise.resolve().then(e),A=global._MP_NO_ITERATOR_SYMBOLS_!==`1`,j=A&&Symbol.asyncIterator||Symbol(`asyncIterator not implemented`),M=A&&Symbol.iterator||Symbol(`iterator not implemented`),N=e=>e===`end`||e===`finish`||e===`prefinish`,P=e=>e instanceof ArrayBuffer||typeof e==`object`&&e.constructor&&e.constructor.name===`ArrayBuffer`&&e.byteLength>=0,F=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),I=class{constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[y](),t.on(`drain`,this.ondrain)}unpipe(){this.dest.removeListener(`drain`,this.ondrain)}proxyErrors(){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},ee=class extends I{unpipe(){this.src.removeListener(`error`,this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=e=>t.emit(`error`,e),e.on(`error`,this.proxyErrors)}};t.exports=class e extends i{constructor(e){super(),this[_]=!1,this[v]=!1,this.pipes=[],this.buffer=[],this[C]=e&&e.objectMode||!1,this[h]=this[C]?null:e&&e.encoding||null,this[h]===`buffer`&&(this[h]=null),this[O]=e&&!!e.async||!1,this[g]=this[h]?new a(this[h]):null,this[o]=!1,this[c]=!1,this[l]=!1,this[d]=!1,this[u]=null,this.writable=!0,this.readable=!0,this[b]=0,this[w]=!1}get bufferLength(){return this[b]}get encoding(){return this[h]}set encoding(e){if(this[C])throw Error(`cannot set encoding in objectMode`);if(this[h]&&e!==this[h]&&(this[g]&&this[g].lastNeed||this[b]))throw Error(`cannot change encoding`);this[h]!==e&&(this[g]=e?new a(e):null,this.buffer.length&&(this.buffer=this.buffer.map(e=>this[g].write(e)))),this[h]=e}setEncoding(e){this.encoding=e}get objectMode(){return this[C]}set objectMode(e){this[C]=this[C]||!!e}get async(){return this[O]}set async(e){this[O]=this[O]||!!e}write(e,t,n){if(this[o])throw Error(`write after end`);if(this[w])return this.emit(`error`,Object.assign(Error(`Cannot call write after a stream was destroyed`),{code:`ERR_STREAM_DESTROYED`})),!0;typeof t==`function`&&(n=t,t=`utf8`),t||=`utf8`;let r=this[O]?k:e=>e();return!this[C]&&!Buffer.isBuffer(e)&&(F(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):P(e)?e=Buffer.from(e):typeof e!=`string`&&(this.objectMode=!0)),this[C]?(this.flowing&&this[b]!==0&&this[p](!0),this.flowing?this.emit(`data`,e):this[x](e),this[b]!==0&&this.emit(`readable`),n&&r(n),this.flowing):e.length?(typeof e==`string`&&(t!==this[h]||this[g].lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[h]&&(e=this[g].write(e)),this.flowing&&this[b]!==0&&this[p](!0),this.flowing?this.emit(`data`,e):this[x](e),this[b]!==0&&this.emit(`readable`),n&&r(n),this.flowing):(this[b]!==0&&this.emit(`readable`),n&&r(n),this.flowing)}read(e){if(this[w])return null;if(this[b]===0||e===0||e>this[b])return this[s](),null;this[C]&&(e=null),this.buffer.length>1&&!this[C]&&(this.buffer=this.encoding?[this.buffer.join(``)]:[Buffer.concat(this.buffer,this[b])]);let t=this[f](e||null,this.buffer[0]);return this[s](),t}[f](e,t){return e===t.length||e===null?this[S]():(this.buffer[0]=t.slice(e),t=t.slice(0,e),this[b]-=e),this.emit(`data`,t),!this.buffer.length&&!this[o]&&this.emit(`drain`),t}end(e,t,n){return typeof e==`function`&&(n=e,e=null),typeof t==`function`&&(n=t,t=`utf8`),e&&this.write(e,t),n&&this.once(`end`,n),this[o]=!0,this.writable=!1,(this.flowing||!this[v])&&this[s](),this}[y](){this[w]||(this[v]=!1,this[_]=!0,this.emit(`resume`),this.buffer.length?this[p]():this[o]?this[s]():this.emit(`drain`))}resume(){return this[y]()}pause(){this[_]=!1,this[v]=!0}get destroyed(){return this[w]}get flowing(){return this[_]}get paused(){return this[v]}[x](e){this[C]?this[b]+=1:this[b]+=e.length,this.buffer.push(e)}[S](){return this.buffer.length&&(this[C]?--this[b]:this[b]-=this.buffer[0].length),this.buffer.shift()}[p](e){do;while(this[m](this[S]()));!e&&!this.buffer.length&&!this[o]&&this.emit(`drain`)}[m](e){return e?(this.emit(`data`,e),this.flowing):!1}pipe(e,t){if(this[w])return;let r=this[c];return t||={},e===n.stdout||e===n.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this.pipes.push(t.proxyErrors?new ee(this,e,t):new I(this,e,t)),this[O]?k(()=>this[y]()):this[y]()),e}unpipe(e){let t=this.pipes.find(t=>t.dest===e);t&&(this.pipes.splice(this.pipes.indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);return e===`data`&&!this.pipes.length&&!this.flowing?this[y]():e===`readable`&&this[b]!==0?super.emit(`readable`):N(e)&&this[c]?(super.emit(e),this.removeAllListeners(e)):e===`error`&&this[u]&&(this[O]?k(()=>t.call(this,this[u])):t.call(this,this[u])),n}get emittedEnd(){return this[c]}[s](){!this[l]&&!this[c]&&!this[w]&&this.buffer.length===0&&this[o]&&(this[l]=!0,this.emit(`end`),this.emit(`prefinish`),this.emit(`finish`),this[d]&&this.emit(`close`),this[l]=!1)}emit(e,t,...n){if(e!==`error`&&e!==`close`&&e!==w&&this[w])return;if(e===`data`)return t?this[O]?k(()=>this[T](t)):this[T](t):!1;if(e===`end`)return this[E]();if(e===`close`){if(this[d]=!0,!this[c]&&!this[w])return;let e=super.emit(`close`);return this.removeAllListeners(`close`),e}if(e===`error`){this[u]=t;let e=super.emit(`error`,t);return this[s](),e}if(e===`resume`){let e=super.emit(`resume`);return this[s](),e}if(e===`finish`||e===`prefinish`){let t=super.emit(e);return this.removeAllListeners(e),t}let r=super.emit(e,t,...n);return this[s](),r}[T](e){for(let t of this.pipes)t.dest.write(e)===!1&&this.pause();let t=super.emit(`data`,e);return this[s](),t}[E](){this[c]||(this[c]=!0,this.readable=!1,this[O]?k(()=>this[D]()):this[D]())}[D](){if(this[g]){let e=this[g].end();if(e){for(let t of this.pipes)t.dest.write(e);super.emit(`data`,e)}}for(let e of this.pipes)e.end();let e=super.emit(`end`);return this.removeAllListeners(`end`),e}collect(){let e=[];this[C]||(e.dataLength=0);let t=this.promise();return this.on(`data`,t=>{e.push(t),this[C]||(e.dataLength+=t.length)}),t.then(()=>e)}concat(){return this[C]?Promise.reject(Error(`cannot concat in objectMode`)):this.collect().then(e=>this[C]?Promise.reject(Error(`cannot concat in objectMode`)):this[h]?e.join(``):Buffer.concat(e,e.dataLength))}promise(){return new Promise((e,t)=>{this.on(w,()=>t(Error(`stream destroyed`))),this.on(`error`,e=>t(e)),this.on(`end`,()=>e())})}[j](){return{next:()=>{let e=this.read();if(e!==null)return Promise.resolve({done:!1,value:e});if(this[o])return Promise.resolve({done:!0});let t=null,n=null,r=e=>{this.removeListener(`data`,i),this.removeListener(`end`,a),n(e)},i=e=>{this.removeListener(`error`,r),this.removeListener(`end`,a),this.pause(),t({value:e,done:!!this[o]})},a=()=>{this.removeListener(`error`,r),this.removeListener(`data`,i),t({done:!0})},s=()=>r(Error(`stream destroyed`));return new Promise((e,o)=>{n=o,t=e,this.once(w,s),this.once(`error`,r),this.once(`end`,a),this.once(`data`,i)})}}}[M](){return{next:()=>{let e=this.read();return{value:e,done:e===null}}}}destroy(e){return this[w]?(e?this.emit(`error`,e):this.emit(w),this):(this[w]=!0,this.buffer.length=0,this[b]=0,typeof this.close==`function`&&!this[d]&&this.close(),e?this.emit(`error`,e):this.emit(w),this)}static isStream(t){return!!t&&(t instanceof e||t instanceof i||t instanceof r&&(typeof t.pipe==`function`||typeof t.write==`function`&&typeof t.end==`function`))}}})),$v=L((e=>{var t=R(`assert`),n=R(`buffer`).Buffer,r=R(`zlib`),i=e.constants=Zv(),a=Qv(),o=n.concat,s=Symbol(`_superWrite`),c=class extends Error{constructor(e){super(`zlib: `+e.message),this.code=e.code,this.errno=e.errno,this.code||=`ZLIB_ERROR`,this.message=`zlib: `+e.message,Error.captureStackTrace(this,this.constructor)}get name(){return`ZlibError`}},l=Symbol(`opts`),u=Symbol(`flushFlag`),d=Symbol(`finishFlushFlag`),f=Symbol(`fullFlushFlag`),p=Symbol(`handle`),m=Symbol(`onError`),h=Symbol(`sawError`),g=Symbol(`level`),_=Symbol(`strategy`),v=Symbol(`ended`),y=class extends a{constructor(e,t){if(!e||typeof e!=`object`)throw TypeError(`invalid options for ZlibBase constructor`);super(e),this[h]=!1,this[v]=!1,this[l]=e,this[u]=e.flush,this[d]=e.finishFlush;try{this[p]=new r[t](e)}catch(e){throw new c(e)}this[m]=e=>{this[h]||(this[h]=!0,this.close(),this.emit(`error`,e))},this[p].on(`error`,e=>this[m](new c(e))),this.once(`end`,()=>this.close)}close(){this[p]&&(this[p].close(),this[p]=null,this.emit(`close`))}reset(){if(!this[h])return t(this[p],`zlib binding closed`),this[p].reset()}flush(e){this.ended||(typeof e!=`number`&&(e=this[f]),this.write(Object.assign(n.alloc(0),{[u]:e})))}end(e,t,n){return e&&this.write(e,t),this.flush(this[d]),this[v]=!0,super.end(null,null,n)}get ended(){return this[v]}write(e,r,i){if(typeof r==`function`&&(i=r,r=`utf8`),typeof e==`string`&&(e=n.from(e,r)),this[h])return;t(this[p],`zlib binding closed`);let a=this[p]._handle,l=a.close;a.close=()=>{};let d=this[p].close;this[p].close=()=>{},n.concat=e=>e;let f;try{let t=typeof e[u]==`number`?e[u]:this[u];f=this[p]._processChunk(e,t),n.concat=o}catch(e){n.concat=o,this[m](new c(e))}finally{this[p]&&(this[p]._handle=a,a.close=l,this[p].close=d,this[p].removeAllListeners(`error`))}this[p]&&this[p].on(`error`,e=>this[m](new c(e)));let g;if(f){if(Array.isArray(f)&&f.length>0){g=this[s](n.from(f[0]));for(let e=1;e<f.length;e++)g=this[s](f[e])}else g=this[s](n.from(f))}return i&&i(),g}[s](e){return super.write(e)}},b=class extends y{constructor(e,t){e||={},e.flush=e.flush||i.Z_NO_FLUSH,e.finishFlush=e.finishFlush||i.Z_FINISH,super(e,t),this[f]=i.Z_FULL_FLUSH,this[g]=e.level,this[_]=e.strategy}params(e,n){if(!this[h]){if(!this[p])throw Error(`cannot switch params when binding is closed`);if(!this[p].params)throw Error(`not supported in this implementation`);if(this[g]!==e||this[_]!==n){this.flush(i.Z_SYNC_FLUSH),t(this[p],`zlib binding closed`);let r=this[p].flush;this[p].flush=(e,t)=>{this.flush(e),t()};try{this[p].params(e,n)}finally{this[p].flush=r}this[p]&&(this[g]=e,this[_]=n)}}}},x=class extends b{constructor(e){super(e,`Deflate`)}},S=class extends b{constructor(e){super(e,`Inflate`)}},C=Symbol(`_portable`),w=class extends b{constructor(e){super(e,`Gzip`),this[C]=e&&!!e.portable}[s](e){return this[C]?(this[C]=!1,e[9]=255,super[s](e)):super[s](e)}},T=class extends b{constructor(e){super(e,`Gunzip`)}},E=class extends b{constructor(e){super(e,`DeflateRaw`)}},D=class extends b{constructor(e){super(e,`InflateRaw`)}},O=class extends b{constructor(e){super(e,`Unzip`)}},k=class extends y{constructor(e,t){e||={},e.flush=e.flush||i.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||i.BROTLI_OPERATION_FINISH,super(e,t),this[f]=i.BROTLI_OPERATION_FLUSH}},A=class extends k{constructor(e){super(e,`BrotliCompress`)}},j=class extends k{constructor(e){super(e,`BrotliDecompress`)}};e.Deflate=x,e.Inflate=S,e.Gzip=w,e.Gunzip=T,e.DeflateRaw=E,e.InflateRaw=D,e.Unzip=O,typeof r.BrotliCompress==`function`?(e.BrotliCompress=A,e.BrotliDecompress=j):e.BrotliCompress=e.BrotliDecompress=class{constructor(){throw Error(`Brotli is not supported in this version of Node.js`)}}})),ey=L(((e,t)=>{t.exports=(process.env.TESTING_TAR_FAKE_PLATFORM||process.platform)===`win32`?e=>e&&e.replace(/\\/g,`/`):e=>e})),ty=L(((e,t)=>{var{Minipass:n}=Xv(),r=ey(),i=Symbol(`slurp`);t.exports=class extends n{constructor(e,t,n){switch(super(),this.pause(),this.extended=t,this.globalExtended=n,this.header=e,this.startBlockSize=512*Math.ceil(e.size/512),this.blockRemain=this.startBlockSize,this.remain=e.size,this.type=e.type,this.meta=!1,this.ignore=!1,this.type){case`File`:case`OldFile`:case`Link`:case`SymbolicLink`:case`CharacterDevice`:case`BlockDevice`:case`Directory`:case`FIFO`:case`ContiguousFile`:case`GNUDumpDir`:break;case`NextFileHasLongLinkpath`:case`NextFileHasLongPath`:case`OldGnuLongPath`:case`GlobalExtendedHeader`:case`ExtendedHeader`:case`OldExtendedHeader`:this.meta=!0;break;default:this.ignore=!0}this.path=r(e.path),this.mode=e.mode,this.mode&&(this.mode&=4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=e.size,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=r(e.linkpath),this.uname=e.uname,this.gname=e.gname,t&&this[i](t),n&&this[i](n,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw Error(`writing more to entry than is appropriate`);let n=this.remain,r=this.blockRemain;return this.remain=Math.max(0,n-t),this.blockRemain=Math.max(0,r-t),this.ignore?!0:n>=t?super.write(e):super.write(e.slice(0,n))}[i](e,t){for(let n in e)e[n]!==null&&e[n]!==void 0&&!(t&&n===`path`)&&(this[n]=n===`path`||n===`linkpath`?r(e[n]):e[n])}}})),ny=L((e=>{e.name=new Map([[`0`,`File`],[``,`OldFile`],[`1`,`Link`],[`2`,`SymbolicLink`],[`3`,`CharacterDevice`],[`4`,`BlockDevice`],[`5`,`Directory`],[`6`,`FIFO`],[`7`,`ContiguousFile`],[`g`,`GlobalExtendedHeader`],[`x`,`ExtendedHeader`],[`A`,`SolarisACL`],[`D`,`GNUDumpDir`],[`I`,`Inode`],[`K`,`NextFileHasLongLinkpath`],[`L`,`NextFileHasLongPath`],[`M`,`ContinuationFile`],[`N`,`OldGnuLongPath`],[`S`,`SparseFile`],[`V`,`TapeVolumeHeader`],[`X`,`OldExtendedHeader`]]),e.code=new Map(Array.from(e.name).map(e=>[e[1],e[0]]))})),ry=L(((e,t)=>{var n=(e,t)=>{if(Number.isSafeInteger(e))e<0?i(e,t):r(e,t);else throw Error(`cannot encode number outside of javascript safe integer range`);return t},r=(e,t)=>{t[0]=128;for(var n=t.length;n>1;n--)t[n-1]=e&255,e=Math.floor(e/256)},i=(e,t)=>{t[0]=255;var n=!1;e*=-1;for(var r=t.length;r>1;r--){var i=e&255;e=Math.floor(e/256),n?t[r-1]=c(i):i===0?t[r-1]=0:(n=!0,t[r-1]=l(i))}},a=e=>{let t=e[0],n=t===128?s(e.slice(1,e.length)):t===255?o(e):null;if(n===null)throw Error(`invalid base256 encoding`);if(!Number.isSafeInteger(n))throw Error(`parsed number outside of javascript safe integer range`);return n},o=e=>{for(var t=e.length,n=0,r=!1,i=t-1;i>-1;i--){var a=e[i],o;r?o=c(a):a===0?o=a:(r=!0,o=l(a)),o!==0&&(n-=o*256**(t-i-1))}return n},s=e=>{for(var t=e.length,n=0,r=t-1;r>-1;r--){var i=e[r];i!==0&&(n+=i*256**(t-r-1))}return n},c=e=>(255^e)&255,l=e=>(255^e)+1&255;t.exports={encode:n,parse:a}})),iy=L(((e,t)=>{var n=ny(),r=R(`path`).posix,i=ry(),a=Symbol(`slurp`),o=Symbol(`type`),s=class{constructor(e,t,n,r){this.cksumValid=!1,this.needPax=!1,this.nullBlock=!1,this.block=null,this.path=null,this.mode=null,this.uid=null,this.gid=null,this.size=null,this.mtime=null,this.cksum=null,this[o]=`0`,this.linkpath=null,this.uname=null,this.gname=null,this.devmaj=0,this.devmin=0,this.atime=null,this.ctime=null,Buffer.isBuffer(e)?this.decode(e,t||0,n,r):e&&this.set(e)}decode(e,t,n,r){if(t||=0,!e||!(e.length>=t+512))throw Error(`need 512 bytes for header`);if(this.path=l(e,t,100),this.mode=f(e,t+100,8),this.uid=f(e,t+108,8),this.gid=f(e,t+116,8),this.size=f(e,t+124,12),this.mtime=u(e,t+136,12),this.cksum=f(e,t+148,12),this[a](n),this[a](r,!0),this[o]=l(e,t+156,1),this[o]===``&&(this[o]=`0`),this[o]===`0`&&this.path.slice(-1)===`/`&&(this[o]=`5`),this[o]===`5`&&(this.size=0),this.linkpath=l(e,t+157,100),e.slice(t+257,t+265).toString()===`ustar\x0000`){if(this.uname=l(e,t+265,32),this.gname=l(e,t+297,32),this.devmaj=f(e,t+329,8),this.devmin=f(e,t+337,8),e[t+475]!==0){let n=l(e,t+345,155);this.path=n+`/`+this.path}else{let n=l(e,t+345,130);n&&(this.path=n+`/`+this.path),this.atime=u(e,t+476,12),this.ctime=u(e,t+488,12)}}let i=256;for(let n=t;n<t+148;n++)i+=e[n];for(let n=t+156;n<t+512;n++)i+=e[n];this.cksumValid=i===this.cksum,this.cksum===null&&i===256&&(this.nullBlock=!0)}[a](e,t){for(let n in e)e[n]!==null&&e[n]!==void 0&&!(t&&n===`path`)&&(this[n]=e[n])}encode(e,t){if(e||(e=this.block=Buffer.alloc(512),t=0),t||=0,!(e.length>=t+512))throw Error(`need 512 bytes for header`);let n=this.ctime||this.atime?130:155,r=c(this.path||``,n),i=r[0],a=r[1];this.needPax=r[2],this.needPax=S(e,t,100,i)||this.needPax,this.needPax=g(e,t+100,8,this.mode)||this.needPax,this.needPax=g(e,t+108,8,this.uid)||this.needPax,this.needPax=g(e,t+116,8,this.gid)||this.needPax,this.needPax=g(e,t+124,12,this.size)||this.needPax,this.needPax=b(e,t+136,12,this.mtime)||this.needPax,e[t+156]=this[o].charCodeAt(0),this.needPax=S(e,t+157,100,this.linkpath)||this.needPax,e.write(`ustar\x0000`,t+257,8),this.needPax=S(e,t+265,32,this.uname)||this.needPax,this.needPax=S(e,t+297,32,this.gname)||this.needPax,this.needPax=g(e,t+329,8,this.devmaj)||this.needPax,this.needPax=g(e,t+337,8,this.devmin)||this.needPax,this.needPax=S(e,t+345,n,a)||this.needPax,e[t+475]===0?(this.needPax=S(e,t+345,130,a)||this.needPax,this.needPax=b(e,t+476,12,this.atime)||this.needPax,this.needPax=b(e,t+488,12,this.ctime)||this.needPax):this.needPax=S(e,t+345,155,a)||this.needPax;let s=256;for(let n=t;n<t+148;n++)s+=e[n];for(let n=t+156;n<t+512;n++)s+=e[n];return this.cksum=s,g(e,t+148,8,this.cksum),this.cksumValid=!0,this.needPax}set(e){for(let t in e)e[t]!==null&&e[t]!==void 0&&(this[t]=e[t])}get type(){return n.name.get(this[o])||this[o]}get typeKey(){return this[o]}set type(e){this[o]=n.code.has(e)?n.code.get(e):e}},c=(e,t)=>{let n=e,i=``,a,o=r.parse(e).root||`.`;if(Buffer.byteLength(n)<100)a=[n,i,!1];else{i=r.dirname(n),n=r.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=t?a=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=t?a=[n.slice(0,99),i,!0]:(n=r.join(r.basename(i),n),i=r.dirname(i));while(i!==o&&!a);a||=[e.slice(0,99),``,!0]}return a},l=(e,t,n)=>e.slice(t,t+n).toString(`utf8`).replace(/\0.*/,``),u=(e,t,n)=>d(f(e,t,n)),d=e=>e===null?null:new Date(e*1e3),f=(e,t,n)=>e[t]&128?i.parse(e.slice(t,t+n)):m(e,t,n),p=e=>isNaN(e)?null:e,m=(e,t,n)=>p(parseInt(e.slice(t,t+n).toString(`utf8`).replace(/\0.*$/,``).trim(),8)),h={12:8589934591,8:2097151},g=(e,t,n,r)=>r===null?!1:r>h[n]||r<0?(i.encode(r,e.slice(t,t+n)),!0):(_(e,t,n,r),!1),_=(e,t,n,r)=>e.write(v(r,n),t,n,`ascii`),v=(e,t)=>y(Math.floor(e).toString(8),t),y=(e,t)=>(e.length===t-1?e:Array(t-e.length-1).join(`0`)+e+` `)+`\0`,b=(e,t,n,r)=>r!==null&&g(e,t,n,r.getTime()/1e3),x=Array(156).join(`\0`),S=(e,t,n,r)=>r!==null&&(e.write(r+x,t,n,`utf8`),r.length!==Buffer.byteLength(r)||r.length>n);t.exports=s})),ay=L(((e,t)=>{var n=iy(),r=R(`path`),i=class{constructor(e,t){this.atime=e.atime||null,this.charset=e.charset||null,this.comment=e.comment||null,this.ctime=e.ctime||null,this.gid=e.gid||null,this.gname=e.gname||null,this.linkpath=e.linkpath||null,this.mtime=e.mtime||null,this.path=e.path||null,this.size=e.size||null,this.uid=e.uid||null,this.uname=e.uname||null,this.dev=e.dev||null,this.ino=e.ino||null,this.nlink=e.nlink||null,this.global=t||!1}encode(){let e=this.encodeBody();if(e===``)return null;let t=Buffer.byteLength(e),i=512*Math.ceil(1+t/512),a=Buffer.allocUnsafe(i);for(let e=0;e<512;e++)a[e]=0;new n({path:(`PaxHeader/`+r.basename(this.path)).slice(0,99),mode:this.mode||420,uid:this.uid||null,gid:this.gid||null,size:t,mtime:this.mtime||null,type:this.global?`GlobalExtendedHeader`:`ExtendedHeader`,linkpath:``,uname:this.uname||``,gname:this.gname||``,devmaj:0,devmin:0,atime:this.atime||null,ctime:this.ctime||null}).encode(a),a.write(e,512,t,`utf8`);for(let e=t+512;e<a.length;e++)a[e]=0;return a}encodeBody(){return this.encodeField(`path`)+this.encodeField(`ctime`)+this.encodeField(`atime`)+this.encodeField(`dev`)+this.encodeField(`ino`)+this.encodeField(`nlink`)+this.encodeField(`charset`)+this.encodeField(`comment`)+this.encodeField(`gid`)+this.encodeField(`gname`)+this.encodeField(`linkpath`)+this.encodeField(`mtime`)+this.encodeField(`size`)+this.encodeField(`uid`)+this.encodeField(`uname`)}encodeField(e){if(this[e]===null||this[e]===void 0)return``;let t=this[e]instanceof Date?this[e].getTime()/1e3:this[e],n=` `+(e===`dev`||e===`ino`||e===`nlink`?`SCHILY.`:``)+e+`=`+t+`
|
|
89
|
+
`)}`}}};e.RequestError=_e;var ve=class extends _e{constructor(e){super(`Redirected ${e.options.maxRedirects} times. Aborting.`,{},e),this.name=`MaxRedirectsError`,this.code=`ERR_TOO_MANY_REDIRECTS`}};e.MaxRedirectsError=ve;var ye=class extends _e{constructor(e){super(`Response code ${e.statusCode} (${e.statusMessage})`,{},e.request),this.name=`HTTPError`,this.code=`ERR_NON_2XX_3XX_RESPONSE`}};e.HTTPError=ye;var be=class extends _e{constructor(e,t){super(e.message,e,t),this.name=`CacheError`,this.code=this.code===`ERR_GOT_REQUEST_ERROR`?`ERR_CACHE_ACCESS`:this.code}};e.CacheError=be;var xe=class extends _e{constructor(e,t){super(e.message,e,t),this.name=`UploadError`,this.code=this.code===`ERR_GOT_REQUEST_ERROR`?`ERR_UPLOAD`:this.code}};e.UploadError=xe;var Se=class extends _e{constructor(e,t,n){super(e.message,e,n),this.name=`TimeoutError`,this.event=e.event,this.timings=t}};e.TimeoutError=Se;var I=class extends _e{constructor(e,t){super(e.message,e,t),this.name=`ReadError`,this.code=this.code===`ERR_GOT_REQUEST_ERROR`?`ERR_READING_RESPONSE_STREAM`:this.code}};e.ReadError=I;var Ce=class extends _e{constructor(e){super(`Unsupported protocol "${e.url.protocol}"`,{},e),this.name=`UnsupportedProtocolError`,this.code=`ERR_UNSUPPORTED_PROTOCOL`}};e.UnsupportedProtocolError=Ce;var we=[`socket`,`connect`,`continue`,`information`,`upgrade`,`timeout`],Te=class extends n.Duplex{constructor(t,n={},i){super({autoDestroy:!1,highWaterMark:0}),this[M]=0,this[P]=0,this.requestInitialized=!1,this[F]=new Set,this.redirects=[],this[ie]=!1,this[ae]=!1,this[se]=[],this.retryCount=0,this._progressCallbacks=[];let a=()=>this._unlockWrite(),s=()=>this._lockWrite();this.on(`pipe`,e=>{e.prependListener(`data`,a),e.on(`data`,s),e.prependListener(`end`,a),e.on(`end`,s)}),this.on(`unpipe`,e=>{e.off(`data`,a),e.off(`data`,s),e.off(`end`,a),e.off(`end`,s)}),this.on(`pipe`,e=>{e instanceof o.IncomingMessage&&(this.options.headers={...e.headers,...this.options.headers})});let{json:c,body:l,form:u}=n;if((c||l||u)&&this._lockWrite(),e.kIsNormalizedAlready in n)this.options=n;else try{this.options=this.constructor.normalizeArguments(t,n,i)}catch(e){m.default.nodeStream(n.body)&&n.body.destroy(),this.destroy(e);return}(async()=>{var e;try{this.options.body instanceof r.ReadStream&&await me(this.options.body);let{url:t}=this.options;if(!t)throw TypeError("Missing `url` property");if(this.requestUrl=t.toString(),decodeURI(this.requestUrl),await this._finalizeBody(),await this._makeRequest(),this.destroyed){(e=this[k])==null||e.destroy();return}for(let e of this[se])e();this[se].length=0,this.requestInitialized=!0}catch(e){if(e instanceof _e){this._beforeError(e);return}this.destroyed||this.destroy(e)}})()}static normalizeArguments(n,r,a){var o;let s=r;if(m.default.object(n)&&!m.default.urlInstance(n))r={...a,...n,...r};else{if(n&&r&&r.url!==void 0)throw TypeError("The `url` option is mutually exclusive with the `input` argument");r={...a,...r},n!==void 0&&(r.url=n),m.default.urlInstance(r.url)&&(r.url=new i.URL(r.url.toString()))}if(r.cache===!1&&(r.cache=void 0),r.dnsCache===!1&&(r.dnsCache=void 0),m.assert.any([m.default.string,m.default.undefined],r.method),m.assert.any([m.default.object,m.default.undefined],r.headers),m.assert.any([m.default.string,m.default.urlInstance,m.default.undefined],r.prefixUrl),m.assert.any([m.default.object,m.default.undefined],r.cookieJar),m.assert.any([m.default.object,m.default.string,m.default.undefined],r.searchParams),m.assert.any([m.default.object,m.default.string,m.default.undefined],r.cache),m.assert.any([m.default.object,m.default.number,m.default.undefined],r.timeout),m.assert.any([m.default.object,m.default.undefined],r.context),m.assert.any([m.default.object,m.default.undefined],r.hooks),m.assert.any([m.default.boolean,m.default.undefined],r.decompress),m.assert.any([m.default.boolean,m.default.undefined],r.ignoreInvalidCookies),m.assert.any([m.default.boolean,m.default.undefined],r.followRedirect),m.assert.any([m.default.number,m.default.undefined],r.maxRedirects),m.assert.any([m.default.boolean,m.default.undefined],r.throwHttpErrors),m.assert.any([m.default.boolean,m.default.undefined],r.http2),m.assert.any([m.default.boolean,m.default.undefined],r.allowGetBody),m.assert.any([m.default.string,m.default.undefined],r.localAddress),m.assert.any([C.isDnsLookupIpVersion,m.default.undefined],r.dnsLookupIpVersion),m.assert.any([m.default.object,m.default.undefined],r.https),m.assert.any([m.default.boolean,m.default.undefined],r.rejectUnauthorized),r.https&&(m.assert.any([m.default.boolean,m.default.undefined],r.https.rejectUnauthorized),m.assert.any([m.default.function_,m.default.undefined],r.https.checkServerIdentity),m.assert.any([m.default.string,m.default.object,m.default.array,m.default.undefined],r.https.certificateAuthority),m.assert.any([m.default.string,m.default.object,m.default.array,m.default.undefined],r.https.key),m.assert.any([m.default.string,m.default.object,m.default.array,m.default.undefined],r.https.certificate),m.assert.any([m.default.string,m.default.undefined],r.https.passphrase),m.assert.any([m.default.string,m.default.buffer,m.default.array,m.default.undefined],r.https.pfx)),m.assert.any([m.default.object,m.default.undefined],r.cacheOptions),m.default.string(r.method)?r.method=r.method.toUpperCase():r.method=`GET`,r.headers===a?.headers?r.headers={...r.headers}:r.headers=p({...a?.headers,...r.headers}),`slashes`in r)throw TypeError("The legacy `url.Url` has been deprecated. Use `URL` instead.");if(`auth`in r)throw TypeError("Parameter `auth` is deprecated. Use `username` / `password` instead.");if(`searchParams`in r&&r.searchParams&&r.searchParams!==a?.searchParams){let e;if(m.default.string(r.searchParams)||r.searchParams instanceof i.URLSearchParams)e=new i.URLSearchParams(r.searchParams);else{de(r.searchParams),e=new i.URLSearchParams;for(let t in r.searchParams){let n=r.searchParams[t];n===null?e.append(t,``):n!==void 0&&e.append(t,n)}}(o=a?.searchParams)==null||o.forEach((t,n)=>{e.has(n)||e.append(n,t)}),r.searchParams=e}if(r.username=r.username??``,r.password=r.password??``,m.default.undefined(r.prefixUrl)?r.prefixUrl=a?.prefixUrl??``:(r.prefixUrl=r.prefixUrl.toString(),r.prefixUrl!==``&&!r.prefixUrl.endsWith(`/`)&&(r.prefixUrl+=`/`)),m.default.string(r.url)){if(r.url.startsWith(`/`))throw Error("`input` must not start with a slash when using `prefixUrl`");r.url=b.default(r.prefixUrl+r.url,r)}else(m.default.undefined(r.url)&&r.prefixUrl!==``||r.protocol)&&(r.url=b.default(r.prefixUrl,r));if(r.url){`port`in r&&delete r.port;let{prefixUrl:e}=r;Object.defineProperty(r,"prefixUrl",{set:t=>{let n=r.url;if(!n.href.startsWith(t))throw Error(`Cannot change \`prefixUrl\` from ${e} to ${t}: ${n.href}`);r.url=new i.URL(t+n.href.slice(e.length)),e=t},get:()=>e});let{protocol:t}=r.url;if(t===`unix:`&&(t=`http:`,r.url=new i.URL(`http://unix${r.url.pathname}${r.url.search}`)),r.searchParams&&(r.url.search=r.searchParams.toString()),t!==`http:`&&t!==`https:`)throw new Ce(r);r.username===``?r.username=r.url.username:r.url.username=r.username,r.password===``?r.password=r.url.password:r.url.password=r.password}let{cookieJar:c}=r;if(c){let{setCookie:e,getCookieString:n}=c;m.assert.function_(e),m.assert.function_(n),e.length===4&&n.length===0&&(e=t.promisify(e.bind(r.cookieJar)),n=t.promisify(n.bind(r.cookieJar)),r.cookieJar={setCookie:e,getCookieString:n})}let{cache:d}=r;if(d&&(pe.has(d)||pe.set(d,new u(((e,t)=>{let n=e[k](e,t);return m.default.promise(n)&&(n.once=(e,t)=>{if(e===`error`)n.catch(t);else if(e===`abort`)(async()=>{try{(await n).once(`abort`,t)}catch{}})();else throw Error(`Unknown HTTP2 promise event: ${e}`);return n}),n}),d))),r.cacheOptions={...r.cacheOptions},r.dnsCache===!0)O||=new l.default,r.dnsCache=O;else if(!m.default.undefined(r.dnsCache)&&!r.dnsCache.lookup)throw TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${m.default(r.dnsCache)}`);m.default.number(r.timeout)?r.timeout={request:r.timeout}:a&&r.timeout!==a.timeout?r.timeout={...a.timeout,...r.timeout}:r.timeout={...r.timeout},r.context||(r.context={});let f=r.hooks===a?.hooks;r.hooks={...r.hooks};for(let t of e.knownHookEvents)if(t in r.hooks){if(m.default.array(r.hooks[t]))r.hooks[t]=[...r.hooks[t]];else throw TypeError(`Parameter \`${t}\` must be an Array, got ${m.default(r.hooks[t])}`)}else r.hooks[t]=[];if(a&&!f)for(let t of e.knownHookEvents)a.hooks[t].length>0&&(r.hooks[t]=[...a.hooks[t],...r.hooks[t]]);if(`family`in r&&T.default(`"options.family" was never documented, please use "options.dnsLookupIpVersion"`),a!=null&&a.https&&(r.https={...a.https,...r.https}),`rejectUnauthorized`in r&&T.default(`"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"`),`checkServerIdentity`in r&&T.default(`"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"`),`ca`in r&&T.default(`"options.ca" was never documented, please use "options.https.certificateAuthority"`),`key`in r&&T.default(`"options.key" was never documented, please use "options.https.key"`),`cert`in r&&T.default(`"options.cert" was never documented, please use "options.https.certificate"`),`passphrase`in r&&T.default(`"options.passphrase" was never documented, please use "options.https.passphrase"`),`pfx`in r&&T.default(`"options.pfx" was never documented, please use "options.https.pfx"`),`followRedirects`in r)throw TypeError("The `followRedirects` option does not exist. Use `followRedirect` instead.");if(r.agent){for(let e in r.agent)if(e!==`http`&&e!==`https`&&e!==`http2`)throw TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${e}\``)}return r.maxRedirects=r.maxRedirects??0,e.setNonEnumerableProperties([a,s],r),E.default(r,a)}_lockWrite(){let e=()=>{throw TypeError(`The payload has been already provided`)};this.write=e,this.end=e}_unlockWrite(){this.write=super.write,this.end=super.end}async _finalizeBody(){let{options:t}=this,{headers:r}=t,a=!m.default.undefined(t.form),o=!m.default.undefined(t.json),s=!m.default.undefined(t.body),c=a||o||s,l=e.withoutBody.has(t.method)&&!(t.method===`GET`&&t.allowGetBody);if(this._cannotHaveBody=l,c){if(l)throw TypeError(`The \`${t.method}\` method cannot be used with a body`);if([s,a,o].filter(e=>e).length>1)throw TypeError("The `body`, `json` and `form` options are mutually exclusive");if(s&&!(t.body instanceof n.Readable)&&!m.default.string(t.body)&&!m.default.buffer(t.body)&&!g.default(t.body))throw TypeError("The `body` option must be a stream.Readable, string or Buffer");if(a&&!m.default.object(t.form))throw TypeError("The `form` option must be an Object");{let e=!m.default.string(r[`content-type`]);s?(g.default(t.body)&&e&&(r[`content-type`]=`multipart/form-data; boundary=${t.body.getBoundary()}`),this[oe]=t.body):a?(e&&(r[`content-type`]=`application/x-www-form-urlencoded`),this[oe]=new i.URLSearchParams(t.form).toString()):(e&&(r[`content-type`]=`application/json`),this[oe]=t.stringifyJson(t.json));let n=await h.default(this[oe],t.headers);m.default.undefined(r[`content-length`])&&m.default.undefined(r[`transfer-encoding`])&&!l&&!m.default.undefined(n)&&(r[`content-length`]=String(n))}}else l?this._lockWrite():this._unlockWrite();this[N]=Number(r[`content-length`])||void 0}async _onResponseBase(e){let{options:t}=this,{url:n}=t;this[ce]=e,t.decompress&&(e=d(e));let r=e.statusCode,o=e;o.statusMessage=o.statusMessage?o.statusMessage:a.STATUS_CODES[r],o.url=t.url.toString(),o.requestUrl=this.requestUrl,o.redirectUrls=this.redirects,o.request=this,o.isFromCache=e.fromCache||!1,o.ip=this.ip,o.retryCount=this.retryCount,this[te]=o.isFromCache,this[j]=Number(e.headers[`content-length`])||void 0,this[A]=e,e.once(`end`,()=>{this[j]=this[M],this.emit(`downloadProgress`,this.downloadProgress)}),e.once(`error`,t=>{e.destroy(),this._beforeError(new I(t,this))}),e.once(`aborted`,()=>{this._beforeError(new I({name:`Error`,message:`The server aborted pending request`,code:`ECONNRESET`},this))}),this.emit(`downloadProgress`,this.downloadProgress);let s=e.headers[`set-cookie`];if(m.default.object(t.cookieJar)&&s){let e=s.map(async e=>t.cookieJar.setCookie(e,n.toString()));t.ignoreInvalidCookies&&(e=e.map(async e=>e.catch(()=>{})));try{await Promise.all(e)}catch(e){this._beforeError(e);return}}if(t.followRedirect&&e.headers.location&&he.has(r)){if(e.resume(),this[k]&&(this[ne](),delete this[k],this[ee]()),(r===303&&t.method!==`GET`&&t.method!==`HEAD`||!t.methodRewriting)&&(t.method=`GET`,`body`in t&&delete t.body,`json`in t&&delete t.json,`form`in t&&delete t.form,this[oe]=void 0,delete t.headers[`content-length`]),this.redirects.length>=t.maxRedirects){this._beforeError(new ve(this));return}try{let r=Buffer.from(e.headers.location,`binary`).toString(),a=new i.URL(r,n),s=a.toString();function c(e){return e.protocol===`unix:`||e.hostname===`unix`}if(!c(n)&&c(a)){this._beforeError(new _e(`Cannot redirect to UNIX socket`,{},this));return}a.hostname!==n.hostname||a.port!==n.port?(`host`in t.headers&&delete t.headers.host,`cookie`in t.headers&&delete t.headers.cookie,`authorization`in t.headers&&delete t.headers.authorization,(t.username||t.password)&&(t.username=``,t.password=``)):(a.username=t.username,a.password=t.password),this.redirects.push(s),t.url=a;for(let e of t.hooks.beforeRedirect)await e(t,o);this.emit(`redirect`,o,t),await this._makeRequest()}catch(e){this._beforeError(e);return}}else if(t.isStream&&t.throwHttpErrors&&!w.isResponseOk(o))this._beforeError(new ye(o));else{e.on(`readable`,()=>{this[ae]&&this._read()}),this.on(`resume`,()=>{e.resume()}),this.on(`pause`,()=>{e.pause()}),e.once(`end`,()=>{this.push(null)}),this.emit(`response`,e);for(let n of this[F])if(!n.headersSent){for(let r in e.headers){let i=!t.decompress||r!==`content-encoding`,a=e.headers[r];i&&n.setHeader(r,a)}n.statusCode=r}}}async _onResponse(e){try{await this._onResponseBase(e)}catch(e){this._beforeError(e)}}_onRequest(e){let{options:t}=this,{timeout:n,url:r}=t;c.default(e),this[ne]=v.default(e,n,r);let i=t.cache?`cacheableResponse`:`response`;e.once(i,e=>{this._onResponse(e)}),e.once(`error`,t=>{var n;e.destroy(),(n=e.res)==null||n.removeAllListeners(`end`),t=t instanceof v.TimeoutError?new Se(t,this.timings,this):new _e(t.message,t,this),this._beforeError(t)}),this[ee]=_.default(e,this,we),this[k]=e,this.emit(`uploadProgress`,this.uploadProgress);let a=this[oe],o=this.redirects.length===0?this:e;m.default.nodeStream(a)?(a.pipe(o),a.once(`error`,e=>{this._beforeError(new xe(e,this))})):(this._unlockWrite(),m.default.undefined(a)?(this._cannotHaveBody||this._noPipe)&&(o.end(),this._lockWrite()):(this._writeRequest(a,void 0,()=>{}),o.end(),this._lockWrite())),this.emit(`request`,e)}async _createCacheableRequest(e,t){return new Promise((n,r)=>{Object.assign(t,y.default(e)),delete t.url;let i,a=pe.get(t.cache)(t,async e=>{e._readableState.autoDestroy=!1,i&&(await i).emit(`cacheableResponse`,e),n(e)});t.url=e,a.once(`error`,r),a.once(`request`,async e=>{i=e,n(i)})})}async _makeRequest(){let{options:e}=this,{headers:t}=e;for(let e in t)if(m.default.undefined(t[e]))delete t[e];else if(m.default.null_(t[e]))throw TypeError(`Use \`undefined\` instead of \`null\` to delete the \`${e}\` header`);if(e.decompress&&m.default.undefined(t[`accept-encoding`])&&(t[`accept-encoding`]=ue?`gzip, deflate, br`:`gzip, deflate`),e.cookieJar){let t=await e.cookieJar.getCookieString(e.url.toString());m.default.nonEmptyString(t)&&(e.headers.cookie=t)}for(let t of e.hooks.beforeRequest){let n=await t(e);if(!m.default.undefined(n)){e.request=()=>n;break}}e.body&&this[oe]!==e.body&&(this[oe]=e.body);let{agent:n,request:r,timeout:i,url:o}=e;if(e.dnsCache&&!(`lookup`in e)&&(e.lookup=e.dnsCache.lookup),o.hostname===`unix`){let t=/(?<socketPath>.+?):(?<path>.+)/.exec(`${o.pathname}${o.search}`);if(t!=null&&t.groups){let{socketPath:n,path:r}=t.groups;Object.assign(e,{socketPath:n,path:r,host:``})}}let c=o.protocol===`https:`,l;l=e.http2?f.auto:c?s.request:a.request;let d=e.request??l,p=e.cache?this._createCacheableRequest:d;n&&!e.http2&&(e.agent=n[c?`https`:`http`]),e[k]=d,delete e.request,delete e.timeout;let h=e;if(h.shared=e.cacheOptions?.shared,h.cacheHeuristic=e.cacheOptions?.cacheHeuristic,h.immutableMinTimeToLive=e.cacheOptions?.immutableMinTimeToLive,h.ignoreCargoCult=e.cacheOptions?.ignoreCargoCult,e.dnsLookupIpVersion!==void 0)try{h.family=C.dnsLookupIpVersionToFamily(e.dnsLookupIpVersion)}catch{throw Error("Invalid `dnsLookupIpVersion` option value")}e.https&&(`rejectUnauthorized`in e.https&&(h.rejectUnauthorized=e.https.rejectUnauthorized),e.https.checkServerIdentity&&(h.checkServerIdentity=e.https.checkServerIdentity),e.https.certificateAuthority&&(h.ca=e.https.certificateAuthority),e.https.certificate&&(h.cert=e.https.certificate),e.https.key&&(h.key=e.https.key),e.https.passphrase&&(h.passphrase=e.https.passphrase),e.https.pfx&&(h.pfx=e.https.pfx));try{let t=await p(o,h);m.default.undefined(t)&&(t=l(o,h)),e.request=r,e.timeout=i,e.agent=n,e.https&&(`rejectUnauthorized`in e.https&&delete h.rejectUnauthorized,e.https.checkServerIdentity&&delete h.checkServerIdentity,e.https.certificateAuthority&&delete h.ca,e.https.certificate&&delete h.cert,e.https.key&&delete h.key,e.https.passphrase&&delete h.passphrase,e.https.pfx&&delete h.pfx),fe(t)?this._onRequest(t):this.writable?(this.once(`finish`,()=>{this._onResponse(t)}),this._unlockWrite(),this.end(),this._lockWrite()):this._onResponse(t)}catch(e){throw e instanceof u.CacheError?new be(e,this):new _e(e.message,e,this)}}async _error(e){try{for(let t of this.options.hooks.beforeError)e=await t(e)}catch(t){e=new _e(t.message,t,this)}this.destroy(e)}_beforeError(e){if(this[ie])return;let{options:t}=this,n=this.retryCount+1;this[ie]=!0,e instanceof _e||(e=new _e(e.message,e,this));let r=e,{response:i}=r;(async()=>{if(i&&!i.body){i.setEncoding(this._readableState.encoding);try{i.rawBody=await S.default(i),i.body=i.rawBody.toString()}catch{}}if(this.listenerCount(`retry`)!==0){let a;try{let e;i&&`retry-after`in i.headers&&(e=Number(i.headers[`retry-after`]),Number.isNaN(e)?(e=Date.parse(i.headers[`retry-after`])-Date.now(),e<=0&&(e=1)):e*=1e3),a=await t.retry.calculateDelay({attemptCount:n,retryOptions:t.retry,error:r,retryAfter:e,computedValue:D.default({attemptCount:n,retryOptions:t.retry,error:r,retryAfter:e,computedValue:0})})}catch(e){this._error(new _e(e.message,e,this));return}if(a){let t=async()=>{try{for(let e of this.options.hooks.beforeRetry)await e(this.options,r,n)}catch(t){this._error(new _e(t.message,e,this));return}this.destroyed||(this.destroy(),this.emit(`retry`,n,e))};this[le]=setTimeout(t,a);return}}this._error(r)})()}_read(){this[ae]=!0;let e=this[A];if(e&&!this[ie]){e.readableLength&&(this[ae]=!1);let t;for(;(t=e.read())!==null;){this[M]+=t.length,this[re]=!0;let e=this.downloadProgress;e.percent<1&&this.emit(`downloadProgress`,e),this.push(t)}}}_write(e,t,n){let r=()=>{this._writeRequest(e,t,n)};this.requestInitialized?r():this[se].push(r)}_writeRequest(e,t,n){this[k].destroyed||(this._progressCallbacks.push(()=>{this[P]+=Buffer.byteLength(e,t);let n=this.uploadProgress;n.percent<1&&this.emit(`uploadProgress`,n)}),this[k].write(e,t,e=>{!e&&this._progressCallbacks.length>0&&this._progressCallbacks.shift()(),n(e)}))}_final(e){let t=()=>{for(;this._progressCallbacks.length!==0;)this._progressCallbacks.shift()();k in this?this[k].destroyed?e():this[k].end(t=>{t||(this[N]=this[P],this.emit(`uploadProgress`,this.uploadProgress),this[k].emit(`upload-complete`)),e(t)}):e()};this.requestInitialized?t():this[se].push(t)}_destroy(e,t){var n;this[ie]=!0,clearTimeout(this[le]),k in this&&(this[ne](),(n=this[A])!=null&&n.complete||this[k].destroy()),e!==null&&!m.default.undefined(e)&&!(e instanceof _e)&&(e=new _e(e.message,e,this)),t(e)}get _isAboutToError(){return this[ie]}get ip(){return this.socket?.remoteAddress}get aborted(){var e;return(this[k]?.destroyed??this.destroyed)&&!((e=this[ce])!=null&&e.complete)}get socket(){return this[k]?.socket??void 0}get downloadProgress(){let e;return e=this[j]?this[M]/this[j]:+(this[j]===this[M]),{percent:e,transferred:this[M],total:this[j]}}get uploadProgress(){let e;return e=this[N]?this[P]/this[N]:+(this[N]===this[P]),{percent:e,transferred:this[P],total:this[N]}}get timings(){return this[k]?.timings}get isFromCache(){return this[te]}pipe(e,t){if(this[re])throw Error(`Failed to pipe. The response has been emitted already.`);return e instanceof o.ServerResponse&&this[F].add(e),super.pipe(e,t)}unpipe(e){return e instanceof o.ServerResponse&&this[F].delete(e),super.unpipe(e),this}};e.default=Te})),T_=X((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.CancelError=e.ParseError=void 0;var r=w_();e.ParseError=class extends r.RequestError{constructor(e,t){let{options:n}=t.request;super(`${e.message} in "${n.url.toString()}"`,e,t.request),this.name=`ParseError`,this.code=this.code===`ERR_GOT_REQUEST_ERROR`?`ERR_BODY_PARSE_FAILURE`:this.code}},e.CancelError=class extends r.RequestError{constructor(e){super(`Promise was canceled`,{},e),this.name=`CancelError`,this.code=`ERR_CANCELED`}get isCanceled(){return!0}},n(w_(),e)})),E_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=T_();e.default=(e,n,r,i)=>{let{rawBody:a}=e;try{if(n===`text`)return a.toString(i);if(n===`json`)return a.length===0?``:r(a.toString());if(n===`buffer`)return a;throw new t.ParseError({message:`Unknown body type '${n}'`,name:`Error`},e)}catch(n){throw new t.ParseError(n,e)}}})),D_=X((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0});var r=Z(`events`),i=Ag(),a=jg(),o=T_(),s=E_(),c=w_(),l=f_(),u=v_(),d=b_(),f=[`request`,`response`,`redirect`,`uploadProgress`,`downloadProgress`];function p(e){let t,n,m=new r.EventEmitter,h=new a((r,a,g)=>{let _=v=>{let y=new c.default(void 0,e);y.retryCount=v,y._noPipe=!0,g(()=>y.destroy()),g.shouldReject=!1,g(()=>a(new o.CancelError(y))),t=y,y.once(`response`,async e=>{if(e.retryCount=v,e.request.aborted)return;let t;try{t=await u.default(y),e.rawBody=t}catch{return}if(y._isAboutToError)return;let i=(e.headers[`content-encoding`]??``).toLowerCase(),a=[`gzip`,`deflate`,`br`].includes(i),{options:l}=y;if(a&&!l.decompress)e.body=t;else try{e.body=s.default(e,l.responseType,l.parseJson,l.encoding)}catch(n){if(e.body=t.toString(),d.isResponseOk(e)){y._beforeError(n);return}}try{for(let[t,n]of l.hooks.afterResponse.entries())e=await n(e,async e=>{let n=c.default.normalizeArguments(void 0,{...e,retry:{calculateDelay:()=>0},throwHttpErrors:!1,resolveBodyOnly:!1},l);n.hooks.afterResponse=n.hooks.afterResponse.slice(0,t);for(let e of n.hooks.beforeRetry)await e(n);let r=p(n);return g(()=>{r.catch(()=>{}),r.cancel()}),r})}catch(e){y._beforeError(new o.RequestError(e.message,e,y));return}n=e,d.isResponseOk(e)?(y.destroy(),r(y.options.resolveBodyOnly?e.body:e)):y._beforeError(new o.HTTPError(e))});let b=e=>{if(h.isCanceled)return;let{options:t}=y;if(e instanceof o.HTTPError&&!t.throwHttpErrors){let{response:t}=e;r(y.options.resolveBodyOnly?t.body:t)}else a(e)};y.once(`error`,b);let x=y.options.body;y.once(`retry`,(e,t)=>{x===t.request?.options.body&&i.default.nodeStream(t.request?.options.body)?b(t):_(e)}),l.default(y,m,f)};_(0)});h.on=(e,t)=>(m.on(e,t),h);let g=e=>{let t=(async()=>{await h;let{options:t}=n.request;return s.default(n,e,t.parseJson,t.encoding)})();return Object.defineProperties(t,Object.getOwnPropertyDescriptors(h)),t};return h.json=()=>{let{headers:e}=t.options;return!t.writableFinished&&e.accept===void 0&&(e.accept=`application/json`),g(`json`)},h.buffer=()=>g(`buffer`),h.text=()=>g(`text`),h}e.default=p,n(T_(),e)})),O_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=T_();function n(e,...n){let r=(async()=>{if(e instanceof t.RequestError)try{for(let t of n)if(t)for(let n of t)e=await n(e)}catch(t){e=t}throw e})(),i=()=>r;return r.json=i,r.text=i,r.buffer=i,r.on=i,r}e.default=n})),k_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Ag();function n(e){for(let r of Object.values(e))(t.default.plainObject(r)||t.default.array(r))&&n(r);return Object.freeze(e)}e.default=n})),A_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),j_=X((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__exportStar||function(e,n){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.defaultHandler=void 0;var r=Ag(),i=D_(),a=O_(),o=w_(),s=k_(),c={RequestError:i.RequestError,CacheError:i.CacheError,ReadError:i.ReadError,HTTPError:i.HTTPError,MaxRedirectsError:i.MaxRedirectsError,TimeoutError:i.TimeoutError,ParseError:i.ParseError,CancelError:i.CancelError,UnsupportedProtocolError:i.UnsupportedProtocolError,UploadError:i.UploadError},l=async e=>new Promise(t=>{setTimeout(t,e)}),{normalizeArguments:u}=o.default,d=(...e)=>{let t;for(let n of e)t=u(void 0,n,t);return t},f=e=>e.isStream?new o.default(void 0,e):i.default(e),p=e=>`defaults`in e&&`options`in e.defaults,m=[`get`,`post`,`put`,`patch`,`head`,`delete`];e.defaultHandler=(e,t)=>t(e);var h=(e,t)=>{if(e)for(let n of e)n(t)},g=t=>{t._rawHandlers=t.handlers,t.handlers=t.handlers.map(e=>((t,n)=>{let r,i=e(t,e=>(r=n(e),r));if(i!==r&&!t.isStream&&r){let e=i,{then:t,catch:n,finally:a}=e;Object.setPrototypeOf(e,Object.getPrototypeOf(r)),Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)),e.then=t,e.catch=n,e.finally=a}return i}));let n=((e,n={},s)=>{let c=0,l=e=>t.handlers[c++](e,c===t.handlers.length?f:l);if(r.default.plainObject(e)){let t={...e,...n};o.setNonEnumerableProperties([e,n],t),n=t,e=void 0}try{let r;try{h(t.options.hooks.init,n),h(n.hooks?.init,n)}catch(e){r=e}let a=u(e,n,s??t.options);if(a[o.kIsNormalizedAlready]=!0,r)throw new i.RequestError(r.message,r,a);return l(a)}catch(e){if(n.isStream)throw e;return a.default(e,t.options.hooks.beforeError,n.hooks?.beforeError)}});n.extend=(...n)=>{let r=[t.options],i=[...t._rawHandlers],a;for(let e of n)p(e)?(r.push(e.defaults.options),i.push(...e.defaults._rawHandlers),a=e.defaults.mutableDefaults):(r.push(e),`handlers`in e&&i.push(...e.handlers),a=e.mutableDefaults);return i=i.filter(t=>t!==e.defaultHandler),i.length===0&&i.push(e.defaultHandler),g({options:d(...r),handlers:i,mutableDefaults:!!a})};let _=(async function*(e,i){let a=u(e,i,t.options);a.resolveBodyOnly=!1;let o=a.pagination;if(!r.default.object(o))throw TypeError("`options.pagination` must be implemented");let s=[],{countLimit:c}=o,d=0;for(;d<o.requestLimit;){d!==0&&await l(o.backoff);let e=await n(void 0,void 0,a),t=await o.transform(e),r=[];for(let e of t)if(o.filter(e,s,r)&&(!o.shouldContinue(e,s,r)||(yield e,o.stackAllItems&&s.push(e),r.push(e),--c<=0)))return;let i=o.paginate(e,s,r);if(i===!1)return;i===e.request.options?a=e.request.options:i!==void 0&&(a=u(void 0,i,a)),d++}});n.paginate=_,n.paginate.all=(async(e,t)=>{let n=[];for await(let r of _(e,t))n.push(r);return n}),n.paginate.each=_,n.stream=((e,t)=>n(e,{...t,isStream:!0}));for(let e of m)n[e]=((t,r)=>n(t,{...r,method:e})),n.stream[e]=((t,r)=>n(t,{...r,method:e,isStream:!0}));return Object.assign(n,c),Object.defineProperty(n,"defaults",{value:t.mutableDefaults?t:s.default(t),writable:t.mutableDefaults,configurable:t.mutableDefaults,enumerable:!0}),n.mergeOptions=d,n};e.default=g,n(A_(),e)})),M_=X(((e,t)=>{var n=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),r=e&&e.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&n(t,e,r)};Object.defineProperty(e,"__esModule",{value:!0});var i=Z(`url`),a=j_(),o={options:{method:`GET`,retry:{limit:2,methods:[`GET`,`PUT`,`HEAD`,`DELETE`,`OPTIONS`,`TRACE`],statusCodes:[408,413,429,500,502,503,504,521,522,524],errorCodes:[`ETIMEDOUT`,`ECONNRESET`,`EADDRINUSE`,`ECONNREFUSED`,`EPIPE`,`ENOTFOUND`,`ENETUNREACH`,`EAI_AGAIN`],maxRetryAfter:void 0,calculateDelay:({computedValue:e})=>e},timeout:{},headers:{"user-agent":`got (https://github.com/sindresorhus/got)`},hooks:{init:[],beforeRequest:[],beforeRedirect:[],beforeRetry:[],beforeError:[],afterResponse:[]},cache:void 0,dnsCache:void 0,decompress:!0,throwHttpErrors:!0,followRedirect:!0,isStream:!1,responseType:`text`,resolveBodyOnly:!1,maxRedirects:10,prefixUrl:``,methodRewriting:!0,ignoreInvalidCookies:!1,context:{},http2:!1,allowGetBody:!1,https:void 0,pagination:{transform:e=>e.request.options.responseType===`json`?e.body:JSON.parse(e.body),paginate:e=>{if(!Reflect.has(e.headers,`link`))return!1;let t=e.headers.link.split(`,`),n;for(let e of t){let t=e.split(`;`);if(t[1].includes(`next`)){n=t[0].trimStart().trim(),n=n.slice(1,-1);break}}return n?{url:new i.URL(n)}:!1},filter:()=>!0,shouldContinue:()=>!0,countLimit:1/0,backoff:0,requestLimit:1e4,stackAllItems:!0},parseJson:e=>JSON.parse(e),stringifyJson:e=>JSON.stringify(e),cacheOptions:{}},handlers:[a.defaultHandler],mutableDefaults:!1},s=a.default(o);e.default=s,t.exports=s,t.exports.default=s,t.exports.__esModule=!0,r(j_(),e),r(D_(),e)})),N_=X(((e,t)=>{var n=new Map([[`C`,`cwd`],[`f`,`file`],[`z`,`gzip`],[`P`,`preservePaths`],[`U`,`unlink`],[`strip-components`,`strip`],[`stripComponents`,`strip`],[`keep-newer`,`newer`],[`keepNewer`,`newer`],[`keep-newer-files`,`newer`],[`keepNewerFiles`,`newer`],[`k`,`keep`],[`keep-existing`,`keep`],[`keepExisting`,`keep`],[`m`,`noMtime`],[`no-mtime`,`noMtime`],[`p`,`preserveOwner`],[`L`,`follow`],[`h`,`follow`]]);t.exports=e=>e?Object.keys(e).map(t=>[n.has(t)?n.get(t):t,e[t]]).reduce((e,t)=>(e[t[0]]=t[1],e),Object.create(null)):{}})),P_=X((e=>{var t=typeof process==`object`&&process?process:{stdout:null,stderr:null},n=Z(`events`),r=Z(`stream`),i=Z(`string_decoder`).StringDecoder,a=Symbol(`EOF`),o=Symbol(`maybeEmitEnd`),s=Symbol(`emittedEnd`),c=Symbol(`emittingEnd`),l=Symbol(`emittedError`),u=Symbol(`closed`),d=Symbol(`read`),f=Symbol(`flush`),p=Symbol(`flushChunk`),m=Symbol(`encoding`),h=Symbol(`decoder`),g=Symbol(`flowing`),_=Symbol(`paused`),v=Symbol(`resume`),y=Symbol(`buffer`),b=Symbol(`pipes`),x=Symbol(`bufferLength`),S=Symbol(`bufferPush`),C=Symbol(`bufferShift`),w=Symbol(`objectMode`),T=Symbol(`destroyed`),E=Symbol(`error`),D=Symbol(`emitData`),O=Symbol(`emitEnd`),k=Symbol(`emitEnd2`),A=Symbol(`async`),j=Symbol(`abort`),M=Symbol(`aborted`),N=Symbol(`signal`),P=e=>Promise.resolve().then(e),F=global._MP_NO_ITERATOR_SYMBOLS_!==`1`,ee=F&&Symbol.asyncIterator||Symbol(`asyncIterator not implemented`),te=F&&Symbol.iterator||Symbol(`iterator not implemented`),ne=e=>e===`end`||e===`finish`||e===`prefinish`,re=e=>e instanceof ArrayBuffer||typeof e==`object`&&e.constructor&&e.constructor.name===`ArrayBuffer`&&e.byteLength>=0,ie=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),ae=class{constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[v](),t.on(`drain`,this.ondrain)}unpipe(){this.dest.removeListener(`drain`,this.ondrain)}proxyErrors(){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},oe=class extends ae{unpipe(){this.src.removeListener(`error`,this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=e=>t.emit(`error`,e),e.on(`error`,this.proxyErrors)}};e.Minipass=class e extends r{constructor(e){super(),this[g]=!1,this[_]=!1,this[b]=[],this[y]=[],this[w]=e&&e.objectMode||!1,this[m]=this[w]?null:e&&e.encoding||null,this[m]===`buffer`&&(this[m]=null),this[A]=e&&!!e.async||!1,this[h]=this[m]?new i(this[m]):null,this[a]=!1,this[s]=!1,this[c]=!1,this[u]=!1,this[l]=null,this.writable=!0,this.readable=!0,this[x]=0,this[T]=!1,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[y]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[b]}),this[N]=e&&e.signal,this[M]=!1,this[N]&&(this[N].addEventListener(`abort`,()=>this[j]()),this[N].aborted&&this[j]())}get bufferLength(){return this[x]}get encoding(){return this[m]}set encoding(e){if(this[w])throw Error(`cannot set encoding in objectMode`);if(this[m]&&e!==this[m]&&(this[h]&&this[h].lastNeed||this[x]))throw Error(`cannot change encoding`);this[m]!==e&&(this[h]=e?new i(e):null,this[y].length&&(this[y]=this[y].map(e=>this[h].write(e)))),this[m]=e}setEncoding(e){this.encoding=e}get objectMode(){return this[w]}set objectMode(e){this[w]=this[w]||!!e}get async(){return this[A]}set async(e){this[A]=this[A]||!!e}[j](){this[M]=!0,this.emit(`abort`,this[N].reason),this.destroy(this[N].reason)}get aborted(){return this[M]}set aborted(e){}write(e,t,n){if(this[M])return!1;if(this[a])throw Error(`write after end`);if(this[T])return this.emit(`error`,Object.assign(Error(`Cannot call write after a stream was destroyed`),{code:`ERR_STREAM_DESTROYED`})),!0;typeof t==`function`&&(n=t,t=`utf8`),t||=`utf8`;let r=this[A]?P:e=>e();return!this[w]&&!Buffer.isBuffer(e)&&(ie(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):re(e)?e=Buffer.from(e):typeof e!=`string`&&(this.objectMode=!0)),this[w]?(this.flowing&&this[x]!==0&&this[f](!0),this.flowing?this.emit(`data`,e):this[S](e),this[x]!==0&&this.emit(`readable`),n&&r(n),this.flowing):e.length?(typeof e==`string`&&(t!==this[m]||this[h].lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[m]&&(e=this[h].write(e)),this.flowing&&this[x]!==0&&this[f](!0),this.flowing?this.emit(`data`,e):this[S](e),this[x]!==0&&this.emit(`readable`),n&&r(n),this.flowing):(this[x]!==0&&this.emit(`readable`),n&&r(n),this.flowing)}read(e){if(this[T])return null;if(this[x]===0||e===0||e>this[x])return this[o](),null;this[w]&&(e=null),this[y].length>1&&!this[w]&&(this[y]=this.encoding?[this[y].join(``)]:[Buffer.concat(this[y],this[x])]);let t=this[d](e||null,this[y][0]);return this[o](),t}[d](e,t){return e===t.length||e===null?this[C]():(this[y][0]=t.slice(e),t=t.slice(0,e),this[x]-=e),this.emit(`data`,t),!this[y].length&&!this[a]&&this.emit(`drain`),t}end(e,t,n){return typeof e==`function`&&(n=e,e=null),typeof t==`function`&&(n=t,t=`utf8`),e&&this.write(e,t),n&&this.once(`end`,n),this[a]=!0,this.writable=!1,(this.flowing||!this[_])&&this[o](),this}[v](){this[T]||(this[_]=!1,this[g]=!0,this.emit(`resume`),this[y].length?this[f]():this[a]?this[o]():this.emit(`drain`))}resume(){return this[v]()}pause(){this[g]=!1,this[_]=!0}get destroyed(){return this[T]}get flowing(){return this[g]}get paused(){return this[_]}[S](e){this[w]?this[x]+=1:this[x]+=e.length,this[y].push(e)}[C](){return this[w]?--this[x]:this[x]-=this[y][0].length,this[y].shift()}[f](e){do;while(this[p](this[C]())&&this[y].length);!e&&!this[y].length&&!this[a]&&this.emit(`drain`)}[p](e){return this.emit(`data`,e),this.flowing}pipe(e,n){if(this[T])return;let r=this[s];return n||={},e===t.stdout||e===t.stderr?n.end=!1:n.end=n.end!==!1,n.proxyErrors=!!n.proxyErrors,r?n.end&&e.end():(this[b].push(n.proxyErrors?new oe(this,e,n):new ae(this,e,n)),this[A]?P(()=>this[v]()):this[v]()),e}unpipe(e){let t=this[b].find(t=>t.dest===e);t&&(this[b].splice(this[b].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);return e===`data`&&!this[b].length&&!this.flowing?this[v]():e===`readable`&&this[x]!==0?super.emit(`readable`):ne(e)&&this[s]?(super.emit(e),this.removeAllListeners(e)):e===`error`&&this[l]&&(this[A]?P(()=>t.call(this,this[l])):t.call(this,this[l])),n}get emittedEnd(){return this[s]}[o](){!this[c]&&!this[s]&&!this[T]&&this[y].length===0&&this[a]&&(this[c]=!0,this.emit(`end`),this.emit(`prefinish`),this.emit(`finish`),this[u]&&this.emit(`close`),this[c]=!1)}emit(e,t,...n){if(e!==`error`&&e!==`close`&&e!==T&&this[T])return;if(e===`data`)return!this[w]&&!t?!1:this[A]?P(()=>this[D](t)):this[D](t);if(e===`end`)return this[O]();if(e===`close`){if(this[u]=!0,!this[s]&&!this[T])return;let e=super.emit(`close`);return this.removeAllListeners(`close`),e}if(e===`error`){this[l]=t,super.emit(E,t);let e=!this[N]||this.listeners(`error`).length?super.emit(`error`,t):!1;return this[o](),e}if(e===`resume`){let e=super.emit(`resume`);return this[o](),e}if(e===`finish`||e===`prefinish`){let t=super.emit(e);return this.removeAllListeners(e),t}let r=super.emit(e,t,...n);return this[o](),r}[D](e){for(let t of this[b])t.dest.write(e)===!1&&this.pause();let t=super.emit(`data`,e);return this[o](),t}[O](){this[s]||(this[s]=!0,this.readable=!1,this[A]?P(()=>this[k]()):this[k]())}[k](){if(this[h]){let e=this[h].end();if(e){for(let t of this[b])t.dest.write(e);super.emit(`data`,e)}}for(let e of this[b])e.end();let e=super.emit(`end`);return this.removeAllListeners(`end`),e}collect(){let e=[];this[w]||(e.dataLength=0);let t=this.promise();return this.on(`data`,t=>{e.push(t),this[w]||(e.dataLength+=t.length)}),t.then(()=>e)}concat(){return this[w]?Promise.reject(Error(`cannot concat in objectMode`)):this.collect().then(e=>this[w]?Promise.reject(Error(`cannot concat in objectMode`)):this[m]?e.join(``):Buffer.concat(e,e.dataLength))}promise(){return new Promise((e,t)=>{this.on(T,()=>t(Error(`stream destroyed`))),this.on(`error`,e=>t(e)),this.on(`end`,()=>e())})}[ee](){let e=!1,t=()=>(this.pause(),e=!0,Promise.resolve({done:!0}));return{next:()=>{if(e)return t();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[a])return t();let r=null,i=null,o=e=>{this.removeListener(`data`,s),this.removeListener(`end`,c),this.removeListener(T,l),t(),i(e)},s=e=>{this.removeListener(`error`,o),this.removeListener(`end`,c),this.removeListener(T,l),this.pause(),r({value:e,done:!!this[a]})},c=()=>{this.removeListener(`error`,o),this.removeListener(`data`,s),this.removeListener(T,l),t(),r({done:!0})},l=()=>o(Error(`stream destroyed`));return new Promise((e,t)=>{i=t,r=e,this.once(T,l),this.once(`error`,o),this.once(`end`,c),this.once(`data`,s)})},throw:t,return:t,[ee](){return this}}}[te](){let e=!1,t=()=>(this.pause(),this.removeListener(E,t),this.removeListener(T,t),this.removeListener(`end`,t),e=!0,{done:!0});return this.once(`end`,t),this.once(E,t),this.once(T,t),{next:()=>{if(e)return t();let n=this.read();return n===null?t():{value:n}},throw:t,return:t,[te](){return this}}}destroy(e){return this[T]?(e?this.emit(`error`,e):this.emit(T),this):(this[T]=!0,this[y].length=0,this[x]=0,typeof this.close==`function`&&!this[u]&&this.close(),e?this.emit(`error`,e):this.emit(T),this)}static isStream(t){return!!t&&(t instanceof e||t instanceof r||t instanceof n&&(typeof t.pipe==`function`||typeof t.write==`function`&&typeof t.end==`function`))}}})),F_=X(((e,t)=>{var n=Z(`zlib`).constants||{ZLIB_VERNUM:4736};t.exports=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},n))})),I_=X(((e,t)=>{var n=typeof process==`object`&&process?process:{stdout:null,stderr:null},r=Z(`events`),i=Z(`stream`),a=Z(`string_decoder`).StringDecoder,o=Symbol(`EOF`),s=Symbol(`maybeEmitEnd`),c=Symbol(`emittedEnd`),l=Symbol(`emittingEnd`),u=Symbol(`emittedError`),d=Symbol(`closed`),f=Symbol(`read`),p=Symbol(`flush`),m=Symbol(`flushChunk`),h=Symbol(`encoding`),g=Symbol(`decoder`),_=Symbol(`flowing`),v=Symbol(`paused`),y=Symbol(`resume`),b=Symbol(`bufferLength`),x=Symbol(`bufferPush`),S=Symbol(`bufferShift`),C=Symbol(`objectMode`),w=Symbol(`destroyed`),T=Symbol(`emitData`),E=Symbol(`emitEnd`),D=Symbol(`emitEnd2`),O=Symbol(`async`),k=e=>Promise.resolve().then(e),A=global._MP_NO_ITERATOR_SYMBOLS_!==`1`,j=A&&Symbol.asyncIterator||Symbol(`asyncIterator not implemented`),M=A&&Symbol.iterator||Symbol(`iterator not implemented`),N=e=>e===`end`||e===`finish`||e===`prefinish`,P=e=>e instanceof ArrayBuffer||typeof e==`object`&&e.constructor&&e.constructor.name===`ArrayBuffer`&&e.byteLength>=0,F=e=>!Buffer.isBuffer(e)&&ArrayBuffer.isView(e),ee=class{constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[y](),t.on(`drain`,this.ondrain)}unpipe(){this.dest.removeListener(`drain`,this.ondrain)}proxyErrors(){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},te=class extends ee{unpipe(){this.src.removeListener(`error`,this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=e=>t.emit(`error`,e),e.on(`error`,this.proxyErrors)}};t.exports=class e extends i{constructor(e){super(),this[_]=!1,this[v]=!1,this.pipes=[],this.buffer=[],this[C]=e&&e.objectMode||!1,this[h]=this[C]?null:e&&e.encoding||null,this[h]===`buffer`&&(this[h]=null),this[O]=e&&!!e.async||!1,this[g]=this[h]?new a(this[h]):null,this[o]=!1,this[c]=!1,this[l]=!1,this[d]=!1,this[u]=null,this.writable=!0,this.readable=!0,this[b]=0,this[w]=!1}get bufferLength(){return this[b]}get encoding(){return this[h]}set encoding(e){if(this[C])throw Error(`cannot set encoding in objectMode`);if(this[h]&&e!==this[h]&&(this[g]&&this[g].lastNeed||this[b]))throw Error(`cannot change encoding`);this[h]!==e&&(this[g]=e?new a(e):null,this.buffer.length&&(this.buffer=this.buffer.map(e=>this[g].write(e)))),this[h]=e}setEncoding(e){this.encoding=e}get objectMode(){return this[C]}set objectMode(e){this[C]=this[C]||!!e}get async(){return this[O]}set async(e){this[O]=this[O]||!!e}write(e,t,n){if(this[o])throw Error(`write after end`);if(this[w])return this.emit(`error`,Object.assign(Error(`Cannot call write after a stream was destroyed`),{code:`ERR_STREAM_DESTROYED`})),!0;typeof t==`function`&&(n=t,t=`utf8`),t||=`utf8`;let r=this[O]?k:e=>e();return!this[C]&&!Buffer.isBuffer(e)&&(F(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):P(e)?e=Buffer.from(e):typeof e!=`string`&&(this.objectMode=!0)),this[C]?(this.flowing&&this[b]!==0&&this[p](!0),this.flowing?this.emit(`data`,e):this[x](e),this[b]!==0&&this.emit(`readable`),n&&r(n),this.flowing):e.length?(typeof e==`string`&&(t!==this[h]||this[g].lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[h]&&(e=this[g].write(e)),this.flowing&&this[b]!==0&&this[p](!0),this.flowing?this.emit(`data`,e):this[x](e),this[b]!==0&&this.emit(`readable`),n&&r(n),this.flowing):(this[b]!==0&&this.emit(`readable`),n&&r(n),this.flowing)}read(e){if(this[w])return null;if(this[b]===0||e===0||e>this[b])return this[s](),null;this[C]&&(e=null),this.buffer.length>1&&!this[C]&&(this.buffer=this.encoding?[this.buffer.join(``)]:[Buffer.concat(this.buffer,this[b])]);let t=this[f](e||null,this.buffer[0]);return this[s](),t}[f](e,t){return e===t.length||e===null?this[S]():(this.buffer[0]=t.slice(e),t=t.slice(0,e),this[b]-=e),this.emit(`data`,t),!this.buffer.length&&!this[o]&&this.emit(`drain`),t}end(e,t,n){return typeof e==`function`&&(n=e,e=null),typeof t==`function`&&(n=t,t=`utf8`),e&&this.write(e,t),n&&this.once(`end`,n),this[o]=!0,this.writable=!1,(this.flowing||!this[v])&&this[s](),this}[y](){this[w]||(this[v]=!1,this[_]=!0,this.emit(`resume`),this.buffer.length?this[p]():this[o]?this[s]():this.emit(`drain`))}resume(){return this[y]()}pause(){this[_]=!1,this[v]=!0}get destroyed(){return this[w]}get flowing(){return this[_]}get paused(){return this[v]}[x](e){this[C]?this[b]+=1:this[b]+=e.length,this.buffer.push(e)}[S](){return this.buffer.length&&(this[C]?--this[b]:this[b]-=this.buffer[0].length),this.buffer.shift()}[p](e){do;while(this[m](this[S]()));!e&&!this.buffer.length&&!this[o]&&this.emit(`drain`)}[m](e){return e?(this.emit(`data`,e),this.flowing):!1}pipe(e,t){if(this[w])return;let r=this[c];return t||={},e===n.stdout||e===n.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this.pipes.push(t.proxyErrors?new te(this,e,t):new ee(this,e,t)),this[O]?k(()=>this[y]()):this[y]()),e}unpipe(e){let t=this.pipes.find(t=>t.dest===e);t&&(this.pipes.splice(this.pipes.indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);return e===`data`&&!this.pipes.length&&!this.flowing?this[y]():e===`readable`&&this[b]!==0?super.emit(`readable`):N(e)&&this[c]?(super.emit(e),this.removeAllListeners(e)):e===`error`&&this[u]&&(this[O]?k(()=>t.call(this,this[u])):t.call(this,this[u])),n}get emittedEnd(){return this[c]}[s](){!this[l]&&!this[c]&&!this[w]&&this.buffer.length===0&&this[o]&&(this[l]=!0,this.emit(`end`),this.emit(`prefinish`),this.emit(`finish`),this[d]&&this.emit(`close`),this[l]=!1)}emit(e,t,...n){if(e!==`error`&&e!==`close`&&e!==w&&this[w])return;if(e===`data`)return t?this[O]?k(()=>this[T](t)):this[T](t):!1;if(e===`end`)return this[E]();if(e===`close`){if(this[d]=!0,!this[c]&&!this[w])return;let e=super.emit(`close`);return this.removeAllListeners(`close`),e}if(e===`error`){this[u]=t;let e=super.emit(`error`,t);return this[s](),e}if(e===`resume`){let e=super.emit(`resume`);return this[s](),e}if(e===`finish`||e===`prefinish`){let t=super.emit(e);return this.removeAllListeners(e),t}let r=super.emit(e,t,...n);return this[s](),r}[T](e){for(let t of this.pipes)t.dest.write(e)===!1&&this.pause();let t=super.emit(`data`,e);return this[s](),t}[E](){this[c]||(this[c]=!0,this.readable=!1,this[O]?k(()=>this[D]()):this[D]())}[D](){if(this[g]){let e=this[g].end();if(e){for(let t of this.pipes)t.dest.write(e);super.emit(`data`,e)}}for(let e of this.pipes)e.end();let e=super.emit(`end`);return this.removeAllListeners(`end`),e}collect(){let e=[];this[C]||(e.dataLength=0);let t=this.promise();return this.on(`data`,t=>{e.push(t),this[C]||(e.dataLength+=t.length)}),t.then(()=>e)}concat(){return this[C]?Promise.reject(Error(`cannot concat in objectMode`)):this.collect().then(e=>this[C]?Promise.reject(Error(`cannot concat in objectMode`)):this[h]?e.join(``):Buffer.concat(e,e.dataLength))}promise(){return new Promise((e,t)=>{this.on(w,()=>t(Error(`stream destroyed`))),this.on(`error`,e=>t(e)),this.on(`end`,()=>e())})}[j](){return{next:()=>{let e=this.read();if(e!==null)return Promise.resolve({done:!1,value:e});if(this[o])return Promise.resolve({done:!0});let t=null,n=null,r=e=>{this.removeListener(`data`,i),this.removeListener(`end`,a),n(e)},i=e=>{this.removeListener(`error`,r),this.removeListener(`end`,a),this.pause(),t({value:e,done:!!this[o]})},a=()=>{this.removeListener(`error`,r),this.removeListener(`data`,i),t({done:!0})},s=()=>r(Error(`stream destroyed`));return new Promise((e,o)=>{n=o,t=e,this.once(w,s),this.once(`error`,r),this.once(`end`,a),this.once(`data`,i)})}}}[M](){return{next:()=>{let e=this.read();return{value:e,done:e===null}}}}destroy(e){return this[w]?(e?this.emit(`error`,e):this.emit(w),this):(this[w]=!0,this.buffer.length=0,this[b]=0,typeof this.close==`function`&&!this[d]&&this.close(),e?this.emit(`error`,e):this.emit(w),this)}static isStream(t){return!!t&&(t instanceof e||t instanceof i||t instanceof r&&(typeof t.pipe==`function`||typeof t.write==`function`&&typeof t.end==`function`))}}})),L_=X((e=>{var t=Z(`assert`),n=Z(`buffer`).Buffer,r=Z(`zlib`),i=e.constants=F_(),a=I_(),o=n.concat,s=Symbol(`_superWrite`),c=class extends Error{constructor(e){super(`zlib: `+e.message),this.code=e.code,this.errno=e.errno,this.code||=`ZLIB_ERROR`,this.message=`zlib: `+e.message,Error.captureStackTrace(this,this.constructor)}get name(){return`ZlibError`}},l=Symbol(`opts`),u=Symbol(`flushFlag`),d=Symbol(`finishFlushFlag`),f=Symbol(`fullFlushFlag`),p=Symbol(`handle`),m=Symbol(`onError`),h=Symbol(`sawError`),g=Symbol(`level`),_=Symbol(`strategy`),v=Symbol(`ended`),y=class extends a{constructor(e,t){if(!e||typeof e!=`object`)throw TypeError(`invalid options for ZlibBase constructor`);super(e),this[h]=!1,this[v]=!1,this[l]=e,this[u]=e.flush,this[d]=e.finishFlush;try{this[p]=new r[t](e)}catch(e){throw new c(e)}this[m]=e=>{this[h]||(this[h]=!0,this.close(),this.emit(`error`,e))},this[p].on(`error`,e=>this[m](new c(e))),this.once(`end`,()=>this.close)}close(){this[p]&&(this[p].close(),this[p]=null,this.emit(`close`))}reset(){if(!this[h])return t(this[p],`zlib binding closed`),this[p].reset()}flush(e){this.ended||(typeof e!=`number`&&(e=this[f]),this.write(Object.assign(n.alloc(0),{[u]:e})))}end(e,t,n){return e&&this.write(e,t),this.flush(this[d]),this[v]=!0,super.end(null,null,n)}get ended(){return this[v]}write(e,r,i){if(typeof r==`function`&&(i=r,r=`utf8`),typeof e==`string`&&(e=n.from(e,r)),this[h])return;t(this[p],`zlib binding closed`);let a=this[p]._handle,l=a.close;a.close=()=>{};let d=this[p].close;this[p].close=()=>{},n.concat=e=>e;let f;try{let t=typeof e[u]==`number`?e[u]:this[u];f=this[p]._processChunk(e,t),n.concat=o}catch(e){n.concat=o,this[m](new c(e))}finally{this[p]&&(this[p]._handle=a,a.close=l,this[p].close=d,this[p].removeAllListeners(`error`))}this[p]&&this[p].on(`error`,e=>this[m](new c(e)));let g;if(f){if(Array.isArray(f)&&f.length>0){g=this[s](n.from(f[0]));for(let e=1;e<f.length;e++)g=this[s](f[e])}else g=this[s](n.from(f))}return i&&i(),g}[s](e){return super.write(e)}},b=class extends y{constructor(e,t){e||={},e.flush=e.flush||i.Z_NO_FLUSH,e.finishFlush=e.finishFlush||i.Z_FINISH,super(e,t),this[f]=i.Z_FULL_FLUSH,this[g]=e.level,this[_]=e.strategy}params(e,n){if(!this[h]){if(!this[p])throw Error(`cannot switch params when binding is closed`);if(!this[p].params)throw Error(`not supported in this implementation`);if(this[g]!==e||this[_]!==n){this.flush(i.Z_SYNC_FLUSH),t(this[p],`zlib binding closed`);let r=this[p].flush;this[p].flush=(e,t)=>{this.flush(e),t()};try{this[p].params(e,n)}finally{this[p].flush=r}this[p]&&(this[g]=e,this[_]=n)}}}},x=class extends b{constructor(e){super(e,`Deflate`)}},S=class extends b{constructor(e){super(e,`Inflate`)}},C=Symbol(`_portable`),w=class extends b{constructor(e){super(e,`Gzip`),this[C]=e&&!!e.portable}[s](e){return this[C]&&(this[C]=!1,e[9]=255),super[s](e)}},T=class extends b{constructor(e){super(e,`Gunzip`)}},E=class extends b{constructor(e){super(e,`DeflateRaw`)}},D=class extends b{constructor(e){super(e,`InflateRaw`)}},O=class extends b{constructor(e){super(e,`Unzip`)}},k=class extends y{constructor(e,t){e||={},e.flush=e.flush||i.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||i.BROTLI_OPERATION_FINISH,super(e,t),this[f]=i.BROTLI_OPERATION_FLUSH}},A=class extends k{constructor(e){super(e,`BrotliCompress`)}},j=class extends k{constructor(e){super(e,`BrotliDecompress`)}};e.Deflate=x,e.Inflate=S,e.Gzip=w,e.Gunzip=T,e.DeflateRaw=E,e.InflateRaw=D,e.Unzip=O,typeof r.BrotliCompress==`function`?(e.BrotliCompress=A,e.BrotliDecompress=j):e.BrotliCompress=e.BrotliDecompress=class{constructor(){throw Error(`Brotli is not supported in this version of Node.js`)}}})),R_=X(((e,t)=>{t.exports=(process.env.TESTING_TAR_FAKE_PLATFORM||process.platform)===`win32`?e=>e&&e.replace(/\\/g,`/`):e=>e})),z_=X(((e,t)=>{var{Minipass:n}=P_(),r=R_(),i=Symbol(`slurp`);t.exports=class extends n{constructor(e,t,n){switch(super(),this.pause(),this.extended=t,this.globalExtended=n,this.header=e,this.startBlockSize=512*Math.ceil(e.size/512),this.blockRemain=this.startBlockSize,this.remain=e.size,this.type=e.type,this.meta=!1,this.ignore=!1,this.type){case`File`:case`OldFile`:case`Link`:case`SymbolicLink`:case`CharacterDevice`:case`BlockDevice`:case`Directory`:case`FIFO`:case`ContiguousFile`:case`GNUDumpDir`:break;case`NextFileHasLongLinkpath`:case`NextFileHasLongPath`:case`OldGnuLongPath`:case`GlobalExtendedHeader`:case`ExtendedHeader`:case`OldExtendedHeader`:this.meta=!0;break;default:this.ignore=!0}this.path=r(e.path),this.mode=e.mode,this.mode&&(this.mode&=4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=e.size,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=r(e.linkpath),this.uname=e.uname,this.gname=e.gname,t&&this[i](t),n&&this[i](n,!0)}write(e){let t=e.length;if(t>this.blockRemain)throw Error(`writing more to entry than is appropriate`);let n=this.remain,r=this.blockRemain;return this.remain=Math.max(0,n-t),this.blockRemain=Math.max(0,r-t),this.ignore?!0:n>=t?super.write(e):super.write(e.slice(0,n))}[i](e,t){for(let n in e)e[n]!==null&&e[n]!==void 0&&!(t&&n===`path`)&&(this[n]=n===`path`||n===`linkpath`?r(e[n]):e[n])}}})),B_=X((e=>{e.name=new Map([[`0`,`File`],[``,`OldFile`],[`1`,`Link`],[`2`,`SymbolicLink`],[`3`,`CharacterDevice`],[`4`,`BlockDevice`],[`5`,`Directory`],[`6`,`FIFO`],[`7`,`ContiguousFile`],[`g`,`GlobalExtendedHeader`],[`x`,`ExtendedHeader`],[`A`,`SolarisACL`],[`D`,`GNUDumpDir`],[`I`,`Inode`],[`K`,`NextFileHasLongLinkpath`],[`L`,`NextFileHasLongPath`],[`M`,`ContinuationFile`],[`N`,`OldGnuLongPath`],[`S`,`SparseFile`],[`V`,`TapeVolumeHeader`],[`X`,`OldExtendedHeader`]]),e.code=new Map(Array.from(e.name).map(e=>[e[1],e[0]]))})),V_=X(((e,t)=>{var n=(e,t)=>{if(Number.isSafeInteger(e))e<0?i(e,t):r(e,t);else throw Error(`cannot encode number outside of javascript safe integer range`);return t},r=(e,t)=>{t[0]=128;for(var n=t.length;n>1;n--)t[n-1]=e&255,e=Math.floor(e/256)},i=(e,t)=>{t[0]=255;var n=!1;e*=-1;for(var r=t.length;r>1;r--){var i=e&255;e=Math.floor(e/256),n?t[r-1]=c(i):i===0?t[r-1]=0:(n=!0,t[r-1]=l(i))}},a=e=>{let t=e[0],n=t===128?s(e.slice(1,e.length)):t===255?o(e):null;if(n===null)throw Error(`invalid base256 encoding`);if(!Number.isSafeInteger(n))throw Error(`parsed number outside of javascript safe integer range`);return n},o=e=>{for(var t=e.length,n=0,r=!1,i=t-1;i>-1;i--){var a=e[i],o;r?o=c(a):a===0?o=a:(r=!0,o=l(a)),o!==0&&(n-=o*256**(t-i-1))}return n},s=e=>{for(var t=e.length,n=0,r=t-1;r>-1;r--){var i=e[r];i!==0&&(n+=i*256**(t-r-1))}return n},c=e=>(255^e)&255,l=e=>(255^e)+1&255;t.exports={encode:n,parse:a}})),H_=X(((e,t)=>{var n=B_(),r=Z(`path`).posix,i=V_(),a=Symbol(`slurp`),o=Symbol(`type`),s=class{constructor(e,t,n,r){this.cksumValid=!1,this.needPax=!1,this.nullBlock=!1,this.block=null,this.path=null,this.mode=null,this.uid=null,this.gid=null,this.size=null,this.mtime=null,this.cksum=null,this[o]=`0`,this.linkpath=null,this.uname=null,this.gname=null,this.devmaj=0,this.devmin=0,this.atime=null,this.ctime=null,Buffer.isBuffer(e)?this.decode(e,t||0,n,r):e&&this.set(e)}decode(e,t,n,r){if(t||=0,!e||!(e.length>=t+512))throw Error(`need 512 bytes for header`);if(this.path=l(e,t,100),this.mode=f(e,t+100,8),this.uid=f(e,t+108,8),this.gid=f(e,t+116,8),this.size=f(e,t+124,12),this.mtime=u(e,t+136,12),this.cksum=f(e,t+148,12),this[a](n),this[a](r,!0),this[o]=l(e,t+156,1),this[o]===``&&(this[o]=`0`),this[o]===`0`&&this.path.slice(-1)===`/`&&(this[o]=`5`),this[o]===`5`&&(this.size=0),this.linkpath=l(e,t+157,100),e.slice(t+257,t+265).toString()===`ustar\x0000`){if(this.uname=l(e,t+265,32),this.gname=l(e,t+297,32),this.devmaj=f(e,t+329,8),this.devmin=f(e,t+337,8),e[t+475]!==0){let n=l(e,t+345,155);this.path=n+`/`+this.path}else{let n=l(e,t+345,130);n&&(this.path=n+`/`+this.path),this.atime=u(e,t+476,12),this.ctime=u(e,t+488,12)}}let i=256;for(let n=t;n<t+148;n++)i+=e[n];for(let n=t+156;n<t+512;n++)i+=e[n];this.cksumValid=i===this.cksum,this.cksum===null&&i===256&&(this.nullBlock=!0)}[a](e,t){for(let n in e)e[n]!==null&&e[n]!==void 0&&!(t&&n===`path`)&&(this[n]=e[n])}encode(e,t){if(e||(e=this.block=Buffer.alloc(512),t=0),t||=0,!(e.length>=t+512))throw Error(`need 512 bytes for header`);let n=this.ctime||this.atime?130:155,r=c(this.path||``,n),i=r[0],a=r[1];this.needPax=r[2],this.needPax=S(e,t,100,i)||this.needPax,this.needPax=g(e,t+100,8,this.mode)||this.needPax,this.needPax=g(e,t+108,8,this.uid)||this.needPax,this.needPax=g(e,t+116,8,this.gid)||this.needPax,this.needPax=g(e,t+124,12,this.size)||this.needPax,this.needPax=b(e,t+136,12,this.mtime)||this.needPax,e[t+156]=this[o].charCodeAt(0),this.needPax=S(e,t+157,100,this.linkpath)||this.needPax,e.write(`ustar\x0000`,t+257,8),this.needPax=S(e,t+265,32,this.uname)||this.needPax,this.needPax=S(e,t+297,32,this.gname)||this.needPax,this.needPax=g(e,t+329,8,this.devmaj)||this.needPax,this.needPax=g(e,t+337,8,this.devmin)||this.needPax,this.needPax=S(e,t+345,n,a)||this.needPax,e[t+475]===0?(this.needPax=S(e,t+345,130,a)||this.needPax,this.needPax=b(e,t+476,12,this.atime)||this.needPax,this.needPax=b(e,t+488,12,this.ctime)||this.needPax):this.needPax=S(e,t+345,155,a)||this.needPax;let s=256;for(let n=t;n<t+148;n++)s+=e[n];for(let n=t+156;n<t+512;n++)s+=e[n];return this.cksum=s,g(e,t+148,8,this.cksum),this.cksumValid=!0,this.needPax}set(e){for(let t in e)e[t]!==null&&e[t]!==void 0&&(this[t]=e[t])}get type(){return n.name.get(this[o])||this[o]}get typeKey(){return this[o]}set type(e){this[o]=n.code.has(e)?n.code.get(e):e}},c=(e,t)=>{let n=e,i=``,a,o=r.parse(e).root||`.`;if(Buffer.byteLength(n)<100)a=[n,i,!1];else{i=r.dirname(n),n=r.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(i)<=t?a=[n,i,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(i)<=t?a=[n.slice(0,99),i,!0]:(n=r.join(r.basename(i),n),i=r.dirname(i));while(i!==o&&!a);a||=[e.slice(0,99),``,!0]}return a},l=(e,t,n)=>e.slice(t,t+n).toString(`utf8`).replace(/\0.*/,``),u=(e,t,n)=>d(f(e,t,n)),d=e=>e===null?null:new Date(e*1e3),f=(e,t,n)=>e[t]&128?i.parse(e.slice(t,t+n)):m(e,t,n),p=e=>isNaN(e)?null:e,m=(e,t,n)=>p(parseInt(e.slice(t,t+n).toString(`utf8`).replace(/\0.*$/,``).trim(),8)),h={12:8589934591,8:2097151},g=(e,t,n,r)=>r===null?!1:r>h[n]||r<0?(i.encode(r,e.slice(t,t+n)),!0):(_(e,t,n,r),!1),_=(e,t,n,r)=>e.write(v(r,n),t,n,`ascii`),v=(e,t)=>y(Math.floor(e).toString(8),t),y=(e,t)=>(e.length===t-1?e:Array(t-e.length-1).join(`0`)+e+` `)+`\0`,b=(e,t,n,r)=>r!==null&&g(e,t,n,r.getTime()/1e3),x=Array(156).join(`\0`),S=(e,t,n,r)=>r!==null&&(e.write(r+x,t,n,`utf8`),r.length!==Buffer.byteLength(r)||r.length>n);t.exports=s})),U_=X(((e,t)=>{var n=H_(),r=Z(`path`),i=class{constructor(e,t){this.atime=e.atime||null,this.charset=e.charset||null,this.comment=e.comment||null,this.ctime=e.ctime||null,this.gid=e.gid||null,this.gname=e.gname||null,this.linkpath=e.linkpath||null,this.mtime=e.mtime||null,this.path=e.path||null,this.size=e.size||null,this.uid=e.uid||null,this.uname=e.uname||null,this.dev=e.dev||null,this.ino=e.ino||null,this.nlink=e.nlink||null,this.global=t||!1}encode(){let e=this.encodeBody();if(e===``)return null;let t=Buffer.byteLength(e),i=512*Math.ceil(1+t/512),a=Buffer.allocUnsafe(i);for(let e=0;e<512;e++)a[e]=0;new n({path:(`PaxHeader/`+r.basename(this.path)).slice(0,99),mode:this.mode||420,uid:this.uid||null,gid:this.gid||null,size:t,mtime:this.mtime||null,type:this.global?`GlobalExtendedHeader`:`ExtendedHeader`,linkpath:``,uname:this.uname||``,gname:this.gname||``,devmaj:0,devmin:0,atime:this.atime||null,ctime:this.ctime||null}).encode(a),a.write(e,512,t,`utf8`);for(let e=t+512;e<a.length;e++)a[e]=0;return a}encodeBody(){return this.encodeField(`path`)+this.encodeField(`ctime`)+this.encodeField(`atime`)+this.encodeField(`dev`)+this.encodeField(`ino`)+this.encodeField(`nlink`)+this.encodeField(`charset`)+this.encodeField(`comment`)+this.encodeField(`gid`)+this.encodeField(`gname`)+this.encodeField(`linkpath`)+this.encodeField(`mtime`)+this.encodeField(`size`)+this.encodeField(`uid`)+this.encodeField(`uname`)}encodeField(e){if(this[e]===null||this[e]===void 0)return``;let t=this[e]instanceof Date?this[e].getTime()/1e3:this[e],n=` `+(e===`dev`||e===`ino`||e===`nlink`?`SCHILY.`:``)+e+`=`+t+`
|
|
76
90
|
`,r=Buffer.byteLength(n),i=Math.floor(Math.log(r)/Math.log(10))+1;return r+i>=10**i&&(i+=1),i+r+n}};i.parse=(e,t,n)=>new i(a(o(e),t),n);var a=(e,t)=>t?Object.keys(e).reduce((t,n)=>(t[n]=e[n],t),t):e,o=e=>e.replace(/\n$/,``).split(`
|
|
77
|
-
`).reduce(s,Object.create(null)),s=(e,t)=>{let n=parseInt(t,10);if(n!==Buffer.byteLength(t)+1)return e;t=t.slice((n+` `).length);let r=t.split(`=`),i=r.shift().replace(/^SCHILY\.(dev|ino|nlink)/,`$1`);if(!i)return e;let a=r.join(`=`);return e[i]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(i)?new Date(a*1e3):/^[0-9]+$/.test(a)?+a:a,e};t.exports=i})),oy=L(((e,t)=>{t.exports=e=>{let t=e.length-1,n=-1;for(;t>-1&&e.charAt(t)===`/`;)n=t,t--;return n===-1?e:e.slice(0,n)}})),sy=L(((e,t)=>{t.exports=e=>class extends e{warn(e,t,n={}){this.file&&(n.file=this.file),this.cwd&&(n.cwd=this.cwd),n.code=t instanceof Error&&t.code||e,n.tarCode=e,!this.strict&&n.recoverable!==!1?(t instanceof Error&&(n=Object.assign(t,n),t=t.message),this.emit(`warn`,n.tarCode,t,n)):t instanceof Error?this.emit(`error`,Object.assign(t,n)):this.emit(`error`,Object.assign(Error(`${e}: ${t}`),n))}}})),cy=L(((e,t)=>{var n=[`|`,`<`,`>`,`?`,`:`],r=n.map(e=>String.fromCharCode(61440+e.charCodeAt(0))),i=new Map(n.map((e,t)=>[e,r[t]])),a=new Map(r.map((e,t)=>[e,n[t]]));t.exports={encode:e=>n.reduce((e,t)=>e.split(t).join(i.get(t)),e),decode:e=>r.reduce((e,t)=>e.split(t).join(a.get(t)),e)}})),ly=L(((e,t)=>{var{isAbsolute:n,parse:r}=R(`path`).win32;t.exports=e=>{let t=``,i=r(e);for(;n(e)||i.root;){let n=e.charAt(0)===`/`&&e.slice(0,4)!==`//?/`?`/`:i.root;e=e.slice(n.length),t+=n,i=r(e)}return[t,e]}})),uy=L(((e,t)=>{t.exports=(e,t,n)=>(e&=4095,n&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e)})),dy=L(((e,t)=>{var{Minipass:n}=Xv(),r=ay(),i=iy(),a=R(`fs`),o=R(`path`),s=ey(),c=oy(),l=(e,t)=>t?(e=s(e).replace(/^\.(\/|$)/,``),c(t)+`/`+e):s(e),u=16777216,d=Symbol(`process`),f=Symbol(`file`),p=Symbol(`directory`),m=Symbol(`symlink`),h=Symbol(`hardlink`),g=Symbol(`header`),_=Symbol(`read`),v=Symbol(`lstat`),y=Symbol(`onlstat`),b=Symbol(`onread`),x=Symbol(`onreadlink`),S=Symbol(`openfile`),C=Symbol(`onopenfile`),w=Symbol(`close`),T=Symbol(`mode`),E=Symbol(`awaitDrain`),D=Symbol(`ondrain`),O=Symbol(`prefix`),k=Symbol(`hadError`),A=sy(),j=cy(),M=ly(),N=uy(),P=A(class extends n{constructor(e,t){if(t||={},super(t),typeof e!=`string`)throw TypeError(`path is required`);this.path=s(e),this.portable=!!t.portable,this.myuid=process.getuid&&process.getuid()||0,this.myuser=process.env.USER||``,this.maxReadSize=t.maxReadSize||u,this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.preservePaths=!!t.preservePaths,this.cwd=s(t.cwd||process.cwd()),this.strict=!!t.strict,this.noPax=!!t.noPax,this.noMtime=!!t.noMtime,this.mtime=t.mtime||null,this.prefix=t.prefix?s(t.prefix):null,this.fd=null,this.blockLen=null,this.blockRemain=null,this.buf=null,this.offset=null,this.length=null,this.pos=null,this.remain=null,typeof t.onwarn==`function`&&this.on(`warn`,t.onwarn);let n=!1;if(!this.preservePaths){let[e,t]=M(this.path);e&&(this.path=t,n=e)}this.win32=!!t.win32||process.platform===`win32`,this.win32&&(this.path=j.decode(this.path.replace(/\\/g,`/`)),e=e.replace(/\\/g,`/`)),this.absolute=s(t.absolute||o.resolve(this.cwd,e)),this.path===``&&(this.path=`./`),n&&this.warn(`TAR_ENTRY_INFO`,`stripping ${n} from absolute path`,{entry:this,path:n+this.path}),this.statCache.has(this.absolute)?this[y](this.statCache.get(this.absolute)):this[v]()}emit(e,...t){return e===`error`&&(this[k]=!0),super.emit(e,...t)}[v](){a.lstat(this.absolute,(e,t)=>{if(e)return this.emit(`error`,e);this[y](t)})}[y](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=ee(e),this.emit(`stat`,e),this[d]()}[d](){switch(this.type){case`File`:return this[f]();case`Directory`:return this[p]();case`SymbolicLink`:return this[m]();default:return this.end()}}[T](e){return N(e,this.type===`Directory`,this.portable)}[O](e){return l(e,this.prefix)}[g](){this.type===`Directory`&&this.portable&&(this.noMtime=!0),this.header=new i({path:this[O](this.path),linkpath:this.type===`Link`?this[O](this.linkpath):this.linkpath,mode:this[T](this.stat.mode),uid:this.portable?null:this.stat.uid,gid:this.portable?null:this.stat.gid,size:this.stat.size,mtime:this.noMtime?null:this.mtime||this.stat.mtime,type:this.type,uname:this.portable?null:this.stat.uid===this.myuid?this.myuser:``,atime:this.portable?null:this.stat.atime,ctime:this.portable?null:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new r({atime:this.portable?null:this.header.atime,ctime:this.portable?null:this.header.ctime,gid:this.portable?null:this.header.gid,mtime:this.noMtime?null:this.mtime||this.header.mtime,path:this[O](this.path),linkpath:this.type===`Link`?this[O](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?null:this.header.uid,uname:this.portable?null:this.header.uname,dev:this.portable?null:this.stat.dev,ino:this.portable?null:this.stat.ino,nlink:this.portable?null:this.stat.nlink}).encode()),super.write(this.header.block)}[p](){this.path.slice(-1)!==`/`&&(this.path+=`/`),this.stat.size=0,this[g](),this.end()}[m](){a.readlink(this.absolute,(e,t)=>{if(e)return this.emit(`error`,e);this[x](t)})}[x](e){this.linkpath=s(e),this[g](),this.end()}[h](e){this.type=`Link`,this.linkpath=s(o.relative(this.cwd,e)),this.stat.size=0,this[g](),this.end()}[f](){if(this.stat.nlink>1){let e=this.stat.dev+`:`+this.stat.ino;if(this.linkCache.has(e)){let t=this.linkCache.get(e);if(t.indexOf(this.cwd)===0)return this[h](t)}this.linkCache.set(e,this.absolute)}if(this[g](),this.stat.size===0)return this.end();this[S]()}[S](){a.open(this.absolute,`r`,(e,t)=>{if(e)return this.emit(`error`,e);this[C](t)})}[C](e){if(this.fd=e,this[k])return this[w]();this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[_]()}[_](){let{fd:e,buf:t,offset:n,length:r,pos:i}=this;a.read(e,t,n,r,i,(e,t)=>{if(e)return this[w](()=>this.emit(`error`,e));this[b](t)})}[w](e){a.close(this.fd,e)}[b](e){if(e<=0&&this.remain>0){let e=Error(`encountered unexpected EOF`);return e.path=this.absolute,e.syscall=`read`,e.code=`EOF`,this[w](()=>this.emit(`error`,e))}if(e>this.remain){let e=Error(`did not encounter expected EOF`);return e.path=this.absolute,e.syscall=`read`,e.code=`EOF`,this[w](()=>this.emit(`error`,e))}if(e===this.remain)for(let t=e;t<this.length&&e<this.blockRemain;t++)this.buf[t+this.offset]=0,e++,this.remain++;let t=this.offset===0&&e===this.buf.length?this.buf:this.buf.slice(this.offset,this.offset+e);this.write(t)?this[D]():this[E](()=>this[D]())}[E](e){this.once(`drain`,e)}write(e){if(this.blockRemain<e.length){let e=Error(`writing more data than expected`);return e.path=this.absolute,this.emit(`error`,e)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e)}[D](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[w](e=>e?this.emit(`error`,e):this.end());this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[_]()}}),F=class extends P{[v](){this[y](a.lstatSync(this.absolute))}[m](){this[x](a.readlinkSync(this.absolute))}[S](){this[C](a.openSync(this.absolute,`r`))}[_](){let e=!0;try{let{fd:t,buf:n,offset:r,length:i,pos:o}=this,s=a.readSync(t,n,r,i,o);this[b](s),e=!1}finally{if(e)try{this[w](()=>{})}catch{}}}[E](e){e()}[w](e){a.closeSync(this.fd),e()}},I=A(class extends n{constructor(e,t){t||={},super(t),this.preservePaths=!!t.preservePaths,this.portable=!!t.portable,this.strict=!!t.strict,this.noPax=!!t.noPax,this.noMtime=!!t.noMtime,this.readEntry=e,this.type=e.type,this.type===`Directory`&&this.portable&&(this.noMtime=!0),this.prefix=t.prefix||null,this.path=s(e.path),this.mode=this[T](e.mode),this.uid=this.portable?null:e.uid,this.gid=this.portable?null:e.gid,this.uname=this.portable?null:e.uname,this.gname=this.portable?null:e.gname,this.size=e.size,this.mtime=this.noMtime?null:t.mtime||e.mtime,this.atime=this.portable?null:e.atime,this.ctime=this.portable?null:e.ctime,this.linkpath=s(e.linkpath),typeof t.onwarn==`function`&&this.on(`warn`,t.onwarn);let n=!1;if(!this.preservePaths){let[e,t]=M(this.path);e&&(this.path=t,n=e)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.header=new i({path:this[O](this.path),linkpath:this.type===`Link`?this[O](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?null:this.uid,gid:this.portable?null:this.gid,size:this.size,mtime:this.noMtime?null:this.mtime,type:this.type,uname:this.portable?null:this.uname,atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime}),n&&this.warn(`TAR_ENTRY_INFO`,`stripping ${n} from absolute path`,{entry:this,path:n+this.path}),this.header.encode()&&!this.noPax&&super.write(new r({atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime,gid:this.portable?null:this.gid,mtime:this.noMtime?null:this.mtime,path:this[O](this.path),linkpath:this.type===`Link`?this[O](this.linkpath):this.linkpath,size:this.size,uid:this.portable?null:this.uid,uname:this.portable?null:this.uname,dev:this.portable?null:this.readEntry.dev,ino:this.portable?null:this.readEntry.ino,nlink:this.portable?null:this.readEntry.nlink}).encode()),super.write(this.header.block),e.pipe(this)}[O](e){return l(e,this.prefix)}[T](e){return N(e,this.type===`Directory`,this.portable)}write(e){let t=e.length;if(t>this.blockRemain)throw Error(`writing more to entry than is appropriate`);return this.blockRemain-=t,super.write(e)}end(){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),super.end()}});P.Sync=F,P.Tar=I;var ee=e=>e.isFile()?`File`:e.isDirectory()?`Directory`:e.isSymbolicLink()?`SymbolicLink`:`Unsupported`;t.exports=P})),fy=L(((e,t)=>{t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}})),py=L(((e,t)=>{t.exports=n,n.Node=o,n.create=n;function n(e){var t=this;if(t instanceof n||(t=new n),t.tail=null,t.head=null,t.length=0,e&&typeof e.forEach==`function`)e.forEach(function(e){t.push(e)});else if(arguments.length>0)for(var r=0,i=arguments.length;r<i;r++)t.push(arguments[r]);return t}n.prototype.removeNode=function(e){if(e.list!==this)throw Error(`removing node which does not belong to this list`);var t=e.next,n=e.prev;return t&&(t.prev=n),n&&(n.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=n),e.list.length--,e.next=null,e.prev=null,e.list=null,t},n.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||=e,this.length++}},n.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||=e,this.length++}},n.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)i(this,arguments[e]);return this.length},n.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)a(this,arguments[e]);return this.length},n.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},n.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},n.prototype.forEach=function(e,t){t||=this;for(var n=this.head,r=0;n!==null;r++)e.call(t,n.value,r,this),n=n.next},n.prototype.forEachReverse=function(e,t){t||=this;for(var n=this.tail,r=this.length-1;n!==null;r--)e.call(t,n.value,r,this),n=n.prev},n.prototype.get=function(e){for(var t=0,n=this.head;n!==null&&t<e;t++)n=n.next;if(t===e&&n!==null)return n.value},n.prototype.getReverse=function(e){for(var t=0,n=this.tail;n!==null&&t<e;t++)n=n.prev;if(t===e&&n!==null)return n.value},n.prototype.map=function(e,t){t||=this;for(var r=new n,i=this.head;i!==null;)r.push(e.call(t,i.value,this)),i=i.next;return r},n.prototype.mapReverse=function(e,t){t||=this;for(var r=new n,i=this.tail;i!==null;)r.push(e.call(t,i.value,this)),i=i.prev;return r},n.prototype.reduce=function(e,t){var n,r=this.head;if(arguments.length>1)n=t;else if(this.head)r=this.head.next,n=this.head.value;else throw TypeError(`Reduce of empty list with no initial value`);for(var i=0;r!==null;i++)n=e(n,r.value,i),r=r.next;return n},n.prototype.reduceReverse=function(e,t){var n,r=this.tail;if(arguments.length>1)n=t;else if(this.tail)r=this.tail.prev,n=this.tail.value;else throw TypeError(`Reduce of empty list with no initial value`);for(var i=this.length-1;r!==null;i--)n=e(n,r.value,i),r=r.prev;return n},n.prototype.toArray=function(){for(var e=Array(this.length),t=0,n=this.head;n!==null;t++)e[t]=n.value,n=n.next;return e},n.prototype.toArrayReverse=function(){for(var e=Array(this.length),t=0,n=this.tail;n!==null;t++)e[t]=n.value,n=n.prev;return e},n.prototype.slice=function(e,t){t||=this.length,t<0&&(t+=this.length),e||=0,e<0&&(e+=this.length);var r=new n;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var i=0,a=this.head;a!==null&&i<e;i++)a=a.next;for(;a!==null&&i<t;i++,a=a.next)r.push(a.value);return r},n.prototype.sliceReverse=function(e,t){t||=this.length,t<0&&(t+=this.length),e||=0,e<0&&(e+=this.length);var r=new n;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var i=this.length,a=this.tail;a!==null&&i>t;i--)a=a.prev;for(;a!==null&&i>e;i--,a=a.prev)r.push(a.value);return r},n.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var i=0,a=this.head;a!==null&&i<e;i++)a=a.next;for(var o=[],i=0;a&&i<t;i++)o.push(a.value),a=this.removeNode(a);a===null&&(a=this.tail),a!==this.head&&a!==this.tail&&(a=a.prev);for(var i=0;i<n.length;i++)a=r(this,a,n[i]);return o},n.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;n!==null;n=n.prev){var r=n.prev;n.prev=n.next,n.next=r}return this.head=t,this.tail=e,this};function r(e,t,n){var r=t===e.head?new o(n,null,t,e):new o(n,t,t.next,e);return r.next===null&&(e.tail=r),r.prev===null&&(e.head=r),e.length++,r}function i(e,t){e.tail=new o(t,e.tail,null,e),e.head||=e.tail,e.length++}function a(e,t){e.head=new o(t,null,e.head,e),e.tail||=e.head,e.length++}function o(e,t,n,r){if(!(this instanceof o))return new o(e,t,n,r);this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,n?(n.prev=this,this.next=n):this.next=null}try{fy()(n)}catch{}})),my=L(((e,t)=>{var n=class{constructor(e,t){this.path=e||`./`,this.absolute=t,this.entry=null,this.stat=null,this.readdir=null,this.pending=!1,this.ignore=!1,this.piped=!1}},{Minipass:r}=Xv(),i=$v(),a=ty(),o=dy(),s=o.Sync,c=o.Tar,l=py(),u=Buffer.alloc(1024),d=Symbol(`onStat`),f=Symbol(`ended`),p=Symbol(`queue`),m=Symbol(`current`),h=Symbol(`process`),g=Symbol(`processing`),_=Symbol(`processJob`),v=Symbol(`jobs`),y=Symbol(`jobDone`),b=Symbol(`addFSEntry`),x=Symbol(`addTarEntry`),S=Symbol(`stat`),C=Symbol(`readdir`),w=Symbol(`onreaddir`),T=Symbol(`pipe`),E=Symbol(`entry`),D=Symbol(`entryOpt`),O=Symbol(`writeEntryClass`),k=Symbol(`write`),A=Symbol(`ondrain`),j=R(`fs`),M=R(`path`),N=sy(),P=ey(),F=N(class extends r{constructor(e){if(super(e),e||=Object.create(null),this.opt=e,this.file=e.file||``,this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=P(e.prefix||``),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this[O]=o,typeof e.onwarn==`function`&&this.on(`warn`,e.onwarn),this.portable=!!e.portable,this.zip=null,e.gzip||e.brotli){if(e.gzip&&e.brotli)throw TypeError(`gzip and brotli are mutually exclusive`);e.gzip&&(typeof e.gzip!=`object`&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new i.Gzip(e.gzip)),e.brotli&&(typeof e.brotli!=`object`&&(e.brotli={}),this.zip=new i.BrotliCompress(e.brotli)),this.zip.on(`data`,e=>super.write(e)),this.zip.on(`end`,e=>super.end()),this.zip.on(`drain`,e=>this[A]()),this.on(`resume`,e=>this.zip.resume())}else this.on(`drain`,this[A]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,this.mtime=e.mtime||null,this.filter=typeof e.filter==`function`?e.filter:e=>!0,this[p]=new l,this[v]=0,this.jobs=+e.jobs||4,this[g]=!1,this[f]=!1}[k](e){return super.write(e)}add(e){return this.write(e),this}end(e){return e&&this.write(e),this[f]=!0,this[h](),this}write(e){if(this[f])throw Error(`write after end`);return e instanceof a?this[x](e):this[b](e),this.flowing}[x](e){let t=P(M.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new n(e.path,t,!1);r.entry=new c(e,this[D](r)),r.entry.on(`end`,e=>this[y](r)),this[v]+=1,this[p].push(r)}this[h]()}[b](e){let t=P(M.resolve(this.cwd,e));this[p].push(new n(e,t)),this[h]()}[S](e){e.pending=!0,this[v]+=1,j[this.follow?`stat`:`lstat`](e.absolute,(t,n)=>{e.pending=!1,--this[v],t?this.emit(`error`,t):this[d](e,n)})}[d](e,t){this.statCache.set(e.absolute,t),e.stat=t,this.filter(e.path,t)||(e.ignore=!0),this[h]()}[C](e){e.pending=!0,this[v]+=1,j.readdir(e.absolute,(t,n)=>{if(e.pending=!1,--this[v],t)return this.emit(`error`,t);this[w](e,n)})}[w](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[h]()}[h](){if(!this[g]){this[g]=!0;for(let e=this[p].head;e!==null&&this[v]<this.jobs;e=e.next)if(this[_](e.value),e.value.ignore){let t=e.next;this[p].removeNode(e),e.next=t}this[g]=!1,this[f]&&!this[p].length&&this[v]===0&&(this.zip?this.zip.end(u):(super.write(u),super.end()))}}get[m](){return this[p]&&this[p].head&&this[p].head.value}[y](e){this[p].shift(),--this[v],this[h]()}[_](e){if(!e.pending){if(e.entry){e===this[m]&&!e.piped&&this[T](e);return}if(e.stat||(this.statCache.has(e.absolute)?this[d](e,this.statCache.get(e.absolute)):this[S](e)),e.stat&&!e.ignore&&!(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir&&(this.readdirCache.has(e.absolute)?this[w](e,this.readdirCache.get(e.absolute)):this[C](e),!e.readdir))){if(e.entry=this[E](e),!e.entry){e.ignore=!0;return}e===this[m]&&!e.piped&&this[T](e)}}}[D](e){return{onwarn:(e,t,n)=>this.warn(e,t,n),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix}}[E](e){this[v]+=1;try{return new this[O](e.path,this[D](e)).on(`end`,()=>this[y](e)).on(`error`,e=>this.emit(`error`,e))}catch(e){this.emit(`error`,e)}}[A](){this[m]&&this[m].entry&&this[m].entry.resume()}[T](e){e.piped=!0,e.readdir&&e.readdir.forEach(t=>{let n=e.path,r=n===`./`?``:n.replace(/\/*$/,`/`);this[b](r+t)});let t=e.entry,n=this.zip;n?t.on(`data`,e=>{n.write(e)||t.pause()}):t.on(`data`,e=>{super.write(e)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}});F.Sync=class extends F{constructor(e){super(e),this[O]=s}pause(){}resume(){}[S](e){let t=this.follow?`statSync`:`lstatSync`;this[d](e,j[t](e.absolute))}[C](e,t){this[w](e,j.readdirSync(e.absolute))}[T](e){let t=e.entry,n=this.zip;e.readdir&&e.readdir.forEach(t=>{let n=e.path,r=n===`./`?``:n.replace(/\/*$/,`/`);this[b](r+t)}),n?t.on(`data`,e=>{n.write(e)}):t.on(`data`,e=>{super[k](e)})}},t.exports=F})),hy=L((e=>{var t=Qv(),n=R(`events`).EventEmitter,r=R(`fs`),i=r.writev;if(!i){let e=process.binding(`fs`),t=e.FSReqWrap||e.FSReqCallback;i=(n,r,i,a)=>{let o=(e,t)=>a(e,t,r),s=new t;s.oncomplete=o,e.writeBuffers(n,r,i,s)}}var a=Symbol(`_autoClose`),o=Symbol(`_close`),s=Symbol(`_ended`),c=Symbol(`_fd`),l=Symbol(`_finished`),u=Symbol(`_flags`),d=Symbol(`_flush`),f=Symbol(`_handleChunk`),p=Symbol(`_makeBuf`),m=Symbol(`_mode`),h=Symbol(`_needDrain`),g=Symbol(`_onerror`),_=Symbol(`_onopen`),v=Symbol(`_onread`),y=Symbol(`_onwrite`),b=Symbol(`_open`),x=Symbol(`_path`),S=Symbol(`_pos`),C=Symbol(`_queue`),w=Symbol(`_read`),T=Symbol(`_readSize`),E=Symbol(`_reading`),D=Symbol(`_remain`),O=Symbol(`_size`),k=Symbol(`_write`),A=Symbol(`_writing`),j=Symbol(`_defaultFlag`),M=Symbol(`_errored`),N=class extends t{constructor(e,t){if(t||={},super(t),this.readable=!0,this.writable=!1,typeof e!=`string`)throw TypeError(`path must be a string`);this[M]=!1,this[c]=typeof t.fd==`number`?t.fd:null,this[x]=e,this[T]=t.readSize||16777216,this[E]=!1,this[O]=typeof t.size==`number`?t.size:1/0,this[D]=this[O],this[a]=typeof t.autoClose!=`boolean`||t.autoClose,typeof this[c]==`number`?this[w]():this[b]()}get fd(){return this[c]}get path(){return this[x]}write(){throw TypeError(`this is a readable stream`)}end(){throw TypeError(`this is a readable stream`)}[b](){r.open(this[x],`r`,(e,t)=>this[_](e,t))}[_](e,t){e?this[g](e):(this[c]=t,this.emit(`open`,t),this[w]())}[p](){return Buffer.allocUnsafe(Math.min(this[T],this[D]))}[w](){if(!this[E]){this[E]=!0;let e=this[p]();if(e.length===0)return process.nextTick(()=>this[v](null,0,e));r.read(this[c],e,0,e.length,null,(e,t,n)=>this[v](e,t,n))}}[v](e,t,n){this[E]=!1,e?this[g](e):this[f](t,n)&&this[w]()}[o](){if(this[a]&&typeof this[c]==`number`){let e=this[c];this[c]=null,r.close(e,e=>e?this.emit(`error`,e):this.emit(`close`))}}[g](e){this[E]=!0,this[o](),this.emit(`error`,e)}[f](e,t){let n=!1;return this[D]-=e,e>0&&(n=super.write(e<t.length?t.slice(0,e):t)),(e===0||this[D]<=0)&&(n=!1,this[o](),super.end()),n}emit(e,t){switch(e){case`prefinish`:case`finish`:break;case`drain`:typeof this[c]==`number`&&this[w]();break;case`error`:return this[M]?void 0:(this[M]=!0,super.emit(e,t));default:return super.emit(e,t)}}},P=class extends N{[b](){let e=!0;try{this[_](null,r.openSync(this[x],`r`)),e=!1}finally{e&&this[o]()}}[w](){let e=!0;try{if(!this[E]){this[E]=!0;do{let e=this[p](),t=e.length===0?0:r.readSync(this[c],e,0,e.length,null);if(!this[f](t,e))break}while(1);this[E]=!1}e=!1}finally{e&&this[o]()}}[o](){if(this[a]&&typeof this[c]==`number`){let e=this[c];this[c]=null,r.closeSync(e),this.emit(`close`)}}},F=class extends n{constructor(e,t){t||={},super(t),this.readable=!1,this.writable=!0,this[M]=!1,this[A]=!1,this[s]=!1,this[h]=!1,this[C]=[],this[x]=e,this[c]=typeof t.fd==`number`?t.fd:null,this[m]=t.mode===void 0?438:t.mode,this[S]=typeof t.start==`number`?t.start:null,this[a]=typeof t.autoClose!=`boolean`||t.autoClose;let n=this[S]===null?`w`:`r+`;this[j]=t.flags===void 0,this[u]=this[j]?n:t.flags,this[c]===null&&this[b]()}emit(e,t){if(e===`error`){if(this[M])return;this[M]=!0}return super.emit(e,t)}get fd(){return this[c]}get path(){return this[x]}[g](e){this[o](),this[A]=!0,this.emit(`error`,e)}[b](){r.open(this[x],this[u],this[m],(e,t)=>this[_](e,t))}[_](e,t){this[j]&&this[u]===`r+`&&e&&e.code===`ENOENT`?(this[u]=`w`,this[b]()):e?this[g](e):(this[c]=t,this.emit(`open`,t),this[d]())}end(e,t){return e&&this.write(e,t),this[s]=!0,!this[A]&&!this[C].length&&typeof this[c]==`number`&&this[y](null,0),this}write(e,t){return typeof e==`string`&&(e=Buffer.from(e,t)),this[s]?(this.emit(`error`,Error(`write() after end()`)),!1):this[c]===null||this[A]||this[C].length?(this[C].push(e),this[h]=!0,!1):(this[A]=!0,this[k](e),!0)}[k](e){r.write(this[c],e,0,e.length,this[S],(e,t)=>this[y](e,t))}[y](e,t){e?this[g](e):(this[S]!==null&&(this[S]+=t),this[C].length?this[d]():(this[A]=!1,this[s]&&!this[l]?(this[l]=!0,this[o](),this.emit(`finish`)):this[h]&&(this[h]=!1,this.emit(`drain`))))}[d](){if(this[C].length===0)this[s]&&this[y](null,0);else if(this[C].length===1)this[k](this[C].pop());else{let e=this[C];this[C]=[],i(this[c],e,this[S],(e,t)=>this[y](e,t))}}[o](){if(this[a]&&typeof this[c]==`number`){let e=this[c];this[c]=null,r.close(e,e=>e?this.emit(`error`,e):this.emit(`close`))}}},I=class extends F{[b](){let e;if(this[j]&&this[u]===`r+`)try{e=r.openSync(this[x],this[u],this[m])}catch(e){if(e.code===`ENOENT`)return this[u]=`w`,this[b]();throw e}else e=r.openSync(this[x],this[u],this[m]);this[_](null,e)}[o](){if(this[a]&&typeof this[c]==`number`){let e=this[c];this[c]=null,r.closeSync(e),this.emit(`close`)}}[k](e){let t=!0;try{this[y](null,r.writeSync(this[c],e,0,e.length,this[S])),t=!1}finally{if(t)try{this[o]()}catch{}}}};e.ReadStream=N,e.ReadStreamSync=P,e.WriteStream=F,e.WriteStreamSync=I})),gy=L(((e,t)=>{var n=sy(),r=iy(),i=R(`events`),a=py(),o=1048576,s=ty(),c=ay(),l=$v(),{nextTick:u}=R(`process`),d=Buffer.from([31,139]),f=Symbol(`state`),p=Symbol(`writeEntry`),m=Symbol(`readEntry`),h=Symbol(`nextEntry`),g=Symbol(`processEntry`),_=Symbol(`extendedHeader`),v=Symbol(`globalExtendedHeader`),y=Symbol(`meta`),b=Symbol(`emitMeta`),x=Symbol(`buffer`),S=Symbol(`queue`),C=Symbol(`ended`),w=Symbol(`emittedEnd`),T=Symbol(`emit`),E=Symbol(`unzip`),D=Symbol(`consumeChunk`),O=Symbol(`consumeChunkSub`),k=Symbol(`consumeBody`),A=Symbol(`consumeMeta`),j=Symbol(`consumeHeader`),M=Symbol(`consuming`),N=Symbol(`bufferConcat`),P=Symbol(`maybeEnd`),F=Symbol(`writing`),I=Symbol(`aborted`),ee=Symbol(`onDone`),te=Symbol(`sawValidEntry`),ne=Symbol(`sawNullBlock`),re=Symbol(`sawEOF`),ie=Symbol(`closeStream`),ae=e=>!0;t.exports=n(class extends i{constructor(e){e||={},super(e),this.file=e.file||``,this[te]=null,this.on(ee,e=>{(this[f]===`begin`||this[te]===!1)&&this.warn(`TAR_BAD_ARCHIVE`,`Unrecognized archive format`)}),e.ondone?this.on(ee,e.ondone):this.on(ee,e=>{this.emit(`prefinish`),this.emit(`finish`),this.emit(`end`)}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||o,this.filter=typeof e.filter==`function`?e.filter:ae;let t=e.file&&(e.file.endsWith(`.tar.br`)||e.file.endsWith(`.tbr`));this.brotli=!e.gzip&&e.brotli!==void 0?e.brotli:t?void 0:!1,this.writable=!0,this.readable=!1,this[S]=new a,this[x]=null,this[m]=null,this[p]=null,this[f]=`begin`,this[y]=``,this[_]=null,this[v]=null,this[C]=!1,this[E]=null,this[I]=!1,this[ne]=!1,this[re]=!1,this.on(`end`,()=>this[ie]()),typeof e.onwarn==`function`&&this.on(`warn`,e.onwarn),typeof e.onentry==`function`&&this.on(`entry`,e.onentry)}[j](e,t){this[te]===null&&(this[te]=!1);let n;try{n=new r(e,t,this[_],this[v])}catch(e){return this.warn(`TAR_ENTRY_INVALID`,e)}if(n.nullBlock)this[ne]?(this[re]=!0,this[f]===`begin`&&(this[f]=`header`),this[T](`eof`)):(this[ne]=!0,this[T](`nullBlock`));else if(this[ne]=!1,!n.cksumValid)this.warn(`TAR_ENTRY_INVALID`,`checksum failure`,{header:n});else if(!n.path)this.warn(`TAR_ENTRY_INVALID`,`path is required`,{header:n});else{let e=n.type;if(/^(Symbolic)?Link$/.test(e)&&!n.linkpath)this.warn(`TAR_ENTRY_INVALID`,`linkpath required`,{header:n});else if(!/^(Symbolic)?Link$/.test(e)&&n.linkpath)this.warn(`TAR_ENTRY_INVALID`,`linkpath forbidden`,{header:n});else{let e=this[p]=new s(n,this[_],this[v]);this[te]||(e.remain?e.on(`end`,()=>{e.invalid||(this[te]=!0)}):this[te]=!0),e.meta?e.size>this.maxMetaEntrySize?(e.ignore=!0,this[T](`ignoredEntry`,e),this[f]=`ignore`,e.resume()):e.size>0&&(this[y]=``,e.on(`data`,e=>this[y]+=e),this[f]=`meta`):(this[_]=null,e.ignore=e.ignore||!this.filter(e.path,e),e.ignore?(this[T](`ignoredEntry`,e),this[f]=e.remain?`ignore`:`header`,e.resume()):(e.remain?this[f]=`body`:(this[f]=`header`,e.end()),this[m]?this[S].push(e):(this[S].push(e),this[h]())))}}}[ie](){u(()=>this.emit(`close`))}[g](e){let t=!0;return e?Array.isArray(e)?this.emit.apply(this,e):(this[m]=e,this.emit(`entry`,e),e.emittedEnd||(e.on(`end`,e=>this[h]()),t=!1)):(this[m]=null,t=!1),t}[h](){do;while(this[g](this[S].shift()));if(!this[S].length){let e=this[m];!e||e.flowing||e.size===e.remain?this[F]||this.emit(`drain`):e.once(`drain`,e=>this.emit(`drain`))}}[k](e,t){let n=this[p],r=n.blockRemain,i=r>=e.length&&t===0?e:e.slice(t,t+r);return n.write(i),n.blockRemain||(this[f]=`header`,this[p]=null,n.end()),i.length}[A](e,t){let n=this[p],r=this[k](e,t);return this[p]||this[b](n),r}[T](e,t,n){!this[S].length&&!this[m]?this.emit(e,t,n):this[S].push([e,t,n])}[b](e){switch(this[T](`meta`,this[y]),e.type){case`ExtendedHeader`:case`OldExtendedHeader`:this[_]=c.parse(this[y],this[_],!1);break;case`GlobalExtendedHeader`:this[v]=c.parse(this[y],this[v],!0);break;case`NextFileHasLongPath`:case`OldGnuLongPath`:this[_]=this[_]||Object.create(null),this[_].path=this[y].replace(/\0.*/,``);break;case`NextFileHasLongLinkpath`:this[_]=this[_]||Object.create(null),this[_].linkpath=this[y].replace(/\0.*/,``);break;default:throw Error(`unknown meta: `+e.type)}}abort(e){this[I]=!0,this.emit(`abort`,e),this.warn(`TAR_ABORT`,e,{recoverable:!1})}write(e){if(this[I])return;if((this[E]===null||this.brotli===void 0&&this[E]===!1)&&e){if(this[x]&&(e=Buffer.concat([this[x],e]),this[x]=null),e.length<d.length)return this[x]=e,!0;for(let t=0;this[E]===null&&t<d.length;t++)e[t]!==d[t]&&(this[E]=!1);let t=this.brotli===void 0;if(this[E]===!1&&t){if(e.length<512){if(this[C])this.brotli=!0;else return this[x]=e,!0}else try{new r(e.slice(0,512)),this.brotli=!1}catch{this.brotli=!0}}if(this[E]===null||this[E]===!1&&this.brotli){let t=this[C];this[C]=!1,this[E]=this[E]===null?new l.Unzip:new l.BrotliDecompress,this[E].on(`data`,e=>this[D](e)),this[E].on(`error`,e=>this.abort(e)),this[E].on(`end`,e=>{this[C]=!0,this[D]()}),this[F]=!0;let n=this[E][t?`end`:`write`](e);return this[F]=!1,n}}this[F]=!0,this[E]?this[E].write(e):this[D](e),this[F]=!1;let t=this[S].length?!1:!this[m]||this[m].flowing;return!t&&!this[S].length&&this[m].once(`drain`,e=>this.emit(`drain`)),t}[N](e){e&&!this[I]&&(this[x]=this[x]?Buffer.concat([this[x],e]):e)}[P](){if(this[C]&&!this[w]&&!this[I]&&!this[M]){this[w]=!0;let e=this[p];if(e&&e.blockRemain){let t=this[x]?this[x].length:0;this.warn(`TAR_BAD_ARCHIVE`,`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[x]&&e.write(this[x]),e.end()}this[T](ee)}}[D](e){if(this[M])this[N](e);else if(!e&&!this[x])this[P]();else{if(this[M]=!0,this[x]){this[N](e);let t=this[x];this[x]=null,this[O](t)}else this[O](e);for(;this[x]&&this[x].length>=512&&!this[I]&&!this[re];){let e=this[x];this[x]=null,this[O](e)}this[M]=!1}(!this[x]||this[C])&&this[P]()}[O](e){let t=0,n=e.length;for(;t+512<=n&&!this[I]&&!this[re];)switch(this[f]){case`begin`:case`header`:this[j](e,t),t+=512;break;case`ignore`:case`body`:t+=this[k](e,t);break;case`meta`:t+=this[A](e,t);break;default:throw Error(`invalid state: `+this[f])}t<n&&(this[x]=this[x]?Buffer.concat([e.slice(t),this[x]]):e.slice(t))}end(e){this[I]||(this[E]?this[E].end(e):(this[C]=!0,this.brotli===void 0&&(e||=Buffer.alloc(0)),this.write(e)))}})})),_y=L(((e,t)=>{var n=Yv(),r=gy(),i=R(`fs`),a=hy(),o=R(`path`),s=oy();t.exports=(e,t,r)=>{typeof e==`function`?(r=e,t=null,e={}):Array.isArray(e)&&(t=e,e={}),typeof t==`function`&&(r=t,t=null),t=t?Array.from(t):[];let i=n(e);if(i.sync&&typeof r==`function`)throw TypeError(`callback not supported for sync tar functions`);if(!i.file&&typeof r==`function`)throw TypeError(`callback only supported with file option`);return t.length&&l(i,t),i.noResume||c(i),i.file&&i.sync?u(i):i.file?d(i,r):f(i)};var c=e=>{let t=e.onentry;e.onentry=t?e=>{t(e),e.resume()}:e=>e.resume()},l=(e,t)=>{let n=new Map(t.map(e=>[s(e),!0])),r=e.filter,i=(e,t)=>{let r=t||o.parse(e).root||`.`,a=e===r?!1:n.has(e)?n.get(e):i(o.dirname(e),r);return n.set(e,a),a};e.filter=r?(e,t)=>r(e,t)&&i(s(e)):e=>i(s(e))},u=e=>{let t=f(e),n=e.file,r=!0,a;try{let o=i.statSync(n),s=e.maxReadSize||16777216;if(o.size<s)t.end(i.readFileSync(n));else{let e=0,r=Buffer.allocUnsafe(s);for(a=i.openSync(n,`r`);e<o.size;){let n=i.readSync(a,r,0,s,e);e+=n,t.write(r.slice(0,n))}t.end()}r=!1}finally{if(r&&a)try{i.closeSync(a)}catch{}}},d=(e,t)=>{let n=new r(e),o=e.maxReadSize||16777216,s=e.file,c=new Promise((e,t)=>{n.on(`error`,t),n.on(`end`,e),i.stat(s,(e,r)=>{if(e)t(e);else{let e=new a.ReadStream(s,{readSize:o,size:r.size});e.on(`error`,t),e.pipe(n)}})});return t?c.then(t,t):c},f=e=>new r(e)})),vy=L(((e,t)=>{var n=Yv(),r=my(),i=hy(),a=_y(),o=R(`path`);t.exports=(e,t,r)=>{if(typeof t==`function`&&(r=t),Array.isArray(e)&&(t=e,e={}),!t||!Array.isArray(t)||!t.length)throw TypeError(`no files or directories specified`);t=Array.from(t);let i=n(e);if(i.sync&&typeof r==`function`)throw TypeError(`callback not supported for sync tar functions`);if(!i.file&&typeof r==`function`)throw TypeError(`callback only supported with file option`);return i.file&&i.sync?s(i,t):i.file?c(i,t,r):i.sync?d(i,t):f(i,t)};var s=(e,t)=>{let n=new r.Sync(e),a=new i.WriteStreamSync(e.file,{mode:e.mode||438});n.pipe(a),l(n,t)},c=(e,t,n)=>{let a=new r(e),o=new i.WriteStream(e.file,{mode:e.mode||438});a.pipe(o);let s=new Promise((e,t)=>{o.on(`error`,t),o.on(`close`,e),a.on(`error`,t)});return u(a,t),n?s.then(n,n):s},l=(e,t)=>{t.forEach(t=>{t.charAt(0)===`@`?a({file:o.resolve(e.cwd,t.slice(1)),sync:!0,noResume:!0,onentry:t=>e.add(t)}):e.add(t)}),e.end()},u=(e,t)=>{for(;t.length;){let n=t.shift();if(n.charAt(0)===`@`)return a({file:o.resolve(e.cwd,n.slice(1)),noResume:!0,onentry:t=>e.add(t)}).then(n=>u(e,t));e.add(n)}e.end()},d=(e,t)=>{let n=new r.Sync(e);return l(n,t),n},f=(e,t)=>{let n=new r(e);return u(n,t),n}})),yy=L(((e,t)=>{var n=Yv(),r=my(),i=R(`fs`),a=hy(),o=_y(),s=R(`path`),c=iy();t.exports=(e,t,r)=>{let i=n(e);if(!i.file)throw TypeError(`file is required`);if(i.gzip||i.brotli||i.file.endsWith(`.br`)||i.file.endsWith(`.tbr`))throw TypeError(`cannot append to compressed archives`);if(!t||!Array.isArray(t)||!t.length)throw TypeError(`no files or directories specified`);return t=Array.from(t),i.sync?l(i,t):d(i,t,r)};var l=(e,t)=>{let n=new r.Sync(e),a=!0,o,s;try{try{o=i.openSync(e.file,`r+`)}catch(t){if(t.code===`ENOENT`)o=i.openSync(e.file,`w+`);else throw t}let r=i.fstatSync(o),l=Buffer.alloc(512);POSITION:for(s=0;s<r.size;s+=512){for(let e=0,t=0;e<512;e+=t){if(t=i.readSync(o,l,e,l.length-e,s+e),s===0&&l[0]===31&&l[1]===139)throw Error(`cannot append to compressed archives`);if(!t)break POSITION}let t=new c(l);if(!t.cksumValid)break;let n=512*Math.ceil(t.size/512);if(s+n+512>r.size)break;s+=n,e.mtimeCache&&e.mtimeCache.set(t.path,t.mtime)}a=!1,u(e,n,s,o,t)}finally{if(a)try{i.closeSync(o)}catch{}}},u=(e,t,n,r,i)=>{let o=new a.WriteStreamSync(e.file,{fd:r,start:n});t.pipe(o),f(t,i)},d=(e,t,n)=>{t=Array.from(t);let o=new r(e),s=(t,n,r)=>{let a=(e,n)=>{e?i.close(t,t=>r(e)):r(null,n)},o=0;if(n===0)return a(null,0);let s=0,l=Buffer.alloc(512),u=(r,d)=>{if(r)return a(r);if(s+=d,s<512&&d)return i.read(t,l,s,l.length-s,o+s,u);if(o===0&&l[0]===31&&l[1]===139)return a(Error(`cannot append to compressed archives`));if(s<512)return a(null,o);let f=new c(l);if(!f.cksumValid)return a(null,o);let p=512*Math.ceil(f.size/512);if(o+p+512>n||(o+=p+512,o>=n))return a(null,o);e.mtimeCache&&e.mtimeCache.set(f.path,f.mtime),s=0,i.read(t,l,0,512,o,u)};i.read(t,l,0,512,o,u)},l=new Promise((n,r)=>{o.on(`error`,r);let c=`r+`,l=(u,d)=>{if(u&&u.code===`ENOENT`&&c===`r+`)return c=`w+`,i.open(e.file,c,l);if(u)return r(u);i.fstat(d,(c,l)=>{if(c)return i.close(d,()=>r(c));s(d,l.size,(i,s)=>{if(i)return r(i);let c=new a.WriteStream(e.file,{fd:d,start:s});o.pipe(c),c.on(`error`,r),c.on(`close`,n),p(o,t)})})};i.open(e.file,c,l)});return n?l.then(n,n):l},f=(e,t)=>{t.forEach(t=>{t.charAt(0)===`@`?o({file:s.resolve(e.cwd,t.slice(1)),sync:!0,noResume:!0,onentry:t=>e.add(t)}):e.add(t)}),e.end()},p=(e,t)=>{for(;t.length;){let n=t.shift();if(n.charAt(0)===`@`)return o({file:s.resolve(e.cwd,n.slice(1)),noResume:!0,onentry:t=>e.add(t)}).then(n=>p(e,t));e.add(n)}e.end()}})),by=L(((e,t)=>{var n=Yv(),r=yy();t.exports=(e,t,a)=>{let o=n(e);if(!o.file)throw TypeError(`file is required`);if(o.gzip||o.brotli||o.file.endsWith(`.br`)||o.file.endsWith(`.tbr`))throw TypeError(`cannot append to compressed archives`);if(!t||!Array.isArray(t)||!t.length)throw TypeError(`no files or directories specified`);return t=Array.from(t),i(o),r(o,t,a)};var i=e=>{let t=e.filter;e.mtimeCache||=new Map,e.filter=t?(n,r)=>t(n,r)&&!(e.mtimeCache.get(n)>r.mtime):(t,n)=>!(e.mtimeCache.get(t)>n.mtime)}})),xy=L(((e,t)=>{var{promisify:n}=R(`util`),r=R(`fs`);t.exports=e=>{if(!e)e={mode:511,fs:r};else if(typeof e==`object`)e={mode:511,fs:r,...e};else if(typeof e==`number`)e={mode:e,fs:r};else if(typeof e==`string`)e={mode:parseInt(e,8),fs:r};else throw TypeError(`invalid options argument`);return e.mkdir=e.mkdir||e.fs.mkdir||r.mkdir,e.mkdirAsync=n(e.mkdir),e.stat=e.stat||e.fs.stat||r.stat,e.statAsync=n(e.stat),e.statSync=e.statSync||e.fs.statSync||r.statSync,e.mkdirSync=e.mkdirSync||e.fs.mkdirSync||r.mkdirSync,e}})),Sy=L(((e,t)=>{var n=process.env.__TESTING_MKDIRP_PLATFORM__||process.platform,{resolve:r,parse:i}=R(`path`);t.exports=e=>{if(/\0/.test(e))throw Object.assign(TypeError(`path must be a string without null bytes`),{path:e,code:`ERR_INVALID_ARG_VALUE`});if(e=r(e),n===`win32`){let t=/[*|"<>?:]/,{root:n}=i(e);if(t.test(e.substr(n.length)))throw Object.assign(Error(`Illegal characters in path.`),{path:e,code:`EINVAL`})}return e}})),Cy=L(((e,t)=>{var{dirname:n}=R(`path`),r=(e,t,i=void 0)=>i===t?Promise.resolve():e.statAsync(t).then(e=>e.isDirectory()?i:void 0,i=>i.code===`ENOENT`?r(e,n(t),t):void 0),i=(e,t,r=void 0)=>{if(r!==t)try{return e.statSync(t).isDirectory()?r:void 0}catch(r){return r.code===`ENOENT`?i(e,n(t),t):void 0}};t.exports={findMade:r,findMadeSync:i}})),wy=L(((e,t)=>{var{dirname:n}=R(`path`),r=(e,t,i)=>{t.recursive=!1;let a=n(e);return a===e?t.mkdirAsync(e,t).catch(e=>{if(e.code!==`EISDIR`)throw e}):t.mkdirAsync(e,t).then(()=>i||e,n=>{if(n.code===`ENOENT`)return r(a,t).then(n=>r(e,t,n));if(n.code!==`EEXIST`&&n.code!==`EROFS`)throw n;return t.statAsync(e).then(e=>{if(e.isDirectory())return i;throw n},()=>{throw n})})},i=(e,t,r)=>{let a=n(e);if(t.recursive=!1,a===e)try{return t.mkdirSync(e,t)}catch(e){if(e.code!==`EISDIR`)throw e;return}try{return t.mkdirSync(e,t),r||e}catch(n){if(n.code===`ENOENT`)return i(e,t,i(a,t,r));if(n.code!==`EEXIST`&&n.code!==`EROFS`)throw n;try{if(!t.statSync(e).isDirectory())throw n}catch{throw n}}};t.exports={mkdirpManual:r,mkdirpManualSync:i}})),Ty=L(((e,t)=>{var{dirname:n}=R(`path`),{findMade:r,findMadeSync:i}=Cy(),{mkdirpManual:a,mkdirpManualSync:o}=wy();t.exports={mkdirpNative:(e,t)=>(t.recursive=!0,n(e)===e?t.mkdirAsync(e,t):r(t,e).then(n=>t.mkdirAsync(e,t).then(()=>n).catch(n=>{if(n.code===`ENOENT`)return a(e,t);throw n}))),mkdirpNativeSync:(e,t)=>{if(t.recursive=!0,n(e)===e)return t.mkdirSync(e,t);let r=i(t,e);try{return t.mkdirSync(e,t),r}catch(n){if(n.code===`ENOENT`)return o(e,t);throw n}}}})),Ey=L(((e,t)=>{var n=R(`fs`),r=(process.env.__TESTING_MKDIRP_NODE_VERSION__||process.version).replace(/^v/,``).split(`.`),i=+r[0]>10||+r[0]==10&&+r[1]>=12;t.exports={useNative:i?e=>e.mkdir===n.mkdir:()=>!1,useNativeSync:i?e=>e.mkdirSync===n.mkdirSync:()=>!1}})),Dy=L(((e,t)=>{var n=xy(),r=Sy(),{mkdirpNative:i,mkdirpNativeSync:a}=Ty(),{mkdirpManual:o,mkdirpManualSync:s}=wy(),{useNative:c,useNativeSync:l}=Ey(),u=(e,t)=>(e=r(e),t=n(t),c(t)?i(e,t):o(e,t));u.sync=(e,t)=>(e=r(e),t=n(t),l(t)?a(e,t):s(e,t)),u.native=(e,t)=>i(r(e),n(t)),u.manual=(e,t)=>o(r(e),n(t)),u.nativeSync=(e,t)=>a(r(e),n(t)),u.manualSync=(e,t)=>s(r(e),n(t)),t.exports=u})),Oy=L(((e,t)=>{var n=R(`fs`),r=R(`path`),i=n.lchown?`lchown`:`chown`,a=n.lchownSync?`lchownSync`:`chownSync`,o=n.lchown&&!process.version.match(/v1[1-9]+\./)&&!process.version.match(/v10\.[6-9]/),s=(e,t,r)=>{try{return n[a](e,t,r)}catch(e){if(e.code!==`ENOENT`)throw e}},c=(e,t,r)=>{try{return n.chownSync(e,t,r)}catch(e){if(e.code!==`ENOENT`)throw e}},l=o?(e,t,r,i)=>a=>{!a||a.code!==`EISDIR`?i(a):n.chown(e,t,r,i)}:(e,t,n,r)=>r,u=o?(e,t,n)=>{try{return s(e,t,n)}catch(r){if(r.code!==`EISDIR`)throw r;c(e,t,n)}}:(e,t,n)=>s(e,t,n),d=process.version,f=(e,t,r)=>n.readdir(e,t,r),p=(e,t)=>n.readdirSync(e,t);/^v4\./.test(d)&&(f=(e,t,r)=>n.readdir(e,r));var m=(e,t,r,a)=>{n[i](e,t,r,l(e,t,r,e=>{a(e&&e.code!==`ENOENT`?e:null)}))},h=(e,t,i,a,o)=>{if(typeof t==`string`)return n.lstat(r.resolve(e,t),(n,r)=>{if(n)return o(n.code===`ENOENT`?null:n);r.name=t,h(e,r,i,a,o)});t.isDirectory()?g(r.resolve(e,t.name),i,a,n=>{if(n)return o(n);m(r.resolve(e,t.name),i,a,o)}):m(r.resolve(e,t.name),i,a,o)},g=(e,t,n,r)=>{f(e,{withFileTypes:!0},(i,a)=>{if(i){if(i.code===`ENOENT`)return r();if(i.code!==`ENOTDIR`&&i.code!==`ENOTSUP`)return r(i)}if(i||!a.length)return m(e,t,n,r);let o=a.length,s=null,c=i=>{if(!s){if(i)return r(s=i);if(--o===0)return m(e,t,n,r)}};a.forEach(r=>h(e,r,t,n,c))})},_=(e,t,i,a)=>{if(typeof t==`string`)try{let i=n.lstatSync(r.resolve(e,t));i.name=t,t=i}catch(e){if(e.code===`ENOENT`)return;throw e}t.isDirectory()&&v(r.resolve(e,t.name),i,a),u(r.resolve(e,t.name),i,a)},v=(e,t,n)=>{let r;try{r=p(e,{withFileTypes:!0})}catch(r){if(r.code===`ENOENT`)return;if(r.code===`ENOTDIR`||r.code===`ENOTSUP`)return u(e,t,n);throw r}return r&&r.length&&r.forEach(r=>_(e,r,t,n)),u(e,t,n)};t.exports=g,g.sync=v})),ky=L(((e,t)=>{var n=Dy(),r=R(`fs`),i=R(`path`),a=Oy(),o=ey(),s=class extends Error{constructor(e,t){super(`Cannot extract through symbolic link`),this.path=t,this.symlink=e}get name(){return`SylinkError`}},c=class extends Error{constructor(e,t){super(t+`: Cannot cd into '`+e+`'`),this.path=e,this.code=t}get name(){return`CwdError`}},l=(e,t)=>e.get(o(t)),u=(e,t,n)=>e.set(o(t),n),d=(e,t)=>{r.stat(e,(n,r)=>{(n||!r.isDirectory())&&(n=new c(e,n&&n.code||`ENOTDIR`)),t(n)})};t.exports=(e,t,s)=>{e=o(e);let c=t.umask,p=t.mode|448,m=(p&c)!==0,h=t.uid,g=t.gid,_=typeof h==`number`&&typeof g==`number`&&(h!==t.processUid||g!==t.processGid),v=t.preserve,y=t.unlink,b=t.cache,x=o(t.cwd),S=(t,n)=>{t?s(t):(u(b,e,!0),n&&_?a(n,h,g,e=>S(e)):m?r.chmod(e,p,s):s())};if(b&&l(b,e)===!0)return S();if(e===x)return d(e,S);if(v)return n(e,{mode:p}).then(e=>S(null,e),S);f(x,o(i.relative(x,e)).split(`/`),p,b,y,x,null,S)};var f=(e,t,n,a,s,c,u,d)=>{if(!t.length)return d(null,u);let m=t.shift(),h=o(i.resolve(e+`/`+m));if(l(a,h))return f(h,t,n,a,s,c,u,d);r.mkdir(h,n,p(h,t,n,a,s,c,u,d))},p=(e,t,n,i,a,c,l,u)=>d=>{d?r.lstat(e,(m,h)=>{if(m)m.path=m.path&&o(m.path),u(m);else if(h.isDirectory())f(e,t,n,i,a,c,l,u);else if(a)r.unlink(e,o=>{if(o)return u(o);r.mkdir(e,n,p(e,t,n,i,a,c,l,u))});else if(h.isSymbolicLink())return u(new s(e,e+`/`+t.join(`/`)));else u(d)}):(l||=e,f(e,t,n,i,a,c,l,u))},m=e=>{let t=!1,n=`ENOTDIR`;try{t=r.statSync(e).isDirectory()}catch(e){n=e.code}finally{if(!t)throw new c(e,n)}};t.exports.sync=(e,t)=>{e=o(e);let c=t.umask,d=t.mode|448,f=(d&c)!==0,p=t.uid,h=t.gid,g=typeof p==`number`&&typeof h==`number`&&(p!==t.processUid||h!==t.processGid),_=t.preserve,v=t.unlink,y=t.cache,b=o(t.cwd),x=t=>{u(y,e,!0),t&&g&&a.sync(t,p,h),f&&r.chmodSync(e,d)};if(y&&l(y,e)===!0)return x();if(e===b)return m(b),x();if(_)return x(n.sync(e,d));let S=o(i.relative(b,e)).split(`/`),C=null;for(let e=S.shift(),t=b;e&&(t+=`/`+e);e=S.shift())if(t=o(i.resolve(t)),!l(y,t))try{r.mkdirSync(t,d),C||=t,u(y,t,!0)}catch{let e=r.lstatSync(t);if(e.isDirectory()){u(y,t,!0);continue}if(v){r.unlinkSync(t),r.mkdirSync(t,d),C||=t,u(y,t,!0);continue}if(e.isSymbolicLink())return new s(t,t+`/`+S.join(`/`))}return x(C)}})),Ay=L(((e,t)=>{var n=Object.create(null),{hasOwnProperty:r}=Object.prototype;t.exports=e=>(r.call(n,e)||(n[e]=e.normalize(`NFD`)),n[e])})),jy=L(((e,t)=>{var n=R(`assert`),r=Ay(),i=oy(),{join:a}=R(`path`),o=(process.env.TESTING_TAR_FAKE_PLATFORM||process.platform)===`win32`;t.exports=()=>{let e=new Map,t=new Map,s=e=>e.split(`/`).slice(0,-1).reduce((e,t)=>(e.length&&(t=a(e[e.length-1],t)),e.push(t||`/`),e),[]),c=new Set,l=n=>{let r=t.get(n);if(!r)throw Error(`function does not have any path reservations`);return{paths:r.paths.map(t=>e.get(t)),dirs:[...r.dirs].map(t=>e.get(t))}},u=e=>{let{paths:t,dirs:n}=l(e);return t.every(t=>t[0]===e)&&n.every(t=>t[0]instanceof Set&&t[0].has(e))},d=e=>c.has(e)||!u(e)?!1:(c.add(e),e(()=>f(e)),!0),f=r=>{if(!c.has(r))return!1;let{paths:i,dirs:a}=t.get(r),o=new Set;return i.forEach(t=>{let i=e.get(t);n.equal(i[0],r),i.length===1?e.delete(t):(i.shift(),typeof i[0]==`function`?o.add(i[0]):i[0].forEach(e=>o.add(e)))}),a.forEach(t=>{let i=e.get(t);n(i[0]instanceof Set),i[0].size===1&&i.length===1?e.delete(t):i[0].size===1?(i.shift(),o.add(i[0])):i[0].delete(r)}),c.delete(r),o.forEach(e=>d(e)),!0};return{check:u,reserve:(n,c)=>{n=o?[`win32 parallelization disabled`]:n.map(e=>i(a(r(e))).toLowerCase());let l=new Set(n.map(e=>s(e)).reduce((e,t)=>e.concat(t)));return t.set(c,{dirs:l,paths:n}),n.forEach(t=>{let n=e.get(t);n?n.push(c):e.set(t,[c])}),l.forEach(t=>{let n=e.get(t);n?n[n.length-1]instanceof Set?n[n.length-1].add(c):n.push(new Set([c])):e.set(t,[new Set([c])])}),d(c)}}}})),My=L(((e,t)=>{var n=(process.env.__FAKE_PLATFORM__||process.platform)===`win32`,{O_CREAT:r,O_TRUNC:i,O_WRONLY:a,UV_FS_O_FILEMAP:o=0}=(global.__FAKE_TESTING_FS__||R(`fs`)).constants,s=n&&!!o,c=524288,l=o|i|r|a;t.exports=s?e=>e<c?l:`w`:()=>`w`})),Ny=L(((e,t)=>{var n=R(`assert`),r=gy(),i=R(`fs`),a=hy(),o=R(`path`),s=ky(),c=cy(),l=jy(),u=ly(),d=ey(),f=oy(),p=Ay(),m=Symbol(`onEntry`),h=Symbol(`checkFs`),g=Symbol(`checkFs2`),_=Symbol(`pruneCache`),v=Symbol(`isReusable`),y=Symbol(`makeFs`),b=Symbol(`file`),x=Symbol(`directory`),S=Symbol(`link`),C=Symbol(`symlink`),w=Symbol(`hardlink`),T=Symbol(`unsupported`),E=Symbol(`checkPath`),D=Symbol(`mkdir`),O=Symbol(`onError`),k=Symbol(`pending`),A=Symbol(`pend`),j=Symbol(`unpend`),M=Symbol(`ended`),N=Symbol(`maybeClose`),P=Symbol(`skip`),F=Symbol(`doChown`),I=Symbol(`uid`),ee=Symbol(`gid`),te=Symbol(`checkedCwd`),ne=R(`crypto`),re=My(),ie=(process.env.TESTING_TAR_FAKE_PLATFORM||process.platform)===`win32`,ae=1024,oe=(e,t)=>{if(!ie)return i.unlink(e,t);let n=e+`.DELETE.`+ne.randomBytes(16).toString(`hex`);i.rename(e,n,e=>{if(e)return t(e);i.unlink(n,t)})},se=e=>{if(!ie)return i.unlinkSync(e);let t=e+`.DELETE.`+ne.randomBytes(16).toString(`hex`);i.renameSync(e,t),i.unlinkSync(t)},ce=(e,t,n)=>e===e>>>0?e:t===t>>>0?t:n,le=e=>f(d(p(e))).toLowerCase(),ue=(e,t)=>{t=le(t);for(let n of e.keys()){let r=le(n);(r===t||r.indexOf(t+`/`)===0)&&e.delete(n)}},de=e=>{for(let t of e.keys())e.delete(t)},fe=class extends r{constructor(e){if(e||={},e.ondone=e=>{this[M]=!0,this[N]()},super(e),this[te]=!1,this.reservations=l(),this.transform=typeof e.transform==`function`?e.transform:null,this.writable=!0,this.readable=!1,this[k]=0,this[M]=!1,this.dirCache=e.dirCache||new Map,typeof e.uid==`number`||typeof e.gid==`number`){if(typeof e.uid!=`number`||typeof e.gid!=`number`)throw TypeError(`cannot set owner without number uid and gid`);if(e.preserveOwner)throw TypeError(`cannot preserve owner in archive and also set owner explicitly`);this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=null,this.gid=null,this.setOwner=!1;this.preserveOwner=e.preserveOwner===void 0&&typeof e.uid!=`number`?process.getuid&&process.getuid()===0:!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():null,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():null,this.maxDepth=typeof e.maxDepth==`number`?e.maxDepth:ae,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||ie,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=d(o.resolve(e.cwd||process.cwd())),this.strip=+e.strip||0,this.processUmask=e.noChmod?0:process.umask(),this.umask=typeof e.umask==`number`?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on(`entry`,e=>this[m](e))}warn(e,t,n={}){return(e===`TAR_BAD_ARCHIVE`||e===`TAR_ABORT`)&&(n.recoverable=!1),super.warn(e,t,n)}[N](){this[M]&&this[k]===0&&(this.emit(`prefinish`),this.emit(`finish`),this.emit(`end`))}[E](e){let t=d(e.path),n=t.split(`/`);if(this.strip){if(n.length<this.strip)return!1;if(e.type===`Link`){let t=d(e.linkpath).split(`/`);if(t.length>=this.strip)e.linkpath=t.slice(this.strip).join(`/`);else return!1}n.splice(0,this.strip),e.path=n.join(`/`)}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn(`TAR_ENTRY_ERROR`,`path excessively deep`,{entry:e,path:t,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this.preservePaths){if(n.includes(`..`)||ie&&/^[a-z]:\.\.$/i.test(n[0]))return this.warn(`TAR_ENTRY_ERROR`,`path contains '..'`,{entry:e,path:t}),!1;let[r,i]=u(t);r&&(e.path=i,this.warn(`TAR_ENTRY_INFO`,`stripping ${r} from absolute path`,{entry:e,path:t}))}if(e.absolute=o.isAbsolute(e.path)?d(o.resolve(e.path)):d(o.resolve(this.cwd,e.path)),!this.preservePaths&&e.absolute.indexOf(this.cwd+`/`)!==0&&e.absolute!==this.cwd)return this.warn(`TAR_ENTRY_ERROR`,`path escaped extraction target`,{entry:e,path:d(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!==`Directory`&&e.type!==`GNUDumpDir`)return!1;if(this.win32){let{root:t}=o.win32.parse(e.absolute);e.absolute=t+c.encode(e.absolute.slice(t.length));let{root:n}=o.win32.parse(e.path);e.path=n+c.encode(e.path.slice(n.length))}return!0}[m](e){if(!this[E](e))return e.resume();switch(n.equal(typeof e.absolute,`string`),e.type){case`Directory`:case`GNUDumpDir`:e.mode&&(e.mode|=448);case`File`:case`OldFile`:case`ContiguousFile`:case`Link`:case`SymbolicLink`:return this[h](e);default:return this[T](e)}}[O](e,t){e.name===`CwdError`?this.emit(`error`,e):(this.warn(`TAR_ENTRY_ERROR`,e,{entry:t}),this[j](),t.resume())}[D](e,t,n){s(d(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:t,noChmod:this.noChmod},n)}[F](e){return this.forceChown||this.preserveOwner&&(typeof e.uid==`number`&&e.uid!==this.processUid||typeof e.gid==`number`&&e.gid!==this.processGid)||typeof this.uid==`number`&&this.uid!==this.processUid||typeof this.gid==`number`&&this.gid!==this.processGid}[I](e){return ce(this.uid,e.uid,this.processUid)}[ee](e){return ce(this.gid,e.gid,this.processGid)}[b](e,t){let n=e.mode&4095||this.fmode,r=new a.WriteStream(e.absolute,{flags:re(e.size),mode:n,autoClose:!1});r.on(`error`,n=>{r.fd&&i.close(r.fd,()=>{}),r.write=()=>!0,this[O](n,e),t()});let o=1,s=n=>{if(n){r.fd&&i.close(r.fd,()=>{}),this[O](n,e),t();return}--o===0&&i.close(r.fd,n=>{n?this[O](n,e):this[j](),t()})};r.on(`finish`,t=>{let n=e.absolute,a=r.fd;if(e.mtime&&!this.noMtime){o++;let t=e.atime||new Date,r=e.mtime;i.futimes(a,t,r,e=>e?i.utimes(n,t,r,t=>s(t&&e)):s())}if(this[F](e)){o++;let t=this[I](e),r=this[ee](e);i.fchown(a,t,r,e=>e?i.chown(n,t,r,t=>s(t&&e)):s())}s()});let c=this.transform&&this.transform(e)||e;c!==e&&(c.on(`error`,n=>{this[O](n,e),t()}),e.pipe(c)),c.pipe(r)}[x](e,t){let n=e.mode&4095||this.dmode;this[D](e.absolute,n,n=>{if(n){this[O](n,e),t();return}let r=1,a=n=>{--r===0&&(t(),this[j](),e.resume())};e.mtime&&!this.noMtime&&(r++,i.utimes(e.absolute,e.atime||new Date,e.mtime,a)),this[F](e)&&(r++,i.chown(e.absolute,this[I](e),this[ee](e),a)),a()})}[T](e){e.unsupported=!0,this.warn(`TAR_ENTRY_UNSUPPORTED`,`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[C](e,t){this[S](e,e.linkpath,`symlink`,t)}[w](e,t){let n=d(o.resolve(this.cwd,e.linkpath));this[S](e,n,`link`,t)}[A](){this[k]++}[j](){this[k]--,this[N]()}[P](e){this[j](),e.resume()}[v](e,t){return e.type===`File`&&!this.unlink&&t.isFile()&&t.nlink<=1&&!ie}[h](e){this[A]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,t=>this[g](e,t))}[_](e){e.type===`SymbolicLink`?de(this.dirCache):e.type!==`Directory`&&ue(this.dirCache,e.absolute)}[g](e,t){this[_](e);let n=n=>{this[_](e),t(n)},r=()=>{this[D](this.cwd,this.dmode,t=>{if(t){this[O](t,e),n();return}this[te]=!0,a()})},a=()=>{if(e.absolute!==this.cwd){let t=d(o.dirname(e.absolute));if(t!==this.cwd)return this[D](t,this.dmode,t=>{if(t){this[O](t,e),n();return}s()})}s()},s=()=>{i.lstat(e.absolute,(t,r)=>{if(r&&(this.keep||this.newer&&r.mtime>e.mtime)){this[P](e),n();return}if(t||this[v](e,r))return this[y](null,e,n);if(r.isDirectory()){if(e.type===`Directory`){let t=!this.noChmod&&e.mode&&(r.mode&4095)!==e.mode,a=t=>this[y](t,e,n);return t?i.chmod(e.absolute,e.mode,a):a()}if(e.absolute!==this.cwd)return i.rmdir(e.absolute,t=>this[y](t,e,n))}if(e.absolute===this.cwd)return this[y](null,e,n);oe(e.absolute,t=>this[y](t,e,n))})};this[te]?a():r()}[y](e,t,n){if(e){this[O](e,t),n();return}switch(t.type){case`File`:case`OldFile`:case`ContiguousFile`:return this[b](t,n);case`Link`:return this[w](t,n);case`SymbolicLink`:return this[C](t,n);case`Directory`:case`GNUDumpDir`:return this[x](t,n)}}[S](e,t,n,r){i[n](t,e.absolute,t=>{t?this[O](t,e):(this[j](),e.resume()),r()})}},pe=e=>{try{return[null,e()]}catch(e){return[e,null]}};fe.Sync=class extends fe{[y](e,t){return super[y](e,t,()=>{})}[h](e){if(this[_](e),!this[te]){let t=this[D](this.cwd,this.dmode);if(t)return this[O](t,e);this[te]=!0}if(e.absolute!==this.cwd){let t=d(o.dirname(e.absolute));if(t!==this.cwd){let n=this[D](t,this.dmode);if(n)return this[O](n,e)}}let[t,n]=pe(()=>i.lstatSync(e.absolute));if(n&&(this.keep||this.newer&&n.mtime>e.mtime))return this[P](e);if(t||this[v](e,n))return this[y](null,e);if(n.isDirectory()){if(e.type===`Directory`){let[t]=!this.noChmod&&e.mode&&(n.mode&4095)!==e.mode?pe(()=>{i.chmodSync(e.absolute,e.mode)}):[];return this[y](t,e)}let[t]=pe(()=>i.rmdirSync(e.absolute));this[y](t,e)}let[r]=e.absolute===this.cwd?[]:pe(()=>se(e.absolute));this[y](r,e)}[b](e,t){let n=e.mode&4095||this.fmode,r=n=>{let r;try{i.closeSync(a)}catch(e){r=e}(n||r)&&this[O](n||r,e),t()},a;try{a=i.openSync(e.absolute,re(e.size),n)}catch(e){return r(e)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on(`error`,t=>this[O](t,e)),e.pipe(o)),o.on(`data`,e=>{try{i.writeSync(a,e,0,e.length)}catch(e){r(e)}}),o.on(`end`,t=>{let n=null;if(e.mtime&&!this.noMtime){let t=e.atime||new Date,r=e.mtime;try{i.futimesSync(a,t,r)}catch(a){try{i.utimesSync(e.absolute,t,r)}catch{n=a}}}if(this[F](e)){let t=this[I](e),r=this[ee](e);try{i.fchownSync(a,t,r)}catch(a){try{i.chownSync(e.absolute,t,r)}catch{n||=a}}}r(n)})}[x](e,t){let n=e.mode&4095||this.dmode,r=this[D](e.absolute,n);if(r){this[O](r,e),t();return}if(e.mtime&&!this.noMtime)try{i.utimesSync(e.absolute,e.atime||new Date,e.mtime)}catch{}if(this[F](e))try{i.chownSync(e.absolute,this[I](e),this[ee](e))}catch{}t(),e.resume()}[D](e,t){try{return s.sync(d(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:t})}catch(e){return e}}[S](e,t,n,r){try{i[n+`Sync`](t,e.absolute),r(),e.resume()}catch(t){return this[O](t,e)}}},t.exports=fe})),Py=L(((e,t)=>{var n=Yv(),r=Ny(),i=R(`fs`),a=hy(),o=R(`path`),s=oy();t.exports=(e,t,r)=>{typeof e==`function`?(r=e,t=null,e={}):Array.isArray(e)&&(t=e,e={}),typeof t==`function`&&(r=t,t=null),t=t?Array.from(t):[];let i=n(e);if(i.sync&&typeof r==`function`)throw TypeError(`callback not supported for sync tar functions`);if(!i.file&&typeof r==`function`)throw TypeError(`callback only supported with file option`);return t.length&&c(i,t),i.file&&i.sync?l(i):i.file?u(i,r):i.sync?d(i):f(i)};var c=(e,t)=>{let n=new Map(t.map(e=>[s(e),!0])),r=e.filter,i=(e,t)=>{let r=t||o.parse(e).root||`.`,a=e===r?!1:n.has(e)?n.get(e):i(o.dirname(e),r);return n.set(e,a),a};e.filter=r?(e,t)=>r(e,t)&&i(s(e)):e=>i(s(e))},l=e=>{let t=new r.Sync(e),n=e.file,o=i.statSync(n),s=e.maxReadSize||16777216;new a.ReadStreamSync(n,{readSize:s,size:o.size}).pipe(t)},u=(e,t)=>{let n=new r(e),o=e.maxReadSize||16777216,s=e.file,c=new Promise((e,t)=>{n.on(`error`,t),n.on(`close`,e),i.stat(s,(e,r)=>{if(e)t(e);else{let e=new a.ReadStream(s,{readSize:o,size:r.size});e.on(`error`,t),e.pipe(n)}})});return t?c.then(t,t):c},d=e=>new r.Sync(e),f=e=>new r(e)})),Fy=L((e=>{e.c=e.create=vy(),e.r=e.replace=yy(),e.t=e.list=_y(),e.u=e.update=by(),e.x=e.extract=Py(),e.Pack=my(),e.Unpack=Ny(),e.Parse=gy(),e.ReadEntry=ty(),e.WriteEntry=dy(),e.Header=iy(),e.Pax=ay(),e.types=ny()})),Iy=L(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),Ly=L(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Iy(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),Ry=L(((e,t)=>{e.formatArgs=r,e.save=i,e.load=a,e.useColors=n,e.storage=o(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function n(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function i(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function a(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&typeof process<`u`&&`env`in process&&(t=process.env.DEBUG),t}function o(){try{return localStorage}catch{}}t.exports=Ly()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),zy=L(((e,t)=>{var n=R(`tty`),r=R(`util`);e.init=u,e.log=s,e.formatArgs=a,e.save=c,e.load=l,e.useColors=i,e.destroy=r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{let t=R(`supports-color`);t&&(t.stderr||t).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}e.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{let n=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase()),r=process.env[t];return r=/^(yes|on|true|enabled)$/i.test(r)?!0:/^(no|off|false|disabled)$/i.test(r)?!1:r===`null`?null:Number(r),e[n]=r,e},{});function i(){return`colors`in e.inspectOpts?!!e.inspectOpts.colors:n.isatty(process.stderr.fd)}function a(e){let{namespace:n,useColors:r}=this;if(r){let r=this.color,i=`\x1B[3`+(r<8?r:`8;5;`+r),a=` ${i};1m${n} \u001B[0m`;e[0]=a+e[0].split(`
|
|
78
|
-
`).join(`
|
|
79
|
-
|
|
80
|
-
`)}function
|
|
81
|
-
`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})),By=L(((e,t)=>{t.exports=typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?Ry():zy()})),Vy=L(((e,t)=>{t.exports=n;function n(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}n.prototype.go=function(e){this.pending<this.max?i(this,e):this.waiting.push(e)},n.prototype.wait=function(e){this.pending===0?e(this.error):this.listeners.push(e)},n.prototype.hold=function(){return r(this)};function r(e){e.pending+=1;var t=!1;return n;function n(n){if(t)throw Error(`callback called twice`);if(t=!0,e.error=e.error||n,--e.pending,e.waiting.length>0&&e.pending<e.max)i(e,e.waiting.shift());else if(e.pending===0){var a=e.listeners;e.listeners=[],a.forEach(r)}}function r(t){t(e.error)}}function i(e,t){t(r(e))}})),Hy=L((e=>{var t=R(`fs`),n=R(`util`),r=R(`stream`),i=r.Readable,a=r.Writable,o=r.PassThrough,s=Vy(),c=R(`events`).EventEmitter;e.createFromBuffer=p,e.createFromFd=m,e.BufferSlicer=f,e.FdSlicer=l,n.inherits(l,c);function l(e,t){t||={},c.call(this),this.fd=e,this.pend=new s,this.pend.max=1,this.refCount=0,this.autoClose=!!t.autoClose}l.prototype.read=function(e,n,r,i,a){var o=this;o.pend.go(function(s){t.read(o.fd,e,n,r,i,function(e,t,n){s(),a(e,t,n)})})},l.prototype.write=function(e,n,r,i,a){var o=this;o.pend.go(function(s){t.write(o.fd,e,n,r,i,function(e,t,n){s(),a(e,t,n)})})},l.prototype.createReadStream=function(e){return new u(this,e)},l.prototype.createWriteStream=function(e){return new d(this,e)},l.prototype.ref=function(){this.refCount+=1},l.prototype.unref=function(){var e=this;if(--e.refCount,e.refCount>0)return;if(e.refCount<0)throw Error(`invalid unref`);e.autoClose&&t.close(e.fd,n);function n(t){t?e.emit(`error`,t):e.emit(`close`)}},n.inherits(u,i);function u(e,t){t||={},i.call(this,t),this.context=e,this.context.ref(),this.start=t.start||0,this.endOffset=t.end,this.pos=this.start,this.destroyed=!1}u.prototype._read=function(e){var n=this;if(!n.destroyed){var r=Math.min(n._readableState.highWaterMark,e);if(n.endOffset!=null&&(r=Math.min(r,n.endOffset-n.pos)),r<=0){n.destroyed=!0,n.push(null),n.context.unref();return}n.context.pend.go(function(e){if(n.destroyed)return e();var i=new Buffer(r);t.read(n.context.fd,i,0,r,n.pos,function(t,r){t?n.destroy(t):r===0?(n.destroyed=!0,n.push(null),n.context.unref()):(n.pos+=r,n.push(i.slice(0,r))),e()})})}},u.prototype.destroy=function(e){this.destroyed||(e||=Error(`stream destroyed`),this.destroyed=!0,this.emit(`error`,e),this.context.unref())},n.inherits(d,a);function d(e,t){t||={},a.call(this,t),this.context=e,this.context.ref(),this.start=t.start||0,this.endOffset=t.end==null?1/0:+t.end,this.bytesWritten=0,this.pos=this.start,this.destroyed=!1,this.on(`finish`,this.destroy.bind(this))}d.prototype._write=function(e,n,r){var i=this;if(!i.destroyed){if(i.pos+e.length>i.endOffset){var a=Error(`maximum file length exceeded`);a.code=`ETOOBIG`,i.destroy(),r(a);return}i.context.pend.go(function(n){if(i.destroyed)return n();t.write(i.context.fd,e,0,e.length,i.pos,function(e,t){e?(i.destroy(),n(),r(e)):(i.bytesWritten+=t,i.pos+=t,i.emit(`progress`),n(),r())})})}},d.prototype.destroy=function(){this.destroyed||(this.destroyed=!0,this.context.unref())},n.inherits(f,c);function f(e,t){c.call(this),t||={},this.refCount=0,this.buffer=e,this.maxChunkSize=t.maxChunkSize||2**53-1}f.prototype.read=function(e,t,n,r,i){var a=r+n,o=a-this.buffer.length,s=o>0?o:n;this.buffer.copy(e,t,r,a),setImmediate(function(){i(null,s)})},f.prototype.write=function(e,t,n,r,i){e.copy(this.buffer,r,t,t+n),setImmediate(function(){i(null,n,e)})},f.prototype.createReadStream=function(e){e||={};var t=new o(e);t.destroyed=!1,t.start=e.start||0,t.endOffset=e.end,t.pos=t.endOffset||this.buffer.length;for(var n=this.buffer.slice(t.start,t.pos),r=0;;){var i=r+this.maxChunkSize;if(i>=n.length){r<n.length&&t.write(n.slice(r,n.length));break}t.write(n.slice(r,i)),r=i}return t.end(),t.destroy=function(){t.destroyed=!0},t},f.prototype.createWriteStream=function(e){var t=this;e||={};var n=new a(e);return n.start=e.start||0,n.endOffset=e.end==null?this.buffer.length:+e.end,n.bytesWritten=0,n.pos=n.start,n.destroyed=!1,n._write=function(e,r,i){if(!n.destroyed){var a=n.pos+e.length;if(a>n.endOffset){var o=Error(`maximum file length exceeded`);o.code=`ETOOBIG`,n.destroyed=!0,i(o);return}e.copy(t.buffer,n.pos,0,e.length),n.bytesWritten+=e.length,n.pos=a,n.emit(`progress`),i()}},n.destroy=function(){n.destroyed=!0},n},f.prototype.ref=function(){this.refCount+=1},f.prototype.unref=function(){if(--this.refCount,this.refCount<0)throw Error(`invalid unref`)};function p(e,t){return new f(e,t)}function m(e,t){return new l(e,t)}})),Uy=L(((e,t)=>{var n=R(`buffer`).Buffer,r=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];typeof Int32Array<`u`&&(r=new Int32Array(r));function i(e){if(n.isBuffer(e))return e;var t=typeof n.alloc==`function`&&typeof n.from==`function`;if(typeof e==`number`)return t?n.alloc(e):new n(e);if(typeof e==`string`)return t?n.from(e):new n(e);throw Error(`input must be buffer, number, or string, received `+typeof e)}function a(e){var t=i(4);return t.writeInt32BE(e,0),t}function o(e,t){e=i(e),n.isBuffer(t)&&(t=t.readUInt32BE(0));for(var a=~~t^-1,o=0;o<e.length;o++)a=r[(a^e[o])&255]^a>>>8;return a^-1}function s(){return a(o.apply(null,arguments))}s.signed=function(){return o.apply(null,arguments)},s.unsigned=function(){return o.apply(null,arguments)>>>0},t.exports=s})),Wy=L((e=>{var t=R(`fs`),n=R(`zlib`),r=Hy(),i=Uy(),a=R(`util`),o=R(`events`).EventEmitter,s=R(`stream`).Transform,c=R(`stream`).PassThrough,l=R(`stream`).Writable;e.open=u,e.fromFd=d,e.fromBuffer=f,e.fromRandomAccessReader=p,e.dosDateTimeToDate=v,e.validateFileName=y,e.ZipFile=m,e.Entry=_,e.RandomAccessReader=S;function u(e,n,r){typeof n==`function`&&(r=n,n=null),n??={},n.autoClose??(n.autoClose=!0),n.lazyEntries??(n.lazyEntries=!1),n.decodeStrings??(n.decodeStrings=!0),n.validateEntrySizes??(n.validateEntrySizes=!0),n.strictFileNames??(n.strictFileNames=!1),r??=O,t.open(e,`r`,function(e,i){if(e)return r(e);d(i,n,function(e,n){e&&t.close(i,O),r(e,n)})})}function d(e,n,i){typeof n==`function`&&(i=n,n=null),n??={},n.autoClose??(n.autoClose=!1),n.lazyEntries??(n.lazyEntries=!1),n.decodeStrings??(n.decodeStrings=!0),n.validateEntrySizes??(n.validateEntrySizes=!0),n.strictFileNames??(n.strictFileNames=!1),i??=O,t.fstat(e,function(t,a){if(t)return i(t);p(r.createFromFd(e,{autoClose:!0}),a.size,n,i)})}function f(e,t,n){typeof t==`function`&&(n=t,t=null),t??={},t.autoClose=!1,t.lazyEntries??(t.lazyEntries=!1),t.decodeStrings??(t.decodeStrings=!0),t.validateEntrySizes??(t.validateEntrySizes=!0),t.strictFileNames??(t.strictFileNames=!1),p(r.createFromBuffer(e,{maxChunkSize:65536}),e.length,t,n)}function p(e,t,n,r){typeof n==`function`&&(r=n,n=null),n??={},n.autoClose??(n.autoClose=!0),n.lazyEntries??(n.lazyEntries=!1),n.decodeStrings??(n.decodeStrings=!0);var i=!!n.decodeStrings;if(n.validateEntrySizes??(n.validateEntrySizes=!0),n.strictFileNames??(n.strictFileNames=!1),r??=O,typeof t!=`number`)throw Error(`expected totalSize parameter to be a number`);if(t>2**53-1)throw Error(`zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.`);e.ref();var a=22,o=Math.min(a+65535,t),s=D(o),c=t-s.length;b(e,s,0,o,c,function(l){if(l)return r(l);for(var u=o-a;u>=0;--u)if(s.readUInt32LE(u)===101010256){var d=s.slice(u),f=d.readUInt16LE(4);if(f!==0)return r(Error(`multi-disk zip files are not supported: found disk number: `+f));var p=d.readUInt16LE(10),h=d.readUInt32LE(16),g=d.readUInt16LE(20),_=d.length-a;if(g!==_)return r(Error(`invalid comment length. expected: `+_+`. found: `+g));var v=i?T(d,22,d.length,!1):d.slice(22);if(p!==65535&&h!==4294967295)return r(null,new m(e,h,t,p,v,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames));var y=D(20),x=c+u-y.length;b(e,y,0,y.length,x,function(a){if(a)return r(a);if(y.readUInt32LE(0)!==117853008)return r(Error(`invalid zip64 end of central directory locator signature`));var o=E(y,8),s=D(56);b(e,s,0,s.length,o,function(a){return a?r(a):s.readUInt32LE(0)===101075792?(p=E(s,32),h=E(s,48),r(null,new m(e,h,t,p,v,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames))):r(Error(`invalid zip64 end of central directory record signature`))})});return}r(Error(`end of central directory record signature not found`))})}a.inherits(m,o);function m(e,t,n,r,i,a,s,c,l,u){var d=this;o.call(d),d.reader=e,d.reader.on(`error`,function(e){g(d,e)}),d.reader.once(`close`,function(){d.emit(`close`)}),d.readEntryCursor=t,d.fileSize=n,d.entryCount=r,d.comment=i,d.entriesRead=0,d.autoClose=!!a,d.lazyEntries=!!s,d.decodeStrings=!!c,d.validateEntrySizes=!!l,d.strictFileNames=!!u,d.isOpen=!0,d.emittedError=!1,d.lazyEntries||d._readEntry()}m.prototype.close=function(){this.isOpen&&(this.isOpen=!1,this.reader.unref())};function h(e,t){e.autoClose&&e.close(),g(e,t)}function g(e,t){e.emittedError||(e.emittedError=!0,e.emit(`error`,t))}m.prototype.readEntry=function(){if(!this.lazyEntries)throw Error(`readEntry() called without lazyEntries:true`);this._readEntry()},m.prototype._readEntry=function(){var e=this;if(e.entryCount===e.entriesRead){setImmediate(function(){e.autoClose&&e.close(),!e.emittedError&&e.emit(`end`)});return}if(!e.emittedError){var t=D(46);b(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return h(e,n);if(!e.emittedError){var r=new _,a=t.readUInt32LE(0);if(a!==33639248)return h(e,Error(`invalid central directory file header signature: 0x`+a.toString(16)));if(r.versionMadeBy=t.readUInt16LE(4),r.versionNeededToExtract=t.readUInt16LE(6),r.generalPurposeBitFlag=t.readUInt16LE(8),r.compressionMethod=t.readUInt16LE(10),r.lastModFileTime=t.readUInt16LE(12),r.lastModFileDate=t.readUInt16LE(14),r.crc32=t.readUInt32LE(16),r.compressedSize=t.readUInt32LE(20),r.uncompressedSize=t.readUInt32LE(24),r.fileNameLength=t.readUInt16LE(28),r.extraFieldLength=t.readUInt16LE(30),r.fileCommentLength=t.readUInt16LE(32),r.internalFileAttributes=t.readUInt16LE(36),r.externalFileAttributes=t.readUInt32LE(38),r.relativeOffsetOfLocalHeader=t.readUInt32LE(42),r.generalPurposeBitFlag&64)return h(e,Error(`strong encryption is not supported`));e.readEntryCursor+=46,t=D(r.fileNameLength+r.extraFieldLength+r.fileCommentLength),b(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return h(e,n);if(!e.emittedError){var a=!!(r.generalPurposeBitFlag&2048);r.fileName=e.decodeStrings?T(t,0,r.fileNameLength,a):t.slice(0,r.fileNameLength);var o=r.fileNameLength+r.extraFieldLength,s=t.slice(r.fileNameLength,o);r.extraFields=[];for(var c=0;c<s.length-3;){var l=s.readUInt16LE(c+0),u=s.readUInt16LE(c+2),d=c+4,f=d+u;if(f>s.length)return h(e,Error(`extra field length exceeds extra field buffer size`));var p=D(u);s.copy(p,0,d,f),r.extraFields.push({id:l,data:p}),c=f}if(r.fileComment=e.decodeStrings?T(t,o,o+r.fileCommentLength,a):t.slice(o,o+r.fileCommentLength),r.comment=r.fileComment,e.readEntryCursor+=t.length,e.entriesRead+=1,r.uncompressedSize===4294967295||r.compressedSize===4294967295||r.relativeOffsetOfLocalHeader===4294967295){for(var m=null,c=0;c<r.extraFields.length;c++){var g=r.extraFields[c];if(g.id===1){m=g.data;break}}if(m==null)return h(e,Error(`expected zip64 extended information extra field`));var _=0;if(r.uncompressedSize===4294967295){if(_+8>m.length)return h(e,Error(`zip64 extended information extra field does not include uncompressed size`));r.uncompressedSize=E(m,_),_+=8}if(r.compressedSize===4294967295){if(_+8>m.length)return h(e,Error(`zip64 extended information extra field does not include compressed size`));r.compressedSize=E(m,_),_+=8}if(r.relativeOffsetOfLocalHeader===4294967295){if(_+8>m.length)return h(e,Error(`zip64 extended information extra field does not include relative header offset`));r.relativeOffsetOfLocalHeader=E(m,_),_+=8}}if(e.decodeStrings)for(var c=0;c<r.extraFields.length;c++){var g=r.extraFields[c];if(g.id===28789){if(g.data.length<6||g.data.readUInt8(0)!==1)continue;var v=g.data.readUInt32LE(1);if(i.unsigned(t.slice(0,r.fileNameLength))!==v)continue;r.fileName=T(g.data,5,g.data.length,!0);break}}if(e.validateEntrySizes&&r.compressionMethod===0){var b=r.uncompressedSize;if(r.isEncrypted()&&(b+=12),r.compressedSize!==b){var x=`compressed/uncompressed size mismatch for stored file: `+r.compressedSize+` != `+r.uncompressedSize;return h(e,Error(x))}}if(e.decodeStrings){e.strictFileNames||(r.fileName=r.fileName.replace(/\\/g,`/`));var S=y(r.fileName,e.validateFileNameOptions);if(S!=null)return h(e,Error(S))}e.emit(`entry`,r),e.lazyEntries||e._readEntry()}})}})}},m.prototype.openReadStream=function(e,t,r){var i=this,a=0,o=e.compressedSize;if(r==null)r=t,t={};else{if(t.decrypt!=null){if(!e.isEncrypted())throw Error(`options.decrypt can only be specified for encrypted entries`);if(t.decrypt!==!1)throw Error(`invalid options.decrypt value: `+t.decrypt);if(e.isCompressed()&&t.decompress!==!1)throw Error(`entry is encrypted and compressed, and options.decompress !== false`)}if(t.decompress!=null){if(!e.isCompressed())throw Error(`options.decompress can only be specified for compressed entries`);if(t.decompress!==!1&&t.decompress!==!0)throw Error(`invalid options.decompress value: `+t.decompress)}if(t.start!=null||t.end!=null){if(e.isCompressed()&&t.decompress!==!1)throw Error(`start/end range not allowed for compressed entry without options.decompress === false`);if(e.isEncrypted()&&t.decrypt!==!1)throw Error(`start/end range not allowed for encrypted entry without options.decrypt === false`)}if(t.start!=null){if(a=t.start,a<0)throw Error(`options.start < 0`);if(a>e.compressedSize)throw Error(`options.start > entry.compressedSize`)}if(t.end!=null){if(o=t.end,o<0)throw Error(`options.end < 0`);if(o>e.compressedSize)throw Error(`options.end > entry.compressedSize`);if(o<a)throw Error(`options.end < options.start`)}}if(!i.isOpen)return r(Error(`closed`));if(e.isEncrypted()&&t.decrypt!==!1)return r(Error(`entry is encrypted, and options.decrypt !== false`));i.reader.ref();var s=D(30);b(i.reader,s,0,s.length,e.relativeOffsetOfLocalHeader,function(c){try{if(c)return r(c);var l=s.readUInt32LE(0);if(l!==67324752)return r(Error(`invalid local file header signature: 0x`+l.toString(16)));var u=s.readUInt16LE(26),d=s.readUInt16LE(28),f=e.relativeOffsetOfLocalHeader+s.length+u+d,p;if(e.compressionMethod===0)p=!1;else if(e.compressionMethod===8)p=t.decompress==null||t.decompress;else return r(Error(`unsupported compression method: `+e.compressionMethod));var m=f,h=m+e.compressedSize;if(e.compressedSize!==0&&h>i.fileSize)return r(Error(`file data overflows file bounds: `+m+` + `+e.compressedSize+` > `+i.fileSize));var g=i.reader.createReadStream({start:m+a,end:m+o}),_=g;if(p){var v=!1,y=n.createInflateRaw();g.on(`error`,function(e){setImmediate(function(){v||y.emit(`error`,e)})}),g.pipe(y),i.validateEntrySizes?(_=new x(e.uncompressedSize),y.on(`error`,function(e){setImmediate(function(){v||_.emit(`error`,e)})}),y.pipe(_)):_=y,_.destroy=function(){v=!0,y!==_&&y.unpipe(_),g.unpipe(y),g.destroy()}}r(null,_)}finally{i.reader.unref()}})};function _(){}_.prototype.getLastModDate=function(){return v(this.lastModFileDate,this.lastModFileTime)},_.prototype.isEncrypted=function(){return!!(this.generalPurposeBitFlag&1)},_.prototype.isCompressed=function(){return this.compressionMethod===8};function v(e,t){var n=e&31,r=(e>>5&15)-1,i=(e>>9&127)+1980,a=0,o=(t&31)*2,s=t>>5&63,c=t>>11&31;return new Date(i,r,n,c,s,o,a)}function y(e){return e.indexOf(`\\`)===-1?/^[a-zA-Z]:/.test(e)||/^\//.test(e)?`absolute path: `+e:e.split(`/`).indexOf(`..`)===-1?null:`invalid relative path: `+e:`invalid characters in fileName: `+e}function b(e,t,n,r,i,a){if(r===0)return setImmediate(function(){a(null,D(0))});e.read(t,n,r,i,function(e,t){if(e)return a(e);if(t<r)return a(Error(`unexpected EOF`));a()})}a.inherits(x,s);function x(e){s.call(this),this.actualByteCount=0,this.expectedByteCount=e}x.prototype._transform=function(e,t,n){if(this.actualByteCount+=e.length,this.actualByteCount>this.expectedByteCount){var r=`too many bytes in the stream. expected `+this.expectedByteCount+`. got at least `+this.actualByteCount;return n(Error(r))}n(null,e)},x.prototype._flush=function(e){if(this.actualByteCount<this.expectedByteCount){var t=`not enough bytes in the stream. expected `+this.expectedByteCount+`. got only `+this.actualByteCount;return e(Error(t))}e()},a.inherits(S,o);function S(){o.call(this),this.refCount=0}S.prototype.ref=function(){this.refCount+=1},S.prototype.unref=function(){var e=this;if(--e.refCount,e.refCount>0)return;if(e.refCount<0)throw Error(`invalid unref`);e.close(t);function t(t){if(t)return e.emit(`error`,t);e.emit(`close`)}},S.prototype.createReadStream=function(e){var t=e.start,n=e.end;if(t===n){var r=new c;return setImmediate(function(){r.end()}),r}var i=this._readStreamForRange(t,n),a=!1,o=new C(this);i.on(`error`,function(e){setImmediate(function(){a||o.emit(`error`,e)})}),o.destroy=function(){i.unpipe(o),o.unref(),i.destroy()};var s=new x(n-t);return o.on(`error`,function(e){setImmediate(function(){a||s.emit(`error`,e)})}),s.destroy=function(){a=!0,o.unpipe(s),o.destroy()},i.pipe(o).pipe(s)},S.prototype._readStreamForRange=function(e,t){throw Error(`not implemented`)},S.prototype.read=function(e,t,n,r,i){var a=this.createReadStream({start:r,end:r+n}),o=new l,s=0;o._write=function(n,r,i){n.copy(e,t+s,0,n.length),s+=n.length,i()},o.on(`finish`,i),a.on(`error`,function(e){i(e)}),a.pipe(o)},S.prototype.close=function(e){setImmediate(e)},a.inherits(C,c);function C(e){c.call(this),this.context=e,this.context.ref(),this.unreffedYet=!1}C.prototype._flush=function(e){this.unref(),e()},C.prototype.unref=function(e){this.unreffedYet||(this.unreffedYet=!0,this.context.unref())};var w=`\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`;function T(e,t,n,r){if(r)return e.toString(`utf8`,t,n);for(var i=``,a=t;a<n;a++)i+=w[e[a]];return i}function E(e,t){var n=e.readUInt32LE(t);return e.readUInt32LE(t+4)*4294967296+n}var D=typeof Buffer.allocUnsafe==`function`?function(e){return Buffer.allocUnsafe(e)}:function(e){return new Buffer(e)};function O(e){if(e)throw e}})),Gy=L(((e,t)=>{var n=By()(`extract-zip`),{createWriteStream:r,promises:i}=R(`fs`),a=rv(),o=R(`path`),{promisify:s}=R(`util`),c=R(`stream`),l=s(Wy().open),u=s(c.pipeline),d=class{constructor(e,t){this.zipPath=e,this.opts=t}async extract(){return n(`opening`,this.zipPath,`with opts`,this.opts),this.zipfile=await l(this.zipPath,{lazyEntries:!0}),this.canceled=!1,new Promise((e,t)=>{this.zipfile.on(`error`,e=>{this.canceled=!0,t(e)}),this.zipfile.readEntry(),this.zipfile.on(`close`,()=>{this.canceled||(n(`zip extraction complete`),e())}),this.zipfile.on(`entry`,async e=>{if(this.canceled){n(`skipping entry`,e.fileName,{cancelled:this.canceled});return}if(n(`zipfile entry`,e.fileName),e.fileName.startsWith(`__MACOSX/`)){this.zipfile.readEntry();return}let r=o.dirname(o.join(this.opts.dir,e.fileName));try{await i.mkdir(r,{recursive:!0});let t=await i.realpath(r);if(o.relative(this.opts.dir,t).split(o.sep).includes(`..`))throw Error(`Out of bound path "${t}" found while processing file ${e.fileName}`);await this.extractEntry(e),n(`finished processing`,e.fileName),this.zipfile.readEntry()}catch(e){this.canceled=!0,this.zipfile.close(),t(e)}})})}async extractEntry(e){if(this.canceled){n(`skipping entry extraction`,e.fileName,{cancelled:this.canceled});return}this.opts.onEntry&&this.opts.onEntry(e,this.zipfile);let t=o.join(this.opts.dir,e.fileName),c=e.externalFileAttributes>>16&65535,l=61440,d=(c&l)==40960,f=(c&l)==16384;!f&&e.fileName.endsWith(`/`)&&(f=!0);let p=e.versionMadeBy>>8;f||=p===0&&e.externalFileAttributes===16,n(`extracting entry`,{filename:e.fileName,isDir:f,isSymlink:d});let m=this.getExtractedMode(c,f)&511,h=f?t:o.dirname(t),g={recursive:!0};if(f&&(g.mode=m),n(`mkdir`,{dir:h,...g}),await i.mkdir(h,g),f)return;n(`opening read stream`,t);let _=await s(this.zipfile.openReadStream.bind(this.zipfile))(e);if(d){let e=await a(_);n(`creating symlink`,e,t),await i.symlink(e,t)}else await u(_,r(t,{mode:m}))}getExtractedMode(e,t){let n=e;return n===0&&(t?(this.opts.defaultDirMode&&(n=parseInt(this.opts.defaultDirMode,10)),n||=493):(this.opts.defaultFileMode&&(n=parseInt(this.opts.defaultFileMode,10)),n||=420)),n}};t.exports=async function(e,t){if(n(`creating target directory`,t.dir),!o.isAbsolute(t.dir))throw Error(`Target directory is expected to be absolute`);return await i.mkdir(t.dir,{recursive:!0}),t.dir=await i.realpath(t.dir),new d(e,t).extract()}})),Ky=be(Jv(),1),qy=be(Fy(),1),Jy=be(Gy(),1),Yy={18:{version:`v18.20.8`},19:{version:`v19.9.0`},20:{version:`v20.20.2`},21:{version:`v21.7.3`},22:{version:`v22.23.2`},23:{version:`v23.11.1`},24:{version:`v24.21.0`},25:{version:`v25.9.0`},26:{version:`v26.8.2`}},Xy=process.platform===`win32`;function Zy(e){if(typeof e!=`string`||!/^\d+(\.\d+){0,2}$/.test(e))throw Error(`nodeVersion 应为 "18" | "18.1" | "18.1.5" 形式(1~3 段数字),收到:${e}`);let t=e.split(`.`).map(Number),n=Object.entries(Yy),r=n.find(([,e])=>{let n=e.version.replace(/^v/,``).split(`.`).map(Number);return t.every((e,t)=>n[t]===e)});if(!r)throw Error(`ezn 内置版本表无匹配 Node ${e} 的版本(当前内置:${n.map(([e,t])=>`${e}=${t.version}`).join(`、`)})。可改传主版本号(如 18),或经 scripts/update-node-assets.mjs 更新版本表。`);return r[1].version}function Qy(e){return Xy?w(e,`node.exe`):w(e,`bin`,`node`)}function $y(){return`${process.platform}-${process.arch}`}function eb(e){let t=T(e);return d(Qy(t))?t:null}function tb(e,t){return[w(e,`node_modules`,`npm`,`bin`,`${t}-cli.js`),w(e,`lib`,`node_modules`,`npm`,`bin`,`${t}-cli.js`)]}function nb(e,t){let n=tb(e,t),r=n.find(e=>d(e));if(!r)throw Error([`未找到自带 ${t}(该目录可能不是完整的 Node 运行时)。已查找以下位置:`,...n.map(e=>` - ${e}`),`可尝试的恢复方式:`,` 1. 托管运行时(<appDir>/node):删除该目录后重新启动服务,由引导重新落位完整运行时;`,` 2. 手工安装的平铺运行时:请确认发行包完整(含自带 npm/npx),必要时重新解压放置。`].join(`
|
|
82
|
-
`));return r}function rb(e){return eb(e)!==null&&tb(e,`npm`).some(e=>d(e))}var ib=[`.cmd`,`.bat`,`.exe`];function ab(e,t){if(t.includes(`/`)||t.includes(`\\`))return null;let n=Xy?ib.map(n=>w(e,`${t}${n}`)):[w(e,t)];return n.push(w(e,`node_modules`,`.bin`,t)),n.find(e=>d(e))??null}function ob(e){return(Xy?[e,w(e,`node_modules`,`.bin`)]:[w(e,`bin`),e]).join(S)+S}var sb={"win32-x64":{dir:`win-x64`,ext:`zip`},"win32-arm64":{dir:`win-arm64`,ext:`zip`},"darwin-arm64":{dir:`darwin-arm64`,ext:`tar.gz`},"darwin-x64":{dir:`darwin-x64`,ext:`tar.gz`},"linux-x64":{dir:`linux-x64`,ext:`tar.gz`},"linux-arm64":{dir:`linux-arm64`,ext:`tar.gz`}},cb=process.platform===`win32`?[[`node_modules`]]:[[`lib`,`node_modules`]];async function lb(e,t,n){let r=`node-${e}-${n.platform.dir}.${n.platform.ext}`,i=w(t,`node.download.tmp`),a=w(t,`node.extract.tmp`),o=()=>{g(i,{force:!0}),g(a,{recursive:!0,force:!0})},s=[];n.mirror&&s.push(n.mirror.replace(/\/+$/,``)),s.push(`https://registry.npmmirror.com/-/binary/node`,`https://nodejs.org/dist`),g(i,{force:!0}),g(a,{recursive:!0,force:!0}),f(a,{recursive:!0});for(let t=0;t<s.length;t++){let c=s[t],l=`${c}/${e}/${r}`;console.error(`[ezn] (${t+1}/${s.length}) 正在下载 ${r}\n[ezn] 来源:${c}`);try{let e=20971520,t=Ky.default.stream(l,{decompress:!1,timeout:{connect:3e4,response:6e4,socket:6e4}});t.on(`downloadProgress`,t=>{t.transferred>=e&&(console.error(`[ezn] 已下载 ${Math.round(t.transferred/1048576)} MB ...`),e+=20971520)}),await de(t,u(i)),console.error(`[ezn] 下载完成,正在解压 ...`),n.platform.ext===`zip`?await(0,Jy.default)(i,{dir:a}):await qy.x({file:i,cwd:a});let r=m(a),s=r.length===1&&r[0]!==void 0&&v(w(a,r[0])).isDirectory()?w(a,r[0]):a;return g(i,{force:!0}),{src:s,cleanup:o}}catch(e){console.error(`[ezn] 该源失败:${e instanceof Error?e.message:String(e)}`),g(i,{force:!0}),g(a,{recursive:!0,force:!0}),f(a,{recursive:!0})}}g(a,{recursive:!0,force:!0});let c=s[s.length-1]??`https://nodejs.org/dist`;throw Error([`Node 运行时下载失败:所有镜像源均不可用。`,`可尝试的恢复方式:`,` 1. 检查网络后重试;`,` 2. 在 package.json 里配置私有镜像(目录结构需同 nodejs.org/dist)后重试,例如:`,` "ezn": { "node": "24", "mirror": "https://your-mirror.example/node-dist" }`,` 3. 手动放置:下载 ${r}(见 ${c}/${e}/),`,` 解压到 ${n.target}(如带顶层版本目录请把其内容上移一层),`,` 确保可执行文件位于 ${n.nodePath}。`].join(`
|
|
83
|
-
`))}function ub(e,t,n,r,i){if(r.some(e=>n.length<=e.length&&n.every((t,n)=>e[n]===t))&&d(t)&&v(e).isDirectory()&&v(t).isDirectory()){for(let a of m(e))ub(w(e,a),w(t,a),[...n,a],r,i);g(e,{recursive:!0,force:!0});return}if(d(t)){let e=`${t}.old-${i}`;h(t,e),console.error(`[ezn] 同名项已备份:${e}`)}h(e,t)}async function db(e,t,n={}){let r=(e,t)=>{let n=Date.now();for(let r of m(e))ub(w(e,r),w(t,r),[r],cb,n)},i=T(e),a=Zy(t),o=Qy(i),s=$y(),c=sb[s];if(!c)throw Error(`暂不支持的平台:${s}。请手动放置 Node ${a} 到 ${i},确保可执行文件位于 ${o}(Windows 为 node.exe,Unix 为 bin/node)。`);f(i,{recursive:!0});let{src:l,cleanup:u}=await lb(a,C(i),{target:i,nodePath:o,platform:c,mirror:n.mirror??null});try{r(l,i)}finally{u()}console.error(`[ezn] Node ${a} 已就绪:${i}`)}function fb(e){return e!==``&&!/[\s"^&|<>()%!]/.test(e)?e:`"${e.replace(/"/g,`\\"`)}"`}function pb(e,t,n){return n?[[e,...t].map(fb).join(` `),[]]:[e,[...t]]}function mb(e,t,n={}){return new Promise((r,i)=>{let a=le(e,t,{windowsHide:!0,...n}),o=null,s=null;a.stdout&&(o=``,a.stdout.on(`data`,e=>o=(o??``)+e)),a.stderr&&(s=``,a.stderr.on(`data`,e=>s=(s??``)+e)),a.on(`error`,i),a.on(`close`,(e,t)=>r({status:e,signal:t,stdout:o,stderr:s}))})}var hb=process.platform===`win32`;function gb(e){return typeof e==`string`?e.trim().split(/\s+/).filter(e=>e.length>0):[...e]}var _b=class e{constructor(e,t){this.path=e,this.rt=t}get npmCliPath(){return nb(this.rt,`npm`)}get npxCliPath(){return nb(this.rt,`npx`)}get major(){return e.probeMajor(this.path)}resolveArgs(e,t){let n=gb(e);if(n.length===0)throw Error(`命令为空`);let r=n[0],i=n.slice(1);return r===`node`?i:r===`npm`?[this.npmCliPath,...i]:r===`npx`?[this.npxCliPath,...i]:t===null?n:[t,...n]}resolveExec(e,t){let n=gb(e);if(n.length===0)throw Error(`命令为空`);let r=n[0],i=n.slice(1),a=this.childEnv(t.env);if(r===`node`)return{file:this.path,argv:i,shell:!1,env:a};if(r===`npm`)return{file:this.path,argv:[this.npmCliPath,...i],shell:!1,env:a};if(r===`npx`)return{file:this.path,argv:[this.npxCliPath,...i],shell:!1,env:a};let o=ab(this.rt,r);if(o!==null){let e=hb&&/\.(cmd|bat)$/i.test(o),[t,n]=pb(o,i,e);return{file:t,argv:n,shell:e,env:a}}return{file:this.path,argv:n,shell:!1,env:a}}childEnv(e){let t=e??process.env;return{...t,PATH:ob(this.rt)+(t.PATH??t.Path??``)}}execSync(e,t){let{file:n,argv:r,shell:i,env:a}=this.resolveExec(e,t??{});return ue(n,r,{windowsHide:!0,encoding:`utf8`,...t,shell:i,env:a})}exec(e,t){let{file:n,argv:r,shell:i,env:a}=this.resolveExec(e,t??{});return mb(n,r,{...t,shell:i,env:a})}npmSync(e,t){return ue(this.path,this.resolveArgs(e,this.npmCliPath),{windowsHide:!0,encoding:`utf8`,...t})}npm(e,t){return mb(this.path,this.resolveArgs(e,this.npmCliPath),t)}npxSync(e,t){return ue(this.path,this.resolveArgs(e,this.npxCliPath),{windowsHide:!0,encoding:`utf8`,...t})}npx(e,t){return mb(this.path,this.resolveArgs(e,this.npxCliPath),t)}static probeMajor(e){try{let t=ce(e,[`-v`],{encoding:`utf8`,timeout:15e3,windowsHide:!0}),n=String(t).trim().match(/^v(\d+)\./);return n?Number(n[1]):null}catch{return null}}static async ensure(t,n,r={}){let i=T(t),a=Zy(n),o=Number(a.replace(/^v/,``).split(`.`)[0]),s=w(i,`node`),c=Qy(s),l=r.nodeBin??null;if(l){if(!d(l))throw Error(`ezn.nodeBin 指定的 Node 不存在:${l}`);let t=e.probeMajor(l);if(t===null)throw Error(`ezn.nodeBin 指定的 Node 无法执行:${l}`);return t<o&&console.error(`[ezn] 警告:ezn.nodeBin 的 Node 主版本为 ${t},低于建议值 ${o},按用户指定继续。`),console.error(`[ezn] Node 运行时(ezn.nodeBin):${l}`),new e(l,s)}if(d(c)){let t=e.probeMajor(c);if(t!==null&&t>=o&&rb(s))return console.error(`[ezn] Node 运行时就绪:${c}`),new e(c,s);console.error(t===null?`[ezn] 已有 Node 运行时无法执行(疑似损坏),准备重新安装 ...`:t<o?`[ezn] 已有 Node 运行时主版本为 ${t},低于要求 ${o},准备重装 ...`:`[ezn] 已有 Node 运行时缺少自带 npm(上次落位可能中断),准备补齐 ...`)}return await db(s,n,{mirror:r.mirror??null}),new e(c,s)}},vb=`24`;async function yb(e){return(await _b.ensure(e,vb)).path}var bb=new Map,xb=1;function Sb(){return typeof process.send==`function`}function Cb(e,t={},n=3e4){if(!process.send)return Promise.reject(Error(`未由 ezllm 主进程托管(源码运行模式),该功能不可用`));let r=xb++;return new Promise((i,a)=>{let o=setTimeout(()=>{bb.delete(r),a(Error(`主进程未在 ${String(Math.round(n/1e3))}s 内响应(${e})`))},n);bb.set(r,{resolve:e=>i(e),reject:a,timer:o}),process.send?.({type:e,id:r,args:t})})}function wb(e){typeof process.send==`function`&&(process.connected===!1?e():process.connected===!0&&process.once(`disconnect`,e)),process.on(`message`,e=>{let t=e;if(!t?.type||typeof t.id!=`number`)return;let n=bb.get(t.id);n&&(bb.delete(t.id),clearTimeout(n.timer),t.error===void 0?n.resolve(t.data):n.reject(Error(t.error)))})}async function Tb(e){let t;try{t=(await e.req.json())?.enabled}catch{return e.json({ok:!1,error:`请求体不是合法 JSON`},400)}return typeof t==`boolean`?t:e.json({ok:!1,error:`body 需为 {"enabled": true|false}`},400)}var Eb=`当前为源码运行模式,更新功能不可用(仅 npm 全局安装的包支持自动更新)`,Db=`服务未由 ezllm 主进程托管,更新功能不可用;请在终端执行 ezllm update`,Ob=9e5;function kb(){if(!kt())return!1;let e=C(Dt);return x(e)===`node_modules`||x(C(e))===`node_modules`}function Ab(){let e=hu()?.autoUpdate;return typeof e!=`boolean`||e}function jb(){return kb()?Sb()?null:Db:Eb}function Mb(e){let t=new $n;return t.get(`/autostart`,t=>t.json({ok:!0,...U_(e.appDir)})),t.post(`/autostart`,async t=>{let n=await Tb(t);if(n instanceof Response)return n;if(n){let{itemPath:n}=await W_({entryJs:Nt(),env:g_(),appDir:e.appDir,nodePath:await yb(e.appDir)});return t.json({ok:!0,enabled:!0,itemPath:n,note:`已注册自启项,下次登录时自动启动服务`})}let{removed:r}=await G_({appDir:e.appDir});return t.json({ok:!0,enabled:!1,removed:r,note:r?`已移除自启项,且首次启动不再自动注册(重新开启即可解除)`:`原本未开启,无操作`})}),t.get(`/update`,e=>{let t=Lt(),n=t.pending??null,r=n!==null&&Date.now()-n.startedAt<Ob;return e.json({ok:!0,enabled:Ab(),lastCheck:t.lastCheck??null,lastApply:t.lastApply??null,pendingUpdate:r&&n?n.toVersion:null,supported:kb()&&Sb(),updating:r})}),t.post(`/update/enabled`,async e=>{let t=await Tb(e);if(t instanceof Response)return t;try{let e=hu();e&&_u({...e,autoUpdate:t})}catch{return e.json({ok:!1,error:`写入配置文件失败(文件只读或损坏)`},500)}return e.json({ok:!0,enabled:t,note:t?`自动更新已开启(主进程每小时检查一次)`:`自动更新已关闭(手动检查不受影响)`})}),t.post(`/update/check`,async e=>{let t=jb();if(t)return e.json({ok:!1,error:t},400);let n=await Cb(`update.check`);return e.json({ok:!0,...n})}),t.post(`/update/apply`,async e=>{let t=jb();if(t)return e.json({ok:!1,error:t},400);let n=await Cb(`update.apply`);return e.json({ok:!0,fromVersion:n.currentVersion,toVersion:n.latestVersion,updated:n.updated,...n.updated?{restarting:!0}:{},note:n.updated?`已开始更新 ${n.currentVersion} → ${n.latestVersion}:装好后服务会重启(期间界面请求会失败,属正常现象)`:`已是最新版本 ${n.latestVersion}`})}),t}var Nb=`服务未由 ezllm 主进程托管(源码运行模式),托管服务不可用;请用 ezllm 启动服务`;function Pb(e,t){let n={};return t===null?typeof e.name==`string`&&(n.name=e.name):n.name=t,typeof e.exec==`string`&&(n.exec=e.exec),typeof e.cwd==`string`&&(n.cwd=e.cwd),typeof e.autostart==`boolean`&&(n.autostart=e.autostart),typeof e.start==`boolean`&&(n.start=e.start),Array.isArray(e.args)&&(n.args=e.args.map(e=>String(e))),n}function Fb(){return Sb()?null:Response.json({ok:!1,error:Nb},{status:400})}function Ib(e){let t=new $n;return t.onError(sm),t.get(`/`,async e=>{let t=Fb();if(t)return t;let n=await Cb(`svc.list`);return e.json({ok:!0,...n})}),t.post(`/`,async e=>{let t=Fb();if(t)return t;let n=await tm(e);if(n===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let r=await Cb(`svc.create`,Pb(n,null));return e.json({ok:!0,...r})}),t.put(`/:name`,async e=>{let t=Fb();if(t)return t;let n=await tm(e);if(n===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let r=await Cb(`svc.update`,Pb(n,e.req.param(`name`)));return e.json({ok:!0,...r})}),t.delete(`/:name`,async e=>{let t=Fb();if(t)return t;let n=await Cb(`svc.remove`,{name:e.req.param(`name`)});return e.json({ok:!0,...n})}),t.post(`/:name/start`,async e=>{let t=Fb();if(t)return t;let n=await Cb(`child.start`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...n}})}),t.post(`/:name/stop`,async e=>{let t=Fb();if(t)return t;let n=await Cb(`child.stop`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...n}})}),t.post(`/:name/restart`,async e=>{let t=Fb();if(t)return t;let n=await Cb(`child.restart`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...n}})}),t}function Lb(e){let t=`${e}.ellm-bak`;return!d(t)&&(d(e)&&l(e,t),!0)}function Rb(e){let t=`${e}.ellm-bak`;return d(t)?(l(t,e),g(t,{force:!0}),!0):!1}function zb(e,t){return String(e||``).replace(/\/+$/,``)===String(t||``).replace(/\/+$/,``)}var Bb=w(t(),`.claude`,`settings.json`);function Vb(){if(!d(Bb))return null;try{return JSON.parse(p(Bb,`utf-8`))}catch(e){throw Error(`${Bb} 不是合法 JSON,拒绝修改(请先手工修复): ${e.message}`)}}function Hb(e){let t=Vb();return t?zb(t?.env?.ANTHROPIC_BASE_URL,e):!1}function Ub(e){f(C(Bb),{recursive:!0});let t=Vb()??{};Lb(Bb),t.env={...t.env??{}},t.env.ANTHROPIC_BASE_URL=e.gatewayBase,t.env.ANTHROPIC_AUTH_TOKEN=e.token,b(Bb,JSON.stringify(t,null,2)+`
|
|
84
|
-
`,`utf-8`)}function Wb(e){if(Rb(Bb))return!0;let t=Vb();return!t||!zb(t?.env?.ANTHROPIC_BASE_URL,e)?!1:(delete t.env.ANTHROPIC_BASE_URL,delete t.env.ANTHROPIC_AUTH_TOKEN,t.env&&Object.keys(t.env).length===0&&delete t.env,b(Bb,JSON.stringify(t,null,2)+`
|
|
85
|
-
`,`utf-8`),!0)}var Gb=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Kb=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(Gb);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};function qb(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Jb(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
|
|
91
|
+
`).reduce(s,Object.create(null)),s=(e,t)=>{let n=parseInt(t,10);if(n!==Buffer.byteLength(t)+1)return e;t=t.slice((n+` `).length);let r=t.split(`=`),i=r.shift().replace(/^SCHILY\.(dev|ino|nlink)/,`$1`);if(!i)return e;let a=r.join(`=`);return e[i]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(i)?new Date(a*1e3):/^[0-9]+$/.test(a)?+a:a,e};t.exports=i})),W_=X(((e,t)=>{t.exports=e=>{let t=e.length-1,n=-1;for(;t>-1&&e.charAt(t)===`/`;)n=t,t--;return n===-1?e:e.slice(0,n)}})),G_=X(((e,t)=>{t.exports=e=>class extends e{warn(e,t,n={}){this.file&&(n.file=this.file),this.cwd&&(n.cwd=this.cwd),n.code=t instanceof Error&&t.code||e,n.tarCode=e,!this.strict&&n.recoverable!==!1?(t instanceof Error&&(n=Object.assign(t,n),t=t.message),this.emit(`warn`,n.tarCode,t,n)):t instanceof Error?this.emit(`error`,Object.assign(t,n)):this.emit(`error`,Object.assign(Error(`${e}: ${t}`),n))}}})),K_=X(((e,t)=>{var n=[`|`,`<`,`>`,`?`,`:`],r=n.map(e=>String.fromCharCode(61440+e.charCodeAt(0))),i=new Map(n.map((e,t)=>[e,r[t]])),a=new Map(r.map((e,t)=>[e,n[t]]));t.exports={encode:e=>n.reduce((e,t)=>e.split(t).join(i.get(t)),e),decode:e=>r.reduce((e,t)=>e.split(t).join(a.get(t)),e)}})),q_=X(((e,t)=>{var{isAbsolute:n,parse:r}=Z(`path`).win32;t.exports=e=>{let t=``,i=r(e);for(;n(e)||i.root;){let n=e.charAt(0)===`/`&&e.slice(0,4)!==`//?/`?`/`:i.root;e=e.slice(n.length),t+=n,i=r(e)}return[t,e]}})),J_=X(((e,t)=>{t.exports=(e,t,n)=>(e&=4095,n&&(e=(e|384)&-19),t&&(e&256&&(e|=64),e&32&&(e|=8),e&4&&(e|=1)),e)})),Y_=X(((e,t)=>{var{Minipass:n}=P_(),r=U_(),i=H_(),a=Z(`fs`),o=Z(`path`),s=R_(),c=W_(),l=(e,t)=>t?(e=s(e).replace(/^\.(\/|$)/,``),c(t)+`/`+e):s(e),u=16777216,d=Symbol(`process`),f=Symbol(`file`),p=Symbol(`directory`),m=Symbol(`symlink`),h=Symbol(`hardlink`),g=Symbol(`header`),_=Symbol(`read`),v=Symbol(`lstat`),y=Symbol(`onlstat`),b=Symbol(`onread`),x=Symbol(`onreadlink`),S=Symbol(`openfile`),C=Symbol(`onopenfile`),w=Symbol(`close`),T=Symbol(`mode`),E=Symbol(`awaitDrain`),D=Symbol(`ondrain`),O=Symbol(`prefix`),k=Symbol(`hadError`),A=G_(),j=K_(),M=q_(),N=J_(),P=A(class extends n{constructor(e,t){if(t||={},super(t),typeof e!=`string`)throw TypeError(`path is required`);this.path=s(e),this.portable=!!t.portable,this.myuid=process.getuid&&process.getuid()||0,this.myuser=process.env.USER||``,this.maxReadSize=t.maxReadSize||u,this.linkCache=t.linkCache||new Map,this.statCache=t.statCache||new Map,this.preservePaths=!!t.preservePaths,this.cwd=s(t.cwd||process.cwd()),this.strict=!!t.strict,this.noPax=!!t.noPax,this.noMtime=!!t.noMtime,this.mtime=t.mtime||null,this.prefix=t.prefix?s(t.prefix):null,this.fd=null,this.blockLen=null,this.blockRemain=null,this.buf=null,this.offset=null,this.length=null,this.pos=null,this.remain=null,typeof t.onwarn==`function`&&this.on(`warn`,t.onwarn);let n=!1;if(!this.preservePaths){let[e,t]=M(this.path);e&&(this.path=t,n=e)}this.win32=!!t.win32||process.platform===`win32`,this.win32&&(this.path=j.decode(this.path.replace(/\\/g,`/`)),e=e.replace(/\\/g,`/`)),this.absolute=s(t.absolute||o.resolve(this.cwd,e)),this.path===``&&(this.path=`./`),n&&this.warn(`TAR_ENTRY_INFO`,`stripping ${n} from absolute path`,{entry:this,path:n+this.path}),this.statCache.has(this.absolute)?this[y](this.statCache.get(this.absolute)):this[v]()}emit(e,...t){return e===`error`&&(this[k]=!0),super.emit(e,...t)}[v](){a.lstat(this.absolute,(e,t)=>{if(e)return this.emit(`error`,e);this[y](t)})}[y](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=te(e),this.emit(`stat`,e),this[d]()}[d](){switch(this.type){case`File`:return this[f]();case`Directory`:return this[p]();case`SymbolicLink`:return this[m]();default:return this.end()}}[T](e){return N(e,this.type===`Directory`,this.portable)}[O](e){return l(e,this.prefix)}[g](){this.type===`Directory`&&this.portable&&(this.noMtime=!0),this.header=new i({path:this[O](this.path),linkpath:this.type===`Link`?this[O](this.linkpath):this.linkpath,mode:this[T](this.stat.mode),uid:this.portable?null:this.stat.uid,gid:this.portable?null:this.stat.gid,size:this.stat.size,mtime:this.noMtime?null:this.mtime||this.stat.mtime,type:this.type,uname:this.portable?null:this.stat.uid===this.myuid?this.myuser:``,atime:this.portable?null:this.stat.atime,ctime:this.portable?null:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new r({atime:this.portable?null:this.header.atime,ctime:this.portable?null:this.header.ctime,gid:this.portable?null:this.header.gid,mtime:this.noMtime?null:this.mtime||this.header.mtime,path:this[O](this.path),linkpath:this.type===`Link`?this[O](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?null:this.header.uid,uname:this.portable?null:this.header.uname,dev:this.portable?null:this.stat.dev,ino:this.portable?null:this.stat.ino,nlink:this.portable?null:this.stat.nlink}).encode()),super.write(this.header.block)}[p](){this.path.slice(-1)!==`/`&&(this.path+=`/`),this.stat.size=0,this[g](),this.end()}[m](){a.readlink(this.absolute,(e,t)=>{if(e)return this.emit(`error`,e);this[x](t)})}[x](e){this.linkpath=s(e),this[g](),this.end()}[h](e){this.type=`Link`,this.linkpath=s(o.relative(this.cwd,e)),this.stat.size=0,this[g](),this.end()}[f](){if(this.stat.nlink>1){let e=this.stat.dev+`:`+this.stat.ino;if(this.linkCache.has(e)){let t=this.linkCache.get(e);if(t.indexOf(this.cwd)===0)return this[h](t)}this.linkCache.set(e,this.absolute)}if(this[g](),this.stat.size===0)return this.end();this[S]()}[S](){a.open(this.absolute,`r`,(e,t)=>{if(e)return this.emit(`error`,e);this[C](t)})}[C](e){if(this.fd=e,this[k])return this[w]();this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let t=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(t),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[_]()}[_](){let{fd:e,buf:t,offset:n,length:r,pos:i}=this;a.read(e,t,n,r,i,(e,t)=>{if(e)return this[w](()=>this.emit(`error`,e));this[b](t)})}[w](e){a.close(this.fd,e)}[b](e){if(e<=0&&this.remain>0){let e=Error(`encountered unexpected EOF`);return e.path=this.absolute,e.syscall=`read`,e.code=`EOF`,this[w](()=>this.emit(`error`,e))}if(e>this.remain){let e=Error(`did not encounter expected EOF`);return e.path=this.absolute,e.syscall=`read`,e.code=`EOF`,this[w](()=>this.emit(`error`,e))}if(e===this.remain)for(let t=e;t<this.length&&e<this.blockRemain;t++)this.buf[t+this.offset]=0,e++,this.remain++;let t=this.offset===0&&e===this.buf.length?this.buf:this.buf.slice(this.offset,this.offset+e);this.write(t)?this[D]():this[E](()=>this[D]())}[E](e){this.once(`drain`,e)}write(e){if(this.blockRemain<e.length){let e=Error(`writing more data than expected`);return e.path=this.absolute,this.emit(`error`,e)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e)}[D](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[w](e=>e?this.emit(`error`,e):this.end());this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[_]()}}),F=class extends P{[v](){this[y](a.lstatSync(this.absolute))}[m](){this[x](a.readlinkSync(this.absolute))}[S](){this[C](a.openSync(this.absolute,`r`))}[_](){let e=!0;try{let{fd:t,buf:n,offset:r,length:i,pos:o}=this,s=a.readSync(t,n,r,i,o);this[b](s),e=!1}finally{if(e)try{this[w](()=>{})}catch{}}}[E](e){e()}[w](e){a.closeSync(this.fd),e()}},ee=A(class extends n{constructor(e,t){t||={},super(t),this.preservePaths=!!t.preservePaths,this.portable=!!t.portable,this.strict=!!t.strict,this.noPax=!!t.noPax,this.noMtime=!!t.noMtime,this.readEntry=e,this.type=e.type,this.type===`Directory`&&this.portable&&(this.noMtime=!0),this.prefix=t.prefix||null,this.path=s(e.path),this.mode=this[T](e.mode),this.uid=this.portable?null:e.uid,this.gid=this.portable?null:e.gid,this.uname=this.portable?null:e.uname,this.gname=this.portable?null:e.gname,this.size=e.size,this.mtime=this.noMtime?null:t.mtime||e.mtime,this.atime=this.portable?null:e.atime,this.ctime=this.portable?null:e.ctime,this.linkpath=s(e.linkpath),typeof t.onwarn==`function`&&this.on(`warn`,t.onwarn);let n=!1;if(!this.preservePaths){let[e,t]=M(this.path);e&&(this.path=t,n=e)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.header=new i({path:this[O](this.path),linkpath:this.type===`Link`?this[O](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?null:this.uid,gid:this.portable?null:this.gid,size:this.size,mtime:this.noMtime?null:this.mtime,type:this.type,uname:this.portable?null:this.uname,atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime}),n&&this.warn(`TAR_ENTRY_INFO`,`stripping ${n} from absolute path`,{entry:this,path:n+this.path}),this.header.encode()&&!this.noPax&&super.write(new r({atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime,gid:this.portable?null:this.gid,mtime:this.noMtime?null:this.mtime,path:this[O](this.path),linkpath:this.type===`Link`?this[O](this.linkpath):this.linkpath,size:this.size,uid:this.portable?null:this.uid,uname:this.portable?null:this.uname,dev:this.portable?null:this.readEntry.dev,ino:this.portable?null:this.readEntry.ino,nlink:this.portable?null:this.readEntry.nlink}).encode()),super.write(this.header.block),e.pipe(this)}[O](e){return l(e,this.prefix)}[T](e){return N(e,this.type===`Directory`,this.portable)}write(e){let t=e.length;if(t>this.blockRemain)throw Error(`writing more to entry than is appropriate`);return this.blockRemain-=t,super.write(e)}end(){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),super.end()}});P.Sync=F,P.Tar=ee;var te=e=>e.isFile()?`File`:e.isDirectory()?`Directory`:e.isSymbolicLink()?`SymbolicLink`:`Unsupported`;t.exports=P})),X_=X(((e,t)=>{t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}})),Z_=X(((e,t)=>{t.exports=n,n.Node=o,n.create=n;function n(e){var t=this;if(t instanceof n||(t=new n),t.tail=null,t.head=null,t.length=0,e&&typeof e.forEach==`function`)e.forEach(function(e){t.push(e)});else if(arguments.length>0)for(var r=0,i=arguments.length;r<i;r++)t.push(arguments[r]);return t}n.prototype.removeNode=function(e){if(e.list!==this)throw Error(`removing node which does not belong to this list`);var t=e.next,n=e.prev;return t&&(t.prev=n),n&&(n.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=n),e.list.length--,e.next=null,e.prev=null,e.list=null,t},n.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||=e,this.length++}},n.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||=e,this.length++}},n.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)i(this,arguments[e]);return this.length},n.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)a(this,arguments[e]);return this.length},n.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},n.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},n.prototype.forEach=function(e,t){t||=this;for(var n=this.head,r=0;n!==null;r++)e.call(t,n.value,r,this),n=n.next},n.prototype.forEachReverse=function(e,t){t||=this;for(var n=this.tail,r=this.length-1;n!==null;r--)e.call(t,n.value,r,this),n=n.prev},n.prototype.get=function(e){for(var t=0,n=this.head;n!==null&&t<e;t++)n=n.next;if(t===e&&n!==null)return n.value},n.prototype.getReverse=function(e){for(var t=0,n=this.tail;n!==null&&t<e;t++)n=n.prev;if(t===e&&n!==null)return n.value},n.prototype.map=function(e,t){t||=this;for(var r=new n,i=this.head;i!==null;)r.push(e.call(t,i.value,this)),i=i.next;return r},n.prototype.mapReverse=function(e,t){t||=this;for(var r=new n,i=this.tail;i!==null;)r.push(e.call(t,i.value,this)),i=i.prev;return r},n.prototype.reduce=function(e,t){var n,r=this.head;if(arguments.length>1)n=t;else if(this.head)r=this.head.next,n=this.head.value;else throw TypeError(`Reduce of empty list with no initial value`);for(var i=0;r!==null;i++)n=e(n,r.value,i),r=r.next;return n},n.prototype.reduceReverse=function(e,t){var n,r=this.tail;if(arguments.length>1)n=t;else if(this.tail)r=this.tail.prev,n=this.tail.value;else throw TypeError(`Reduce of empty list with no initial value`);for(var i=this.length-1;r!==null;i--)n=e(n,r.value,i),r=r.prev;return n},n.prototype.toArray=function(){for(var e=Array(this.length),t=0,n=this.head;n!==null;t++)e[t]=n.value,n=n.next;return e},n.prototype.toArrayReverse=function(){for(var e=Array(this.length),t=0,n=this.tail;n!==null;t++)e[t]=n.value,n=n.prev;return e},n.prototype.slice=function(e,t){t||=this.length,t<0&&(t+=this.length),e||=0,e<0&&(e+=this.length);var r=new n;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var i=0,a=this.head;a!==null&&i<e;i++)a=a.next;for(;a!==null&&i<t;i++,a=a.next)r.push(a.value);return r},n.prototype.sliceReverse=function(e,t){t||=this.length,t<0&&(t+=this.length),e||=0,e<0&&(e+=this.length);var r=new n;if(t<e||t<0)return r;e<0&&(e=0),t>this.length&&(t=this.length);for(var i=this.length,a=this.tail;a!==null&&i>t;i--)a=a.prev;for(;a!==null&&i>e;i--,a=a.prev)r.push(a.value);return r},n.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var i=0,a=this.head;a!==null&&i<e;i++)a=a.next;for(var o=[],i=0;a&&i<t;i++)o.push(a.value),a=this.removeNode(a);a===null&&(a=this.tail),a!==this.head&&a!==this.tail&&(a=a.prev);for(var i=0;i<n.length;i++)a=r(this,a,n[i]);return o},n.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;n!==null;n=n.prev){var r=n.prev;n.prev=n.next,n.next=r}return this.head=t,this.tail=e,this};function r(e,t,n){var r=t===e.head?new o(n,null,t,e):new o(n,t,t.next,e);return r.next===null&&(e.tail=r),r.prev===null&&(e.head=r),e.length++,r}function i(e,t){e.tail=new o(t,e.tail,null,e),e.head||=e.tail,e.length++}function a(e,t){e.head=new o(t,null,e.head,e),e.tail||=e.head,e.length++}function o(e,t,n,r){if(!(this instanceof o))return new o(e,t,n,r);this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,n?(n.prev=this,this.next=n):this.next=null}try{X_()(n)}catch{}})),Q_=X(((e,t)=>{var n=class{constructor(e,t){this.path=e||`./`,this.absolute=t,this.entry=null,this.stat=null,this.readdir=null,this.pending=!1,this.ignore=!1,this.piped=!1}},{Minipass:r}=P_(),i=L_(),a=z_(),o=Y_(),s=o.Sync,c=o.Tar,l=Z_(),u=Buffer.alloc(1024),d=Symbol(`onStat`),f=Symbol(`ended`),p=Symbol(`queue`),m=Symbol(`current`),h=Symbol(`process`),g=Symbol(`processing`),_=Symbol(`processJob`),v=Symbol(`jobs`),y=Symbol(`jobDone`),b=Symbol(`addFSEntry`),x=Symbol(`addTarEntry`),S=Symbol(`stat`),C=Symbol(`readdir`),w=Symbol(`onreaddir`),T=Symbol(`pipe`),E=Symbol(`entry`),D=Symbol(`entryOpt`),O=Symbol(`writeEntryClass`),k=Symbol(`write`),A=Symbol(`ondrain`),j=Z(`fs`),M=Z(`path`),N=G_(),P=R_(),F=N(class extends r{constructor(e){if(super(e),e||=Object.create(null),this.opt=e,this.file=e.file||``,this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=P(e.prefix||``),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this[O]=o,typeof e.onwarn==`function`&&this.on(`warn`,e.onwarn),this.portable=!!e.portable,this.zip=null,e.gzip||e.brotli){if(e.gzip&&e.brotli)throw TypeError(`gzip and brotli are mutually exclusive`);e.gzip&&(typeof e.gzip!=`object`&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new i.Gzip(e.gzip)),e.brotli&&(typeof e.brotli!=`object`&&(e.brotli={}),this.zip=new i.BrotliCompress(e.brotli)),this.zip.on(`data`,e=>super.write(e)),this.zip.on(`end`,e=>super.end()),this.zip.on(`drain`,e=>this[A]()),this.on(`resume`,e=>this.zip.resume())}else this.on(`drain`,this[A]);this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,this.mtime=e.mtime||null,this.filter=typeof e.filter==`function`?e.filter:e=>!0,this[p]=new l,this[v]=0,this.jobs=+e.jobs||4,this[g]=!1,this[f]=!1}[k](e){return super.write(e)}add(e){return this.write(e),this}end(e){return e&&this.write(e),this[f]=!0,this[h](),this}write(e){if(this[f])throw Error(`write after end`);return e instanceof a?this[x](e):this[b](e),this.flowing}[x](e){let t=P(M.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let r=new n(e.path,t,!1);r.entry=new c(e,this[D](r)),r.entry.on(`end`,e=>this[y](r)),this[v]+=1,this[p].push(r)}this[h]()}[b](e){let t=P(M.resolve(this.cwd,e));this[p].push(new n(e,t)),this[h]()}[S](e){e.pending=!0,this[v]+=1,j[this.follow?`stat`:`lstat`](e.absolute,(t,n)=>{e.pending=!1,--this[v],t?this.emit(`error`,t):this[d](e,n)})}[d](e,t){this.statCache.set(e.absolute,t),e.stat=t,this.filter(e.path,t)||(e.ignore=!0),this[h]()}[C](e){e.pending=!0,this[v]+=1,j.readdir(e.absolute,(t,n)=>{if(e.pending=!1,--this[v],t)return this.emit(`error`,t);this[w](e,n)})}[w](e,t){this.readdirCache.set(e.absolute,t),e.readdir=t,this[h]()}[h](){if(!this[g]){this[g]=!0;for(let e=this[p].head;e!==null&&this[v]<this.jobs;e=e.next)if(this[_](e.value),e.value.ignore){let t=e.next;this[p].removeNode(e),e.next=t}this[g]=!1,this[f]&&!this[p].length&&this[v]===0&&(this.zip?this.zip.end(u):(super.write(u),super.end()))}}get[m](){return this[p]&&this[p].head&&this[p].head.value}[y](e){this[p].shift(),--this[v],this[h]()}[_](e){e.pending||(e.entry?e===this[m]&&!e.piped&&this[T](e):(e.stat||(this.statCache.has(e.absolute)?this[d](e,this.statCache.get(e.absolute)):this[S](e)),e.stat&&(e.ignore||!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir&&(this.readdirCache.has(e.absolute)?this[w](e,this.readdirCache.get(e.absolute)):this[C](e),!e.readdir)||(e.entry=this[E](e),e.entry?e===this[m]&&!e.piped&&this[T](e):e.ignore=!0))))}[D](e){return{onwarn:(e,t,n)=>this.warn(e,t,n),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix}}[E](e){this[v]+=1;try{return new this[O](e.path,this[D](e)).on(`end`,()=>this[y](e)).on(`error`,e=>this.emit(`error`,e))}catch(e){this.emit(`error`,e)}}[A](){this[m]&&this[m].entry&&this[m].entry.resume()}[T](e){e.piped=!0,e.readdir&&e.readdir.forEach(t=>{let n=e.path,r=n===`./`?``:n.replace(/\/*$/,`/`);this[b](r+t)});let t=e.entry,n=this.zip;n?t.on(`data`,e=>{n.write(e)||t.pause()}):t.on(`data`,e=>{super.write(e)||t.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}});F.Sync=class extends F{constructor(e){super(e),this[O]=s}pause(){}resume(){}[S](e){let t=this.follow?`statSync`:`lstatSync`;this[d](e,j[t](e.absolute))}[C](e,t){this[w](e,j.readdirSync(e.absolute))}[T](e){let t=e.entry,n=this.zip;e.readdir&&e.readdir.forEach(t=>{let n=e.path,r=n===`./`?``:n.replace(/\/*$/,`/`);this[b](r+t)}),n?t.on(`data`,e=>{n.write(e)}):t.on(`data`,e=>{super[k](e)})}},t.exports=F})),$_=X((e=>{var t=I_(),n=Z(`events`).EventEmitter,r=Z(`fs`),i=r.writev;if(!i){let e=process.binding(`fs`),t=e.FSReqWrap||e.FSReqCallback;i=(n,r,i,a)=>{let o=(e,t)=>a(e,t,r),s=new t;s.oncomplete=o,e.writeBuffers(n,r,i,s)}}var a=Symbol(`_autoClose`),o=Symbol(`_close`),s=Symbol(`_ended`),c=Symbol(`_fd`),l=Symbol(`_finished`),u=Symbol(`_flags`),d=Symbol(`_flush`),f=Symbol(`_handleChunk`),p=Symbol(`_makeBuf`),m=Symbol(`_mode`),h=Symbol(`_needDrain`),g=Symbol(`_onerror`),_=Symbol(`_onopen`),v=Symbol(`_onread`),y=Symbol(`_onwrite`),b=Symbol(`_open`),x=Symbol(`_path`),S=Symbol(`_pos`),C=Symbol(`_queue`),w=Symbol(`_read`),T=Symbol(`_readSize`),E=Symbol(`_reading`),D=Symbol(`_remain`),O=Symbol(`_size`),k=Symbol(`_write`),A=Symbol(`_writing`),j=Symbol(`_defaultFlag`),M=Symbol(`_errored`),N=class extends t{constructor(e,t){if(t||={},super(t),this.readable=!0,this.writable=!1,typeof e!=`string`)throw TypeError(`path must be a string`);this[M]=!1,this[c]=typeof t.fd==`number`?t.fd:null,this[x]=e,this[T]=t.readSize||16777216,this[E]=!1,this[O]=typeof t.size==`number`?t.size:1/0,this[D]=this[O],this[a]=typeof t.autoClose!=`boolean`||t.autoClose,typeof this[c]==`number`?this[w]():this[b]()}get fd(){return this[c]}get path(){return this[x]}write(){throw TypeError(`this is a readable stream`)}end(){throw TypeError(`this is a readable stream`)}[b](){r.open(this[x],`r`,(e,t)=>this[_](e,t))}[_](e,t){e?this[g](e):(this[c]=t,this.emit(`open`,t),this[w]())}[p](){return Buffer.allocUnsafe(Math.min(this[T],this[D]))}[w](){if(!this[E]){this[E]=!0;let e=this[p]();if(e.length===0)return process.nextTick(()=>this[v](null,0,e));r.read(this[c],e,0,e.length,null,(e,t,n)=>this[v](e,t,n))}}[v](e,t,n){this[E]=!1,e?this[g](e):this[f](t,n)&&this[w]()}[o](){if(this[a]&&typeof this[c]==`number`){let e=this[c];this[c]=null,r.close(e,e=>e?this.emit(`error`,e):this.emit(`close`))}}[g](e){this[E]=!0,this[o](),this.emit(`error`,e)}[f](e,t){let n=!1;return this[D]-=e,e>0&&(n=super.write(e<t.length?t.slice(0,e):t)),(e===0||this[D]<=0)&&(n=!1,this[o](),super.end()),n}emit(e,t){switch(e){case`prefinish`:case`finish`:break;case`drain`:typeof this[c]==`number`&&this[w]();break;case`error`:return this[M]?void 0:(this[M]=!0,super.emit(e,t));default:return super.emit(e,t)}}},P=class extends N{[b](){let e=!0;try{this[_](null,r.openSync(this[x],`r`)),e=!1}finally{e&&this[o]()}}[w](){let e=!0;try{if(!this[E]){this[E]=!0;do{let e=this[p](),t=e.length===0?0:r.readSync(this[c],e,0,e.length,null);if(!this[f](t,e))break}while(1);this[E]=!1}e=!1}finally{e&&this[o]()}}[o](){if(this[a]&&typeof this[c]==`number`){let e=this[c];this[c]=null,r.closeSync(e),this.emit(`close`)}}},F=class extends n{constructor(e,t){t||={},super(t),this.readable=!1,this.writable=!0,this[M]=!1,this[A]=!1,this[s]=!1,this[h]=!1,this[C]=[],this[x]=e,this[c]=typeof t.fd==`number`?t.fd:null,this[m]=t.mode===void 0?438:t.mode,this[S]=typeof t.start==`number`?t.start:null,this[a]=typeof t.autoClose!=`boolean`||t.autoClose;let n=this[S]===null?`w`:`r+`;this[j]=t.flags===void 0,this[u]=this[j]?n:t.flags,this[c]===null&&this[b]()}emit(e,t){if(e===`error`){if(this[M])return;this[M]=!0}return super.emit(e,t)}get fd(){return this[c]}get path(){return this[x]}[g](e){this[o](),this[A]=!0,this.emit(`error`,e)}[b](){r.open(this[x],this[u],this[m],(e,t)=>this[_](e,t))}[_](e,t){this[j]&&this[u]===`r+`&&e&&e.code===`ENOENT`?(this[u]=`w`,this[b]()):e?this[g](e):(this[c]=t,this.emit(`open`,t),this[d]())}end(e,t){return e&&this.write(e,t),this[s]=!0,!this[A]&&!this[C].length&&typeof this[c]==`number`&&this[y](null,0),this}write(e,t){return typeof e==`string`&&(e=Buffer.from(e,t)),this[s]?(this.emit(`error`,Error(`write() after end()`)),!1):this[c]===null||this[A]||this[C].length?(this[C].push(e),this[h]=!0,!1):(this[A]=!0,this[k](e),!0)}[k](e){r.write(this[c],e,0,e.length,this[S],(e,t)=>this[y](e,t))}[y](e,t){e?this[g](e):(this[S]!==null&&(this[S]+=t),this[C].length?this[d]():(this[A]=!1,this[s]&&!this[l]?(this[l]=!0,this[o](),this.emit(`finish`)):this[h]&&(this[h]=!1,this.emit(`drain`))))}[d](){if(this[C].length===0)this[s]&&this[y](null,0);else if(this[C].length===1)this[k](this[C].pop());else{let e=this[C];this[C]=[],i(this[c],e,this[S],(e,t)=>this[y](e,t))}}[o](){if(this[a]&&typeof this[c]==`number`){let e=this[c];this[c]=null,r.close(e,e=>e?this.emit(`error`,e):this.emit(`close`))}}},ee=class extends F{[b](){let e;if(this[j]&&this[u]===`r+`)try{e=r.openSync(this[x],this[u],this[m])}catch(e){if(e.code===`ENOENT`)return this[u]=`w`,this[b]();throw e}else e=r.openSync(this[x],this[u],this[m]);this[_](null,e)}[o](){if(this[a]&&typeof this[c]==`number`){let e=this[c];this[c]=null,r.closeSync(e),this.emit(`close`)}}[k](e){let t=!0;try{this[y](null,r.writeSync(this[c],e,0,e.length,this[S])),t=!1}finally{if(t)try{this[o]()}catch{}}}};e.ReadStream=N,e.ReadStreamSync=P,e.WriteStream=F,e.WriteStreamSync=ee})),ev=X(((e,t)=>{var n=G_(),r=H_(),i=Z(`events`),a=Z_(),o=1048576,s=z_(),c=U_(),l=L_(),{nextTick:u}=Z(`process`),d=Buffer.from([31,139]),f=Symbol(`state`),p=Symbol(`writeEntry`),m=Symbol(`readEntry`),h=Symbol(`nextEntry`),g=Symbol(`processEntry`),_=Symbol(`extendedHeader`),v=Symbol(`globalExtendedHeader`),y=Symbol(`meta`),b=Symbol(`emitMeta`),x=Symbol(`buffer`),S=Symbol(`queue`),C=Symbol(`ended`),w=Symbol(`emittedEnd`),T=Symbol(`emit`),E=Symbol(`unzip`),D=Symbol(`consumeChunk`),O=Symbol(`consumeChunkSub`),k=Symbol(`consumeBody`),A=Symbol(`consumeMeta`),j=Symbol(`consumeHeader`),M=Symbol(`consuming`),N=Symbol(`bufferConcat`),P=Symbol(`maybeEnd`),F=Symbol(`writing`),ee=Symbol(`aborted`),te=Symbol(`onDone`),ne=Symbol(`sawValidEntry`),re=Symbol(`sawNullBlock`),ie=Symbol(`sawEOF`),ae=Symbol(`closeStream`),oe=e=>!0;t.exports=n(class extends i{constructor(e){e||={},super(e),this.file=e.file||``,this[ne]=null,this.on(te,e=>{(this[f]===`begin`||this[ne]===!1)&&this.warn(`TAR_BAD_ARCHIVE`,`Unrecognized archive format`)}),e.ondone?this.on(te,e.ondone):this.on(te,e=>{this.emit(`prefinish`),this.emit(`finish`),this.emit(`end`)}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||o,this.filter=typeof e.filter==`function`?e.filter:oe;let t=e.file&&(e.file.endsWith(`.tar.br`)||e.file.endsWith(`.tbr`));this.brotli=!e.gzip&&e.brotli!==void 0?e.brotli:t?void 0:!1,this.writable=!0,this.readable=!1,this[S]=new a,this[x]=null,this[m]=null,this[p]=null,this[f]=`begin`,this[y]=``,this[_]=null,this[v]=null,this[C]=!1,this[E]=null,this[ee]=!1,this[re]=!1,this[ie]=!1,this.on(`end`,()=>this[ae]()),typeof e.onwarn==`function`&&this.on(`warn`,e.onwarn),typeof e.onentry==`function`&&this.on(`entry`,e.onentry)}[j](e,t){this[ne]===null&&(this[ne]=!1);let n;try{n=new r(e,t,this[_],this[v])}catch(e){return this.warn(`TAR_ENTRY_INVALID`,e)}if(n.nullBlock)this[re]?(this[ie]=!0,this[f]===`begin`&&(this[f]=`header`),this[T](`eof`)):(this[re]=!0,this[T](`nullBlock`));else if(this[re]=!1,!n.cksumValid)this.warn(`TAR_ENTRY_INVALID`,`checksum failure`,{header:n});else if(!n.path)this.warn(`TAR_ENTRY_INVALID`,`path is required`,{header:n});else{let e=n.type;if(/^(Symbolic)?Link$/.test(e)&&!n.linkpath)this.warn(`TAR_ENTRY_INVALID`,`linkpath required`,{header:n});else if(!/^(Symbolic)?Link$/.test(e)&&n.linkpath)this.warn(`TAR_ENTRY_INVALID`,`linkpath forbidden`,{header:n});else{let e=this[p]=new s(n,this[_],this[v]);this[ne]||(e.remain?e.on(`end`,()=>{e.invalid||(this[ne]=!0)}):this[ne]=!0),e.meta?e.size>this.maxMetaEntrySize?(e.ignore=!0,this[T](`ignoredEntry`,e),this[f]=`ignore`,e.resume()):e.size>0&&(this[y]=``,e.on(`data`,e=>this[y]+=e),this[f]=`meta`):(this[_]=null,e.ignore=e.ignore||!this.filter(e.path,e),e.ignore?(this[T](`ignoredEntry`,e),this[f]=e.remain?`ignore`:`header`,e.resume()):(e.remain?this[f]=`body`:(this[f]=`header`,e.end()),this[m]?this[S].push(e):(this[S].push(e),this[h]())))}}}[ae](){u(()=>this.emit(`close`))}[g](e){let t=!0;return e?Array.isArray(e)?this.emit.apply(this,e):(this[m]=e,this.emit(`entry`,e),e.emittedEnd||(e.on(`end`,e=>this[h]()),t=!1)):(this[m]=null,t=!1),t}[h](){do;while(this[g](this[S].shift()));if(!this[S].length){let e=this[m];!e||e.flowing||e.size===e.remain?this[F]||this.emit(`drain`):e.once(`drain`,e=>this.emit(`drain`))}}[k](e,t){let n=this[p],r=n.blockRemain,i=r>=e.length&&t===0?e:e.slice(t,t+r);return n.write(i),n.blockRemain||(this[f]=`header`,this[p]=null,n.end()),i.length}[A](e,t){let n=this[p],r=this[k](e,t);return this[p]||this[b](n),r}[T](e,t,n){!this[S].length&&!this[m]?this.emit(e,t,n):this[S].push([e,t,n])}[b](e){switch(this[T](`meta`,this[y]),e.type){case`ExtendedHeader`:case`OldExtendedHeader`:this[_]=c.parse(this[y],this[_],!1);break;case`GlobalExtendedHeader`:this[v]=c.parse(this[y],this[v],!0);break;case`NextFileHasLongPath`:case`OldGnuLongPath`:this[_]=this[_]||Object.create(null),this[_].path=this[y].replace(/\0.*/,``);break;case`NextFileHasLongLinkpath`:this[_]=this[_]||Object.create(null),this[_].linkpath=this[y].replace(/\0.*/,``);break;default:throw Error(`unknown meta: `+e.type)}}abort(e){this[ee]=!0,this.emit(`abort`,e),this.warn(`TAR_ABORT`,e,{recoverable:!1})}write(e){if(this[ee])return;if((this[E]===null||this.brotli===void 0&&this[E]===!1)&&e){if(this[x]&&(e=Buffer.concat([this[x],e]),this[x]=null),e.length<d.length)return this[x]=e,!0;for(let t=0;this[E]===null&&t<d.length;t++)e[t]!==d[t]&&(this[E]=!1);let t=this.brotli===void 0;if(this[E]===!1&&t){if(e.length<512){if(this[C])this.brotli=!0;else return this[x]=e,!0}else try{new r(e.slice(0,512)),this.brotli=!1}catch{this.brotli=!0}}if(this[E]===null||this[E]===!1&&this.brotli){let t=this[C];this[C]=!1,this[E]=this[E]===null?new l.Unzip:new l.BrotliDecompress,this[E].on(`data`,e=>this[D](e)),this[E].on(`error`,e=>this.abort(e)),this[E].on(`end`,e=>{this[C]=!0,this[D]()}),this[F]=!0;let n=this[E][t?`end`:`write`](e);return this[F]=!1,n}}this[F]=!0,this[E]?this[E].write(e):this[D](e),this[F]=!1;let t=this[S].length?!1:!this[m]||this[m].flowing;return!t&&!this[S].length&&this[m].once(`drain`,e=>this.emit(`drain`)),t}[N](e){e&&!this[ee]&&(this[x]=this[x]?Buffer.concat([this[x],e]):e)}[P](){if(this[C]&&!this[w]&&!this[ee]&&!this[M]){this[w]=!0;let e=this[p];if(e&&e.blockRemain){let t=this[x]?this[x].length:0;this.warn(`TAR_BAD_ARCHIVE`,`Truncated input (needed ${e.blockRemain} more bytes, only ${t} available)`,{entry:e}),this[x]&&e.write(this[x]),e.end()}this[T](te)}}[D](e){if(this[M])this[N](e);else if(!e&&!this[x])this[P]();else{if(this[M]=!0,this[x]){this[N](e);let t=this[x];this[x]=null,this[O](t)}else this[O](e);for(;this[x]&&this[x].length>=512&&!this[ee]&&!this[ie];){let e=this[x];this[x]=null,this[O](e)}this[M]=!1}(!this[x]||this[C])&&this[P]()}[O](e){let t=0,n=e.length;for(;t+512<=n&&!this[ee]&&!this[ie];)switch(this[f]){case`begin`:case`header`:this[j](e,t),t+=512;break;case`ignore`:case`body`:t+=this[k](e,t);break;case`meta`:t+=this[A](e,t);break;default:throw Error(`invalid state: `+this[f])}t<n&&(this[x]=this[x]?Buffer.concat([e.slice(t),this[x]]):e.slice(t))}end(e){this[ee]||(this[E]?this[E].end(e):(this[C]=!0,this.brotli===void 0&&(e||=Buffer.alloc(0)),this.write(e)))}})})),tv=X(((e,t)=>{var n=N_(),r=ev(),i=Z(`fs`),a=$_(),o=Z(`path`),s=W_();t.exports=(e,t,r)=>{typeof e==`function`?(r=e,t=null,e={}):Array.isArray(e)&&(t=e,e={}),typeof t==`function`&&(r=t,t=null),t=t?Array.from(t):[];let i=n(e);if(i.sync&&typeof r==`function`)throw TypeError(`callback not supported for sync tar functions`);if(!i.file&&typeof r==`function`)throw TypeError(`callback only supported with file option`);return t.length&&l(i,t),i.noResume||c(i),i.file&&i.sync?u(i):i.file?d(i,r):f(i)};var c=e=>{let t=e.onentry;e.onentry=t?e=>{t(e),e.resume()}:e=>e.resume()},l=(e,t)=>{let n=new Map(t.map(e=>[s(e),!0])),r=e.filter,i=(e,t)=>{let r=t||o.parse(e).root||`.`,a=e===r?!1:n.has(e)?n.get(e):i(o.dirname(e),r);return n.set(e,a),a};e.filter=r?(e,t)=>r(e,t)&&i(s(e)):e=>i(s(e))},u=e=>{let t=f(e),n=e.file,r=!0,a;try{let o=i.statSync(n),s=e.maxReadSize||16777216;if(o.size<s)t.end(i.readFileSync(n));else{let e=0,r=Buffer.allocUnsafe(s);for(a=i.openSync(n,`r`);e<o.size;){let n=i.readSync(a,r,0,s,e);e+=n,t.write(r.slice(0,n))}t.end()}r=!1}finally{if(r&&a)try{i.closeSync(a)}catch{}}},d=(e,t)=>{let n=new r(e),o=e.maxReadSize||16777216,s=e.file,c=new Promise((e,t)=>{n.on(`error`,t),n.on(`end`,e),i.stat(s,(e,r)=>{if(e)t(e);else{let e=new a.ReadStream(s,{readSize:o,size:r.size});e.on(`error`,t),e.pipe(n)}})});return t?c.then(t,t):c},f=e=>new r(e)})),nv=X(((e,t)=>{var n=N_(),r=Q_(),i=$_(),a=tv(),o=Z(`path`);t.exports=(e,t,r)=>{if(typeof t==`function`&&(r=t),Array.isArray(e)&&(t=e,e={}),!t||!Array.isArray(t)||!t.length)throw TypeError(`no files or directories specified`);t=Array.from(t);let i=n(e);if(i.sync&&typeof r==`function`)throw TypeError(`callback not supported for sync tar functions`);if(!i.file&&typeof r==`function`)throw TypeError(`callback only supported with file option`);return i.file&&i.sync?s(i,t):i.file?c(i,t,r):i.sync?d(i,t):f(i,t)};var s=(e,t)=>{let n=new r.Sync(e),a=new i.WriteStreamSync(e.file,{mode:e.mode||438});n.pipe(a),l(n,t)},c=(e,t,n)=>{let a=new r(e),o=new i.WriteStream(e.file,{mode:e.mode||438});a.pipe(o);let s=new Promise((e,t)=>{o.on(`error`,t),o.on(`close`,e),a.on(`error`,t)});return u(a,t),n?s.then(n,n):s},l=(e,t)=>{t.forEach(t=>{t.charAt(0)===`@`?a({file:o.resolve(e.cwd,t.slice(1)),sync:!0,noResume:!0,onentry:t=>e.add(t)}):e.add(t)}),e.end()},u=(e,t)=>{for(;t.length;){let n=t.shift();if(n.charAt(0)===`@`)return a({file:o.resolve(e.cwd,n.slice(1)),noResume:!0,onentry:t=>e.add(t)}).then(n=>u(e,t));e.add(n)}e.end()},d=(e,t)=>{let n=new r.Sync(e);return l(n,t),n},f=(e,t)=>{let n=new r(e);return u(n,t),n}})),rv=X(((e,t)=>{var n=N_(),r=Q_(),i=Z(`fs`),a=$_(),o=tv(),s=Z(`path`),c=H_();t.exports=(e,t,r)=>{let i=n(e);if(!i.file)throw TypeError(`file is required`);if(i.gzip||i.brotli||i.file.endsWith(`.br`)||i.file.endsWith(`.tbr`))throw TypeError(`cannot append to compressed archives`);if(!t||!Array.isArray(t)||!t.length)throw TypeError(`no files or directories specified`);return t=Array.from(t),i.sync?l(i,t):d(i,t,r)};var l=(e,t)=>{let n=new r.Sync(e),a=!0,o,s;try{try{o=i.openSync(e.file,`r+`)}catch(t){if(t.code===`ENOENT`)o=i.openSync(e.file,`w+`);else throw t}let r=i.fstatSync(o),l=Buffer.alloc(512);POSITION:for(s=0;s<r.size;s+=512){for(let e=0,t=0;e<512;e+=t){if(t=i.readSync(o,l,e,l.length-e,s+e),s===0&&l[0]===31&&l[1]===139)throw Error(`cannot append to compressed archives`);if(!t)break POSITION}let t=new c(l);if(!t.cksumValid)break;let n=512*Math.ceil(t.size/512);if(s+n+512>r.size)break;s+=n,e.mtimeCache&&e.mtimeCache.set(t.path,t.mtime)}a=!1,u(e,n,s,o,t)}finally{if(a)try{i.closeSync(o)}catch{}}},u=(e,t,n,r,i)=>{let o=new a.WriteStreamSync(e.file,{fd:r,start:n});t.pipe(o),f(t,i)},d=(e,t,n)=>{t=Array.from(t);let o=new r(e),s=(t,n,r)=>{let a=(e,n)=>{e?i.close(t,t=>r(e)):r(null,n)},o=0;if(n===0)return a(null,0);let s=0,l=Buffer.alloc(512),u=(r,d)=>{if(r)return a(r);if(s+=d,s<512&&d)return i.read(t,l,s,l.length-s,o+s,u);if(o===0&&l[0]===31&&l[1]===139)return a(Error(`cannot append to compressed archives`));if(s<512)return a(null,o);let f=new c(l);if(!f.cksumValid)return a(null,o);let p=512*Math.ceil(f.size/512);if(o+p+512>n||(o+=p+512,o>=n))return a(null,o);e.mtimeCache&&e.mtimeCache.set(f.path,f.mtime),s=0,i.read(t,l,0,512,o,u)};i.read(t,l,0,512,o,u)},l=new Promise((n,r)=>{o.on(`error`,r);let c=`r+`,l=(u,d)=>{if(u&&u.code===`ENOENT`&&c===`r+`)return c=`w+`,i.open(e.file,c,l);if(u)return r(u);i.fstat(d,(c,l)=>{if(c)return i.close(d,()=>r(c));s(d,l.size,(i,s)=>{if(i)return r(i);let c=new a.WriteStream(e.file,{fd:d,start:s});o.pipe(c),c.on(`error`,r),c.on(`close`,n),p(o,t)})})};i.open(e.file,c,l)});return n?l.then(n,n):l},f=(e,t)=>{t.forEach(t=>{t.charAt(0)===`@`?o({file:s.resolve(e.cwd,t.slice(1)),sync:!0,noResume:!0,onentry:t=>e.add(t)}):e.add(t)}),e.end()},p=(e,t)=>{for(;t.length;){let n=t.shift();if(n.charAt(0)===`@`)return o({file:s.resolve(e.cwd,n.slice(1)),noResume:!0,onentry:t=>e.add(t)}).then(n=>p(e,t));e.add(n)}e.end()}})),iv=X(((e,t)=>{var n=N_(),r=rv();t.exports=(e,t,a)=>{let o=n(e);if(!o.file)throw TypeError(`file is required`);if(o.gzip||o.brotli||o.file.endsWith(`.br`)||o.file.endsWith(`.tbr`))throw TypeError(`cannot append to compressed archives`);if(!t||!Array.isArray(t)||!t.length)throw TypeError(`no files or directories specified`);return t=Array.from(t),i(o),r(o,t,a)};var i=e=>{let t=e.filter;e.mtimeCache||=new Map,e.filter=t?(n,r)=>t(n,r)&&!(e.mtimeCache.get(n)>r.mtime):(t,n)=>!(e.mtimeCache.get(t)>n.mtime)}})),av=X(((e,t)=>{var{promisify:n}=Z(`util`),r=Z(`fs`);t.exports=e=>{if(!e)e={mode:511,fs:r};else if(typeof e==`object`)e={mode:511,fs:r,...e};else if(typeof e==`number`)e={mode:e,fs:r};else if(typeof e==`string`)e={mode:parseInt(e,8),fs:r};else throw TypeError(`invalid options argument`);return e.mkdir=e.mkdir||e.fs.mkdir||r.mkdir,e.mkdirAsync=n(e.mkdir),e.stat=e.stat||e.fs.stat||r.stat,e.statAsync=n(e.stat),e.statSync=e.statSync||e.fs.statSync||r.statSync,e.mkdirSync=e.mkdirSync||e.fs.mkdirSync||r.mkdirSync,e}})),ov=X(((e,t)=>{var n=process.env.__TESTING_MKDIRP_PLATFORM__||process.platform,{resolve:r,parse:i}=Z(`path`);t.exports=e=>{if(/\0/.test(e))throw Object.assign(TypeError(`path must be a string without null bytes`),{path:e,code:`ERR_INVALID_ARG_VALUE`});if(e=r(e),n===`win32`){let t=/[*|"<>?:]/,{root:n}=i(e);if(t.test(e.substr(n.length)))throw Object.assign(Error(`Illegal characters in path.`),{path:e,code:`EINVAL`})}return e}})),sv=X(((e,t)=>{var{dirname:n}=Z(`path`),r=(e,t,i=void 0)=>i===t?Promise.resolve():e.statAsync(t).then(e=>e.isDirectory()?i:void 0,i=>i.code===`ENOENT`?r(e,n(t),t):void 0),i=(e,t,r=void 0)=>{if(r!==t)try{return e.statSync(t).isDirectory()?r:void 0}catch(r){return r.code===`ENOENT`?i(e,n(t),t):void 0}};t.exports={findMade:r,findMadeSync:i}})),cv=X(((e,t)=>{var{dirname:n}=Z(`path`),r=(e,t,i)=>{t.recursive=!1;let a=n(e);return a===e?t.mkdirAsync(e,t).catch(e=>{if(e.code!==`EISDIR`)throw e}):t.mkdirAsync(e,t).then(()=>i||e,n=>{if(n.code===`ENOENT`)return r(a,t).then(n=>r(e,t,n));if(n.code!==`EEXIST`&&n.code!==`EROFS`)throw n;return t.statAsync(e).then(e=>{if(e.isDirectory())return i;throw n},()=>{throw n})})},i=(e,t,r)=>{let a=n(e);if(t.recursive=!1,a===e)try{return t.mkdirSync(e,t)}catch(e){if(e.code!==`EISDIR`)throw e;return}try{return t.mkdirSync(e,t),r||e}catch(n){if(n.code===`ENOENT`)return i(e,t,i(a,t,r));if(n.code!==`EEXIST`&&n.code!==`EROFS`)throw n;try{if(!t.statSync(e).isDirectory())throw n}catch{throw n}}};t.exports={mkdirpManual:r,mkdirpManualSync:i}})),lv=X(((e,t)=>{var{dirname:n}=Z(`path`),{findMade:r,findMadeSync:i}=sv(),{mkdirpManual:a,mkdirpManualSync:o}=cv();t.exports={mkdirpNative:(e,t)=>(t.recursive=!0,n(e)===e?t.mkdirAsync(e,t):r(t,e).then(n=>t.mkdirAsync(e,t).then(()=>n).catch(n=>{if(n.code===`ENOENT`)return a(e,t);throw n}))),mkdirpNativeSync:(e,t)=>{if(t.recursive=!0,n(e)===e)return t.mkdirSync(e,t);let r=i(t,e);try{return t.mkdirSync(e,t),r}catch(n){if(n.code===`ENOENT`)return o(e,t);throw n}}}})),uv=X(((e,t)=>{var n=Z(`fs`),r=(process.env.__TESTING_MKDIRP_NODE_VERSION__||process.version).replace(/^v/,``).split(`.`),i=+r[0]>10||+r[0]==10&&+r[1]>=12;t.exports={useNative:i?e=>e.mkdir===n.mkdir:()=>!1,useNativeSync:i?e=>e.mkdirSync===n.mkdirSync:()=>!1}})),dv=X(((e,t)=>{var n=av(),r=ov(),{mkdirpNative:i,mkdirpNativeSync:a}=lv(),{mkdirpManual:o,mkdirpManualSync:s}=cv(),{useNative:c,useNativeSync:l}=uv(),u=(e,t)=>(e=r(e),t=n(t),c(t)?i(e,t):o(e,t));u.sync=(e,t)=>(e=r(e),t=n(t),l(t)?a(e,t):s(e,t)),u.native=(e,t)=>i(r(e),n(t)),u.manual=(e,t)=>o(r(e),n(t)),u.nativeSync=(e,t)=>a(r(e),n(t)),u.manualSync=(e,t)=>s(r(e),n(t)),t.exports=u})),fv=X(((e,t)=>{var n=Z(`fs`),r=Z(`path`),i=n.lchown?`lchown`:`chown`,a=n.lchownSync?`lchownSync`:`chownSync`,o=n.lchown&&!process.version.match(/v1[1-9]+\./)&&!process.version.match(/v10\.[6-9]/),s=(e,t,r)=>{try{return n[a](e,t,r)}catch(e){if(e.code!==`ENOENT`)throw e}},c=(e,t,r)=>{try{return n.chownSync(e,t,r)}catch(e){if(e.code!==`ENOENT`)throw e}},l=o?(e,t,r,i)=>a=>{!a||a.code!==`EISDIR`?i(a):n.chown(e,t,r,i)}:(e,t,n,r)=>r,u=o?(e,t,n)=>{try{return s(e,t,n)}catch(r){if(r.code!==`EISDIR`)throw r;c(e,t,n)}}:(e,t,n)=>s(e,t,n),d=process.version,f=(e,t,r)=>n.readdir(e,t,r),p=(e,t)=>n.readdirSync(e,t);/^v4\./.test(d)&&(f=(e,t,r)=>n.readdir(e,r));var m=(e,t,r,a)=>{n[i](e,t,r,l(e,t,r,e=>{a(e&&e.code!==`ENOENT`?e:null)}))},h=(e,t,i,a,o)=>{if(typeof t==`string`)return n.lstat(r.resolve(e,t),(n,r)=>{if(n)return o(n.code===`ENOENT`?null:n);r.name=t,h(e,r,i,a,o)});t.isDirectory()?g(r.resolve(e,t.name),i,a,n=>{if(n)return o(n);m(r.resolve(e,t.name),i,a,o)}):m(r.resolve(e,t.name),i,a,o)},g=(e,t,n,r)=>{f(e,{withFileTypes:!0},(i,a)=>{if(i){if(i.code===`ENOENT`)return r();if(i.code!==`ENOTDIR`&&i.code!==`ENOTSUP`)return r(i)}if(i||!a.length)return m(e,t,n,r);let o=a.length,s=null,c=i=>{if(!s){if(i)return r(s=i);if(--o===0)return m(e,t,n,r)}};a.forEach(r=>h(e,r,t,n,c))})},_=(e,t,i,a)=>{if(typeof t==`string`)try{let i=n.lstatSync(r.resolve(e,t));i.name=t,t=i}catch(e){if(e.code===`ENOENT`)return;throw e}t.isDirectory()&&v(r.resolve(e,t.name),i,a),u(r.resolve(e,t.name),i,a)},v=(e,t,n)=>{let r;try{r=p(e,{withFileTypes:!0})}catch(r){if(r.code===`ENOENT`)return;if(r.code===`ENOTDIR`||r.code===`ENOTSUP`)return u(e,t,n);throw r}return r&&r.length&&r.forEach(r=>_(e,r,t,n)),u(e,t,n)};t.exports=g,g.sync=v})),pv=X(((e,t)=>{var n=dv(),r=Z(`fs`),i=Z(`path`),a=fv(),o=R_(),s=class extends Error{constructor(e,t){super(`Cannot extract through symbolic link`),this.path=t,this.symlink=e}get name(){return`SylinkError`}},c=class extends Error{constructor(e,t){super(t+`: Cannot cd into '`+e+`'`),this.path=e,this.code=t}get name(){return`CwdError`}},l=(e,t)=>e.get(o(t)),u=(e,t,n)=>e.set(o(t),n),d=(e,t)=>{r.stat(e,(n,r)=>{(n||!r.isDirectory())&&(n=new c(e,n&&n.code||`ENOTDIR`)),t(n)})};t.exports=(e,t,s)=>{e=o(e);let c=t.umask,p=t.mode|448,m=(p&c)!==0,h=t.uid,g=t.gid,_=typeof h==`number`&&typeof g==`number`&&(h!==t.processUid||g!==t.processGid),v=t.preserve,y=t.unlink,b=t.cache,x=o(t.cwd),S=(t,n)=>{t?s(t):(u(b,e,!0),n&&_?a(n,h,g,e=>S(e)):m?r.chmod(e,p,s):s())};if(b&&l(b,e)===!0)return S();if(e===x)return d(e,S);if(v)return n(e,{mode:p}).then(e=>S(null,e),S);f(x,o(i.relative(x,e)).split(`/`),p,b,y,x,null,S)};var f=(e,t,n,a,s,c,u,d)=>{if(!t.length)return d(null,u);let m=t.shift(),h=o(i.resolve(e+`/`+m));if(l(a,h))return f(h,t,n,a,s,c,u,d);r.mkdir(h,n,p(h,t,n,a,s,c,u,d))},p=(e,t,n,i,a,c,l,u)=>d=>{d?r.lstat(e,(m,h)=>{if(m)m.path=m.path&&o(m.path),u(m);else if(h.isDirectory())f(e,t,n,i,a,c,l,u);else if(a)r.unlink(e,o=>{if(o)return u(o);r.mkdir(e,n,p(e,t,n,i,a,c,l,u))});else if(h.isSymbolicLink())return u(new s(e,e+`/`+t.join(`/`)));else u(d)}):(l||=e,f(e,t,n,i,a,c,l,u))},m=e=>{let t=!1,n=`ENOTDIR`;try{t=r.statSync(e).isDirectory()}catch(e){n=e.code}finally{if(!t)throw new c(e,n)}};t.exports.sync=(e,t)=>{e=o(e);let c=t.umask,d=t.mode|448,f=(d&c)!==0,p=t.uid,h=t.gid,g=typeof p==`number`&&typeof h==`number`&&(p!==t.processUid||h!==t.processGid),_=t.preserve,v=t.unlink,y=t.cache,b=o(t.cwd),x=t=>{u(y,e,!0),t&&g&&a.sync(t,p,h),f&&r.chmodSync(e,d)};if(y&&l(y,e)===!0)return x();if(e===b)return m(b),x();if(_)return x(n.sync(e,d));let S=o(i.relative(b,e)).split(`/`),C=null;for(let e=S.shift(),t=b;e&&(t+=`/`+e);e=S.shift())if(t=o(i.resolve(t)),!l(y,t))try{r.mkdirSync(t,d),C||=t,u(y,t,!0)}catch{let e=r.lstatSync(t);if(e.isDirectory()){u(y,t,!0);continue}if(v){r.unlinkSync(t),r.mkdirSync(t,d),C||=t,u(y,t,!0);continue}if(e.isSymbolicLink())return new s(t,t+`/`+S.join(`/`))}return x(C)}})),mv=X(((e,t)=>{var n=Object.create(null),{hasOwnProperty:r}=Object.prototype;t.exports=e=>(r.call(n,e)||(n[e]=e.normalize(`NFD`)),n[e])})),hv=X(((e,t)=>{var n=Z(`assert`),r=mv(),i=W_(),{join:a}=Z(`path`),o=(process.env.TESTING_TAR_FAKE_PLATFORM||process.platform)===`win32`;t.exports=()=>{let e=new Map,t=new Map,s=e=>e.split(`/`).slice(0,-1).reduce((e,t)=>(e.length&&(t=a(e[e.length-1],t)),e.push(t||`/`),e),[]),c=new Set,l=n=>{let r=t.get(n);if(!r)throw Error(`function does not have any path reservations`);return{paths:r.paths.map(t=>e.get(t)),dirs:[...r.dirs].map(t=>e.get(t))}},u=e=>{let{paths:t,dirs:n}=l(e);return t.every(t=>t[0]===e)&&n.every(t=>t[0]instanceof Set&&t[0].has(e))},d=e=>c.has(e)||!u(e)?!1:(c.add(e),e(()=>f(e)),!0),f=r=>{if(!c.has(r))return!1;let{paths:i,dirs:a}=t.get(r),o=new Set;return i.forEach(t=>{let i=e.get(t);n.equal(i[0],r),i.length===1?e.delete(t):(i.shift(),typeof i[0]==`function`?o.add(i[0]):i[0].forEach(e=>o.add(e)))}),a.forEach(t=>{let i=e.get(t);n(i[0]instanceof Set),i[0].size===1&&i.length===1?e.delete(t):i[0].size===1?(i.shift(),o.add(i[0])):i[0].delete(r)}),c.delete(r),o.forEach(e=>d(e)),!0};return{check:u,reserve:(n,c)=>{n=o?[`win32 parallelization disabled`]:n.map(e=>i(a(r(e))).toLowerCase());let l=new Set(n.map(e=>s(e)).reduce((e,t)=>e.concat(t)));return t.set(c,{dirs:l,paths:n}),n.forEach(t=>{let n=e.get(t);n?n.push(c):e.set(t,[c])}),l.forEach(t=>{let n=e.get(t);n?n[n.length-1]instanceof Set?n[n.length-1].add(c):n.push(new Set([c])):e.set(t,[new Set([c])])}),d(c)}}}})),gv=X(((e,t)=>{var n=(process.env.__FAKE_PLATFORM__||process.platform)===`win32`,{O_CREAT:r,O_TRUNC:i,O_WRONLY:a,UV_FS_O_FILEMAP:o=0}=(global.__FAKE_TESTING_FS__||Z(`fs`)).constants,s=n&&!!o,c=524288,l=o|i|r|a;t.exports=s?e=>e<c?l:`w`:()=>`w`})),_v=X(((e,t)=>{var n=Z(`assert`),r=ev(),i=Z(`fs`),a=$_(),o=Z(`path`),s=pv(),c=K_(),l=hv(),u=q_(),d=R_(),f=W_(),p=mv(),m=Symbol(`onEntry`),h=Symbol(`checkFs`),g=Symbol(`checkFs2`),_=Symbol(`pruneCache`),v=Symbol(`isReusable`),y=Symbol(`makeFs`),b=Symbol(`file`),x=Symbol(`directory`),S=Symbol(`link`),C=Symbol(`symlink`),w=Symbol(`hardlink`),T=Symbol(`unsupported`),E=Symbol(`checkPath`),D=Symbol(`mkdir`),O=Symbol(`onError`),k=Symbol(`pending`),A=Symbol(`pend`),j=Symbol(`unpend`),M=Symbol(`ended`),N=Symbol(`maybeClose`),P=Symbol(`skip`),F=Symbol(`doChown`),ee=Symbol(`uid`),te=Symbol(`gid`),ne=Symbol(`checkedCwd`),re=Z(`crypto`),ie=gv(),ae=(process.env.TESTING_TAR_FAKE_PLATFORM||process.platform)===`win32`,oe=1024,se=(e,t)=>{if(!ae)return i.unlink(e,t);let n=e+`.DELETE.`+re.randomBytes(16).toString(`hex`);i.rename(e,n,e=>{if(e)return t(e);i.unlink(n,t)})},ce=e=>{if(!ae)return i.unlinkSync(e);let t=e+`.DELETE.`+re.randomBytes(16).toString(`hex`);i.renameSync(e,t),i.unlinkSync(t)},le=(e,t,n)=>e===e>>>0?e:t===t>>>0?t:n,ue=e=>f(d(p(e))).toLowerCase(),de=(e,t)=>{t=ue(t);for(let n of e.keys()){let r=ue(n);(r===t||r.indexOf(t+`/`)===0)&&e.delete(n)}},fe=e=>{for(let t of e.keys())e.delete(t)},pe=class extends r{constructor(e){if(e||={},e.ondone=e=>{this[M]=!0,this[N]()},super(e),this[ne]=!1,this.reservations=l(),this.transform=typeof e.transform==`function`?e.transform:null,this.writable=!0,this.readable=!1,this[k]=0,this[M]=!1,this.dirCache=e.dirCache||new Map,typeof e.uid==`number`||typeof e.gid==`number`){if(typeof e.uid!=`number`||typeof e.gid!=`number`)throw TypeError(`cannot set owner without number uid and gid`);if(e.preserveOwner)throw TypeError(`cannot preserve owner in archive and also set owner explicitly`);this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=null,this.gid=null,this.setOwner=!1;this.preserveOwner=e.preserveOwner===void 0&&typeof e.uid!=`number`?process.getuid&&process.getuid()===0:!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():null,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():null,this.maxDepth=typeof e.maxDepth==`number`?e.maxDepth:oe,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||ae,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=d(o.resolve(e.cwd||process.cwd())),this.strip=+e.strip||0,this.processUmask=e.noChmod?0:process.umask(),this.umask=typeof e.umask==`number`?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on(`entry`,e=>this[m](e))}warn(e,t,n={}){return(e===`TAR_BAD_ARCHIVE`||e===`TAR_ABORT`)&&(n.recoverable=!1),super.warn(e,t,n)}[N](){this[M]&&this[k]===0&&(this.emit(`prefinish`),this.emit(`finish`),this.emit(`end`))}[E](e){let t=d(e.path),n=t.split(`/`);if(this.strip){if(n.length<this.strip)return!1;if(e.type===`Link`){let t=d(e.linkpath).split(`/`);if(t.length>=this.strip)e.linkpath=t.slice(this.strip).join(`/`);else return!1}n.splice(0,this.strip),e.path=n.join(`/`)}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn(`TAR_ENTRY_ERROR`,`path excessively deep`,{entry:e,path:t,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this.preservePaths){if(n.includes(`..`)||ae&&/^[a-z]:\.\.$/i.test(n[0]))return this.warn(`TAR_ENTRY_ERROR`,`path contains '..'`,{entry:e,path:t}),!1;let[r,i]=u(t);r&&(e.path=i,this.warn(`TAR_ENTRY_INFO`,`stripping ${r} from absolute path`,{entry:e,path:t}))}if(e.absolute=o.isAbsolute(e.path)?d(o.resolve(e.path)):d(o.resolve(this.cwd,e.path)),!this.preservePaths&&e.absolute.indexOf(this.cwd+`/`)!==0&&e.absolute!==this.cwd)return this.warn(`TAR_ENTRY_ERROR`,`path escaped extraction target`,{entry:e,path:d(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!==`Directory`&&e.type!==`GNUDumpDir`)return!1;if(this.win32){let{root:t}=o.win32.parse(e.absolute);e.absolute=t+c.encode(e.absolute.slice(t.length));let{root:n}=o.win32.parse(e.path);e.path=n+c.encode(e.path.slice(n.length))}return!0}[m](e){if(!this[E](e))return e.resume();switch(n.equal(typeof e.absolute,`string`),e.type){case`Directory`:case`GNUDumpDir`:e.mode&&(e.mode|=448);case`File`:case`OldFile`:case`ContiguousFile`:case`Link`:case`SymbolicLink`:return this[h](e);default:return this[T](e)}}[O](e,t){e.name===`CwdError`?this.emit(`error`,e):(this.warn(`TAR_ENTRY_ERROR`,e,{entry:t}),this[j](),t.resume())}[D](e,t,n){s(d(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:t,noChmod:this.noChmod},n)}[F](e){return this.forceChown||this.preserveOwner&&(typeof e.uid==`number`&&e.uid!==this.processUid||typeof e.gid==`number`&&e.gid!==this.processGid)||typeof this.uid==`number`&&this.uid!==this.processUid||typeof this.gid==`number`&&this.gid!==this.processGid}[ee](e){return le(this.uid,e.uid,this.processUid)}[te](e){return le(this.gid,e.gid,this.processGid)}[b](e,t){let n=e.mode&4095||this.fmode,r=new a.WriteStream(e.absolute,{flags:ie(e.size),mode:n,autoClose:!1});r.on(`error`,n=>{r.fd&&i.close(r.fd,()=>{}),r.write=()=>!0,this[O](n,e),t()});let o=1,s=n=>{n?(r.fd&&i.close(r.fd,()=>{}),this[O](n,e),t()):--o===0&&i.close(r.fd,n=>{n?this[O](n,e):this[j](),t()})};r.on(`finish`,t=>{let n=e.absolute,a=r.fd;if(e.mtime&&!this.noMtime){o++;let t=e.atime||new Date,r=e.mtime;i.futimes(a,t,r,e=>e?i.utimes(n,t,r,t=>s(t&&e)):s())}if(this[F](e)){o++;let t=this[ee](e),r=this[te](e);i.fchown(a,t,r,e=>e?i.chown(n,t,r,t=>s(t&&e)):s())}s()});let c=this.transform&&this.transform(e)||e;c!==e&&(c.on(`error`,n=>{this[O](n,e),t()}),e.pipe(c)),c.pipe(r)}[x](e,t){let n=e.mode&4095||this.dmode;this[D](e.absolute,n,n=>{if(n){this[O](n,e),t();return}let r=1,a=n=>{--r===0&&(t(),this[j](),e.resume())};e.mtime&&!this.noMtime&&(r++,i.utimes(e.absolute,e.atime||new Date,e.mtime,a)),this[F](e)&&(r++,i.chown(e.absolute,this[ee](e),this[te](e),a)),a()})}[T](e){e.unsupported=!0,this.warn(`TAR_ENTRY_UNSUPPORTED`,`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[C](e,t){this[S](e,e.linkpath,`symlink`,t)}[w](e,t){let n=d(o.resolve(this.cwd,e.linkpath));this[S](e,n,`link`,t)}[A](){this[k]++}[j](){this[k]--,this[N]()}[P](e){this[j](),e.resume()}[v](e,t){return e.type===`File`&&!this.unlink&&t.isFile()&&t.nlink<=1&&!ae}[h](e){this[A]();let t=[e.path];e.linkpath&&t.push(e.linkpath),this.reservations.reserve(t,t=>this[g](e,t))}[_](e){e.type===`SymbolicLink`?fe(this.dirCache):e.type!==`Directory`&&de(this.dirCache,e.absolute)}[g](e,t){this[_](e);let n=n=>{this[_](e),t(n)},r=()=>{this[D](this.cwd,this.dmode,t=>{t?(this[O](t,e),n()):(this[ne]=!0,a())})},a=()=>{if(e.absolute!==this.cwd){let t=d(o.dirname(e.absolute));if(t!==this.cwd)return this[D](t,this.dmode,t=>{t?(this[O](t,e),n()):s()})}s()},s=()=>{i.lstat(e.absolute,(t,r)=>{if(r&&(this.keep||this.newer&&r.mtime>e.mtime))this[P](e),n();else{if(t||this[v](e,r))return this[y](null,e,n);if(r.isDirectory()){if(e.type===`Directory`){let t=!this.noChmod&&e.mode&&(r.mode&4095)!==e.mode,a=t=>this[y](t,e,n);return t?i.chmod(e.absolute,e.mode,a):a()}if(e.absolute!==this.cwd)return i.rmdir(e.absolute,t=>this[y](t,e,n))}if(e.absolute===this.cwd)return this[y](null,e,n);se(e.absolute,t=>this[y](t,e,n))}})};this[ne]?a():r()}[y](e,t,n){if(e)this[O](e,t),n();else switch(t.type){case`File`:case`OldFile`:case`ContiguousFile`:return this[b](t,n);case`Link`:return this[w](t,n);case`SymbolicLink`:return this[C](t,n);case`Directory`:case`GNUDumpDir`:return this[x](t,n)}}[S](e,t,n,r){i[n](t,e.absolute,t=>{t?this[O](t,e):(this[j](),e.resume()),r()})}},me=e=>{try{return[null,e()]}catch(e){return[e,null]}};pe.Sync=class extends pe{[y](e,t){return super[y](e,t,()=>{})}[h](e){if(this[_](e),!this[ne]){let t=this[D](this.cwd,this.dmode);if(t)return this[O](t,e);this[ne]=!0}if(e.absolute!==this.cwd){let t=d(o.dirname(e.absolute));if(t!==this.cwd){let n=this[D](t,this.dmode);if(n)return this[O](n,e)}}let[t,n]=me(()=>i.lstatSync(e.absolute));if(n&&(this.keep||this.newer&&n.mtime>e.mtime))return this[P](e);if(t||this[v](e,n))return this[y](null,e);if(n.isDirectory()){if(e.type===`Directory`){let[t]=!this.noChmod&&e.mode&&(n.mode&4095)!==e.mode?me(()=>{i.chmodSync(e.absolute,e.mode)}):[];return this[y](t,e)}let[t]=me(()=>i.rmdirSync(e.absolute));this[y](t,e)}let[r]=e.absolute===this.cwd?[]:me(()=>ce(e.absolute));this[y](r,e)}[b](e,t){let n=e.mode&4095||this.fmode,r=n=>{let r;try{i.closeSync(a)}catch(e){r=e}(n||r)&&this[O](n||r,e),t()},a;try{a=i.openSync(e.absolute,ie(e.size),n)}catch(e){return r(e)}let o=this.transform&&this.transform(e)||e;o!==e&&(o.on(`error`,t=>this[O](t,e)),e.pipe(o)),o.on(`data`,e=>{try{i.writeSync(a,e,0,e.length)}catch(e){r(e)}}),o.on(`end`,t=>{let n=null;if(e.mtime&&!this.noMtime){let t=e.atime||new Date,r=e.mtime;try{i.futimesSync(a,t,r)}catch(a){try{i.utimesSync(e.absolute,t,r)}catch{n=a}}}if(this[F](e)){let t=this[ee](e),r=this[te](e);try{i.fchownSync(a,t,r)}catch(a){try{i.chownSync(e.absolute,t,r)}catch{n||=a}}}r(n)})}[x](e,t){let n=e.mode&4095||this.dmode,r=this[D](e.absolute,n);if(r)this[O](r,e),t();else{if(e.mtime&&!this.noMtime)try{i.utimesSync(e.absolute,e.atime||new Date,e.mtime)}catch{}if(this[F](e))try{i.chownSync(e.absolute,this[ee](e),this[te](e))}catch{}t(),e.resume()}}[D](e,t){try{return s.sync(d(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:t})}catch(e){return e}}[S](e,t,n,r){try{i[n+`Sync`](t,e.absolute),r(),e.resume()}catch(t){return this[O](t,e)}}},t.exports=pe})),vv=X(((e,t)=>{var n=N_(),r=_v(),i=Z(`fs`),a=$_(),o=Z(`path`),s=W_();t.exports=(e,t,r)=>{typeof e==`function`?(r=e,t=null,e={}):Array.isArray(e)&&(t=e,e={}),typeof t==`function`&&(r=t,t=null),t=t?Array.from(t):[];let i=n(e);if(i.sync&&typeof r==`function`)throw TypeError(`callback not supported for sync tar functions`);if(!i.file&&typeof r==`function`)throw TypeError(`callback only supported with file option`);return t.length&&c(i,t),i.file&&i.sync?l(i):i.file?u(i,r):i.sync?d(i):f(i)};var c=(e,t)=>{let n=new Map(t.map(e=>[s(e),!0])),r=e.filter,i=(e,t)=>{let r=t||o.parse(e).root||`.`,a=e===r?!1:n.has(e)?n.get(e):i(o.dirname(e),r);return n.set(e,a),a};e.filter=r?(e,t)=>r(e,t)&&i(s(e)):e=>i(s(e))},l=e=>{let t=new r.Sync(e),n=e.file,o=i.statSync(n),s=e.maxReadSize||16777216;new a.ReadStreamSync(n,{readSize:s,size:o.size}).pipe(t)},u=(e,t)=>{let n=new r(e),o=e.maxReadSize||16777216,s=e.file,c=new Promise((e,t)=>{n.on(`error`,t),n.on(`close`,e),i.stat(s,(e,r)=>{if(e)t(e);else{let e=new a.ReadStream(s,{readSize:o,size:r.size});e.on(`error`,t),e.pipe(n)}})});return t?c.then(t,t):c},d=e=>new r.Sync(e),f=e=>new r(e)})),yv=X((e=>{e.c=e.create=nv(),e.r=e.replace=rv(),e.t=e.list=tv(),e.u=e.update=iv(),e.x=e.extract=vv(),e.Pack=Q_(),e.Unpack=_v(),e.Parse=ev(),e.ReadEntry=z_(),e.WriteEntry=Y_(),e.Header=H_(),e.Pax=U_(),e.types=B_()})),bv=kg(M_()),xv=kg(yv()),Sv={18:{version:`v18.20.8`},19:{version:`v19.9.0`},20:{version:`v20.20.2`},21:{version:`v21.7.3`},22:{version:`v22.23.3`},23:{version:`v23.11.1`},24:{version:`v24.21.0`},25:{version:`v25.9.0`},26:{version:`v26.11.1`}},Cv=process.platform===`win32`;function wv(e){if(typeof e!=`string`||!/^\d+(\.\d+){0,2}$/.test(e))throw Error(`nodeVersion 应为 "18" | "18.1" | "18.1.5" 形式(1~3 段数字),收到:${e}`);let t=e.split(`.`).map(Number),n=Object.entries(Sv),r=n.find(([,e])=>{let n=e.version.replace(/^v/,``).split(`.`).map(Number);return t.every((e,t)=>n[t]===e)});if(!r)throw Error(`ezn 内置版本表无匹配 Node ${e} 的版本(当前内置:${n.map(([e,t])=>`${e}=${t.version}`).join(`、`)})。可改传主版本号(如 18),或经 scripts/update-node-assets.mts 更新版本表。`);return r[1].version}function Tv(e){return Cv?E(e,`node.exe`):E(e,`bin`,`node`)}function Ev(){return`${process.platform}-${process.arch}`}function Dv(e){let t=D(e);return f(Tv(t))?t:null}function Ov(e,t){return[E(e,`node_modules`,`npm`,`bin`,`${t}-cli.js`),E(e,`lib`,`node_modules`,`npm`,`bin`,`${t}-cli.js`)]}function kv(e,t){let n=Ov(e,t),r=n.find(e=>f(e));if(!r)throw Error([`未找到自带 ${t}(该目录可能不是完整的 Node 运行时)。已查找以下位置:`,...n.map(e=>` - ${e}`),`可尝试的恢复方式:`,` 1. 托管运行时(<appDir>/node):删除该目录后重新启动服务,由引导重新落位完整运行时;`,` 2. 手工安装的平铺运行时:请确认发行包完整(含自带 npm/npx),必要时重新解压放置。`].join(`
|
|
92
|
+
`));return r}function Av(e){return Dv(e)!==null&&Ov(e,`npm`).some(e=>f(e))}var jv=[`.cmd`,`.bat`,`.exe`];function Mv(e,t){if(t.includes(`/`)||t.includes(`\\`))return null;let n=Cv?jv.map(n=>E(e,`${t}${n}`)):[E(e,t)];return n.push(E(e,`node_modules`,`.bin`,t)),n.find(e=>f(e))??null}function Nv(e){return(Cv?[e,E(e,`node_modules`,`.bin`)]:[E(e,`bin`),e]).join(w)+w}var Pv=X(((e,t)=>{t.exports=n;function n(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}n.prototype.go=function(e){this.pending<this.max?i(this,e):this.waiting.push(e)},n.prototype.wait=function(e){this.pending===0?e(this.error):this.listeners.push(e)},n.prototype.hold=function(){return r(this)};function r(e){e.pending+=1;var t=!1;return n;function n(n){if(t)throw Error(`callback called twice`);if(t=!0,e.error=e.error||n,--e.pending,e.waiting.length>0&&e.pending<e.max)i(e,e.waiting.shift());else if(e.pending===0){var a=e.listeners;e.listeners=[],a.forEach(r)}}function r(t){t(e.error)}}function i(e,t){t(r(e))}})),Fv=X((e=>{var t=Z(`fs`),n=Z(`util`),r=Z(`stream`),i=r.Readable,a=r.PassThrough,o=Pv(),s=Z(`events`).EventEmitter;e.BufferSlicer=u,e.FdSlicer=c,n.inherits(c,s);function c(e){s.call(this),this.fd=e,this.pend=new o,this.pend.max=1,this.refCount=0}c.prototype.read=function(e,n,r,i,a){var o=this;o.pend.go(function(s){t.read(o.fd,e,n,r,i,function(e,t,n){s(),a(e,t,n)})})},c.prototype.createReadStream=function(e){return new l(this,e)},c.prototype.ref=function(){this.refCount+=1},c.prototype.unref=function(){var e=this;if(--e.refCount,e.refCount<0)throw Error(`invalid unref`);if(e.refCount>0)return;t.close(e.fd,n);function n(t){t?e.emit(`error`,t):e.emit(`close`)}},n.inherits(l,i);function l(e,t){t||={},i.call(this,t),this.context=e,this.context.ref(),this.start=t.start||0,this.endOffset=t.end,this.pos=this.start}l.prototype._read=function(e){var n=this,r=Math.min(n._readableState.highWaterMark,e);n.endOffset!=null&&(r=Math.min(r,n.endOffset-n.pos)),r<=0?(n.push(null),this._cleanup()):n.context.pend.go(function(e){var i=Buffer.allocUnsafe(r);t.read(n.context.fd,i,0,r,n.pos,function(t,r){t?n.destroy(t):r===0?(n.push(null),n._cleanup()):(n.pos+=r,n.push(i.slice(0,r))),e()})})},l.prototype._destroy=function(e,t){this._cleanup(),t(e)},l.prototype._cleanup=function(){this.context!=null&&(this.context.unref(),this.context=null)},n.inherits(u,s);function u(e){s.call(this),this.refCount=0,this.buffer=e}u.prototype.read=function(e,t,n,r,i){if(!(0<=t&&t<=e.length))throw RangeError(`offset outside buffer: 0 <= `+t+` <= `+e.length);if(r<0)throw RangeError(`position is negative: `+r);t+n>e.length&&(n=e.length-t),r+n>this.buffer.length&&(n=this.buffer.length-r),n<=0?setImmediate(function(){i(null,0)}):(this.buffer.copy(e,t,r,r+n),setImmediate(function(){i(null,n)}))},u.prototype.createReadStream=function(e){e||={};var t=new a(e);t.start=e.start||0,t.endOffset=e.end,t.pos=t.endOffset||this.buffer.length;for(var n=this.buffer.slice(t.start,t.pos),r=65536,i=0;;){var o=i+r;if(o>=n.length){i<n.length&&t.write(n.slice(i,n.length));break}t.write(n.slice(i,o)),i=o}return t.end(),t},u.prototype.ref=function(){this.refCount+=1},u.prototype.unref=function(){if(--this.refCount,this.refCount<0)throw Error(`invalid unref`)}})),Iv=X(((e,t)=>{var n=new Int32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function r(e){let t=-1;for(let r of e)t=n[(t^r)&255]^t>>>8;return(t^-1)>>>0}t.exports=r})),Lv=X((e=>{var t=Z(`fs`),n=Z(`zlib`),r=Fv(),i=Z(`util`),a=Z(`events`).EventEmitter,o=Z(`stream`).Transform,s=Z(`stream`).PassThrough,c=Z(`stream`).Writable,l=typeof n.crc32==`function`?n.crc32:Iv();e.openPromise=u;function u(e,t){return new Promise((n,r)=>{d(e,{...t,lazyEntries:!0},function(e,t){if(e)return r(e);n(t)})})}function d(e,n,r){typeof n==`function`&&(r=n,n=null),n??={},n.autoClose??(n.autoClose=!0),n.lazyEntries??(n.lazyEntries=!1),n.decodeStrings??(n.decodeStrings=!0),n.validateEntrySizes??(n.validateEntrySizes=!0),n.strictFileNames??(n.strictFileNames=!1),r??=M,t.open(e,`r`,function(e,i){if(e)return r(e);f(i,n,function(e,n){e&&t.close(i,M),r(e,n)})})}function f(e,n,i){typeof n==`function`&&(i=n,n=null),n??={},n.autoClose??(n.autoClose=!1),n.lazyEntries??(n.lazyEntries=!1),n.decodeStrings??(n.decodeStrings=!0),n.validateEntrySizes??(n.validateEntrySizes=!0),n.strictFileNames??(n.strictFileNames=!1),i??=M,t.fstat(e,function(t,a){if(t)return i(t);p(new r.FdSlicer(e),a.size,n,i)})}function p(e,t,n,r){typeof n==`function`&&(r=n,n=null),n??={},n.autoClose??(n.autoClose=!0),n.lazyEntries??(n.lazyEntries=!1),n.decodeStrings??(n.decodeStrings=!0);var i=!!n.decodeStrings;if(n.validateEntrySizes??(n.validateEntrySizes=!0),n.strictFileNames??(n.strictFileNames=!1),r??=M,typeof t!=`number`)throw Error(`expected totalSize parameter to be a number`);if(t>2**53-1)throw Error(`zip file too large. only file sizes up to 2^52 are supported due to JavaScript's Number type being an IEEE 754 double.`);e.ref();var a=22,o=20,s=Math.min(o+a+65535,t),c=A(s);C(e,c,0,s,t-c.length,function(l){if(l)return r(l);for(var u=s-a;u>=0;--u)if(c.readUInt32LE(u)===101010256){var d=c.subarray(u),f=d.readUInt16LE(4),p=d.readUInt16LE(10),h=d.readUInt32LE(16),g=d.readUInt16LE(20),_=d.length-a;if(g!==_)return r(Error(`Invalid comment length. Expected: `+_+`. Found: `+g+". Are there extra bytes at the end of the file? Or is the end of central dir signature `PK☺☻` in the comment?"));var v=i?O(d.subarray(22),!1):d.subarray(22);if(u-o>=0&&c.readUInt32LE(u-o)===117853008){var y=k(c.subarray(u-o,u-o+o),8),b=A(56);return C(e,b,0,b.length,y,function(a){return a?r(a):b.readUInt32LE(0)===101075792?(f=b.readUInt32LE(16),f===0?(p=k(b,32),h=k(b,48),r(null,new m(e,h,t,p,v,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames))):r(Error(`multi-disk zip files are not supported: found disk number: `+f))):r(Error(`invalid zip64 end of central directory record signature`))})}return f===0?r(null,new m(e,h,t,p,v,n.autoClose,n.lazyEntries,i,n.validateEntrySizes,n.strictFileNames)):r(Error(`multi-disk zip files are not supported: found disk number: `+f))}r(Error(`End of central directory record signature not found. Either not a zip file, or file is truncated.`))})}i.inherits(m,a);function m(e,t,n,r,i,o,s,c,l,u){var d=this;a.call(d),d.reader=e,d.reader.on(`error`,function(e){g(d,e)}),d.reader.once(`close`,function(){d.emit(`close`)}),d.readEntryCursor=t,d.fileSize=n,d.entryCount=r,d.comment=i,d.entriesRead=0,d.autoClose=!!o,d.lazyEntries=!!s,d.decodeStrings=!!c,d.validateEntrySizes=!!l,d.strictFileNames=!!u,d.isOpen=!0,d.emittedError=!1,d.hasEachEntryBeenCalled=!1,d.lazyEntries||d._readEntry()}m.prototype.close=function(){this.isOpen&&(this.isOpen=!1,this.reader.unref())};function h(e,t){e.autoClose&&e.close(),g(e,t)}function g(e,t){e.emittedError||(e.emittedError=!0,e.emit(`error`,t))}m.prototype.readEntry=function(){if(!this.lazyEntries)throw Error(`readEntry() called without lazyEntries:true`);this._readEntry()},m.prototype._readEntry=function(){var e=this;if(e.entryCount===e.entriesRead)setImmediate(function(){e.autoClose&&e.close(),!e.emittedError&&e.emit(`end`)});else if(!e.emittedError){var t=A(46);C(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return h(e,n);if(!e.emittedError){var r=new _,i=t.readUInt32LE(0);if(i!==33639248)return h(e,Error(`invalid central directory file header signature: 0x`+i.toString(16)));if(r.versionMadeBy=t.readUInt16LE(4),r.versionNeededToExtract=t.readUInt16LE(6),r.generalPurposeBitFlag=t.readUInt16LE(8),r.compressionMethod=t.readUInt16LE(10),r.lastModFileTime=t.readUInt16LE(12),r.lastModFileDate=t.readUInt16LE(14),r.crc32=t.readUInt32LE(16),r.compressedSize=t.readUInt32LE(20),r.uncompressedSize=t.readUInt32LE(24),r.fileNameLength=t.readUInt16LE(28),r.extraFieldLength=t.readUInt16LE(30),r.fileCommentLength=t.readUInt16LE(32),r.internalFileAttributes=t.readUInt16LE(36),r.externalFileAttributes=t.readUInt32LE(38),r.relativeOffsetOfLocalHeader=t.readUInt32LE(42),r.generalPurposeBitFlag&64)return h(e,Error(`strong encryption is not supported`));e.readEntryCursor+=46,t=A(r.fileNameLength+r.extraFieldLength+r.fileCommentLength),C(e.reader,t,0,t.length,e.readEntryCursor,function(n){if(n)return h(e,n);if(!e.emittedError){r.fileNameRaw=t.subarray(0,r.fileNameLength);var i=r.fileNameLength+r.extraFieldLength;r.extraFieldRaw=t.subarray(r.fileNameLength,i),r.fileCommentRaw=t.subarray(i,i+r.fileCommentLength);try{r.extraFields=S(r.extraFieldRaw)}catch(t){return h(e,t)}if(e.decodeStrings){var a=!!(r.generalPurposeBitFlag&2048);r.fileComment=O(r.fileCommentRaw,a),r.fileName=b(r.generalPurposeBitFlag,r.fileNameRaw,r.extraFields,e.strictFileNames);var o=x(r.fileName);if(o!=null)return h(e,Error(o))}else r.fileComment=r.fileCommentRaw,r.fileName=r.fileNameRaw;r.comment=r.fileComment,e.readEntryCursor+=t.length,e.entriesRead+=1;for(var s=0;s<r.extraFields.length;s++){var c=r.extraFields[s];if(c.id===1){var l=c.data,u=0;if(r.uncompressedSize===4294967295){if(u+8>l.length)return h(e,Error(`zip64 extended information extra field does not include uncompressed size`));r.uncompressedSize=k(l,u),u+=8}if(r.compressedSize===4294967295){if(u+8>l.length)return h(e,Error(`zip64 extended information extra field does not include compressed size`));r.compressedSize=k(l,u),u+=8}if(r.relativeOffsetOfLocalHeader===4294967295){if(u+8>l.length)return h(e,Error(`zip64 extended information extra field does not include relative header offset`));r.relativeOffsetOfLocalHeader=k(l,u),u+=8}break}}if(e.validateEntrySizes&&r.compressionMethod===0){var d=r.uncompressedSize;if(r.isEncrypted()&&(d+=12),r.compressedSize!==d){var f=`compressed/uncompressed size mismatch for stored file: `+r.compressedSize+` != `+r.uncompressedSize;return h(e,Error(f))}}e.emit(`entry`,r),e.lazyEntries||e._readEntry()}})}})}},m.prototype.eachEntry=function(){let e=this;if(!e.lazyEntries)throw Error(`eachEntry() requires lazyEntries: true`);if(e.hasEachEntryBeenCalled)throw Error(`eachEntry() must only be called once per ZipFile`);e.hasEachEntryBeenCalled=!0;let t=null;e.on(`entry`,r),e.on(`end`,i),e.on(`error`,a);function n(){e.removeListener(`entry`,r),e.removeListener(`end`,i),e.removeListener(`error`,a),e.autoClose&&e.close()}function r(e){let{resolve:n}=t;t=null,n({value:e})}function i(){let{resolve:e}=t;t=null,n(),e({done:!0})}function a(e){let{reject:r}=t;t=null,n(),r(e)}return{[Symbol.asyncIterator](){return this},next(){let n=new Promise((e,n)=>{if(t!=null)throw Error(`next() called before previous Promise was resolved.`);t={resolve:e,reject:n}});return e.readEntry(),n},return(e){return n(),Promise.resolve({done:!0,value:e})},throw(e){return n(),Promise.reject(e)}}},m.prototype.openReadStream=function(e,t,n){var r=this,i=0,a=e.compressedSize;if(n??(n=t,t=null),t==null)t={};else{if(t.decodeFileData===!1){if(t.decrypt!=null)throw Error(`cannot use options.decrypt when options.decodeFileData === false`);if(t.decompress!=null)throw Error(`cannot use options.decompress when options.decodeFileData === false`)}else{if(t.decrypt!=null){if(!e.isEncrypted())throw Error(`options.decrypt can only be specified for encrypted entries. See also option decodeFileData.`);if(t.decrypt!==!1)throw Error(`invalid options.decrypt value: `+t.decrypt);if(e.isCompressed()&&t.decompress!==!1)throw Error(`entry is encrypted and compressed, and options.decompress !== false. See also option decodeFileData.`)}if(t.decompress!=null){if(!e.isCompressed())throw Error(`options.decompress can only be specified for compressed entries. See also option decodeFileData.`);if(t.decompress!==!1&&t.decompress!==!0)throw Error(`invalid options.decompress value: `+t.decompress);s=t.decompress}}if(t.start!=null){if(i=t.start,i<0)throw Error(`options.start < 0`);if(i>e.compressedSize)throw Error(`options.start > entry.compressedSize`)}if(t.end!=null){if(a=t.end,a<0)throw Error(`options.end < 0`);if(a>e.compressedSize)throw Error(`options.end > entry.compressedSize`);if(a<i)throw Error(`options.end < options.start`)}}var o=t.decodeFileData===!1||(e.compressionMethod===0||e.compressionMethod===8&&t.decompress===!1)&&(!e.isEncrypted()||t.decrypt===!1);if((t.start!=null||t.end!=null)&&!o)throw Error(`start/end range require options.decodeFileData === false for non-trivial encoded entries.`);if(!r.isOpen)return n(Error(`closed`));if(e.isEncrypted()&&!o&&t.decrypt!==!1)return n(Error(`entry is encrypted, and options.decodeFileData !== false`));var s;if(o)s=!1;else if(e.compressionMethod===8)s=t.decodeFileData!==!0;else return n(Error(`unsupported compression method: `+e.compressionMethod));r.readLocalFileHeader(e,{minimal:!0},function(t,o){if(t)return n(t);r.openReadStreamLowLevel(o.fileDataStart,e.compressedSize,i,a,s,e.uncompressedSize,n)})},m.prototype.openReadStreamLowLevel=function(e,t,r,i,a,o,s){var c=this;e+t;var l=c.reader.createReadStream({start:e+r,end:e+i}),u=l;if(a){var d=!1,f=n.createInflateRaw();l.on(`error`,function(e){setImmediate(function(){d||f.emit(`error`,e)})}),l.pipe(f),c.validateEntrySizes?(u=new w(o),f.on(`error`,function(e){setImmediate(function(){d||u.emit(`error`,e)})}),f.pipe(u)):u=f,j(u,function(){d=!0,f!==u&&f.unpipe(u),l.unpipe(f),l.destroy()})}s(null,u)},m.prototype.readLocalFileHeader=function(e,t,n){var r=this;n??(n=t,t=null),t??={},r.reader.ref();var i=A(30);C(r.reader,i,0,i.length,e.relativeOffsetOfLocalHeader,function(a){try{if(a)return n(a);var o=i.readUInt32LE(0);if(o!==67324752)return n(Error(`invalid local file header signature: 0x`+o.toString(16)));var s=i.readUInt16LE(26),c=i.readUInt16LE(28),l=e.relativeOffsetOfLocalHeader+30+s+c;if(l+e.compressedSize>r.fileSize)return n(Error(`file data overflows file bounds: `+l+` + `+e.compressedSize+` > `+r.fileSize));if(t.minimal)return n(null,{fileDataStart:l});var u=new v;u.fileDataStart=l,u.versionNeededToExtract=i.readUInt16LE(4),u.generalPurposeBitFlag=i.readUInt16LE(6),u.compressionMethod=i.readUInt16LE(8),u.lastModFileTime=i.readUInt16LE(10),u.lastModFileDate=i.readUInt16LE(12),u.crc32=i.readUInt32LE(14),u.compressedSize=i.readUInt32LE(18),u.uncompressedSize=i.readUInt32LE(22),u.fileNameLength=s,u.extraFieldLength=c,i=A(s+c),r.reader.ref(),C(r.reader,i,0,i.length,e.relativeOffsetOfLocalHeader+30,function(e){try{return e?n(e):(u.fileName=i.subarray(0,s),u.extraField=i.subarray(s),n(null,u))}finally{r.reader.unref()}})}finally{r.reader.unref()}})},m.prototype.openReadStreamPromise=function(e,t){return new Promise((n,r)=>{this.openReadStream(e,t,function(e,t){if(e)return r(e);n(t)})})},m.prototype.openReadStreamLowLevelPromise=function(e,t,n,r,i,a){return new Promise((o,s)=>{this.openReadStream(e,t,n,r,i,a,function(e,t){if(e)return s(e);o(t)})})},m.prototype.readLocalFileHeaderPromise=function(e,t){return new Promise((n,r)=>{this.readLocalFileHeader(e,t,function(e,t){if(e)return r(e);n(t)})})};function _(){}_.prototype.getLastModDate=function(e){if(e??={},!e.forceDosFormat)for(var t=0;t<this.extraFields.length;t++){var n=this.extraFields[t];if(n.id===21589){var r=n.data;if(r.length<5||!(r[0]&1))continue;var i=r.readInt32LE(1);return new Date(i*1e3)}if(n.id===10){var r=n.data;if(r.length!==32||r.readUInt16LE(4)!==1||r.readUInt16LE(6)!==24)continue;var a=(r.readUInt32LE(8)+4294967296*r.readInt32LE(12))/1e4-0xa9730b66800;return new Date(a)}}return y(this.lastModFileDate,this.lastModFileTime,e.timezone)},_.prototype.canDecodeFileData=function(){return!this.isEncrypted()&&(this.compressionMethod===0||this.compressionMethod===8)},_.prototype.isEncrypted=function(){return!!(this.generalPurposeBitFlag&1)},_.prototype.isCompressed=function(){return this.compressionMethod===8};function v(){}function y(e,t,n){var r=e&31,i=(e>>5&15)-1,a=(e>>9&127)+1980,o=0,s=(t&31)*2,c=t>>5&63,l=t>>11&31;if(n==null||n===`local`)return new Date(a,i,r,l,c,s,o);if(n===`UTC`)return new Date(Date.UTC(a,i,r,l,c,s,o));throw Error(`unrecognized options.timezone: `+options.timezone)}function b(e,t,n,r){for(var i=null,a=0;a<n.length;a++){var o=n[a];if(o.id===28789){if(o.data.length<6||o.data.readUInt8(0)!==1)continue;var s=o.data.readUInt32LE(1);if(l(t)!==s)continue;i=O(o.data.subarray(5),!0);break}}return i??=O(t,!!(e&2048)),r||(i=i.replace(/\\/g,`/`)),i}function x(e){return e.indexOf(`\\`)===-1?/^[a-zA-Z]:/.test(e)||/^\//.test(e)?`absolute path: `+e:e.split(`/`).indexOf(`..`)===-1?null:`invalid relative path: `+e:`invalid characters in fileName: `+e}function S(e){for(var t=[],n=0;n<e.length-3;){var r=e.readUInt16LE(n+0),i=e.readUInt16LE(n+2),a=n+4,o=a+i;if(o>e.length)throw Error(`extra field length exceeds extra field buffer size`);var s=e.subarray(a,o);t.push({id:r,data:s}),n=o}return t}function C(e,t,n,r,i,a){if(r===0)return setImmediate(function(){a(null,A(0))});e.read(t,n,r,i,function(e,t){if(e)return a(e);if(t<r)return a(Error(`unexpected EOF`));a()})}i.inherits(w,o);function w(e){o.call(this),this.actualByteCount=0,this.expectedByteCount=e}w.prototype._transform=function(e,t,n){if(this.actualByteCount+=e.length,this.actualByteCount>this.expectedByteCount){var r=`too many bytes in the stream. expected `+this.expectedByteCount+`. got at least `+this.actualByteCount;return n(Error(r))}n(null,e)},w.prototype._flush=function(e){if(this.actualByteCount<this.expectedByteCount){var t=`not enough bytes in the stream. expected `+this.expectedByteCount+`. got only `+this.actualByteCount;return e(Error(t))}e()},i.inherits(T,a);function T(){a.call(this),this.refCount=0}T.prototype.ref=function(){this.refCount+=1},T.prototype.unref=function(){var e=this;if(--e.refCount,e.refCount>0)return;if(e.refCount<0)throw Error(`invalid unref`);e.close(t);function t(t){if(t)return e.emit(`error`,t);e.emit(`close`)}},T.prototype.createReadStream=function(e){e??={};var t=e.start,n=e.end;if(t===n){var r=new s;return setImmediate(function(){r.end()}),r}var i=this._readStreamForRange(t,n),a=!1,o=new E(this);i.on(`error`,function(e){setImmediate(function(){a||o.emit(`error`,e)})}),j(o,function(){i.unpipe(o),o.unref(),i.destroy()});var c=new w(n-t);return o.on(`error`,function(e){setImmediate(function(){a||c.emit(`error`,e)})}),j(c,function(){a=!0,o.unpipe(c),o.destroy()}),i.pipe(o).pipe(c)},T.prototype._readStreamForRange=function(e,t){throw Error(`not implemented`)},T.prototype.read=function(e,t,n,r,i){var a=this.createReadStream({start:r,end:r+n}),o=new c,s=0;o._write=function(n,r,i){n.copy(e,t+s,0,n.length),s+=n.length,i()},o.on(`finish`,i),a.on(`error`,function(e){i(e)}),a.pipe(o)},T.prototype.close=function(e){setImmediate(e)},i.inherits(E,s);function E(e){s.call(this),this.context=e,this.context.ref(),this.unreffedYet=!1}E.prototype._flush=function(e){this.unref(),e()},E.prototype.unref=function(e){this.unreffedYet||(this.unreffedYet=!0,this.context.unref())};var D=`\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xA0`;function O(e,t){if(t)return e.toString(`utf8`);for(var n=``,r=0;r<e.length;r++)n+=D[e[r]];return n}function k(e,t){var n=e.readUInt32LE(t);return e.readUInt32LE(t+4)*4294967296+n}var A=typeof Buffer.allocUnsafe==`function`?function(e){return Buffer.allocUnsafe(e)}:function(e){return new Buffer(e)};function j(e,t){typeof e.destroy==`function`?e._destroy=function(e,n){t(),n?.(e)}:e.destroy=t}function M(e){if(e)throw e}}))(),Rv=16384,zv=16;function Bv(e,t){let n=D(e,t);if(!n.startsWith(e+O))throw Error(`zip 条目越出目标目录:${t}`);if(t.split(`/`).some(e=>e.includes(`:`)))throw Error(`zip 条目名含非法字符「:」(NTFS 数据流形态):${t}`);return n}function Vv(e){return(e.externalFileAttributes>>>16&61440)===Rv||e.fileName.endsWith(`/`)?!0:!(e.versionMadeBy>>>8)&&e.externalFileAttributes===zv}async function Hv(e,t,n){let r=D(t);p(r,{recursive:!0});let i=0,a=0,o=null,s=(e=0)=>{n?.({entries:i,bytes:a+e,current:o})},c=await(0,Lv.openPromise)(e);try{for await(let e of c.eachEntry()){if(e.fileName.startsWith(`__MACOSX/`))continue;let t=Bv(r,e.fileName);if(Vv(e)){p(t,{recursive:!0}),i+=1,s();continue}p(T(t),{recursive:!0}),o=e.fileName,s();let n=0,l=await c.openReadStreamPromise(e);l.on(`data`,e=>{n+=e.length,s(n)}),await he(l,d(t)),a+=n,i+=1,o=null,s()}}finally{c.isOpen&&c.close()}}var Uv={"win32-x64":{dir:`win-x64`,ext:`zip`},"win32-arm64":{dir:`win-arm64`,ext:`zip`},"darwin-arm64":{dir:`darwin-arm64`,ext:`tar.gz`},"darwin-x64":{dir:`darwin-x64`,ext:`tar.gz`},"linux-x64":{dir:`linux-x64`,ext:`tar.gz`},"linux-arm64":{dir:`linux-arm64`,ext:`tar.gz`}},Wv=process.platform===`win32`?[[`node_modules`]]:[[`lib`,`node_modules`]],Gv=5e3,Kv=3e3;function qv(e,t){let n=e.bytes===null?``:`,${Math.round(e.bytes/1048576)} MB`,r=e.current===null?``:`(正在 ${e.current})`;return`[ezn] 已解压 ${e.entries} 项${n}${r}(已用 ${t} 秒) ...`}function Jv(e,t){let n=setInterval(()=>console.error(t()),e);return()=>clearInterval(n)}function Yv(e){return Math.round((Date.now()-e)/1e3)}async function Xv(e,t,n){let r=`node-${e}-${n.platform.dir}.${n.platform.ext}`,i=E(t,`node.download.tmp`),a=E(t,`node.extract.tmp`),o=()=>{v(i,{force:!0}),v(a,{recursive:!0,force:!0})},s=[];n.mirror&&s.push(n.mirror.replace(/\/+$/,``)),s.push(`https://registry.npmmirror.com/-/binary/node`,`https://nodejs.org/dist`),v(i,{force:!0}),v(a,{recursive:!0,force:!0}),p(a,{recursive:!0});for(let t=0;t<s.length;t++){let c=s[t],l=`${c}/${e}/${r}`;console.error(`[ezn] (${t+1}/${s.length}) 正在下载 ${r}\n[ezn] 来源:${c}`);try{let e=Date.now(),t=0,r=bv.default.stream(l,{decompress:!1,timeout:{connect:3e4,response:6e4,socket:6e4}});r.on(`downloadProgress`,e=>{t=e.transferred});let s=Jv(Gv,()=>`[ezn] 已下载 ${Math.round(t/1048576)} MB(已用 ${Yv(e)} 秒) ...`);try{await he(r,d(i))}finally{s()}console.error(`[ezn] 下载完成(${Math.round(b(i).size/1048576)} MB,耗时 ${Yv(e)} 秒),正在解压 ...`);let c=Date.now(),u={entries:0,bytes:null,current:null},f=Jv(Kv,()=>qv(u,Yv(c)));try{n.platform.ext===`zip`?await Hv(i,a,e=>{u=e}):await xv.x({file:i,cwd:a,onentry:e=>{u={entries:u.entries+1,bytes:null,current:e.path}}})}finally{f()}console.error(`[ezn] 解压完成(${u.entries} 项,耗时 ${Yv(c)} 秒)`);let p=g(a),m=p.length===1&&p[0]!==void 0&&b(E(a,p[0])).isDirectory()?E(a,p[0]):a;return v(i,{force:!0}),{src:m,cleanup:o}}catch(e){console.error(`[ezn] 该源失败:${e instanceof Error?e.message:String(e)}`),v(i,{force:!0}),v(a,{recursive:!0,force:!0}),p(a,{recursive:!0})}}v(a,{recursive:!0,force:!0});let c=s[s.length-1]??`https://nodejs.org/dist`;throw Error([`Node 运行时下载失败:所有镜像源均不可用。`,`可尝试的恢复方式:`,` 1. 检查网络后重试;`,` 2. 在 package.json 里配置私有镜像(目录结构需同 nodejs.org/dist)后重试,例如:`,` "ezn": { "node": "24", "mirror": "https://your-mirror.example/node-dist" }`,` 3. 手动放置:下载 ${r}(见 ${c}/${e}/),`,` 解压到 ${n.target}(如带顶层版本目录请把其内容上移一层),`,` 确保可执行文件位于 ${n.nodePath}。`].join(`
|
|
93
|
+
`))}function Zv(e,t,n,r,i){if(r.some(e=>n.length<=e.length&&n.every((t,n)=>e[n]===t))&&f(t)&&b(e).isDirectory()&&b(t).isDirectory()){for(let a of g(e))Zv(E(e,a),E(t,a),[...n,a],r,i);v(e,{recursive:!0,force:!0})}else{if(f(t)){let e=`${t}.old-${i}`;_(t,e),console.error(`[ezn] 同名项已备份:${e}`)}_(e,t)}}async function Qv(e,t,n={}){let r=(e,t)=>{let n=Date.now();for(let r of g(e))Zv(E(e,r),E(t,r),[r],Wv,n)},i=D(e),a=wv(t),o=Tv(i),s=Ev(),c=Uv[s];if(!c)throw Error(`暂不支持的平台:${s}。请手动放置 Node ${a} 到 ${i},确保可执行文件位于 ${o}(Windows 为 node.exe,Unix 为 bin/node)。`);p(i,{recursive:!0});let{src:l,cleanup:u}=await Xv(a,T(i),{target:i,nodePath:o,platform:c,mirror:n.mirror??null});try{console.error(`[ezn] 正在落位运行时文件 ...`),r(l,i)}finally{u()}console.error(`[ezn] Node ${a} 已就绪:${i}`)}function $v(e){return e!==``&&!/[\s"^&|<>()%!]/.test(e)?e:`"${e.replace(/"/g,`\\"`)}"`}function ey(e,t,n){return n?[[e,...t].map($v).join(` `),[]]:[e,[...t]]}function ty(e,t,n={}){return new Promise((r,i)=>{let a=pe(e,t,{windowsHide:!0,...n}),o=null,s=null;a.stdout&&(o=``,a.stdout.on(`data`,e=>o=(o??``)+e)),a.stderr&&(s=``,a.stderr.on(`data`,e=>s=(s??``)+e)),a.on(`error`,i),a.on(`close`,(e,t)=>r({status:e,signal:t,stdout:o,stderr:s}))})}var ny=process.platform===`win32`;function ry(e){return typeof e==`string`?e.trim().split(/\s+/).filter(e=>e.length>0):[...e]}var iy=class e{constructor(e,t){this.path=e,this.rt=t}get npmCliPath(){return kv(this.rt,`npm`)}get npxCliPath(){return kv(this.rt,`npx`)}get major(){return e.probeMajor(this.path)}resolveArgs(e,t){let n=ry(e);if(n.length===0)throw Error(`命令为空`);let r=n[0],i=n.slice(1);return r===`node`?i:r===`npm`?[this.npmCliPath,...i]:r===`npx`?[this.npxCliPath,...i]:t===null?n:[t,...n]}resolveExec(e,t){let n=ry(e);if(n.length===0)throw Error(`命令为空`);let r=n[0],i=n.slice(1),a=this.childEnv(t.env);if(r===`node`)return{file:this.path,argv:i,shell:!1,env:a};if(r===`npm`)return{file:this.path,argv:[this.npmCliPath,...i],shell:!1,env:a};if(r===`npx`)return{file:this.path,argv:[this.npxCliPath,...i],shell:!1,env:a};let o=Mv(this.rt,r);if(o!==null){let e=ny&&/\.(cmd|bat)$/i.test(o),[t,n]=ey(o,i,e);return{file:t,argv:n,shell:e,env:a}}return{file:this.path,argv:n,shell:!1,env:a}}childEnv(e){let t=e??process.env;return{...t,PATH:Nv(this.rt)+(t.PATH??t.Path??``)}}execSync(e,t){let{file:n,argv:r,shell:i,env:a}=this.resolveExec(e,t??{});return me(n,r,{windowsHide:!0,encoding:`utf8`,...t,shell:i,env:a})}exec(e,t){let{file:n,argv:r,shell:i,env:a}=this.resolveExec(e,t??{});return ty(n,r,{...t,shell:i,env:a})}npmSync(e,t){return me(this.path,this.resolveArgs(e,this.npmCliPath),{windowsHide:!0,encoding:`utf8`,...t})}npm(e,t){return ty(this.path,this.resolveArgs(e,this.npmCliPath),t)}npxSync(e,t){return me(this.path,this.resolveArgs(e,this.npxCliPath),{windowsHide:!0,encoding:`utf8`,...t})}npx(e,t){return ty(this.path,this.resolveArgs(e,this.npxCliPath),t)}static probeMajor(e){try{let t=fe(e,[`-v`],{encoding:`utf8`,timeout:15e3,windowsHide:!0}),n=String(t).trim().match(/^v(\d+)\./);return n?Number(n[1]):null}catch{return null}}static async ensure(t,n,r={}){let i=D(t),a=wv(n),o=Number(a.replace(/^v/,``).split(`.`)[0]),s=E(i,`node`),c=Tv(s),l=r.nodeBin??null;if(l){if(!f(l))throw Error(`ezn.nodeBin 指定的 Node 不存在:${l}`);let t=e.probeMajor(l);if(t===null)throw Error(`ezn.nodeBin 指定的 Node 无法执行:${l}`);return t<o&&console.error(`[ezn] 警告:ezn.nodeBin 的 Node 主版本为 ${t},低于建议值 ${o},按用户指定继续。`),console.error(`[ezn] Node 运行时(ezn.nodeBin):${l}`),new e(l,s)}if(f(c)){let t=e.probeMajor(c);if(t!==null&&t>=o&&Av(s))return console.error(`[ezn] Node 运行时就绪:${c}`),new e(c,s);console.error(t===null?`[ezn] 已有 Node 运行时无法执行(疑似损坏),准备重新安装 ...`:t<o?`[ezn] 已有 Node 运行时主版本为 ${t},低于要求 ${o},准备重装 ...`:`[ezn] 已有 Node 运行时缺少自带 npm(上次落位可能中断),准备补齐 ...`)}return await Qv(s,n,{mirror:r.mirror??null}),new e(c,s)}},ay=`24`;function oy(e=ht){let t={};return e.NODE_MIRROR&&(t.mirror=e.NODE_MIRROR),e.NODE_BIN&&(t.nodeBin=e.NODE_BIN),t}async function sy(e){return(await iy.ensure(e,ay,oy())).path}var cy=new Map,ly=1;function uy(){return typeof process.send==`function`}function dy(e,t={},n=3e4){if(!process.send)return Promise.reject(Error(`未由 ezllm 主进程托管(源码运行模式),该功能不可用`));let r=ly++;return new Promise((i,a)=>{let o=setTimeout(()=>{cy.delete(r),a(Error(`主进程未在 ${String(Math.round(n/1e3))}s 内响应(${e})`))},n);cy.set(r,{resolve:e=>i(e),reject:a,timer:o}),process.send?.({type:e,id:r,args:t})})}function fy(e){typeof process.send==`function`&&(process.connected===!1?e():process.connected===!0&&process.once(`disconnect`,e)),process.on(`message`,e=>{let t=e;if(!t?.type||typeof t.id!=`number`)return;let n=cy.get(t.id);n&&(cy.delete(t.id),clearTimeout(n.timer),t.error===void 0?n.resolve(t.data):n.reject(Error(t.error)))})}async function py(e){let t;try{t=(await e.req.json())?.enabled}catch{return e.json({ok:!1,error:`请求体不是合法 JSON`},400)}return typeof t==`boolean`?t:e.json({ok:!1,error:`body 需为 {"enabled": true|false}`},400)}var my=`当前为源码运行模式,更新功能不可用(仅 npm 全局安装的包支持自动更新)`,hy=`服务未由 ezllm 主进程托管,更新功能不可用;请在终端执行 ezllm update`,gy=9e5;function _y(e){let t=()=>{if(!Pt())return!1;let e=T(Mt);return C(e)===`node_modules`||C(T(e))===`node_modules`},n=()=>{let e=Dl()?.autoUpdate;return typeof e!=`boolean`||e},r=()=>t()?uy()?null:hy:my,i=new er;return i.get(`/autostart`,t=>t.json({ok:!0,...yg(e.appDir)})),i.post(`/autostart`,async t=>{let n=await py(t);if(n instanceof Response)return n;if(n){let{itemPath:n}=await bg({entryJs:Rt(),env:tg(),appDir:e.appDir,nodePath:await sy(e.appDir)});return t.json({ok:!0,enabled:!0,itemPath:n,note:`已注册自启项,下次登录时自动启动服务`})}let{removed:r}=await xg({appDir:e.appDir});return t.json({ok:!0,enabled:!1,removed:r,note:r?`已移除自启项,且首次启动不再自动注册(重新开启即可解除)`:`原本未开启,无操作`})}),i.get(`/update`,e=>{let r=Vt(),i=r.pending??null,a=i!==null&&Date.now()-i.startedAt<gy;return e.json({ok:!0,enabled:n(),lastCheck:r.lastCheck??null,lastApply:r.lastApply??null,pendingUpdate:a&&i?i.toVersion:null,supported:t()&&uy(),updating:a})}),i.post(`/update/enabled`,async e=>{let t=await py(e);if(t instanceof Response)return t;try{let e=Dl();e&&kl({...e,autoUpdate:t})}catch{return e.json({ok:!1,error:`写入配置文件失败(文件只读或损坏)`},500)}return e.json({ok:!0,enabled:t,note:t?`自动更新已开启(主进程每小时检查一次)`:`自动更新已关闭(手动检查不受影响)`})}),i.post(`/update/check`,async e=>{let t=r();if(t)return e.json({ok:!1,error:t},400);let n=await dy(`update.check`);return e.json({ok:!0,...n})}),i.post(`/update/apply`,async e=>{let t=r();if(t)return e.json({ok:!1,error:t},400);let n=await dy(`update.apply`);return e.json({ok:!0,fromVersion:n.currentVersion,toVersion:n.latestVersion,updated:n.updated,...n.updated?{restarting:!0}:{},note:n.updated?`已开始更新 ${n.currentVersion} → ${n.latestVersion}:装好后服务会重启(期间界面请求会失败,属正常现象)`:`已是最新版本 ${n.latestVersion}`})}),i}var vy=`服务未由 ezllm 主进程托管(源码运行模式),托管服务不可用;请用 ezllm 启动服务`;function yy(e){let t=(e,t)=>{let n={};return t===null?typeof e.name==`string`&&(n.name=e.name):n.name=t,typeof e.exec==`string`&&(n.exec=e.exec),typeof e.cwd==`string`&&(n.cwd=e.cwd),typeof e.autostart==`boolean`&&(n.autostart=e.autostart),typeof e.start==`boolean`&&(n.start=e.start),Array.isArray(e.args)&&(n.args=e.args.map(e=>String(e))),n},n=()=>uy()?null:Response.json({ok:!1,error:vy},{status:400}),r=new er;return r.onError(wp),r.get(`/`,async e=>{let t=n();if(t)return t;let r=await dy(`svc.list`);return e.json({ok:!0,...r})}),r.post(`/`,async e=>{let r=n();if(r)return r;let i=await vp(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await dy(`svc.create`,t(i,null));return e.json({ok:!0,...a})}),r.put(`/:name`,async e=>{let r=n();if(r)return r;let i=await vp(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await dy(`svc.update`,t(i,e.req.param(`name`)));return e.json({ok:!0,...a})}),r.delete(`/:name`,async e=>{let t=n();if(t)return t;let r=await dy(`svc.remove`,{name:e.req.param(`name`)});return e.json({ok:!0,...r})}),r.post(`/:name/start`,async e=>{let t=n();if(t)return t;let r=await dy(`child.start`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r.post(`/:name/stop`,async e=>{let t=n();if(t)return t;let r=await dy(`child.stop`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r.post(`/:name/restart`,async e=>{let t=n();if(t)return t;let r=await dy(`child.restart`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r}function by(e){let t=`${e}.ellm-bak`;return!f(t)&&(f(e)&&u(e,t),!0)}function xy(e){let t=`${e}.ellm-bak`;return f(t)?(u(t,e),v(t,{force:!0}),!0):!1}function Sy(e,t){return String(e||``).replace(/\/+$/,``)===String(t||``).replace(/\/+$/,``)}var Cy=E(t(),`.claude`,`settings.json`);function wy(){if(!f(Cy))return null;try{return JSON.parse(h(Cy,`utf-8`))}catch(e){throw Error(`${Cy} 不是合法 JSON,拒绝修改(请先手工修复): ${e.message}`)}}function Ty(e){let t=wy();return t?Sy(t?.env?.ANTHROPIC_BASE_URL,e):!1}function Ey(e){p(T(Cy),{recursive:!0});let t=wy()??{};by(Cy),t.env={...t.env??{}},t.env.ANTHROPIC_BASE_URL=e.gatewayBase,t.env.ANTHROPIC_AUTH_TOKEN=e.token,S(Cy,JSON.stringify(t,null,2)+`
|
|
94
|
+
`,`utf-8`)}function Dy(e){if(xy(Cy))return!0;let t=wy();return!t||!Sy(t?.env?.ANTHROPIC_BASE_URL,e)?!1:(delete t.env.ANTHROPIC_BASE_URL,delete t.env.ANTHROPIC_AUTH_TOKEN,t.env&&Object.keys(t.env).length===0&&delete t.env,S(Cy,JSON.stringify(t,null,2)+`
|
|
95
|
+
`,`utf-8`),!0)}var Oy=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,ky=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e){let t=!0,n=!0,r=`Z`;if(typeof e==`string`){let i=e.match(Oy);i?(i[1]||(t=!1,e=`0000-01-01T${e}`),n=!!i[2],n&&e[10]===` `&&(e=e.replace(` `,`T`)),i[2]&&+i[2]>23?e=``:(r=i[3]||null,e=e.toUpperCase(),!r&&n&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=t,this.#t=n,this.#n=r)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};function Ay(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function jy(e,t,n){let r=e.split(/\r\n|\n|\r/g),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
|
|
86
96
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
87
|
-
`))}return i}var Q=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
88
|
-
`,t);return e.charCodeAt(n-1)===13&&n--,n}function
|
|
89
|
-
`;else if(n===102)o+=`\f`;else if(n===114)o+=`\r`;else if(n===101)o+=`\x1B`;else if(n===34)o+=`"`;else if(n===92)o+=`\\`;else throw new Q(`unrecognized escape sequence`,{toml:e.s,ptr:e.p});s=e.p+1,c=0}}else if(n!==32&&n!==9){if(c===2)throw new Q(`invalid escape: only line-ending whitespace may be escaped`,{toml:e.s,ptr:s});c=+(!i&&n===92),s=e.p}throw new Q(`unfinished string`,{toml:e.s,ptr:t})}function
|
|
90
|
-
`),i
|
|
91
|
-
`)?`${i}\n${r}`:i+r;
|
|
97
|
+
`))}return i}var Q=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=Ay(t.toml,t.ptr),i=jy(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};function My(e,t=0){let n=e.indexOf(`
|
|
98
|
+
`,t);return e.charCodeAt(n-1)===13&&n--,n}function Ny(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}if(t<32&&t!==9||t===127)throw new Q(`control characters are not allowed in comments`,{toml:e.s,ptr:e.p})}}function Py(e,t,n){let r;for(;;){for(;(r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10);)e.p++;if(n||r!==35)break;Ny(e)}}function Fy(e,t,n){let r=e.p;if(!n){r=My(e.s,r),e.p=r<0?e.s.length:r;return}for(;e.p<e.s.length;e.p++){let r=e.s.charCodeAt(e.p);if(r===35)Ny(e);else if(r===n||r===t)return}throw new Q(`cannot find end of structure`,{toml:e.s,ptr:r})}var Iy=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Ly=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Ry=/^[+-]?0[0-9_]/;function zy(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)throw new Q(`control characters are not allowed in strings`,{toml:e.s,ptr:e.p});else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r))return a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),c||(o+=e.s.slice(s,e.p)),e.p+=a?3:1,o;else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1){if(n===120||n===117||n===85){let t=0,r=n===120?2:n===117?4:8;for(let n=0;n<r;n++,e.p++){let n=e.s.charCodeAt(e.p+1),r=n>=48&&n<=57?n-48:n>=65&&n<=70?n-65+10:n>=97&&n<=102?n-97+10:-1;if(r<0)throw new Q(`invalid non-hex character in unicode escape`,{toml:e.s,ptr:e.p+1});t=t<<4|r}if(t<0||t>1114111||t>=55296&&t<=57343)throw new Q(`invalid unicode escape`,{toml:e.s,ptr:e.p});o+=String.fromCodePoint(t),s=e.p+1,c=0}else if(n===32||n===9)c=2;else{if(n===98)o+=`\b`;else if(n===116)o+=` `;else if(n===110)o+=`
|
|
99
|
+
`;else if(n===102)o+=`\f`;else if(n===114)o+=`\r`;else if(n===101)o+=`\x1B`;else if(n===34)o+=`"`;else if(n===92)o+=`\\`;else throw new Q(`unrecognized escape sequence`,{toml:e.s,ptr:e.p});s=e.p+1,c=0}}else if(n!==32&&n!==9){if(c===2)throw new Q(`invalid escape: only line-ending whitespace may be escaped`,{toml:e.s,ptr:s});c=+(!i&&n===92),s=e.p}throw new Q(`unfinished string`,{toml:e.s,ptr:t})}function By(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(Ny({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function Vy(e,t,n){let r=e.p,i={toml:e.s,ptr:r};Fy(e,44,n);let a=By(e,r,e.p);if(!a)throw new Q(`incomplete declaration: value expected`,i);if(a===`-inf`)return-1/0;if(a===`inf`||a===`+inf`)return 1/0;if(a===`nan`||a===`+nan`||a===`-nan`)return NaN;if(a===`-0`)return t?0n:0;let o=Iy.test(a);if(o||Ly.test(a)){if(Ry.test(a))throw new Q(`leading zeroes are not allowed`,i);a=a.replace(/_/g,``);let e=+a;if(isNaN(e))throw new Q(`invalid number`,i);if(o){if((o=!Number.isSafeInteger(e))&&!t)throw new Q(`integer value cannot be represented losslessly`,i);(o||t===!0)&&(e=BigInt(a))}return e}let s=new ky(a);if(!s.isValid())throw new Q(`invalid value`,i);return s}function Hy(e,t,n){let r=e.p,i=e.s.charCodeAt(r);if(i===91||i===123){if(!e.d--)throw new Q(`document contains excessively nested structures. aborting.`,{toml:e.s,ptr:r});let t=i===91?Ky(e,n):Gy(e,n);return e.d++,t}if(i===34||i===39)return zy(e);if(i===116){if(e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)throw new Q(`invalid value`,{toml:e.s,ptr:r});return e.p++,!0}if(i===102){if(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)throw new Q(`invalid value`,{toml:e.s,ptr:r});return e.p++,!1}return Vy(e,n,t)}var Uy=/^[a-zA-Z0-9-_]+[ \t]*$/;function Wy(e,t=`=`){let n=e.p,r=n-1,i=[],a=e.s.indexOf(t,n);if(a<0)throw new Q(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});do{let o=e.s.charCodeAt(e.p=++r);if(o!==32&&o!==9){if(o===34||o===39){if(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2))throw new Q(`multiline strings are not allowed in keys`,{toml:e.s,ptr:e.p});let s=zy(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=My(c);if(l>-1)throw new Q(`newlines are not allowed in keys`,{toml:e.s,ptr:l});if(c.trimStart())throw new Q(`found extra tokens after the string part`,{toml:e.s,ptr:e.p});if(a<e.p&&(a=e.s.indexOf(t,e.p),a<0))throw new Q(`incomplete key-value: cannot find end of key`,{toml:e.s,ptr:n});i.push(s)}else{r=e.s.indexOf(`.`,e.p);let t=e.s.slice(e.p,r<0||r>a?a:r);if(!Uy.test(t))throw new Q(`only letter, numbers, dashes and underscores are allowed in keys`,{toml:e.s,ptr:e.p});i.push(t.trimEnd())}}}while(r+1&&r<a);return e.p=a+1,Py(e,!0,!0),i}function Gy(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(Py(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=Wy(e);for(let t=0;t<l.length;t++){if(t&&(o=s?o[a]:o[a]={}),a=l[t],(s=Object.hasOwn(o,a))&&(typeof o[a]!=`object`||r.has(o[a])))throw new Q(`trying to redefine an already defined value`,{toml:e.s,ptr:c});!s&&a===`__proto__`&&Object.defineProperty(o,a,{enumerable:!0,configurable:!0,writable:!0})}if(s)throw new Q(`trying to redefine an already defined value`,{toml:e.s,ptr:e.p});let u=Hy(e,125,t);if(r.add(o[a]=u),Py(e),(i=e.s.charCodeAt(e.p++))===125)return n;if(i!==44)throw new Q(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new Q(`unfinished table encountered`,{toml:e.s,ptr:e.p})}function Ky(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(Py(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Hy(e,93,t)),Py(e),(r=e.s.charCodeAt(e.p++))===93)return n;if(r!==44)throw new Q(`expected comma or end of structure`,{toml:e.s,ptr:e.p-1})}throw new Q(`unfinished array encountered`,{toml:e.s,ptr:e.p})}function qy(e,t,n,r){let i=t,a=n,o,s=!1,c;for(let t=0;t<e.length;t++){if(t){if(i=s?i[o]:i[o]={},a=(c=a[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let e=i.length-1;i=i[e],a=a[e].c}}if(o=e[t],(s=Object.hasOwn(i,o))&&a[o]?.t===0&&a[o]?.d)return null;s||(o===`__proto__`&&(Object.defineProperty(i,o,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(a,o,{enumerable:!0,configurable:!0,writable:!0})),a[o]={t:t<e.length-1&&r===2?3:r,d:!1,i:0,c:{}})}if(c=a[o],c.t!==r&&(r!==1||c.t!==3)||(r===2&&(c.d||(c.d=!0,i[o]=[]),i[o].push(i={}),c.c[c.i++]=c={t:1,d:!1,i:0,c:{}}),c.d))return null;if(c.d=!0,r===1)i=s?i[o]:i[o]={};else if(r===0&&s)return null;return[o,i,c.c]}function Jy(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(Py(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=Wy(r,`]`);if(t){if(e.charCodeAt(r.p-1)!==93)throw new Q(`expected end of table declaration`,{toml:e,ptr:r.p-1});r.p++}let l=qy(n,i,a,t?2:1);if(!l)throw new Q(`trying to redefine an already defined table or value`,{toml:e,ptr:o});c=l[2],s=l[1]}else{o=r.p;let t=qy(Wy(r),s,c,0);if(!t)throw new Q(`trying to redefine an already defined table or value`,{toml:e,ptr:o});t[1][t[0]]=Hy(r,void 0,n)}if(Py(r,!0),r.p<e.length&&(o=e.charCodeAt(r.p))!==10&&o!==13)throw new Q(`each key-value declaration must be followed by an end-of-line`,{toml:e,ptr:r.p});Py(r)}return i}var Yy=`ellm-proxy`,Xy=E(t(),`.codex`,`config.toml`),Zy=`# >>> ellm-proxy codex switch >>>`,Qy=`# <<< ellm-proxy codex switch <<<`;function $y(e){return f(e)?h(e,`utf-8`):null}function eb(){return RegExp(`${Zy}[\\s\\S]*?${Qy}\\n?`)}function tb(e,n,r=(e,t)=>fe(e,t,{stdio:`ignore`}),i=process.platform,a=E(t(),`.zshrc`)){let o=e=>e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/`/g,"\\`").replace(/\$/g,`\\$`),s=(e,t,n)=>{let r=[Zy,`export ${e}="${o(t)}"`,Qy,``].join(`
|
|
100
|
+
`),i=$y(n)??``,a=eb(),s=a.test(i)?i.replace(a,r):i&&!i.endsWith(`
|
|
101
|
+
`)?`${i}\n${r}`:i+r;p(T(n),{recursive:!0}),S(n,s,`utf-8`)};if(i===`win32`)r(`setx`,[e,n]);else if(i!==`darwin`)return!1;else s(e,n,a);return process.env[e]=n,!0}function nb(e,n=E(t(),`.zshrc`),r=process.platform){if(r!==`darwin`)return!1;let i=$y(n),a=i?.match(eb());return!i||!a||!a[0].includes(`export ${e}=`)?!1:(S(n,i.replace(eb(),``),`utf-8`),!0)}function rb(e){try{return Jy(e)?.model_provider===Yy}catch{return!1}}function ib(e,t){let n;try{n=Jy(e)}catch(e){throw Error(`编辑后的 config.toml 不是合法 TOML,已保留原文件: ${e.message}`)}if(t&&n?.model_provider!==Yy)throw Error(`编辑后的 config.toml 顶层 model_provider 不是 "${Yy}",已保留原文件`)}function ab(){let e=$y(Xy);return e?rb(e):!1}function ob(e){let t=(()=>{let e=Yy.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^\\s*\\[model_providers\\.(?:"|')?(?:${e}|ezllm)(?:"|')?\\]\\s*$`)})(),n=e.split(`
|
|
92
102
|
`),r=[],i=!1;for(let e of n){if(t.test(e)){i=!0;continue}i&&/^\s*\[/.test(e)&&(i=!1),i||r.push(e)}return r.join(`
|
|
93
103
|
`).replace(/\n{3,}$/,`
|
|
94
104
|
|
|
95
|
-
`)}function
|
|
96
|
-
`),n=`model_provider = "${
|
|
105
|
+
`)}function sb(e){let t=e=>{let t=e.split(`
|
|
106
|
+
`),n=`model_provider = "${Yy}"`,r=!1,i=t.map(e=>!r&&/^\s*model_provider\s*=/.test(e)&&!e.trim().startsWith(`#`)?(r=!0,n):e);if(r)return i.join(`
|
|
97
107
|
`);let a=i.findIndex(e=>/^\s*\[/.test(e));return a===-1?[...i,n].join(`
|
|
98
108
|
`):(i.splice(a,0,n,``),i.join(`
|
|
99
|
-
`))}
|
|
100
|
-
`);return
|
|
109
|
+
`))};p(T(Xy),{recursive:!0});let n=$y(Xy);if(n!==null)try{Jy(n)}catch(e){throw Error(`${Xy} 不是合法 TOML,拒绝修改(请先手工修复): ${e.message}`)}let r=n??``;by(Xy),r=ob(r),r=t(r);let i=[`[model_providers.${Yy}]`,`name = "ezllm gateway"`,`base_url = "${e.gatewayBase}/v1"`,`wire_api = "chat"`,`env_key = "ELLM_PROXY_API_KEY"`].join(`
|
|
110
|
+
`);return r=r.replace(/\s*$/,``)+`
|
|
101
111
|
|
|
102
|
-
`+
|
|
103
|
-
`,
|
|
112
|
+
`+i+`
|
|
113
|
+
`,ib(r,!0),S(Xy,r,`utf-8`),e.apiKey?tb(`ELLM_PROXY_API_KEY`,e.apiKey):!1}function cb(){let e=xy(Xy),t=nb(`ELLM_PROXY_API_KEY`);if(delete process.env.ELLM_PROXY_API_KEY,e)return!0;let n=$y(Xy);if(!n||!rb(n))return t;let r=ob(n);return r=r.split(`
|
|
104
114
|
`).filter(e=>!/^\s*model_provider\s*=\s*["']?ellm-proxy["']?\s*$/.test(e)).join(`
|
|
105
|
-
`),
|
|
106
|
-
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),
|
|
115
|
+
`),ib(r,!1),S(Xy,r,`utf-8`),!0}var $=I((e=>{var t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),lb=I((e=>{var t=$(),n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),ub=I((e=>{var t=$(),n=lb(),r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]),a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)(t!==`!!`||n!==`tag:yaml.org,2002:`)&&(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
116
|
+
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),db=I((e=>{var t=$(),n=lb();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),fb=I((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),pb=I((e=>{var t=$();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),mb=I((e=>{var t=fb(),n=$(),r=pb();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),hb=I((e=>{var t=db(),n=lb(),r=$(),i=mb(),a=pb(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),gb=I((e=>{var t=$(),n=mb(),r=pb(),i=e=>!e||typeof e!=`function`&&typeof e!=`object`,a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),_b=I((e=>{var t=hb(),n=$(),r=gb(),i=`tag:yaml.org,2002:`;function a(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function o(e,o,s){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=s.schema[n.MAP].createNode?.(s.schema,null,s);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:c,onAnchor:l,onTagObj:u,schema:d,sourceObjects:f}=s,p;if(c&&e&&typeof e==`object`){if(p=f.get(e),p)return p.anchor??(p.anchor=l(e)),new t.Alias(p.anchor);p={anchor:null,node:null},f.set(e,p)}o?.startsWith(`!!`)&&(o=i+o.slice(2));let m=a(e,o,d.tags);if(!m){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return p&&(p.node=t),t}m=e instanceof Map?d[n.MAP]:Symbol.iterator in Object(e)?d[n.SEQ]:d[n.MAP]}u&&(u(m),delete s.onTagObj);let h=m?.createNode?m.createNode(s.schema,e,s):typeof m?.nodeClass?.from==`function`?m.nodeClass.from(s.schema,e,s):new r.Scalar(e);return o?h.tag=o:m.default||(h.tag=m.tag),p&&(p.node=h),h}e.createNode=o})),vb=I((e=>{var t=_b(),n=$(),r=mb();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),yb=I((e=>{var t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
|
|
107
117
|
`)?n(r,t):r.includes(`
|
|
108
118
|
`)?`
|
|
109
|
-
`+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),
|
|
119
|
+
`+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),bb=I((e=>{var t=`flow`,n=`block`,r=`quoted`;function i(e,t,i=`flow`,{indentAtStart:o,lineWidth:s=80,minContentWidth:c=20,onFold:l,onOverflow:u}={}){if(!s||s<0)return e;s<c&&(c=0);let d=Math.max(1+c,1+s-t.length);if(e.length<=d)return e;let f=[],p={},m=s-t.length;typeof o==`number`&&(o>s-Math.max(2,c)?f.push(0):m=s-o);let h,g,_=!1,v=-1,y=-1,b=-1;i===n&&(v=a(e,v,t.length),v!==-1&&(m=v+d));for(let o;o=e[v+=1];){if(i===r&&o===`\\`){switch(y=v,e[v+1]){case`x`:v+=3;break;case`u`:v+=5;break;case`U`:v+=9;break;default:v+=1}b=v}if(o===`
|
|
110
120
|
`)i===n&&(v=a(e,v,t.length)),m=v+t.length+d,h=void 0;else{if(o===` `&&g&&g!==` `&&g!==`
|
|
111
121
|
`&&g!==` `){let t=e[v+1];t&&t!==` `&&t!==`
|
|
112
122
|
`&&t!==` `&&(h=v)}if(v>=m){if(h)f.push(h),m=h+d,h=void 0;else if(i===r){for(;g===` `||g===` `;)g=o,o=e[v+=1],_=!0;let t=v>b+1?v-2:y-1;if(p[t])return e;f.push(t),p[t]=!0,m=t+d,h=void 0}else _=!0}}g=o}if(_&&u&&u(),f.length===0)return e;l&&l();let x=e.slice(0,f[0]);for(let n=0;n<f.length;++n){let a=f[n],o=f[n+1]||e.length;a===0?x=`\n${t}${e.slice(0,o)}`:(i===r&&p[a]&&(x+=`${e[a]}\\`),x+=`\n${t}${e.slice(a+1,o)}`)}return x}function a(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
|
|
113
|
-
`);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=i})),
|
|
123
|
+
`);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=n,e.FOLD_FLOW=t,e.FOLD_QUOTED=r,e.foldFlowLines=i})),xb=I((e=>{var t=gb(),n=bb(),r=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),i=e=>/^(%|---|\.\.\.)/m.test(e);function a(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
|
|
114
124
|
`){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function o(e,t){let a=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return a;let{implicitKey:o}=t,s=t.options.doubleQuotedMinMultiLineLength,c=t.indent||(i(e)?` `:``),l=``,u=0;for(let e=0,t=a[e];t;t=a[++e])if(t===` `&&a[e+1]===`\\`&&a[e+2]===`n`&&(l+=a.slice(u,e)+`\\ `,e+=1,u=e,t=`\\`),t===`\\`)switch(a[e+1]){case`u`:{l+=a.slice(u,e);let t=a.substr(e+2,4);switch(t){case`0000`:l+=`\\0`;break;case`0007`:l+=`\\a`;break;case`000b`:l+=`\\v`;break;case`001b`:l+=`\\e`;break;case`0085`:l+=`\\N`;break;case`00a0`:l+=`\\_`;break;case`2028`:l+=`\\L`;break;case`2029`:l+=`\\P`;break;default:t.substr(0,2)===`00`?l+=`\\x`+t.substr(2):l+=a.substr(e,6)}e+=5,u=e+1}break;case`n`:if(o||a[e+2]===`"`||a.length<s)e+=1;else{for(l+=a.slice(u,e)+`
|
|
115
125
|
|
|
116
126
|
`;a[e+2]===`\\`&&a[e+3]===`n`&&a[e+4]!==`"`;)l+=`
|
|
@@ -128,29 +138,29 @@ import{createRequire as e}from"node:module";import{homedir as t,networkInterface
|
|
|
128
138
|
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${g}`),i=!1,a=r(u,!0);p!==`folded`&&o!==t.Scalar.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let c=n.foldFlowLines(`${T}${e}${b}`,g,n.FOLD_BLOCK,a);if(!i)return`>${E}\n${g}${c}`}return s=s.replace(/\n+/g,`$&${g}`),`|${E}\n${g}${T}${s}${b}`}function d(e,a,o,s){let{type:l,value:d}=e,{actualString:f,implicitKey:p,indent:m,indentStep:h,inFlow:g}=a;if(p&&d.includes(`
|
|
129
139
|
`)||g&&/[[\]{},]/.test(d))return c(d,a);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(d))return p||g||!d.includes(`
|
|
130
140
|
`)?c(d,a):u(e,a,o,s);if(!p&&!g&&l!==t.Scalar.PLAIN&&d.includes(`
|
|
131
|
-
`))return u(e,a,o,s);if(i(d)){if(m===``)return a.forceBlockIndent=!0,u(e,a,o,s);if(p&&m===h)return c(d,a)}let _=d.replace(/\n+/g,`$&\n${m}`);if(f){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(_),{compat:t,tags:n}=a.doc.schema;if(n.some(e)||t?.some(e))return c(d,a)}return p?_:n.foldFlowLines(_,m,n.FOLD_FLOW,r(a,!1))}function f(e,n,r,i){let{implicitKey:a,inFlow:l}=n,f=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:p}=e;p!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(f.value)&&(p=t.Scalar.QUOTE_DOUBLE);let m=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||l?c(f.value,n):u(f,n,r,i);case t.Scalar.QUOTE_DOUBLE:return o(f.value,n);case t.Scalar.QUOTE_SINGLE:return s(f.value,n);case t.Scalar.PLAIN:return d(f,n,r,i);default:return null}},h=m(p);if(h===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(h=m(r),h===null)throw Error(`Unsupported default string type ${r}`)}return h}e.stringifyString=f})),
|
|
141
|
+
`))return u(e,a,o,s);if(i(d)){if(m===``)return a.forceBlockIndent=!0,u(e,a,o,s);if(p&&m===h)return c(d,a)}let _=d.replace(/\n+/g,`$&\n${m}`);if(f){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(_),{compat:t,tags:n}=a.doc.schema;if(n.some(e)||t?.some(e))return c(d,a)}return p?_:n.foldFlowLines(_,m,n.FOLD_FLOW,r(a,!1))}function f(e,n,r,i){let{implicitKey:a,inFlow:l}=n,f=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:p}=e;p!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(f.value)&&(p=t.Scalar.QUOTE_DOUBLE);let m=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||l?c(f.value,n):u(f,n,r,i);case t.Scalar.QUOTE_DOUBLE:return o(f.value,n);case t.Scalar.QUOTE_SINGLE:return s(f.value,n);case t.Scalar.PLAIN:return d(f,n,r,i);default:return null}},h=m(p);if(h===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(h=m(r),h===null)throw Error(`Unsupported default string type ${r}`)}return h}e.stringifyString=f})),Sb=I((e=>{var t=db(),n=$(),r=yb(),i=xb();function a(e,t){let n=Object.assign({blockQuote:!0,commentString:r.stringifyComment,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),i;switch(n.collectionStyle){case`block`:i=!1;break;case`flow`:i=!0;break;default:i=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:i,options:n}}function o(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let r,i;if(n.isScalar(t)){i=t.value;let n=e.filter(e=>e.identify?.(i));if(n.length>1){let e=n.filter(e=>e.test);e.length>0&&(n=e)}r=n.find(e=>e.format===t.format)??n.find(e=>!e.format)}else i=t,r=e.find(e=>e.nodeClass&&i instanceof e.nodeClass);if(!r){let e=i?.constructor?.name??(i===null?`null`:typeof i);throw Error(`Tag not resolved for ${e} value`)}return r}function s(e,r,{anchors:i,doc:a}){if(!a.directives)return``;let o=[],s=(n.isScalar(e)||n.isCollection(e))&&e.anchor;s&&t.anchorIsValid(s)&&(i.add(s),o.push(`&${s}`));let c=e.tag??(r.default?null:r.tag);return c&&o.push(a.directives.tagString(c)),o.join(` `)}function c(e,t,r,a){if(n.isPair(e))return e.toString(t,r,a);if(n.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let c,l=n.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>c=e});c??=o(t.doc.schema.tags,l);let u=s(l,c,t);u.length>0&&(t.indentAtStart=(t.indentAtStart??0)+u.length+1);let d=typeof c.stringify==`function`?c.stringify(l,t,r,a):n.isScalar(l)?i.stringifyString(l,t,r,a):l.toString(t,r,a);return u?n.isScalar(l)||d[0]===`{`||d[0]===`[`?`${u} ${d}`:`${u}\n${t.indent}${d}`:d}e.createStringifyContext=a,e.stringify=c})),Cb=I((e=>{var t=$(),n=gb(),r=Sb(),i=yb();function a({key:e,value:a},o,s,c){let{allNullValues:l,doc:u,indent:d,indentStep:f,options:{commentString:p,indentSeq:m,simpleKeys:h}}=o,g=t.isNode(e)&&e.comment||null;if(h){if(g)throw Error(`With simple keys, key nodes cannot have comments`);if(t.isCollection(e)||!t.isNode(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let _=!h&&(!e||g&&a==null&&!o.inFlow||t.isCollection(e)||(t.isScalar(e)?e.type===n.Scalar.BLOCK_FOLDED||e.type===n.Scalar.BLOCK_LITERAL:typeof e==`object`));o=Object.assign({},o,{allNullValues:!1,implicitKey:!_&&(h||!l),indent:d+f});let v=!1,y=!1,b=r.stringify(e,o,()=>v=!0,()=>y=!0);if(!_&&!o.inFlow&&b.length>1024){if(h)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);_=!0}if(o.inFlow){if(l||a==null)return v&&s&&s(),b===``?`?`:_?`? ${b}`:b}else if(l&&!h||a==null&&_)return b=`? ${b}`,g&&!v?b+=i.lineComment(b,o.indent,p(g)):y&&c&&c(),b;v&&(g=null),_?(g&&(b+=i.lineComment(b,o.indent,p(g))),b=`? ${b}\n${d}:`):(b=`${b}:`,g&&(b+=i.lineComment(b,o.indent,p(g))));let x,S,C;t.isNode(a)?(x=!!a.spaceBefore,S=a.commentBefore,C=a.comment):(x=!1,S=null,C=null,a&&typeof a==`object`&&(a=u.createNode(a))),o.implicitKey=!1,!_&&!g&&t.isScalar(a)&&(o.indentAtStart=b.length+1),y=!1,!m&&f.length>=2&&!o.inFlow&&!_&&t.isSeq(a)&&!a.flow&&!a.tag&&!a.anchor&&(o.indent=o.indent.substring(2));let w=!1,T=r.stringify(a,o,()=>w=!0,()=>y=!0),E=` `;if(g||x||S){if(E=x?`
|
|
132
142
|
`:``,S){let e=p(S);E+=`\n${i.indentComment(e,o.indent)}`}T===``&&!o.inFlow?E===`
|
|
133
143
|
`&&C&&(E=`
|
|
134
144
|
|
|
135
145
|
`):E+=`\n${o.indent}`}else if(!_&&t.isCollection(a)){let e=T[0],t=T.indexOf(`
|
|
136
146
|
`),n=t!==-1,r=o.inFlow??a.flow??a.items.length===0;if(n||!r){let r=!1;if(n&&(e===`&`||e===`!`)){let n=T.indexOf(` `);e===`&`&&n!==-1&&n<t&&T[n+1]===`!`&&(n=T.indexOf(` `,n+1)),(n===-1||t<n)&&(r=!0)}r||(E=`\n${o.indent}`)}}else(T===``||T[0]===`
|
|
137
|
-
`)&&(E=``);return b+=E+T,o.inFlow?w&&s&&s():C&&!w?b+=i.lineComment(b,o.indent,p(C)):y&&c&&c(),b}e.stringifyPair=a})),
|
|
147
|
+
`)&&(E=``);return b+=E+T,o.inFlow?w&&s&&s():C&&!w?b+=i.lineComment(b,o.indent,p(C)):y&&c&&c(),b}e.stringifyPair=a})),wb=I((e=>{var t=Te(`process`);function n(e,...t){e===`debug`&&console.log(...t)}function r(e,n){(e===`debug`||e===`warn`)&&(typeof t.emitWarning==`function`?t.emitWarning(n):console.warn(n))}e.debug=n,e.warn=r})),Tb=I((e=>{var t=$(),n=gb(),r=`<<`,i={identify:e=>e===r||typeof e==`symbol`&&e.description===r,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new n.Scalar(Symbol(r)),{addToJSMap:o}),stringify:()=>r},a=(e,r)=>(i.identify(r)||t.isScalar(r)&&(!r.type||r.type===n.Scalar.PLAIN)&&i.identify(r.value))&&e?.doc.schema.tags.some(e=>e.tag===i.tag&&e.default);function o(e,n,r){let i=c(e,r);if(t.isSeq(i))for(let t of i.items)s(e,n,t);else if(Array.isArray(i))for(let t of i)s(e,n,t);else s(e,n,i)}function s(e,n,r){let i=c(e,r);if(!t.isMap(i))throw Error(`Merge sources must be maps or map aliases`);let a=i.toJSON(null,e,Map);for(let[e,t]of a)n instanceof Map?n.has(e)||n.set(e,t):n instanceof Set?n.add(e):Object.prototype.hasOwnProperty.call(n,e)||Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return n}function c(e,n){return e&&t.isAlias(n)?n.resolve(e.doc,e):n}e.addMergeToJSMap=o,e.isMergeKey=a,e.merge=i})),Eb=I((e=>{var t=wb(),n=Tb(),r=Sb(),i=$(),a=pb();function o(e,t,{key:r,value:o}){if(i.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,o);else if(n.isMergeKey(e,r))n.addMergeToJSMap(e,t,o);else{let n=a.toJS(r,``,e);if(t instanceof Map)t.set(n,a.toJS(o,n,e));else if(t instanceof Set)t.add(n);else{let i=s(r,n,e),c=a.toJS(o,i,e);i in t?Object.defineProperty(t,i,{value:c,writable:!0,enumerable:!0,configurable:!0}):t[i]=c}}return t}function s(e,n,a){if(n===null)return``;if(typeof n!=`object`)return String(n);if(i.isNode(e)&&a?.doc){let n=r.createStringifyContext(a.doc,{});n.anchors=new Set;for(let e of a.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!a.mapKeyWarned){let e=JSON.stringify(i);e.length>40&&(e=e.substring(0,36)+`..."`),t.warn(a.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),a.mapKeyWarned=!0}return i}return JSON.stringify(n)}e.addPairToJSMap=o})),Db=I((e=>{var t=_b(),n=Cb(),r=Eb(),i=$();function a(e,n,r){return new o(t.createNode(e,void 0,r),t.createNode(n,void 0,r))}var o=class e{constructor(e,t=null){Object.defineProperty(this,i.NODE_TYPE,{value:i.PAIR}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return i.isNode(n)&&(n=n.clone(t)),i.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,r){return e?.doc?n.stringifyPair(this,e,t,r):JSON.stringify(this)}};e.Pair=o,e.createPair=a})),Ob=I((e=>{var t=$(),n=Sb(),r=yb();function i(e,t,n){return(t.inFlow??e.flow?o:a)(e,t,n)}function a({comment:e,items:i},a,{blockItemPrefix:o,flowChars:c,itemIndent:l,onChompKeep:u,onComment:d}){let{indent:f,options:{commentString:p}}=a,m=Object.assign({},a,{indent:l,type:null}),h=!1,g=[];for(let e=0;e<i.length;++e){let c=i[e],u=null;if(t.isNode(c))!h&&c.spaceBefore&&g.push(``),s(a,g,c.commentBefore,h),c.comment&&(u=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(!h&&e.spaceBefore&&g.push(``),s(a,g,e.commentBefore,h))}h=!1;let d=n.stringify(c,m,()=>u=null,()=>h=!0);u&&(d+=r.lineComment(d,l,p(u))),h&&u&&(h=!1),g.push(o+d)}let _;if(g.length===0)_=c.start+c.end;else{_=g[0];for(let e=1;e<g.length;++e){let t=g[e];_+=t?`\n${f}${t}`:`
|
|
138
148
|
`}}return e?(_+=`
|
|
139
149
|
`+r.indentComment(p(e),f),d&&d()):h&&u&&u(),_}function o({items:e},i,{flowChars:a,itemIndent:o}){let{indent:c,indentStep:l,flowCollectionPadding:u,options:{commentString:d}}=i;o+=l;let f=Object.assign({},i,{indent:o,inFlow:!0,type:null}),p=!1,m=0,h=[];for(let a=0;a<e.length;++a){let c=e[a],l=null;if(t.isNode(c))c.spaceBefore&&h.push(``),s(i,h,c.commentBefore,!1),c.comment&&(l=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(e.spaceBefore&&h.push(``),s(i,h,e.commentBefore,!1),e.comment&&(p=!0));let n=t.isNode(c.value)?c.value:null;n?(n.comment&&(l=n.comment),n.commentBefore&&(p=!0)):c.value==null&&e?.comment&&(l=e.comment)}l&&(p=!0);let u=n.stringify(c,f,()=>l=null);p||=h.length>m||u.includes(`
|
|
140
150
|
`),a<e.length-1?u+=`,`:i.options.trailingComma&&(i.options.lineWidth>0&&(p||=h.reduce((e,t)=>e+t.length+2,2)+(u.length+2)>i.options.lineWidth),p&&(u+=`,`)),l&&(u+=r.lineComment(u,o,d(l))),h.push(u),m=h.length}let{start:g,end:_}=a;if(h.length===0)return g+_;if(!p){let e=h.reduce((e,t)=>e+t.length+2,2);p=i.options.lineWidth>0&&e>i.options.lineWidth}if(p){let e=g;for(let t of h)e+=t?`\n${l}${c}${t}`:`
|
|
141
|
-
`;return`${e}\n${c}${_}`}return`${g}${u}${h.join(` `)}${u}${_}`}function s({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=i})),
|
|
142
|
-
`:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),lS=L((e=>{var t=$(),n=Jx(),r=Lx(),i=Qx();function a(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function o(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}var s={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:a,createNode:o};e.createPairs=o,e.pairs=s,e.resolvePairs=a})),uS=L((e=>{var t=$(),n=Px(),r=Xx(),i=Qx(),a=lS(),o=class e extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;var s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),dS=L((e=>{var t=Lx();function n({value:e,source:t},n){return t&&(e?r:i).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var r={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r})),fS=L((e=>{var t=Lx(),n=rS(),r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),pS=L((e=>{var t=rS(),n=e=>typeof e==`bigint`||Number.isInteger(e);function r(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function i(e,r,i){let{value:a}=e;if(n(a)){let e=a.toString(r);return a<0?`-`+i+e.substr(1):i+e}return t.stringifyNumber(e)}var a={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),stringify:e=>i(e,2,`0b`)},o={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>i(e,8,`0`)},s={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},c={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)};e.int=s,e.intBin=a,e.intHex=c,e.intOct=o})),mS=L((e=>{var t=$(),n=Jx(),r=Xx(),i=class e extends r.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;var a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),hS=L((e=>{var t=rS();function n(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function r(e){let{value:n}=e,r=e=>e;if(typeof n==`bigint`)r=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let i=``;n<0&&(i=`-`,n*=r(-1));let a=r(60),o=[n%a];return n<60?o.unshift(0):(n=(n-o[0])/a,o.unshift(n%a),n>=60&&(n=(n-o[0])/a,o.unshift(n))),i+o.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var i={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>n(e,r),stringify:r},a={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>n(e,!1),stringify:r},o={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(o.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,r,i,a,s,c,l]=t.map(Number),u=t[7]?Number((t[7]+`00`).substr(1,3)):0,d=Date.UTC(r,i-1,a,s||0,c||0,l||0,u),f=t[8];if(f&&f!==`Z`){let e=n(f,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=a,e.intTime=i,e.timestamp=o})),gS=L((e=>{var t=Zx(),n=tS(),r=$x(),i=eS(),a=cS(),o=dS(),s=fS(),c=pS(),l=Kx(),u=uS(),d=lS(),f=mS(),p=hS();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),_S=L((e=>{var t=Zx(),n=tS(),r=$x(),i=eS(),a=nS(),o=iS(),s=aS(),c=oS(),l=sS(),u=cS(),d=Kx(),f=uS(),p=lS(),m=gS(),h=mS(),g=hS(),_=new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function b(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=b})),vS=L((e=>{var t=$(),n=Zx(),r=$x(),i=eS(),a=_S(),o=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class e{constructor({compat:e,customTags:s,merge:c,resolveKnownTags:l,schema:u,sortMapEntries:d,toStringDefaults:f}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof u==`string`&&u||`core`,this.knownTags=l?a.coreKnownTags:{},this.tags=a.getTags(s,this.name,c),this.toStringOptions=f??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof d==`function`?d:d===!0?o:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}})),yS=L((e=>{var t=$(),n=Ux(),r=Bx();function i(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
|
|
151
|
+
`;return`${e}\n${c}${_}`}return`${g}${u}${h.join(` `)}${u}${_}`}function s({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=i})),kb=I((e=>{var t=Ob(),n=Eb(),r=vb(),i=$(),a=Db(),o=gb();function s(e,t){let n=i.isScalar(t)?t.value:t;for(let r of e)if(i.isPair(r)&&(r.key===t||r.key===n||i.isScalar(r.key)&&r.key.value===n))return r}e.YAMLMap=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(i.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,o=new this(e),s=(e,s)=>{if(typeof i==`function`)s=i.call(t,e,s);else if(Array.isArray(i)&&!i.includes(e))return;(s!==void 0||r)&&o.items.push(a.createPair(e,s,n))};if(t instanceof Map)for(let[e,n]of t)s(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))s(e,t[e]);return typeof e.sortMapEntries==`function`&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;n=i.isPair(e)?e:!e||typeof e!=`object`||!(`key`in e)?new a.Pair(e,e?.value):new a.Pair(e.key,e.value);let r=s(this.items,n.key),c=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);i.isScalar(r.value)&&o.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(c){let e=this.items.findIndex(e=>c(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=s(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=s(this.items,e)?.value;return(!t&&i.isScalar(n)?n.value:n)??void 0}has(e){return!!s(this.items,e)}set(e,t){this.add(new a.Pair(e,t),!0)}toJSON(e,t,r){let i=r?new r:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let e of this.items)n.addPairToJSMap(t,i,e);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let e of this.items)if(!i.isPair(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),t.stringifyCollection(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:r,onComment:n})}},e.findPair=s})),Ab=I((e=>{var t=$(),n=kb();e.map={collection:`map`,default:!0,nodeClass:n.YAMLMap,tag:`tag:yaml.org,2002:map`,resolve(e,n){return t.isMap(e)||n(`Expected a mapping for this tag`),e},createNode:(e,t,r)=>n.YAMLMap.from(e,t,r)}})),jb=I((e=>{var t=_b(),n=Ob(),r=vb(),i=$(),a=gb(),o=pb(),s=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(i.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=c(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=c(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&i.isScalar(r)?r.value:r}has(e){let t=c(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=c(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];i.isScalar(r)&&a.isScalarValue(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(o.toJS(e,String(r++),t));return n}toString(e,t,r){return e?n.stringifyCollection(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,n,r){let{replacer:i}=r,a=new this(e);if(n&&Symbol.iterator in Object(n)){let e=0;for(let o of n){if(typeof i==`function`){let t=n instanceof Set?o:String(e++);o=i.call(n,t,o)}a.items.push(t.createNode(o,void 0,r))}}return a}};function c(e){let t=i.isScalar(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}e.YAMLSeq=s})),Mb=I((e=>{var t=$(),n=jb();e.seq={collection:`seq`,default:!0,nodeClass:n.YAMLSeq,tag:`tag:yaml.org,2002:seq`,resolve(e,n){return t.isSeq(e)||n(`Expected a sequence for this tag`),e},createNode:(e,t,r)=>n.YAMLSeq.from(e,t,r)}})),Nb=I((e=>{var t=xb();e.string={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,n,r,i){return n=Object.assign({actualString:!0},n),t.stringifyString(e,n,r,i)}}})),Pb=I((e=>{var t=gb(),n={identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new t.Scalar(null),stringify:({source:e},t)=>typeof e==`string`&&n.test.test(e)?e:t.options.nullStr};e.nullTag=n})),Fb=I((e=>{var t=gb(),n={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new t.Scalar(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},r){return e&&n.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?r.options.trueStr:r.options.falseStr}};e.boolTag=n})),Ib=I((e=>{function t({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}e.stringifyNumber=t})),Lb=I((e=>{var t=gb(),n=Ib(),r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let n=new t.Scalar(parseFloat(e)),r=e.indexOf(`.`);return r!==-1&&e[e.length-1]===`0`&&(n.minFractionDigits=e.length-r-1),n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),Rb=I((e=>{var t=Ib(),n=e=>typeof e==`bigint`||Number.isInteger(e),r=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function i(e,r,i){let{value:a}=e;return n(a)&&a>=0?i+a.toString(r):t.stringifyNumber(e)}e.int={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},e.intHex={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)},e.intOct={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>r(e,2,8,n),stringify:e=>i(e,8,`0o`)}})),zb=I((e=>{var t=Ab(),n=Pb(),r=Mb(),i=Nb(),a=Fb(),o=Lb(),s=Rb();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),Bb=I((e=>{var t=gb(),n=Ab(),r=Mb();function i(e){return typeof e==`bigint`||Number.isInteger(e)}var a=({value:e})=>JSON.stringify(e),o=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:a},{identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:a},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:a},{identify:i,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>i(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:a}];e.schema=[n.map,r.seq].concat(o,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),Vb=I((e=>{var t=Te(`buffer`),n=gb(),r=xb();e.binary={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,n){if(typeof t.Buffer==`function`)return t.Buffer.from(e,`base64`);if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return n(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:i,value:a},o,s,c){if(!a)return``;let l=a,u;if(typeof t.Buffer==`function`)u=l instanceof t.Buffer?l.toString(`base64`):t.Buffer.from(l.buffer).toString(`base64`);else if(typeof btoa==`function`){let e=``;for(let t=0;t<l.length;++t)e+=String.fromCharCode(l[t]);u=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(i??=n.Scalar.BLOCK_LITERAL,i!==n.Scalar.QUOTE_DOUBLE){let e=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),t=Math.ceil(u.length/e),r=Array(t);for(let n=0,i=0;n<t;++n,i+=e)r[n]=u.substr(i,e);u=r.join(i===n.Scalar.BLOCK_LITERAL?`
|
|
152
|
+
`:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),Hb=I((e=>{var t=$(),n=Db(),r=gb(),i=jb();function a(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function o(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}var s={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:a,createNode:o};e.createPairs=o,e.pairs=s,e.resolvePairs=a})),Ub=I((e=>{var t=$(),n=pb(),r=kb(),i=jb(),a=Hb(),o=class e extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;var s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),Wb=I((e=>{var t=gb();function n({value:e,source:t},n){return t&&(e?r:i).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var r={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new t.Scalar(!0),stringify:n},i={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r})),Gb=I((e=>{var t=gb(),n=Ib(),r={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():n.stringifyNumber(e)}},e.floatNaN=r})),Kb=I((e=>{var t=Ib(),n=e=>typeof e==`bigint`||Number.isInteger(e);function r(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function i(e,r,i){let{value:a}=e;if(n(a)){let e=a.toString(r);return a<0?`-`+i+e.substr(1):i+e}return t.stringifyNumber(e)}var a={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),stringify:e=>i(e,2,`0b`)},o={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>i(e,8,`0`)},s={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},c={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)};e.int=s,e.intBin=a,e.intHex=c,e.intOct=o})),qb=I((e=>{var t=$(),n=Db(),r=kb(),i=class e extends r.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;var a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),Jb=I((e=>{var t=Ib();function n(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function r(e){let{value:n}=e,r=e=>e;if(typeof n==`bigint`)r=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let i=``;n<0&&(i=`-`,n*=r(-1));let a=r(60),o=[n%a];return n<60?o.unshift(0):(n=(n-o[0])/a,o.unshift(n%a),n>=60&&(n=(n-o[0])/a,o.unshift(n))),i+o.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var i={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:r})=>n(e,r),stringify:r},a={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>n(e,!1),stringify:r},o={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(o.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,r,i,a,s,c,l]=t.map(Number),u=t[7]?Number((t[7]+`00`).substr(1,3)):0,d=Date.UTC(r,i-1,a,s||0,c||0,l||0,u),f=t[8];if(f&&f!==`Z`){let e=n(f,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=a,e.intTime=i,e.timestamp=o})),Yb=I((e=>{var t=Ab(),n=Pb(),r=Mb(),i=Nb(),a=Vb(),o=Wb(),s=Gb(),c=Kb(),l=Tb(),u=Ub(),d=Hb(),f=qb(),p=Jb();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),Xb=I((e=>{var t=Ab(),n=Pb(),r=Mb(),i=Nb(),a=Fb(),o=Lb(),s=Rb(),c=zb(),l=Bb(),u=Vb(),d=Tb(),f=Ub(),p=Hb(),m=Yb(),h=qb(),g=Jb(),_=new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function b(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=b})),Zb=I((e=>{var t=$(),n=Ab(),r=Mb(),i=Nb(),a=Xb(),o=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class e{constructor({compat:e,customTags:s,merge:c,resolveKnownTags:l,schema:u,sortMapEntries:d,toStringDefaults:f}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof u==`string`&&u||`core`,this.knownTags=l?a.coreKnownTags:{},this.tags=a.getTags(s,this.name,c),this.toStringOptions=f??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof d==`function`?d:d===!0?o:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}})),Qb=I((e=>{var t=$(),n=Sb(),r=yb();function i(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
|
|
143
153
|
`)?(a.push(`...`),a.push(r.indentComment(t,``))):a.push(`... ${t}`)}else a.push(`...`)}else{let t=e.comment;t&&l&&(t=t.replace(/^\n+/,``)),t&&((!l||u)&&a[a.length-1]!==``&&a.push(``),a.push(r.indentComment(c(t),``)))}return a.join(`
|
|
144
154
|
`)+`
|
|
145
|
-
`}e.stringifyDocument=i}))
|
|
146
|
-
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}})),
|
|
147
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let n of e.items){for(let e of n.start)if(e.type===`newline`)return!0;if(n.sep){for(let e of n.sep)if(e.type===`newline`)return!0}if(t(n.key)||t(n.value))return!0}return!1;default:return!0}}e.containsNewline=t})),
|
|
155
|
+
`}e.stringifyDocument=i})),$b=I((e=>{var t=hb(),n=vb(),r=$(),i=Db(),a=pb(),o=Zb(),s=Qb(),c=db(),l=fb(),u=_b(),d=ub(),f=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let i=null;typeof t==`function`||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new d.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let t=Object.create(e.prototype,{[r.NODE_TYPE]:{value:r.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=r.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){p(this.contents)&&this.contents.add(e)}addIn(e,t){p(this.contents)&&this.contents.addIn(e,t)}createAlias(e,n){if(!e.anchor){let t=c.anchorNames(this);e.anchor=!n||t.has(n)?c.findNewAnchor(n||`a`,t):n}return new t.Alias(e.anchor)}createNode(e,t,n){let i;if(typeof t==`function`)e=t.call({"":e},``,e),i=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:d,tag:f}=n??{},{onAnchor:p,setAnchors:m,sourceObjects:h}=c.createNodeAnchors(this,o||`a`),g={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:p,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:h},_=u.createNode(e,f,g);return s&&r.isCollection(_)&&(_.flow=!0),m(),_}createPair(e,t,n={}){let r=this.createNode(e,null,n),a=this.createNode(t,null,n);return new i.Pair(r,a)}delete(e){return p(this.contents)?this.contents.delete(e):!1}deleteIn(e){return n.isEmptyPath(e)?this.contents!=null&&(this.contents=null,!0):p(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return n.isEmptyPath(e)?!t&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return r.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return n.isEmptyPath(e)?this.contents!==void 0:r.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=n.collectionFromPath(this.schema,[e],t):p(this.contents)&&this.contents.set(e,t)}setIn(e,t){n.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=n.collectionFromPath(this.schema,Array.from(e),t):p(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new d.Directives({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new d.Directives({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new o.Schema(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:o}={}){let s={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},c=a.toJS(this.contents,t??``,s);if(typeof i==`function`)for(let{count:e,res:t}of s.anchors.values())i(t,e);return typeof o==`function`?l.applyReviver(o,{"":c},``,c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return s.stringifyDocument(this,e)}};function p(e){if(r.isCollection(e))return!0;throw Error(`Expected a YAML collection as document contents`)}e.Document=f})),ex=I((e=>{var t=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},n=class extends t{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},r=class extends t{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
|
|
156
|
+
`),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}})),tx=I((e=>{function t(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}e.resolveProps=t})),nx=I((e=>{function t(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
|
|
157
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let n of e.items){for(let e of n.start)if(e.type===`newline`)return!0;if(n.sep){for(let e of n.sep)if(e.type===`newline`)return!0}if(t(n.key)||t(n.value))return!0}return!1;default:return!0}}e.containsNewline=t})),rx=I((e=>{var t=nx();function n(e,n,r){if(n?.type===`flow-collection`){let i=n.end[0];i.indent===e&&(i.source===`]`||i.source===`}`)&&t.containsNewline(n)&&r(i,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}e.flowIndentCheck=n})),ix=I((e=>{var t=$();function n(e,n,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let a=typeof i==`function`?i:(e,n)=>e===n||t.isScalar(e)&&t.isScalar(n)&&e.value===n.value;return n.some(e=>a(e.key,r))}e.mapIncludes=n})),ax=I((e=>{var t=Db(),n=kb(),r=tx(),i=nx(),a=rx(),o=ix(),s=`All mapping items must start at the same column`;function c({composeNode:e,composeEmptyNode:c},l,u,d,f){let p=new((f?.nodeClass)??n.YAMLMap)(l.schema);l.atRoot&&=!1;let m=u.offset,h=null;for(let n of u.items){let{start:f,key:g,sep:_,value:v}=n,y=r.resolveProps(f,{indicator:`explicit-key-ind`,next:g??_?.[0],offset:m,onError:d,parentIndent:u.indent,startOnNewline:!0}),b=!y.found;if(b){if(g&&(g.type===`block-seq`?d(m,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in g&&g.indent!==u.indent&&d(m,`BAD_INDENT`,s)),!y.anchor&&!y.tag&&!_){h=y.end,y.comment&&(p.comment?p.comment+=`
|
|
148
158
|
`+y.comment:p.comment=y.comment);continue}(y.newlineAfterProp||i.containsNewline(g))&&d(g??f[f.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else y.found?.indent!==u.indent&&d(m,`BAD_INDENT`,s);l.atKey=!0;let x=y.end,S=g?e(l,g,y,d):c(l,x,f,null,y,d);l.schema.compat&&a.flowIndentCheck(u.indent,g,d),l.atKey=!1,o.mapIncludes(l,p.items,S)&&d(x,`DUPLICATE_KEY`,`Map keys must be unique`);let C=r.resolveProps(_??[],{indicator:`map-value-ind`,next:v,offset:S.range[2],onError:d,parentIndent:u.indent,startOnNewline:!g||g.type===`block-scalar`});if(m=C.end,C.found){b&&(v?.type===`block-map`&&!C.hasNewline&&d(m,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),l.options.strict&&y.start<C.found.offset-1024&&d(S.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let r=v?e(l,v,C,d):c(l,m,_,null,C,d);l.schema.compat&&a.flowIndentCheck(u.indent,v,d),m=r.range[2];let i=new t.Pair(S,r);l.options.keepSourceTokens&&(i.srcToken=n),p.items.push(i)}else{b&&d(S.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),C.comment&&(S.comment?S.comment+=`
|
|
149
|
-
`+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=c})),
|
|
159
|
+
`+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=c})),ox=I((e=>{var t=jb(),n=tx(),r=rx();function i({composeNode:e,composeEmptyNode:i},a,o,s,c){let l=new((c?.nodeClass)??t.YAMLSeq)(a.schema);a.atRoot&&=!1,a.atKey&&=!1;let u=o.offset,d=null;for(let{start:t,value:c}of o.items){let f=n.resolveProps(t,{indicator:`seq-item-ind`,next:c,offset:u,onError:s,parentIndent:o.indent,startOnNewline:!0});if(!f.found){if(f.anchor||f.tag||c)c?.type===`block-seq`?s(f.end,`BAD_INDENT`,`All sequence items must start at the same column`):s(u,`MISSING_CHAR`,`Sequence item without - indicator`);else{d=f.end,f.comment&&(l.comment=f.comment);continue}}let p=c?e(a,c,f,s):i(a,f.end,t,null,f,s);a.schema.compat&&r.flowIndentCheck(o.indent,c,s),u=p.range[2],l.items.push(p)}return l.range=[o.offset,u,d??u],l}e.resolveBlockSeq=i})),sx=I((e=>{function t(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}e.resolveEnd=t})),cx=I((e=>{var t=$(),n=Db(),r=kb(),i=jb(),a=sx(),o=tx(),s=nx(),c=ix(),l=`Block collections are not allowed within flow collections`,u=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function d({composeNode:e,composeEmptyNode:d},f,p,m,h){let g=p.start.source===`{`,_=g?`flow map`:`flow sequence`,v=new((h?.nodeClass)??(g?r.YAMLMap:i.YAMLSeq))(f.schema);v.flow=!0;let y=f.atRoot;y&&(f.atRoot=!1),f.atKey&&=!1;let b=p.offset+p.start.source.length;for(let i=0;i<p.items.length;++i){let a=p.items[i],{start:h,key:y,sep:x,value:S}=a,C=o.resolveProps(h,{flow:_,indicator:`explicit-key-ind`,next:y??x?.[0],offset:b,onError:m,parentIndent:p.indent,startOnNewline:!1});if(!C.found){if(!C.anchor&&!C.tag&&!x&&!S){i===0&&C.comma?m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`):i<p.items.length-1&&m(C.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${_}`),C.comment&&(v.comment?v.comment+=`
|
|
150
160
|
`+C.comment:v.comment=C.comment),b=C.end;continue}!g&&f.options.strict&&s.containsNewline(y)&&m(y,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(i===0)C.comma&&m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`);else if(C.comma||m(C.start,`MISSING_CHAR`,`Missing , between ${_} items`),C.comment){let e=``;loop:for(let t of h)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let n=v.items[v.items.length-1];t.isPair(n)&&(n=n.value??n.key),n.comment?n.comment+=`
|
|
151
161
|
`+e:n.comment=e,C.comment=C.comment.substring(e.length+1)}}if(!g&&!x&&!C.found){let t=S?e(f,S,C,m):d(f,C.end,x,null,C,m);v.items.push(t),b=t.range[2],u(S)&&m(t.range,`BLOCK_IN_FLOW`,l)}else{f.atKey=!0;let t=C.end,i=y?e(f,y,C,m):d(f,t,h,null,C,m);u(y)&&m(i.range,`BLOCK_IN_FLOW`,l),f.atKey=!1;let s=o.resolveProps(x??[],{flow:_,indicator:`map-value-ind`,next:S,offset:i.range[2],onError:m,parentIndent:p.indent,startOnNewline:!1});if(s.found){if(!g&&!C.found&&f.options.strict){if(x)for(let e of x){if(e===s.found)break;if(e.type===`newline`){m(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}C.start<s.found.offset-1024&&m(s.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else S&&(`source`in S&&S.source?.[0]===`:`?m(S,`MISSING_CHAR`,`Missing space after : in ${_}`):m(s.start,`MISSING_CHAR`,`Missing , or : between ${_} items`));let w=S?e(f,S,s,m):s.found?d(f,s.end,x,null,s,m):null;w?u(S)&&m(w.range,`BLOCK_IN_FLOW`,l):s.comment&&(i.comment?i.comment+=`
|
|
152
162
|
`+s.comment:i.comment=s.comment);let T=new n.Pair(i,w);if(f.options.keepSourceTokens&&(T.srcToken=a),g){let e=v;c.mapIncludes(f,e.items,i)&&m(t,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(T)}else{let e=new r.YAMLMap(f.schema);e.flow=!0,e.items.push(T);let t=(w??i).range;e.range=[i.range[0],t[1],t[2]],v.items.push(e)}b=w?w.range[2]:s.end}}let x=g?`}`:`]`,[S,...C]=p.end,w=b;if(S?.source===x)w=S.offset+S.source.length;else{let e=_[0].toUpperCase()+_.substring(1),t=y?`${e} must end with a ${x}`:`${e} in block collection must be sufficiently indented and end with a ${x}`;m(b,y?`MISSING_CHAR`:`BAD_INDENT`,t),S&&S.source.length!==1&&C.unshift(S)}if(C.length>0){let e=a.resolveEnd(C,w,f.options.strict,m);e.comment&&(v.comment?v.comment+=`
|
|
153
|
-
`+e.comment:v.comment=e.comment),v.range=[p.offset,w,e.offset]}else v.range=[p.offset,w,w];return v}e.resolveFlowCollection=d})),
|
|
163
|
+
`+e.comment:v.comment=e.comment),v.range=[p.offset,w,e.offset]}else v.range=[p.offset,w,w];return v}e.resolveFlowCollection=d})),lx=I((e=>{var t=$(),n=gb(),r=kb(),i=jb(),a=ax(),o=ox(),s=cx();function c(e,t,n,r,i,c){let l=n.type===`block-map`?a.resolveBlockMap(e,t,n,r,c):n.type===`block-seq`?o.resolveBlockSeq(e,t,n,r,c):s.resolveFlowCollection(e,t,n,r,c),u=l.constructor;return i===`!`||i===u.tagName?(l.tag=u.tagName,l):(i&&(l.tag=i),l)}function l(e,a,o,s,l){let u=s.tag,d=u?a.directives.tagName(u.source,e=>l(u,`TAG_RESOLVE_FAILED`,e)):null;if(o.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=s,n=e&&u?e.offset>u.offset?e:u:e??u;n&&(!t||t.offset<n.offset)&&l(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let f=o.type===`block-map`?`map`:o.type===`block-seq`?`seq`:o.start.source===`{`?`map`:`seq`;if(!u||!d||d===`!`||d===r.YAMLMap.tagName&&f===`map`||d===i.YAMLSeq.tagName&&f===`seq`)return c(e,a,o,l,d);let p=a.schema.tags.find(e=>e.tag===d&&e.collection===f);if(!p){let t=a.schema.knownTags[d];if(t?.collection===f)a.schema.tags.push(Object.assign({},t,{default:!1})),p=t;else return t?l(u,`BAD_COLLECTION_TYPE`,`${t.tag} used for ${f} collection, but expects ${t.collection??`scalar`}`,!0):l(u,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${d}`,!0),c(e,a,o,l,d)}let m=c(e,a,o,l,d,p),h=p.resolve?.(m,e=>l(u,`TAG_RESOLVE_FAILED`,e),a.options)??m,g=t.isNode(h)?h:new n.Scalar(h);return g.range=m.range,g.tag=d,p?.format&&(g.format=p.format),g}e.composeCollection=l})),ux=I((e=>{var t=gb();function n(e,n,a){let o=n.offset,s=r(n,e.options.strict,a);if(!s)return{value:``,type:null,comment:``,range:[o,o,o]};let c=s.mode===`>`?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,l=n.source?i(n.source):[],u=l.length;for(let e=l.length-1;e>=0;--e){let t=l[e][1];if(t===``||t===`\r`)u=e;else break}if(u===0){let e=s.chomp===`+`&&l.length>0?`
|
|
154
164
|
`.repeat(Math.max(1,l.length-1)):``,t=o+s.length;return n.source&&(t+=n.source.length),{value:e,type:c,comment:s.comment,range:[o,t,t]}}let d=n.indent+s.indent,f=n.offset+s.length,p=0;for(let t=0;t<u;++t){let[n,r]=l[t];if(r===``||r===`\r`)s.indent===0&&n.length>d&&(d=n.length);else{n.length<d&&a(f+n.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),s.indent===0&&(d=n.length),p=t,d===0&&!e.atRoot&&a(f,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}f+=n.length+r.length+1}for(let e=l.length-1;e>=u;--e)l[e][0].length>d&&(u=e+1);let m=``,h=``,g=!1;for(let e=0;e<p;++e)m+=l[e][0].slice(d)+`
|
|
155
165
|
`;for(let e=p;e<u;++e){let[n,r]=l[e];f+=n.length+r.length+1;let i=r[r.length-1]===`\r`;if(i&&(r=r.slice(0,-1)),r&&n.length<d){let e=`Block scalar lines must not be less indented than their ${s.indent?`explicit indentation indicator`:`first line`}`;a(f-r.length-(i?2:1),`BAD_INDENT`,e),n=``}c===t.Scalar.BLOCK_LITERAL?(m+=h+n.slice(d)+r,h=`
|
|
156
166
|
`):n.length>d||r[0]===` `?(h===` `?h=`
|
|
@@ -165,7 +175,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
165
175
|
`+l[e][0].slice(d);m[m.length-1]!==`
|
|
166
176
|
`&&(m+=`
|
|
167
177
|
`);break;default:m+=`
|
|
168
|
-
`}let _=o+s.length+n.source.length;return{value:m,type:c,comment:s.comment,range:[o,_,_]}}function r({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function i(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=n})),
|
|
178
|
+
`}let _=o+s.length+n.source.length;return{value:m,type:c,comment:s.comment,range:[o,_,_]}}function r({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function i(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}e.resolveBlockScalar=n})),dx=I((e=>{var t=gb(),n=sx();function r(e,r,o){let{offset:c,type:l,source:u,end:d}=e,f,p,m=(e,t,n)=>o(c+e,t,n);switch(l){case`scalar`:f=t.Scalar.PLAIN,p=i(u,m);break;case`single-quoted-scalar`:f=t.Scalar.QUOTE_SINGLE,p=a(u,m);break;case`double-quoted-scalar`:f=t.Scalar.QUOTE_DOUBLE,p=s(u,m);break;default:return o(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${l}`),{value:``,type:null,comment:``,range:[c,c+u.length,c+u.length]}}let h=c+u.length,g=n.resolveEnd(d,h,r,o);return{value:p,type:f,comment:g.comment,range:[c,h,g.offset]}}function i(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),o(e)}function a(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),o(e.slice(1,-1)).replace(/''/g,`'`)}function o(e){let t,n;try{t=RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
169
179
|
`,`sy`),n=RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
170
180
|
`,`sy`)}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],a=` `,o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)r[1]===``?a===`
|
|
171
181
|
`?i+=a:a=`
|
|
@@ -180,10 +190,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
180
190
|
`);)r===`
|
|
181
191
|
`&&(n+=`
|
|
182
192
|
`),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var l={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
|
|
183
|
-
`,r:`\r`,t:` `,v:`\v`,N:`
`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function u(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}e.resolveFlowScalar=r})),
|
|
193
|
+
`,r:`\r`,t:` `,v:`\v`,N:`
`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function u(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}e.resolveFlowScalar=r})),fx=I((e=>{var t=$(),n=gb(),r=ux(),i=dx();function a(e,a,c,l){let{value:u,type:d,comment:f,range:p}=a.type===`block-scalar`?r.resolveBlockScalar(e,a,l):i.resolveFlowScalar(a,e.options.strict,l),m=c?e.directives.tagName(c.source,e=>l(c,`TAG_RESOLVE_FAILED`,e)):null,h;h=e.options.stringKeys&&e.atKey?e.schema[t.SCALAR]:m?o(e.schema,u,m,c,l):a.type===`scalar`?s(e,u,a,l):e.schema[t.SCALAR];let g;try{let r=h.resolve(u,e=>l(c??a,`TAG_RESOLVE_FAILED`,e),e.options);g=t.isScalar(r)?r:new n.Scalar(r)}catch(e){let t=e instanceof Error?e.message:String(e);l(c??a,`TAG_RESOLVE_FAILED`,t),g=new n.Scalar(u)}return g.range=p,g.source=u,d&&(g.type=d),m&&(g.tag=m),h.format&&(g.format=h.format),f&&(g.comment=f),g}function o(e,n,r,i,a){if(r===`!`)return e[t.SCALAR];let o=[];for(let t of e.tags)if(!t.collection&&t.tag===r){if(t.default&&t.test)o.push(t);else return t}for(let e of o)if(e.test?.test(n))return e;let s=e.knownTags[r];return s&&!s.collection?(e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(a(i,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${r}`,r!==`tag:yaml.org,2002:str`),e[t.SCALAR])}function s({atKey:e,directives:n,schema:r},i,a,o){let s=r.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(i))||r[t.SCALAR];if(r.compat){let e=r.compat.find(e=>e.default&&e.test?.test(i))??r[t.SCALAR];s.tag!==e.tag&&o(a,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${n.tagString(s.tag)} or ${n.tagString(e.tag)}`,!0)}return s}e.composeScalar=a})),px=I((e=>{function t(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}e.emptyScalarPosition=t})),mx=I((e=>{var t=hb(),n=$(),r=lx(),i=fx(),a=sx(),o=px(),s={composeNode:c,composeEmptyNode:l};function c(e,t,a,o){let c=e.atKey,{spaceBefore:d,comment:f,anchor:p,tag:m}=a,h,g=!0;switch(t.type){case`alias`:h=u(e,t,o),(p||m)&&o(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:h=i.composeScalar(e,t,m,o),p&&(h.anchor=p.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{h=r.composeCollection(s,e,t,a,o),p&&(h.anchor=p.source.substring(1))}catch(e){o(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:o(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),g=!1}return h??=l(e,t.offset,void 0,null,a,o),p&&h.anchor===``&&o(p,`BAD_ALIAS`,`Anchor cannot be an empty string`),c&&e.options.stringKeys&&(!n.isScalar(h)||typeof h.value!=`string`||h.tag&&h.tag!==`tag:yaml.org,2002:str`)&&o(m??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),d&&(h.spaceBefore=!0),f&&(t.type===`scalar`&&t.source===``?h.comment=f:h.commentBefore=f),e.options.keepSourceTokens&&g&&(h.srcToken=t),h}function l(e,t,n,r,{spaceBefore:a,comment:s,anchor:c,tag:l,end:u},d){let f={type:`scalar`,offset:o.emptyScalarPosition(t,n,r),indent:-1,source:``},p=i.composeScalar(e,f,l,d);return c&&(p.anchor=c.source.substring(1),p.anchor===``&&d(c,`BAD_ALIAS`,`Anchor cannot be an empty string`)),a&&(p.spaceBefore=!0),s&&(p.comment=s,p.range[2]=u),p}function u({options:e},{offset:n,source:r,end:i},o){let s=new t.Alias(r.substring(1));s.source===``&&o(n,`BAD_ALIAS`,`Alias cannot be an empty string`),s.source.endsWith(`:`)&&o(n+r.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let c=n+r.length,l=a.resolveEnd(i,c,e.strict,o);return s.range=[n,c,l.offset],l.comment&&(s.comment=l.comment),s}e.composeEmptyNode=l,e.composeNode=c})),hx=I((e=>{var t=$b(),n=mx(),r=sx(),i=tx();function a(e,a,{offset:o,start:s,value:c,end:l},u){let d=Object.assign({_directives:a},e),f=new t.Document(void 0,d),p={atKey:!1,atRoot:!0,directives:f.directives,options:f.options,schema:f.schema},m=i.resolveProps(s,{indicator:`doc-start`,next:c??l?.[0],offset:o,onError:u,parentIndent:0,startOnNewline:!0});m.found&&(f.directives.docStart=!0,c&&(c.type===`block-map`||c.type===`block-seq`)&&!m.hasNewline&&u(m.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),f.contents=c?n.composeNode(p,c,m,u):n.composeEmptyNode(p,m.end,s,null,m,u);let h=f.contents.range[2],g=r.resolveEnd(l,h,!1,u);return g.comment&&(f.comment=g.comment),f.range=[o,h,g.offset],f}e.composeDoc=a})),gx=I((e=>{var t=Te(`process`),n=ub(),r=$b(),i=ex(),a=$(),o=hx(),s=sx();function c(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function l(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
|
|
184
194
|
|
|
185
195
|
`:`
|
|
186
|
-
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}e.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=c(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=l(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:l(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=c(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}})),
|
|
196
|
+
`)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}e.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=c(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=l(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:l(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=c(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new r.Document(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}})),_x=I((e=>{var t=ux(),n=dx(),r=ex(),i=xb();function a(e,i=!0,a){if(e){let o=(e,t,n)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(a)a(i,t,n);else throw new r.YAMLParseError([i,i+1],t,n)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return n.resolveFlowScalar(e,i,o);case`block-scalar`:return t.resolveBlockScalar({options:{strict:i}},e,o)}}return null}function o(e,t){let{implicitKey:n=!1,indent:r,inFlow:a=!1,offset:o=-1,type:s=`PLAIN`}=t,c=i.stringifyString({type:s,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}}),u=t.end??[{type:`newline`,offset:-1,indent:r,source:`
|
|
187
197
|
`}];switch(c[0]){case`|`:case`>`:{let e=c.indexOf(`
|
|
188
198
|
`),t=c.substring(0,e),n=c.substring(e+1)+`
|
|
189
199
|
`,i=[{type:`block-scalar-header`,offset:o,indent:r,source:t}];return l(i,u)||i.push({type:`newline`,offset:-1,indent:r,source:`
|
|
@@ -191,9 +201,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
191
201
|
`),r=t.substring(0,n),i=t.substring(n+1)+`
|
|
192
202
|
`;if(e.type===`block-scalar`){let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);t.source=r,e.source=i}else{let{offset:t}=e,n=`indent`in e?e.indent:-1,a=[{type:`block-scalar-header`,offset:t,indent:n,source:r}];l(a,`end`in e?e.end:void 0)||a.push({type:`newline`,offset:-1,indent:n,source:`
|
|
193
203
|
`});for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:`block-scalar`,indent:n,props:a,source:i})}}function l(e,t){if(t)for(let n of t)switch(n.type){case`space`:case`comment`:e.push(n);break;case`newline`:return e.push(n),!0}return!1}function u(e,t,n){switch(e.type){case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:e.type=n,e.source=t;break;case`block-scalar`:{let r=e.props.slice(1),i=t.length;e.props[0].type===`block-scalar-header`&&(i-=e.props[0].source.length);for(let e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case`block-map`:case`block-seq`:{let r={type:`newline`,offset:e.offset+t.length,indent:e.indent,source:`
|
|
194
|
-
`};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}e.createScalarToken=o,e.resolveAsScalar=a,e.setScalarValue=s})),
|
|
204
|
+
`};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}e.createScalarToken=o,e.resolveAsScalar=a,e.setScalarValue=s})),vx=I((e=>{var t=e=>`type`in e?n(e):r(e);function n(e){switch(e.type){case`block-scalar`:{let t=``;for(let r of e.props)t+=n(r);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=r(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=r(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=r(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if(`end`in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function r({start:e,key:t,sep:r,value:i}){let a=``;for(let t of e)a+=t.source;if(t&&(a+=n(t)),r)for(let e of r)a+=e.source;return i&&(a+=n(i)),a}e.stringify=t})),yx=I((e=>{var t=Symbol(`break visit`),n=Symbol(`skip children`),r=Symbol(`remove item`);function i(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),a(Object.freeze([]),e,t)}i.BREAK=t,i.SKIP=n,i.REMOVE=r,i.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},i.parentCollection=(e,t)=>{let n=i.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],a=n?.[r];if(a&&`items`in a)return a;throw Error(`Parent collection not found`)};function a(e,n,i){let o=i(n,e);if(typeof o==`symbol`)return o;for(let s of[`key`,`value`]){let c=n[s];if(c&&`items`in c){for(let n=0;n<c.items.length;++n){let o=a(Object.freeze(e.concat([[s,n]])),c.items[n],i);if(typeof o==`number`)n=o-1;else if(o===t)return t;else o===r&&(c.items.splice(n,1),--n)}typeof o==`function`&&s===`key`&&(o=o(n,e))}}return typeof o==`function`?o(n,e):o}e.visit=i})),bx=I((e=>{var t=_x(),n=vx(),r=yx(),i=``,a=``,o=``,s=``,c=e=>!!e&&`items`in e,l=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`);function u(e){switch(e){case i:return`<BOM>`;case a:return`<DOC>`;case o:return`<FLOW_END>`;case s:return`<SCALAR>`;default:return JSON.stringify(e)}}function d(e){switch(e){case i:return`byte-order-mark`;case a:return`doc-mode`;case o:return`flow-error-end`;case s:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
|
|
195
205
|
`:case`\r
|
|
196
|
-
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=i,e.DOCUMENT=a,e.FLOW_END=o,e.SCALAR=s,e.isCollection=c,e.isScalar=l,e.prettyToken=u,e.tokenType=d})),
|
|
206
|
+
`:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=i,e.DOCUMENT=a,e.FLOW_END=o,e.SCALAR=s,e.isCollection=c,e.isScalar=l,e.prettyToken=u,e.tokenType=d})),xx=I((e=>{var t=bx();function n(e){switch(e){case void 0:case` `:case`
|
|
197
207
|
`:case`\r`:case` `:return!0;default:return!1}}var r=new Set(`0123456789ABCDEFabcdef`),i=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),a=new Set(`,[]{}`),o=new Set(` ,[]{}
|
|
198
208
|
\r `),s=e=>!e||o.has(e);e.Lexer=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
|
|
199
209
|
`||t===`\r`&&this.buffer[e+1]===`
|
|
@@ -212,8 +222,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
212
222
|
`,t=this.buffer[i+1]):r=i),t===`#`||e&&a.has(t))break;if(o===`
|
|
213
223
|
`){let e=this.continueScalar(i+1);if(e===-1)break;i=Math.max(i,e-2)}}else{if(e&&a.has(o))break;r=i}return!o&&!this.atEnd?this.setNext(`plain-scalar`):(yield t.SCALAR,yield*this.pushToIndex(r+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(s),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,r=this.charAt(1);if(n(r)||t&&a.has(r)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!n(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(i.has(t))t=this.buffer[++e];else if(t===`%`&&r.has(this.buffer[e+1])&&r.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
214
224
|
`?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
|
|
215
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),
|
|
225
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),Sx=I((e=>{e.LineCounter=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}})),Cx=I((e=>{var t=Te(`process`),n=bx(),r=xx();function i(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function a(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function o(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function s(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function c(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function l(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function u(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!i(t.start,`explicit-key-ind`)&&!i(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,o(t.value)?t.value.end?l(t.value.end,t.sep):t.value.end=t.sep:l(t.start,t.sep),delete t.sep)}e.Parser=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new r.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,t.env.LOG_TOKENS&&console.log(`|`,n.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=n.tokenType(e);if(!r){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(r===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=r,yield*this.step(),r){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&u(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&a(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:a(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=c(s(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
|
|
216
226
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
217
227
|
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){l(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,a=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(a=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(i(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=c(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(i(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(o(t.key)&&!i(t.sep,`newline`)){let e=c(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else a.length>0?t.sep=t.sep.concat(a,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):i(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:a,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!i(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:a});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){l(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||i(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=c(s(t));u(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
|
|
218
228
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
219
|
-
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),GS=L((e=>{var t=LS(),n=bS(),r=xS(),i=Gx(),a=$(),o=US(),s=WS();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),KS=L((e=>{var t=LS(),n=bS(),r=vS(),i=xS(),a=Ix(),o=$(),s=Jx(),c=Lx(),l=Xx(),u=Qx();VS();var d=HS(),f=US(),p=WS(),m=GS(),h=Ax();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))(),qS=`DEEPSEEK_API_KEY`,JS=1,YS=`ezllm`,XS=()=>process.env.DSH_HOME||w(t(),`.dsh`),ZS=()=>w(XS(),`settings.yaml`),QS=()=>w(XS(),`.credentials.yaml`);function $S(e){if(!d(e))return null;let t=p(e,`utf-8`);return t.trim()===``?null:t}function eC(e,t){let n=(0,KS.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function tC(e){return`${e}/v1`}function nC(e){let t=$S(ZS());if(!t)return!1;try{return zb(eC(t,ZS()).toJS()?.[`llm-deepseek`]?.baseURL,tC(e))}catch{return!1}}function rC(e){let t=tC(e.gatewayBase);f(XS(),{recursive:!0});let n=ZS(),r=$S(n),i=eC(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);Lb(n),i.setIn([`llm-deepseek`,`baseURL`],t),aC(n,i);let o=QS(),s=e.masterKey||YS,c=$S(o);if(Lb(o),c===null){let e=eC(``,o);e.set(`version`,JS),e.setIn([`refs`,qS],s),aC(o,e);return}let l=eC(c,o),u=l.toJS();if(!(0,KS.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(u.version!==void 0&&u.version!==JS)throw Error(`${o} 的 version 为 ${String(u.version)},本开关仅支持 version: ${String(JS)}`);if(u.version===void 0){if(!Object.values(u).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(qS,s)}else{if(u.refs!==void 0&&(typeof u.refs!=`object`||u.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,qS],s)}aC(o,l)}function iC(e,t){let n=ZS(),r=QS(),i=!1;if(Rb(n))i=!0;else{let t=$S(n);if(t){let r=eC(t,n);if(zb(r.toJS()?.[`llm-deepseek`]?.baseURL,tC(e))){r.deleteIn([`llm-deepseek`,`baseURL`]);let e=r.toJS()?.[`llm-deepseek`];(!e||typeof e!=`object`||Object.keys(e).length===0)&&r.deleteIn([`llm-deepseek`]),aC(n,r),i=!0}}}if(Rb(r))i=!0;else{let e=$S(r);if(e){let n=eC(e,r),a=n.toJS(),o=e=>e===t||e===YS;a?.version===JS&&o(a?.refs?.[qS])?(n.deleteIn([`refs`,qS]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),aC(r,n),i=!0):a?.version===void 0&&o(a?.[qS])&&(n.deleteIn([qS]),aC(r,n),i=!0)}}return i}function aC(e,t){let n=t.toString(),r=(0,KS.parseDocument)(n);if(r.errors.length>0)throw Error(`编辑后的 ${e} 不是合法 YAML,已保留原文件: ${r.errors[0]?.message??`未知错误`}`);f(C(e),{recursive:!0}),b(e,n,`utf-8`)}function oC(e){try{return JSON.parse(p(e,`utf-8`)).masterKey||``}catch{return``}}function sC(e){let t=new $n;return t.get(`/`,t=>{let n=r_(e);return t.json({ok:!0,claudeCode:Hb(n),codex:wx(),dsh:nC(n),gatewayBase:n})}),t.post(`/claude-code`,async t=>{let n=await Tb(t);if(n instanceof Response)return n;let r=r_(e);if(n){let e=oC(_t());return e?(Ub({gatewayBase:r,token:e}),t.json({ok:!0,claudeCode:!0,file:`~/.claude/settings.json`,note:`已备份原文件为 settings.json.ellm-bak,重启 Claude Code 会话后生效`})):t.json({ok:!1,error:`配置未设置 masterKey,Claude Code 代理无法鉴权。请先在配置文件中设置 masterKey: ${_t()}`},400)}let i=Wb(r);return t.json({ok:!0,claudeCode:!1,changed:i,note:i?`已从备份还原`:`原本未开启,无操作`})}),t.post(`/codex`,async t=>{let n=await Tb(t);if(n instanceof Response)return n;let r=r_(e);if(n){let e=oC(_t()),n=Ox({gatewayBase:r,apiKey:e||void 0});return t.json({ok:!0,codex:!0,file:`~/.codex/config.toml`,note:e?n?`已备份原文件为 config.toml.ellm-bak;已自动写入用户环境变量 ELLM_PROXY_API_KEY(Windows 写注册表 / macOS 写 ~/.zshrc,对之后新开的终端与 Codex 会话生效)`:`已备份原文件为 config.toml.ellm-bak;当前平台不支持自动写入,请手动设置环境变量 ELLM_PROXY_API_KEY=${e}`:`已备份原文件为 config.toml.ellm-bak;请设置环境变量 ELLM_PROXY_API_KEY(网关未配 masterKey 时取值任意)`})}let i=kx();return t.json({ok:!0,codex:!1,changed:i,note:i?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),t.post(`/dsh`,async t=>{let n=await Tb(t);if(n instanceof Response)return n;let r=r_(e),i=oC(_t());if(n)return rC({gatewayBase:r,masterKey:i}),t.json({ok:!0,dsh:!0,file:`~/.dsh/settings.yaml`,note:i?`已写入 settings.yaml(llm-deepseek.baseURL)与 .credentials.yaml(refs.DEEPSEEK_API_KEY),原文件备份为 *.ellm-bak。注意:进程环境里已设 DEEPSEEK_API_KEY 时其优先级更高,需自行改用网关 masterKey;模型请在 dsh 内选择与网关部署名一致的模型`:`已写入 settings.yaml 与 .credentials.yaml(网关未配 masterKey,密钥为占位值即可放行),原文件备份为 *.ellm-bak。模型请在 dsh 内选择与网关部署名一致的模型`});let a=iC(r,i);return t.json({ok:!0,dsh:!1,changed:a,note:a?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),t}var cC=(e,t=lC)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},lC={aac:`audio/aac`,avi:`video/x-msvideo`,avif:`image/avif`,av1:`video/av1`,bin:`application/octet-stream`,bmp:`image/bmp`,css:`text/css; charset=utf-8`,csv:`text/csv; charset=utf-8`,eot:`application/vnd.ms-fontobject`,epub:`application/epub+zip`,gif:`image/gif`,gz:`application/gzip`,htm:`text/html; charset=utf-8`,html:`text/html; charset=utf-8`,ico:`image/x-icon`,ics:`text/calendar; charset=utf-8`,jpeg:`image/jpeg`,jpg:`image/jpeg`,js:`text/javascript; charset=utf-8`,json:`application/json`,jsonld:`application/ld+json`,map:`application/json`,mid:`audio/x-midi`,midi:`audio/x-midi`,mjs:`text/javascript; charset=utf-8`,mp3:`audio/mpeg`,mp4:`video/mp4`,mpeg:`video/mpeg`,oga:`audio/ogg`,ogv:`video/ogg`,ogx:`application/ogg`,opus:`audio/opus`,otf:`font/otf`,pdf:`application/pdf`,png:`image/png`,rtf:`application/rtf`,svg:`image/svg+xml; charset=utf-8`,tif:`image/tiff`,tiff:`image/tiff`,ts:`video/mp2t`,ttf:`font/ttf`,txt:`text/plain; charset=utf-8`,wasm:`application/wasm`,webm:`video/webm`,weba:`audio/webm`,webmanifest:`application/manifest+json`,webp:`image/webp`,woff:`font/woff`,woff2:`font/woff2`,xhtml:`application/xhtml+xml; charset=utf-8`,xml:`application/xml; charset=utf-8`,zip:`application/zip`,"3gp":`video/3gpp`,"3g2":`video/3gpp2`,gltf:`model/gltf+json`,glb:`model/gltf-binary`},uC=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,dC={br:`.br`,zstd:`.zst`,gzip:`.gz`},fC=Object.keys(dC),pC=(()=>{let[e,t]=fe.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),mC=e=>pC?s.toWeb(e):new ReadableStream({start(t){e.on(`data`,e=>{t.enqueue(e)}),e.on(`error`,e=>{t.error(e)}),e.on(`end`,()=>{t.close()})},cancel(){e.destroy()}}),hC=e=>{let t;try{t=oe(e)}catch{}return t},gC=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},_C=e=>gC(e,decodeURI),vC=(e={root:``})=>{let t=e.root||``,n=e.path;return t!==``&&!ae(t)&&console.error(`serveStatic: root path '${t}' is not found, are you sure it's correct?`),async(r,i)=>{if(r.finalized)return i();let a;if(n)a=n;else try{if(a=_C(r.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(a))throw Error()}catch{return await e.onNotFound?.(r.req.path,r),i()}let o=se(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(a,r):a),s=hC(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=se(o,t),s=hC(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=cC(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||uC.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of fC){if(!e.has(t))continue;let n=hC(o+dC[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=dC[t];break}}}let l,u=s.size,d=r.req.header(`range`)||``;if(r.req.method==`HEAD`||r.req.method==`OPTIONS`)r.header(`Content-Length`,u.toString()),r.status(200),l=r.body(null);else if(!d)r.header(`Content-Length`,u.toString()),l=r.body(mC(ie(o)),200);else{r.header(`Accept-Ranges`,`bytes`),r.header(`Date`,s.birthtime.toUTCString());let e=d.replace(/bytes=/,``).split(`-`,2),t=parseInt(e[0],10)||0,n=parseInt(e[1],10)||u-1;u<n-t+1&&(n=u-1);let i=n-t+1,a=ie(o,{start:t,end:n});r.header(`Content-Length`,i.toString()),r.header(`Content-Range`,`bytes ${t}-${n}/${s.size}`),l=r.body(mC(a),206)}return await e.onFound?.(o,r),l}},yC=C(D(import.meta.url));function bC(){return[w(yC,`web-ui`),T(yC,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),T(yC,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>d(w(e,`index.html`)))??w(yC,`web-ui`)}function xC(e,t){let n=t??bC();d(w(n,`index.html`))&&(e.get(`/`,async e=>{try{let t=await P(w(n,`index.html`));return e.body(new Uint8Array(t),200,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-cache`})}catch{return e.text(`Not Found`,404)}}),e.use(`/*`,async(e,t)=>{if(e.req.path===`/`)return t();let r=await vC({root:n})(e,t);return r instanceof Response&&r.status===200&&e.req.path.startsWith(`/assets/`)&&r.headers.set(`Cache-Control`,`public, max-age=31536000, immutable`),r}))}function SC(e,t,n){let r=new $n;return r.use(`/v1/*`,em()),r.route(`/api/auth`,rm),r.route(`/api/setup`,fm()),r.use(`/api/*`,am),r.route(`/api/config`,pm({runtime:e})),r.route(`/api/test`,_m(e)),r.route(`/api/latency`,zm(e)),r.route(`/api/usage`,Hm()),r.route(`/api/quota`,Fg()),r.route(`/api/logs`,Gg()),r.route(`/api/status`,Ig(e,n)),t&&(r.route(`/api/service`,o_(t)),r.route(`/api/service`,Mb(t)),r.route(`/api/service/managed`,Ib(t)),r.route(`/api/harness`,sC(t))),r.route(`/`,e.proxy),xC(r),r.notFound(e=>e.json({ok:!1,error:`未知接口: ${e.req.method} ${e.req.path}(可用: GET /(管理界面), /v1/*(网关), /api/*(管理台与全部接口), GET /api/service/status|processes, GET|POST /api/service/autostart, GET /api/service/update, POST /api/service/update/enabled|check|apply, GET|POST /api/service/managed, PUT|DELETE /api/service/managed/:name, POST /api/service/managed/:name/start|stop|restart, GET /api/harness, POST /api/harness/claude-code|codex|dsh, GET /api/latency/history, POST /api/latency/run)`},404)),r.onError(sm),r}var CC=6e4;function wC(){let e=hu()?.latencyTest;return typeof e==`object`&&e?e:{}}function TC(e,t,n){if(e.enabled!==!0)return!1;let r=(e.intervalMinutes??60)*60*1e3;return t===void 0||n-t>=r}function EC(e){return{name:`latencyAutoTest`,everyMs:CC,run:async()=>{try{if(Im(e)===0||!TC(wC(),Em()??void 0,Date.now()))return;z(`[latency] 自动测试触发`),await Fm(e)}catch(e){B(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var DC=6e5,OC=3e4;function kC(){return{name:`quotaRefresh`,everyMs:DC,firstDelayMs:OC,run:async()=>{try{await Mg()}catch(e){B(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var AC=gu();AC===null&&(B(`[ezllm] 缺少配置文件 ${_t()}(参考 ezllm.config.example.json)`),process.exit(1));var jC=AC;pf(),Sm();var MC=new td({maxBytes:Lu().maxBytes}),NC=Tp({spool:MC,getConfig:()=>Lu()}),PC=ed();PC>0&&z(`[ezllm] spool 启动清理:回收中断残留 ${String(PC)} 个中转文件`),await Dp();var FC=new Wp({spool:MC}),IC=()=>jC.providers.flatMap(e=>e.models.map(e=>e.modelName)),LC=await Xp(jC,{authorize(e){let t=wu();return t===``||e===`Bearer ${t}`},register(e){e.addHook(`onAuthorize`,e=>{let t=wu();t!==``&&(e.headers.authorization??``)!==`Bearer ${t}`&&e.reject(`invalid api key`)}),$p(e,{knownModelNames:IC})}},{traceSink:FC}),RC={port:0,startedAt:Date.now(),appDir:ht()},zC=Mu(),BC=SC(LC,RC,zC),VC=Vt({jobs:[NC,jp({getRetention:()=>Iu()}),EC(LC),kC()]}),HC=await GC(BC,Yp(LC),zC.hostname);RC.port=HC;var UC=!1;function WC(e,t=0){UC||(UC=!0,VC.stop(),z(`[ezllm] ${e},服务退出`),Promise.race([FC.flush(),new Promise(e=>setTimeout(e,5e3))]).then(()=>process.exit(t)))}wb(()=>WC(`与主进程的 IPC 连接已断开`));for(let e of[`SIGINT`,`SIGTERM`])process.on(e,()=>WC(`收到 ${e}`));qC(HC,zC);async function GC(e,t,n){let r=Date.now()+1e4;for(;;)try{return await new Promise((r,i)=>{let a=ot({fetch:e.fetch,port:t,hostname:n,overrideGlobalObjects:!1});a.once(`error`,e=>i(e)),a.once(`listening`,()=>r(a.address()?.port??t))})}catch(e){let n=e.code??String(e);if(n===`EADDRINUSE`&&Date.now()<r){await new Promise(e=>setTimeout(e,300));continue}B(`错误:服务监听 ${String(t)} 失败(${n})${n===`EADDRINUSE`?`,端口被占用(可在配置文件修改 port)`:``}`),process.exit(1)}}function KC(e){return e===`0.0.0.0`||e===`::`}function qC(e,t){let n=KC(t.hostname)?`localhost`:t.hostname,r=KC(t.hostname)?`全部网卡`:t.hostname,i=t.source===`credentials`?`未设置任何凭据(主密钥与登录账号皆无),强制仅本机(设置页开关已忽略)`:t.hostname===`127.0.0.1`?`设置页「允许局域网访问」已关闭`:`设置页「允许局域网访问」开启(缺省)`;if(z(`========================================`),z(` EZLLM 服务(网关 + 管理台,单进程)`),z(` 网关端点: http://${n}:${String(e)}/v1/*`),z(` 管理台: http://${n}:${String(e)}/(管理 API 与界面同端口,登录后使用)`),z(` 监听地址: ${r}:${String(e)}(${i})`),KC(t.hostname))for(let t of JC())z(` 局域网访问: http://${t}:${String(e)}`);z(` 模型数量: ${String(LC.current.expanded.deployments.names.length)}`),Ou().completed||z(` ⚠ 首次启动:请打开 http://${n}:${String(e)}/ 完成初始化向导(设置主密钥与登录账号)`),z(`========================================`)}function JC(){let e=[];for(let t of Object.values(n()))for(let n of t??[])!n.internal&&n.family===`IPv4`&&e.push(n.address);return e}export{};
|
|
229
|
+
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),wx=I((e=>{var t=gx(),n=$b(),r=ex(),i=wb(),a=$(),o=Sx(),s=Cx();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),Tx=I((e=>{var t=gx(),n=$b(),r=Zb(),i=ex(),a=hb(),o=$(),s=Db(),c=gb(),l=kb(),u=jb();bx();var d=xx(),f=Sx(),p=Cx(),m=wx(),h=lb();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))(),Ex=`DEEPSEEK_API_KEY`,Dx=1,Ox=`ezllm`,kx=()=>process.env.DSH_HOME||E(t(),`.dsh`),Ax=()=>E(kx(),`settings.yaml`),jx=()=>E(kx(),`.credentials.yaml`);function Mx(e){if(!f(e))return null;let t=h(e,`utf-8`);return t.trim()===``?null:t}function Nx(e,t){let n=(0,Tx.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function Px(e){return`${e}/v1`}function Fx(e){let t=Mx(Ax());if(!t)return!1;try{return Sy(Nx(t,Ax()).toJS()?.[`llm-deepseek`]?.baseURL,Px(e))}catch{return!1}}function Ix(e){let t=Px(e.gatewayBase);p(kx(),{recursive:!0});let n=Ax(),r=Mx(n),i=Nx(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);by(n),i.setIn([`llm-deepseek`,`baseURL`],t),Rx(n,i);let o=jx(),s=e.masterKey||Ox,c=Mx(o);if(by(o),c===null){let e=Nx(``,o);e.set(`version`,Dx),e.setIn([`refs`,Ex],s),Rx(o,e);return}let l=Nx(c,o),u=l.toJS();if(!(0,Tx.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(u.version!==void 0&&u.version!==Dx)throw Error(`${o} 的 version 为 ${String(u.version)},本开关仅支持 version: ${String(Dx)}`);if(u.version===void 0){if(!Object.values(u).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(Ex,s)}else{if(u.refs!==void 0&&(typeof u.refs!=`object`||u.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,Ex],s)}Rx(o,l)}function Lx(e,t){let n=Ax(),r=jx(),i=!1;if(xy(n))i=!0;else{let t=Mx(n);if(t){let r=Nx(t,n);if(Sy(r.toJS()?.[`llm-deepseek`]?.baseURL,Px(e))){r.deleteIn([`llm-deepseek`,`baseURL`]);let e=r.toJS()?.[`llm-deepseek`];(!e||typeof e!=`object`||Object.keys(e).length===0)&&r.deleteIn([`llm-deepseek`]),Rx(n,r),i=!0}}}if(xy(r))i=!0;else{let e=Mx(r);if(e){let n=Nx(e,r),a=n.toJS(),o=e=>e===t||e===Ox;a?.version===Dx&&o(a?.refs?.[Ex])?(n.deleteIn([`refs`,Ex]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),Rx(r,n),i=!0):a?.version===void 0&&o(a?.[Ex])&&(n.deleteIn([Ex]),Rx(r,n),i=!0)}}return i}function Rx(e,t){let n=t.toString(),r=(0,Tx.parseDocument)(n);if(r.errors.length>0)throw Error(`编辑后的 ${e} 不是合法 YAML,已保留原文件: ${r.errors[0]?.message??`未知错误`}`);p(T(e),{recursive:!0}),S(e,n,`utf-8`)}function zx(e){let t=e=>{try{return JSON.parse(h(e,`utf-8`)).masterKey||``}catch{return``}},n=new er;return n.get(`/`,t=>{let n=Wh(e);return t.json({ok:!0,claudeCode:Ty(n),codex:ab(),dsh:Fx(n),gatewayBase:n})}),n.post(`/claude-code`,async n=>{let r=await py(n);if(r instanceof Response)return r;let i=Wh(e);if(r){let e=t(xt());return e?(Ey({gatewayBase:i,token:e}),n.json({ok:!0,claudeCode:!0,file:`~/.claude/settings.json`,note:`已备份原文件为 settings.json.ellm-bak,重启 Claude Code 会话后生效`})):n.json({ok:!1,error:`配置未设置 masterKey,Claude Code 代理无法鉴权。请先在配置文件中设置 masterKey: ${xt()}`},400)}let a=Dy(i);return n.json({ok:!0,claudeCode:!1,changed:a,note:a?`已从备份还原`:`原本未开启,无操作`})}),n.post(`/codex`,async n=>{let r=await py(n);if(r instanceof Response)return r;let i=Wh(e);if(r){let e=t(xt()),r=sb({gatewayBase:i,apiKey:e||void 0});return n.json({ok:!0,codex:!0,file:`~/.codex/config.toml`,note:e?r?`已备份原文件为 config.toml.ellm-bak;已自动写入用户环境变量 ELLM_PROXY_API_KEY(Windows 写注册表 / macOS 写 ~/.zshrc,对之后新开的终端与 Codex 会话生效)`:`已备份原文件为 config.toml.ellm-bak;当前平台不支持自动写入,请手动设置环境变量 ELLM_PROXY_API_KEY=${e}`:`已备份原文件为 config.toml.ellm-bak;请设置环境变量 ELLM_PROXY_API_KEY(网关未配 masterKey 时取值任意)`})}let a=cb();return n.json({ok:!0,codex:!1,changed:a,note:a?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),n.post(`/dsh`,async n=>{let r=await py(n);if(r instanceof Response)return r;let i=Wh(e),a=t(xt());if(r)return Ix({gatewayBase:i,masterKey:a}),n.json({ok:!0,dsh:!0,file:`~/.dsh/settings.yaml`,note:a?`已写入 settings.yaml(llm-deepseek.baseURL)与 .credentials.yaml(refs.DEEPSEEK_API_KEY),原文件备份为 *.ellm-bak。注意:进程环境里已设 DEEPSEEK_API_KEY 时其优先级更高,需自行改用网关 masterKey;模型请在 dsh 内选择与网关部署名一致的模型`:`已写入 settings.yaml 与 .credentials.yaml(网关未配 masterKey,密钥为占位值即可放行),原文件备份为 *.ellm-bak。模型请在 dsh 内选择与网关部署名一致的模型`});let o=Lx(i,a);return n.json({ok:!0,dsh:!1,changed:o,note:o?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),n}var Bx=(e,t=Vx)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},Vx={aac:`audio/aac`,avi:`video/x-msvideo`,avif:`image/avif`,av1:`video/av1`,bin:`application/octet-stream`,bmp:`image/bmp`,css:`text/css; charset=utf-8`,csv:`text/csv; charset=utf-8`,eot:`application/vnd.ms-fontobject`,epub:`application/epub+zip`,gif:`image/gif`,gz:`application/gzip`,htm:`text/html; charset=utf-8`,html:`text/html; charset=utf-8`,ico:`image/x-icon`,ics:`text/calendar; charset=utf-8`,jpeg:`image/jpeg`,jpg:`image/jpeg`,js:`text/javascript; charset=utf-8`,json:`application/json`,jsonld:`application/ld+json`,map:`application/json`,mid:`audio/x-midi`,midi:`audio/x-midi`,mjs:`text/javascript; charset=utf-8`,mp3:`audio/mpeg`,mp4:`video/mp4`,mpeg:`video/mpeg`,oga:`audio/ogg`,ogv:`video/ogg`,ogx:`application/ogg`,opus:`audio/opus`,otf:`font/otf`,pdf:`application/pdf`,png:`image/png`,rtf:`application/rtf`,svg:`image/svg+xml; charset=utf-8`,tif:`image/tiff`,tiff:`image/tiff`,ts:`video/mp2t`,ttf:`font/ttf`,txt:`text/plain; charset=utf-8`,wasm:`application/wasm`,webm:`video/webm`,weba:`audio/webm`,webmanifest:`application/manifest+json`,webp:`image/webp`,woff:`font/woff`,woff2:`font/woff2`,xhtml:`application/xhtml+xml; charset=utf-8`,xml:`application/xml; charset=utf-8`,zip:`application/zip`,"3gp":`video/3gpp`,"3g2":`video/3gpp2`,gltf:`model/gltf+json`,glb:`model/gltf-binary`},Hx=/^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i,Ux={br:`.br`,zstd:`.zst`,gzip:`.gz`},Wx=Object.keys(Ux),Gx=(()=>{let[e,t]=ge.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),Kx=e=>Gx?s.toWeb(e):new ReadableStream({start(t){e.on(`data`,e=>{t.enqueue(e)}),e.on(`error`,e=>{t.error(e)}),e.on(`end`,()=>{t.close()})},cancel(){e.destroy()}}),qx=e=>{let t;try{t=ue(e)}catch{}return t},Jx=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},Yx=e=>Jx(e,decodeURI),Xx=(e={root:``})=>{let t=e.root||``,n=e.path;return t!==``&&!le(t)&&console.error(`serveStatic: root path '${t}' is not found, are you sure it's correct?`),async(r,i)=>{if(r.finalized)return i();let a;if(n)a=n;else try{if(a=Yx(r.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(a))throw Error()}catch{return await e.onNotFound?.(r.req.path,r),i()}let o=de(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(a,r):a),s=qx(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=de(o,t),s=qx(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=Bx(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||Hx.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of Wx){if(!e.has(t))continue;let n=qx(o+Ux[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=Ux[t];break}}}let l,u=s.size,d=r.req.header(`range`)||``;if(r.req.method==`HEAD`||r.req.method==`OPTIONS`)r.header(`Content-Length`,u.toString()),r.status(200),l=r.body(null);else if(!d)r.header(`Content-Length`,u.toString()),l=r.body(Kx(ce(o)),200);else{r.header(`Accept-Ranges`,`bytes`),r.header(`Date`,s.birthtime.toUTCString());let e=d.replace(/bytes=/,``).split(`-`,2),t=parseInt(e[0],10)||0,n=parseInt(e[1],10)||u-1;u<n-t+1&&(n=u-1);let i=n-t+1,a=ce(o,{start:t,end:n});r.header(`Content-Length`,i.toString()),r.header(`Content-Range`,`bytes ${t}-${n}/${s.size}`),l=r.body(Kx(a),206)}return await e.onFound?.(o,r),l}},Zx=T(A(import.meta.url));function Qx(e,t){let n=t??[E(Zx,`web-ui`),D(Zx,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),D(Zx,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>f(E(e,`index.html`)))??E(Zx,`web-ui`);f(E(n,`index.html`))&&(e.get(`/`,async e=>{try{let t=await te(E(n,`index.html`));return e.body(new Uint8Array(t),200,{"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-cache`})}catch{return e.text(`Not Found`,404)}}),e.use(`/*`,async(e,t)=>{if(e.req.path===`/`)return t();let r=await Xx({root:n})(e,t);return r instanceof Response&&r.status===200&&e.req.path.startsWith(`/assets/`)&&r.headers.set(`Cache-Control`,`public, max-age=31536000, immutable`),r}))}function $x(e,t,n){let r=new er;return r.use(`/v1/*`,_p()),r.route(`/api/auth`,bp),r.route(`/api/setup`,Op()),r.use(`/api/*`,Sp),r.route(`/api/config`,kp({runtime:e})),r.route(`/api/test`,Np(e)),r.route(`/api/latency`,$p(e)),r.route(`/api/usage`,em()),r.route(`/api/quota`,Eh()),r.route(`/api/logs`,Mh()),r.route(`/api/status`,Dh(e,n)),t&&(r.route(`/api/service`,Gh(t)),r.route(`/api/service`,_y(t)),r.route(`/api/service/managed`,yy(t)),r.route(`/api/harness`,zx(t))),r.route(`/`,e.proxy),Qx(r),r.notFound(e=>e.json({ok:!1,error:`未知接口: ${e.req.method} ${e.req.path}(可用: GET /(管理界面), /v1/*(网关), /api/*(管理台与全部接口), GET /api/service/status|processes, GET|POST /api/service/autostart, GET /api/service/update, POST /api/service/update/enabled|check|apply, GET|POST /api/service/managed, PUT|DELETE /api/service/managed/:name, POST /api/service/managed/:name/start|stop|restart, GET /api/harness, POST /api/harness/claude-code|codex|dsh, GET /api/latency/history, POST /api/latency/run)`},404)),r.onError(wp),r}var eS=6e4;function tS(e){let t=()=>{let e=Dl()?.latencyTest;return typeof e==`object`&&e?e:{}},n=(e,t,n)=>{if(e.enabled!==!0)return!1;let r=(e.intervalMinutes??60)*60*1e3;return t===void 0||n-t>=r};return{name:`latencyAutoTest`,everyMs:eS,run:async()=>{try{if(Xp(e)===0)return;let r=t();if(!n(r,Hp()??void 0,Date.now()))return;L(`[latency] 自动测试触发`),await Yp(e)}catch(e){R(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var nS=6e5,rS=3e4;function iS(){return{name:`quotaRefresh`,everyMs:nS,firstDelayMs:rS,run:async()=>{try{await Th()}catch(e){R(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var aS=6e4,oS=3e4,sS=20,cS=3e4,lS=1024,uS=/^[^\u0000-\u001f\u007f]{1,24}$/u,dS=new Set([`unknown`,`n/a`,`na`,`-`,`未知`,`无法判断`]),fS=[`你是日志归类助手:给定若干 HTTP User-Agent 字符串,判断每个 UA 属于哪个客户端产品。`,`只输出一个 JSON 数组,元素形如 {"i":<序号>,"name":"<客户端短名>"},不要解释、不要代码块、不要多余文字。`,`name 用该客户端常见的写法(如 CodeBuddy、Claude Code、ZCode、curl),限 1~24 个字符、不含换行;无法判断时 name 用 unknown。`].join(`
|
|
230
|
+
`);async function pS(e){let t=async(e,t)=>{let n=(e,t)=>{let n=jp((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0);return e.provider===`anthropic`?{url:`${n}/messages`,payload:{model:e.modelName,system:fS,messages:[{role:`user`,content:t}],max_tokens:lS}}:e.provider===`openai-responses`?{url:`${n}/responses`,payload:{model:e.modelName,instructions:fS,input:t,max_output_tokens:lS}}:{url:`${n}/chat/completions`,payload:{model:e.modelName,messages:[{role:`system`,content:fS},{role:`user`,content:t}],max_tokens:lS}}},r=(e,t)=>{if(typeof t!=`object`||!t)return``;let n=t;if(e===`anthropic`){let e=n.content;return typeof e==`string`?e:Array.isArray(e)?e.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(``):``}if(e===`openai-responses`){if(typeof n.output_text==`string`)return n.output_text;let e=n.output;return Array.isArray(e)?e.map(e=>{if(typeof e!=`object`||!e)return``;let t=e.content;return Array.isArray(t)?t.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(``):``}).join(``):``}let r=n.choices;if(!Array.isArray(r)||r.length===0)return``;let i=r[0].message;if(typeof i!=`object`||!i)return``;let a=i.content;return typeof a==`string`?a:Array.isArray(a)?a.map(e=>typeof e==`object`&&e&&typeof e.text==`string`?e.text:``).join(``):``},{url:i,payload:a}=n(e,t),o={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?Mp(e.apiKey,e.provider):{}},s=await fetch(i,{method:`POST`,headers:o,body:JSON.stringify(a),signal:AbortSignal.timeout(cS)});if(!s.ok){let e=await s.text().then(e=>e.replace(/\s+/g,` `).trim().slice(0,160)).catch(()=>``);throw Error(`HTTP ${String(s.status)}${e?`: ${e}`:``}`)}let c=await s.json().catch(()=>null);return r(e.provider,c)},n=e=>{let t=e.current.expanded.deployments,n=t.names;if(n.length===0)return null;let r=lf({status:`2xx`,pageSize:30}).items;for(let e of r){let n=typeof e.model==`string`?e.model:``;if(n===``)continue;let r=t.byName.get(n);if(r!==void 0)return{provider:r.provider,modelName:r.modelName,apiKey:r.apiKey,apiBase:r.apiBase,autoV1:r.autoV1,headers:r.headers}}let i=t.byName.get(n[0]);return i===void 0?null:{provider:i.provider,modelName:i.modelName,apiKey:i.apiKey,apiBase:i.apiBase,autoV1:i.autoV1,headers:i.headers}},r=(e,t)=>{let n=new Map,r=e.replace(/```[a-zA-Z]*/g,``).trim(),i=r.indexOf(`[`),a=r.lastIndexOf(`]`);if(i===-1||a<=i)return n;let o;try{o=JSON.parse(r.slice(i,a+1))}catch{return n}if(!Array.isArray(o))return n;for(let e of o){if(typeof e!=`object`||!e)continue;let r=e,i=Number(r.i),a=r.name;if(!Number.isInteger(i)||i<1||i>t||typeof a!=`string`)continue;let o=a.trim();uS.test(o)&&(dS.has(o.toLowerCase())||n.set(i,o))}return n},i=Jf(sS);if(i.length===0)return{resolved:0,fallback:0,failed:0};let a=n(e);if(a===null)return gt(`[client-name] 无可用部署,${String(i.length)} 个待识别 UA 顺延到下一轮`),{resolved:0,fallback:0,failed:i.length};let o=i.map((e,t)=>`${String(t+1)}) ${e}`).join(`
|
|
231
|
+
`),s=``,c=null;try{s=await t(a,o)}catch(e){c=e instanceof Error?e.message:String(e)}let l=new Map;if(c===null)for(let[e,t]of r(s,i.length)){let n=i[e-1];n!==void 0&&l.set(n,t)}let u=Yf(l,`llm`),d=i.filter(e=>!l.has(e)),f=Xf(d),p=new Map;for(let e of f){let t=op(e);t!==``&&p.set(e,t)}let m=Yf(p,If);return c!==null&>(`[client-name] 识别请求失败(${String(d.length)} 个 UA 顺延重试): ${c}`),(u>0||m>0)&&L(`[client-name] 客户端短名: 模型定名 ${String(u)} 个 / 回落 ${String(m)} 个(模型 ${a.modelName})`),{resolved:u,fallback:m,failed:d.length-m}}function mS(e){return{name:`clientNameResolve`,everyMs:aS,firstDelayMs:oS,run:async()=>{try{await pS(e)}catch(e){R(`[client-name] 识别作业异常:`,e instanceof Error?e.message:String(e))}}}}var hS=`--log-backfill`;function gS(e=process.argv){return e.includes(hS)}async function _S(){L(`[log-backfill] 开始存量补齐(入站头 → 会话标识;客户端短名随后由服务内作业定名)`),wd();let e=cp({onProgress:e=>L(`[log-backfill] ${e}`)});L(`[log-backfill] 入站头:${String(e.days)} 天 / 扫描 ${String(e.scanned)} 行,回填 ${String(e.filled)} 行,跳过(详情无入站头)${String(e.skipped)} 行,登记 UA ${String(e.uas)} 个,补写 client ${String(e.clientsAssigned)} 行`);let t=dp({onProgress:e=>L(`[log-backfill] ${e}`)});L(`[log-backfill] 会话标识:扫描 ${String(t.scanned)} 行,补 session_id ${String(t.filled)} 行`),L(`[log-backfill] 完成`)}function vS(e={}){let t=e.entry??process.argv[1];if(t===void 0||t===``)return{started:!1,reason:`拿不到本进程入口(process.argv[1] 为空)`};let n=e.spawnFn??pe,r,i;try{return p(Ct(),{recursive:!0}),r=m(E(Ct(),`out-backfill.log`),`a`),i=m(E(Ct(),`err-backfill.log`),`a`),n(process.execPath,[...e.execArgv??process.execArgv,t,hS],{detached:!0,stdio:[`ignore`,r,i],env:{...process.env,ELLM_APP_DIR:yt()}}).unref(),{started:!0,reason:``}}catch(e){return{started:!1,reason:e instanceof Error?e.message:String(e)}}finally{r!==void 0&&l(r),i!==void 0&&l(i)}}function yS(e={}){let t=vS(e);return t.started||R(`[log-backfill] 存量补齐子进程未拉起:${t.reason}`),t}gS()&&(await _S(),process.exit(0));var bS=Ol();bS===null&&(R(`[ezllm] 缺少配置文件 ${xt()}(参考 ezllm.config.example.json)`),process.exit(1));var xS=bS;wd(),Rp();var SS=new pu({maxBytes:ql().maxBytes}),CS=Of({spool:SS,getConfig:()=>ql()}),wS=fu();wS>0&&L(`[ezllm] spool 启动清理:回收中断残留 ${String(wS)} 个中转文件`),await Af(),yS();var TS=new rp({spool:SS}),ES=()=>xS.providers.flatMap(e=>e.models.map(e=>e.modelName)),DS=await mp(xS,{authorize(e){let t=Il();return t===``||e===`Bearer ${t}`},register(e){e.addHook(`onAuthorize`,e=>{let t=Il();t!==``&&(e.headers.authorization??``)!==`Bearer ${t}`&&e.reject(`invalid api key`)}),gp(e,{knownModelNames:ES})}},{traceSink:TS}),OS={port:0,startedAt:Date.now(),appDir:yt()},kS=Hl(),AS=$x(DS,OS,kS),jS=Ht({jobs:[CS,Pf({getRetention:()=>Kl()}),tS(DS),iS(),mS(DS)]}),MS=await FS(AS,pp(DS),kS.hostname);OS.port=MS;var NS=!1;function PS(e,t=0){NS||(NS=!0,jS.stop(),L(`[ezllm] ${e},服务退出`),Promise.race([TS.flush(),new Promise(e=>setTimeout(e,5e3))]).then(()=>process.exit(t)))}fy(()=>PS(`与主进程的 IPC 连接已断开`));for(let e of[`SIGINT`,`SIGTERM`])process.on(e,()=>PS(`收到 ${e}`));IS(MS,kS);async function FS(e,t,n){let r=Date.now()+1e4;for(;;)try{return await new Promise((r,i)=>{let a=dt({fetch:e.fetch,port:t,hostname:n,overrideGlobalObjects:!1});a.once(`error`,e=>i(e)),a.once(`listening`,()=>r(a.address()?.port??t))})}catch(e){let n=e.code??String(e);if(n===`EADDRINUSE`&&Date.now()<r){await new Promise(e=>setTimeout(e,300));continue}R(`错误:服务监听 ${String(t)} 失败(${n})${n===`EADDRINUSE`?`,端口被占用(可在配置文件修改 port)`:``}`),process.exit(1)}}function IS(e,t){let r=e=>e===`0.0.0.0`||e===`::`,i=()=>{let e=[];for(let t of Object.values(n()))for(let n of t??[])!n.internal&&n.family===`IPv4`&&e.push(n.address);return e},a=r(t.hostname)?`localhost`:t.hostname,o=r(t.hostname)?`全部网卡`:t.hostname,s=t.source===`credentials`?`未设置任何凭据(主密钥与登录账号皆无),强制仅本机(设置页开关已忽略)`:t.hostname===`127.0.0.1`?`设置页「允许局域网访问」已关闭`:`设置页「允许局域网访问」开启(缺省)`;if(L(`========================================`),L(` EZLLM 服务(网关 + 管理台,单进程)`),L(` 网关端点: http://${a}:${String(e)}/v1/*`),L(` 管理台: http://${a}:${String(e)}/(管理 API 与界面同端口,登录后使用)`),L(` 监听地址: ${o}:${String(e)}(${s})`),r(t.hostname))for(let t of i())L(` 局域网访问: http://${t}:${String(e)}`);L(` 模型数量: ${String(DS.current.expanded.deployments.names.length)}`),Bl().completed||L(` ⚠ 首次启动:请打开 http://${a}:${String(e)}/ 完成初始化向导(设置主密钥与登录账号)`),L(`========================================`)}export{};
|