blink 0.1.82 → 0.1.84

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.
Files changed (36) hide show
  1. package/dist/browser/agent/client/index.cjs +8 -8
  2. package/dist/browser/agent/client/index.d.cts +3 -3
  3. package/dist/browser/agent/client/index.d.ts +3 -3
  4. package/dist/browser/agent/client/index.js +8 -8
  5. package/dist/browser/agent/index.browser.d.cts +3 -3
  6. package/dist/browser/agent/index.browser.d.ts +3 -3
  7. package/dist/browser/{chat-B3FNVJ5h.d.cts → chat-DjsYj6b0.d.cts} +11 -1
  8. package/dist/browser/{chat-BpCaFSfj.d.ts → chat-k3skFyU5.d.ts} +11 -1
  9. package/dist/browser/control/index.cjs +1 -1
  10. package/dist/browser/control/index.d.cts +27 -18
  11. package/dist/browser/control/index.d.ts +27 -18
  12. package/dist/browser/control/index.js +1 -1
  13. package/dist/browser/{index-CiKnRuyK.d.cts → index-Cm9mLCpT.d.cts} +3 -3
  14. package/dist/browser/{index-BG1gi0aW.d.ts → index-Ct7PnO7V.d.ts} +3 -3
  15. package/dist/browser/{index.browser-Bivj_NTA.d.cts → index.browser-9_0VjM7D.d.cts} +1 -1
  16. package/dist/browser/{index.browser-CddR1S-T.d.ts → index.browser-DkykGx0f.d.ts} +1 -1
  17. package/dist/browser/react/index.cjs +1 -1
  18. package/dist/browser/react/index.d.cts +3 -3
  19. package/dist/browser/react/index.d.ts +3 -3
  20. package/dist/browser/react/index.js +1 -1
  21. package/dist/cli/{dev-CB_oM-uX.js → dev-FGXkSqqr.js} +11 -10
  22. package/dist/cli/index.js +2 -2
  23. package/dist/cli/{init-BV36CyKQ.js → init-iSl35rQ-.js} +1 -1
  24. package/dist/node/agent/index.node.cjs +39 -39
  25. package/dist/node/agent/index.node.d.cts +2 -2
  26. package/dist/node/agent/index.node.d.ts +2 -2
  27. package/dist/node/agent/index.node.js +39 -39
  28. package/dist/node/build/index.cjs +2 -2
  29. package/dist/node/build/index.js +2 -2
  30. package/dist/node/esm-BK4bGWKt.cjs +1 -1
  31. package/dist/node/esm-Bu_mj8Z9.js +1 -1
  32. package/dist/node/{index.browser-DePGDuoD.d.cts → index.browser-CQKM-pMt.d.ts} +11 -1
  33. package/dist/node/{index.browser-K_A3oWLI.d.ts → index.browser-Chqtpkvq.d.cts} +11 -1
  34. package/dist/node/test.d.cts +2 -2
  35. package/dist/node/test.d.ts +2 -2
  36. package/package.json +4 -1
@@ -1,3 +1,3 @@
1
- import { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, EnsuredChat, MessageOptions, StoreContext } from "../chat-B3FNVJ5h.cjs";
2
- import { ContextFromTools, ExtractUIOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat } from "../index.browser-Bivj_NTA.cjs";
3
- export { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, ContextFromTools, EnsuredChat, ExtractUIOptions, MessageOptions, StoreContext, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat };
1
+ import { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, EnsuredChat, MessageOptions, OtlpContext, StoreContext } from "../chat-DjsYj6b0.cjs";
2
+ import { ContextFromTools, ExtractUIOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat } from "../index.browser-9_0VjM7D.cjs";
3
+ export { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, ContextFromTools, EnsuredChat, ExtractUIOptions, MessageOptions, OtlpContext, StoreContext, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat };
@@ -1,3 +1,3 @@
1
- import { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, EnsuredChat, MessageOptions, StoreContext } from "../chat-BpCaFSfj.js";
2
- import { ContextFromTools, ExtractUIOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat } from "../index.browser-CddR1S-T.js";
3
- export { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, ContextFromTools, EnsuredChat, ExtractUIOptions, MessageOptions, StoreContext, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat };
1
+ import { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, EnsuredChat, MessageOptions, OtlpContext, StoreContext } from "../chat-k3skFyU5.js";
2
+ import { ContextFromTools, ExtractUIOptions, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat } from "../index.browser-DkykGx0f.js";
3
+ export { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, ContextFromTools, EnsuredChat, ExtractUIOptions, MessageOptions, OtlpContext, StoreContext, StreamResponseFormat, StreamResponseFormatHeader, ToolApprovalOutput, ToolSetWithApproval, ToolWithApproval, ToolWithContext, UIEvent, UIHandler, UIOptionSelect, UIOptionSelectValue, UIOptions, UIOptionsSchema, WithUIOptions, isToolApprovalOutput, lastUIOptions, toolWithApproval, tools, withResponseFormat };
@@ -9,6 +9,10 @@ interface Context {
9
9
  * Commonly used for: authentication state, caching external resources, or other state.
10
10
  */
11
11
  readonly store: StoreContext;
12
+ /**
13
+ * Otlp is for forwarding OpenTelemetry traces.
14
+ */
15
+ readonly otlp: OtlpContext;
12
16
  }
