blink 0.1.106 → 0.1.107
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/{chat-manager-r6Y3l4iZ.js → chat-manager-BL3XfguD.js} +1 -1
- package/dist/cli/{dev-D_0M2SCQ.js → dev-CHnIFYZD.js} +2 -2
- package/dist/cli/index.js +2 -2
- package/dist/cli/{run-CfFYxCDt.js → run-9Tt6YpRG.js} +1 -1
- package/dist/node/agent/index.node.cjs +1 -1
- package/dist/node/agent/index.node.js +1 -1
- package/dist/node/build/index.cjs +1 -1
- package/dist/node/build/index.js +1 -1
- package/dist/node/{build-lx6plR19.cjs → build-BzoNpizh.cjs} +4 -4
- package/dist/node/{build-M5Q2ZTGh.js → build-D_L0gFGa.js} +5 -5
- package/dist/node/{getMachineId-bsd-CUUgtcEk.cjs → getMachineId-bsd-B84ixt26.cjs} +1 -1
- package/dist/node/{getMachineId-bsd-YA-Qh955.cjs → getMachineId-bsd-BudRe7J9.cjs} +1 -1
- package/dist/node/{getMachineId-bsd-CpiyZ31n.js → getMachineId-bsd-BxqlJcyA.js} +1 -1
- package/dist/node/{getMachineId-bsd-DKc3Wh2z.js → getMachineId-bsd-C10eVJgT.js} +1 -1
- package/dist/node/{getMachineId-darwin-BBDIi9K5.js → getMachineId-darwin-Bf4P0U5b.js} +1 -1
- package/dist/node/{getMachineId-darwin-CcM48gLI.cjs → getMachineId-darwin-Cyng5kFG.cjs} +1 -1
- package/dist/node/{getMachineId-darwin-CQ9-5u-a.js → getMachineId-darwin-JB29MQsG.js} +1 -1
- package/dist/node/{getMachineId-darwin-IcDjLpqm.cjs → getMachineId-darwin-ZVi3EKE3.cjs} +1 -1
- package/dist/node/{getMachineId-linux-BzwdWZoB.cjs → getMachineId-linux-B-CtXK0L.cjs} +1 -1
- package/dist/node/{getMachineId-linux-Cc8c4coA.js → getMachineId-linux-BPnkHJah.js} +1 -1
- package/dist/node/{getMachineId-linux-DMvLmvRp.cjs → getMachineId-linux-CJXPQ8U5.cjs} +1 -1
- package/dist/node/{getMachineId-linux-TNXyQsBB.js → getMachineId-linux-CmMSYp7C.js} +1 -1
- package/dist/node/{getMachineId-unsupported-ApoW5rxx.cjs → getMachineId-unsupported--0R36RP6.cjs} +1 -1
- package/dist/node/{getMachineId-unsupported-CRrpolgF.js → getMachineId-unsupported-C_4fnT4Z.js} +1 -1
- package/dist/node/{getMachineId-unsupported-DYGwqELh.cjs → getMachineId-unsupported-DM7fz1pP.cjs} +1 -1
- package/dist/node/{getMachineId-unsupported-DGhOj3l0.js → getMachineId-unsupported-Dtt3HTNZ.js} +1 -1
- package/dist/node/{getMachineId-win-Dfq5UG8G.js → getMachineId-win-C4G-fkEF.js} +1 -1
- package/dist/node/{getMachineId-win-B-bRjIv0.cjs → getMachineId-win-CjJkZMZe.cjs} +1 -1
- package/dist/node/{getMachineId-win-CSKzOPIT.js → getMachineId-win-D1szVnqR.js} +1 -1
- package/dist/node/{getMachineId-win-CoAu5xDr.cjs → getMachineId-win-DDz2FyEp.cjs} +1 -1
- package/dist/node/{index.node-CA-85Opm.js → index.node-SyKw4kKs.js} +4 -4
- package/dist/node/{index.node-UnooY2Tf.cjs → index.node-nrQ20r3u.cjs} +4 -4
- package/dist/node/react/index.node.cjs +32 -32
- package/dist/node/react/index.node.js +23 -23
- package/dist/node/{token-C10csUbV.cjs → token-BBGr-czK.cjs} +1 -1
- package/dist/node/{token-B0ivJQut.js → token-DOfE6QlD.js} +1 -1
- package/dist/node/{token-util-BwRq8n40.cjs → token-util-BOoyY0PX.cjs} +1 -1
- package/dist/node/token-util-C_uzN2q9.js +1 -0
- package/dist/node/token-util-D9kCwzE6.cjs +1 -0
- package/dist/node/{token-util-1r_uDcp7.js → token-util-_pz5CtFI.js} +1 -1
- package/package.json +1 -1
- package/dist/node/token-util-CSWJ2yfA.js +0 -1
- package/dist/node/token-util-beB2LRJ9.cjs +0 -1
- /package/dist/node/{esm-C-vSI1Ww.cjs → esm-0UNjvroT.cjs} +0 -0
- /package/dist/node/{esm-D1GEQyaY.js → esm-CbZfjZBn.js} +0 -0
- /package/dist/node/{token-error-wsvzy87W.js → token-error-488npYdU.js} +0 -0
- /package/dist/node/{token-error-l6zIbPbZ.cjs → token-error-BoNG8ooW.cjs} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../build-lx6plR19.cjs`),n=require(`../index.node-UnooY2Tf.cjs`);require(`../token-error-l6zIbPbZ.cjs`),require(`../esm-C-vSI1Ww.cjs`);let r=require(`path`);r=e.__toESM(r);let i=require(`fs`);i=e.__toESM(i);let a=require(`module`);a=e.__toESM(a);let o=require(`fs/promises`);o=e.__toESM(o);let s=require(`zod/v4`);s=e.__toESM(s),require(`zod/v3`);let c=require(`node:fs`);c=e.__toESM(c);let l=require(`node:stream`);l=e.__toESM(l);let u=require(`node:util`);u=e.__toESM(u);let d=require(`http`);d=e.__toESM(d);let f=require(`node:process`);f=e.__toESM(f);let p=require(`ai`);p=e.__toESM(p);let m=require(`child_process`);m=e.__toESM(m);let h=require(`react`);h=e.__toESM(h);let g=require(`node:path`);g=e.__toESM(g);let _=require(`node:module`);_=e.__toESM(_);let v=require(`zod`);v=e.__toESM(v);let y=require(`node:readline`);y=e.__toESM(y);let b=require(`node:fs/promises`);b=e.__toESM(b);function x(e){let[t,r]=(0,h.useState)(void 0),[i,a]=(0,h.useState)([]),[o,s]=(0,h.useState)(void 0),[c,l]=(0,h.useState)(e.buildResult),[u,d]=(0,h.useState)(e.env),[f,p]=(0,h.useState)(e.apiServerUrl),[g,_]=(0,h.useState)(void 0);return(0,h.useEffect)(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),(0,h.useEffect)(()=>{if(!c||`error`in c){r(void 0),a([]),s(void 0);return}let e=new AbortController,t=!1;return s(void 0),(async()=>{let t=await S(),i=(0,m.spawn)(`node`,[`--no-deprecation`,c.entry],{stdio:`pipe`,env:{...process.env,...u,[n.APIServerURLEnvironmentVariable]:f,PORT:t.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{i.kill()}catch{}});let o=!1;i.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!o&&t.startsWith(`Agent server listening on`)||(o||console.log(`stdout: ${t}`),t.length&&a(e=>[...e,{level:`log`,message:t}]))}),i.stderr.on(`data`,e=>{o||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&a(e=>[...e,{level:`error`,message:t}])}),i.on(`error`,t=>{e.abort(t)}),i.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let s=new n.Client({baseUrl:`http://127.0.0.1:${t}`});for(;!e.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;o=!0;let l=await s.capabilities();_(l),r(s)})().catch(e=>{t||s(e instanceof Error?e:Error(String(e)))}),()=>{t=!0,e.abort()}},[c,u,f]),(0,h.useMemo)(()=>({agent:t,logs:i,error:o,capabilities:g}),[t,i,o,g])}async function S(){let e=(0,d.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function C(e){let{directory:n,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,h.useMemo)(()=>t.resolveConfig(n),[n]),[s,c]=(0,h.useState)(void 0),[l,u]=(0,h.useState)(void 0),[d,f]=(0,h.useState)(`building`),p=(0,h.useRef)(r),m=(0,h.useRef)(i),g=(0,h.useRef)(a);return(0,h.useEffect)(()=>{p.current=r,m.current=i,g.current=a},[r,i,a]),(0,h.useEffect)(()=>{let e=new AbortController;return o.build({cwd:n,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),g.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),g.current?.(e)}),()=>{e.abort()}},[n]),(0,h.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function w(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function T(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const E=100,D=/^\.+(\\|\/)|^\.+$/,O=/[. ]+$/,k=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,A=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,j=e=>e===``,M=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,N=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let P;function F(){return P??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),P}function ee(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(w().test(n)||[...n].some(e=>A.test(e)&&!j(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(N,` `),n.length>0&&(e=e.replaceAll(M,`$1`)),e=e.replace(O,``),e=e.replace(D,n),e=e.replace(w(),n),e=e.replaceAll(k,e=>j(e)?e:n),e.length===0&&(e=n),e=T().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=I(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=I(n,a)+i}}return e}function I(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of F().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function L(e){return`${e}.lock`}function R(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function te(e,t={}){let n=L(e),r=process.pid.toString();try{return c.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let i;try{i=parseInt(c.readFileSync(n,`utf8`),10)}catch{return c.unlinkSync(n),te(e,{...t,stale:0})}if(!R(i))try{return c.unlinkSync(n),te(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return te(e,{...t,stale:0});throw n}return!1}}async function z(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=g.resolve(e),i=0;for(;i<=n.retries;){if(te(r,n))return()=>B(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function B(e){let t=g.resolve(e),n=L(t);try{if(parseInt(c.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}c.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function V(e){let t=g.resolve(e),n=L(t);try{if(!c.existsSync(n))return{locked:!1};let e=c.readFileSync(n,`utf8`),t=parseInt(e,10);return R(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const ne=e=>{c.mkdirSync(e,{recursive:!0})},re=e=>{try{c.fdatasyncSync(e)}catch{}try{c.closeSync(e)}catch{}},H=e=>{try{let t=c.openSync(e,`r`);try{c.fsyncSync(t)}finally{c.closeSync(t)}}catch{}},U=(e,t)=>{let n=g.dirname(e);ne(n);let r=g.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),i;try{i=c.openSync(r,`w`),c.writeFileSync(i,t,`utf-8`),re(i),i=void 0,c.renameSync(r,e),H(e),H(n)}catch(e){if(i!==void 0)try{c.closeSync(i)}catch{}try{c.rmSync(r,{force:!0})}catch{}throw e}},ie=(e,t)=>{let n=new Map,r,i=e=>{if(c.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(c.readFileSync(e,`utf-8`))},a=(e,t)=>{U(e,JSON.stringify(t,null,2))},o=async()=>{if(r)throw Error(`Index is already locked`);let t=g.join(e,`index.json`);ne(e),c.existsSync(t)||c.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await z(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},s=async()=>{let t=g.join(e,`index.json`),n=i(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=g.join(e,`index.json`);a(n,t)},u=async t=>{let n=(await s()).ids[t];if(n)return g.join(e,n)},d=async t=>{let n=(await s()).ids[t];if(!n)return;let r=g.join(e,n);if(c.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(c.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),c=ee(i,{replacement:`_`})+`.json`,u=await o();try{let t=await s();t.ids[i]=c,t.current=i;let r=g.join(e,c);a(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!c.statSync(e,{throwIfNoEntry:!1}))return[];let t=await s(),n=[];for(let[r,i]of Object.entries(t.ids)){let t=g.join(e,i),a=c.statSync(t,{throwIfNoEntry:!1});if(!a)continue;let o=V(t);n.push({key:r,locked:o.locked,pid:o.pid,mtime:a.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,i){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let a=await u(r);if(!a){let t=ee(r,{replacement:`_`})+`.json`,n=await o();try{let n=await s();n.ids[r]=t;let i=g.join(e,t);ne(e),c.writeFileSync(i,JSON.stringify({}),`utf-8`),await l(n),a=i}finally{await n()}}if(i?.force){let e=V(a);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await z(a,{stale:!0,retries:i?.force?10:5,retryInterval:(i?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await o();try{let t=await s(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let i=g.join(e,n);try{c.rmSync(i,{force:!0}),H(e)}catch{}}}finally{await t()}},async release(){p(),n.delete(r)}}},dispose(){n.clear()}}},W=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,i=new Set,a,o,s=new Map,l=new Map,u=g.join(e,`index.json`),d=()=>{try{if(!c.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=c.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let a of i)try{a({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let i=g.join(e,n);try{let e=c.statSync(i,{throwIfNoEntry:!1}),a=l.get(n);if(!e){a&&(l.delete(n),f(t,void 0,!1));return}let o=e.mtimeMs,s=a?{locked:a.locked,pid:a.pid}:{locked:!1,pid:void 0};if((r||!a)&&(s=V(i)),!a||a.mtime!==o||a.locked!==s.locked||a.pid!==s.pid){let e;e=!a||a.mtime!==o?JSON.parse(c.readFileSync(i,`utf-8`)):a.cachedValue,l.set(n,{mtime:o,key:t,locked:s.locked,pid:s.pid,cachedValue:e}),f(t,e,s.locked,s.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=s.get(e);i&&clearTimeout(i),s.set(e,setTimeout(()=>{s.delete(e),p(e,t,n)},r))},_=()=>{if(a)return;try{c.mkdirSync(e,{recursive:!0})}catch{}a=c.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),o=setTimeout(t,n)};m(),o=setTimeout(t,n)};return{onChange(e){return i.size===0&&_(),i.add(e),()=>{if(i.delete(e),i.size===0){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),l.clear()}}},dispose(){a&&=(a.close(),void 0),o&&=(clearTimeout(o),void 0);for(let e of s.values())clearTimeout(e);s.clear(),i.clear(),l.clear()}}};async function ae({chatKey:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=oe}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,chat:{key:e}},{signal:r}),l=(0,p.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const oe=e=>{if(e.role!==`assistant`)return!1;let t=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(t+1).filter(p.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>n.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},se=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function ce(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var le=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=ie(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=W(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,messages:(this.chat?.messages??[]).filter(e=>!ce(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessage(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=e;if(this.serializeMessage){let t=this.serializeMessage(e);if(t===void 0)return;n=t}let i=n.id||crypto.randomUUID(),a=n.mode||`run`,o=se(n,a,i),s=t.messages.find(e=>e.id===o.id)?t.messages.map(e=>e.id===o.id?o:e):[...t.messages,o];this.chat={...t,updated_at:new Date().toISOString(),messages:s},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessage(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>t.id!==e),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessage(e){if(this.chat.error=void 0,this.status===`streaming`){this.queue.push(e),this.notifyListeners();return}this.queue=[e],await this.processQueueOrRun()}async start(){await this.processQueueOrRun()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0;let e=new AbortController;this.abortController=e,this.chat.error=void 0;let t;try{t=await this.chatStore.lock(this.chatId);let n=!0;for(;this.queue.length>0||n;){n=!1;let r=this.queue.shift();this.status=`streaming`,this.streamingMessage=void 0,r&&await this.upsertMessage(r,t);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!(0,p.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=await ae({agent:this.agent,chatKey:this.chatId,signal:e.signal,messages:i}),o=async e=>{let n=e;if(this.serializeMessage){let t=this.serializeMessage(e);if(t===void 0)return;n=t}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await t?.set(this.chat)},s=a.getReader();try{for(;;){let{done:t,value:n}=await s.read();if(t||e.signal.aborted)break;this.streamingMessage&&n.id!==this.streamingMessage.id&&await o(this.streamingMessage),this.streamingMessage=this.serializeMessage?this.serializeMessage(n):n,this.notifyListeners()}}finally{s.releaseLock()}this.streamingMessage&&await o(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,t&&(this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),await t.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort(),this.queue.length>0&&setTimeout(()=>{this.processQueueOrRun()},100)}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function ue(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=(0,h.useRef)(null),[s,c]=(0,h.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,h.useEffect)(()=>{o.current&&o.current.dispose();let e=new le({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),(0,h.useEffect)(()=>{o.current&&o.current.setAgent(n)},[n]);let l=(0,h.useCallback)(async e=>{o.current&&await o.current.sendMessage(e)},[]),u=(0,h.useCallback)(async e=>{o.current&&await o.current.upsertMessage(e)},[]),d=(0,h.useCallback)(()=>{o.current&&o.current.stopStreaming()},[]),f=(0,h.useCallback)(async()=>{o.current&&await o.current.resetChat()},[]),p=(0,h.useCallback)(()=>{o.current&&o.current.clearQueue()},[]),m=(0,h.useCallback)(async e=>{o.current&&await o.current.deleteMessage(e)},[]),g=(0,h.useCallback)(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:g}}var de=Object.getOwnPropertyNames,fe=(e,t)=>function(){return t||(0,e[de(e)[0]])((t={exports:{}}).exports,t),t.exports},G=(0,_.createRequire)(require(`url`).pathToFileURL(__filename).href);v.z.object({email:v.z.string().email(),password:v.z.string().min(8)}),v.z.object({email:v.z.string().email(),code:v.z.string()}),v.z.object({email:v.z.string().email(),password:v.z.string().min(8)});var pe=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))}})}},me=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 he(e){}function ge(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=he,onError:n=he,onRetry:r=he,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=K(`${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}
|
|
1
|
+
const e=require(`../chunk-iXuH7AlR.cjs`),t=require(`../index.node-nrQ20r3u.cjs`);require(`../token-error-BoNG8ooW.cjs`),require(`../esm-0UNjvroT.cjs`);const n=require(`../build-BzoNpizh.cjs`);let r=require(`zod/v4`);r=e.__toESM(r),require(`zod/v3`);let i=require(`node:fs`);i=e.__toESM(i);let a=require(`node:stream`);a=e.__toESM(a);let o=require(`node:util`);o=e.__toESM(o);let s=require(`http`);s=e.__toESM(s);let c=require(`path`);c=e.__toESM(c);let l=require(`module`);l=e.__toESM(l);let u=require(`fs`);u=e.__toESM(u);let d=require(`node:process`);d=e.__toESM(d);let f=require(`ai`);f=e.__toESM(f);let p=require(`fs/promises`);p=e.__toESM(p);let m=require(`child_process`);m=e.__toESM(m);let h=require(`react`);h=e.__toESM(h);let g=require(`node:path`);g=e.__toESM(g);let _=require(`node:module`);_=e.__toESM(_);let v=require(`zod`);v=e.__toESM(v);let y=require(`node:readline`);y=e.__toESM(y);let b=require(`node:fs/promises`);b=e.__toESM(b);function x(e){let[n,r]=(0,h.useState)(void 0),[i,a]=(0,h.useState)([]),[o,s]=(0,h.useState)(void 0),[c,l]=(0,h.useState)(e.buildResult),[u,d]=(0,h.useState)(e.env),[f,p]=(0,h.useState)(e.apiServerUrl),[g,_]=(0,h.useState)(void 0);return(0,h.useEffect)(()=>{d(e.env),l(e.buildResult),p(e.apiServerUrl)},[e.env,e.buildResult,e.apiServerUrl]),(0,h.useEffect)(()=>{if(!c||`error`in c){r(void 0),a([]),s(void 0);return}let e=new AbortController,n=!1;return s(void 0),(async()=>{let n=await S(),i=(0,m.spawn)(`node`,[`--no-deprecation`,c.entry],{stdio:`pipe`,env:{...process.env,...u,[t.APIServerURLEnvironmentVariable]:f,PORT:n.toString(),HOST:`127.0.0.1`}});e.signal.addEventListener(`abort`,()=>{try{i.kill()}catch{}});let o=!1;i.stdout.on(`data`,e=>{let t=Buffer.from(e).toString(`utf-8`).trim();!o&&t.startsWith(`Agent server listening on`)||(o||console.log(`stdout: ${t}`),t.length&&a(e=>[...e,{level:`log`,message:t}]))}),i.stderr.on(`data`,e=>{o||console.error(`stderr: ${Buffer.from(e).toString(`utf-8`).trim()}`);let t=Buffer.from(e).toString(`utf-8`).trim();t.length&&a(e=>[...e,{level:`error`,message:t}])}),i.on(`error`,t=>{e.abort(t)}),i.on(`exit`,(t,n)=>{e.abort(`Agent exited with code ${t??`unknown`} and signal ${n??`unknown`}. Be sure to call "blink.agent(...).serve()".`)});let s=new t.Client({baseUrl:`http://127.0.0.1:${n}`});for(;!e.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(e.signal.aborted)throw e.signal.reason;o=!0;let l=await s.capabilities();_(l),r(s)})().catch(e=>{n||s(e instanceof Error?e:Error(String(e)))}),()=>{n=!0,e.abort()}},[c,u,f]),(0,h.useMemo)(()=>({agent:n,logs:i,error:o,capabilities:g}),[n,i,o,g])}async function S(){let e=(0,s.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function C(e){let{directory:t,onBuildStart:r,onBuildSuccess:i,onBuildError:a}=typeof e==`string`?{directory:e}:e,o=(0,h.useMemo)(()=>n.resolveConfig(t),[t]),[s,c]=(0,h.useState)(void 0),[l,u]=(0,h.useState)(void 0),[d,f]=(0,h.useState)(`building`),p=(0,h.useRef)(r),m=(0,h.useRef)(i),g=(0,h.useRef)(a);return(0,h.useEffect)(()=>{p.current=r,m.current=i,g.current=a},[r,i,a]),(0,h.useEffect)(()=>{let e=new AbortController;return o.build({cwd:t,entry:o.entry,outdir:o.outdir,watch:!0,dev:!0,signal:e.signal,onStart:()=>{f(`building`),c(void 0),u(void 0),p.current?.()},onResult:e=>{`error`in e?(c(e.error),f(`error`),g.current?.(e.error)):(u(e),f(`success`),m.current?.(e))}}).catch(e=>{console.log(`error`,e),f(`error`),c(e),g.current?.(e)}),()=>{e.abort()}},[t]),(0,h.useMemo)(()=>({error:s,status:d,result:l,entry:o.entry,outdir:o.outdir}),[s,d,l,o.entry,o.outdir])}function w(){return/[<>:"/\\|?*\u0000-\u001F]|[. ]$/g}function T(){return/^(con|prn|aux|nul|com\d|lpt\d)$/i}const E=100,D=/^\.+(\\|\/)|^\.+$/,O=/[. ]+$/,k=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/gu,A=/[\p{Control}\p{Format}\p{Zl}\p{Zp}\uFFF0-\uFFFF]/u,j=e=>e===``,M=/([<>:"/\\|?*\u0000-\u001F]){2,}/g,N=/[\t\n\r\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000]+/g;let P;function F(){return P??=new Intl.Segmenter(void 0,{granularity:`grapheme`}),P}function ee(e,t={}){if(typeof e!=`string`)throw TypeError(`Expected a string`);let n=t.replacement??`!`;if(w().test(n)||[...n].some(e=>A.test(e)&&!j(e)))throw Error(`Replacement string cannot contain reserved filename characters`);e=e.normalize(`NFC`),e=e.replaceAll(N,` `),n.length>0&&(e=e.replaceAll(M,`$1`)),e=e.replace(O,``),e=e.replace(D,n),e=e.replace(w(),n),e=e.replaceAll(k,e=>j(e)?e:n),e.length===0&&(e=n),e=T().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=I(e,r);else{let n=e.slice(0,t),i=e.slice(t),a=Math.max(0,r-i.length);e=I(n,a)+i}}return e}function I(e,t){if(e.length<=t)return e;let n=0,r=``;for(let{segment:i}of F().segment(e)){let e=n+i.length;if(e>t)break;r+=i,n=e}return r}function L(e){return`${e}.lock`}function R(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function te(e,t={}){let n=L(e),r=process.pid.toString();try{return i.writeFileSync(n,r,{flag:`wx`}),!0}catch(r){if(r.code!==`EEXIST`)throw r;if(t.stale===0)return!1;let a;try{a=parseInt(i.readFileSync(n,`utf8`),10)}catch{return i.unlinkSync(n),te(e,{...t,stale:0})}if(!R(a))try{return i.unlinkSync(n),te(e,{...t,stale:0})}catch(n){if(n.code===`ENOENT`)return te(e,{...t,stale:0});throw n}return!1}}async function z(e,t={}){let n={stale:!0,retries:0,retryInterval:100,...t},r=g.resolve(e),i=0;for(;i<=n.retries;){if(te(r,n))return()=>B(r);i<n.retries&&await new Promise(e=>setTimeout(e,n.retryInterval)),i++}let a=Error(`Lock file is already being held`);throw a.code=`ELOCKED`,a.file=r,a}function B(e){let t=g.resolve(e),n=L(t);try{if(parseInt(i.readFileSync(n,`utf8`),10)!==process.pid){let e=Error(`Lock is not owned by this process`);throw e.code=`ENOTACQUIRED`,e}i.unlinkSync(n)}catch(e){if(e.code===`ENOENT`){let e=Error(`Lock is not acquired`);throw e.code=`ENOTACQUIRED`,e}throw e}}function V(e){let t=g.resolve(e),n=L(t);try{if(!i.existsSync(n))return{locked:!1};let e=i.readFileSync(n,`utf8`),t=parseInt(e,10);return R(t)?{locked:!0,pid:t}:{locked:!1}}catch(e){return e.code,{locked:!1}}}const ne=e=>{i.mkdirSync(e,{recursive:!0})},re=e=>{try{i.fdatasyncSync(e)}catch{}try{i.closeSync(e)}catch{}},H=e=>{try{let t=i.openSync(e,`r`);try{i.fsyncSync(t)}finally{i.closeSync(t)}}catch{}},U=(e,t)=>{let n=g.dirname(e);ne(n);let r=g.join(n,`.tmp-`+process.pid+`-`+Math.random().toString(36).slice(2)),a;try{a=i.openSync(r,`w`),i.writeFileSync(a,t,`utf-8`),re(a),a=void 0,i.renameSync(r,e),H(e),H(n)}catch(e){if(a!==void 0)try{i.closeSync(a)}catch{}try{i.rmSync(r,{force:!0})}catch{}throw e}},ie=(e,t)=>{let n=new Map,r,a=e=>{if(i.statSync(e,{throwIfNoEntry:!1}))return JSON.parse(i.readFileSync(e,`utf-8`))},o=(e,t)=>{U(e,JSON.stringify(t,null,2))},s=async()=>{if(r)throw Error(`Index is already locked`);let t=g.join(e,`index.json`);ne(e),i.existsSync(t)||i.writeFileSync(t,JSON.stringify({ids:{}}),`utf-8`);let n=await z(t,{stale:!0,retries:5,retryInterval:100});return r=()=>Promise.resolve(n()),()=>{n(),r=void 0}},c=async()=>{let t=g.join(e,`index.json`),n=a(t)??{ids:{}};return n.ids||={},n},l=async t=>{let n=g.join(e,`index.json`);o(n,t)},u=async t=>{let n=(await c()).ids[t];if(n)return g.join(e,n)},d=async t=>{let n=(await c()).ids[t];if(!n)return;let r=g.join(e,n);if(i.statSync(r,{throwIfNoEntry:!1}))return JSON.parse(i.readFileSync(r,`utf-8`))},f=async n=>{let r=n[t],i=String(r),a=ee(i,{replacement:`_`})+`.json`,u=await s();try{let t=await c();t.ids[i]=a,t.current=i;let r=g.join(e,a);o(r,n),await l(t)}finally{await u()}};return{async get(e){return await d(e)},async list(){if(!i.statSync(e,{throwIfNoEntry:!1}))return[];let t=await c(),n=[];for(let[r,a]of Object.entries(t.ids)){let t=g.join(e,a),o=i.statSync(t,{throwIfNoEntry:!1});if(!o)continue;let s=V(t);n.push({key:r,locked:s.locked,pid:s.pid,mtime:o.mtimeMs})}return n.sort((e,t)=>t.mtime-e.mtime),n},async lock(r,a){if(n.has(r))throw Error(`Key "${r}" is already locked in this process`);let o=await u(r);if(!o){let t=ee(r,{replacement:`_`})+`.json`,n=await s();try{let n=await c();n.ids[r]=t;let a=g.join(e,t);ne(e),i.writeFileSync(a,JSON.stringify({}),`utf-8`),await l(n),o=a}finally{await n()}}if(a?.force){let e=V(o);if(e.locked&&e.pid&&e.pid!==process.pid)try{process.kill(e.pid,`SIGTERM`),await new Promise(e=>setTimeout(e,100))}catch(t){t.code!==`ESRCH`&&console.warn(`Failed to kill process ${e.pid}:`,t.message)}}let p=await z(o,{stale:!0,retries:a?.force?10:5,retryInterval:(a?.force,100)});return n.set(r,()=>Promise.resolve(p())),{async get(){let e=await d(r);if(!e)throw Error(`Key ${r} not found`);return e},async set(e){await f(e)},async update(e){let n=await d(r);if(!n||!(t in n))throw Error(`Key ${r} not found`);await f({...n,...e})},async delete(){let t=await s();try{let t=await c(),n=t.ids[r];if(n){delete t.ids[r],t.current===r&&(t.current=void 0),await l(t);let a=g.join(e,n);try{i.rmSync(a,{force:!0}),H(e)}catch{}}}finally{await t()}},async release(){p(),n.delete(r)}}},dispose(){n.clear()}}},W=(e,t)=>{let n=t?.pollInterval??200,r=t?.debounce??50,a=new Set,o,s,c=new Map,l=new Map,u=g.join(e,`index.json`),d=()=>{try{if(!i.statSync(u,{throwIfNoEntry:!1}))return{ids:{}};let e=i.readFileSync(u,`utf-8`);return{ids:JSON.parse(e).ids??{}}}catch{return{ids:{}}}},f=(e,t,n,r)=>{for(let i of a)try{i({key:e,value:t,locked:n,pid:r})}catch(e){console.error(`Error in onChange callback:`,e)}},p=(t,n,r=!1)=>{let a=g.join(e,n);try{let e=i.statSync(a,{throwIfNoEntry:!1}),o=l.get(n);if(!e){o&&(l.delete(n),f(t,void 0,!1));return}let s=e.mtimeMs,c=o?{locked:o.locked,pid:o.pid}:{locked:!1,pid:void 0};if((r||!o)&&(c=V(a)),!o||o.mtime!==s||o.locked!==c.locked||o.pid!==c.pid){let e;e=!o||o.mtime!==s?JSON.parse(i.readFileSync(a,`utf-8`)):o.cachedValue,l.set(n,{mtime:s,key:t,locked:c.locked,pid:c.pid,cachedValue:e}),f(t,e,c.locked,c.pid)}}catch{}},m=()=>{try{let e=d(),t=new Set(Object.keys(e.ids));for(let[t,n]of Object.entries(e.ids))p(t,n,!0);for(let[e,n]of l.entries())t.has(n.key)||(l.delete(e),f(n.key,void 0,!1))}catch{}},h=(e,t,n=!1)=>{let i=c.get(e);i&&clearTimeout(i),c.set(e,setTimeout(()=>{c.delete(e),p(e,t,n)},r))},_=()=>{if(o)return;try{i.mkdirSync(e,{recursive:!0})}catch{}o=i.watch(e,(e,t)=>{if(!t||t.startsWith(`.tmp-`))return;if(t===`index.json`){m();return}if(t.endsWith(`.lock`)){let e=t.replace(`.lock`,``),n=d(),r=Object.keys(n.ids).find(t=>n.ids[t]===e);r&&p(r,e,!0);return}let n=d(),r=Object.keys(n.ids).find(e=>n.ids[e]===t);r&&h(r,t,!1)});let t=()=>{m(),s=setTimeout(t,n)};m(),s=setTimeout(t,n)};return{onChange(e){return a.size===0&&_(),a.add(e),()=>{if(a.delete(e),a.size===0){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),l.clear()}}},dispose(){o&&=(o.close(),void 0),s&&=(clearTimeout(s),void 0);for(let e of c.values())clearTimeout(e);c.clear(),a.clear(),l.clear()}}};async function ae({chatKey:e,agent:t,messages:n,signal:r,shouldContinueStreaming:i=oe}){n=[...n];let a=new TransformStream,o=a.writable.getWriter(),s=async()=>{let a;try{let c=await t.chat({messages:n,chat:{key:e}},{signal:r}),l=(0,f.readUIMessageStream)({message:{id:crypto.randomUUID(),role:`assistant`,parts:[],metadata:{}},stream:c,onError:e=>{e instanceof Error&&e.name===`AbortError`||o.abort(e)}});for await(let e of l)o.write(e),a=e;if(a&&i(a)){n.push(a),await s();return}await o.close()}catch(e){if(e?.name===`AbortError`||r?.aborted)return;await o.abort(e)}finally{await o.close()}};return s().catch(e=>{o.abort(e)}),a.readable}const oe=e=>{if(e.role!==`assistant`)return!1;let n=e.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=e.parts.slice(n+1).filter(f.isToolOrDynamicToolUIPart);return r.length===0||r.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`)?!1:r.every(e=>e.state.startsWith(`output-`))},se=(e,t,n=crypto.randomUUID())=>({created_at:new Date().toISOString(),...e,id:n,metadata:e.metadata,mode:t});function ce(e){return typeof e==`object`&&e?.__blink_internal!==void 0}var le=class{chatId;agent;chatStore;serializeMessage;filterMessages;chat;loading=!1;streamingMessage;status=`idle`;queue=[];abortController;isProcessingQueue=!1;listeners=new Set;watcher;disposed=!1;constructor(e){this.chatId=e.chatId,this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.loading=!0,this.chatStore=ie(e.chatsDirectory,`id`),this.serializeMessage=e.serializeMessage,this.filterMessages=e.filterMessages,this.watcher=W(e.chatsDirectory,{pollInterval:1e3,debounce:50}),this.watcher.onChange(e=>{if(e.key!==this.chatId||this.isProcessingQueue)return;if(!e.value){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.status=`idle`,this.streamingMessage=void 0,this.notifyListeners();return}let t=e.value,n=e.value?.error?`error`:`idle`;e.locked&&(n=`streaming`);let r=this.chat.updated_at!==t?.updated_at||this.status!==n;this.chat=t,this.streamingMessage=void 0,this.status=n,r&&this.notifyListeners()}),this.chatStore.get(this.chatId).then(e=>{this.disposed||e&&(this.chat=e)}).catch(e=>{this.chat.error=e instanceof Error?e.message:String(e)}).finally(()=>{this.loading=!1,this.notifyListeners()})}setAgent(e){this.agent=e}getState(){return{id:this.chatId,messages:(this.chat?.messages??[]).filter(e=>!ce(e.metadata)),created_at:this.chat?.created_at,updated_at:this.chat?.updated_at,status:this.status,streamingMessage:this.streamingMessage,error:this.chat?.error,loading:this.loading,queuedMessages:this.queue}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async upsertMessage(e,t){let n=!1,r;t?r=t:(r=await this.chatStore.lock(this.chatId),n=!0);try{let t=await r.get();(!t.id||!Array.isArray(t.messages))&&(t={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]});let n=e;if(this.serializeMessage){let t=this.serializeMessage(e);if(t===void 0)return;n=t}let i=n.id||crypto.randomUUID(),a=n.mode||`run`,o=se(n,a,i),s=t.messages.find(e=>e.id===o.id)?t.messages.map(e=>e.id===o.id?o:e):[...t.messages,o];this.chat={...t,updated_at:new Date().toISOString(),messages:s},await r.set(this.chat),this.notifyListeners()}finally{n&&await r.release()}}async deleteMessage(e){let t;try{t=await this.chatStore.lock(this.chatId);let n=await t.get();this.chat.messages=n.messages.filter(t=>t.id!==e),this.chat.updated_at=new Date().toISOString(),await t.set(this.chat),this.notifyListeners()}finally{t&&await t.release()}}async sendMessage(e){if(this.chat.error=void 0,this.status===`streaming`){this.queue.push(e),this.notifyListeners();return}this.queue=[e],await this.processQueueOrRun()}async start(){await this.processQueueOrRun()}async processQueueOrRun(){if(!this.agent){this.chat.error=`The agent is not available. Please wait for the build to succeed.`,this.status=`error`,this.queue=[],this.notifyListeners();return}if(this.isProcessingQueue)return;this.isProcessingQueue=!0,this.chat.error=void 0;let e;try{e=await this.chatStore.lock(this.chatId);let t=!0;for(;this.queue.length>0||t;){t=!1;let n=new AbortController;this.abortController=n;let r=this.queue.shift();this.streamingMessage=void 0,this.status=`streaming`,this.notifyListeners(),r&&await this.upsertMessage(r,e);let i=this.chat.messages;this.filterMessages&&(i=i.filter(this.filterMessages)),i=i.map(e=>({...e,parts:e.parts.map(e=>!(0,f.isToolOrDynamicToolUIPart)(e)||e.input!==``?e:{...e,input:{}})}));let a=await ae({agent:this.agent,chatKey:this.chatId,signal:n.signal,messages:i}),o=async t=>{let n=t;if(this.serializeMessage){let e=this.serializeMessage(t);if(e===void 0)return;n=e}this.chat.updated_at=new Date().toISOString(),this.chat.messages.push(n),this.streamingMessage=void 0,await e?.set(this.chat)},s=a.getReader();try{for(;;){let{done:e,value:t}=await s.read();if(e||n.signal.aborted)break;this.streamingMessage&&t.id!==this.streamingMessage.id&&await o(this.streamingMessage),this.streamingMessage=this.serializeMessage?this.serializeMessage(t):t,this.notifyListeners()}}finally{s.releaseLock()}this.streamingMessage&&await o(this.streamingMessage)}}catch(e){this.chat.error=e instanceof Error?e.message:String(e)}finally{this.isProcessingQueue=!1,this.streamingMessage=void 0,this.chat.error?this.status=`error`:this.status=`idle`,e&&(this.chat.updated_at=new Date().toISOString(),await e.set(this.chat),await e.release(),this.notifyListeners())}}stopStreaming(){this.abortController?.abort()}clearQueue(){this.queue=[],this.notifyListeners()}async resetChat(){this.abortController?.abort(),this.resetChatState(),this.notifyListeners();let e;try{e=await this.chatStore.lock(this.chatId),await e.delete()}catch{}finally{if(e)try{await e.release()}catch{}}}dispose(){this.disposed=!0,this.watcher.dispose(),this.listeners.clear(),this.abortController?.abort()}resetChatState(){this.chat={id:this.chatId,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),messages:[]},this.streamingMessage=void 0,this.status=`idle`,this.queue=[]}notifyListeners(){let e=this.getState();for(let t of this.listeners)t(e)}};function ue(e){let{chatId:t,agent:n,chatsDirectory:r,serializeMessage:i,filterMessages:a}=e,o=(0,h.useRef)(null),[s,c]=(0,h.useState)({id:t,messages:[],status:`idle`,loading:!0,queuedMessages:[]});(0,h.useEffect)(()=>{o.current&&o.current.dispose();let e=new le({chatId:t,chatsDirectory:r,serializeMessage:i,filterMessages:a}),n=e.subscribe(e=>{c(e)});return c(e.getState()),o.current=e,()=>{n(),e.dispose(),o.current=null}},[t,r]),(0,h.useEffect)(()=>{o.current&&o.current.setAgent(n)},[n]);let l=(0,h.useCallback)(async e=>{o.current&&await o.current.sendMessage(e)},[]),u=(0,h.useCallback)(async e=>{o.current&&await o.current.upsertMessage(e)},[]),d=(0,h.useCallback)(()=>{o.current&&o.current.stopStreaming()},[]),f=(0,h.useCallback)(async()=>{o.current&&await o.current.resetChat()},[]),p=(0,h.useCallback)(()=>{o.current&&o.current.clearQueue()},[]),m=(0,h.useCallback)(async e=>{o.current&&await o.current.deleteMessage(e)},[]),g=(0,h.useCallback)(async()=>{o.current&&await o.current.start()},[]);return{...s,sendMessage:l,upsertMessage:u,stopStreaming:d,resetChat:f,clearQueue:p,deleteMessage:m,start:g}}var de=Object.getOwnPropertyNames,fe=(e,t)=>function(){return t||(0,e[de(e)[0]])((t={exports:{}}).exports,t),t.exports},G=(0,_.createRequire)(require(`url`).pathToFileURL(__filename).href);v.z.object({email:v.z.string().email(),password:v.z.string().min(8)}),v.z.object({email:v.z.string().email(),code:v.z.string()}),v.z.object({email:v.z.string().email(),password:v.z.string().min(8)});var pe=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))}})}},me=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 he(e){}function ge(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=he,onError:n=he,onRetry:r=he,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=K(`${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}
|
|
2
2
|
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new me(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new me(`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(`
|
|
3
3
|
`)?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 K(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
4
4
|
`,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]===`
|
|
@@ -22,7 +22,7 @@ Error message: ${Ce(t)}`,cause:t}),this[Le]=!0,this.value=e}static isInstance(e)
|
|
|
22
22
|
`));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
|
|
23
23
|
`);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}})}),Ut=a.__commonJS({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=Vt(),a=It(),o=Lt(),s=Ht(),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}})}),Wt=a.__commonJS({"../../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=G(`fs`).constants||n}catch{t.exports=n}})}),Gt=a.__commonJS({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=Vt(),a=Lt(),o=Wt(),s=Ht(),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)}})}),Kt=a.__commonJS({"../../node_modules/tar-stream/index.js":(e=>{e.extract=Ut(),e.pack=Gt()})}),qt=a.__toESM(Kt(),1);let Jt=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await o.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=qt.pack(),i=async(e,t=``)=>{let n=await o.readdir(e,{withFileTypes:!0});for(let a of n){let n=`${e}/${a.name}`,s=t?`${t}/${a.name}`:a.name;if(a.isDirectory()){r.entry({name:`${s}/`,type:`directory`}),await i(n,s);continue}if(a.isSymbolicLink?.()){let e=await o.readlink(n);r.entry({name:s,type:`symlink`,linkname:e});continue}if(a.isFile()){let e=await o.stat(n);await new Promise((t,i)=>{let a=(0,u.createReadStream)(n),o=r.entry({name:s,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&i(e)});a.on(`error`,i),a.on(`data`,e=>o.write(e)),a.on(`end`,()=>{o.end(),t()})});continue}}};(async()=>{try{await i(e),r.finalize()}catch(e){r.destroy(e)}})();let a=r,s=0,c=!1;return new ReadableStream({start(e){a.on(`data`,t=>{if(!c){if(s+=t.length,s>n){c=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${s} bytes.`));try{a.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),a.once(`error`,t=>{c||(c=!0,e.error(t instanceof Error?t:Error(String(t))))}),a.once(`end`,()=>{c||(c=!0,e.close())})},cancel(){try{a.destroy()}catch{}}})},Yt=(e,t)=>e.length<=t?e:e.slice(e.length-t),Xt=(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 Zt=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 v({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new yt({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=h.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 a.ClientMessageType.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 a.ClientMessageType.PROXY_INIT:{let t=a.ClientMessageSchema[a.ClientMessageType.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 Pt.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(a.ServerMessageType.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(a.ServerMessageType.PROXY_WEBSOCKET_MESSAGE,a.createWebSocketMessagePayload(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(a.ServerMessageType.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 a.ClientMessageType.PROXY_WEBSOCKET_MESSAGE:{let e=a.parseWebSocketMessagePayload(n,this.decoder);r.send(e);break}case a.ClientMessageType.PROXY_WEBSOCKET_CLOSE:{let e=a.ClientMessageSchema[a.ClientMessageType.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 a.ClientMessageType.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},o;o=this.fetchProxyRequest?await this.fetchProxyRequest(t.url,i):await fetch(t.url,i);let s={};o.headers.forEach((e,t)=>{s[t]=e});let c={headers:s,status_code:o.status,status_message:o.statusText};e.writeTyped(a.ServerMessageType.PROXY_INIT,this.encoder.encode(JSON.stringify(c)));let l=o.headers.get(`content-length`),u=l?parseInt(l):0,d=h.getMaxPayloadSize()-1;if(u>=d){if(!o.body){e.close();return}let t=o.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(d,r.length-t),i=r.subarray(t,t+n);e.writeTyped(a.ServerMessageType.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else o.body&&await o.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(a.ServerMessageType.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=a.RequestSchema[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=Xt(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 Jt(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 c.readFile(t.payload.path),r=await dt(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(`
|
|
24
24
|
`),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(`
|
|
25
|
-
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await c.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await c.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await c.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await c.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(a.ServerMessageType.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([a.ServerMessageType.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=Yt(this.processManager.readANSIOutput(i.pid),64e3),f=Xt(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}};Object.defineProperty(e,`Multiplexer`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`Server`,{enumerable:!0,get:function(){return Zt}})})}),Ln=fe({"node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{Fn(),e.Server=In().Server})}),Rn=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(()=>{f()},t),a=Math.min(i,Math.floor(a*1.5))},c=()=>{a=250},{Server:l}=Ln(),u=new l({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}))}}),d=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{u.handleMessage(new Uint8Array(e.data))}catch(e){console.error(`message handler error`,e);try{t.close(1011)}catch{}}})},f=()=>{if(!r)try{let n=this.client.websocket(`/api/devhook/${e.id}`);t=n,d(n)}catch(t){try{e.onError?.(t)}catch{}s()}};return f(),{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{}}}}};let zn=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}({}),Bn=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}({});zn.REQUEST,v.z.string(),zn.PROXY_INIT,v.z.object({method:v.z.string(),headers:v.z.record(v.z.string(),v.z.string()),url:v.z.string()}),zn.PROXY_BODY,v.z.instanceof(Uint8Array),zn.PROXY_WEBSOCKET_MESSAGE,v.z.object({type:v.z.enum([`text`,`binary`]),data:v.z.instanceof(Uint8Array)}),zn.PROXY_WEBSOCKET_CLOSE,v.z.object({code:v.z.number().optional(),reason:v.z.string().optional()}),Bn.RESPONSE,v.z.string(),Bn.NOTIFICATION,v.z.string(),Bn.PROXY_INIT,v.z.object({status_code:v.z.number(),status_message:v.z.string(),headers:v.z.record(v.z.string(),v.z.string())}),Bn.PROXY_DATA,v.z.instanceof(Uint8Array),Bn.PROXY_WEBSOCKET_MESSAGE,v.z.instanceof(Uint8Array),Bn.PROXY_WEBSOCKET_CLOSE,v.z.object({code:v.z.number(),reason:v.z.string()}),zn.PROXY_INIT,v.z.string(),v.z.record(v.z.string(),v.z.string()),v.z.string(),v.z.object({command:v.z.string(),args:v.z.array(v.z.string()),env:v.z.record(v.z.string(),v.z.string()).optional(),cwd:v.z.string().optional()}),v.z.object({pid:v.z.number(),data:v.z.string()}),v.z.object({pid:v.z.number(),output_idle_timeout_ms:v.z.number().optional(),timeout_ms:v.z.number().optional()}),v.z.object({include_dead:v.z.boolean().optional()}),v.z.object({pid:v.z.number(),start_line:v.z.number().optional(),end_line:v.z.number().optional()}),v.z.object({pid:v.z.number(),signal:v.z.string().optional()}),v.z.object({env:v.z.record(v.z.string(),v.z.string())}),v.z.object({path:v.z.string(),line_start:v.z.number().optional(),line_end:v.z.number().optional()}),v.z.object({path:v.z.string(),content:v.z.string(),base64:v.z.boolean().optional(),mode:v.z.number().optional()}),v.z.object({path:v.z.string()}),v.z.object({path:v.z.string()}),v.z.object({path:v.z.string()});const Vn=v.z.object({pid:v.z.number(),command:v.z.string(),args:v.z.array(v.z.string()),title:v.z.string().optional(),cwd:v.z.string(),env:v.z.record(v.z.string(),v.z.string()),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional(),duration_ms:v.z.number().optional(),output_total_lines:v.z.number()});Vn.extend({ansi_output:v.z.string(),plain_output:v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number()})}),v.z.object({pid:v.z.number()}),v.z.object({}),v.z.object({processes:v.z.array(Vn)}),v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number(),duration_ms:v.z.number(),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional()}),v.z.object({}),v.z.object({}),v.z.object({total_lines:v.z.number(),lines_read:v.z.number(),start_line:v.z.number(),content:v.z.string(),mime_type:v.z.string()}),v.z.object({}),v.z.object({entries:v.z.array(v.z.object({name:v.z.string(),type:v.z.enum([`file`,`directory`,`symlink`])}))}),v.z.object({}),v.z.object({deployment_id:v.z.string()});const Hn=v.z.object({type:v.z.enum([`create`,`update`,`delete`]),path:v.z.string()}),Un=v.z.object({type:v.z.enum([`context`,`added`,`deleted`]),content:v.z.string(),oldLineNumber:v.z.number().optional(),newLineNumber:v.z.number().optional()}),Wn=v.z.object({oldStart:v.z.number(),oldLines:v.z.number(),newStart:v.z.number(),newLines:v.z.number(),lines:v.z.array(Un)}),Gn=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:v.z.string().optional(),insertions:v.z.number(),deletions:v.z.number(),chunks:v.z.array(Wn)}),Kn=v.z.object({totalFiles:v.z.number(),totalInsertions:v.z.number(),totalDeletions:v.z.number(),netChange:v.z.number(),startHash:v.z.string().optional(),currentHash:v.z.string().optional(),timespan:v.z.number(),files:v.z.array(Gn)}),qn=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:v.z.boolean()}),Jn=v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),email:v.z.string(),date:v.z.date(),timestamp:v.z.date(),filesChanged:v.z.number(),insertions:v.z.number(),deletions:v.z.number(),commitDiff:v.z.array(Gn).optional()});v.z.object({files:v.z.array(qn),branch:v.z.string(),ahead:v.z.number(),behind:v.z.number(),timestamp:v.z.date(),sessionDiff:Kn.optional(),workingDirectoryDiff:Kn.optional(),newCommits:v.z.array(Jn),currentCommit:v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),date:v.z.date()}).optional(),diffSkipped:v.z.boolean().optional(),payloadTruncated:v.z.boolean().optional(),estimatedSizeKB:v.z.number().optional()}),v.z.object({debounceDelay:v.z.number().optional(),gitStatusInterval:v.z.number().optional(),ignoreDotfiles:v.z.boolean().optional(),ignored:v.z.array(v.z.string()).optional(),watchGit:v.z.boolean().optional(),includeDiffs:v.z.boolean().optional(),maxDiffFiles:v.z.number().optional(),maxPayloadSizeKB:v.z.number().optional(),truncateLargeDiffs:v.z.boolean().optional()}),v.z.object({status:Vn}),v.z.object({pid:v.z.number(),output:v.z.string()}),v.z.object({changes:v.z.array(Hn)});var Yn=class{constructor({send:e,jwt:t,requestTimeoutMS:n}){this.notificationCallbacks=new Map,this.disposables=[],this.requestHandlers=new Map,this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}};v.z.object({}),v.z.object({id:v.z.string(),token:v.z.string()});var Xn=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await q(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new Yn({send:e=>t.send(e)})}},Zn=class{constructor(e){this.client=e,this.compute=new Xn(this.client)}},Qn=class extends Pn{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new Rn(this),this.tools=new Zn(this)}},$n=e.__commonJSMin((e=>{e.__esModule=!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;return{XDGAppPaths:new(function(){function e(s){s===void 0&&(s={});function c(t){return t===void 0&&(t={}),new e(t)}var l=n(s)?s:{name:s},u=l.suffix??``,d=l.isolated??!0,f=[l.name,i.pkgMainFilename(),i.mainFilename()],p=a.parse((f.find(function(e){return r(e)})??`$eval`)+u).name;c.$name=function(){return p},c.$isolated=function(){return d};function m(e){return e??={isolated:d},t(e)?e:e.isolated??d}function h(e){return m(e)?p:``}return c.cache=function(e){return a.join(o.cache(),h(e))},c.config=function(e){return a.join(o.config(),h(e))},c.data=function(e){return a.join(o.data(),h(e))},c.runtime=function(e){return o.runtime()?a.join(o.runtime(),h(e)):void 0},c.state=function(e){return a.join(o.state(),h(e))},c.configDirs=function(e){return o.configDirs().map(function(t){return a.join(t,h(e))})},c.dataDirs=function(e){return o.dataDirs().map(function(t){return a.join(t,h(e))})},c}return e}())}}e.Adapt=a})),er=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!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(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`.local`,`share`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`.local`,`state`])}}},u=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`Library`,`Caches`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`Library`,`Preferences`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`Library`,`Application Support`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`Library`,`State`])}}},d=function(){function e(){return c(n.get(`APPDATA`),[s(),`AppData`,`Roaming`])}function t(){return c(n.get(`LOCALAPPDATA`),[s(),`AppData`,`Local`])}return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[t(),`xdg.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[e(),`xdg.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[e(),`xdg.data`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[t(),`xdg.state`])}}};return{XDG:new(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}())}}e.Adapt=n})),tr=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!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(){return o?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)}))}():function(){return s((typeof i.homedir==`function`?i.homedir():void 0)||r.get(`HOME`))}()}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`])}].find(function(e){return e&&!n(e())});return a&&s(a())||t}return o?u():l()}return{OSPaths:new(function(){function e(){function t(){return new e}return t.home=c,t.temp=l,t}return e}())}}e.Adapt=r})),nr=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__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};e.__esModule=!0;var i=r(require(`os`)),a=r(require(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:i,path:a,process}})),rr=e.__commonJSMin(((e,t)=>{var n=tr(),r=nr();t.exports=n.Adapt(r.adapter).OSPaths})),ir=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__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},i=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var a=r(require(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:i(rr()).default,path:a,process}})),ar=e.__commonJSMin(((e,t)=>{var n=er(),r=ir();t.exports=n.Adapt(r.adapter).XDG})),or=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__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},i=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var a=r(require(`path`)),o=i(ar());e.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=(typeof require<`u`&&require!==null&&require.main?require.main:{filename:void 0}).filename;return(e===process.execArgv[0]?void 0:e)||(process._eval===void 0?process.argv[1]:void 0)},pkgMainFilename:function(){return process.pkg?process.execPath:void 0}},path:a,process,xdg:o.default}})),sr=e.__commonJSMin(((e,t)=>{var n=$n(),r=or();t.exports=n.Adapt(r.adapter).XDGAppPaths})),cr=e.__toESM(sr(),1),lr=cr.default,ur=e.__commonJSMin(((e,t)=>{t.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}})),dr=e.__commonJSMin(((e,t)=>{let n=ur(),r={};for(let e of Object.keys(n))r[n[e]]=e;let i={rgb:{channels:3,labels:`rgb`},hsl:{channels:3,labels:`hsl`},hsv:{channels:3,labels:`hsv`},hwb:{channels:3,labels:`hwb`},cmyk:{channels:4,labels:`cmyk`},xyz:{channels:3,labels:`xyz`},lab:{channels:3,labels:`lab`},lch:{channels:3,labels:`lch`},hex:{channels:1,labels:[`hex`]},keyword:{channels:1,labels:[`keyword`]},ansi16:{channels:1,labels:[`ansi16`]},ansi256:{channels:1,labels:[`ansi256`]},hcg:{channels:3,labels:[`h`,`c`,`g`]},apple:{channels:3,labels:[`r16`,`g16`,`b16`]},gray:{channels:1,labels:[`gray`]}};t.exports=i;for(let e of Object.keys(i)){if(!(`channels`in i[e]))throw Error(`missing channels property: `+e);if(!(`labels`in i[e]))throw Error(`missing channel labels property: `+e);if(i[e].labels.length!==i[e].channels)throw Error(`channel and label counts mismatch: `+e);let{channels:t,labels:n}=i[e];delete i[e].channels,delete i[e].labels,Object.defineProperty(i[e],`channels`,{value:t}),Object.defineProperty(i[e],`labels`,{value:n})}i.rgb.hsl=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s,c;a===i?s=0:t===a?s=(n-r)/o:n===a?s=2+(r-t)/o:r===a&&(s=4+(t-n)/o),s=Math.min(s*60,360),s<0&&(s+=360);let l=(i+a)/2;return c=a===i?0:l<=.5?o/(a+i):o/(2-a-i),[s,c*100,l*100]},i.rgb.hsv=function(e){let t,n,r,i,a,o=e[0]/255,s=e[1]/255,c=e[2]/255,l=Math.max(o,s,c),u=l-Math.min(o,s,c),d=function(e){return(l-e)/6/u+1/2};return u===0?(i=0,a=0):(a=u/l,t=d(o),n=d(s),r=d(c),o===l?i=r-n:s===l?i=1/3+t-r:c===l&&(i=2/3+n-t),i<0?i+=1:i>1&&--i),[i*360,a*100,l*100]},i.rgb.hwb=function(e){let t=e[0],n=e[1],r=e[2],a=i.rgb.hsl(e)[0],o=1/255*Math.min(t,Math.min(n,r));return r=1-1/255*Math.max(t,Math.max(n,r)),[a,o*100,r*100]},i.rgb.cmyk=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(1-t,1-n,1-r),a=(1-t-i)/(1-i)||0,o=(1-n-i)/(1-i)||0,s=(1-r-i)/(1-i)||0;return[a*100,o*100,s*100,i*100]};function a(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}i.rgb.keyword=function(e){let t=r[e];if(t)return t;let i=1/0,o;for(let t of Object.keys(n)){let r=n[t],s=a(e,r);s<i&&(i=s,o=t)}return o},i.keyword.rgb=function(e){return n[e]},i.rgb.xyz=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92;let i=t*.4124+n*.3576+r*.1805,a=t*.2126+n*.7152+r*.0722,o=t*.0193+n*.1192+r*.9505;return[i*100,a*100,o*100]},i.rgb.lab=function(e){let t=i.rgb.xyz(e),n=t[0],r=t[1],a=t[2];n/=95.047,r/=100,a/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,a=a>.008856?a**(1/3):7.787*a+16/116;let o=116*r-16,s=500*(n-r),c=200*(r-a);return[o,s,c]},i.hsl.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i,a,o;if(n===0)return o=r*255,[o,o,o];i=r<.5?r*(1+n):r+n-r*n;let s=2*r-i,c=[0,0,0];for(let e=0;e<3;e++)a=t+1/3*-(e-1),a<0&&a++,a>1&&a--,o=6*a<1?s+(i-s)*6*a:2*a<1?i:3*a<2?s+(i-s)*(2/3-a)*6:s,c[e]=o*255;return c},i.hsl.hsv=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=n,a=Math.max(r,.01);r*=2,n*=r<=1?r:2-r,i*=a<=1?a:2-a;let o=(r+n)/2,s=r===0?2*i/(a+i):2*n/(r+n);return[t,s*100,o*100]},i.hsv.rgb=function(e){let t=e[0]/60,n=e[1]/100,r=e[2]/100,i=Math.floor(t)%6,a=t-Math.floor(t),o=255*r*(1-n),s=255*r*(1-n*a),c=255*r*(1-n*(1-a));switch(r*=255,i){case 0:return[r,c,o];case 1:return[s,r,o];case 2:return[o,r,c];case 3:return[o,s,r];case 4:return[c,o,r];case 5:return[r,o,s]}},i.hsv.hsl=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=Math.max(r,.01),a,o;o=(2-n)*r;let s=(2-n)*i;return a=n*i,a/=s<=1?s:2-s,a||=0,o/=2,[t,a*100,o*100]},i.hwb.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i=n+r,a;i>1&&(n/=i,r/=i);let o=Math.floor(6*t),s=1-r;a=6*t-o,o&1&&(a=1-a);let c=n+a*(s-n),l,u,d;switch(o){default:case 6:case 0:l=s,u=c,d=n;break;case 1:l=c,u=s,d=n;break;case 2:l=n,u=s,d=c;break;case 3:l=n,u=c,d=s;break;case 4:l=c,u=n,d=s;break;case 5:l=s,u=n,d=c;break}return[l*255,u*255,d*255]},i.cmyk.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i=e[3]/100,a=1-Math.min(1,t*(1-i)+i),o=1-Math.min(1,n*(1-i)+i),s=1-Math.min(1,r*(1-i)+i);return[a*255,o*255,s*255]},i.xyz.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i,a,o;return i=t*3.2406+n*-1.5372+r*-.4986,a=t*-.9689+n*1.8758+r*.0415,o=t*.0557+n*-.204+r*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,i=Math.min(Math.max(0,i),1),a=Math.min(Math.max(0,a),1),o=Math.min(Math.max(0,o),1),[i*255,a*255,o*255]},i.xyz.lab=function(e){let t=e[0],n=e[1],r=e[2];t/=95.047,n/=100,r/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let i=116*n-16,a=500*(t-n),o=200*(n-r);return[i,a,o]},i.lab.xyz=function(e){let t=e[0],n=e[1],r=e[2],i,a,o;a=(t+16)/116,i=n/500+a,o=a-r/200;let s=a**3,c=i**3,l=o**3;return a=s>.008856?s:(a-16/116)/7.787,i=c>.008856?c:(i-16/116)/7.787,o=l>.008856?l:(o-16/116)/7.787,i*=95.047,a*=100,o*=108.883,[i,a,o]},i.lab.lch=function(e){let t=e[0],n=e[1],r=e[2],i;i=Math.atan2(r,n)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(n*n+r*r);return[t,a,i]},i.lch.lab=function(e){let t=e[0],n=e[1],r=e[2]/360*2*Math.PI,i=n*Math.cos(r),a=n*Math.sin(r);return[t,i,a]},i.rgb.ansi16=function(e,t=null){let[n,r,a]=e,o=t===null?i.rgb.hsv(e)[2]:t;if(o=Math.round(o/50),o===0)return 30;let s=30+(Math.round(a/255)<<2|Math.round(r/255)<<1|Math.round(n/255));return o===2&&(s+=60),s},i.hsv.ansi16=function(e){return i.rgb.ansi16(i.hsv.rgb(e),e[2])},i.rgb.ansi256=function(e){let t=e[0],n=e[1],r=e[2];return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},i.ansi16.rgb=function(e){let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let n=(~~(e>50)+1)*.5,r=(t&1)*n*255,i=(t>>1&1)*n*255,a=(t>>2&1)*n*255;return[r,i,a]},i.ansi256.rgb=function(e){if(e>=232){let t=(e-232)*10+8;return[t,t,t]}e-=16;let t,n=Math.floor(e/36)/5*255,r=Math.floor((t=e%36)/6)/5*255,i=t%6/5*255;return[n,r,i]},i.rgb.hex=function(e){let t=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return`000000`.substring(t.length)+t},i.hex.rgb=function(e){let t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let n=t[0];t[0].length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=parseInt(n,16),i=r>>16&255,a=r>>8&255,o=r&255;return[i,a,o]},i.rgb.hcg=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.max(Math.max(t,n),r),a=Math.min(Math.min(t,n),r),o=i-a,s,c;return s=o<1?a/(1-o):0,c=o<=0?0:i===t?(n-r)/o%6:i===n?2+(r-t)/o:4+(t-n)/o,c/=6,c%=1,[c*360,o*100,s*100]},i.hsl.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=n<.5?2*t*n:2*t*(1-n),i=0;return r<1&&(i=(n-.5*r)/(1-r)),[e[0],r*100,i*100]},i.hsv.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=t*n,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.hcg.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100;if(n===0)return[r*255,r*255,r*255];let i=[0,0,0],a=t%1*6,o=a%1,s=1-o,c=0;switch(Math.floor(a)){case 0:i[0]=1,i[1]=o,i[2]=0;break;case 1:i[0]=s,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=o;break;case 3:i[0]=0,i[1]=s,i[2]=1;break;case 4:i[0]=o,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=s}return c=(1-n)*r,[(n*i[0]+c)*255,(n*i[1]+c)*255,(n*i[2]+c)*255]},i.hcg.hsv=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t),i=0;return r>0&&(i=t/r),[e[0],i*100,r*100]},i.hcg.hsl=function(e){let t=e[1]/100,n=e[2]/100*(1-t)+.5*t,r=0;return n>0&&n<.5?r=t/(2*n):n>=.5&&n<1&&(r=t/(2*(1-n))),[e[0],r*100,n*100]},i.hcg.hwb=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t);return[e[0],(r-t)*100,(1-r)*100]},i.hwb.hcg=function(e){let t=e[1]/100,n=1-e[2]/100,r=n-t,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},i.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},i.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},i.gray.hsl=function(e){return[0,0,e[0]]},i.gray.hsv=i.gray.hsl,i.gray.hwb=function(e){return[0,100,e[0]]},i.gray.cmyk=function(e){return[0,0,0,e[0]]},i.gray.lab=function(e){return[e[0],0,0]},i.gray.hex=function(e){let t=Math.round(e[0]/100*255)&255,n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return`000000`.substring(n.length)+n},i.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}})),fr=e.__commonJSMin(((e,t)=>{let n=dr();function r(){let e={},t=Object.keys(n);for(let n=t.length,r=0;r<n;r++)e[t[r]]={distance:-1,parent:null};return e}function i(e){let t=r(),i=[e];for(t[e].distance=0;i.length;){let e=i.pop(),r=Object.keys(n[e]);for(let n=r.length,a=0;a<n;a++){let n=r[a],o=t[n];o.distance===-1&&(o.distance=t[e].distance+1,o.parent=e,i.unshift(n))}}return t}function a(e,t){return function(n){return t(e(n))}}function o(e,t){let r=[t[e].parent,e],i=n[t[e].parent][e],o=t[e].parent;for(;t[o].parent;)r.unshift(t[o].parent),i=a(n[t[o].parent][o],i),o=t[o].parent;return i.conversion=r,i}t.exports=function(e){let t=i(e),n={},r=Object.keys(t);for(let e=r.length,i=0;i<e;i++){let e=r[i];t[e].parent!==null&&(n[e]=o(e,t))}return n}})),pr=e.__commonJSMin(((e,t)=>{let n=dr(),r=fr(),i={},a=Object.keys(n);function o(e){let t=function(...t){let n=t[0];return n==null?n:(n.length>1&&(t=n),e(t))};return`conversion`in e&&(t.conversion=e.conversion),t}function s(e){let t=function(...t){let n=t[0];if(n==null)return n;n.length>1&&(t=n);let r=e(t);if(typeof r==`object`)for(let e=r.length,t=0;t<e;t++)r[t]=Math.round(r[t]);return r};return`conversion`in e&&(t.conversion=e.conversion),t}a.forEach(e=>{i[e]={},Object.defineProperty(i[e],`channels`,{value:n[e].channels}),Object.defineProperty(i[e],`labels`,{value:n[e].labels});let t=r(e);Object.keys(t).forEach(n=>{let r=t[n];i[e][n]=s(r),i[e][n].raw=o(r)})}),t.exports=i})),mr=e.__commonJSMin(((e,t)=>{let n=(e,t)=>(...n)=>`\u001B[${e(...n)+t}m`,r=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};5;${r}m`},i=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};2;${r[0]};${r[1]};${r[2]}m`},a=e=>e,o=(e,t,n)=>[e,t,n],s=(e,t,n)=>{Object.defineProperty(e,t,{get:()=>{let r=n();return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0}),r},enumerable:!0,configurable:!0})},c,l=(e,t,n,r)=>{c===void 0&&(c=pr());let i=r?10:0,a={};for(let[r,o]of Object.entries(c)){let s=r===`ansi16`?`ansi`:r;r===t?a[s]=e(n,i):typeof o==`object`&&(a[s]=e(o[t],i))}return a};function u(){let e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],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],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],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[n,r]of Object.entries(t)){for(let[n,i]of Object.entries(r))t[n]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[n]=t[n],e.set(i[0],i[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,`codes`,{value:e,enumerable:!1}),t.color.close=`\x1B[39m`,t.bgColor.close=`\x1B[49m`,s(t.color,`ansi`,()=>l(n,`ansi16`,a,!1)),s(t.color,`ansi256`,()=>l(r,`ansi256`,a,!1)),s(t.color,`ansi16m`,()=>l(i,`rgb`,o,!1)),s(t.bgColor,`ansi`,()=>l(n,`ansi16`,a,!0)),s(t.bgColor,`ansi256`,()=>l(r,`ansi256`,a,!0)),s(t.bgColor,`ansi16m`,()=>l(i,`rgb`,o,!0)),t}Object.defineProperty(t,`exports`,{enumerable:!0,get:u})})),hr=e.__commonJSMin(((e,t)=>{let r=require(`os`),i=require(`tty`),a=n.require_has_flag(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:n;if(`TEAMCITY_VERSION`in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:n}function u(e){let t=l(e,e&&e.isTTY);return c(t)}t.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),gr=e.__commonJSMin(((e,t)=>{t.exports={stringReplaceAll:(e,t,n)=>{let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.substr(a,r-a)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.substr(a),o},stringEncaseCRLFWithFirstIndex:(e,t,n,r)=>{let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.substr(i,(o?r-1:r)-i)+t+(o?`\r
|
|
25
|
+
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await c.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await c.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await c.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await c.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(a.ServerMessageType.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([a.ServerMessageType.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=Yt(this.processManager.readANSIOutput(i.pid),64e3),f=Xt(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}};Object.defineProperty(e,`Multiplexer`,{enumerable:!0,get:function(){return v}}),Object.defineProperty(e,`Server`,{enumerable:!0,get:function(){return Zt}})})}),Ln=fe({"node_modules/@blink-sdk/compute-protocol/dist/server.cjs":(e=>{Fn(),e.Server=In().Server})}),Rn=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(()=>{f()},t),a=Math.min(i,Math.floor(a*1.5))},c=()=>{a=250},{Server:l}=Ln(),u=new l({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}))}}),d=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{u.handleMessage(new Uint8Array(e.data))}catch(e){console.error(`message handler error`,e);try{t.close(1011)}catch{}}})},f=()=>{if(!r)try{let n=this.client.websocket(`/api/devhook/${e.id}`);t=n,d(n)}catch(t){try{e.onError?.(t)}catch{}s()}};return f(),{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{}}}}};let zn=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}({}),Bn=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}({});zn.REQUEST,v.z.string(),zn.PROXY_INIT,v.z.object({method:v.z.string(),headers:v.z.record(v.z.string(),v.z.string()),url:v.z.string()}),zn.PROXY_BODY,v.z.instanceof(Uint8Array),zn.PROXY_WEBSOCKET_MESSAGE,v.z.object({type:v.z.enum([`text`,`binary`]),data:v.z.instanceof(Uint8Array)}),zn.PROXY_WEBSOCKET_CLOSE,v.z.object({code:v.z.number().optional(),reason:v.z.string().optional()}),Bn.RESPONSE,v.z.string(),Bn.NOTIFICATION,v.z.string(),Bn.PROXY_INIT,v.z.object({status_code:v.z.number(),status_message:v.z.string(),headers:v.z.record(v.z.string(),v.z.string())}),Bn.PROXY_DATA,v.z.instanceof(Uint8Array),Bn.PROXY_WEBSOCKET_MESSAGE,v.z.instanceof(Uint8Array),Bn.PROXY_WEBSOCKET_CLOSE,v.z.object({code:v.z.number(),reason:v.z.string()}),zn.PROXY_INIT,v.z.string(),v.z.record(v.z.string(),v.z.string()),v.z.string(),v.z.object({command:v.z.string(),args:v.z.array(v.z.string()),env:v.z.record(v.z.string(),v.z.string()).optional(),cwd:v.z.string().optional()}),v.z.object({pid:v.z.number(),data:v.z.string()}),v.z.object({pid:v.z.number(),output_idle_timeout_ms:v.z.number().optional(),timeout_ms:v.z.number().optional()}),v.z.object({include_dead:v.z.boolean().optional()}),v.z.object({pid:v.z.number(),start_line:v.z.number().optional(),end_line:v.z.number().optional()}),v.z.object({pid:v.z.number(),signal:v.z.string().optional()}),v.z.object({env:v.z.record(v.z.string(),v.z.string())}),v.z.object({path:v.z.string(),line_start:v.z.number().optional(),line_end:v.z.number().optional()}),v.z.object({path:v.z.string(),content:v.z.string(),base64:v.z.boolean().optional(),mode:v.z.number().optional()}),v.z.object({path:v.z.string()}),v.z.object({path:v.z.string()}),v.z.object({path:v.z.string()});const Vn=v.z.object({pid:v.z.number(),command:v.z.string(),args:v.z.array(v.z.string()),title:v.z.string().optional(),cwd:v.z.string(),env:v.z.record(v.z.string(),v.z.string()),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional(),duration_ms:v.z.number().optional(),output_total_lines:v.z.number()});Vn.extend({ansi_output:v.z.string(),plain_output:v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number()})}),v.z.object({pid:v.z.number()}),v.z.object({}),v.z.object({processes:v.z.array(Vn)}),v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number(),duration_ms:v.z.number(),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional()}),v.z.object({}),v.z.object({}),v.z.object({total_lines:v.z.number(),lines_read:v.z.number(),start_line:v.z.number(),content:v.z.string(),mime_type:v.z.string()}),v.z.object({}),v.z.object({entries:v.z.array(v.z.object({name:v.z.string(),type:v.z.enum([`file`,`directory`,`symlink`])}))}),v.z.object({}),v.z.object({deployment_id:v.z.string()});const Hn=v.z.object({type:v.z.enum([`create`,`update`,`delete`]),path:v.z.string()}),Un=v.z.object({type:v.z.enum([`context`,`added`,`deleted`]),content:v.z.string(),oldLineNumber:v.z.number().optional(),newLineNumber:v.z.number().optional()}),Wn=v.z.object({oldStart:v.z.number(),oldLines:v.z.number(),newStart:v.z.number(),newLines:v.z.number(),lines:v.z.array(Un)}),Gn=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:v.z.string().optional(),insertions:v.z.number(),deletions:v.z.number(),chunks:v.z.array(Wn)}),Kn=v.z.object({totalFiles:v.z.number(),totalInsertions:v.z.number(),totalDeletions:v.z.number(),netChange:v.z.number(),startHash:v.z.string().optional(),currentHash:v.z.string().optional(),timespan:v.z.number(),files:v.z.array(Gn)}),qn=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:v.z.boolean()}),Jn=v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),email:v.z.string(),date:v.z.date(),timestamp:v.z.date(),filesChanged:v.z.number(),insertions:v.z.number(),deletions:v.z.number(),commitDiff:v.z.array(Gn).optional()});v.z.object({files:v.z.array(qn),branch:v.z.string(),ahead:v.z.number(),behind:v.z.number(),timestamp:v.z.date(),sessionDiff:Kn.optional(),workingDirectoryDiff:Kn.optional(),newCommits:v.z.array(Jn),currentCommit:v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),date:v.z.date()}).optional(),diffSkipped:v.z.boolean().optional(),payloadTruncated:v.z.boolean().optional(),estimatedSizeKB:v.z.number().optional()}),v.z.object({debounceDelay:v.z.number().optional(),gitStatusInterval:v.z.number().optional(),ignoreDotfiles:v.z.boolean().optional(),ignored:v.z.array(v.z.string()).optional(),watchGit:v.z.boolean().optional(),includeDiffs:v.z.boolean().optional(),maxDiffFiles:v.z.number().optional(),maxPayloadSizeKB:v.z.number().optional(),truncateLargeDiffs:v.z.boolean().optional()}),v.z.object({status:Vn}),v.z.object({pid:v.z.number(),output:v.z.string()}),v.z.object({changes:v.z.array(Hn)});var Yn=class{constructor({send:e,jwt:t,requestTimeoutMS:n}){this.notificationCallbacks=new Map,this.disposables=[],this.requestHandlers=new Map,this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}};v.z.object({}),v.z.object({id:v.z.string(),token:v.z.string()});var Xn=class{constructor(e){this.client=e}async token(){let e=await this.client.request(`POST`,`/api/tools/compute`);return await q(e,201),e.json()}async connect(e){let t=this.client.websocket(`/api/tools/compute/connect?id=${e}`);return new Yn({send:e=>t.send(e)})}},Zn=class{constructor(e){this.client=e,this.compute=new Xn(this.client)}},Qn=class extends Pn{constructor(e){super({...e,baseURL:e?.baseURL??process.env.BLINK_API_URL}),this.devhook=new Rn(this),this.tools=new Zn(this)}},$n=e.__commonJSMin((e=>{e.__esModule=!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;return{XDGAppPaths:new(function(){function e(s){s===void 0&&(s={});function c(t){return t===void 0&&(t={}),new e(t)}var l=n(s)?s:{name:s},u=l.suffix??``,d=l.isolated??!0,f=[l.name,i.pkgMainFilename(),i.mainFilename()],p=a.parse((f.find(function(e){return r(e)})??`$eval`)+u).name;c.$name=function(){return p},c.$isolated=function(){return d};function m(e){return e??={isolated:d},t(e)?e:e.isolated??d}function h(e){return m(e)?p:``}return c.cache=function(e){return a.join(o.cache(),h(e))},c.config=function(e){return a.join(o.config(),h(e))},c.data=function(e){return a.join(o.data(),h(e))},c.runtime=function(e){return o.runtime()?a.join(o.runtime(),h(e)):void 0},c.state=function(e){return a.join(o.state(),h(e))},c.configDirs=function(e){return o.configDirs().map(function(t){return a.join(t,h(e))})},c.dataDirs=function(e){return o.dataDirs().map(function(t){return a.join(t,h(e))})},c}return e}())}}e.Adapt=a})),er=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!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(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`.local`,`share`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`.local`,`state`])}}},u=function(){return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[s(),`Library`,`Caches`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[s(),`Library`,`Preferences`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[s(),`Library`,`Application Support`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[s(),`Library`,`State`])}}},d=function(){function e(){return c(n.get(`APPDATA`),[s(),`AppData`,`Roaming`])}function t(){return c(n.get(`LOCALAPPDATA`),[s(),`AppData`,`Local`])}return{cache:function(){return c(n.get(`XDG_CACHE_HOME`),[t(),`xdg.cache`])},config:function(){return c(n.get(`XDG_CONFIG_HOME`),[e(),`xdg.config`])},data:function(){return c(n.get(`XDG_DATA_HOME`),[e(),`xdg.data`])},runtime:function(){return n.get(`XDG_RUNTIME_DIR`)||void 0},state:function(){return c(n.get(`XDG_STATE_HOME`),[t(),`xdg.state`])}}};return{XDG:new(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}())}}e.Adapt=n})),tr=e.__commonJSMin((e=>{var t=e&&e.__spreadArray||function(e,t){for(var n=0,r=t.length,i=e.length;n<r;n++,i++)e[i]=t[n];return e};e.__esModule=!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(){return o?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)}))}():function(){return s((typeof i.homedir==`function`?i.homedir():void 0)||r.get(`HOME`))}()}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`])}].find(function(e){return e&&!n(e())});return a&&s(a())||t}return o?u():l()}return{OSPaths:new(function(){function e(){function t(){return new e}return t.home=c,t.temp=l,t}return e}())}}e.Adapt=r})),nr=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__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};e.__esModule=!0;var i=r(require(`os`)),a=r(require(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},os:i,path:a,process}})),rr=e.__commonJSMin(((e,t)=>{var n=tr(),r=nr();t.exports=n.Adapt(r.adapter).OSPaths})),ir=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__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},i=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var a=r(require(`path`));e.adapter={atImportPermissions:{env:!0},env:{get:function(e){return process.env[e]}},osPaths:i(rr()).default,path:a,process}})),ar=e.__commonJSMin(((e,t)=>{var n=er(),r=ir();t.exports=n.Adapt(r.adapter).XDG})),or=e.__commonJSMin((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[n]}})}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,`default`,{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__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},i=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};e.__esModule=!0;var a=r(require(`path`)),o=i(ar());e.adapter={atImportPermissions:{env:!0,read:!0},meta:{mainFilename:function(){var e=(typeof require<`u`&&require!==null&&require.main?require.main:{filename:void 0}).filename;return(e===process.execArgv[0]?void 0:e)||(process._eval===void 0?process.argv[1]:void 0)},pkgMainFilename:function(){return process.pkg?process.execPath:void 0}},path:a,process,xdg:o.default}})),sr=e.__commonJSMin(((e,t)=>{var n=$n(),r=or();t.exports=n.Adapt(r.adapter).XDGAppPaths})),cr=e.__toESM(sr(),1),lr=cr.default,ur=e.__commonJSMin(((e,t)=>{t.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}})),dr=e.__commonJSMin(((e,t)=>{let n=ur(),r={};for(let e of Object.keys(n))r[n[e]]=e;let i={rgb:{channels:3,labels:`rgb`},hsl:{channels:3,labels:`hsl`},hsv:{channels:3,labels:`hsv`},hwb:{channels:3,labels:`hwb`},cmyk:{channels:4,labels:`cmyk`},xyz:{channels:3,labels:`xyz`},lab:{channels:3,labels:`lab`},lch:{channels:3,labels:`lch`},hex:{channels:1,labels:[`hex`]},keyword:{channels:1,labels:[`keyword`]},ansi16:{channels:1,labels:[`ansi16`]},ansi256:{channels:1,labels:[`ansi256`]},hcg:{channels:3,labels:[`h`,`c`,`g`]},apple:{channels:3,labels:[`r16`,`g16`,`b16`]},gray:{channels:1,labels:[`gray`]}};t.exports=i;for(let e of Object.keys(i)){if(!(`channels`in i[e]))throw Error(`missing channels property: `+e);if(!(`labels`in i[e]))throw Error(`missing channel labels property: `+e);if(i[e].labels.length!==i[e].channels)throw Error(`channel and label counts mismatch: `+e);let{channels:t,labels:n}=i[e];delete i[e].channels,delete i[e].labels,Object.defineProperty(i[e],`channels`,{value:t}),Object.defineProperty(i[e],`labels`,{value:n})}i.rgb.hsl=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s,c;a===i?s=0:t===a?s=(n-r)/o:n===a?s=2+(r-t)/o:r===a&&(s=4+(t-n)/o),s=Math.min(s*60,360),s<0&&(s+=360);let l=(i+a)/2;return c=a===i?0:l<=.5?o/(a+i):o/(2-a-i),[s,c*100,l*100]},i.rgb.hsv=function(e){let t,n,r,i,a,o=e[0]/255,s=e[1]/255,c=e[2]/255,l=Math.max(o,s,c),u=l-Math.min(o,s,c),d=function(e){return(l-e)/6/u+1/2};return u===0?(i=0,a=0):(a=u/l,t=d(o),n=d(s),r=d(c),o===l?i=r-n:s===l?i=1/3+t-r:c===l&&(i=2/3+n-t),i<0?i+=1:i>1&&--i),[i*360,a*100,l*100]},i.rgb.hwb=function(e){let t=e[0],n=e[1],r=e[2],a=i.rgb.hsl(e)[0],o=1/255*Math.min(t,Math.min(n,r));return r=1-1/255*Math.max(t,Math.max(n,r)),[a,o*100,r*100]},i.rgb.cmyk=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(1-t,1-n,1-r),a=(1-t-i)/(1-i)||0,o=(1-n-i)/(1-i)||0,s=(1-r-i)/(1-i)||0;return[a*100,o*100,s*100,i*100]};function a(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}i.rgb.keyword=function(e){let t=r[e];if(t)return t;let i=1/0,o;for(let t of Object.keys(n)){let r=n[t],s=a(e,r);s<i&&(i=s,o=t)}return o},i.keyword.rgb=function(e){return n[e]},i.rgb.xyz=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,n=n>.04045?((n+.055)/1.055)**2.4:n/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92;let i=t*.4124+n*.3576+r*.1805,a=t*.2126+n*.7152+r*.0722,o=t*.0193+n*.1192+r*.9505;return[i*100,a*100,o*100]},i.rgb.lab=function(e){let t=i.rgb.xyz(e),n=t[0],r=t[1],a=t[2];n/=95.047,r/=100,a/=108.883,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,a=a>.008856?a**(1/3):7.787*a+16/116;let o=116*r-16,s=500*(n-r),c=200*(r-a);return[o,s,c]},i.hsl.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i,a,o;if(n===0)return o=r*255,[o,o,o];i=r<.5?r*(1+n):r+n-r*n;let s=2*r-i,c=[0,0,0];for(let e=0;e<3;e++)a=t+1/3*-(e-1),a<0&&a++,a>1&&a--,o=6*a<1?s+(i-s)*6*a:2*a<1?i:3*a<2?s+(i-s)*(2/3-a)*6:s,c[e]=o*255;return c},i.hsl.hsv=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=n,a=Math.max(r,.01);r*=2,n*=r<=1?r:2-r,i*=a<=1?a:2-a;let o=(r+n)/2,s=r===0?2*i/(a+i):2*n/(r+n);return[t,s*100,o*100]},i.hsv.rgb=function(e){let t=e[0]/60,n=e[1]/100,r=e[2]/100,i=Math.floor(t)%6,a=t-Math.floor(t),o=255*r*(1-n),s=255*r*(1-n*a),c=255*r*(1-n*(1-a));switch(r*=255,i){case 0:return[r,c,o];case 1:return[s,r,o];case 2:return[o,r,c];case 3:return[o,s,r];case 4:return[c,o,r];case 5:return[r,o,s]}},i.hsv.hsl=function(e){let t=e[0],n=e[1]/100,r=e[2]/100,i=Math.max(r,.01),a,o;o=(2-n)*r;let s=(2-n)*i;return a=n*i,a/=s<=1?s:2-s,a||=0,o/=2,[t,a*100,o*100]},i.hwb.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100,i=n+r,a;i>1&&(n/=i,r/=i);let o=Math.floor(6*t),s=1-r;a=6*t-o,o&1&&(a=1-a);let c=n+a*(s-n),l,u,d;switch(o){default:case 6:case 0:l=s,u=c,d=n;break;case 1:l=c,u=s,d=n;break;case 2:l=n,u=s,d=c;break;case 3:l=n,u=c,d=s;break;case 4:l=c,u=n,d=s;break;case 5:l=s,u=n,d=c;break}return[l*255,u*255,d*255]},i.cmyk.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i=e[3]/100,a=1-Math.min(1,t*(1-i)+i),o=1-Math.min(1,n*(1-i)+i),s=1-Math.min(1,r*(1-i)+i);return[a*255,o*255,s*255]},i.xyz.rgb=function(e){let t=e[0]/100,n=e[1]/100,r=e[2]/100,i,a,o;return i=t*3.2406+n*-1.5372+r*-.4986,a=t*-.9689+n*1.8758+r*.0415,o=t*.0557+n*-.204+r*1.057,i=i>.0031308?1.055*i**(1/2.4)-.055:i*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,o=o>.0031308?1.055*o**(1/2.4)-.055:o*12.92,i=Math.min(Math.max(0,i),1),a=Math.min(Math.max(0,a),1),o=Math.min(Math.max(0,o),1),[i*255,a*255,o*255]},i.xyz.lab=function(e){let t=e[0],n=e[1],r=e[2];t/=95.047,n/=100,r/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,n=n>.008856?n**(1/3):7.787*n+16/116,r=r>.008856?r**(1/3):7.787*r+16/116;let i=116*n-16,a=500*(t-n),o=200*(n-r);return[i,a,o]},i.lab.xyz=function(e){let t=e[0],n=e[1],r=e[2],i,a,o;a=(t+16)/116,i=n/500+a,o=a-r/200;let s=a**3,c=i**3,l=o**3;return a=s>.008856?s:(a-16/116)/7.787,i=c>.008856?c:(i-16/116)/7.787,o=l>.008856?l:(o-16/116)/7.787,i*=95.047,a*=100,o*=108.883,[i,a,o]},i.lab.lch=function(e){let t=e[0],n=e[1],r=e[2],i;i=Math.atan2(r,n)*360/2/Math.PI,i<0&&(i+=360);let a=Math.sqrt(n*n+r*r);return[t,a,i]},i.lch.lab=function(e){let t=e[0],n=e[1],r=e[2]/360*2*Math.PI,i=n*Math.cos(r),a=n*Math.sin(r);return[t,i,a]},i.rgb.ansi16=function(e,t=null){let[n,r,a]=e,o=t===null?i.rgb.hsv(e)[2]:t;if(o=Math.round(o/50),o===0)return 30;let s=30+(Math.round(a/255)<<2|Math.round(r/255)<<1|Math.round(n/255));return o===2&&(s+=60),s},i.hsv.ansi16=function(e){return i.rgb.ansi16(i.hsv.rgb(e),e[2])},i.rgb.ansi256=function(e){let t=e[0],n=e[1],r=e[2];return t===n&&n===r?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(r/255*5)},i.ansi16.rgb=function(e){let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];let n=(~~(e>50)+1)*.5,r=(t&1)*n*255,i=(t>>1&1)*n*255,a=(t>>2&1)*n*255;return[r,i,a]},i.ansi256.rgb=function(e){if(e>=232){let t=(e-232)*10+8;return[t,t,t]}e-=16;let t,n=Math.floor(e/36)/5*255,r=Math.floor((t=e%36)/6)/5*255,i=t%6/5*255;return[n,r,i]},i.rgb.hex=function(e){let t=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return`000000`.substring(t.length)+t},i.hex.rgb=function(e){let t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let n=t[0];t[0].length===3&&(n=n.split(``).map(e=>e+e).join(``));let r=parseInt(n,16),i=r>>16&255,a=r>>8&255,o=r&255;return[i,a,o]},i.rgb.hcg=function(e){let t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.max(Math.max(t,n),r),a=Math.min(Math.min(t,n),r),o=i-a,s,c;return s=o<1?a/(1-o):0,c=o<=0?0:i===t?(n-r)/o%6:i===n?2+(r-t)/o:4+(t-n)/o,c/=6,c%=1,[c*360,o*100,s*100]},i.hsl.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=n<.5?2*t*n:2*t*(1-n),i=0;return r<1&&(i=(n-.5*r)/(1-r)),[e[0],r*100,i*100]},i.hsv.hcg=function(e){let t=e[1]/100,n=e[2]/100,r=t*n,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.hcg.rgb=function(e){let t=e[0]/360,n=e[1]/100,r=e[2]/100;if(n===0)return[r*255,r*255,r*255];let i=[0,0,0],a=t%1*6,o=a%1,s=1-o,c=0;switch(Math.floor(a)){case 0:i[0]=1,i[1]=o,i[2]=0;break;case 1:i[0]=s,i[1]=1,i[2]=0;break;case 2:i[0]=0,i[1]=1,i[2]=o;break;case 3:i[0]=0,i[1]=s,i[2]=1;break;case 4:i[0]=o,i[1]=0,i[2]=1;break;default:i[0]=1,i[1]=0,i[2]=s}return c=(1-n)*r,[(n*i[0]+c)*255,(n*i[1]+c)*255,(n*i[2]+c)*255]},i.hcg.hsv=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t),i=0;return r>0&&(i=t/r),[e[0],i*100,r*100]},i.hcg.hsl=function(e){let t=e[1]/100,n=e[2]/100*(1-t)+.5*t,r=0;return n>0&&n<.5?r=t/(2*n):n>=.5&&n<1&&(r=t/(2*(1-n))),[e[0],r*100,n*100]},i.hcg.hwb=function(e){let t=e[1]/100,n=e[2]/100,r=t+n*(1-t);return[e[0],(r-t)*100,(1-r)*100]},i.hwb.hcg=function(e){let t=e[1]/100,n=1-e[2]/100,r=n-t,i=0;return r<1&&(i=(n-r)/(1-r)),[e[0],r*100,i*100]},i.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},i.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},i.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},i.gray.hsl=function(e){return[0,0,e[0]]},i.gray.hsv=i.gray.hsl,i.gray.hwb=function(e){return[0,100,e[0]]},i.gray.cmyk=function(e){return[0,0,0,e[0]]},i.gray.lab=function(e){return[e[0],0,0]},i.gray.hex=function(e){let t=Math.round(e[0]/100*255)&255,n=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return`000000`.substring(n.length)+n},i.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}})),fr=e.__commonJSMin(((e,t)=>{let n=dr();function r(){let e={},t=Object.keys(n);for(let n=t.length,r=0;r<n;r++)e[t[r]]={distance:-1,parent:null};return e}function i(e){let t=r(),i=[e];for(t[e].distance=0;i.length;){let e=i.pop(),r=Object.keys(n[e]);for(let n=r.length,a=0;a<n;a++){let n=r[a],o=t[n];o.distance===-1&&(o.distance=t[e].distance+1,o.parent=e,i.unshift(n))}}return t}function a(e,t){return function(n){return t(e(n))}}function o(e,t){let r=[t[e].parent,e],i=n[t[e].parent][e],o=t[e].parent;for(;t[o].parent;)r.unshift(t[o].parent),i=a(n[t[o].parent][o],i),o=t[o].parent;return i.conversion=r,i}t.exports=function(e){let t=i(e),n={},r=Object.keys(t);for(let e=r.length,i=0;i<e;i++){let e=r[i];t[e].parent!==null&&(n[e]=o(e,t))}return n}})),pr=e.__commonJSMin(((e,t)=>{let n=dr(),r=fr(),i={},a=Object.keys(n);function o(e){let t=function(...t){let n=t[0];return n==null?n:(n.length>1&&(t=n),e(t))};return`conversion`in e&&(t.conversion=e.conversion),t}function s(e){let t=function(...t){let n=t[0];if(n==null)return n;n.length>1&&(t=n);let r=e(t);if(typeof r==`object`)for(let e=r.length,t=0;t<e;t++)r[t]=Math.round(r[t]);return r};return`conversion`in e&&(t.conversion=e.conversion),t}a.forEach(e=>{i[e]={},Object.defineProperty(i[e],`channels`,{value:n[e].channels}),Object.defineProperty(i[e],`labels`,{value:n[e].labels});let t=r(e);Object.keys(t).forEach(n=>{let r=t[n];i[e][n]=s(r),i[e][n].raw=o(r)})}),t.exports=i})),mr=e.__commonJSMin(((e,t)=>{let n=(e,t)=>(...n)=>`\u001B[${e(...n)+t}m`,r=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};5;${r}m`},i=(e,t)=>(...n)=>{let r=e(...n);return`\u001B[${38+t};2;${r[0]};${r[1]};${r[2]}m`},a=e=>e,o=(e,t,n)=>[e,t,n],s=(e,t,n)=>{Object.defineProperty(e,t,{get:()=>{let r=n();return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0}),r},enumerable:!0,configurable:!0})},c,l=(e,t,n,r)=>{c===void 0&&(c=pr());let i=r?10:0,a={};for(let[r,o]of Object.entries(c)){let s=r===`ansi16`?`ansi`:r;r===t?a[s]=e(n,i):typeof o==`object`&&(a[s]=e(o[t],i))}return a};function u(){let e=new Map,t={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],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],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],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};t.color.gray=t.color.blackBright,t.bgColor.bgGray=t.bgColor.bgBlackBright,t.color.grey=t.color.blackBright,t.bgColor.bgGrey=t.bgColor.bgBlackBright;for(let[n,r]of Object.entries(t)){for(let[n,i]of Object.entries(r))t[n]={open:`\u001B[${i[0]}m`,close:`\u001B[${i[1]}m`},r[n]=t[n],e.set(i[0],i[1]);Object.defineProperty(t,n,{value:r,enumerable:!1})}return Object.defineProperty(t,`codes`,{value:e,enumerable:!1}),t.color.close=`\x1B[39m`,t.bgColor.close=`\x1B[49m`,s(t.color,`ansi`,()=>l(n,`ansi16`,a,!1)),s(t.color,`ansi256`,()=>l(r,`ansi256`,a,!1)),s(t.color,`ansi16m`,()=>l(i,`rgb`,o,!1)),s(t.bgColor,`ansi`,()=>l(n,`ansi16`,a,!0)),s(t.bgColor,`ansi256`,()=>l(r,`ansi256`,a,!0)),s(t.bgColor,`ansi16m`,()=>l(i,`rgb`,o,!0)),t}Object.defineProperty(t,`exports`,{enumerable:!0,get:u})})),hr=e.__commonJSMin(((e,n)=>{let r=require(`os`),i=require(`tty`),a=t.require_has_flag(),{env:o}=process,s;a(`no-color`)||a(`no-colors`)||a(`color=false`)||a(`color=never`)?s=0:(a(`color`)||a(`colors`)||a(`color=true`)||a(`color=always`))&&(s=1),`FORCE_COLOR`in o&&(s=o.FORCE_COLOR===`true`?1:o.FORCE_COLOR===`false`?0:o.FORCE_COLOR.length===0?1:Math.min(parseInt(o.FORCE_COLOR,10),3));function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(s===0)return 0;if(a(`color=16m`)||a(`color=full`)||a(`color=truecolor`))return 3;if(a(`color=256`))return 2;if(e&&!t&&s===void 0)return 0;let n=s||0;if(o.TERM===`dumb`)return n;if(process.platform===`win32`){let e=r.release().split(`.`);return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if(`CI`in o)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(e=>e in o)||o.CI_NAME===`codeship`?1:n;if(`TEAMCITY_VERSION`in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if(o.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in o){let e=parseInt((o.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(o.TERM_PROGRAM){case`iTerm.app`:return e>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)||`COLORTERM`in o?1:n}function u(e){let t=l(e,e&&e.isTTY);return c(t)}n.exports={supportsColor:u,stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}})),gr=e.__commonJSMin(((e,t)=>{t.exports={stringReplaceAll:(e,t,n)=>{let r=e.indexOf(t);if(r===-1)return e;let i=t.length,a=0,o=``;do o+=e.substr(a,r-a)+t+n,a=r+i,r=e.indexOf(t,a);while(r!==-1);return o+=e.substr(a),o},stringEncaseCRLFWithFirstIndex:(e,t,n,r)=>{let i=0,a=``;do{let o=e[r-1]===`\r`;a+=e.substr(i,(o?r-1:r)-i)+t+(o?`\r
|
|
26
26
|
`:`
|
|
27
27
|
`)+n,i=r+1,r=e.indexOf(`
|
|
28
28
|
`,i)}while(r!==-1);return a+=e.substr(i),a}}})),_r=e.__commonJSMin(((e,t)=>{let n=/(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,r=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,i=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,a=/\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi,o=new Map([[`n`,`
|
|
@@ -35,12 +35,12 @@ Error message: ${Ce(t)}`,cause:t}),this[Le]=!0,this.value=e}static isInstance(e)
|
|
|
35
35
|
`).map(e=>ei(e,t,n)).join(`
|
|
36
36
|
`)}const ni={actions:new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]])};function ri(e,t){if(typeof e==`string`)return ni.aliases.get(e)===t;for(let n of e)if(n!==void 0&&ri(n,t))return!0;return!1}function ii(e,t){if(e===t)return;let n=e.split(`
|
|
37
37
|
`),r=t.split(`
|
|
38
|
-
`),i=[];for(let e=0;e<Math.max(n.length,r.length);e++)n[e]!==r[e]&&i.push(e);return i}const ai=globalThis.process.platform.startsWith(`win`),oi=Symbol(`clack:cancel`);function si(e){return e===oi}function ci(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function li({input:e=
|
|
38
|
+
`),i=[];for(let e=0;e<Math.max(n.length,r.length);e++)n[e]!==r[e]&&i.push(e);return i}const ai=globalThis.process.platform.startsWith(`win`),oi=Symbol(`clack:cancel`);function si(e){return e===oi}function ci(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function li({input:e=d.stdin,output:t=d.stdout,overwrite:n=!0,hideCursor:r=!0}={}){let i=y.createInterface({input:e,output:t,prompt:``,tabSize:1});y.emitKeypressEvents(e,i),e.isTTY&&e.setRawMode(!0);let a=(i,{name:o,sequence:s})=>{if(ri([String(i),o,s],`cancel`)){r&&t.write(Sr.cursor.show),process.exit(0);return}if(!n)return;let c=o===`return`?0:-1,l=o===`return`?-1:0;y.moveCursor(t,c,l,()=>{y.clearLine(t,1,()=>{e.once(`keypress`,a)})})};return r&&t.write(Sr.cursor.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(Sr.cursor.show),e.isTTY&&!ai&&e.setRawMode(!1),i.terminal=!1,i.close()}}var ui=Object.defineProperty,di=(e,t,n)=>t in e?ui(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,fi=(e,t,n)=>(di(e,typeof t==`symbol`?t:t+``,n),n),pi=class{constructor(e,t=!0){fi(this,`input`),fi(this,`output`),fi(this,`_abortSignal`),fi(this,`rl`),fi(this,`opts`),fi(this,`_render`),fi(this,`_track`,!1),fi(this,`_prevFrame`,``),fi(this,`_subscribers`,new Map),fi(this,`_cursor`,0),fi(this,`state`,`initial`),fi(this,`error`,``),fi(this,`value`);let{input:n=d.stdin,output:r=d.stdout,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(oi);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}let n=new a.Writable;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=y.default.createInterface({input:this.input,output:n,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),y.default.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),ci(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(Sr.cursor.show),this.output.off(`resize`,this.render),ci(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(Sr.cursor.show),this.output.off(`resize`,this.render),ci(this.input,!1),e(oi)})})}onKeypress(e,t){if(this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&ni.aliases.has(t.name)&&this.emit(`cursor`,ni.aliases.get(t.name)),ni.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`)}ri([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(`
|
|
39
39
|
`),ci(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=ti(this._prevFrame,process.stdout.columns,{hard:!0}).split(`
|
|
40
40
|
`).length-1;this.output.write(Sr.cursor.move(-999,e*-1))}render(){let e=ti(this._render(this)??``,process.stdout.columns,{hard:!0});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(Sr.cursor.hide);else{let t=ii(this._prevFrame,e);if(this.restoreCursor(),t&&t?.length===1){let n=t[0];this.output.write(Sr.cursor.move(0,n)),this.output.write(Sr.erase.lines(1));let r=e.split(`
|
|
41
41
|
`);this.output.write(r[n]),this._prevFrame=e,this.output.write(Sr.cursor.move(0,r.length-n-1));return}if(t&&t?.length>1){let n=t[0];this.output.write(Sr.cursor.move(0,n)),this.output.write(Sr.erase.down());let r=e.split(`
|
|
42
42
|
`).slice(n);this.output.write(r.join(`
|
|
43
|
-
`)),this._prevFrame=e;return}this.output.write(Sr.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},mi=class extends pi{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(Sr.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},hi=Object.defineProperty,gi=(e,t,n)=>t in e?hi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_i=(e,t,n)=>(gi(e,typeof t==`symbol`?t:t+``,n),n),vi=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},yi=(e,t,n)=>(vi(e,t,`read from private field`),n?n.call(e):t.get(e)),bi=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},xi=(e,t,n,r)=>(vi(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n),Si;let Ci=class extends pi{constructor(e){super(e,!1),_i(this,`options`),_i(this,`cursor`,0),bi(this,Si,void 0);let{options:t}=e;xi(this,Si,e.selectableGroups!==!1),this.options=Object.entries(t).flatMap(([e,t])=>[{value:e,group:!0,label:e},...t.map(t=>({...t,group:e}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),yi(this,Si)?0:1),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let e=this.options[this.cursor]?.group===!0;!yi(this,Si)&&e&&(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;let e=this.options[this.cursor]?.group===!0;!yi(this,Si)&&e&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case`space`:this.toggleValue();break}})}getGroupItems(e){return this.options.filter(t=>t.group===e)}isGroupSelected(e){return this.getGroupItems(e).every(e=>this.value.includes(e.value))}toggleValue(){let e=this.options[this.cursor];if(e.group===!0){let t=e.value,n=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter(e=>n.findIndex(t=>t.value===e)===-1):this.value=[...this.value,...n.map(e=>e.value)],this.value=Array.from(new Set(this.value))}else this.value=this.value.includes(e.value)?this.value.filter(t=>t!==e.value):[...this.value,e.value]}};Si=new WeakMap;var wi=Object.defineProperty,Ti=(e,t,n)=>t in e?wi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ei=(e,t,n)=>(Ti(e,typeof t==`symbol`?t:t+``,n),n);let Di=class extends pi{constructor(e){super(e,!1),Ei(this,`options`),Ei(this,`cursor`,0),this.options=e.options,this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0),this.on(`key`,e=>{e===`a`&&this.toggleAll()}),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;case`space`:this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){this.value=this.value.length===this.options.length?[]:this.options.map(e=>e.value)}toggleValue(){this.value=this.value.includes(this._value)?this.value.filter(e=>e!==this._value):[...this.value,this._value]}};var Oi=Object.defineProperty,ki=(e,t,n)=>t in e?Oi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ai=(e,t,n)=>(ki(e,typeof t==`symbol`?t:t+``,n),n),ji=class extends pi{constructor({mask:e,...t}){super(t),Ai(this,`valueWithCursor`,``),Ai(this,`_mask`,`•`),this._mask=e??`•`,this.on(`finalize`,()=>{this.valueWithCursor=this.masked}),this.on(`value`,()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${Cr.default.inverse(Cr.default.hidden(`_`))}`;else{let e=this.masked.slice(0,this.cursor),t=this.masked.slice(this.cursor);this.valueWithCursor=`${e}${Cr.default.inverse(t[0])}${t.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}},Mi=Object.defineProperty,Ni=(e,t,n)=>t in e?Mi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pi=(e,t,n)=>(Ni(e,typeof t==`symbol`?t:t+``,n),n),Fi=class extends pi{constructor(e){super(e,!1),Pi(this,`options`),Pi(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}},Ii=Object.defineProperty,Li=(e,t,n)=>t in e?Ii(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ri=(e,t,n)=>(Li(e,typeof t==`symbol`?t:t+``,n),n),zi=class extends pi{constructor(e){super(e,!1),Ri(this,`options`),Ri(this,`cursor`,0),this.options=e.options;let t=this.options.map(({value:[e]})=>e?.toLowerCase());this.cursor=Math.max(t.indexOf(e.initialValue),0),this.on(`key`,e=>{if(!t.includes(e))return;let n=this.options.find(({value:[t]})=>t?.toLowerCase()===e);n&&(this.value=n.value,this.state=`submit`,this.emit(`submit`))})}},Bi=class extends pi{get valueWithCursor(){if(this.state===`submit`)return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;let e=this.value.slice(0,this.cursor),[t,...n]=this.value.slice(this.cursor);return`${e}${Cr.default.inverse(t)}${n.join(``)}`}get cursor(){return this._cursor}constructor(e){super(e),this.on(`finalize`,()=>{this.value||=e.defaultValue})}},Y=e.__toESM(br(),1),Vi=e.__toESM(yr(),1);function Hi(){return
|
|
43
|
+
`)),this._prevFrame=e;return}this.output.write(Sr.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}},mi=class extends pi{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(Sr.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},hi=Object.defineProperty,gi=(e,t,n)=>t in e?hi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_i=(e,t,n)=>(gi(e,typeof t==`symbol`?t:t+``,n),n),vi=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},yi=(e,t,n)=>(vi(e,t,`read from private field`),n?n.call(e):t.get(e)),bi=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},xi=(e,t,n,r)=>(vi(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n),Si;let Ci=class extends pi{constructor(e){super(e,!1),_i(this,`options`),_i(this,`cursor`,0),bi(this,Si,void 0);let{options:t}=e;xi(this,Si,e.selectableGroups!==!1),this.options=Object.entries(t).flatMap(([e,t])=>[{value:e,group:!0,label:e},...t.map(t=>({...t,group:e}))]),this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),yi(this,Si)?0:1),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let e=this.options[this.cursor]?.group===!0;!yi(this,Si)&&e&&(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;let e=this.options[this.cursor]?.group===!0;!yi(this,Si)&&e&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case`space`:this.toggleValue();break}})}getGroupItems(e){return this.options.filter(t=>t.group===e)}isGroupSelected(e){return this.getGroupItems(e).every(e=>this.value.includes(e.value))}toggleValue(){let e=this.options[this.cursor];if(e.group===!0){let t=e.value,n=this.getGroupItems(t);this.isGroupSelected(t)?this.value=this.value.filter(e=>n.findIndex(t=>t.value===e)===-1):this.value=[...this.value,...n.map(e=>e.value)],this.value=Array.from(new Set(this.value))}else this.value=this.value.includes(e.value)?this.value.filter(t=>t!==e.value):[...this.value,e.value]}};Si=new WeakMap;var wi=Object.defineProperty,Ti=(e,t,n)=>t in e?wi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ei=(e,t,n)=>(Ti(e,typeof t==`symbol`?t:t+``,n),n);let Di=class extends pi{constructor(e){super(e,!1),Ei(this,`options`),Ei(this,`cursor`,0),this.options=e.options,this.value=[...e.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:t})=>t===e.cursorAt),0),this.on(`key`,e=>{e===`a`&&this.toggleAll()}),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;case`space`:this.toggleValue();break}})}get _value(){return this.options[this.cursor].value}toggleAll(){this.value=this.value.length===this.options.length?[]:this.options.map(e=>e.value)}toggleValue(){this.value=this.value.includes(this._value)?this.value.filter(e=>e!==this._value):[...this.value,this._value]}};var Oi=Object.defineProperty,ki=(e,t,n)=>t in e?Oi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ai=(e,t,n)=>(ki(e,typeof t==`symbol`?t:t+``,n),n),ji=class extends pi{constructor({mask:e,...t}){super(t),Ai(this,`valueWithCursor`,``),Ai(this,`_mask`,`•`),this._mask=e??`•`,this.on(`finalize`,()=>{this.valueWithCursor=this.masked}),this.on(`value`,()=>{if(this.cursor>=this.value.length)this.valueWithCursor=`${this.masked}${Cr.default.inverse(Cr.default.hidden(`_`))}`;else{let e=this.masked.slice(0,this.cursor),t=this.masked.slice(this.cursor);this.valueWithCursor=`${e}${Cr.default.inverse(t[0])}${t.slice(1)}`}})}get cursor(){return this._cursor}get masked(){return this.value.replaceAll(/./g,this._mask)}},Mi=Object.defineProperty,Ni=(e,t,n)=>t in e?Mi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pi=(e,t,n)=>(Ni(e,typeof t==`symbol`?t:t+``,n),n),Fi=class extends pi{constructor(e){super(e,!1),Pi(this,`options`),Pi(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}},Ii=Object.defineProperty,Li=(e,t,n)=>t in e?Ii(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ri=(e,t,n)=>(Li(e,typeof t==`symbol`?t:t+``,n),n),zi=class extends pi{constructor(e){super(e,!1),Ri(this,`options`),Ri(this,`cursor`,0),this.options=e.options;let t=this.options.map(({value:[e]})=>e?.toLowerCase());this.cursor=Math.max(t.indexOf(e.initialValue),0),this.on(`key`,e=>{if(!t.includes(e))return;let n=this.options.find(({value:[t]})=>t?.toLowerCase()===e);n&&(this.value=n.value,this.state=`submit`,this.emit(`submit`))})}},Bi=class extends pi{get valueWithCursor(){if(this.state===`submit`)return this.value;if(this.cursor>=this.value.length)return`${this.value}\u2588`;let e=this.value.slice(0,this.cursor),[t,...n]=this.value.slice(this.cursor);return`${e}${Cr.default.inverse(t)}${n.join(``)}`}get cursor(){return this._cursor}constructor(e){super(e),this.on(`finalize`,()=>{this.value||=e.defaultValue})}},Y=e.__toESM(br(),1),Vi=e.__toESM(yr(),1);function Hi(){return d.default.platform===`win32`?!!d.default.env.CI||!!d.default.env.WT_SESSION||!!d.default.env.TERMINUS_SUBLIME||d.default.env.ConEmuTask===`{cmd::Cmder}`||d.default.env.TERM_PROGRAM===`Terminus-Sublime`||d.default.env.TERM_PROGRAM===`vscode`||d.default.env.TERM===`xterm-256color`||d.default.env.TERM===`alacritty`||d.default.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:d.default.env.TERM!==`linux`}const Ui=Hi(),Wi=(e,t)=>Ui?e:t,Gi=Wi(`◆`,`*`),Ki=Wi(`■`,`x`),qi=Wi(`▲`,`x`),Ji=Wi(`◇`,`o`),Yi=Wi(`┌`,`T`),X=Wi(`│`,`|`),Xi=Wi(`└`,`—`),Zi=Wi(`●`,`>`),Qi=Wi(`○`,` `),$i=Wi(`◻`,`[•]`),ea=Wi(`◼`,`[+]`),ta=Wi(`◻`,`[ ]`),na=Wi(`▪`,`•`),ra=Wi(`─`,`-`),ia=Wi(`╮`,`+`),aa=Wi(`├`,`+`),oa=Wi(`╯`,`+`),sa=Wi(`●`,`•`),ca=Wi(`◆`,`*`),la=Wi(`▲`,`!`),ua=Wi(`■`,`x`),da=e=>{switch(e){case`initial`:case`active`:return Y.default.cyan(Gi);case`cancel`:return Y.default.red(Ki);case`error`:return Y.default.yellow(qi);case`submit`:return Y.default.green(Ji)}},fa=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?Y.default.dim(`...`):r(e,n+s===t)})},pa=e=>new Bi({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,render(){let t=`${Y.default.gray(X)}
|
|
44
44
|
${da(this.state)} ${e.message}
|
|
45
45
|
`,n=e.placeholder?Y.default.inverse(e.placeholder[0])+Y.default.dim(e.placeholder.slice(1)):Y.default.inverse(Y.default.hidden(`_`)),r=this.value?this.valueWithCursor:n;switch(this.state){case`error`:return`${t.trim()}
|
|
46
46
|
${Y.default.yellow(X)} ${r}
|
|
@@ -100,7 +100,7 @@ ${Y.default.cyan(Xi)}
|
|
|
100
100
|
`}}}).prompt()},ba=(e=``,t=``)=>{let n=`
|
|
101
101
|
${e}
|
|
102
102
|
`.split(`
|
|
103
|
-
`),r=(0,
|
|
103
|
+
`),r=(0,o.stripVTControlCharacters)(t).length,i=Math.max(n.reduce((e,t)=>{let n=(0,o.stripVTControlCharacters)(t);return n.length>e?n.length:e},0),r)+2,a=n.map(e=>`${Y.default.gray(X)} ${Y.default.dim(e)}${` `.repeat(i-(0,o.stripVTControlCharacters)(e).length)}${Y.default.gray(X)}`).join(`
|
|
104
104
|
`);process.stdout.write(`${Y.default.gray(X)}
|
|
105
105
|
${Y.default.green(Ji)} ${Y.default.reset(t)} ${Y.default.gray(ra.repeat(Math.max(i-r-1,1))+ia)}
|
|
106
106
|
${a}
|
|
@@ -117,22 +117,22 @@ ${Y.default.gray(Xi)} ${e}
|
|
|
117
117
|
`)},info:e=>{wa.message(e,{symbol:Y.default.blue(sa)})},success:e=>{wa.message(e,{symbol:Y.default.green(ca)})},step:e=>{wa.message(e,{symbol:Y.default.green(Ji)})},warn:e=>{wa.message(e,{symbol:Y.default.yellow(la)})},warning:e=>{wa.warn(e)},error:e=>{wa.message(e,{symbol:Y.default.red(ua)})}},Ta=`${Y.default.gray(X)} `,Ea={message:async(e,{symbol:t=Y.default.gray(X)}={})=>{process.stdout.write(`${Y.default.gray(X)}
|
|
118
118
|
${t} `);let n=3;for await(let t of e){t=t.replace(/\n/g,`
|
|
119
119
|
${Ta}`),t.includes(`
|
|
120
|
-
`)&&(n=3+(0,
|
|
121
|
-
`))).length);let e=(0,
|
|
122
|
-
${Ta}${t.trimStart()}`),n=3+(0,
|
|
120
|
+
`)&&(n=3+(0,o.stripVTControlCharacters)(t.slice(t.lastIndexOf(`
|
|
121
|
+
`))).length);let e=(0,o.stripVTControlCharacters)(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
122
|
+
${Ta}${t.trimStart()}`),n=3+(0,o.stripVTControlCharacters)(t.trimStart()).length)}process.stdout.write(`
|
|
123
123
|
`)},info:e=>Ea.message(e,{symbol:Y.default.blue(sa)}),success:e=>Ea.message(e,{symbol:Y.default.green(ca)}),step:e=>Ea.message(e,{symbol:Y.default.green(Ji)}),warn:e=>Ea.message(e,{symbol:Y.default.yellow(la)}),warning:e=>Ea.warn(e),error:e=>Ea.message(e,{symbol:Y.default.red(ua)})},Da=({indicator:e=`dots`}={})=>{let t=Ui?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],n=Ui?80:120,r=process.env.CI===`true`,i,a,o=!1,s=``,c,l=performance.now(),u=e=>{o&&y(e>1?`Something went wrong`:`Canceled`,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(`
|
|
124
124
|
`);let e=c.split(`
|
|
125
125
|
`);process.stdout.write(Vi.cursor.move(-999,e.length-1)),process.stdout.write(Vi.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=li(),s=g(u),l=performance.now(),process.stdout.write(`${Y.default.gray(X)}
|
|
126
126
|
`);let d=0,f=0;p(),a=setInterval(()=>{if(r&&s===c)return;h(),c=s;let n=Y.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?Y.default.green(Ji):n===1?Y.default.red(Ki):Y.default.red(qi);s=g(t??s),e===`timer`?process.stdout.write(`${r} ${s} ${_(l)}
|
|
127
127
|
`):process.stdout.write(`${r} ${s}
|
|
128
|
-
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Oa=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&si(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},ka=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=Da();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};function Aa(){let e=ja();if((0,
|
|
128
|
+
`),m(),i()};return{start:v,stop:y,message:(e=``)=>{s=g(e??s)}}},Oa=async(e,t)=>{let n={},r=Object.keys(e);for(let i of r){let r=e[i],a=await r({results:n})?.catch(e=>{throw e});if(typeof t?.onCancel==`function`&&si(a)){n[i]=`canceled`,t.onCancel({results:n});continue}n[i]=a}return n},ka=async e=>{for(let t of e){if(t.enabled===!1)continue;let e=Da();e.start(t.title);let n=await t.task(e.message);e.stop(n||t.title)}};function Aa(){let e=ja();if((0,u.existsSync)(e)){let t=(0,u.readFileSync)(e,`utf8`);return JSON.parse(t).token}}function ja(){let e=lr(`blink`).dataDirs();if(e.length===0)throw Error(`No suitable data directory for Blink storage found!`);return(0,c.join)(e[0],`auth.json`)}function Ma(e){let t=(0,c.join)(e,`data`,`devhook.txt`);if((0,u.mkdirSync)((0,c.dirname)(t),{recursive:!0}),(0,u.existsSync)(t))return(0,u.readFileSync)(t,`utf-8`);let n=crypto.randomUUID();return(0,u.writeFileSync)(t,n),n}const Na=(e,t)=>e.json({error:t},400),Pa=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Fa=()=>new t.Hono,Ia=Fa().get(`/:key`,async e=>{let{key:t,err:n}=Pa(e);if(n)return Na(e,n);let r=await e.env.context.store.get(t);return e.json({value:r},200)}).post(`/:key`,t.validator(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Na(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Na(t,`Value must be a string`):Na(t,`Value is required`)}),async e=>{let{key:t,err:n}=Pa(e);if(n)return Na(e,n);let{value:r}=e.req.valid(`json`);return await e.env.context.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Pa(e);return n?Na(e,n):(await e.env.context.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.context.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),La=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},Ra=Fa().basePath(`/:key`).post(`/`,async e=>{let{key:t,err:n}=La(e);return n?Na(e,n):e.json(await e.env.context.chat.ensure(t),200)}).post(`/sendMessages`,t.validator(`json`,(e,t)=>({message:e.message,options:e.options})),async e=>{let{key:t,err:n}=La(e);if(n)return Na(e,n);let{message:r,options:i}=e.req.valid(`json`);try{await e.env.context.chat.message(t,r,i)}catch(t){return Na(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),za=Fa().post(`/v1/traces`,async e=>e.env.context.otlp?e.env.context.otlp.traces(e.req.raw):e.body(null,204)),Ba=new t.Hono().route(`/kv`,Ia).route(`/chat`,Ra).route(`/otlp`,za);function Va(e){let n=(0,g.join)(e.dataDirectory,`chats`),r={},a=(0,g.join)(e.dataDirectory,`storage.json`);i.existsSync(a)&&(r=JSON.parse(i.readFileSync(a,`utf-8`)));let o=new Map,c=t=>{let r=o.get(t);return r||(r=new le({chatId:t,chatsDirectory:n}),r.setAgent(e.getAgent()),o.set(t,r)),r},l={chat:{async ensure(e){let t=c(e).getState(),n=t.messages.length===0&&!t.created_at;return{key:e,created:n}},async message(e,t,n){let r=c(e),i=se(t,`run`);if(n?.behavior===`append`){await r.upsertMessage(i);return}if(n?.behavior===`interrupt`){await r.sendMessage(i);return}await r.sendMessage(i)}},store:{get(e){return Promise.resolve(r[e])},set(e,t){return r[e]=t,i.writeFileSync(a,JSON.stringify(r),`utf-8`),Promise.resolve()},delete(e){return delete r[e],i.writeFileSync(a,JSON.stringify(r),`utf-8`),Promise.resolve()},list(e,t){let n=Math.min(t?.limit??100,1e3),i=t?.cursor,a=Object.keys(r).filter(t=>t.startsWith(e??``)).sort(),o=0;if(i){let e=a.indexOf(i);e!==-1&&(o=e+1)}let s=a.slice(o,o+n),c=o+n<a.length?s[s.length-1]:void 0;return Promise.resolve({entries:s.map(e=>({key:e})),cursor:c})}}},u=(0,s.createServer)(t.createServerAdapter(e=>Ba.fetch(e,{context:l})));u.listen(e.port??0);let d=ie(n,`id`);return{url:`http://127.0.0.1:${u.address().port}`,runtime:l,chatsDirectory:n,getChatManager:c,listChats:()=>d.list(),lockChat:e=>d.lock(e),startChat:async e=>{await c(e).start()},stopChat:e=>{o.get(e)?.stopStreaming()},dispose:()=>{for(let e of o.values())e.dispose();o.clear(),d.dispose(),u.close()}}}function Ha({agent:e,capabilities:n,messages:r}){let[i,a]=(0,h.useState)(void 0),[o,s]=(0,h.useState)(!0),[c,l]=(0,h.useState)(void 0),u=(0,h.useRef)(c);(0,h.useEffect)(()=>{u.current=c},[c]);let[d,f]=(0,h.useState)(()=>t.lastUIOptions(r));(0,h.useEffect)(()=>{f(e=>{let n=t.lastUIOptions(r);return JSON.stringify(n)===JSON.stringify(e)?e:n})},[r]);let[p,m]=(0,h.useState)(void 0),g=(0,h.useCallback)((e,t)=>{if(!u.current)return!1;let n=u.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,h.useCallback)(e=>{m(t=>{let n={...d,...t,...e};for(let[e,t]of Object.entries(n))g(e,t)||delete n[e];for(let[e,t]of Object.entries(u.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[d,g]);(0,h.useEffect)(()=>{if(!d&&!c){m(void 0);return}_()},[d,c,_]);let v=(0,h.useRef)(void 0),y=(0,h.useRef)(void 0);(0,h.useEffect)(()=>{e!==y.current&&(y.current=e,l(void 0),m(void 0),a(void 0),s(!0),v.current=void 0)},[e]),(0,h.useEffect)(()=>{if(n&&!n.ui||!e){l(void 0),m(void 0),a(void 0),v.current=void 0;return}let t=p?JSON.stringify(p):``;if(v.current===t){s(!1),a(void 0);return}let r=new AbortController;return s(!0),a(void 0),e.ui(p?{selectedOptions:p}:{},{signal:r.signal}).then(e=>{if(!e){l(void 0);return}r.signal.aborted||(l(t=>JSON.stringify(t)===JSON.stringify(e)?t:e),v.current=t)}).catch(e=>{r.signal.aborted||a(e instanceof Error?e:Error(String(e)))}).finally(()=>{s(!1)}),()=>{r.abort()}},[e,n,p]);let b=(0,h.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:c,options:p,setOption:b,loading:o,error:i}}function Ua(e){let t=(0,h.useRef)(e.onRequest);(0,h.useEffect)(()=>{t.current=e.onRequest},[e.onRequest]);let n=(0,h.useRef)(e.id??crypto.randomUUID()),[r,i]=(0,h.useState)(`disconnected`);return(0,h.useEffect)(()=>{if(e.disabled){i(`disconnected`);return}let r=!1,a,o,s=!1,c=()=>{if(!(r||s)){if(s=!0,a){try{a.dispose()}catch{}a=void 0}a=new Qn({baseURL:`https://blink.so`}).devhook.listen({id:n.current,onRequest:async e=>t.current(e),onConnect:()=>{s=!1,i(`connected`)},onDisconnect:()=>{s=!1,i(`disconnected`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))},onError:e=>{s=!1,i(`error`),!r&&!o&&(o=setTimeout(()=>{o=void 0,c()},2e3))}})}};return c(),()=>{if(r=!0,o&&=(clearTimeout(o),void 0),a){try{a.dispose()}catch{}a=void 0}}},[e.disabled]),{id:n.current,status:r}}var Wa=e.__commonJSMin(((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,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 tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,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}}})),Ga=e.__commonJSMin(((e,t)=>{let n=require(`fs`),r=require(`path`),i=require(`os`),a=require(`crypto`),o=Wa().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
129
129
|
`);let r;for(;(r=f.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,`
|
|
130
|
-
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(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 y(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 b(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 x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${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 E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};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],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),Ka=e.__toESM(Ga(),1);async function qa(e,t){let n=e;for(;n!==(0,r.dirname)(n);){let e=(0,r.join)(n,t);try{return await(0,o.stat)(e),e}catch{}n=(0,r.dirname)(n)}}function Ja(e,t=`.env.local`){let[n,r]=(0,h.useState)({});return(0,h.useEffect)(()=>{let n,a=e=>{try{let t=(0,i.readFileSync)(e,`utf-8`),n=(0,Ka.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return qa(e,t).then(e=>{if(!e){r({});return}a(e),n=(0,i.watch)(e,{persistent:!1},()=>{a(e)})}),()=>{n&&n.close()}},[e,t]),n}const Ya=(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},Xa=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1));let Za=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}({}),Qa=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 $a={[Za.REQUEST]:v.z.string(),[Za.PROXY_INIT]:v.z.object({method:v.z.string(),headers:v.z.record(v.z.string(),v.z.string()),url:v.z.string()}),[Za.PROXY_BODY]:v.z.instanceof(Uint8Array),[Za.PROXY_WEBSOCKET_MESSAGE]:v.z.object({type:v.z.enum([`text`,`binary`]),data:v.z.instanceof(Uint8Array)}),[Za.PROXY_WEBSOCKET_CLOSE]:v.z.object({code:v.z.number().optional(),reason:v.z.string().optional()})},eo={[Qa.RESPONSE]:v.z.string(),[Qa.NOTIFICATION]:v.z.string(),[Qa.PROXY_INIT]:v.z.object({status_code:v.z.number(),status_message:v.z.string(),headers:v.z.record(v.z.string(),v.z.string())}),[Qa.PROXY_DATA]:v.z.instanceof(Uint8Array),[Qa.PROXY_WEBSOCKET_MESSAGE]:v.z.instanceof(Uint8Array),[Qa.PROXY_WEBSOCKET_CLOSE]:v.z.object({code:v.z.number(),reason:v.z.string()})},to={[Za.PROXY_INIT]:{method:v.z.string(),headers:v.z.record(v.z.string(),v.z.string()),url:v.z.string()}},no={process_execute:v.z.object({command:v.z.string(),args:v.z.array(v.z.string()),env_file:v.z.string().optional(),env:v.z.record(v.z.string(),v.z.string()).optional(),cwd:v.z.string().optional()}),process_send_input:v.z.object({pid:v.z.number(),data:v.z.string()}),process_wait:v.z.object({pid:v.z.number(),output_idle_timeout_ms:v.z.number().optional(),timeout_ms:v.z.number().optional()}),process_list:v.z.object({include_dead:v.z.boolean().optional()}),process_read_plain_output:v.z.object({pid:v.z.number(),start_line:v.z.number().optional(),end_line:v.z.number().optional()}),process_kill:v.z.object({pid:v.z.number(),signal:v.z.string().optional()}),set_env:v.z.object({env:v.z.record(v.z.string(),v.z.string())}),read_file:v.z.object({path:v.z.string(),line_start:v.z.number().optional(),line_end:v.z.number().optional()}),write_file:v.z.object({path:v.z.string(),content:v.z.string(),base64:v.z.boolean().optional(),mode:v.z.number().optional()}),read_directory:v.z.object({path:v.z.string()}),watch_directory:v.z.object({path:v.z.string()}),deploy_static_files:v.z.object({path:v.z.string()})},ro=v.z.object({pid:v.z.number(),command:v.z.string(),args:v.z.array(v.z.string()),title:v.z.string().optional(),cwd:v.z.string(),env:v.z.record(v.z.string(),v.z.string()),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional(),duration_ms:v.z.number().optional(),output_total_lines:v.z.number()}),io=ro.extend({ansi_output:v.z.string(),plain_output:v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number()})}),ao={process_execute:v.z.object({pid:v.z.number()}),process_send_input:v.z.object({}),process_wait:io,process_list:v.z.object({processes:v.z.array(ro)}),process_read_plain_output:v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number(),duration_ms:v.z.number(),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional()}),process_kill:v.z.object({}),set_env:v.z.object({}),read_file:v.z.object({total_lines:v.z.number(),lines_read:v.z.number(),start_line:v.z.number(),content:v.z.string(),mime_type:v.z.string()}),write_file:v.z.object({}),read_directory:v.z.object({entries:v.z.array(v.z.object({name:v.z.string(),type:v.z.enum([`file`,`directory`,`symlink`])}))}),watch_directory:v.z.object({}),deploy_static_files:v.z.object({deployment_id:v.z.string()})},oo=v.z.object({type:v.z.enum([`create`,`update`,`delete`]),path:v.z.string()}),so=v.z.object({type:v.z.enum([`context`,`added`,`deleted`]),content:v.z.string(),oldLineNumber:v.z.number().optional(),newLineNumber:v.z.number().optional()}),co=v.z.object({oldStart:v.z.number(),oldLines:v.z.number(),newStart:v.z.number(),newLines:v.z.number(),lines:v.z.array(so)}),lo=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:v.z.string().optional(),insertions:v.z.number(),deletions:v.z.number(),chunks:v.z.array(co)}),uo=v.z.object({totalFiles:v.z.number(),totalInsertions:v.z.number(),totalDeletions:v.z.number(),netChange:v.z.number(),startHash:v.z.string().optional(),currentHash:v.z.string().optional(),timespan:v.z.number(),files:v.z.array(lo)}),fo=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:v.z.boolean()}),po=v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),email:v.z.string(),date:v.z.date(),timestamp:v.z.date(),filesChanged:v.z.number(),insertions:v.z.number(),deletions:v.z.number(),commitDiff:v.z.array(lo).optional()}),mo=v.z.object({files:v.z.array(fo),branch:v.z.string(),ahead:v.z.number(),behind:v.z.number(),timestamp:v.z.date(),sessionDiff:uo.optional(),workingDirectoryDiff:uo.optional(),newCommits:v.z.array(po),currentCommit:v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),date:v.z.date()}).optional(),diffSkipped:v.z.boolean().optional(),payloadTruncated:v.z.boolean().optional(),estimatedSizeKB:v.z.number().optional()}),ho=v.z.object({debounceDelay:v.z.number().optional(),gitStatusInterval:v.z.number().optional(),ignoreDotfiles:v.z.boolean().optional(),ignored:v.z.array(v.z.string()).optional(),watchGit:v.z.boolean().optional(),includeDiffs:v.z.boolean().optional(),maxDiffFiles:v.z.number().optional(),maxPayloadSizeKB:v.z.number().optional(),truncateLargeDiffs:v.z.boolean().optional()}),go={process_status:v.z.object({status:ro}),process_output:v.z.object({pid:v.z.number(),output:v.z.string()}),file_change:v.z.object({changes:v.z.array(oo)}),git_status:mo};var _o=class{notificationCallbacks=new Map;disposables=[];requestHandlers=new Map;send;jwt;requestTimeoutMS;constructor({send:e,jwt:t,requestTimeoutMS:n}){this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}},vo=e.__commonJSMin(((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:()=>{}}})),yo=e.__commonJSMin(((e,t)=>{let{EMPTY_BUFFER:n}=vo(),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=require(`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{}})),bo=e.__commonJSMin(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=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])}}}})),xo=e.__commonJSMin(((e,t)=>{let n=require(`zlib`),r=yo(),i=bo(),{kStatusCode:a}=vo(),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;t.exports=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`,g),this._inflate.on(`data`,h)}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`,m)}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)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(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`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),So=e.__commonJSMin(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=vo(),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=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),Co=e.__commonJSMin(((e,t)=>{let{Writable:n}=require(`stream`),r=xo(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=vo(),{concat:c,toArrayBuffer:l,unmask:u}=yo(),{isValidStatusCode:d,isValidUTF8:f}=So(),p=Buffer[Symbol.species];t.exports=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}}})),wo=e.__commonJSMin(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=xo(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=vo(),{isBlob:c,isValidStatusCode:l}=So(),{mask:u,toBuffer:d}=yo(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=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(_,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(v,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){_(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)}};function _(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 v(e,t,n){_(e,t,n),e.onerror(t)}})),To=e.__commonJSMin(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=vo(),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}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{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,g(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,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(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}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Eo=e.__commonJSMin(((e,t)=>{let{tokenChars:n}=So();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}})),Do=e.__commonJSMin(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=xo(),p=Co(),m=wo(),{isBlob:h}=So(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=vo(),{EventTarget:{addEventListener:w,removeEventListener:T}}=To(),{format:E,parse:D}=Eo(),{toBuffer:O}=yo(),k=Symbol(`kAborted`),A=[8,13],j=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=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]),P(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`,ne),i.on(`ping`,re),i.on(`pong`,H),a.onerror=ie,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,ae),t.on(`data`,oe),t.on(`end`,se),t.on(`error`,ce),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())}),W(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(N,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.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})}})}),N.prototype.addEventListener=w,N.prototype.removeEventListener=T,t.exports=N;function P(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;F(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:ee),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`||!M.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,F(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}`);F(e,t);return}P(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!==N.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 F(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ee(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=N.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(F,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`,oe),process.nextTick(U,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`,oe),process.nextTick(U,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function V(){this[S].emitClose()}function ne(e,t){this[S].emit(`message`,e,t)}function re(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function H(e){this[S].emit(`pong`,e)}function U(e){e.resume()}function ie(e){let t=this[S];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,W(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function W(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function ae(){let e=this[S];this.removeListener(`close`,ae),this.removeListener(`data`,oe),this.removeListener(`end`,se),e._readyState=N.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`,V),e._receiver.on(`finish`,V))}function oe(e){this[S]._receiver.write(e)||this.pause()}function se(){let e=this[S];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function ce(){let e=this[S];this.removeListener(`error`,ce),this.on(`error`,C),e&&(e._readyState=N.CLOSING,this.destroy())}})),Oo=e.__commonJSMin(((e,t)=>{Do();let{Duplex:n}=require(`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})),ko=e.__commonJSMin(((e,t)=>{let{tokenChars:n}=So();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}})),Ao=e.__commonJSMin(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=Eo(),s=xo(),c=ko(),l=Do(),{GUID:u,kWebSocket:d}=vo(),f=/^[+/0-9A-Za-z]{22}==$/;t.exports=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=p(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(m,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(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(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`,h);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){_(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){_(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!f.test(i)){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){g(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{_(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{_(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 g(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return g(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 g(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
|
|
130
|
+
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(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 y(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 b(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 x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${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 E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};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],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})),Ka=e.__toESM(Ga(),1);async function qa(e,t){let n=e;for(;n!==(0,c.dirname)(n);){let e=(0,c.join)(n,t);try{return await(0,p.stat)(e),e}catch{}n=(0,c.dirname)(n)}}function Ja(e,t=`.env.local`){let[n,r]=(0,h.useState)({});return(0,h.useEffect)(()=>{let n,i=e=>{try{let t=(0,u.readFileSync)(e,`utf-8`),n=(0,Ka.parse)(t);r(n)}catch(e){console.error(`Error reading ${t}:`,e),r({})}};return qa(e,t).then(e=>{if(!e){r({});return}i(e),n=(0,u.watch)(e,{persistent:!1},()=>{i(e)})}),()=>{n&&n.close()}},[e,t]),n}const Ya=(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},Xa=(e,t)=>e[0]===0?t.decode(e.subarray(1)):new Uint8Array(e.subarray(1));let Za=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}({}),Qa=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 $a={[Za.REQUEST]:v.z.string(),[Za.PROXY_INIT]:v.z.object({method:v.z.string(),headers:v.z.record(v.z.string(),v.z.string()),url:v.z.string()}),[Za.PROXY_BODY]:v.z.instanceof(Uint8Array),[Za.PROXY_WEBSOCKET_MESSAGE]:v.z.object({type:v.z.enum([`text`,`binary`]),data:v.z.instanceof(Uint8Array)}),[Za.PROXY_WEBSOCKET_CLOSE]:v.z.object({code:v.z.number().optional(),reason:v.z.string().optional()})},eo={[Qa.RESPONSE]:v.z.string(),[Qa.NOTIFICATION]:v.z.string(),[Qa.PROXY_INIT]:v.z.object({status_code:v.z.number(),status_message:v.z.string(),headers:v.z.record(v.z.string(),v.z.string())}),[Qa.PROXY_DATA]:v.z.instanceof(Uint8Array),[Qa.PROXY_WEBSOCKET_MESSAGE]:v.z.instanceof(Uint8Array),[Qa.PROXY_WEBSOCKET_CLOSE]:v.z.object({code:v.z.number(),reason:v.z.string()})},to={[Za.PROXY_INIT]:{method:v.z.string(),headers:v.z.record(v.z.string(),v.z.string()),url:v.z.string()}},no={process_execute:v.z.object({command:v.z.string(),args:v.z.array(v.z.string()),env_file:v.z.string().optional(),env:v.z.record(v.z.string(),v.z.string()).optional(),cwd:v.z.string().optional()}),process_send_input:v.z.object({pid:v.z.number(),data:v.z.string()}),process_wait:v.z.object({pid:v.z.number(),output_idle_timeout_ms:v.z.number().optional(),timeout_ms:v.z.number().optional()}),process_list:v.z.object({include_dead:v.z.boolean().optional()}),process_read_plain_output:v.z.object({pid:v.z.number(),start_line:v.z.number().optional(),end_line:v.z.number().optional()}),process_kill:v.z.object({pid:v.z.number(),signal:v.z.string().optional()}),set_env:v.z.object({env:v.z.record(v.z.string(),v.z.string())}),read_file:v.z.object({path:v.z.string(),line_start:v.z.number().optional(),line_end:v.z.number().optional()}),write_file:v.z.object({path:v.z.string(),content:v.z.string(),base64:v.z.boolean().optional(),mode:v.z.number().optional()}),read_directory:v.z.object({path:v.z.string()}),watch_directory:v.z.object({path:v.z.string()}),deploy_static_files:v.z.object({path:v.z.string()})},ro=v.z.object({pid:v.z.number(),command:v.z.string(),args:v.z.array(v.z.string()),title:v.z.string().optional(),cwd:v.z.string(),env:v.z.record(v.z.string(),v.z.string()),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional(),duration_ms:v.z.number().optional(),output_total_lines:v.z.number()}),io=ro.extend({ansi_output:v.z.string(),plain_output:v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number()})}),ao={process_execute:v.z.object({pid:v.z.number()}),process_send_input:v.z.object({}),process_wait:io,process_list:v.z.object({processes:v.z.array(ro)}),process_read_plain_output:v.z.object({lines:v.z.array(v.z.string()),total_lines:v.z.number(),duration_ms:v.z.number(),exit_code:v.z.number().optional(),exit_signal:v.z.number().optional()}),process_kill:v.z.object({}),set_env:v.z.object({}),read_file:v.z.object({total_lines:v.z.number(),lines_read:v.z.number(),start_line:v.z.number(),content:v.z.string(),mime_type:v.z.string()}),write_file:v.z.object({}),read_directory:v.z.object({entries:v.z.array(v.z.object({name:v.z.string(),type:v.z.enum([`file`,`directory`,`symlink`])}))}),watch_directory:v.z.object({}),deploy_static_files:v.z.object({deployment_id:v.z.string()})},oo=v.z.object({type:v.z.enum([`create`,`update`,`delete`]),path:v.z.string()}),so=v.z.object({type:v.z.enum([`context`,`added`,`deleted`]),content:v.z.string(),oldLineNumber:v.z.number().optional(),newLineNumber:v.z.number().optional()}),co=v.z.object({oldStart:v.z.number(),oldLines:v.z.number(),newStart:v.z.number(),newLines:v.z.number(),lines:v.z.array(so)}),lo=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),oldPath:v.z.string().optional(),insertions:v.z.number(),deletions:v.z.number(),chunks:v.z.array(co)}),uo=v.z.object({totalFiles:v.z.number(),totalInsertions:v.z.number(),totalDeletions:v.z.number(),netChange:v.z.number(),startHash:v.z.string().optional(),currentHash:v.z.string().optional(),timespan:v.z.number(),files:v.z.array(lo)}),fo=v.z.object({path:v.z.string(),status:v.z.enum([`added`,`modified`,`deleted`,`renamed`,`copied`,`untracked`,`ignored`,`unmerged`,`typechange`]),staged:v.z.boolean()}),po=v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),email:v.z.string(),date:v.z.date(),timestamp:v.z.date(),filesChanged:v.z.number(),insertions:v.z.number(),deletions:v.z.number(),commitDiff:v.z.array(lo).optional()}),mo=v.z.object({files:v.z.array(fo),branch:v.z.string(),ahead:v.z.number(),behind:v.z.number(),timestamp:v.z.date(),sessionDiff:uo.optional(),workingDirectoryDiff:uo.optional(),newCommits:v.z.array(po),currentCommit:v.z.object({hash:v.z.string(),shortHash:v.z.string(),message:v.z.string(),author:v.z.string(),date:v.z.date()}).optional(),diffSkipped:v.z.boolean().optional(),payloadTruncated:v.z.boolean().optional(),estimatedSizeKB:v.z.number().optional()}),ho=v.z.object({debounceDelay:v.z.number().optional(),gitStatusInterval:v.z.number().optional(),ignoreDotfiles:v.z.boolean().optional(),ignored:v.z.array(v.z.string()).optional(),watchGit:v.z.boolean().optional(),includeDiffs:v.z.boolean().optional(),maxDiffFiles:v.z.number().optional(),maxPayloadSizeKB:v.z.number().optional(),truncateLargeDiffs:v.z.boolean().optional()}),go={process_status:v.z.object({status:ro}),process_output:v.z.object({pid:v.z.number(),output:v.z.string()}),file_change:v.z.object({changes:v.z.array(oo)}),git_status:mo};var _o=class{notificationCallbacks=new Map;disposables=[];requestHandlers=new Map;send;jwt;requestTimeoutMS;constructor({send:e,jwt:t,requestTimeoutMS:n}){this.send=e,this.jwt=t,this.requestTimeoutMS=n}handleMessage(e){if(typeof e!=`string`)return;let t=JSON.parse(e);if(`id`in t){let e=this.requestHandlers.get(t.id);if(!e)return;e(t.payload,t.error)}else if(`type`in t)this.notificationCallbacks.get(t.type)?.forEach(e=>{e(t.payload)});else return}dispose(e){this.disposables.forEach(t=>t.dispose(e))}async request(e,t,n){let r=crypto.randomUUID(),i,a,o=new Promise((e,t)=>{i=e,a=t}),s={dispose:e=>{l();let t=`Client was disposed!`;e&&(t+=` Reason: ${e}`),a(Error(t))}};this.disposables.push(s);let c;this.requestTimeoutMS&&(c=setTimeout(()=>{a(Error(`Request timed out`))},this.requestTimeoutMS));let l=()=>{this.disposables.splice(this.disposables.indexOf(s),1),this.requestHandlers.delete(r),c&&clearTimeout(c)};n?.signal&&n.signal.addEventListener(`abort`,()=>{l(),a(n.signal?.reason)}),this.requestHandlers.set(r,(e,t)=>{if(l(),t)return a(Error(t));i(e)});let u={id:r,type:e,payload:t,jwt:this.jwt};return this.send(JSON.stringify(u)),o}onNotification(e,t){let n=this.notificationCallbacks.get(e)??[];return n.push(t),this.notificationCallbacks.set(e,n),{dispose:()=>{let n=this.notificationCallbacks.get(e)??[],r=n.indexOf(t);r!==-1&&n.splice(r,1)}}}},vo=e.__commonJSMin(((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:()=>{}}})),yo=e.__commonJSMin(((e,t)=>{let{EMPTY_BUFFER:n}=vo(),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=require(`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{}})),bo=e.__commonJSMin(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=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])}}}})),xo=e.__commonJSMin(((e,t)=>{let n=require(`zlib`),r=yo(),i=bo(),{kStatusCode:a}=vo(),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;t.exports=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`,g),this._inflate.on(`data`,h)}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`,m)}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)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(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`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),So=e.__commonJSMin(((e,t)=>{let{isUtf8:n}=require(`buffer`),{hasBlob:r}=vo(),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=require(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),Co=e.__commonJSMin(((e,t)=>{let{Writable:n}=require(`stream`),r=xo(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=vo(),{concat:c,toArrayBuffer:l,unmask:u}=yo(),{isValidStatusCode:d,isValidUTF8:f}=So(),p=Buffer[Symbol.species];t.exports=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}}})),wo=e.__commonJSMin(((e,t)=>{let{Duplex:n}=require(`stream`),{randomFillSync:r}=require(`crypto`),i=xo(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=vo(),{isBlob:c,isValidStatusCode:l}=So(),{mask:u,toBuffer:d}=yo(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=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(_,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(v,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){_(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)}};function _(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 v(e,t,n){_(e,t,n),e.onerror(t)}})),To=e.__commonJSMin(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=vo(),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}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{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,g(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,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(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}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),Eo=e.__commonJSMin(((e,t)=>{let{tokenChars:n}=So();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}})),Do=e.__commonJSMin(((e,t)=>{let n=require(`events`),r=require(`https`),i=require(`http`),a=require(`net`),o=require(`tls`),{randomBytes:s,createHash:c}=require(`crypto`),{Duplex:l,Readable:u}=require(`stream`),{URL:d}=require(`url`),f=xo(),p=Co(),m=wo(),{isBlob:h}=So(),{BINARY_TYPES:g,EMPTY_BUFFER:_,GUID:v,kForOnEventAttribute:y,kListener:b,kStatusCode:x,kWebSocket:S,NOOP:C}=vo(),{EventTarget:{addEventListener:w,removeEventListener:T}}=To(),{format:E,parse:D}=Eo(),{toBuffer:O}=yo(),k=Symbol(`kAborted`),A=[8,13],j=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var N=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]),P(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`,ne),i.on(`ping`,re),i.on(`pong`,H),a.onerror=ie,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,ae),t.on(`data`,oe),t.on(`end`,se),t.on(`error`,ce),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())}),W(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(N,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N.prototype,`CONNECTING`,{enumerable:!0,value:j.indexOf(`CONNECTING`)}),Object.defineProperty(N,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N.prototype,`OPEN`,{enumerable:!0,value:j.indexOf(`OPEN`)}),Object.defineProperty(N,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N.prototype,`CLOSING`,{enumerable:!0,value:j.indexOf(`CLOSING`)}),Object.defineProperty(N,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),Object.defineProperty(N.prototype,`CLOSED`,{enumerable:!0,value:j.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(N.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(N.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})}})}),N.prototype.addEventListener=w,N.prototype.removeEventListener=T,t.exports=N;function P(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;F(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:ee),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`||!M.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,F(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}`);F(e,t);return}P(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!==N.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 F(e,t){e._readyState=N.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function ee(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=N.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(F,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`,oe),process.nextTick(U,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`,oe),process.nextTick(U,t._socket),t.close(e[x])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function V(){this[S].emitClose()}function ne(e,t){this[S].emit(`message`,e,t)}function re(e){let t=this[S];t._autoPong&&t.pong(e,!this._isServer,C),t.emit(`ping`,e)}function H(e){this[S].emit(`pong`,e)}function U(e){e.resume()}function ie(e){let t=this[S];t.readyState!==N.CLOSED&&(t.readyState===N.OPEN&&(t._readyState=N.CLOSING,W(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function W(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function ae(){let e=this[S];this.removeListener(`close`,ae),this.removeListener(`data`,oe),this.removeListener(`end`,se),e._readyState=N.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`,V),e._receiver.on(`finish`,V))}function oe(e){this[S]._receiver.write(e)||this.pause()}function se(){let e=this[S];e._readyState=N.CLOSING,e._receiver.end(),this.end()}function ce(){let e=this[S];this.removeListener(`error`,ce),this.on(`error`,C),e&&(e._readyState=N.CLOSING,this.destroy())}})),Oo=e.__commonJSMin(((e,t)=>{Do();let{Duplex:n}=require(`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})),ko=e.__commonJSMin(((e,t)=>{let{tokenChars:n}=So();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}})),Ao=e.__commonJSMin(((e,t)=>{let n=require(`events`),r=require(`http`),{Duplex:i}=require(`stream`),{createHash:a}=require(`crypto`),o=Eo(),s=xo(),c=ko(),l=Do(),{GUID:u,kWebSocket:d}=vo(),f=/^[+/0-9A-Za-z]{22}==$/;t.exports=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=p(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(m,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(m,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{m(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`,h);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){_(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){_(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!f.test(i)){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){_(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){g(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{_(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{_(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 g(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return g(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 g(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
|
|
131
131
|
`).join(`\r
|
|
132
132
|
`)),i.removeListener(`error`,h),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(m,this)})),l(p,r)}};function p(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 m(e){e._state=2,e.emit(`close`)}function h(){this.destroy()}function g(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
|
|
133
133
|
`)+`\r
|
|
134
134
|
\r
|
|
135
|
-
`+n)}function _(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,_),e.emit(`wsClientError`,r,n,t)}else g(n,r,i,a)}})),jo=e.__toESM(Oo(),1),Mo=e.__toESM(Co(),1),No=e.__toESM(wo(),1),Po=e.__toESM(Do(),1),Fo=e.__toESM(Ao(),1),Io=Object.create,Lo=Object.defineProperty,Ro=Object.getOwnPropertyDescriptor,zo=Object.getOwnPropertyNames,Bo=Object.getPrototypeOf,Vo=Object.prototype.hasOwnProperty,Z=(e,t)=>function(){return t||(0,e[zo(e)[0]])((t={exports:{}}).exports,t),t.exports},Ho=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=zo(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Vo.call(e,s)&&s!==n&&Lo(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ro(t,s))||r.enumerable});return e},Uo=(e,t,n)=>(n=e==null?{}:Io(Bo(e)),Ho(t||!e||!e.__esModule?Lo(n,`default`,{value:e,enumerable:!0}):n,e)),Wo=(0,_.createRequire)(require(`url`).pathToFileURL(__filename).href),Go=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=[]}};let Ko=function(e){return e[e.DATA=0]=`DATA`,e[e.CLOSE=1]=`CLOSE`,e[e.ERROR=2]=`ERROR`,e}({}),qo=function(e){return e[e.NEW=1]=`NEW`,e}({});var Jo=class{static MAX_POOL_SIZE=100;static COMMON_SIZES=[64,256,1024,4096,16384];static pools=new Map;static{for(let e of this.COMMON_SIZES)this.pools.set(e,[])}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}}},Yo=class e{static HEADER_SIZE=4;static MAX_FRAME_SIZE=1024*1024-e.HEADER_SIZE;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=Jo.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=Jo.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){Jo.release(e)}static getMaxPayloadSize(){return e.MAX_FRAME_SIZE}},Xo=class{_onData;_onClose;_onError;_disposed=!1;_id;constructor(e,t,n){this.send=t,this.sendTypedCb=n,this._id=e}get id(){return this._id}get onData(){return this._onData||=new Go,this._onData.event}get onClose(){return this._onClose||=new Go,this._onClose.event}get onError(){return this._onError||=new Go,this._onError.event}write(e,t=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let n=Yo.getMaxPayloadSize();if(e.length<=n){this.send({streamId:this.id,type:Ko.DATA,flags:t?qo.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:Ko.DATA,flags:t&&i?qo.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=Yo.getMaxPayloadSize()-1;if(t.length<=r){this.sendTypedCb(this.id,n?qo.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?qo.NEW:0,e,c),i+=s,a=!1}}close(){this._disposed||(this.send({streamId:this.id,type:Ko.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(e){this._disposed||this.send({streamId:this.id,type:Ko.ERROR,flags:0,payload:new TextEncoder().encode(e)})}_handleFrame(e){if(!this._disposed)switch(e.type){case Ko.DATA:this._onData?.emit(e.payload);break;case Ko.CLOSE:this._onClose?.emit(),this._dispose();break;case Ko.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}},Zo=class{static MAX_POOL_SIZE=200;static pool=[];static acquire(e,t,n){let r=this.pool.pop();return r?(r._reset(e,t,n),r):new Xo(e,t,n)}static release(e){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(e)}},Qo=class{_onNextStreamIDChange=new Go;onNextStreamIDChange=this._onNextStreamIDChange.event;_onStream=new Go;onStream=this._onStream.event;streams=[];streamCount=0;nextStreamId=1;send;releaseAfterSend;constructor(e){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=Zo.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=Yo.encode(e);try{this.send(t)}finally{this.releaseAfterSend&&Yo.releaseBuffer(t)}}sendFrameTyped(e,t,n,r){let i=Yo.encodeTyped(e,Ko.DATA,n,t,r);try{this.send(i)}finally{this.releaseAfterSend&&Yo.releaseBuffer(i)}}handleMessage(e){this.handleFrame(Yo.decode(e))}handleFrame(e){let t=this.streams[e.streamId];(!t||t.disposed)&&(t=Zo.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===Ko.CLOSE||e.type===Ko.ERROR)&&(this.streams[e.streamId]=void 0,this.streamCount--,Zo.release(t))}get activeStreamCount(){return this.streamCount}dispose(){for(let e of this.streams)e&&!e.disposed&&(e.close(),Zo.release(e));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}};const $o=`End-Of-Stream`;var es=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},ts=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},ns=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 es;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 ts;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new es;return n}},rs=class extends ns{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},os=class extends rs{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}},ss=class extends ns{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 es;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function cs(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new ss(t):new os(t)}catch(t){if(t instanceof TypeError)return new ss(e.getReader());throw t}}var ls=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 es;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 es;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new es;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new es;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()}};const us=256e3;var ds=class extends ls{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 es;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 es)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new es}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}},fs=class extends ls{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 es;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 ps(e,t){let n=cs(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new ds(n,r)}function ms(e,t){return new fs(e,t)}const hs={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:`Ÿ`},gs={};for(let[e,t]of Object.entries(hs))gs[t]=Number.parseInt(e);function _s(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?vs(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return ys(e);case`ascii`:return bs(e);case`latin1`:case`iso-8859-1`:return xs(e);case`windows-1252`:return Ss(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function vs(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 ys(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function bs(e){return String.fromCharCode(...e.map(e=>e&127))}function xs(e){return String.fromCharCode(...e)}function Ss(e){let t=``;for(let n of e)n>=128&&n<=159&&hs[n]?t+=hs[n]:t+=String.fromCharCode(n);return t}function Cs(e){return new DataView(e.buffer,e.byteOffset)}const ws={len:1,get(e,t){return Cs(e).getUint8(t)},put(e,t,n){return Cs(e).setUint8(t,n),t+1}},Ts={len:2,get(e,t){return Cs(e).getUint16(t,!0)},put(e,t,n){return Cs(e).setUint16(t,n,!0),t+2}},Es={len:2,get(e,t){return Cs(e).getUint16(t)},put(e,t,n){return Cs(e).setUint16(t,n),t+2}},Ds={len:4,get(e,t){return Cs(e).getUint32(t,!0)},put(e,t,n){return Cs(e).setUint32(t,n,!0),t+4}},Os={len:4,get(e,t){return Cs(e).getUint32(t)},put(e,t,n){return Cs(e).setUint32(t,n),t+4}},ks={len:4,get(e,t){return Cs(e).getInt32(t)},put(e,t,n){return Cs(e).setInt32(t,n),t+4}},As={len:8,get(e,t){return Cs(e).getBigUint64(t,!0)},put(e,t,n){return Cs(e).setBigUint64(t,n,!0),t+8}};var js=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return _s(n,this.encoding)}},Ms=(0,a.createRequire)(`/`);try{Ms(`worker_threads`).Worker}catch{}var Ns=Uint8Array,Ps=Uint16Array,Fs=Int32Array,Is=new Ns([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]),Ls=new Ns([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]),Rs=new Ns([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),zs=function(e,t){for(var n=new Ps(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Fs(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}},Bs=zs(Is,2),Vs=Bs.b,Hs=Bs.r;Vs[28]=258,Hs[258]=28;var Us=zs(Ls,0),Ws=Us.b;Us.r;for(var Gs=new Ps(32768),Ks=0;Ks<32768;++Ks){var qs=(Ks&43690)>>1|(Ks&21845)<<1;qs=(qs&52428)>>2|(qs&13107)<<2,qs=(qs&61680)>>4|(qs&3855)<<4,Gs[Ks]=((qs&65280)>>8|(qs&255)<<8)>>1}for(var Js=(function(e,t,n){for(var r=e.length,i=0,a=new Ps(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Ps(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Ps(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[Gs[d]>>c]=l}else for(s=new Ps(r),i=0;i<r;++i)e[i]&&(s[i]=Gs[o[e[i]-1]++]>>15-e[i]);return s}),Ys=new Ns(288),Ks=0;Ks<144;++Ks)Ys[Ks]=8;for(var Ks=144;Ks<256;++Ks)Ys[Ks]=9;for(var Ks=256;Ks<280;++Ks)Ys[Ks]=7;for(var Ks=280;Ks<288;++Ks)Ys[Ks]=8;for(var Xs=new Ns(32),Ks=0;Ks<32;++Ks)Xs[Ks]=5;var Zs=Js(Ys,9,1),Qs=Js(Xs,5,1),$s=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},ec=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},tc=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},nc=function(e){return(e+7)/8|0},rc=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Ns(e.subarray(t,n))},ic=[`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`],ac=function(e,t,n){var r=Error(t||ic[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,ac),!n)throw r;return r},oc=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new Ns(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new Ns(i*3));var l=function(e){var t=n.length;if(e>t){var r=new Ns(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=ec(e,d,1);var v=ec(e,d+1,3);if(d+=3,v)if(v==1)p=Zs,m=Qs,h=9,g=5;else if(v==2){var y=ec(e,d,31)+257,b=ec(e,d+10,15)+4,x=y+ec(e,d+5,31)+1;d+=14;for(var S=new Ns(x),C=new Ns(19),w=0;w<b;++w)C[Rs[w]]=ec(e,d+w*3,7);d+=b*3;for(var T=$s(C),E=(1<<T)-1,D=Js(C,T,1),w=0;w<x;){var O=D[ec(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+ec(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+ec(e,d,7),d+=3):k==18&&(j=11+ec(e,d,127),d+=7);j--;)S[w++]=A}}var M=S.subarray(0,y),N=S.subarray(y);h=$s(M),g=$s(N),p=Js(M,h,1),m=Js(N,g,1)}else ac(1);else{var k=nc(d)+4,P=e[k-4]|e[k-3]<<8,F=k+P;if(F>i){c&&ac(0);break}s&&l(f+P),n.set(e.subarray(k,F),f),t.b=f+=P,t.p=d=F*8,t.f=u;continue}if(d>_){c&&ac(0);break}}s&&l(f+131072);for(var ee=(1<<h)-1,I=(1<<g)-1,L=d;;L=d){var A=p[tc(e,d)&ee],R=A>>4;if(d+=A&15,d>_){c&&ac(0);break}if(A||ac(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=Is[w];te=ec(e,d,(1<<z)-1)+Vs[w],d+=z}var B=m[tc(e,d)&I],V=B>>4;B||ac(3),d+=B&15;var N=Ws[V];if(V>3){var z=Ls[V];N+=tc(e,d)&(1<<z)-1,d+=z}if(d>_){c&&ac(0);break}s&&l(f+131072);var ne=f+te;if(f<N){var re=a-N,H=Math.min(N,ne);for(re+f<0&&ac(3);f<H;++f)n[f]=r[re+f]}for(;f<ne;++f)n[f]=n[f-N]}}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?rc(n,0,f):n.subarray(0,f)},sc=new Ns(0),cc=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&ac(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)},lc=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},uc=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&ac(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&ac(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function dc(e,t){return oc(e,{i:2},t&&t.out,t&&t.dictionary)}function fc(e,t){var n=cc(e);return n+8>e.length&&ac(6,`invalid gzip data`),oc(e.subarray(n,-8),{i:2},t&&t.out||new Ns(lc(e)),t&&t.dictionary)}function pc(e,t){return oc(e.subarray(uc(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function mc(e,t){return e[0]==31&&e[1]==139&&e[2]==8?fc(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?dc(e,t):pc(e,t)}var hc=typeof TextDecoder<`u`&&new TextDecoder;try{hc.decode(sc,{stream:!0})}catch{}var gc=Z({"../../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`:``)}})}),_c=Z({"../../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=gc(),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})}),vc=Z({"../../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=_c()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),yc=Z({"../../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)}})}),bc=Z({"../../node_modules/supports-color/index.js":((e,t)=>{let n=Wo(`os`),r=Wo(`tty`),i=yc(),{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);function s(){if(`FORCE_COLOR`in a)return a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(a.FORCE_COLOR,10),3)}function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let c=s();c!==void 0&&(o=c);let l=r?o:c;if(l===0)return 0;if(r){if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2}if(e&&!t&&l===void 0)return 0;let u=l||0;if(a.TERM===`dumb`)return u;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`,`DRONE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:u;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=Number.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:u}function u(e,t={}){let n=l(e,{streamIsTTY:e&&e.isTTY,...t});return c(n)}t.exports={supportsColor:u,stdout:u({isTTY:r.isatty(1)}),stderr:u({isTTY:r.isatty(2)})}})}),xc=Z({"../../node_modules/debug/src/node.js":((e,t)=>{let n=Wo(`tty`),r=Wo(`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=bc();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(`
|
|
135
|
+
`+n)}function _(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,_),e.emit(`wsClientError`,r,n,t)}else g(n,r,i,a)}})),jo=e.__toESM(Oo(),1),Mo=e.__toESM(Co(),1),No=e.__toESM(wo(),1),Po=e.__toESM(Do(),1),Fo=e.__toESM(Ao(),1),Io=Object.create,Lo=Object.defineProperty,Ro=Object.getOwnPropertyDescriptor,zo=Object.getOwnPropertyNames,Bo=Object.getPrototypeOf,Vo=Object.prototype.hasOwnProperty,Z=(e,t)=>function(){return t||(0,e[zo(e)[0]])((t={exports:{}}).exports,t),t.exports},Ho=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=zo(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Vo.call(e,s)&&s!==n&&Lo(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ro(t,s))||r.enumerable});return e},Uo=(e,t,n)=>(n=e==null?{}:Io(Bo(e)),Ho(t||!e||!e.__esModule?Lo(n,`default`,{value:e,enumerable:!0}):n,e)),Wo=(0,_.createRequire)(require(`url`).pathToFileURL(__filename).href),Go=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=[]}};let Ko=function(e){return e[e.DATA=0]=`DATA`,e[e.CLOSE=1]=`CLOSE`,e[e.ERROR=2]=`ERROR`,e}({}),qo=function(e){return e[e.NEW=1]=`NEW`,e}({});var Jo=class{static MAX_POOL_SIZE=100;static COMMON_SIZES=[64,256,1024,4096,16384];static pools=new Map;static{for(let e of this.COMMON_SIZES)this.pools.set(e,[])}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}}},Yo=class e{static HEADER_SIZE=4;static MAX_FRAME_SIZE=1024*1024-e.HEADER_SIZE;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=Jo.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=Jo.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){Jo.release(e)}static getMaxPayloadSize(){return e.MAX_FRAME_SIZE}},Xo=class{_onData;_onClose;_onError;_disposed=!1;_id;constructor(e,t,n){this.send=t,this.sendTypedCb=n,this._id=e}get id(){return this._id}get onData(){return this._onData||=new Go,this._onData.event}get onClose(){return this._onClose||=new Go,this._onClose.event}get onError(){return this._onError||=new Go,this._onError.event}write(e,t=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let n=Yo.getMaxPayloadSize();if(e.length<=n){this.send({streamId:this.id,type:Ko.DATA,flags:t?qo.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:Ko.DATA,flags:t&&i?qo.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=Yo.getMaxPayloadSize()-1;if(t.length<=r){this.sendTypedCb(this.id,n?qo.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?qo.NEW:0,e,c),i+=s,a=!1}}close(){this._disposed||(this.send({streamId:this.id,type:Ko.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(e){this._disposed||this.send({streamId:this.id,type:Ko.ERROR,flags:0,payload:new TextEncoder().encode(e)})}_handleFrame(e){if(!this._disposed)switch(e.type){case Ko.DATA:this._onData?.emit(e.payload);break;case Ko.CLOSE:this._onClose?.emit(),this._dispose();break;case Ko.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}},Zo=class{static MAX_POOL_SIZE=200;static pool=[];static acquire(e,t,n){let r=this.pool.pop();return r?(r._reset(e,t,n),r):new Xo(e,t,n)}static release(e){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(e)}},Qo=class{_onNextStreamIDChange=new Go;onNextStreamIDChange=this._onNextStreamIDChange.event;_onStream=new Go;onStream=this._onStream.event;streams=[];streamCount=0;nextStreamId=1;send;releaseAfterSend;constructor(e){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=Zo.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=Yo.encode(e);try{this.send(t)}finally{this.releaseAfterSend&&Yo.releaseBuffer(t)}}sendFrameTyped(e,t,n,r){let i=Yo.encodeTyped(e,Ko.DATA,n,t,r);try{this.send(i)}finally{this.releaseAfterSend&&Yo.releaseBuffer(i)}}handleMessage(e){this.handleFrame(Yo.decode(e))}handleFrame(e){let t=this.streams[e.streamId];(!t||t.disposed)&&(t=Zo.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===Ko.CLOSE||e.type===Ko.ERROR)&&(this.streams[e.streamId]=void 0,this.streamCount--,Zo.release(t))}get activeStreamCount(){return this.streamCount}dispose(){for(let e of this.streams)e&&!e.disposed&&(e.close(),Zo.release(e));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}};const $o=`End-Of-Stream`;var es=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},ts=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},ns=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 es;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 ts;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new es;return n}},rs=class extends ns{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},os=class extends rs{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}},ss=class extends ns{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 es;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function cs(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new ss(t):new os(t)}catch(t){if(t instanceof TypeError)return new ss(e.getReader());throw t}}var ls=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 es;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 es;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new es;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new es;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()}};const us=256e3;var ds=class extends ls{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 es;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 es)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new es}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}},fs=class extends ls{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 es;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 ps(e,t){let n=cs(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new ds(n,r)}function ms(e,t){return new fs(e,t)}const hs={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:`Ÿ`},gs={};for(let[e,t]of Object.entries(hs))gs[t]=Number.parseInt(e);function _s(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?vs(e):new globalThis.TextDecoder(`utf-8`).decode(e);case`utf-16le`:return ys(e);case`ascii`:return bs(e);case`latin1`:case`iso-8859-1`:return xs(e);case`windows-1252`:return Ss(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function vs(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 ys(e){let t=``;for(let n=0;n<e.length;n+=2)t+=String.fromCharCode(e[n]|e[n+1]<<8);return t}function bs(e){return String.fromCharCode(...e.map(e=>e&127))}function xs(e){return String.fromCharCode(...e)}function Ss(e){let t=``;for(let n of e)n>=128&&n<=159&&hs[n]?t+=hs[n]:t+=String.fromCharCode(n);return t}function Cs(e){return new DataView(e.buffer,e.byteOffset)}const ws={len:1,get(e,t){return Cs(e).getUint8(t)},put(e,t,n){return Cs(e).setUint8(t,n),t+1}},Ts={len:2,get(e,t){return Cs(e).getUint16(t,!0)},put(e,t,n){return Cs(e).setUint16(t,n,!0),t+2}},Es={len:2,get(e,t){return Cs(e).getUint16(t)},put(e,t,n){return Cs(e).setUint16(t,n),t+2}},Ds={len:4,get(e,t){return Cs(e).getUint32(t,!0)},put(e,t,n){return Cs(e).setUint32(t,n,!0),t+4}},Os={len:4,get(e,t){return Cs(e).getUint32(t)},put(e,t,n){return Cs(e).setUint32(t,n),t+4}},ks={len:4,get(e,t){return Cs(e).getInt32(t)},put(e,t,n){return Cs(e).setInt32(t,n),t+4}},As={len:8,get(e,t){return Cs(e).getBigUint64(t,!0)},put(e,t,n){return Cs(e).setBigUint64(t,n,!0),t+8}};var js=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return _s(n,this.encoding)}},Ms=(0,l.createRequire)(`/`);try{Ms(`worker_threads`).Worker}catch{}var Ns=Uint8Array,Ps=Uint16Array,Fs=Int32Array,Is=new Ns([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]),Ls=new Ns([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]),Rs=new Ns([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),zs=function(e,t){for(var n=new Ps(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Fs(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}},Bs=zs(Is,2),Vs=Bs.b,Hs=Bs.r;Vs[28]=258,Hs[258]=28;var Us=zs(Ls,0),Ws=Us.b;Us.r;for(var Gs=new Ps(32768),Ks=0;Ks<32768;++Ks){var qs=(Ks&43690)>>1|(Ks&21845)<<1;qs=(qs&52428)>>2|(qs&13107)<<2,qs=(qs&61680)>>4|(qs&3855)<<4,Gs[Ks]=((qs&65280)>>8|(qs&255)<<8)>>1}for(var Js=(function(e,t,n){for(var r=e.length,i=0,a=new Ps(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new Ps(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new Ps(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[Gs[d]>>c]=l}else for(s=new Ps(r),i=0;i<r;++i)e[i]&&(s[i]=Gs[o[e[i]-1]++]>>15-e[i]);return s}),Ys=new Ns(288),Ks=0;Ks<144;++Ks)Ys[Ks]=8;for(var Ks=144;Ks<256;++Ks)Ys[Ks]=9;for(var Ks=256;Ks<280;++Ks)Ys[Ks]=7;for(var Ks=280;Ks<288;++Ks)Ys[Ks]=8;for(var Xs=new Ns(32),Ks=0;Ks<32;++Ks)Xs[Ks]=5;var Zs=Js(Ys,9,1),Qs=Js(Xs,5,1),$s=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},ec=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},tc=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},nc=function(e){return(e+7)/8|0},rc=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Ns(e.subarray(t,n))},ic=[`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`],ac=function(e,t,n){var r=Error(t||ic[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,ac),!n)throw r;return r},oc=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new Ns(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new Ns(i*3));var l=function(e){var t=n.length;if(e>t){var r=new Ns(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=ec(e,d,1);var v=ec(e,d+1,3);if(d+=3,v)if(v==1)p=Zs,m=Qs,h=9,g=5;else if(v==2){var y=ec(e,d,31)+257,b=ec(e,d+10,15)+4,x=y+ec(e,d+5,31)+1;d+=14;for(var S=new Ns(x),C=new Ns(19),w=0;w<b;++w)C[Rs[w]]=ec(e,d+w*3,7);d+=b*3;for(var T=$s(C),E=(1<<T)-1,D=Js(C,T,1),w=0;w<x;){var O=D[ec(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+ec(e,d,3),d+=2,A=S[w-1]):k==17?(j=3+ec(e,d,7),d+=3):k==18&&(j=11+ec(e,d,127),d+=7);j--;)S[w++]=A}}var M=S.subarray(0,y),N=S.subarray(y);h=$s(M),g=$s(N),p=Js(M,h,1),m=Js(N,g,1)}else ac(1);else{var k=nc(d)+4,P=e[k-4]|e[k-3]<<8,F=k+P;if(F>i){c&&ac(0);break}s&&l(f+P),n.set(e.subarray(k,F),f),t.b=f+=P,t.p=d=F*8,t.f=u;continue}if(d>_){c&&ac(0);break}}s&&l(f+131072);for(var ee=(1<<h)-1,I=(1<<g)-1,L=d;;L=d){var A=p[tc(e,d)&ee],R=A>>4;if(d+=A&15,d>_){c&&ac(0);break}if(A||ac(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=Is[w];te=ec(e,d,(1<<z)-1)+Vs[w],d+=z}var B=m[tc(e,d)&I],V=B>>4;B||ac(3),d+=B&15;var N=Ws[V];if(V>3){var z=Ls[V];N+=tc(e,d)&(1<<z)-1,d+=z}if(d>_){c&&ac(0);break}s&&l(f+131072);var ne=f+te;if(f<N){var re=a-N,H=Math.min(N,ne);for(re+f<0&&ac(3);f<H;++f)n[f]=r[re+f]}for(;f<ne;++f)n[f]=n[f-N]}}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?rc(n,0,f):n.subarray(0,f)},sc=new Ns(0),cc=function(e){(e[0]!=31||e[1]!=139||e[2]!=8)&&ac(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)},lc=function(e){var t=e.length;return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0},uc=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&ac(6,`invalid zlib data`),(e[1]>>5&1)==+!t&&ac(6,`invalid zlib data: `+(e[1]&32?`need`:`unexpected`)+` dictionary`),(e[1]>>3&4)+2};function dc(e,t){return oc(e,{i:2},t&&t.out,t&&t.dictionary)}function fc(e,t){var n=cc(e);return n+8>e.length&&ac(6,`invalid gzip data`),oc(e.subarray(n,-8),{i:2},t&&t.out||new Ns(lc(e)),t&&t.dictionary)}function pc(e,t){return oc(e.subarray(uc(e,t&&t.dictionary),-4),{i:2},t&&t.out,t&&t.dictionary)}function mc(e,t){return e[0]==31&&e[1]==139&&e[2]==8?fc(e,t):(e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31?dc(e,t):pc(e,t)}var hc=typeof TextDecoder<`u`&&new TextDecoder;try{hc.decode(sc,{stream:!0})}catch{}var gc=Z({"../../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`:``)}})}),_c=Z({"../../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=gc(),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})}),vc=Z({"../../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=_c()(e);let{formatters:s}=t.exports;s.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}})}),yc=Z({"../../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)}})}),bc=Z({"../../node_modules/supports-color/index.js":((e,t)=>{let n=Wo(`os`),r=Wo(`tty`),i=yc(),{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);function s(){if(`FORCE_COLOR`in a)return a.FORCE_COLOR===`true`?1:a.FORCE_COLOR===`false`?0:a.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(a.FORCE_COLOR,10),3)}function c(e){return e===0?!1:{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,{streamIsTTY:t,sniffFlags:r=!0}={}){let c=s();c!==void 0&&(o=c);let l=r?o:c;if(l===0)return 0;if(r){if(i(`color=16m`)||i(`color=full`)||i(`color=truecolor`))return 3;if(i(`color=256`))return 2}if(e&&!t&&l===void 0)return 0;let u=l||0;if(a.TERM===`dumb`)return u;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`,`DRONE`].some(e=>e in a)||a.CI_NAME===`codeship`?1:u;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=Number.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:u}function u(e,t={}){let n=l(e,{streamIsTTY:e&&e.isTTY,...t});return c(n)}t.exports={supportsColor:u,stdout:u({isTTY:r.isatty(1)}),stderr:u({isTTY:r.isatty(2)})}})}),xc=Z({"../../node_modules/debug/src/node.js":((e,t)=>{let n=Wo(`tty`),r=Wo(`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=bc();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(`
|
|
136
136
|
`).join(`
|
|
137
137
|
`+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)+`
|
|
138
138
|
`)}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=_c()(e);let{formatters:d}=t.exports;d.o=function(e){return this.inspectOpts.colors=this.useColors,r.inspect(e,this.inspectOpts).split(`
|
|
@@ -143,11 +143,11 @@ ${Ta}${t.trimStart()}`),n=3+(0,u.stripVTControlCharacters)(t.trimStart()).length
|
|
|
143
143
|
`,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})})()})}),Jc=Uo(Kc(),1),Yc=Uo(qc(),1),Xc=class e{static COLUMNS=80;static ROWS=24;static SCROLLBACK=128e3;globalEnv;processes=new Map;spawnListeners=[];nodePty;constructor(e){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]})}async execute(t,n,r){let i=await Zc(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 Yc.default.Terminal({allowProposedApi:!0,convertEol:!0,scrollback:e.SCROLLBACK,cols:e.COLUMNS,rows:e.ROWS}),o=new Jc.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()})}};const Zc=async(e,t,n,r)=>{if(!r||globalThis.Bun!==void 0){let r=new Go,i=new Go,a=(0,m.spawn)(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})}),{pid:await new Promise((e,t)=>{a.on(`spawn`,()=>{e(a.pid??-1)}),a.on(`error`,e=>{t(e)})}),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 Qc=Z({"../../node_modules/events-universal/default.js":((e,t)=>{t.exports=Wo(`events`)})}),$c=Z({"../../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}}})}),el=Z({"../../node_modules/fast-fifo/index.js":((e,t)=>{let n=$c();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}}})}),tl=Z({"../../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){return b(e).readDoubleBE(t)}function w(e,t){return b(e).readDoubleLE(t)}function T(e,t){return b(e).readFloatBE(t)}function E(e,t){return b(e).readFloatLE(t)}function D(e,t){return b(e).readInt32BE(t)}function O(e,t){return b(e).readInt32LE(t)}function k(e,t){return b(e).readUInt32BE(t)}function A(e,t){return b(e).readUInt32LE(t)}function j(e,t,n){return b(e).writeDoubleBE(t,n)}function M(e,t,n){return b(e).writeDoubleLE(t,n)}function N(e,t,n){return b(e).writeFloatBE(t,n)}function P(e,t,n){return b(e).writeFloatLE(t,n)}function F(e,t,n){return b(e).writeInt32BE(t,n)}function ee(e,t,n){return b(e).writeInt32LE(t,n)}function I(e,t,n){return b(e).writeUInt32BE(t,n)}function L(e,t,n){return b(e).writeUInt32LE(t,n)}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,readDoubleBE:C,readDoubleLE:w,readFloatBE:T,readFloatLE:E,readInt32BE:D,readInt32LE:O,readUInt32BE:k,readUInt32LE:A,writeDoubleBE:j,writeDoubleLE:M,writeFloatBE:N,writeFloatLE:P,writeInt32BE:F,writeInt32LE:ee,writeUInt32BE:I,writeUInt32LE:L}})}),nl=Z({"../../node_modules/text-decoder/lib/pass-through-decoder.js":((e,t)=>{let n=tl();t.exports=class{constructor(e){this.encoding=e}get remaining(){return 0}decode(e){return n.toString(e,this.encoding)}flush(){return``}}})}),rl=Z({"../../node_modules/text-decoder/lib/utf8-decoder.js":((e,t)=>{let n=tl();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}}})}),il=Z({"../../node_modules/text-decoder/index.js":((e,t)=>{let n=nl(),r=rl();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)}}})}),al=Z({"../../node_modules/streamx/index.js":((e,t)=>{let{EventEmitter:n}=Qc(),r=Error(`Stream was destroyed`),i=Error(`Premature close`),a=el(),o=il(),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,M=512<<18,N=1024<<18;c^(C|j);let P=c^T;c^(C|M),c^D,c^E;let F=c^A;c^w;let ee=c^N,I=16|C,L=c^I,R=m|O,te=14|R;P&536870847;let z=A|h;z&L;let B=33587215;u|16399;let V=m|143;u|143,u|16398,h|1,M|8388623,E|D,E|C;let ne=270794767;T|C,C|j,O|134217742;let re=Symbol.asyncIterator||Symbol(`asyncIterator`);var H=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||Me,this.map=r||n,this.afterWrite=ce.bind(this),this.afterUpdateNextTick=de.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|M)&P}autoBatch(e,t){let n=[],r=this.stream;for(n.push(e);(r._duplexState&ne)===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&ne)===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)===M){e._duplexState|=C,e._final(oe.bind(this));return}if((e._duplexState&14)==4){(e._duplexState&z)===0&&(e._duplexState|=I,e._destroy(se.bind(this)));return}(e._duplexState&B)===1&&(e._duplexState=(e._duplexState|I)&l,e._open(G.bind(this)))}continueUpdate(){return(this.stream._duplexState&A)===0?!1:(this.stream._duplexState&=F,!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))}},U=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||Me,this.map=r||n,this.pipeTo=null,this.afterRead=le.bind(this),this.afterUpdateNextTick=ue.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 W(this.stream,e,t),t&&this.stream.on(`error`,Ne),Te(e))e._writableState.pipeline=this.pipeline,t&&e.on(`error`,Ne),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`,ae.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&V)===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&V)===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(se.bind(this)));return}(e._duplexState&B)===1&&(e._duplexState=(e._duplexState|I)&l,e._open(G.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))}},ie=class{constructor(e){this.data=null,this.afterTransform=pe.bind(e),this.afterFinal=null}},W=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 ae(){this.stream._duplexState|=512,this.updateCallback()}function oe(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 se(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 ce(e){let t=this.stream;e&&t.destroy(e),t._duplexState&=469499903,this.drains!==null&&fe(this.drains),(t._duplexState&6553615)===D&&(t._duplexState&=532676607,(t._duplexState&k)===k&&t.emit(`drain`)),this.updateCallback()}function le(e){e&&this.stream.destroy(e),this.stream._duplexState&=536870895,this.readAhead===!1&&!(this.stream._duplexState&256)&&(this.stream._duplexState&=S),this.updateCallback()}function ue(){this.stream._duplexState&32||(this.stream._duplexState&=x,this.update())}function de(){(this.stream._duplexState&w)===0&&(this.stream._duplexState&=F,this.update())}function fe(e){for(let t=0;t<e.length;t++)--e[t].writes===0&&(e.shift().resolve(!0),t--)}function G(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 pe(e,t){t!=null&&this.push(t),this._writableState.afterWrite(e)}function me(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 he=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`,Pe.bind(this))),this.on(`newListener`,me)}_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())}},ge=class e extends he{constructor(e){super(e),this._duplexState|=O|131073,this._readableState=new U(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||Ce;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(ke(t))return t;if(t[re])return this._fromAsyncIterator(t[re](),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}[re](){let e=this,t=null,n=null,i=null;return this.on(`error`,e=>{t=e}),this.on(`readable`,a),this.on(`close`,o),{[re](){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})})})}}},K=class extends he{constructor(e){super(e),this._duplexState|=1|m,this._writableState=new H(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|=N}uncork(){this._duplexState&=ee,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=(Fe(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}},_e=class extends ge{constructor(e){super(e),this._duplexState=1|this._duplexState&_,this._writableState=new H(this,e),e&&(e.writev&&(this._writev=e.writev),e.write&&(this._write=e.write),e.final&&(this._final=e.final))}cork(){this._duplexState|=N}uncork(){this._duplexState&=ee,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}},ve=class extends _e{constructor(e){super(e),this._transformState=new ie(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(be.bind(this))}},ye=class extends ve{};function be(e,t){let n=this._transformState.afterFinal;if(e)return n(e);t!=null&&this.push(t),this.push(null),n(null)}function xe(...e){return new Promise((t,n)=>Se(...e,e=>{if(e)return n(e);t()}))}function Se(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],Te(a)?a.pipe(o,l):(c(a,!0,e>1,l),a.pipe(o)),a=o;if(r){let e=!1,t=Te(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 Ce(e){return e}function we(e){return!!e._readableState||!!e._writableState}function Te(e){return typeof e._duplexState==`number`&&we(e)}function Ee(e){return!!e._readableState&&e._readableState.ended}function De(e){return!!e._writableState&&e._writableState.ended}function Oe(e,t={}){let n=e._readableState&&e._readableState.error||e._writableState&&e._writableState.error;return!t.all&&n===r?null:n}function ke(e){return Te(e)&&e.readable}function Ae(e){return(e._duplexState&1)!=1||(e._duplexState&z)!==0}function je(e){return typeof e==`object`&&!!e&&typeof e.byteLength==`number`}function Me(e){return je(e)?e.byteLength:1024}function Ne(){}function Pe(){this.destroy(Error(`Stream aborted.`))}function Fe(e){return e._writev!==K.prototype._writev&&e._writev!==_e.prototype._writev}t.exports={pipeline:Se,pipelinePromise:xe,isStream:we,isStreamx:Te,isEnded:Ee,isFinished:De,isDisturbed:Ae,getStreamError:Oe,Stream:he,Writable:K,Readable:ge,Duplex:_e,Transform:ve,PassThrough:ye}})}),ol=Z({"../../node_modules/tar-stream/headers.js":(e=>{let t=tl(),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+`
|
|
144
144
|
`)),e.linkname&&(n+=y(` linkpath=`+e.linkname+`
|
|
145
145
|
`));let r=e.pax;if(r)for(let e in r)n+=y(` `+e+`=`+r[e]+`
|
|
146
|
-
`);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}})}),sl=Z({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=al(),a=el(),o=tl(),s=ol(),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}})}),cl=Z({"../../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=Wo(`fs`).constants||n}catch{t.exports=n}})}),ll=Z({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=al(),a=tl(),o=cl(),s=ol(),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)}})}),ul=Uo(Z({"../../node_modules/tar-stream/index.js":(e=>{e.extract=sl(),e.pack=ll()})})(),1);const dl=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await b.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=ul.pack(),i=async(e,t=``)=>{let n=await b.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 b.readlink(n);r.entry({name:o,type:`symlink`,linkname:e});continue}if(a.isFile()){let e=await b.stat(n);await new Promise((t,i)=>{let a=(0,c.createReadStream)(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){a.on(`data`,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))}}),a.once(`error`,t=>{s||(s=!0,e.error(t instanceof Error?t:Error(String(t))))}),a.once(`end`,()=>{s||(s=!0,e.close())})},cancel(){try{a.destroy()}catch{}}})};var fl=Z({"../../node_modules/dotenv/package.json":((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,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 tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,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}}})}),pl=Uo(Z({"../../node_modules/dotenv/lib/main.js":((e,t)=>{let n=Wo(`fs`),r=Wo(`path`),i=Wo(`os`),a=Wo(`crypto`),o=fl().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
146
|
+
`);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}})}),sl=Z({"../../node_modules/tar-stream/extract.js":((e,t)=>{let{Writable:n,Readable:r,getStreamError:i}=al(),a=el(),o=tl(),s=ol(),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}})}),cl=Z({"../../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=Wo(`fs`).constants||n}catch{t.exports=n}})}),ll=Z({"../../node_modules/tar-stream/pack.js":((e,t)=>{let{Readable:n,Writable:r,getStreamError:i}=al(),a=tl(),o=cl(),s=ol(),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)}})}),ul=Uo(Z({"../../node_modules/tar-stream/index.js":(e=>{e.extract=sl(),e.pack=ll()})})(),1);const dl=async(e,t)=>{let{maxBytes:n=50*1024*1024}=t??{};if(!(await b.stat(e)).isDirectory())throw Error(`Path is not a directory: ${e}`);let r=ul.pack(),a=async(e,t=``)=>{let n=await b.readdir(e,{withFileTypes:!0});for(let o of n){let n=`${e}/${o.name}`,s=t?`${t}/${o.name}`:o.name;if(o.isDirectory()){r.entry({name:`${s}/`,type:`directory`}),await a(n,s);continue}if(o.isSymbolicLink?.()){let e=await b.readlink(n);r.entry({name:s,type:`symlink`,linkname:e});continue}if(o.isFile()){let e=await b.stat(n);await new Promise((t,a)=>{let o=(0,i.createReadStream)(n),c=r.entry({name:s,size:e.size,mode:e.mode,mtime:e.mtime},e=>{e&&a(e)});o.on(`error`,a),o.on(`data`,e=>c.write(e)),o.on(`end`,()=>{c.end(),t()})});continue}}};(async()=>{try{await a(e),r.finalize()}catch(e){r.destroy(e)}})();let o=r,s=0,c=!1;return new ReadableStream({start(e){o.on(`data`,t=>{if(!c){if(s+=t.length,s>n){c=!0,e.error(Error(`Archive exceeds size limit (${n} bytes). Emitted=${s} bytes.`));try{o.destroy()}catch{}return}e.enqueue(new Uint8Array(t))}}),o.once(`error`,t=>{c||(c=!0,e.error(t instanceof Error?t:Error(String(t))))}),o.once(`end`,()=>{c||(c=!0,e.close())})},cancel(){try{o.destroy()}catch{}}})};var fl=Z({"../../node_modules/dotenv/package.json":((e,t)=>{t.exports={name:`dotenv`,version:`17.2.3`,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 tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000`,"test:coverage":`tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov`,prerelease:`npm test`,release:`standard-version`},repository:{type:`git`,url:`git://github.com/motdotla/dotenv.git`},homepage:`https://github.com/motdotla/dotenv#readme`,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}}})}),pl=Uo(Z({"../../node_modules/dotenv/lib/main.js":((e,t)=>{let n=Wo(`fs`),r=Wo(`path`),i=Wo(`os`),a=Wo(`crypto`),o=fl().version,s=[`🔐 encrypt with Dotenvx: https://dotenvx.com`,`🔐 prevent committing .env to code: https://dotenvx.com/precommit`,`🔐 prevent building .env in docker: https://dotenvx.com/prebuild`,`📡 add observability to secrets: https://dotenvx.com/ops`,`👥 sync secrets across teammates & machines: https://dotenvx.com/ops`,`🗂️ backup and recover secrets: https://dotenvx.com/ops`,`✅ audit secrets and track compliance: https://dotenvx.com/ops`,`🔄 add secrets lifecycle management: https://dotenvx.com/ops`,`🔑 add access controls to secrets: https://dotenvx.com/ops`,"🛠️ run anywhere with `dotenvx run -- yourcommand`",`⚙️ specify custom .env file path with { path: '/custom/path/.env' }`,`⚙️ enable debug logging with { debug: true }`,`⚙️ override existing env vars with { override: true }`,`⚙️ suppress all logs with { quiet: true }`,`⚙️ write to custom object with { processEnv: myObject }`,`⚙️ load multiple .env files with { path: ['.env.local', '.env'] }`];function c(){return s[Math.floor(Math.random()*s.length)]}function l(e){return typeof e==`string`?![`false`,`0`,`no`,`off`,``].includes(e.toLowerCase()):!!e}function u(){return process.stdout.isTTY}function d(e){return u()?`\x1b[2m${e}\x1b[0m`:e}let f=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function p(e){let t={},n=e.toString();n=n.replace(/\r\n?/gm,`
|
|
147
147
|
`);let r;for(;(r=f.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,`
|
|
148
|
-
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(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 y(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 b(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 x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${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 E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};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],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})})(),1);const ml=(e,t)=>e.length<=t?e:e.slice(e.length-t),hl=(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 gl=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;proxyOnly;fetchProxyRequest;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new Qo({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new Xc({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=Yo.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 Za.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 Za.PROXY_INIT:{let t=$a[Za.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 Po.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(Qa.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(Qa.PROXY_WEBSOCKET_MESSAGE,Ya(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(Qa.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 Za.PROXY_WEBSOCKET_MESSAGE:{let e=Xa(n,this.decoder);r.send(e);break}case Za.PROXY_WEBSOCKET_CLOSE:{let e=$a[Za.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 Za.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,redirect:`manual`},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(Qa.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,u=Yo.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(Qa.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(Qa.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=no[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{if(t.payload.env_file){let e=await o.readFile(t.payload.env_file,`utf-8`),n=(0,pl.parse)(e);t.payload.env={...t.payload.env,...n}}let n=await 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=hl(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 dl(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 o.readFile(t.payload.path),r=await Hc(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(`
|
|
149
|
-
`),a=Math.max(0,(t.payload.line_start??1)-1),
|
|
150
|
-
`),mime_type:`text/plain`,total_lines:i.length,lines_read:
|
|
148
|
+
`),n=n.replace(/\\r/g,`\r`)),t[e]=n}return t}function m(e){e||={};let t=b(e);e.path=t;let n=D.configDotenv(e);if(!n.parsed){let e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code=`MISSING_DATA`,e}let r=v(e).split(`,`),i=r.length,a;for(let e=0;e<i;e++)try{let t=r[e].trim(),i=y(n,t);a=D.decrypt(i.ciphertext,i.key);break}catch(t){if(e+1>=i)throw t}return D.parse(a)}function h(e){console.error(`[dotenv@${o}][WARN] ${e}`)}function g(e){console.log(`[dotenv@${o}][DEBUG] ${e}`)}function _(e){console.log(`[dotenv@${o}] ${e}`)}function v(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 y(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 b(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 x(e){return e[0]===`~`?r.join(i.homedir(),e.slice(1)):e}function S(e){let t=l(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=l(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(t||!n)&&_(`Loading env from encrypted .env.vault`);let r=D._parseVault(e),i=process.env;return e&&e.processEnv!=null&&(i=e.processEnv),D.populate(i,r,e),{parsed:r}}function C(e){let t=r.resolve(process.cwd(),`.env`),i=`utf8`,a=process.env;e&&e.processEnv!=null&&(a=e.processEnv);let o=l(a.DOTENV_CONFIG_DEBUG||e&&e.debug),s=l(a.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?i=e.encoding:o&&g(`No encoding is specified. UTF-8 is used by default`);let u=[t];if(e&&e.path)if(!Array.isArray(e.path))u=[x(e.path)];else{u=[];for(let t of e.path)u.push(x(t))}let f,p={};for(let t of u)try{let r=D.parse(n.readFileSync(t,{encoding:i}));D.populate(p,r,e)}catch(e){o&&g(`Failed to load ${t} ${e.message}`),f=e}let m=D.populate(a,p,e);if(o=l(a.DOTENV_CONFIG_DEBUG||o),s=l(a.DOTENV_CONFIG_QUIET||s),o||!s){let e=Object.keys(m).length,t=[];for(let e of u)try{let n=r.relative(process.cwd(),e);t.push(n)}catch(t){o&&g(`Failed to load ${e} ${t.message}`),f=t}_(`injecting env (${e}) from ${t.join(`,`)} ${d(`-- tip: ${c()}`)}`)}return f?{parsed:p,error:f}:{parsed:p}}function w(e){if(v(e).length===0)return D.configDotenv(e);let t=b(e);return t?D._configVault(e):(h(`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`),D.configDotenv(e))}function T(e,t){let n=Buffer.from(t.slice(-64),`hex`),r=Buffer.from(e,`base64`),i=r.subarray(0,12),o=r.subarray(-16);r=r.subarray(12,-16);try{let e=a.createDecipheriv(`aes-256-gcm`,n,i);return e.setAuthTag(o),`${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 E(e,t,n={}){let r=!!(n&&n.debug),i=!!(n&&n.override),a={};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],a[n]=t[n]),r&&g(i===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):(e[n]=t[n],a[n]=t[n]);return a}let D={configDotenv:C,_configVault:S,_parseVault:m,config:w,decrypt:T,parse:p,populate:E};t.exports.configDotenv=D.configDotenv,t.exports._configVault=D._configVault,t.exports._parseVault=D._parseVault,t.exports.config=D.config,t.exports.decrypt=D.decrypt,t.exports.parse=D.parse,t.exports.populate=D.populate,t.exports=D})})(),1);const ml=(e,t)=>e.length<=t?e:e.slice(e.length-t),hl=(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 gl=class{multiplexer;notificationStream;decoder=new TextDecoder;encoder=new TextEncoder;processManager;createDeploymentFromTar;proxyOnly;fetchProxyRequest;constructor(e){this.createDeploymentFromTar=e.createDeploymentFromTar,this.proxyOnly=e.proxyOnly,this.fetchProxyRequest=e.fetchProxyRequest,this.multiplexer=new Qo({send:t=>{e.send(t)}}),this.multiplexer.onStream(e=>{this.handleStream(e)}),this.notificationStream=this.multiplexer.createStream(),this.processManager=new Xc({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=Yo.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 Za.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 Za.PROXY_INIT:{let t=$a[Za.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 Po.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(Qa.PROXY_INIT,this.encoder.encode(JSON.stringify({status_code:101,status_message:`Switching Protocols`,headers:{}})))}),r.addEventListener(`message`,t=>{e.disposed||e.writeTyped(Qa.PROXY_WEBSOCKET_MESSAGE,Ya(t.data,this.encoder))}),r.addEventListener(`close`,t=>{if(e.disposed)return;let n={code:t.code,reason:t.reason};e.writeTyped(Qa.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 Za.PROXY_WEBSOCKET_MESSAGE:{let e=Xa(n,this.decoder);r.send(e);break}case Za.PROXY_WEBSOCKET_CLOSE:{let e=$a[Za.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 Za.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,redirect:`manual`},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(Qa.PROXY_INIT,this.encoder.encode(JSON.stringify(s)));let c=a.headers.get(`content-length`),l=c?parseInt(c):0,u=Yo.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(Qa.PROXY_DATA,i),t+=n}}}}finally{t.releaseLock()}}else a.body&&await a.body.pipeTo(new WritableStream({write:t=>{e.writeTyped(Qa.PROXY_DATA,t)}}));e.close()}async handleRequest(e,t,n){let r=no[t.type].safeParse(t.payload);if(!r.success)throw Error(`Invalid request payload: ${r.error.message}`);switch(t.type){case`process_execute`:{if(t.payload.env_file){let e=await p.readFile(t.payload.env_file,`utf-8`),n=(0,pl.parse)(e);t.payload.env={...t.payload.env,...n}}let n=await 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=hl(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 dl(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 p.readFile(t.payload.path),r=await Hc(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(`
|
|
149
|
+
`),a=Math.max(0,(t.payload.line_start??1)-1),o=Math.min(i.length,t.payload.line_end??i.length),s=i.slice(a,o);this.sendResponse(e,{id:t.id,payload:{content:s.join(`
|
|
150
|
+
`),mime_type:`text/plain`,total_lines:i.length,lines_read:s.length,start_line:a}});break}case`write_file`:t.payload.base64?await p.writeFile(t.payload.path,Buffer.from(t.payload.content,`base64`)):await p.writeFile(t.payload.path,t.payload.content),typeof t.payload.mode==`number`&&await p.chmod(t.payload.path,t.payload.mode),this.sendResponse(e,{id:t.id,payload:{}});break;case`read_directory`:{let n=await p.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(Qa.RESPONSE,this.encoder.encode(JSON.stringify(t)))}sendNotification(e){this.notificationStream.write(new Uint8Array([Qa.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=ml(this.processManager.readANSIOutput(i.pid),64e3),f=hl(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}};function _l(e){let t=new TextEncoder,n=new TextDecoder,r=new gl({...e,send:e=>{i.handleMessage(e)}}),i=new Qo({send:e=>{r.handleMessage(e)},isClient:!0}),a=i.createStream(),o=new _o({send:e=>{a.writeTyped(0,t.encode(e),!0)}});return a.onData(e=>{let t=e.subarray(1);o.handleMessage(n.decode(t))}),i.onStream(e=>{e.onData(e=>{let t=e.subarray(1);o.handleMessage(n.decode(t))})}),{client:o,server:r}}var vl=class{diff(e,t,n={}){let r;typeof n==`function`?(r=n,n={}):`callback`in n&&(r=n.callback);let i=this.castInput(e,n),a=this.castInput(t,n),o=this.removeEmpty(this.tokenize(i,n)),s=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,s,n,r)}diffWithOptionsObj(e,t,n,r){let i=e=>{if(e=this.postProcess(e,n),r){setTimeout(function(){r(e)},0);return}else return e},a=t.length,o=e.length,s=1,c=a+o;n.maxEditLength!=null&&(c=Math.min(c,n.maxEditLength));let l=n.timeout??1/0,u=Date.now()+l,d=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(d[0],t,e,0,n);if(d[0].oldPos+1>=o&&f+1>=a)return i(this.buildValues(d[0].lastComponent,t,e));let p=-1/0,m=1/0,h=()=>{for(let r=Math.max(p,-s);r<=Math.min(m,s);r+=2){let s,c=d[r-1],l=d[r+1];c&&(d[r-1]=void 0);let u=!1;if(l){let e=l.oldPos-r;u=l&&0<=e&&e<a}let h=c&&c.oldPos+1<o;if(!u&&!h){d[r]=void 0;continue}if(s=!h||u&&c.oldPos<l.oldPos?this.addToPath(l,!0,!1,0,n):this.addToPath(c,!1,!0,1,n),f=this.extractCommon(s,t,e,r,n),s.oldPos+1>=o&&f+1>=a)return i(this.buildValues(s.lastComponent,t,e))||!0;d[r]=s,s.oldPos+1>=o&&(m=Math.min(m,r-1)),f+1>=a&&(p=Math.max(p,r+1))}s++};if(r)(function e(){setTimeout(function(){if(s>c||Date.now()>u)return r(void 0);h()||e()},0)})();else for(;s<=c&&Date.now()<=u;){let e=h();if(e)return e}}addToPath(e,t,n,r,i){let a=e.lastComponent;return a&&!i.oneChangePerToken&&a.added===t&&a.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:a.count+1,added:t,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:a}}}extractCommon(e,t,n,r,i){let a=t.length,o=n.length,s=e.oldPos,c=s-r,l=0;for(;c+1<a&&s+1<o&&this.equals(n[s+1],t[c+1],i);)c++,s++,l++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return l&&!i.oneChangePerToken&&(e.lastComponent={count:l,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=s,c}equals(e,t,n){return n.comparator?n.comparator(e,t):e===t||!!n.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join(``)}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,n){let r=[],i;for(;e;)r.push(e),i=e.previousComponent,delete e.previousComponent,e=i;r.reverse();let a=r.length,o=0,s=0,c=0;for(;o<a;o++){let e=r[o];if(e.removed)e.value=this.join(n.slice(c,c+e.count)),c+=e.count;else{if(!e.added&&this.useLongestToken){let r=t.slice(s,s+e.count);r=r.map(function(e,t){let r=n[c+t];return r.length>e.length?r:e}),e.value=this.join(r)}else e.value=this.join(t.slice(s,s+e.count));s+=e.count,e.added||(c+=e.count)}}return r}},yl=class extends vl{};new yl;function bl(e,t){let n;for(n=0;n<e.length&&n<t.length;n++)if(e[n]!=t[n])return e.slice(0,n);return e.slice(0,n)}function xl(e,t){let n;if(!e||!t||e[e.length-1]!=t[t.length-1])return``;for(n=0;n<e.length&&n<t.length;n++)if(e[e.length-(n+1)]!=t[t.length-(n+1)])return e.slice(-n);return e.slice(-n)}function Sl(e,t,n){if(e.slice(0,t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't start with prefix ${JSON.stringify(t)}; this is a bug`);return n+e.slice(t.length)}function Cl(e,t,n){if(!t)return e+n;if(e.slice(-t.length)!=t)throw Error(`string ${JSON.stringify(e)} doesn't end with suffix ${JSON.stringify(t)}; this is a bug`);return e.slice(0,-t.length)+n}function wl(e,t){return Sl(e,t,``)}function Tl(e,t){return Cl(e,t,``)}function El(e,t){return t.slice(0,Dl(e,t))}function Dl(e,t){let n=0;e.length>t.length&&(n=e.length-t.length);let r=t.length;e.length<t.length&&(r=e.length);let i=Array(r),a=0;i[0]=0;for(let e=1;e<r;e++){for(t[e]==t[a]?i[e]=i[a]:i[e]=a;a>0&&t[e]!=t[a];)a=i[a];t[e]==t[a]&&a++}a=0;for(let r=n;r<e.length;r++){for(;a>0&&e[r]!=t[a];)a=i[a];e[r]==t[a]&&a++}return a}function Ol(e){let t;for(t=e.length-1;t>=0&&e[t].match(/\s/);t--);return e.substring(t+1)}function kl(e){let t=e.match(/^\s*/);return t?t[0]:``}const Al=`a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}`,jl=RegExp(`[${Al}]+|\\s+|[^${Al}]`,`ug`);var Ml=class extends vl{equals(e,t,n){return n.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e.trim()===t.trim()}tokenize(e,t={}){let n;if(t.intlSegmenter){let r=t.intlSegmenter;if(r.resolvedOptions().granularity!=`word`)throw Error(`The segmenter passed must have a granularity of "word"`);n=Array.from(r.segment(e),e=>e.segment)}else n=e.match(jl)||[];let r=[],i=null;return n.forEach(e=>{/\s/.test(e)?i==null?r.push(e):r.push(r.pop()+e):i!=null&&/\s/.test(i)?r[r.length-1]==i?r.push(r.pop()+e):r.push(i+e):r.push(e),i=e}),r}join(e){return e.map((e,t)=>t==0?e:e.replace(/^\s+/,``)).join(``)}postProcess(e,t){if(!e||t.oneChangePerToken)return e;let n=null,r=null,i=null;return e.forEach(e=>{e.added?r=e:e.removed?i=e:((r||i)&&Nl(n,i,r,e),n=e,r=null,i=null)}),(r||i)&&Nl(n,i,r,null),e}};new Ml;function Nl(e,t,n,r){if(t&&n){let i=kl(t.value),a=Ol(t.value),o=kl(n.value),s=Ol(n.value);if(e){let r=bl(i,o);e.value=Cl(e.value,o,r),t.value=wl(t.value,r),n.value=wl(n.value,r)}if(r){let e=xl(a,s);r.value=Sl(r.value,s,e),t.value=Tl(t.value,e),n.value=Tl(n.value,e)}}else if(n){if(e){let e=kl(n.value);n.value=n.value.substring(e.length)}if(r){let e=kl(r.value);r.value=r.value.substring(e.length)}}else if(e&&r){let n=kl(r.value),i=kl(t.value),a=Ol(t.value),o=bl(n,i);t.value=wl(t.value,o);let s=xl(wl(n,o),a);t.value=Tl(t.value,s),r.value=Sl(r.value,n,s),e.value=Cl(e.value,n,n.slice(0,n.length-s.length))}else if(r){let e=kl(r.value),n=Ol(t.value),i=El(n,e);t.value=Tl(t.value,i)}else if(e){let n=Ol(e.value),r=kl(t.value),i=El(n,r);t.value=wl(t.value,i)}}var Pl=class extends vl{tokenize(e){let t=RegExp(`(\\r?\\n)|[${Al}]+|[^\\S\\n\\r]+|[^${Al}]`,`ug`);return e.match(t)||[]}};new Pl;var Fl=class extends vl{constructor(){super(...arguments),this.tokenize=Rl}equals(e,t,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(`
|
|
151
151
|
`))&&(e=e.trim()),(!n.newlineIsToken||!t.includes(`
|
|
152
152
|
`))&&(t=t.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(`
|
|
153
153
|
`)&&(e=e.slice(0,-1)),t.endsWith(`
|
|
@@ -166,7 +166,7 @@ Use the same rules as \`execute_bash\`, but the output is returned synchronously
|
|
|
166
166
|
Output from the process will be returned along with it's exit code, duration, and whether the process is still running.
|
|
167
167
|
|
|
168
168
|
IMPORTANT: ALWAYS use this tool to determine the status of a process. NEVER use "ps".
|
|
169
|
-
`,inputSchema:v.z.object({pid:v.z.number(),timeout_ms:v.z.number().optional().describe(`The timeout in milliseconds to wait to return output. This does *not* kill the process, it simply returns early with current output of the process. Defaults to 25 seconds.`)}),async*execute(t,n){for await(let r of Ql({client:await e(),pid:t.pid,abortSignal:n.abortSignal,timeoutMs:t.timeout_ms}))yield r},toModelOutput:Xl})),read_file:Yl(({client:e})=>(0,
|
|
169
|
+
`,inputSchema:v.z.object({pid:v.z.number(),timeout_ms:v.z.number().optional().describe(`The timeout in milliseconds to wait to return output. This does *not* kill the process, it simply returns early with current output of the process. Defaults to 25 seconds.`)}),async*execute(t,n){for await(let r of Ql({client:await e(),pid:t.pid,abortSignal:n.abortSignal,timeoutMs:t.timeout_ms}))yield r},toModelOutput:Xl})),read_file:Yl(({client:e})=>(0,f.tool)({description:`Reads a file from the workspace filesystem. You can access any file directly by using this tool.
|
|
170
170
|
Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.
|
|
171
171
|
|
|
172
172
|
Usage:
|
|
@@ -178,7 +178,7 @@ Usage:
|
|
|
178
178
|
- This tool allows Blink to read images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as Blink is a multimodal LLM
|
|
179
179
|
- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.
|
|
180
180
|
- You will regularly be asked to read screenshots. If the user provides a path to a screenshot ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths like /var/folders/123/abc/T/TemporaryItems/NSIRD_screencaptureui_ZfB1tD/Screenshot.png
|
|
181
|
-
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:v.z.object({file_path:v.z.string(),line_offset:v.z.number(),line_limit:v.z.number()}),execute:async(t,n)=>await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal}),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:Yl(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:v.z.object({file_path:v.z.string(),content:v.z.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:Yl(({client:e})=>(0,
|
|
181
|
+
- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.`,inputSchema:v.z.object({file_path:v.z.string(),line_offset:v.z.number(),line_limit:v.z.number()}),execute:async(t,n)=>await(await e()).request(`read_file`,{path:t.file_path,line_start:t.line_offset,line_end:t.line_offset+t.line_limit},{signal:n.abortSignal}),toModelOutput:e=>e.mime_type?.startsWith(`image/`)?{type:`content`,value:[{type:`media`,data:e.content,mediaType:e.mime_type}]}:{type:`json`,value:e}})),write_file:Yl(({client:e})=>({description:`Write a file to the filesystem.`,inputSchema:v.z.object({file_path:v.z.string(),content:v.z.string()}),execute:async(t,n)=>{await(await e()).request(`write_file`,{path:t.file_path,content:t.content},{signal:n.abortSignal})}})),read_directory:Yl(({client:e})=>(0,f.tool)({description:`Reads a directory from the workspace filesystem.`,inputSchema:v.z.object({directory_path:v.z.string()}),execute:async(t,n)=>(await e()).request(`read_directory`,{path:t.directory_path})})),edit_file:Yl(({client:e})=>({description:`This is a tool for making multiple edits to a single file in one operation. It is built on top of the "workspace_edit_file" tool and allows you to perform multiple find-and-replace operations efficiently. Prefer this tool over the "workspace_edit_file" tool when you need to make multiple edits to the same file.
|
|
182
182
|
|
|
183
183
|
Before using this tool:
|
|
184
184
|
|
|
@@ -237,15 +237,15 @@ for await (const chunk of exa.streamAnswer(query)) {
|
|
|
237
237
|
// Handle chunks
|
|
238
238
|
}`,400);let n=t?.outputSchema;n&&Ld(n)&&(n=Rd(n));let r={query:e,stream:!1,text:t?.text??!1,model:t?.model??`exa`,systemPrompt:t?.systemPrompt,outputSchema:n,userLocation:t?.userLocation};return await this.request(`/answer`,`POST`,r)}async*streamAnswer(e,t){let n=t?.outputSchema;n&&Ld(n)&&(n=Rd(n));let r={query:e,text:t?.text??!1,stream:!0,model:t?.model??`exa`,systemPrompt:t?.systemPrompt,outputSchema:n},i=await Zd(this.baseURL+`/answer`,{method:`POST`,headers:this.headers,body:JSON.stringify(r)});if(!i.ok){let e=await i.text();throw new Id(e,i.status,new Date().toISOString())}let a=i.body?.getReader();if(!a)throw new Id(`No response body available for streaming.`,500,new Date().toISOString());let o=new TextDecoder,s=``;try{for(;;){let{done:e,value:t}=await a.read();if(e)break;s+=o.decode(t,{stream:!0});let n=s.split(`
|
|
239
239
|
`);s=n.pop()||``;for(let e of n){if(!e.startsWith(`data: `))continue;let t=e.replace(/^data:\s*/,``).trim();if(!t||t===`[DONE]`)continue;let n;try{n=JSON.parse(t)}catch{continue}let r=this.processChunk(n);(r.content||r.citations)&&(yield r)}}if(s.startsWith(`data: `)){let e=s.replace(/^data:\s*/,``).trim();if(e&&e!==`[DONE]`)try{let t=JSON.parse(e),n=this.processChunk(t);(n.content||n.citations)&&(yield n)}catch{}}}finally{a.releaseLock()}}processChunk(e){let t,n;return e.choices&&e.choices[0]&&e.choices[0].delta&&(t=e.choices[0].delta.content),e.citations&&e.citations!==`null`&&(n=e.citations.map(e=>({id:e.id,url:e.url,title:e.title,publishedDate:e.publishedDate,author:e.author,text:e.text}))),{content:t,citations:n}}async parseSSEStream(e){let t=e.body?.getReader();if(!t)throw new Id(`No response body available for streaming.`,500,new Date().toISOString());let n=new TextDecoder,r=``;return new Promise(async(e,i)=>{try{for(;;){let{done:a,value:o}=await t.read();if(a)break;r+=n.decode(o,{stream:!0});let s=r.split(`
|
|
240
|
-
`);r=s.pop()||``;for(let n of s){if(!n.startsWith(`data: `))continue;let r=n.replace(/^data:\s*/,``).trim();if(!r||r===`[DONE]`)continue;let a;try{a=JSON.parse(r)}catch{continue}switch(a.tag){case`complete`:t.releaseLock(),e(a.data);return;case`error`:{let e=a.error?.message||`Unknown error`;t.releaseLock(),i(new Id(e,500,new Date().toISOString()));return}default:break}}}i(new Id(`Stream ended without a completion event.`,500,new Date().toISOString()))}catch(e){i(e)}finally{try{t.releaseLock()}catch{}}})}};const ef=()=>{let e;if(process.env.EXA_API_KEY)e=new $d(process.env.EXA_API_KEY);else if(process.env.BLINK_INVOCATION_AUTH_TOKEN)e=new $d(process.env.BLINK_INVOCATION_AUTH_TOKEN,`https://blink.so/api/tools/exa`);else if(process.env.BLINK_TOKEN)e=new $d(process.env.BLINK_TOKEN,`https://blink.so/api/tools/exa`);else throw console.warn(`You must set the EXA_API_KEY environment variable or be authenticated with Blink to use the web search SDK.`),Error(`The EXA_API_KEY environment variable or a Blink token must be set to use the web search SDK.`);return e},tf={web_search:Su({description:`Perform a search query on the web, and retrieve the most relevant URLs/web data.`,inputSchema:v.z.object({query:v.z.string()}),execute:async({query:e})=>await ef().searchAndContents(e,{numResults:5,type:`auto`,text:{maxCharacters:3e3},livecrawl:`preferred`})})};function nf(e,
|
|
240
|
+
`);r=s.pop()||``;for(let n of s){if(!n.startsWith(`data: `))continue;let r=n.replace(/^data:\s*/,``).trim();if(!r||r===`[DONE]`)continue;let a;try{a=JSON.parse(r)}catch{continue}switch(a.tag){case`complete`:t.releaseLock(),e(a.data);return;case`error`:{let e=a.error?.message||`Unknown error`;t.releaseLock(),i(new Id(e,500,new Date().toISOString()));return}default:break}}}i(new Id(`Stream ended without a completion event.`,500,new Date().toISOString()))}catch(e){i(e)}finally{try{t.releaseLock()}catch{}}})}};const ef=()=>{let e;if(process.env.EXA_API_KEY)e=new $d(process.env.EXA_API_KEY);else if(process.env.BLINK_INVOCATION_AUTH_TOKEN)e=new $d(process.env.BLINK_INVOCATION_AUTH_TOKEN,`https://blink.so/api/tools/exa`);else if(process.env.BLINK_TOKEN)e=new $d(process.env.BLINK_TOKEN,`https://blink.so/api/tools/exa`);else throw console.warn(`You must set the EXA_API_KEY environment variable or be authenticated with Blink to use the web search SDK.`),Error(`The EXA_API_KEY environment variable or a Blink token must be set to use the web search SDK.`);return e},tf={web_search:Su({description:`Perform a search query on the web, and retrieve the most relevant URLs/web data.`,inputSchema:v.z.object({query:v.z.string()}),execute:async({query:e})=>await ef().searchAndContents(e,{numResults:5,type:`auto`,text:{maxCharacters:3e3},livecrawl:`preferred`})})};function nf(e,n,r){let i,a=s.default.createServer(t.createServerAdapter(async t=>{let o=new URL(t.url,i);if(o.pathname!==`/`)return new Response(`Not found`,{status:404});let s=o.searchParams.get(`code`);if(s)try{let e=await fetch(`https://api.github.com/app-manifests/${s}/conversions`,{method:`POST`,headers:{Accept:`application/vnd.github+json`,"User-Agent":`blink.so`,"X-GitHub-Api-Version":`2022-11-28`}});if(!e.ok){let t=await e.text();throw Error(`GitHub API error: ${e.status} ${e.statusText}${t?` - ${t}`:``}`)}let t=await e.json();return await r?.(null,t),new Response(`GitHub App created successfully! Return to your terminal to continue.`,{headers:{"Content-Type":`text/plain`}})}catch(e){let t=e instanceof Error?e:Error(String(e));try{await r?.(t,null)}catch(e){t=e instanceof Error?e:Error(String(e))}let n=t.message;return new Response(`Error: ${n}\n\nReturn to your terminal for more details.`,{status:500,headers:{"Content-Type":`text/plain`}})}finally{a.close()}let c={...e,redirect_url:i},l=`<!DOCTYPE html>
|
|
241
241
|
<html>
|
|
242
242
|
<body>
|
|
243
|
-
<form id="f" method="POST" action="${
|
|
243
|
+
<form id="f" method="POST" action="${n?`https://github.com/organizations/${n}/settings/apps/new`:`https://github.com/settings/apps/new`}">
|
|
244
244
|
<input type="hidden" name="manifest" value='${JSON.stringify(c).replace(/'/g,`'`)}' />
|
|
245
245
|
</form>
|
|
246
246
|
<script>document.getElementById('f').submit()<\/script>
|
|
247
247
|
</body>
|
|
248
|
-
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{a.on(`error`,t),a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}i=`http://127.0.0.1:${n.port}`,e(i)})})}const rf=v.z.enum([`read`,`write`]),af=v.z.union([v.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),v.z.literal(`check_run`).describe(`Check run created, completed, or requested`),v.z.literal(`check_suite`).describe(`Check suite completed or requested`),v.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),v.z.literal(`commit_comment`).describe(`Commit comment created`),v.z.literal(`create`).describe(`Branch or tag created`),v.z.literal(`delete`).describe(`Branch or tag deleted`),v.z.literal(`deployment`).describe(`Deployment created`),v.z.literal(`deployment_status`).describe(`Deployment status created`),v.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),v.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),v.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),v.z.literal(`fork`).describe(`Repository forked`),v.z.literal(`gollum`).describe(`Wiki page created or updated`),v.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),v.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),v.z.literal(`label`).describe(`Label created, edited, or deleted`),v.z.literal(`member`).describe(`Collaborator added, removed, or edited`),v.z.literal(`membership`).describe(`Team membership added or removed`),v.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),v.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),v.z.literal(`organization`).describe(`Organization member added, removed, or invited`),v.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),v.z.literal(`package`).describe(`Package published or updated`),v.z.literal(`page_build`).describe(`GitHub Pages site built`),v.z.literal(`project`).describe(`Project created, updated, or deleted`),v.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),v.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),v.z.literal(`public`).describe(`Repository visibility changed to public`),v.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),v.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),v.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),v.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),v.z.literal(`push`).describe(`Git push to a repository`),v.z.literal(`registry_package`).describe(`Registry package published or updated`),v.z.literal(`release`).describe(`Release published or edited`),v.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),v.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),v.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),v.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),v.z.literal(`star`).describe(`Repository starred or unstarred`),v.z.literal(`status`).describe(`Commit status created`),v.z.literal(`team`).describe(`Team created, deleted, or edited`),v.z.literal(`team_add`).describe(`Repository added to team`),v.z.literal(`watch`).describe(`User started watching repository`),v.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),v.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),v.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),sf=v.z.object({name:v.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:v.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:v.z.string().optional().describe(`The description of the GitHub App.`),public:v.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:v.z.object({url:v.z.url(),active:v.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:v.z.array(v.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:v.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:v.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:v.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:v.z.array(af).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:v.z.record(v.z.string(),rf).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function cf(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const lf=v.z.union([v.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),v.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),v.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),v.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),v.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),v.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),v.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),v.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),v.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),v.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),v.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),v.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),v.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),v.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),v.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),v.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),v.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),v.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),v.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),v.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),v.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),v.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),v.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),v.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),v.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),v.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),v.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),v.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),v.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),v.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),v.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),v.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),v.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),v.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),v.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),v.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),v.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),uf=v.z.union([v.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),v.z.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),v.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),v.z.literal(`channels:join`).describe(`Join public channels`),v.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),v.z.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),v.z.literal(`chat:write`).describe(`Send messages as the bot`),v.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),v.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),v.z.literal(`commands`).describe(`Add and use slash commands`),v.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),v.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),v.z.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),v.z.literal(`files:write`).describe(`Upload, edit, and delete files`),v.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),v.z.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),v.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),v.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),v.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),v.z.literal(`im:write`).describe(`Start and manage direct messages with users`),v.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),v.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),v.z.literal(`metadata.message:read`).describe(`Read message metadata`),v.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),v.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),v.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),v.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),v.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),v.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),v.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),v.z.literal(`reminders:read`).describe(`View reminders created by the bot`),v.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),v.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),v.z.literal(`usergroups:read`).describe(`View user groups and their members`),v.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),v.z.literal(`users.profile:read`).describe(`View profile information about users`),v.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),v.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),v.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),df=v.z.union([v.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),v.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),v.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),v.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),v.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),v.z.literal(`files:read`).describe(`View files on behalf of the user`),v.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),v.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),v.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),v.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),v.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),v.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),v.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),v.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),v.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),v.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),v.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),v.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),v.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),v.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),v.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),v.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),v.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),v.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),v.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),v.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),v.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),v.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),v.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),v.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),v.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),v.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),v.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),v.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),v.z.literal(`users:write`).describe(`Set presence for the user`)]),ff=v.z.object({display_information:v.z.object({name:v.z.string().describe(`The name of the Slack app.`),description:v.z.string().optional().describe(`A short description of the app.`),background_color:v.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:v.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:v.z.object({bot_user:v.z.object({display_name:v.z.string().describe(`The display name for the bot user.`),always_online:v.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:v.z.object({home_tab_enabled:v.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:v.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:v.z.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home.`),assistant_view:v.z.object({assistant_description:v.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:v.z.array(v.z.object({command:v.z.string().regex(/^\//).describe(`The command (must start with /).`),description:v.z.string().describe(`Description of the command.`),usage_hint:v.z.string().optional().describe(`Usage hint for the command.`),should_escape:v.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:v.z.array(v.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:v.z.object({redirect_urls:v.z.array(v.z.string().url()).optional().describe(`OAuth redirect URLs.`),scopes:v.z.object({bot:v.z.array(v.z.union([uf,v.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:v.z.array(v.z.union([df,v.z.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).optional().describe(`OAuth configuration for the Slack app.`),settings:v.z.object({event_subscriptions:v.z.object({request_url:v.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:v.z.array(v.z.union([lf,v.z.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:v.z.object({is_enabled:v.z.boolean().describe(`Enable interactivity.`),request_url:v.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:v.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:v.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:v.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:v.z.boolean().optional().default(!0).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function pf(e){let t=n.agent(),i,a;return t.on(`chat`,async({messages:t,context:a,chat:s})=>{let{execute_bash:c,execute_bash_sync:l,...u}=Zl,d={execute_bash:c,execute_bash_sync:l};process.env.BLINK_AUTO_APPROVE||(d=await n.tools.withApproval({messages:t,tools:d}));let f={...u,...d,...tf,create_github_app:(0,p.tool)({description:`A URL will be returned that will redirect the user to create a GitHub App.
|
|
248
|
+
</html>`;return new Response(l,{headers:{"Content-Type":`text/html`}})}));return new Promise((e,t)=>{a.on(`error`,t),a.listen(0,`127.0.0.1`,()=>{let n=a.address();if(!n||typeof n==`string`){t(Error(`Failed to get server address`));return}i=`http://127.0.0.1:${n.port}`,e(i)})})}const rf=v.z.enum([`read`,`write`]),af=v.z.union([v.z.literal(`branch_protection_rule`).describe(`Branch protection rule created, edited, or deleted`),v.z.literal(`check_run`).describe(`Check run created, completed, or requested`),v.z.literal(`check_suite`).describe(`Check suite completed or requested`),v.z.literal(`code_scanning_alert`).describe(`Code scanning alert created, fixed, or reopened`),v.z.literal(`commit_comment`).describe(`Commit comment created`),v.z.literal(`create`).describe(`Branch or tag created`),v.z.literal(`delete`).describe(`Branch or tag deleted`),v.z.literal(`deployment`).describe(`Deployment created`),v.z.literal(`deployment_status`).describe(`Deployment status created`),v.z.literal(`deployment_protection_rule`).describe(`Deployment protection rule requested`),v.z.literal(`discussion`).describe(`Discussion created, edited, or deleted`),v.z.literal(`discussion_comment`).describe(`Discussion comment created, edited, or deleted`),v.z.literal(`fork`).describe(`Repository forked`),v.z.literal(`gollum`).describe(`Wiki page created or updated`),v.z.literal(`issue_comment`).describe(`Issue comment created, edited, or deleted`),v.z.literal(`issues`).describe(`Issue opened, edited, closed, or labeled`),v.z.literal(`label`).describe(`Label created, edited, or deleted`),v.z.literal(`member`).describe(`Collaborator added, removed, or edited`),v.z.literal(`membership`).describe(`Team membership added or removed`),v.z.literal(`meta`).describe(`GitHub App webhook configuration changed`),v.z.literal(`milestone`).describe(`Milestone created, closed, or deleted`),v.z.literal(`organization`).describe(`Organization member added, removed, or invited`),v.z.literal(`org_block`).describe(`Organization blocked or unblocked a user`),v.z.literal(`package`).describe(`Package published or updated`),v.z.literal(`page_build`).describe(`GitHub Pages site built`),v.z.literal(`project`).describe(`Project created, updated, or deleted`),v.z.literal(`project_card`).describe(`Project card created, edited, or deleted`),v.z.literal(`project_column`).describe(`Project column created, updated, or deleted`),v.z.literal(`public`).describe(`Repository visibility changed to public`),v.z.literal(`pull_request`).describe(`Pull request opened, closed, edited, or synchronized`),v.z.literal(`pull_request_review`).describe(`Pull request review submitted, edited, or dismissed`),v.z.literal(`pull_request_review_comment`).describe(`Pull request review comment created or edited`),v.z.literal(`pull_request_review_thread`).describe(`Pull request review thread resolved or unresolved`),v.z.literal(`push`).describe(`Git push to a repository`),v.z.literal(`registry_package`).describe(`Registry package published or updated`),v.z.literal(`release`).describe(`Release published or edited`),v.z.literal(`repository`).describe(`Repository created, deleted, archived, or publicized`),v.z.literal(`repository_dispatch`).describe(`Custom webhook event triggered`),v.z.literal(`secret_scanning_alert`).describe(`Secret scanning alert created or resolved`),v.z.literal(`security_and_analysis`).describe(`Security features enabled or disabled`),v.z.literal(`star`).describe(`Repository starred or unstarred`),v.z.literal(`status`).describe(`Commit status created`),v.z.literal(`team`).describe(`Team created, deleted, or edited`),v.z.literal(`team_add`).describe(`Repository added to team`),v.z.literal(`watch`).describe(`User started watching repository`),v.z.literal(`workflow_dispatch`).describe(`Workflow manually triggered`),v.z.literal(`workflow_job`).describe(`Workflow job queued, started, or completed`),v.z.literal(`workflow_run`).describe(`Workflow run requested or completed`)]),sf=v.z.object({name:v.z.string().optional().describe(`The name of the GitHub App. Leave blank to let the user name it on GitHub.`),url:v.z.url().describe(`The homepage URL of the GitHub App. If unknown, set to https://blink.so.`),description:v.z.string().optional().describe(`The description of the GitHub App.`),public:v.z.boolean().optional().describe(`Whether the GitHub App is public. Always default to false unless the user explicitly requests otherwise.`),hook_attributes:v.z.object({url:v.z.url(),active:v.z.boolean().optional().default(!0)}).optional().describe(`The webhook configuration for the GitHub App.`),callback_urls:v.z.array(v.z.url()).max(10).optional().describe(`Callback URLs for the GitHub App after the user authenticates with GitHub.`),setup_url:v.z.url().optional().describe(`The URL to redirect the user to after they install the GitHub App.`),setup_on_update:v.z.boolean().optional().describe(`Whether to redirect the user to the setup URL after an update to the installed app.`),request_oauth_on_install:v.z.boolean().optional().describe(`Whether to request OAuth on install.`),default_events:v.z.array(af).optional().describe(`Webhook events sent to the webhook URL.`),default_permissions:v.z.record(v.z.string(),rf).optional().describe(`Repository and organization permissions for the GitHub App. Available permissions: actions (GitHub Actions workflows), administration (repository settings), checks (check runs), contents (repository code), deployments, environments, issues, metadata (always granted), packages, pages, pull_requests, repository_hooks (webhooks), repository_projects, secret_scanning_alerts, secrets (Actions secrets), security_events (code scanning/Dependabot), single_file, statuses (commit statuses), vulnerability_alerts (Dependabot), workflows (workflow files), members (collaborators). Values can be 'read' or 'write'.`)});function cf(e){return`https://api.slack.com/apps?new_app=1&manifest_json=${encodeURIComponent(JSON.stringify(e))}`}const lf=v.z.union([v.z.literal(`app_mention`).describe(`Bot is @mentioned in a channel or conversation. Requires scope: app_mentions:read`),v.z.literal(`app_home_opened`).describe(`User opened the app's Home tab. No additional scope required beyond bot token`),v.z.literal(`app_installed`).describe(`App was installed to a workspace. No additional scope required beyond bot token`),v.z.literal(`app_uninstalled`).describe(`App was uninstalled from a workspace. No additional scope required beyond bot token`),v.z.literal(`assistant_thread_context_changed`).describe(`Context changed in an assistant thread. Requires scope: assistant:write`),v.z.literal(`assistant_thread_started`).describe(`New assistant thread was started. Requires scope: assistant:write`),v.z.literal(`channel_archive`).describe(`Public channel was archived. Requires scope: channels:read`),v.z.literal(`channel_created`).describe(`Public channel was created. Requires scope: channels:read`),v.z.literal(`channel_deleted`).describe(`Public channel was deleted. Requires scope: channels:read`),v.z.literal(`channel_rename`).describe(`Public channel was renamed. Requires scope: channels:read`),v.z.literal(`channel_unarchive`).describe(`Public channel was unarchived. Requires scope: channels:read`),v.z.literal(`dnd_updated_user`).describe(`User's Do Not Disturb settings changed. Requires scope: dnd:read`),v.z.literal(`email_domain_changed`).describe(`Workspace's email domain changed. Requires scope: team:read`),v.z.literal(`emoji_changed`).describe(`Custom emoji was added or changed. Requires scope: emoji:read`),v.z.literal(`file_change`).describe(`File was changed. Requires scope: files:read`),v.z.literal(`file_created`).describe(`File was created. Requires scope: files:read`),v.z.literal(`file_deleted`).describe(`File was deleted. Requires scope: files:read`),v.z.literal(`file_public`).describe(`File was made public. Requires scope: files:read`),v.z.literal(`file_shared`).describe(`File was shared. Requires scope: files:read`),v.z.literal(`file_unshared`).describe(`File was unshared. Requires scope: files:read`),v.z.literal(`group_archive`).describe(`Private channel was archived. Requires scope: groups:read`),v.z.literal(`group_deleted`).describe(`Private channel was deleted. Requires scope: groups:read`),v.z.literal(`group_rename`).describe(`Private channel was renamed. Requires scope: groups:read`),v.z.literal(`group_unarchive`).describe(`Private channel was unarchived. Requires scope: groups:read`),v.z.literal(`link_shared`).describe(`Link from a registered domain was shared. Requires scope: links:read`),v.z.literal(`member_joined_channel`).describe(`User joined a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),v.z.literal(`member_left_channel`).describe(`User left a public or private channel. Requires scope: channels:read (public) or groups:read (private)`),v.z.literal(`message.channels`).describe(`Message was posted in a public channel. Requires scope: channels:history`),v.z.literal(`message.groups`).describe(`Message was posted in a private channel. Requires scope: groups:history`),v.z.literal(`message.im`).describe(`Message was posted in a direct message. Requires scope: im:history`),v.z.literal(`message.mpim`).describe(`Message was posted in a multi-party direct message. Requires scope: mpim:history`),v.z.literal(`pin_added`).describe(`Item was pinned in a channel. Requires scope: pins:read`),v.z.literal(`pin_removed`).describe(`Item was unpinned from a channel. Requires scope: pins:read`),v.z.literal(`reaction_added`).describe(`Reaction was added to a message. Requires scope: reactions:read`),v.z.literal(`reaction_removed`).describe(`Reaction was removed from a message. Requires scope: reactions:read`),v.z.literal(`team_join`).describe(`New user joined the workspace. Requires scope: users:read`),v.z.literal(`user_change`).describe(`User's profile or settings changed. Requires scope: users:read`)]),uf=v.z.union([v.z.literal(`app_mentions:read`).describe(`Read messages that directly mention the bot. Required for: app_mention event`),v.z.literal(`assistant:write`).describe(`Update bot status and write assistant messages. This should *always* be included for Slack bots. It improves the UX dramatically for users. Required for: assistant_thread_context_changed, assistant_thread_started events`),v.z.literal(`channels:history`).describe(`Read message history in public channels the bot has access to. Required for: message.channels event`),v.z.literal(`channels:join`).describe(`Join public channels`),v.z.literal(`channels:manage`).describe(`Manage public channels (archive, rename, etc.)`),v.z.literal(`channels:read`).describe(`View basic information about public channels. Required for: channel_archive, channel_created, channel_deleted, channel_rename, channel_unarchive, member_joined_channel, member_left_channel events`),v.z.literal(`chat:write`).describe(`Send messages as the bot`),v.z.literal(`chat:write.customize`).describe(`Send messages with a customized username and avatar`),v.z.literal(`chat:write.public`).describe(`Send messages to public channels without joining`),v.z.literal(`commands`).describe(`Add and use slash commands`),v.z.literal(`dnd:read`).describe(`View Do Not Disturb settings for users. Required for: dnd_updated_user event`),v.z.literal(`emoji:read`).describe(`View custom emoji in the workspace. Required for: emoji_changed event`),v.z.literal(`files:read`).describe(`View files shared in channels and conversations. Required for: file_change, file_created, file_deleted, file_public, file_shared, file_unshared events`),v.z.literal(`files:write`).describe(`Upload, edit, and delete files`),v.z.literal(`groups:history`).describe(`Read message history in private channels the bot has access to. Required for: message.groups event`),v.z.literal(`groups:read`).describe(`View basic information about private channels. Required for: group_archive, group_deleted, group_rename, group_unarchive, member_joined_channel, member_left_channel events`),v.z.literal(`groups:write`).describe(`Manage private channels (archive, rename, create, etc.)`),v.z.literal(`im:history`).describe(`Read message history in direct messages with the bot. Required for: message.im event`),v.z.literal(`im:read`).describe(`View basic information about direct messages with the bot`),v.z.literal(`im:write`).describe(`Start and manage direct messages with users`),v.z.literal(`links:read`).describe(`View URLs in messages. Required for: link_shared event`),v.z.literal(`links:write`).describe(`Show previews of URLs (unfurling)`),v.z.literal(`metadata.message:read`).describe(`Read message metadata`),v.z.literal(`mpim:history`).describe(`Read message history in multi-party direct messages. Required for: message.mpim event`),v.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages`),v.z.literal(`mpim:write`).describe(`Start and manage multi-party direct messages`),v.z.literal(`pins:read`).describe(`View pinned items in channels and conversations. Required for: pin_added, pin_removed events`),v.z.literal(`pins:write`).describe(`Pin and unpin items in channels and conversations`),v.z.literal(`reactions:read`).describe(`View emoji reactions on messages. Required for: reaction_added, reaction_removed events`),v.z.literal(`reactions:write`).describe(`Add and remove emoji reactions to messages`),v.z.literal(`reminders:read`).describe(`View reminders created by the bot`),v.z.literal(`reminders:write`).describe(`Create, update, and delete reminders`),v.z.literal(`team:read`).describe(`View workspace name, domain, and other basic information. Required for: email_domain_changed event`),v.z.literal(`usergroups:read`).describe(`View user groups and their members`),v.z.literal(`usergroups:write`).describe(`Create, update, and archive user groups`),v.z.literal(`users.profile:read`).describe(`View profile information about users`),v.z.literal(`users:read`).describe(`View users in the workspace. Required for: team_join, user_change events`),v.z.literal(`users:read.email`).describe(`View email addresses of users in the workspace`),v.z.literal(`users:write`).describe(`Set presence and status for the bot user`)]),df=v.z.union([v.z.literal(`channels:history`).describe(`Read message history in public channels on behalf of the user`),v.z.literal(`channels:read`).describe(`View basic information about public channels on behalf of the user`),v.z.literal(`channels:write`).describe(`Manage public channels on behalf of the user`),v.z.literal(`chat:write`).describe(`Send messages on behalf of the user`),v.z.literal(`emoji:read`).describe(`View custom emoji on behalf of the user`),v.z.literal(`files:read`).describe(`View files on behalf of the user`),v.z.literal(`files:write`).describe(`Upload, edit, and delete files on behalf of the user`),v.z.literal(`groups:history`).describe(`Read message history in private channels on behalf of the user`),v.z.literal(`groups:read`).describe(`View basic information about private channels on behalf of the user`),v.z.literal(`groups:write`).describe(`Manage private channels on behalf of the user`),v.z.literal(`im:history`).describe(`Read direct message history on behalf of the user`),v.z.literal(`im:read`).describe(`View basic information about direct messages on behalf of the user`),v.z.literal(`im:write`).describe(`Manage direct messages on behalf of the user`),v.z.literal(`links:read`).describe(`View URLs in messages on behalf of the user`),v.z.literal(`links:write`).describe(`Show URL previews on behalf of the user`),v.z.literal(`mpim:history`).describe(`Read multi-party direct message history on behalf of the user`),v.z.literal(`mpim:read`).describe(`View basic information about multi-party direct messages on behalf of the user`),v.z.literal(`mpim:write`).describe(`Manage multi-party direct messages on behalf of the user`),v.z.literal(`pins:read`).describe(`View pinned items on behalf of the user`),v.z.literal(`pins:write`).describe(`Pin and unpin items on behalf of the user`),v.z.literal(`reactions:read`).describe(`View emoji reactions on behalf of the user`),v.z.literal(`reactions:write`).describe(`Add and remove emoji reactions on behalf of the user`),v.z.literal(`reminders:read`).describe(`View reminders on behalf of the user`),v.z.literal(`reminders:write`).describe(`Create, update, and delete reminders on behalf of the user`),v.z.literal(`search:read`).describe(`Search messages and files on behalf of the user`),v.z.literal(`stars:read`).describe(`View starred items on behalf of the user`),v.z.literal(`stars:write`).describe(`Star and unstar items on behalf of the user`),v.z.literal(`team:read`).describe(`View workspace information on behalf of the user`),v.z.literal(`usergroups:read`).describe(`View user groups on behalf of the user`),v.z.literal(`usergroups:write`).describe(`Manage user groups on behalf of the user`),v.z.literal(`users.profile:read`).describe(`View user profile information on behalf of the user`),v.z.literal(`users.profile:write`).describe(`Edit the user's profile information`),v.z.literal(`users:read`).describe(`View users in the workspace on behalf of the user`),v.z.literal(`users:read.email`).describe(`View email addresses on behalf of the user`),v.z.literal(`users:write`).describe(`Set presence for the user`)]),ff=v.z.object({display_information:v.z.object({name:v.z.string().describe(`The name of the Slack app.`),description:v.z.string().optional().describe(`A short description of the app.`),background_color:v.z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().describe(`Background color for the app in hex format (e.g., #4A154B).`),long_description:v.z.string().optional().describe(`A longer description of the app.`)}).describe(`Display information for the Slack app.`),features:v.z.object({bot_user:v.z.object({display_name:v.z.string().describe(`The display name for the bot user.`),always_online:v.z.boolean().optional().default(!0).describe(`Whether the bot always appears online.`)}).optional().describe(`Configuration for the bot user.`),app_home:v.z.object({home_tab_enabled:v.z.boolean().optional().describe(`Enable the Home tab.`),messages_tab_enabled:v.z.boolean().optional().describe(`Enable the Messages tab.`),messages_tab_read_only_enabled:v.z.boolean().optional().describe(`Make the Messages tab read-only.`)}).optional().describe(`Configuration for the App Home.`),assistant_view:v.z.object({assistant_description:v.z.string().optional().describe(`Description for the assistant view.`)}).optional().describe(`Configuration for the assistant view.`),slash_commands:v.z.array(v.z.object({command:v.z.string().regex(/^\//).describe(`The command (must start with /).`),description:v.z.string().describe(`Description of the command.`),usage_hint:v.z.string().optional().describe(`Usage hint for the command.`),should_escape:v.z.boolean().optional().describe(`Whether to escape special characters.`)})).optional().describe(`Slash commands for the app.`),unfurl_domains:v.z.array(v.z.string()).optional().describe(`Domains for link unfurling.`)}).optional().describe(`Features configuration for the Slack app.`),oauth_config:v.z.object({redirect_urls:v.z.array(v.z.string().url()).optional().describe(`OAuth redirect URLs.`),scopes:v.z.object({bot:v.z.array(v.z.union([uf,v.z.string()])).optional().describe(`Bot scopes required by the app. Each scope defines specific permissions for what the bot can do.`),user:v.z.array(v.z.union([df,v.z.string()])).optional().describe(`User scopes required by the app. Each scope defines specific permissions for actions performed on behalf of users.`)}).describe(`OAuth scopes for bot and user tokens.`)}).optional().describe(`OAuth configuration for the Slack app.`),settings:v.z.object({event_subscriptions:v.z.object({request_url:v.z.string().url().describe(`The webhook URL for event subscriptions.`),bot_events:v.z.array(v.z.union([lf,v.z.string()])).optional().describe(`Bot events to subscribe to. Each event notifies your app when specific actions occur in the workspace.`)}).optional().describe(`Event subscriptions configuration.`),interactivity:v.z.object({is_enabled:v.z.boolean().describe(`Enable interactivity.`),request_url:v.z.string().url().describe(`The webhook URL for interactive components.`),message_menu_options_url:v.z.string().url().optional().describe(`URL for message menu options.`)}).optional().describe(`Interactivity configuration.`),org_deploy_enabled:v.z.boolean().optional().default(!1).describe(`Enable organization-wide deployment.`),socket_mode_enabled:v.z.boolean().optional().default(!1).describe(`Enable Socket Mode.`),token_rotation_enabled:v.z.boolean().optional().default(!0).describe(`Enable automatic token rotation.`)}).optional().describe(`Settings for the Slack app.`)});function pf(e){let n=t.agent(),r,i;return n.on(`chat`,async({messages:n,context:i,chat:a})=>{let{execute_bash:o,execute_bash_sync:s,...l}=Zl,u={execute_bash:o,execute_bash_sync:s};process.env.BLINK_AUTO_APPROVE||(u=await t.tools.withApproval({messages:n,tools:u}));let d={...l,...u,...tf,create_github_app:(0,f.tool)({description:`A URL will be returned that will redirect the user to create a GitHub App.
|
|
249
249
|
|
|
250
250
|
IMPORTANT: You must explain to the user what's happening and why:
|
|
251
251
|
- Tell them this will open a localhost URL that redirects them to GitHub
|
|
@@ -255,14 +255,14 @@ IMPORTANT: You must explain to the user what's happening and why:
|
|
|
255
255
|
|
|
256
256
|
You *must* ensure the organization is correct - ask the user prior.
|
|
257
257
|
|
|
258
|
-
Once they complete the app creation, environment variables will be automatically set in the provided environment file.`,inputSchema:v.z.object({manifest:sf,envFile:v.z.enum([`local`,`production`]).describe(`The environment file to put credentials in on app creation.`),organization:v.z.string().optional().describe(`An optional GitHub organization the app should be created for. Leave blank to create a personal app.`)}),execute:async(t,n)=>`Direct the user to create the GitHub App at: ${await nf(t.manifest,t.organization,async(n,
|
|
258
|
+
Once they complete the app creation, environment variables will be automatically set in the provided environment file.`,inputSchema:v.z.object({manifest:sf,envFile:v.z.enum([`local`,`production`]).describe(`The environment file to put credentials in on app creation.`),organization:v.z.string().optional().describe(`An optional GitHub organization the app should be created for. Leave blank to create a personal app.`)}),execute:async(t,n)=>`Direct the user to create the GitHub App at: ${await nf(t.manifest,t.organization,async(n,r)=>{if(n){await i.chat.message(a.key,{role:`assistant`,parts:[{type:`text`,text:`Failed to create GitHub App: ${n.message}`}]});return}if(r){try{let n=t.envFile===`production`?`.env.production`:`.env.local`,i=(0,c.join)(e.directory,n),a=``;try{a=await(0,p.readFile)(i,`utf-8`)}catch{}let o=`
|
|
259
259
|
# GitHub App credentials (created with the blink edit agent)
|
|
260
|
-
GITHUB_APP_ID=${
|
|
261
|
-
GITHUB_CLIENT_ID=${
|
|
262
|
-
GITHUB_CLIENT_SECRET=${
|
|
263
|
-
GITHUB_WEBHOOK_SECRET=${
|
|
264
|
-
GITHUB_PRIVATE_KEY="${btoa(
|
|
265
|
-
`;await(0,
|
|
260
|
+
GITHUB_APP_ID=${r.id}
|
|
261
|
+
GITHUB_CLIENT_ID=${r.client_id}
|
|
262
|
+
GITHUB_CLIENT_SECRET=${r.client_secret}
|
|
263
|
+
GITHUB_WEBHOOK_SECRET=${r.webhook_secret}
|
|
264
|
+
GITHUB_PRIVATE_KEY="${btoa(r.pem)}"
|
|
265
|
+
`;await(0,p.writeFile)(i,a+o,`utf-8`)}catch(e){await i.chat.message(a.key,{role:`assistant`,parts:[{type:`text`,text:`GitHub App created but failed to write credentials to env file: ${e instanceof Error?e.message:String(e)}`}]});return}await i.chat.message(a.key,{role:`assistant`,parts:[{type:`text`,text:`GitHub App created successfully. The following environment variables have been set in the ${t.envFile} environment file: GITHUB_APP_ID, GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, GITHUB_WEBHOOK_SECRET, GITHUB_PRIVATE_KEY.`}]})}})}`}),create_slack_app:(0,f.tool)({description:`Returns a URL for a user to create a Slack App.
|
|
266
266
|
|
|
267
267
|
IMPORTANT: After invoking this tool, you must:
|
|
268
268
|
1. Tell the user to navigate to the URL ABOVE (they see the tool output, so do *not* tell them to copy it).
|
|
@@ -272,11 +272,11 @@ IMPORTANT: After invoking this tool, you must:
|
|
|
272
272
|
- SLACK_CLIENT_SECRET=value
|
|
273
273
|
3. Explain that they can find these values in the Slack app settings after creation (this is the page they are redirected to)
|
|
274
274
|
|
|
275
|
-
You MUST GUIDE THE USER through these steps - do not provide all the steps at once.`,inputSchema:ff,execute:async(e,t)=>`${cf(e)}`}),message_user_agent:(0,
|
|
275
|
+
You MUST GUIDE THE USER through these steps - do not provide all the steps at once.`,inputSchema:ff,execute:async(e,t)=>`${cf(e)}`}),message_user_agent:(0,f.tool)({description:`Messages the user agent. There is no conversation history - this will be the only message sent, and only one message responds. Every time you invoke this tool, a new conversation occurs.
|
|
276
276
|
|
|
277
|
-
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:v.z.object({message:v.z.string()}),execute:async(e,
|
|
277
|
+
Instruct the agent to invoke tools you are debugging. e.g. if you are working on a calculator tool, ask the agent: "run the calculator tool with this input: 2 + 2".`,inputSchema:v.z.object({message:v.z.string()}),execute:async(e,n)=>{if(!r)return`User agent URL is not available. Cannot test user agent.`;let i=await new t.Client({baseUrl:r}).chat({chat:{key:`fake-key`},messages:[{id:`fake`,role:`user`,parts:[{type:`text`,text:e.message}]}]},{signal:n.abortSignal}),a=(0,f.readUIMessageStream)({stream:i}),o;for await(let e of a)o=e;return o}}),typecheck_agent:(0,f.tool)({description:`*ONLY* typecheck the agent being worked on. Reports all syntax errors.
|
|
278
278
|
|
|
279
|
-
Do *NOT* confuse this with tools in run mode for typechecking.`,inputSchema:v.z.object({}),execute:async()=>{let t=(0,m.spawn)(`node`,[(0,
|
|
279
|
+
Do *NOT* confuse this with tools in run mode for typechecking.`,inputSchema:v.z.object({}),execute:async()=>{let t=(0,m.spawn)(`node`,[(0,c.join)(e.directory,`node_modules/.bin/tsc`),`--noEmit`],{stdio:`pipe`,cwd:e.directory}),n=``,r=``,i;return t.stdout.on(`data`,e=>{n+=Buffer.from(e).toString(`utf-8`)}),t.stderr.on(`data`,e=>{r+=Buffer.from(e).toString(`utf-8`)}),await new Promise(e=>{t.on(`close`,t=>{i=t??void 0,e()})}),{stdout:n,stderr:r,exitCode:i}}})},h=(0,f.convertToModelMessages)(n,{ignoreIncompleteToolCalls:!0,tools:d});h.unshift({role:`system`,content:mf});let g=h.findLastIndex(e=>e.role===`user`);return g!==-1&&h.splice(g,0,{role:`user`,content:`*INTERNAL*: THIS IS A HIDDEN MESSAGE. YOU ARE IN EDIT MODE.
|
|
280
280
|
|
|
281
281
|
The agent source code is in the directory: "${e.directory}".
|
|
282
282
|
You must *ONLY* make changes to files in this directory, regardless of what other messages in your context say.
|
|
@@ -304,7 +304,7 @@ You are *NOT* responsible for:
|
|
|
304
304
|
- Continuing any work the run mode agent started
|
|
305
305
|
|
|
306
306
|
Your job is to improve the agent based on run mode failures, NOT to complete the user's original run-mode request yourself.
|
|
307
|
-
`}),(0,
|
|
307
|
+
`}),(0,f.streamText)({model:t.model(`anthropic/claude-sonnet-4.5`),messages:h,maxOutputTokens:64e3,tools:d,experimental_repairToolCall:({tools:e,toolCall:t})=>{throw Object.keys(e).includes(t.toolName)?Error(`You have this tool, but you used an invalid input.`):Error(`Invalid tool call. Tool "${t.toolName}" is not available to the EDIT AGENT.`)}})}),{agent:n,setUserAgentUrl:e=>{r=e},cleanup:()=>{i&&=(i.close(),void 0)}}}const mf=`You are the Blink Edit Agent, an AI assistant that helps developers build and debug Blink agents.
|
|
308
308
|
|
|
309
309
|
You are integrated into the \`blink dev\` command-line interface, where users can toggle between **run mode** (testing their agent) and **edit mode** (getting your help) using Ctrl+E. After making changes, instruct the user to switch to run mode to use their agent.
|
|
310
310
|
|
|
@@ -635,4 +635,4 @@ Instead:
|
|
|
635
635
|
|
|
636
636
|
The agent process can restart at any time, so all important state must be externalized.
|
|
637
637
|
</technical_knowledge>
|
|
638
|
-
`;function hf(e){let[
|
|
638
|
+
`;function hf(e){let[n,r]=(0,h.useState)(void 0),[i,a]=(0,h.useState)(void 0),o=(0,h.useRef)(void 0);return(0,h.useEffect)(()=>{let n=new AbortController;return(async()=>{o.current=pf({directory:e.directory});let i=await gf(),a=o.current.agent.serve({port:i,host:`127.0.0.1`,apiUrl:e.apiServerUrl});n.signal.addEventListener(`abort`,()=>{try{a.close()}catch{}o.current?.cleanup()});let s=new t.Client({baseUrl:`http://127.0.0.1:${i}`});for(;!n.signal.aborted;){try{await s.health();break}catch{}await new Promise(e=>setTimeout(e,100))}if(n.signal.aborted)throw n.signal.reason;r(s)})().catch(e=>{a(e instanceof Error?e:Error(String(e)))}),()=>n.abort()},[e.directory,e.apiServerUrl]),(0,h.useMemo)(()=>({client:n,error:i,setUserAgentUrl:e=>{o.current?.setUserAgentUrl(e)}}),[n,i])}async function gf(){let e=(0,s.createServer)();return new Promise((t,n)=>{e.listen(0,()=>{let n=e.address().port;t(n)}).on(`error`,e=>{n(e)})}).finally(()=>{e.close()})}function _f(e){let{directory:n}=e,[r,i]=(0,h.useState)(`run`),a=(0,h.useRef)(`run`);(0,h.useEffect)(()=>{a.current=r},[r]);let o=(0,h.useCallback)(t=>{i(t),e.onModeChange?.(t)},[e.onModeChange]),s=(0,h.useCallback)(()=>{o(r===`run`?`edit`:`run`)},[r,o]),{error:l,status:u,result:d,entry:p}=C({directory:n,onBuildStart:e.onBuildStart,onBuildSuccess:e.onBuildSuccess,onBuildError:e.onBuildError}),m=Ja(n),g=(0,h.useMemo)(()=>{let e=Aa();return e?{...m,BLINK_TOKEN:e}:m},[m]),_=(0,h.useRef)(void 0);(0,h.useEffect)(()=>{let t=Object.keys(g);if(t.length===_.current||_.current===void 0){_.current=t.length;return}_.current=t.length,e.onEnvLoaded?.(t)},[g,e.onEnvLoaded]);let v=(0,h.useRef)(void 0),y=(0,h.useMemo)(()=>Va({port:0,dataDirectory:(0,c.join)(n,`data`),getAgent:()=>v.current}),[n]),{agent:b,logs:S,error:w,capabilities:T}=x({buildResult:d,env:g,apiServerUrl:y.url}),{client:E,error:D,setUserAgentUrl:O}=hf({directory:n,apiServerUrl:y.url}),[k,A]=(0,h.useState)(`default`);(0,h.useEffect)(()=>{b&&O(b.baseUrl),r===`run`?b?v.current=b:(v.current=void 0,y.stopChat(k)):r===`edit`&&(E?v.current=E:(v.current=void 0,y.stopChat(k)))},[b,E,r,k,y]);let j=(0,h.useRef)(void 0),M=ue({chatId:k,agent:r===`run`?b:E,chatsDirectory:y.chatsDirectory,serializeMessage:e=>{let t=e.role===`user`&&j.current?{...typeof e.metadata==`object`&&e.metadata!==null?e.metadata:{},options:j.current}:e.metadata;return{id:e.id??crypto.randomUUID(),created_at:new Date().toISOString(),role:e.role,parts:e.parts,mode:a.current,metadata:t}},filterMessages:e=>a.current===`edit`?!0:!(ce(e.metadata)||e.mode===`edit`)}),N=(0,h.useRef)(0);(0,h.useEffect)(()=>{if(S.length===N.current)return;let t=N.current;for(let n of S.slice(t))e.onAgentLog?.(n);N.current=S.length},[S,e.onAgentLog,M.upsertMessage]);let[P,F]=(0,h.useState)([]);(0,h.useEffect)(()=>{y.listChats().then(e=>{F(e.map(e=>e.key))})},[y]),(0,h.useEffect)(()=>{k&&!P.includes(k)&&F(e=>[...e,k])},[k,P]);let ee=(0,h.useMemo)(()=>Ma(n),[n]),I=Ua({id:ee,disabled:!T?.request,onRequest:async t=>{if(!b)throw Error(`No agent`);let n=new URL(t.url),r=new URL(b.baseUrl);r.pathname=n.pathname,r.search=n.search;try{let i=await fetch(r.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:`manual`,signal:t.signal,duplex:`half`});return e.onDevhookRequest?.({method:t.method,path:n.pathname,status:i.status}),i}catch(e){return console.error(`Error sending request to user's agent:`,e),new Response(`Internal server error`,{status:500})}}});(0,h.useEffect)(()=>{I.status===`connected`&&e.onDevhookConnected?.(`https://${I.id}.dev.blink.host`)},[I.status,I.id]);let{schema:L,options:R,error:te,setOption:z}=Ha({agent:r===`run`?b:E,capabilities:T,messages:M.messages});(0,h.useEffect)(()=>{j.current=R},[R]);let B=(0,h.useMemo)(()=>{let e=[];return w&&r===`run`&&e.push(w.message),D&&r===`edit`&&e.push(`Edit agent error: ${D.message}`),M.error&&e.push(`Chat error: ${M.error}`),te&&e.push(`Options error: ${te.message}`),e},[w,D,M.error,te,r]);(0,h.useEffect)(()=>{for(let t of B)e.onError?.(t)},[B]);let[V,ne]=(0,h.useState)(),[re,H]=(0,h.useState)(!1),U=(0,h.useMemo)(()=>{let e=[...M.messages].reverse().find(e=>!(e.role!==`assistant`||e.metadata&&e.metadata.ephemeral));if(!e||V===e.id)return;let n=e.parts.filter(f.isToolOrDynamicToolUIPart);if(n.length!==0&&n.some(e=>t.isToolApprovalOutput(e.output)&&e.output.outcome===`pending`))return e},[M.messages,V]),ie=(0,h.useCallback)(async(e,n)=>{if(!U)return;n&&e&&H(!0),ne(U.id);let r=M.messages;if(r.length===0)return;let i=r[r.length-1];if(!i||i.role!==`assistant`||!Array.isArray(i.parts))return;let a=i.parts.map(n=>n.output&&t.isToolApprovalOutput(n.output)&&n.output.outcome===`pending`?{...n,output:{...n.output,outcome:e?`approved`:`rejected`}}:n);await M.upsertMessage({...i,parts:a}),await M.start()},[U,M]);(0,h.useEffect)(()=>{re&&U&&ie(!0)},[re,U,ie]);let W=(0,h.useCallback)(()=>{let e=crypto.randomUUID();A(e),F(t=>[...t,e])},[]),ae=(0,h.useMemo)(()=>{if(U)return{message:U,approve:e=>ie(!0,e),reject:()=>ie(!1),autoApproveEnabled:re}},[U,ie,re]),oe=(0,h.useMemo)(()=>{let e=M.messages;if(e.length!==0)for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||n.role!==`assistant`||!n.metadata||typeof n.metadata!=`object`||!(`totalUsage`in n.metadata))continue;let r=n.metadata.totalUsage;if(!(!r||typeof r!=`object`)&&!(!(`inputTokens`in r)||!(`outputTokens`in r)||!(`totalTokens`in r)))return{inputTokens:r.inputTokens,outputTokens:r.outputTokens,totalTokens:r.totalTokens,cachedInputTokens:r.cachedInputTokens}}},[M.messages]),se=(0,h.useMemo)(()=>{if(M.status!==`streaming`)return!1;if(!M.streamingMessage)return!0;let e=M.streamingMessage.parts.filter(f.isToolOrDynamicToolUIPart);return e.length>0&&e.every(e=>e.state.startsWith(`output-`))},[M.status,M.streamingMessage]);return{mode:r,setMode:o,toggleMode:s,chat:M,chats:P,switchChat:A,newChat:W,build:{status:u,error:l,entrypoint:p},devhook:{connected:I.status===`connected`,url:I.status===`connected`?`https://${I.id}.dev.blink.host`:void 0},capabilities:T,options:{schema:L,selected:R,error:te,setOption:z},approval:ae,tokenUsage:oe,server:y,showWaitingPlaceholder:se}}exports.useAgent=x,exports.useBundler=C,exports.useChat=ue,exports.useDevMode=_f,exports.useDevhook=Ua,exports.useDotenv=Ja,exports.useEditAgent=hf,exports.useOptions=Ha;
|