blink 0.1.31 → 0.1.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/test.cjs CHANGED
@@ -1 +1 @@
1
- const e=require(`./cookie-B3SvZDri.cjs`);let t=require(`fs/promises`);t=e.__toESM(t);let n=require(`path`);n=e.__toESM(n);async function r(e,{outdir:t}={}){t||=await a(e);let r=(0,n.join)(t,`agent.js`),i=c(),o=await i.build({...s,entryPoints:[e],outfile:r});if(o.errors.length>0)throw Error(`Failed to build agent!`);return{outfile:r}}async function i(e){let r=await o(e,`package.json`);if(!r)throw Error(`No package.json found in ${e}`);let i=JSON.parse(await(0,t.readFile)(r,`utf-8`)),a=i.main;if(!a)throw Error(`"main" is not set in ${(0,n.relative)(process.cwd(),r)}. It should be set to the entrypoint of your agent.`);let s=(0,n.join)((0,n.dirname)(r),a),c=await(0,t.stat)(s);if(!c.isFile())throw Error(`${s} is not a file.`);return s}async function a(e){let r=await o(e,`node_modules`);if(!r){let r=await(0,t.stat)(e);return r.isDirectory()?(0,n.join)(e,`.blink`):(0,n.join)((0,n.dirname)(e),`.blink`)}let i=(0,n.join)(r,`.blink`);return await(0,t.mkdir)(i,{recursive:!0}),i}async function o(e,r){let i=e;for(;i!==(0,n.dirname)(i);){let e=(0,n.join)(i,r);try{return await(0,t.stat)(e),e}catch{}i=(0,n.dirname)(i)}}const s={bundle:!0,format:`cjs`,platform:`node`,target:`node18`,sourcemap:`inline`},c=()=>{try{return require(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};function l(e){let t=require(e);if(typeof t!=`object`)throw Error(`The module at ${e} must export an object.`);let n=t.default;if(typeof n!=`object`)throw Error(`The module at ${e} must export an object.`);if(!n.version)throw Error(`The module at ${e} must export a "version" property.`);if(typeof n.fetch!=`function`)throw Error(`The module at ${e} must export a "fetch" function.`);return n}function u(e){return new d(`http://agent.local`,{fetch:async(t,n)=>e.fetch(new Request(t,{...n,duplex:n.body?`half`:void 0}))})}var d=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/sendMessages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendWebhook(e){let t=new URL(e.url),n=new Headers(e.headers);return this.fetch(`${this.baseUrl}/webhook?${t.searchParams.toString()}`,{method:e.method,headers:n,body:e.body})}},f=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},p=Symbol(),m=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof y?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?h(e,{all:n,dot:r}):{}};async function h(e,t){let n=await e.formData();return n?g(n,t):{}}function g(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?ee(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(_(n,e,t),delete n[e])}),n}var ee=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},_=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},v=t=>e.tryDecode(t,e.decodeURIComponent_),y=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?v(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?v(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(t){return e.getQueryParam(this.url,t)}queries(t){return e.getQueryParams(this.url,t)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await m(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[p](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},te={Stringify:1,BeforeStream:2,Stream:3},ne=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},b=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>b(e,t,!1,r,i))).then(()=>i[0]));return n?ne(await o,a):o},x=`text/plain; charset=UTF-8`,S=(e,t)=>({"Content-Type":e,...t}),re=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new y(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,S(x,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,S(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,S(`text/html; charset=UTF-8`,n));return typeof e==`object`?b(e,te.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},C=`ALL`,ie=`all`,ae=[`get`,`post`,`put`,`delete`,`options`,`patch`],w=`Can not add a route since the matcher is already built.`,T=class extends Error{},E=`__COMPOSED_HANDLER`,D=e=>e.text(`404 Not Found`,404),O=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},k=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(t={}){let n=[...ae,ie];n.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(C,this.#path,e)}),this);let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??e.getPath:e.getPathNoStrict}#clone(){let e=new k({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=D;errorHandler=O;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===O?r=e.handler:(r=async(n,r)=>(await f([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[E]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(t){let n=this.#clone();return n._basePath=e.mergePath(this._basePath,t),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(t,n,r){let i,a;r&&(typeof r==`function`?a=r:(a=r.optionHandler,i=r.replaceRequest===!1?e=>e:r.replaceRequest));let o=a?e=>{let t=a(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};i||=(()=>{let n=e.mergePath(this._basePath,t),r=n===`/`?0:n.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(r)||`/`,new Request(t,e)}})();let s=async(e,t)=>{let r=await n(i(e.req.raw),...o(e));if(r)return r;await t()};return this.#addRoute(C,e.mergePath(t,`*`),s),this}#addRoute(t,n,r){t=t.toUpperCase(),n=e.mergePath(this._basePath,n);let i={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,i]),this.routes.push(i)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new re(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=f(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(t,n,r,i)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,i):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${e.mergePath(`/`,t)}`,n),r,i));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},A=`[^/]+`,j=`.*`,M=`(?:|/.*)`,N=Symbol(),oe=new Set(`.\\+*[^]$()`);function se(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===j||e===M?1:t===j||t===M?-1:e===A?1:t===A?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var P=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw N;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,j]:[``,``,A]:a===`/*`?[``,``,M]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||A;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw N;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==j&&e!==M))throw N;if(i)return;c=this.#children[t]=new P,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==j&&e!==M))throw N;if(i)return;c=this.#children[a]=new P}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(se),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:oe.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},ce=class{#context={varIndex:0};#root=new P;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},F=[],I=[/^$/,[],Object.create(null)],L=Object.create(null);function R(e){return L[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function z(){L=Object.create(null)}function B(e){let t=new ce,n=[];if(e.length===0)return I;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),F]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===N?new T(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function V(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(R(n).test(t))return[...e[n]]}}var H=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[C]:Object.create(null)},this.#routes={[C]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(w);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[C]).forEach(n=>{e[t][n]=[...e[C][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=R(n);t===C?Object.keys(i).forEach(e=>{i[e][n]||=V(i[e],n)||V(i[C],n)||[]}):i[t][n]||=V(i[t],n)||V(i[C],n)||[],Object.keys(i).forEach(n=>{(t===C||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===C||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e.checkOptionalParameter(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===C||t===s)&&(a[s][c]||=[...V(i[s],c)||V(i[C],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){z();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[C],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],F];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===C;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==C&&t.push(...Object.keys(r[C]).map(e=>[e,r[C][e]])):(n||=!0,t.push(...i))}),n?B(t):null}},U=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(w);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof T)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(t,n,r){this.#order=++this.#order;let i=this,a=e.splitRoutingPath(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=e.getPattern(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#children){i=i.#children[c],s&&o.push(s[1]);continue}i.#children[c]=new G,s&&(i.#patterns.push(s),o.push(s[1])),i=i.#children[c]}return i.#methods.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),i}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[C],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(t,n){let r=[];this.#params=W;let i=this,a=[i],o=e.splitPath(n),s=[];for(let e=0,n=o.length;e<n;e++){let i=o[e],c=e===n-1,l=[];for(let n=0,u=a.length;n<u;n++){let u=a[n],d=u.#children[i];d&&(d.#params=u.#params,c?(d.#children[`*`]&&r.push(...this.#getHandlerSets(d.#children[`*`],t,u.#params)),r.push(...this.#getHandlerSets(d,t,u.#params))):l.push(d));for(let n=0,a=u.#patterns.length;n<a;n++){let a=u.#patterns[n],d=u.#params===W?{}:{...u.#params};if(a===`*`){let e=u.#children[`*`];e&&(r.push(...this.#getHandlerSets(e,t,u.#params)),e.#params=d,l.push(e));continue}let[f,p,m]=a;if(!i&&!(m instanceof RegExp))continue;let h=u.#children[f],g=o.slice(e).join(`/`);if(m instanceof RegExp){let e=m.exec(g);if(e){if(d[p]=e[0],r.push(...this.#getHandlerSets(h,t,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let t=e[0].match(/\//)?.length??0,n=s[t]||=[];n.push(h)}continue}}(m===!0||m.test(i))&&(d[p]=i,c?(r.push(...this.#getHandlerSets(h,t,d,u.#params)),h.#children[`*`]&&r.push(...this.#getHandlerSets(h.#children[`*`],t,d,u.#params))):(h.#params=d,l.push(h)))}}a=l.concat(s.shift()??[])}return r.length>1&&r.sort((e,t)=>e.score-t.score),[r.map(({handler:e,params:t})=>[e,t])]}},le=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(t,n,r){let i=e.checkOptionalParameter(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},K=class extends k{constructor(e={}){super(e),this.router=e.router??new U({routers:[new H,new le]})}},ue=(t,n,r)=>{let i=t.req.raw.headers.get(`Cookie`);if(typeof n==`string`){if(!i)return;let t=n;r===`secure`?t=`__Secure-`+n:r===`host`&&(t=`__Host-`+n);let a=e.parse(i,t);return a[t]}if(!i)return{};let a=e.parse(i);return a},q=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},de=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},fe=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,pe=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,me=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,J=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!fe.test(a))break;try{i=await n.req.json()}catch{throw new q(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(pe.test(a)||me.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await de(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new q(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=ue(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const Y=()=>new K,X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=Y().basePath(`/:key`).get(`/`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.get(t);return e.json({value:r},200)}).post(`/`,J(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.set(t,r),e.body(null,204)}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},he=Y().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,J(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)}),ge=new K().route(`/storage`,Q).route(`/chat`,he);async function _e(e){let t=e?.entrypoint??await i(e?.cwd??process.cwd());if(!t)throw Error(`Unable to locate the entrypoint of the agent. Please specify it manually.`);let n;if(typeof Bun<`u`)n=l(t);else{let{outfile:e}=await r(t);n=l(e)}return u(n)}exports.create=_e;
1
+ const e=require(`./cookie-B3SvZDri.cjs`);let t=require(`fs/promises`);t=e.__toESM(t);let n=require(`path`);n=e.__toESM(n);async function r(e,{outdir:t}={}){t||=await a(e);let r=(0,n.join)(t,`agent.js`),i=c(),o=await i.build({...s,entryPoints:[e],outfile:r});if(o.errors.length>0)throw Error(`Failed to build agent!`);return{outfile:r}}async function i(e){let r=await o(e,`package.json`);if(!r)throw Error(`No package.json found in ${e}`);let i=JSON.parse(await(0,t.readFile)(r,`utf-8`)),a=i.main;if(!a)throw Error(`"main" is not set in ${(0,n.relative)(process.cwd(),r)}. It should be set to the entrypoint of your agent.`);let s=(0,n.join)((0,n.dirname)(r),a),c=await(0,t.stat)(s);if(!c.isFile())throw Error(`${s} is not a file.`);return s}async function a(e){let r=await o(e,`node_modules`);if(!r){let r=await(0,t.stat)(e);return r.isDirectory()?(0,n.join)(e,`.blink`):(0,n.join)((0,n.dirname)(e),`.blink`)}let i=(0,n.join)(r,`.blink`);return await(0,t.mkdir)(i,{recursive:!0}),i}async function o(e,r){let i=e;for(;i!==(0,n.dirname)(i);){let e=(0,n.join)(i,r);try{return await(0,t.stat)(e),e}catch{}i=(0,n.dirname)(i)}}const s={bundle:!0,format:`cjs`,platform:`node`,target:`node18`,sourcemap:`inline`},c=()=>{try{return require(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};function l(e){let t=require(e);if(typeof t!=`object`)throw Error(`The module at ${e} must export an object.`);let n=t.default;if(typeof n!=`object`)throw Error(`The module at ${e} must export an object.`);if(!n.version)throw Error(`The module at ${e} must export a "version" property.`);if(typeof n.fetch!=`function`)throw Error(`The module at ${e} must export a "fetch" function.`);return n}function u(e){return new d(`http://agent.local`,{fetch:async(t,n)=>e.fetch(new Request(t,{...n,duplex:n.body?`half`:void 0}))})}var d=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/sendMessages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendWebhook(e){let t=new URL(e.url),n=new Headers(e.headers);return this.fetch(`${this.baseUrl}/webhook?${t.searchParams.toString()}`,{method:e.method,headers:n,body:e.body,duplex:e.body?`half`:void 0})}},f=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},p=Symbol(),m=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof y?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?h(e,{all:n,dot:r}):{}};async function h(e,t){let n=await e.formData();return n?g(n,t):{}}function g(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?ee(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(_(n,e,t),delete n[e])}),n}var ee=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},_=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},v=t=>e.tryDecode(t,e.decodeURIComponent_),y=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?v(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?v(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(t){return e.getQueryParam(this.url,t)}queries(t){return e.getQueryParams(this.url,t)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await m(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[p](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},te={Stringify:1,BeforeStream:2,Stream:3},ne=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},b=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>b(e,t,!1,r,i))).then(()=>i[0]));return n?ne(await o,a):o},x=`text/plain; charset=UTF-8`,S=(e,t)=>({"Content-Type":e,...t}),re=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new y(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,S(x,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,S(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,S(`text/html; charset=UTF-8`,n));return typeof e==`object`?b(e,te.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},C=`ALL`,ie=`all`,ae=[`get`,`post`,`put`,`delete`,`options`,`patch`],w=`Can not add a route since the matcher is already built.`,T=class extends Error{},E=`__COMPOSED_HANDLER`,D=e=>e.text(`404 Not Found`,404),O=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},k=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(t={}){let n=[...ae,ie];n.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(C,this.#path,e)}),this);let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??e.getPath:e.getPathNoStrict}#clone(){let e=new k({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=D;errorHandler=O;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===O?r=e.handler:(r=async(n,r)=>(await f([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[E]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(t){let n=this.#clone();return n._basePath=e.mergePath(this._basePath,t),n}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(t,n,r){let i,a;r&&(typeof r==`function`?a=r:(a=r.optionHandler,i=r.replaceRequest===!1?e=>e:r.replaceRequest));let o=a?e=>{let t=a(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};i||=(()=>{let n=e.mergePath(this._basePath,t),r=n===`/`?0:n.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(r)||`/`,new Request(t,e)}})();let s=async(e,t)=>{let r=await n(i(e.req.raw),...o(e));if(r)return r;await t()};return this.#addRoute(C,e.mergePath(t,`*`),s),this}#addRoute(t,n,r){t=t.toUpperCase(),n=e.mergePath(this._basePath,n);let i={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,i]),this.routes.push(i)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new re(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=f(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(t,n,r,i)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,i):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${e.mergePath(`/`,t)}`,n),r,i));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},A=`[^/]+`,j=`.*`,M=`(?:|/.*)`,N=Symbol(),oe=new Set(`.\\+*[^]$()`);function se(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===j||e===M?1:t===j||t===M?-1:e===A?1:t===A?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var P=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw N;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,j]:[``,``,A]:a===`/*`?[``,``,M]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||A;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw N;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==j&&e!==M))throw N;if(i)return;c=this.#children[t]=new P,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==j&&e!==M))throw N;if(i)return;c=this.#children[a]=new P}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(se),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:oe.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},ce=class{#context={varIndex:0};#root=new P;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},F=[],I=[/^$/,[],Object.create(null)],L=Object.create(null);function R(e){return L[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function z(){L=Object.create(null)}function B(e){let t=new ce,n=[];if(e.length===0)return I;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),F]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===N?new T(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function V(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(R(n).test(t))return[...e[n]]}}var H=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[C]:Object.create(null)},this.#routes={[C]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(w);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[C]).forEach(n=>{e[t][n]=[...e[C][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=R(n);t===C?Object.keys(i).forEach(e=>{i[e][n]||=V(i[e],n)||V(i[C],n)||[]}):i[t][n]||=V(i[t],n)||V(i[C],n)||[],Object.keys(i).forEach(n=>{(t===C||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===C||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e.checkOptionalParameter(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===C||t===s)&&(a[s][c]||=[...V(i[s],c)||V(i[C],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){z();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[C],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],F];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===C;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==C&&t.push(...Object.keys(r[C]).map(e=>[e,r[C][e]])):(n||=!0,t.push(...i))}),n?B(t):null}},U=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(w);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof T)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(t,n,r){this.#order=++this.#order;let i=this,a=e.splitRoutingPath(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=e.getPattern(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#children){i=i.#children[c],s&&o.push(s[1]);continue}i.#children[c]=new G,s&&(i.#patterns.push(s),o.push(s[1])),i=i.#children[c]}return i.#methods.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),i}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[C],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(t,n){let r=[];this.#params=W;let i=this,a=[i],o=e.splitPath(n),s=[];for(let e=0,n=o.length;e<n;e++){let i=o[e],c=e===n-1,l=[];for(let n=0,u=a.length;n<u;n++){let u=a[n],d=u.#children[i];d&&(d.#params=u.#params,c?(d.#children[`*`]&&r.push(...this.#getHandlerSets(d.#children[`*`],t,u.#params)),r.push(...this.#getHandlerSets(d,t,u.#params))):l.push(d));for(let n=0,a=u.#patterns.length;n<a;n++){let a=u.#patterns[n],d=u.#params===W?{}:{...u.#params};if(a===`*`){let e=u.#children[`*`];e&&(r.push(...this.#getHandlerSets(e,t,u.#params)),e.#params=d,l.push(e));continue}let[f,p,m]=a;if(!i&&!(m instanceof RegExp))continue;let h=u.#children[f],g=o.slice(e).join(`/`);if(m instanceof RegExp){let e=m.exec(g);if(e){if(d[p]=e[0],r.push(...this.#getHandlerSets(h,t,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let t=e[0].match(/\//)?.length??0,n=s[t]||=[];n.push(h)}continue}}(m===!0||m.test(i))&&(d[p]=i,c?(r.push(...this.#getHandlerSets(h,t,d,u.#params)),h.#children[`*`]&&r.push(...this.#getHandlerSets(h.#children[`*`],t,d,u.#params))):(h.#params=d,l.push(h)))}}a=l.concat(s.shift()??[])}return r.length>1&&r.sort((e,t)=>e.score-t.score),[r.map(({handler:e,params:t})=>[e,t])]}},le=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(t,n,r){let i=e.checkOptionalParameter(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},K=class extends k{constructor(e={}){super(e),this.router=e.router??new U({routers:[new H,new le]})}},ue=(t,n,r)=>{let i=t.req.raw.headers.get(`Cookie`);if(typeof n==`string`){if(!i)return;let t=n;r===`secure`?t=`__Secure-`+n:r===`host`&&(t=`__Host-`+n);let a=e.parse(i,t);return a[t]}if(!i)return{};let a=e.parse(i);return a},q=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},de=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},fe=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,pe=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,me=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,J=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!fe.test(a))break;try{i=await n.req.json()}catch{throw new q(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(pe.test(a)||me.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await de(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new q(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=ue(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const Y=()=>new K,X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=Y().basePath(`/:key`).get(`/`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.get(t);return e.json({value:r},200)}).post(`/`,J(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.set(t,r),e.body(null,204)}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},he=Y().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,J(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)}),ge=new K().route(`/storage`,Q).route(`/chat`,he);async function _e(e){let t=e?.entrypoint??await i(e?.cwd??process.cwd());if(!t)throw Error(`Unable to locate the entrypoint of the agent. Please specify it manually.`);let n;if(typeof Bun<`u`)n=l(t);else{let{outfile:e}=await r(t);n=l(e)}return u(n)}exports.create=_e;
package/dist/test.js CHANGED
@@ -1 +1 @@
1
- import{checkOptionalParameter as e,decodeURIComponent_ as t,getPath as n,getPathNoStrict as r,getPattern as i,getQueryParam as a,getQueryParams as o,mergePath as s,parse as c,splitPath as l,splitRoutingPath as u,tryDecode as d}from"./cookie-BiKY7-P1.js";import{createRequire as f}from"node:module";import{mkdir as p,readFile as m,stat as h}from"fs/promises";import{dirname as g,join as _,relative as ee}from"path";var v=f(import.meta.url);async function y(e,{outdir:t}={}){t||=await te(e);let n=_(t,`agent.js`),r=re(),i=await r.build({...ne,entryPoints:[e],outfile:n});if(i.errors.length>0)throw Error(`Failed to build agent!`);return{outfile:n}}async function b(e){let t=await x(e,`package.json`);if(!t)throw Error(`No package.json found in ${e}`);let n=JSON.parse(await m(t,`utf-8`)),r=n.main;if(!r)throw Error(`"main" is not set in ${ee(process.cwd(),t)}. It should be set to the entrypoint of your agent.`);let i=_(g(t),r),a=await h(i);if(!a.isFile())throw Error(`${i} is not a file.`);return i}async function te(e){let t=await x(e,`node_modules`);if(!t){let t=await h(e);return t.isDirectory()?_(e,`.blink`):_(g(e),`.blink`)}let n=_(t,`.blink`);return await p(n,{recursive:!0}),n}async function x(e,t){let n=e;for(;n!==g(n);){let e=_(n,t);try{return await h(e),e}catch{}n=g(n)}}const ne={bundle:!0,format:`cjs`,platform:`node`,target:`node18`,sourcemap:`inline`},re=()=>{try{return v(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};function S(e){let t=v(e);if(typeof t!=`object`)throw Error(`The module at ${e} must export an object.`);let n=t.default;if(typeof n!=`object`)throw Error(`The module at ${e} must export an object.`);if(!n.version)throw Error(`The module at ${e} must export a "version" property.`);if(typeof n.fetch!=`function`)throw Error(`The module at ${e} must export a "fetch" function.`);return n}function ie(e){return new ae(`http://agent.local`,{fetch:async(t,n)=>e.fetch(new Request(t,{...n,duplex:n.body?`half`:void 0}))})}var ae=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/sendMessages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendWebhook(e){let t=new URL(e.url),n=new Headers(e.headers);return this.fetch(`${this.baseUrl}/webhook?${t.searchParams.toString()}`,{method:e.method,headers:n,body:e.body})}},C=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},w=Symbol(),T=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof D?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?oe(e,{all:n,dot:r}):{}};async function oe(e,t){let n=await e.formData();return n?se(n,t):{}}function se(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?ce(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(le(n,e,t),delete n[e])}),n}var ce=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},le=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},E=e=>d(e,t),D=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?E(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?E(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return a(this.url,e)}queries(e){return o(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await T(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[w](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ue={Stringify:1,BeforeStream:2,Stream:3},de=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},O=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>O(e,t,!1,r,i))).then(()=>i[0]));return n?de(await o,a):o},fe=`text/plain; charset=UTF-8`,k=(e,t)=>({"Content-Type":e,...t}),pe=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new D(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,k(fe,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,k(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,k(`text/html; charset=UTF-8`,n));return typeof e==`object`?O(e,ue.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},A=`ALL`,me=`all`,he=[`get`,`post`,`put`,`delete`,`options`,`patch`],j=`Can not add a route since the matcher is already built.`,M=class extends Error{},ge=`__COMPOSED_HANDLER`,_e=e=>e.text(`404 Not Found`,404),N=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},P=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...he,me];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(A,this.#path,e)}),this);let{strict:i,...a}=e;Object.assign(this,a),this.getPath=i??!0?e.getPath??n:r}#clone(){let e=new P({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=_e;errorHandler=N;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===N?r=e.handler:(r=async(n,r)=>(await C([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[ge]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=s(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=s(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(A,s(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=s(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new pe(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=C(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${s(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},F=`[^/]+`,I=`.*`,L=`(?:|/.*)`,R=Symbol(),ve=new Set(`.\\+*[^]$()`);function ye(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===I||e===L?1:t===I||t===L?-1:e===F?1:t===F?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var z=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw R;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,I]:[``,``,F]:a===`/*`?[``,``,L]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||F;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw R;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==I&&e!==L))throw R;if(i)return;c=this.#children[t]=new z,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==I&&e!==L))throw R;if(i)return;c=this.#children[a]=new z}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(ye),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ve.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},be=class{#context={varIndex:0};#root=new z;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},B=[],xe=[/^$/,[],Object.create(null)],V=Object.create(null);function H(e){return V[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function Se(){V=Object.create(null)}function Ce(e){let t=new be,n=[];if(e.length===0)return xe;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),B]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===R?new M(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function U(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(H(n).test(t))return[...e[n]]}}var we=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[A]:Object.create(null)},this.#routes={[A]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(j);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[A]).forEach(n=>{e[t][n]=[...e[A][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=H(n);t===A?Object.keys(i).forEach(e=>{i[e][n]||=U(i[e],n)||U(i[A],n)||[]}):i[t][n]||=U(i[t],n)||U(i[A],n)||[],Object.keys(i).forEach(n=>{(t===A||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===A||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===A||t===s)&&(a[s][c]||=[...U(i[s],c)||U(i[A],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){Se();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[A],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],B];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===A;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==A&&t.push(...Object.keys(r[A]).map(e=>[e,r[A][e]])):(n||=!0,t.push(...i))}),n?Ce(t):null}},Te=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(j);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof M)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,a=u(t),o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e],n=a[e+1],s=i(t,n),c=Array.isArray(s)?s[0]:t;if(c in r.#children){r=r.#children[c],s&&o.push(s[1]);continue}r.#children[c]=new G,s&&(r.#patterns.push(s),o.push(s[1])),r=r.#children[c]}return r.#methods.push({[e]:{handler:n,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[A],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=W;let r=this,i=[r],a=l(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===W?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},Ee=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(t,n,r){let i=e(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},K=class extends P{constructor(e={}){super(e),this.router=e.router??new Te({routers:[new we,new Ee]})}},De=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=c(r,e);return i[e]}if(!r)return{};let i=c(r);return i},q=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},Oe=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},J=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ke=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,Ae=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!J.test(a))break;try{i=await n.req.json()}catch{throw new q(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(ke.test(a)||Ae.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await Oe(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new q(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=De(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=()=>new K,Z=(e,t)=>e.json({error:t},400),Q=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},je=X().basePath(`/:key`).get(`/`,async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let r=await e.env.storage.get(t);return e.json({value:r},200)}).post(`/`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?Z(t,`Value is too long. Max length is 1024 characters.`):{value:n}:Z(t,`Value must be a string`):Z(t,`Value is required`)}),async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.set(t,r),e.body(null,204)}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Me=X().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return Z(t,`Messages are required`);if(!Array.isArray(n))return Z(t,`Messages must be an array`);if(n.length===0)return Z(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`?Z(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)});new K().route(`/storage`,je).route(`/chat`,Me);async function Ne(e){let t=e?.entrypoint??await b(e?.cwd??process.cwd());if(!t)throw Error(`Unable to locate the entrypoint of the agent. Please specify it manually.`);let n;if(typeof Bun<`u`)n=S(t);else{let{outfile:e}=await y(t);n=S(e)}return ie(n)}export{Ne as create};
1
+ import{checkOptionalParameter as e,decodeURIComponent_ as t,getPath as n,getPathNoStrict as r,getPattern as i,getQueryParam as a,getQueryParams as o,mergePath as s,parse as c,splitPath as l,splitRoutingPath as u,tryDecode as d}from"./cookie-BiKY7-P1.js";import{createRequire as f}from"node:module";import{mkdir as p,readFile as m,stat as h}from"fs/promises";import{dirname as g,join as _,relative as ee}from"path";var v=f(import.meta.url);async function y(e,{outdir:t}={}){t||=await te(e);let n=_(t,`agent.js`),r=re(),i=await r.build({...ne,entryPoints:[e],outfile:n});if(i.errors.length>0)throw Error(`Failed to build agent!`);return{outfile:n}}async function b(e){let t=await x(e,`package.json`);if(!t)throw Error(`No package.json found in ${e}`);let n=JSON.parse(await m(t,`utf-8`)),r=n.main;if(!r)throw Error(`"main" is not set in ${ee(process.cwd(),t)}. It should be set to the entrypoint of your agent.`);let i=_(g(t),r),a=await h(i);if(!a.isFile())throw Error(`${i} is not a file.`);return i}async function te(e){let t=await x(e,`node_modules`);if(!t){let t=await h(e);return t.isDirectory()?_(e,`.blink`):_(g(e),`.blink`)}let n=_(t,`.blink`);return await p(n,{recursive:!0}),n}async function x(e,t){let n=e;for(;n!==g(n);){let e=_(n,t);try{return await h(e),e}catch{}n=g(n)}}const ne={bundle:!0,format:`cjs`,platform:`node`,target:`node18`,sourcemap:`inline`},re=()=>{try{return v(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};function S(e){let t=v(e);if(typeof t!=`object`)throw Error(`The module at ${e} must export an object.`);let n=t.default;if(typeof n!=`object`)throw Error(`The module at ${e} must export an object.`);if(!n.version)throw Error(`The module at ${e} must export a "version" property.`);if(typeof n.fetch!=`function`)throw Error(`The module at ${e} must export a "fetch" function.`);return n}function ie(e){return new ae(`http://agent.local`,{fetch:async(t,n)=>e.fetch(new Request(t,{...n,duplex:n.body?`half`:void 0}))})}var ae=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/sendMessages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendWebhook(e){let t=new URL(e.url),n=new Headers(e.headers);return this.fetch(`${this.baseUrl}/webhook?${t.searchParams.toString()}`,{method:e.method,headers:n,body:e.body,duplex:e.body?`half`:void 0})}},C=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},w=Symbol(),T=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof D?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?oe(e,{all:n,dot:r}):{}};async function oe(e,t){let n=await e.formData();return n?se(n,t):{}}function se(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?ce(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(le(n,e,t),delete n[e])}),n}var ce=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},le=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},E=e=>d(e,t),D=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?E(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?E(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return a(this.url,e)}queries(e){return o(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await T(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[w](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ue={Stringify:1,BeforeStream:2,Stream:3},de=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},O=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>O(e,t,!1,r,i))).then(()=>i[0]));return n?de(await o,a):o},fe=`text/plain; charset=UTF-8`,k=(e,t)=>({"Content-Type":e,...t}),pe=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new D(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,k(fe,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,k(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,k(`text/html; charset=UTF-8`,n));return typeof e==`object`?O(e,ue.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},A=`ALL`,me=`all`,he=[`get`,`post`,`put`,`delete`,`options`,`patch`],j=`Can not add a route since the matcher is already built.`,M=class extends Error{},ge=`__COMPOSED_HANDLER`,_e=e=>e.text(`404 Not Found`,404),N=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},P=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...he,me];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(A,this.#path,e)}),this);let{strict:i,...a}=e;Object.assign(this,a),this.getPath=i??!0?e.getPath??n:r}#clone(){let e=new P({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=_e;errorHandler=N;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===N?r=e.handler:(r=async(n,r)=>(await C([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[ge]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=s(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=s(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(A,s(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=s(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new pe(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=C(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${s(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},F=`[^/]+`,I=`.*`,L=`(?:|/.*)`,R=Symbol(),ve=new Set(`.\\+*[^]$()`);function ye(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===I||e===L?1:t===I||t===L?-1:e===F?1:t===F?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var z=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw R;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,I]:[``,``,F]:a===`/*`?[``,``,L]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||F;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw R;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==I&&e!==L))throw R;if(i)return;c=this.#children[t]=new z,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==I&&e!==L))throw R;if(i)return;c=this.#children[a]=new z}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(ye),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:ve.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},be=class{#context={varIndex:0};#root=new z;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},B=[],xe=[/^$/,[],Object.create(null)],V=Object.create(null);function H(e){return V[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function Se(){V=Object.create(null)}function Ce(e){let t=new be,n=[];if(e.length===0)return xe;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),B]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===R?new M(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function U(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(H(n).test(t))return[...e[n]]}}var we=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[A]:Object.create(null)},this.#routes={[A]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(j);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[A]).forEach(n=>{e[t][n]=[...e[A][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=H(n);t===A?Object.keys(i).forEach(e=>{i[e][n]||=U(i[e],n)||U(i[A],n)||[]}):i[t][n]||=U(i[t],n)||U(i[A],n)||[],Object.keys(i).forEach(n=>{(t===A||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===A||t===n)&&Object.keys(a[n]).forEach(t=>e.test(t)&&a[n][t].push([r,o]))});return}let s=e(n)||[n];for(let e=0,n=s.length;e<n;e++){let c=s[e];Object.keys(a).forEach(s=>{(t===A||t===s)&&(a[s][c]||=[...U(i[s],c)||U(i[A],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){Se();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[A],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],B];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===A;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==A&&t.push(...Object.keys(r[A]).map(e=>[e,r[A][e]])):(n||=!0,t.push(...i))}),n?Ce(t):null}},Te=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(j);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof M)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},W=Object.create(null),G=class{#methods;#children;#patterns;#order=0;#params=W;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,a=u(t),o=[];for(let e=0,t=a.length;e<t;e++){let t=a[e],n=a[e+1],s=i(t,n),c=Array.isArray(s)?s[0]:t;if(c in r.#children){r=r.#children[c],s&&o.push(s[1]);continue}r.#children[c]=new G,s&&(r.#patterns.push(s),o.push(s[1])),r=r.#children[c]}return r.#methods.push({[e]:{handler:n,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[A],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==W||r&&r!==W))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=W;let r=this,i=[r],a=l(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===W?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},Ee=class{name=`TrieRouter`;#node;constructor(){this.#node=new G}add(t,n,r){let i=e(n);if(i){for(let e=0,n=i.length;e<n;e++)this.#node.insert(t,i[e],r);return}this.#node.insert(t,n,r)}match(e,t){return this.#node.search(e,t)}},K=class extends P{constructor(e={}){super(e),this.router=e.router??new Te({routers:[new we,new Ee]})}},De=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=c(r,e);return i[e]}if(!r)return{};let i=c(r);return i},q=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},Oe=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},J=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ke=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,Ae=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!J.test(a))break;try{i=await n.req.json()}catch{throw new q(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(ke.test(a)||Ae.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await Oe(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new q(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=De(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=()=>new K,Z=(e,t)=>e.json({error:t},400),Q=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},je=X().basePath(`/:key`).get(`/`,async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let r=await e.env.storage.get(t);return e.json({value:r},200)}).post(`/`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?Z(t,`Value is too long. Max length is 1024 characters.`):{value:n}:Z(t,`Value must be a string`):Z(t,`Value is required`)}),async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.set(t,r),e.body(null,204)}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},Me=X().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return Z(t,`Messages are required`);if(!Array.isArray(n))return Z(t,`Messages must be an array`);if(n.length===0)return Z(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`?Z(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)});new K().route(`/storage`,je).route(`/chat`,Me);async function Ne(e){let t=e?.entrypoint??await b(e?.cwd??process.cwd());if(!t)throw Error(`Unable to locate the entrypoint of the agent. Please specify it manually.`);let n;if(typeof Bun<`u`)n=S(t);else{let{outfile:e}=await y(t);n=S(e)}return ie(n)}export{Ne as create};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blink",
3
- "version": "0.1.31",
3
+ "version": "0.1.33",
4
4
  "description": "Blink is a JavaScript runtime for building and deploying AI agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -33,7 +33,8 @@
33
33
  "README.md"
34
34
  ],
35
35
  "scripts": {
36
- "build": "tsdown"
36
+ "build": "tsdown",
37
+ "dev-install": "rm -rf ./*.tgz && bun run build && npm pack && bun remove -g blink && bun install -g $(pwd)/*.tgz"
37
38
  },
38
39
  "devDependencies": {
39
40
  "@ai-sdk/anthropic": "^2.0.15",
@@ -41,7 +42,7 @@
41
42
  "@ai-sdk/openai": "^2.0.28",
42
43
  "@ai-sdk/react": "^2.0.35",
43
44
  "@ai-sdk/xai": "^2.0.16",
44
- "@blink.so/api": "^0.0.4",
45
+ "@blink.so/api": "^0.0.6",
45
46
  "@clack/prompts": "^0.11.0",
46
47
  "@hono/node-server": "^1.19.3",
47
48
  "@hugodutka/gemini-cli": "^0.6.0-nightly-20250912-5",