@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/index.js CHANGED
@@ -1,332 +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
- // src/html.ts
71
- var import_escape_html = __toESM(require_escape_html(), 1);
72
-
73
- // src/clientjs/md5.js
74
- function md5cycle(x, k) {
75
- var a = x[0], b = x[1], c = x[2], d = x[3];
76
- a = ff(a, b, c, d, k[0], 7, -680876936);
77
- d = ff(d, a, b, c, k[1], 12, -389564586);
78
- c = ff(c, d, a, b, k[2], 17, 606105819);
79
- b = ff(b, c, d, a, k[3], 22, -1044525330);
80
- a = ff(a, b, c, d, k[4], 7, -176418897);
81
- d = ff(d, a, b, c, k[5], 12, 1200080426);
82
- c = ff(c, d, a, b, k[6], 17, -1473231341);
83
- b = ff(b, c, d, a, k[7], 22, -45705983);
84
- a = ff(a, b, c, d, k[8], 7, 1770035416);
85
- d = ff(d, a, b, c, k[9], 12, -1958414417);
86
- c = ff(c, d, a, b, k[10], 17, -42063);
87
- b = ff(b, c, d, a, k[11], 22, -1990404162);
88
- a = ff(a, b, c, d, k[12], 7, 1804603682);
89
- d = ff(d, a, b, c, k[13], 12, -40341101);
90
- c = ff(c, d, a, b, k[14], 17, -1502002290);
91
- b = ff(b, c, d, a, k[15], 22, 1236535329);
92
- a = gg(a, b, c, d, k[1], 5, -165796510);
93
- d = gg(d, a, b, c, k[6], 9, -1069501632);
94
- c = gg(c, d, a, b, k[11], 14, 643717713);
95
- b = gg(b, c, d, a, k[0], 20, -373897302);
96
- a = gg(a, b, c, d, k[5], 5, -701558691);
97
- d = gg(d, a, b, c, k[10], 9, 38016083);
98
- c = gg(c, d, a, b, k[15], 14, -660478335);
99
- b = gg(b, c, d, a, k[4], 20, -405537848);
100
- a = gg(a, b, c, d, k[9], 5, 568446438);
101
- d = gg(d, a, b, c, k[14], 9, -1019803690);
102
- c = gg(c, d, a, b, k[3], 14, -187363961);
103
- b = gg(b, c, d, a, k[8], 20, 1163531501);
104
- a = gg(a, b, c, d, k[13], 5, -1444681467);
105
- d = gg(d, a, b, c, k[2], 9, -51403784);
106
- c = gg(c, d, a, b, k[7], 14, 1735328473);
107
- b = gg(b, c, d, a, k[12], 20, -1926607734);
108
- a = hh(a, b, c, d, k[5], 4, -378558);
109
- d = hh(d, a, b, c, k[8], 11, -2022574463);
110
- c = hh(c, d, a, b, k[11], 16, 1839030562);
111
- b = hh(b, c, d, a, k[14], 23, -35309556);
112
- a = hh(a, b, c, d, k[1], 4, -1530992060);
113
- d = hh(d, a, b, c, k[4], 11, 1272893353);
114
- c = hh(c, d, a, b, k[7], 16, -155497632);
115
- b = hh(b, c, d, a, k[10], 23, -1094730640);
116
- a = hh(a, b, c, d, k[13], 4, 681279174);
117
- d = hh(d, a, b, c, k[0], 11, -358537222);
118
- c = hh(c, d, a, b, k[3], 16, -722521979);
119
- b = hh(b, c, d, a, k[6], 23, 76029189);
120
- a = hh(a, b, c, d, k[9], 4, -640364487);
121
- d = hh(d, a, b, c, k[12], 11, -421815835);
122
- c = hh(c, d, a, b, k[15], 16, 530742520);
123
- b = hh(b, c, d, a, k[2], 23, -995338651);
124
- a = ii(a, b, c, d, k[0], 6, -198630844);
125
- d = ii(d, a, b, c, k[7], 10, 1126891415);
126
- c = ii(c, d, a, b, k[14], 15, -1416354905);
127
- b = ii(b, c, d, a, k[5], 21, -57434055);
128
- a = ii(a, b, c, d, k[12], 6, 1700485571);
129
- d = ii(d, a, b, c, k[3], 10, -1894986606);
130
- c = ii(c, d, a, b, k[10], 15, -1051523);
131
- b = ii(b, c, d, a, k[1], 21, -2054922799);
132
- a = ii(a, b, c, d, k[8], 6, 1873313359);
133
- d = ii(d, a, b, c, k[15], 10, -30611744);
134
- c = ii(c, d, a, b, k[6], 15, -1560198380);
135
- b = ii(b, c, d, a, k[13], 21, 1309151649);
136
- a = ii(a, b, c, d, k[4], 6, -145523070);
137
- d = ii(d, a, b, c, k[11], 10, -1120210379);
138
- c = ii(c, d, a, b, k[2], 15, 718787259);
139
- b = ii(b, c, d, a, k[9], 21, -343485551);
140
- x[0] = add32(a, x[0]);
141
- x[1] = add32(b, x[1]);
142
- x[2] = add32(c, x[2]);
143
- x[3] = add32(d, x[3]);
144
- }
145
- function cmn(q, a, b, x, s, t) {
146
- a = add32(add32(a, q), add32(x, t));
147
- return add32(a << s | a >>> 32 - s, b);
148
- }
149
- function ff(a, b, c, d, x, s, t) {
150
- return cmn(b & c | ~b & d, a, b, x, s, t);
151
- }
152
- function gg(a, b, c, d, x, s, t) {
153
- return cmn(b & d | c & ~d, a, b, x, s, t);
154
- }
155
- function hh(a, b, c, d, x, s, t) {
156
- return cmn(b ^ c ^ d, a, b, x, s, t);
157
- }
158
- function ii(a, b, c, d, x, s, t) {
159
- return cmn(c ^ (b | ~d), a, b, x, s, t);
160
- }
161
- function md51(s) {
162
- var txt = "";
163
- var n = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i;
164
- for (i = 64;i <= s.length; i += 64) {
165
- md5cycle(state, md5blk(s.substring(i - 64, i)));
166
- }
167
- s = s.substring(i - 64);
168
- var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
169
- for (i = 0;i < s.length; i++)
170
- tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);
171
- tail[i >> 2] |= 128 << (i % 4 << 3);
172
- if (i > 55) {
173
- md5cycle(state, tail);
174
- for (i = 0;i < 16; i++)
175
- tail[i] = 0;
176
- }
177
- tail[14] = n * 8;
178
- md5cycle(state, tail);
179
- return state;
180
- }
181
- function md5blk(s) {
182
- var md5blks = [], i;
183
- for (i = 0;i < 64; i += 4) {
184
- md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
185
- }
186
- return md5blks;
187
- }
188
- function rhex(n) {
189
- var s = "", j = 0;
190
- for (;j < 4; j++)
191
- s += hex_chr[n >> j * 8 + 4 & 15] + hex_chr[n >> j * 8 & 15];
192
- return s;
193
- }
194
- function hex(x) {
195
- for (var i = 0;i < x.length; i++)
196
- x[i] = rhex(x[i]);
197
- return x.join("");
198
- }
199
- function add32(a, b) {
200
- return a + b & 4294967295;
201
- }
202
- function md5(s) {
203
- return hex(md51(s));
204
- }
205
- var hex_chr = "0123456789abcdef".split("");
1
+ // src/server.ts
2
+ import { readdir as readdir2 } from "node:fs/promises";
3
+ import { basename, extname, join } from "node:path";
206
4
 
