@cloudwerk/cli 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2494 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { program } from "commander";
5
+
6
+ // src/commands/dev.ts
7
+ import * as path2 from "path";
8
+ import * as fs2 from "fs";
9
+ import * as os from "os";
10
+ import { serve } from "@hono/node-server";
11
+ import {
12
+ loadConfig,
13
+ scanRoutes,
14
+ buildRouteManifest,
15
+ resolveLayouts,
16
+ resolveMiddleware,
17
+ resolveRoutesDir,
18
+ hasErrors,
19
+ formatErrors,
20
+ formatWarnings
21
+ } from "@cloudwerk/core";
22
+
23
+ // src/types.ts
24
+ var CliError = class extends Error {
25
+ constructor(message, code, suggestion) {
26
+ super(message);
27
+ this.code = code;
28
+ this.suggestion = suggestion;
29
+ this.name = "CliError";
30
+ }
31
+ };
32
+
33
+ // src/utils/logger.ts
34
+ import pc from "picocolors";
35
+ function createLogger(verbose = false) {
36
+ return {
37
+ info(message) {
38
+ console.log(pc.blue("info") + " " + message);
39
+ },
40
+ success(message) {
41
+ console.log(pc.green("success") + " " + message);
42
+ },
43
+ warn(message) {
44
+ console.log(pc.yellow("warn") + " " + message);
45
+ },
46
+ error(message) {
47
+ console.log(pc.red("error") + " " + message);
48
+ },
49
+ debug(message) {
50
+ if (verbose) {
51
+ console.log(pc.gray("debug") + " " + message);
52
+ }
53
+ },
54
+ log(message) {
55
+ console.log(message);
56
+ }
57
+ };
58
+ }
59
+ function printStartupBanner(version, localUrl, networkUrl, routes, startupTime) {
60
+ console.log();
61
+ console.log(pc.bold(pc.cyan(" Cloudwerk")) + pc.dim(` v${version}`));
62
+ console.log();
63
+ console.log(pc.dim(" > ") + pc.bold("Local:") + " " + pc.cyan(localUrl));
64
+ if (networkUrl) {
65
+ console.log(pc.dim(" > ") + pc.bold("Network:") + " " + pc.cyan(networkUrl));
66
+ }
67
+ console.log();
68
+ if (routes.length > 0) {
69
+ console.log(pc.dim(" Routes:"));
70
+ const displayRoutes = routes.slice(0, 10);
71
+ const remainingCount = routes.length - displayRoutes.length;
72
+ for (const route of displayRoutes) {
73
+ const methodColor = getMethodColor(route.method);
74
+ console.log(
75
+ pc.dim(" ") + methodColor(route.method.padEnd(6)) + " " + route.pattern
76
+ );
77
+ }
78
+ if (remainingCount > 0) {
79
+ console.log(pc.dim(` ... and ${remainingCount} more routes`));
80
+ }
81
+ console.log();
82
+ }
83
+ console.log(pc.dim(` Ready in ${startupTime}ms`));
84
+ console.log();
85
+ }
86
+ function getMethodColor(method) {
87
+ switch (method.toUpperCase()) {
88
+ case "GET":
89
+ return pc.green;
90
+ case "POST":
91
+ return pc.blue;
92
+ case "PUT":
93
+ return pc.yellow;
94
+ case "PATCH":
95
+ return pc.magenta;
96
+ case "DELETE":
97
+ return pc.red;
98
+ case "OPTIONS":
99
+ return pc.cyan;
100
+ case "HEAD":
101
+ return pc.gray;
102
+ default:
103
+ return pc.white;
104
+ }
105
+ }
106
+ function printError(message, suggestion) {
107
+ console.log();
108
+ console.log(pc.red("Error: ") + message);
109
+ if (suggestion) {
110
+ console.log();
111
+ console.log(pc.dim(" " + suggestion));
112
+ }
113
+ console.log();
114
+ }
115
+ function logRequest(method, path3, status, duration) {
116
+ const methodColor = getMethodColor(method);
117
+ const statusColor = status >= 400 ? pc.red : status >= 300 ? pc.yellow : pc.green;
118
+ console.log(
119
+ pc.dim("[") + methodColor(method.padEnd(6)) + pc.dim("]") + " " + path3 + " " + statusColor(String(status)) + " " + pc.dim(`${duration}ms`)
120
+ );
121
+ }
122
+
123
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/compose.js
124
+ var compose = (middleware, onError, onNotFound) => {
125
+ return (context, next) => {
126
+ let index = -1;
127
+ return dispatch(0);
128
+ async function dispatch(i) {
129
+ if (i <= index) {
130
+ throw new Error("next() called multiple times");
131
+ }
132
+ index = i;
133
+ let res;
134
+ let isError = false;
135
+ let handler;
136
+ if (middleware[i]) {
137
+ handler = middleware[i][0][0];
138
+ context.req.routeIndex = i;
139
+ } else {
140
+ handler = i === middleware.length && next || void 0;
141
+ }
142
+ if (handler) {
143
+ try {
144
+ res = await handler(context, () => dispatch(i + 1));
145
+ } catch (err) {
146
+ if (err instanceof Error && onError) {
147
+ context.error = err;
148
+ res = await onError(err, context);
149
+ isError = true;
150
+ } else {
151
+ throw err;
152
+ }
153
+ }
154
+ } else {
155
+ if (context.finalized === false && onNotFound) {
156
+ res = await onNotFound(context);
157
+ }
158
+ }
159
+ if (res && (context.finalized === false || isError)) {
160
+ context.res = res;
161
+ }
162
+ return context;
163
+ }
164
+ };
165
+ };
166
+
167
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/request/constants.js
168
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
169
+
170
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/utils/body.js
171
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
172
+ const { all = false, dot = false } = options;
173
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
174
+ const contentType = headers.get("Content-Type");
175
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
176
+ return parseFormData(request, { all, dot });
177
+ }
178
+ return {};
179
+ };
180
+ async function parseFormData(request, options) {
181
+ const formData = await request.formData();
182
+ if (formData) {
183
+ return convertFormDataToBodyData(formData, options);
184
+ }
185
+ return {};
186
+ }
187
+ function convertFormDataToBodyData(formData, options) {
188
+ const form = /* @__PURE__ */ Object.create(null);
189
+ formData.forEach((value, key) => {
190
+ const shouldParseAllValues = options.all || key.endsWith("[]");
191
+ if (!shouldParseAllValues) {
192
+ form[key] = value;
193
+ } else {
194
+ handleParsingAllValues(form, key, value);
195
+ }
196
+ });
197
+ if (options.dot) {
198
+ Object.entries(form).forEach(([key, value]) => {
199
+ const shouldParseDotValues = key.includes(".");
200
+ if (shouldParseDotValues) {
201
+ handleParsingNestedValues(form, key, value);
202
+ delete form[key];
203
+ }
204
+ });
205
+ }
206
+ return form;
207
+ }
208
+ var handleParsingAllValues = (form, key, value) => {
209
+ if (form[key] !== void 0) {
210
+ if (Array.isArray(form[key])) {
211
+ ;
212
+ form[key].push(value);
213
+ } else {
214
+ form[key] = [form[key], value];
215
+ }
216
+ } else {
217
+ if (!key.endsWith("[]")) {
218
+ form[key] = value;
219
+ } else {
220
+ form[key] = [value];
221
+ }
222
+ }
223
+ };
224
+ var handleParsingNestedValues = (form, key, value) => {
225
+ let nestedForm = form;
226
+ const keys = key.split(".");
227
+ keys.forEach((key2, index) => {
228
+ if (index === keys.length - 1) {
229
+ nestedForm[key2] = value;
230
+ } else {
231
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
232
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
233
+ }
234
+ nestedForm = nestedForm[key2];
235
+ }
236
+ });
237
+ };
238
+
239
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/utils/url.js
240
+ var splitPath = (path3) => {
241
+ const paths = path3.split("/");
242
+ if (paths[0] === "") {
243
+ paths.shift();
244
+ }
245
+ return paths;
246
+ };
247
+ var splitRoutingPath = (routePath) => {
248
+ const { groups, path: path3 } = extractGroupsFromPath(routePath);
249
+ const paths = splitPath(path3);
250
+ return replaceGroupMarks(paths, groups);
251
+ };
252
+ var extractGroupsFromPath = (path3) => {
253
+ const groups = [];
254
+ path3 = path3.replace(/\{[^}]+\}/g, (match2, index) => {
255
+ const mark = `@${index}`;
256
+ groups.push([mark, match2]);
257
+ return mark;
258
+ });
259
+ return { groups, path: path3 };
260
+ };
261
+ var replaceGroupMarks = (paths, groups) => {
262
+ for (let i = groups.length - 1; i >= 0; i--) {
263
+ const [mark] = groups[i];
264
+ for (let j = paths.length - 1; j >= 0; j--) {
265
+ if (paths[j].includes(mark)) {
266
+ paths[j] = paths[j].replace(mark, groups[i][1]);
267
+ break;
268
+ }
269
+ }
270
+ }
271
+ return paths;
272
+ };
273
+ var patternCache = {};
274
+ var getPattern = (label, next) => {
275
+ if (label === "*") {
276
+ return "*";
277
+ }
278
+ const match2 = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
279
+ if (match2) {
280
+ const cacheKey = `${label}#${next}`;
281
+ if (!patternCache[cacheKey]) {
282
+ if (match2[2]) {
283
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match2[1], new RegExp(`^${match2[2]}(?=/${next})`)] : [label, match2[1], new RegExp(`^${match2[2]}$`)];
284
+ } else {
285
+ patternCache[cacheKey] = [label, match2[1], true];
286
+ }
287
+ }
288
+ return patternCache[cacheKey];
289
+ }
290
+ return null;
291
+ };
292
+ var tryDecode = (str, decoder) => {
293
+ try {
294
+ return decoder(str);
295
+ } catch {
296
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match2) => {
297
+ try {
298
+ return decoder(match2);
299
+ } catch {
300
+ return match2;
301
+ }
302
+ });
303
+ }
304
+ };
305
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
306
+ var getPath = (request) => {
307
+ const url = request.url;
308
+ const start = url.indexOf("/", url.indexOf(":") + 4);
309
+ let i = start;
310
+ for (; i < url.length; i++) {
311
+ const charCode = url.charCodeAt(i);
312
+ if (charCode === 37) {
313
+ const queryIndex = url.indexOf("?", i);
314
+ const path3 = url.slice(start, queryIndex === -1 ? void 0 : queryIndex);
315
+ return tryDecodeURI(path3.includes("%25") ? path3.replace(/%25/g, "%2525") : path3);
316
+ } else if (charCode === 63) {
317
+ break;
318
+ }
319
+ }
320
+ return url.slice(start, i);
321
+ };
322
+ var getPathNoStrict = (request) => {
323
+ const result = getPath(request);
324
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
325
+ };
326
+ var mergePath = (base, sub, ...rest) => {
327
+ if (rest.length) {
328
+ sub = mergePath(sub, ...rest);
329
+ }
330
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
331
+ };
332
+ var checkOptionalParameter = (path3) => {
333
+ if (path3.charCodeAt(path3.length - 1) !== 63 || !path3.includes(":")) {
334
+ return null;
335
+ }
336
+ const segments = path3.split("/");
337
+ const results = [];
338
+ let basePath = "";
339
+ segments.forEach((segment) => {
340
+ if (segment !== "" && !/\:/.test(segment)) {
341
+ basePath += "/" + segment;
342
+ } else if (/\:/.test(segment)) {
343
+ if (/\?/.test(segment)) {
344
+ if (results.length === 0 && basePath === "") {
345
+ results.push("/");
346
+ } else {
347
+ results.push(basePath);
348
+ }
349
+ const optionalSegment = segment.replace("?", "");
350
+ basePath += "/" + optionalSegment;
351
+ results.push(basePath);
352
+ } else {
353
+ basePath += "/" + segment;
354
+ }
355
+ }
356
+ });
357
+ return results.filter((v, i, a) => a.indexOf(v) === i);
358
+ };
359
+ var _decodeURI = (value) => {
360
+ if (!/[%+]/.test(value)) {
361
+ return value;
362
+ }
363
+ if (value.indexOf("+") !== -1) {
364
+ value = value.replace(/\+/g, " ");
365
+ }
366
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
367
+ };
368
+ var _getQueryParam = (url, key, multiple) => {
369
+ let encoded;
370
+ if (!multiple && key && !/[%+]/.test(key)) {
371
+ let keyIndex2 = url.indexOf("?", 8);
372
+ if (keyIndex2 === -1) {
373
+ return void 0;
374
+ }
375
+ if (!url.startsWith(key, keyIndex2 + 1)) {
376
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
377
+ }
378
+ while (keyIndex2 !== -1) {
379
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
380
+ if (trailingKeyCode === 61) {
381
+ const valueIndex = keyIndex2 + key.length + 2;
382
+ const endIndex = url.indexOf("&", valueIndex);
383
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));
384
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
385
+ return "";
386
+ }
387
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
388
+ }
389
+ encoded = /[%+]/.test(url);
390
+ if (!encoded) {
391
+ return void 0;
392
+ }
393
+ }
394
+ const results = {};
395
+ encoded ??= /[%+]/.test(url);
396
+ let keyIndex = url.indexOf("?", 8);
397
+ while (keyIndex !== -1) {
398
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
399
+ let valueIndex = url.indexOf("=", keyIndex);
400
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
401
+ valueIndex = -1;
402
+ }
403
+ let name = url.slice(
404
+ keyIndex + 1,
405
+ valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex
406
+ );
407
+ if (encoded) {
408
+ name = _decodeURI(name);
409
+ }
410
+ keyIndex = nextKeyIndex;
411
+ if (name === "") {
412
+ continue;
413
+ }
414
+ let value;
415
+ if (valueIndex === -1) {
416
+ value = "";
417
+ } else {
418
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);
419
+ if (encoded) {
420
+ value = _decodeURI(value);
421
+ }
422
+ }
423
+ if (multiple) {
424
+ if (!(results[name] && Array.isArray(results[name]))) {
425
+ results[name] = [];
426
+ }
427
+ ;
428
+ results[name].push(value);
429
+ } else {
430
+ results[name] ??= value;
431
+ }
432
+ }
433
+ return key ? results[key] : results;
434
+ };
435
+ var getQueryParam = _getQueryParam;
436
+ var getQueryParams = (url, key) => {
437
+ return _getQueryParam(url, key, true);
438
+ };
439
+ var decodeURIComponent_ = decodeURIComponent;
440
+
441
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/request.js
442
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
443
+ var HonoRequest = class {
444
+ /**
445
+ * `.raw` can get the raw Request object.
446
+ *
447
+ * @see {@link https://hono.dev/docs/api/request#raw}
448
+ *
449
+ * @example
450
+ * ```ts
451
+ * // For Cloudflare Workers
452
+ * app.post('/', async (c) => {
453
+ * const metadata = c.req.raw.cf?.hostMetadata?
454
+ * ...
455
+ * })
456
+ * ```
457
+ */
458
+ raw;
459
+ #validatedData;
460
+ // Short name of validatedData
461
+ #matchResult;
462
+ routeIndex = 0;
463
+ /**
464
+ * `.path` can get the pathname of the request.
465
+ *
466
+ * @see {@link https://hono.dev/docs/api/request#path}
467
+ *
468
+ * @example
469
+ * ```ts
470
+ * app.get('/about/me', (c) => {
471
+ * const pathname = c.req.path // `/about/me`
472
+ * })
473
+ * ```
474
+ */
475
+ path;
476
+ bodyCache = {};
477
+ constructor(request, path3 = "/", matchResult = [[]]) {
478
+ this.raw = request;
479
+ this.path = path3;
480
+ this.#matchResult = matchResult;
481
+ this.#validatedData = {};
482
+ }
483
+ param(key) {
484
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
485
+ }
486
+ #getDecodedParam(key) {
487
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
488
+ const param = this.#getParamValue(paramKey);
489
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
490
+ }
491
+ #getAllDecodedParams() {
492
+ const decoded = {};
493
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
494
+ for (const key of keys) {
495
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
496
+ if (value !== void 0) {
497
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
498
+ }
499
+ }
500
+ return decoded;
501
+ }
502
+ #getParamValue(paramKey) {
503
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
504
+ }
505
+ query(key) {
506
+ return getQueryParam(this.url, key);
507
+ }
508
+ queries(key) {
509
+ return getQueryParams(this.url, key);
510
+ }
511
+ header(name) {
512
+ if (name) {
513
+ return this.raw.headers.get(name) ?? void 0;
514
+ }
515
+ const headerData = {};
516
+ this.raw.headers.forEach((value, key) => {
517
+ headerData[key] = value;
518
+ });
519
+ return headerData;
520
+ }
521
+ async parseBody(options) {
522
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
523
+ }
524
+ #cachedBody = (key) => {
525
+ const { bodyCache, raw: raw2 } = this;
526
+ const cachedBody = bodyCache[key];
527
+ if (cachedBody) {
528
+ return cachedBody;
529
+ }
530
+ const anyCachedKey = Object.keys(bodyCache)[0];
531
+ if (anyCachedKey) {
532
+ return bodyCache[anyCachedKey].then((body) => {
533
+ if (anyCachedKey === "json") {
534
+ body = JSON.stringify(body);
535
+ }
536
+ return new Response(body)[key]();
537
+ });
538
+ }
539
+ return bodyCache[key] = raw2[key]();
540
+ };
541
+ /**
542
+ * `.json()` can parse Request body of type `application/json`
543
+ *
544
+ * @see {@link https://hono.dev/docs/api/request#json}
545
+ *
546
+ * @example
547
+ * ```ts
548
+ * app.post('/entry', async (c) => {
549
+ * const body = await c.req.json()
550
+ * })
551
+ * ```
552
+ */
553
+ json() {
554
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
555
+ }
556
+ /**
557
+ * `.text()` can parse Request body of type `text/plain`
558
+ *
559
+ * @see {@link https://hono.dev/docs/api/request#text}
560
+ *
561
+ * @example
562
+ * ```ts
563
+ * app.post('/entry', async (c) => {
564
+ * const body = await c.req.text()
565
+ * })
566
+ * ```
567
+ */
568
+ text() {
569
+ return this.#cachedBody("text");
570
+ }
571
+ /**
572
+ * `.arrayBuffer()` parse Request body as an `ArrayBuffer`
573
+ *
574
+ * @see {@link https://hono.dev/docs/api/request#arraybuffer}
575
+ *
576
+ * @example
577
+ * ```ts
578
+ * app.post('/entry', async (c) => {
579
+ * const body = await c.req.arrayBuffer()
580
+ * })
581
+ * ```
582
+ */
583
+ arrayBuffer() {
584
+ return this.#cachedBody("arrayBuffer");
585
+ }
586
+ /**
587
+ * Parses the request body as a `Blob`.
588
+ * @example
589
+ * ```ts
590
+ * app.post('/entry', async (c) => {
591
+ * const body = await c.req.blob();
592
+ * });
593
+ * ```
594
+ * @see https://hono.dev/docs/api/request#blob
595
+ */
596
+ blob() {
597
+ return this.#cachedBody("blob");
598
+ }
599
+ /**
600
+ * Parses the request body as `FormData`.
601
+ * @example
602
+ * ```ts
603
+ * app.post('/entry', async (c) => {
604
+ * const body = await c.req.formData();
605
+ * });
606
+ * ```
607
+ * @see https://hono.dev/docs/api/request#formdata
608
+ */
609
+ formData() {
610
+ return this.#cachedBody("formData");
611
+ }
612
+ /**
613
+ * Adds validated data to the request.
614
+ *
615
+ * @param target - The target of the validation.
616
+ * @param data - The validated data to add.
617
+ */
618
+ addValidatedData(target, data) {
619
+ this.#validatedData[target] = data;
620
+ }
621
+ valid(target) {
622
+ return this.#validatedData[target];
623
+ }
624
+ /**
625
+ * `.url()` can get the request url strings.
626
+ *
627
+ * @see {@link https://hono.dev/docs/api/request#url}
628
+ *
629
+ * @example
630
+ * ```ts
631
+ * app.get('/about/me', (c) => {
632
+ * const url = c.req.url // `http://localhost:8787/about/me`
633
+ * ...
634
+ * })
635
+ * ```
636
+ */
637
+ get url() {
638
+ return this.raw.url;
639
+ }
640
+ /**
641
+ * `.method()` can get the method name of the request.
642
+ *
643
+ * @see {@link https://hono.dev/docs/api/request#method}
644
+ *
645
+ * @example
646
+ * ```ts
647
+ * app.get('/about/me', (c) => {
648
+ * const method = c.req.method // `GET`
649
+ * })
650
+ * ```
651
+ */
652
+ get method() {
653
+ return this.raw.method;
654
+ }
655
+ get [GET_MATCH_RESULT]() {
656
+ return this.#matchResult;
657
+ }
658
+ /**
659
+ * `.matchedRoutes()` can return a matched route in the handler
660
+ *
661
+ * @deprecated
662
+ *
663
+ * Use matchedRoutes helper defined in "hono/route" instead.
664
+ *
665
+ * @see {@link https://hono.dev/docs/api/request#matchedroutes}
666
+ *
667
+ * @example
668
+ * ```ts
669
+ * app.use('*', async function logger(c, next) {
670
+ * await next()
671
+ * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {
672
+ * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')
673
+ * console.log(
674
+ * method,
675
+ * ' ',
676
+ * path,
677
+ * ' '.repeat(Math.max(10 - path.length, 0)),
678
+ * name,
679
+ * i === c.req.routeIndex ? '<- respond from here' : ''
680
+ * )
681
+ * })
682
+ * })
683
+ * ```
684
+ */
685
+ get matchedRoutes() {
686
+ return this.#matchResult[0].map(([[, route]]) => route);
687
+ }
688
+ /**
689
+ * `routePath()` can retrieve the path registered within the handler
690
+ *
691
+ * @deprecated
692
+ *
693
+ * Use routePath helper defined in "hono/route" instead.
694
+ *
695
+ * @see {@link https://hono.dev/docs/api/request#routepath}
696
+ *
697
+ * @example
698
+ * ```ts
699
+ * app.get('/posts/:id', (c) => {
700
+ * return c.json({ path: c.req.routePath })
701
+ * })
702
+ * ```
703
+ */
704
+ get routePath() {
705
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
706
+ }
707
+ };
708
+
709
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/utils/html.js
710
+ var HtmlEscapedCallbackPhase = {
711
+ Stringify: 1,
712
+ BeforeStream: 2,
713
+ Stream: 3
714
+ };
715
+ var raw = (value, callbacks) => {
716
+ const escapedString = new String(value);
717
+ escapedString.isEscaped = true;
718
+ escapedString.callbacks = callbacks;
719
+ return escapedString;
720
+ };
721
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
722
+ if (typeof str === "object" && !(str instanceof String)) {
723
+ if (!(str instanceof Promise)) {
724
+ str = str.toString();
725
+ }
726
+ if (str instanceof Promise) {
727
+ str = await str;
728
+ }
729
+ }
730
+ const callbacks = str.callbacks;
731
+ if (!callbacks?.length) {
732
+ return Promise.resolve(str);
733
+ }
734
+ if (buffer) {
735
+ buffer[0] += str;
736
+ } else {
737
+ buffer = [str];
738
+ }
739
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(
740
+ (res) => Promise.all(
741
+ res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))
742
+ ).then(() => buffer[0])
743
+ );
744
+ if (preserveCallbacks) {
745
+ return raw(await resStr, callbacks);
746
+ } else {
747
+ return resStr;
748
+ }
749
+ };
750
+
751
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/context.js
752
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
753
+ var setDefaultContentType = (contentType, headers) => {
754
+ return {
755
+ "Content-Type": contentType,
756
+ ...headers
757
+ };
758
+ };
759
+ var Context = class {
760
+ #rawRequest;
761
+ #req;
762
+ /**
763
+ * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.
764
+ *
765
+ * @see {@link https://hono.dev/docs/api/context#env}
766
+ *
767
+ * @example
768
+ * ```ts
769
+ * // Environment object for Cloudflare Workers
770
+ * app.get('*', async c => {
771
+ * const counter = c.env.COUNTER
772
+ * })
773
+ * ```
774
+ */
775
+ env = {};
776
+ #var;
777
+ finalized = false;
778
+ /**
779
+ * `.error` can get the error object from the middleware if the Handler throws an error.
780
+ *
781
+ * @see {@link https://hono.dev/docs/api/context#error}
782
+ *
783
+ * @example
784
+ * ```ts
785
+ * app.use('*', async (c, next) => {
786
+ * await next()
787
+ * if (c.error) {
788
+ * // do something...
789
+ * }
790
+ * })
791
+ * ```
792
+ */
793
+ error;
794
+ #status;
795
+ #executionCtx;
796
+ #res;
797
+ #layout;
798
+ #renderer;
799
+ #notFoundHandler;
800
+ #preparedHeaders;
801
+ #matchResult;
802
+ #path;
803
+ /**
804
+ * Creates an instance of the Context class.
805
+ *
806
+ * @param req - The Request object.
807
+ * @param options - Optional configuration options for the context.
808
+ */
809
+ constructor(req, options) {
810
+ this.#rawRequest = req;
811
+ if (options) {
812
+ this.#executionCtx = options.executionCtx;
813
+ this.env = options.env;
814
+ this.#notFoundHandler = options.notFoundHandler;
815
+ this.#path = options.path;
816
+ this.#matchResult = options.matchResult;
817
+ }
818
+ }
819
+ /**
820
+ * `.req` is the instance of {@link HonoRequest}.
821
+ */
822
+ get req() {
823
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
824
+ return this.#req;
825
+ }
826
+ /**
827
+ * @see {@link https://hono.dev/docs/api/context#event}
828
+ * The FetchEvent associated with the current request.
829
+ *
830
+ * @throws Will throw an error if the context does not have a FetchEvent.
831
+ */
832
+ get event() {
833
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
834
+ return this.#executionCtx;
835
+ } else {
836
+ throw Error("This context has no FetchEvent");
837
+ }
838
+ }
839
+ /**
840
+ * @see {@link https://hono.dev/docs/api/context#executionctx}
841
+ * The ExecutionContext associated with the current request.
842
+ *
843
+ * @throws Will throw an error if the context does not have an ExecutionContext.
844
+ */
845
+ get executionCtx() {
846
+ if (this.#executionCtx) {
847
+ return this.#executionCtx;
848
+ } else {
849
+ throw Error("This context has no ExecutionContext");
850
+ }
851
+ }
852
+ /**
853
+ * @see {@link https://hono.dev/docs/api/context#res}
854
+ * The Response object for the current request.
855
+ */
856
+ get res() {
857
+ return this.#res ||= new Response(null, {
858
+ headers: this.#preparedHeaders ??= new Headers()
859
+ });
860
+ }
861
+ /**
862
+ * Sets the Response object for the current request.
863
+ *
864
+ * @param _res - The Response object to set.
865
+ */
866
+ set res(_res) {
867
+ if (this.#res && _res) {
868
+ _res = new Response(_res.body, _res);
869
+ for (const [k, v] of this.#res.headers.entries()) {
870
+ if (k === "content-type") {
871
+ continue;
872
+ }
873
+ if (k === "set-cookie") {
874
+ const cookies = this.#res.headers.getSetCookie();
875
+ _res.headers.delete("set-cookie");
876
+ for (const cookie of cookies) {
877
+ _res.headers.append("set-cookie", cookie);
878
+ }
879
+ } else {
880
+ _res.headers.set(k, v);
881
+ }
882
+ }
883
+ }
884
+ this.#res = _res;
885
+ this.finalized = true;
886
+ }
887
+ /**
888
+ * `.render()` can create a response within a layout.
889
+ *
890
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
891
+ *
892
+ * @example
893
+ * ```ts
894
+ * app.get('/', (c) => {
895
+ * return c.render('Hello!')
896
+ * })
897
+ * ```
898
+ */
899
+ render = (...args) => {
900
+ this.#renderer ??= (content) => this.html(content);
901
+ return this.#renderer(...args);
902
+ };
903
+ /**
904
+ * Sets the layout for the response.
905
+ *
906
+ * @param layout - The layout to set.
907
+ * @returns The layout function.
908
+ */
909
+ setLayout = (layout) => this.#layout = layout;
910
+ /**
911
+ * Gets the current layout for the response.
912
+ *
913
+ * @returns The current layout function.
914
+ */
915
+ getLayout = () => this.#layout;
916
+ /**
917
+ * `.setRenderer()` can set the layout in the custom middleware.
918
+ *
919
+ * @see {@link https://hono.dev/docs/api/context#render-setrenderer}
920
+ *
921
+ * @example
922
+ * ```tsx
923
+ * app.use('*', async (c, next) => {
924
+ * c.setRenderer((content) => {
925
+ * return c.html(
926
+ * <html>
927
+ * <body>
928
+ * <p>{content}</p>
929
+ * </body>
930
+ * </html>
931
+ * )
932
+ * })
933
+ * await next()
934
+ * })
935
+ * ```
936
+ */
937
+ setRenderer = (renderer) => {
938
+ this.#renderer = renderer;
939
+ };
940
+ /**
941
+ * `.header()` can set headers.
942
+ *
943
+ * @see {@link https://hono.dev/docs/api/context#header}
944
+ *
945
+ * @example
946
+ * ```ts
947
+ * app.get('/welcome', (c) => {
948
+ * // Set headers
949
+ * c.header('X-Message', 'Hello!')
950
+ * c.header('Content-Type', 'text/plain')
951
+ *
952
+ * return c.body('Thank you for coming')
953
+ * })
954
+ * ```
955
+ */
956
+ header = (name, value, options) => {
957
+ if (this.finalized) {
958
+ this.#res = new Response(this.#res.body, this.#res);
959
+ }
960
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();
961
+ if (value === void 0) {
962
+ headers.delete(name);
963
+ } else if (options?.append) {
964
+ headers.append(name, value);
965
+ } else {
966
+ headers.set(name, value);
967
+ }
968
+ };
969
+ status = (status) => {
970
+ this.#status = status;
971
+ };
972
+ /**
973
+ * `.set()` can set the value specified by the key.
974
+ *
975
+ * @see {@link https://hono.dev/docs/api/context#set-get}
976
+ *
977
+ * @example
978
+ * ```ts
979
+ * app.use('*', async (c, next) => {
980
+ * c.set('message', 'Hono is hot!!')
981
+ * await next()
982
+ * })
983
+ * ```
984
+ */
985
+ set = (key, value) => {
986
+ this.#var ??= /* @__PURE__ */ new Map();
987
+ this.#var.set(key, value);
988
+ };
989
+ /**
990
+ * `.get()` can use the value specified by the key.
991
+ *
992
+ * @see {@link https://hono.dev/docs/api/context#set-get}
993
+ *
994
+ * @example
995
+ * ```ts
996
+ * app.get('/', (c) => {
997
+ * const message = c.get('message')
998
+ * return c.text(`The message is "${message}"`)
999
+ * })
1000
+ * ```
1001
+ */
1002
+ get = (key) => {
1003
+ return this.#var ? this.#var.get(key) : void 0;
1004
+ };
1005
+ /**
1006
+ * `.var` can access the value of a variable.
1007
+ *
1008
+ * @see {@link https://hono.dev/docs/api/context#var}
1009
+ *
1010
+ * @example
1011
+ * ```ts
1012
+ * const result = c.var.client.oneMethod()
1013
+ * ```
1014
+ */
1015
+ // c.var.propName is a read-only
1016
+ get var() {
1017
+ if (!this.#var) {
1018
+ return {};
1019
+ }
1020
+ return Object.fromEntries(this.#var);
1021
+ }
1022
+ #newResponse(data, arg, headers) {
1023
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();
1024
+ if (typeof arg === "object" && "headers" in arg) {
1025
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
1026
+ for (const [key, value] of argHeaders) {
1027
+ if (key.toLowerCase() === "set-cookie") {
1028
+ responseHeaders.append(key, value);
1029
+ } else {
1030
+ responseHeaders.set(key, value);
1031
+ }
1032
+ }
1033
+ }
1034
+ if (headers) {
1035
+ for (const [k, v] of Object.entries(headers)) {
1036
+ if (typeof v === "string") {
1037
+ responseHeaders.set(k, v);
1038
+ } else {
1039
+ responseHeaders.delete(k);
1040
+ for (const v2 of v) {
1041
+ responseHeaders.append(k, v2);
1042
+ }
1043
+ }
1044
+ }
1045
+ }
1046
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
1047
+ return new Response(data, { status, headers: responseHeaders });
1048
+ }
1049
+ newResponse = (...args) => this.#newResponse(...args);
1050
+ /**
1051
+ * `.body()` can return the HTTP response.
1052
+ * You can set headers with `.header()` and set HTTP status code with `.status`.
1053
+ * This can also be set in `.text()`, `.json()` and so on.
1054
+ *
1055
+ * @see {@link https://hono.dev/docs/api/context#body}
1056
+ *
1057
+ * @example
1058
+ * ```ts
1059
+ * app.get('/welcome', (c) => {
1060
+ * // Set headers
1061
+ * c.header('X-Message', 'Hello!')
1062
+ * c.header('Content-Type', 'text/plain')
1063
+ * // Set HTTP status code
1064
+ * c.status(201)
1065
+ *
1066
+ * // Return the response body
1067
+ * return c.body('Thank you for coming')
1068
+ * })
1069
+ * ```
1070
+ */
1071
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
1072
+ /**
1073
+ * `.text()` can render text as `Content-Type:text/plain`.
1074
+ *
1075
+ * @see {@link https://hono.dev/docs/api/context#text}
1076
+ *
1077
+ * @example
1078
+ * ```ts
1079
+ * app.get('/say', (c) => {
1080
+ * return c.text('Hello!')
1081
+ * })
1082
+ * ```
1083
+ */
1084
+ text = (text, arg, headers) => {
1085
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(
1086
+ text,
1087
+ arg,
1088
+ setDefaultContentType(TEXT_PLAIN, headers)
1089
+ );
1090
+ };
1091
+ /**
1092
+ * `.json()` can render JSON as `Content-Type:application/json`.
1093
+ *
1094
+ * @see {@link https://hono.dev/docs/api/context#json}
1095
+ *
1096
+ * @example
1097
+ * ```ts
1098
+ * app.get('/api', (c) => {
1099
+ * return c.json({ message: 'Hello!' })
1100
+ * })
1101
+ * ```
1102
+ */
1103
+ json = (object, arg, headers) => {
1104
+ return this.#newResponse(
1105
+ JSON.stringify(object),
1106
+ arg,
1107
+ setDefaultContentType("application/json", headers)
1108
+ );
1109
+ };
1110
+ html = (html, arg, headers) => {
1111
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
1112
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
1113
+ };
1114
+ /**
1115
+ * `.redirect()` can Redirect, default status code is 302.
1116
+ *
1117
+ * @see {@link https://hono.dev/docs/api/context#redirect}
1118
+ *
1119
+ * @example
1120
+ * ```ts
1121
+ * app.get('/redirect', (c) => {
1122
+ * return c.redirect('/')
1123
+ * })
1124
+ * app.get('/redirect-permanently', (c) => {
1125
+ * return c.redirect('/', 301)
1126
+ * })
1127
+ * ```
1128
+ */
1129
+ redirect = (location, status) => {
1130
+ const locationString = String(location);
1131
+ this.header(
1132
+ "Location",
1133
+ // Multibyes should be encoded
1134
+ // eslint-disable-next-line no-control-regex
1135
+ !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString)
1136
+ );
1137
+ return this.newResponse(null, status ?? 302);
1138
+ };
1139
+ /**
1140
+ * `.notFound()` can return the Not Found Response.
1141
+ *
1142
+ * @see {@link https://hono.dev/docs/api/context#notfound}
1143
+ *
1144
+ * @example
1145
+ * ```ts
1146
+ * app.get('/notfound', (c) => {
1147
+ * return c.notFound()
1148
+ * })
1149
+ * ```
1150
+ */
1151
+ notFound = () => {
1152
+ this.#notFoundHandler ??= () => new Response();
1153
+ return this.#notFoundHandler(this);
1154
+ };
1155
+ };
1156
+
1157
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router.js
1158
+ var METHOD_NAME_ALL = "ALL";
1159
+ var METHOD_NAME_ALL_LOWERCASE = "all";
1160
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1161
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1162
+ var UnsupportedPathError = class extends Error {
1163
+ };
1164
+
1165
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/utils/constants.js
1166
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1167
+
1168
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/hono-base.js
1169
+ var notFoundHandler = (c) => {
1170
+ return c.text("404 Not Found", 404);
1171
+ };
1172
+ var errorHandler = (err, c) => {
1173
+ if ("getResponse" in err) {
1174
+ const res = err.getResponse();
1175
+ return c.newResponse(res.body, res);
1176
+ }
1177
+ console.error(err);
1178
+ return c.text("Internal Server Error", 500);
1179
+ };
1180
+ var Hono = class _Hono {
1181
+ get;
1182
+ post;
1183
+ put;
1184
+ delete;
1185
+ options;
1186
+ patch;
1187
+ all;
1188
+ on;
1189
+ use;
1190
+ /*
1191
+ This class is like an abstract class and does not have a router.
1192
+ To use it, inherit the class and implement router in the constructor.
1193
+ */
1194
+ router;
1195
+ getPath;
1196
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1197
+ _basePath = "/";
1198
+ #path = "/";
1199
+ routes = [];
1200
+ constructor(options = {}) {
1201
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
1202
+ allMethods.forEach((method) => {
1203
+ this[method] = (args1, ...args) => {
1204
+ if (typeof args1 === "string") {
1205
+ this.#path = args1;
1206
+ } else {
1207
+ this.#addRoute(method, this.#path, args1);
1208
+ }
1209
+ args.forEach((handler) => {
1210
+ this.#addRoute(method, this.#path, handler);
1211
+ });
1212
+ return this;
1213
+ };
1214
+ });
1215
+ this.on = (method, path3, ...handlers) => {
1216
+ for (const p of [path3].flat()) {
1217
+ this.#path = p;
1218
+ for (const m of [method].flat()) {
1219
+ handlers.map((handler) => {
1220
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
1221
+ });
1222
+ }
1223
+ }
1224
+ return this;
1225
+ };
1226
+ this.use = (arg1, ...handlers) => {
1227
+ if (typeof arg1 === "string") {
1228
+ this.#path = arg1;
1229
+ } else {
1230
+ this.#path = "*";
1231
+ handlers.unshift(arg1);
1232
+ }
1233
+ handlers.forEach((handler) => {
1234
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1235
+ });
1236
+ return this;
1237
+ };
1238
+ const { strict, ...optionsWithoutStrict } = options;
1239
+ Object.assign(this, optionsWithoutStrict);
1240
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1241
+ }
1242
+ #clone() {
1243
+ const clone = new _Hono({
1244
+ router: this.router,
1245
+ getPath: this.getPath
1246
+ });
1247
+ clone.errorHandler = this.errorHandler;
1248
+ clone.#notFoundHandler = this.#notFoundHandler;
1249
+ clone.routes = this.routes;
1250
+ return clone;
1251
+ }
1252
+ #notFoundHandler = notFoundHandler;
1253
+ // Cannot use `#` because it requires visibility at JavaScript runtime.
1254
+ errorHandler = errorHandler;
1255
+ /**
1256
+ * `.route()` allows grouping other Hono instance in routes.
1257
+ *
1258
+ * @see {@link https://hono.dev/docs/api/routing#grouping}
1259
+ *
1260
+ * @param {string} path - base Path
1261
+ * @param {Hono} app - other Hono instance
1262
+ * @returns {Hono} routed Hono instance
1263
+ *
1264
+ * @example
1265
+ * ```ts
1266
+ * const app = new Hono()
1267
+ * const app2 = new Hono()
1268
+ *
1269
+ * app2.get("/user", (c) => c.text("user"))
1270
+ * app.route("/api", app2) // GET /api/user
1271
+ * ```
1272
+ */
1273
+ route(path3, app) {
1274
+ const subApp = this.basePath(path3);
1275
+ app.routes.map((r) => {
1276
+ let handler;
1277
+ if (app.errorHandler === errorHandler) {
1278
+ handler = r.handler;
1279
+ } else {
1280
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
1281
+ handler[COMPOSED_HANDLER] = r.handler;
1282
+ }
1283
+ subApp.#addRoute(r.method, r.path, handler);
1284
+ });
1285
+ return this;
1286
+ }
1287
+ /**
1288
+ * `.basePath()` allows base paths to be specified.
1289
+ *
1290
+ * @see {@link https://hono.dev/docs/api/routing#base-path}
1291
+ *
1292
+ * @param {string} path - base Path
1293
+ * @returns {Hono} changed Hono instance
1294
+ *
1295
+ * @example
1296
+ * ```ts
1297
+ * const api = new Hono().basePath('/api')
1298
+ * ```
1299
+ */
1300
+ basePath(path3) {
1301
+ const subApp = this.#clone();
1302
+ subApp._basePath = mergePath(this._basePath, path3);
1303
+ return subApp;
1304
+ }
1305
+ /**
1306
+ * `.onError()` handles an error and returns a customized Response.
1307
+ *
1308
+ * @see {@link https://hono.dev/docs/api/hono#error-handling}
1309
+ *
1310
+ * @param {ErrorHandler} handler - request Handler for error
1311
+ * @returns {Hono} changed Hono instance
1312
+ *
1313
+ * @example
1314
+ * ```ts
1315
+ * app.onError((err, c) => {
1316
+ * console.error(`${err}`)
1317
+ * return c.text('Custom Error Message', 500)
1318
+ * })
1319
+ * ```
1320
+ */
1321
+ onError = (handler) => {
1322
+ this.errorHandler = handler;
1323
+ return this;
1324
+ };
1325
+ /**
1326
+ * `.notFound()` allows you to customize a Not Found Response.
1327
+ *
1328
+ * @see {@link https://hono.dev/docs/api/hono#not-found}
1329
+ *
1330
+ * @param {NotFoundHandler} handler - request handler for not-found
1331
+ * @returns {Hono} changed Hono instance
1332
+ *
1333
+ * @example
1334
+ * ```ts
1335
+ * app.notFound((c) => {
1336
+ * return c.text('Custom 404 Message', 404)
1337
+ * })
1338
+ * ```
1339
+ */
1340
+ notFound = (handler) => {
1341
+ this.#notFoundHandler = handler;
1342
+ return this;
1343
+ };
1344
+ /**
1345
+ * `.mount()` allows you to mount applications built with other frameworks into your Hono application.
1346
+ *
1347
+ * @see {@link https://hono.dev/docs/api/hono#mount}
1348
+ *
1349
+ * @param {string} path - base Path
1350
+ * @param {Function} applicationHandler - other Request Handler
1351
+ * @param {MountOptions} [options] - options of `.mount()`
1352
+ * @returns {Hono} mounted Hono instance
1353
+ *
1354
+ * @example
1355
+ * ```ts
1356
+ * import { Router as IttyRouter } from 'itty-router'
1357
+ * import { Hono } from 'hono'
1358
+ * // Create itty-router application
1359
+ * const ittyRouter = IttyRouter()
1360
+ * // GET /itty-router/hello
1361
+ * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
1362
+ *
1363
+ * const app = new Hono()
1364
+ * app.mount('/itty-router', ittyRouter.handle)
1365
+ * ```
1366
+ *
1367
+ * @example
1368
+ * ```ts
1369
+ * const app = new Hono()
1370
+ * // Send the request to another application without modification.
1371
+ * app.mount('/app', anotherApp, {
1372
+ * replaceRequest: (req) => req,
1373
+ * })
1374
+ * ```
1375
+ */
1376
+ mount(path3, applicationHandler, options) {
1377
+ let replaceRequest;
1378
+ let optionHandler;
1379
+ if (options) {
1380
+ if (typeof options === "function") {
1381
+ optionHandler = options;
1382
+ } else {
1383
+ optionHandler = options.optionHandler;
1384
+ if (options.replaceRequest === false) {
1385
+ replaceRequest = (request) => request;
1386
+ } else {
1387
+ replaceRequest = options.replaceRequest;
1388
+ }
1389
+ }
1390
+ }
1391
+ const getOptions = optionHandler ? (c) => {
1392
+ const options2 = optionHandler(c);
1393
+ return Array.isArray(options2) ? options2 : [options2];
1394
+ } : (c) => {
1395
+ let executionContext = void 0;
1396
+ try {
1397
+ executionContext = c.executionCtx;
1398
+ } catch {
1399
+ }
1400
+ return [c.env, executionContext];
1401
+ };
1402
+ replaceRequest ||= (() => {
1403
+ const mergedPath = mergePath(this._basePath, path3);
1404
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1405
+ return (request) => {
1406
+ const url = new URL(request.url);
1407
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
1408
+ return new Request(url, request);
1409
+ };
1410
+ })();
1411
+ const handler = async (c, next) => {
1412
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1413
+ if (res) {
1414
+ return res;
1415
+ }
1416
+ await next();
1417
+ };
1418
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path3, "*"), handler);
1419
+ return this;
1420
+ }
1421
+ #addRoute(method, path3, handler) {
1422
+ method = method.toUpperCase();
1423
+ path3 = mergePath(this._basePath, path3);
1424
+ const r = { basePath: this._basePath, path: path3, method, handler };
1425
+ this.router.add(method, path3, [handler, r]);
1426
+ this.routes.push(r);
1427
+ }
1428
+ #handleError(err, c) {
1429
+ if (err instanceof Error) {
1430
+ return this.errorHandler(err, c);
1431
+ }
1432
+ throw err;
1433
+ }
1434
+ #dispatch(request, executionCtx, env, method) {
1435
+ if (method === "HEAD") {
1436
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1437
+ }
1438
+ const path3 = this.getPath(request, { env });
1439
+ const matchResult = this.router.match(method, path3);
1440
+ const c = new Context(request, {
1441
+ path: path3,
1442
+ matchResult,
1443
+ env,
1444
+ executionCtx,
1445
+ notFoundHandler: this.#notFoundHandler
1446
+ });
1447
+ if (matchResult[0].length === 1) {
1448
+ let res;
1449
+ try {
1450
+ res = matchResult[0][0][0][0](c, async () => {
1451
+ c.res = await this.#notFoundHandler(c);
1452
+ });
1453
+ } catch (err) {
1454
+ return this.#handleError(err, c);
1455
+ }
1456
+ return res instanceof Promise ? res.then(
1457
+ (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))
1458
+ ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
1459
+ }
1460
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
1461
+ return (async () => {
1462
+ try {
1463
+ const context = await composed(c);
1464
+ if (!context.finalized) {
1465
+ throw new Error(
1466
+ "Context is not finalized. Did you forget to return a Response object or `await next()`?"
1467
+ );
1468
+ }
1469
+ return context.res;
1470
+ } catch (err) {
1471
+ return this.#handleError(err, c);
1472
+ }
1473
+ })();
1474
+ }
1475
+ /**
1476
+ * `.fetch()` will be entry point of your app.
1477
+ *
1478
+ * @see {@link https://hono.dev/docs/api/hono#fetch}
1479
+ *
1480
+ * @param {Request} request - request Object of request
1481
+ * @param {Env} Env - env Object
1482
+ * @param {ExecutionContext} - context of execution
1483
+ * @returns {Response | Promise<Response>} response of request
1484
+ *
1485
+ */
1486
+ fetch = (request, ...rest) => {
1487
+ return this.#dispatch(request, rest[1], rest[0], request.method);
1488
+ };
1489
+ /**
1490
+ * `.request()` is a useful method for testing.
1491
+ * You can pass a URL or pathname to send a GET request.
1492
+ * app will return a Response object.
1493
+ * ```ts
1494
+ * test('GET /hello is ok', async () => {
1495
+ * const res = await app.request('/hello')
1496
+ * expect(res.status).toBe(200)
1497
+ * })
1498
+ * ```
1499
+ * @see https://hono.dev/docs/api/hono#request
1500
+ */
1501
+ request = (input, requestInit, Env, executionCtx) => {
1502
+ if (input instanceof Request) {
1503
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
1504
+ }
1505
+ input = input.toString();
1506
+ return this.fetch(
1507
+ new Request(
1508
+ /^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`,
1509
+ requestInit
1510
+ ),
1511
+ Env,
1512
+ executionCtx
1513
+ );
1514
+ };
1515
+ /**
1516
+ * `.fire()` automatically adds a global fetch event listener.
1517
+ * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.
1518
+ * @deprecated
1519
+ * Use `fire` from `hono/service-worker` instead.
1520
+ * ```ts
1521
+ * import { Hono } from 'hono'
1522
+ * import { fire } from 'hono/service-worker'
1523
+ *
1524
+ * const app = new Hono()
1525
+ * // ...
1526
+ * fire(app)
1527
+ * ```
1528
+ * @see https://hono.dev/docs/api/hono#fire
1529
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
1530
+ * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/
1531
+ */
1532
+ fire = () => {
1533
+ addEventListener("fetch", (event) => {
1534
+ event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));
1535
+ });
1536
+ };
1537
+ };
1538
+
1539
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router/reg-exp-router/matcher.js
1540
+ var emptyParam = [];
1541
+ function match(method, path3) {
1542
+ const matchers = this.buildAllMatchers();
1543
+ const match2 = ((method2, path22) => {
1544
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
1545
+ const staticMatch = matcher[2][path22];
1546
+ if (staticMatch) {
1547
+ return staticMatch;
1548
+ }
1549
+ const match3 = path22.match(matcher[0]);
1550
+ if (!match3) {
1551
+ return [[], emptyParam];
1552
+ }
1553
+ const index = match3.indexOf("", 1);
1554
+ return [matcher[1][index], match3];
1555
+ });
1556
+ this.match = match2;
1557
+ return match2(method, path3);
1558
+ }
1559
+
1560
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router/reg-exp-router/node.js
1561
+ var LABEL_REG_EXP_STR = "[^/]+";
1562
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
1563
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
1564
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
1565
+ var regExpMetaChars = new Set(".\\+*[^]$()");
1566
+ function compareKey(a, b) {
1567
+ if (a.length === 1) {
1568
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
1569
+ }
1570
+ if (b.length === 1) {
1571
+ return 1;
1572
+ }
1573
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
1574
+ return 1;
1575
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
1576
+ return -1;
1577
+ }
1578
+ if (a === LABEL_REG_EXP_STR) {
1579
+ return 1;
1580
+ } else if (b === LABEL_REG_EXP_STR) {
1581
+ return -1;
1582
+ }
1583
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
1584
+ }
1585
+ var Node = class _Node {
1586
+ #index;
1587
+ #varIndex;
1588
+ #children = /* @__PURE__ */ Object.create(null);
1589
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
1590
+ if (tokens.length === 0) {
1591
+ if (this.#index !== void 0) {
1592
+ throw PATH_ERROR;
1593
+ }
1594
+ if (pathErrorCheckOnly) {
1595
+ return;
1596
+ }
1597
+ this.#index = index;
1598
+ return;
1599
+ }
1600
+ const [token, ...restTokens] = tokens;
1601
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1602
+ let node;
1603
+ if (pattern) {
1604
+ const name = pattern[1];
1605
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
1606
+ if (name && pattern[2]) {
1607
+ if (regexpStr === ".*") {
1608
+ throw PATH_ERROR;
1609
+ }
1610
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
1611
+ if (/\((?!\?:)/.test(regexpStr)) {
1612
+ throw PATH_ERROR;
1613
+ }
1614
+ }
1615
+ node = this.#children[regexpStr];
1616
+ if (!node) {
1617
+ if (Object.keys(this.#children).some(
1618
+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
1619
+ )) {
1620
+ throw PATH_ERROR;
1621
+ }
1622
+ if (pathErrorCheckOnly) {
1623
+ return;
1624
+ }
1625
+ node = this.#children[regexpStr] = new _Node();
1626
+ if (name !== "") {
1627
+ node.#varIndex = context.varIndex++;
1628
+ }
1629
+ }
1630
+ if (!pathErrorCheckOnly && name !== "") {
1631
+ paramMap.push([name, node.#varIndex]);
1632
+ }
1633
+ } else {
1634
+ node = this.#children[token];
1635
+ if (!node) {
1636
+ if (Object.keys(this.#children).some(
1637
+ (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR
1638
+ )) {
1639
+ throw PATH_ERROR;
1640
+ }
1641
+ if (pathErrorCheckOnly) {
1642
+ return;
1643
+ }
1644
+ node = this.#children[token] = new _Node();
1645
+ }
1646
+ }
1647
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
1648
+ }
1649
+ buildRegExpStr() {
1650
+ const childKeys = Object.keys(this.#children).sort(compareKey);
1651
+ const strList = childKeys.map((k) => {
1652
+ const c = this.#children[k];
1653
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
1654
+ });
1655
+ if (typeof this.#index === "number") {
1656
+ strList.unshift(`#${this.#index}`);
1657
+ }
1658
+ if (strList.length === 0) {
1659
+ return "";
1660
+ }
1661
+ if (strList.length === 1) {
1662
+ return strList[0];
1663
+ }
1664
+ return "(?:" + strList.join("|") + ")";
1665
+ }
1666
+ };
1667
+
1668
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router/reg-exp-router/trie.js
1669
+ var Trie = class {
1670
+ #context = { varIndex: 0 };
1671
+ #root = new Node();
1672
+ insert(path3, index, pathErrorCheckOnly) {
1673
+ const paramAssoc = [];
1674
+ const groups = [];
1675
+ for (let i = 0; ; ) {
1676
+ let replaced = false;
1677
+ path3 = path3.replace(/\{[^}]+\}/g, (m) => {
1678
+ const mark = `@\\${i}`;
1679
+ groups[i] = [mark, m];
1680
+ i++;
1681
+ replaced = true;
1682
+ return mark;
1683
+ });
1684
+ if (!replaced) {
1685
+ break;
1686
+ }
1687
+ }
1688
+ const tokens = path3.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1689
+ for (let i = groups.length - 1; i >= 0; i--) {
1690
+ const [mark] = groups[i];
1691
+ for (let j = tokens.length - 1; j >= 0; j--) {
1692
+ if (tokens[j].indexOf(mark) !== -1) {
1693
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
1694
+ break;
1695
+ }
1696
+ }
1697
+ }
1698
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
1699
+ return paramAssoc;
1700
+ }
1701
+ buildRegExp() {
1702
+ let regexp = this.#root.buildRegExpStr();
1703
+ if (regexp === "") {
1704
+ return [/^$/, [], []];
1705
+ }
1706
+ let captureIndex = 0;
1707
+ const indexReplacementMap = [];
1708
+ const paramReplacementMap = [];
1709
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1710
+ if (handlerIndex !== void 0) {
1711
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
1712
+ return "$()";
1713
+ }
1714
+ if (paramIndex !== void 0) {
1715
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1716
+ return "";
1717
+ }
1718
+ return "";
1719
+ });
1720
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
1721
+ }
1722
+ };
1723
+
1724
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router/reg-exp-router/router.js
1725
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
1726
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1727
+ function buildWildcardRegExp(path3) {
1728
+ return wildcardRegExpCache[path3] ??= new RegExp(
1729
+ path3 === "*" ? "" : `^${path3.replace(
1730
+ /\/\*$|([.\\+*[^\]$()])/g,
1731
+ (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)"
1732
+ )}$`
1733
+ );
1734
+ }
1735
+ function clearWildcardRegExpCache() {
1736
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1737
+ }
1738
+ function buildMatcherFromPreprocessedRoutes(routes) {
1739
+ const trie = new Trie();
1740
+ const handlerData = [];
1741
+ if (routes.length === 0) {
1742
+ return nullMatcher;
1743
+ }
1744
+ const routesWithStaticPathFlag = routes.map(
1745
+ (route) => [!/\*|\/:/.test(route[0]), ...route]
1746
+ ).sort(
1747
+ ([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length
1748
+ );
1749
+ const staticMap = /* @__PURE__ */ Object.create(null);
1750
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {
1751
+ const [pathErrorCheckOnly, path3, handlers] = routesWithStaticPathFlag[i];
1752
+ if (pathErrorCheckOnly) {
1753
+ staticMap[path3] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1754
+ } else {
1755
+ j++;
1756
+ }
1757
+ let paramAssoc;
1758
+ try {
1759
+ paramAssoc = trie.insert(path3, j, pathErrorCheckOnly);
1760
+ } catch (e) {
1761
+ throw e === PATH_ERROR ? new UnsupportedPathError(path3) : e;
1762
+ }
1763
+ if (pathErrorCheckOnly) {
1764
+ continue;
1765
+ }
1766
+ handlerData[j] = handlers.map(([h, paramCount]) => {
1767
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
1768
+ paramCount -= 1;
1769
+ for (; paramCount >= 0; paramCount--) {
1770
+ const [key, value] = paramAssoc[paramCount];
1771
+ paramIndexMap[key] = value;
1772
+ }
1773
+ return [h, paramIndexMap];
1774
+ });
1775
+ }
1776
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1777
+ for (let i = 0, len = handlerData.length; i < len; i++) {
1778
+ for (let j = 0, len2 = handlerData[i].length; j < len2; j++) {
1779
+ const map = handlerData[i][j]?.[1];
1780
+ if (!map) {
1781
+ continue;
1782
+ }
1783
+ const keys = Object.keys(map);
1784
+ for (let k = 0, len3 = keys.length; k < len3; k++) {
1785
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
1786
+ }
1787
+ }
1788
+ }
1789
+ const handlerMap = [];
1790
+ for (const i in indexReplacementMap) {
1791
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
1792
+ }
1793
+ return [regexp, handlerMap, staticMap];
1794
+ }
1795
+ function findMiddleware(middleware, path3) {
1796
+ if (!middleware) {
1797
+ return void 0;
1798
+ }
1799
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1800
+ if (buildWildcardRegExp(k).test(path3)) {
1801
+ return [...middleware[k]];
1802
+ }
1803
+ }
1804
+ return void 0;
1805
+ }
1806
+ var RegExpRouter = class {
1807
+ name = "RegExpRouter";
1808
+ #middleware;
1809
+ #routes;
1810
+ constructor() {
1811
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1812
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1813
+ }
1814
+ add(method, path3, handler) {
1815
+ const middleware = this.#middleware;
1816
+ const routes = this.#routes;
1817
+ if (!middleware || !routes) {
1818
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1819
+ }
1820
+ if (!middleware[method]) {
1821
+ ;
1822
+ [middleware, routes].forEach((handlerMap) => {
1823
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
1824
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
1825
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
1826
+ });
1827
+ });
1828
+ }
1829
+ if (path3 === "/*") {
1830
+ path3 = "*";
1831
+ }
1832
+ const paramCount = (path3.match(/\/:/g) || []).length;
1833
+ if (/\*$/.test(path3)) {
1834
+ const re = buildWildcardRegExp(path3);
1835
+ if (method === METHOD_NAME_ALL) {
1836
+ Object.keys(middleware).forEach((m) => {
1837
+ middleware[m][path3] ||= findMiddleware(middleware[m], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || [];
1838
+ });
1839
+ } else {
1840
+ middleware[method][path3] ||= findMiddleware(middleware[method], path3) || findMiddleware(middleware[METHOD_NAME_ALL], path3) || [];
1841
+ }
1842
+ Object.keys(middleware).forEach((m) => {
1843
+ if (method === METHOD_NAME_ALL || method === m) {
1844
+ Object.keys(middleware[m]).forEach((p) => {
1845
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
1846
+ });
1847
+ }
1848
+ });
1849
+ Object.keys(routes).forEach((m) => {
1850
+ if (method === METHOD_NAME_ALL || method === m) {
1851
+ Object.keys(routes[m]).forEach(
1852
+ (p) => re.test(p) && routes[m][p].push([handler, paramCount])
1853
+ );
1854
+ }
1855
+ });
1856
+ return;
1857
+ }
1858
+ const paths = checkOptionalParameter(path3) || [path3];
1859
+ for (let i = 0, len = paths.length; i < len; i++) {
1860
+ const path22 = paths[i];
1861
+ Object.keys(routes).forEach((m) => {
1862
+ if (method === METHOD_NAME_ALL || method === m) {
1863
+ routes[m][path22] ||= [
1864
+ ...findMiddleware(middleware[m], path22) || findMiddleware(middleware[METHOD_NAME_ALL], path22) || []
1865
+ ];
1866
+ routes[m][path22].push([handler, paramCount - len + i + 1]);
1867
+ }
1868
+ });
1869
+ }
1870
+ }
1871
+ match = match;
1872
+ buildAllMatchers() {
1873
+ const matchers = /* @__PURE__ */ Object.create(null);
1874
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
1875
+ matchers[method] ||= this.#buildMatcher(method);
1876
+ });
1877
+ this.#middleware = this.#routes = void 0;
1878
+ clearWildcardRegExpCache();
1879
+ return matchers;
1880
+ }
1881
+ #buildMatcher(method) {
1882
+ const routes = [];
1883
+ let hasOwnRoute = method === METHOD_NAME_ALL;
1884
+ [this.#middleware, this.#routes].forEach((r) => {
1885
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path3) => [path3, r[method][path3]]) : [];
1886
+ if (ownRoute.length !== 0) {
1887
+ hasOwnRoute ||= true;
1888
+ routes.push(...ownRoute);
1889
+ } else if (method !== METHOD_NAME_ALL) {
1890
+ routes.push(
1891
+ ...Object.keys(r[METHOD_NAME_ALL]).map((path3) => [path3, r[METHOD_NAME_ALL][path3]])
1892
+ );
1893
+ }
1894
+ });
1895
+ if (!hasOwnRoute) {
1896
+ return null;
1897
+ } else {
1898
+ return buildMatcherFromPreprocessedRoutes(routes);
1899
+ }
1900
+ }
1901
+ };
1902
+
1903
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router/smart-router/router.js
1904
+ var SmartRouter = class {
1905
+ name = "SmartRouter";
1906
+ #routers = [];
1907
+ #routes = [];
1908
+ constructor(init) {
1909
+ this.#routers = init.routers;
1910
+ }
1911
+ add(method, path3, handler) {
1912
+ if (!this.#routes) {
1913
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1914
+ }
1915
+ this.#routes.push([method, path3, handler]);
1916
+ }
1917
+ match(method, path3) {
1918
+ if (!this.#routes) {
1919
+ throw new Error("Fatal error");
1920
+ }
1921
+ const routers = this.#routers;
1922
+ const routes = this.#routes;
1923
+ const len = routers.length;
1924
+ let i = 0;
1925
+ let res;
1926
+ for (; i < len; i++) {
1927
+ const router = routers[i];
1928
+ try {
1929
+ for (let i2 = 0, len2 = routes.length; i2 < len2; i2++) {
1930
+ router.add(...routes[i2]);
1931
+ }
1932
+ res = router.match(method, path3);
1933
+ } catch (e) {
1934
+ if (e instanceof UnsupportedPathError) {
1935
+ continue;
1936
+ }
1937
+ throw e;
1938
+ }
1939
+ this.match = router.match.bind(router);
1940
+ this.#routers = [router];
1941
+ this.#routes = void 0;
1942
+ break;
1943
+ }
1944
+ if (i === len) {
1945
+ throw new Error("Fatal error");
1946
+ }
1947
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
1948
+ return res;
1949
+ }
1950
+ get activeRouter() {
1951
+ if (this.#routes || this.#routers.length !== 1) {
1952
+ throw new Error("No active router has been determined yet.");
1953
+ }
1954
+ return this.#routers[0];
1955
+ }
1956
+ };
1957
+
1958
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router/trie-router/node.js
1959
+ var emptyParams = /* @__PURE__ */ Object.create(null);
1960
+ var Node2 = class _Node2 {
1961
+ #methods;
1962
+ #children;
1963
+ #patterns;
1964
+ #order = 0;
1965
+ #params = emptyParams;
1966
+ constructor(method, handler, children) {
1967
+ this.#children = children || /* @__PURE__ */ Object.create(null);
1968
+ this.#methods = [];
1969
+ if (method && handler) {
1970
+ const m = /* @__PURE__ */ Object.create(null);
1971
+ m[method] = { handler, possibleKeys: [], score: 0 };
1972
+ this.#methods = [m];
1973
+ }
1974
+ this.#patterns = [];
1975
+ }
1976
+ insert(method, path3, handler) {
1977
+ this.#order = ++this.#order;
1978
+ let curNode = this;
1979
+ const parts = splitRoutingPath(path3);
1980
+ const possibleKeys = [];
1981
+ for (let i = 0, len = parts.length; i < len; i++) {
1982
+ const p = parts[i];
1983
+ const nextP = parts[i + 1];
1984
+ const pattern = getPattern(p, nextP);
1985
+ const key = Array.isArray(pattern) ? pattern[0] : p;
1986
+ if (key in curNode.#children) {
1987
+ curNode = curNode.#children[key];
1988
+ if (pattern) {
1989
+ possibleKeys.push(pattern[1]);
1990
+ }
1991
+ continue;
1992
+ }
1993
+ curNode.#children[key] = new _Node2();
1994
+ if (pattern) {
1995
+ curNode.#patterns.push(pattern);
1996
+ possibleKeys.push(pattern[1]);
1997
+ }
1998
+ curNode = curNode.#children[key];
1999
+ }
2000
+ curNode.#methods.push({
2001
+ [method]: {
2002
+ handler,
2003
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
2004
+ score: this.#order
2005
+ }
2006
+ });
2007
+ return curNode;
2008
+ }
2009
+ #getHandlerSets(node, method, nodeParams, params) {
2010
+ const handlerSets = [];
2011
+ for (let i = 0, len = node.#methods.length; i < len; i++) {
2012
+ const m = node.#methods[i];
2013
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
2014
+ const processedSet = {};
2015
+ if (handlerSet !== void 0) {
2016
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
2017
+ handlerSets.push(handlerSet);
2018
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
2019
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length; i2 < len2; i2++) {
2020
+ const key = handlerSet.possibleKeys[i2];
2021
+ const processed = processedSet[handlerSet.score];
2022
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
2023
+ processedSet[handlerSet.score] = true;
2024
+ }
2025
+ }
2026
+ }
2027
+ }
2028
+ return handlerSets;
2029
+ }
2030
+ search(method, path3) {
2031
+ const handlerSets = [];
2032
+ this.#params = emptyParams;
2033
+ const curNode = this;
2034
+ let curNodes = [curNode];
2035
+ const parts = splitPath(path3);
2036
+ const curNodesQueue = [];
2037
+ for (let i = 0, len = parts.length; i < len; i++) {
2038
+ const part = parts[i];
2039
+ const isLast = i === len - 1;
2040
+ const tempNodes = [];
2041
+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {
2042
+ const node = curNodes[j];
2043
+ const nextNode = node.#children[part];
2044
+ if (nextNode) {
2045
+ nextNode.#params = node.#params;
2046
+ if (isLast) {
2047
+ if (nextNode.#children["*"]) {
2048
+ handlerSets.push(
2049
+ ...this.#getHandlerSets(nextNode.#children["*"], method, node.#params)
2050
+ );
2051
+ }
2052
+ handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
2053
+ } else {
2054
+ tempNodes.push(nextNode);
2055
+ }
2056
+ }
2057
+ for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {
2058
+ const pattern = node.#patterns[k];
2059
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
2060
+ if (pattern === "*") {
2061
+ const astNode = node.#children["*"];
2062
+ if (astNode) {
2063
+ handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
2064
+ astNode.#params = params;
2065
+ tempNodes.push(astNode);
2066
+ }
2067
+ continue;
2068
+ }
2069
+ const [key, name, matcher] = pattern;
2070
+ if (!part && !(matcher instanceof RegExp)) {
2071
+ continue;
2072
+ }
2073
+ const child = node.#children[key];
2074
+ const restPathString = parts.slice(i).join("/");
2075
+ if (matcher instanceof RegExp) {
2076
+ const m = matcher.exec(restPathString);
2077
+ if (m) {
2078
+ params[name] = m[0];
2079
+ handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
2080
+ if (Object.keys(child.#children).length) {
2081
+ child.#params = params;
2082
+ const componentCount = m[0].match(/\//)?.length ?? 0;
2083
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
2084
+ targetCurNodes.push(child);
2085
+ }
2086
+ continue;
2087
+ }
2088
+ }
2089
+ if (matcher === true || matcher.test(part)) {
2090
+ params[name] = part;
2091
+ if (isLast) {
2092
+ handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
2093
+ if (child.#children["*"]) {
2094
+ handlerSets.push(
2095
+ ...this.#getHandlerSets(child.#children["*"], method, params, node.#params)
2096
+ );
2097
+ }
2098
+ } else {
2099
+ child.#params = params;
2100
+ tempNodes.push(child);
2101
+ }
2102
+ }
2103
+ }
2104
+ }
2105
+ curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
2106
+ }
2107
+ if (handlerSets.length > 1) {
2108
+ handlerSets.sort((a, b) => {
2109
+ return a.score - b.score;
2110
+ });
2111
+ }
2112
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
2113
+ }
2114
+ };
2115
+
2116
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/router/trie-router/router.js
2117
+ var TrieRouter = class {
2118
+ name = "TrieRouter";
2119
+ #node;
2120
+ constructor() {
2121
+ this.#node = new Node2();
2122
+ }
2123
+ add(method, path3, handler) {
2124
+ const results = checkOptionalParameter(path3);
2125
+ if (results) {
2126
+ for (let i = 0, len = results.length; i < len; i++) {
2127
+ this.#node.insert(method, results[i], handler);
2128
+ }
2129
+ return;
2130
+ }
2131
+ this.#node.insert(method, path3, handler);
2132
+ }
2133
+ match(method, path3) {
2134
+ return this.#node.search(method, path3);
2135
+ }
2136
+ };
2137
+
2138
+ // ../../node_modules/.pnpm/hono@4.11.5/node_modules/hono/dist/hono.js
2139
+ var Hono2 = class extends Hono {
2140
+ /**
2141
+ * Creates an instance of the Hono class.
2142
+ *
2143
+ * @param options - Optional configuration options for the Hono instance.
2144
+ */
2145
+ constructor(options = {}) {
2146
+ super(options);
2147
+ this.router = options.router ?? new SmartRouter({
2148
+ routers: [new RegExpRouter(), new TrieRouter()]
2149
+ });
2150
+ }
2151
+ };
2152
+
2153
+ // src/server/loadHandler.ts
2154
+ import * as fs from "fs";
2155
+ import * as path from "path";
2156
+ import { builtinModules } from "module";
2157
+ import { build } from "esbuild";
2158
+ import { pathToFileURL } from "url";
2159
+ var moduleCache = /* @__PURE__ */ new Map();
2160
+ async function loadRouteHandler(absolutePath, verbose = false) {
2161
+ try {
2162
+ const stat = fs.statSync(absolutePath);
2163
+ const mtime = stat.mtimeMs;
2164
+ const cached = moduleCache.get(absolutePath);
2165
+ if (cached && cached.mtime === mtime) {
2166
+ return cached.module;
2167
+ }
2168
+ const nodeVersion = process.versions.node.split(".")[0];
2169
+ const target = `node${nodeVersion}`;
2170
+ const result = await build({
2171
+ entryPoints: [absolutePath],
2172
+ bundle: true,
2173
+ write: false,
2174
+ format: "esm",
2175
+ platform: "node",
2176
+ target,
2177
+ external: [
2178
+ "@cloudwerk/core",
2179
+ "hono",
2180
+ // Use builtinModules for comprehensive Node.js built-in coverage
2181
+ ...builtinModules,
2182
+ ...builtinModules.map((m) => `node:${m}`)
2183
+ ],
2184
+ logLevel: verbose ? "warning" : "silent",
2185
+ sourcemap: "inline"
2186
+ });
2187
+ if (!result.outputFiles || result.outputFiles.length === 0) {
2188
+ throw new Error("No output from esbuild");
2189
+ }
2190
+ const code = result.outputFiles[0].text;
2191
+ const cacheKey = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
2192
+ const tempDir = findSafeTempDir(absolutePath);
2193
+ const tempFile = path.join(tempDir, `.cloudwerk-route-${cacheKey}.mjs`);
2194
+ fs.writeFileSync(tempFile, code);
2195
+ try {
2196
+ const module = await import(pathToFileURL(tempFile).href);
2197
+ moduleCache.set(absolutePath, { module, mtime });
2198
+ return module;
2199
+ } finally {
2200
+ try {
2201
+ fs.unlinkSync(tempFile);
2202
+ } catch {
2203
+ }
2204
+ }
2205
+ } catch (error) {
2206
+ const message = error instanceof Error ? error.message : String(error);
2207
+ throw new Error(`Failed to compile route handler at ${absolutePath}: ${message}`);
2208
+ }
2209
+ }
2210
+ function findSafeTempDir(filePath) {
2211
+ let dir = path.dirname(filePath);
2212
+ const hasSpecialChars = (p) => /\[|\]|\(|\)/.test(path.basename(p));
2213
+ while (hasSpecialChars(dir)) {
2214
+ const parent = path.dirname(dir);
2215
+ if (parent === dir) {
2216
+ break;
2217
+ }
2218
+ dir = parent;
2219
+ }
2220
+ return dir;
2221
+ }
2222
+
2223
+ // src/server/registerRoutes.ts
2224
+ var HTTP_METHODS = [
2225
+ "GET",
2226
+ "POST",
2227
+ "PUT",
2228
+ "PATCH",
2229
+ "DELETE",
2230
+ "OPTIONS",
2231
+ "HEAD"
2232
+ ];
2233
+ async function registerRoutes(app, manifest, logger, verbose = false) {
2234
+ const registeredRoutes = [];
2235
+ for (const route of manifest.routes) {
2236
+ if (route.fileType !== "route") {
2237
+ logger.debug(`Skipping non-route file: ${route.filePath}`);
2238
+ continue;
2239
+ }
2240
+ try {
2241
+ logger.debug(`Loading route handler: ${route.filePath}`);
2242
+ const module = await loadRouteHandler(route.absolutePath, verbose);
2243
+ for (const method of HTTP_METHODS) {
2244
+ const handler = module[method];
2245
+ if (handler && typeof handler === "function") {
2246
+ registerMethod(app, method, route.urlPattern, handler);
2247
+ registeredRoutes.push({
2248
+ method,
2249
+ pattern: route.urlPattern,
2250
+ filePath: route.filePath
2251
+ });
2252
+ logger.debug(`Registered ${method} ${route.urlPattern}`);
2253
+ }
2254
+ }
2255
+ } catch (error) {
2256
+ const message = error instanceof Error ? error.message : String(error);
2257
+ logger.error(`Failed to load route ${route.filePath}: ${message}`);
2258
+ }
2259
+ }
2260
+ return registeredRoutes;
2261
+ }
2262
+ function registerMethod(app, method, pattern, handler) {
2263
+ const h = handler;
2264
+ switch (method) {
2265
+ case "GET":
2266
+ app.get(pattern, h);
2267
+ break;
2268
+ case "POST":
2269
+ app.post(pattern, h);
2270
+ break;
2271
+ case "PUT":
2272
+ app.put(pattern, h);
2273
+ break;
2274
+ case "PATCH":
2275
+ app.patch(pattern, h);
2276
+ break;
2277
+ case "DELETE":
2278
+ app.delete(pattern, h);
2279
+ break;
2280
+ case "OPTIONS":
2281
+ app.options(pattern, h);
2282
+ break;
2283
+ case "HEAD":
2284
+ app.on("HEAD", [pattern], h);
2285
+ break;
2286
+ }
2287
+ }
2288
+
2289
+ // src/constants.ts
2290
+ var DEFAULT_PORT = 3e3;
2291
+ var DEFAULT_HOST = "localhost";
2292
+ var SHUTDOWN_TIMEOUT_MS = 5e3;
2293
+ var HTTP_STATUS = {
2294
+ NOT_FOUND: 404,
2295
+ INTERNAL_SERVER_ERROR: 500
2296
+ };
2297
+
2298
+ // src/server/createApp.ts
2299
+ async function createApp(manifest, config, logger, verbose = false) {
2300
+ const app = new Hono2({
2301
+ strict: false
2302
+ });
2303
+ if (verbose) {
2304
+ app.use("*", async (c, next) => {
2305
+ const start = Date.now();
2306
+ await next();
2307
+ const duration = Date.now() - start;
2308
+ logRequest(c.req.method, c.req.path, c.res.status, duration);
2309
+ });
2310
+ }
2311
+ if (config.globalMiddleware && config.globalMiddleware.length > 0) {
2312
+ for (const middleware of config.globalMiddleware) {
2313
+ app.use("*", middleware);
2314
+ }
2315
+ }
2316
+ const routes = await registerRoutes(app, manifest, logger, verbose);
2317
+ app.notFound((c) => {
2318
+ return c.json(
2319
+ {
2320
+ error: "Not Found",
2321
+ path: c.req.path,
2322
+ method: c.req.method
2323
+ },
2324
+ HTTP_STATUS.NOT_FOUND
2325
+ );
2326
+ });
2327
+ app.onError((err, c) => {
2328
+ logger.error(`Request error: ${err.message}`);
2329
+ return c.json(
2330
+ {
2331
+ error: "Internal Server Error",
2332
+ message: err.message,
2333
+ stack: err.stack
2334
+ },
2335
+ HTTP_STATUS.INTERNAL_SERVER_ERROR
2336
+ );
2337
+ });
2338
+ return { app, routes };
2339
+ }
2340
+
2341
+ // src/version.ts
2342
+ import { createRequire } from "module";
2343
+ var require2 = createRequire(import.meta.url);
2344
+ var pkg = require2("../package.json");
2345
+ var VERSION = pkg.version;
2346
+
2347
+ // src/commands/dev.ts
2348
+ async function dev(pathArg, options) {
2349
+ const startTime = Date.now();
2350
+ const verbose = options.verbose ?? false;
2351
+ const logger = createLogger(verbose);
2352
+ try {
2353
+ const cwd = pathArg ? path2.resolve(process.cwd(), pathArg) : process.cwd();
2354
+ if (!fs2.existsSync(cwd)) {
2355
+ throw new CliError(
2356
+ `Directory does not exist: ${cwd}`,
2357
+ "ENOENT",
2358
+ `Make sure the path exists and try again.`
2359
+ );
2360
+ }
2361
+ logger.debug(`Working directory: ${cwd}`);
2362
+ logger.debug(`Loading configuration...`);
2363
+ const config = await loadConfig(cwd);
2364
+ logger.debug(`Config loaded: routesDir=${config.routesDir}, extensions=${config.extensions.join(", ")}`);
2365
+ const routesDir = resolveRoutesDir(config, cwd);
2366
+ logger.debug(`Routes directory: ${routesDir}`);
2367
+ if (!fs2.existsSync(routesDir)) {
2368
+ throw new CliError(
2369
+ `Routes directory does not exist: ${routesDir}`,
2370
+ "ENOENT",
2371
+ `Create the "${config.routesDir}" directory or update routesDir in cloudwerk.config.ts`
2372
+ );
2373
+ }
2374
+ logger.debug(`Scanning routes...`);
2375
+ const scanResult = await scanRoutes(routesDir, config);
2376
+ logger.debug(`Found ${scanResult.routes.length} route files`);
2377
+ logger.debug(`Building route manifest...`);
2378
+ const manifest = buildRouteManifest(
2379
+ scanResult,
2380
+ routesDir,
2381
+ resolveLayouts,
2382
+ resolveMiddleware
2383
+ );
2384
+ if (hasErrors(manifest)) {
2385
+ const errorMessages = formatErrors(manifest.errors);
2386
+ logger.error(errorMessages);
2387
+ throw new CliError(
2388
+ "Route validation failed",
2389
+ "VALIDATION_ERROR",
2390
+ "Fix the errors above and try again."
2391
+ );
2392
+ }
2393
+ if (manifest.warnings.length > 0) {
2394
+ const warningMessages = formatWarnings(manifest.warnings);
2395
+ logger.warn(warningMessages);
2396
+ }
2397
+ if (manifest.routes.length === 0) {
2398
+ logger.warn(`No routes found in ${config.routesDir}`);
2399
+ logger.warn(`Create a route.ts file to get started.`);
2400
+ }
2401
+ logger.debug(`Creating Hono app...`);
2402
+ const { app, routes } = await createApp(manifest, config, logger, verbose);
2403
+ const port = parseInt(options.port, 10);
2404
+ if (isNaN(port) || port < 1 || port > 65535) {
2405
+ throw new CliError(
2406
+ `Invalid port: ${options.port}`,
2407
+ "INVALID_PORT",
2408
+ "Port must be a number between 1 and 65535"
2409
+ );
2410
+ }
2411
+ logger.debug(`Starting server on port ${port}...`);
2412
+ const host = options.host;
2413
+ const server = serve({
2414
+ fetch: app.fetch,
2415
+ port,
2416
+ hostname: host
2417
+ });
2418
+ server.on("error", (err) => {
2419
+ if (err.code === "EADDRINUSE") {
2420
+ printError(
2421
+ `Port ${port} is already in use`,
2422
+ `Try using a different port:
2423
+ cloudwerk dev --port ${port + 1}`
2424
+ );
2425
+ process.exit(1);
2426
+ } else {
2427
+ printError(err.message);
2428
+ process.exit(1);
2429
+ }
2430
+ });
2431
+ await new Promise((resolve2) => {
2432
+ server.on("listening", resolve2);
2433
+ });
2434
+ const startupTime = Date.now() - startTime;
2435
+ const localUrl = `http://${host === "0.0.0.0" ? "localhost" : host}:${port}/`;
2436
+ const networkUrl = host === "0.0.0.0" ? getNetworkUrl(port) : void 0;
2437
+ printStartupBanner(
2438
+ VERSION,
2439
+ localUrl,
2440
+ networkUrl,
2441
+ routes.map((r) => ({ method: r.method, pattern: r.pattern })),
2442
+ startupTime
2443
+ );
2444
+ setupGracefulShutdown(server, logger);
2445
+ } catch (error) {
2446
+ if (error instanceof CliError) {
2447
+ printError(error.message, error.suggestion);
2448
+ process.exit(1);
2449
+ }
2450
+ if (error instanceof Error) {
2451
+ printError(error.message);
2452
+ if (verbose && error.stack) {
2453
+ console.log(error.stack);
2454
+ }
2455
+ process.exit(1);
2456
+ }
2457
+ printError(String(error));
2458
+ process.exit(1);
2459
+ }
2460
+ }
2461
+ function getNetworkUrl(port) {
2462
+ const interfaces = os.networkInterfaces();
2463
+ for (const name of Object.keys(interfaces)) {
2464
+ const iface = interfaces[name];
2465
+ if (!iface) continue;
2466
+ for (const alias of iface) {
2467
+ if (alias.family === "IPv4" && !alias.internal) {
2468
+ return `http://${alias.address}:${port}/`;
2469
+ }
2470
+ }
2471
+ }
2472
+ return void 0;
2473
+ }
2474
+ function setupGracefulShutdown(server, logger) {
2475
+ const shutdown = () => {
2476
+ console.log();
2477
+ logger.info("Shutting down...");
2478
+ server.close(() => {
2479
+ logger.info("Server closed");
2480
+ process.exit(0);
2481
+ });
2482
+ setTimeout(() => {
2483
+ logger.warn("Forcing shutdown...");
2484
+ process.exit(0);
2485
+ }, SHUTDOWN_TIMEOUT_MS);
2486
+ };
2487
+ process.on("SIGINT", shutdown);
2488
+ process.on("SIGTERM", shutdown);
2489
+ }
2490
+
2491
+ // src/index.ts
2492
+ program.name("cloudwerk").description("Cloudwerk CLI - Build and deploy full-stack apps to Cloudflare").version(VERSION);
2493
+ program.command("dev [path]").description("Start development server").option("-p, --port <number>", "Port to listen on", String(DEFAULT_PORT)).option("-H, --host <host>", "Host to bind", DEFAULT_HOST).option("-c, --config <path>", "Path to config file").option("--verbose", "Enable verbose logging").action(dev);
2494
+ program.parse();