ezllm 0.0.32 → 0.0.34
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/README.md +1 -1
- package/dist/cli.js +27 -31
- package/dist/daemon.js +15 -19
- package/dist/server.js +88 -92
- package/dist/web-ui/assets/DashboardView-DB3iKQCS.js +1 -0
- package/dist/web-ui/assets/{LayoutView-CruZSfjc.css → LayoutView-BLjO8ed9.css} +1 -1
- package/dist/web-ui/assets/{LayoutView-Qw_xi3gT.js → LayoutView-DWg8yVra.js} +1 -1
- package/dist/web-ui/assets/{LoginView-KgJeUWPc.js → LoginView-Hrm8Vnje.js} +1 -1
- package/dist/web-ui/assets/LogsView-D33M-JJ7.js +5 -0
- package/dist/web-ui/assets/{LogsView-BGMjgMrv.css → LogsView-D7FTeaYQ.css} +1 -1
- package/dist/web-ui/assets/{ManagedServicesView-Bj3uLrri.js → ManagedServicesView-CyEGu6c8.js} +4 -4
- package/dist/web-ui/assets/{ManagedServicesView-Bi180Qjf.css → ManagedServicesView-D29NyvP6.css} +1 -1
- package/dist/web-ui/assets/ProvidersView-C8CfibS_.js +14 -0
- package/dist/web-ui/assets/{ProvidersView-5-nXXTf1.css → ProvidersView-DIlimMSR.css} +1 -1
- package/dist/web-ui/assets/{ServiceStatusView-9V1m2wDr.js → ServiceStatusView-BctoPehE.js} +1 -1
- package/dist/web-ui/assets/{SettingsView-MZYnVBqd.js → SettingsView-3gy8wT-p.js} +1 -1
- package/dist/web-ui/assets/SetupView-B1Mz6mzJ.js +1 -0
- package/dist/web-ui/assets/SetupView-BLl-ZFOA.css +1 -0
- package/dist/web-ui/assets/{config-BhvFrUZd.js → config-BU1w8kdn.js} +1 -1
- package/dist/web-ui/assets/format-Z1cpFfkW.js +1 -0
- package/dist/web-ui/assets/{index-WKbWAuG9.js → index-CREDEMKs.js} +1 -1
- package/dist/web-ui/assets/{message-D0z70H44.js → message-DPoeboTE.js} +1 -1
- package/dist/web-ui/assets/{providers-DvU3UWSV.js → providers-DQ4Op0Nb.js} +1 -1
- package/dist/web-ui/assets/router-CHObBy9_.js +6 -0
- package/dist/web-ui/assets/{useCopyToast-BpTqOna-.js → useCopyToast-pgRyL4NF.js} +1 -1
- package/dist/web-ui/assets/{useManagerApi-DFpyIMxD.js → useManagerApi-DIMNWza9.js} +1 -1
- package/dist/web-ui/assets/{useQuickRangeFilter-C-umbLTm.js → useQuickRangeFilter-D2Kl9eRA.js} +1 -1
- package/dist/web-ui/assets/useToast-CmSnOJzB.js +1 -0
- package/dist/web-ui/index.html +3 -3
- package/package.json +2 -2
- package/dist/web-ui/assets/DashboardView-3tDCIXni.js +0 -1
- package/dist/web-ui/assets/LogsView-LgHo98dV.js +0 -5
- package/dist/web-ui/assets/ProvidersView-DFJ4KxaM.js +0 -14
- package/dist/web-ui/assets/SetupView-BDyHouba.css +0 -1
- package/dist/web-ui/assets/SetupView-DNyvm9nq.js +0 -1
- package/dist/web-ui/assets/format-Dy_WTL6U.js +0 -1
- package/dist/web-ui/assets/router-Bu_wBVat.js +0 -6
- package/dist/web-ui/assets/useToast-BOEMOwWH.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{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}from"node:path";import{cwd as O}from"node:process";import{fileURLToPath as k,pathToFileURL as A}from"node:url";import{createHash as j,randomBytes as M,randomUUID as N}from"node:crypto";import{Readable as P}from"node:stream";import{mkdir as F,readFile as I,rename as ee,writeFile as te}from"node:fs/promises";import{DatabaseSync as ne}from"node:sqlite";import{brotliCompressSync as re,brotliDecompressSync as ie,constants as ae}from"node:zlib";import{createReadStream as oe,existsSync as se,statSync as ce}from"fs";import{join as le}from"path";import{execFileSync as ue,spawn as de,spawnSync as fe}from"node:child_process";import{pipeline as pe}from"node:stream/promises";import{versions as me}from"process";var he=Object.create,ge=Object.defineProperty,_e=Object.getOwnPropertyDescriptor,ve=Object.getOwnPropertyNames,ye=Object.getPrototypeOf,be=Object.prototype.hasOwnProperty,L=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),xe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ve(t),a=0,o=i.length,s;a<o;a++)s=i[a],!be.call(e,s)&&s!==n&&ge(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=_e(t,s))||r.enumerable});return e},Se=(e,t,n)=>(n=e==null?{}:he(ye(e)),xe(t||!e||!e.__esModule||!be.call(e,`default`)?ge(n,`default`,{value:e,enumerable:!0}):n,e)),R=e(import.meta.url),Ce=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},we=e=>e instanceof Ce?e:new Ce(e.message,{cause:e}),Te=global.Request,Ee=class extends Te{constructor(e,t){typeof e==`object`&&Ae in e&&(e=e[Ae]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},De=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)},Oe=Symbol(`wrapBodyStream`),ke=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new Ee(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[Oe]){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 Ee(t,a)},Ae=Symbol(`getRequestCache`),je=Symbol(`requestCache`),Me=Symbol(`incomingKey`),Ne=Symbol(`urlKey`),Pe=Symbol(`headersKey`),Fe=Symbol(`abortControllerKey`),Ie={get method(){return this[Me].method||`GET`},get url(){return this[Ne]},get headers(){return this[Pe]||=De(this[Me])},[Symbol(`getAbortController`)](){return this[Ae](),this[Fe]},[Ae](){return this[Fe]||=new AbortController,this[je]||=ke(this.method,this[Ne],this.headers,this[Me],this[Fe])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(Ie,e,{get(){return this[Ae]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Ie,e,{value:function(){return this[Ae]()[e]()}})}),Object.defineProperty(Ie,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[je]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Ie,Ee.prototype);var Le=(e,t)=>{let n=Object.create(Ie);n[Me]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof a)throw new Ce(`Absolute URL for :path is not allowed in HTTP/2`);try{n[Ne]=new URL(r).href}catch(e){throw new Ce(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof a?e.authority:e.headers.host)||t;if(!i)throw new Ce(`Missing host header`);let o;if(e instanceof a){if(o=e.scheme,o!==`http`&&o!==`https`)throw new Ce(`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 Ce(`Invalid host header`);return n[Ne]=s.href,n},Re=Symbol(`responseCache`),ze=Symbol(`getResponseCache`),Be=Symbol(`cache`),Ve=global.Response,He=class e{#e;#t;[ze](){return delete this[Be],this[Re]||=new Ve(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[Re];if(e){this.#t=e,this[ze]();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[Be]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[Be];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[ze]().headers}get status(){return this[Be]?.[0]??this[ze]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(He.prototype,e,{get(){return this[ze]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(He.prototype,e,{value:function(){return this[ze]()[e]()}})}),Object.defineProperty(He.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[Re]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(He,Ve),Object.setPrototypeOf(He.prototype,Ve.prototype);async function Ue(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function We(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 Ge(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);if(!t.destroyed)return We(e.getReader(),t)}var Ke=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},qe=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=c);var Je=Symbol(`outgoingEnded`),Ye=Symbol(`incomingDraining`),Xe=500,Ze=67108864,Qe=e=>{let t=e;if(e.destroyed||t[Ye])return;if(t[Ye]=!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,Xe);s.unref?.();let c=e=>{n+=e.length,n>Ze&&i()};e.on(`data`,c),e.on(`end`,r),e.on(`error`,r),e.resume()},$e=()=>new Response(null,{status:400}),et=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),tt=(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))},nt=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},rt=async(e,t)=>{let[n,r,i]=e[Be],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=Ke(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=Ke(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())):(nt(t),await Ge(r,t)?.catch(e=>tt(e,t))),t[Je]?.()},it=e=>typeof e.then==`function`,at=async(e,t,n={})=>{if(it(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(et)}if(Be in e)return rt(e,t);let r=Ke(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 Ue(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&&nt(t),await We(n,t,o))}else r[qe]||(t.writeHead(e.status,r),t.end());t[Je]?.()},ot=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Ee&&(Object.defineProperty(global,"Request",{value:Ee}),Object.defineProperty(global,"Response",{value:He})),async(r,i)=>{let o,s;try{s=Le(r,t.hostname);let c=!n||r.method===`GET`||r.method===`HEAD`;if(c||(r[Oe]=!0,r.on(`end`,()=>{c=!0}),r instanceof a&&(i[Je]=()=>{c||setTimeout(()=>{c||setTimeout(()=>{Qe(r)})})}),i.on(`finish`,()=>{c||Qe(r)})),i.on(`close`,()=>{s[Fe]&&(r.errored?s[Fe].abort(r.errored.toString()):i.writableFinished||s[Fe].abort(`Client connection prematurely closed.`)),c||setTimeout(()=>{c||setTimeout(()=>{Qe(r)})})}),o=e(s,{incoming:r,outgoing:i}),Be in o)return rt(o,i)}catch(e){if(o)return tt(e,i);if(t.errorHandler){if(o=await t.errorHandler(s?e:we(e)),!o)return}else o=s?et(e):$e()}try{return await at(o,i,t)}catch(e){return tt(e,i)}}},st=e=>{let t=e.fetch,n=ot(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||i)(e.serverOptions||{},n)},ct=(e,t)=>{let n=st(e);return n.listen(e?.port??3e3,e.hostname,()=>{let e=n.address();t&&t(e)}),n};function lt(e){if(e===void 0)return;let t=e.trim();return t===``?void 0:t}function ut(e){return lt(process.env[e])}function dt(e){let t=lt(e);if(t===void 0)return;let n=Number(t);return Number.isInteger(n)&&n>0?n:void 0}var ft={APP_DIR:ut(`ELLM_APP_DIR`),PORT:dt(ut(`ELLM_PORT`))};function z(e,...t){console.log(e,...t)}function pt(e,...t){console.warn(e,...t)}function B(e,...t){console.error(e,...t)}var mt=T(k(import.meta.url)),ht;function gt(){return E(t(),`.ezllm`)}function _t(){return ht===void 0&&(ht=D(O(),ft.APP_DIR??gt())),ht}function vt(){return D(_t(),`data`)}function yt(){return D(_t(),`ezllm.config.json`)}function bt(){return D(vt(),`ipinfo.json`)}function xt(){return D(_t(),`logs`)}function St(){return D(vt(),`updater.json`)}var Ct=[`hook.cjs`,`hook.mjs`,`hook.js`];function wt(){return Ct.map(e=>E(_t(),e))}function Tt(){return D(_t(),`node`)}function Et(e){return e.find(e=>f(e))}function Dt(){let e=Tt(),t=[E(e,`node_modules`,`ezllm`),E(e,`lib`,`node_modules`,`ezllm`)];return Et(t)??t[0]}function Ot(e){try{return JSON.parse(h(E(e,`package.json`),`utf-8`))}catch{return null}}function kt(e,t){let n=mt;for(let r=0;r<t;r++){if(Ot(n)?.name===e)return n;n=T(n)}return null}var At=kt(`ezllm`,5)??D(mt,`..`),jt=kt(`ellm`,6);function Mt(){return Ot(At)?.name===`ezllm`}function Nt(){let e=Ot(At);return e?.name===`ezllm`?e.version??`0.0.0`:`0.0.0`}function Pt(){let e=vt();f(e)||p(e,{recursive:!0})}function Ft(e){return Et([D(Dt(),`dist`,e),E(At,`dist`,e),...jt?[E(jt,`app`,`cli`,`dist`,e)]:[]])??E(At,`dist`,e)}function It(){return Ft(`daemon.js`)}function Lt(e,t){let n=`${e}.${`${process.pid}.${M(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 Rt(e){return e instanceof Error?e.message:String(e)}function zt(e){Pt();let t=D(vt(),e),n=()=>{if(!f(t))return null;try{return JSON.parse(h(t,`utf-8`))}catch(e){return B(`[store] 读取 ${t} 失败,按空数据处理(原内容将在下次写入时被覆盖):`,Rt(e)),null}},r=null,i=()=>(r===null&&(r=n()??{}),r),a=Promise.resolve(),o=()=>{a=a.then(()=>{Lt(t,{...i()})}).catch(e=>{B(`[store] 写入 ${t} 失败:`,Rt(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 Bt(){try{let e=JSON.parse(h(St(),`utf-8`));return typeof e!=`object`||!e||Array.isArray(e)?{}:e}catch{return{}}}function Vt(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:null}function Ht(e,t){return Vt(typeof e==`function`?e():e)??t}function Ut(e){return typeof e==`object`&&!!e&&typeof e.then==`function`}function Wt(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??Ht(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=Ht(e.job.retryMs??e.job.everyMs,r),s=n??Ht(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(!Ut(t)){u(e,Vt(t),null);return}t.then(t=>{u(e,Vt(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 Gt=(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}},Kt=Symbol(),qt=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),Jt=32,Yt=1e4,Xt=e=>`headers`in e,Zt=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(Xt(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?Qt(e,{all:n,dot:r}):{}};async function Qt(e,t){if(!Xt(e)&&e.bodyCache.formData)return $t(await e.bodyCache.formData,t);let n=Xt(e)?e.headers:e.raw.headers,r=qt(await e.arrayBuffer(),n.get(`Content-Type`)||``);Xt(e)||(e.bodyCache.formData=r);let i=await r;return i?$t(i,t):{}}function $t(e,t){let n=Object.create(null),r={count:0};return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?en(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(tn(n,e,t,r),delete n[e])}),n}var en=(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]},tn=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,a=t.split(`.`,Jt+2);a.length>Jt+1&&nn(),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++>=Yt&&nn(),i[e]=Object.create(null)),i=i[e])})},nn=()=>{throw Error(`Nesting limit exceeded`)},rn=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},an=e=>{let{groups:t,path:n}=on(e);return sn(rn(n),t)},on=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},sn=(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},cn={},ln=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return cn[r]||(cn[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]),cn[r]}return null},un=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},dn=e=>un(e,decodeURI),fn=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 dn(o.includes(`%25`)?o.replace(/%25/g,`%2525`):o)}if(e===63||e===35)break}return t.slice(n,r)},pn=e=>{let t=fn(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},mn=(e,t,...n)=>(n.length&&(t=mn(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),hn=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)},gn=e=>e.indexOf(`%`)===-1?e:un(e,xn),_n=e=>(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),gn(e)),vn=(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 _n(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=_n(s)),o=t,s===``)continue;let c;r===-1?c=``:(c=e.slice(r+1,t===-1?void 0:t),i&&(c=_n(c))),n?(a[s]&&Array.isArray(a[s])||(a[s]=[]),a[s].push(c)):a[s]??=c}return t?a[t]:a},yn=vn,bn=(e,t)=>vn(e,t,!0),xn=decodeURIComponent,Sn=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&&gn(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]=gn(t))}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return yn(this.url,e)}queries(e){return bn(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 Zt(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[Kt](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},Cn={Stringify:1,BeforeStream:2,Stream:3},wn=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},Tn=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=>Tn(e,t,!1,r,i))).then(()=>i[0]));return n?wn(await o,a):o},En=`text/plain; charset=UTF-8`,Dn=(e,t)=>({"Content-Type":e,...t}),On=(e,t)=>new Response(e,t),kn=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 Sn(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||=On(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=On(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=On(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 On(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,Dn(En,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,Dn(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,Dn(`text/html; charset=UTF-8`,n));return typeof e==`object`?Tn(e,Cn.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??=()=>On(),this.#c(this))},An=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],jn=`Can not add a route since the matcher is already built.`,Mn=class extends Error{},Nn=`__COMPOSED_HANDLER`,Pn=e=>e.text(`404 Not Found`,404),Fn=(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)},In=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...An,`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??fn:pn}#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=Pn;errorHandler=Fn;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Fn?r=e.handler:(r=async(n,r)=>(await Gt([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[Nn]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=mn(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=mn(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`,mn(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=mn(this._basePath,t);let i={basePath:r===void 0?this._basePath:mn(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 kn(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=Gt(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${mn(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},Ln=()=>Object.create(null),Rn=[];function zn(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[[],Rn];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var Bn=`[^/]+`,Vn=`(?:|/.*)`,Hn=Symbol(),Un=new Set(`.\\+*[^]$()`);function Wn(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 Gn=class e{#e;#t;#n=Ln();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?[``,``,`.*`]:[``,``,Bn]:null:s===`/*`?[``,``,Vn]: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&&Un.has(n)))throw Hn;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 Hn}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 Hn;l=o.#n[s]=new e}o=l}if(o.#e!==void 0)throw Hn;o.#e=a?-1:n}buildRegExpStr(){let e=Object.keys(this.#n).sort(Wn).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Un.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(`|`)+`)`}},Kn=class{#e={varIndex:0};#t=new Gn;#n=0;paths=Ln();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]}},qn=Ln();function Jn(e){return qn[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?Vn:e===`*`?`.*`:`/:${Bn}`)}$`)}function Yn(e,t){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(Jn(n).test(t))return[...e[n]]}var Xn=class{name=`RegExpRouter`;#e;#t;#n;constructor(){this.#e={ALL:Ln()},this.#t={ALL:Ln()},this.#n={ALL:new Kn}}#r(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===Hn?new Mn(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(jn);if(!r[e]){this.#n[e]=new Kn;for(let t of[r,i]){t[e]=Ln();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=Jn(t);for(let e of a)r[e][t]||(this.#r(e,t),r[e][t]=Yn(r[e],t)||Yn(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=hn(t)||[t];for(let e of o)for(let t of a)i[t][e]||(this.#r(t,e),i[t][e]=Yn(r[t],e)||Yn(r.ALL,e)||[]),i[t][e].push([n,e])}match=zn;buildAllMatchers(){let e=Ln();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,qn=Ln(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=Ln(),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,Ln()]),Rn];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),Ln())])}return[o,s.map(e=>a[e]),i]}},Zn=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(jn);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 Mn)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]}},Qn=Ln(),$n=0,er=class e{#e=[];#t=Ln();#n=[];#r;#i=Qn;insert(t,n,r){let i=this,a=an(n),o=new Set,s=0;for(let t of a){let n=a[++s],r=ln(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:++$n}})}#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=Ln(),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=Qn;let r=[this],i=rn(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===Qn?{}:{...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])]}},tr=class{name=`TrieRouter`;#e=new er;add(e,t,n){for(let r of hn(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}},nr=class extends In{constructor(e={}){super(e),this.router=e.router??new Zn({routers:[new Xn,new tr]})}},rr=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function ir(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 ar(e){return{byName:new Map(e.map(e=>[e.name,e])),names:e.map(e=>e.name)}}function or(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 sr(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function cr(e){return e instanceof Error?e.message:String(e)}function lr(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}var ur=[`openai`,`anthropic`,`openai-responses`],dr=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{createServer as t}from"http";import{Http2ServerRequest as n,constants as r}from"http2";import{Readable as i}from"stream";import a from"crypto";import{closeSync as o,copyFileSync as s,createWriteStream as c,existsSync as l,mkdirSync as u,openSync as d,readFileSync as f,readdirSync as p,renameSync as m,rmSync as h,rmdirSync as g,statSync as _,unlinkSync as v,writeFileSync as y}from"node:fs";import{homedir as b,networkInterfaces as x,platform as S}from"node:os";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{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";import{createReadStream as pe,existsSync as me,statSync as he}from"fs";import{join as ge}from"path";var I=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),_e=e(import.meta.url),ve=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},ye=e=>e instanceof ve?e:new ve(e.message,{cause:e}),be=global.Request,xe=class extends be{constructor(e,t){typeof e==`object`&&Te in e&&(e=e[Te]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Se=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)},Ce=Symbol(`wrapBodyStream`),we=(e,t,n,r,a)=>{let o={method:e,headers:n,signal:a.signal};if(e===`TRACE`){o.method=`GET`;let e=new xe(t,o);return Object.defineProperty(e,"method",{get(){return`TRACE`}}),e}if(e!==`GET`&&e!==`HEAD`){if(`rawBody`in r&&r.rawBody instanceof Buffer)o.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[Ce]){let e;o.body=new ReadableStream({async pull(t){try{e||=i.toWeb(r).getReader();let{done:n,value:a}=await e.read();n?t.close():t.enqueue(a)}catch(e){t.error(e)}}})}else o.body=i.toWeb(r)}return new xe(t,o)},Te=Symbol(`getRequestCache`),Ee=Symbol(`requestCache`),De=Symbol(`incomingKey`),Oe=Symbol(`urlKey`),ke=Symbol(`headersKey`),Ae=Symbol(`abortControllerKey`),je={get method(){return this[De].method||`GET`},get url(){return this[Oe]},get headers(){return this[ke]||=Se(this[De])},[Symbol(`getAbortController`)](){return this[Te](),this[Ae]},[Te](){return this[Ae]||=new AbortController,this[Ee]||=we(this.method,this[Oe],this.headers,this[De],this[Ae])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(je,e,{get(){return this[Te]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(je,e,{value:function(){return this[Te]()[e]()}})}),Object.defineProperty(je,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[Ee]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(je,xe.prototype);var Me=(e,t)=>{let r=Object.create(je);r[De]=e;let i=e.url||``;if(i[0]!==`/`&&(i.startsWith(`http://`)||i.startsWith(`https://`))){if(e instanceof n)throw new ve(`Absolute URL for :path is not allowed in HTTP/2`);try{r[Oe]=new URL(i).href}catch(e){throw new ve(`Invalid absolute URL`,{cause:e})}return r}let a=(e instanceof n?e.authority:e.headers.host)||t;if(!a)throw new ve(`Missing host header`);let o;if(e instanceof n){if(o=e.scheme,o!==`http`&&o!==`https`)throw new ve(`Unsupported scheme`)}else o=e.socket&&e.socket.encrypted?`https`:`http`;let s=new URL(`${o}://${a}${i}`);if(s.hostname.length!==a.length&&s.hostname!==a.replace(/:\d+$/,``))throw new ve(`Invalid host header`);return r[Oe]=s.href,r},Ne=Symbol(`responseCache`),Pe=Symbol(`getResponseCache`),Fe=Symbol(`cache`),Ie=global.Response,Le=class e{#e;#t;[Pe](){return delete this[Fe],this[Ne]||=new Ie(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[Ne];if(e){this.#t=e,this[Pe]();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[Fe]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[Fe];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[Pe]().headers}get status(){return this[Fe]?.[0]??this[Pe]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(Le.prototype,e,{get(){return this[Pe]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(Le.prototype,e,{value:function(){return this[Pe]()[e]()}})}),Object.defineProperty(Le.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[Ne]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(Le,Ie),Object.setPrototypeOf(Le.prototype,Ie.prototype);async function Re(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function ze(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 Be(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);if(!t.destroyed)return ze(e.getReader(),t)}var Ve=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},He=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=a);var Ue=Symbol(`outgoingEnded`),We=Symbol(`incomingDraining`),Ge=500,Ke=67108864,qe=e=>{let t=e;if(e.destroyed||t[We])return;if(t[We]=!0,e instanceof n){try{e.stream?.close?.(r.NGHTTP2_NO_ERROR)}catch{}return}let i=0,a=()=>{clearTimeout(s),e.off(`data`,c),e.off(`end`,a),e.off(`error`,a)},o=()=>{a();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},s=setTimeout(o,Ge);s.unref?.();let c=e=>{i+=e.length,i>Ke&&o()};e.on(`data`,c),e.on(`end`,a),e.on(`error`,a),e.resume()},Je=()=>new Response(null,{status:400}),Ye=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),Xe=(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))},Ze=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},Qe=async(e,t)=>{let[n,r,i]=e[Fe],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=Ve(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=Ve(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())):(Ze(t),await Be(r,t)?.catch(e=>Xe(e,t))),t[Ue]?.()},$e=e=>typeof e.then==`function`,et=async(e,t,n={})=>{if($e(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(Ye)}if(Fe in e)return Qe(e,t);let r=Ve(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 Re(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&&Ze(t),await ze(n,t,o))}else r[He]||(t.writeHead(e.status,r),t.end());t[Ue]?.()},tt=(e,t={})=>{let r=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==xe&&(Object.defineProperty(global,"Request",{value:xe}),Object.defineProperty(global,"Response",{value:Le})),async(i,a)=>{let o,s;try{s=Me(i,t.hostname);let c=!r||i.method===`GET`||i.method===`HEAD`;if(c||(i[Ce]=!0,i.on(`end`,()=>{c=!0}),i instanceof n&&(a[Ue]=()=>{c||setTimeout(()=>{c||setTimeout(()=>{qe(i)})})}),a.on(`finish`,()=>{c||qe(i)})),a.on(`close`,()=>{s[Ae]&&(i.errored?s[Ae].abort(i.errored.toString()):a.writableFinished||s[Ae].abort(`Client connection prematurely closed.`)),c||setTimeout(()=>{c||setTimeout(()=>{qe(i)})})}),o=e(s,{incoming:i,outgoing:a}),Fe in o)return Qe(o,a)}catch(e){if(o)return Xe(e,a);if(t.errorHandler){if(o=await t.errorHandler(s?e:ye(e)),!o)return}else o=s?Ye(e):Je()}try{return await et(o,a,t)}catch(e){return Xe(e,a)}}},nt=e=>{let n=e.fetch,r=tt(n,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming});return(e.createServer||t)(e.serverOptions||{},r)},rt=(e,t)=>{let n=nt(e);return n.listen(e?.port??3e3,e.hostname,()=>{let e=n.address();t&&t(e)}),n};function it(e){if(e===void 0)return;let t=e.trim();return t===``?void 0:t}function at(e){return it(process.env[e])}function ot(e){let t=it(e);if(t===void 0)return;let n=Number(t);return Number.isInteger(n)&&n>0?n:void 0}var st={APP_DIR:at(`ELLM_APP_DIR`),PORT:ot(at(`ELLM_PORT`)),NODE_MIRROR:at(`ELLM_NODE_MIRROR`),NODE_BIN:at(`ELLM_NODE_BIN`)};function L(e,...t){console.log(e,...t)}function ct(e,...t){console.warn(e,...t)}function R(e,...t){console.error(e,...t)}var lt=T(A(import.meta.url)),ut;function dt(){return ut===void 0&&(ut=D(k(),st.APP_DIR??E(b(),`.ezllm`))),ut}function ft(){return D(dt(),`data`)}function pt(){return D(dt(),`ezllm.config.json`)}function mt(){return D(ft(),`ipinfo.json`)}function ht(){return D(dt(),`logs`)}function gt(){return D(ft(),`updater.json`)}var _t=[`hook.cjs`,`hook.mjs`,`hook.js`];function vt(){return _t.map(e=>E(dt(),e))}function yt(){return D(dt(),`node`)}function bt(e){return e.find(e=>l(e))}function xt(){let e=yt(),t=[E(e,`node_modules`,`ezllm`),E(e,`lib`,`node_modules`,`ezllm`)];return bt(t)??t[0]}function St(e){try{return JSON.parse(f(E(e,`package.json`),`utf-8`))}catch{return null}}function Ct(e,t){let n=lt;for(let r=0;r<t;r++){if(St(n)?.name===e)return n;n=T(n)}return null}var wt=Ct(`ezllm`,5)??D(lt,`..`),Tt=Ct(`ellm`,6);function Et(){return St(wt)?.name===`ezllm`}function Dt(){let e=St(wt);return e?.name===`ezllm`?e.version??`0.0.0`:`0.0.0`}function Ot(){let e=ft();l(e)||u(e,{recursive:!0})}function kt(e){return bt([D(xt(),`dist`,e),E(wt,`dist`,e),...Tt?[E(Tt,`app`,`cli`,`dist`,e)]:[]])??E(wt,`dist`,e)}function At(){return kt(`daemon.js`)}function jt(e,t){let n=`${e}.${`${process.pid}.${N(6).toString(`hex`)}`}.tmp`;try{y(n,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,`utf-8`),m(n,e)}finally{try{h(n,{force:!0})}catch{}}}function Mt(e){Ot();let t=D(ft(),e),n=e=>e instanceof Error?e.message:String(e),r=()=>{if(!l(t))return null;try{return JSON.parse(f(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(()=>{jt(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 Nt(){try{let e=JSON.parse(f(gt(),`utf-8`));return typeof e!=`object`||!e||Array.isArray(e)?{}:e}catch{return{}}}function Pt(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 Ft=(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}},It=Symbol(),Lt=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),Rt=32,zt=1e4,Bt=e=>`headers`in e,Vt=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(Bt(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?Ht(e,{all:n,dot:r}):{}};async function Ht(e,t){if(!Bt(e)&&e.bodyCache.formData)return Ut(await e.bodyCache.formData,t);let n=Bt(e)?e.headers:e.raw.headers,r=Lt(await e.arrayBuffer(),n.get(`Content-Type`)||``);Bt(e)||(e.bodyCache.formData=r);let i=await r;return i?Ut(i,t):{}}function Ut(e,t){let n=Object.create(null),r={count:0};return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?Wt(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&(Gt(n,e,t,r),delete n[e])}),n}var Wt=(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]},Gt=(e,t,n,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let i=e,a=t.split(`.`,Rt+2);a.length>Rt+1&&Kt(),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++>=zt&&Kt(),i[e]=Object.create(null)),i=i[e])})},Kt=()=>{throw Error(`Nesting limit exceeded`)},qt=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},Jt=e=>{let{groups:t,path:n}=Yt(e);return Xt(qt(n),t)},Yt=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},Xt=(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},Zt={},Qt=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return Zt[r]||(Zt[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]),Zt[r]}return null},$t=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},en=e=>$t(e,decodeURI),tn=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 en(o.includes(`%25`)?o.replace(/%25/g,`%2525`):o)}if(e===63||e===35)break}return t.slice(n,r)},nn=e=>{let t=tn(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},rn=(e,t,...n)=>(n.length&&(t=rn(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),an=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)},on=e=>e.indexOf(`%`)===-1?e:$t(e,dn),sn=e=>(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),on(e)),cn=(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 sn(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=sn(s)),o=t,s===``)continue;let c;r===-1?c=``:(c=e.slice(r+1,t===-1?void 0:t),i&&(c=sn(c))),n?(a[s]&&Array.isArray(a[s])||(a[s]=[]),a[s].push(c)):a[s]??=c}return t?a[t]:a},ln=cn,un=(e,t)=>cn(e,t,!0),dn=decodeURIComponent,fn=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&&on(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]=on(t))}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return ln(this.url,e)}queries(e){return un(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 Vt(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[It](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},pn={Stringify:1,BeforeStream:2,Stream:3},mn=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},hn=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=>hn(e,t,!1,r,i))).then(()=>i[0]));return n?mn(await o,a):o},gn=`text/plain; charset=UTF-8`,_n=(e,t)=>({"Content-Type":e,...t}),vn=(e,t)=>new Response(e,t),yn=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 fn(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||=vn(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=vn(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=vn(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 vn(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,_n(gn,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,_n(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,_n(`text/html; charset=UTF-8`,n));return typeof e==`object`?hn(e,pn.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??=()=>vn(),this.#c(this))},bn=[`get`,`post`,`put`,`delete`,`options`,`patch`,`query`],xn=`Can not add a route since the matcher is already built.`,Sn=class extends Error{},Cn=`__COMPOSED_HANDLER`,wn=e=>e.text(`404 Not Found`,404),Tn=(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)},En=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...bn,`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??tn:nn}#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=wn;errorHandler=Tn;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Tn?r=e.handler:(r=async(n,r)=>(await Ft([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[Cn]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=rn(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=rn(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`,rn(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=rn(this._basePath,t);let i={basePath:r===void 0?this._basePath:rn(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 yn(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=Ft(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${rn(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},Dn=()=>Object.create(null),On=[];function kn(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[[],On];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var An=`[^/]+`,jn=`(?:|/.*)`,Mn=Symbol(),Nn=new Set(`.\\+*[^]$()`);function Pn(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 Fn=class e{#e;#t;#n=Dn();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?[``,``,`.*`]:[``,``,An]:null:s===`/*`?[``,``,jn]: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&&Nn.has(n)))throw Mn;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 Mn}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 Mn;l=o.#n[s]=new e}o=l}if(o.#e!==void 0)throw Mn;o.#e=a?-1:n}buildRegExpStr(){let e=Object.keys(this.#n).sort(Pn).map(e=>{let t=this.#n[e],n=t.buildRegExpStr();return n===``?``:(typeof t.#t==`number`?`(${e})@${t.#t}`:Nn.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(`|`)+`)`}},In=class{#e={varIndex:0};#t=new Fn;#n=0;paths=Dn();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]}},Ln=Dn();function Rn(e){return Ln[e]??=RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(e,t)=>t?`\\${t}`:e===`/*`?jn:e===`*`?`.*`:`/:${An}`)}$`)}function zn(e,t){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(Rn(n).test(t))return[...e[n]]}var Bn=class{name=`RegExpRouter`;#e;#t;#n;constructor(){this.#e={ALL:Dn()},this.#t={ALL:Dn()},this.#n={ALL:new In}}#r(e,t){try{this.#n[e].insert(t,!/\*|\/:/.test(t))}catch(e){throw e===Mn?new Sn(t):e}}add(e,t,n){let r=this.#e,i=this.#t;if(!r)throw Error(xn);if(!r[e]){this.#n[e]=new In;for(let t of[r,i]){t[e]=Dn();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=Rn(t);for(let e of a)r[e][t]||(this.#r(e,t),r[e][t]=zn(r[e],t)||zn(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=an(t)||[t];for(let e of o)for(let t of a)i[t][e]||(this.#r(t,e),i[t][e]=zn(r[t],e)||zn(r.ALL,e)||[]),i[t][e].push([n,e])}match=kn;buildAllMatchers(){let e=Dn();for(let t of Object.keys(this.#t))e[t]=this.#i(t);return this.#e=this.#t=this.#n=void 0,Ln=Dn(),e}#i(e){let t=this.#e[e],n=this.#t[e],r=this.#n[e],i=Dn(),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,Dn()]),On];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),Dn())])}return[o,s.map(e=>a[e]),i]}},Vn=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(xn);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 Sn)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]}},Hn=Dn(),Un=0,Wn=class e{#e=[];#t=Dn();#n=[];#r;#i=Hn;insert(t,n,r){let i=this,a=Jt(n),o=new Set,s=0;for(let t of a){let n=a[++s],r=Qt(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:++Un}})}#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=Dn(),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=Hn;let r=[this],i=qt(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===Hn?{}:{...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])]}},Gn=class{name=`TrieRouter`;#e=new Wn;add(e,t,n){for(let r of an(t)||[t])this.#e.insert(e,r,n)}match(e,t){return this.#e.search(e,t)}},Kn=class extends En{constructor(e={}){super(e),this.router=e.router??new Vn({routers:[new Bn,new Gn]})}},qn=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Jn(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 Yn(e){return{byName:new Map(e.map(e=>[e.name,e])),names:e.map(e=>e.name)}}function Xn(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 Zn(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Qn(e){return e instanceof Error?e.message:String(e)}function $n(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}var er=[`openai`,`anthropic`,`openai-responses`],tr=class extends Error{issues;constructor(e){super(`配置校验失败:\n - ${e.join(`
|
|
4
|
+
- `)}`),this.name=`ConfigValidationError`,this.issues=e}};function nr(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 tr([`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=er.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;er.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=rr(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&&!qn.includes(y)&&i.push(`${u}.maxReasoningEffort 必须是 ${qn.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 tr(i);return{deployments:Yn(l),port:e.port??29770,warnings:a}}function rr(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 ir(e){return{kind:`ok`,value:e}}function ar(e,t){return{kind:`error`,status:e,message:t}}var or=class extends Error{status;constructor(e,t){super(e),this.name=`ProtocolError`,t?.status!==void 0&&(this.status=t.status)}};function sr(e){return e instanceof or&&e.status!==void 0?e.status:void 0}function cr(e){return typeof e.then==`function`}function lr(e){return e instanceof Error?e.message:String(e)}var ur=class{#e;constructor(e){this.#e=e}run(e,t){let n=-1,r=(e,i)=>{if(e<=n)return ar(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 ar(500,lr(e))}return cr(o)?o.then(void 0,e=>ar(500,lr(e))):o};return r(0,e)}};function dr(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 fr(e){return e===`openai`}var pr=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}},mr=10,hr=13,gr=32,_r=6;function vr(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<_r&&!b(s.join(``)+e.slice(0,_r-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)===mr?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)===hr?(h=!1,g=!0,``):(h=!1,e.slice(r+(e.charCodeAt(r)===hr&&e.charCodeAt(r+1)===mr?2:1)))}function y(e){if(e){if(e.charCodeAt(e.length-1)===hr){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&&xr(e,`data`)||t===101&&xr(e,`event`)||t===105&&xr(e,`id`)||t===114&&xr(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 pr(`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(yr(e,t,r)){let r=e.charCodeAt(t+5)===gr?t+6:t+5,o=e.slice(r,n);if(f===0&&e.charCodeAt(n+1)===mr){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 br(e,t,r)?p=e.slice(e.charCodeAt(t+6)===gr?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)===hr&&e.charCodeAt(t)===mr&&t++}return e.slice(t)}function C(e,t,r){if(t===r){T();return}let i=e.charCodeAt(t);if(yr(e,t,i)){let n=e.charCodeAt(t+5)===gr?t+6:t+5,i=e.slice(n,r);d=f===0?i:`${d}\n${i}`,f++;return}if(br(e,t,i)){p=e.slice(e.charCodeAt(t+6)===gr?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)===gr?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)===gr?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)===gr?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 pr(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:n}));break;default:r?.(new pr(`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 yr(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 br(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 xr(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 Sr=`[DONE]`,Cr=``,wr=class{parser;collected=[];sawFirstChunk=!1;constructor(){this.parser=vr({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(Cr)&&(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 Br(e,t={}){let n=e.type;return zr((t.protocol===void 0||t.protocol===`anthropic`)&&typeof n==`string`?n:null,JSON.stringify(e))}function Vr(){return zr(null,Fr)}async function*Hr(e,t){let n=e.getReader(),r=new TextDecoder,i=new Lr,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=Ur(e,t);if(yield n,n.done)return}}for(let e of i.push(r.decode())){let n=Ur(e,t);if(yield n,n.done)return}for(let e of i.flush()){let n=Ur(e,t);if(yield n,n.done)return}a=!0}finally{a||n.cancel().catch(()=>{})}}function Ur(e,t){return{event:e.event,data:e.data,done:t!==`anthropic`&&e.data===`[DONE]`}}function Wr(e){let t;try{t=JSON.parse(e.data)}catch{return null}return typeof t!=`object`||!t||Array.isArray(t)?null:t}function Gr(e,t){return Br(e,{protocol:t})}function Kr(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 xr(i)?i.then(a):a(i);function a(e){return e.kind===`error`?e:_r(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:qr(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 xr(i)?i.then(e=>Jr(e,n,t.pair.inbound,t)):Jr(i,n,t.pair.inbound,t)})}return{requestLayers:n,responseLayers:r}}function qr(e,t,n,r){return e instanceof ReadableStream?e.pipeThrough(Yr(t,n,`upstream`,r)):e===null?null:t(e,r)}function Jr(e,t,n,r){if(e.kind===`error`)return e;let i=e.value;if(`stream`in i)return _r({...i,stream:i.stream.pipeThrough(Yr(t,n,`client`,r))});if(i.body===null||typeof i.body!=`object`)return e;let a=t(i.body,r);return _r(a===null?{...i,body:null}:{...i,body:a})}function Yr(e,t,n,r){let i=new Lr,a=new TextDecoder,o=!1,s=(i,a)=>{if(t!==`anthropic`&&i.data===`[DONE]`){a.enqueue(Vr());return}let s=Wr({event:i.event,data:i.data,done:!1});if(s===null){a.enqueue(zr(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 wr(t,{message:Sr(e)}))a.enqueue(Br(n,{protocol:t}));a.terminate();return}c!==null&&a.enqueue(Br(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 Xr(e,t){return new Cr([...t.specs.flatMap(e=>Kr(e,t).requestLayers),Zr(t)]).run(e,e=>_r(e))}function Zr(e){return(t,n)=>{let r;try{r=e.options.translate===!1?t.body:e.pair.translateRequest(t.body,e.options)}catch(e){return vr(br(e)??500,Sr(e))}let i={"content-type":`application/json`},a=r.stream===!0;return n({headers:i,body:r,stream:a})}}var Qr=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 P({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=P.toWeb(t)}async*#a(){for await(let e of Hr(this.#e.upstreamBytes,this.#e.upstreamProtocol)){if(e.done){this.#i=!0;return}let t=Wr(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 wr(this.#e.inboundProtocol,{status:502,message:`upstream stream ended before the [DONE] sentinel (truncated)`}))yield Gr(e,this.#e.inboundProtocol);return}Tr(this.#e.inboundProtocol)&&(yield Vr());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 Gr(t,this.#e.inboundProtocol)}}catch(e){let t=Sr(e);for(let n of wr(this.#e.inboundProtocol,{status:br(e),message:t}))yield Gr(n,this.#e.inboundProtocol)}finally{await this.#n.return?.().catch(()=>{})}}};function $r(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 ei(e,t){let n=$r(e.headers),r=(n[`content-type`]??``).includes(`text/event-stream`);return e.status<200||e.status>299||!r?ti(e,t,n):ni(e,t,n)}async function ti(e,t,n){let r;try{r=await e.text()}catch(e){return vr(502,`failed to read upstream response body: ${Sr(e)}`)}let i;try{let e=JSON.parse(r);if(typeof e!=`object`||!e)return vr(502,`upstream response is not a valid JSON object`);i=e}catch{return vr(502,`upstream response is not valid JSON`)}return new Cr([...t.specs.flatMap(e=>Kr(e,t).responseLayers),ri(t)]).run({status:e.status,headers:n,body:i},e=>_r(e))}function ni(e,t,n){return e.body===null?vr(502,`streaming response has no body`):new Cr([...t.specs.flatMap(e=>Kr(e,t).responseLayers),ii(t)]).run({status:e.status,headers:n,body:e.body},e=>_r(e))}function ri(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 vr(br(e)??500,Sr(e))}return n({status:r.status,headers:r.headers,body:i})}}function ii(e){return(t,n)=>{let r=t,i=new Qr({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 ai=[],oi=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=ai;#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 vr(500,`RequestContext: request() can only be called once (one container per round trip)`);this.#r=!0,this.#e=e,this.#t=si(this.#a,e,this);let t=Xr(e,this);return xr(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(vr(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 ei(e,this)}};function si(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 ci=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]}},li=class{#e;#t;#n;#r=new ci;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 oi({chainName:this.#n,pair:this.#e,options:Object.freeze({...this.#t}),snapshot:this.#r.snapshot()})}};function H(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(e){return H(e)?e:{}}function W(e){return Array.isArray(e)?e:[]}function G(e){return typeof e==`string`?e:null}function K(e){return typeof e==`string`?e:``}function ui(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function di(e){return typeof e!=`number`||!Number.isFinite(e)?0:Math.max(0,Math.trunc(e))}function fi(){return crypto.randomUUID()}function pi(){return Math.floor(Date.now()/1e3)}function mi(...e){for(let t of e){let e=di(t);if(e>0)return e}return 0}function hi(e){let t=U(e.prompt_tokens_details);return{cacheRead:mi(e.cache_read_input_tokens,e.prompt_cache_hit_tokens,t.cached_tokens),cacheCreation:mi(e.cache_creation_input_tokens,t.cache_creation_tokens,t.cache_write_tokens)}}function gi(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 _i=new Set([`end_turn`,`max_tokens`,`stop_sequence`,`tool_use`,`refusal`]),vi=new Set([`stop`,`length`,`tool_calls`,`function_call`,`content_filter`]);function yi(e){return{stop:`end_turn`,length:`max_tokens`,tool_calls:`tool_use`}[e]??`end_turn`}function bi(e){let t=G(e)??``;return _i.has(t)?t:yi(t)}function xi(e){let t=G(e.stop_reason),n=G(U(e.provider_specific_fields).stop_reason),r=t??n;return r===null||r===``||_i.has(r)||vi.has(r)?null:r}function Si(e){let t=G(e.refusal);if(t!==null&&t!==``)return t;let n=G(U(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 wi(e){return Ci[e]??`api_error`}function Ti(e){let t=H(e)?e.code:void 0;return typeof t==`number`&&Number.isInteger(t)&&t>=400&&t<600?t:500}function Ei(e){if(!H(e))return!1;let t=e.type===`error`?e.error:void 0;return H(t)&&typeof t.type==`string`&&typeof t.message==`string`}function Di(e,t){if(H(t)){let e=t.error;if(H(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(H(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 Oi(e,t){return Ei(t)?t:{type:`error`,error:{type:wi(e),message:Di(e,t)}}}function ki(e){let t=U(e);if(t.type===`message_start`){let e=U(t.message).usage;return H(e)?e:null}if(t.type===`message_delta`){let e=t.usage;return H(e)?e:null}return null}function Ai(e){if(typeof e!=`object`||!e||Array.isArray(e))return String(e);let t=U(e),n=t.message;return typeof n==`string`&&n!==``?n:JSON.stringify(t)}var ji=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 yr(Ai(t),{status:Ti(t)});let n=U(W(e.choices)[0]),r=U(n.delta),i=[];if(!this.#c){this.#c=!0;let t=e.id;this.#p=typeof t==`string`&&t!==``?t:fi(),i.push(this.#m(G(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 W(r.thinking_blocks)){let t=G(U(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 W(r.tool_calls).entries()){let n=U(t),r=U(n.function),a=typeof n.index==`number`?n.index:e,o=G(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:G(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=U(e.usage),l=di(c.prompt_tokens),u=di(c.completion_tokens);if(l>0){this.#i=l;let e=hi(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=xi(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`:bi(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:gi(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*Mi(e){let t=new ji;for await(let n of e)for(let e of t.translateFrame(U(n)))yield e;for(let e of t.flush())yield e}var Ni=4096;function Pi(e){return e.map(e=>{if(!H(e))return U(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(!H(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 Fi(e,t){let n=!1;for(let t of e){let e=t.content;if(Array.isArray(e)){for(let t of e)if(U(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 Ii(e){if(!H(e.metadata))return;let t=U(e.metadata).user_id;t==null?delete e.metadata:e.metadata={user_id:t}}function Li(e){let t=e.output_config;if(!H(t))return;let n=t.effort;if(typeof n==`string`&&n!==``&&![`high`,`medium`,`low`,`xhigh`,`max`].includes(n))throw new yr(`Invalid effort value: ${JSON.stringify(n)}. Must be one of: 'high', 'medium', 'low', 'xhigh', 'max'`,{status:400})}function Ri(e){let t=U(e),n=Pi(W(t.messages)),r=W(t.tools).map(U),i=Fi(n,r),a={...t,messages:n};return i!==r&&(a.tools=i),`max_tokens`in a||(a.max_tokens=Ni),Ii(a),delete a.is_vertex_request,delete a.client_metadata,Li(a),a}function zi(e){return typeof e==`number`&&Number.isFinite(e)?Math.floor(e):0}function Bi(e){let t=zi(e.input_tokens??0),n=zi(e.output_tokens??0),r=0,i=0,a=e.iterations,o=Array.isArray(a)?a.map(U):null;o!==null&&o.length>0&&(t=o.reduce((e,t)=>e+zi(t.input_tokens??0),0),n=o.reduce((e,t)=>e+zi(t.output_tokens??0),0),r=o.reduce((e,t)=>e+zi(t.cache_creation_input_tokens??0),0),i=o.reduce((e,t)=>e+zi(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 Vi=/^<(?:think|thinking|budget:thinking)>([\s\S]*?)<\/(?:think|thinking|budget:thinking)>([\s\S]*)/;function Hi(e){if(!e)return{reasoningContent:null,content:e};let t=Vi.exec(e);return t===null?{reasoningContent:null,content:e}:{reasoningContent:t[1]??null,content:t[2]??null}}function Ui(e){let t=e.content,n=G(t);return`reasoning_content`in e?{reasoningContent:G(e.reasoning_content),content:n}:`reasoning`in e?{reasoningContent:G(e.reasoning),content:n}:typeof t==`string`?Hi(t):{reasoningContent:null,content:n}}function Wi(e){let t=U(e),n=t.arguments,r;if(n==null){let e=t.parameters;r=H(e)?JSON.stringify(e):``}else r=H(n)?JSON.stringify(n):String(n);return{arguments:r,name:G(t.name)}}function Gi(e){return e.type===`custom`||e.custom!=null}function Ki(e){return Gi(e)?Object.fromEntries(Object.entries(e).filter(([e,t])=>e!==`function`&&e!==`type`||t!=null)):{id:e.id==null?fi():String(e.id),type:e.type==null?`function`:String(e.type),function:Wi(e.function)}}function qi(e){let t=new Map;for(let[n,r]of e.entries()){if(Gi(r))continue;let e=U(r.function),i=e.name,a=JSON.parse(typeof e.arguments==`string`?e.arguments:``);if(i!==`multi_tool_use.parallel`)continue;let o=U(a),s=(Array.isArray(o.tool_uses)?o.tool_uses:[]).map((e,t)=>{let n=U(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 Ji(e){try{let t=qi(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 Yi(e){return Array.isArray(e.tool_calls)?Ji(e.tool_calls.map(e=>Ki(U(e)))):[]}function Xi(e){if(typeof e!=`string`||e===``)return{};try{return U(JSON.parse(e))}catch{return{}}}function Zi(e){let t=[];for(let n of e.thinkingBlocks){let e=U(n);e.type===`thinking`?t.push({type:`thinking`,thinking:G(e.thinking)??``,signature:G(e.signature)}):e.type===`redacted_thinking`&&t.push({type:`redacted_thinking`,data:G(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=U(n),r=U(e.function);t.push({type:`tool_use`,id:G(e.id)??``,name:G(r.name)??``,input:Xi(r.arguments)})}return t}function Qi(e){let{cacheRead:t,cacheCreation:n}=hi(e);return gi(di(e.prompt_tokens),di(e.completion_tokens),t,n)}function $i(e){let t=U(e),n=t.error;if(n!=null){let e=U(n);throw new yr(typeof e.message==`string`?e.message:JSON.stringify(n),{status:Ti(n)})}let r=W(t.choices);if(r.length===0)throw Error(`upstream returned a response with no 'choices'. Raw keys: ${Object.keys(t).join(`, `)}`);let i=U(r[0]),a=U(i.message),o=Yi(a),{reasoningContent:s,content:c}=Ui(a),l=W(a.thinking_blocks),u=Si(a),d=G(i.finish_reason)??`stop`;d===`stop`&&o.length>0&&(d=`tool_calls`);let f=xi(i),p=f===null?bi(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:Zi({thinkingBlocks:l,reasoningContent:s,content:c,refusal:u,toolCalls:o}),stop_reason:p,...m?{stop_details:{type:`refusal`}}:{},stop_sequence:f,usage:Qi(U(t.usage))}}function ea(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=>ea(e)).join(`, `)}]`:H(e)?`{${Object.entries(e).map(([e,t])=>`'${e}': ${ea(t)}`).join(`, `)}}`:String(e)}function ta(e){let t=``,n=[],r=null,i=[];if((Array.isArray(e.content)?e.content:[]).forEach((e,r)=>{let a=U(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 na(e){let t=[];for(let n of e){let e=U(n),r=typeof e.type==`string`?e.type:``;(r===`tool_use`||r===`server_tool_use`)&&t.push(e.caller)}return t}function ra(e,t){let n=na(Array.isArray(t.content)?t.content:[]),r=Array.isArray(e.content)?e.content:[],i=0;for(let e of r){let t=U(e);if(t.type!==`tool_use`)continue;let r=n[i];i+=1,r!==void 0&&(t.caller=r)}}function ia(e){let t=U(e);if(`error`in t&&t.error!==null&&t.error!==void 0)throw new yr(ea(t.error));let n=ta(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=U($i({id:fi(),object:`chat.completion`,...t.model===void 0?{}:{model:t.model},choices:[{index:0,finish_reason:G(t.stop_reason),message:r}],usage:Bi(U(t.usage))}));return ra(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 aa=class{contentBlocks=[];toolIndex=-1;currentContentBlockType=null;cumulativeUsage={};parse(e){let t=G(e.type)??``,n=``,r=null,i=``,a=null,o=null,s=null,c=null;if(t===`content_block_delta`){let t=U(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=>U(e.delta)).filter(e=>typeof e.thinking==`string`).map(e=>e.thinking).join(``),signature:n}])}}else if(t===`content_block_start`){let t=U(e.content_block);if(this.contentBlocks.length=0,this.currentContentBlockType=G(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=G(t.name)??``;r={id:G(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=>U(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=G(U(e.delta).stop_reason)??``,`usage`in e&&(a=Bi(this.#e(e.usage)));else if(t===`message_start`){let t=U(e.message);c=G(t.model),`usage`in t&&(a=Bi(this.#e(t.usage)))}else if(t===`error`){let t=U(e.error);throw new yr(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,...U(e)},this.cumulativeUsage}},oa=class{inbound=`anthropic`;upstream=`anthropic`;translateRequest(e){return Ri(e)}translateResponse(e){return ia(e)}async*bridgeFrames(e){let t=new aa,n=new ji;for await(let r of e){let e=t.parse(U(r));if(e!==null)for(let t of n.translateFrame(e))yield t}for(let e of n.flush())yield e}usageFromFrame(e){return ki(e)}errorEnvelope(e,t){return Oi(e,t)}},sa=`Operator note (not from the user): the following was originally a mid-conversation system-role reminder.`;function ca(e){let t=e.role;return t===`system`?`system`:t===`tool`||t===`function`?`tool`:t===`user`?`user`:`other`}function la(e){let t=e.content;if(typeof t==`string`)return t===``?[]:[{type:`text`,text:t}];let n=[];for(let e of W(t)){let t=U(e);if(t.type!==`text`)continue;let r=G(t.text)??``;r!==``&&n.push({type:`text`,text:r})}return n}function ua(e){return{role:`user`,content:[{type:`text`,text:sa},...la(e)]}}function da(e){return e.filter(e=>la(e).length>0).map(ua)}function fa(e){let t=[],n=null,r=[];for(let i of e){let e=ca(i);e!==n&&(r.length>0&&t.push(r),r=[],n=e),r.push(i)}return r.length>0&&t.push(r),t}function pa(e){let t=fa(e),n=[];for(let e=0;e<t.length;e++){let r=t[e]??[],i=ca(r[0]??{}),a=t[e+1],o=a===void 0?null:ca(a[0]??{});if(i===`system`){o!==`tool`&&n.push(...da(r));continue}let s=e>0?t[e-1]:void 0;if(i===`tool`&&s!==void 0&&ca(s[0]??{})===`system`){n.push(...r,...da(s));continue}n.push(...r)}return n}function ma(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),...pa(e.slice(t))]}var ha=new Set([`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`not`,`propertyNames`,`then`,`unevaluatedItems`,`unevaluatedProperties`]),ga=new Set([`allOf`,`anyOf`,`items`,`oneOf`,`prefixItems`]),_a=new Set([`$defs`,`definitions`,`dependentSchemas`,`patternProperties`,`properties`]),va=1024;function ya(e){if(e.includes(`\\p{`)||e.includes(`\\p<`))return!1;try{new RegExp(e)}catch{return!1}return!0}function ba(e,t){let n={},r=!1;for(let[i,a]of Object.entries(e)){if(i===`pattern`&&typeof a==`string`&&!ya(a)){r=!0;continue}let e=xa(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 xa(e,t,n){if(ga.has(e)&&Array.isArray(t)){let e=t.map(e=>H(e)?n.get(e)??e:e);return e.every((e,n)=>e===t[n])?t:e}if(!H(t))return t;if(_a.has(e)){let r={},i=!1;for(let[a,o]of Object.entries(t)){if(e===`patternProperties`&&typeof a==`string`&&!ya(a)){i=!0;continue}if(H(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 ha.has(e)?n.get(t)??t:t}function Sa(e,t){for(let[n,r]of Object.entries(e))if(_a.has(n)&&H(r))for(let e of Object.values(r))H(e)&&t.push(e);else if(ga.has(n)&&Array.isArray(r))for(let e of r)H(e)&&t.push(e);else ha.has(n)&&H(r)&&t.push(r)}function Ca(e){let t=new Map,n=[],r=[e];for(;r.length>0&&n.length<va;){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=ba(n,t);e!==n&&t.set(n,e)}return t.get(e)??e}function wa(e){if(H(e))return e;if(typeof e!=`string`)return null;try{let t=JSON.parse(e);return H(t)?t:null}catch{return null}}function Ta(e,t){if(typeof e==`string`)return e===``?null:e;let n=[];for(let r of W(e)){let e=U(r);if(e.type!==`text`)continue;let i=G(e.text)??``;(i!==``||t)&&n.push({type:`text`,text:i})}return n.length>0?n:null}function Ea(e){let t=Ta(e,!0);return t===null?[]:[{role:`system`,content:t}]}function Da(e){return e.flatMap(e=>{let t=U(e),n=t.content;if(t.role===`system`){let e=Ta(n,!1);return e===null?[]:[{role:`system`,content:e}]}return t.role===`user`?Oa(n):t.role===`assistant`?Ma(n):[]})}function Oa(e){if(typeof e==`string`)return[{role:`user`,content:e}];let t=[],n=[];for(let r of W(e)){let e=U(r);if(e.type===`text`)t.push({type:`text`,text:G(e.text)??``});else if(e.type===`image`){let n=Aa(e.source);n!==null&&t.push({type:`image_url`,image_url:{url:n}})}else e.type===`tool_result`&&n.push({role:`tool`,content:ka(e.content),tool_call_id:G(e.tool_use_id)??``})}let r=t.length>0?t:``;return n.length>0&&t.length===0?n:[...n,{role:`user`,content:r}]}function ka(e){return typeof e==`string`?e:W(e).map(e=>G(U(e).text)??``).join(``)}function Aa(e){let t=U(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`?G(t.url):null}function ja(e){return e.map(e=>e.type===`thinking`?G(e.thinking)??``:``).filter(e=>e!==``).join(`
|
|
16
|
-
`)}function Ma(e){if(typeof e==`string`)return[{role:`assistant`,content:e}];let t=[],n=[],r=[];for(let i of W(e)){let e=U(i);e.type===`text`?t.push(G(e.text)??``):e.type===`tool_use`?n.push({id:G(e.id)??``,type:`function`,function:{name:G(e.name)??``,arguments:JSON.stringify(e.input??{})}}):e.type===`thinking`?r.push({type:`thinking`,thinking:G(e.thinking)??``,signature:G(e.signature)??``}):e.type===`redacted_thinking`&&r.push({type:`redacted_thinking`,data:G(e.data)??``})}let i=ja(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 Na=64;function Pa(e){if(typeof e!=`string`)return null;let t;try{t=JSON.parse(e)}catch{return null}let n=U(t).session_id;if(typeof n!=`string`)return null;let r=n.slice(0,Na);return r===``?null:r}function Fa(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=Pa(U(e.metadata).user_id);i(`prompt_cache_key`,l,l!==null);let u=Ia(e.tool_choice);i(`tool_choice`,u,u!==null);let d=e.tools;i(`tools`,W(d).map(La),W(d).length>0);let f=Ra(e.thinking,e.output_config);return i(`reasoning_effort`,f,f!==null),r}function Ia(e){let t=U(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 La(e){let t=U(e),n=t.input_schema,r=wa(n);if(r===null&&n!=null)throw new yr(`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 Ra(e,t=void 0){let n=U(e),r=G(n.type)??``;if(r===`disabled`)return null;if(r===`adaptive`)return G(U(n.output_config).effort)??G(U(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 za(e,t){let n=U(e),r=ma([...Ea(n.system),...Da(W(n.messages))]),i=Fa(n,t);if(i.messages=r,i.reasoning_effort===`none`){let e={...i};delete e.reasoning_effort,i=e}return i}var Ba=class{inbound=`anthropic`;upstream=`openai`;translateRequest(e,t){return za(e,t)}translateResponse(e){return $i(e)}bridgeFrames(e){return Mi(e)}usageFromFrame(e){return ki(e)}errorEnvelope(e,t){return Oi(e,t)}},Va={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`};function Ha(e){let t=Va[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t}function Ua(e,t){if(typeof t==`string`&&t!==``)return t;if(H(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 Wa(e,t){return H(t)&&H(t.error)?t:{error:{message:Ua(e,t),type:Ha(e),param:null,code:String(e)}}}function Ga(){return`chatcmpl-${fi()}`}var Ka={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 qa(e){return Ka[G(e)??``]??`stop`}function Ja(e,t){let n=e.iterations,r=null;if(Array.isArray(n)&&n.length>0){let e=n.map(e=>{let t=U(U(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=U(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 Ya(e,t={}){let n=di(e.input_tokens),r=di(e.output_tokens),i=di(e.cache_creation_input_tokens),a=di(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(H(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]=di(r))}s.cache_creation_token_details=n}let c={completion_tokens:r,prompt_tokens:o,total_tokens:o+r,completion_tokens_details:Ja(e,r),prompt_tokens_details:s,cache_creation_input_tokens:i,cache_read_input_tokens:a},l=G(e.inference_geo);l!==null&&(c.inference_geo=l);let u=G(e.speed);if(u!==null&&(c.speed=u),t.fromStreamBuilder!==!0){let t=G(e.service_tier);t!==null&&(c.service_tier=t)}return c}function Xa(e,t){return{...e??{},...t}}function Za(e){return/claude-[a-z]+-(?:4[-._](?:[6-9]|[1-9]\d)(?!\d)|[5-9](?!\d)(?:[-._]\d{1,2}(?!\d))?)/.test(e)}function Qa(e){return/claude-[a-z]+-4[-._]6(?!\d)/.test(e)}function $a(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 eo(e,t){if(typeof t==`string`&&t!==``)return t;if(H(t)){let e=t.error;if(H(e)){let t=e.message;if(typeof t==`string`&&t!==``)return t}let n=t.detail;if(H(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 to(e,t){if(H(t)){let e=t.error;if(H(e)&&t.type!==`error`&&typeof e.message==`string`)return t}return{error:{message:eo(e,t),type:Ha(e),param:null,code:String(e)}}}var no={low:1024,medium:2048,high:4096,xhigh:8192,max:16384,minimal:1024},ro={low:`low`,minimal:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:`max`},io=4096,ao=1024,oo=`[System: Empty message content sanitised to satisfy protocol]`,so=new Set([`type`,`properties`,`additionalProperties`,`required`,`$defs`,`strict`]);function co(e,t){if(e==null)return{type:`object`,properties:{}};if(!H(e))throw new yr(`Invalid input_schema for tool "${t}": expected an object, got ${typeof e}`,{status:400});let n={};for(let[t,r]of Object.entries(e))so.has(t)&&(n[t]=r);return n.type!==`object`&&(n.type=`object`),n.properties===void 0&&(n.properties={}),n}function lo(e){let t=U(e),n=U(t.function),r=t.type;if(r!==`function`&&r!==`custom`)throw new yr(`Unsupported tool type: ${String(r)}`,{status:400});let i=G(n.name)??``,a={name:i,input_schema:co(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;H(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 uo(e){return e.map(e=>{let t=U(e);return t.input_schema===void 0?lo(e):t})}var fo={name:`dummy_tool`,input_schema:{type:`object`,properties:{}},type:`custom`,description:`This is a dummy tool call`};function po(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`)||`tool_use_id`}function mo(e,t){if(typeof e!=`string`||e.trim()===``)return{};try{return JSON.parse(e)}catch(e){throw new yr(`Failed to parse tool call arguments for tool '${t}': ${e instanceof Error?e.message:String(e)}`,{status:400})}}function ho(e){if(!H(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 go(e){let t=e.cache_control;return H(t)?t:void 0}function _o(e,t){return e===``?null:t===void 0?{type:`text`,text:e}:{type:`text`,text:e,cache_control:t}}function vo(e){let t=typeof e==`string`?e:G(U(e).url)??``,n=typeof e==`string`?null:G(U(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 yr(`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 yo(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=U(n);if(t.type===`text`)e.push({type:`text`,text:G(t.text)??``});else if(t.type===`image_url`){let n=vo(t.image_url),r=go(t);r!==void 0&&(n.cache_control=r),e.push(n)}}n=e}let r={type:`tool_result`,tool_use_id:po(G(e.tool_call_id)??fi()),content:n},i=go(e);return i!==void 0&&(r.cache_control=i),r}function bo(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:oo}:e;if(!Array.isArray(n))return e;let r=!1,i=n.map(e=>{let t=U(e);if(t.type!==`text`)return e;let n=t.text;return typeof n==`string`&&n.trim()!==``?e:(r=!0,{...t,text:oo})});return r?{...e,content:i}:e}function xo(e){let t=[];for(let n of e){let e=n.role;if(e===`tool`||e===`function`){t.push(yo(n));continue}let r=n.content;if(typeof r==`string`){let e=_o(r,void 0);e!==null&&t.push(e);continue}for(let e of W(r)){let n=U(e),r=go(n);if(n.type===`text`){let e=_o(G(n.text)??``,r);e!==null&&t.push(e)}else if(n.type===`image_url`){let e=vo(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 So(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=U(e).type;return t===`thinking`||t===`redacted_thinking`}),o=r.thinking_blocks;if(Array.isArray(o)&&!a)for(let e of o)ho(e)||t.push(U(e));if(i!==null)for(let e of i){let n=U(e),r=n.type;if(r===`thinking`){let e=n.thinking;typeof e==`string`&&e!==``&&!ho(n)&&t.push(n)}else if(r===`text`){let e=_o(G(n.text)??``,go(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=_o(e,go(r));n!==null&&t.push(n)}let s=r.tool_calls;if(Array.isArray(s))for(let e of s){let r=U(e);if(r.type!==`function`)continue;let i=U(r.function),a=G(i.name)??``,o=po(G(r.id)??fi());if(n.has(o))continue;n.add(o);let s={type:`tool_use`,id:o,name:a,input:mo(i.arguments,a)},c=go(r);c!==void 0&&(s.cache_control=c),t.push(s)}}return t.length>0?{role:`assistant`,content:t}:null}function Co(e){let t=e.map(e=>bo(U(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=xo(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=So(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 wo(e){let t=[];for(let n of e){let e=n.content;if(typeof e==`string`){let r=_o(e,go(n));r!==null&&t.push(r);continue}for(let n of W(e)){let e=U(n);if(e.type!==`text`)continue;let r=_o(G(e.text)??``,go(e));r!==null&&t.push(r)}}return t}var To=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,Eo=/^\+?[\d\s()-]{7,}$/;function Do(e){return!To.test(e)&&!Eo.test(e)}function Oo(e){return typeof e!=`number`||!Number.isFinite(e)?null:Number.isInteger(e)?e:Math.max(1,Math.round(e))}function ko(e){let t=typeof e==`string`?[e]:W(e),n=[];for(let e of t)typeof e==`string`&&e.trim()!==``&&n.push(e);return n.length>0?n:null}function Ao(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(H(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=U(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 jo(e,t){let n=Za(e)&&!Qa(e);return t>=8192&&n?`xhigh`:t>=4096?`high`:t>=2048?`medium`:`low`}function Mo(e,t){if(!Za(e)||Qa(e))return;let n=U(t.thinking);if(n.type!==`enabled`)return;let r=n.budget_tokens,i=jo(e,typeof r==`number`?r:0);t.thinking={type:`adaptive`};let a=t.output_config;t.output_config={effort:i,...H(a)?a:{}}}function No(e,t){let n=e.budget_tokens;return typeof t!=`number`||typeof n!=`number`?e:t<=ao?null:n<t?e:{type:e.type??`enabled`,budget_tokens:t-1}}function Po(e,t){if(Za(t))return{type:`adaptive`,display:`summarized`};let n=no[e];if(n===void 0)throw new yr(`Unmapped reasoning effort: '${e}'. Must be one of: 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'none'.`,{status:400});return{type:`enabled`,budget_tokens:n}}function Fo(e,t,n,r){if(U(n).type===`adaptive`&&!Za(r)){let n=e.max_completion_tokens??e.max_tokens,r=No({type:`enabled`,budget_tokens:no.medium??2048},n);r!==null&&(t.thinking=r);return}t.thinking=n,Mo(r,t)}function Io(e,t,n){let r=typeof t==`string`?t:G(U(t).effort);if(r!==null){if(r===`none`){delete e.thinking,delete e.output_config;return}if(e.thinking=Po(r,n),Za(n)){let t=ro[r];if(t===void 0)throw new yr(`Invalid reasoning_effort: '${r}'. Must be one of: 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'none'`,{status:400});e.output_config={effort:t}}}}var Lo=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 Ro(e,t){let n=G(e.model)??``,r={};for(let[t,i]of Object.entries(e)){if(!Lo.has(t)){r[t]=i;continue}switch(t){case`model`:r.model=i;break;case`max_tokens`:case`max_completion_tokens`:{let e=Oo(i);e!==null&&(r.max_tokens=e);break}case`tools`:W(i).length>0&&(r.tools=uo(W(i)));break;case`tool_choice`:case`parallel_tool_calls`:{let t=Ao(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=ko(i);e!==null&&(r.stop_sequences=e);break}case`temperature`:case`top_p`:($a(n)||t===`temperature`&&i===1)&&(r[t]=i);break;case`top_k`:$a(n)&&(r.top_k=i);break;case`thinking`:Fo(e,r,i,n);break;case`reasoning_effort`:Io(r,i,n);break;case`user`:{let e=G(i);e!==null&&Do(e)&&(r.metadata={user_id:e});break}case`metadata`:H(i)&&i.user_id!==null&&i.user_id!==void 0&&(r.metadata={user_id:i.user_id});break;case`cache_control`:H(i)&&(r.cache_control=i)}}return r.messages=t,r.tools===void 0&&zo(e)&&(r.tools=[fo]),r}function zo(e){return W(e.messages).some(e=>`tool_calls`in U(e))}function Bo(e){let t=U(e),n=W(t.messages),r=0;for(;r<n.length&&U(n[r]).role===`system`;)r+=1;let i=n.slice(0,r).map(e=>U(e)),a=Ro(t,Co(ma(n.slice(r).map(e=>U(e))))),o=wo(i);if(o.length>0&&(a.system=o),a.max_tokens===void 0){let e=U(a.thinking).budget_tokens;a.max_tokens=typeof e==`number`?e+io:io}return a}function Vo(e){let t=``,n=[],r=null;for(let[i,a]of e.entries()){let e=U(a),o=G(e.type)??``;if(o===`text`)t+=G(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};H(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 Ho(e){let t=U(e),n=t.error;if(n!=null)throw new yr(G(U(n).message)??JSON.stringify(n)??String(n),{status:Ti(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:Ga(),created:pi(),...t.model===void 0?{}:{model:t.model},object:`chat.completion`,choices:[{finish_reason:qa(t.stop_reason),index:0,message:Vo(W(r))}],usage:Ya(U(t.usage))}}var Uo=class{#e;#t;#n=null;#r=null;#i=!1;#a=!1;#o=!1;#s=!1;#c=null;#l=-1;#u=``;#d=``;constructor(){this.#e=Ga(),this.#t=pi()}translateFrame(e){if(this.#o)return[];switch(G(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 yr(G(U(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:Ya(this.#r,{fromStreamBuilder:!0})})])}#f(e){let t=U(e.message),n=G(t.model);n!==null&&(this.#n=n);let r=t.usage;return H(r)&&(this.#r=Xa(this.#r,r)),[]}#p(e){let t=U(e.content_block),n=G(t.type)??``;if(this.#c=n,this.#u=``,this.#d=``,n===`text`){let e=G(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 H(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=U(e.delta),n=G(t.type)??``;if(n===`text_delta`){let e=G(t.text)??``;return e===``?[]:[this.#_({content:e})]}if(n===`thinking_delta`){let e=G(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=G(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=G(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;H(t)&&(this.#r=Xa(this.#r,t));let n=qa(U(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*Wo(e){let t=new Uo;for await(let n of e)for(let e of t.translateFrame(U(n)))yield e;for(let e of t.flush())yield e}var Go=class{inbound=`openai`;upstream=`anthropic`;translateRequest(e){return Bo(e)}translateResponse(e){return Ho(e)}bridgeFrames(e){return Wo(e)}usageFromFrame(e){let t=e.usage;return H(t)?t:null}errorEnvelope(e,t){return to(e,t)}},Ko=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 H(t)?t:null}errorEnvelope(e,t){return Wa(e,t)}};function qo(e){let t=e;if(H(t.usage))return t.usage;let n=t.response;return H(n)&&H(n.usage)?n.usage:null}var Jo=new Set([`text`,`image_url`,`input_audio`,`audio_url`,`document`,`guarded_text`,`grounding_source`,`query`,`video_url`,`file`,`thinking`,`redacted_thinking`]),Yo=new Set([`encrypted_content`,`redacted_thinking`]),Xo=new Set;function Zo(e){return typeof e==`string`?e:W(e).flatMap(e=>{if(typeof e==`string`)return[e];let t=U(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:K(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:Qo(K(t.type)),text:n};return`cache_control`in t&&(r.cache_control=t.cache_control),[r]})}function Qo(e){if(e.startsWith(`input_`)){let t=e.slice(6);return t===`audio`?`input_audio`:Jo.has(t)?t:`text`}return e===`tool_result`||e===`output_text`?`text`:Jo.has(e)?e:`text`}function $o(e){let t=e.arguments;if(!t&&e.type===`custom_tool_call`){let n=K(e.input);t=n===``?``:JSON.stringify({content:n})}return[{role:`assistant`,content:null,tool_calls:[{id:K(e.call_id??e.id),type:`function`,function:{name:K(e.name),arguments:String(t??``)},index:0}]}]}function es(e){let t=K(e.call_id);return t===``?[]:[{role:`tool`,content:ts(e.output),tool_call_id:t}]}function ts(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=U(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(H(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=>U(e).type===`image_url`))return t;if(n.length>0)return n.join(``)}try{return JSON.stringify(e)}catch{return String(e)}}function ns(e){return[`function_call_output`,`custom_tool_call_output`,`web_search_call`,`computer_call_output`,`tool_result`].includes(K(e.type))}function rs(e){return K(e.type)===`function_call`||K(e.type)===`custom_tool_call`}function is(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 W(e)){let e=U(t);if(rs(e)){let t=$o(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(ns(e)){n.push(...es(e));continue}if(e.type===`reasoning`){n.push(...fs(e));continue}let r=e.content;if(r==null)continue;let i=os(e),a=i,o=Zo(r),s=n[n.length-1];i===`assistant`&&s?.role===`assistant`&&Array.isArray(s.tool_calls)?n[n.length-1]={...s,content:as(s.content,o)}:n.push({role:a,content:o})}return gs(n)}function as(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}]:W(e),r=typeof t==`string`?[{type:`text`,text:t}]:W(t);return[...n,...r]}function os(e){return K(e.role)===``?`user`:K(e.role)}function ss(e){return ls(e.content)??us(e.summary)}function cs(e,t){let n=e.flatMap(e=>{let n=U(e);if(t.has(K(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=>W(e.thinking_blocks));return{...e,...i===null?{}:{reasoning_content:i},...a.length>0?{thinking_blocks:[...a,...W(e.thinking_blocks)]}:{}}}function gs(e){let t=[],n=[];for(let r of e){if(ms(r)){n.push(r);continue}if(n.length>0){if(r.role===`assistant`){t.push(hs(r,n)),n=[];continue}t.push(...n),n=[]}t.push(r)}return t.push(...n),t}function _s(e){if(e==null)return null;if(typeof e==`string`)return e;let t=U(e),n=U(t.function);if(H(t.function)&&K(n.name)!==``)return t;let r=K(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=K(t.name);return e===``?`required`:{type:`function`,function:{name:e}}}if(r===`custom`){let e=U(t.custom),n=K(t.name)===``?K(e.name):K(t.name);return n===``?`required`:{type:`function`,function:{name:n}}}return e}function vs(e){let t=[],n=null,r=W(e);for(let e=0;e<r.length;e++){let i=U(r[e]),a=K(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=wa(n);if(r===null&&n!=null)throw new yr(`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:K(i.name),description:K(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 ys(e){let t=U(U(e).format);return K(t.type)===`json_schema`?{type:`json_schema`,json_schema:{name:t.name??`response_schema`,schema:t.schema??{},strict:t.strict??!1}}:K(t.type)===`json_object`?{type:`json_object`}:null}function bs(e){let t=e,{tools:n,webSearchOptions:r}=vs(t.tools??[]),i=ys(t.text),a=U(t.reasoning).effort,o=typeof a==`string`?a:null,s={messages:is(t.input,t.instructions),model:t.model??null,tool_choice:_s(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 W(c.tools).length===0?Object.fromEntries(Object.entries(c).filter(([e])=>e!==`tool_choice`&&e!==`tools`&&e!==`parallel_tool_calls`)):c}var xs={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=xs[e];return n===void 0?(t(e),`stop`):n}function Cs(e){let t=U(e.message),n=Array.isArray(t.tool_calls)?t.tool_calls.map(e=>Ki(U(e))):null;n!==null&&(n=Ji(n));let{reasoningContent:r,content:i}=Ui(t),a={content:i,role:t.role==null?`assistant`:String(t.role),tool_calls:n};r!==null&&(a.reasoning_content=r);let o=G(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 ws(e){let t=U(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=H(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=H(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 Ts(e){let t=e.error;if(t!=null){let e=U(t);throw new yr(typeof e.message==`string`?e.message:JSON.stringify(t),{status:Ti(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(U(e)))};return e.usage!=null&&(r.usage=ws(e.usage)),r}function Es(e){return e===`length`||e===`max_tokens`||e===`content_filter`?`incomplete`:`completed`}function Ds(e){return e===`content_filter`?`content_filter`:`max_output_tokens`}function Os(e){return typeof e==`string`?e:W(e).map(e=>typeof e==`string`?e:G(U(e).text)??``).join(``)}function ks(e){if(!H(e))return null;let t=ui(e.prompt_tokens)??0,n=ui(e.completion_tokens)??0,r=ui(e.total_tokens)??t+n,i=U(e.prompt_tokens_details),a={},o=ui(i.cached_tokens);o!==null&&(a.cached_tokens=o);let s=ui(i.text_tokens);s!==null&&(a.text_tokens=s);let c=U(e.completion_tokens_details),l={},u=ui(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 As(e,t){let n=U(e.function);return{type:`function_call`,id:t,call_id:G(e.id)??`call_${fi()}`,name:G(n.name)??``,arguments:G(n.arguments)??``,status:`completed`,namespace:null}}function js(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:Ds(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 Ms(e,t){let n=U(W(e.choices)[0]),r=U(n.message),i=G(n.finish_reason),a=Os(r.content),o=W(r.tool_calls),s=G(r.reasoning_content),c=[];s!==null&&s!==``&&c.push({type:`reasoning`,id:`rs_${fi()}`,status:Es(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_${fi()}`,status:Es(i),role:`assistant`,content:[{type:`output_text`,text:a,annotations:[]}],phase:null});for(let e of o)c.push(As(U(e),`fc_${fi()}`));return js(t,Es(i),c,ks(e.usage),i)}function Ns(e){let t=U(e),n=G(t.model);return Ms(Ts(t),{id:`resp_${fi()}`,created:pi(),...n===null?{}:{model:n}})}function Ps(e){let t=e.error;if(t)throw new yr(typeof t!=`object`||!t||Array.isArray(t)?String(t):typeof U(t).message==`string`?U(t).message:JSON.stringify(t),{status:Ti(t)});let n={choices:(Array.isArray(e.choices)?e.choices:[]).map(e=>{let t=U(e),n=t.finish_reason,r=U(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={...U(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 Fs=10;function Is(e){let t={};for(let[n,r]of Object.entries(e))r!==null&&(t[n]=r);return t}function Ls(e){if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var Rs=class{#e=0;#t=!1;#n=!1;#r=`msg_${fi()}`;#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=G(e.model);t!==null&&(this.#p=t);let n=[];if(!this.#t){this.#t=!0;let e=js(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())}H(e.usage)&&(this.#l=e.usage);let r=U(W(e.choices)[0]),i=U(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=G(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 W(i.tool_calls))n.push(...this.#_(U(e)));let c=G(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=Es(this.#c);return e.push(this.#S({type:`response.completed`,response:js(this.#m(),t,this.#x(),ks(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_${fi()}`),this.#d+=e,[this.#S({type:`response.reasoning_summary_text.delta`,item_id:this.#u,output_index:0,delta:e})]}#_(e){let t=ui(e.index)??0,n=U(e.function),r=this.#s.get(t),i=[];if(r===void 0){let a=G(e.id)??`call_${fi()}`;r={itemId:`fc_${a}`,outputIndex:this.#o,callId:a,name:G(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=G(n.name);a!==null&&a!==``&&r.name===``&&(r.name=a);let o=Ls(n.arguments);if(o!==``){r.args+=o;for(let e=0;e<o.length;e+=Fs)i.push(this.#S({type:`response.function_call_arguments.delta`,item_id:r.itemId,output_index:r.outputIndex,delta:o.slice(e,e+Fs)}))}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:Es(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=Is(e.response)),t}},zs=class{inbound=`openai-responses`;upstream=`openai`;translateRequest(e){return bs(e)}translateResponse(e){return Ns(e)}async*bridgeFrames(e,t,n){let r=new Rs({id:`resp_${fi()}`,created:pi(),...H(n)?{requestEcho:n}:{}});for await(let t of e)for(let e of r.translateFrame(Ps(t)))yield e;for(let e of r.flush())yield e}usageFromFrame(e){return qo(e)}errorEnvelope(e,t){return Wa(e,t)}};function Bs(e){return Array.isArray(e)?e.map(e=>{if(!H(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 Vs(e){let t=e;return{...t,input:Bs(t.input)}}var Hs=[`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`],Us=[`input_tokens_details`,`output_tokens_details`,`cost`],Ws={audio_tokens:null,cached_tokens:0,cached_tokens_details:null,image_tokens:null,text_tokens:null,video_tokens:null},Gs={audio_tokens:null,reasoning_tokens:null,text_tokens:null};function Ks(e,t){let n={...e};for(let[e,r]of Object.entries(t))e in n||(n[e]=r);return n}function qs(e){let t=e.usage;if(!H(t))return;let n={...t};for(let e of Us)e in n||(n[e]=null);let r=n.input_tokens_details;H(r)&&(n.input_tokens_details=Ks(r,Ws));let i=n.output_tokens_details;H(i)&&(n.output_tokens_details=Ks(i,Gs)),e.usage=n}function Js(e){let t=e.tools;if(!Array.isArray(t))return;let n=null;for(let[e,r]of t.entries()){if(!H(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 Ys(e){let t=e.output;if(!Array.isArray(t))return;let n=null;for(let[e,r]of t.entries()){if(!H(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 Xs(e){for(let t of Hs)t in e||(e[t]=null);return Js(e),Ys(e),qs(e),e}function Zs(e){return Xs({...e})}function Qs(e){let t=e.error;if(H(t)&&t.code===null)return{...e,error:{...t,code:`unknown_error`}};let n=e.response;if(H(n)){let t=n.error;if(H(t)&&t.code===null)return{...e,response:{...n,error:{...t,code:`unknown_error`}}}}return null}function $s(e){if(!H(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 ec(e){let t=e.response;if(!H(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($s);e.some((e,t)=>e!==i[t])&&(n.tools=e,r=!0)}return r?{...e,response:n}:e}var tc=class{inbound=`openai-responses`;upstream=`openai-responses`;translateRequest(e){return Vs(e)}translateResponse(e){return Zs(e)}async*bridgeFrames(e){for await(let t of e){let e=t;yield ec(Qs(e)??e)}}usageFromFrame(e){return qo(e)}errorEnvelope(e,t){return Wa(e,t)}},nc={anthropicToAnthropic:new oa,anthropicToChatCompletions:new Ba,chatCompletionsToAnthropic:new Go,chatCompletionsToChatCompletions:new Ko,responsesToResponses:new tc,responsesToChatCompletions:new zs},rc=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 li(nc[e],t??{},e)}};function ic(){return new rc}var ac={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`},oc={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`},sc=new Set([204,205,304]);function cc(e){return ac[e]??`api_error`}function lc(e){let t=oc[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t}function uc(e){let t;try{t=JSON.parse(e)}catch{return null}return V(t)?t:null}function dc(e){let t=e.type===`error`?e.error:void 0;return V(t)&&typeof t.type==`string`&&typeof t.message==`string`}function fc(e){let t=uc(e);if(t===null)return e;if(dc(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 pc(e,t,n){let r=t===``||sc.has(e)?null:t;return new Response(r,{status:e,headers:{"content-type":n}})}function mc(e,t,n){let r=uc(t),i;if(r!==null&&dc(r))i={...r},n!==void 0&&r.request_id===void 0&&(i.request_id=n);else{let r={type:`error`,error:{type:cc(e),message:fc(t)}};n!==void 0&&(r.request_id=n),i=r}return pc(e,JSON.stringify(i),`application/json`)}function hc(e,t){let n={error:{message:fc(t),type:lc(e),param:null,code:String(e)}};return pc(e,JSON.stringify(n),`application/json`)}function gc(e,t,n,r){return e===`anthropic`?mc(t,n,r):hc(t,n)}function _c(e,t,n,r){return e===`anthropic`?mc(t,n,r):hc(t,n)}var vc={openai:`chat/completions`,anthropic:`messages`,"openai-responses":`responses`},yc={openai:`https://api.openai.com`,anthropic:`https://api.anthropic.com`,"openai-responses":`https://api.openai.com`};function bc(e){let t=e.provider,n=(e.apiBase??yc[t]).replace(/\/+$/,``),r=vc[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 xc=6e5,Sc=12e4,Cc=65536,wc=4096,Tc=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??xc,this.#a=t.timeouts?.idleMs??Sc;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,cr(e))}let t=e.body;if(t===null?this.#l():(this.#u(this.#a),t=this.#p(t)),!e.ok){let n=await Dc(t,Cc),r=n.length<=wc?n:n.slice(0,wc);return{kind:`error`,status:e.status,response:gc(this.#t,e.status,r,this.#n)}}return{kind:`ok`,transport:{status:e.status,headers:lr(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 yr(`upstream timeout: no data for ${String(this.#a)}ms`,{status:504})}#f(e,t){return{kind:`error`,status:e,response:_c(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 Ec(e){e!==null&&e.cancel().catch(()=>{})}async function Dc(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 Oc=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`]),kc=`sk-ant-oat`,Ac=`oauth-2025-04-20`,jc="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 Mc(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();Oc.has(e)||e.startsWith(`proxy-`)||e.startsWith(`x-forwarded-`)||(t[n]=r)}return t}function Nc(e,t){return e===void 0?t:e.split(`,`).map(e=>e.trim()).includes(t)?e:`${e}, ${t}`}function Pc(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 ${kc}`)){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`]=Nc(n[`anthropic-beta`],Ac),n[`anthropic-dangerous-direct-browser-access`]=`true`}if(r===void 0)throw new yr(jc,{status:401});let o=r.startsWith(kc),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 Fc(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 Ic(e,t,n){let r={...Mc(n),...t.headers??{}};return e===`anthropic`?Pc(r,t.apiKey):Fc(r,t.apiKey)}var Lc=/<invoke\s+name=/g,Rc=2;function zc(e,t){let n=Ic(e.provider,e,t??{});return{upstreamRequest:e=>({...e,headers:n})}}function Bc(e){return{clientRequest:t=>V(t.body)?{...t,body:{...t.body,model:e.modelName}}:t}}function Vc(e){return V(e.error)}function Hc(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 Vc(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 Vc(t)?e:{...t,model:n}}}}}function Uc(e,t){let n=rr.indexOf(e),r=rr.indexOf(t);return n<0||r<0||n<=r?e:t}function Wc(e){return{upstreamRequest:t=>{if(!V(t.body))return t;let n=t.body.reasoning_effort;if(typeof n!=`string`)return t;let r=Uc(n,e);return r===n?t:{...t,body:{...t.body,reasoning_effort:r}}}}}function Gc(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,Lc.lastIndex=0;for(let e=Lc.exec(o);e!==null;e=Lc.exec(o))n+=1;if(t>e&&n>=Rc)throw new yr(`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 Kc(){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 qc(){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 Jc(e,t){let n=[];(e===`anthropicToChatCompletions`||e===`chatCompletionsToChatCompletions`||e===`responsesToChatCompletions`)&&n.push(Kc()),e===`chatCompletionsToAnthropic`&&n.push(qc()),e===`anthropicToChatCompletions`&&t.maxReasoningEffort!==void 0&&n.push(Wc(t.maxReasoningEffort));let r=t.thinkingGuardMaxChars??0;return(e===`anthropicToAnthropic`||e===`anthropicToChatCompletions`)&&r>0&&n.push(Gc(r)),n}function Yc(e){if(!V(e))return null;let t=sr(e.prompt_tokens),n=sr(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:sr(r.cached_tokens)??0,cacheCreationInputTokens:sr(r.cache_creation_tokens)??sr(e.cache_creation_input_tokens)??0}}function Xc(e){if(!V(e))return null;let t=sr(e.input_tokens),n=sr(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:sr(r.cached_tokens)??0,cacheCreationInputTokens:0}}function Zc(e){let t=sr(e.input_tokens),n=sr(e.output_tokens);if(t===null&&n===null)return null;let r=sr(e.cache_read_input_tokens),i=sr(e.cache_creation_input_tokens);return{inputTokens:(t??0)+(r??0)+(i??0),outputTokens:n??0,cacheReadInputTokens:r??0,cacheCreationInputTokens:i??0}}function Qc(e){return V(e)?e.prompt_tokens!==void 0||e.completion_tokens!==void 0?Yc(e):e.input_tokens_details!==void 0||e.output_tokens_details!==void 0?Xc(e):Zc(e):null}var $c=ic();function el(e){let t=null;try{t=new URL(bc(e)).hostname}catch{t=null}return t===null||t===``?`drop`:t!==`openai.com`&&!t.endsWith(`.openai.com`)?`preserve`:`drop`}function tl(e,t,n){let r=t.rawPassthrough===!0,i=$c[e]({...r?{translate:!1}:{},...e===`anthropicToChatCompletions`?{topK:el(t)}:{}});if(i.intercept(zc(t,n)),i.intercept(Bc(t)),!r){e!==`anthropicToAnthropic`&&i.intercept(Hc(e,t));for(let n of Jc(e,t))i.intercept(n)}return i}async function nl(e,t,n,r,i){let a;try{a=tl(t,n,i.inboundHeaders)}catch(t){let n=br(t)??500;return{kind:`error`,status:n,response:_c(e,n,cr(t),i.requestId)}}let o=a.begin(),s=await o.request({body:r});if(s.kind===`error`)return{kind:`error`,status:s.status,response:_c(e,s.status,s.message,i.requestId)};let c=await new Tc({url:bc(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(!rl(c.transport))try{let e=await c.transport.text();l={...c.transport,stream:null,text:()=>Promise.resolve(e)}}catch(t){let n=br(t)??502;return{kind:`error`,status:n,response:_c(e,n,cr(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 Ec(l.stream),{kind:`error`,status:500,response:_c(e,500,cr(t),i.requestId)}}if(u.kind===`error`)return Ec(l.stream),{kind:`error`,status:u.status,response:_c(e,u.status,u.message,i.requestId)};let d=u.value;return`stream`in d?{kind:`ok`,sse:!0,stream:d.stream,collectUsage:()=>Qc(d.collectUsage())}:{kind:`ok`,sse:!1,body:d.body,usage:Qc(V(d.body)?d.body.usage:void 0)}}function rl(e){return(e.headers[`content-type`]??``).includes(`text/event-stream`)}function il(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 al(e,t){return il(e,t.provider,t.rawPassthrough===!0)!==null}function ol(e){return e===`anthropic`?`Anthropic Messages`:e===`openai-responses`?`OpenAI Responses`:`OpenAI Chat Completions`}async function sl(e,t,n){return ll(e,t,n,t.inbound_format===`anthropic`?`anthropic`:`openai`)}async function cl(e,t,n){return ll(e,t,n,`openai-responses`)}async function ll(e,t,n,r){try{return await ul(e,t,n,r)}catch(e){return fl(e,r,n.requestId)}}async function ul(e,t,n,r){let i=e.rawPassthrough===!0,a=il(r,e.provider,i);if(a===null){let t=e.name||e.modelName;return{kind:`error`,status:400,response:_c(r,400,i?`Model '${t}' has rawPassthrough enabled (upstream '${e.provider}'): ${ol(r)} inbound requests cannot be forwarded as-is. Use a matching protocol or turn rawPassthrough off.`:`Model '${t}' (upstream '${e.provider}') does not accept ${ol(r)} inbound requests`,n.requestId)}}let o=await nl(r,a,e,r===`anthropic`?dl(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 dl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function fl(e,t,n){let r=br(e)??500;return{kind:`error`,status:r,response:_c(t,r,cr(e),n)}}var pl=[`x-litellm-trace-id`,`x-litellm-session-id`],ml=new Set(pl),hl=/^x-.+-session-id$/,gl=/^x-.+-conversation-id$/,_l=[`thread-id`,`conversation_id`],vl=/^codex[-_ /]/i,yl=/^[a-zA-Z0-9_-]{8,}$/,bl=/^[a-zA-Z0-9_-]+$/,xl=`_session_`;function Sl(e){let t=new Map;e.forEach((e,n)=>t.set(n.toLowerCase(),e));for(let e of pl){let n=t.get(e);if(n!==void 0&&yl.test(n))return n}let n=ml;for(let[e,r]of t)if(!n.has(e)&&(hl.test(e)||gl.test(e))&&yl.test(r))return r;for(let e of[`x-session-id`,`x-conversation-id`]){let n=t.get(e);if(n!==void 0&&yl.test(n))return n}for(let e of[`session-id`,`session_id`]){let n=t.get(e);if(n!==void 0&&yl.test(n))return n}let r=t.get(`user-agent`);if(r!==void 0&&vl.test(r))for(let e of _l){let n=t.get(e);if(n!==void 0&&yl.test(n))return n}return``}function Cl(e){if(!V(e))return null;let t=e.metadata;return V(t)?Tl(t.user_id):null}function wl(e,t){if(!V(e))return null;let n=e[t];return typeof n==`string`&&bl.test(n)?n:null}function Tl(e){if(V(e))return wl(e,`session_id`);if(typeof e!=`string`)return null;if(e.startsWith(`{`))try{let t=wl(JSON.parse(e),`session_id`);if(t!==null)return t}catch{}let t=e.lastIndexOf(xl);return t===-1?null:wl({session_id:e.slice(t+9)},`session_id`)}var El=10485760;function Dl(e){try{return JSON.parse(e)}catch{return e}}function Ol(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}},Tr=new TextEncoder;function Er(e,t){let n=[];e!==null&&n.push(`event: ${e}`);for(let e of t.split(`
|
|
14
|
+
`))n.push(`data: ${e}`);return Tr.encode(`${n.join(`
|
|
15
|
+
`)}\n\n`)}function Dr(e,t={}){let n=e.type;return Er((t.protocol===void 0||t.protocol===`anthropic`)&&typeof n==`string`?n:null,JSON.stringify(e))}function Or(){return Er(null,Sr)}async function*kr(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 wr,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 Ar(e){let t;try{t=JSON.parse(e.data)}catch{return null}return typeof t!=`object`||!t||Array.isArray(t)?null:t}function jr(e,t){return Dr(e,{protocol:t})}function Mr(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 ir({...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 ir(o===null?{...a,body:null}:{...a,body:o})},i=(e,t,n,r)=>{let i=new wr,a=new TextDecoder,o=!1,s=(i,a)=>{if(t!==`anthropic`&&i.data===`[DONE]`){a.enqueue(Or());return}let s=Ar({event:i.event,data:i.data,done:!1});if(s===null){a.enqueue(Er(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 dr(t,{message:lr(e)}))a.enqueue(Dr(n,{protocol:t}));a.terminate();return}c!==null&&a.enqueue(Dr(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 cr(i)?i.then(a):a(i);function a(e){return e.kind===`error`?e:ir(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 cr(a)?a.then(e=>r(e,n,t.pair.inbound,t)):r(a,n,t.pair.inbound,t)})}return{requestLayers:a,responseLayers:o}}function Nr(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 ar(sr(e)??500,lr(e))}let i={"content-type":`application/json`},a=r.stream===!0;return n({headers:i,body:r,stream:a})};return new ur([...t.specs.flatMap(e=>Mr(e,t).requestLayers),n(t)]).run(e,e=>ir(e))}var Pr=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 kr(this.#e.upstreamBytes,this.#e.upstreamProtocol)){if(e.done){this.#i=!0;return}let t=Ar(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 dr(this.#e.inboundProtocol,{status:502,message:`upstream stream ended before the [DONE] sentinel (truncated)`}))yield jr(e,this.#e.inboundProtocol);return}fr(this.#e.inboundProtocol)&&(yield Or());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 jr(t,this.#e.inboundProtocol)}}catch(e){let t=lr(e);for(let n of dr(this.#e.inboundProtocol,{status:sr(e),message:t}))yield jr(n,this.#e.inboundProtocol)}finally{await this.#n.return?.().catch(()=>{})}}};async function Fr(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 ar(sr(e)??500,lr(e))}return n({status:r.status,headers:r.headers,body:i})},i;try{i=await e.text()}catch(e){return ar(502,`failed to read upstream response body: ${lr(e)}`)}let a;try{let e=JSON.parse(i);if(typeof e!=`object`||!e)return ar(502,`upstream response is not a valid JSON object`);a=e}catch{return ar(502,`upstream response is not valid JSON`)}return new ur([...t.specs.flatMap(e=>Mr(e,t).responseLayers),r(t)]).run({status:e.status,headers:n,body:a},e=>ir(e))},i=(e,t,n)=>{let r=e=>(t,n)=>{let r=t,i=new Pr({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?ar(502,`streaming response has no body`):new ur([...t.specs.flatMap(e=>Mr(e,t).responseLayers),r(t)]).run({status:e.status,headers:n,body:e.body},e=>ir(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 Ir=[],Lr=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=Ir;#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 ar(500,`RequestContext: request() can only be called once (one container per round trip)`);this.#r=!0,this.#e=e,this.#t=Rr(this.#a,e,this);let t=Nr(e,this);return cr(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(ar(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 Fr(e,this)}};function Rr(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 zr=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]}},Br=class{#e;#t;#n;#r=new zr;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 Lr({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 Vr(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function Hr(e){return typeof e!=`number`||!Number.isFinite(e)?0:Math.max(0,Math.trunc(e))}function Ur(){return crypto.randomUUID()}function Wr(){return Math.floor(Date.now()/1e3)}function Gr(...e){for(let t of e){let e=Hr(t);if(e>0)return e}return 0}function Kr(e){let t=V(e.prompt_tokens_details);return{cacheRead:Gr(e.cache_read_input_tokens,e.prompt_cache_hit_tokens,t.cached_tokens),cacheCreation:Gr(e.cache_creation_input_tokens,t.cache_creation_tokens,t.cache_write_tokens)}}function qr(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 Jr=new Set([`end_turn`,`max_tokens`,`stop_sequence`,`tool_use`,`refusal`]),Yr=new Set([`stop`,`length`,`tool_calls`,`function_call`,`content_filter`]);function Xr(e){return{stop:`end_turn`,length:`max_tokens`,tool_calls:`tool_use`}[e]??`end_turn`}function Zr(e){let t=U(e)??``;return Jr.has(t)?t:Xr(t)}function Qr(e){let t=U(e.stop_reason),n=U(V(e.provider_specific_fields).stop_reason),r=t??n;return r===null||r===``||Jr.has(r)||Yr.has(r)?null:r}function $r(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 ei={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 ti(e){return ei[e]??`api_error`}function ni(e){let t=B(e)?e.code:void 0;return typeof t==`number`&&Number.isInteger(t)&&t>=400&&t<600?t:500}function ri(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 ii(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 ai(e,t){return ri(t)?t:{type:`error`,error:{type:ti(e),message:ii(e,t)}}}function oi(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 si(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 ci=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 or(si(t),{status:ni(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:Ur(),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=$r(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=Hr(c.prompt_tokens),u=Hr(c.completion_tokens);if(l>0){this.#i=l;let e=Kr(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=Qr(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`:Zr(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:qr(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*li(e){let t=new ci;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 ui=4096;function di(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 fi(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 pi(e){if(!B(e.metadata))return;let t=V(e.metadata).user_id;t==null?delete e.metadata:e.metadata={user_id:t}}function mi(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 or(`Invalid effort value: ${JSON.stringify(n)}. Must be one of: 'high', 'medium', 'low', 'xhigh', 'max'`,{status:400})}function hi(e){let t=V(e),n=di(H(t.messages)),r=H(t.tools).map(V),i=fi(n,r),a={...t,messages:n};return i!==r&&(a.tools=i),`max_tokens`in a||(a.max_tokens=ui),pi(a),delete a.is_vertex_request,delete a.client_metadata,mi(a),a}function gi(e){return typeof e==`number`&&Number.isFinite(e)?Math.floor(e):0}function _i(e){let t=gi(e.input_tokens??0),n=gi(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+gi(t.input_tokens??0),0),n=o.reduce((e,t)=>e+gi(t.output_tokens??0),0),r=o.reduce((e,t)=>e+gi(t.cache_creation_input_tokens??0),0),i=o.reduce((e,t)=>e+gi(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 vi=/^<(?:think|thinking|budget:thinking)>([\s\S]*?)<\/(?:think|thinking|budget:thinking)>([\s\S]*)/;function yi(e){if(!e)return{reasoningContent:null,content:e};let t=vi.exec(e);return t===null?{reasoningContent:null,content:e}:{reasoningContent:t[1]??null,content:t[2]??null}}function bi(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`?yi(t):{reasoningContent:null,content:n}}function xi(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 Si(e){return e.type===`custom`||e.custom!=null}function Ci(e){return Si(e)?Object.fromEntries(Object.entries(e).filter(([e,t])=>e!==`function`&&e!==`type`||t!=null)):{id:e.id==null?Ur():String(e.id),type:e.type==null?`function`:String(e.type),function:xi(e.function)}}function wi(e){let t=new Map;for(let[n,r]of e.entries()){if(Si(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 Ti(e){try{let t=wi(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 Ei(e){return Array.isArray(e.tool_calls)?Ti(e.tool_calls.map(e=>Ci(V(e)))):[]}function Di(e){if(typeof e!=`string`||e===``)return{};try{return V(JSON.parse(e))}catch{return{}}}function Oi(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:Di(r.arguments)})}return t}function ki(e){let{cacheRead:t,cacheCreation:n}=Kr(e);return qr(Hr(e.prompt_tokens),Hr(e.completion_tokens),t,n)}function Ai(e){let t=V(e),n=t.error;if(n!=null){let e=V(n);throw new or(typeof e.message==`string`?e.message:JSON.stringify(n),{status:ni(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=Ei(a),{reasoningContent:s,content:c}=bi(a),l=H(a.thinking_blocks),u=$r(a),d=U(i.finish_reason)??`stop`;d===`stop`&&o.length>0&&(d=`tool_calls`);let f=Qr(i),p=f===null?Zr(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:Oi({thinkingBlocks:l,reasoningContent:s,content:c,refusal:u,toolCalls:o}),stop_reason:p,...m?{stop_details:{type:`refusal`}}:{},stop_sequence:f,usage:ki(V(t.usage))}}function ji(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=>ji(e)).join(`, `)}]`:B(e)?`{${Object.entries(e).map(([e,t])=>`'${e}': ${ji(t)}`).join(`, `)}}`:String(e)}function Mi(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 Ni(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 Pi(e,t){let n=Ni(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 Fi(e){let t=V(e);if(`error`in t&&t.error!==null&&t.error!==void 0)throw new or(ji(t.error));let n=Mi(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(Ai({id:Ur(),object:`chat.completion`,...t.model===void 0?{}:{model:t.model},choices:[{index:0,finish_reason:U(t.stop_reason),message:r}],usage:_i(V(t.usage))}));return Pi(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 Ii=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=_i(this.#e(e.usage)));else if(t===`message_start`){let t=V(e.message);c=U(t.model),`usage`in t&&(a=_i(this.#e(t.usage)))}else if(t===`error`){let t=V(e.error);throw new or(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}},Li=class{inbound=`anthropic`;upstream=`anthropic`;translateRequest(e){return hi(e)}translateResponse(e){return Fi(e)}async*bridgeFrames(e){let t=new Ii,n=new ci;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 oi(e)}errorEnvelope(e,t){return ai(e,t)}},Ri=`Operator note (not from the user): the following was originally a mid-conversation system-role reminder.`;function zi(e){let t=e.role;return t===`system`?`system`:t===`tool`||t===`function`?`tool`:t===`user`?`user`:`other`}function Bi(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 Vi(e){return{role:`user`,content:[{type:`text`,text:Ri},...Bi(e)]}}function Hi(e){return e.filter(e=>Bi(e).length>0).map(Vi)}function Ui(e){let t=[],n=null,r=[];for(let i of e){let e=zi(i);e!==n&&(r.length>0&&t.push(r),r=[],n=e),r.push(i)}return r.length>0&&t.push(r),t}function Wi(e){let t=Ui(e),n=[];for(let e=0;e<t.length;e++){let r=t[e]??[],i=zi(r[0]??{}),a=t[e+1],o=a===void 0?null:zi(a[0]??{});if(i===`system`){o!==`tool`&&n.push(...Hi(r));continue}let s=e>0?t[e-1]:void 0;if(i===`tool`&&s!==void 0&&zi(s[0]??{})===`system`){n.push(...r,...Hi(s));continue}n.push(...r)}return n}function Gi(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),...Wi(e.slice(t))]}var Ki=new Set([`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`not`,`propertyNames`,`then`,`unevaluatedItems`,`unevaluatedProperties`]),qi=new Set([`allOf`,`anyOf`,`items`,`oneOf`,`prefixItems`]),Ji=new Set([`$defs`,`definitions`,`dependentSchemas`,`patternProperties`,`properties`]),Yi=1024;function Xi(e){if(e.includes(`\\p{`)||e.includes(`\\p<`))return!1;try{new RegExp(e)}catch{return!1}return!0}function Zi(e,t){let n={},r=!1;for(let[i,a]of Object.entries(e)){if(i===`pattern`&&typeof a==`string`&&!Xi(a)){r=!0;continue}let e=Qi(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 Qi(e,t,n){if(qi.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(Ji.has(e)){let r={},i=!1;for(let[a,o]of Object.entries(t)){if(e===`patternProperties`&&typeof a==`string`&&!Xi(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 Ki.has(e)?n.get(t)??t:t}function $i(e,t){for(let[n,r]of Object.entries(e))if(Ji.has(n)&&B(r))for(let e of Object.values(r))B(e)&&t.push(e);else if(qi.has(n)&&Array.isArray(r))for(let e of r)B(e)&&t.push(e);else Ki.has(n)&&B(r)&&t.push(r)}function ea(e){let t=new Map,n=[],r=[e];for(;r.length>0&&n.length<Yi;){n.push(r);let e=[];for(let t of r)$i(t,e);r=e}for(let e of n.reverse())for(let n of e){let e=Zi(n,t);e!==n&&t.set(n,e)}return t.get(e)??e}function ta(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 na(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 ra(e){let t=na(e,!0);return t===null?[]:[{role:`system`,content:t}]}function ia(e){return e.flatMap(e=>{let t=V(e),n=t.content;if(t.role===`system`){let e=na(n,!1);return e===null?[]:[{role:`system`,content:e}]}return t.role===`user`?aa(n):t.role===`assistant`?la(n):[]})}function aa(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=sa(e.source);n!==null&&t.push({type:`image_url`,image_url:{url:n}})}else e.type===`tool_result`&&n.push({role:`tool`,content:oa(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 oa(e){return typeof e==`string`?e:H(e).map(e=>U(V(e).text)??``).join(``)}function sa(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 ca(e){return e.map(e=>e.type===`thinking`?U(e.thinking)??``:``).filter(e=>e!==``).join(`
|
|
16
|
+
`)}function la(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=ca(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 ua=64;function da(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,ua);return r===``?null:r}function fa(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=da(V(e.metadata).user_id);i(`prompt_cache_key`,l,l!==null);let u=pa(e.tool_choice);i(`tool_choice`,u,u!==null);let d=e.tools;i(`tools`,H(d).map(ma),H(d).length>0);let f=ha(e.thinking,e.output_config);return i(`reasoning_effort`,f,f!==null),r}function pa(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 ma(e){let t=V(e),n=t.input_schema,r=ta(n);if(r===null&&n!=null)throw new or(`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:ea(r!==null&&Object.keys(r).length>0?r:{type:`object`,properties:{}})}}}function ha(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 ga(e,t){let n=V(e),r=Gi([...ra(n.system),...ia(H(n.messages))]),i=fa(n,t);if(i.messages=r,i.reasoning_effort===`none`){let e={...i};delete e.reasoning_effort,i=e}return i}var _a=class{inbound=`anthropic`;upstream=`openai`;translateRequest(e,t){return ga(e,t)}translateResponse(e){return Ai(e)}bridgeFrames(e){return li(e)}usageFromFrame(e){return oi(e)}errorEnvelope(e,t){return ai(e,t)}},va={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`};function ya(e){let t=va[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t}function ba(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 xa(e,t){return B(t)&&B(t.error)?t:{error:{message:ba(e,t),type:ya(e),param:null,code:String(e)}}}function Sa(){return`chatcmpl-${Ur()}`}var Ca={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 wa(e){return Ca[U(e)??``]??`stop`}function Ta(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 Ea(e,t={}){let n=Hr(e.input_tokens),r=Hr(e.output_tokens),i=Hr(e.cache_creation_input_tokens),a=Hr(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]=Hr(r))}s.cache_creation_token_details=n}let c={completion_tokens:r,prompt_tokens:o,total_tokens:o+r,completion_tokens_details:Ta(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 Da(e,t){return{...e??{},...t}}function Oa(e){return/claude-[a-z]+-(?:4[-._](?:[6-9]|[1-9]\d)(?!\d)|[5-9](?!\d)(?:[-._]\d{1,2}(?!\d))?)/.test(e)}function ka(e){return/claude-[a-z]+-4[-._]6(?!\d)/.test(e)}function Aa(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 ja(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 Ma(e,t){if(B(t)){let e=t.error;if(B(e)&&t.type!==`error`&&typeof e.message==`string`)return t}return{error:{message:ja(e,t),type:ya(e),param:null,code:String(e)}}}var Na={low:1024,medium:2048,high:4096,xhigh:8192,max:16384,minimal:1024},Pa={low:`low`,minimal:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:`max`},Fa=4096,Ia=1024,La=`[System: Empty message content sanitised to satisfy protocol]`,Ra=new Set([`type`,`properties`,`additionalProperties`,`required`,`$defs`,`strict`]);function za(e,t){if(e==null)return{type:`object`,properties:{}};if(!B(e))throw new or(`Invalid input_schema for tool "${t}": expected an object, got ${typeof e}`,{status:400});let n={};for(let[t,r]of Object.entries(e))Ra.has(t)&&(n[t]=r);return n.type!==`object`&&(n.type=`object`),n.properties===void 0&&(n.properties={}),n}function Ba(e){let t=V(e),n=V(t.function),r=t.type;if(r!==`function`&&r!==`custom`)throw new or(`Unsupported tool type: ${String(r)}`,{status:400});let i=U(n.name)??``,a={name:i,input_schema:za(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 Va(e){return e.map(e=>{let t=V(e);return t.input_schema===void 0?Ba(e):t})}var Ha={name:`dummy_tool`,input_schema:{type:`object`,properties:{}},type:`custom`,description:`This is a dummy tool call`};function Ua(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`)||`tool_use_id`}function Wa(e,t){if(typeof e!=`string`||e.trim()===``)return{};try{return JSON.parse(e)}catch(e){throw new or(`Failed to parse tool call arguments for tool '${t}': ${e instanceof Error?e.message:String(e)}`,{status:400})}}function Ga(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 Ka(e){let t=e.cache_control;return B(t)?t:void 0}function qa(e,t){return e===``?null:t===void 0?{type:`text`,text:e}:{type:`text`,text:e,cache_control:t}}function Ja(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 or(`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 Ya(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=Ja(t.image_url),r=Ka(t);r!==void 0&&(n.cache_control=r),e.push(n)}}n=e}let r={type:`tool_result`,tool_use_id:Ua(U(e.tool_call_id)??Ur()),content:n},i=Ka(e);return i!==void 0&&(r.cache_control=i),r}function Xa(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:La}: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:La})});return r?{...e,content:i}:e}function Za(e){let t=[];for(let n of e){let e=n.role;if(e===`tool`||e===`function`){t.push(Ya(n));continue}let r=n.content;if(typeof r==`string`){let e=qa(r,void 0);e!==null&&t.push(e);continue}for(let e of H(r)){let n=V(e),r=Ka(n);if(n.type===`text`){let e=qa(U(n.text)??``,r);e!==null&&t.push(e)}else if(n.type===`image_url`){let e=Ja(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 Qa(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)Ga(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!==``&&!Ga(n)&&t.push(n)}else if(r===`text`){let e=qa(U(n.text)??``,Ka(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=qa(e,Ka(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=Ua(U(r.id)??Ur());if(n.has(o))continue;n.add(o);let s={type:`tool_use`,id:o,name:a,input:Wa(i.arguments,a)},c=Ka(r);c!==void 0&&(s.cache_control=c),t.push(s)}}return t.length>0?{role:`assistant`,content:t}:null}function $a(e){let t=e.map(e=>Xa(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=Za(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=Qa(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 eo(e){let t=[];for(let n of e){let e=n.content;if(typeof e==`string`){let r=qa(e,Ka(n));r!==null&&t.push(r);continue}for(let n of H(e)){let e=V(n);if(e.type!==`text`)continue;let r=qa(U(e.text)??``,Ka(e));r!==null&&t.push(r)}}return t}var to=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,no=/^\+?[\d\s()-]{7,}$/;function ro(e){return!to.test(e)&&!no.test(e)}function io(e){return typeof e!=`number`||!Number.isFinite(e)?null:Number.isInteger(e)?e:Math.max(1,Math.round(e))}function ao(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 oo(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 so(e,t){let n=Oa(e)&&!ka(e);return t>=8192&&n?`xhigh`:t>=4096?`high`:t>=2048?`medium`:`low`}function co(e,t){if(!Oa(e)||ka(e))return;let n=V(t.thinking);if(n.type!==`enabled`)return;let r=n.budget_tokens,i=so(e,typeof r==`number`?r:0);t.thinking={type:`adaptive`};let a=t.output_config;t.output_config={effort:i,...B(a)?a:{}}}function lo(e,t){let n=e.budget_tokens;return typeof t!=`number`||typeof n!=`number`?e:t<=Ia?null:n<t?e:{type:e.type??`enabled`,budget_tokens:t-1}}function uo(e,t){if(Oa(t))return{type:`adaptive`,display:`summarized`};let n=Na[e];if(n===void 0)throw new or(`Unmapped reasoning effort: '${e}'. Must be one of: 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'none'.`,{status:400});return{type:`enabled`,budget_tokens:n}}function fo(e,t,n,r){if(V(n).type===`adaptive`&&!Oa(r)){let n=e.max_completion_tokens??e.max_tokens,r=lo({type:`enabled`,budget_tokens:Na.medium??2048},n);r!==null&&(t.thinking=r);return}t.thinking=n,co(r,t)}function po(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=uo(r,n),Oa(n)){let t=Pa[r];if(t===void 0)throw new or(`Invalid reasoning_effort: '${r}'. Must be one of: 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'none'`,{status:400});e.output_config={effort:t}}}}var mo=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 ho(e,t){let n=U(e.model)??``,r={};for(let[t,i]of Object.entries(e)){if(!mo.has(t)){r[t]=i;continue}switch(t){case`model`:r.model=i;break;case`max_tokens`:case`max_completion_tokens`:{let e=io(i);e!==null&&(r.max_tokens=e);break}case`tools`:H(i).length>0&&(r.tools=Va(H(i)));break;case`tool_choice`:case`parallel_tool_calls`:{let t=oo(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=ao(i);e!==null&&(r.stop_sequences=e);break}case`temperature`:case`top_p`:(Aa(n)||t===`temperature`&&i===1)&&(r[t]=i);break;case`top_k`:Aa(n)&&(r.top_k=i);break;case`thinking`:fo(e,r,i,n);break;case`reasoning_effort`:po(r,i,n);break;case`user`:{let e=U(i);e!==null&&ro(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&&go(e)&&(r.tools=[Ha]),r}function go(e){return H(e.messages).some(e=>`tool_calls`in V(e))}function _o(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=ho(t,$a(Gi(n.slice(r).map(e=>V(e))))),o=eo(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+Fa:Fa}return a}function vo(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 yo(e){let t=V(e),n=t.error;if(n!=null)throw new or(U(V(n).message)??JSON.stringify(n)??String(n),{status:ni(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:Sa(),created:Wr(),...t.model===void 0?{}:{model:t.model},object:`chat.completion`,choices:[{finish_reason:wa(t.stop_reason),index:0,message:vo(H(r))}],usage:Ea(V(t.usage))}}var bo=class{#e;#t;#n=null;#r=null;#i=!1;#a=!1;#o=!1;#s=!1;#c=null;#l=-1;#u=``;#d=``;constructor(){this.#e=Sa(),this.#t=Wr()}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 or(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:Ea(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=Da(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=Da(this.#r,t));let n=wa(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*xo(e){let t=new bo;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 So=class{inbound=`openai`;upstream=`anthropic`;translateRequest(e){return _o(e)}translateResponse(e){return yo(e)}bridgeFrames(e){return xo(e)}usageFromFrame(e){let t=e.usage;return B(t)?t:null}errorEnvelope(e,t){return Ma(e,t)}},Co=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 xa(e,t)}};function wo(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 To=new Set([`text`,`image_url`,`input_audio`,`audio_url`,`document`,`guarded_text`,`grounding_source`,`query`,`video_url`,`file`,`thinking`,`redacted_thinking`]),Eo=new Set([`encrypted_content`,`redacted_thinking`]),Do=new Set;function Oo(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:ko(W(t.type)),text:n};return`cache_control`in t&&(r.cache_control=t.cache_control),[r]})}function ko(e){if(e.startsWith(`input_`)){let t=e.slice(6);return t===`audio`?`input_audio`:To.has(t)?t:`text`}return e===`tool_result`||e===`output_text`?`text`:To.has(e)?e:`text`}function Ao(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 jo(e){let t=W(e.call_id);return t===``?[]:[{role:`tool`,content:Mo(e.output),tool_call_id:t}]}function Mo(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 No(e){return[`function_call_output`,`custom_tool_call_output`,`web_search_call`,`computer_call_output`,`tool_result`].includes(W(e.type))}function Po(e){return W(e.type)===`function_call`||W(e.type)===`custom_tool_call`}function Fo(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(Po(e)){let t=Ao(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(No(e)){n.push(...jo(e));continue}if(e.type===`reasoning`){n.push(...Uo(e));continue}let r=e.content;if(r==null)continue;let i=Lo(e),a=i,o=Oo(r),s=n[n.length-1];i===`assistant`&&s?.role===`assistant`&&Array.isArray(s.tool_calls)?n[n.length-1]={...s,content:Io(s.content,o)}:n.push({role:a,content:o})}return qo(n)}function Io(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 Lo(e){return W(e.role)===``?`user`:W(e.role)}function Ro(e){return Bo(e.content)??Vo(e.summary)}function zo(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 Bo(e){return typeof e==`string`&&e.trim()!==``?e:Array.isArray(e)?zo(e,Eo):null}function Vo(e){return Array.isArray(e)?zo(e,Do):null}function Ho(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 Uo(e){let t=Ro(e),n=Ho(e);return t===null&&n===null?[]:[{role:`assistant`,content:null,...t===null?{}:{reasoning_content:t},...n===null?{}:{thinking_blocks:n}}]}function Wo(e){return typeof e==`string`&&e!==``}function Go(e){return e.role===`assistant`&&e.content===null&&H(e.tool_calls).length===0&&(Wo(e.reasoning_content)||H(e.thinking_blocks).length>0)}function Ko(e,t){let n=t.map(e=>e.reasoning_content).filter(Wo),r=e.reasoning_content,i=n.length>0?[...n,...Wo(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 qo(e){let t=[],n=[];for(let r of e){if(Go(r)){n.push(r);continue}if(n.length>0){if(r.role===`assistant`){t.push(Ko(r,n)),n=[];continue}t.push(...n),n=[]}t.push(r)}return t.push(...n),t}function Jo(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 Yo(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=ta(n);if(r===null&&n!=null)throw new or(`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:ea(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 Xo(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 Zo(e){let t=e,{tools:n,webSearchOptions:r}=Yo(t.tools??[]),i=Xo(t.text),a=V(t.reasoning).effort,o=typeof a==`string`?a:null,s={messages:Fo(t.input,t.instructions),model:t.model??null,tool_choice:Jo(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 Qo={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 $o(e,t=()=>{}){let n=Qo[e];return n===void 0?(t(e),`stop`):n}function es(e){let t=V(e.message),n=Array.isArray(t.tool_calls)?t.tool_calls.map(e=>Ci(V(e))):null;n!==null&&(n=Ti(n));let{reasoningContent:r,content:i}=bi(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:$o(o),message:a}}function ts(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 ns(e){let t=e.error;if(t!=null){let e=V(t);throw new or(typeof e.message==`string`?e.message:JSON.stringify(t),{status:ni(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=>es(V(e)))};return e.usage!=null&&(r.usage=ts(e.usage)),r}function rs(e){return e===`length`||e===`max_tokens`||e===`content_filter`?`incomplete`:`completed`}function is(e){return e===`content_filter`?`content_filter`:`max_output_tokens`}function as(e){return typeof e==`string`?e:H(e).map(e=>typeof e==`string`?e:U(V(e).text)??``).join(``)}function os(e){if(!B(e))return null;let t=Vr(e.prompt_tokens)??0,n=Vr(e.completion_tokens)??0,r=Vr(e.total_tokens)??t+n,i=V(e.prompt_tokens_details),a={},o=Vr(i.cached_tokens);o!==null&&(a.cached_tokens=o);let s=Vr(i.text_tokens);s!==null&&(a.text_tokens=s);let c=V(e.completion_tokens_details),l={},u=Vr(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 ss(e,t){let n=V(e.function);return{type:`function_call`,id:t,call_id:U(e.id)??`call_${Ur()}`,name:U(n.name)??``,arguments:U(n.arguments)??``,status:`completed`,namespace:null}}function cs(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:is(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 ls(e,t){let n=V(H(e.choices)[0]),r=V(n.message),i=U(n.finish_reason),a=as(r.content),o=H(r.tool_calls),s=U(r.reasoning_content),c=[];s!==null&&s!==``&&c.push({type:`reasoning`,id:`rs_${Ur()}`,status:rs(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_${Ur()}`,status:rs(i),role:`assistant`,content:[{type:`output_text`,text:a,annotations:[]}],phase:null});for(let e of o)c.push(ss(V(e),`fc_${Ur()}`));return cs(t,rs(i),c,os(e.usage),i)}function us(e){let t=V(e),n=U(t.model);return ls(ns(t),{id:`resp_${Ur()}`,created:Wr(),...n===null?{}:{model:n}})}function ds(e){let t=e.error;if(t)throw new or(typeof t!=`object`||!t||Array.isArray(t)?String(t):typeof V(t).message==`string`?V(t).message:JSON.stringify(t),{status:ni(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?$o(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 fs=10;function ps(e){let t={};for(let[n,r]of Object.entries(e))r!==null&&(t[n]=r);return t}function ms(e){if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var hs=class{#e=0;#t=!1;#n=!1;#r=`msg_${Ur()}`;#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=cs(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=rs(this.#c);return e.push(this.#S({type:`response.completed`,response:cs(this.#m(),t,this.#x(),os(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_${Ur()}`),this.#d+=e,[this.#S({type:`response.reasoning_summary_text.delta`,item_id:this.#u,output_index:0,delta:e})]}#_(e){let t=Vr(e.index)??0,n=V(e.function),r=this.#s.get(t),i=[];if(r===void 0){let a=U(e.id)??`call_${Ur()}`;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=ms(n.arguments);if(o!==``){r.args+=o;for(let e=0;e<o.length;e+=fs)i.push(this.#S({type:`response.function_call_arguments.delta`,item_id:r.itemId,output_index:r.outputIndex,delta:o.slice(e,e+fs)}))}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:rs(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=ps(e.response)),t}},gs=class{inbound=`openai-responses`;upstream=`openai`;translateRequest(e){return Zo(e)}translateResponse(e){return us(e)}async*bridgeFrames(e,t,n){let r=new hs({id:`resp_${Ur()}`,created:Wr(),...B(n)?{requestEcho:n}:{}});for await(let t of e)for(let e of r.translateFrame(ds(t)))yield e;for(let e of r.flush())yield e}usageFromFrame(e){return wo(e)}errorEnvelope(e,t){return xa(e,t)}};function _s(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 vs(e){let t=e;return{...t,input:_s(t.input)}}var ys=[`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`],bs=[`input_tokens_details`,`output_tokens_details`,`cost`],xs={audio_tokens:null,cached_tokens:0,cached_tokens_details:null,image_tokens:null,text_tokens:null,video_tokens:null},Ss={audio_tokens:null,reasoning_tokens:null,text_tokens:null};function Cs(e,t){let n={...e};for(let[e,r]of Object.entries(t))e in n||(n[e]=r);return n}function ws(e){let t=e.usage;if(!B(t))return;let n={...t};for(let e of bs)e in n||(n[e]=null);let r=n.input_tokens_details;B(r)&&(n.input_tokens_details=Cs(r,xs));let i=n.output_tokens_details;B(i)&&(n.output_tokens_details=Cs(i,Ss)),e.usage=n}function Ts(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 Es(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 Ds(e){for(let t of ys)t in e||(e[t]=null);return Ts(e),Es(e),ws(e),e}function Os(e){return Ds({...e})}function ks(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 As(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 js(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(As);e.some((e,t)=>e!==i[t])&&(n.tools=e,r=!0)}return r?{...e,response:n}:e}var Ms=class{inbound=`openai-responses`;upstream=`openai-responses`;translateRequest(e){return vs(e)}translateResponse(e){return Os(e)}async*bridgeFrames(e){for await(let t of e){let e=t;yield js(ks(e)??e)}}usageFromFrame(e){return wo(e)}errorEnvelope(e,t){return xa(e,t)}},Ns={anthropicToAnthropic:new Li,anthropicToChatCompletions:new _a,chatCompletionsToAnthropic:new So,chatCompletionsToChatCompletions:new Co,responsesToResponses:new Ms,responsesToChatCompletions:new gs},Ps=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 Br(Ns[e],t??{},e)}};function Fs(){return new Ps}var Is={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`},Ls={401:`authentication_error`,403:`permission_error`,429:`rate_limit_error`},Rs=new Set([204,205,304]);function zs(e){let t;try{t=JSON.parse(e)}catch{return null}return z(t)?t:null}function Bs(e){let t=e.type===`error`?e.error:void 0;return z(t)&&typeof t.type==`string`&&typeof t.message==`string`}function Vs(e){let t=zs(e);if(t===null)return e;if(Bs(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 Hs(e,t,n){let r=t===``||Rs.has(e)?null:t;return new Response(r,{status:e,headers:{"content-type":n}})}function Us(e,t,n){let r=e=>Is[e]??`api_error`,i=zs(t),a;if(i!==null&&Bs(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:Vs(t)}};n!==void 0&&(i.request_id=n),a=i}return Hs(e,JSON.stringify(a),`application/json`)}function Ws(e,t){let n={error:{message:Vs(t),type:(e=>{let t=Ls[e];return t===void 0?e<500?`invalid_request_error`:`internal_server_error`:t})(e),param:null,code:String(e)}};return Hs(e,JSON.stringify(n),`application/json`)}function Gs(e,t,n,r){return e===`anthropic`?Us(t,n,r):Ws(t,n)}function Ks(e,t,n,r){return e===`anthropic`?Us(t,n,r):Ws(t,n)}var qs={openai:`chat/completions`,anthropic:`messages`,"openai-responses":`responses`},Js={openai:`https://api.openai.com`,anthropic:`https://api.anthropic.com`,"openai-responses":`https://api.openai.com`};function Ys(e){let t=e.provider,n=(e.apiBase??Js[t]).replace(/\/+$/,``),r=qs[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 Xs=6e5,Zs=12e4,Qs=65536,$s=4096,ec=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??Xs,this.#a=t.timeouts?.idleMs??Zs;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,Qn(e))}let t=e.body;if(t===null?this.#l():(this.#u(this.#a),t=this.#p(t)),!e.ok){let n=await nc(t,Qs),r=n.length<=$s?n:n.slice(0,$s);return{kind:`error`,status:e.status,response:Gs(this.#t,e.status,r,this.#n)}}return{kind:`ok`,transport:{status:e.status,headers:$n(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 or(`upstream timeout: no data for ${String(this.#a)}ms`,{status:504})}#f(e,t){return{kind:`error`,status:e,response:Ks(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 tc(e){e!==null&&e.cancel().catch(()=>{})}async function nc(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 rc=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`]),ic=`sk-ant-oat`,ac=`oauth-2025-04-20`,oc="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 sc(e){let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase();rc.has(e)||e.startsWith(`proxy-`)||e.startsWith(`x-forwarded-`)||(t[n]=r)}return t}function cc(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 ${ic}`)){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`],ac),n[`anthropic-dangerous-direct-browser-access`]=`true`}if(i===void 0)throw new or(oc,{status:401});let s=i.startsWith(ic),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={...sc(n),...t.headers??{}};return e===`anthropic`?i(o,t.apiKey):a(o,t.apiKey)}var lc=/<invoke\s+name=/g,uc=2;function dc(e,t){let n=cc(e.provider,e,t??{});return{upstreamRequest:e=>({...e,headers:n})}}function fc(e){return{clientRequest:t=>z(t.body)?{...t,body:{...t.body,model:e.modelName}}:t}}function pc(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 mc(e){let t=(e,t)=>{let n=qn.indexOf(e),r=qn.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 hc(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,lc.lastIndex=0;for(let e=lc.exec(o);e!==null;e=lc.exec(o))n+=1;if(t>e&&n>=uc)throw new or(`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 gc(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(mc(t.maxReasoningEffort));let a=t.thinkingGuardMaxChars??0;return(e===`anthropicToAnthropic`||e===`anthropicToChatCompletions`)&&a>0&&i.push(hc(a)),i}function _c(e){if(!z(e))return null;let t=Zn(e.prompt_tokens),n=Zn(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:Zn(r.cached_tokens)??0,cacheCreationInputTokens:Zn(r.cache_creation_tokens)??Zn(e.cache_creation_input_tokens)??0}}function vc(e){if(!z(e))return null;let t=Zn(e.input_tokens),n=Zn(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:Zn(r.cached_tokens)??0,cacheCreationInputTokens:0}}function yc(e){return z(e)?e.prompt_tokens!==void 0||e.completion_tokens!==void 0?_c(e):e.input_tokens_details!==void 0||e.output_tokens_details!==void 0?vc(e):(e=>{let t=Zn(e.input_tokens),n=Zn(e.output_tokens);if(t===null&&n===null)return null;let r=Zn(e.cache_read_input_tokens),i=Zn(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 bc=Fs();async function xc(e,t,n,r,i){let a=(e,t,n)=>{let r=e=>{let t=null;try{t=new URL(Ys(e)).hostname}catch{t=null}return t===null||t===``?`drop`:t!==`openai.com`&&!t.endsWith(`.openai.com`)?`preserve`:`drop`},i=t.rawPassthrough===!0,a=bc[e]({...i?{translate:!1}:{},...e===`anthropicToChatCompletions`?{topK:r(t)}:{}});if(a.intercept(dc(t,n)),a.intercept(fc(t)),!i){e!==`anthropicToAnthropic`&&a.intercept(pc(e,t));for(let n of gc(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=sr(t)??500;return{kind:`error`,status:n,response:Ks(e,n,Qn(t),i.requestId)}}let c=s.begin(),l=await c.request({body:r});if(l.kind===`error`)return{kind:`error`,status:l.status,response:Ks(e,l.status,l.message,i.requestId)};let u=await new ec({url:Ys(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=sr(t)??502;return{kind:`error`,status:n,response:Ks(e,n,Qn(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 tc(d.stream),{kind:`error`,status:500,response:Ks(e,500,Qn(t),i.requestId)}}if(f.kind===`error`)return tc(d.stream),{kind:`error`,status:f.status,response:Ks(e,f.status,f.message,i.requestId)};let p=f.value;return`stream`in p?{kind:`ok`,sse:!0,stream:p.stream,collectUsage:()=>yc(p.collectUsage())}:{kind:`ok`,sse:!1,body:p.body,usage:yc(z(p.body)?p.body.usage:void 0)}}function Sc(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 Cc(e,t){return Sc(e,t.provider,t.rawPassthrough===!0)!==null}async function wc(e,t,n){return Ec(e,t,n,t.inbound_format===`anthropic`?`anthropic`:`openai`)}async function Tc(e,t,n){return Ec(e,t,n,`openai-responses`)}async function Ec(e,t,n,r){let i=(e,t,n)=>{let r=sr(e)??500;return{kind:`error`,status:r,response:Ks(t,r,Qn(e),n)}};try{return await Dc(e,t,n,r)}catch(e){return i(e,r,n.requestId)}}async function Dc(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=Sc(r,e.provider,o);if(s===null){let t=e.name||e.modelName;return{kind:`error`,status:400,response:Ks(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 xc(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 Oc=[`x-litellm-trace-id`,`x-litellm-session-id`],kc=new Set(Oc),Ac=/^x-.+-session-id$/,jc=/^x-.+-conversation-id$/,Mc=[`thread-id`,`conversation_id`],Nc=/^codex[-_ /]/i,Pc=/^[a-zA-Z0-9_-]{8,}$/,Fc=/^[a-zA-Z0-9_-]+$/,Ic=`_session_`;function Lc(e){let t=new Map;e.forEach((e,n)=>t.set(n.toLowerCase(),e));for(let e of Oc){let n=t.get(e);if(n!==void 0&&Pc.test(n))return n}let n=kc;for(let[e,r]of t)if(!n.has(e)&&(Ac.test(e)||jc.test(e))&&Pc.test(r))return r;for(let e of[`x-session-id`,`x-conversation-id`]){let n=t.get(e);if(n!==void 0&&Pc.test(n))return n}for(let e of[`session-id`,`session_id`]){let n=t.get(e);if(n!==void 0&&Pc.test(n))return n}let r=t.get(`user-agent`);if(r!==void 0&&Nc.test(r))for(let e of Mc){let n=t.get(e);if(n!==void 0&&Pc.test(n))return n}return``}function Rc(e){let t=e=>{let t=(e,t)=>{if(!z(e))return null;let n=e[t];return typeof n==`string`&&Fc.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(Ic);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 zc=10485760;function Bc(e){try{return JSON.parse(e)}catch{return e}}function Vc(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 Hc=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)}},Uc=class{text=null;#e;constructor(e){this.#e=e}add(e){this.text=this.#e.append(this.text,e)}},Wc=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)}},Gc=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 Hc(e.maxBytes??zc),this.#t=new Uc(this.#e),this.#n=new Uc(this.#e),this.#r=new Uc(this.#e),this.#i=new Wc(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(Rc(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 Kc(e);t.#i.addBody(n),t.clientBody=Bc(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=Vc(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?{}:$n(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,$n(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:Dl(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 Nl(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 Pl=[`onAuthorize`,`onModelList`,`onModel`,`onModelNotFound`,`onModelRequest`,`onModelResponse`];function Fl(e){return{requestId:e.requestId,inboundProtocol:e.inboundProtocol,requestModel:e.requestModel,startedAt:e.startedAt,userAgent:e.userAgent??``,values:{},principal:void 0,model:null}}var Il=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=!Pl.includes(e),i;for(let a of n)try{i=await a(t)}catch(t){if(!r)throw t;pt(`[gateway] hook ${e} threw, ignored:`,t)}return i}},Ll=67108864;function Rl(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 zl=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??Fl({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){pt(`[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 Bl(e,t){return async(n,r)=>{let i=n.get(`gctx`),a=i.session,o=new zl(i,e,t),s=new URL(n.req.url);a.setHttpMeta({method:n.req.method,url:s.toString(),path:s.pathname,clientIp:Hl(n.req.raw.headers),sessionId:Sl(n.req.raw.headers),userAgent:n.req.header(`user-agent`)??``});let c=null;if(n.req.method===`POST`){let e=t.maxBodyBytes??Ll,r=Rl(n.req.raw.headers),s=r!==null&&r>e?r:null;if(s===null)try{let t=await Vl(n.req.raw,e);if(t.kind===`tooLarge`)s=t.totalBytes;else{let{body:e,parseError:r}=a.setInbound(lr(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(lr(n.req.raw.headers));i.parseError=c;try{await r()}catch(e){throw await o.finish({status:500,streaming:!1,error:{stage:`handler`,message:cr(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,lr(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: ${cr(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 Vl(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 Hl(e){let t=e.get(`x-forwarded-for`)?.split(`,`)[0]?.trim();return t!==void 0&&t!==``?t.replace(/^::ffff:/,``):``}var Ul=3.5,Wl=8,Gl=24;function Kl(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+=Kl(r,t+1);return n}if(typeof e==`object`){let n=0;for(let[r,i]of Object.entries(e))n+=r.length+Kl(i,t+1);return n}return 0}function ql(e){return e<=0?0:Math.max(1,Math.ceil(e/Ul))}function Jl(e,t){if(Array.isArray(e)){let n=0;for(let r of e)n+=Kl(r)+t;return n}return e===void 0?0:Kl(e)}function Yl(e){let t=0;return t+=Jl(e.messages,Wl),t+=Kl(e.system),t+=Kl(e.thinking),t+=Kl(e.output_config),t+=Jl(e.tools,Gl),{input_tokens:ql(t)}}var Xl=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}},Zl={"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 nr,n=e.runner??new Il().addAll(e.hooks),r=e.captureContent===!0,i=e.maxBodyBytes;return t.use(`*`,async(t,i)=>{let a=e.deps?.randomId?.()??N(),o=new Ml({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 Xl({requestId:a,deployments:e.deployments,runner:n,session:o,dispatchCtx:{deps:s,requestId:a,inboundHeaders:Mc(c),signal:t.req.raw.signal,timeouts:void 0}})),await i()}),t.use(`*`,Bl(n,{traceSink:e.traceSink,maxBodyBytes:i})),t.onError((e,t)=>{let n=typeof e?.status==`number`?e.status:500,r=cr(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=>iu(e,`openai`)),t.post(`/v1/messages`,e=>iu(e,`anthropic`)),t.post(`/v1/responses`,e=>nu(e)),t.post(`/v1/messages/count_tokens`,e=>ru(e)),t.post(`/responses`,e=>nu(e)),t.post(`/chat/completions`,e=>iu(e,`openai`)),t.post(`/messages`,e=>iu(e,`anthropic`)),t.post(`/messages/count_tokens`,e=>ru(e)),t.get(`/v1/models`,e=>eu(e)),t.get(`/models`,e=>eu(e)),t}async function $l(e,t,n){let{response:r,reason:i}=await hu(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 eu(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(Fl({requestId:t.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{models:i});t.hookCtx=r;let a=await $l(e,n,r);if(a!==null)return a;await n.run(`onModelList`,r)}return e.json({object:`list`,data:i})}async function tu(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=Fl({requestId:n.requestId,inboundProtocol:t.hookProtocol,requestModel:a??``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),n.hookCtx=o;let i=await $l(e,r,o);if(i!==null)return i}let s=uu(e);if(s!==null)return s;let c=or(n.deployments,a);if(c===null){let s=await pu(e,r,o,a??``,t.routableAs);s!==null&&(a=s,i.model=s,c=or(n.deployments,s))}return c===null?cu(e,a??``):(o!==null&&o.model===null&&(o.model=su(a??``,c)),{body:i,model:a,deployment:c,hookCtx:o})}async function nu(e){let t=e.get(`gctx`),n=await tu(e,{hookProtocol:`openai`,routableAs:`openai-responses`,hookCtxWhen:`always`});if(n instanceof Response)return n;let{body:r,deployment:i}=n;return au(e,await cl(i,fu(r),t.dispatchCtx))}async function ru(e){let t=await tu(e,{hookProtocol:`anthropic`,routableAs:`anthropic`,hookCtxWhen:`ifAuthorize`});if(t instanceof Response)return t;let{body:n}=t;return e.json(Yl(n))}async function iu(e,t){let n=e.get(`gctx`),r=n.runner,i=await tu(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=su(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=or(n.deployments,d);e!==null&&al(t,e)?(c=d,l=e):pt(`[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 au(e,await sl(l,du(o.request.body,t),u),{runner:r,hookCtx:s})}let u=du(a,t);return au(e,await sl(l,u,n.dispatchCtx))}async function au(e,t,n){let r=e.get(`gctx`);if(t.kind===`error`)return r.traceError={stage:`upstream`,...await mu(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 ou(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 ou(e){return new Response(e.stream??e.body,{status:200,headers:{...Zl}})}function su(e,t){return{name:e,provider:t.provider,upstreamModel:t.modelName,apiBase:t.apiBase}}function cu(e,t){let n=ir(t);return e.get(`gctx`).traceError={stage:`route`,message:n.error.message,status:404},e.json(n,404)}function lu(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 uu(e){let t=e.get(`gctx`).parseError;return t===null?null:lu(e,t)}function du(e,t){return t===`anthropic`?{...e,inbound_format:`anthropic`}:fu(e)}function fu(e){let{inbound_format:t,...n}=e;return n}async function pu(e,t,n,r,i){if(!t.has(`onModelNotFound`))return null;let a=Object.assign(n??Fl({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=or(e.get(`gctx`).deployments,o);return s===null||!al(i,s)?null:o}async function mu(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 hu(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=cr(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 gu=class{hookRunner;_expanded;options;constructor(e){this.options=e,this._expanded=fr(e.config),_u(this._expanded.warnings),this.hookRunner=new Il().addAll(e.hooks)}get expanded(){return this._expanded}reload(e){return this._expanded=fr(e),_u(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 nr;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 dr}};function _u(e){for(let t of e)pt(`[ezllm] ${t}`)}var vu=`重启服务(CLI 会重新生成默认配置)`,yu=class extends Error{constructor(e,t=yt(),n=vu){super(`配置文件解析失败:${t}(${e})。文件可能被截断或损坏,请修复文件内容,或备份后删除该文件并${n}`),this.name=`ConfigParseError`}};function bu(){let e=yt();if(!f(e))return null;let t;try{t=JSON.parse(h(e,`utf-8`))}catch(t){throw new yu(t.message,e)}if(typeof t!=`object`||!t||Array.isArray(t))throw new yu(`顶层必须是 JSON 对象`,e);return t}function xu(){try{return bu()}catch(e){throw e instanceof yu&&(B(`[ezllm] ${e.message}`),process.exit(1)),e}}function Su(e){Lt(yt(),e)}function Cu(e){let{masterKey:t,"web-ui":n,logs:r,setup:i,autoUpdate:a,allowLan:o,latencyTest:s,...c}=e;return c}function wu(e){return fr(Cu(e))}var Tu=`0.0.0.0`,Eu=`127.0.0.1`,Du=`监听相关配置已变更,需重启服务后生效;当前仍按启动时的地址与端口运行`;function Ou(e){let t=e?.masterKey;return typeof t==`string`?t.trim():``}function ku(){return Ou(bu())}function Au(){try{return{config:bu(),broken:!1}}catch(e){if(!(e instanceof yu))throw e;return{config:null,broken:!0}}}function ju(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 Mu(){let{config:e,broken:t}=Au(),n=ju(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 Nu(){let{config:e,broken:t}=Au();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 Pu(e){return e?.allowLan!==!1}function Fu(e){return Ou(e)!==``||ju(e)!==void 0}function Iu(e){return Fu(e)?{hostname:Pu(e)?Tu:Eu,source:`config`}:{hostname:Eu,source:`credentials`}}function Lu(){try{return Iu(bu())}catch{return Iu(null)}}function Ru(e,t){return Iu(e).hostname!==Iu(t).hostname||e?.port!==t.port}function zu(){return bu()?.logs}function Bu(e){return typeof e==`number`&&Number.isFinite(e)}function Vu(){let e=zu(),t=(e,t)=>Bu(e)&&e>=0?Math.floor(e):t;return{detailDays:t(e?.[`detail-retention-days`],0),rowDays:t(e?.[`row-retention-days`],0)}}function Hu(){let e=zu(),t=(e,t)=>Bu(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 Uu=`__blob`,Wu=[`%chat/completions%`,`%/messages%`,`%/embeddings%`,`%/responses%`,`%/models%`,`%model/info%`],Gu=1e3,Ku=134217728;function qu(e){return new Date(Date.parse(e)+288e5).toISOString().slice(0,10)}function Ju(e){return e instanceof Error?e.message:String(e)}var Yu=`CASE WHEN json_valid(headers) THEN json_extract(headers, '$.user-agent') END`;function Xu(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 Zu(){return E(vt(),`spool`)}var Qu=/^(\d+)\.jsonl$/,$u=`.tmp`,ed=268435456;function td(){return new Promise(e=>setImmediate(e))}function nd(e){return E(Zu(),`${String(e)}.jsonl`)}function rd(e){return nd(e)+$u}function id(){Pt(),p(Zu(),{recursive:!0})}function ad(){try{return g(Zu()).map(e=>Qu.exec(e)).filter(e=>e!==null).map(e=>Number(e[1])).sort((e,t)=>e-t)}catch{return[]}}function od(e){let t;try{t=h(nd(e),`utf-8`)}catch{return{kind:`missing`}}try{return{kind:`ok`,entry:JSON.parse(t)}}catch{return{kind:`corrupt`}}}function sd(){let e=0;try{for(let t of g(Zu()))if(t.endsWith($u))try{x(E(Zu(),t)),e++}catch{}}catch{return 0}return e}var cd=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:ed}totalBytes(){if(this.#n>=0)return this.#n;let e=0;try{for(let t of g(Zu()))if(Qu.test(t))try{e+=b(E(Zu(),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 ad()}readRecord(e){return od(e)}deleteFile(e){try{let t=b(nd(e)).size;x(nd(e)),this.#o(-t)}catch{}}#o(e){this.#n>=0&&(this.#n+=e)}#s(e){id();let t=rd(e.id);S(t,e.line,`utf-8`),_(t,nd(e.id)),this.#o(Buffer.byteLength(e.line))}async#c(e){await F(Zu(),{recursive:!0});let t=rd(e.id);await te(t,e.line,`utf-8`),await ee(t,nd(e.id)),this.#o(Buffer.byteLength(e.line))}async#l(e){try{await this.#c(e)}catch(e){B(`[spool] 写入失败:`,Ju(e))}}#u(){this.#r.length===0||this.#a>0||(this.#a++,this.#i=this.#i.then(()=>td()).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)&&pt(`[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,td()]);await this.#i}flushSync(){for(;this.#r.length>0;){let e=this.#r.shift();try{this.#s(e)}catch(e){B(`[spool] 崩溃前写入失败:`,Ju(e))}}}};function ld(e){let t=od(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 ud(e){return typeof e==`boolean`?+!!e:e===void 0?null:e}function dd(e){return e.map(ud)}function fd(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.text==`string`&&Array.isArray(t.values)}function pd(e){return{text:e,values:[]}}function md(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];fd(e)?(n+=e.text,r.push(...e.values)):(n+=`?`,r.push(e))}return{text:n,values:r}}var hd=Object.assign(md,{raw:pd}),gd=Symbol(`ezllm-db:table`);function _d(e){return e[gd]}function vd(e){return`"${e.replaceAll(`"`,`""`)}"`}function yd(e){return e.map(e=>vd(e)).join(`, `)}function bd(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 xd(){return bd(`text`)}function Sd(){return bd(`integer`)}function Cd(){return bd(`blob`)}function wd(e){return{on(...t){return{name:e,columns:t}}}}function Td(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,[gd]:{name:e,columns:t,indexes:n,tablePrimaryKey:i}}}function Ed(e){return e===null?`NULL`:typeof e==`boolean`?e?`1`:`0`:typeof e==`number`?String(e):`'${e.replaceAll(`'`,`''`)}'`}function Dd(e,t){let n=[vd(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`,Ed(t.defaultValue)),n.join(` `)}function Od(e){let t=_d(e),n=[],r=[];for(let[e,i]of Object.entries(t.columns))n.push(` ${Dd(e,i.meta)}`),i.meta.unique&&r.push(` UNIQUE (${vd(e)})`);let i=[...n,...r].join(`,
|
|
22
|
-
`),
|
|
23
|
-
`)}
|
|
24
|
-
`)}function jd(e){return`${vd(e.meta.table)}.${vd(e.meta.name)}`}function Md(e,t){return{kind:`condition`,text:e,values:t}}function Nd(e,t){return Md(`${jd(e)} = ?`,[t])}function Pd(e,t){return Md(`${jd(e)} <> ?`,[t])}function Fd(e,t){return Md(`${jd(e)} > ?`,[t])}function Id(e,t){return Md(`${jd(e)} >= ?`,[t])}function Ld(e,t){return Md(`${jd(e)} < ?`,[t])}function Rd(e,t){return Md(`${jd(e)} <= ?`,[t])}function zd(e,t){return Md(`${jd(e)} LIKE ?`,[t])}function Bd(e,t){if(t.length===0)return Md(`0 = 1`,[]);let n=t.map(()=>`?`).join(`, `);return Md(`${jd(e)} IN (${n})`,t)}function Vd(e){return Md(`${jd(e)} IS NULL`,[])}function Hd(e){return Md(`${jd(e)} IS NOT NULL`,[])}function Ud(e,t,n){return e.length===0?Md(n,[]):Md(e.map(e=>`(${e.text})`).join(` ${t} `),e.flatMap(e=>e.values))}function Wd(...e){return Ud(e,`AND`,`1 = 1`)}function Gd(...e){return Ud(e,`OR`,`1 = 0`)}function Kd(e){return Md(`NOT (${e.text})`,e.values)}function qd(e,t){return{kind:`sort`,text:`${jd(e)} ${t}`,values:[]}}function Jd(e){return qd(e,`ASC`)}function Yd(e){return qd(e,`DESC`)}function Xd(e){return{kind:`aggregation`,text:e,values:[]}}function Zd(e,t){return Xd(`${e}(${jd(t)})`)}function Qd(e){return Zd(`SUM`,e)}function $d(e){return Zd(`MIN`,e)}function ef(e){return Zd(`MAX`,e)}function tf(e){return e?Zd(`COUNT`,e):Xd(`COUNT(*)`)}var q={eq:Nd,ne:Pd,gt:Fd,gte:Id,lt:Ld,lte:Rd,like:zd,in:Bd,isNull:Vd,isNotNull:Hd,and:Wd,or:Gd,not:Kd,asc:Jd,desc:Yd,sum:Qd,count:tf,min:$d,max:ef},nf=class{executor;table;constructor(e,t){this.executor=e,this.table=t}get tableName(){return _d(this.table).name}get tableColumns(){return _d(this.table).columns}get quotedTable(){return vd(this.tableName)}},rf=class extends nf{conds=[];where(e){return this.conds.push(e),this}appendWhere(e,t){if(this.conds.length===0)return e;let n=Wd(...this.conds);return t.push(...n.values),`${e} WHERE ${n.text}`}},af=class extends rf{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 of(e,t){return typeof e==`bigint`||typeof t==`bigint`?BigInt(e)+BigInt(t):e+t}var sf=class extends nf{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(ud(n[e])),`?`)).join(`, `)})`),a=`INSERT${this.conflictMode} INTO ${this.quotedTable} (${yd(e.columns)}) VALUES ${i.join(`, `)}`,o=this.executor.run({text:a,values:t});n=of(n,o.changes),r=o.lastInsertRowid}return{changes:n,lastInsertRowid:r}}},cf=class extends rf{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=yd(this.projection.columns);break;case`aggregate`:e=this.projection.entries.map(([e,t])=>`${t.text} AS ${vd(e)}`).join(`, `);break;default:e=yd(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=>jd(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())}},lf=class extends af{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(ud(r)),`${vd(n)} = ?`}).join(`, `),r=this.appendWhere(`UPDATE ${this.quotedTable} SET ${n}`,e);return this.executor.run({text:r,values:e})}},uf=class extends af{run(){this.assertWhereOrAllRows(`delete`,`删除`);let e=[],t=this.appendWhere(`DELETE FROM ${this.quotedTable}`,e);return this.executor.run({text:t,values:e})}},df=new Map,ff=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(...dd(t))}}getPrepared(e,t){return e.get(...dd(t))}allPrepared(e,t){return e.all(...dd(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(Ad(e))}insert(e){return new sf(this,e)}select(e){return new cf(this,e)}update(e){return new lf(this,e)}delete(e){return new uf(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(),df.get(this.name)===this&&df.delete(this.name))}};function pf(e){let t=df.get(e);if(t!==void 0)return t;Pt();let n=new ne(E(vt(),`${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 ff(e,n);return df.set(e,r),r}var J=Td(`logs`,{id:Sd().primaryKey({autoIncrement:!0}),time:xd().notNull(),date:xd().notNull(),method:xd(),path:xd(),model:xd(),status:Sd(),stream:Sd(),error:xd(),preview:xd(),input_tokens:Sd().default(0),output_tokens:Sd().default(0),cache_read_tokens:Sd().default(0),cache_creation_tokens:Sd().default(0),ip:xd(),session_id:xd(),duration:Sd().default(0),headers:xd(),client:xd()},[wd(`idx_logs_date`).on(`date`),wd(`idx_logs_time`).on(`time`),wd(`idx_logs_model`).on(`model`),wd(`idx_logs_session`).on(`session_id`),wd(`idx_logs_client`).on(`client`)]),mf=Td(`log_details`,{log_id:Sd().primaryKey(),detail:Cd().notNull()}),hf=Td(`log_blobs`,{hash:xd().primaryKey(),content:Cd().notNull()}),gf=Td(`log_id_alloc`,{next_id:Sd().notNull()}),_f=Td(`client_names`,{ua:xd().primaryKey(),client:xd(),source:xd(),attempts:Sd().notNull().default(0),created_at:xd().notNull(),updated_at:xd().notNull()}),vf=[J,gf,_f],yf=[mf,hf],bf=[[`headers`,`TEXT`],[`client`,`TEXT`]],xf=[`CREATE INDEX IF NOT EXISTS idx_logs_ua ON logs (${Yu})`];function Sf(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 bf)n.has(t)||e.exec(`ALTER TABLE logs ADD COLUMN ${t} ${r}`)}function Cf(e){for(let t of xf)e.exec(t)}var wf=null;function Tf(){return Ef().native}function Ef(){if(wf!==null)return wf;let e=pf(`logs`);return Sf(e),e.createTables(vf),Cf(e),wf=e,e}function Y(){return Ef()}function Df(e){return Y().transaction(e)}var Of=1e3,kf=!1,Af=0,jf=0;function Mf(e){let t=e.get(hd`SELECT seq FROM sqlite_sequence WHERE name = 'logs'`);return t===void 0?0:Number(t.seq)}function Nf(e,t){if(Mf(e)>=t)return;let n=e.run(hd`UPDATE sqlite_sequence SET seq = ${t} WHERE name = 'logs'`);Number(n.changes)===0&&e.run(hd`INSERT INTO sqlite_sequence (name, seq) VALUES ('logs', ${t})`)}function Pf(e){if(e.select(gf).columns([`next_id`]).limit(1).get()!==void 0)return;let t=e.select(J).columns({m:q.max(J.id)}).get(),n=Math.max(Number(t?.m??0),Mf(e))+1;e.insert(gf).values({next_id:n}).run()}function Ff(){if(Af>=jf){let e=Y();Df(()=>{kf||=(Pf(e),!0);let t=e.select(gf).columns([`next_id`]).limit(1).get();Af=Number(t.next_id),jf=Af+Of,e.update(gf).set({next_id:jf}).allRows().run(),Nf(e,jf-1)})}return Af++}function If(e){return re(e,{params:{[ae.BROTLI_PARAM_QUALITY]:9}})}function Lf(e,t=9){let n=re(Buffer.from(e,`utf-8`),{params:{[ae.BROTLI_PARAM_QUALITY]:t}});return Buffer.concat([Buffer.from([2]),n])}function Rf(e){return j(`sha256`).update(e,`utf-8`).digest(`hex`)}function zf(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
|
|
21
|
+
`).filter(e=>e.trim()!==``);return{inboundRequest:this.truncated?null:this.inboundBody,upstreamRequest:this.upstreamUrl===null?null:{url:this.upstreamUrl,headers:this.upstreamRequestHeaders??{},body:Bc(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 Kc(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 qc=[`onAuthorize`,`onModelList`,`onModel`,`onModelNotFound`,`onModelRequest`,`onModelResponse`];function Jc(e){return{requestId:e.requestId,inboundProtocol:e.inboundProtocol,requestModel:e.requestModel,startedAt:e.startedAt,userAgent:e.userAgent??``,values:{},principal:void 0,model:null}}var Yc=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=!qc.includes(e),i;for(let a of n)try{i=await a(t)}catch(t){if(!r)throw t;ct(`[gateway] hook ${e} threw, ignored:`,t)}return i}},Xc=67108864,Zc=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??Jc({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){ct(`[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 Qc(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 Zc(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:Lc(n.req.raw.headers),userAgent:n.req.header(`user-agent`)??``});let d=null;if(n.req.method===`POST`){let e=t.maxBodyBytes??Xc,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($n(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($n(n.req.raw.headers));s.parseError=d;try{await r()}catch(e){throw await l.finish({status:500,streaming:!1,error:{stage:`handler`,message:Qn(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,$n(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: ${Qn(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 $c=3.5,el=8,tl=24;function nl(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/$c)),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,el),i+=t(e.system),i+=t(e.thinking),i+=t(e.output_config),i+=r(e.tools,tl),{input_tokens:n(i)}}var rl=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}},il={"content-type":`text/event-stream; charset=utf-8`,"cache-control":`no-cache`,connection:`keep-alive`,"x-accel-buffering":`no`};function al(e){let t=new Kn,n=e.runner??new Yc().addAll(e.hooks),r=e.captureContent===!0,i=e.maxBodyBytes;return t.use(`*`,async(t,i)=>{let a=e.deps?.randomId?.()??P(),o=new Gc({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 rl({requestId:a,deployments:e.deployments,runner:n,session:o,dispatchCtx:{deps:s,requestId:a,inboundHeaders:sc(c),signal:t.req.raw.signal,timeouts:void 0}})),await i()}),t.use(`*`,Qc(n,{traceSink:e.traceSink,maxBodyBytes:i})),t.onError((e,t)=>{let n=typeof e?.status==`number`?e.status:500,r=Qn(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=>dl(e,`openai`)),t.post(`/v1/messages`,e=>dl(e,`anthropic`)),t.post(`/v1/responses`,e=>ll(e)),t.post(`/v1/messages/count_tokens`,e=>ul(e)),t.post(`/responses`,e=>ll(e)),t.post(`/chat/completions`,e=>dl(e,`openai`)),t.post(`/messages`,e=>dl(e,`anthropic`)),t.post(`/messages/count_tokens`,e=>ul(e)),t.get(`/v1/models`,e=>sl(e)),t.get(`/models`,e=>sl(e)),t}async function ol(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=Qn(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 sl(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(Jc({requestId:t.requestId,inboundProtocol:`openai`,requestModel:``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),{models:i});t.hookCtx=r;let a=await ol(e,n,r);if(a!==null)return a;await n.run(`onModelList`,r)}return e.json({object:`list`,data:i})}async function cl(e,t){let n=(e,t)=>{let n=Jn(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??Jc({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=Xn(e.get(`gctx`).deployments,o);return s===null||!Cc(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=Jc({requestId:a.requestId,inboundProtocol:t.hookProtocol,requestModel:c??``,startedAt:Date.now(),userAgent:e.req.header(`user-agent`)}),a.hookCtx=l;let n=await ol(e,o,l);if(n!==null)return n}let u=r(e);if(u!==null)return u;let d=Xn(a.deployments,c);if(d===null){let n=await i(e,o,l,c??``,t.routableAs);n!==null&&(c=n,s.model=n,d=Xn(a.deployments,n))}return d===null?n(e,c??``):(l!==null&&l.model===null&&(l.model=pl(c??``,d)),{body:s,model:c,deployment:d,hookCtx:l})}async function ll(e){let t=e.get(`gctx`),n=await cl(e,{hookProtocol:`openai`,routableAs:`openai-responses`,hookCtxWhen:`always`});if(n instanceof Response)return n;let{body:r,deployment:i}=n;return fl(e,await Tc(i,ml(r),t.dispatchCtx))}async function ul(e){let t=await cl(e,{hookProtocol:`anthropic`,routableAs:`anthropic`,hookCtxWhen:`ifAuthorize`});if(t instanceof Response)return t;let{body:n}=t;return e.json(nl(n))}async function dl(e,t){let n=(e,t)=>t===`anthropic`?{...e,inbound_format:`anthropic`}:ml(e),r=e.get(`gctx`),i=r.runner,a=await cl(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=pl(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=Xn(r.deployments,d);e!==null&&Cc(t,e)?(l=d,u=e):ct(`[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 fl(e,await wc(u,n(s.request.body,t),d),{runner:i,hookCtx:c})}let d=n(o,t);return fl(e,await wc(u,d,r.dispatchCtx))}async function fl(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:{...il}}),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 pl(e,t){return{name:e,provider:t.provider,upstreamModel:t.modelName,apiBase:t.apiBase}}function ml(e){let{inbound_format:t,...n}=e;return n}var hl=class{hookRunner;_expanded;options;constructor(e){this.options=e,this._expanded=nr(e.config),gl(this._expanded.warnings),this.hookRunner=new Yc().addAll(e.hooks)}get expanded(){return this._expanded}reload(e){return this._expanded=nr(e),gl(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 Kn;return e.get(`/healthz`,e=>e.json({status:`ok`})),e.route(`/`,al({deployments:this.expanded.deployments,runner:this.hookRunner,deps:this.options.deps,captureContent:!0,traceSink:this.options.traceSink})),e}static get ConfigError(){return tr}};function gl(e){for(let t of e)ct(`[ezllm] ${t}`)}var _l=`重启服务(CLI 会重新生成默认配置)`,vl=class extends Error{constructor(e,t=pt(),n=_l){super(`配置文件解析失败:${t}(${e})。文件可能被截断或损坏,请修复文件内容,或备份后删除该文件并${n}`),this.name=`ConfigParseError`}};function yl(){let e=pt();if(!l(e))return null;let t;try{t=JSON.parse(f(e,`utf-8`))}catch(t){throw new vl(t.message,e)}if(typeof t!=`object`||!t||Array.isArray(t))throw new vl(`顶层必须是 JSON 对象`,e);return t}function bl(){try{return yl()}catch(e){throw e instanceof vl&&(R(`[ezllm] ${e.message}`),process.exit(1)),e}}function xl(e){jt(pt(),e)}function Sl(e){let{masterKey:t,"web-ui":n,logs:r,setup:i,autoUpdate:a,allowLan:o,latencyTest:s,...c}=e;return c}function Cl(e){return nr(Sl(e))}var wl=`0.0.0.0`,Tl=`127.0.0.1`,El=`监听相关配置已变更,需重启服务后生效;当前仍按启动时的地址与端口运行`;function Dl(e){let t=e?.masterKey;return typeof t==`string`?t.trim():``}function Ol(){return Dl(yl())}function kl(){try{return{config:yl(),broken:!1}}catch(e){if(!(e instanceof vl))throw e;return{config:null,broken:!0}}}function Al(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 jl(){let{config:e,broken:t}=kl(),n=Al(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 Ml(){let{config:e,broken:t}=kl();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 Nl(e){return(e=>Dl(e)!==``||Al(e)!==void 0)(e)?{hostname:(e=>e?.allowLan!==!1)(e)?wl:Tl,source:`config`}:{hostname:Tl,source:`credentials`}}function Pl(){try{return Nl(yl())}catch{return Nl(null)}}function Fl(e,t){return Nl(e).hostname!==Nl(t).hostname||e?.port!==t.port}function Il(){return yl()?.logs}function Ll(e){return typeof e==`number`&&Number.isFinite(e)}function Rl(){let e=Il(),t=(e,t)=>Ll(e)&&e>=0?Math.floor(e):t;return{detailDays:t(e?.[`detail-retention-days`],0),rowDays:t(e?.[`row-retention-days`],0)}}function zl(){let e=Il(),t=(e,t)=>Ll(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 Bl=`__blob`,Vl=[`%chat/completions%`,`%/messages%`,`%/embeddings%`,`%/responses%`,`%/models%`,`%model/info%`],Hl=1e3,Ul=134217728;function Wl(e){return new Date(Date.parse(e)+288e5).toISOString().slice(0,10)}function Gl(e){return e instanceof Error?e.message:String(e)}var Kl=`CASE WHEN json_valid(headers) THEN json_extract(headers, '$.user-agent') END`;function ql(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 Jl(){return E(ft(),`spool`)}var Yl=/^(\d+)\.jsonl$/,Xl=`.tmp`,Zl=268435456;function Ql(){return new Promise(e=>setImmediate(e))}function $l(e){return E(Jl(),`${String(e)}.jsonl`)}function eu(e){return $l(e)+Xl}function tu(){Ot(),u(Jl(),{recursive:!0})}function nu(){try{return p(Jl()).map(e=>Yl.exec(e)).filter(e=>e!==null).map(e=>Number(e[1])).sort((e,t)=>e-t)}catch{return[]}}function ru(e){let t;try{t=f($l(e),`utf-8`)}catch{return{kind:`missing`}}try{return{kind:`ok`,entry:JSON.parse(t)}}catch{return{kind:`corrupt`}}}function iu(){let e=0;try{for(let t of p(Jl()))if(t.endsWith(Xl))try{v(E(Jl(),t)),e++}catch{}}catch{return 0}return e}var au=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:Zl}totalBytes(){if(this.#n>=0)return this.#n;let e=0;try{for(let t of p(Jl()))if(Yl.test(t))try{e+=_(E(Jl(),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 nu()}readRecord(e){return ru(e)}deleteFile(e){try{let t=_($l(e)).size;v($l(e)),this.#o(-t)}catch{}}#o(e){this.#n>=0&&(this.#n+=e)}#s(e){tu();let t=eu(e.id);y(t,e.line,`utf-8`),m(t,$l(e.id)),this.#o(Buffer.byteLength(e.line))}async#c(e){await ee(Jl(),{recursive:!0});let t=eu(e.id);await re(t,e.line,`utf-8`),await ne(t,$l(e.id)),this.#o(Buffer.byteLength(e.line))}async#l(e){try{await this.#c(e)}catch(e){R(`[spool] 写入失败:`,Gl(e))}}#u(){this.#r.length===0||this.#a>0||(this.#a++,this.#i=this.#i.then(()=>Ql()).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)&&ct(`[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,Ql()]);await this.#i}flushSync(){for(;this.#r.length>0;){let e=this.#r.shift();try{this.#s(e)}catch(e){R(`[spool] 崩溃前写入失败:`,Gl(e))}}}};function ou(e){let t=ru(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 su(e){return typeof e==`boolean`?+!!e:e===void 0?null:e}function cu(e){return e.map(su)}function lu(e){return{text:e,values:[]}}function uu(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 du=Object.assign(uu,{raw:lu}),fu=Symbol(`ezllm-db:table`);function pu(e){return e[fu]}function mu(e){return`"${e.replaceAll(`"`,`""`)}"`}function hu(e){return e.map(e=>mu(e)).join(`, `)}function gu(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 _u(){return gu(`text`)}function vu(){return gu(`integer`)}function yu(){return gu(`blob`)}function bu(e){return{on(...t){return{name:e,columns:t}}}}function xu(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,[fu]:{name:e,columns:t,indexes:n,tablePrimaryKey:i}}}function Su(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=[mu(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=hu(t.columns);return`CREATE INDEX IF NOT EXISTS ${mu(t.name)} ON ${mu(e)} (${n})`},r=pu(e),i=[],a=[];for(let[e,n]of Object.entries(r.columns))i.push(` ${t(e,n.meta)}`),n.meta.unique&&a.push(` UNIQUE (${mu(e)})`);let o=[...i,...a].join(`,
|
|
22
|
+
`),s=o;r.tablePrimaryKey!==void 0&&(s=`${o},\n PRIMARY KEY (${hu(r.tablePrimaryKey)})`);let c=[`CREATE TABLE IF NOT EXISTS ${mu(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 Cu(e){return`${mu(e.meta.table)}.${mu(e.meta.name)}`}function wu(e,t){return{kind:`condition`,text:e,values:t}}function Tu(e,t){return wu(`${Cu(e)} = ?`,[t])}function Eu(e,t){return wu(`${Cu(e)} <> ?`,[t])}function Du(e,t){return wu(`${Cu(e)} > ?`,[t])}function Ou(e,t){return wu(`${Cu(e)} >= ?`,[t])}function ku(e,t){return wu(`${Cu(e)} < ?`,[t])}function Au(e,t){return wu(`${Cu(e)} <= ?`,[t])}function ju(e,t){return wu(`${Cu(e)} LIKE ?`,[t])}function Mu(e,t){if(t.length===0)return wu(`0 = 1`,[]);let n=t.map(()=>`?`).join(`, `);return wu(`${Cu(e)} IN (${n})`,t)}function Nu(e){return wu(`${Cu(e)} IS NULL`,[])}function Pu(e){return wu(`${Cu(e)} IS NOT NULL`,[])}function Fu(e,t,n){return e.length===0?wu(n,[]):wu(e.map(e=>`(${e.text})`).join(` ${t} `),e.flatMap(e=>e.values))}function Iu(...e){return Fu(e,`AND`,`1 = 1`)}function Lu(...e){return Fu(e,`OR`,`1 = 0`)}function Ru(e){return wu(`NOT (${e.text})`,e.values)}function zu(e,t){return{kind:`sort`,text:`${Cu(e)} ${t}`,values:[]}}function Bu(e){return zu(e,`ASC`)}function Vu(e){return zu(e,`DESC`)}function Hu(e){return{kind:`aggregation`,text:e,values:[]}}function Uu(e,t){return Hu(`${e}(${Cu(t)})`)}function Wu(e){return Uu(`SUM`,e)}function Gu(e){return Uu(`MIN`,e)}function Ku(e){return Uu(`MAX`,e)}function qu(e){return e?Uu(`COUNT`,e):Hu(`COUNT(*)`)}var G={eq:Tu,ne:Eu,gt:Du,gte:Ou,lt:ku,lte:Au,like:ju,in:Mu,isNull:Nu,isNotNull:Pu,and:Iu,or:Lu,not:Ru,asc:Bu,desc:Vu,sum:Wu,count:qu,min:Gu,max:Ku},Ju=class{executor;table;constructor(e,t){this.executor=e,this.table=t}get tableName(){return pu(this.table).name}get tableColumns(){return pu(this.table).columns}get quotedTable(){return mu(this.tableName)}},Yu=class extends Ju{conds=[];where(e){return this.conds.push(e),this}appendWhere(e,t){if(this.conds.length===0)return e;let n=Iu(...this.conds);return t.push(...n.values),`${e} WHERE ${n.text}`}},Xu=class extends Yu{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 Zu(e,t){return typeof e==`bigint`||typeof t==`bigint`?BigInt(e)+BigInt(t):e+t}var Qu=class extends Ju{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(su(n[e])),`?`)).join(`, `)})`),a=`INSERT${this.conflictMode} INTO ${this.quotedTable} (${hu(e.columns)}) VALUES ${i.join(`, `)}`,o=this.executor.run({text:a,values:t});n=Zu(n,o.changes),r=o.lastInsertRowid}return{changes:n,lastInsertRowid:r}}},$u=class extends Yu{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=hu(this.projection.columns);break;case`aggregate`:e=this.projection.entries.map(([e,t])=>`${t.text} AS ${mu(e)}`).join(`, `);break;default:e=hu(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=>Cu(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())}},ed=class extends Xu{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(su(r)),`${mu(n)} = ?`}).join(`, `),r=this.appendWhere(`UPDATE ${this.quotedTable} SET ${n}`,e);return this.executor.run({text:r,values:e})}},td=class extends Xu{run(){this.assertWhereOrAllRows(`delete`,`删除`);let e=[],t=this.appendWhere(`DELETE FROM ${this.quotedTable}`,e);return this.executor.run({text:t,values:e})}},nd=new Map,rd=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(...cu(t))}}getPrepared(e,t){return e.get(...cu(t))}allPrepared(e,t){return e.all(...cu(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(Su(e))}insert(e){return new Qu(this,e)}select(e){return new $u(this,e)}update(e){return new ed(this,e)}delete(e){return new td(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(),nd.get(this.name)===this&&nd.delete(this.name))}};function id(e){let t=nd.get(e);if(t!==void 0)return t;Ot();let n=new ie(E(ft(),`${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 rd(e,n);return nd.set(e,r),r}var K=xu(`logs`,{id:vu().primaryKey({autoIncrement:!0}),time:_u().notNull(),date:_u().notNull(),method:_u(),path:_u(),model:_u(),status:vu(),stream:vu(),error:_u(),preview:_u(),input_tokens:vu().default(0),output_tokens:vu().default(0),cache_read_tokens:vu().default(0),cache_creation_tokens:vu().default(0),ip:_u(),session_id:_u(),duration:vu().default(0),headers:_u(),client:_u()},[bu(`idx_logs_date`).on(`date`),bu(`idx_logs_time`).on(`time`),bu(`idx_logs_model`).on(`model`),bu(`idx_logs_session`).on(`session_id`),bu(`idx_logs_client`).on(`client`)]),ad=xu(`log_details`,{log_id:vu().primaryKey(),detail:yu().notNull()}),od=xu(`log_blobs`,{hash:_u().primaryKey(),content:yu().notNull()}),sd=xu(`log_id_alloc`,{next_id:vu().notNull()}),cd=xu(`client_names`,{ua:_u().primaryKey(),client:_u(),source:_u(),attempts:vu().notNull().default(0),created_at:_u().notNull(),updated_at:_u().notNull()}),ld=[K,sd,cd],ud=[ad,od],dd=[[`headers`,`TEXT`],[`client`,`TEXT`]],fd=[`CREATE INDEX IF NOT EXISTS idx_logs_ua ON logs (${Kl})`];function pd(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 dd)n.has(t)||e.exec(`ALTER TABLE logs ADD COLUMN ${t} ${r}`)}function md(e){for(let t of fd)e.exec(t)}var hd=null;function gd(){return _d().native}function _d(){if(hd!==null)return hd;let e=id(`logs`);return pd(e),e.createTables(ld),md(e),hd=e,e}function q(){return _d()}function vd(e){return q().transaction(e)}var yd=1e3,bd=!1,xd=0,Sd=0;function Cd(){let e=e=>{let t=e.get(du`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(du`UPDATE sqlite_sequence SET seq = ${n} WHERE name = 'logs'`);Number(r.changes)===0&&t.run(du`INSERT INTO sqlite_sequence (name, seq) VALUES ('logs', ${n})`)},n=t=>{if(t.select(sd).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(sd).values({next_id:r}).run()};if(xd>=Sd){let e=q();vd(()=>{bd||=(n(e),!0);let r=e.select(sd).columns([`next_id`]).limit(1).get();xd=Number(r.next_id),Sd=xd+yd,e.update(sd).set({next_id:Sd}).allRows().run(),t(e,Sd-1)})}return xd++}function wd(e){return ae(e,{params:{[se.BROTLI_PARAM_QUALITY]:9}})}function Td(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 Ed(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),{[Bl]: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:Wl(o),preview:Td(e.response),detail:r(JSON.stringify(c),n),blobs:s,entry:e}}function Dd(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 Od(e,t){let n=t.time||new Date().toISOString(),r=Wl(n),i=q();return vd(()=>{i.insert(K).values({id:e,time:n,date:r,preview:Td(t.response),...Dd(t)}).run()}),e}var kd=4,Ad=/^logs-(\d{4})(\d{2})(\d{2})\.db$/,jd=/^\d{6}$/;function Md(){return E(ft(),`details`)}function Nd(e){return E(Md(),e.slice(0,7).replace(/-/g,``))}function Pd(e){let t=e.replace(/-/g,``);return`details/${t.slice(0,6)}/logs-${t}`}function Fd(e){return E(Nd(e),`logs-${e.replace(/-/g,``)}.db`)}var Id=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)u(Nd(e),{recursive:!0});else if(!l(Fd(e)))return null;let r=id(Pd(e));return r.createTables(ud),this.#n(e,r)}#n(e,t){for(this.#e.set(e,t);this.#e.size>kd;){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=p(Md())}catch{return[]}let t=[];for(let n of e){if(!jd.test(n))continue;let e;try{e=p(E(Md(),n))}catch{continue}for(let n of e){let e=Ad.exec(n);e!==null&&t.push(`${e[1]}-${e[2]}-${e[3]}`)}}return t.sort()}deleteDetailDb(e){this.#r(e);let t=Fd(e),n=!1;l(t)&&(h(t,{force:!0}),n=!0);for(let e of[`-wal`,`-shm`])h(t+e,{force:!0});try{g(Nd(e))}catch{}return n}};function Ld(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){vd(()=>{for(let e of r)n.insert(K).values({id:e.id,time:e.time,date:e.date,preview:e.preview,...Dd(e.entry)}).orIgnore().run()});let t=Id.open(e);t.transaction(()=>{for(let e of r){t.insert(ad).values({log_id:e.id,detail:e.detail}).orReplace().run();for(let[n,r]of e.blobs)t.insert(od).values({hash:n,content:wd(Buffer.from(r,`utf-8`))}).orIgnore().run()}})}return e.length}function Rd(e){return oe(Buffer.from(e)).toString(`utf-8`)}function zd(e){if(e.length>0&&e[0]===2)return oe(Buffer.from(e.subarray(1)));throw Error(`详情 BLOB 格式非法:缺少 brotli 标记字节(历史 gzip 格式已不再支持)`)}function Bd(e){let t=Object.keys(e);if(t.length!==1||t[0]!==`__blob`)return null;let n=e[Bl];return typeof n==`string`?n:null}function Vd(e,t){if(Array.isArray(e))return e.map(e=>Vd(e,t));if(typeof e==`object`&&e){let n=e,r=Bd(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]=Vd(r,t);return i}return e}function Hd(e,t){if(Array.isArray(e)){for(let n of e)Hd(n,t);return}if(typeof e==`object`&&e){let n=e,r=Bd(n);if(r!==null){t.add(r);return}for(let e of Object.values(n))Hd(e,t)}}function Ud(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(od).columns([`hash`,`content`]).where(G.in(od.hash,i)).all();for(let e of a)n.set(e.hash,Rd(e.content))}return n}function Wd(e){let t=q().select(K).where(G.eq(K.id,Number(e))).get();if(t===void 0)return null;let n=Id.openIfExists(t.date);if(n===null)return null;let r=null,i=n.select(ad).columns([`detail`]).where(G.eq(ad.log_id,t.id)).get();if(i&&i.detail!=null&&i.detail.length>0)try{let e=JSON.parse(zd(i.detail).toString(`utf-8`)),t=new Set;Hd(e,t),r=Vd(e,Ud(t,n))}catch(e){R(`[logs] 详情 ${String(t.id)} 解析失败,按无详情处理:`,Gl(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 Gd(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 Kd(e,t){if(!t)return!0;let n=Vl.some(t=>RegExp(`^`+t.replace(/%/g,`.*`)+`$`).test(e||``));return t===`model`?n:!n}function qd(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 Jd(e){let t=[],n=qd(e);if(n!==null&&t.push(n),e.pathGroup){let n=G.or(...Vl.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 Yd(e,t){return t===null?e:e.where(t)}function Xd(e){return{p:Math.max(parseInt(String(e.page))||1,1),ps:Math.min(Math.max(parseInt(String(e.pageSize))||50,1),500)}}function Zd(e){return e===`model`||e===`status`||e===`stream`?e:`time`}var Qd={model:K.model,status:K.status,stream:K.stream,time:K.time},$d=[`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 ef(e){let t=e=>{let t=Qd[Zd(e.sort)];return e.order===`asc`?G.asc(t):G.desc(t)},{p:n,ps:r}=Xd(e),i=Jd(e),a=q(),o=Yd(a.select(K).columns({c:G.count()}),i).get();return{total:o?Number(o.c):0,page:n,pageSize:r,items:Yd(a.select(K).columns($d),i).orderBy(t(e)).limit(r).offset((n-1)*r).all().map(e=>({...e}))}}function tf(e={}){let t=[G.and(G.isNotNull(K.model),G.ne(K.model,``)),G.eq(K.status,200),G.or(...Vl.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(du`
|
|
26
26
|
SELECT model,
|
|
27
27
|
COUNT(*) AS calls,
|
|
28
28
|
SUM(input_tokens) AS input_tokens,
|
|
@@ -34,7 +34,7 @@ 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 nf(){return q().select(K).columns([`date`]).groupBy(K.date).orderBy(G.desc(K.date)).all().map(e=>e.date)}function rf(){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 af=du.raw(`
|
|
38
38
|
COUNT(*) AS calls,
|
|
39
39
|
MIN(time) AS first_time,
|
|
40
40
|
MAX(time) AS last_time,
|
|
@@ -45,86 +45,82 @@ import{createRequire as e}from"node:module";import{homedir as t,networkInterface
|
|
|
45
45
|
SUM(output_tokens) AS output_tokens,
|
|
46
46
|
SUM(cache_read_tokens) AS cache_read_tokens,
|
|
47
47
|
SUM(cache_creation_tokens) AS cache_creation_tokens,
|
|
48
|
-
SUM(duration) AS duration`);function
|
|
49
|
-
SELECT session_id, ${
|
|
48
|
+
SUM(duration) AS duration`);function of(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}=Xd(e),i=Jd(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(du`
|
|
49
|
+
SELECT session_id, ${af}
|
|
50
50
|
FROM logs
|
|
51
|
-
WHERE ${
|
|
51
|
+
WHERE ${s}
|
|
52
52
|
GROUP BY session_id
|
|
53
53
|
ORDER BY last_time DESC
|
|
54
|
-
LIMIT ${
|
|
55
|
-
`).map(
|
|
56
|
-
SELECT ${
|
|
54
|
+
LIMIT ${r} OFFSET ${(n-1)*r}
|
|
55
|
+
`).map(t),d=l.get(du`
|
|
56
|
+
SELECT ${af}
|
|
57
57
|
FROM logs
|
|
58
|
-
WHERE ${
|
|
59
|
-
`),d
|
|
60
|
-
SELECT COUNT(DISTINCT session_id) AS c FROM logs WHERE ${
|
|
61
|
-
`),
|
|
62
|
-
SELECT COUNT(*) AS c FROM logs WHERE ${
|
|
63
|
-
`);return{total:Number(
|
|
58
|
+
WHERE ${c}
|
|
59
|
+
`),f=d&&Number(d.calls??0)>0?t(d):null,p=l.get(du`
|
|
60
|
+
SELECT COUNT(DISTINCT session_id) AS c FROM logs WHERE ${s}
|
|
61
|
+
`),m=l.get(du`
|
|
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 sf=[`id`,`time`,`date`,`model`,`status`,`stream`,`error`,`preview`];function cf(e,t=Hl,n=Ul){let{p:r,ps:i}=Xd(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=Yd(q().select(K).columns(sf),qd(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=Id.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(ad).columns([`log_id`,`detail`]).where(G.in(ad.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=zd(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;Hd(i,e),m.set(r,e)}else Hd(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,Ud(t,n))}let y=[];for(let{r:t,date:n,raw:r}of p){let i=Vd(r,v.get(n)??new Map);JSON.stringify(i).toLowerCase().includes(a)&&(!e.model||String(i.model??``).includes(e.model))&&(!e.status||Gd(Number(i.status??0),e.status,i.error))&&Kd(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=Zd(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 lf(e){let t=Id.open(e),n=new Set,r=0,i=0,a=t.select(ad).columns([`detail`]).all();for(let e of a){r++;try{Hd(JSON.parse(zd(e.detail).toString(`utf-8`)),n)}catch{i++}}if(i>0)return ct(`[logs] 详情库 ${e} 有 ${String(i)} 条详情解析失败,跳过本次 blob 回收(避免误删仍被引用的内容)`),{scanned:r,blobsDeleted:0,skipped:!0};let o=t.select(od).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(od).where(G.in(od.hash,o.slice(e,e+400))).run();s+=Number(n.changes)}}),{scanned:r,blobsDeleted:s,skipped:!1}}function uf(e){let t=q(),n=Jd(e),r=Yd(t.select(K).columns({c:G.count()}),n).get(),i=r?Number(r.c):0,a;if(i>0)a=Yd(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=cf({...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&&ct(`[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=Id.open(e);n.transaction(()=>{for(let e=0;e<t.length;e+=400)n.delete(ad).where(G.in(ad.log_id,t.slice(e,e+400))).run()})}vd(()=>{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{lf(e)}catch(t){ct(`[logs] 详情库 ${e} 的 blob 回收失败:`,Gl(t))}return a.length}function df(e,t){let n=e=>Wl(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 Id.listDetailDates())e<t&&Id.deleteDetailDb(e)&&r++}let i=0;if(t>0){let e=n(t),r=vd(()=>q().delete(K).where(G.lt(K.date,e)).run());i=Number(r.changes)}return{detailsDeleted:r,rowsDeleted:i}}var ff={syncIntervalMs:5e3,payloadQuality:9},pf=2e3,mf=1e3,hf=1e3;function gf(e){return q().select(K).columns([`id`]).where(G.eq(K.id,e)).get()!==void 0}var _f=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 入库失败:`,Gl(e))}).finally(()=>{this.#r=!1}))}async syncOnce(e={}){let t=e.budgetMs??pf,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`){ct(`[spool] 丢弃不可解析的记录 ${String(e)}.jsonl`),this.#e.deleteFile(e),r.poisoned++;continue}try{let n=Ed(t.entry,e,i.payloadQuality),a=gf(e);Ld([n]),a||r.anchorFilled++,r.inserted++}catch(t){R(`[spool] 记录 ${String(e)} 入库失败:`,Gl(t));continue}this.#e.deleteFile(e),r.filesDone.push(e),await Ql()}}return r}async syncNow(){if(this.#n!==null){await this.#n;return}if(!this.#r&&!(Date.now()-this.#i<hf)){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 启动恢复失败:`,Gl(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}},vf=null;function yf(e){return vf===null&&(vf=e===void 0?new _f({spool:new au,getConfig:()=>ff}):new _f(e)),vf}function bf(e){let t=yf(e);return{name:`spoolSync`,everyMs:()=>e.getConfig().syncIntervalMs,firstDelayMs:mf,run:()=>{t.runScheduledRound()}}}async function xf(){await yf().syncNow()}async function Sf(){await yf().recover()}async function Cf(e=6e4){return yf().drain(e)}var wf=216e5,Tf=3e4;function Ef(e){return{name:`logPrune`,everyMs:wf,firstDelayMs:Tf,run:()=>{try{let{detailDays:t,rowDays:n}=e.getRetention(),r=df(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] 日志清理失败:`,Gl(e))}}}}var Df=3,Of=`fallback`;function kf(){return new Date().toISOString()}function Af(e){return q().select(cd).columns([`client`]).where(G.eq(cd.ua,e)).get()}function jf(e){if(e.length===0)return 0;let t=kf(),n=q(),r=0;return vd(()=>{for(let i of e){let e=n.insert(cd).values({ua:i,client:null,source:null,attempts:0,created_at:t,updated_at:t}).orIgnore().run();r+=Number(e.changes)}}),r}function Mf(){return q().select(cd).columns([`ua`,`client`]).where(G.isNotNull(cd.client)).all().filter(e=>e.client!==null&&e.client!==``)}function Nf(e,t){if(e===``||t===``)return 0;let n=q().run(du`
|
|
64
64
|
UPDATE logs SET client = ${t}
|
|
65
|
-
WHERE client IS NULL AND ${
|
|
66
|
-
`);return Number(n.changes)}function
|
|
65
|
+
WHERE client IS NULL AND ${du.raw(Kl)} = ${e}
|
|
66
|
+
`);return Number(n.changes)}function Pf(e){return q().select(cd).columns([`ua`]).where(G.and(G.isNull(cd.client),G.lt(cd.attempts,Df))).orderBy(G.asc(cd.created_at)).limit(e).all().map(e=>e.ua)}function Ff(e,t){if(e.size===0)return 0;let n=kf(),r=q(),i=0;return vd(()=>{for(let[a,o]of e){let e=r.update(cd).set({client:o,source:t,updated_at:n}).where(G.eq(cd.ua,a)).run();i+=Number(e.changes)}}),i}function If(e){if(e.length===0)return[];let t=q(),n=t.select(cd).columns([`ua`,`attempts`,`client`]).where(G.in(cd.ua,[...e])).all(),r=[],i=kf();return vd(()=>{for(let e of n){if(e.client!==null)continue;let n=e.attempts+1;t.update(cd).set({attempts:n,updated_at:i}).where(G.eq(cd.ua,e.ua)).run(),n>=Df&&r.push(e.ua)}}),r}var Lf=new Map,Rf=new Set;function zf(e){let t=e.trim();if(t===``)return null;if(Lf.has(t))return Lf.get(t)??null;let n=Af(t);return n===void 0?(Lf.set(t,null),Rf.add(t),null):(Lf.set(t,n.client),n.client)}function Bf(e){return(()=>{if(Rf.size===0)return 0;let e=jf([...Rf]);return Rf.clear(),e})(),Pf(e)}function Vf(e,t){if(e.size===0)return 0;let n=Ff(e,t);for(let[t,n]of e)Nf(t,n),Lf.set(t,n),Rf.delete(t);return n}function Hf(e){return If(e)}var Uf=100,Wf=67108864,Gf=new Set([`authorization`,`proxy-authorization`,`x-api-key`,`api-key`,`x-goog-api-key`,`cookie`,`set-cookie`]),Kf=new Set([`key`,`apikey`,`accesskey`,`accesstoken`,`token`,`authtoken`,`sig`,`signature`,`secret`,`password`]);function qf(e){let t=e=>e===null?null:e.split(`
|
|
67
67
|
|
|
68
|
-
`).filter(e=>e.trim()!==``)
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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))Gf.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()))Kf.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:zf(e.http.userAgent)}}function Jf(e,t){let n=qf(t),r=Number(t.requestId),i=Number.isSafeInteger(r)&&r>0?r:Cd();e.write(i,n),Od(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 Yf=class{#e;#t;#n;#r=[];#i=0;#a=!1;constructor(e={}){this.#e=e.spool??new au,this.#t=e.queueCapacity??Uf,this.#n=e.queueMaxBytes??Wf}#o(){let e=this.#r.shift();return this.#i-=Xf(e),e}async#s(){if(!this.#a){this.#a=!0;try{for(;this.#r.length>0;){await Ql();try{Jf(this.#e,this.#o())}catch(e){R(`[ezllm] trace 落盘失败:`,Gl(e))}}}finally{this.#a=!1}}}write(e){for(;this.#r.length>=this.#t||this.#i>=this.#n&&this.#r.length>0;)this.#o(),ct(`[ezllm] trace 队列已满(${String(this.#t)} 条 / ${String(Math.round(this.#n/1024/1024))}MB),丢弃最旧一条`);this.#r.push(e),this.#i+=Xf(e),this.#s()}async flush(){for(;this.#r.length>0||this.#a;)await Ql();await this.#e.flush()}flushSync(){for(;this.#r.length>0;)try{Jf(this.#e,this.#o())}catch(e){R(`[ezllm] trace 崩溃前落盘失败:`,Gl(e))}this.#e.flushSync()}};function Xf(e){return(e.inbound.bodyText?.length??0)+(e.upstream.requestBody?.length??0)+(e.upstream.responseText?.length??0)+(e.client.streamText?.length??0)+4096}var Zf=48;function Qf(e){let t=e.trim();if(t===``)return``;let n=t.split(/\s+/)[0]??t;return n.length>Zf?n.slice(0,Zf):n}var $f=500;function ep(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(du`SELECT detail FROM log_details WHERE log_id = ${t}`);if(n===void 0)return null;try{return JSON.parse(zd(n.detail).toString(`utf-8`))}catch{return null}},r=q(),i={days:0,scanned:0,filled:0,skipped:0,uas:0,clientsAssigned:0},a=Id.listDetailDates();for(let o of a){let a=r.all(du`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=Id.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=[],vd(()=>{for(let t of e)r.run(du`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=ql(a);o!==``&&c.add(o),l.length>=$f&&u()}u(),c.size>0&&(i.uas+=jf([...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 Mf())i.clientsAssigned+=Nf(e.ua,e.client);return i}var tp=2e3,np=500;function rp(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 Lc(e)}catch{return``}},n=(e,t)=>{t.length!==0&&vd(()=>{for(let n of t)e.run(du`
|
|
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(du`
|
|
72
72
|
SELECT id, headers FROM logs
|
|
73
|
-
WHERE id > ${
|
|
73
|
+
WHERE id > ${a}
|
|
74
74
|
AND (session_id IS NULL OR session_id = '')
|
|
75
75
|
AND headers IS NOT NULL
|
|
76
76
|
ORDER BY id
|
|
77
|
-
LIMIT ${
|
|
78
|
-
`);if(i.length===0)break;let a=[];for(let e of i){r=Number(e.id),n.scanned++;let i=km(e.headers);i!==``&&(a.push({id:Number(e.id),sessionId:i}),n.filled++,a.length>=Om&&(Am(t,a),a.length=0))}Am(t,a),e.onProgress?.(`已扫描到 id ${String(r)}:写入 ${String(n.filled)} 行(累计)`)}return n}function Mm(){for(let e of wt())if(f(e))return e;return null}function Nm(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}:(pt(`[ezllm] ${t} 未导出 onModelRequest 函数,已忽略(不挂任何钩子)`),null)}async function Pm(e){let t=Mm();if(t===null)return;let n;try{n=await import(A(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=Nm(n,t);r?.onModelRequest!==void 0&&(e.addHook(`onModelRequest`,r.onModelRequest),z(`[ezllm] 已加载用户钩子:${t}(onModelRequest)`))}function Fm(e){return ft.PORT??e.port}async function Im(e,t,n={}){let r=new gu({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(Ff())}});t.register(r),await Pm(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 nr},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 Lm=64;function Rm(e){return e.trim()}function zm(e,t={}){let n=new Map;function r(e,t){for(n.delete(e),n.set(e,t);n.size>Lm;){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=Rm(e.ctx.userAgent);t!==``&&r(t,e.ctx.model.name)}),e.addHook(`onModelNotFound`,t=>{if(i().has(t.requestedModel))return;let r=Rm(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 Bm=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 Vm(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var Hm=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,Um=new nr;function Wm(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}Um.post(`/login`,async e=>{let t=Mu();if(t.configBroken)return e.json({error:Hm},503);if(!t.required)return e.json({error:`当前未设置登录账号,管理台免登录访问(如需启用请先设置账号)`},400);let n=await Vm(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:Wm(t)})});async function Gm(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=Mu();if(!n.required)return await t();if(n.configBroken)return e.json({error:Hm},401);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==Wm(n))return e.json({error:`token 无效或已过期`},401);await t()}var Km=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function qm(e,t){return e instanceof Km?(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 Jm(e){return async t=>{try{return await e(t)}catch(e){throw new Km(500,e.message)}}}var Ym=8,Xm=6;function Zm(){let e=bu();if(e===null)throw new Km(500,`配置文件不存在`);return e}function Qm(){let e=new nr;return e.onError(qm),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=Nu(),n=!1;try{n=ku()!==``}catch(e){if(!(e instanceof yu))throw e}return e.json({initialized:t.completed,deployment:t.deployment,masterKeySet:n,authRequired:Mu().required,version:Nt()})}),e.post(`/master-key`,async e=>{if(Nu().completed)return e.json({error:`已完成初始化,请到设置页修改主密钥`},403);let t=await Vm(e);if(t===null)return e.json({error:`请求体格式错误`},400);let n;if(t.mode===`generate`)n=M(32).toString(`base64url`);else if(t.mode===`custom`){if(n=(t.masterKey??``).trim(),n.length<Ym)return e.json({error:`主密钥至少 ${String(Ym)} 位`},400)}else return e.json({error:`mode 必须是 generate 或 custom`},400);let r=Zm(),i={...r,masterKey:n};return Su(i),e.json({masterKey:n,...Ru(r,i)?{restartHint:Du}:{}})}),e.post(`/finish`,async e=>{if(Nu().completed)return e.json({error:`已完成初始化,请到设置页修改`},403);let t=await Vm(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`&&ku()===``)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<Xm)return e.json({error:`密码至少 ${String(Xm)} 位`},400)}else if(n===`server`)return e.json({error:`服务器部署必须设置登录账号密码,防止管理台被陌生人登录`},400);let o=Zm(),s={...o,setup:{completed:!0,deployment:n},allowLan:n===`server`,...a?{"web-ui":{...o[`web-ui`],"login-account":{username:r,password:i}}}:{}};return Su(s),e.json({message:a?`初始化完成,请使用新账号登录`:`初始化完成`,...Ru(o,s)?{restartHint:Du}:{}})}),e}function $m(e){let t=new nr;return t.onError(qm),t.get(`/`,Jm(e=>{let t=bu();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,Jm(async t=>{let n=await t.req.json();if(typeof n!=`object`||!n||!Array.isArray(n.providers))return t.json({error:`配置格式错误:providers 必须是数组`},400);try{wu(n)}catch(e){if(e instanceof dr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let r=null;try{r=bu()}catch{r=null}return Su(n),e.runtime.rebuild(Cu(n)),t.json({message:`配置已保存并生效`,...Ru(r,n)?{restartHint:Du}:{}})})),t}var eh=`直接回复我 ok,不要思考不要解释`;function th(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function nh(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function rh(e){let t=new nr;t.onError(qm);let n=zt(`test-results.json`),r=zt(`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)),`${th(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:nh(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`,Jm(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,Jm(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,Jm(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:eh}],max_tokens:16}:t===`openai-responses`?{model:e,input:eh}:{model:e,messages:[{role:`user`,content:eh}]}}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`,...nh(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${th(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=bu();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=ku(),i=Fm(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 ih=Td(`latency_probes`,{id:Sd().primaryKey({autoIncrement:!0}),model:xd().notNull(),time:Sd().notNull(),latency_ms:Sd().notNull(),ok:Sd().notNull(),error:xd()},[wd(`idx_latency_probes_model_time`).on(`model`,`time`),wd(`idx_latency_probes_time`).on(`time`)]),ah=2592e6,oh=null;function sh(){let e=oh;if(e!==null)return e;let t=pf(`latency`);return t.createTables([ih]),oh=t,t}function ch(){return sh().native}function lh(e){if(e.length!==0)try{sh().insert(ih).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 uh(){let e=Date.now()-ah;return sh().select(ih).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(q.gt(ih.time,e)).orderBy(q.asc(ih.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 dh(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=sh().select(ih).columns([`time`,`latency_ms`,`ok`]).where(q.and(q.eq(ih.model,e),q.gt(ih.time,a),q.lte(ih.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 fh(){let e=sh().select(ih).columns({t:q.max(ih.time)}).get();return e?.t==null?null:Number(e.t)}function ph(e){try{let t=Date.now()-e;sh().delete(ih).where(q.lte(ih.time,t)).run()}catch(e){B(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var mh=3e4,hh=4,gh=!1;function _h(){return gh}async function vh(e){let t=th((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?nh(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:eh}],max_tokens:1}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:eh,max_output_tokens:16}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:eh}],max_tokens:1});let a=Date.now();try{let t=await fetch(r,{method:`POST`,headers:n,body:JSON.stringify(i),signal:AbortSignal.timeout(mh)}),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 yh(e){let t=[],n=0,r=Array.from({length:Math.max(1,Math.min(hh,e.length))},async()=>{for(;;){let r=n++;if(r>=e.length)return;t.push(await vh(e[r]))}});return await Promise.all(r),t}function bh(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function xh(e){if(gh)return!1;gh=!0;try{let t=await yh(bh(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));lh(t),ph(ah);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{gh=!1}}function Sh(e){return bh(e).length}var Ch=[{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 wh(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 Ch){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 Th(e){let t=new nr;return t.get(`/history`,t=>{let n=uh(),r=Date.now();return t.json({running:_h(),lastRunAt:fh(),models:wh(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=dh(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>_h()?t.json({ok:!1,error:`测试进行中,请稍候`},409):Sh(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(xh(e),t.json({ok:!0,running:!0}))),t}function Eh(e){let t=0;if(!f(e))return 0;for(let n of g(e)){let r=E(e,n),i;try{i=b(r)}catch{continue}i.isDirectory()?t+=Eh(r):t+=i.size}return t}function Dh(){return Math.round(Eh(vt())/1024/1024*10)/10}function Oh(){let e=new nr;return e.onError(qm),e.get(`/`,Jm(e=>{let t=e.req.query(),n=vp({startDate:t.startDate,endDate:t.endDate,model:t.model});return e.json({...n,logStorageMB:Dh()})})),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 kh(e){return typeof e==`string`?e:null}function Ah(e,t){let n=t;for(;n<e.length&&/\s/.test(e[n]);)n+=1;return n}function jh(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 Mh(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=jh(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 Nh(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===`"`||r===`'`||r==="`"){let r=jh(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 Ph(e){let t;try{t=JSON.parse(Nh(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 Fh(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function Ih(e,t){let n=Fh(e,t);return n===void 0?void 0:e[n]}function Lh(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 Rh(e){let t=new Map;for(let n of e){let e=Fh(n.headers,`cookie`);if(e===void 0)continue;let r=zh(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if(Fh(e.headers,`cookie`)!==void 0)return e;let n=zh(e.url),r=n===``?void 0:t.get(n);return r===void 0?e:{...e,headers:{...e.headers,[r.key]:r.value}}})}function zh(e){try{return new URL(e).hostname.toLowerCase()}catch{return``}}function Bh(e,t){let n=jh(e,Ah(e,t));if(n===null)return null;let r=n.value,i=Ah(e,n.end);if(e[i]!==`,`)return{url:r,method:`GET`,headers:{},body:null};let a=Mh(e,Ah(e,i+1));if(a===null)return{url:r,method:`GET`,headers:{},body:null};let o=Ph(a.raw);if(o===null)throw Error(`无法解析 fetch 的 options 对象(可能复制不完整,请重新复制完整的 fetch 调用)`);return{url:r,method:o.method,headers:o.headers,body:o.body}}function Vh(e){let t=[],n=/\bfetch\s*\(/g,r;for(;(r=n.exec(e))!==null;){let n=Bh(e,r.index+r[0].length);n!==null&&t.push(n)}return Rh(t)}function Hh(e){return e.some(e=>Fh(e.headers,`cookie`)!==void 0)}var Uh=0xe8d4a51000,Wh=3e4;function Gh(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 Kh(e,t){let n=await fetch(e,{...t,headers:Gh(t.headers),signal:AbortSignal.timeout(Wh)});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 qh(e){return e===null||e<=0?null:Math.round(e<Uh?e*1e3:e)}function Jh(e){return Math.round(e*100)/100}function Yh(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function Xh(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function Zh(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:qh(Z(n[t.resetAt])),exceeded:a}}var Qh=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await Kh(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await Kh(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},$h=`https://api.commandcode.ai`,eg=`/alpha/billing/credits`,tg=`/alpha/usage/summary`,ng=`/alpha/billing/subscriptions`,rg={"individual-pro-v1":80,"individual-goat":70},ig=/^user_[A-Za-z0-9_-]+$/,ag={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function og(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:Yh(t)}]}function sg(e){let t=kh(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var cg=class extends Qh{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=ig;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!ig.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super($h,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(tg),this.get(eg),this.get(ng).catch(()=>null)]),r=X(t.windowLimits),i=X(t.credits),a=n===null?null:X(n.data),o=a===null?null:kh(a.planId),s=o===null?null:rg[o]??null,c=i===null?null:Z(i.monthlyCredits),l=s===null||c===null?null:{used:Jh(Math.max(0,s-c)),cap:s,resetAt:a===null?null:sg(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:Zh(r.fiveHour,ag),weekly:r===null?null:Zh(r.weekly,ag),monthly:l,totalTokens:Z(e.totalTokens),totalRuns:Z(e.totalCount),voucherBalance:null,balance:null,extraStats:og(l,c)}}},lg=`platform.deepseek.com`,ug=`/api/v0/users/get_user_summary`,dg=`/api/v0/usage/by_api_key/cost`,fg=`/api/v0/usage/by_api_key/amount`,pg=86400;function mg(e){let t=Z(e);if(t!==null)return t;let n=kh(e);if(n!==null&&n.trim()!==``){let e=Number(n);if(Number.isFinite(e))return e}return null}function hg(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 gg(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+pg),tz:String(n)}}function _g(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=mg(e.balance)??mg(e.amount),i=kh(e.currency);r!==null&&i!==null&&i!==``&&t.set(i,(t.get(i)??0)+r)}return t}var vg=class extends Qh{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static hosts=[lg];static apiHosts=[`api.deepseek.com`];static credentialSource=`fetchText`;constructor(e){let t=Vh(e).find(e=>zh(e.url)===lg);if(t===void 0)throw Error(`未找到 DeepSeek 平台请求:请在已登录的 DeepSeek 开放平台(platform.deepseek.com)的用量页面里复制接口请求的 fetch 调用粘贴进来`);if(Ih(t.headers,`cookie`)===void 0&&Ih(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=kh(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=gg(e);try{let e=X((await this.get(dg,`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:kh(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:mg(t.cost);i!==null&&r.set(n,(r.get(n)??0)+i)}}}let i=hg(r);return i===null?null:{cost:Jh(i.amount),currency:i.currency}}catch{return null}}async#t(e){let t=gg(e);try{let e=X((await this.get(fg,`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:mg(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(ug).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=hg(_g(t.normal_wallets));e!==null&&(a=Jh(e.amount));let n=hg(_g(t.total_costs));n!==null&&(o=Jh(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}}},yg=`/api/user/self`,bg=`/api/user/subscription/current_cycle`,xg={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function Sg(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 Cg(e){return e===null||Z(e.total_count)===null?null:Zh(e,xg)}function wg(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 Tg(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var Eg=class extends Qh{static vendorId=`sense-audio`;static vendorLabel=`SenseAudio`;static hosts=[`platform.senseaudio.cn`];static apiHosts=[`api.senseaudio.cn`];static credentialSource=`fetchText`;constructor(e){let t=Vh(e),n=Tg(t,yg),r=Tg(t,bg);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>Ih(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(yg),this.get(bg).catch(()=>null)]),n=Cg(Sg(e,`credit_5h_limit`)),r=Cg(Sg(e,`credit_7d_limit`)),i=Cg(Sg(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:qh(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:wg(e),balance:null}}},Dg=`GetAgentPlanAFPUsage`,Og=`GetAgentPlanUsageDetails`,kg=`console.volcengine.com`,Ag=`2024-01-01`,jg=`cn-beijing`,Mg={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function Ng(e){return e.find(e=>e.url.includes(Dg))}function Pg(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??jg}/${Ag}`:t}function Fg(e){return e.find(e=>zh(e.url)===kg)}var Ig=class extends Qh{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=Vh(e),n=Ng(t)??Fg(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!Hh(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==kg)throw Error(`非方舟控制台域`);r=e.origin,i=Pg(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=Lh(Ih(n.headers,`cookie`),`csrfToken`)??Ih(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}/${Dg}`,this.#t=`${i}/${Og}`}envelope(e){let t=X(e.ResponseMetadata),n=t===null?null:X(t.Error);if(n!==null){let e=kh(n.Code)??`Unknown`,t=kh(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=Zh(e.AFPFiveHour,Mg),n=Zh(e.AFPWeekly,Mg),r=Zh(e.AFPMonthly,Mg);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:Xh(new Date(n)),EndTime:Xh(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}}},Lg=`/api/biz/account/query-customer-account-report`,Rg=`/api/finance/expenseBill/expenseBillListByDay`,zg=200,Bg=`bigmodel_token_production`;function Vg(e){let t=Lh(Ih(e.headers,`cookie`),Bg);if(t!==null&&t.trim()!==``)return t.trim();let n=Ih(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var Hg=class extends Qh{static vendorId=`zhipu-bigmodel`;static vendorLabel=`智谱 BigModel`;static hosts=[`bigmodel.cn`];static apiHosts=[`open.bigmodel.cn`];static credentialSource=`fetchText`;constructor(e){let t=Vh(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=Vg(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=kh(e.msg)??`未知错误`;throw Error(`上游业务错误 ${n}(code ${t===null?`未知`:String(t)})——多为登录凭据失效,请在 bigmodel.cn 重新登录后复制`)}return e}async#e(){let e=new Date,t=Xh(e).slice(0,7),n=Xh(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(Rg,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String(zg)}`),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=kh(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(Lg),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:Wg(n)}}};function Ug(e){return`${Yh(e)} 元`}function Wg(e){let t=[],n=Z(e.rechargeAmount);n!==null&&t.push({label:`累计充值`,value:Ug(n)});let r=Z(e.giveAmount);r!==null&&t.push({label:`赠送金额`,value:Ug(r)});let i=Z(e.creditBalance);return i===null?e.creditStatus===`NOT_OPEN`&&t.push({label:`信用余额`,value:`未开通`}):t.push({label:`信用余额`,value:Ug(i)}),t}var Gg=[cg,vg,Eg,Ig,Hg];function Kg(){return Gg}function qg(e){let t=new Set;for(let n of Vh(e)){let e=zh(n.url);e!==``&&t.add(e)}return t}function Jg(e){if(e===void 0)return null;let t=zh(e);if(t===``)return null;for(let e of Gg)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function Yg(e,t){let n=Jg(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 Xg(e,t){let n=e.trim();for(let e of Gg)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(n)===!0)return e;if(t!==void 0){let e=zh(t);if(e!==``){for(let t of Gg)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let r=qg(e);for(let e of Gg)if(e.credentialSource===`fetchText`&&e.hosts?.some(e=>r.has(e))===!0)return e;return null}function Zg(e,t){if(e.trim()===``)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);let n=Xg(e,t);if(n===null){let e=Gg.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=Gg.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=Jg(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:n.vendorId,vendor:new n(e)}}var Qg=zt(`quota.json`);function $g(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 e_(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 t_(e){let t=X(e);if(t===null)return null;let n=e_(t.cost),r=e_(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 n_(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 r_(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:$g(t.fiveHour),weekly:$g(t.weekly),monthly:$g(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:e_(o),totalCostCurrency:typeof s==`string`&&s!==``?s:null,today:t_(t.today),yesterday:t_(t.yesterday),extraStats:n_(t.extraStats)}}function i_(e){let t=X(Qg.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:r_(t.snapshot)??void 0,fetchedAt:typeof i==`number`&&Number.isFinite(i)?i:void 0,error:typeof a==`string`&&a!==``?a:void 0}}function a_(e,t){Qg.set(e,t)}function o_(e){Qg.get(e)!==void 0&&Qg.set(e,void 0)}function s_(){let e=Qg.getAll(),t={};for(let n of Object.keys(e)){let e=i_(n);e!==null&&(t[n]=e)}return t}function c_(e,t,n,r){a_(e,{fetchText:i_(e)?.fetchText,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function l_(e,t){let n=i_(e);if(n===null){a_(e,{error:t});return}a_(e,{...n,error:t})}var u_=!1;function d_(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function f_(e){if(!e.startsWith(`os.environ/`))return e;let t=process.env[e.slice(11)];return t===void 0||t===``?void 0:t}function p_(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:f_(r)}}function m_(){try{let e=bu();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,p_(n))}return t}catch{return null}}function h_(e){return m_()?.get(e)??null}async function g_(e){try{let t=h_(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(Jg(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=Yg(t.apiKey,t.apiBase))}else{let i=i_(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=Zg(i,t.apiBase))}let i=await r.fetchQuota();c_(e,n,i,Date.now())}catch(t){l_(e,d_(t))}return i_(e)}function __(){let e=m_();return e===null?null:new Set(e.keys())}async function v_(){if(!u_){u_=!0;try{let e=m_(),t=e===null?[]:[...e.entries()].filter(([,e])=>Jg(e.apiBase)!==null).map(([e])=>e);for(let e of t)await g_(e);let n=__();for(let[e,r]of Object.entries(s_()))if(r.fetchText!==void 0){if(n!==null&&!n.has(e)){o_(e);continue}t.includes(e)||await g_(e)}}catch(e){B(`[quota] 刷新失败:`,d_(e))}finally{u_=!1}}}async function y_(e){let t=(await Vm(e))?.fetchText;return typeof t==`string`?t:null}function b_(){return Kg().map(e=>({vendorId:e.vendorId,vendorLabel:e.vendorLabel,hosts:e.hosts??[],apiHosts:e.apiHosts??[],credentialSource:e.credentialSource}))}function x_(){let e=new nr;return e.get(`/`,e=>e.json({ok:!0,vendors:b_(),providers:s_()})),e.get(`/vendors`,e=>e.json({ok:!0,vendors:b_()})),e.put(`/:provider`,async e=>{let t=e.req.param(`provider`);if(Jg(h_(t)?.apiBase)!==null)return e.json({ok:!1,error:`该供应商自动使用配置里的 apiKey 查询额度,无需手动配置`},400);let n=await y_(e);if(n===null)return e.json({ok:!1,error:`请求体需为 {"fetchText": "..."}`},400);let r=i_(t);a_(t,{fetchText:n,vendorId:r?.vendorId,snapshot:r?.snapshot,fetchedAt:r?.fetchedAt,error:void 0});let i=await g_(t);return e.json({ok:!0,entry:i})}),e.delete(`/:provider`,e=>(o_(e.req.param(`provider`)),e.json({ok:!0}))),e.post(`/:provider/refresh`,async e=>{let t=await g_(e.req.param(`provider`));return e.json({ok:!0,entry:t})}),e}function S_(e,t){let n=new nr;return n.get(`/`,n=>n.json({listenPort:Fm(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},masterKeySet:ku()!==``})),n}var C_=864e5,w_=3e5,T_=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,E_=new Map;try{let e=h(bt(),`utf-8`),t=JSON.parse(e);for(let[e,n]of Object.entries(t)){let{_ts:t,...r}=n;E_.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function D_(){try{let e={};for(let[t,{value:n,at:r}]of E_)e[t]={...n,_ts:r};S(bt(),JSON.stringify(e))}catch(e){B(`保存 IP 缓存失败:`,e.message)}}function O_(e){let t=E_.get(e);if(!t)return null;let n=t.value.error===void 0?C_:w_;return Date.now()-t.at>=n?(E_.delete(e),null):t.value}async function k_(e){let t=O_(e);if(t)return t;let n=await(await fetch(T_.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(n.status!==`success`){let t={error:n.message||`查询失败`};return E_.set(e,{value:t,at:Date.now()}),t}let r={country:n.country,region:n.regionName,city:n.city,isp:n.isp};return E_.set(e,{value:r,at:Date.now()}),D_(),r}function A_(e){return{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}}function j_(){let e=new nr;return e.onError(qm),e.get(`/dates`,e=>{let t=yp();return e.json({dates:t})}),e.get(`/clients`,e=>{let t=bp();return e.json({clients: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 k_(t);return e.json({ip:t,...n})}catch(e){throw new Km(502,e.message)}}),e.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=ap(t);return n||=(await Rp(),ap(t)??ld(Number(t))),n?e.json(n):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),e.get(`/`,Jm(async e=>{let t=e.req.query(),n=_p({...A_(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=Tp({...A_(t),keyword:r,sort:t.sort,order:t.order,page:t.page,pageSize:t.pageSize})),e.json({...n,items:n.items.map(e=>({...e,user_agent:Xu(e.headers)}))})})),e.get(`/sessions`,Jm(e=>{let t=e.req.query(),n=Cp({...A_(t),page:t.page,pageSize:t.pageSize});return e.json(n)})),e.post(`/clear`,Jm(async e=>{await Bp();let t=ad().length;t>0&&pt(`[logs] 清空前 spool 仍有 ${String(t)} 条未入库,这些记录可能在入库后重现`);let n=e.req.query(),r=Dp(A_(n));return z(`[logs] 已清理筛选日志 ${r} 条(筛选: ${JSON.stringify(n)})`),e.json({deleted:r})})),e}var M_=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})),N_=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}})),P_=L(((e,t)=>{var n=R(`os`),r=M_(),i=N_(),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})),F_=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})),I_=L(((e,t)=>{var n=R(`os`),r=R(`fs`),i=R(`child_process`).exec,a=F_();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))})}})),L_=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)}})),R_=L(((e,t)=>{var n=R(`fs`),r=R(`path`),i=I_(),a=F_(),o=N_(),s=null,c=L_().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})),z_=L(((e,t)=>{var n=R(`os`),r=M_(),i=N_();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})),B_=L(((e,t)=>{var n=R(`os`),r=M_(),i=N_();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})),V_=L(((e,t)=>{var n=R(`fs`),r=R(`os`),i=R(`child_process`).spawn,a={ps:()=>P_(),procfile:()=>R_(),wmic:()=>z_(),gwmi:()=>B_()},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})),H_=Se(L(((e,t)=>{var n=V_();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=N_().clear}))(),1);function U_(e){return`http://127.0.0.1:${String(e.port)}`}function W_(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 G_(e){try{let t=await(0,H_.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 K_(e){let t=new nr;return t.get(`/status`,async t=>t.json({ok:!0,running:!0,pid:process.pid,status:`online`,uptime:e.startedAt,gatewayBase:U_(e)})),t.get(`/processes`,async t=>{let n=await G_(process.pid);return t.json({ok:!0,processes:[W_({pid:process.pid,status:`online`,port:e.port,startedAt:e.startedAt,memory:n.memory,cpu:n.cpu})]})}),t}var q_=`ezllm-autostart.vbs`,J_=`ezllm-autostart.cmd`,Y_=`com.ezllm.autostart`,X_=`ezllm.service`,Z_=`autostart.opt-out`,Q_=`ezllm-v2`,$_=`Auto-generated by "ezllm autostart on" (${Q_}). Disable with "ezllm autostart off".`,ev=`ELLM_`,tv=new Set([`WEBUI_USERNAME`,`WEBUI_PASSWORD`,`HOST`]);function nv(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(n.startsWith(ev)||tv.has(n))&&(t[n]=r);return t}function rv(e){return E(e,Z_)}function iv(){let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return E(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)}function av(){return E(iv(),q_)}function ov(){return E(t(),`Library`,`LaunchAgents`,`${Y_}.plist`)}function sv(){return E(t(),`.config`,`systemd`,`user`,X_)}function cv(e,t){return new Promise(n=>{let r=de(e,t,{stdio:`ignore`,shell:!1});r.on(`error`,()=>n(127)),r.on(`exit`,e=>n(e??1))})}var lv={win32:{itemPath:av,on:Sv,off:Tv},darwin:{itemPath:ov,on:Cv,off:Ev},linux:{itemPath:sv,on:wv,off:Dv}};function uv(e){return lv[e]??null}function dv(e){let t=uv(e);if(!t)throw Error(`暂不支持的平台: ${e}。`);return t}function fv(){return uv(r())?.itemPath()??null}function pv(e,t){return[e,t.entryJs,...t.args??[]]}function mv(e){return E(e,`logs`,`autostart.log`)}function hv(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`)}function gv(e,t){let n=/["%\r\n]/;if(n.test(e)||n.test(t))throw Error(`环境变量 ${e} 的键/值含 cmd 无法安全转义的字符(" % 或换行),已拒绝写入自启项;请调整该变量后重试 ezllm autostart on`)}function _v(e,t){let n=mv(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${$_}`,...Object.entries(t.env).map(([e,t])=>(gv(e,t),`set "${e}=${t}"`)),`>> "${n}" echo [%date% %time%] autostart launching.`,`${pv(e,t).map(e=>`"${e}"`).join(` `)} >> "${n}" 2>&1`,``].join(`\r
|
|
79
|
-
`)}
|
|
80
|
-
`)}function
|
|
81
|
-
`),
|
|
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">`,`<!-- ${
|
|
83
|
-
`)}function
|
|
84
|
-
`),r=
|
|
85
|
-
`)}async function xv(e,t,n=cv){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 Sv(e,t){let n=av(),r=E(t.appDir,J_);return S(r,_v(e,t),`utf-8`),await xv(n,`\uFEFF${vv(r)}`),n}async function Cv(e,t){let n=ov();S(n,yv(e,t),`utf-8`),await cv(`launchctl`,[`unload`,n]);let r=await cv(`launchctl`,[`load`,n]);if(r!==0)throw Error(`launchctl load 失败(退出码 ${String(r)})。请手动执行: launchctl load "${n}"`);return n}async function wv(e,t){let n=sv();p(T(n),{recursive:!0}),S(n,bv(e,t),`utf-8`);let r=await cv(`systemctl`,[`--user`,`daemon-reload`]);if(r!==0)throw Error(`systemctl --user daemon-reload 失败(退出码 ${String(r)})。当前环境可能无 systemd(WSL/容器),请手动启用或删除: ${n}`);let i=await cv(`systemctl`,[`--user`,`enable`,X_]);if(i!==0)throw Error(`systemctl --user enable 失败(退出码 ${String(i)})。请手动执行: systemctl --user enable ${X_}`);return n}async function Tv(e){let t=av(),n=f(t);return v(t,{force:!0}),v(E(e,J_),{force:!0}),n}async function Ev(){let e=ov();return f(e)?(await cv(`launchctl`,[`unload`,e]),v(e,{force:!0}),!0):!1}async function Dv(){let e=sv();return f(e)?(await cv(`systemctl`,[`--user`,`disable`,X_]),v(e,{force:!0}),await cv(`systemctl`,[`--user`,`daemon-reload`]),!0):!1}function Ov(e){let t=h(e);return t.length>=2&&t[0]===255&&t[1]===254?t.toString(`utf16le`).slice(1):t.toString(`utf-8`)}function kv(e){let t=fv(),n=!1;if(t&&f(t))try{n=Ov(t).includes(Q_)}catch{}return{platform:r(),enabled:n,itemPath:t,optOut:f(rv(e))}}async function Av(e){let t=dv(r());p(E(e.appDir,`logs`),{recursive:!0});let n=await t.on(e.nodePath,e);return v(rv(e.appDir),{force:!0}),{itemPath:n}}async function jv(e){let t=await dv(r()).off(e.appDir);return p(e.appDir,{recursive:!0}),S(rv(e.appDir),new Date().toISOString(),`utf-8`),{removed:t}}var Mv=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})),Nv=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})),Pv=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})),Fv=L(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=Pv(),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})),Iv=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})),Lv=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}})),Rv=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}}})),zv=L(((e,t)=>{var n=Rv();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}})),Bv=L(((e,t)=>{var n=zv(),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})),Vv=L(((e,t)=>{var n=zv(),r=Bv(),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)}})),Hv=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}})),Uv=L(((e,t)=>{var{constants:n}=R(`buffer`),r=Vv(),i=Hv(),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})),Wv=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}}}})),Gv=L(((e,t)=>{t.exports=e=>{let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}})),Kv=L(((e,t)=>{var n=R(`stream`).Readable,r=Gv();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)}}})),qv=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])}})),Jv=L(((e,t)=>{var n=R(`stream`).PassThrough,r=qv();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)}})),Yv=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})}})),Xv=L(((e,t)=>{var n=R(`events`),r=Yv(),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()}}})),Zv=L(((e,t)=>{var n=R(`events`),r=R(`url`),i=Lv(),a=Uv(),o=Wv(),s=Kv(),c=Gv(),l=Jv(),u=Xv(),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})),Qv=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}})),$v=L(((e,t)=>{var{Transform:n,PassThrough:r}=R(`stream`),i=R(`zlib`),a=Qv();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}})),ey=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)}}})),ty=L(((e,t)=>{var n=R(`events`),r=R(`tls`),i=R(`http2`),a=ey(),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 _}})),ny=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()}}})),ry=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}})),iy=L(((e,t)=>{t.exports=(e,t,n)=>{for(let r of n)e.on(r,(...e)=>t.emit(r,...e))}})),ay=L(((e,t)=>{t.exports=e=>{switch(e){case`:method`:case`:scheme`:case`:authority`:case`:path`:return!0;default:return!1}}})),oy=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]}]`)})),sy=L(((e,t)=>{var n=R(`http2`),{Writable:r}=R(`stream`),{Agent:i,globalAgent:a}=ty(),o=ny(),s=ry(),c=iy(),l=ay(),{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}=oy(),{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){}}})),cy=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)}})()})})),ly=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}})),uy=L(((e,t)=>{var n=R(`http`),r=R(`https`),i=cy(),a=ey(),o=sy(),s=ly(),c=ry(),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})),dy=L(((e,t)=>{var n=R(`http2`),r=ty(),i=sy(),a=ny(),o=uy(),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}})),fy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Mv();e.default=e=>t.default.nodeStream(e)&&t.default.function_(e.getBoundary)})),py=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=R(`fs`),n=R(`util`),r=Mv(),i=fy(),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}}})),my=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})),hy=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}}}})),gy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TimeoutError=void 0;var t=R(`net`),n=hy(),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}})),_y=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Mv();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}})),vy=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}})),yy=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)}}})),by=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(``))}})),xy=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`)}})),Sy=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}})),Cy=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`}))}})),wy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Mv();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}})),Ty=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}})),Ey=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=Fv(),l=Iv(),u=Zv(),d=$v(),f=dy(),p=Gv(),m=Mv(),h=py(),g=fy(),_=my(),v=gy(),y=_y(),b=vy(),x=yy(),S=by(),C=xy(),w=Sy(),T=Cy(),E=wy(),D=Ty(),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(`
|
|
77
|
+
LIMIT ${tp}
|
|
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>=np&&(n(r,s),s.length=0))}n(r,s),e.onProgress?.(`已扫描到 id ${String(a)}:写入 ${String(i.filled)} 行(累计)`)}return i}async function ip(e){let t=()=>{for(let e of vt())if(l(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}:(ct(`[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 ap(e){return st.PORT??e.port}async function op(e,t,n={}){let r=new hl({config:e,traceSink:n.traceSink,deps:{randomId:()=>String(Cd())}});t.register(r),await ip(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 Kn},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 sp=64;function cp(e,t={}){let n=e=>e.trim(),r=new Map;function i(e,t){for(r.delete(e),r.set(e,t);r.size>sp;){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 lp=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 up(e){try{let t=await e.req.json();return typeof t==`object`&&t?t:null}catch{return null}}var dp=`配置文件解析失败(可能被截断或损坏),管理台已锁定。请修复或删除配置文件后重试`,fp=new Kn;function pp(e){return Buffer.from(`${e.username}:${e.password}`).toString(`base64`)}fp.post(`/login`,async e=>{let t=jl();if(t.configBroken)return e.json({error:dp},503);if(!t.required)return e.json({error:`当前未设置登录账号,管理台免登录访问(如需启用请先设置账号)`},400);let n=await up(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:pp(t)})});async function mp(e,t){if(e.req.path===`/api/auth/login`)return await t();let n=jl();if(!n.required)return await t();if(n.configBroken)return e.json({error:dp},401);let r=e.req.header(`Authorization`);if(!r||!r.startsWith(`Bearer `))return e.json({error:`未登录`},401);if(r.slice(7)!==pp(n))return e.json({error:`token 无效或已过期`},401);await t()}var hp=class extends Error{status;constructor(e,t){super(t),this.name=`HttpError`,this.status=e}};function gp(e,t){return e instanceof hp?(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 _p(e){return async t=>{try{return await e(t)}catch(e){throw new hp(500,e.message)}}}var vp=8,yp=6;function bp(){let e=()=>{let e=yl();if(e===null)throw new hp(500,`配置文件不存在`);return e},t=new Kn;return t.onError(gp),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=Ml(),n=!1;try{n=Ol()!==``}catch(e){if(!(e instanceof vl))throw e}return e.json({initialized:t.completed,deployment:t.deployment,masterKeySet:n,authRequired:jl().required,version:Dt()})}),t.post(`/master-key`,async t=>{if(Ml().completed)return t.json({error:`已完成初始化,请到设置页修改主密钥`},403);let n=await up(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<vp)return t.json({error:`主密钥至少 ${String(vp)} 位`},400)}else return t.json({error:`mode 必须是 generate 或 custom`},400);let i=e(),a={...i,masterKey:r};return xl(a),t.json({masterKey:r,...Fl(i,a)?{restartHint:El}:{}})}),t.post(`/finish`,async t=>{if(Ml().completed)return t.json({error:`已完成初始化,请到设置页修改`},403);let n=await up(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`&&Ol()===``)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<yp)return t.json({error:`密码至少 ${String(yp)} 位`},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 xl(c),t.json({message:o?`初始化完成,请使用新账号登录`:`初始化完成`,...Fl(s,c)?{restartHint:El}:{}})}),t}function xp(e){let t=new Kn;return t.onError(gp),t.get(`/`,_p(e=>{let t=yl();return t===null?e.json({error:`配置文件不存在`},404):e.json(t)})),t.put(`/`,_p(async t=>{let n=await t.req.json();if(typeof n!=`object`||!n||!Array.isArray(n.providers))return t.json({error:`配置格式错误:providers 必须是数组`},400);try{Cl(n)}catch(e){if(e instanceof tr)return t.json({error:`配置校验失败`,issues:e.issues},400);throw e}let r=null;try{r=yl()}catch{r=null}return xl(n),e.runtime.rebuild(Sl(n)),t.json({message:`配置已保存并生效`,...Fl(r,n)?{restartHint:El}:{}})})),t}var Sp=`直接回复我 ok,不要思考不要解释`;function Cp(e,t){return t&&!/\/v\d+$/i.test(e)?`${e}/v1`:e}function wp(e,t){return t===`anthropic`?{"x-api-key":e,"anthropic-version":`2023-06-01`}:{Authorization:`Bearer ${e}`}}function Tp(e){let t=new Kn;t.onError(gp);let n=Mt(`test-results.json`),r=Mt(`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)),`${Cp(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:wp(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`,_p(e=>e.json(n.getAll()))),t.get(`/models-cache/:keyId`,_p(e=>{let t=e.req.param(`keyId`);return e.json({models:r.get(t)??[]})})),t.post(`/models-cache`,_p(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:Sp}],max_tokens:16}:t===`openai-responses`?{model:e,input:Sp}:{model:e,messages:[{role:`user`,content:Sp}]}}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`,...wp(e.api_key,t)},a=t===`anthropic`?`/messages`:t===`openai-responses`?`/responses`:`/chat/completions`,o=`${Cp(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=yl();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=Ol(),i=ap(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 Ep=xu(`latency_probes`,{id:vu().primaryKey({autoIncrement:!0}),model:_u().notNull(),time:vu().notNull(),latency_ms:vu().notNull(),ok:vu().notNull(),error:_u()},[bu(`idx_latency_probes_model_time`).on(`model`,`time`),bu(`idx_latency_probes_time`).on(`time`)]),Dp=2592e6,Op=null;function kp(){let e=Op;if(e!==null)return e;let t=id(`latency`);return t.createTables([Ep]),Op=t,t}function Ap(){return kp().native}function jp(e){if(e.length!==0)try{kp().insert(Ep).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 Mp(){let e=Date.now()-Dp;return kp().select(Ep).columns([`model`,`time`,`latency_ms`,`ok`,`error`]).where(G.gt(Ep.time,e)).orderBy(G.asc(Ep.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 Np(e,t,n,r){let i=t===`hour`?36e5:864e5,a=r-n*36e5,o=kp().select(Ep).columns([`time`,`latency_ms`,`ok`]).where(G.and(G.eq(Ep.model,e),G.gt(Ep.time,a),G.lte(Ep.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 Pp(){let e=kp().select(Ep).columns({t:G.max(Ep.time)}).get();return e?.t==null?null:Number(e.t)}function Fp(e){try{let t=Date.now()-e;kp().delete(Ep).where(G.lte(Ep.time,t)).run()}catch(e){R(`[latency] 旧记录清理失败:`,e instanceof Error?e.message:String(e))}}var Ip=3e4,Lp=4,Rp=!1;function zp(){return Rp}function Bp(e){return e.current.expanded.deployments.names.map(t=>e.current.expanded.deployments.byName.get(t)).filter(e=>e!==void 0)}async function Vp(e){let t=async e=>{let t=Cp((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0),n={"Content-Type":`application/json`,...e.headers??{},...e.apiKey?wp(e.apiKey,e.provider):{}},r,i;e.provider===`anthropic`?(r=`${t}/messages`,i={model:e.modelName,messages:[{role:`user`,content:Sp}],max_tokens:1}):e.provider===`openai-responses`?(r=`${t}/responses`,i={model:e.modelName,input:Sp,max_output_tokens:16}):(r=`${t}/chat/completions`,i={model:e.modelName,messages:[{role:`user`,content:Sp}],max_tokens:1});let a=Date.now();try{let t=await fetch(r,{method:`POST`,headers:n,body:JSON.stringify(i),signal:AbortSignal.timeout(Ip)}),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(Lp,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(Rp)return!1;Rp=!0;try{let t=await n(Bp(e).map(e=>({name:e.name,provider:e.provider,modelName:e.modelName,apiKey:e.apiKey,apiBase:e.apiBase,autoV1:e.autoV1,headers:e.headers})));jp(t),Fp(Dp);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{Rp=!1}}function Hp(e){return Bp(e).length}var Up=[{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 Wp(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 Up){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 Gp(e){let t=new Kn;return t.get(`/history`,t=>{let n=Mp(),r=Date.now();return t.json({running:zp(),lastRunAt:Pp(),models:Wp(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=Np(t,n,n===`hour`?24:720,Date.now());return e.json({model:t,granularity:n,buckets:r})}),t.post(`/run`,t=>zp()?t.json({ok:!1,error:`测试进行中,请稍候`},409):Hp(e)===0?t.json({ok:!1,error:`当前配置没有任何模型部署`},400):(Vp(e),t.json({ok:!0,running:!0}))),t}function Kp(){let e=t=>{let n=0;if(!l(t))return 0;for(let r of p(t)){let i=E(t,r),a;try{a=_(i)}catch{continue}a.isDirectory()?n+=e(i):n+=a.size}return n},t=()=>Math.round(e(ft())/1024/1024*10)/10,n=new Kn;return n.onError(gp),n.get(`/`,_p(e=>{let n=e.req.query(),r=tf({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 qp(e){return typeof e==`string`?e:null}function Jp(e,t){let n=t.toLowerCase();return Object.keys(e).find(e=>e.toLowerCase()===n)}function Yp(e,t){let n=Jp(e,t);return n===void 0?void 0:e[n]}function Xp(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 Zp(e){try{return new URL(e).hostname.toLowerCase()}catch{return``}}function Qp(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=Jp(n.headers,`cookie`);if(e===void 0)continue;let r=Zp(n.url);r!==``&&!t.has(r)&&t.set(r,{key:e,value:n.headers[e]})}return e.map(e=>{if(Jp(e.headers,`cookie`)!==void 0)return e;let n=Zp(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 $p(e){return e.some(e=>Jp(e.headers,`cookie`)!==void 0)}var em=0xe8d4a51000,tm=3e4;async function nm(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(tm)});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 rm(e){return e===null||e<=0?null:Math.round(e<em?e*1e3:e)}function im(e){return Math.round(e*100)/100}function am(e){return Number.isInteger(e)?String(e):e.toFixed(2)}function om(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function sm(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:rm(Y(n[t.resetAt])),exceeded:a}}var cm=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async get(e,t){let n=await nm(`${this.#e}${e}${t===void 0?``:`?${t}`}`,{method:`GET`,headers:this.#t});return this.envelope(n)}async post(e,t){let n=await nm(`${this.#e}${e}`,{method:`POST`,headers:{...this.#t,"content-type":`application/json`},body:JSON.stringify(t)});return this.envelope(n)}envelope(e){return e}},lm=`https://api.commandcode.ai`,um=`/alpha/billing/credits`,dm=`/alpha/usage/summary`,fm=`/alpha/billing/subscriptions`,pm={"individual-pro-v1":80,"individual-goat":70},mm=/^user_[A-Za-z0-9_-]+$/,hm={used:`used`,cap:`cap`,resetAt:`resetAt`,exceeded:`exceeded`};function gm(e,t){return e!==null||t===null?null:[{label:`月额度剩余`,value:am(t)}]}function _m(e){let t=qp(e);if(t===null)return null;let n=Date.parse(t);return Number.isFinite(n)&&n>0?n:null}var vm=class extends cm{static vendorId=`command-code`;static vendorLabel=`CommandCode`;static apiHosts=[`api.commandcode.ai`];static apiKeyPattern=mm;static credentialSource=`apiKey`;constructor(e){let t=e.trim();if(!mm.test(t))throw Error(`apiKey 不是 CommandCode 的 API key(应为 Studio 生成的 user_… 形态)——请在 CommandCode Studio 创建 API key 后填入该供应商的 apiKey 字段`);super(lm,{authorization:`Bearer ${t}`,accept:`application/json`})}async fetchQuota(){let[e,t,n]=await Promise.all([this.get(dm),this.get(um),this.get(fm).catch(()=>null)]),r=J(t.windowLimits),i=J(t.credits),a=n===null?null:J(n.data),o=a===null?null:qp(a.planId),s=o===null?null:pm[o]??null,c=i===null?null:Y(i.monthlyCredits),l=s===null||c===null?null:{used:im(Math.max(0,s-c)),cap:s,resetAt:a===null?null:_m(a.currentPeriodEnd),exceeded:c<=0};return{fiveHour:r===null?null:sm(r.fiveHour,hm),weekly:r===null?null:sm(r.weekly,hm),monthly:l,totalTokens:Y(e.totalTokens),totalRuns:Y(e.totalCount),voucherBalance:null,balance:null,extraStats:gm(l,c)}}},ym=`platform.deepseek.com`,bm=`/api/v0/users/get_user_summary`,xm=`/api/v0/usage/by_api_key/cost`,Sm=`/api/v0/usage/by_api_key/amount`,Cm=86400;function wm(e){let t=Y(e);if(t!==null)return t;let n=qp(e);if(n!==null&&n.trim()!==``){let e=Number(n);if(Number.isFinite(e))return e}return null}function Tm(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 Em(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+Cm),tz:String(n)}}function Dm(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=wm(e.balance)??wm(e.amount),i=qp(e.currency);r!==null&&i!==null&&i!==``&&t.set(i,(t.get(i)??0)+r)}return t}var Om=class extends cm{static vendorId=`deepseek`;static vendorLabel=`DeepSeek`;static hosts=[ym];static apiHosts=[`api.deepseek.com`];static credentialSource=`fetchText`;constructor(e){let t=Qp(e).find(e=>Zp(e.url)===ym);if(t===void 0)throw Error(`未找到 DeepSeek 平台请求:请在已登录的 DeepSeek 开放平台(platform.deepseek.com)的用量页面里复制接口请求的 fetch 调用粘贴进来`);if(Yp(t.headers,`cookie`)===void 0&&Yp(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=qp(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=Em(e);try{let e=J((await this.get(xm,`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:qp(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:wm(t.cost);i!==null&&r.set(n,(r.get(n)??0)+i)}}}let i=Tm(r);return i===null?null:{cost:im(i.amount),currency:i.currency}}catch{return null}}async#t(e){let t=Em(e);try{let e=J((await this.get(Sm,`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:wm(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(bm).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=Tm(Dm(t.normal_wallets));e!==null&&(a=im(e.amount));let n=Tm(Dm(t.total_costs));n!==null&&(o=im(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}}},km=`/api/user/self`,Am=`/api/user/subscription/current_cycle`,jm={used:`used_count`,cap:`total_count`,resetAt:`reset_time`};function Mm(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 Nm(e){return e===null||Y(e.total_count)===null?null:sm(e,jm)}function Pm(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 Fm(e,t){return e.find(e=>{try{return new URL(e.url).pathname===t}catch{return!1}})}var Im=class extends cm{static vendorId=`sense-audio`;static vendorLabel=`SenseAudio`;static hosts=[`platform.senseaudio.cn`];static apiHosts=[`api.senseaudio.cn`];static credentialSource=`fetchText`;constructor(e){let t=Qp(e),n=Fm(t,km),r=Fm(t,Am);if(n===void 0&&r===void 0)throw Error(`未找到额度查询请求:请粘贴 user/self、user/subscription/current_cycle 任一接口的 fetch 调用(其余会自动补上)`);if(!t.some(e=>Yp(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(km),this.get(Am).catch(()=>null)]),n=Nm(Mm(e,`credit_5h_limit`)),r=Nm(Mm(e,`credit_7d_limit`)),i=Nm(Mm(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:rm(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:Pm(e),balance:null}}},Lm=`GetAgentPlanAFPUsage`,Rm=`GetAgentPlanUsageDetails`,zm=`console.volcengine.com`,Bm=`2024-01-01`,Vm=`cn-beijing`,Hm={used:`Used`,cap:`Quota`,resetAt:`ResetTime`};function Um(e){return e.find(e=>e.url.includes(Lm))}function Wm(e){let t=/^(\/api\/top\/ark\/[^/]+\/[^/]+)\//.exec(e.pathname)?.[1];return t===void 0?`/api/top/ark/${/\/region:([^/:]+)/.exec(e.pathname)?.[1]??Vm}/${Bm}`:t}function Gm(e){return e.find(e=>Zp(e.url)===zm)}var Km=class extends cm{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=Qp(e),n=Um(t)??Gm(t);if(n===void 0)throw Error(`未找到可用的火山方舟请求:请在已登录的方舟控制台(console.volcengine.com)里复制任意请求的 fetch 调用粘贴进来——「订阅套餐」页本身的请求或 GetAgentPlanAFPUsage 接口都可以,AFP 端点会自动换算`);if(!$p(t))throw Error(`复制的请求里没有 Cookie(浏览器复制出的 fetch 通常不含它)——请改用「Copy as cURL」再粘贴,或手动在 headers 中补上 cookie 字段`);let r,i;try{let e=new URL(n.url);if(e.hostname.toLowerCase()!==zm)throw Error(`非方舟控制台域`);r=e.origin,i=Wm(e)}catch{throw Error(`粘贴的请求不是火山方舟控制台(console.volcengine.com)的请求,无法换算出 AFP 用量端点`)}let a=Xp(Yp(n.headers,`cookie`),`csrfToken`)??Yp(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}/${Lm}`,this.#t=`${i}/${Rm}`}envelope(e){let t=J(e.ResponseMetadata),n=t===null?null:J(t.Error);if(n!==null){let e=qp(n.Code)??`Unknown`,t=qp(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=sm(e.AFPFiveHour,Hm),n=sm(e.AFPWeekly,Hm),r=sm(e.AFPMonthly,Hm);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:om(new Date(n)),EndTime:om(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}}},qm=`/api/biz/account/query-customer-account-report`,Jm=`/api/finance/expenseBill/expenseBillListByDay`,Ym=200,Xm=`bigmodel_token_production`;function Zm(e){let t=Xp(Yp(e.headers,`cookie`),Xm);if(t!==null&&t.trim()!==``)return t.trim();let n=Yp(e.headers,`authorization`);return n!==void 0&&n.trim()!==``?n.trim():null}var Qm=class extends cm{static vendorId=`zhipu-bigmodel`;static vendorLabel=`智谱 BigModel`;static hosts=[`bigmodel.cn`];static apiHosts=[`open.bigmodel.cn`];static credentialSource=`fetchText`;constructor(e){let t=Qp(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=Zm(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=qp(e.msg)??`未知错误`;throw Error(`上游业务错误 ${n}(code ${t===null?`未知`:String(t)})——多为登录凭据失效,请在 bigmodel.cn 重新登录后复制`)}return e}async#e(){let e=new Date,t=om(e).slice(0,7),n=om(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(Jm,`billingMonth=${t}&pageNum=${String(e)}&pageSize=${String(Ym)}`),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=qp(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(qm),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:$m(n)}}};function $m(e){let t=e=>`${am(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 eh=[vm,Om,Im,Km,Qm];function th(){return eh}function nh(e){if(e===void 0)return null;let t=Zp(e);if(t===``)return null;for(let e of eh)if(e.credentialSource===`apiKey`&&e.apiHosts?.some(e=>e===t))return e;return null}function rh(e,t){let n=nh(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 ih(e,t){let n=(e,t)=>{let n=e=>{let t=new Set;for(let n of Qp(e)){let e=Zp(n.url);e!==``&&t.add(e)}return t},r=e.trim();for(let e of eh)if(e.credentialSource===`fetchText`&&e.apiKeyPattern?.test(r)===!0)return e;if(t!==void 0){let e=Zp(t);if(e!==``){for(let t of eh)if(t.credentialSource===`fetchText`&&t.apiHosts?.some(t=>t===e))return t}}let i=n(e);for(let e of eh)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=eh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.apiHosts??[]]).join(`、`),n=eh.filter(e=>e.credentialSource===`fetchText`).flatMap(e=>[...e.hosts??[]]).join(`、`),r=nh(t)===null?``:`(该供应商已支持自动查询:确认供应商配置里的 apiKey 填写正确即可,无需粘贴凭据)`;throw Error(`暂不支持以粘贴凭据的方式查询该供应商的额度(按模型接口地址已支持:${e};按额度请求域名已支持:${n})${r}`)}return{vendorId:r.vendorId,vendor:new r(e)}}var ah=Mt(`quota.json`);function oh(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(ah.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 sh(e,t){ah.set(e,t)}function ch(e){ah.get(e)!==void 0&&ah.set(e,void 0)}function lh(){let e=ah.getAll(),t={};for(let n of Object.keys(e)){let e=oh(n);e!==null&&(t[n]=e)}return t}function uh(e,t,n,r){sh(e,{fetchText:oh(e)?.fetchText,vendorId:t,snapshot:n,fetchedAt:r,error:void 0})}function dh(e,t){let n=oh(e);if(n===null){sh(e,{error:t});return}sh(e,{...n,error:t})}var fh=!1;function ph(e){return(e instanceof Error?e.message:String(e)).replace(/\s+/g,` `).trim().slice(0,300)}function mh(){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=yl();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 hh(e){return mh()?.get(e)??null}async function gh(e){try{let t=hh(e);if(t===null)throw Error(`供应商配置不存在(可能已被删除)`);let n,r;if(nh(t.apiBase)!==null){if(t.apiKey===void 0)throw Error(`该供应商未配置 apiKey,无法自动查询额度——请在供应商配置里填入 API key`);({vendorId:n,vendor:r}=rh(t.apiKey,t.apiBase))}else{let i=oh(e)?.fetchText;if(i===void 0)throw Error(`未配置额度查询凭据(请在额度查询配置弹窗粘贴浏览器复制的 fetch 请求原文)`);({vendorId:n,vendor:r}=ih(i,t.apiBase))}let i=await r.fetchQuota();uh(e,n,i,Date.now())}catch(t){dh(e,ph(t))}return oh(e)}async function _h(){let e=()=>{let e=mh();return e===null?null:new Set(e.keys())};if(!fh){fh=!0;try{let t=mh(),n=t===null?[]:[...t.entries()].filter(([,e])=>nh(e.apiBase)!==null).map(([e])=>e);for(let e of n)await gh(e);let r=e();for(let[e,t]of Object.entries(lh()))if(t.fetchText!==void 0){if(r!==null&&!r.has(e)){ch(e);continue}n.includes(e)||await gh(e)}}catch(e){R(`[quota] 刷新失败:`,ph(e))}finally{fh=!1}}}function vh(){let e=async e=>{let t=(await up(e))?.fetchText;return typeof t==`string`?t:null},t=()=>th().map(e=>({vendorId:e.vendorId,vendorLabel:e.vendorLabel,hosts:e.hosts??[],apiHosts:e.apiHosts??[],credentialSource:e.credentialSource})),n=new Kn;return n.get(`/`,e=>e.json({ok:!0,vendors:t(),providers:lh()})),n.get(`/vendors`,e=>e.json({ok:!0,vendors:t()})),n.put(`/:provider`,async t=>{let n=t.req.param(`provider`);if(nh(hh(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=oh(n);sh(n,{fetchText:r,vendorId:i?.vendorId,snapshot:i?.snapshot,fetchedAt:i?.fetchedAt,error:void 0});let a=await gh(n);return t.json({ok:!0,entry:a})}),n.delete(`/:provider`,e=>(ch(e.req.param(`provider`)),e.json({ok:!0}))),n.post(`/:provider/refresh`,async e=>{let t=await gh(e.req.param(`provider`));return e.json({ok:!0,entry:t})}),n}function yh(e){return e===`0.0.0.0`||e===`::`}function bh(e=x()){let t=[];for(let n of Object.values(e))for(let e of n??[])e.internal||e.family!==`IPv4`||t.includes(e.address)||t.push(e.address);return t}function xh(e,t){let n=new Kn;return n.get(`/`,n=>n.json({listenPort:ap(e),...t?{listenHost:t.hostname,listenSource:t.source}:{},...t&&yh(t.hostname)?{lanAddresses:bh()}:{},masterKey:Ol()})),n}var Sh=864e5,Ch=3e5,wh=`http://ip-api.com/json/{ip}?lang=zh-CN&fields=status,message,country,regionName,city,isp`,Th=new Map;try{let e=f(mt(),`utf-8`),t=JSON.parse(e);for(let[e,n]of Object.entries(t)){let{_ts:t,...r}=n;Th.set(e,{value:r,at:typeof t==`number`?t:0})}}catch{}function Eh(){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=Th.get(e);if(!t)return null;let n=t.value.error===void 0?Sh:Ch;return Date.now()-t.at>=n?(Th.delete(e),null):t.value},n=()=>{try{let e={};for(let[t,{value:n,at:r}]of Th)e[t]={...n,_ts:r};y(mt(),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(wh.replace(`{ip}`,encodeURIComponent(e)),{signal:AbortSignal.timeout(8e3)})).json();if(i.status!==`success`){let t={error:i.message||`查询失败`};return Th.set(e,{value:t,at:Date.now()}),t}let a={country:i.country,region:i.regionName,city:i.city,isp:i.isp};return Th.set(e,{value:a,at:Date.now()}),n(),a},i=new Kn;return i.onError(gp),i.get(`/dates`,e=>{let t=nf();return e.json({dates:t})}),i.get(`/clients`,e=>{let t=rf();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 hp(502,e.message)}}),i.get(`/detail`,async e=>{let t=e.req.query(`id`);if(t){let n=Wd(t);return n||=(await xf(),Wd(t)??ou(Number(t))),n?e.json(n):e.json({error:`not found`},404)}return e.json({error:`invalid request`},400)}),i.get(`/`,_p(async t=>{let n=t.req.query(),r=ef({...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=cf({...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:ql(e.headers)}))})})),i.get(`/sessions`,_p(t=>{let n=t.req.query(),r=of({...e(n),page:n.page,pageSize:n.pageSize});return t.json(r)})),i.post(`/clear`,_p(async t=>{await Cf();let n=nu().length;n>0&&ct(`[logs] 清空前 spool 仍有 ${String(n)} 条未入库,这些记录可能在入库后重现`);let r=t.req.query(),i=uf(e(r));return L(`[logs] 已清理筛选日志 ${i} 条(筛选: ${JSON.stringify(r)})`),t.json({deleted:i})})),i}function Dh(e){return`http://127.0.0.1:${String(e.port)}`}var Oh=`daemon.json`;function kh(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,restarts:null}},n=e=>{try{let t=JSON.parse(f(E(e,Oh),`utf-8`))?.children;if(typeof t!=`object`||!t)return null;for(let e of Object.values(t)){let t=e;if(t?.pid===process.pid)return typeof t.startedAt==`number`?{pid:t.pid,startedAt:t.startedAt}:null}return null}catch{return null}},r=new Kn;return r.get(`/status`,async t=>t.json({ok:!0,running:!0,pid:process.pid,status:`online`,uptime:e.startedAt,gatewayBase:Dh(e)})),r.get(`/processes`,r=>{let i=n(e.appDir);return r.json({ok:!0,processes:[t({pid:i?.pid??process.pid,status:`online`,port:e.port,startedAt:i?.startedAt??e.startedAt})]})}),r}var Ah=`ezllm-autostart.vbs`,jh=`ezllm-autostart.cmd`,Mh=`com.ezllm.autostart`,Nh=`ezllm.service`,Ph=`autostart.opt-out`,Fh=`ezllm-v2`,Ih=`Auto-generated by "ezllm autostart on" (${Fh}). Disable with "ezllm autostart off".`,Lh=`ELLM_`,Rh=new Set([`WEBUI_USERNAME`,`WEBUI_PASSWORD`,`HOST`]);function zh(e=process.env){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(n.startsWith(Lh)||Rh.has(n))&&(t[n]=r);return t}function Bh(e){return E(e,Ph)}function Vh(){return E((()=>{let e=process.env.APPDATA;if(!e)throw Error(`无法定位启动文件夹(APPDATA 环境变量未设置)。`);return E(e,`Microsoft`,`Windows`,`Start Menu`,`Programs`,`Startup`)})(),Ah)}function Hh(){return E(b(),`Library`,`LaunchAgents`,`${Mh}.plist`)}function Uh(){return E(b(),`.config`,`systemd`,`user`,Nh)}function Wh(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 Gh={win32:{itemPath:Vh,on:Zh,off:eg},darwin:{itemPath:Hh,on:Qh,off:tg},linux:{itemPath:Uh,on:$h,off:ng}};function Kh(e){return Gh[e]??null}function qh(e){let t=Kh(e);if(!t)throw Error(`暂不支持的平台: ${e}。`);return t}function Jh(e,t){return[e,t.entryJs,...t.args??[]]}function Yh(e){return E(e,`logs`,`autostart.log`)}async function Xh(e,t,n=Wh){try{y(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 Zh(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=Yh(t.appDir);return[`@echo off`,`chcp 65001 >nul`,`rem ${Ih}`,...Object.entries(t.env).map(([e,t])=>(n(e,t),`set "${e}=${t}"`)),`>> "${r}" echo [%date% %time%] autostart launching.`,`${Jh(e,t).map(e=>`"${e}"`).join(` `)} >> "${r}" 2>&1`,``].join(`\r
|
|
79
|
+
`)},i=e=>[`' ${Ih}`,`CreateObject("WScript.Shell").Run """${e}""", 0, False`,``].join(`\r
|
|
80
|
+
`),a=Vh(),o=E(t.appDir,jh);return y(o,r(e,t),`utf-8`),await Xh(a,`\uFEFF${i(o)}`),a}async function Qh(e,t){let n=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`),r=(e,t)=>{let r=Yh(t.appDir),i=Object.entries(t.env).map(([e,t])=>` <string>${n(e)}</string>\n <string>${n(t)}</string>`).join(`
|
|
81
|
+
`),a=Jh(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">`,`<!-- ${Fh}: launch daemon -->`,`<plist version="1.0">`,`<dict>`,` <key>Label</key><string>${n(Mh)}</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=Hh();y(i,r(e,t),`utf-8`),await Wh(`launchctl`,[`unload`,i]);let a=await Wh(`launchctl`,[`load`,i]);if(a!==0)throw Error(`launchctl load 失败(退出码 ${String(a)})。请手动执行: launchctl load "${i}"`);return i}async function $h(e,t){let n=(e,t)=>{let n=Object.entries(t.env).map(([e,t])=>`Environment="${e}=${t.replace(/"/g,`\\"`)}"`).join(`
|
|
84
|
+
`),r=Jh(e,t).map(e=>`"${e.replace(/"/g,`\\"`)}"`).join(` `);return[`[Unit]`,`Description=ezllm autostart (${Fh}, launch daemon)`,`After=default.target`,``,`[Service]`,`Type=simple`,`ExecStart=${r}`,n,`Restart=on-failure`,`RestartSec=3`,``,`[Install]`,`WantedBy=default.target`,``].join(`
|
|
85
|
+
`)},r=Uh();u(T(r),{recursive:!0}),y(r,n(e,t),`utf-8`);let i=await Wh(`systemctl`,[`--user`,`daemon-reload`]);if(i!==0)throw Error(`systemctl --user daemon-reload 失败(退出码 ${String(i)})。当前环境可能无 systemd(WSL/容器),请手动启用或删除: ${r}`);let a=await Wh(`systemctl`,[`--user`,`enable`,Nh]);if(a!==0)throw Error(`systemctl --user enable 失败(退出码 ${String(a)})。请手动执行: systemctl --user enable ${Nh}`);return r}async function eg(e){let t=Vh(),n=l(t);return h(t,{force:!0}),h(E(e,jh),{force:!0}),n}async function tg(){let e=Hh();return l(e)?(await Wh(`launchctl`,[`unload`,e]),h(e,{force:!0}),!0):!1}async function ng(){let e=Uh();return l(e)?(await Wh(`systemctl`,[`--user`,`disable`,Nh]),h(e,{force:!0}),await Wh(`systemctl`,[`--user`,`daemon-reload`]),!0):!1}function rg(e){let t=()=>Kh(S())?.itemPath()??null,n=e=>{let t=f(e);return t.length>=2&&t[0]===255&&t[1]===254?t.toString(`utf16le`).slice(1):t.toString(`utf-8`)},r=t(),i=!1;if(r&&l(r))try{i=n(r).includes(Fh)}catch{}return{platform:S(),enabled:i,itemPath:r,optOut:l(Bh(e))}}async function ig(e){let t=qh(S());u(E(e.appDir,`logs`),{recursive:!0});let n=await t.on(e.nodePath,e);return h(Bh(e.appDir),{force:!0}),{itemPath:n}}async function ag(e){let t=await qh(S()).off(e.appDir);return u(e.appDir,{recursive:!0}),y(Bh(e.appDir),new Date().toISOString(),`utf-8`),{removed:t}}var og=Object.create,sg=Object.defineProperty,cg=Object.getOwnPropertyDescriptor,lg=Object.getOwnPropertyNames,ug=Object.getPrototypeOf,dg=Object.prototype.hasOwnProperty,X=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),fg=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=lg(t),a=0,o=i.length,s;a<o;a++)s=i[a],!dg.call(e,s)&&s!==n&&sg(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=cg(t,s))||r.enumerable});return e},pg=(e,t,n)=>(n=e==null?{}:og(ug(e)),fg(t||!e||!e.__esModule||!dg.call(e,`default`)?sg(n,`default`,{value:e,enumerable:!0}):n,e)),Z=e(import.meta.url),mg=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})),hg=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})),gg=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})),_g=X(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});var n=gg(),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})),vg=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})),yg=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}})),bg=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}}})),xg=X(((e,t)=>{var n=bg();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}})),Sg=X(((e,t)=>{var n=xg(),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})),Cg=X(((e,t)=>{var n=xg(),r=Sg(),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)}})),wg=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}})),Tg=X(((e,t)=>{var{constants:n}=Z(`buffer`),r=Cg(),i=wg(),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})),Eg=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}}}})),Dg=X(((e,t)=>{t.exports=e=>{let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}})),Og=X(((e,t)=>{var n=Z(`stream`).Readable,r=Dg();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)}}})),kg=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])}})),Ag=X(((e,t)=>{var n=Z(`stream`).PassThrough,r=kg();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)}})),jg=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})}})),Mg=X(((e,t)=>{var n=Z(`events`),r=jg(),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()}}})),Ng=X(((e,t)=>{var n=Z(`events`),r=Z(`url`),i=yg(),a=Tg(),o=Eg(),s=Og(),c=Dg(),l=Ag(),u=Mg(),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})),Pg=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}})),Fg=X(((e,t)=>{var{Transform:n,PassThrough:r}=Z(`stream`),i=Z(`zlib`),a=Pg();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}})),Ig=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)}}})),Lg=X(((e,t)=>{var n=Z(`events`),r=Z(`tls`),i=Z(`http2`),a=Ig(),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 _}})),Rg=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()}}})),zg=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}})),Bg=X(((e,t)=>{t.exports=(e,t,n)=>{for(let r of n)e.on(r,(...e)=>t.emit(r,...e))}})),Vg=X(((e,t)=>{t.exports=e=>{switch(e){case`:method`:case`:scheme`:case`:authority`:case`:path`:return!0;default:return!1}}})),Hg=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]}]`)})),Ug=X(((e,t)=>{var n=Z(`http2`),{Writable:r}=Z(`stream`),{Agent:i,globalAgent:a}=Lg(),o=Rg(),s=zg(),c=Bg(),l=Vg(),{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}=Hg(),{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){}}})),Wg=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)}})()})})),Gg=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}})),Kg=X(((e,t)=>{var n=Z(`http`),r=Z(`https`),i=Wg(),a=Ig(),o=Ug(),s=Gg(),c=zg(),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})),qg=X(((e,t)=>{var n=Z(`http2`),r=Lg(),i=Ug(),a=Rg(),o=Kg(),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}})),Jg=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mg();e.default=e=>t.default.nodeStream(e)&&t.default.function_(e.getBoundary)})),Yg=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Z(`fs`),n=Z(`util`),r=mg(),i=Jg(),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}}})),Xg=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})),Zg=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}}}})),Qg=X((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.TimeoutError=void 0;var t=Z(`net`),n=Zg(),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}})),$g=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mg();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}})),e_=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}})),t_=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)}}})),n_=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(``))}})),r_=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`)}})),i_=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}})),a_=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`}))}})),o_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mg();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}})),s_=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}})),c_=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=_g(),l=vg(),u=Ng(),d=Fg(),f=qg(),p=Dg(),m=mg(),h=Yg(),g=Jg(),_=Xg(),v=Qg(),y=$g(),b=e_(),x=t_(),S=n_(),C=r_(),w=i_(),T=a_(),E=o_(),D=s_(),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 I=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(`
|
|
86
86
|
`).reverse(),r=t.stack.slice(t.stack.indexOf(t.message)+t.message.length).split(`
|
|
87
87
|
`).reverse();for(;r.length!==0&&r[0]===n[0];)n.shift();this.stack=`${this.stack.slice(0,e)}${n.reverse().join(`
|
|
88
88
|
`)}${r.reverse().join(`
|
|
89
|
-
`)}`}}};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 ye=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=ye;var be=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=be;var L=class extends ge{constructor(e,t,n){super(e.message,e,n),this.name=`TimeoutError`,this.event=e.event,this.timings=t}};e.TimeoutError=L;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 L(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 be(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 ye(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})),Dy=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=Ey();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(Ey(),e)})),Oy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Dy();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)}}})),ky=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=Mv(),a=Nv(),o=Dy(),s=Oy(),c=Ey(),l=my(),u=by(),d=Sy(),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(Dy(),e)})),Ay=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Dy();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})),jy=L((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=Mv();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})),My=L((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),Ny=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=Mv(),i=ky(),a=Ay(),o=Ey(),s=jy(),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(My(),e)})),Py=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=Ny(),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(Ny(),e),r(ky(),e)})),Fy=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)):{}})),Iy=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`))}}})),Ly=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))})),Ry=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`))}}})),zy=L((e=>{var t=R(`assert`),n=R(`buffer`).Buffer,r=R(`zlib`),i=e.constants=Ly(),a=Ry(),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`)}}})),By=L(((e,t)=>{t.exports=(process.env.TESTING_TAR_FAKE_PLATFORM||process.platform)===`win32`?e=>e&&e.replace(/\\/g,`/`):e=>e})),Vy=L(((e,t)=>{var{Minipass:n}=Iy(),r=By(),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])}}})),Hy=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]]))})),Uy=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}})),Wy=L(((e,t)=>{var n=Hy(),r=R(`path`).posix,i=Uy(),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})),Gy=L(((e,t)=>{var n=Wy(),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=I;var _e=class extends I{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 I{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 ye=class extends I{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=ye;var be=class extends I{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=be;var xe=class extends I{constructor(e,t,n){super(e.message,e,n),this.name=`TimeoutError`,this.event=e.event,this.timings=t}};e.TimeoutError=xe;var Se=class extends I{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=Se;var Ce=class extends I{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 I){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 Se(t,this))}),e.once(`aborted`,()=>{this._beforeError(new Se({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 _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 I(`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 ve(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 xe(t,this.timings,this):new I(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 be(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 ye(e,this):new I(e.message,e,this)}}async _error(e){try{for(let t of this.options.hooks.beforeError)e=await t(e)}catch(t){e=new I(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 I||(e=new I(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 I(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 I(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 I)&&(e=new I(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})),l_=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=c_();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(c_(),e)})),u_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=l_();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=mg(),a=hg(),o=l_(),s=u_(),c=c_(),l=Xg(),u=n_(),d=i_(),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(l_(),e)})),f_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=l_();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})),p_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0});var t=mg();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})),m_=X((e=>{Object.defineProperty(e,"__esModule",{value:!0})})),h_=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=mg(),i=d_(),a=f_(),o=c_(),s=p_(),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(m_(),e)})),g_=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=h_(),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(h_(),e),r(d_(),e)})),__=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)):{}})),v_=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`))}}})),y_=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))})),b_=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`))}}})),x_=X((e=>{var t=Z(`assert`),n=Z(`buffer`).Buffer,r=Z(`zlib`),i=e.constants=y_(),a=b_(),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`)}}})),S_=X(((e,t)=>{t.exports=(process.env.TESTING_TAR_FAKE_PLATFORM||process.platform)===`win32`?e=>e&&e.replace(/\\/g,`/`):e=>e})),C_=X(((e,t)=>{var{Minipass:n}=v_(),r=S_(),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])}}})),w_=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]]))})),T_=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}})),E_=X(((e,t)=>{var n=w_(),r=Z(`path`).posix,i=T_(),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})),D_=X(((e,t)=>{var n=E_(),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+`
|
|
90
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(`
|
|
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})),Ky=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)}})),qy=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))}}})),Jy=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)}})),Yy=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]}})),Xy=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)})),Zy=L(((e,t)=>{var{Minipass:n}=Iy(),r=Gy(),i=Wy(),a=R(`fs`),o=R(`path`),s=By(),c=Ky(),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=qy(),j=Jy(),M=Yy(),N=Xy(),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})),Qy=L(((e,t)=>{t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}})),$y=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{Qy()(n)}catch{}})),eb=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}=Iy(),i=zy(),a=Vy(),o=Zy(),s=o.Sync,c=o.Tar,l=$y(),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=qy(),P=By(),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})),tb=L((e=>{var t=Ry(),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})),nb=L(((e,t)=>{var n=qy(),r=Wy(),i=R(`events`),a=$y(),o=1048576,s=Vy(),c=Gy(),l=zy(),{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)))}})})),rb=L(((e,t)=>{var n=Fy(),r=nb(),i=R(`fs`),a=tb(),o=R(`path`),s=Ky();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)})),ib=L(((e,t)=>{var n=Fy(),r=eb(),i=tb(),a=rb(),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}})),ab=L(((e,t)=>{var n=Fy(),r=eb(),i=R(`fs`),a=tb(),o=rb(),s=R(`path`),c=Wy();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()}})),ob=L(((e,t)=>{var n=Fy(),r=ab();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)}})),sb=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}})),cb=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}})),lb=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}})),ub=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}})),db=L(((e,t)=>{var{dirname:n}=R(`path`),{findMade:r,findMadeSync:i}=lb(),{mkdirpManual:a,mkdirpManualSync:o}=ub();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}}}})),fb=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}})),pb=L(((e,t)=>{var n=sb(),r=cb(),{mkdirpNative:i,mkdirpNativeSync:a}=db(),{mkdirpManual:o,mkdirpManualSync:s}=ub(),{useNative:c,useNativeSync:l}=fb(),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})),mb=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})),hb=L(((e,t)=>{var n=pb(),r=R(`fs`),i=R(`path`),a=mb(),o=By(),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)}})),gb=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])})),_b=L(((e,t)=>{var n=R(`assert`),r=gb(),i=Ky(),{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)}}}})),vb=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`})),yb=L(((e,t)=>{var n=R(`assert`),r=nb(),i=R(`fs`),a=tb(),o=R(`path`),s=hb(),c=Jy(),l=_b(),u=Yy(),d=By(),f=Ky(),p=gb(),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=vb(),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})),bb=L(((e,t)=>{var n=Fy(),r=yb(),i=R(`fs`),a=tb(),o=R(`path`),s=Ky();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)})),xb=L((e=>{e.c=e.create=ib(),e.r=e.replace=ab(),e.t=e.list=rb(),e.u=e.update=ob(),e.x=e.extract=bb(),e.Pack=eb(),e.Unpack=yb(),e.Parse=nb(),e.ReadEntry=Vy(),e.WriteEntry=Zy(),e.Header=Wy(),e.Pax=Gy(),e.types=Hy()})),Sb=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`:``)}})),Cb=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=Sb(),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})),wb=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=Cb()(e);var{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})),Tb=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(`
|
|
92
|
-
`).join(`
|
|
93
|
-
|
|
94
|
-
`)}function
|
|
95
|
-
`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})),Eb=L(((e,t)=>{t.exports=typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?wb():Tb()})),Db=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))}})),Ob=L((e=>{var t=R(`fs`),n=R(`util`),r=R(`stream`),i=r.Readable,a=r.Writable,o=r.PassThrough,s=Db(),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)}})),kb=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})),Ab=L((e=>{var t=R(`fs`),n=R(`zlib`),r=Ob(),i=kb(),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}})),jb=L(((e,t)=>{var n=Eb()(`extract-zip`),{createWriteStream:r,promises:i}=R(`fs`),a=Uv(),o=R(`path`),{promisify:s}=R(`util`),c=R(`stream`),l=s(Ab().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()}})),Mb=Se(Py(),1),Nb=Se(xb(),1),Pb=Se(jb(),1),Fb={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`}},Ib=process.platform===`win32`;function Lb(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(Fb),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 Rb(e){return Ib?E(e,`node.exe`):E(e,`bin`,`node`)}function zb(){return`${process.platform}-${process.arch}`}function Bb(e){let t=D(e);return f(Rb(t))?t:null}function Vb(e,t){return[E(e,`node_modules`,`npm`,`bin`,`${t}-cli.js`),E(e,`lib`,`node_modules`,`npm`,`bin`,`${t}-cli.js`)]}function Hb(e,t){let n=Vb(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(`
|
|
96
|
-
`));return r}function Ub(e){return Bb(e)!==null&&Vb(e,`npm`).some(e=>f(e))}var Wb=[`.cmd`,`.bat`,`.exe`];function Gb(e,t){if(t.includes(`/`)||t.includes(`\\`))return null;let n=Ib?Wb.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 Kb(e){return(Ib?[e,E(e,`node_modules`,`.bin`)]:[E(e,`bin`),e]).join(w)+w}var qb={"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`}},Jb=process.platform===`win32`?[[`node_modules`]]:[[`lib`,`node_modules`]];async function Yb(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=20971520,t=Mb.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 pe(t,d(i)),console.error(`[ezn] 下载完成,正在解压 ...`),n.platform.ext===`zip`?await(0,Pb.default)(i,{dir:a}):await Nb.x({file:i,cwd:a});let r=g(a),s=r.length===1&&r[0]!==void 0&&b(E(a,r[0])).isDirectory()?E(a,r[0]):a;return v(i,{force:!0}),{src:s,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(`
|
|
97
|
-
`))}function Xb(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))Xb(E(e,a),E(t,a),[...n,a],r,i);v(e,{recursive:!0,force:!0});return}if(f(t)){let e=`${t}.old-${i}`;_(t,e),console.error(`[ezn] 同名项已备份:${e}`)}_(e,t)}async function Zb(e,t,n={}){let r=(e,t)=>{let n=Date.now();for(let r of g(e))Xb(E(e,r),E(t,r),[r],Jb,n)},i=D(e),a=Lb(t),o=Rb(i),s=zb(),c=qb[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 Yb(a,T(i),{target:i,nodePath:o,platform:c,mirror:n.mirror??null});try{r(l,i)}finally{u()}console.error(`[ezn] Node ${a} 已就绪:${i}`)}function Qb(e){return e!==``&&!/[\s"^&|<>()%!]/.test(e)?e:`"${e.replace(/"/g,`\\"`)}"`}function $b(e,t,n){return n?[[e,...t].map(Qb).join(` `),[]]:[e,[...t]]}function ex(e,t,n={}){return new Promise((r,i)=>{let a=de(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 tx=process.platform===`win32`;function nx(e){return typeof e==`string`?e.trim().split(/\s+/).filter(e=>e.length>0):[...e]}var rx=class e{constructor(e,t){this.path=e,this.rt=t}get npmCliPath(){return Hb(this.rt,`npm`)}get npxCliPath(){return Hb(this.rt,`npx`)}get major(){return e.probeMajor(this.path)}resolveArgs(e,t){let n=nx(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=nx(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=Gb(this.rt,r);if(o!==null){let e=tx&&/\.(cmd|bat)$/i.test(o),[t,n]=$b(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:Kb(this.rt)+(t.PATH??t.Path??``)}}execSync(e,t){let{file:n,argv:r,shell:i,env:a}=this.resolveExec(e,t??{});return fe(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 ex(n,r,{...t,shell:i,env:a})}npmSync(e,t){return fe(this.path,this.resolveArgs(e,this.npmCliPath),{windowsHide:!0,encoding:`utf8`,...t})}npm(e,t){return ex(this.path,this.resolveArgs(e,this.npmCliPath),t)}npxSync(e,t){return fe(this.path,this.resolveArgs(e,this.npxCliPath),{windowsHide:!0,encoding:`utf8`,...t})}npx(e,t){return ex(this.path,this.resolveArgs(e,this.npxCliPath),t)}static probeMajor(e){try{let t=ue(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=Lb(n),o=Number(a.replace(/^v/,``).split(`.`)[0]),s=E(i,`node`),c=Rb(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&&Ub(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 Zb(s,n,{mirror:r.mirror??null}),new e(c,s)}},ix=`24`;async function ax(e){return(await rx.ensure(e,ix)).path}var ox=new Map,sx=1;function cx(){return typeof process.send==`function`}function lx(e,t={},n=3e4){if(!process.send)return Promise.reject(Error(`未由 ezllm 主进程托管(源码运行模式),该功能不可用`));let r=sx++;return new Promise((i,a)=>{let o=setTimeout(()=>{ox.delete(r),a(Error(`主进程未在 ${String(Math.round(n/1e3))}s 内响应(${e})`))},n);ox.set(r,{resolve:e=>i(e),reject:a,timer:o}),process.send?.({type:e,id:r,args:t})})}function ux(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=ox.get(t.id);n&&(ox.delete(t.id),clearTimeout(n.timer),t.error===void 0?n.resolve(t.data):n.reject(Error(t.error)))})}async function dx(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 fx=`当前为源码运行模式,更新功能不可用(仅 npm 全局安装的包支持自动更新)`,px=`服务未由 ezllm 主进程托管,更新功能不可用;请在终端执行 ezllm update`,mx=9e5;function hx(){if(!Mt())return!1;let e=T(At);return C(e)===`node_modules`||C(T(e))===`node_modules`}function gx(){let e=bu()?.autoUpdate;return typeof e!=`boolean`||e}function _x(){return hx()?cx()?null:px:fx}function vx(e){let t=new nr;return t.get(`/autostart`,t=>t.json({ok:!0,...kv(e.appDir)})),t.post(`/autostart`,async t=>{let n=await dx(t);if(n instanceof Response)return n;if(n){let{itemPath:n}=await Av({entryJs:It(),env:nv(),appDir:e.appDir,nodePath:await ax(e.appDir)});return t.json({ok:!0,enabled:!0,itemPath:n,note:`已注册自启项,下次登录时自动启动服务`})}let{removed:r}=await jv({appDir:e.appDir});return t.json({ok:!0,enabled:!1,removed:r,note:r?`已移除自启项,且首次启动不再自动注册(重新开启即可解除)`:`原本未开启,无操作`})}),t.get(`/update`,e=>{let t=Bt(),n=t.pending??null,r=n!==null&&Date.now()-n.startedAt<mx;return e.json({ok:!0,enabled:gx(),lastCheck:t.lastCheck??null,lastApply:t.lastApply??null,pendingUpdate:r&&n?n.toVersion:null,supported:hx()&&cx(),updating:r})}),t.post(`/update/enabled`,async e=>{let t=await dx(e);if(t instanceof Response)return t;try{let e=bu();e&&Su({...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=_x();if(t)return e.json({ok:!1,error:t},400);let n=await lx(`update.check`);return e.json({ok:!0,...n})}),t.post(`/update/apply`,async e=>{let t=_x();if(t)return e.json({ok:!1,error:t},400);let n=await lx(`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 yx=`服务未由 ezllm 主进程托管(源码运行模式),托管服务不可用;请用 ezllm 启动服务`;function bx(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 xx(){return cx()?null:Response.json({ok:!1,error:yx},{status:400})}function Sx(e){let t=new nr;return t.onError(qm),t.get(`/`,async e=>{let t=xx();if(t)return t;let n=await lx(`svc.list`);return e.json({ok:!0,...n})}),t.post(`/`,async e=>{let t=xx();if(t)return t;let n=await Vm(e);if(n===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let r=await lx(`svc.create`,bx(n,null));return e.json({ok:!0,...r})}),t.put(`/:name`,async e=>{let t=xx();if(t)return t;let n=await Vm(e);if(n===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let r=await lx(`svc.update`,bx(n,e.req.param(`name`)));return e.json({ok:!0,...r})}),t.delete(`/:name`,async e=>{let t=xx();if(t)return t;let n=await lx(`svc.remove`,{name:e.req.param(`name`)});return e.json({ok:!0,...n})}),t.post(`/:name/start`,async e=>{let t=xx();if(t)return t;let n=await lx(`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=xx();if(t)return t;let n=await lx(`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=xx();if(t)return t;let n=await lx(`child.restart`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...n}})}),t}function Cx(e){let t=`${e}.ellm-bak`;return!f(t)&&(f(e)&&u(e,t),!0)}function wx(e){let t=`${e}.ellm-bak`;return f(t)?(u(t,e),v(t,{force:!0}),!0):!1}function Tx(e,t){return String(e||``).replace(/\/+$/,``)===String(t||``).replace(/\/+$/,``)}var Ex=E(t(),`.claude`,`settings.json`);function Dx(){if(!f(Ex))return null;try{return JSON.parse(h(Ex,`utf-8`))}catch(e){throw Error(`${Ex} 不是合法 JSON,拒绝修改(请先手工修复): ${e.message}`)}}function Ox(e){let t=Dx();return t?Tx(t?.env?.ANTHROPIC_BASE_URL,e):!1}function kx(e){p(T(Ex),{recursive:!0});let t=Dx()??{};Cx(Ex),t.env={...t.env??{}},t.env.ANTHROPIC_BASE_URL=e.gatewayBase,t.env.ANTHROPIC_AUTH_TOKEN=e.token,S(Ex,JSON.stringify(t,null,2)+`
|
|
98
|
-
`,`utf-8`)}function Ax(e){if(wx(Ex))return!0;let t=Dx();return!t||!Tx(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(Ex,JSON.stringify(t,null,2)+`
|
|
99
|
-
`,`utf-8`),!0)}var jx=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Mx=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(jx);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 Nx(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function Px(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})),O_=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)}})),k_=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))}}})),A_=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)}})),j_=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]}})),M_=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)})),N_=X(((e,t)=>{var{Minipass:n}=v_(),r=D_(),i=E_(),a=Z(`fs`),o=Z(`path`),s=S_(),c=O_(),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=k_(),j=A_(),M=j_(),N=M_(),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})),P_=X(((e,t)=>{t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}})),F_=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{P_()(n)}catch{}})),I_=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}=v_(),i=x_(),a=C_(),o=N_(),s=o.Sync,c=o.Tar,l=F_(),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=k_(),P=S_(),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})),L_=X((e=>{var t=b_(),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})),R_=X(((e,t)=>{var n=k_(),r=E_(),i=Z(`events`),a=F_(),o=1048576,s=C_(),c=D_(),l=x_(),{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)))}})})),z_=X(((e,t)=>{var n=__(),r=R_(),i=Z(`fs`),a=L_(),o=Z(`path`),s=O_();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)})),B_=X(((e,t)=>{var n=__(),r=I_(),i=L_(),a=z_(),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}})),V_=X(((e,t)=>{var n=__(),r=I_(),i=Z(`fs`),a=L_(),o=z_(),s=Z(`path`),c=E_();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()}})),H_=X(((e,t)=>{var n=__(),r=V_();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)}})),U_=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}})),W_=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}})),G_=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}})),K_=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}})),q_=X(((e,t)=>{var{dirname:n}=Z(`path`),{findMade:r,findMadeSync:i}=G_(),{mkdirpManual:a,mkdirpManualSync:o}=K_();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}}}})),J_=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}})),Y_=X(((e,t)=>{var n=U_(),r=W_(),{mkdirpNative:i,mkdirpNativeSync:a}=q_(),{mkdirpManual:o,mkdirpManualSync:s}=K_(),{useNative:c,useNativeSync:l}=J_(),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})),X_=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})),Z_=X(((e,t)=>{var n=Y_(),r=Z(`fs`),i=Z(`path`),a=X_(),o=S_(),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)}})),Q_=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])})),$_=X(((e,t)=>{var n=Z(`assert`),r=Q_(),i=O_(),{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)}}}})),ev=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`})),tv=X(((e,t)=>{var n=Z(`assert`),r=R_(),i=Z(`fs`),a=L_(),o=Z(`path`),s=Z_(),c=A_(),l=$_(),u=j_(),d=S_(),f=O_(),p=Q_(),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=ev(),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})),nv=X(((e,t)=>{var n=__(),r=tv(),i=Z(`fs`),a=L_(),o=Z(`path`),s=O_();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)})),rv=X((e=>{e.c=e.create=B_(),e.r=e.replace=V_(),e.t=e.list=z_(),e.u=e.update=H_(),e.x=e.extract=nv(),e.Pack=I_(),e.Unpack=tv(),e.Parse=R_(),e.ReadEntry=C_(),e.WriteEntry=N_(),e.Header=E_(),e.Pax=D_(),e.types=w_()})),iv=pg(g_()),av=pg(rv()),ov={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`}},sv=process.platform===`win32`;function cv(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(ov),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 lv(e){return sv?E(e,`node.exe`):E(e,`bin`,`node`)}function uv(){return`${process.platform}-${process.arch}`}function dv(e){let t=D(e);return l(lv(t))?t:null}function fv(e,t){return[E(e,`node_modules`,`npm`,`bin`,`${t}-cli.js`),E(e,`lib`,`node_modules`,`npm`,`bin`,`${t}-cli.js`)]}function pv(e,t){let n=fv(e,t),r=n.find(e=>l(e));if(!r)throw Error([`未找到自带 ${t}(该目录可能不是完整的 Node 运行时)。已查找以下位置:`,...n.map(e=>` - ${e}`),`可尝试的恢复方式:`,` 1. 托管运行时(<appDir>/node):删除该目录后重新启动服务,由引导重新落位完整运行时;`,` 2. 手工安装的平铺运行时:请确认发行包完整(含自带 npm/npx),必要时重新解压放置。`].join(`
|
|
92
|
+
`));return r}function mv(e){return dv(e)!==null&&fv(e,`npm`).some(e=>l(e))}var hv=[`.cmd`,`.bat`,`.exe`];function gv(e,t){if(t.includes(`/`)||t.includes(`\\`))return null;let n=sv?hv.map(n=>E(e,`${t}${n}`)):[E(e,t)];return n.push(E(e,`node_modules`,`.bin`,t)),n.find(e=>l(e))??null}function _v(e){return(sv?[e,E(e,`node_modules`,`.bin`)]:[E(e,`bin`),e]).join(w)+w}var vv=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))}})),yv=X((e=>{var t=Z(`fs`),n=Z(`util`),r=Z(`stream`),i=r.Readable,a=r.PassThrough,o=vv(),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`)}})),bv=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})),xv=X((e=>{var t=Z(`fs`),n=Z(`zlib`),r=yv(),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:bv();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}}))(),Sv=16384,Cv=16;function wv(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 Tv(e){return(e.externalFileAttributes>>>16&61440)===Sv||e.fileName.endsWith(`/`)?!0:!(e.versionMadeBy>>>8)&&e.externalFileAttributes===Cv}async function Ev(e,t,n){let r=D(t);u(r,{recursive:!0});let i=0,a=0,o=null,s=(e=0)=>{n?.({entries:i,bytes:a+e,current:o})},l=await(0,xv.openPromise)(e);try{for await(let e of l.eachEntry()){if(e.fileName.startsWith(`__MACOSX/`))continue;let t=wv(r,e.fileName);if(Tv(e)){u(t,{recursive:!0}),i+=1,s();continue}u(T(t),{recursive:!0}),o=e.fileName,s();let n=0,d=await l.openReadStreamPromise(e);d.on(`data`,e=>{n+=e.length,s(n)}),await de(d,c(t)),a+=n,i+=1,o=null,s()}}finally{l.isOpen&&l.close()}}var Dv={"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`}},Ov=process.platform===`win32`?[[`node_modules`]]:[[`lib`,`node_modules`]],kv=5e3,Av=3e3;function jv(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 Mv(e,t){let n=setInterval(()=>console.error(t()),e);return()=>clearInterval(n)}function Nv(e){return Math.round((Date.now()-e)/1e3)}async function Pv(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=()=>{h(i,{force:!0}),h(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`),h(i,{force:!0}),h(a,{recursive:!0,force:!0}),u(a,{recursive:!0});for(let t=0;t<s.length;t++){let l=s[t],d=`${l}/${e}/${r}`;console.error(`[ezn] (${t+1}/${s.length}) 正在下载 ${r}\n[ezn] 来源:${l}`);try{let e=Date.now(),t=0,r=iv.default.stream(d,{decompress:!1,timeout:{connect:3e4,response:6e4,socket:6e4}});r.on(`downloadProgress`,e=>{t=e.transferred});let s=Mv(kv,()=>`[ezn] 已下载 ${Math.round(t/1048576)} MB(已用 ${Nv(e)} 秒) ...`);try{await de(r,c(i))}finally{s()}console.error(`[ezn] 下载完成(${Math.round(_(i).size/1048576)} MB,耗时 ${Nv(e)} 秒),正在解压 ...`);let l=Date.now(),u={entries:0,bytes:null,current:null},f=Mv(Av,()=>jv(u,Nv(l)));try{n.platform.ext===`zip`?await Ev(i,a,e=>{u=e}):await av.x({file:i,cwd:a,onentry:e=>{u={entries:u.entries+1,bytes:null,current:e.path}}})}finally{f()}console.error(`[ezn] 解压完成(${u.entries} 项,耗时 ${Nv(l)} 秒)`);let m=p(a),g=m.length===1&&m[0]!==void 0&&_(E(a,m[0])).isDirectory()?E(a,m[0]):a;return h(i,{force:!0}),{src:g,cleanup:o}}catch(e){console.error(`[ezn] 该源失败:${e instanceof Error?e.message:String(e)}`),h(i,{force:!0}),h(a,{recursive:!0,force:!0}),u(a,{recursive:!0})}}h(a,{recursive:!0,force:!0});let l=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}(见 ${l}/${e}/),`,` 解压到 ${n.target}(如带顶层版本目录请把其内容上移一层),`,` 确保可执行文件位于 ${n.nodePath}。`].join(`
|
|
93
|
+
`))}function Fv(e,t,n,r,i){if(r.some(e=>n.length<=e.length&&n.every((t,n)=>e[n]===t))&&l(t)&&_(e).isDirectory()&&_(t).isDirectory()){for(let a of p(e))Fv(E(e,a),E(t,a),[...n,a],r,i);h(e,{recursive:!0,force:!0})}else{if(l(t)){let e=`${t}.old-${i}`;m(t,e),console.error(`[ezn] 同名项已备份:${e}`)}m(e,t)}}async function Iv(e,t,n={}){let r=(e,t)=>{let n=Date.now();for(let r of p(e))Fv(E(e,r),E(t,r),[r],Ov,n)},i=D(e),a=cv(t),o=lv(i),s=uv(),c=Dv[s];if(!c)throw Error(`暂不支持的平台:${s}。请手动放置 Node ${a} 到 ${i},确保可执行文件位于 ${o}(Windows 为 node.exe,Unix 为 bin/node)。`);u(i,{recursive:!0});let{src:l,cleanup:d}=await Pv(a,T(i),{target:i,nodePath:o,platform:c,mirror:n.mirror??null});try{console.error(`[ezn] 正在落位运行时文件 ...`),r(l,i)}finally{d()}console.error(`[ezn] Node ${a} 已就绪:${i}`)}function Lv(e){return e!==``&&!/[\s"^&|<>()%!]/.test(e)?e:`"${e.replace(/"/g,`\\"`)}"`}function Rv(e,t,n){return n?[[e,...t].map(Lv).join(` `),[]]:[e,[...t]]}function zv(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 Bv=process.platform===`win32`;function Vv(e){return typeof e==`string`?e.trim().split(/\s+/).filter(e=>e.length>0):[...e]}var Hv=class e{constructor(e,t){this.path=e,this.rt=t}get npmCliPath(){return pv(this.rt,`npm`)}get npxCliPath(){return pv(this.rt,`npx`)}get major(){return e.probeMajor(this.path)}resolveArgs(e,t){let n=Vv(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=Vv(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=gv(this.rt,r);if(o!==null){let e=Bv&&/\.(cmd|bat)$/i.test(o),[t,n]=Rv(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:_v(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 zv(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 zv(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 zv(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=D(t),a=cv(n),o=Number(a.replace(/^v/,``).split(`.`)[0]),s=E(i,`node`),c=lv(s),u=r.nodeBin??null;if(u){if(!l(u))throw Error(`ezn.nodeBin 指定的 Node 不存在:${u}`);let t=e.probeMajor(u);if(t===null)throw Error(`ezn.nodeBin 指定的 Node 无法执行:${u}`);return t<o&&console.error(`[ezn] 警告:ezn.nodeBin 的 Node 主版本为 ${t},低于建议值 ${o},按用户指定继续。`),console.error(`[ezn] Node 运行时(ezn.nodeBin):${u}`),new e(u,s)}if(l(c)){let t=e.probeMajor(c);if(t!==null&&t>=o&&mv(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 Iv(s,n,{mirror:r.mirror??null}),new e(c,s)}},Uv=`24`;function Wv(e=st){let t={};return e.NODE_MIRROR&&(t.mirror=e.NODE_MIRROR),e.NODE_BIN&&(t.nodeBin=e.NODE_BIN),t}async function Gv(e){return(await Hv.ensure(e,Uv,Wv())).path}var Kv=new Map,qv=1;function Jv(){return typeof process.send==`function`}function Yv(e,t={},n=3e4){if(!process.send)return Promise.reject(Error(`未由 ezllm 主进程托管(源码运行模式),该功能不可用`));let r=qv++;return new Promise((i,a)=>{let o=setTimeout(()=>{Kv.delete(r),a(Error(`主进程未在 ${String(Math.round(n/1e3))}s 内响应(${e})`))},n);Kv.set(r,{resolve:e=>i(e),reject:a,timer:o}),process.send?.({type:e,id:r,args:t})})}function Xv(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=Kv.get(t.id);n&&(Kv.delete(t.id),clearTimeout(n.timer),t.error===void 0?n.resolve(t.data):n.reject(Error(t.error)))})}async function Zv(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 Qv=`当前为源码运行模式,更新功能不可用(仅 npm 全局安装的包支持自动更新)`,$v=`服务未由 ezllm 主进程托管,更新功能不可用;请在终端执行 ezllm update`,ey=9e5;function ty(e){let t=()=>{if(!Et())return!1;let e=T(wt);return C(e)===`node_modules`||C(T(e))===`node_modules`},n=()=>{let e=yl()?.autoUpdate;return typeof e!=`boolean`||e},r=()=>t()?Jv()?null:$v:Qv,i=new Kn;return i.get(`/autostart`,t=>t.json({ok:!0,...rg(e.appDir)})),i.post(`/autostart`,async t=>{let n=await Zv(t);if(n instanceof Response)return n;if(n){let{itemPath:n}=await ig({entryJs:At(),env:zh(),appDir:e.appDir,nodePath:await Gv(e.appDir)});return t.json({ok:!0,enabled:!0,itemPath:n,note:`已注册自启项,下次登录时自动启动服务`})}let{removed:r}=await ag({appDir:e.appDir});return t.json({ok:!0,enabled:!1,removed:r,note:r?`已移除自启项,且首次启动不再自动注册(重新开启即可解除)`:`原本未开启,无操作`})}),i.get(`/update`,e=>{let r=Nt(),i=r.pending??null,a=i!==null&&Date.now()-i.startedAt<ey;return e.json({ok:!0,enabled:n(),lastCheck:r.lastCheck??null,lastApply:r.lastApply??null,pendingUpdate:a&&i?i.toVersion:null,supported:t()&&Jv(),updating:a})}),i.post(`/update/enabled`,async e=>{let t=await Zv(e);if(t instanceof Response)return t;try{let e=yl();e&&xl({...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 Yv(`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 Yv(`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 ny=`服务未由 ezllm 主进程托管(源码运行模式),托管服务不可用;请用 ezllm 启动服务`;function ry(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=()=>Jv()?null:Response.json({ok:!1,error:ny},{status:400}),r=new Kn;return r.onError(gp),r.get(`/`,async e=>{let t=n();if(t)return t;let r=await Yv(`svc.list`);return e.json({ok:!0,...r})}),r.post(`/`,async e=>{let r=n();if(r)return r;let i=await up(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await Yv(`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 up(e);if(i===null)return e.json({ok:!1,error:`请求体不是合法 JSON 对象`},400);let a=await Yv(`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 Yv(`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 Yv(`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 Yv(`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 Yv(`child.restart`,{name:e.req.param(`name`)});return e.json({ok:!0,service:{name:e.req.param(`name`),...r}})}),r}function iy(e){let t=`${e}.ellm-bak`;return!l(t)&&(l(e)&&s(e,t),!0)}function ay(e){let t=`${e}.ellm-bak`;return l(t)?(s(t,e),h(t,{force:!0}),!0):!1}function oy(e,t){return String(e||``).replace(/\/+$/,``)===String(t||``).replace(/\/+$/,``)}var sy=E(b(),`.claude`,`settings.json`);function cy(){if(!l(sy))return null;try{return JSON.parse(f(sy,`utf-8`))}catch(e){throw Error(`${sy} 不是合法 JSON,拒绝修改(请先手工修复): ${e.message}`)}}function ly(e){let t=cy();return t?oy(t?.env?.ANTHROPIC_BASE_URL,e):!1}function uy(e){u(T(sy),{recursive:!0});let t=cy()??{};iy(sy),t.env={...t.env??{}},t.env.ANTHROPIC_BASE_URL=e.gatewayBase,t.env.ANTHROPIC_AUTH_TOKEN=e.token,y(sy,JSON.stringify(t,null,2)+`
|
|
94
|
+
`,`utf-8`)}function dy(e){if(ay(sy))return!0;let t=cy();return!t||!oy(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,y(sy,JSON.stringify(t,null,2)+`
|
|
95
|
+
`,`utf-8`),!0)}var fy=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,py=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(fy);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 my(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return[n.length,n.pop().length+1]}function hy(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+=`
|
|
100
96
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
101
|
-
`))}return i}var Q=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
102
|
-
`,t);return e.charCodeAt(n-1)===13&&n--,n}function
|
|
103
|
-
`;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
|
|
104
|
-
`),i=
|
|
105
|
-
`)?`${i}\n${r}`:i+r;
|
|
97
|
+
`))}return i}var Q=class extends Error{line;column;codeblock;constructor(e,t){let[n,r]=my(t.toml,t.ptr),i=hy(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}};function gy(e,t=0){let n=e.indexOf(`
|
|
98
|
+
`,t);return e.charCodeAt(n-1)===13&&n--,n}function _y(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 vy(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;_y(e)}}function yy(e,t,n){let r=e.p;if(!n){r=gy(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)_y(e);else if(r===n||r===t)return}throw new Q(`cannot find end of structure`,{toml:e.s,ptr:r})}var by=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,xy=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Sy=/^[+-]?0[0-9_]/;function Cy(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 wy(e,t,n){let r=e.s.slice(t,n),i=r.indexOf(`#`);return i>0&&(_y({s:r,p:i,d:0}),r=r.slice(0,i)),r.trimEnd()}function Ty(e,t,n){let r=e.p,i={toml:e.s,ptr:r};yy(e,44,n);let a=wy(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=by.test(a);if(o||xy.test(a)){if(Sy.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 py(a);if(!s.isValid())throw new Q(`invalid value`,i);return s}function Ey(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?Ay(e,n):ky(e,n);return e.d++,t}if(i===34||i===39)return Cy(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 Ty(e,n,t)}var Dy=/^[a-zA-Z0-9-_]+[ \t]*$/;function Oy(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=Cy(e);r=e.s.indexOf(`.`,e.p);let c=e.s.slice(e.p,r<0||r>a?a:r),l=gy(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(!Dy.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,vy(e,!0,!0),i}function ky(e,t){let n={},r=new Set,i;for(e.p++;e.p<e.s.length;){if(vy(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let a,o=n,s=!1,c=e.p,l=Oy(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=Ey(e,125,t);if(r.add(o[a]=u),vy(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 Ay(e,t){let n=[],r;for(e.p++;e.p<e.s.length;){if(vy(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Ey(e,93,t)),vy(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 jy(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 My(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={s:e,p:0,d:t},i={},a={},o,s=i,c=a;for(vy(r);r.p<e.length;){if(e.charCodeAt(r.p)===91){let t=e.charCodeAt(++r.p)===91;o=r.p+=+t;let n=Oy(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=jy(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=jy(Oy(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]]=Ey(r,void 0,n)}if(vy(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});vy(r)}return i}var Ny=`ellm-proxy`,Py=E(b(),`.codex`,`config.toml`),Fy=`# >>> ellm-proxy codex switch >>>`,Iy=`# <<< ellm-proxy codex switch <<<`;function Ly(e){return l(e)?f(e,`utf-8`):null}function Ry(){return RegExp(`${Fy}[\\s\\S]*?${Iy}\\n?`)}function zy(e,t,n=(e,t)=>ce(e,t,{stdio:`ignore`}),r=process.platform,i=E(b(),`.zshrc`)){let a=e=>e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/`/g,"\\`").replace(/\$/g,`\\$`),o=(e,t,n)=>{let r=[Fy,`export ${e}="${a(t)}"`,Iy,``].join(`
|
|
100
|
+
`),i=Ly(n)??``,o=Ry(),s=o.test(i)?i.replace(o,r):i&&!i.endsWith(`
|
|
101
|
+
`)?`${i}\n${r}`:i+r;u(T(n),{recursive:!0}),y(n,s,`utf-8`)};if(r===`win32`)n(`setx`,[e,t]);else if(r!==`darwin`)return!1;else o(e,t,i);return process.env[e]=t,!0}function By(e,t=E(b(),`.zshrc`),n=process.platform){if(n!==`darwin`)return!1;let r=Ly(t),i=r?.match(Ry());return!r||!i||!i[0].includes(`export ${e}=`)?!1:(y(t,r.replace(Ry(),``),`utf-8`),!0)}function Vy(e){try{return My(e)?.model_provider===Ny}catch{return!1}}function Hy(e,t){let n;try{n=My(e)}catch(e){throw Error(`编辑后的 config.toml 不是合法 TOML,已保留原文件: ${e.message}`)}if(t&&n?.model_provider!==Ny)throw Error(`编辑后的 config.toml 顶层 model_provider 不是 "${Ny}",已保留原文件`)}function Uy(){let e=Ly(Py);return e?Vy(e):!1}function Wy(e){let t=(()=>{let e=Ny.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`^\\s*\\[model_providers\\.(?:"|')?(?:${e}|ezllm)(?:"|')?\\]\\s*$`)})(),n=e.split(`
|
|
106
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(`
|
|
107
103
|
`).replace(/\n{3,}$/,`
|
|
108
104
|
|
|
109
|
-
`)}function
|
|
110
|
-
`),n=`model_provider = "${
|
|
105
|
+
`)}function Gy(e){let t=e=>{let t=e.split(`
|
|
106
|
+
`),n=`model_provider = "${Ny}"`,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(`
|
|
111
107
|
`);let a=i.findIndex(e=>/^\s*\[/.test(e));return a===-1?[...i,n].join(`
|
|
112
108
|
`):(i.splice(a,0,n,``),i.join(`
|
|
113
|
-
`))}
|
|
114
|
-
`);return
|
|
109
|
+
`))};u(T(Py),{recursive:!0});let n=Ly(Py);if(n!==null)try{My(n)}catch(e){throw Error(`${Py} 不是合法 TOML,拒绝修改(请先手工修复): ${e.message}`)}let r=n??``;iy(Py),r=Wy(r),r=t(r);let i=[`[model_providers.${Ny}]`,`name = "ezllm gateway"`,`base_url = "${e.gatewayBase}/v1"`,`wire_api = "chat"`,`env_key = "ELLM_PROXY_API_KEY"`].join(`
|
|
110
|
+
`);return r=r.replace(/\s*$/,``)+`
|
|
115
111
|
|
|
116
|
-
`+
|
|
117
|
-
`,
|
|
112
|
+
`+i+`
|
|
113
|
+
`,Hy(r,!0),y(Py,r,`utf-8`),e.apiKey?zy(`ELLM_PROXY_API_KEY`,e.apiKey):!1}function Ky(){let e=ay(Py),t=By(`ELLM_PROXY_API_KEY`);if(delete process.env.ELLM_PROXY_API_KEY,e)return!0;let n=Ly(Py);if(!n||!Vy(n))return t;let r=Wy(n);return r=r.split(`
|
|
118
114
|
`).filter(e=>!/^\s*model_provider\s*=\s*["']?ellm-proxy["']?\s*$/.test(e)).join(`
|
|
119
|
-
`),
|
|
120
|
-
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),
|
|
115
|
+
`),Hy(r,!1),y(Py,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})),qy=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})),Jy=I((e=>{var t=$(),n=qy(),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})),Yy=I((e=>{var t=$(),n=qy();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})),Xy=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})),Zy=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})),Qy=I((e=>{var t=Xy(),n=$(),r=Zy();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}}})),$y=I((e=>{var t=Yy(),n=qy(),r=$(),i=Qy(),a=Zy(),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})),eb=I((e=>{var t=$(),n=Qy(),r=Zy(),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})),tb=I((e=>{var t=$y(),n=$(),r=eb(),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})),nb=I((e=>{var t=tb(),n=$(),r=Qy();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})),rb=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(`
|
|
121
117
|
`)?n(r,t):r.includes(`
|
|
122
118
|
`)?`
|
|
123
|
-
`+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),
|
|
119
|
+
`+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),ib=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===`
|
|
124
120
|
`)i===n&&(v=a(e,v,t.length)),m=v+t.length+d,h=void 0;else{if(o===` `&&g&&g!==` `&&g!==`
|
|
125
121
|
`&&g!==` `){let t=e[v+1];t&&t!==` `&&t!==`
|
|
126
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!==`
|
|
127
|
-
`);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})),ab=I((e=>{var t=eb(),n=ib(),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]===`
|
|
128
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)+`
|
|
129
125
|
|
|
130
126
|
`;a[e+2]===`\\`&&a[e+3]===`n`&&a[e+4]!==`"`;)l+=`
|
|
@@ -142,29 +138,29 @@ import{createRequire as e}from"node:module";import{homedir as t,networkInterface
|
|
|
142
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(`
|
|
143
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(`
|
|
144
140
|
`)?c(d,a):u(e,a,o,s);if(!p&&!g&&l!==t.Scalar.PLAIN&&d.includes(`
|
|
145
|
-
`))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})),ob=I((e=>{var t=Yy(),n=$(),r=rb(),i=ab();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})),sb=I((e=>{var t=$(),n=eb(),r=ob(),i=rb();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?`
|
|
146
142
|
`:``,S){let e=p(S);E+=`\n${i.indentComment(e,o.indent)}`}T===``&&!o.inFlow?E===`
|
|
147
143
|
`&&C&&(E=`
|
|
148
144
|
|
|
149
145
|
`):E+=`\n${o.indent}`}else if(!_&&t.isCollection(a)){let e=T[0],t=T.indexOf(`
|
|
150
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]===`
|
|
151
|
-
`)&&(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})),cb=I((e=>{var t=_e(`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})),lb=I((e=>{var t=$(),n=eb(),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})),ub=I((e=>{var t=cb(),n=lb(),r=ob(),i=$(),a=Zy();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=tb(),n=sb(),r=ub(),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})),fb=I((e=>{var t=$(),n=ob(),r=rb();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}`:`
|
|
152
148
|
`}}return e?(_+=`
|
|
153
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(`
|
|
154
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}`:`
|
|
155
|
-
`;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})),
|
|
156
|
-
`:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),YS=L((e=>{var t=$(),n=PS(),r=CS(),i=RS();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})),XS=L((e=>{var t=$(),n=bS(),r=IS(),i=RS(),a=YS(),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})),ZS=L((e=>{var t=CS();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})),QS=L((e=>{var t=CS(),n=US(),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})),$S=L((e=>{var t=US(),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})),eC=L((e=>{var t=$(),n=PS(),r=IS(),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})),tC=L((e=>{var t=US();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})),nC=L((e=>{var t=LS(),n=VS(),r=zS(),i=BS(),a=JS(),o=ZS(),s=QS(),c=$S(),l=MS(),u=XS(),d=YS(),f=eC(),p=tC();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]})),rC=L((e=>{var t=LS(),n=VS(),r=zS(),i=BS(),a=HS(),o=WS(),s=GS(),c=KS(),l=qS(),u=JS(),d=MS(),f=XS(),p=YS(),m=nC(),h=eC(),g=tC(),_=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})),iC=L((e=>{var t=$(),n=LS(),r=zS(),i=BS(),a=rC(),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}}})),aC=L((e=>{var t=$(),n=kS(),r=ES();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})),pb=I((e=>{var t=fb(),n=ub(),r=nb(),i=$(),a=db(),o=eb();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})),mb=I((e=>{var t=$(),n=pb();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)}})),hb=I((e=>{var t=tb(),n=fb(),r=nb(),i=$(),a=eb(),o=Zy(),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})),gb=I((e=>{var t=$(),n=hb();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)}})),_b=I((e=>{var t=ab();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)}}})),vb=I((e=>{var t=eb(),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})),yb=I((e=>{var t=eb(),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})),bb=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})),xb=I((e=>{var t=eb(),n=bb(),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})),Sb=I((e=>{var t=bb(),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`)}})),Cb=I((e=>{var t=mb(),n=vb(),r=gb(),i=_b(),a=yb(),o=xb(),s=Sb();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),wb=I((e=>{var t=eb(),n=mb(),r=gb();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}})})),Tb=I((e=>{var t=_e(`buffer`),n=eb(),r=ab();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)}}})),Eb=I((e=>{var t=$(),n=db(),r=eb(),i=hb();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})),Db=I((e=>{var t=$(),n=Zy(),r=pb(),i=hb(),a=Eb(),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})),Ob=I((e=>{var t=eb();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})),kb=I((e=>{var t=eb(),n=bb(),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})),Ab=I((e=>{var t=bb(),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})),jb=I((e=>{var t=$(),n=db(),r=pb(),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})),Mb=I((e=>{var t=bb();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})),Nb=I((e=>{var t=mb(),n=vb(),r=gb(),i=_b(),a=Tb(),o=Ob(),s=kb(),c=Ab(),l=lb(),u=Db(),d=Eb(),f=jb(),p=Mb();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]})),Pb=I((e=>{var t=mb(),n=vb(),r=gb(),i=_b(),a=yb(),o=xb(),s=Sb(),c=Cb(),l=wb(),u=Tb(),d=lb(),f=Db(),p=Eb(),m=Nb(),h=jb(),g=Mb(),_=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})),Fb=I((e=>{var t=$(),n=mb(),r=gb(),i=_b(),a=Pb(),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}}})),Ib=I((e=>{var t=$(),n=ob(),r=rb();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(`
|
|
157
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(`
|
|
158
154
|
`)+`
|
|
159
|
-
`}e.stringifyDocument=i})),
|
|
160
|
-
`),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`}}})),
|
|
161
|
-
`))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})),Lb=I((e=>{var t=$y(),n=nb(),r=$(),i=db(),a=Zy(),o=Fb(),s=Ib(),c=Yy(),l=Xy(),u=tb(),d=Jy(),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})),Rb=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`}}})),zb=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})),Bb=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})),Vb=I((e=>{var t=Bb();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})),Hb=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})),Ub=I((e=>{var t=db(),n=pb(),r=zb(),i=Bb(),a=Vb(),o=Hb(),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+=`
|
|
162
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+=`
|
|
163
|
-
`+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})),Wb=I((e=>{var t=hb(),n=zb(),r=Vb();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})),Gb=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})),Kb=I((e=>{var t=$(),n=db(),r=pb(),i=hb(),a=Gb(),o=zb(),s=Bb(),c=Hb(),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+=`
|
|
164
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+=`
|
|
165
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+=`
|
|
166
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+=`
|
|
167
|
-
`+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})),qb=I((e=>{var t=$(),n=eb(),r=pb(),i=hb(),a=Ub(),o=Wb(),s=Kb();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})),Jb=I((e=>{var t=eb();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?`
|
|
168
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)+`
|
|
169
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=`
|
|
170
166
|
`):n.length>d||r[0]===` `?(h===` `?h=`
|
|
@@ -179,7 +175,7 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
179
175
|
`+l[e][0].slice(d);m[m.length-1]!==`
|
|
180
176
|
`&&(m+=`
|
|
181
177
|
`);break;default:m+=`
|
|
182
|
-
`}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})),Yb=I((e=>{var t=eb(),n=Gb();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?
|
|
183
179
|
`,`sy`),n=RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
184
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===`
|
|
185
181
|
`?i+=a:a=`
|
|
@@ -194,10 +190,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
194
190
|
`);)r===`
|
|
195
191
|
`&&(n+=`
|
|
196
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:`
|
|
197
|
-
`,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})),Xb=I((e=>{var t=$(),n=eb(),r=Jb(),i=Yb();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})),Zb=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})),Qb=I((e=>{var t=$y(),n=$(),r=qb(),i=Xb(),a=Gb(),o=Zb(),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})),$b=I((e=>{var t=Lb(),n=Qb(),r=Gb(),i=zb();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})),ex=I((e=>{var t=_e(`process`),n=Jy(),r=Lb(),i=Rb(),a=$(),o=$b(),s=Gb();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?`
|
|
198
194
|
|
|
199
195
|
`:`
|
|
200
|
-
`)+(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}}}})),tx=I((e=>{var t=Jb(),n=Yb(),r=Rb(),i=ab();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:`
|
|
201
197
|
`}];switch(c[0]){case`|`:case`>`:{let e=c.indexOf(`
|
|
202
198
|
`),t=c.substring(0,e),n=c.substring(e+1)+`
|
|
203
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:`
|
|
@@ -205,9 +201,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
205
201
|
`),r=t.substring(0,n),i=t.substring(n+1)+`
|
|
206
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:`
|
|
207
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:`
|
|
208
|
-
`};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})),nx=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})),rx=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})),ix=I((e=>{var t=tx(),n=nx(),r=rx(),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`
|
|
209
205
|
`:case`\r
|
|
210
|
-
`: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})),ax=I((e=>{var t=ix();function n(e){switch(e){case void 0:case` `:case`
|
|
211
207
|
`:case`\r`:case` `:return!0;default:return!1}}var r=new Set(`0123456789ABCDEFabcdef`),i=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),a=new Set(`,[]{}`),o=new Set(` ,[]{}
|
|
212
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===`
|
|
213
209
|
`||t===`\r`&&this.buffer[e+1]===`
|
|
@@ -226,10 +222,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
226
222
|
`,t=this.buffer[i+1]):r=i),t===`#`||e&&a.has(t))break;if(o===`
|
|
227
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===`
|
|
228
224
|
`?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
|
|
229
|
-
`?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)}}})),ox=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}}}}})),sx=I((e=>{var t=_e(`process`),n=ix(),r=ax();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(`
|
|
230
226
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
231
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(`
|
|
232
228
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
233
|
-
`,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())}}}})),jC=L((e=>{var t=CC(),n=oC(),r=sC(),i=jS(),a=$(),o=kC(),s=AC();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})),MC=L((e=>{var t=CC(),n=oC(),r=iC(),i=sC(),a=SS(),o=$(),s=PS(),c=CS(),l=IS(),u=RS();DC();var d=OC(),f=kC(),p=AC(),m=jC(),h=gS();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}))(),NC=`DEEPSEEK_API_KEY`,PC=1,FC=`ezllm`,IC=()=>process.env.DSH_HOME||E(t(),`.dsh`),LC=()=>E(IC(),`settings.yaml`),RC=()=>E(IC(),`.credentials.yaml`);function zC(e){if(!f(e))return null;let t=h(e,`utf-8`);return t.trim()===``?null:t}function BC(e,t){let n=(0,MC.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function VC(e){return`${e}/v1`}function HC(e){let t=zC(LC());if(!t)return!1;try{return Tx(BC(t,LC()).toJS()?.[`llm-deepseek`]?.baseURL,VC(e))}catch{return!1}}function UC(e){let t=VC(e.gatewayBase);p(IC(),{recursive:!0});let n=LC(),r=zC(n),i=BC(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);Cx(n),i.setIn([`llm-deepseek`,`baseURL`],t),GC(n,i);let o=RC(),s=e.masterKey||FC,c=zC(o);if(Cx(o),c===null){let e=BC(``,o);e.set(`version`,PC),e.setIn([`refs`,NC],s),GC(o,e);return}let l=BC(c,o),u=l.toJS();if(!(0,MC.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(u.version!==void 0&&u.version!==PC)throw Error(`${o} 的 version 为 ${String(u.version)},本开关仅支持 version: ${String(PC)}`);if(u.version===void 0){if(!Object.values(u).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(NC,s)}else{if(u.refs!==void 0&&(typeof u.refs!=`object`||u.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,NC],s)}GC(o,l)}function WC(e,t){let n=LC(),r=RC(),i=!1;if(wx(n))i=!0;else{let t=zC(n);if(t){let r=BC(t,n);if(Tx(r.toJS()?.[`llm-deepseek`]?.baseURL,VC(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`]),GC(n,r),i=!0}}}if(wx(r))i=!0;else{let e=zC(r);if(e){let n=BC(e,r),a=n.toJS(),o=e=>e===t||e===FC;a?.version===PC&&o(a?.refs?.[NC])?(n.deleteIn([`refs`,NC]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),GC(r,n),i=!0):a?.version===void 0&&o(a?.[NC])&&(n.deleteIn([NC]),GC(r,n),i=!0)}}return i}function GC(e,t){let n=t.toString(),r=(0,MC.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 KC(e){try{return JSON.parse(h(e,`utf-8`)).masterKey||``}catch{return``}}function qC(e){let t=new nr;return t.get(`/`,t=>{let n=U_(e);return t.json({ok:!0,claudeCode:Ox(n),codex:uS(),dsh:HC(n),gatewayBase:n})}),t.post(`/claude-code`,async t=>{let n=await dx(t);if(n instanceof Response)return n;let r=U_(e);if(n){let e=KC(yt());return e?(kx({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: ${yt()}`},400)}let i=Ax(r);return t.json({ok:!0,claudeCode:!1,changed:i,note:i?`已从备份还原`:`原本未开启,无操作`})}),t.post(`/codex`,async t=>{let n=await dx(t);if(n instanceof Response)return n;let r=U_(e);if(n){let e=KC(yt()),n=mS({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=hS();return t.json({ok:!0,codex:!1,changed:i,note:i?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),t.post(`/dsh`,async t=>{let n=await dx(t);if(n instanceof Response)return n;let r=U_(e),i=KC(yt());if(n)return UC({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=WC(r,i);return t.json({ok:!0,dsh:!1,changed:a,note:a?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),t}var JC=(e,t=YC)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},YC={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`},XC=/^\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,ZC={br:`.br`,zstd:`.zst`,gzip:`.gz`},QC=Object.keys(ZC),$C=(()=>{let[e,t]=me.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),ew=e=>$C?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()}}),tw=e=>{let t;try{t=ce(e)}catch{}return t},nw=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},rw=e=>nw(e,decodeURI),iw=(e={root:``})=>{let t=e.root||``,n=e.path;return t!==``&&!se(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=rw(r.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(a))throw Error()}catch{return await e.onNotFound?.(r.req.path,r),i()}let o=le(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(a,r):a),s=tw(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=le(o,t),s=tw(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=JC(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||XC.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of QC){if(!e.has(t))continue;let n=tw(o+ZC[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=ZC[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(ew(oe(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=oe(o,{start:t,end:n});r.header(`Content-Length`,i.toString()),r.header(`Content-Range`,`bytes ${t}-${n}/${s.size}`),l=r.body(ew(a),206)}return await e.onFound?.(o,r),l}},aw=T(k(import.meta.url));function ow(){return[E(aw,`web-ui`),D(aw,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),D(aw,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>f(E(e,`index.html`)))??E(aw,`web-ui`)}function sw(e,t){let n=t??ow();f(E(n,`index.html`))&&(e.get(`/`,async e=>{try{let t=await I(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 iw({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 cw(e,t,n){let r=new nr;return r.use(`/v1/*`,Bm()),r.route(`/api/auth`,Um),r.route(`/api/setup`,Qm()),r.use(`/api/*`,Gm),r.route(`/api/config`,$m({runtime:e})),r.route(`/api/test`,rh(e)),r.route(`/api/latency`,Th(e)),r.route(`/api/usage`,Oh()),r.route(`/api/quota`,x_()),r.route(`/api/logs`,j_()),r.route(`/api/status`,S_(e,n)),t&&(r.route(`/api/service`,K_(t)),r.route(`/api/service`,vx(t)),r.route(`/api/service/managed`,Sx(t)),r.route(`/api/harness`,qC(t))),r.route(`/`,e.proxy),sw(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(qm),r}var lw=6e4;function uw(){let e=bu()?.latencyTest;return typeof e==`object`&&e?e:{}}function dw(e,t,n){if(e.enabled!==!0)return!1;let r=(e.intervalMinutes??60)*60*1e3;return t===void 0||n-t>=r}function fw(e){return{name:`latencyAutoTest`,everyMs:lw,run:async()=>{try{if(Sh(e)===0||!dw(uw(),fh()??void 0,Date.now()))return;z(`[latency] 自动测试触发`),await xh(e)}catch(e){B(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var pw=6e5,mw=3e4;function hw(){return{name:`quotaRefresh`,everyMs:pw,firstDelayMs:mw,run:async()=>{try{await v_()}catch(e){B(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var gw=6e4,_w=3e4,vw=20,yw=3e4,bw=1024,xw=/^[^\u0000-\u001f\u007f]{1,24}$/u,Sw=new Set([`unknown`,`n/a`,`na`,`-`,`未知`,`无法判断`]),Cw=[`你是日志归类助手:给定若干 HTTP User-Agent 字符串,判断每个 UA 属于哪个客户端产品。`,`只输出一个 JSON 数组,元素形如 {"i":<序号>,"name":"<客户端短名>"},不要解释、不要代码块、不要多余文字。`,`name 用该客户端常见的写法(如 CodeBuddy、Claude Code、ZCode、curl),限 1~24 个字符、不含换行;无法判断时 name 用 unknown。`].join(`
|
|
234
|
-
`);function
|
|
235
|
-
`),
|
|
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())}}}})),cx=I((e=>{var t=ex(),n=Lb(),r=Rb(),i=cb(),a=$(),o=ox(),s=sx();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})),lx=I((e=>{var t=ex(),n=Lb(),r=Fb(),i=Rb(),a=$y(),o=$(),s=db(),c=eb(),l=pb(),u=hb();ix();var d=ax(),f=ox(),p=sx(),m=cx(),h=qy();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}))(),ux=`DEEPSEEK_API_KEY`,dx=1,fx=`ezllm`,px=()=>process.env.DSH_HOME||E(b(),`.dsh`),mx=()=>E(px(),`settings.yaml`),hx=()=>E(px(),`.credentials.yaml`);function gx(e){if(!l(e))return null;let t=f(e,`utf-8`);return t.trim()===``?null:t}function _x(e,t){let n=(0,lx.parseDocument)(e);if(n.errors.length>0)throw Error(`${t} 不是合法 YAML,拒绝修改(请先手工修复): ${n.errors[0]?.message??`未知错误`}`);return n}function vx(e){return`${e}/v1`}function yx(e){let t=gx(mx());if(!t)return!1;try{return oy(_x(t,mx()).toJS()?.[`llm-deepseek`]?.baseURL,vx(e))}catch{return!1}}function bx(e){let t=vx(e.gatewayBase);u(px(),{recursive:!0});let n=mx(),r=gx(n),i=_x(r===null?``:r,n),a=i.toJS();if(a&&a[`llm-deepseek`]!==void 0&&typeof a[`llm-deepseek`]!=`object`)throw Error(`${n} 的 llm-deepseek 不是映射结构,拒绝修改`);iy(n),i.setIn([`llm-deepseek`,`baseURL`],t),Sx(n,i);let o=hx(),s=e.masterKey||fx,c=gx(o);if(iy(o),c===null){let e=_x(``,o);e.set(`version`,dx),e.setIn([`refs`,ux],s),Sx(o,e);return}let l=_x(c,o),d=l.toJS();if(!(0,lx.isMap)(l.contents))throw Error(`${o} 根节点不是映射结构,拒绝修改`);if(d.version!==void 0&&d.version!==dx)throw Error(`${o} 的 version 为 ${String(d.version)},本开关仅支持 version: ${String(dx)}`);if(d.version===void 0){if(!Object.values(d).every(e=>typeof e==`string`&&e.length>0))throw Error(`${o} 既非 version:1 也非旧版扁平结构,请手工整理后重试`);l.set(ux,s)}else{if(d.refs!==void 0&&(typeof d.refs!=`object`||d.refs===null))throw Error(`${o} 的 refs 不是映射结构,拒绝修改`);l.setIn([`refs`,ux],s)}Sx(o,l)}function xx(e,t){let n=mx(),r=hx(),i=!1;if(ay(n))i=!0;else{let t=gx(n);if(t){let r=_x(t,n);if(oy(r.toJS()?.[`llm-deepseek`]?.baseURL,vx(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`]),Sx(n,r),i=!0}}}if(ay(r))i=!0;else{let e=gx(r);if(e){let n=_x(e,r),a=n.toJS(),o=e=>e===t||e===fx;a?.version===dx&&o(a?.refs?.[ux])?(n.deleteIn([`refs`,ux]),Object.keys(n.toJS()?.refs??{}).length===0&&n.deleteIn([`refs`]),Sx(r,n),i=!0):a?.version===void 0&&o(a?.[ux])&&(n.deleteIn([ux]),Sx(r,n),i=!0)}}return i}function Sx(e,t){let n=t.toString(),r=(0,lx.parseDocument)(n);if(r.errors.length>0)throw Error(`编辑后的 ${e} 不是合法 YAML,已保留原文件: ${r.errors[0]?.message??`未知错误`}`);u(T(e),{recursive:!0}),y(e,n,`utf-8`)}function Cx(e){let t=e=>{try{return JSON.parse(f(e,`utf-8`)).masterKey||``}catch{return``}},n=new Kn;return n.get(`/`,t=>{let n=Dh(e);return t.json({ok:!0,claudeCode:ly(n),codex:Uy(),dsh:yx(n),gatewayBase:n})}),n.post(`/claude-code`,async n=>{let r=await Zv(n);if(r instanceof Response)return r;let i=Dh(e);if(r){let e=t(pt());return e?(uy({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: ${pt()}`},400)}let a=dy(i);return n.json({ok:!0,claudeCode:!1,changed:a,note:a?`已从备份还原`:`原本未开启,无操作`})}),n.post(`/codex`,async n=>{let r=await Zv(n);if(r instanceof Response)return r;let i=Dh(e);if(r){let e=t(pt()),r=Gy({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=Ky();return n.json({ok:!0,codex:!1,changed:a,note:a?`已从备份还原(macOS 会同时清理 ~/.zshrc 中自动写入的环境变量托管块)`:`原本未开启,无操作`})}),n.post(`/dsh`,async n=>{let r=await Zv(n);if(r instanceof Response)return r;let i=Dh(e),a=t(pt());if(r)return bx({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=xx(i,a);return n.json({ok:!0,dsh:!1,changed:o,note:o?`已从备份还原(或移除本开关写入的字段)`:`原本未开启,无操作`})}),n}var wx=(e,t=Tx)=>{let n=e.match(/\.([a-zA-Z0-9]+?)$/);if(n)return t[n[1].toLowerCase()]},Tx={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`},Ex=/^\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,Dx={br:`.br`,zstd:`.zst`,gzip:`.gz`},Ox=Object.keys(Dx),kx=(()=>{let[e,t]=fe.node.split(`.`).map(e=>parseInt(e));return e>=23||e===22&&t>=7||e===20&&t>=18})(),Ax=e=>kx?i.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()}}),jx=e=>{let t;try{t=he(e)}catch{}return t},Mx=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},Nx=e=>Mx(e,decodeURI),Px=(e={root:``})=>{let t=e.root||``,n=e.path;return t!==``&&!me(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=Nx(r.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(a))throw Error()}catch{return await e.onNotFound?.(r.req.path,r),i()}let o=ge(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(a,r):a),s=jx(o);if(s&&s.isDirectory()){let t=e.index??`index.html`;o=ge(o,t),s=jx(o)}if(!s)return await e.onNotFound?.(o,r),i();let c=wx(o);if(r.header(`Content-Type`,c||`application/octet-stream`),e.precompressed&&(!c||Ex.test(c))){let e=new Set(r.req.header(`Accept-Encoding`)?.split(`,`).map(e=>e.trim()));for(let t of Ox){if(!e.has(t))continue;let n=jx(o+Dx[t]);if(n){r.header(`Content-Encoding`,t),r.header(`Vary`,`Accept-Encoding`,{append:!0}),s=n,o+=Dx[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(Ax(pe(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=pe(o,{start:t,end:n});r.header(`Content-Length`,i.toString()),r.header(`Content-Range`,`bytes ${t}-${n}/${s.size}`),l=r.body(Ax(a),206)}return await e.onFound?.(o,r),l}},Fx=T(A(import.meta.url));function Ix(e,t){let n=t??[E(Fx,`web-ui`),D(Fx,`..`,`..`,`..`,`..`,`app`,`web`,`dist`),D(Fx,`..`,`..`,`..`,`app`,`web`,`dist`)].find(e=>l(E(e,`index.html`)))??E(Fx,`web-ui`);l(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 Px({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 Lx(e,t,n){let r=new Kn;return r.use(`/v1/*`,lp()),r.route(`/api/auth`,fp),r.route(`/api/setup`,bp()),r.use(`/api/*`,mp),r.route(`/api/config`,xp({runtime:e})),r.route(`/api/test`,Tp(e)),r.route(`/api/latency`,Gp(e)),r.route(`/api/usage`,Kp()),r.route(`/api/quota`,vh()),r.route(`/api/logs`,Eh()),r.route(`/api/status`,xh(e,n)),t&&(r.route(`/api/service`,kh(t)),r.route(`/api/service`,ty(t)),r.route(`/api/service/managed`,ry(t)),r.route(`/api/harness`,Cx(t))),r.route(`/`,e.proxy),Ix(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(gp),r}var Rx=6e4;function zx(e){let t=()=>{let e=yl()?.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:Rx,run:async()=>{try{if(Hp(e)===0)return;let r=t();if(!n(r,Pp()??void 0,Date.now()))return;L(`[latency] 自动测试触发`),await Vp(e)}catch(e){R(`[latency] 自动测试执行异常:`,e instanceof Error?e.message:String(e))}}}}var Bx=6e5,Vx=3e4;function Hx(){return{name:`quotaRefresh`,everyMs:Bx,firstDelayMs:Vx,run:async()=>{try{await _h()}catch(e){R(`[quota] 定时刷新异常:`,e instanceof Error?e.message:String(e))}}}}var Ux=6e4,Wx=3e4,Gx=20,Kx=3e4,qx=1024,Jx=/^[^\u0000-\u001f\u007f]{1,24}$/u,Yx=new Set([`unknown`,`n/a`,`na`,`-`,`未知`,`无法判断`]),Xx=[`你是日志归类助手:给定若干 HTTP User-Agent 字符串,判断每个 UA 属于哪个客户端产品。`,`只输出一个 JSON 数组,元素形如 {"i":<序号>,"name":"<客户端短名>"},不要解释、不要代码块、不要多余文字。`,`name 用该客户端常见的写法(如 CodeBuddy、Claude Code、ZCode、curl),限 1~24 个字符、不含换行;无法判断时 name 用 unknown。`].join(`
|
|
230
|
+
`);async function Zx(e){let t=async(e,t)=>{let n=(e,t)=>{let n=Cp((e.apiBase??``).replace(/\/+$/,``),e.autoV1??!0);return e.provider===`anthropic`?{url:`${n}/messages`,payload:{model:e.modelName,system:Xx,messages:[{role:`user`,content:t}],max_tokens:qx}}:e.provider===`openai-responses`?{url:`${n}/responses`,payload:{model:e.modelName,instructions:Xx,input:t,max_output_tokens:qx}}:{url:`${n}/chat/completions`,payload:{model:e.modelName,messages:[{role:`system`,content:Xx},{role:`user`,content:t}],max_tokens:qx}}},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?wp(e.apiKey,e.provider):{}},s=await fetch(i,{method:`POST`,headers:o,body:JSON.stringify(a),signal:AbortSignal.timeout(Kx)});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=ef({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();Jx.test(o)&&(Yx.has(o.toLowerCase())||n.set(i,o))}return n},i=Bf(Gx);if(i.length===0)return{resolved:0,fallback:0,failed:0};let a=n(e);if(a===null)return ct(`[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=Vf(l,`llm`),d=i.filter(e=>!l.has(e)),f=Hf(d),p=new Map;for(let e of f){let t=Qf(e);t!==``&&p.set(e,t)}let m=Vf(p,Of);return c!==null&&ct(`[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 Qx(e){return{name:`clientNameResolve`,everyMs:Ux,firstDelayMs:Wx,run:async()=>{try{await Zx(e)}catch(e){R(`[client-name] 识别作业异常:`,e instanceof Error?e.message:String(e))}}}}var $x=`--log-backfill`;function eS(e=process.argv){return e.includes($x)}async function tS(){L(`[log-backfill] 开始存量补齐(入站头 → 会话标识;客户端短名随后由服务内作业定名)`),gd();let e=ep({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=rp({onProgress:e=>L(`[log-backfill] ${e}`)});L(`[log-backfill] 会话标识:扫描 ${String(t.scanned)} 行,补 session_id ${String(t.filled)} 行`),L(`[log-backfill] 完成`)}function nS(e={}){let t=e.entry??process.argv[1];if(t===void 0||t===``)return{started:!1,reason:`拿不到本进程入口(process.argv[1] 为空)`};let n=e.spawnFn??le,r,i;try{return u(ht(),{recursive:!0}),r=d(E(ht(),`out-backfill.log`),`a`),i=d(E(ht(),`err-backfill.log`),`a`),n(process.execPath,[...e.execArgv??process.execArgv,t,$x],{detached:!0,stdio:[`ignore`,r,i],env:{...process.env,ELLM_APP_DIR:dt()}}).unref(),{started:!0,reason:``}}catch(e){return{started:!1,reason:e instanceof Error?e.message:String(e)}}finally{r!==void 0&&o(r),i!==void 0&&o(i)}}function rS(e={}){let t=nS(e);return t.started||R(`[log-backfill] 存量补齐子进程未拉起:${t.reason}`),t}eS()&&(await tS(),process.exit(0));var iS=bl();iS===null&&(R(`[ezllm] 缺少配置文件 ${pt()}(参考 ezllm.config.example.json)`),process.exit(1));var aS=iS;gd(),Ap();var oS=new au({maxBytes:zl().maxBytes}),sS=bf({spool:oS,getConfig:()=>zl()}),cS=iu();cS>0&&L(`[ezllm] spool 启动清理:回收中断残留 ${String(cS)} 个中转文件`),await Sf(),rS();var lS=new Yf({spool:oS}),uS=()=>aS.providers.flatMap(e=>e.models.map(e=>e.modelName)),dS=await op(aS,{authorize(e){let t=Ol();return t===``||e===`Bearer ${t}`},register(e){e.addHook(`onAuthorize`,e=>{let t=Ol();t!==``&&(e.headers.authorization??``)!==`Bearer ${t}`&&e.reject(`invalid api key`)}),cp(e,{knownModelNames:uS})}},{traceSink:lS}),fS={port:0,startedAt:Date.now(),appDir:dt()},pS=Pl(),mS=Lx(dS,fS,pS),hS=Pt({jobs:[sS,Ef({getRetention:()=>Rl()}),zx(dS),Hx(),Qx(dS)]}),gS=await yS(mS,ap(dS),pS.hostname);fS.port=gS;var _S=!1;function vS(e,t=0){_S||(_S=!0,hS.stop(),L(`[ezllm] ${e},服务退出`),Promise.race([lS.flush(),new Promise(e=>setTimeout(e,5e3))]).then(()=>process.exit(t)))}Xv(()=>vS(`与主进程的 IPC 连接已断开`));for(let e of[`SIGINT`,`SIGTERM`])process.on(e,()=>vS(`收到 ${e}`));bS(gS,pS);async function yS(e,t,n){let r=Date.now()+1e4;for(;;)try{return await new Promise((r,i)=>{let a=rt({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 bS(e,t){let n=yh(t.hostname)?`localhost`:t.hostname,r=yh(t.hostname)?`全部网卡`:t.hostname,i=t.source===`credentials`?`未设置任何凭据(主密钥与登录账号皆无),强制仅本机(设置页开关已忽略)`:t.hostname===`127.0.0.1`?`设置页「允许局域网访问」已关闭`:`设置页「允许局域网访问」开启(缺省)`;if(L(`========================================`),L(` EZLLM 服务(网关 + 管理台,单进程)`),L(` 网关端点: http://${n}:${String(e)}/v1/*`),L(` 管理台: http://${n}:${String(e)}/(管理 API 与界面同端口,登录后使用)`),L(` 监听地址: ${r}:${String(e)}(${i})`),yh(t.hostname))for(let t of bh())L(` 局域网访问: http://${t}:${String(e)}`);L(` 模型数量: ${String(dS.current.expanded.deployments.names.length)}`),Ml().completed||L(` ⚠ 首次启动:请打开 http://${n}:${String(e)}/ 完成初始化向导(设置主密钥与登录账号)`),L(`========================================`)}export{};
|