13
17
  interface ChatContext {
14
18
  /**
@@ -84,6 +88,12 @@ interface StoreContext {
84
88
  cursor?: string;
85
89
  }>;
86
90
  }
91
+ interface OtlpContext {
92
+ /**
93
+ * traces forwards OpenTelemetry traces.
94
+ */
95
+ traces: (request: Request) => Promise<Response>;
96
+ }
87
97
  //#endregion
88
98
  //#region src/agent/internal/types.d.ts
89
99
  type Promisable<T> = T | Promise<T>;
@@ -126,4 +136,4 @@ type ChatResponse<MESSAGE extends UIMessage> = {
126
136
  } | Response | ReadableStream<InferUIMessageChunk<MESSAGE>> | void;
127
137
  type ChatHandler<MESSAGE extends UIMessage> = (event: ChatEvent<MESSAGE>) => Promisable<ChatResponse<MESSAGE>>;
128
138
  //#endregion
129
- export { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, EnsuredChat, MessageOptions, Promisable, StoreContext };
139
+ export { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, EnsuredChat, MessageOptions, OtlpContext, Promisable, StoreContext };
@@ -9,6 +9,10 @@ interface Context {
9
9
  * Commonly used for: authentication state, caching external resources, or other state.
10
10
  */
11
11
  readonly store: StoreContext;
12
+ /**
13
+ * Otlp is for forwarding OpenTelemetry traces.
14
+ */
15
+ readonly otlp: OtlpContext;
12
16
  }
13
17
  interface ChatContext {
14
18
  /**
@@ -84,6 +88,12 @@ interface StoreContext {
84
88
  cursor?: string;
85
89
  }>;
86
90
  }
91
+ interface OtlpContext {
92
+ /**
93
+ * traces forwards OpenTelemetry traces.
94
+ */
95
+ traces: (request: Request) => Promise<Response>;
96
+ }
87
97
  //#endregion
88
98
  //#region src/agent/internal/types.d.ts
89
99
  type Promisable<T> = T | Promise<T>;
@@ -126,4 +136,4 @@ type ChatResponse<MESSAGE extends UIMessage> = {
126
136
  } | Response | ReadableStream<InferUIMessageChunk<MESSAGE>> | void;
127
137
  type ChatHandler<MESSAGE extends UIMessage> = (event: ChatEvent<MESSAGE>) => Promisable<ChatResponse<MESSAGE>>;
128
138
  //#endregion
