@gravito/monolith 1.0.0-alpha.2 → 1.0.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4631 @@
1
+ import { createRequire } from "node:module";
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __toESM = (mod, isNodeMode, target) => {
8
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
9
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
10
+ for (let key of __getOwnPropNames(mod))
11
+ if (!__hasOwnProp.call(to, key))
12
+ __defProp(to, key, {
13
+ get: () => mod[key],
14
+ enumerable: true
15
+ });
16
+ return to;
17
+ };
18
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
19
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
20
+
21
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/compose.js
22
+ var require_compose = __commonJS((exports, module) => {
23
+ var __defProp2 = Object.defineProperty;
24
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
25
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
26
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
27
+ var __export = (target, all) => {
28
+ for (var name in all)
29
+ __defProp2(target, name, { get: all[name], enumerable: true });
30
+ };
31
+ var __copyProps = (to, from, except, desc) => {
32
+ if (from && typeof from === "object" || typeof from === "function") {
33
+ for (let key of __getOwnPropNames2(from))
34
+ if (!__hasOwnProp2.call(to, key) && key !== except)
35
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
36
+ }
37
+ return to;
38
+ };
39
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
40
+ var compose_exports = {};
41
+ __export(compose_exports, {
42
+ compose: () => compose
43
+ });
44
+ module.exports = __toCommonJS(compose_exports);
45
+ var compose = (middleware, onError, onNotFound) => {
46
+ return (context, next) => {
47
+ let index = -1;
48
+ return dispatch(0);
49
+ async function dispatch(i) {
50
+ if (i <= index) {
51
+ throw new Error("next() called multiple times");
52
+ }
53
+ index = i;
54
+ let res;
55
+ let isError = false;
56
+ let handler;
57
+ if (middleware[i]) {
58
+ handler = middleware[i][0][0];
59
+ context.req.routeIndex = i;
60
+ } else {
61
+ handler = i === middleware.length && next || undefined;
62
+ }
63
+ if (handler) {
64
+ try {
65
+ res = await handler(context, () => dispatch(i + 1));
66
+ } catch (err) {
67
+ if (err instanceof Error && onError) {
68
+ context.error = err;
69
+ res = await onError(err, context);
70
+ isError = true;
71
+ } else {
72
+ throw err;
73
+ }
74
+ }
75
+ } else {
76
+ if (context.finalized === false && onNotFound) {
77
+ res = await onNotFound(context);
78
+ }
79
+ }
80
+ if (res && (context.finalized === false || isError)) {
81
+ context.res = res;
82
+ }
83
+ return context;
84
+ }
85
+ };
86
+ };
87
+ });
88
+
89
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/http-exception.js
90
+ var require_http_exception = __commonJS((exports, module) => {
91
+ var __defProp2 = Object.defineProperty;
92
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
93
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
94
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
95
+ var __export = (target, all) => {
96
+ for (var name in all)
97
+ __defProp2(target, name, { get: all[name], enumerable: true });
98
+ };
99
+ var __copyProps = (to, from, except, desc) => {
100
+ if (from && typeof from === "object" || typeof from === "function") {
101
+ for (let key of __getOwnPropNames2(from))
102
+ if (!__hasOwnProp2.call(to, key) && key !== except)
103
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
104
+ }
105
+ return to;
106
+ };
107
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
108
+ var http_exception_exports = {};
109
+ __export(http_exception_exports, {
110
+ HTTPException: () => HTTPException
111
+ });
112
+ module.exports = __toCommonJS(http_exception_exports);
113
+
114
+ class HTTPException extends Error {
115
+ res;
116
+ status;
117
+ constructor(status = 500, options) {
118
+ super(options?.message, { cause: options?.cause });
119
+ this.res = options?.res;
120
+ this.status = status;
121
+ }
122
+ getResponse() {
123
+ if (this.res) {
124
+ const newResponse = new Response(this.res.body, {
125
+ status: this.status,
126
+ headers: this.res.headers
127
+ });
128
+ return newResponse;
129
+ }
130
+ return new Response(this.message, {
131
+ status: this.status
132
+ });
133
+ }
134
+ }
135
+ });
136
+
137
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/request/constants.js
138
+ var require_constants = __commonJS((exports, module) => {
139
+ var __defProp2 = Object.defineProperty;
140
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
141
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
142
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
143
+ var __export = (target, all) => {
144
+ for (var name in all)
145
+ __defProp2(target, name, { get: all[name], enumerable: true });
146
+ };
147
+ var __copyProps = (to, from, except, desc) => {
148
+ if (from && typeof from === "object" || typeof from === "function") {
149
+ for (let key of __getOwnPropNames2(from))
150
+ if (!__hasOwnProp2.call(to, key) && key !== except)
151
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
152
+ }
153
+ return to;
154
+ };
155
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
156
+ var constants_exports = {};
157
+ __export(constants_exports, {
158
+ GET_MATCH_RESULT: () => GET_MATCH_RESULT
159
+ });
160
+ module.exports = __toCommonJS(constants_exports);
161
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
162
+ });
163
+
164
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/utils/body.js
165
+ var require_body = __commonJS((exports, module) => {
166
+ var __defProp2 = Object.defineProperty;
167
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
168
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
169
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
170
+ var __export = (target, all) => {
171
+ for (var name in all)
172
+ __defProp2(target, name, { get: all[name], enumerable: true });
173
+ };
174
+ var __copyProps = (to, from, except, desc) => {
175
+ if (from && typeof from === "object" || typeof from === "function") {
176
+ for (let key of __getOwnPropNames2(from))
177
+ if (!__hasOwnProp2.call(to, key) && key !== except)
178
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
179
+ }
180
+ return to;
181
+ };
182
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
183
+ var body_exports = {};
184
+ __export(body_exports, {
185
+ parseBody: () => parseBody
186
+ });
187
+ module.exports = __toCommonJS(body_exports);
188
+ var import_request = require_request();
189
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
190
+ const { all = false, dot = false } = options;
191
+ const headers = request instanceof import_request.HonoRequest ? request.raw.headers : request.headers;
192
+ const contentType = headers.get("Content-Type");
193
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
194
+ return parseFormData(request, { all, dot });
195
+ }
196
+ return {};
197
+ };
198
+ async function parseFormData(request, options) {
199
+ const formData = await request.formData();
200
+ if (formData) {
201
+ return convertFormDataToBodyData(formData, options);
202
+ }
203
+ return {};
204
+ }
205
+ function convertFormDataToBodyData(formData, options) {
206
+ const form = /* @__PURE__ */ Object.create(null);
207
+ formData.forEach((value, key) => {
208
+ const shouldParseAllValues = options.all || key.endsWith("[]");
209
+ if (!shouldParseAllValues) {
210
+ form[key] = value;
211
+ } else {
212
+ handleParsingAllValues(form, key, value);
213
+ }
214
+ });
215
+ if (options.dot) {
216
+ Object.entries(form).forEach(([key, value]) => {
217
+ const shouldParseDotValues = key.includes(".");
218
+ if (shouldParseDotValues) {
219
+ handleParsingNestedValues(form, key, value);
220
+ delete form[key];
221
+ }
222
+ });
223
+ }
224
+ return form;
225
+ }
226
+ var handleParsingAllValues = (form, key, value) => {
227
+ if (form[key] !== undefined) {
228
+ if (Array.isArray(form[key])) {
229
+ form[key].push(value);
230
+ } else {
231
+ form[key] = [form[key], value];
232
+ }
233
+ } else {
234
+ if (!key.endsWith("[]")) {
235
+ form[key] = value;
236
+ } else {
237
+ form[key] = [value];
238
+ }
239
+ }
240
+ };
241
+ var handleParsingNestedValues = (form, key, value) => {
242
+ let nestedForm = form;
243
+ const keys = key.split(".");
244
+ keys.forEach((key2, index) => {
245
+ if (index === keys.length - 1) {
246
+ nestedForm[key2] = value;
247
+ } else {
248
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
249
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
250
+ }
251
+ nestedForm = nestedForm[key2];
252
+ }
253
+ });
254
+ };
255
+ });
256
+
257
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/utils/url.js
258
+ var require_url = __commonJS((exports, module) => {
259
+ var __defProp2 = Object.defineProperty;
260
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
261
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
262
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
263
+ var __export = (target, all) => {
264
+ for (var name in all)
265
+ __defProp2(target, name, { get: all[name], enumerable: true });
266
+ };
267
+ var __copyProps = (to, from, except, desc) => {
268
+ if (from && typeof from === "object" || typeof from === "function") {
269
+ for (let key of __getOwnPropNames2(from))
270
+ if (!__hasOwnProp2.call(to, key) && key !== except)
271
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
272
+ }
273
+ return to;
274
+ };
275
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
276
+ var url_exports = {};
277
+ __export(url_exports, {
278
+ checkOptionalParameter: () => checkOptionalParameter,
279
+ decodeURIComponent_: () => decodeURIComponent_,
280
+ getPath: () => getPath,
281
+ getPathNoStrict: () => getPathNoStrict,
282
+ getPattern: () => getPattern,
283
+ getQueryParam: () => getQueryParam,
284
+ getQueryParams: () => getQueryParams,
285
+ getQueryStrings: () => getQueryStrings,
286
+ mergePath: () => mergePath,
287
+ splitPath: () => splitPath,
288
+ splitRoutingPath: () => splitRoutingPath,
289
+ tryDecode: () => tryDecode
290
+ });
291
+ module.exports = __toCommonJS(url_exports);
292
+ var splitPath = (path) => {
293
+ const paths = path.split("/");
294
+ if (paths[0] === "") {
295
+ paths.shift();
296
+ }
297
+ return paths;
298
+ };
299
+ var splitRoutingPath = (routePath) => {
300
+ const { groups, path } = extractGroupsFromPath(routePath);
301
+ const paths = splitPath(path);
302
+ return replaceGroupMarks(paths, groups);
303
+ };
304
+ var extractGroupsFromPath = (path) => {
305
+ const groups = [];
306
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
307
+ const mark = `@${index}`;
308
+ groups.push([mark, match]);
309
+ return mark;
310
+ });
311
+ return { groups, path };
312
+ };
313
+ var replaceGroupMarks = (paths, groups) => {
314
+ for (let i = groups.length - 1;i >= 0; i--) {
315
+ const [mark] = groups[i];
316
+ for (let j = paths.length - 1;j >= 0; j--) {
317
+ if (paths[j].includes(mark)) {
318
+ paths[j] = paths[j].replace(mark, groups[i][1]);
319
+ break;
320
+ }
321
+ }
322
+ }
323
+ return paths;
324
+ };
325
+ var patternCache = {};
326
+ var getPattern = (label, next) => {
327
+ if (label === "*") {
328
+ return "*";
329
+ }
330
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
331
+ if (match) {
332
+ const cacheKey = `${label}#${next}`;
333
+ if (!patternCache[cacheKey]) {
334
+ if (match[2]) {
335
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
336
+ } else {
337
+ patternCache[cacheKey] = [label, match[1], true];
338
+ }
339
+ }
340
+ return patternCache[cacheKey];
341
+ }
342
+ return null;
343
+ };
344
+ var tryDecode = (str, decoder) => {
345
+ try {
346
+ return decoder(str);
347
+ } catch {
348
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
349
+ try {
350
+ return decoder(match);
351
+ } catch {
352
+ return match;
353
+ }
354
+ });
355
+ }
356
+ };
357
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
358
+ var getPath = (request) => {
359
+ const url = request.url;
360
+ const start = url.indexOf("/", url.indexOf(":") + 4);
361
+ let i = start;
362
+ for (;i < url.length; i++) {
363
+ const charCode = url.charCodeAt(i);
364
+ if (charCode === 37) {
365
+ const queryIndex = url.indexOf("?", i);
366
+ const path = url.slice(start, queryIndex === -1 ? undefined : queryIndex);
367
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
368
+ } else if (charCode === 63) {
369
+ break;
370
+ }
371
+ }
372
+ return url.slice(start, i);
373
+ };
374
+ var getQueryStrings = (url) => {
375
+ const queryIndex = url.indexOf("?", 8);
376
+ return queryIndex === -1 ? "" : "?" + url.slice(queryIndex + 1);
377
+ };
378
+ var getPathNoStrict = (request) => {
379
+ const result = getPath(request);
380
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
381
+ };
382
+ var mergePath = (base, sub, ...rest) => {
383
+ if (rest.length) {
384
+ sub = mergePath(sub, ...rest);
385
+ }
386
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
387
+ };
388
+ var checkOptionalParameter = (path) => {
389
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
390
+ return null;
391
+ }
392
+ const segments = path.split("/");
393
+ const results = [];
394
+ let basePath = "";
395
+ segments.forEach((segment) => {
396
+ if (segment !== "" && !/\:/.test(segment)) {
397
+ basePath += "/" + segment;
398
+ } else if (/\:/.test(segment)) {
399
+ if (/\?/.test(segment)) {
400
+ if (results.length === 0 && basePath === "") {
401
+ results.push("/");
402
+ } else {
403
+ results.push(basePath);
404
+ }
405
+ const optionalSegment = segment.replace("?", "");
406
+ basePath += "/" + optionalSegment;
407
+ results.push(basePath);
408
+ } else {
409
+ basePath += "/" + segment;
410
+ }
411
+ }
412
+ });
413
+ return results.filter((v, i, a) => a.indexOf(v) === i);
414
+ };
415
+ var _decodeURI = (value) => {
416
+ if (!/[%+]/.test(value)) {
417
+ return value;
418
+ }
419
+ if (value.indexOf("+") !== -1) {
420
+ value = value.replace(/\+/g, " ");
421
+ }
422
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
423
+ };
424
+ var _getQueryParam = (url, key, multiple) => {
425
+ let encoded;
426
+ if (!multiple && key && !/[%+]/.test(key)) {
427
+ let keyIndex2 = url.indexOf("?", 8);
428
+ if (keyIndex2 === -1) {
429
+ return;
430
+ }
431
+ if (!url.startsWith(key, keyIndex2 + 1)) {
432
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
433
+ }
434
+ while (keyIndex2 !== -1) {
435
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
436
+ if (trailingKeyCode === 61) {
437
+ const valueIndex = keyIndex2 + key.length + 2;
438
+ const endIndex = url.indexOf("&", valueIndex);
439
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
440
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
441
+ return "";
442
+ }
443
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
444
+ }
445
+ encoded = /[%+]/.test(url);
446
+ if (!encoded) {
447
+ return;
448
+ }
449
+ }
450
+ const results = {};
451
+ encoded ??= /[%+]/.test(url);
452
+ let keyIndex = url.indexOf("?", 8);
453
+ while (keyIndex !== -1) {
454
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
455
+ let valueIndex = url.indexOf("=", keyIndex);
456
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
457
+ valueIndex = -1;
458
+ }
459
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
460
+ if (encoded) {
461
+ name = _decodeURI(name);
462
+ }
463
+ keyIndex = nextKeyIndex;
464
+ if (name === "") {
465
+ continue;
466
+ }
467
+ let value;
468
+ if (valueIndex === -1) {
469
+ value = "";
470
+ } else {
471
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
472
+ if (encoded) {
473
+ value = _decodeURI(value);
474
+ }
475
+ }
476
+ if (multiple) {
477
+ if (!(results[name] && Array.isArray(results[name]))) {
478
+ results[name] = [];
479
+ }
480
+ results[name].push(value);
481
+ } else {
482
+ results[name] ??= value;
483
+ }
484
+ }
485
+ return key ? results[key] : results;
486
+ };
487
+ var getQueryParam = _getQueryParam;
488
+ var getQueryParams = (url, key) => {
489
+ return _getQueryParam(url, key, true);
490
+ };
491
+ var decodeURIComponent_ = decodeURIComponent;
492
+ });
493
+
494
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/request.js
495
+ var require_request = __commonJS((exports, module) => {
496
+ var __defProp2 = Object.defineProperty;
497
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
498
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
499
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
500
+ var __export = (target, all) => {
501
+ for (var name in all)
502
+ __defProp2(target, name, { get: all[name], enumerable: true });
503
+ };
504
+ var __copyProps = (to, from, except, desc) => {
505
+ if (from && typeof from === "object" || typeof from === "function") {
506
+ for (let key of __getOwnPropNames2(from))
507
+ if (!__hasOwnProp2.call(to, key) && key !== except)
508
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
509
+ }
510
+ return to;
511
+ };
512
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
513
+ var request_exports = {};
514
+ __export(request_exports, {
515
+ HonoRequest: () => HonoRequest,
516
+ cloneRawRequest: () => cloneRawRequest
517
+ });
518
+ module.exports = __toCommonJS(request_exports);
519
+ var import_http_exception = require_http_exception();
520
+ var import_constants = require_constants();
521
+ var import_body = require_body();
522
+ var import_url = require_url();
523
+ var tryDecodeURIComponent = (str) => (0, import_url.tryDecode)(str, import_url.decodeURIComponent_);
524
+
525
+ class HonoRequest {
526
+ raw;
527
+ #validatedData;
528
+ #matchResult;
529
+ routeIndex = 0;
530
+ path;
531
+ bodyCache = {};
532
+ constructor(request, path = "/", matchResult = [[]]) {
533
+ this.raw = request;
534
+ this.path = path;
535
+ this.#matchResult = matchResult;
536
+ this.#validatedData = {};
537
+ }
538
+ param(key) {
539
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
540
+ }
541
+ #getDecodedParam(key) {
542
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
543
+ const param = this.#getParamValue(paramKey);
544
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
545
+ }
546
+ #getAllDecodedParams() {
547
+ const decoded = {};
548
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
549
+ for (const key of keys) {
550
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
551
+ if (value !== undefined) {
552
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
553
+ }
554
+ }
555
+ return decoded;
556
+ }
557
+ #getParamValue(paramKey) {
558
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
559
+ }
560
+ query(key) {
561
+ return (0, import_url.getQueryParam)(this.url, key);
562
+ }
563
+ queries(key) {
564
+ return (0, import_url.getQueryParams)(this.url, key);
565
+ }
566
+ header(name) {
567
+ if (name) {
568
+ return this.raw.headers.get(name) ?? undefined;
569
+ }
570
+ const headerData = {};
571
+ this.raw.headers.forEach((value, key) => {
572
+ headerData[key] = value;
573
+ });
574
+ return headerData;
575
+ }
576
+ async parseBody(options) {
577
+ return this.bodyCache.parsedBody ??= await (0, import_body.parseBody)(this, options);
578
+ }
579
+ #cachedBody = (key) => {
580
+ const { bodyCache, raw } = this;
581
+ const cachedBody = bodyCache[key];
582
+ if (cachedBody) {
583
+ return cachedBody;
584
+ }
585
+ const anyCachedKey = Object.keys(bodyCache)[0];
586
+ if (anyCachedKey) {
587
+ return bodyCache[anyCachedKey].then((body) => {
588
+ if (anyCachedKey === "json") {
589
+ body = JSON.stringify(body);
590
+ }
591
+ return new Response(body)[key]();
592
+ });
593
+ }
594
+ return bodyCache[key] = raw[key]();
595
+ };
596
+ json() {
597
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
598
+ }
599
+ text() {
600
+ return this.#cachedBody("text");
601
+ }
602
+ arrayBuffer() {
603
+ return this.#cachedBody("arrayBuffer");
604
+ }
605
+ blob() {
606
+ return this.#cachedBody("blob");
607
+ }
608
+ formData() {
609
+ return this.#cachedBody("formData");
610
+ }
611
+ addValidatedData(target, data) {
612
+ this.#validatedData[target] = data;
613
+ }
614
+ valid(target) {
615
+ return this.#validatedData[target];
616
+ }
617
+ get url() {
618
+ return this.raw.url;
619
+ }
620
+ get method() {
621
+ return this.raw.method;
622
+ }
623
+ get [import_constants.GET_MATCH_RESULT]() {
624
+ return this.#matchResult;
625
+ }
626
+ get matchedRoutes() {
627
+ return this.#matchResult[0].map(([[, route]]) => route);
628
+ }
629
+ get routePath() {
630
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
631
+ }
632
+ }
633
+ var cloneRawRequest = async (req) => {
634
+ if (!req.raw.bodyUsed) {
635
+ return req.raw.clone();
636
+ }
637
+ const cacheKey = Object.keys(req.bodyCache)[0];
638
+ if (!cacheKey) {
639
+ throw new import_http_exception.HTTPException(500, {
640
+ message: "Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly."
641
+ });
642
+ }
643
+ const requestInit = {
644
+ body: await req[cacheKey](),
645
+ cache: req.raw.cache,
646
+ credentials: req.raw.credentials,
647
+ headers: req.header(),
648
+ integrity: req.raw.integrity,
649
+ keepalive: req.raw.keepalive,
650
+ method: req.method,
651
+ mode: req.raw.mode,
652
+ redirect: req.raw.redirect,
653
+ referrer: req.raw.referrer,
654
+ referrerPolicy: req.raw.referrerPolicy,
655
+ signal: req.raw.signal
656
+ };
657
+ return new Request(req.url, requestInit);
658
+ };
659
+ });
660
+
661
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/utils/html.js
662
+ var require_html = __commonJS((exports, module) => {
663
+ var __defProp2 = Object.defineProperty;
664
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
665
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
666
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
667
+ var __export = (target, all) => {
668
+ for (var name in all)
669
+ __defProp2(target, name, { get: all[name], enumerable: true });
670
+ };
671
+ var __copyProps = (to, from, except, desc) => {
672
+ if (from && typeof from === "object" || typeof from === "function") {
673
+ for (let key of __getOwnPropNames2(from))
674
+ if (!__hasOwnProp2.call(to, key) && key !== except)
675
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
676
+ }
677
+ return to;
678
+ };
679
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
680
+ var html_exports = {};
681
+ __export(html_exports, {
682
+ HtmlEscapedCallbackPhase: () => HtmlEscapedCallbackPhase,
683
+ escapeToBuffer: () => escapeToBuffer,
684
+ raw: () => raw,
685
+ resolveCallback: () => resolveCallback,
686
+ resolveCallbackSync: () => resolveCallbackSync,
687
+ stringBufferToString: () => stringBufferToString
688
+ });
689
+ module.exports = __toCommonJS(html_exports);
690
+ var HtmlEscapedCallbackPhase = {
691
+ Stringify: 1,
692
+ BeforeStream: 2,
693
+ Stream: 3
694
+ };
695
+ var raw = (value, callbacks) => {
696
+ const escapedString = new String(value);
697
+ escapedString.isEscaped = true;
698
+ escapedString.callbacks = callbacks;
699
+ return escapedString;
700
+ };
701
+ var escapeRe = /[&<>'"]/;
702
+ var stringBufferToString = async (buffer, callbacks) => {
703
+ let str = "";
704
+ callbacks ||= [];
705
+ const resolvedBuffer = await Promise.all(buffer);
706
+ for (let i = resolvedBuffer.length - 1;; i--) {
707
+ str += resolvedBuffer[i];
708
+ i--;
709
+ if (i < 0) {
710
+ break;
711
+ }
712
+ let r = resolvedBuffer[i];
713
+ if (typeof r === "object") {
714
+ callbacks.push(...r.callbacks || []);
715
+ }
716
+ const isEscaped = r.isEscaped;
717
+ r = await (typeof r === "object" ? r.toString() : r);
718
+ if (typeof r === "object") {
719
+ callbacks.push(...r.callbacks || []);
720
+ }
721
+ if (r.isEscaped ?? isEscaped) {
722
+ str += r;
723
+ } else {
724
+ const buf = [str];
725
+ escapeToBuffer(r, buf);
726
+ str = buf[0];
727
+ }
728
+ }
729
+ return raw(str, callbacks);
730
+ };
731
+ var escapeToBuffer = (str, buffer) => {
732
+ const match = str.search(escapeRe);
733
+ if (match === -1) {
734
+ buffer[0] += str;
735
+ return;
736
+ }
737
+ let escape;
738
+ let index;
739
+ let lastIndex = 0;
740
+ for (index = match;index < str.length; index++) {
741
+ switch (str.charCodeAt(index)) {
742
+ case 34:
743
+ escape = "&quot;";
744
+ break;
745
+ case 39:
746
+ escape = "&#39;";
747
+ break;
748
+ case 38:
749
+ escape = "&amp;";
750
+ break;
751
+ case 60:
752
+ escape = "&lt;";
753
+ break;
754
+ case 62:
755
+ escape = "&gt;";
756
+ break;
757
+ default:
758
+ continue;
759
+ }
760
+ buffer[0] += str.substring(lastIndex, index) + escape;
761
+ lastIndex = index + 1;
762
+ }
763
+ buffer[0] += str.substring(lastIndex, index);
764
+ };
765
+ var resolveCallbackSync = (str) => {
766
+ const callbacks = str.callbacks;
767
+ if (!callbacks?.length) {
768
+ return str;
769
+ }
770
+ const buffer = [str];
771
+ const context = {};
772
+ callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));
773
+ return buffer[0];
774
+ };
775
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
776
+ if (typeof str === "object" && !(str instanceof String)) {
777
+ if (!(str instanceof Promise)) {
778
+ str = str.toString();
779
+ }
780
+ if (str instanceof Promise) {
781
+ str = await str;
782
+ }
783
+ }
784
+ const callbacks = str.callbacks;
785
+ if (!callbacks?.length) {
786
+ return Promise.resolve(str);
787
+ }
788
+ if (buffer) {
789
+ buffer[0] += str;
790
+ } else {
791
+ buffer = [str];
792
+ }
793
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
794
+ if (preserveCallbacks) {
795
+ return raw(await resStr, callbacks);
796
+ } else {
797
+ return resStr;
798
+ }
799
+ };
800
+ });
801
+
802
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/context.js
803
+ var require_context = __commonJS((exports, module) => {
804
+ var __defProp2 = Object.defineProperty;
805
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
806
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
807
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
808
+ var __export = (target, all) => {
809
+ for (var name in all)
810
+ __defProp2(target, name, { get: all[name], enumerable: true });
811
+ };
812
+ var __copyProps = (to, from, except, desc) => {
813
+ if (from && typeof from === "object" || typeof from === "function") {
814
+ for (let key of __getOwnPropNames2(from))
815
+ if (!__hasOwnProp2.call(to, key) && key !== except)
816
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
817
+ }
818
+ return to;
819
+ };
820
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
821
+ var context_exports = {};
822
+ __export(context_exports, {
823
+ Context: () => Context,
824
+ TEXT_PLAIN: () => TEXT_PLAIN
825
+ });
826
+ module.exports = __toCommonJS(context_exports);
827
+ var import_request = require_request();
828
+ var import_html = require_html();
829
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
830
+ var setDefaultContentType = (contentType, headers) => {
831
+ return {
832
+ "Content-Type": contentType,
833
+ ...headers
834
+ };
835
+ };
836
+
837
+ class Context {
838
+ #rawRequest;
839
+ #req;
840
+ env = {};
841
+ #var;
842
+ finalized = false;
843
+ error;
844
+ #status;
845
+ #executionCtx;
846
+ #res;
847
+ #layout;
848
+ #renderer;
849
+ #notFoundHandler;
850
+ #preparedHeaders;
851
+ #matchResult;
852
+ #path;
853
+ constructor(req, options) {
854
+ this.#rawRequest = req;
855
+ if (options) {
856
+ this.#executionCtx = options.executionCtx;
857
+ this.env = options.env;
858
+ this.#notFoundHandler = options.notFoundHandler;
859
+ this.#path = options.path;
860
+ this.#matchResult = options.matchResult;
861
+ }
862
+ }
863
+ get req() {
864
+ this.#req ??= new import_request.HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
865
+ return this.#req;
866
+ }
867
+ get event() {
868
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
869
+ return this.#executionCtx;
870
+ } else {
871
+ throw Error("This context has no FetchEvent");
872
+ }
873
+ }
874
+ get executionCtx() {
875
+ if (this.#executionCtx) {
876
+ return this.#executionCtx;
877
+ } else {
878
+ throw Error("This context has no ExecutionContext");
879
+ }
880
+ }
881
+ get res() {
882
+ return this.#res ||= new Response(null, {
883
+ headers: this.#preparedHeaders ??= new Headers
884
+ });
885
+ }
886
+ set res(_res) {
887
+ if (this.#res && _res) {
888
+ _res = new Response(_res.body, _res);
889
+ for (const [k, v] of this.#res.headers.entries()) {
890
+ if (k === "content-type") {
891
+ continue;
892
+ }
893
+ if (k === "set-cookie") {
894
+ const cookies = this.#res.headers.getSetCookie();
895
+ _res.headers.delete("set-cookie");
896
+ for (const cookie of cookies) {
897
+ _res.headers.append("set-cookie", cookie);
898
+ }
899
+ } else {
900
+ _res.headers.set(k, v);
901
+ }
902
+ }
903
+ }
904
+ this.#res = _res;
905
+ this.finalized = true;
906
+ }
907
+ render = (...args) => {
908
+ this.#renderer ??= (content) => this.html(content);
909
+ return this.#renderer(...args);
910
+ };
911
+ setLayout = (layout) => this.#layout = layout;
912
+ getLayout = () => this.#layout;
913
+ setRenderer = (renderer) => {
914
+ this.#renderer = renderer;
915
+ };
916
+ header = (name, value, options) => {
917
+ if (this.finalized) {
918
+ this.#res = new Response(this.#res.body, this.#res);
919
+ }
920
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
921
+ if (value === undefined) {
922
+ headers.delete(name);
923
+ } else if (options?.append) {
924
+ headers.append(name, value);
925
+ } else {
926
+ headers.set(name, value);
927
+ }
928
+ };
929
+ status = (status) => {
930
+ this.#status = status;
931
+ };
932
+ set = (key, value) => {
933
+ this.#var ??= /* @__PURE__ */ new Map;
934
+ this.#var.set(key, value);
935
+ };
936
+ get = (key) => {
937
+ return this.#var ? this.#var.get(key) : undefined;
938
+ };
939
+ get var() {
940
+ if (!this.#var) {
941
+ return {};
942
+ }
943
+ return Object.fromEntries(this.#var);
944
+ }
945
+ #newResponse(data, arg, headers) {
946
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
947
+ if (typeof arg === "object" && "headers" in arg) {
948
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
949
+ for (const [key, value] of argHeaders) {
950
+ if (key.toLowerCase() === "set-cookie") {
951
+ responseHeaders.append(key, value);
952
+ } else {
953
+ responseHeaders.set(key, value);
954
+ }
955
+ }
956
+ }
957
+ if (headers) {
958
+ for (const [k, v] of Object.entries(headers)) {
959
+ if (typeof v === "string") {
960
+ responseHeaders.set(k, v);
961
+ } else {
962
+ responseHeaders.delete(k);
963
+ for (const v2 of v) {
964
+ responseHeaders.append(k, v2);
965
+ }
966
+ }
967
+ }
968
+ }
969
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
970
+ return new Response(data, { status, headers: responseHeaders });
971
+ }
972
+ newResponse = (...args) => this.#newResponse(...args);
973
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
974
+ text = (text, arg, headers) => {
975
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
976
+ };
977
+ json = (object, arg, headers) => {
978
+ return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
979
+ };
980
+ html = (html, arg, headers) => {
981
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
982
+ return typeof html === "object" ? (0, import_html.resolveCallback)(html, import_html.HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
983
+ };
984
+ redirect = (location, status) => {
985
+ const locationString = String(location);
986
+ this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
987
+ return this.newResponse(null, status ?? 302);
988
+ };
989
+ notFound = () => {
990
+ this.#notFoundHandler ??= () => new Response;
991
+ return this.#notFoundHandler(this);
992
+ };
993
+ }
994
+ });
995
+
996
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router.js
997
+ var require_router = __commonJS((exports, module) => {
998
+ var __defProp2 = Object.defineProperty;
999
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1000
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1001
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1002
+ var __export = (target, all) => {
1003
+ for (var name in all)
1004
+ __defProp2(target, name, { get: all[name], enumerable: true });
1005
+ };
1006
+ var __copyProps = (to, from, except, desc) => {
1007
+ if (from && typeof from === "object" || typeof from === "function") {
1008
+ for (let key of __getOwnPropNames2(from))
1009
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1010
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1011
+ }
1012
+ return to;
1013
+ };
1014
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1015
+ var router_exports = {};
1016
+ __export(router_exports, {
1017
+ MESSAGE_MATCHER_IS_ALREADY_BUILT: () => MESSAGE_MATCHER_IS_ALREADY_BUILT,
1018
+ METHODS: () => METHODS,
1019
+ METHOD_NAME_ALL: () => METHOD_NAME_ALL,
1020
+ METHOD_NAME_ALL_LOWERCASE: () => METHOD_NAME_ALL_LOWERCASE,
1021
+ UnsupportedPathError: () => UnsupportedPathError
1022
+ });
1023
+ module.exports = __toCommonJS(router_exports);
1024
+ var METHOD_NAME_ALL = "ALL";
1025
+ var METHOD_NAME_ALL_LOWERCASE = "all";
1026
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
1027
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
1028
+
1029
+ class UnsupportedPathError extends Error {
1030
+ }
1031
+ });
1032
+
1033
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/utils/constants.js
1034
+ var require_constants2 = __commonJS((exports, module) => {
1035
+ var __defProp2 = Object.defineProperty;
1036
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1037
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1038
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1039
+ var __export = (target, all) => {
1040
+ for (var name in all)
1041
+ __defProp2(target, name, { get: all[name], enumerable: true });
1042
+ };
1043
+ var __copyProps = (to, from, except, desc) => {
1044
+ if (from && typeof from === "object" || typeof from === "function") {
1045
+ for (let key of __getOwnPropNames2(from))
1046
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1047
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1048
+ }
1049
+ return to;
1050
+ };
1051
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1052
+ var constants_exports = {};
1053
+ __export(constants_exports, {
1054
+ COMPOSED_HANDLER: () => COMPOSED_HANDLER
1055
+ });
1056
+ module.exports = __toCommonJS(constants_exports);
1057
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
1058
+ });
1059
+
1060
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/hono-base.js
1061
+ var require_hono_base = __commonJS((exports, module) => {
1062
+ var __defProp2 = Object.defineProperty;
1063
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1064
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1065
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1066
+ var __export = (target, all) => {
1067
+ for (var name in all)
1068
+ __defProp2(target, name, { get: all[name], enumerable: true });
1069
+ };
1070
+ var __copyProps = (to, from, except, desc) => {
1071
+ if (from && typeof from === "object" || typeof from === "function") {
1072
+ for (let key of __getOwnPropNames2(from))
1073
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1074
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1075
+ }
1076
+ return to;
1077
+ };
1078
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1079
+ var hono_base_exports = {};
1080
+ __export(hono_base_exports, {
1081
+ HonoBase: () => Hono2
1082
+ });
1083
+ module.exports = __toCommonJS(hono_base_exports);
1084
+ var import_compose = require_compose();
1085
+ var import_context = require_context();
1086
+ var import_router = require_router();
1087
+ var import_constants = require_constants2();
1088
+ var import_url = require_url();
1089
+ var notFoundHandler = (c) => {
1090
+ return c.text("404 Not Found", 404);
1091
+ };
1092
+ var errorHandler = (err, c) => {
1093
+ if ("getResponse" in err) {
1094
+ const res = err.getResponse();
1095
+ return c.newResponse(res.body, res);
1096
+ }
1097
+ console.error(err);
1098
+ return c.text("Internal Server Error", 500);
1099
+ };
1100
+
1101
+ class Hono2 {
1102
+ get;
1103
+ post;
1104
+ put;
1105
+ delete;
1106
+ options;
1107
+ patch;
1108
+ all;
1109
+ on;
1110
+ use;
1111
+ router;
1112
+ getPath;
1113
+ _basePath = "/";
1114
+ #path = "/";
1115
+ routes = [];
1116
+ constructor(options = {}) {
1117
+ const allMethods = [...import_router.METHODS, import_router.METHOD_NAME_ALL_LOWERCASE];
1118
+ allMethods.forEach((method) => {
1119
+ this[method] = (args1, ...args) => {
1120
+ if (typeof args1 === "string") {
1121
+ this.#path = args1;
1122
+ } else {
1123
+ this.#addRoute(method, this.#path, args1);
1124
+ }
1125
+ args.forEach((handler) => {
1126
+ this.#addRoute(method, this.#path, handler);
1127
+ });
1128
+ return this;
1129
+ };
1130
+ });
1131
+ this.on = (method, path, ...handlers) => {
1132
+ for (const p of [path].flat()) {
1133
+ this.#path = p;
1134
+ for (const m of [method].flat()) {
1135
+ handlers.map((handler) => {
1136
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
1137
+ });
1138
+ }
1139
+ }
1140
+ return this;
1141
+ };
1142
+ this.use = (arg1, ...handlers) => {
1143
+ if (typeof arg1 === "string") {
1144
+ this.#path = arg1;
1145
+ } else {
1146
+ this.#path = "*";
1147
+ handlers.unshift(arg1);
1148
+ }
1149
+ handlers.forEach((handler) => {
1150
+ this.#addRoute(import_router.METHOD_NAME_ALL, this.#path, handler);
1151
+ });
1152
+ return this;
1153
+ };
1154
+ const { strict, ...optionsWithoutStrict } = options;
1155
+ Object.assign(this, optionsWithoutStrict);
1156
+ this.getPath = strict ?? true ? options.getPath ?? import_url.getPath : import_url.getPathNoStrict;
1157
+ }
1158
+ #clone() {
1159
+ const clone = new Hono2({
1160
+ router: this.router,
1161
+ getPath: this.getPath
1162
+ });
1163
+ clone.errorHandler = this.errorHandler;
1164
+ clone.#notFoundHandler = this.#notFoundHandler;
1165
+ clone.routes = this.routes;
1166
+ return clone;
1167
+ }
1168
+ #notFoundHandler = notFoundHandler;
1169
+ errorHandler = errorHandler;
1170
+ route(path, app) {
1171
+ const subApp = this.basePath(path);
1172
+ app.routes.map((r) => {
1173
+ let handler;
1174
+ if (app.errorHandler === errorHandler) {
1175
+ handler = r.handler;
1176
+ } else {
1177
+ handler = async (c, next) => (await (0, import_compose.compose)([], app.errorHandler)(c, () => r.handler(c, next))).res;
1178
+ handler[import_constants.COMPOSED_HANDLER] = r.handler;
1179
+ }
1180
+ subApp.#addRoute(r.method, r.path, handler);
1181
+ });
1182
+ return this;
1183
+ }
1184
+ basePath(path) {
1185
+ const subApp = this.#clone();
1186
+ subApp._basePath = (0, import_url.mergePath)(this._basePath, path);
1187
+ return subApp;
1188
+ }
1189
+ onError = (handler) => {
1190
+ this.errorHandler = handler;
1191
+ return this;
1192
+ };
1193
+ notFound = (handler) => {
1194
+ this.#notFoundHandler = handler;
1195
+ return this;
1196
+ };
1197
+ mount(path, applicationHandler, options) {
1198
+ let replaceRequest;
1199
+ let optionHandler;
1200
+ if (options) {
1201
+ if (typeof options === "function") {
1202
+ optionHandler = options;
1203
+ } else {
1204
+ optionHandler = options.optionHandler;
1205
+ if (options.replaceRequest === false) {
1206
+ replaceRequest = (request) => request;
1207
+ } else {
1208
+ replaceRequest = options.replaceRequest;
1209
+ }
1210
+ }
1211
+ }
1212
+ const getOptions = optionHandler ? (c) => {
1213
+ const options2 = optionHandler(c);
1214
+ return Array.isArray(options2) ? options2 : [options2];
1215
+ } : (c) => {
1216
+ let executionContext = undefined;
1217
+ try {
1218
+ executionContext = c.executionCtx;
1219
+ } catch {}
1220
+ return [c.env, executionContext];
1221
+ };
1222
+ replaceRequest ||= (() => {
1223
+ const mergedPath = (0, import_url.mergePath)(this._basePath, path);
1224
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1225
+ return (request) => {
1226
+ const url = new URL(request.url);
1227
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
1228
+ return new Request(url, request);
1229
+ };
1230
+ })();
1231
+ const handler = async (c, next) => {
1232
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1233
+ if (res) {
1234
+ return res;
1235
+ }
1236
+ await next();
1237
+ };
1238
+ this.#addRoute(import_router.METHOD_NAME_ALL, (0, import_url.mergePath)(path, "*"), handler);
1239
+ return this;
1240
+ }
1241
+ #addRoute(method, path, handler) {
1242
+ method = method.toUpperCase();
1243
+ path = (0, import_url.mergePath)(this._basePath, path);
1244
+ const r = { basePath: this._basePath, path, method, handler };
1245
+ this.router.add(method, path, [handler, r]);
1246
+ this.routes.push(r);
1247
+ }
1248
+ #handleError(err, c) {
1249
+ if (err instanceof Error) {
1250
+ return this.errorHandler(err, c);
1251
+ }
1252
+ throw err;
1253
+ }
1254
+ #dispatch(request, executionCtx, env, method) {
1255
+ if (method === "HEAD") {
1256
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1257
+ }
1258
+ const path = this.getPath(request, { env });
1259
+ const matchResult = this.router.match(method, path);
1260
+ const c = new import_context.Context(request, {
1261
+ path,
1262
+ matchResult,
1263
+ env,
1264
+ executionCtx,
1265
+ notFoundHandler: this.#notFoundHandler
1266
+ });
1267
+ if (matchResult[0].length === 1) {
1268
+ let res;
1269
+ try {
1270
+ res = matchResult[0][0][0][0](c, async () => {
1271
+ c.res = await this.#notFoundHandler(c);
1272
+ });
1273
+ } catch (err) {
1274
+ return this.#handleError(err, c);
1275
+ }
1276
+ return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
1277
+ }
1278
+ const composed = (0, import_compose.compose)(matchResult[0], this.errorHandler, this.#notFoundHandler);
1279
+ return (async () => {
1280
+ try {
1281
+ const context = await composed(c);
1282
+ if (!context.finalized) {
1283
+ throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
1284
+ }
1285
+ return context.res;
1286
+ } catch (err) {
1287
+ return this.#handleError(err, c);
1288
+ }
1289
+ })();
1290
+ }
1291
+ fetch = (request, ...rest) => {
1292
+ return this.#dispatch(request, rest[1], rest[0], request.method);
1293
+ };
1294
+ request = (input, requestInit, Env, executionCtx) => {
1295
+ if (input instanceof Request) {
1296
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
1297
+ }
1298
+ input = input.toString();
1299
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${(0, import_url.mergePath)("/", input)}`, requestInit), Env, executionCtx);
1300
+ };
1301
+ fire = () => {
1302
+ addEventListener("fetch", (event) => {
1303
+ event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
1304
+ });
1305
+ };
1306
+ }
1307
+ });
1308
+
1309
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/reg-exp-router/matcher.js
1310
+ var require_matcher = __commonJS((exports, module) => {
1311
+ var __defProp2 = Object.defineProperty;
1312
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1313
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1314
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1315
+ var __export = (target, all) => {
1316
+ for (var name in all)
1317
+ __defProp2(target, name, { get: all[name], enumerable: true });
1318
+ };
1319
+ var __copyProps = (to, from, except, desc) => {
1320
+ if (from && typeof from === "object" || typeof from === "function") {
1321
+ for (let key of __getOwnPropNames2(from))
1322
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1323
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1324
+ }
1325
+ return to;
1326
+ };
1327
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1328
+ var matcher_exports = {};
1329
+ __export(matcher_exports, {
1330
+ emptyParam: () => emptyParam,
1331
+ match: () => match
1332
+ });
1333
+ module.exports = __toCommonJS(matcher_exports);
1334
+ var import_router = require_router();
1335
+ var emptyParam = [];
1336
+ function match(method, path) {
1337
+ const matchers = this.buildAllMatchers();
1338
+ const match2 = (method2, path2) => {
1339
+ const matcher = matchers[method2] || matchers[import_router.METHOD_NAME_ALL];
1340
+ const staticMatch = matcher[2][path2];
1341
+ if (staticMatch) {
1342
+ return staticMatch;
1343
+ }
1344
+ const match3 = path2.match(matcher[0]);
1345
+ if (!match3) {
1346
+ return [[], emptyParam];
1347
+ }
1348
+ const index = match3.indexOf("", 1);
1349
+ return [matcher[1][index], match3];
1350
+ };
1351
+ this.match = match2;
1352
+ return match2(method, path);
1353
+ }
1354
+ });
1355
+
1356
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/reg-exp-router/node.js
1357
+ var require_node = __commonJS((exports, module) => {
1358
+ var __defProp2 = Object.defineProperty;
1359
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1360
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1361
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1362
+ var __export = (target, all) => {
1363
+ for (var name in all)
1364
+ __defProp2(target, name, { get: all[name], enumerable: true });
1365
+ };
1366
+ var __copyProps = (to, from, except, desc) => {
1367
+ if (from && typeof from === "object" || typeof from === "function") {
1368
+ for (let key of __getOwnPropNames2(from))
1369
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1370
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1371
+ }
1372
+ return to;
1373
+ };
1374
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1375
+ var node_exports = {};
1376
+ __export(node_exports, {
1377
+ Node: () => Node,
1378
+ PATH_ERROR: () => PATH_ERROR
1379
+ });
1380
+ module.exports = __toCommonJS(node_exports);
1381
+ var LABEL_REG_EXP_STR = "[^/]+";
1382
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
1383
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
1384
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
1385
+ var regExpMetaChars = new Set(".\\+*[^]$()");
1386
+ function compareKey(a, b) {
1387
+ if (a.length === 1) {
1388
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
1389
+ }
1390
+ if (b.length === 1) {
1391
+ return 1;
1392
+ }
1393
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
1394
+ return 1;
1395
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
1396
+ return -1;
1397
+ }
1398
+ if (a === LABEL_REG_EXP_STR) {
1399
+ return 1;
1400
+ } else if (b === LABEL_REG_EXP_STR) {
1401
+ return -1;
1402
+ }
1403
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
1404
+ }
1405
+
1406
+ class Node {
1407
+ #index;
1408
+ #varIndex;
1409
+ #children = /* @__PURE__ */ Object.create(null);
1410
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
1411
+ if (tokens.length === 0) {
1412
+ if (this.#index !== undefined) {
1413
+ throw PATH_ERROR;
1414
+ }
1415
+ if (pathErrorCheckOnly) {
1416
+ return;
1417
+ }
1418
+ this.#index = index;
1419
+ return;
1420
+ }
1421
+ const [token, ...restTokens] = tokens;
1422
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1423
+ let node;
1424
+ if (pattern) {
1425
+ const name = pattern[1];
1426
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
1427
+ if (name && pattern[2]) {
1428
+ if (regexpStr === ".*") {
1429
+ throw PATH_ERROR;
1430
+ }
1431
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
1432
+ if (/\((?!\?:)/.test(regexpStr)) {
1433
+ throw PATH_ERROR;
1434
+ }
1435
+ }
1436
+ node = this.#children[regexpStr];
1437
+ if (!node) {
1438
+ if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
1439
+ throw PATH_ERROR;
1440
+ }
1441
+ if (pathErrorCheckOnly) {
1442
+ return;
1443
+ }
1444
+ node = this.#children[regexpStr] = new Node;
1445
+ if (name !== "") {
1446
+ node.#varIndex = context.varIndex++;
1447
+ }
1448
+ }
1449
+ if (!pathErrorCheckOnly && name !== "") {
1450
+ paramMap.push([name, node.#varIndex]);
1451
+ }
1452
+ } else {
1453
+ node = this.#children[token];
1454
+ if (!node) {
1455
+ if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
1456
+ throw PATH_ERROR;
1457
+ }
1458
+ if (pathErrorCheckOnly) {
1459
+ return;
1460
+ }
1461
+ node = this.#children[token] = new Node;
1462
+ }
1463
+ }
1464
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
1465
+ }
1466
+ buildRegExpStr() {
1467
+ const childKeys = Object.keys(this.#children).sort(compareKey);
1468
+ const strList = childKeys.map((k) => {
1469
+ const c = this.#children[k];
1470
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
1471
+ });
1472
+ if (typeof this.#index === "number") {
1473
+ strList.unshift(`#${this.#index}`);
1474
+ }
1475
+ if (strList.length === 0) {
1476
+ return "";
1477
+ }
1478
+ if (strList.length === 1) {
1479
+ return strList[0];
1480
+ }
1481
+ return "(?:" + strList.join("|") + ")";
1482
+ }
1483
+ }
1484
+ });
1485
+
1486
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/reg-exp-router/trie.js
1487
+ var require_trie = __commonJS((exports, module) => {
1488
+ var __defProp2 = Object.defineProperty;
1489
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1490
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1491
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1492
+ var __export = (target, all) => {
1493
+ for (var name in all)
1494
+ __defProp2(target, name, { get: all[name], enumerable: true });
1495
+ };
1496
+ var __copyProps = (to, from, except, desc) => {
1497
+ if (from && typeof from === "object" || typeof from === "function") {
1498
+ for (let key of __getOwnPropNames2(from))
1499
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1500
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1501
+ }
1502
+ return to;
1503
+ };
1504
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1505
+ var trie_exports = {};
1506
+ __export(trie_exports, {
1507
+ Trie: () => Trie
1508
+ });
1509
+ module.exports = __toCommonJS(trie_exports);
1510
+ var import_node = require_node();
1511
+
1512
+ class Trie {
1513
+ #context = { varIndex: 0 };
1514
+ #root = new import_node.Node;
1515
+ insert(path, index, pathErrorCheckOnly) {
1516
+ const paramAssoc = [];
1517
+ const groups = [];
1518
+ for (let i = 0;; ) {
1519
+ let replaced = false;
1520
+ path = path.replace(/\{[^}]+\}/g, (m) => {
1521
+ const mark = `@\\${i}`;
1522
+ groups[i] = [mark, m];
1523
+ i++;
1524
+ replaced = true;
1525
+ return mark;
1526
+ });
1527
+ if (!replaced) {
1528
+ break;
1529
+ }
1530
+ }
1531
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1532
+ for (let i = groups.length - 1;i >= 0; i--) {
1533
+ const [mark] = groups[i];
1534
+ for (let j = tokens.length - 1;j >= 0; j--) {
1535
+ if (tokens[j].indexOf(mark) !== -1) {
1536
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
1537
+ break;
1538
+ }
1539
+ }
1540
+ }
1541
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
1542
+ return paramAssoc;
1543
+ }
1544
+ buildRegExp() {
1545
+ let regexp = this.#root.buildRegExpStr();
1546
+ if (regexp === "") {
1547
+ return [/^$/, [], []];
1548
+ }
1549
+ let captureIndex = 0;
1550
+ const indexReplacementMap = [];
1551
+ const paramReplacementMap = [];
1552
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1553
+ if (handlerIndex !== undefined) {
1554
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
1555
+ return "$()";
1556
+ }
1557
+ if (paramIndex !== undefined) {
1558
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1559
+ return "";
1560
+ }
1561
+ return "";
1562
+ });
1563
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
1564
+ }
1565
+ }
1566
+ });
1567
+
1568
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/reg-exp-router/router.js
1569
+ var require_router2 = __commonJS((exports, module) => {
1570
+ var __defProp2 = Object.defineProperty;
1571
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1572
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1573
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1574
+ var __export = (target, all) => {
1575
+ for (var name in all)
1576
+ __defProp2(target, name, { get: all[name], enumerable: true });
1577
+ };
1578
+ var __copyProps = (to, from, except, desc) => {
1579
+ if (from && typeof from === "object" || typeof from === "function") {
1580
+ for (let key of __getOwnPropNames2(from))
1581
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1582
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1583
+ }
1584
+ return to;
1585
+ };
1586
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1587
+ var router_exports = {};
1588
+ __export(router_exports, {
1589
+ RegExpRouter: () => RegExpRouter2
1590
+ });
1591
+ module.exports = __toCommonJS(router_exports);
1592
+ var import_router = require_router();
1593
+ var import_url = require_url();
1594
+ var import_matcher = require_matcher();
1595
+ var import_node = require_node();
1596
+ var import_trie = require_trie();
1597
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
1598
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1599
+ function buildWildcardRegExp(path) {
1600
+ return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
1601
+ }
1602
+ function clearWildcardRegExpCache() {
1603
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1604
+ }
1605
+ function buildMatcherFromPreprocessedRoutes(routes) {
1606
+ const trie = new import_trie.Trie;
1607
+ const handlerData = [];
1608
+ if (routes.length === 0) {
1609
+ return nullMatcher;
1610
+ }
1611
+ const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
1612
+ const staticMap = /* @__PURE__ */ Object.create(null);
1613
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
1614
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
1615
+ if (pathErrorCheckOnly) {
1616
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), import_matcher.emptyParam];
1617
+ } else {
1618
+ j++;
1619
+ }
1620
+ let paramAssoc;
1621
+ try {
1622
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
1623
+ } catch (e) {
1624
+ throw e === import_node.PATH_ERROR ? new import_router.UnsupportedPathError(path) : e;
1625
+ }
1626
+ if (pathErrorCheckOnly) {
1627
+ continue;
1628
+ }
1629
+ handlerData[j] = handlers.map(([h, paramCount]) => {
1630
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
1631
+ paramCount -= 1;
1632
+ for (;paramCount >= 0; paramCount--) {
1633
+ const [key, value] = paramAssoc[paramCount];
1634
+ paramIndexMap[key] = value;
1635
+ }
1636
+ return [h, paramIndexMap];
1637
+ });
1638
+ }
1639
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1640
+ for (let i = 0, len = handlerData.length;i < len; i++) {
1641
+ for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
1642
+ const map = handlerData[i][j]?.[1];
1643
+ if (!map) {
1644
+ continue;
1645
+ }
1646
+ const keys = Object.keys(map);
1647
+ for (let k = 0, len3 = keys.length;k < len3; k++) {
1648
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
1649
+ }
1650
+ }
1651
+ }
1652
+ const handlerMap = [];
1653
+ for (const i in indexReplacementMap) {
1654
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
1655
+ }
1656
+ return [regexp, handlerMap, staticMap];
1657
+ }
1658
+ function findMiddleware(middleware, path) {
1659
+ if (!middleware) {
1660
+ return;
1661
+ }
1662
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1663
+ if (buildWildcardRegExp(k).test(path)) {
1664
+ return [...middleware[k]];
1665
+ }
1666
+ }
1667
+ return;
1668
+ }
1669
+
1670
+ class RegExpRouter2 {
1671
+ name = "RegExpRouter";
1672
+ #middleware;
1673
+ #routes;
1674
+ constructor() {
1675
+ this.#middleware = { [import_router.METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1676
+ this.#routes = { [import_router.METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1677
+ }
1678
+ add(method, path, handler) {
1679
+ const middleware = this.#middleware;
1680
+ const routes = this.#routes;
1681
+ if (!middleware || !routes) {
1682
+ throw new Error(import_router.MESSAGE_MATCHER_IS_ALREADY_BUILT);
1683
+ }
1684
+ if (!middleware[method]) {
1685
+ [middleware, routes].forEach((handlerMap) => {
1686
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
1687
+ Object.keys(handlerMap[import_router.METHOD_NAME_ALL]).forEach((p) => {
1688
+ handlerMap[method][p] = [...handlerMap[import_router.METHOD_NAME_ALL][p]];
1689
+ });
1690
+ });
1691
+ }
1692
+ if (path === "/*") {
1693
+ path = "*";
1694
+ }
1695
+ const paramCount = (path.match(/\/:/g) || []).length;
1696
+ if (/\*$/.test(path)) {
1697
+ const re = buildWildcardRegExp(path);
1698
+ if (method === import_router.METHOD_NAME_ALL) {
1699
+ Object.keys(middleware).forEach((m) => {
1700
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[import_router.METHOD_NAME_ALL], path) || [];
1701
+ });
1702
+ } else {
1703
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[import_router.METHOD_NAME_ALL], path) || [];
1704
+ }
1705
+ Object.keys(middleware).forEach((m) => {
1706
+ if (method === import_router.METHOD_NAME_ALL || method === m) {
1707
+ Object.keys(middleware[m]).forEach((p) => {
1708
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
1709
+ });
1710
+ }
1711
+ });
1712
+ Object.keys(routes).forEach((m) => {
1713
+ if (method === import_router.METHOD_NAME_ALL || method === m) {
1714
+ Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
1715
+ }
1716
+ });
1717
+ return;
1718
+ }
1719
+ const paths = (0, import_url.checkOptionalParameter)(path) || [path];
1720
+ for (let i = 0, len = paths.length;i < len; i++) {
1721
+ const path2 = paths[i];
1722
+ Object.keys(routes).forEach((m) => {
1723
+ if (method === import_router.METHOD_NAME_ALL || method === m) {
1724
+ routes[m][path2] ||= [
1725
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[import_router.METHOD_NAME_ALL], path2) || []
1726
+ ];
1727
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
1728
+ }
1729
+ });
1730
+ }
1731
+ }
1732
+ match = import_matcher.match;
1733
+ buildAllMatchers() {
1734
+ const matchers = /* @__PURE__ */ Object.create(null);
1735
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
1736
+ matchers[method] ||= this.#buildMatcher(method);
1737
+ });
1738
+ this.#middleware = this.#routes = undefined;
1739
+ clearWildcardRegExpCache();
1740
+ return matchers;
1741
+ }
1742
+ #buildMatcher(method) {
1743
+ const routes = [];
1744
+ let hasOwnRoute = method === import_router.METHOD_NAME_ALL;
1745
+ [this.#middleware, this.#routes].forEach((r) => {
1746
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
1747
+ if (ownRoute.length !== 0) {
1748
+ hasOwnRoute ||= true;
1749
+ routes.push(...ownRoute);
1750
+ } else if (method !== import_router.METHOD_NAME_ALL) {
1751
+ routes.push(...Object.keys(r[import_router.METHOD_NAME_ALL]).map((path) => [path, r[import_router.METHOD_NAME_ALL][path]]));
1752
+ }
1753
+ });
1754
+ if (!hasOwnRoute) {
1755
+ return null;
1756
+ } else {
1757
+ return buildMatcherFromPreprocessedRoutes(routes);
1758
+ }
1759
+ }
1760
+ }
1761
+ });
1762
+
1763
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/reg-exp-router/prepared-router.js
1764
+ var require_prepared_router = __commonJS((exports, module) => {
1765
+ var __defProp2 = Object.defineProperty;
1766
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1767
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1768
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1769
+ var __export = (target, all) => {
1770
+ for (var name in all)
1771
+ __defProp2(target, name, { get: all[name], enumerable: true });
1772
+ };
1773
+ var __copyProps = (to, from, except, desc) => {
1774
+ if (from && typeof from === "object" || typeof from === "function") {
1775
+ for (let key of __getOwnPropNames2(from))
1776
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1777
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1778
+ }
1779
+ return to;
1780
+ };
1781
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1782
+ var prepared_router_exports = {};
1783
+ __export(prepared_router_exports, {
1784
+ PreparedRegExpRouter: () => PreparedRegExpRouter2,
1785
+ buildInitParams: () => buildInitParams2,
1786
+ serializeInitParams: () => serializeInitParams2
1787
+ });
1788
+ module.exports = __toCommonJS(prepared_router_exports);
1789
+ var import_router = require_router();
1790
+ var import_matcher = require_matcher();
1791
+ var import_router2 = require_router2();
1792
+
1793
+ class PreparedRegExpRouter2 {
1794
+ name = "PreparedRegExpRouter";
1795
+ #matchers;
1796
+ #relocateMap;
1797
+ constructor(matchers, relocateMap) {
1798
+ this.#matchers = matchers;
1799
+ this.#relocateMap = relocateMap;
1800
+ }
1801
+ #addWildcard(method, handlerData) {
1802
+ const matcher = this.#matchers[method];
1803
+ matcher[1].forEach((list) => list && list.push(handlerData));
1804
+ Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
1805
+ }
1806
+ #addPath(method, path, handler, indexes, map) {
1807
+ const matcher = this.#matchers[method];
1808
+ if (!map) {
1809
+ matcher[2][path][0].push([handler, {}]);
1810
+ } else {
1811
+ indexes.forEach((index) => {
1812
+ if (typeof index === "number") {
1813
+ matcher[1][index].push([handler, map]);
1814
+ } else {
1815
+ matcher[2][index || path][0].push([handler, map]);
1816
+ }
1817
+ });
1818
+ }
1819
+ }
1820
+ add(method, path, handler) {
1821
+ if (!this.#matchers[method]) {
1822
+ const all = this.#matchers[import_router.METHOD_NAME_ALL];
1823
+ const staticMap = {};
1824
+ for (const key in all[2]) {
1825
+ staticMap[key] = [all[2][key][0].slice(), import_matcher.emptyParam];
1826
+ }
1827
+ this.#matchers[method] = [
1828
+ all[0],
1829
+ all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
1830
+ staticMap
1831
+ ];
1832
+ }
1833
+ if (path === "/*" || path === "*") {
1834
+ const handlerData = [handler, {}];
1835
+ if (method === import_router.METHOD_NAME_ALL) {
1836
+ for (const m in this.#matchers) {
1837
+ this.#addWildcard(m, handlerData);
1838
+ }
1839
+ } else {
1840
+ this.#addWildcard(method, handlerData);
1841
+ }
1842
+ return;
1843
+ }
1844
+ const data = this.#relocateMap[path];
1845
+ if (!data) {
1846
+ throw new Error(`Path ${path} is not registered`);
1847
+ }
1848
+ for (const [indexes, map] of data) {
1849
+ if (method === import_router.METHOD_NAME_ALL) {
1850
+ for (const m in this.#matchers) {
1851
+ this.#addPath(m, path, handler, indexes, map);
1852
+ }
1853
+ } else {
1854
+ this.#addPath(method, path, handler, indexes, map);
1855
+ }
1856
+ }
1857
+ }
1858
+ buildAllMatchers() {
1859
+ return this.#matchers;
1860
+ }
1861
+ match = import_matcher.match;
1862
+ }
1863
+ var buildInitParams2 = ({ paths }) => {
1864
+ const RegExpRouterWithMatcherExport = class extends import_router2.RegExpRouter {
1865
+ buildAndExportAllMatchers() {
1866
+ return this.buildAllMatchers();
1867
+ }
1868
+ };
1869
+ const router = new RegExpRouterWithMatcherExport;
1870
+ for (const path of paths) {
1871
+ router.add(import_router.METHOD_NAME_ALL, path, path);
1872
+ }
1873
+ const matchers = router.buildAndExportAllMatchers();
1874
+ const all = matchers[import_router.METHOD_NAME_ALL];
1875
+ const relocateMap = {};
1876
+ for (const path of paths) {
1877
+ if (path === "/*" || path === "*") {
1878
+ continue;
1879
+ }
1880
+ all[1].forEach((list, i) => {
1881
+ list.forEach(([p, map]) => {
1882
+ if (p === path) {
1883
+ if (relocateMap[path]) {
1884
+ relocateMap[path][0][1] = {
1885
+ ...relocateMap[path][0][1],
1886
+ ...map
1887
+ };
1888
+ } else {
1889
+ relocateMap[path] = [[[], map]];
1890
+ }
1891
+ if (relocateMap[path][0][0].findIndex((j) => j === i) === -1) {
1892
+ relocateMap[path][0][0].push(i);
1893
+ }
1894
+ }
1895
+ });
1896
+ });
1897
+ for (const path2 in all[2]) {
1898
+ all[2][path2][0].forEach(([p]) => {
1899
+ if (p === path) {
1900
+ relocateMap[path] ||= [[[]]];
1901
+ const value = path2 === path ? "" : path2;
1902
+ if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) {
1903
+ relocateMap[path][0][0].push(value);
1904
+ }
1905
+ }
1906
+ });
1907
+ }
1908
+ }
1909
+ for (let i = 0, len = all[1].length;i < len; i++) {
1910
+ all[1][i] = all[1][i] ? [] : 0;
1911
+ }
1912
+ for (const path in all[2]) {
1913
+ all[2][path][0] = [];
1914
+ }
1915
+ return [matchers, relocateMap];
1916
+ };
1917
+ var serializeInitParams2 = ([matchers, relocateMap]) => {
1918
+ const matchersStr = JSON.stringify(matchers, (_, value) => value instanceof RegExp ? `##${value.toString()}##` : value).replace(/"##(.+?)##"/g, (_, str) => str.replace(/\\\\/g, "\\"));
1919
+ const relocateMapStr = JSON.stringify(relocateMap);
1920
+ return `[${matchersStr},${relocateMapStr}]`;
1921
+ };
1922
+ });
1923
+
1924
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/reg-exp-router/index.js
1925
+ var require_reg_exp_router = __commonJS((exports, module) => {
1926
+ var __defProp2 = Object.defineProperty;
1927
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1928
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1929
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1930
+ var __export = (target, all) => {
1931
+ for (var name in all)
1932
+ __defProp2(target, name, { get: all[name], enumerable: true });
1933
+ };
1934
+ var __copyProps = (to, from, except, desc) => {
1935
+ if (from && typeof from === "object" || typeof from === "function") {
1936
+ for (let key of __getOwnPropNames2(from))
1937
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1938
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1939
+ }
1940
+ return to;
1941
+ };
1942
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1943
+ var reg_exp_router_exports = {};
1944
+ __export(reg_exp_router_exports, {
1945
+ PreparedRegExpRouter: () => import_prepared_router.PreparedRegExpRouter,
1946
+ RegExpRouter: () => import_router.RegExpRouter,
1947
+ buildInitParams: () => import_prepared_router.buildInitParams,
1948
+ serializeInitParams: () => import_prepared_router.serializeInitParams
1949
+ });
1950
+ module.exports = __toCommonJS(reg_exp_router_exports);
1951
+ var import_router = require_router2();
1952
+ var import_prepared_router = require_prepared_router();
1953
+ });
1954
+
1955
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/smart-router/router.js
1956
+ var require_router3 = __commonJS((exports, module) => {
1957
+ var __defProp2 = Object.defineProperty;
1958
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
1959
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
1960
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1961
+ var __export = (target, all) => {
1962
+ for (var name in all)
1963
+ __defProp2(target, name, { get: all[name], enumerable: true });
1964
+ };
1965
+ var __copyProps = (to, from, except, desc) => {
1966
+ if (from && typeof from === "object" || typeof from === "function") {
1967
+ for (let key of __getOwnPropNames2(from))
1968
+ if (!__hasOwnProp2.call(to, key) && key !== except)
1969
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
1970
+ }
1971
+ return to;
1972
+ };
1973
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
1974
+ var router_exports = {};
1975
+ __export(router_exports, {
1976
+ SmartRouter: () => SmartRouter2
1977
+ });
1978
+ module.exports = __toCommonJS(router_exports);
1979
+ var import_router = require_router();
1980
+
1981
+ class SmartRouter2 {
1982
+ name = "SmartRouter";
1983
+ #routers = [];
1984
+ #routes = [];
1985
+ constructor(init) {
1986
+ this.#routers = init.routers;
1987
+ }
1988
+ add(method, path, handler) {
1989
+ if (!this.#routes) {
1990
+ throw new Error(import_router.MESSAGE_MATCHER_IS_ALREADY_BUILT);
1991
+ }
1992
+ this.#routes.push([method, path, handler]);
1993
+ }
1994
+ match(method, path) {
1995
+ if (!this.#routes) {
1996
+ throw new Error("Fatal error");
1997
+ }
1998
+ const routers = this.#routers;
1999
+ const routes = this.#routes;
2000
+ const len = routers.length;
2001
+ let i = 0;
2002
+ let res;
2003
+ for (;i < len; i++) {
2004
+ const router = routers[i];
2005
+ try {
2006
+ for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
2007
+ router.add(...routes[i2]);
2008
+ }
2009
+ res = router.match(method, path);
2010
+ } catch (e) {
2011
+ if (e instanceof import_router.UnsupportedPathError) {
2012
+ continue;
2013
+ }
2014
+ throw e;
2015
+ }
2016
+ this.match = router.match.bind(router);
2017
+ this.#routers = [router];
2018
+ this.#routes = undefined;
2019
+ break;
2020
+ }
2021
+ if (i === len) {
2022
+ throw new Error("Fatal error");
2023
+ }
2024
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
2025
+ return res;
2026
+ }
2027
+ get activeRouter() {
2028
+ if (this.#routes || this.#routers.length !== 1) {
2029
+ throw new Error("No active router has been determined yet.");
2030
+ }
2031
+ return this.#routers[0];
2032
+ }
2033
+ }
2034
+ });
2035
+
2036
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/smart-router/index.js
2037
+ var require_smart_router = __commonJS((exports, module) => {
2038
+ var __defProp2 = Object.defineProperty;
2039
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2040
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
2041
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2042
+ var __export = (target, all) => {
2043
+ for (var name in all)
2044
+ __defProp2(target, name, { get: all[name], enumerable: true });
2045
+ };
2046
+ var __copyProps = (to, from, except, desc) => {
2047
+ if (from && typeof from === "object" || typeof from === "function") {
2048
+ for (let key of __getOwnPropNames2(from))
2049
+ if (!__hasOwnProp2.call(to, key) && key !== except)
2050
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2051
+ }
2052
+ return to;
2053
+ };
2054
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
2055
+ var smart_router_exports = {};
2056
+ __export(smart_router_exports, {
2057
+ SmartRouter: () => import_router.SmartRouter
2058
+ });
2059
+ module.exports = __toCommonJS(smart_router_exports);
2060
+ var import_router = require_router3();
2061
+ });
2062
+
2063
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/trie-router/node.js
2064
+ var require_node2 = __commonJS((exports, module) => {
2065
+ var __defProp2 = Object.defineProperty;
2066
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2067
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
2068
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2069
+ var __export = (target, all) => {
2070
+ for (var name in all)
2071
+ __defProp2(target, name, { get: all[name], enumerable: true });
2072
+ };
2073
+ var __copyProps = (to, from, except, desc) => {
2074
+ if (from && typeof from === "object" || typeof from === "function") {
2075
+ for (let key of __getOwnPropNames2(from))
2076
+ if (!__hasOwnProp2.call(to, key) && key !== except)
2077
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2078
+ }
2079
+ return to;
2080
+ };
2081
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
2082
+ var node_exports = {};
2083
+ __export(node_exports, {
2084
+ Node: () => Node
2085
+ });
2086
+ module.exports = __toCommonJS(node_exports);
2087
+ var import_router = require_router();
2088
+ var import_url = require_url();
2089
+ var emptyParams = /* @__PURE__ */ Object.create(null);
2090
+
2091
+ class Node {
2092
+ #methods;
2093
+ #children;
2094
+ #patterns;
2095
+ #order = 0;
2096
+ #params = emptyParams;
2097
+ constructor(method, handler, children) {
2098
+ this.#children = children || /* @__PURE__ */ Object.create(null);
2099
+ this.#methods = [];
2100
+ if (method && handler) {
2101
+ const m = /* @__PURE__ */ Object.create(null);
2102
+ m[method] = { handler, possibleKeys: [], score: 0 };
2103
+ this.#methods = [m];
2104
+ }
2105
+ this.#patterns = [];
2106
+ }
2107
+ insert(method, path, handler) {
2108
+ this.#order = ++this.#order;
2109
+ let curNode = this;
2110
+ const parts = (0, import_url.splitRoutingPath)(path);
2111
+ const possibleKeys = [];
2112
+ for (let i = 0, len = parts.length;i < len; i++) {
2113
+ const p = parts[i];
2114
+ const nextP = parts[i + 1];
2115
+ const pattern = (0, import_url.getPattern)(p, nextP);
2116
+ const key = Array.isArray(pattern) ? pattern[0] : p;
2117
+ if (key in curNode.#children) {
2118
+ curNode = curNode.#children[key];
2119
+ if (pattern) {
2120
+ possibleKeys.push(pattern[1]);
2121
+ }
2122
+ continue;
2123
+ }
2124
+ curNode.#children[key] = new Node;
2125
+ if (pattern) {
2126
+ curNode.#patterns.push(pattern);
2127
+ possibleKeys.push(pattern[1]);
2128
+ }
2129
+ curNode = curNode.#children[key];
2130
+ }
2131
+ curNode.#methods.push({
2132
+ [method]: {
2133
+ handler,
2134
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
2135
+ score: this.#order
2136
+ }
2137
+ });
2138
+ return curNode;
2139
+ }
2140
+ #getHandlerSets(node, method, nodeParams, params) {
2141
+ const handlerSets = [];
2142
+ for (let i = 0, len = node.#methods.length;i < len; i++) {
2143
+ const m = node.#methods[i];
2144
+ const handlerSet = m[method] || m[import_router.METHOD_NAME_ALL];
2145
+ const processedSet = {};
2146
+ if (handlerSet !== undefined) {
2147
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
2148
+ handlerSets.push(handlerSet);
2149
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
2150
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
2151
+ const key = handlerSet.possibleKeys[i2];
2152
+ const processed = processedSet[handlerSet.score];
2153
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
2154
+ processedSet[handlerSet.score] = true;
2155
+ }
2156
+ }
2157
+ }
2158
+ }
2159
+ return handlerSets;
2160
+ }
2161
+ search(method, path) {
2162
+ const handlerSets = [];
2163
+ this.#params = emptyParams;
2164
+ const curNode = this;
2165
+ let curNodes = [curNode];
2166
+ const parts = (0, import_url.splitPath)(path);
2167
+ const curNodesQueue = [];
2168
+ for (let i = 0, len = parts.length;i < len; i++) {
2169
+ const part = parts[i];
2170
+ const isLast = i === len - 1;
2171
+ const tempNodes = [];
2172
+ for (let j = 0, len2 = curNodes.length;j < len2; j++) {
2173
+ const node = curNodes[j];
2174
+ const nextNode = node.#children[part];
2175
+ if (nextNode) {
2176
+ nextNode.#params = node.#params;
2177
+ if (isLast) {
2178
+ if (nextNode.#children["*"]) {
2179
+ handlerSets.push(...this.#getHandlerSets(nextNode.#children["*"], method, node.#params));
2180
+ }
2181
+ handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
2182
+ } else {
2183
+ tempNodes.push(nextNode);
2184
+ }
2185
+ }
2186
+ for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
2187
+ const pattern = node.#patterns[k];
2188
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
2189
+ if (pattern === "*") {
2190
+ const astNode = node.#children["*"];
2191
+ if (astNode) {
2192
+ handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
2193
+ astNode.#params = params;
2194
+ tempNodes.push(astNode);
2195
+ }
2196
+ continue;
2197
+ }
2198
+ const [key, name, matcher] = pattern;
2199
+ if (!part && !(matcher instanceof RegExp)) {
2200
+ continue;
2201
+ }
2202
+ const child = node.#children[key];
2203
+ const restPathString = parts.slice(i).join("/");
2204
+ if (matcher instanceof RegExp) {
2205
+ const m = matcher.exec(restPathString);
2206
+ if (m) {
2207
+ params[name] = m[0];
2208
+ handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
2209
+ if (Object.keys(child.#children).length) {
2210
+ child.#params = params;
2211
+ const componentCount = m[0].match(/\//)?.length ?? 0;
2212
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
2213
+ targetCurNodes.push(child);
2214
+ }
2215
+ continue;
2216
+ }
2217
+ }
2218
+ if (matcher === true || matcher.test(part)) {
2219
+ params[name] = part;
2220
+ if (isLast) {
2221
+ handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
2222
+ if (child.#children["*"]) {
2223
+ handlerSets.push(...this.#getHandlerSets(child.#children["*"], method, params, node.#params));
2224
+ }
2225
+ } else {
2226
+ child.#params = params;
2227
+ tempNodes.push(child);
2228
+ }
2229
+ }
2230
+ }
2231
+ }
2232
+ curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
2233
+ }
2234
+ if (handlerSets.length > 1) {
2235
+ handlerSets.sort((a, b) => {
2236
+ return a.score - b.score;
2237
+ });
2238
+ }
2239
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
2240
+ }
2241
+ }
2242
+ });
2243
+
2244
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/trie-router/router.js
2245
+ var require_router4 = __commonJS((exports, module) => {
2246
+ var __defProp2 = Object.defineProperty;
2247
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2248
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
2249
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2250
+ var __export = (target, all) => {
2251
+ for (var name in all)
2252
+ __defProp2(target, name, { get: all[name], enumerable: true });
2253
+ };
2254
+ var __copyProps = (to, from, except, desc) => {
2255
+ if (from && typeof from === "object" || typeof from === "function") {
2256
+ for (let key of __getOwnPropNames2(from))
2257
+ if (!__hasOwnProp2.call(to, key) && key !== except)
2258
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2259
+ }
2260
+ return to;
2261
+ };
2262
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
2263
+ var router_exports = {};
2264
+ __export(router_exports, {
2265
+ TrieRouter: () => TrieRouter2
2266
+ });
2267
+ module.exports = __toCommonJS(router_exports);
2268
+ var import_url = require_url();
2269
+ var import_node = require_node2();
2270
+
2271
+ class TrieRouter2 {
2272
+ name = "TrieRouter";
2273
+ #node;
2274
+ constructor() {
2275
+ this.#node = new import_node.Node;
2276
+ }
2277
+ add(method, path, handler) {
2278
+ const results = (0, import_url.checkOptionalParameter)(path);
2279
+ if (results) {
2280
+ for (let i = 0, len = results.length;i < len; i++) {
2281
+ this.#node.insert(method, results[i], handler);
2282
+ }
2283
+ return;
2284
+ }
2285
+ this.#node.insert(method, path, handler);
2286
+ }
2287
+ match(method, path) {
2288
+ return this.#node.search(method, path);
2289
+ }
2290
+ }
2291
+ });
2292
+
2293
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/router/trie-router/index.js
2294
+ var require_trie_router = __commonJS((exports, module) => {
2295
+ var __defProp2 = Object.defineProperty;
2296
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2297
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
2298
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2299
+ var __export = (target, all) => {
2300
+ for (var name in all)
2301
+ __defProp2(target, name, { get: all[name], enumerable: true });
2302
+ };
2303
+ var __copyProps = (to, from, except, desc) => {
2304
+ if (from && typeof from === "object" || typeof from === "function") {
2305
+ for (let key of __getOwnPropNames2(from))
2306
+ if (!__hasOwnProp2.call(to, key) && key !== except)
2307
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2308
+ }
2309
+ return to;
2310
+ };
2311
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
2312
+ var trie_router_exports = {};
2313
+ __export(trie_router_exports, {
2314
+ TrieRouter: () => import_router.TrieRouter
2315
+ });
2316
+ module.exports = __toCommonJS(trie_router_exports);
2317
+ var import_router = require_router4();
2318
+ });
2319
+
2320
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/hono.js
2321
+ var require_hono = __commonJS((exports, module) => {
2322
+ var __defProp2 = Object.defineProperty;
2323
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2324
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
2325
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2326
+ var __export = (target, all) => {
2327
+ for (var name in all)
2328
+ __defProp2(target, name, { get: all[name], enumerable: true });
2329
+ };
2330
+ var __copyProps = (to, from, except, desc) => {
2331
+ if (from && typeof from === "object" || typeof from === "function") {
2332
+ for (let key of __getOwnPropNames2(from))
2333
+ if (!__hasOwnProp2.call(to, key) && key !== except)
2334
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2335
+ }
2336
+ return to;
2337
+ };
2338
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
2339
+ var hono_exports = {};
2340
+ __export(hono_exports, {
2341
+ Hono: () => Hono2
2342
+ });
2343
+ module.exports = __toCommonJS(hono_exports);
2344
+ var import_hono_base = require_hono_base();
2345
+ var import_reg_exp_router = require_reg_exp_router();
2346
+ var import_smart_router = require_smart_router();
2347
+ var import_trie_router = require_trie_router();
2348
+
2349
+ class Hono2 extends import_hono_base.HonoBase {
2350
+ constructor(options = {}) {
2351
+ super(options);
2352
+ this.router = options.router ?? new import_smart_router.SmartRouter({
2353
+ routers: [new import_reg_exp_router.RegExpRouter, new import_trie_router.TrieRouter]
2354
+ });
2355
+ }
2356
+ }
2357
+ });
2358
+
2359
+ // ../../node_modules/.bun/hono@4.11.1/node_modules/hono/dist/cjs/index.js
2360
+ var require_cjs = __commonJS((exports, module) => {
2361
+ var __defProp2 = Object.defineProperty;
2362
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2363
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
2364
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
2365
+ var __export = (target, all) => {
2366
+ for (var name in all)
2367
+ __defProp2(target, name, { get: all[name], enumerable: true });
2368
+ };
2369
+ var __copyProps = (to, from, except, desc) => {
2370
+ if (from && typeof from === "object" || typeof from === "function") {
2371
+ for (let key of __getOwnPropNames2(from))
2372
+ if (!__hasOwnProp2.call(to, key) && key !== except)
2373
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2374
+ }
2375
+ return to;
2376
+ };
2377
+ var __toCommonJS = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod);
2378
+ var index_exports = {};
2379
+ __export(index_exports, {
2380
+ Hono: () => import_hono.Hono
2381
+ });
2382
+ module.exports = __toCommonJS(index_exports);
2383
+ var import_hono = require_hono();
2384
+ });
2385
+ // ../core/package.json
2386
+ var package_default = {
2387
+ name: "gravito-core",
2388
+ version: "1.0.0-beta.2",
2389
+ description: "",
2390
+ module: "./dist/index.mjs",
2391
+ main: "./dist/index.cjs",
2392
+ type: "module",
2393
+ types: "./dist/index.d.ts",
2394
+ exports: {
2395
+ ".": {
2396
+ types: "./dist/index.d.ts",
2397
+ import: "./dist/index.mjs",
2398
+ require: "./dist/index.cjs"
2399
+ },
2400
+ "./compat": {
2401
+ types: "./dist/compat.d.ts",
2402
+ import: "./dist/compat.mjs",
2403
+ require: "./dist/compat.cjs"
2404
+ }
2405
+ },
2406
+ files: [
2407
+ "dist",
2408
+ "README.md",
2409
+ "LICENSE"
2410
+ ],
2411
+ scripts: {
2412
+ build: "bun run build.ts",
2413
+ test: "bun test",
2414
+ "test:coverage": "bun test --coverage",
2415
+ "test:ci": "bun test --coverage --coverage-threshold=100",
2416
+ lint: "biome lint ./src ./tests",
2417
+ "lint:fix": "biome lint --write ./src ./tests",
2418
+ format: "biome format --write ./src ./tests",
2419
+ "format:check": "biome format ./src ./tests",
2420
+ check: "biome check ./src ./tests",
2421
+ "check:fix": "biome check --write ./src ./tests",
2422
+ typecheck: "tsc --noEmit",
2423
+ prepublishOnly: "bun run typecheck && bun run test && bun run build"
2424
+ },
2425
+ keywords: [],
2426
+ author: "Carl Lee <carllee0520@gmail.com>",
2427
+ license: "MIT",
2428
+ repository: {
2429
+ type: "git",
2430
+ url: "git+https://github.com/gravito-framework/gravito.git",
2431
+ directory: "packages/core"
2432
+ },
2433
+ bugs: {
2434
+ url: "https://github.com/gravito-framework/gravito/issues"
2435
+ },
2436
+ homepage: "https://github.com/gravito-framework/gravito#readme",
2437
+ engines: {
2438
+ node: ">=18.0.0"
2439
+ },
2440
+ devDependencies: {
2441
+ "bun-types": "latest",
2442
+ typescript: "^5.9.3"
2443
+ },
2444
+ publishConfig: {
2445
+ access: "public",
2446
+ registry: "https://registry.npmjs.org/"
2447
+ },
2448
+ dependencies: {
2449
+ hono: "^4.11.1"
2450
+ }
2451
+ };
2452
+
2453
+ // ../core/src/adapters/HonoAdapter.ts
2454
+ class HonoRequestWrapper {
2455
+ honoCtx;
2456
+ constructor(honoCtx) {
2457
+ this.honoCtx = honoCtx;
2458
+ }
2459
+ get url() {
2460
+ return this.honoCtx.req.url;
2461
+ }
2462
+ get method() {
2463
+ return this.honoCtx.req.method;
2464
+ }
2465
+ get path() {
2466
+ return this.honoCtx.req.path;
2467
+ }
2468
+ param(name) {
2469
+ return this.honoCtx.req.param(name);
2470
+ }
2471
+ params() {
2472
+ return this.honoCtx.req.param();
2473
+ }
2474
+ query(name) {
2475
+ return this.honoCtx.req.query(name);
2476
+ }
2477
+ queries() {
2478
+ return this.honoCtx.req.queries();
2479
+ }
2480
+ header(name) {
2481
+ if (name) {
2482
+ return this.honoCtx.req.header(name);
2483
+ }
2484
+ return this.honoCtx.req.header();
2485
+ }
2486
+ async json() {
2487
+ return this.honoCtx.req.json();
2488
+ }
2489
+ async text() {
2490
+ return this.honoCtx.req.text();
2491
+ }
2492
+ async formData() {
2493
+ return this.honoCtx.req.formData();
2494
+ }
2495
+ async arrayBuffer() {
2496
+ return this.honoCtx.req.arrayBuffer();
2497
+ }
2498
+ get raw() {
2499
+ return this.honoCtx.req.raw;
2500
+ }
2501
+ valid(target) {
2502
+ return this.honoCtx.req.valid(target);
2503
+ }
2504
+ }
2505
+
2506
+ class HonoContextWrapper {
2507
+ honoCtx;
2508
+ _req;
2509
+ constructor(honoCtx) {
2510
+ this.honoCtx = honoCtx;
2511
+ this._req = new HonoRequestWrapper(honoCtx);
2512
+ }
2513
+ static create(honoCtx) {
2514
+ const instance = new HonoContextWrapper(honoCtx);
2515
+ return new Proxy(instance, {
2516
+ get(target, prop, receiver) {
2517
+ if (prop in target) {
2518
+ const value = Reflect.get(target, prop, receiver);
2519
+ if (typeof value === "function") {
2520
+ return value.bind(target);
2521
+ }
2522
+ return value;
2523
+ }
2524
+ if (typeof prop === "string") {
2525
+ return target.get(prop);
2526
+ }
2527
+ return;
2528
+ }
2529
+ });
2530
+ }
2531
+ get req() {
2532
+ return this._req;
2533
+ }
2534
+ json(data, status) {
2535
+ if (status !== undefined) {
2536
+ return this.honoCtx.json(data, status);
2537
+ }
2538
+ return this.honoCtx.json(data);
2539
+ }
2540
+ text(text, status) {
2541
+ if (status !== undefined) {
2542
+ return this.honoCtx.text(text, status);
2543
+ }
2544
+ return this.honoCtx.text(text);
2545
+ }
2546
+ html(html, status) {
2547
+ if (status !== undefined) {
2548
+ return this.honoCtx.html(html, status);
2549
+ }
2550
+ return this.honoCtx.html(html);
2551
+ }
2552
+ redirect(url, status = 302) {
2553
+ return this.honoCtx.redirect(url, status);
2554
+ }
2555
+ body(data, status) {
2556
+ if (data === null) {
2557
+ return this.honoCtx.body(null, status);
2558
+ }
2559
+ return new Response(data, {
2560
+ status: status ?? 200,
2561
+ headers: new Headers
2562
+ });
2563
+ }
2564
+ stream(stream, status) {
2565
+ return new Response(stream, {
2566
+ status: status ?? 200,
2567
+ headers: {
2568
+ "Content-Type": "application/octet-stream"
2569
+ }
2570
+ });
2571
+ }
2572
+ header(name, value, options) {
2573
+ if (value !== undefined) {
2574
+ if (options?.append) {
2575
+ this.honoCtx.header(name, value, { append: true });
2576
+ } else {
2577
+ this.honoCtx.header(name, value);
2578
+ }
2579
+ return;
2580
+ }
2581
+ return this.honoCtx.req.header(name);
2582
+ }
2583
+ status(code) {
2584
+ this.honoCtx.status(code);
2585
+ }
2586
+ get(key) {
2587
+ return this.honoCtx.get(key);
2588
+ }
2589
+ set(key, value) {
2590
+ this.honoCtx.set(key, value);
2591
+ }
2592
+ get executionCtx() {
2593
+ return this.honoCtx.executionCtx;
2594
+ }
2595
+ get env() {
2596
+ return this.honoCtx.env;
2597
+ }
2598
+ get native() {
2599
+ return this.honoCtx;
2600
+ }
2601
+ }
2602
+ function toHonoMiddleware(middleware) {
2603
+ return async (c, next) => {
2604
+ const ctx = HonoContextWrapper.create(c);
2605
+ const gravitoNext = async () => {
2606
+ await next();
2607
+ };
2608
+ return middleware(ctx, gravitoNext);
2609
+ };
2610
+ }
2611
+ function toHonoErrorHandler(handler) {
2612
+ return async (err, c) => {
2613
+ const ctx = HonoContextWrapper.create(c);
2614
+ return handler(err, ctx);
2615
+ };
2616
+ }
2617
+
2618
+ class HonoAdapter {
2619
+ config;
2620
+ name = "hono";
2621
+ version = "1.0.0";
2622
+ app;
2623
+ constructor(config = {}, honoInstance) {
2624
+ this.config = config;
2625
+ if (honoInstance) {
2626
+ this.app = honoInstance;
2627
+ } else {
2628
+ const { Hono: HonoClass } = require_cjs();
2629
+ this.app = new HonoClass;
2630
+ }
2631
+ }
2632
+ get native() {
2633
+ return this.app;
2634
+ }
2635
+ setNative(app) {
2636
+ this.app = app;
2637
+ }
2638
+ route(method, path, ...handlers) {
2639
+ const fullPath = (this.config.basePath || "") + path;
2640
+ const honoHandlers = handlers.map((h) => toHonoMiddleware(h));
2641
+ const methodFn = this.app[method];
2642
+ if (typeof methodFn !== "function") {
2643
+ throw new Error(`Unsupported HTTP method: ${method}`);
2644
+ }
2645
+ methodFn.call(this.app, fullPath, ...honoHandlers);
2646
+ }
2647
+ routes(routes) {
2648
+ for (const routeDef of routes) {
2649
+ const middlewareHandlers = (routeDef.middleware || []).map((m) => m);
2650
+ const allHandlers = [
2651
+ ...middlewareHandlers,
2652
+ ...routeDef.handlers
2653
+ ];
2654
+ this.route(routeDef.method, routeDef.path, ...allHandlers);
2655
+ }
2656
+ }
2657
+ use(path, ...middleware) {
2658
+ const fullPath = (this.config.basePath || "") + path;
2659
+ const honoMiddleware = middleware.map((m) => toHonoMiddleware(m));
2660
+ for (const m of honoMiddleware) {
2661
+ this.app.use(fullPath, m);
2662
+ }
2663
+ }
2664
+ useGlobal(...middleware) {
2665
+ this.use("*", ...middleware);
2666
+ }
2667
+ mount(path, subAdapter) {
2668
+ if (subAdapter.name === "hono") {
2669
+ this.app.route(path, subAdapter.native);
2670
+ } else {
2671
+ this.use(`${path}/*`, async (ctx) => {
2672
+ const response = await subAdapter.fetch(ctx.req.raw);
2673
+ return response;
2674
+ });
2675
+ }
2676
+ }
2677
+ onError(handler) {
2678
+ this.app.onError(toHonoErrorHandler(handler));
2679
+ }
2680
+ onNotFound(handler) {
2681
+ this.app.notFound(async (c) => {
2682
+ const ctx = HonoContextWrapper.create(c);
2683
+ return handler(ctx);
2684
+ });
2685
+ }
2686
+ fetch = (request, server) => {
2687
+ return this.app.fetch(request, server);
2688
+ };
2689
+ createContext(_request) {
2690
+ throw new Error("HonoAdapter.createContext() should not be called directly. " + "Use the router pipeline instead.");
2691
+ }
2692
+ async init() {}
2693
+ async shutdown() {}
2694
+ }
2695
+ // ../core/src/ConfigManager.ts
2696
+ class ConfigManager {
2697
+ config = new Map;
2698
+ constructor(initialConfig = {}) {
2699
+ for (const [key, value] of Object.entries(initialConfig)) {
2700
+ this.config.set(key, value);
2701
+ }
2702
+ this.loadEnv();
2703
+ }
2704
+ loadEnv() {
2705
+ const env = Bun.env;
2706
+ for (const key of Object.keys(env)) {
2707
+ if (env[key] !== undefined) {
2708
+ this.config.set(key, env[key]);
2709
+ }
2710
+ }
2711
+ }
2712
+ get(key, defaultValue) {
2713
+ if (this.config.has(key)) {
2714
+ return this.config.get(key);
2715
+ }
2716
+ if (defaultValue !== undefined) {
2717
+ return defaultValue;
2718
+ }
2719
+ throw new Error(`Config key '${key}' not found`);
2720
+ }
2721
+ set(key, value) {
2722
+ this.config.set(key, value);
2723
+ }
2724
+ has(key) {
2725
+ return this.config.has(key);
2726
+ }
2727
+ }
2728
+ // ../core/src/Container.ts
2729
+ class Container {
2730
+ bindings = new Map;
2731
+ instances = new Map;
2732
+ bind(key, factory) {
2733
+ this.bindings.set(key, { factory, shared: false });
2734
+ }
2735
+ singleton(key, factory) {
2736
+ this.bindings.set(key, { factory, shared: true });
2737
+ }
2738
+ instance(key, instance) {
2739
+ this.instances.set(key, instance);
2740
+ }
2741
+ make(key) {
2742
+ if (this.instances.has(key)) {
2743
+ return this.instances.get(key);
2744
+ }
2745
+ const binding = this.bindings.get(key);
2746
+ if (!binding) {
2747
+ throw new Error(`Service '${key}' not found in container`);
2748
+ }
2749
+ const instance = binding.factory(this);
2750
+ if (binding.shared) {
2751
+ this.instances.set(key, instance);
2752
+ }
2753
+ return instance;
2754
+ }
2755
+ has(key) {
2756
+ return this.bindings.has(key) || this.instances.has(key);
2757
+ }
2758
+ flush() {
2759
+ this.bindings.clear();
2760
+ this.instances.clear();
2761
+ }
2762
+ forget(key) {
2763
+ this.instances.delete(key);
2764
+ }
2765
+ }
2766
+ // ../core/src/types/events.ts
2767
+ class Event {
2768
+ shouldBroadcast() {
2769
+ return "broadcastOn" in this && typeof this.broadcastOn === "function";
2770
+ }
2771
+ getBroadcastChannel() {
2772
+ if (this.shouldBroadcast()) {
2773
+ return this.broadcastOn();
2774
+ }
2775
+ return null;
2776
+ }
2777
+ getBroadcastData() {
2778
+ if (this.shouldBroadcast()) {
2779
+ const broadcast = this;
2780
+ if (broadcast.broadcastWith) {
2781
+ return broadcast.broadcastWith();
2782
+ }
2783
+ const data = {};
2784
+ for (const [key, value] of Object.entries(this)) {
2785
+ if (!key.startsWith("_") && typeof value !== "function") {
2786
+ data[key] = value;
2787
+ }
2788
+ }
2789
+ return data;
2790
+ }
2791
+ return {};
2792
+ }
2793
+ getBroadcastEventName() {
2794
+ if (this.shouldBroadcast()) {
2795
+ const broadcast = this;
2796
+ if (broadcast.broadcastAs) {
2797
+ return broadcast.broadcastAs();
2798
+ }
2799
+ }
2800
+ return this.constructor.name;
2801
+ }
2802
+ }
2803
+ // ../core/src/EventManager.ts
2804
+ class EventManager {
2805
+ core;
2806
+ listeners = new Map;
2807
+ broadcastManager;
2808
+ queueManager;
2809
+ constructor(core) {
2810
+ this.core = core;
2811
+ }
2812
+ setBroadcastManager(manager) {
2813
+ this.broadcastManager = manager;
2814
+ }
2815
+ setQueueManager(manager) {
2816
+ this.queueManager = manager;
2817
+ }
2818
+ listen(event, listener, options) {
2819
+ const eventKey = typeof event === "string" ? event : event;
2820
+ if (!this.listeners.has(eventKey)) {
2821
+ this.listeners.set(eventKey, []);
2822
+ }
2823
+ const registration = {
2824
+ listener,
2825
+ ...options
2826
+ };
2827
+ this.listeners.get(eventKey)?.push(registration);
2828
+ }
2829
+ unlisten(event, listener) {
2830
+ const eventKey = typeof event === "string" ? event : event;
2831
+ const registrations = this.listeners.get(eventKey);
2832
+ if (!registrations) {
2833
+ return;
2834
+ }
2835
+ const filtered = registrations.filter((reg) => reg.listener !== listener);
2836
+ if (filtered.length === 0) {
2837
+ this.listeners.delete(eventKey);
2838
+ } else {
2839
+ this.listeners.set(eventKey, filtered);
2840
+ }
2841
+ }
2842
+ async dispatch(event) {
2843
+ const eventKey = event.constructor;
2844
+ const eventName = event.constructor.name;
2845
+ await this.core.hooks.doAction(`event:${eventName}`, event);
2846
+ await this.core.hooks.doAction("event:dispatched", { event, eventName });
2847
+ if (event instanceof Event && event.shouldBroadcast() && this.broadcastManager) {
2848
+ const channel = event.getBroadcastChannel();
2849
+ if (channel) {
2850
+ const channelName = typeof channel === "string" ? channel : channel.name;
2851
+ const channelType = typeof channel === "string" ? "public" : channel.type;
2852
+ const data = event.getBroadcastData();
2853
+ const broadcastEventName = event.getBroadcastEventName();
2854
+ await this.broadcastManager.broadcast(event, { name: channelName, type: channelType }, data, broadcastEventName).catch((error) => {
2855
+ this.core.logger.error(`[EventManager] Failed to broadcast event ${eventName}:`, error);
2856
+ });
2857
+ }
2858
+ }
2859
+ const registrations = this.listeners.get(eventKey) || [];
2860
+ const stringRegistrations = this.listeners.get(eventName) || [];
2861
+ const allRegistrations = [...registrations, ...stringRegistrations];
2862
+ for (const registration of allRegistrations) {
2863
+ try {
2864
+ let listenerInstance;
2865
+ if (typeof registration.listener === "function") {
2866
+ listenerInstance = new registration.listener;
2867
+ } else {
2868
+ listenerInstance = registration.listener;
2869
+ }
2870
+ const shouldQueue = "queue" in listenerInstance || registration.queue !== undefined || registration.connection !== undefined || registration.delay !== undefined;
2871
+ if (shouldQueue && this.queueManager) {
2872
+ const queue = listenerInstance.queue || registration.queue;
2873
+ const connection = listenerInstance.connection || registration.connection;
2874
+ const delay = listenerInstance.delay || registration.delay;
2875
+ const queueJob = {
2876
+ type: "event-listener",
2877
+ event: eventName,
2878
+ listener: listenerInstance.constructor.name,
2879
+ eventData: this.serializeEvent(event),
2880
+ handle: async () => {
2881
+ await listenerInstance.handle(event);
2882
+ }
2883
+ };
2884
+ await this.queueManager.push(queueJob, queue, connection, delay);
2885
+ } else {
2886
+ await listenerInstance.handle(event);
2887
+ }
2888
+ } catch (error) {
2889
+ this.core.logger.error(`[EventManager] Error in listener for event ${eventName}:`, error);
2890
+ }
2891
+ }
2892
+ }
2893
+ serializeEvent(event) {
2894
+ const data = {};
2895
+ for (const [key, value] of Object.entries(event)) {
2896
+ if (!key.startsWith("_") && typeof value !== "function") {
2897
+ data[key] = value;
2898
+ }
2899
+ }
2900
+ return data;
2901
+ }
2902
+ getListeners(event) {
2903
+ if (event) {
2904
+ const eventKey = typeof event === "string" ? event : event;
2905
+ return this.listeners.get(eventKey) || [];
2906
+ }
2907
+ const all = [];
2908
+ for (const registrations of this.listeners.values()) {
2909
+ all.push(...registrations);
2910
+ }
2911
+ return all;
2912
+ }
2913
+ clear() {
2914
+ this.listeners.clear();
2915
+ }
2916
+ }
2917
+ // ../core/src/exceptions/GravitoException.ts
2918
+ class GravitoException extends Error {
2919
+ status;
2920
+ code;
2921
+ i18nKey;
2922
+ i18nParams;
2923
+ constructor(status, code, options = {}) {
2924
+ super(options.message);
2925
+ this.name = "GravitoException";
2926
+ this.status = status;
2927
+ this.cause = options.cause;
2928
+ this.code = code;
2929
+ if (options.i18nKey) {
2930
+ this.i18nKey = options.i18nKey;
2931
+ }
2932
+ if (options.i18nParams) {
2933
+ this.i18nParams = options.i18nParams;
2934
+ }
2935
+ }
2936
+ getLocalizedMessage(t) {
2937
+ if (this.i18nKey) {
2938
+ return t(this.i18nKey, this.i18nParams);
2939
+ }
2940
+ return this.message;
2941
+ }
2942
+ }
2943
+ // ../core/src/exceptions/HttpException.ts
2944
+ class HttpException extends GravitoException {
2945
+ constructor(status, options = {}) {
2946
+ super(status, "HTTP_ERROR", options);
2947
+ this.name = "HttpException";
2948
+ }
2949
+ }
2950
+ // ../core/src/exceptions/ModelNotFoundException.ts
2951
+ class ModelNotFoundException extends GravitoException {
2952
+ model;
2953
+ id;
2954
+ constructor(model, id) {
2955
+ super(404, "NOT_FOUND", {
2956
+ message: `${model} not found.`,
2957
+ i18nKey: "errors.model.not_found",
2958
+ i18nParams: { model, id: String(id ?? "") }
2959
+ });
2960
+ this.model = model;
2961
+ if (id !== undefined) {
2962
+ this.id = id;
2963
+ }
2964
+ }
2965
+ }
2966
+ // ../core/src/exceptions/ValidationException.ts
2967
+ class ValidationException extends GravitoException {
2968
+ errors;
2969
+ redirectTo;
2970
+ input;
2971
+ constructor(errors, message = "Validation failed") {
2972
+ super(422, "VALIDATION_ERROR", {
2973
+ message,
2974
+ i18nKey: "errors.validation.failed"
2975
+ });
2976
+ this.errors = errors;
2977
+ }
2978
+ withRedirect(url) {
2979
+ this.redirectTo = url;
2980
+ return this;
2981
+ }
2982
+ withInput(input) {
2983
+ this.input = input;
2984
+ return this;
2985
+ }
2986
+ }
2987
+ // ../core/src/GlobalErrorHandlers.ts
2988
+ var stateKey = Symbol.for("gravito.core.globalErrorHandlers");
2989
+ function getGlobalState() {
2990
+ const g = globalThis;
2991
+ const existing = g[stateKey];
2992
+ if (existing) {
2993
+ return existing;
2994
+ }
2995
+ const created = {
2996
+ nextId: 1,
2997
+ sinks: new Map,
2998
+ listenersInstalled: false,
2999
+ onUnhandledRejection: undefined,
3000
+ onUncaughtException: undefined
3001
+ };
3002
+ g[stateKey] = created;
3003
+ return created;
3004
+ }
3005
+ function offProcess(event, listener) {
3006
+ const p = process;
3007
+ if (typeof p.off === "function") {
3008
+ p.off(event, listener);
3009
+ return;
3010
+ }
3011
+ if (typeof p.removeListener === "function") {
3012
+ p.removeListener(event, listener);
3013
+ }
3014
+ }
3015
+ function safeMessageFromUnknown(error) {
3016
+ if (error instanceof Error) {
3017
+ return error.message || "Error";
3018
+ }
3019
+ if (typeof error === "string") {
3020
+ return error;
3021
+ }
3022
+ try {
3023
+ return JSON.stringify(error);
3024
+ } catch {
3025
+ return String(error);
3026
+ }
3027
+ }
3028
+ async function handleProcessError(kind, error) {
3029
+ const state = getGlobalState();
3030
+ if (state.sinks.size === 0) {
3031
+ return;
3032
+ }
3033
+ const isProduction = false;
3034
+ let shouldExit = false;
3035
+ let exitCode = 1;
3036
+ let exitTimer;
3037
+ try {
3038
+ const sinks = Array.from(state.sinks.values());
3039
+ const prepared = await Promise.all(sinks.map(async (sink) => {
3040
+ const defaultExit = sink.mode === "exit" || sink.mode === "exitInProduction" && isProduction;
3041
+ let ctx = {
3042
+ ...sink.core ? { core: sink.core } : {},
3043
+ kind,
3044
+ error,
3045
+ isProduction,
3046
+ timestamp: Date.now(),
3047
+ exit: defaultExit,
3048
+ exitCode: sink.exitCode ?? 1,
3049
+ gracePeriodMs: sink.gracePeriodMs ?? 250
3050
+ };
3051
+ if (sink.core) {
3052
+ ctx = await sink.core.hooks.applyFilters("processError:context", ctx);
3053
+ }
3054
+ return { sink, ctx };
3055
+ }));
3056
+ const exitTargets = prepared.map((p) => p.ctx).filter((ctx) => (ctx.exit ?? false) && (ctx.exitCode ?? 1) >= 0);
3057
+ shouldExit = exitTargets.length > 0;
3058
+ const gracePeriodMs = Math.max(0, ...exitTargets.map((c) => c.gracePeriodMs ?? 250));
3059
+ exitCode = Math.max(0, ...exitTargets.map((c) => c.exitCode ?? 1));
3060
+ if (shouldExit) {
3061
+ exitTimer = setTimeout(() => {
3062
+ process.exit(exitCode);
3063
+ }, gracePeriodMs);
3064
+ exitTimer.unref?.();
3065
+ }
3066
+ await Promise.all(prepared.map(async ({ sink, ctx }) => {
3067
+ const logger = sink.logger ?? sink.core?.logger;
3068
+ const logLevel = ctx.logLevel ?? "error";
3069
+ if (logger && logLevel !== "none") {
3070
+ const message = safeMessageFromUnknown(ctx.error);
3071
+ const msg = ctx.logMessage ?? `[${ctx.kind}] ${message}`;
3072
+ if (logLevel === "error") {
3073
+ logger.error(msg, ctx.error);
3074
+ } else if (logLevel === "warn") {
3075
+ logger.warn(msg, ctx.error);
3076
+ } else {
3077
+ logger.info(msg, ctx.error);
3078
+ }
3079
+ }
3080
+ if (sink.core) {
3081
+ await sink.core.hooks.doAction("processError:report", ctx);
3082
+ }
3083
+ }));
3084
+ } catch (e) {
3085
+ console.error("[gravito-core] Failed to handle process-level error:", e);
3086
+ } finally {
3087
+ if (shouldExit) {
3088
+ clearTimeout(exitTimer);
3089
+ process.exit(exitCode);
3090
+ }
3091
+ }
3092
+ }
3093
+ function ensureListenersInstalled() {
3094
+ const state = getGlobalState();
3095
+ if (state.listenersInstalled) {
3096
+ return;
3097
+ }
3098
+ if (typeof process === "undefined" || typeof process.on !== "function") {
3099
+ return;
3100
+ }
3101
+ state.onUnhandledRejection = (reason) => {
3102
+ handleProcessError("unhandledRejection", reason);
3103
+ };
3104
+ state.onUncaughtException = (error) => {
3105
+ handleProcessError("uncaughtException", error);
3106
+ };
3107
+ process.on("unhandledRejection", state.onUnhandledRejection);
3108
+ process.on("uncaughtException", state.onUncaughtException);
3109
+ state.listenersInstalled = true;
3110
+ }
3111
+ function teardownListenersIfUnused() {
3112
+ const state = getGlobalState();
3113
+ if (!state.listenersInstalled || state.sinks.size > 0) {
3114
+ return;
3115
+ }
3116
+ if (state.onUnhandledRejection) {
3117
+ offProcess("unhandledRejection", state.onUnhandledRejection);
3118
+ }
3119
+ if (state.onUncaughtException) {
3120
+ offProcess("uncaughtException", state.onUncaughtException);
3121
+ }
3122
+ state.onUnhandledRejection = undefined;
3123
+ state.onUncaughtException = undefined;
3124
+ state.listenersInstalled = false;
3125
+ }
3126
+ function registerGlobalErrorHandlers(options = {}) {
3127
+ const state = getGlobalState();
3128
+ ensureListenersInstalled();
3129
+ const id = state.nextId++;
3130
+ state.sinks.set(id, {
3131
+ ...options,
3132
+ mode: options.mode ?? "exitInProduction"
3133
+ });
3134
+ return () => {
3135
+ state.sinks.delete(id);
3136
+ teardownListenersIfUnused();
3137
+ };
3138
+ }
3139
+ // ../core/src/HookManager.ts
3140
+ class HookManager {
3141
+ filters = new Map;
3142
+ actions = new Map;
3143
+ addFilter(hook, callback) {
3144
+ if (!this.filters.has(hook)) {
3145
+ this.filters.set(hook, []);
3146
+ }
3147
+ this.filters.get(hook)?.push(callback);
3148
+ }
3149
+ async applyFilters(hook, initialValue, ...args) {
3150
+ const callbacks = this.filters.get(hook) || [];
3151
+ let value = initialValue;
3152
+ for (const callback of callbacks) {
3153
+ try {
3154
+ value = await callback(value, ...args);
3155
+ } catch (error) {
3156
+ console.error(`[HookManager] Error in filter '${hook}':`, error);
3157
+ }
3158
+ }
3159
+ return value;
3160
+ }
3161
+ addAction(hook, callback) {
3162
+ if (!this.actions.has(hook)) {
3163
+ this.actions.set(hook, []);
3164
+ }
3165
+ this.actions.get(hook)?.push(callback);
3166
+ }
3167
+ async doAction(hook, args) {
3168
+ const callbacks = this.actions.get(hook) || [];
3169
+ for (const callback of callbacks) {
3170
+ try {
3171
+ await callback(args);
3172
+ } catch (error) {
3173
+ console.error(`[HookManager] Error in action '${hook}':`, error);
3174
+ }
3175
+ }
3176
+ }
3177
+ }
3178
+ // ../core/src/helpers/response.ts
3179
+ function fail(message, code, details) {
3180
+ const error = { message };
3181
+ if (code !== undefined) {
3182
+ error.code = code;
3183
+ }
3184
+ if (details !== undefined) {
3185
+ error.details = details;
3186
+ }
3187
+ return { success: false, error };
3188
+ }
3189
+ // ../core/src/http/CookieJar.ts
3190
+ class CookieJar {
3191
+ encrypter;
3192
+ queued = new Map;
3193
+ constructor(encrypter) {
3194
+ this.encrypter = encrypter;
3195
+ }
3196
+ queue(name, value, minutes = 60, options = {}) {
3197
+ if (minutes && !options.maxAge) {
3198
+ options.maxAge = minutes * 60;
3199
+ }
3200
+ let finalValue = value;
3201
+ if (options.encrypt) {
3202
+ if (!this.encrypter) {
3203
+ throw new Error("Encryption is not available. Ensure APP_KEY is set.");
3204
+ }
3205
+ finalValue = this.encrypter.encrypt(value);
3206
+ }
3207
+ this.queued.set(name, { value: finalValue, options });
3208
+ }
3209
+ forever(name, value, options = {}) {
3210
+ this.queue(name, value, 2628000, options);
3211
+ }
3212
+ forget(name, options = {}) {
3213
+ this.queue(name, "", 0, { ...options, maxAge: 0, expires: new Date(0) });
3214
+ }
3215
+ serializeCookie(name, value, opts) {
3216
+ const parts = [`${name}=${encodeURIComponent(value)}`];
3217
+ if (opts.maxAge !== undefined) {
3218
+ parts.push(`Max-Age=${opts.maxAge}`);
3219
+ }
3220
+ if (opts.expires) {
3221
+ parts.push(`Expires=${opts.expires.toUTCString()}`);
3222
+ }
3223
+ if (opts.path) {
3224
+ parts.push(`Path=${opts.path}`);
3225
+ }
3226
+ if (opts.domain) {
3227
+ parts.push(`Domain=${opts.domain}`);
3228
+ }
3229
+ if (opts.secure) {
3230
+ parts.push("Secure");
3231
+ }
3232
+ if (opts.httpOnly) {
3233
+ parts.push("HttpOnly");
3234
+ }
3235
+ if (opts.sameSite) {
3236
+ parts.push(`SameSite=${opts.sameSite}`);
3237
+ }
3238
+ return parts.join("; ");
3239
+ }
3240
+ attach(c) {
3241
+ for (const [name, { value, options }] of this.queued) {
3242
+ c.header("Set-Cookie", this.serializeCookie(name, value, options), { append: true });
3243
+ }
3244
+ }
3245
+ }
3246
+ // ../core/src/Logger.ts
3247
+ class ConsoleLogger {
3248
+ debug(message, ...args) {
3249
+ console.debug(`[DEBUG] ${message}`, ...args);
3250
+ }
3251
+ info(message, ...args) {
3252
+ console.info(`[INFO] ${message}`, ...args);
3253
+ }
3254
+ warn(message, ...args) {
3255
+ console.warn(`[WARN] ${message}`, ...args);
3256
+ }
3257
+ error(message, ...args) {
3258
+ console.error(`[ERROR] ${message}`, ...args);
3259
+ }
3260
+ }
3261
+ // ../core/src/adapters/bun/BunRequest.ts
3262
+ class BunRequest {
3263
+ raw;
3264
+ _url;
3265
+ _params = {};
3266
+ _query = null;
3267
+ _validated = {};
3268
+ constructor(raw, params = {}) {
3269
+ this.raw = raw;
3270
+ this._url = new URL(raw.url);
3271
+ this._params = params;
3272
+ }
3273
+ setParams(params) {
3274
+ this._params = params;
3275
+ }
3276
+ get url() {
3277
+ return this.raw.url;
3278
+ }
3279
+ get method() {
3280
+ return this.raw.method;
3281
+ }
3282
+ get path() {
3283
+ return this._url.pathname;
3284
+ }
3285
+ param(name) {
3286
+ return this._params[name];
3287
+ }
3288
+ params() {
3289
+ return this._params;
3290
+ }
3291
+ query(name) {
3292
+ if (!this._query) {
3293
+ this.parseQuery();
3294
+ }
3295
+ const val = this._query?.[name];
3296
+ if (Array.isArray(val)) {
3297
+ return val[0];
3298
+ }
3299
+ return val;
3300
+ }
3301
+ queries() {
3302
+ if (!this._query) {
3303
+ this.parseQuery();
3304
+ }
3305
+ return this._query;
3306
+ }
3307
+ header(name) {
3308
+ if (name) {
3309
+ return this.raw.headers.get(name) || undefined;
3310
+ }
3311
+ const headers = {};
3312
+ this.raw.headers.forEach((value, key) => {
3313
+ headers[key] = value;
3314
+ });
3315
+ return headers;
3316
+ }
3317
+ async json() {
3318
+ return this.raw.json();
3319
+ }
3320
+ async text() {
3321
+ return this.raw.text();
3322
+ }
3323
+ async formData() {
3324
+ return this.raw.formData();
3325
+ }
3326
+ async arrayBuffer() {
3327
+ return this.raw.arrayBuffer();
3328
+ }
3329
+ setValidated(target, data2) {
3330
+ this._validated[target] = data2;
3331
+ }
3332
+ valid(target) {
3333
+ const data2 = this._validated[target];
3334
+ if (data2 === undefined) {
3335
+ throw new Error(`Validation target '${target}' not found or validation failed.`);
3336
+ }
3337
+ return data2;
3338
+ }
3339
+ parseQuery() {
3340
+ this._query = {};
3341
+ for (const [key, value] of this._url.searchParams) {
3342
+ if (this._query[key]) {
3343
+ if (Array.isArray(this._query[key])) {
3344
+ this._query[key].push(value);
3345
+ } else {
3346
+ this._query[key] = [this._query[key], value];
3347
+ }
3348
+ } else {
3349
+ this._query[key] = value;
3350
+ }
3351
+ }
3352
+ }
3353
+ }
3354
+
3355
+ // ../core/src/adapters/bun/BunContext.ts
3356
+ class BunContext {
3357
+ env;
3358
+ req;
3359
+ _variables = new Map;
3360
+ _status = 200;
3361
+ _headers = new Headers;
3362
+ _executionCtx;
3363
+ res;
3364
+ native;
3365
+ constructor(request, env = {}, executionCtx) {
3366
+ this.env = env;
3367
+ this.req = new BunRequest(request);
3368
+ this._executionCtx = executionCtx;
3369
+ this.native = { request, env, executionCtx };
3370
+ }
3371
+ static create(request, env = {}, executionCtx) {
3372
+ const instance = new BunContext(request, env, executionCtx);
3373
+ return new Proxy(instance, {
3374
+ get(target, prop, receiver) {
3375
+ if (prop in target) {
3376
+ const value = Reflect.get(target, prop, receiver);
3377
+ if (typeof value === "function") {
3378
+ return value.bind(target);
3379
+ }
3380
+ return value;
3381
+ }
3382
+ if (typeof prop === "string") {
3383
+ return target.get(prop);
3384
+ }
3385
+ return;
3386
+ }
3387
+ });
3388
+ }
3389
+ json(data2, status = 200) {
3390
+ this.status(status);
3391
+ this.header("Content-Type", "application/json");
3392
+ this.res = new Response(JSON.stringify(data2), {
3393
+ status: this._status,
3394
+ headers: this._headers
3395
+ });
3396
+ return this.res;
3397
+ }
3398
+ text(text, status = 200) {
3399
+ this.status(status);
3400
+ this.header("Content-Type", "text/plain");
3401
+ this.res = new Response(text, {
3402
+ status: this._status,
3403
+ headers: this._headers
3404
+ });
3405
+ return this.res;
3406
+ }
3407
+ html(html, status = 200) {
3408
+ this.status(status);
3409
+ this.header("Content-Type", "text/html");
3410
+ this.res = new Response(html, {
3411
+ status: this._status,
3412
+ headers: this._headers
3413
+ });
3414
+ return this.res;
3415
+ }
3416
+ redirect(url, status = 302) {
3417
+ this.status(status);
3418
+ this.header("Location", url);
3419
+ this.res = new Response(null, {
3420
+ status: this._status,
3421
+ headers: this._headers
3422
+ });
3423
+ return this.res;
3424
+ }
3425
+ body(data2, status = 200) {
3426
+ this.status(status);
3427
+ this.res = new Response(data2, {
3428
+ status: this._status,
3429
+ headers: this._headers
3430
+ });
3431
+ return this.res;
3432
+ }
3433
+ stream(stream, status = 200) {
3434
+ this.status(status);
3435
+ this.res = new Response(stream, {
3436
+ status: this._status,
3437
+ headers: this._headers
3438
+ });
3439
+ return this.res;
3440
+ }
3441
+ header(name, value, options) {
3442
+ if (value === undefined) {
3443
+ return this.req.header(name);
3444
+ }
3445
+ if (options?.append) {
3446
+ this._headers.append(name, value);
3447
+ this.res?.headers.append(name, value);
3448
+ } else {
3449
+ this._headers.set(name, value);
3450
+ if (this.res) {
3451
+ this.res.headers.set(name, value);
3452
+ }
3453
+ }
3454
+ return;
3455
+ }
3456
+ status(code) {
3457
+ this._status = code;
3458
+ }
3459
+ get(key) {
3460
+ return this._variables.get(key);
3461
+ }
3462
+ set(key, value) {
3463
+ this._variables.set(key, value);
3464
+ }
3465
+ get executionCtx() {
3466
+ return this._executionCtx;
3467
+ }
3468
+ }
3469
+
3470
+ // ../core/src/adapters/bun/RadixNode.ts
3471
+ class RadixNode {
3472
+ segment;
3473
+ type;
3474
+ children = new Map;
3475
+ paramChild = null;
3476
+ wildcardChild = null;
3477
+ handlers = new Map;
3478
+ paramName = null;
3479
+ regex = null;
3480
+ constructor(segment = "", type = 0 /* STATIC */) {
3481
+ this.segment = segment;
3482
+ this.type = type;
3483
+ }
3484
+ toJSON() {
3485
+ return {
3486
+ segment: this.segment,
3487
+ type: this.type,
3488
+ children: Array.from(this.children.entries()).map(([k, v]) => [k, v.toJSON()]),
3489
+ paramChild: this.paramChild?.toJSON() || null,
3490
+ wildcardChild: this.wildcardChild?.toJSON() || null,
3491
+ paramName: this.paramName,
3492
+ regex: this.regex ? this.regex.source : null
3493
+ };
3494
+ }
3495
+ static fromJSON(json) {
3496
+ const node = new RadixNode(json.segment, json.type);
3497
+ node.paramName = json.paramName;
3498
+ if (json.regex) {
3499
+ node.regex = new RegExp(json.regex);
3500
+ }
3501
+ if (json.children) {
3502
+ for (const [key, childJson] of json.children) {
3503
+ node.children.set(key, RadixNode.fromJSON(childJson));
3504
+ }
3505
+ }
3506
+ if (json.paramChild) {
3507
+ node.paramChild = RadixNode.fromJSON(json.paramChild);
3508
+ }
3509
+ if (json.wildcardChild) {
3510
+ node.wildcardChild = RadixNode.fromJSON(json.wildcardChild);
3511
+ }
3512
+ return node;
3513
+ }
3514
+ }
3515
+
3516
+ // ../core/src/adapters/bun/RadixRouter.ts
3517
+ class RadixRouter {
3518
+ root = new RadixNode;
3519
+ globalConstraints = new Map;
3520
+ where(param, regex) {
3521
+ this.globalConstraints.set(param, regex);
3522
+ }
3523
+ add(method, path, handlers) {
3524
+ let node = this.root;
3525
+ const segments = this.splitPath(path);
3526
+ for (let i = 0;i < segments.length; i++) {
3527
+ const segment = segments[i];
3528
+ if (segment === "*") {
3529
+ if (!node.wildcardChild) {
3530
+ node.wildcardChild = new RadixNode("*", 2 /* WILDCARD */);
3531
+ }
3532
+ node = node.wildcardChild;
3533
+ break;
3534
+ } else if (segment.startsWith(":")) {
3535
+ const paramName = segment.slice(1);
3536
+ if (!node.paramChild) {
3537
+ const child = new RadixNode(segment, 1 /* PARAM */);
3538
+ child.paramName = paramName;
3539
+ const constraint = this.globalConstraints.get(paramName);
3540
+ if (constraint) {
3541
+ child.regex = constraint;
3542
+ }
3543
+ node.paramChild = child;
3544
+ }
3545
+ node = node.paramChild;
3546
+ } else {
3547
+ if (!node.children.has(segment)) {
3548
+ node.children.set(segment, new RadixNode(segment, 0 /* STATIC */));
3549
+ }
3550
+ node = node.children.get(segment);
3551
+ }
3552
+ }
3553
+ node.handlers.set(method.toLowerCase(), handlers);
3554
+ }
3555
+ match(method, path) {
3556
+ const normalizedMethod = method.toLowerCase();
3557
+ if (path === "/" || path === "") {
3558
+ const handlers = this.root.handlers.get(normalizedMethod);
3559
+ if (handlers) {
3560
+ return { handlers, params: {} };
3561
+ }
3562
+ return null;
3563
+ }
3564
+ const searchPath = path.startsWith("/") ? path.slice(1) : path;
3565
+ const segments = searchPath.split("/");
3566
+ return this.matchRecursive(this.root, segments, 0, {}, normalizedMethod);
3567
+ }
3568
+ matchRecursive(node, segments, depth, params, method) {
3569
+ if (depth >= segments.length) {
3570
+ let handlers = node.handlers.get(method);
3571
+ if (!handlers) {
3572
+ handlers = node.handlers.get("all");
3573
+ }
3574
+ if (handlers) {
3575
+ return { handlers, params };
3576
+ }
3577
+ return null;
3578
+ }
3579
+ const segment = segments[depth];
3580
+ const staticChild = node.children.get(segment);
3581
+ if (staticChild) {
3582
+ const match = this.matchRecursive(staticChild, segments, depth + 1, params, method);
3583
+ if (match) {
3584
+ return match;
3585
+ }
3586
+ }
3587
+ const paramChild = node.paramChild;
3588
+ if (paramChild) {
3589
+ if (paramChild.regex && !paramChild.regex.test(segment)) {} else {
3590
+ if (paramChild.paramName) {
3591
+ params[paramChild.paramName] = decodeURIComponent(segment);
3592
+ const match = this.matchRecursive(paramChild, segments, depth + 1, params, method);
3593
+ if (match) {
3594
+ return match;
3595
+ }
3596
+ delete params[paramChild.paramName];
3597
+ }
3598
+ }
3599
+ }
3600
+ if (node.wildcardChild) {
3601
+ let handlers = node.wildcardChild.handlers.get(method);
3602
+ if (!handlers) {
3603
+ handlers = node.wildcardChild.handlers.get("all");
3604
+ }
3605
+ if (handlers) {
3606
+ return { handlers, params };
3607
+ }
3608
+ }
3609
+ return null;
3610
+ }
3611
+ splitPath(path) {
3612
+ if (path === "/" || path === "") {
3613
+ return [];
3614
+ }
3615
+ let p = path;
3616
+ if (p.startsWith("/")) {
3617
+ p = p.slice(1);
3618
+ }
3619
+ if (p.endsWith("/")) {
3620
+ p = p.slice(0, -1);
3621
+ }
3622
+ return p.split("/");
3623
+ }
3624
+ serialize() {
3625
+ return JSON.stringify({
3626
+ root: this.root.toJSON(),
3627
+ globalConstraints: Array.from(this.globalConstraints.entries()).map(([k, v]) => [
3628
+ k,
3629
+ v.source
3630
+ ])
3631
+ });
3632
+ }
3633
+ static fromSerialized(json) {
3634
+ const data2 = JSON.parse(json);
3635
+ const router = new RadixRouter;
3636
+ router.root = RadixNode.fromJSON(data2.root);
3637
+ if (data2.globalConstraints) {
3638
+ for (const [key, source] of data2.globalConstraints) {
3639
+ router.globalConstraints.set(key, new RegExp(source));
3640
+ }
3641
+ }
3642
+ return router;
3643
+ }
3644
+ }
3645
+
3646
+ // ../core/src/adapters/bun/BunNativeAdapter.ts
3647
+ class BunNativeAdapter {
3648
+ name = "bun-native";
3649
+ version = "0.0.1";
3650
+ get native() {
3651
+ return this;
3652
+ }
3653
+ router = new RadixRouter;
3654
+ middlewares = [];
3655
+ errorHandler = null;
3656
+ notFoundHandler = null;
3657
+ route(method, path, ...handlers) {
3658
+ this.router.add(method, path, handlers);
3659
+ }
3660
+ routes(routes) {
3661
+ for (const route of routes) {
3662
+ this.route(route.method, route.path, ...route.handlers);
3663
+ }
3664
+ }
3665
+ use(path, ...middleware) {
3666
+ this.middlewares.push({ path, handlers: middleware });
3667
+ }
3668
+ useGlobal(...middleware) {
3669
+ this.use("*", ...middleware);
3670
+ }
3671
+ mount(path, subAdapter) {
3672
+ const fullPath = path.endsWith("/") ? `${path}*` : `${path}/*`;
3673
+ this.route("all", fullPath, async (ctx) => {
3674
+ const url = new URL(ctx.req.url);
3675
+ const prefix = path.endsWith("/") ? path.slice(0, -1) : path;
3676
+ console.log("[DEBUG] Mount Prefix:", prefix);
3677
+ console.log("[DEBUG] Original Path:", url.pathname);
3678
+ if (url.pathname.startsWith(prefix)) {
3679
+ const newPath = url.pathname.slice(prefix.length);
3680
+ url.pathname = newPath === "" ? "/" : newPath;
3681
+ }
3682
+ const newReq = new Request(url.toString(), {
3683
+ method: ctx.req.method,
3684
+ headers: ctx.req.raw.headers
3685
+ });
3686
+ const res = await subAdapter.fetch(newReq);
3687
+ if (ctx instanceof BunContext) {
3688
+ ctx.res = res;
3689
+ }
3690
+ return res;
3691
+ });
3692
+ }
3693
+ createContext(request) {
3694
+ return BunContext.create(request);
3695
+ }
3696
+ onError(handler) {
3697
+ this.errorHandler = handler;
3698
+ }
3699
+ onNotFound(handler) {
3700
+ this.notFoundHandler = handler;
3701
+ }
3702
+ async fetch(request, _server) {
3703
+ const ctx = BunContext.create(request);
3704
+ try {
3705
+ const url = new URL(request.url);
3706
+ const path = url.pathname;
3707
+ const method = request.method;
3708
+ const match = this.router.match(method, path);
3709
+ const handlers = [];
3710
+ for (const mw of this.middlewares) {
3711
+ if (mw.path === "*" || path.startsWith(mw.path)) {
3712
+ handlers.push(...mw.handlers);
3713
+ }
3714
+ }
3715
+ if (match) {
3716
+ if (match.params) {
3717
+ ctx.req.setParams(match.params);
3718
+ }
3719
+ handlers.push(...match.handlers);
3720
+ } else {
3721
+ if (this.notFoundHandler) {
3722
+ handlers.push(this.notFoundHandler);
3723
+ } else {}
3724
+ }
3725
+ return await this.executeChain(ctx, handlers);
3726
+ } catch (err) {
3727
+ if (this.errorHandler) {
3728
+ try {
3729
+ const response2 = await this.errorHandler(err, ctx);
3730
+ if (response2) {
3731
+ return response2;
3732
+ }
3733
+ } catch (e) {
3734
+ console.error("Error handler failed", e);
3735
+ }
3736
+ }
3737
+ console.error(err);
3738
+ return new Response("Internal Server Error", { status: 500 });
3739
+ }
3740
+ }
3741
+ async executeChain(ctx, handlers) {
3742
+ let index = -1;
3743
+ const dispatch = async (i) => {
3744
+ if (i <= index) {
3745
+ throw new Error("next() called multiple times");
3746
+ }
3747
+ index = i;
3748
+ const fn = handlers[i];
3749
+ if (!fn) {
3750
+ return;
3751
+ }
3752
+ const result = await fn(ctx, async () => {
3753
+ const res = await dispatch(i + 1);
3754
+ if (res && ctx.res !== res) {
3755
+ ctx.res = res;
3756
+ }
3757
+ return res;
3758
+ });
3759
+ return result;
3760
+ };
3761
+ const finalResponse = await dispatch(0);
3762
+ if (finalResponse && (finalResponse instanceof Response || typeof finalResponse.status === "number")) {
3763
+ return finalResponse;
3764
+ }
3765
+ if (ctx.res) {
3766
+ return ctx.res;
3767
+ }
3768
+ return new Response("Not Found", { status: 404 });
3769
+ }
3770
+ }
3771
+
3772
+ // ../core/src/Route.ts
3773
+ class Route {
3774
+ router;
3775
+ method;
3776
+ path;
3777
+ options;
3778
+ constructor(router, method, path, options) {
3779
+ this.router = router;
3780
+ this.method = method;
3781
+ this.path = path;
3782
+ this.options = options;
3783
+ }
3784
+ name(name) {
3785
+ this.router.registerName(name, this.method, this.path, this.options);
3786
+ return this;
3787
+ }
3788
+ }
3789
+
3790
+ // ../core/src/Router.ts
3791
+ function isFormRequestClass(value) {
3792
+ if (typeof value !== "function") {
3793
+ return false;
3794
+ }
3795
+ try {
3796
+ const instance = new value;
3797
+ return instance !== null && typeof instance === "object" && "schema" in instance && "validate" in instance && typeof instance.validate === "function";
3798
+ } catch {
3799
+ return false;
3800
+ }
3801
+ }
3802
+ function formRequestToMiddleware(RequestClass) {
3803
+ return async (ctx, next) => {
3804
+ const request = new RequestClass;
3805
+ if (typeof request.validate !== "function") {
3806
+ throw new Error("Invalid FormRequest: validate() is missing.");
3807
+ }
3808
+ const result = await request.validate(ctx);
3809
+ if (!result.success) {
3810
+ const errorCode = result.error?.error?.code;
3811
+ const status = errorCode === "AUTHORIZATION_ERROR" ? 403 : 422;
3812
+ return ctx.json(result.error, status);
3813
+ }
3814
+ ctx.set("validated", result.data);
3815
+ await next();
3816
+ return;
3817
+ };
3818
+ }
3819
+
3820
+ class RouteGroup {
3821
+ router;
3822
+ options;
3823
+ constructor(router, options) {
3824
+ this.router = router;
3825
+ this.options = options;
3826
+ }
3827
+ prefix(path) {
3828
+ return new RouteGroup(this.router, {
3829
+ ...this.options,
3830
+ prefix: (this.options.prefix || "") + path
3831
+ });
3832
+ }
3833
+ middleware(...handlers) {
3834
+ const flattened = handlers.flat();
3835
+ return new RouteGroup(this.router, {
3836
+ ...this.options,
3837
+ middleware: [...this.options.middleware || [], ...flattened]
3838
+ });
3839
+ }
3840
+ group(callback) {
3841
+ callback(this);
3842
+ }
3843
+ get(path, requestOrHandler, handler) {
3844
+ return this.router.req("get", path, requestOrHandler, handler, this.options);
3845
+ }
3846
+ post(path, requestOrHandler, handler) {
3847
+ return this.router.req("post", path, requestOrHandler, handler, this.options);
3848
+ }
3849
+ put(path, requestOrHandler, handler) {
3850
+ return this.router.req("put", path, requestOrHandler, handler, this.options);
3851
+ }
3852
+ delete(path, requestOrHandler, handler) {
3853
+ return this.router.req("delete", path, requestOrHandler, handler, this.options);
3854
+ }
3855
+ patch(path, requestOrHandler, handler) {
3856
+ return this.router.req("patch", path, requestOrHandler, handler, this.options);
3857
+ }
3858
+ resource(name, controller, options = {}) {
3859
+ const actions = [
3860
+ "index",
3861
+ "create",
3862
+ "store",
3863
+ "show",
3864
+ "edit",
3865
+ "update",
3866
+ "destroy"
3867
+ ];
3868
+ const map = {
3869
+ index: { method: "get", path: `/${name}` },
3870
+ create: { method: "get", path: `/${name}/create` },
3871
+ store: { method: "post", path: `/${name}` },
3872
+ show: { method: "get", path: `/${name}/:id` },
3873
+ edit: { method: "get", path: `/${name}/:id/edit` },
3874
+ update: { method: "put", path: `/${name}/:id` },
3875
+ destroy: { method: "delete", path: `/${name}/:id` }
3876
+ };
3877
+ const allowed = actions.filter((action) => {
3878
+ if (options.only) {
3879
+ return options.only.includes(action);
3880
+ }
3881
+ if (options.except) {
3882
+ return !options.except.includes(action);
3883
+ }
3884
+ return true;
3885
+ });
3886
+ for (const action of allowed) {
3887
+ const { method, path } = map[action];
3888
+ if (action === "update") {
3889
+ this.router.req("put", path, [controller, action], undefined, this.options).name(`${name}.${action}`);
3890
+ this.router.req("patch", path, [controller, action], undefined, this.options);
3891
+ } else {
3892
+ this.router.req(method, path, [controller, action], undefined, this.options).name(`${name}.${action}`);
3893
+ }
3894
+ }
3895
+ }
3896
+ }
3897
+
3898
+ class Router {
3899
+ core;
3900
+ controllers = new Map;
3901
+ namedRoutes = new Map;
3902
+ bindings = new Map;
3903
+ compile() {
3904
+ const routes = [];
3905
+ for (const [name, info] of this.namedRoutes) {
3906
+ routes.push({
3907
+ name,
3908
+ method: info.method,
3909
+ path: info.path,
3910
+ domain: info.domain
3911
+ });
3912
+ }
3913
+ return routes;
3914
+ }
3915
+ registerName(name, method, path, options = {}) {
3916
+ const fullPath = (options.prefix || "") + path;
3917
+ this.namedRoutes.set(name, {
3918
+ method: method.toUpperCase(),
3919
+ path: fullPath,
3920
+ domain: options.domain
3921
+ });
3922
+ }
3923
+ url(name, params = {}, query = {}) {
3924
+ const route = this.namedRoutes.get(name);
3925
+ if (!route) {
3926
+ throw new Error(`Named route '${name}' not found`);
3927
+ }
3928
+ let path = route.path;
3929
+ path = path.replace(/:([A-Za-z0-9_]+)/g, (_, key) => {
3930
+ const value = params[key];
3931
+ if (value === undefined || value === null) {
3932
+ throw new Error(`Missing route param '${key}' for route '${name}'`);
3933
+ }
3934
+ return encodeURIComponent(String(value));
3935
+ });
3936
+ const qs = new URLSearchParams;
3937
+ for (const [k, v] of Object.entries(query)) {
3938
+ if (v === undefined || v === null) {
3939
+ continue;
3940
+ }
3941
+ qs.set(k, String(v));
3942
+ }
3943
+ const suffix = qs.toString();
3944
+ return suffix ? `${path}?${suffix}` : path;
3945
+ }
3946
+ exportNamedRoutes() {
3947
+ return Object.fromEntries(this.namedRoutes.entries());
3948
+ }
3949
+ loadNamedRoutes(manifest) {
3950
+ this.namedRoutes = new Map(Object.entries(manifest));
3951
+ }
3952
+ bind(param, resolver) {
3953
+ this.bindings.set(param, resolver);
3954
+ }
3955
+ model(param, modelClass) {
3956
+ this.bind(param, async (id) => {
3957
+ if (modelClass && typeof modelClass === "object" && "find" in modelClass && typeof modelClass.find === "function") {
3958
+ const instance = await modelClass.find(id);
3959
+ if (!instance) {
3960
+ throw new Error("ModelNotFound");
3961
+ }
3962
+ return instance;
3963
+ }
3964
+ throw new Error(`Invalid model class for binding '${param}'`);
3965
+ });
3966
+ }
3967
+ constructor(core) {
3968
+ this.core = core;
3969
+ this.core.adapter.useGlobal(async (c, next) => {
3970
+ const routeModels = c.get("routeModels") ?? {};
3971
+ for (const [param, resolver] of this.bindings) {
3972
+ const value = c.req.param(param);
3973
+ if (value) {
3974
+ try {
3975
+ const resolved = await resolver(value);
3976
+ routeModels[param] = resolved;
3977
+ } catch (err) {
3978
+ const message = err instanceof Error ? err.message : undefined;
3979
+ if (message === "ModelNotFound") {
3980
+ throw new ModelNotFoundException(param, value);
3981
+ }
3982
+ throw err;
3983
+ }
3984
+ }
3985
+ }
3986
+ c.set("routeModels", routeModels);
3987
+ await next();
3988
+ return;
3989
+ });
3990
+ }
3991
+ prefix(path) {
3992
+ return new RouteGroup(this, { prefix: path });
3993
+ }
3994
+ domain(host) {
3995
+ return new RouteGroup(this, { domain: host });
3996
+ }
3997
+ middleware(...handlers) {
3998
+ return new RouteGroup(this, { middleware: handlers.flat() });
3999
+ }
4000
+ get(path, requestOrHandler, handler) {
4001
+ return this.req("get", path, requestOrHandler, handler);
4002
+ }
4003
+ post(path, requestOrHandler, handler) {
4004
+ return this.req("post", path, requestOrHandler, handler);
4005
+ }
4006
+ put(path, requestOrHandler, handler) {
4007
+ return this.req("put", path, requestOrHandler, handler);
4008
+ }
4009
+ delete(path, requestOrHandler, handler) {
4010
+ return this.req("delete", path, requestOrHandler, handler);
4011
+ }
4012
+ patch(path, requestOrHandler, handler) {
4013
+ return this.req("patch", path, requestOrHandler, handler);
4014
+ }
4015
+ resource(name, controller, options = {}) {
4016
+ const actions = [
4017
+ "index",
4018
+ "create",
4019
+ "store",
4020
+ "show",
4021
+ "edit",
4022
+ "update",
4023
+ "destroy"
4024
+ ];
4025
+ const map = {
4026
+ index: { method: "get", path: `/${name}` },
4027
+ create: { method: "get", path: `/${name}/create` },
4028
+ store: { method: "post", path: `/${name}` },
4029
+ show: { method: "get", path: `/${name}/:id` },
4030
+ edit: { method: "get", path: `/${name}/:id/edit` },
4031
+ update: { method: "put", path: `/${name}/:id` },
4032
+ destroy: { method: "delete", path: `/${name}/:id` }
4033
+ };
4034
+ const allowed = actions.filter((action) => {
4035
+ if (options.only) {
4036
+ return options.only.includes(action);
4037
+ }
4038
+ if (options.except) {
4039
+ return !options.except.includes(action);
4040
+ }
4041
+ return true;
4042
+ });
4043
+ for (const action of allowed) {
4044
+ const { method, path } = map[action];
4045
+ if (action === "update") {
4046
+ this.req("put", path, [controller, action]).name(`${name}.${action}`);
4047
+ this.req("patch", path, [controller, action]);
4048
+ } else {
4049
+ this.req(method, path, [controller, action]).name(`${name}.${action}`);
4050
+ }
4051
+ }
4052
+ }
4053
+ req(method, path, requestOrHandler, handler, options = {}) {
4054
+ const fullPath = (options.prefix || "") + path;
4055
+ let formRequestMiddleware = null;
4056
+ let finalRouteHandler;
4057
+ if (handler !== undefined) {
4058
+ if (isFormRequestClass(requestOrHandler)) {
4059
+ formRequestMiddleware = formRequestToMiddleware(requestOrHandler);
4060
+ }
4061
+ finalRouteHandler = handler;
4062
+ } else {
4063
+ finalRouteHandler = requestOrHandler;
4064
+ }
4065
+ let resolvedHandler;
4066
+ if (Array.isArray(finalRouteHandler)) {
4067
+ const [CtrlClass, methodName] = finalRouteHandler;
4068
+ resolvedHandler = this.resolveControllerHandler(CtrlClass, methodName);
4069
+ } else {
4070
+ resolvedHandler = finalRouteHandler;
4071
+ }
4072
+ const handlers = [];
4073
+ if (options.middleware) {
4074
+ handlers.push(...options.middleware);
4075
+ }
4076
+ if (formRequestMiddleware) {
4077
+ handlers.push(formRequestMiddleware);
4078
+ }
4079
+ handlers.push(resolvedHandler);
4080
+ if (options.domain) {
4081
+ const _wrappedHandler = async (c) => {
4082
+ if (c.req.header("host") !== options.domain) {
4083
+ return new Response("Not Found", { status: 404 });
4084
+ }
4085
+ return;
4086
+ };
4087
+ const domainCheck = async (c, next) => {
4088
+ if (c.req.header("host") !== options.domain) {
4089
+ return c.text("Not Found", 404);
4090
+ }
4091
+ await next();
4092
+ };
4093
+ handlers.unshift(domainCheck);
4094
+ }
4095
+ this.core.adapter.route(method, fullPath, ...handlers);
4096
+ return new Route(this, method, fullPath, options);
4097
+ }
4098
+ resolveControllerHandler(CtrlClass, methodName) {
4099
+ let instance = this.controllers.get(CtrlClass);
4100
+ if (!instance) {
4101
+ instance = new CtrlClass(this.core);
4102
+ this.controllers.set(CtrlClass, instance);
4103
+ }
4104
+ const handler = instance[methodName];
4105
+ if (typeof handler !== "function") {
4106
+ throw new Error(`Method '${methodName}' not found in controller '${CtrlClass.name}'`);
4107
+ }
4108
+ return handler.bind(instance);
4109
+ }
4110
+ }
4111
+
4112
+ // ../core/src/security/Encrypter.ts
4113
+ import crypto from "node:crypto";
4114
+
4115
+ class Encrypter {
4116
+ algorithm;
4117
+ key;
4118
+ constructor(options) {
4119
+ this.algorithm = options.cipher || "aes-256-cbc";
4120
+ if (options.key.startsWith("base64:")) {
4121
+ this.key = Buffer.from(options.key.substring(7), "base64");
4122
+ } else {
4123
+ this.key = Buffer.from(options.key);
4124
+ }
4125
+ if (this.algorithm === "aes-128-cbc" && this.key.length !== 16) {
4126
+ throw new Error("The key must be 16 bytes (128 bits) for AES-128-CBC.");
4127
+ }
4128
+ if (this.algorithm === "aes-256-cbc" && this.key.length !== 32) {
4129
+ throw new Error("The key must be 32 bytes (256 bits) for AES-256-CBC.");
4130
+ }
4131
+ }
4132
+ encrypt(value, serialize = true) {
4133
+ const iv = crypto.randomBytes(16);
4134
+ const cipher = crypto.createCipheriv(this.algorithm, this.key, iv);
4135
+ const stringValue = serialize ? JSON.stringify(value) : String(value);
4136
+ let encrypted = cipher.update(stringValue, "utf8", "base64");
4137
+ encrypted += cipher.final("base64");
4138
+ const mac = this.hash(iv.toString("base64"), encrypted);
4139
+ const payload = {
4140
+ iv: iv.toString("base64"),
4141
+ value: encrypted,
4142
+ mac,
4143
+ tag: ""
4144
+ };
4145
+ return Buffer.from(JSON.stringify(payload)).toString("base64");
4146
+ }
4147
+ decrypt(payload, deserialize = true) {
4148
+ const json = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
4149
+ if (!this.validPayload(json)) {
4150
+ throw new Error("The payload is invalid.");
4151
+ }
4152
+ if (!this.validMac(json)) {
4153
+ throw new Error("The MAC is invalid.");
4154
+ }
4155
+ const iv = Buffer.from(json.iv, "base64");
4156
+ const decipher = crypto.createDecipheriv(this.algorithm, this.key, iv);
4157
+ let decrypted = decipher.update(json.value, "base64", "utf8");
4158
+ decrypted += decipher.final("utf8");
4159
+ return deserialize ? JSON.parse(decrypted) : decrypted;
4160
+ }
4161
+ hash(iv, value) {
4162
+ const hmac = crypto.createHmac("sha256", this.key);
4163
+ hmac.update(iv + value);
4164
+ return hmac.digest("hex");
4165
+ }
4166
+ validPayload(payload) {
4167
+ return typeof payload === "object" && payload !== null && "iv" in payload && "value" in payload && "mac" in payload;
4168
+ }
4169
+ validMac(payload) {
4170
+ const calculated = this.hash(payload.iv, payload.value);
4171
+ return crypto.timingSafeEqual(Buffer.from(calculated), Buffer.from(payload.mac));
4172
+ }
4173
+ static generateKey(cipher = "aes-256-cbc") {
4174
+ const bytes = cipher === "aes-128-cbc" ? 16 : 32;
4175
+ return `base64:${crypto.randomBytes(bytes).toString("base64")}`;
4176
+ }
4177
+ }
4178
+
4179
+ // ../core/src/security/Hasher.ts
4180
+ class BunHasher {
4181
+ async make(value, options) {
4182
+ const bun = Bun;
4183
+ return await bun.password.hash(value, options);
4184
+ }
4185
+ async check(value, hashedValue) {
4186
+ const bun = Bun;
4187
+ return await bun.password.verify(value, hashedValue);
4188
+ }
4189
+ needsRehash(_hashedValue, _options) {
4190
+ return false;
4191
+ }
4192
+ }
4193
+
4194
+ // ../core/src/PlanetCore.ts
4195
+ class PlanetCore {
4196
+ _adapter;
4197
+ get app() {
4198
+ return this._adapter.native;
4199
+ }
4200
+ get adapter() {
4201
+ return this._adapter;
4202
+ }
4203
+ logger;
4204
+ config;
4205
+ hooks;
4206
+ events;
4207
+ router;
4208
+ container = new Container;
4209
+ services = new Map;
4210
+ encrypter;
4211
+ hasher;
4212
+ providers = [];
4213
+ register(provider) {
4214
+ this.providers.push(provider);
4215
+ return this;
4216
+ }
4217
+ async bootstrap() {
4218
+ for (const provider of this.providers) {
4219
+ provider.register(this.container);
4220
+ }
4221
+ for (const provider of this.providers) {
4222
+ if (provider.boot) {
4223
+ await provider.boot(this);
4224
+ }
4225
+ }
4226
+ }
4227
+ constructor(options = {}) {
4228
+ this.logger = options.logger ?? new ConsoleLogger;
4229
+ this.config = new ConfigManager(options.config ?? {});
4230
+ this.hooks = new HookManager;
4231
+ this.events = new EventManager(this);
4232
+ this.hasher = new BunHasher;
4233
+ const appKey = (this.config.has("APP_KEY") ? this.config.get("APP_KEY") : undefined) || process.env.APP_KEY;
4234
+ if (appKey) {
4235
+ try {
4236
+ this.encrypter = new Encrypter({ key: appKey });
4237
+ } catch (e) {
4238
+ this.logger.warn("Failed to initialize Encrypter (invalid APP_KEY?):", e);
4239
+ }
4240
+ }
4241
+ if (options.adapter) {
4242
+ this._adapter = options.adapter;
4243
+ } else if (typeof Bun !== "undefined") {
4244
+ this._adapter = new BunNativeAdapter;
4245
+ } else {
4246
+ this._adapter = new HonoAdapter;
4247
+ }
4248
+ this.adapter.use("*", async (c, next) => {
4249
+ c.set("core", this);
4250
+ c.set("logger", this.logger);
4251
+ c.set("config", this.config);
4252
+ const cookieJar = new CookieJar(this.encrypter);
4253
+ c.set("cookieJar", cookieJar);
4254
+ c.route = (name, params, query) => this.router.url(name, params, query);
4255
+ await next();
4256
+ return;
4257
+ });
4258
+ this.router = new Router(this);
4259
+ this.adapter.onError(async (err, c) => {
4260
+ const isProduction = false;
4261
+ const codeFromStatus = (status2) => {
4262
+ switch (status2) {
4263
+ case 400:
4264
+ return "BAD_REQUEST";
4265
+ case 401:
4266
+ return "UNAUTHENTICATED";
4267
+ case 403:
4268
+ return "FORBIDDEN";
4269
+ case 404:
4270
+ return "NOT_FOUND";
4271
+ case 405:
4272
+ return "METHOD_NOT_ALLOWED";
4273
+ case 409:
4274
+ return "CONFLICT";
4275
+ case 422:
4276
+ return "VALIDATION_ERROR";
4277
+ case 429:
4278
+ return "TOO_MANY_REQUESTS";
4279
+ default:
4280
+ return status2 >= 500 ? "INTERNAL_ERROR" : "HTTP_ERROR";
4281
+ }
4282
+ };
4283
+ const messageFromStatus = (status2) => {
4284
+ switch (status2) {
4285
+ case 400:
4286
+ return "Bad Request";
4287
+ case 401:
4288
+ return "Unauthorized";
4289
+ case 403:
4290
+ return "Forbidden";
4291
+ case 404:
4292
+ return "Not Found";
4293
+ case 405:
4294
+ return "Method Not Allowed";
4295
+ case 409:
4296
+ return "Conflict";
4297
+ case 422:
4298
+ return "Unprocessable Content";
4299
+ case 429:
4300
+ return "Too Many Requests";
4301
+ case 500:
4302
+ return "Internal Server Error";
4303
+ case 502:
4304
+ return "Bad Gateway";
4305
+ case 503:
4306
+ return "Service Unavailable";
4307
+ case 504:
4308
+ return "Gateway Timeout";
4309
+ default:
4310
+ return status2 >= 500 ? "Internal Server Error" : "Request Error";
4311
+ }
4312
+ };
4313
+ const view = c.get("view");
4314
+ const i18n = c.get("i18n");
4315
+ const accept = c.req.header("Accept") || "";
4316
+ const wantsHtml = Boolean(view && accept.includes("text/html") && !accept.includes("application/json"));
4317
+ let status = 500;
4318
+ let message = messageFromStatus(500);
4319
+ let code = "INTERNAL_ERROR";
4320
+ let details;
4321
+ if (err instanceof GravitoException) {
4322
+ status = err.status;
4323
+ code = err.code;
4324
+ if (code === "HTTP_ERROR") {
4325
+ code = codeFromStatus(status);
4326
+ }
4327
+ if (i18n?.t && err.i18nKey) {
4328
+ message = i18n.t(err.i18nKey, err.i18nParams);
4329
+ } else {
4330
+ message = err.message || messageFromStatus(status);
4331
+ }
4332
+ if (err instanceof ValidationException) {
4333
+ details = err.errors;
4334
+ if (wantsHtml) {
4335
+ const session = c.get("session");
4336
+ if (session) {
4337
+ const errorBag = {};
4338
+ for (const e of err.errors) {
4339
+ if (!errorBag[e.field]) {
4340
+ errorBag[e.field] = [];
4341
+ }
4342
+ errorBag[e.field]?.push(e.message);
4343
+ }
4344
+ session.flash("errors", errorBag);
4345
+ if (err.input) {
4346
+ session.flash("_old_input", err.input);
4347
+ }
4348
+ const redirectUrl = err.redirectTo ?? c.req.header("Referer") ?? "/";
4349
+ return c.redirect(redirectUrl);
4350
+ }
4351
+ }
4352
+ } else if (err instanceof Error && !isProduction && err.cause) {
4353
+ details = { cause: err.cause };
4354
+ }
4355
+ } else if (err instanceof HttpException) {
4356
+ status = err.status;
4357
+ message = err.message;
4358
+ } else if (err instanceof Error && "status" in err && typeof err.status === "number") {
4359
+ status = err.status;
4360
+ message = err.message;
4361
+ code = codeFromStatus(status);
4362
+ } else if (err instanceof Error) {
4363
+ if (!isProduction) {
4364
+ message = err.message || message;
4365
+ }
4366
+ } else if (typeof err === "string") {
4367
+ if (!isProduction) {
4368
+ message = err;
4369
+ }
4370
+ }
4371
+ if (isProduction && status >= 500) {
4372
+ message = messageFromStatus(status);
4373
+ }
4374
+ if (!isProduction && err instanceof Error && !details) {
4375
+ details = { stack: err.stack, ...details };
4376
+ }
4377
+ let handlerContext = {
4378
+ core: this,
4379
+ c,
4380
+ error: err,
4381
+ isProduction,
4382
+ accept,
4383
+ wantsHtml,
4384
+ status,
4385
+ payload: fail(message, code, details),
4386
+ ...wantsHtml ? {
4387
+ html: {
4388
+ templates: status === 500 ? ["errors/500"] : [`errors/${status}`, "errors/500"],
4389
+ data: {
4390
+ status,
4391
+ message,
4392
+ code,
4393
+ error: !isProduction && err instanceof Error ? err.stack : undefined,
4394
+ debug: !isProduction,
4395
+ details
4396
+ }
4397
+ }
4398
+ } : {}
4399
+ };
4400
+ handlerContext = await this.hooks.applyFilters("error:context", handlerContext);
4401
+ const defaultLogLevel = handlerContext.status >= 500 ? "error" : "none";
4402
+ const logLevel = handlerContext.logLevel ?? defaultLogLevel;
4403
+ if (logLevel !== "none") {
4404
+ const rawErrorMessage = handlerContext.error instanceof Error ? handlerContext.error.message : typeof handlerContext.error === "string" ? handlerContext.error : handlerContext.payload.error.message;
4405
+ const msg = handlerContext.logMessage ?? (logLevel === "error" ? `Application Error: ${rawErrorMessage || handlerContext.payload.error.message}` : `HTTP ${handlerContext.status}: ${handlerContext.payload.error.message}`);
4406
+ if (logLevel === "error") {
4407
+ this.logger.error(msg, err);
4408
+ } else if (logLevel === "warn") {
4409
+ this.logger.warn(msg);
4410
+ } else {
4411
+ this.logger.info(msg);
4412
+ }
4413
+ }
4414
+ await this.hooks.doAction("error:report", handlerContext);
4415
+ const customResponse = await this.hooks.applyFilters("error:render", null, handlerContext);
4416
+ if (customResponse) {
4417
+ return customResponse;
4418
+ }
4419
+ if (handlerContext.wantsHtml && view && handlerContext.html) {
4420
+ let lastRenderError;
4421
+ for (const template of handlerContext.html.templates) {
4422
+ try {
4423
+ return c.html(view.render(template, handlerContext.html.data), handlerContext.status);
4424
+ } catch (renderError) {
4425
+ lastRenderError = renderError;
4426
+ }
4427
+ }
4428
+ this.logger.error("Failed to render error view", lastRenderError);
4429
+ }
4430
+ return c.json(handlerContext.payload, handlerContext.status);
4431
+ });
4432
+ this.adapter.onNotFound(async (c) => {
4433
+ const view = c.get("view");
4434
+ const accept = c.req.header("Accept") || "";
4435
+ const wantsHtml = view && accept.includes("text/html") && !accept.includes("application/json");
4436
+ const isProduction = false;
4437
+ let handlerContext = {
4438
+ core: this,
4439
+ c,
4440
+ error: new HttpException(404, { message: "Route not found" }),
4441
+ isProduction,
4442
+ accept,
4443
+ wantsHtml: Boolean(wantsHtml),
4444
+ status: 404,
4445
+ payload: fail("Route not found", "NOT_FOUND"),
4446
+ ...wantsHtml ? {
4447
+ html: {
4448
+ templates: ["errors/404", "errors/500"],
4449
+ data: {
4450
+ status: 404,
4451
+ message: "Route not found",
4452
+ code: "NOT_FOUND",
4453
+ debug: !isProduction
4454
+ }
4455
+ }
4456
+ } : {}
4457
+ };
4458
+ handlerContext = await this.hooks.applyFilters("notFound:context", handlerContext);
4459
+ const logLevel = handlerContext.logLevel ?? "info";
4460
+ if (logLevel !== "none") {
4461
+ const msg = handlerContext.logMessage ?? `404 Not Found: ${c.req.url}`;
4462
+ if (logLevel === "error") {
4463
+ this.logger.error(msg);
4464
+ } else if (logLevel === "warn") {
4465
+ this.logger.warn(msg);
4466
+ } else {
4467
+ this.logger.info(msg);
4468
+ }
4469
+ }
4470
+ await this.hooks.doAction("notFound:report", handlerContext);
4471
+ const customResponse = await this.hooks.applyFilters("notFound:render", null, handlerContext);
4472
+ if (customResponse) {
4473
+ return customResponse;
4474
+ }
4475
+ if (handlerContext.wantsHtml && view && handlerContext.html) {
4476
+ let lastRenderError;
4477
+ for (const template of handlerContext.html.templates) {
4478
+ try {
4479
+ return c.html(view.render(template, handlerContext.html.data), handlerContext.status);
4480
+ } catch (renderError) {
4481
+ lastRenderError = renderError;
4482
+ }
4483
+ }
4484
+ this.logger.error("Failed to render 404 view", lastRenderError);
4485
+ }
4486
+ return c.json(handlerContext.payload, handlerContext.status);
4487
+ });
4488
+ }
4489
+ async orbit(orbit) {
4490
+ const instance = typeof orbit === "function" ? new orbit : orbit;
4491
+ await instance.install(this);
4492
+ return this;
4493
+ }
4494
+ async use(satellite) {
4495
+ if (typeof satellite === "function") {
4496
+ await satellite(this);
4497
+ } else {
4498
+ this.register(satellite);
4499
+ }
4500
+ return this;
4501
+ }
4502
+ registerGlobalErrorHandlers(options = {}) {
4503
+ return registerGlobalErrorHandlers({ ...options, core: this });
4504
+ }
4505
+ static async boot(config) {
4506
+ const core = new PlanetCore({
4507
+ ...config.logger && { logger: config.logger },
4508
+ ...config.config && { config: config.config },
4509
+ ...config.adapter && { adapter: config.adapter }
4510
+ });
4511
+ if (config.orbits) {
4512
+ for (const OrbitClassOrInstance of config.orbits) {
4513
+ let orbit;
4514
+ if (typeof OrbitClassOrInstance === "function") {
4515
+ orbit = new OrbitClassOrInstance;
4516
+ } else {
4517
+ orbit = OrbitClassOrInstance;
4518
+ }
4519
+ await orbit.install(core);
4520
+ }
4521
+ }
4522
+ return core;
4523
+ }
4524
+ mountOrbit(path, orbitApp) {
4525
+ this.logger.info(`Mounting orbit at path: ${path}`);
4526
+ if (this.adapter.name === "hono") {
4527
+ this.adapter.native.route(path, orbitApp);
4528
+ } else {
4529
+ const subAdapter = new HonoAdapter({}, orbitApp);
4530
+ this.adapter.mount(path, subAdapter);
4531
+ }
4532
+ }
4533
+ liftoff(port) {
4534
+ const finalPort = port ?? this.config.get("PORT", 3000);
4535
+ this.hooks.doAction("app:liftoff", { port: finalPort });
4536
+ this.logger.info(`Ready to liftoff on port ${finalPort} \uD83D\uDE80`);
4537
+ return {
4538
+ port: finalPort,
4539
+ fetch: this.adapter.fetch.bind(this.adapter),
4540
+ core: this
4541
+ };
4542
+ }
4543
+ }
4544
+
4545
+ // ../core/src/index.ts
4546
+ var VERSION = package_default.version;
4547
+
4548
+ // ../ion/src/InertiaService.ts
4549
+ class InertiaService {
4550
+ context;
4551
+ config;
4552
+ sharedProps = {};
4553
+ constructor(context, config = {}) {
4554
+ this.context = context;
4555
+ this.config = config;
4556
+ }
4557
+ escapeForSingleQuotedHtmlAttribute(value) {
4558
+ return value.replace(/&/g, "&amp;").replace(/\\"/g, "\\&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/'/g, "&#039;");
4559
+ }
4560
+ render(component, props = {}, rootVars = {}) {
4561
+ let pageUrl;
4562
+ try {
4563
+ const reqUrl = new URL(this.context.req.url, "http://localhost");
4564
+ pageUrl = reqUrl.pathname + reqUrl.search;
4565
+ } catch {
4566
+ pageUrl = this.context.req.url;
4567
+ }
4568
+ const resolveProps = (p) => {
4569
+ const resolved = {};
4570
+ for (const [key, value] of Object.entries(p)) {
4571
+ resolved[key] = typeof value === "function" ? value() : value;
4572
+ }
4573
+ return resolved;
4574
+ };
4575
+ const page = {
4576
+ component,
4577
+ props: resolveProps({ ...this.sharedProps, ...props }),
4578
+ url: pageUrl,
4579
+ version: this.config.version
4580
+ };
4581
+ if (this.context.req.header("X-Inertia")) {
4582
+ this.context.header("X-Inertia", "true");
4583
+ this.context.header("Vary", "Accept");
4584
+ return this.context.json(page);
4585
+ }
4586
+ const view = this.context.get("view");
4587
+ const rootView = this.config.rootView ?? "app";
4588
+ if (!view) {
4589
+ throw new Error("OrbitPrism is required for the initial page load in OrbitIon");
4590
+ }
4591
+ const isDev = true;
4592
+ return this.context.html(view.render(rootView, {
4593
+ ...rootVars,
4594
+ page: this.escapeForSingleQuotedHtmlAttribute(JSON.stringify(page)),
4595
+ isDev
4596
+ }, { layout: "" }));
4597
+ }
4598
+ share(key, value) {
4599
+ this.sharedProps[key] = value;
4600
+ }
4601
+ shareAll(props) {
4602
+ Object.assign(this.sharedProps, props);
4603
+ }
4604
+ getSharedProps() {
4605
+ return { ...this.sharedProps };
4606
+ }
4607
+ }
4608
+
4609
+ // ../ion/src/index.ts
4610
+ class OrbitIon {
4611
+ install(core) {
4612
+ core.logger.info("\uD83D\uDEF0️ Orbit Inertia installed");
4613
+ const appVersion = core.config.get("APP_VERSION", "1.0.0");
4614
+ core.adapter.use("*", async (c, next) => {
4615
+ const gravitoCtx = new HonoContextWrapper(c);
4616
+ const inertia = new InertiaService(gravitoCtx, {
4617
+ version: String(appVersion),
4618
+ rootView: "app"
4619
+ });
4620
+ c.set("inertia", inertia);
4621
+ await next();
4622
+ return;
4623
+ });
4624
+ }
4625
+ }
4626
+ var src_default = OrbitIon;
4627
+ export {
4628
+ src_default as default,
4629
+ OrbitIon,
4630
+ InertiaService
4631
+ };