blink 0.1.51 → 0.1.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/chunk-ByIbJXPc.js +1 -0
- package/dist/cli/dev-DD1tf2AT.js +1625 -0
- package/dist/cli/devtools-D6beCbGn.js +91 -0
- package/dist/cli/esm-DiE8Xvft.js +1 -0
- package/dist/cli/execAsync-Cr3GNTA4.js +1 -0
- package/dist/cli/getMachineId-bsd-CY-GIKzh.js +1 -0
- package/dist/cli/getMachineId-darwin-BvUyLisY.js +2 -0
- package/dist/cli/getMachineId-linux-CaBhu4UD.js +1 -0
- package/dist/cli/getMachineId-unsupported-DsibGvjs.js +1 -0
- package/dist/cli/getMachineId-win-_QXKq1ge.js +1 -0
- package/dist/cli/index.js +36 -2046
- package/dist/cli/main-CiEwxfsi.js +138 -0
- package/dist/cli/undici-0ADe8h0l.js +94 -0
- package/dist/cli/undici-DjSrZtb9.js +1 -0
- package/dist/cli/wrapper-B4vDwpOq.js +6 -0
- package/package.json +1 -1
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import{__commonJSMin as e,__esmMin as t,__export as n,__reExport as r,__require as i,__toCommonJS as a,__toESM as o}from"./chunk-ByIbJXPc.js";import{SpanStatusCode as s,init_esm as c,trace as l}from"./esm-DiE8Xvft.js";import{createRequire as u}from"node:module";import{createServer as d}from"http";import f,{execFile as p}from"node:child_process";import*as m from"node:path";import h from"node:path";import*as g from"node:fs";import _,{createReadStream as v}from"node:fs";import y,{stdin as b,stdout as x}from"node:process";import*as S from"fs/promises";import{mkdir as C,readFile as w,stat as T,writeFile as E}from"fs/promises";import{dirname as D,join as O,relative as k,resolve as A}from"path";import{builtinModules as j,createRequire as ee}from"module";import{Buffer as M}from"node:buffer";import{fileURLToPath as N}from"node:url";import{promisify as P,stripVTControlCharacters as F}from"node:util";import*as I from"node:fs/promises";import L,{constants as R}from"node:fs/promises";import te from"node:os";import z,{z as B}from"zod";import{spawn as ne}from"child_process";import re,{existsSync as ie,mkdirSync as ae,readFileSync as oe,writeFileSync as se}from"fs";import*as ce from"node:readline";import le from"node:readline";import{Writable as ue}from"node:stream";import*as de from"zod/v4";import fe,{z as V}from"zod/v4";import{ZodFirstPartyTypeKind as H}from"zod/v3";import{tmpdir as pe}from"os";import me from"node:tty";async function he(e,{outdir:t}={}){t||=await ve(e);let n=O(t,`agent.js`),r=xe(),i=await r.build({...be,entryPoints:[e],outfile:n,write:!1});if(i.errors.length>0)throw Error(`Failed to build agent!`);let a=i.outputFiles[0];return await E(n,Buffer.from(a.contents),`utf-8`),{outfile:n}}async function ge(e,{onErrors:t,onBuildStart:n,onBuildEnd:r,outdir:i}){let a=xe();i||=await ve(e);let o=O(i,`agent.js`),s=await a.context({...be,entryPoints:[e],logLevel:`silent`,outfile:o,plugins:[...be.plugins??[],{name:`blink-dev-server`,setup(e){e.onStart(()=>{n?.()}),e.onEnd(async e=>{if(e.errors.length>0){t?.(e.errors);return}let n=e.outputFiles[0];await E(o,Buffer.from(n.contents),`utf-8`),r?.({outfile:o})})}}],write:!1});return await s.watch(),{dispose:()=>{s.dispose()}}}async function _e(e){let t=await ye(e,`package.json`);if(!t)throw Error(`No package.json found in ${e}`);let n=JSON.parse(await w(t,`utf-8`)),r=n.main;if(!r)throw Error(`"main" is not set in ${k(process.cwd(),t)}. It should be set to the entrypoint of your agent.`);let i=O(D(t),r),a=await T(i);if(!a.isFile())throw Error(`${i} is not a file.`);return i}async function ve(e){let t=await ye(e,`node_modules`);if(!t){let t=await T(e);return t.isDirectory()?O(e,`.blink`):O(D(e),`.blink`)}let n=O(t,`.blink`);return await C(n,{recursive:!0}),n}async function ye(e,t){let n=e;for(;n!==D(n);){let e=O(n,t);try{return await T(e),e}catch{}n=D(n)}}const be={bundle:!0,format:`esm`,platform:`node`,target:`node22`,mainFields:[`module`,`main`],conditions:[`import`,`module`],plugins:[{name:`blink-esm-require-to-import`,setup(e){e.onEnd(t=>{e.initialOptions.format!==`esm`||e.initialOptions.platform!==`node`||t.outputFiles?.forEach(e=>{if(e.path.endsWith(`.js`)||e.path.endsWith(`.mjs`)){let t=Buffer.from(e.contents).toString(`utf-8`),n=new Map,r=RegExp(`\\b__require\\("(${j.join(`|`)})"\\)`,`gm`);if(t=t.replace(r,(e,t)=>{let r=`__import_${t.toUpperCase().replace(/-/g,`_`)}`;return n.set(t,r),r}),n.size>0){let e=Array.from(n.entries()).map(([e,t])=>`import ${t} from "${e}";`).join(`
|
|
2
|
+
`);t=e+`
|
|
3
|
+
|
|
4
|
+
`+t}e.contents=Buffer.from(t,`utf-8`)}})})}}]},xe=()=>{try{return i(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};let Se;function Ce(){try{return _.statSync(`/.dockerenv`),!0}catch{return!1}}function we(){try{return _.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function Te(){return Se===void 0&&(Se=Ce()||we()),Se}let Ee;const De=()=>{try{return _.statSync(`/run/.containerenv`),!0}catch{return!1}};function Oe(){return Ee===void 0&&(Ee=De()||Te()),Ee}const ke=()=>{if(y.platform!==`linux`)return!1;if(te.release().toLowerCase().includes(`microsoft`))return!Oe();try{return _.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!Oe():!1}catch{return!1}};var Ae=y.env.__IS_WSL_TEST__?ke:ke();const je=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await L.access(n,R.F_OK),r=!0}catch{}if(!r)return e;let i=await L.readFile(n,{encoding:`utf8`}),a=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(i);return a?(t=a.groups.mountPoint.trim(),t=t.endsWith(`/`)?t:`${t}/`,t):e}})(),Me=async()=>{let e=await je();return`${e}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`},Ne=async()=>Ae?Me():`${y.env.SYSTEMROOT||y.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function Pe(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const Fe=P(p);async function Ie(){if(y.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await Fe(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]),t=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e);return t?.groups.id??`com.apple.Safari`}const Le=P(p);async function Re(e,{humanReadableOutput:t=!0}={}){if(y.platform!==`darwin`)throw Error(`macOS only`);let n=t?[]:[`-ss`],{stdout:r}=await Le(`osascript`,[`-e`,e,n]);return r.trim()}async function ze(e){return Re(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const Be=P(p),Ve={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var He=class extends Error{};async function Ue(e=Be){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new He(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=Ve[r];if(!i)throw new He(`Unknown browser ID: ${r}`);return i}const We=P(p),Ge=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function Ke(){if(y.platform===`darwin`){let e=await Ie(),t=await ze(e);return{name:t,id:e}}if(y.platform===`linux`){let{stdout:e}=await We(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim(),n=Ge(t.replace(/.desktop$/,``).replace(`-`,` `));return{name:n,id:t}}if(y.platform===`win32`)return Ue();throw Error(`Only macOS, Linux, and Windows are supported`)}const qe=P(f.execFile),Je=h.dirname(N(import.meta.url)),Ye=h.join(Je,`xdg-open`),{platform:Xe,arch:Ze}=y;async function Qe(){let e=await Ne(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,n=M.from(t,`utf16le`).toString(`base64`),{stdout:r}=await qe(e,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,n],{encoding:`utf8`}),i=r.trim(),a={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return a[i]?{id:a[i]}:{}}const $e=async(e,t)=>{let n;for(let r of e)try{return await t(r)}catch(e){n=e}throw n},et=async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return $e(e.app,t=>et({...e,app:t}));let{name:t,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(t))return $e(t,t=>et({...e,app:{name:t,arguments:n}}));if(t===`browser`||t===`browserPrivate`){let r={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a=Ae?await Qe():await Ke();if(a.id in r){let o=r[a.id];return t===`browserPrivate`&&n.push(i[o]),et({...e,app:{name:it[o],arguments:n}})}throw Error(`${a.name} is not supported as a default browser`)}let r,i=[],a={};if(Xe===`darwin`)r=`open`,e.wait&&i.push(`--wait-apps`),e.background&&i.push(`--background`),e.newInstance&&i.push(`--new`),t&&i.push(`-a`,t);else if(Xe===`win32`||Ae&&!Oe()&&!t){r=await Ne(),i.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),Ae||(a.windowsVerbatimArguments=!0);let o=[`Start`];e.wait&&o.push(`-Wait`),t?(o.push(`"\`"${t}\`""`),e.target&&n.push(e.target)):e.target&&o.push(`"${e.target}"`),n.length>0&&(n=n.map(e=>`"\`"${e}\`""`),o.push(`-ArgumentList`,n.join(`,`))),e.target=M.from(o.join(` `),`utf16le`).toString(`base64`)}else{if(t)r=t;else{let e=!Je||Je===`/`,t=!1;try{await L.access(Ye,R.X_OK),t=!0}catch{}let n=y.versions.electron??(Xe===`android`||e||!t);r=n?`xdg-open`:Ye}n.length>0&&i.push(...n),e.wait||(a.stdio=`ignore`,a.detached=!0)}Xe===`darwin`&&n.length>0&&i.push(`--args`,...n),e.target&&i.push(e.target);let o=f.spawn(r,i,a);return e.wait?new Promise((t,n)=>{o.once(`error`,n),o.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r>0){n(Error(`Exited with code ${r}`));return}t(o)})}):(o.unref(),o)},tt=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return et({...t,target:e})};function nt(e){if(typeof e==`string`||Array.isArray(e))return e;let{[Ze]:t}=e;if(!t)throw Error(`${Ze} is not supported`);return t}function rt({[Xe]:e},{wsl:t}){if(t&&Ae)return nt(t);if(!e)throw Error(`${Xe} is not supported`);return nt(e)}const it={};Pe(it,`chrome`,()=>rt({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),Pe(it,`brave`,()=>rt({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),Pe(it,`firefox`,()=>rt({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),Pe(it,`edge`,()=>rt({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),Pe(it,`browser`,()=>`browser`),Pe(it,`browserPrivate`,()=>`browserPrivate`);var at=tt,ot=class{listeners=[];get event(){return e=>(this.listeners.push(e),{dispose:()=>{this.listeners=this.listeners.filter(t=>t!==e)}})}emit(e){for(let t=this.listeners.length-1;t>=0;t--)this.listeners[t]?.(e)}dispose(){this.listeners=[]}},st=e(((exports,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`},r={up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},i={screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}};t.exports={cursor:n,scroll:r,erase:i,beep:`\x07`}})),ct=e(((exports,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>String;return{isColorSupported:e,reset:t(`\x1B[0m`,`\x1B[0m`),bold:t(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:t(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:t(`\x1B[3m`,`\x1B[23m`),underline:t(`\x1B[4m`,`\x1B[24m`),inverse:t(`\x1B[7m`,`\x1B[27m`),hidden:t(`\x1B[8m`,`\x1B[28m`),strikethrough:t(`\x1B[9m`,`\x1B[29m`),black:t(`\x1B[30m`,`\x1B[39m`),red:t(`\x1B[31m`,`\x1B[39m`),green:t(`\x1B[32m`,`\x1B[39m`),yellow:t(`\x1B[33m`,`\x1B[39m`),blue:t(`\x1B[34m`,`\x1B[39m`),magenta:t(`\x1B[35m`,`\x1B[39m`),cyan:t(`\x1B[36m`,`\x1B[39m`),white:t(`\x1B[37m`,`\x1B[39m`),gray:t(`\x1B[90m`,`\x1B[39m`),bgBlack:t(`\x1B[40m`,`\x1B[49m`),bgRed:t(`\x1B[41m`,`\x1B[49m`),bgGreen:t(`\x1B[42m`,`\x1B[49m`),bgYellow:t(`\x1B[43m`,`\x1B[49m`),bgBlue:t(`\x1B[44m`,`\x1B[49m`),bgMagenta:t(`\x1B[45m`,`\x1B[49m`),bgCyan:t(`\x1B[46m`,`\x1B[49m`),bgWhite:t(`\x1B[47m`,`\x1B[49m`),blackBright:t(`\x1B[90m`,`\x1B[39m`),redBright:t(`\x1B[91m`,`\x1B[39m`),greenBright:t(`\x1B[92m`,`\x1B[39m`),yellowBright:t(`\x1B[93m`,`\x1B[39m`),blueBright:t(`\x1B[94m`,`\x1B[39m`),magentaBright:t(`\x1B[95m`,`\x1B[39m`),cyanBright:t(`\x1B[96m`,`\x1B[39m`),whiteBright:t(`\x1B[97m`,`\x1B[39m`),bgBlackBright:t(`\x1B[100m`,`\x1B[49m`),bgRedBright:t(`\x1B[101m`,`\x1B[49m`),bgGreenBright:t(`\x1B[102m`,`\x1B[49m`),bgYellowBright:t(`\x1B[103m`,`\x1B[49m`),bgBlueBright:t(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:t(`\x1B[105m`,`\x1B[49m`),bgCyanBright:t(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:t(`\x1B[107m`,`\x1B[49m`)}};t.exports=c(),t.exports.createColors=c})),lt=o(st(),1);ct();function ut({onlyFirst:e=!1}={}){let t=[`[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?(?:\\u0007|\\u001B\\u005C|\\u009C))`,`(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))`].join(`|`);return new RegExp(t,e?void 0:`g`)}const dt=ut();function ft(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(dt,``)}function pt(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var mt={exports:{}};(function(e){var t={};e.exports=t,t.eastAsianWidth=function(e){var t=e.charCodeAt(0),n=e.length==2?e.charCodeAt(1):0,r=t;return 55296<=t&&t<=56319&&56320<=n&&n<=57343&&(t&=1023,n&=1023,r=t<<10|n,r+=65536),r==12288||65281<=r&&r<=65376||65504<=r&&r<=65510?`F`:r==8361||65377<=r&&r<=65470||65474<=r&&r<=65479||65482<=r&&r<=65487||65490<=r&&r<=65495||65498<=r&&r<=65500||65512<=r&&r<=65518?`H`:4352<=r&&r<=4447||4515<=r&&r<=4519||4602<=r&&r<=4607||9001<=r&&r<=9002||11904<=r&&r<=11929||11931<=r&&r<=12019||12032<=r&&r<=12245||12272<=r&&r<=12283||12289<=r&&r<=12350||12353<=r&&r<=12438||12441<=r&&r<=12543||12549<=r&&r<=12589||12593<=r&&r<=12686||12688<=r&&r<=12730||12736<=r&&r<=12771||12784<=r&&r<=12830||12832<=r&&r<=12871||12880<=r&&r<=13054||13056<=r&&r<=19903||19968<=r&&r<=42124||42128<=r&&r<=42182||43360<=r&&r<=43388||44032<=r&&r<=55203||55216<=r&&r<=55238||55243<=r&&r<=55291||63744<=r&&r<=64255||65040<=r&&r<=65049||65072<=r&&r<=65106||65108<=r&&r<=65126||65128<=r&&r<=65131||110592<=r&&r<=110593||127488<=r&&r<=127490||127504<=r&&r<=127546||127552<=r&&r<=127560||127568<=r&&r<=127569||131072<=r&&r<=194367||177984<=r&&r<=196605||196608<=r&&r<=262141?`W`:32<=r&&r<=126||162<=r&&r<=163||165<=r&&r<=166||r==172||r==175||10214<=r&&r<=10221||10629<=r&&r<=10630?`Na`:r==161||r==164||167<=r&&r<=168||r==170||173<=r&&r<=174||176<=r&&r<=180||182<=r&&r<=186||188<=r&&r<=191||r==198||r==208||215<=r&&r<=216||222<=r&&r<=225||r==230||232<=r&&r<=234||236<=r&&r<=237||r==240||242<=r&&r<=243||247<=r&&r<=250||r==252||r==254||r==257||r==273||r==275||r==283||294<=r&&r<=295||r==299||305<=r&&r<=307||r==312||319<=r&&r<=322||r==324||328<=r&&r<=331||r==333||338<=r&&r<=339||358<=r&&r<=359||r==363||r==462||r==464||r==466||r==468||r==470||r==472||r==474||r==476||r==593||r==609||r==708||r==711||713<=r&&r<=715||r==717||r==720||728<=r&&r<=731||r==733||r==735||768<=r&&r<=879||913<=r&&r<=929||931<=r&&r<=937||945<=r&&r<=961||963<=r&&r<=969||r==1025||1040<=r&&r<=1103||r==1105||r==8208||8211<=r&&r<=8214||8216<=r&&r<=8217||8220<=r&&r<=8221||8224<=r&&r<=8226||8228<=r&&r<=8231||r==8240||8242<=r&&r<=8243||r==8245||r==8251||r==8254||r==8308||r==8319||8321<=r&&r<=8324||r==8364||r==8451||r==8453||r==8457||r==8467||r==8470||8481<=r&&r<=8482||r==8486||r==8491||8531<=r&&r<=8532||8539<=r&&r<=8542||8544<=r&&r<=8555||8560<=r&&r<=8569||r==8585||8592<=r&&r<=8601||8632<=r&&r<=8633||r==8658||r==8660||r==8679||r==8704||8706<=r&&r<=8707||8711<=r&&r<=8712||r==8715||r==8719||r==8721||r==8725||r==8730||8733<=r&&r<=8736||r==8739||r==8741||8743<=r&&r<=8748||r==8750||8756<=r&&r<=8759||8764<=r&&r<=8765||r==8776||r==8780||r==8786||8800<=r&&r<=8801||8804<=r&&r<=8807||8810<=r&&r<=8811||8814<=r&&r<=8815||8834<=r&&r<=8835||8838<=r&&r<=8839||r==8853||r==8857||r==8869||r==8895||r==8978||9312<=r&&r<=9449||9451<=r&&r<=9547||9552<=r&&r<=9587||9600<=r&&r<=9615||9618<=r&&r<=9621||9632<=r&&r<=9633||9635<=r&&r<=9641||9650<=r&&r<=9651||9654<=r&&r<=9655||9660<=r&&r<=9661||9664<=r&&r<=9665||9670<=r&&r<=9672||r==9675||9678<=r&&r<=9681||9698<=r&&r<=9701||r==9711||9733<=r&&r<=9734||r==9737||9742<=r&&r<=9743||9748<=r&&r<=9749||r==9756||r==9758||r==9792||r==9794||9824<=r&&r<=9825||9827<=r&&r<=9829||9831<=r&&r<=9834||9836<=r&&r<=9837||r==9839||9886<=r&&r<=9887||9918<=r&&r<=9919||9924<=r&&r<=9933||9935<=r&&r<=9953||r==9955||9960<=r&&r<=9983||r==10045||r==10071||10102<=r&&r<=10111||11093<=r&&r<=11097||12872<=r&&r<=12879||57344<=r&&r<=63743||65024<=r&&r<=65039||r==65533||127232<=r&&r<=127242||127248<=r&&r<=127277||127280<=r&&r<=127337||127344<=r&&r<=127386||917760<=r&&r<=917999||983040<=r&&r<=1048573||1048576<=r&&r<=1114109?`A`:`N`},t.characterLength=function(e){var t=this.eastAsianWidth(e);return t==`F`||t==`W`||t==`A`?2:1};function n(e){return e.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]|[^\uD800-\uDFFF]/g)||[]}t.length=function(e){for(var t=n(e),r=0,i=0;i<t.length;i++)r+=this.characterLength(t[i]);return r},t.slice=function(e,r,i){textLen=t.length(e),r||=0,i||=1,r<0&&(r=textLen+r),i<0&&(i=textLen+i);for(var a=``,o=0,s=n(e),c=0;c<s.length;c++){var l=s[c],u=t.length(l);if(o>=r-(u==2?1:0))if(o+u<=i)a+=l;else break;o+=u}return a}})(mt);var ht=mt.exports;const gt=pt(ht);var _t=function(){return/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|(?:\uD83E\uDDD1\uD83C\uDFFF\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFC-\uDFFF])|\uD83D\uDC68(?:\uD83C\uDFFB(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|[\u2695\u2696\u2708]\uFE0F|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))?|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFF]))|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])\uFE0F|\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC)?|(?:\uD83D\uDC69(?:\uD83C\uDFFB\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|(?:\uD83C[\uDFFC-\uDFFF])\u200D\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC69(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83E\uDDD1(?:\u200D(?:\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|\uD83D\uDE36\u200D\uD83C\uDF2B|\uD83C\uDFF3\uFE0F\u200D\u26A7|\uD83D\uDC3B\u200D\u2744|(?:(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\uD83C\uDFF4\u200D\u2620|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])\u200D[\u2640\u2642]|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u2600-\u2604\u260E\u2611\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26B0\u26B1\u26C8\u26CF\u26D1\u26D3\u26E9\u26F0\u26F1\u26F4\u26F7\u26F8\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u3030\u303D\u3297\u3299]|\uD83C[\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]|\uD83D[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3])\uFE0F|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDE35\u200D\uD83D\uDCAB|\uD83D\uDE2E\u200D\uD83D\uDCA8|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83E\uDDD1(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83D\uDC69(?:\uD83C\uDFFF|\uD83C\uDFFE|\uD83C\uDFFD|\uD83C\uDFFC|\uD83C\uDFFB)?|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC08\u200D\u2B1B|\u2764\uFE0F\u200D(?:\uD83D\uDD25|\uD83E\uDE79)|\uD83D\uDC41\uFE0F|\uD83C\uDFF3\uFE0F|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|[#\*0-9]\uFE0F\u20E3|\u2764\uFE0F|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF4|(?:[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270C\u270D]|\uD83D[\uDD74\uDD90])(?:\uFE0F|\uD83C[\uDFFB-\uDFFF])|[\u270A\u270B]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC08\uDC15\uDC3B\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE2E\uDE35\uDE36\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5]|\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC70\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD35\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD4\uDDD6-\uDDDD]|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0D\uDD0E\uDD10-\uDD17\uDD1D\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78\uDD7A-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCB\uDDD0\uDDE0-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6]|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26A7\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5-\uDED7\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0C\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDD77\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g};const vt=pt(_t);function yt(e,t={}){if(typeof e!=`string`||e.length===0||(t={ambiguousIsNarrow:!0,...t},e=ft(e),e.length===0))return 0;e=e.replace(vt(),` `);let n=t.ambiguousIsNarrow?1:2,r=0;for(let t of e){let e=t.codePointAt(0);if(e<=31||e>=127&&e<=159||e>=768&&e<=879)continue;switch(gt.eastAsianWidth(t)){case`F`:case`W`:r+=2;break;case`A`:r+=n;break;default:r+=1}}return r}const bt=(e=0)=>t=>`\x1B[${t+e}m`,xt=(e=0)=>t=>`\x1B[${38+e};5;${t}m`,St=(e=0)=>(t,n,r)=>`\x1B[${38+e};2;${t};${n};${r}m`,U={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(U.modifier);const Ct=Object.keys(U.color),wt=Object.keys(U.bgColor);[...Ct,...wt];function Tt(){let e=new Map;for(let[t,n]of Object.entries(U)){for(let[t,r]of Object.entries(n))U[t]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[t]=U[t],e.set(r[0],r[1]);Object.defineProperty(U,t,{value:n,enumerable:!1})}return Object.defineProperty(U,`codes`,{value:e,enumerable:!1}),U.color.close=`\x1B[39m`,U.bgColor.close=`\x1B[49m`,U.color.ansi=bt(),U.color.ansi256=xt(),U.color.ansi16m=St(),U.bgColor.ansi=bt(10),U.bgColor.ansi256=xt(10),U.bgColor.ansi16m=St(10),Object.defineProperties(U,{rgbToAnsi256:{value:(e,t,n)=>e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5),enumerable:!1},hexToRgb:{value:e=>{let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>U.rgbToAnsi256(...U.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value:e=>{if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>U.ansi256ToAnsi(U.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>U.ansi256ToAnsi(U.hexToAnsi256(e)),enumerable:!1}}),U}const Et=Tt(),Dt=new Set([`\x1B`,``]),Ot=`]8;;`,kt=e=>`${Dt.values().next().value}[${e}m`,At=e=>`${Dt.values().next().value}${Ot}${e}`,jt=e=>e.split(` `).map(e=>yt(e)),Mt=(e,t,n)=>{let r=[...t],i=!1,a=!1,o=yt(ft(e[e.length-1]));for(let[t,s]of r.entries()){let c=yt(s);if(o+c<=n?e[e.length-1]+=s:(e.push(s),o=0),Dt.has(s)&&(i=!0,a=r.slice(t+1).join(``).startsWith(Ot)),i){a?s===`\x07`&&(i=!1,a=!1):s===`m`&&(i=!1);continue}o+=c,o===n&&t<r.length-1&&(e.push(``),o=0)}!o&&e[e.length-1].length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Nt=e=>{let t=e.split(` `),n=t.length;for(;n>0&&!(yt(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},Pt=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=jt(e),s=[``];for(let[r,i]of e.split(` `).entries()){n.trim!==!1&&(s[s.length-1]=s[s.length-1].trimStart());let e=yt(s[s.length-1]);if(r!==0&&(e>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),e=0),(e>0||n.trim===!1)&&(s[s.length-1]+=` `,e++)),n.hard&&o[r]>t){let n=t-e,a=1+Math.floor((o[r]-n-1)/t);Math.floor((o[r]-1)/t)<a&&s.push(``),Mt(s,i,t);continue}if(e+o[r]>t&&e>0&&o[r]>0){if(n.wordWrap===!1&&e<t){Mt(s,i,t);continue}s.push(``)}if(e+o[r]>t&&n.wordWrap===!1){Mt(s,i,t);continue}s[s.length-1]+=i}n.trim!==!1&&(s=s.map(e=>Nt(e)));let c=[...s.join(`
|
|
5
|
+
`)];for(let[e,t]of c.entries()){if(r+=t,Dt.has(t)){let{groups:t}=RegExp(`(?:\\[(?<code>\\d+)m|\\${Ot}(?<uri>.*))`).exec(c.slice(e).join(``))||{groups:{}};if(t.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}let n=Et.codes.get(Number(i));c[e+1]===`
|
|
6
|
+
`?(a&&(r+=At(``)),i&&n&&(r+=kt(n))):t===`
|
|
7
|
+
`&&(i&&n&&(r+=kt(i)),a&&(r+=At(a)))}return r};function Ft(e,t,n){return String(e).normalize().replace(/\r\n/g,`
|
|
8
|
+
`).split(`
|
|
9
|
+
`).map(e=>Pt(e,t,n)).join(`
|
|
10
|
+
`)}const It=[`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`],Lt={actions:new Set(It),aliases:new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]])};function Rt(e,t){if(typeof e==`string`)return Lt.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Rt(n,t))return!0;return!1}function zt(e,t){if(e===t)return;let n=e.split(`
|
|
11
|
+
`),r=t.split(`
|
|
12
|
+
`),i=[];for(let e=0;e<Math.max(n.length,r.length);e++)n[e]!==r[e]&&i.push(e);return i}const Bt=globalThis.process.platform.startsWith(`win`),Vt=Symbol(`clack:cancel`);function Ht(e){return e===Vt}function Ut(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Wt({input:e=b,output:t=x,overwrite:n=!0,hideCursor:r=!0}={}){let i=ce.createInterface({input:e,output:t,prompt:``,tabSize:1});ce.emitKeypressEvents(e,i),e.isTTY&&e.setRawMode(!0);let a=(i,{name:o,sequence:s})=>{let c=String(i);if(Rt([c,o,s],`cancel`)){r&&t.write(lt.cursor.show),process.exit(0);return}if(!n)return;let l=o===`return`?0:-1,u=o===`return`?-1:0;ce.moveCursor(t,l,u,()=>{ce.clearLine(t,1,()=>{e.once(`keypress`,a)})})};return r&&t.write(lt.cursor.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(lt.cursor.show),e.isTTY&&!Bt&&e.setRawMode(!1),i.terminal=!1,i.close()}}var Gt=Object.defineProperty,Kt=(e,t,n)=>t in e?Gt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,qt=(e,t,n)=>(Kt(e,typeof t==`symbol`?t:t+``,n),n),Jt=class{constructor(e,t=!0){qt(this,`input`),qt(this,`output`),qt(this,`_abortSignal`),qt(this,`rl`),qt(this,`opts`),qt(this,`_render`),qt(this,`_track`,!1),qt(this,`_prevFrame`,``),qt(this,`_subscribers`,new Map),qt(this,`_cursor`,0),qt(this,`state`,`initial`),qt(this,`error`,``),qt(this,`value`);let{input:n=b,output:r=x,render:i,signal:a,...o}=e;this.opts=o,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=t,this._abortSignal=a,this.input=n,this.output=r}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise((e,t)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(Vt);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}let n=new ue;n._write=(e,t,n)=>{this._track&&(this.value=this.rl?.line.replace(/\t/g,``),this._cursor=this.rl?.cursor??0,this.emit(`value`,this.value)),n()},this.input.pipe(n),this.rl=le.createInterface({input:this.input,output:n,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),le.emitKeypressEvents(this.input,this.rl),this.rl.prompt(),this.opts.initialValue!==void 0&&this._track&&this.rl.write(this.opts.initialValue),this.input.on(`keypress`,this.onKeypress),Ut(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(lt.cursor.show),this.output.off(`resize`,this.render),Ut(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(lt.cursor.show),this.output.off(`resize`,this.render),Ut(this.input,!1),e(Vt)})})}onKeypress(e,t){if(this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&Lt.aliases.has(t.name)&&this.emit(`cursor`,Lt.aliases.get(t.name)),Lt.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),e===` `&&this.opts.placeholder&&(this.value||(this.rl?.write(this.opts.placeholder),this.emit(`value`,this.opts.placeholder))),e&&this.emit(`key`,e.toLowerCase()),t?.name===`return`){if(this.opts.validate){let e=this.opts.validate(this.value);e&&(this.error=e instanceof Error?e.message:e,this.state=`error`,this.rl?.write(this.value))}this.state!==`error`&&(this.state=`submit`)}Rt([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
|
|
13
|
+
`),Ut(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=Ft(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
|
|
14
|
+
`).length-1;this.output.write(lt.cursor.move(-999,e*-1))}render(){let e=Ft(this._render(this)??``,process.stdout.columns,{hard:!0});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(lt.cursor.hide);else{let t=zt(this._prevFrame,e);if(this.restoreCursor(),t&&t?.length===1){let n=t[0];this.output.write(lt.cursor.move(0,n)),this.output.write(lt.erase.lines(1));let r=e.split(`
|
|
15
|
+
`);this.output.write(r[n]),this._prevFrame=e,this.output.write(lt.cursor.move(0,r.length-n-1));return}if(t&&t?.length>1){let n=t[0];this.output.write(lt.cursor.move(0,n)),this.output.write(lt.erase.down());let r=e.split(`
|
|
16
|
+
`).slice(n);this.output.write(r.join(`
|
|
17
|
+
`)),this._prevFrame=e;return}this.output.write(lt.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},Yt=class extends Jt{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`value`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(lt.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}};Object.defineProperty;var Xt;Xt=new WeakMap,Object.defineProperty,Object.defineProperty;var Zt=Object.defineProperty,Qt=(e,t,n)=>t in e?Zt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$t=(e,t,n)=>(Qt(e,typeof t==`symbol`?t:t+``,n),n),en=class extends Jt{constructor(e){super(e,!1),$t(this,`options`),$t(this,`cursor`,0),this.options=e.options,this.cursor=this.options.findIndex(({value:t})=>t===e.initialValue),this.cursor===-1&&(this.cursor=0),this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break;case`down`:case`right`:this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}this.changeValue()})}get _value(){return this.options[this.cursor]}changeValue(){this.value=this._value.value}};Object.defineProperty;var W=o(ct(),1),tn=o(st(),1);function nn(){return y.platform===`win32`?!!y.env.CI||!!y.env.WT_SESSION||!!y.env.TERMINUS_SUBLIME||y.env.ConEmuTask===`{cmd::Cmder}`||y.env.TERM_PROGRAM===`Terminus-Sublime`||y.env.TERM_PROGRAM===`vscode`||y.env.TERM===`xterm-256color`||y.env.TERM===`alacritty`||y.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:y.env.TERM!==`linux`}const rn=nn(),an=(e,t)=>rn?e:t,on=an(`◆`,`*`),sn=an(`■`,`x`),cn=an(`▲`,`x`),ln=an(`◇`,`o`),un=an(`┌`,`T`),dn=an(`│`,`|`),fn=an(`└`,`—`),pn=an(`●`,`>`),mn=an(`○`,` `);an(`◻`,`[•]`),an(`◼`,`[+]`),an(`◻`,`[ ]`),an(`▪`,`•`),an(`─`,`-`),an(`╮`,`+`),an(`├`,`+`),an(`╯`,`+`);const hn=an(`●`,`•`),gn=an(`◆`,`*`),_n=an(`▲`,`!`),vn=an(`■`,`x`),yn=e=>{switch(e){case`initial`:case`active`:return W.default.cyan(on);case`cancel`:return W.default.red(sn);case`error`:return W.default.yellow(cn);case`submit`:return W.default.green(ln)}},bn=e=>{let{cursor:t,options:n,style:r}=e,i=e.maxItems??1/0,a=Math.max(process.stdout.rows-4,0),o=Math.min(a,Math.max(i,5)),s=0;t>=s+o-3?s=Math.max(Math.min(t-o+3,n.length-o),0):t<s+2&&(s=Math.max(t-2,0));let c=o<n.length&&s>0,l=o<n.length&&s+o<n.length;return n.slice(s,s+o).map((e,n,i)=>{let a=n===0&&c,o=n===i.length-1&&l;return a||o?W.default.dim(`...`):r(e,n+s===t)})},xn=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new Yt({active:t,inactive:n,initialValue:e.initialValue??!0,render(){let r=`${W.default.gray(dn)}
|
|
18
|
+
${yn(this.state)} ${e.message}
|
|
19
|
+
`,i=this.value?t:n;switch(this.state){case`submit`:return`${r}${W.default.gray(dn)} ${W.default.dim(i)}`;case`cancel`:return`${r}${W.default.gray(dn)} ${W.default.strikethrough(W.default.dim(i))}
|
|
20
|
+
${W.default.gray(dn)}`;default:return`${r}${W.default.cyan(dn)} ${this.value?`${W.default.green(pn)} ${t}`:`${W.default.dim(mn)} ${W.default.dim(t)}`} ${W.default.dim(`/`)} ${this.value?`${W.default.dim(mn)} ${W.default.dim(n)}`:`${W.default.green(pn)} ${n}`}
|
|
21
|
+
${W.default.cyan(fn)}
|
|
22
|
+
`}}}).prompt()},Sn=e=>{let t=(e,t)=>{let n=e.label??String(e.value);switch(t){case`selected`:return`${W.default.dim(n)}`;case`active`:return`${W.default.green(pn)} ${n} ${e.hint?W.default.dim(`(${e.hint})`):``}`;case`cancelled`:return`${W.default.strikethrough(W.default.dim(n))}`;default:return`${W.default.dim(mn)} ${W.default.dim(n)}`}};return new en({options:e.options,initialValue:e.initialValue,render(){let n=`${W.default.gray(dn)}
|
|
23
|
+
${yn(this.state)} ${e.message}
|
|
24
|
+
`;switch(this.state){case`submit`:return`${n}${W.default.gray(dn)} ${t(this.options[this.cursor],`selected`)}`;case`cancel`:return`${n}${W.default.gray(dn)} ${t(this.options[this.cursor],`cancelled`)}
|
|
25
|
+
${W.default.gray(dn)}`;default:return`${n}${W.default.cyan(dn)} ${bn({cursor:this.cursor,options:this.options,maxItems:e.maxItems,style:(e,n)=>t(e,n?`active`:`inactive`)}).join(`
|
|
26
|
+
${W.default.cyan(dn)} `)}
|
|
27
|
+
${W.default.cyan(fn)}
|
|
28
|
+
`}}}).prompt()},Cn=(e=``)=>{process.stdout.write(`${W.default.gray(fn)} ${W.default.red(e)}
|
|
29
|
+
|
|
30
|
+
`)},wn=(e=``)=>{process.stdout.write(`${W.default.gray(un)} ${e}
|
|
31
|
+
`)},Tn=(e=``)=>{process.stdout.write(`${W.default.gray(dn)}
|
|
32
|
+
${W.default.gray(fn)} ${e}
|
|
33
|
+
|
|
34
|
+
`)},En={message:(e=``,{symbol:t=W.default.gray(dn)}={})=>{let n=[`${W.default.gray(dn)}`];if(e){let[r,...i]=e.split(`
|
|
35
|
+
`);n.push(`${t} ${r}`,...i.map(e=>`${W.default.gray(dn)} ${e}`))}process.stdout.write(`${n.join(`
|
|
36
|
+
`)}
|
|
37
|
+
`)},info:e=>{En.message(e,{symbol:W.default.blue(hn)})},success:e=>{En.message(e,{symbol:W.default.green(gn)})},step:e=>{En.message(e,{symbol:W.default.green(ln)})},warn:e=>{En.message(e,{symbol:W.default.yellow(_n)})},warning:e=>{En.warn(e)},error:e=>{En.message(e,{symbol:W.default.red(vn)})}},Dn=`${W.default.gray(dn)} `,On={message:async(e,{symbol:t=W.default.gray(dn)}={})=>{process.stdout.write(`${W.default.gray(dn)}
|
|
38
|
+
${t} `);let n=3;for await(let t of e){t=t.replace(/\n/g,`
|
|
39
|
+
${Dn}`),t.includes(`
|
|
40
|
+
`)&&(n=3+F(t.slice(t.lastIndexOf(`
|
|
41
|
+
`))).length);let e=F(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
42
|
+
${Dn}${t.trimStart()}`),n=3+F(t.trimStart()).length)}process.stdout.write(`
|
|
43
|
+
`)},info:e=>On.message(e,{symbol:W.default.blue(hn)}),success:e=>On.message(e,{symbol:W.default.green(gn)}),step:e=>On.message(e,{symbol:W.default.green(ln)}),warn:e=>On.message(e,{symbol:W.default.yellow(_n)}),warning:e=>On.warn(e),error:e=>On.message(e,{symbol:W.default.red(vn)})},kn=({indicator:e=`dots`}={})=>{let t=rn?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],n=rn?80:120,r=process.env.CI===`true`,i,a,o=!1,s=``,c,l=performance.now(),u=e=>{let t=e>1?`Something went wrong`:`Canceled`;o&&y(t,e)},d=()=>u(2),f=()=>u(1),p=()=>{process.on(`uncaughtExceptionMonitor`,d),process.on(`unhandledRejection`,d),process.on(`SIGINT`,f),process.on(`SIGTERM`,f),process.on(`exit`,u)},m=()=>{process.removeListener(`uncaughtExceptionMonitor`,d),process.removeListener(`unhandledRejection`,d),process.removeListener(`SIGINT`,f),process.removeListener(`SIGTERM`,f),process.removeListener(`exit`,u)},h=()=>{if(c===void 0)return;r&&process.stdout.write(`
|
|
44
|
+
`);let e=c.split(`
|
|
45
|
+
`);process.stdout.write(tn.cursor.move(-999,e.length-1)),process.stdout.write(tn.erase.down(e.length))},g=e=>e.replace(/\.+$/,``),_=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},v=(u=``)=>{o=!0,i=Wt(),s=g(u),l=performance.now(),process.stdout.write(`${W.default.gray(dn)}
|
|
46
|
+
`);let d=0,f=0;p(),a=setInterval(()=>{if(r&&s===c)return;h(),c=s;let n=W.default.magenta(t[d]);if(r)process.stdout.write(`${n} ${s}...`);else if(e===`timer`)process.stdout.write(`${n} ${s} ${_(l)}`);else{let e=`.`.repeat(Math.floor(f)).slice(0,3);process.stdout.write(`${n} ${s}${e}`)}d=d+1<t.length?d+1:0,f=f<t.length?f+.125:0},n)},y=(t=``,n=0)=>{o=!1,clearInterval(a),h();let r=n===0?W.default.green(ln):n===1?W.default.red(sn):W.default.red(cn);s=g(t??s),e===`timer`?process.stdout.write(`${r} ${s} ${_(l)}
|
|
47
|
+
`):process.stdout.write(`${r} ${s}
|
|
48
|
+
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},An=Symbol.for(`@whatwg-node/promise-helpers/FakePromise`);function jn(e){return e?.then!=null}function Mn(e){let t=e;return t&&t.then&&t.catch&&t.finally}function Nn(e,t,n,r){let i=Pn().then(e).then(t,n);return r&&(i=i.finally(r)),Vn(i)}function Pn(e){return e&&Mn(e)?e:jn(e)?{then:(t,n)=>Pn(e.then(t,n)),catch:t=>Pn(e.then(e=>e,t)),finally:t=>Pn(t?Bn(e,t):e),[Symbol.toStringTag]:`Promise`}:{then(t){if(t)try{return Pn(t(e))}catch(e){return Ln(e)}return this},catch(){return this},finally(t){if(t)try{return Pn(t()).then(()=>e,()=>e)}catch(e){return Ln(e)}return this},[Symbol.toStringTag]:`Promise`,__fakePromiseValue:e,[An]:`resolved`}}function Fn(){if(Promise.withResolvers)return Promise.withResolvers();let e,t,n=new Promise(function(n,r){e=n,t=r});return{promise:n,get resolve(){return e},get reject(){return t}}}function In(e,t,n){if(e?.length===0)return;let r=e[Symbol.iterator](),i=0;function a(){let{done:e,value:o}=r.next();if(e)return;let s=!1;function c(){s=!0}return Nn(function(){return t(o,c,i++)},function(e){if(e&&n?.push(e),!s)return a()})}return a()}function Ln(e){return{then(t,n){if(n)try{return Pn(n(e))}catch(e){return Ln(e)}return this},catch(t){if(t)try{return Pn(t(e))}catch(e){return Ln(e)}return this},finally(e){if(e)try{e()}catch(e){return Ln(e)}return this},__fakeRejectError:e,[Symbol.toStringTag]:`Promise`,[An]:`rejected`}}function Rn(e){return e?.[An]===`resolved`}function zn(e){return e?.[An]===`rejected`}function Bn(e,t){return`finally`in e?e.finally(t):e.then(e=>{let n=t();return jn(n)?n.then(()=>e):e},e=>{let n=t();if(jn(n))return n.then(()=>{throw e});throw e})}function Vn(e){if(Rn(e))return e.__fakePromiseValue;if(zn(e))throw e.__fakeRejectError;return e}function Hn(e,t){let n={...t,...e};for(let r of Object.keys(n))r in e&&r in t&&(n[r]=(n,i)=>e[r](n,()=>t[r](n,i)));return n}const Un=e=>({fn(t,n){return t?(...r)=>{let i;return t(e,()=>{i=n(...r)}),i}:n},asyncFn(t,n){return t?(...r)=>{let i;return Nn(()=>t(e,()=>(i=n(...r),jn(i)?i.then(()=>void 0):void 0)),()=>i)}:n}});var Wn=class extends Error{error;suppressed;constructor(e,t,n){super(n),this.error=e,this.suppressed=t,this.name=`SuppressedError`,Error.captureStackTrace(this,this.constructor)}};const Gn={get dispose(){return Symbol.dispose||Symbol.for(`dispose`)},get asyncDispose(){return Symbol.asyncDispose||Symbol.for(`asyncDispose`)}};function Kn(e){return e?.[Gn.dispose]!=null}function qn(e){return e?.[Gn.asyncDispose]!=null}const Jn=globalThis.SuppressedError||Wn;var Yn=class e{callbacks=[];get disposed(){return this.callbacks.length===0}use(e){return qn(e)?this.callbacks.push(()=>e[Gn.asyncDispose]()):Kn(e)&&this.callbacks.push(()=>e[Gn.dispose]()),e}adopt(e,t){return t&&this.callbacks.push(()=>t(e)),e}defer(e){e&&this.callbacks.push(e)}move(){let t=new e;return t.callbacks=this.callbacks,this.callbacks=[],t}disposeAsync(){return this[Gn.asyncDispose]()}_error;_iterateCallbacks(){let e=this.callbacks.pop();if(e)return Nn(e,()=>this._iterateCallbacks(),e=>(this._error=this._error?new Jn(e,this._error):e,this._iterateCallbacks()))}[Gn.asyncDispose](){let e=this._iterateCallbacks();if(e?.then)return e.then(()=>{if(this._error){let e=this._error;throw this._error=void 0,e}});if(this._error){let e=this._error;throw this._error=void 0,e}}[Symbol.toStringTag]=`AsyncDisposableStack`};globalThis.SuppressedError,Gn.dispose,Symbol.toStringTag,globalThis.DisposableStack;const Xn=globalThis.AsyncDisposableStack||Yn;globalThis.SuppressedError;var Zn=e(((exports,t)=>{function n(){return Object.keys(globalThis).some(e=>e.startsWith(`__NEXT`))}t.exports=function(){return!!(globalThis.Deno||globalThis.Bun||n())}})),Qn=e(((exports,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>n(e,`name`,{value:t,configurable:!0}),s=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},c=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},l=e=>c(n({},`__esModule`,{value:!0}),e),u={};s(u,{URLPattern:()=>_e}),t.exports=l(u);var d=class{type=3;name=``;prefix=``;value=``;suffix=``;modifier=3;constructor(e,t,n,r,i,a){this.type=e,this.name=t,this.prefix=n,this.value=r,this.suffix=i,this.modifier=a}hasCustomName(){return this.name!==``&&typeof this.name!=`number`}};o(d,`Part`);var f=/[$_\p{ID_Start}]/u,p=/[$_\u200C\u200D\p{ID_Continue}]/u,m=`.*`;function h(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}o(h,`isASCII`);function g(e,t=!1){let n=[],r=0;for(;r<e.length;){let i=e[r],a=o(function(i){if(!t)throw TypeError(i);n.push({type:`INVALID_CHAR`,index:r,value:e[r++]})},`ErrorOrInvalid`);if(i===`*`){n.push({type:`ASTERISK`,index:r,value:e[r++]});continue}if(i===`+`||i===`?`){n.push({type:`OTHER_MODIFIER`,index:r,value:e[r++]});continue}if(i===`\\`){n.push({type:`ESCAPED_CHAR`,index:r++,value:e[r++]});continue}if(i===`{`){n.push({type:`OPEN`,index:r,value:e[r++]});continue}if(i===`}`){n.push({type:`CLOSE`,index:r,value:e[r++]});continue}if(i===`:`){let t=``,i=r+1;for(;i<e.length;){let n=e.substr(i,1);if(i===r+1&&f.test(n)||i!==r+1&&p.test(n)){t+=e[i++];continue}break}if(!t){a(`Missing parameter name at ${r}`);continue}n.push({type:`NAME`,index:r,value:t}),r=i;continue}if(i===`(`){let t=1,i=``,o=r+1,s=!1;if(e[o]===`?`){a(`Pattern cannot start with "?" at ${o}`);continue}for(;o<e.length;){if(!h(e[o],!1)){a(`Invalid character '${e[o]}' at ${o}.`),s=!0;break}if(e[o]===`\\`){i+=e[o++]+e[o++];continue}if(e[o]===`)`){if(t--,t===0){o++;break}}else if(e[o]===`(`&&(t++,e[o+1]!==`?`)){a(`Capturing groups are not allowed at ${o}`),s=!0;break}i+=e[o++]}if(s)continue;if(t){a(`Unbalanced pattern at ${r}`);continue}if(!i){a(`Missing pattern at ${r}`);continue}n.push({type:`REGEX`,index:r,value:i}),r=o;continue}n.push({type:`CHAR`,index:r,value:e[r++]})}return n.push({type:`END`,index:r,value:``}),n}o(g,`lexer`);function _(e,t={}){let n=g(e);t.delimiter??=`/#?`,t.prefixes??=`./`;let r=`[^${v(t.delimiter)}]+?`,i=[],a=0,s=0,c=new Set,l=o(e=>{if(s<n.length&&n[s].type===e)return n[s++].value},`tryConsume`),u=o(()=>l(`OTHER_MODIFIER`)??l(`ASTERISK`),`tryConsumeModifier`),f=o(e=>{let t=l(e);if(t!==void 0)return t;let{type:r,index:i}=n[s];throw TypeError(`Unexpected ${r} at ${i}, expected ${e}`)},`mustConsume`),p=o(()=>{let e=``,t;for(;t=l(`CHAR`)??l(`ESCAPED_CHAR`);)e+=t;return e},`consumeText`),h=o(e=>e,`DefaultEncodePart`),_=t.encodePart||h,y=``,b=o(e=>{y+=e},`appendToPendingFixedValue`),x=o(()=>{y.length&&(i.push(new d(3,``,``,_(y),``,3)),y=``)},`maybeAddPartFromPendingFixedValue`),S=o((e,t,n,o,s)=>{let l=3;switch(s){case`?`:l=1;break;case`*`:l=0;break;case`+`:l=2;break}if(!t&&!n&&l===3){b(e);return}if(x(),!t&&!n){if(!e)return;i.push(new d(3,``,``,_(e),``,l));return}let u;u=n?n===`*`?m:n:r;let f=2;u===r?(f=1,u=``):u===m&&(f=0,u=``);let p;if(t?p=t:n&&(p=a++),c.has(p))throw TypeError(`Duplicate name '${p}'.`);c.add(p),i.push(new d(f,p,_(e),u,_(o),l))},`addPart`);for(;s<n.length;){let e=l(`CHAR`),n=l(`NAME`),r=l(`REGEX`);if(!n&&!r&&(r=l(`ASTERISK`)),n||r){let i=e??``;t.prefixes.indexOf(i)===-1&&(b(i),i=``),x();let a=u();S(i,n,r,``,a);continue}let i=e??l(`ESCAPED_CHAR`);if(i){b(i);continue}if(l(`OPEN`)){let e=p(),t=l(`NAME`),n=l(`REGEX`);!t&&!n&&(n=l(`ASTERISK`));let r=p();f(`CLOSE`);let i=u();S(e,t,n,r,i);continue}x(),f(`END`)}return i}o(_,`parse`);function v(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,`\\$1`)}o(v,`escapeString`);function y(e){return e&&e.ignoreCase?`ui`:`u`}o(y,`flags`);function b(e,t,n){return S(_(e,n),t,n)}o(b,`stringToRegexp`);function x(e){switch(e){case 0:return`*`;case 1:return`?`;case 2:return`+`;case 3:return``}}o(x,`modifierToString`);function S(e,t,n={}){n.delimiter??=`/#?`,n.prefixes??=`./`,n.sensitive??=!1,n.strict??=!1,n.end??=!0,n.start??=!0,n.endsWith=``;let r=n.start?`^`:``;for(let i of e){if(i.type===3){i.modifier===3?r+=v(i.value):r+=`(?:${v(i.value)})${x(i.modifier)}`;continue}t&&t.push(i.name);let e=`[^${v(n.delimiter)}]+?`,a=i.value;if(i.type===1?a=e:i.type===0&&(a=m),!i.prefix.length&&!i.suffix.length){i.modifier===3||i.modifier===1?r+=`(${a})${x(i.modifier)}`:r+=`((?:${a})${x(i.modifier)})`;continue}if(i.modifier===3||i.modifier===1){r+=`(?:${v(i.prefix)}(${a})${v(i.suffix)})`,r+=x(i.modifier);continue}r+=`(?:${v(i.prefix)}`,r+=`((?:${a})(?:`,r+=v(i.suffix),r+=v(i.prefix),r+=`(?:${a}))*)${v(i.suffix)})`,i.modifier===0&&(r+=`?`)}let i=`[${v(n.endsWith)}]|$`,a=`[${v(n.delimiter)}]`;if(n.end)return n.strict||(r+=`${a}?`),n.endsWith.length?r+=`(?=${i})`:r+=`$`,new RegExp(r,y(n));n.strict||(r+=`(?:${a}(?=${i}))?`);let o=!1;if(e.length){let t=e[e.length-1];t.type===3&&t.modifier===3&&(o=n.delimiter.indexOf(t)>-1)}return o||(r+=`(?=${a}|${i})`),new RegExp(r,y(n))}o(S,`partsToRegexp`);var C={delimiter:``,prefixes:``,sensitive:!0,strict:!0},w={delimiter:`.`,prefixes:``,sensitive:!0,strict:!0},T={delimiter:`/`,prefixes:`/`,sensitive:!0,strict:!0};function E(e,t){return e.length?e[0]===`/`?!0:!t||e.length<2?!1:(e[0]==`\\`||e[0]==`{`)&&e[1]==`/`:!1}o(E,`isAbsolutePathname`);function D(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}o(D,`maybeStripPrefix`);function O(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}o(O,`maybeStripSuffix`);function k(e){return!e||e.length<2?!1:e[0]===`[`||(e[0]===`\\`||e[0]===`{`)&&e[1]===`[`}o(k,`treatAsIPv6Hostname`);var A=[`ftp`,`file`,`http`,`https`,`ws`,`wss`];function j(e){if(!e)return!0;for(let t of A)if(e.test(t))return!0;return!1}o(j,`isSpecialScheme`);function ee(e,t){if(e=D(e,`#`),t||e===``)return e;let n=new URL(`https://example.com`);return n.hash=e,n.hash?n.hash.substring(1,n.hash.length):``}o(ee,`canonicalizeHash`);function M(e,t){if(e=D(e,`?`),t||e===``)return e;let n=new URL(`https://example.com`);return n.search=e,n.search?n.search.substring(1,n.search.length):``}o(M,`canonicalizeSearch`);function N(e,t){return t||e===``?e:k(e)?ie(e):re(e)}o(N,`canonicalizeHostname`);function P(e,t){if(t||e===``)return e;let n=new URL(`https://example.com`);return n.password=e,n.password}o(P,`canonicalizePassword`);function F(e,t){if(t||e===``)return e;let n=new URL(`https://example.com`);return n.username=e,n.username}o(F,`canonicalizeUsername`);function I(e,t,n){if(n||e===``)return e;if(t&&!A.includes(t))return new URL(`${t}:${e}`).pathname;let r=e[0]==`/`;return e=new URL(r?e:`/-`+e,`https://example.com`).pathname,r||(e=e.substring(2,e.length)),e}o(I,`canonicalizePathname`);function L(e,t,n){return te(t)===e&&(e=``),n||e===``?e:ae(e)}o(L,`canonicalizePort`);function R(e,t){return e=O(e,`:`),t||e===``?e:z(e)}o(R,`canonicalizeProtocol`);function te(e){switch(e){case`ws`:case`http`:return`80`;case`wws`:case`https`:return`443`;case`ftp`:return`21`;default:return``}}o(te,`defaultPortForProtocol`);function z(e){if(e===``)return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw TypeError(`Invalid protocol '${e}'.`)}o(z,`protocolEncodeCallback`);function B(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.username=e,t.username}o(B,`usernameEncodeCallback`);function ne(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.password=e,t.password}o(ne,`passwordEncodeCallback`);function re(e){if(e===``)return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw TypeError(`Invalid hostname '${e}'`);let t=new URL(`https://example.com`);return t.hostname=e,t.hostname}o(re,`hostnameEncodeCallback`);function ie(e){if(e===``)return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}o(ie,`ipv6HostnameEncodeCallback`);function ae(e){if(e===``||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw TypeError(`Invalid port '${e}'.`)}o(ae,`portEncodeCallback`);function oe(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.pathname=e[0]===`/`?e:`/-`+e,e[0]===`/`?t.pathname:t.pathname.substring(2,t.pathname.length)}o(oe,`standardURLPathnameEncodeCallback`);function se(e){return e===``?e:new URL(`data:${e}`).pathname}o(se,`pathURLPathnameEncodeCallback`);function ce(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.search=e,t.search.substring(1,t.search.length)}o(ce,`searchEncodeCallback`);function le(e){if(e===``)return e;let t=new URL(`https://example.com`);return t.hash=e,t.hash.substring(1,t.hash.length)}o(le,`hashEncodeCallback`);var ue=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=!1;constructor(e){this.#i=e}get result(){return this.#t}parse(){for(this.#n=g(this.#i,!0);this.#e<this.#n.length;this.#e+=this.#s){if(this.#s=1,this.#n[this.#e].type===`END`){if(this.#o===0){this.#b(),this.#f()?this.#r(9,1):this.#h()?this.#r(8,1):this.#r(7,0);continue}else if(this.#o===2){this.#u(5);continue}this.#r(10,0);break}if(this.#d>0)if(this.#A())--this.#d;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let e=7,t=1;this.#E()?(e=2,t=3):this.#g&&(e=2),this.#r(e,t)}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&--this.#p,this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port=``)}#r(e,t){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;case 10:break}this.#o!==0&&e!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(e)&&(this.#t.hostname??=``),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(e)&&(this.#t.pathname??=this.#g?`/`:``),[1,2,3,4,5,6,7].includes(this.#o)&&e===9&&(this.#t.search??=``)),this.#R(e,t)}#R(e,t){this.#o=e,this.#l=this.#e+t,this.#e+=t,this.#s=0}#b(){this.#e=this.#l,this.#s=0}#u(e){this.#b(),this.#o=e}#m(e){return e<0&&(e=this.#n.length-e),e<this.#n.length?this.#n[e]:this.#n[this.#n.length-1]}#a(e,t){let n=this.#m(e);return n.value===t&&(n.type===`CHAR`||n.type===`ESCAPED_CHAR`||n.type===`INVALID_CHAR`)}#P(){return this.#a(this.#e,`:`)}#E(){return this.#a(this.#e+1,`/`)&&this.#a(this.#e+2,`/`)}#S(){return this.#a(this.#e,`@`)}#O(){return this.#a(this.#e,`:`)}#k(){return this.#a(this.#e,`:`)}#x(){return this.#a(this.#e,`/`)}#h(){if(this.#a(this.#e,`?`))return!0;if(this.#n[this.#e].value!==`?`)return!1;let e=this.#m(this.#e-1);return e.type!==`NAME`&&e.type!==`REGEX`&&e.type!==`CLOSE`&&e.type!==`ASTERISK`}#f(){return this.#a(this.#e,`#`)}#T(){return this.#n[this.#e].type==`OPEN`}#A(){return this.#n[this.#e].type==`CLOSE`}#y(){return this.#a(this.#e,`[`)}#w(){return this.#a(this.#e,`]`)}#c(){let e=this.#n[this.#e],t=this.#m(this.#l).index;return this.#i.substring(t,e.index)}#C(){let e={};Object.assign(e,C),e.encodePart=z;let t=b(this.#c(),void 0,e);this.#g=j(t)}};o(ue,`Parser`);var de=[`protocol`,`username`,`password`,`hostname`,`port`,`pathname`,`search`,`hash`],fe=`*`;function V(e,t){if(typeof e!=`string`)throw TypeError(`parameter 1 is not of type 'string'.`);let n=new URL(e,t);return{protocol:n.protocol.substring(0,n.protocol.length-1),username:n.username,password:n.password,hostname:n.hostname,port:n.port,pathname:n.pathname,search:n.search===``?void 0:n.search.substring(1,n.search.length),hash:n.hash===``?void 0:n.hash.substring(1,n.hash.length)}}o(V,`extractValues`);function H(e,t){return t?me(e):e}o(H,`processBaseURLString`);function pe(e,t,n){let r;if(typeof t.baseURL==`string`)try{r=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=H(r.protocol.substring(0,r.protocol.length-1),n)),!n&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=H(r.username,n)),!n&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=H(r.password,n)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=H(r.hostname,n)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=H(r.port,n)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=H(r.pathname,n)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=H(r.search.substring(1,r.search.length),n)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=H(r.hash.substring(1,r.hash.length),n))}catch{throw TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol==`string`&&(e.protocol=R(t.protocol,n)),typeof t.username==`string`&&(e.username=F(t.username,n)),typeof t.password==`string`&&(e.password=P(t.password,n)),typeof t.hostname==`string`&&(e.hostname=N(t.hostname,n)),typeof t.port==`string`&&(e.port=L(t.port,e.protocol,n)),typeof t.pathname==`string`){if(e.pathname=t.pathname,r&&!E(e.pathname,n)){let t=r.pathname.lastIndexOf(`/`);t>=0&&(e.pathname=H(r.pathname.substring(0,t+1),n)+e.pathname)}e.pathname=I(e.pathname,e.protocol,n)}return typeof t.search==`string`&&(e.search=M(t.search,n)),typeof t.hash==`string`&&(e.hash=ee(t.hash,n)),e}o(pe,`applyInit`);function me(e){return e.replace(/([+*?:{}()\\])/g,`\\$1`)}o(me,`escapePatternString`);function he(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,`\\$1`)}o(he,`escapeRegexpString`);function ge(e,t){t.delimiter??=`/#?`,t.prefixes??=`./`,t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith=``;let n=`[^${he(t.delimiter)}]+?`,r=/[$_\u200C\u200D\p{ID_Continue}]/u,i=``;for(let a=0;a<e.length;++a){let o=e[a];if(o.type===3){if(o.modifier===3){i+=me(o.value);continue}i+=`{${me(o.value)}}${x(o.modifier)}`;continue}let s=o.hasCustomName(),c=!!o.suffix.length||!!o.prefix.length&&(o.prefix.length!==1||!t.prefixes.includes(o.prefix)),l=a>0?e[a-1]:null,u=a<e.length-1?e[a+1]:null;if(!c&&s&&o.type===1&&o.modifier===3&&u&&!u.prefix.length&&!u.suffix.length)if(u.type===3){let e=u.value.length>0?u.value[0]:``;c=r.test(e)}else c=!u.hasCustomName();if(!c&&!o.prefix.length&&l&&l.type===3){let e=l.value[l.value.length-1];c=t.prefixes.includes(e)}c&&(i+=`{`),i+=me(o.prefix),s&&(i+=`:${o.name}`),o.type===2?i+=`(${o.value})`:o.type===1?s||(i+=`(${n})`):o.type===0&&(!s&&(!l||l.type===3||l.modifier!==3||c||o.prefix!==``)?i+=`*`:i+=`(.*)`),o.type===1&&s&&o.suffix.length&&r.test(o.suffix[0])&&(i+=`\\`),i+=me(o.suffix),c&&(i+=`}`),o.modifier!==3&&(i+=x(o.modifier))}return i}o(ge,`partsToPattern`);var _e=class{#i;#n={};#t={};#e={};#s={};#l=!1;constructor(e={},t,n){try{let r;if(typeof t==`string`?r=t:n=t,typeof e==`string`){let t=new ue(e);if(t.parse(),e=t.result,r===void 0&&typeof e.protocol!=`string`)throw TypeError(`A base URL must be provided for a relative constructor string.`);e.baseURL=r}else{if(!e||typeof e!=`object`)throw TypeError(`parameter 1 is not of type 'string' and cannot convert to dictionary.`);if(r)throw TypeError(`parameter 1 is not of type 'string'.`)}typeof n>`u`&&(n={ignoreCase:!1});let i={ignoreCase:n.ignoreCase===!0},a={pathname:fe,protocol:fe,username:fe,password:fe,hostname:fe,port:fe,search:fe,hash:fe};this.#i=pe(a,e,!0),te(this.#i.protocol)===this.#i.port&&(this.#i.port=``);let o;for(o of de){if(!(o in this.#i))continue;let e={},t=this.#i[o];switch(this.#t[o]=[],o){case`protocol`:Object.assign(e,C),e.encodePart=z;break;case`username`:Object.assign(e,C),e.encodePart=B;break;case`password`:Object.assign(e,C),e.encodePart=ne;break;case`hostname`:Object.assign(e,w),k(t)?e.encodePart=ie:e.encodePart=re;break;case`port`:Object.assign(e,C),e.encodePart=ae;break;case`pathname`:j(this.#n.protocol)?(Object.assign(e,T,i),e.encodePart=oe):(Object.assign(e,C,i),e.encodePart=se);break;case`search`:Object.assign(e,C,i),e.encodePart=ce;break;case`hash`:Object.assign(e,C,i),e.encodePart=le;break}try{this.#s[o]=_(t,e),this.#n[o]=S(this.#s[o],this.#t[o],e),this.#e[o]=ge(this.#s[o],e),this.#l=this.#l||this.#s[o].some(e=>e.type===2)}catch{throw TypeError(`invalid ${o} pattern '${this.#i[o]}'.`)}}}catch(e){throw TypeError(`Failed to construct 'URLPattern': ${e.message}`)}}get[Symbol.toStringTag](){return`URLPattern`}test(e={},t){let n={pathname:``,protocol:``,username:``,password:``,hostname:``,port:``,search:``,hash:``};if(typeof e!=`string`&&t)throw TypeError(`parameter 1 is not of type 'string'.`);if(typeof e>`u`)return!1;try{n=typeof e==`object`?pe(n,e,!1):pe(n,V(e,t),!1)}catch{return!1}let r;for(r of de)if(!this.#n[r].exec(n[r]))return!1;return!0}exec(e={},t){let n={pathname:``,protocol:``,username:``,password:``,hostname:``,port:``,search:``,hash:``};if(typeof e!=`string`&&t)throw TypeError(`parameter 1 is not of type 'string'.`);if(typeof e>`u`)return;try{n=typeof e==`object`?pe(n,e,!1):pe(n,V(e,t),!1)}catch{return null}let r={};t?r.inputs=[e,t]:r.inputs=[e];let i;for(i of de){let e=this.#n[i].exec(n[i]);if(!e)return null;let t={};for(let[n,r]of this.#t[i].entries())if(typeof r==`string`||typeof r==`number`){let i=e[n+1];t[r]=i}r[i]={input:n[i]??``,groups:t}}return r}static compareComponent(e,t,n){let r=o((e,t)=>{for(let n of[`type`,`modifier`,`prefix`,`value`,`suffix`]){if(e[n]<t[n])return-1;if(e[n]===t[n])continue;return 1}return 0},`comparePart`),i=new d(3,``,``,``,``,3),a=new d(0,``,``,``,``,3),s=o((e,t)=>{let n=0;for(;n<Math.min(e.length,t.length);++n){let i=r(e[n],t[n]);if(i)return i}return e.length===t.length?0:r(e[n]??i,t[n]??i)},`comparePartList`);return!t.#e[e]&&!n.#e[e]?0:t.#e[e]&&!n.#e[e]?s(t.#s[e],[a]):!t.#e[e]&&n.#e[e]?s([a],n.#s[e]):s(t.#s[e],n.#s[e])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#l}};o(_e,`URLPattern`)})),$n=e(((exports,t)=>{let{URLPattern:n}=Qn();t.exports={URLPattern:n},globalThis.URLPattern||(globalThis.URLPattern=n)})),er=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.isPromise=n,exports.isActualPromise=r,exports.handleMaybePromise=i,exports.fakePromise=a,exports.createDeferredPromise=o,exports.iterateAsync=s,exports.iterateAsyncVoid=s,exports.fakeRejectPromise=c,exports.mapMaybePromise=l,exports.mapAsyncIterator=u,exports.promiseLikeFinally=m,exports.unfakePromise=h;let t=Symbol.for(`@whatwg-node/promise-helpers/FakePromise`);function n(e){return e?.then!=null}function r(e){let t=e;return t&&t.then&&t.catch&&t.finally}function i(e,t,n,r){let i=a().then(e).then(t,n);return r&&(i=i.finally(r)),h(i)}function a(e){return e&&r(e)?e:n(e)?{then:(t,n)=>a(e.then(t,n)),catch:t=>a(e.then(e=>e,t)),finally:t=>a(t?m(e,t):e),[Symbol.toStringTag]:`Promise`}:{then(t){if(t)try{return a(t(e))}catch(e){return c(e)}return this},catch(){return this},finally(t){if(t)try{return a(t()).then(()=>e,()=>e)}catch(e){return c(e)}return this},[Symbol.toStringTag]:`Promise`,__fakePromiseValue:e,[t]:`resolved`}}function o(){if(Promise.withResolvers)return Promise.withResolvers();let e,t,n=new Promise(function(n,r){e=n,t=r});return{promise:n,get resolve(){return e},get reject(){return t}}}function s(e,t,n){if(e?.length===0)return;let r=e[Symbol.iterator](),a=0;function o(){let{done:e,value:s}=r.next();if(e)return;let c=!1;function l(){c=!0}return i(function(){return t(s,l,a++)},function(e){if(e&&n?.push(e),!c)return o()})}return o()}function c(e){return{then(t,n){if(n)try{return a(n(e))}catch(e){return c(e)}return this},catch(t){if(t)try{return a(t(e))}catch(e){return c(e)}return this},finally(e){if(e)try{e()}catch(e){return c(e)}return this},__fakeRejectError:e,[Symbol.toStringTag]:`Promise`,[t]:`rejected`}}function l(e,t,n){return i(()=>e,t,n)}function u(e,t,n,r){Symbol.asyncIterator in e&&(e=e[Symbol.asyncIterator]());let o,s,l;if(r){let e;l=t=>(e||=i(r,()=>t,()=>t),e)}typeof e.return==`function`&&(o=e.return,s=t=>{let n=()=>{throw t};return o.call(e).then(n,n)});function u(e){return e.done?l?l(e):e:i(()=>e.value,e=>i(()=>t(e),d,s))}let f;if(n){let e,t=n;f=n=>(e||=i(()=>n,e=>i(()=>t(e),d,s)),e)}return{next(){return e.next().then(u,f)},return(){let t=o?o.call(e).then(u,f):a({value:void 0,done:!0});return l?t.then(l):t},throw(t){return typeof e.throw==`function`?e.throw(t).then(u,f):s?s(t):c(t)},[Symbol.asyncIterator](){return this}}}function d(e){return{value:e,done:!1}}function f(e){return e?.[t]===`resolved`}function p(e){return e?.[t]===`rejected`}function m(e,t){return`finally`in e?e.finally(t):e.then(e=>{let r=t();return n(r)?r.then(()=>e):e},e=>{let r=t();if(n(r))return r.then(()=>{throw e});throw e})}function h(e){if(f(e))return e.__fakePromiseValue;if(p(e))throw e.__fakeRejectError;return e}})),tr=e(((exports,t)=>{let{EventEmitter:n}=i(`node:events`),{inherits:r}=i(`node:util`);function a(e){if(typeof e==`string`&&(e=Buffer.from(e)),!Buffer.isBuffer(e))throw TypeError(`The needle has to be a String or a Buffer.`);let t=e.length,n=t-1;if(t===0)throw Error(`The needle cannot be an empty String/Buffer.`);if(t>256)throw Error(`The needle cannot have a length bigger than 256.`);this.maxMatches=1/0,this.matches=0,this._occ=new Uint8Array(256).fill(t),this._lookbehind_size=0,this._needle=e,this._bufpos=0,this._lookbehind=Buffer.alloc(n);for(var r=0;r<n;++r)this._occ[e[r]]=n-r}r(a,n),a.prototype.reset=function(){this._lookbehind_size=0,this.matches=0,this._bufpos=0},a.prototype.push=function(e,t){Buffer.isBuffer(e)||(e=Buffer.from(e,`binary`));let n=e.length;this._bufpos=t||0;let r;for(;r!==n&&this.matches<this.maxMatches;)r=this._sbmh_feed(e);return r},a.prototype._sbmh_feed=function(e){let t=e.length,n=this._needle,r=n.length,i=r-1,a=n[i],o=-this._lookbehind_size,s;if(o<0){for(;o<0&&o<=t-r;){if(s=e[o+i],s===a&&this._sbmh_memcmp(e,o,i))return this._lookbehind_size=0,++this.matches,this.emit(`info`,!0),this._bufpos=o+r;o+=this._occ[s]}for(;o<0&&!this._sbmh_memcmp(e,o,t-o);)++o;if(o>=0)this.emit(`info`,!1,this._lookbehind,0,this._lookbehind_size),this._lookbehind_size=0;else{let n=this._lookbehind_size+o;return n>0&&this.emit(`info`,!1,this._lookbehind,0,n),this._lookbehind_size-=n,this._lookbehind.copy(this._lookbehind,0,n,this._lookbehind_size),e.copy(this._lookbehind,this._lookbehind_size),this._lookbehind_size+=t,this._bufpos=t,t}}if(o=e.indexOf(n,o+this._bufpos),o!==-1)return++this.matches,o===0?this.emit(`info`,!0):this.emit(`info`,!0,e,this._bufpos,o),this._bufpos=o+r;for(o=t-i,o<0&&(o=0);o!==t&&(e[o]!==n[0]||Buffer.compare(e.subarray(o+1,t),n.subarray(1,t-o))!==0);)++o;return o!==t&&(e.copy(this._lookbehind,0,o,t),this._lookbehind_size=t-o),o!==0&&this.emit(`info`,!1,e,this._bufpos,o),this._bufpos=t,t},a.prototype._sbmh_lookup_char=function(e,t){return t<0?this._lookbehind[this._lookbehind_size+t]:e[t]},a.prototype._sbmh_memcmp=function(e,t,n){for(var r=0;r<n;++r)if(this._sbmh_lookup_char(e,t+r)!==this._needle[r])return!1;return!0},t.exports=a})),nr=e(((exports,t)=>{let n=i(`node:util`).inherits,r=i(`node:stream`).Readable;function a(e){r.call(this,e)}n(a,r),a.prototype._read=function(e){},t.exports=a})),rr=e(((exports,t)=>{t.exports=function(e,t,n){if(!e||e[t]===void 0||e[t]===null)return n;if(typeof e[t]!=`number`||isNaN(e[t]))throw TypeError(`Limit `+t+` is not a valid number`);return e[t]}})),ir=e(((exports,t)=>{let n=i(`node:events`).EventEmitter,r=i(`node:util`).inherits,a=rr(),o=tr(),s=Buffer.from(`\r
|
|
49
|
+
\r
|
|
50
|
+
`),c=/\r\n/g,l=/^([^:]+):[ \t]?([\x00-\xFF]+)?$/;function u(e){n.call(this),e||={};let t=this;this.nread=0,this.maxed=!1,this.npairs=0,this.maxHeaderPairs=a(e,`maxHeaderPairs`,2e3),this.maxHeaderSize=a(e,`maxHeaderSize`,80*1024),this.buffer=``,this.header={},this.finished=!1,this.ss=new o(s),this.ss.on(`info`,function(e,n,r,i){n&&!t.maxed&&(t.nread+i-r>=t.maxHeaderSize?(i=t.maxHeaderSize-t.nread+r,t.nread=t.maxHeaderSize,t.maxed=!0):t.nread+=i-r,t.buffer+=n.toString(`binary`,r,i)),e&&t._finish()})}r(u,n),u.prototype.push=function(e){let t=this.ss.push(e);if(this.finished)return t},u.prototype.reset=function(){this.finished=!1,this.buffer=``,this.header={},this.ss.reset()},u.prototype._finish=function(){this.buffer&&this._parseHeader(),this.ss.matches=this.ss.maxMatches;let e=this.header;this.header={},this.buffer=``,this.finished=!0,this.nread=this.npairs=0,this.maxed=!1,this.emit(`header`,e)},u.prototype._parseHeader=function(){if(this.npairs===this.maxHeaderPairs)return;let e=this.buffer.split(c),t=e.length,n,r;for(var i=0;i<t;++i){if(e[i].length===0)continue;if((e[i][0]===` `||e[i][0]===` `)&&r){this.header[r][this.header[r].length-1]+=e[i];continue}let t=e[i].indexOf(`:`);if(t===-1||t===0)return;if(n=l.exec(e[i]),r=n[1].toLowerCase(),this.header[r]=this.header[r]||[],this.header[r].push(n[2]||``),++this.npairs===this.maxHeaderPairs)break}},t.exports=u})),ar=e(((exports,t)=>{let n=i(`node:stream`).Writable,r=i(`node:util`).inherits,a=tr(),o=nr(),s=ir(),c=Buffer.from(`-`),l=Buffer.from(`\r
|
|
51
|
+
`),u=function(){};function d(e){if(!(this instanceof d))return new d(e);if(n.call(this,e),!e||!e.headerFirst&&typeof e.boundary!=`string`)throw TypeError(`Boundary required`);typeof e.boundary==`string`?this.setBoundary(e.boundary):this._bparser=void 0,this._headerFirst=e.headerFirst,this._dashes=0,this._parts=0,this._finished=!1,this._realFinish=!1,this._isPreamble=!0,this._justMatched=!1,this._firstWrite=!0,this._inHeader=!0,this._part=void 0,this._cb=void 0,this._ignoreData=!1,this._partOpts={highWaterMark:e.partHwm},this._pause=!1;let t=this;this._hparser=new s(e),this._hparser.on(`header`,function(e){t._inHeader=!1,t._part.emit(`header`,e)})}r(d,n),d.prototype.emit=function(e){if(e===`finish`&&!this._realFinish){if(!this._finished){let e=this;process.nextTick(function(){if(e.emit(`error`,Error(`Unexpected end of multipart data`)),e._part&&!e._ignoreData){let t=e._isPreamble?`Preamble`:`Part`;e._part.emit(`error`,Error(t+` terminated early due to unexpected end of multipart data`)),e._part.push(null),process.nextTick(function(){e._realFinish=!0,e.emit(`finish`),e._realFinish=!1});return}e._realFinish=!0,e.emit(`finish`),e._realFinish=!1})}}else n.prototype.emit.apply(this,arguments)},d.prototype._write=function(e,t,n){if(!this._hparser&&!this._bparser)return n();if(this._headerFirst&&this._isPreamble){this._part||(this._part=new o(this._partOpts),this.listenerCount(`preamble`)===0?this._ignore():this.emit(`preamble`,this._part));let t=this._hparser.push(e);if(!this._inHeader&&t!==void 0&&t<e.length)e=e.slice(t);else return n()}this._firstWrite&&=(this._bparser.push(l),!1),this._bparser.push(e),this._pause?this._cb=n:n()},d.prototype.reset=function(){this._part=void 0,this._bparser=void 0,this._hparser=void 0},d.prototype.setBoundary=function(e){let t=this;this._bparser=new a(`\r
|
|
52
|
+
--`+e),this._bparser.on(`info`,function(e,n,r,i){t._oninfo(e,n,r,i)})},d.prototype._ignore=function(){this._part&&!this._ignoreData&&(this._ignoreData=!0,this._part.on(`error`,u),this._part.resume())},d.prototype._oninfo=function(e,t,n,r){let i,a=this,s=0,l,u=!0;if(!this._part&&this._justMatched&&t){for(;this._dashes<2&&n+s<r;)if(t[n+s]===45)++s,++this._dashes;else{this._dashes&&(i=c),this._dashes=0;break}if(this._dashes===2&&(n+s<r&&this.listenerCount(`trailer`)!==0&&this.emit(`trailer`,t.slice(n+s,r)),this.reset(),this._finished=!0,a._parts===0&&(a._realFinish=!0,a.emit(`finish`),a._realFinish=!1)),this._dashes)return}this._justMatched&&=!1,this._part||(this._part=new o(this._partOpts),this._part._read=function(e){a._unpause()},this._isPreamble&&this.listenerCount(`preamble`)!==0?this.emit(`preamble`,this._part):this._isPreamble!==!0&&this.listenerCount(`part`)!==0?this.emit(`part`,this._part):this._ignore(),this._isPreamble||(this._inHeader=!0)),t&&n<r&&!this._ignoreData&&(this._isPreamble||!this._inHeader?(i&&(u=this._part.push(i)),u=this._part.push(t.slice(n,r)),u||(this._pause=!0)):!this._isPreamble&&this._inHeader&&(i&&this._hparser.push(i),l=this._hparser.push(t.slice(n,r)),!this._inHeader&&l!==void 0&&l<r&&this._oninfo(!1,t,n+l,r))),e&&(this._hparser.reset(),this._isPreamble?this._isPreamble=!1:n!==r&&(++this._parts,this._part.on(`end`,function(){--a._parts===0&&(a._finished?(a._realFinish=!0,a.emit(`finish`),a._realFinish=!1):a._unpause())})),this._part.push(null),this._part=void 0,this._ignoreData=!1,this._justMatched=!0,this._dashes=0)},d.prototype._unpause=function(){if(this._pause&&(this._pause=!1,this._cb)){let e=this._cb;this._cb=void 0,e()}},t.exports=d})),or=e(((exports,t)=>{let n=new TextDecoder(`utf-8`),r=new Map([[`utf-8`,n],[`utf8`,n]]);function i(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return a.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return a.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return a.utf16le;case`base64`:return a.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return a.other.bind(e)}}let a={utf8:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,t)),e.utf8Slice(0,e.length)),latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,t)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,t)),e.base64Slice(0,e.length)),other:(t,n)=>{if(t.length===0)return``;if(typeof t==`string`&&(t=Buffer.from(t,n)),r.has(exports.toString()))try{return r.get(exports).decode(t)}catch{}return typeof t==`string`?t:t.toString()}};function o(e,t,n){return e&&i(n)(e,t)}t.exports=o})),sr=e(((exports,t)=>{let n=or(),r=/%[a-fA-F0-9][a-fA-F0-9]/g,i={"%00":`\0`,"%01":``,"%02":``,"%03":``,"%04":``,"%05":``,"%06":``,"%07":`\x07`,"%08":`\b`,"%09":` `,"%0a":`
|
|
53
|
+
`,"%0A":`
|
|
54
|
+
`,"%0b":`\v`,"%0B":`\v`,"%0c":`\f`,"%0C":`\f`,"%0d":`\r`,"%0D":`\r`,"%0e":``,"%0E":``,"%0f":``,"%0F":``,"%10":``,"%11":``,"%12":``,"%13":``,"%14":``,"%15":``,"%16":``,"%17":``,"%18":``,"%19":``,"%1a":``,"%1A":``,"%1b":`\x1B`,"%1B":`\x1B`,"%1c":``,"%1C":``,"%1d":``,"%1D":``,"%1e":``,"%1E":``,"%1f":``,"%1F":``,"%20":` `,"%21":`!`,"%22":`"`,"%23":`#`,"%24":`$`,"%25":`%`,"%26":`&`,"%27":`'`,"%28":`(`,"%29":`)`,"%2a":`*`,"%2A":`*`,"%2b":`+`,"%2B":`+`,"%2c":`,`,"%2C":`,`,"%2d":`-`,"%2D":`-`,"%2e":`.`,"%2E":`.`,"%2f":`/`,"%2F":`/`,"%30":`0`,"%31":`1`,"%32":`2`,"%33":`3`,"%34":`4`,"%35":`5`,"%36":`6`,"%37":`7`,"%38":`8`,"%39":`9`,"%3a":`:`,"%3A":`:`,"%3b":`;`,"%3B":`;`,"%3c":`<`,"%3C":`<`,"%3d":`=`,"%3D":`=`,"%3e":`>`,"%3E":`>`,"%3f":`?`,"%3F":`?`,"%40":`@`,"%41":`A`,"%42":`B`,"%43":`C`,"%44":`D`,"%45":`E`,"%46":`F`,"%47":`G`,"%48":`H`,"%49":`I`,"%4a":`J`,"%4A":`J`,"%4b":`K`,"%4B":`K`,"%4c":`L`,"%4C":`L`,"%4d":`M`,"%4D":`M`,"%4e":`N`,"%4E":`N`,"%4f":`O`,"%4F":`O`,"%50":`P`,"%51":`Q`,"%52":`R`,"%53":`S`,"%54":`T`,"%55":`U`,"%56":`V`,"%57":`W`,"%58":`X`,"%59":`Y`,"%5a":`Z`,"%5A":`Z`,"%5b":`[`,"%5B":`[`,"%5c":`\\`,"%5C":`\\`,"%5d":`]`,"%5D":`]`,"%5e":`^`,"%5E":`^`,"%5f":`_`,"%5F":`_`,"%60":"`","%61":`a`,"%62":`b`,"%63":`c`,"%64":`d`,"%65":`e`,"%66":`f`,"%67":`g`,"%68":`h`,"%69":`i`,"%6a":`j`,"%6A":`j`,"%6b":`k`,"%6B":`k`,"%6c":`l`,"%6C":`l`,"%6d":`m`,"%6D":`m`,"%6e":`n`,"%6E":`n`,"%6f":`o`,"%6F":`o`,"%70":`p`,"%71":`q`,"%72":`r`,"%73":`s`,"%74":`t`,"%75":`u`,"%76":`v`,"%77":`w`,"%78":`x`,"%79":`y`,"%7a":`z`,"%7A":`z`,"%7b":`{`,"%7B":`{`,"%7c":`|`,"%7C":`|`,"%7d":`}`,"%7D":`}`,"%7e":`~`,"%7E":`~`,"%7f":``,"%7F":``,"%80":``,"%81":``,"%82":``,"%83":``,"%84":``,"%85":`
`,"%86":``,"%87":``,"%88":``,"%89":``,"%8a":``,"%8A":``,"%8b":``,"%8B":``,"%8c":``,"%8C":``,"%8d":``,"%8D":``,"%8e":``,"%8E":``,"%8f":``,"%8F":``,"%90":``,"%91":``,"%92":``,"%93":``,"%94":``,"%95":``,"%96":``,"%97":``,"%98":``,"%99":``,"%9a":``,"%9A":``,"%9b":``,"%9B":``,"%9c":``,"%9C":``,"%9d":``,"%9D":``,"%9e":``,"%9E":``,"%9f":``,"%9F":``,"%a0":`\xA0`,"%A0":`\xA0`,"%a1":`¡`,"%A1":`¡`,"%a2":`¢`,"%A2":`¢`,"%a3":`£`,"%A3":`£`,"%a4":`¤`,"%A4":`¤`,"%a5":`¥`,"%A5":`¥`,"%a6":`¦`,"%A6":`¦`,"%a7":`§`,"%A7":`§`,"%a8":`¨`,"%A8":`¨`,"%a9":`©`,"%A9":`©`,"%aa":`ª`,"%Aa":`ª`,"%aA":`ª`,"%AA":`ª`,"%ab":`«`,"%Ab":`«`,"%aB":`«`,"%AB":`«`,"%ac":`¬`,"%Ac":`¬`,"%aC":`¬`,"%AC":`¬`,"%ad":``,"%Ad":``,"%aD":``,"%AD":``,"%ae":`®`,"%Ae":`®`,"%aE":`®`,"%AE":`®`,"%af":`¯`,"%Af":`¯`,"%aF":`¯`,"%AF":`¯`,"%b0":`°`,"%B0":`°`,"%b1":`±`,"%B1":`±`,"%b2":`²`,"%B2":`²`,"%b3":`³`,"%B3":`³`,"%b4":`´`,"%B4":`´`,"%b5":`µ`,"%B5":`µ`,"%b6":`¶`,"%B6":`¶`,"%b7":`·`,"%B7":`·`,"%b8":`¸`,"%B8":`¸`,"%b9":`¹`,"%B9":`¹`,"%ba":`º`,"%Ba":`º`,"%bA":`º`,"%BA":`º`,"%bb":`»`,"%Bb":`»`,"%bB":`»`,"%BB":`»`,"%bc":`¼`,"%Bc":`¼`,"%bC":`¼`,"%BC":`¼`,"%bd":`½`,"%Bd":`½`,"%bD":`½`,"%BD":`½`,"%be":`¾`,"%Be":`¾`,"%bE":`¾`,"%BE":`¾`,"%bf":`¿`,"%Bf":`¿`,"%bF":`¿`,"%BF":`¿`,"%c0":`À`,"%C0":`À`,"%c1":`Á`,"%C1":`Á`,"%c2":`Â`,"%C2":`Â`,"%c3":`Ã`,"%C3":`Ã`,"%c4":`Ä`,"%C4":`Ä`,"%c5":`Å`,"%C5":`Å`,"%c6":`Æ`,"%C6":`Æ`,"%c7":`Ç`,"%C7":`Ç`,"%c8":`È`,"%C8":`È`,"%c9":`É`,"%C9":`É`,"%ca":`Ê`,"%Ca":`Ê`,"%cA":`Ê`,"%CA":`Ê`,"%cb":`Ë`,"%Cb":`Ë`,"%cB":`Ë`,"%CB":`Ë`,"%cc":`Ì`,"%Cc":`Ì`,"%cC":`Ì`,"%CC":`Ì`,"%cd":`Í`,"%Cd":`Í`,"%cD":`Í`,"%CD":`Í`,"%ce":`Î`,"%Ce":`Î`,"%cE":`Î`,"%CE":`Î`,"%cf":`Ï`,"%Cf":`Ï`,"%cF":`Ï`,"%CF":`Ï`,"%d0":`Ð`,"%D0":`Ð`,"%d1":`Ñ`,"%D1":`Ñ`,"%d2":`Ò`,"%D2":`Ò`,"%d3":`Ó`,"%D3":`Ó`,"%d4":`Ô`,"%D4":`Ô`,"%d5":`Õ`,"%D5":`Õ`,"%d6":`Ö`,"%D6":`Ö`,"%d7":`×`,"%D7":`×`,"%d8":`Ø`,"%D8":`Ø`,"%d9":`Ù`,"%D9":`Ù`,"%da":`Ú`,"%Da":`Ú`,"%dA":`Ú`,"%DA":`Ú`,"%db":`Û`,"%Db":`Û`,"%dB":`Û`,"%DB":`Û`,"%dc":`Ü`,"%Dc":`Ü`,"%dC":`Ü`,"%DC":`Ü`,"%dd":`Ý`,"%Dd":`Ý`,"%dD":`Ý`,"%DD":`Ý`,"%de":`Þ`,"%De":`Þ`,"%dE":`Þ`,"%DE":`Þ`,"%df":`ß`,"%Df":`ß`,"%dF":`ß`,"%DF":`ß`,"%e0":`à`,"%E0":`à`,"%e1":`á`,"%E1":`á`,"%e2":`â`,"%E2":`â`,"%e3":`ã`,"%E3":`ã`,"%e4":`ä`,"%E4":`ä`,"%e5":`å`,"%E5":`å`,"%e6":`æ`,"%E6":`æ`,"%e7":`ç`,"%E7":`ç`,"%e8":`è`,"%E8":`è`,"%e9":`é`,"%E9":`é`,"%ea":`ê`,"%Ea":`ê`,"%eA":`ê`,"%EA":`ê`,"%eb":`ë`,"%Eb":`ë`,"%eB":`ë`,"%EB":`ë`,"%ec":`ì`,"%Ec":`ì`,"%eC":`ì`,"%EC":`ì`,"%ed":`í`,"%Ed":`í`,"%eD":`í`,"%ED":`í`,"%ee":`î`,"%Ee":`î`,"%eE":`î`,"%EE":`î`,"%ef":`ï`,"%Ef":`ï`,"%eF":`ï`,"%EF":`ï`,"%f0":`ð`,"%F0":`ð`,"%f1":`ñ`,"%F1":`ñ`,"%f2":`ò`,"%F2":`ò`,"%f3":`ó`,"%F3":`ó`,"%f4":`ô`,"%F4":`ô`,"%f5":`õ`,"%F5":`õ`,"%f6":`ö`,"%F6":`ö`,"%f7":`÷`,"%F7":`÷`,"%f8":`ø`,"%F8":`ø`,"%f9":`ù`,"%F9":`ù`,"%fa":`ú`,"%Fa":`ú`,"%fA":`ú`,"%FA":`ú`,"%fb":`û`,"%Fb":`û`,"%fB":`û`,"%FB":`û`,"%fc":`ü`,"%Fc":`ü`,"%fC":`ü`,"%FC":`ü`,"%fd":`ý`,"%Fd":`ý`,"%fD":`ý`,"%FD":`ý`,"%fe":`þ`,"%Fe":`þ`,"%fE":`þ`,"%FE":`þ`,"%ff":`ÿ`,"%Ff":`ÿ`,"%fF":`ÿ`,"%FF":`ÿ`};function a(e){return i[e]}function o(e){let t=[],i=0,o=``,s=!1,c=!1,l=0,u=``,d=e.length;for(var f=0;f<d;++f){let p=e[f];if(p===`\\`&&s)if(c)c=!1;else{c=!0;continue}else if(p===`"`)if(c)c=!1;else{if(s)for(s=!1,i=0;f+1<d&&e[f+1]!==`;`;)++f;else s=!0;continue}else if(c&&s&&(u+=`\\`),c=!1,(i===2||i===3)&&p===`'`){i===2?(i=3,o=u.substring(1)):i=1,u=``;continue}else if(i===0&&(p===`*`||p===`=`)&&t.length){i=p===`*`?2:1,t[l]=[u,void 0],u=``;continue}else if(!s&&p===`;`){i=0,o?(u.length&&(u=n(u.replace(r,a),`binary`,o)),o=``):u.length&&(u=n(u,`binary`,`utf8`)),t[l]===void 0?t[l]=u:t[l][1]=u,u=``,++l;continue}else if(!s&&(p===` `||p===` `))continue;u+=p}return o&&u.length?u=n(u.replace(r,a),`binary`,o):u&&=n(u,`binary`,`utf8`),t[l]===void 0?u&&(t[l]=u):t[l][1]=u,t}t.exports=o})),cr=e(((exports,t)=>{t.exports=function(e){if(typeof e!=`string`)return``;for(var t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}})),lr=e(((exports,t)=>{let{Readable:n}=i(`node:stream`),{inherits:r}=i(`node:util`),a=ar(),o=sr(),s=or(),c=cr(),l=rr(),u=/^boundary$/i,d=/^form-data$/i,f=/^charset$/i,p=/^filename$/i,m=/^name$/i;h.detect=/^multipart\/form-data/i;function h(e,t){let n,r,i=this,h,v=t.limits,y=t.isPartAFile||((e,t,n)=>t===`application/octet-stream`||n!==void 0),b=t.parsedConType||[],x=t.defCharset||`utf8`,S=t.preservePath,C={highWaterMark:t.fileHwm};for(n=0,r=b.length;n<r;++n)if(Array.isArray(b[n])&&u.test(b[n][0])){h=b[n][1];break}function w(){N===0&&I&&!e._done&&(I=!1,i.end())}if(typeof h!=`string`)throw Error(`Multipart: Boundary not found`);let T=l(v,`fieldSize`,1*1024*1024),E=l(v,`fileSize`,1/0),D=l(v,`files`,1/0),O=l(v,`fields`,1/0),k=l(v,`parts`,1/0),A=l(v,`headerPairs`,2e3),j=l(v,`headerSize`,80*1024),ee=0,M=0,N=0,P,F,I=!1;this._needDrain=!1,this._pause=!1,this._cb=void 0,this._nparts=0,this._boy=e;let L={boundary:h,maxHeaderPairs:A,maxHeaderSize:j,partHwm:C.highWaterMark,highWaterMark:t.highWaterMark};this.parser=new a(L),this.parser.on(`drain`,function(){if(i._needDrain=!1,i._cb&&!i._pause){let e=i._cb;i._cb=void 0,e()}}).on(`part`,function t(a){if(++i._nparts>k)return i.parser.removeListener(`part`,t),i.parser.on(`part`,g),e.hitPartsLimit=!0,e.emit(`partsLimit`),g(a);if(F){let e=F;e.emit(`end`),e.removeAllListeners(`end`)}a.on(`header`,function(t){let l,u,h,v,b,k,A=0;if(t[`content-type`]&&(h=o(t[`content-type`][0]),h[0])){for(l=h[0].toLowerCase(),n=0,r=h.length;n<r;++n)if(f.test(h[n][0])){v=h[n][1].toLowerCase();break}}if(l===void 0&&(l=`text/plain`),v===void 0&&(v=x),t[`content-disposition`]){if(h=o(t[`content-disposition`][0]),!d.test(h[0]))return g(a);for(n=0,r=h.length;n<r;++n)m.test(h[n][0])?u=h[n][1]:p.test(h[n][0])&&(k=h[n][1],S||(k=c(k)))}else return g(a);b=t[`content-transfer-encoding`]?t[`content-transfer-encoding`][0].toLowerCase():`7bit`;let j,I;if(y(u,l,k)){if(ee===D)return e.hitFilesLimit||(e.hitFilesLimit=!0,e.emit(`filesLimit`)),g(a);if(++ee,e.listenerCount(`file`)===0){i.parser._ignore();return}++N;let t=new _(C);P=t,t.on(`end`,function(){if(--N,i._pause=!1,w(),i._cb&&!i._needDrain){let e=i._cb;i._cb=void 0,e()}}),t._read=function(e){if(i._pause&&(i._pause=!1,i._cb&&!i._needDrain)){let e=i._cb;i._cb=void 0,e()}},e.emit(`file`,u,t,k,b,l),j=function(e){if((A+=e.length)>E){let n=E-A+e.length;n>0&&t.push(e.slice(0,n)),t.truncated=!0,t.bytesRead=E,a.removeAllListeners(`data`),t.emit(`limit`);return}else t.push(e)||(i._pause=!0);t.bytesRead=A},I=function(){P=void 0,t.push(null)}}else{if(M===O)return e.hitFieldsLimit||(e.hitFieldsLimit=!0,e.emit(`fieldsLimit`)),g(a);++M,++N;let t=``,n=!1;F=a,j=function(e){if((A+=e.length)>T){let r=T-(A-e.length);t+=e.toString(`binary`,0,r),n=!0,a.removeAllListeners(`data`)}else t+=e.toString(`binary`)},I=function(){F=void 0,t.length&&(t=s(t,`binary`,v)),e.emit(`field`,u,t,!1,n,b,l),--N,w()}}a._readableState.sync=!1,a.on(`data`,j),a.on(`end`,I)}).on(`error`,function(e){P&&P.emit(`error`,e)})}).on(`error`,function(t){e.emit(`error`,t)}).on(`finish`,function(){I=!0,w()})}h.prototype.write=function(e,t){let n=this.parser.write(e);n&&!this._pause?t():(this._needDrain=!n,this._cb=t)},h.prototype.end=function(){let e=this;e.parser.writable?e.parser.end():e._boy._done||process.nextTick(function(){e._boy._done=!0,e._boy.emit(`finish`)})};function g(e){e.resume()}function _(e){n.call(this,e),this.bytesRead=0,this.truncated=!1}r(_,n),_.prototype._read=function(e){},t.exports=h})),ur=e(((exports,t)=>{let n=/\+/g,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];function i(){this.buffer=void 0}i.prototype.write=function(e){e=e.replace(n,` `);let t=``,i=0,a=0,o=e.length;for(;i<o;++i)this.buffer===void 0?e[i]===`%`&&(i>a&&(t+=e.substring(a,i),a=i),this.buffer=``,++a):r[e.charCodeAt(i)]?(this.buffer+=e[i],++a,this.buffer.length===2&&(t+=String.fromCharCode(parseInt(this.buffer,16)),this.buffer=void 0)):(t+=`%`+this.buffer,this.buffer=void 0,--i);return a<o&&this.buffer===void 0&&(t+=e.substring(a)),t},i.prototype.reset=function(){this.buffer=void 0},t.exports=i})),dr=e(((exports,t)=>{let n=ur(),r=or(),i=rr(),a=/^charset$/i;o.detect=/^application\/x-www-form-urlencoded/i;function o(e,t){let r=t.limits,o=t.parsedConType;this.boy=e,this.fieldSizeLimit=i(r,`fieldSize`,1*1024*1024),this.fieldNameSizeLimit=i(r,`fieldNameSize`,100),this.fieldsLimit=i(r,`fields`,1/0);let s;for(var c=0,l=o.length;c<l;++c)if(Array.isArray(o[c])&&a.test(o[c][0])){s=o[c][1].toLowerCase();break}s===void 0&&(s=t.defCharset||`utf8`),this.decoder=new n,this.charset=s,this._fields=0,this._state=`key`,this._checkingBytes=!0,this._bytesKey=0,this._bytesVal=0,this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._hitLimit=!1}o.prototype.write=function(e,t){if(this._fields===this.fieldsLimit)return this.boy.hitFieldsLimit||(this.boy.hitFieldsLimit=!0,this.boy.emit(`fieldsLimit`)),t();let n,i,a,o=0,s=e.length;for(;o<s;)if(this._state===`key`){for(n=i=void 0,a=o;a<s;++a){if(this._checkingBytes||++o,e[a]===61){n=a;break}else if(e[a]===38){i=a;break}if(this._checkingBytes&&this._bytesKey===this.fieldNameSizeLimit){this._hitLimit=!0;break}else this._checkingBytes&&++this._bytesKey}if(n!==void 0)n>o&&(this._key+=this.decoder.write(e.toString(`binary`,o,n))),this._state=`val`,this._hitLimit=!1,this._checkingBytes=!0,this._val=``,this._bytesVal=0,this._valTrunc=!1,this.decoder.reset(),o=n+1;else if(i!==void 0){++this._fields;let n,a=this._keyTrunc;if(n=i>o?this._key+=this.decoder.write(e.toString(`binary`,o,i)):this._key,this._hitLimit=!1,this._checkingBytes=!0,this._key=``,this._bytesKey=0,this._keyTrunc=!1,this.decoder.reset(),n.length&&this.boy.emit(`field`,r(n,`binary`,this.charset),``,a,!1),o=i+1,this._fields===this.fieldsLimit)return t()}else this._hitLimit?(a>o&&(this._key+=this.decoder.write(e.toString(`binary`,o,a))),o=a,(this._bytesKey=this._key.length)===this.fieldNameSizeLimit&&(this._checkingBytes=!1,this._keyTrunc=!0)):(o<s&&(this._key+=this.decoder.write(e.toString(`binary`,o))),o=s)}else{for(i=void 0,a=o;a<s;++a){if(this._checkingBytes||++o,e[a]===38){i=a;break}if(this._checkingBytes&&this._bytesVal===this.fieldSizeLimit){this._hitLimit=!0;break}else this._checkingBytes&&++this._bytesVal}if(i!==void 0){if(++this._fields,i>o&&(this._val+=this.decoder.write(e.toString(`binary`,o,i))),this.boy.emit(`field`,r(this._key,`binary`,this.charset),r(this._val,`binary`,this.charset),this._keyTrunc,this._valTrunc),this._state=`key`,this._hitLimit=!1,this._checkingBytes=!0,this._key=``,this._bytesKey=0,this._keyTrunc=!1,this.decoder.reset(),o=i+1,this._fields===this.fieldsLimit)return t()}else this._hitLimit?(a>o&&(this._val+=this.decoder.write(e.toString(`binary`,o,a))),o=a,(this._val===``&&this.fieldSizeLimit===0||(this._bytesVal=this._val.length)===this.fieldSizeLimit)&&(this._checkingBytes=!1,this._valTrunc=!0)):(o<s&&(this._val+=this.decoder.write(e.toString(`binary`,o))),o=s)}t()},o.prototype.end=function(){this.boy._done||(this._state===`key`&&this._key.length>0?this.boy.emit(`field`,r(this._key,`binary`,this.charset),``,this._keyTrunc,!1):this._state===`val`&&this.boy.emit(`field`,r(this._key,`binary`,this.charset),r(this._val,`binary`,this.charset),this._keyTrunc,this._valTrunc),this.boy._done=!0,this.boy.emit(`finish`))},t.exports=o})),fr=e(((exports,t)=>{let n=i(`node:stream`).Writable,{inherits:r}=i(`node:util`),a=ar(),o=lr(),s=dr(),c=sr();function l(e){if(!(this instanceof l))return new l(e);if(typeof e!=`object`)throw TypeError(`Busboy expected an options-Object.`);if(typeof e.headers!=`object`)throw TypeError(`Busboy expected an options-Object with headers-attribute.`);if(typeof e.headers[`content-type`]!=`string`)throw TypeError(`Missing Content-Type-header.`);let{headers:t,...r}=e;this.opts={autoDestroy:!1,...r},n.call(this,this.opts),this._done=!1,this._parser=this.getParserByHeaders(t),this._finished=!1}r(l,n),l.prototype.emit=function(e){if(e===`finish`){if(this._done){if(this._finished)return}else{this._parser?.end();return}this._finished=!0}n.prototype.emit.apply(this,arguments)},l.prototype.getParserByHeaders=function(e){let t=c(e[`content-type`]),n={defCharset:this.opts.defCharset,fileHwm:this.opts.fileHwm,headers:e,highWaterMark:this.opts.highWaterMark,isPartAFile:this.opts.isPartAFile,limits:this.opts.limits,parsedConType:t,preservePath:this.opts.preservePath};if(o.detect.test(t[0]))return new o(this,n);if(s.detect.test(t[0]))return new s(this,n);throw Error(`Unsupported Content-Type.`)},l.prototype._write=function(e,t,n){this._parser.write(e,n)},t.exports=l,t.exports.default=l,t.exports.Busboy=l,t.exports.Dicer=a})),pr=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.fakePromise=void 0,exports.getHeadersObj=r,exports.defaultHeadersSerializer=a,exports.isArrayBufferView=s,exports.isNodeReadable=c,exports.isIterable=l,exports.shouldRedirect=u,exports.pipeThrough=d,exports.endStream=f,exports.safeWrite=p;let t=i(`node:events`);function n(e){return e?.forEach!=null}function r(e){return e==null||!n(e)?e:e.headersInit&&!e._map&&!n(e.headersInit)?e.headersInit:Object.fromEntries(e.entries())}function a(e,t){let n=[];return e.forEach((e,r)=>{t&&r===`content-length`&&t(e),n.push(`${r}: ${e}`)}),n}var o=er();Object.defineProperty(exports,`fakePromise`,{enumerable:!0,get:function(){return o.fakePromise}});function s(e){return e!=null&&e.buffer!=null&&e.byteLength!=null&&e.byteOffset!=null}function c(e){return e!=null&&e.pipe!=null}function l(e){return e?.[Symbol.iterator]!=null}function u(e){return e===301||e===302||e===303||e===307||e===308}function d({src:e,dest:t,signal:n,onError:r}){if(r&&t.once(`error`,r),e.once(`error`,e=>{t.destroy(e)}),t.once(`close`,()=>{e.destroyed||e.destroy()}),n){let t=new WeakRef(e),r=new WeakRef(n);function i(){r.deref()?.removeEventListener(`abort`,a),t.deref()?.removeListener(`end`,i),t.deref()?.removeListener(`error`,i),t.deref()?.removeListener(`close`,i)}function a(){t.deref()?.destroy(new m),i()}n.addEventListener(`abort`,a,{once:!0}),e.once(`end`,i),e.once(`error`,i),e.once(`close`,i)}e.pipe(t,{end:!0})}function f(e){return e.end(null,null,null)}function p(e,n){let r=n.write(e);if(!r)return(0,t.once)(n,`drain`)}var m=class extends Error{constructor(e=`The operation was aborted`,t=void 0){super(e,t),this.name=`AbortError`}}})),mr=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillReadableStream=void 0;let t=i(`node:buffer`),n=i(`node:events`),r=i(`node:stream`),a=i(`node:stream/promises`),o=er(),s=pr();function c(e,n){let r=[],i=!1,a=!1;return{desiredSize:e,enqueue(e){let i=typeof e==`string`?t.Buffer.from(e):e;a?n.push(i):r.push(i)},close(){r.length>0&&this._flush(),n.push(null),i=!0},error(e){r.length>0&&this._flush(),n.destroy(e)},get _closed(){return i},_flush(){if(a=!0,r.length>0){let e=r.length>1?t.Buffer.concat(r):r[0];n.push(e),r=[]}}}}function l(e){return e?.read!=null}function u(e){return e?.getReader!=null}var d=class e{readable;constructor(t){if(t instanceof e&&t.readable!=null)this.readable=t.readable;else if(l(t))this.readable=t;else if(u(t))this.readable=r.Readable.fromWeb(t);else{let e=!1,n=!1,i=n=>{if(!e){let r=c(n,this.readable);return e=!0,(0,o.handleMaybePromise)(()=>t?.start?.(r),()=>(r._flush(),!r._closed))}return!0},a=e=>(0,o.handleMaybePromise)(()=>i(e),r=>{if(!r)return;let i=c(e,this.readable);return(0,o.handleMaybePromise)(()=>t?.pull?.(i),()=>{i._flush(),n=!1})});this.readable=new r.Readable({read(e){if(!n)return n=!0,a(e)},destroy(e,n){if(t?.cancel)try{let r=t.cancel(e);if(r?.then)return r.then(()=>{n(null)},e=>{n(e)})}catch(e){n(e);return}n(null)}})}}cancel(e){return this.readable.destroy(e),(0,n.once)(this.readable,`close`)}locked=!1;getReader(e){let t=this.readable[Symbol.asyncIterator]();this.locked=!0;let r=this.readable;return{read(){return t.next()},releaseLock:()=>{if(t.return){let e=t.return();if(e.then){e.then(()=>{this.locked=!1});return}}this.locked=!1},cancel:e=>{if(t.return){let n=t.return(e);if(n.then)return n.then(()=>{this.locked=!1})}return this.locked=!1,(0,s.fakePromise)()},get closed(){return Promise.race([(0,n.once)(r,`end`),(0,n.once)(r,`error`).then(e=>Promise.reject(e))])}}}[Symbol.asyncIterator](){let e=this.readable[Symbol.asyncIterator]();return{[Symbol.asyncIterator](){return this},next:()=>e.next(),return:()=>(this.readable.destroyed||this.readable.destroy(),e.return?.()||(0,s.fakePromise)({done:!0,value:void 0})),throw:t=>(this.readable.destroyed||this.readable.destroy(t),e.throw?.(t)||(0,s.fakePromise)({done:!0,value:void 0}))}}tee(){throw Error(`Not implemented`)}async pipeToWriter(e){try{for await(let t of this)await e.write(t);await e.close()}catch(t){await e.abort(t)}}pipeTo(e){if(p(e))return(0,a.pipeline)(this.readable,e.writable,{end:!0});{let t=e.getWriter();return this.pipeToWriter(t)}}pipeThrough({writable:e,readable:t}){return this.pipeTo(e).catch(e=>{this.readable.destroy(e)}),f(t)&&(t.readable.once(`error`,e=>this.readable.destroy(e)),t.readable.once(`finish`,()=>this.readable.push(null)),t.readable.once(`close`,()=>this.readable.push(null))),t}static[Symbol.hasInstance](e){return u(e)}static from(t){return new e(r.Readable.from(t))}[Symbol.toStringTag]=`ReadableStream`};exports.PonyfillReadableStream=d;function f(e){return e?.readable!=null}function p(e){return e?.writable!=null}})),hr=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillBlob=void 0,exports.hasBufferMethod=o,exports.hasArrayBufferMethod=s,exports.hasBytesMethod=c,exports.hasTextMethod=l,exports.hasSizeProperty=u,exports.hasStreamMethod=d,exports.hasBlobSignature=f,exports.isArrayBuffer=p;let t=i(`node:buffer`),n=mr(),r=pr();function a(e){return typeof e==`string`?t.Buffer.from(e):t.Buffer.isBuffer(e)?e:(0,r.isArrayBufferView)(e)?t.Buffer.from(e.buffer,e.byteOffset,e.byteLength):t.Buffer.from(e)}function o(e){return e!=null&&e.buffer!=null&&typeof e.buffer==`function`}function s(e){return e!=null&&e.arrayBuffer!=null&&typeof e.arrayBuffer==`function`}function c(e){return e!=null&&e.bytes!=null&&typeof e.bytes==`function`}function l(e){return e!=null&&e.text!=null&&typeof e.text==`function`}function u(e){return e!=null&&typeof e.size==`number`}function d(e){return e!=null&&e.stream!=null&&typeof e.stream==`function`}function f(e){return e!=null&&e[Symbol.toStringTag]===`Blob`}function p(e){return e!=null&&e.byteLength!=null&&e.slice!=null}var m=class{blobParts;type;encoding;_size=null;constructor(e=[],t){if(this.blobParts=e,this.type=t?.type||`application/octet-stream`,this.encoding=t?.encoding||`utf8`,this._size=t?.size||null,e.length===1&&f(e[0]))return e[0]}_buffer=null;buffer(){if(this._buffer)return(0,r.fakePromise)(this._buffer);if(this.blobParts.length===1){let e=this.blobParts[0];return o(e)?e.buffer().then(e=>(this._buffer=e,this._buffer)):c(e)?e.bytes().then(e=>(this._buffer=t.Buffer.from(e),this._buffer)):s(e)?e.arrayBuffer().then(n=>(this._buffer=t.Buffer.from(n,void 0,e.size),this._buffer)):(this._buffer=a(e),(0,r.fakePromise)(this._buffer))}let e=[],n=this.blobParts.map((r,i)=>{if(o(r)){e.push(r.buffer().then(e=>{n[i]=e}));return}else if(s(r)){e.push(r.arrayBuffer().then(e=>{n[i]=t.Buffer.from(e,void 0,r.size)}));return}else if(c(r)){e.push(r.bytes().then(e=>{n[i]=t.Buffer.from(e)}));return}else return a(r)});return e.length>0?Promise.all(e).then(()=>t.Buffer.concat(n,this._size||void 0)):(0,r.fakePromise)(t.Buffer.concat(n,this._size||void 0))}arrayBuffer(){if(this._buffer)return(0,r.fakePromise)(this._buffer);if(this.blobParts.length===1){if(p(this.blobParts[0]))return(0,r.fakePromise)(this.blobParts[0]);if(s(this.blobParts[0]))return this.blobParts[0].arrayBuffer()}return this.buffer()}bytes(){if(this._buffer)return(0,r.fakePromise)(this._buffer);if(this.blobParts.length===1){if(t.Buffer.isBuffer(this.blobParts[0]))return this._buffer=this.blobParts[0],(0,r.fakePromise)(this._buffer);if(this.blobParts[0]instanceof Uint8Array)return this._buffer=t.Buffer.from(this.blobParts[0]),(0,r.fakePromise)(this._buffer);if(c(this.blobParts[0]))return this.blobParts[0].bytes();if(o(this.blobParts[0]))return this.blobParts[0].buffer()}return this.buffer()}_text=null;text(){if(this._text)return(0,r.fakePromise)(this._text);if(this.blobParts.length===1){let e=this.blobParts[0];if(typeof e==`string`)return this._text=e,(0,r.fakePromise)(this._text);if(l(e))return e.text().then(e=>(this._text=e,this._text));let t=a(e);return this._text=t.toString(this.encoding),(0,r.fakePromise)(this._text)}return this.buffer().then(e=>(this._text=e.toString(this.encoding),this._text))}_json=null;json(){return this._json?(0,r.fakePromise)(this._json):this.text().then(e=>(this._json=JSON.parse(e),this._json))}_formData=null;formData(){if(this._formData)return(0,r.fakePromise)(this._formData);throw Error(`Not implemented`)}get size(){if(this._size==null){this._size=0;for(let e of this.blobParts)typeof e==`string`?this._size+=t.Buffer.byteLength(e):u(e)?this._size+=e.size:(0,r.isArrayBufferView)(e)&&(this._size+=e.byteLength)}return this._size}stream(){if(this.blobParts.length===1){let e=this.blobParts[0];if(d(e))return e.stream();let t=a(e);return new n.PonyfillReadableStream({start:e=>{e.enqueue(t),e.close()}})}if(this._buffer!=null)return new n.PonyfillReadableStream({start:e=>{e.enqueue(this._buffer),e.close()}});let e;return new n.PonyfillReadableStream({start:t=>{if(this.blobParts.length===0){t.close();return}e=this.blobParts[Symbol.iterator]()},pull:n=>{let{value:r,done:i}=e.next();if(i){n.close();return}if(r){if(o(r))return r.buffer().then(e=>{n.enqueue(e)});if(c(r))return r.bytes().then(e=>{let r=t.Buffer.from(e);n.enqueue(r)});if(s(r))return r.arrayBuffer().then(e=>{let i=t.Buffer.from(e,void 0,r.size);n.enqueue(i)});let e=a(r);n.enqueue(e)}}})}slice(){throw Error(`Not implemented`)}};exports.PonyfillBlob=m})),gr=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillFile=void 0;let t=hr();var n=class extends t.PonyfillBlob{name;lastModified;constructor(e,t,n){super(e,n),this.name=t,this.lastModified=n?.lastModified||Date.now()}webkitRelativePath=``};exports.PonyfillFile=n})),_r={};n(_r,{__addDisposableResource:()=>Gr,__assign:()=>Yr,__asyncDelegator:()=>Lr,__asyncGenerator:()=>Ir,__asyncValues:()=>Rr,__await:()=>Fr,__awaiter:()=>Dr,__classPrivateFieldGet:()=>Hr,__classPrivateFieldIn:()=>Wr,__classPrivateFieldSet:()=>Ur,__createBinding:()=>Xr,__decorate:()=>br,__disposeResources:()=>Kr,__esDecorate:()=>Sr,__exportStar:()=>kr,__extends:()=>vr,__generator:()=>Or,__importDefault:()=>Vr,__importStar:()=>Br,__makeTemplateObject:()=>zr,__metadata:()=>Er,__param:()=>xr,__propKey:()=>wr,__read:()=>jr,__rest:()=>yr,__rewriteRelativeImportExtension:()=>qr,__runInitializers:()=>Cr,__setFunctionName:()=>Tr,__spread:()=>Mr,__spreadArray:()=>Pr,__spreadArrays:()=>Nr,__values:()=>Ar,default:()=>ei});function vr(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);Jr(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function yr(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function br(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function xr(e,t){return function(n,r){t(n,r,e)}}function Sr(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else (d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0}function Cr(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function wr(e){return typeof e==`symbol`?e:`${e}`}function Tr(e,t,n){return typeof t==`symbol`&&(t=t.description?`[${t.description}]`:``),Object.defineProperty(e,`name`,{configurable:!0,value:n?`${n} ${t}`:t})}function Er(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function Dr(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Or(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if((a=n.trys,!(a=a.length>0&&a[a.length-1]))&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function kr(e,t){for(var n in e)n!==`default`&&!Object.prototype.hasOwnProperty.call(t,n)&&Xr(t,e,n)}function Ar(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function jr(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function Mr(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(jr(arguments[t]));return e}function Nr(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r}function Pr(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function Fr(e){return this instanceof Fr?(this.v=e,this):new Fr(e)}function Ir(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof Fr?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function Lr(e){var t,n;return t={},r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:Fr(e[r](t)),done:!1}:i?i(t):t}:i}}function Rr(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Ar==`function`?Ar(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function zr(e,t){return Object.defineProperty?Object.defineProperty(e,`raw`,{value:t}):e.raw=t,e}function Br(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=Qr(e),r=0;r<n.length;r++)n[r]!==`default`&&Xr(t,e,n[r]);return Zr(t,e),t}function Vr(e){return e&&e.__esModule?e:{default:e}}function Hr(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}function Ur(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function Wr(e,t){if(t===null||typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Cannot use 'in' operator on non-object`);return typeof e==`function`?t===e:e.has(t)}function Gr(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t}function Kr(e){function t(t){e.error=e.hasError?new $r(t,e.error,`An error was suppressed during disposal.`):t,e.hasError=!0}var n,r=0;function i(){for(;n=e.stack.pop();)try{if(!n.async&&r===1)return r=0,e.stack.push(n),Promise.resolve().then(i);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(a).then(i,function(e){return t(e),i()})}else r|=1}catch(e){t(e)}if(r===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return i()}function qr(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e}var Jr,Yr,Xr,Zr,Qr,$r,ei,ti=t((()=>{Jr=function(e,t){return Jr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},Jr(e,t)},Yr=function(){return Yr=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},Yr.apply(this,arguments)},Xr=Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),Zr=Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t},Qr=function(e){return Qr=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},Qr(e)},$r=typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r},ei={__extends:vr,__assign:Yr,__rest:yr,__decorate:br,__param:xr,__esDecorate:Sr,__runInitializers:Cr,__propKey:wr,__setFunctionName:Tr,__metadata:Er,__awaiter:Dr,__generator:Or,__createBinding:Xr,__exportStar:kr,__values:Ar,__read:jr,__spread:Mr,__spreadArrays:Nr,__spreadArray:Pr,__await:Fr,__asyncGenerator:Ir,__asyncDelegator:Lr,__asyncValues:Rr,__makeTemplateObject:zr,__importStar:Br,__importDefault:Vr,__classPrivateFieldGet:Hr,__classPrivateFieldSet:Ur,__classPrivateFieldIn:Wr,__addDisposableResource:Gr,__disposeResources:Kr,__rewriteRelativeImportExtension:qr}})),ni=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillSuppressedError=void 0;var t=class extends Error{error;suppressed;constructor(e,t,n){super(n),this.error=e,this.suppressed=t,this.name=`SuppressedError`,Error.captureStackTrace(this,this.constructor)}};exports.PonyfillSuppressedError=t})),ri=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.DisposableSymbols=void 0,exports.patchSymbols=t,exports.DisposableSymbols={get dispose(){return Symbol.dispose||Symbol.for(`dispose`)},get asyncDispose(){return Symbol.asyncDispose||Symbol.for(`asyncDispose`)}};function t(){Symbol.dispose||=Symbol.for(`dispose`),Symbol.asyncDispose||=Symbol.for(`asyncDispose`)}})),ii=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.isSyncDisposable=n,exports.isAsyncDisposable=r;let t=ri();function n(e){return e?.[t.DisposableSymbols.dispose]!=null}function r(e){return e?.[t.DisposableSymbols.asyncDispose]!=null}})),ai=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillAsyncDisposableStack=void 0;let t=er(),n=ni(),r=ri(),i=ii(),a=globalThis.SuppressedError||n.PonyfillSuppressedError;var o=class e{callbacks=[];get disposed(){return this.callbacks.length===0}use(e){return(0,i.isAsyncDisposable)(e)?this.callbacks.push(()=>e[r.DisposableSymbols.asyncDispose]()):(0,i.isSyncDisposable)(e)&&this.callbacks.push(()=>e[r.DisposableSymbols.dispose]()),e}adopt(e,t){return t&&this.callbacks.push(()=>t(e)),e}defer(e){e&&this.callbacks.push(e)}move(){let t=new e;return t.callbacks=this.callbacks,this.callbacks=[],t}disposeAsync(){return this[r.DisposableSymbols.asyncDispose]()}_error;_iterateCallbacks(){let e=this.callbacks.pop();if(e)return(0,t.handleMaybePromise)(e,()=>this._iterateCallbacks(),e=>(this._error=this._error?new a(e,this._error):e,this._iterateCallbacks()))}[r.DisposableSymbols.asyncDispose](){let e=this._iterateCallbacks();if(e?.then)return e.then(()=>{if(this._error){let e=this._error;throw this._error=void 0,e}});if(this._error){let e=this._error;throw this._error=void 0,e}}[Symbol.toStringTag]=`AsyncDisposableStack`};exports.PonyfillAsyncDisposableStack=o})),oi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillDisposableStack=void 0;let t=ni(),n=ri(),r=ii(),i=globalThis.SuppressedError||t.PonyfillSuppressedError;var a=class e{callbacks=[];get disposed(){return this.callbacks.length===0}use(e){return(0,r.isSyncDisposable)(e)&&this.callbacks.push(()=>e[n.DisposableSymbols.dispose]()),e}adopt(e,t){return t&&this.callbacks.push(()=>t(e)),e}defer(e){e&&this.callbacks.push(e)}move(){let t=new e;return t.callbacks=this.callbacks,this.callbacks=[],t}dispose(){return this[n.DisposableSymbols.dispose]()}_error;_iterateCallbacks(){let e=this.callbacks.pop();if(e){try{e()}catch(e){this._error=this._error?new i(e,this._error):e}return this._iterateCallbacks()}}[n.DisposableSymbols.dispose](){if(this._iterateCallbacks(),this._error){let e=this._error;throw this._error=void 0,e}}[Symbol.toStringTag]=`DisposableStack`};exports.PonyfillDisposableStack=a})),si=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.SuppressedError=exports.AsyncDisposableStack=exports.DisposableStack=void 0;let t=(ti(),a(_r)),n=ai(),r=oi(),i=ni();exports.DisposableStack=globalThis.DisposableStack||r.PonyfillDisposableStack,exports.AsyncDisposableStack=globalThis.AsyncDisposableStack||n.PonyfillAsyncDisposableStack,exports.SuppressedError=globalThis.SuppressedError||i.PonyfillSuppressedError,t.__exportStar(ri(),exports)})),ci=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillIteratorObject=void 0;let t=i(`node:util`),n=si(),r=pr();var a=class{iterableIterator;[Symbol.toStringTag]=`IteratorObject`;constructor(e,t){this.iterableIterator=e,this[Symbol.toStringTag]=t}*map(e){let t=0;for(let n of this.iterableIterator)yield e(n,t++)}*filter(e){let t=0;for(let n of this.iterableIterator)e(n,t++)&&(yield n)}reduce(e,t){let n=0,r=t;for(let t of this.iterableIterator)r=e(r,t,n++);return r}forEach(e){let t=0;for(let n of this.iterableIterator)e(n,t++)}*take(e){let t=0;for(let n of this.iterableIterator){if(t>=e)break;yield n,t++}}*drop(e){let t=0;for(let n of this.iterableIterator)t>=e&&(yield n),t++}*flatMap(e){let t=0;for(let n of this.iterableIterator){let i=e(n,t++);if((0,r.isIterable)(i))for(let e of i)yield e;else for(let e of{[Symbol.iterator]:()=>i})yield e}}some(e){let t=0;for(let n of this.iterableIterator)if(e(n,t++))return!0;return!1}every(e){let t=0;for(let n of this.iterableIterator)if(!e(n,t++))return!1;return!0}find(e){let t=0;for(let n of this.iterableIterator)if(e(n,t++))return n}toArray(){return Array.from(this.iterableIterator)}[n.DisposableSymbols.dispose](){this.iterableIterator.return?.()}next(...[e]){return this.iterableIterator.next(e)}[Symbol.iterator](){return this}[Symbol.for(`nodejs.util.inspect.custom`)](){let e={};return this.forEach((n,r)=>{let i=(0,t.inspect)(n);e[r]=i.includes(`,`)?i.split(`,`).map(e=>e.trim()):i}),`${this[Symbol.toStringTag]} ${(0,t.inspect)(e)}`}};exports.PonyfillIteratorObject=a})),li=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillFormData=void 0,exports.getStreamFromFormData=o;let t=i(`node:buffer`),n=ci(),r=mr();var a=class{map=new Map;append(e,t,n){let r=this.map.get(e);r||(r=[],this.map.set(e,r));let i=c(t)?s(e,t,n):t;r.push(i)}delete(e){this.map.delete(e)}get(e){let t=this.map.get(e);return t?t[0]:null}getAll(e){return this.map.get(e)||[]}has(e){return this.map.has(e)}set(e,t,n){let r=c(t)?s(e,t,n):t;this.map.set(e,[r])}[Symbol.iterator](){return this._entries()}*_entries(){for(let[e,t]of this.map)for(let n of t)yield[e,n]}entries(){return new n.PonyfillIteratorObject(this._entries(),`FormDataIterator`)}_keys(){return this.map.keys()}keys(){return new n.PonyfillIteratorObject(this._keys(),`FormDataIterator`)}*_values(){for(let e of this.map.values())for(let t of e)yield t}values(){return new n.PonyfillIteratorObject(this._values(),`FormDataIterator`)}forEach(e){for(let[t,n]of this)e(n,t,this)}};exports.PonyfillFormData=a;function o(e,n=`---`){let i,a=!1,o,s=!1;function c(e){let{done:r,value:a}=i.next();if(r)return e.enqueue(t.Buffer.from(`\r\n--${n}--\r\n`)),e.close();if(s&&e.enqueue(t.Buffer.from(`\r\n--${n}\r\n`)),a){let[n,r]=a;if(typeof r==`string`)e.enqueue(t.Buffer.from(`Content-Disposition: form-data; name="${n}"\r\n\r\n`)),e.enqueue(t.Buffer.from(r));else{let i=``;r.name&&(i=`; filename="${r.name}"`),e.enqueue(t.Buffer.from(`Content-Disposition: form-data; name="${n}"${i}\r\n`)),e.enqueue(t.Buffer.from(`Content-Type: ${r.type||`application/octet-stream`}\r\n\r\n`));let a=r.stream();o=a[Symbol.asyncIterator]()}s=!0}}return new r.PonyfillReadableStream({start:()=>{i=e.entries()},pull:e=>a?o?o.next().then(({done:t,value:n})=>(t&&(o=void 0),n?e.enqueue(n):c(e))):c(e):(a=!0,e.enqueue(t.Buffer.from(`--${n}\r\n`))),cancel:e=>{i?.return?.(e),o?.return?.(e)}})}function s(e,t,n){return Object.defineProperty(t,`name`,{configurable:!0,enumerable:!0,value:n||t.name||e}),t}function c(e){return e?.arrayBuffer!=null}})),ui=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillBody=void 0;let t=i(`node:buffer`),n=i(`node:stream`),r=fr(),a=er(),o=hr(),s=gr(),c=li(),l=mr(),u=pr();var d;(function(e){e.ReadableStream=`ReadableStream`,e.Blob=`Blob`,e.FormData=`FormData`,e.String=`String`,e.Readable=`Readable`,e.Buffer=`Buffer`,e.AsyncIterable=`AsyncIterable`})(d||={});var f=class{bodyInit;options;bodyUsed=!1;contentType=null;contentLength=null;constructor(e,t={}){this.bodyInit=e,this.options=t;let{bodyFactory:n,contentType:r,contentLength:i,bodyType:a,buffer:o}=p(e);this._bodyFactory=n,this.contentType=r,this.contentLength=i,this.bodyType=a,this._buffer=o,this._signal=t.signal}bodyType;_bodyFactory=()=>null;_generatedBody=null;_buffer;_signal;generateBody(){if(this._generatedBody?.readable?.destroyed&&this._buffer&&(this._generatedBody.readable=n.Readable.from(this._buffer)),this._generatedBody)return this._generatedBody;let e=this._bodyFactory();return this._generatedBody=e,e}handleContentLengthHeader(e=!1){let t=this.headers.get(`content-type`);t?this.contentType=t:this.contentType&&this.headers.set(`content-type`,this.contentType);let n=this.headers.get(`content-length`);e&&this.bodyInit==null&&!n&&(this.contentLength=0,this.headers.set(`content-length`,`0`)),n?this.contentLength=parseInt(n,10):this.contentLength&&this.headers.set(`content-length`,this.contentLength.toString())}get body(){let e=this.generateBody();if(e!=null){let t=e,n=e.readable;return new Proxy(e.readable,{get(e,r){if(r in t){let e=t[r];return typeof e==`function`?e.bind(t):e}if(r in n){let e=n[r];return typeof e==`function`?e.bind(n):e}}})}return null}_chunks=null;_doCollectChunksFromReadableJob(){if(this.bodyType===d.AsyncIterable){if(Array.fromAsync)return(0,a.handleMaybePromise)(()=>Array.fromAsync(this.bodyInit),e=>(this._chunks=e,this._chunks));let e=this.bodyInit[Symbol.asyncIterator](),t=[],n=()=>(0,a.handleMaybePromise)(()=>e.next(),({value:e,done:r})=>(e&&t.push(e),r?(this._chunks=t,this._chunks):n()));return n()}let e=this.generateBody();if(!e)return this._chunks=[],(0,u.fakePromise)(this._chunks);if(e.readable.destroyed)return(0,u.fakePromise)(this._chunks=[]);let t=[];return new Promise((n,r)=>{e.readable.on(`data`,e=>{t.push(e)}),e.readable.once(`error`,r),e.readable.once(`end`,()=>{n(this._chunks=t)})})}_collectChunksFromReadable(){return this._chunks?(0,u.fakePromise)(this._chunks):(this._chunks||=this._doCollectChunksFromReadableJob(),this._chunks)}_blob=null;blob(){return this._blob?(0,u.fakePromise)(this._blob):(this.bodyType===d.String&&(this._text=this.bodyInit,this._blob=new o.PonyfillBlob([this._text],{type:this.contentType||`text/plain;charset=UTF-8`,size:this.contentLength})),this.bodyType===d.Blob?(this._blob=this.bodyInit,(0,u.fakePromise)(this._blob)):this._buffer?(this._blob=new o.PonyfillBlob([this._buffer],{type:this.contentType||``,size:this.contentLength}),(0,u.fakePromise)(this._blob)):(0,u.fakePromise)((0,a.handleMaybePromise)(()=>this._collectChunksFromReadable(),e=>(this._blob=new o.PonyfillBlob(e,{type:this.contentType||``,size:this.contentLength}),this._blob))))}_formData=null;formData(e){if(this._formData)return(0,u.fakePromise)(this._formData);if(this.bodyType===d.FormData)return this._formData=this.bodyInit,(0,u.fakePromise)(this._formData);this._formData=new c.PonyfillFormData;let t=this.generateBody();if(t==null)return(0,u.fakePromise)(this._formData);let i={...this.options.formDataLimits,...e?.formDataLimits};return new Promise((e,t)=>{let a=this.body?.readable;if(!a)return t(Error(`No stream available`));let o=null,c=new r.Busboy({headers:{"content-length":typeof this.contentLength==`number`?this.contentLength.toString():this.contentLength||``,"content-type":this.contentType||``},limits:i,defCharset:`utf-8`});this._signal&&(0,n.addAbortSignal)(this._signal,c);let l=!1,u=n=>{l||(l=!0,a.unpipe(c),c.destroy(),o&&=(o.destroy(),null),n?t(n):e(this._formData))};a.on(`error`,u),c.on(`field`,(e,t,n,r)=>{if(n)return u(Error(`Field name size exceeded: ${i?.fieldNameSize} bytes`));if(r)return u(Error(`Field value size exceeded: ${i?.fieldSize} bytes`));this._formData.set(e,t)}),c.on(`file`,(e,t,n,r,a)=>{o=t;let c=[];t.on(`data`,e=>{c.push(e)}),t.on(`error`,u),t.on(`limit`,()=>{u(Error(`File size limit exceeded: ${i?.fileSize} bytes`))}),t.on(`close`,()=>{t.truncated&&u(Error(`File size limit exceeded: ${i?.fileSize} bytes`)),o=null;let r=new s.PonyfillFile(c,n,{type:a});this._formData.set(e,r)})}),c.on(`fieldsLimit`,()=>{u(Error(`Fields limit exceeded: ${i?.fields}`))}),c.on(`filesLimit`,()=>{u(Error(`Files limit exceeded: ${i?.files}`))}),c.on(`partsLimit`,()=>{u(Error(`Parts limit exceeded: ${i?.parts}`))}),c.on(`end`,u),c.on(`finish`,u),c.on(`close`,u),c.on(`error`,u),a.pipe(c)})}buffer(){if(this._buffer)return(0,u.fakePromise)(this._buffer);if(this._text)return this._buffer=t.Buffer.from(this._text,`utf-8`),(0,u.fakePromise)(this._buffer);if(this.bodyType===d.String)return this.text().then(e=>(this._text=e,this._buffer=t.Buffer.from(e,`utf-8`),this._buffer));if(this.bodyType===d.Blob){if((0,o.hasBufferMethod)(this.bodyInit))return this.bodyInit.buffer().then(e=>(this._buffer=e,this._buffer));if((0,o.hasBytesMethod)(this.bodyInit))return this.bodyInit.bytes().then(e=>(this._buffer=t.Buffer.from(e),this._buffer));if((0,o.hasArrayBufferMethod)(this.bodyInit))return this.bodyInit.arrayBuffer().then(e=>(this._buffer=t.Buffer.from(e,void 0,e.byteLength),this._buffer))}return(0,u.fakePromise)((0,a.handleMaybePromise)(()=>this._collectChunksFromReadable(),e=>e.length===1?(this._buffer=e[0],this._buffer):(this._buffer=t.Buffer.concat(e),this._buffer)))}bytes(){return this.buffer()}arrayBuffer(){return this.buffer()}_json=null;json(){return this._json?(0,u.fakePromise)(this._json):this.text().then(e=>{try{this._json=JSON.parse(e)}catch(t){throw t instanceof SyntaxError&&(t.message+=`, "${e}" is not valid JSON`),t}return this._json})}_text=null;text(){return this._text?(0,u.fakePromise)(this._text):this.bodyType===d.String?(this._text=this.bodyInit,(0,u.fakePromise)(this._text)):this.buffer().then(e=>(this._text=e.toString(`utf-8`),this._text))}};exports.PonyfillBody=f;function p(e){if(e==null)return{bodyFactory:()=>null,contentType:null,contentLength:null};if(typeof e==`string`){let r=t.Buffer.byteLength(e);return{bodyType:d.String,contentType:`text/plain;charset=UTF-8`,contentLength:r,bodyFactory(){let r=n.Readable.from(t.Buffer.from(e,`utf-8`));return new l.PonyfillReadableStream(r)}}}if(t.Buffer.isBuffer(e)){let t=e;return{bodyType:d.Buffer,contentType:null,contentLength:e.length,buffer:e,bodyFactory(){let e=n.Readable.from(t),r=new l.PonyfillReadableStream(e);return r}}}if((0,u.isArrayBufferView)(e)){let r=t.Buffer.from(e.buffer,e.byteOffset,e.byteLength);return{bodyType:d.Buffer,contentLength:e.byteLength,contentType:null,buffer:r,bodyFactory(){let e=n.Readable.from(r),t=new l.PonyfillReadableStream(e);return t}}}if(e instanceof l.PonyfillReadableStream&&e.readable!=null){let t=e;return{bodyType:d.ReadableStream,bodyFactory:()=>t,contentType:null,contentLength:null}}if(h(e)){let t=e;return{bodyType:d.Blob,contentType:e.type,contentLength:e.size,bodyFactory(){return t.stream()}}}if(e instanceof ArrayBuffer){let r=e.byteLength,i=t.Buffer.from(e,void 0,e.byteLength);return{bodyType:d.Buffer,contentType:null,contentLength:r,buffer:i,bodyFactory(){let e=n.Readable.from(i),t=new l.PonyfillReadableStream(e);return t}}}if(e instanceof n.Readable)return{bodyType:d.Readable,contentType:null,contentLength:null,bodyFactory(){let t=new l.PonyfillReadableStream(e);return t}};if(g(e))return{bodyType:d.String,contentType:`application/x-www-form-urlencoded;charset=UTF-8`,contentLength:null,bodyFactory(){let t=new l.PonyfillReadableStream(n.Readable.from(e.toString()));return t}};if(m(e)){let t=Math.random().toString(36).substr(2),n=`multipart/form-data; boundary=${t}`;return{bodyType:d.FormData,contentType:n,contentLength:null,bodyFactory(){return(0,c.getStreamFromFormData)(e,t)}}}if(_(e))return{contentType:null,contentLength:null,bodyFactory(){return new l.PonyfillReadableStream(e)}};if(e[Symbol.iterator]||e[Symbol.asyncIterator])return{contentType:null,contentLength:null,bodyType:d.AsyncIterable,bodyFactory(){let t=n.Readable.from(e);return new l.PonyfillReadableStream(t)}};throw Error(`Unknown body type`)}function m(e){return e?.forEach!=null}function h(e){return e?.stream!=null&&typeof e.stream==`function`}function g(e){return e?.sort!=null}function _(e){return e?.getReader!=null}})),di=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillHeaders=void 0,exports.isHeadersLike=r;let t=i(`node:util`),n=ci();function r(e){return e?.get&&e?.forEach}var a=class{headersInit;_map;objectNormalizedKeysOfHeadersInit=[];objectOriginalKeysOfHeadersInit=[];_setCookies;constructor(e){this.headersInit=e}_get(e){let t=e.toLowerCase();if(t===`set-cookie`&&this._setCookies?.length)return this._setCookies.join(`, `);if(this._map)return this._map.get(t)||null;if(this.headersInit==null)return null;if(Array.isArray(this.headersInit)){let e=this.headersInit.filter(([e])=>e.toLowerCase()===t);return e.length===0?null:e.length===1?e[0][1]:e.map(([,e])=>e).join(`, `)}else if(r(this.headersInit))return this.headersInit.get(t);else{let n=this.headersInit[e]||this.headersInit[t];if(n!=null)return n;this.objectNormalizedKeysOfHeadersInit.length||Object.keys(this.headersInit).forEach(e=>{this.objectOriginalKeysOfHeadersInit.push(e),this.objectNormalizedKeysOfHeadersInit.push(e.toLowerCase())});let r=this.objectNormalizedKeysOfHeadersInit.indexOf(t);if(r===-1)return null;let i=this.objectOriginalKeysOfHeadersInit[r];return this.headersInit[i]}}getMap(){if(!this._map)if(this._setCookies||=[],this.headersInit!=null)if(Array.isArray(this.headersInit)){this._map=new Map;for(let[e,t]of this.headersInit){let n=e.toLowerCase();if(n===`set-cookie`){this._setCookies.push(t);continue}this._map.set(n,t)}}else if(r(this.headersInit))this._map=new Map,this.headersInit.forEach((e,t)=>{if(t===`set-cookie`){this._setCookies||=[],this._setCookies.push(e);return}this._map.set(t,e)});else for(let e in this._map=new Map,this.headersInit){let t=this.headersInit[e];if(t!=null){let n=e.toLowerCase();if(n===`set-cookie`){this._setCookies||=[],this._setCookies.push(t);continue}this._map.set(n,t)}}else this._map=new Map;return this._map}append(e,t){let n=e.toLowerCase();if(n===`set-cookie`){this._setCookies||=[],this._setCookies.push(t);return}let r=this.getMap().get(n),i=r?`${r}, ${t}`:t;this.getMap().set(n,i)}get(e){let t=this._get(e);return t==null?null:t.toString()}has(e){let t=e.toLowerCase();return t===`set-cookie`?!!this._setCookies?.length:!!this._get(e)}set(e,t){let n=e.toLowerCase();if(n===`set-cookie`){this._setCookies=[t];return}if(!this._map&&this.headersInit!=null)if(Array.isArray(this.headersInit)){let e=this.headersInit.find(([e])=>e.toLowerCase()===n);e?e[1]=t:this.headersInit.push([n,t]);return}else if(r(this.headersInit)){this.headersInit.set(n,t);return}else{this.headersInit[n]=t;return}this.getMap().set(n,t)}delete(e){let t=e.toLowerCase();if(t===`set-cookie`){this._setCookies=[];return}this.getMap().delete(t)}forEach(e){if(this._setCookies?.forEach(t=>{e(t,`set-cookie`,this)}),!this._map){if(this.headersInit){if(Array.isArray(this.headersInit)){this.headersInit.forEach(([t,n])=>{e(n,t,this)});return}if(r(this.headersInit)){this.headersInit.forEach(e);return}Object.entries(this.headersInit).forEach(([t,n])=>{n!=null&&e(n,t,this)})}return}this.getMap().forEach((t,n)=>{e(t,n,this)})}*_keys(){if(this._setCookies?.length&&(yield`set-cookie`),!this._map&&this.headersInit){if(Array.isArray(this.headersInit)){yield*this.headersInit.map(([e])=>e)[Symbol.iterator]();return}if(r(this.headersInit)){yield*this.headersInit.keys();return}yield*Object.keys(this.headersInit)[Symbol.iterator]();return}yield*this.getMap().keys()}keys(){return new n.PonyfillIteratorObject(this._keys(),`HeadersIterator`)}*_values(){if(this._setCookies?.length&&(yield*this._setCookies),!this._map&&this.headersInit){if(Array.isArray(this.headersInit)){yield*this.headersInit.map(([,e])=>e)[Symbol.iterator]();return}if(r(this.headersInit)){yield*this.headersInit.values();return}yield*Object.values(this.headersInit)[Symbol.iterator]();return}yield*this.getMap().values()}values(){return new n.PonyfillIteratorObject(this._values(),`HeadersIterator`)}*_entries(){if(this._setCookies?.length&&(yield*this._setCookies.map(e=>[`set-cookie`,e])),!this._map&&this.headersInit){if(Array.isArray(this.headersInit)){yield*this.headersInit;return}if(r(this.headersInit)){yield*this.headersInit.entries();return}yield*Object.entries(this.headersInit);return}yield*this.getMap().entries()}entries(){return new n.PonyfillIteratorObject(this._entries(),`HeadersIterator`)}getSetCookie(){return this._setCookies||this.getMap(),this._setCookies}[Symbol.iterator](){return this.entries()}[Symbol.for(`nodejs.util.inspect.custom`)](){let e={};return this.forEach((t,n)=>{n===`set-cookie`?e[`set-cookie`]=this._setCookies||[]:e[n]=t?.includes(`,`)?t.split(`,`).map(e=>e.trim()):t}),`Headers ${(0,t.inspect)(e)}`}};exports.PonyfillHeaders=a})),fi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillResponse=void 0;let t=i(`node:http`),n=ui(),r=di(),a=`application/json; charset=utf-8`;var o=class e extends n.PonyfillBody{headers;constructor(e,n){super(e||null,n),this.headers=n?.headers&&(0,r.isHeadersLike)(n.headers)?n.headers:new r.PonyfillHeaders(n?.headers),this.status=n?.status||200,this.statusText=n?.statusText||t.STATUS_CODES[this.status]||`OK`,this.url=n?.url||``,this.redirected=n?.redirected||!1,this.type=n?.type||`default`,this.handleContentLengthHeader()}get ok(){return this.status>=200&&this.status<300}status;statusText;url;redirected;type;clone(){return this}static error(){return new e(null,{status:500,statusText:`Internal Server Error`})}static redirect(t,n=302){if(n<300||n>399)throw RangeError(`Invalid status code`);return new e(null,{headers:{location:t},status:n})}static json(t,n){let i=JSON.stringify(t);if(!n)n={headers:{"content-type":a,"content-length":Buffer.byteLength(i).toString()}};else if(!n.headers)n.headers={"content-type":a,"content-length":Buffer.byteLength(i).toString()};else if((0,r.isHeadersLike)(n.headers))n.headers.has(`content-type`)||n.headers.set(`content-type`,a),n.headers.has(`content-length`)||n.headers.set(`content-length`,Buffer.byteLength(i).toString());else if(Array.isArray(n.headers)){let e=!1,t=!1;for(let[r]of n.headers){if(t&&e)break;!e&&r.toLowerCase()===`content-type`?e=!0:!t&&r.toLowerCase()===`content-length`&&(t=!0)}e||n.headers.push([`content-type`,a]),t||n.headers.push([`content-length`,Buffer.byteLength(i).toString()])}else typeof n.headers==`object`&&(n.headers?.[`content-type`]??(n.headers[`content-type`]=a),n.headers?.[`content-length`]??(n.headers[`content-length`]=Buffer.byteLength(i).toString()));return new e(i,n)}[Symbol.toStringTag]=`Response`};exports.PonyfillResponse=o})),pi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.fetchCurl=s;let t=i(`node:stream`),n=i(`node:tls`),r=er(),a=fi(),o=pr();function s(e){let{Curl:i,CurlFeature:s,CurlPause:c,CurlProgressFunc:l}=globalThis.libcurl,u=new i;u.enable(s.NoDataParsing),u.setOpt(`URL`,e.url),process.env.NODE_TLS_REJECT_UNAUTHORIZED===`0`&&u.setOpt(`SSL_VERIFYPEER`,!1),process.env.NODE_EXTRA_CA_CERTS?u.setOpt(`CAINFO`,process.env.NODE_EXTRA_CA_CERTS):u.setOpt(`CAINFO_BLOB`,n.rootCertificates.join(`
|
|
55
|
+
`)),u.enable(s.StreamResponse);let d;if(e._signal===null?d=void 0:e._signal&&(d=e._signal),u.setStreamProgressCallback(function(){return d?.aborted?process.env.DEBUG?l.Continue:1:0}),e.bodyType===`String`)u.setOpt(`POSTFIELDS`,e.bodyInit);else{let n=e.body==null?null:(0,o.isNodeReadable)(e.body)?e.body:t.Readable.from(e.body);n&&(u.setOpt(`UPLOAD`,!0),u.setUploadStream(n))}process.env.DEBUG&&u.setOpt(`VERBOSE`,!0),u.setOpt(`TRANSFER_ENCODING`,!1),u.setOpt(`HTTP_TRANSFER_DECODING`,!0),u.setOpt(`FOLLOWLOCATION`,e.redirect===`follow`),u.setOpt(`MAXREDIRS`,20),u.setOpt(`ACCEPT_ENCODING`,``),u.setOpt(`CUSTOMREQUEST`,e.method);let f=e.headersSerializer||o.defaultHeadersSerializer,p,m=f(e.headers,e=>{p=Number(e)});p!=null&&u.setOpt(`INFILESIZE`,p),u.setOpt(`HTTPHEADER`,m),u.enable(s.NoHeaderParsing);let h=(0,r.createDeferredPromise)(),g;function _(){if(u.isOpen)try{u.pause(c.Recv)}catch(e){h.reject(e)}}return d?.addEventListener(`abort`,_,{once:!0}),u.once(`end`,function(){try{u.close()}catch(e){h.reject(e)}d?.removeEventListener(`abort`,_)}),u.once(`error`,function(e){g&&!g.closed&&!g.destroyed?g.destroy(e):(e.message===`Operation was aborted by an application callback`&&(e.message=`The operation was aborted.`),h.reject(e));try{u.close()}catch(e){h.reject(e)}}),u.once(`stream`,function(n,r,s){let c=n.pipe(new t.PassThrough,{end:!0}),l=s.toString(`utf8`).split(/\r?\n|\r/g).filter(t=>t&&!t.startsWith(`HTTP/`)?(e.redirect===`error`&&t.toLowerCase().includes(`location`)&&(0,o.shouldRedirect)(r)&&(n.destroyed||n.resume(),c.destroy(),h.reject(Error(`redirect is not allowed`))),!0):!1),d=l.map(e=>e.split(/:\s(.+)/).slice(0,2)),f=new a.PonyfillResponse(c,{status:r,headers:d,url:u.getInfo(i.info.REDIRECT_URL)?.toString()||e.url,redirected:Number(u.getInfo(i.info.REDIRECT_COUNT))>0});h.resolve(f),g=c}),setImmediate(()=>{u.perform()}),h.promise}})),mi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillURL=void 0;let t=(ti(),a(_r)),n=t.__importDefault(i(`node:buffer`)),r=i(`node:crypto`),o=globalThis.URL;var s=class extends o{static blobRegistry=new Map;static createObjectURL(e){let t=`blob:whatwgnode:${(0,r.randomUUID)()}`;return this.blobRegistry.set(t,e),t}static revokeObjectURL(e){this.blobRegistry.has(e)?this.blobRegistry.delete(e):o.revokeObjectURL(e)}static getBlobFromURL(e){return this.blobRegistry.get(e)||n.default?.resolveObjectURL?.(e)}};exports.PonyfillURL=s})),hi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillRequest=void 0;let t=i(`node:http`),n=i(`node:https`),r=ui(),a=di(),o=mi();function s(e){return e[Symbol.toStringTag]===`Request`}function c(e){return e?.href!=null}var l=class extends r.PonyfillBody{constructor(e,r){let i,o,l=null,u;if(typeof e==`string`?i=e:c(e)?o=e:s(e)&&(e._parsedUrl?o=e._parsedUrl:i=e._url?e._url:e.url,l=e.body,u=e),r!=null&&(l=r.body||null,u=r),super(l,u),this._url=i,this._parsedUrl=o,this.cache=u?.cache||`default`,this.credentials=u?.credentials||`same-origin`,this.headers=u?.headers&&(0,a.isHeadersLike)(u.headers)?u.headers:new a.PonyfillHeaders(u?.headers),this.integrity=u?.integrity||``,this.keepalive=u?.keepalive==null?!1:u?.keepalive,this.method=u?.method?.toUpperCase()||`GET`,this.mode=u?.mode||`cors`,this.redirect=u?.redirect||`follow`,this.referrer=u?.referrer||`about:client`,this.referrerPolicy=u?.referrerPolicy||`no-referrer`,this.headersSerializer=u?.headersSerializer,this.duplex=u?.duplex||`half`,this.destination=`document`,this.priority=`auto`,this.method!==`GET`&&this.method!==`HEAD`&&this.handleContentLengthHeader(!0),u?.agent!=null){let e=o?.protocol||i||this.url;u.agent===!1?this.agent=!1:(e.startsWith(`http:`)&&u.agent instanceof t.Agent||e.startsWith(`https:`)&&u.agent instanceof n.Agent)&&(this.agent=u.agent)}}headersSerializer;cache;credentials;destination;headers;integrity;keepalive;method;mode;priority;redirect;referrer;referrerPolicy;_url;get signal(){return this._signal||=new AbortController().signal,this._signal}get url(){if(this._url==null)if(this._parsedUrl)this._url=this._parsedUrl.toString();else throw TypeError(`Invalid URL`);return this._url}_parsedUrl;get parsedUrl(){if(this._parsedUrl==null)if(this._url!=null)this._parsedUrl=new o.PonyfillURL(this._url,`http://localhost`);else throw TypeError(`Invalid URL`);return this._parsedUrl}duplex;agent;clone(){return this}[Symbol.toStringTag]=`Request`};exports.PonyfillRequest=l})),gi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.fetchNodeHttp=f;let t=i(`node:http`),n=i(`node:https`),r=i(`node:stream`),a=i(`node:zlib`),o=er(),s=hi(),c=fi(),l=mi(),u=pr();function d(e){if(e.startsWith(`http:`))return t.request;if(e.startsWith(`https:`))return n.request;throw Error(`Unsupported protocol: ${e.split(`:`)[0]||e}`)}function f(e){return new Promise((n,i)=>{try{let p=d(e.parsedUrl?.protocol||e.url),m=e.headersSerializer||u.getHeadersObj,h=m(e.headers);h[`accept-encoding`]??=`gzip, deflate, br`;let g;e._signal==null?g=void 0:e._signal&&(g=e._signal);let _;if(_=e.parsedUrl?p(e.parsedUrl,{method:e.method,headers:h,signal:g,agent:e.agent}):p(e.url,{method:e.method,headers:h,signal:g,agent:e.agent}),_.once(`error`,i),_.once(`response`,o=>{let d,p=o.headers[`content-encoding`];switch(p){case`x-gzip`:case`gzip`:d=(0,a.createGunzip)();break;case`x-deflate`:case`deflate`:d=(0,a.createInflate)();break;case`x-deflate-raw`:case`deflate-raw`:d=(0,a.createInflateRaw)();break;case`br`:d=(0,a.createBrotliDecompress)();break}if(o.headers.location&&(0,u.shouldRedirect)(o.statusCode)){if(e.redirect===`error`){let e=Error(`Redirects are not allowed`);i(e),o.resume();return}if(e.redirect===`follow`){let t=new l.PonyfillURL(o.headers.location,e.parsedUrl||e.url),r=f(new s.PonyfillRequest(t,e));n(r.then(e=>(e.redirected=!0,e))),o.resume();return}}d||=new r.PassThrough,(0,u.pipeThrough)({src:o,dest:d,signal:g,onError:e=>{o.destroyed||o.destroy(e),d.destroyed||d.destroy(e),i(e)}});let m=o.statusCode||200,h=o.statusMessage||t.STATUS_CODES[m];h??=``;let _=new c.PonyfillResponse(d||o,{status:m,statusText:h,headers:o.headers,url:e.url,signal:g});n(_)}),e._buffer!=null)(0,o.handleMaybePromise)(()=>(0,u.safeWrite)(e._buffer,_),()=>(0,u.endStream)(_),i);else{let t=e.body==null?null:(0,u.isNodeReadable)(e.body)?e.body:r.Readable.from(e.body);t?t.pipe(_):(0,u.endStream)(_)}}catch(e){i(e)}})}})),_i=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.fetchPonyfill=h;let t=i(`node:buffer`),n=i(`node:fs`),r=i(`node:url`),a=pi(),o=gi(),s=hi(),c=fi(),l=mi(),u=pr();async function d(e){let t=(0,r.fileURLToPath)(e);try{await n.promises.access(t,n.promises.constants.R_OK);let e=await n.promises.stat(t,{bigint:!0}),r=(0,n.createReadStream)(t);return new c.PonyfillResponse(r,{status:200,statusText:`OK`,headers:{"content-type":`application/octet-stream`,"last-modified":e.mtime.toUTCString()}})}catch(e){if(e.code===`ENOENT`)return new c.PonyfillResponse(null,{status:404,statusText:`Not Found`});if(e.code===`EACCES`)return new c.PonyfillResponse(null,{status:403,statusText:`Forbidden`});throw e}}function f(e){let[n=`text/plain`,...r]=e.substring(5).split(`,`),i=decodeURIComponent(r.join(`,`));if(n.endsWith(`;base64`)){let e=t.Buffer.from(i,`base64url`),r=n.slice(0,-7);return new c.PonyfillResponse(e,{status:200,statusText:`OK`,headers:{"content-type":r}})}return new c.PonyfillResponse(i,{status:200,statusText:`OK`,headers:{"content-type":n}})}function p(e){let t=l.PonyfillURL.getBlobFromURL(e);if(!t)throw TypeError(`Invalid Blob URL`);return new c.PonyfillResponse(t,{status:200,headers:{"content-type":t.type,"content-length":t.size.toString()}})}function m(e){return e!=null&&e.href!=null}function h(e,t){if(typeof e==`string`||m(e)){let n=new s.PonyfillRequest(e,t);return h(n)}let n=e;if(n.url.startsWith(`data:`)){let e=f(n.url);return(0,u.fakePromise)(e)}if(n.url.startsWith(`file:`)){let e=d(n.url);return e}if(n.url.startsWith(`blob:`)){let e=p(n.url);return(0,u.fakePromise)(e)}return globalThis.libcurl&&!n.agent?(0,a.fetchCurl)(n):(0,o.fetchNodeHttp)(n)}})),vi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillTextDecoder=exports.PonyfillTextEncoder=void 0,exports.PonyfillBtoa=o;let t=i(`node:buffer`),n=pr();var r=class{encoding;constructor(e=`utf-8`){this.encoding=e}encode(e){return t.Buffer.from(e,this.encoding)}encodeInto(e,t){let n=this.encode(e),r=n.copy(t);return{read:r,written:r}}};exports.PonyfillTextEncoder=r;var a=class{encoding;fatal=!1;ignoreBOM=!1;constructor(e=`utf-8`,t){this.encoding=e,t&&(this.fatal=t.fatal||!1,this.ignoreBOM=t.ignoreBOM||!1)}decode(e){return t.Buffer.isBuffer(e)?e.toString(this.encoding):(0,n.isArrayBufferView)(e)?t.Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(this.encoding):t.Buffer.from(e).toString(this.encoding)}};exports.PonyfillTextDecoder=a;function o(e){return t.Buffer.from(e,`binary`).toString(`base64`)}})),yi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillURLSearchParams=void 0,exports.PonyfillURLSearchParams=globalThis.URLSearchParams})),bi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillWritableStream=void 0;let t=i(`node:events`),n=i(`node:stream`),r=er(),a=pr();var o=class{writable;constructor(e){if(e instanceof n.Writable)this.writable=e;else if(e){let t=new n.Writable({write(t,n,r){try{let n=e.write?.(t,i);n instanceof Promise?n.then(()=>{r()},e=>{r(e)}):r()}catch(e){r(e)}},final(t){let n=e.close?.();n instanceof Promise?n.then(()=>{t()},e=>{t(e)}):t()}});this.writable=t;let r=new AbortController,i={signal:r.signal,error(e){t.destroy(e)}};t.once(`error`,e=>r.abort(e)),t.once(`close`,()=>r.abort())}else this.writable=new n.Writable}getWriter(){let e=this.writable;return{get closed(){return(0,t.once)(e,`close`)},get desiredSize(){return e.writableLength},get ready(){return(0,t.once)(e,`drain`)},releaseLock(){},write(t){let n=(0,a.fakePromise)();return t==null?n:n.then(()=>(0,a.safeWrite)(t,e))},close(){return!e.errored&&e.closed?(0,a.fakePromise)():e.errored?(0,r.fakeRejectPromise)(e.errored):(0,a.fakePromise)().then(()=>(0,a.endStream)(e))},abort(n){return e.destroy(n),(0,t.once)(e,`close`)}}}close(){return!this.writable.errored&&this.writable.closed?(0,a.fakePromise)():this.writable.errored?(0,r.fakeRejectPromise)(this.writable.errored):(0,a.fakePromise)().then(()=>(0,a.endStream)(this.writable))}abort(e){return this.writable.destroy(e),(0,t.once)(this.writable,`close`)}locked=!1};exports.PonyfillWritableStream=o})),xi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillTransformStream=void 0;let t=i(`node:stream`),n=mr(),r=pr(),a=bi();var o=class{transform;writable;readable;constructor(e){if(e instanceof t.Transform)this.transform=e;else if(e){let n={enqueue(e){i.push(e)},error(e){i.destroy(e)},terminate(){(0,r.endStream)(i)},get desiredSize(){return i.writableLength}},i=new t.Transform({read(){},write(t,r,i){try{let r=e.transform?.(t,n);r instanceof Promise?r.then(()=>{i()},e=>{i(e)}):i()}catch(e){i(e)}},final(t){try{let r=e.flush?.(n);r instanceof Promise?r.then(()=>{t()},e=>{t(e)}):t()}catch(e){t(e)}}});this.transform=i}else this.transform=new t.Transform;this.writable=new a.PonyfillWritableStream(this.transform),this.readable=new n.PonyfillReadableStream(this.transform)}};exports.PonyfillTransformStream=o})),Si=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillCompressionStream=void 0;let t=i(`node:zlib`),n=xi();var r=class extends n.PonyfillTransformStream{static supportedFormats=globalThis.process?.version?.startsWith(`v2`)?[`gzip`,`deflate`,`br`]:[`gzip`,`deflate`,`deflate-raw`,`br`];constructor(e){switch(e){case`x-gzip`:case`gzip`:super((0,t.createGzip)());break;case`x-deflate`:case`deflate`:super((0,t.createDeflate)());break;case`deflate-raw`:super((0,t.createDeflateRaw)());break;case`br`:super((0,t.createBrotliCompress)());break;default:throw Error(`Unsupported compression format: ${e}`)}}};exports.PonyfillCompressionStream=r})),Ci=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillDecompressionStream=void 0;let t=i(`node:zlib`),n=xi();var r=class extends n.PonyfillTransformStream{static supportedFormats=globalThis.process?.version?.startsWith(`v2`)?[`gzip`,`deflate`,`br`]:[`gzip`,`deflate`,`deflate-raw`,`br`];constructor(e){switch(e){case`x-gzip`:case`gzip`:super((0,t.createGunzip)());break;case`x-deflate`:case`deflate`:super((0,t.createInflate)());break;case`deflate-raw`:super((0,t.createInflateRaw)());break;case`br`:super((0,t.createBrotliDecompress)());break;default:throw TypeError(`Unsupported compression format: '${e}'`)}}};exports.PonyfillDecompressionStream=r})),wi=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.PonyfillTextEncoderStream=exports.PonyfillTextDecoderStream=void 0;let t=vi(),n=xi();var r=class extends n.PonyfillTransformStream{textDecoder;constructor(e,n){super({transform:(e,t)=>t.enqueue(this.textDecoder.decode(e,{stream:!0}))}),this.textDecoder=new t.PonyfillTextDecoder(e,n)}get encoding(){return this.textDecoder.encoding}get fatal(){return this.textDecoder.fatal}get ignoreBOM(){return this.textDecoder.ignoreBOM}};exports.PonyfillTextDecoderStream=r;var i=class extends n.PonyfillTransformStream{textEncoder;constructor(e){super({transform:(e,t)=>t.enqueue(this.textEncoder.encode(e))}),this.textEncoder=new t.PonyfillTextEncoder(e)}get encoding(){return this.textEncoder.encoding}encode(e){return this.textEncoder.encode(e)}};exports.PonyfillTextEncoderStream=i})),Ti=e((exports=>{Object.defineProperty(exports,`__esModule`,{value:!0}),exports.TextEncoderStream=exports.TextDecoderStream=exports.IteratorObject=exports.DecompressionStream=exports.CompressionStream=exports.TransformStream=exports.WritableStream=exports.URLSearchParams=exports.URL=exports.btoa=exports.TextDecoder=exports.TextEncoder=exports.Blob=exports.FormData=exports.File=exports.ReadableStream=exports.Response=exports.Request=exports.Body=exports.Headers=exports.fetch=void 0;var t=_i();Object.defineProperty(exports,`fetch`,{enumerable:!0,get:function(){return t.fetchPonyfill}});var n=di();Object.defineProperty(exports,`Headers`,{enumerable:!0,get:function(){return n.PonyfillHeaders}});var r=ui();Object.defineProperty(exports,`Body`,{enumerable:!0,get:function(){return r.PonyfillBody}});var i=hi();Object.defineProperty(exports,`Request`,{enumerable:!0,get:function(){return i.PonyfillRequest}});var a=fi();Object.defineProperty(exports,`Response`,{enumerable:!0,get:function(){return a.PonyfillResponse}});var o=mr();Object.defineProperty(exports,`ReadableStream`,{enumerable:!0,get:function(){return o.PonyfillReadableStream}});var s=gr();Object.defineProperty(exports,`File`,{enumerable:!0,get:function(){return s.PonyfillFile}});var c=li();Object.defineProperty(exports,`FormData`,{enumerable:!0,get:function(){return c.PonyfillFormData}});var l=hr();Object.defineProperty(exports,`Blob`,{enumerable:!0,get:function(){return l.PonyfillBlob}});var u=vi();Object.defineProperty(exports,`TextEncoder`,{enumerable:!0,get:function(){return u.PonyfillTextEncoder}}),Object.defineProperty(exports,`TextDecoder`,{enumerable:!0,get:function(){return u.PonyfillTextDecoder}}),Object.defineProperty(exports,`btoa`,{enumerable:!0,get:function(){return u.PonyfillBtoa}});var d=mi();Object.defineProperty(exports,`URL`,{enumerable:!0,get:function(){return d.PonyfillURL}});var f=yi();Object.defineProperty(exports,`URLSearchParams`,{enumerable:!0,get:function(){return f.PonyfillURLSearchParams}});var p=bi();Object.defineProperty(exports,`WritableStream`,{enumerable:!0,get:function(){return p.PonyfillWritableStream}});var m=xi();Object.defineProperty(exports,`TransformStream`,{enumerable:!0,get:function(){return m.PonyfillTransformStream}});var h=Si();Object.defineProperty(exports,`CompressionStream`,{enumerable:!0,get:function(){return h.PonyfillCompressionStream}});var g=Ci();Object.defineProperty(exports,`DecompressionStream`,{enumerable:!0,get:function(){return g.PonyfillDecompressionStream}});var _=ci();Object.defineProperty(exports,`IteratorObject`,{enumerable:!0,get:function(){return _.PonyfillIteratorObject}});var v=wi();Object.defineProperty(exports,`TextDecoderStream`,{enumerable:!0,get:function(){return v.PonyfillTextDecoderStream}}),Object.defineProperty(exports,`TextEncoderStream`,{enumerable:!0,get:function(){return v.PonyfillTextEncoderStream}})})),Ei=e(((exports,t)=>{let n=Zn(),r;t.exports=function(e={}){let t={};if(t.URLPattern=globalThis.URLPattern,!t.URLPattern){let e=$n();t.URLPattern=e.URLPattern}if(e.skipPonyfill||n())return{fetch:globalThis.fetch,Headers:globalThis.Headers,Request:globalThis.Request,Response:globalThis.Response,FormData:globalThis.FormData,ReadableStream:globalThis.ReadableStream,WritableStream:globalThis.WritableStream,TransformStream:globalThis.TransformStream,CompressionStream:globalThis.CompressionStream,DecompressionStream:globalThis.DecompressionStream,TextDecoderStream:globalThis.TextDecoderStream,TextEncoderStream:globalThis.TextEncoderStream,Blob:globalThis.Blob,File:globalThis.File,crypto:globalThis.crypto,btoa:globalThis.btoa,TextEncoder:globalThis.TextEncoder,TextDecoder:globalThis.TextDecoder,URLPattern:t.URLPattern,URL:globalThis.URL,URLSearchParams:globalThis.URLSearchParams};if(r||=Ti(),t.fetch=r.fetch,t.Request=r.Request,t.Response=r.Response,t.Headers=r.Headers,t.FormData=r.FormData,t.ReadableStream=r.ReadableStream,t.URL=r.URL,t.URLSearchParams=r.URLSearchParams,t.WritableStream=r.WritableStream,t.TransformStream=r.TransformStream,t.CompressionStream=r.CompressionStream,t.DecompressionStream=r.DecompressionStream,t.TextDecoderStream=r.TextDecoderStream,t.TextEncoderStream=r.TextEncoderStream,t.Blob=r.Blob,t.File=r.File,t.crypto=globalThis.crypto,t.btoa=r.btoa,t.TextEncoder=r.TextEncoder,t.TextDecoder=r.TextDecoder,e.formDataLimits&&(t.Body=class extends r.Body{constructor(t,n){super(t,{formDataLimits:e.formDataLimits,...n})}},t.Request=class extends r.Request{constructor(t,n){super(t,{formDataLimits:e.formDataLimits,...n})}},t.Response=class extends r.Response{constructor(t,n){super(t,{formDataLimits:e.formDataLimits,...n})}}),!t.crypto){let e=i(`crypto`);t.crypto=e.webcrypto}return t}})),Di=e(((exports,t)=>{let n=Ei(),r=Zn(),a=n();if(!r())try{globalThis.libcurl=globalThis.libcurl||i(`node-libcurl`)}catch{}t.exports.fetch=a.fetch,t.exports.Headers=a.Headers,t.exports.Request=a.Request,t.exports.Response=a.Response,t.exports.FormData=a.FormData,t.exports.ReadableStream=a.ReadableStream,t.exports.WritableStream=a.WritableStream,t.exports.TransformStream=a.TransformStream,t.exports.CompressionStream=a.CompressionStream,t.exports.DecompressionStream=a.DecompressionStream,t.exports.TextDecoderStream=a.TextDecoderStream,t.exports.TextEncoderStream=a.TextEncoderStream,t.exports.Blob=a.Blob,t.exports.File=a.File,t.exports.crypto=a.crypto,t.exports.btoa=a.btoa,t.exports.TextEncoder=a.TextEncoder,t.exports.TextDecoder=a.TextDecoder,t.exports.URLPattern=a.URLPattern,t.exports.URL=a.URL,t.exports.URLSearchParams=a.URLSearchParams,exports.createFetch=n}));function Oi(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}function ki(e){if(e.socket?.localPort)return e.socket?.localPort;let t=e.headers?.[`:authority`]||e.headers?.host,n=t?.split(`:`)?.[1];return n||80}function Ai(e){if(e.headers?.[`:authority`])return e.headers?.[`:authority`];if(e.headers?.host)return e.headers?.host;let t=ki(e);if(e.hostname)return e.hostname+`:`+t;let n=e.socket?.localAddress;return n&&!n?.includes(`::`)&&!n?.includes(`ffff`)?`${n}:${t}`:`localhost`}function ji(e){let t=Ai(e),n=e.protocol||(e.socket?.encrypted?`https`:`http`),r=e.originalUrl||e.url||`/graphql`;return`${n}://${t}${r}`}function Mi(e){let t=e[Symbol.toStringTag];return!!(typeof e==`string`||t===`Uint8Array`||t===`Blob`||t===`FormData`||t===`URLSearchParams`||Oi(e))}function Ni(e,t,n,r){let i=e.raw||e.req||e,a=ji(i);if(e.query){let n=new t.URL(a);for(let t in e.query)n.searchParams.set(t,e.query[t]);a=n.toString()}let o=e.headers;if(e.headers?.[`:method`])for(let t in o={},e.headers)t.startsWith(`:`)||(o[t]=e.headers[t]);let s=r?na():new AbortController;if(n?.once){let e=()=>{s.signal.aborted||(Object.defineProperty(i,`aborted`,{value:!0}),s.abort(n.errored??void 0))};n.once(`error`,e),n.once(`close`,e),n.once(`finish`,()=>{n.removeListener(`close`,e)})}if(e.method===`GET`||e.method===`HEAD`)return new t.Request(a,{method:e.method,headers:o,signal:s.signal});let c=e.body;if(c!=null&&Object.keys(c).length>0){if(Mi(c))return new t.Request(a,{method:e.method||`GET`,headers:o,body:c,signal:s.signal});let n=new t.Request(a,{method:e.method||`GET`,headers:o,signal:s.signal});return n.headers.get(`content-type`)?.includes(`json`)||n.headers.set(`content-type`,`application/json; charset=utf-8`),new Proxy(n,{get:(e,t,n)=>{switch(t){case`json`:return()=>Pn(c);case`text`:return()=>Pn(JSON.stringify(c));default:return globalThis.Bun?Reflect.get(e,t):Reflect.get(e,t,n)}}})}return new t.Request(a,{method:e.method,headers:o,signal:s.signal,body:i,duplex:`half`})}function Pi(e){return e.read!=null}function Fi(e){return Pi(e)}function Ii(e){return e!=null&&e.setHeader!=null&&e.end!=null&&e.once!=null&&e.write!=null}function Li(e){return e!=null&&e.getReader!=null}function Ri(e){return e!=null&&e.request!=null&&e.respondWith!=null}function zi(e){e?.socket?.setTimeout?.(0),e?.socket?.setNoDelay?.(!0),e?.socket?.setKeepAlive?.(!0)}function Bi(e){e.end(null,null,null)}function Vi(e,t){let n=!1,r=()=>{n=!0};e.once(`error`,r),e.once(`close`,r),e.once(`finish`,()=>{e.removeListener(`close`,r),e.removeListener(`error`,r)});let i=t[Symbol.asyncIterator](),a=()=>i.next().then(({done:t,value:r})=>{if(!(n||t))return Nn(()=>Hi(r,e),()=>n?Bi(e):a())});return a()}function Hi(e,t){let n=t.write(e);if(!n)return new Promise(e=>t.once(`drain`,e))}function Ui(e,t,n,r){if(t.closed||t.destroyed||t.writableEnded)return;if(!e){t.statusCode=404,Bi(t);return}if(r&&e.headers?.headersInit&&!Array.isArray(e.headers.headersInit)&&!e.headers.headersInit.get&&!e.headers._map&&!e.headers._setCookies?.length)t.writeHead(e.status,e.statusText,e.headers.headersInit);else{if(t.setHeaders)t.setHeaders(e.headers);else{let n=!1;e.headers.forEach((r,i)=>{if(i===`set-cookie`){if(n)return;n=!0;let r=e.headers.getSetCookie?.();if(r){t.setHeader(`set-cookie`,r);return}}t.setHeader(i,r)})}t.writeHead(e.status,e.statusText)}if(e.bodyType===`String`)return Nn(()=>Hi(e.bodyInit,t),()=>Bi(t));let i=e._buffer;if(i)return Nn(()=>Hi(i,t),()=>Bi(t));let a=e.body;if(a==null){Bi(t);return}if(a[Symbol.toStringTag]===`Uint8Array`)return Nn(()=>Hi(a,t),()=>Bi(t));if(zi(n),Pi(a)){t.once(`close`,()=>{a.destroy()}),a.pipe(t,{end:!0});return}if(Li(a))return Wi(n,t,a);if(Oi(a))return Vi(t,a)}function Wi(e,t,n){let r=n.getReader();e?.once?.(`error`,e=>{r.cancel(e)});function i(){return r.read().then(({done:e,value:n})=>e?Bi(t):Nn(()=>Hi(n,t),i))}return i()}function Gi(e){return typeof e==`object`&&!!e&&(`body`in e||`cache`in e||`credentials`in e||`headers`in e||`integrity`in e||`keepalive`in e||`method`in e||`mode`in e||`redirect`in e||`referrer`in e||`referrerPolicy`in e||`signal`in e||`window`in e)}function Ki(...e){let[t,...n]=e.filter(e=>typeof e==`object`&&!!e);return n.forEach(e=>{let n=Object.getOwnPropertyNames(e).reduce((t,n)=>{let r=Object.getOwnPropertyDescriptor(e,n);return r&&(t[n]=Object.getOwnPropertyDescriptor(e,n)),t},{});Object.getOwnPropertySymbols(e).forEach(t=>{let r=Object.getOwnPropertyDescriptor(e,t);r?.enumerable&&(n[t]=r)}),Object.defineProperties(t,n)}),t}function qi(e,t){return new t(e.stack||e.message||e.toString(),{status:e.status||500})}function Ji(e,t){return e==null?t==null?{}:{waitUntil:t}:Ki(Object.create(e),{waitUntil:t},e)}function Yi(e,t){if(t?.aborted)throw t.reason;if(jn(e)&&t){let n=Fn();function r(){n.reject(t.reason)}return t.addEventListener(`abort`,r,{once:!0}),e.then(function(e){n.resolve(e)}).catch(function(e){n.reject(e)}).finally(()=>{t.removeEventListener(`abort`,r)}),n.promise}return e}const Xi=[`SIGINT`,`exit`,`SIGTERM`],Zi=new Set;let Qi=!1;function $i(){if(!Qi){Qi=!0;for(let e of Xi)globalThis.process.once(e,function(){return Promise.allSettled([...Zi].map(e=>!e.disposed&&e.disposeAsync()))})}}function ea(e){globalThis.process&&($i(),Zi.has(e)||(Zi.add(e),e.defer(()=>{Zi.delete(e)})))}var ta=class extends EventTarget{aborted=!1;_onabort=null;_reason;constructor(){super();let e=globalThis.process?.getBuiltinModule?.(`node:events`);e?.kMaxEventTargetListeners&&(this[e.kMaxEventTargetListeners]=0)}throwIfAborted(){if(this._nativeCtrl?.signal?.throwIfAborted)return this._nativeCtrl.signal.throwIfAborted();if(this.aborted)throw this._reason}_nativeCtrl;ensureNativeCtrl(){if(!this._nativeCtrl){let e=this.aborted;this._nativeCtrl=new AbortController,e&&this._nativeCtrl.abort(this._reason)}return this._nativeCtrl}abort(e){if(this._nativeCtrl?.abort)return this._nativeCtrl?.abort(e);this._reason=e||new DOMException(`This operation was aborted`,`AbortError`),this.aborted=!0,this.dispatchEvent(new Event(`abort`))}get signal(){return this._nativeCtrl?.signal?this._nativeCtrl.signal:this}get reason(){return this._nativeCtrl?.signal?this._nativeCtrl.signal.reason:this._reason}get onabort(){return this._onabort,this._onabort}set onabort(e){if(this._nativeCtrl?.signal){this._nativeCtrl.signal.onabort=e;return}this._onabort&&this.removeEventListener(`abort`,this._onabort),this._onabort=e,e&&this.addEventListener(`abort`,e)}};function na(){return globalThis.Bun||globalThis.Deno?new AbortController:new Proxy(new ta,{get(e,t,n){if(t.toString().includes(`kDependantSignals`)){let n=e.ensureNativeCtrl();return Reflect.get(n.signal,t,n.signal)}return Reflect.get(e,t,n)},set(e,t,n,r){if(t.toString().includes(`kDependantSignals`)){let r=e.ensureNativeCtrl();return Reflect.set(r.signal,t,n,r.signal)}return Reflect.set(e,t,n,r)},getPrototypeOf(){return AbortSignal.prototype}})}function ra(e){return!!e.onData}function ia({req:e,res:t,fetchAPI:n,controller:r}){let i=e.getMethod(),a,o=[],s=[e=>{o.push(e)}],c=e=>{for(let t of s)t(e)},l=!1,u=[()=>{l=!0}],d=()=>{for(let e of u)e()};t.onData(function(e,t){c(Buffer.from(Buffer.from(e,0,e.byteLength))),t&&d()});let f;if(i!==`get`&&i!==`head`){a=`half`,r.signal.addEventListener(`abort`,()=>{d()},{once:!0});let e;f=()=>(e||=new n.ReadableStream({start(e){for(let t of o)e.enqueue(t);if(l){e.close();return}s.push(t=>{e.enqueue(t)}),u.push(()=>{if(r.signal.reason){e.error(r.signal.reason);return}e.desiredSize&&e.close()})}}),e)}let p=new n.Headers;e.forEach((e,t)=>{p.append(e,t)});let m=`http://localhost${e.getUrl()}`,h=e.getQuery();h&&(m+=`?${h}`);let g;function _(){return f?l?y():f():null}let v=new n.Request(m,{method:i,headers:p,get body(){return _()},signal:r.signal,duplex:a});function y(){return g||=o.length===1?o[0]:Buffer.concat(o),g}function b(){return l?Pn(y()):new Promise((e,t)=>{try{u.push(()=>{e(y())})}catch(e){t(e)}})}return Object.defineProperties(v,{body:{get(){return _()},configurable:!0,enumerable:!0},json:{value(){return b().then(e=>e.toString(`utf8`)).then(e=>JSON.parse(e))},configurable:!0,enumerable:!0},text:{value(){return b().then(e=>e.toString(`utf8`))},configurable:!0,enumerable:!0},arrayBuffer:{value(){return b()},configurable:!0,enumerable:!0}}),v}function aa(e,t){return new t.WritableStream({write(t){e.cork(()=>{e.write(t)})},close(){e.cork(()=>{e.end()})}})}function oa(e,t,n,r){if(!t){e.writeStatus(`404 Not Found`),e.end();return}let i=t._buffer,a=t.bodyType===`String`?t.bodyInit:void 0;if(!n.signal.aborted&&(e.cork(()=>{e.writeStatus(`${t.status} ${t.statusText}`);for(let[n,r]of t.headers)if(n!==`content-length`){if(n===`set-cookie`){let r=t.headers.getSetCookie?.();if(r){for(let t of r)e.writeHeader(n,t);continue}}e.writeHeader(n,r)}a?e.end(a):i?e.end(i):t.body||e.end()}),!(a||i||!t.body)))return n.signal.addEventListener(`abort`,()=>{t.body?.locked||t.body?.cancel(n.signal.reason)},{once:!0}),t.body.pipeTo(aa(e,r),{signal:n.signal}).catch(e=>{if(!n.signal.aborted)throw e})}var sa=o(Di(),1);function ca(e){try{return!!e?.request}catch{return!1}}const la={};function ua(e,t){let n=t?.__useSingleWriteHead==null?!0:t.__useSingleWriteHead,r={...sa,...t?.fetchAPI},i=t?.__useCustomAbortCtrl==null?r.Request!==globalThis.Request:t.__useCustomAbortCtrl,a=typeof e==`function`?e:e.handle,o=[],s=[],c,l=new Set,u;function d(){return u||(u=new Xn,t?.disposeOnProcessTerminate&&ea(u),u.defer(()=>{if(l.size>0)return Promise.allSettled(l).then(()=>{l.clear()},()=>{l.clear()})})),u}function f(e){jn(e)&&(d(),l.add(e),e.then(()=>{l.delete(e)},t=>{console.error(`Unexpected error while waiting: ${t.message||t}`),l.delete(e)}))}if(t?.plugins!=null)for(let e of t.plugins){e.instrumentation&&(c=c?Hn(c,e.instrumentation):e.instrumentation),e.onRequest&&o.push(e.onRequest),e.onResponse&&s.push(e.onResponse);let t=e[Gn.dispose];t&&d().defer(t);let n=e[Gn.asyncDispose];n&&d().defer(n),e.onDispose&&d().defer(e.onDispose)}let p=o.length>0||s.length>0?function(e,t){let n=a,i;if(o.length===0)return u();let c=e.parsedUrl||new Proxy(la,{get(t,n,i){return c=new r.URL(e.url,`http://localhost`),Reflect.get(c,n,c)}});function l(n){return s.length===0?n:Nn(()=>In(s,i=>i({request:e,response:n,serverContext:t,setResponse(e){n=e},fetchAPI:r})),()=>n)}function u(){return i?l(i):Nn(()=>n(e,t),l)}return Nn(()=>In(o,(a,o)=>a({request:e,setRequest(t){e=t},serverContext:t,fetchAPI:r,url:c,requestHandler:n,setRequestHandler(e){n=e},endResponse(e){i=e,e&&o()}})),u)}:a;if(c?.request){let e=p;p=(t,n)=>Un({request:t}).asyncFn(c.request,e)(t,n)}function m(e,...t){let n=t.length>1?Ki(...t):t[0]||{};n.waitUntil||=f;let a=Ni(e,r,void 0,i);return p(a,n)}function h(e,t,...n){let a=t.raw||t,o=n.length>1?Ki(...n):n[0]||{};o.waitUntil||=f;let s=Ni(e,r,a,i);return p(s,o)}function g(e,t,...i){let a={req:e,res:t,waitUntil:f};return Vn(Pn().then(()=>h(e,t,a,...i)).catch(e=>qi(e,r.Response)).then(r=>Ui(r,t,e,n)).catch(e=>console.error(`Unexpected error while handling request: ${e.message||e}`)))}function _(e,t,...n){let a={res:e,req:t,waitUntil:f},o=n.filter(e=>e!=null),s=o.length>0?Ki(a,...n):a,c=i?na():new AbortController,l=e.end.bind(e),u=!1;e.end=function(e){return u=!0,l(e)};let d=e.onAborted.bind(e);d(function(){c.abort()}),e.onAborted=function(e){c.signal.addEventListener(`abort`,e,{once:!0})};let m=ia({req:t,res:e,fetchAPI:r,controller:c});return Nn(()=>Nn(()=>p(m,s),e=>e,e=>qi(e,r.Response)),t=>{if(!c.signal.aborted&&!u)return Nn(()=>oa(e,t,c,r),e=>e,e=>{console.error(`Unexpected error while handling request: ${e.message||e}`)})})}function v(e,...t){if(!e.respondWith||!e.request)throw TypeError(`Expected FetchEvent, got ${e}`);let n=t.filter(e=>e!=null),r=n.length>0?Ki({},e,...n):Ji(e),i=p(e.request,r);e.respondWith(i)}function y(e,...t){let n=t.filter(e=>e!=null),r=n.length>1?Ki({},...n):Ji(n[0],n[0]==null||n[0].waitUntil==null?f:void 0);return p(e,r)}let b=(e,...t)=>{if(typeof e==`string`||`href`in e){let[n,...i]=t;if(Gi(n)){let t=new r.Request(e,n),a=y(t,...i),o=n.signal;return o?Yi(a,o):a}let a=new r.Request(e);return y(a,...t)}let n=y(e,...t);return Yi(n,e.signal)},x=(e,...t)=>{let[n,...r]=t;if(Fi(e)){if(!Ii(n))throw TypeError(`Expected ServerResponse, got ${n}`);return g(e,n,...r)}if(ra(e))return _(e,n,...r);if(Ii(n))throw TypeError(`Got Node response without Node request`);return ca(e)?Ri(e)?v(e,...t):y(e.request,e,...t):b(e,...t)},S={handleRequest:y,fetch:b,handleNodeRequest:m,handleNodeRequestAndResponse:h,requestListener:g,handleEvent:v,handleUWS:_,handle:x,get disposableStack(){return d()},[Gn.asyncDispose](){return u&&!u.disposed?u.disposeAsync():Pn()},dispose(){return u&&!u.disposed?u.disposeAsync():Pn()},waitUntil:f},C=new Proxy(x,{has:(t,n)=>n in S||n in x||e&&n in e,get:(t,n)=>{if(globalThis.Deno||n===Symbol.asyncDispose||n===Symbol.dispose){let e=Reflect.get(S,n,S);if(e)return e}let r=S[n];if(r)return r.bind?r.bind(S):r;let i=x[n];if(i)return i.bind?i.bind(x):i;if(e){let t=e[n];if(t)return t.bind?function(...t){let r=e[n](...t);return r===e?C:r}:t}},apply(e,t,n){return x(...n)}});return C}function da(e){let t=i(e);if(typeof t!=`object`)throw Error(`The module at ${e} must export an object.`);let n=t.default;if(typeof n!=`object`)throw Error(`The module at ${e} must export an object.`);if(!n.version)throw Error(`The module at ${e} must export a "version" property.`);if(typeof n.fetch!=`function`)throw Error(`The module at ${e} must export a "fetch" function.`);return n}function fa(e){return ua(e.fetch)}function pa(e){return new ma(e)}var ma=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/_agent/send-messages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendRequest(e){let t=new URL(e.url),n=new Headers(e.headers),r=new URL(this.baseUrl);if(r.pathname=t.pathname,r.search=t.search,t.pathname.startsWith(`/_agent/`))throw Error(`The pathname "/_agent/" is reserved for agent-specific requests.`);return this.fetch(r,{method:e.method,headers:n,body:e.body,duplex:e.body?`half`:void 0})}},ha=`vercel.ai.error`,ga=Symbol.for(ha),_a,va=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[_a]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,ha)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};_a=ga;var G=va,ya=`AI_APICallError`,ba=`vercel.ai.error.${ya}`,xa=Symbol.for(ba),Sa,Ca=class extends G{constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:i,responseBody:a,cause:o,isRetryable:s=r!=null&&(r===408||r===409||r===429||r>=500),data:c}){super({name:ya,message:e,cause:o}),this[Sa]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=i,this.responseBody=a,this.isRetryable=s,this.data=c}static isInstance(e){return G.hasMarker(e,ba)}};Sa=xa;var wa=`AI_EmptyResponseBodyError`,Ta=`vercel.ai.error.${wa}`,Ea=Symbol.for(Ta),Da,Oa=class extends G{constructor({message:e=`Empty response body`}={}){super({name:wa,message:e}),this[Da]=!0}static isInstance(e){return G.hasMarker(e,Ta)}};Da=Ea;function ka(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var Aa=`AI_InvalidArgumentError`,ja=`vercel.ai.error.${Aa}`,Ma=Symbol.for(ja),Na,Pa=class extends G{constructor({message:e,cause:t,argument:n}){super({name:Aa,message:e,cause:t}),this[Na]=!0,this.argument=n}static isInstance(e){return G.hasMarker(e,ja)}};Na=Ma;var Fa=`AI_InvalidPromptError`,Ia=`vercel.ai.error.${Fa}`,La=Symbol.for(Ia),Ra,za=class extends G{constructor({prompt:e,message:t,cause:n}){super({name:Fa,message:`Invalid prompt: ${t}`,cause:n}),this[Ra]=!0,this.prompt=e}static isInstance(e){return G.hasMarker(e,Ia)}};Ra=La;var Ba=`AI_InvalidResponseDataError`,Va=`vercel.ai.error.${Ba}`,Ha=Symbol.for(Va),Ua,Wa=class extends G{constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:Ba,message:t}),this[Ua]=!0,this.data=e}static isInstance(e){return G.hasMarker(e,Va)}};Ua=Ha;var Ga=`AI_JSONParseError`,Ka=`vercel.ai.error.${Ga}`,qa=Symbol.for(Ka),Ja,Ya=class extends G{constructor({text:e,cause:t}){super({name:Ga,message:`JSON parsing failed: Text: ${e}.
|
|
56
|
+
Error message: ${ka(t)}`,cause:t}),this[Ja]=!0,this.text=e}static isInstance(e){return G.hasMarker(e,Ka)}};Ja=qa;var Xa=`AI_LoadAPIKeyError`,Za=`vercel.ai.error.${Xa}`,Qa=Symbol.for(Za),$a,eo=class extends G{constructor({message:e}){super({name:Xa,message:e}),this[$a]=!0}static isInstance(e){return G.hasMarker(e,Za)}};$a=Qa;var to=`AI_LoadSettingError`,no=`vercel.ai.error.${to}`,ro=Symbol.for(no),io;io=ro;var ao=`AI_NoContentGeneratedError`,oo=`vercel.ai.error.${ao}`,so=Symbol.for(oo),co;co=so;var lo=`AI_NoSuchModelError`,uo=`vercel.ai.error.${lo}`,fo=Symbol.for(uo),po,mo=class extends G{constructor({errorName:e=lo,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[po]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return G.hasMarker(e,uo)}};po=fo;var ho=`AI_TooManyEmbeddingValuesForCallError`,go=`vercel.ai.error.${ho}`,_o=Symbol.for(go),vo,yo=class extends G{constructor(e){super({name:ho,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[vo]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return G.hasMarker(e,go)}};vo=_o;var bo=`AI_TypeValidationError`,xo=`vercel.ai.error.${bo}`,So=Symbol.for(xo),Co,wo=class e extends G{constructor({value:e,cause:t}){super({name:bo,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
57
|
+
Error message: ${ka(t)}`,cause:t}),this[Co]=!0,this.value=e}static isInstance(e){return G.hasMarker(e,xo)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};Co=So;var To=wo,Eo=`AI_UnsupportedFunctionalityError`,Do=`vercel.ai.error.${Eo}`,Oo=Symbol.for(Do),ko,Ao=class extends G{constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Eo,message:t}),this[ko]=!0,this.functionality=e}static isInstance(e){return G.hasMarker(e,Do)}};ko=Oo;var jo=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}};function Mo(e){}function No(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Mo,onError:n=Mo,onRetry:r=Mo,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=Po(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
58
|
+
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new jo(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new jo(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
59
|
+
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function Po(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
60
|
+
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
61
|
+
`&&r++}}return[t,n]}var Fo=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=No({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};function Io(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}async function Lo(e,t){if(e==null)return Promise.resolve();let n=t?.abortSignal;return new Promise((t,r)=>{if(n?.aborted){r(Ro());return}let i=setTimeout(()=>{a(),t()},e),a=()=>{clearTimeout(i),n?.removeEventListener(`abort`,o)},o=()=>{a(),r(Ro())};n?.addEventListener(`abort`,o)})}function Ro(){return new DOMException(`Delay was aborted`,`AbortError`)}function zo(e){return Object.fromEntries([...e.headers])}var Bo=({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new Pa({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`},Vo=Bo();function Ho(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}function Uo(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var Wo=[`fetch failed`,`failed to fetch`];function Go({error:e,url:t,requestBodyValues:n}){if(Uo(e))return e;if(e instanceof TypeError&&Wo.includes(e.message.toLowerCase())){let r=e.cause;if(r!=null)return new Ca({message:`Cannot connect to API: ${r.message}`,cause:r,url:t,requestBodyValues:n,isRetryable:!0})}return e}function Ko(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>t!=null))}var qo=()=>globalThis.fetch,Jo=async({url:e,headers:t={},successfulResponseHandler:n,failedResponseHandler:r,abortSignal:i,fetch:a=qo()})=>{try{let o=await a(e,{method:`GET`,headers:Ko(t),signal:i}),s=zo(o);if(!o.ok){let t;try{t=await r({response:o,url:e,requestBodyValues:{}})}catch(t){throw Uo(t)||Ca.isInstance(t)?t:new Ca({message:`Failed to process error response`,cause:t,statusCode:o.status,url:e,responseHeaders:s,requestBodyValues:{}})}throw t.value}try{return await n({response:o,url:e,requestBodyValues:{}})}catch(t){throw t instanceof Error&&(Uo(t)||Ca.isInstance(t))?t:new Ca({message:`Failed to process successful response`,cause:t,statusCode:o.status,url:e,responseHeaders:s,requestBodyValues:{}})}}catch(t){throw Go({error:t,url:e,requestBodyValues:{}})}};function Yo({mediaType:e,url:t,supportedUrls:n}){return t=t.toLowerCase(),e=e.toLowerCase(),Object.entries(n).map(([e,t])=>{let n=e.toLowerCase();return n===`*`||n===`*/*`?{mediaTypePrefix:``,regexes:t}:{mediaTypePrefix:n.replace(/\*/,``),regexes:t}}).filter(({mediaTypePrefix:t})=>e.startsWith(t)).flatMap(({regexes:e})=>e).some(e=>e.test(t))}function Xo({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new eo({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new eo({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new eo({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new eo({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function Zo({settingValue:e,environmentVariableName:t}){if(typeof e==`string`||!(e!=null||typeof process>`u`)&&(e=process.env[t],!(e==null||typeof e!=`string`)))return e}function Qo(e){var t;let[n,r=``]=e.toLowerCase().split(`/`);return(t={mpeg:`mp3`,"x-wav":`wav`,opus:`ogg`,mp4:`m4a`,"x-m4a":`m4a`}[r])??r}var $o=/"__proto__"\s*:/,es=/"constructor"\s*:/;function ts(e){let t=JSON.parse(e);return typeof t!=`object`||!t||$o.test(e)===!1&&es.test(e)===!1?t:ns(t)}function ns(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function rs(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return ts(e)}finally{Error.stackTraceLimit=t}}var os=Symbol.for(`vercel.ai.validator`);function ss(e){return{[os]:!0,validate:e}}function cs(e){return typeof e==`object`&&!!e&&os in e&&e[os]===!0&&`validate`in e}function ls(e){return cs(e)?e:us(e)}function us(e){return ss(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new To({value:t,cause:n.issues})}})}async function ds({value:e,schema:t}){let n=await fs({value:e,schema:t});if(!n.success)throw To.wrap({value:e,cause:n.error});return n.value}async function fs({value:e,schema:t}){let n=ls(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:To.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:To.wrap({value:e,cause:t}),rawValue:e}}}async function ps({text:e,schema:t}){try{let n=rs(e);return t==null?n:ds({value:n,schema:t})}catch(t){throw Ya.isInstance(t)||To.isInstance(t)?t:new Ya({text:e,cause:t})}}async function ms({text:e,schema:t}){try{let n=rs(e);return t==null?{success:!0,value:n,rawValue:n}:await fs({value:n,schema:t})}catch(t){return{success:!1,error:Ya.isInstance(t)?t:new Ya({text:e,cause:t}),rawValue:void 0}}}function hs(e){try{return rs(e),!0}catch{return!1}}function gs({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Fo).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await ms({text:e,schema:t}))}}))}async function _s({provider:e,providerOptions:t,schema:n}){if(t?.[e]==null)return;let r=await fs({value:t[e],schema:n});if(!r.success)throw new Pa({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:r.error});return r.value}var vs=()=>globalThis.fetch,K=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>bs({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),ys=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>bs({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),bs=async({url:e,headers:t={},body:n,successfulResponseHandler:r,failedResponseHandler:i,abortSignal:a,fetch:o=vs()})=>{try{let s=await o(e,{method:`POST`,headers:Ko(t),body:n.content,signal:a}),c=zo(s);if(!s.ok){let t;try{t=await i({response:s,url:e,requestBodyValues:n.values})}catch(t){throw Uo(t)||Ca.isInstance(t)?t:new Ca({message:`Failed to process error response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}throw t.value}try{return await r({response:s,url:e,requestBodyValues:n.values})}catch(t){throw t instanceof Error&&(Uo(t)||Ca.isInstance(t))?t:new Ca({message:`Failed to process successful response`,cause:t,statusCode:s.status,url:e,responseHeaders:c,requestBodyValues:n.values})}}catch(t){throw Go({error:t,url:e,requestBodyValues:n.values})}};function xs(e){return e}function Ss({id:e,name:t,inputSchema:n}){return({execute:r,outputSchema:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>xs({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:i,execute:r,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function Cs({id:e,name:t,inputSchema:n,outputSchema:r}){return({execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>xs({type:`provider-defined`,id:e,name:t,args:l,inputSchema:n,outputSchema:r,execute:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function ws(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var Ts=({errorSchema:e,errorToMessage:t,isRetryable:n})=>async({response:r,url:i,requestBodyValues:a})=>{let o=await r.text(),s=zo(r);if(o.trim()===``)return{responseHeaders:s,value:new Ca({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})};try{let c=await ps({text:o,schema:e});return{responseHeaders:s,value:new Ca({message:t(c),url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,data:c,isRetryable:n?.(r,c)})}}catch{return{responseHeaders:s,value:new Ca({message:r.statusText,url:i,requestBodyValues:a,statusCode:r.status,responseHeaders:s,responseBody:o,isRetryable:n?.(r)})}}},Es=e=>async({response:t})=>{let n=zo(t);if(t.body==null)throw new Oa({});return{responseHeaders:n,value:gs({stream:t.body,schema:e})}},Ds=e=>async({response:t,url:n,requestBodyValues:r})=>{let i=await t.text(),a=await ms({text:i,schema:e}),o=zo(t);if(!a.success)throw new Ca({message:`Invalid JSON response`,cause:a.error,statusCode:t.status,responseHeaders:o,responseBody:i,url:n,requestBodyValues:r});return{responseHeaders:o,value:a.value,rawValue:a.rawValue}},Os=()=>async({response:e,url:t,requestBodyValues:n})=>{let r=zo(e);if(!e.body)throw new Ca({message:`Response body is empty`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0});try{let t=await e.arrayBuffer();return{responseHeaders:r,value:new Uint8Array(t)}}catch(i){throw new Ca({message:`Failed to read response as array buffer`,url:t,requestBodyValues:n,statusCode:e.status,responseHeaders:r,responseBody:void 0,cause:i})}},ks=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)},As=Symbol(`Let zodToJsonSchema decide on which parser to use`),js={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`},Ms=e=>typeof e==`string`?{...js,name:e}:{...js,...e};function Ns(){return{}}function Ps(e,t){var n,r,i;let a={type:`array`};return(n=e.type)?._def&&(i=(r=e.type)?._def)?.typeName!==H.ZodAny&&(a.items=q(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&(a.minItems=e.minLength.value),e.maxLength&&(a.maxItems=e.maxLength.value),e.exactLength&&(a.minItems=e.exactLength.value,a.maxItems=e.exactLength.value),a}function Fs(e){let t={type:`integer`,format:`int64`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function Is(){return{type:`boolean`}}function Ls(e,t){return q(e.type._def,t)}var Rs=(e,t)=>q(e.innerType._def,t);function zs(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>zs(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Bs(e)}}var Bs=e=>{let t={type:`integer`,format:`unix-time`};for(let n of e.checks)switch(n.kind){case`min`:t.minimum=n.value;break;case`max`:t.maximum=n.value;break}return t};function Vs(e,t){return{...q(e.innerType._def,t),default:e.defaultValue()}}function Hs(e,t){return t.effectStrategy===`input`?q(e.schema._def,t):Ns()}function Us(e){return{type:`string`,enum:Array.from(e.values)}}var Ws=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Gs(e,t){let n=[q(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),q(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=[];return n.forEach(e=>{if(Ws(e))r.push(...e.allOf);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}r.push(t)}}),r.length?{allOf:r}:void 0}function Ks(e){let t=typeof e.value;return t!==`bigint`&&t!==`number`&&t!==`boolean`&&t!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:{type:t===`bigint`?`integer`:t,const:e.value}}var qs=void 0,Js={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(qs===void 0&&(qs=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),qs),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ys(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value;break;case`max`:n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`email`:switch(t.emailStrategy){case`format:email`:$s(n,`email`,r.message,t);break;case`format:idn-email`:$s(n,`idn-email`,r.message,t);break;case`pattern:zod`:ec(n,Js.email,r.message,t);break}break;case`url`:$s(n,`uri`,r.message,t);break;case`uuid`:$s(n,`uuid`,r.message,t);break;case`regex`:ec(n,r.regex,r.message,t);break;case`cuid`:ec(n,Js.cuid,r.message,t);break;case`cuid2`:ec(n,Js.cuid2,r.message,t);break;case`startsWith`:ec(n,RegExp(`^${Xs(r.value,t)}`),r.message,t);break;case`endsWith`:ec(n,RegExp(`${Xs(r.value,t)}$`),r.message,t);break;case`datetime`:$s(n,`date-time`,r.message,t);break;case`date`:$s(n,`date`,r.message,t);break;case`time`:$s(n,`time`,r.message,t);break;case`duration`:$s(n,`duration`,r.message,t);break;case`length`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`includes`:ec(n,RegExp(Xs(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&$s(n,`ipv4`,r.message,t),r.version!==`v4`&&$s(n,`ipv6`,r.message,t);break;case`base64url`:ec(n,Js.base64url,r.message,t);break;case`jwt`:ec(n,Js.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&ec(n,Js.ipv4Cidr,r.message,t),r.version!==`v4`&&ec(n,Js.ipv6Cidr,r.message,t);break;case`emoji`:ec(n,Js.emoji(),r.message,t);break;case`ulid`:ec(n,Js.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:$s(n,`binary`,r.message,t);break;case`contentEncoding:base64`:n.contentEncoding=`base64`;break;case`pattern:zod`:ec(n,Js.base64,r.message,t);break}break;case`nanoid`:ec(n,Js.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}function Xs(e,t){return t.patternStrategy===`escape`?Qs(e):e}var Zs=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Qs(e){let t=``;for(let n=0;n<e.length;n++)Zs.has(e[n])||(t+=`\\`),t+=e[n];return t}function $s(e,t,n,r){var i;e.format||(i=e.anyOf)?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function ec(e,t,n,r){var i;e.pattern||(i=e.allOf)?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:tc(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=tc(t,r)}function tc(e,t){var n;if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},i=r.i?e.source.toLowerCase():e.source,a=``,o=!1,s=!1,c=!1;for(let e=0;e<i.length;e++){if(o){a+=i[e],o=!1;continue}if(r.i){if(s){if(i[e].match(/[a-z]/)){c?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),c=!1):i[e+1]===`-`&&(n=i[e+2])?.match(/[a-z]/)?(a+=i[e],c=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}}if(r.m){if(i[e]===`^`){a+=`(^|(?<=[\r
|
|
62
|
+
]))`;continue}else if(i[e]===`$`){a+=`($|(?=[\r
|
|
63
|
+
]))`;continue}}if(r.s&&i[e]===`.`){a+=s?`${i[e]}\r
|
|
64
|
+
`:`[${i[e]}\r
|
|
65
|
+
]`;continue}a+=i[e],i[e]===`\\`?o=!0:s&&i[e]===`]`?s=!1:!s&&i[e]===`[`&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function nc(e,t){var n,r,i,a,o,s;let c={type:`object`,additionalProperties:(n=q(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]}))??t.allowedAdditionalProperties};if((r=e.keyType)?._def.typeName===H.ZodString&&(i=e.keyType._def.checks)?.length){let{type:n,...r}=Ys(e.keyType._def,t);return{...c,propertyNames:r}}else if((a=e.keyType)?._def.typeName===H.ZodEnum)return{...c,propertyNames:{enum:e.keyType._def.values}};else if((o=e.keyType)?._def.typeName===H.ZodBranded&&e.keyType._def.type._def.typeName===H.ZodString&&(s=e.keyType._def.type._def.checks)?.length){let{type:n,...r}=Ls(e.keyType._def,t);return{...c,propertyNames:r}}return c}function rc(e,t){if(t.mapStrategy===`record`)return nc(e,t);let n=q(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Ns(),r=q(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Ns();return{type:`array`,maxItems:125,items:{type:`array`,items:[n,r],minItems:2,maxItems:2}}}function ic(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`),r=n.map(e=>t[e]),i=Array.from(new Set(r.map(e=>typeof e)));return{type:i.length===1?i[0]===`string`?`string`:`number`:[`string`,`number`],enum:r}}function ac(){return{not:Ns()}}function oc(){return{type:`null`}}var sc={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function cc(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in sc&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=sc[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];case`symbol`:case`undefined`:case`function`:default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return lc(e,t)}var lc=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>q(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function uc(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[sc[e.innerType._def.typeName],`null`]};let n=q(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function dc(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function fc(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=mc(a),s=q(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});if(s===void 0)continue;n.properties[e]=s,o||r.push(e)}r.length&&(n.required=r);let a=pc(e,t);return a!==void 0&&(n.additionalProperties=a),n}function pc(e,t){if(e.catchall._def.typeName!==`ZodNever`)return q(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function mc(e){try{return e.isOptional()}catch{return!0}}var hc=(e,t)=>{var n;if(t.currentPath.toString()===(n=t.propertyPath)?.toString())return q(e.innerType._def,t);let r=q(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return r?{anyOf:[{not:Ns()},r]}:Ns()},gc=(e,t)=>{if(t.pipeStrategy===`input`)return q(e.in._def,t);if(t.pipeStrategy===`output`)return q(e.out._def,t);let n=q(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),r=q(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]});return{allOf:[n,r].filter(e=>e!==void 0)}};function _c(e,t){return q(e.type._def,t)}function vc(e,t){let n=q(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]}),r={type:`array`,uniqueItems:!0,items:n};return e.minSize&&(r.minItems=e.minSize.value),e.maxSize&&(r.maxItems=e.maxSize.value),r}function yc(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>q(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:q(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>q(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function bc(){return{not:Ns()}}function xc(){return Ns()}var Sc=(e,t)=>q(e.innerType._def,t),Cc=(e,t,n)=>{switch(t){case H.ZodString:return Ys(e,n);case H.ZodNumber:return dc(e);case H.ZodObject:return fc(e,n);case H.ZodBigInt:return Fs(e);case H.ZodBoolean:return Is();case H.ZodDate:return zs(e,n);case H.ZodUndefined:return bc();case H.ZodNull:return oc();case H.ZodArray:return Ps(e,n);case H.ZodUnion:case H.ZodDiscriminatedUnion:return cc(e,n);case H.ZodIntersection:return Gs(e,n);case H.ZodTuple:return yc(e,n);case H.ZodRecord:return nc(e,n);case H.ZodLiteral:return Ks(e);case H.ZodEnum:return Us(e);case H.ZodNativeEnum:return ic(e);case H.ZodNullable:return uc(e,n);case H.ZodOptional:return hc(e,n);case H.ZodMap:return rc(e,n);case H.ZodSet:return vc(e,n);case H.ZodLazy:return()=>e.getter()._def;case H.ZodPromise:return _c(e,n);case H.ZodNaN:case H.ZodNever:return ac();case H.ZodEffects:return Hs(e,n);case H.ZodAny:return Ns();case H.ZodUnknown:return xc();case H.ZodDefault:return Vs(e,n);case H.ZodBranded:return Ls(e,n);case H.ZodReadonly:return Sc(e,n);case H.ZodCatch:return Rs(e,n);case H.ZodPipeline:return gc(e,n);case H.ZodFunction:case H.ZodVoid:case H.ZodSymbol:return;default:return(e=>void 0)(t)}};function q(e,t,n=!1){var r;let i=t.seen.get(e);if(t.override){let a=(r=t.override)?.call(t,e,t,i,n);if(a!==As)return a}if(i&&!n){let e=wc(i,t);if(e!==void 0)return e}let a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);let o=Cc(e,e.typeName,t),s=typeof o==`function`?q(o(),t):o;if(s&&Tc(e,t,s),t.postProcess){let n=t.postProcess(s,e,t);return a.jsonSchema=s,n}return a.jsonSchema=s,s}var wc=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:ks(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Ns()):t.$refStrategy===`seen`?Ns():void 0}},Tc=(e,t,n)=>(e.description&&(n.description=e.description),n),Ec=e=>{let t=Ms(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Dc=(e,t)=>{var n;let r=Ec(t),i=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,n])=>{var i;return{...e,[t]:(i=q(n._def,{...r,currentPath:[...r.basePath,r.definitionPath,t]},!0))??Ns()}},{}):void 0,a=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,o=(n=q(e._def,a===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,a]},!1))??Ns(),s=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;s!==void 0&&(o.title=s);let c=a===void 0?i?{...o,[r.definitionPath]:i}:o:{$ref:[...r.$refStrategy===`relative`?[]:r.basePath,r.definitionPath,a].join(`/`),[r.definitionPath]:{...i,[a]:o}};return c.$schema=`http://json-schema.org/draft-07/schema#`,c},Oc=Dc;function kc(e,t){var n;let r=(n=t?.useReferences)??!1;return Pc(Oc(e,{$refStrategy:r?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function Ac(e,t){var n;let r=(n=t?.useReferences)??!1,i=de.toJSONSchema(e,{target:`draft-7`,io:`output`,reused:r?`ref`:`inline`});return Pc(i,{validate:async t=>{let n=await de.safeParseAsync(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function jc(e){return`_zod`in e}function Mc(e,t){return jc(e)?Ac(e,t):kc(e,t)}var Nc=Symbol.for(`vercel.ai.schema`);function Pc(e,{validate:t}={}){return{[Nc]:!0,_type:void 0,[os]:!0,jsonSchema:e,validate:t}}function Fc(e){return typeof e==`object`&&!!e&&Nc in e&&e[Nc]===!0&&`jsonSchema`in e&&`validate`in e}function Ic(e){return e==null?Pc({properties:{},additionalProperties:!1}):Fc(e)?e:Mc(e)}var{btoa:Lc,atob:Rc}=globalThis;function zc(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=Rc(t);return Uint8Array.from(n,e=>e.codePointAt(0))}function Bc(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return Lc(t)}function Vc(e){return e instanceof Uint8Array?Bc(e):e}function Hc(e){return e?.replace(/\/$/,``)}function Uc(e){return e!=null&&typeof e[Symbol.asyncIterator]==`function`}async function*Wc({execute:e,input:t,options:n}){let r=e(t,n);if(Uc(r)){let e;for await(let t of r)e=t,yield{type:`preliminary`,output:t};yield{type:`final`,output:e}}else yield{type:`final`,output:await r}}var Gc=`vercel.ai.gateway.error`,Kc=Symbol.for(Gc),qc,Jc,Yc=class e extends (Jc=Error,qc=Kc,Jc){constructor({message:e,statusCode:t=500,cause:n}){super(e),this[qc]=!0,this.statusCode=t,this.cause=n}static isInstance(t){return e.hasMarker(t)}static hasMarker(e){return typeof e==`object`&&!!e&&Kc in e&&e[Kc]===!0}},Xc=`GatewayAuthenticationError`,Zc=`vercel.ai.gateway.error.${Xc}`,Qc=Symbol.for(Zc),$c,el,tl=class e extends (el=Yc,$c=Qc,el){constructor({message:e=`Authentication failed`,statusCode:t=401,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[$c]=!0,this.name=Xc,this.type=`authentication_error`}static isInstance(e){return Yc.hasMarker(e)&&Qc in e}static createContextualError({apiKeyProvided:t,oidcTokenProvided:n,message:r=`Authentication failed`,statusCode:i=401,cause:a}){let o;return o=t?`AI Gateway authentication failed: Invalid API key provided.
|
|
66
|
+
|
|
67
|
+
The token is expected to be provided via the 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:n?`AI Gateway authentication failed: Invalid OIDC token provided.
|
|
68
|
+
|
|
69
|
+
The token is expected to be provided via the 'VERCEL_OIDC_TOKEN' environment variable. It expires every 12 hours.
|
|
70
|
+
- make sure your Vercel project settings have OIDC enabled
|
|
71
|
+
- if running locally with 'vercel dev', the token is automatically obtained and refreshed
|
|
72
|
+
- if running locally with your own dev server, run 'vercel env pull' to fetch the token
|
|
73
|
+
- in production/preview, the token is automatically obtained and refreshed
|
|
74
|
+
|
|
75
|
+
Alternative: Provide an API key via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`:`AI Gateway authentication failed: No authentication provided.
|
|
76
|
+
|
|
77
|
+
Provide either an API key or OIDC token.
|
|
78
|
+
|
|
79
|
+
API key instructions:
|
|
80
|
+
|
|
81
|
+
The token is expected to be provided via the 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
|
|
82
|
+
|
|
83
|
+
OIDC token instructions:
|
|
84
|
+
|
|
85
|
+
The token is expected to be provided via the 'VERCEL_OIDC_TOKEN' environment variable. It expires every 12 hours.
|
|
86
|
+
- make sure your Vercel project settings have OIDC enabled
|
|
87
|
+
- if running locally with 'vercel dev', the token is automatically obtained and refreshed
|
|
88
|
+
- if running locally with your own dev server, run 'vercel env pull' to fetch the token
|
|
89
|
+
- in production/preview, the token is automatically obtained and refreshed`,new e({message:o,statusCode:i,cause:a})}},nl=`GatewayInvalidRequestError`,rl=`vercel.ai.gateway.error.${nl}`,il=Symbol.for(rl),al,ol,sl=class extends (ol=Yc,al=il,ol){constructor({message:e=`Invalid request`,statusCode:t=400,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[al]=!0,this.name=nl,this.type=`invalid_request_error`}static isInstance(e){return Yc.hasMarker(e)&&il in e}},cl=`GatewayRateLimitError`,ll=`vercel.ai.gateway.error.${cl}`,ul=Symbol.for(ll),dl,fl,pl=class extends (fl=Yc,dl=ul,fl){constructor({message:e=`Rate limit exceeded`,statusCode:t=429,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[dl]=!0,this.name=cl,this.type=`rate_limit_exceeded`}static isInstance(e){return Yc.hasMarker(e)&&ul in e}},ml=`GatewayModelNotFoundError`,hl=`vercel.ai.gateway.error.${ml}`,gl=Symbol.for(hl),_l=V.object({modelId:V.string()}),vl,yl,bl=class extends (yl=Yc,vl=gl,yl){constructor({message:e=`Model not found`,statusCode:t=404,modelId:n,cause:r}={}){super({message:e,statusCode:t,cause:r}),this[vl]=!0,this.name=ml,this.type=`model_not_found`,this.modelId=n}static isInstance(e){return Yc.hasMarker(e)&&gl in e}},xl=`GatewayInternalServerError`,Sl=`vercel.ai.gateway.error.${xl}`,Cl=Symbol.for(Sl),wl,Tl,El=class extends (Tl=Yc,wl=Cl,Tl){constructor({message:e=`Internal server error`,statusCode:t=500,cause:n}={}){super({message:e,statusCode:t,cause:n}),this[wl]=!0,this.name=xl,this.type=`internal_server_error`}static isInstance(e){return Yc.hasMarker(e)&&Cl in e}},Dl=`GatewayResponseError`,Ol=`vercel.ai.gateway.error.${Dl}`,kl=Symbol.for(Ol),Al,jl,Ml=class extends (jl=Yc,Al=kl,jl){constructor({message:e=`Invalid response from Gateway`,statusCode:t=502,response:n,validationError:r,cause:i}={}){super({message:e,statusCode:t,cause:i}),this[Al]=!0,this.name=Dl,this.type=`response_error`,this.response=n,this.validationError=r}static isInstance(e){return Yc.hasMarker(e)&&kl in e}};function Nl({response:e,statusCode:t,defaultMessage:n=`Gateway request failed`,cause:r,authMethod:i}){let a=Pl.safeParse(e);if(!a.success)return new Ml({message:`Invalid error response format: ${n}`,statusCode:t,response:e,validationError:a.error,cause:r});let o=a.data,s=o.error.type,c=o.error.message;switch(s){case`authentication_error`:return tl.createContextualError({apiKeyProvided:i===`api-key`,oidcTokenProvided:i===`oidc`,statusCode:t,cause:r});case`invalid_request_error`:return new sl({message:c,statusCode:t,cause:r});case`rate_limit_exceeded`:return new pl({message:c,statusCode:t,cause:r});case`model_not_found`:{let e=_l.safeParse(o.error.param);return new bl({message:c,statusCode:t,modelId:e.success?e.data.modelId:void 0,cause:r})}case`internal_server_error`:return new El({message:c,statusCode:t,cause:r});default:return new El({message:c,statusCode:t,cause:r})}}var Pl=V.object({error:V.object({message:V.string(),type:V.string().nullish(),param:V.unknown().nullish(),code:V.union([V.string(),V.number()]).nullish()})});function Fl(e,t){var n;return Yc.isInstance(e)?e:Ca.isInstance(e)?Nl({response:Il(e),statusCode:(n=e.statusCode)??500,defaultMessage:`Gateway request failed`,cause:e,authMethod:t}):Nl({response:{},statusCode:500,defaultMessage:e instanceof Error?`Gateway request failed: ${e.message}`:`Unknown Gateway error`,cause:e,authMethod:t})}function Il(e){if(e.data!==void 0)return e.data;if(e.responseBody!=null)try{return JSON.parse(e.responseBody)}catch{return e.responseBody}return{}}var Ll=`ai-gateway-auth-method`;function Rl(e){let t=zl.safeParse(e[Ll]);return t.success?t.data:void 0}var zl=V.union([V.literal(`api-key`),V.literal(`oidc`)]),Bl=class{constructor(e){this.config=e}async getAvailableModels(){try{let{value:e}=await Jo({url:`${this.config.baseURL}/config`,headers:await ws(this.config.headers()),successfulResponseHandler:Ds(Wl),failedResponseHandler:Ts({errorSchema:V.any(),errorToMessage:e=>e}),fetch:this.config.fetch});return e}catch(e){throw Fl(e)}}},Vl=V.object({specificationVersion:V.literal(`v2`),provider:V.string(),modelId:V.string()}),Hl=V.object({input:V.string(),output:V.string(),input_cache_read:V.string().nullish(),input_cache_write:V.string().nullish()}).transform(({input:e,output:t,input_cache_read:n,input_cache_write:r})=>({input:e,output:t,...n?{cachedInputTokens:n}:{},...r?{cacheCreationInputTokens:r}:{}})),Ul=V.object({id:V.string(),name:V.string(),description:V.string().nullish(),pricing:Hl.nullish(),specification:Vl,modelType:V.enum([`language`,`embedding`,`image`]).nullish()}),Wl=V.object({models:V.array(Ul)}),Gl=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.supportedUrls={"*/*":[/.*/]}}get provider(){return this.config.provider}async getArgs(e){let{abortSignal:t,...n}=e;return{args:this.maybeEncodeFileParts(n),warnings:[]}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,i=await ws(this.config.headers());try{let{responseHeaders:a,value:o,rawValue:s}=await K({url:this.getUrl(),headers:Io(i,e.headers,this.getModelConfigHeaders(this.modelId,!1),await ws(this.config.o11yHeaders)),body:t,successfulResponseHandler:Ds(V.any()),failedResponseHandler:Ts({errorSchema:V.any(),errorToMessage:e=>e}),...r&&{abortSignal:r},fetch:this.config.fetch});return{...o,request:{body:t},response:{headers:a,body:s},warnings:n}}catch(e){throw Fl(e,Rl(i))}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),{abortSignal:r}=e,i=await ws(this.config.headers());try{let{value:a,responseHeaders:o}=await K({url:this.getUrl(),headers:Io(i,e.headers,this.getModelConfigHeaders(this.modelId,!0),await ws(this.config.o11yHeaders)),body:t,successfulResponseHandler:Es(V.any()),failedResponseHandler:Ts({errorSchema:V.any(),errorToMessage:e=>e}),...r&&{abortSignal:r},fetch:this.config.fetch});return{stream:a.pipeThrough(new TransformStream({start(e){n.length>0&&e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(t.success){let r=t.value;if(r.type===`raw`&&!e.includeRawChunks)return;r.type===`response-metadata`&&r.timestamp&&typeof r.timestamp==`string`&&(r.timestamp=new Date(r.timestamp)),n.enqueue(r)}else n.error(t.error)}})),request:{body:t},response:{headers:o}}}catch(e){throw Fl(e,Rl(i))}}isFilePart(e){return e&&typeof e==`object`&&`type`in e&&e.type===`file`}maybeEncodeFileParts(e){for(let t of e.prompt)for(let e of t.content)if(this.isFilePart(e)){let t=e;if(t.data instanceof Uint8Array){let e=Uint8Array.from(t.data),n=Buffer.from(e).toString(`base64`);t.data=new URL(`data:${t.mediaType||`application/octet-stream`};base64,${n}`)}}return e}getUrl(){return`${this.config.baseURL}/language-model`}getModelConfigHeaders(e,t){return{"ai-language-model-specification-version":`2`,"ai-language-model-id":e,"ai-language-model-streaming":String(t)}}},Kl=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var i;let a=await ws(this.config.headers());try{let{responseHeaders:o,value:s,rawValue:c}=await K({url:this.getUrl(),headers:Io(a,t??{},this.getModelConfigHeaders(),await ws(this.config.o11yHeaders)),body:{input:e.length===1?e[0]:e,...r?{providerOptions:r}:{}},successfulResponseHandler:Ds(ql),failedResponseHandler:Ts({errorSchema:V.any(),errorToMessage:e=>e}),...n&&{abortSignal:n},fetch:this.config.fetch});return{embeddings:s.embeddings,usage:(i=s.usage)??void 0,providerMetadata:s.providerMetadata,response:{headers:o,body:c}}}catch(e){throw Fl(e,Rl(a))}}getUrl(){return`${this.config.baseURL}/embedding-model`}getModelConfigHeaders(){return{"ai-embedding-model-specification-version":`2`,"ai-model-id":this.modelId}}},ql=V.object({embeddings:V.array(V.array(V.number())),usage:V.object({tokens:V.number()}).nullish(),providerMetadata:V.record(V.string(),V.record(V.string(),V.unknown())).optional()});async function Jl(){var e,t;let n=(t=(e=Zl().headers)?.[`x-vercel-oidc-token`])??process.env.VERCEL_OIDC_TOKEN;if(!n)throw new tl({message:`OIDC token not available`,statusCode:401});return n}async function Yl(){var e;return(e=Zl().headers)?.[`x-vercel-id`]}var Xl=Symbol.for(`@vercel/request-context`);function Zl(){var e,t,n;let r=globalThis;return(n=(t=(e=r[Xl])?.get)?.call(e))??{}}var Ql=`0.0.1`;function $l(e={}){var t,n;let r=null,i=null,a=(t=e.metadataCacheRefreshMillis)??1e3*60*5,o=0,s=(n=Hc(e.baseURL))??`https://ai-gateway.vercel.sh/v1/ai`,c=async()=>{let t=await tu(e);if(t)return{Authorization:`Bearer ${t.token}`,"ai-gateway-protocol-version":Ql,[Ll]:t.authMethod,...e.headers};throw tl.createContextualError({apiKeyProvided:!1,oidcTokenProvided:!1,statusCode:401})},l=()=>{let e=Zo({settingValue:void 0,environmentVariableName:`VERCEL_DEPLOYMENT_ID`}),t=Zo({settingValue:void 0,environmentVariableName:`VERCEL_ENV`}),n=Zo({settingValue:void 0,environmentVariableName:`VERCEL_REGION`});return async()=>{let r=await Yl();return{...e&&{"ai-o11y-deployment-id":e},...t&&{"ai-o11y-environment":t},...n&&{"ai-o11y-region":n},...r&&{"ai-o11y-request-id":r}}}},u=t=>new Gl(t,{provider:`gateway`,baseURL:s,headers:c,fetch:e.fetch,o11yHeaders:l()}),d=async()=>{var t,n,l;let u=(l=(n=(t=e._internal)?.currentDate)?.call(t).getTime())??Date.now();return(!r||u-o>a)&&(o=u,r=new Bl({baseURL:s,headers:c,fetch:e.fetch}).getAvailableModels().then(e=>(i=e,e)).catch(async e=>{throw Fl(e,Rl(await c()))})),i?Promise.resolve(i):r},f=function(e){if(new.target)throw Error(`The Gateway Provider model function cannot be called with the new keyword.`);return u(e)};return f.getAvailableModels=d,f.imageModel=e=>{throw new mo({modelId:e,modelType:`imageModel`})},f.languageModel=u,f.textEmbeddingModel=t=>new Kl(t,{provider:`gateway`,baseURL:s,headers:c,fetch:e.fetch,o11yHeaders:l()}),f}var eu=$l();async function tu(e){let t=Zo({settingValue:e.apiKey,environmentVariableName:`AI_GATEWAY_API_KEY`});if(t)return{token:t,authMethod:`api-key`};try{let e=await Jl();return{token:e,authMethod:`oidc`}}catch{return null}}c();var nu=Object.defineProperty,ru=(e,t)=>{for(var n in t)nu(e,n,{get:t[n],enumerable:!0})},iu=`AI_NoOutputSpecifiedError`,au=`vercel.ai.error.${iu}`,ou=Symbol.for(au),su,cu=class extends G{constructor({message:e=`No output specified.`}={}){super({name:iu,message:e}),this[su]=!0}static isInstance(e){return G.hasMarker(e,au)}};su=ou;function lu(e){let t=`AI SDK Warning:`;switch(e.type){case`unsupported-setting`:{let n=`${t} The "${e.setting}" setting is not supported by this model`;return e.details&&(n+=` - ${e.details}`),n}case`unsupported-tool`:{let n=`name`in e.tool?e.tool.name:`unknown tool`,r=`${t} The tool "${n}" is not supported by this model`;return e.details&&(r+=` - ${e.details}`),r}case`other`:return`${t} ${e.message}`;default:return`${t} ${JSON.stringify(e,null,2)}`}}var uu=`AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.`,du=!1,fu=e=>{if(e.length===0)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t==`function`){t(e);return}du||(du=!0,console.info(uu));for(let t of e)console.warn(lu(t))}},pu=`AI_InvalidArgumentError`,mu=`vercel.ai.error.${pu}`,hu=Symbol.for(mu),gu,_u=class extends G{constructor({parameter:e,value:t,message:n}){super({name:pu,message:`Invalid argument for parameter ${e}: ${n}`}),this[gu]=!0,this.parameter=e,this.value=t}static isInstance(e){return G.hasMarker(e,mu)}};gu=hu;var vu=`AI_InvalidStreamPartError`,yu=`vercel.ai.error.${vu}`,bu=Symbol.for(yu),xu;xu=bu;var Su=`AI_InvalidToolInputError`,Cu=`vercel.ai.error.${Su}`,wu=Symbol.for(Cu),Tu,Eu=class extends G{constructor({toolInput:e,toolName:t,cause:n,message:r=`Invalid input for tool ${t}: ${ka(n)}`}){super({name:Su,message:r,cause:n}),this[Tu]=!0,this.toolInput=e,this.toolName=t}static isInstance(e){return G.hasMarker(e,Cu)}};Tu=wu;var Du=`AI_MCPClientError`,Ou=`vercel.ai.error.${Du}`,ku=Symbol.for(Ou),Au;Au=ku;var ju=`AI_NoImageGeneratedError`,Mu=`vercel.ai.error.${ju}`,Nu=Symbol.for(Mu),Pu;Pu=Nu;var Fu=`AI_NoObjectGeneratedError`,Iu=`vercel.ai.error.${Fu}`,Lu=Symbol.for(Iu),Ru,zu=class extends G{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:Fu,message:e,cause:t}),this[Ru]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return G.hasMarker(e,Iu)}};Ru=Lu;var Bu=`AI_NoOutputGeneratedError`,Vu=`vercel.ai.error.${Bu}`,Hu=Symbol.for(Vu),Uu,Wu=class extends G{constructor({message:e=`No output generated.`,cause:t}={}){super({name:Bu,message:e,cause:t}),this[Uu]=!0}static isInstance(e){return G.hasMarker(e,Vu)}};Uu=Hu;var Gu=`AI_NoSuchToolError`,Ku=`vercel.ai.error.${Gu}`,qu=Symbol.for(Ku),Ju,Yu=class extends G{constructor({toolName:e,availableTools:t=void 0,message:n=`Model tried to call unavailable tool '${e}'. ${t===void 0?`No tools are available.`:`Available tools: ${t.join(`, `)}.`}`}){super({name:Gu,message:n}),this[Ju]=!0,this.toolName=e,this.availableTools=t}static isInstance(e){return G.hasMarker(e,Ku)}};Ju=qu;var Xu=`AI_ToolCallRepairError`,Zu=`vercel.ai.error.${Xu}`,Qu=Symbol.for(Zu),$u,ed=class extends G{constructor({cause:e,originalError:t,message:n=`Error repairing tool call: ${ka(e)}`}){super({name:Xu,message:n,cause:e}),this[$u]=!0,this.originalError=t}static isInstance(e){return G.hasMarker(e,Zu)}};$u=Qu;var td=class extends G{constructor(e){super({name:`AI_UnsupportedModelVersionError`,message:`Unsupported model version ${e.version} for provider "${e.provider}" and model "${e.modelId}". AI SDK 5 only supports models that implement specification version "v2".`}),this.version=e.version,this.provider=e.provider,this.modelId=e.modelId}},nd=`AI_InvalidDataContentError`,rd=`vercel.ai.error.${nd}`,id=Symbol.for(rd),ad;ad=id;var od=`AI_InvalidMessageRoleError`,sd=`vercel.ai.error.${od}`,cd=Symbol.for(sd),ld,ud=class extends G{constructor({role:e,message:t=`Invalid message role: '${e}'. Must be one of: "system", "user", "assistant", "tool".`}){super({name:od,message:t}),this[ld]=!0,this.role=e}static isInstance(e){return G.hasMarker(e,sd)}};ld=cd;var dd=`AI_MessageConversionError`,fd=`vercel.ai.error.${dd}`,pd=Symbol.for(fd),md;md=pd;var hd=`AI_DownloadError`,gd=`vercel.ai.error.${hd}`,_d=Symbol.for(gd),vd,yd=class extends G{constructor({url:e,statusCode:t,statusText:n,cause:r,message:i=r==null?`Failed to download ${e}: ${t} ${n}`:`Failed to download ${e}: ${r}`}){super({name:hd,message:i,cause:r}),this[vd]=!0,this.url=e,this.statusCode=t,this.statusText=n}static isInstance(e){return G.hasMarker(e,gd)}};vd=_d;var bd=`AI_RetryError`,xd=`vercel.ai.error.${bd}`,Sd=Symbol.for(xd),Cd,wd=class extends G{constructor({message:e,reason:t,errors:n}){super({name:bd,message:e}),this[Cd]=!0,this.reason=t,this.errors=n,this.lastError=n[n.length-1]}static isInstance(e){return G.hasMarker(e,xd)}};Cd=Sd;function Td(e){if(typeof e!=`string`){if(e.specificationVersion!==`v2`)throw new td({version:e.specificationVersion,provider:e.provider,modelId:e.modelId});return e}return Ed().languageModel(e)}function Ed(){var e;return(e=globalThis.AI_SDK_DEFAULT_PROVIDER)??eu}var Dd=[{mediaType:`image/gif`,bytesPrefix:[71,73,70],base64Prefix:`R0lG`},{mediaType:`image/png`,bytesPrefix:[137,80,78,71],base64Prefix:`iVBORw`},{mediaType:`image/jpeg`,bytesPrefix:[255,216],base64Prefix:`/9j/`},{mediaType:`image/webp`,bytesPrefix:[82,73,70,70],base64Prefix:`UklGRg`},{mediaType:`image/bmp`,bytesPrefix:[66,77],base64Prefix:`Qk`},{mediaType:`image/tiff`,bytesPrefix:[73,73,42,0],base64Prefix:`SUkqAA`},{mediaType:`image/tiff`,bytesPrefix:[77,77,0,42],base64Prefix:`TU0AKg`},{mediaType:`image/avif`,bytesPrefix:[0,0,0,32,102,116,121,112,97,118,105,102],base64Prefix:`AAAAIGZ0eXBhdmlm`},{mediaType:`image/heic`,bytesPrefix:[0,0,0,32,102,116,121,112,104,101,105,99],base64Prefix:`AAAAIGZ0eXBoZWlj`}],Od=e=>{let t=typeof e==`string`?zc(e):e,n=(t[6]&127)<<21|(t[7]&127)<<14|(t[8]&127)<<7|t[9]&127;return t.slice(n+10)};function kd(e){let t=typeof e==`string`&&e.startsWith(`SUQz`)||typeof e!=`string`&&e.length>10&&e[0]===73&&e[1]===68&&e[2]===51;return t?Od(e):e}function Ad({data:e,signatures:t}){let n=kd(e);for(let e of t)if(typeof n==`string`?n.startsWith(e.base64Prefix):n.length>=e.bytesPrefix.length&&e.bytesPrefix.every((e,t)=>n[t]===e))return e.mediaType}var jd=async({url:e})=>{var t;let n=e.toString();try{let e=await fetch(n);if(!e.ok)throw new yd({url:n,statusCode:e.status,statusText:e.statusText});return{data:new Uint8Array(await e.arrayBuffer()),mediaType:(t=e.headers.get(`content-type`))??void 0}}catch(e){throw yd.isInstance(e)?e:new yd({url:n,cause:e})}},Md=(e=jd)=>t=>Promise.all(t.map(async t=>t.isUrlSupportedByModel?null:e(t)));function Nd(e){try{let[t,n]=e.split(`,`);return{mediaType:t.split(`;`)[0].split(`:`)[1],base64Content:n}}catch{return{mediaType:void 0,base64Content:void 0}}}var Pd=V.union([V.string(),V.instanceof(Uint8Array),V.instanceof(ArrayBuffer),V.custom(e=>{var t,n;return(n=(t=globalThis.Buffer)?.isBuffer(e))??!1},{message:`Must be a Buffer`})]);function Fd(e){if(e instanceof Uint8Array)return{data:e,mediaType:void 0};if(e instanceof ArrayBuffer)return{data:new Uint8Array(e),mediaType:void 0};if(typeof e==`string`)try{e=new URL(e)}catch{}if(e instanceof URL&&e.protocol===`data:`){let{mediaType:t,base64Content:n}=Nd(e.toString());if(t==null||n==null)throw new G({name:`InvalidDataContentError`,message:`Invalid data URL format in content ${e.toString()}`});return{data:n,mediaType:t}}return{data:e,mediaType:void 0}}function Id(e){return typeof e==`string`?e:e instanceof ArrayBuffer?Bc(new Uint8Array(e)):Bc(e)}async function Ld({prompt:e,supportedUrls:t,download:n=Md()}){let r=await zd(e.messages,n,t);return[...e.system==null?[]:[{role:`system`,content:e.system}],...e.messages.map(e=>Rd({message:e,downloadedAssets:r}))]}function Rd({message:e,downloadedAssets:t}){let n=e.role;switch(n){case`system`:return{role:`system`,content:e.content,providerOptions:e.providerOptions};case`user`:return typeof e.content==`string`?{role:`user`,content:[{type:`text`,text:e.content}],providerOptions:e.providerOptions}:{role:`user`,content:e.content.map(e=>Bd(e,t)).filter(e=>e.type!==`text`||e.text!==``),providerOptions:e.providerOptions};case`assistant`:return typeof e.content==`string`?{role:`assistant`,content:[{type:`text`,text:e.content}],providerOptions:e.providerOptions}:{role:`assistant`,content:e.content.filter(e=>e.type!==`text`||e.text!==``).map(e=>{let t=e.providerOptions;switch(e.type){case`file`:{let{data:n,mediaType:r}=Fd(e.data);return{type:`file`,data:n,filename:e.filename,mediaType:r??e.mediaType,providerOptions:t}}case`reasoning`:return{type:`reasoning`,text:e.text,providerOptions:t};case`text`:return{type:`text`,text:e.text,providerOptions:t};case`tool-call`:return{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:t};case`tool-result`:return{type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:e.output,providerOptions:t}}}),providerOptions:e.providerOptions};case`tool`:return{role:`tool`,content:e.content.map(e=>({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:e.output,providerOptions:e.providerOptions})),providerOptions:e.providerOptions};default:{let e=n;throw new ud({role:e})}}}async function zd(e,t,n){let r=e.filter(e=>e.role===`user`).map(e=>e.content).filter(e=>Array.isArray(e)).flat().filter(e=>e.type===`image`||e.type===`file`).map(e=>{var t;let n=(t=e.mediaType)??(e.type===`image`?`image/*`:void 0),r=e.type===`image`?e.image:e.data;if(typeof r==`string`)try{r=new URL(r)}catch{}return{mediaType:n,data:r}}).filter(e=>e.data instanceof URL).map(e=>({url:e.data,isUrlSupportedByModel:e.mediaType!=null&&Yo({url:e.data.toString(),mediaType:e.mediaType,supportedUrls:n})})),i=await t(r);return Object.fromEntries(i.filter(e=>e?.data!=null).map(({data:e,mediaType:t},n)=>[r[n].url.toString(),{data:e,mediaType:t}]))}function Bd(e,t){var n;if(e.type===`text`)return{type:`text`,text:e.text,providerOptions:e.providerOptions};let r,i=e.type;switch(i){case`image`:r=e.image;break;case`file`:r=e.data;break;default:throw Error(`Unsupported part type: ${i}`)}let{data:a,mediaType:o}=Fd(r),s=o??e.mediaType,c=a;if(c instanceof URL){let e=t[c.toString()];e&&(c=e.data,s??=e.mediaType)}switch(i){case`image`:return(c instanceof Uint8Array||typeof c==`string`)&&(s=(n=Ad({data:c,signatures:Dd}))??s),{type:`file`,mediaType:s??`image/*`,filename:void 0,data:c,providerOptions:e.providerOptions};case`file`:if(s==null)throw Error(`Media type is missing for file part`);return{type:`file`,mediaType:s,filename:e.filename,data:c,providerOptions:e.providerOptions}}}function Vd({maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:i,frequencyPenalty:a,seed:o,stopSequences:s}){if(e!=null){if(!Number.isInteger(e))throw new _u({parameter:`maxOutputTokens`,value:e,message:`maxOutputTokens must be an integer`});if(e<1)throw new _u({parameter:`maxOutputTokens`,value:e,message:`maxOutputTokens must be >= 1`})}if(t!=null&&typeof t!=`number`)throw new _u({parameter:`temperature`,value:t,message:`temperature must be a number`});if(n!=null&&typeof n!=`number`)throw new _u({parameter:`topP`,value:n,message:`topP must be a number`});if(r!=null&&typeof r!=`number`)throw new _u({parameter:`topK`,value:r,message:`topK must be a number`});if(i!=null&&typeof i!=`number`)throw new _u({parameter:`presencePenalty`,value:i,message:`presencePenalty must be a number`});if(a!=null&&typeof a!=`number`)throw new _u({parameter:`frequencyPenalty`,value:a,message:`frequencyPenalty must be a number`});if(o!=null&&!Number.isInteger(o))throw new _u({parameter:`seed`,value:o,message:`seed must be an integer`});return{maxOutputTokens:e,temperature:t,topP:n,topK:r,presencePenalty:i,frequencyPenalty:a,stopSequences:s,seed:o}}function Hd(e){return e!=null&&Object.keys(e).length>0}function Ud({tools:e,toolChoice:t,activeTools:n}){if(!Hd(e))return{tools:void 0,toolChoice:void 0};let r=n==null?Object.entries(e):Object.entries(e).filter(([e])=>n.includes(e));return{tools:r.map(([e,t])=>{let n=t.type;switch(n){case void 0:case`dynamic`:case`function`:return{type:`function`,name:e,description:t.description,inputSchema:Ic(t.inputSchema).jsonSchema,providerOptions:t.providerOptions};case`provider-defined`:return{type:`provider-defined`,name:e,id:t.id,args:t.args};default:{let e=n;throw Error(`Unsupported tool type: ${e}`)}}}),toolChoice:t==null?{type:`auto`}:typeof t==`string`?{type:t}:{type:`tool`,toolName:t.toolName}}}var Wd=V.lazy(()=>V.union([V.null(),V.string(),V.number(),V.boolean(),V.record(V.string(),Wd),V.array(Wd)])),J=V.record(V.string(),V.record(V.string(),Wd)),Gd=V.object({type:V.literal(`text`),text:V.string(),providerOptions:J.optional()}),Kd=V.object({type:V.literal(`image`),image:V.union([Pd,V.instanceof(URL)]),mediaType:V.string().optional(),providerOptions:J.optional()}),qd=V.object({type:V.literal(`file`),data:V.union([Pd,V.instanceof(URL)]),filename:V.string().optional(),mediaType:V.string(),providerOptions:J.optional()}),Jd=V.object({type:V.literal(`reasoning`),text:V.string(),providerOptions:J.optional()}),Yd=V.object({type:V.literal(`tool-call`),toolCallId:V.string(),toolName:V.string(),input:V.unknown(),providerOptions:J.optional(),providerExecuted:V.boolean().optional()}),Xd=V.discriminatedUnion(`type`,[V.object({type:V.literal(`text`),value:V.string()}),V.object({type:V.literal(`json`),value:Wd}),V.object({type:V.literal(`error-text`),value:V.string()}),V.object({type:V.literal(`error-json`),value:Wd}),V.object({type:V.literal(`content`),value:V.array(V.union([V.object({type:V.literal(`text`),text:V.string()}),V.object({type:V.literal(`media`),data:V.string(),mediaType:V.string()})]))})]),Zd=V.object({type:V.literal(`tool-result`),toolCallId:V.string(),toolName:V.string(),output:Xd,providerOptions:J.optional()}),Qd=V.object({role:V.literal(`system`),content:V.string(),providerOptions:J.optional()}),$d=V.object({role:V.literal(`user`),content:V.union([V.string(),V.array(V.union([Gd,Kd,qd]))]),providerOptions:J.optional()}),ef=V.object({role:V.literal(`assistant`),content:V.union([V.string(),V.array(V.union([Gd,qd,Jd,Yd,Zd]))]),providerOptions:J.optional()}),tf=V.object({role:V.literal(`tool`),content:V.array(Zd),providerOptions:J.optional()}),nf=V.union([Qd,$d,ef,tf]);async function rf(e){if(e.prompt==null&&e.messages==null)throw new za({prompt:e,message:`prompt or messages must be defined`});if(e.prompt!=null&&e.messages!=null)throw new za({prompt:e,message:`prompt and messages cannot be defined at the same time`});if(e.system!=null&&typeof e.system!=`string`)throw new za({prompt:e,message:`system must be a string`});let t;if(e.prompt!=null&&typeof e.prompt==`string`)t=[{role:`user`,content:e.prompt}];else if(e.prompt!=null&&Array.isArray(e.prompt))t=e.prompt;else if(e.messages!=null)t=e.messages;else throw new za({prompt:e,message:`prompt or messages must be defined`});if(t.length===0)throw new za({prompt:e,message:`messages must not be empty`});let n=await fs({value:t,schema:V.array(nf)});if(!n.success)throw new za({prompt:e,message:`The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.`,cause:n.error});return{messages:t,system:e.system}}function af(e){return tl.isInstance(e)||bl.isInstance(e)?new G({name:`GatewayError`,message:`Vercel AI Gateway access failed. If you want to use AI SDK providers directly, use the providers, e.g. @ai-sdk/openai, or register a different global default provider.`,cause:e}):e}function sf({operationId:e,telemetry:t}){return{"operation.name":`${e}${t?.functionId==null?``:` ${t.functionId}`}`,"resource.name":t?.functionId,"ai.operationId":e,"ai.telemetry.functionId":t?.functionId}}function cf({model:e,settings:t,telemetry:n,headers:r}){var i;return{"ai.model.provider":e.provider,"ai.model.id":e.modelId,...Object.entries(t).reduce((e,[t,n])=>(e[`ai.settings.${t}`]=n,e),{}),...Object.entries((i=n?.metadata)??{}).reduce((e,[t,n])=>(e[`ai.telemetry.metadata.${t}`]=n,e),{}),...Object.entries(r??{}).reduce((e,[t,n])=>(n!==void 0&&(e[`ai.request.headers.${t}`]=n),e),{})}}var lf={startSpan(){return uf},startActiveSpan(e,t,n,r){if(typeof t==`function`)return t(uf);if(typeof n==`function`)return n(uf);if(typeof r==`function`)return r(uf)}},uf={spanContext(){return df},setAttribute(){return this},setAttributes(){return this},addEvent(){return this},addLink(){return this},addLinks(){return this},setStatus(){return this},updateName(){return this},end(){return this},isRecording(){return!1},recordException(){return this}},df={traceId:``,spanId:``,traceFlags:0};function ff({isEnabled:e=!1,tracer:t}={}){return e?t||l.getTracer(`ai`):lf}function pf({name:e,tracer:t,attributes:n,fn:r,endWhenDone:i=!0}){return t.startActiveSpan(e,{attributes:n},async e=>{try{let t=await r(e);return i&&e.end(),t}catch(t){try{mf(e,t)}finally{e.end()}throw t}})}function mf(e,t){t instanceof Error?(e.recordException({name:t.name,message:t.message,stack:t.stack}),e.setStatus({code:s.ERROR,message:t.message})):e.setStatus({code:s.ERROR})}function hf({telemetry:e,attributes:t}){return e?.isEnabled===!0?Object.entries(t).reduce((t,[n,r])=>{if(r==null)return t;if(typeof r==`object`&&`input`in r&&typeof r.input==`function`){if(e?.recordInputs===!1)return t;let i=r.input();return i==null?t:{...t,[n]:i}}if(typeof r==`object`&&`output`in r&&typeof r.output==`function`){if(e?.recordOutputs===!1)return t;let i=r.output();return i==null?t:{...t,[n]:i}}return{...t,[n]:r}},{}):{}}function gf(e){return JSON.stringify(e.map(e=>({...e,content:typeof e.content==`string`?e.content:e.content.map(e=>e.type===`file`?{...e,data:e.data instanceof Uint8Array?Id(e.data):e.data}:e)})))}function _f(e,t){return{inputTokens:vf(e.inputTokens,t.inputTokens),outputTokens:vf(e.outputTokens,t.outputTokens),totalTokens:vf(e.totalTokens,t.totalTokens),reasoningTokens:vf(e.reasoningTokens,t.reasoningTokens),cachedInputTokens:vf(e.cachedInputTokens,t.cachedInputTokens)}}function vf(e,t){return e==null&&t==null?void 0:(e??0)+(t??0)}function yf(e){return e===void 0?[]:Array.isArray(e)?e:[e]}function bf({error:e,exponentialBackoffDelay:t}){let n=e.responseHeaders;if(!n)return t;let r,i=n[`retry-after-ms`];if(i){let e=parseFloat(i);Number.isNaN(e)||(r=e)}let a=n[`retry-after`];if(a&&r===void 0){let e=parseFloat(a);r=Number.isNaN(e)?Date.parse(a)-Date.now():e*1e3}return r!=null&&!Number.isNaN(r)&&0<=r&&(r<60*1e3||r<t)?r:t}var xf=({maxRetries:e=2,initialDelayInMs:t=2e3,backoffFactor:n=2,abortSignal:r}={})=>async i=>Sf(i,{maxRetries:e,delayInMs:t,backoffFactor:n,abortSignal:r});async function Sf(e,{maxRetries:t,delayInMs:n,backoffFactor:r,abortSignal:i},a=[]){try{return await e()}catch(o){if(Uo(o)||t===0)throw o;let s=Ho(o),c=[...a,o],l=c.length;if(l>t)throw new wd({message:`Failed after ${l} attempts. Last error: ${s}`,reason:`maxRetriesExceeded`,errors:c});if(o instanceof Error&&Ca.isInstance(o)&&o.isRetryable===!0&&l<=t)return await Lo(bf({error:o,exponentialBackoffDelay:n}),{abortSignal:i}),Sf(e,{maxRetries:t,delayInMs:r*n,backoffFactor:r,abortSignal:i},c);throw l===1?o:new wd({message:`Failed after ${l} attempts with non-retryable error: '${s}'`,reason:`errorNotRetryable`,errors:c})}}function Cf({maxRetries:e,abortSignal:t}){if(e!=null){if(!Number.isInteger(e))throw new _u({parameter:`maxRetries`,value:e,message:`maxRetries must be an integer`});if(e<0)throw new _u({parameter:`maxRetries`,value:e,message:`maxRetries must be >= 0`})}let n=e??2;return{maxRetries:n,retry:xf({maxRetries:n,abortSignal:t})}}var wf=class{constructor({data:e,mediaType:t}){let n=e instanceof Uint8Array;this.base64Data=n?void 0:e,this.uint8ArrayData=n?e:void 0,this.mediaType=t}get base64(){return this.base64Data??=Bc(this.uint8ArrayData),this.base64Data}get uint8Array(){return this.uint8ArrayData??=zc(this.base64Data),this.uint8ArrayData}},Tf=class extends wf{constructor(e){super(e),this.type=`file`}};async function Ef({toolCall:e,tools:t,repairToolCall:n,system:r,messages:i}){try{if(t==null)throw new Yu({toolName:e.toolName});try{return await Df({toolCall:e,tools:t})}catch(a){if(n==null||!(Yu.isInstance(a)||Eu.isInstance(a)))throw a;let o=null;try{o=await n({toolCall:e,tools:t,inputSchema:({toolName:e})=>{let{inputSchema:n}=t[e];return Ic(n).jsonSchema},system:r,messages:i,error:a})}catch(e){throw new ed({cause:e,originalError:a})}if(o==null)throw a;return await Df({toolCall:o,tools:t})}}catch(t){let n=await ms({text:e.input}),r=n.success?n.value:e.input;return{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:r,dynamic:!0,invalid:!0,error:t}}}async function Df({toolCall:e,tools:t}){let n=e.toolName,r=t[n];if(r==null)throw new Yu({toolName:e.toolName,availableTools:Object.keys(t)});let i=Ic(r.inputSchema),a=e.input.trim()===``?await fs({value:{},schema:i}):await ms({text:e.input,schema:i});if(a.success===!1)throw new Eu({toolName:n,toolInput:e.input,cause:a.error});return r.type===`dynamic`?{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:a.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,dynamic:!0}:{type:`tool-call`,toolCallId:e.toolCallId,toolName:n,input:a.value,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}}var Of=class{constructor({content:e,finishReason:t,usage:n,warnings:r,request:i,response:a,providerMetadata:o}){this.content=e,this.finishReason=t,this.usage=n,this.warnings=r,this.request=i,this.response=a,this.providerMetadata=o}get text(){return this.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}get reasoning(){return this.content.filter(e=>e.type===`reasoning`)}get reasoningText(){return this.reasoning.length===0?void 0:this.reasoning.map(e=>e.text).join(``)}get files(){return this.content.filter(e=>e.type===`file`).map(e=>e.file)}get sources(){return this.content.filter(e=>e.type===`source`)}get toolCalls(){return this.content.filter(e=>e.type===`tool-call`)}get staticToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!1)}get dynamicToolCalls(){return this.toolCalls.filter(e=>e.dynamic===!0)}get toolResults(){return this.content.filter(e=>e.type===`tool-result`)}get staticToolResults(){return this.toolResults.filter(e=>e.dynamic===!1)}get dynamicToolResults(){return this.toolResults.filter(e=>e.dynamic===!0)}};function kf(e){return({steps:t})=>t.length===e}async function Af({stopConditions:e,steps:t}){return(await Promise.all(e.map(e=>e({steps:t})))).some(e=>e)}function jf({output:e,tool:t,errorMode:n}){return n===`text`?{type:`error-text`,value:ka(e)}:n===`json`?{type:`error-json`,value:Mf(e)}:t?.toModelOutput?t.toModelOutput(e):typeof e==`string`?{type:`text`,value:e}:{type:`json`,value:Mf(e)}}function Mf(e){return e===void 0?null:e}function Nf({content:e,tools:t}){let n=[],r=e.filter(e=>e.type!==`source`).filter(e=>(e.type!==`tool-result`||e.providerExecuted)&&(e.type!==`tool-error`||e.providerExecuted)).filter(e=>e.type!==`text`||e.text.length>0).map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,providerOptions:e.providerMetadata};case`reasoning`:return{type:`reasoning`,text:e.text,providerOptions:e.providerMetadata};case`file`:return{type:`file`,data:e.file.base64,mediaType:e.file.mediaType,providerOptions:e.providerMetadata};case`tool-call`:return{type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,providerExecuted:e.providerExecuted,providerOptions:e.providerMetadata};case`tool-result`:return{type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:jf({tool:t?.[e.toolName],output:e.output,errorMode:`none`}),providerExecuted:!0,providerOptions:e.providerMetadata};case`tool-error`:return{type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:jf({tool:t?.[e.toolName],output:e.error,errorMode:`json`}),providerOptions:e.providerMetadata}}});r.length>0&&n.push({role:`assistant`,content:r});let i=e.filter(e=>e.type===`tool-result`||e.type===`tool-error`).filter(e=>!e.providerExecuted).map(e=>({type:`tool-result`,toolCallId:e.toolCallId,toolName:e.toolName,output:jf({tool:t?.[e.toolName],output:e.type===`tool-result`?e.output:e.error,errorMode:e.type===`tool-error`?`text`:`none`})}));return i.length>0&&n.push({role:`tool`,content:i}),n}Bo({prefix:`aitxt`,size:24});function Pf(e,t){let n=new Headers(e??{});for(let[e,r]of Object.entries(t))n.has(e)||n.set(e,r);return n}function Ff({status:e,statusText:t,headers:n,textStream:r}){return new Response(r.pipeThrough(new TextEncoderStream),{status:e??200,statusText:t,headers:Pf(n,{"content-type":`text/plain; charset=utf-8`})})}function If({response:e,status:t,statusText:n,headers:r,stream:i}){e.writeHead(t??200,n,r);let a=i.getReader(),o=async()=>{try{for(;;){let{done:t,value:n}=await a.read();if(t)break;e.write(n)}}catch(e){throw e}finally{e.end()}};o()}function Lf({response:e,status:t,statusText:n,headers:r,textStream:i}){If({response:e,status:t,statusText:n,headers:Object.fromEntries(Pf(r,{"content-type":`text/plain; charset=utf-8`}).entries()),stream:i.pipeThrough(new TextEncoderStream)})}var Rf=class extends TransformStream{constructor(){super({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}
|
|
90
|
+
|
|
91
|
+
`)},flush(e){e.enqueue(`data: [DONE]
|
|
92
|
+
|
|
93
|
+
`)}})}},zf={"content-type":`text/event-stream`,"cache-control":`no-cache`,connection:`keep-alive`,"x-vercel-ai-ui-message-stream":`v1`,"x-accel-buffering":`no`};function Bf({status:e,statusText:t,headers:n,stream:r,consumeSseStream:i}){let a=r.pipeThrough(new Rf);if(i){let[e,t]=a.tee();a=e,i({stream:t})}return new Response(a.pipeThrough(new TextEncoderStream),{status:e,statusText:t,headers:Pf(n,zf)})}function Vf({originalMessages:e,responseMessageId:t}){if(e==null)return;let n=e[e.length-1];return n?.role===`assistant`?n.id:typeof t==`function`?t():t}V.union([V.strictObject({type:V.literal(`text-start`),id:V.string(),providerMetadata:J.optional()}),V.strictObject({type:V.literal(`text-delta`),id:V.string(),delta:V.string(),providerMetadata:J.optional()}),V.strictObject({type:V.literal(`text-end`),id:V.string(),providerMetadata:J.optional()}),V.strictObject({type:V.literal(`error`),errorText:V.string()}),V.strictObject({type:V.literal(`tool-input-start`),toolCallId:V.string(),toolName:V.string(),providerExecuted:V.boolean().optional(),dynamic:V.boolean().optional()}),V.strictObject({type:V.literal(`tool-input-delta`),toolCallId:V.string(),inputTextDelta:V.string()}),V.strictObject({type:V.literal(`tool-input-available`),toolCallId:V.string(),toolName:V.string(),input:V.unknown(),providerExecuted:V.boolean().optional(),providerMetadata:J.optional(),dynamic:V.boolean().optional()}),V.strictObject({type:V.literal(`tool-input-error`),toolCallId:V.string(),toolName:V.string(),input:V.unknown(),providerExecuted:V.boolean().optional(),providerMetadata:J.optional(),dynamic:V.boolean().optional(),errorText:V.string()}),V.strictObject({type:V.literal(`tool-output-available`),toolCallId:V.string(),output:V.unknown(),providerExecuted:V.boolean().optional(),dynamic:V.boolean().optional(),preliminary:V.boolean().optional()}),V.strictObject({type:V.literal(`tool-output-error`),toolCallId:V.string(),errorText:V.string(),providerExecuted:V.boolean().optional(),dynamic:V.boolean().optional()}),V.strictObject({type:V.literal(`reasoning`),text:V.string(),providerMetadata:J.optional()}),V.strictObject({type:V.literal(`reasoning-start`),id:V.string(),providerMetadata:J.optional()}),V.strictObject({type:V.literal(`reasoning-delta`),id:V.string(),delta:V.string(),providerMetadata:J.optional()}),V.strictObject({type:V.literal(`reasoning-end`),id:V.string(),providerMetadata:J.optional()}),V.strictObject({type:V.literal(`reasoning-part-finish`)}),V.strictObject({type:V.literal(`source-url`),sourceId:V.string(),url:V.string(),title:V.string().optional(),providerMetadata:J.optional()}),V.strictObject({type:V.literal(`source-document`),sourceId:V.string(),mediaType:V.string(),title:V.string(),filename:V.string().optional(),providerMetadata:J.optional()}),V.strictObject({type:V.literal(`file`),url:V.string(),mediaType:V.string(),providerMetadata:J.optional()}),V.strictObject({type:V.string().startsWith(`data-`),id:V.string().optional(),data:V.unknown(),transient:V.boolean().optional()}),V.strictObject({type:V.literal(`start-step`)}),V.strictObject({type:V.literal(`finish-step`)}),V.strictObject({type:V.literal(`start`),messageId:V.string().optional(),messageMetadata:V.unknown().optional()}),V.strictObject({type:V.literal(`finish`),messageMetadata:V.unknown().optional()}),V.strictObject({type:V.literal(`abort`)}),V.strictObject({type:V.literal(`message-metadata`),messageMetadata:V.unknown()})]);function Hf(e){return e.type.startsWith(`data-`)}function Uf(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let n={...e};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(i===void 0)continue;let a=r in e?e[r]:void 0,o=typeof i==`object`&&!!i&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),s=typeof a==`object`&&!!a&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);o&&s?n[r]=Uf(a,i):n[r]=i}return n}function Wf(e){let t=[`ROOT`],n=-1,r=null;function i(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`);break}}function a(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop();break}}function o(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop();break}}for(let s=0;s<e.length;s++){let c=e[s],l=t[t.length-1];switch(l){case`ROOT`:i(c,s,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=s,t.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break}break;case`INSIDE_OBJECT_KEY`:switch(c){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(c){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:i(c,s,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:a(c,s);break;case`INSIDE_STRING`:switch(c){case`"`:t.pop(),n=s;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=s}break;case`INSIDE_ARRAY_START`:switch(c){case`]`:n=s,t.pop();break;default:n=s,i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(c){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=s,t.pop();break;default:n=s;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:i(c,s,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),n=s;break;case`INSIDE_NUMBER`:switch(c){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=s;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&a(c,s);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s);break;default:t.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,s+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?a(c,s):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&o(c,s)):n=s;break}}}let s=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--){let i=t[n];switch(i){case`INSIDE_STRING`:s+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:s+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:s+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?s+=`true`.slice(t.length):`false`.startsWith(t)?s+=`false`.slice(t.length):`null`.startsWith(t)&&(s+=`null`.slice(t.length))}}}return s}async function Gf(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await ms({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await ms({text:Wf(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}function Kf(e){return e.type.startsWith(`tool-`)}function qf(e){return e.type===`dynamic-tool`}function Jf(e){return Kf(e)||qf(e)}function Yf(e){return e.type.split(`-`).slice(1).join(`-`)}function Xf(e){return qf(e)?e.toolName:Yf(e)}function Zf({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:{},activeReasoningParts:{},partialToolCalls:{}}}function Qf({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:a,onData:o}){return e.pipeThrough(new TransformStream({async transform(e,s){await r(async({state:r,write:c})=>{var l,u,d,f;function p(e){let t=r.message.parts.filter(Kf),n=t.find(t=>t.toolCallId===e);if(n==null)throw Error(`tool-output-error must be preceded by a tool-input-available`);return n}function m(e){let t=r.message.parts.filter(e=>e.type===`dynamic-tool`),n=t.find(t=>t.toolCallId===e);if(n==null)throw Error(`tool-output-error must be preceded by a tool-input-available`);return n}function h(e){var t;let n=r.message.parts.find(t=>Kf(t)&&t.toolCallId===e.toolCallId),i=e,a=n;n==null?r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...i.providerMetadata==null?{}:{callProviderMetadata:i.providerMetadata}}):(n.state=e.state,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput,a.preliminary=i.preliminary,a.providerExecuted=(t=i.providerExecuted)??n.providerExecuted,i.providerMetadata!=null&&n.state===`input-available`&&(n.callProviderMetadata=i.providerMetadata))}function g(e){var t;let n=r.message.parts.find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),i=e,a=n;n==null?r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,...i.providerMetadata==null?{}:{callProviderMetadata:i.providerMetadata}}):(n.state=e.state,a.toolName=e.toolName,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=(t=i.rawInput)??a.rawInput,a.preliminary=i.preliminary,i.providerMetadata!=null&&n.state===`input-available`&&(n.callProviderMetadata=i.providerMetadata))}async function _(e){if(e!=null){let n=r.message.metadata==null?e:Uf(r.message.metadata,e);t!=null&&await ds({value:n,schema:t}),r.message.metadata=n}}switch(e.type){case`text-start`:{let t={type:`text`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeTextParts[e.id]=t,r.message.parts.push(t),c();break}case`text-delta`:{let t=r.activeTextParts[e.id];t.text+=e.delta,t.providerMetadata=(l=e.providerMetadata)??t.providerMetadata,c();break}case`text-end`:{let t=r.activeTextParts[e.id];t.state=`done`,t.providerMetadata=(u=e.providerMetadata)??t.providerMetadata,delete r.activeTextParts[e.id],c();break}case`reasoning-start`:{let t={type:`reasoning`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),c();break}case`reasoning-delta`:{let t=r.activeReasoningParts[e.id];t.text+=e.delta,t.providerMetadata=(d=e.providerMetadata)??t.providerMetadata,c();break}case`reasoning-end`:{let t=r.activeReasoningParts[e.id];t.providerMetadata=(f=e.providerMetadata)??t.providerMetadata,t.state=`done`,delete r.activeReasoningParts[e.id],c();break}case`file`:r.message.parts.push({type:`file`,mediaType:e.mediaType,url:e.url}),c();break;case`source-url`:r.message.parts.push({type:`source-url`,sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),c();break;case`source-document`:r.message.parts.push({type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),c();break;case`tool-input-start`:{let t=r.message.parts.filter(Kf);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic},e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];t.text+=e.inputTextDelta;let{value:n}=await Gf(t.text);t.dynamic?g({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n}):h({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n}),c();break}case`tool-input-available`:e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerMetadata:e.providerMetadata}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:e.dynamic?g({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerMetadata:e.providerMetadata}):h({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata}),c();break;case`tool-output-available`:if(e.dynamic){let t=m(e.toolCallId);g({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-available`,input:t.input,output:e.output,preliminary:e.preliminary})}else{let t=p(e.toolCallId);h({toolCallId:e.toolCallId,toolName:Yf(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary})}c();break;case`tool-output-error`:if(e.dynamic){let t=m(e.toolCallId);g({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText})}else{let t=p(e.toolCallId);h({toolCallId:e.toolCallId,toolName:Yf(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText})}c();break;case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:r.activeTextParts={},r.activeReasoningParts={};break;case`start`:e.messageId!=null&&(r.message.id=e.messageId),await _(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c();break;case`finish`:await _(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await _(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(Hf(e)){n?.[e.type]!=null&&await ds({value:e.data,schema:n[e.type]});let t=e;if(t.transient){o?.(t);break}let i=t.id==null?void 0:r.message.parts.find(e=>t.type===e.type&&t.id===e.id);i==null?r.message.parts.push(t):i.data=t.data,o?.(t),c()}}s.enqueue(e)})}}))}function $f({messageId:e,originalMessages:t=[],onFinish:n,onError:r,stream:i}){let a=t?.[t.length-1];a?.role===`assistant`?e=a.id:a=void 0;let o=!1,s=i.pipeThrough(new TransformStream({transform(t,n){if(t.type===`start`){let n=t;n.messageId==null&&e!=null&&(n.messageId=e)}t.type===`abort`&&(o=!0),n.enqueue(t)}}));if(n==null)return s;let c=Zf({lastMessage:a?structuredClone(a):void 0,messageId:e??``}),l=async e=>{await e({state:c,write:()=>{}})},u=!1,d=async()=>{if(u||!n)return;u=!0;let e=c.message.id===a?.id;await n({isAborted:o,isContinuation:e,responseMessage:c.message,messages:[...e?t.slice(0,-1):t,c.message]})};return Qf({stream:s,runUpdateMessageJob:l,onError:r}).pipeThrough(new TransformStream({transform(e,t){t.enqueue(e)},async cancel(){await d()},async flush(){await d()}}))}function ep({response:e,status:t,statusText:n,headers:r,stream:i,consumeSseStream:a}){let o=i.pipeThrough(new Rf);if(a){let[e,t]=o.tee();o=e,a({stream:t})}If({response:e,status:t,statusText:n,headers:Object.fromEntries(Pf(r,zf).entries()),stream:o.pipeThrough(new TextEncoderStream)})}function tp(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){var r;t=!0;try{n&&await(r=e.cancel)?.call(e)}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}async function np({stream:e,onError:t}){let n=e.getReader();try{for(;;){let{done:e}=await n.read();if(e)break}}catch(e){t?.(e)}finally{n.releaseLock()}}function rp(){let e,t,n=new Promise((n,r)=>{e=n,t=r});return{promise:n,resolve:e,reject:t}}function ip(){let e=[],t=null,n=!1,r=rp(),i=()=>{n=!0,r.resolve(),e.forEach(e=>e.cancel()),e=[],t?.close()},a=async()=>{if(n&&e.length===0){t?.close();return}if(e.length===0)return r=rp(),await r.promise,a();try{let{value:r,done:i}=await e[0].read();i?(e.shift(),e.length>0?await a():n&&t?.close()):t?.enqueue(r)}catch(n){t?.error(n),e.shift(),i()}};return{stream:new ReadableStream({start(e){t=e},pull:a,async cancel(){for(let t of e)await t.cancel();e=[],n=!0}}),addStream:t=>{if(n)throw Error(`Cannot add inner stream: outer stream is closed`);e.push(t.getReader()),r.resolve()},close:()=>{n=!0,r.resolve(),e.length===0&&t?.close()},terminate:i}}var ap=class{constructor(){this.status={type:`pending`},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise||=new Promise((e,t)=>{this.status.type===`resolved`?e(this.status.value):this.status.type===`rejected`&&t(this.status.error),this._resolve=e,this._reject=t}),this._promise}resolve(e){var t;this.status={type:`resolved`,value:e},this._promise&&((t=this._resolve)==null||t.call(this,e))}reject(e){var t;this.status={type:`rejected`,error:e},this._promise&&((t=this._reject)==null||t.call(this,e))}};function op(){var e,t;return(t=(e=globalThis==null?void 0:globalThis.performance)?.now())??Date.now()}function sp({tools:e,generatorStream:t,tracer:n,telemetry:r,system:i,messages:a,abortSignal:o,repairToolCall:s,experimental_context:c}){let l=null,u=new ReadableStream({start(e){l=e}}),d=new Set,f=new Map,p=!1,m;function h(){p&&d.size===0&&(m!=null&&l.enqueue(m),l.close())}let g=new TransformStream({async transform(t,u){let p=t.type;switch(p){case`stream-start`:case`text-start`:case`text-delta`:case`text-end`:case`reasoning-start`:case`reasoning-delta`:case`reasoning-end`:case`tool-input-start`:case`tool-input-delta`:case`tool-input-end`:case`source`:case`response-metadata`:case`error`:case`raw`:u.enqueue(t);break;case`file`:u.enqueue({type:`file`,file:new Tf({data:t.data,mediaType:t.mediaType})});break;case`finish`:m={type:`finish`,finishReason:t.finishReason,usage:t.usage,providerMetadata:t.providerMetadata};break;case`tool-call`:try{let p=await Ef({toolCall:t,tools:e,repairToolCall:s,system:i,messages:a});if(u.enqueue(p),p.invalid){l.enqueue({type:`tool-error`,toolCallId:p.toolCallId,toolName:p.toolName,input:p.input,error:Ho(p.error),dynamic:!0});break}let m=e[p.toolName];if(f.set(p.toolCallId,p.input),m.onInputAvailable!=null&&await m.onInputAvailable({input:p.input,toolCallId:p.toolCallId,messages:a,abortSignal:o,experimental_context:c}),m.execute!=null&&p.providerExecuted!==!0){let e=Vo();d.add(e),pf({name:`ai.toolCall`,attributes:hf({telemetry:r,attributes:{...sf({operationId:`ai.toolCall`,telemetry:r}),"ai.toolCall.name":p.toolName,"ai.toolCall.id":p.toolCallId,"ai.toolCall.args":{output:()=>JSON.stringify(p.input)}}}),tracer:n,fn:async t=>{let n;try{let e=Wc({execute:m.execute.bind(m),input:p.input,options:{toolCallId:p.toolCallId,messages:a,abortSignal:o,experimental_context:c}});for await(let t of e)l.enqueue({...p,type:`tool-result`,output:t.output,...t.type===`preliminary`&&{preliminary:!0}}),t.type===`final`&&(n=t.output)}catch(n){mf(t,n),l.enqueue({...p,type:`tool-error`,error:n}),d.delete(e),h();return}d.delete(e),h();try{t.setAttributes(hf({telemetry:r,attributes:{"ai.toolCall.result":{output:()=>JSON.stringify(n)}}}))}catch{}}})}}catch(e){l.enqueue({type:`error`,error:e})}break;case`tool-result`:{let e=t.toolName;t.isError?l.enqueue({type:`tool-error`,toolCallId:t.toolCallId,toolName:e,input:f.get(t.toolCallId),providerExecuted:t.providerExecuted,error:t.result}):u.enqueue({type:`tool-result`,toolCallId:t.toolCallId,toolName:e,input:f.get(t.toolCallId),output:t.result,providerExecuted:t.providerExecuted});break}default:{let e=p;throw Error(`Unhandled chunk type: ${e}`)}}},flush(){p=!0,h()}});return new ReadableStream({async start(e){return Promise.all([t.pipeThrough(g).pipeTo(new WritableStream({write(t){e.enqueue(t)},close(){}})),u.pipeTo(new WritableStream({write(t){e.enqueue(t)},close(){e.close()}}))])}})}var cp=Bo({prefix:`aitxt`,size:24});function lp({model:e,tools:t,toolChoice:n,system:r,prompt:i,messages:a,maxRetries:o,abortSignal:s,headers:c,stopWhen:l=kf(1),experimental_output:u,experimental_telemetry:d,prepareStep:f,providerOptions:p,experimental_activeTools:m,activeTools:h=m,experimental_repairToolCall:g,experimental_transform:_,experimental_download:v,includeRawChunks:y=!1,onChunk:b,onError:x=({error:e})=>{console.error(e)},onFinish:S,onAbort:C,onStepFinish:w,experimental_context:T,_internal:{now:E=op,generateId:D=cp,currentDate:O=()=>new Date}={},...k}){return new dp({model:Td(e),telemetry:d,headers:c,settings:k,maxRetries:o,abortSignal:s,system:r,prompt:i,messages:a,tools:t,toolChoice:n,transforms:yf(_),activeTools:h,repairToolCall:g,stopConditions:yf(l),output:u,providerOptions:p,prepareStep:f,includeRawChunks:y,onChunk:b,onError:x,onFinish:S,onAbort:C,onStepFinish:w,now:E,currentDate:O,generateId:D,experimental_context:T,download:v})}function up(e){if(!e)return new TransformStream({transform(e,t){t.enqueue({part:e,partialOutput:void 0})}});let t,n=``,r=``,i=``;function a({controller:e,partialOutput:n=void 0}){e.enqueue({part:{type:`text-delta`,id:t,text:r},partialOutput:n}),r=``}return new TransformStream({async transform(o,s){if(o.type===`finish-step`&&r.length>0&&a({controller:s}),o.type!==`text-delta`&&o.type!==`text-start`&&o.type!==`text-end`){s.enqueue({part:o,partialOutput:void 0});return}if(t==null)t=o.id;else if(o.id!==t){s.enqueue({part:o,partialOutput:void 0});return}if(o.type===`text-start`){s.enqueue({part:o,partialOutput:void 0});return}if(o.type===`text-end`){r.length>0&&a({controller:s}),s.enqueue({part:o,partialOutput:void 0});return}n+=o.text,r+=o.text;let c=await e.parsePartial({text:n});if(c!=null){let e=JSON.stringify(c.partial);e!==i&&(a({controller:s,partialOutput:c.partial}),i=e)}}})}var dp=class{constructor({model:e,telemetry:t,headers:n,settings:r,maxRetries:i,abortSignal:a,system:o,prompt:s,messages:c,tools:l,toolChoice:u,transforms:d,activeTools:f,repairToolCall:p,stopConditions:m,output:h,providerOptions:g,prepareStep:_,includeRawChunks:v,now:y,currentDate:b,generateId:x,onChunk:S,onError:C,onFinish:w,onAbort:T,onStepFinish:E,experimental_context:D,download:O}){this._totalUsage=new ap,this._finishReason=new ap,this._steps=new ap,this.output=h,this.includeRawChunks=v,this.tools=l;let k,A=[],j=[],ee,M,N={},P=[],F=[],I,L={},R={},te=new TransformStream({async transform(e,t){var n,r,i;t.enqueue(e);let{part:a}=e;if((a.type===`text-delta`||a.type===`reasoning-delta`||a.type===`source`||a.type===`tool-call`||a.type===`tool-result`||a.type===`tool-input-start`||a.type===`tool-input-delta`||a.type===`raw`)&&await S?.({chunk:a}),a.type===`error`&&await C({error:af(a.error)}),a.type===`text-start`&&(L[a.id]={type:`text`,text:``,providerMetadata:a.providerMetadata},A.push(L[a.id])),a.type===`text-delta`){let e=L[a.id];if(e==null){t.enqueue({part:{type:`error`,error:`text part ${a.id} not found`},partialOutput:void 0});return}e.text+=a.text,e.providerMetadata=(n=a.providerMetadata)??e.providerMetadata}if(a.type===`text-end`&&delete L[a.id],a.type===`reasoning-start`&&(R[a.id]={type:`reasoning`,text:``,providerMetadata:a.providerMetadata},A.push(R[a.id])),a.type===`reasoning-delta`){let e=R[a.id];if(e==null){t.enqueue({part:{type:`error`,error:`reasoning part ${a.id} not found`},partialOutput:void 0});return}e.text+=a.text,e.providerMetadata=(r=a.providerMetadata)??e.providerMetadata}if(a.type===`reasoning-end`){let e=R[a.id];if(e==null){t.enqueue({part:{type:`error`,error:`reasoning part ${a.id} not found`},partialOutput:void 0});return}e.providerMetadata=(i=a.providerMetadata)??e.providerMetadata,delete R[a.id]}if(a.type===`file`&&A.push({type:`file`,file:a.file}),a.type===`source`&&A.push(a),a.type===`tool-call`&&A.push(a),a.type===`tool-result`&&!a.preliminary&&A.push(a),a.type===`tool-error`&&A.push(a),a.type===`start-step`&&(N=a.request,P=a.warnings),a.type===`finish-step`){let e=Nf({content:A,tools:l}),t=new Of({content:A,finishReason:a.finishReason,usage:a.usage,warnings:P,request:N,response:{...a.response,messages:[...j,...e]},providerMetadata:a.providerMetadata});await E?.(t),fu(P),F.push(t),A=[],R={},L={},j.push(...e),k.resolve()}a.type===`finish`&&(M=a.totalUsage,ee=a.finishReason)},async flush(e){try{if(F.length===0){let e=new Wu({message:`No output generated. Check the stream for errors.`});ce._finishReason.reject(e),ce._totalUsage.reject(e),ce._steps.reject(e);return}let e=ee??`unknown`,n=M??{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};ce._finishReason.resolve(e),ce._totalUsage.resolve(n),ce._steps.resolve(F);let r=F[F.length-1];await w?.({finishReason:e,totalUsage:n,usage:r.usage,content:r.content,text:r.text,reasoningText:r.reasoningText,reasoning:r.reasoning,files:r.files,sources:r.sources,toolCalls:r.toolCalls,staticToolCalls:r.staticToolCalls,dynamicToolCalls:r.dynamicToolCalls,toolResults:r.toolResults,staticToolResults:r.staticToolResults,dynamicToolResults:r.dynamicToolResults,request:r.request,response:r.response,warnings:r.warnings,providerMetadata:r.providerMetadata,steps:F}),I.setAttributes(hf({telemetry:t,attributes:{"ai.response.finishReason":e,"ai.response.text":{output:()=>r.text},"ai.response.toolCalls":{output:()=>{var e;return(e=r.toolCalls)?.length?JSON.stringify(r.toolCalls):void 0}},"ai.response.providerMetadata":JSON.stringify(r.providerMetadata),"ai.usage.inputTokens":n.inputTokens,"ai.usage.outputTokens":n.outputTokens,"ai.usage.totalTokens":n.totalTokens,"ai.usage.reasoningTokens":n.reasoningTokens,"ai.usage.cachedInputTokens":n.cachedInputTokens}}))}catch(t){e.error(t)}finally{I.end()}}}),z=ip();this.addStream=z.addStream,this.closeStream=z.close;let B=z.stream.getReader(),ne=new ReadableStream({async start(e){e.enqueue({type:`start`})},async pull(e){function t(){T?.({steps:F}),e.enqueue({type:`abort`}),e.close()}try{let{done:n,value:r}=await B.read();if(n){e.close();return}if(a?.aborted){t();return}e.enqueue(r)}catch(n){Uo(n)&&a?.aborted?t():e.error(n)}},cancel(e){return z.stream.cancel(e)}});for(let e of d)ne=ne.pipeThrough(e({tools:l,stopStream(){z.terminate()}}));this.baseStream=ne.pipeThrough(up(h)).pipeThrough(te);let{maxRetries:re,retry:ie}=Cf({maxRetries:i,abortSignal:a}),ae=ff(t),oe=Vd(r),se=cf({model:e,telemetry:t,headers:n,settings:{...oe,maxRetries:re}}),ce=this;pf({name:`ai.streamText`,attributes:hf({telemetry:t,attributes:{...sf({operationId:`ai.streamText`,telemetry:t}),...se,"ai.prompt":{input:()=>JSON.stringify({system:o,prompt:s,messages:c})}}}),tracer:ae,endWhenDone:!1,fn:async r=>{I=r;async function i({currentStep:r,responseMessages:d,usage:v}){var S,C,w,T,E;let A=ce.includeRawChunks;k=new ap;let j=await rf({system:o,prompt:s,messages:c}),ee=[...j.messages,...d],M=await _?.({model:e,steps:F,stepNumber:F.length,messages:ee}),N=await Ld({prompt:{system:(S=M?.system)??j.system,messages:(C=M?.messages)??ee},supportedUrls:await e.supportedUrls,download:O}),P=Td((w=M?.model)??e),{toolChoice:I,tools:L}=Ud({tools:l,toolChoice:(T=M?.toolChoice)??u,activeTools:(E=M?.activeTools)??f}),{result:{stream:R,response:te,request:z},doStreamSpan:B,startTimestampMs:ne}=await ie(()=>pf({name:`ai.streamText.doStream`,attributes:hf({telemetry:t,attributes:{...sf({operationId:`ai.streamText.doStream`,telemetry:t}),...se,"ai.model.provider":P.provider,"ai.model.id":P.modelId,"ai.prompt.messages":{input:()=>gf(N)},"ai.prompt.tools":{input:()=>L?.map(e=>JSON.stringify(e))},"ai.prompt.toolChoice":{input:()=>I==null?void 0:JSON.stringify(I)},"gen_ai.system":P.provider,"gen_ai.request.model":P.modelId,"gen_ai.request.frequency_penalty":oe.frequencyPenalty,"gen_ai.request.max_tokens":oe.maxOutputTokens,"gen_ai.request.presence_penalty":oe.presencePenalty,"gen_ai.request.stop_sequences":oe.stopSequences,"gen_ai.request.temperature":oe.temperature,"gen_ai.request.top_k":oe.topK,"gen_ai.request.top_p":oe.topP}}),tracer:ae,endWhenDone:!1,fn:async e=>({startTimestampMs:y(),doStreamSpan:e,result:await P.doStream({...oe,tools:L,toolChoice:I,responseFormat:h?.responseFormat,prompt:N,providerOptions:g,abortSignal:a,headers:n,includeRawChunks:A})})})),re=sp({tools:l,generatorStream:R,tracer:ae,telemetry:t,system:o,messages:ee,repairToolCall:p,abortSignal:a,experimental_context:D}),le=z??{},ue=[],de=[],fe,V={},H=`unknown`,pe={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},me,he=!0,ge={id:x(),timestamp:b(),modelId:e.modelId},_e=``;ce.addStream(re.pipeThrough(new TransformStream({async transform(e,t){var n,r,i,o;if(e.type===`stream-start`){fe=e.warnings;return}if(he){let e=y()-ne;he=!1,B.addEvent(`ai.stream.firstChunk`,{"ai.response.msToFirstChunk":e}),B.setAttributes({"ai.response.msToFirstChunk":e}),t.enqueue({type:`start-step`,request:le,warnings:fe??[]})}let s=e.type;switch(s){case`text-start`:case`text-end`:t.enqueue(e);break;case`text-delta`:e.delta.length>0&&(t.enqueue({type:`text-delta`,id:e.id,text:e.delta,providerMetadata:e.providerMetadata}),_e+=e.delta);break;case`reasoning-start`:case`reasoning-end`:t.enqueue(e);break;case`reasoning-delta`:t.enqueue({type:`reasoning-delta`,id:e.id,text:e.delta,providerMetadata:e.providerMetadata});break;case`tool-call`:t.enqueue(e),ue.push(e);break;case`tool-result`:t.enqueue(e),e.preliminary||de.push(e);break;case`tool-error`:t.enqueue(e),de.push(e);break;case`response-metadata`:ge={id:(n=e.id)??ge.id,timestamp:(r=e.timestamp)??ge.timestamp,modelId:(i=e.modelId)??ge.modelId};break;case`finish`:{pe=e.usage,H=e.finishReason,me=e.providerMetadata;let t=y()-ne;B.addEvent(`ai.stream.finish`),B.setAttributes({"ai.response.msToFinish":t,"ai.response.avgOutputTokensPerSecond":1e3*((o=pe.outputTokens)??0)/t});break}case`file`:t.enqueue(e);break;case`source`:t.enqueue(e);break;case`tool-input-start`:{V[e.id]=e.toolName;let n=l?.[e.toolName];n?.onInputStart!=null&&await n.onInputStart({toolCallId:e.id,messages:ee,abortSignal:a,experimental_context:D}),t.enqueue({...e,dynamic:n?.type===`dynamic`});break}case`tool-input-end`:delete V[e.id],t.enqueue(e);break;case`tool-input-delta`:{let n=V[e.id],r=l?.[n];r?.onInputDelta!=null&&await r.onInputDelta({inputTextDelta:e.delta,toolCallId:e.id,messages:ee,abortSignal:a,experimental_context:D}),t.enqueue(e);break}case`error`:t.enqueue(e),H=`error`;break;case`raw`:A&&t.enqueue(e);break;default:{let e=s;throw Error(`Unknown chunk type: ${e}`)}}},async flush(e){let n=ue.length>0?JSON.stringify(ue):void 0;try{B.setAttributes(hf({telemetry:t,attributes:{"ai.response.finishReason":H,"ai.response.text":{output:()=>_e},"ai.response.toolCalls":{output:()=>n},"ai.response.id":ge.id,"ai.response.model":ge.modelId,"ai.response.timestamp":ge.timestamp.toISOString(),"ai.response.providerMetadata":JSON.stringify(me),"ai.usage.inputTokens":pe.inputTokens,"ai.usage.outputTokens":pe.outputTokens,"ai.usage.totalTokens":pe.totalTokens,"ai.usage.reasoningTokens":pe.reasoningTokens,"ai.usage.cachedInputTokens":pe.cachedInputTokens,"gen_ai.response.finish_reasons":[H],"gen_ai.response.id":ge.id,"gen_ai.response.model":ge.modelId,"gen_ai.usage.input_tokens":pe.inputTokens,"gen_ai.usage.output_tokens":pe.outputTokens}}))}catch{}finally{B.end()}e.enqueue({type:`finish-step`,finishReason:H,usage:pe,providerMetadata:me,response:{...ge,headers:te?.headers}});let a=_f(v,pe);await k.promise;let o=ue.filter(e=>e.providerExecuted!==!0),s=de.filter(e=>e.providerExecuted!==!0);if(o.length>0&&s.length===o.length&&!await Af({stopConditions:m,steps:F})){d.push(...Nf({content:F[F.length-1].content,tools:l}));try{await i({currentStep:r+1,responseMessages:d,usage:a})}catch(t){e.enqueue({type:`error`,error:t}),ce.closeStream()}}else e.enqueue({type:`finish`,finishReason:H,totalUsage:a}),ce.closeStream()}})))}await i({currentStep:0,responseMessages:[],usage:{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0}})}}).catch(e=>{ce.addStream(new ReadableStream({start(t){t.enqueue({type:`error`,error:e}),t.close()}})),ce.closeStream()})}get steps(){return this.consumeStream(),this._steps.promise}get finalStep(){return this.steps.then(e=>e[e.length-1])}get content(){return this.finalStep.then(e=>e.content)}get warnings(){return this.finalStep.then(e=>e.warnings)}get providerMetadata(){return this.finalStep.then(e=>e.providerMetadata)}get text(){return this.finalStep.then(e=>e.text)}get reasoningText(){return this.finalStep.then(e=>e.reasoningText)}get reasoning(){return this.finalStep.then(e=>e.reasoning)}get sources(){return this.finalStep.then(e=>e.sources)}get files(){return this.finalStep.then(e=>e.files)}get toolCalls(){return this.finalStep.then(e=>e.toolCalls)}get staticToolCalls(){return this.finalStep.then(e=>e.staticToolCalls)}get dynamicToolCalls(){return this.finalStep.then(e=>e.dynamicToolCalls)}get toolResults(){return this.finalStep.then(e=>e.toolResults)}get staticToolResults(){return this.finalStep.then(e=>e.staticToolResults)}get dynamicToolResults(){return this.finalStep.then(e=>e.dynamicToolResults)}get usage(){return this.finalStep.then(e=>e.usage)}get request(){return this.finalStep.then(e=>e.request)}get response(){return this.finalStep.then(e=>e.response)}get totalUsage(){return this.consumeStream(),this._totalUsage.promise}get finishReason(){return this.consumeStream(),this._finishReason.promise}teeStream(){let[e,t]=this.baseStream.tee();return this.baseStream=t,e}get textStream(){return tp(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){e.type===`text-delta`&&t.enqueue(e.text)}})))}get fullStream(){return tp(this.teeStream().pipeThrough(new TransformStream({transform({part:e},t){t.enqueue(e)}})))}async consumeStream(e){var t;try{await np({stream:this.fullStream,onError:e?.onError})}catch(n){(t=e?.onError)==null||t.call(e,n)}}get experimental_partialOutputStream(){if(this.output==null)throw new cu;return tp(this.teeStream().pipeThrough(new TransformStream({transform({partialOutput:e},t){e!=null&&t.enqueue(e)}})))}toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:i=!0,sendSources:a=!1,sendStart:o=!0,sendFinish:s=!0,onError:c=ka}={}){let l=t==null?void 0:Vf({originalMessages:e,responseMessageId:t}),u={},d=e=>{var t,n;let r=u[e],i=(n=(t=this.tools)?.[r])?.type===`dynamic`;return i?!0:void 0},f=this.fullStream.pipeThrough(new TransformStream({transform:async(e,t)=>{let n=r?.({part:e}),f=e.type;switch(f){case`text-start`:t.enqueue({type:`text-start`,id:e.id,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`text-delta`:t.enqueue({type:`text-delta`,id:e.id,delta:e.text,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`text-end`:t.enqueue({type:`text-end`,id:e.id,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`reasoning-start`:t.enqueue({type:`reasoning-start`,id:e.id,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`reasoning-delta`:i&&t.enqueue({type:`reasoning-delta`,id:e.id,delta:e.text,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`reasoning-end`:t.enqueue({type:`reasoning-end`,id:e.id,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`file`:t.enqueue({type:`file`,mediaType:e.file.mediaType,url:`data:${e.file.mediaType};base64,${e.file.base64}`});break;case`source`:a&&e.sourceType===`url`&&t.enqueue({type:`source-url`,sourceId:e.id,url:e.url,title:e.title,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}}),a&&e.sourceType===`document`&&t.enqueue({type:`source-document`,sourceId:e.id,mediaType:e.mediaType,title:e.title,filename:e.filename,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}});break;case`tool-input-start`:{u[e.id]=e.toolName;let n=d(e.id);t.enqueue({type:`tool-input-start`,toolCallId:e.id,toolName:e.toolName,...e.providerExecuted==null?{}:{providerExecuted:e.providerExecuted},...n==null?{}:{dynamic:n}});break}case`tool-input-delta`:t.enqueue({type:`tool-input-delta`,toolCallId:e.id,inputTextDelta:e.delta});break;case`tool-call`:{u[e.toolCallId]=e.toolName;let n=d(e.toolCallId);e.invalid?t.enqueue({type:`tool-input-error`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...e.providerExecuted==null?{}:{providerExecuted:e.providerExecuted},...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata},...n==null?{}:{dynamic:n},errorText:c(e.error)}):t.enqueue({type:`tool-input-available`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input,...e.providerExecuted==null?{}:{providerExecuted:e.providerExecuted},...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata},...n==null?{}:{dynamic:n}});break}case`tool-result`:{let n=d(e.toolCallId);t.enqueue({type:`tool-output-available`,toolCallId:e.toolCallId,output:e.output,...e.providerExecuted==null?{}:{providerExecuted:e.providerExecuted},...e.preliminary==null?{}:{preliminary:e.preliminary},...n==null?{}:{dynamic:n}});break}case`tool-error`:{let n=d(e.toolCallId);t.enqueue({type:`tool-output-error`,toolCallId:e.toolCallId,errorText:c(e.error),...e.providerExecuted==null?{}:{providerExecuted:e.providerExecuted},...n==null?{}:{dynamic:n}});break}case`error`:t.enqueue({type:`error`,errorText:c(e.error)});break;case`start-step`:t.enqueue({type:`start-step`});break;case`finish-step`:t.enqueue({type:`finish-step`});break;case`start`:o&&t.enqueue({type:`start`,...n==null?{}:{messageMetadata:n},...l==null?{}:{messageId:l}});break;case`finish`:s&&t.enqueue({type:`finish`,...n==null?{}:{messageMetadata:n}});break;case`abort`:t.enqueue(e);break;case`tool-input-end`:break;case`raw`:break;default:{let e=f;throw Error(`Unknown chunk type: ${e}`)}}n!=null&&f!==`start`&&f!==`finish`&&t.enqueue({type:`message-metadata`,messageMetadata:n})}}));return tp($f({stream:f,messageId:l??t?.(),originalMessages:e,onFinish:n,onError:c}))}pipeUIMessageStreamToResponse(e,{originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:i,sendReasoning:a,sendSources:o,sendFinish:s,sendStart:c,onError:l,...u}={}){ep({response:e,stream:this.toUIMessageStream({originalMessages:t,generateMessageId:n,onFinish:r,messageMetadata:i,sendReasoning:a,sendSources:o,sendFinish:s,sendStart:c,onError:l}),...u})}pipeTextStreamToResponse(e,t){Lf({response:e,textStream:this.textStream,...t})}toUIMessageStreamResponse({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:i,sendSources:a,sendFinish:o,sendStart:s,onError:c,...l}={}){return Bf({stream:this.toUIMessageStream({originalMessages:e,generateMessageId:t,onFinish:n,messageMetadata:r,sendReasoning:i,sendSources:a,sendFinish:o,sendStart:s,onError:c}),...l})}toTextStreamResponse(e){return Ff({textStream:this.textStream,...e})}};Bo({prefix:`aiobj`,size:24}),Bo({prefix:`aiobj`,size:24});var fp={};ru(fp,{object:()=>mp,text:()=>pp});var pp=()=>({type:`text`,responseFormat:{type:`text`},async parsePartial({text:e}){return{partial:e}},async parseOutput({text:e}){return e}}),mp=({schema:e})=>{let t=Ic(e);return{type:`object`,responseFormat:{type:`json`,schema:t.jsonSchema},async parsePartial({text:e}){let t=await Gf(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value};default:{let e=t.state;throw Error(`Unsupported parse state: ${e}`)}}},async parseOutput({text:e},n){let r=await ms({text:e});if(!r.success)throw new zu({message:`No object generated: could not parse the response.`,cause:r.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=await fs({value:r.value,schema:t});if(!i.success)throw new zu({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.value}}},hp=`AI_NoSuchProviderError`,gp=`vercel.ai.error.${hp}`,_p=Symbol.for(gp),vp;vp=_p;var yp=V.looseObject({name:V.string(),version:V.string()}),bp=V.looseObject({_meta:V.optional(V.object({}).loose())}),xp=bp,Sp=V.object({method:V.string(),params:V.optional(bp)}),Cp=V.looseObject({experimental:V.optional(V.object({}).loose()),logging:V.optional(V.object({}).loose()),prompts:V.optional(V.looseObject({listChanged:V.optional(V.boolean())})),resources:V.optional(V.looseObject({subscribe:V.optional(V.boolean()),listChanged:V.optional(V.boolean())})),tools:V.optional(V.looseObject({listChanged:V.optional(V.boolean())}))});xp.extend({protocolVersion:V.string(),capabilities:Cp,serverInfo:yp,instructions:V.optional(V.string())});var wp=xp.extend({nextCursor:V.optional(V.string())}),Tp=V.object({name:V.string(),description:V.optional(V.string()),inputSchema:V.object({type:V.literal(`object`),properties:V.optional(V.object({}).loose())}).loose()}).loose();wp.extend({tools:V.array(Tp)});var Ep=V.object({type:V.literal(`text`),text:V.string()}).loose(),Dp=V.object({type:V.literal(`image`),data:V.base64(),mimeType:V.string()}).loose(),Op=V.object({uri:V.string(),mimeType:V.optional(V.string())}).loose(),kp=Op.extend({text:V.string()}),Ap=Op.extend({blob:V.base64()}),jp=V.object({type:V.literal(`resource`),resource:V.union([kp,Ap])}).loose();xp.extend({content:V.array(V.union([Ep,Dp,jp])),isError:V.boolean().default(!1).optional()}).or(xp.extend({toolResult:V.unknown()}));var Mp=`2.0`,Np=V.object({jsonrpc:V.literal(Mp),id:V.union([V.string(),V.number().int()])}).merge(Sp).strict(),Pp=V.object({jsonrpc:V.literal(Mp),id:V.union([V.string(),V.number().int()]),result:xp}).strict(),Fp=V.object({jsonrpc:V.literal(Mp),id:V.union([V.string(),V.number().int()]),error:V.object({code:V.number().int(),message:V.string(),data:V.optional(V.unknown())})}).strict(),Ip=V.object({jsonrpc:V.literal(Mp)}).merge(V.object({method:V.string(),params:V.optional(bp)})).strict();V.union([Np,Ip,Pp,Fp]);var Lp=V.object({type:V.literal(`text`),text:V.string(),state:V.enum([`streaming`,`done`]).optional(),providerMetadata:J.optional()}),Rp=V.object({type:V.literal(`reasoning`),text:V.string(),state:V.enum([`streaming`,`done`]).optional(),providerMetadata:J.optional()}),zp=V.object({type:V.literal(`source-url`),sourceId:V.string(),url:V.string(),title:V.string().optional(),providerMetadata:J.optional()}),Bp=V.object({type:V.literal(`source-document`),sourceId:V.string(),mediaType:V.string(),title:V.string(),filename:V.string().optional(),providerMetadata:J.optional()}),Vp=V.object({type:V.literal(`file`),mediaType:V.string(),filename:V.string().optional(),url:V.string(),providerMetadata:J.optional()}),Hp=V.object({type:V.literal(`step-start`)}),Up=V.object({type:V.string().startsWith(`data-`),id:V.string().optional(),data:V.unknown()}),Wp=[V.object({type:V.literal(`dynamic-tool`),toolName:V.string(),toolCallId:V.string(),state:V.literal(`input-streaming`),input:V.unknown().optional(),output:V.never().optional(),errorText:V.never().optional()}),V.object({type:V.literal(`dynamic-tool`),toolName:V.string(),toolCallId:V.string(),state:V.literal(`input-available`),input:V.unknown(),output:V.never().optional(),errorText:V.never().optional(),callProviderMetadata:J.optional()}),V.object({type:V.literal(`dynamic-tool`),toolName:V.string(),toolCallId:V.string(),state:V.literal(`output-available`),input:V.unknown(),output:V.unknown(),errorText:V.never().optional(),callProviderMetadata:J.optional(),preliminary:V.boolean().optional()}),V.object({type:V.literal(`dynamic-tool`),toolName:V.string(),toolCallId:V.string(),state:V.literal(`output-error`),input:V.unknown(),output:V.never().optional(),errorText:V.string(),callProviderMetadata:J.optional()})],Gp=[V.object({type:V.string().startsWith(`tool-`),toolCallId:V.string(),state:V.literal(`input-streaming`),input:V.unknown().optional(),output:V.never().optional(),errorText:V.never().optional()}),V.object({type:V.string().startsWith(`tool-`),toolCallId:V.string(),state:V.literal(`input-available`),input:V.unknown(),output:V.never().optional(),errorText:V.never().optional(),callProviderMetadata:J.optional()}),V.object({type:V.string().startsWith(`tool-`),toolCallId:V.string(),state:V.literal(`output-available`),input:V.unknown(),output:V.unknown(),errorText:V.never().optional(),callProviderMetadata:J.optional(),preliminary:V.boolean().optional()}),V.object({type:V.string().startsWith(`tool-`),toolCallId:V.string(),state:V.literal(`output-error`),input:V.unknown(),output:V.never().optional(),errorText:V.string(),callProviderMetadata:J.optional()})];V.object({id:V.string(),role:V.enum([`system`,`user`,`assistant`]),metadata:V.unknown().optional(),parts:V.array(V.union([Lp,Rp,zp,Bp,Vp,Hp,Up,...Wp,...Gp]))});function Kp({message:e,stream:t,onError:n,terminateOnError:r=!1}){var i;let a,o=!1,s=new ReadableStream({start(e){a=e}}),c=Zf({messageId:(i=e?.id)??``,lastMessage:e}),l=e=>{n?.(e),!o&&r&&(o=!0,a?.error(e))};return np({stream:Qf({stream:t,runUpdateMessageJob(e){return e({state:c,write:()=>{a?.enqueue(structuredClone(c.message))}})},onError:l}),onError:l}).finally(()=>{o||a?.close()}),tp(s)}var qp=V.object({type:V.literal(`error`),error:V.object({type:V.string(),message:V.string()})}),Jp=Ts({errorSchema:qp,errorToMessage:e=>e.error.message}),Yp=V.object({citations:V.object({enabled:V.boolean()}).optional(),title:V.string().optional(),context:V.string().optional()}),Xp=V.object({sendReasoning:V.boolean().optional(),thinking:V.object({type:V.union([V.literal(`enabled`),V.literal(`disabled`)]),budgetTokens:V.number().optional()}).optional(),disableParallelToolUse:V.boolean().optional()});function Zp(e){var t;let n=e?.anthropic,r=(t=n?.cacheControl)??n?.cache_control;return r}var Qp=V.object({maxUses:V.number().optional(),allowedDomains:V.array(V.string()).optional(),blockedDomains:V.array(V.string()).optional(),userLocation:V.object({type:V.literal(`approximate`),city:V.string().optional(),region:V.string().optional(),country:V.string().optional(),timezone:V.string().optional()}).optional()}),$p=V.array(V.object({url:V.string(),title:V.string(),pageAge:V.string().nullable(),encryptedContent:V.string(),type:V.string()})),em=Cs({id:`anthropic.web_search_20250305`,name:`web_search`,inputSchema:V.object({query:V.string()}),outputSchema:$p}),tm=(e={})=>em(e);function nm(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`web_search_20250305`}function rm({tools:e,toolChoice:t,disableParallelToolUse:n}){e=e?.length?e:void 0;let r=[],i=new Set;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};let a=[];for(let t of e){if(nm(t)){a.push(t);continue}switch(t.type){case`function`:let e=Zp(t.providerOptions);a.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e});break;case`provider-defined`:switch(t.id){case`anthropic.computer_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.computer_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber});break;case`anthropic.text_editor_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_editor`,type:`text_editor_20250124`});break;case`anthropic.text_editor_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`str_replace_editor`,type:`text_editor_20241022`});break;case`anthropic.text_editor_20250429`:i.add(`computer-use-2025-01-24`),a.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`});break;case`anthropic.bash_20250124`:i.add(`computer-use-2025-01-24`),a.push({name:`bash`,type:`bash_20250124`});break;case`anthropic.bash_20241022`:i.add(`computer-use-2024-10-22`),a.push({name:`bash`,type:`bash_20241022`});break;case`anthropic.web_search_20250305`:{let e=Qp.parse(t.args);a.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation});break}case`anthropic.code_execution_20250522`:i.add(`code-execution-2025-05-22`),a.push({type:`code_execution_20250522`,name:`code_execution`});break;default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}}if(t==null)return{tools:a,toolChoice:n?{type:`auto`,disable_parallel_tool_use:n}:void 0,toolWarnings:r,betas:i};let o=t.type;switch(o){case`auto`:return{tools:a,toolChoice:{type:`auto`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`required`:return{tools:a,toolChoice:{type:`any`,disable_parallel_tool_use:n},toolWarnings:r,betas:i};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:r,betas:i};case`tool`:return{tools:a,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:n},toolWarnings:r,betas:i};default:{let e=o;throw new Ao({functionality:`tool choice type: ${e}`})}}}var im=V.object({type:V.literal(`code_execution_result`),stdout:V.string(),stderr:V.string(),return_code:V.number()}),am=Cs({id:`anthropic.code_execution_20250522`,name:`code_execution`,inputSchema:V.object({code:V.string()}),outputSchema:im}),om=(e={})=>am(e);function sm(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new Ao({functionality:`URL-based text documents are not supported for citations`}):new Ao({functionality:`unsupported data type for text documents: ${typeof e}`})}async function cm({prompt:e,sendReasoning:t,warnings:n}){var r,i,a,o,s;let c=new Set,l=lm(e),u,d=[];async function f(e){var t,n;let r=await _s({provider:`anthropic`,providerOptions:e,schema:Yp});return(n=(t=r?.citations)?.enabled)??!1}async function p(e){let t=await _s({provider:`anthropic`,providerOptions:e,schema:Yp});return{title:t?.title,context:t?.context}}for(let e=0;e<l.length;e++){let m=l[e],h=e===l.length-1,g=m.type;switch(g){case`system`:if(u!=null)throw new Ao({functionality:`Multiple system messages that are separated by user/assistant messages`});u=m.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:Zp(t)}));break;case`user`:{let e=[];for(let t of m.messages){let{role:n,content:s}=t;switch(n){case`user`:for(let n=0;n<s.length;n++){let o=s[n],l=n===s.length-1,u=(r=Zp(o.providerOptions))??(l?Zp(t.providerOptions):void 0);switch(o.type){case`text`:e.push({type:`text`,text:o.text,cache_control:u});break;case`file`:if(o.mediaType.startsWith(`image/`))e.push({type:`image`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:o.mediaType===`image/*`?`image/jpeg`:o.mediaType,data:Vc(o.data)},cache_control:u});else if(o.mediaType===`application/pdf`){c.add(`pdfs-2024-09-25`);let t=await f(o.providerOptions),n=await p(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:Vc(o.data)},title:(i=n.title)??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else if(o.mediaType===`text/plain`){let t=await f(o.providerOptions),n=await p(o.providerOptions);e.push({type:`document`,source:o.data instanceof URL?{type:`url`,url:o.data.toString()}:{type:`text`,media_type:`text/plain`,data:sm(o.data)},title:(a=n.title)??o.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new Ao({functionality:`media type: ${o.mediaType}`});break}}break;case`tool`:for(let n=0;n<s.length;n++){let r=s[n],i=n===s.length-1,a=(o=Zp(r.providerOptions))??(i?Zp(t.providerOptions):void 0),c=r.output,l;switch(c.type){case`content`:l=c.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text,cache_control:void 0};case`media`:if(e.mediaType.startsWith(`image/`))return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data},cache_control:void 0};throw new Ao({functionality:`media type: ${e.mediaType}`})}});break;case`text`:case`error-text`:l=c.value;break;case`json`:case`error-json`:default:l=JSON.stringify(c.value);break}e.push({type:`tool_result`,tool_use_id:r.toolCallId,content:l,is_error:c.type===`error-text`||c.type===`error-json`?!0:void 0,cache_control:a})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}}d.push({role:`user`,content:e});break}case`assistant`:{let e=[];for(let r=0;r<m.messages.length;r++){let i=m.messages[r],a=r===m.messages.length-1,{content:o}=i;for(let r=0;r<o.length;r++){let c=o[r],l=r===o.length-1,u=(s=Zp(c.providerOptions))??(l?Zp(i.providerOptions):void 0);switch(c.type){case`text`:e.push({type:`text`,text:h&&a&&l?c.text.trim():c.text,cache_control:u});break;case`reasoning`:if(t){let t=await _s({provider:`anthropic`,providerOptions:c.providerOptions,schema:vm});t==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?n.push({type:`other`,message:`unsupported reasoning metadata`}):e.push({type:`redacted_thinking`,data:t.redactedData,cache_control:u}):e.push({type:`thinking`,thinking:c.text,signature:t.signature,cache_control:u})}else n.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(c.providerExecuted){if(c.toolName===`web_search`){e.push({type:`server_tool_use`,id:c.toolCallId,name:`web_search`,input:c.input,cache_control:u});break}if(c.toolName===`code_execution`){e.push({type:`server_tool_use`,id:c.toolCallId,name:`code_execution`,input:c.input,cache_control:u});break}n.push({type:`other`,message:`provider executed tool call for tool ${c.toolName} is not supported`});break}e.push({type:`tool_use`,id:c.toolCallId,name:c.toolName,input:c.input,cache_control:u});break;case`tool-result`:if(c.toolName===`web_search`){let t=c.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let r=$p.parse(t.value);e.push({type:`web_search_tool_result`,tool_use_id:c.toolCallId,content:r.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:u});break}if(c.toolName===`code_execution`){let t=c.output;if(t.type!==`json`){n.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${c.toolName} is not supported`});break}let r=im.parse(t.value);e.push({type:`code_execution_tool_result`,tool_use_id:c.toolCallId,content:{type:r.type,stdout:r.stdout,stderr:r.stderr,return_code:r.return_code},cache_control:u});break}n.push({type:`other`,message:`provider executed tool result for tool ${c.toolName} is not supported`});break}}}d.push({role:`assistant`,content:e});break}default:{let e=g;throw Error(`content type: ${e}`)}}}return{prompt:{system:u,messages:d},betas:c}}function lm(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function um({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;default:return`unknown`}}var dm={webSearchResult:V.object({type:V.literal(`web_search_result_location`),cited_text:V.string(),url:V.string(),title:V.string(),encrypted_index:V.string()}),pageLocation:V.object({type:V.literal(`page_location`),cited_text:V.string(),document_index:V.number(),document_title:V.string().nullable(),start_page_number:V.number(),end_page_number:V.number()}),charLocation:V.object({type:V.literal(`char_location`),cited_text:V.string(),document_index:V.number(),document_title:V.string().nullable(),start_char_index:V.number(),end_char_index:V.number()})},fm=V.discriminatedUnion(`type`,[dm.webSearchResult,dm.pageLocation,dm.charLocation]);V.discriminatedUnion(`type`,[dm.pageLocation,dm.charLocation]);function pm(e,t,n,r){if(e.type===`page_location`||e.type===`char_location`){let i=mm(e,t,n);i&&r(i)}}function mm(e,t,n){var r;let i=t[e.document_index];if(!i)return null;let a=e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index};return{type:`source`,sourceType:`document`,id:n(),mediaType:i.mediaType,title:(r=e.document_title)??i.title,filename:i.filename,providerMetadata:{anthropic:a}}}var hm=class{constructor(e,t){this.specificationVersion=`v2`;var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)??Vo}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)?.call(e))??{}}async getArgs({prompt:e,maxOutputTokens:t=4096,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){var p,m,h;let g=[];a!=null&&g.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&g.push({type:`unsupported-setting`,setting:`presencePenalty`}),l!=null&&g.push({type:`unsupported-setting`,setting:`seed`}),c?.type===`json`&&(c.schema==null?g.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}):u!=null&&g.push({type:`unsupported-setting`,setting:`tools`,details:`JSON response format does not support tools. The provided tools are ignored.`}));let _=c?.type===`json`&&c.schema!=null?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:c.schema}:void 0,v=await _s({provider:`anthropic`,providerOptions:f,schema:Xp}),{prompt:y,betas:b}=await cm({prompt:e,sendReasoning:(p=v?.sendReasoning)??!0,warnings:g}),x=(m=v?.thinking)?.type===`enabled`,S=(h=v?.thinking)?.budgetTokens,C={model:this.modelId,max_tokens:t,temperature:n,top_k:i,top_p:r,stop_sequences:s,...x&&{thinking:{type:`enabled`,budget_tokens:S}},system:y.system,messages:y.messages};if(x){if(S==null)throw new Ao({functionality:`thinking requires a budget`});C.temperature!=null&&(C.temperature=void 0,g.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported when thinking is enabled`})),i!=null&&(C.top_k=void 0,g.push({type:`unsupported-setting`,setting:`topK`,details:`topK is not supported when thinking is enabled`})),r!=null&&(C.top_p=void 0,g.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported when thinking is enabled`})),C.max_tokens=t+S}let{tools:w,toolChoice:T,toolWarnings:E,betas:D}=rm(_==null?{tools:u??[],toolChoice:d,disableParallelToolUse:v?.disableParallelToolUse}:{tools:[_],toolChoice:{type:`tool`,toolName:_.name},disableParallelToolUse:!0});return{args:{...C,tools:w,tool_choice:T},warnings:[...g,...E],betas:new Set([...b,...D]),usesJsonResponseTool:_!=null}}async getHeaders({betas:e,headers:t}){return Io(await ws(this.config.headers),e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{},t)}buildRequestUrl(e){var t,n,r;return(r=(n=(t=this.config).buildRequestUrl)?.call(t,this.config.baseURL,e))??`${this.config.baseURL}/messages`}transformRequestBody(e){var t,n,r;return(r=(n=(t=this.config).transformRequestBody)?.call(t,e))??e}extractCitationDocuments(e){let t=e=>{var t,n;if(e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`)return!1;let r=(t=e.providerOptions)?.anthropic,i=r?.citations;return(n=i?.enabled)??!1};return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(t).map(e=>{var t;let n=e;return{title:(t=n.filename)??`Untitled Document`,filename:n.filename,mediaType:n.mediaType}})}async doGenerate(e){var t,n,r,i,a;let{args:o,warnings:s,betas:c,usesJsonResponseTool:l}=await this.getArgs(e),u=this.extractCitationDocuments(e.prompt),{responseHeaders:d,value:f,rawValue:p}=await K({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:c,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:Jp,successfulResponseHandler:Ds(gm),abortSignal:e.abortSignal,fetch:this.config.fetch}),m=[];for(let e of f.content)switch(e.type){case`text`:if(!l&&(m.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations)pm(t,u,this.generateId,e=>m.push(e));break;case`thinking`:m.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:m.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:m.push(l?{type:`text`,text:JSON.stringify(e.input)}:{type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:(e.name===`web_search`||e.name===`code_execution`)&&m.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0});break;case`web_search_tool_result`:if(Array.isArray(e.content)){m.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:(t=e.page_age)??null,encryptedContent:e.encrypted_content,type:e.type}}),providerExecuted:!0});for(let n of e.content)m.push({type:`source`,sourceType:`url`,id:this.generateId(),url:n.url,title:n.title,providerMetadata:{anthropic:{pageAge:(t=n.page_age)??null}}})}else m.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?m.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&m.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});break}return{content:m,finishReason:um({finishReason:f.stop_reason,isJsonResponseFromTool:l}),usage:{inputTokens:f.usage.input_tokens,outputTokens:f.usage.output_tokens,totalTokens:f.usage.input_tokens+f.usage.output_tokens,cachedInputTokens:(n=f.usage.cache_read_input_tokens)??void 0},request:{body:o},response:{id:(r=f.id)??void 0,modelId:(i=f.model)??void 0,headers:d,body:p},warnings:s,providerMetadata:{anthropic:{usage:f.usage,cacheCreationInputTokens:(a=f.usage.cache_creation_input_tokens)??null}}}}async doStream(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i}=await this.getArgs(e),a=this.extractCitationDocuments(e.prompt),o={...t,stream:!0},{responseHeaders:s,value:c}=await K({url:this.buildRequestUrl(!0),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(o),failedResponseHandler:Jp,successfulResponseHandler:Es(_m),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=`unknown`,u={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},d={},f,p,m=this.generateId;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var r,o,s,c,h,g,_;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let v=t.value;switch(v.type){case`ping`:return;case`content_block_start`:{let e=v.content_block.type;switch(p=e,e){case`text`:d[v.index]={type:`text`},n.enqueue({type:`text-start`,id:String(v.index)});return;case`thinking`:d[v.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(v.index)});return;case`redacted_thinking`:d[v.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(v.index),providerMetadata:{anthropic:{redactedData:v.content_block.data}}});return;case`tool_use`:d[v.index]=i?{type:`text`}:{type:`tool-call`,toolCallId:v.content_block.id,toolName:v.content_block.name,input:``},n.enqueue(i?{type:`text-start`,id:String(v.index)}:{type:`tool-input-start`,id:v.content_block.id,toolName:v.content_block.name});return;case`server_tool_use`:(v.content_block.name===`web_search`||v.content_block.name===`code_execution`)&&(d[v.index]={type:`tool-call`,toolCallId:v.content_block.id,toolName:v.content_block.name,input:``,providerExecuted:!0},n.enqueue({type:`tool-input-start`,id:v.content_block.id,toolName:v.content_block.name,providerExecuted:!0}));return;case`web_search_tool_result`:{let e=v.content_block;if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,result:e.content.map(e=>{var t;return{url:e.url,title:e.title,pageAge:(t=e.page_age)??null,encryptedContent:e.encrypted_content,type:e.type}}),providerExecuted:!0});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:m(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:(r=t.page_age)??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`web_search`,isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}case`code_execution_tool_result`:{let e=v.content_block;e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code},providerExecuted:!0}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:`code_execution`,isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code},providerExecuted:!0});return}default:{let t=e;throw Error(`Unsupported content block type: ${t}`)}}}case`content_block_stop`:if(d[v.index]!=null){let e=d[v.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(v.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(v.index)});break;case`tool-call`:i||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue(e));break}delete d[v.index]}p=void 0;return;case`content_block_delta`:{let e=v.delta.type;switch(e){case`text_delta`:if(i)return;n.enqueue({type:`text-delta`,id:String(v.index),delta:v.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(v.index),delta:v.delta.thinking});return;case`signature_delta`:p===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(v.index),delta:``,providerMetadata:{anthropic:{signature:v.delta.signature}}});return;case`input_json_delta`:{let e=d[v.index],t=v.delta.partial_json;if(i){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(v.index),delta:t})}else{if(e?.type!==`tool-call`)return;n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t}return}case`citations_delta`:{let e=v.delta.citation;pm(e,a,m,e=>n.enqueue(e));return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:u.inputTokens=v.message.usage.input_tokens,u.cachedInputTokens=(o=v.message.usage.cache_read_input_tokens)??void 0,f={anthropic:{usage:v.message.usage,cacheCreationInputTokens:(s=v.message.usage.cache_creation_input_tokens)??null}},n.enqueue({type:`response-metadata`,id:(c=v.message.id)??void 0,modelId:(h=v.message.model)??void 0});return;case`message_delta`:u.outputTokens=v.usage.output_tokens,u.totalTokens=((g=u.inputTokens)??0)+((_=v.usage.output_tokens)??0),l=um({finishReason:v.delta.stop_reason,isJsonResponseFromTool:i});return;case`message_stop`:n.enqueue({type:`finish`,finishReason:l,usage:u,providerMetadata:f});return;case`error`:n.enqueue({type:`error`,error:v.error});return;default:{let e=v;throw Error(`Unsupported chunk type: ${e}`)}}}})),request:{body:o},response:{headers:s}}}},gm=V.object({type:V.literal(`message`),id:V.string().nullish(),model:V.string().nullish(),content:V.array(V.discriminatedUnion(`type`,[V.object({type:V.literal(`text`),text:V.string(),citations:V.array(fm).optional()}),V.object({type:V.literal(`thinking`),thinking:V.string(),signature:V.string()}),V.object({type:V.literal(`redacted_thinking`),data:V.string()}),V.object({type:V.literal(`tool_use`),id:V.string(),name:V.string(),input:V.unknown()}),V.object({type:V.literal(`server_tool_use`),id:V.string(),name:V.string(),input:V.record(V.string(),V.unknown()).nullish()}),V.object({type:V.literal(`web_search_tool_result`),tool_use_id:V.string(),content:V.union([V.array(V.object({type:V.literal(`web_search_result`),url:V.string(),title:V.string(),encrypted_content:V.string(),page_age:V.string().nullish()})),V.object({type:V.literal(`web_search_tool_result_error`),error_code:V.string()})])}),V.object({type:V.literal(`code_execution_tool_result`),tool_use_id:V.string(),content:V.union([V.object({type:V.literal(`code_execution_result`),stdout:V.string(),stderr:V.string(),return_code:V.number()}),V.object({type:V.literal(`code_execution_tool_result_error`),error_code:V.string()})])})])),stop_reason:V.string().nullish(),usage:V.looseObject({input_tokens:V.number(),output_tokens:V.number(),cache_creation_input_tokens:V.number().nullish(),cache_read_input_tokens:V.number().nullish()})}),_m=V.discriminatedUnion(`type`,[V.object({type:V.literal(`message_start`),message:V.object({id:V.string().nullish(),model:V.string().nullish(),usage:V.looseObject({input_tokens:V.number(),output_tokens:V.number(),cache_creation_input_tokens:V.number().nullish(),cache_read_input_tokens:V.number().nullish()})})}),V.object({type:V.literal(`content_block_start`),index:V.number(),content_block:V.discriminatedUnion(`type`,[V.object({type:V.literal(`text`),text:V.string()}),V.object({type:V.literal(`thinking`),thinking:V.string()}),V.object({type:V.literal(`tool_use`),id:V.string(),name:V.string()}),V.object({type:V.literal(`redacted_thinking`),data:V.string()}),V.object({type:V.literal(`server_tool_use`),id:V.string(),name:V.string(),input:V.record(V.string(),V.unknown()).nullish()}),V.object({type:V.literal(`web_search_tool_result`),tool_use_id:V.string(),content:V.union([V.array(V.object({type:V.literal(`web_search_result`),url:V.string(),title:V.string(),encrypted_content:V.string(),page_age:V.string().nullish()})),V.object({type:V.literal(`web_search_tool_result_error`),error_code:V.string()})])}),V.object({type:V.literal(`code_execution_tool_result`),tool_use_id:V.string(),content:V.union([V.object({type:V.literal(`code_execution_result`),stdout:V.string(),stderr:V.string(),return_code:V.number()}),V.object({type:V.literal(`code_execution_tool_result_error`),error_code:V.string()})])})])}),V.object({type:V.literal(`content_block_delta`),index:V.number(),delta:V.discriminatedUnion(`type`,[V.object({type:V.literal(`input_json_delta`),partial_json:V.string()}),V.object({type:V.literal(`text_delta`),text:V.string()}),V.object({type:V.literal(`thinking_delta`),thinking:V.string()}),V.object({type:V.literal(`signature_delta`),signature:V.string()}),V.object({type:V.literal(`citations_delta`),citation:fm})])}),V.object({type:V.literal(`content_block_stop`),index:V.number()}),V.object({type:V.literal(`error`),error:V.object({type:V.string(),message:V.string()})}),V.object({type:V.literal(`message_delta`),delta:V.object({stop_reason:V.string().nullish()}),usage:V.object({output_tokens:V.number()})}),V.object({type:V.literal(`message_stop`)}),V.object({type:V.literal(`ping`)})]),vm=V.object({signature:V.string().optional(),redactedData:V.string().optional()}),ym=Ss({id:`anthropic.bash_20241022`,name:`bash`,inputSchema:fe.object({command:fe.string(),restart:fe.boolean().optional()})}),bm=Ss({id:`anthropic.bash_20250124`,name:`bash`,inputSchema:fe.object({command:fe.string(),restart:fe.boolean().optional()})}),xm=Ss({id:`anthropic.computer_20241022`,name:`computer`,inputSchema:V.object({action:V.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:V.array(V.number().int()).optional(),text:V.string().optional()})}),Sm=Ss({id:`anthropic.computer_20250124`,name:`computer`,inputSchema:V.object({action:V.enum([`key`,`hold_key`,`type`,`cursor_position`,`mouse_move`,`left_mouse_down`,`left_mouse_up`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`triple_click`,`scroll`,`wait`,`screenshot`]),coordinate:V.tuple([V.number().int(),V.number().int()]).optional(),duration:V.number().optional(),scroll_amount:V.number().optional(),scroll_direction:V.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:V.tuple([V.number().int(),V.number().int()]).optional(),text:V.string().optional()})}),Cm=Ss({id:`anthropic.text_editor_20241022`,name:`str_replace_editor`,inputSchema:V.object({command:V.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:V.string(),file_text:V.string().optional(),insert_line:V.number().int().optional(),new_str:V.string().optional(),old_str:V.string().optional(),view_range:V.array(V.number().int()).optional()})}),wm=Ss({id:`anthropic.text_editor_20250124`,name:`str_replace_editor`,inputSchema:V.object({command:V.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:V.string(),file_text:V.string().optional(),insert_line:V.number().int().optional(),new_str:V.string().optional(),old_str:V.string().optional(),view_range:V.array(V.number().int()).optional()})}),Tm=Ss({id:`anthropic.text_editor_20250429`,name:`str_replace_based_edit_tool`,inputSchema:V.object({command:V.enum([`view`,`create`,`str_replace`,`insert`]),path:V.string(),file_text:V.string().optional(),insert_line:V.number().int().optional(),new_str:V.string().optional(),old_str:V.string().optional(),view_range:V.array(V.number().int()).optional()})}),Em={bash_20241022:ym,bash_20250124:bm,codeExecution_20250522:om,computer_20241022:xm,computer_20250124:Sm,textEditor_20241022:Cm,textEditor_20250124:wm,textEditor_20250429:Tm,webSearch_20250305:tm};function Dm(e={}){var t;let n=(t=Hc(e.baseURL))??`https://api.anthropic.com/v1`,r=()=>({"anthropic-version":`2023-06-01`,"x-api-key":Xo({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers}),i=t=>{var i;return new hm(t,{provider:`anthropic.messages`,baseURL:n,headers:r,fetch:e.fetch,generateId:(i=e.generateId)??Vo,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})})},a=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return i(e)};return a.languageModel=i,a.chat=i,a.messages=i,a.textEmbeddingModel=e=>{throw new mo({modelId:e,modelType:`textEmbeddingModel`})},a.imageModel=e=>{throw new mo({modelId:e,modelType:`imageModel`})},a.tools=Em,a}Dm();var Om=V.object({error:V.object({code:V.number().nullable(),message:V.string(),status:V.string()})}),km=Ts({errorSchema:Om,errorToMessage:e=>e.error.message}),Am=V.object({outputDimensionality:V.number().optional(),taskType:V.enum([`SEMANTIC_SIMILARITY`,`CLASSIFICATION`,`CLUSTERING`,`RETRIEVAL_DOCUMENT`,`RETRIEVAL_QUERY`,`QUESTION_ANSWERING`,`FACT_VERIFICATION`,`CODE_RETRIEVAL_QUERY`]).optional()}),jm=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){let i=await _s({provider:`google`,providerOptions:r,schema:Am});if(e.length>this.maxEmbeddingsPerCall)throw new yo({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=Io(await ws(this.config.headers),t);if(e.length===1){let{responseHeaders:t,value:r,rawValue:o}=await K({url:`${this.config.baseURL}/models/${this.modelId}:embedContent`,headers:a,body:{model:`models/${this.modelId}`,content:{parts:[{text:e[0]}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType},failedResponseHandler:km,successfulResponseHandler:Ds(Nm),abortSignal:n,fetch:this.config.fetch});return{embeddings:[r.embedding.values],usage:void 0,response:{headers:t,body:o}}}let{responseHeaders:o,value:s,rawValue:c}=await K({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:a,body:{requests:e.map(e=>({model:`models/${this.modelId}`,content:{role:`user`,parts:[{text:e}]},outputDimensionality:i?.outputDimensionality,taskType:i?.taskType}))},failedResponseHandler:km,successfulResponseHandler:Ds(Mm),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.embeddings.map(e=>e.values),usage:void 0,response:{headers:o,body:c}}}},Mm=V.object({embeddings:V.array(V.object({values:V.array(V.number())}))}),Nm=V.object({embedding:V.object({values:V.array(V.number())})});function Pm(e){if(e==null||Fm(e))return;if(typeof e==`boolean`)return{type:`boolean`,properties:{}};let{type:t,description:n,required:r,properties:i,items:a,allOf:o,anyOf:s,oneOf:c,format:l,const:u,minLength:d,enum:f}=e,p={};if(n&&(p.description=n),r&&(p.required=r),l&&(p.format=l),u!==void 0&&(p.enum=[u]),t&&(Array.isArray(t)?t.includes(`null`)?(p.type=t.filter(e=>e!==`null`)[0],p.nullable=!0):p.type=t:t===`null`?p.type=`null`:p.type=t),f!==void 0&&(p.enum=f),i!=null&&(p.properties=Object.entries(i).reduce((e,[t,n])=>(e[t]=Pm(n),e),{})),a&&(p.items=Array.isArray(a)?a.map(Pm):Pm(a)),o&&(p.allOf=o.map(Pm)),s)if(s.some(e=>typeof e==`object`&&e?.type===`null`)){let e=s.filter(e=>!(typeof e==`object`&&e?.type===`null`));if(e.length===1){let t=Pm(e[0]);typeof t==`object`&&(p.nullable=!0,Object.assign(p,t))}else p.anyOf=e.map(Pm),p.nullable=!0}else p.anyOf=s.map(Pm);return c&&(p.oneOf=c.map(Pm)),d!==void 0&&(p.minLength=d),p}function Fm(e){return typeof e==`object`&&!!e&&e.type===`object`&&(e.properties==null||Object.keys(e.properties).length===0)&&!e.additionalProperties}function Im(e,t){var n;let r=[],i=[],a=!0,o=(n=t?.isGemmaModel)??!1;for(let{role:t,content:n}of e)switch(t){case`system`:if(!a)throw new Ao({functionality:`system messages are only supported at the beginning of the conversation`});r.push({text:n});break;case`user`:{a=!1;let e=[];for(let t of n)switch(t.type){case`text`:e.push({text:t.text});break;case`file`:{let n=t.mediaType===`image/*`?`image/jpeg`:t.mediaType;e.push(t.data instanceof URL?{fileData:{mimeType:n,fileUri:t.data.toString()}}:{inlineData:{mimeType:n,data:Vc(t.data)}});break}}i.push({role:`user`,parts:e});break}case`assistant`:a=!1,i.push({role:`model`,parts:n.map(e=>{var t,n,r,i,a,o;switch(e.type){case`text`:return e.text.length===0?void 0:{text:e.text,thoughtSignature:(n=(t=e.providerOptions)?.google)?.thoughtSignature};case`reasoning`:return e.text.length===0?void 0:{text:e.text,thought:!0,thoughtSignature:(i=(r=e.providerOptions)?.google)?.thoughtSignature};case`file`:if(e.mediaType!==`image/png`)throw new Ao({functionality:`Only PNG images are supported in assistant messages`});if(e.data instanceof URL)throw new Ao({functionality:`File data URLs in assistant messages are not supported`});return{inlineData:{mimeType:e.mediaType,data:Vc(e.data)}};case`tool-call`:return{functionCall:{name:e.toolName,args:e.input},thoughtSignature:(o=(a=e.providerOptions)?.google)?.thoughtSignature}}}).filter(e=>e!==void 0)});break;case`tool`:{a=!1;let e=[];for(let t of n){let n=t.output;if(n.type===`content`)for(let r of n.value)switch(r.type){case`text`:e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:r.text}}});break;case`media`:e.push({inlineData:{mimeType:r.mediaType,data:r.data}},{text:`Tool executed successfully and returned this image as a response`});break;default:e.push({text:JSON.stringify(r)});break}else e.push({functionResponse:{name:t.toolName,response:{name:t.toolName,content:n.value}}})}i.push({role:`user`,parts:e});break}}if(o&&r.length>0&&i.length>0&&i[0].role===`user`){let e=r.map(e=>e.text).join(`
|
|
94
|
+
|
|
95
|
+
`);i[0].parts.unshift({text:e+`
|
|
96
|
+
|
|
97
|
+
`})}return{systemInstruction:r.length>0&&!o?{parts:r}:void 0,contents:i}}function Lm(e){return e.includes(`/`)?e:`models/${e}`}var Rm=V.object({responseModalities:V.array(V.enum([`TEXT`,`IMAGE`])).optional(),thinkingConfig:V.object({thinkingBudget:V.number().optional(),includeThoughts:V.boolean().optional()}).optional(),cachedContent:V.string().optional(),structuredOutputs:V.boolean().optional(),safetySettings:V.array(V.object({category:V.enum([`HARM_CATEGORY_UNSPECIFIED`,`HARM_CATEGORY_HATE_SPEECH`,`HARM_CATEGORY_DANGEROUS_CONTENT`,`HARM_CATEGORY_HARASSMENT`,`HARM_CATEGORY_SEXUALLY_EXPLICIT`,`HARM_CATEGORY_CIVIC_INTEGRITY`]),threshold:V.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`])})).optional(),threshold:V.enum([`HARM_BLOCK_THRESHOLD_UNSPECIFIED`,`BLOCK_LOW_AND_ABOVE`,`BLOCK_MEDIUM_AND_ABOVE`,`BLOCK_ONLY_HIGH`,`BLOCK_NONE`,`OFF`]).optional(),audioTimestamp:V.boolean().optional(),labels:V.record(V.string(),V.string()).optional()});function zm({tools:e,toolChoice:t,modelId:n}){var r;e=e?.length?e:void 0;let i=[],a=n.includes(`gemini-2`),o=n.includes(`gemini-1.5-flash`)&&!n.includes(`-8b`);if(e==null)return{tools:void 0,toolConfig:void 0,toolWarnings:i};let s=e.some(e=>e.type===`function`),c=e.some(e=>e.type===`provider-defined`);if(s&&c&&i.push({type:`unsupported-tool`,tool:e.find(e=>e.type===`function`),details:`Cannot mix function tools with provider-defined tools in the same request. Please use either function tools or provider-defined tools, but not both.`}),c){let t={},n=e.filter(e=>e.type===`provider-defined`);return n.forEach(e=>{switch(e.id){case`google.google_search`:a?t.googleSearch={}:o?t.googleSearchRetrieval={dynamicRetrievalConfig:{mode:e.args.mode,dynamicThreshold:e.args.dynamicThreshold}}:t.googleSearchRetrieval={};break;case`google.url_context`:a?t.urlContext={}:i.push({type:`unsupported-tool`,tool:e,details:`The URL context tool is not supported with other Gemini models than Gemini 2.`});break;case`google.code_execution`:a?t.codeExecution={}:i.push({type:`unsupported-tool`,tool:e,details:`The code execution tools is not supported with other Gemini models than Gemini 2.`});break;default:i.push({type:`unsupported-tool`,tool:e});break}}),{tools:Object.keys(t).length>0?t:void 0,toolConfig:void 0,toolWarnings:i}}let l=[];for(let t of e)switch(t.type){case`function`:l.push({name:t.name,description:(r=t.description)??``,parameters:Pm(t.inputSchema)});break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:{functionDeclarations:l},toolConfig:void 0,toolWarnings:i};let u=t.type;switch(u){case`auto`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`AUTO`}},toolWarnings:i};case`none`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`NONE`}},toolWarnings:i};case`required`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`ANY`}},toolWarnings:i};case`tool`:return{tools:{functionDeclarations:l},toolConfig:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[t.toolName]}},toolWarnings:i};default:{let e=u;throw new Ao({functionality:`tool choice type: ${e}`})}}}function Bm({finishReason:e,hasToolCalls:t}){switch(e){case`STOP`:return t?`tool-calls`:`stop`;case`MAX_TOKENS`:return`length`;case`IMAGE_SAFETY`:case`RECITATION`:case`SAFETY`:case`BLOCKLIST`:case`PROHIBITED_CONTENT`:case`SPII`:return`content-filter`;case`FINISH_REASON_UNSPECIFIED`:case`OTHER`:return`other`;case`MALFORMED_FUNCTION_CALL`:return`error`;default:return`unknown`}}var Vm=V.object({web:V.object({uri:V.string(),title:V.string()}).nullish(),retrievedContext:V.object({uri:V.string(),title:V.string()}).nullish()}),Hm=V.object({webSearchQueries:V.array(V.string()).nullish(),retrievalQueries:V.array(V.string()).nullish(),searchEntryPoint:V.object({renderedContent:V.string()}).nullish(),groundingChunks:V.array(Vm).nullish(),groundingSupports:V.array(V.object({segment:V.object({startIndex:V.number().nullish(),endIndex:V.number().nullish(),text:V.string().nullish()}),segment_text:V.string().nullish(),groundingChunkIndices:V.array(V.number()).nullish(),supportChunkIndices:V.array(V.number()).nullish(),confidenceScores:V.array(V.number()).nullish(),confidenceScore:V.array(V.number()).nullish()})).nullish(),retrievalMetadata:V.union([V.object({webDynamicRetrievalScore:V.number()}),V.object({})]).nullish()}),Um=Ss({id:`google.google_search`,name:`google_search`,inputSchema:V.object({mode:V.enum([`MODE_DYNAMIC`,`MODE_UNSPECIFIED`]).default(`MODE_UNSPECIFIED`),dynamicThreshold:V.number().default(1)})}),Wm=V.object({retrievedUrl:V.string(),urlRetrievalStatus:V.string()}),Gm=V.object({urlMetadata:V.array(Wm)}),Km=Ss({id:`google.url_context`,name:`url_context`,inputSchema:V.object({})}),qm=class{constructor(e,t){this.specificationVersion=`v2`;var n;this.modelId=e,this.config=t,this.generateId=(n=t.generateId)??Vo}get provider(){return this.config.provider}get supportedUrls(){var e,t,n;return(n=(t=(e=this.config).supportedUrls)?.call(e))??{}}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){var p,m;let h=[],g=await _s({provider:`google`,providerOptions:f,schema:Rm});(p=g?.thinkingConfig)?.includeThoughts===!0&&!this.config.provider.startsWith(`google.vertex.`)&&h.push({type:`other`,message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let _=this.modelId.toLowerCase().startsWith(`gemma-`),{contents:v,systemInstruction:y}=Im(e,{isGemmaModel:_}),{tools:b,toolConfig:x,toolWarnings:S}=zm({tools:u,toolChoice:d,modelId:this.modelId});return{args:{generationConfig:{maxOutputTokens:t,temperature:n,topK:i,topP:r,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:l,responseMimeType:c?.type===`json`?`application/json`:void 0,responseSchema:c?.type===`json`&&c.schema!=null&&((m=g?.structuredOutputs)??!0)?Pm(c.schema):void 0,...g?.audioTimestamp&&{audioTimestamp:g.audioTimestamp},responseModalities:g?.responseModalities,thinkingConfig:g?.thinkingConfig},contents:v,systemInstruction:_?void 0:y,safetySettings:g?.safetySettings,tools:b,toolConfig:x,cachedContent:g?.cachedContent,labels:g?.labels},warnings:[...h,...S]}}async doGenerate(e){var t,n,r,i,a,o,s,c,l,u,d,f;let{args:p,warnings:m}=await this.getArgs(e),h=JSON.stringify(p),g=Io(await ws(this.config.headers),e.headers),{responseHeaders:_,value:v,rawValue:y}=await K({url:`${this.config.baseURL}/${Lm(this.modelId)}:generateContent`,headers:g,body:p,failedResponseHandler:km,successfulResponseHandler:Ds(eh),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=v.candidates[0],x=[],S=(n=(t=b.content)?.parts)??[],C=v.usageMetadata,w;for(let e of S)if(`executableCode`in e&&(r=e.executableCode)?.code){let t=this.config.generateId();w=t,x.push({type:`tool-call`,toolCallId:t,toolName:`code_execution`,input:JSON.stringify(e.executableCode),providerExecuted:!0})}else `codeExecutionResult`in e&&e.codeExecutionResult?(x.push({type:`tool-result`,toolCallId:w,toolName:`code_execution`,result:{outcome:e.codeExecutionResult.outcome,output:e.codeExecutionResult.output},providerExecuted:!0}),w=void 0):`text`in e&&e.text!=null&&e.text.length>0?x.push({type:e.thought===!0?`reasoning`:`text`,text:e.text,providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`functionCall`in e?x.push({type:`tool-call`,toolCallId:this.config.generateId(),toolName:e.functionCall.name,input:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}):`inlineData`in e&&x.push({type:`file`,data:e.inlineData.data,mediaType:e.inlineData.mimeType});let T=(i=Xm({groundingMetadata:b.groundingMetadata,generateId:this.config.generateId}))??[];for(let e of T)x.push(e);return{content:x,finishReason:Bm({finishReason:b.finishReason,hasToolCalls:x.some(e=>e.type===`tool-call`)}),usage:{inputTokens:(a=C?.promptTokenCount)??void 0,outputTokens:(o=C?.candidatesTokenCount)??void 0,totalTokens:(s=C?.totalTokenCount)??void 0,reasoningTokens:(c=C?.thoughtsTokenCount)??void 0,cachedInputTokens:(l=C?.cachedContentTokenCount)??void 0},warnings:m,providerMetadata:{google:{groundingMetadata:(u=b.groundingMetadata)??null,urlContextMetadata:(d=b.urlContextMetadata)??null,safetyRatings:(f=b.safetyRatings)??null,usageMetadata:C??null}},request:{body:h},response:{headers:_,body:y}}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r=JSON.stringify(t),i=Io(await ws(this.config.headers),e.headers),{responseHeaders:a,value:o}=await K({url:`${this.config.baseURL}/${Lm(this.modelId)}:streamGenerateContent?alt=sse`,headers:i,body:t,failedResponseHandler:km,successfulResponseHandler:Es(th),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l,u=this.config.generateId,d=!1,f=null,p=null,m=0,h=new Set,g;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var r,i,a,o,_,v,y,b,x,S,C;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let w=t.value,T=w.usageMetadata;T!=null&&(c.inputTokens=(r=T.promptTokenCount)??void 0,c.outputTokens=(i=T.candidatesTokenCount)??void 0,c.totalTokens=(a=T.totalTokenCount)??void 0,c.reasoningTokens=(o=T.thoughtsTokenCount)??void 0,c.cachedInputTokens=(_=T.cachedContentTokenCount)??void 0);let E=(v=w.candidates)?.[0];if(E==null)return;let D=E.content,O=Xm({groundingMetadata:E.groundingMetadata,generateId:u});if(O!=null)for(let e of O)e.sourceType===`url`&&!h.has(e.url)&&(h.add(e.url),n.enqueue(e));if(D!=null){let e=(y=D.parts)??[];for(let t of e)if(`executableCode`in t&&(b=t.executableCode)?.code){let e=u();g=e,n.enqueue({type:`tool-call`,toolCallId:e,toolName:`code_execution`,input:JSON.stringify(t.executableCode),providerExecuted:!0}),d=!0}else if(`codeExecutionResult`in t&&t.codeExecutionResult){let e=g;e&&(n.enqueue({type:`tool-result`,toolCallId:e,toolName:`code_execution`,result:{outcome:t.codeExecutionResult.outcome,output:t.codeExecutionResult.output},providerExecuted:!0}),g=void 0)}else `text`in t&&t.text!=null&&t.text.length>0&&(t.thought===!0?(f!==null&&(n.enqueue({type:`text-end`,id:f}),f=null),p===null&&(p=String(m++),n.enqueue({type:`reasoning-start`,id:p,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`reasoning-delta`,id:p,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})):(p!==null&&(n.enqueue({type:`reasoning-end`,id:p}),p=null),f===null&&(f=String(m++),n.enqueue({type:`text-start`,id:f,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})),n.enqueue({type:`text-delta`,id:f,delta:t.text,providerMetadata:t.thoughtSignature?{google:{thoughtSignature:t.thoughtSignature}}:void 0})));let t=Ym(D.parts);if(t!=null)for(let e of t)n.enqueue({type:`file`,mediaType:e.inlineData.mimeType,data:e.inlineData.data});let r=Jm({parts:D.parts,generateId:u});if(r!=null)for(let e of r)n.enqueue({type:`tool-input-start`,id:e.toolCallId,toolName:e.toolName,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:e.args,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-input-end`,id:e.toolCallId,providerMetadata:e.providerMetadata}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.args,providerMetadata:e.providerMetadata}),d=!0}E.finishReason!=null&&(s=Bm({finishReason:E.finishReason,hasToolCalls:d}),l={google:{groundingMetadata:(x=E.groundingMetadata)??null,urlContextMetadata:(S=E.urlContextMetadata)??null,safetyRatings:(C=E.safetyRatings)??null}},T!=null&&(l.google.usageMetadata=T))},flush(e){f!==null&&e.enqueue({type:`text-end`,id:f}),p!==null&&e.enqueue({type:`reasoning-end`,id:p}),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:l})}})),response:{headers:a},request:{body:r}}}};function Jm({parts:e,generateId:t}){let n=e?.filter(e=>`functionCall`in e);return n==null||n.length===0?void 0:n.map(e=>({type:`tool-call`,toolCallId:t(),toolName:e.functionCall.name,args:JSON.stringify(e.functionCall.args),providerMetadata:e.thoughtSignature?{google:{thoughtSignature:e.thoughtSignature}}:void 0}))}function Ym(e){return e?.filter(e=>`inlineData`in e)}function Xm({groundingMetadata:e,generateId:t}){var n;return(n=e?.groundingChunks)?.filter(e=>e.web!=null).map(e=>({type:`source`,sourceType:`url`,id:t(),url:e.web.uri,title:e.web.title}))}var Zm=V.object({parts:V.array(V.union([V.object({functionCall:V.object({name:V.string(),args:V.unknown()}),thoughtSignature:V.string().nullish()}),V.object({inlineData:V.object({mimeType:V.string(),data:V.string()})}),V.object({executableCode:V.object({language:V.string(),code:V.string()}).nullish(),codeExecutionResult:V.object({outcome:V.string(),output:V.string()}).nullish(),text:V.string().nullish(),thought:V.boolean().nullish(),thoughtSignature:V.string().nullish()})])).nullish()}),Qm=V.object({category:V.string().nullish(),probability:V.string().nullish(),probabilityScore:V.number().nullish(),severity:V.string().nullish(),severityScore:V.number().nullish(),blocked:V.boolean().nullish()}),$m=V.object({cachedContentTokenCount:V.number().nullish(),thoughtsTokenCount:V.number().nullish(),promptTokenCount:V.number().nullish(),candidatesTokenCount:V.number().nullish(),totalTokenCount:V.number().nullish()}),eh=V.object({candidates:V.array(V.object({content:Zm.nullish().or(V.object({}).strict()),finishReason:V.string().nullish(),safetyRatings:V.array(Qm).nullish(),groundingMetadata:Hm.nullish(),urlContextMetadata:Gm.nullish()})),usageMetadata:$m.nullish()}),th=V.object({candidates:V.array(V.object({content:Zm.nullish(),finishReason:V.string().nullish(),safetyRatings:V.array(Qm).nullish(),groundingMetadata:Hm.nullish(),urlContextMetadata:Gm.nullish()})).nullish(),usageMetadata:$m.nullish()}),nh=Cs({id:`google.code_execution`,name:`code_execution`,inputSchema:V.object({language:V.string().describe(`The programming language of the code.`),code:V.string().describe(`The code to be executed.`)}),outputSchema:V.object({outcome:V.string().describe(`The outcome of the execution (e.g., "OUTCOME_OK").`),output:V.string().describe(`The output from the code execution.`)})}),rh={googleSearch:Um,urlContext:Km,codeExecution:nh},ih=class{constructor(e,t,n){this.modelId=e,this.settings=t,this.config=n,this.specificationVersion=`v2`}get maxImagesPerCall(){var e;return(e=this.settings.maxImagesPerCall)??4}get provider(){return this.config.provider}async doGenerate(e){var t,n,r;let{prompt:i,n:a=1,size:o=`1024x1024`,aspectRatio:s=`1:1`,seed:c,providerOptions:l,headers:u,abortSignal:d}=e,f=[];o!=null&&f.push({type:`unsupported-setting`,setting:`size`,details:"This model does not support the `size` option. Use `aspectRatio` instead."}),c!=null&&f.push({type:`unsupported-setting`,setting:`seed`,details:"This model does not support the `seed` option through this provider."});let p=await _s({provider:`google`,providerOptions:l,schema:oh}),m=(r=(n=(t=this.config._internal)?.currentDate)?.call(t))??new Date,h={sampleCount:a};s!=null&&(h.aspectRatio=s),p&&Object.assign(h,p);let g={instances:[{prompt:i}],parameters:h},{responseHeaders:_,value:v}=await K({url:`${this.config.baseURL}/models/${this.modelId}:predict`,headers:Io(await ws(this.config.headers),u),body:g,failedResponseHandler:km,successfulResponseHandler:Ds(ah),abortSignal:d,fetch:this.config.fetch});return{images:v.predictions.map(e=>e.bytesBase64Encoded),warnings:f??[],providerMetadata:{google:{images:v.predictions.map(e=>({}))}},response:{timestamp:m,modelId:this.modelId,headers:_}}}},ah=V.object({predictions:V.array(V.object({bytesBase64Encoded:V.string()})).default([])}),oh=V.object({personGeneration:V.enum([`dont_allow`,`allow_adult`,`allow_all`]).nullish(),aspectRatio:V.enum([`1:1`,`3:4`,`4:3`,`9:16`,`16:9`]).nullish()});function sh(e={}){var t;let n=(t=Hc(e.baseURL))??`https://generativelanguage.googleapis.com/v1beta`,r=()=>({"x-goog-api-key":Xo({apiKey:e.apiKey,environmentVariableName:`GOOGLE_GENERATIVE_AI_API_KEY`,description:`Google Generative AI`}),...e.headers}),i=t=>{var i;return new qm(t,{provider:`google.generative-ai`,baseURL:n,headers:r,generateId:(i=e.generateId)??Vo,supportedUrls:()=>({"*":[RegExp(`^${n}/files/.*$`),RegExp(`^https://(?:www\\.)?youtube\\.com/watch\\?v=[\\w-]+(?:&[\\w=&.-]*)?$`),RegExp(`^https://youtu\\.be/[\\w-]+(?:\\?[\\w=&.-]*)?$`)]}),fetch:e.fetch})},a=t=>new jm(t,{provider:`google.generative-ai`,baseURL:n,headers:r,fetch:e.fetch}),o=(t,i={})=>new ih(t,i,{provider:`google.generative-ai`,baseURL:n,headers:r,fetch:e.fetch}),s=function(e){if(new.target)throw Error(`The Google Generative AI model function cannot be called with the new keyword.`);return i(e)};return s.languageModel=i,s.chat=i,s.generativeAI=i,s.embedding=a,s.textEmbedding=a,s.textEmbeddingModel=a,s.image=o,s.imageModel=o,s.tools=rh,s}sh();var ch=V.object({error:V.object({message:V.string(),type:V.string().nullish(),param:V.any().nullish(),code:V.union([V.string(),V.number()]).nullish()})}),lh=Ts({errorSchema:ch,errorToMessage:e=>e.error.message});function uh({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:i,content:a}of e)switch(i){case`system`:switch(t){case`system`:n.push({role:`system`,content:a});break;case`developer`:n.push({role:`developer`,content:a});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:if(a.length===1&&a[0].type===`text`){n.push({role:`user`,content:a[0].text});break}n.push({role:`user`,content:a.map((e,t)=>{var n,r,i;switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${Vc(e.data)}`,detail:(r=(n=e.providerOptions)?.openai)?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new Ao({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:Vc(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:Vc(e.data),format:`mp3`}};default:throw new Ao({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new Ao({functionality:`PDF file parts with URLs`});return{type:`file`,file:typeof e.data==`string`&&e.data.startsWith(`file-`)?{file_id:e.data}:{filename:(i=e.filename)??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Vc(e.data)}`}}}else throw new Ao({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of a)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:JSON.stringify(n.input)}});break}n.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of a){let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function dh({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function fh(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var ph=V.object({logitBias:V.record(V.coerce.number(),V.number()).optional(),logprobs:V.union([V.boolean(),V.number()]).optional(),parallelToolCalls:V.boolean().optional(),user:V.string().optional(),reasoningEffort:V.enum([`minimal`,`low`,`medium`,`high`]).optional(),maxCompletionTokens:V.number().optional(),store:V.boolean().optional(),metadata:V.record(V.string().max(64),V.string().max(512)).optional(),prediction:V.record(V.string(),V.any()).optional(),structuredOutputs:V.boolean().optional(),serviceTier:V.enum([`auto`,`flex`,`priority`]).optional(),strictJsonSchema:V.boolean().optional(),textVerbosity:V.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:V.string().optional(),safetyIdentifier:V.string().optional()}),mh=V.object({key:V.string(),type:V.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`]),value:V.union([V.string(),V.number(),V.boolean()])}),hh=V.object({type:V.enum([`and`,`or`]),filters:V.array(V.union([mh,V.lazy(()=>hh)]))}),gh=V.union([mh,hh]),_h=V.object({vectorStoreIds:V.array(V.string()).optional(),maxNumResults:V.number().optional(),ranking:V.object({ranker:V.enum([`auto`,`default-2024-08-21`]).optional()}).optional(),filters:gh.optional()}),vh=Ss({id:`openai.file_search`,name:`file_search`,inputSchema:V.object({query:V.string()})}),yh=V.object({searchContextSize:V.enum([`low`,`medium`,`high`]).optional(),userLocation:V.object({type:V.literal(`approximate`),country:V.string().optional(),city:V.string().optional(),region:V.string().optional(),timezone:V.string().optional()}).optional()}),bh=Ss({id:`openai.web_search_preview`,name:`web_search_preview`,inputSchema:V.object({action:V.discriminatedUnion(`type`,[V.object({type:V.literal(`search`),query:V.string().nullish()}),V.object({type:V.literal(`open_page`),url:V.string()}),V.object({type:V.literal(`find`),url:V.string(),pattern:V.string()})]).nullish()})});function xh({tools:e,toolChoice:t,structuredOutputs:n,strictJsonSchema:r}){e=e?.length?e:void 0;let i=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};let a=[];for(let t of e)switch(t.type){case`function`:a.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,strict:n?r:void 0}});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=_h.parse(t.args);a.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case`openai.web_search_preview`:{let e=yh.parse(t.args);a.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}default:i.push({type:`unsupported-tool`,tool:t});break}break;default:i.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:a,toolChoice:void 0,toolWarnings:i};let o=t.type;switch(o){case`auto`:case`none`:case`required`:return{tools:a,toolChoice:o,toolWarnings:i};case`tool`:return{tools:a,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:i};default:{let e=o;throw new Ao({functionality:`tool choice type: ${e}`})}}}var Sh=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){var p,m,h,g;let _=[],v=(p=await _s({provider:`openai`,providerOptions:f,schema:ph}))??{},y=(m=v.structuredOutputs)??!0;i!=null&&_.push({type:`unsupported-setting`,setting:`topK`}),c?.type===`json`&&c.schema!=null&&!y&&_.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is only supported with structuredOutputs`});let{messages:b,warnings:x}=uh({prompt:e,systemMessageMode:kh(this.modelId)});_.push(...x);let S=(h=v.strictJsonSchema)??!1,C={model:this.modelId,logit_bias:v.logitBias,logprobs:v.logprobs===!0||typeof v.logprobs==`number`?!0:void 0,top_logprobs:typeof v.logprobs==`number`?v.logprobs:typeof v.logprobs==`boolean`&&v.logprobs?0:void 0,user:v.user,parallel_tool_calls:v.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?y&&c.schema!=null?{type:`json_schema`,json_schema:{schema:c.schema,strict:S,name:(g=c.name)??`response`,description:c.description}}:{type:`json_object`}:void 0,stop:s,seed:l,verbosity:v.textVerbosity,max_completion_tokens:v.maxCompletionTokens,store:v.store,metadata:v.metadata,prediction:v.prediction,reasoning_effort:v.reasoningEffort,service_tier:v.serviceTier,prompt_cache_key:v.promptCacheKey,safety_identifier:v.safetyIdentifier,messages:b};Eh(this.modelId)?(C.temperature!=null&&(C.temperature=void 0,_.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),C.top_p!=null&&(C.top_p=void 0,_.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`})),C.frequency_penalty!=null&&(C.frequency_penalty=void 0,_.push({type:`unsupported-setting`,setting:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),C.presence_penalty!=null&&(C.presence_penalty=void 0,_.push({type:`unsupported-setting`,setting:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),C.logit_bias!=null&&(C.logit_bias=void 0,_.push({type:`other`,message:`logitBias is not supported for reasoning models`})),C.logprobs!=null&&(C.logprobs=void 0,_.push({type:`other`,message:`logprobs is not supported for reasoning models`})),C.top_logprobs!=null&&(C.top_logprobs=void 0,_.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),C.max_tokens!=null&&(C.max_completion_tokens??=C.max_tokens,C.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&C.temperature!=null&&(C.temperature=void 0,_.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),v.serviceTier===`flex`&&!Dh(this.modelId)&&(_.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),C.service_tier=void 0),v.serviceTier===`priority`&&!Oh(this.modelId)&&(_.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),C.service_tier=void 0);let{tools:w,toolChoice:T,toolWarnings:E}=xh({tools:u,toolChoice:d,structuredOutputs:y,strictJsonSchema:S});return{args:{...C,tools:w,tool_choice:T},warnings:[..._,...E]}}async doGenerate(e){var t,n,r,i,a,o,s,c,l,u,d,f,p,m;let{args:h,warnings:g}=await this.getArgs(e),{responseHeaders:_,value:v,rawValue:y}=await K({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:Io(this.config.headers(),e.headers),body:h,failedResponseHandler:lh,successfulResponseHandler:Ds(wh),abortSignal:e.abortSignal,fetch:this.config.fetch}),b=v.choices[0],x=[],S=b.message.content;S!=null&&S.length>0&&x.push({type:`text`,text:S});for(let e of(t=b.message.tool_calls)??[])x.push({type:`tool-call`,toolCallId:(n=e.id)??Vo(),toolName:e.function.name,input:e.function.arguments});for(let e of(r=b.message.annotations)??[])x.push({type:`source`,sourceType:`url`,id:Vo(),url:e.url,title:e.title});let C=(i=v.usage)?.completion_tokens_details,w=(a=v.usage)?.prompt_tokens_details,T={openai:{}};return C?.accepted_prediction_tokens!=null&&(T.openai.acceptedPredictionTokens=C?.accepted_prediction_tokens),C?.rejected_prediction_tokens!=null&&(T.openai.rejectedPredictionTokens=C?.rejected_prediction_tokens),(o=b.logprobs)?.content!=null&&(T.openai.logprobs=b.logprobs.content),{content:x,finishReason:fh(b.finish_reason),usage:{inputTokens:(c=(s=v.usage)?.prompt_tokens)??void 0,outputTokens:(u=(l=v.usage)?.completion_tokens)??void 0,totalTokens:(f=(d=v.usage)?.total_tokens)??void 0,reasoningTokens:(p=C?.reasoning_tokens)??void 0,cachedInputTokens:(m=w?.cached_tokens)??void 0},request:{body:h},response:{...dh(v),headers:_,body:y},warnings:g,providerMetadata:T}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await K({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:Io(this.config.headers(),e.headers),body:r,failedResponseHandler:lh,successfulResponseHandler:Es(Th),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=[],s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0,u=!1,d={openai:{}};return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var r,i,a,f,p,m,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,ee;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let M=t.value;if(`error`in M){s=`error`,n.enqueue({type:`error`,error:M.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...dh(M)})),M.usage!=null&&(c.inputTokens=(r=M.usage.prompt_tokens)??void 0,c.outputTokens=(i=M.usage.completion_tokens)??void 0,c.totalTokens=(a=M.usage.total_tokens)??void 0,c.reasoningTokens=(p=(f=M.usage.completion_tokens_details)?.reasoning_tokens)??void 0,c.cachedInputTokens=(h=(m=M.usage.prompt_tokens_details)?.cached_tokens)??void 0,(g=M.usage.completion_tokens_details)?.accepted_prediction_tokens!=null&&(d.openai.acceptedPredictionTokens=(_=M.usage.completion_tokens_details)?.accepted_prediction_tokens),(v=M.usage.completion_tokens_details)?.rejected_prediction_tokens!=null&&(d.openai.rejectedPredictionTokens=(y=M.usage.completion_tokens_details)?.rejected_prediction_tokens));let N=M.choices[0];if(N?.finish_reason!=null&&(s=fh(N.finish_reason)),(b=N?.logprobs)?.content!=null&&(d.openai.logprobs=N.logprobs.content),N?.delta==null)return;let P=N.delta;if(P.content!=null&&(u||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:P.content})),P.tool_calls!=null)for(let e of P.tool_calls){let t=e.index;if(o[t]==null){if(e.type!==`function`)throw new Wa({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new Wa({data:e,message:`Expected 'id' to be a string.`});if((x=e.function)?.name==null)throw new Wa({data:e,message:`Expected 'function.name' to be a string.`});n.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),o[t]={id:e.id,type:`function`,function:{name:e.function.name,arguments:(S=e.function.arguments)??``},hasFinished:!1};let r=o[t];(C=r.function)?.name!=null&&(w=r.function)?.arguments!=null&&(r.function.arguments.length>0&&n.enqueue({type:`tool-input-delta`,id:r.id,delta:r.function.arguments}),hs(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:(T=r.id)??Vo(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0));continue}let r=o[t];if(r.hasFinished)continue;(E=e.function)?.arguments!=null&&(r.function.arguments+=(O=(D=e.function)?.arguments)??``),n.enqueue({type:`tool-input-delta`,id:r.id,delta:(k=e.function.arguments)??``}),(A=r.function)?.name!=null&&(j=r.function)?.arguments!=null&&hs(r.function.arguments)&&(n.enqueue({type:`tool-input-end`,id:r.id}),n.enqueue({type:`tool-call`,toolCallId:(ee=r.id)??Vo(),toolName:r.function.name,input:r.function.arguments}),r.hasFinished=!0)}if(P.annotations!=null)for(let e of P.annotations)n.enqueue({type:`source`,sourceType:`url`,id:Vo(),url:e.url,title:e.title})},flush(e){u&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,usage:c,...d==null?{}:{providerMetadata:d}})}})),request:{body:r},response:{headers:i}}}},Ch=V.object({prompt_tokens:V.number().nullish(),completion_tokens:V.number().nullish(),total_tokens:V.number().nullish(),prompt_tokens_details:V.object({cached_tokens:V.number().nullish()}).nullish(),completion_tokens_details:V.object({reasoning_tokens:V.number().nullish(),accepted_prediction_tokens:V.number().nullish(),rejected_prediction_tokens:V.number().nullish()}).nullish()}).nullish(),wh=V.object({id:V.string().nullish(),created:V.number().nullish(),model:V.string().nullish(),choices:V.array(V.object({message:V.object({role:V.literal(`assistant`).nullish(),content:V.string().nullish(),tool_calls:V.array(V.object({id:V.string().nullish(),type:V.literal(`function`),function:V.object({name:V.string(),arguments:V.string()})})).nullish(),annotations:V.array(V.object({type:V.literal(`url_citation`),start_index:V.number(),end_index:V.number(),url:V.string(),title:V.string()})).nullish()}),index:V.number(),logprobs:V.object({content:V.array(V.object({token:V.string(),logprob:V.number(),top_logprobs:V.array(V.object({token:V.string(),logprob:V.number()}))})).nullish()}).nullish(),finish_reason:V.string().nullish()})),usage:Ch}),Th=V.union([V.object({id:V.string().nullish(),created:V.number().nullish(),model:V.string().nullish(),choices:V.array(V.object({delta:V.object({role:V.enum([`assistant`]).nullish(),content:V.string().nullish(),tool_calls:V.array(V.object({index:V.number(),id:V.string().nullish(),type:V.literal(`function`).nullish(),function:V.object({name:V.string().nullish(),arguments:V.string().nullish()})})).nullish(),annotations:V.array(V.object({type:V.literal(`url_citation`),start_index:V.number(),end_index:V.number(),url:V.string(),title:V.string()})).nullish()}).nullish(),logprobs:V.object({content:V.array(V.object({token:V.string(),logprob:V.number(),top_logprobs:V.array(V.object({token:V.string(),logprob:V.number()}))})).nullish()}).nullish(),finish_reason:V.string().nullish(),index:V.number()})),usage:Ch}),ch]);function Eh(e){return(e.startsWith(`o`)||e.startsWith(`gpt-5`))&&!e.startsWith(`gpt-5-chat`)}function Dh(e){return e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)}function Oh(e){return e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`)}function kh(e){var t,n;return Eh(e)?(n=(t=Ah[e])?.systemMessageMode)??`developer`:`system`}var Ah={"o1-mini":{systemMessageMode:`remove`},"o1-mini-2024-09-12":{systemMessageMode:`remove`},"o1-preview":{systemMessageMode:`remove`},"o1-preview-2024-09-12":{systemMessageMode:`remove`},o3:{systemMessageMode:`developer`},"o3-2025-04-16":{systemMessageMode:`developer`},"o3-mini":{systemMessageMode:`developer`},"o3-mini-2025-01-31":{systemMessageMode:`developer`},"o4-mini":{systemMessageMode:`developer`},"o4-mini-2025-04-16":{systemMessageMode:`developer`}};function jh({prompt:e,user:t=`user`,assistant:n=`assistant`}){let r=``;e[0].role===`system`&&(r+=`${e[0].content}
|
|
98
|
+
|
|
99
|
+
`,e=e.slice(1));for(let{role:i,content:a}of e)switch(i){case`system`:throw new za({message:"Unexpected system message in prompt: ${content}",prompt:e});case`user`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text}}).filter(Boolean).join(``);r+=`${t}:
|
|
100
|
+
${e}
|
|
101
|
+
|
|
102
|
+
`;break}case`assistant`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text;case`tool-call`:throw new Ao({functionality:`tool-call messages`})}}).join(``);r+=`${n}:
|
|
103
|
+
${e}
|
|
104
|
+
|
|
105
|
+
`;break}case`tool`:throw new Ao({functionality:`tool messages`});default:{let e=i;throw Error(`Unsupported role: ${e}`)}}return r+=`${n}:
|
|
106
|
+
`,{prompt:r,stopSequences:[`
|
|
107
|
+
${t}:`]}}function Mh({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Nh(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`unknown`}}var Ph=V.object({echo:V.boolean().optional(),logitBias:V.record(V.string(),V.number()).optional(),suffix:V.string().optional(),user:V.string().optional(),logprobs:V.union([V.boolean(),V.number()]).optional()}),Fh=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await _s({provider:`openai`,providerOptions:f,schema:Ph}),...await _s({provider:this.providerOptionsName,providerOptions:f,schema:Ph})};i!=null&&p.push({type:`unsupported-setting`,setting:`topK`}),l?.length&&p.push({type:`unsupported-setting`,setting:`tools`}),u!=null&&p.push({type:`unsupported-setting`,setting:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=jh({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){var t,n,r;let{args:i,warnings:a}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:c}=await K({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Io(this.config.headers(),e.headers),body:i,failedResponseHandler:lh,successfulResponseHandler:Ds(Lh),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.choices[0],u={openai:{}};return l.logprobs!=null&&(u.openai.logprobs=l.logprobs),{content:[{type:`text`,text:l.text}],usage:{inputTokens:(t=s.usage)?.prompt_tokens,outputTokens:(n=s.usage)?.completion_tokens,totalTokens:(r=s.usage)?.total_tokens},finishReason:Nh(l.finish_reason),request:{body:i},response:{...Mh(s),headers:o,body:c},providerMetadata:u,warnings:a}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:a}=await K({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:Io(this.config.headers(),e.headers),body:r,failedResponseHandler:lh,successfulResponseHandler:Es(Rh),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=`unknown`,s={openai:{}},c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=!0;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){o=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){o=`error`,n.enqueue({type:`error`,error:r.error});return}l&&(l=!1,n.enqueue({type:`response-metadata`,...Mh(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(c.inputTokens=r.usage.prompt_tokens,c.outputTokens=r.usage.completion_tokens,c.totalTokens=r.usage.total_tokens);let i=r.choices[0];i?.finish_reason!=null&&(o=Nh(i.finish_reason)),i?.logprobs!=null&&(s.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){l||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:o,providerMetadata:s,usage:c})}})),request:{body:r},response:{headers:i}}}},Ih=V.object({prompt_tokens:V.number(),completion_tokens:V.number(),total_tokens:V.number()}),Lh=V.object({id:V.string().nullish(),created:V.number().nullish(),model:V.string().nullish(),choices:V.array(V.object({text:V.string(),finish_reason:V.string(),logprobs:V.object({tokens:V.array(V.string()),token_logprobs:V.array(V.number()),top_logprobs:V.array(V.record(V.string(),V.number())).nullish()}).nullish()})),usage:Ih.nullish()}),Rh=V.union([V.object({id:V.string().nullish(),created:V.number().nullish(),model:V.string().nullish(),choices:V.array(V.object({text:V.string(),finish_reason:V.string().nullish(),index:V.number(),logprobs:V.object({tokens:V.array(V.string()),token_logprobs:V.array(V.number()),top_logprobs:V.array(V.record(V.string(),V.number())).nullish()}).nullish()})),usage:Ih.nullish()}),ch]),zh=V.object({dimensions:V.number().optional(),user:V.string().optional()}),Bh=class{constructor(e,t){this.specificationVersion=`v2`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:r}){var i;if(e.length>this.maxEmbeddingsPerCall)throw new yo({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let a=(i=await _s({provider:`openai`,providerOptions:r,schema:zh}))??{},{responseHeaders:o,value:s,rawValue:c}=await K({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:Io(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:a.dimensions,user:a.user},failedResponseHandler:lh,successfulResponseHandler:Ds(Vh),abortSignal:n,fetch:this.config.fetch});return{embeddings:s.data.map(e=>e.embedding),usage:s.usage?{tokens:s.usage.prompt_tokens}:void 0,response:{headers:o,body:c}}}},Vh=V.object({data:V.array(V.object({embedding:V.array(V.number())})),usage:V.object({prompt_tokens:V.number()}).nullish()}),Hh={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},Uh=new Set([`gpt-image-1`]),Wh=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get maxImagesPerCall(){var e;return(e=Hh[this.modelId])??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c,l,u,d;let f=[];r!=null&&f.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&f.push({type:`unsupported-setting`,setting:`seed`});let p=(u=(l=(c=this.config._internal)?.currentDate)?.call(c))??new Date,{value:m,responseHeaders:h}=await K({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Io(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...(d=a.openai)??{},...Uh.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:lh,successfulResponseHandler:Ds(Gh),abortSignal:s,fetch:this.config.fetch});return{images:m.data.map(e=>e.b64_json),warnings:f,response:{timestamp:p,modelId:this.modelId,headers:h},providerMetadata:{openai:{images:m.data.map(e=>e.revised_prompt?{revisedPrompt:e.revised_prompt}:null)}}}}},Gh=V.object({data:V.array(V.object({b64_json:V.string(),revised_prompt:V.string().optional()}))}),Kh=V.object({container:V.union([V.string(),V.object({fileIds:V.array(V.string()).optional()})]).optional()}),qh=Ss({id:`openai.code_interpreter`,name:`code_interpreter`,inputSchema:V.object({})}),Jh=(e={})=>qh(e),Yh=V.object({filters:V.object({allowedDomains:V.array(V.string()).optional()}).optional(),searchContextSize:V.enum([`low`,`medium`,`high`]).optional(),userLocation:V.object({type:V.literal(`approximate`),country:V.string().optional(),city:V.string().optional(),region:V.string().optional(),timezone:V.string().optional()}).optional()}),Xh=Ss({id:`openai.web_search`,name:`web_search`,inputSchema:V.object({action:V.discriminatedUnion(`type`,[V.object({type:V.literal(`search`),query:V.string().nullish()}),V.object({type:V.literal(`open_page`),url:V.string()}),V.object({type:V.literal(`find`),url:V.string(),pattern:V.string()})]).nullish()})}),Zh=(e={})=>Xh(e),Qh={codeInterpreter:Jh,fileSearch:vh,webSearchPreview:bh,webSearch:Zh};function $h(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function eg({prompt:e,systemMessageMode:t,fileIdPrefixes:n}){var r,i,a,o,s,c;let l=[],u=[];for(let{role:d,content:f}of e)switch(d){case`system`:switch(t){case`system`:l.push({role:`system`,content:f});break;case`developer`:l.push({role:`developer`,content:f});break;case`remove`:u.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:l.push({role:`user`,content:f.map((e,t)=>{var r,i,a;switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&$h(e.data,n)?{file_id:e.data}:{image_url:`data:${t};base64,${Vc(e.data)}`},detail:(i=(r=e.providerOptions)?.openai)?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&$h(e.data,n)?{file_id:e.data}:{filename:(a=e.filename)??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${Vc(e.data)}`}};else throw new Ao({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={};for(let t of f)switch(t.type){case`text`:l.push({role:`assistant`,content:[{type:`output_text`,text:t.text}],id:(a=(i=(r=t.providerOptions)?.openai)?.itemId)??void 0});break;case`tool-call`:if(t.providerExecuted)break;l.push({type:`function_call`,call_id:t.toolCallId,name:t.toolName,arguments:JSON.stringify(t.input),id:(c=(s=(o=t.providerOptions)?.openai)?.itemId)??void 0});break;case`tool-result`:u.push({type:`other`,message:`tool result parts in assistant messages are not supported for OpenAI responses`});break;case`reasoning`:{let n=await _s({provider:`openai`,providerOptions:t.providerOptions,schema:tg}),r=n?.itemId;if(r!=null){let i=e[r],a=[];t.text.length>0?a.push({type:`summary_text`,text:t.text}):i!==void 0&&u.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(t)}.`}),i===void 0?(e[r]={type:`reasoning`,id:r,encrypted_content:n?.reasoningEncryptedContent,summary:a},l.push(e[r])):i.summary.push(...a)}else u.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(t)}.`});break}}break}case`tool`:for(let e of f){let t=e.output,n;switch(t.type){case`text`:case`error-text`:n=t.value;break;case`content`:case`json`:case`error-json`:n=JSON.stringify(t.value);break}l.push({type:`function_call_output`,call_id:e.toolCallId,output:n})}break;default:{let e=d;throw Error(`Unsupported role: ${e}`)}}return{messages:l,warnings:u}}var tg=V.object({itemId:V.string().nullish(),reasoningEncryptedContent:V.string().nullish()});function ng({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}function rg({tools:e,toolChoice:t,strictJsonSchema:n}){e=e?.length?e:void 0;let r=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:r};let i=[];for(let t of e)switch(t.type){case`function`:i.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,strict:n});break;case`provider-defined`:switch(t.id){case`openai.file_search`:{let e=_h.parse(t.args);i.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker}:void 0,filters:e.filters});break}case`openai.web_search_preview`:{let e=yh.parse(t.args);i.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=Yh.parse(t.args);i.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=Kh.parse(t.args);i.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}default:r.push({type:`unsupported-tool`,tool:t});break}break;default:r.push({type:`unsupported-tool`,tool:t});break}if(t==null)return{tools:i,toolChoice:void 0,toolWarnings:r};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:i,toolChoice:a,toolWarnings:r};case`tool`:return{tools:i,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`web_search_preview`||t.toolName===`web_search`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:r};default:{let e=a;throw new Ao({functionality:`tool choice type: ${e}`})}}}var ig=V.object({type:V.literal(`web_search_call`),id:V.string(),status:V.string(),action:V.discriminatedUnion(`type`,[V.object({type:V.literal(`search`),query:V.string().nullish()}),V.object({type:V.literal(`open_page`),url:V.string()}),V.object({type:V.literal(`find`),url:V.string(),pattern:V.string()})]).nullish()}),ag=20,og=V.array(V.object({token:V.string(),logprob:V.number(),top_logprobs:V.array(V.object({token:V.string(),logprob:V.number()}))})),sg=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){var p,m,h;let g=[],_=Mg(this.modelId);i!=null&&g.push({type:`unsupported-setting`,setting:`topK`}),s!=null&&g.push({type:`unsupported-setting`,setting:`seed`}),a!=null&&g.push({type:`unsupported-setting`,setting:`presencePenalty`}),o!=null&&g.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),n!=null&&g.push({type:`unsupported-setting`,setting:`stopSequences`});let{messages:v,warnings:y}=await eg({prompt:c,systemMessageMode:_.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes});g.push(...y);let b=await _s({provider:`openai`,providerOptions:l,schema:Ng}),x=(p=b?.strictJsonSchema)??!1,S=b?.include,C=typeof b?.logprobs==`number`?b?.logprobs:b?.logprobs===!0?ag:void 0;S=C?Array.isArray(S)?[...S,`message.output_text.logprobs`]:[`message.output_text.logprobs`]:S;let w=(m=u?.find(e=>e.type===`provider-defined`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`)))?.name;S=w?Array.isArray(S)?[...S,`web_search_call.action.sources`]:[`web_search_call.action.sources`]:S;let T={model:this.modelId,input:v,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||b?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:x,name:(h=f.name)??`response`,description:f.description,schema:f.schema}},...b?.textVerbosity&&{verbosity:b.textVerbosity}}},metadata:b?.metadata,parallel_tool_calls:b?.parallelToolCalls,previous_response_id:b?.previousResponseId,store:b?.store,user:b?.user,instructions:b?.instructions,service_tier:b?.serviceTier,include:S,prompt_cache_key:b?.promptCacheKey,safety_identifier:b?.safetyIdentifier,top_logprobs:C,..._.isReasoningModel&&(b?.reasoningEffort!=null||b?.reasoningSummary!=null)&&{reasoning:{...b?.reasoningEffort!=null&&{effort:b.reasoningEffort},...b?.reasoningSummary!=null&&{summary:b.reasoningSummary}}},..._.requiredAutoTruncation&&{truncation:`auto`}};_.isReasoningModel?(T.temperature!=null&&(T.temperature=void 0,g.push({type:`unsupported-setting`,setting:`temperature`,details:`temperature is not supported for reasoning models`})),T.top_p!=null&&(T.top_p=void 0,g.push({type:`unsupported-setting`,setting:`topP`,details:`topP is not supported for reasoning models`}))):(b?.reasoningEffort!=null&&g.push({type:`unsupported-setting`,setting:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),b?.reasoningSummary!=null&&g.push({type:`unsupported-setting`,setting:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),b?.serviceTier===`flex`&&!_.supportsFlexProcessing&&(g.push({type:`unsupported-setting`,setting:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete T.service_tier),b?.serviceTier===`priority`&&!_.supportsPriorityProcessing&&(g.push({type:`unsupported-setting`,setting:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete T.service_tier);let{tools:E,toolChoice:D,toolWarnings:O}=rg({tools:u,toolChoice:d,strictJsonSchema:x});return{webSearchToolName:w,args:{...T,tools:E,tool_choice:D},warnings:[...g,...O]}}async doGenerate(e){var t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_;let{args:v,warnings:y,webSearchToolName:b}=await this.getArgs(e),x=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:S,value:C,rawValue:w}=await K({url:x,headers:Io(this.config.headers(),e.headers),body:v,failedResponseHandler:lh,successfulResponseHandler:Ds(V.object({id:V.string(),created_at:V.number(),error:V.object({code:V.string(),message:V.string()}).nullish(),model:V.string(),output:V.array(V.discriminatedUnion(`type`,[V.object({type:V.literal(`message`),role:V.literal(`assistant`),id:V.string(),content:V.array(V.object({type:V.literal(`output_text`),text:V.string(),logprobs:og.nullish(),annotations:V.array(V.discriminatedUnion(`type`,[V.object({type:V.literal(`url_citation`),start_index:V.number(),end_index:V.number(),url:V.string(),title:V.string()}),V.object({type:V.literal(`file_citation`),file_id:V.string(),filename:V.string().nullish(),index:V.number().nullish(),start_index:V.number().nullish(),end_index:V.number().nullish(),quote:V.string().nullish()}),V.object({type:V.literal(`container_file_citation`)})]))}))}),V.object({type:V.literal(`code_interpreter_call`)}),V.object({type:V.literal(`function_call`),call_id:V.string(),name:V.string(),arguments:V.string(),id:V.string()}),ig,V.object({type:V.literal(`computer_call`),id:V.string(),status:V.string().optional()}),V.object({type:V.literal(`file_search_call`),id:V.string(),status:V.string().optional(),queries:V.array(V.string()).nullish(),results:V.array(V.object({attributes:V.object({file_id:V.string(),filename:V.string(),score:V.number(),text:V.string()})})).nullish()}),V.object({type:V.literal(`reasoning`),id:V.string(),encrypted_content:V.string().nullish(),summary:V.array(V.object({type:V.literal(`summary_text`),text:V.string()}))})])),service_tier:V.string().nullish(),incomplete_details:V.object({reason:V.string()}).nullable(),usage:cg})),abortSignal:e.abortSignal,fetch:this.config.fetch});if(C.error)throw new Ca({message:C.error.message,url:x,requestBodyValues:v,statusCode:400,responseHeaders:S,responseBody:w,isRetryable:!1});let T=[],E=[],D=!1;for(let p of C.output)switch(p.type){case`reasoning`:p.summary.length===0&&p.summary.push({type:`summary_text`,text:``});for(let e of p.summary)T.push({type:`reasoning`,text:e.text,providerMetadata:{openai:{itemId:p.id,reasoningEncryptedContent:(t=p.encrypted_content)??null}}});break;case`message`:for(let t of p.content){(r=(n=e.providerOptions)?.openai)?.logprobs&&t.logprobs&&E.push(t.logprobs),T.push({type:`text`,text:t.text,providerMetadata:{openai:{itemId:p.id}}});for(let e of t.annotations)e.type===`url_citation`?T.push({type:`source`,sourceType:`url`,id:(o=(a=(i=this.config).generateId)?.call(i))??Vo(),url:e.url,title:e.title}):e.type===`file_citation`&&T.push({type:`source`,sourceType:`document`,id:(l=(c=(s=this.config).generateId)?.call(s))??Vo(),mediaType:`text/plain`,title:(d=(u=e.quote)??e.filename)??`Document`,filename:(f=e.filename)??e.file_id})}break;case`function_call`:D=!0,T.push({type:`tool-call`,toolCallId:p.call_id,toolName:p.name,input:p.arguments,providerMetadata:{openai:{itemId:p.id}}});break;case`web_search_call`:T.push({type:`tool-call`,toolCallId:p.id,toolName:b??`web_search`,input:JSON.stringify({action:p.action}),providerExecuted:!0}),T.push({type:`tool-result`,toolCallId:p.id,toolName:b??`web_search`,result:{status:p.status},providerExecuted:!0});break;case`computer_call`:T.push({type:`tool-call`,toolCallId:p.id,toolName:`computer_use`,input:``,providerExecuted:!0}),T.push({type:`tool-result`,toolCallId:p.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:p.status||`completed`},providerExecuted:!0});break;case`file_search_call`:T.push({type:`tool-call`,toolCallId:p.id,toolName:`file_search`,input:``,providerExecuted:!0}),T.push({type:`tool-result`,toolCallId:p.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:p.status||`completed`,...p.queries&&{queries:p.queries},...p.results&&{results:p.results}},providerExecuted:!0});break}let O={openai:{responseId:C.id}};return E.length>0&&(O.openai.logprobs=E),typeof C.service_tier==`string`&&(O.openai.serviceTier=C.service_tier),{content:T,finishReason:ng({finishReason:(p=C.incomplete_details)?.reason,hasFunctionCall:D}),usage:{inputTokens:C.usage.input_tokens,outputTokens:C.usage.output_tokens,totalTokens:C.usage.input_tokens+C.usage.output_tokens,reasoningTokens:(h=(m=C.usage.output_tokens_details)?.reasoning_tokens)??void 0,cachedInputTokens:(_=(g=C.usage.input_tokens_details)?.cached_tokens)??void 0},request:{body:v},response:{id:C.id,timestamp:new Date(C.created_at*1e3),modelId:C.model,headers:S,body:w},providerMetadata:O,warnings:y}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r}=await this.getArgs(e),{responseHeaders:i,value:a}=await K({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:Io(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:lh,successfulResponseHandler:Es(yg),abortSignal:e.abortSignal,fetch:this.config.fetch}),o=this,s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l=[],u=null,d={},f=!1,p={},m;return{stream:a.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var i,a,h,g,_,v,y,b,x,S,C,w,T,E,D,O,k,A,j,ee,M;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let N=t.value;if(Eg(N))N.item.type===`function_call`?(d[N.output_index]={toolName:N.item.name,toolCallId:N.item.call_id},n.enqueue({type:`tool-input-start`,id:N.item.call_id,toolName:N.item.name})):N.item.type===`web_search_call`?(d[N.output_index]={toolName:r??`web_search`,toolCallId:N.item.id},n.enqueue({type:`tool-input-start`,id:N.item.id,toolName:r??`web_search`})):N.item.type===`computer_call`?(d[N.output_index]={toolName:`computer_use`,toolCallId:N.item.id},n.enqueue({type:`tool-input-start`,id:N.item.id,toolName:`computer_use`})):N.item.type===`file_search_call`?(d[N.output_index]={toolName:`file_search`,toolCallId:N.item.id},n.enqueue({type:`tool-input-start`,id:N.item.id,toolName:`file_search`})):N.item.type===`message`?n.enqueue({type:`text-start`,id:N.item.id,providerMetadata:{openai:{itemId:N.item.id}}}):Dg(N)&&(p[N.item.id]={encryptedContent:N.item.encrypted_content,summaryParts:[0]},n.enqueue({type:`reasoning-start`,id:`${N.item.id}:0`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:(i=N.item.encrypted_content)??null}}}));else if(xg(N)){if(N.item.type===`function_call`)d[N.output_index]=void 0,f=!0,n.enqueue({type:`tool-input-end`,id:N.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:N.item.call_id,toolName:N.item.name,input:N.item.arguments,providerMetadata:{openai:{itemId:N.item.id}}});else if(N.item.type===`web_search_call`)d[N.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:N.item.id}),n.enqueue({type:`tool-call`,toolCallId:N.item.id,toolName:`web_search`,input:JSON.stringify({action:N.item.action}),providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:N.item.id,toolName:`web_search`,result:{status:N.item.status},providerExecuted:!0});else if(N.item.type===`computer_call`)d[N.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:N.item.id}),n.enqueue({type:`tool-call`,toolCallId:N.item.id,toolName:`computer_use`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:N.item.id,toolName:`computer_use`,result:{type:`computer_use_tool_result`,status:N.item.status||`completed`},providerExecuted:!0});else if(N.item.type===`file_search_call`)d[N.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:N.item.id}),n.enqueue({type:`tool-call`,toolCallId:N.item.id,toolName:`file_search`,input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:N.item.id,toolName:`file_search`,result:{type:`file_search_tool_result`,status:N.item.status||`completed`,...N.item.queries&&{queries:N.item.queries},...N.item.results&&{results:N.item.results}},providerExecuted:!0});else if(N.item.type===`message`)n.enqueue({type:`text-end`,id:N.item.id});else if(Sg(N)){let e=p[N.item.id];for(let t of e.summaryParts)n.enqueue({type:`reasoning-end`,id:`${N.item.id}:${t}`,providerMetadata:{openai:{itemId:N.item.id,reasoningEncryptedContent:(a=N.item.encrypted_content)??null}}});delete p[N.item.id]}}else if(Tg(N)){let e=d[N.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:N.delta})}else wg(N)?(u=N.response.id,n.enqueue({type:`response-metadata`,id:N.response.id,timestamp:new Date(N.response.created_at*1e3),modelId:N.response.model})):bg(N)?(n.enqueue({type:`text-delta`,id:N.item_id,delta:N.delta}),(g=(h=e.providerOptions)?.openai)?.logprobs&&N.logprobs&&l.push(N.logprobs)):kg(N)?N.summary_index>0&&((_=p[N.item_id])==null||_.summaryParts.push(N.summary_index),n.enqueue({type:`reasoning-start`,id:`${N.item_id}:${N.summary_index}`,providerMetadata:{openai:{itemId:N.item_id,reasoningEncryptedContent:(y=(v=p[N.item_id])?.encryptedContent)??null}}})):Ag(N)?n.enqueue({type:`reasoning-delta`,id:`${N.item_id}:${N.summary_index}`,delta:N.delta,providerMetadata:{openai:{itemId:N.item_id}}}):Cg(N)?(s=ng({finishReason:(b=N.response.incomplete_details)?.reason,hasFunctionCall:f}),c.inputTokens=N.response.usage.input_tokens,c.outputTokens=N.response.usage.output_tokens,c.totalTokens=N.response.usage.input_tokens+N.response.usage.output_tokens,c.reasoningTokens=(S=(x=N.response.usage.output_tokens_details)?.reasoning_tokens)??void 0,c.cachedInputTokens=(w=(C=N.response.usage.input_tokens_details)?.cached_tokens)??void 0,typeof N.response.service_tier==`string`&&(m=N.response.service_tier)):Og(N)?N.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(D=(E=(T=o.config).generateId)?.call(T))??Vo(),url:N.annotation.url,title:N.annotation.title}):N.annotation.type===`file_citation`&&n.enqueue({type:`source`,sourceType:`document`,id:(A=(k=(O=o.config).generateId)?.call(O))??Vo(),mediaType:`text/plain`,title:(ee=(j=N.annotation.quote)??N.annotation.filename)??`Document`,filename:(M=N.annotation.filename)??N.annotation.file_id}):jg(N)&&n.enqueue({type:`error`,error:N})},flush(e){let t={openai:{responseId:u}};l.length>0&&(t.openai.logprobs=l),m!==void 0&&(t.openai.serviceTier=m),e.enqueue({type:`finish`,finishReason:s,usage:c,providerMetadata:t})}})),request:{body:t},response:{headers:i}}}},cg=V.object({input_tokens:V.number(),input_tokens_details:V.object({cached_tokens:V.number().nullish()}).nullish(),output_tokens:V.number(),output_tokens_details:V.object({reasoning_tokens:V.number().nullish()}).nullish()}),lg=V.object({type:V.literal(`response.output_text.delta`),item_id:V.string(),delta:V.string(),logprobs:og.nullish()}),ug=V.object({type:V.literal(`error`),code:V.string(),message:V.string(),param:V.string().nullish(),sequence_number:V.number()}),dg=V.object({type:V.enum([`response.completed`,`response.incomplete`]),response:V.object({incomplete_details:V.object({reason:V.string()}).nullish(),usage:cg,service_tier:V.string().nullish()})}),fg=V.object({type:V.literal(`response.created`),response:V.object({id:V.string(),created_at:V.number(),model:V.string(),service_tier:V.string().nullish()})}),pg=V.object({type:V.literal(`response.output_item.added`),output_index:V.number(),item:V.discriminatedUnion(`type`,[V.object({type:V.literal(`message`),id:V.string()}),V.object({type:V.literal(`reasoning`),id:V.string(),encrypted_content:V.string().nullish()}),V.object({type:V.literal(`function_call`),id:V.string(),call_id:V.string(),name:V.string(),arguments:V.string()}),V.object({type:V.literal(`web_search_call`),id:V.string(),status:V.string(),action:V.object({type:V.literal(`search`),query:V.string().optional()}).nullish()}),V.object({type:V.literal(`computer_call`),id:V.string(),status:V.string()}),V.object({type:V.literal(`file_search_call`),id:V.string(),status:V.string(),queries:V.array(V.string()).nullish(),results:V.array(V.object({attributes:V.object({file_id:V.string(),filename:V.string(),score:V.number(),text:V.string()})})).optional()})])}),mg=V.object({type:V.literal(`response.output_item.done`),output_index:V.number(),item:V.discriminatedUnion(`type`,[V.object({type:V.literal(`message`),id:V.string()}),V.object({type:V.literal(`reasoning`),id:V.string(),encrypted_content:V.string().nullish()}),V.object({type:V.literal(`function_call`),id:V.string(),call_id:V.string(),name:V.string(),arguments:V.string(),status:V.literal(`completed`)}),ig,V.object({type:V.literal(`computer_call`),id:V.string(),status:V.literal(`completed`)}),V.object({type:V.literal(`file_search_call`),id:V.string(),status:V.literal(`completed`),queries:V.array(V.string()).nullish(),results:V.array(V.object({attributes:V.object({file_id:V.string(),filename:V.string(),score:V.number(),text:V.string()})})).nullish()})])}),hg=V.object({type:V.literal(`response.function_call_arguments.delta`),item_id:V.string(),output_index:V.number(),delta:V.string()}),gg=V.object({type:V.literal(`response.output_text.annotation.added`),annotation:V.discriminatedUnion(`type`,[V.object({type:V.literal(`url_citation`),url:V.string(),title:V.string()}),V.object({type:V.literal(`file_citation`),file_id:V.string(),filename:V.string().nullish(),index:V.number().nullish(),start_index:V.number().nullish(),end_index:V.number().nullish(),quote:V.string().nullish()})])}),_g=V.object({type:V.literal(`response.reasoning_summary_part.added`),item_id:V.string(),summary_index:V.number()}),vg=V.object({type:V.literal(`response.reasoning_summary_text.delta`),item_id:V.string(),summary_index:V.number(),delta:V.string()}),yg=V.union([lg,dg,fg,pg,mg,hg,gg,_g,vg,ug,V.object({type:V.string()}).loose()]);function bg(e){return e.type===`response.output_text.delta`}function xg(e){return e.type===`response.output_item.done`}function Sg(e){return xg(e)&&e.item.type===`reasoning`}function Cg(e){return e.type===`response.completed`||e.type===`response.incomplete`}function wg(e){return e.type===`response.created`}function Tg(e){return e.type===`response.function_call_arguments.delta`}function Eg(e){return e.type===`response.output_item.added`}function Dg(e){return Eg(e)&&e.item.type===`reasoning`}function Og(e){return e.type===`response.output_text.annotation.added`}function kg(e){return e.type===`response.reasoning_summary_part.added`}function Ag(e){return e.type===`response.reasoning_summary_text.delta`}function jg(e){return e.type===`error`}function Mg(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r={requiredAutoTruncation:!1,systemMessageMode:`system`,supportsFlexProcessing:t,supportsPriorityProcessing:n};return e.startsWith(`gpt-5-chat`)?{...r,isReasoningModel:!1}:e.startsWith(`o`)||e.startsWith(`gpt-5`)||e.startsWith(`codex-`)||e.startsWith(`computer-use`)?e.startsWith(`o1-mini`)||e.startsWith(`o1-preview`)?{...r,isReasoningModel:!0,systemMessageMode:`remove`}:{...r,isReasoningModel:!0,systemMessageMode:`developer`}:{...r,isReasoningModel:!1}}var Ng=V.object({metadata:V.any().nullish(),parallelToolCalls:V.boolean().nullish(),previousResponseId:V.string().nullish(),store:V.boolean().nullish(),user:V.string().nullish(),reasoningEffort:V.string().nullish(),strictJsonSchema:V.boolean().nullish(),instructions:V.string().nullish(),reasoningSummary:V.string().nullish(),serviceTier:V.enum([`auto`,`flex`,`priority`]).nullish(),include:V.array(V.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),textVerbosity:V.enum([`low`,`medium`,`high`]).nullish(),promptCacheKey:V.string().nullish(),safetyIdentifier:V.string().nullish(),logprobs:V.union([V.boolean(),V.number().min(1).max(ag)]).optional()}),Pg=V.object({instructions:V.string().nullish(),speed:V.number().min(.25).max(4).default(1).nullish()}),Fg=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await _s({provider:`openai`,providerOptions:o,schema:Pg}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported-setting`,setting:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported-setting`,setting:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t,n,r;let i=(r=(n=(t=this.config._internal)?.currentDate)?.call(t))??new Date,{requestBody:a,warnings:o}=await this.getArgs(e),{value:s,responseHeaders:c,rawValue:l}=await K({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:Io(this.config.headers(),e.headers),body:a,failedResponseHandler:lh,successfulResponseHandler:Os(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:o,request:{body:JSON.stringify(a)},response:{timestamp:i,modelId:this.modelId,headers:c,body:l}}}},Ig=V.object({include:V.array(V.string()).optional(),language:V.string().optional(),prompt:V.string().optional(),temperature:V.number().min(0).max(1).default(0).optional(),timestampGranularities:V.array(V.enum([`word`,`segment`])).default([`segment`]).optional()}),Lg={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},Rg=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await _s({provider:`openai`,providerOptions:n,schema:Ig}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([zc(e)]);a.append(`model`,this.modelId);let s=Qo(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t,n,r,i,a,o,s,c;let l=(r=(n=(t=this.config._internal)?.currentDate)?.call(t))??new Date,{formData:u,warnings:d}=await this.getArgs(e),{value:f,responseHeaders:p,rawValue:m}=await ys({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:Io(this.config.headers(),e.headers),formData:u,failedResponseHandler:lh,successfulResponseHandler:Ds(zg),abortSignal:e.abortSignal,fetch:this.config.fetch}),h=f.language!=null&&f.language in Lg?Lg[f.language]:void 0;return{text:f.text,segments:(s=(o=(i=f.segments)?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end})))??(a=f.words)?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end})))??[],language:h,durationInSeconds:(c=f.duration)??void 0,warnings:d,response:{timestamp:l,modelId:this.modelId,headers:p,body:m}}}},zg=V.object({text:V.string(),language:V.string().nullish(),duration:V.number().nullish(),words:V.array(V.object({word:V.string(),start:V.number(),end:V.number()})).nullish(),segments:V.array(V.object({id:V.number(),seek:V.number(),start:V.number(),end:V.number(),text:V.string(),tokens:V.array(V.number()),temperature:V.number(),avg_logprob:V.number(),compression_ratio:V.number(),no_speech_prob:V.number()})).nullish()});function Bg(e={}){var t,n;let r=(t=Hc(e.baseURL))??`https://api.openai.com/v1`,i=(n=e.name)??`openai`,a=()=>({Authorization:`Bearer ${Xo({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers}),o=t=>new Sh(t,{provider:`${i}.chat`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),s=t=>new Fh(t,{provider:`${i}.completion`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),c=t=>new Bh(t,{provider:`${i}.embedding`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),l=t=>new Wh(t,{provider:`${i}.image`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),u=t=>new Rg(t,{provider:`${i}.transcription`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),d=t=>new Fg(t,{provider:`${i}.speech`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch}),f=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return p(e)},p=t=>new sg(t,{provider:`${i}.responses`,url:({path:e})=>`${r}${e}`,headers:a,fetch:e.fetch,fileIdPrefixes:[`file-`]}),m=function(e){return f(e)};return m.languageModel=f,m.chat=o,m.completion=s,m.responses=p,m.embedding=c,m.textEmbedding=c,m.textEmbeddingModel=c,m.image=l,m.imageModel=l,m.transcription=u,m.transcriptionModel=u,m.speech=d,m.speechModel=d,m.tools=Qh,m}Bg(),V.object({user:V.string().optional(),reasoningEffort:V.string().optional()});var Vg=V.object({error:V.object({message:V.string(),type:V.string().nullish(),param:V.any().nullish(),code:V.union([V.string(),V.number()]).nullish()})}),Hg={errorSchema:Vg,errorToMessage:e=>e.error.message},Ug=V.object({prompt_tokens:V.number().nullish(),completion_tokens:V.number().nullish(),total_tokens:V.number().nullish(),prompt_tokens_details:V.object({cached_tokens:V.number().nullish()}).nullish(),completion_tokens_details:V.object({reasoning_tokens:V.number().nullish(),accepted_prediction_tokens:V.number().nullish(),rejected_prediction_tokens:V.number().nullish()}).nullish()}).nullish();V.object({id:V.string().nullish(),created:V.number().nullish(),model:V.string().nullish(),choices:V.array(V.object({message:V.object({role:V.literal(`assistant`).nullish(),content:V.string().nullish(),reasoning_content:V.string().nullish(),reasoning:V.string().nullish(),tool_calls:V.array(V.object({id:V.string().nullish(),function:V.object({name:V.string(),arguments:V.string()})})).nullish()}),finish_reason:V.string().nullish()})),usage:Ug}),V.object({echo:V.boolean().optional(),logitBias:V.record(V.string(),V.number()).optional(),suffix:V.string().optional(),user:V.string().optional()});var Wg=V.object({prompt_tokens:V.number(),completion_tokens:V.number(),total_tokens:V.number()});V.object({id:V.string().nullish(),created:V.number().nullish(),model:V.string().nullish(),choices:V.array(V.object({text:V.string(),finish_reason:V.string()})),usage:Wg.nullish()}),V.object({dimensions:V.number().optional(),user:V.string().optional()}),V.object({data:V.array(V.object({embedding:V.array(V.number())})),usage:V.object({prompt_tokens:V.number()}).nullish(),providerMetadata:V.record(V.string(),V.record(V.string(),V.any())).optional()});var Gg=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v2`,this.maxImagesPerCall=10}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:a,headers:o,abortSignal:s}){var c,l,u,d,f;let p=[];r!=null&&p.push({type:`unsupported-setting`,setting:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&p.push({type:`unsupported-setting`,setting:`seed`});let m=(u=(l=(c=this.config._internal)?.currentDate)?.call(c))??new Date,{value:h,responseHeaders:g}=await K({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:Io(this.config.headers(),o),body:{model:this.modelId,prompt:e,n:t,size:n,...(d=a.openai)??{},response_format:`b64_json`},failedResponseHandler:Ts((f=this.config.errorStructure)??Hg),successfulResponseHandler:Ds(Kg),abortSignal:s,fetch:this.config.fetch});return{images:h.data.map(e=>e.b64_json),warnings:p,response:{timestamp:m,modelId:this.modelId,headers:g}}}},Kg=V.object({data:V.array(V.object({b64_json:V.string()}))});function qg(e){let t=[],n=[];for(let{role:n,content:r}of e)switch(n){case`system`:t.push({role:`system`,content:r});break;case`user`:if(r.length===1&&r[0].type===`text`){t.push({role:`user`,content:r[0].text});break}t.push({role:`user`,content:r.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${Vc(e.data)}`}}}else throw new Ao({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,n=[];for(let t of r)switch(t.type){case`text`:e+=t.text;break;case`tool-call`:n.push({id:t.toolCallId,type:`function`,function:{name:t.toolName,arguments:JSON.stringify(t.input)}});break}t.push({role:`assistant`,content:e,tool_calls:n.length>0?n:void 0});break}case`tool`:for(let e of r){let n=e.output,r;switch(n.type){case`text`:case`error-text`:r=n.value;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(n.value);break}t.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=n;throw Error(`Unsupported role: ${e}`)}}return{messages:t,warnings:n}}function Jg({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Yg(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`tool-calls`;case`content_filter`:return`content-filter`;default:return`unknown`}}var Xg=V.object({type:V.literal(`web`),country:V.string().length(2).optional(),excludedWebsites:V.array(V.string()).max(5).optional(),allowedWebsites:V.array(V.string()).max(5).optional(),safeSearch:V.boolean().optional()}),Zg=V.object({type:V.literal(`x`),xHandles:V.array(V.string()).optional()}),Qg=V.object({type:V.literal(`news`),country:V.string().length(2).optional(),excludedWebsites:V.array(V.string()).max(5).optional(),safeSearch:V.boolean().optional()}),$g=V.object({type:V.literal(`rss`),links:V.array(V.string().url()).max(1)}),e_=V.discriminatedUnion(`type`,[Xg,Zg,Qg,$g]),t_=V.object({reasoningEffort:V.enum([`low`,`high`]).optional(),searchParameters:V.object({mode:V.enum([`off`,`auto`,`on`]),returnCitations:V.boolean().optional(),fromDate:V.string().optional(),toDate:V.string().optional(),maxSearchResults:V.number().min(1).max(50).optional(),sources:V.array(e_).optional()}).optional()}),n_=V.object({error:V.object({message:V.string(),type:V.string().nullish(),param:V.any().nullish(),code:V.union([V.string(),V.number()]).nullish()})}),r_=Ts({errorSchema:n_,errorToMessage:e=>e.error.message});function i_({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)t.type===`provider-defined`?n.push({type:`unsupported-tool`,tool:t}):r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema}});if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:return{tools:r,toolChoice:i,toolWarnings:n};case`required`:return{tools:r,toolChoice:`required`,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:{let e=i;throw new Ao({functionality:`tool choice type: ${e}`})}}}var a_=class{constructor(e,t){this.specificationVersion=`v2`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,seed:c,responseFormat:l,providerOptions:u,tools:d,toolChoice:f}){var p,m,h;let g=[],_=(p=await _s({provider:`xai`,providerOptions:u,schema:t_}))??{};i!=null&&g.push({type:`unsupported-setting`,setting:`topK`}),a!=null&&g.push({type:`unsupported-setting`,setting:`frequencyPenalty`}),o!=null&&g.push({type:`unsupported-setting`,setting:`presencePenalty`}),s!=null&&g.push({type:`unsupported-setting`,setting:`stopSequences`}),l!=null&&l.type===`json`&&l.schema!=null&&g.push({type:`unsupported-setting`,setting:`responseFormat`,details:`JSON response format schema is not supported`});let{messages:v,warnings:y}=qg(e);g.push(...y);let{tools:b,toolChoice:x,toolWarnings:S}=i_({tools:d,toolChoice:f});g.push(...S);let C={model:this.modelId,max_tokens:t,temperature:n,top_p:r,seed:c,reasoning_effort:_.reasoningEffort,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{name:(m=l.name)??`response`,schema:l.schema,strict:!0}}:void 0,search_parameters:_.searchParameters?{mode:_.searchParameters.mode,return_citations:_.searchParameters.returnCitations,from_date:_.searchParameters.fromDate,to_date:_.searchParameters.toDate,max_search_results:_.searchParameters.maxSearchResults,sources:(h=_.searchParameters.sources)?.map(e=>({type:e.type,...e.type===`web`&&{country:e.country,excluded_websites:e.excludedWebsites,allowed_websites:e.allowedWebsites,safe_search:e.safeSearch},...e.type===`x`&&{x_handles:e.xHandles},...e.type===`news`&&{country:e.country,excluded_websites:e.excludedWebsites,safe_search:e.safeSearch},...e.type===`rss`&&{links:e.links}}))}:void 0,messages:v,tools:b,tool_choice:x};return{args:C,warnings:g}}async doGenerate(e){var t,n,r;let{args:i,warnings:a}=await this.getArgs(e),{responseHeaders:o,value:s,rawValue:c}=await K({url:`${(t=this.config.baseURL)??`https://api.x.ai/v1`}/chat/completions`,headers:Io(this.config.headers(),e.headers),body:i,failedResponseHandler:r_,successfulResponseHandler:Ds(s_),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=s.choices[0],u=[];if(l.message.content!=null&&l.message.content.length>0){let e=l.message.content,t=i.messages[i.messages.length-1];t?.role===`assistant`&&e===t.content&&(e=``),e.length>0&&u.push({type:`text`,text:e})}if(l.message.reasoning_content!=null&&l.message.reasoning_content.length>0&&u.push({type:`reasoning`,text:l.message.reasoning_content}),l.message.tool_calls!=null)for(let e of l.message.tool_calls)u.push({type:`tool-call`,toolCallId:e.id,toolName:e.function.name,input:e.function.arguments});if(s.citations!=null)for(let e of s.citations)u.push({type:`source`,sourceType:`url`,id:this.config.generateId(),url:e});return{content:u,finishReason:Yg(l.finish_reason),usage:{inputTokens:s.usage.prompt_tokens,outputTokens:s.usage.completion_tokens,totalTokens:s.usage.total_tokens,reasoningTokens:(r=(n=s.usage.completion_tokens_details)?.reasoning_tokens)??void 0},request:{body:i},response:{...Jg(s),headers:o,body:c},warnings:a}}async doStream(e){var t;let{args:n,warnings:r}=await this.getArgs(e),i={...n,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:a,value:o}=await K({url:`${(t=this.config.baseURL)??`https://api.x.ai/v1`}/chat/completions`,headers:Io(this.config.headers(),e.headers),body:i,failedResponseHandler:r_,successfulResponseHandler:Es(c_),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={inputTokens:void 0,outputTokens:void 0,totalTokens:void 0},l={},u={},d=this;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(t,n){var r,a;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){n.enqueue({type:`error`,error:t.error});return}let o=t.value;if(n.enqueue({type:`response-metadata`,...Jg(o)}),o.citations!=null)for(let e of o.citations)n.enqueue({type:`source`,sourceType:`url`,id:d.config.generateId(),url:e});o.usage!=null&&(c.inputTokens=o.usage.prompt_tokens,c.outputTokens=o.usage.completion_tokens,c.totalTokens=o.usage.total_tokens,c.reasoningTokens=(a=(r=o.usage.completion_tokens_details)?.reasoning_tokens)??void 0);let f=o.choices[0];if(f?.finish_reason!=null&&(s=Yg(f.finish_reason)),f?.delta==null)return;let p=f.delta,m=f.index;if(p.content!=null&&p.content.length>0){let e=p.content,t=i.messages[i.messages.length-1];if(t?.role===`assistant`&&e===t.content)return;let r=`text-${o.id||m}`;l[r]??(l[r]={type:`text`},n.enqueue({type:`text-start`,id:r})),n.enqueue({type:`text-delta`,id:r,delta:e})}if(p.reasoning_content!=null&&p.reasoning_content.length>0){let e=`reasoning-${o.id||m}`;if(u[e]===p.reasoning_content)return;u[e]=p.reasoning_content,l[e]??(l[e]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:e})),n.enqueue({type:`reasoning-delta`,id:e,delta:p.reasoning_content})}if(p.tool_calls!=null)for(let e of p.tool_calls){let t=e.id;n.enqueue({type:`tool-input-start`,id:t,toolName:e.function.name}),n.enqueue({type:`tool-input-delta`,id:t,delta:e.function.arguments}),n.enqueue({type:`tool-input-end`,id:t}),n.enqueue({type:`tool-call`,toolCallId:t,toolName:e.function.name,input:e.function.arguments})}},flush(e){for(let[t,n]of Object.entries(l))e.enqueue({type:n.type===`text`?`text-end`:`reasoning-end`,id:t});e.enqueue({type:`finish`,finishReason:s,usage:c})}})),request:{body:i},response:{headers:a}}}},o_=V.object({prompt_tokens:V.number(),completion_tokens:V.number(),total_tokens:V.number(),completion_tokens_details:V.object({reasoning_tokens:V.number().nullish()}).nullish()}),s_=V.object({id:V.string().nullish(),created:V.number().nullish(),model:V.string().nullish(),choices:V.array(V.object({message:V.object({role:V.literal(`assistant`),content:V.string().nullish(),reasoning_content:V.string().nullish(),tool_calls:V.array(V.object({id:V.string(),type:V.literal(`function`),function:V.object({name:V.string(),arguments:V.string()})})).nullish()}),index:V.number(),finish_reason:V.string().nullish()})),object:V.literal(`chat.completion`),usage:o_,citations:V.array(V.string().url()).nullish()}),c_=V.object({id:V.string().nullish(),created:V.number().nullish(),model:V.string().nullish(),choices:V.array(V.object({delta:V.object({role:V.enum([`assistant`]).optional(),content:V.string().nullish(),reasoning_content:V.string().nullish(),tool_calls:V.array(V.object({id:V.string(),type:V.literal(`function`),function:V.object({name:V.string(),arguments:V.string()})})).nullish()}),finish_reason:V.string().nullish(),index:V.number()})),usage:o_.nullish(),citations:V.array(V.string().url()).nullish()}),l_={errorSchema:n_,errorToMessage:e=>e.error.message};function u_(e={}){var t;let n=Hc((t=e.baseURL)??`https://api.x.ai/v1`),r=()=>({Authorization:`Bearer ${Xo({apiKey:e.apiKey,environmentVariableName:`XAI_API_KEY`,description:`xAI API key`})}`,...e.headers}),i=t=>new a_(t,{provider:`xai.chat`,baseURL:n,headers:r,generateId:Vo,fetch:e.fetch}),a=t=>new Gg(t,{provider:`xai.image`,url:({path:e})=>`${n}${e}`,headers:r,fetch:e.fetch,errorStructure:l_}),o=e=>i(e);return o.languageModel=i,o.chat=i,o.textEmbeddingModel=e=>{throw new mo({modelId:e,modelType:`textEmbeddingModel`})},o.imageModel=a,o.image=a,o}u_();function d_(e){if(!e.body)throw Error(`Response body is required`);let t=e.headers.get(`x-blink-stream-response-format`);if(!t||t===`ui-message`)return e.body.pipeThrough(new TextDecoderStream).pipeThrough(new Fo).pipeThrough(new TransformStream({async transform(e,t){if(e.data===`[DONE]`)return;let n=await ms({text:e.data});n.success?t.enqueue(n.value):t.error(n.error)}}));let n=e=>lp({model:e,prompt:[{role:`user`,content:[{type:`text`,text:`Hello, world!`}]}]}).toUIMessageStream();switch(t){case`openai-chat`:return n(Bg({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`openai-response`:return n(Bg({apiKey:`ignored`,fetch:(t,n)=>e}).responses(`fake-model`));case`anthropic`:return n(Dm({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`google`:return n(sh({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));case`xai`:return n(u_({apiKey:`ignored`,fetch:(t,n)=>e}).chat(`fake-model`));default:throw Error(`Unsupported response format: ${t}`)}}var f_=(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}},p_=Symbol(),m_=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof L_?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?h_(e,{all:n,dot:r}):{}};async function h_(e,t){let n=await e.formData();return n?g_(n,t):{}}function g_(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?__(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(v_(n,e,t),delete n[e])}),n}var __=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},v_=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},y_=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},b_=e=>{let{groups:t,path:n}=x_(e),r=y_(n);return S_(r,t)},x_=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},S_=(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},C_={},w_=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return C_[r]||(n[2]?C_[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:C_[r]=[e,n[1],!0]),C_[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}})}},E_=e=>T_(e,decodeURI),D_=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.slice(n,e===-1?void 0:e);return E_(i.includes(`%25`)?i.replace(/%25/g,`%2525`):i)}else if(e===63)break}return t.slice(n,r)},O_=e=>{let t=D_(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},k_=(e,t,...n)=>(n.length&&(t=k_(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),A_=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(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},j_=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:T_(e,F_)):e,M_=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?${t}`,8);for(n===-1&&(n=e.indexOf(`&${t}`,8));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return j_(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=j_(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=j_(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},N_=M_,P_=(e,t)=>M_(e,t,!0),F_=decodeURIComponent,I_=e=>T_(e,F_),L_=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?I_(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?I_(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return N_(this.url,e)}queries(e){return P_(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await m_(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[p_](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},R_={Stringify:1,BeforeStream:2,Stream:3},z_=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},B_=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=>B_(e,t,!1,r,i))).then(()=>i[0]));return n?z_(await o,a):o},V_=`text/plain; charset=UTF-8`,H_=(e,t)=>({"Content-Type":e,...t}),U_=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new L_(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.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.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,H_(V_,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,H_(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,H_(`text/html; charset=UTF-8`,n));return typeof e==`object`?B_(e,R_.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.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},W_=`ALL`,G_=`all`,K_=[`get`,`post`,`put`,`delete`,`options`,`patch`],q_=`Can not add a route since the matcher is already built.`,J_=class extends Error{},Y_=`__COMPOSED_HANDLER`,X_=e=>e.text(`404 Not Found`,404),Z_=(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)},Q_=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...K_,G_];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(W_,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??D_:O_}#clone(){let e=new Q_({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=X_;errorHandler=Z_;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===Z_?r=e.handler:(r=async(n,r)=>(await f_([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[Y_]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=k_(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=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]};r||=(()=>{let t=k_(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(W_,k_(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=k_(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new U_(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=f_(a[0],this.errorHandler,this.#notFoundHandler);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.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(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${k_(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},$_=`[^/]+`,ev=`.*`,tv=`(?:|/.*)`,nv=Symbol(),rv=new Set(`.\\+*[^]$()`);function iv(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===ev||e===tv?1:t===ev||t===tv?-1:e===$_?1:t===$_?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var av=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw nv;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,ev]:[``,``,$_]:a===`/*`?[``,``,tv]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||$_;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw nv;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==ev&&e!==tv))throw nv;if(i)return;c=this.#children[t]=new av,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==ev&&e!==tv))throw nv;if(i)return;c=this.#children[a]=new av}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(iv),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:rv.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},ov=class{#context={varIndex:0};#root=new av;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.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]}},sv=[],cv=[/^$/,[],Object.create(null)],lv=Object.create(null);function uv(e){return lv[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function dv(){lv=Object.create(null)}function fv(e){let t=new ov,n=[];if(e.length===0)return cv;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),sv]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===nv?new J_(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function pv(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(uv(n).test(t))return[...e[n]]}}var mv=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[W_]:Object.create(null)},this.#routes={[W_]:Object.create(null)}}add(e,t,n){let r=this.#middleware,i=this.#routes;if(!r||!i)throw Error(q_);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t[W_]).forEach(n=>{t[e][n]=[...t[W_][n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=uv(t);e===W_?Object.keys(r).forEach(e=>{r[e][t]||=pv(r[e],t)||pv(r[W_],t)||[]}):r[e][t]||=pv(r[e],t)||pv(r[W_],t)||[],Object.keys(r).forEach(t=>{(e===W_||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===W_||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=A_(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===W_||e===o)&&(i[o][c]||=[...pv(r[o],c)||pv(r[W_],c)||[]],i[o][c].push([n,a-s+t+1]))})}}match(e,t){dv();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[W_],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],sv];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===W_;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==W_&&t.push(...Object.keys(r[W_]).map(e=>[e,r[W_][e]])):(n||=!0,t.push(...i))}),n?fv(t):null}},hv=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(q_);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,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 J_)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},gv=Object.create(null),_v=class{#methods;#children;#patterns;#order=0;#params=gv;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,i=b_(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=w_(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new _v,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[W_],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==gv||r&&r!==gv))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=gv;let r=this,i=[r],a=y_(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===gv?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},vv=class{name=`TrieRouter`;#node;constructor(){this.#node=new _v}add(e,t,n){let r=A_(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#node.insert(e,r[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},yv=class extends Q_{constructor(e={}){super(e),this.router=e.router??new hv({routers:[new mv,new vv]})}},bv=/^[\w!#$%&'*.^`|~+-]+$/,xv=/^[ !#-:<-[\]-~]*$/,Sv=(e,t)=>{if(t&&e.indexOf(t)===-1)return{};let n=e.trim().split(`;`),r={};for(let e of n){e=e.trim();let n=e.indexOf(`=`);if(n===-1)continue;let i=e.substring(0,n).trim();if(t&&t!==i||!bv.test(i))continue;let a=e.substring(n+1).trim();if(a.startsWith(`"`)&&a.endsWith(`"`)&&(a=a.slice(1,-1)),xv.test(a)&&(r[i]=a.indexOf(`%`)===-1?a:T_(a,F_),t))break}return r},Cv=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=Sv(r,e);return i[e]}if(!r)return{};let i=Sv(r);return i},wv=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},Tv=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},Ev=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Dv=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,Ov=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,kv=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!Ev.test(a))break;try{i=await n.req.json()}catch{throw new wv(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(Dv.test(a)||Ov.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await Tv(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new wv(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=Cv(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const Av=()=>new yv,jv=(e,t)=>e.json({error:t},400),Mv=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Nv=Av().get(`/kv/:key`,async e=>{let{key:t,err:n}=Mv(e);if(n)return jv(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,kv(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?jv(t,`Value is too long. Max length is 1024 characters.`):{value:n}:jv(t,`Value must be a string`):jv(t,`Value is required`)}),async e=>{let{key:t,err:n}=Mv(e);if(n)return jv(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Mv(e);return n?jv(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),Pv=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Fv=Av().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=Pv(e);if(n)return jv(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,kv(`json`,(e,t)=>{let n=e.messages;if(!n)return jv(t,`Messages are required`);if(!Array.isArray(n))return jv(t,`Messages must be an array`);if(n.length===0)return jv(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?jv(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=Pv(e);if(n)return jv(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)}),Iv=new yv().route(`/storage`,Nv).route(`/chat`,Fv);var Lv=Iv;function Rv(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function zv(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const Bv=/^\.+(\\|\/)|^\.+$/,Vv=/[. ]+$/,Hv=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,Uv=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,Wv=e=>e===``,Gv=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,Kv=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let qv;function Jv(){return qv??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),qv}function Yv(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(Rv().test(n)||[...n].some(e=>Uv.test(e)&&!Wv(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(Kv,` `),n.length>0&&(e=e.replaceAll(Gv,`$1`)),e=e.replace(Vv,``),e=e.replace(Bv,n),e=e.replace(Rv(),n),e=e.replaceAll(Hv,e=>Wv(e)?e:n),e.length===0&&(e=n),e=zv().test(e)?e+n:e;let r=typeof t.maxLength==`number`?t.maxLength:100;if(e.length>r){let t=e.lastIndexOf(`.`);if(t===-1)e=Xv(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=Xv(n,a)+i}}return e}function Xv(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of Jv().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}const Zv=(e,t,n)=>{let r,i=new Map,a=e=>{g.mkdirSync(e,{recursive:!0})},o=e=>{let t=g.statSync(e,{throwIfNoEntry:!1});if(t)return JSON.parse(g.readFileSync(e,`utf-8`))},s=e=>{try{g.fdatasyncSync(e)}catch{}try{g.closeSync(e)}catch{}},c=e=>{try{let t=g.openSync(e,`r`);try{g.fsyncSync(t)}finally{g.closeSync(t)}}catch{}},l=(e,t)=>{let n=m.dirname(e);a(n);let r=m.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i=JSON.stringify(t,null,2),o;try{o=g.openSync(r,`w`),g.writeFileSync(o,i,`utf-8`),s(o),o=void 0,g.renameSync(r,e),c(e),c(n)}catch(e){if(o!==void 0)try{g.closeSync(o)}catch{}try{g.rmSync(r,{force:!0})}catch{}throw e}},u=()=>{if(r)return r;let t=m.join(e,`index.json`),n=o(t)??{ids:{}};return n.ids||={},r=n,n},d=t=>{let n=m.join(e,`index.json`);l(n,t),r=t},f=t=>{let r=i.get(t);if(r)return r;let a=u(),o=a.ids[t];if(!o)return;let s=m.join(e,o),c=g.statSync(s,{throwIfNoEntry:!1});if(!c)return;let l=JSON.parse(g.readFileSync(s,`utf-8`));return i.set(t,n?.hydrate?n.hydrate(l):l),l},p=(r,a)=>{let o=i.get(r);if(n?.shouldWriteToDisk&&o&&!n.shouldWriteToDisk(o,a)){i.set(r,a);return}let s=a,c=s[t],f=String(c),p=Yv(f,{replacement:`_`}),h=p+`.json`,g=u();g.ids[f]=h,g.current=f;let _=m.join(e,h);l(_,n?.serialize?.(a)??a),d(g),i.set(r,a)};return{get(e){return f(e)},set(e,t){p(e,t)},update(e,t){let n=this.get(e);if(!n)throw Error(`Key ${e} not found`);p(e,{...n,...t})},delete(t){let n=u(),r=n.ids[t];if(r){let i=m.join(e,r);try{g.rmSync(i,{force:!0}),c(e)}catch{}delete n.ids[t],n.current===t&&(n.current=void 0),d(n)}i.delete(t)},list(){let t=g.statSync(e,{throwIfNoEntry:!1});if(!t)return[];let n=u();return Object.keys(n.ids)}}};function Qv(e){e.dataDirectory||=re.mkdtempSync(pe());let t=Zv(O(e.dataDirectory,`chats`),`id`,{hydrate:e=>({...e,status:`idle`,queuedMessages:[],streamingMessage:void 0}),serialize:t=>(e.serializeChat&&(t=e.serializeChat(t)),{id:t.id,created_at:t.created_at,updated_at:t.updated_at,messages:t.messages}),shouldWriteToDisk:(e,t)=>e.updated_at!==t.updated_at||e.status!==t.status||e.messages.length!==t.messages.length}),n=new ot,r=t.set;t.set=(e,i)=>{r.call(t,e,i),n.emit(i)};let i=t.update;t.update=(e,r)=>{i.call(t,e,r),n.emit(t.get(e))};let a={},o=O(e.dataDirectory,`storage.json`);re.existsSync(o)&&(a=JSON.parse(re.readFileSync(o,`utf-8`)));let s=new AbortController,c=new Map,l=e=>{let t=c.get(e);t?.signal.aborted||t?.abort()},u,f=(e,t=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:t,metadata:e.metadata}),p=async(n,r)=>{let i=t.get(n);if(!i)return;let a=r?[...i.messages,...r.map(e=>f(e))]:i.messages;t.update(n,{status:`streaming`,updated_at:new Date().toISOString(),messages:a});let o=new AbortController;c.set(n,o);let l;try{l=await e.sendMessages({messages:[...a],chat:{id:n}},AbortSignal.any([s.signal,o.signal]))}catch(e){t.update(n,{status:`error`,error:e instanceof Error?e:Error(String(e)),streamingMessage:void 0});return}let u=d_(l),d=Kp({stream:u}),m=crypto.randomUUID(),h;if(i=t.get(n),!i)return;try{for await(let e of d){if(o.signal.aborted)break;h=e,t.update(n,{streamingMessage:f(e,m)})}}catch(e){let r=!1;if(e instanceof Error&&e.message.includes(`Controller is already closed`)&&(r=!0),e instanceof Error&&e.name===`AbortError`&&(r=!0),r){if(h){if(i=t.get(n),!i)return;t.update(n,{status:`idle`,messages:[...i.messages,f(h,m)],streamingMessage:void 0});return}throw e}}if(i=t.get(n),!i)return;let g=[...i.messages];if(h&&g.push(f(h,m)),i?.queuedMessages.length){t.update(n,{messages:[...i.messages,...i.queuedMessages.map(e=>f(e))],queuedMessages:[]}),await p(n);return}if(h&&e.shouldLoop&&e.shouldLoop({messages:g})){t.update(n,{messages:g,streamingMessage:void 0}),await p(n);return}t.update(n,{status:`idle`,streamingMessage:void 0,messages:g})},m={chat:{async upsert(e){let n=await t.get(e);return n?await t.set(e,{...n,updated_at:new Date().toISOString(),status:`idle`}):await t.set(e,{id:e,messages:[],created_at:new Date().toISOString(),updated_at:new Date().toISOString(),status:`idle`,streamingMessage:void 0,queuedMessages:[]}),{id:e}},async sendMessages(e,n){let r=t.get(e);if(!r)throw Error(`Chat not found`);if(n.behavior===`append`){t.set(e,{...r,messages:[...r.messages,...n.messages.map(e=>f(e))]});return}if(r.status===`streaming`){if(n.behavior===`enqueue`){t.set(e,{...r,queuedMessages:[...r.queuedMessages,...n.messages]});return}l(e),await u}u=p(e,n.messages)}},storage:{kv:{get(e){return Promise.resolve(a[e])},set(e,t){return a[e]=t,re.writeFileSync(o,JSON.stringify(a),`utf-8`),Promise.resolve()},del(e){return delete a[e],re.writeFileSync(o,JSON.stringify(a),`utf-8`),Promise.resolve()}}}},h=d(ua(e=>Lv.fetch(e,m)));return h.listen(e.port),{url:`http://127.0.0.1:${h.address().port}`,runtime:m,onChatChanged:n.event,listChats:()=>t.list(),getChat:e=>t.get(e),stopChat:e=>{l(e)},upsertChatMessage:(e,n)=>{let r=t.get(e);if(!r)throw Error(`Chat not found`);let i=r.messages.length>0?r.messages.at(-1):void 0;if(i&&JSON.stringify(i.parts)===JSON.stringify(n.parts))return;let a=[...r.messages,f(n)];t.set(e,{...r,messages:a})},resetChat:e=>{t.set(e,{id:e,messages:[],status:`idle`,queuedMessages:[],streamingMessage:void 0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}),l(e)},upsertChat:e=>{let n=t.get(e);if(n)return n;let r={id:e,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[],status:`idle`,queuedMessages:[],streamingMessage:void 0};return t.set(e,r),r},dispose:()=>{h.close(),s.abort()}}}const $v=B.object({host:B.string(),port:B.number(),supportsRequests:B.boolean()});async function ey(e){let t=A(e),n=da(t),r=fa(n),i=process.env.HOST||`127.0.0.1`,a=process.env.PORT?parseInt(process.env.PORT):3e3,o=d(r);o.listen(a,i,()=>{let e={host:i,port:a,supportsRequests:n.supportsRequests??!1};console.log(JSON.stringify(e))}).on(`error`,e=>{console.error(e),process.exit(1)})}async function ty(e){let t=process.argv[0];if(!t)throw Error(`Executable not found`);let n=process.argv[1];if(!n)throw Error(`Entrypoint not found`);n.endsWith(`.ts`)&&(n=O(import.meta.dirname,`index.ts`));let r=e.port;r||=await ny();let i=e.host;i||=`127.0.0.1`;let a=ne(t,[n,`serve`,e.entrypoint],{stdio:`pipe`,env:{...process.env,...e.env,BLINK_API_SERVER_URL:e.apiServerUrl,PORT:r.toString(),HOST:i}}),o,s,c=new Promise((e,t)=>{o=e,s=t});a.stdout.on(`data`,t=>{let n=Buffer.from(t).toString().trim();try{let e=$v.parse(JSON.parse(n));o(e);return}catch{}e.onStdout?.(Buffer.from(t).toString())}),a.stderr.on(`data`,t=>{e.onStderr?.(Buffer.from(t).toString())}),a.on(`error`,e=>{u.emit(e),s(e)}),a.on(`exit`,e=>{l.emit(e),s(Error(`Server exited with code ${e}`))}),a.on(`close`,e=>{l.emit(e)});let l=new ot,u=new ot,d=await c;return{info:d,onError:u.event,onExit:l.event,url:`http://${i}:${r}`,dispose:()=>{a.kill()},[Symbol.dispose](){a.kill()}}}async function ny(){let e=d();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}B.object({email:B.string().email(),password:B.string().min(8)}),B.object({email:B.string().email(),code:B.string()}),B.object({email:B.string().email(),password:B.string().min(8)});var ry=class{constructor(e,t){this.client=e,this.baseURL=t}async token(e,t={timeout:12e4}){return new Promise((n,r)=>{let i=crypto.randomUUID(),a=this.client.websocket(`/api/auth/token?id=${i}`),o=new URL(`/auth?id=${i}`,this.baseURL),s=setTimeout(()=>{r(Error(`Timeout waiting for the user to authenticate`))},t.timeout);a.onerror=e=>{clearTimeout(s),console.log(`error`,e),r(Error(`Failed to connect to server`))},a.onopen=()=>{e(o.toString(),i)},a.onmessage=e=>{typeof e.data==`string`&&(clearTimeout(s),n(e.data))}})}};const Y=async(e,t)=>{if(e.status!==t){let n=await e.text();try{let r=JSON.parse(n);throw r.message?Error(r.message,{cause:r.details}):Error(`Expected status ${t}, got ${e.status}: ${n}`)}catch{throw Error(`Expected status ${t}, got ${e.status}: ${n}`)}}},iy=B.object({per_page:B.number().int().positive().max(100).default(10).optional(),page:B.number().int().nonnegative().default(0).optional()}),ay=e=>B.object({has_more:B.boolean(),items:B.array(e)}),oy=B.object({limit:B.number().int().positive().max(100).default(10).optional(),cursor:B.string().optional()}),sy=e=>B.object({next_cursor:B.string().nullable(),items:B.array(e)}),cy=B.record(B.string().min(1).max(64),B.string().max(512)).nullable().refine(e=>e?Object.keys(e).length<=16:!0,{message:`Metadata must contain at most 16 keys`}),ly=/^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/i;B.object({agent_id:B.uuid(),deployment_id:B.uuid()}),B.object({agent_id:B.uuid(),deployment_id:B.uuid()});const uy=B.object({path:B.string(),id:B.uuid()}),dy=uy.or(B.object({path:B.string(),data:B.string().max(1024*1024*5)})),fy=B.enum([`production`,`preview`]);B.object({agent_id:B.uuid(),files:B.array(dy),target:fy,entrypoint:B.string().optional(),message:B.string().max(128).optional()});const py=B.object({id:B.uuid(),number:B.number().int().positive(),created_at:B.iso.datetime(),updated_at:B.iso.datetime(),created_by:B.uuid().nullable(),created_from:B.enum([`cli`]),agent_id:B.uuid(),files:B.array(uy),status:B.enum([`success`,`failed`,`deploying`,`pending`]),target:fy,error_message:B.string().nullable(),user_message:B.string().nullable(),platform:B.enum([`lambda`]),platform_memory_mb:B.number().int().positive(),platform_region:B.string().nullable()});B.object({id:B.uuid(),created_at:B.string().datetime(),updated_at:B.string().datetime(),agent_id:B.uuid(),deployment_id:B.uuid(),level:B.enum([`log`,`info`,`warning`,`error`]),message:B.string()}),iy.extend({agent_id:B.uuid(),order:B.enum([`asc`,`desc`]).default(`asc`).optional()}),ay(py);var my=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString()),e.order&&t.set(`order`,e.order);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments?${t.toString()}`);return await Y(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);return await Y(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/deployments`,JSON.stringify(e));return await Y(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/deployments/${e.deployment_id}`);await Y(t,200)}async promote(){}async logs(){}};B.object({agent_id:B.uuid(),target:fy.array().optional()}),B.object({id:B.uuid(),created_at:B.date(),updated_at:B.date(),created_by:B.uuid(),updated_by:B.uuid(),key:B.string(),value:B.string().nullable(),secret:B.boolean(),target:fy.array()});const hy=B.object({key:B.string(),value:B.string(),secret:B.boolean(),target:fy.array().optional(),upsert:B.boolean().optional()});hy.extend({agent_id:B.uuid()}),B.object({agent_id:B.uuid(),id:B.uuid()}),B.object({agent_id:B.uuid(),id:B.uuid(),key:B.string().optional(),value:B.string().optional(),secret:B.boolean().optional(),target:fy.array().default([`preview`,`production`]).optional()});var gy=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;if(e.target)for(let n of e.target)t.append(`target`,n);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/env?${t.toString()}`);return await Y(n,200),n.json()}async create(e){let t=await this.client.request(`POST`,`/api/agents/${e.agent_id}/env`,JSON.stringify(e));return await Y(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e.agent_id}/env/${e.id}`);await Y(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/agents/${e.agent_id}/env/${e.id}`,JSON.stringify(e));return await Y(t,200),t.json()}};const _y=B.object({id:B.string(),agent_id:B.uuid(),agent_deployment_id:B.uuid(),received_at:B.date(),request_method:B.string(),request_handler_location:B.string().nullable(),duration_ms:B.number().nullable(),error:B.string().nullable(),response_status:B.number().nullable()});_y.extend({request_headers:B.record(B.string(),B.string()),request_headers_redacted:B.boolean(),request_body:B.string().nullable(),request_body_redacted:B.boolean(),response_headers:B.record(B.string(),B.string()).nullable(),response_headers_redacted:B.boolean(),response_body:B.string().nullable(),response_body_redacted:B.boolean()}),oy.extend({agent_id:B.string(),agent_deployment_id:B.number().optional()}),sy(_y);var vy=class{constructor(e){this.client=e}async log(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs/${e.webhook_id}`);return await Y(t,200),t.json()}async logs(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id.toString()),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/webhook/logs?${t.toString()}`);return await Y(n,200),n.json()}};oy.extend({agent_id:B.uuid(),agent_deployment_id:B.uuid().optional()}),B.object({agent_id:B.uuid(),run_id:B.uuid()});var yy=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs?${t.toString()}`);return await Y(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/runs/${e.run_id}`);return await Y(t,200),t.json()}};const by=B.enum([`streaming`,`stalled`,`completed`,`interrupted`,`error`]),xy=B.enum([`tool_call`,`queued_message`]),Sy=B.object({id:B.uuid(),number:B.number().int().positive(),chat_id:B.uuid(),chat_run_id:B.uuid(),agent_id:B.uuid(),agent_deployment_id:B.uuid(),started_at:B.string().datetime(),status:by,error:B.string().nullable(),continuation_reason:xy.nullable(),response_status:B.number().nullable(),response_message_id:B.uuid().nullable()});Sy.extend({heartbeat_at:B.date(),completed_at:B.date().nullable(),interrupted_at:B.date().nullable(),first_message_id:B.uuid().nullable(),last_message_id:B.uuid().nullable(),response_headers:B.record(B.string(),B.string()).nullable(),response_headers_redacted:B.boolean(),response_body:B.string().nullable(),response_body_redacted:B.boolean()}),oy.extend({chat_id:B.uuid(),run_id:B.uuid().optional()}),sy(Sy);var Cy=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id);let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps?${t.toString()}`);return await Y(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/steps/${e.step_id}`);return await Y(t,200),t.json()}};oy.extend({agent_id:B.uuid(),agent_deployment_id:B.uuid().optional(),chat_id:B.uuid().optional(),run_id:B.uuid().optional(),status:by.optional()}),sy(Sy);var wy=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.run_id&&t.set(`run_id`,e.run_id),e.agent_deployment_id&&t.set(`agent_deployment_id`,e.agent_deployment_id),e.chat_id&&t.set(`chat_id`,e.chat_id),e.status&&t.set(`status`,e.status);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps?${t.toString()}`);return await Y(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e.agent_id}/steps/${e.step_id}`);return await Y(t,200),t.json()}};z.object({start_time:z.iso.datetime().pipe(z.coerce.date()),end_time:z.iso.datetime().pipe(z.coerce.date()),message_pattern:z.string().optional(),limit:z.string().pipe(z.coerce.number().min(1).max(1e4)).optional()});const Ty=z.object({timestamp:z.iso.datetime().pipe(z.coerce.date()),message:z.string(),level:z.enum([`info`,`error`,`warn`])}),Ey=z.object({logs:z.array(Ty)});var Dy=class{constructor(e){this.client=e}async logs(e){let t=new URLSearchParams;t.set(`start_time`,e.start_time.toISOString()),t.set(`end_time`,e.end_time.toISOString()),e.limit&&t.set(`limit`,e.limit.toString()),e.message_pattern&&t.set(`message_pattern`,e.message_pattern);let n=await this.client.request(`GET`,`/api/agents/${e.agent_id}/logs?${t.toString()}`);await Y(n,200);let r=await n.json();return Ey.parse(r)}};const Oy=B.enum([`private`,`public`]);B.object({organization_id:B.uuid(),name:B.string().regex(ly),description:B.string().optional(),visibility:Oy.default(`private`).optional(),files:B.array(dy).optional(),entrypoint:B.string().optional(),env:B.array(hy).optional()});const ky=B.object({id:B.uuid(),organization_id:B.uuid(),created_at:B.iso.datetime(),updated_at:B.iso.datetime(),created_by:B.uuid(),name:B.string().regex(ly),description:B.string().nullable(),avatar_url:B.string().nullable(),visibility:Oy,active_deployment_id:B.uuid().nullable(),webhook_route:B.string().url().nullable().describe(`The route for the agent's webhook. Only visible to owners.`)});B.object({id:B.uuid(),name:B.string().regex(ly).optional(),description:B.string().optional(),visibility:Oy.optional(),active_deployment_id:B.uuid().optional()}),iy.extend({organization_id:B.uuid().optional()}),ay(ky);var Ay=class{constructor(e){this.client=e,this.deployments=new my(e),this.env=new gy(e),this.webhook=new vy(e),this.runs=new yy(e),this.steps=new wy(e),this.logs=new Dy(e)}async create(e){let t=await this.client.request(`POST`,`/api/agents`,JSON.stringify(e));return await Y(t,200),t.json()}async update(e){let t=await this.client.request(`PATCH`,`/api/agents/${e.id}`,JSON.stringify(e));return await Y(t,200),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/agents/${e}`);return await Y(t,200),t.json()}async list(e){let t=new URLSearchParams;e.organization_id&&t.set(`organization_id`,e.organization_id),e.page&&t.set(`page`,e.page.toString()),e.per_page&&t.set(`per_page`,e.per_page.toString());let n=await this.client.request(`GET`,`/api/agents?${t.toString()}`);return await Y(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/agents/${e}`);await Y(t,204)}},jy=class{constructor(e){this.client=e}async upload(e){let t=new FormData;t.append(`file`,e);let n=await this.client.request(`POST`,`/api/files`,t);return await Y(n,201),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/files/${e}`);return await Y(t,200),new File([await t.blob()],``)}};const My=B.enum([`owner`,`admin`,`billing_admin`,`member`]),Ny=B.object({user_id:B.uuid(),organization_id:B.uuid(),role:My,created_at:B.date(),updated_at:B.date()}),Py=B.object({id:B.uuid(),created_at:B.date(),updated_at:B.date(),display_name:B.string().nullable(),email:B.email(),avatar_url:B.url().nullable(),username:B.string()}),Fy=Ny.extend({user:Py});iy.extend({organization_id:B.uuid()}),ay(Fy),B.object({organization_id:B.uuid(),user_id:B.uuid()});const Iy=B.object({role:B.enum([`owner`,`admin`,`member`,`billing_admin`]).optional()});Iy.extend({organization_id:B.uuid(),user_id:B.uuid()});var Ly=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.per_page&&t.set(`per_page`,e.per_page.toString()),e.page&&t.set(`page`,e.page.toString());let n=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members?${t.toString()}`);return await Y(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);return await Y(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e.organization_id}/members/${e.user_id}`);await Y(t,204)}async update(e){let t=await this.client.request(`PUT`,`/api/organizations/${e.organization_id}/members/${e.user_id}`,JSON.stringify({role:e.role}));return await Y(t,200),t.json()}},Ry=class{constructor(e){this.client=e}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e.organization_id}/agents/${e.agent_name}`);return await Y(t,200),t.json()}};B.object({id:B.uuid(),name:B.string(),created_at:B.date(),updated_at:B.date(),membership:Ny.nullable(),members_url:B.url(),invites_url:B.url(),avatar_url:B.url().nullable()}),B.object({name:B.string().regex(ly)});var zy=class{constructor(e){this.client=e,this.members=new Ly(e),this.agents=new Ry(e)}async list(){let e=await this.client.request(`GET`,`/api/organizations`);return await Y(e,200),e.json()}async get(e){let t=await this.client.request(`GET`,`/api/organizations/${e}`);return await Y(t,200),t.json()}async create(e){let t=await this.client.request(`POST`,`/api/organizations`,JSON.stringify(e));return await Y(t,201),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/organizations/${e}`);await Y(t,204)}};z.object({id:z.uuid(),created_at:z.date(),updated_at:z.date(),email:z.string().email(),email_verified:z.boolean(),display_name:z.string(),username:z.string(),organization_id:z.uuid(),avatar_url:z.string().url().nullable()});var By=class{constructor(e){this.client=e}async me(){return this.get(`me`)}async get(e){let t=await this.client.request(`GET`,`/api/users/${e}`);return await Y(t,200),t.json()}},Vy=`vercel.ai.error`,Hy=Symbol.for(Vy),Uy,Wy=class e extends Error{constructor({name:e,message:t,cause:n}){super(t),this[Uy]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,Vy)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};Uy=Hy;var Gy=Wy,Ky=`AI_APICallError`,qy=`vercel.ai.error.${Ky}`,Jy=Symbol.for(qy),Yy;Yy=Jy;var Xy=`AI_EmptyResponseBodyError`,Zy=`vercel.ai.error.${Xy}`,Qy=Symbol.for(Zy),$y;$y=Qy;function eb(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var tb=`AI_InvalidArgumentError`,nb=`vercel.ai.error.${tb}`,rb=Symbol.for(nb),ib,ab=class extends Gy{constructor({message:e,cause:t,argument:n}){super({name:tb,message:e,cause:t}),this[ib]=!0,this.argument=n}static isInstance(e){return Gy.hasMarker(e,nb)}};ib=rb;var ob=`AI_InvalidPromptError`,sb=`vercel.ai.error.${ob}`,cb=Symbol.for(sb),lb;lb=cb;var ub=`AI_InvalidResponseDataError`,db=`vercel.ai.error.${ub}`,fb=Symbol.for(db),pb;pb=fb;var mb=`AI_JSONParseError`,hb=`vercel.ai.error.${mb}`,gb=Symbol.for(hb),_b,vb=class extends Gy{constructor({text:e,cause:t}){super({name:mb,message:`JSON parsing failed: Text: ${e}.
|
|
108
|
+
Error message: ${eb(t)}`,cause:t}),this[_b]=!0,this.text=e}static isInstance(e){return Gy.hasMarker(e,hb)}};_b=gb;var yb=`AI_LoadAPIKeyError`,bb=`vercel.ai.error.${yb}`,xb=Symbol.for(bb),Sb;Sb=xb;var Cb=`AI_LoadSettingError`,wb=`vercel.ai.error.${Cb}`,Tb=Symbol.for(wb),Eb;Eb=Tb;var Db=`AI_NoContentGeneratedError`,Ob=`vercel.ai.error.${Db}`,kb=Symbol.for(Ob),Ab;Ab=kb;var jb=`AI_NoSuchModelError`,Mb=`vercel.ai.error.${jb}`,Nb=Symbol.for(Mb),Pb;Pb=Nb;var Fb=`AI_TooManyEmbeddingValuesForCallError`,Ib=`vercel.ai.error.${Fb}`,Lb=Symbol.for(Ib),Rb;Rb=Lb;var zb=`AI_TypeValidationError`,Bb=`vercel.ai.error.${zb}`,Vb=Symbol.for(Bb),Hb,Ub=class e extends Gy{constructor({value:e,cause:t}){super({name:zb,message:`Type validation failed: Value: ${JSON.stringify(e)}.
|
|
109
|
+
Error message: ${eb(t)}`,cause:t}),this[Hb]=!0,this.value=e}static isInstance(e){return Gy.hasMarker(e,Bb)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}};Hb=Vb;var Wb=Ub,Gb=`AI_UnsupportedFunctionalityError`,Kb=`vercel.ai.error.${Gb}`,qb=Symbol.for(Kb),Jb;Jb=qb;var Yb=({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new ab({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`};Yb();var Xb=/"__proto__"\s*:/,Zb=/"constructor"\s*:/;function Qb(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Xb.test(e)===!1&&Zb.test(e)===!1?t:$b(t)}function $b(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function ex(e){let{stackTraceLimit:t}=Error;Error.stackTraceLimit=0;try{return Qb(e)}finally{Error.stackTraceLimit=t}}var tx=Symbol.for(`vercel.ai.validator`);function nx(e){return{[tx]:!0,validate:e}}function rx(e){return typeof e==`object`&&!!e&&tx in e&&e[tx]===!0&&`validate`in e}function ix(e){return rx(e)?e:ax(e)}function ax(e){return nx(async t=>{let n=await e[`~standard`].validate(t);return n.issues==null?{success:!0,value:n.value}:{success:!1,error:new Wb({value:t,cause:n.issues})}})}async function ox({value:e,schema:t}){let n=ix(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:Wb.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:Wb.wrap({value:e,cause:t}),rawValue:e}}}async function sx({text:e,schema:t}){try{let n=ex(e);return t==null?{success:!0,value:n,rawValue:n}:await ox({value:n,schema:t})}catch(t){return{success:!1,error:vb.isInstance(t)?t:new vb({text:e,cause:t}),rawValue:void 0}}}var{btoa:cx,atob:lx}=globalThis,ux=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}};function dx(e){}function fx(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=dx,onError:n=dx,onRetry:r=dx,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=px(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1,i=e.slice(t+r);f(n,i,e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
110
|
+
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new ux(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new ux(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
111
|
+
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function px(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
112
|
+
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
113
|
+
`&&r++}}return[t,n]}var mx=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=fx({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};function hx(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}const gx=B.enum([`ai-sdk`]),_x=B.array(B.custom()),vx=B.enum([`user`,`assistant`,`system`]),yx=B.object({id:B.uuid(),created_at:B.string().datetime(),chat_id:B.uuid(),metadata:cy}).extend({format:B.literal(`ai-sdk`),parts:_x,role:vx}),bx=B.discriminatedUnion(`format`,[yx]);oy.extend({chat_id:B.uuid(),format:gx.default(`ai-sdk`).optional()}),sy(bx),B.object({chat_id:B.uuid(),message_id:B.uuid()});const xx=B.object({role:vx,parts:_x,metadata:cy.optional(),format:B.literal(`ai-sdk`).optional()});B.object({message_id:B.uuid(),metadata:cy.optional(),role:vx.optional(),parts:_x.optional(),format:B.literal(`ai-sdk`).optional()});const Sx=B.enum([`enqueue`,`interrupt`,`append`]);B.object({chat_id:B.uuid(),behavior:Sx.optional(),messages:B.array(xx).min(1)}),B.object({messages:B.array(bx)});var Cx=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;t.set(`chat_id`,e.chat_id),e.limit&&t.set(`limit`,e.limit.toString()),e.cursor&&t.set(`cursor`,e.cursor),e.format&&t.set(`format`,e.format);let n=await this.client.request(`GET`,`/api/messages?${t.toString()}`);return await Y(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/messages/${e}`);await Y(t,204)}async get(e){let t=await this.client.request(`GET`,`/api/messages/${e}`);return await Y(t,200),t.json()}async update(e){let t=await this.client.request(`PUT`,`/api/messages/${e.message_id}`,JSON.stringify(e));await Y(t,200)}async send(e){let t=await this.client.request(`POST`,`/api/messages`,JSON.stringify(e));return await Y(t,201),t.json()}};oy.extend({chat_id:B.uuid()});const wx=B.object({id:B.uuid(),started_at:B.date(),agent_id:B.uuid(),agent_deployment_id:B.uuid().nullable(),chat_id:B.uuid(),step_count:B.number().int().positive(),status:by.nullable(),error:B.string().nullable()});sy(wx);var Tx=class{constructor(e){this.client=e}async list(e){let t=new URLSearchParams;e.cursor&&t.set(`cursor`,e.cursor),e.limit&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/chats/${e.chat_id}/runs?${t.toString()}`);return await Y(n,200),n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e.chat_id}/runs/${e.run_id}`);return await Y(t,200),t.json()}};const Ex=B.enum([`streaming`,`idle`,`error`,`interrupted`]),Dx=B.enum([`private`,`organization`,`public`]),Ox=B.object({id:B.uuid(),created_at:B.string().datetime(),created_by:B.uuid().nullable(),organization_id:B.uuid(),title:B.string(),visibility:Dx,metadata:cy,archived:B.boolean(),status:Ex,error:B.string().nullable(),agent_deployment_id:B.uuid().nullable(),agent:ky});B.enum([`websocket`,`sse`]);const kx=B.object({organization_id:B.uuid(),title:B.string().optional(),visibility:Dx.default(`private`).optional(),metadata:cy.optional(),agent_id:B.uuid(),agent_deployment_id:B.uuid().optional(),messages:B.array(xx).optional()}),Ax=kx.extend({stream:B.literal(!0)}),jx=kx.extend({stream:B.literal(!1).optional()});B.union([Ax,jx]),B.union([oy.extend({organization_id:B.uuid()}),oy.extend({agent_id:B.uuid()})]);const Mx=Ox.extend({messages:B.array(bx)});sy(Ox);const Nx=B.discriminatedUnion(`event`,[B.strictObject({event:B.literal(`chat.updated`),data:Ox}),B.strictObject({event:B.literal(`message.created`),data:bx}),B.strictObject({event:B.literal(`message.updated`),data:bx}),B.strictObject({event:B.literal(`message.deleted`),data:B.object({id:B.uuid()})}),B.strictObject({event:B.literal(`message.chunk.added`),data:B.object({id:B.uuid(),chunk:B.custom()})})]),Px=B.strictObject({event:B.literal(`chat.created`),data:Mx});var Fx=class{constructor(e){this.client=e,this.runs=new Tx(e),this.steps=new Cy(e)}async create(e){let t={};e.stream&&(t.Accept=`text/event-stream`);let n=await this.client.request(`POST`,`/api/chats`,JSON.stringify(e),{headers:t});if(await Y(n,201),e.stream){let e=n.headers.get(`Content-Type`);if(e!==`text/event-stream`)throw Error(`Expected text/event-stream, got ${e}`);if(!n.body)throw Error(`The stream endpoint did not return a body!`);let t=this.streamSSE(n,B.discriminatedUnion(`event`,[Nx,Px])),r=t.getReader(),{done:i,value:a}=await r.read();if(i)throw Error(`The stream ended before the chat.created event was received!`);if(a.event!==`chat.created`)throw Error(`Expected chat.created, got ${a.event}`);return r.releaseLock(),{...a.data,messages:a.data.messages,stream:t}}return n.json()}async get(e){let t=await this.client.request(`GET`,`/api/chats/${e}`);return await Y(t,200),t.json()}async list(e){let t=new URLSearchParams;`organization_id`in e&&e.organization_id?t.set(`organization_id`,e.organization_id):`agent_id`in e&&e.agent_id&&t.set(`agent_id`,e.agent_id),e.cursor&&t.set(`cursor`,e.cursor),e.limit&&t.set(`limit`,e.limit.toString());let n=await this.client.request(`GET`,`/api/chats?${t.toString()}`);return await Y(n,200),n.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/chats/${e}`);await Y(t,204)}async stop(e){let t=await this.client.request(`POST`,`/api/chats/${e}/stop`);await Y(t,200)}async stream(e,t={transport:`websocket`}){if(t?.transport===`websocket`)return this.streamWS(e);let n=await this.client.request(`GET`,`/api/chats/${e}/stream`,void 0,{abortSignal:t?.signal,headers:{Accept:`text/event-stream`}});return await Y(n,200),this.streamSSE(n)}streamWS(e){let t=this.client.websocket(`/api/chats/${e}/stream`),n=new mx,r=n.writable.getWriter(),i,a=new TextDecoder,o=!1,s=()=>{o||(o=!0,i?i.finally(()=>{r.close().catch(()=>{})}):r.close().catch(()=>{}),t.close())};return t.addEventListener(`error`,()=>{s()}),t.addEventListener(`close`,()=>{s()}),t.addEventListener(`message`,e=>{if(o)return;let t;t=typeof e.data==`string`?e.data:a.decode(e.data),i=i?i.then(()=>{if(!o)return r.write(t).catch(()=>{})}):r.write(t).catch(()=>{})}),Ix(n.readable,Nx)}streamSSE(e,t=Nx){let n=new mx;if(!e.body)throw Error(`The stream endpoint did not return a body!`);return e.body.pipeThrough(new TextDecoderStream).pipeTo(n.writable).catch(e=>{}),Ix(n.readable,t)}};const Ix=(e,t)=>{let n=e.pipeThrough(new TransformStream({async transform(e,n){let r=await sx({text:e.data});if(!r.success){n.error(r.error);return}let i=t.safeParse({event:e.event,data:r.value});if(!i.success){n.error(i.error);return}n.enqueue(i.data)}}));return hx(n)},Lx=B.enum([`managed`,`self_managed`]);B.object({organization_id:B.uuid(),type:Lx}),B.object({id:B.uuid(),token:B.string().nullable().describe(`The token is only returned for self-managed compute instances.`)});const Rx=B.object({id:B.uuid(),created_at:B.string().date(),updated_at:B.string().date(),organization_id:B.uuid(),type:Lx}),zx=B.discriminatedUnion(`type`,[Rx.extend({type:B.literal(`managed`),status:B.enum([`pending`,`running`,`stopped`,`error`]),resources:B.object({cpu:B.number(),memory:B.number(),storage:B.number()}),operating_system:B.enum([`linux`,`windows`,`macos`])}),Rx.extend({type:B.literal(`self_managed`)})]);iy.extend({organization_id:B.uuid()}),ay(zx);var Bx=class{constructor(e){this.client=e}async create(e){let t=await this.client.request(`POST`,`/api/tools/compute`,JSON.stringify(e));return await Y(t,201),t.json()}async get(e){let t=await this.client.request(`GET`,`/api/tools/compute/${e}`);return await Y(t,200),t.json()}async list(e){let t=await this.client.request(`GET`,`/api/tools/compute?organization_id=${e.organization_id}`);return await Y(t,200),t.json()}async connect(e){let t=await this.client.request(`GET`,`/api/tools/compute/${e}/connect`);throw await Y(t,200),Error(`Not implemented`)}},Vx=class{constructor(e){this.client=e,this.compute=new Bx(this.client)}};B.object({id:B.uuid(),organization_id:B.uuid(),role:My,invited_by:B.uuid(),expires_at:B.date(),created_at:B.date(),updated_at:B.date(),reusable:B.boolean(),accepted_at:B.date().nullable(),email:B.string().email().nullable()}),B.object({organization_id:B.uuid(),role:My,email:B.string().email().optional(),reusable:B.boolean().optional()}),B.object({organization_id:B.uuid()}),B.object({organization_id:B.uuid(),invite_id:B.uuid()});const Hx=B.object({code:B.string()});Hx.extend({invite_id:B.uuid()});var Ux=class{constructor(e){this.client=e}async create(e){let t=await this.client.request(`POST`,`/api/invites`,JSON.stringify(e));return await Y(t,201),t.json()}async list(e){let t=await this.client.request(`GET`,`/api/invites?organization_id=${e.organization_id}`);return await Y(t,200),t.json()}async delete(e){let t=await this.client.request(`DELETE`,`/api/invites/${e.invite_id}`);await Y(t,204)}async accept(e){let t=await this.client.request(`POST`,`/api/invites/${e.invite_id}/accept`,JSON.stringify({code:e.code}));return await Y(t,201),t.json()}},Wx=class{constructor(e){this.chats=new Fx(this),this.runs=new Tx(this),this.agents=new Ay(this),this.files=new jy(this),this.organizations=new zy(this),this.invites=new Ux(this),this.users=new By(this),this.tools=new Vx(this),this.messages=new Cx(this),this.baseURL=new URL(e?.baseURL??(globalThis.window===void 0?`https://blink.so`:window.location.origin)),this.fetch=e?.fetch,this.authToken=e?.authToken,this.auth=new ry(this,this.baseURL)}request(e,t,n,r){let i=new URL(t,this.baseURL),a=new Headers;if(this.authToken&&a.set(`Authorization`,`Bearer ${this.authToken}`),typeof n==`string`&&a.set(`Content-Type`,`application/json`),r?.headers)for(let[e,t]of Object.entries(r.headers))a.set(e,t);let o;if(r?.abortSignal&&r?.timeout)throw Error(`Cannot specify both abortSignal and timeout`);return r?.abortSignal&&(o=r.abortSignal),r?.timeout&&(o=AbortSignal.timeout(r.timeout)),(this.fetch??fetch)(i.toString(),{method:e,headers:a,body:n,signal:o})}websocket(e){let t=new URL(e,this.baseURL);return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,new WebSocket(t.toString())}},Gx=Object.create,Kx=Object.defineProperty,qx=Object.getOwnPropertyDescriptor,Jx=Object.getOwnPropertyNames,Yx=Object.getPrototypeOf,Xx=Object.prototype.hasOwnProperty,X=(e,t)=>function(){return t||(0,e[Jx(e)[0]])((t={exports:{}}).exports,t),t.exports},Zx=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Jx(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Xx.call(e,s)&&s!==n&&Kx(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=qx(t,s))||r.enumerable});return e},Qx=(e,t,n)=>(n=e==null?{}:Gx(Yx(e)),Zx(t||!e||!e.__esModule?Kx(n,`default`,{value:e,enumerable:!0}):n,e)),Z=u(import.meta.url),$x=class{constructor(){this.listeners=[]}get event(){return e=>(this.listeners.push(e),{dispose:()=>{this.listeners=this.listeners.filter(t=>t!==e)}})}emit(e){for(let t=this.listeners.length-1;t>=0;t--)this.listeners[t]?.(e)}dispose(){this.listeners=[]}},eS,tS;let nS=function(e){return e[e.DATA=0]=`DATA`,e[e.CLOSE=1]=`CLOSE`,e[e.ERROR=2]=`ERROR`,e}({}),rS=function(e){return e[e.NEW=1]=`NEW`,e}({});var iS=class{static acquire(e){for(let t of this.COMMON_SIZES)if(t>=e){let e=this.pools.get(t);if(e&&e.length>0)return e.pop();break}return new Uint8Array(e)}static release(e){let t=e.length;for(let n of this.COMMON_SIZES)if(n===t){let t=this.pools.get(n);t&&t.length<this.MAX_POOL_SIZE&&t.push(e);break}}};eS=iS,iS.MAX_POOL_SIZE=100,iS.COMMON_SIZES=[64,256,1024,4096,16384],iS.pools=new Map,(()=>{for(let e of eS.COMMON_SIZES)eS.pools.set(e,[])})();var aS=class e{static encode(e){let t=e.payload.length;if(t>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${t} > ${this.MAX_FRAME_SIZE}`);let n=this.HEADER_SIZE+t,r=iS.acquire(n),i=e.streamId<<8|e.type<<4|e.flags&15;return r[0]=i>>>24&255,r[1]=i>>>16&255,r[2]=i>>>8&255,r[3]=i&255,t>0&&r.set(e.payload,this.HEADER_SIZE),r.length===n?r:r.subarray(0,n)}static encodeTyped(t,n,r,i,a){let o=1+a.length;if(o>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${o} > ${this.MAX_FRAME_SIZE}`);let s=this.HEADER_SIZE+o,c=iS.acquire(s),l=t<<8|n<<4|r&15;return c[0]=l>>>24&255,c[1]=l>>>16&255,c[2]=l>>>8&255,c[3]=l&255,c[e.HEADER_SIZE]=i&255,a.length>0&&c.set(a,e.HEADER_SIZE+1),c.length===s?c:c.subarray(0,s)}static decode(t){if(t.length<e.HEADER_SIZE)throw Error(`Invalid frame: too short (${t.length} < ${e.HEADER_SIZE})`);let n=t[0]<<24|t[1]<<16|t[2]<<8|t[3],r=n>>>8,i=n&255,a=i>>>4,o=i&15,s=t.length>e.HEADER_SIZE?t.subarray(e.HEADER_SIZE):new Uint8Array;return{streamId:r,type:a,flags:o,payload:s}}static releaseBuffer(e){iS.release(e)}static getMaxPayloadSize(){return e.MAX_FRAME_SIZE}};tS=aS,aS.HEADER_SIZE=4,aS.MAX_FRAME_SIZE=1024*1024-tS.HEADER_SIZE;var oS=class{constructor(e,t,n){this.send=t,this.sendTypedCb=n,this._disposed=!1,this._id=e}get id(){return this._id}get onData(){return this._onData||=new $x,this._onData.event}get onClose(){return this._onClose||=new $x,this._onClose.event}get onError(){return this._onError||=new $x,this._onError.event}write(e,t=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let n=aS.getMaxPayloadSize();if(e.length<=n){this.send({streamId:this.id,type:nS.DATA,flags:t?rS.NEW:0,payload:e});return}let r=0,i=!0;for(;r<e.length;){let a=e.length-r,o=a>n?n:a,s=e.subarray(r,r+o);this.send({streamId:this.id,type:nS.DATA,flags:t&&i?rS.NEW:0,payload:s}),r+=o,i=!1}}writeTyped(e,t,n=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);if(!this.sendTypedCb){let r=new Uint8Array(1+t.length);r[0]=e&255,t.length&&r.set(t,1),this.write(r,n);return}let r=aS.getMaxPayloadSize()-1;if(t.length<=r){this.sendTypedCb(this.id,n?rS.NEW:0,e,t);return}let i=0,a=!0;for(;i<t.length;){let o=t.length-i,s=o>r?r:o,c=t.subarray(i,i+s);this.sendTypedCb(this.id,n&&a?rS.NEW:0,e,c),i+=s,a=!1}}close(){this._disposed||(this.send({streamId:this.id,type:nS.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(e){this._disposed||this.send({streamId:this.id,type:nS.ERROR,flags:0,payload:new TextEncoder().encode(e)})}_handleFrame(e){if(!this._disposed)switch(e.type){case nS.DATA:this._onData?.emit(e.payload);break;case nS.CLOSE:this._onClose?.emit(),this._dispose();break;case nS.ERROR:let t=new TextDecoder().decode(e.payload);this._onError?.emit(t),this._dispose();break}}_dispose(){this._disposed||(this._disposed=!0,this._onData?.dispose(),this._onClose?.dispose(),this._onError?.dispose(),this._onData=void 0,this._onClose=void 0,this._onError=void 0)}_reset(e,t,n){this._dispose(),this._id=e,this.send=t,this.sendTypedCb=n,this._disposed=!1}get createdByClient(){return this.id%2==1}get disposed(){return this._disposed}},sS=class{static acquire(e,t,n){let r=this.pool.pop();return r?(r._reset(e,t,n),r):new oS(e,t,n)}static release(e){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(e)}};sS.MAX_POOL_SIZE=200,sS.pool=[];var cS=class{constructor(e){this._onNextStreamIDChange=new $x,this.onNextStreamIDChange=this._onNextStreamIDChange.event,this._onStream=new $x,this.onStream=this._onStream.event,this.streams=[],this.streamCount=0,this.nextStreamId=1,this.nextStreamId=e.initialNextStreamID??(e.isClient?1:2),this.send=e.send,this.releaseAfterSend=!!e.releaseAfterSend}getStream(e){return this.streams[e]}createStream(e){e===void 0&&(e=this.nextStreamId,this.nextStreamId+=2,this._onNextStreamIDChange.emit(this.nextStreamId));let t=this.streams[e];if(t&&!t.disposed)throw Error(`Stream ${e} already exists`);let n=sS.acquire(e,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r));return this.streams[e]=n,this.streamCount++,n}sendFrame(e){let t=aS.encode(e);try{this.send(t)}finally{this.releaseAfterSend&&aS.releaseBuffer(t)}}sendFrameTyped(e,t,n,r){let i=aS.encodeTyped(e,nS.DATA,n,t,r);try{this.send(i)}finally{this.releaseAfterSend&&aS.releaseBuffer(i)}}handleMessage(e){this.handleFrame(aS.decode(e))}handleFrame(e){let t=this.streams[e.streamId];(!t||t.disposed)&&(t=sS.acquire(e.streamId,e=>this.sendFrame(e),(e,t,n,r)=>this.sendFrameTyped(e,n,t,r)),this.streams[e.streamId]=t,this.streamCount++,this._onStream.emit(t)),t._handleFrame(e),(e.type===nS.CLOSE||e.type===nS.ERROR)&&(this.streams[e.streamId]=void 0,this.streamCount--,sS.release(t))}get activeStreamCount(){return this.streamCount}dispose(){for(let e of this.streams)e&&!e.disposed&&(e.close(),sS.release(e));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}},lS=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},uS=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},dS=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new lS;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new uS;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new lS;return n}},fS=class extends dS{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},pS=class extends fS{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},mS=class extends dS{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new lS;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function hS(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new mS(t):new pS(t)}catch(t){if(t instanceof TypeError)return new mS(e.getReader());throw t}}var gS=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new lS;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new lS;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new lS;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new lS;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}},_S=class extends gS{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new lS;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof lS)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new lS}return r}async ignore(e){let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},vS=class extends gS{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new lS;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function yS(e,t){let n=hS(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new _S(n,r)}function bS(e,t){return new vS(e,t)}const xS={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},SS={};for(let[e,t]of Object.entries(xS))SS[t]=Number.parseInt(e);function CS(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?wS(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return TS(e);case`ascii`:return ES(e);case`latin1`:case`iso-8859-1`:return DS(e);case`windows-1252`:return OS(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function wS(e){let t=``,n=0;for(;n<e.length;){let r=e[n++];if(r<128)t+=String.fromCharCode(r);else if(r<224){let i=e[n++]&63;t+=String.fromCharCode((r&31)<<6|i)}else if(r<240){let i=e[n++]&63,a=e[n++]&63;t+=String.fromCharCode((r&15)<<12|i<<6|a)}else{let i=e[n++]&63,a=e[n++]&63,o=e[n++]&63,s=(r&7)<<18|i<<12|a<<6|o;s-=65536,t+=String.fromCharCode(55296+(s>>10&1023),56320+(s&1023))}}return t}function TS(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function ES(e){return String.fromCharCode(...e.map(e=>e&127))}function DS(e){return String.fromCharCode(...e)}function OS(e){let t=``;for(let n of e)n>=128&&n<=159&&xS[n]?t+=xS[n]:t+=String.fromCharCode(n);return t}function kS(e){return new DataView(e.buffer,e.byteOffset)}const AS={len:1,get(e,t){return kS(e).getUint8(t)},put(e,t,n){return kS(e).setUint8(t,n),t+1}},jS={len:2,get(e,t){return kS(e).getUint16(t,!0)},put(e,t,n){return kS(e).setUint16(t,n,!0),t+2}},MS={len:2,get(e,t){return kS(e).getUint16(t)},put(e,t,n){return kS(e).setUint16(t,n),t+2}},NS={len:4,get(e,t){return kS(e).getUint32(t,!0)},put(e,t,n){return kS(e).setUint32(t,n,!0),t+4}},PS={len:4,get(e,t){return kS(e).getUint32(t)},put(e,t,n){return kS(e).setUint32(t,n),t+4}},FS={len:4,get(e,t){return kS(e).getInt32(t)},put(e,t,n){return kS(e).setInt32(t,n),t+4}},IS={len:8,get(e,t){return kS(e).getBigUint64(t,!0)},put(e,t,n){return kS(e).setBigUint64(t,n,!0),t+8}};var LS=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return CS(n,this.encoding)}},RS=ee(`/`),zS;try{zS=RS(`worker_threads`).Worker}catch{}var BS=Uint8Array,VS=Uint16Array,HS=Int32Array,US=new BS([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),WS=new BS([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),GS=new BS([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),KS=function(e,t){for(var n=new VS(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new HS(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},qS=KS(US,2),JS=qS.b,YS=qS.r;JS[28]=258,YS[258]=28;var XS=KS(WS,0),ZS=XS.b;XS.r;for(var QS=new VS(32768),$S=0;$S<32768;++$S){var eC=($S&43690)>>1|($S&21845)<<1;eC=(eC&52428)>>2|(eC&13107)<<2,eC=(eC&61680)>>4|(eC&3855)<<4,QS[$S]=((eC&65280)>>8|(eC&255)<<8)>>1}for(var tC=(function(e,t,n){for(var r=e.length,i=0,a=new VS(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new VS(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new VS(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[QS[d]>>c]=l}else for(s=new VS(r),i=0;i<r;++i)e[i]&&(s[i]=QS[o[e[i]-1]++]>>15-e[i]);return s}),nC=new BS(288),$S=0;$S<144;++$S)nC[$S]=8;for(var $S=144;$S<256;++$S)nC[$S]=9;for(var $S=256;$S<280;++$S)nC[$S]=7;for(var $S=280;$S<288;++$S)nC[$S]=8;for(var rC=new BS(32),$S=0;$S<32;++$S)rC[$S]=5;var iC=tC(nC,9,1),aC=tC(rC,5,1),oC=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},sC=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},cC=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},lC=function(e){return(e+7)/8|0},uC=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new BS(e.subarray(t,n))},dC=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],fC=function(e,t,n){var r=Error(t||dC[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,fC),!n)throw r;return r},pC=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new BS(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new BS(i*3));var l=function(e){var t=n.length;if(e>t){var r=new BS(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=sC(e,d,1);var v=sC(e,d+1,3);if(d+=3,v)if(v==1)p=iC,m=aC,h=9,g=5;else if(v==2){var y=sC(e,d,31)+257,b=sC(e,d+10,15)+4,x=y+sC(e,d+5,31)+1;d+=14;for(var S=new BS(x),C=new BS(19),w=0;w<b;++w)C[GS[w]]=sC(e,d+w*3,7);d+=b*3;for(var T=oC(C),E=(1<<T)-1,D=tC(C,T,1),w=0;w<x;){var O=D[sC(e,d,E)];d+=O&15;var k=O>>4;if(k<16)S[w++]=k;else{var A=0,j=0;for(k==16?(j=3+sC(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+sC(e,d,7),d+=3):k==18&&(j=11+sC(e,d,127),d+=7);j--;)S[w++]=A}}var ee=S.subarray(0,y),M=S.subarray(y);h=oC(ee),g=oC(M),p=tC(ee,h,1),m=tC(M,g,1)}else fC(1);else{var k=lC(d)+4,N=e[k-4]|e[k-3]<<8,P=k+N;if(P>i){c&&fC(0);break}s&&l(f+N),n.set(e.subarray(k,P),f),t.b=f+=N,t.p=d=P*8,t.f=u;continue}if(d>_){c&&fC(0);break}}s&&l(f+131072);for(var F=(1<<h)-1,I=(1<<g)-1,L=d;;L=d){var A=p[cC(e,d)&F],R=A>>4;if(d+=A&15,d>_){c&&fC(0);break}if(A||fC(2),R<256)n[f++]=R;else if(R==256){L=d,p=null;break}else{var te=R-254;if(R>264){var w=R-257,z=US[w];te=sC(e,d,(1<<z)-1)+JS[w],d+=z}var B=m[cC(e,d)&I],ne=B>>4;B||fC(3),d+=B&15;var M=ZS[ne];if(ne>3){var z=WS[ne];M+=cC(e,d)&(1<<z)-1,d+=z}if(d>_){c&&fC(0);break}s&&l(f+131072);var re=f+te;if(f<M){var ie=a-M,ae=Math.min(M,re);for(ie+f<0&&fC(3);f<ae;++f)n[f]=r[ie+f]}for(;f<re;++f)n[f]=n[f-M]}}t.l=p,t.p=L,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?uC(n,0,f):n.subarray(0,f)},mC=new BS(0),hC=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&fC(6,`invalid gzip data`);var t=e[3],n=10;t&4&&(n+=(e[10]|e[11]<<8)+2);for(var r=(t>>3&1)+(t>>4&1);r>0;r-=!e[n++]);return n+(t&2)},gC=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},_C=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&fC(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&fC(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function vC(e,t){return pC(e,{i:2},t&&t.out,t&&t.dictionary)}function yC(e,t){var n=hC(e);return n+8>e.length&&fC(6,`invalid gzip data`),pC(e.subarray(n,-8),{i:2},t&&t.out||new BS(gC(e)),t&&t.dictionary)}function bC(e,t){return pC(e.subarray(_C(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function xC(e,t){return e[0]==31&&e[1]==139&&e[2]==8?yC(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?vC(e,t):bC(e,t)}var SC=typeof TextDecoder<`u`&&new TextDecoder,CC=0;try{SC.decode(mC,{stream:!0}),CC=1}catch{}var wC=X({"../../vendor/blink/node_modules/ms/index.js":((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`:``)}})}),TC=X({"../../vendor/blink/node_modules/debug/src/common.js":((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=wC(),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})}),EC=X({"../../vendor/blink/node_modules/debug/src/browser.js":((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=TC()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),DC=X({"../../node_modules/has-flag/index.js":((e,t)=>{t.exports=(e,t=process.argv)=>{let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}})}),OC=X({"../../node_modules/supports-color/index.js":((e,t)=>{let n=Z(`os`),r=Z(`tty`),i=DC(),{env:a}=process,o;i(`no-color`)||i(`no-colors`)||i(`color=false`)||i(`color=never`)?o=0:(i(`color`)||i(`colors`)||i(`color=true`)||i(`color=always`))&&(o=1),`FORCE_COLOR`in a&&(o=a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(parseInt(a.FORCE_COLOR,10),3));function s(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function c(e,t){if(o===0)return 0;if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2;if(e&&!t&&o===void 0)return 0;let r=o||0;if(a.TERM===`dumb`)return r;if(process.platform===`win32`){let e=n.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in a)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:r;if(`TEAMCITY_VERSION`in a)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(a.TEAMCITY_VERSION)?1:0;if(a.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in a){let e=parseInt((a.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(a.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(a.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(a.TERM)||`COLORTERM`in a?1:r}function l(e){let t=c(e,e&&e.isTTY);return s(t)}t.exports={supportsColor:l,stdout:s(c(!0,r.isatty(1))),stderr:s(c(!0,r.isatty(2)))}})}),kC=X({"../../vendor/blink/node_modules/debug/src/node.js":((e,t)=>{let n=Z(`tty`),r=Z(`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=OC();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(`
|
|
114
|
+
`).join(`
|
|
115
|
+
`+a),e.push(i+`m+`+t.exports.humanize(this.diff)+`\x1B[0m`)}else e[0]=o()+n+` `+e[0]}function o(){return e.inspectOpts.hideDate?``:new Date().toISOString()+` `}function s(...t){return process.stderr.write(r.formatWithOptions(e.inspectOpts,...t)+`
|
|
116
|
+
`)}function c(e){e?process.env.DEBUG=e:delete process.env.DEBUG}function l(){return process.env.DEBUG}function u(t){t.inspectOpts={};let n=Object.keys(e.inspectOpts);for(let r=0;r<n.length;r++)t.inspectOpts[n[r]]=e.inspectOpts[n[r]]}t.exports=TC()(e);let{formatters:d}=t.exports;d.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split(`
|
|
117
|
+
`).map(e=>e.trim()).join(` `)},d.O=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts)}})}),AC=X({"../../vendor/blink/node_modules/debug/src/index.js":((e,t)=>{typeof process>`u`||process.type===`renderer`||process.browser===!0||process.__nwjs?t.exports=EC():t.exports=kC()})});const jC={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},MC={get(e){return jS.get(e,6),{signature:NS.get(e,0),compressedSize:NS.get(e,8),uncompressedSize:NS.get(e,12)}},len:16},NC={get(e){let t=jS.get(e,6);return{signature:NS.get(e,0),minVersion:jS.get(e,4),dataDescriptor:!!(t&8),compressedMethod:jS.get(e,8),compressedSize:NS.get(e,18),uncompressedSize:NS.get(e,22),filenameLength:jS.get(e,26),extraFieldLength:jS.get(e,28),filename:null}},len:30},PC={get(e){return{signature:NS.get(e,0),nrOfThisDisk:jS.get(e,4),nrOfThisDiskWithTheStart:jS.get(e,6),nrOfEntriesOnThisDisk:jS.get(e,8),nrOfEntriesOfSize:jS.get(e,10),sizeOfCd:NS.get(e,12),offsetOfStartOfCd:NS.get(e,16),zipFileCommentLength:jS.get(e,20)}},len:22},FC={get(e){let t=jS.get(e,8);return{signature:NS.get(e,0),minVersion:jS.get(e,6),dataDescriptor:!!(t&8),compressedMethod:jS.get(e,10),compressedSize:NS.get(e,20),uncompressedSize:NS.get(e,24),filenameLength:jS.get(e,28),extraFieldLength:jS.get(e,30),fileCommentLength:jS.get(e,32),relativeOffsetOfLocalHeader:NS.get(e,42),filename:null}},len:46};var IC=Qx(AC(),1);function LC(e){let t=new Uint8Array(NS.len);return NS.put(t,0,e),t}const RC=(0,IC.default)(`tokenizer:inflate`),zC=256*1024,BC=LC(jC.DataDescriptor),VC=LC(jC.EndOfCentralDirectory);var HC=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(zC)}async isZip(){return await this.peekSignature()===jC.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(NS)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===VC[0]&&n[r+1]===VC[1]&&n[r+2]===VC[2]&&n[r+3]===VC[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){RC(`Cannot reading central-directory without random-read support`);return}RC(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){RC(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(PC,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(FC);if(t.signature!==jC.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new LS(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),RC(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=zC;RC(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===zC;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=UC(this.syncBuffer.subarray(0,n),BC);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}RC(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,WC(e),r.handler)}else r.handler?(RC(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(RC(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(RC(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(MC)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-MC.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}inflate(e,t,n){if(e.compressedMethod===0)return n(t);RC(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let r=xC(t);return n(r)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(NS);if(e===jC.LocalFileHeader){let e=await this.tokenizer.readToken(NC);return e.filename=await this.tokenizer.readToken(new LS(e.filenameLength,`utf-8`)),e}if(e===jC.CentralFileHeader)return!1;throw e===3759263696?Error(`Encrypted ZIP`):Error(`Unexpected signature`)}};function UC(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function WC(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function GC(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function KC(e){return[...e].map(e=>e.charCodeAt(0))}function qC(e,t=0){let n=Number.parseInt(new LS(6).get(e,148).replace(/\0.*$/,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}const JC={get:(e,t)=>e[t+3]&127|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},YC=4100;async function XC(e,t){return new $C(t).fromBuffer(e)}function ZC(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function QC(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}var $C=class{constructor(e){this.detectConfident=async e=>{if(this.buffer=new Uint8Array(YC),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return{ext:`gz`,mime:`application/gzip`};if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await e.ignore(6);let t=await e.readToken(JC);return e.position+t>e.fileInfo.size?{ext:`mp3`,mime:`audio/mpeg`}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4])){let t;return await new HC(e).unzip(e=>{switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return{async handler(e){let n=new TextDecoder(`utf-8`).decode(e).trim();t=ZC(n)},stop:!0};case`[Content_Types].xml`:return{async handler(e){let n=new TextDecoder(`utf-8`).decode(e),r=n.indexOf(`.main+xml"`);if(r===-1){let e=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;n.includes(`ContentType="${e}"`)&&(t=ZC(e))}else{n=n.slice(0,Math.max(0,r));let e=n.lastIndexOf(`"`),i=n.slice(Math.max(0,e+1));t=ZC(i)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}}),t??{ext:`zip`,mime:`application/zip`}}if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),QC(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:QC(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:QC(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:QC(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:QC(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:QC(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/x-lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163])){async function t(){let t=await e.peekNumber(AS),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await e.readBuffer(i),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:GC(i),len:GC(a)}}async function r(t){for(;t>0;){let r=await n();if(r.id===17026)return(await e.readToken(new LS(r.len))).replaceAll(/\00.*$/g,``);await e.ignore(r.len),--t}}let i=await n();switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:return}}if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(`{\\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190]))return{ext:`class`,mime:`application/java-vm`};if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/vnd.google.draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new LS(4,`latin1`).get(this.buffer,2);if(e.match(`^d*`)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new LS(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
|
|
118
|
+
`,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(FS),type:await e.readToken(new LS(4,`latin1`))}}do{let n=await t();if(n.length<0)return;switch(n.type){case`IDAT`:return{ext:`png`,mime:`image/png`};case`acTL`:return{ext:`apng`,mime:`image/apng`};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:`png`,mime:`image/png`}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new LS(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.check([82,73,70,70])){if(this.checkString(`WEBP`,{offset:8}))return{ext:`webp`,mime:`image/webp`};if(this.check([65,86,73],{offset:8}))return{ext:`avi`,mime:`video/vnd.avi`};if(this.check([87,65,86,69],{offset:8}))return{ext:`wav`,mime:`audio/wav`};if(this.check([81,76,67,77],{offset:8}))return{ext:`qcp`,mime:`audio/qcelp`}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:`rw2`,mime:`image/x-panasonic-rw2`};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(IS))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),r=n.size-24;if(QC(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(r-=await e.readBuffer(t),QC(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(QC(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}await e.ignore(r)}return{ext:`asf`,mime:`application/vnd.ms-asf`}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:`ktx`,mime:`image/ktx`};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:`mie`,mime:`application/x-mie`};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:`shp`,mime:`application/x-esri-shape`};if(this.check([255,79,255,81]))return{ext:`j2c`,mime:`image/j2c`};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new LS(4,`ascii`))){case`jp2 `:return{ext:`jp2`,mime:`image/jp2`};case`jpx `:return{ext:`jpx`,mime:`image/jpx`};case`jpm `:return{ext:`jpm`,mime:`image/jpm`};case`mjp2`:return{ext:`mj2`,mime:`image/mj2`};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:`jxl`,mime:`image/jxl`};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:`xml`,mime:`application/xml`}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:`cfb`,mime:`application/x-cfb`};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:`icc`,mime:`application/vnd.iccprofile`};if(this.checkString(`**ACE`,{offset:7})&&this.checkString(`**`,{offset:12}))return{ext:`ace`,mime:`application/x-ace-compressed`};if(this.checkString(`BEGIN:`)){if(this.checkString(`VCARD`,{offset:6}))return{ext:`vcf`,mime:`text/vcard`};if(this.checkString(`VCALENDAR`,{offset:6}))return{ext:`ics`,mime:`text/calendar`}}if(this.checkString(`FUJIFILMCCD-RAW`))return{ext:`raf`,mime:`image/x-fujifilm-raf`};if(this.checkString(`Extended Module:`))return{ext:`xm`,mime:`audio/x-xm`};if(this.checkString(`Creative Voice File`))return{ext:`voc`,mime:`audio/x-voc`};if(this.check([4,0,0,0])&&this.buffer.length>=16){let e=new DataView(this.buffer.buffer).getUint32(12,!0);if(e>12&&this.buffer.length>=e+16)try{let t=new TextDecoder().decode(this.buffer.subarray(16,e+16));if(JSON.parse(t).files)return{ext:`asar`,mime:`application/x-asar`}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:`mxf`,mime:`application/mxf`};if(this.checkString(`SCRM`,{offset:44}))return{ext:`s3m`,mime:`audio/x-s3m`};if(this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:`mts`,mime:`video/mp2t`};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:`mobi`,mime:`application/x-mobipocket-ebook`};if(this.check([68,73,67,77],{offset:128}))return{ext:`dcm`,mime:`application/dicom`};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:`lnk`,mime:`application/x.ms.shortcut`};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:`alias`,mime:`application/x.apple.alias`};if(this.checkString(`Kaydara FBX Binary \0`))return{ext:`fbx`,mime:`application/x.autodesk.fbx`};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:`eot`,mime:`application/vnd.ms-fontobject`};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:`indd`,mime:`application/x-indesign`};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString(`ustar`,{offset:257})&&(this.checkString(`\0`,{offset:262})||this.checkString(` `,{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&qC(this.buffer))return{ext:`tar`,mime:`application/x-tar`};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:`xml`,mime:`application/xml`}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:`skp`,mime:`application/vnd.sketchup.skp`}:void 0;if(this.checkString(`-----BEGIN PGP MESSAGE-----`))return{ext:`pgp`,mime:`application/pgp-encrypted`}},this.detectImprecise=async e=>{if(this.buffer=new Uint8Array(YC),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:`mpg`,mime:`video/mpeg`};if(this.check([0,1,0,0,0]))return{ext:`ttf`,mime:`font/ttf`};if(this.check([0,0,1,0]))return{ext:`ico`,mime:`image/x-icon`};if(this.check([0,0,2,0]))return{ext:`cur`,mime:`image/x-icon`};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let e=0;e<=this.options.mpegOffsetTolerance;++e){let t=this.scanMpeg(e);if(t)return t}},this.options={mpegOffsetTolerance:0,...e},this.detectors=[...e?.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let r=await n.detect(e);if(r)return r;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(bS(t,this.tokenizerOptions))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){let t=await yS(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=YC}=t,r,i,a=e.getReader({mode:`byob`});try{let{value:e,done:t}=await a.read(new Uint8Array(n));if(i=e,!t&&e)try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof lS))throw e;r=void 0}i=e}finally{a.releaseLock()}let o=new TransformStream({async start(e){e.enqueue(i)},transform(e,t){t.enqueue(e)}}),s=e.pipeThrough(o);return s.fileType=r,s}check(e,t){return QC(this.buffer,e,t)}checkString(e,t){return this.check(KC(e),t)}async readTiffTag(e){let t=await this.tokenizer.readToken(e?MS:jS);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:`arw`,mime:`image/x-sony-arw`};case 50706:return{ext:`dng`,mime:`image/x-adobe-dng`};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?MS:jS);for(let n=0;n<t;++n){let t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){let t=(e?MS:jS).get(this.buffer,2),n=(e?PS:NS).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString(`CR`,{offset:8}))return{ext:`cr2`,mime:`image/x-canon-cr2`};if(n>=8){let t=(e?MS:jS).get(this.buffer,8),n=(e?MS:jS).get(this.buffer,10);if(t===28&&n===254||t===31&&n===11)return{ext:`nef`,mime:`image/x-nikon-nef`}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:`tif`,mime:`image/tiff`}}if(t===43)return{ext:`tif`,mime:`image/tiff`}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:`aac`,mime:`audio/aac`};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:`mp3`,mime:`audio/mpeg`};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:`mp2`,mime:`audio/mpeg`};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:`mp1`,mime:`audio/mpeg`}}}},ew=X({"../../vendor/blink/node_modules/@xterm/addon-serialize/lib/addon-serialize.js":((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.SerializeAddon=r():n.SerializeAddon=r()})(e,(()=>(()=>{var e={930:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ColorContrastCache=void 0;let r=n(485);t.ColorContrastCache=class{constructor(){this._color=new r.TwoKeyMap,this._css=new r.TwoKeyMap}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}}},997:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.ThemeService=t.DEFAULT_ANSI_COLORS=void 0;let a=n(930),o=n(160),s=n(345),c=n(859),l=n(97),u=o.css.toColor(`#ffffff`),d=o.css.toColor(`#000000`),f=o.css.toColor(`#ffffff`),p=o.css.toColor(`#000000`),m={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117};t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{let e=[o.css.toColor(`#2e3436`),o.css.toColor(`#cc0000`),o.css.toColor(`#4e9a06`),o.css.toColor(`#c4a000`),o.css.toColor(`#3465a4`),o.css.toColor(`#75507b`),o.css.toColor(`#06989a`),o.css.toColor(`#d3d7cf`),o.css.toColor(`#555753`),o.css.toColor(`#ef2929`),o.css.toColor(`#8ae234`),o.css.toColor(`#fce94f`),o.css.toColor(`#729fcf`),o.css.toColor(`#ad7fa8`),o.css.toColor(`#34e2e2`),o.css.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:o.channels.toCss(r,i,a),rgba:o.channels.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+10*t;e.push({css:o.channels.toCss(n,n,n),rgba:o.channels.toRgba(n,n,n)})}return e})());let h=t.ThemeService=class extends c.Disposable{get colors(){return this._colors}constructor(e){super(),this._optionsService=e,this._contrastCache=new a.ColorContrastCache,this._halfContrastCache=new a.ColorContrastCache,this._onChangeColors=this.register(new s.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:u,background:d,cursor:f,cursorAccent:p,selectionForeground:void 0,selectionBackgroundTransparent:m,selectionBackgroundOpaque:o.color.blend(d,m),selectionInactiveBackgroundTransparent:m,selectionInactiveBackgroundOpaque:o.color.blend(d,m),ansi:t.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange(`theme`,(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(e={}){let n=this._colors;if(n.foreground=g(e.foreground,u),n.background=g(e.background,d),n.cursor=g(e.cursor,f),n.cursorAccent=g(e.cursorAccent,p),n.selectionBackgroundTransparent=g(e.selectionBackground,m),n.selectionBackgroundOpaque=o.color.blend(n.background,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundTransparent=g(e.selectionInactiveBackground,n.selectionBackgroundTransparent),n.selectionInactiveBackgroundOpaque=o.color.blend(n.background,n.selectionInactiveBackgroundTransparent),n.selectionForeground=e.selectionForeground?g(e.selectionForeground,o.NULL_COLOR):void 0,n.selectionForeground===o.NULL_COLOR&&(n.selectionForeground=void 0),o.color.isOpaque(n.selectionBackgroundTransparent)&&(n.selectionBackgroundTransparent=o.color.opacity(n.selectionBackgroundTransparent,.3)),o.color.isOpaque(n.selectionInactiveBackgroundTransparent)&&(n.selectionInactiveBackgroundTransparent=o.color.opacity(n.selectionInactiveBackgroundTransparent,.3)),n.ansi=t.DEFAULT_ANSI_COLORS.slice(),n.ansi[0]=g(e.black,t.DEFAULT_ANSI_COLORS[0]),n.ansi[1]=g(e.red,t.DEFAULT_ANSI_COLORS[1]),n.ansi[2]=g(e.green,t.DEFAULT_ANSI_COLORS[2]),n.ansi[3]=g(e.yellow,t.DEFAULT_ANSI_COLORS[3]),n.ansi[4]=g(e.blue,t.DEFAULT_ANSI_COLORS[4]),n.ansi[5]=g(e.magenta,t.DEFAULT_ANSI_COLORS[5]),n.ansi[6]=g(e.cyan,t.DEFAULT_ANSI_COLORS[6]),n.ansi[7]=g(e.white,t.DEFAULT_ANSI_COLORS[7]),n.ansi[8]=g(e.brightBlack,t.DEFAULT_ANSI_COLORS[8]),n.ansi[9]=g(e.brightRed,t.DEFAULT_ANSI_COLORS[9]),n.ansi[10]=g(e.brightGreen,t.DEFAULT_ANSI_COLORS[10]),n.ansi[11]=g(e.brightYellow,t.DEFAULT_ANSI_COLORS[11]),n.ansi[12]=g(e.brightBlue,t.DEFAULT_ANSI_COLORS[12]),n.ansi[13]=g(e.brightMagenta,t.DEFAULT_ANSI_COLORS[13]),n.ansi[14]=g(e.brightCyan,t.DEFAULT_ANSI_COLORS[14]),n.ansi[15]=g(e.brightWhite,t.DEFAULT_ANSI_COLORS[15]),e.extendedAnsi){let r=Math.min(n.ansi.length-16,e.extendedAnsi.length);for(let i=0;i<r;i++)n.ansi[i+16]=g(e.extendedAnsi[i],t.DEFAULT_ANSI_COLORS[i+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e!==void 0)switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}else for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e]}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function g(e,t){if(e!==void 0)try{return o.css.toColor(e)}catch{}return t}t.ThemeService=h=r([i(0,l.IOptionsService)],h)},160:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.contrastRatio=t.toPaddedHex=t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0;let n=0,r=0,i=0,a=0;var o,s,c,l,u;function d(e){let t=e.toString(16);return t.length<2?`0`+t:t}function f(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}t.NULL_COLOR={css:`#00000000`,rgba:0},function(e){e.toCss=function(e,t,n,r){return r===void 0?`#${d(e)}${d(t)}${d(n)}`:`#${d(e)}${d(t)}${d(n)}${d(r)}`},e.toRgba=function(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0},e.toColor=function(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}}(o||(t.channels=o={})),function(e){function t(e,t){return a=Math.round(255*t),[n,r,i]=u.toChannels(e.rgba),{css:o.toCss(n,r,i,a),rgba:o.toRgba(n,r,i,a)}}e.blend=function(e,t){if(a=(255&t.rgba)/255,a===1)return{css:t.css,rgba:t.rgba};let s=t.rgba>>24&255,c=t.rgba>>16&255,l=t.rgba>>8&255,u=e.rgba>>24&255,d=e.rgba>>16&255,f=e.rgba>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),{css:o.toCss(n,r,i),rgba:o.toRgba(n,r,i)}},e.isOpaque=function(e){return(255&e.rgba)==255},e.ensureContrastRatio=function(e,t,n){let r=u.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return o.toColor(r>>24&255,r>>16&255,r>>8&255)},e.opaque=function(e){let t=(255|e.rgba)>>>0;return[n,r,i]=u.toChannels(t),{css:o.toCss(n,r,i),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,n){return a=255&e.rgba,t(e,a*n/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}}(s||(t.color=s={})),function(e){let t,s;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let n=e.getContext(`2d`,{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation=`copy`,s=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),o.toColor(n,r,i);case 5:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),a=parseInt(e.slice(4,5).repeat(2),16),o.toColor(n,r,i,a);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let c=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(c)return n=parseInt(c[1]),r=parseInt(c[2]),i=parseInt(c[3]),a=Math.round(255*(c[5]===void 0?1:parseFloat(c[5]))),o.toColor(n,r,i,a);if(!t||!s||(t.fillStyle=s,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[n,r,i,a]=t.getImageData(0,0,1,1).data,a!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:o.toRgba(n,r,i,a),css:e}}}(c||(t.css=c={})),function(e){function t(e,t,n){let r=e/255,i=t/255,a=n/255;return .2126*(r<=.03928?r/12.92:((r+.055)/1.055)**2.4)+.7152*(i<=.03928?i/12.92:((i+.055)/1.055)**2.4)+.0722*(a<=.03928?a/12.92:((a+.055)/1.055)**2.4)}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(l||(t.rgb=l={})),function(e){function t(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(.1*o)),s-=Math.max(0,Math.ceil(.1*s)),c-=Math.max(0,Math.ceil(.1*c)),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}function s(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil(.1*(255-o))),s=Math.min(255,s+Math.ceil(.1*(255-s))),c=Math.min(255,c+Math.ceil(.1*(255-c))),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.blend=function(e,t){if(a=(255&t)/255,a===1)return t;let s=t>>24&255,c=t>>16&255,l=t>>8&255,u=e>>24&255,d=e>>16&255,f=e>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),o.toRgba(n,r,i)},e.ensureContrastRatio=function(e,n,r){let i=l.relativeLuminance(e>>8),a=l.relativeLuminance(n>>8);if(f(i,a)<r){if(a<i){let a=t(e,n,r),o=f(i,l.relativeLuminance(a>>8));if(o<r){let t=s(e,n,r);return o>f(i,l.relativeLuminance(t>>8))?a:t}return a}let o=s(e,n,r),c=f(i,l.relativeLuminance(o>>8));if(c<r){let a=t(e,n,r);return c>f(i,l.relativeLuminance(a>>8))?o:a}return o}},e.reduceLuminance=t,e.increaseLuminance=s,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}}(u||(t.rgba=u={})),t.toPaddedHex=d,t.contrastRatio=f},345:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed){for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}}}),this._event}fire(e,t){let n=[];for(let e=0;e<this._listeners.length;e++)n.push(this._listeners[e]);for(let r=0;r<n.length;r++)n[r].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},859:(e,t)=>{function n(e){for(let t of e)t.dispose();e.length=0}Object.defineProperty(t,`__esModule`,{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){let t=this._disposables.indexOf(e);t!==-1&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=n,t.getDisposeArrayDisposable=function(e){return{dispose:()=>n(e)}}},485:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class n{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}}t.TwoKeyMap=n,t.FourKeyMap=class{constructor(){this._data=new n}set(e,t,r,i,a){this._data.get(e,t)||this._data.set(e,t,new n),this._data.get(e,t).set(r,i,a)}get(e,t,n,r){return this._data.get(e,t)?.get(n,r)}clear(){this._data.clear()}}},726:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;let n=`di$target`,r=`di$dependencies`;t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[r]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);let i=function(e,t,a){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);(function(e,t,i){t[n]===t?t[r].push({id:e,index:i}):(t[r]=[{id:e,index:i}],t[n]=t)})(i,e,a)};return i.toString=()=>e,t.serviceRegistry.set(e,i),i}},97:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;let r=n(726);var i;t.IBufferService=(0,r.createDecorator)(`BufferService`),t.ICoreMouseService=(0,r.createDecorator)(`CoreMouseService`),t.ICoreService=(0,r.createDecorator)(`CoreService`),t.ICharsetService=(0,r.createDecorator)(`CharsetService`),t.IInstantiationService=(0,r.createDecorator)(`InstantiationService`),function(e){e[e.TRACE=0]=`TRACE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARN=3]=`WARN`,e[e.ERROR=4]=`ERROR`,e[e.OFF=5]=`OFF`}(i||(t.LogLevelEnum=i={})),t.ILogService=(0,r.createDecorator)(`LogService`),t.IOptionsService=(0,r.createDecorator)(`OptionsService`),t.IOscLinkService=(0,r.createDecorator)(`OscLinkService`),t.IUnicodeService=(0,r.createDecorator)(`UnicodeService`),t.IDecorationService=(0,r.createDecorator)(`DecorationService`)}},t={};function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}var r={};return(()=>{var e=r;Object.defineProperty(e,`__esModule`,{value:!0}),e.HTMLSerializeHandler=e.SerializeAddon=void 0;let t=n(997);function i(e,t,n){return Math.max(t,Math.min(e,n))}class a{constructor(e){this._buffer=e}serialize(e,t){let n=this._buffer.getNullCell(),r=this._buffer.getNullCell(),i=n,a=e.start.y,o=e.end.y,s=e.start.x,c=e.end.x;this._beforeSerialize(o-a,a,o);for(let t=a;t<=o;t++){let a=this._buffer.getLine(t);if(a){let o=t===e.start.y?s:0,l=t===e.end.y?c:a.length;for(let e=o;e<l;e++){let o=a.getCell(e,i===n?r:n);o?(this._nextCell(o,i,t,e),i=o):console.warn(`Can't get cell at row=${t}, col=${e}`)}}this._rowEnd(t,t===o)}return this._afterSerialize(),this._serializeString(t)}_nextCell(e,t,n,r){}_rowEnd(e,t){}_beforeSerialize(e,t,n){}_afterSerialize(){}_serializeString(e){return``}}function o(e,t){return e.getFgColorMode()===t.getFgColorMode()&&e.getFgColor()===t.getFgColor()}function s(e,t){return e.getBgColorMode()===t.getBgColorMode()&&e.getBgColor()===t.getBgColor()}function c(e,t){return e.isInverse()===t.isInverse()&&e.isBold()===t.isBold()&&e.isUnderline()===t.isUnderline()&&e.isOverline()===t.isOverline()&&e.isBlink()===t.isBlink()&&e.isInvisible()===t.isInvisible()&&e.isItalic()===t.isItalic()&&e.isDim()===t.isDim()&&e.isStrikethrough()===t.isStrikethrough()}class l extends a{constructor(e,t){super(e),this._terminal=t,this._rowIndex=0,this._allRows=[],this._allRowSeparators=[],this._currentRow=``,this._nullCellCount=0,this._cursorStyle=this._buffer.getNullCell(),this._cursorStyleRow=0,this._cursorStyleCol=0,this._backgroundCell=this._buffer.getNullCell(),this._firstRow=0,this._lastCursorRow=0,this._lastCursorCol=0,this._lastContentCursorRow=0,this._lastContentCursorCol=0,this._thisRowLastChar=this._buffer.getNullCell(),this._thisRowLastSecondChar=this._buffer.getNullCell(),this._nextRowFirstChar=this._buffer.getNullCell()}_beforeSerialize(e,t,n){this._allRows=Array(e),this._lastContentCursorRow=t,this._lastCursorRow=t,this._firstRow=t}_rowEnd(e,t){this._nullCellCount>0&&!s(this._cursorStyle,this._backgroundCell)&&(this._currentRow+=`[${this._nullCellCount}X`);let n=``;if(!t){e-this._firstRow>=this._terminal.rows&&this._buffer.getLine(this._cursorStyleRow)?.getCell(this._cursorStyleCol,this._backgroundCell);let t=this._buffer.getLine(e),r=this._buffer.getLine(e+1);if(r.isWrapped){n=``;let i=t.getCell(t.length-1,this._thisRowLastChar),a=t.getCell(t.length-2,this._thisRowLastSecondChar),o=r.getCell(0,this._nextRowFirstChar),c=o.getWidth()>1,l=!1;(o.getChars()&&c?this._nullCellCount<=1:this._nullCellCount<=0)&&((i.getChars()||i.getWidth()===0)&&s(i,o)&&(l=!0),c&&(a.getChars()||a.getWidth()===0)&&s(i,o)&&s(a,o)&&(l=!0)),l||(n=`-`.repeat(this._nullCellCount+1),n+=`\x1B[1D\x1B[1X`,this._nullCellCount>0&&(n+=`\x1B[A`,n+=`[${t.length-this._nullCellCount}C`,n+=`[${this._nullCellCount}X`,n+=`[${t.length-this._nullCellCount}D`,n+=`\x1B[B`),this._lastContentCursorRow=e+1,this._lastContentCursorCol=0,this._lastCursorRow=e+1,this._lastCursorCol=0)}else n=`\r
|
|
119
|
+
`,this._lastCursorRow=e+1,this._lastCursorCol=0}this._allRows[this._rowIndex]=this._currentRow,this._allRowSeparators[this._rowIndex++]=n,this._currentRow=``,this._nullCellCount=0}_diffStyle(e,t){let n=[],r=!o(e,t),i=!s(e,t),a=!c(e,t);if(r||i||a)if(e.isAttributeDefault())t.isAttributeDefault()||n.push(0);else{if(r){let t=e.getFgColor();e.isFgRGB()?n.push(38,2,t>>>16&255,t>>>8&255,255&t):e.isFgPalette()?t>=16?n.push(38,5,t):n.push(8&t?90+(7&t):30+(7&t)):n.push(39)}if(i){let t=e.getBgColor();e.isBgRGB()?n.push(48,2,t>>>16&255,t>>>8&255,255&t):e.isBgPalette()?t>=16?n.push(48,5,t):n.push(8&t?100+(7&t):40+(7&t)):n.push(49)}a&&(e.isInverse()!==t.isInverse()&&n.push(e.isInverse()?7:27),e.isBold()!==t.isBold()&&n.push(e.isBold()?1:22),e.isUnderline()!==t.isUnderline()&&n.push(e.isUnderline()?4:24),e.isOverline()!==t.isOverline()&&n.push(e.isOverline()?53:55),e.isBlink()!==t.isBlink()&&n.push(e.isBlink()?5:25),e.isInvisible()!==t.isInvisible()&&n.push(e.isInvisible()?8:28),e.isItalic()!==t.isItalic()&&n.push(e.isItalic()?3:23),e.isDim()!==t.isDim()&&n.push(e.isDim()?2:22),e.isStrikethrough()!==t.isStrikethrough()&&n.push(e.isStrikethrough()?9:29))}return n}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,this._cursorStyle);if(i?!s(this._cursorStyle,e):a.length>0){this._nullCellCount>0&&(s(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r,this._currentRow+=`[${a.join(`;`)}m`;let e=this._buffer.getLine(n);e!==void 0&&(e.getCell(r,this._cursorStyle),this._cursorStyleRow=n,this._cursorStyleCol=r)}i?this._nullCellCount+=e.getWidth():(this._nullCellCount>0&&(s(this._cursorStyle,this._backgroundCell)||(this._currentRow+=`[${this._nullCellCount}X`),this._currentRow+=`[${this._nullCellCount}C`,this._nullCellCount=0),this._currentRow+=e.getChars(),this._lastContentCursorRow=this._lastCursorRow=n,this._lastContentCursorCol=this._lastCursorCol=r+e.getWidth())}_serializeString(e){let t=this._allRows.length;this._buffer.length-this._firstRow<=this._terminal.rows&&(t=this._lastContentCursorRow+1-this._firstRow,this._lastCursorCol=this._lastContentCursorCol,this._lastCursorRow=this._lastContentCursorRow);let n=``;for(let e=0;e<t;e++)n+=this._allRows[e],e+1<t&&(n+=this._allRowSeparators[e]);if(!e){let e=this._buffer.baseY+this._buffer.cursorY,t=this._buffer.cursorX,i=e=>{e>0?n+=`[${e}C`:e<0&&(n+=`[${-e}D`)};(e!==this._lastCursorRow||t!==this._lastCursorCol)&&((r=e-this._lastCursorRow)>0?n+=`[${r}B`:r<0&&(n+=`[${-r}A`),i(t-this._lastCursorCol))}var r;let i=this._terminal._core._inputHandler._curAttrData,a=this._diffStyle(i,this._cursorStyle);return a.length>0&&(n+=`[${a.join(`;`)}m`),n}}e.SerializeAddon=class{activate(e){this._terminal=e}_serializeBufferByScrollback(e,t,n){let r=t.length,a=n===void 0?r:i(n+e.rows,0,r);return this._serializeBufferByRange(e,t,{start:r-a,end:r-1},!1)}_serializeBufferByRange(e,t,n,r){return new l(t,e).serialize({start:{x:0,y:typeof n.start==`number`?n.start:n.start.line},end:{x:e.cols,y:typeof n.end==`number`?n.end:n.end.line}},r)}_serializeBufferAsHTML(e,t){let n=e.buffer.active,r=new u(n,e,t);if(!t.onlySelection){let a=n.length,o=t.scrollback,s=o===void 0?a:i(o+e.rows,0,a);return r.serialize({start:{x:0,y:a-s},end:{x:e.cols,y:a-1}})}let a=this._terminal?.getSelectionPosition();return a===void 0?``:r.serialize({start:{x:a.start.x,y:a.start.y},end:{x:a.end.x,y:a.end.y}})}_serializeModes(e){let t=``,n=e.modes;if(n.applicationCursorKeysMode&&(t+=`\x1B[?1h`),n.applicationKeypadMode&&(t+=`\x1B[?66h`),n.bracketedPasteMode&&(t+=`\x1B[?2004h`),n.insertMode&&(t+=`\x1B[4h`),n.originMode&&(t+=`\x1B[?6h`),n.reverseWraparoundMode&&(t+=`\x1B[?45h`),n.sendFocusMode&&(t+=`\x1B[?1004h`),!1===n.wraparoundMode&&(t+=`\x1B[?7l`),n.mouseTrackingMode!==`none`)switch(n.mouseTrackingMode){case`x10`:t+=`\x1B[?9h`;break;case`vt200`:t+=`\x1B[?1000h`;break;case`drag`:t+=`\x1B[?1002h`;break;case`any`:t+=`\x1B[?1003h`}return t}serialize(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);let t=e?.range?this._serializeBufferByRange(this._terminal,this._terminal.buffer.normal,e.range,!0):this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.normal,e?.scrollback);return e?.excludeAltBuffer||this._terminal.buffer.active.type!==`alternate`||(t+=`[?1049h[H${this._serializeBufferByScrollback(this._terminal,this._terminal.buffer.alternate,void 0)}`),e?.excludeModes||(t+=this._serializeModes(this._terminal)),t}serializeAsHTML(e){if(!this._terminal)throw Error(`Cannot use addon until it has been loaded`);return this._serializeBufferAsHTML(this._terminal,e||{})}dispose(){}};class u extends a{constructor(e,n,r){super(e),this._terminal=n,this._options=r,this._currentRow=``,this._htmlContent=``,n._core._themeService?this._ansiColors=n._core._themeService.colors.ansi:this._ansiColors=t.DEFAULT_ANSI_COLORS}_padStart(e,t,n){return t>>=0,n??=` `,e.length>t?e:((t-=e.length)>n.length&&(n+=n.repeat(t/n.length)),n.slice(0,t)+e)}_beforeSerialize(e,t,n){this._htmlContent+=`<html><body><!--StartFragment--><pre>`;let r=`#000000`,i=`#ffffff`;this._options.includeGlobalBackground&&(r=this._terminal.options.theme?.foreground??`#ffffff`,i=this._terminal.options.theme?.background??`#000000`);let a=[];a.push(`color: `+r+`;`),a.push(`background-color: `+i+`;`),a.push(`font-family: `+this._terminal.options.fontFamily+`;`),a.push(`font-size: `+this._terminal.options.fontSize+`px;`),this._htmlContent+=`<div style='`+a.join(` `)+`'>`}_afterSerialize(){this._htmlContent+=`</div>`,this._htmlContent+=`</pre><!--EndFragment--></body></html>`}_rowEnd(e,t){this._htmlContent+=`<div><span>`+this._currentRow+`</span></div>`,this._currentRow=``}_getHexColor(e,t){let n=t?e.getFgColor():e.getBgColor();return(t?e.isFgRGB():e.isBgRGB())?`#`+[n>>16&255,n>>8&255,255&n].map((e=>this._padStart(e.toString(16),2,`0`))).join(``):(t?e.isFgPalette():e.isBgPalette())?this._ansiColors[n].css:void 0}_diffStyle(e,t){let n=[],r=!o(e,t),i=!s(e,t),a=!c(e,t);if(r||i||a){let t=this._getHexColor(e,!0);t&&n.push(`color: `+t+`;`);let r=this._getHexColor(e,!1);return r&&n.push(`background-color: `+r+`;`),e.isInverse()&&n.push(`color: #000000; background-color: #BFBFBF;`),e.isBold()&&n.push(`font-weight: bold;`),e.isUnderline()&&e.isOverline()?n.push(`text-decoration: overline underline;`):e.isUnderline()?n.push(`text-decoration: underline;`):e.isOverline()&&n.push(`text-decoration: overline;`),e.isBlink()&&n.push(`text-decoration: blink;`),e.isInvisible()&&n.push(`visibility: hidden;`),e.isItalic()&&n.push(`font-style: italic;`),e.isDim()&&n.push(`opacity: 0.5;`),e.isStrikethrough()&&n.push(`text-decoration: line-through;`),n}}_nextCell(e,t,n,r){if(e.getWidth()===0)return;let i=e.getChars()===``,a=this._diffStyle(e,t);a&&(this._currentRow+=a.length===0?`</span><span>`:`</span><span style='`+a.join(` `)+`'>`),this._currentRow+=i?` `:e.getChars()}_serializeString(){return this._htmlContent}}e.HTMLSerializeHandler=u})(),r})()))})}),tw=X({"../../vendor/blink/node_modules/@xterm/headless/lib-headless/xterm-headless.js":(e=>{(()=>{var t={349:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CircularList=void 0;let r=n(460),i=n(844);class a extends i.Disposable{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this.register(new r.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new r.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new r.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}}t.CircularList=a},439:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.clone=void 0,t.clone=function e(t,n=5){if(typeof t!=`object`)return t;let r=Array.isArray(t)?[]:{};for(let i in t)r[i]=n<=1?t[i]:t[i]&&e(t[i],n-1);return r}},969:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreTerminal=void 0;let r=n(844),i=n(585),a=n(348),o=n(866),s=n(744),c=n(302),l=n(83),u=n(460),d=n(753),f=n(480),p=n(994),m=n(282),h=n(435),g=n(981),_=n(660),v=!1;class y extends r.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new u.EventEmitter),this._onScroll.event((e=>{this._onScrollApi?.fire(e.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}constructor(e){super(),this._windowsWrappingHeuristics=this.register(new r.MutableDisposable),this._onBinary=this.register(new u.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new u.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new u.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new u.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new u.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new u.EventEmitter),this._instantiationService=new a.InstantiationService,this.optionsService=this.register(new c.OptionsService(e)),this._instantiationService.setService(i.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(s.BufferService)),this._instantiationService.setService(i.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(o.LogService)),this._instantiationService.setService(i.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(l.CoreService)),this._instantiationService.setService(i.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(d.CoreMouseService)),this._instantiationService.setService(i.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(f.UnicodeService)),this._instantiationService.setService(i.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(p.CharsetService),this._instantiationService.setService(i.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(_.OscLinkService),this._instantiationService.setService(i.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new h.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,u.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,u.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,u.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,u.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new g.WriteBuffer(((e,t)=>this._inputHandler.parse(e,t)))),this.register((0,u.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=i.LogLevelEnum.WARN&&!v&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),v=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,s.MINIMUM_COLS),t=Math.max(t,s.MINIMUM_ROWS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t,n){this._bufferService.scrollLines(e,t,n)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(m.updateWindowsModeWrappedState.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},(()=>((0,m.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,r.toDisposable)((()=>{for(let t of e)t.dispose()}))}}}t.CoreTerminal=y},460:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.runAndSubscribe=t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed){for(let t=0;t<this._listeners.length;t++)if(this._listeners[t]===e)return void this._listeners.splice(t,1)}}}),this._event}fire(e,t){let n=[];for(let e=0;e<this._listeners.length;e++)n.push(this._listeners[e]);for(let r=0;r<n.length;r++)n[r].call(void 0,e,t)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},t.forwardEvent=function(e,t){return e((e=>t.fire(e)))},t.runAndSubscribe=function(e,t){return t(void 0),e((e=>t(e)))}},435:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0;let a=n(584),o=n(116),s=n(15),c=n(844),l=n(482),u=n(437),d=n(460),f=n(643),p=n(511),m=n(734),h=n(585),g=n(480),_=n(242),v=n(351),y=n(941),b={"(":0,")":1,"*":2,"+":3,"-":1,".":2},x=131072;function S(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var C;(function(e){e[e.GET_WIN_SIZE_PIXELS=0]=`GET_WIN_SIZE_PIXELS`,e[e.GET_CELL_SIZE_PIXELS=1]=`GET_CELL_SIZE_PIXELS`})(C||(t.WindowsOptionsReportType=C={}));let w=0;class T extends c.Disposable{getAttrData(){return this._curAttrData}constructor(e,t,n,r,i,c,f,m,h=new s.EscapeSequenceParser){for(let s in super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=c,this._coreMouseService=f,this._unicodeService=m,this._parser=h,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new l.StringToUtf32,this._utf8Decoder=new l.Utf8ToUtf32,this._workCell=new p.CellData,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new d.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new d.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new d.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new d.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new d.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new d.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new d.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new d.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new d.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new d.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new d.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new d.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new E(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._parser.setCsiHandlerFallback(((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})})),this._parser.setEscHandlerFallback((e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})})),this._parser.setExecuteHandlerFallback((e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})})),this._parser.setOscHandlerFallback(((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})})),this._parser.setDcsHandlerFallback(((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})})),this._parser.setPrintHandler(((e,t,n)=>this.print(e,t,n))),this._parser.registerCsiHandler({final:`@`},(e=>this.insertChars(e))),this._parser.registerCsiHandler({intermediates:` `,final:`@`},(e=>this.scrollLeft(e))),this._parser.registerCsiHandler({final:`A`},(e=>this.cursorUp(e))),this._parser.registerCsiHandler({intermediates:` `,final:`A`},(e=>this.scrollRight(e))),this._parser.registerCsiHandler({final:`B`},(e=>this.cursorDown(e))),this._parser.registerCsiHandler({final:`C`},(e=>this.cursorForward(e))),this._parser.registerCsiHandler({final:`D`},(e=>this.cursorBackward(e))),this._parser.registerCsiHandler({final:`E`},(e=>this.cursorNextLine(e))),this._parser.registerCsiHandler({final:`F`},(e=>this.cursorPrecedingLine(e))),this._parser.registerCsiHandler({final:`G`},(e=>this.cursorCharAbsolute(e))),this._parser.registerCsiHandler({final:`H`},(e=>this.cursorPosition(e))),this._parser.registerCsiHandler({final:`I`},(e=>this.cursorForwardTab(e))),this._parser.registerCsiHandler({final:`J`},(e=>this.eraseInDisplay(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`J`},(e=>this.eraseInDisplay(e,!0))),this._parser.registerCsiHandler({final:`K`},(e=>this.eraseInLine(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`K`},(e=>this.eraseInLine(e,!0))),this._parser.registerCsiHandler({final:`L`},(e=>this.insertLines(e))),this._parser.registerCsiHandler({final:`M`},(e=>this.deleteLines(e))),this._parser.registerCsiHandler({final:`P`},(e=>this.deleteChars(e))),this._parser.registerCsiHandler({final:`S`},(e=>this.scrollUp(e))),this._parser.registerCsiHandler({final:`T`},(e=>this.scrollDown(e))),this._parser.registerCsiHandler({final:`X`},(e=>this.eraseChars(e))),this._parser.registerCsiHandler({final:`Z`},(e=>this.cursorBackwardTab(e))),this._parser.registerCsiHandler({final:"`"},(e=>this.charPosAbsolute(e))),this._parser.registerCsiHandler({final:`a`},(e=>this.hPositionRelative(e))),this._parser.registerCsiHandler({final:`b`},(e=>this.repeatPrecedingCharacter(e))),this._parser.registerCsiHandler({final:`c`},(e=>this.sendDeviceAttributesPrimary(e))),this._parser.registerCsiHandler({prefix:`>`,final:`c`},(e=>this.sendDeviceAttributesSecondary(e))),this._parser.registerCsiHandler({final:`d`},(e=>this.linePosAbsolute(e))),this._parser.registerCsiHandler({final:`e`},(e=>this.vPositionRelative(e))),this._parser.registerCsiHandler({final:`f`},(e=>this.hVPosition(e))),this._parser.registerCsiHandler({final:`g`},(e=>this.tabClear(e))),this._parser.registerCsiHandler({final:`h`},(e=>this.setMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`h`},(e=>this.setModePrivate(e))),this._parser.registerCsiHandler({final:`l`},(e=>this.resetMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`l`},(e=>this.resetModePrivate(e))),this._parser.registerCsiHandler({final:`m`},(e=>this.charAttributes(e))),this._parser.registerCsiHandler({final:`n`},(e=>this.deviceStatus(e))),this._parser.registerCsiHandler({prefix:`?`,final:`n`},(e=>this.deviceStatusPrivate(e))),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},(e=>this.softReset(e))),this._parser.registerCsiHandler({intermediates:` `,final:`q`},(e=>this.setCursorStyle(e))),this._parser.registerCsiHandler({final:`r`},(e=>this.setScrollRegion(e))),this._parser.registerCsiHandler({final:`s`},(e=>this.saveCursor(e))),this._parser.registerCsiHandler({final:`t`},(e=>this.windowOptions(e))),this._parser.registerCsiHandler({final:`u`},(e=>this.restoreCursor(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},(e=>this.insertColumns(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},(e=>this.deleteColumns(e))),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},(e=>this.selectProtected(e))),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},(e=>this.requestMode(e,!0))),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},(e=>this.requestMode(e,!1))),this._parser.setExecuteHandler(a.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(a.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(a.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(a.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(a.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(a.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(a.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(a.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(a.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new _.OscHandler((e=>(this.setTitle(e),this.setIconName(e),!0)))),this._parser.registerOscHandler(1,new _.OscHandler((e=>this.setIconName(e)))),this._parser.registerOscHandler(2,new _.OscHandler((e=>this.setTitle(e)))),this._parser.registerOscHandler(4,new _.OscHandler((e=>this.setOrReportIndexedColor(e)))),this._parser.registerOscHandler(8,new _.OscHandler((e=>this.setHyperlink(e)))),this._parser.registerOscHandler(10,new _.OscHandler((e=>this.setOrReportFgColor(e)))),this._parser.registerOscHandler(11,new _.OscHandler((e=>this.setOrReportBgColor(e)))),this._parser.registerOscHandler(12,new _.OscHandler((e=>this.setOrReportCursorColor(e)))),this._parser.registerOscHandler(104,new _.OscHandler((e=>this.restoreIndexedColor(e)))),this._parser.registerOscHandler(110,new _.OscHandler((e=>this.restoreFgColor(e)))),this._parser.registerOscHandler(111,new _.OscHandler((e=>this.restoreBgColor(e)))),this._parser.registerOscHandler(112,new _.OscHandler((e=>this.restoreCursorColor(e)))),this._parser.registerEscHandler({final:`7`},(()=>this.saveCursor())),this._parser.registerEscHandler({final:`8`},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:`D`},(()=>this.index())),this._parser.registerEscHandler({final:`E`},(()=>this.nextLine())),this._parser.registerEscHandler({final:`H`},(()=>this.tabSet())),this._parser.registerEscHandler({final:`M`},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:`=`},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:`>`},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:`c`},(()=>this.fullReset())),this._parser.registerEscHandler({final:`n`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`o`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`|`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`}`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`~`},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:`%`,final:`@`},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:`%`,final:`G`},(()=>this.selectDefaultCharset())),o.CHARSETS)this._parser.registerEscHandler({intermediates:`(`,final:s},(()=>this.selectCharset(`(`+s))),this._parser.registerEscHandler({intermediates:`)`,final:s},(()=>this.selectCharset(`)`+s))),this._parser.registerEscHandler({intermediates:`*`,final:s},(()=>this.selectCharset(`*`+s))),this._parser.registerEscHandler({intermediates:`+`,final:s},(()=>this.selectCharset(`+`+s))),this._parser.registerEscHandler({intermediates:`-`,final:s},(()=>this.selectCharset(`-`+s))),this._parser.registerEscHandler({intermediates:`.`,final:s},(()=>this.selectCharset(`.`+s))),this._parser.registerEscHandler({intermediates:`/`,final:s},(()=>this.selectCharset(`/`+s)));this._parser.registerEscHandler({intermediates:`#`,final:`8`},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((e=>(this._logService.error(`Parsing error: `,e),e))),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new v.DcsHandler(((e,t)=>this.requestStatusString(e,t))))}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=h.LogLevelEnum.WARN&&Promise.race([e,new Promise(((e,t)=>setTimeout((()=>t(`#SLOW_TIMEOUT`)),5e3)))]).catch((e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than 5000 ms`)}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>x&&(a=this._parseStack.position+x)}if(this._logService.logLevel<=h.LogLevelEnum.DEBUG&&this._logService.debug(`parsing data`+(typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,(e=>String.fromCharCode(e))).join(``)}"`),typeof e==`string`?e.split(``).map((e=>e.charCodeAt(0))):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<x&&(this._parseBuffer=new Uint32Array(Math.min(e.length,x))),o||this._dirtyRowTracker.clearRange(),e.length>x)for(let t=a;t<e.length;t+=x){let a=t+x<e.length?t+x:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}this._activeBuffer.x===r&&this._activeBuffer.y===i||this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(c,this._bufferService.rows-1),Math.min(s,this._bufferService.rows-1))}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,d=this._coreService.modes.insertMode,p=this._curAttrData,m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&m.getWidth(this._activeBuffer.x-1)===2&&m.setCellFromCodepoint(this._activeBuffer.x-1,0,1,p);let h=this._parser.precedingJoinState;for(let _=t;_<n;++_){if(r=e[_],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,h);i=g.UnicodeService.extractWidth(t);let n=g.UnicodeService.extractShouldJoin(t),v=n?g.UnicodeService.extractWidth(h):0;if(h=t,o&&this._onA11yChar.fire((0,l.stringFromCodePoint)(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-v>s){if(c){let e=m,t=this._activeBuffer.x-v;for(this._activeBuffer.x=v,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),v>0&&m instanceof u.BufferLine&&m.copyCellsFrom(e,t,0,v,!1);t<s;)e.setCellFromCodepoint(t++,0,1,p)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=m.getWidth(this._activeBuffer.x-1)?1:2;m.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-v;--e>=0;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}else if(d&&(m.insertCells(this._activeBuffer.x,i-v,this._activeBuffer.getNullCell(p)),m.getWidth(s-1)===2&&m.setCellFromCodepoint(s-1,f.NULL_CELL_CODE,f.NULL_CELL_WIDTH,p)),m.setCellFromCodepoint(this._activeBuffer.x++,r,i,p),i>0)for(;--i;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}this._parser.precedingJoinState=h,this._activeBuffer.x<s&&n-t>0&&m.getWidth(this._activeBuffer.x)===0&&!m.hasContent(this._activeBuffer.x)&&m.setCellFromCodepoint(this._activeBuffer.x,0,1,p),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final!==`t`||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,(e=>!S(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new v.DcsHandler(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new _.OscHandler(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),t!==2&&t!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){let n;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(u.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=g.UnicodeService.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(a.C0.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),this._charsetService.setgCharset(1,o.DEFAULT_CHARSET),this._charsetService.setgCharset(2,o.DEFAULT_CHARSET),this._charsetService.setgCharset(3,o.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(e,t){let n=this._coreService.decPrivateModes,{activeProtocol:r,activeEncoding:i}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=e=>e?1:2,p=e.params[0];return m=p,h=t?p===2?4:p===4?f(o.modes.insertMode):p===12?3:p===20?f(d.convertEol):0:p===1?f(n.applicationCursorKeys):p===3?d.windowOptions.setWinLines?c===80?2:c===132?1:0:0:p===6?f(n.origin):p===7?f(n.wraparound):p===8?3:p===9?f(r===`X10`):p===12?f(d.cursorBlink):p===25?f(!o.isCursorHidden):p===45?f(n.reverseWraparound):p===66?f(n.applicationKeypad):p===67?4:p===1e3?f(r===`VT200`):p===1002?f(r===`DRAG`):p===1003?f(r===`ANY`):p===1004?f(n.sendFocus):p===1005?4:p===1006?f(i===`SGR`):p===1015?4:p===1016?f(i===`SGR_PIXELS`):p===1048?1:p===47||p===1047||p===1049?f(l===u):p===2004?f(n.bracketedPasteMode):0,o.triggerDataEvent(`${a.C0.ESC}[${t?``:`?`}${m};${h}$y`),!0;var m,h}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=m.AttributeData.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|255&n),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=u.DEFAULT_ATTR_DATA.fg,e.bg=u.DEFAULT_ATTR_DATA.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777224|n-90):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777224|n-100):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg):n===49?(r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg,r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${a.C0.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle=`block`;break;case 3:case 4:this._optionsService.options.cursorStyle=`underline`;break;case 5:case 6:this._optionsService.options.cursorStyle=`bar`}let n=t%2==1;return this._optionsService.options.cursorBlink=n,!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!S(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(C.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(C.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${a.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:t!==0&&t!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),t!==0&&t!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:t!==0&&t!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),t!==0&&t!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(D(n))if(r===`?`)t.push({type:0,index:n});else{let e=(0,y.parseColor)(r);e&&t.push({type:1,index:n,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.split(`;`);return!(t.length<2)&&(t[1]?this._createHyperlink(t[0],t[1]):!t[0]&&this._finishHyperlink())}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex((e=>e.startsWith(`id=`)));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=(0,y.parseColor)(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);D(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,o.DEFAULT_CHARSET),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(b[e[0]],o.CHARSETS[e[1]]||o.DEFAULT_CHARSET),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new p.CellData;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=this._bufferService.buffer,r=this._optionsService.rawOptions;return(e=>(this._coreService.triggerDataEvent(`${a.C0.ESC}${e}${a.C0.ESC}\\`),!0))(e===`"q`?`P1$r${this._curAttrData.isProtected()?1:0}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-(r.cursorBlink?1:0)} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}}t.InputHandler=T;let E=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(w=e,e=t,t=w),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function D(e){return 0<=e&&e<256}E=r([i(0,h.IBufferService)],E)},844:(e,t)=>{function n(e){for(let t of e)t.dispose();e.length=0}Object.defineProperty(t,`__esModule`,{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(let e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){let t=this._disposables.indexOf(e);t!==-1&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=n,t.getDisposeArrayDisposable=function(e){return{dispose:()=>n(e)}}},114:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.getSafariVersion=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.isNode=typeof process<`u`&&`title`in process;let n=t.isNode?`node`:navigator.userAgent,r=t.isNode?`node`:navigator.platform;t.isFirefox=n.includes(`Firefox`),t.isLegacyEdge=n.includes(`Edge`),t.isSafari=/^((?!chrome|android).)*safari/i.test(n),t.getSafariVersion=function(){if(!t.isSafari)return 0;let e=n.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])},t.isMac=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(r),t.isIpad=r===`iPad`,t.isIphone=r===`iPhone`,t.isWindows=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(r),t.isLinux=r.indexOf(`Linux`)>=0,t.isChromeOS=/\bCrOS\b/.test(n)},226:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;let r=n(114);class i{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=Date.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,Date.now()-t),n=Math.max(t,n),i=e.timeRemaining(),1.5*n>i)return r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),void this._start();r=i}this.clear()}}class a extends i{_requestCallback(e){return setTimeout((()=>e(this._createDeadline(16))))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=Date.now()+e;return{timeRemaining:()=>Math.max(0,t-Date.now())}}}t.PriorityTaskQueue=a,t.IdleTaskQueue=!r.isNode&&`requestIdleCallback`in window?class extends i{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:a,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}}},282:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.updateWindowsModeWrappedState=void 0;let r=n(643);t.updateWindowsModeWrappedState=function(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1),n=t?.get(e.cols-1),i=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);i&&n&&(i.isWrapped=n[r.CHAR_DATA_CODE_INDEX]!==r.NULL_CELL_CODE&&n[r.CHAR_DATA_CODE_INDEX]!==r.WHITESPACE_CELL_CODE)}},734:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class n{constructor(){this.fg=0,this.bg=0,this.extended=new r}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){let e=new n;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t.AttributeData=n;class r{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new r(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}t.ExtendedAttrs=r},92:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;let r=n(349),i=n(226),a=n(734),o=n(437),s=n(634),c=n(511),l=n(643),u=n(863),d=n(116);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o.DEFAULT_ATTR_DATA.clone(),this.savedCharset=d.DEFAULT_CHARSET,this.markers=[],this._nullCell=c.CellData.fromCharData([0,l.NULL_CELL_CHAR,l.NULL_CELL_WIDTH,l.NULL_CELL_CODE]),this._whitespaceCell=c.CellData.fromCharData([0,l.WHITESPACE_CELL_CHAR,l.WHITESPACE_CELL_WIDTH,l.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new i.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new a.ExtendedAttrs),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new a.ExtendedAttrs),this._whitespaceCell}getBlankLine(e,t){return new o.BufferLine(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let n=e+this._optionsService.rawOptions.scrollback;return n>t.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:n}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=o.DEFAULT_ATTR_DATA);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new o.BufferLine(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new o.BufferLine(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=(0,s.reflowLargerGetLinesToRemove)(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(o.DEFAULT_ATTR_DATA));if(n.length>0){let r=(0,s.reflowLargerCreateNewLayout)(this.lines,n);(0,s.reflowLargerApplyNewLayout)(this.lines,r.layout),this._reflowLargerAdjustViewport(e,t,r.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(o.DEFAULT_ATTR_DATA),i=n;for(;i-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new o.BufferLine(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=[],i=0;for(let a=this.lines.length-1;a>=0;a--){let c=this.lines.get(a);if(!c||!c.isWrapped&&c.getTrimmedLength()<=e)continue;let l=[c];for(;c.isWrapped&&a>0;)c=this.lines.get(--a),l.unshift(c);let u=this.ybase+this.y;if(u>=a&&u<a+l.length)continue;let d=l[l.length-1].getTrimmedLength(),f=(0,s.reflowSmallerGetNewLineLengths)(l,this._cols,e),p=f.length-l.length,m=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+p):Math.max(0,this.lines.length-this.lines.maxLength+p),h=[];for(let e=0;e<p;e++){let e=this.getBlankLine(o.DEFAULT_ATTR_DATA,!0);h.push(e)}h.length>0&&(r.push({start:a+l.length+i,newLines:h}),i+=h.length),l.push(...h);let g=f.length-1,_=f[g];_===0&&(g--,_=f[g]);let v=l.length-p-1,y=d;for(;v>=0;){let e=Math.min(y,_);if(l[g]===void 0)break;if(l[g].copyCellsFrom(l[v],y-e,_-e,e,!0),_-=e,_===0&&(g--,_=f[g]),y-=e,y===0){v--;let e=Math.max(v,0);y=(0,s.getWrappedLineTrimmedLength)(l,e,this._cols)}}for(let t=0;t<l.length;t++)f[t]<e&&l[t].setCell(f[t],n);let b=p-m;for(;b-- >0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+i)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+p,this.ybase+t-1)}if(r.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,a=n-1,o=0,s=r[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+i);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+i-1);l>=0;l--)if(s&&s.start>a+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:a+1,amount:s.newLines.length}),c+=s.newLines.length,s=r[++o]}else this.lines.set(l,t[a--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+i-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose(),this.markers.splice(e--,1);this._isClearing=!1}addMarker(e){let t=new u.Marker(e);return this.markers.push(t),t.register(this.lines.onTrim((e=>{t.line-=e,t.line<0&&t.dispose()}))),t.register(this.lines.onInsert((e=>{t.line>=e.index&&(t.line+=e.amount)}))),t.register(this.lines.onDelete((e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)}))),t.register(t.onDispose((()=>this._removeMarker(t)))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}}},437:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;let r=n(734),i=n(511),a=n(643),o=n(482);t.DEFAULT_ATTR_DATA=Object.freeze(new r.AttributeData);let s=0;class c{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);let r=t||i.CellData.fromCharData([0,a.NULL_CELL_CHAR,a.NULL_CELL_WIDTH,a.NULL_CELL_CODE]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[3*e+0],n=2097151&t;return[this._data[3*e+1],2097152&t?this._combined[e]:n?(0,o.stringFromCodePoint)(n):``,t>>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[3*e+1]=t[a.CHAR_DATA_ATTR_INDEX],t[a.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[a.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e+0]=t[a.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[a.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?(0,o.stringFromCodePoint)(2097151&t):``}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return s=3*e,t.content=this._data[s+0],t.fg=this._data[s+1],t.bg=this._data[s+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,n,r){268435456&r.bg&&(this._extendedAttrs[e]=r.extended),this._data[3*e+0]=t|n<<22,this._data[3*e+1]=r.fg,this._data[3*e+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[3*e+0];2097152&r?this._combined[e]+=(0,o.stringFromCodePoint)(t):2097151&r?(this._combined[e]=(0,o.stringFromCodePoint)(2097151&r)+(0,o.stringFromCodePoint)(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[3*e+0]=r}insertCells(e,t,n){if((e%=this.length)&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new i.CellData;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new i.CellData;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)!==0||this.hasContent(e)||this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;let n=3*e;if(e>this.length){if(this._data.buffer.byteLength>=4*n)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,4*n*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){for(let t in this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={},e._combined)this._combined[t]=e._combined[t];for(let t in this._extendedAttrs={},e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let e=new c(0);for(let t in e._data=new Uint32Array(this._data),e.length=this.length,this._combined)e._combined[t]=this._combined[t];for(let t in this._extendedAttrs)e._extendedAttrs[t]=this._extendedAttrs[t];return e.isWrapped=this.isWrapped,e}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[3*t+0],n=2097151&e,s=2097152&e?this._combined[t]:n?(0,o.stringFromCodePoint)(n):a.WHITESPACE_CELL_CHAR;if(i+=s,r)for(let e=0;e<s.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}}t.BufferLine=c},634:(e,t)=>{function n(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}Object.defineProperty(t,`__esModule`,{value:!0}),t.getWrappedLineTrimmedLength=t.reflowSmallerGetNewLineLengths=t.reflowLargerApplyNewLayout=t.reflowLargerCreateNewLayout=t.reflowLargerGetLinesToRemove=void 0,t.reflowLargerGetLinesToRemove=function(e,t,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(i>=s&&i<c){s+=u.length-1;continue}let d=0,f=n(u,d,t),p=1,m=0;for(;p<u.length;){let e=n(u,p,t),i=e-m,o=r-f,s=Math.min(i,o);u[d].copyCellsFrom(u[p],m,f,s,!1),f+=s,f===r&&(d++,f=0),m+=s,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(r-1)===2&&(u[d].copyCellsFrom(u[d-1],r-1,f++,1,!1),u[d-1].setCell(r-1,a))}u[d].replaceCells(f,r,a);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o},t.reflowLargerCreateNewLayout=function(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}},t.reflowLargerApplyNewLayout=function(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length},t.reflowSmallerGetNewLineLengths=function(e,t,r){let i=[],a=e.map(((r,i)=>n(e,i,t))).reduce(((e,t)=>e+t)),o=0,s=0,c=0;for(;c<a;){if(a-c<r){i.push(a-c);break}o+=r;let l=n(e,s,t);o>l&&(o-=l,s++);let u=e[s].getWidth(o-1)===2;u&&o--;let d=u?r-1:r;i.push(d),c+=d}return i},t.getWrappedLineTrimmedLength=n},295:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferSet=void 0;let r=n(460),i=n(844),a=n(92);class o extends i.Disposable{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this.register(new r.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange(`scrollback`,(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,(()=>this.setupTabStops())))}reset(){this._normal=new a.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new a.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}}t.BufferSet=o},511:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CellData=void 0;let r=n(482),i=n(643),a=n(734);class o extends a.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new a.ExtendedAttrs,this.combinedData=``}static fromCharData(e){let t=new o;return t.setFromCharData(e),t}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,r.stringFromCodePoint)(2097151&this.content):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[i.CHAR_DATA_ATTR_INDEX],this.bg=0;let t=!1;if(e[i.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(e[i.CHAR_DATA_CHAR_INDEX].length===2){let n=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=r&&r<=57343?this.content=1024*(n-55296)+r-56320+65536|e[i.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[i.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[i.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[i.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=o},643:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=256|t.DEFAULT_COLOR<<9,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR=``,t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=` `,t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},863:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Marker=void 0;let r=n(460),i=n(844);class a{get id(){return this._id}constructor(e){this.line=e,this.isDisposed=!1,this._disposables=[],this._id=a._nextId++,this._onDispose=this.register(new r.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,i.disposeArray)(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}}t.Marker=a,a._nextId=1},116:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:``,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},t.CHARSETS.A={"#":`£`},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},t.CHARSETS.C=t.CHARSETS[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},t.CHARSETS.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},t.CHARSETS.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},t.CHARSETS.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},t.CHARSETS.E=t.CHARSETS[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},t.CHARSETS.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},t.CHARSETS.H=t.CHARSETS[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`}},584:(e,t)=>{var n,r,i;Object.defineProperty(t,`__esModule`,{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,function(e){e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
|
|
120
|
+
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``}(n||(t.C0=n={})),function(e){e.PAD=``,e.HOP=``,e.BPH=``,e.NBH=``,e.IND=``,e.NEL=`
`,e.SSA=``,e.ESA=``,e.HTS=``,e.HTJ=``,e.VTS=``,e.PLD=``,e.PLU=``,e.RI=``,e.SS2=``,e.SS3=``,e.DCS=``,e.PU1=``,e.PU2=``,e.STS=``,e.CCH=``,e.MW=``,e.SPA=``,e.EPA=``,e.SOS=``,e.SGCI=``,e.SCI=``,e.CSI=``,e.ST=``,e.OSC=``,e.PM=``,e.APC=``}(r||(t.C1=r={})),function(e){e.ST=`${n.ESC}\\`}(i||(t.C1_ESCAPED=i={}))},482:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Utf8ToUtf32=t.StringToUtf32=t.utf32ToString=t.stringFromCodePoint=void 0,t.stringFromCodePoint=function(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)},t.utf32ToString=function(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r},t.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=1024*(this._interim-55296)+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=1024*(i-55296)+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},t.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r,i,a,o,s=0,c=0,l=0;if(this.interim[0]){let r=!1,i=this.interim[0];i&=(224&i)==192?31:(240&i)==224?15:7;let a,o=0;for(;(a=63&this.interim[++o])&&o<4;)i<<=6,i|=a;let c=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(a=e[l++],(192&a)!=128){l--,r=!0;break}this.interim[o++]=a,i<<=6,i|=63&a}r||(c===2?i<128?l--:t[s++]=i:c===3?i<2048||i>=55296&&i<=57343||i===65279||(t[s++]=i):i<65536||i>1114111||(t[s++]=i)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;!(!(d<u)||128&(r=e[d])||128&(i=e[d+1])||128&(a=e[d+2])||128&(o=e[d+3]));)t[s++]=r,t[s++]=i,t[s++]=a,t[s++]=o,d+=4;if(r=e[d++],r<128)t[s++]=r;else if((224&r)==192){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(c=(31&r)<<6|63&i,c<128){d--;continue}t[s++]=c}else if((240&r)==224){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,s;if(a=e[d++],(192&a)!=128){d--;continue}if(c=(15&r)<<12|(63&i)<<6|63&a,c<2048||c>=55296&&c<=57343||c===65279)continue;t[s++]=c}else if((248&r)==240){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,s;if(a=e[d++],(192&a)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,this.interim[2]=a,s;if(o=e[d++],(192&o)!=128){d--;continue}if(c=(7&r)<<18|(63&i)<<12|(63&a)<<6|63&o,c<65536||c>1114111)continue;t[s++]=c}}return s}}},225:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.UnicodeV6=void 0;let r=n(480),i=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],a=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],o;t.UnicodeV6=class{constructor(){if(this.version=`6`,!o){o=new Uint8Array(65536),o.fill(1),o[0]=0,o.fill(0,1,32),o.fill(0,127,160),o.fill(2,4352,4448),o[9001]=2,o[9002]=2,o.fill(2,11904,42192),o[12351]=1,o.fill(2,44032,55204),o.fill(2,63744,64256),o.fill(2,65040,65050),o.fill(2,65072,65136),o.fill(2,65280,65377),o.fill(2,65504,65511);for(let e=0;e<i.length;++e)o.fill(0,i[e][0],i[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?o[e]:function(e,t){let n,r=0,i=t.length-1;if(e<t[0][0]||e>t[i][1])return!1;for(;i>=r;)if(n=r+i>>1,e>t[n][1])r=n+1;else{if(!(e<t[n][0]))return!0;i=n-1}return!1}(e,a)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),i=n===0&&t!==0;if(i){let e=r.UnicodeService.extractWidth(t);e===0?i=!1:e>n&&(n=e)}return r.UnicodeService.createPropertyValue(0,n,i)}}},981:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.WriteBuffer=void 0;let r=n(460),i=n(844);class a extends i.Disposable{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new r.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t)return void(this._syncCalls=0);if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let n;for(this._isSyncWriting=!0;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>5e7)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){let e=e=>Date.now()-n>=12?setTimeout((()=>this._innerWrite(0,e))):this._innerWrite(n,e);r.catch((e=>(queueMicrotask((()=>{throw e})),Promise.resolve(!1)))).then(e);return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,Date.now()-n>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}t.WriteBuffer=a},941:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.toRgbString=t.parseColor=void 0;let n=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,r=/^[\da-f]+$/;function i(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}t.parseColor=function(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=n.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),r.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}},t.toRgbString=function(e,t=16){let[n,r,a]=e;return`rgb:${i(n,t)}/${i(r,t)}/${i(a,t)}`}},770:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.PAYLOAD_LIMIT=void 0,t.PAYLOAD_LIMIT=1e7},351:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.DcsHandler=t.DcsParser=void 0;let r=n(482),i=n(742),a=n(770),o=[];t.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=o,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=o}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=o,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||o,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t);else this._handlerFb(this._ident,`HOOK`,t)}put(e,t,n){if(this._active.length)for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n);else this._handlerFb(this._ident,`PUT`,(0,r.utf32ToString)(e,t,n))}unhook(e,t=!0){if(this._active.length){let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===n){for(;r>=0&&(n=this._active[r].unhook(e),!0!==n);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}else this._handlerFb(this._ident,`UNHOOK`,e);this._active=o,this._ident=0}};let s=new i.Params;s.addParam(0),t.DcsHandler=class{constructor(e){this._handler=e,this._data=``,this._params=s,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():s,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=(0,r.utf32ToString)(e,t,n),this._data.length>a.PAYLOAD_LIMIT&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then((e=>(this._params=s,this._data=``,this._hitLimit=!1,e)));return this._params=s,this._data=``,this._hitLimit=!1,t}}},15:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.EscapeSequenceParser=t.VT500_TRANSITION_TABLE=t.TransitionTable=void 0;let r=n(844),i=n(742),a=n(242),o=n(351);class s{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}}t.TransitionTable=s,t.VT500_TRANSITION_TABLE=function(){let e=new s(4095),t=Array.apply(null,Array(256)).map(((e,t)=>t)),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(160,0,2,0),e.add(160,8,5,8),e.add(160,6,0,6),e.add(160,11,0,11),e.add(160,13,13,13),e}();class c extends r.Disposable{constructor(e=t.VT500_TRANSITION_TABLE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new i.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,r.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new a.OscParser),this._dcsParser=this.register(new o.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},(()=>!0))}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r,i=0,a=0,o=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,a=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===n&&a>-1){for(;a>=0&&(r=t[a](this._params),!0!==r);a--)if(r instanceof Promise)return this._parseStack.handlerPos=a,r}this._parseStack.handlers=[];break;case 4:if(!1===n&&a>-1){for(;a>=0&&(r=t[a](),!0!==r);a--)if(r instanceof Promise)return this._parseStack.handlerPos=a,r}this._parseStack.handlers=[];break;case 6:if(i=e[this._parseStack.chunkPos],r=this._dcsParser.unhook(i!==24&&i!==26,n),r)return r;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(i=e[this._parseStack.chunkPos],r=this._oscParser.end(i!==24&&i!==26,n),r)return r;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let n=o;n<t;++n){switch(i=e[n],a=this._transitions.table[this.currentState<<8|(i<160?i:160)],a>>4){case 2:for(let r=n+1;;++r){if(r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}if(++r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}if(++r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}if(++r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}}break;case 3:this._executeHandlers[i]?this._executeHandlers[i]():this._executeHandlerFb(i),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:i,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let o=this._csiHandlers[this._collect<<8|i],s=o?o.length-1:-1;for(;s>=0&&(r=o[s](this._params),!0!==r);s--)if(r instanceof Promise)return this._preserveStack(3,o,s,a,n),r;s<0&&this._csiHandlerFb(this._collect<<8|i,this._params),this.precedingJoinState=0;break;case 8:do switch(i){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(i-48)}while(++n<t&&(i=e[n])>47&&i<60);n--;break;case 9:this._collect<<=8,this._collect|=i;break;case 10:let c=this._escHandlers[this._collect<<8|i],l=c?c.length-1:-1;for(;l>=0&&(r=c[l](),!0!==r);l--)if(r instanceof Promise)return this._preserveStack(4,c,l,a,n),r;l<0&&this._escHandlerFb(this._collect<<8|i),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|i,this._params);break;case 13:for(let r=n+1;;++r)if(r>=t||(i=e[r])===24||i===26||i===27||i>127&&i<160){this._dcsParser.put(e,n,r),n=r-1;break}break;case 14:if(r=this._dcsParser.unhook(i!==24&&i!==26),r)return this._preserveStack(6,[],0,a,n),r;i===27&&(a|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let r=n+1;;r++)if(r>=t||(i=e[r])<32||i>127&&i<160){this._oscParser.put(e,n,r),n=r-1;break}break;case 6:if(r=this._oscParser.end(i!==24&&i!==26),r)return this._preserveStack(5,[],0,a,n),r;i===27&&(a|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&a}}}t.EscapeSequenceParser=c},242:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.OscHandler=t.OscParser=void 0;let r=n(770),i=n(482),a=[];t.OscParser=class{constructor(){this._state=0,this._active=a,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=a}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=a,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||a,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,`START`)}_put(e,t,n){if(this._active.length)for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n);else this._handlerFb(this._id,`PUT`,(0,i.utf32ToString)(e,t,n))}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===n){for(;r>=0&&(n=this._active[r].end(e),!0!==n);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}else this._handlerFb(this._id,`END`,e);this._active=a,this._id=-1,this._state=0}}},t.OscHandler=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=(0,i.utf32ToString)(e,t,n),this._data.length>r.PAYLOAD_LIMIT&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then((e=>(this._data=``,this._hitLimit=!1,e)));return this._data=``,this._hitLimit=!1,t}}},742:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Params=void 0;let n=2147483647;class r{static fromArray(e){let t=new r;if(!e.length)return t;for(let n=Array.isArray(e[0])?1:0;n<e.length;++n){let r=e[n];if(Array.isArray(r))for(let e=0;e<r.length;++e)t.addSubParam(r[e]);else t.addParam(r)}return t}constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>256)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let e=new r(this.maxLength,this.maxSubParamsLength);return e.params.set(this.params),e.length=this.length,e._subParams.set(this._subParams),e._subParamsLength=this._subParamsLength,e._subParamsIdx.set(this._subParamsIdx),e._rejectDigits=this._rejectDigits,e._rejectSubDigits=this._rejectSubDigits,e._digitIsSub=this._digitIsSub,e}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=255&this._subParamsIdx[t];r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>n?n:e}}addSubParam(e){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>n?n:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=255&this._subParamsIdx[e];return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=255&this._subParamsIdx[t];r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let r=this._digitIsSub?this._subParams:this.params,i=r[t-1];r[t-1]=~i?Math.min(10*i+e,n):e}}t.Params=r},741:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.AddonManager=void 0,t.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}}},771:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferApiView=void 0;let r=n(785),i=n(511);t.BufferApiView=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new r.BufferLineApiView(t)}getNullCell(){return new i.CellData}}},785:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferLineApiView=void 0;let r=n(511);t.BufferLineApiView=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new r.CellData)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}}},285:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferNamespaceApi=void 0;let r=n(771),i=n(460),a=n(844);class o extends a.Disposable{constructor(e){super(),this._core=e,this._onBufferChange=this.register(new i.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new r.BufferApiView(this._core.buffers.normal,`normal`),this._alternate=new r.BufferApiView(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}t.BufferNamespaceApi=o},975:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.ParserApi=void 0,t.ParserApi=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,(e=>t(e.toArray())))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,((e,n)=>t(e,n.toArray())))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}}},90:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.UnicodeApi=void 0,t.UnicodeApi=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}}},744:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.BufferService=t.MINIMUM_ROWS=t.MINIMUM_COLS=void 0;let a=n(460),o=n(844),s=n(295),c=n(585);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;let l=t.BufferService=class extends o.Disposable{get buffer(){return this.buffers.active}constructor(e){super(),this.isUserScrolling=!1,this._onResize=this.register(new a.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new a.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,t.MINIMUM_COLS),this.rows=Math.max(e.rawOptions.rows||0,t.MINIMUM_ROWS),this.buffers=this.register(new s.BufferSet(e,this))}resize(e,t){this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r=this._cachedBlankLine;r&&r.length===this.cols&&r.getFg(0)===e.fg&&r.getBg(0)===e.bg||(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t,n){let r=this.buffer;if(e<0){if(r.ydisp===0)return;this.isUserScrolling=!0}else e+r.ydisp>=r.ybase&&(this.isUserScrolling=!1);let i=r.ydisp;r.ydisp=Math.max(Math.min(r.ydisp+e,r.ybase),0),i!==r.ydisp&&(t||this._onScroll.fire(r.ydisp))}};t.BufferService=l=r([i(0,c.IOptionsService)],l)},994:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.CharsetService=void 0,t.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}}},753:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreMouseService=void 0;let a=n(585),o=n(460),s=n(844),c={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button!==4&&e.action===1&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function l(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=3&e.button,4&e.button&&(n|=64),8&e.button&&(n|=128),e.action===32?n|=32:e.action!==0||t||(n|=3)),n}let u=String.fromCharCode,d={DEFAULT:e=>{let t=[l(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`[M${u(t[0])}${u(t[1])}${u(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`[<${l(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`[<${l(e,!0)};${e.x};${e.y}${t}`}},f=t.CoreMouseService=class extends s.Disposable{constructor(e,t){super(),this._bufferService=e,this._coreService=t,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._onProtocolChange=this.register(new o.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(c))this.addProtocol(e,c[e]);for(let e of Object.keys(d))this.addEncoding(e,d[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};t.CoreMouseService=f=r([i(0,a.IBufferService),i(1,a.ICoreService)],f)},83:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.CoreService=void 0;let a=n(439),o=n(460),s=n(844),c=n(585),l=Object.freeze({insertMode:!1}),u=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0}),d=t.CoreService=class extends s.Disposable{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new o.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new o.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new o.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new o.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,a.clone)(l),this.decPrivateModes=(0,a.clone)(u)}reset(){this.modes=(0,a.clone)(l),this.decPrivateModes=(0,a.clone)(u)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`,(()=>e.split(``).map((e=>e.charCodeAt(0))))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`,(()=>e.split(``).map((e=>e.charCodeAt(0))))),this._onBinary.fire(e))}};t.CoreService=d=r([i(0,c.IBufferService),i(1,c.ILogService),i(2,c.IOptionsService)],d)},348:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.InstantiationService=t.ServiceCollection=void 0;let r=n(585),i=n(343);class a{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}}t.ServiceCollection=a,t.InstantiationService=class{constructor(){this._services=new a,this._services.set(r.IInstantiationService,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=(0,i.getServiceDependencies)(e).sort(((e,t)=>e.index-t.index)),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id}.`);r.push(n)}let a=n.length>0?n[0].index:t.length;if(t.length!==a)throw Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}}},866:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.traceCall=t.setTraceLogger=t.LogService=void 0;let a=n(844),o=n(585),s={trace:o.LogLevelEnum.TRACE,debug:o.LogLevelEnum.DEBUG,info:o.LogLevelEnum.INFO,warn:o.LogLevelEnum.WARN,error:o.LogLevelEnum.ERROR,off:o.LogLevelEnum.OFF},c,l=t.LogService=class extends a.Disposable{get logLevel(){return this._logLevel}constructor(e){super(),this._optionsService=e,this._logLevel=o.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange(`logLevel`,(()=>this._updateLogLevel()))),c=this}_updateLogLevel(){this._logLevel=s[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:`xterm.js: `)+t,...n)}trace(e,...t){this._logLevel<=o.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=o.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=o.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=o.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=o.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};t.LogService=l=r([i(0,o.IOptionsService)],l),t.setTraceLogger=function(e){c=e},t.traceCall=function(e,t,n){if(typeof n.value!=`function`)throw Error(`not supported`);let r=n.value;n.value=function(...e){if(c.logLevel!==o.LogLevelEnum.TRACE)return r.apply(this,e);c.trace(`GlyphRenderer#${r.name}(${e.map((e=>JSON.stringify(e))).join(`, `)})`);let t=r.apply(this,e);return c.trace(`GlyphRenderer#${r.name} return`,t),t}}},302:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.OptionsService=t.DEFAULT_OPTIONS=void 0;let r=n(460),i=n(844);t.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`courier-new, courier, monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:n(114).isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRulerWidth:0};let a=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`];class o extends i.Disposable{constructor(e){super(),this._onOptionChange=this.register(new r.EventEmitter),this.onOptionChange=this._onOptionChange.event;let n={...t.DEFAULT_OPTIONS};for(let t in e)if(t in n)try{let r=e[t];n[t]=this._sanitizeAndValidateOption(t,r)}catch(e){console.error(e)}this.rawOptions=n,this.options={...n},this._setupOptions(),this.register((0,i.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(e,t){return this.onOptionChange((n=>{n===e&&t(this.rawOptions[e])}))}onMultipleOptionChange(e,t){return this.onOptionChange((n=>{e.indexOf(n)!==-1&&t()}))}_setupOptions(){let e=e=>{if(!(e in t.DEFAULT_OPTIONS))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},n=(e,n)=>{if(!(e in t.DEFAULT_OPTIONS))throw Error(`No option with key "${e}"`);n=this._sanitizeAndValidateOption(e,n),this.rawOptions[e]!==n&&(this.rawOptions[e]=n,this._onOptionChange.fire(e))};for(let t in this.rawOptions){let r={get:e.bind(this,t),set:n.bind(this,t)};Object.defineProperty(this.options,t,r)}}_sanitizeAndValidateOption(e,n){switch(e){case`cursorStyle`:if(n||=t.DEFAULT_OPTIONS[e],!function(e){return e===`block`||e===`underline`||e===`bar`}(n))throw Error(`"${n}" is not a valid value for ${e}`);break;case`wordSeparator`:n||=t.DEFAULT_OPTIONS[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof n==`number`&&1<=n&&n<=1e3)break;n=a.includes(n)?n:t.DEFAULT_OPTIONS[e];break;case`cursorWidth`:n=Math.floor(n);case`lineHeight`:case`tabStopWidth`:if(n<1)throw Error(`${e} cannot be less than 1, value: ${n}`);break;case`minimumContrastRatio`:n=Math.max(1,Math.min(21,Math.round(10*n)/10));break;case`scrollback`:if((n=Math.min(n,4294967295))<0)throw Error(`${e} cannot be less than 0, value: ${n}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(n<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${n}`);break;case`rows`:case`cols`:if(!n&&n!==0)throw Error(`${e} must be numeric, value: ${n}`);break;case`windowsPty`:n??={}}return n}}t.OptionsService=o},660:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,`__esModule`,{value:!0}),t.OscLinkService=void 0;let a=n(585),o=t.OscLinkService=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose((()=>this._removeMarkerFromLink(r,n))),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose((()=>this._removeMarkerFromLink(o,a))),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every((e=>e.line!==t))){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose((()=>this._removeMarkerFromLink(n,e)))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};t.OscLinkService=o=r([i(0,a.IBufferService)],o)},343:(e,t)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;let n=`di$target`,r=`di$dependencies`;t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[r]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);let i=function(e,t,a){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);(function(e,t,i){t[n]===t?t[r].push({id:e,index:i}):(t[r]=[{id:e,index:i}],t[n]=t)})(i,e,a)};return i.toString=()=>e,t.serviceRegistry.set(e,i),i}},585:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;let r=n(343);var i;t.IBufferService=(0,r.createDecorator)(`BufferService`),t.ICoreMouseService=(0,r.createDecorator)(`CoreMouseService`),t.ICoreService=(0,r.createDecorator)(`CoreService`),t.ICharsetService=(0,r.createDecorator)(`CharsetService`),t.IInstantiationService=(0,r.createDecorator)(`InstantiationService`),function(e){e[e.TRACE=0]=`TRACE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARN=3]=`WARN`,e[e.ERROR=4]=`ERROR`,e[e.OFF=5]=`OFF`}(i||(t.LogLevelEnum=i={})),t.ILogService=(0,r.createDecorator)(`LogService`),t.IOptionsService=(0,r.createDecorator)(`OptionsService`),t.IOscLinkService=(0,r.createDecorator)(`OscLinkService`),t.IUnicodeService=(0,r.createDecorator)(`UnicodeService`),t.IDecorationService=(0,r.createDecorator)(`DecorationService`)},480:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.UnicodeService=void 0;let r=n(460),i=n(225);class a{static extractShouldJoin(e){return(1&e)!=0}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(16777215&e)<<3|(3&t)<<1|(n?1:0)}constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new r.EventEmitter,this.onChange=this._onChange.event;let e=new i.UnicodeV6;this.register(e),this._active=e.version,this._activeProvider=e}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(e){let t=0,n=0,r=e.length;for(let i=0;i<r;++i){let o=e.charCodeAt(i);if(55296<=o&&o<=56319){if(++i>=r)return t+this.wcwidth(o);let n=e.charCodeAt(i);56320<=n&&n<=57343?o=1024*(o-55296)+n-56320+65536:t+=this.wcwidth(n)}let s=this.charProperties(o,n),c=a.extractWidth(s);a.extractShouldJoin(s)&&(c-=a.extractWidth(n)),t+=c,n=s}return t}charProperties(e,t){return this._activeProvider.charProperties(e,t)}}t.UnicodeService=a},781:(e,t,n)=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.Terminal=void 0;let r=n(437),i=n(969),a=n(460);class o extends i.CoreTerminal{constructor(e={}){super(e),this._onBell=this.register(new a.EventEmitter),this.onBell=this._onBell.event,this._onCursorMove=this.register(new a.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onTitleChange=this.register(new a.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onA11yCharEmitter=this.register(new a.EventEmitter),this.onA11yChar=this._onA11yCharEmitter.event,this._onA11yTabEmitter=this.register(new a.EventEmitter),this.onA11yTab=this._onA11yTabEmitter.event,this._setup(),this.register(this._inputHandler.onRequestBell((()=>this.bell()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register((0,a.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,a.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,a.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,a.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter))}get buffer(){return this.buffers.active}get markers(){return this.buffer.markers}addMarker(e){if(this.buffer===this.buffers.normal)return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}bell(){this._onBell.fire()}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){e===this.cols&&t===this.rows||super.resize(e,t)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(r.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0})}}reset(){this.options.rows=this.rows,this.options.cols=this.cols,this._setup(),super.reset()}}t.Terminal=o}},n={};function r(e){var i=n[e];if(i!==void 0)return i.exports;var a=n[e]={exports:{}};return t[e].call(a.exports,a,a.exports,r),a.exports}var i={};(()=>{var e=i;Object.defineProperty(e,`__esModule`,{value:!0}),e.Terminal=void 0;let t=r(285),n=r(975),a=r(90),o=r(781),s=r(741),c=r(844),l=[`cols`,`rows`];class u extends c.Disposable{constructor(e){super(),this._core=this.register(new o.Terminal(e)),this._addonManager=this.register(new s.AddonManager),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){Object.defineProperty(this._publicOptions,e,{get:()=>this._core.options[e],set:t=>{this._checkReadonlyOptions(e),this._core.options[e]=t}});let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(l.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.options.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onLineFeed(){return this._core.onLineFeed}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onTitleChange(){return this._core.onTitleChange}get parser(){return this._checkProposedApi(),this._parser||=new n.ParserApi(this._core),this._parser}get unicode(){return this._checkProposedApi(),new a.UnicodeApi(this._core)}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._checkProposedApi(),this._buffer||=this.register(new t.BufferNamespaceApi(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}registerMarker(e=0){return this._checkProposedApi(),this._verifyIntegers(e),this._core.addMarker(e)}addMarker(e){return this.registerMarker(e)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
121
|
+
`,t)}reset(){this._core.reset()}loadAddon(e){this._addonManager.loadAddon(this,e)}_verifyIntegers(...e){for(let t of e)if(t===1/0||isNaN(t)||t%1!=0)throw Error(`This API only accepts integers`)}}e.Terminal=u})();var a=e;for(var o in i)a[o]=i[o];i.__esModule&&Object.defineProperty(a,`__esModule`,{value:!0})})()})}),nw=Qx(tw()),rw=Qx(ew());const iw=(e,t)=>{let n=typeof e==`string`;typeof e==`string`&&(e=t.encode(e));let r=new Uint8Array(1+e.byteLength);return r[0]=n?0:1,r.set(new Uint8Array(e),1),r},aw=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1));let ow=function(e){return e[e.REQUEST=0]=`REQUEST`,e[e.PROXY_INIT=1]=`PROXY_INIT`,e[e.PROXY_BODY=2]=`PROXY_BODY`,e[e.PROXY_WEBSOCKET_MESSAGE=3]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=4]=`PROXY_WEBSOCKET_CLOSE`,e}({}),sw=function(e){return e[e.RESPONSE=0]=`RESPONSE`,e[e.NOTIFICATION=1]=`NOTIFICATION`,e[e.PROXY_INIT=2]=`PROXY_INIT`,e[e.PROXY_DATA=3]=`PROXY_DATA`,e[e.PROXY_WEBSOCKET_MESSAGE=4]=`PROXY_WEBSOCKET_MESSAGE`,e[e.PROXY_WEBSOCKET_CLOSE=5]=`PROXY_WEBSOCKET_CLOSE`,e}({});const cw={[ow.REQUEST]:B.string(),[ow.PROXY_INIT]:B.object({method:B.string(),headers:B.record(B.string(),B.string()),url:B.string()}),[ow.PROXY_BODY]:B.instanceof(Uint8Array),[ow.PROXY_WEBSOCKET_MESSAGE]:B.object({type:B.enum([`text`,`binary`]),data:B.instanceof(Uint8Array)}),[ow.PROXY_WEBSOCKET_CLOSE]:B.object({code:B.number().optional(),reason:B.string().optional()})};sw.RESPONSE,B.string(),sw.NOTIFICATION,B.string(),sw.PROXY_INIT,B.object({status_code:B.number(),status_message:B.string(),headers:B.record(B.string(),B.string())}),sw.PROXY_DATA,B.instanceof(Uint8Array),sw.PROXY_WEBSOCKET_MESSAGE,B.instanceof(Uint8Array),sw.PROXY_WEBSOCKET_CLOSE,B.object({code:B.number(),reason:B.string()}),ow.PROXY_INIT,B.string(),B.record(B.string(),B.string()),B.string();const lw={process_execute:B.object({command:B.string(),args:B.array(B.string()),env:B.record(B.string(),B.string()).optional(),cwd:B.string().optional()}),process_send_input:B.object({pid:B.number(),data:B.string()}),process_wait:B.object({pid:B.number(),output_idle_timeout_ms:B.number().optional(),timeout_ms:B.number().optional()}),process_list:B.object({include_dead:B.boolean().optional()}),process_read_plain_output:B.object({pid:B.number(),start_line:B.number().optional(),end_line:B.number().optional()}),process_kill:B.object({pid:B.number(),signal:B.string().optional()}),set_env:B.object({env:B.record(B.string(),B.string())}),read_file:B.object({path:B.string(),line_start:B.number().optional(),line_end:B.number().optional()}),write_file:B.object({path:B.string(),content:B.string(),base64:B.boolean().optional(),mode:B.number().optional()}),read_directory:B.object({path:B.string()}),watch_directory:B.object({path:B.string()}),deploy_static_files:B.object({path:B.string()})},uw=B.object({pid:B.number(),command:B.string(),args:B.array(B.string()),title:B.string().optional(),cwd:B.string(),env:B.record(B.string(),B.string()),exit_code:B.number().optional(),exit_signal:B.number().optional(),duration_ms:B.number().optional(),output_total_lines:B.number()});uw.extend({ansi_output:B.string(),plain_output:B.object({lines:B.array(B.string()),total_lines:B.number()})}),B.object({pid:B.number()}),B.object({}),B.object({processes:B.array(uw)}),B.object({lines:B.array(B.string()),total_lines:B.number(),duration_ms:B.number(),exit_code:B.number().optional(),exit_signal:B.number().optional()}),B.object({}),B.object({}),B.object({total_lines:B.number(),lines_read:B.number(),start_line:B.number(),content:B.string(),mime_type:B.string()}),B.object({}),B.object({entries:B.array(B.object({name:B.string(),type:B.enum([`file`,`directory`,`symlink`])}))}),B.object({}),B.object({deployment_id:B.string()});const dw=B.object({type:B.enum([`create`,`update`,`delete`]),path:B.string()}),fw=B.object({type:B.enum([`context`,`added`,`deleted`]),content:B.string(),oldLineNumber:B.number().optional(),newLineNumber:B.number().optional()}),pw=B.object({oldStart:B.number(),oldLines:B.number(),newStart:B.number(),newLines:B.number(),lines:B.array(fw)}),mw=B.object({path:B.string(),status:B.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:B.string().optional(),insertions:B.number(),deletions:B.number(),chunks:B.array(pw)}),hw=B.object({totalFiles:B.number(),totalInsertions:B.number(),totalDeletions:B.number(),netChange:B.number(),startHash:B.string().optional(),currentHash:B.string().optional(),timespan:B.number(),files:B.array(mw)}),gw=B.object({path:B.string(),status:B.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:B.boolean()}),_w=B.object({hash:B.string(),shortHash:B.string(),message:B.string(),author:B.string(),email:B.string(),date:B.date(),timestamp:B.date(),filesChanged:B.number(),insertions:B.number(),deletions:B.number(),commitDiff:B.array(mw).optional()});B.object({files:B.array(gw),branch:B.string(),ahead:B.number(),behind:B.number(),timestamp:B.date(),sessionDiff:hw.optional(),workingDirectoryDiff:hw.optional(),newCommits:B.array(_w),currentCommit:B.object({hash:B.string(),shortHash:B.string(),message:B.string(),author:B.string(),date:B.date()}).optional(),diffSkipped:B.boolean().optional(),payloadTruncated:B.boolean().optional(),estimatedSizeKB:B.number().optional()}),B.object({debounceDelay:B.number().optional(),gitStatusInterval:B.number().optional(),ignoreDotfiles:B.boolean().optional(),ignored:B.array(B.string()).optional(),watchGit:B.boolean().optional(),includeDiffs:B.boolean().optional(),maxDiffFiles:B.number().optional(),maxPayloadSizeKB:B.number().optional(),truncateLargeDiffs:B.boolean().optional()}),B.object({status:uw}),B.object({pid:B.number(),output:B.string()}),B.object({changes:B.array(dw)});var vw=class e{constructor(e){this.processes=new Map,this.spawnListeners=[],this.globalEnv=e?.env??{},this.nodePty=e?.nodePty}onSpawn(e){return this.spawnListeners.push(e),{dispose:()=>{this.spawnListeners=this.spawnListeners.filter(t=>t!==e)}}}setEnv(e){this.globalEnv={...this.globalEnv,...e},Object.keys(e).forEach(t=>{e[t]===``&&delete this.globalEnv[t]})}execute(t,n,r){let i=yw(t,n,{name:`xterm-256color`,cols:e.COLUMNS,rows:e.ROWS,cwd:r?.cwd,env:{...globalThis.process.env,...this.globalEnv,...r?.env}},this.nodePty),a=new nw.Terminal({allowProposedApi:!0,convertEol:!0,scrollback:e.SCROLLBACK,cols:e.COLUMNS,rows:e.ROWS}),o=new rw.SerializeAddon;a.loadAddon(o);let s;i.onData(e=>{s=new Promise(t=>{a.write(e,t)})}),a.onData(e=>{i.write(e)});let c={command:t,args:n,cwd:r?.cwd??``,env:{...r?.env},startTimeMS:Date.now(),exitCode:void 0,exitSignal:void 0,pid:i.pid,pty:i,terminal:a,serializer:o,kill:e=>{i.kill(e)},onExit:e=>i.onExit(({exitCode:t,signal:n})=>{s?s.then(()=>{e(t,n)}):e(t,n)}),onOutput:e=>i.onData(t=>{e(t)}),sendInput:e=>{a.input(e)}};this.processes.set(i.pid,c),i.onExit(({exitCode:e,signal:t})=>{c.exitCode=e,c.exitSignal=t});for(let e of this.spawnListeners)e(c);return c}status(e){let t=this.processes.get(e);if(!t)throw Error(`Process with PID ${e} not found`);let n=this.readPlainOutput(e);return{pid:t.pid,command:t.command,title:t.pty.process,args:t.args,cwd:t.cwd,env:t.env,exit_code:t.exitCode,exit_signal:t.exitSignal,duration_ms:Date.now()-t.startTimeMS,output_total_lines:n.totalLines}}list(e){return Array.from(this.processes.values()).filter(t=>e||t.exitCode===void 0).map(e=>this.status(e.pid))}getProcess(e){return this.processes.get(e)}readANSIOutput(e,t){let n=this.processes.get(e);if(!n)throw Error(`Process with PID ${e} not found`);return n.serializer.serialize({scrollback:t})}readPlainOutput(t,n,r){let i=n?Math.max(0,n-1):0,a=r?Math.max(0,r-1):e.SCROLLBACK+e.ROWS-1,o=this.processes.get(t);if(!o)throw Error(`Process with PID ${t} not found`);let s=[];for(let t=0;t<e.SCROLLBACK+e.ROWS;t++){let e=o.terminal.buffer.normal.getLine(t);e&&s.push(e.translateToString(!0)??``)}for(;s.length>0&&s[s.length-1].trim()===``;)s.pop();return{lines:s.slice(i,a+1),totalLines:s.length}}close(){this.processes.forEach(e=>{e.pty.kill()})}};vw.COLUMNS=80,vw.ROWS=24,vw.SCROLLBACK=128e3;const yw=(e,t,n,r)=>{if(!r||globalThis.Bun!==void 0){let r=new $x,i=new $x,a=ne(e,t,{env:n.env,cwd:n.cwd,stdio:`pipe`});return a.stdout.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.stderr.on(`data`,e=>{i.emit(Buffer.from(e).toString(`utf-8`))}),a.on(`exit`,(e,t)=>{let n=e??-1,i=t?n:void 0;r.emit({exitCode:n,signal:i})}),a.on(`error`,e=>{throw e}),{pid:a.pid??-1,process:``,onExit:e=>r.event(e),kill(e){a.kill(e)},onData:e=>i.event(e),write(e){a.stdin?.write(e)}}}return r.spawn(e,t,n)};var bw=X({"../../vendor/blink/node_modules/ws/lib/constants.js":((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})}),xw=X({"../../vendor/blink/node_modules/ws/lib/buffer-util.js":((e,t)=>{let{EMPTY_BUFFER:n}=bw(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=Z(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})}),Sw=X({"../../vendor/blink/node_modules/ws/lib/limiter.js":((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);var i=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}};t.exports=i})}),Cw=X({"../../vendor/blink/node_modules/ws/lib/permessage-deflate.js":((e,t)=>{let n=Z(`zlib`),r=xw(),i=Sw(),{kStatusCode:a}=bw(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;var m=class{constructor(e,t,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!p){let e=this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit;p=new i(e)}}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,_),this._inflate.on(`data`,g)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,h)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};t.exports=m;function h(e){this[d].push(e),this[l]+=e.length}function g(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,g),this.reset()}function _(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})}),ww=X({"../../vendor/blink/node_modules/ws/lib/validation.js":((e,t)=>{let{isUtf8:n}=Z(`buffer`),{hasBlob:r}=bw(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=Z(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})}),Tw=X({"../../vendor/blink/node_modules/ws/lib/receiver.js":((e,t)=>{let{Writable:n}=Z(`stream`),r=Cw(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=bw(),{concat:c,toArrayBuffer:l,unmask:u}=xw(),{isValidStatusCode:d,isValidUTF8:f}=ww(),p=Buffer[Symbol.species];var m=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){let t=this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`);e(t);return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(!this._fragmented){let t=this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let t=this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`);e(t);return}if(n){let t=this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`);e(t);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let t=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`);e(t);return}}else{let t=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`);e(t);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){let t=this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`);e(t);return}}else if(this._masked){let t=this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`);e(t);return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){let t=this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`);e(t);return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);e(t);return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let e=this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`);t(e);return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){let t=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);e(t);return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){let e=this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`);t(e);return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){let e=this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`);t(e);return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}};t.exports=m})}),Ew=X({"../../vendor/blink/node_modules/ws/lib/sender.js":((e,t)=>{let{Duplex:n}=Z(`stream`),{randomFillSync:r}=Z(`crypto`),i=Cw(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=bw(),{isBlob:c,isValidStatusCode:l}=ww(),{mask:u,toBuffer:d}=xw(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;var _=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(v,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(y,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){v(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};t.exports=_;function v(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function y(e,t,n){v(e,t,n),e.onerror(t)}})}),Dw=X({"../../vendor/blink/node_modules/ws/lib/event-target.js":((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=bw(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0});let g={addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,_(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,_(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,_(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,_(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}};t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:g,MessageEvent:h};function _(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})}),Ow=X({"../../vendor/blink/node_modules/ws/lib/extension.js":((e,t)=>{let{tokenChars:n}=ww();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})}),kw=X({"../../vendor/blink/node_modules/ws/lib/websocket.js":((e,t)=>{let n=Z(`events`),r=Z(`https`),i=Z(`http`),a=Z(`net`),o=Z(`tls`),{randomBytes:s,createHash:c}=Z(`crypto`),{Duplex:l,Readable:u}=Z(`stream`),{URL:d}=Z(`url`),f=Cw(),p=Tw(),m=Ew(),{isBlob:h}=ww(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=bw(),{EventTarget:{addEventListener:w,removeEventListener:T}}=Dw(),{format:E,parse:D}=Ow(),{toBuffer:O}=xw(),k=Symbol(`kAborted`),A=[8,13],j=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ee=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var M=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),N(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[S]=this,a[S]=this,t[S]=this,i.on(`conclude`,te),i.on(`drain`,z),i.on(`error`,B),i.on(`message`,re),i.on(`ping`,ie),i.on(`pong`,ae),a.onerror=se,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,le),t.on(`data`,ue),t.on(`end`,de),t.on(`error`,fe),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){L(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),ce(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||_,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||_,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){R(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||_,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){L(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(M,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(M.prototype,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(M,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(M.prototype,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(M,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(M.prototype,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(M,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),Object.defineProperty(M.prototype,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(M.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(M.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[y])return t[b];return null},set(t){for(let t of this.listeners(e))if(t[y]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[y]:!0})}})}),M.prototype.addEventListener=w,M.prototype.removeEventListener=T,t.exports=M;function N(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:A[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,!A.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${A.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;P(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),_=u?r.request:i.request,y=new Set,b;if(o.createConnection=o.createConnection||(u?I:F),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(b=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=E({[f.extensionName]:b.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ee.test(e)||y.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);y.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let x;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),x=e._req=_(o),e._redirects&&e.emit(`redirect`,e.url,x)}else x=e._req=_(o);o.timeout&&x.on(`timeout`,()=>{L(e,x,`Opening handshake has timed out`)}),x.on(`error`,t=>{x===null||x[k]||(x=e._req=null,P(e,t))}),x.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){L(e,x,`Maximum redirects exceeded`);return}x.abort();let r;try{r=new d(i,t)}catch{let t=SyntaxError(`Invalid URL: ${i}`);P(e,t);return}N(e,r,n,a)}else e.emit(`unexpected-response`,x,r)||L(e,x,`Unexpected server response: ${r.statusCode}`)}),x.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==M.CONNECTING)return;x=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){L(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+v).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){L(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?y.size&&(l=`Server sent no subprotocol`):y.size?y.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){L(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!b){L(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=D(u)}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){L(e,n,`Server indicated an extension that was not requested`);return}try{b.accept(t[f.extensionName])}catch{L(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=b}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(x,e):x.end()}function P(e,t){e._readyState=M.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function F(e){return e.path=e.socketPath,a.connect(e)}function I(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function L(e,t,n){e._readyState=M.CLOSING;let r=Error(n);Error.captureStackTrace(r,L),t.setHeader?(t[k]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(P,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function R(e,t,n){if(t){let n=h(t)?t.size:O(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${j[e.readyState]})`);process.nextTick(n,t)}}function te(e,t){let n=this[S];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[S]!==void 0&&(n._socket.removeListener(`data`,ue),process.nextTick(oe,n._socket),e===1005?n.close():n.close(e,t))}function z(){let e=this[S];e.isPaused||e._socket.resume()}function B(e){let t=this[S];t._socket[S]!==void 0&&(t._socket.removeListener(`data`,ue),process.nextTick(oe,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function ne(){this[S].emitClose()}function re(e,t){this[S].emit(`message`,e,t)}function ie(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function ae(e){this[S].emit(`pong`,e)}function oe(e){e.resume()}function se(e){let t=this[S];t.readyState!==M.CLOSED&&(t.readyState===M.OPEN&&(t._readyState=M.CLOSING,ce(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function ce(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function le(){let e=this[S];this.removeListener(`close`,le),this.removeListener(`data`,ue),this.removeListener(`end`,de),e._readyState=M.CLOSING;let t;!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&(t=e._socket.read())!==null&&e._receiver.write(t),e._receiver.end(),this[S]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,ne),e._receiver.on(`finish`,ne))}function ue(e){this[S]._receiver.write(e)||this.pause()}function de(){let e=this[S];e._readyState=M.CLOSING,e._receiver.end(),this.end()}function fe(){let e=this[S];this.removeListener(`error`,fe),this.on(`error`,C),e&&(e._readyState=M.CLOSING,this.destroy())}})}),Aw=X({"../../vendor/blink/node_modules/ws/lib/stream.js":((e,t)=>{kw();let{Duplex:n}=Z(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})}),jw=X({"../../vendor/blink/node_modules/ws/lib/subprotocol.js":((e,t)=>{let{tokenChars:n}=ww();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})}),Mw=X({"../../vendor/blink/node_modules/ws/lib/websocket-server.js":((e,t)=>{let n=Z(`events`),r=Z(`http`),{Duplex:i}=Z(`stream`),{createHash:a}=Z(`crypto`),o=Ow(),s=Cw(),c=jw(),l=kw(),{GUID:u,kWebSocket:d}=bw(),f=/^[+/0-9A-Za-z]{22}==$/;var p=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!f.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let p=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&p!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(p);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[d])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let f=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+u).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(f.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});f.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,f,r),i.write(f.concat(`\r
|
|
122
|
+
`).join(`\r
|
|
123
|
+
`)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};t.exports=p;function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
|
|
124
|
+
`)+`\r
|
|
125
|
+
\r
|
|
126
|
+
`+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}})});Aw(),Tw(),Ew();var Nw=Qx(kw(),1);Mw();var Pw=X({"../../vendor/blink/node_modules/fast-fifo/fixed-size.js":((e,t)=>{t.exports=class{constructor(e){if(!(e>0)||e-1&e)throw Error(`Max size for a FixedFIFO should be a power of two`);this.buffer=Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}clear(){this.top=this.btm=0,this.next=null,this.buffer.fill(void 0)}push(e){return this.buffer[this.top]===void 0?(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0):!1}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}peek(){return this.buffer[this.btm]}isEmpty(){return this.buffer[this.btm]===void 0}}})}),Fw=X({"../../vendor/blink/node_modules/fast-fifo/index.js":((e,t)=>{let n=Pw();t.exports=class{constructor(e){this.hwm=e||16,this.head=new n(this.hwm),this.tail=this.head,this.length=0}clear(){this.head=this.tail,this.head.clear(),this.length=0}push(e){if(this.length++,!this.head.push(e)){let t=this.head;this.head=t.next=new n(2*this.head.buffer.length),this.head.push(e)}}shift(){this.length!==0&&this.length--;let e=this.tail.shift();if(e===void 0&&this.tail.next){let e=this.tail.next;return this.tail.next=null,this.tail=e,this.tail.shift()}return e}peek(){let e=this.tail.peek();return e===void 0&&this.tail.next?this.tail.next.peek():e}isEmpty(){return this.length===0}}})}),Iw=X({"../../vendor/blink/node_modules/b4a/index.js":((e,t)=>{function n(e){return Buffer.isBuffer(e)||e instanceof Uint8Array}function r(e){return Buffer.isEncoding(e)}function i(e,t,n){return Buffer.alloc(e,t,n)}function a(e){return Buffer.allocUnsafe(e)}function o(e){return Buffer.allocUnsafeSlow(e)}function s(e,t){return Buffer.byteLength(e,t)}function c(e,t){return Buffer.compare(e,t)}function l(e,t){return Buffer.concat(e,t)}function u(e,t,n,r,i){return b(e).copy(t,n,r,i)}function d(e,t){return b(e).equals(t)}function f(e,t,n,r,i){return b(e).fill(t,n,r,i)}function p(e,t,n){return Buffer.from(e,t,n)}function m(e,t,n,r){return b(e).includes(t,n,r)}function h(e,t,n,r){return b(e).indexOf(t,n,r)}function g(e,t,n,r){return b(e).lastIndexOf(t,n,r)}function _(e){return b(e).swap16()}function v(e){return b(e).swap32()}function y(e){return b(e).swap64()}function b(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function x(e,t,n,r){return b(e).toString(t,n,r)}function S(e,t,n,r,i){return b(e).write(t,n,r,i)}function C(e,t,n){return b(e).writeDoubleLE(t,n)}function w(e,t,n){return b(e).writeFloatLE(t,n)}function T(e,t,n){return b(e).writeUInt32LE(t,n)}function E(e,t,n){return b(e).writeInt32LE(t,n)}function D(e,t){return b(e).readDoubleLE(t)}function O(e,t){return b(e).readFloatLE(t)}function k(e,t){return b(e).readUInt32LE(t)}function A(e,t){return b(e).readInt32LE(t)}function j(e,t,n){return b(e).writeDoubleBE(t,n)}function ee(e,t,n){return b(e).writeFloatBE(t,n)}function M(e,t,n){return b(e).writeUInt32BE(t,n)}function N(e,t,n){return b(e).writeInt32BE(t,n)}function P(e,t){return b(e).readDoubleBE(t)}function F(e,t){return b(e).readFloatBE(t)}function I(e,t){return b(e).readUInt32BE(t)}function L(e,t){return b(e).readInt32BE(t)}t.exports={isBuffer:n,isEncoding:r,alloc:i,allocUnsafe:a,allocUnsafeSlow:o,byteLength:s,compare:c,concat:l,copy:u,equals:d,fill:f,from:p,includes:m,indexOf:h,lastIndexOf:g,swap16:_,swap32:v,swap64:y,toBuffer:b,toString:x,write:S,writeDoubleLE:C,writeFloatLE:w,writeUInt32LE:T,writeInt32LE:E,readDoubleLE:D,readFloatLE:O,readUInt32LE:k,readInt32LE:A,writeDoubleBE:j,writeFloatBE:ee,writeUInt32BE:M,writeInt32BE:N,readDoubleBE:P,readFloatBE:F,readUInt32BE:I,readInt32BE:L}})}),Lw=X({"../../vendor/blink/node_modules/text-decoder/lib/pass-through-decoder.js":((e,t)=>{let n=Iw();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})}),Rw=X({"../../vendor/blink/node_modules/text-decoder/lib/utf8-decoder.js":((e,t)=>{let n=Iw();t.exports=class{constructor(){this.codePoint=0,this.bytesSeen=0,this.bytesNeeded=0,this.lowerBoundary=128,this.upperBoundary=191}get remaining(){return this.bytesSeen}decode(e){if(this.bytesNeeded===0){let t=!0;for(let n=Math.max(0,e.byteLength-4),r=e.byteLength;n<r&&t;n++)t=e[n]<=127;if(t)return n.toString(e,`utf8`)}let t=``;for(let n=0,r=e.byteLength;n<r;n++){let r=e[n];if(this.bytesNeeded===0){r<=127?t+=String.fromCharCode(r):(this.bytesSeen=1,r>=194&&r<=223?(this.bytesNeeded=2,this.codePoint=r&31):r>=224&&r<=239?(r===224?this.lowerBoundary=160:r===237&&(this.upperBoundary=159),this.bytesNeeded=3,this.codePoint=r&15):r>=240&&r<=244?(r===240&&(this.lowerBoundary=144),r===244&&(this.upperBoundary=143),this.bytesNeeded=4,this.codePoint=r&7):t+=`�`);continue}if(r<this.lowerBoundary||r>this.upperBoundary){this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,t+=`�`;continue}this.lowerBoundary=128,this.upperBoundary=191,this.codePoint=this.codePoint<<6|r&63,this.bytesSeen++,this.bytesSeen===this.bytesNeeded&&(t+=String.fromCodePoint(this.codePoint),this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0)}return t}flush(){let e=this.bytesNeeded>0?`�`:``;return this.codePoint=0,this.bytesNeeded=0,this.bytesSeen=0,this.lowerBoundary=128,this.upperBoundary=191,e}}})}),zw=X({"../../vendor/blink/node_modules/text-decoder/index.js":((e,t)=>{let n=Lw(),r=Rw();t.exports=class{constructor(e=`utf8`){switch(this.encoding=i(e),this.encoding){case`utf8`:this.decoder=new r;break;case`utf16le`:case`base64`:throw Error(`Unsupported encoding: `+this.encoding);default:this.decoder=new n(this.encoding)}}get remaining(){return this.decoder.remaining}push(e){return typeof e==`string`?e:this.decoder.decode(e)}write(e){return this.push(e)}end(e){let t=``;return e&&(t=this.push(e)),t+=this.decoder.flush(),t}};function i(e){switch(e=e.toLowerCase(),e){case`utf8`:case`utf-8`:return`utf8`;case`ucs2`:case`ucs-2`:case`utf16le`:case`utf-16le`:return`utf16le`;case`latin1`:case`binary`:return`latin1`;case`base64`:case`ascii`:case`hex`:return e;default:throw Error(`Unknown encoding: `+e)}}})}),Bw=X({"../../vendor/blink/node_modules/streamx/index.js":((e,t)=>{let{EventEmitter:n}=Z(`events`),r=Error(`Stream was destroyed`),i=Error(`Premature close`),a=Fw(),o=zw(),s=typeof queueMicrotask>`u`?e=>global.process.nextTick(e):queueMicrotask,c=(1<<29)-1,l=c^1;c^2;let u=1024,d=2048,f=4096,p=8192,m=16384,h=32768,g=65536,_=131072;16|g,f|128;let v=256|_;c^16,c^64,c^(64|g);let y=c^g;c^256,c^(128|p),c^u;let b=c^768,x=c^h;c^32;let S=c^_;c^v;let C=1<<18,w=2<<18,T=4<<18,E=8<<18,D=16<<18,O=32<<18,k=64<<18,A=128<<18,j=256<<18,ee=512<<18,M=1024<<18;c^(C|j);let N=c^T;c^(C|ee),c^D,c^E;let P=c^A;c^w;let F=c^M,I=16|C,L=c^I,R=m|O,te=14|R;N&536870847;let z=A|h;z&L;let B=33587215;u|16399;let ne=m|143;u|143,u|16398,h|1,ee|8388623,E|D,E|C;let re=270794767;T|C,C|j,O|134217742;let ie=Symbol.asyncIterator||Symbol(`asyncIterator`);var ae=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapWritable:r,byteLength:i,byteLengthWritable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t,this.buffered=0,this.error=null,this.pipeline=null,this.drains=null,this.byteLength=o||i||Ie,this.map=r||n,this.afterWrite=fe.bind(this),this.afterUpdateNextTick=pe.bind(this)}get ended(){return(this.stream._duplexState&O)!==0}push(e){return this.stream._duplexState&142606350?!1:(this.map!==null&&(e=this.map(e)),this.buffered+=this.byteLength(e),this.queue.push(e),this.buffered<this.highWaterMark?(this.stream._duplexState|=E,!0):(this.stream._duplexState|=6291456,!1))}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=534773759),e}end(e){typeof e==`function`?this.stream.once(`finish`,e):e!=null&&this.push(e),this.stream._duplexState=(this.stream._duplexState|ee)&N}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&re)===2359296;)n.push(r._writableState.shift());if(r._duplexState&15)return t(null);r._writev(n,t)}update(){let e=this.stream;e._duplexState|=w;do{for(;(e._duplexState&re)===E;){let t=this.shift();e._duplexState|=67371008,e._write(t,this.afterWrite)}e._duplexState&1310720||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536346623}updateNonPrimary(){let e=this.stream;if((e._duplexState&144965647)===ee){e._duplexState|=C,e._final(ue.bind(this));return}if((e._duplexState&14)==4){(e._duplexState&z)===0&&(e._duplexState|=I,e._destroy(de.bind(this)));return}(e._duplexState&B)===1&&(e._duplexState=(e._duplexState|I)&l,e._open(he.bind(this)))}continueUpdate(){return(this.stream._duplexState&A)===0?!1:(this.stream._duplexState&=P,!0)}updateCallback(){(this.stream._duplexState&35127311)===T?this.update():this.updateNextTick()}updateNextTick(){(this.stream._duplexState&A)===0&&(this.stream._duplexState|=A,(this.stream._duplexState&w)===0&&s(this.afterUpdateNextTick))}},oe=class{constructor(e,{highWaterMark:t=16384,map:n=null,mapReadable:r,byteLength:i,byteLengthReadable:o}={}){this.stream=e,this.queue=new a,this.highWaterMark=t===0?1:t,this.buffered=0,this.readAhead=t>0,this.error=null,this.pipeline=null,this.byteLength=o||i||Ie,this.map=r||n,this.pipeTo=null,this.afterRead=V.bind(this),this.afterUpdateNextTick=H.bind(this)}get ended(){return(this.stream._duplexState&m)!==0}pipe(e,t){if(this.pipeTo!==null)throw Error(`Can only pipe to one destination`);if(typeof t!=`function`&&(t=null),this.stream._duplexState|=512,this.pipeTo=e,this.pipeline=new ce(this.stream,e,t),t&&this.stream.on(`error`,Le),ke(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,Le),e.on(`finish`,this.pipeline.finished.bind(this.pipeline));else{let t=this.pipeline.done.bind(this.pipeline,e),n=this.pipeline.done.bind(this.pipeline,e,null);e.on(`error`,t),e.on(`close`,n),e.on(`finish`,this.pipeline.finished.bind(this.pipeline))}e.on(`drain`,le.bind(this)),this.stream.emit(`piping`,e),e.emit(`pipe`,this.stream)}push(e){let t=this.stream;return e===null?(this.highWaterMark=0,t._duplexState=(t._duplexState|u)&536805311,!1):this.map!==null&&(e=this.map(e),e===null)?(t._duplexState&=y,this.buffered<this.highWaterMark):(this.buffered+=this.byteLength(e),this.queue.push(e),t._duplexState=(t._duplexState|128)&y,this.buffered<this.highWaterMark)}shift(){let e=this.queue.shift();return this.buffered-=this.byteLength(e),this.buffered===0&&(this.stream._duplexState&=536862591),e}unshift(e){let t=[this.map===null?e:this.map(e)];for(;this.buffered>0;)t.push(this.shift());for(let e=0;e<t.length-1;e++){let n=t[e];this.buffered+=this.byteLength(n),this.queue.push(n)}this.push(t[t.length-1])}read(){let e=this.stream;if((e._duplexState&ne)===128){let t=this.shift();return this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t),t}return this.readAhead===!1&&(e._duplexState|=_,this.updateNextTick()),null}drain(){let e=this.stream;for(;(e._duplexState&ne)===128&&e._duplexState&768;){let t=this.shift();this.pipeTo!==null&&this.pipeTo.write(t)===!1&&(e._duplexState&=b),(e._duplexState&d)!==0&&e.emit(`data`,t)}}update(){let e=this.stream;e._duplexState|=32;do{for(this.drain();this.buffered<this.highWaterMark&&(e._duplexState&214047)===_;)e._duplexState|=65552,e._read(this.afterRead),this.drain();(e._duplexState&12431)==4224&&(e._duplexState|=p,e.emit(`readable`)),e._duplexState&80||this.updateNonPrimary()}while(this.continueUpdate()===!0);e._duplexState&=536870879}updateNonPrimary(){let e=this.stream;if((e._duplexState&1167)===u&&(e._duplexState=(e._duplexState|m)&536869887,e.emit(`end`),(e._duplexState&te)===R&&(e._duplexState|=4),this.pipeTo!==null&&this.pipeTo.end()),(e._duplexState&14)==4){(e._duplexState&z)===0&&(e._duplexState|=I,e._destroy(de.bind(this)));return}(e._duplexState&B)===1&&(e._duplexState=(e._duplexState|I)&l,e._open(he.bind(this)))}continueUpdate(){return(this.stream._duplexState&h)===0?!1:(this.stream._duplexState&=x,!0)}updateCallback(){(this.stream._duplexState&32879)==64?this.update():this.updateNextTick()}updateNextTickIfOpen(){this.stream._duplexState&32769||(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}updateNextTick(){(this.stream._duplexState&h)===0&&(this.stream._duplexState|=h,this.stream._duplexState&32||s(this.afterUpdateNextTick))}},se=class{constructor(e){this.data=null,this.afterTransform=ge.bind(e),this.afterFinal=null}},ce=class{constructor(e,t,n){this.from=e,this.to=t,this.afterPipe=n,this.error=null,this.pipeToFinished=!1}finished(){this.pipeToFinished=!0}done(e,t){if(t&&(this.error=t),e===this.to&&(this.to=null,this.from!==null)){((this.from._duplexState&m)===0||!this.pipeToFinished)&&this.from.destroy(this.error||Error(`Writable stream closed prematurely`));return}if(e===this.from&&(this.from=null,this.to!==null)){(e._duplexState&m)===0&&this.to.destroy(this.error||Error(`Readable stream closed before ending`));return}this.afterPipe!==null&&this.afterPipe(this.error),this.to=this.from=this.afterPipe=null}};function le(){this.stream._duplexState|=512,this.updateCallback()}function ue(e){let t=this.stream;e&&t.destroy(e),t._duplexState&14||(t._duplexState|=O,t.emit(`finish`)),(t._duplexState&te)===R&&(t._duplexState|=4),t._duplexState&=402391039,(t._duplexState&w)===0?this.update():this.updateNextTick()}function de(e){let t=this.stream;!e&&this.error!==r&&(e=this.error),e&&t.emit(`error`,e),t._duplexState|=8,t.emit(`close`);let n=t._readableState,i=t._writableState;if(n!==null&&n.pipeline!==null&&n.pipeline.done(t,e),i!==null){for(;i.drains!==null&&i.drains.length>0;)i.drains.shift().resolve(!1);i.pipeline!==null&&i.pipeline.done(t,e)}}function fe(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&me(this.drains),(t._duplexState&6553615)===D&&(t._duplexState&=532676607,(t._duplexState&k)===k&&t.emit(`drain`)),this.updateCallback()}function V(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=S),this.updateCallback()}function H(){this.stream._duplexState&32||(this.stream._duplexState&=x,this.update())}function pe(){(this.stream._duplexState&w)===0&&(this.stream._duplexState&=P,this.update())}function me(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function he(e){let t=this.stream;e&&t.destroy(e),t._duplexState&4||(t._duplexState&17423||(t._duplexState|=64),t._duplexState&142606351||(t._duplexState|=T),t.emit(`open`)),t._duplexState&=L,t._writableState!==null&&t._writableState.updateCallback(),t._readableState!==null&&t._readableState.updateCallback()}function ge(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function _e(e){this._readableState!==null&&(e===`data`&&(this._duplexState|=d|v,this._readableState.updateNextTick()),e===`readable`&&(this._duplexState|=f,this._readableState.updateNextTick())),this._writableState!==null&&e===`drain`&&(this._duplexState|=k,this._writableState.updateNextTick())}var ve=class extends n{constructor(e){super(),this._duplexState=0,this._readableState=null,this._writableState=null,e&&(e.open&&(this._open=e.open),e.destroy&&(this._destroy=e.destroy),e.predestroy&&(this._predestroy=e.predestroy),e.signal&&e.signal.addEventListener(`abort`,Re.bind(this))),this.on(`newListener`,_e)}_open(e){e(null)}_destroy(e){e(null)}_predestroy(){}get readable(){return this._readableState===null?void 0:!0}get writable(){return this._writableState===null?void 0:!0}get destroyed(){return(this._duplexState&8)!=0}get destroying(){return(this._duplexState&14)!=0}destroy(e){this._duplexState&14||(e||=r,this._duplexState=(this._duplexState|4)&535822271,this._readableState!==null&&(this._readableState.highWaterMark=0,this._readableState.error=e),this._writableState!==null&&(this._writableState.highWaterMark=0,this._writableState.error=e),this._duplexState|=2,this._predestroy(),this._duplexState&=536870909,this._readableState!==null&&this._readableState.updateNextTick(),this._writableState!==null&&this._writableState.updateNextTick())}},ye=class e extends ve{constructor(e){super(e),this._duplexState|=O|131073,this._readableState=new oe(this,e),e&&(this._readableState.readAhead===!1&&(this._duplexState&=S),e.read&&(this._read=e.read),e.eagerOpen&&this._readableState.updateNextTick(),e.encoding&&this.setEncoding(e.encoding))}setEncoding(e){let t=new o(e),n=this._readableState.map||De;return this._readableState.map=r,this;function r(e){let r=t.push(e);return r===``&&(e.byteLength!==0||t.remaining>0)?null:n(r)}}_read(e){e(null)}pipe(e,t){return this._readableState.updateNextTick(),this._readableState.pipe(e,t),e}read(){return this._readableState.updateNextTick(),this._readableState.read()}push(e){return this._readableState.updateNextTickIfOpen(),this._readableState.push(e)}unshift(e){return this._readableState.updateNextTickIfOpen(),this._readableState.unshift(e)}resume(){return this._duplexState|=v,this._readableState.updateNextTick(),this}pause(){return this._duplexState&=this._readableState.readAhead===!1?536739583:536870655,this}static _fromAsyncIterator(t,n){let r,i=new e({...n,read(e){t.next().then(a).then(e.bind(null,null)).catch(e)},predestroy(){r=t.return()},destroy(e){if(!r)return e(null);r.then(e.bind(null,null)).catch(e)}});return i;function a(e){e.done?i.push(null):i.push(e.value)}}static from(t,n){if(Ne(t))return t;if(t[ie])return this._fromAsyncIterator(t[ie](),n);Array.isArray(t)||(t=t===void 0?[]:[t]);let r=0;return new e({...n,read(e){this.push(r===t.length?null:t[r++]),e(null)}})}static isBackpressured(e){return(e._duplexState&17422)!=0||e._readableState.buffered>=e._readableState.highWaterMark}static isPaused(e){return(e._duplexState&256)==0}[ie](){let e=this,t=null,n=null,i=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,a),this.on(`close`,o),{[ie](){return this},next(){return new Promise(function(t,r){n=t,i=r;let a=e.read();a===null?e._duplexState&8&&s(null):s(a)})},return(){return c(null)},throw(e){return c(e)}};function a(){n!==null&&s(e.read())}function o(){n!==null&&s(null)}function s(a){i!==null&&(t?i(t):a===null&&(e._duplexState&m)===0?i(r):n({value:a,done:a===null}),i=n=null)}function c(t){return e.destroy(t),new Promise((n,r)=>{if(e._duplexState&8)return n({value:void 0,done:!0});e.once(`close`,function(){t?r(t):n({value:void 0,done:!0})})})}}},be=class extends ve{constructor(e){super(e),this._duplexState|=1|m,this._writableState=new ae(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final),e.eagerOpen&&this._writableState.updateNextTick())}cork(){this._duplexState|=M}uncork(){this._duplexState&=F,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}static isBackpressured(e){return(e._duplexState&146800654)!=0}static drained(e){if(e.destroyed)return Promise.resolve(!1);let t=e._writableState,n=(ze(e)?Math.min(1,t.queue.length):t.queue.length)+(e._duplexState&j?1:0);return n===0?Promise.resolve(!0):(t.drains===null&&(t.drains=[]),new Promise(e=>{t.drains.push({writes:n,resolve:e})}))}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},xe=class extends ye{constructor(e){super(e),this._duplexState=1|this._duplexState&_,this._writableState=new ae(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=M}uncork(){this._duplexState&=F,this._writableState.updateNextTick()}_writev(e,t){t(null)}_write(e,t){this._writableState.autoBatch(e,t)}_final(e){e(null)}write(e){return this._writableState.updateNextTick(),this._writableState.push(e)}end(e){return this._writableState.updateNextTick(),this._writableState.end(e),this}},Se=class extends xe{constructor(e){super(e),this._transformState=new se(this),e&&(e.transform&&(this._transform=e.transform),e.flush&&(this._flush=e.flush))}_write(e,t){this._readableState.buffered>=this._readableState.highWaterMark?this._transformState.data=e:this._transform(e,this._transformState.afterTransform)}_read(e){if(this._transformState.data!==null){let t=this._transformState.data;this._transformState.data=null,e(null),this._transform(t,this._transformState.afterTransform)}else e(null)}destroy(e){super.destroy(e),this._transformState.data!==null&&(this._transformState.data=null,this._transformState.afterTransform())}_transform(e,t){t(null,e)}_flush(e){e(null)}_final(e){this._transformState.afterFinal=e,this._flush(we.bind(this))}},Ce=class extends Se{};function we(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function Te(...e){return new Promise((t,n)=>Ee(...e,e=>{if(e)return n(e);t()}))}function Ee(e,...t){let n=Array.isArray(e)?[...e,...t]:[e,...t],r=n.length&&typeof n[n.length-1]==`function`?n.pop():null;if(n.length<2)throw Error(`Pipeline requires at least 2 streams`);let a=n[0],o=null,s=null;for(let e=1;e<n.length;e++)o=n[e],ke(a)?a.pipe(o,l):(c(a,!0,e>1,l),a.pipe(o)),a=o;if(r){let e=!1,t=ke(o)||!!(o._writableState&&o._writableState.autoDestroy);o.on(`error`,e=>{s===null&&(s=e)}),o.on(`finish`,()=>{e=!0,t||r(s)}),t&&o.on(`close`,()=>r(s||(e?null:i)))}return o;function c(e,t,n,r){e.on(`error`,r),e.on(`close`,a);function a(){if(t&&e._readableState&&!e._readableState.ended||n&&e._writableState&&!e._writableState.ended)return r(i)}}function l(e){if(!(!e||s)){s=e;for(let t of n)t.destroy(e)}}}function De(e){return e}function Oe(e){return!!e._readableState||!!e._writableState}function ke(e){return typeof e._duplexState==`number`&&Oe(e)}function Ae(e){return!!e._readableState&&e._readableState.ended}function je(e){return!!e._writableState&&e._writableState.ended}function Me(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===r?null:n}function Ne(e){return ke(e)&&e.readable}function Pe(e){return(e._duplexState&1)!=1||(e._duplexState&z)!==0}function Fe(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Ie(e){return Fe(e)?e.byteLength:1024}function Le(){}function Re(){this.destroy(Error(`Stream aborted.`))}function ze(e){return e._writev!==be.prototype._writev&&e._writev!==xe.prototype._writev}t.exports={pipeline:Ee,pipelinePromise:Te,isStream:Oe,isStreamx:ke,isEnded:Ae,isFinished:je,isDisturbed:Pe,getStreamError:Me,Stream:ve,Writable:be,Readable:ye,Duplex:xe,Transform:Se,PassThrough:Ce}})}),Vw=X({"../../vendor/blink/node_modules/tar-stream/headers.js":(e=>{let t=Iw(),n=t.from([117,115,116,97,114,0]),r=t.from([48,48]),i=t.from([117,115,116,97,114,32]),a=t.from([32,0]);e.decodeLongPath=function(e,t){return v(e,0,e.length,t)},e.encodePax=function(e){let n=``;e.name&&(n+=y(` path=`+e.name+`
|
|
127
|
+
`)),e.linkname&&(n+=y(` linkpath=`+e.linkname+`
|
|
128
|
+
`));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
|
|
129
|
+
`);return t.from(n)},e.decodePax=function(e){let n={};for(;e.length;){let r=0;for(;r<e.length&&e[r]!==32;)r++;let i=parseInt(t.toString(e.subarray(0,r)),10);if(!i)return n;let a=t.toString(e.subarray(r+1,i-1)),o=a.indexOf(`=`);if(o===-1)return n;n[a.slice(0,o)]=a.slice(o+1),e=e.subarray(i)}return n},e.encode=function(e){let i=t.alloc(512),a=e.name,o=``;if(e.typeflag===5&&a[a.length-1]!==`/`&&(a+=`/`),t.byteLength(a)!==a.length)return null;for(;t.byteLength(a)>100;){let e=a.indexOf(`/`);if(e===-1)return null;o+=o?`/`+a.slice(0,e):a.slice(0,e),a=a.slice(e+1)}return t.byteLength(a)>100||t.byteLength(o)>155||e.linkname&&t.byteLength(e.linkname)>100?null:(t.write(i,a),t.write(i,p(e.mode&4095,6),100),t.write(i,p(e.uid,6),108),t.write(i,p(e.gid,6),116),h(e.size,i,124),t.write(i,p(e.mtime.getTime()/1e3|0,11),136),i[156]=48+u(e.type),e.linkname&&t.write(i,e.linkname,157),t.copy(n,i,257),t.copy(r,i,263),e.uname&&t.write(i,e.uname,265),e.gname&&t.write(i,e.gname,297),t.write(i,p(e.devmajor||0,6),329),t.write(i,p(e.devminor||0,6),337),o&&t.write(i,o,345),t.write(i,p(f(i),6),148),i)},e.decode=function(e,t,n){let r=e[156]===0?0:e[156]-48,i=v(e,0,100,t),a=_(e,100,8),c=_(e,108,8),u=_(e,116,8),d=_(e,124,12),p=_(e,136,12),m=l(r),h=e[157]===0?null:v(e,157,100,t),g=v(e,265,32),y=v(e,297,32),b=_(e,329,8),x=_(e,337,8),S=f(e);if(S===256)return null;if(S!==_(e,148,8))throw Error(`Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?`);if(o(e))e[345]&&(i=v(e,345,155,t)+`/`+i);else if(!s(e)&&!n)throw Error(`Invalid tar header: unknown format.`);return r===0&&i&&i[i.length-1]===`/`&&(r=5),{name:i,mode:a,uid:c,gid:u,size:d,mtime:new Date(1e3*p),type:m,linkname:h,uname:g,gname:y,devmajor:b,devminor:x,pax:null}};function o(e){return t.equals(n,e.subarray(257,263))}function s(e){return t.equals(i,e.subarray(257,263))&&t.equals(a,e.subarray(263,265))}function c(e,t,n){return typeof e==`number`?(e=~~e,e>=t?t:e>=0||(e+=t,e>=0)?e:0):n}function l(e){switch(e){case 0:return`file`;case 1:return`link`;case 2:return`symlink`;case 3:return`character-device`;case 4:return`block-device`;case 5:return`directory`;case 6:return`fifo`;case 7:return`contiguous-file`;case 72:return`pax-header`;case 55:return`pax-global-header`;case 27:return`gnu-long-link-path`;case 28:case 30:return`gnu-long-path`}return null}function u(e){switch(e){case`file`:return 0;case`link`:return 1;case`symlink`:return 2;case`character-device`:return 3;case`block-device`:return 4;case`directory`:return 5;case`fifo`:return 6;case`contiguous-file`:return 7;case`pax-header`:return 72}return 0}function d(e,t,n,r){for(;n<r;n++)if(e[n]===t)return n;return r}function f(e){let t=256;for(let n=0;n<148;n++)t+=e[n];for(let n=156;n<512;n++)t+=e[n];return t}function p(e,t){return e=e.toString(8),e.length>t?`7777777777777777777`.slice(0,t)+` `:`0000000000000000000`.slice(0,t-e.length)+e+` `}function m(e,t,n){t[n]=128;for(let r=11;r>0;r--)t[n+r]=e&255,e=Math.floor(e/256)}function h(e,n,r){e.toString(8).length>11?m(e,n,r):t.write(n,p(e,11),r)}function g(e){let t;if(e[0]===128)t=!0;else if(e[0]===255)t=!1;else return null;let n=[],r;for(r=e.length-1;r>0;r--){let i=e[r];t?n.push(i):n.push(255-i)}let i=0,a=n.length;for(r=0;r<a;r++)i+=n[r]*256**r;return t?i:-1*i}function _(e,n,r){if(e=e.subarray(n,n+r),n=0,e[n]&128)return g(e);{for(;n<e.length&&e[n]===32;)n++;let r=c(d(e,32,n,e.length),e.length,e.length);for(;n<r&&e[n]===0;)n++;return r===n?0:parseInt(t.toString(e.subarray(n,r)),8)}}function v(e,n,r,i){return t.toString(e.subarray(n,d(e,0,n,n+r)),i)}function y(e){let n=t.byteLength(e),r=Math.floor(Math.log(n)/Math.log(10))+1;return n+r>=10**r&&r++,n+r+e}})}),Hw=X({"../../vendor/blink/node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=Bw(),a=Fw(),o=Iw(),s=Vw(),c=o.alloc(0);var l=class{constructor(){this.buffered=0,this.shifted=0,this.queue=new a,this._offset=0}push(e){this.buffered+=e.byteLength,this.queue.push(e)}shiftFirst(e){return this._buffered===0?null:this._next(e)}shift(e){if(e>this.buffered)return null;if(e===0)return c;let t=this._next(e);if(e===t.byteLength)return t;let n=[t];for(;(e-=t.byteLength)>0;)t=this._next(e),n.push(t);return o.concat(n)}_next(e){let t=this.queue.peek(),n=t.byteLength-this._offset;if(e>=n){let e=this._offset?t.subarray(this._offset,t.byteLength):t;return this.queue.shift(),this._offset=0,this.buffered-=n,this.shifted+=n,e}return this.buffered-=e,this.shifted+=e,t.subarray(this._offset,this._offset+=e)}},u=class extends r{constructor(e,t,n){super(),this.header=t,this.offset=n,this._parent=e}_read(e){this.header.size===0&&this.push(null),this._parent._stream===this&&this._parent._update(),e(null)}_predestroy(){this._parent.destroy(i(this))}_detach(){this._parent._stream===this&&(this._parent._stream=null,this._parent._missing=p(this.header.size),this._parent._update())}_destroy(e){this._detach(),e(null)}},d=class extends n{constructor(e){super(e),e||={},this._buffer=new l,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=f,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=e.filenameEncoding||`utf-8`,this._allowUnknownFormat=!!e.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(e){if(this._locked=!1,e){this.destroy(e),this._continueWrite(e);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=s.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(e){return this._continueWrite(e),!1}if(!this._header)return!0;switch(this._header.type){case`gnu-long-path`:case`gnu-long-link-path`:case`pax-global-header`:case`pax-header`:return this._longHeader=!0,this._missing=this._header.size,!0}return this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type===`directory`?(this.emit(`entry`,this._header,this._createStream(),this._unlockBound),!0):(this._stream=this._createStream(),this._missing=this._header.size,this.emit(`entry`,this._header,this._stream,this._unlockBound),!0)}_applyLongHeaders(){this._gnuLongPath&&=(this._header.name=this._gnuLongPath,null),this._gnuLongLinkPath&&=(this._header.linkname=this._gnuLongLinkPath,null),this._pax&&=(this._pax.path&&(this._header.name=this._pax.path),this._pax.linkpath&&(this._header.linkname=this._pax.linkpath),this._pax.size&&(this._header.size=parseInt(this._pax.size,10)),this._header.pax=this._pax,null)}_decodeLongHeader(e){switch(this._header.type){case`gnu-long-path`:this._gnuLongPath=s.decodeLongPath(e,this._filenameEncoding);break;case`gnu-long-link-path`:this._gnuLongLinkPath=s.decodeLongPath(e,this._filenameEncoding);break;case`pax-global-header`:this._paxGlobal=s.decodePax(e);break;case`pax-header`:this._pax=this._paxGlobal===null?s.decodePax(e):Object.assign({},this._paxGlobal,s.decodePax(e));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=p(this._header.size);let e=this._buffer.shift(this._header.size);try{this._decodeLongHeader(e)}catch(e){return this._continueWrite(e),!1}return!0}_consumeStream(){let e=this._buffer.shiftFirst(this._missing);if(e===null)return!1;this._missing-=e.byteLength;let t=this._stream.push(e);return this._missing===0?(this._stream.push(null),t&&this._stream._detach(),t&&this._locked===!1):t}_createStream(){return new u(this,this._header,this._offset)}_update(){for(;this._buffer.buffered>0&&!this.destroying;){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let e=this._buffer.shiftFirst(this._missing);e!==null&&(this._missing-=e.byteLength);continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(e){let t=this._callback;this._callback=f,t(e)}_write(e,t){this._callback=t,this._buffer.push(e),this._update()}_final(e){this._finished=this._missing===0&&this._buffer.buffered===0,e(this._finished?null:Error(`Unexpected end of data`))}_predestroy(){this._continueWrite(null)}_destroy(e){this._stream&&this._stream.destroy(i(this)),e(null)}[Symbol.asyncIterator](){let e=null,t=null,n=null,r=null,i=null,a=this;return this.on(`entry`,c),this.on(`error`,t=>{e=t}),this.on(`close`,l),{[Symbol.asyncIterator](){return this},next(){return new Promise(s)},return(){return u(null)},throw(e){return u(e)}};function o(e){if(!i)return;let t=i;i=null,t(e)}function s(i,s){if(e)return s(e);if(r){i({value:r,done:!1}),r=null;return}t=i,n=s,o(null),a._finished&&t&&(t({value:void 0,done:!0}),t=n=null)}function c(e,a,o){i=o,a.on(`error`,f),t?(t({value:a,done:!1}),t=n=null):r=a}function l(){o(e),t&&=(e?n(e):t({value:void 0,done:!0}),n=null)}function u(e){return a.destroy(e),o(e),new Promise((t,n)=>{if(a.destroyed)return t({value:void 0,done:!0});a.once(`close`,function(){e?n(e):t({value:void 0,done:!0})})})}}};t.exports=function(e){return new d(e)};function f(){}function p(e){return e&=511,e&&512-e}})}),Uw=X({"../../vendor/blink/node_modules/tar-stream/constants.js":((e,t)=>{let n={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{t.exports=Z(`fs`).constants||n}catch{t.exports=n}})}),Ww=X({"../../vendor/blink/node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=Bw(),a=Iw(),o=Uw(),s=Vw(),c=a.alloc(1024);var l=class extends r{constructor(e,t,n){super({mapWritable:m,eagerOpen:!0}),this.written=0,this.header=t,this._callback=n,this._linkname=null,this._isLinkname=t.type===`symlink`&&!t.linkname,this._isVoid=t.type!==`file`&&t.type!==`contiguous-file`,this._finished=!1,this._pack=e,this._openCallback=null,this._pack._stream===null?this._pack._stream=this:this._pack._pending.push(this)}_open(e){this._openCallback=e,this._pack._stream===this&&this._continueOpen()}_continuePack(e){if(this._callback===null)return;let t=this._callback;this._callback=null,t(e)}_continueOpen(){this._pack._stream===null&&(this._pack._stream=this);let e=this._openCallback;if(this._openCallback=null,e!==null){if(this._pack.destroying)return e(Error(`pack stream destroyed`));if(this._pack._finalized)return e(Error(`pack stream is already finalized`));this._pack._stream=this,this._isLinkname||this._pack._encode(this.header),this._isVoid&&(this._finish(),this._continuePack(null)),e(null)}}_write(e,t){if(this._isLinkname)return this._linkname=this._linkname?a.concat([this._linkname,e]):e,t(null);if(this._isVoid)return e.byteLength>0?t(Error(`No body allowed for this entry`)):t();if(this.written+=e.byteLength,this._pack.push(e))return t();this._pack._drain=t}_finish(){this._finished||(this._finished=!0,this._isLinkname&&(this.header.linkname=this._linkname?a.toString(this._linkname,`utf-8`):``,this._pack._encode(this.header)),p(this._pack,this.header.size),this._pack._done(this))}_final(e){if(this.written!==this.header.size)return e(Error(`Size mismatch`));this._finish(),e(null)}_getError(){return i(this)||Error(`tar entry destroyed`)}_predestroy(){this._pack.destroy(this._getError())}_destroy(e){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),e()}},u=class extends n{constructor(e){super(e),this._drain=f,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(e,t,n){if(this._finalized||this.destroying)throw Error(`already finalized or destroyed`);typeof t==`function`&&(n=t,t=null),n||=f,(!e.size||e.type===`symlink`)&&(e.size=0),e.type||=d(e.mode),e.mode||=e.type===`directory`?493:420,e.uid||=0,e.gid||=0,e.mtime||=new Date,typeof t==`string`&&(t=a.from(t));let r=new l(this,e,n);return a.isBuffer(t)?(e.size=t.byteLength,r.write(t),r.end(),r):(r._isVoid,r)}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(c),this.push(null))}_done(e){e===this._stream&&(this._stream=null,this._finalizing&&this.finalize(),this._pending.length&&this._pending.shift()._continueOpen())}_encode(e){if(!e.pax){let t=s.encode(e);if(t){this.push(t);return}}this._encodePax(e)}_encodePax(e){let t=s.encodePax({name:e.name,linkname:e.linkname,pax:e.pax}),n={name:`PaxHeader`,mode:e.mode,uid:e.uid,gid:e.gid,size:t.byteLength,mtime:e.mtime,type:`pax-header`,linkname:e.linkname&&`PaxHeader`,uname:e.uname,gname:e.gname,devmajor:e.devmajor,devminor:e.devminor};this.push(s.encode(n)),this.push(t),p(this,t.byteLength),n.size=e.size,n.type=e.type,this.push(s.encode(n))}_doDrain(){let e=this._drain;this._drain=f,e()}_predestroy(){let e=i(this);for(this._stream&&this._stream.destroy(e);this._pending.length;){let t=this._pending.shift();t.destroy(e),t._continueOpen()}this._doDrain()}_read(e){this._doDrain(),e()}};t.exports=function(e){return new u(e)};function d(e){switch(e&o.S_IFMT){case o.S_IFBLK:return`block-device`;case o.S_IFCHR:return`character-device`;case o.S_IFDIR:return`directory`;case o.S_IFIFO:return`fifo`;case o.S_IFLNK:return`symlink`}return`file`}function f(){}function p(e,t){t&=511,t&&e.push(c.subarray(0,512-t))}function m(e){return a.isBuffer(e)?e:a.from(e)}})}),Gw=X({"../../vendor/blink/node_modules/tar-stream/index.js":(e=>{e.extract=Hw(),e.pack=Ww()})}),Kw=Qx(Gw());const qw=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await I.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=Kw.pack(),i=async(e,t=``)=>{let n=await I.readdir(e,{withFileTypes:!0});for(let a of n){let n=`${e}/${a.name}`,o=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){r.entry({name:`${o}/`,type:`directory`}),await i(n,o);continue}if(a.isSymbolicLink?.()){let e=await I.readlink(n);r.entry({name:o,type:`symlink`,linkname:e});continue}if(a.isFile()){let e=await I.stat(n);await new Promise((t,i)=>{let a=v(n),s=r.entry({name:o,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&i(e)});a.on(`error`,i),a.on(`data`,e=>s.write(e)),a.on(`end`,()=>{s.end(),t()})});continue}}};(async()=>{try{await i(e),r.finalize()}catch(e){r.destroy(e)}})();let a=r,o=0,s=!1;return new ReadableStream({start(e){let t=t=>{if(!s){if(o+=t.length,o>n){s=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${o} bytes.`));try{a.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}},r=t=>{s||(s=!0,e.error(t instanceof Error?t:Error(String(t))))},i=()=>{s||(s=!0,e.close())};a.on(`data`,t),a.once(`error`,r),a.once(`end`,i)},cancel(){try{a.destroy()}catch{}}})},Jw=(e,t)=>e.length<=t?e:e.slice(e.length-t),Yw=(e,t)=>{if(e.length===0)return{lines:[],truncated:!1};let n=0,r=e.length;for(let i=e.length-1;i>=0;i--){let a=e[i].length;if(n+a>t&&r!==e.length)break;n+=a,r=i}return r===0?{lines:e,truncated:!1}:{lines:e.slice(r),truncated:!0}};var Xw=class{constructor(e){this.decoder=new TextDecoder,this.encoder=new TextEncoder,this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new cS({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new vw({env:e.env,nodePty:e.nodePty}),this.processManager.onSpawn(e=>{let t=()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})};t(),e.terminal.onTitleChange(()=>{t()}),e.onExit(()=>{this.sendNotification({type:`process_status`,payload:{status:this.processManager.status(e.pid)}})}),e.onOutput(t=>{let n=aS.getMaxPayloadSize()-1;for(let r=0;r<t.length;r+=n){let i=t.slice(r,r+n);this.sendNotification({type:`process_output`,payload:{pid:e.pid,output:i}})}})})}handleMessage(e){this.multiplexer.handleMessage(e)}handleStream(e){let t=new AbortController;e.onClose(()=>{t.abort()}),e.onData(n=>{let r=n[0],i=n.subarray(1);switch(r){case ow.REQUEST:{let n=JSON.parse(this.decoder.decode(i));if(this.proxyOnly){this.sendResponse(e,{id:n.id,error:`This server is in proxy only mode.`});return}this.handleRequest(e,n,t.signal).catch(t=>{this.sendResponse(e,{id:n.id,error:t instanceof Error?t.message:String(t)})});break}case ow.PROXY_INIT:{let t=cw[ow.PROXY_INIT].safeParse(JSON.parse(this.decoder.decode(i)));if(!t.success)throw Error(`Invalid proxy init message`);let n;n=t.data.headers.upgrade===`websocket`?this.handleProxyWebSocket(e,t.data):this.handleProxyRequest(e,t.data),n.catch(t=>{e.error(t.message)});break}}})}async handleProxyWebSocket(e,t){let n=new URL(t.url);n.protocol===`http:`?n.protocol=`ws:`:n.protocol===`https:`&&(n.protocol=`wss:`);let r=new Nw.default(n.toString(),t.headers[`sec-websocket-protocol`]?t.headers[`sec-websocket-protocol`]:void 0,{headers:t.headers,perMessageDeflate:!1});r.addEventListener(`open`,()=>{e.writeTyped(sw.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(sw.PROXY_WEBSOCKET_MESSAGE,iw(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(sw.PROXY_WEBSOCKET_CLOSE,this.encoder.encode(JSON.stringify(n))),e.close()}),r.addEventListener(`error`,e=>{console.log(`err`,e)}),e.onClose(()=>{r.close()}),e.onError(e=>{r.close(1011,e)}),e.onData(t=>{let n=t.subarray(1);switch(t[0]){case ow.PROXY_WEBSOCKET_MESSAGE:{let e=aw(n,this.decoder);r.send(e);break}case ow.PROXY_WEBSOCKET_CLOSE:{let e=cw[ow.PROXY_WEBSOCKET_CLOSE].safeParse(JSON.parse(this.decoder.decode(n)));if(!e.success)throw Error(`Invalid proxy websocket close message`);try{r.close(e.data.code,e.data.reason)}catch(t){console.error(`Error closing websocket`,t,e.data)}break}default:e.error(`Unexpected message type: ${t[0]}`)}})}async handleProxyRequest(e,t){let n,r;if(t.method!==`GET`&&t.method!==`HEAD`&&t.method!==`OPTIONS`){let e=new TransformStream;n=e.writable.getWriter(),r=e.readable}e.onData(t=>{switch(t[0]){case ow.PROXY_BODY:if(n){let e=t.subarray(1);e.length===0?n.close():n.write(e)}break;default:e.error(`Unexpected message type: ${t[0]}`)}});let i={headers:t.headers,method:t.method,body:r},a;a=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let o={};a.headers.forEach((e,t)=>{o[t]=e});let s={headers:o,status_code:a.status,status_message:a.statusText};e.writeTyped(sw.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,u=aS.getMaxPayloadSize()-1;if(l>=u){if(!a.body){e.close();return}let t=a.body.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;if(r){let t=0;for(;t<r.length;){let n=Math.min(u,r.length-t),i=r.subarray(t,t+n);e.writeTyped(sw.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(sw.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=lw[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{let n=this.processManager.execute(t.payload.command,t.payload.args,{cwd:t.payload.cwd,env:t.payload.env});this.sendResponse(e,{id:t.id,payload:{pid:n.pid}});break}case`process_wait`:this.handleProcessWait(e,t,n);break;case`process_kill`:this.mustGetProcess(t.payload.pid).kill(t.payload.signal),this.sendResponse(e,{id:t.id,payload:{}});break;case`process_list`:this.sendResponse(e,{id:t.id,payload:{processes:this.processManager.list(t.payload.include_dead??!1)}});break;case`process_read_plain_output`:{let n=this.mustGetProcess(t.payload.pid),r=this.processManager.readPlainOutput(t.payload.pid,t.payload.start_line,t.payload.end_line),i=Yw(r.lines,256e3);this.sendResponse(e,{id:t.id,payload:{lines:i.lines,total_lines:r.totalLines,duration_ms:Date.now()-n.startTimeMS,exit_code:n.exitCode,exit_signal:n.exitSignal}});break}case`process_send_input`:this.mustGetProcess(t.payload.pid).sendInput(t.payload.data),this.sendResponse(e,{id:t.id,payload:{}});break;case`set_env`:this.processManager.setEnv(t.payload.env),this.sendResponse(e,{id:t.id,payload:{}});break;case`deploy_static_files`:{if(!this.createDeploymentFromTar)throw Error(`This server does not support static file deployments!`);let n=await qw(t.payload.path),r=await this.createDeploymentFromTar(n);this.sendResponse(e,{id:t.id,payload:{deployment_id:r}});break}case`read_file`:{let n=await S.readFile(t.payload.path),r=await XC(n);if(!(!r||r?.mime===`text/plain`)){this.sendResponse(e,{id:t.id,payload:{content:n.toString(`base64`),mime_type:r?.mime,total_lines:0,lines_read:0,start_line:0}});break}let i=n.toString(`utf-8`).split(`
|
|
130
|
+
`),a=(t.payload.line_start??1)-1,o=t.payload.line_end??i.length,s=i.slice(a,o);this.sendResponse(e,{id:t.id,payload:{content:s.join(`
|
|
131
|
+
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await S.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await S.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await S.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await S.readdir(t.payload.path,{withFileTypes:!0});this.sendResponse(e,{id:t.id,payload:{entries:n.map(e=>({name:e.name,type:e.isDirectory()?`directory`:e.isSymbolicLink()?`symlink`:`file`}))}});break}default:throw Error(`Unknown request type: ${t.type}`)}}sendResponse(e,t){e.writeTyped(sw.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([sw.NOTIFICATION,...this.encoder.encode(JSON.stringify(e))]))}handleProcessWait(e,t,n){let r=t.payload,i=this.mustGetProcess(r.pid),a,o,s=!1,c,l;typeof r.timeout_ms==`number`&&(l=setTimeout(()=>{u()},r.timeout_ms));let u=()=>{if(s||(s=!0,a&&a.dispose(),o&&o.dispose(),l&&clearTimeout(l),c&&clearTimeout(c),n?.aborted))return;let i=this.processManager.status(r.pid),u=this.processManager.readPlainOutput(i.pid),d=Jw(this.processManager.readANSIOutput(i.pid),64e3),f=Yw(u.lines,256e3);this.sendResponse(e,{id:t.id,payload:{...i,ansi_output:d,plain_output:{lines:f.lines,total_lines:u.totalLines}}})};if(typeof i.exitCode==`number`||typeof i.exitSignal==`number`){u();return}a=i.onOutput(()=>{c&&clearTimeout(c),typeof r.output_idle_timeout_ms==`number`&&(c=setTimeout(()=>{u()},r.output_idle_timeout_ms))}),o=i.onExit(()=>{setTimeout(()=>{u()},10)}),n.addEventListener(`abort`,()=>{u()})}mustGetProcess(e){let t=this.processManager.getProcess(e);if(!t)throw Error(`Process ${e} not found`);return t}},Zw=class{constructor(e){this.client=e}listen(e){let t,n,r=!1,i=1e4,a=250,o=()=>{n&&=(clearTimeout(n),void 0)},s=()=>{if(r)return;o();let e=a*.2*Math.random(),t=Math.min(i,Math.floor(a+e));n=setTimeout(()=>{d()},t),a=Math.min(i,Math.floor(a*1.5))},c=()=>{a=250},l=new Xw({send:e=>{let n=t;!n||n.readyState!==WebSocket.OPEN||n.send(e)},fetchProxyRequest(t,n){return e.onRequest(new Request(t,{...n,duplex:n.body?`half`:void 0}))}}),u=t=>{t.binaryType=`arraybuffer`,t.addEventListener(`open`,()=>{r||(c(),e.onConnect?.())}),t.addEventListener(`close`,()=>{r||(e.onDisconnect?.(),s())}),t.addEventListener(`error`,n=>{try{e.onError?.(n)}catch{}try{t.close()}catch{}}),t.addEventListener(`message`,e=>{if(typeof e.data==`string`){console.warn(`Message skipped because it is not a buffer.`);return}try{l.handleMessage(new Uint8Array(e.data))}catch(e){console.error(`message handler error`,e);try{t.close(1011)}catch{}}})},d=()=>{if(!r)try{let n=this.client.websocket(`/api/devhook/${e.id}`);t=n,u(n)}catch(t){try{e.onError?.(t)}catch{}s()}};return d(),{dispose:()=>{if(r)return;r=!0,o();let e=t;t=void 0;try{e&&(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3)}catch{}}}}},Qw=class extends Wx{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new Zw(this)}},$w=e((exports=>{exports.__esModule=!0,exports.Adapt=void 0;function t(e){return i(e)===`boolean`}function n(e){return i(e)===`object`}function r(e){return i(e)===`string`}function i(e){return typeof e}function a(e){var i=e.meta,a=e.path,o=e.xdg,s=function(){function e(s){s===void 0&&(s={});var c,l,u;function d(t){return t===void 0&&(t={}),new e(t)}var f=n(s)?s:{name:s},p=(c=f.suffix)??``,m=(l=f.isolated)??!0,h=[f.name,i.pkgMainFilename(),i.mainFilename()],g=`$eval`,_=a.parse(((u=h.find(function(e){return r(e)}))??g)+p).name;d.$name=function(){return _},d.$isolated=function(){return m};function v(e){var n;e??={isolated:m};var r=t(e)?e:(n=e.isolated)??m;return r}function y(e){return v(e)?_:``}return d.cache=function(e){return a.join(o.cache(),y(e))},d.config=function(e){return a.join(o.config(),y(e))},d.data=function(e){return a.join(o.data(),y(e))},d.runtime=function(e){return o.runtime()?a.join(o.runtime(),y(e)):void 0},d.state=function(e){return a.join(o.state(),y(e))},d.configDirs=function(e){return o.configDirs().map(function(t){return a.join(t,y(e))})},d.dataDirs=function(e){return o.dataDirs().map(function(t){return a.join(t,y(e))})},d}return e}();return{XDGAppPaths:new s}}exports.Adapt=a})),eT=e((exports=>{var t=exports&&exports.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};exports.__esModule=!0,exports.Adapt=void 0;function n(e){var n=e.env,r=e.osPaths,i=e.path,a=/^darwin$/i.test(e.process.platform),o=/^win/i.test(e.process.platform);function s(){return r.home()||r.temp()}function c(e,t){return e||i.join.apply(i,t)}var l=function(){var e=function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`.cache`])},t=function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`.config`])},r=function(){return c(n.get(`XDG_DATA_HOME`),[s(),`.local`,`share`])},i=function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},a=function(){return c(n.get(`XDG_STATE_HOME`),[s(),`.local`,`state`])};return{cache:e,config:t,data:r,runtime:i,state:a}},u=function(){var e=function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`Library`,`Caches`])},t=function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`Library`,`Preferences`])},r=function(){return c(n.get(`XDG_DATA_HOME`),[s(),`Library`,`Application Support`])},i=function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},a=function(){return c(n.get(`XDG_STATE_HOME`),[s(),`Library`,`State`])};return{cache:e,config:t,data:r,runtime:i,state:a}},d=function(){function e(){return c(n.get(`APPDATA`),[s(),`AppData`,`Roaming`])}function t(){return c(n.get(`LOCALAPPDATA`),[s(),`AppData`,`Local`])}var r=function(){return c(n.get(`XDG_CACHE_HOME`),[t(),`xdg.cache`])},i=function(){return c(n.get(`XDG_CONFIG_HOME`),[e(),`xdg.config`])},a=function(){return c(n.get(`XDG_DATA_HOME`),[e(),`xdg.data`])},o=function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},l=function(){return c(n.get(`XDG_STATE_HOME`),[t(),`xdg.state`])};return{cache:r,config:i,data:a,runtime:o,state:l}},f=function(){function e(){function r(){return new e}var s=a?u():o?d():l();return r.cache=s.cache,r.config=s.config,r.data=s.data,r.runtime=s.runtime,r.state=s.state,r.configDirs=function(){var e=n.get(`XDG_CONFIG_DIRS`);return t([s.config()],e?e.split(i.delimiter):[])},r.dataDirs=function(){var e=n.get(`XDG_DATA_DIRS`);return t([s.data()],e?e.split(i.delimiter):[])},r}return e}();return{XDG:new f}}exports.Adapt=n})),tT=e((exports=>{var t=exports&&exports.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};exports.__esModule=!0,exports.Adapt=void 0;function n(e){return!e}function r(e){var r=e.env,i=e.os,a=e.path,o=/^win/i.test(e.process.platform);function s(t){return t?e.path.normalize(e.path.join(t,`.`)):void 0}function c(){var e=function(){return s((typeof i.homedir==`function`?i.homedir():void 0)||r.get(`HOME`))},t=function(){var e=[typeof i.homedir==`function`?i.homedir():void 0,r.get(`USERPROFILE`),r.get(`HOME`),r.get(`HOMEDRIVE`)||r.get(`HOMEPATH`)?a.join(r.get(`HOMEDRIVE`)||``,r.get(`HOMEPATH`)||``):void 0];return s(e.find(function(e){return!n(e)}))};return o?t():e()}function l(){function e(e,n){return e?a.join.apply(a,t([e],n)):void 0}function l(){var e=`/tmp`,t=[typeof i.tmpdir==`function`?i.tmpdir():void 0,r.get(`TMPDIR`),r.get(`TEMP`),r.get(`TMP`)];return s(t.find(function(e){return!n(e)}))||e}function u(){var t=`C:\\Temp`,a=[typeof i.tmpdir==`function`?i.tmpdir:function(){},function(){return r.get(`TEMP`)},function(){return r.get(`TMP`)},function(){return e(r.get(`LOCALAPPDATA`),[`Temp`])},function(){return e(c(),[`AppData`,`Local`,`Temp`])},function(){return e(r.get(`ALLUSERSPROFILE`),[`Temp`])},function(){return e(r.get(`SystemRoot`),[`Temp`])},function(){return e(r.get(`windir`),[`Temp`])},function(){return e(r.get(`SystemDrive`),[`\\`,`Temp`])}],o=a.find(function(e){return e&&!n(e())});return o&&s(o())||t}return o?u():l()}var u=function(){function e(){function t(){return new e}return t.home=c,t.temp=l,t}return e}();return{OSPaths:new u}}exports.Adapt=r})),nT=e((exports=>{var t=exports&&exports.__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=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=exports&&exports.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};exports.__esModule=!0,exports.adapter=void 0;var a=r(i(`os`)),o=r(i(`path`));exports.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:a,path:o,process}})),rT=e(((exports,t)=>{var n=tT(),r=nT();t.exports=n.Adapt(r.adapter).OSPaths})),iT=e((exports=>{var t=exports&&exports.__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=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=exports&&exports.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},a=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};exports.__esModule=!0,exports.adapter=void 0;var o=r(i(`path`)),s=a(rT());exports.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:s.default,path:o,process}})),aT=e(((exports,t)=>{var n=eT(),r=iT();t.exports=n.Adapt(r.adapter).XDG})),oT=e((exports=>{var t=exports&&exports.__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=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=exports&&exports.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!==`default`&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r},a=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};exports.__esModule=!0,exports.adapter=void 0;var o=r(i(`path`)),s=a(aT());exports.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=i!=null&&i.main?i.main:{filename:void 0},t=e.filename,n=(t===process.execArgv[0]?void 0:t)||(process._eval===void 0?process.argv[1]:void 0);return n},pkgMainFilename:function(){return process.pkg?process.execPath:void 0}},path:o,process,xdg:s.default}})),sT=e(((exports,t)=>{var n=$w(),r=oT();t.exports=n.Adapt(r.adapter).XDGAppPaths})),cT={};n(cT,{default:()=>uT});var lT=o(sT(),1);r(cT,o(sT(),1));var uT=lT.default;const dT=(e=0)=>t=>`\u001B[${t+e}m`,fT=(e=0)=>t=>`\u001B[${38+e};5;${t}m`,pT=(e=0)=>(t,n,r)=>`\u001B[${38+e};2;${t};${n};${r}m`,Q={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};Object.keys(Q.modifier);const mT=Object.keys(Q.color),hT=Object.keys(Q.bgColor);[...mT,...hT];function gT(){let e=new Map;for(let[t,n]of Object.entries(Q)){for(let[t,r]of Object.entries(n))Q[t]={open:`\u001B[${r[0]}m`,close:`\u001B[${r[1]}m`},n[t]=Q[t],e.set(r[0],r[1]);Object.defineProperty(Q,t,{value:n,enumerable:!1})}return Object.defineProperty(Q,`codes`,{value:e,enumerable:!1}),Q.color.close=`\x1B[39m`,Q.bgColor.close=`\x1B[49m`,Q.color.ansi=dT(),Q.color.ansi256=fT(),Q.color.ansi16m=pT(),Q.bgColor.ansi=dT(10),Q.bgColor.ansi256=fT(10),Q.bgColor.ansi16m=pT(10),Object.defineProperties(Q,{rgbToAnsi256:{value(e,t,n){return e===t&&t===n?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(t/255*5)+Math.round(n/255*5)},enumerable:!1},hexToRgb:{value(e){let t=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!t)return[0,0,0];let[n]=t;n.length===3&&(n=[...n].map(e=>e+e).join(``));let r=Number.parseInt(n,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:e=>Q.rgbToAnsi256(...Q.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let t,n,r;if(e>=232)t=((e-232)*10+8)/255,n=t,r=t;else{e-=16;let i=e%36;t=Math.floor(e/36)/5,n=Math.floor(i/6)/5,r=i%6/5}let i=Math.max(t,n,r)*2;if(i===0)return 30;let a=30+(Math.round(r)<<2|Math.round(n)<<1|Math.round(t));return i===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,t,n)=>Q.ansi256ToAnsi(Q.rgbToAnsi256(e,t,n)),enumerable:!1},hexToAnsi:{value:e=>Q.ansi256ToAnsi(Q.hexToAnsi256(e)),enumerable:!1}}),Q}const _T=gT();var vT=_T;function yT(e,t=globalThis.Deno?globalThis.Deno.args:y.argv){let n=e.startsWith(`-`)?``:e.length===1?`-`:`--`,r=t.indexOf(n+e),i=t.indexOf(`--`);return r!==-1&&(i===-1||r<i)}const{env:$}=y;let bT;yT(`no-color`)||yT(`no-colors`)||yT(`color=false`)||yT(`color=never`)?bT=0:(yT(`color`)||yT(`colors`)||yT(`color=true`)||yT(`color=always`))&&(bT=1);function xT(){if(`FORCE_COLOR`in $)return $.FORCE_COLOR===`true`?1:$.FORCE_COLOR===`false`?0:$.FORCE_COLOR.length===0?1:Math.min(Number.parseInt($.FORCE_COLOR,10),3)}function ST(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function CT(e,{streamIsTTY:t,sniffFlags:n=!0}={}){let r=xT();r!==void 0&&(bT=r);let i=n?bT:r;if(i===0)return 0;if(n){if(yT(`color=16m`)||yT(`color=full`)||yT(`color=truecolor`))return 3;if(yT(`color=256`))return 2}if(`TF_BUILD`in $&&`AGENT_NAME`in $)return 1;if(e&&!t&&i===void 0)return 0;let a=i||0;if($.TERM===`dumb`)return a;if(y.platform===`win32`){let e=te.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in $)return[`GITHUB_ACTIONS`,`GITEA_ACTIONS`,`CIRCLECI`].some(e=>e in $)?3:[`TRAVIS`,`APPVEYOR`,`GITLAB_CI`,`BUILDKITE`,`DRONE`].some(e=>e in $)||$.CI_NAME===`codeship`?1:a;if(`TEAMCITY_VERSION`in $)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test($.TEAMCITY_VERSION)?1:0;if($.COLORTERM===`truecolor`||$.TERM===`xterm-kitty`||$.TERM===`xterm-ghostty`||$.TERM===`wezterm`)return 3;if(`TERM_PROGRAM`in $){let e=Number.parseInt(($.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch($.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test($.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test($.TERM)||`COLORTERM`in $?1:a}function wT(e,t={}){let n=CT(e,{streamIsTTY:e&&e.isTTY,...t});return ST(n)}const TT={stdout:wT({isTTY:me.isatty(1)}),stderr:wT({isTTY:me.isatty(2)})};var ET=TT;function DT(e,t,n){let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.slice(a,r)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.slice(a),o}function OT(e,t,n,r){let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.slice(i,o?r-1:r)+t+(o?`\r
|
|
132
|
+
`:`
|
|
133
|
+
`)+n,i=r+1,r=e.indexOf(`
|
|
134
|
+
`,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:kT,stderr:AT}=ET,jT=Symbol(`GENERATOR`),MT=Symbol(`STYLER`),NT=Symbol(`IS_EMPTY`),PT=[`ansi`,`ansi`,`ansi256`,`ansi16m`],FT=Object.create(null),IT=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=kT?kT.level:0;e.level=t.level===void 0?n:t.level},LT=e=>{let t=(...e)=>e.join(` `);return IT(t,e),Object.setPrototypeOf(t,RT.prototype),t};function RT(e){return LT(e)}Object.setPrototypeOf(RT.prototype,Function.prototype);for(let[e,t]of Object.entries(vT))FT[e]={get(){let n=UT(this,HT(t.open,t.close,this[MT]),this[NT]);return Object.defineProperty(this,e,{value:n}),n}};FT.visible={get(){let e=UT(this,this[MT],!0);return Object.defineProperty(this,`visible`,{value:e}),e}};const zT=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?vT[n].ansi16m(...r):t===`ansi256`?vT[n].ansi256(vT.rgbToAnsi256(...r)):vT[n].ansi(vT.rgbToAnsi(...r)):e===`hex`?zT(`rgb`,t,n,...vT.hexToRgb(...r)):vT[n][e](...r),BT=[`rgb`,`hex`,`ansi256`];for(let e of BT){FT[e]={get(){let{level:t}=this;return function(...n){let r=HT(zT(e,PT[t],`color`,...n),vT.color.close,this[MT]);return UT(this,r,this[NT])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);FT[t]={get(){let{level:t}=this;return function(...n){let r=HT(zT(e,PT[t],`bgColor`,...n),vT.bgColor.close,this[MT]);return UT(this,r,this[NT])}}}}const VT=Object.defineProperties(()=>{},{...FT,level:{enumerable:!0,get(){return this[jT].level},set(e){this[jT].level=e}}}),HT=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},UT=(e,t,n)=>{let r=(...e)=>WT(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,VT),r[jT]=e,r[MT]=t,r[NT]=n,r},WT=(e,t)=>{if(e.level<=0||!t)return e[NT]?``:t;let n=e[MT];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=DT(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
|
|
135
|
+
`);return a!==-1&&(t=OT(t,i,r,a)),r+t+i};Object.defineProperties(RT.prototype,FT);const GT=RT();RT({level:AT?AT.level:0});var KT=GT;function qT(){let e=YT();if(ie(e)){let t=oe(e,`utf8`);return JSON.parse(t).token}}function JT(e){let t=YT();ie(D(t))||ae(D(t),{recursive:!0}),se(t,JSON.stringify({_:`This is your Blink credentials file. DO NOT SHARE THIS FILE WITH ANYONE!`,token:e}))}function YT(){let e=uT(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return O(e[0],`auth.json`)}async function XT(){let e=new Qw,t=qT();if(t){e.authToken=t;try{await e.users.me()}catch{t=await ZT()}}else t=await ZT();return t}async function ZT(){let e=new Qw,t,n,r=(e,n)=>{t=e,console.log(`Visit`,KT.bold(e),`to authenticate with Blink.`),console.log(KT.dim(`Press [ENTER] to open the browser`))};n=e.auth.token(r),await new Promise(e=>{process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,t=>{(t.toString()===`\r`||t.toString()===`
|
|
136
|
+
`)&&(process.stdin.setRawMode(!1),process.stdin.pause(),e()),t.toString()===``&&(process.stdin.setRawMode(!1),process.stdin.pause(),process.exit(1))})}),await at(t);let i=kn();i.start(`Waiting for authentication...`);try{let t=await n;e.authToken=t;let r=await e.users.me();return i.stop(`Congratulations, you are now signed in as ${r.email}!`),JT(t),t}catch(e){i.stop(`Authentication failed: `+e),process.exit(1)}}var QT=e(((exports,t)=>{t.exports={name:`dotenv`,version:`16.4.7`,description:`Loads environment variables from .env file`,main:`lib/main.js`,types:`lib/main.d.ts`,exports:{".":{types:`./lib/main.d.ts`,require:`./lib/main.js`,default:`./lib/main.js`},"./config":`./config.js`,"./config.js":`./config.js`,"./lib/env-options":`./lib/env-options.js`,"./lib/env-options.js":`./lib/env-options.js`,"./lib/cli-options":`./lib/cli-options.js`,"./lib/cli-options.js":`./lib/cli-options.js`,"./package.json":`./package.json`},scripts:{"dts-check":`tsc --project tests/types/tsconfig.json`,lint:`standard`,pretest:`npm run lint && npm run dts-check`,test:`tap run --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run --show-full-coverage --timeout=60000 --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},funding:`https://dotenvx.com`,keywords:[`dotenv`,`env`,`.env`,`environment`,`variables`,`config`,`settings`],readmeFilename:`README.md`,license:`BSD-2-Clause`,devDependencies:{"@types/node":`^18.11.3`,decache:`^4.6.2`,sinon:`^14.0.1`,standard:`^17.0.0`,"standard-version":`^9.5.0`,tap:`^19.2.0`,typescript:`^4.8.4`},engines:{node:`>=12`},browser:{fs:!1}}})),$T=e(((exports,t)=>{let n=i(`fs`),r=i(`path`),a=i(`os`),o=i(`crypto`),s=QT(),c=s.version,l=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function u(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
137
|
+
`);let r;for(;(r=l.exec(n))!=null;){let e=r[1],n=r[2]||``;n=n.trim();let i=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/gm,`$2`),i===`"`&&(n=n.replace(/\\n/g,`
|
|
138
|
+
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function d(e){let t=_(e),n=w.configDotenv({path:t});if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=h(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=g(n,t);a=w.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return w.parse(a)}function f(e){console.log(`[dotenv@${c}][INFO] ${e}`)}function p(e){console.log(`[dotenv@${c}][WARN] ${e}`)}function m(e){console.log(`[dotenv@${c}][DEBUG] ${e}`)}function h(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:``}function g(e,t){let n;try{n=new URL(t)}catch(e){if(e.code===`ERR_INVALID_URL`){let e=Error(`INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development`);throw e.code=`INVALID_DOTENV_KEY`,e}throw e}let r=n.password;if(!r){let e=Error(`INVALID_DOTENV_KEY: Missing key part`);throw e.code=`INVALID_DOTENV_KEY`,e}let i=n.searchParams.get(`environment`);if(!i){let e=Error(`INVALID_DOTENV_KEY: Missing environment part`);throw e.code=`INVALID_DOTENV_KEY`,e}let a=`DOTENV_VAULT_${i.toUpperCase()}`,o=e.parsed[a];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code=`NOT_FOUND_DOTENV_ENVIRONMENT`,e}return{ciphertext:o,key:r}}function _(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let r of e.path)n.existsSync(r)&&(t=r.endsWith(`.vault`)?r:`${r}.vault`);else t=e.path.endsWith(`.vault`)?e.path:`${e.path}.vault`;else t=r.resolve(process.cwd(),`.env.vault`);return n.existsSync(t)?t:null}function v(e){return e[0]===`~`?r.join(a.homedir(),e.slice(1)):e}function y(e){f(`Loading env from encrypted .env.vault`);let t=w._parseVault(e),n=process.env;return e&&e.processEnv!=null&&(n=e.processEnv),w.populate(n,t,e),{parsed:t}}function b(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=!!(e&&e.debug);e&&e.encoding?i=e.encoding:a&&m(`No encoding is specified. UTF-8 is used by default`);let o=[t];if(e&&e.path)if(!Array.isArray(e.path))o=[v(e.path)];else{o=[];for(let t of e.path)o.push(v(t))}let s,c={};for(let t of o)try{let r=w.parse(n.readFileSync(t,{encoding:i}));w.populate(c,r,e)}catch(e){a&&m(`Failed to load ${t} ${e.message}`),s=e}let l=process.env;return e&&e.processEnv!=null&&(l=e.processEnv),w.populate(l,c,e),s?{parsed:c,error:s}:{parsed:c}}function x(e){if(h(e).length===0)return w.configDotenv(e);let t=_(e);return t?w._configVault(e):(p(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),w.configDotenv(e))}function S(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),a=r.subarray(-16);r=r.subarray(12,-16);try{let e=o.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){let t=e instanceof RangeError,n=e.message===`Invalid key length`,r=e.message===`Unsupported state or unable to authenticate data`;if(t||n){let e=Error(`INVALID_DOTENV_KEY: It must be 64 characters long (or more)`);throw e.code=`INVALID_DOTENV_KEY`,e}else if(r){let e=Error(`DECRYPTION_FAILED: Please check your DOTENV_KEY`);throw e.code=`DECRYPTION_FAILED`,e}else throw e}}function C(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override);if(typeof t!=`object`){let e=Error(`OBJECT_REQUIRED: Please check the processEnv argument being passed to populate`);throw e.code=`OBJECT_REQUIRED`,e}for(let n of Object.keys(t))Object.prototype.hasOwnProperty.call(e,n)?(i===!0&&(e[n]=t[n]),r&&m(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):e[n]=t[n]}let w={configDotenv:b,_configVault:y,_parseVault:d,config:x,decrypt:S,parse:u,populate:C};t.exports.configDotenv=w.configDotenv,t.exports._configVault=w._configVault,t.exports._parseVault=w._parseVault,t.exports.config=w.config,t.exports.decrypt=w.decrypt,t.exports.parse=w.parse,t.exports.populate=w.populate,t.exports=w}));export{Qw as Client,ot as Emitter,Fo as EventSourceParserStream,wn as Ie,En as M,Tn as Se,kn as Y,he as build,pa as createAgentClient,No as createParser,ty as createServeClient,Qv as createServer,ye as findNearestEntry,qT as getAuthToken,Xf as getToolOrDynamicToolName,Jf as isToolOrDynamicToolUIPart,ZT as login,XT as loginIfNeeded,at as open_default,Ht as pD,$T as require_main,_e as resolveEntrypoint,ey as serve,KT as source_default,Sn as ve,ge as watch,Cn as xe,xn as ye};
|