207
- // src/html.ts
208
- function html(strings, ...values) {
209
- const content = [];
210
- if (values.length === 0) {
211
- content.push({ kind: "string_safe", value: strings.join("\n") });
212
- return new HSTemplate(content);
213
- }
214
- let i = 0;
215
- for (i = 0;i < values.length; i++) {
216
- content.push({ kind: "string_safe", value: strings[i] });
217
- let tValue = values[i] === undefined || values[i] === null || values[i] === "" ? "" : values[i];
218
- if (!Array.isArray(tValue)) {
219
- tValue = [tValue];
220
- }
221
- for (let j = 0;j < tValue.length; j++) {
222
- content.push({ kind: _typeOf(tValue[j]), value: tValue[j] });
223
- }
224
- }
225
- content.push({ kind: "string_safe", value: strings[i] });
226
- return new HSTemplate(content);
227
- }
228
- async function* _render(obj, promises = [], { js }) {
229
- let { kind, value } = obj;
230
- let id = randomId();
231
- if (!kind || !value) {
232
- kind = _typeOf(obj);
233
- value = obj;
234
- }
235
- if (value instanceof HSTemplate || value.__hsTemplate) {
236
- yield* renderToStream(value);
237
- } else if (typeof value.render !== "undefined") {
238
- value.id = id;
239
- yield await value.render();
240
- } else if (value === undefined || value === null) {
241
- yield "";
242
- } else {
243
- switch (kind) {
244
- case "string":
245
- yield import_escape_html.default(value);
246
- break;
247
- case "string_safe":
248
- yield value;
249
- break;
250
- case "array":
251
- yield* value;
252
- break;
253
- case "promise":
254
- const promise = value.then((v) => {
255
- return _render(v, promises, { js });
256
- });
257
- const pid = "async_" + id;
258
- promises.push({ id: pid, pending: true, promise });
259
- yield* renderToStream(html`<div id="${pid}">Loading...</div>`);
260
- break;
261
- case "function":
262
- const fns = renderFunctionToString(value);
263
- const fnId = "fn_" + md5(fns);
264
- if (!IS_CLIENT || !window.hyperspan._fn.has(fnId)) {
265
- js.push(`hyperspan.fn('${fnId}', ${fns});`);
266
- }
267
- yield `"hyperspan:${fnId}"`;
268
- break;
269
- case "json":
270
- yield "";
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;";
271
28
  break;
272
- case "number":
273
- yield String(value);
29
+ case 38:
30
+ escape = "&amp;";
274
31
  break;
275
- case "object":
276
- if (typeof value.render === "function") {
277
- yield value.render();
278
- } else if (typeof value.toString === "function") {
279
- yield value.toString();
280
- } else {
281
- yield value;
282
- }
32
+ case 39:
33
+ escape = "&#39;";
283
34
  break;
284
- case "generator":
285
- yield* value;
35
+ case 60:
36
+ escape = "&lt;";
286
37
  break;
287
- case "date":
288
- yield value.toISOString();
38
+ case 62:
39
+ escape = "&gt;";
289
40
  break;
290
41
  default:
291
- yield String(value);
42
+ continue;
43
+ }
44
+ if (lastIndex !== index) {
45
+ html += str.substring(lastIndex, index);
292
46
  }
47
+ lastIndex = index + 1;
48
+ html += escape;
293
49
  }
50
+ return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
294
51
  }