129
- export { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, EnsuredChat, MessageOptions, Promisable, StoreContext };
139
+ export { Chat, ChatBehavior, ChatContext, ChatEvent, ChatHandler, ChatResponse, Context, EnsuredChat, MessageOptions, OtlpContext, Promisable, StoreContext };
@@ -1 +1 @@
1
- const e=require(`../cookie-CjFyFt_v.cjs`);var t=(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}},n=Symbol(),r=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,a=e instanceof l?e.raw.headers:e.headers,o=a.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?i(e,{all:n,dot:r}):{}};async function i(e,t){let n=await e.formData();return n?a(n,t):{}}function a(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?o(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(s(n,e,t),delete n[e])}),n}var o=(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]},s=(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])})},c=t=>e.tryDecode(t,e.decodeURIComponent_),l=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?c(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)?c(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 r(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[n](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},u={Stringify:1,BeforeStream:2,Stream:3},d=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},f=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=>f(e,t,!1,r,i))).then(()=>i[0]));return n?d(await o,a):o},p=`text/plain; charset=UTF-8`,m=(e,t)=>({"Content-Type":e,...t}),h=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new l(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,m(p,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,m(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,m(`text/html; charset=UTF-8`,n));return typeof e==`object`?f(e,u.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))},g=`ALL`,_=`all`,ee=[`get`,`post`,`put`,`delete`,`options`,`patch`],v=`Can not add a route since the matcher is already built.`,y=class extends Error{},te=`__COMPOSED_HANDLER`,b=e=>e.text(`404 Not Found`,404),x=(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)},S=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(t={}){let n=[...ee,_];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(g,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 S({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=b;errorHandler=x;route(e,n){let r=this.basePath(e);return n.routes.map(e=>{let i;n.errorHandler===x?i=e.handler:(i=async(r,i)=>(await t([],n.errorHandler)(r,()=>e.handler(r,i))).res,i[te]=e.handler),r.#addRoute(e.method,e.path,i)}),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(g,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,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,n,r,`GET`)))();let a=this.getPath(e,{env:r}),o=this.router.match(i,a),s=new h(e,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=t(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);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,s)}})()}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))})}},C=`[^/]+`,w=`.*`,T=`(?:|/.*)`,E=Symbol(),D=new Set(`.\\+*[^]$()`);function O(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===w||e===T?1:t===w||t===T?-1:e===C?1:t===C?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var k=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw E;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,w]:[``,``,C]:a===`/*`?[``,``,T]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||C;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw E;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==w&&e!==T))throw E;if(i)return;c=this.#children[t]=new k,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!==w&&e!==T))throw E;if(i)return;c=this.#children[a]=new k}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(O),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:D.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(`|`)+`)`}},A=class{#context={varIndex:0};#root=new k;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]}},j=[],M=[/^$/,[],Object.create(null)],N=Object.create(null);function P(e){return N[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function ne(){N=Object.create(null)}function F(e){let t=new A,n=[];if(e.length===0)return M;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)]),j]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===E?new y(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 I(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(P(n).test(t))return[...e[n]]}}var L=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[g]:Object.create(null)},this.#routes={[g]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(v);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[g]).forEach(n=>{e[t][n]=[...e[g][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=P(n);t===g?Object.keys(i).forEach(e=>{i[e][n]||=I(i[e],n)||I(i[g],n)||[]}):i[t][n]||=I(i[t],n)||I(i[g],n)||[],Object.keys(i).forEach(n=>{(t===g||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===g||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===g||t===s)&&(a[s][c]||=[...I(i[s],c)||I(i[g],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){ne();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[g],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],j];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===g;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!==g&&t.push(...Object.keys(r[g]).map(e=>[e,r[g][e]])):(n||=!0,t.push(...i))}),n?F(t):null}},R=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(v);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 y)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]}},z=Object.create(null),B=class{#methods;#children;#patterns;#order=0;#params=z;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 B,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[g],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==z||r&&r!==z))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=z;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===z?{}:{...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])]}},V=class{name=`TrieRouter`;#node;constructor(){this.#node=new B}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)}},H=class extends S{constructor(e={}){super(e),this.router=e.router??new R({routers:[new L,new V]})}},U=(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},W=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})}},G=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},K=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,q=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,J=/^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||!K.test(a))break;try{i=await n.req.json()}catch{throw new W(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(q.test(a)||J.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 G(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new W(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=U(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const 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>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Q=()=>new H,re=Q().get(`/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.context.store.get(t);return e.json({value:r},200)}).post(`/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?X(t,`Value is too long. Max length is 20,000 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.context.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.context.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.context.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),$=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},ie=Q().basePath(`/:key`).post(`/`,async e=>{let{key:t,err:n}=$(e);return n?X(e,n):e.json(await e.env.context.chat.ensure(t),200)}).post(`/sendMessages`,Y(`json`,(e,t)=>({message:e.message,options:e.options})),async e=>{let{key:t,err:n}=$(e);if(n)return X(e,n);let{message:r,options:i}=e.req.valid(`json`);try{await e.env.context.chat.message(t,r,i)}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),ae=new H().route(`/kv`,re).route(`/chat`,ie);exports.api=ae;
1
+ const e=require(`../cookie-CjFyFt_v.cjs`);var t=(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}},n=Symbol(),r=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,a=e instanceof l?e.raw.headers:e.headers,o=a.get(`Content-Type`);return o?.startsWith(`multipart/form-data`)||o?.startsWith(`application/x-www-form-urlencoded`)?i(e,{all:n,dot:r}):{}};async function i(e,t){let n=await e.formData();return n?a(n,t):{}}function a(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?o(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(s(n,e,t),delete n[e])}),n}var o=(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]},s=(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])})},c=t=>e.tryDecode(t,e.decodeURIComponent_),l=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?c(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)?c(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 r(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[n](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},u={Stringify:1,BeforeStream:2,Stream:3},d=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},f=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=>f(e,t,!1,r,i))).then(()=>i[0]));return n?d(await o,a):o},p=`text/plain; charset=UTF-8`,m=(e,t)=>({"Content-Type":e,...t}),h=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new l(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,m(p,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,m(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,m(`text/html; charset=UTF-8`,n));return typeof e==`object`?f(e,u.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))},g=`ALL`,_=`all`,ee=[`get`,`post`,`put`,`delete`,`options`,`patch`],v=`Can not add a route since the matcher is already built.`,y=class extends Error{},te=`__COMPOSED_HANDLER`,b=e=>e.text(`404 Not Found`,404),x=(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)},S=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(t={}){let n=[...ee,_];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(g,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 S({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=b;errorHandler=x;route(e,n){let r=this.basePath(e);return n.routes.map(e=>{let i;n.errorHandler===x?i=e.handler:(i=async(r,i)=>(await t([],n.errorHandler)(r,()=>e.handler(r,i))).res,i[te]=e.handler),r.#addRoute(e.method,e.path,i)}),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(g,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,n,r,i){if(i===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,n,r,`GET`)))();let a=this.getPath(e,{env:r}),o=this.router.match(i,a),s=new h(e,{path:a,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#notFoundHandler});if(o[0].length===1){let e;try{e=o[0][0][0][0](s,async()=>{s.res=await this.#notFoundHandler(s)})}catch(e){return this.#handleError(e,s)}return e instanceof Promise?e.then(e=>e||(s.finalized?s.res:this.#notFoundHandler(s))).catch(e=>this.#handleError(e,s)):e??this.#notFoundHandler(s)}let c=t(o[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await c(s);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,s)}})()}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))})}},C=`[^/]+`,w=`.*`,T=`(?:|/.*)`,E=Symbol(),D=new Set(`.\\+*[^]$()`);function O(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===w||e===T?1:t===w||t===T?-1:e===C?1:t===C?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var k=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw E;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,w]:[``,``,C]:a===`/*`?[``,``,T]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||C;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw E;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==w&&e!==T))throw E;if(i)return;c=this.#children[t]=new k,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!==w&&e!==T))throw E;if(i)return;c=this.#children[a]=new k}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(O),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:D.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(`|`)+`)`}},A=class{#context={varIndex:0};#root=new k;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]}},j=[],M=[/^$/,[],Object.create(null)],N=Object.create(null);function P(e){return N[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function ne(){N=Object.create(null)}function F(e){let t=new A,n=[];if(e.length===0)return M;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)]),j]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===E?new y(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 I(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(P(n).test(t))return[...e[n]]}}var L=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[g]:Object.create(null)},this.#routes={[g]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(v);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[g]).forEach(n=>{e[t][n]=[...e[g][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=P(n);t===g?Object.keys(i).forEach(e=>{i[e][n]||=I(i[e],n)||I(i[g],n)||[]}):i[t][n]||=I(i[t],n)||I(i[g],n)||[],Object.keys(i).forEach(n=>{(t===g||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===g||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===g||t===s)&&(a[s][c]||=[...I(i[s],c)||I(i[g],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){ne();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[g],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],j];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===g;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!==g&&t.push(...Object.keys(r[g]).map(e=>[e,r[g][e]])):(n||=!0,t.push(...i))}),n?F(t):null}},R=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(v);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 y)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]}},z=Object.create(null),B=class{#methods;#children;#patterns;#order=0;#params=z;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 B,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[g],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==z||r&&r!==z))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=z;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===z?{}:{...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])]}},V=class{name=`TrieRouter`;#node;constructor(){this.#node=new B}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)}},H=class extends S{constructor(e={}){super(e),this.router=e.router??new R({routers:[new L,new V]})}},U=(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},W=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})}},G=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},K=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,q=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,J=/^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||!K.test(a))break;try{i=await n.req.json()}catch{throw new W(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(q.test(a)||J.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 G(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new W(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=U(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const 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>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Q=()=>new H,re=Q().get(`/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.context.store.get(t);return e.json({value:r},200)}).post(`/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?X(t,`Value is too long. Max length is 20,000 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.context.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.context.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.context.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),$=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},ie=Q().basePath(`/:key`).post(`/`,async e=>{let{key:t,err:n}=$(e);return n?X(e,n):e.json(await e.env.context.chat.ensure(t),200)}).post(`/sendMessages`,Y(`json`,(e,t)=>({message:e.message,options:e.options})),async e=>{let{key:t,err:n}=$(e);if(n)return X(e,n);let{message:r,options:i}=e.req.valid(`json`);try{await e.env.context.chat.message(t,r,i)}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),ae=Q().post(`/v1/traces`,async e=>e.env.context.otlp.traces(e.req.raw)),oe=new H().route(`/kv`,re).route(`/chat`,ie).route(`/otlp`,ae);exports.api=oe;
@@ -1,4 +1,4 @@
1
- import { Context, MessageOptions } from "../chat-B3FNVJ5h.cjs";
1
+ import { Context, MessageOptions } from "../chat-DjsYj6b0.cjs";
2
2
  import { UIMessage } from "ai";
3
3
  import * as hono_types0 from "hono/types";
4
4
  import * as hono_utils_http_status0 from "hono/utils/http-status";
@@ -62,11 +62,9 @@ declare const api: hono_hono_base0.HonoBase<{
62
62
  key: string;
63
63
  };
64
64
  };
65
- output: {
66
- error: string;
67
- };
68
- outputFormat: "json";
69
- status: 400;
65
+ output: null;
66
+ outputFormat: "body";
67
+ status: 204;
70
68
  } | {
71
69
  input: {
72
70
  json: {
@@ -77,9 +75,11 @@ declare const api: hono_hono_base0.HonoBase<{
77
75
  key: string;
78
76
  };
79
77
  };
80
- output: null;
81
- outputFormat: "body";
82
- status: 204;
78
+ output: {
79
+ error: string;
80
+ };
81
+ outputFormat: "json";
82
+ status: 400;
83
83
  };
84
84
  };
85
85
  } & {
@@ -161,11 +161,9 @@ declare const api: hono_hono_base0.HonoBase<{
161
161
  key: string;
162
162
  };
163
163
  };
164
- output: {
165
- error: string;
166
- };
167
- outputFormat: "json";
168
- status: 400;
164
+ output: null;
165
+ outputFormat: "body";
166
+ status: 204;
169
167
  } | {
170
168
  input: {
171
169
  json: {
@@ -177,11 +175,22 @@ declare const api: hono_hono_base0.HonoBase<{
177
175
  key: string;
178
176
  };
179
177
  };
180
- output: null;
181
- outputFormat: "body";
182
- status: 204;
178
+ output: {
179
+ error: string;
180
+ };
181
+ outputFormat: "json";
182
+ status: 400;
183
+ };
184
+ };
185
+ }, "/chat"> | hono_types0.MergeSchemaPath<{
186
+ "/v1/traces": {
187
+ $post: {
188
+ input: {};
189
+ output: {};
190
+ outputFormat: string;
191
+ status: hono_utils_http_status0.StatusCode;
183
192
  };
184
193
  };
185
- }, "/chat">, "/">;
194
+ }, "/otlp">, "/">;
186
195
  //#endregion
187
196
  export { api };
@@ -1,4 +1,4 @@
1
- import { Context, MessageOptions } from "../chat-BpCaFSfj.js";
1
+ import { Context, MessageOptions } from "../chat-k3skFyU5.js";
2
2
  import { UIMessage } from "ai";
3
3
  import * as hono_types0 from "hono/types";
4
4
  import * as hono_utils_http_status0 from "hono/utils/http-status";
@@ -62,11 +62,9 @@ declare const api: hono_hono_base0.HonoBase<{
62
62
  key: string;
63
63
  };
64
64
  };
