@cohaku/cli 0.2.6

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.
@@ -0,0 +1,2863 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+
3
+ // ../../node_modules/.pnpm/@hono+node-server@1.19.9_hono@4.12.3/node_modules/@hono/node-server/dist/index.mjs
4
+ import { createServer as createServerHTTP } from "http";
5
+ import { Http2ServerRequest as Http2ServerRequest2 } from "http2";
6
+ import { Http2ServerRequest } from "http2";
7
+ import { Readable } from "stream";
8
+ import crypto from "crypto";
9
+ var RequestError = class extends Error {
10
+ constructor(message, options) {
11
+ super(message, options);
12
+ this.name = "RequestError";
13
+ }
14
+ };
15
+ var toRequestError = (e) => {
16
+ if (e instanceof RequestError) {
17
+ return e;
18
+ }
19
+ return new RequestError(e.message, { cause: e });
20
+ };
21
+ var GlobalRequest = global.Request;
22
+ var Request2 = class extends GlobalRequest {
23
+ constructor(input, options) {
24
+ if (typeof input === "object" && getRequestCache in input) {
25
+ input = input[getRequestCache]();
26
+ }
27
+ if (typeof options?.body?.getReader !== "undefined") {
28
+ ;
29
+ options.duplex ??= "half";
30
+ }
31
+ super(input, options);
32
+ }
33
+ };
34
+ var newHeadersFromIncoming = (incoming) => {
35
+ const headerRecord = [];
36
+ const rawHeaders = incoming.rawHeaders;
37
+ for (let i = 0; i < rawHeaders.length; i += 2) {
38
+ const { [i]: key, [i + 1]: value } = rawHeaders;
39
+ if (key.charCodeAt(0) !== /*:*/
40
+ 58) {
41
+ headerRecord.push([key, value]);
42
+ }
43
+ }
44
+ return new Headers(headerRecord);
45
+ };
46
+ var wrapBodyStream = /* @__PURE__ */ Symbol("wrapBodyStream");
47
+ var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
48
+ const init = {
49
+ method,
50
+ headers,
51
+ signal: abortController.signal
52
+ };
53
+ if (method === "TRACE") {
54
+ init.method = "GET";
55
+ const req = new Request2(url, init);
56
+ Object.defineProperty(req, "method", {
57
+ get() {
58
+ return "TRACE";
59
+ }
60
+ });
61
+ return req;
62
+ }
63
+ if (!(method === "GET" || method === "HEAD")) {
64
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
65
+ init.body = new ReadableStream({
66
+ start(controller) {
67
+ controller.enqueue(incoming.rawBody);
68
+ controller.close();
69
+ }
70
+ });
71
+ } else if (incoming[wrapBodyStream]) {
72
+ let reader;
73
+ init.body = new ReadableStream({
74
+ async pull(controller) {
75
+ try {
76
+ reader ||= Readable.toWeb(incoming).getReader();
77
+ const { done, value } = await reader.read();
78
+ if (done) {
79
+ controller.close();
80
+ } else {
81
+ controller.enqueue(value);
82
+ }
83
+ } catch (error) {
84
+ controller.error(error);
85
+ }
86
+ }
87
+ });
88
+ } else {
89
+ init.body = Readable.toWeb(incoming);
90
+ }
91
+ }
92
+ return new Request2(url, init);
93
+ };
94
+ var getRequestCache = /* @__PURE__ */ Symbol("getRequestCache");
95
+ var requestCache = /* @__PURE__ */ Symbol("requestCache");
96
+ var incomingKey = /* @__PURE__ */ Symbol("incomingKey");
97
+ var urlKey = /* @__PURE__ */ Symbol("urlKey");
98
+ var headersKey = /* @__PURE__ */ Symbol("headersKey");
99
+ var abortControllerKey = /* @__PURE__ */ Symbol("abortControllerKey");
100
+ var getAbortController = /* @__PURE__ */ Symbol("getAbortController");
101
+ var requestPrototype = {
102
+ get method() {
103
+ return this[incomingKey].method || "GET";
104
+ },
105
+ get url() {
106
+ return this[urlKey];
107
+ },
108
+ get headers() {
109
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
110
+ },
111
+ [getAbortController]() {
112
+ this[getRequestCache]();
113
+ return this[abortControllerKey];
114
+ },
115
+ [getRequestCache]() {
116
+ this[abortControllerKey] ||= new AbortController();
117
+ return this[requestCache] ||= newRequestFromIncoming(
118
+ this.method,
119
+ this[urlKey],
120
+ this.headers,
121
+ this[incomingKey],
122
+ this[abortControllerKey]
123
+ );
124
+ }
125
+ };
126
+ [
127
+ "body",
128
+ "bodyUsed",
129
+ "cache",
130
+ "credentials",
131
+ "destination",
132
+ "integrity",
133
+ "mode",
134
+ "redirect",
135
+ "referrer",
136
+ "referrerPolicy",
137
+ "signal",
138
+ "keepalive"
139
+ ].forEach((k) => {
140
+ Object.defineProperty(requestPrototype, k, {
141
+ get() {
142
+ return this[getRequestCache]()[k];
143
+ }
144
+ });
145
+ });
146
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
147
+ Object.defineProperty(requestPrototype, k, {
148
+ value: function() {
149
+ return this[getRequestCache]()[k]();
150
+ }
151
+ });
152
+ });
153
+ Object.setPrototypeOf(requestPrototype, Request2.prototype);
154
+ var newRequest = (incoming, defaultHostname) => {
155
+ const req = Object.create(requestPrototype);
156
+ req[incomingKey] = incoming;
157
+ const incomingUrl = incoming.url || "";
158
+ if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
159
+ (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
160
+ if (incoming instanceof Http2ServerRequest) {
161
+ throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
162
+ }
163
+ try {
164
+ const url2 = new URL(incomingUrl);
165
+ req[urlKey] = url2.href;
166
+ } catch (e) {
167
+ throw new RequestError("Invalid absolute URL", { cause: e });
168
+ }
169
+ return req;
170
+ }
171
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
172
+ if (!host) {
173
+ throw new RequestError("Missing host header");
174
+ }
175
+ let scheme;
176
+ if (incoming instanceof Http2ServerRequest) {
177
+ scheme = incoming.scheme;
178
+ if (!(scheme === "http" || scheme === "https")) {
179
+ throw new RequestError("Unsupported scheme");
180
+ }
181
+ } else {
182
+ scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
183
+ }
184
+ const url = new URL(`${scheme}://${host}${incomingUrl}`);
185
+ if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
186
+ throw new RequestError("Invalid host header");
187
+ }
188
+ req[urlKey] = url.href;
189
+ return req;
190
+ };
191
+ var responseCache = /* @__PURE__ */ Symbol("responseCache");
192
+ var getResponseCache = /* @__PURE__ */ Symbol("getResponseCache");
193
+ var cacheKey = /* @__PURE__ */ Symbol("cache");
194
+ var GlobalResponse = global.Response;
195
+ var Response2 = class _Response {
196
+ #body;
197
+ #init;
198
+ [getResponseCache]() {
199
+ delete this[cacheKey];
200
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
201
+ }
202
+ constructor(body, init) {
203
+ let headers;
204
+ this.#body = body;
205
+ if (init instanceof _Response) {
206
+ const cachedGlobalResponse = init[responseCache];
207
+ if (cachedGlobalResponse) {
208
+ this.#init = cachedGlobalResponse;
209
+ this[getResponseCache]();
210
+ return;
211
+ } else {
212
+ this.#init = init.#init;
213
+ headers = new Headers(init.#init.headers);
214
+ }
215
+ } else {
216
+ this.#init = init;
217
+ }
218
+ if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
219
+ headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
220
+ this[cacheKey] = [init?.status || 200, body, headers];
221
+ }
222
+ }
223
+ get headers() {
224
+ const cache = this[cacheKey];
225
+ if (cache) {
226
+ if (!(cache[2] instanceof Headers)) {
227
+ cache[2] = new Headers(cache[2]);
228
+ }
229
+ return cache[2];
230
+ }
231
+ return this[getResponseCache]().headers;
232
+ }
233
+ get status() {
234
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
235
+ }
236
+ get ok() {
237
+ const status = this.status;
238
+ return status >= 200 && status < 300;
239
+ }
240
+ };
241
+ ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
242
+ Object.defineProperty(Response2.prototype, k, {
243
+ get() {
244
+ return this[getResponseCache]()[k];
245
+ }
246
+ });
247
+ });
248
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
249
+ Object.defineProperty(Response2.prototype, k, {
250
+ value: function() {
251
+ return this[getResponseCache]()[k]();
252
+ }
253
+ });
254
+ });
255
+ Object.setPrototypeOf(Response2, GlobalResponse);
256
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
257
+ async function readWithoutBlocking(readPromise) {
258
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
259
+ }
260
+ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
261
+ const cancel = (error) => {
262
+ reader.cancel(error).catch(() => {
263
+ });
264
+ };
265
+ writable.on("close", cancel);
266
+ writable.on("error", cancel);
267
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
268
+ return reader.closed.finally(() => {
269
+ writable.off("close", cancel);
270
+ writable.off("error", cancel);
271
+ });
272
+ function handleStreamError(error) {
273
+ if (error) {
274
+ writable.destroy(error);
275
+ }
276
+ }
277
+ function onDrain() {
278
+ reader.read().then(flow, handleStreamError);
279
+ }
280
+ function flow({ done, value }) {
281
+ try {
282
+ if (done) {
283
+ writable.end();
284
+ } else if (!writable.write(value)) {
285
+ writable.once("drain", onDrain);
286
+ } else {
287
+ return reader.read().then(flow, handleStreamError);
288
+ }
289
+ } catch (e) {
290
+ handleStreamError(e);
291
+ }
292
+ }
293
+ }
294
+ function writeFromReadableStream(stream, writable) {
295
+ if (stream.locked) {
296
+ throw new TypeError("ReadableStream is locked.");
297
+ } else if (writable.destroyed) {
298
+ return;
299
+ }
300
+ return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
301
+ }
302
+ var buildOutgoingHttpHeaders = (headers) => {
303
+ const res = {};
304
+ if (!(headers instanceof Headers)) {
305
+ headers = new Headers(headers ?? void 0);
306
+ }
307
+ const cookies = [];
308
+ for (const [k, v] of headers) {
309
+ if (k === "set-cookie") {
310
+ cookies.push(v);
311
+ } else {
312
+ res[k] = v;
313
+ }
314
+ }
315
+ if (cookies.length > 0) {
316
+ res["set-cookie"] = cookies;
317
+ }
318
+ res["content-type"] ??= "text/plain; charset=UTF-8";
319
+ return res;
320
+ };
321
+ var X_ALREADY_SENT = "x-hono-already-sent";
322
+ if (typeof global.crypto === "undefined") {
323
+ global.crypto = crypto;
324
+ }
325
+ var outgoingEnded = /* @__PURE__ */ Symbol("outgoingEnded");
326
+ var handleRequestError = () => new Response(null, {
327
+ status: 400
328
+ });
329
+ var handleFetchError = (e) => new Response(null, {
330
+ status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
331
+ });
332
+ var handleResponseError = (e, outgoing) => {
333
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
334
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
335
+ console.info("The user aborted a request.");
336
+ } else {
337
+ console.error(e);
338
+ if (!outgoing.headersSent) {
339
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
340
+ }
341
+ outgoing.end(`Error: ${err.message}`);
342
+ outgoing.destroy(err);
343
+ }
344
+ };
345
+ var flushHeaders = (outgoing) => {
346
+ if ("flushHeaders" in outgoing && outgoing.writable) {
347
+ outgoing.flushHeaders();
348
+ }
349
+ };
350
+ var responseViaCache = async (res, outgoing) => {
351
+ let [status, body, header] = res[cacheKey];
352
+ if (header instanceof Headers) {
353
+ header = buildOutgoingHttpHeaders(header);
354
+ }
355
+ if (typeof body === "string") {
356
+ header["Content-Length"] = Buffer.byteLength(body);
357
+ } else if (body instanceof Uint8Array) {
358
+ header["Content-Length"] = body.byteLength;
359
+ } else if (body instanceof Blob) {
360
+ header["Content-Length"] = body.size;
361
+ }
362
+ outgoing.writeHead(status, header);
363
+ if (typeof body === "string" || body instanceof Uint8Array) {
364
+ outgoing.end(body);
365
+ } else if (body instanceof Blob) {
366
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
367
+ } else {
368
+ flushHeaders(outgoing);
369
+ await writeFromReadableStream(body, outgoing)?.catch(
370
+ (e) => handleResponseError(e, outgoing)
371
+ );
372
+ }
373
+ ;
374
+ outgoing[outgoingEnded]?.();
375
+ };
376
+ var isPromise = (res) => typeof res.then === "function";
377
+ var responseViaResponseObject = async (res, outgoing, options = {}) => {
378
+ if (isPromise(res)) {
379
+ if (options.errorHandler) {
380
+ try {
381
+ res = await res;
382
+ } catch (err) {
383
+ const errRes = await options.errorHandler(err);
384
+ if (!errRes) {
385
+ return;
386
+ }
387
+ res = errRes;
388
+ }
389
+ } else {
390
+ res = await res.catch(handleFetchError);
391
+ }
392
+ }
393
+ if (cacheKey in res) {
394
+ return responseViaCache(res, outgoing);
395
+ }
396
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
397
+ if (res.body) {
398
+ const reader = res.body.getReader();
399
+ const values = [];
400
+ let done = false;
401
+ let currentReadPromise = void 0;
402
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
403
+ let maxReadCount = 2;
404
+ for (let i = 0; i < maxReadCount; i++) {
405
+ currentReadPromise ||= reader.read();
406
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
407
+ console.error(e);
408
+ done = true;
409
+ });
410
+ if (!chunk) {
411
+ if (i === 1) {
412
+ await new Promise((resolve) => setTimeout(resolve));
413
+ maxReadCount = 3;
414
+ continue;
415
+ }
416
+ break;
417
+ }
418
+ currentReadPromise = void 0;
419
+ if (chunk.value) {
420
+ values.push(chunk.value);
421
+ }
422
+ if (chunk.done) {
423
+ done = true;
424
+ break;
425
+ }
426
+ }
427
+ if (done && !("content-length" in resHeaderRecord)) {
428
+ resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
429
+ }
430
+ }
431
+ outgoing.writeHead(res.status, resHeaderRecord);
432
+ values.forEach((value) => {
433
+ ;
434
+ outgoing.write(value);
435
+ });
436
+ if (done) {
437
+ outgoing.end();
438
+ } else {
439
+ if (values.length === 0) {
440
+ flushHeaders(outgoing);
441
+ }
442
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
443
+ }
444
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {
445
+ } else {
446
+ outgoing.writeHead(res.status, resHeaderRecord);
447
+ outgoing.end();
448
+ }
449
+ ;
450
+ outgoing[outgoingEnded]?.();
451
+ };
452
+ var getRequestListener = (fetchCallback, options = {}) => {
453
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
454
+ if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
455
+ Object.defineProperty(global, "Request", {
456
+ value: Request2
457
+ });
458
+ Object.defineProperty(global, "Response", {
459
+ value: Response2
460
+ });
461
+ }
462
+ return async (incoming, outgoing) => {
463
+ let res, req;
464
+ try {
465
+ req = newRequest(incoming, options.hostname);
466
+ let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
467
+ if (!incomingEnded) {
468
+ ;
469
+ incoming[wrapBodyStream] = true;
470
+ incoming.on("end", () => {
471
+ incomingEnded = true;
472
+ });
473
+ if (incoming instanceof Http2ServerRequest2) {
474
+ ;
475
+ outgoing[outgoingEnded] = () => {
476
+ if (!incomingEnded) {
477
+ setTimeout(() => {
478
+ if (!incomingEnded) {
479
+ setTimeout(() => {
480
+ incoming.destroy();
481
+ outgoing.destroy();
482
+ });
483
+ }
484
+ });
485
+ }
486
+ };
487
+ }
488
+ }
489
+ outgoing.on("close", () => {
490
+ const abortController = req[abortControllerKey];
491
+ if (abortController) {
492
+ if (incoming.errored) {
493
+ req[abortControllerKey].abort(incoming.errored.toString());
494
+ } else if (!outgoing.writableFinished) {
495
+ req[abortControllerKey].abort("Client connection prematurely closed.");
496
+ }
497
+ }
498
+ if (!incomingEnded) {
499
+ setTimeout(() => {
500
+ if (!incomingEnded) {
501
+ setTimeout(() => {
502
+ incoming.destroy();
503
+ });
504
+ }
505
+ });
506
+ }
507
+ });
508
+ res = fetchCallback(req, { incoming, outgoing });
509
+ if (cacheKey in res) {
510
+ return responseViaCache(res, outgoing);
511
+ }
512
+ } catch (e) {
513
+ if (!res) {
514
+ if (options.errorHandler) {
515
+ res = await options.errorHandler(req ? e : toRequestError(e));
516
+ if (!res) {
517
+ return;
518
+ }
519
+ } else if (!req) {
520
+ res = handleRequestError();
521
+ } else {
522
+ res = handleFetchError(e);
523
+ }
524
+ } else {
525
+ return handleResponseError(e, outgoing);
526
+ }
527
+ }
528
+ try {
529
+ return await responseViaResponseObject(res, outgoing, options);
530
+ } catch (e) {
531
+ return handleResponseError(e, outgoing);
532
+ }
533
+ };
534
+ };
535
+ var createAdaptorServer = (options) => {
536
+ const fetchCallback = options.fetch;
537
+ const requestListener = getRequestListener(fetchCallback, {
538
+ hostname: options.hostname,
539
+ overrideGlobalObjects: options.overrideGlobalObjects,
540
+ autoCleanupIncoming: options.autoCleanupIncoming
541
+ });
542
+ const createServer = options.createServer || createServerHTTP;
543
+ const server = createServer(options.serverOptions || {}, requestListener);
544
+ return server;
545
+ };
546
+ var serve = (options, listeningListener) => {
547
+ const server = createAdaptorServer(options);
548
+ server.listen(options?.port ?? 3e3, options.hostname, () => {
549
+ const serverInfo = server.address();
550
+ listeningListener && listeningListener(serverInfo);
551
+ });
552
+ return server;
553
+ };
554
+
555
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/compose.js
556
+ var compose = (middleware, onError, onNotFound) => {
557
+ return (context, next) => {
558
+ let index = -1;
559
+ return dispatch(0);
560
+ async function dispatch(i) {
561
+ if (i <= index) {
562
+ throw new Error("next() called multiple times");
563
+ }
564
+ index = i;
565
+ let res;
566
+ let isError = false;
567
+ let handler;
568
+ if (middleware[i]) {
569
+ handler = middleware[i][0][0];
570
+ context.req.routeIndex = i;
571
+ } else {
572
+ handler = i === middleware.length && next || void 0;
573
+ }
574
+ if (handler) {
575
+ try {
576
+ res = await handler(context, () => dispatch(i + 1));
577
+ } catch (err) {
578
+ if (err instanceof Error && onError) {
579
+ context.error = err;
580
+ res = await onError(err, context);
581
+ isError = true;
582
+ } else {
583
+ throw err;
584
+ }
585
+ }
586
+ } else {
587
+ if (context.finalized === false && onNotFound) {
588
+ res = await onNotFound(context);
589
+ }
590
+ }
591
+ if (res && (context.finalized === false || isError)) {
592
+ context.res = res;
593
+ }
594
+ return context;
595
+ }
596
+ };
597
+ };
598
+
599
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/request/constants.js
600
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
601
+
602
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/utils/body.js
603
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
604
+ const { all = false, dot = false } = options;
605
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
606
+ const contentType = headers.get("Content-Type");
607
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
608
+ return parseFormData(request, { all, dot });
609
+ }
610
+ return {};
611
+ };
612
+ async function parseFormData(request, options) {
613
+ const formData = await request.formData();
614
+ if (formData) {
615
+ return convertFormDataToBodyData(formData, options);
616
+ }
617
+ return {};
618
+ }
619
+ function convertFormDataToBodyData(formData, options) {
620
+ const form = /* @__PURE__ */ Object.create(null);
621
+ formData.forEach((value, key) => {
622
+ const shouldParseAllValues = options.all || key.endsWith("[]");
623
+ if (!shouldParseAllValues) {
624
+ form[key] = value;
625
+ } else {
626
+ handleParsingAllValues(form, key, value);
627
+ }
628
+ });
629
+ if (options.dot) {
630
+ Object.entries(form).forEach(([key, value]) => {
631
+ const shouldParseDotValues = key.includes(".");
632
+ if (shouldParseDotValues) {
633
+ handleParsingNestedValues(form, key, value);
634
+ delete form[key];
635
+ }
636
+ });
637
+ }
638
+ return form;
639
+ }
640
+ var handleParsingAllValues = (form, key, value) => {
641
+ if (form[key] !== void 0) {
642
+ if (Array.isArray(form[key])) {
643
+ ;
644
+ form[key].push(value);
645
+ } else {
646
+ form[key] = [form[key], value];
647
+ }
648
+ } else {
649
+ if (!key.endsWith("[]")) {
650
+ form[key] = value;
651
+ } else {
652
+ form[key] = [value];
653
+ }
654
+ }
655
+ };
656
+ var handleParsingNestedValues = (form, key, value) => {
657
+ let nestedForm = form;
658
+ const keys = key.split(".");
659
+ keys.forEach((key2, index) => {
660
+ if (index === keys.length - 1) {
661
+ nestedForm[key2] = value;
662
+ } else {
663
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
664
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
665
+ }
666
+ nestedForm = nestedForm[key2];
667
+ }
668
+ });
669
+ };
670
+
671
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/utils/url.js
672
+ var splitPath = (path) => {
673
+ const paths = path.split("/");
674
+ if (paths[0] === "") {
675
+ paths.shift();
676
+ }
677
+ return paths;
678
+ };
679
+ var splitRoutingPath = (routePath) => {
680
+ const { groups, path } = extractGroupsFromPath(routePath);
681
+ const paths = splitPath(path);
682
+ return replaceGroupMarks(paths, groups);
683
+ };
684
+ var extractGroupsFromPath = (path) => {
685
+ const groups = [];
686
+ path = path.replace(/\{[^}]+\}/g, (match2, index) => {
687
+ const mark = `@${index}`;
688
+ groups.push([mark, match2]);
689
+ return mark;
690
+ });
691
+ return { groups, path };
692
+ };
693
+ var replaceGroupMarks = (paths, groups) => {
694
+ for (let i = groups.length - 1; i >= 0; i--) {
695
+ const [mark] = groups[i];
696
+ for (let j = paths.length - 1; j >= 0; j--) {
697
+ if (paths[j].includes(mark)) {
698
+ paths[j] = paths[j].replace(mark, groups[i][1]);
699
+ break;
700
+ }
701
+ }
702
+ }
703
+ return paths;
704
+ };
705
+ var patternCache = {};
706
+ var getPattern = (label, next) => {
707
+ if (label === "*") {
708
+ return "*";
709
+ }
710
+ const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
711
+ if (match2) {
712
+ const cacheKey2 = `${label}#${next}`;
713
+ if (!patternCache[cacheKey2]) {
714
+ if (match2[2]) {
715
+ patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
716
+ } else {
717
+ patternCache[cacheKey2] = [label, match2[1], true];
718
+ }
719
+ }
720
+ return patternCache[cacheKey2];
721
+ }
722
+ return null;
723
+ };
724
+ var tryDecode = (str, decoder) => {
725
+ try {
726
+ return decoder(str);
727
+ } catch {
728
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
729
+ try {
730
+ return decoder(match2);
731
+ } catch {
732
+ return match2;
733
+ }
734
+ });
735
+ }
736
+ };
737
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
738
+ var getPath = (request) => {
739
+ const url = request.url;
740
+ const start = url.indexOf("/", url.indexOf(":") + 4);
741
+ let i = start;
742
+ for (; i < url.length; i++) {
743
+ const charCode = url.charCodeAt(i);
744
+ if (charCode === 37) {
745
+ const queryIndex = url.indexOf("?", i);
746
+ const hashIndex = url.indexOf("#", i);
747
+ const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
748
+ const path = url.slice(start, end);
749
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
750
+ } else if (charCode === 63 || charCode === 35) {
751
+ break;
752
+ }
753
+ }
754
+ return url.slice(start, i);
755
+ };
756
+ var getPathNoStrict = (request) => {
757
+ const result = getPath(request);
758
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
759
+ };
760
+ var mergePath = (base, sub, ...rest) => {
761
+ if (rest.length) {
762
+ sub = mergePath(sub, ...rest);
763
+ }
764
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
765
+ };
766
+ var checkOptionalParameter = (path) => {
767
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
768
+ return null;
769
+ }
770
+ const segments = path.split("/");
771
+ const results = [];
772
+ let basePath = "";
773
+ segments.forEach((segment) => {
774
+ if (segment !== "" && !/\:/.test(segment)) {
775
+ basePath += "/" + segment;
776
+ } else if (/\:/.test(segment)) {
777
+ if (/\?/.test(segment)) {
778
+ if (results.length === 0 && basePath === "") {
779
+ results.push("/");
780
+ } else {
781
+ results.push(basePath);
782
+ }
783
+ const optionalSegment = segment.replace("?", "");
784
+ basePath += "/" + optionalSegment;
785
+ results.push(basePath);
786
+ } else {
787
+ basePath += "/" + segment;
788
+ }
789
+ }
790
+ });
791
+ return results.filter((v, i, a) => a.indexOf(v) === i);
792
+ };
793
+ var _decodeURI = (value) => {
794
+ if (!/[%+]/.test(value)) {
795
+ return value;
796
+ }
797
+ if (value.indexOf("+") !== -1) {
798
+ value = value.replace(/\+/g, " ");
799
+ }
800
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
801
+ };
802
+ var _getQueryParam = (url, key, multiple) => {
803
+ let encoded;
804
+ if (!multiple && key && !/[%+]/.test(key)) {
805
+ let keyIndex2 = url.indexOf("?", 8);
806
+ if (keyIndex2 === -1) {
807
+ return void 0;
808
+ }
809
+ if (!url.startsWith(key, keyIndex2 + 1)) {
810
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
811
+ }
812
+ while (keyIndex2 !== -1) {
813
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
814
+ if (trailingKeyCode === 61) {
815
+ const valueIndex = keyIndex2 + key.length + 2;
816
+ const endIndex = url.indexOf("&", valueIndex);
817
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
818
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
819
+ return "";
820
+ }
821
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
822
+ }
823
+ encoded = /[%+]/.test(url);
824
+ if (!encoded) {
825
+ return void 0;
826
+ }
827
+ }
828
+ const results = {};
829
+ encoded ??= /[%+]/.test(url);
830
+ let keyIndex = url.indexOf("?", 8);
831
+ while (keyIndex !== -1) {
832
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
833
+ let valueIndex = url.indexOf("=", keyIndex);
834
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
835
+ valueIndex = -1;
836
+ }
837
+ let name = url.slice(
838
+ keyIndex + 1,
839
+ valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
840
+ );
841
+ if (encoded) {
842
+ name = _decodeURI(name);
843
+ }
844
+ keyIndex = nextKeyIndex;
845
+ if (name === "") {
846
+ continue;
847
+ }
848
+ let value;
849
+ if (valueIndex === -1) {
850
+ value = "";
851
+ } else {
852
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
853
+ if (encoded) {
854
+ value = _decodeURI(value);
855
+ }
856
+ }
857
+ if (multiple) {
858
+ if (!(results[name] && Array.isArray(results[name]))) {
859
+ results[name] = [];
860
+ }
861
+ ;
862
+ results[name].push(value);
863
+ } else {
864
+ results[name] ??= value;
865
+ }
866
+ }
867
+ return key ? results[key] : results;
868
+ };
869
+ var getQueryParam = _getQueryParam;
870
+ var getQueryParams = (url, key) => {
871
+ return _getQueryParam(url, key, true);
872
+ };
873
+ var decodeURIComponent_ = decodeURIComponent;
874
+
875
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/request.js
876
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
877
+ var HonoRequest = class {
878
+ /**
879
+ * `.raw` can get the raw Request object.
880
+ *
881
+ * @see {@link https://hono.dev/docs/api/request#raw}
882
+ *
883
+ * @example
884
+ * ```ts
885
+ * // For Cloudflare Workers
886
+ * app.post('/', async (c) => {
887
+ * const metadata = c.req.raw.cf?.hostMetadata?
888
+ * ...
889
+ * })
890
+ * ```
891
+ */
892
+ raw;
893
+ #validatedData;
894
+ // Short name of validatedData
895
+ #matchResult;
896
+ routeIndex = 0;
897
+ /**
898
+ * `.path` can get the pathname of the request.
899
+ *
900
+ * @see {@link https://hono.dev/docs/api/request#path}
901
+ *
902
+ * @example
903
+ * ```ts
904
+ * app.get('/about/me', (c) => {
905
+ * const pathname = c.req.path // `/about/me`
906
+ * })
907
+ * ```
908
+ */
909
+ path;
910
+ bodyCache = {};
911
+ constructor(request, path = "/", matchResult = [[]]) {
912
+ this.raw = request;
913
+ this.path = path;
914
+ this.#matchResult = matchResult;
915
+ this.#validatedData = {};
916
+ }
917
+ param(key) {
918
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
919
+ }
920
+ #getDecodedParam(key) {
921
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
922
+ const param = this.#getParamValue(paramKey);
923
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
924
+ }
925
+ #getAllDecodedParams() {
926
+ const decoded = {};
927
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
928
+ for (const key of keys) {
929
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
930
+ if (value !== void 0) {
931
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
932
+ }
933
+ }
934
+ return decoded;
935
+ }
936
+ #getParamValue(paramKey) {
937
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
938
+ }
939
+ query(key) {
940
+ return getQueryParam(this.url, key);
941
+ }
942
+ queries(key) {
943
+ return getQueryParams(this.url, key);
944
+ }
945
+ header(name) {
946
+ if (name) {
947
+ return this.raw.headers.get(name) ?? void 0;
948
+ }
949
+ const headerData = {};
950
+ this.raw.headers.forEach((value, key) => {
951
+ headerData[key] = value;
952
+ });
953
+ return headerData;
954
+ }
955
+ async parseBody(options) {
956
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
957
+ }
958
+ #cachedBody = (key) => {
959
+ const { bodyCache, raw: raw2 } = this;
960
+ const cachedBody = bodyCache[key];
961
+ if (cachedBody) {
962
+ return cachedBody;
963
+ }
964
+ const anyCachedKey = Object.keys(bodyCache)[0];
965
+ if (anyCachedKey) {
966
+ return bodyCache[anyCachedKey].then((body) => {
967
+ if (anyCachedKey === "json") {
968
+ body = JSON.stringify(body);
969
+ }
970
+ return new Response(body)[key]();
971
+ });
972
+ }
973
+ return bodyCache[key] = raw2[key]();
974
+ };
975
+ /**
976
+ * `.json()` can parse Request body of type `application/json`
977
+ *
978
+ * @see {@link https://hono.dev/docs/api/request#json}
979
+ *
980
+ * @example
981
+ * ```ts
982
+ * app.post('/entry', async (c) => {
983
+ * const body = await c.req.json()
984
+ * })
985
+ * ```
986
+ */
987
+ json() {
988
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
989
+ }
990
+ /**
991
+ * `.text()` can parse Request body of type `text/plain`
992
+ *
993
+ * @see {@link https://hono.dev/docs/api/request#text}
994
+ *
995
+ * @example
996
+ * ```ts
997
+ * app.post('/entry', async (c) => {
998
+ * const body = await c.req.text()
999
+ * })
1000
+ * ```
1001
+ */
1002
+ text() {
1003
+ return this.#cachedBody("text");
1004
+ }
1005
+ /**
1006
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
1007
+ *
1008
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
1009
+ *
1010
+ * @example
1011
+ * ```ts
1012
+ * app.post('/entry', async (c) => {
1013
+ * const body = await c.req.arrayBuffer()
1014
+ * })
1015
+ * ```
1016
+ */
1017
+ arrayBuffer() {
1018
+ return this.#cachedBody("arrayBuffer");
1019
+ }
1020
+ /**
1021
+ * Parses the request body as a `Blob`.
1022
+ * @example
1023
+ * ```ts
1024
+ * app.post('/entry', async (c) => {
1025
+ * const body = await c.req.blob();
1026
+ * });
1027
+ * ```
1028
+ * @see https://hono.dev/docs/api/request#blob
1029
+ */
1030
+ blob() {
1031
+ return this.#cachedBody("blob");
1032
+ }
1033
+ /**
1034
+ * Parses the request body as `FormData`.
1035
+ * @example
1036
+ * ```ts
1037
+ * app.post('/entry', async (c) => {
1038
+ * const body = await c.req.formData();
1039
+ * });
1040
+ * ```
1041
+ * @see https://hono.dev/docs/api/request#formdata
1042
+ */
1043
+ formData() {
1044
+ return this.#cachedBody("formData");
1045
+ }
1046
+ /**
1047
+ * Adds validated data to the request.
1048
+ *
1049
+ * @param target - The target of the validation.
1050
+ * @param data - The validated data to add.
1051
+ */
1052
+ addValidatedData(target, data) {
1053
+ this.#validatedData[target] = data;
1054
+ }
1055
+ valid(target) {
1056
+ return this.#validatedData[target];
1057
+ }
1058
+ /**
1059
+ * `.url()` can get the request url strings.
1060
+ *
1061
+ * @see {@link https://hono.dev/docs/api/request#url}
1062
+ *
1063
+ * @example
1064
+ * ```ts
1065
+ * app.get('/about/me', (c) => {
1066
+ * const url = c.req.url // `http://localhost:8787/about/me`
1067
+ * ...
1068
+ * })
1069
+ * ```
1070
+ */
1071
+ get url() {
1072
+ return this.raw.url;
1073
+ }
1074
+ /**
1075
+ * `.method()` can get the method name of the request.
1076
+ *
1077
+ * @see {@link https://hono.dev/docs/api/request#method}
1078
+ *
1079
+ * @example
1080
+ * ```ts
1081
+ * app.get('/about/me', (c) => {
1082
+ * const method = c.req.method // `GET`
1083
+ * })
1084
+ * ```
1085
+ */
1086
+ get method() {
1087
+ return this.raw.method;
1088
+ }
1089
+ get [GET_MATCH_RESULT]() {
1090
+ return this.#matchResult;
1091
+ }
1092
+ /**
1093
+ * `.matchedRoutes()` can return a matched route in the handler
1094
+ *
1095
+ * @deprecated
1096
+ *
1097
+ * Use matchedRoutes helper defined in "hono/route" instead.
1098
+ *
1099
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
1100
+ *
1101
+ * @example
1102
+ * ```ts
1103
+ * app.use('*', async function logger(c, next) {
1104
+ * await next()
1105
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
1106
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
1107
+ * console.log(
1108
+ * method,
1109
+ * ' ',
1110
+ * path,
1111
+ * ' '.repeat(Math.max(10 - path.length, 0)),
1112
+ * name,
1113
+ * i === c.req.routeIndex ? '<- respond from here' : ''
1114
+ * )
1115
+ * })
1116
+ * })
1117
+ * ```
1118
+ */
1119
+ get matchedRoutes() {
1120
+ return this.#matchResult[0].map(([[, route]]) => route);
1121
+ }
1122
+ /**
1123
+ * `routePath()` can retrieve the path registered within the handler
1124
+ *
1125
+ * @deprecated
1126
+ *
1127
+ * Use routePath helper defined in "hono/route" instead.
1128
+ *
1129
+ * @see {@link https://hono.dev/docs/api/request#routepath}
1130
+ *
1131
+ * @example
1132
+ * ```ts
1133
+ * app.get('/posts/:id', (c) => {
1134
+ * return c.json({ path: c.req.routePath })
1135
+ * })
1136
+ * ```
1137
+ */
1138
+ get routePath() {
1139
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
1140
+ }
1141
+ };
1142
+
1143
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/utils/html.js
1144
+ var HtmlEscapedCallbackPhase = {
1145
+ Stringify: 1,
1146
+ BeforeStream: 2,
1147
+ Stream: 3
1148
+ };
1149
+ var raw = (value, callbacks) => {
1150
+ const escapedString = new String(value);
1151
+ escapedString.isEscaped = true;
1152
+ escapedString.callbacks = callbacks;
1153
+ return escapedString;
1154
+ };
1155
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
1156
+ if (typeof str === "object" && !(str instanceof String)) {
1157
+ if (!(str instanceof Promise)) {
1158
+ str = str.toString();
1159
+ }
1160
+ if (str instanceof Promise) {
1161
+ str = await str;
1162
+ }
1163
+ }
1164
+ const callbacks = str.callbacks;
1165
+ if (!callbacks?.length) {
1166
+ return Promise.resolve(str);
1167
+ }
1168
+ if (buffer) {
1169
+ buffer[0] += str;
1170
+ } else {
1171
+ buffer = [str];
1172
+ }
1173
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
1174
+ (res) => Promise.all(
1175
+ res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
1176
+ ).then(() => buffer[0])
1177
+ );
1178
+ if (preserveCallbacks) {
1179
+ return raw(await resStr, callbacks);
1180
+ } else {
1181
+ return resStr;
1182
+ }
1183
+ };
1184
+
1185
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/context.js
1186
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
1187
+ var setDefaultContentType = (contentType, headers) => {
1188
+ return {
1189
+ "Content-Type": contentType,
1190
+ ...headers
1191
+ };
1192
+ };
1193
+ var createResponseInstance = (body, init) => new Response(body, init);
1194
+ var Context = class {
1195
+ #rawRequest;
1196
+ #req;
1197
+ /**
1198
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
1199
+ *
1200
+ * @see {@link https://hono.dev/docs/api/context#env}
1201
+ *
1202
+ * @example
1203
+ * ```ts
1204
+ * // Environment object for Cloudflare Workers
1205
+ * app.get('*', async c => {
1206
+ * const counter = c.env.COUNTER
1207
+ * })
1208
+ * ```
1209
+ */
1210
+ env = {};
1211
+ #var;
1212
+ finalized = false;
1213
+ /**
1214
+ * `.error` can get the error object from the middleware if the Handler throws an error.
1215
+ *
1216
+ * @see {@link https://hono.dev/docs/api/context#error}
1217
+ *
1218
+ * @example
1219
+ * ```ts
1220
+ * app.use('*', async (c, next) => {
1221
+ * await next()
1222
+ * if (c.error) {
1223
+ * // do something...
1224
+ * }
1225
+ * })
1226
+ * ```
1227
+ */
1228
+ error;
1229
+ #status;
1230
+ #executionCtx;
1231
+ #res;
1232
+ #layout;
1233
+ #renderer;
1234
+ #notFoundHandler;
1235
+ #preparedHeaders;
1236
+ #matchResult;
1237
+ #path;
1238
+ /**
1239
+ * Creates an instance of the Context class.
1240
+ *
1241
+ * @param req - The Request object.
1242
+ * @param options - Optional configuration options for the context.
1243
+ */
1244
+ constructor(req, options) {
1245
+ this.#rawRequest = req;
1246
+ if (options) {
1247
+ this.#executionCtx = options.executionCtx;
1248
+ this.env = options.env;
1249
+ this.#notFoundHandler = options.notFoundHandler;
1250
+ this.#path = options.path;
1251
+ this.#matchResult = options.matchResult;
1252
+ }
1253
+ }
1254
+ /**
1255
+ * `.req` is the instance of {@link HonoRequest}.
1256
+ */
1257
+ get req() {
1258
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
1259
+ return this.#req;
1260
+ }
1261
+ /**
1262
+ * @see {@link https://hono.dev/docs/api/context#event}
1263
+ * The FetchEvent associated with the current request.
1264
+ *
1265
+ * @throws Will throw an error if the context does not have a FetchEvent.
1266
+ */
1267
+ get event() {
1268
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
1269
+ return this.#executionCtx;
1270
+ } else {
1271
+ throw Error("This context has no FetchEvent");
1272
+ }
1273
+ }
1274
+ /**
1275
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
1276
+ * The ExecutionContext associated with the current request.
1277
+ *
1278
+ * @throws Will throw an error if the context does not have an ExecutionContext.
1279
+ */
1280
+ get executionCtx() {
1281
+ if (this.#executionCtx) {
1282
+ return this.#executionCtx;
1283
+ } else {
1284
+ throw Error("This context has no ExecutionContext");
1285
+ }
1286
+ }
1287
+ /**
1288
+ * @see {@link https://hono.dev/docs/api/context#res}
1289
+ * The Response object for the current request.
1290
+ */
1291
+ get res() {
1292
+ return this.#res ||= createResponseInstance(null, {
1293
+ headers: this.#preparedHeaders ??= new Headers()
1294
+ });
1295
+ }
1296
+ /**
1297
+ * Sets the Response object for the current request.
1298
+ *
1299
+ * @param _res - The Response object to set.
1300
+ */
1301
+ set res(_res) {
1302
+ if (this.#res && _res) {
1303
+ _res = createResponseInstance(_res.body, _res);
1304
+ for (const [k, v] of this.#res.headers.entries()) {
1305
+ if (k === "content-type") {
1306
+ continue;
1307
+ }
1308
+ if (k === "set-cookie") {
1309
+ const cookies = this.#res.headers.getSetCookie();
1310
+ _res.headers.delete("set-cookie");
1311
+ for (const cookie of cookies) {
1312
+ _res.headers.append("set-cookie", cookie);
1313
+ }
1314
+ } else {
1315
+ _res.headers.set(k, v);
1316
+ }
1317
+ }
1318
+ }
1319
+ this.#res = _res;
1320
+ this.finalized = true;
1321
+ }
1322
+ /**
1323
+ * `.render()` can create a response within a layout.
1324
+ *
1325
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1326
+ *
1327
+ * @example
1328
+ * ```ts
1329
+ * app.get('/', (c) => {
1330
+ * return c.render('Hello!')
1331
+ * })
1332
+ * ```
1333
+ */
1334
+ render = (...args) => {
1335
+ this.#renderer ??= (content) => this.html(content);
1336
+ return this.#renderer(...args);
1337
+ };
1338
+ /**
1339
+ * Sets the layout for the response.
1340
+ *
1341
+ * @param layout - The layout to set.
1342
+ * @returns The layout function.
1343
+ */
1344
+ setLayout = (layout) => this.#layout = layout;
1345
+ /**
1346
+ * Gets the current layout for the response.
1347
+ *
1348
+ * @returns The current layout function.
1349
+ */
1350
+ getLayout = () => this.#layout;
1351
+ /**
1352
+ * `.setRenderer()` can set the layout in the custom middleware.
1353
+ *
1354
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1355
+ *
1356
+ * @example
1357
+ * ```tsx
1358
+ * app.use('*', async (c, next) => {
1359
+ * c.setRenderer((content) => {
1360
+ * return c.html(
1361
+ * <html>
1362
+ * <body>
1363
+ * <p>{content}</p>
1364
+ * </body>
1365
+ * </html>
1366
+ * )
1367
+ * })
1368
+ * await next()
1369
+ * })
1370
+ * ```
1371
+ */
1372
+ setRenderer = (renderer) => {
1373
+ this.#renderer = renderer;
1374
+ };
1375
+ /**
1376
+ * `.header()` can set headers.
1377
+ *
1378
+ * @see {@link https://hono.dev/docs/api/context#header}
1379
+ *
1380
+ * @example
1381
+ * ```ts
1382
+ * app.get('/welcome', (c) => {
1383
+ * // Set headers
1384
+ * c.header('X-Message', 'Hello!')
1385
+ * c.header('Content-Type', 'text/plain')
1386
+ *
1387
+ * return c.body('Thank you for coming')
1388
+ * })
1389
+ * ```
1390
+ */
1391
+ header = (name, value, options) => {
1392
+ if (this.finalized) {
1393
+ this.#res = createResponseInstance(this.#res.body, this.#res);
1394
+ }
1395
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
1396
+ if (value === void 0) {
1397
+ headers.delete(name);
1398
+ } else if (options?.append) {
1399
+ headers.append(name, value);
1400
+ } else {
1401
+ headers.set(name, value);
1402
+ }
1403
+ };
1404
+ status = (status) => {
1405
+ this.#status = status;
1406
+ };
1407
+ /**
1408
+ * `.set()` can set the value specified by the key.
1409
+ *
1410
+ * @see {@link https://hono.dev/docs/api/context#set-get}
1411
+ *
1412
+ * @example
1413
+ * ```ts
1414
+ * app.use('*', async (c, next) => {
1415
+ * c.set('message', 'Hono is hot!!')
1416
+ * await next()
1417
+ * })
1418
+ * ```
1419
+ */
1420
+ set = (key, value) => {
1421
+ this.#var ??= /* @__PURE__ */ new Map();
1422
+ this.#var.set(key, value);
1423
+ };
1424
+ /**
1425
+ * `.get()` can use the value specified by the key.
1426
+ *
1427
+ * @see {@link https://hono.dev/docs/api/context#set-get}
1428
+ *
1429
+ * @example
1430
+ * ```ts
1431
+ * app.get('/', (c) => {
1432
+ * const message = c.get('message')
1433
+ * return c.text(`The message is "${message}"`)
1434
+ * })
1435
+ * ```
1436
+ */
1437
+ get = (key) => {
1438
+ return this.#var ? this.#var.get(key) : void 0;
1439
+ };
1440
+ /**
1441
+ * `.var` can access the value of a variable.
1442
+ *
1443
+ * @see {@link https://hono.dev/docs/api/context#var}
1444
+ *
1445
+ * @example
1446
+ * ```ts
1447
+ * const result = c.var.client.oneMethod()
1448
+ * ```
1449
+ */
1450
+ // c.var.propName is a read-only
1451
+ get var() {
1452
+ if (!this.#var) {
1453
+ return {};
1454
+ }
1455
+ return Object.fromEntries(this.#var);
1456
+ }
1457
+ #newResponse(data, arg, headers) {
1458
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
1459
+ if (typeof arg === "object" && "headers" in arg) {
1460
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
1461
+ for (const [key, value] of argHeaders) {
1462
+ if (key.toLowerCase() === "set-cookie") {
1463
+ responseHeaders.append(key, value);
1464
+ } else {
1465
+ responseHeaders.set(key, value);
1466
+ }
1467
+ }
1468
+ }
1469
+ if (headers) {
1470
+ for (const [k, v] of Object.entries(headers)) {
1471
+ if (typeof v === "string") {
1472
+ responseHeaders.set(k, v);
1473
+ } else {
1474
+ responseHeaders.delete(k);
1475
+ for (const v2 of v) {
1476
+ responseHeaders.append(k, v2);
1477
+ }
1478
+ }
1479
+ }
1480
+ }
1481
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
1482
+ return createResponseInstance(data, { status, headers: responseHeaders });
1483
+ }
1484
+ newResponse = (...args) => this.#newResponse(...args);
1485
+ /**
1486
+ * `.body()` can return the HTTP response.
1487
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
1488
+ * This can also be set in `.text()`, `.json()` and so on.
1489
+ *
1490
+ * @see {@link https://hono.dev/docs/api/context#body}
1491
+ *
1492
+ * @example
1493
+ * ```ts
1494
+ * app.get('/welcome', (c) => {
1495
+ * // Set headers
1496
+ * c.header('X-Message', 'Hello!')
1497
+ * c.header('Content-Type', 'text/plain')
1498
+ * // Set HTTP status code
1499
+ * c.status(201)
1500
+ *
1501
+ * // Return the response body
1502
+ * return c.body('Thank you for coming')
1503
+ * })
1504
+ * ```
1505
+ */
1506
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
1507
+ /**
1508
+ * `.text()` can render text as `Content-Type:text/plain`.
1509
+ *
1510
+ * @see {@link https://hono.dev/docs/api/context#text}
1511
+ *
1512
+ * @example
1513
+ * ```ts
1514
+ * app.get('/say', (c) => {
1515
+ * return c.text('Hello!')
1516
+ * })
1517
+ * ```
1518
+ */
1519
+ text = (text, arg, headers) => {
1520
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
1521
+ text,
1522
+ arg,
1523
+ setDefaultContentType(TEXT_PLAIN, headers)
1524
+ );
1525
+ };
1526
+ /**
1527
+ * `.json()` can render JSON as `Content-Type:application/json`.
1528
+ *
1529
+ * @see {@link https://hono.dev/docs/api/context#json}
1530
+ *
1531
+ * @example
1532
+ * ```ts
1533
+ * app.get('/api', (c) => {
1534
+ * return c.json({ message: 'Hello!' })
1535
+ * })
1536
+ * ```
1537
+ */
1538
+ json = (object, arg, headers) => {
1539
+ return this.#newResponse(
1540
+ JSON.stringify(object),
1541
+ arg,
1542
+ setDefaultContentType("application/json", headers)
1543
+ );
1544
+ };
1545
+ html = (html, arg, headers) => {
1546
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
1547
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
1548
+ };
1549
+ /**
1550
+ * `.redirect()` can Redirect, default status code is 302.
1551
+ *
1552
+ * @see {@link https://hono.dev/docs/api/context#redirect}
1553
+ *
1554
+ * @example
1555
+ * ```ts
1556
+ * app.get('/redirect', (c) => {
1557
+ * return c.redirect('/')
1558
+ * })
1559
+ * app.get('/redirect-permanently', (c) => {
1560
+ * return c.redirect('/', 301)
1561
+ * })
1562
+ * ```
1563
+ */
1564
+ redirect = (location, status) => {
1565
+ const locationString = String(location);
1566
+ this.header(
1567
+ "Location",
1568
+ // Multibyes should be encoded
1569
+ // eslint-disable-next-line no-control-regex
1570
+ !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
1571
+ );
1572
+ return this.newResponse(null, status ?? 302);
1573
+ };
1574
+ /**
1575
+ * `.notFound()` can return the Not Found Response.
1576
+ *
1577
+ * @see {@link https://hono.dev/docs/api/context#notfound}
1578
+ *
1579
+ * @example
1580
+ * ```ts
1581
+ * app.get('/notfound', (c) => {
1582
+ * return c.notFound()
1583
+ * })
1584
+ * ```
1585
+ */
1586
+ notFound = () => {
1587
+ this.#notFoundHandler ??= () => createResponseInstance();
1588
+ return this.#notFoundHandler(this);
1589
+ };
1590
+ };
1591
+
1592
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/router.js
1593
+ var METHOD_NAME_ALL = "ALL";
1594
+ var METHOD_NAME_ALL_LOWERCASE = "all";
1595
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1596
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1597
+ var UnsupportedPathError = class extends Error {
1598
+ };
1599
+
1600
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/utils/constants.js
1601
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1602
+
1603
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/hono-base.js
1604
+ var notFoundHandler = (c) => {
1605
+ return c.text("404 Not Found", 404);
1606
+ };
1607
+ var errorHandler = (err, c) => {
1608
+ if ("getResponse" in err) {
1609
+ const res = err.getResponse();
1610
+ return c.newResponse(res.body, res);
1611
+ }
1612
+ console.error(err);
1613
+ return c.text("Internal Server Error", 500);
1614
+ };
1615
+ var Hono = class _Hono {
1616
+ get;
1617
+ post;
1618
+ put;
1619
+ delete;
1620
+ options;
1621
+ patch;
1622
+ all;
1623
+ on;
1624
+ use;
1625
+ /*
1626
+ This class is like an abstract class and does not have a router.
1627
+ To use it, inherit the class and implement router in the constructor.
1628
+ */
1629
+ router;
1630
+ getPath;
1631
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1632
+ _basePath = "/";
1633
+ #path = "/";
1634
+ routes = [];
1635
+ constructor(options = {}) {
1636
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
1637
+ allMethods.forEach((method) => {
1638
+ this[method] = (args1, ...args) => {
1639
+ if (typeof args1 === "string") {
1640
+ this.#path = args1;
1641
+ } else {
1642
+ this.#addRoute(method, this.#path, args1);
1643
+ }
1644
+ args.forEach((handler) => {
1645
+ this.#addRoute(method, this.#path, handler);
1646
+ });
1647
+ return this;
1648
+ };
1649
+ });
1650
+ this.on = (method, path, ...handlers) => {
1651
+ for (const p of [path].flat()) {
1652
+ this.#path = p;
1653
+ for (const m of [method].flat()) {
1654
+ handlers.map((handler) => {
1655
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
1656
+ });
1657
+ }
1658
+ }
1659
+ return this;
1660
+ };
1661
+ this.use = (arg1, ...handlers) => {
1662
+ if (typeof arg1 === "string") {
1663
+ this.#path = arg1;
1664
+ } else {
1665
+ this.#path = "*";
1666
+ handlers.unshift(arg1);
1667
+ }
1668
+ handlers.forEach((handler) => {
1669
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1670
+ });
1671
+ return this;
1672
+ };
1673
+ const { strict, ...optionsWithoutStrict } = options;
1674
+ Object.assign(this, optionsWithoutStrict);
1675
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1676
+ }
1677
+ #clone() {
1678
+ const clone = new _Hono({
1679
+ router: this.router,
1680
+ getPath: this.getPath
1681
+ });
1682
+ clone.errorHandler = this.errorHandler;
1683
+ clone.#notFoundHandler = this.#notFoundHandler;
1684
+ clone.routes = this.routes;
1685
+ return clone;
1686
+ }
1687
+ #notFoundHandler = notFoundHandler;
1688
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1689
+ errorHandler = errorHandler;
1690
+ /**
1691
+ * `.route()` allows grouping other Hono instance in routes.
1692
+ *
1693
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
1694
+ *
1695
+ * @param {string} path - base Path
1696
+ * @param {Hono} app - other Hono instance
1697
+ * @returns {Hono} routed Hono instance
1698
+ *
1699
+ * @example
1700
+ * ```ts
1701
+ * const app = new Hono()
1702
+ * const app2 = new Hono()
1703
+ *
1704
+ * app2.get("/user", (c) => c.text("user"))
1705
+ * app.route("/api", app2) // GET /api/user
1706
+ * ```
1707
+ */
1708
+ route(path, app) {
1709
+ const subApp = this.basePath(path);
1710
+ app.routes.map((r) => {
1711
+ let handler;
1712
+ if (app.errorHandler === errorHandler) {
1713
+ handler = r.handler;
1714
+ } else {
1715
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
1716
+ handler[COMPOSED_HANDLER] = r.handler;
1717
+ }
1718
+ subApp.#addRoute(r.method, r.path, handler);
1719
+ });
1720
+ return this;
1721
+ }
1722
+ /**
1723
+ * `.basePath()` allows base paths to be specified.
1724
+ *
1725
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
1726
+ *
1727
+ * @param {string} path - base Path
1728
+ * @returns {Hono} changed Hono instance
1729
+ *
1730
+ * @example
1731
+ * ```ts
1732
+ * const api = new Hono().basePath('/api')
1733
+ * ```
1734
+ */
1735
+ basePath(path) {
1736
+ const subApp = this.#clone();
1737
+ subApp._basePath = mergePath(this._basePath, path);
1738
+ return subApp;
1739
+ }
1740
+ /**
1741
+ * `.onError()` handles an error and returns a customized Response.
1742
+ *
1743
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
1744
+ *
1745
+ * @param {ErrorHandler} handler - request Handler for error
1746
+ * @returns {Hono} changed Hono instance
1747
+ *
1748
+ * @example
1749
+ * ```ts
1750
+ * app.onError((err, c) => {
1751
+ * console.error(`${err}`)
1752
+ * return c.text('Custom Error Message', 500)
1753
+ * })
1754
+ * ```
1755
+ */
1756
+ onError = (handler) => {
1757
+ this.errorHandler = handler;
1758
+ return this;
1759
+ };
1760
+ /**
1761
+ * `.notFound()` allows you to customize a Not Found Response.
1762
+ *
1763
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
1764
+ *
1765
+ * @param {NotFoundHandler} handler - request handler for not-found
1766
+ * @returns {Hono} changed Hono instance
1767
+ *
1768
+ * @example
1769
+ * ```ts
1770
+ * app.notFound((c) => {
1771
+ * return c.text('Custom 404 Message', 404)
1772
+ * })
1773
+ * ```
1774
+ */
1775
+ notFound = (handler) => {
1776
+ this.#notFoundHandler = handler;
1777
+ return this;
1778
+ };
1779
+ /**
1780
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
1781
+ *
1782
+ * @see {@link https://hono.dev/docs/api/hono#mount}
1783
+ *
1784
+ * @param {string} path - base Path
1785
+ * @param {Function} applicationHandler - other Request Handler
1786
+ * @param {MountOptions} [options] - options of `.mount()`
1787
+ * @returns {Hono} mounted Hono instance
1788
+ *
1789
+ * @example
1790
+ * ```ts
1791
+ * import { Router as IttyRouter } from 'itty-router'
1792
+ * import { Hono } from 'hono'
1793
+ * // Create itty-router application
1794
+ * const ittyRouter = IttyRouter()
1795
+ * // GET /itty-router/hello
1796
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
1797
+ *
1798
+ * const app = new Hono()
1799
+ * app.mount('/itty-router', ittyRouter.handle)
1800
+ * ```
1801
+ *
1802
+ * @example
1803
+ * ```ts
1804
+ * const app = new Hono()
1805
+ * // Send the request to another application without modification.
1806
+ * app.mount('/app', anotherApp, {
1807
+ * replaceRequest: (req) => req,
1808
+ * })
1809
+ * ```
1810
+ */
1811
+ mount(path, applicationHandler, options) {
1812
+ let replaceRequest;
1813
+ let optionHandler;
1814
+ if (options) {
1815
+ if (typeof options === "function") {
1816
+ optionHandler = options;
1817
+ } else {
1818
+ optionHandler = options.optionHandler;
1819
+ if (options.replaceRequest === false) {
1820
+ replaceRequest = (request) => request;
1821
+ } else {
1822
+ replaceRequest = options.replaceRequest;
1823
+ }
1824
+ }
1825
+ }
1826
+ const getOptions = optionHandler ? (c) => {
1827
+ const options2 = optionHandler(c);
1828
+ return Array.isArray(options2) ? options2 : [options2];
1829
+ } : (c) => {
1830
+ let executionContext = void 0;
1831
+ try {
1832
+ executionContext = c.executionCtx;
1833
+ } catch {
1834
+ }
1835
+ return [c.env, executionContext];
1836
+ };
1837
+ replaceRequest ||= (() => {
1838
+ const mergedPath = mergePath(this._basePath, path);
1839
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1840
+ return (request) => {
1841
+ const url = new URL(request.url);
1842
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
1843
+ return new Request(url, request);
1844
+ };
1845
+ })();
1846
+ const handler = async (c, next) => {
1847
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1848
+ if (res) {
1849
+ return res;
1850
+ }
1851
+ await next();
1852
+ };
1853
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
1854
+ return this;
1855
+ }
1856
+ #addRoute(method, path, handler) {
1857
+ method = method.toUpperCase();
1858
+ path = mergePath(this._basePath, path);
1859
+ const r = { basePath: this._basePath, path, method, handler };
1860
+ this.router.add(method, path, [handler, r]);
1861
+ this.routes.push(r);
1862
+ }
1863
+ #handleError(err, c) {
1864
+ if (err instanceof Error) {
1865
+ return this.errorHandler(err, c);
1866
+ }
1867
+ throw err;
1868
+ }
1869
+ #dispatch(request, executionCtx, env, method) {
1870
+ if (method === "HEAD") {
1871
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1872
+ }
1873
+ const path = this.getPath(request, { env });
1874
+ const matchResult = this.router.match(method, path);
1875
+ const c = new Context(request, {
1876
+ path,
1877
+ matchResult,
1878
+ env,
1879
+ executionCtx,
1880
+ notFoundHandler: this.#notFoundHandler
1881
+ });
1882
+ if (matchResult[0].length === 1) {
1883
+ let res;
1884
+ try {
1885
+ res = matchResult[0][0][0][0](c, async () => {
1886
+ c.res = await this.#notFoundHandler(c);
1887
+ });
1888
+ } catch (err) {
1889
+ return this.#handleError(err, c);
1890
+ }
1891
+ return res instanceof Promise ? res.then(
1892
+ (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
1893
+ ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
1894
+ }
1895
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
1896
+ return (async () => {
1897
+ try {
1898
+ const context = await composed(c);
1899
+ if (!context.finalized) {
1900
+ throw new Error(
1901
+ "Context is not finalized. Did you forget to return a Response object or `await next()`?"
1902
+ );
1903
+ }
1904
+ return context.res;
1905
+ } catch (err) {
1906
+ return this.#handleError(err, c);
1907
+ }
1908
+ })();
1909
+ }
1910
+ /**
1911
+ * `.fetch()` will be entry point of your app.
1912
+ *
1913
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
1914
+ *
1915
+ * @param {Request} request - request Object of request
1916
+ * @param {Env} Env - env Object
1917
+ * @param {ExecutionContext} - context of execution
1918
+ * @returns {Response | Promise<Response>} response of request
1919
+ *
1920
+ */
1921
+ fetch = (request, ...rest) => {
1922
+ return this.#dispatch(request, rest[1], rest[0], request.method);
1923
+ };
1924
+ /**
1925
+ * `.request()` is a useful method for testing.
1926
+ * You can pass a URL or pathname to send a GET request.
1927
+ * app will return a Response object.
1928
+ * ```ts
1929
+ * test('GET /hello is ok', async () => {
1930
+ * const res = await app.request('/hello')
1931
+ * expect(res.status).toBe(200)
1932
+ * })
1933
+ * ```
1934
+ * @see https://hono.dev/docs/api/hono#request
1935
+ */
1936
+ request = (input, requestInit, Env, executionCtx) => {
1937
+ if (input instanceof Request) {
1938
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
1939
+ }
1940
+ input = input.toString();
1941
+ return this.fetch(
1942
+ new Request(
1943
+ /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
1944
+ requestInit
1945
+ ),
1946
+ Env,
1947
+ executionCtx
1948
+ );
1949
+ };
1950
+ /**
1951
+ * `.fire()` automatically adds a global fetch event listener.
1952
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
1953
+ * @deprecated
1954
+ * Use `fire` from `hono/service-worker` instead.
1955
+ * ```ts
1956
+ * import { Hono } from 'hono'
1957
+ * import { fire } from 'hono/service-worker'
1958
+ *
1959
+ * const app = new Hono()
1960
+ * // ...
1961
+ * fire(app)
1962
+ * ```
1963
+ * @see https://hono.dev/docs/api/hono#fire
1964
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
1965
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
1966
+ */
1967
+ fire = () => {
1968
+ addEventListener("fetch", (event) => {
1969
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
1970
+ });
1971
+ };
1972
+ };
1973
+
1974
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/router/reg-exp-router/matcher.js
1975
+ var emptyParam = [];
1976
+ function match(method, path) {
1977
+ const matchers = this.buildAllMatchers();
1978
+ const match2 = ((method2, path2) => {
1979
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
1980
+ const staticMatch = matcher[2][path2];
1981
+ if (staticMatch) {
1982
+ return staticMatch;
1983
+ }
1984
+ const match3 = path2.match(matcher[0]);
1985
+ if (!match3) {
1986
+ return [[], emptyParam];
1987
+ }
1988
+ const index = match3.indexOf("", 1);
1989
+ return [matcher[1][index], match3];
1990
+ });
1991
+ this.match = match2;
1992
+ return match2(method, path);
1993
+ }
1994
+
1995
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/router/reg-exp-router/node.js
1996
+ var LABEL_REG_EXP_STR = "[^/]+";
1997
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
1998
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
1999
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
2000
+ var regExpMetaChars = new Set(".\\+*[^]$()");
2001
+ function compareKey(a, b) {
2002
+ if (a.length === 1) {
2003
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
2004
+ }
2005
+ if (b.length === 1) {
2006
+ return 1;
2007
+ }
2008
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
2009
+ return 1;
2010
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
2011
+ return -1;
2012
+ }
2013
+ if (a === LABEL_REG_EXP_STR) {
2014
+ return 1;
2015
+ } else if (b === LABEL_REG_EXP_STR) {
2016
+ return -1;
2017
+ }
2018
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
2019
+ }
2020
+ var Node = class _Node {
2021
+ #index;
2022
+ #varIndex;
2023
+ #children = /* @__PURE__ */ Object.create(null);
2024
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
2025
+ if (tokens.length === 0) {
2026
+ if (this.#index !== void 0) {
2027
+ throw PATH_ERROR;
2028
+ }
2029
+ if (pathErrorCheckOnly) {
2030
+ return;
2031
+ }
2032
+ this.#index = index;
2033
+ return;
2034
+ }
2035
+ const [token, ...restTokens] = tokens;
2036
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2037
+ let node;
2038
+ if (pattern) {
2039
+ const name = pattern[1];
2040
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
2041
+ if (name && pattern[2]) {
2042
+ if (regexpStr === ".*") {
2043
+ throw PATH_ERROR;
2044
+ }
2045
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
2046
+ if (/\((?!\?:)/.test(regexpStr)) {
2047
+ throw PATH_ERROR;
2048
+ }
2049
+ }
2050
+ node = this.#children[regexpStr];
2051
+ if (!node) {
2052
+ if (Object.keys(this.#children).some(
2053
+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2054
+ )) {
2055
+ throw PATH_ERROR;
2056
+ }
2057
+ if (pathErrorCheckOnly) {
2058
+ return;
2059
+ }
2060
+ node = this.#children[regexpStr] = new _Node();
2061
+ if (name !== "") {
2062
+ node.#varIndex = context.varIndex++;
2063
+ }
2064
+ }
2065
+ if (!pathErrorCheckOnly && name !== "") {
2066
+ paramMap.push([name, node.#varIndex]);
2067
+ }
2068
+ } else {
2069
+ node = this.#children[token];
2070
+ if (!node) {
2071
+ if (Object.keys(this.#children).some(
2072
+ (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2073
+ )) {
2074
+ throw PATH_ERROR;
2075
+ }
2076
+ if (pathErrorCheckOnly) {
2077
+ return;
2078
+ }
2079
+ node = this.#children[token] = new _Node();
2080
+ }
2081
+ }
2082
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
2083
+ }
2084
+ buildRegExpStr() {
2085
+ const childKeys = Object.keys(this.#children).sort(compareKey);
2086
+ const strList = childKeys.map((k) => {
2087
+ const c = this.#children[k];
2088
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
2089
+ });
2090
+ if (typeof this.#index === "number") {
2091
+ strList.unshift(`#${this.#index}`);
2092
+ }
2093
+ if (strList.length === 0) {
2094
+ return "";
2095
+ }
2096
+ if (strList.length === 1) {
2097
+ return strList[0];
2098
+ }
2099
+ return "(?:" + strList.join("|") + ")";
2100
+ }
2101
+ };
2102
+
2103
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/router/reg-exp-router/trie.js
2104
+ var Trie = class {
2105
+ #context = { varIndex: 0 };
2106
+ #root = new Node();
2107
+ insert(path, index, pathErrorCheckOnly) {
2108
+ const paramAssoc = [];
2109
+ const groups = [];
2110
+ for (let i = 0; ; ) {
2111
+ let replaced = false;
2112
+ path = path.replace(/\{[^}]+\}/g, (m) => {
2113
+ const mark = `@\\${i}`;
2114
+ groups[i] = [mark, m];
2115
+ i++;
2116
+ replaced = true;
2117
+ return mark;
2118
+ });
2119
+ if (!replaced) {
2120
+ break;
2121
+ }
2122
+ }
2123
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
2124
+ for (let i = groups.length - 1; i >= 0; i--) {
2125
+ const [mark] = groups[i];
2126
+ for (let j = tokens.length - 1; j >= 0; j--) {
2127
+ if (tokens[j].indexOf(mark) !== -1) {
2128
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
2129
+ break;
2130
+ }
2131
+ }
2132
+ }
2133
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
2134
+ return paramAssoc;
2135
+ }
2136
+ buildRegExp() {
2137
+ let regexp = this.#root.buildRegExpStr();
2138
+ if (regexp === "") {
2139
+ return [/^$/, [], []];
2140
+ }
2141
+ let captureIndex = 0;
2142
+ const indexReplacementMap = [];
2143
+ const paramReplacementMap = [];
2144
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
2145
+ if (handlerIndex !== void 0) {
2146
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
2147
+ return "$()";
2148
+ }
2149
+ if (paramIndex !== void 0) {
2150
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
2151
+ return "";
2152
+ }
2153
+ return "";
2154
+ });
2155
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
2156
+ }
2157
+ };
2158
+
2159
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/router/reg-exp-router/router.js
2160
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
2161
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2162
+ function buildWildcardRegExp(path) {
2163
+ return wildcardRegExpCache[path] ??= new RegExp(
2164
+ path === "*" ? "" : `^${path.replace(
2165
+ /\/\*$|([.\\+*[^\]$()])/g,
2166
+ (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
2167
+ )}$`
2168
+ );
2169
+ }
2170
+ function clearWildcardRegExpCache() {
2171
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2172
+ }
2173
+ function buildMatcherFromPreprocessedRoutes(routes) {
2174
+ const trie = new Trie();
2175
+ const handlerData = [];
2176
+ if (routes.length === 0) {
2177
+ return nullMatcher;
2178
+ }
2179
+ const routesWithStaticPathFlag = routes.map(
2180
+ (route) => [!/\*|\/:/.test(route[0]), ...route]
2181
+ ).sort(
2182
+ ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
2183
+ );
2184
+ const staticMap = /* @__PURE__ */ Object.create(null);
2185
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
2186
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
2187
+ if (pathErrorCheckOnly) {
2188
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
2189
+ } else {
2190
+ j++;
2191
+ }
2192
+ let paramAssoc;
2193
+ try {
2194
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
2195
+ } catch (e) {
2196
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
2197
+ }
2198
+ if (pathErrorCheckOnly) {
2199
+ continue;
2200
+ }
2201
+ handlerData[j] = handlers.map(([h, paramCount]) => {
2202
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
2203
+ paramCount -= 1;
2204
+ for (; paramCount >= 0; paramCount--) {
2205
+ const [key, value] = paramAssoc[paramCount];
2206
+ paramIndexMap[key] = value;
2207
+ }
2208
+ return [h, paramIndexMap];
2209
+ });
2210
+ }
2211
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
2212
+ for (let i = 0, len = handlerData.length; i < len; i++) {
2213
+ for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
2214
+ const map = handlerData[i][j]?.[1];
2215
+ if (!map) {
2216
+ continue;
2217
+ }
2218
+ const keys = Object.keys(map);
2219
+ for (let k = 0, len3 = keys.length; k < len3; k++) {
2220
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
2221
+ }
2222
+ }
2223
+ }
2224
+ const handlerMap = [];
2225
+ for (const i in indexReplacementMap) {
2226
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
2227
+ }
2228
+ return [regexp, handlerMap, staticMap];
2229
+ }
2230
+ function findMiddleware(middleware, path) {
2231
+ if (!middleware) {
2232
+ return void 0;
2233
+ }
2234
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
2235
+ if (buildWildcardRegExp(k).test(path)) {
2236
+ return [...middleware[k]];
2237
+ }
2238
+ }
2239
+ return void 0;
2240
+ }
2241
+ var RegExpRouter = class {
2242
+ name = "RegExpRouter";
2243
+ #middleware;
2244
+ #routes;
2245
+ constructor() {
2246
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2247
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2248
+ }
2249
+ add(method, path, handler) {
2250
+ const middleware = this.#middleware;
2251
+ const routes = this.#routes;
2252
+ if (!middleware || !routes) {
2253
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2254
+ }
2255
+ if (!middleware[method]) {
2256
+ ;
2257
+ [middleware, routes].forEach((handlerMap) => {
2258
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
2259
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
2260
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
2261
+ });
2262
+ });
2263
+ }
2264
+ if (path === "/*") {
2265
+ path = "*";
2266
+ }
2267
+ const paramCount = (path.match(/\/:/g) || []).length;
2268
+ if (/\*$/.test(path)) {
2269
+ const re = buildWildcardRegExp(path);
2270
+ if (method === METHOD_NAME_ALL) {
2271
+ Object.keys(middleware).forEach((m) => {
2272
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2273
+ });
2274
+ } else {
2275
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2276
+ }
2277
+ Object.keys(middleware).forEach((m) => {
2278
+ if (method === METHOD_NAME_ALL || method === m) {
2279
+ Object.keys(middleware[m]).forEach((p) => {
2280
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
2281
+ });
2282
+ }
2283
+ });
2284
+ Object.keys(routes).forEach((m) => {
2285
+ if (method === METHOD_NAME_ALL || method === m) {
2286
+ Object.keys(routes[m]).forEach(
2287
+ (p) => re.test(p) && routes[m][p].push([handler, paramCount])
2288
+ );
2289
+ }
2290
+ });
2291
+ return;
2292
+ }
2293
+ const paths = checkOptionalParameter(path) || [path];
2294
+ for (let i = 0, len = paths.length; i < len; i++) {
2295
+ const path2 = paths[i];
2296
+ Object.keys(routes).forEach((m) => {
2297
+ if (method === METHOD_NAME_ALL || method === m) {
2298
+ routes[m][path2] ||= [
2299
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
2300
+ ];
2301
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
2302
+ }
2303
+ });
2304
+ }
2305
+ }
2306
+ match = match;
2307
+ buildAllMatchers() {
2308
+ const matchers = /* @__PURE__ */ Object.create(null);
2309
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
2310
+ matchers[method] ||= this.#buildMatcher(method);
2311
+ });
2312
+ this.#middleware = this.#routes = void 0;
2313
+ clearWildcardRegExpCache();
2314
+ return matchers;
2315
+ }
2316
+ #buildMatcher(method) {
2317
+ const routes = [];
2318
+ let hasOwnRoute = method === METHOD_NAME_ALL;
2319
+ [this.#middleware, this.#routes].forEach((r) => {
2320
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
2321
+ if (ownRoute.length !== 0) {
2322
+ hasOwnRoute ||= true;
2323
+ routes.push(...ownRoute);
2324
+ } else if (method !== METHOD_NAME_ALL) {
2325
+ routes.push(
2326
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
2327
+ );
2328
+ }
2329
+ });
2330
+ if (!hasOwnRoute) {
2331
+ return null;
2332
+ } else {
2333
+ return buildMatcherFromPreprocessedRoutes(routes);
2334
+ }
2335
+ }
2336
+ };
2337
+
2338
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/router/smart-router/router.js
2339
+ var SmartRouter = class {
2340
+ name = "SmartRouter";
2341
+ #routers = [];
2342
+ #routes = [];
2343
+ constructor(init) {
2344
+ this.#routers = init.routers;
2345
+ }
2346
+ add(method, path, handler) {
2347
+ if (!this.#routes) {
2348
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2349
+ }
2350
+ this.#routes.push([method, path, handler]);
2351
+ }
2352
+ match(method, path) {
2353
+ if (!this.#routes) {
2354
+ throw new Error("Fatal error");
2355
+ }
2356
+ const routers = this.#routers;
2357
+ const routes = this.#routes;
2358
+ const len = routers.length;
2359
+ let i = 0;
2360
+ let res;
2361
+ for (; i < len; i++) {
2362
+ const router = routers[i];
2363
+ try {
2364
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
2365
+ router.add(...routes[i2]);
2366
+ }
2367
+ res = router.match(method, path);
2368
+ } catch (e) {
2369
+ if (e instanceof UnsupportedPathError) {
2370
+ continue;
2371
+ }
2372
+ throw e;
2373
+ }
2374
+ this.match = router.match.bind(router);
2375
+ this.#routers = [router];
2376
+ this.#routes = void 0;
2377
+ break;
2378
+ }
2379
+ if (i === len) {
2380
+ throw new Error("Fatal error");
2381
+ }
2382
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
2383
+ return res;
2384
+ }
2385
+ get activeRouter() {
2386
+ if (this.#routes || this.#routers.length !== 1) {
2387
+ throw new Error("No active router has been determined yet.");
2388
+ }
2389
+ return this.#routers[0];
2390
+ }
2391
+ };
2392
+
2393
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/router/trie-router/node.js
2394
+ var emptyParams = /* @__PURE__ */ Object.create(null);
2395
+ var hasChildren = (children) => {
2396
+ for (const _ in children) {
2397
+ return true;
2398
+ }
2399
+ return false;
2400
+ };
2401
+ var Node2 = class _Node2 {
2402
+ #methods;
2403
+ #children;
2404
+ #patterns;
2405
+ #order = 0;
2406
+ #params = emptyParams;
2407
+ constructor(method, handler, children) {
2408
+ this.#children = children || /* @__PURE__ */ Object.create(null);
2409
+ this.#methods = [];
2410
+ if (method && handler) {
2411
+ const m = /* @__PURE__ */ Object.create(null);
2412
+ m[method] = { handler, possibleKeys: [], score: 0 };
2413
+ this.#methods = [m];
2414
+ }
2415
+ this.#patterns = [];
2416
+ }
2417
+ insert(method, path, handler) {
2418
+ this.#order = ++this.#order;
2419
+ let curNode = this;
2420
+ const parts = splitRoutingPath(path);
2421
+ const possibleKeys = [];
2422
+ for (let i = 0, len = parts.length; i < len; i++) {
2423
+ const p = parts[i];
2424
+ const nextP = parts[i + 1];
2425
+ const pattern = getPattern(p, nextP);
2426
+ const key = Array.isArray(pattern) ? pattern[0] : p;
2427
+ if (key in curNode.#children) {
2428
+ curNode = curNode.#children[key];
2429
+ if (pattern) {
2430
+ possibleKeys.push(pattern[1]);
2431
+ }
2432
+ continue;
2433
+ }
2434
+ curNode.#children[key] = new _Node2();
2435
+ if (pattern) {
2436
+ curNode.#patterns.push(pattern);
2437
+ possibleKeys.push(pattern[1]);
2438
+ }
2439
+ curNode = curNode.#children[key];
2440
+ }
2441
+ curNode.#methods.push({
2442
+ [method]: {
2443
+ handler,
2444
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
2445
+ score: this.#order
2446
+ }
2447
+ });
2448
+ return curNode;
2449
+ }
2450
+ #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
2451
+ for (let i = 0, len = node.#methods.length; i < len; i++) {
2452
+ const m = node.#methods[i];
2453
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
2454
+ const processedSet = {};
2455
+ if (handlerSet !== void 0) {
2456
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
2457
+ handlerSets.push(handlerSet);
2458
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
2459
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
2460
+ const key = handlerSet.possibleKeys[i2];
2461
+ const processed = processedSet[handlerSet.score];
2462
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
2463
+ processedSet[handlerSet.score] = true;
2464
+ }
2465
+ }
2466
+ }
2467
+ }
2468
+ }
2469
+ search(method, path) {
2470
+ const handlerSets = [];
2471
+ this.#params = emptyParams;
2472
+ const curNode = this;
2473
+ let curNodes = [curNode];
2474
+ const parts = splitPath(path);
2475
+ const curNodesQueue = [];
2476
+ const len = parts.length;
2477
+ let partOffsets = null;
2478
+ for (let i = 0; i < len; i++) {
2479
+ const part = parts[i];
2480
+ const isLast = i === len - 1;
2481
+ const tempNodes = [];
2482
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
2483
+ const node = curNodes[j];
2484
+ const nextNode = node.#children[part];
2485
+ if (nextNode) {
2486
+ nextNode.#params = node.#params;
2487
+ if (isLast) {
2488
+ if (nextNode.#children["*"]) {
2489
+ this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
2490
+ }
2491
+ this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
2492
+ } else {
2493
+ tempNodes.push(nextNode);
2494
+ }
2495
+ }
2496
+ for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
2497
+ const pattern = node.#patterns[k];
2498
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
2499
+ if (pattern === "*") {
2500
+ const astNode = node.#children["*"];
2501
+ if (astNode) {
2502
+ this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
2503
+ astNode.#params = params;
2504
+ tempNodes.push(astNode);
2505
+ }
2506
+ continue;
2507
+ }
2508
+ const [key, name, matcher] = pattern;
2509
+ if (!part && !(matcher instanceof RegExp)) {
2510
+ continue;
2511
+ }
2512
+ const child = node.#children[key];
2513
+ if (matcher instanceof RegExp) {
2514
+ if (partOffsets === null) {
2515
+ partOffsets = new Array(len);
2516
+ let offset = path[0] === "/" ? 1 : 0;
2517
+ for (let p = 0; p < len; p++) {
2518
+ partOffsets[p] = offset;
2519
+ offset += parts[p].length + 1;
2520
+ }
2521
+ }
2522
+ const restPathString = path.substring(partOffsets[i]);
2523
+ const m = matcher.exec(restPathString);
2524
+ if (m) {
2525
+ params[name] = m[0];
2526
+ this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
2527
+ if (hasChildren(child.#children)) {
2528
+ child.#params = params;
2529
+ const componentCount = m[0].match(/\//)?.length ?? 0;
2530
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
2531
+ targetCurNodes.push(child);
2532
+ }
2533
+ continue;
2534
+ }
2535
+ }
2536
+ if (matcher === true || matcher.test(part)) {
2537
+ params[name] = part;
2538
+ if (isLast) {
2539
+ this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
2540
+ if (child.#children["*"]) {
2541
+ this.#pushHandlerSets(
2542
+ handlerSets,
2543
+ child.#children["*"],
2544
+ method,
2545
+ params,
2546
+ node.#params
2547
+ );
2548
+ }
2549
+ } else {
2550
+ child.#params = params;
2551
+ tempNodes.push(child);
2552
+ }
2553
+ }
2554
+ }
2555
+ }
2556
+ const shifted = curNodesQueue.shift();
2557
+ curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
2558
+ }
2559
+ if (handlerSets.length > 1) {
2560
+ handlerSets.sort((a, b) => {
2561
+ return a.score - b.score;
2562
+ });
2563
+ }
2564
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
2565
+ }
2566
+ };
2567
+
2568
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/router/trie-router/router.js
2569
+ var TrieRouter = class {
2570
+ name = "TrieRouter";
2571
+ #node;
2572
+ constructor() {
2573
+ this.#node = new Node2();
2574
+ }
2575
+ add(method, path, handler) {
2576
+ const results = checkOptionalParameter(path);
2577
+ if (results) {
2578
+ for (let i = 0, len = results.length; i < len; i++) {
2579
+ this.#node.insert(method, results[i], handler);
2580
+ }
2581
+ return;
2582
+ }
2583
+ this.#node.insert(method, path, handler);
2584
+ }
2585
+ match(method, path) {
2586
+ return this.#node.search(method, path);
2587
+ }
2588
+ };
2589
+
2590
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/hono.js
2591
+ var Hono2 = class extends Hono {
2592
+ /**
2593
+ * Creates an instance of the Hono class.
2594
+ *
2595
+ * @param options - Optional configuration options for the Hono instance.
2596
+ */
2597
+ constructor(options = {}) {
2598
+ super(options);
2599
+ this.router = options.router ?? new SmartRouter({
2600
+ routers: [new RegExpRouter(), new TrieRouter()]
2601
+ });
2602
+ }
2603
+ };
2604
+
2605
+ // ../../node_modules/.pnpm/hono@4.12.3/node_modules/hono/dist/middleware/cors/index.js
2606
+ var cors = (options) => {
2607
+ const defaults = {
2608
+ origin: "*",
2609
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
2610
+ allowHeaders: [],
2611
+ exposeHeaders: []
2612
+ };
2613
+ const opts = {
2614
+ ...defaults,
2615
+ ...options
2616
+ };
2617
+ const findAllowOrigin = ((optsOrigin) => {
2618
+ if (typeof optsOrigin === "string") {
2619
+ if (optsOrigin === "*") {
2620
+ return () => optsOrigin;
2621
+ } else {
2622
+ return (origin) => optsOrigin === origin ? origin : null;
2623
+ }
2624
+ } else if (typeof optsOrigin === "function") {
2625
+ return optsOrigin;
2626
+ } else {
2627
+ return (origin) => optsOrigin.includes(origin) ? origin : null;
2628
+ }
2629
+ })(opts.origin);
2630
+ const findAllowMethods = ((optsAllowMethods) => {
2631
+ if (typeof optsAllowMethods === "function") {
2632
+ return optsAllowMethods;
2633
+ } else if (Array.isArray(optsAllowMethods)) {
2634
+ return () => optsAllowMethods;
2635
+ } else {
2636
+ return () => [];
2637
+ }
2638
+ })(opts.allowMethods);
2639
+ return async function cors2(c, next) {
2640
+ function set(key, value) {
2641
+ c.res.headers.set(key, value);
2642
+ }
2643
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
2644
+ if (allowOrigin) {
2645
+ set("Access-Control-Allow-Origin", allowOrigin);
2646
+ }
2647
+ if (opts.credentials) {
2648
+ set("Access-Control-Allow-Credentials", "true");
2649
+ }
2650
+ if (opts.exposeHeaders?.length) {
2651
+ set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
2652
+ }
2653
+ if (c.req.method === "OPTIONS") {
2654
+ if (opts.origin !== "*") {
2655
+ set("Vary", "Origin");
2656
+ }
2657
+ if (opts.maxAge != null) {
2658
+ set("Access-Control-Max-Age", opts.maxAge.toString());
2659
+ }
2660
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
2661
+ if (allowMethods.length) {
2662
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
2663
+ }
2664
+ let headers = opts.allowHeaders;
2665
+ if (!headers?.length) {
2666
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
2667
+ if (requestHeaders) {
2668
+ headers = requestHeaders.split(/\s*,\s*/);
2669
+ }
2670
+ }
2671
+ if (headers?.length) {
2672
+ set("Access-Control-Allow-Headers", headers.join(","));
2673
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
2674
+ }
2675
+ c.res.headers.delete("Content-Length");
2676
+ c.res.headers.delete("Content-Type");
2677
+ return new Response(null, {
2678
+ headers: c.res.headers,
2679
+ status: 204,
2680
+ statusText: "No Content"
2681
+ });
2682
+ }
2683
+ await next();
2684
+ if (opts.origin !== "*") {
2685
+ c.header("Vary", "Origin", { append: true });
2686
+ }
2687
+ };
2688
+ };
2689
+
2690
+ // ../api/src/routes/memories.ts
2691
+ function createMemoryRoutes() {
2692
+ const app = new Hono2();
2693
+ app.get("/", async (c) => {
2694
+ const engine = c.get("engine");
2695
+ const layer = c.req.query("layer");
2696
+ const scope = c.req.query("scope");
2697
+ const limit = Number(c.req.query("limit") ?? 100);
2698
+ const memories = await engine.listMemories({ layer, limit, scope });
2699
+ return c.json(memories);
2700
+ });
2701
+ app.get("/:id", async (c) => {
2702
+ const engine = c.get("engine");
2703
+ const memory = await engine.getMemory(c.req.param("id"));
2704
+ if (!memory) return c.json({ error: "Not found" }, 404);
2705
+ return c.json(memory);
2706
+ });
2707
+ app.post("/", async (c) => {
2708
+ const engine = c.get("engine");
2709
+ const body = await c.req.json();
2710
+ const memory = await engine.addMemory(body);
2711
+ return c.json(memory, 201);
2712
+ });
2713
+ app.patch("/:id", async (c) => {
2714
+ const engine = c.get("engine");
2715
+ const id = c.req.param("id");
2716
+ const body = await c.req.json();
2717
+ await engine.updateMemory(id, body);
2718
+ const updated = await engine.getMemory(id);
2719
+ return c.json(updated);
2720
+ });
2721
+ app.delete("/:id", async (c) => {
2722
+ const engine = c.get("engine");
2723
+ await engine.deleteMemory(c.req.param("id"));
2724
+ return c.json({ ok: true });
2725
+ });
2726
+ app.post("/search", async (c) => {
2727
+ const engine = c.get("engine");
2728
+ const body = await c.req.json();
2729
+ const results = await engine.searchMemories(body);
2730
+ return c.json(results);
2731
+ });
2732
+ app.post("/duplicates", async (c) => {
2733
+ const engine = c.get("engine");
2734
+ const { memoryId, threshold } = await c.req.json();
2735
+ const results = await engine.findDuplicates(memoryId, threshold);
2736
+ return c.json(results);
2737
+ });
2738
+ app.post("/consolidate", async (c) => {
2739
+ const engine = c.get("engine");
2740
+ const { sourceIds, mergedContent, layer } = await c.req.json();
2741
+ const merged = await engine.consolidateMemories(sourceIds, mergedContent, layer);
2742
+ return c.json(merged, 201);
2743
+ });
2744
+ return app;
2745
+ }
2746
+
2747
+ // ../api/src/routes/graph.ts
2748
+ function createGraphRoutes() {
2749
+ const app = new Hono2();
2750
+ app.get("/entities", async (c) => {
2751
+ const engine = c.get("engine");
2752
+ const scope = c.req.query("scope");
2753
+ const limit = Number(c.req.query("limit") ?? 100);
2754
+ const entities = await engine.listEntities({ limit, scope });
2755
+ return c.json(entities);
2756
+ });
2757
+ app.post("/entities", async (c) => {
2758
+ const engine = c.get("engine");
2759
+ const body = await c.req.json();
2760
+ const entity = await engine.addEntity(body);
2761
+ return c.json(entity, 201);
2762
+ });
2763
+ app.get("/edges", async (c) => {
2764
+ const engine = c.get("engine");
2765
+ const scope = c.req.query("scope");
2766
+ const includeExpired = c.req.query("includeExpired") === "true";
2767
+ const limit = Number(c.req.query("limit") ?? 100);
2768
+ const edges = await engine.listEdges({ limit, includeExpired, scope });
2769
+ return c.json(edges);
2770
+ });
2771
+ app.post("/edges", async (c) => {
2772
+ const engine = c.get("engine");
2773
+ const body = await c.req.json();
2774
+ const edge = await engine.addEdge(body);
2775
+ return c.json(edge, 201);
2776
+ });
2777
+ app.patch("/edges/:id", async (c) => {
2778
+ const engine = c.get("engine");
2779
+ const id = c.req.param("id");
2780
+ const body = await c.req.json();
2781
+ const updated = await engine.updateEdge(id, body);
2782
+ if (!updated) return c.json({ error: "Not found" }, 404);
2783
+ return c.json(updated);
2784
+ });
2785
+ app.delete("/edges/:id", async (c) => {
2786
+ const engine = c.get("engine");
2787
+ await engine.invalidateEdge(c.req.param("id"));
2788
+ return c.json({ ok: true });
2789
+ });
2790
+ app.post("/search", async (c) => {
2791
+ const engine = c.get("engine");
2792
+ const { query, limit, traverseDepth, scope } = await c.req.json();
2793
+ const results = await engine.searchGraph(query, limit, { traverseDepth, scope });
2794
+ return c.json(results);
2795
+ });
2796
+ return app;
2797
+ }
2798
+
2799
+ // ../api/src/routes/sessions.ts
2800
+ function createSessionRoutes() {
2801
+ const app = new Hono2();
2802
+ app.get("/", async (c) => {
2803
+ const engine = c.get("engine");
2804
+ const scope = c.req.query("scope");
2805
+ const limit = Number(c.req.query("limit") ?? 20);
2806
+ const sessions = await engine.sessionList(limit, scope);
2807
+ return c.json(sessions);
2808
+ });
2809
+ return app;
2810
+ }
2811
+
2812
+ // ../api/src/routes/episodes.ts
2813
+ function createEpisodeRoutes() {
2814
+ const app = new Hono2();
2815
+ app.get("/", async (c) => {
2816
+ const engine = c.get("engine");
2817
+ const scope = c.req.query("scope");
2818
+ const limit = Number(c.req.query("limit") ?? 20);
2819
+ const episodes = await engine.listEpisodes(limit, scope);
2820
+ return c.json(episodes);
2821
+ });
2822
+ app.get("/:id", async (c) => {
2823
+ const engine = c.get("engine");
2824
+ const episode = await engine.getEpisode(c.req.param("id"));
2825
+ if (!episode) return c.json({ error: "Not found" }, 404);
2826
+ return c.json(episode);
2827
+ });
2828
+ return app;
2829
+ }
2830
+
2831
+ // ../api/src/routes/context.ts
2832
+ function createContextRoutes() {
2833
+ const app = new Hono2();
2834
+ app.get("/", async (c) => {
2835
+ const engine = c.get("engine");
2836
+ const scope = c.req.query("scope");
2837
+ const maxMemories = Number(c.req.query("maxMemories") ?? 50);
2838
+ const context = await engine.getContext({ maxMemories, scope });
2839
+ return c.json(context);
2840
+ });
2841
+ return app;
2842
+ }
2843
+
2844
+ // ../api/src/index.ts
2845
+ function createApi(engine) {
2846
+ const app = new Hono2();
2847
+ app.use("*", cors());
2848
+ app.use("/api/*", async (c, next) => {
2849
+ c.set("engine", engine);
2850
+ await next();
2851
+ });
2852
+ app.route("/api/memories", createMemoryRoutes());
2853
+ app.route("/api/graph", createGraphRoutes());
2854
+ app.route("/api/sessions", createSessionRoutes());
2855
+ app.route("/api/episodes", createEpisodeRoutes());
2856
+ app.route("/api/context", createContextRoutes());
2857
+ return app;
2858
+ }
2859
+
2860
+ export {
2861
+ serve,
2862
+ createApi
2863
+ };