295
- async function* renderToStream(template) {
296
- let promises = [];
297
- let js = [];
298
- if (typeof template === "string") {
299
- return template;
52
+
53
+ class TmplHtml {
54
+ content = "";
55
+ asyncContent;
56
+ constructor(props) {
57
+ this.content = props.content;
58
+ this.asyncContent = props.asyncContent;
300
59
  }
301
- for (let i = 0;i < template.content.length; i++) {
302
- yield* _render(template.content[i], promises, { js });
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 }) || "";
73
+ }
74
+ }
75
+ content += strings[i] + (renderValue ? renderValue : "");
303
76
  }
304
- while (promises.length > 0) {
305
- const promisesToRun = promises.map((p) => p.promise.then((v) => {
306
- return { id: p.id, pending: false, value: v, promise: null };
307
- }));
308
- const result = await Promise.race(promisesToRun);
309
- yield* renderToStream(html`<template id="${result.id}_content">${result.value}</template>`);
310
- promises = promises.filter((p) => {
311
- return p.id !== result.id;
312
- });
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 "";
313
87
  }
314
- if (js.length !== 0) {
315
- yield "<script>" + js.join("\n") + "</script>";
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;
97
+ }
98
+ if (value?._kind === "html_safe") {
99
+ return value?.content || "";
100
+ }
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
+ });
110
+ }
111
+ if (typeof value.render === "function") {
112
+ return render(_htmlPlaceholder(id, value.render()));
113
+ }
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 :(");
316
127
  }
128
+ return escapeHtml(String(value));
317
129
  }
