@classicicn/codex-transfer 0.2.0

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,3757 @@
1
+ #!/usr/bin/env node
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __esm = (fn, res) => function __init() {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ };
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+
13
+ // node_modules/@hono/node-server/dist/index.mjs
14
+ var dist_exports = {};
15
+ __export(dist_exports, {
16
+ RequestError: () => RequestError,
17
+ createAdaptorServer: () => createAdaptorServer,
18
+ getRequestListener: () => getRequestListener,
19
+ serve: () => serve
20
+ });
21
+ import { createServer as createServerHTTP } from "http";
22
+ import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
23
+ import { Http2ServerRequest } from "http2";
24
+ import { Readable } from "stream";
25
+ import crypto from "crypto";
26
+ async function readWithoutBlocking(readPromise) {
27
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
28
+ }
29
+ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
30
+ const cancel = (error) => {
31
+ reader.cancel(error).catch(() => {
32
+ });
33
+ };
34
+ writable.on("close", cancel);
35
+ writable.on("error", cancel);
36
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
37
+ return reader.closed.finally(() => {
38
+ writable.off("close", cancel);
39
+ writable.off("error", cancel);
40
+ });
41
+ function handleStreamError(error) {
42
+ if (error) {
43
+ writable.destroy(error);
44
+ }
45
+ }
46
+ function onDrain() {
47
+ reader.read().then(flow, handleStreamError);
48
+ }
49
+ function flow({ done, value }) {
50
+ try {
51
+ if (done) {
52
+ writable.end();
53
+ } else if (!writable.write(value)) {
54
+ writable.once("drain", onDrain);
55
+ } else {
56
+ return reader.read().then(flow, handleStreamError);
57
+ }
58
+ } catch (e) {
59
+ handleStreamError(e);
60
+ }
61
+ }
62
+ }
63
+ function writeFromReadableStream(stream2, writable) {
64
+ if (stream2.locked) {
65
+ throw new TypeError("ReadableStream is locked.");
66
+ } else if (writable.destroyed) {
67
+ return;
68
+ }
69
+ return writeFromReadableStreamDefaultReader(stream2.getReader(), writable);
70
+ }
71
+ var RequestError, toRequestError, GlobalRequest, Request2, newHeadersFromIncoming, wrapBodyStream, newRequestFromIncoming, getRequestCache, requestCache, incomingKey, urlKey, headersKey, abortControllerKey, getAbortController, requestPrototype, newRequest, responseCache, getResponseCache, cacheKey, GlobalResponse, Response2, buildOutgoingHttpHeaders, X_ALREADY_SENT, outgoingEnded, incomingDraining, DRAIN_TIMEOUT_MS, MAX_DRAIN_BYTES, drainIncoming, handleRequestError, handleFetchError, handleResponseError, flushHeaders, responseViaCache, isPromise, responseViaResponseObject, getRequestListener, createAdaptorServer, serve;
72
+ var init_dist = __esm({
73
+ "node_modules/@hono/node-server/dist/index.mjs"() {
74
+ RequestError = class extends Error {
75
+ constructor(message, options) {
76
+ super(message, options);
77
+ this.name = "RequestError";
78
+ }
79
+ };
80
+ toRequestError = (e) => {
81
+ if (e instanceof RequestError) {
82
+ return e;
83
+ }
84
+ return new RequestError(e.message, { cause: e });
85
+ };
86
+ GlobalRequest = global.Request;
87
+ Request2 = class extends GlobalRequest {
88
+ constructor(input, options) {
89
+ if (typeof input === "object" && getRequestCache in input) {
90
+ input = input[getRequestCache]();
91
+ }
92
+ if (typeof options?.body?.getReader !== "undefined") {
93
+ ;
94
+ options.duplex ??= "half";
95
+ }
96
+ super(input, options);
97
+ }
98
+ };
99
+ newHeadersFromIncoming = (incoming) => {
100
+ const headerRecord = [];
101
+ const rawHeaders = incoming.rawHeaders;
102
+ for (let i = 0; i < rawHeaders.length; i += 2) {
103
+ const { [i]: key, [i + 1]: value } = rawHeaders;
104
+ if (key.charCodeAt(0) !== /*:*/
105
+ 58) {
106
+ headerRecord.push([key, value]);
107
+ }
108
+ }
109
+ return new Headers(headerRecord);
110
+ };
111
+ wrapBodyStream = Symbol("wrapBodyStream");
112
+ newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
113
+ const init = {
114
+ method,
115
+ headers,
116
+ signal: abortController.signal
117
+ };
118
+ if (method === "TRACE") {
119
+ init.method = "GET";
120
+ const req = new Request2(url, init);
121
+ Object.defineProperty(req, "method", {
122
+ get() {
123
+ return "TRACE";
124
+ }
125
+ });
126
+ return req;
127
+ }
128
+ if (!(method === "GET" || method === "HEAD")) {
129
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
130
+ init.body = new ReadableStream({
131
+ start(controller) {
132
+ controller.enqueue(incoming.rawBody);
133
+ controller.close();
134
+ }
135
+ });
136
+ } else if (incoming[wrapBodyStream]) {
137
+ let reader;
138
+ init.body = new ReadableStream({
139
+ async pull(controller) {
140
+ try {
141
+ reader ||= Readable.toWeb(incoming).getReader();
142
+ const { done, value } = await reader.read();
143
+ if (done) {
144
+ controller.close();
145
+ } else {
146
+ controller.enqueue(value);
147
+ }
148
+ } catch (error) {
149
+ controller.error(error);
150
+ }
151
+ }
152
+ });
153
+ } else {
154
+ init.body = Readable.toWeb(incoming);
155
+ }
156
+ }
157
+ return new Request2(url, init);
158
+ };
159
+ getRequestCache = Symbol("getRequestCache");
160
+ requestCache = Symbol("requestCache");
161
+ incomingKey = Symbol("incomingKey");
162
+ urlKey = Symbol("urlKey");
163
+ headersKey = Symbol("headersKey");
164
+ abortControllerKey = Symbol("abortControllerKey");
165
+ getAbortController = Symbol("getAbortController");
166
+ requestPrototype = {
167
+ get method() {
168
+ return this[incomingKey].method || "GET";
169
+ },
170
+ get url() {
171
+ return this[urlKey];
172
+ },
173
+ get headers() {
174
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
175
+ },
176
+ [getAbortController]() {
177
+ this[getRequestCache]();
178
+ return this[abortControllerKey];
179
+ },
180
+ [getRequestCache]() {
181
+ this[abortControllerKey] ||= new AbortController();
182
+ return this[requestCache] ||= newRequestFromIncoming(
183
+ this.method,
184
+ this[urlKey],
185
+ this.headers,
186
+ this[incomingKey],
187
+ this[abortControllerKey]
188
+ );
189
+ }
190
+ };
191
+ [
192
+ "body",
193
+ "bodyUsed",
194
+ "cache",
195
+ "credentials",
196
+ "destination",
197
+ "integrity",
198
+ "mode",
199
+ "redirect",
200
+ "referrer",
201
+ "referrerPolicy",
202
+ "signal",
203
+ "keepalive"
204
+ ].forEach((k) => {
205
+ Object.defineProperty(requestPrototype, k, {
206
+ get() {
207
+ return this[getRequestCache]()[k];
208
+ }
209
+ });
210
+ });
211
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
212
+ Object.defineProperty(requestPrototype, k, {
213
+ value: function() {
214
+ return this[getRequestCache]()[k]();
215
+ }
216
+ });
217
+ });
218
+ Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
219
+ value: function(depth, options, inspectFn) {
220
+ const props = {
221
+ method: this.method,
222
+ url: this.url,
223
+ headers: this.headers,
224
+ nativeRequest: this[requestCache]
225
+ };
226
+ return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
227
+ }
228
+ });
229
+ Object.setPrototypeOf(requestPrototype, Request2.prototype);
230
+ newRequest = (incoming, defaultHostname) => {
231
+ const req = Object.create(requestPrototype);
232
+ req[incomingKey] = incoming;
233
+ const incomingUrl = incoming.url || "";
234
+ if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
235
+ (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
236
+ if (incoming instanceof Http2ServerRequest) {
237
+ throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
238
+ }
239
+ try {
240
+ const url2 = new URL(incomingUrl);
241
+ req[urlKey] = url2.href;
242
+ } catch (e) {
243
+ throw new RequestError("Invalid absolute URL", { cause: e });
244
+ }
245
+ return req;
246
+ }
247
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
248
+ if (!host) {
249
+ throw new RequestError("Missing host header");
250
+ }
251
+ let scheme;
252
+ if (incoming instanceof Http2ServerRequest) {
253
+ scheme = incoming.scheme;
254
+ if (!(scheme === "http" || scheme === "https")) {
255
+ throw new RequestError("Unsupported scheme");
256
+ }
257
+ } else {
258
+ scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
259
+ }
260
+ const url = new URL(`${scheme}://${host}${incomingUrl}`);
261
+ if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
262
+ throw new RequestError("Invalid host header");
263
+ }
264
+ req[urlKey] = url.href;
265
+ return req;
266
+ };
267
+ responseCache = Symbol("responseCache");
268
+ getResponseCache = Symbol("getResponseCache");
269
+ cacheKey = Symbol("cache");
270
+ GlobalResponse = global.Response;
271
+ Response2 = class _Response {
272
+ #body;
273
+ #init;
274
+ [getResponseCache]() {
275
+ delete this[cacheKey];
276
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
277
+ }
278
+ constructor(body, init) {
279
+ let headers;
280
+ this.#body = body;
281
+ if (init instanceof _Response) {
282
+ const cachedGlobalResponse = init[responseCache];
283
+ if (cachedGlobalResponse) {
284
+ this.#init = cachedGlobalResponse;
285
+ this[getResponseCache]();
286
+ return;
287
+ } else {
288
+ this.#init = init.#init;
289
+ headers = new Headers(init.#init.headers);
290
+ }
291
+ } else {
292
+ this.#init = init;
293
+ }
294
+ if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
295
+ ;
296
+ this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
297
+ }
298
+ }
299
+ get headers() {
300
+ const cache = this[cacheKey];
301
+ if (cache) {
302
+ if (!(cache[2] instanceof Headers)) {
303
+ cache[2] = new Headers(
304
+ cache[2] || { "content-type": "text/plain; charset=UTF-8" }
305
+ );
306
+ }
307
+ return cache[2];
308
+ }
309
+ return this[getResponseCache]().headers;
310
+ }
311
+ get status() {
312
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
313
+ }
314
+ get ok() {
315
+ const status = this.status;
316
+ return status >= 200 && status < 300;
317
+ }
318
+ };
319
+ ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
320
+ Object.defineProperty(Response2.prototype, k, {
321
+ get() {
322
+ return this[getResponseCache]()[k];
323
+ }
324
+ });
325
+ });
326
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
327
+ Object.defineProperty(Response2.prototype, k, {
328
+ value: function() {
329
+ return this[getResponseCache]()[k]();
330
+ }
331
+ });
332
+ });
333
+ Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
334
+ value: function(depth, options, inspectFn) {
335
+ const props = {
336
+ status: this.status,
337
+ headers: this.headers,
338
+ ok: this.ok,
339
+ nativeResponse: this[responseCache]
340
+ };
341
+ return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
342
+ }
343
+ });
344
+ Object.setPrototypeOf(Response2, GlobalResponse);
345
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
346
+ buildOutgoingHttpHeaders = (headers) => {
347
+ const res = {};
348
+ if (!(headers instanceof Headers)) {
349
+ headers = new Headers(headers ?? void 0);
350
+ }
351
+ const cookies = [];
352
+ for (const [k, v] of headers) {
353
+ if (k === "set-cookie") {
354
+ cookies.push(v);
355
+ } else {
356
+ res[k] = v;
357
+ }
358
+ }
359
+ if (cookies.length > 0) {
360
+ res["set-cookie"] = cookies;
361
+ }
362
+ res["content-type"] ??= "text/plain; charset=UTF-8";
363
+ return res;
364
+ };
365
+ X_ALREADY_SENT = "x-hono-already-sent";
366
+ if (typeof global.crypto === "undefined") {
367
+ global.crypto = crypto;
368
+ }
369
+ outgoingEnded = Symbol("outgoingEnded");
370
+ incomingDraining = Symbol("incomingDraining");
371
+ DRAIN_TIMEOUT_MS = 500;
372
+ MAX_DRAIN_BYTES = 64 * 1024 * 1024;
373
+ drainIncoming = (incoming) => {
374
+ const incomingWithDrainState = incoming;
375
+ if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
376
+ return;
377
+ }
378
+ incomingWithDrainState[incomingDraining] = true;
379
+ if (incoming instanceof Http2ServerRequest2) {
380
+ try {
381
+ ;
382
+ incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
383
+ } catch {
384
+ }
385
+ return;
386
+ }
387
+ let bytesRead = 0;
388
+ const cleanup = () => {
389
+ clearTimeout(timer);
390
+ incoming.off("data", onData);
391
+ incoming.off("end", cleanup);
392
+ incoming.off("error", cleanup);
393
+ };
394
+ const forceClose = () => {
395
+ cleanup();
396
+ const socket = incoming.socket;
397
+ if (socket && !socket.destroyed) {
398
+ socket.destroySoon();
399
+ }
400
+ };
401
+ const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
402
+ timer.unref?.();
403
+ const onData = (chunk) => {
404
+ bytesRead += chunk.length;
405
+ if (bytesRead > MAX_DRAIN_BYTES) {
406
+ forceClose();
407
+ }
408
+ };
409
+ incoming.on("data", onData);
410
+ incoming.on("end", cleanup);
411
+ incoming.on("error", cleanup);
412
+ incoming.resume();
413
+ };
414
+ handleRequestError = () => new Response(null, {
415
+ status: 400
416
+ });
417
+ handleFetchError = (e) => new Response(null, {
418
+ status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
419
+ });
420
+ handleResponseError = (e, outgoing) => {
421
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
422
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
423
+ console.info("The user aborted a request.");
424
+ } else {
425
+ console.error(e);
426
+ if (!outgoing.headersSent) {
427
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
428
+ }
429
+ outgoing.end(`Error: ${err.message}`);
430
+ outgoing.destroy(err);
431
+ }
432
+ };
433
+ flushHeaders = (outgoing) => {
434
+ if ("flushHeaders" in outgoing && outgoing.writable) {
435
+ outgoing.flushHeaders();
436
+ }
437
+ };
438
+ responseViaCache = async (res, outgoing) => {
439
+ let [status, body, header] = res[cacheKey];
440
+ let hasContentLength = false;
441
+ if (!header) {
442
+ header = { "content-type": "text/plain; charset=UTF-8" };
443
+ } else if (header instanceof Headers) {
444
+ hasContentLength = header.has("content-length");
445
+ header = buildOutgoingHttpHeaders(header);
446
+ } else if (Array.isArray(header)) {
447
+ const headerObj = new Headers(header);
448
+ hasContentLength = headerObj.has("content-length");
449
+ header = buildOutgoingHttpHeaders(headerObj);
450
+ } else {
451
+ for (const key in header) {
452
+ if (key.length === 14 && key.toLowerCase() === "content-length") {
453
+ hasContentLength = true;
454
+ break;
455
+ }
456
+ }
457
+ }
458
+ if (!hasContentLength) {
459
+ if (typeof body === "string") {
460
+ header["Content-Length"] = Buffer.byteLength(body);
461
+ } else if (body instanceof Uint8Array) {
462
+ header["Content-Length"] = body.byteLength;
463
+ } else if (body instanceof Blob) {
464
+ header["Content-Length"] = body.size;
465
+ }
466
+ }
467
+ outgoing.writeHead(status, header);
468
+ if (typeof body === "string" || body instanceof Uint8Array) {
469
+ outgoing.end(body);
470
+ } else if (body instanceof Blob) {
471
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
472
+ } else {
473
+ flushHeaders(outgoing);
474
+ await writeFromReadableStream(body, outgoing)?.catch(
475
+ (e) => handleResponseError(e, outgoing)
476
+ );
477
+ }
478
+ ;
479
+ outgoing[outgoingEnded]?.();
480
+ };
481
+ isPromise = (res) => typeof res.then === "function";
482
+ responseViaResponseObject = async (res, outgoing, options = {}) => {
483
+ if (isPromise(res)) {
484
+ if (options.errorHandler) {
485
+ try {
486
+ res = await res;
487
+ } catch (err) {
488
+ const errRes = await options.errorHandler(err);
489
+ if (!errRes) {
490
+ return;
491
+ }
492
+ res = errRes;
493
+ }
494
+ } else {
495
+ res = await res.catch(handleFetchError);
496
+ }
497
+ }
498
+ if (cacheKey in res) {
499
+ return responseViaCache(res, outgoing);
500
+ }
501
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
502
+ if (res.body) {
503
+ const reader = res.body.getReader();
504
+ const values = [];
505
+ let done = false;
506
+ let currentReadPromise = void 0;
507
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
508
+ let maxReadCount = 2;
509
+ for (let i = 0; i < maxReadCount; i++) {
510
+ currentReadPromise ||= reader.read();
511
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
512
+ console.error(e);
513
+ done = true;
514
+ });
515
+ if (!chunk) {
516
+ if (i === 1) {
517
+ await new Promise((resolve2) => setTimeout(resolve2));
518
+ maxReadCount = 3;
519
+ continue;
520
+ }
521
+ break;
522
+ }
523
+ currentReadPromise = void 0;
524
+ if (chunk.value) {
525
+ values.push(chunk.value);
526
+ }
527
+ if (chunk.done) {
528
+ done = true;
529
+ break;
530
+ }
531
+ }
532
+ if (done && !("content-length" in resHeaderRecord)) {
533
+ resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
534
+ }
535
+ }
536
+ outgoing.writeHead(res.status, resHeaderRecord);
537
+ values.forEach((value) => {
538
+ ;
539
+ outgoing.write(value);
540
+ });
541
+ if (done) {
542
+ outgoing.end();
543
+ } else {
544
+ if (values.length === 0) {
545
+ flushHeaders(outgoing);
546
+ }
547
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
548
+ }
549
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {
550
+ } else {
551
+ outgoing.writeHead(res.status, resHeaderRecord);
552
+ outgoing.end();
553
+ }
554
+ ;
555
+ outgoing[outgoingEnded]?.();
556
+ };
557
+ getRequestListener = (fetchCallback, options = {}) => {
558
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
559
+ if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
560
+ Object.defineProperty(global, "Request", {
561
+ value: Request2
562
+ });
563
+ Object.defineProperty(global, "Response", {
564
+ value: Response2
565
+ });
566
+ }
567
+ return async (incoming, outgoing) => {
568
+ let res, req;
569
+ try {
570
+ req = newRequest(incoming, options.hostname);
571
+ let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
572
+ if (!incomingEnded) {
573
+ ;
574
+ incoming[wrapBodyStream] = true;
575
+ incoming.on("end", () => {
576
+ incomingEnded = true;
577
+ });
578
+ if (incoming instanceof Http2ServerRequest2) {
579
+ ;
580
+ outgoing[outgoingEnded] = () => {
581
+ if (!incomingEnded) {
582
+ setTimeout(() => {
583
+ if (!incomingEnded) {
584
+ setTimeout(() => {
585
+ drainIncoming(incoming);
586
+ });
587
+ }
588
+ });
589
+ }
590
+ };
591
+ }
592
+ outgoing.on("finish", () => {
593
+ if (!incomingEnded) {
594
+ drainIncoming(incoming);
595
+ }
596
+ });
597
+ }
598
+ outgoing.on("close", () => {
599
+ const abortController = req[abortControllerKey];
600
+ if (abortController) {
601
+ if (incoming.errored) {
602
+ req[abortControllerKey].abort(incoming.errored.toString());
603
+ } else if (!outgoing.writableFinished) {
604
+ req[abortControllerKey].abort("Client connection prematurely closed.");
605
+ }
606
+ }
607
+ if (!incomingEnded) {
608
+ setTimeout(() => {
609
+ if (!incomingEnded) {
610
+ setTimeout(() => {
611
+ drainIncoming(incoming);
612
+ });
613
+ }
614
+ });
615
+ }
616
+ });
617
+ res = fetchCallback(req, { incoming, outgoing });
618
+ if (cacheKey in res) {
619
+ return responseViaCache(res, outgoing);
620
+ }
621
+ } catch (e) {
622
+ if (!res) {
623
+ if (options.errorHandler) {
624
+ res = await options.errorHandler(req ? e : toRequestError(e));
625
+ if (!res) {
626
+ return;
627
+ }
628
+ } else if (!req) {
629
+ res = handleRequestError();
630
+ } else {
631
+ res = handleFetchError(e);
632
+ }
633
+ } else {
634
+ return handleResponseError(e, outgoing);
635
+ }
636
+ }
637
+ try {
638
+ return await responseViaResponseObject(res, outgoing, options);
639
+ } catch (e) {
640
+ return handleResponseError(e, outgoing);
641
+ }
642
+ };
643
+ };
644
+ createAdaptorServer = (options) => {
645
+ const fetchCallback = options.fetch;
646
+ const requestListener = getRequestListener(fetchCallback, {
647
+ hostname: options.hostname,
648
+ overrideGlobalObjects: options.overrideGlobalObjects,
649
+ autoCleanupIncoming: options.autoCleanupIncoming
650
+ });
651
+ const createServer = options.createServer || createServerHTTP;
652
+ const server = createServer(options.serverOptions || {}, requestListener);
653
+ return server;
654
+ };
655
+ serve = (options, listeningListener) => {
656
+ const server = createAdaptorServer(options);
657
+ server.listen(options?.port ?? 3e3, options.hostname, () => {
658
+ const serverInfo = server.address();
659
+ listeningListener && listeningListener(serverInfo);
660
+ });
661
+ return server;
662
+ };
663
+ }
664
+ });
665
+
666
+ // node_modules/hono/dist/compose.js
667
+ var compose = (middleware, onError, onNotFound) => {
668
+ return (context, next) => {
669
+ let index = -1;
670
+ return dispatch(0);
671
+ async function dispatch(i) {
672
+ if (i <= index) {
673
+ throw new Error("next() called multiple times");
674
+ }
675
+ index = i;
676
+ let res;
677
+ let isError = false;
678
+ let handler;
679
+ if (middleware[i]) {
680
+ handler = middleware[i][0][0];
681
+ context.req.routeIndex = i;
682
+ } else {
683
+ handler = i === middleware.length && next || void 0;
684
+ }
685
+ if (handler) {
686
+ try {
687
+ res = await handler(context, () => dispatch(i + 1));
688
+ } catch (err) {
689
+ if (err instanceof Error && onError) {
690
+ context.error = err;
691
+ res = await onError(err, context);
692
+ isError = true;
693
+ } else {
694
+ throw err;
695
+ }
696
+ }
697
+ } else {
698
+ if (context.finalized === false && onNotFound) {
699
+ res = await onNotFound(context);
700
+ }
701
+ }
702
+ if (res && (context.finalized === false || isError)) {
703
+ context.res = res;
704
+ }
705
+ return context;
706
+ }
707
+ };
708
+ };
709
+
710
+ // node_modules/hono/dist/request/constants.js
711
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
712
+
713
+ // node_modules/hono/dist/utils/body.js
714
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
715
+ const { all = false, dot = false } = options;
716
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
717
+ const contentType = headers.get("Content-Type");
718
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
719
+ return parseFormData(request, { all, dot });
720
+ }
721
+ return {};
722
+ };
723
+ async function parseFormData(request, options) {
724
+ const formData = await request.formData();
725
+ if (formData) {
726
+ return convertFormDataToBodyData(formData, options);
727
+ }
728
+ return {};
729
+ }
730
+ function convertFormDataToBodyData(formData, options) {
731
+ const form = /* @__PURE__ */ Object.create(null);
732
+ formData.forEach((value, key) => {
733
+ const shouldParseAllValues = options.all || key.endsWith("[]");
734
+ if (!shouldParseAllValues) {
735
+ form[key] = value;
736
+ } else {
737
+ handleParsingAllValues(form, key, value);
738
+ }
739
+ });
740
+ if (options.dot) {
741
+ Object.entries(form).forEach(([key, value]) => {
742
+ const shouldParseDotValues = key.includes(".");
743
+ if (shouldParseDotValues) {
744
+ handleParsingNestedValues(form, key, value);
745
+ delete form[key];
746
+ }
747
+ });
748
+ }
749
+ return form;
750
+ }
751
+ var handleParsingAllValues = (form, key, value) => {
752
+ if (form[key] !== void 0) {
753
+ if (Array.isArray(form[key])) {
754
+ ;
755
+ form[key].push(value);
756
+ } else {
757
+ form[key] = [form[key], value];
758
+ }
759
+ } else {
760
+ if (!key.endsWith("[]")) {
761
+ form[key] = value;
762
+ } else {
763
+ form[key] = [value];
764
+ }
765
+ }
766
+ };
767
+ var handleParsingNestedValues = (form, key, value) => {
768
+ if (/(?:^|\.)__proto__\./.test(key)) {
769
+ return;
770
+ }
771
+ let nestedForm = form;
772
+ const keys = key.split(".");
773
+ keys.forEach((key2, index) => {
774
+ if (index === keys.length - 1) {
775
+ nestedForm[key2] = value;
776
+ } else {
777
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
778
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
779
+ }
780
+ nestedForm = nestedForm[key2];
781
+ }
782
+ });
783
+ };
784
+
785
+ // node_modules/hono/dist/utils/url.js
786
+ var splitPath = (path) => {
787
+ const paths = path.split("/");
788
+ if (paths[0] === "") {
789
+ paths.shift();
790
+ }
791
+ return paths;
792
+ };
793
+ var splitRoutingPath = (routePath) => {
794
+ const { groups, path } = extractGroupsFromPath(routePath);
795
+ const paths = splitPath(path);
796
+ return replaceGroupMarks(paths, groups);
797
+ };
798
+ var extractGroupsFromPath = (path) => {
799
+ const groups = [];
800
+ path = path.replace(/\{[^}]+\}/g, (match2, index) => {
801
+ const mark = `@${index}`;
802
+ groups.push([mark, match2]);
803
+ return mark;
804
+ });
805
+ return { groups, path };
806
+ };
807
+ var replaceGroupMarks = (paths, groups) => {
808
+ for (let i = groups.length - 1; i >= 0; i--) {
809
+ const [mark] = groups[i];
810
+ for (let j = paths.length - 1; j >= 0; j--) {
811
+ if (paths[j].includes(mark)) {
812
+ paths[j] = paths[j].replace(mark, groups[i][1]);
813
+ break;
814
+ }
815
+ }
816
+ }
817
+ return paths;
818
+ };
819
+ var patternCache = {};
820
+ var getPattern = (label, next) => {
821
+ if (label === "*") {
822
+ return "*";
823
+ }
824
+ const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
825
+ if (match2) {
826
+ const cacheKey2 = `${label}#${next}`;
827
+ if (!patternCache[cacheKey2]) {
828
+ if (match2[2]) {
829
+ patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
830
+ } else {
831
+ patternCache[cacheKey2] = [label, match2[1], true];
832
+ }
833
+ }
834
+ return patternCache[cacheKey2];
835
+ }
836
+ return null;
837
+ };
838
+ var tryDecode = (str, decoder) => {
839
+ try {
840
+ return decoder(str);
841
+ } catch {
842
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
843
+ try {
844
+ return decoder(match2);
845
+ } catch {
846
+ return match2;
847
+ }
848
+ });
849
+ }
850
+ };
851
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
852
+ var getPath = (request) => {
853
+ const url = request.url;
854
+ const start = url.indexOf("/", url.indexOf(":") + 4);
855
+ let i = start;
856
+ for (; i < url.length; i++) {
857
+ const charCode = url.charCodeAt(i);
858
+ if (charCode === 37) {
859
+ const queryIndex = url.indexOf("?", i);
860
+ const hashIndex = url.indexOf("#", i);
861
+ const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
862
+ const path = url.slice(start, end);
863
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
864
+ } else if (charCode === 63 || charCode === 35) {
865
+ break;
866
+ }
867
+ }
868
+ return url.slice(start, i);
869
+ };
870
+ var getPathNoStrict = (request) => {
871
+ const result = getPath(request);
872
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
873
+ };
874
+ var mergePath = (base, sub, ...rest) => {
875
+ if (rest.length) {
876
+ sub = mergePath(sub, ...rest);
877
+ }
878
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
879
+ };
880
+ var checkOptionalParameter = (path) => {
881
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
882
+ return null;
883
+ }
884
+ const segments = path.split("/");
885
+ const results = [];
886
+ let basePath = "";
887
+ segments.forEach((segment) => {
888
+ if (segment !== "" && !/\:/.test(segment)) {
889
+ basePath += "/" + segment;
890
+ } else if (/\:/.test(segment)) {
891
+ if (/\?/.test(segment)) {
892
+ if (results.length === 0 && basePath === "") {
893
+ results.push("/");
894
+ } else {
895
+ results.push(basePath);
896
+ }
897
+ const optionalSegment = segment.replace("?", "");
898
+ basePath += "/" + optionalSegment;
899
+ results.push(basePath);
900
+ } else {
901
+ basePath += "/" + segment;
902
+ }
903
+ }
904
+ });
905
+ return results.filter((v, i, a) => a.indexOf(v) === i);
906
+ };
907
+ var _decodeURI = (value) => {
908
+ if (!/[%+]/.test(value)) {
909
+ return value;
910
+ }
911
+ if (value.indexOf("+") !== -1) {
912
+ value = value.replace(/\+/g, " ");
913
+ }
914
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
915
+ };
916
+ var _getQueryParam = (url, key, multiple) => {
917
+ let encoded;
918
+ if (!multiple && key && !/[%+]/.test(key)) {
919
+ let keyIndex2 = url.indexOf("?", 8);
920
+ if (keyIndex2 === -1) {
921
+ return void 0;
922
+ }
923
+ if (!url.startsWith(key, keyIndex2 + 1)) {
924
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
925
+ }
926
+ while (keyIndex2 !== -1) {
927
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
928
+ if (trailingKeyCode === 61) {
929
+ const valueIndex = keyIndex2 + key.length + 2;
930
+ const endIndex = url.indexOf("&", valueIndex);
931
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
932
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
933
+ return "";
934
+ }
935
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
936
+ }
937
+ encoded = /[%+]/.test(url);
938
+ if (!encoded) {
939
+ return void 0;
940
+ }
941
+ }
942
+ const results = {};
943
+ encoded ??= /[%+]/.test(url);
944
+ let keyIndex = url.indexOf("?", 8);
945
+ while (keyIndex !== -1) {
946
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
947
+ let valueIndex = url.indexOf("=", keyIndex);
948
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
949
+ valueIndex = -1;
950
+ }
951
+ let name = url.slice(
952
+ keyIndex + 1,
953
+ valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
954
+ );
955
+ if (encoded) {
956
+ name = _decodeURI(name);
957
+ }
958
+ keyIndex = nextKeyIndex;
959
+ if (name === "") {
960
+ continue;
961
+ }
962
+ let value;
963
+ if (valueIndex === -1) {
964
+ value = "";
965
+ } else {
966
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
967
+ if (encoded) {
968
+ value = _decodeURI(value);
969
+ }
970
+ }
971
+ if (multiple) {
972
+ if (!(results[name] && Array.isArray(results[name]))) {
973
+ results[name] = [];
974
+ }
975
+ ;
976
+ results[name].push(value);
977
+ } else {
978
+ results[name] ??= value;
979
+ }
980
+ }
981
+ return key ? results[key] : results;
982
+ };
983
+ var getQueryParam = _getQueryParam;
984
+ var getQueryParams = (url, key) => {
985
+ return _getQueryParam(url, key, true);
986
+ };
987
+ var decodeURIComponent_ = decodeURIComponent;
988
+
989
+ // node_modules/hono/dist/request.js
990
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
991
+ var HonoRequest = class {
992
+ /**
993
+ * `.raw` can get the raw Request object.
994
+ *
995
+ * @see {@link https://hono.dev/docs/api/request#raw}
996
+ *
997
+ * @example
998
+ * ```ts
999
+ * // For Cloudflare Workers
1000
+ * app.post('/', async (c) => {
1001
+ * const metadata = c.req.raw.cf?.hostMetadata?
1002
+ * ...
1003
+ * })
1004
+ * ```
1005
+ */
1006
+ raw;
1007
+ #validatedData;
1008
+ // Short name of validatedData
1009
+ #matchResult;
1010
+ routeIndex = 0;
1011
+ /**
1012
+ * `.path` can get the pathname of the request.
1013
+ *
1014
+ * @see {@link https://hono.dev/docs/api/request#path}
1015
+ *
1016
+ * @example
1017
+ * ```ts
1018
+ * app.get('/about/me', (c) => {
1019
+ * const pathname = c.req.path // `/about/me`
1020
+ * })
1021
+ * ```
1022
+ */
1023
+ path;
1024
+ bodyCache = {};
1025
+ constructor(request, path = "/", matchResult = [[]]) {
1026
+ this.raw = request;
1027
+ this.path = path;
1028
+ this.#matchResult = matchResult;
1029
+ this.#validatedData = {};
1030
+ }
1031
+ param(key) {
1032
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
1033
+ }
1034
+ #getDecodedParam(key) {
1035
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
1036
+ const param = this.#getParamValue(paramKey);
1037
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
1038
+ }
1039
+ #getAllDecodedParams() {
1040
+ const decoded = {};
1041
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
1042
+ for (const key of keys) {
1043
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
1044
+ if (value !== void 0) {
1045
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
1046
+ }
1047
+ }
1048
+ return decoded;
1049
+ }
1050
+ #getParamValue(paramKey) {
1051
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
1052
+ }
1053
+ query(key) {
1054
+ return getQueryParam(this.url, key);
1055
+ }
1056
+ queries(key) {
1057
+ return getQueryParams(this.url, key);
1058
+ }
1059
+ header(name) {
1060
+ if (name) {
1061
+ return this.raw.headers.get(name) ?? void 0;
1062
+ }
1063
+ const headerData = {};
1064
+ this.raw.headers.forEach((value, key) => {
1065
+ headerData[key] = value;
1066
+ });
1067
+ return headerData;
1068
+ }
1069
+ async parseBody(options) {
1070
+ return parseBody(this, options);
1071
+ }
1072
+ #cachedBody = (key) => {
1073
+ const { bodyCache, raw: raw2 } = this;
1074
+ const cachedBody = bodyCache[key];
1075
+ if (cachedBody) {
1076
+ return cachedBody;
1077
+ }
1078
+ const anyCachedKey = Object.keys(bodyCache)[0];
1079
+ if (anyCachedKey) {
1080
+ return bodyCache[anyCachedKey].then((body) => {
1081
+ if (anyCachedKey === "json") {
1082
+ body = JSON.stringify(body);
1083
+ }
1084
+ return new Response(body)[key]();
1085
+ });
1086
+ }
1087
+ return bodyCache[key] = raw2[key]();
1088
+ };
1089
+ /**
1090
+ * `.json()` can parse Request body of type `application/json`
1091
+ *
1092
+ * @see {@link https://hono.dev/docs/api/request#json}
1093
+ *
1094
+ * @example
1095
+ * ```ts
1096
+ * app.post('/entry', async (c) => {
1097
+ * const body = await c.req.json()
1098
+ * })
1099
+ * ```
1100
+ */
1101
+ json() {
1102
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
1103
+ }
1104
+ /**
1105
+ * `.text()` can parse Request body of type `text/plain`
1106
+ *
1107
+ * @see {@link https://hono.dev/docs/api/request#text}
1108
+ *
1109
+ * @example
1110
+ * ```ts
1111
+ * app.post('/entry', async (c) => {
1112
+ * const body = await c.req.text()
1113
+ * })
1114
+ * ```
1115
+ */
1116
+ text() {
1117
+ return this.#cachedBody("text");
1118
+ }
1119
+ /**
1120
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
1121
+ *
1122
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
1123
+ *
1124
+ * @example
1125
+ * ```ts
1126
+ * app.post('/entry', async (c) => {
1127
+ * const body = await c.req.arrayBuffer()
1128
+ * })
1129
+ * ```
1130
+ */
1131
+ arrayBuffer() {
1132
+ return this.#cachedBody("arrayBuffer");
1133
+ }
1134
+ /**
1135
+ * Parses the request body as a `Blob`.
1136
+ * @example
1137
+ * ```ts
1138
+ * app.post('/entry', async (c) => {
1139
+ * const body = await c.req.blob();
1140
+ * });
1141
+ * ```
1142
+ * @see https://hono.dev/docs/api/request#blob
1143
+ */
1144
+ blob() {
1145
+ return this.#cachedBody("blob");
1146
+ }
1147
+ /**
1148
+ * Parses the request body as `FormData`.
1149
+ * @example
1150
+ * ```ts
1151
+ * app.post('/entry', async (c) => {
1152
+ * const body = await c.req.formData();
1153
+ * });
1154
+ * ```
1155
+ * @see https://hono.dev/docs/api/request#formdata
1156
+ */
1157
+ formData() {
1158
+ return this.#cachedBody("formData");
1159
+ }
1160
+ /**
1161
+ * Adds validated data to the request.
1162
+ *
1163
+ * @param target - The target of the validation.
1164
+ * @param data - The validated data to add.
1165
+ */
1166
+ addValidatedData(target, data) {
1167
+ this.#validatedData[target] = data;
1168
+ }
1169
+ valid(target) {
1170
+ return this.#validatedData[target];
1171
+ }
1172
+ /**
1173
+ * `.url()` can get the request url strings.
1174
+ *
1175
+ * @see {@link https://hono.dev/docs/api/request#url}
1176
+ *
1177
+ * @example
1178
+ * ```ts
1179
+ * app.get('/about/me', (c) => {
1180
+ * const url = c.req.url // `http://localhost:8787/about/me`
1181
+ * ...
1182
+ * })
1183
+ * ```
1184
+ */
1185
+ get url() {
1186
+ return this.raw.url;
1187
+ }
1188
+ /**
1189
+ * `.method()` can get the method name of the request.
1190
+ *
1191
+ * @see {@link https://hono.dev/docs/api/request#method}
1192
+ *
1193
+ * @example
1194
+ * ```ts
1195
+ * app.get('/about/me', (c) => {
1196
+ * const method = c.req.method // `GET`
1197
+ * })
1198
+ * ```
1199
+ */
1200
+ get method() {
1201
+ return this.raw.method;
1202
+ }
1203
+ get [GET_MATCH_RESULT]() {
1204
+ return this.#matchResult;
1205
+ }
1206
+ /**
1207
+ * `.matchedRoutes()` can return a matched route in the handler
1208
+ *
1209
+ * @deprecated
1210
+ *
1211
+ * Use matchedRoutes helper defined in "hono/route" instead.
1212
+ *
1213
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
1214
+ *
1215
+ * @example
1216
+ * ```ts
1217
+ * app.use('*', async function logger(c, next) {
1218
+ * await next()
1219
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
1220
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
1221
+ * console.log(
1222
+ * method,
1223
+ * ' ',
1224
+ * path,
1225
+ * ' '.repeat(Math.max(10 - path.length, 0)),
1226
+ * name,
1227
+ * i === c.req.routeIndex ? '<- respond from here' : ''
1228
+ * )
1229
+ * })
1230
+ * })
1231
+ * ```
1232
+ */
1233
+ get matchedRoutes() {
1234
+ return this.#matchResult[0].map(([[, route]]) => route);
1235
+ }
1236
+ /**
1237
+ * `routePath()` can retrieve the path registered within the handler
1238
+ *
1239
+ * @deprecated
1240
+ *
1241
+ * Use routePath helper defined in "hono/route" instead.
1242
+ *
1243
+ * @see {@link https://hono.dev/docs/api/request#routepath}
1244
+ *
1245
+ * @example
1246
+ * ```ts
1247
+ * app.get('/posts/:id', (c) => {
1248
+ * return c.json({ path: c.req.routePath })
1249
+ * })
1250
+ * ```
1251
+ */
1252
+ get routePath() {
1253
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
1254
+ }
1255
+ };
1256
+
1257
+ // node_modules/hono/dist/utils/html.js
1258
+ var HtmlEscapedCallbackPhase = {
1259
+ Stringify: 1,
1260
+ BeforeStream: 2,
1261
+ Stream: 3
1262
+ };
1263
+ var raw = (value, callbacks) => {
1264
+ const escapedString = new String(value);
1265
+ escapedString.isEscaped = true;
1266
+ escapedString.callbacks = callbacks;
1267
+ return escapedString;
1268
+ };
1269
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
1270
+ if (typeof str === "object" && !(str instanceof String)) {
1271
+ if (!(str instanceof Promise)) {
1272
+ str = str.toString();
1273
+ }
1274
+ if (str instanceof Promise) {
1275
+ str = await str;
1276
+ }
1277
+ }
1278
+ const callbacks = str.callbacks;
1279
+ if (!callbacks?.length) {
1280
+ return Promise.resolve(str);
1281
+ }
1282
+ if (buffer) {
1283
+ buffer[0] += str;
1284
+ } else {
1285
+ buffer = [str];
1286
+ }
1287
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
1288
+ (res) => Promise.all(
1289
+ res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
1290
+ ).then(() => buffer[0])
1291
+ );
1292
+ if (preserveCallbacks) {
1293
+ return raw(await resStr, callbacks);
1294
+ } else {
1295
+ return resStr;
1296
+ }
1297
+ };
1298
+
1299
+ // node_modules/hono/dist/context.js
1300
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
1301
+ var setDefaultContentType = (contentType, headers) => {
1302
+ return {
1303
+ "Content-Type": contentType,
1304
+ ...headers
1305
+ };
1306
+ };
1307
+ var createResponseInstance = (body, init) => new Response(body, init);
1308
+ var Context = class {
1309
+ #rawRequest;
1310
+ #req;
1311
+ /**
1312
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
1313
+ *
1314
+ * @see {@link https://hono.dev/docs/api/context#env}
1315
+ *
1316
+ * @example
1317
+ * ```ts
1318
+ * // Environment object for Cloudflare Workers
1319
+ * app.get('*', async c => {
1320
+ * const counter = c.env.COUNTER
1321
+ * })
1322
+ * ```
1323
+ */
1324
+ env = {};
1325
+ #var;
1326
+ finalized = false;
1327
+ /**
1328
+ * `.error` can get the error object from the middleware if the Handler throws an error.
1329
+ *
1330
+ * @see {@link https://hono.dev/docs/api/context#error}
1331
+ *
1332
+ * @example
1333
+ * ```ts
1334
+ * app.use('*', async (c, next) => {
1335
+ * await next()
1336
+ * if (c.error) {
1337
+ * // do something...
1338
+ * }
1339
+ * })
1340
+ * ```
1341
+ */
1342
+ error;
1343
+ #status;
1344
+ #executionCtx;
1345
+ #res;
1346
+ #layout;
1347
+ #renderer;
1348
+ #notFoundHandler;
1349
+ #preparedHeaders;
1350
+ #matchResult;
1351
+ #path;
1352
+ /**
1353
+ * Creates an instance of the Context class.
1354
+ *
1355
+ * @param req - The Request object.
1356
+ * @param options - Optional configuration options for the context.
1357
+ */
1358
+ constructor(req, options) {
1359
+ this.#rawRequest = req;
1360
+ if (options) {
1361
+ this.#executionCtx = options.executionCtx;
1362
+ this.env = options.env;
1363
+ this.#notFoundHandler = options.notFoundHandler;
1364
+ this.#path = options.path;
1365
+ this.#matchResult = options.matchResult;
1366
+ }
1367
+ }
1368
+ /**
1369
+ * `.req` is the instance of {@link HonoRequest}.
1370
+ */
1371
+ get req() {
1372
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
1373
+ return this.#req;
1374
+ }
1375
+ /**
1376
+ * @see {@link https://hono.dev/docs/api/context#event}
1377
+ * The FetchEvent associated with the current request.
1378
+ *
1379
+ * @throws Will throw an error if the context does not have a FetchEvent.
1380
+ */
1381
+ get event() {
1382
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
1383
+ return this.#executionCtx;
1384
+ } else {
1385
+ throw Error("This context has no FetchEvent");
1386
+ }
1387
+ }
1388
+ /**
1389
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
1390
+ * The ExecutionContext associated with the current request.
1391
+ *
1392
+ * @throws Will throw an error if the context does not have an ExecutionContext.
1393
+ */
1394
+ get executionCtx() {
1395
+ if (this.#executionCtx) {
1396
+ return this.#executionCtx;
1397
+ } else {
1398
+ throw Error("This context has no ExecutionContext");
1399
+ }
1400
+ }
1401
+ /**
1402
+ * @see {@link https://hono.dev/docs/api/context#res}
1403
+ * The Response object for the current request.
1404
+ */
1405
+ get res() {
1406
+ return this.#res ||= createResponseInstance(null, {
1407
+ headers: this.#preparedHeaders ??= new Headers()
1408
+ });
1409
+ }
1410
+ /**
1411
+ * Sets the Response object for the current request.
1412
+ *
1413
+ * @param _res - The Response object to set.
1414
+ */
1415
+ set res(_res) {
1416
+ if (this.#res && _res) {
1417
+ _res = createResponseInstance(_res.body, _res);
1418
+ for (const [k, v] of this.#res.headers.entries()) {
1419
+ if (k === "content-type") {
1420
+ continue;
1421
+ }
1422
+ if (k === "set-cookie") {
1423
+ const cookies = this.#res.headers.getSetCookie();
1424
+ _res.headers.delete("set-cookie");
1425
+ for (const cookie of cookies) {
1426
+ _res.headers.append("set-cookie", cookie);
1427
+ }
1428
+ } else {
1429
+ _res.headers.set(k, v);
1430
+ }
1431
+ }
1432
+ }
1433
+ this.#res = _res;
1434
+ this.finalized = true;
1435
+ }
1436
+ /**
1437
+ * `.render()` can create a response within a layout.
1438
+ *
1439
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1440
+ *
1441
+ * @example
1442
+ * ```ts
1443
+ * app.get('/', (c) => {
1444
+ * return c.render('Hello!')
1445
+ * })
1446
+ * ```
1447
+ */
1448
+ render = (...args2) => {
1449
+ this.#renderer ??= (content) => this.html(content);
1450
+ return this.#renderer(...args2);
1451
+ };
1452
+ /**
1453
+ * Sets the layout for the response.
1454
+ *
1455
+ * @param layout - The layout to set.
1456
+ * @returns The layout function.
1457
+ */
1458
+ setLayout = (layout) => this.#layout = layout;
1459
+ /**
1460
+ * Gets the current layout for the response.
1461
+ *
1462
+ * @returns The current layout function.
1463
+ */
1464
+ getLayout = () => this.#layout;
1465
+ /**
1466
+ * `.setRenderer()` can set the layout in the custom middleware.
1467
+ *
1468
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
1469
+ *
1470
+ * @example
1471
+ * ```tsx
1472
+ * app.use('*', async (c, next) => {
1473
+ * c.setRenderer((content) => {
1474
+ * return c.html(
1475
+ * <html>
1476
+ * <body>
1477
+ * <p>{content}</p>
1478
+ * </body>
1479
+ * </html>
1480
+ * )
1481
+ * })
1482
+ * await next()
1483
+ * })
1484
+ * ```
1485
+ */
1486
+ setRenderer = (renderer) => {
1487
+ this.#renderer = renderer;
1488
+ };
1489
+ /**
1490
+ * `.header()` can set headers.
1491
+ *
1492
+ * @see {@link https://hono.dev/docs/api/context#header}
1493
+ *
1494
+ * @example
1495
+ * ```ts
1496
+ * app.get('/welcome', (c) => {
1497
+ * // Set headers
1498
+ * c.header('X-Message', 'Hello!')
1499
+ * c.header('Content-Type', 'text/plain')
1500
+ *
1501
+ * return c.body('Thank you for coming')
1502
+ * })
1503
+ * ```
1504
+ */
1505
+ header = (name, value, options) => {
1506
+ if (this.finalized) {
1507
+ this.#res = createResponseInstance(this.#res.body, this.#res);
1508
+ }
1509
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
1510
+ if (value === void 0) {
1511
+ headers.delete(name);
1512
+ } else if (options?.append) {
1513
+ headers.append(name, value);
1514
+ } else {
1515
+ headers.set(name, value);
1516
+ }
1517
+ };
1518
+ status = (status) => {
1519
+ this.#status = status;
1520
+ };
1521
+ /**
1522
+ * `.set()` can set the value specified by the key.
1523
+ *
1524
+ * @see {@link https://hono.dev/docs/api/context#set-get}
1525
+ *
1526
+ * @example
1527
+ * ```ts
1528
+ * app.use('*', async (c, next) => {
1529
+ * c.set('message', 'Hono is hot!!')
1530
+ * await next()
1531
+ * })
1532
+ * ```
1533
+ */
1534
+ set = (key, value) => {
1535
+ this.#var ??= /* @__PURE__ */ new Map();
1536
+ this.#var.set(key, value);
1537
+ };
1538
+ /**
1539
+ * `.get()` can use the value specified by the key.
1540
+ *
1541
+ * @see {@link https://hono.dev/docs/api/context#set-get}
1542
+ *
1543
+ * @example
1544
+ * ```ts
1545
+ * app.get('/', (c) => {
1546
+ * const message = c.get('message')
1547
+ * return c.text(`The message is "${message}"`)
1548
+ * })
1549
+ * ```
1550
+ */
1551
+ get = (key) => {
1552
+ return this.#var ? this.#var.get(key) : void 0;
1553
+ };
1554
+ /**
1555
+ * `.var` can access the value of a variable.
1556
+ *
1557
+ * @see {@link https://hono.dev/docs/api/context#var}
1558
+ *
1559
+ * @example
1560
+ * ```ts
1561
+ * const result = c.var.client.oneMethod()
1562
+ * ```
1563
+ */
1564
+ // c.var.propName is a read-only
1565
+ get var() {
1566
+ if (!this.#var) {
1567
+ return {};
1568
+ }
1569
+ return Object.fromEntries(this.#var);
1570
+ }
1571
+ #newResponse(data, arg, headers) {
1572
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
1573
+ if (typeof arg === "object" && "headers" in arg) {
1574
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
1575
+ for (const [key, value] of argHeaders) {
1576
+ if (key.toLowerCase() === "set-cookie") {
1577
+ responseHeaders.append(key, value);
1578
+ } else {
1579
+ responseHeaders.set(key, value);
1580
+ }
1581
+ }
1582
+ }
1583
+ if (headers) {
1584
+ for (const [k, v] of Object.entries(headers)) {
1585
+ if (typeof v === "string") {
1586
+ responseHeaders.set(k, v);
1587
+ } else {
1588
+ responseHeaders.delete(k);
1589
+ for (const v2 of v) {
1590
+ responseHeaders.append(k, v2);
1591
+ }
1592
+ }
1593
+ }
1594
+ }
1595
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
1596
+ return createResponseInstance(data, { status, headers: responseHeaders });
1597
+ }
1598
+ newResponse = (...args2) => this.#newResponse(...args2);
1599
+ /**
1600
+ * `.body()` can return the HTTP response.
1601
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
1602
+ * This can also be set in `.text()`, `.json()` and so on.
1603
+ *
1604
+ * @see {@link https://hono.dev/docs/api/context#body}
1605
+ *
1606
+ * @example
1607
+ * ```ts
1608
+ * app.get('/welcome', (c) => {
1609
+ * // Set headers
1610
+ * c.header('X-Message', 'Hello!')
1611
+ * c.header('Content-Type', 'text/plain')
1612
+ * // Set HTTP status code
1613
+ * c.status(201)
1614
+ *
1615
+ * // Return the response body
1616
+ * return c.body('Thank you for coming')
1617
+ * })
1618
+ * ```
1619
+ */
1620
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
1621
+ /**
1622
+ * `.text()` can render text as `Content-Type:text/plain`.
1623
+ *
1624
+ * @see {@link https://hono.dev/docs/api/context#text}
1625
+ *
1626
+ * @example
1627
+ * ```ts
1628
+ * app.get('/say', (c) => {
1629
+ * return c.text('Hello!')
1630
+ * })
1631
+ * ```
1632
+ */
1633
+ text = (text, arg, headers) => {
1634
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
1635
+ text,
1636
+ arg,
1637
+ setDefaultContentType(TEXT_PLAIN, headers)
1638
+ );
1639
+ };
1640
+ /**
1641
+ * `.json()` can render JSON as `Content-Type:application/json`.
1642
+ *
1643
+ * @see {@link https://hono.dev/docs/api/context#json}
1644
+ *
1645
+ * @example
1646
+ * ```ts
1647
+ * app.get('/api', (c) => {
1648
+ * return c.json({ message: 'Hello!' })
1649
+ * })
1650
+ * ```
1651
+ */
1652
+ json = (object, arg, headers) => {
1653
+ return this.#newResponse(
1654
+ JSON.stringify(object),
1655
+ arg,
1656
+ setDefaultContentType("application/json", headers)
1657
+ );
1658
+ };
1659
+ html = (html, arg, headers) => {
1660
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
1661
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
1662
+ };
1663
+ /**
1664
+ * `.redirect()` can Redirect, default status code is 302.
1665
+ *
1666
+ * @see {@link https://hono.dev/docs/api/context#redirect}
1667
+ *
1668
+ * @example
1669
+ * ```ts
1670
+ * app.get('/redirect', (c) => {
1671
+ * return c.redirect('/')
1672
+ * })
1673
+ * app.get('/redirect-permanently', (c) => {
1674
+ * return c.redirect('/', 301)
1675
+ * })
1676
+ * ```
1677
+ */
1678
+ redirect = (location, status) => {
1679
+ const locationString = String(location);
1680
+ this.header(
1681
+ "Location",
1682
+ // Multibyes should be encoded
1683
+ // eslint-disable-next-line no-control-regex
1684
+ !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
1685
+ );
1686
+ return this.newResponse(null, status ?? 302);
1687
+ };
1688
+ /**
1689
+ * `.notFound()` can return the Not Found Response.
1690
+ *
1691
+ * @see {@link https://hono.dev/docs/api/context#notfound}
1692
+ *
1693
+ * @example
1694
+ * ```ts
1695
+ * app.get('/notfound', (c) => {
1696
+ * return c.notFound()
1697
+ * })
1698
+ * ```
1699
+ */
1700
+ notFound = () => {
1701
+ this.#notFoundHandler ??= () => createResponseInstance();
1702
+ return this.#notFoundHandler(this);
1703
+ };
1704
+ };
1705
+
1706
+ // node_modules/hono/dist/router.js
1707
+ var METHOD_NAME_ALL = "ALL";
1708
+ var METHOD_NAME_ALL_LOWERCASE = "all";
1709
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1710
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1711
+ var UnsupportedPathError = class extends Error {
1712
+ };
1713
+
1714
+ // node_modules/hono/dist/utils/constants.js
1715
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1716
+
1717
+ // node_modules/hono/dist/hono-base.js
1718
+ var notFoundHandler = (c) => {
1719
+ return c.text("404 Not Found", 404);
1720
+ };
1721
+ var errorHandler = (err, c) => {
1722
+ if ("getResponse" in err) {
1723
+ const res = err.getResponse();
1724
+ return c.newResponse(res.body, res);
1725
+ }
1726
+ console.error(err);
1727
+ return c.text("Internal Server Error", 500);
1728
+ };
1729
+ var Hono = class _Hono {
1730
+ get;
1731
+ post;
1732
+ put;
1733
+ delete;
1734
+ options;
1735
+ patch;
1736
+ all;
1737
+ on;
1738
+ use;
1739
+ /*
1740
+ This class is like an abstract class and does not have a router.
1741
+ To use it, inherit the class and implement router in the constructor.
1742
+ */
1743
+ router;
1744
+ getPath;
1745
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1746
+ _basePath = "/";
1747
+ #path = "/";
1748
+ routes = [];
1749
+ constructor(options = {}) {
1750
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
1751
+ allMethods.forEach((method) => {
1752
+ this[method] = (args1, ...args2) => {
1753
+ if (typeof args1 === "string") {
1754
+ this.#path = args1;
1755
+ } else {
1756
+ this.#addRoute(method, this.#path, args1);
1757
+ }
1758
+ args2.forEach((handler) => {
1759
+ this.#addRoute(method, this.#path, handler);
1760
+ });
1761
+ return this;
1762
+ };
1763
+ });
1764
+ this.on = (method, path, ...handlers) => {
1765
+ for (const p of [path].flat()) {
1766
+ this.#path = p;
1767
+ for (const m of [method].flat()) {
1768
+ handlers.map((handler) => {
1769
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
1770
+ });
1771
+ }
1772
+ }
1773
+ return this;
1774
+ };
1775
+ this.use = (arg1, ...handlers) => {
1776
+ if (typeof arg1 === "string") {
1777
+ this.#path = arg1;
1778
+ } else {
1779
+ this.#path = "*";
1780
+ handlers.unshift(arg1);
1781
+ }
1782
+ handlers.forEach((handler) => {
1783
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1784
+ });
1785
+ return this;
1786
+ };
1787
+ const { strict, ...optionsWithoutStrict } = options;
1788
+ Object.assign(this, optionsWithoutStrict);
1789
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1790
+ }
1791
+ #clone() {
1792
+ const clone = new _Hono({
1793
+ router: this.router,
1794
+ getPath: this.getPath
1795
+ });
1796
+ clone.errorHandler = this.errorHandler;
1797
+ clone.#notFoundHandler = this.#notFoundHandler;
1798
+ clone.routes = this.routes;
1799
+ return clone;
1800
+ }
1801
+ #notFoundHandler = notFoundHandler;
1802
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1803
+ errorHandler = errorHandler;
1804
+ /**
1805
+ * `.route()` allows grouping other Hono instance in routes.
1806
+ *
1807
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
1808
+ *
1809
+ * @param {string} path - base Path
1810
+ * @param {Hono} app - other Hono instance
1811
+ * @returns {Hono} routed Hono instance
1812
+ *
1813
+ * @example
1814
+ * ```ts
1815
+ * const app = new Hono()
1816
+ * const app2 = new Hono()
1817
+ *
1818
+ * app2.get("/user", (c) => c.text("user"))
1819
+ * app.route("/api", app2) // GET /api/user
1820
+ * ```
1821
+ */
1822
+ route(path, app2) {
1823
+ const subApp = this.basePath(path);
1824
+ app2.routes.map((r) => {
1825
+ let handler;
1826
+ if (app2.errorHandler === errorHandler) {
1827
+ handler = r.handler;
1828
+ } else {
1829
+ handler = async (c, next) => (await compose([], app2.errorHandler)(c, () => r.handler(c, next))).res;
1830
+ handler[COMPOSED_HANDLER] = r.handler;
1831
+ }
1832
+ subApp.#addRoute(r.method, r.path, handler);
1833
+ });
1834
+ return this;
1835
+ }
1836
+ /**
1837
+ * `.basePath()` allows base paths to be specified.
1838
+ *
1839
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
1840
+ *
1841
+ * @param {string} path - base Path
1842
+ * @returns {Hono} changed Hono instance
1843
+ *
1844
+ * @example
1845
+ * ```ts
1846
+ * const api = new Hono().basePath('/api')
1847
+ * ```
1848
+ */
1849
+ basePath(path) {
1850
+ const subApp = this.#clone();
1851
+ subApp._basePath = mergePath(this._basePath, path);
1852
+ return subApp;
1853
+ }
1854
+ /**
1855
+ * `.onError()` handles an error and returns a customized Response.
1856
+ *
1857
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
1858
+ *
1859
+ * @param {ErrorHandler} handler - request Handler for error
1860
+ * @returns {Hono} changed Hono instance
1861
+ *
1862
+ * @example
1863
+ * ```ts
1864
+ * app.onError((err, c) => {
1865
+ * console.error(`${err}`)
1866
+ * return c.text('Custom Error Message', 500)
1867
+ * })
1868
+ * ```
1869
+ */
1870
+ onError = (handler) => {
1871
+ this.errorHandler = handler;
1872
+ return this;
1873
+ };
1874
+ /**
1875
+ * `.notFound()` allows you to customize a Not Found Response.
1876
+ *
1877
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
1878
+ *
1879
+ * @param {NotFoundHandler} handler - request handler for not-found
1880
+ * @returns {Hono} changed Hono instance
1881
+ *
1882
+ * @example
1883
+ * ```ts
1884
+ * app.notFound((c) => {
1885
+ * return c.text('Custom 404 Message', 404)
1886
+ * })
1887
+ * ```
1888
+ */
1889
+ notFound = (handler) => {
1890
+ this.#notFoundHandler = handler;
1891
+ return this;
1892
+ };
1893
+ /**
1894
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
1895
+ *
1896
+ * @see {@link https://hono.dev/docs/api/hono#mount}
1897
+ *
1898
+ * @param {string} path - base Path
1899
+ * @param {Function} applicationHandler - other Request Handler
1900
+ * @param {MountOptions} [options] - options of `.mount()`
1901
+ * @returns {Hono} mounted Hono instance
1902
+ *
1903
+ * @example
1904
+ * ```ts
1905
+ * import { Router as IttyRouter } from 'itty-router'
1906
+ * import { Hono } from 'hono'
1907
+ * // Create itty-router application
1908
+ * const ittyRouter = IttyRouter()
1909
+ * // GET /itty-router/hello
1910
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
1911
+ *
1912
+ * const app = new Hono()
1913
+ * app.mount('/itty-router', ittyRouter.handle)
1914
+ * ```
1915
+ *
1916
+ * @example
1917
+ * ```ts
1918
+ * const app = new Hono()
1919
+ * // Send the request to another application without modification.
1920
+ * app.mount('/app', anotherApp, {
1921
+ * replaceRequest: (req) => req,
1922
+ * })
1923
+ * ```
1924
+ */
1925
+ mount(path, applicationHandler, options) {
1926
+ let replaceRequest;
1927
+ let optionHandler;
1928
+ if (options) {
1929
+ if (typeof options === "function") {
1930
+ optionHandler = options;
1931
+ } else {
1932
+ optionHandler = options.optionHandler;
1933
+ if (options.replaceRequest === false) {
1934
+ replaceRequest = (request) => request;
1935
+ } else {
1936
+ replaceRequest = options.replaceRequest;
1937
+ }
1938
+ }
1939
+ }
1940
+ const getOptions = optionHandler ? (c) => {
1941
+ const options2 = optionHandler(c);
1942
+ return Array.isArray(options2) ? options2 : [options2];
1943
+ } : (c) => {
1944
+ let executionContext = void 0;
1945
+ try {
1946
+ executionContext = c.executionCtx;
1947
+ } catch {
1948
+ }
1949
+ return [c.env, executionContext];
1950
+ };
1951
+ replaceRequest ||= (() => {
1952
+ const mergedPath = mergePath(this._basePath, path);
1953
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1954
+ return (request) => {
1955
+ const url = new URL(request.url);
1956
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
1957
+ return new Request(url, request);
1958
+ };
1959
+ })();
1960
+ const handler = async (c, next) => {
1961
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1962
+ if (res) {
1963
+ return res;
1964
+ }
1965
+ await next();
1966
+ };
1967
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
1968
+ return this;
1969
+ }
1970
+ #addRoute(method, path, handler) {
1971
+ method = method.toUpperCase();
1972
+ path = mergePath(this._basePath, path);
1973
+ const r = { basePath: this._basePath, path, method, handler };
1974
+ this.router.add(method, path, [handler, r]);
1975
+ this.routes.push(r);
1976
+ }
1977
+ #handleError(err, c) {
1978
+ if (err instanceof Error) {
1979
+ return this.errorHandler(err, c);
1980
+ }
1981
+ throw err;
1982
+ }
1983
+ #dispatch(request, executionCtx, env, method) {
1984
+ if (method === "HEAD") {
1985
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1986
+ }
1987
+ const path = this.getPath(request, { env });
1988
+ const matchResult = this.router.match(method, path);
1989
+ const c = new Context(request, {
1990
+ path,
1991
+ matchResult,
1992
+ env,
1993
+ executionCtx,
1994
+ notFoundHandler: this.#notFoundHandler
1995
+ });
1996
+ if (matchResult[0].length === 1) {
1997
+ let res;
1998
+ try {
1999
+ res = matchResult[0][0][0][0](c, async () => {
2000
+ c.res = await this.#notFoundHandler(c);
2001
+ });
2002
+ } catch (err) {
2003
+ return this.#handleError(err, c);
2004
+ }
2005
+ return res instanceof Promise ? res.then(
2006
+ (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
2007
+ ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
2008
+ }
2009
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
2010
+ return (async () => {
2011
+ try {
2012
+ const context = await composed(c);
2013
+ if (!context.finalized) {
2014
+ throw new Error(
2015
+ "Context is not finalized. Did you forget to return a Response object or `await next()`?"
2016
+ );
2017
+ }
2018
+ return context.res;
2019
+ } catch (err) {
2020
+ return this.#handleError(err, c);
2021
+ }
2022
+ })();
2023
+ }
2024
+ /**
2025
+ * `.fetch()` will be entry point of your app.
2026
+ *
2027
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
2028
+ *
2029
+ * @param {Request} request - request Object of request
2030
+ * @param {Env} Env - env Object
2031
+ * @param {ExecutionContext} - context of execution
2032
+ * @returns {Response | Promise<Response>} response of request
2033
+ *
2034
+ */
2035
+ fetch = (request, ...rest) => {
2036
+ return this.#dispatch(request, rest[1], rest[0], request.method);
2037
+ };
2038
+ /**
2039
+ * `.request()` is a useful method for testing.
2040
+ * You can pass a URL or pathname to send a GET request.
2041
+ * app will return a Response object.
2042
+ * ```ts
2043
+ * test('GET /hello is ok', async () => {
2044
+ * const res = await app.request('/hello')
2045
+ * expect(res.status).toBe(200)
2046
+ * })
2047
+ * ```
2048
+ * @see https://hono.dev/docs/api/hono#request
2049
+ */
2050
+ request = (input, requestInit, Env, executionCtx) => {
2051
+ if (input instanceof Request) {
2052
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
2053
+ }
2054
+ input = input.toString();
2055
+ return this.fetch(
2056
+ new Request(
2057
+ /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
2058
+ requestInit
2059
+ ),
2060
+ Env,
2061
+ executionCtx
2062
+ );
2063
+ };
2064
+ /**
2065
+ * `.fire()` automatically adds a global fetch event listener.
2066
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
2067
+ * @deprecated
2068
+ * Use `fire` from `hono/service-worker` instead.
2069
+ * ```ts
2070
+ * import { Hono } from 'hono'
2071
+ * import { fire } from 'hono/service-worker'
2072
+ *
2073
+ * const app = new Hono()
2074
+ * // ...
2075
+ * fire(app)
2076
+ * ```
2077
+ * @see https://hono.dev/docs/api/hono#fire
2078
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
2079
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
2080
+ */
2081
+ fire = () => {
2082
+ addEventListener("fetch", (event) => {
2083
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
2084
+ });
2085
+ };
2086
+ };
2087
+
2088
+ // node_modules/hono/dist/router/reg-exp-router/matcher.js
2089
+ var emptyParam = [];
2090
+ function match(method, path) {
2091
+ const matchers = this.buildAllMatchers();
2092
+ const match2 = ((method2, path2) => {
2093
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
2094
+ const staticMatch = matcher[2][path2];
2095
+ if (staticMatch) {
2096
+ return staticMatch;
2097
+ }
2098
+ const match3 = path2.match(matcher[0]);
2099
+ if (!match3) {
2100
+ return [[], emptyParam];
2101
+ }
2102
+ const index = match3.indexOf("", 1);
2103
+ return [matcher[1][index], match3];
2104
+ });
2105
+ this.match = match2;
2106
+ return match2(method, path);
2107
+ }
2108
+
2109
+ // node_modules/hono/dist/router/reg-exp-router/node.js
2110
+ var LABEL_REG_EXP_STR = "[^/]+";
2111
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
2112
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
2113
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
2114
+ var regExpMetaChars = new Set(".\\+*[^]$()");
2115
+ function compareKey(a, b) {
2116
+ if (a.length === 1) {
2117
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
2118
+ }
2119
+ if (b.length === 1) {
2120
+ return 1;
2121
+ }
2122
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
2123
+ return 1;
2124
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
2125
+ return -1;
2126
+ }
2127
+ if (a === LABEL_REG_EXP_STR) {
2128
+ return 1;
2129
+ } else if (b === LABEL_REG_EXP_STR) {
2130
+ return -1;
2131
+ }
2132
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
2133
+ }
2134
+ var Node = class _Node {
2135
+ #index;
2136
+ #varIndex;
2137
+ #children = /* @__PURE__ */ Object.create(null);
2138
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
2139
+ if (tokens.length === 0) {
2140
+ if (this.#index !== void 0) {
2141
+ throw PATH_ERROR;
2142
+ }
2143
+ if (pathErrorCheckOnly) {
2144
+ return;
2145
+ }
2146
+ this.#index = index;
2147
+ return;
2148
+ }
2149
+ const [token, ...restTokens] = tokens;
2150
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
2151
+ let node;
2152
+ if (pattern) {
2153
+ const name = pattern[1];
2154
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
2155
+ if (name && pattern[2]) {
2156
+ if (regexpStr === ".*") {
2157
+ throw PATH_ERROR;
2158
+ }
2159
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
2160
+ if (/\((?!\?:)/.test(regexpStr)) {
2161
+ throw PATH_ERROR;
2162
+ }
2163
+ }
2164
+ node = this.#children[regexpStr];
2165
+ if (!node) {
2166
+ if (Object.keys(this.#children).some(
2167
+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2168
+ )) {
2169
+ throw PATH_ERROR;
2170
+ }
2171
+ if (pathErrorCheckOnly) {
2172
+ return;
2173
+ }
2174
+ node = this.#children[regexpStr] = new _Node();
2175
+ if (name !== "") {
2176
+ node.#varIndex = context.varIndex++;
2177
+ }
2178
+ }
2179
+ if (!pathErrorCheckOnly && name !== "") {
2180
+ paramMap.push([name, node.#varIndex]);
2181
+ }
2182
+ } else {
2183
+ node = this.#children[token];
2184
+ if (!node) {
2185
+ if (Object.keys(this.#children).some(
2186
+ (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
2187
+ )) {
2188
+ throw PATH_ERROR;
2189
+ }
2190
+ if (pathErrorCheckOnly) {
2191
+ return;
2192
+ }
2193
+ node = this.#children[token] = new _Node();
2194
+ }
2195
+ }
2196
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
2197
+ }
2198
+ buildRegExpStr() {
2199
+ const childKeys = Object.keys(this.#children).sort(compareKey);
2200
+ const strList = childKeys.map((k) => {
2201
+ const c = this.#children[k];
2202
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
2203
+ });
2204
+ if (typeof this.#index === "number") {
2205
+ strList.unshift(`#${this.#index}`);
2206
+ }
2207
+ if (strList.length === 0) {
2208
+ return "";
2209
+ }
2210
+ if (strList.length === 1) {
2211
+ return strList[0];
2212
+ }
2213
+ return "(?:" + strList.join("|") + ")";
2214
+ }
2215
+ };
2216
+
2217
+ // node_modules/hono/dist/router/reg-exp-router/trie.js
2218
+ var Trie = class {
2219
+ #context = { varIndex: 0 };
2220
+ #root = new Node();
2221
+ insert(path, index, pathErrorCheckOnly) {
2222
+ const paramAssoc = [];
2223
+ const groups = [];
2224
+ for (let i = 0; ; ) {
2225
+ let replaced = false;
2226
+ path = path.replace(/\{[^}]+\}/g, (m) => {
2227
+ const mark = `@\\${i}`;
2228
+ groups[i] = [mark, m];
2229
+ i++;
2230
+ replaced = true;
2231
+ return mark;
2232
+ });
2233
+ if (!replaced) {
2234
+ break;
2235
+ }
2236
+ }
2237
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
2238
+ for (let i = groups.length - 1; i >= 0; i--) {
2239
+ const [mark] = groups[i];
2240
+ for (let j = tokens.length - 1; j >= 0; j--) {
2241
+ if (tokens[j].indexOf(mark) !== -1) {
2242
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
2243
+ break;
2244
+ }
2245
+ }
2246
+ }
2247
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
2248
+ return paramAssoc;
2249
+ }
2250
+ buildRegExp() {
2251
+ let regexp = this.#root.buildRegExpStr();
2252
+ if (regexp === "") {
2253
+ return [/^$/, [], []];
2254
+ }
2255
+ let captureIndex = 0;
2256
+ const indexReplacementMap = [];
2257
+ const paramReplacementMap = [];
2258
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
2259
+ if (handlerIndex !== void 0) {
2260
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
2261
+ return "$()";
2262
+ }
2263
+ if (paramIndex !== void 0) {
2264
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
2265
+ return "";
2266
+ }
2267
+ return "";
2268
+ });
2269
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
2270
+ }
2271
+ };
2272
+
2273
+ // node_modules/hono/dist/router/reg-exp-router/router.js
2274
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
2275
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2276
+ function buildWildcardRegExp(path) {
2277
+ return wildcardRegExpCache[path] ??= new RegExp(
2278
+ path === "*" ? "" : `^${path.replace(
2279
+ /\/\*$|([.\\+*[^\]$()])/g,
2280
+ (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
2281
+ )}$`
2282
+ );
2283
+ }
2284
+ function clearWildcardRegExpCache() {
2285
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
2286
+ }
2287
+ function buildMatcherFromPreprocessedRoutes(routes) {
2288
+ const trie = new Trie();
2289
+ const handlerData = [];
2290
+ if (routes.length === 0) {
2291
+ return nullMatcher;
2292
+ }
2293
+ const routesWithStaticPathFlag = routes.map(
2294
+ (route) => [!/\*|\/:/.test(route[0]), ...route]
2295
+ ).sort(
2296
+ ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
2297
+ );
2298
+ const staticMap = /* @__PURE__ */ Object.create(null);
2299
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
2300
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
2301
+ if (pathErrorCheckOnly) {
2302
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
2303
+ } else {
2304
+ j++;
2305
+ }
2306
+ let paramAssoc;
2307
+ try {
2308
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
2309
+ } catch (e) {
2310
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
2311
+ }
2312
+ if (pathErrorCheckOnly) {
2313
+ continue;
2314
+ }
2315
+ handlerData[j] = handlers.map(([h, paramCount]) => {
2316
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
2317
+ paramCount -= 1;
2318
+ for (; paramCount >= 0; paramCount--) {
2319
+ const [key, value] = paramAssoc[paramCount];
2320
+ paramIndexMap[key] = value;
2321
+ }
2322
+ return [h, paramIndexMap];
2323
+ });
2324
+ }
2325
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
2326
+ for (let i = 0, len = handlerData.length; i < len; i++) {
2327
+ for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
2328
+ const map = handlerData[i][j]?.[1];
2329
+ if (!map) {
2330
+ continue;
2331
+ }
2332
+ const keys = Object.keys(map);
2333
+ for (let k = 0, len3 = keys.length; k < len3; k++) {
2334
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
2335
+ }
2336
+ }
2337
+ }
2338
+ const handlerMap = [];
2339
+ for (const i in indexReplacementMap) {
2340
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
2341
+ }
2342
+ return [regexp, handlerMap, staticMap];
2343
+ }
2344
+ function findMiddleware(middleware, path) {
2345
+ if (!middleware) {
2346
+ return void 0;
2347
+ }
2348
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
2349
+ if (buildWildcardRegExp(k).test(path)) {
2350
+ return [...middleware[k]];
2351
+ }
2352
+ }
2353
+ return void 0;
2354
+ }
2355
+ var RegExpRouter = class {
2356
+ name = "RegExpRouter";
2357
+ #middleware;
2358
+ #routes;
2359
+ constructor() {
2360
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2361
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
2362
+ }
2363
+ add(method, path, handler) {
2364
+ const middleware = this.#middleware;
2365
+ const routes = this.#routes;
2366
+ if (!middleware || !routes) {
2367
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2368
+ }
2369
+ if (!middleware[method]) {
2370
+ ;
2371
+ [middleware, routes].forEach((handlerMap) => {
2372
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
2373
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
2374
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
2375
+ });
2376
+ });
2377
+ }
2378
+ if (path === "/*") {
2379
+ path = "*";
2380
+ }
2381
+ const paramCount = (path.match(/\/:/g) || []).length;
2382
+ if (/\*$/.test(path)) {
2383
+ const re = buildWildcardRegExp(path);
2384
+ if (method === METHOD_NAME_ALL) {
2385
+ Object.keys(middleware).forEach((m) => {
2386
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2387
+ });
2388
+ } else {
2389
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
2390
+ }
2391
+ Object.keys(middleware).forEach((m) => {
2392
+ if (method === METHOD_NAME_ALL || method === m) {
2393
+ Object.keys(middleware[m]).forEach((p) => {
2394
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
2395
+ });
2396
+ }
2397
+ });
2398
+ Object.keys(routes).forEach((m) => {
2399
+ if (method === METHOD_NAME_ALL || method === m) {
2400
+ Object.keys(routes[m]).forEach(
2401
+ (p) => re.test(p) && routes[m][p].push([handler, paramCount])
2402
+ );
2403
+ }
2404
+ });
2405
+ return;
2406
+ }
2407
+ const paths = checkOptionalParameter(path) || [path];
2408
+ for (let i = 0, len = paths.length; i < len; i++) {
2409
+ const path2 = paths[i];
2410
+ Object.keys(routes).forEach((m) => {
2411
+ if (method === METHOD_NAME_ALL || method === m) {
2412
+ routes[m][path2] ||= [
2413
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
2414
+ ];
2415
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
2416
+ }
2417
+ });
2418
+ }
2419
+ }
2420
+ match = match;
2421
+ buildAllMatchers() {
2422
+ const matchers = /* @__PURE__ */ Object.create(null);
2423
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
2424
+ matchers[method] ||= this.#buildMatcher(method);
2425
+ });
2426
+ this.#middleware = this.#routes = void 0;
2427
+ clearWildcardRegExpCache();
2428
+ return matchers;
2429
+ }
2430
+ #buildMatcher(method) {
2431
+ const routes = [];
2432
+ let hasOwnRoute = method === METHOD_NAME_ALL;
2433
+ [this.#middleware, this.#routes].forEach((r) => {
2434
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
2435
+ if (ownRoute.length !== 0) {
2436
+ hasOwnRoute ||= true;
2437
+ routes.push(...ownRoute);
2438
+ } else if (method !== METHOD_NAME_ALL) {
2439
+ routes.push(
2440
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]])
2441
+ );
2442
+ }
2443
+ });
2444
+ if (!hasOwnRoute) {
2445
+ return null;
2446
+ } else {
2447
+ return buildMatcherFromPreprocessedRoutes(routes);
2448
+ }
2449
+ }
2450
+ };
2451
+
2452
+ // node_modules/hono/dist/router/smart-router/router.js
2453
+ var SmartRouter = class {
2454
+ name = "SmartRouter";
2455
+ #routers = [];
2456
+ #routes = [];
2457
+ constructor(init) {
2458
+ this.#routers = init.routers;
2459
+ }
2460
+ add(method, path, handler) {
2461
+ if (!this.#routes) {
2462
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
2463
+ }
2464
+ this.#routes.push([method, path, handler]);
2465
+ }
2466
+ match(method, path) {
2467
+ if (!this.#routes) {
2468
+ throw new Error("Fatal error");
2469
+ }
2470
+ const routers = this.#routers;
2471
+ const routes = this.#routes;
2472
+ const len = routers.length;
2473
+ let i = 0;
2474
+ let res;
2475
+ for (; i < len; i++) {
2476
+ const router = routers[i];
2477
+ try {
2478
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
2479
+ router.add(...routes[i2]);
2480
+ }
2481
+ res = router.match(method, path);
2482
+ } catch (e) {
2483
+ if (e instanceof UnsupportedPathError) {
2484
+ continue;
2485
+ }
2486
+ throw e;
2487
+ }
2488
+ this.match = router.match.bind(router);
2489
+ this.#routers = [router];
2490
+ this.#routes = void 0;
2491
+ break;
2492
+ }
2493
+ if (i === len) {
2494
+ throw new Error("Fatal error");
2495
+ }
2496
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
2497
+ return res;
2498
+ }
2499
+ get activeRouter() {
2500
+ if (this.#routes || this.#routers.length !== 1) {
2501
+ throw new Error("No active router has been determined yet.");
2502
+ }
2503
+ return this.#routers[0];
2504
+ }
2505
+ };
2506
+
2507
+ // node_modules/hono/dist/router/trie-router/node.js
2508
+ var emptyParams = /* @__PURE__ */ Object.create(null);
2509
+ var hasChildren = (children) => {
2510
+ for (const _ in children) {
2511
+ return true;
2512
+ }
2513
+ return false;
2514
+ };
2515
+ var Node2 = class _Node2 {
2516
+ #methods;
2517
+ #children;
2518
+ #patterns;
2519
+ #order = 0;
2520
+ #params = emptyParams;
2521
+ constructor(method, handler, children) {
2522
+ this.#children = children || /* @__PURE__ */ Object.create(null);
2523
+ this.#methods = [];
2524
+ if (method && handler) {
2525
+ const m = /* @__PURE__ */ Object.create(null);
2526
+ m[method] = { handler, possibleKeys: [], score: 0 };
2527
+ this.#methods = [m];
2528
+ }
2529
+ this.#patterns = [];
2530
+ }
2531
+ insert(method, path, handler) {
2532
+ this.#order = ++this.#order;
2533
+ let curNode = this;
2534
+ const parts = splitRoutingPath(path);
2535
+ const possibleKeys = [];
2536
+ for (let i = 0, len = parts.length; i < len; i++) {
2537
+ const p = parts[i];
2538
+ const nextP = parts[i + 1];
2539
+ const pattern = getPattern(p, nextP);
2540
+ const key = Array.isArray(pattern) ? pattern[0] : p;
2541
+ if (key in curNode.#children) {
2542
+ curNode = curNode.#children[key];
2543
+ if (pattern) {
2544
+ possibleKeys.push(pattern[1]);
2545
+ }
2546
+ continue;
2547
+ }
2548
+ curNode.#children[key] = new _Node2();
2549
+ if (pattern) {
2550
+ curNode.#patterns.push(pattern);
2551
+ possibleKeys.push(pattern[1]);
2552
+ }
2553
+ curNode = curNode.#children[key];
2554
+ }
2555
+ curNode.#methods.push({
2556
+ [method]: {
2557
+ handler,
2558
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
2559
+ score: this.#order
2560
+ }
2561
+ });
2562
+ return curNode;
2563
+ }
2564
+ #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
2565
+ for (let i = 0, len = node.#methods.length; i < len; i++) {
2566
+ const m = node.#methods[i];
2567
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
2568
+ const processedSet = {};
2569
+ if (handlerSet !== void 0) {
2570
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
2571
+ handlerSets.push(handlerSet);
2572
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
2573
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
2574
+ const key = handlerSet.possibleKeys[i2];
2575
+ const processed = processedSet[handlerSet.score];
2576
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
2577
+ processedSet[handlerSet.score] = true;
2578
+ }
2579
+ }
2580
+ }
2581
+ }
2582
+ }
2583
+ search(method, path) {
2584
+ const handlerSets = [];
2585
+ this.#params = emptyParams;
2586
+ const curNode = this;
2587
+ let curNodes = [curNode];
2588
+ const parts = splitPath(path);
2589
+ const curNodesQueue = [];
2590
+ const len = parts.length;
2591
+ let partOffsets = null;
2592
+ for (let i = 0; i < len; i++) {
2593
+ const part = parts[i];
2594
+ const isLast = i === len - 1;
2595
+ const tempNodes = [];
2596
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
2597
+ const node = curNodes[j];
2598
+ const nextNode = node.#children[part];
2599
+ if (nextNode) {
2600
+ nextNode.#params = node.#params;
2601
+ if (isLast) {
2602
+ if (nextNode.#children["*"]) {
2603
+ this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
2604
+ }
2605
+ this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
2606
+ } else {
2607
+ tempNodes.push(nextNode);
2608
+ }
2609
+ }
2610
+ for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
2611
+ const pattern = node.#patterns[k];
2612
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
2613
+ if (pattern === "*") {
2614
+ const astNode = node.#children["*"];
2615
+ if (astNode) {
2616
+ this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
2617
+ astNode.#params = params;
2618
+ tempNodes.push(astNode);
2619
+ }
2620
+ continue;
2621
+ }
2622
+ const [key, name, matcher] = pattern;
2623
+ if (!part && !(matcher instanceof RegExp)) {
2624
+ continue;
2625
+ }
2626
+ const child = node.#children[key];
2627
+ if (matcher instanceof RegExp) {
2628
+ if (partOffsets === null) {
2629
+ partOffsets = new Array(len);
2630
+ let offset = path[0] === "/" ? 1 : 0;
2631
+ for (let p = 0; p < len; p++) {
2632
+ partOffsets[p] = offset;
2633
+ offset += parts[p].length + 1;
2634
+ }
2635
+ }
2636
+ const restPathString = path.substring(partOffsets[i]);
2637
+ const m = matcher.exec(restPathString);
2638
+ if (m) {
2639
+ params[name] = m[0];
2640
+ this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
2641
+ if (hasChildren(child.#children)) {
2642
+ child.#params = params;
2643
+ const componentCount = m[0].match(/\//)?.length ?? 0;
2644
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
2645
+ targetCurNodes.push(child);
2646
+ }
2647
+ continue;
2648
+ }
2649
+ }
2650
+ if (matcher === true || matcher.test(part)) {
2651
+ params[name] = part;
2652
+ if (isLast) {
2653
+ this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
2654
+ if (child.#children["*"]) {
2655
+ this.#pushHandlerSets(
2656
+ handlerSets,
2657
+ child.#children["*"],
2658
+ method,
2659
+ params,
2660
+ node.#params
2661
+ );
2662
+ }
2663
+ } else {
2664
+ child.#params = params;
2665
+ tempNodes.push(child);
2666
+ }
2667
+ }
2668
+ }
2669
+ }
2670
+ const shifted = curNodesQueue.shift();
2671
+ curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
2672
+ }
2673
+ if (handlerSets.length > 1) {
2674
+ handlerSets.sort((a, b) => {
2675
+ return a.score - b.score;
2676
+ });
2677
+ }
2678
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
2679
+ }
2680
+ };
2681
+
2682
+ // node_modules/hono/dist/router/trie-router/router.js
2683
+ var TrieRouter = class {
2684
+ name = "TrieRouter";
2685
+ #node;
2686
+ constructor() {
2687
+ this.#node = new Node2();
2688
+ }
2689
+ add(method, path, handler) {
2690
+ const results = checkOptionalParameter(path);
2691
+ if (results) {
2692
+ for (let i = 0, len = results.length; i < len; i++) {
2693
+ this.#node.insert(method, results[i], handler);
2694
+ }
2695
+ return;
2696
+ }
2697
+ this.#node.insert(method, path, handler);
2698
+ }
2699
+ match(method, path) {
2700
+ return this.#node.search(method, path);
2701
+ }
2702
+ };
2703
+
2704
+ // node_modules/hono/dist/hono.js
2705
+ var Hono2 = class extends Hono {
2706
+ /**
2707
+ * Creates an instance of the Hono class.
2708
+ *
2709
+ * @param options - Optional configuration options for the Hono instance.
2710
+ */
2711
+ constructor(options = {}) {
2712
+ super(options);
2713
+ this.router = options.router ?? new SmartRouter({
2714
+ routers: [new RegExpRouter(), new TrieRouter()]
2715
+ });
2716
+ }
2717
+ };
2718
+
2719
+ // node_modules/hono/dist/utils/stream.js
2720
+ var StreamingApi = class {
2721
+ writer;
2722
+ encoder;
2723
+ writable;
2724
+ abortSubscribers = [];
2725
+ responseReadable;
2726
+ /**
2727
+ * Whether the stream has been aborted.
2728
+ */
2729
+ aborted = false;
2730
+ /**
2731
+ * Whether the stream has been closed normally.
2732
+ */
2733
+ closed = false;
2734
+ constructor(writable, _readable) {
2735
+ this.writable = writable;
2736
+ this.writer = writable.getWriter();
2737
+ this.encoder = new TextEncoder();
2738
+ const reader = _readable.getReader();
2739
+ this.abortSubscribers.push(async () => {
2740
+ await reader.cancel();
2741
+ });
2742
+ this.responseReadable = new ReadableStream({
2743
+ async pull(controller) {
2744
+ const { done, value } = await reader.read();
2745
+ done ? controller.close() : controller.enqueue(value);
2746
+ },
2747
+ cancel: () => {
2748
+ this.abort();
2749
+ }
2750
+ });
2751
+ }
2752
+ async write(input) {
2753
+ try {
2754
+ if (typeof input === "string") {
2755
+ input = this.encoder.encode(input);
2756
+ }
2757
+ await this.writer.write(input);
2758
+ } catch {
2759
+ }
2760
+ return this;
2761
+ }
2762
+ async writeln(input) {
2763
+ await this.write(input + "\n");
2764
+ return this;
2765
+ }
2766
+ sleep(ms) {
2767
+ return new Promise((res) => setTimeout(res, ms));
2768
+ }
2769
+ async close() {
2770
+ try {
2771
+ await this.writer.close();
2772
+ } catch {
2773
+ }
2774
+ this.closed = true;
2775
+ }
2776
+ async pipe(body) {
2777
+ this.writer.releaseLock();
2778
+ await body.pipeTo(this.writable, { preventClose: true });
2779
+ this.writer = this.writable.getWriter();
2780
+ }
2781
+ onAbort(listener) {
2782
+ this.abortSubscribers.push(listener);
2783
+ }
2784
+ /**
2785
+ * Abort the stream.
2786
+ * You can call this method when stream is aborted by external event.
2787
+ */
2788
+ abort() {
2789
+ if (!this.aborted) {
2790
+ this.aborted = true;
2791
+ this.abortSubscribers.forEach((subscriber) => subscriber());
2792
+ }
2793
+ }
2794
+ };
2795
+
2796
+ // node_modules/hono/dist/helper/streaming/utils.js
2797
+ var isOldBunVersion = () => {
2798
+ const version = typeof Bun !== "undefined" ? Bun.version : void 0;
2799
+ if (version === void 0) {
2800
+ return false;
2801
+ }
2802
+ const result = version.startsWith("1.1") || version.startsWith("1.0") || version.startsWith("0.");
2803
+ isOldBunVersion = () => result;
2804
+ return result;
2805
+ };
2806
+
2807
+ // node_modules/hono/dist/helper/streaming/stream.js
2808
+ var contextStash = /* @__PURE__ */ new WeakMap();
2809
+ var stream = (c, cb, onError) => {
2810
+ const { readable, writable } = new TransformStream();
2811
+ const stream2 = new StreamingApi(writable, readable);
2812
+ if (isOldBunVersion()) {
2813
+ c.req.raw.signal.addEventListener("abort", () => {
2814
+ if (!stream2.closed) {
2815
+ stream2.abort();
2816
+ }
2817
+ });
2818
+ }
2819
+ contextStash.set(stream2.responseReadable, c);
2820
+ (async () => {
2821
+ try {
2822
+ await cb(stream2);
2823
+ } catch (e) {
2824
+ if (e === void 0) {
2825
+ } else if (e instanceof Error && onError) {
2826
+ await onError(e, stream2);
2827
+ } else {
2828
+ console.error(e);
2829
+ }
2830
+ } finally {
2831
+ stream2.close();
2832
+ }
2833
+ })();
2834
+ return c.newResponse(stream2.responseReadable);
2835
+ };
2836
+
2837
+ // src/session.ts
2838
+ import { randomUUID, createHash } from "node:crypto";
2839
+ var SessionStore = class {
2840
+ /** response_id → message history */
2841
+ history = /* @__PURE__ */ new Map();
2842
+ /** call_id → reasoning_content */
2843
+ reasoning = /* @__PURE__ */ new Map();
2844
+ /** content-hash → reasoning_content (turn-level fallback) */
2845
+ turnReasoning = /* @__PURE__ */ new Map();
2846
+ // ── Reasoning by call_id ────────────────────────────────────────────────────
2847
+ /** Store reasoning_content keyed by the tool call_id. */
2848
+ storeReasoning(callId, reasoning) {
2849
+ if (reasoning) {
2850
+ this.reasoning.set(callId, reasoning);
2851
+ }
2852
+ }
2853
+ /** Look up stored reasoning_content for a call_id. */
2854
+ getReasoning(callId) {
2855
+ return this.reasoning.get(callId);
2856
+ }
2857
+ // ── Reasoning by turn content (fallback) ────────────────────────────────────
2858
+ /** Store reasoning_content for an assistant turn, keyed by content hash. */
2859
+ storeTurnReasoning(_prior, assistant, reasoning) {
2860
+ if (!reasoning) return;
2861
+ const content = assistant.content ?? "";
2862
+ if (content) {
2863
+ this.turnReasoning.set(this.contentKey(content), reasoning);
2864
+ }
2865
+ if (assistant.tool_calls) {
2866
+ for (const tc of assistant.tool_calls) {
2867
+ const id = tc.id;
2868
+ if (id) {
2869
+ this.storeReasoning(id, reasoning);
2870
+ }
2871
+ }
2872
+ }
2873
+ }
2874
+ /** Look up reasoning_content for an assistant turn by its text content. */
2875
+ getTurnReasoning(_prior, assistant) {
2876
+ const content = assistant.content ?? "";
2877
+ if (!content) return void 0;
2878
+ return this.turnReasoning.get(this.contentKey(content));
2879
+ }
2880
+ /** Hash assistant message content for turn-level reasoning lookup. */
2881
+ contentKey(content) {
2882
+ return createHash("sha256").update(content).digest("hex");
2883
+ }
2884
+ // ── History storage ─────────────────────────────────────────────────────────
2885
+ /** Retrieve history for a prior response_id, or empty array if not found. */
2886
+ getHistory(responseId) {
2887
+ return this.history.get(responseId) ?? [];
2888
+ }
2889
+ /** Allocate a fresh response_id. */
2890
+ newId() {
2891
+ return `resp_${randomUUID().replace(/-/g, "")}`;
2892
+ }
2893
+ /** Store under a pre-allocated response_id (streaming path). */
2894
+ saveWithId(id, messages) {
2895
+ this.history.set(id, messages);
2896
+ }
2897
+ /** Allocate an id and store atomically (non-streaming path). */
2898
+ save(messages) {
2899
+ const id = this.newId();
2900
+ this.history.set(id, messages);
2901
+ return id;
2902
+ }
2903
+ };
2904
+
2905
+ // src/translate.ts
2906
+ function toChatRequest(req, history, sessions) {
2907
+ const messages = [...history];
2908
+ const systemText = req.instructions ?? req.system;
2909
+ if (systemText) {
2910
+ if (messages.length === 0 || messages[0].role !== "system") {
2911
+ messages.unshift({
2912
+ role: "system",
2913
+ content: systemText
2914
+ });
2915
+ }
2916
+ }
2917
+ if (typeof req.input === "string") {
2918
+ messages.push({ role: "user", content: req.input });
2919
+ } else {
2920
+ const items = req.input;
2921
+ let i = 0;
2922
+ while (i < items.length) {
2923
+ const item = items[i];
2924
+ const itemType = item.type ?? "";
2925
+ if (itemType === "function_call") {
2926
+ const grouped = [];
2927
+ let reasoningContent;
2928
+ while (i < items.length) {
2929
+ const cur = items[i];
2930
+ if ((cur.type ?? "") !== "function_call") break;
2931
+ const callId = cur.call_id ?? "";
2932
+ const name = cur.name ?? "";
2933
+ const args2 = cur.arguments ?? "{}";
2934
+ if (!reasoningContent) {
2935
+ reasoningContent = sessions.getReasoning(callId);
2936
+ }
2937
+ grouped.push({
2938
+ id: callId,
2939
+ type: "function",
2940
+ function: { name, arguments: args2 }
2941
+ });
2942
+ i++;
2943
+ }
2944
+ const msg = {
2945
+ role: "assistant",
2946
+ content: null,
2947
+ reasoning_content: reasoningContent ?? null,
2948
+ tool_calls: grouped
2949
+ };
2950
+ if (!msg.reasoning_content) {
2951
+ msg.reasoning_content = sessions.getTurnReasoning(messages, msg) ?? null;
2952
+ }
2953
+ messages.push(msg);
2954
+ } else if (itemType === "function_call_output") {
2955
+ const callId = item.call_id ?? "";
2956
+ const output = item.output ?? "";
2957
+ messages.push({
2958
+ role: "tool",
2959
+ content: output,
2960
+ tool_call_id: callId
2961
+ });
2962
+ i++;
2963
+ } else {
2964
+ let role = item.role ?? "user";
2965
+ if (role === "developer") role = "system";
2966
+ const content = valueToText(item.content);
2967
+ const msg = { role, content };
2968
+ if (role === "assistant") {
2969
+ msg.reasoning_content = sessions.getTurnReasoning(messages, msg) ?? null;
2970
+ }
2971
+ messages.push(msg);
2972
+ i++;
2973
+ }
2974
+ }
2975
+ }
2976
+ const filteredTools = (req.tools ?? []).filter((t) => t.type === "function").map(convertTool);
2977
+ const reordered = reorderForToolCalls(messages);
2978
+ return {
2979
+ model: req.model,
2980
+ messages: reordered,
2981
+ ...filteredTools.length > 0 ? { tools: filteredTools } : {},
2982
+ ...req.temperature != null ? { temperature: req.temperature } : {},
2983
+ ...req.max_output_tokens != null ? { max_tokens: req.max_output_tokens } : {},
2984
+ stream: req.stream ?? false
2985
+ };
2986
+ }
2987
+ function convertTool(tool) {
2988
+ if ("function" in tool) return tool;
2989
+ if (tool.type === "function") {
2990
+ const func = {};
2991
+ if ("name" in tool) func.name = tool.name;
2992
+ if ("description" in tool) func.description = tool.description;
2993
+ if ("parameters" in tool) func.parameters = tool.parameters;
2994
+ if ("strict" in tool) func.strict = tool.strict;
2995
+ return { type: "function", function: func };
2996
+ }
2997
+ return tool;
2998
+ }
2999
+ function fromChatResponse(id, model, chat) {
3000
+ const choice = chat.choices?.[0] ?? {
3001
+ message: { role: "assistant", content: "" }
3002
+ };
3003
+ const text = choice.message.content ?? "";
3004
+ const usage = chat.usage ?? {
3005
+ prompt_tokens: 0,
3006
+ completion_tokens: 0,
3007
+ total_tokens: 0
3008
+ };
3009
+ const output = [
3010
+ {
3011
+ type: "message",
3012
+ role: "assistant",
3013
+ content: [{ type: "output_text", text }]
3014
+ }
3015
+ ];
3016
+ const respUsage = {
3017
+ input_tokens: usage.prompt_tokens,
3018
+ output_tokens: usage.completion_tokens,
3019
+ total_tokens: usage.total_tokens
3020
+ };
3021
+ const response = {
3022
+ id,
3023
+ object: "response",
3024
+ model,
3025
+ output,
3026
+ usage: respUsage
3027
+ };
3028
+ return { response, assistantMessage: choice.message };
3029
+ }
3030
+ function valueToText(v) {
3031
+ if (v == null) return "";
3032
+ if (typeof v === "string") return v;
3033
+ if (Array.isArray(v)) {
3034
+ return v.map((p) => p.text ?? "").join("");
3035
+ }
3036
+ return String(v);
3037
+ }
3038
+ function reorderForToolCalls(messages) {
3039
+ const hasToolCalls = messages.some(
3040
+ (m) => m.role === "assistant" && m.tool_calls?.length
3041
+ );
3042
+ if (!hasToolCalls) return messages;
3043
+ const toolMsgMap = /* @__PURE__ */ new Map();
3044
+ for (const msg of messages) {
3045
+ if (msg.role === "tool" && msg.tool_call_id) {
3046
+ toolMsgMap.set(msg.tool_call_id, msg);
3047
+ }
3048
+ }
3049
+ const result = [];
3050
+ const consumedToolIds = /* @__PURE__ */ new Set();
3051
+ for (const msg of messages) {
3052
+ if (msg.role === "tool" && msg.tool_call_id) {
3053
+ continue;
3054
+ }
3055
+ result.push(msg);
3056
+ if (msg.role === "assistant" && msg.tool_calls?.length) {
3057
+ for (const tc of msg.tool_calls) {
3058
+ const callId = tc.id;
3059
+ if (callId) {
3060
+ const toolMsg = toolMsgMap.get(callId);
3061
+ if (toolMsg) {
3062
+ result.push(toolMsg);
3063
+ consumedToolIds.add(callId);
3064
+ } else {
3065
+ result.push({
3066
+ role: "tool",
3067
+ content: "(no output)",
3068
+ tool_call_id: callId
3069
+ });
3070
+ consumedToolIds.add(callId);
3071
+ }
3072
+ }
3073
+ }
3074
+ }
3075
+ }
3076
+ for (const [callId, msg] of toolMsgMap) {
3077
+ if (!consumedToolIds.has(callId)) {
3078
+ result.push(msg);
3079
+ }
3080
+ }
3081
+ return result;
3082
+ }
3083
+
3084
+ // src/stream.ts
3085
+ import { randomUUID as randomUUID2 } from "node:crypto";
3086
+ async function* translateStream(args2, signal) {
3087
+ const {
3088
+ url,
3089
+ apiKey,
3090
+ chatReq,
3091
+ responseId,
3092
+ sessions,
3093
+ priorMessages,
3094
+ requestMessages,
3095
+ model
3096
+ } = args2;
3097
+ try {
3098
+ const msgItemId = `msg_${randomUUID2().replace(/-/g, "")}`;
3099
+ const createdAt = Math.floor(Date.now() / 1e3);
3100
+ yield formatSSE("response.created", {
3101
+ type: "response.created",
3102
+ response: {
3103
+ id: responseId,
3104
+ object: "response",
3105
+ created_at: createdAt,
3106
+ status: "in_progress",
3107
+ model,
3108
+ output: [],
3109
+ usage: null
3110
+ }
3111
+ });
3112
+ let upstream;
3113
+ try {
3114
+ const headers = {
3115
+ "Content-Type": "application/json"
3116
+ };
3117
+ if (apiKey) {
3118
+ headers["Authorization"] = `Bearer ${apiKey}`;
3119
+ }
3120
+ console.log(`[transfer] POST ${url} model=${chatReq.model} stream=${chatReq.stream} key=${apiKey ? `${apiKey.slice(0, 6)}...` : "(empty)"}`);
3121
+ upstream = await fetch(url, {
3122
+ method: "POST",
3123
+ headers,
3124
+ body: JSON.stringify(chatReq),
3125
+ signal
3126
+ });
3127
+ } catch (e) {
3128
+ if (signal?.aborted) return;
3129
+ const msg = e instanceof Error ? e.message : String(e);
3130
+ const cause = e instanceof Error && e.cause ? ` | cause: ${e.cause}` : "";
3131
+ console.error(`[transfer] fetch failed: ${msg}${cause}`);
3132
+ yield sseFailed(responseId, model, "connection_error", msg);
3133
+ return;
3134
+ }
3135
+ if (!upstream.ok) {
3136
+ const body = await upstream.text().catch(() => "");
3137
+ console.error(`[transfer] upstream ${upstream.status}: ${body.slice(0, 500)}`);
3138
+ yield sseFailed(responseId, model, String(upstream.status), body);
3139
+ return;
3140
+ }
3141
+ if (!upstream.body) {
3142
+ yield sseFailed(responseId, model, "no_body", "upstream returned no body");
3143
+ return;
3144
+ }
3145
+ let accumulatedText = "";
3146
+ let accumulatedReasoning = "";
3147
+ const toolCalls = /* @__PURE__ */ new Map();
3148
+ let emittedMessageItem = false;
3149
+ let done = false;
3150
+ const reader = upstream.body.getReader();
3151
+ const decoder = new TextDecoder();
3152
+ let buffer = "";
3153
+ try {
3154
+ while (!done) {
3155
+ if (signal?.aborted) break;
3156
+ let readResult;
3157
+ try {
3158
+ readResult = await reader.read();
3159
+ } catch (e) {
3160
+ if (signal?.aborted) break;
3161
+ console.error(`[transfer] stream read error:`, e);
3162
+ break;
3163
+ }
3164
+ if (readResult.done) break;
3165
+ buffer += decoder.decode(readResult.value, { stream: true });
3166
+ const lines = buffer.split(/\r?\n/);
3167
+ buffer = lines.pop() ?? "";
3168
+ let currentData = "";
3169
+ for (const line of lines) {
3170
+ if (line.startsWith(":")) continue;
3171
+ if (line.startsWith("data:")) {
3172
+ const value = line.slice(5);
3173
+ const data = value.startsWith(" ") ? value.slice(1) : value;
3174
+ if (data === "[DONE]") {
3175
+ done = true;
3176
+ break;
3177
+ }
3178
+ if (currentData) {
3179
+ currentData += "\n" + data;
3180
+ } else {
3181
+ currentData = data;
3182
+ }
3183
+ } else if (line.trim() === "" && currentData) {
3184
+ try {
3185
+ const chunk = JSON.parse(currentData);
3186
+ const err = chunk.error;
3187
+ if (err) {
3188
+ console.error(`[transfer] upstream error in stream:`, err);
3189
+ }
3190
+ for (const choice of chunk.choices ?? []) {
3191
+ const rc = choice.delta?.reasoning_content;
3192
+ if (rc) {
3193
+ accumulatedReasoning += rc;
3194
+ }
3195
+ const content = choice.delta?.content ?? "";
3196
+ if (content) {
3197
+ if (!emittedMessageItem) {
3198
+ yield formatSSE("response.output_item.added", {
3199
+ type: "response.output_item.added",
3200
+ output_index: 0,
3201
+ item: {
3202
+ type: "message",
3203
+ id: msgItemId,
3204
+ role: "assistant",
3205
+ status: "in_progress",
3206
+ content: []
3207
+ }
3208
+ });
3209
+ emittedMessageItem = true;
3210
+ }
3211
+ accumulatedText += content;
3212
+ yield formatSSE("response.output_text.delta", {
3213
+ type: "response.output_text.delta",
3214
+ item_id: msgItemId,
3215
+ output_index: 0,
3216
+ content_index: 0,
3217
+ delta: content
3218
+ });
3219
+ }
3220
+ const deltaCalls = choice.delta?.tool_calls;
3221
+ if (deltaCalls) {
3222
+ for (const dc of deltaCalls) {
3223
+ let entry = toolCalls.get(dc.index);
3224
+ if (!entry) {
3225
+ entry = { id: "", name: "", arguments: "" };
3226
+ toolCalls.set(dc.index, entry);
3227
+ }
3228
+ if (dc.id) entry.id = dc.id;
3229
+ if (dc.function?.name) entry.name += dc.function.name;
3230
+ if (dc.function?.arguments)
3231
+ entry.arguments += dc.function.arguments;
3232
+ }
3233
+ }
3234
+ if (choice.finish_reason) {
3235
+ }
3236
+ }
3237
+ } catch (parseErr) {
3238
+ console.warn(`[transfer] SSE chunk parse error: ${parseErr} \u2014 data: ${currentData.slice(0, 200)}`);
3239
+ }
3240
+ currentData = "";
3241
+ }
3242
+ }
3243
+ }
3244
+ } finally {
3245
+ reader.releaseLock();
3246
+ try {
3247
+ await upstream.body?.cancel();
3248
+ } catch {
3249
+ }
3250
+ }
3251
+ if (emittedMessageItem) {
3252
+ yield formatSSE("response.output_item.done", {
3253
+ type: "response.output_item.done",
3254
+ output_index: 0,
3255
+ item: {
3256
+ type: "message",
3257
+ id: msgItemId,
3258
+ role: "assistant",
3259
+ status: "completed",
3260
+ content: [{ type: "output_text", text: accumulatedText }]
3261
+ }
3262
+ });
3263
+ }
3264
+ const baseIndex = emittedMessageItem ? 1 : 0;
3265
+ const fcItems = [];
3266
+ let relIdx = 0;
3267
+ for (const [, tc] of toolCalls) {
3268
+ const fcItemId = `fc_${randomUUID2().replace(/-/g, "")}`;
3269
+ const outputIndex = baseIndex + relIdx;
3270
+ yield formatSSE("response.output_item.added", {
3271
+ type: "response.output_item.added",
3272
+ output_index: outputIndex,
3273
+ item: {
3274
+ type: "function_call",
3275
+ id: fcItemId,
3276
+ call_id: tc.id,
3277
+ name: tc.name,
3278
+ arguments: "",
3279
+ status: "in_progress"
3280
+ }
3281
+ });
3282
+ if (tc.arguments) {
3283
+ yield formatSSE("response.function_call_arguments.delta", {
3284
+ type: "response.function_call_arguments.delta",
3285
+ item_id: fcItemId,
3286
+ output_index: outputIndex,
3287
+ delta: tc.arguments
3288
+ });
3289
+ }
3290
+ yield formatSSE("response.output_item.done", {
3291
+ type: "response.output_item.done",
3292
+ output_index: outputIndex,
3293
+ item: {
3294
+ type: "function_call",
3295
+ id: fcItemId,
3296
+ call_id: tc.id,
3297
+ name: tc.name,
3298
+ arguments: tc.arguments,
3299
+ status: "completed"
3300
+ }
3301
+ });
3302
+ fcItems.push({
3303
+ type: "function_call",
3304
+ id: fcItemId,
3305
+ call_id: tc.id,
3306
+ name: tc.name,
3307
+ arguments: tc.arguments,
3308
+ status: "completed"
3309
+ });
3310
+ relIdx++;
3311
+ }
3312
+ for (const tc of toolCalls.values()) {
3313
+ if (tc.id) {
3314
+ sessions.storeReasoning(tc.id, accumulatedReasoning);
3315
+ }
3316
+ }
3317
+ const assistantToolCalls = toolCalls.size > 0 ? [...toolCalls.values()].map((tc) => ({
3318
+ id: tc.id,
3319
+ type: "function",
3320
+ function: { name: tc.name, arguments: tc.arguments }
3321
+ })) : null;
3322
+ const assistantMsg = {
3323
+ role: "assistant",
3324
+ content: accumulatedText || null,
3325
+ reasoning_content: accumulatedReasoning || null,
3326
+ tool_calls: assistantToolCalls
3327
+ };
3328
+ if (accumulatedReasoning) {
3329
+ sessions.storeTurnReasoning(requestMessages, assistantMsg, accumulatedReasoning);
3330
+ }
3331
+ const messages = [...priorMessages, assistantMsg];
3332
+ sessions.saveWithId(responseId, messages);
3333
+ const outputItems = [];
3334
+ if (emittedMessageItem) {
3335
+ outputItems.push({
3336
+ type: "message",
3337
+ id: msgItemId,
3338
+ role: "assistant",
3339
+ status: "completed",
3340
+ content: [{ type: "output_text", text: accumulatedText }]
3341
+ });
3342
+ }
3343
+ outputItems.push(...fcItems);
3344
+ yield formatSSE("response.completed", {
3345
+ type: "response.completed",
3346
+ response: {
3347
+ id: responseId,
3348
+ object: "response",
3349
+ created_at: createdAt,
3350
+ status: "completed",
3351
+ model,
3352
+ output: outputItems,
3353
+ usage: { input_tokens: 0, output_tokens: 0, total_tokens: 0 }
3354
+ }
3355
+ });
3356
+ console.log(`[transfer] stream completed: ${accumulatedText.length} chars, ${toolCalls.size} tool calls`);
3357
+ } catch (e) {
3358
+ if (signal?.aborted) return;
3359
+ const msg = e instanceof Error ? e.message : String(e);
3360
+ console.error(`[transfer] unhandled stream error: ${msg}`);
3361
+ yield sseFailed(args2.responseId, args2.model, "internal_error", msg);
3362
+ }
3363
+ }
3364
+ function sseFailed(responseId, model, code, message) {
3365
+ return formatSSE("response.failed", {
3366
+ type: "response.failed",
3367
+ response: {
3368
+ id: responseId,
3369
+ status: "failed",
3370
+ model,
3371
+ error: { code, message }
3372
+ }
3373
+ });
3374
+ }
3375
+ function formatSSE(event, data) {
3376
+ return `event: ${event}
3377
+ data: ${JSON.stringify(data)}
3378
+
3379
+ `;
3380
+ }
3381
+
3382
+ // src/config.ts
3383
+ import { readFileSync, existsSync, mkdirSync } from "node:fs";
3384
+ import { resolve, join, dirname } from "node:path";
3385
+ var DEFAULT_CONFIG = {
3386
+ port: 4444,
3387
+ upstream: "https://openrouter.ai/api/v1",
3388
+ apiKey: "",
3389
+ insecure: false,
3390
+ modelMap: {}
3391
+ };
3392
+ function loadConfig(configPath) {
3393
+ const fileConfig = loadConfigFile(configPath);
3394
+ return {
3395
+ port: Number(process.env.CODEX_TRANSFER_PORT ?? fileConfig.port ?? DEFAULT_CONFIG.port),
3396
+ upstream: (process.env.CODEX_TRANSFER_UPSTREAM ?? fileConfig.upstream ?? DEFAULT_CONFIG.upstream).replace(/\/+$/, ""),
3397
+ apiKey: process.env.CODEX_TRANSFER_API_KEY ?? fileConfig.apiKey ?? DEFAULT_CONFIG.apiKey,
3398
+ insecure: parseBool(
3399
+ process.env.CODEX_TRANSFER_INSECURE ?? fileConfig.insecure
3400
+ ),
3401
+ modelMap: fileConfig.modelMap ?? DEFAULT_CONFIG.modelMap
3402
+ };
3403
+ }
3404
+ function loadConfigFile(explicitPath) {
3405
+ const searchPaths = [];
3406
+ if (explicitPath) {
3407
+ searchPaths.push(resolve(explicitPath));
3408
+ } else if (process.env.CODEX_TRANSFER_CONFIG) {
3409
+ searchPaths.push(resolve(process.env.CODEX_TRANSFER_CONFIG));
3410
+ }
3411
+ searchPaths.push(
3412
+ resolve("./codex-transfer.json"),
3413
+ join(process.env.HOME ?? "~", ".codex-transfer", "config.json")
3414
+ );
3415
+ for (const path of searchPaths) {
3416
+ if (existsSync(path)) {
3417
+ try {
3418
+ const content = readFileSync(path, "utf-8");
3419
+ const parsed = JSON.parse(content);
3420
+ return {
3421
+ port: typeof parsed.port === "number" ? parsed.port : void 0,
3422
+ upstream: typeof parsed.upstream === "string" ? parsed.upstream : void 0,
3423
+ apiKey: typeof parsed.apiKey === "string" ? parsed.apiKey : void 0,
3424
+ insecure: typeof parsed.insecure === "boolean" ? parsed.insecure : void 0,
3425
+ modelMap: typeof parsed.modelMap === "object" && parsed.modelMap !== null ? parsed.modelMap : void 0
3426
+ };
3427
+ } catch {
3428
+ }
3429
+ }
3430
+ }
3431
+ return {};
3432
+ }
3433
+ function parseBool(value) {
3434
+ if (typeof value === "boolean") return value;
3435
+ if (typeof value === "string") {
3436
+ return value === "true" || value === "1";
3437
+ }
3438
+ return false;
3439
+ }
3440
+ function resolveConfigDir(configPath) {
3441
+ const candidates = [];
3442
+ if (configPath) {
3443
+ candidates.push(resolve(configPath));
3444
+ } else if (process.env.CODEX_TRANSFER_CONFIG) {
3445
+ candidates.push(resolve(process.env.CODEX_TRANSFER_CONFIG));
3446
+ }
3447
+ candidates.push(
3448
+ resolve("./codex-transfer.json"),
3449
+ join(process.env.HOME ?? "~", ".codex-transfer", "config.json")
3450
+ );
3451
+ for (const p of candidates) {
3452
+ if (existsSync(p)) return dirname(p);
3453
+ }
3454
+ return join(process.env.HOME ?? "~", ".codex-transfer");
3455
+ }
3456
+ function ensureLogDir(configPath) {
3457
+ const base = resolveConfigDir(configPath);
3458
+ const logDir = join(base, "logs");
3459
+ mkdirSync(logDir, { recursive: true });
3460
+ return logDir;
3461
+ }
3462
+
3463
+ // src/server.ts
3464
+ function createTransfer(options = {}) {
3465
+ const fileConfig = loadConfig(options.configPath);
3466
+ const port2 = options.port ?? fileConfig.port;
3467
+ const insecure = options.disableTlsVerify || fileConfig.insecure;
3468
+ if (insecure) {
3469
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
3470
+ console.warn("[transfer] TLS certificate verification disabled (--insecure)");
3471
+ }
3472
+ const upstream = (options.upstream ?? fileConfig.upstream).replace(
3473
+ /\/+$/,
3474
+ ""
3475
+ );
3476
+ const apiKey = options.apiKey ?? fileConfig.apiKey;
3477
+ const modelOverride = options.modelOverride;
3478
+ const sessions = new SessionStore();
3479
+ const app2 = new Hono2();
3480
+ app2.get("/health", async (c) => {
3481
+ const result = {
3482
+ upstream,
3483
+ apiKeySet: !!apiKey,
3484
+ apiKeyPrefix: apiKey ? `${apiKey.slice(0, 6)}...` : "(empty)"
3485
+ };
3486
+ try {
3487
+ const headers = {};
3488
+ if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
3489
+ const resp = await fetch(`${upstream}/models`, {
3490
+ headers,
3491
+ signal: AbortSignal.timeout(1e4)
3492
+ });
3493
+ result.upstreamStatus = resp.status;
3494
+ result.upstreamOk = resp.ok;
3495
+ } catch (e) {
3496
+ result.upstreamError = e instanceof Error ? e.message : String(e);
3497
+ result.upstreamCause = e instanceof Error && e.cause ? String(e.cause) : null;
3498
+ }
3499
+ return c.json(result);
3500
+ });
3501
+ app2.get("/v1/models", async (c) => {
3502
+ try {
3503
+ const headers = {};
3504
+ if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
3505
+ const resp = await fetch(`${upstream}/models`, { headers });
3506
+ if (!resp.ok) {
3507
+ return c.json({ object: "list", data: [] });
3508
+ }
3509
+ const body = await resp.json();
3510
+ return c.json(body);
3511
+ } catch {
3512
+ return c.json({ object: "list", data: [] });
3513
+ }
3514
+ });
3515
+ app2.post("/v1/responses", async (c) => {
3516
+ let req;
3517
+ try {
3518
+ req = await c.req.json();
3519
+ } catch (e) {
3520
+ const msg = e instanceof Error ? e.message : String(e);
3521
+ console.error(`[transfer] JSON parse error: ${msg}`);
3522
+ return c.text(msg, 422);
3523
+ }
3524
+ const inputLen = typeof req.input === "string" ? 1 : req.input?.length ?? 0;
3525
+ const model = modelOverride ?? resolveModel(req.model, fileConfig.modelMap);
3526
+ console.log(`[transfer] \u2190 POST /v1/responses model=${req.model}${model !== req.model ? ` \u2192 ${model}` : ""} stream=${req.stream} input_items=${inputLen} tools=${req.tools?.length ?? 0} prev=${req.previous_response_id ?? "none"}`);
3527
+ const history = req.previous_response_id ? sessions.getHistory(req.previous_response_id) : [];
3528
+ const chatReq = toChatRequest(req, history, sessions);
3529
+ chatReq.model = model;
3530
+ const url = `${upstream}/chat/completions`;
3531
+ if (req.stream) {
3532
+ const responseId = sessions.newId();
3533
+ chatReq.stream = true;
3534
+ const requestMessages = [...chatReq.messages];
3535
+ return stream(c, async (streamWriter) => {
3536
+ c.header("Content-Type", "text/event-stream");
3537
+ c.header("Cache-Control", "no-cache");
3538
+ c.header("Connection", "keep-alive");
3539
+ const signal = c.req.raw.signal;
3540
+ const sseStream = translateStream({
3541
+ url,
3542
+ apiKey,
3543
+ chatReq,
3544
+ responseId,
3545
+ sessions,
3546
+ priorMessages: history,
3547
+ requestMessages,
3548
+ model
3549
+ }, signal);
3550
+ try {
3551
+ for await (const event of sseStream) {
3552
+ if (signal.aborted) break;
3553
+ await streamWriter.write(event);
3554
+ }
3555
+ } catch (e) {
3556
+ if (!signal.aborted) {
3557
+ console.error("Stream write error:", e);
3558
+ }
3559
+ }
3560
+ });
3561
+ } else {
3562
+ chatReq.stream = false;
3563
+ const headers = {
3564
+ "Content-Type": "application/json"
3565
+ };
3566
+ if (apiKey) {
3567
+ headers["Authorization"] = `Bearer ${apiKey}`;
3568
+ }
3569
+ let resp;
3570
+ try {
3571
+ resp = await fetch(url, {
3572
+ method: "POST",
3573
+ headers,
3574
+ body: JSON.stringify(chatReq)
3575
+ });
3576
+ } catch (e) {
3577
+ const msg = e instanceof Error ? e.message : String(e);
3578
+ console.error(`upstream error: ${msg}`);
3579
+ return c.text(msg, 502);
3580
+ }
3581
+ if (!resp.ok) {
3582
+ const body = await resp.text().catch(() => "");
3583
+ console.error(`upstream ${resp.status}: ${body}`);
3584
+ return c.text(body, resp.status);
3585
+ }
3586
+ const chatResp = await resp.json();
3587
+ const assistantMsg = chatResp.choices?.[0]?.message ?? {
3588
+ role: "assistant",
3589
+ content: ""
3590
+ };
3591
+ const fullHistory = [...chatReq.messages, assistantMsg];
3592
+ const responseId = sessions.save(fullHistory);
3593
+ const { response } = fromChatResponse(responseId, model, chatResp);
3594
+ return c.json(response);
3595
+ }
3596
+ });
3597
+ app2.all("*", (c) => {
3598
+ console.warn(`unhandled ${c.req.method} ${c.req.path}`);
3599
+ return c.text("not found", 404);
3600
+ });
3601
+ return { app: app2, port: port2 };
3602
+ }
3603
+ function resolveModel(model, modelMap) {
3604
+ if (modelMap[model]) return modelMap[model];
3605
+ if (modelMap["*"]) return modelMap["*"];
3606
+ return model;
3607
+ }
3608
+
3609
+ // src/cli.ts
3610
+ import { spawn } from "node:child_process";
3611
+ import {
3612
+ appendFileSync,
3613
+ writeFileSync,
3614
+ statSync,
3615
+ renameSync,
3616
+ unlinkSync,
3617
+ existsSync as existsSync2
3618
+ } from "node:fs";
3619
+ import { join as join2 } from "node:path";
3620
+ var args = process.argv.slice(2);
3621
+ var disableTlsVerify = false;
3622
+ var daemonMode = false;
3623
+ var overrides = {};
3624
+ for (let i = 0; i < args.length; i++) {
3625
+ const a = args[i];
3626
+ if (a === "--insecure" || a === "-k") {
3627
+ disableTlsVerify = true;
3628
+ } else if (a === "--daemon" || a === "-d") {
3629
+ daemonMode = true;
3630
+ } else if ((a === "--port" || a === "-p") && args[i + 1]) {
3631
+ overrides.port = args[++i];
3632
+ } else if ((a === "--upstream" || a === "-u") && args[i + 1]) {
3633
+ overrides.upstream = args[++i];
3634
+ } else if (a === "--api-key" && args[i + 1]) {
3635
+ overrides.apiKey = args[++i];
3636
+ } else if ((a === "--config" || a === "-c") && args[i + 1]) {
3637
+ overrides.configPath = args[++i];
3638
+ } else if ((a === "--model" || a === "-m") && args[i + 1]) {
3639
+ overrides.model = args[++i];
3640
+ } else if (a === "--help" || a === "-h") {
3641
+ console.log(`
3642
+ codex-transfer \u2014 Responses API \u2194 Chat Completions bridge
3643
+
3644
+ Usage:
3645
+ codex-transfer [options]
3646
+
3647
+ Options:
3648
+ -p, --port PORT Listen port (default: 4444)
3649
+ -u, --upstream URL Upstream Chat Completions base URL
3650
+ --api-key KEY API key for upstream
3651
+ -m, --model MODEL Override model name (highest priority model mapping)
3652
+ -c, --config PATH Path to config file (JSON)
3653
+ -k, --insecure Skip TLS certificate verification
3654
+ -d, --daemon Run in background, logs to logs/ directory
3655
+ -h, --help Show this help
3656
+
3657
+ Environment variables:
3658
+ CODEX_TRANSFER_PORT Same as --port
3659
+ CODEX_TRANSFER_UPSTREAM Same as --upstream
3660
+ CODEX_TRANSFER_API_KEY Same as --api-key
3661
+ CODEX_TRANSFER_CONFIG Same as --config
3662
+ CODEX_TRANSFER_INSECURE Set to "1" to skip TLS verification
3663
+
3664
+ Config file options:
3665
+ modelMap Model name mapping, e.g. {"*": "deepseek-v4-pro"}
3666
+ Lookup: exact match \u2192 wildcard "*" \u2192 original name
3667
+
3668
+ Config file locations (searched in order):
3669
+ 1. --config path
3670
+ 2. CODEX_TRANSFER_CONFIG env var
3671
+ 3. ./codex-transfer.json
3672
+ 4. ~/.codex-transfer/config.json
3673
+ `);
3674
+ process.exit(0);
3675
+ }
3676
+ }
3677
+ if (daemonMode) {
3678
+ const logDir = ensureLogDir(overrides.configPath);
3679
+ const ts = formatTimestampCompact(/* @__PURE__ */ new Date());
3680
+ const logFile2 = join2(logDir, `codex-transfer-${ts}.log`);
3681
+ const pidFile = join2(logDir, "codex-transfer.pid");
3682
+ const childArgs = process.argv.slice(2).filter(
3683
+ (a) => a !== "--daemon" && a !== "-d"
3684
+ );
3685
+ const child = spawn(process.execPath, [process.argv[1], ...childArgs], {
3686
+ detached: true,
3687
+ stdio: ["ignore", "ignore", "ignore"],
3688
+ env: {
3689
+ ...process.env,
3690
+ __CODEX_TRANSFER_LOG: logFile2
3691
+ }
3692
+ });
3693
+ child.unref();
3694
+ writeFileSync(pidFile, String(child.pid), "utf-8");
3695
+ console.log(`codex-transfer started in background (PID: ${child.pid})`);
3696
+ console.log(`Log file: ${logFile2}`);
3697
+ console.log(`PID file: ${pidFile}`);
3698
+ console.log(`Stop: kill $(cat ${pidFile})`);
3699
+ process.exit(0);
3700
+ }
3701
+ var logFile = process.env.__CODEX_TRANSFER_LOG;
3702
+ if (logFile) {
3703
+ let rotateIfNeeded = function() {
3704
+ try {
3705
+ if (!existsSync2(logFilePath)) return;
3706
+ const stat = statSync(logFilePath);
3707
+ if (stat.size < MAX_LOG_SIZE) return;
3708
+ const base = logFilePath.slice(0, -".log".length);
3709
+ const oldest = `${base}.${MAX_LOG_FILES}.log`;
3710
+ if (existsSync2(oldest)) unlinkSync(oldest);
3711
+ for (let i = MAX_LOG_FILES - 1; i >= 1; i--) {
3712
+ const from = `${base}.${i}.log`;
3713
+ if (existsSync2(from)) renameSync(from, `${base}.${i + 1}.log`);
3714
+ }
3715
+ renameSync(logFilePath, `${base}.1.log`);
3716
+ } catch {
3717
+ }
3718
+ }, logWrite = function(msg) {
3719
+ try {
3720
+ rotateIfNeeded();
3721
+ const ts = formatTimestamp(/* @__PURE__ */ new Date());
3722
+ appendFileSync(logFilePath, `[${ts} transfer] ${msg}
3723
+ `);
3724
+ } catch {
3725
+ process.stderr.write(msg + "\n");
3726
+ }
3727
+ };
3728
+ rotateIfNeeded2 = rotateIfNeeded, logWrite2 = logWrite;
3729
+ const logFilePath = logFile;
3730
+ const MAX_LOG_SIZE = 10 * 1024 * 1024;
3731
+ const MAX_LOG_FILES = 5;
3732
+ console.log = (...args2) => logWrite(args2.map(String).join(" "));
3733
+ console.error = (...args2) => logWrite("[ERROR] " + args2.map(String).join(" "));
3734
+ console.warn = (...args2) => logWrite("[WARN] " + args2.map(String).join(" "));
3735
+ }
3736
+ var rotateIfNeeded2;
3737
+ var logWrite2;
3738
+ var { app, port } = createTransfer({
3739
+ configPath: overrides.configPath,
3740
+ port: overrides.port ? Number(overrides.port) : void 0,
3741
+ upstream: overrides.upstream,
3742
+ apiKey: overrides.apiKey,
3743
+ modelOverride: overrides.model,
3744
+ disableTlsVerify
3745
+ });
3746
+ var { serve: serve2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
3747
+ serve2({ fetch: app.fetch, port }, (info) => {
3748
+ console.log(`codex-transfer listening on 127.0.0.1:${info.port}`);
3749
+ });
3750
+ function formatTimestamp(d) {
3751
+ const pad = (n) => String(n).padStart(2, "0");
3752
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
3753
+ }
3754
+ function formatTimestampCompact(d) {
3755
+ const pad = (n) => String(n).padStart(2, "0");
3756
+ return `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`;
3757
+ }