@hyperspan/framework 0.0.3 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,676 +1,166 @@
1
- var __create = Object.create;
2
- var __getProtoOf = Object.getPrototypeOf;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __toESM = (mod, isNodeMode, target) => {
7
- target = mod != null ? __create(__getProtoOf(mod)) : {};
8
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
9
- for (let key of __getOwnPropNames(mod))
10
- if (!__hasOwnProp.call(to, key))
11
- __defProp(to, key, {
12
- get: () => mod[key],
13
- enumerable: true
14
- });
15
- return to;
16
- };
17
- var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
18
-
19
- // node_modules/escape-html/index.js
20
- var require_escape_html = __commonJS((exports, module) => {
21
- function escapeHtml(string) {
22
- var str = "" + string;
23
- var match = matchHtmlRegExp.exec(str);
24
- if (!match) {
25
- return str;
26
- }
27
- var escape;
28
- var html = "";
29
- var index = 0;
30
- var lastIndex = 0;
31
- for (index = match.index;index < str.length; index++) {
32
- switch (str.charCodeAt(index)) {
33
- case 34:
34
- escape = "&quot;";
35
- break;
36
- case 38:
37
- escape = "&amp;";
38
- break;
39
- case 39:
40
- escape = "&#39;";
41
- break;
42
- case 60:
43
- escape = "&lt;";
44
- break;
45
- case 62:
46
- escape = "&gt;";
47
- break;
48
- default:
49
- continue;
50
- }
51
- if (lastIndex !== index) {
52
- html += str.substring(lastIndex, index);
53
- }
54
- lastIndex = index + 1;
55
- html += escape;
56
- }
57
- return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
58
- }
59
- /*!
60
- * escape-html
61
- * Copyright(c) 2012-2013 TJ Holowaychuk
62
- * Copyright(c) 2015 Andreas Lubbe
63
- * Copyright(c) 2015 Tiancheng "Timothy" Gu
64
- * MIT Licensed
65
- */
66
- var matchHtmlRegExp = /["'&<>]/;
67
- module.exports = escapeHtml;
68
- });
69
-
70
- // node_modules/trek-router/index.js
71
- var require_trek_router = __commonJS((exports, module) => {
72
- /*!
73
- * router
74
- * Copyright(c) 2015-2017 Fangdun Cai
75
- * MIT Licensed
76
- */
77
- var [SKIND, PKIND, AKIND, STAR, SLASH, COLON] = [0, 1, 2, 42, 47, 58];
1
+ // src/server.ts
2
+ import { readdir as readdir2 } from "node:fs/promises";
3
+ import { basename, extname, join } from "node:path";
78
4
 
79
- class Node {
80
- constructor(prefix = "/", children = [], kind = SKIND, map = Object.create(null)) {
81
- this.label = prefix.charCodeAt(0);
82
- this.prefix = prefix;
83
- this.children = children;
84
- this.kind = kind;
85
- this.map = map;
86
- }
87
- addChild(n) {
88
- this.children.push(n);
89
- }
90
- findChild(c, t, l, e, i = 0) {
91
- for (l = this.children.length;i < l; i++) {
92
- e = this.children[i];
93
- if (c === e.label && t === e.kind) {
94
- return e;
95
- }
96
- }
97
- }
98
- findChildWithLabel(c, l, e, i = 0) {
99
- for (l = this.children.length;i < l; i++) {
100
- e = this.children[i];
101
- if (c === e.label) {
102
- return e;
103
- }
104
- }
105
- }
106
- findChildByKind(t, l, e, i = 0) {
107
- for (l = this.children.length;i < l; i++) {
108
- e = this.children[i];
109
- if (t === e.kind) {
110
- return e;
111
- }
112
- }
113
- }
114
- addHandler(method, handler, pnames) {
115
- this.map[method] = { handler, pnames };
5
+ // node_modules/@hyperspan/html/dist/html.js
6
+ /*!
7
+ * escape-html
8
+ * Copyright(c) 2012-2013 TJ Holowaychuk
9
+ * Copyright(c) 2015 Andreas Lubbe
10
+ * Copyright(c) 2015 Tiancheng "Timothy" Gu
11
+ * MIT Licensed
12
+ */
13
+ var matchHtmlRegExp = /["'&<>]/;
14
+ function escapeHtml(string) {
15
+ const str = "" + string;
16
+ const match = matchHtmlRegExp.exec(str);
17
+ if (!match) {
18
+ return str;
19
+ }
20
+ let escape;
21
+ let html = "";
22
+ let index = 0;
23
+ let lastIndex = 0;
24
+ for (index = match.index;index < str.length; index++) {
25
+ switch (str.charCodeAt(index)) {
26
+ case 34:
27
+ escape = "&quot;";
28
+ break;
29
+ case 38:
30
+ escape = "&amp;";
31
+ break;
32
+ case 39:
33
+ escape = "&#39;";
34
+ break;
35
+ case 60:
36
+ escape = "&lt;";
37
+ break;
38
+ case 62:
39
+ escape = "&gt;";
40
+ break;
41
+ default:
42
+ continue;
116
43
  }
117
- findHandler(method) {
118
- return this.map[method];
44
+ if (lastIndex !== index) {
45
+ html += str.substring(lastIndex, index);
119
46
  }
47
+ lastIndex = index + 1;
48
+ html += escape;
120
49
  }
50
+ return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
51
+ }
121
52
 
122
- class Router {
123
- constructor() {
124
- this.tree = new Node;
125
- }
126
- add(method, path, handler) {
127
- let [i, l, pnames, ch, j] = [0, path.length, []];
128
- for (;i < l; ++i) {
129
- ch = path.charCodeAt(i);
130
- if (ch === COLON) {
131
- j = i + 1;
132
- this.insert(method, path.substring(0, i), SKIND);
133
- while (i < l && path.charCodeAt(i) !== SLASH) {
134
- i++;
135
- }
136
- pnames.push(path.substring(j, i));
137
- path = path.substring(0, j) + path.substring(i);
138
- i = j;
139
- l = path.length;
140
- if (i === l) {
141
- this.insert(method, path.substring(0, i), PKIND, pnames, handler);
142
- return;
143
- }
144
- this.insert(method, path.substring(0, i), PKIND, pnames);
145
- } else if (ch === STAR) {
146
- this.insert(method, path.substring(0, i), SKIND);
147
- pnames.push("*");
148
- this.insert(method, path.substring(0, l), AKIND, pnames, handler);
149
- return;
150
- }
151
- }
152
- this.insert(method, path, SKIND, pnames, handler);
153
- }
154
- insert(method, path, t, pnames, handler) {
155
- let [cn, prefix, sl, pl, l, max, n, c] = [this.tree];
156
- while (true) {
157
- prefix = cn.prefix;
158
- sl = path.length;
159
- pl = prefix.length;
160
- l = 0;
161
- max = sl < pl ? sl : pl;
162
- while (l < max && path.charCodeAt(l) === prefix.charCodeAt(l)) {
163
- l++;
164
- }
165
- if (l < pl) {
166
- n = new Node(prefix.substring(l), cn.children, cn.kind, cn.map);
167
- cn.children = [n];
168
- cn.label = prefix.charCodeAt(0);
169
- cn.prefix = prefix.substring(0, l);
170
- cn.map = Object.create(null);
171
- cn.kind = SKIND;
172
- if (l === sl) {
173
- cn.addHandler(method, handler, pnames);
174
- cn.kind = t;
175
- } else {
176
- n = new Node(path.substring(l), [], t);
177
- n.addHandler(method, handler, pnames);
178
- cn.addChild(n);
179
- }
180
- } else if (l < sl) {
181
- path = path.substring(l);
182
- c = cn.findChildWithLabel(path.charCodeAt(0));
183
- if (c !== undefined) {
184
- cn = c;
185
- continue;
186
- }
187
- n = new Node(path, [], t);
188
- n.addHandler(method, handler, pnames);
189
- cn.addChild(n);
190
- } else if (handler !== undefined) {
191
- cn.addHandler(method, handler, pnames);
192
- }
193
- return;
194
- }
195
- }
196
- find(method, path, cn, n = 0, result = [undefined, []]) {
197
- cn = cn || this.tree;
198
- const sl = path.length;
199
- const prefix = cn.prefix;
200
- const pvalues = result[1];
201
- let i, pl, l, max, c;
202
- let preSearch;
203
- if (sl === 0 || path === prefix) {
204
- const r = cn.findHandler(method);
205
- if ((result[0] = r && r.handler) !== undefined) {
206
- const pnames = r.pnames;
207
- if (pnames !== undefined) {
208
- for (i = 0, l = pnames.length;i < l; ++i) {
209
- pvalues[i] = {
210
- name: pnames[i],
211
- value: pvalues[i]
212
- };
213
- }
214
- }
215
- }
216
- return result;
217
- }
218
- pl = prefix.length;
219
- l = 0;
220
- max = sl < pl ? sl : pl;
221
- while (l < max && path.charCodeAt(l) === prefix.charCodeAt(l)) {
222
- l++;
223
- }
224
- if (l === pl) {
225
- path = path.substring(l);
226
- }
227
- preSearch = path;
228
- c = cn.findChild(path.charCodeAt(0), SKIND);
229
- if (c !== undefined) {
230
- this.find(method, path, c, n, result);
231
- if (result[0] !== undefined) {
232
- return result;
233
- }
234
- path = preSearch;
235
- }
236
- if (l !== pl) {
237
- return result;
238
- }
239
- c = cn.findChildByKind(PKIND);
240
- if (c !== undefined) {
241
- l = path.length;
242
- i = 0;
243
- while (i < l && path.charCodeAt(i) !== SLASH) {
244
- i++;
245
- }
246
- pvalues[n] = path.substring(0, i);
247
- n++;
248
- preSearch = path;
249
- path = path.substring(i);
250
- this.find(method, path, c, n, result);
251
- if (result[0] !== undefined) {
252
- return result;
253
- }
254
- n--;
255
- pvalues.pop();
256
- path = preSearch;
257
- }
258
- c = cn.findChildByKind(AKIND);
259
- if (c !== undefined) {
260
- pvalues[n] = path;
261
- path = "";
262
- this.find(method, path, c, n, result);
53
+ class TmplHtml {
54
+ content = "";
55
+ asyncContent;
56
+ constructor(props) {
57
+ this.content = props.content;
58
+ this.asyncContent = props.asyncContent;
59
+ }
60
+ }
61
+ var htmlId = 0;
62
+ function html(strings, ...values) {
63
+ const asyncContent = [];
64
+ let content = "";
65
+ for (let i = 0;i < strings.length; i++) {
66
+ let value = values[i];
67
+ let renderValue;
68
+ if (value !== null && value !== undefined) {
69
+ let id = `async_loading_${htmlId++}`;
70
+ let kind = _typeOf(value);
71
+ if (!renderValue) {
72
+ renderValue = _renderValue(value, { id, kind, asyncContent }) || "";
263
73
  }
264
- return result;
265
74
  }
75
+ content += strings[i] + (renderValue ? renderValue : "");
266
76
  }
267
- Router.Node = Node;
268
- module.exports = Router;
269
- });
270
-
271
- // node_modules/trek-middleware/index.js
272
- var require_trek_middleware = __commonJS((exports, module) => {
273
- /*!
274
- * middleware
275
- * Copyright(c) 2015-2017 Fangdun Cai
276
- * MIT Licensed
277
- */
278
- module.exports = class Middleware extends Array {
279
- next(context, last, i, done, called, fn) {
280
- if (done = i > this.length)
281
- return;
282
- fn = this[i] || last;
283
- return fn && fn(context, () => {
284
- if (called)
285
- throw new Error("next() called multiple times");
286
- called = true;
287
- return Promise.resolve(this.next(context, last, i + 1));
288
- });
289
- }
290
- compose(context, last) {
291
- try {
292
- return Promise.resolve(this.next(context, last, 0));
293
- } catch (err) {
294
- return Promise.reject(err);
77
+ return new TmplHtml({ content, asyncContent });
78
+ }
79
+ html.raw = (content) => ({ _kind: "html_safe", content });
80
+ function _renderValue(value, opts = {
81
+ kind: undefined,
82
+ id: undefined,
83
+ asyncContent: []
84
+ }) {
85
+ if (value === null || value === undefined || Number.isNaN(value)) {
86
+ return "";
87
+ }
88
+ const kind = opts.kind || _typeOf(value);
89
+ const id = opts.id || "";
90
+ switch (kind) {
91
+ case "array":
92
+ return value.map((v) => _renderValue(v, { id, asyncContent: opts.asyncContent })).join("");
93
+ case "object":
94
+ if (value instanceof TmplHtml) {
95
+ opts.asyncContent.push(...value.asyncContent);
96
+ return value.content;
295
97
  }
296
- }
297
- };
298
- });
299
-
300
- // node_modules/@fastify/deepmerge/index.js
301
- var require_deepmerge = __commonJS((exports, module) => {
302
- function deepmergeConstructor(options) {
303
- function isNotPrototypeKey(value) {
304
- return value !== "constructor" && value !== "prototype" && value !== "__proto__";
305
- }
306
- function cloneArray(value) {
307
- let i = 0;
308
- const il = value.length;
309
- const result = new Array(il);
310
- for (i = 0;i < il; ++i) {
311
- result[i] = clone(value[i]);
312
- }
313
- return result;
314
- }
315
- function cloneObject(target) {
316
- const result = {};
317
- if (cloneProtoObject && Object.getPrototypeOf(target) !== JSON_PROTO) {
318
- return cloneProtoObject(target);
319
- }
320
- const targetKeys = getKeys(target);
321
- let i, il, key;
322
- for (i = 0, il = targetKeys.length;i < il; ++i) {
323
- isNotPrototypeKey(key = targetKeys[i]) && (result[key] = clone(target[key]));
324
- }
325
- return result;
326
- }
327
- function concatArrays(target, source) {
328
- const tl = target.length;
329
- const sl = source.length;
330
- let i = 0;
331
- const result = new Array(tl + sl);
332
- for (i = 0;i < tl; ++i) {
333
- result[i] = clone(target[i]);
334
- }
335
- for (i = 0;i < sl; ++i) {
336
- result[i + tl] = clone(source[i]);
337
- }
338
- return result;
339
- }
340
- const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
341
- function getSymbolsAndKeys(value) {
342
- const result = Object.keys(value);
343
- const keys = Object.getOwnPropertySymbols(value);
344
- for (let i = 0, il = keys.length;i < il; ++i) {
345
- propertyIsEnumerable.call(value, keys[i]) && result.push(keys[i]);
346
- }
347
- return result;
348
- }
349
- const getKeys = options && options.symbols ? getSymbolsAndKeys : Object.keys;
350
- const cloneProtoObject = typeof options?.cloneProtoObject === "function" ? options.cloneProtoObject : undefined;
351
- function isMergeableObject(value) {
352
- return typeof value === "object" && value !== null && !(value instanceof RegExp) && !(value instanceof Date);
353
- }
354
- function isPrimitive(value) {
355
- return typeof value !== "object" || value === null;
356
- }
357
- const isPrimitiveOrBuiltIn = typeof Buffer !== "undefined" ? (value) => typeof value !== "object" || value === null || value instanceof RegExp || value instanceof Date || value instanceof Buffer : (value) => typeof value !== "object" || value === null || value instanceof RegExp || value instanceof Date;
358
- const mergeArray = options && typeof options.mergeArray === "function" ? options.mergeArray({ clone, deepmerge: _deepmerge, getKeys, isMergeableObject }) : concatArrays;
359
- function clone(entry) {
360
- return isMergeableObject(entry) ? Array.isArray(entry) ? cloneArray(entry) : cloneObject(entry) : entry;
361
- }
362
- function mergeObject(target, source) {
363
- const result = {};
364
- const targetKeys = getKeys(target);
365
- const sourceKeys = getKeys(source);
366
- let i, il, key;
367
- for (i = 0, il = targetKeys.length;i < il; ++i) {
368
- isNotPrototypeKey(key = targetKeys[i]) && sourceKeys.indexOf(key) === -1 && (result[key] = clone(target[key]));
369
- }
370
- for (i = 0, il = sourceKeys.length;i < il; ++i) {
371
- isNotPrototypeKey(key = sourceKeys[i]) && ((key in target) && (targetKeys.indexOf(key) !== -1 && (result[key] = _deepmerge(target[key], source[key])), true) || (result[key] = clone(source[key])));
372
- }
373
- return result;
374
- }
375
- function _deepmerge(target, source) {
376
- const sourceIsArray = Array.isArray(source);
377
- const targetIsArray = Array.isArray(target);
378
- if (isPrimitive(source)) {
379
- return source;
380
- } else if (isPrimitiveOrBuiltIn(target)) {
381
- return clone(source);
382
- } else if (sourceIsArray && targetIsArray) {
383
- return mergeArray(target, source);
384
- } else if (sourceIsArray !== targetIsArray) {
385
- return clone(source);
386
- } else {
387
- return mergeObject(target, source);
98
+ if (value?._kind === "html_safe") {
99
+ return value?.content || "";
388
100
  }
389
- }
390
- function _deepmergeAll() {
391
- switch (arguments.length) {
392
- case 0:
393
- return {};
394
- case 1:
395
- return clone(arguments[0]);
396
- case 2:
397
- return _deepmerge(arguments[0], arguments[1]);
101
+ if (typeof value.renderAsync === "function") {
102
+ opts.asyncContent.push({
103
+ id,
104
+ promise: value.renderAsync().then((result) => ({
105
+ id,
106
+ value: result,
107
+ asyncContent: opts.asyncContent
108
+ }))
109
+ });
398
110
  }
399
- let result;
400
- for (let i = 0, il = arguments.length;i < il; ++i) {
401
- result = _deepmerge(result, arguments[i]);
111
+ if (typeof value.render === "function") {
112
+ return render(_htmlPlaceholder(id, value.render()));
402
113
  }
403
- return result;
404
- }
405
- return options && options.all ? _deepmergeAll : _deepmerge;
406
- }
407
- var JSON_PROTO = Object.getPrototypeOf({});
408
- module.exports = deepmergeConstructor;
409
- module.exports.default = deepmergeConstructor;
410
- module.exports.deepmerge = deepmergeConstructor;
411
- });
412
-
413
- // src/server.ts
414
- import { readdir } from "node:fs/promises";
415
- import { basename, extname, join, resolve } from "node:path";
416
-
417
- // src/html.ts
418
- var import_escape_html = __toESM(require_escape_html(), 1);
419
-
420
- // src/clientjs/md5.js
421
- function md5cycle(x, k) {
422
- var a = x[0], b = x[1], c = x[2], d = x[3];
423
- a = ff(a, b, c, d, k[0], 7, -680876936);
424
- d = ff(d, a, b, c, k[1], 12, -389564586);
425
- c = ff(c, d, a, b, k[2], 17, 606105819);
426
- b = ff(b, c, d, a, k[3], 22, -1044525330);
427
- a = ff(a, b, c, d, k[4], 7, -176418897);
428
- d = ff(d, a, b, c, k[5], 12, 1200080426);
429
- c = ff(c, d, a, b, k[6], 17, -1473231341);
430
- b = ff(b, c, d, a, k[7], 22, -45705983);
431
- a = ff(a, b, c, d, k[8], 7, 1770035416);
432
- d = ff(d, a, b, c, k[9], 12, -1958414417);
433
- c = ff(c, d, a, b, k[10], 17, -42063);
434
- b = ff(b, c, d, a, k[11], 22, -1990404162);
435
- a = ff(a, b, c, d, k[12], 7, 1804603682);
436
- d = ff(d, a, b, c, k[13], 12, -40341101);
437
- c = ff(c, d, a, b, k[14], 17, -1502002290);
438
- b = ff(b, c, d, a, k[15], 22, 1236535329);
439
- a = gg(a, b, c, d, k[1], 5, -165796510);
440
- d = gg(d, a, b, c, k[6], 9, -1069501632);
441
- c = gg(c, d, a, b, k[11], 14, 643717713);
442
- b = gg(b, c, d, a, k[0], 20, -373897302);
443
- a = gg(a, b, c, d, k[5], 5, -701558691);
444
- d = gg(d, a, b, c, k[10], 9, 38016083);
445
- c = gg(c, d, a, b, k[15], 14, -660478335);
446
- b = gg(b, c, d, a, k[4], 20, -405537848);
447
- a = gg(a, b, c, d, k[9], 5, 568446438);
448
- d = gg(d, a, b, c, k[14], 9, -1019803690);
449
- c = gg(c, d, a, b, k[3], 14, -187363961);
450
- b = gg(b, c, d, a, k[8], 20, 1163531501);
451
- a = gg(a, b, c, d, k[13], 5, -1444681467);
452
- d = gg(d, a, b, c, k[2], 9, -51403784);
453
- c = gg(c, d, a, b, k[7], 14, 1735328473);
454
- b = gg(b, c, d, a, k[12], 20, -1926607734);
455
- a = hh(a, b, c, d, k[5], 4, -378558);
456
- d = hh(d, a, b, c, k[8], 11, -2022574463);
457
- c = hh(c, d, a, b, k[11], 16, 1839030562);
458
- b = hh(b, c, d, a, k[14], 23, -35309556);
459
- a = hh(a, b, c, d, k[1], 4, -1530992060);
460
- d = hh(d, a, b, c, k[4], 11, 1272893353);
461
- c = hh(c, d, a, b, k[7], 16, -155497632);
462
- b = hh(b, c, d, a, k[10], 23, -1094730640);
463
- a = hh(a, b, c, d, k[13], 4, 681279174);
464
- d = hh(d, a, b, c, k[0], 11, -358537222);
465
- c = hh(c, d, a, b, k[3], 16, -722521979);
466
- b = hh(b, c, d, a, k[6], 23, 76029189);
467
- a = hh(a, b, c, d, k[9], 4, -640364487);
468
- d = hh(d, a, b, c, k[12], 11, -421815835);
469
- c = hh(c, d, a, b, k[15], 16, 530742520);
470
- b = hh(b, c, d, a, k[2], 23, -995338651);
471
- a = ii(a, b, c, d, k[0], 6, -198630844);
472
- d = ii(d, a, b, c, k[7], 10, 1126891415);
473
- c = ii(c, d, a, b, k[14], 15, -1416354905);
474
- b = ii(b, c, d, a, k[5], 21, -57434055);
475
- a = ii(a, b, c, d, k[12], 6, 1700485571);
476
- d = ii(d, a, b, c, k[3], 10, -1894986606);
477
- c = ii(c, d, a, b, k[10], 15, -1051523);
478
- b = ii(b, c, d, a, k[1], 21, -2054922799);
479
- a = ii(a, b, c, d, k[8], 6, 1873313359);
480
- d = ii(d, a, b, c, k[15], 10, -30611744);
481
- c = ii(c, d, a, b, k[6], 15, -1560198380);
482
- b = ii(b, c, d, a, k[13], 21, 1309151649);
483
- a = ii(a, b, c, d, k[4], 6, -145523070);
484
- d = ii(d, a, b, c, k[11], 10, -1120210379);
485
- c = ii(c, d, a, b, k[2], 15, 718787259);
486
- b = ii(b, c, d, a, k[9], 21, -343485551);
487
- x[0] = add32(a, x[0]);
488
- x[1] = add32(b, x[1]);
489
- x[2] = add32(c, x[2]);
490
- x[3] = add32(d, x[3]);
491
- }
492
- function cmn(q, a, b, x, s, t) {
493
- a = add32(add32(a, q), add32(x, t));
494
- return add32(a << s | a >>> 32 - s, b);
495
- }
496
- function ff(a, b, c, d, x, s, t) {
497
- return cmn(b & c | ~b & d, a, b, x, s, t);
498
- }
499
- function gg(a, b, c, d, x, s, t) {
500
- return cmn(b & d | c & ~d, a, b, x, s, t);
501
- }
502
- function hh(a, b, c, d, x, s, t) {
503
- return cmn(b ^ c ^ d, a, b, x, s, t);
504
- }
505
- function ii(a, b, c, d, x, s, t) {
506
- return cmn(c ^ (b | ~d), a, b, x, s, t);
507
- }
508
- function md51(s) {
509
- var txt = "";
510
- var n = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i;
511
- for (i = 64;i <= s.length; i += 64) {
512
- md5cycle(state, md5blk(s.substring(i - 64, i)));
513
- }
514
- s = s.substring(i - 64);
515
- var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
516
- for (i = 0;i < s.length; i++)
517
- tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);
518
- tail[i >> 2] |= 128 << (i % 4 << 3);
519
- if (i > 55) {
520
- md5cycle(state, tail);
521
- for (i = 0;i < 16; i++)
522
- tail[i] = 0;
523
- }
524
- tail[14] = n * 8;
525
- md5cycle(state, tail);
526
- return state;
527
- }
528
- function md5blk(s) {
529
- var md5blks = [], i;
530
- for (i = 0;i < 64; i += 4) {
531
- md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
114
+ return JSON.stringify(value);
115
+ case "promise":
116
+ opts.asyncContent.push({
117
+ id,
118
+ promise: value.then((result) => ({
119
+ id,
120
+ value: result,
121
+ asyncContent: opts.asyncContent
122
+ }))
123
+ });
124
+ return render(_htmlPlaceholder(id));
125
+ case "generator":
126
+ throw new Error("Generators are not supported as a template value at this time. Sorry :(");
532
127
  }
533
- return md5blks;
534
- }
535
- function rhex(n) {
536
- var s = "", j = 0;
537
- for (;j < 4; j++)
538
- s += hex_chr[n >> j * 8 + 4 & 15] + hex_chr[n >> j * 8 & 15];
539
- return s;
540
- }
541
- function hex(x) {
542
- for (var i = 0;i < x.length; i++)
543
- x[i] = rhex(x[i]);
544
- return x.join("");
128
+ return escapeHtml(String(value));
545
129
  }
546
- function add32(a, b) {
547
- return a + b & 4294967295;
130
+ function _htmlPlaceholder(id, content = "Loading...") {
131
+ return html`<!--hs:loading:${id}--><slot id="${id}">${content}</slot><!--/hs:loading:${id}-->`;
548
132
  }
549
- function md5(s) {
550
- return hex(md51(s));
551
- }
552
- var hex_chr = "0123456789abcdef".split("");
553
-
554
- // src/html.ts
555
- function html(strings, ...values) {
556
- const content = [];
557
- if (values.length === 0) {
558
- content.push({ kind: "string_safe", value: strings.join("\n") });
559
- return new HSTemplate(content);
560
- }
561
- let i = 0;
562
- for (i = 0;i < values.length; i++) {
563
- content.push({ kind: "string_safe", value: strings[i] });
564
- let tValue = values[i] === undefined || values[i] === null || values[i] === "" ? "" : values[i];
565
- if (!Array.isArray(tValue)) {
566
- tValue = [tValue];
567
- }
568
- for (let j = 0;j < tValue.length; j++) {
569
- content.push({ kind: _typeOf(tValue[j]), value: tValue[j] });
570
- }
571
- }
572
- content.push({ kind: "string_safe", value: strings[i] });
573
- return new HSTemplate(content);
574
- }
575
- async function* _render(obj, promises = [], { js }) {
576
- let { kind, value } = obj;
577
- let id = randomId();
578
- if (!kind || !value) {
579
- kind = _typeOf(obj);
580
- value = obj;
581
- }
582
- if (value instanceof HSTemplate || value.__hsTemplate) {
583
- yield* renderToStream(value);
584
- } else if (typeof value.render !== "undefined") {
585
- value.id = id;
586
- yield await value.render();
587
- } else if (value === undefined || value === null) {
588
- yield "";
589
- } else {
590
- switch (kind) {
591
- case "string":
592
- yield import_escape_html.default(value);
593
- break;
594
- case "string_safe":
595
- yield value;
596
- break;
597
- case "array":
598
- yield* value;
599
- break;
600
- case "promise":
601
- const promise = value.then((v) => {
602
- return _render(v, promises, { js });
603
- });
604
- const pid = "async_" + id;
605
- promises.push({ id: pid, pending: true, promise });
606
- yield* renderToStream(html`<div id="${pid}">Loading...</div>`);
607
- break;
608
- case "function":
609
- const fns = renderFunctionToString(value);
610
- const fnId = "fn_" + md5(fns);
611
- if (!IS_CLIENT || !window.hyperspan._fn.has(fnId)) {
612
- js.push(`hyperspan.fn('${fnId}', ${fns});`);
613
- }
614
- yield `"hyperspan:${fnId}"`;
615
- break;
616
- case "json":
617
- yield "";
618
- break;
619
- case "number":
620
- yield String(value);
621
- break;
622
- case "object":
623
- if (typeof value.render === "function") {
624
- yield value.render();
625
- } else if (typeof value.toString === "function") {
626
- yield value.toString();
627
- } else {
628
- yield value;
629
- }
630
- break;
631
- case "generator":
632
- yield* value;
633
- break;
634
- case "date":
635
- yield value.toISOString();
636
- break;
637
- default:
638
- yield String(value);
639
- }
640
- }
133
+ function render(tmpl) {
134
+ return tmpl.content;
641
135
  }
642
- async function* renderToStream(template) {
643
- let promises = [];
644
- let js = [];
645
- if (typeof template === "string") {
646
- return template;
647
- }
648
- for (let i = 0;i < template.content.length; i++) {
649
- yield* _render(template.content[i], promises, { js });
650
- }
651
- while (promises.length > 0) {
652
- const promisesToRun = promises.map((p) => p.promise.then((v) => {
653
- return { id: p.id, pending: false, value: v, promise: null };
654
- }));
655
- const result = await Promise.race(promisesToRun);
656
- yield* renderToStream(html`<template id="${result.id}_content">${result.value}</template>`);
657
- promises = promises.filter((p) => {
658
- return p.id !== result.id;
136
+ async function renderAsync(tmpl) {
137
+ let { content, asyncContent } = tmpl;
138
+ while (asyncContent.length !== 0) {
139
+ const resolvedHtml = await Promise.all(asyncContent.map((p) => p.promise));
140
+ asyncContent = [];
141
+ resolvedHtml.map((obj) => {
142
+ const r = new RegExp(`<!--hs:loading:${obj.id}-->(.*?)<!--/hs:loading:${obj.id}-->`);
143
+ const found = content.match(r);
144
+ if (found) {
145
+ content = content.replace(found[0], _renderValue(obj.value, { asyncContent }));
146
+ }
659
147
  });
660
148
  }
661
- if (js.length !== 0) {
662
- yield "<script>" + js.join("\n") + "</script>";
663
- }
149
+ return content;
664
150
  }
665
- async function renderToString(template) {
666
- let result = "";
667
- for await (const chunk of renderToStream(template)) {
668
- result += chunk;
151
+ async function* renderStream(tmpl) {
152
+ yield render(tmpl);
153
+ let asyncContent = tmpl.asyncContent;
154
+ while (asyncContent.length > 0) {
155
+ const nextContent = await Promise.race(asyncContent.map((p) => p.promise));
156
+ asyncContent = asyncContent.filter((p) => p.id !== nextContent.id);
157
+ const id = nextContent.id;
158
+ const content = _renderValue(nextContent.value, {
159
+ asyncContent
160
+ });
161
+ const script = html`<template id="${id}_content">${html.raw(content)}</template>`;
162
+ yield render(script);
669
163
  }
670
- return result;
671
- }
672
- function randomId() {
673
- return Math.random().toString(36).substring(2, 9);
674
164
  }
675
165
  function _typeOf(obj) {
676
166
  if (obj instanceof Promise)
@@ -688,55 +178,23 @@ function _typeOf(obj) {
688
178
  if (Array.isArray(obj))
689
179
  return "array";
690
180
  if (Number.isNaN(obj))
691
- return "nan";
181
+ return "NaN";
692
182
  if (obj === undefined)
693
183
  return "undefined";
694
184
  if (obj === null)
695
185
  return "null";
696
186
  if (isGenerator(obj))
697
187
  return "generator";
698
- if (isPlainObject(obj))
699
- return "json";
700
188
  return typeof obj;
701
189
  }
702
190
  function isGenerator(obj) {
703
191
  return obj && typeof obj.next == "function" && typeof obj.throw == "function";
704
192
  }
705
- function isPlainObject(val) {
706
- return Object == val.constructor;
707
- }
708
- function renderFunctionToString(fn) {
709
- let fns = fn.toString();
710
- const firstLine = fns.split("\n")[0];
711
- const isFatArrow = firstLine.includes("=>");
712
- const isAsync = firstLine.includes("async");
713
- const hasFunctionWord = firstLine.includes("function");
714
- if (isFatArrow) {
715
- fns = "function (...args) { return (" + fns + ")(..args); }";
716
- } else {
717
- if (!hasFunctionWord) {
718
- fns = "function " + fns;
719
- }
720
- }
721
- if (isAsync) {
722
- fns = "async " + fns.replace("async ", "");
723
- }
724
- return fns;
725
- }
726
- var IS_CLIENT = typeof window !== "undefined";
727
-
728
- class HSTemplate {
729
- __hsTemplate = true;
730
- content;
731
- constructor(content) {
732
- this.content = content;
733
- }
734
- }
735
- html.raw = (value) => {
736
- return new HSTemplate([{ kind: "string_safe", value }]);
737
- };
738
193
 
739
- // node_modules/isbot/index.mjs
194
+ // ../../node_modules/isbot/index.mjs
195
+ var fullPattern = " daum[ /]| deusu/| yadirectfetcher|(?:^|[^g])news(?!sapphire)|(?<! (?:channel/|google/))google(?!(app|/google| pixel))|(?<! cu)bots?(?:\\b|_)|(?<!(?:lib))http|(?<![hg]m)score|@[a-z][\\w-]+\\.|\\(\\)|\\.com\\b|\\btime/|\\||^<|^[\\w \\.\\-\\(?:\\):%]+(?:/v?\\d+(?:\\.\\d+)?(?:\\.\\d{1,10})*?)?(?:,|$)|^[^ ]{50,}$|^\\d+\\b|^\\w*search\\b|^\\w+/[\\w\\(\\)]*$|^active|^ad muncher|^amaya|^avsdevicesdk/|^biglotron|^bot|^bw/|^clamav[ /]|^client/|^cobweb/|^custom|^ddg[_-]android|^discourse|^dispatch/\\d|^downcast/|^duckduckgo|^email|^facebook|^getright/|^gozilla/|^hobbit|^hotzonu|^hwcdn/|^igetter/|^jeode/|^jetty/|^jigsaw|^microsoft bits|^movabletype|^mozilla/\\d\\.\\d\\s[\\w\\.-]+$|^mozilla/\\d\\.\\d\\s\\(compatible;?(?:\\s\\w+\\/\\d+\\.\\d+)?\\)$|^navermailapp|^netsurf|^offline|^openai/|^owler|^php|^postman|^python|^rank|^read|^reed|^rest|^rss|^snapchat|^space bison|^svn|^swcd |^taringa|^thumbor/|^track|^w3c|^webbandit/|^webcopier|^wget|^whatsapp|^wordpress|^xenu link sleuth|^yahoo|^yandex|^zdm/\\d|^zoom marketplace/|^{{.*}}$|adscanner/|analyzer|archive|ask jeeves/teoma|audit|bit\\.ly/|bluecoat drtr|browsex|burpcollaborator|capture|catch|check\\b|checker|chrome-lighthouse|chromeframe|classifier|cloudflare|convertify|cookiehubscan|crawl|cypress/|dareboost|datanyze|dejaclick|detect|dmbrowser|download|evc-batch/|exaleadcloudview|feed|firephp|functionize|gomezagent|headless|httrack|hubspot marketing grader|hydra|ibisbrowser|infrawatch|insight|inspect|iplabel|ips-agent|java(?!;)|jsjcw_scanner|library|linkcheck|mail\\.ru/|manager|measure|neustar wpm|node|nutch|offbyone|onetrust|optimize|pageburst|pagespeed|parser|perl|phantomjs|pingdom|powermarks|preview|proxy|ptst[ /]\\d|retriever|rexx;|rigor|rss\\b|scanner\\.|scrape|server|sogou|sparkler/|speedcurve|spider|splash|statuscake|supercleaner|synapse|synthetic|tools|torrent|transcoder|url|validator|virtuoso|wappalyzer|webglance|webkit2png|whatcms/|zgrab";
196
+ var naivePattern = /bot|crawl|http|lighthouse|scan|search|spider/i;
197
+ var pattern;
740
198
  function getPattern() {
741
199
  if (pattern instanceof RegExp) {
742
200
  return pattern;
@@ -751,1005 +209,2119 @@ function getPattern() {
751
209
  function isbot(userAgent) {
752
210
  return Boolean(userAgent) && getPattern().test(userAgent);
753
211
  }
754
- var fullPattern = " daum[ /]| deusu/| yadirectfetcher|(?:^|[^g])news(?!sapphire)|(?<! (?:channel/|google/))google(?!(app|/google| pixel))|(?<! cu)bots?(?:\\b|_)|(?<!(?:lib))http|(?<![hg]m)score|@[a-z][\\w-]+\\.|\\(\\)|\\.com\\b|\\btime/|^<|^[\\w \\.\\-\\(?:\\):]+(?:/v?\\d+(?:\\.\\d+)?(?:\\.\\d{1,10})*?)?(?:,|$)|^[^ ]{50,}$|^\\d+\\b|^\\w*search\\b|^\\w+/[\\w\\(\\)]*$|^active|^ad muncher|^amaya|^avsdevicesdk/|^biglotron|^bot|^bw/|^clamav[ /]|^client/|^cobweb/|^custom|^ddg[_-]android|^discourse|^dispatch/\\d|^downcast/|^duckduckgo|^facebook|^getright/|^gozilla/|^hobbit|^hotzonu|^hwcdn/|^jeode/|^jetty/|^jigsaw|^microsoft bits|^movabletype|^mozilla/5\\.0\\s[a-z\\.-]+$|^mozilla/\\d\\.\\d \\(compatible;?\\)$|^mozilla/\\d\\.\\d \\w*$|^navermailapp|^netsurf|^offline|^owler|^php|^postman|^python|^rank|^read|^reed|^rest|^rss|^snapchat|^space bison|^svn|^swcd |^taringa|^thumbor/|^track|^valid|^w3c|^webbandit/|^webcopier|^wget|^whatsapp|^wordpress|^xenu link sleuth|^yahoo|^yandex|^zdm/\\d|^zoom marketplace/|^{{.*}}$|adscanner/|analyzer|archive|ask jeeves/teoma|bit\\.ly/|bluecoat drtr|browsex|burpcollaborator|capture|catch|check\\b|checker|chrome-lighthouse|chromeframe|classifier|cloudflare|convertify|crawl|cypress/|dareboost|datanyze|dejaclick|detect|dmbrowser|download|evc-batch/|exaleadcloudview|feed|firephp|functionize|gomezagent|headless|httrack|hubspot marketing grader|hydra|ibisbrowser|images|infrawatch|insight|inspect|iplabel|ips-agent|java(?!;)|jsjcw_scanner|library|linkcheck|mail\\.ru/|manager|measure|neustar wpm|node|nutch|offbyone|optimize|pageburst|pagespeed|parser|perl|phantomjs|pingdom|powermarks|preview|proxy|ptst[ /]\\d|reputation|resolver|retriever|rexx;|rigor|rss\\b|scanner\\.|scrape|server|sogou|sparkler/|speedcurve|spider|splash|statuscake|supercleaner|synapse|synthetic|tools|torrent|trace|transcoder|url|virtuoso|wappalyzer|webglance|webkit2png|whatcms/|zgrab";
755
- var naivePattern = /bot|crawl|http|lighthouse|scan|search|spider/i;
756
- var pattern;
757
212
 
758
- // src/app.ts
759
- var import_trek_router = __toESM(require_trek_router(), 1);
760
- var import_trek_middleware = __toESM(require_trek_middleware(), 1);
761
- var import_deepmerge = __toESM(require_deepmerge(), 1);
213
+ // src/clientjs/md5.js
214
+ var hex_chr = "0123456789abcdef".split("");
762
215
 
763
- // node_modules/@mjackson/headers/dist/lib/param-values.js
764
- function parseParams(input, delimiter = ";") {
765
- let regex = /(?:^|;)\s*([^=;\s]+)(\s*=\s*(?:"((?:[^"\\]|\\.)*)"|((?:[^;]|\\\;)+))?)?/g;
766
- if (delimiter === ",") {
767
- regex = /(?:^|,)\s*([^=,\s]+)(\s*=\s*(?:"((?:[^"\\]|\\.)*)"|((?:[^,]|\\\,)+))?)?/g;
768
- }
769
- let params = [];
770
- let match;
771
- while ((match = regex.exec(input)) !== null) {
772
- let key = match[1].trim();
773
- let value;
774
- if (match[2]) {
775
- value = (match[3] || match[4] || "").replace(/\\(.)/g, "$1").trim();
216
+ // src/assets.ts
217
+ import { readdir } from "node:fs/promises";
218
+ import { resolve } from "node:path";
219
+ var IS_PROD = false;
220
+ var PWD = import.meta.dir;
221
+ var clientJSFiles = new Map;
222
+ async function buildClientJS() {
223
+ const sourceFile = resolve(PWD, "../", "./hyperspan/clientjs/hyperspan-client.ts");
224
+ const output = await Bun.build({
225
+ entrypoints: [sourceFile],
226
+ outdir: `./public/_hs/js`,
227
+ naming: IS_PROD ? "[dir]/[name]-[hash].[ext]" : undefined,
228
+ minify: IS_PROD
229
+ });
230
+ const jsFile = output.outputs[0].path.split("/").reverse()[0];
231
+ clientJSFiles.set("_hs", { src: "/_hs/js/" + jsFile });
232
+ return jsFile;
233
+ }
234
+ var clientCSSFiles = new Map;
235
+ async function buildClientCSS() {
236
+ if (clientCSSFiles.has("_hs")) {
237
+ return clientCSSFiles.get("_hs");
238
+ }
239
+ const cssDir = "./public/_hs/css/";
240
+ const cssFiles = await readdir(cssDir);
241
+ let foundCSSFile = "";
242
+ for (const file of cssFiles) {
243
+ if (!file.endsWith(".css")) {
244
+ continue;
776
245
  }
777
- params.push([key, value]);
246
+ foundCSSFile = file.replace(cssDir, "");
247
+ clientCSSFiles.set("_hs", foundCSSFile);
248
+ break;
778
249
  }
779
- return params;
780
- }
781
- function quote(value) {
782
- if (value.includes('"') || value.includes(";") || value.includes(" ")) {
783
- return `"${value.replace(/"/g, '\\"')}"`;
250
+ if (!foundCSSFile) {
251
+ console.log(`Unable to build CSS files from ${cssDir}`);
784
252
  }
785
- return value;
786
253
  }
787
254
 
788
- // node_modules/@mjackson/headers/dist/lib/utils.js
789
- function capitalize(str) {
790
- return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
791
- }
792
- function isIterable(value) {
793
- return value != null && typeof value[Symbol.iterator] === "function";
794
- }
795
- function isValidDate(date) {
796
- return date instanceof Date && !isNaN(date.getTime());
797
- }
798
-
799
- // node_modules/@mjackson/headers/dist/lib/accept-language.js
800
- class AcceptLanguage {
801
- #map;
802
- constructor(init) {
803
- this.#map = new Map;
804
- if (init) {
805
- if (typeof init === "string") {
806
- let params = parseParams(init, ",");
807
- for (let [language, quality] of params) {
808
- if (typeof quality === "string") {
809
- language = language.slice(0, -2).trim();
255
+ // ../../node_modules/hono/dist/compose.js
256
+ var compose = (middleware, onError, onNotFound) => {
257
+ return (context, next) => {
258
+ let index = -1;
259
+ return dispatch(0);
260
+ async function dispatch(i) {
261
+ if (i <= index) {
262
+ throw new Error("next() called multiple times");
263
+ }
264
+ index = i;
265
+ let res;
266
+ let isError = false;
267
+ let handler;
268
+ if (middleware[i]) {
269
+ handler = middleware[i][0][0];
270
+ context.req.routeIndex = i;
271
+ } else {
272
+ handler = i === middleware.length && next || undefined;
273
+ }
274
+ if (handler) {
275
+ try {
276
+ res = await handler(context, () => dispatch(i + 1));
277
+ } catch (err) {
278
+ if (err instanceof Error && onError) {
279
+ context.error = err;
280
+ res = await onError(err, context);
281
+ isError = true;
810
282
  } else {
811
- quality = "1";
812
- }
813
- this.#map.set(language, Number(quality));
814
- }
815
- } else if (isIterable(init)) {
816
- for (let language of init) {
817
- let quality;
818
- if (Array.isArray(language)) {
819
- [language, quality] = language;
283
+ throw err;
820
284
  }
821
- this.#map.set(language, quality ?? 1);
822
285
  }
823
286
  } else {
824
- for (let language in init) {
825
- if (Object.prototype.hasOwnProperty.call(init, language)) {
826
- this.#map.set(language, init[language] ?? 1);
827
- }
287
+ if (context.finalized === false && onNotFound) {
288
+ res = await onNotFound(context);
828
289
  }
829
290
  }
830
- this.#sort();
291
+ if (res && (context.finalized === false || isError)) {
292
+ context.res = res;
293
+ }
294
+ return context;
831
295
  }
296
+ };
297
+ };
298
+
299
+ // ../../node_modules/hono/dist/utils/body.js
300
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
301
+ const { all = false, dot = false } = options;
302
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
303
+ const contentType = headers.get("Content-Type");
304
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
305
+ return parseFormData(request, { all, dot });
306
+ }
307
+ return {};
308
+ };
309
+ async function parseFormData(request, options) {
310
+ const formData = await request.formData();
311
+ if (formData) {
312
+ return convertFormDataToBodyData(formData, options);
832
313
  }
833
- #sort() {
834
- this.#map = new Map([...this.#map].sort(([, a], [, b]) => b - a));
835
- }
836
- get(language) {
837
- return this.#map.get(language);
838
- }
839
- set(language, quality = 1) {
840
- this.#map.set(language, quality);
841
- this.#sort();
842
- }
843
- delete(language) {
844
- return this.#map.delete(language);
845
- }
846
- has(language) {
847
- return this.#map.has(language);
848
- }
849
- clear() {
850
- this.#map.clear();
314
+ return {};
315
+ }
316
+ function convertFormDataToBodyData(formData, options) {
317
+ const form = /* @__PURE__ */ Object.create(null);
318
+ formData.forEach((value, key) => {
319
+ const shouldParseAllValues = options.all || key.endsWith("[]");
320
+ if (!shouldParseAllValues) {
321
+ form[key] = value;
322
+ } else {
323
+ handleParsingAllValues(form, key, value);
324
+ }
325
+ });
326
+ if (options.dot) {
327
+ Object.entries(form).forEach(([key, value]) => {
328
+ const shouldParseDotValues = key.includes(".");
329
+ if (shouldParseDotValues) {
330
+ handleParsingNestedValues(form, key, value);
331
+ delete form[key];
332
+ }
333
+ });
851
334
  }
852
- entries() {
853
- return this.#map.entries();
335
+ return form;
336
+ }
337
+ var handleParsingAllValues = (form, key, value) => {
338
+ if (form[key] !== undefined) {
339
+ if (Array.isArray(form[key])) {
340
+ form[key].push(value);
341
+ } else {
342
+ form[key] = [form[key], value];
343
+ }
344
+ } else {
345
+ form[key] = value;
854
346
  }
855
- get languages() {
856
- return Array.from(this.#map.keys());
347
+ };
348
+ var handleParsingNestedValues = (form, key, value) => {
349
+ let nestedForm = form;
350
+ const keys = key.split(".");
351
+ keys.forEach((key2, index) => {
352
+ if (index === keys.length - 1) {
353
+ nestedForm[key2] = value;
354
+ } else {
355
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
356
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
357
+ }
358
+ nestedForm = nestedForm[key2];
359
+ }
360
+ });
361
+ };
362
+
363
+ // ../../node_modules/hono/dist/utils/url.js
364
+ var splitPath = (path) => {
365
+ const paths = path.split("/");
366
+ if (paths[0] === "") {
367
+ paths.shift();
857
368
  }
858
- get qualities() {
859
- return Array.from(this.#map.values());
369
+ return paths;
370
+ };
371
+ var splitRoutingPath = (routePath) => {
372
+ const { groups, path } = extractGroupsFromPath(routePath);
373
+ const paths = splitPath(path);
374
+ return replaceGroupMarks(paths, groups);
375
+ };
376
+ var extractGroupsFromPath = (path) => {
377
+ const groups = [];
378
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
379
+ const mark = `@${index}`;
380
+ groups.push([mark, match]);
381
+ return mark;
382
+ });
383
+ return { groups, path };
384
+ };
385
+ var replaceGroupMarks = (paths, groups) => {
386
+ for (let i = groups.length - 1;i >= 0; i--) {
387
+ const [mark] = groups[i];
388
+ for (let j = paths.length - 1;j >= 0; j--) {
389
+ if (paths[j].includes(mark)) {
390
+ paths[j] = paths[j].replace(mark, groups[i][1]);
391
+ break;
392
+ }
393
+ }
860
394
  }
861
- [Symbol.iterator]() {
862
- return this.entries();
395
+ return paths;
396
+ };
397
+ var patternCache = {};
398
+ var getPattern2 = (label, next) => {
399
+ if (label === "*") {
400
+ return "*";
401
+ }
402
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
403
+ if (match) {
404
+ const cacheKey = `${label}#${next}`;
405
+ if (!patternCache[cacheKey]) {
406
+ if (match[2]) {
407
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
408
+ } else {
409
+ patternCache[cacheKey] = [label, match[1], true];
410
+ }
411
+ }
412
+ return patternCache[cacheKey];
863
413
  }
864
- forEach(callback, thisArg) {
865
- this.#map.forEach((quality, language, map) => callback(language, quality, map), thisArg);
414
+ return null;
415
+ };
416
+ var tryDecode = (str, decoder) => {
417
+ try {
418
+ return decoder(str);
419
+ } catch {
420
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
421
+ try {
422
+ return decoder(match);
423
+ } catch {
424
+ return match;
425
+ }
426
+ });
866
427
  }
867
- get size() {
868
- return this.#map.size;
428
+ };
429
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
430
+ var getPath = (request) => {
431
+ const url = request.url;
432
+ const start = url.indexOf("/", 8);
433
+ let i = start;
434
+ for (;i < url.length; i++) {
435
+ const charCode = url.charCodeAt(i);
436
+ if (charCode === 37) {
437
+ const queryIndex = url.indexOf("?", i);
438
+ const path = url.slice(start, queryIndex === -1 ? undefined : queryIndex);
439
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
440
+ } else if (charCode === 63) {
441
+ break;
442
+ }
443
+ }
444
+ return url.slice(start, i);
445
+ };
446
+ var getPathNoStrict = (request) => {
447
+ const result = getPath(request);
448
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
449
+ };
450
+ var mergePath = (base, sub, ...rest) => {
451
+ if (rest.length) {
452
+ sub = mergePath(sub, ...rest);
869
453
  }
870
- toString() {
871
- let pairs = [];
872
- for (let [language, quality] of this.#map) {
873
- pairs.push(`${language}${quality === 1 ? "" : `;q=${quality}`}`);
874
- }
875
- return pairs.join(",");
454
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
455
+ };
456
+ var checkOptionalParameter = (path) => {
457
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
458
+ return null;
876
459
  }
877
- }
878
- // node_modules/@mjackson/headers/dist/lib/cache-control.js
879
- class CacheControl {
880
- maxAge;
881
- maxStale;
882
- minFresh;
883
- sMaxage;
884
- noCache;
885
- noStore;
886
- noTransform;
887
- onlyIfCached;
888
- mustRevalidate;
889
- proxyRevalidate;
890
- mustUnderstand;
891
- private;
892
- public;
893
- immutable;
894
- staleWhileRevalidate;
895
- staleIfError;
896
- constructor(init) {
897
- if (init) {
898
- if (typeof init === "string") {
899
- let params = parseParams(init, ",");
900
- if (params.length > 0) {
901
- for (let [name, value] of params) {
902
- switch (name) {
903
- case "max-age":
904
- this.maxAge = Number(value);
905
- break;
906
- case "max-stale":
907
- this.maxStale = Number(value);
908
- break;
909
- case "min-fresh":
910
- this.minFresh = Number(value);
911
- break;
912
- case "s-maxage":
913
- this.sMaxage = Number(value);
914
- break;
915
- case "no-cache":
916
- this.noCache = true;
917
- break;
918
- case "no-store":
919
- this.noStore = true;
920
- break;
921
- case "no-transform":
922
- this.noTransform = true;
923
- break;
924
- case "only-if-cached":
925
- this.onlyIfCached = true;
926
- break;
927
- case "must-revalidate":
928
- this.mustRevalidate = true;
929
- break;
930
- case "proxy-revalidate":
931
- this.proxyRevalidate = true;
932
- break;
933
- case "must-understand":
934
- this.mustUnderstand = true;
935
- break;
936
- case "private":
937
- this.private = true;
938
- break;
939
- case "public":
940
- this.public = true;
941
- break;
942
- case "immutable":
943
- this.immutable = true;
944
- break;
945
- case "stale-while-revalidate":
946
- this.staleWhileRevalidate = Number(value);
947
- break;
948
- case "stale-if-error":
949
- this.staleIfError = Number(value);
950
- break;
951
- }
952
- }
460
+ const segments = path.split("/");
461
+ const results = [];
462
+ let basePath = "";
463
+ segments.forEach((segment) => {
464
+ if (segment !== "" && !/\:/.test(segment)) {
465
+ basePath += "/" + segment;
466
+ } else if (/\:/.test(segment)) {
467
+ if (/\?/.test(segment)) {
468
+ if (results.length === 0 && basePath === "") {
469
+ results.push("/");
470
+ } else {
471
+ results.push(basePath);
953
472
  }
473
+ const optionalSegment = segment.replace("?", "");
474
+ basePath += "/" + optionalSegment;
475
+ results.push(basePath);
954
476
  } else {
955
- this.maxAge = init.maxAge;
956
- this.maxStale = init.maxStale;
957
- this.minFresh = init.minFresh;
958
- this.sMaxage = init.sMaxage;
959
- this.noCache = init.noCache;
960
- this.noStore = init.noStore;
961
- this.noTransform = init.noTransform;
962
- this.onlyIfCached = init.onlyIfCached;
963
- this.mustRevalidate = init.mustRevalidate;
964
- this.proxyRevalidate = init.proxyRevalidate;
965
- this.mustUnderstand = init.mustUnderstand;
966
- this.private = init.private;
967
- this.public = init.public;
968
- this.immutable = init.immutable;
969
- this.staleWhileRevalidate = init.staleWhileRevalidate;
970
- this.staleIfError = init.staleIfError;
477
+ basePath += "/" + segment;
971
478
  }
972
479
  }
480
+ });
481
+ return results.filter((v, i, a) => a.indexOf(v) === i);
482
+ };
483
+ var _decodeURI = (value) => {
484
+ if (!/[%+]/.test(value)) {
485
+ return value;
973
486
  }
974
- toString() {
975
- let parts = [];
976
- if (this.public) {
977
- parts.push("public");
978
- }
979
- if (this.private) {
980
- parts.push("private");
981
- }
982
- if (typeof this.maxAge === "number") {
983
- parts.push(`max-age=${this.maxAge}`);
487
+ if (value.indexOf("+") !== -1) {
488
+ value = value.replace(/\+/g, " ");
489
+ }
490
+ return value.indexOf("%") !== -1 ? decodeURIComponent_(value) : value;
491
+ };
492
+ var _getQueryParam = (url, key, multiple) => {
493
+ let encoded;
494
+ if (!multiple && key && !/[%+]/.test(key)) {
495
+ let keyIndex2 = url.indexOf(`?${key}`, 8);
496
+ if (keyIndex2 === -1) {
497
+ keyIndex2 = url.indexOf(`&${key}`, 8);
498
+ }
499
+ while (keyIndex2 !== -1) {
500
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
501
+ if (trailingKeyCode === 61) {
502
+ const valueIndex = keyIndex2 + key.length + 2;
503
+ const endIndex = url.indexOf("&", valueIndex);
504
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
505
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
506
+ return "";
507
+ }
508
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
984
509
  }
985
- if (typeof this.sMaxage === "number") {
986
- parts.push(`s-maxage=${this.sMaxage}`);
510
+ encoded = /[%+]/.test(url);
511
+ if (!encoded) {
512
+ return;
987
513
  }
988
- if (this.noCache) {
989
- parts.push("no-cache");
514
+ }
515
+ const results = {};
516
+ encoded ??= /[%+]/.test(url);
517
+ let keyIndex = url.indexOf("?", 8);
518
+ while (keyIndex !== -1) {
519
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
520
+ let valueIndex = url.indexOf("=", keyIndex);
521
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
522
+ valueIndex = -1;
990
523
  }
991
- if (this.noStore) {
992
- parts.push("no-store");
524
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
525
+ if (encoded) {
526
+ name = _decodeURI(name);
993
527
  }
994
- if (this.noTransform) {
995
- parts.push("no-transform");
528
+ keyIndex = nextKeyIndex;
529
+ if (name === "") {
530
+ continue;
996
531
  }
997
- if (this.onlyIfCached) {
998
- parts.push("only-if-cached");
532
+ let value;
533
+ if (valueIndex === -1) {
534
+ value = "";
535
+ } else {
536
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
537
+ if (encoded) {
538
+ value = _decodeURI(value);
539
+ }
999
540
  }
1000
- if (this.mustRevalidate) {
1001
- parts.push("must-revalidate");
541
+ if (multiple) {
542
+ if (!(results[name] && Array.isArray(results[name]))) {
543
+ results[name] = [];
544
+ }
545
+ results[name].push(value);
546
+ } else {
547
+ results[name] ??= value;
1002
548
  }
1003
- if (this.proxyRevalidate) {
1004
- parts.push("proxy-revalidate");
549
+ }
550
+ return key ? results[key] : results;
551
+ };
552
+ var getQueryParam = _getQueryParam;
553
+ var getQueryParams = (url, key) => {
554
+ return _getQueryParam(url, key, true);
555
+ };
556
+ var decodeURIComponent_ = decodeURIComponent;
557
+
558
+ // ../../node_modules/hono/dist/request.js
559
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
560
+ var HonoRequest = class {
561
+ raw;
562
+ #validatedData;
563
+ #matchResult;
564
+ routeIndex = 0;
565
+ path;
566
+ bodyCache = {};
567
+ constructor(request, path = "/", matchResult = [[]]) {
568
+ this.raw = request;
569
+ this.path = path;
570
+ this.#matchResult = matchResult;
571
+ this.#validatedData = {};
572
+ }
573
+ param(key) {
574
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
575
+ }
576
+ #getDecodedParam(key) {
577
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
578
+ const param = this.#getParamValue(paramKey);
579
+ return param ? /\%/.test(param) ? tryDecodeURIComponent(param) : param : undefined;
580
+ }
581
+ #getAllDecodedParams() {
582
+ const decoded = {};
583
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
584
+ for (const key of keys) {
585
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
586
+ if (value && typeof value === "string") {
587
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
588
+ }
1005
589
  }
1006
- if (this.mustUnderstand) {
1007
- parts.push("must-understand");
590
+ return decoded;
591
+ }
592
+ #getParamValue(paramKey) {
593
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
594
+ }
595
+ query(key) {
596
+ return getQueryParam(this.url, key);
597
+ }
598
+ queries(key) {
599
+ return getQueryParams(this.url, key);
600
+ }
601
+ header(name) {
602
+ if (name) {
603
+ return this.raw.headers.get(name) ?? undefined;
1008
604
  }
1009
- if (this.immutable) {
1010
- parts.push("immutable");
605
+ const headerData = {};
606
+ this.raw.headers.forEach((value, key) => {
607
+ headerData[key] = value;
608
+ });
609
+ return headerData;
610
+ }
611
+ async parseBody(options) {
612
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
613
+ }
614
+ #cachedBody = (key) => {
615
+ const { bodyCache, raw } = this;
616
+ const cachedBody = bodyCache[key];
617
+ if (cachedBody) {
618
+ return cachedBody;
619
+ }
620
+ const anyCachedKey = Object.keys(bodyCache)[0];
621
+ if (anyCachedKey) {
622
+ return bodyCache[anyCachedKey].then((body) => {
623
+ if (anyCachedKey === "json") {
624
+ body = JSON.stringify(body);
625
+ }
626
+ return new Response(body)[key]();
627
+ });
1011
628
  }
1012
- if (typeof this.staleWhileRevalidate === "number") {
1013
- parts.push(`stale-while-revalidate=${this.staleWhileRevalidate}`);
629
+ return bodyCache[key] = raw[key]();
630
+ };
631
+ json() {
632
+ return this.#cachedBody("json");
633
+ }
634
+ text() {
635
+ return this.#cachedBody("text");
636
+ }
637
+ arrayBuffer() {
638
+ return this.#cachedBody("arrayBuffer");
639
+ }
640
+ blob() {
641
+ return this.#cachedBody("blob");
642
+ }
643
+ formData() {
644
+ return this.#cachedBody("formData");
645
+ }
646
+ addValidatedData(target, data) {
647
+ this.#validatedData[target] = data;
648
+ }
649
+ valid(target) {
650
+ return this.#validatedData[target];
651
+ }
652
+ get url() {
653
+ return this.raw.url;
654
+ }
655
+ get method() {
656
+ return this.raw.method;
657
+ }
658
+ get matchedRoutes() {
659
+ return this.#matchResult[0].map(([[, route]]) => route);
660
+ }
661
+ get routePath() {
662
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
663
+ }
664
+ };
665
+
666
+ // ../../node_modules/hono/dist/utils/html.js
667
+ var HtmlEscapedCallbackPhase = {
668
+ Stringify: 1,
669
+ BeforeStream: 2,
670
+ Stream: 3
671
+ };
672
+ var raw = (value, callbacks) => {
673
+ const escapedString = new String(value);
674
+ escapedString.isEscaped = true;
675
+ escapedString.callbacks = callbacks;
676
+ return escapedString;
677
+ };
678
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
679
+ if (typeof str === "object" && !(str instanceof String)) {
680
+ if (!(str instanceof Promise)) {
681
+ str = str.toString();
1014
682
  }
1015
- if (typeof this.staleIfError === "number") {
1016
- parts.push(`stale-if-error=${this.staleIfError}`);
683
+ if (str instanceof Promise) {
684
+ str = await str;
1017
685
  }
1018
- if (typeof this.maxStale === "number") {
1019
- parts.push(`max-stale=${this.maxStale}`);
686
+ }
687
+ const callbacks = str.callbacks;
688
+ if (!callbacks?.length) {
689
+ return Promise.resolve(str);
690
+ }
691
+ if (buffer) {
692
+ buffer[0] += str;
693
+ } else {
694
+ buffer = [str];
695
+ }
696
+ 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]));
697
+ if (preserveCallbacks) {
698
+ return raw(await resStr, callbacks);
699
+ } else {
700
+ return resStr;
701
+ }
702
+ };
703
+
704
+ // ../../node_modules/hono/dist/context.js
705
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
706
+ var setHeaders = (headers, map = {}) => {
707
+ for (const key of Object.keys(map)) {
708
+ headers.set(key, map[key]);
709
+ }
710
+ return headers;
711
+ };
712
+ var Context = class {
713
+ #rawRequest;
714
+ #req;
715
+ env = {};
716
+ #var;
717
+ finalized = false;
718
+ error;
719
+ #status = 200;
720
+ #executionCtx;
721
+ #headers;
722
+ #preparedHeaders;
723
+ #res;
724
+ #isFresh = true;
725
+ #layout;
726
+ #renderer;
727
+ #notFoundHandler;
728
+ #matchResult;
729
+ #path;
730
+ constructor(req, options) {
731
+ this.#rawRequest = req;
732
+ if (options) {
733
+ this.#executionCtx = options.executionCtx;
734
+ this.env = options.env;
735
+ this.#notFoundHandler = options.notFoundHandler;
736
+ this.#path = options.path;
737
+ this.#matchResult = options.matchResult;
738
+ }
739
+ }
740
+ get req() {
741
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
742
+ return this.#req;
743
+ }
744
+ get event() {
745
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
746
+ return this.#executionCtx;
747
+ } else {
748
+ throw Error("This context has no FetchEvent");
1020
749
  }
1021
- if (typeof this.minFresh === "number") {
1022
- parts.push(`min-fresh=${this.minFresh}`);
750
+ }
751
+ get executionCtx() {
752
+ if (this.#executionCtx) {
753
+ return this.#executionCtx;
754
+ } else {
755
+ throw Error("This context has no ExecutionContext");
1023
756
  }
1024
- return parts.join(", ");
1025
757
  }
1026
- }
1027
- // node_modules/@mjackson/headers/dist/lib/content-disposition.js
1028
- function decodeFilenameSplat(value) {
1029
- let match = value.match(/^([\w-]+)'([^']*)'(.+)$/);
1030
- if (!match)
1031
- return null;
1032
- let [, charset, , encodedFilename] = match;
1033
- let decodedFilename = percentDecode(encodedFilename);
1034
- try {
1035
- let decoder = new TextDecoder(charset);
1036
- let bytes = new Uint8Array(decodedFilename.split("").map((char) => char.charCodeAt(0)));
1037
- return decoder.decode(bytes);
1038
- } catch (error) {
1039
- console.warn(`Failed to decode filename from charset ${charset}:`, error);
1040
- return decodedFilename;
758
+ get res() {
759
+ this.#isFresh = false;
760
+ return this.#res ||= new Response("404 Not Found", { status: 404 });
1041
761
  }
1042
- }
1043
- function percentDecode(value) {
1044
- return value.replace(/\+/g, " ").replace(/%([0-9A-Fa-f]{2})/g, (_, hex2) => {
1045
- return String.fromCharCode(parseInt(hex2, 16));
1046
- });
1047
- }
1048
-
1049
- class ContentDisposition {
1050
- filename;
1051
- filenameSplat;
1052
- name;
1053
- type;
1054
- constructor(init) {
1055
- if (init) {
1056
- if (typeof init === "string") {
1057
- let params = parseParams(init);
1058
- if (params.length > 0) {
1059
- this.type = params[0][0];
1060
- for (let [name, value] of params.slice(1)) {
1061
- if (name === "filename") {
1062
- this.filename = value;
1063
- } else if (name === "filename*") {
1064
- this.filenameSplat = value;
1065
- } else if (name === "name") {
1066
- this.name = value;
762
+ set res(_res) {
763
+ this.#isFresh = false;
764
+ if (this.#res && _res) {
765
+ try {
766
+ for (const [k, v] of this.#res.headers.entries()) {
767
+ if (k === "content-type") {
768
+ continue;
769
+ }
770
+ if (k === "set-cookie") {
771
+ const cookies = this.#res.headers.getSetCookie();
772
+ _res.headers.delete("set-cookie");
773
+ for (const cookie of cookies) {
774
+ _res.headers.append("set-cookie", cookie);
1067
775
  }
776
+ } else {
777
+ _res.headers.set(k, v);
1068
778
  }
1069
779
  }
1070
- } else {
1071
- this.filename = init.filename;
1072
- this.filenameSplat = init.filenameSplat;
1073
- this.name = init.name;
1074
- this.type = init.type;
780
+ } catch (e) {
781
+ if (e instanceof TypeError && e.message.includes("immutable")) {
782
+ this.res = new Response(_res.body, {
783
+ headers: _res.headers,
784
+ status: _res.status
785
+ });
786
+ return;
787
+ } else {
788
+ throw e;
789
+ }
1075
790
  }
1076
791
  }
792
+ this.#res = _res;
793
+ this.finalized = true;
1077
794
  }
1078
- get preferredFilename() {
1079
- let filenameSplat = this.filenameSplat;
1080
- if (filenameSplat) {
1081
- let decodedFilename = decodeFilenameSplat(filenameSplat);
1082
- if (decodedFilename)
1083
- return decodedFilename;
1084
- }
1085
- return this.filename;
1086
- }
1087
- toString() {
1088
- if (!this.type) {
1089
- return "";
795
+ render = (...args) => {
796
+ this.#renderer ??= (content) => this.html(content);
797
+ return this.#renderer(...args);
798
+ };
799
+ setLayout = (layout) => this.#layout = layout;
800
+ getLayout = () => this.#layout;
801
+ setRenderer = (renderer) => {
802
+ this.#renderer = renderer;
803
+ };
804
+ header = (name, value, options) => {
805
+ if (value === undefined) {
806
+ if (this.#headers) {
807
+ this.#headers.delete(name);
808
+ } else if (this.#preparedHeaders) {
809
+ delete this.#preparedHeaders[name.toLocaleLowerCase()];
810
+ }
811
+ if (this.finalized) {
812
+ this.res.headers.delete(name);
813
+ }
814
+ return;
1090
815
  }
1091
- let parts = [this.type];
1092
- if (this.name) {
1093
- parts.push(`name=${quote(this.name)}`);
816
+ if (options?.append) {
817
+ if (!this.#headers) {
818
+ this.#isFresh = false;
819
+ this.#headers = new Headers(this.#preparedHeaders);
820
+ this.#preparedHeaders = {};
821
+ }
822
+ this.#headers.append(name, value);
823
+ } else {
824
+ if (this.#headers) {
825
+ this.#headers.set(name, value);
826
+ } else {
827
+ this.#preparedHeaders ??= {};
828
+ this.#preparedHeaders[name.toLowerCase()] = value;
829
+ }
1094
830
  }
1095
- if (this.filename) {
1096
- parts.push(`filename=${quote(this.filename)}`);
831
+ if (this.finalized) {
832
+ if (options?.append) {
833
+ this.res.headers.append(name, value);
834
+ } else {
835
+ this.res.headers.set(name, value);
836
+ }
1097
837
  }
1098
- if (this.filenameSplat) {
1099
- parts.push(`filename*=${quote(this.filenameSplat)}`);
838
+ };
839
+ status = (status) => {
840
+ this.#isFresh = false;
841
+ this.#status = status;
842
+ };
843
+ set = (key, value) => {
844
+ this.#var ??= /* @__PURE__ */ new Map;
845
+ this.#var.set(key, value);
846
+ };
847
+ get = (key) => {
848
+ return this.#var ? this.#var.get(key) : undefined;
849
+ };
850
+ get var() {
851
+ if (!this.#var) {
852
+ return {};
1100
853
  }
1101
- return parts.join("; ");
854
+ return Object.fromEntries(this.#var);
1102
855
  }
1103
- }
1104
- // node_modules/@mjackson/headers/dist/lib/content-type.js
1105
- class ContentType {
1106
- boundary;
1107
- charset;
1108
- mediaType;
1109
- constructor(init) {
1110
- if (init) {
1111
- if (typeof init === "string") {
1112
- let params = parseParams(init);
1113
- if (params.length > 0) {
1114
- this.mediaType = params[0][0];
1115
- for (let [name, value] of params.slice(1)) {
1116
- if (name === "boundary") {
1117
- this.boundary = value;
1118
- } else if (name === "charset") {
1119
- this.charset = value;
1120
- }
856
+ #newResponse(data, arg, headers) {
857
+ if (this.#isFresh && !headers && !arg && this.#status === 200) {
858
+ return new Response(data, {
859
+ headers: this.#preparedHeaders
860
+ });
861
+ }
862
+ if (arg && typeof arg !== "number") {
863
+ const header = new Headers(arg.headers);
864
+ if (this.#headers) {
865
+ this.#headers.forEach((v, k) => {
866
+ if (k === "set-cookie") {
867
+ header.append(k, v);
868
+ } else {
869
+ header.set(k, v);
1121
870
  }
871
+ });
872
+ }
873
+ const headers2 = setHeaders(header, this.#preparedHeaders);
874
+ return new Response(data, {
875
+ headers: headers2,
876
+ status: arg.status ?? this.#status
877
+ });
878
+ }
879
+ const status = typeof arg === "number" ? arg : this.#status;
880
+ this.#preparedHeaders ??= {};
881
+ this.#headers ??= new Headers;
882
+ setHeaders(this.#headers, this.#preparedHeaders);
883
+ if (this.#res) {
884
+ this.#res.headers.forEach((v, k) => {
885
+ if (k === "set-cookie") {
886
+ this.#headers?.append(k, v);
887
+ } else {
888
+ this.#headers?.set(k, v);
1122
889
  }
890
+ });
891
+ setHeaders(this.#headers, this.#preparedHeaders);
892
+ }
893
+ headers ??= {};
894
+ for (const [k, v] of Object.entries(headers)) {
895
+ if (typeof v === "string") {
896
+ this.#headers.set(k, v);
1123
897
  } else {
1124
- this.boundary = init.boundary;
1125
- this.charset = init.charset;
1126
- this.mediaType = init.mediaType;
898
+ this.#headers.delete(k);
899
+ for (const v2 of v) {
900
+ this.#headers.append(k, v2);
901
+ }
1127
902
  }
1128
903
  }
904
+ return new Response(data, {
905
+ status,
906
+ headers: this.#headers
907
+ });
1129
908
  }
1130
- toString() {
1131
- if (!this.mediaType) {
1132
- return "";
909
+ newResponse = (...args) => this.#newResponse(...args);
910
+ body = (data, arg, headers) => {
911
+ return typeof arg === "number" ? this.#newResponse(data, arg, headers) : this.#newResponse(data, arg);
912
+ };
913
+ text = (text, arg, headers) => {
914
+ if (!this.#preparedHeaders) {
915
+ if (this.#isFresh && !headers && !arg) {
916
+ return new Response(text);
917
+ }
918
+ this.#preparedHeaders = {};
1133
919
  }
1134
- let parts = [this.mediaType];
1135
- if (this.charset) {
1136
- parts.push(`charset=${quote(this.charset)}`);
920
+ this.#preparedHeaders["content-type"] = TEXT_PLAIN;
921
+ if (typeof arg === "number") {
922
+ return this.#newResponse(text, arg, headers);
1137
923
  }
1138
- if (this.boundary) {
1139
- parts.push(`boundary=${quote(this.boundary)}`);
924
+ return this.#newResponse(text, arg);
925
+ };
926
+ json = (object, arg, headers) => {
927
+ const body = JSON.stringify(object);
928
+ this.#preparedHeaders ??= {};
929
+ this.#preparedHeaders["content-type"] = "application/json";
930
+ return typeof arg === "number" ? this.#newResponse(body, arg, headers) : this.#newResponse(body, arg);
931
+ };
932
+ html = (html2, arg, headers) => {
933
+ this.#preparedHeaders ??= {};
934
+ this.#preparedHeaders["content-type"] = "text/html; charset=UTF-8";
935
+ if (typeof html2 === "object") {
936
+ return resolveCallback(html2, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html22) => {
937
+ return typeof arg === "number" ? this.#newResponse(html22, arg, headers) : this.#newResponse(html22, arg);
938
+ });
1140
939
  }
1141
- return parts.join("; ");
940
+ return typeof arg === "number" ? this.#newResponse(html2, arg, headers) : this.#newResponse(html2, arg);
941
+ };
942
+ redirect = (location, status) => {
943
+ this.#headers ??= new Headers;
944
+ this.#headers.set("Location", String(location));
945
+ return this.newResponse(null, status ?? 302);
946
+ };
947
+ notFound = () => {
948
+ this.#notFoundHandler ??= () => new Response;
949
+ return this.#notFoundHandler(this);
950
+ };
951
+ };
952
+
953
+ // ../../node_modules/hono/dist/router.js
954
+ var METHOD_NAME_ALL = "ALL";
955
+ var METHOD_NAME_ALL_LOWERCASE = "all";
956
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
957
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
958
+ var UnsupportedPathError = class extends Error {
959
+ };
960
+
961
+ // ../../node_modules/hono/dist/utils/constants.js
962
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
963
+
964
+ // ../../node_modules/hono/dist/hono-base.js
965
+ var notFoundHandler = (c) => {
966
+ return c.text("404 Not Found", 404);
967
+ };
968
+ var errorHandler = (err, c) => {
969
+ if ("getResponse" in err) {
970
+ return err.getResponse();
1142
971
  }
1143
- }
1144
- // node_modules/@mjackson/headers/dist/lib/cookie.js
1145
- class Cookie {
1146
- #map;
1147
- constructor(init) {
1148
- this.#map = new Map;
1149
- if (init) {
1150
- if (typeof init === "string") {
1151
- let params = parseParams(init);
1152
- for (let [name, value] of params) {
1153
- this.#map.set(name, value || "");
972
+ console.error(err);
973
+ return c.text("Internal Server Error", 500);
974
+ };
975
+ var Hono = class {
976
+ get;
977
+ post;
978
+ put;
979
+ delete;
980
+ options;
981
+ patch;
982
+ all;
983
+ on;
984
+ use;
985
+ router;
986
+ getPath;
987
+ _basePath = "/";
988
+ #path = "/";
989
+ routes = [];
990
+ constructor(options = {}) {
991
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
992
+ allMethods.forEach((method) => {
993
+ this[method] = (args1, ...args) => {
994
+ if (typeof args1 === "string") {
995
+ this.#path = args1;
996
+ } else {
997
+ this.#addRoute(method, this.#path, args1);
1154
998
  }
1155
- } else if (isIterable(init)) {
1156
- for (let [name, value] of init) {
1157
- this.#map.set(name, value);
999
+ args.forEach((handler) => {
1000
+ this.#addRoute(method, this.#path, handler);
1001
+ });
1002
+ return this;
1003
+ };
1004
+ });
1005
+ this.on = (method, path, ...handlers) => {
1006
+ for (const p of [path].flat()) {
1007
+ this.#path = p;
1008
+ for (const m of [method].flat()) {
1009
+ handlers.map((handler) => {
1010
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
1011
+ });
1158
1012
  }
1013
+ }
1014
+ return this;
1015
+ };
1016
+ this.use = (arg1, ...handlers) => {
1017
+ if (typeof arg1 === "string") {
1018
+ this.#path = arg1;
1159
1019
  } else {
1160
- for (let name in init) {
1161
- if (Object.prototype.hasOwnProperty.call(init, name)) {
1162
- this.#map.set(name, init[name]);
1163
- }
1164
- }
1020
+ this.#path = "*";
1021
+ handlers.unshift(arg1);
1165
1022
  }
1166
- }
1167
- }
1168
- get(name) {
1169
- return this.#map.get(name);
1023
+ handlers.forEach((handler) => {
1024
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
1025
+ });
1026
+ return this;
1027
+ };
1028
+ const { strict, ...optionsWithoutStrict } = options;
1029
+ Object.assign(this, optionsWithoutStrict);
1030
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
1031
+ }
1032
+ #clone() {
1033
+ const clone = new Hono({
1034
+ router: this.router,
1035
+ getPath: this.getPath
1036
+ });
1037
+ clone.routes = this.routes;
1038
+ return clone;
1039
+ }
1040
+ #notFoundHandler = notFoundHandler;
1041
+ errorHandler = errorHandler;
1042
+ route(path, app) {
1043
+ const subApp = this.basePath(path);
1044
+ app.routes.map((r) => {
1045
+ let handler;
1046
+ if (app.errorHandler === errorHandler) {
1047
+ handler = r.handler;
1048
+ } else {
1049
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
1050
+ handler[COMPOSED_HANDLER] = r.handler;
1051
+ }
1052
+ subApp.#addRoute(r.method, r.path, handler);
1053
+ });
1054
+ return this;
1170
1055
  }
1171
- set(name, value) {
1172
- this.#map.set(name, value);
1056
+ basePath(path) {
1057
+ const subApp = this.#clone();
1058
+ subApp._basePath = mergePath(this._basePath, path);
1059
+ return subApp;
1173
1060
  }
1174
- delete(name) {
1175
- return this.#map.delete(name);
1061
+ onError = (handler) => {
1062
+ this.errorHandler = handler;
1063
+ return this;
1064
+ };
1065
+ notFound = (handler) => {
1066
+ this.#notFoundHandler = handler;
1067
+ return this;
1068
+ };
1069
+ mount(path, applicationHandler, options) {
1070
+ let replaceRequest;
1071
+ let optionHandler;
1072
+ if (options) {
1073
+ if (typeof options === "function") {
1074
+ optionHandler = options;
1075
+ } else {
1076
+ optionHandler = options.optionHandler;
1077
+ replaceRequest = options.replaceRequest;
1078
+ }
1079
+ }
1080
+ const getOptions = optionHandler ? (c) => {
1081
+ const options2 = optionHandler(c);
1082
+ return Array.isArray(options2) ? options2 : [options2];
1083
+ } : (c) => {
1084
+ let executionContext = undefined;
1085
+ try {
1086
+ executionContext = c.executionCtx;
1087
+ } catch {}
1088
+ return [c.env, executionContext];
1089
+ };
1090
+ replaceRequest ||= (() => {
1091
+ const mergedPath = mergePath(this._basePath, path);
1092
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
1093
+ return (request) => {
1094
+ const url = new URL(request.url);
1095
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
1096
+ return new Request(url, request);
1097
+ };
1098
+ })();
1099
+ const handler = async (c, next) => {
1100
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1101
+ if (res) {
1102
+ return res;
1103
+ }
1104
+ await next();
1105
+ };
1106
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
1107
+ return this;
1176
1108
  }
1177
- has(name) {
1178
- return this.#map.has(name);
1109
+ #addRoute(method, path, handler) {
1110
+ method = method.toUpperCase();
1111
+ path = mergePath(this._basePath, path);
1112
+ const r = { path, method, handler };
1113
+ this.router.add(method, path, [handler, r]);
1114
+ this.routes.push(r);
1115
+ }
1116
+ #handleError(err, c) {
1117
+ if (err instanceof Error) {
1118
+ return this.errorHandler(err, c);
1119
+ }
1120
+ throw err;
1121
+ }
1122
+ #dispatch(request, executionCtx, env, method) {
1123
+ if (method === "HEAD") {
1124
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
1125
+ }
1126
+ const path = this.getPath(request, { env });
1127
+ const matchResult = this.router.match(method, path);
1128
+ const c = new Context(request, {
1129
+ path,
1130
+ matchResult,
1131
+ env,
1132
+ executionCtx,
1133
+ notFoundHandler: this.#notFoundHandler
1134
+ });
1135
+ if (matchResult[0].length === 1) {
1136
+ let res;
1137
+ try {
1138
+ res = matchResult[0][0][0][0](c, async () => {
1139
+ c.res = await this.#notFoundHandler(c);
1140
+ });
1141
+ } catch (err) {
1142
+ return this.#handleError(err, c);
1143
+ }
1144
+ 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);
1145
+ }
1146
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
1147
+ return (async () => {
1148
+ try {
1149
+ const context = await composed(c);
1150
+ if (!context.finalized) {
1151
+ throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
1152
+ }
1153
+ return context.res;
1154
+ } catch (err) {
1155
+ return this.#handleError(err, c);
1156
+ }
1157
+ })();
1179
1158
  }
1180
- clear() {
1181
- this.#map.clear();
1159
+ fetch = (request, ...rest) => {
1160
+ return this.#dispatch(request, rest[1], rest[0], request.method);
1161
+ };
1162
+ request = (input, requestInit, Env, executionCtx) => {
1163
+ if (input instanceof Request) {
1164
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
1165
+ }
1166
+ input = input.toString();
1167
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
1168
+ };
1169
+ fire = () => {
1170
+ addEventListener("fetch", (event) => {
1171
+ event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
1172
+ });
1173
+ };
1174
+ };
1175
+
1176
+ // ../../node_modules/hono/dist/router/reg-exp-router/node.js
1177
+ var LABEL_REG_EXP_STR = "[^/]+";
1178
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
1179
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
1180
+ var PATH_ERROR = Symbol();
1181
+ var regExpMetaChars = new Set(".\\+*[^]$()");
1182
+ function compareKey(a, b) {
1183
+ if (a.length === 1) {
1184
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
1185
+ }
1186
+ if (b.length === 1) {
1187
+ return 1;
1188
+ }
1189
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
1190
+ return 1;
1191
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
1192
+ return -1;
1193
+ }
1194
+ if (a === LABEL_REG_EXP_STR) {
1195
+ return 1;
1196
+ } else if (b === LABEL_REG_EXP_STR) {
1197
+ return -1;
1198
+ }
1199
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
1200
+ }
1201
+ var Node = class {
1202
+ #index;
1203
+ #varIndex;
1204
+ #children = /* @__PURE__ */ Object.create(null);
1205
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
1206
+ if (tokens.length === 0) {
1207
+ if (this.#index !== undefined) {
1208
+ throw PATH_ERROR;
1209
+ }
1210
+ if (pathErrorCheckOnly) {
1211
+ return;
1212
+ }
1213
+ this.#index = index;
1214
+ return;
1215
+ }
1216
+ const [token, ...restTokens] = tokens;
1217
+ const pattern2 = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1218
+ let node;
1219
+ if (pattern2) {
1220
+ const name = pattern2[1];
1221
+ let regexpStr = pattern2[2] || LABEL_REG_EXP_STR;
1222
+ if (name && pattern2[2]) {
1223
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
1224
+ if (/\((?!\?:)/.test(regexpStr)) {
1225
+ throw PATH_ERROR;
1226
+ }
1227
+ }
1228
+ node = this.#children[regexpStr];
1229
+ if (!node) {
1230
+ if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
1231
+ throw PATH_ERROR;
1232
+ }
1233
+ if (pathErrorCheckOnly) {
1234
+ return;
1235
+ }
1236
+ node = this.#children[regexpStr] = new Node;
1237
+ if (name !== "") {
1238
+ node.#varIndex = context.varIndex++;
1239
+ }
1240
+ }
1241
+ if (!pathErrorCheckOnly && name !== "") {
1242
+ paramMap.push([name, node.#varIndex]);
1243
+ }
1244
+ } else {
1245
+ node = this.#children[token];
1246
+ if (!node) {
1247
+ if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
1248
+ throw PATH_ERROR;
1249
+ }
1250
+ if (pathErrorCheckOnly) {
1251
+ return;
1252
+ }
1253
+ node = this.#children[token] = new Node;
1254
+ }
1255
+ }
1256
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
1182
1257
  }
1183
- entries() {
1184
- return this.#map.entries();
1258
+ buildRegExpStr() {
1259
+ const childKeys = Object.keys(this.#children).sort(compareKey);
1260
+ const strList = childKeys.map((k) => {
1261
+ const c = this.#children[k];
1262
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
1263
+ });
1264
+ if (typeof this.#index === "number") {
1265
+ strList.unshift(`#${this.#index}`);
1266
+ }
1267
+ if (strList.length === 0) {
1268
+ return "";
1269
+ }
1270
+ if (strList.length === 1) {
1271
+ return strList[0];
1272
+ }
1273
+ return "(?:" + strList.join("|") + ")";
1185
1274
  }
1186
- names() {
1187
- return this.#map.keys();
1275
+ };
1276
+
1277
+ // ../../node_modules/hono/dist/router/reg-exp-router/trie.js
1278
+ var Trie = class {
1279
+ #context = { varIndex: 0 };
1280
+ #root = new Node;
1281
+ insert(path, index, pathErrorCheckOnly) {
1282
+ const paramAssoc = [];
1283
+ const groups = [];
1284
+ for (let i = 0;; ) {
1285
+ let replaced = false;
1286
+ path = path.replace(/\{[^}]+\}/g, (m) => {
1287
+ const mark = `@\\${i}`;
1288
+ groups[i] = [mark, m];
1289
+ i++;
1290
+ replaced = true;
1291
+ return mark;
1292
+ });
1293
+ if (!replaced) {
1294
+ break;
1295
+ }
1296
+ }
1297
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1298
+ for (let i = groups.length - 1;i >= 0; i--) {
1299
+ const [mark] = groups[i];
1300
+ for (let j = tokens.length - 1;j >= 0; j--) {
1301
+ if (tokens[j].indexOf(mark) !== -1) {
1302
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
1303
+ break;
1304
+ }
1305
+ }
1306
+ }
1307
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
1308
+ return paramAssoc;
1309
+ }
1310
+ buildRegExp() {
1311
+ let regexp = this.#root.buildRegExpStr();
1312
+ if (regexp === "") {
1313
+ return [/^$/, [], []];
1314
+ }
1315
+ let captureIndex = 0;
1316
+ const indexReplacementMap = [];
1317
+ const paramReplacementMap = [];
1318
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1319
+ if (handlerIndex !== undefined) {
1320
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
1321
+ return "$()";
1322
+ }
1323
+ if (paramIndex !== undefined) {
1324
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1325
+ return "";
1326
+ }
1327
+ return "";
1328
+ });
1329
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
1188
1330
  }
1189
- values() {
1190
- return this.#map.values();
1331
+ };
1332
+
1333
+ // ../../node_modules/hono/dist/router/reg-exp-router/router.js
1334
+ var emptyParam = [];
1335
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
1336
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1337
+ function buildWildcardRegExp(path) {
1338
+ return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
1339
+ }
1340
+ function clearWildcardRegExpCache() {
1341
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1342
+ }
1343
+ function buildMatcherFromPreprocessedRoutes(routes) {
1344
+ const trie = new Trie;
1345
+ const handlerData = [];
1346
+ if (routes.length === 0) {
1347
+ return nullMatcher;
1348
+ }
1349
+ const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
1350
+ const staticMap = /* @__PURE__ */ Object.create(null);
1351
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
1352
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
1353
+ if (pathErrorCheckOnly) {
1354
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1355
+ } else {
1356
+ j++;
1357
+ }
1358
+ let paramAssoc;
1359
+ try {
1360
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
1361
+ } catch (e) {
1362
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
1363
+ }
1364
+ if (pathErrorCheckOnly) {
1365
+ continue;
1366
+ }
1367
+ handlerData[j] = handlers.map(([h, paramCount]) => {
1368
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
1369
+ paramCount -= 1;
1370
+ for (;paramCount >= 0; paramCount--) {
1371
+ const [key, value] = paramAssoc[paramCount];
1372
+ paramIndexMap[key] = value;
1373
+ }
1374
+ return [h, paramIndexMap];
1375
+ });
1191
1376
  }
1192
- [Symbol.iterator]() {
1193
- return this.entries();
1377
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1378
+ for (let i = 0, len = handlerData.length;i < len; i++) {
1379
+ for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
1380
+ const map = handlerData[i][j]?.[1];
1381
+ if (!map) {
1382
+ continue;
1383
+ }
1384
+ const keys = Object.keys(map);
1385
+ for (let k = 0, len3 = keys.length;k < len3; k++) {
1386
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
1387
+ }
1388
+ }
1194
1389
  }
1195
- forEach(callback, thisArg) {
1196
- this.#map.forEach(callback, thisArg);
1390
+ const handlerMap = [];
1391
+ for (const i in indexReplacementMap) {
1392
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
1197
1393
  }
1198
- get size() {
1199
- return this.#map.size;
1394
+ return [regexp, handlerMap, staticMap];
1395
+ }
1396
+ function findMiddleware(middleware, path) {
1397
+ if (!middleware) {
1398
+ return;
1200
1399
  }
1201
- toString() {
1202
- let pairs = [];
1203
- for (let [name, value] of this.#map) {
1204
- pairs.push(`${name}=${quote(value)}`);
1400
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1401
+ if (buildWildcardRegExp(k).test(path)) {
1402
+ return [...middleware[k]];
1205
1403
  }
1206
- return pairs.join("; ");
1207
1404
  }
1405
+ return;
1208
1406
  }
1209
- // node_modules/@mjackson/headers/dist/lib/set-cookie.js
1210
- class SetCookie {
1211
- domain;
1212
- expires;
1213
- httpOnly;
1214
- maxAge;
1215
- name;
1216
- path;
1217
- sameSite;
1218
- secure;
1219
- value;
1220
- constructor(init) {
1221
- if (init) {
1222
- if (typeof init === "string") {
1223
- let params = parseParams(init);
1224
- if (params.length > 0) {
1225
- this.name = params[0][0];
1226
- this.value = params[0][1];
1227
- for (let [key, value] of params.slice(1)) {
1228
- switch (key.toLowerCase()) {
1229
- case "domain":
1230
- this.domain = value;
1231
- break;
1232
- case "expires": {
1233
- if (typeof value === "string") {
1234
- let v = new Date(value);
1235
- if (isValidDate(v))
1236
- this.expires = v;
1237
- }
1238
- break;
1239
- }
1240
- case "httponly":
1241
- this.httpOnly = true;
1242
- break;
1243
- case "max-age": {
1244
- if (typeof value === "string") {
1245
- let v = parseInt(value, 10);
1246
- if (!isNaN(v))
1247
- this.maxAge = v;
1248
- }
1249
- break;
1250
- }
1251
- case "path":
1252
- this.path = value;
1253
- break;
1254
- case "samesite":
1255
- if (typeof value === "string" && /strict|lax|none/i.test(value)) {
1256
- this.sameSite = capitalize(value);
1257
- }
1258
- break;
1259
- case "secure":
1260
- this.secure = true;
1261
- break;
1262
- }
1263
- }
1264
- }
1407
+ var RegExpRouter = class {
1408
+ name = "RegExpRouter";
1409
+ #middleware;
1410
+ #routes;
1411
+ constructor() {
1412
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1413
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1414
+ }
1415
+ add(method, path, handler) {
1416
+ const middleware = this.#middleware;
1417
+ const routes = this.#routes;
1418
+ if (!middleware || !routes) {
1419
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1420
+ }
1421
+ if (!middleware[method]) {
1422
+ [middleware, routes].forEach((handlerMap) => {
1423
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
1424
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
1425
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
1426
+ });
1427
+ });
1428
+ }
1429
+ if (path === "/*") {
1430
+ path = "*";
1431
+ }
1432
+ const paramCount = (path.match(/\/:/g) || []).length;
1433
+ if (/\*$/.test(path)) {
1434
+ const re = buildWildcardRegExp(path);
1435
+ if (method === METHOD_NAME_ALL) {
1436
+ Object.keys(middleware).forEach((m) => {
1437
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1438
+ });
1265
1439
  } else {
1266
- this.domain = init.domain;
1267
- this.expires = init.expires;
1268
- this.httpOnly = init.httpOnly;
1269
- this.maxAge = init.maxAge;
1270
- this.name = init.name;
1271
- this.path = init.path;
1272
- this.sameSite = init.sameSite;
1273
- this.secure = init.secure;
1274
- this.value = init.value;
1440
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1275
1441
  }
1442
+ Object.keys(middleware).forEach((m) => {
1443
+ if (method === METHOD_NAME_ALL || method === m) {
1444
+ Object.keys(middleware[m]).forEach((p) => {
1445
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
1446
+ });
1447
+ }
1448
+ });
1449
+ Object.keys(routes).forEach((m) => {
1450
+ if (method === METHOD_NAME_ALL || method === m) {
1451
+ Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
1452
+ }
1453
+ });
1454
+ return;
1455
+ }
1456
+ const paths = checkOptionalParameter(path) || [path];
1457
+ for (let i = 0, len = paths.length;i < len; i++) {
1458
+ const path2 = paths[i];
1459
+ Object.keys(routes).forEach((m) => {
1460
+ if (method === METHOD_NAME_ALL || method === m) {
1461
+ routes[m][path2] ||= [
1462
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
1463
+ ];
1464
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
1465
+ }
1466
+ });
1276
1467
  }
1277
1468
  }
1278
- toString() {
1279
- if (!this.name) {
1280
- return "";
1281
- }
1282
- let parts = [`${this.name}=${quote(this.value || "")}`];
1283
- if (this.domain) {
1284
- parts.push(`Domain=${this.domain}`);
1285
- }
1286
- if (this.path) {
1287
- parts.push(`Path=${this.path}`);
1469
+ match(method, path) {
1470
+ clearWildcardRegExpCache();
1471
+ const matchers = this.#buildAllMatchers();
1472
+ this.match = (method2, path2) => {
1473
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
1474
+ const staticMatch = matcher[2][path2];
1475
+ if (staticMatch) {
1476
+ return staticMatch;
1477
+ }
1478
+ const match = path2.match(matcher[0]);
1479
+ if (!match) {
1480
+ return [[], emptyParam];
1481
+ }
1482
+ const index = match.indexOf("", 1);
1483
+ return [matcher[1][index], match];
1484
+ };
1485
+ return this.match(method, path);
1486
+ }
1487
+ #buildAllMatchers() {
1488
+ const matchers = /* @__PURE__ */ Object.create(null);
1489
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
1490
+ matchers[method] ||= this.#buildMatcher(method);
1491
+ });
1492
+ this.#middleware = this.#routes = undefined;
1493
+ return matchers;
1494
+ }
1495
+ #buildMatcher(method) {
1496
+ const routes = [];
1497
+ let hasOwnRoute = method === METHOD_NAME_ALL;
1498
+ [this.#middleware, this.#routes].forEach((r) => {
1499
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
1500
+ if (ownRoute.length !== 0) {
1501
+ hasOwnRoute ||= true;
1502
+ routes.push(...ownRoute);
1503
+ } else if (method !== METHOD_NAME_ALL) {
1504
+ routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
1505
+ }
1506
+ });
1507
+ if (!hasOwnRoute) {
1508
+ return null;
1509
+ } else {
1510
+ return buildMatcherFromPreprocessedRoutes(routes);
1288
1511
  }
1289
- if (this.expires) {
1290
- parts.push(`Expires=${this.expires.toUTCString()}`);
1512
+ }
1513
+ };
1514
+
1515
+ // ../../node_modules/hono/dist/router/smart-router/router.js
1516
+ var SmartRouter = class {
1517
+ name = "SmartRouter";
1518
+ #routers = [];
1519
+ #routes = [];
1520
+ constructor(init) {
1521
+ this.#routers = init.routers;
1522
+ }
1523
+ add(method, path, handler) {
1524
+ if (!this.#routes) {
1525
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1291
1526
  }
1292
- if (this.maxAge) {
1293
- parts.push(`Max-Age=${this.maxAge}`);
1527
+ this.#routes.push([method, path, handler]);
1528
+ }
1529
+ match(method, path) {
1530
+ if (!this.#routes) {
1531
+ throw new Error("Fatal error");
1294
1532
  }
1295
- if (this.secure) {
1296
- parts.push("Secure");
1533
+ const routers = this.#routers;
1534
+ const routes = this.#routes;
1535
+ const len = routers.length;
1536
+ let i = 0;
1537
+ let res;
1538
+ for (;i < len; i++) {
1539
+ const router = routers[i];
1540
+ try {
1541
+ for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
1542
+ router.add(...routes[i2]);
1543
+ }
1544
+ res = router.match(method, path);
1545
+ } catch (e) {
1546
+ if (e instanceof UnsupportedPathError) {
1547
+ continue;
1548
+ }
1549
+ throw e;
1550
+ }
1551
+ this.match = router.match.bind(router);
1552
+ this.#routers = [router];
1553
+ this.#routes = undefined;
1554
+ break;
1297
1555
  }
1298
- if (this.httpOnly) {
1299
- parts.push("HttpOnly");
1556
+ if (i === len) {
1557
+ throw new Error("Fatal error");
1300
1558
  }
1301
- if (this.sameSite) {
1302
- parts.push(`SameSite=${this.sameSite}`);
1559
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
1560
+ return res;
1561
+ }
1562
+ get activeRouter() {
1563
+ if (this.#routes || this.#routers.length !== 1) {
1564
+ throw new Error("No active router has been determined yet.");
1303
1565
  }
1304
- return parts.join("; ");
1566
+ return this.#routers[0];
1305
1567
  }
1306
- }
1307
- // node_modules/@mjackson/headers/dist/lib/header-names.js
1308
- function canonicalHeaderName(name) {
1309
- return name.toLowerCase().split("-").map((word) => HeaderWordCasingExceptions[word] || word.charAt(0).toUpperCase() + word.slice(1)).join("-");
1310
- }
1311
- var HeaderWordCasingExceptions = {
1312
- ct: "CT",
1313
- etag: "ETag",
1314
- te: "TE",
1315
- www: "WWW",
1316
- x: "X",
1317
- xss: "XSS"
1318
1568
  };
1319
1569
 
1320
- // node_modules/@mjackson/headers/dist/lib/super-headers.js
1321
- var CRLF = "\r\n";
1322
- var SetCookieKey = "set-cookie";
1323
-
1324
- class SuperHeaders extends Headers {
1325
- #map;
1326
- #setCookieValues = [];
1327
- constructor(init) {
1328
- super();
1329
- this.#map = new Map;
1330
- if (init) {
1331
- if (typeof init === "string") {
1332
- let lines = init.split(CRLF);
1333
- for (let line of lines) {
1334
- let match = line.match(/^([^:]+):(.*)/);
1335
- if (match) {
1336
- this.append(match[1].trim(), match[2].trim());
1570
+ // ../../node_modules/hono/dist/router/trie-router/node.js
1571
+ var emptyParams = /* @__PURE__ */ Object.create(null);
1572
+ var Node2 = class {
1573
+ #methods;
1574
+ #children;
1575
+ #patterns;
1576
+ #order = 0;
1577
+ #params = emptyParams;
1578
+ constructor(method, handler, children) {
1579
+ this.#children = children || /* @__PURE__ */ Object.create(null);
1580
+ this.#methods = [];
1581
+ if (method && handler) {
1582
+ const m = /* @__PURE__ */ Object.create(null);
1583
+ m[method] = { handler, possibleKeys: [], score: 0 };
1584
+ this.#methods = [m];
1585
+ }
1586
+ this.#patterns = [];
1587
+ }
1588
+ insert(method, path, handler) {
1589
+ this.#order = ++this.#order;
1590
+ let curNode = this;
1591
+ const parts = splitRoutingPath(path);
1592
+ const possibleKeys = [];
1593
+ for (let i = 0, len = parts.length;i < len; i++) {
1594
+ const p = parts[i];
1595
+ const nextP = parts[i + 1];
1596
+ const pattern2 = getPattern2(p, nextP);
1597
+ const key = Array.isArray(pattern2) ? pattern2[0] : p;
1598
+ if (Object.keys(curNode.#children).includes(key)) {
1599
+ curNode = curNode.#children[key];
1600
+ const pattern22 = getPattern2(p, nextP);
1601
+ if (pattern22) {
1602
+ possibleKeys.push(pattern22[1]);
1603
+ }
1604
+ continue;
1605
+ }
1606
+ curNode.#children[key] = new Node2;
1607
+ if (pattern2) {
1608
+ curNode.#patterns.push(pattern2);
1609
+ possibleKeys.push(pattern2[1]);
1610
+ }
1611
+ curNode = curNode.#children[key];
1612
+ }
1613
+ const m = /* @__PURE__ */ Object.create(null);
1614
+ const handlerSet = {
1615
+ handler,
1616
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
1617
+ score: this.#order
1618
+ };
1619
+ m[method] = handlerSet;
1620
+ curNode.#methods.push(m);
1621
+ return curNode;
1622
+ }
1623
+ #getHandlerSets(node, method, nodeParams, params) {
1624
+ const handlerSets = [];
1625
+ for (let i = 0, len = node.#methods.length;i < len; i++) {
1626
+ const m = node.#methods[i];
1627
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
1628
+ const processedSet = {};
1629
+ if (handlerSet !== undefined) {
1630
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
1631
+ handlerSets.push(handlerSet);
1632
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
1633
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
1634
+ const key = handlerSet.possibleKeys[i2];
1635
+ const processed = processedSet[handlerSet.score];
1636
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
1637
+ processedSet[handlerSet.score] = true;
1337
1638
  }
1338
1639
  }
1339
- } else if (isIterable(init)) {
1340
- for (let [name, value] of init) {
1341
- this.append(name, value);
1640
+ }
1641
+ }
1642
+ return handlerSets;
1643
+ }
1644
+ search(method, path) {
1645
+ const handlerSets = [];
1646
+ this.#params = emptyParams;
1647
+ const curNode = this;
1648
+ let curNodes = [curNode];
1649
+ const parts = splitPath(path);
1650
+ const curNodesQueue = [];
1651
+ for (let i = 0, len = parts.length;i < len; i++) {
1652
+ const part = parts[i];
1653
+ const isLast = i === len - 1;
1654
+ const tempNodes = [];
1655
+ for (let j = 0, len2 = curNodes.length;j < len2; j++) {
1656
+ const node = curNodes[j];
1657
+ const nextNode = node.#children[part];
1658
+ if (nextNode) {
1659
+ nextNode.#params = node.#params;
1660
+ if (isLast) {
1661
+ if (nextNode.#children["*"]) {
1662
+ handlerSets.push(...this.#getHandlerSets(nextNode.#children["*"], method, node.#params));
1663
+ }
1664
+ handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
1665
+ } else {
1666
+ tempNodes.push(nextNode);
1667
+ }
1342
1668
  }
1343
- } else if (typeof init === "object") {
1344
- for (let name in init) {
1345
- if (Object.prototype.hasOwnProperty.call(init, name)) {
1346
- let setter = Object.getOwnPropertyDescriptor(SuperHeaders.prototype, name)?.set;
1347
- if (setter) {
1348
- setter.call(this, init[name]);
1669
+ for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
1670
+ const pattern2 = node.#patterns[k];
1671
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
1672
+ if (pattern2 === "*") {
1673
+ const astNode = node.#children["*"];
1674
+ if (astNode) {
1675
+ handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
1676
+ astNode.#params = params;
1677
+ tempNodes.push(astNode);
1678
+ }
1679
+ continue;
1680
+ }
1681
+ if (part === "") {
1682
+ continue;
1683
+ }
1684
+ const [key, name, matcher] = pattern2;
1685
+ const child = node.#children[key];
1686
+ const restPathString = parts.slice(i).join("/");
1687
+ if (matcher instanceof RegExp) {
1688
+ const m = matcher.exec(restPathString);
1689
+ if (m) {
1690
+ params[name] = m[0];
1691
+ handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
1692
+ if (Object.keys(child.#children).length) {
1693
+ child.#params = params;
1694
+ const componentCount = m[0].match(/\//)?.length ?? 0;
1695
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
1696
+ targetCurNodes.push(child);
1697
+ }
1698
+ continue;
1699
+ }
1700
+ }
1701
+ if (matcher === true || matcher.test(part)) {
1702
+ params[name] = part;
1703
+ if (isLast) {
1704
+ handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
1705
+ if (child.#children["*"]) {
1706
+ handlerSets.push(...this.#getHandlerSets(child.#children["*"], method, params, node.#params));
1707
+ }
1349
1708
  } else {
1350
- this.append(name, init[name]);
1709
+ child.#params = params;
1710
+ tempNodes.push(child);
1351
1711
  }
1352
1712
  }
1353
1713
  }
1354
1714
  }
1715
+ curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
1355
1716
  }
1356
- }
1357
- append(name, value) {
1358
- let key = name.toLowerCase();
1359
- if (key === SetCookieKey) {
1360
- this.#setCookieValues.push(value);
1361
- } else {
1362
- let existingValue = this.#map.get(key);
1363
- this.#map.set(key, existingValue ? `${existingValue}, ${value}` : value);
1717
+ if (handlerSets.length > 1) {
1718
+ handlerSets.sort((a, b) => {
1719
+ return a.score - b.score;
1720
+ });
1364
1721
  }
1722
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
1365
1723
  }
1366
- delete(name) {
1367
- let key = name.toLowerCase();
1368
- if (key === SetCookieKey) {
1369
- this.#setCookieValues = [];
1370
- } else {
1371
- this.#map.delete(key);
1372
- }
1724
+ };
1725
+
1726
+ // ../../node_modules/hono/dist/router/trie-router/router.js
1727
+ var TrieRouter = class {
1728
+ name = "TrieRouter";
1729
+ #node;
1730
+ constructor() {
1731
+ this.#node = new Node2;
1373
1732
  }
1374
- get(name) {
1375
- let key = name.toLowerCase();
1376
- if (key === SetCookieKey) {
1377
- return this.#setCookieValues.map((value) => value.toString()).join(", ");
1378
- } else {
1379
- let value = this.#map.get(key);
1380
- if (typeof value === "string") {
1381
- return value;
1382
- } else if (value instanceof Date) {
1383
- return value.toUTCString();
1384
- } else if (value != null) {
1385
- return value.toString();
1386
- } else {
1387
- return null;
1733
+ add(method, path, handler) {
1734
+ const results = checkOptionalParameter(path);
1735
+ if (results) {
1736
+ for (let i = 0, len = results.length;i < len; i++) {
1737
+ this.#node.insert(method, results[i], handler);
1388
1738
  }
1739
+ return;
1389
1740
  }
1741
+ this.#node.insert(method, path, handler);
1390
1742
  }
1391
- getSetCookie() {
1392
- return this.#setCookieValues.map((value) => value.toString());
1743
+ match(method, path) {
1744
+ return this.#node.search(method, path);
1393
1745
  }
1394
- has(name) {
1395
- let key = name.toLowerCase();
1396
- if (key === SetCookieKey) {
1397
- return this.#setCookieValues.length > 0;
1398
- } else {
1399
- return this.#map.has(key);
1400
- }
1746
+ };
1747
+
1748
+ // ../../node_modules/hono/dist/hono.js
1749
+ var Hono2 = class extends Hono {
1750
+ constructor(options = {}) {
1751
+ super(options);
1752
+ this.router = options.router ?? new SmartRouter({
1753
+ routers: [new RegExpRouter, new TrieRouter]
1754
+ });
1401
1755
  }
1402
- set(name, value) {
1403
- let key = name.toLowerCase();
1404
- if (key === SetCookieKey) {
1405
- this.#setCookieValues = [value];
1756
+ };
1757
+
1758
+ // ../../node_modules/hono/dist/adapter/bun/serve-static.js
1759
+ import { stat } from "node:fs/promises";
1760
+
1761
+ // ../../node_modules/hono/dist/utils/compress.js
1762
+ var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
1763
+
1764
+ // ../../node_modules/hono/dist/utils/filepath.js
1765
+ var getFilePath = (options) => {
1766
+ let filename = options.filename;
1767
+ const defaultDocument = options.defaultDocument || "index.html";
1768
+ if (filename.endsWith("/")) {
1769
+ filename = filename.concat(defaultDocument);
1770
+ } else if (!filename.match(/\.[a-zA-Z0-9_-]+$/)) {
1771
+ filename = filename.concat("/" + defaultDocument);
1772
+ }
1773
+ const path = getFilePathWithoutDefaultDocument({
1774
+ root: options.root,
1775
+ filename
1776
+ });
1777
+ return path;
1778
+ };
1779
+ var getFilePathWithoutDefaultDocument = (options) => {
1780
+ let root = options.root || "";
1781
+ let filename = options.filename;
1782
+ if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {
1783
+ return;
1784
+ }
1785
+ filename = filename.replace(/^\.?[\/\\]/, "");
1786
+ filename = filename.replace(/\\/, "/");
1787
+ root = root.replace(/\/$/, "");
1788
+ let path = root ? root + "/" + filename : filename;
1789
+ path = path.replace(/^\.?\//, "");
1790
+ if (root[0] !== "/" && path[0] === "/") {
1791
+ return;
1792
+ }
1793
+ return path;
1794
+ };
1795
+
1796
+ // ../../node_modules/hono/dist/utils/mime.js
1797
+ var getMimeType = (filename, mimes = baseMimes) => {
1798
+ const regexp = /\.([a-zA-Z0-9]+?)$/;
1799
+ const match = filename.match(regexp);
1800
+ if (!match) {
1801
+ return;
1802
+ }
1803
+ let mimeType = mimes[match[1]];
1804
+ if (mimeType && mimeType.startsWith("text")) {
1805
+ mimeType += "; charset=utf-8";
1806
+ }
1807
+ return mimeType;
1808
+ };
1809
+ var _baseMimes = {
1810
+ aac: "audio/aac",
1811
+ avi: "video/x-msvideo",
1812
+ avif: "image/avif",
1813
+ av1: "video/av1",
1814
+ bin: "application/octet-stream",
1815
+ bmp: "image/bmp",
1816
+ css: "text/css",
1817
+ csv: "text/csv",
1818
+ eot: "application/vnd.ms-fontobject",
1819
+ epub: "application/epub+zip",
1820
+ gif: "image/gif",
1821
+ gz: "application/gzip",
1822
+ htm: "text/html",
1823
+ html: "text/html",
1824
+ ico: "image/x-icon",
1825
+ ics: "text/calendar",
1826
+ jpeg: "image/jpeg",
1827
+ jpg: "image/jpeg",
1828
+ js: "text/javascript",
1829
+ json: "application/json",
1830
+ jsonld: "application/ld+json",
1831
+ map: "application/json",
1832
+ mid: "audio/x-midi",
1833
+ midi: "audio/x-midi",
1834
+ mjs: "text/javascript",
1835
+ mp3: "audio/mpeg",
1836
+ mp4: "video/mp4",
1837
+ mpeg: "video/mpeg",
1838
+ oga: "audio/ogg",
1839
+ ogv: "video/ogg",
1840
+ ogx: "application/ogg",
1841
+ opus: "audio/opus",
1842
+ otf: "font/otf",
1843
+ pdf: "application/pdf",
1844
+ png: "image/png",
1845
+ rtf: "application/rtf",
1846
+ svg: "image/svg+xml",
1847
+ tif: "image/tiff",
1848
+ tiff: "image/tiff",
1849
+ ts: "video/mp2t",
1850
+ ttf: "font/ttf",
1851
+ txt: "text/plain",
1852
+ wasm: "application/wasm",
1853
+ webm: "video/webm",
1854
+ weba: "audio/webm",
1855
+ webp: "image/webp",
1856
+ woff: "font/woff",
1857
+ woff2: "font/woff2",
1858
+ xhtml: "application/xhtml+xml",
1859
+ xml: "application/xml",
1860
+ zip: "application/zip",
1861
+ "3gp": "video/3gpp",
1862
+ "3g2": "video/3gpp2",
1863
+ gltf: "model/gltf+json",
1864
+ glb: "model/gltf-binary"
1865
+ };
1866
+ var baseMimes = _baseMimes;
1867
+
1868
+ // ../../node_modules/hono/dist/middleware/serve-static/index.js
1869
+ var ENCODINGS = {
1870
+ br: ".br",
1871
+ zstd: ".zst",
1872
+ gzip: ".gz"
1873
+ };
1874
+ var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
1875
+ var DEFAULT_DOCUMENT = "index.html";
1876
+ var defaultPathResolve = (path) => path;
1877
+ var serveStatic = (options) => {
1878
+ let isAbsoluteRoot = false;
1879
+ let root;
1880
+ if (options.root) {
1881
+ if (options.root.startsWith("/")) {
1882
+ isAbsoluteRoot = true;
1883
+ root = new URL(`file://${options.root}`).pathname;
1406
1884
  } else {
1407
- this.#map.set(key, value);
1885
+ root = options.root;
1408
1886
  }
1409
1887
  }
1410
- *entries() {
1411
- for (let [key] of this.#map) {
1412
- let stringValue = this.get(key);
1413
- if (stringValue) {
1414
- yield [key, stringValue];
1415
- }
1888
+ return async (c, next) => {
1889
+ if (c.finalized) {
1890
+ await next();
1891
+ return;
1416
1892
  }
1417
- for (let value of this.#setCookieValues) {
1418
- let stringValue = value.toString();
1419
- if (stringValue) {
1420
- yield [SetCookieKey, stringValue];
1893
+ let filename = options.path ?? decodeURI(c.req.path);
1894
+ filename = options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename;
1895
+ if (!filename.endsWith("/") && options.isDir) {
1896
+ const path2 = getFilePathWithoutDefaultDocument({
1897
+ filename,
1898
+ root
1899
+ });
1900
+ if (path2 && await options.isDir(path2)) {
1901
+ filename += "/";
1421
1902
  }
1422
1903
  }
1423
- }
1424
- *keys() {
1425
- for (let [key] of this) {
1426
- yield key;
1427
- }
1428
- }
1429
- *values() {
1430
- for (let [, value] of this) {
1431
- yield value;
1904
+ let path = getFilePath({
1905
+ filename,
1906
+ root,
1907
+ defaultDocument: DEFAULT_DOCUMENT
1908
+ });
1909
+ if (!path) {
1910
+ return await next();
1911
+ }
1912
+ if (isAbsoluteRoot) {
1913
+ path = "/" + path;
1914
+ }
1915
+ const getContent = options.getContent;
1916
+ const pathResolve = options.pathResolve ?? defaultPathResolve;
1917
+ path = pathResolve(path);
1918
+ let content = await getContent(path, c);
1919
+ if (!content) {
1920
+ let pathWithoutDefaultDocument = getFilePathWithoutDefaultDocument({
1921
+ filename,
1922
+ root
1923
+ });
1924
+ if (!pathWithoutDefaultDocument) {
1925
+ return await next();
1926
+ }
1927
+ pathWithoutDefaultDocument = pathResolve(pathWithoutDefaultDocument);
1928
+ if (pathWithoutDefaultDocument !== path) {
1929
+ content = await getContent(pathWithoutDefaultDocument, c);
1930
+ if (content) {
1931
+ path = pathWithoutDefaultDocument;
1932
+ }
1933
+ }
1432
1934
  }
1433
- }
1434
- [Symbol.iterator]() {
1435
- return this.entries();
1436
- }
1437
- forEach(callback, thisArg) {
1438
- for (let [key, value] of this) {
1439
- callback.call(thisArg, value, key, this);
1935
+ if (content instanceof Response) {
1936
+ return c.newResponse(content.body, content);
1440
1937
  }
1441
- }
1442
- toString() {
1443
- let lines = [];
1444
- for (let [key, value] of this) {
1445
- lines.push(`${canonicalHeaderName(key)}: ${value}`);
1938
+ if (content) {
1939
+ const mimeType = options.mimes && getMimeType(path, options.mimes) || getMimeType(path);
1940
+ c.header("Content-Type", mimeType || "application/octet-stream");
1941
+ if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
1942
+ const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
1943
+ for (const encoding of ENCODINGS_ORDERED_KEYS) {
1944
+ if (!acceptEncodingSet.has(encoding)) {
1945
+ continue;
1946
+ }
1947
+ const compressedContent = await getContent(path + ENCODINGS[encoding], c);
1948
+ if (compressedContent) {
1949
+ content = compressedContent;
1950
+ c.header("Content-Encoding", encoding);
1951
+ c.header("Vary", "Accept-Encoding", { append: true });
1952
+ break;
1953
+ }
1954
+ }
1955
+ }
1956
+ await options.onFound?.(path, c);
1957
+ return c.body(content);
1446
1958
  }
1447
- return lines.join(CRLF);
1448
- }
1449
- get acceptLanguage() {
1450
- return this.#getHeaderValue("accept-language", AcceptLanguage);
1451
- }
1452
- set acceptLanguage(value) {
1453
- this.#setHeaderValue("accept-language", AcceptLanguage, value);
1454
- }
1455
- get age() {
1456
- return this.#getNumberValue("age");
1457
- }
1458
- set age(value) {
1459
- this.#map.set("age", value);
1460
- }
1461
- get cacheControl() {
1462
- return this.#getHeaderValue("cache-control", CacheControl);
1463
- }
1464
- set cacheControl(value) {
1465
- this.#setHeaderValue("cache-control", CacheControl, value);
1466
- }
1467
- get contentDisposition() {
1468
- return this.#getHeaderValue("content-disposition", ContentDisposition);
1469
- }
1470
- set contentDisposition(value) {
1471
- this.#setHeaderValue("content-disposition", ContentDisposition, value);
1472
- }
1473
- get contentLength() {
1474
- return this.#getNumberValue("content-length");
1475
- }
1476
- set contentLength(value) {
1477
- this.#map.set("content-length", value);
1478
- }
1479
- get contentType() {
1480
- return this.#getHeaderValue("content-type", ContentType);
1481
- }
1482
- set contentType(value) {
1483
- this.#setHeaderValue("content-type", ContentType, value);
1484
- }
1485
- get cookie() {
1486
- return this.#getHeaderValue("cookie", Cookie);
1487
- }
1488
- set cookie(value) {
1489
- this.#setHeaderValue("cookie", Cookie, value);
1490
- }
1491
- get date() {
1492
- return this.#getDateValue("date");
1493
- }
1494
- set date(value) {
1495
- this.#map.set("date", value);
1959
+ await options.onNotFound?.(path, c);
1960
+ await next();
1961
+ return;
1962
+ };
1963
+ };
1964
+
1965
+ // ../../node_modules/hono/dist/adapter/bun/serve-static.js
1966
+ var serveStatic2 = (options) => {
1967
+ return async function serveStatic2(c, next) {
1968
+ const getContent = async (path) => {
1969
+ path = path.startsWith("/") ? path : `./${path}`;
1970
+ const file = Bun.file(path);
1971
+ return await file.exists() ? file : null;
1972
+ };
1973
+ const pathResolve = (path) => {
1974
+ return path.startsWith("/") ? path : `./${path}`;
1975
+ };
1976
+ const isDir = async (path) => {
1977
+ let isDir2;
1978
+ try {
1979
+ const stats = await stat(path);
1980
+ isDir2 = stats.isDirectory();
1981
+ } catch {}
1982
+ return isDir2;
1983
+ };
1984
+ return serveStatic({
1985
+ ...options,
1986
+ getContent,
1987
+ pathResolve,
1988
+ isDir
1989
+ })(c, next);
1990
+ };
1991
+ };
1992
+
1993
+ // ../../node_modules/hono/dist/helper/ssg/middleware.js
1994
+ var X_HONO_DISABLE_SSG_HEADER_KEY = "x-hono-disable-ssg";
1995
+ var SSG_DISABLED_RESPONSE = (() => {
1996
+ try {
1997
+ return new Response("SSG is disabled", {
1998
+ status: 404,
1999
+ headers: { [X_HONO_DISABLE_SSG_HEADER_KEY]: "true" }
2000
+ });
2001
+ } catch {
2002
+ return null;
1496
2003
  }
1497
- get expires() {
1498
- return this.#getDateValue("expires");
2004
+ })();
2005
+ // ../../node_modules/hono/dist/adapter/bun/ssg.js
2006
+ var { write } = Bun;
2007
+
2008
+ // ../../node_modules/hono/dist/helper/websocket/index.js
2009
+ var WSContext = class {
2010
+ #init;
2011
+ constructor(init) {
2012
+ this.#init = init;
2013
+ this.raw = init.raw;
2014
+ this.url = init.url ? new URL(init.url) : null;
2015
+ this.protocol = init.protocol ?? null;
1499
2016
  }
1500
- set expires(value) {
1501
- this.#map.set("expires", value);
2017
+ send(source, options) {
2018
+ this.#init.send(source, options ?? {});
1502
2019
  }
1503
- get ifModifiedSince() {
1504
- return this.#getDateValue("if-modified-since");
2020
+ raw;
2021
+ binaryType = "arraybuffer";
2022
+ get readyState() {
2023
+ return this.#init.readyState;
1505
2024
  }
1506
- set ifModifiedSince(value) {
1507
- this.#map.set("if-modified-since", value);
2025
+ url;
2026
+ protocol;
2027
+ close(code, reason) {
2028
+ this.#init.close(code, reason);
1508
2029
  }
1509
- get ifUnmodifiedSince() {
1510
- return this.#getDateValue("if-unmodified-since");
2030
+ };
2031
+
2032
+ // ../../node_modules/@zod/core/dist/esm/core.js
2033
+ var $brand = Symbol("zod_brand");
2034
+
2035
+ class $ZodAsyncError extends Error {
2036
+ constructor() {
2037
+ super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
1511
2038
  }
1512
- set ifUnmodifiedSince(value) {
1513
- this.#map.set("if-unmodified-since", value);
2039
+ }
2040
+ var globalConfig = {};
2041
+ function config(config2) {
2042
+ if (config2)
2043
+ Object.assign(globalConfig, config2);
2044
+ return globalConfig;
2045
+ }
2046
+
2047
+ // ../../node_modules/@zod/core/dist/esm/util.js
2048
+ function jsonStringifyReplacer(_, value) {
2049
+ if (typeof value === "bigint")
2050
+ return value.toString();
2051
+ return value;
2052
+ }
2053
+ function cached(getter) {
2054
+ const set = false;
2055
+ return {
2056
+ get value() {
2057
+ if (!set) {
2058
+ const value = getter();
2059
+ Object.defineProperty(this, "value", { value });
2060
+ return value;
2061
+ }
2062
+ throw new Error("cached value already set");
2063
+ }
2064
+ };
2065
+ }
2066
+ var allowsEval = cached(() => {
2067
+ try {
2068
+ new Function("");
2069
+ return true;
2070
+ } catch (_) {
2071
+ return false;
1514
2072
  }
1515
- get lastModified() {
1516
- return this.#getDateValue("last-modified");
2073
+ });
2074
+ var propertyKeyTypes = new Set(["string", "number", "symbol"]);
2075
+ var primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
2076
+ var NUMBER_FORMAT_RANGES = {
2077
+ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
2078
+ int32: [-2147483648, 2147483647],
2079
+ uint32: [0, 4294967295],
2080
+ float32: [-340282346638528860000000000000000000000, 340282346638528860000000000000000000000],
2081
+ float64: [-179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000]
2082
+ };
2083
+ function unwrapMessage(message) {
2084
+ return typeof message === "string" ? message : message?.message;
2085
+ }
2086
+ function finalizeIssue(iss, ctx, config2) {
2087
+ const full = { ...iss, path: iss.path ?? [] };
2088
+ if (!iss.message) {
2089
+ const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
2090
+ full.message = message;
2091
+ }
2092
+ delete full.inst;
2093
+ delete full.continue;
2094
+ if (!ctx?.reportInput) {
2095
+ delete full.input;
2096
+ }
2097
+ return full;
2098
+ }
2099
+
2100
+ // ../../node_modules/@zod/core/dist/esm/errors.js
2101
+ var ZOD_ERROR = Symbol.for("{{zod.error}}");
2102
+
2103
+ class $ZodError {
2104
+ get message() {
2105
+ return JSON.stringify(this.issues, jsonStringifyReplacer, 2);
1517
2106
  }
1518
- set lastModified(value) {
1519
- this.#map.set("last-modified", value);
2107
+ constructor(issues) {
2108
+ Object.defineProperty(this, "_tag", { value: ZOD_ERROR, enumerable: false });
2109
+ Object.defineProperty(this, "name", { value: "$ZodError", enumerable: false });
2110
+ this.issues = issues;
1520
2111
  }
1521
- get setCookie() {
1522
- for (let i = 0;i < this.#setCookieValues.length; ++i) {
1523
- let value = this.#setCookieValues[i];
1524
- if (typeof value === "string") {
1525
- this.#setCookieValues[i] = new SetCookie(value);
1526
- }
1527
- }
1528
- return this.#setCookieValues;
2112
+ static [Symbol.hasInstance](inst) {
2113
+ return inst?._tag === ZOD_ERROR;
1529
2114
  }
1530
- set setCookie(values) {
1531
- if (typeof values === "string") {
1532
- this.#setCookieValues = [values];
2115
+ }
2116
+ function flattenError(error, mapper = (issue) => issue.message) {
2117
+ const fieldErrors = {};
2118
+ const formErrors = [];
2119
+ for (const sub of error.issues) {
2120
+ if (sub.path.length > 0) {
2121
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
2122
+ fieldErrors[sub.path[0]].push(mapper(sub));
1533
2123
  } else {
1534
- this.#setCookieValues = values.map((value) => {
1535
- if (typeof value === "string" || value instanceof SetCookie) {
1536
- return value;
1537
- } else {
1538
- return new SetCookie(value);
1539
- }
1540
- });
2124
+ formErrors.push(mapper(sub));
1541
2125
  }
1542
2126
  }
1543
- #getDateValue(key) {
1544
- let value = this.#map.get(key);
1545
- if (value) {
1546
- if (typeof value === "string") {
1547
- let date = new Date(value);
1548
- if (isValidDate(date)) {
1549
- this.#map.set(key, date);
1550
- return date;
1551
- } else {
1552
- this.#map.delete(key);
1553
- }
1554
- } else if (value instanceof Date) {
1555
- return value;
2127
+ return { formErrors, fieldErrors };
2128
+ }
2129
+ function formatError(error, _mapper) {
2130
+ const mapper = _mapper || function(issue) {
2131
+ return issue.message;
2132
+ };
2133
+ const fieldErrors = { _errors: [] };
2134
+ const processError = (error2) => {
2135
+ for (const issue of error2.issues) {
2136
+ if (issue.code === "invalid_union") {
2137
+ issue.errors.map((issues) => processError({ issues }));
2138
+ } else if (issue.code === "invalid_key") {
2139
+ processError({ issues: issue.issues });
2140
+ } else if (issue.code === "invalid_element") {
2141
+ processError({ issues: issue.issues });
2142
+ } else if (issue.path.length === 0) {
2143
+ fieldErrors._errors.push(mapper(issue));
1556
2144
  } else {
1557
- this.#map.delete(key);
1558
- }
1559
- }
1560
- }
1561
- #getNumberValue(key) {
1562
- let value = this.#map.get(key);
1563
- if (value) {
1564
- if (typeof value === "string") {
1565
- let v = parseInt(value, 10);
1566
- if (!isNaN(v)) {
1567
- this.#map.set(key, v);
1568
- return v;
1569
- } else {
1570
- this.#map.delete(key);
2145
+ let curr = fieldErrors;
2146
+ let i = 0;
2147
+ while (i < issue.path.length) {
2148
+ const el = issue.path[i];
2149
+ const terminal = i === issue.path.length - 1;
2150
+ if (!terminal) {
2151
+ curr[el] = curr[el] || { _errors: [] };
2152
+ } else {
2153
+ curr[el] = curr[el] || { _errors: [] };
2154
+ curr[el]._errors.push(mapper(issue));
2155
+ }
2156
+ curr = curr[el];
2157
+ i++;
1571
2158
  }
1572
- } else if (typeof value === "number") {
1573
- return value;
1574
- } else {
1575
- this.#map.delete(key);
1576
- }
1577
- }
1578
- }
1579
- #getHeaderValue(key, ctor) {
1580
- let value = this.#map.get(key);
1581
- if (value) {
1582
- if (typeof value === "string") {
1583
- let headerValue = new ctor(value);
1584
- this.#map.set(key, headerValue);
1585
- return headerValue;
1586
- } else {
1587
- return value;
1588
2159
  }
1589
- } else {
1590
- let headerValue = new ctor;
1591
- this.#map.set(key, headerValue);
1592
- return headerValue;
1593
2160
  }
2161
+ };
2162
+ processError(error);
2163
+ return fieldErrors;
2164
+ }
2165
+
2166
+ // ../../node_modules/@zod/core/dist/esm/parse.js
2167
+ function _parse(schema, value, _ctx) {
2168
+ const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
2169
+ const result = schema._zod.run({ value, issues: [] }, ctx);
2170
+ if (result instanceof Promise) {
2171
+ throw new $ZodAsyncError;
1594
2172
  }
1595
- #setHeaderValue(key, ctor, value) {
1596
- if (typeof value === "string" || value instanceof ctor) {
1597
- this.#map.set(key, value);
1598
- } else {
1599
- this.#map.set(key, new ctor(value));
1600
- }
2173
+ if (result.issues.length) {
2174
+ throw new (this?.Error ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
1601
2175
  }
2176
+ return result.value;
1602
2177
  }
1603
- // src/app.ts
1604
- function normalizePath(urlPath) {
1605
- return (urlPath.endsWith("/") ? urlPath.substring(0, urlPath.length - 1) : urlPath).toLowerCase() || "/";
1606
- }
1607
- var mergeAll = import_deepmerge.default({ all: true });
1608
2178
 
1609
- class HSRequestContext {
1610
- req;
1611
- locals;
1612
- headers;
1613
- route;
1614
- constructor(req, params = {}) {
1615
- this.req = req;
1616
- this.locals = {};
1617
- this.route = {
1618
- params,
1619
- query: new URL(req.url).searchParams
1620
- };
1621
- const allowHeaders = ["cookie"];
1622
- const reqHeaders = {};
1623
- for (let [name, value] of req.headers) {
1624
- if (allowHeaders.includes(name)) {
1625
- reqHeaders[name] = value;
1626
- }
1627
- }
1628
- this.headers = new SuperHeaders(reqHeaders);
2179
+ // ../../node_modules/zod/dist/esm/errors.js
2180
+ class ZodError extends $ZodError {
2181
+ format(mapper) {
2182
+ return formatError(this, mapper);
1629
2183
  }
1630
- resMerge(res) {
1631
- const cHeaders = {};
1632
- for (let [name, value] of this.headers) {
1633
- cHeaders[name] = value;
1634
- }
1635
- const newRes = new Response(res.body, mergeAll({ headers: cHeaders }, { headers: res.headers.toJSON() }, { status: res.status, statusText: res.statusText }));
1636
- return newRes;
2184
+ flatten(mapper) {
2185
+ return flattenError(this, mapper);
1637
2186
  }
1638
- html(content, options) {
1639
- return new Response(content, mergeAll({ headers: { "Content-Type": "text/html" } }, options));
2187
+ addIssue(issue) {
2188
+ this.issues.push(issue);
1640
2189
  }
1641
- json(content, options) {
1642
- return new Response(JSON.stringify(content), mergeAll({ headers: { "Content-Type": "application/json" } }, options));
2190
+ addIssues(issues) {
2191
+ this.issues.push(...issues);
1643
2192
  }
1644
- notFound(msg = "Not found!") {
1645
- return this.html(msg, { status: 404 });
2193
+ get isEmpty() {
2194
+ return this.issues.length === 0;
1646
2195
  }
1647
2196
  }
1648
2197
 
1649
- class HSApp {
1650
- _router;
1651
- _mw;
1652
- _defaultRoute;
1653
- constructor() {
1654
- this._router = new import_trek_router.default;
1655
- this._mw = new import_trek_middleware.default;
1656
- this._defaultRoute = (c) => {
1657
- return c.notFound("Not found");
1658
- };
2198
+ // ../../node_modules/zod/dist/esm/parse.js
2199
+ var parse = /* @__PURE__ */ _parse.bind({ Error: ZodError });
2200
+
2201
+ // src/server.ts
2202
+ var IS_PROD2 = false;
2203
+ var CWD = process.cwd();
2204
+ function createRoute(handler) {
2205
+ return new HSRoute(handler);
2206
+ }
2207
+ function createComponent(render2) {
2208
+ return new HSComponent(render2);
2209
+ }
2210
+ function createForm(renderForm, schema) {
2211
+ return new HSFormRoute(renderForm, schema);
2212
+ }
2213
+ var HS_DEFAULT_LOADING = () => html`<div>Loading...</div>`;
2214
+
2215
+ class HSComponent {
2216
+ _kind = "hsComponent";
2217
+ _handlers = {};
2218
+ _loading;
2219
+ render;
2220
+ constructor(render2) {
2221
+ this.render = render2;
2222
+ }
2223
+ loading(fn) {
2224
+ this._loading = fn;
2225
+ return this;
1659
2226
  }
1660
- get(path, handler) {
1661
- return this._route("GET", path, handler);
2227
+ }
2228
+
2229
+ class HSRoute {
2230
+ _kind = "hsRoute";
2231
+ _handlers = {};
2232
+ _methods = null;
2233
+ constructor(handler) {
2234
+ this._handlers.GET = handler;
1662
2235
  }
1663
- post(path, handler) {
1664
- return this._route("POST", path, handler);
2236
+ }
2237
+
2238
+ class HSFormRoute {
2239
+ _kind = "hsFormRoute";
2240
+ _handlers = {};
2241
+ _form;
2242
+ _methods = null;
2243
+ _schema = null;
2244
+ constructor(renderForm, schema = null) {
2245
+ if (schema) {
2246
+ this._form = renderForm;
2247
+ this._schema = schema;
2248
+ } else {
2249
+ this._form = renderForm;
2250
+ }
2251
+ this._handlers.GET = () => renderForm(this.getDefaultData());
1665
2252
  }
1666
- put(path, handler) {
1667
- return this._route("PUT", path, handler);
2253
+ getDefaultData() {
2254
+ if (!this._schema) {
2255
+ return {};
2256
+ }
2257
+ const data = parse(this._schema, {});
2258
+ return data;
1668
2259
  }
1669
- delete(path, handler) {
1670
- return this._route("DELETE", path, handler);
2260
+ renderForm(data) {
2261
+ return this._form(data || this.getDefaultData());
1671
2262
  }
1672
- all(path, handler) {
1673
- return this.addRoute(["GET", "POST", "PUT", "PATCH", "DELETE"], path, handler);
2263
+ get(handler) {
2264
+ this._handlers.GET = handler;
2265
+ return this;
1674
2266
  }
1675
- addRoute(methods, path, handler) {
1676
- methods.forEach((method) => {
1677
- this._route(method, path, handler);
1678
- });
2267
+ patch(handler) {
2268
+ this._handlers.PATCH = handler;
1679
2269
  return this;
1680
2270
  }
1681
- defaultRoute(handler) {
1682
- this._defaultRoute = handler;
2271
+ post(handler) {
2272
+ this._handlers.POST = handler;
2273
+ return this;
1683
2274
  }
1684
- _route(method, path, handler) {
1685
- this._router.add(method, path, handler);
2275
+ put(handler) {
2276
+ this._handlers.PUT = handler;
1686
2277
  return this;
1687
2278
  }
1688
- async run(req) {
1689
- let response;
1690
- let url = new URL(req.url);
1691
- let urlPath = normalizePath(url.pathname);
1692
- if (urlPath !== url.pathname) {
1693
- url.pathname = urlPath;
1694
- return Response.redirect(url);
1695
- }
1696
- let result = this._router.find(req.method.toUpperCase(), urlPath);
1697
- let params = {};
1698
- if (result && result[0]) {
1699
- result[1].forEach((param) => params[param.name] = param.value);
1700
- const context2 = new HSRequestContext(req, params);
1701
- response = result[0](context2);
1702
- }
1703
- if (response) {
1704
- return response;
1705
- }
1706
- const context = new HSRequestContext(req);
1707
- return this._defaultRoute(context);
2279
+ delete(handler) {
2280
+ this._handlers.DELETE = handler;
2281
+ return this;
1708
2282
  }
1709
2283
  }
1710
-
1711
- // src/server.ts
1712
- function requestIsBot(req) {
1713
- const ua = req.headers.get("User-Agent");
1714
- return ua ? isbot(ua) : false;
1715
- }
1716
- async function runFileRoute(routeFile, context) {
2284
+ async function runFileRoute(RouteModule, context) {
1717
2285
  const req = context.req;
1718
2286
  const url = new URL(req.url);
1719
2287
  const qs = url.searchParams;
2288
+ const userIsBot = isbot(context.req.header("User-Agent"));
1720
2289
  const streamOpt = qs.get("__nostream") ? !Boolean(qs.get("__nostream")) : undefined;
1721
- const streamingEnabled = streamOpt !== undefined ? streamOpt : true;
1722
- const RouteModule = _routeCache[routeFile] || await import(routeFile);
1723
- if (IS_PROD) {
1724
- _routeCache[routeFile] = RouteModule;
1725
- }
2290
+ const streamingEnabled = !userIsBot && (streamOpt !== undefined ? streamOpt : true);
1726
2291
  const RouteComponent = RouteModule.default;
1727
2292
  const reqMethod = req.method.toUpperCase();
1728
- const routeMiddleware = RouteModule.middleware || {};
1729
- const middlewareResult = {};
1730
2293
  try {
1731
- if (Object.keys(routeMiddleware).length) {
1732
- for (const mKey in routeMiddleware) {
1733
- const mRes = await routeMiddleware[mKey](context);
1734
- if (mRes instanceof Response) {
1735
- return context.resMerge(mRes);
1736
- }
1737
- middlewareResult[mKey] = mRes;
1738
- }
1739
- }
1740
2294
  if (RouteModule[reqMethod] !== undefined) {
1741
- return await runAPIRoute(RouteModule[reqMethod], context, middlewareResult);
2295
+ return await runAPIRoute(RouteModule[reqMethod], context);
2296
+ }
2297
+ let routeContent;
2298
+ if (!RouteComponent) {
2299
+ throw new Error("No route was exported by default in matched route file.");
2300
+ }
2301
+ if (typeof RouteComponent._handlers !== "undefined") {
2302
+ const routeMethodHandler = RouteComponent._handlers[reqMethod];
2303
+ if (!routeMethodHandler) {
2304
+ return new Response("Method Not Allowed", {
2305
+ status: 405,
2306
+ headers: { "content-type": "text/plain" }
2307
+ });
2308
+ }
2309
+ routeContent = await routeMethodHandler(context);
2310
+ } else {
2311
+ routeContent = await RouteComponent(context);
1742
2312
  }
1743
- const routeContent = await RouteComponent(context, middlewareResult);
1744
2313
  if (routeContent instanceof Response) {
1745
- return context.resMerge(routeContent);
2314
+ return routeContent;
1746
2315
  }
1747
- if (streamingEnabled && !requestIsBot(req)) {
1748
- return context.resMerge(new StreamResponse(renderToStream(routeContent)));
1749
- } else {
1750
- const output = await renderToString(routeContent);
1751
- return context.html(output);
2316
+ if (routeContent instanceof TmplHtml) {
2317
+ if (streamingEnabled) {
2318
+ return new StreamResponse(renderStream(routeContent));
2319
+ } else {
2320
+ const output = await renderAsync(routeContent);
2321
+ return context.html(output);
2322
+ }
1752
2323
  }
2324
+ return routeContent;
1753
2325
  } catch (e) {
1754
2326
  console.error(e);
1755
2327
  return await showErrorReponse(context, e);
@@ -1765,26 +2337,31 @@ async function runAPIRoute(routeFn, context, middlewareResult) {
1765
2337
  meta: { success: false },
1766
2338
  data: {
1767
2339
  message: e.message,
1768
- stack: IS_PROD ? undefined : e.stack?.split("\n")
2340
+ stack: IS_PROD2 ? undefined : e.stack?.split(`
2341
+ `)
1769
2342
  }
1770
2343
  }, { status: 500 });
1771
2344
  }
1772
2345
  }
1773
2346
  async function showErrorReponse(context, err) {
1774
- const output = await renderToString(html`
2347
+ const output = render(html`
1775
2348
  <main>
1776
2349
  <h1>Error</h1>
1777
2350
  <pre>${err.message}</pre>
1778
- <pre>${!IS_PROD && err.stack ? err.stack.split("\n").slice(1).join("\n") : ""}</pre>
2351
+ <pre>${!IS_PROD2 && err.stack ? err.stack.split(`
2352
+ `).slice(1).join(`
2353
+ `) : ""}</pre>
1779
2354
  </main>
1780
2355
  `);
1781
2356
  return context.html(output, {
1782
2357
  status: 500
1783
2358
  });
1784
2359
  }
1785
- async function buildRoutes(config) {
1786
- const routesDir = join(config.appDir, "routes");
1787
- const files = await readdir(routesDir, { recursive: true });
2360
+ var ROUTE_SEGMENT = /(\[[a-zA-Z_\.]+\])/g;
2361
+ async function buildRoutes(config2) {
2362
+ const routesDir = join(config2.appDir, "routes");
2363
+ console.log(routesDir);
2364
+ const files = await readdir2(routesDir, { recursive: true });
1788
2365
  const routes = [];
1789
2366
  for (const file of files) {
1790
2367
  if (!file.includes(".") || basename(file).startsWith(".")) {
@@ -1798,7 +2375,7 @@ async function buildRoutes(config) {
1798
2375
  const dynamicPaths = ROUTE_SEGMENT.test(route);
1799
2376
  if (dynamicPaths) {
1800
2377
  params = [];
1801
- route = route.replace(ROUTE_SEGMENT, (match, p1, offset) => {
2378
+ route = route.replace(ROUTE_SEGMENT, (match) => {
1802
2379
  const paramName = match.replace(/[^a-zA-Z_\.]+/g, "");
1803
2380
  if (match.includes("...")) {
1804
2381
  params.push(paramName.replace("...", ""));
@@ -1817,75 +2394,58 @@ async function buildRoutes(config) {
1817
2394
  }
1818
2395
  return routes;
1819
2396
  }
1820
- async function createServer(config) {
2397
+ async function createServer(config2) {
1821
2398
  await Promise.all([buildClientJS(), buildClientCSS()]);
1822
- const app = new HSApp;
1823
- app.defaultRoute(() => {
1824
- return new Response("Not... found?", { status: 404 });
1825
- });
1826
- config.beforeRoutesAdded && config.beforeRoutesAdded(app);
1827
- const fileRoutes = await buildRoutes(config);
2399
+ const app = new Hono2;
2400
+ config2.beforeRoutesAdded && config2.beforeRoutesAdded(app);
2401
+ const fileRoutes = await buildRoutes(config2);
1828
2402
  const routeMap = [];
1829
2403
  for (let i = 0;i < fileRoutes.length; i++) {
1830
2404
  let route = fileRoutes[i];
1831
2405
  const fullRouteFile = join(CWD, route.file);
1832
2406
  const routePattern = normalizePath(route.route);
1833
2407
  routeMap.push({ route: routePattern, file: route.file });
2408
+ const routeModule = await import(fullRouteFile);
1834
2409
  app.all(routePattern, async (context) => {
1835
- const matchedRoute = await runFileRoute(fullRouteFile, context);
2410
+ const matchedRoute = await runFileRoute(routeModule, context);
1836
2411
  if (matchedRoute) {
1837
2412
  return matchedRoute;
1838
2413
  }
1839
- return app._defaultRoute(context);
2414
+ return context.notFound();
1840
2415
  });
1841
2416
  }
1842
- if (!IS_PROD) {
2417
+ if (routeMap.length === 0) {
2418
+ app.get("/", (context) => {
2419
+ return context.text("No routes found. Add routes to app/routes. Example: `app/routes/index.ts`", { status: 404 });
2420
+ });
2421
+ }
2422
+ if (!IS_PROD2) {
1843
2423
  console.log("[Hyperspan] File system routes (in app/routes):");
1844
2424
  console.table(routeMap);
1845
2425
  }
1846
- config.afterRoutesAdded && config.afterRoutesAdded(app);
1847
- app.all("*", (context) => {
1848
- const req = context.req;
1849
- if (STATIC_FILE_MATCHER.test(req.url)) {
1850
- const filePath = config.staticFileRoot + new URL(req.url).pathname;
1851
- const file = Bun.file(filePath);
1852
- let headers = {};
1853
- if (IS_PROD) {
1854
- headers = {
1855
- "cache-control": "public, max-age=31557600"
1856
- };
1857
- }
1858
- return new Response(file, { headers });
1859
- }
1860
- return app._defaultRoute(context);
2426
+ config2.afterRoutesAdded && config2.afterRoutesAdded(app);
2427
+ app.use("*", serveStatic2({
2428
+ root: config2.staticFileRoot
2429
+ }));
2430
+ app.notFound((context) => {
2431
+ return context.text("Not... found?", { status: 404 });
1861
2432
  });
1862
2433
  return app;
1863
2434
  }
1864
- async function buildClientJS() {
1865
- const sourceFile = resolve(PWD, "../", "./src/clientjs/hyperspan-client.ts");
1866
- const output = await Bun.build({
1867
- entrypoints: [sourceFile],
1868
- outdir: `./public/_hs/js`,
1869
- naming: IS_PROD ? "[dir]/[name]-[hash].[ext]" : undefined,
1870
- minify: IS_PROD
1871
- });
1872
- clientJSFile = output.outputs[0].path.split("/").reverse()[0];
1873
- return clientJSFile;
1874
- }
1875
- async function buildClientCSS() {
1876
- if (clientCSSFile) {
1877
- return clientCSSFile;
1878
- }
1879
- const cssDir = "./public/_hs/css/";
1880
- const cssFiles = await readdir(cssDir);
1881
- for (const file of cssFiles) {
1882
- if (clientCSSFile || !file.endsWith(".css")) {
1883
- continue;
1884
- }
1885
- return clientCSSFile = file.replace(cssDir, "");
1886
- }
1887
- if (!clientCSSFile) {
1888
- throw new Error(`Unable to build CSS files from ${cssDir}`);
2435
+
2436
+ class StreamResponse extends Response {
2437
+ constructor(iterator, options = {}) {
2438
+ super();
2439
+ const stream = createReadableStreamFromAsyncGenerator(iterator);
2440
+ return new Response(stream, {
2441
+ status: 200,
2442
+ headers: {
2443
+ "Content-Type": "text/html",
2444
+ "Transfer-Encoding": "chunked",
2445
+ ...options?.headers ?? {}
2446
+ },
2447
+ ...options
2448
+ });
1889
2449
  }
1890
2450
  }
1891
2451
  function createReadableStreamFromAsyncGenerator(output) {
@@ -1903,43 +2463,22 @@ function createReadableStreamFromAsyncGenerator(output) {
1903
2463
  }
1904
2464
  });
1905
2465
  }
1906
- function formRoute(handlerFn) {
1907
- return function _formRouteHandler(context) {
1908
- };
1909
- }
1910
- var IS_PROD = false;
1911
- var PWD = import.meta.dir;
1912
- var CWD = process.cwd();
1913
- var STATIC_FILE_MATCHER = /[^/\\&\?]+\.([a-zA-Z]+)$/;
1914
- var _routeCache = {};
1915
- var ROUTE_SEGMENT = /(\[[a-zA-Z_\.]+\])/g;
1916
- var clientJSFile;
1917
- var clientCSSFile;
1918
-
1919
- class StreamResponse {
1920
- constructor(iterator, options = {}) {
1921
- const stream = createReadableStreamFromAsyncGenerator(iterator);
1922
- return new Response(stream, {
1923
- status: 200,
1924
- headers: {
1925
- "Content-Type": "text/html",
1926
- "Transfer-Encoding": "chunked",
1927
- ...options?.headers ?? {}
1928
- },
1929
- ...options
1930
- });
1931
- }
2466
+ function normalizePath(urlPath) {
2467
+ return (urlPath.endsWith("/") ? urlPath.substring(0, urlPath.length - 1) : urlPath).toLowerCase() || "/";
1932
2468
  }
1933
2469
  export {
1934
2470
  runFileRoute,
1935
- formRoute,
2471
+ normalizePath,
1936
2472
  createServer,
2473
+ createRoute,
1937
2474
  createReadableStreamFromAsyncGenerator,
1938
- clientJSFile,
1939
- clientCSSFile,
2475
+ createForm,
2476
+ createComponent,
1940
2477
  buildRoutes,
1941
- buildClientJS,
1942
- buildClientCSS,
1943
2478
  StreamResponse,
1944
- IS_PROD
2479
+ IS_PROD2 as IS_PROD,
2480
+ HS_DEFAULT_LOADING,
2481
+ HSRoute,
2482
+ HSFormRoute,
2483
+ HSComponent
1945
2484
  };