318
- async function renderToString(template) {
319
- let result = "";
320
- for await (const chunk of renderToStream(template)) {
321
- result += chunk;
322
- }
323
- return result;
130
+ function _htmlPlaceholder(id, content = "Loading...") {
131
+ return html`<!--hs:loading:${id}--><slot id="${id}">${content}</slot><!--/hs:loading:${id}-->`;
324
132
  }
325
- function compressHTMLString(str) {
326
- return str.replace(/(<(pre|script|style|textarea)[^]+?<\/\2)|(^|>)\s+|\s+(?=<|$)/g, "$1$3");
133
+ function render(tmpl) {
134
+ return tmpl.content;
135
+ }
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
+ }
147
+ });
148
+ }
149
+ return content;
327
150
  }
328
- function randomId() {
329
- return Math.random().toString(36).substring(2, 9);
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);
163
+ }
330
164
  }
331
165
  function _typeOf(obj) {
332
166
  if (obj instanceof Promise)
@@ -344,128 +178,2307 @@ function _typeOf(obj) {
344
178
  if (Array.isArray(obj))
345
179
  return "array";
346
180
  if (Number.isNaN(obj))
347
- return "nan";
181
+ return "NaN";
348
182
  if (obj === undefined)
349
183
  return "undefined";
350
184
  if (obj === null)
351
185
  return "null";
352
186
  if (isGenerator(obj))
353
187
  return "generator";
354
- if (isPlainObject(obj))
355
- return "json";
356
188
  return typeof obj;
357
189
  }
358
190
  function isGenerator(obj) {
359
191
  return obj && typeof obj.next == "function" && typeof obj.throw == "function";
360
192
  }
361
- function isPlainObject(val) {
362
- return Object == val.constructor;
363
- }
364
- function clientComponent(id, wc) {
365
- const comp = {
366
- ...wc,
367
- state: wc.state || {},
368
- id,
369
- randomId() {
370
- return Math.random().toString(36).substring(2, 9);
371
- },
372
- setState(fn) {
373
- try {
374
- const val = typeof fn === "function" ? fn(this.state) : fn;
375
- this.state = val;
376
- const el = document.getElementById(this.id);
377
- if (el) {
378
- el.dataset.state = JSON.stringify(val);
193
+
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;
198
+ function getPattern() {
199
+ if (pattern instanceof RegExp) {
200
+ return pattern;
201
+ }
202
+ try {
203
+ pattern = new RegExp(fullPattern, "i");
204
+ } catch (error) {
205
+ pattern = naivePattern;
206
+ }
207
+ return pattern;
208
+ }
209
+ function isbot(userAgent) {
210
+ return Boolean(userAgent) && getPattern().test(userAgent);
211
+ }
212
+
213
+ // src/clientjs/md5.js
214
+ var hex_chr = "0123456789abcdef".split("");
215
+
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;
245
+ }
246
+ foundCSSFile = file.replace(cssDir, "");
247
+ clientCSSFiles.set("_hs", foundCSSFile);
248
+ break;
249
+ }
250
+ if (!foundCSSFile) {
251
+ console.log(`Unable to build CSS files from ${cssDir}`);
252
+ }
253
+ }
254
+
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;
282
+ } else {
283
+ throw err;
284
+ }
379
285
  }
380
- } catch (e) {
381
- console.error(e);
286
+ } else {
287
+ if (context.finalized === false && onNotFound) {
288
+ res = await onNotFound(context);
289
+ }
290
+ }
291
+ if (res && (context.finalized === false || isError)) {
292
+ context.res = res;
382
293
  }
383
- return this.state;
384
- },
385
- mergeState(newState) {
386
- return this.setState(Object.assign(this.state, newState));
294
+ return context;
387
295
  }
388
296
  };
389
- if (typeof window !== "undefined") {
390
- window.hyperspan.wc.set(id, comp);
391
- }
392
- return (attrs, state) => {
393
- const _state = Object.assign({}, comp.state, state || {});
394
- return html`
395
- <script>
396
- ${html.raw(renderObjectToLiteralString(comp))};
397
- </script>
398
- <hs-wc id="${attrs?.id || id}" data-state="${JSON.stringify(_state)}"></hs-wc>
399
- `;
400
- };
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);
313
+ }
314
+ return {};
401
315
  }