65
- output: {
66
- error: string;
67
- };
68
- outputFormat: "json";
69
- status: 400;
65
+ output: null;
66
+ outputFormat: "body";
67
+ status: 204;
70
68
  } | {
71
69
  input: {
72
70
  json: {
@@ -77,9 +75,11 @@ declare const api: hono_hono_base0.HonoBase<{
77
75
  key: string;
78
76
  };
79
77
  };
80
- output: null;
81
- outputFormat: "body";
82
- status: 204;
78
+ output: {
79
+ error: string;
80
+ };
81
+ outputFormat: "json";
82
+ status: 400;
83
83
  };
84
84
  };
85
85
  } & {
@@ -161,11 +161,9 @@ declare const api: hono_hono_base0.HonoBase<{
161
161
  key: string;
162
162
  };
163
163
  };
164
- output: {
165
- error: string;
166
- };
167
- outputFormat: "json";
168
- status: 400;
164
+ output: null;
165
+ outputFormat: "body";
166
+ status: 204;
169
167
  } | {
170
168
  input: {
171
169
  json: {
@@ -177,11 +175,22 @@ declare const api: hono_hono_base0.HonoBase<{
177
175
  key: string;
178
176
  };
179
177
  };
180
- output: null;
181
- outputFormat: "body";
182
- status: 204;
178
+ output: {
179
+ error: string;
180
+ };
181
+ outputFormat: "json";
182
+ status: 400;
183
+ };
184
+ };
185
+ }, "/chat"> | hono_types0.MergeSchemaPath<{
186
+ "/v1/traces": {
187
+ $post: {
188
+ input: {};
189
+ output: {};
190
+ outputFormat: string;
191
+ status: hono_utils_http_status0.StatusCode;
183
192
  };
184
193
  };
185
- }, "/chat">, "/">;
194
+ }, "/otlp">, "/">;
186
195
  //#endregion
