blink 0.1.40 → 0.1.42

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.
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`../cookie-B3SvZDri.cjs`);let t=require(`util`);t=e.__toESM(t);const n=`x-blink-stream-response-format`,r=`BLINK_API_SERVER_URL`;var i=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),a=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},o=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r)}return t},s=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},c=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function l(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function u(e,t){if(!l(e)&&!l(t))return t;let n={...e};for(let e in t){let r=t[e];l(n[e])&&l(r)?n[e]=u(n[e],r):n[e]=r}return n}var d=(e,t)=>{let n=new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return d(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}});return n},f=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(t,n)=>{if(t){if(t.query&&(this.queryParams=o(t.query)),t.form){let e=new FormData;for(let[n,r]of Object.entries(t.form))if(Array.isArray(r))for(let t of r)e.append(n,t);else e.append(n,r);this.rBody=e}t.json&&(this.rBody=JSON.stringify(t.json),this.cType=`application/json`),t.param&&(this.pathParams=t.param)}let r=this.method.toUpperCase(),i={...t?.header,...typeof n?.headers==`function`?await n.headers():n?.headers};if(t?.cookie){let n=[];for(let[r,i]of Object.entries(t.cookie))n.push(e.serialize(r,i,{path:`/`}));i.Cookie=n.join(`,`)}this.cType&&(i[`Content-Type`]=this.cType);let s=new Headers(i??void 0),l=this.url;l=c(l),l=a(l,this.pathParams),this.queryParams&&(l=l+`?`+this.queryParams.toString()),r=this.method.toUpperCase();let u=!(r===`GET`||r===`HEAD`);return(n?.fetch||fetch)(l,{body:u?this.rBody:void 0,method:r,headers:s,...n?.init})}},p=(e,t)=>d(function n(r){let l=[...r.path],d=l.slice(-3).reverse();if(d[0]===`toString`)return d[1]===`name`?d[2]||``:n.toString();if(d[0]===`valueOf`)return d[1]===`name`?d[2]||``:n;let p=``;if(/^\$/.test(d[0])){let e=l.pop();e&&(p=e.replace(/^\$/,``))}let m=l.join(`/`),h=i(e,m);if(p===`url`){let e=h;return r.args[0]&&(r.args[0].param&&(e=a(h,r.args[0].param)),r.args[0].query&&(e=e+`?`+o(r.args[0].query).toString())),e=c(e),new URL(e)}if(p===`ws`){let e=s(r.args[0]&&r.args[0].param?a(h,r.args[0].param):h,`ws`),n=new URL(e),i=r.args[0]?.query;i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)});let o=(...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e);return o(n.toString())}let g=new f(h,p);if(p){t??={};let e=u(t,{...r.args[1]});return g.fetch(r.args[0],e)}return g},[]);const m=process.env.BLINK_API_SERVER_URL,h=p(m??``,{fetch:m?void 0:async()=>{throw console.warn(`Your code is attempting to use the Blink API server, but no API server is configured for this Blink agent.`),Error(`No API server is configured for this Blink agent. External APIs are not available.`)}}),g=Object.freeze({upsert:async e=>{let t=await h.chat[`:id`].$post({param:{id:e}});if(t.status!==200){let e=await t.json();throw Error(e.error)}return{id:e}},message:async(e,t,n)=>{let r=await h.chat[`:id`].sendMessages.$post({param:{id:e},json:{messages:[t],behavior:n?.behavior??`enqueue`}});if(r.status!==204){let e=await r.json();throw Error(e.error)}}}),_=Object.freeze({get:async e=>{let t=await h.storage[`:key`].$get({param:{key:e}});if(t.status!==200){let e=await t.json();throw Error(e.error)}let n=await t.json();return n.value},set:async(e,t)=>{let n=await h.storage[`:key`].$post({param:{key:e},json:{value:t}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}});function v(e){return{version:`v0`,supportsWebhooks:e.webhook!==void 0,fetch:async t=>{let n=new URL(t.url);switch(n.pathname){case`/sendMessages`:return y(t,e);case`/webhook`:return b(t,e);default:return new Response(`Not found`,{status:404})}}}}async function y(e,n){if(e.method!==`POST`)return new Response(`Method not allowed`,{status:405});let r;try{r=await e.json()}catch{return new Response(`Invalid request`,{status:400})}let i;try{i=await n.sendMessages({messages:r.messages,request:e})}catch(e){return new Response(JSON.stringify({error:t.default.inspect(e)}),{status:500})}if(i instanceof Response)return i;let a;if(i instanceof ReadableStream)a=i;else{if(typeof i!=`object`||!(`toUIMessageStream`in i))throw Error(`The agent must return a "Response", "ReadableStream", or "toUIMessageStream" function.`);a=i.toUIMessageStream()}return new Response(a.pipeThrough(new TransformStream({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}\n\n`)},flush(e){e.enqueue(`data: [DONE]
1
+ Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`../cookie-B3SvZDri.cjs`);let t=require(`util`);t=e.__toESM(t);const n=`x-blink-stream-response-format`,r=`BLINK_API_SERVER_URL`;var i=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),a=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},o=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r)}return t},s=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},c=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function l(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function u(e,t){if(!l(e)&&!l(t))return t;let n={...e};for(let e in t){let r=t[e];l(n[e])&&l(r)?n[e]=u(n[e],r):n[e]=r}return n}var d=(e,t)=>{let n=new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return d(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}});return n},f=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(t,n)=>{if(t){if(t.query&&(this.queryParams=o(t.query)),t.form){let e=new FormData;for(let[n,r]of Object.entries(t.form))if(Array.isArray(r))for(let t of r)e.append(n,t);else e.append(n,r);this.rBody=e}t.json&&(this.rBody=JSON.stringify(t.json),this.cType=`application/json`),t.param&&(this.pathParams=t.param)}let r=this.method.toUpperCase(),i={...t?.header,...typeof n?.headers==`function`?await n.headers():n?.headers};if(t?.cookie){let n=[];for(let[r,i]of Object.entries(t.cookie))n.push(e.serialize(r,i,{path:`/`}));i.Cookie=n.join(`,`)}this.cType&&(i[`Content-Type`]=this.cType);let s=new Headers(i??void 0),l=this.url;l=c(l),l=a(l,this.pathParams),this.queryParams&&(l=l+`?`+this.queryParams.toString()),r=this.method.toUpperCase();let u=!(r===`GET`||r===`HEAD`);return(n?.fetch||fetch)(l,{body:u?this.rBody:void 0,method:r,headers:s,...n?.init})}},p=(e,t)=>d(function n(r){let l=[...r.path],d=l.slice(-3).reverse();if(d[0]===`toString`)return d[1]===`name`?d[2]||``:n.toString();if(d[0]===`valueOf`)return d[1]===`name`?d[2]||``:n;let p=``;if(/^\$/.test(d[0])){let e=l.pop();e&&(p=e.replace(/^\$/,``))}let m=l.join(`/`),h=i(e,m);if(p===`url`){let e=h;return r.args[0]&&(r.args[0].param&&(e=a(h,r.args[0].param)),r.args[0].query&&(e=e+`?`+o(r.args[0].query).toString())),e=c(e),new URL(e)}if(p===`ws`){let e=s(r.args[0]&&r.args[0].param?a(h,r.args[0].param):h,`ws`),n=new URL(e),i=r.args[0]?.query;i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)});let o=(...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e);return o(n.toString())}let g=new f(h,p);if(p){t??={};let e=u(t,{...r.args[1]});return g.fetch(r.args[0],e)}return g},[]);const m=process.env.BLINK_API_SERVER_URL,h=p(m??``,{fetch:m?void 0:async()=>{throw console.warn(`Your code is attempting to use the Blink API server, but no API server is configured for this Blink agent.`),Error(`No API server is configured for this Blink agent. External APIs are not available.`)}}),g=Object.freeze({upsert:async e=>{let t=await h.chat[`:id`].$post({param:{id:e}});if(t.status!==200){let e=await t.json();throw Error(e.error)}return{id:e}},message:async(e,t,n)=>{let r=await h.chat[`:id`].sendMessages.$post({param:{id:e},json:{messages:[t],behavior:n?.behavior??`enqueue`}});if(r.status!==204){let e=await r.json();throw Error(e.error)}}}),_=Object.freeze({get:async e=>{let t=await h.storage[`:key`].$get({param:{key:e}});if(t.status!==200){let e=await t.json();throw Error(e.error)}let n=await t.json();return n.value},set:async(e,t)=>{let n=await h.storage[`:key`].$post({param:{key:e},json:{value:t}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}}),v={with(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=i.with(t);return n},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}};function y(e){return{version:`v0`,supportsWebhooks:e.webhook!==void 0,fetch:async t=>{let n=new URL(t.url);switch(n.pathname){case`/sendMessages`:return b(t,e);case`/webhook`:return x(t,e);default:return new Response(`Not found`,{status:404})}}}}async function b(e,n){if(e.method!==`POST`)return new Response(`Method not allowed`,{status:405});let r;try{r=await e.json()}catch{return new Response(`Invalid request`,{status:400})}let i;try{i=await n.sendMessages({messages:r.messages,request:e})}catch(e){return new Response(JSON.stringify({error:t.default.inspect(e)}),{status:500})}if(i instanceof Response)return i;let a;if(i instanceof ReadableStream)a=i;else{if(typeof i!=`object`||!(`toUIMessageStream`in i))throw Error(`The agent must return a "Response", "ReadableStream", or "toUIMessageStream" function.`);a=i.toUIMessageStream()}return new Response(a.pipeThrough(new TransformStream({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}\n\n`)},flush(e){e.enqueue(`data: [DONE]
2
2
 
3
- `)}})).pipeThrough(new TextEncoderStream),{headers:{"content-type":`text/event-stream`,"cache-control":`no-cache, no-transform`,connection:`keep-alive`,"x-vercel-ai-ui-message-stream":`v1`,"x-accel-buffering":`no`}})}async function b(e,n){if(!n.webhook)return new Response(`No webhook function provided`,{status:501});try{let t=await n.webhook(e);return t||new Response(`OK`,{status:200})}catch(e){return new Response(JSON.stringify({error:t.default.inspect(e)}),{status:500})}}function x(e,t){return e.headers.set(`x-blink-stream-response-format`,t),e}var S={agent:v,chat:g,storage:_};exports.agent=v,exports.chat=g,exports.default=S,exports.storage=_,exports.withResponseFormat=x;
3
+ `)}})).pipeThrough(new TextEncoderStream),{headers:{"content-type":`text/event-stream`,"cache-control":`no-cache, no-transform`,connection:`keep-alive`,"x-vercel-ai-ui-message-stream":`v1`,"x-accel-buffering":`no`}})}async function x(e,n){if(!n.webhook)return new Response(`No webhook function provided`,{status:501});try{let t=await n.webhook(e);return t||new Response(`OK`,{status:200})}catch(e){return new Response(JSON.stringify({error:t.default.inspect(e)}),{status:500})}}function S(e,t){return e.headers.set(`x-blink-stream-response-format`,t),e}var C={agent:y,chat:g,storage:_,tools:v};exports.agent=y,exports.chat=g,exports.default=C,exports.storage=_,exports.tools=v,exports.withResponseFormat=S;
@@ -1,4 +1,5 @@
1
- import { AsyncIterableStream, InferUIMessageChunk, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
1
+ import * as ai0 from "ai";
2
+ import { AsyncIterableStream, InferUIMessageChunk, Tool, ToolSet, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
2
3
 
3
4
  //#region src/api/chat.d.ts
4
5
  interface Chat {
@@ -24,6 +25,39 @@ declare const chat: Readonly<{
24
25
  message: (id: string, message: Message, options?: MessageOptions) => Promise<void>;
25
26
  }>;
26
27
  //#endregion
28
+ //#region src/api/tools.d.ts
29
+ /**
30
+ * ToolWith is a tool that supports the "with" method.
31
+ *
32
+ * @param CONTEXT The context type.
33
+ * @param TOOL The tool type.
34
+ * @returns The tool with the given context.
35
+ */
36
+ type ToolWith<CONTEXT, TOOL extends Tool> = TOOL & {
37
+ with: (context: CONTEXT) => TOOL;
38
+ };
39
+ /**
40
+ * Tools are helpers for managing tools.
41
+ */
42
+ declare const tools: {
43
+ /**
44
+ * with adds context to a set of tools that supports the "with" method.
45
+ *
46
+ * @param context
47
+ * @param tools
48
+ * @returns
49
+ */
50
+ with<TOOLS extends Record<string, ToolWith<CONTEXT, Tool>>, CONTEXT>(tools: TOOLS, context: CONTEXT): Record<string, Tool>;
51
+ /**
52
+ * prefix adds a prefix to all the tools in a tool set.
53
+ *
54
+ * @param tools The tool set to prefix.
55
+ * @param prefix The prefix to add to the tools.
56
+ * @returns The prefixed tool set.
57
+ */
58
+ prefix(tools: ToolSet, prefix: string): ToolSet;
59
+ };
60
+ //#endregion
27
61
  //#region src/api/storage.d.ts
28
62
  /**
29
63
  * Storage is namespaced by the agent.
@@ -84,6 +118,10 @@ declare const _default: {
84
118
  get: (key: string) => Promise<string | undefined>;
85
119
  set: (key: string, value: string) => Promise<void>;
86
120
  }>;
121
+ tools: {
122
+ with<TOOLS extends Record<string, ToolWith<CONTEXT, ai0.Tool>>, CONTEXT>(tools: TOOLS, context: CONTEXT): Record<string, ai0.Tool>;
123
+ prefix(tools: ai0.ToolSet, prefix: string): ai0.ToolSet;
124
+ };
87
125
  };
88
126
  //#endregion
89
- export { Agent, AgentDefaultExport, Chat, Message, MessageOptions, SendMessagesOptions, SendMessagesResponse, StreamResponseFormat, agent, chat, _default as default, storage, withResponseFormat };
127
+ export { Agent, AgentDefaultExport, Chat, Message, MessageOptions, SendMessagesOptions, SendMessagesResponse, StreamResponseFormat, ToolWith, agent, chat, _default as default, storage, tools, withResponseFormat };
@@ -1,4 +1,5 @@
1
- import { AsyncIterableStream, InferUIMessageChunk, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
1
+ import * as ai0 from "ai";
2
+ import { AsyncIterableStream, InferUIMessageChunk, Tool, ToolSet, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
2
3
 
3
4
  //#region src/api/chat.d.ts
4
5
  interface Chat {
@@ -24,6 +25,39 @@ declare const chat: Readonly<{
24
25
  message: (id: string, message: Message, options?: MessageOptions) => Promise<void>;
25
26
  }>;
26
27
  //#endregion
28
+ //#region src/api/tools.d.ts
29
+ /**
30
+ * ToolWith is a tool that supports the "with" method.
31
+ *
32
+ * @param CONTEXT The context type.
33
+ * @param TOOL The tool type.
34
+ * @returns The tool with the given context.
35
+ */
36
+ type ToolWith<CONTEXT, TOOL extends Tool> = TOOL & {
37
+ with: (context: CONTEXT) => TOOL;
38
+ };
39
+ /**
40
+ * Tools are helpers for managing tools.
41
+ */
42
+ declare const tools: {
43
+ /**
44
+ * with adds context to a set of tools that supports the "with" method.
45
+ *
46
+ * @param context
47
+ * @param tools
48
+ * @returns
49
+ */
50
+ with<TOOLS extends Record<string, ToolWith<CONTEXT, Tool>>, CONTEXT>(tools: TOOLS, context: CONTEXT): Record<string, Tool>;
51
+ /**
52
+ * prefix adds a prefix to all the tools in a tool set.
53
+ *
54
+ * @param tools The tool set to prefix.
55
+ * @param prefix The prefix to add to the tools.
56
+ * @returns The prefixed tool set.
57
+ */
58
+ prefix(tools: ToolSet, prefix: string): ToolSet;
59
+ };
60
+ //#endregion
27
61
  //#region src/api/storage.d.ts
28
62
  /**
29
63
  * Storage is namespaced by the agent.
@@ -84,6 +118,10 @@ declare const _default: {
84
118
  get: (key: string) => Promise<string | undefined>;
85
119
  set: (key: string, value: string) => Promise<void>;
86
120
  }>;
121
+ tools: {
122
+ with<TOOLS extends Record<string, ToolWith<CONTEXT, ai0.Tool>>, CONTEXT>(tools: TOOLS, context: CONTEXT): Record<string, ai0.Tool>;
123
+ prefix(tools: ai0.ToolSet, prefix: string): ai0.ToolSet;
124
+ };
87
125
  };
88
126
  //#endregion
89
- export { Agent, AgentDefaultExport, Chat, Message, MessageOptions, SendMessagesOptions, SendMessagesResponse, StreamResponseFormat, agent, chat, _default as default, storage, withResponseFormat };
127
+ export { Agent, AgentDefaultExport, Chat, Message, MessageOptions, SendMessagesOptions, SendMessagesResponse, StreamResponseFormat, ToolWith, agent, chat, _default as default, storage, tools, withResponseFormat };
package/dist/api/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import{serialize as e}from"../cookie-BiKY7-P1.js";import t from"util";var n=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),r=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},i=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r)}return t},a=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},o=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function s(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function c(e,t){if(!s(e)&&!s(t))return t;let n={...e};for(let e in t){let r=t[e];s(n[e])&&s(r)?n[e]=c(n[e],r):n[e]=r}return n}var l=(e,t)=>{let n=new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return l(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}});return n},u=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(t,n)=>{if(t){if(t.query&&(this.queryParams=i(t.query)),t.form){let e=new FormData;for(let[n,r]of Object.entries(t.form))if(Array.isArray(r))for(let t of r)e.append(n,t);else e.append(n,r);this.rBody=e}t.json&&(this.rBody=JSON.stringify(t.json),this.cType=`application/json`),t.param&&(this.pathParams=t.param)}let a=this.method.toUpperCase(),s={...t?.header,...typeof n?.headers==`function`?await n.headers():n?.headers};if(t?.cookie){let n=[];for(let[r,i]of Object.entries(t.cookie))n.push(e(r,i,{path:`/`}));s.Cookie=n.join(`,`)}this.cType&&(s[`Content-Type`]=this.cType);let c=new Headers(s??void 0),l=this.url;l=o(l),l=r(l,this.pathParams),this.queryParams&&(l=l+`?`+this.queryParams.toString()),a=this.method.toUpperCase();let u=!(a===`GET`||a===`HEAD`);return(n?.fetch||fetch)(l,{body:u?this.rBody:void 0,method:a,headers:c,...n?.init})}},d=(e,t)=>l(function s(l){let d=[...l.path],f=d.slice(-3).reverse();if(f[0]===`toString`)return f[1]===`name`?f[2]||``:s.toString();if(f[0]===`valueOf`)return f[1]===`name`?f[2]||``:s;let p=``;if(/^\$/.test(f[0])){let e=d.pop();e&&(p=e.replace(/^\$/,``))}let m=d.join(`/`),h=n(e,m);if(p===`url`){let e=h;return l.args[0]&&(l.args[0].param&&(e=r(h,l.args[0].param)),l.args[0].query&&(e=e+`?`+i(l.args[0].query).toString())),e=o(e),new URL(e)}if(p===`ws`){let e=a(l.args[0]&&l.args[0].param?r(h,l.args[0].param):h,`ws`),n=new URL(e),i=l.args[0]?.query;i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)});let o=(...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e);return o(n.toString())}let g=new u(h,p);if(p){t??={};let e=c(t,{...l.args[1]});return g.fetch(l.args[0],e)}return g},[]);const f=process.env.BLINK_API_SERVER_URL,p=d(f??``,{fetch:f?void 0:async()=>{throw console.warn(`Your code is attempting to use the Blink API server, but no API server is configured for this Blink agent.`),Error(`No API server is configured for this Blink agent. External APIs are not available.`)}}),m=Object.freeze({upsert:async e=>{let t=await p.chat[`:id`].$post({param:{id:e}});if(t.status!==200){let e=await t.json();throw Error(e.error)}return{id:e}},message:async(e,t,n)=>{let r=await p.chat[`:id`].sendMessages.$post({param:{id:e},json:{messages:[t],behavior:n?.behavior??`enqueue`}});if(r.status!==204){let e=await r.json();throw Error(e.error)}}}),h=Object.freeze({get:async e=>{let t=await p.storage[`:key`].$get({param:{key:e}});if(t.status!==200){let e=await t.json();throw Error(e.error)}let n=await t.json();return n.value},set:async(e,t)=>{let n=await p.storage[`:key`].$post({param:{key:e},json:{value:t}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}});function g(e){return{version:`v0`,supportsWebhooks:e.webhook!==void 0,fetch:async t=>{let n=new URL(t.url);switch(n.pathname){case`/sendMessages`:return _(t,e);case`/webhook`:return v(t,e);default:return new Response(`Not found`,{status:404})}}}}async function _(e,n){if(e.method!==`POST`)return new Response(`Method not allowed`,{status:405});let r;try{r=await e.json()}catch{return new Response(`Invalid request`,{status:400})}let i;try{i=await n.sendMessages({messages:r.messages,request:e})}catch(e){return new Response(JSON.stringify({error:t.inspect(e)}),{status:500})}if(i instanceof Response)return i;let a;if(i instanceof ReadableStream)a=i;else{if(typeof i!=`object`||!(`toUIMessageStream`in i))throw Error(`The agent must return a "Response", "ReadableStream", or "toUIMessageStream" function.`);a=i.toUIMessageStream()}return new Response(a.pipeThrough(new TransformStream({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}\n\n`)},flush(e){e.enqueue(`data: [DONE]
1
+ import{serialize as e}from"../cookie-BiKY7-P1.js";import t from"util";var n=(e,t)=>(e=e.replace(/\/+$/,``),e+=`/`,t=t.replace(/^\/+/,``),e+t),r=(e,t)=>{for(let[n,r]of Object.entries(t)){let t=RegExp(`/:`+n+`(?:{[^/]+})?\\??`);e=e.replace(t,r?`/${r}`:``)}return e},i=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e)){if(r===void 0)continue;if(Array.isArray(r))for(let e of r)t.append(n,e);else t.set(n,r)}return t},a=(e,t)=>{switch(t){case`ws`:return e.replace(/^http/,`ws`);case`http`:return e.replace(/^ws/,`http`)}},o=e=>/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(e)?e.replace(/\/index(?=\?|$)/,`/`):e.replace(/\/index(?=\?|$)/,``);function s(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function c(e,t){if(!s(e)&&!s(t))return t;let n={...e};for(let e in t){let r=t[e];s(n[e])&&s(r)?n[e]=c(n[e],r):n[e]=r}return n}var l=(e,t)=>{let n=new Proxy(()=>{},{get(n,r){if(!(typeof r!=`string`||r===`then`))return l(e,[...t,r])},apply(n,r,i){return e({path:t,args:i})}});return n},u=class{url;method;queryParams=void 0;pathParams={};rBody;cType=void 0;constructor(e,t){this.url=e,this.method=t}fetch=async(t,n)=>{if(t){if(t.query&&(this.queryParams=i(t.query)),t.form){let e=new FormData;for(let[n,r]of Object.entries(t.form))if(Array.isArray(r))for(let t of r)e.append(n,t);else e.append(n,r);this.rBody=e}t.json&&(this.rBody=JSON.stringify(t.json),this.cType=`application/json`),t.param&&(this.pathParams=t.param)}let a=this.method.toUpperCase(),s={...t?.header,...typeof n?.headers==`function`?await n.headers():n?.headers};if(t?.cookie){let n=[];for(let[r,i]of Object.entries(t.cookie))n.push(e(r,i,{path:`/`}));s.Cookie=n.join(`,`)}this.cType&&(s[`Content-Type`]=this.cType);let c=new Headers(s??void 0),l=this.url;l=o(l),l=r(l,this.pathParams),this.queryParams&&(l=l+`?`+this.queryParams.toString()),a=this.method.toUpperCase();let u=!(a===`GET`||a===`HEAD`);return(n?.fetch||fetch)(l,{body:u?this.rBody:void 0,method:a,headers:c,...n?.init})}},d=(e,t)=>l(function s(l){let d=[...l.path],f=d.slice(-3).reverse();if(f[0]===`toString`)return f[1]===`name`?f[2]||``:s.toString();if(f[0]===`valueOf`)return f[1]===`name`?f[2]||``:s;let p=``;if(/^\$/.test(f[0])){let e=d.pop();e&&(p=e.replace(/^\$/,``))}let m=d.join(`/`),h=n(e,m);if(p===`url`){let e=h;return l.args[0]&&(l.args[0].param&&(e=r(h,l.args[0].param)),l.args[0].query&&(e=e+`?`+i(l.args[0].query).toString())),e=o(e),new URL(e)}if(p===`ws`){let e=a(l.args[0]&&l.args[0].param?r(h,l.args[0].param):h,`ws`),n=new URL(e),i=l.args[0]?.query;i&&Object.entries(i).forEach(([e,t])=>{Array.isArray(t)?t.forEach(t=>n.searchParams.append(e,t)):n.searchParams.set(e,t)});let o=(...e)=>t?.webSocket!==void 0&&typeof t.webSocket==`function`?t.webSocket(...e):new WebSocket(...e);return o(n.toString())}let g=new u(h,p);if(p){t??={};let e=c(t,{...l.args[1]});return g.fetch(l.args[0],e)}return g},[]);const f=process.env.BLINK_API_SERVER_URL,p=d(f??``,{fetch:f?void 0:async()=>{throw console.warn(`Your code is attempting to use the Blink API server, but no API server is configured for this Blink agent.`),Error(`No API server is configured for this Blink agent. External APIs are not available.`)}}),m=Object.freeze({upsert:async e=>{let t=await p.chat[`:id`].$post({param:{id:e}});if(t.status!==200){let e=await t.json();throw Error(e.error)}return{id:e}},message:async(e,t,n)=>{let r=await p.chat[`:id`].sendMessages.$post({param:{id:e},json:{messages:[t],behavior:n?.behavior??`enqueue`}});if(r.status!==204){let e=await r.json();throw Error(e.error)}}}),h=Object.freeze({get:async e=>{let t=await p.storage[`:key`].$get({param:{key:e}});if(t.status!==200){let e=await t.json();throw Error(e.error)}let n=await t.json();return n.value},set:async(e,t)=>{let n=await p.storage[`:key`].$post({param:{key:e},json:{value:t}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}}),g={with(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=i.with(t);return n},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}};function _(e){return{version:`v0`,supportsWebhooks:e.webhook!==void 0,fetch:async t=>{let n=new URL(t.url);switch(n.pathname){case`/sendMessages`:return v(t,e);case`/webhook`:return y(t,e);default:return new Response(`Not found`,{status:404})}}}}async function v(e,n){if(e.method!==`POST`)return new Response(`Method not allowed`,{status:405});let r;try{r=await e.json()}catch{return new Response(`Invalid request`,{status:400})}let i;try{i=await n.sendMessages({messages:r.messages,request:e})}catch(e){return new Response(JSON.stringify({error:t.inspect(e)}),{status:500})}if(i instanceof Response)return i;let a;if(i instanceof ReadableStream)a=i;else{if(typeof i!=`object`||!(`toUIMessageStream`in i))throw Error(`The agent must return a "Response", "ReadableStream", or "toUIMessageStream" function.`);a=i.toUIMessageStream()}return new Response(a.pipeThrough(new TransformStream({transform(e,t){t.enqueue(`data: ${JSON.stringify(e)}\n\n`)},flush(e){e.enqueue(`data: [DONE]
2
2
 
3
- `)}})).pipeThrough(new TextEncoderStream),{headers:{"content-type":`text/event-stream`,"cache-control":`no-cache, no-transform`,connection:`keep-alive`,"x-vercel-ai-ui-message-stream":`v1`,"x-accel-buffering":`no`}})}async function v(e,n){if(!n.webhook)return new Response(`No webhook function provided`,{status:501});try{let t=await n.webhook(e);return t||new Response(`OK`,{status:200})}catch(e){return new Response(JSON.stringify({error:t.inspect(e)}),{status:500})}}function y(e,t){return e.headers.set(`x-blink-stream-response-format`,t),e}var b={agent:g,chat:m,storage:h};export{g as agent,m as chat,b as default,h as storage,y as withResponseFormat};
3
+ `)}})).pipeThrough(new TextEncoderStream),{headers:{"content-type":`text/event-stream`,"cache-control":`no-cache, no-transform`,connection:`keep-alive`,"x-vercel-ai-ui-message-stream":`v1`,"x-accel-buffering":`no`}})}async function y(e,n){if(!n.webhook)return new Response(`No webhook function provided`,{status:501});try{let t=await n.webhook(e);return t||new Response(`OK`,{status:200})}catch(e){return new Response(JSON.stringify({error:t.inspect(e)}),{status:500})}}function b(e,t){return e.headers.set(`x-blink-stream-response-format`,t),e}var x={agent:_,chat:m,storage:h,tools:g};export{_ as agent,m as chat,x as default,h as storage,g as tools,b as withResponseFormat};
package/dist/cli/index.js CHANGED
@@ -22,7 +22,7 @@ Expecting one of '${allowedValues.join(`', '`)}'`);return this._lifeCycleHooks[e
22
22
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
23
23
  - ${executableDirMessage}`;throw Error(executableMissing)}_executeSubCommand(subcommand,args){args=args.slice();let launchWithNode=!1,sourceExt=[`.js`,`.ts`,`.tsx`,`.mjs`,`.cjs`];function findFile(baseDir,baseName){let localBin=path$37.resolve(baseDir,baseName);if(fs$44.existsSync(localBin))return localBin;if(sourceExt.includes(path$37.extname(baseName)))return;let foundExt=sourceExt.find(ext$1=>fs$44.existsSync(`${localBin}${ext$1}`));if(foundExt)return`${localBin}${foundExt}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let executableFile=subcommand._executableFile||`${this._name}-${subcommand._name}`,executableDir=this._executableDir||``;if(this._scriptPath){let resolvedScriptPath;try{resolvedScriptPath=fs$44.realpathSync(this._scriptPath)}catch{resolvedScriptPath=this._scriptPath}executableDir=path$37.resolve(path$37.dirname(resolvedScriptPath),executableDir)}if(executableDir){let localFile=findFile(executableDir,executableFile);if(!localFile&&!subcommand._executableFile&&this._scriptPath){let legacyName=path$37.basename(this._scriptPath,path$37.extname(this._scriptPath));legacyName!==this._name&&(localFile=findFile(executableDir,`${legacyName}-${subcommand._name}`))}executableFile=localFile||executableFile}launchWithNode=sourceExt.includes(path$37.extname(executableFile));let proc$1;if(process$8.platform===`win32`?(this._checkForMissingExecutable(executableFile,executableDir,subcommand._name),args.unshift(executableFile),args=incrementNodeInspectorPort(process$8.execArgv).concat(args),proc$1=childProcess$2.spawn(process$8.execPath,args,{stdio:`inherit`})):launchWithNode?(args.unshift(executableFile),args=incrementNodeInspectorPort(process$8.execArgv).concat(args),proc$1=childProcess$2.spawn(process$8.argv[0],args,{stdio:`inherit`})):proc$1=childProcess$2.spawn(executableFile,args,{stdio:`inherit`}),!proc$1.killed){let signals$2=[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`];signals$2.forEach(signal=>{process$8.on(signal,()=>{proc$1.killed===!1&&proc$1.exitCode===null&&proc$1.kill(signal)})})}let exitCallback=this._exitCallback;proc$1.on(`close`,code$1=>{code$1??=1,exitCallback?exitCallback(new CommanderError$2(code$1,`commander.executeSubCommandAsync`,`(close)`)):process$8.exit(code$1)}),proc$1.on(`error`,err$2=>{if(err$2.code===`ENOENT`)this._checkForMissingExecutable(executableFile,executableDir,subcommand._name);else if(err$2.code===`EACCES`)throw Error(`'${executableFile}' not executable`);if(!exitCallback)process$8.exit(1);else{let wrappedError=new CommanderError$2(1,`commander.executeSubCommandAsync`,`(error)`);wrappedError.nestedError=err$2,exitCallback(wrappedError)}}),this.runningCommand=proc$1}_dispatchSubcommand(commandName,operands,unknown){let subCommand=this._findCommand(commandName);subCommand||this.help({error:!0}),subCommand._prepareForParse();let promiseChain;return promiseChain=this._chainOrCallSubCommandHook(promiseChain,subCommand,`preSubcommand`),promiseChain=this._chainOrCall(promiseChain,()=>{if(subCommand._executableHandler)this._executeSubCommand(subCommand,operands.concat(unknown));else return subCommand._parseCommand(operands,unknown)}),promiseChain}_dispatchHelpCommand(subcommandName){subcommandName||this.help();let subCommand=this._findCommand(subcommandName);return subCommand&&!subCommand._executableHandler&&subCommand.help(),this._dispatchSubcommand(subcommandName,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??`--help`])}_checkNumberOfArguments(){this.registeredArguments.forEach((arg,i$7)=>{arg.required&&this.args[i$7]==null&&this.missingArgument(arg.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let myParseArg=(argument,value,previous)=>{let parsedValue=value;if(value!==null&&argument.parseArg){let invalidValueMessage=`error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;parsedValue=this._callParseArg(argument,value,previous,invalidValueMessage)}return parsedValue};this._checkNumberOfArguments();let processedArgs=[];this.registeredArguments.forEach((declaredArg,index)=>{let value=declaredArg.defaultValue;declaredArg.variadic?index<this.args.length?(value=this.args.slice(index),declaredArg.parseArg&&(value=value.reduce((processed,v$2)=>myParseArg(declaredArg,v$2,processed),declaredArg.defaultValue))):value===void 0&&(value=[]):index<this.args.length&&(value=this.args[index],declaredArg.parseArg&&(value=myParseArg(declaredArg,value,declaredArg.defaultValue))),processedArgs[index]=value}),this.processedArgs=processedArgs}_chainOrCall(promise$1,fn){return promise$1&&promise$1.then&&typeof promise$1.then==`function`?promise$1.then(()=>fn()):fn()}_chainOrCallHooks(promise$1,event){let result=promise$1,hooks=[];return this._getCommandAndAncestors().reverse().filter(cmd=>cmd._lifeCycleHooks[event]!==void 0).forEach(hookedCommand=>{hookedCommand._lifeCycleHooks[event].forEach(callback$1=>{hooks.push({hookedCommand,callback:callback$1})})}),event===`postAction`&&hooks.reverse(),hooks.forEach(hookDetail=>{result=this._chainOrCall(result,()=>hookDetail.callback(hookDetail.hookedCommand,this))}),result}_chainOrCallSubCommandHook(promise$1,subCommand,event){let result=promise$1;return this._lifeCycleHooks[event]!==void 0&&this._lifeCycleHooks[event].forEach(hook=>{result=this._chainOrCall(result,()=>hook(this,subCommand))}),result}_parseCommand(operands,unknown){let parsed=this.parseOptions(unknown);if(this._parseOptionsEnv(),this._parseOptionsImplied(),operands=operands.concat(parsed.operands),unknown=parsed.unknown,this.args=operands.concat(unknown),operands&&this._findCommand(operands[0]))return this._dispatchSubcommand(operands[0],operands.slice(1),unknown);if(this._getHelpCommand()&&operands[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(operands[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(unknown),this._dispatchSubcommand(this._defaultCommandName,operands,unknown);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(parsed.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let checkForUnknownOptions=()=>{parsed.unknown.length>0&&this.unknownOption(parsed.unknown[0])},commandEvent=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions(),this._processArguments();let promiseChain;return promiseChain=this._chainOrCallHooks(promiseChain,`preAction`),promiseChain=this._chainOrCall(promiseChain,()=>this._actionHandler(this.processedArgs)),this.parent&&(promiseChain=this._chainOrCall(promiseChain,()=>{this.parent.emit(commandEvent,operands,unknown)})),promiseChain=this._chainOrCallHooks(promiseChain,`postAction`),promiseChain}if(this.parent&&this.parent.listenerCount(commandEvent))checkForUnknownOptions(),this._processArguments(),this.parent.emit(commandEvent,operands,unknown);else if(operands.length){if(this._findCommand(`*`))return this._dispatchSubcommand(`*`,operands,unknown);this.listenerCount(`command:*`)?this.emit(`command:*`,operands,unknown):this.commands.length?this.unknownCommand():(checkForUnknownOptions(),this._processArguments())}else this.commands.length?(checkForUnknownOptions(),this.help({error:!0})):(checkForUnknownOptions(),this._processArguments())}_findCommand(name$5){if(name$5)return this.commands.find(cmd=>cmd._name===name$5||cmd._aliases.includes(name$5))}_findOption(arg){return this.options.find(option$1=>option$1.is(arg))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(cmd=>{cmd.options.forEach(anOption=>{anOption.mandatory&&cmd.getOptionValue(anOption.attributeName())===void 0&&cmd.missingMandatoryOptionValue(anOption)})})}_checkForConflictingLocalOptions(){let definedNonDefaultOptions=this.options.filter(option$1=>{let optionKey=option$1.attributeName();return this.getOptionValue(optionKey)===void 0?!1:this.getOptionValueSource(optionKey)!==`default`}),optionsWithConflicting=definedNonDefaultOptions.filter(option$1=>option$1.conflictsWith.length>0);optionsWithConflicting.forEach(option$1=>{let conflictingAndDefined=definedNonDefaultOptions.find(defined=>option$1.conflictsWith.includes(defined.attributeName()));conflictingAndDefined&&this._conflictingOption(option$1,conflictingAndDefined)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(cmd=>{cmd._checkForConflictingLocalOptions()})}parseOptions(argv$1){let operands=[],unknown=[],dest=operands,args=argv$1.slice();function maybeOption(arg){return arg.length>1&&arg[0]===`-`}let negativeNumberArg=arg=>/^-\d*\.?\d+(e[+-]?\d+)?$/.test(arg)?!this._getCommandAndAncestors().some(cmd=>cmd.options.map(opt=>opt.short).some(short=>/^-\d$/.test(short))):!1,activeVariadicOption=null;for(;args.length;){let arg=args.shift();if(arg===`--`){dest===unknown&&dest.push(arg),dest.push(...args);break}if(activeVariadicOption&&(!maybeOption(arg)||negativeNumberArg(arg))){this.emit(`option:${activeVariadicOption.name()}`,arg);continue}if(activeVariadicOption=null,maybeOption(arg)){let option$1=this._findOption(arg);if(option$1){if(option$1.required){let value=args.shift();value===void 0&&this.optionMissingArgument(option$1),this.emit(`option:${option$1.name()}`,value)}else if(option$1.optional){let value=null;args.length>0&&(!maybeOption(args[0])||negativeNumberArg(args[0]))&&(value=args.shift()),this.emit(`option:${option$1.name()}`,value)}else this.emit(`option:${option$1.name()}`);activeVariadicOption=option$1.variadic?option$1:null;continue}}if(arg.length>2&&arg[0]===`-`&&arg[1]!==`-`){let option$1=this._findOption(`-${arg[1]}`);if(option$1){option$1.required||option$1.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${option$1.name()}`,arg.slice(2)):(this.emit(`option:${option$1.name()}`),args.unshift(`-${arg.slice(2)}`));continue}}if(/^--[^=]+=/.test(arg)){let index=arg.indexOf(`=`),option$1=this._findOption(arg.slice(0,index));if(option$1&&(option$1.required||option$1.optional)){this.emit(`option:${option$1.name()}`,arg.slice(index+1));continue}}if(dest===operands&&maybeOption(arg)&&!(this.commands.length===0&&negativeNumberArg(arg))&&(dest=unknown),(this._enablePositionalOptions||this._passThroughOptions)&&operands.length===0&&unknown.length===0){if(this._findCommand(arg)){operands.push(arg),args.length>0&&unknown.push(...args);break}else if(this._getHelpCommand()&&arg===this._getHelpCommand().name()){operands.push(arg),args.length>0&&operands.push(...args);break}else if(this._defaultCommandName){unknown.push(arg),args.length>0&&unknown.push(...args);break}}if(this._passThroughOptions){dest.push(arg),args.length>0&&dest.push(...args);break}dest.push(arg)}return{operands,unknown}}opts(){if(this._storeOptionsAsProperties){let result={},len$1=this.options.length;for(let i$7=0;i$7<len$1;i$7++){let key=this.options[i$7].attributeName();result[key]=key===this._versionOptionName?this._version:this[key]}return result}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((combinedOptions,cmd)=>Object.assign(combinedOptions,cmd.opts()),{})}error(message,errorOptions){this._outputConfiguration.outputError(`${message}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==`string`?this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
24
24
  `),this.outputHelp({error:!0}));let config$1=errorOptions||{},exitCode=config$1.exitCode||1,code$1=config$1.code||`commander.error`;this._exit(exitCode,code$1,message)}_parseOptionsEnv(){this.options.forEach(option$1=>{if(option$1.envVar&&option$1.envVar in process$8.env){let optionKey=option$1.attributeName();(this.getOptionValue(optionKey)===void 0||[`default`,`config`,`env`].includes(this.getOptionValueSource(optionKey)))&&(option$1.required||option$1.optional?this.emit(`optionEnv:${option$1.name()}`,process$8.env[option$1.envVar]):this.emit(`optionEnv:${option$1.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=optionKey=>this.getOptionValue(optionKey)!==void 0&&![`default`,`implied`].includes(this.getOptionValueSource(optionKey));this.options.filter(option$1=>option$1.implied!==void 0&&hasCustomOptionValue(option$1.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option$1.attributeName()),option$1)).forEach(option$1=>{Object.keys(option$1.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option$1.implied[impliedKey],`implied`)})})}missingArgument(name$5){let message=`error: missing required argument '${name$5}'`;this.error(message,{code:`commander.missingArgument`})}optionMissingArgument(option$1){let message=`error: option '${option$1.flags}' argument missing`;this.error(message,{code:`commander.optionMissingArgument`})}missingMandatoryOptionValue(option$1){let message=`error: required option '${option$1.flags}' not specified`;this.error(message,{code:`commander.missingMandatoryOptionValue`})}_conflictingOption(option$1,conflictingOption){let findBestOptionFromValue=option$2=>{let optionKey=option$2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option$2},getErrorMessage$6=option$2=>{let bestOption=findBestOptionFromValue(option$2),optionKey=bestOption.attributeName(),source$39=this.getOptionValueSource(optionKey);return source$39===`env`?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},message=`error: ${getErrorMessage$6(option$1)} cannot be used with ${getErrorMessage$6(conflictingOption)}`;this.error(message,{code:`commander.conflictingOption`})}unknownOption(flag){if(this._allowUnknownOption)return;let suggestion=``;if(flag.startsWith(`--`)&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option$1=>option$1.long).map(option$1=>option$1.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag,candidateFlags)}let message=`error: unknown option '${flag}'${suggestion}`;this.error(message,{code:`commander.unknownOption`})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s$3=expected===1?``:`s`,forSubcommand=this.parent?` for '${this.name()}'`:``,message=`error: too many arguments${forSubcommand}. Expected ${expected} argument${s$3} but got ${receivedArgs.length}.`;this.error(message,{code:`commander.excessArguments`})}unknownCommand(){let unknownName=this.args[0],suggestion=``;if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:`commander.unknownCommand`})}version(str$1,flags,description){if(str$1===void 0)return this._version;this._version=str$1,flags||=`-V, --version`,description||=`output the version number`;let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on(`option:`+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str$1}\n`),this._exit(0,`commander.version`,str$1)}),this}description(str$1,argsDescription){return str$1===void 0&&argsDescription===void 0?this._description:(this._description=str$1,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str$1){return str$1===void 0?this._summary:(this._summary=str$1,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw Error(`Command alias can't be the same as its name`);let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join(`|`);throw Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases$1){return aliases$1===void 0?this._aliases:(aliases$1.forEach(alias=>this.alias(alias)),this)}usage(str$1){if(str$1===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?`[options]`:[],this.commands.length?`[command]`:[],this.registeredArguments.length?args:[]).join(` `)}return this._usage=str$1,this}name(str$1){return str$1===void 0?this._name:(this._name=str$1,this)}helpGroup(heading$1){return heading$1===void 0?this._helpGroupHeading??``:(this._helpGroupHeading=heading$1,this)}commandsGroup(heading$1){return heading$1===void 0?this._defaultCommandGroup??``:(this._defaultCommandGroup=heading$1,this)}optionsGroup(heading$1){return heading$1===void 0?this._defaultOptionGroup??``:(this._defaultOptionGroup=heading$1,this)}_initOptionGroup(option$1){this._defaultOptionGroup&&!option$1.helpGroupHeading&&option$1.helpGroup(this._defaultOptionGroup)}_initCommandGroup(cmd){this._defaultCommandGroup&&!cmd.helpGroup()&&cmd.helpGroup(this._defaultCommandGroup)}nameFromFilename(filename){return this._name=path$37.basename(filename,path$37.extname(filename)),this}executableDir(path$38){return path$38===void 0?this._executableDir:(this._executableDir=path$38,this)}helpInformation(contextOptions){let helper=this.createHelp(),context$1=this._getOutputContext(contextOptions);helper.prepareContext({error:context$1.error,helpWidth:context$1.helpWidth,outputHasColors:context$1.hasColors});let text$1=helper.formatHelp(this,helper);return context$1.hasColors?text$1:this._outputConfiguration.stripColor(text$1)}_getOutputContext(contextOptions){contextOptions||={};let error$22=!!contextOptions.error,baseWrite,hasColors$1,helpWidth;error$22?(baseWrite=str$1=>this._outputConfiguration.writeErr(str$1),hasColors$1=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=str$1=>this._outputConfiguration.writeOut(str$1),hasColors$1=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth());let write$2=str$1=>(hasColors$1||(str$1=this._outputConfiguration.stripColor(str$1)),baseWrite(str$1));return{error:error$22,write:write$2,hasColors:hasColors$1,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions==`function`&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit(`beforeAllHelp`,eventContext)),this.emit(`beforeHelp`,eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!=`string`&&!Buffer.isBuffer(helpInformation)))throw Error(`outputHelp callback must return a string or a Buffer`);outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit(`afterHelp`,eventContext),this._getCommandAndAncestors().forEach(command=>command.emit(`afterAllHelp`,eventContext))}helpOption(flags,description){return typeof flags==`boolean`?(flags?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(flags??`-h, --help`,description??`display help for command`),(flags||description)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option$1){return this._helpOption=option$1,this._initOptionGroup(option$1),this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process$8.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!=`function`&&contextOptions.error&&(exitCode=1),this._exit(exitCode,`commander.help`,`(outputHelp)`)}addHelpText(position,text$1){let allowedValues=[`beforeAll`,`before`,`after`,`afterAll`];if(!allowedValues.includes(position))throw Error(`Unexpected value for position to addHelpText.
25
- Expecting one of '${allowedValues.join(`', '`)}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context$1=>{let helpStr;helpStr=typeof text$1==`function`?text$1({error:context$1.error,command:context$1.command}):text$1,helpStr&&context$1.write(`${helpStr}\n`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption(),helpRequested=helpOption&&args.find(arg=>helpOption.is(arg));helpRequested&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith(`--inspect`))return arg;let debugOption,debugHost=`127.0.0.1`,debugPort=`9229`,match$1;return(match$1=arg.match(/^(--inspect(-brk)?)$/))===null?(match$1=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(match$1=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match$1[1],debugHost=match$1[3],debugPort=match$1[4]):(debugOption=match$1[1],/^\d+$/.test(match$1[3])?debugPort=match$1[3]:debugHost=match$1[3]):debugOption=match$1[1],debugOption&&debugPort!==`0`?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}function useColor(){if(process$8.env.NO_COLOR||process$8.env.FORCE_COLOR===`0`||process$8.env.FORCE_COLOR===`false`)return!1;if(process$8.env.FORCE_COLOR||process$8.env.CLICOLOR_FORCE!==void 0)return!0}exports.Command=Command$3,exports.useColor=useColor})),require_commander=__commonJSMin((exports=>{let{Argument:Argument$1}=require_argument(),{Command:Command$2}=require_command(),{CommanderError:CommanderError$1,InvalidArgumentError:InvalidArgumentError$37}=require_error$2(),{Help:Help$1}=require_help(),{Option:Option$1}=require_option();exports.program=new Command$2,exports.createCommand=name$5=>new Command$2(name$5),exports.createOption=(flags,description)=>new Option$1(flags,description),exports.createArgument=(name$5,description)=>new Argument$1(name$5,description),exports.Command=Command$2,exports.Option=Option$1,exports.Argument=Argument$1,exports.Help=Help$1,exports.CommanderError=CommanderError$1,exports.InvalidArgumentError=InvalidArgumentError$37,exports.InvalidOptionArgumentError=InvalidArgumentError$37}));init_wrapper();var import_commander=__toESM$1(require_commander(),1);const{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError:InvalidArgumentError$36,InvalidOptionArgumentError,Command:Command$1,Argument,Option,Help}=import_commander.default;async function build$1(path$38,{outdir}={}){outdir||=await resolveOutputDirectory(path$38);let outfile=join$1(outdir,`agent.js`),esbuild=loadEsbuild(),result=await esbuild.build({...sharedBuildOptions,entryPoints:[path$38],outfile});if(result.errors.length>0)throw Error(`Failed to build agent!`);return{outfile}}async function watch$1(entrypoint,{onErrors,onBuildStart,onBuildEnd,outdir}){let esbuild=loadEsbuild();outdir||=await resolveOutputDirectory(entrypoint);let outfile=join$1(outdir,`agent.js`),context$1=await esbuild.context({...sharedBuildOptions,entryPoints:[entrypoint],logLevel:`silent`,outfile,plugins:[{name:`blink-dev-server`,setup(build$11){build$11.onStart(()=>{onBuildStart?.()}),build$11.onEnd(result=>{if(result.errors.length>0){onErrors?.(result.errors);return}onBuildEnd?.({outfile})})}}]});return await context$1.watch(),{dispose:()=>{context$1.dispose()}}}async function resolveEntrypoint(directory){let packageJsonPath=await findNearestEntry(directory,`package.json`);if(!packageJsonPath)throw Error(`No package.json found in ${directory}`);let packageJson$1=JSON.parse(await readFile(packageJsonPath,`utf-8`)),main=packageJson$1.main;if(!main)throw Error(`"main" is not set in ${relative(process.cwd(),packageJsonPath)}. It should be set to the entrypoint of your agent.`);let mainPath=join$1(dirname$1(packageJsonPath),main),stats=await stat(mainPath);if(!stats.isFile())throw Error(`${mainPath} is not a file.`);return mainPath}async function resolveOutputDirectory(path$38){let nodeModulesPath=await findNearestEntry(path$38,`node_modules`);if(!nodeModulesPath){let stats=await stat(path$38);return stats.isDirectory()?join$1(path$38,`.blink`):join$1(dirname$1(path$38),`.blink`)}let blinkPath=join$1(nodeModulesPath,`.blink`);return await mkdir(blinkPath,{recursive:!0}),blinkPath}async function findNearestEntry(startDir,name$5){let currentDir=startDir;for(;currentDir!==dirname$1(currentDir);){let file=join$1(currentDir,name$5);try{return await stat(file),file}catch{}currentDir=dirname$1(currentDir)}}const sharedBuildOptions={bundle:!0,format:`cjs`,platform:`node`,target:`node18`,sourcemap:`inline`},loadEsbuild=()=>{try{return __require$2(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};async function build(directory){directory||=process.cwd();let entrypoint=await resolveEntrypoint(directory),{outfile}=await build$1(entrypoint);console.log(`Built agent.js to ${outfile}`)}let isDockerCached;function hasDockerEnv(){try{return fs.statSync(`/.dockerenv`),!0}catch{return!1}}function hasDockerCGroup(){try{return fs.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function isDocker(){return isDockerCached===void 0&&(isDockerCached=hasDockerEnv()||hasDockerCGroup()),isDockerCached}let cachedResult;const hasContainerEnv=()=>{try{return fs.statSync(`/run/.containerenv`),!0}catch{return!1}};function isInsideContainer(){return cachedResult===void 0&&(cachedResult=hasContainerEnv()||isDocker()),cachedResult}const isWsl=()=>{if(y.platform!==`linux`)return!1;if(os.release().toLowerCase().includes(`microsoft`))return!isInsideContainer();try{return fs.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!isInsideContainer():!1}catch{return!1}};var is_wsl_default=y.env.__IS_WSL_TEST__?isWsl:isWsl();const wslDrivesMountPoint=(()=>{let defaultMountPoint=`/mnt/`,mountPoint;return async function(){if(mountPoint)return mountPoint;let configFilePath$1=`/etc/wsl.conf`,isConfigFileExists=!1;try{await fs$1.access(configFilePath$1,constants.F_OK),isConfigFileExists=!0}catch{}if(!isConfigFileExists)return defaultMountPoint;let configContent=await fs$1.readFile(configFilePath$1,{encoding:`utf8`}),configMountPoint=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);return configMountPoint?(mountPoint=configMountPoint.groups.mountPoint.trim(),mountPoint=mountPoint.endsWith(`/`)?mountPoint:`${mountPoint}/`,mountPoint):defaultMountPoint}})(),powerShellPathFromWsl=async()=>{let mountPoint=await wslDrivesMountPoint();return`${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`},powerShellPath=async()=>is_wsl_default?powerShellPathFromWsl():`${y.env.SYSTEMROOT||y.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function defineLazyProperty(object$1,propertyName,valueGetter){let define$2=value=>Object.defineProperty(object$1,propertyName,{value,enumerable:!0,writable:!0});return Object.defineProperty(object$1,propertyName,{configurable:!0,enumerable:!0,get(){let result=valueGetter();return define$2(result),result},set(value){define$2(value)}}),object$1}const execFileAsync$4=promisify(execFile);async function defaultBrowserId(){if(y.platform!==`darwin`)throw Error(`macOS only`);let{stdout:stdout$1}=await execFileAsync$4(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]),match$1=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout$1);return match$1?.groups.id??`com.apple.Safari`}const execFileAsync$3=promisify(execFile);async function runAppleScript(script,{humanReadableOutput=!0}={}){if(y.platform!==`darwin`)throw Error(`macOS only`);let outputArguments=humanReadableOutput?[]:[`-ss`],{stdout:stdout$1}=await execFileAsync$3(`osascript`,[`-e`,script,outputArguments]);return stdout$1.trim()}async function bundleName(bundleId){return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const execFileAsync$2=promisify(execFile),windowsBrowserProgIds={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var UnknownBrowserError=class extends Error{};async function defaultBrowser$1(_execFileAsync=execFileAsync$2){let{stdout:stdout$1}=await _execFileAsync(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),match$1=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout$1);if(!match$1)throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout$1)}`);let{id}=match$1.groups,browser=windowsBrowserProgIds[id];if(!browser)throw new UnknownBrowserError(`Unknown browser ID: ${id}`);return browser}const execFileAsync$1=promisify(execFile),titleize=string=>string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,x$5=>x$5.toUpperCase());async function defaultBrowser(){if(y.platform===`darwin`){let id=await defaultBrowserId(),name$5=await bundleName(id);return{name:name$5,id}}if(y.platform===`linux`){let{stdout:stdout$1}=await execFileAsync$1(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),id=stdout$1.trim(),name$5=titleize(id.replace(/.desktop$/,``).replace(`-`,` `));return{name:name$5,id}}if(y.platform===`win32`)return defaultBrowser$1();throw Error(`Only macOS, Linux, and Windows are supported`)}const execFile$1=promisify(childProcess.execFile),__dirname$3=path.dirname(fileURLToPath(import.meta.url)),localXdgOpenPath=path.join(__dirname$3,`xdg-open`),{platform:platform$4,arch}=y;async function getWindowsDefaultBrowserFromWsl(){let powershellPath=await powerShellPath(),rawCommand=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,encodedCommand=Buffer$1.from(rawCommand,`utf16le`).toString(`base64`),{stdout:stdout$1}=await execFile$1(powershellPath,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,encodedCommand],{encoding:`utf8`}),progId=stdout$1.trim(),browserMap={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return browserMap[progId]?{id:browserMap[progId]}:{}}const pTryEach=async(array,mapper)=>{let latestError;for(let item of array)try{return await mapper(item)}catch(error$22){latestError=error$22}throw latestError},baseOpen=async options$1=>{if(options$1={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...options$1},Array.isArray(options$1.app))return pTryEach(options$1.app,singleApp=>baseOpen({...options$1,app:singleApp}));let{name:app,arguments:appArguments=[]}=options$1.app??{};if(appArguments=[...appArguments],Array.isArray(app))return pTryEach(app,appName=>baseOpen({...options$1,app:{name:appName,arguments:appArguments}}));if(app===`browser`||app===`browserPrivate`){let ids={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},flags={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},browser=is_wsl_default?await getWindowsDefaultBrowserFromWsl():await defaultBrowser();if(browser.id in ids){let browserName=ids[browser.id];return app===`browserPrivate`&&appArguments.push(flags[browserName]),baseOpen({...options$1,app:{name:apps[browserName],arguments:appArguments}})}throw Error(`${browser.name} is not supported as a default browser`)}let command,cliArguments=[],childProcessOptions={};if(platform$4===`darwin`)command=`open`,options$1.wait&&cliArguments.push(`--wait-apps`),options$1.background&&cliArguments.push(`--background`),options$1.newInstance&&cliArguments.push(`--new`),app&&cliArguments.push(`-a`,app);else if(platform$4===`win32`||is_wsl_default&&!isInsideContainer()&&!app){command=await powerShellPath(),cliArguments.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),is_wsl_default||(childProcessOptions.windowsVerbatimArguments=!0);let encodedArguments=[`Start`];options$1.wait&&encodedArguments.push(`-Wait`),app?(encodedArguments.push(`"\`"${app}\`""`),options$1.target&&appArguments.push(options$1.target)):options$1.target&&encodedArguments.push(`"${options$1.target}"`),appArguments.length>0&&(appArguments=appArguments.map(argument=>`"\`"${argument}\`""`),encodedArguments.push(`-ArgumentList`,appArguments.join(`,`))),options$1.target=Buffer$1.from(encodedArguments.join(` `),`utf16le`).toString(`base64`)}else{if(app)command=app;else{let isBundled=!__dirname$3||__dirname$3===`/`,exeLocalXdgOpen=!1;try{await fs$1.access(localXdgOpenPath,constants.X_OK),exeLocalXdgOpen=!0}catch{}let useSystemXdgOpen=y.versions.electron??(platform$4===`android`||isBundled||!exeLocalXdgOpen);command=useSystemXdgOpen?`xdg-open`:localXdgOpenPath}appArguments.length>0&&cliArguments.push(...appArguments),options$1.wait||(childProcessOptions.stdio=`ignore`,childProcessOptions.detached=!0)}platform$4===`darwin`&&appArguments.length>0&&cliArguments.push(`--args`,...appArguments),options$1.target&&cliArguments.push(options$1.target);let subprocess=childProcess.spawn(command,cliArguments,childProcessOptions);return options$1.wait?new Promise((resolve$10,reject)=>{subprocess.once(`error`,reject),subprocess.once(`close`,exitCode=>{if(!options$1.allowNonzeroExitCode&&exitCode>0){reject(Error(`Exited with code ${exitCode}`));return}resolve$10(subprocess)})}):(subprocess.unref(),subprocess)},open$2=(target,options$1)=>{if(typeof target!=`string`)throw TypeError("Expected a `target`");return baseOpen({...options$1,target})};function detectArchBinary(binary){if(typeof binary==`string`||Array.isArray(binary))return binary;let{[arch]:archBinary}=binary;if(!archBinary)throw Error(`${arch} is not supported`);return archBinary}function detectPlatformBinary({[platform$4]:platformBinary},{wsl}){if(wsl&&is_wsl_default)return detectArchBinary(wsl);if(!platformBinary)throw Error(`${platform$4} is not supported`);return detectArchBinary(platformBinary)}const apps={};defineLazyProperty(apps,`chrome`,()=>detectPlatformBinary({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),defineLazyProperty(apps,`brave`,()=>detectPlatformBinary({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),defineLazyProperty(apps,`firefox`,()=>detectPlatformBinary({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),defineLazyProperty(apps,`edge`,()=>detectPlatformBinary({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),defineLazyProperty(apps,`browser`,()=>`browser`),defineLazyProperty(apps,`browserPrivate`,()=>`browserPrivate`);var open_default=open$2,Emitter$1=class{listeners=[];get event(){return listener=>(this.listeners.push(listener),{dispose:()=>{this.listeners=this.listeners.filter(l$2=>l$2!==listener)}})}emit(event){for(let i$7=this.listeners.length-1;i$7>=0;i$7--)this.listeners[i$7]?.(event)}dispose(){this.listeners=[]}};let MessageType$1=function(MessageType$2){return MessageType$2[MessageType$2.DATA=0]=`DATA`,MessageType$2[MessageType$2.CLOSE=1]=`CLOSE`,MessageType$2[MessageType$2.ERROR=2]=`ERROR`,MessageType$2}({}),Flag$1=function(Flag$2){return Flag$2[Flag$2.NEW=1]=`NEW`,Flag$2}({});var BufferPool$1=class{static MAX_POOL_SIZE=100;static COMMON_SIZES=[64,256,1024,4096,16384];static pools=new Map;static{for(let size of this.COMMON_SIZES)this.pools.set(size,[])}static acquire(size){for(let poolSize of this.COMMON_SIZES)if(poolSize>=size){let pool$1=this.pools.get(poolSize);if(pool$1&&pool$1.length>0)return pool$1.pop();break}return new Uint8Array(size)}static release(buffer$2){let size=buffer$2.length;for(let poolSize of this.COMMON_SIZES)if(poolSize===size){let pool$1=this.pools.get(poolSize);pool$1&&pool$1.length<this.MAX_POOL_SIZE&&pool$1.push(buffer$2);break}}},FrameCodec$1=class FrameCodec$1{static HEADER_SIZE=4;static MAX_FRAME_SIZE=1024*1024-FrameCodec$1.HEADER_SIZE;static encode(frame){let payloadLength=frame.payload.length;if(payloadLength>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${payloadLength} > ${this.MAX_FRAME_SIZE}`);let totalSize=this.HEADER_SIZE+payloadLength,result=BufferPool$1.acquire(totalSize),word=frame.streamId<<8|frame.type<<4|frame.flags&15;return result[0]=word>>>24&255,result[1]=word>>>16&255,result[2]=word>>>8&255,result[3]=word&255,payloadLength>0&&result.set(frame.payload,this.HEADER_SIZE),result.length===totalSize?result:result.subarray(0,totalSize)}static encodeTyped(streamId,msgType,flags,typeByte,payload){let payloadLength=1+payload.length;if(payloadLength>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${payloadLength} > ${this.MAX_FRAME_SIZE}`);let totalSize=this.HEADER_SIZE+payloadLength,result=BufferPool$1.acquire(totalSize),word=streamId<<8|msgType<<4|flags&15;return result[0]=word>>>24&255,result[1]=word>>>16&255,result[2]=word>>>8&255,result[3]=word&255,result[FrameCodec$1.HEADER_SIZE]=typeByte&255,payload.length>0&&result.set(payload,FrameCodec$1.HEADER_SIZE+1),result.length===totalSize?result:result.subarray(0,totalSize)}static decode(data$2){if(data$2.length<FrameCodec$1.HEADER_SIZE)throw Error(`Invalid frame: too short (${data$2.length} < ${FrameCodec$1.HEADER_SIZE})`);let word=data$2[0]<<24|data$2[1]<<16|data$2[2]<<8|data$2[3],streamId=word>>>8,typeAndFlags=word&255,type=typeAndFlags>>>4,flags=typeAndFlags&15,payload=data$2.length>FrameCodec$1.HEADER_SIZE?data$2.subarray(FrameCodec$1.HEADER_SIZE):new Uint8Array;return{streamId,type,flags,payload}}static releaseBuffer(buffer$2){BufferPool$1.release(buffer$2)}static getMaxPayloadSize(){return FrameCodec$1.MAX_FRAME_SIZE}},Stream$8=class{_onData;_onClose;_onError;_disposed=!1;_id;constructor(id,send,sendTypedCb){this.send=send,this.sendTypedCb=sendTypedCb,this._id=id}get id(){return this._id}get onData(){return this._onData||=new Emitter$1,this._onData.event}get onClose(){return this._onClose||=new Emitter$1,this._onClose.event}get onError(){return this._onError||=new Emitter$1,this._onError.event}write(data$2,isFirst=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let maxPayload=FrameCodec$1.getMaxPayloadSize();if(data$2.length<=maxPayload){this.send({streamId:this.id,type:MessageType$1.DATA,flags:isFirst?Flag$1.NEW:0,payload:data$2});return}let offset=0,firstChunk=!0;for(;offset<data$2.length;){let remaining=data$2.length-offset,chunkSize=remaining>maxPayload?maxPayload:remaining,chunk$1=data$2.subarray(offset,offset+chunkSize);this.send({streamId:this.id,type:MessageType$1.DATA,flags:isFirst&&firstChunk?Flag$1.NEW:0,payload:chunk$1}),offset+=chunkSize,firstChunk=!1}}writeTyped(typeByte,data$2,isFirst=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);if(!this.sendTypedCb){let merged=new Uint8Array(1+data$2.length);merged[0]=typeByte&255,data$2.length&&merged.set(data$2,1),this.write(merged,isFirst);return}let maxPayload=FrameCodec$1.getMaxPayloadSize()-1;if(data$2.length<=maxPayload){this.sendTypedCb(this.id,isFirst?Flag$1.NEW:0,typeByte,data$2);return}let offset=0,firstChunk=!0;for(;offset<data$2.length;){let remaining=data$2.length-offset,chunkSize=remaining>maxPayload?maxPayload:remaining,chunk$1=data$2.subarray(offset,offset+chunkSize);this.sendTypedCb(this.id,isFirst&&firstChunk?Flag$1.NEW:0,typeByte,chunk$1),offset+=chunkSize,firstChunk=!1}}close(){this._disposed||(this.send({streamId:this.id,type:MessageType$1.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(message){this._disposed||this.send({streamId:this.id,type:MessageType$1.ERROR,flags:0,payload:new TextEncoder().encode(message)})}_handleFrame(frame){if(!this._disposed)switch(frame.type){case MessageType$1.DATA:this._onData?.emit(frame.payload);break;case MessageType$1.CLOSE:this._onClose?.emit(),this._dispose();break;case MessageType$1.ERROR:let error$22=new TextDecoder().decode(frame.payload);this._onError?.emit(error$22),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(newId,newSend,newSendTyped){this._dispose(),this._id=newId,this.send=newSend,this.sendTypedCb=newSendTyped,this._disposed=!1}get createdByClient(){return this.id%2==1}get disposed(){return this._disposed}},StreamPool$1=class{static MAX_POOL_SIZE=200;static pool=[];static acquire(id,send,sendTyped){let stream$10=this.pool.pop();return stream$10?(stream$10._reset(id,send,sendTyped),stream$10):new Stream$8(id,send,sendTyped)}static release(stream$10){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(stream$10)}},Multiplexer$1=class{_onNextStreamIDChange=new Emitter$1;onNextStreamIDChange=this._onNextStreamIDChange.event;_onStream=new Emitter$1;onStream=this._onStream.event;streams=[];streamCount=0;nextStreamId=1;send;releaseAfterSend;constructor(opts){this.nextStreamId=opts.initialNextStreamID??(opts.isClient?1:2),this.send=opts.send,this.releaseAfterSend=!!opts.releaseAfterSend}getStream(id){return this.streams[id]}createStream(id){id===void 0&&(id=this.nextStreamId,this.nextStreamId+=2,this._onNextStreamIDChange.emit(this.nextStreamId));let existingStream=this.streams[id];if(existingStream&&!existingStream.disposed)throw Error(`Stream ${id} already exists`);let stream$10=StreamPool$1.acquire(id,frame=>this.sendFrame(frame),(sid,flags,typeByte,payload)=>this.sendFrameTyped(sid,typeByte,flags,payload));return this.streams[id]=stream$10,this.streamCount++,stream$10}sendFrame(frame){let encoded=FrameCodec$1.encode(frame);try{this.send(encoded)}finally{this.releaseAfterSend&&FrameCodec$1.releaseBuffer(encoded)}}sendFrameTyped(streamId,appTypeByte,flags,payload){let encoded=FrameCodec$1.encodeTyped(streamId,MessageType$1.DATA,flags,appTypeByte,payload);try{this.send(encoded)}finally{this.releaseAfterSend&&FrameCodec$1.releaseBuffer(encoded)}}handleMessage(data$2){this.handleFrame(FrameCodec$1.decode(data$2))}handleFrame(frame){let stream$10=this.streams[frame.streamId];(!stream$10||stream$10.disposed)&&(stream$10=StreamPool$1.acquire(frame.streamId,frame$1=>this.sendFrame(frame$1),(sid,flags,typeByte,payload)=>this.sendFrameTyped(sid,typeByte,flags,payload)),this.streams[frame.streamId]=stream$10,this.streamCount++,this._onStream.emit(stream$10)),stream$10._handleFrame(frame),(frame.type===MessageType$1.CLOSE||frame.type===MessageType$1.ERROR)&&(this.streams[frame.streamId]=void 0,this.streamCount--,StreamPool$1.release(stream$10))}get activeStreamCount(){return this.streamCount}dispose(){for(let stream$10 of this.streams)stream$10&&!stream$10.disposed&&(stream$10.close(),StreamPool$1.release(stream$10));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}};const defaultMessages$1=`End-Of-Stream`;var EndOfStreamError$1=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},AbortError$8=class extends Error{constructor(message=`The operation was aborted`){super(message),this.name=`AbortError`}},AbstractStreamReader$1=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(uint8Array,mayBeLess=!1){let bytesRead=await this.read(uint8Array,mayBeLess);return this.peekQueue.push(uint8Array.subarray(0,bytesRead)),bytesRead}async read(buffer$2,mayBeLess=!1){if(buffer$2.length===0)return 0;let bytesRead=this.readFromPeekBuffer(buffer$2);if(this.endOfStream||(bytesRead+=await this.readRemainderFromStream(buffer$2.subarray(bytesRead),mayBeLess)),bytesRead===0&&!mayBeLess)throw new EndOfStreamError$1;return bytesRead}readFromPeekBuffer(buffer$2){let remaining=buffer$2.length,bytesRead=0;for(;this.peekQueue.length>0&&remaining>0;){let peekData=this.peekQueue.pop();if(!peekData)throw Error(`peekData should be defined`);let lenCopy=Math.min(peekData.length,remaining);buffer$2.set(peekData.subarray(0,lenCopy),bytesRead),bytesRead+=lenCopy,remaining-=lenCopy,lenCopy<peekData.length&&this.peekQueue.push(peekData.subarray(lenCopy))}return bytesRead}async readRemainderFromStream(buffer$2,mayBeLess){let bytesRead=0;for(;bytesRead<buffer$2.length&&!this.endOfStream;){if(this.interrupted)throw new AbortError$8;let chunkLen=await this.readFromStream(buffer$2.subarray(bytesRead),mayBeLess);if(chunkLen===0)break;bytesRead+=chunkLen}if(!mayBeLess&&bytesRead<buffer$2.length)throw new EndOfStreamError$1;return bytesRead}},WebStreamReader$1=class extends AbstractStreamReader$1{constructor(reader){super(),this.reader=reader}async abort(){return this.close()}async close(){this.reader.releaseLock()}},WebStreamByobReader$1=class extends WebStreamReader$1{async readFromStream(buffer$2,mayBeLess){if(buffer$2.length===0)return 0;let result=await this.reader.read(new Uint8Array(buffer$2.length),{min:mayBeLess?void 0:buffer$2.length});return result.done&&(this.endOfStream=result.done),result.value?(buffer$2.set(result.value),result.value.length):0}},WebStreamDefaultReader$1=class extends AbstractStreamReader$1{constructor(reader){super(),this.reader=reader,this.buffer=null}writeChunk(target,chunk$1){let written=Math.min(chunk$1.length,target.length);return target.set(chunk$1.subarray(0,written)),written<chunk$1.length?this.buffer=chunk$1.subarray(written):this.buffer=null,written}async readFromStream(buffer$2,mayBeLess){if(buffer$2.length===0)return 0;let totalBytesRead=0;for(this.buffer&&(totalBytesRead+=this.writeChunk(buffer$2,this.buffer));totalBytesRead<buffer$2.length&&!this.endOfStream;){let result=await this.reader.read();if(result.done){this.endOfStream=!0;break}result.value&&(totalBytesRead+=this.writeChunk(buffer$2.subarray(totalBytesRead),result.value))}if(!mayBeLess&&totalBytesRead===0&&this.endOfStream)throw new EndOfStreamError$1;return totalBytesRead}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function makeWebStreamReader$1(stream$10){try{let reader=stream$10.getReader({mode:`byob`});return reader instanceof ReadableStreamDefaultReader?new WebStreamDefaultReader$1(reader):new WebStreamByobReader$1(reader)}catch(error$22){if(error$22 instanceof TypeError)return new WebStreamDefaultReader$1(stream$10.getReader());throw error$22}}var AbstractTokenizer$1=class{constructor(options$1){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=options$1?.onClose,options$1?.abortSignal&&options$1.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(token$1,position=this.position){let uint8Array=new Uint8Array(token$1.len),len$1=await this.readBuffer(uint8Array,{position});if(len$1<token$1.len)throw new EndOfStreamError$1;return token$1.get(uint8Array,0)}async peekToken(token$1,position=this.position){let uint8Array=new Uint8Array(token$1.len),len$1=await this.peekBuffer(uint8Array,{position});if(len$1<token$1.len)throw new EndOfStreamError$1;return token$1.get(uint8Array,0)}async readNumber(token$1){let len$1=await this.readBuffer(this.numBuffer,{length:token$1.len});if(len$1<token$1.len)throw new EndOfStreamError$1;return token$1.get(this.numBuffer,0)}async peekNumber(token$1){let len$1=await this.peekBuffer(this.numBuffer,{length:token$1.len});if(len$1<token$1.len)throw new EndOfStreamError$1;return token$1.get(this.numBuffer,0)}async ignore(length){if(this.fileInfo.size!==void 0){let bytesLeft=this.fileInfo.size-this.position;if(length>bytesLeft)return this.position+=bytesLeft,bytesLeft}return this.position+=length,length}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(uint8Array,options$1){if(!this.supportsRandomAccess()&&options$1&&options$1.position!==void 0&&options$1.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:uint8Array.length,position:this.position,...options$1}}abort(){return Promise.resolve()}};const maxBufferSize$1=256e3;var ReadStreamTokenizer$1=class extends AbstractTokenizer$1{constructor(streamReader,options$1){super(options$1),this.streamReader=streamReader,this.fileInfo=options$1?.fileInfo??{}}async readBuffer(uint8Array,options$1){let normOptions=this.normalizeOptions(uint8Array,options$1),skipBytes=normOptions.position-this.position;if(skipBytes>0)return await this.ignore(skipBytes),this.readBuffer(uint8Array,options$1);if(skipBytes<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(normOptions.length===0)return 0;let bytesRead=await this.streamReader.read(uint8Array.subarray(0,normOptions.length),normOptions.mayBeLess);if(this.position+=bytesRead,(!options$1||!options$1.mayBeLess)&&bytesRead<normOptions.length)throw new EndOfStreamError$1;return bytesRead}async peekBuffer(uint8Array,options$1){let normOptions=this.normalizeOptions(uint8Array,options$1),bytesRead=0;if(normOptions.position){let skipBytes=normOptions.position-this.position;if(skipBytes>0){let skipBuffer=new Uint8Array(normOptions.length+skipBytes);return bytesRead=await this.peekBuffer(skipBuffer,{mayBeLess:normOptions.mayBeLess}),uint8Array.set(skipBuffer.subarray(skipBytes)),bytesRead-skipBytes}if(skipBytes<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(normOptions.length>0){try{bytesRead=await this.streamReader.peek(uint8Array.subarray(0,normOptions.length),normOptions.mayBeLess)}catch(err$2){if(options$1?.mayBeLess&&err$2 instanceof EndOfStreamError$1)return 0;throw err$2}if(!normOptions.mayBeLess&&bytesRead<normOptions.length)throw new EndOfStreamError$1}return bytesRead}async ignore(length){let bufSize=Math.min(256e3,length),buf=new Uint8Array(bufSize),totBytesRead=0;for(;totBytesRead<length;){let remaining=length-totBytesRead,bytesRead=await this.readBuffer(buf,{length:Math.min(bufSize,remaining)});if(bytesRead<0)return bytesRead;totBytesRead+=bytesRead}return totBytesRead}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},BufferTokenizer$1=class extends AbstractTokenizer$1{constructor(uint8Array,options$1){super(options$1),this.uint8Array=uint8Array,this.fileInfo={...options$1?.fileInfo??{},size:uint8Array.length}}async readBuffer(uint8Array,options$1){options$1?.position&&(this.position=options$1.position);let bytesRead=await this.peekBuffer(uint8Array,options$1);return this.position+=bytesRead,bytesRead}async peekBuffer(uint8Array,options$1){let normOptions=this.normalizeOptions(uint8Array,options$1),bytes2read=Math.min(this.uint8Array.length-normOptions.position,normOptions.length);if(!normOptions.mayBeLess&&bytes2read<normOptions.length)throw new EndOfStreamError$1;return uint8Array.set(this.uint8Array.subarray(normOptions.position,normOptions.position+bytes2read)),bytes2read}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(position){this.position=position}};function fromWebStream$1(webStream,options$1){let webStreamReader=makeWebStreamReader$1(webStream),_options$1=options$1??{},chainedClose=_options$1.onClose;return _options$1.onClose=async()=>{if(await webStreamReader.close(),chainedClose)return chainedClose()},new ReadStreamTokenizer$1(webStreamReader,_options$1)}function fromBuffer$2(uint8Array,options$1){return new BufferTokenizer$1(uint8Array,options$1)}const WINDOWS_1252_EXTRA$1={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:`Ÿ`},WINDOWS_1252_REVERSE$1={};for(let[code$1,char]of Object.entries(WINDOWS_1252_EXTRA$1))WINDOWS_1252_REVERSE$1[char]=Number.parseInt(code$1);function textDecode$1(bytes,encoding=`utf-8`){switch(encoding.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?decodeUTF8$1(bytes):new globalThis.TextDecoder(`utf-8`).decode(bytes);case`utf-16le`:return decodeUTF16LE$1(bytes);case`ascii`:return decodeASCII$1(bytes);case`latin1`:case`iso-8859-1`:return decodeLatin1$1(bytes);case`windows-1252`:return decodeWindows1252$1(bytes);default:throw RangeError(`Encoding '${encoding}' not supported`)}}function decodeUTF8$1(bytes){let out=``,i$7=0;for(;i$7<bytes.length;){let b1=bytes[i$7++];if(b1<128)out+=String.fromCharCode(b1);else if(b1<224){let b2=bytes[i$7++]&63;out+=String.fromCharCode((b1&31)<<6|b2)}else if(b1<240){let b2=bytes[i$7++]&63,b3=bytes[i$7++]&63;out+=String.fromCharCode((b1&15)<<12|b2<<6|b3)}else{let b2=bytes[i$7++]&63,b3=bytes[i$7++]&63,b4=bytes[i$7++]&63,cp$1=(b1&7)<<18|b2<<12|b3<<6|b4;cp$1-=65536,out+=String.fromCharCode(55296+(cp$1>>10&1023),56320+(cp$1&1023))}}return out}function decodeUTF16LE$1(bytes){let out=``;for(let i$7=0;i$7<bytes.length;i$7+=2)out+=String.fromCharCode(bytes[i$7]|bytes[i$7+1]<<8);return out}function decodeASCII$1(bytes){return String.fromCharCode(...bytes.map(b$4=>b$4&127))}function decodeLatin1$1(bytes){return String.fromCharCode(...bytes)}function decodeWindows1252$1(bytes){let out=``;for(let b$4 of bytes)b$4>=128&&b$4<=159&&WINDOWS_1252_EXTRA$1[b$4]?out+=WINDOWS_1252_EXTRA$1[b$4]:out+=String.fromCharCode(b$4);return out}function dv$1(array){return new DataView(array.buffer,array.byteOffset)}const UINT8$1={len:1,get(array,offset){return dv$1(array).getUint8(offset)},put(array,offset,value){return dv$1(array).setUint8(offset,value),offset+1}},UINT16_LE$1={len:2,get(array,offset){return dv$1(array).getUint16(offset,!0)},put(array,offset,value){return dv$1(array).setUint16(offset,value,!0),offset+2}},UINT16_BE$1={len:2,get(array,offset){return dv$1(array).getUint16(offset)},put(array,offset,value){return dv$1(array).setUint16(offset,value),offset+2}},UINT32_LE$1={len:4,get(array,offset){return dv$1(array).getUint32(offset,!0)},put(array,offset,value){return dv$1(array).setUint32(offset,value,!0),offset+4}},UINT32_BE$1={len:4,get(array,offset){return dv$1(array).getUint32(offset)},put(array,offset,value){return dv$1(array).setUint32(offset,value),offset+4}},INT32_BE$1={len:4,get(array,offset){return dv$1(array).getInt32(offset)},put(array,offset,value){return dv$1(array).setInt32(offset,value),offset+4}},UINT64_LE$1={len:8,get(array,offset){return dv$1(array).getBigUint64(offset,!0)},put(array,offset,value){return dv$1(array).setBigUint64(offset,value,!0),offset+8}};var StringType$1=class{constructor(len$1,encoding){this.len=len$1,this.encoding=encoding}get(data$2,offset=0){let bytes=data$2.subarray(offset,offset+this.len);return textDecode$1(bytes,this.encoding)}},require$2=createRequire$1(`/`),Worker$1;try{Worker$1=require$2(`worker_threads`).Worker}catch{}var u8$1=Uint8Array,u16$1=Uint16Array,i32$1=Int32Array,fleb$1=new u8$1([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]),fdeb$1=new u8$1([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]),clim$1=new u8$1([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb$1=function(eb,start$1){for(var b$4=new u16$1(31),i$7=0;i$7<31;++i$7)b$4[i$7]=start$1+=1<<eb[i$7-1];for(var r$3=new i32$1(b$4[30]),i$7=1;i$7<30;++i$7)for(var j$2=b$4[i$7];j$2<b$4[i$7+1];++j$2)r$3[j$2]=j$2-b$4[i$7]<<5|i$7;return{b:b$4,r:r$3}},_a$14=freb$1(fleb$1,2),fl$1=_a$14.b,revfl$1=_a$14.r;fl$1[28]=258,revfl$1[258]=28;for(var _b$4=freb$1(fdeb$1,0),fd$1=_b$4.b,revfd=_b$4.r,rev$1=new u16$1(32768),i$6=0;i$6<32768;++i$6){var x$4=(i$6&43690)>>1|(i$6&21845)<<1;x$4=(x$4&52428)>>2|(x$4&13107)<<2,x$4=(x$4&61680)>>4|(x$4&3855)<<4,rev$1[i$6]=((x$4&65280)>>8|(x$4&255)<<8)>>1}for(var hMap$1=(function(cd,mb,r$3){for(var s$3=cd.length,i$7=0,l$2=new u16$1(mb);i$7<s$3;++i$7)cd[i$7]&&++l$2[cd[i$7]-1];var le$3=new u16$1(mb);for(i$7=1;i$7<mb;++i$7)le$3[i$7]=le$3[i$7-1]+l$2[i$7-1]<<1;var co;if(r$3){co=new u16$1(1<<mb);var rvb=15-mb;for(i$7=0;i$7<s$3;++i$7)if(cd[i$7])for(var sv=i$7<<4|cd[i$7],r_1=mb-cd[i$7],v$2=le$3[cd[i$7]-1]++<<r_1,m$3=v$2|(1<<r_1)-1;v$2<=m$3;++v$2)co[rev$1[v$2]>>rvb]=sv}else for(co=new u16$1(s$3),i$7=0;i$7<s$3;++i$7)cd[i$7]&&(co[i$7]=rev$1[le$3[cd[i$7]-1]++]>>15-cd[i$7]);return co}),flt$1=new u8$1(288),i$6=0;i$6<144;++i$6)flt$1[i$6]=8;for(var i$6=144;i$6<256;++i$6)flt$1[i$6]=9;for(var i$6=256;i$6<280;++i$6)flt$1[i$6]=7;for(var i$6=280;i$6<288;++i$6)flt$1[i$6]=8;for(var fdt$1=new u8$1(32),i$6=0;i$6<32;++i$6)fdt$1[i$6]=5;var flm=hMap$1(flt$1,9,0),flrm$1=hMap$1(flt$1,9,1),fdm=hMap$1(fdt$1,5,0),fdrm$1=hMap$1(fdt$1,5,1),max$2=function(a$4){for(var m$3=a$4[0],i$7=1;i$7<a$4.length;++i$7)a$4[i$7]>m$3&&(m$3=a$4[i$7]);return m$3},bits$1=function(d$5,p$2,m$3){var o$3=p$2/8|0;return(d$5[o$3]|d$5[o$3+1]<<8)>>(p$2&7)&m$3},bits16$1=function(d$5,p$2){var o$3=p$2/8|0;return(d$5[o$3]|d$5[o$3+1]<<8|d$5[o$3+2]<<16)>>(p$2&7)},shft$1=function(p$2){return(p$2+7)/8|0},slc$1=function(v$2,s$3,e$3){return(s$3==null||s$3<0)&&(s$3=0),(e$3==null||e$3>v$2.length)&&(e$3=v$2.length),new u8$1(v$2.subarray(s$3,e$3))},ec$1=[`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`],err$1=function(ind,msg,nt){var e$3=Error(msg||ec$1[ind]);if(e$3.code=ind,Error.captureStackTrace&&Error.captureStackTrace(e$3,err$1),!nt)throw e$3;return e$3},inflt$1=function(dat,st,buf,dict){var sl=dat.length,dl=dict?dict.length:0;if(!sl||st.f&&!st.l)return buf||new u8$1(0);var noBuf=!buf,resize=noBuf||st.i!=2,noSt=st.i;noBuf&&(buf=new u8$1(sl*3));var cbuf=function(l$3){var bl=buf.length;if(l$3>bl){var nbuf=new u8$1(Math.max(bl*2,l$3));nbuf.set(buf),buf=nbuf}},final=st.f||0,pos=st.p||0,bt=st.b||0,lm=st.l,dm=st.d,lbt=st.m,dbt=st.n,tbts=sl*8;do{if(!lm){final=bits$1(dat,pos,1);var type=bits$1(dat,pos+1,3);if(pos+=3,type)if(type==1)lm=flrm$1,dm=fdrm$1,lbt=9,dbt=5;else if(type==2){var hLit=bits$1(dat,pos,31)+257,hcLen=bits$1(dat,pos+10,15)+4,tl=hLit+bits$1(dat,pos+5,31)+1;pos+=14;for(var ldt=new u8$1(tl),clt=new u8$1(19),i$7=0;i$7<hcLen;++i$7)clt[clim$1[i$7]]=bits$1(dat,pos+i$7*3,7);pos+=hcLen*3;for(var clb=max$2(clt),clbmsk=(1<<clb)-1,clm=hMap$1(clt,clb,1),i$7=0;i$7<tl;){var r$3=clm[bits$1(dat,pos,clbmsk)];pos+=r$3&15;var s$3=r$3>>4;if(s$3<16)ldt[i$7++]=s$3;else{var c$3=0,n$2=0;for(s$3==16?(n$2=3+bits$1(dat,pos,3),pos+=2,c$3=ldt[i$7-1]):s$3==17?(n$2=3+bits$1(dat,pos,7),pos+=3):s$3==18&&(n$2=11+bits$1(dat,pos,127),pos+=7);n$2--;)ldt[i$7++]=c$3}}var lt=ldt.subarray(0,hLit),dt=ldt.subarray(hLit);lbt=max$2(lt),dbt=max$2(dt),lm=hMap$1(lt,lbt,1),dm=hMap$1(dt,dbt,1)}else err$1(1);else{var s$3=shft$1(pos)+4,l$2=dat[s$3-4]|dat[s$3-3]<<8,t$1=s$3+l$2;if(t$1>sl){noSt&&err$1(0);break}resize&&cbuf(bt+l$2),buf.set(dat.subarray(s$3,t$1),bt),st.b=bt+=l$2,st.p=pos=t$1*8,st.f=final;continue}if(pos>tbts){noSt&&err$1(0);break}}resize&&cbuf(bt+131072);for(var lms=(1<<lbt)-1,dms=(1<<dbt)-1,lpos=pos;;lpos=pos){var c$3=lm[bits16$1(dat,pos)&lms],sym=c$3>>4;if(pos+=c$3&15,pos>tbts){noSt&&err$1(0);break}if(c$3||err$1(2),sym<256)buf[bt++]=sym;else if(sym==256){lpos=pos,lm=null;break}else{var add=sym-254;if(sym>264){var i$7=sym-257,b$4=fleb$1[i$7];add=bits$1(dat,pos,(1<<b$4)-1)+fl$1[i$7],pos+=b$4}var d$5=dm[bits16$1(dat,pos)&dms],dsym=d$5>>4;d$5||err$1(3),pos+=d$5&15;var dt=fd$1[dsym];if(dsym>3){var b$4=fdeb$1[dsym];dt+=bits16$1(dat,pos)&(1<<b$4)-1,pos+=b$4}if(pos>tbts){noSt&&err$1(0);break}resize&&cbuf(bt+131072);var end=bt+add;if(bt<dt){var shift=dl-dt,dend=Math.min(dt,end);for(shift+bt<0&&err$1(3);bt<dend;++bt)buf[bt]=dict[shift+bt]}for(;bt<end;++bt)buf[bt]=buf[bt-dt]}}st.l=lm,st.p=lpos,st.b=bt,st.f=final,lm&&(final=1,st.m=lbt,st.d=dm,st.n=dbt)}while(!final);return bt!=buf.length&&noBuf?slc$1(buf,0,bt):buf.subarray(0,bt)},et$1=new u8$1(0),gzs$1=function(d$5){(d$5[0]!=31||d$5[1]!=139||d$5[2]!=8)&&err$1(6,`invalid gzip data`);var flg=d$5[3],st=10;flg&4&&(st+=(d$5[10]|d$5[11]<<8)+2);for(var zs=(flg>>3&1)+(flg>>4&1);zs>0;zs-=!d$5[st++]);return st+(flg&2)},gzl$1=function(d$5){var l$2=d$5.length;return(d$5[l$2-4]|d$5[l$2-3]<<8|d$5[l$2-2]<<16|d$5[l$2-1]<<24)>>>0},zls$1=function(d$5,dict){return((d$5[0]&15)!=8||d$5[0]>>4>7||(d$5[0]<<8|d$5[1])%31)&&err$1(6,`invalid zlib data`),(d$5[1]>>5&1)==+!dict&&err$1(6,`invalid zlib data: `+(d$5[1]&32?`need`:`unexpected`)+` dictionary`),(d$5[1]>>3&4)+2};function inflateSync$1(data$2,opts){return inflt$1(data$2,{i:2},opts&&opts.out,opts&&opts.dictionary)}function gunzipSync$1(data$2,opts){var st=gzs$1(data$2);return st+8>data$2.length&&err$1(6,`invalid gzip data`),inflt$1(data$2.subarray(st,-8),{i:2},opts&&opts.out||new u8$1(gzl$1(data$2)),opts&&opts.dictionary)}function unzlibSync$1(data$2,opts){return inflt$1(data$2.subarray(zls$1(data$2,opts&&opts.dictionary),-4),{i:2},opts&&opts.out,opts&&opts.dictionary)}function decompressSync$1(data$2,opts){return data$2[0]==31&&data$2[1]==139&&data$2[2]==8?gunzipSync$1(data$2,opts):(data$2[0]&15)!=8||data$2[0]>>4>7||(data$2[0]<<8|data$2[1])%31?inflateSync$1(data$2,opts):unzlibSync$1(data$2,opts)}var td$1=typeof TextDecoder<`u`&&new TextDecoder,tds$1=0;try{td$1.decode(et$1,{stream:!0}),tds$1=1}catch{}var require_ms$1=__commonJSMin(((exports,module)=>{var s$2=1e3,m$2=s$2*60,h$3=m$2*60,d$4=h$3*24,w$3=d$4*7,y$3=d$4*365.25;module.exports=function(val,options$1){options$1||={};var type=typeof val;if(type===`string`&&val.length>0)return parse$18(val);if(type===`number`&&isFinite(val))return options$1.long?fmtLong(val):fmtShort(val);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(val))};function parse$18(str$1){if(str$1=String(str$1),!(str$1.length>100)){var match$1=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str$1);if(match$1){var n$2=parseFloat(match$1[1]),type=(match$1[2]||`ms`).toLowerCase();switch(type){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return n$2*y$3;case`weeks`:case`week`:case`w`:return n$2*w$3;case`days`:case`day`:case`d`:return n$2*d$4;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return n$2*h$3;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return n$2*m$2;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return n$2*s$2;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return n$2;default:return}}}}function fmtShort(ms){var msAbs=Math.abs(ms);return msAbs>=d$4?Math.round(ms/d$4)+`d`:msAbs>=h$3?Math.round(ms/h$3)+`h`:msAbs>=m$2?Math.round(ms/m$2)+`m`:msAbs>=s$2?Math.round(ms/s$2)+`s`:ms+`ms`}function fmtLong(ms){var msAbs=Math.abs(ms);return msAbs>=d$4?plural(ms,msAbs,d$4,`day`):msAbs>=h$3?plural(ms,msAbs,h$3,`hour`):msAbs>=m$2?plural(ms,msAbs,m$2,`minute`):msAbs>=s$2?plural(ms,msAbs,s$2,`second`):ms+` ms`}function plural(ms,msAbs,n$2,name$5){var isPlural=msAbs>=n$2*1.5;return Math.round(ms/n$2)+` `+name$5+(isPlural?`s`:``)}})),require_common$4=__commonJSMin(((exports,module)=>{function setup$7(env$8){createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=coerce,createDebug.disable=disable,createDebug.enable=enable,createDebug.enabled=enabled,createDebug.humanize=require_ms$1(),createDebug.destroy=destroy$2,Object.keys(env$8).forEach(key=>{createDebug[key]=env$8[key]}),createDebug.names=[],createDebug.skips=[],createDebug.formatters={};function selectColor(namespace){let hash$1=0;for(let i$7=0;i$7<namespace.length;i$7++)hash$1=(hash$1<<5)-hash$1+namespace.charCodeAt(i$7),hash$1|=0;return createDebug.colors[Math.abs(hash$1)%createDebug.colors.length]}createDebug.selectColor=selectColor;function createDebug(namespace){let prevTime,enableOverride=null,namespacesCache,enabledCache;function debug$12(...args){if(!debug$12.enabled)return;let self$1=debug$12,curr=Number(new Date),ms=curr-(prevTime||curr);self$1.diff=ms,self$1.prev=prevTime,self$1.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),typeof args[0]!=`string`&&args.unshift(`%O`);let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match$1,format$4)=>{if(match$1===`%%`)return`%`;index++;let formatter$1=createDebug.formatters[format$4];if(typeof formatter$1==`function`){let val=args[index];match$1=formatter$1.call(self$1,val),args.splice(index,1),index--}return match$1}),createDebug.formatArgs.call(self$1,args);let logFn=self$1.log||createDebug.log;logFn.apply(self$1,args)}return debug$12.namespace=namespace,debug$12.useColors=createDebug.useColors(),debug$12.color=createDebug.selectColor(namespace),debug$12.extend=extend,debug$12.destroy=createDebug.destroy,Object.defineProperty(debug$12,`enabled`,{enumerable:!0,configurable:!1,get:()=>enableOverride===null?(namespacesCache!==createDebug.namespaces&&(namespacesCache=createDebug.namespaces,enabledCache=createDebug.enabled(namespace)),enabledCache):enableOverride,set:v$2=>{enableOverride=v$2}}),typeof createDebug.init==`function`&&createDebug.init(debug$12),debug$12}function extend(namespace,delimiter){let newDebug=createDebug(this.namespace+(delimiter===void 0?`:`:delimiter)+namespace);return newDebug.log=this.log,newDebug}function enable(namespaces){createDebug.save(namespaces),createDebug.namespaces=namespaces,createDebug.names=[],createDebug.skips=[];let split=(typeof namespaces==`string`?namespaces:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let ns of split)ns[0]===`-`?createDebug.skips.push(ns.slice(1)):createDebug.names.push(ns)}function matchesTemplate(search,template$1){let searchIndex=0,templateIndex=0,starIndex=-1,matchIndex=0;for(;searchIndex<search.length;)if(templateIndex<template$1.length&&(template$1[templateIndex]===search[searchIndex]||template$1[templateIndex]===`*`))template$1[templateIndex]===`*`?(starIndex=templateIndex,matchIndex=searchIndex,templateIndex++):(searchIndex++,templateIndex++);else if(starIndex!==-1)templateIndex=starIndex+1,matchIndex++,searchIndex=matchIndex;else return!1;for(;templateIndex<template$1.length&&template$1[templateIndex]===`*`;)templateIndex++;return templateIndex===template$1.length}function disable(){let namespaces=[...createDebug.names,...createDebug.skips.map(namespace=>`-`+namespace)].join(`,`);return createDebug.enable(``),namespaces}function enabled(name$5){for(let skip of createDebug.skips)if(matchesTemplate(name$5,skip))return!1;for(let ns of createDebug.names)if(matchesTemplate(name$5,ns))return!0;return!1}function coerce(val){return val instanceof Error?val.stack||val.message:val}function destroy$2(){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 createDebug.enable(createDebug.load()),createDebug}module.exports=setup$7})),require_browser$1=__commonJSMin(((exports,module)=>{exports.formatArgs=formatArgs$1,exports.save=save$1,exports.load=load$6,exports.useColors=useColors$1,exports.storage=localstorage(),exports.destroy=(()=>{let warned$1=!1;return()=>{warned$1||(warned$1=!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`."))}})(),exports.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 useColors$1(){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 m$3;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&&(m$3=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(m$3[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs$1(args){if(args[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+args[0]+(this.useColors?`%c `:` `)+`+`+module.exports.humanize(this.diff),!this.useColors)return;let c$3=`color: `+this.color;args.splice(1,0,c$3,`color: inherit`);let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match$1=>{match$1!==`%%`&&(index++,match$1===`%c`&&(lastC=index))}),args.splice(lastC,0,c$3)}exports.log=console.debug||console.log||(()=>{});function save$1(namespaces){try{namespaces?exports.storage.setItem(`debug`,namespaces):exports.storage.removeItem(`debug`)}catch{}}function load$6(){let r$3;try{r$3=exports.storage.getItem(`debug`)||exports.storage.getItem(`DEBUG`)}catch{}return!r$3&&typeof process<`u`&&`env`in process&&(r$3=process.env.DEBUG),r$3}function localstorage(){try{return localStorage}catch{}}module.exports=require_common$4()(exports);let{formatters:formatters$1}=module.exports;formatters$1.j=function(v$2){try{return JSON.stringify(v$2)}catch(error$22){return`[UnexpectedJSONParseError]: `+error$22.message}}})),require_has_flag$2=__commonJSMin(((exports,module)=>{module.exports=(flag,argv$1=process.argv)=>{let prefix=flag.startsWith(`-`)?``:flag.length===1?`-`:`--`,position=argv$1.indexOf(prefix+flag),terminatorPosition=argv$1.indexOf(`--`);return position!==-1&&(terminatorPosition===-1||position<terminatorPosition)}})),require_supports_color$3=__commonJSMin(((exports,module)=>{let os$13=__require$2(`os`),tty$5=__require$2(`tty`),hasFlag$5=require_has_flag$2(),{env:env$7}=process,forceColor$3;hasFlag$5(`no-color`)||hasFlag$5(`no-colors`)||hasFlag$5(`color=false`)||hasFlag$5(`color=never`)?forceColor$3=0:(hasFlag$5(`color`)||hasFlag$5(`colors`)||hasFlag$5(`color=true`)||hasFlag$5(`color=always`))&&(forceColor$3=1),`FORCE_COLOR`in env$7&&(forceColor$3=env$7.FORCE_COLOR===`true`?1:env$7.FORCE_COLOR===`false`?0:env$7.FORCE_COLOR.length===0?1:Math.min(parseInt(env$7.FORCE_COLOR,10),3));function translateLevel$4(level$1){return level$1===0?!1:{level:level$1,hasBasic:!0,has256:level$1>=2,has16m:level$1>=3}}function supportsColor$5(haveStream,streamIsTTY){if(forceColor$3===0)return 0;if(hasFlag$5(`color=16m`)||hasFlag$5(`color=full`)||hasFlag$5(`color=truecolor`))return 3;if(hasFlag$5(`color=256`))return 2;if(haveStream&&!streamIsTTY&&forceColor$3===void 0)return 0;let min=forceColor$3||0;if(env$7.TERM===`dumb`)return min;if(process.platform===`win32`){let osRelease=os$13.release().split(`.`);return Number(osRelease[0])>=10&&Number(osRelease[2])>=10586?Number(osRelease[2])>=14931?3:2:1}if(`CI`in env$7)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(sign$2=>sign$2 in env$7)||env$7.CI_NAME===`codeship`?1:min;if(`TEAMCITY_VERSION`in env$7)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$7.TEAMCITY_VERSION)?1:0;if(env$7.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in env$7){let version$4=parseInt((env$7.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(env$7.TERM_PROGRAM){case`iTerm.app`:return version$4>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(env$7.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$7.TERM)||`COLORTERM`in env$7?1:min}function getSupportLevel$3(stream$10){let level$1=supportsColor$5(stream$10,stream$10&&stream$10.isTTY);return translateLevel$4(level$1)}module.exports={supportsColor:getSupportLevel$3,stdout:translateLevel$4(supportsColor$5(!0,tty$5.isatty(1))),stderr:translateLevel$4(supportsColor$5(!0,tty$5.isatty(2)))}})),require_node$19=__commonJSMin(((exports,module)=>{let tty$4=__require$2(`tty`),util$67=__require$2(`util`);exports.init=init$3,exports.log=log$4,exports.formatArgs=formatArgs,exports.save=save,exports.load=load$5,exports.useColors=useColors,exports.destroy=util$67.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),exports.colors=[6,2,3,4,5,1];try{let supportsColor$6=require_supports_color$3();supportsColor$6&&(supportsColor$6.stderr||supportsColor$6).level>=2&&(exports.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{}exports.inspectOpts=Object.keys(process.env).filter(key=>/^debug_/i.test(key)).reduce((obj,key)=>{let prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,(_$6,k$2)=>k$2.toUpperCase()),val=process.env[key];return val=/^(yes|on|true|enabled)$/i.test(val)?!0:/^(no|off|false|disabled)$/i.test(val)?!1:val===`null`?null:Number(val),obj[prop]=val,obj},{});function useColors(){return`colors`in exports.inspectOpts?!!exports.inspectOpts.colors:tty$4.isatty(process.stderr.fd)}function formatArgs(args){let{namespace:name$5,useColors:useColors$2}=this;if(useColors$2){let c$3=this.color,colorCode=`\x1B[3`+(c$3<8?c$3:`8;5;`+c$3),prefix=` ${colorCode};1m${name$5} \u001B[0m`;args[0]=prefix+args[0].split(`
25
+ Expecting one of '${allowedValues.join(`', '`)}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context$1=>{let helpStr;helpStr=typeof text$1==`function`?text$1({error:context$1.error,command:context$1.command}):text$1,helpStr&&context$1.write(`${helpStr}\n`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption(),helpRequested=helpOption&&args.find(arg=>helpOption.is(arg));helpRequested&&(this.outputHelp(),this._exit(0,`commander.helpDisplayed`,`(outputHelp)`))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith(`--inspect`))return arg;let debugOption,debugHost=`127.0.0.1`,debugPort=`9229`,match$1;return(match$1=arg.match(/^(--inspect(-brk)?)$/))===null?(match$1=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))===null?(match$1=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match$1[1],debugHost=match$1[3],debugPort=match$1[4]):(debugOption=match$1[1],/^\d+$/.test(match$1[3])?debugPort=match$1[3]:debugHost=match$1[3]):debugOption=match$1[1],debugOption&&debugPort!==`0`?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}function useColor(){if(process$8.env.NO_COLOR||process$8.env.FORCE_COLOR===`0`||process$8.env.FORCE_COLOR===`false`)return!1;if(process$8.env.FORCE_COLOR||process$8.env.CLICOLOR_FORCE!==void 0)return!0}exports.Command=Command$3,exports.useColor=useColor})),require_commander=__commonJSMin((exports=>{let{Argument:Argument$1}=require_argument(),{Command:Command$2}=require_command(),{CommanderError:CommanderError$1,InvalidArgumentError:InvalidArgumentError$37}=require_error$2(),{Help:Help$1}=require_help(),{Option:Option$1}=require_option();exports.program=new Command$2,exports.createCommand=name$5=>new Command$2(name$5),exports.createOption=(flags,description)=>new Option$1(flags,description),exports.createArgument=(name$5,description)=>new Argument$1(name$5,description),exports.Command=Command$2,exports.Option=Option$1,exports.Argument=Argument$1,exports.Help=Help$1,exports.CommanderError=CommanderError$1,exports.InvalidArgumentError=InvalidArgumentError$37,exports.InvalidOptionArgumentError=InvalidArgumentError$37}));init_wrapper();var import_commander=__toESM$1(require_commander(),1);const{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError:InvalidArgumentError$36,InvalidOptionArgumentError,Command:Command$1,Argument,Option,Help}=import_commander.default;async function build$1(path$38,{outdir}={}){outdir||=await resolveOutputDirectory(path$38);let outfile=join$1(outdir,`agent.js`),esbuild=loadEsbuild(),result=await esbuild.build({...sharedBuildOptions,entryPoints:[path$38],outfile});if(result.errors.length>0)throw Error(`Failed to build agent!`);return{outfile}}async function watch$1(entrypoint,{onErrors,onBuildStart,onBuildEnd,outdir}){let esbuild=loadEsbuild();outdir||=await resolveOutputDirectory(entrypoint);let outfile=join$1(outdir,`agent.js`),context$1=await esbuild.context({...sharedBuildOptions,entryPoints:[entrypoint],logLevel:`silent`,outfile,plugins:[{name:`blink-dev-server`,setup(build$11){build$11.onStart(()=>{onBuildStart?.()}),build$11.onEnd(result=>{if(result.errors.length>0){onErrors?.(result.errors);return}onBuildEnd?.({outfile})})}}]});return await context$1.watch(),{dispose:()=>{context$1.dispose()}}}async function resolveEntrypoint(directory){let packageJsonPath=await findNearestEntry(directory,`package.json`);if(!packageJsonPath)throw Error(`No package.json found in ${directory}`);let packageJson$1=JSON.parse(await readFile(packageJsonPath,`utf-8`)),main=packageJson$1.main;if(!main)throw Error(`"main" is not set in ${relative(process.cwd(),packageJsonPath)}. It should be set to the entrypoint of your agent.`);let mainPath=join$1(dirname$1(packageJsonPath),main),stats=await stat(mainPath);if(!stats.isFile())throw Error(`${mainPath} is not a file.`);return mainPath}async function resolveOutputDirectory(path$38){let nodeModulesPath=await findNearestEntry(path$38,`node_modules`);if(!nodeModulesPath){let stats=await stat(path$38);return stats.isDirectory()?join$1(path$38,`.blink`):join$1(dirname$1(path$38),`.blink`)}let blinkPath=join$1(nodeModulesPath,`.blink`);return await mkdir(blinkPath,{recursive:!0}),blinkPath}async function findNearestEntry(startDir,name$5){let currentDir=startDir;for(;currentDir!==dirname$1(currentDir);){let file=join$1(currentDir,name$5);try{return await stat(file),file}catch{}currentDir=dirname$1(currentDir)}}const sharedBuildOptions={bundle:!0,format:`esm`,platform:`node`,target:`node22`,mainFields:[`module`,`main`],conditions:[`import`,`module`]},loadEsbuild=()=>{try{return __require$2(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};async function build(directory){directory||=process.cwd();let entrypoint=await resolveEntrypoint(directory),{outfile}=await build$1(entrypoint);console.log(`Built agent to ${outfile}`)}let isDockerCached;function hasDockerEnv(){try{return fs.statSync(`/.dockerenv`),!0}catch{return!1}}function hasDockerCGroup(){try{return fs.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function isDocker(){return isDockerCached===void 0&&(isDockerCached=hasDockerEnv()||hasDockerCGroup()),isDockerCached}let cachedResult;const hasContainerEnv=()=>{try{return fs.statSync(`/run/.containerenv`),!0}catch{return!1}};function isInsideContainer(){return cachedResult===void 0&&(cachedResult=hasContainerEnv()||isDocker()),cachedResult}const isWsl=()=>{if(y.platform!==`linux`)return!1;if(os.release().toLowerCase().includes(`microsoft`))return!isInsideContainer();try{return fs.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!isInsideContainer():!1}catch{return!1}};var is_wsl_default=y.env.__IS_WSL_TEST__?isWsl:isWsl();const wslDrivesMountPoint=(()=>{let defaultMountPoint=`/mnt/`,mountPoint;return async function(){if(mountPoint)return mountPoint;let configFilePath$1=`/etc/wsl.conf`,isConfigFileExists=!1;try{await fs$1.access(configFilePath$1,constants.F_OK),isConfigFileExists=!0}catch{}if(!isConfigFileExists)return defaultMountPoint;let configContent=await fs$1.readFile(configFilePath$1,{encoding:`utf8`}),configMountPoint=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);return configMountPoint?(mountPoint=configMountPoint.groups.mountPoint.trim(),mountPoint=mountPoint.endsWith(`/`)?mountPoint:`${mountPoint}/`,mountPoint):defaultMountPoint}})(),powerShellPathFromWsl=async()=>{let mountPoint=await wslDrivesMountPoint();return`${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`},powerShellPath=async()=>is_wsl_default?powerShellPathFromWsl():`${y.env.SYSTEMROOT||y.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;function defineLazyProperty(object$1,propertyName,valueGetter){let define$2=value=>Object.defineProperty(object$1,propertyName,{value,enumerable:!0,writable:!0});return Object.defineProperty(object$1,propertyName,{configurable:!0,enumerable:!0,get(){let result=valueGetter();return define$2(result),result},set(value){define$2(value)}}),object$1}const execFileAsync$4=promisify(execFile);async function defaultBrowserId(){if(y.platform!==`darwin`)throw Error(`macOS only`);let{stdout:stdout$1}=await execFileAsync$4(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]),match$1=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout$1);return match$1?.groups.id??`com.apple.Safari`}const execFileAsync$3=promisify(execFile);async function runAppleScript(script,{humanReadableOutput=!0}={}){if(y.platform!==`darwin`)throw Error(`macOS only`);let outputArguments=humanReadableOutput?[]:[`-ss`],{stdout:stdout$1}=await execFileAsync$3(`osascript`,[`-e`,script,outputArguments]);return stdout$1.trim()}async function bundleName(bundleId){return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const execFileAsync$2=promisify(execFile),windowsBrowserProgIds={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},MSEdgeDHTML:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`}};var UnknownBrowserError=class extends Error{};async function defaultBrowser$1(_execFileAsync=execFileAsync$2){let{stdout:stdout$1}=await _execFileAsync(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),match$1=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout$1);if(!match$1)throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout$1)}`);let{id}=match$1.groups,browser=windowsBrowserProgIds[id];if(!browser)throw new UnknownBrowserError(`Unknown browser ID: ${id}`);return browser}const execFileAsync$1=promisify(execFile),titleize=string=>string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,x$5=>x$5.toUpperCase());async function defaultBrowser(){if(y.platform===`darwin`){let id=await defaultBrowserId(),name$5=await bundleName(id);return{name:name$5,id}}if(y.platform===`linux`){let{stdout:stdout$1}=await execFileAsync$1(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),id=stdout$1.trim(),name$5=titleize(id.replace(/.desktop$/,``).replace(`-`,` `));return{name:name$5,id}}if(y.platform===`win32`)return defaultBrowser$1();throw Error(`Only macOS, Linux, and Windows are supported`)}const execFile$1=promisify(childProcess.execFile),__dirname$3=path.dirname(fileURLToPath(import.meta.url)),localXdgOpenPath=path.join(__dirname$3,`xdg-open`),{platform:platform$4,arch}=y;async function getWindowsDefaultBrowserFromWsl(){let powershellPath=await powerShellPath(),rawCommand=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,encodedCommand=Buffer$1.from(rawCommand,`utf16le`).toString(`base64`),{stdout:stdout$1}=await execFile$1(powershellPath,[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`,encodedCommand],{encoding:`utf8`}),progId=stdout$1.trim(),browserMap={ChromeHTML:`com.google.chrome`,BraveHTML:`com.brave.Browser`,MSEdgeHTM:`com.microsoft.edge`,FirefoxURL:`org.mozilla.firefox`};return browserMap[progId]?{id:browserMap[progId]}:{}}const pTryEach=async(array,mapper)=>{let latestError;for(let item of array)try{return await mapper(item)}catch(error$22){latestError=error$22}throw latestError},baseOpen=async options$1=>{if(options$1={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...options$1},Array.isArray(options$1.app))return pTryEach(options$1.app,singleApp=>baseOpen({...options$1,app:singleApp}));let{name:app,arguments:appArguments=[]}=options$1.app??{};if(appArguments=[...appArguments],Array.isArray(app))return pTryEach(app,appName=>baseOpen({...options$1,app:{name:appName,arguments:appArguments}}));if(app===`browser`||app===`browserPrivate`){let ids={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.Browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`},flags={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},browser=is_wsl_default?await getWindowsDefaultBrowserFromWsl():await defaultBrowser();if(browser.id in ids){let browserName=ids[browser.id];return app===`browserPrivate`&&appArguments.push(flags[browserName]),baseOpen({...options$1,app:{name:apps[browserName],arguments:appArguments}})}throw Error(`${browser.name} is not supported as a default browser`)}let command,cliArguments=[],childProcessOptions={};if(platform$4===`darwin`)command=`open`,options$1.wait&&cliArguments.push(`--wait-apps`),options$1.background&&cliArguments.push(`--background`),options$1.newInstance&&cliArguments.push(`--new`),app&&cliArguments.push(`-a`,app);else if(platform$4===`win32`||is_wsl_default&&!isInsideContainer()&&!app){command=await powerShellPath(),cliArguments.push(`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`),is_wsl_default||(childProcessOptions.windowsVerbatimArguments=!0);let encodedArguments=[`Start`];options$1.wait&&encodedArguments.push(`-Wait`),app?(encodedArguments.push(`"\`"${app}\`""`),options$1.target&&appArguments.push(options$1.target)):options$1.target&&encodedArguments.push(`"${options$1.target}"`),appArguments.length>0&&(appArguments=appArguments.map(argument=>`"\`"${argument}\`""`),encodedArguments.push(`-ArgumentList`,appArguments.join(`,`))),options$1.target=Buffer$1.from(encodedArguments.join(` `),`utf16le`).toString(`base64`)}else{if(app)command=app;else{let isBundled=!__dirname$3||__dirname$3===`/`,exeLocalXdgOpen=!1;try{await fs$1.access(localXdgOpenPath,constants.X_OK),exeLocalXdgOpen=!0}catch{}let useSystemXdgOpen=y.versions.electron??(platform$4===`android`||isBundled||!exeLocalXdgOpen);command=useSystemXdgOpen?`xdg-open`:localXdgOpenPath}appArguments.length>0&&cliArguments.push(...appArguments),options$1.wait||(childProcessOptions.stdio=`ignore`,childProcessOptions.detached=!0)}platform$4===`darwin`&&appArguments.length>0&&cliArguments.push(`--args`,...appArguments),options$1.target&&cliArguments.push(options$1.target);let subprocess=childProcess.spawn(command,cliArguments,childProcessOptions);return options$1.wait?new Promise((resolve$10,reject)=>{subprocess.once(`error`,reject),subprocess.once(`close`,exitCode=>{if(!options$1.allowNonzeroExitCode&&exitCode>0){reject(Error(`Exited with code ${exitCode}`));return}resolve$10(subprocess)})}):(subprocess.unref(),subprocess)},open$2=(target,options$1)=>{if(typeof target!=`string`)throw TypeError("Expected a `target`");return baseOpen({...options$1,target})};function detectArchBinary(binary){if(typeof binary==`string`||Array.isArray(binary))return binary;let{[arch]:archBinary}=binary;if(!archBinary)throw Error(`${arch} is not supported`);return archBinary}function detectPlatformBinary({[platform$4]:platformBinary},{wsl}){if(wsl&&is_wsl_default)return detectArchBinary(wsl);if(!platformBinary)throw Error(`${platform$4} is not supported`);return detectArchBinary(platformBinary)}const apps={};defineLazyProperty(apps,`chrome`,()=>detectPlatformBinary({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),defineLazyProperty(apps,`brave`,()=>detectPlatformBinary({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),defineLazyProperty(apps,`firefox`,()=>detectPlatformBinary({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),defineLazyProperty(apps,`edge`,()=>detectPlatformBinary({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),defineLazyProperty(apps,`browser`,()=>`browser`),defineLazyProperty(apps,`browserPrivate`,()=>`browserPrivate`);var open_default=open$2,Emitter$1=class{listeners=[];get event(){return listener=>(this.listeners.push(listener),{dispose:()=>{this.listeners=this.listeners.filter(l$2=>l$2!==listener)}})}emit(event){for(let i$7=this.listeners.length-1;i$7>=0;i$7--)this.listeners[i$7]?.(event)}dispose(){this.listeners=[]}};let MessageType$1=function(MessageType$2){return MessageType$2[MessageType$2.DATA=0]=`DATA`,MessageType$2[MessageType$2.CLOSE=1]=`CLOSE`,MessageType$2[MessageType$2.ERROR=2]=`ERROR`,MessageType$2}({}),Flag$1=function(Flag$2){return Flag$2[Flag$2.NEW=1]=`NEW`,Flag$2}({});var BufferPool$1=class{static MAX_POOL_SIZE=100;static COMMON_SIZES=[64,256,1024,4096,16384];static pools=new Map;static{for(let size of this.COMMON_SIZES)this.pools.set(size,[])}static acquire(size){for(let poolSize of this.COMMON_SIZES)if(poolSize>=size){let pool$1=this.pools.get(poolSize);if(pool$1&&pool$1.length>0)return pool$1.pop();break}return new Uint8Array(size)}static release(buffer$2){let size=buffer$2.length;for(let poolSize of this.COMMON_SIZES)if(poolSize===size){let pool$1=this.pools.get(poolSize);pool$1&&pool$1.length<this.MAX_POOL_SIZE&&pool$1.push(buffer$2);break}}},FrameCodec$1=class FrameCodec$1{static HEADER_SIZE=4;static MAX_FRAME_SIZE=1024*1024-FrameCodec$1.HEADER_SIZE;static encode(frame){let payloadLength=frame.payload.length;if(payloadLength>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${payloadLength} > ${this.MAX_FRAME_SIZE}`);let totalSize=this.HEADER_SIZE+payloadLength,result=BufferPool$1.acquire(totalSize),word=frame.streamId<<8|frame.type<<4|frame.flags&15;return result[0]=word>>>24&255,result[1]=word>>>16&255,result[2]=word>>>8&255,result[3]=word&255,payloadLength>0&&result.set(frame.payload,this.HEADER_SIZE),result.length===totalSize?result:result.subarray(0,totalSize)}static encodeTyped(streamId,msgType,flags,typeByte,payload){let payloadLength=1+payload.length;if(payloadLength>this.MAX_FRAME_SIZE)throw Error(`Frame payload too large: ${payloadLength} > ${this.MAX_FRAME_SIZE}`);let totalSize=this.HEADER_SIZE+payloadLength,result=BufferPool$1.acquire(totalSize),word=streamId<<8|msgType<<4|flags&15;return result[0]=word>>>24&255,result[1]=word>>>16&255,result[2]=word>>>8&255,result[3]=word&255,result[FrameCodec$1.HEADER_SIZE]=typeByte&255,payload.length>0&&result.set(payload,FrameCodec$1.HEADER_SIZE+1),result.length===totalSize?result:result.subarray(0,totalSize)}static decode(data$2){if(data$2.length<FrameCodec$1.HEADER_SIZE)throw Error(`Invalid frame: too short (${data$2.length} < ${FrameCodec$1.HEADER_SIZE})`);let word=data$2[0]<<24|data$2[1]<<16|data$2[2]<<8|data$2[3],streamId=word>>>8,typeAndFlags=word&255,type=typeAndFlags>>>4,flags=typeAndFlags&15,payload=data$2.length>FrameCodec$1.HEADER_SIZE?data$2.subarray(FrameCodec$1.HEADER_SIZE):new Uint8Array;return{streamId,type,flags,payload}}static releaseBuffer(buffer$2){BufferPool$1.release(buffer$2)}static getMaxPayloadSize(){return FrameCodec$1.MAX_FRAME_SIZE}},Stream$8=class{_onData;_onClose;_onError;_disposed=!1;_id;constructor(id,send,sendTypedCb){this.send=send,this.sendTypedCb=sendTypedCb,this._id=id}get id(){return this._id}get onData(){return this._onData||=new Emitter$1,this._onData.event}get onClose(){return this._onClose||=new Emitter$1,this._onClose.event}get onError(){return this._onError||=new Emitter$1,this._onError.event}write(data$2,isFirst=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);let maxPayload=FrameCodec$1.getMaxPayloadSize();if(data$2.length<=maxPayload){this.send({streamId:this.id,type:MessageType$1.DATA,flags:isFirst?Flag$1.NEW:0,payload:data$2});return}let offset=0,firstChunk=!0;for(;offset<data$2.length;){let remaining=data$2.length-offset,chunkSize=remaining>maxPayload?maxPayload:remaining,chunk$1=data$2.subarray(offset,offset+chunkSize);this.send({streamId:this.id,type:MessageType$1.DATA,flags:isFirst&&firstChunk?Flag$1.NEW:0,payload:chunk$1}),offset+=chunkSize,firstChunk=!1}}writeTyped(typeByte,data$2,isFirst=!1){if(this._disposed)throw Error(`Cannot write to disposed stream ${this.id}`);if(!this.sendTypedCb){let merged=new Uint8Array(1+data$2.length);merged[0]=typeByte&255,data$2.length&&merged.set(data$2,1),this.write(merged,isFirst);return}let maxPayload=FrameCodec$1.getMaxPayloadSize()-1;if(data$2.length<=maxPayload){this.sendTypedCb(this.id,isFirst?Flag$1.NEW:0,typeByte,data$2);return}let offset=0,firstChunk=!0;for(;offset<data$2.length;){let remaining=data$2.length-offset,chunkSize=remaining>maxPayload?maxPayload:remaining,chunk$1=data$2.subarray(offset,offset+chunkSize);this.sendTypedCb(this.id,isFirst&&firstChunk?Flag$1.NEW:0,typeByte,chunk$1),offset+=chunkSize,firstChunk=!1}}close(){this._disposed||(this.send({streamId:this.id,type:MessageType$1.CLOSE,flags:0,payload:new Uint8Array}),this._dispose())}error(message){this._disposed||this.send({streamId:this.id,type:MessageType$1.ERROR,flags:0,payload:new TextEncoder().encode(message)})}_handleFrame(frame){if(!this._disposed)switch(frame.type){case MessageType$1.DATA:this._onData?.emit(frame.payload);break;case MessageType$1.CLOSE:this._onClose?.emit(),this._dispose();break;case MessageType$1.ERROR:let error$22=new TextDecoder().decode(frame.payload);this._onError?.emit(error$22),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(newId,newSend,newSendTyped){this._dispose(),this._id=newId,this.send=newSend,this.sendTypedCb=newSendTyped,this._disposed=!1}get createdByClient(){return this.id%2==1}get disposed(){return this._disposed}},StreamPool$1=class{static MAX_POOL_SIZE=200;static pool=[];static acquire(id,send,sendTyped){let stream$10=this.pool.pop();return stream$10?(stream$10._reset(id,send,sendTyped),stream$10):new Stream$8(id,send,sendTyped)}static release(stream$10){this.pool.length<this.MAX_POOL_SIZE&&this.pool.push(stream$10)}},Multiplexer$1=class{_onNextStreamIDChange=new Emitter$1;onNextStreamIDChange=this._onNextStreamIDChange.event;_onStream=new Emitter$1;onStream=this._onStream.event;streams=[];streamCount=0;nextStreamId=1;send;releaseAfterSend;constructor(opts){this.nextStreamId=opts.initialNextStreamID??(opts.isClient?1:2),this.send=opts.send,this.releaseAfterSend=!!opts.releaseAfterSend}getStream(id){return this.streams[id]}createStream(id){id===void 0&&(id=this.nextStreamId,this.nextStreamId+=2,this._onNextStreamIDChange.emit(this.nextStreamId));let existingStream=this.streams[id];if(existingStream&&!existingStream.disposed)throw Error(`Stream ${id} already exists`);let stream$10=StreamPool$1.acquire(id,frame=>this.sendFrame(frame),(sid,flags,typeByte,payload)=>this.sendFrameTyped(sid,typeByte,flags,payload));return this.streams[id]=stream$10,this.streamCount++,stream$10}sendFrame(frame){let encoded=FrameCodec$1.encode(frame);try{this.send(encoded)}finally{this.releaseAfterSend&&FrameCodec$1.releaseBuffer(encoded)}}sendFrameTyped(streamId,appTypeByte,flags,payload){let encoded=FrameCodec$1.encodeTyped(streamId,MessageType$1.DATA,flags,appTypeByte,payload);try{this.send(encoded)}finally{this.releaseAfterSend&&FrameCodec$1.releaseBuffer(encoded)}}handleMessage(data$2){this.handleFrame(FrameCodec$1.decode(data$2))}handleFrame(frame){let stream$10=this.streams[frame.streamId];(!stream$10||stream$10.disposed)&&(stream$10=StreamPool$1.acquire(frame.streamId,frame$1=>this.sendFrame(frame$1),(sid,flags,typeByte,payload)=>this.sendFrameTyped(sid,typeByte,flags,payload)),this.streams[frame.streamId]=stream$10,this.streamCount++,this._onStream.emit(stream$10)),stream$10._handleFrame(frame),(frame.type===MessageType$1.CLOSE||frame.type===MessageType$1.ERROR)&&(this.streams[frame.streamId]=void 0,this.streamCount--,StreamPool$1.release(stream$10))}get activeStreamCount(){return this.streamCount}dispose(){for(let stream$10 of this.streams)stream$10&&!stream$10.disposed&&(stream$10.close(),StreamPool$1.release(stream$10));this.streams.length=0,this.streamCount=0,this._onNextStreamIDChange.dispose(),this._onStream.dispose()}};const defaultMessages$1=`End-Of-Stream`;var EndOfStreamError$1=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},AbortError$8=class extends Error{constructor(message=`The operation was aborted`){super(message),this.name=`AbortError`}},AbstractStreamReader$1=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(uint8Array,mayBeLess=!1){let bytesRead=await this.read(uint8Array,mayBeLess);return this.peekQueue.push(uint8Array.subarray(0,bytesRead)),bytesRead}async read(buffer$2,mayBeLess=!1){if(buffer$2.length===0)return 0;let bytesRead=this.readFromPeekBuffer(buffer$2);if(this.endOfStream||(bytesRead+=await this.readRemainderFromStream(buffer$2.subarray(bytesRead),mayBeLess)),bytesRead===0&&!mayBeLess)throw new EndOfStreamError$1;return bytesRead}readFromPeekBuffer(buffer$2){let remaining=buffer$2.length,bytesRead=0;for(;this.peekQueue.length>0&&remaining>0;){let peekData=this.peekQueue.pop();if(!peekData)throw Error(`peekData should be defined`);let lenCopy=Math.min(peekData.length,remaining);buffer$2.set(peekData.subarray(0,lenCopy),bytesRead),bytesRead+=lenCopy,remaining-=lenCopy,lenCopy<peekData.length&&this.peekQueue.push(peekData.subarray(lenCopy))}return bytesRead}async readRemainderFromStream(buffer$2,mayBeLess){let bytesRead=0;for(;bytesRead<buffer$2.length&&!this.endOfStream;){if(this.interrupted)throw new AbortError$8;let chunkLen=await this.readFromStream(buffer$2.subarray(bytesRead),mayBeLess);if(chunkLen===0)break;bytesRead+=chunkLen}if(!mayBeLess&&bytesRead<buffer$2.length)throw new EndOfStreamError$1;return bytesRead}},WebStreamReader$1=class extends AbstractStreamReader$1{constructor(reader){super(),this.reader=reader}async abort(){return this.close()}async close(){this.reader.releaseLock()}},WebStreamByobReader$1=class extends WebStreamReader$1{async readFromStream(buffer$2,mayBeLess){if(buffer$2.length===0)return 0;let result=await this.reader.read(new Uint8Array(buffer$2.length),{min:mayBeLess?void 0:buffer$2.length});return result.done&&(this.endOfStream=result.done),result.value?(buffer$2.set(result.value),result.value.length):0}},WebStreamDefaultReader$1=class extends AbstractStreamReader$1{constructor(reader){super(),this.reader=reader,this.buffer=null}writeChunk(target,chunk$1){let written=Math.min(chunk$1.length,target.length);return target.set(chunk$1.subarray(0,written)),written<chunk$1.length?this.buffer=chunk$1.subarray(written):this.buffer=null,written}async readFromStream(buffer$2,mayBeLess){if(buffer$2.length===0)return 0;let totalBytesRead=0;for(this.buffer&&(totalBytesRead+=this.writeChunk(buffer$2,this.buffer));totalBytesRead<buffer$2.length&&!this.endOfStream;){let result=await this.reader.read();if(result.done){this.endOfStream=!0;break}result.value&&(totalBytesRead+=this.writeChunk(buffer$2.subarray(totalBytesRead),result.value))}if(!mayBeLess&&totalBytesRead===0&&this.endOfStream)throw new EndOfStreamError$1;return totalBytesRead}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function makeWebStreamReader$1(stream$10){try{let reader=stream$10.getReader({mode:`byob`});return reader instanceof ReadableStreamDefaultReader?new WebStreamDefaultReader$1(reader):new WebStreamByobReader$1(reader)}catch(error$22){if(error$22 instanceof TypeError)return new WebStreamDefaultReader$1(stream$10.getReader());throw error$22}}var AbstractTokenizer$1=class{constructor(options$1){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=options$1?.onClose,options$1?.abortSignal&&options$1.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(token$1,position=this.position){let uint8Array=new Uint8Array(token$1.len),len$1=await this.readBuffer(uint8Array,{position});if(len$1<token$1.len)throw new EndOfStreamError$1;return token$1.get(uint8Array,0)}async peekToken(token$1,position=this.position){let uint8Array=new Uint8Array(token$1.len),len$1=await this.peekBuffer(uint8Array,{position});if(len$1<token$1.len)throw new EndOfStreamError$1;return token$1.get(uint8Array,0)}async readNumber(token$1){let len$1=await this.readBuffer(this.numBuffer,{length:token$1.len});if(len$1<token$1.len)throw new EndOfStreamError$1;return token$1.get(this.numBuffer,0)}async peekNumber(token$1){let len$1=await this.peekBuffer(this.numBuffer,{length:token$1.len});if(len$1<token$1.len)throw new EndOfStreamError$1;return token$1.get(this.numBuffer,0)}async ignore(length){if(this.fileInfo.size!==void 0){let bytesLeft=this.fileInfo.size-this.position;if(length>bytesLeft)return this.position+=bytesLeft,bytesLeft}return this.position+=length,length}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(uint8Array,options$1){if(!this.supportsRandomAccess()&&options$1&&options$1.position!==void 0&&options$1.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:uint8Array.length,position:this.position,...options$1}}abort(){return Promise.resolve()}};const maxBufferSize$1=256e3;var ReadStreamTokenizer$1=class extends AbstractTokenizer$1{constructor(streamReader,options$1){super(options$1),this.streamReader=streamReader,this.fileInfo=options$1?.fileInfo??{}}async readBuffer(uint8Array,options$1){let normOptions=this.normalizeOptions(uint8Array,options$1),skipBytes=normOptions.position-this.position;if(skipBytes>0)return await this.ignore(skipBytes),this.readBuffer(uint8Array,options$1);if(skipBytes<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(normOptions.length===0)return 0;let bytesRead=await this.streamReader.read(uint8Array.subarray(0,normOptions.length),normOptions.mayBeLess);if(this.position+=bytesRead,(!options$1||!options$1.mayBeLess)&&bytesRead<normOptions.length)throw new EndOfStreamError$1;return bytesRead}async peekBuffer(uint8Array,options$1){let normOptions=this.normalizeOptions(uint8Array,options$1),bytesRead=0;if(normOptions.position){let skipBytes=normOptions.position-this.position;if(skipBytes>0){let skipBuffer=new Uint8Array(normOptions.length+skipBytes);return bytesRead=await this.peekBuffer(skipBuffer,{mayBeLess:normOptions.mayBeLess}),uint8Array.set(skipBuffer.subarray(skipBytes)),bytesRead-skipBytes}if(skipBytes<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(normOptions.length>0){try{bytesRead=await this.streamReader.peek(uint8Array.subarray(0,normOptions.length),normOptions.mayBeLess)}catch(err$2){if(options$1?.mayBeLess&&err$2 instanceof EndOfStreamError$1)return 0;throw err$2}if(!normOptions.mayBeLess&&bytesRead<normOptions.length)throw new EndOfStreamError$1}return bytesRead}async ignore(length){let bufSize=Math.min(256e3,length),buf=new Uint8Array(bufSize),totBytesRead=0;for(;totBytesRead<length;){let remaining=length-totBytesRead,bytesRead=await this.readBuffer(buf,{length:Math.min(bufSize,remaining)});if(bytesRead<0)return bytesRead;totBytesRead+=bytesRead}return totBytesRead}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},BufferTokenizer$1=class extends AbstractTokenizer$1{constructor(uint8Array,options$1){super(options$1),this.uint8Array=uint8Array,this.fileInfo={...options$1?.fileInfo??{},size:uint8Array.length}}async readBuffer(uint8Array,options$1){options$1?.position&&(this.position=options$1.position);let bytesRead=await this.peekBuffer(uint8Array,options$1);return this.position+=bytesRead,bytesRead}async peekBuffer(uint8Array,options$1){let normOptions=this.normalizeOptions(uint8Array,options$1),bytes2read=Math.min(this.uint8Array.length-normOptions.position,normOptions.length);if(!normOptions.mayBeLess&&bytes2read<normOptions.length)throw new EndOfStreamError$1;return uint8Array.set(this.uint8Array.subarray(normOptions.position,normOptions.position+bytes2read)),bytes2read}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(position){this.position=position}};function fromWebStream$1(webStream,options$1){let webStreamReader=makeWebStreamReader$1(webStream),_options$1=options$1??{},chainedClose=_options$1.onClose;return _options$1.onClose=async()=>{if(await webStreamReader.close(),chainedClose)return chainedClose()},new ReadStreamTokenizer$1(webStreamReader,_options$1)}function fromBuffer$2(uint8Array,options$1){return new BufferTokenizer$1(uint8Array,options$1)}const WINDOWS_1252_EXTRA$1={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:`Ÿ`},WINDOWS_1252_REVERSE$1={};for(let[code$1,char]of Object.entries(WINDOWS_1252_EXTRA$1))WINDOWS_1252_REVERSE$1[char]=Number.parseInt(code$1);function textDecode$1(bytes,encoding=`utf-8`){switch(encoding.toLowerCase()){case`utf-8`:case`utf8`:return globalThis.TextDecoder===void 0?decodeUTF8$1(bytes):new globalThis.TextDecoder(`utf-8`).decode(bytes);case`utf-16le`:return decodeUTF16LE$1(bytes);case`ascii`:return decodeASCII$1(bytes);case`latin1`:case`iso-8859-1`:return decodeLatin1$1(bytes);case`windows-1252`:return decodeWindows1252$1(bytes);default:throw RangeError(`Encoding '${encoding}' not supported`)}}function decodeUTF8$1(bytes){let out=``,i$7=0;for(;i$7<bytes.length;){let b1=bytes[i$7++];if(b1<128)out+=String.fromCharCode(b1);else if(b1<224){let b2=bytes[i$7++]&63;out+=String.fromCharCode((b1&31)<<6|b2)}else if(b1<240){let b2=bytes[i$7++]&63,b3=bytes[i$7++]&63;out+=String.fromCharCode((b1&15)<<12|b2<<6|b3)}else{let b2=bytes[i$7++]&63,b3=bytes[i$7++]&63,b4=bytes[i$7++]&63,cp$1=(b1&7)<<18|b2<<12|b3<<6|b4;cp$1-=65536,out+=String.fromCharCode(55296+(cp$1>>10&1023),56320+(cp$1&1023))}}return out}function decodeUTF16LE$1(bytes){let out=``;for(let i$7=0;i$7<bytes.length;i$7+=2)out+=String.fromCharCode(bytes[i$7]|bytes[i$7+1]<<8);return out}function decodeASCII$1(bytes){return String.fromCharCode(...bytes.map(b$4=>b$4&127))}function decodeLatin1$1(bytes){return String.fromCharCode(...bytes)}function decodeWindows1252$1(bytes){let out=``;for(let b$4 of bytes)b$4>=128&&b$4<=159&&WINDOWS_1252_EXTRA$1[b$4]?out+=WINDOWS_1252_EXTRA$1[b$4]:out+=String.fromCharCode(b$4);return out}function dv$1(array){return new DataView(array.buffer,array.byteOffset)}const UINT8$1={len:1,get(array,offset){return dv$1(array).getUint8(offset)},put(array,offset,value){return dv$1(array).setUint8(offset,value),offset+1}},UINT16_LE$1={len:2,get(array,offset){return dv$1(array).getUint16(offset,!0)},put(array,offset,value){return dv$1(array).setUint16(offset,value,!0),offset+2}},UINT16_BE$1={len:2,get(array,offset){return dv$1(array).getUint16(offset)},put(array,offset,value){return dv$1(array).setUint16(offset,value),offset+2}},UINT32_LE$1={len:4,get(array,offset){return dv$1(array).getUint32(offset,!0)},put(array,offset,value){return dv$1(array).setUint32(offset,value,!0),offset+4}},UINT32_BE$1={len:4,get(array,offset){return dv$1(array).getUint32(offset)},put(array,offset,value){return dv$1(array).setUint32(offset,value),offset+4}},INT32_BE$1={len:4,get(array,offset){return dv$1(array).getInt32(offset)},put(array,offset,value){return dv$1(array).setInt32(offset,value),offset+4}},UINT64_LE$1={len:8,get(array,offset){return dv$1(array).getBigUint64(offset,!0)},put(array,offset,value){return dv$1(array).setBigUint64(offset,value,!0),offset+8}};var StringType$1=class{constructor(len$1,encoding){this.len=len$1,this.encoding=encoding}get(data$2,offset=0){let bytes=data$2.subarray(offset,offset+this.len);return textDecode$1(bytes,this.encoding)}},require$2=createRequire$1(`/`),Worker$1;try{Worker$1=require$2(`worker_threads`).Worker}catch{}var u8$1=Uint8Array,u16$1=Uint16Array,i32$1=Int32Array,fleb$1=new u8$1([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]),fdeb$1=new u8$1([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]),clim$1=new u8$1([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),freb$1=function(eb,start$1){for(var b$4=new u16$1(31),i$7=0;i$7<31;++i$7)b$4[i$7]=start$1+=1<<eb[i$7-1];for(var r$3=new i32$1(b$4[30]),i$7=1;i$7<30;++i$7)for(var j$2=b$4[i$7];j$2<b$4[i$7+1];++j$2)r$3[j$2]=j$2-b$4[i$7]<<5|i$7;return{b:b$4,r:r$3}},_a$14=freb$1(fleb$1,2),fl$1=_a$14.b,revfl$1=_a$14.r;fl$1[28]=258,revfl$1[258]=28;for(var _b$4=freb$1(fdeb$1,0),fd$1=_b$4.b,revfd=_b$4.r,rev$1=new u16$1(32768),i$6=0;i$6<32768;++i$6){var x$4=(i$6&43690)>>1|(i$6&21845)<<1;x$4=(x$4&52428)>>2|(x$4&13107)<<2,x$4=(x$4&61680)>>4|(x$4&3855)<<4,rev$1[i$6]=((x$4&65280)>>8|(x$4&255)<<8)>>1}for(var hMap$1=(function(cd,mb,r$3){for(var s$3=cd.length,i$7=0,l$2=new u16$1(mb);i$7<s$3;++i$7)cd[i$7]&&++l$2[cd[i$7]-1];var le$3=new u16$1(mb);for(i$7=1;i$7<mb;++i$7)le$3[i$7]=le$3[i$7-1]+l$2[i$7-1]<<1;var co;if(r$3){co=new u16$1(1<<mb);var rvb=15-mb;for(i$7=0;i$7<s$3;++i$7)if(cd[i$7])for(var sv=i$7<<4|cd[i$7],r_1=mb-cd[i$7],v$2=le$3[cd[i$7]-1]++<<r_1,m$3=v$2|(1<<r_1)-1;v$2<=m$3;++v$2)co[rev$1[v$2]>>rvb]=sv}else for(co=new u16$1(s$3),i$7=0;i$7<s$3;++i$7)cd[i$7]&&(co[i$7]=rev$1[le$3[cd[i$7]-1]++]>>15-cd[i$7]);return co}),flt$1=new u8$1(288),i$6=0;i$6<144;++i$6)flt$1[i$6]=8;for(var i$6=144;i$6<256;++i$6)flt$1[i$6]=9;for(var i$6=256;i$6<280;++i$6)flt$1[i$6]=7;for(var i$6=280;i$6<288;++i$6)flt$1[i$6]=8;for(var fdt$1=new u8$1(32),i$6=0;i$6<32;++i$6)fdt$1[i$6]=5;var flm=hMap$1(flt$1,9,0),flrm$1=hMap$1(flt$1,9,1),fdm=hMap$1(fdt$1,5,0),fdrm$1=hMap$1(fdt$1,5,1),max$2=function(a$4){for(var m$3=a$4[0],i$7=1;i$7<a$4.length;++i$7)a$4[i$7]>m$3&&(m$3=a$4[i$7]);return m$3},bits$1=function(d$5,p$2,m$3){var o$3=p$2/8|0;return(d$5[o$3]|d$5[o$3+1]<<8)>>(p$2&7)&m$3},bits16$1=function(d$5,p$2){var o$3=p$2/8|0;return(d$5[o$3]|d$5[o$3+1]<<8|d$5[o$3+2]<<16)>>(p$2&7)},shft$1=function(p$2){return(p$2+7)/8|0},slc$1=function(v$2,s$3,e$3){return(s$3==null||s$3<0)&&(s$3=0),(e$3==null||e$3>v$2.length)&&(e$3=v$2.length),new u8$1(v$2.subarray(s$3,e$3))},ec$1=[`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`],err$1=function(ind,msg,nt){var e$3=Error(msg||ec$1[ind]);if(e$3.code=ind,Error.captureStackTrace&&Error.captureStackTrace(e$3,err$1),!nt)throw e$3;return e$3},inflt$1=function(dat,st,buf,dict){var sl=dat.length,dl=dict?dict.length:0;if(!sl||st.f&&!st.l)return buf||new u8$1(0);var noBuf=!buf,resize=noBuf||st.i!=2,noSt=st.i;noBuf&&(buf=new u8$1(sl*3));var cbuf=function(l$3){var bl=buf.length;if(l$3>bl){var nbuf=new u8$1(Math.max(bl*2,l$3));nbuf.set(buf),buf=nbuf}},final=st.f||0,pos=st.p||0,bt=st.b||0,lm=st.l,dm=st.d,lbt=st.m,dbt=st.n,tbts=sl*8;do{if(!lm){final=bits$1(dat,pos,1);var type=bits$1(dat,pos+1,3);if(pos+=3,type)if(type==1)lm=flrm$1,dm=fdrm$1,lbt=9,dbt=5;else if(type==2){var hLit=bits$1(dat,pos,31)+257,hcLen=bits$1(dat,pos+10,15)+4,tl=hLit+bits$1(dat,pos+5,31)+1;pos+=14;for(var ldt=new u8$1(tl),clt=new u8$1(19),i$7=0;i$7<hcLen;++i$7)clt[clim$1[i$7]]=bits$1(dat,pos+i$7*3,7);pos+=hcLen*3;for(var clb=max$2(clt),clbmsk=(1<<clb)-1,clm=hMap$1(clt,clb,1),i$7=0;i$7<tl;){var r$3=clm[bits$1(dat,pos,clbmsk)];pos+=r$3&15;var s$3=r$3>>4;if(s$3<16)ldt[i$7++]=s$3;else{var c$3=0,n$2=0;for(s$3==16?(n$2=3+bits$1(dat,pos,3),pos+=2,c$3=ldt[i$7-1]):s$3==17?(n$2=3+bits$1(dat,pos,7),pos+=3):s$3==18&&(n$2=11+bits$1(dat,pos,127),pos+=7);n$2--;)ldt[i$7++]=c$3}}var lt=ldt.subarray(0,hLit),dt=ldt.subarray(hLit);lbt=max$2(lt),dbt=max$2(dt),lm=hMap$1(lt,lbt,1),dm=hMap$1(dt,dbt,1)}else err$1(1);else{var s$3=shft$1(pos)+4,l$2=dat[s$3-4]|dat[s$3-3]<<8,t$1=s$3+l$2;if(t$1>sl){noSt&&err$1(0);break}resize&&cbuf(bt+l$2),buf.set(dat.subarray(s$3,t$1),bt),st.b=bt+=l$2,st.p=pos=t$1*8,st.f=final;continue}if(pos>tbts){noSt&&err$1(0);break}}resize&&cbuf(bt+131072);for(var lms=(1<<lbt)-1,dms=(1<<dbt)-1,lpos=pos;;lpos=pos){var c$3=lm[bits16$1(dat,pos)&lms],sym=c$3>>4;if(pos+=c$3&15,pos>tbts){noSt&&err$1(0);break}if(c$3||err$1(2),sym<256)buf[bt++]=sym;else if(sym==256){lpos=pos,lm=null;break}else{var add=sym-254;if(sym>264){var i$7=sym-257,b$4=fleb$1[i$7];add=bits$1(dat,pos,(1<<b$4)-1)+fl$1[i$7],pos+=b$4}var d$5=dm[bits16$1(dat,pos)&dms],dsym=d$5>>4;d$5||err$1(3),pos+=d$5&15;var dt=fd$1[dsym];if(dsym>3){var b$4=fdeb$1[dsym];dt+=bits16$1(dat,pos)&(1<<b$4)-1,pos+=b$4}if(pos>tbts){noSt&&err$1(0);break}resize&&cbuf(bt+131072);var end=bt+add;if(bt<dt){var shift=dl-dt,dend=Math.min(dt,end);for(shift+bt<0&&err$1(3);bt<dend;++bt)buf[bt]=dict[shift+bt]}for(;bt<end;++bt)buf[bt]=buf[bt-dt]}}st.l=lm,st.p=lpos,st.b=bt,st.f=final,lm&&(final=1,st.m=lbt,st.d=dm,st.n=dbt)}while(!final);return bt!=buf.length&&noBuf?slc$1(buf,0,bt):buf.subarray(0,bt)},et$1=new u8$1(0),gzs$1=function(d$5){(d$5[0]!=31||d$5[1]!=139||d$5[2]!=8)&&err$1(6,`invalid gzip data`);var flg=d$5[3],st=10;flg&4&&(st+=(d$5[10]|d$5[11]<<8)+2);for(var zs=(flg>>3&1)+(flg>>4&1);zs>0;zs-=!d$5[st++]);return st+(flg&2)},gzl$1=function(d$5){var l$2=d$5.length;return(d$5[l$2-4]|d$5[l$2-3]<<8|d$5[l$2-2]<<16|d$5[l$2-1]<<24)>>>0},zls$1=function(d$5,dict){return((d$5[0]&15)!=8||d$5[0]>>4>7||(d$5[0]<<8|d$5[1])%31)&&err$1(6,`invalid zlib data`),(d$5[1]>>5&1)==+!dict&&err$1(6,`invalid zlib data: `+(d$5[1]&32?`need`:`unexpected`)+` dictionary`),(d$5[1]>>3&4)+2};function inflateSync$1(data$2,opts){return inflt$1(data$2,{i:2},opts&&opts.out,opts&&opts.dictionary)}function gunzipSync$1(data$2,opts){var st=gzs$1(data$2);return st+8>data$2.length&&err$1(6,`invalid gzip data`),inflt$1(data$2.subarray(st,-8),{i:2},opts&&opts.out||new u8$1(gzl$1(data$2)),opts&&opts.dictionary)}function unzlibSync$1(data$2,opts){return inflt$1(data$2.subarray(zls$1(data$2,opts&&opts.dictionary),-4),{i:2},opts&&opts.out,opts&&opts.dictionary)}function decompressSync$1(data$2,opts){return data$2[0]==31&&data$2[1]==139&&data$2[2]==8?gunzipSync$1(data$2,opts):(data$2[0]&15)!=8||data$2[0]>>4>7||(data$2[0]<<8|data$2[1])%31?inflateSync$1(data$2,opts):unzlibSync$1(data$2,opts)}var td$1=typeof TextDecoder<`u`&&new TextDecoder,tds$1=0;try{td$1.decode(et$1,{stream:!0}),tds$1=1}catch{}var require_ms$1=__commonJSMin(((exports,module)=>{var s$2=1e3,m$2=s$2*60,h$3=m$2*60,d$4=h$3*24,w$3=d$4*7,y$3=d$4*365.25;module.exports=function(val,options$1){options$1||={};var type=typeof val;if(type===`string`&&val.length>0)return parse$18(val);if(type===`number`&&isFinite(val))return options$1.long?fmtLong(val):fmtShort(val);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(val))};function parse$18(str$1){if(str$1=String(str$1),!(str$1.length>100)){var match$1=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str$1);if(match$1){var n$2=parseFloat(match$1[1]),type=(match$1[2]||`ms`).toLowerCase();switch(type){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return n$2*y$3;case`weeks`:case`week`:case`w`:return n$2*w$3;case`days`:case`day`:case`d`:return n$2*d$4;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return n$2*h$3;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return n$2*m$2;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return n$2*s$2;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return n$2;default:return}}}}function fmtShort(ms){var msAbs=Math.abs(ms);return msAbs>=d$4?Math.round(ms/d$4)+`d`:msAbs>=h$3?Math.round(ms/h$3)+`h`:msAbs>=m$2?Math.round(ms/m$2)+`m`:msAbs>=s$2?Math.round(ms/s$2)+`s`:ms+`ms`}function fmtLong(ms){var msAbs=Math.abs(ms);return msAbs>=d$4?plural(ms,msAbs,d$4,`day`):msAbs>=h$3?plural(ms,msAbs,h$3,`hour`):msAbs>=m$2?plural(ms,msAbs,m$2,`minute`):msAbs>=s$2?plural(ms,msAbs,s$2,`second`):ms+` ms`}function plural(ms,msAbs,n$2,name$5){var isPlural=msAbs>=n$2*1.5;return Math.round(ms/n$2)+` `+name$5+(isPlural?`s`:``)}})),require_common$4=__commonJSMin(((exports,module)=>{function setup$7(env$8){createDebug.debug=createDebug,createDebug.default=createDebug,createDebug.coerce=coerce,createDebug.disable=disable,createDebug.enable=enable,createDebug.enabled=enabled,createDebug.humanize=require_ms$1(),createDebug.destroy=destroy$2,Object.keys(env$8).forEach(key=>{createDebug[key]=env$8[key]}),createDebug.names=[],createDebug.skips=[],createDebug.formatters={};function selectColor(namespace){let hash$1=0;for(let i$7=0;i$7<namespace.length;i$7++)hash$1=(hash$1<<5)-hash$1+namespace.charCodeAt(i$7),hash$1|=0;return createDebug.colors[Math.abs(hash$1)%createDebug.colors.length]}createDebug.selectColor=selectColor;function createDebug(namespace){let prevTime,enableOverride=null,namespacesCache,enabledCache;function debug$12(...args){if(!debug$12.enabled)return;let self$1=debug$12,curr=Number(new Date),ms=curr-(prevTime||curr);self$1.diff=ms,self$1.prev=prevTime,self$1.curr=curr,prevTime=curr,args[0]=createDebug.coerce(args[0]),typeof args[0]!=`string`&&args.unshift(`%O`);let index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,(match$1,format$4)=>{if(match$1===`%%`)return`%`;index++;let formatter$1=createDebug.formatters[format$4];if(typeof formatter$1==`function`){let val=args[index];match$1=formatter$1.call(self$1,val),args.splice(index,1),index--}return match$1}),createDebug.formatArgs.call(self$1,args);let logFn=self$1.log||createDebug.log;logFn.apply(self$1,args)}return debug$12.namespace=namespace,debug$12.useColors=createDebug.useColors(),debug$12.color=createDebug.selectColor(namespace),debug$12.extend=extend,debug$12.destroy=createDebug.destroy,Object.defineProperty(debug$12,`enabled`,{enumerable:!0,configurable:!1,get:()=>enableOverride===null?(namespacesCache!==createDebug.namespaces&&(namespacesCache=createDebug.namespaces,enabledCache=createDebug.enabled(namespace)),enabledCache):enableOverride,set:v$2=>{enableOverride=v$2}}),typeof createDebug.init==`function`&&createDebug.init(debug$12),debug$12}function extend(namespace,delimiter){let newDebug=createDebug(this.namespace+(delimiter===void 0?`:`:delimiter)+namespace);return newDebug.log=this.log,newDebug}function enable(namespaces){createDebug.save(namespaces),createDebug.namespaces=namespaces,createDebug.names=[],createDebug.skips=[];let split=(typeof namespaces==`string`?namespaces:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let ns of split)ns[0]===`-`?createDebug.skips.push(ns.slice(1)):createDebug.names.push(ns)}function matchesTemplate(search,template$1){let searchIndex=0,templateIndex=0,starIndex=-1,matchIndex=0;for(;searchIndex<search.length;)if(templateIndex<template$1.length&&(template$1[templateIndex]===search[searchIndex]||template$1[templateIndex]===`*`))template$1[templateIndex]===`*`?(starIndex=templateIndex,matchIndex=searchIndex,templateIndex++):(searchIndex++,templateIndex++);else if(starIndex!==-1)templateIndex=starIndex+1,matchIndex++,searchIndex=matchIndex;else return!1;for(;templateIndex<template$1.length&&template$1[templateIndex]===`*`;)templateIndex++;return templateIndex===template$1.length}function disable(){let namespaces=[...createDebug.names,...createDebug.skips.map(namespace=>`-`+namespace)].join(`,`);return createDebug.enable(``),namespaces}function enabled(name$5){for(let skip of createDebug.skips)if(matchesTemplate(name$5,skip))return!1;for(let ns of createDebug.names)if(matchesTemplate(name$5,ns))return!0;return!1}function coerce(val){return val instanceof Error?val.stack||val.message:val}function destroy$2(){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 createDebug.enable(createDebug.load()),createDebug}module.exports=setup$7})),require_browser$1=__commonJSMin(((exports,module)=>{exports.formatArgs=formatArgs$1,exports.save=save$1,exports.load=load$6,exports.useColors=useColors$1,exports.storage=localstorage(),exports.destroy=(()=>{let warned$1=!1;return()=>{warned$1||(warned$1=!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`."))}})(),exports.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 useColors$1(){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 m$3;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&&(m$3=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(m$3[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs$1(args){if(args[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+args[0]+(this.useColors?`%c `:` `)+`+`+module.exports.humanize(this.diff),!this.useColors)return;let c$3=`color: `+this.color;args.splice(1,0,c$3,`color: inherit`);let index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,match$1=>{match$1!==`%%`&&(index++,match$1===`%c`&&(lastC=index))}),args.splice(lastC,0,c$3)}exports.log=console.debug||console.log||(()=>{});function save$1(namespaces){try{namespaces?exports.storage.setItem(`debug`,namespaces):exports.storage.removeItem(`debug`)}catch{}}function load$6(){let r$3;try{r$3=exports.storage.getItem(`debug`)||exports.storage.getItem(`DEBUG`)}catch{}return!r$3&&typeof process<`u`&&`env`in process&&(r$3=process.env.DEBUG),r$3}function localstorage(){try{return localStorage}catch{}}module.exports=require_common$4()(exports);let{formatters:formatters$1}=module.exports;formatters$1.j=function(v$2){try{return JSON.stringify(v$2)}catch(error$22){return`[UnexpectedJSONParseError]: `+error$22.message}}})),require_has_flag$2=__commonJSMin(((exports,module)=>{module.exports=(flag,argv$1=process.argv)=>{let prefix=flag.startsWith(`-`)?``:flag.length===1?`-`:`--`,position=argv$1.indexOf(prefix+flag),terminatorPosition=argv$1.indexOf(`--`);return position!==-1&&(terminatorPosition===-1||position<terminatorPosition)}})),require_supports_color$3=__commonJSMin(((exports,module)=>{let os$13=__require$2(`os`),tty$5=__require$2(`tty`),hasFlag$5=require_has_flag$2(),{env:env$7}=process,forceColor$3;hasFlag$5(`no-color`)||hasFlag$5(`no-colors`)||hasFlag$5(`color=false`)||hasFlag$5(`color=never`)?forceColor$3=0:(hasFlag$5(`color`)||hasFlag$5(`colors`)||hasFlag$5(`color=true`)||hasFlag$5(`color=always`))&&(forceColor$3=1),`FORCE_COLOR`in env$7&&(forceColor$3=env$7.FORCE_COLOR===`true`?1:env$7.FORCE_COLOR===`false`?0:env$7.FORCE_COLOR.length===0?1:Math.min(parseInt(env$7.FORCE_COLOR,10),3));function translateLevel$4(level$1){return level$1===0?!1:{level:level$1,hasBasic:!0,has256:level$1>=2,has16m:level$1>=3}}function supportsColor$5(haveStream,streamIsTTY){if(forceColor$3===0)return 0;if(hasFlag$5(`color=16m`)||hasFlag$5(`color=full`)||hasFlag$5(`color=truecolor`))return 3;if(hasFlag$5(`color=256`))return 2;if(haveStream&&!streamIsTTY&&forceColor$3===void 0)return 0;let min=forceColor$3||0;if(env$7.TERM===`dumb`)return min;if(process.platform===`win32`){let osRelease=os$13.release().split(`.`);return Number(osRelease[0])>=10&&Number(osRelease[2])>=10586?Number(osRelease[2])>=14931?3:2:1}if(`CI`in env$7)return[`TRAVIS`,`CIRCLECI`,`APPVEYOR`,`GITLAB_CI`,`GITHUB_ACTIONS`,`BUILDKITE`].some(sign$2=>sign$2 in env$7)||env$7.CI_NAME===`codeship`?1:min;if(`TEAMCITY_VERSION`in env$7)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$7.TEAMCITY_VERSION)?1:0;if(env$7.COLORTERM===`truecolor`)return 3;if(`TERM_PROGRAM`in env$7){let version$4=parseInt((env$7.TERM_PROGRAM_VERSION||``).split(`.`)[0],10);switch(env$7.TERM_PROGRAM){case`iTerm.app`:return version$4>=3?3:2;case`Apple_Terminal`:return 2}}return/-256(color)?$/i.test(env$7.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$7.TERM)||`COLORTERM`in env$7?1:min}function getSupportLevel$3(stream$10){let level$1=supportsColor$5(stream$10,stream$10&&stream$10.isTTY);return translateLevel$4(level$1)}module.exports={supportsColor:getSupportLevel$3,stdout:translateLevel$4(supportsColor$5(!0,tty$5.isatty(1))),stderr:translateLevel$4(supportsColor$5(!0,tty$5.isatty(2)))}})),require_node$19=__commonJSMin(((exports,module)=>{let tty$4=__require$2(`tty`),util$67=__require$2(`util`);exports.init=init$3,exports.log=log$4,exports.formatArgs=formatArgs,exports.save=save,exports.load=load$5,exports.useColors=useColors,exports.destroy=util$67.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),exports.colors=[6,2,3,4,5,1];try{let supportsColor$6=require_supports_color$3();supportsColor$6&&(supportsColor$6.stderr||supportsColor$6).level>=2&&(exports.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{}exports.inspectOpts=Object.keys(process.env).filter(key=>/^debug_/i.test(key)).reduce((obj,key)=>{let prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,(_$6,k$2)=>k$2.toUpperCase()),val=process.env[key];return val=/^(yes|on|true|enabled)$/i.test(val)?!0:/^(no|off|false|disabled)$/i.test(val)?!1:val===`null`?null:Number(val),obj[prop]=val,obj},{});function useColors(){return`colors`in exports.inspectOpts?!!exports.inspectOpts.colors:tty$4.isatty(process.stderr.fd)}function formatArgs(args){let{namespace:name$5,useColors:useColors$2}=this;if(useColors$2){let c$3=this.color,colorCode=`\x1B[3`+(c$3<8?c$3:`8;5;`+c$3),prefix=` ${colorCode};1m${name$5} \u001B[0m`;args[0]=prefix+args[0].split(`
26
26
  `).join(`
27
27
  `+prefix),args.push(colorCode+`m+`+module.exports.humanize(this.diff)+`\x1B[0m`)}else args[0]=getDate()+name$5+` `+args[0]}function getDate(){return exports.inspectOpts.hideDate?``:new Date().toISOString()+` `}function log$4(...args){return process.stderr.write(util$67.formatWithOptions(exports.inspectOpts,...args)+`
28
28
  `)}function save(namespaces){namespaces?process.env.DEBUG=namespaces:delete process.env.DEBUG}function load$5(){return process.env.DEBUG}function init$3(debug$12){debug$12.inspectOpts={};let keys=Object.keys(exports.inspectOpts);for(let i$7=0;i$7<keys.length;i$7++)debug$12.inspectOpts[keys[i$7]]=exports.inspectOpts[keys[i$7]]}module.exports=require_common$4()(exports);let{formatters}=module.exports;formatters.o=function(v$2){return this.inspectOpts.colors=this.useColors,util$67.inspect(v$2,this.inspectOpts).split(`
@@ -2118,4 +2118,4 @@ node_modules
2118
2118
 
2119
2119
  ${packageManager} blink dev`),Se(`Edit agent.ts to hot-reload your agent.`)}var import_main=__toESM$1(require_main(),1);async function deploy(directory,options$1){directory||=process.cwd();let token$1=await loginIfNeeded(),client=new Client({authToken:token$1}),packageJSON=await findNearestEntry(directory,`package.json`);if(!packageJSON)throw Error(`package.json not found`);let packageJSONContent=await readFile$1(packageJSON,`utf-8`),packageJSONData=JSON.parse(packageJSONContent),deployDirectory=dirname(packageJSON),deployConfigPath=join(deployDirectory,`.blink`,`config.json`),deployConfig={};if(existsSync(deployConfigPath)){let deployConfigContent=await readFile$1(deployConfigPath,`utf-8`);deployConfig=JSON.parse(deployConfigContent)}let organizationName;if(deployConfig?.organizationId)try{let org=await client.organizations.get(deployConfig.organizationId);organizationName=org.name}catch{deployConfig.organizationId=void 0}if(!deployConfig?.organizationId){let organizations=await client.organizations.list();if(organizations.length===1){let organization=organizations[0];deployConfig.organizationId=organization.id,organizationName=organization.name}else{let organization=await ve({message:`Which organization should contain this agent?`,options:organizations.map(organization$1=>({value:organization$1.id,label:organization$1.name}))});if(pD(organization))return;deployConfig.organizationId=organization,organizationName=organizations.find(org=>org.id===organization).name}}if(!deployConfig.organizationId)throw Error(`Developer error: No organization ID found.`);let agentName;if(deployConfig?.agentId)try{let agent=await client.agents.get(deployConfig.agentId);agentName=agent.name}catch{deployConfig.agentId=void 0}if(!deployConfig?.agentId)try{let agent=await client.organizations.agents.get({organization_id:deployConfig.organizationId,agent_name:packageJSONData.name});deployConfig.agentId=agent.id,agentName=agent.name}catch{let agent=await client.agents.create({name:packageJSONData.name,organization_id:deployConfig.organizationId});deployConfig.agentId=agent.id,agentName=agent.name}if(!deployConfig.agentId)throw Error(`Developer error: No agent ID found.`);await mkdir(dirname(deployConfigPath),{recursive:!0}),await writeFile(deployConfigPath,JSON.stringify({_:`This file can be source controlled. It contains no secrets.`,...deployConfig},null,2),`utf-8`);let entrypoint=await resolveEntrypoint(directory),{outfile}=await build$1(entrypoint),filesToUpload={},outputFiles=await readdir(dirname(outfile));for(let file of outputFiles)filesToUpload[join(dirname(outfile),file)]=file;let readmePath=join(directory,`README.md`);await exists(readmePath)&&(filesToUpload[readmePath]=`README.md`);let uploadedFiles=[],totalFiles=Object.keys(filesToUpload).length,uploadedCount=0,totalUploadedBytes=0;for(let[filePath,uploadPath]of Object.entries(filesToUpload)){let st=await stat$1(filePath),fileSize=st.size;writeInline(`${source_default.dim(`[${uploadedCount+1}/${totalFiles}]`)} Uploading ${uploadPath} (${formatBytes(fileSize)})...`);let fileContent=await readFile$1(filePath),uploadedFile=await client.files.upload(new File([fileContent],uploadPath));uploadedFiles.push({path:uploadPath,id:uploadedFile.id}),uploadedCount+=1,totalUploadedBytes+=fileSize}writeInline(`${source_default.dim(`[${uploadedCount}/${totalFiles}]`)} Uploaded files (${formatBytes(totalUploadedBytes)}).`),process.stdout.write(`
2120
2120
  `);let localEnvFile=join(directory,`.env.local`),localEnvVarsSet=[];if(await exists(localEnvFile)){let localEnv=(0,import_main.parse)(await readFile$1(localEnvFile,`utf-8`));localEnvVarsSet=Object.keys(localEnv)}let cloudEnvVarsSet=[],cloudEnvVars=await client.agents.env.list({agent_id:deployConfig.agentId});cloudEnvVarsSet=cloudEnvVars.map(env$8=>env$8.key);let prodEnvFile=join(directory,`.env.production`);if(await exists(prodEnvFile)){let prodEnv=(0,import_main.parse)(await readFile$1(prodEnvFile,`utf-8`)),envEntries=Object.entries(prodEnv),totalEnvVars=envEntries.length,updatedEnvNames=[],updatedCount=0;for(let[key,value]of envEntries){let created=await client.agents.env.create({agent_id:deployConfig.agentId,key,value,target:[`production`,`preview`],secret:!0,upsert:!0});cloudEnvVarsSet.push(created.key),updatedEnvNames.push(key),updatedCount+=1,writeInline(`${source_default.dim(`[${updatedCount}/${totalEnvVars}]`)} Updating environment variables: ${updatedEnvNames.join(`, `)}`)}writeInline(`${source_default.dim(`[${updatedCount}/${totalEnvVars}]`)} Updated environment variables: ${updatedEnvNames.join(`, `)} ${source_default.dim(`(.env.production)`)}`),process.stdout.write(`
2121
- `)}let missingEnvVars=localEnvVarsSet.filter(v$2=>!cloudEnvVarsSet.includes(v$2));if(missingEnvVars.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let v$2 of missingEnvVars)console.log(`- ${v$2}`);let confirmed=await ye({message:`Do you want to deploy anyway?`});if(confirmed===!1||pD(confirmed))return}let deployment=await client.agents.deployments.create({agent_id:deployConfig.agentId,target:`production`,entrypoint:basename(outfile),files:uploadedFiles,message:options$1?.message}),inspectUrl=`https://blink.so/${organizationName}/${agentName}/deployments/${deployment.number}`;console.log(`Deployed:`,inspectUrl);let s$3=Y();s$3.start(`Waiting for deployment to be live...`);try{let pollIntervalMs=500;for(;;){let current=await client.agents.deployments.get({agent_id:deployConfig.agentId,deployment_id:deployment.id});if(current.status===`success`){let msg=`Deployment successful.`;current.target===`production`&&(msg+=` All chats will use this deployment!`),s$3.stop(msg);break}if(current.status===`failed`){let msg=`Deployment failed.`;current.error_message&&(msg+=` ${current.error_message}`),s$3.stop(msg),console.log(`Read logs for details:`,inspectUrl);return}await new Promise(r$3=>setTimeout(r$3,500))}}catch{s$3.stop(`Failed to poll for deployment status.`),console.log(`Read logs for details:`,inspectUrl);return}}const exists=async path$38=>{try{return await stat$1(path$38),!0}catch{return!1}};function formatBytes(bytes){if(bytes===0)return`0B`;let k$2=1024,sizes=[`B`,`KB`,`MB`,`GB`,`TB`],i$7=Math.floor(Math.log(bytes)/Math.log(k$2)),value=bytes/k$2**+i$7;return`${value.toFixed(value>=100?0:value>=10?1:2)}${sizes[i$7]}`}function writeInline(message){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(message);return}catch{}console.log(message)}async function login(){await login$1()}var version=`0.1.40`;await init_wrapper(),globalThis.WebSocket||(globalThis.WebSocket=import_websocket$1.default),globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>randomUUID()),program.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(version).action(()=>{program.outputHelp()}),program.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(init),program.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(dev),program.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(deploy),program.command(`build [directory]`).description(`Build your agent for production.`).action(build),program.command(`telemetry [boolean]`).description(`Enable or disable telemetry.`),program.command(`start [directory]`).description("Starts the Blink runtime in production mode. The agent must be compiled with `blink build` first."),program.command(`serve [entrypoint]`).description(`Serve the Blink agent as an HTTP server.`).action(serve),program.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(connect),program.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(chat),program.command(`login`,{hidden:!0}).description(`Log in to the Blink Cloud.`).action(login),program.parse(process.argv);export{};
2121
+ `)}let missingEnvVars=localEnvVarsSet.filter(v$2=>!cloudEnvVarsSet.includes(v$2));if(missingEnvVars.length>0){console.log(`Warning: The following environment variables are set in .env.local but not in .env.production:`);for(let v$2 of missingEnvVars)console.log(`- ${v$2}`);let confirmed=await ye({message:`Do you want to deploy anyway?`});if(confirmed===!1||pD(confirmed))return}let deployment=await client.agents.deployments.create({agent_id:deployConfig.agentId,target:`production`,entrypoint:basename(outfile),files:uploadedFiles,message:options$1?.message}),inspectUrl=`https://blink.so/${organizationName}/${agentName}/deployments/${deployment.number}`;console.log(`Deployed:`,inspectUrl);let s$3=Y();s$3.start(`Waiting for deployment to be live...`);try{let pollIntervalMs=500;for(;;){let current=await client.agents.deployments.get({agent_id:deployConfig.agentId,deployment_id:deployment.id});if(current.status===`success`){let msg=`Deployment successful.`;current.target===`production`&&(msg+=` All chats will use this deployment!`),s$3.stop(msg);break}if(current.status===`failed`){let msg=`Deployment failed.`;current.error_message&&(msg+=` ${current.error_message}`),s$3.stop(msg),console.log(`Read logs for details:`,inspectUrl);return}await new Promise(r$3=>setTimeout(r$3,500))}}catch{s$3.stop(`Failed to poll for deployment status.`),console.log(`Read logs for details:`,inspectUrl);return}}const exists=async path$38=>{try{return await stat$1(path$38),!0}catch{return!1}};function formatBytes(bytes){if(bytes===0)return`0B`;let k$2=1024,sizes=[`B`,`KB`,`MB`,`GB`,`TB`],i$7=Math.floor(Math.log(bytes)/Math.log(k$2)),value=bytes/k$2**+i$7;return`${value.toFixed(value>=100?0:value>=10?1:2)}${sizes[i$7]}`}function writeInline(message){if(process.stdout.isTTY)try{process.stdout.clearLine(0),process.stdout.cursorTo(0),process.stdout.write(message);return}catch{}console.log(message)}async function login(){await login$1()}var version=`0.1.42`;await init_wrapper(),globalThis.WebSocket||(globalThis.WebSocket=import_websocket$1.default),globalThis.crypto||(globalThis.crypto={}),globalThis.crypto.randomUUID||(globalThis.crypto.randomUUID=()=>randomUUID()),program.name(`blink`).description(`Blink is a runtime for building and deploying AI agents.`).version(version).action(()=>{program.outputHelp()}),program.command(`init [directory]`).description(`Initialize a new Blink agent.`).action(init),program.command(`dev [directory] [options]`).description(`Start a development server for your agent.`).action(dev),program.command(`deploy [directory]`).description(`Deploy your agent to the Blink Cloud.`).option(`-m, --message <message>`,`Message for this deployment`).action(deploy),program.command(`build [directory]`).description(`Build your agent for production.`).action(build),program.command(`telemetry [boolean]`).description(`Enable or disable telemetry.`),program.command(`start [directory]`).description("Starts the Blink runtime in production mode. The agent must be compiled with `blink build` first."),program.command(`serve [entrypoint]`).description(`Serve the Blink agent as an HTTP server.`).action(serve),program.command(`connect`,{hidden:!0}).description(`Connect compute to the Blink Cloud.`).action(connect),program.command(`chat`,{hidden:!0}).description(`Start a Blink chat connected to your machine.`).action(chat),program.command(`login`,{hidden:!0}).description(`Log in to the Blink Cloud.`).action(login),program.parse(process.argv);export{};
package/dist/test.cjs CHANGED
@@ -1 +1 @@
1
- const e=require(`./cookie-B3SvZDri.cjs`);let t=require(`fs/promises`);t=e.__toESM(t);let n=require(`path`);n=e.__toESM(n);async function r(e,{outdir:t}={}){t||=await a(e);let r=(0,n.join)(t,`agent.js`),i=c(),o=await i.build({...s,entryPoints:[e],outfile:r});if(o.errors.length>0)throw Error(`Failed to build agent!`);return{outfile:r}}async function i(e){let r=await o(e,`package.json`);if(!r)throw Error(`No package.json found in ${e}`);let i=JSON.parse(await(0,t.readFile)(r,`utf-8`)),a=i.main;if(!a)throw Error(`"main" is not set in ${(0,n.relative)(process.cwd(),r)}. It should be set to the entrypoint of your agent.`);let s=(0,n.join)((0,n.dirname)(r),a),c=await(0,t.stat)(s);if(!c.isFile())throw Error(`${s} is not a file.`);return s}async function a(e){let r=await o(e,`node_modules`);if(!r){let r=await(0,t.stat)(e);return r.isDirectory()?(0,n.join)(e,`.blink`):(0,n.join)((0,n.dirname)(e),`.blink`)}let i=(0,n.join)(r,`.blink`);return await(0,t.mkdir)(i,{recursive:!0}),i}async function o(e,r){let i=e;for(;i!==(0,n.dirname)(i);){let e=(0,n.join)(i,r);try{return await(0,t.stat)(e),e}catch{}i=(0,n.dirname)(i)}}const s={bundle:!0,format:`cjs`,platform:`node`,target:`node18`,sourcemap:`inline`},c=()=>{try{return require(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};function l(e){let t=require(e);if(typeof t!=`object`)throw Error(`The module at ${e} must export an object.`);let n=t.default;if(typeof n!=`object`)throw Error(`The module at ${e} must export an object.`);if(!n.version)throw Error(`The module at ${e} must export a "version" property.`);if(typeof n.fetch!=`function`)throw Error(`The module at ${e} must export a "fetch" function.`);return n}function u(e){return new d(`http://agent.local`,{fetch:async(t,n)=>e.fetch(new Request(t,{...n,duplex:n.body?`half`:void 0}))})}var d=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/sendMessages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendWebhook(e){let t=new URL(e.url),n=new Headers(e.headers);return this.fetch(`${this.baseUrl}/webhook?${t.searchParams.toString()}`,{method:e.method,headers:n,body:e.body,duplex:e.body?`half`:void 0})}},f=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},p=Symbol(),m=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof y?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?h(e,{all:n,dot:r}):{}};async function h(e,t){let n=await e.formData();return n?g(n,t):{}}function g(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?ee(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(_(n,e,t),delete n[e])}),n}var ee=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},_=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},v=t=>e.tryDecode(t,e.decodeURIComponent_),y=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?v(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?v(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(t){return e.getQueryParam(this.url,t)}queries(t){return e.getQueryParams(this.url,t)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await m(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[p](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},te={Stringify:1,BeforeStream:2,Stream:3},ne=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},b=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>b(e,t,!1,r,i))).then(()=>i[0]));return n?ne(await o,a):o},x=`text/plain; charset=UTF-8`,S=(e,t)=>({"Content-Type":e,...t}),re=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new y(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,S(x,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,S(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,S(`text/html; charset=UTF-8`,n));return typeof e==`object`?b(e,te.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},C=`ALL`,ie=`all`,ae=[`get`,`post`,`put`,`delete`,`options`,`patch`],w=`Can not add a route since the matcher is already built.`,T=class extends Error{},E=`__COMPOSED_HANDLER`,D=e=>e.text(`404 Not Found`,404),O=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},k=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(t={}){let n=[...ae,ie];n.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(C,this.#path,e)}),this);let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??e.getPath:e.getPathNoStrict}#clone(){let e=new k({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=D;errorHandler=O;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===O?r=e.handler:(r=async(n,r)=>(await f([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[E]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(t){let n=this.#clone();return n._basePath=e.mergePath(this._basePath,t),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(t,n,r){let i,a;r&&(typeof r==`function`?a=r:(a=r.optionHandler,i=r.replaceRequest===!1?e=>e:r.replaceRequest));let o=a?e=>{let t=a(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};i||=(()=>{let n=e.mergePath(this._basePath,t),r=n===`/`?0:n.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(r)||`/`,new Request(t,e)}})();let s=async(e,t)=>{let r=await n(i(e.req.raw),...o(e));if(r)return r;await t()};return this.#addRoute(C,e.mergePath(t,`*`),s),this}#addRoute(t,n,r){t=t.toUpperCase(),n=e.mergePath(this._basePath,n);let i={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,i]),this.routes.push(i)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new re(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=f(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(t,n,r,i)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,i):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${e.mergePath(`/`,t)}`,n),r,i));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},A=`[^/]+`,j=`.*`,M=`(?:|/.*)`,N=Symbol(),oe=new Set(`.\\+*[^]$()`);function se(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===j||e===M?1:t===j||t===M?-1:e===A?1:t===A?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var P=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw N;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,j]:[``,``,A]:a===`/*`?[``,``,M]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||A;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw N;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==j&&e!==M))throw N;if(i)return;c=this.#children[t]=new P,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==j&&e!==M))throw N;if(i)return;c=this.#children[a]=new P}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(se),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:oe.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},ce=class{#context={varIndex:0};#root=new P;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},F=[],I=[/^$/,[],Object.create(null)],L=Object.create(null);function R(e){return L[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function z(){L=Object.create(null)}function B(e){let t=new ce,n=[];if(e.length===0)return I;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),F]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===N?new T(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function V(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(R(n).test(t))return[...e[n]]}}var H=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[C]:Object.create(null)},this.#routes={[C]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(w);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[C]).forEach(n=>{e[t][n]=[...e[C][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=R(n);t===C?Object.keys(i).forEach(e=>{i[e][n]||=V(i[e],n)||V(i[C],n)||[]}):i[t][n]||=V(i[t],n)||V(i[C],n)||[],Object.keys(i).forEach(n=>{(t===C||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===C||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e.checkOptionalParameter(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===C||t===s)&&(a[s][c]||=[...V(i[s],c)||V(i[C],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){z();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[C],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],F];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===C;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==C&&t.push(...Object.keys(r[C]).map(e=>[e,r[C][e]])):(n||=!0,t.push(...i))}),n?B(t):null}},U=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(w);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof T)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(t,n,r){this.#order=++this.#order;let i=this,a=e.splitRoutingPath(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=e.getPattern(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#children){i=i.#children[c],s&&o.push(s[1]);continue}i.#children[c]=new G,s&&(i.#patterns.push(s),o.push(s[1])),i=i.#children[c]}return i.#methods.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),i}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[C],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(t,n){let r=[];this.#params=W;let i=this,a=[i],o=e.splitPath(n),s=[];for(let e=0,n=o.length;e<n;e++){let i=o[e],c=e===n-1,l=[];for(let n=0,u=a.length;n<u;n++){let u=a[n],d=u.#children[i];d&&(d.#params=u.#params,c?(d.#children[`*`]&&r.push(...this.#getHandlerSets(d.#children[`*`],t,u.#params)),r.push(...this.#getHandlerSets(d,t,u.#params))):l.push(d));for(let n=0,a=u.#patterns.length;n<a;n++){let a=u.#patterns[n],d=u.#params===W?{}:{...u.#params};if(a===`*`){let e=u.#children[`*`];e&&(r.push(...this.#getHandlerSets(e,t,u.#params)),e.#params=d,l.push(e));continue}let[f,p,m]=a;if(!i&&!(m instanceof RegExp))continue;let h=u.#children[f],g=o.slice(e).join(`/`);if(m instanceof RegExp){let e=m.exec(g);if(e){if(d[p]=e[0],r.push(...this.#getHandlerSets(h,t,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let t=e[0].match(/\//)?.length??0,n=s[t]||=[];n.push(h)}continue}}(m===!0||m.test(i))&&(d[p]=i,c?(r.push(...this.#getHandlerSets(h,t,d,u.#params)),h.#children[`*`]&&r.push(...this.#getHandlerSets(h.#children[`*`],t,d,u.#params))):(h.#params=d,l.push(h)))}}a=l.concat(s.shift()??[])}return r.length>1&&r.sort((e,t)=>e.score-t.score),[r.map(({handler:e,params:t})=>[e,t])]}},le=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(t,n,r){let i=e.checkOptionalParameter(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},K=class extends k{constructor(e={}){super(e),this.router=e.router??new U({routers:[new H,new le]})}},ue=(t,n,r)=>{let i=t.req.raw.headers.get(`Cookie`);if(typeof n==`string`){if(!i)return;let t=n;r===`secure`?t=`__Secure-`+n:r===`host`&&(t=`__Host-`+n);let a=e.parse(i,t);return a[t]}if(!i)return{};let a=e.parse(i);return a},q=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},de=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},fe=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,pe=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,me=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,J=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!fe.test(a))break;try{i=await n.req.json()}catch{throw new q(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(pe.test(a)||me.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await de(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new q(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=ue(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const Y=()=>new K,X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=Y().basePath(`/:key`).get(`/`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.get(t);return e.json({value:r},200)}).post(`/`,J(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.set(t,r),e.body(null,204)}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},he=Y().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,J(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)}),ge=new K().route(`/storage`,Q).route(`/chat`,he);async function _e(e){let t=e?.entrypoint??await i(e?.cwd??process.cwd());if(!t)throw Error(`Unable to locate the entrypoint of the agent. Please specify it manually.`);let n;if(typeof Bun<`u`)n=l(t);else{let{outfile:e}=await r(t);n=l(e)}return u(n)}exports.create=_e;
1
+ const e=require(`./cookie-B3SvZDri.cjs`);let t=require(`fs/promises`);t=e.__toESM(t);let n=require(`path`);n=e.__toESM(n);async function r(e,{outdir:t}={}){t||=await a(e);let r=(0,n.join)(t,`agent.js`),i=c(),o=await i.build({...s,entryPoints:[e],outfile:r});if(o.errors.length>0)throw Error(`Failed to build agent!`);return{outfile:r}}async function i(e){let r=await o(e,`package.json`);if(!r)throw Error(`No package.json found in ${e}`);let i=JSON.parse(await(0,t.readFile)(r,`utf-8`)),a=i.main;if(!a)throw Error(`"main" is not set in ${(0,n.relative)(process.cwd(),r)}. It should be set to the entrypoint of your agent.`);let s=(0,n.join)((0,n.dirname)(r),a),c=await(0,t.stat)(s);if(!c.isFile())throw Error(`${s} is not a file.`);return s}async function a(e){let r=await o(e,`node_modules`);if(!r){let r=await(0,t.stat)(e);return r.isDirectory()?(0,n.join)(e,`.blink`):(0,n.join)((0,n.dirname)(e),`.blink`)}let i=(0,n.join)(r,`.blink`);return await(0,t.mkdir)(i,{recursive:!0}),i}async function o(e,r){let i=e;for(;i!==(0,n.dirname)(i);){let e=(0,n.join)(i,r);try{return await(0,t.stat)(e),e}catch{}i=(0,n.dirname)(i)}}const s={bundle:!0,format:`esm`,platform:`node`,target:`node22`,mainFields:[`module`,`main`],conditions:[`import`,`module`]},c=()=>{try{return require(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};function l(e){let t=require(e);if(typeof t!=`object`)throw Error(`The module at ${e} must export an object.`);let n=t.default;if(typeof n!=`object`)throw Error(`The module at ${e} must export an object.`);if(!n.version)throw Error(`The module at ${e} must export a "version" property.`);if(typeof n.fetch!=`function`)throw Error(`The module at ${e} must export a "fetch" function.`);return n}function u(e){return new d(`http://agent.local`,{fetch:async(t,n)=>e.fetch(new Request(t,{...n,duplex:n.body?`half`:void 0}))})}var d=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/sendMessages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendWebhook(e){let t=new URL(e.url),n=new Headers(e.headers);return this.fetch(`${this.baseUrl}/webhook?${t.searchParams.toString()}`,{method:e.method,headers:n,body:e.body,duplex:e.body?`half`:void 0})}},f=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},p=Symbol(),m=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof y?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?h(e,{all:n,dot:r}):{}};async function h(e,t){let n=await e.formData();return n?g(n,t):{}}function g(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?ee(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(_(n,e,t),delete n[e])}),n}var ee=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},_=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},v=t=>e.tryDecode(t,e.decodeURIComponent_),y=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?v(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?v(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(t){return e.getQueryParam(this.url,t)}queries(t){return e.getQueryParams(this.url,t)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await m(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[p](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},te={Stringify:1,BeforeStream:2,Stream:3},ne=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},b=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>b(e,t,!1,r,i))).then(()=>i[0]));return n?ne(await o,a):o},x=`text/plain; charset=UTF-8`,S=(e,t)=>({"Content-Type":e,...t}),re=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new y(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,S(x,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,S(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,S(`text/html; charset=UTF-8`,n));return typeof e==`object`?b(e,te.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},C=`ALL`,ie=`all`,ae=[`get`,`post`,`put`,`delete`,`options`,`patch`],w=`Can not add a route since the matcher is already built.`,T=class extends Error{},E=`__COMPOSED_HANDLER`,D=e=>e.text(`404 Not Found`,404),O=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},k=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(t={}){let n=[...ae,ie];n.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(C,this.#path,e)}),this);let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??e.getPath:e.getPathNoStrict}#clone(){let e=new k({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=D;errorHandler=O;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===O?r=e.handler:(r=async(n,r)=>(await f([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[E]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(t){let n=this.#clone();return n._basePath=e.mergePath(this._basePath,t),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(t,n,r){let i,a;r&&(typeof r==`function`?a=r:(a=r.optionHandler,i=r.replaceRequest===!1?e=>e:r.replaceRequest));let o=a?e=>{let t=a(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};i||=(()=>{let n=e.mergePath(this._basePath,t),r=n===`/`?0:n.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(r)||`/`,new Request(t,e)}})();let s=async(e,t)=>{let r=await n(i(e.req.raw),...o(e));if(r)return r;await t()};return this.#addRoute(C,e.mergePath(t,`*`),s),this}#addRoute(t,n,r){t=t.toUpperCase(),n=e.mergePath(this._basePath,n);let i={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,i]),this.routes.push(i)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new re(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=f(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(t,n,r,i)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,i):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${e.mergePath(`/`,t)}`,n),r,i));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},A=`[^/]+`,j=`.*`,M=`(?:|/.*)`,N=Symbol(),oe=new Set(`.\\+*[^]$()`);function se(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===j||e===M?1:t===j||t===M?-1:e===A?1:t===A?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var P=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw N;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,j]:[``,``,A]:a===`/*`?[``,``,M]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||A;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw N;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==j&&e!==M))throw N;if(i)return;c=this.#children[t]=new P,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==j&&e!==M))throw N;if(i)return;c=this.#children[a]=new P}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(se),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:oe.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},ce=class{#context={varIndex:0};#root=new P;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},F=[],I=[/^$/,[],Object.create(null)],L=Object.create(null);function R(e){return L[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function z(){L=Object.create(null)}function B(e){let t=new ce,n=[];if(e.length===0)return I;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),F]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===N?new T(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function V(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(R(n).test(t))return[...e[n]]}}var H=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[C]:Object.create(null)},this.#routes={[C]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(w);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[C]).forEach(n=>{e[t][n]=[...e[C][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=R(n);t===C?Object.keys(i).forEach(e=>{i[e][n]||=V(i[e],n)||V(i[C],n)||[]}):i[t][n]||=V(i[t],n)||V(i[C],n)||[],Object.keys(i).forEach(n=>{(t===C||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===C||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e.checkOptionalParameter(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===C||t===s)&&(a[s][c]||=[...V(i[s],c)||V(i[C],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){z();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[C],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],F];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===C;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==C&&t.push(...Object.keys(r[C]).map(e=>[e,r[C][e]])):(n||=!0,t.push(...i))}),n?B(t):null}},U=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(w);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof T)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(t,n,r){this.#order=++this.#order;let i=this,a=e.splitRoutingPath(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=e.getPattern(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#children){i=i.#children[c],s&&o.push(s[1]);continue}i.#children[c]=new G,s&&(i.#patterns.push(s),o.push(s[1])),i=i.#children[c]}return i.#methods.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),i}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[C],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(t,n){let r=[];this.#params=W;let i=this,a=[i],o=e.splitPath(n),s=[];for(let e=0,n=o.length;e<n;e++){let i=o[e],c=e===n-1,l=[];for(let n=0,u=a.length;n<u;n++){let u=a[n],d=u.#children[i];d&&(d.#params=u.#params,c?(d.#children[`*`]&&r.push(...this.#getHandlerSets(d.#children[`*`],t,u.#params)),r.push(...this.#getHandlerSets(d,t,u.#params))):l.push(d));for(let n=0,a=u.#patterns.length;n<a;n++){let a=u.#patterns[n],d=u.#params===W?{}:{...u.#params};if(a===`*`){let e=u.#children[`*`];e&&(r.push(...this.#getHandlerSets(e,t,u.#params)),e.#params=d,l.push(e));continue}let[f,p,m]=a;if(!i&&!(m instanceof RegExp))continue;let h=u.#children[f],g=o.slice(e).join(`/`);if(m instanceof RegExp){let e=m.exec(g);if(e){if(d[p]=e[0],r.push(...this.#getHandlerSets(h,t,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let t=e[0].match(/\//)?.length??0,n=s[t]||=[];n.push(h)}continue}}(m===!0||m.test(i))&&(d[p]=i,c?(r.push(...this.#getHandlerSets(h,t,d,u.#params)),h.#children[`*`]&&r.push(...this.#getHandlerSets(h.#children[`*`],t,d,u.#params))):(h.#params=d,l.push(h)))}}a=l.concat(s.shift()??[])}return r.length>1&&r.sort((e,t)=>e.score-t.score),[r.map(({handler:e,params:t})=>[e,t])]}},le=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(t,n,r){let i=e.checkOptionalParameter(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},K=class extends k{constructor(e={}){super(e),this.router=e.router??new U({routers:[new H,new le]})}},ue=(t,n,r)=>{let i=t.req.raw.headers.get(`Cookie`);if(typeof n==`string`){if(!i)return;let t=n;r===`secure`?t=`__Secure-`+n:r===`host`&&(t=`__Host-`+n);let a=e.parse(i,t);return a[t]}if(!i)return{};let a=e.parse(i);return a},q=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},de=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},fe=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,pe=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,me=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,J=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!fe.test(a))break;try{i=await n.req.json()}catch{throw new q(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(pe.test(a)||me.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await de(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new q(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=ue(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const Y=()=>new K,X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=Y().basePath(`/:key`).get(`/`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.get(t);return e.json({value:r},200)}).post(`/`,J(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.set(t,r),e.body(null,204)}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},he=Y().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,J(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)}),ge=new K().route(`/storage`,Q).route(`/chat`,he);async function _e(e){let t=e?.entrypoint??await i(e?.cwd??process.cwd());if(!t)throw Error(`Unable to locate the entrypoint of the agent. Please specify it manually.`);let n;if(typeof Bun<`u`)n=l(t);else{let{outfile:e}=await r(t);n=l(e)}return u(n)}exports.create=_e;
package/dist/test.js CHANGED
@@ -1 +1 @@
1
- import{checkOptionalParameter as e,decodeURIComponent_ as t,getPath as n,getPathNoStrict as r,getPattern as i,getQueryParam as a,getQueryParams as o,mergePath as s,parse as c,splitPath as l,splitRoutingPath as u,tryDecode as d}from"./cookie-BiKY7-P1.js";import{createRequire as f}from"node:module";import{mkdir as p,readFile as m,stat as h}from"fs/promises";import{dirname as g,join as _,relative as ee}from"path";var v=f(import.meta.url);async function y(e,{outdir:t}={}){t||=await te(e);let n=_(t,`agent.js`),r=re(),i=await r.build({...ne,entryPoints:[e],outfile:n});if(i.errors.length>0)throw Error(`Failed to build agent!`);return{outfile:n}}async function b(e){let t=await x(e,`package.json`);if(!t)throw Error(`No package.json found in ${e}`);let n=JSON.parse(await m(t,`utf-8`)),r=n.main;if(!r)throw Error(`"main" is not set in ${ee(process.cwd(),t)}. It should be set to the entrypoint of your agent.`);let i=_(g(t),r),a=await h(i);if(!a.isFile())throw Error(`${i} is not a file.`);return i}async function te(e){let t=await x(e,`node_modules`);if(!t){let t=await h(e);return t.isDirectory()?_(e,`.blink`):_(g(e),`.blink`)}let n=_(t,`.blink`);return await p(n,{recursive:!0}),n}async function x(e,t){let n=e;for(;n!==g(n);){let e=_(n,t);try{return await h(e),e}catch{}n=g(n)}}const ne={bundle:!0,format:`cjs`,platform:`node`,target:`node18`,sourcemap:`inline`},re=()=>{try{return v(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};function S(e){let t=v(e);if(typeof t!=`object`)throw Error(`The module at ${e} must export an object.`);let n=t.default;if(typeof n!=`object`)throw Error(`The module at ${e} must export an object.`);if(!n.version)throw Error(`The module at ${e} must export a "version" property.`);if(typeof n.fetch!=`function`)throw Error(`The module at ${e} must export a "fetch" function.`);return n}function ie(e){return new ae(`http://agent.local`,{fetch:async(t,n)=>e.fetch(new Request(t,{...n,duplex:n.body?`half`:void 0}))})}var ae=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/sendMessages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendWebhook(e){let t=new URL(e.url),n=new Headers(e.headers);return this.fetch(`${this.baseUrl}/webhook?${t.searchParams.toString()}`,{method:e.method,headers:n,body:e.body,duplex:e.body?`half`:void 0})}},C=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},w=Symbol(),T=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof D?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?oe(e,{all:n,dot:r}):{}};async function oe(e,t){let n=await e.formData();return n?se(n,t):{}}function se(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?ce(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(le(n,e,t),delete n[e])}),n}var ce=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},le=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},E=e=>d(e,t),D=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?E(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?E(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return a(this.url,e)}queries(e){return o(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await T(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[w](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ue={Stringify:1,BeforeStream:2,Stream:3},de=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},O=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>O(e,t,!1,r,i))).then(()=>i[0]));return n?de(await o,a):o},fe=`text/plain; charset=UTF-8`,k=(e,t)=>({"Content-Type":e,...t}),pe=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new D(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,k(fe,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,k(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,k(`text/html; charset=UTF-8`,n));return typeof e==`object`?O(e,ue.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},A=`ALL`,me=`all`,he=[`get`,`post`,`put`,`delete`,`options`,`patch`],j=`Can not add a route since the matcher is already built.`,M=class extends Error{},ge=`__COMPOSED_HANDLER`,_e=e=>e.text(`404 Not Found`,404),N=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},P=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...he,me];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(A,this.#path,e)}),this);let{strict:i,...a}=e;Object.assign(this,a),this.getPath=i??!0?e.getPath??n:r}#clone(){let e=new P({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=_e;errorHandler=N;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===N?r=e.handler:(r=async(n,r)=>(await C([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[ge]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=s(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=s(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(A,s(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=s(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new pe(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=C(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${s(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},F=`[^/]+`,I=`.*`,L=`(?:|/.*)`,R=Symbol(),ve=new Set(`.\\+*[^]$()`);function ye(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===I||e===L?1:t===I||t===L?-1:e===F?1:t===F?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var z=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw R;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,I]:[``,``,F]:a===`/*`?[``,``,L]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||F;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw R;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==I&&e!==L))throw R;if(i)return;c=this.#children[t]=new z,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==I&&e!==L))throw R;if(i)return;c=this.#children[a]=new z}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(ye),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ve.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},be=class{#context={varIndex:0};#root=new z;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},B=[],xe=[/^$/,[],Object.create(null)],V=Object.create(null);function H(e){return V[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function Se(){V=Object.create(null)}function Ce(e){let t=new be,n=[];if(e.length===0)return xe;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),B]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===R?new M(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function U(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(H(n).test(t))return[...e[n]]}}var we=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[A]:Object.create(null)},this.#routes={[A]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(j);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[A]).forEach(n=>{e[t][n]=[...e[A][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=H(n);t===A?Object.keys(i).forEach(e=>{i[e][n]||=U(i[e],n)||U(i[A],n)||[]}):i[t][n]||=U(i[t],n)||U(i[A],n)||[],Object.keys(i).forEach(n=>{(t===A||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===A||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===A||t===s)&&(a[s][c]||=[...U(i[s],c)||U(i[A],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){Se();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[A],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],B];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===A;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==A&&t.push(...Object.keys(r[A]).map(e=>[e,r[A][e]])):(n||=!0,t.push(...i))}),n?Ce(t):null}},Te=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(j);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof M)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,a=u(t),o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e],n=a[e+1],s=i(t,n),c=Array.isArray(s)?s[0]:t;if(c in r.#children){r=r.#children[c],s&&o.push(s[1]);continue}r.#children[c]=new G,s&&(r.#patterns.push(s),o.push(s[1])),r=r.#children[c]}return r.#methods.push({[e]:{handler:n,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[A],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=W;let r=this,i=[r],a=l(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===W?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},Ee=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(t,n,r){let i=e(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},K=class extends P{constructor(e={}){super(e),this.router=e.router??new Te({routers:[new we,new Ee]})}},De=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=c(r,e);return i[e]}if(!r)return{};let i=c(r);return i},q=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},Oe=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},J=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ke=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,Ae=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!J.test(a))break;try{i=await n.req.json()}catch{throw new q(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(ke.test(a)||Ae.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await Oe(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new q(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=De(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=()=>new K,Z=(e,t)=>e.json({error:t},400),Q=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},je=X().basePath(`/:key`).get(`/`,async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let r=await e.env.storage.get(t);return e.json({value:r},200)}).post(`/`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?Z(t,`Value is too long. Max length is 1024 characters.`):{value:n}:Z(t,`Value must be a string`):Z(t,`Value is required`)}),async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.set(t,r),e.body(null,204)}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Me=X().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return Z(t,`Messages are required`);if(!Array.isArray(n))return Z(t,`Messages must be an array`);if(n.length===0)return Z(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?Z(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)});new K().route(`/storage`,je).route(`/chat`,Me);async function Ne(e){let t=e?.entrypoint??await b(e?.cwd??process.cwd());if(!t)throw Error(`Unable to locate the entrypoint of the agent. Please specify it manually.`);let n;if(typeof Bun<`u`)n=S(t);else{let{outfile:e}=await y(t);n=S(e)}return ie(n)}export{Ne as create};
1
+ import{checkOptionalParameter as e,decodeURIComponent_ as t,getPath as n,getPathNoStrict as r,getPattern as i,getQueryParam as a,getQueryParams as o,mergePath as s,parse as c,splitPath as l,splitRoutingPath as u,tryDecode as d}from"./cookie-BiKY7-P1.js";import{createRequire as f}from"node:module";import{mkdir as p,readFile as m,stat as h}from"fs/promises";import{dirname as g,join as _,relative as ee}from"path";var v=f(import.meta.url);async function y(e,{outdir:t}={}){t||=await te(e);let n=_(t,`agent.js`),r=re(),i=await r.build({...ne,entryPoints:[e],outfile:n});if(i.errors.length>0)throw Error(`Failed to build agent!`);return{outfile:n}}async function b(e){let t=await x(e,`package.json`);if(!t)throw Error(`No package.json found in ${e}`);let n=JSON.parse(await m(t,`utf-8`)),r=n.main;if(!r)throw Error(`"main" is not set in ${ee(process.cwd(),t)}. It should be set to the entrypoint of your agent.`);let i=_(g(t),r),a=await h(i);if(!a.isFile())throw Error(`${i} is not a file.`);return i}async function te(e){let t=await x(e,`node_modules`);if(!t){let t=await h(e);return t.isDirectory()?_(e,`.blink`):_(g(e),`.blink`)}let n=_(t,`.blink`);return await p(n,{recursive:!0}),n}async function x(e,t){let n=e;for(;n!==g(n);){let e=_(n,t);try{return await h(e),e}catch{}n=g(n)}}const ne={bundle:!0,format:`esm`,platform:`node`,target:`node22`,mainFields:[`module`,`main`],conditions:[`import`,`module`]},re=()=>{try{return v(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};function S(e){let t=v(e);if(typeof t!=`object`)throw Error(`The module at ${e} must export an object.`);let n=t.default;if(typeof n!=`object`)throw Error(`The module at ${e} must export an object.`);if(!n.version)throw Error(`The module at ${e} must export a "version" property.`);if(typeof n.fetch!=`function`)throw Error(`The module at ${e} must export a "fetch" function.`);return n}function ie(e){return new ae(`http://agent.local`,{fetch:async(t,n)=>e.fetch(new Request(t,{...n,duplex:n.body?`half`:void 0}))})}var ae=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/sendMessages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendWebhook(e){let t=new URL(e.url),n=new Headers(e.headers);return this.fetch(`${this.baseUrl}/webhook?${t.searchParams.toString()}`,{method:e.method,headers:n,body:e.body,duplex:e.body?`half`:void 0})}},C=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},w=Symbol(),T=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof D?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?oe(e,{all:n,dot:r}):{}};async function oe(e,t){let n=await e.formData();return n?se(n,t):{}}function se(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?ce(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(le(n,e,t),delete n[e])}),n}var ce=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},le=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},E=e=>d(e,t),D=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?E(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?E(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return a(this.url,e)}queries(e){return o(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await T(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[w](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ue={Stringify:1,BeforeStream:2,Stream:3},de=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},O=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>O(e,t,!1,r,i))).then(()=>i[0]));return n?de(await o,a):o},fe=`text/plain; charset=UTF-8`,k=(e,t)=>({"Content-Type":e,...t}),pe=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new D(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,k(fe,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,k(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,k(`text/html; charset=UTF-8`,n));return typeof e==`object`?O(e,ue.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},A=`ALL`,me=`all`,he=[`get`,`post`,`put`,`delete`,`options`,`patch`],j=`Can not add a route since the matcher is already built.`,M=class extends Error{},ge=`__COMPOSED_HANDLER`,_e=e=>e.text(`404 Not Found`,404),N=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},P=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...he,me];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(A,this.#path,e)}),this);let{strict:i,...a}=e;Object.assign(this,a),this.getPath=i??!0?e.getPath??n:r}#clone(){let e=new P({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=_e;errorHandler=N;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===N?r=e.handler:(r=async(n,r)=>(await C([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[ge]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=s(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=s(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(A,s(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=s(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new pe(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=C(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${s(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},F=`[^/]+`,I=`.*`,L=`(?:|/.*)`,R=Symbol(),ve=new Set(`.\\+*[^]$()`);function ye(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===I||e===L?1:t===I||t===L?-1:e===F?1:t===F?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var z=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw R;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,I]:[``,``,F]:a===`/*`?[``,``,L]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||F;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw R;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==I&&e!==L))throw R;if(i)return;c=this.#children[t]=new z,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==I&&e!==L))throw R;if(i)return;c=this.#children[a]=new z}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(ye),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ve.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},be=class{#context={varIndex:0};#root=new z;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},B=[],xe=[/^$/,[],Object.create(null)],V=Object.create(null);function H(e){return V[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function Se(){V=Object.create(null)}function Ce(e){let t=new be,n=[];if(e.length===0)return xe;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),B]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===R?new M(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function U(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(H(n).test(t))return[...e[n]]}}var we=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[A]:Object.create(null)},this.#routes={[A]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(j);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[A]).forEach(n=>{e[t][n]=[...e[A][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=H(n);t===A?Object.keys(i).forEach(e=>{i[e][n]||=U(i[e],n)||U(i[A],n)||[]}):i[t][n]||=U(i[t],n)||U(i[A],n)||[],Object.keys(i).forEach(n=>{(t===A||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===A||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===A||t===s)&&(a[s][c]||=[...U(i[s],c)||U(i[A],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){Se();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[A],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],B];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===A;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==A&&t.push(...Object.keys(r[A]).map(e=>[e,r[A][e]])):(n||=!0,t.push(...i))}),n?Ce(t):null}},Te=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(j);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof M)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,a=u(t),o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e],n=a[e+1],s=i(t,n),c=Array.isArray(s)?s[0]:t;if(c in r.#children){r=r.#children[c],s&&o.push(s[1]);continue}r.#children[c]=new G,s&&(r.#patterns.push(s),o.push(s[1])),r=r.#children[c]}return r.#methods.push({[e]:{handler:n,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[A],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=W;let r=this,i=[r],a=l(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===W?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},Ee=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(t,n,r){let i=e(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},K=class extends P{constructor(e={}){super(e),this.router=e.router??new Te({routers:[new we,new Ee]})}},De=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=c(r,e);return i[e]}if(!r)return{};let i=c(r);return i},q=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},Oe=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},J=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ke=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,Ae=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!J.test(a))break;try{i=await n.req.json()}catch{throw new q(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(ke.test(a)||Ae.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await Oe(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new q(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=De(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=()=>new K,Z=(e,t)=>e.json({error:t},400),Q=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},je=X().basePath(`/:key`).get(`/`,async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let r=await e.env.storage.get(t);return e.json({value:r},200)}).post(`/`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?Z(t,`Value is too long. Max length is 1024 characters.`):{value:n}:Z(t,`Value must be a string`):Z(t,`Value is required`)}),async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.set(t,r),e.body(null,204)}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Me=X().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return Z(t,`Messages are required`);if(!Array.isArray(n))return Z(t,`Messages must be an array`);if(n.length===0)return Z(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?Z(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)});new K().route(`/storage`,je).route(`/chat`,Me);async function Ne(e){let t=e?.entrypoint??await b(e?.cwd??process.cwd());if(!t)throw Error(`Unable to locate the entrypoint of the agent. Please specify it manually.`);let n;if(typeof Bun<`u`)n=S(t);else{let{outfile:e}=await y(t);n=S(e)}return ie(n)}export{Ne as create};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blink",
3
- "version": "0.1.40",
3
+ "version": "0.1.42",
4
4
  "description": "Blink is a JavaScript runtime for building and deploying AI agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -21,11 +21,6 @@
21
21
  "types": "./dist/runtime/node.d.ts",
22
22
  "import": "./dist/runtime/node.js",
23
23
  "require": "./dist/runtime/node.cjs"
24
- },
25
- "./tools": {
26
- "types": "./dist/tools.d.ts",
27
- "import": "./dist/tools.js",
28
- "require": "./dist/tools.cjs"
29
24
  }
30
25
  },
31
26
  "files": [
package/dist/tools.cjs DELETED
@@ -1 +0,0 @@
1
- const e=(e,t)=>{let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n};function t(e,n){return{...e(n),with:n=>t(e,n)}}function n(e,t){let n={};for(let[r,i]of Object.entries(t))n[r]=i.with(e);return n}exports.prefix=e,exports.toolWith=t,exports.toolsWith=n;
package/dist/tools.d.cts DELETED
@@ -1,33 +0,0 @@
1
- import { Tool, ToolSet } from "ai";
2
-
3
- //#region src/tools.d.ts
4
-
5
- /**
6
- * prefix all the tools with a given string.
7
- *
8
- * @param tools The tool set to prefix.
9
- * @param prefix The prefix to add to the tools.
10
- * @returns The prefixed tool set.
11
- */
12
- declare const prefix: (tools: ToolSet, prefix: string) => ToolSet;
13
- type ToolWith<CONTEXT, TOOL extends Tool> = TOOL & {
14
- with: (context: CONTEXT) => ToolWith<CONTEXT, TOOL>;
15
- };
16
- /**
17
- * toolWith is a helper function to create a tool with a given context.
18
- *
19
- * @param fn The function to create the tool.
20
- * @param defaultContext The default context to use for the tool.
21
- * @returns The tool with the given context.
22
- */
23
- declare function toolWith<CONTEXT, TOOL extends Tool>(fn: (context: CONTEXT) => TOOL, defaultContext: CONTEXT): ToolWith<CONTEXT, TOOL>;
24
- /**
25
- * toolsWith is a helper function to create a set of tools with a given context.
26
- *
27
- * @param context The context to use for the tools.
28
- * @param tools The tools to create with the given context.
29
- * @returns The set of tools with the given context.
30
- */
31
- declare function toolsWith<CONTEXT, TOOLS extends Record<string, ToolWith<CONTEXT, Tool>>>(context: CONTEXT, tools: TOOLS): Record<string, ToolWith<CONTEXT, Tool>>;
32
- //#endregion
33
- export { ToolWith, prefix, toolWith, toolsWith };
package/dist/tools.d.ts DELETED
@@ -1,33 +0,0 @@
1
- import { Tool, ToolSet } from "ai";
2
-
3
- //#region src/tools.d.ts
4
-
5
- /**
6
- * prefix all the tools with a given string.
7
- *
8
- * @param tools The tool set to prefix.
9
- * @param prefix The prefix to add to the tools.
10
- * @returns The prefixed tool set.
11
- */
12
- declare const prefix: (tools: ToolSet, prefix: string) => ToolSet;
13
- type ToolWith<CONTEXT, TOOL extends Tool> = TOOL & {
14
- with: (context: CONTEXT) => ToolWith<CONTEXT, TOOL>;
15
- };
16
- /**
17
- * toolWith is a helper function to create a tool with a given context.
18
- *
19
- * @param fn The function to create the tool.
20
- * @param defaultContext The default context to use for the tool.
21
- * @returns The tool with the given context.
22
- */
23
- declare function toolWith<CONTEXT, TOOL extends Tool>(fn: (context: CONTEXT) => TOOL, defaultContext: CONTEXT): ToolWith<CONTEXT, TOOL>;
24
- /**
25
- * toolsWith is a helper function to create a set of tools with a given context.
26
- *
27
- * @param context The context to use for the tools.
28
- * @param tools The tools to create with the given context.
29
- * @returns The set of tools with the given context.
30
- */
31
- declare function toolsWith<CONTEXT, TOOLS extends Record<string, ToolWith<CONTEXT, Tool>>>(context: CONTEXT, tools: TOOLS): Record<string, ToolWith<CONTEXT, Tool>>;
32
- //#endregion
33
- export { ToolWith, prefix, toolWith, toolsWith };
package/dist/tools.js DELETED
@@ -1 +0,0 @@
1
- const e=(e,t)=>{let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n};function t(e,n){return{...e(n),with:n=>t(e,n)}}function n(e,t){let n={};for(let[r,i]of Object.entries(t))n[r]=i.with(e);return n}export{e as prefix,t as toolWith,n as toolsWith};