402
- function renderFunctionToString(fn) {
403
- let fns = fn.toString();
404
- const firstLine = fns.split("\n")[0];
405
- const isFatArrow = firstLine.includes("=>");
406
- const isAsync = firstLine.includes("async");
407
- const hasFunctionWord = firstLine.includes("function");
408
- if (isFatArrow) {
409
- fns = "function (...args) { return (" + fns + ")(..args); }";
410
- } else {
411
- if (!hasFunctionWord) {
412
- fns = "function " + fns;
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);
413
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
+ });
414
334
  }
415
- if (isAsync) {
416
- fns = "async " + fns.replace("async ", "");
417
- }
418
- return fns;
335
+ return form;
419
336
  }
420
- function renderObjectToLiteralString(obj) {
421
- const lines = [];
422
- let str = 'hyperspan.wc.set("' + obj.id + '", {\n';
423
- for (const prop in obj) {
424
- const kind = _typeOf(obj[prop]);
425
- let val = obj[prop];
426
- switch (kind) {
427
- case "string":
428
- lines.push([prop, ": ", '"' + val + '"']);
429
- break;
430
- case "object":
431
- case "json":
432
- lines.push([prop, ": ", "JSON.parse('" + JSON.stringify(val) + "')"]);
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;
346
+ }
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();
368
+ }
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]);
433
391
  break;
434
- case "function":
435
- const fn = val.toString();
436
- const isFatArrow = fn.split("\n")[0].includes("=>");
437
- if (isFatArrow) {
438
- lines.push([prop, ": ", fn]);
392
+ }
393
+ }
394
+ }
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];
413
+ }
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
+ });
427
+ }
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);
453
+ }
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;
459
+ }
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("/");
439
470
  } else {
440
- lines.push([fn]);
471
+ results.push(basePath);
441
472
  }
442
- break;
443
- default:
444
- lines.push([prop, ": ", val]);
473
+ const optionalSegment = segment.replace("?", "");
474
+ basePath += "/" + optionalSegment;
475
+ results.push(basePath);
476
+ } else {
477
+ basePath += "/" + segment;
478
+ }
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;
486
+ }
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);
509
+ }
510
+ encoded = /[%+]/.test(url);
511
+ if (!encoded) {
512
+ return;
445
513
  }
446
514
  }
447
- str += lines.map((line) => line.join("") + ",").join("\n");
448
- str += "\n})";
449
- return str;
450
- }
451
- var IS_CLIENT = typeof window !== "undefined";
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;
523
+ }
524
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
525
+ if (encoded) {
526
+ name = _decodeURI(name);
527
+ }
528
+ keyIndex = nextKeyIndex;
529
+ if (name === "") {
530
+ continue;
531
+ }
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
+ }
540
+ }
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;
548
+ }
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;
452
557
 