187
196
  export { api };
@@ -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-CrDJkqg5.js";var f=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},p=Symbol(),m=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof v?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&&(te(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]},te=(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=>d(e,t),v=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)?_(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)?_(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 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}},y={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}),C=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 v(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,y.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},w=`ALL`,T=`all`,E=[`get`,`post`,`put`,`delete`,`options`,`patch`],D=`Can not add a route since the matcher is already built.`,O=class extends Error{},re=`__COMPOSED_HANDLER`,ie=e=>e.text(`404 Not Found`,404),k=(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)},A=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...E,T];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(w,this.#path,e)}),this);let{strict:i,...a}=e;Object.assign(this,a),this.getPath=i??!0?e.getPath??n:r}#clone(){let e=new A({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=ie;errorHandler=k;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===k?r=e.handler:(r=async(n,r)=>(await f([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[re]=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(w,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 C(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=f(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${s(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},j=`[^/]+`,M=`.*`,N=`(?:|/.*)`,P=Symbol(),ae=new Set(`.\\+*[^]$()`);function oe(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===M||e===N?1:t===M||t===N?-1:e===j?1:t===j?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var F=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw P;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,M]:[``,``,j]:a===`/*`?[``,``,N]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||j;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw P;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==M&&e!==N))throw P;if(i)return;c=this.#children[t]=new F,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!==M&&e!==N))throw P;if(i)return;c=this.#children[a]=new F}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(oe),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ae.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(`|`)+`)`}},se=class{#context={varIndex:0};#root=new F;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]}},I=[],L=[/^$/,[],Object.create(null)],R=Object.create(null);function z(e){return R[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function B(){R=Object.create(null)}function V(e){let t=new se,n=[];if(e.length===0)return L;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)]),I]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===P?new O(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 H(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(z(n).test(t))return[...e[n]]}}var U=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[w]:Object.create(null)},this.#routes={[w]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(D);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[w]).forEach(n=>{e[t][n]=[...e[w][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=z(n);t===w?Object.keys(i).forEach(e=>{i[e][n]||=H(i[e],n)||H(i[w],n)||[]}):i[t][n]||=H(i[t],n)||H(i[w],n)||[],Object.keys(i).forEach(n=>{(t===w||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===w||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===w||t===s)&&(a[s][c]||=[...H(i[s],c)||H(i[w],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){B();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[w],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],I];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===w;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==w&&t.push(...Object.keys(r[w]).map(e=>[e,r[w][e]])):(n||=!0,t.push(...i))}),n?V(t):null}},W=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(D);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 O)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]}},G=Object.create(null),K=class{#methods;#children;#patterns;#order=0;#params=G;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 K,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[w],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==G||r&&r!==G))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=G;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===G?{}:{...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])]}},ce=class{name=`TrieRouter`;#node;constructor(){this.#node=new K}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)}},q=class extends A{constructor(e={}){super(e),this.router=e.router??new W({routers:[new U,new ce]})}},le=(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},J=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})}},ue=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},de=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,fe=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,pe=/^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||!de.test(a))break;try{i=await n.req.json()}catch{throw new J(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(fe.test(a)||pe.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 ue(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new J(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=le(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const 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>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Q=()=>new q,me=Q().get(`/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.context.store.get(t);return e.json({value:r},200)}).post(`/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?X(t,`Value is too long. Max length is 20,000 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.context.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.context.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.context.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),$=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},he=Q().basePath(`/:key`).post(`/`,async e=>{let{key:t,err:n}=$(e);return n?X(e,n):e.json(await e.env.context.chat.ensure(t),200)}).post(`/sendMessages`,Y(`json`,(e,t)=>({message:e.message,options:e.options})),async e=>{let{key:t,err:n}=$(e);if(n)return X(e,n);let{message:r,options:i}=e.req.valid(`json`);try{await e.env.context.chat.message(t,r,i)}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),ge=new q().route(`/kv`,me).route(`/chat`,he);export{ge as api};
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-CrDJkqg5.js";var f=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},p=Symbol(),m=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof 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=e=>d(e,t),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(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 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(e={}){let t=[...ae,ie];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(C,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 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(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(C,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 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=(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))})}},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(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(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[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(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])]}},le=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 k{constructor(e={}){super(e),this.router=e.router??new U({routers:[new H,new le]})}},ue=(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})}},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=(e,t)=>e.json({error:t},400),X=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}},Z=()=>new K,he=Z().get(`/:key`,async e=>{let{key:t,err:n}=X(e);if(n)return Y(e,n);let r=await e.env.context.store.get(t);return e.json({value:r},200)}).post(`/:key`,J(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>2e4?Y(t,`Value is too long. Max length is 20,000 characters.`):{value:n}:Y(t,`Value must be a string`):Y(t,`Value is required`)}),async e=>{let{key:t,err:n}=X(e);if(n)return Y(e,n);let{value:r}=e.req.valid(`json`);return await e.env.context.store.set(t,r),e.body(null,204)}).delete(`/:key`,async e=>{let{key:t,err:n}=X(e);return n?Y(e,n):(await e.env.context.store.delete(t),e.body(null,204))}).get(`/`,async e=>{let{cursor:t,limit:n,prefix:r}=e.req.query(),{entries:i,cursor:a}=await e.env.context.store.list(r,{cursor:t?String(t):void 0,limit:n?Number(n):100});return e.json({entries:i,cursor:a})}),Q=e=>{let t=e.req.param(`key`);return t?t.length>475?{key:t,err:`Key is too long. Max length is 475 characters.`}:{key:t}:{key:t,err:`Key is required`}},ge=Z().basePath(`/:key`).post(`/`,async e=>{let{key:t,err:n}=Q(e);return n?Y(e,n):e.json(await e.env.context.chat.ensure(t),200)}).post(`/sendMessages`,J(`json`,(e,t)=>({message:e.message,options:e.options})),async e=>{let{key:t,err:n}=Q(e);if(n)return Y(e,n);let{message:r,options:i}=e.req.valid(`json`);try{await e.env.context.chat.message(t,r,i)}catch(t){return Y(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),$=Z().post(`/v1/traces`,async e=>e.env.context.otlp.traces(e.req.raw)),_e=new K().route(`/kv`,he).route(`/chat`,ge).route(`/otlp`,$);export{_e as api};
@@ -1,5 +1,5 @@
1
- import { Chat } from "./chat-B3FNVJ5h.cjs";
2
- import { UIOptions, UIOptionsSchema } from "./index.browser-Bivj_NTA.cjs";
1
+ import { Chat } from "./chat-DjsYj6b0.cjs";
2
+ import { UIOptions, UIOptionsSchema } from "./index.browser-9_0VjM7D.cjs";
3
3
  import { UIMessage, UIMessageChunk } from "ai";
