blink 0.1.53 → 0.1.55
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/api/index.cjs +22 -3
- package/dist/api/index.d.cts +2 -218
- package/dist/api/index.d.ts +2 -218
- package/dist/api/index.js +22 -3
- package/dist/build/index.cjs +7 -0
- package/dist/build/index.d.cts +107 -0
- package/dist/build/index.d.ts +107 -0
- package/dist/build/index.js +7 -0
- package/dist/chunk-___ucjiX.js +1 -0
- package/dist/chunk-hhQzssFb.cjs +1 -0
- package/dist/cli/auth-Dw-wJ1IM.js +30 -0
- package/dist/cli/{chat-DstkfVtn.js → chat-CvTLq5E0.js} +1 -1
- package/dist/cli/connect-BHyGYU8L.js +1 -0
- package/dist/cli/connect-Cxa-uIEb.js +26 -0
- package/dist/cli/{dev-D5eJ3-13.js → dev-Kje8z9kN.js} +426 -351
- package/dist/cli/devtools-BS9tk1Y9.js +14 -14
- package/dist/cli/{dist-NqrnQGst.js → dist-CN69Y-yA.js} +1 -1
- package/dist/cli/esm-CeJfCMPI.js +1 -1
- package/dist/cli/index.js +10 -10
- package/dist/cli/{init-BsN-peJw.js → init-x07jlFqm.js} +2 -2
- package/dist/cli/login-KHDcJ0iZ.js +1 -0
- package/dist/cli/undici-BG07ys6c.js +6 -6
- package/dist/cli/util-cVEGIV3r.js +9 -0
- package/dist/cli/wrapper-B4vDwpOq.js +2 -2
- package/dist/http/index.cjs +1 -0
- package/dist/http/index.d.cts +3 -0
- package/dist/http/index.d.ts +3 -0
- package/dist/http/index.js +1 -0
- package/dist/http-BAfeJhFm.js +53 -0
- package/dist/http-DS8vmbQx.cjs +53 -0
- package/dist/index-BgJpZoBy.d.cts +102 -0
- package/dist/index-IWju3eNc.d.cts +286 -0
- package/dist/index-auvvMWNH.d.ts +102 -0
- package/dist/index-tvf1rglX.d.ts +286 -0
- package/dist/test.cjs +1 -4
- package/dist/test.d.cts +4 -1
- package/dist/test.d.ts +4 -1
- package/dist/test.js +1 -4
- package/package.json +12 -8
- package/dist/cli/auth-DFAAGrh0.js +0 -30
- package/dist/cli/connect-CUOPse6P.js +0 -1
- package/dist/cli/connect-CswVxp7Y.js +0 -26
- package/dist/cli/login-CU2BqznA.js +0 -1
- package/dist/cli/main-DqOlaYW2.js +0 -6
- package/dist/cli/serve-DYwdm-QS.js +0 -1
- package/dist/cli/serve-neuJCuqR.js +0 -60
- package/dist/cookie-BtKXrFr6.cjs +0 -1
- package/dist/cookie-CyZUsiHM.js +0 -1
- /package/dist/cli/{open-CSMQaj0E.js → open-Cr8lEmcs.js} +0 -0
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import http from "http";
|
|
2
|
+
import * as _ai_sdk_provider0 from "@ai-sdk/provider";
|
|
3
|
+
import * as ai0 from "ai";
|
|
4
|
+
import { AsyncIterableStream, InferUIMessageChunk, Tool, ToolSet, UIDataTypes, UIMessage, UIMessagePart, UITools } from "ai";
|
|
5
|
+
|
|
6
|
+
//#region src/api/chat.d.ts
|
|
7
|
+
interface Chat {
|
|
8
|
+
readonly id: string;
|
|
9
|
+
}
|
|
10
|
+
type ChatBehavior = "enqueue" | "interrupt" | "append";
|
|
11
|
+
interface MessageOptions {
|
|
12
|
+
/**
|
|
13
|
+
* behavior of the chat when sending this message.
|
|
14
|
+
*
|
|
15
|
+
* - "enqueue" will add messages to the chat and start the chat eventually.
|
|
16
|
+
* - "interrupt" will interrupt the chat if running and send messages.
|
|
17
|
+
* - "append" will add messages to the chat.
|
|
18
|
+
*/
|
|
19
|
+
readonly behavior?: ChatBehavior;
|
|
20
|
+
}
|
|
21
|
+
interface Message<METADATA = unknown, DATA_TYPES extends UIDataTypes = UIDataTypes, TOOLS extends UITools = UITools> {
|
|
22
|
+
readonly role: UIMessage["role"];
|
|
23
|
+
readonly parts: UIMessagePart<DATA_TYPES, TOOLS>[];
|
|
24
|
+
readonly metadata?: METADATA;
|
|
25
|
+
}
|
|
26
|
+
declare const chat: Readonly<{
|
|
27
|
+
upsert: (id: string) => Promise<Chat>;
|
|
28
|
+
message: (id: string, message: Message, options?: MessageOptions) => Promise<void>;
|
|
29
|
+
}>;
|
|
30
|
+
//#endregion
|
|
31
|
+
//#region src/api/tools.d.ts
|
|
32
|
+
/**
|
|
33
|
+
* ToolWithContext is a tool that supports the "withContext" method.
|
|
34
|
+
*
|
|
35
|
+
* @param CONTEXT The context type.
|
|
36
|
+
* @param TOOL The tool type.
|
|
37
|
+
* @returns The tool with the given context.
|
|
38
|
+
*/
|
|
39
|
+
type ToolWithContext<CONTEXT, TOOL extends Tool> = TOOL & {
|
|
40
|
+
withContext(context: CONTEXT): TOOL;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Tools are helpers for managing tools.
|
|
44
|
+
*/
|
|
45
|
+
declare const tools: {
|
|
46
|
+
/**
|
|
47
|
+
* withContext adds context to a set of tools that supports the "withContext" method.
|
|
48
|
+
*
|
|
49
|
+
* @param context
|
|
50
|
+
* @param tools
|
|
51
|
+
* @returns
|
|
52
|
+
*/
|
|
53
|
+
withContext<const TOOLS extends ToolsWithContext>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: Tool };
|
|
54
|
+
/**
|
|
55
|
+
* @internal
|
|
56
|
+
* @deprecated Use withContext instead - it's the same thing.
|
|
57
|
+
*/
|
|
58
|
+
with<const TOOLS extends ToolsWithContext>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: Tool };
|
|
59
|
+
/**
|
|
60
|
+
* withApproval ensures a set of tools need explicit user approval
|
|
61
|
+
* before they are executed.
|
|
62
|
+
*
|
|
63
|
+
* This works by replacing the execution of all provided tools with
|
|
64
|
+
* special output that interfaces must handle.
|
|
65
|
+
*
|
|
66
|
+
* On approval, the tool will be executed with the verbatim input.
|
|
67
|
+
*
|
|
68
|
+
* @returns Tools that should be sent in `streamText`.
|
|
69
|
+
*/
|
|
70
|
+
withApproval<TOOLS extends ToolSet, MESSAGE extends UIMessage>(options: {
|
|
71
|
+
messages: MESSAGE[];
|
|
72
|
+
tools: TOOLS;
|
|
73
|
+
abortSignal?: AbortSignal;
|
|
74
|
+
}): Promise<TOOLS>;
|
|
75
|
+
/**
|
|
76
|
+
* prefix adds a prefix to all the tools in a tool set.
|
|
77
|
+
*
|
|
78
|
+
* @param tools The tool set to prefix.
|
|
79
|
+
* @param prefix The prefix to add to the tools.
|
|
80
|
+
* @returns The prefixed tool set.
|
|
81
|
+
*/
|
|
82
|
+
prefix(tools: ToolSet, prefix: string): ToolSet;
|
|
83
|
+
};
|
|
84
|
+
type ToolsWithContext = Record<string, Tool & {
|
|
85
|
+
withContext(context: unknown): Tool;
|
|
86
|
+
}>;
|
|
87
|
+
type ContextFromTools<TOOLS extends ToolsWithContext> = TOOLS[keyof TOOLS] extends {
|
|
88
|
+
withContext(context: infer C): any;
|
|
89
|
+
} ? C : never;
|
|
90
|
+
/**
|
|
91
|
+
* ToolApprovalOutput is the output of a tool that requires approval.
|
|
92
|
+
*
|
|
93
|
+
* This should be consumed by the UI to display an approval prompt.
|
|
94
|
+
*/
|
|
95
|
+
interface ToolApprovalOutput {
|
|
96
|
+
type: "tool-approval";
|
|
97
|
+
outcome: "pending" | "approved" | "rejected";
|
|
98
|
+
reason?: string;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* isToolApprovalOutput checks if an output is a tool approval output.
|
|
102
|
+
*/
|
|
103
|
+
declare function isToolApprovalOutput(output: unknown): output is ToolApprovalOutput;
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region src/api/storage.d.ts
|
|
106
|
+
/**
|
|
107
|
+
* Storage allows agents to persist data.
|
|
108
|
+
* Every agent has it's own persistent storage namespace.
|
|
109
|
+
*/
|
|
110
|
+
declare const storage: Readonly<{
|
|
111
|
+
kv: Readonly<{
|
|
112
|
+
get: (key: string) => Promise<string | undefined>;
|
|
113
|
+
set: (key: string, value: string) => Promise<void>;
|
|
114
|
+
del: (key: string) => Promise<void>;
|
|
115
|
+
}>;
|
|
116
|
+
}>;
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/api/index.d.ts
|
|
119
|
+
/**
|
|
120
|
+
* SendMessagesResponse is the response of the sendMessages function.
|
|
121
|
+
* It can be a stream of messages or an arbitrary response.
|
|
122
|
+
*/
|
|
123
|
+
type SendMessagesResponse = {
|
|
124
|
+
toUIMessageStream(): AsyncIterableStream<InferUIMessageChunk<UIMessage>>;
|
|
125
|
+
} | Response | ReadableStream<InferUIMessageChunk<UIMessage>>;
|
|
126
|
+
/**
|
|
127
|
+
* SendMessagesOptions is the options for the sendMessages function.
|
|
128
|
+
*/
|
|
129
|
+
interface SendMessagesOptions<MESSAGE extends UIMessage = UIMessage> {
|
|
130
|
+
/**
|
|
131
|
+
* Messages are all messages for the history of the chat.
|
|
132
|
+
* It is the user's responsibility to manage context for the chat.
|
|
133
|
+
*/
|
|
134
|
+
readonly messages: MESSAGE[];
|
|
135
|
+
/**
|
|
136
|
+
* Chat is the associated chat for the messages.
|
|
137
|
+
*/
|
|
138
|
+
readonly chat: Chat;
|
|
139
|
+
/**
|
|
140
|
+
* abortSignal can be used to terminate streaming operations
|
|
141
|
+
* immediately when the streaming request ends.
|
|
142
|
+
*/
|
|
143
|
+
readonly abortSignal?: AbortSignal;
|
|
144
|
+
}
|
|
145
|
+
interface ExperimentalProvideCompletionsOptions<MESSAGE extends UIMessage = UIMessage> {
|
|
146
|
+
/**
|
|
147
|
+
* The chat for the completions.
|
|
148
|
+
* Omitted if there is no chat.
|
|
149
|
+
*/
|
|
150
|
+
readonly chat?: Chat;
|
|
151
|
+
/**
|
|
152
|
+
* Messages that are part of the current chat.
|
|
153
|
+
* Omitted if there is no chat.
|
|
154
|
+
*/
|
|
155
|
+
readonly messages?: MESSAGE[];
|
|
156
|
+
readonly input: string;
|
|
157
|
+
readonly caret: number;
|
|
158
|
+
readonly selection?: [number, number];
|
|
159
|
+
readonly abortSignal?: AbortSignal;
|
|
160
|
+
}
|
|
161
|
+
type ExperimentalCompletion = {
|
|
162
|
+
text: string;
|
|
163
|
+
replace?: [number, number];
|
|
164
|
+
} | {
|
|
165
|
+
id: string;
|
|
166
|
+
label: string;
|
|
167
|
+
detail?: string;
|
|
168
|
+
insertText?: string;
|
|
169
|
+
replace?: [number, number];
|
|
170
|
+
};
|
|
171
|
+
type ExperimentalProvideCompletionsResponse = ReadableStream<ExperimentalCompletion> | Promise<ReadableStream<ExperimentalCompletion>> | Promise<ExperimentalCompletion> | ExperimentalCompletion;
|
|
172
|
+
interface AgentOptions<MESSAGE extends UIMessage = UIMessage> {
|
|
173
|
+
/**
|
|
174
|
+
* sendMessages is called when the agent is streaming chat messages.
|
|
175
|
+
* This is invoked on chat creation, and can be programatically
|
|
176
|
+
* invoked at any time with `blink.chat.message`.
|
|
177
|
+
*/
|
|
178
|
+
sendMessages(options: SendMessagesOptions<MESSAGE>): Promise<SendMessagesResponse> | SendMessagesResponse;
|
|
179
|
+
/**
|
|
180
|
+
* onRequest is called when the agent receives a request.
|
|
181
|
+
* This is for handling webhooks, or incoming client payloads
|
|
182
|
+
* that warrant a response.
|
|
183
|
+
*
|
|
184
|
+
* @param request The request received by the agent.
|
|
185
|
+
* @returns A response to the request. If void, the agent will
|
|
186
|
+
* respond with a 404.
|
|
187
|
+
*/
|
|
188
|
+
onRequest?(request: Request): Promise<Response | void>;
|
|
189
|
+
/**
|
|
190
|
+
* experimental_provideCompletions is called when the user is typing in the chat input.
|
|
191
|
+
* This is used to provide completions to the user.
|
|
192
|
+
*
|
|
193
|
+
* *NOTE*: This *only* works in the browser at the moment.
|
|
194
|
+
*
|
|
195
|
+
* @param options The options for the completions.
|
|
196
|
+
* @returns A stream of completions, or a single completion.
|
|
197
|
+
*/
|
|
198
|
+
experimental_provideCompletions?(options: ExperimentalProvideCompletionsOptions<MESSAGE>): ExperimentalProvideCompletionsResponse;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* A Blink agent is simply an HTTP handler with a reserved
|
|
202
|
+
* "/_agent/" path used for agent-specific requests.
|
|
203
|
+
*
|
|
204
|
+
* The environment variable "BLINK_API_SERVER_URL" is used
|
|
205
|
+
* to serve responses to the `blink.*` API. (e.g. blink.chat.upsert).
|
|
206
|
+
*/
|
|
207
|
+
interface Agent {
|
|
208
|
+
/**
|
|
209
|
+
* fetch is the HTTP handler for the agent.
|
|
210
|
+
*
|
|
211
|
+
* @param request The request to handle.
|
|
212
|
+
* @returns A response to the request.
|
|
213
|
+
*/
|
|
214
|
+
fetch(request: Request): Promise<Response> | Response;
|
|
215
|
+
/**
|
|
216
|
+
* serve starts the agent as an unauthenticated HTTP server.
|
|
217
|
+
* This is required for use in the Blink Cloud or with the Blink CLI.
|
|
218
|
+
*
|
|
219
|
+
* @param options Optional options for the server.
|
|
220
|
+
* @returns A Node.JS HTTP server.
|
|
221
|
+
*/
|
|
222
|
+
serve(options?: ServeOptions): http.Server;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* ServeOptions is the options for the `.serve()` method.
|
|
226
|
+
*/
|
|
227
|
+
type ServeOptions = {
|
|
228
|
+
readonly host?: string;
|
|
229
|
+
readonly port?: number;
|
|
230
|
+
};
|
|
231
|
+
/**
|
|
232
|
+
* agent creates an HTTP handler that when served
|
|
233
|
+
* speaks the Blink agent protocol.
|
|
234
|
+
*
|
|
235
|
+
* Call `.serve()` to serve the agent for use in
|
|
236
|
+
* the Blink Cloud or with the Blink CLI.
|
|
237
|
+
*/
|
|
238
|
+
declare function agent<MESSAGE extends UIMessage = UIMessage>(agent: AgentOptions<MESSAGE>): Agent;
|
|
239
|
+
type StreamResponseFormat = "ui-message" | "openai-chat" | "openai-response" | "anthropic" | "google" | "xai";
|
|
240
|
+
declare function withResponseFormat(response: Response, format: StreamResponseFormat): Response;
|
|
241
|
+
/**
|
|
242
|
+
* model returns an AI SDK model that is authenticated through Blink.
|
|
243
|
+
*
|
|
244
|
+
* Blink's AI Gateway uses Vercel's AI Gateway under-the-hood, and passes
|
|
245
|
+
* through billing cost without any upcharge.
|
|
246
|
+
*
|
|
247
|
+
* Feel free to use any provide you'd like.
|
|
248
|
+
*
|
|
249
|
+
* @param modelName - See: https://vercel.com/ai-gateway/models
|
|
250
|
+
* @returns An AI SDK model that is authenticated through Blink.
|
|
251
|
+
*/
|
|
252
|
+
declare const model: (modelName: string) => _ai_sdk_provider0.LanguageModelV2;
|
|
253
|
+
declare const _default: {
|
|
254
|
+
agent: typeof agent;
|
|
255
|
+
chat: Readonly<{
|
|
256
|
+
upsert: (id: string) => Promise<Chat>;
|
|
257
|
+
message: (id: string, message: Message, options?: MessageOptions) => Promise<void>;
|
|
258
|
+
}>;
|
|
259
|
+
storage: Readonly<{
|
|
260
|
+
kv: Readonly<{
|
|
261
|
+
get: (key: string) => Promise<string | undefined>;
|
|
262
|
+
set: (key: string, value: string) => Promise<void>;
|
|
263
|
+
del: (key: string) => Promise<void>;
|
|
264
|
+
}>;
|
|
265
|
+
}>;
|
|
266
|
+
tools: {
|
|
267
|
+
withContext<const TOOLS extends {
|
|
268
|
+
[x: string]: ai0.Tool & {
|
|
269
|
+
withContext(context: unknown): ai0.Tool;
|
|
270
|
+
};
|
|
271
|
+
}>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: ai0.Tool };
|
|
272
|
+
with<const TOOLS extends {
|
|
273
|
+
[x: string]: ai0.Tool & {
|
|
274
|
+
withContext(context: unknown): ai0.Tool;
|
|
275
|
+
};
|
|
276
|
+
}>(tools: TOOLS, context: ContextFromTools<TOOLS>): { [K in keyof TOOLS]: ai0.Tool };
|
|
277
|
+
withApproval<TOOLS extends ai0.ToolSet, MESSAGE extends UIMessage>(options: {
|
|
278
|
+
messages: MESSAGE[];
|
|
279
|
+
tools: TOOLS;
|
|
280
|
+
abortSignal?: AbortSignal;
|
|
281
|
+
}): Promise<TOOLS>;
|
|
282
|
+
prefix(tools: ai0.ToolSet, prefix: string): ai0.ToolSet;
|
|
283
|
+
};
|
|
284
|
+
};
|
|
285
|
+
//#endregion
|
|
286
|
+
export { Agent, AgentOptions, Chat, ChatBehavior, ContextFromTools, ExperimentalCompletion, ExperimentalProvideCompletionsOptions, ExperimentalProvideCompletionsResponse, Message, MessageOptions, SendMessagesOptions, SendMessagesResponse, ServeOptions, StreamResponseFormat, ToolApprovalOutput, ToolWithContext, _default, agent, chat, isToolApprovalOutput, model, storage, tools, withResponseFormat };
|
package/dist/test.cjs
CHANGED
|
@@ -1,4 +1 @@
|
|
|
1
|
-
const e=require(`./
|
|
2
|
-
`);t=e+`
|
|
3
|
-
|
|
4
|
-
`+t}e.contents=Buffer.from(t,`utf-8`)}})})}}]},l=()=>{try{return require(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};function u(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 d(e){return new f(`http://agent.local`,{fetch:async(t,n)=>e.fetch(new Request(t,{...n,duplex:n.body?`half`:void 0}))})}var f=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/_agent/send-messages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendRequest(e){let t=new URL(e.url),n=new Headers(e.headers),r=new URL(this.baseUrl);if(r.pathname=t.pathname,r.search=t.search,t.pathname.startsWith(`/_agent/`))throw Error(`The pathname "/_agent/" is reserved for agent-specific requests.`);return this.fetch(r,{method:e.method,headers:n,body:e.body,duplex:e.body?`half`:void 0})}},p=(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}},m=Symbol(),h=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`)?g(e,{all:n,dot:r}):{}};async function g(e,t){let n=await e.formData();return n?_(n,t):{}}function _(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?ee(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(te(n,e,t),delete n[e])}),n}var ee=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},te=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},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 h(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[m](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ne={Stringify:1,BeforeStream:2,Stream:3},re=(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?re(await o,a):o},ie=`text/plain; charset=UTF-8`,x=(e,t)=>({"Content-Type":e,...t}),ae=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,x(ie,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,x(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,x(`text/html; charset=UTF-8`,n));return typeof e==`object`?b(e,ne.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))},S=`ALL`,C=`all`,w=[`get`,`post`,`put`,`delete`,`options`,`patch`],T=`Can not add a route since the matcher is already built.`,E=class extends Error{},D=`__COMPOSED_HANDLER`,oe=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=[...w,C];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(S,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=oe;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 p([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[D]=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(S,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 ae(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=p(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(),se=new Set(`.\\+*[^]$()`);function ce(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(ce),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:se.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(`|`)+`)`}},le=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 le,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 E(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={[S]:Object.create(null)},this.#routes={[S]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(T);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[S]).forEach(n=>{e[t][n]=[...e[S][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=R(n);t===S?Object.keys(i).forEach(e=>{i[e][n]||=V(i[e],n)||V(i[S],n)||[]}):i[t][n]||=V(i[t],n)||V(i[S],n)||[],Object.keys(i).forEach(n=>{(t===S||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===S||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===S||t===s)&&(a[s][c]||=[...V(i[s],c)||V(i[S],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[S],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===S;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!==S&&t.push(...Object.keys(r[S]).map(e=>[e,r[S][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(T);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 E)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[S],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])]}},ue=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 ue]})}},de=(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})}},fe=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},pe=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,J=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,me=/^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||!pe.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||!(J.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 fe(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}},he=X().get(`/kv/:key`,async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,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.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Q(e);return n?Z(e,n):(await e.env.storage.kv.del(t),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`}},ge=X().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return Z(t,`Messages are required`);if(!Array.isArray(n))return Z(t,`Messages must be an array`);if(n.length===0)return Z(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?Z(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)}),_e=new K().route(`/storage`,he).route(`/chat`,ge);async function ve(e){let t=e?.entrypoint??await a(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=u(t);else{let{outfile:e}=await i(t);n=u(e)}return d(n)}exports.create=ve;
|
|
1
|
+
const e=require(`./chunk-hhQzssFb.cjs`);async function t(e){return{}}exports.create=t;
|
package/dist/test.d.cts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import "./index-IWju3eNc.cjs";
|
|
2
|
+
import { Client } from "./index-BgJpZoBy.cjs";
|
|
3
|
+
|
|
1
4
|
//#region src/test.d.ts
|
|
2
5
|
interface CreateOptions {
|
|
3
6
|
readonly entrypoint?: string;
|
|
4
7
|
readonly cwd?: string;
|
|
5
8
|
readonly env?: Record<string, string>;
|
|
6
9
|
}
|
|
7
|
-
declare function create(options?: CreateOptions): Promise<
|
|
10
|
+
declare function create(options?: CreateOptions): Promise<Client>;
|
|
8
11
|
//#endregion
|
|
9
12
|
export { CreateOptions, create };
|
package/dist/test.d.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import "./index-tvf1rglX.js";
|
|
2
|
+
import { Client } from "./index-auvvMWNH.js";
|
|
3
|
+
|
|
1
4
|
//#region src/test.d.ts
|
|
2
5
|
interface CreateOptions {
|
|
3
6
|
readonly entrypoint?: string;
|
|
4
7
|
readonly cwd?: string;
|
|
5
8
|
readonly env?: Record<string, string>;
|
|
6
9
|
}
|
|
7
|
-
declare function create(options?: CreateOptions): Promise<
|
|
10
|
+
declare function create(options?: CreateOptions): Promise<Client>;
|
|
8
11
|
//#endregion
|
|
9
12
|
export { CreateOptions, create };
|
package/dist/test.js
CHANGED
|
@@ -1,4 +1 @@
|
|
|
1
|
-
|
|
2
|
-
`);t=e+`
|
|
3
|
-
|
|
4
|
-
`+t}e.contents=Buffer.from(t,`utf-8`)}})})}}]},oe=()=>{try{return y(`esbuild`)}catch{throw Error("esbuild is not installed. Please install it with `bun add esbuild`.")}};function x(e){let t=y(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 se(e){return new ce(`http://agent.local`,{fetch:async(t,n)=>e.fetch(new Request(t,{...n,duplex:n.body?`half`:void 0}))})}var ce=class{baseUrl;fetch;constructor(e,t){this.baseUrl=e,this.fetch=t?.fetch??fetch}async sendMessages(e,t){return this.fetch(`${this.baseUrl}/_agent/send-messages`,{method:`POST`,body:JSON.stringify(e),signal:t?.signal})}async sendRequest(e){let t=new URL(e.url),n=new Headers(e.headers),r=new URL(this.baseUrl);if(r.pathname=t.pathname,r.search=t.search,t.pathname.startsWith(`/_agent/`))throw Error(`The pathname "/_agent/" is reserved for agent-specific requests.`);return this.fetch(r,{method:e.method,headers:n,body:e.body,duplex:e.body?`half`:void 0})}},S=(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}},le=Symbol(),C=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof T?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?ue(e,{all:n,dot:r}):{}};async function ue(e,t){let n=await e.formData();return n?de(n,t):{}}function de(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?fe(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(pe(n,e,t),delete n[e])}),n}var fe=(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]},pe=(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])})},w=e=>d(e,t),T=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)?w(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)?w(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 C(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[le](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},E={Stringify:1,BeforeStream:2,Stream:3},me=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},D=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=>D(e,t,!1,r,i))).then(()=>i[0]));return n?me(await o,a):o},he=`text/plain; charset=UTF-8`,O=(e,t)=>({"Content-Type":e,...t}),ge=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 T(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,O(he,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,O(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,O(`text/html; charset=UTF-8`,n));return typeof e==`object`?D(e,E.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))},k=`ALL`,_e=`all`,ve=[`get`,`post`,`put`,`delete`,`options`,`patch`],A=`Can not add a route since the matcher is already built.`,j=class extends Error{},ye=`__COMPOSED_HANDLER`,M=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=[...ve,_e];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(k,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=M;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 S([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[ye]=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(k,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 ge(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=S(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(),be=new Set(`.\\+*[^]$()`);function xe(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(xe),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:be.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},Se=class{#context={varIndex:0};#root=new 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=[],Ce=[/^$/,[],Object.create(null)],V=Object.create(null);function H(e){return V[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function we(){V=Object.create(null)}function Te(e){let t=new Se,n=[];if(e.length===0)return Ce;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 j(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function 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 Ee=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[k]:Object.create(null)},this.#routes={[k]:Object.create(null)}}add(t,n,r){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(A);i[t]||[i,a].forEach(e=>{e[t]=Object.create(null),Object.keys(e[k]).forEach(n=>{e[t][n]=[...e[k][n]]})}),n===`/*`&&(n=`*`);let o=(n.match(/\/:/g)||[]).length;if(/\*$/.test(n)){let e=H(n);t===k?Object.keys(i).forEach(e=>{i[e][n]||=U(i[e],n)||U(i[k],n)||[]}):i[t][n]||=U(i[t],n)||U(i[k],n)||[],Object.keys(i).forEach(n=>{(t===k||t===n)&&Object.keys(i[n]).forEach(t=>{e.test(t)&&i[n][t].push([r,o])})}),Object.keys(a).forEach(n=>{(t===k||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===k||t===s)&&(a[s][c]||=[...U(i[s],c)||U(i[k],c)||[]],a[s][c].push([r,o-n+e+1]))})}}match(e,t){we();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[k],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===k;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!==k&&t.push(...Object.keys(r[k]).map(e=>[e,r[k][e]])):(n||=!0,t.push(...i))}),n?Te(t):null}},De=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(A);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof j)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},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[k],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])]}},Oe=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 De({routers:[new Ee,new Oe]})}},ke=(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})}},J=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},Ae=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,je=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,Me=/^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||!Ae.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||!(je.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 J(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=ke(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}},Ne=X().get(`/kv/:key`,async e=>{let{key:t,err:n}=Q(e);if(n)return Z(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,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.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Q(e);return n?Z(e,n):(await e.env.storage.kv.del(t),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`}},Pe=X().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return Z(t,`Messages are required`);if(!Array.isArray(n))return Z(t,`Messages must be an array`);if(n.length===0)return Z(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?Z(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return Z(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);return await e.env.chat.sendMessages(t,{messages:r,behavior:i}),e.body(null,204)});new K().route(`/storage`,Ne).route(`/chat`,Pe);async function Fe(e){let t=e?.entrypoint??await re(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=x(t);else{let{outfile:e}=await ne(t);n=x(e)}return se(n)}export{Fe as create};
|
|
1
|
+
async function e(e){return{}}export{e as create};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "blink",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.55",
|
|
4
4
|
"description": "Blink is a JavaScript runtime for building and deploying AI agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -17,10 +17,15 @@
|
|
|
17
17
|
"import": "./dist/test.js",
|
|
18
18
|
"require": "./dist/test.cjs"
|
|
19
19
|
},
|
|
20
|
-
"./
|
|
21
|
-
"types": "./dist/
|
|
22
|
-
"import": "./dist/
|
|
23
|
-
"require": "./dist/
|
|
20
|
+
"./http": {
|
|
21
|
+
"types": "./dist/http/index.d.ts",
|
|
22
|
+
"import": "./dist/http/index.js",
|
|
23
|
+
"require": "./dist/http/index.cjs"
|
|
24
|
+
},
|
|
25
|
+
"./build": {
|
|
26
|
+
"types": "./dist/build/index.d.ts",
|
|
27
|
+
"import": "./dist/build/index.js",
|
|
28
|
+
"require": "./dist/build/index.cjs"
|
|
24
29
|
}
|
|
25
30
|
},
|
|
26
31
|
"files": [
|
|
@@ -42,12 +47,12 @@
|
|
|
42
47
|
"@clack/prompts": "^0.11.0",
|
|
43
48
|
"@hono/node-server": "^1.19.3",
|
|
44
49
|
"@hugodutka/gemini-cli": "^0.6.0-nightly-20250912-5",
|
|
45
|
-
"@mswjs/interceptors": "^0.39.6",
|
|
46
50
|
"@types/marked-terminal": "^6.1.1",
|
|
47
51
|
"@whatwg-node/server": "^0.10.12",
|
|
48
52
|
"ai": "^5.0.34",
|
|
49
53
|
"commander": "^14.0.0",
|
|
50
54
|
"eventsource-parser": "^3.0.6",
|
|
55
|
+
"filenamify": "^7.0.0",
|
|
51
56
|
"hono": "^4.9.8",
|
|
52
57
|
"ink": "^6.2.3",
|
|
53
58
|
"ink-spinner": "^5.0.0",
|
|
@@ -57,8 +62,7 @@
|
|
|
57
62
|
"open": "^10.2.0",
|
|
58
63
|
"react": "^19.1.1",
|
|
59
64
|
"react-devtools-core": "^6.1.5",
|
|
60
|
-
"tsdown": "
|
|
61
|
-
"unique-names-generator": "^4.7.1",
|
|
65
|
+
"tsdown": "0.14.2",
|
|
62
66
|
"xdg-app-paths": "^8.3.0"
|
|
63
67
|
},
|
|
64
68
|
"optionalDependencies": {
|