453
- class HSTemplate {
454
- __hsTemplate = true;
455
- content;
456
- constructor(content) {
457
- this.content = content;
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 = {};
458
572
  }
459
- }
460
- html.raw = (value) => {
461
- return new HSTemplate([{ kind: "string_safe", value }]);
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
+ }
589
+ }
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;
604
+ }
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
+ });
628
+ }
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();
682
+ }
683
+ if (str instanceof Promise) {
684
+ str = await str;
685
+ }
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");
749
+ }
750
+ }
751
+ get executionCtx() {
752
+ if (this.#executionCtx) {
753
+ return this.#executionCtx;
754
+ } else {
755
+ throw Error("This context has no ExecutionContext");
756
+ }
757
+ }
758
+ get res() {
759
+ this.#isFresh = false;
760
+ return this.#res ||= new Response("404 Not Found", { status: 404 });
761
+ }
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);
775
+ }
776
+ } else {
777
+ _res.headers.set(k, v);
778
+ }
779
+ }
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
+ }
790
+ }
791
+ }
792
+ this.#res = _res;
793
+ this.finalized = true;
794
+ }
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;
815
+ }
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
+ }
830
+ }
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
+ }
837
+ }
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 {};
853
+ }
854
+ return Object.fromEntries(this.#var);
855
+ }
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);
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);
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);
897
+ } else {
898
+ this.#headers.delete(k);
899
+ for (const v2 of v) {
900
+ this.#headers.append(k, v2);
901
+ }
902
+ }
903
+ }
904
+ return new Response(data, {
905
+ status,
906
+ headers: this.#headers
907
+ });
908
+ }
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 = {};
919
+ }
920
+ this.#preparedHeaders["content-type"] = TEXT_PLAIN;
921
+ if (typeof arg === "number") {
922
+ return this.#newResponse(text, arg, headers);
923
+ }
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
+ });
939
+ }
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();
971
+ }
972
+ console.error(err);
973
+ return c.text("Internal Server Error", 500);
462
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);
998
+ }
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
+ });
1012
+ }
1013
+ }
1014
+ return this;
1015
+ };
1016
+ this.use = (arg1, ...handlers) => {
1017
+ if (typeof arg1 === "string") {
1018
+ this.#path = arg1;
1019
+ } else {
1020
+ this.#path = "*";
1021
+ handlers.unshift(arg1);
1022
+ }
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;
1055
+ }
1056
+ basePath(path) {
1057
+ const subApp = this.#clone();
1058
+ subApp._basePath = mergePath(this._basePath, path);
1059
+ return subApp;
1060
+ }
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;
1108
+ }
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
+ })();
1158
+ }
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);
1257
+ }
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("|") + ")";
1274
+ }
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];
1330
+ }
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
+ });
1376
+ }
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
+ }
1389
+ }
1390
+ const handlerMap = [];
1391
+ for (const i in indexReplacementMap) {
1392
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
1393
+ }
1394
+ return [regexp, handlerMap, staticMap];
1395
+ }
1396
+ function findMiddleware(middleware, path) {
1397
+ if (!middleware) {
1398
+ return;
1399
+ }
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]];
1403
+ }
1404
+ }
1405
+ return;
1406
+ }
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
+ });
1439
+ } else {
1440
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
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
+ });
1467
+ }
1468
+ }
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);
1511
+ }
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);
1526
+ }
1527
+ this.#routes.push([method, path, handler]);
1528
+ }
1529
+ match(method, path) {
1530
+ if (!this.#routes) {
1531
+ throw new Error("Fatal error");
1532
+ }
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;
1555
+ }
1556
+ if (i === len) {
1557
+ throw new Error("Fatal error");
1558
+ }
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.");
1565
+ }
1566
+ return this.#routers[0];
1567
+ }
1568
+ };
1569
+
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;
1638
+ }
1639
+ }
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
+ }
1668
+ }
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
+ }
1708
+ } else {
1709
+ child.#params = params;
1710
+ tempNodes.push(child);
1711
+ }
1712
+ }
1713
+ }
1714
+ }
1715
+ curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
1716
+ }
1717
+ if (handlerSets.length > 1) {
1718
+ handlerSets.sort((a, b) => {
1719
+ return a.score - b.score;
1720
+ });
1721
+ }
1722
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
1723
+ }
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;
1732
+ }
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);
1738
+ }
1739
+ return;
1740
+ }
1741
+ this.#node.insert(method, path, handler);
1742
+ }
1743
+ match(method, path) {
1744
+ return this.#node.search(method, path);
1745
+ }
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
+ });
1755
+ }
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;
1884
+ } else {
1885
+ root = options.root;
1886
+ }
1887
+ }
1888
+ return async (c, next) => {
1889
+ if (c.finalized) {
1890
+ await next();
1891
+ return;
1892
+ }
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 += "/";
1902
+ }
1903
+ }
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
+ }
1934
+ }
1935
+ if (content instanceof Response) {
1936
+ return c.newResponse(content.body, content);
1937
+ }
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);
1958
+ }
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;
2003
+ }
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;
2016
+ }
2017
+ send(source, options) {
2018
+ this.#init.send(source, options ?? {});
2019
+ }
2020
+ raw;
2021
+ binaryType = "arraybuffer";
2022
+ get readyState() {
2023
+ return this.#init.readyState;
2024
+ }
2025
+ url;
2026
+ protocol;
2027
+ close(code, reason) {
2028
+ this.#init.close(code, reason);
2029
+ }
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.`);
2038
+ }
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;
2072
+ }
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);
2106
+ }
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;
2111
+ }
2112
+ static [Symbol.hasInstance](inst) {
2113
+ return inst?._tag === ZOD_ERROR;
2114
+ }
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));
2123
+ } else {
2124
+ formErrors.push(mapper(sub));
2125
+ }
2126
+ }
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));
2144
+ } else {
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++;
2158
+ }
2159
+ }
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;
2172
+ }
2173
+ if (result.issues.length) {
2174
+ throw new (this?.Error ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
2175
+ }
2176
+ return result.value;
2177
+ }
2178
+
2179
+ // ../../node_modules/zod/dist/esm/errors.js
2180
+ class ZodError extends $ZodError {
2181
+ format(mapper) {
2182
+ return formatError(this, mapper);
2183
+ }
2184
+ flatten(mapper) {
2185
+ return flattenError(this, mapper);
2186
+ }
2187
+ addIssue(issue) {
2188
+ this.issues.push(issue);
2189
+ }
2190
+ addIssues(issues) {
2191
+ this.issues.push(...issues);
2192
+ }
2193
+ get isEmpty() {
2194
+ return this.issues.length === 0;
2195
+ }
2196
+ }
2197
+
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;
2226
+ }
2227
+ }
2228
+
2229
+ class HSRoute {
2230
+ _kind = "hsRoute";
2231
+ _handlers = {};
2232
+ _methods = null;
2233
+ constructor(handler) {
2234
+ this._handlers.GET = handler;
2235
+ }
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());
2252
+ }
2253
+ getDefaultData() {
2254
+ if (!this._schema) {
2255
+ return {};
2256
+ }
2257
+ const data = parse(this._schema, {});
2258
+ return data;
2259
+ }
2260
+ renderForm(data) {
2261
+ return this._form(data || this.getDefaultData());
2262
+ }
2263
+ get(handler) {
2264
+ this._handlers.GET = handler;
2265
+ return this;
2266
+ }
2267
+ patch(handler) {
2268
+ this._handlers.PATCH = handler;
2269
+ return this;
2270
+ }
2271
+ post(handler) {
2272
+ this._handlers.POST = handler;
2273
+ return this;
2274
+ }
2275
+ put(handler) {
2276
+ this._handlers.PUT = handler;
2277
+ return this;
2278
+ }
2279
+ delete(handler) {
2280
+ this._handlers.DELETE = handler;
2281
+ return this;
2282
+ }
2283
+ }
2284
+ async function runFileRoute(RouteModule, context) {
2285
+ const req = context.req;
2286
+ const url = new URL(req.url);
2287
+ const qs = url.searchParams;
2288
+ const userIsBot = isbot(context.req.header("User-Agent"));
2289
+ const streamOpt = qs.get("__nostream") ? !Boolean(qs.get("__nostream")) : undefined;
2290
+ const streamingEnabled = !userIsBot && (streamOpt !== undefined ? streamOpt : true);
2291
+ const RouteComponent = RouteModule.default;
2292
+ const reqMethod = req.method.toUpperCase();
2293
+ try {
2294
+ if (RouteModule[reqMethod] !== undefined) {
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);
2312
+ }
2313
+ if (routeContent instanceof Response) {
2314
+ return routeContent;
2315
+ }
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
+ }
2323
+ }
2324
+ return routeContent;
2325
+ } catch (e) {
2326
+ console.error(e);
2327
+ return await showErrorReponse(context, e);
2328
+ }
2329
+ }
2330
+ async function runAPIRoute(routeFn, context, middlewareResult) {
2331
+ try {
2332
+ return await routeFn(context, middlewareResult);
2333
+ } catch (err) {
2334
+ const e = err;
2335
+ console.error(e);
2336
+ return context.json({
2337
+ meta: { success: false },
2338
+ data: {
2339
+ message: e.message,
2340
+ stack: IS_PROD2 ? undefined : e.stack?.split(`
2341
+ `)
2342
+ }
2343
+ }, { status: 500 });
2344
+ }
2345
+ }
2346
+ async function showErrorReponse(context, err) {
2347
+ const output = render(html`
2348
+ <main>
2349
+ <h1>Error</h1>
2350
+ <pre>${err.message}</pre>
2351
+ <pre>${!IS_PROD2 && err.stack ? err.stack.split(`
2352
+ `).slice(1).join(`
2353
+ `) : ""}</pre>
2354
+ </main>
2355
+ `);
2356
+ return context.html(output, {
2357
+ status: 500
2358
+ });
2359
+ }
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 });
2365
+ const routes = [];
2366
+ for (const file of files) {
2367
+ if (!file.includes(".") || basename(file).startsWith(".")) {
2368
+ continue;
2369
+ }
2370
+ let route = "/" + file.replace(extname(file), "");
2371
+ if (route.endsWith("index")) {
2372
+ route = route === "index" ? "/" : route.substring(0, route.length - 6);
2373
+ }
2374
+ let params = [];
2375
+ const dynamicPaths = ROUTE_SEGMENT.test(route);
2376
+ if (dynamicPaths) {
2377
+ params = [];
2378
+ route = route.replace(ROUTE_SEGMENT, (match) => {
2379
+ const paramName = match.replace(/[^a-zA-Z_\.]+/g, "");
2380
+ if (match.includes("...")) {
2381
+ params.push(paramName.replace("...", ""));
2382
+ return "*";
2383
+ } else {
2384
+ params.push(paramName);
2385
+ return ":" + paramName;
2386
+ }
2387
+ });
2388
+ }
2389
+ routes.push({
2390
+ file: join("./", routesDir, file),
2391
+ route: route || "/",
2392
+ params
2393
+ });
2394
+ }
2395
+ return routes;
2396
+ }
2397
+ async function createServer(config2) {
2398
+ await Promise.all([buildClientJS(), buildClientCSS()]);
2399
+ const app = new Hono2;
2400
+ config2.beforeRoutesAdded && config2.beforeRoutesAdded(app);
2401
+ const fileRoutes = await buildRoutes(config2);
2402
+ const routeMap = [];
2403
+ for (let i = 0;i < fileRoutes.length; i++) {
2404
+ let route = fileRoutes[i];
2405
+ const fullRouteFile = join(CWD, route.file);
2406
+ const routePattern = normalizePath(route.route);
2407
+ routeMap.push({ route: routePattern, file: route.file });
2408
+ const routeModule = await import(fullRouteFile);
2409
+ app.all(routePattern, async (context) => {
2410
+ const matchedRoute = await runFileRoute(routeModule, context);
2411
+ if (matchedRoute) {
2412
+ return matchedRoute;
2413
+ }
2414
+ return context.notFound();
2415
+ });
2416
+ }
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) {
2423
+ console.log("[Hyperspan] File system routes (in app/routes):");
2424
+ console.table(routeMap);
2425
+ }
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 });
2432
+ });
2433
+ return app;
2434
+ }
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
+ });
2449
+ }
2450
+ }
2451
+ function createReadableStreamFromAsyncGenerator(output) {
2452
+ const encoder = new TextEncoder;
2453
+ return new ReadableStream({
2454
+ async start(controller) {
2455
+ while (true) {
2456
+ const { done, value } = await output.next();
2457
+ if (done) {
2458
+ controller.close();
2459
+ break;
2460
+ }
2461
+ controller.enqueue(encoder.encode(value));
2462
+ }
2463
+ }
2464
+ });
2465
+ }
2466
+ function normalizePath(urlPath) {
2467
+ return (urlPath.endsWith("/") ? urlPath.substring(0, urlPath.length - 1) : urlPath).toLowerCase() || "/";
2468
+ }
463
2469
  export {
464
- renderToString,
465
- renderToStream,
466
- html,
467
- compressHTMLString,
468
- clientComponent,
469
- _typeOf,
470
- HSTemplate
2470
+ runFileRoute,
2471
+ normalizePath,
2472
+ createServer,
2473
+ createRoute,
2474
+ createReadableStreamFromAsyncGenerator,
2475
+ createForm,
2476
+ createComponent,
2477
+ buildRoutes,
2478
+ StreamResponse,
2479
+ IS_PROD2 as IS_PROD,
2480
+ HS_DEFAULT_LOADING,
2481
+ HSRoute,
2482
+ HSFormRoute,
2483
+ HSComponent
471
2484
  };