4
4
 
5
5
  //#region src/agent/client/index.d.ts
@@ -40,7 +40,7 @@ declare class Client {
40
40
  selectedOptions?: UIOptions;
41
41
  }, options?: {
42
42
  signal?: AbortSignal;
43
- }): Promise<UIOptionsSchema>;
43
+ }): Promise<UIOptionsSchema | undefined>;
44
44
  /**
45
45
  * health simply returns a 200 response.
46
46
  * This is used to check if the agent is running.
@@ -1,5 +1,5 @@
1
- import { Chat } from "./chat-BpCaFSfj.js";
2
- import { UIOptions, UIOptionsSchema } from "./index.browser-CddR1S-T.js";
1
+ import { Chat } from "./chat-k3skFyU5.js";
2
+ import { UIOptions, UIOptionsSchema } from "./index.browser-DkykGx0f.js";
3
3
  import { UIMessage, UIMessageChunk } from "ai";
4
4
 
5
5
  //#region src/agent/client/index.d.ts
@@ -40,7 +40,7 @@ declare class Client {
40
40
  selectedOptions?: UIOptions;
41
41
  }, options?: {
42
42
  signal?: AbortSignal;
43
- }): Promise<UIOptionsSchema>;
43
+ }): Promise<UIOptionsSchema | undefined>;
44
44
  /**
45
45
  * health simply returns a 200 response.
46
46
  * This is used to check if the agent is running.
@@ -1,4 +1,4 @@
1
- import { Promisable } from "./chat-B3FNVJ5h.cjs";
1
+ import { Promisable } from "./chat-DjsYj6b0.cjs";
2
2
  import { InferToolInput, InferToolOutput, Tool, ToolSet, UIMessage } from "ai";
3
3
 
4
4
  //#region src/agent/ui.d.ts
@@ -1,4 +1,4 @@
1
- import { Promisable } from "./chat-BpCaFSfj.js";
1
+ import { Promisable } from "./chat-k3skFyU5.js";
2
2
  import { InferToolInput, InferToolOutput, Tool, ToolSet, UIMessage } from "ai";
3
3
 
4
4
  //#region src/agent/ui.d.ts
@@ -1 +1 @@
1
- const e=require(`../index.browser-MaMFf-YB.cjs`);let t=require(`react`);t=e.__toESM(t);function n({agent:n,capabilities:r,messages:i}){let[a,o]=(0,t.useState)(void 0),[s,c]=(0,t.useState)(!0),[l,u]=(0,t.useState)(void 0),d=(0,t.useRef)(l);(0,t.useEffect)(()=>{d.current=l},[l]);let[f,p]=(0,t.useState)(()=>e.lastUIOptions(i));(0,t.useEffect)(()=>{p(t=>{let n=e.lastUIOptions(i);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[i]);let[m,h]=(0,t.useState)(void 0),g=(0,t.useCallback)((e,t)=>{if(!d.current)return!1;let n=d.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,t.useCallback)(e=>{h(t=>{let n={...f,...t,...e};for(let[e,t]of Object.entries(n))g(e,t)||delete n[e];for(let[e,t]of Object.entries(d.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[f,g]);(0,t.useEffect)(()=>{if(!f&&!l){h(void 0);return}_()},[f,l,_]);let v=(0,t.useRef)(void 0),y=(0,t.useRef)(void 0);(0,t.useEffect)(()=>{n!==y.current&&(y.current=n,u(void 0),h(void 0),o(void 0),c(!0),v.current=void 0)},[n]),(0,t.useEffect)(()=>{if(r&&!r.ui||!n){u(void 0),h(void 0),o(void 0),v.current=void 0;return}let e=m?JSON.stringify(m):``;if(v.current===e){c(!1),o(void 0);return}let t=new AbortController;return c(!0),o(void 0),n.ui(m?{selectedOptions:m}:{},{signal:t.signal}).then(n=>{t.signal.aborted||(u(e=>JSON.stringify(e)===JSON.stringify(n)?e:n),v.current=e)}).catch(e=>{t.signal.aborted||o(e instanceof Error?e:Error(String(e)))}).finally(()=>{c(!1)}),()=>{t.abort()}},[n,r,m]);let b=(0,t.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:l,options:m,setOption:b,loading:s,error:a}}exports.useOptions=n;
1
+ const e=require(`../index.browser-MaMFf-YB.cjs`);let t=require(`react`);t=e.__toESM(t);function n({agent:n,capabilities:r,messages:i}){let[a,o]=(0,t.useState)(void 0),[s,c]=(0,t.useState)(!0),[l,u]=(0,t.useState)(void 0),d=(0,t.useRef)(l);(0,t.useEffect)(()=>{d.current=l},[l]);let[f,p]=(0,t.useState)(()=>e.lastUIOptions(i));(0,t.useEffect)(()=>{p(t=>{let n=e.lastUIOptions(i);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[i]);let[m,h]=(0,t.useState)(void 0),g=(0,t.useCallback)((e,t)=>{if(!d.current)return!1;let n=d.current[e];return n?n.values.some(e=>e.id===t):!1},[]),_=(0,t.useCallback)(e=>{h(t=>{let n={...f,...t,...e};for(let[e,t]of Object.entries(n))g(e,t)||delete n[e];for(let[e,t]of Object.entries(d.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[f,g]);(0,t.useEffect)(()=>{if(!f&&!l){h(void 0);return}_()},[f,l,_]);let v=(0,t.useRef)(void 0),y=(0,t.useRef)(void 0);(0,t.useEffect)(()=>{n!==y.current&&(y.current=n,u(void 0),h(void 0),o(void 0),c(!0),v.current=void 0)},[n]),(0,t.useEffect)(()=>{if(r&&!r.ui||!n){u(void 0),h(void 0),o(void 0),v.current=void 0;return}let e=m?JSON.stringify(m):``;if(v.current===e){c(!1),o(void 0);return}let t=new AbortController;return c(!0),o(void 0),n.ui(m?{selectedOptions:m}:{},{signal:t.signal}).then(n=>{if(!n){u(void 0);return}t.signal.aborted||(u(e=>JSON.stringify(e)===JSON.stringify(n)?e:n),v.current=e)}).catch(e=>{t.signal.aborted||o(e instanceof Error?e:Error(String(e)))}).finally(()=>{c(!1)}),()=>{t.abort()}},[n,r,m]);let b=(0,t.useCallback)((e,t)=>{_({[e]:t})},[_]);return{schema:l,options:m,setOption:b,loading:s,error:a}}exports.useOptions=n;
@@ -1,6 +1,6 @@
1
- import "../chat-B3FNVJ5h.cjs";
2
- import { UIOptions, UIOptionsSchema } from "../index.browser-Bivj_NTA.cjs";
3
- import { CapabilitiesResponse, Client } from "../index-CiKnRuyK.cjs";
1
+ import "../chat-DjsYj6b0.cjs";
2
+ import { UIOptions, UIOptionsSchema } from "../index.browser-9_0VjM7D.cjs";
3
+ import { CapabilitiesResponse, Client } from "../index-Cm9mLCpT.cjs";
4
4
  import { UIMessage } from "ai";
5
5
 
6
6
  //#region src/react/use-options.d.ts
@@ -1,6 +1,6 @@
1
- import "../chat-BpCaFSfj.js";
2
- import { UIOptions, UIOptionsSchema } from "../index.browser-CddR1S-T.js";
3
- import { CapabilitiesResponse, Client } from "../index-BG1gi0aW.js";
1
+ import "../chat-k3skFyU5.js";
2
+ import { UIOptions, UIOptionsSchema } from "../index.browser-DkykGx0f.js";
3
+ import { CapabilitiesResponse, Client } from "../index-Ct7PnO7V.js";
4
4
  import { UIMessage } from "ai";
5
5
 
6
6
  //#region src/react/use-options.d.ts
@@ -1 +1 @@
1
- import{lastUIOptions as e}from"../index.browser-BmUS9RoH.js";import{useCallback as t,useEffect as n,useRef as r,useState as i}from"react";function a({agent:a,capabilities:o,messages:s}){let[c,l]=i(void 0),[u,d]=i(!0),[f,p]=i(void 0),m=r(f);n(()=>{m.current=f},[f]);let[h,g]=i(()=>e(s));n(()=>{g(t=>{let n=e(s);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[s]);let[_,v]=i(void 0),y=t((e,t)=>{if(!m.current)return!1;let n=m.current[e];return n?n.values.some(e=>e.id===t):!1},[]),b=t(e=>{v(t=>{let n={...h,...t,...e};for(let[e,t]of Object.entries(n))y(e,t)||delete n[e];for(let[e,t]of Object.entries(m.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[h,y]);n(()=>{if(!h&&!f){v(void 0);return}b()},[h,f,b]);let x=r(void 0),S=r(void 0);n(()=>{a!==S.current&&(S.current=a,p(void 0),v(void 0),l(void 0),d(!0),x.current=void 0)},[a]),n(()=>{if(o&&!o.ui||!a){p(void 0),v(void 0),l(void 0),x.current=void 0;return}let e=_?JSON.stringify(_):``;if(x.current===e){d(!1),l(void 0);return}let t=new AbortController;return d(!0),l(void 0),a.ui(_?{selectedOptions:_}:{},{signal:t.signal}).then(n=>{t.signal.aborted||(p(e=>JSON.stringify(e)===JSON.stringify(n)?e:n),x.current=e)}).catch(e=>{t.signal.aborted||l(e instanceof Error?e:Error(String(e)))}).finally(()=>{d(!1)}),()=>{t.abort()}},[a,o,_]);let C=t((e,t)=>{b({[e]:t})},[b]);return{schema:f,options:_,setOption:C,loading:u,error:c}}export{a as useOptions};
1
+ import{lastUIOptions as e}from"../index.browser-BmUS9RoH.js";import{useCallback as t,useEffect as n,useRef as r,useState as i}from"react";function a({agent:a,capabilities:o,messages:s}){let[c,l]=i(void 0),[u,d]=i(!0),[f,p]=i(void 0),m=r(f);n(()=>{m.current=f},[f]);let[h,g]=i(()=>e(s));n(()=>{g(t=>{let n=e(s);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[s]);let[_,v]=i(void 0),y=t((e,t)=>{if(!m.current)return!1;let n=m.current[e];return n?n.values.some(e=>e.id===t):!1},[]),b=t(e=>{v(t=>{let n={...h,...t,...e};for(let[e,t]of Object.entries(n))y(e,t)||delete n[e];for(let[e,t]of Object.entries(m.current??{}))!n[e]&&t.defaultValue!==void 0&&(n[e]=t.defaultValue);return JSON.stringify(n)===JSON.stringify(t)?t:n})},[h,y]);n(()=>{if(!h&&!f){v(void 0);return}b()},[h,f,b]);let x=r(void 0),S=r(void 0);n(()=>{a!==S.current&&(S.current=a,p(void 0),v(void 0),l(void 0),d(!0),x.current=void 0)},[a]),n(()=>{if(o&&!o.ui||!a){p(void 0),v(void 0),l(void 0),x.current=void 0;return}let e=_?JSON.stringify(_):``;if(x.current===e){d(!1),l(void 0);return}let t=new AbortController;return d(!0),l(void 0),a.ui(_?{selectedOptions:_}:{},{signal:t.signal}).then(n=>{if(!n){p(void 0);return}t.signal.aborted||(p(e=>JSON.stringify(e)===JSON.stringify(n)?e:n),x.current=e)}).catch(e=>{t.signal.aborted||l(e instanceof Error?e:Error(String(e)))}).finally(()=>{d(!1)}),()=>{t.abort()}},[a,o,_]);let C=t((e,t)=>{b({[e]:t})},[b]);return{schema:f,options:_,setOption:C,loading:u,error:c}}export{a as useOptions};