@hyperspan/framework 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js DELETED
@@ -1,1945 +0,0 @@
1
- var __create = Object.create;
2
- var __getProtoOf = Object.getPrototypeOf;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __toESM = (mod, isNodeMode, target) => {
7
- target = mod != null ? __create(__getProtoOf(mod)) : {};
8
- const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
9
- for (let key of __getOwnPropNames(mod))
10
- if (!__hasOwnProp.call(to, key))
11
- __defProp(to, key, {
12
- get: () => mod[key],
13
- enumerable: true
14
- });
15
- return to;
16
- };
17
- var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
18
-
19
- // node_modules/escape-html/index.js
20
- var require_escape_html = __commonJS((exports, module) => {
21
- function escapeHtml(string) {
22
- var str = "" + string;
23
- var match = matchHtmlRegExp.exec(str);
24
- if (!match) {
25
- return str;
26
- }
27
- var escape;
28
- var html = "";
29
- var index = 0;
30
- var lastIndex = 0;
31
- for (index = match.index;index < str.length; index++) {
32
- switch (str.charCodeAt(index)) {
33
- case 34:
34
- escape = "&quot;";
35
- break;
36
- case 38:
37
- escape = "&amp;";
38
- break;
39
- case 39:
40
- escape = "&#39;";
41
- break;
42
- case 60:
43
- escape = "&lt;";
44
- break;
45
- case 62:
46
- escape = "&gt;";
47
- break;
48
- default:
49
- continue;
50
- }
51
- if (lastIndex !== index) {
52
- html += str.substring(lastIndex, index);
53
- }
54
- lastIndex = index + 1;
55
- html += escape;
56
- }
57
- return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
58
- }
59
- /*!
60
- * escape-html
61
- * Copyright(c) 2012-2013 TJ Holowaychuk
62
- * Copyright(c) 2015 Andreas Lubbe
63
- * Copyright(c) 2015 Tiancheng "Timothy" Gu
64
- * MIT Licensed
65
- */
66
- var matchHtmlRegExp = /["'&<>]/;
67
- module.exports = escapeHtml;
68
- });
69
-
70
- // node_modules/trek-router/index.js
71
- var require_trek_router = __commonJS((exports, module) => {
72
- /*!
73
- * router
74
- * Copyright(c) 2015-2017 Fangdun Cai
75
- * MIT Licensed
76
- */
77
- var [SKIND, PKIND, AKIND, STAR, SLASH, COLON] = [0, 1, 2, 42, 47, 58];
78
-
79
- class Node {
80
- constructor(prefix = "/", children = [], kind = SKIND, map = Object.create(null)) {
81
- this.label = prefix.charCodeAt(0);
82
- this.prefix = prefix;
83
- this.children = children;
84
- this.kind = kind;
85
- this.map = map;
86
- }
87
- addChild(n) {
88
- this.children.push(n);
89
- }
90
- findChild(c, t, l, e, i = 0) {
91
- for (l = this.children.length;i < l; i++) {
92
- e = this.children[i];
93
- if (c === e.label && t === e.kind) {
94
- return e;
95
- }
96
- }
97
- }
98
- findChildWithLabel(c, l, e, i = 0) {
99
- for (l = this.children.length;i < l; i++) {
100
- e = this.children[i];
101
- if (c === e.label) {
102
- return e;
103
- }
104
- }
105
- }
106
- findChildByKind(t, l, e, i = 0) {
107
- for (l = this.children.length;i < l; i++) {
108
- e = this.children[i];
109
- if (t === e.kind) {
110
- return e;
111
- }
112
- }
113
- }
114
- addHandler(method, handler, pnames) {
115
- this.map[method] = { handler, pnames };
116
- }
117
- findHandler(method) {
118
- return this.map[method];
119
- }
120
- }
121
-
122
- class Router {
123
- constructor() {
124
- this.tree = new Node;
125
- }
126
- add(method, path, handler) {
127
- let [i, l, pnames, ch, j] = [0, path.length, []];
128
- for (;i < l; ++i) {
129
- ch = path.charCodeAt(i);
130
- if (ch === COLON) {
131
- j = i + 1;
132
- this.insert(method, path.substring(0, i), SKIND);
133
- while (i < l && path.charCodeAt(i) !== SLASH) {
134
- i++;
135
- }
136
- pnames.push(path.substring(j, i));
137
- path = path.substring(0, j) + path.substring(i);
138
- i = j;
139
- l = path.length;
140
- if (i === l) {
141
- this.insert(method, path.substring(0, i), PKIND, pnames, handler);
142
- return;
143
- }
144
- this.insert(method, path.substring(0, i), PKIND, pnames);
145
- } else if (ch === STAR) {
146
- this.insert(method, path.substring(0, i), SKIND);
147
- pnames.push("*");
148
- this.insert(method, path.substring(0, l), AKIND, pnames, handler);
149
- return;
150
- }
151
- }
152
- this.insert(method, path, SKIND, pnames, handler);
153
- }
154
- insert(method, path, t, pnames, handler) {
155
- let [cn, prefix, sl, pl, l, max, n, c] = [this.tree];
156
- while (true) {
157
- prefix = cn.prefix;
158
- sl = path.length;
159
- pl = prefix.length;
160
- l = 0;
161
- max = sl < pl ? sl : pl;
162
- while (l < max && path.charCodeAt(l) === prefix.charCodeAt(l)) {
163
- l++;
164
- }
165
- if (l < pl) {
166
- n = new Node(prefix.substring(l), cn.children, cn.kind, cn.map);
167
- cn.children = [n];
168
- cn.label = prefix.charCodeAt(0);
169
- cn.prefix = prefix.substring(0, l);
170
- cn.map = Object.create(null);
171
- cn.kind = SKIND;
172
- if (l === sl) {
173
- cn.addHandler(method, handler, pnames);
174
- cn.kind = t;
175
- } else {
176
- n = new Node(path.substring(l), [], t);
177
- n.addHandler(method, handler, pnames);
178
- cn.addChild(n);
179
- }
180
- } else if (l < sl) {
181
- path = path.substring(l);
182
- c = cn.findChildWithLabel(path.charCodeAt(0));
183
- if (c !== undefined) {
184
- cn = c;
185
- continue;
186
- }
187
- n = new Node(path, [], t);
188
- n.addHandler(method, handler, pnames);
189
- cn.addChild(n);
190
- } else if (handler !== undefined) {
191
- cn.addHandler(method, handler, pnames);
192
- }
193
- return;
194
- }
195
- }
196
- find(method, path, cn, n = 0, result = [undefined, []]) {
197
- cn = cn || this.tree;
198
- const sl = path.length;
199
- const prefix = cn.prefix;
200
- const pvalues = result[1];
201
- let i, pl, l, max, c;
202
- let preSearch;
203
- if (sl === 0 || path === prefix) {
204
- const r = cn.findHandler(method);
205
- if ((result[0] = r && r.handler) !== undefined) {
206
- const pnames = r.pnames;
207
- if (pnames !== undefined) {
208
- for (i = 0, l = pnames.length;i < l; ++i) {
209
- pvalues[i] = {
210
- name: pnames[i],
211
- value: pvalues[i]
212
- };
213
- }
214
- }
215
- }
216
- return result;
217
- }
218
- pl = prefix.length;
219
- l = 0;
220
- max = sl < pl ? sl : pl;
221
- while (l < max && path.charCodeAt(l) === prefix.charCodeAt(l)) {
222
- l++;
223
- }
224
- if (l === pl) {
225
- path = path.substring(l);
226
- }
227
- preSearch = path;
228
- c = cn.findChild(path.charCodeAt(0), SKIND);
229
- if (c !== undefined) {
230
- this.find(method, path, c, n, result);
231
- if (result[0] !== undefined) {
232
- return result;
233
- }
234
- path = preSearch;
235
- }
236
- if (l !== pl) {
237
- return result;
238
- }
239
- c = cn.findChildByKind(PKIND);
240
- if (c !== undefined) {
241
- l = path.length;
242
- i = 0;
243
- while (i < l && path.charCodeAt(i) !== SLASH) {
244
- i++;
245
- }
246
- pvalues[n] = path.substring(0, i);
247
- n++;
248
- preSearch = path;
249
- path = path.substring(i);
250
- this.find(method, path, c, n, result);
251
- if (result[0] !== undefined) {
252
- return result;
253
- }
254
- n--;
255
- pvalues.pop();
256
- path = preSearch;
257
- }
258
- c = cn.findChildByKind(AKIND);
259
- if (c !== undefined) {
260
- pvalues[n] = path;
261
- path = "";
262
- this.find(method, path, c, n, result);
263
- }
264
- return result;
265
- }
266
- }
267
- Router.Node = Node;
268
- module.exports = Router;
269
- });
270
-
271
- // node_modules/trek-middleware/index.js
272
- var require_trek_middleware = __commonJS((exports, module) => {
273
- /*!
274
- * middleware
275
- * Copyright(c) 2015-2017 Fangdun Cai
276
- * MIT Licensed
277
- */
278
- module.exports = class Middleware extends Array {
279
- next(context, last, i, done, called, fn) {
280
- if (done = i > this.length)
281
- return;
282
- fn = this[i] || last;
283
- return fn && fn(context, () => {
284
- if (called)
285
- throw new Error("next() called multiple times");
286
- called = true;
287
- return Promise.resolve(this.next(context, last, i + 1));
288
- });
289
- }
290
- compose(context, last) {
291
- try {
292
- return Promise.resolve(this.next(context, last, 0));
293
- } catch (err) {
294
- return Promise.reject(err);
295
- }
296
- }
297
- };
298
- });
299
-
300
- // node_modules/@fastify/deepmerge/index.js
301
- var require_deepmerge = __commonJS((exports, module) => {
302
- function deepmergeConstructor(options) {
303
- function isNotPrototypeKey(value) {
304
- return value !== "constructor" && value !== "prototype" && value !== "__proto__";
305
- }
306
- function cloneArray(value) {
307
- let i = 0;
308
- const il = value.length;
309
- const result = new Array(il);
310
- for (i = 0;i < il; ++i) {
311
- result[i] = clone(value[i]);
312
- }
313
- return result;
314
- }
315
- function cloneObject(target) {
316
- const result = {};
317
- if (cloneProtoObject && Object.getPrototypeOf(target) !== JSON_PROTO) {
318
- return cloneProtoObject(target);
319
- }
320
- const targetKeys = getKeys(target);
321
- let i, il, key;
322
- for (i = 0, il = targetKeys.length;i < il; ++i) {
323
- isNotPrototypeKey(key = targetKeys[i]) && (result[key] = clone(target[key]));
324
- }
325
- return result;
326
- }
327
- function concatArrays(target, source) {
328
- const tl = target.length;
329
- const sl = source.length;
330
- let i = 0;
331
- const result = new Array(tl + sl);
332
- for (i = 0;i < tl; ++i) {
333
- result[i] = clone(target[i]);
334
- }
335
- for (i = 0;i < sl; ++i) {
336
- result[i + tl] = clone(source[i]);
337
- }
338
- return result;
339
- }
340
- const propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
341
- function getSymbolsAndKeys(value) {
342
- const result = Object.keys(value);
343
- const keys = Object.getOwnPropertySymbols(value);
344
- for (let i = 0, il = keys.length;i < il; ++i) {
345
- propertyIsEnumerable.call(value, keys[i]) && result.push(keys[i]);
346
- }
347
- return result;
348
- }
349
- const getKeys = options && options.symbols ? getSymbolsAndKeys : Object.keys;
350
- const cloneProtoObject = typeof options?.cloneProtoObject === "function" ? options.cloneProtoObject : undefined;
351
- function isMergeableObject(value) {
352
- return typeof value === "object" && value !== null && !(value instanceof RegExp) && !(value instanceof Date);
353
- }
354
- function isPrimitive(value) {
355
- return typeof value !== "object" || value === null;
356
- }
357
- const isPrimitiveOrBuiltIn = typeof Buffer !== "undefined" ? (value) => typeof value !== "object" || value === null || value instanceof RegExp || value instanceof Date || value instanceof Buffer : (value) => typeof value !== "object" || value === null || value instanceof RegExp || value instanceof Date;
358
- const mergeArray = options && typeof options.mergeArray === "function" ? options.mergeArray({ clone, deepmerge: _deepmerge, getKeys, isMergeableObject }) : concatArrays;
359
- function clone(entry) {
360
- return isMergeableObject(entry) ? Array.isArray(entry) ? cloneArray(entry) : cloneObject(entry) : entry;
361
- }
362
- function mergeObject(target, source) {
363
- const result = {};
364
- const targetKeys = getKeys(target);
365
- const sourceKeys = getKeys(source);
366
- let i, il, key;
367
- for (i = 0, il = targetKeys.length;i < il; ++i) {
368
- isNotPrototypeKey(key = targetKeys[i]) && sourceKeys.indexOf(key) === -1 && (result[key] = clone(target[key]));
369
- }
370
- for (i = 0, il = sourceKeys.length;i < il; ++i) {
371
- isNotPrototypeKey(key = sourceKeys[i]) && ((key in target) && (targetKeys.indexOf(key) !== -1 && (result[key] = _deepmerge(target[key], source[key])), true) || (result[key] = clone(source[key])));
372
- }
373
- return result;
374
- }
375
- function _deepmerge(target, source) {
376
- const sourceIsArray = Array.isArray(source);
377
- const targetIsArray = Array.isArray(target);
378
- if (isPrimitive(source)) {
379
- return source;
380
- } else if (isPrimitiveOrBuiltIn(target)) {
381
- return clone(source);
382
- } else if (sourceIsArray && targetIsArray) {
383
- return mergeArray(target, source);
384
- } else if (sourceIsArray !== targetIsArray) {
385
- return clone(source);
386
- } else {
387
- return mergeObject(target, source);
388
- }
389
- }
390
- function _deepmergeAll() {
391
- switch (arguments.length) {
392
- case 0:
393
- return {};
394
- case 1:
395
- return clone(arguments[0]);
396
- case 2:
397
- return _deepmerge(arguments[0], arguments[1]);
398
- }
399
- let result;
400
- for (let i = 0, il = arguments.length;i < il; ++i) {
401
- result = _deepmerge(result, arguments[i]);
402
- }
403
- return result;
404
- }
405
- return options && options.all ? _deepmergeAll : _deepmerge;
406
- }
407
- var JSON_PROTO = Object.getPrototypeOf({});
408
- module.exports = deepmergeConstructor;
409
- module.exports.default = deepmergeConstructor;
410
- module.exports.deepmerge = deepmergeConstructor;
411
- });
412
-
413
- // src/server.ts
414
- import { readdir } from "node:fs/promises";
415
- import { basename, extname, join, resolve } from "node:path";
416
-
417
- // src/html.ts
418
- var import_escape_html = __toESM(require_escape_html(), 1);
419
-
420
- // src/clientjs/md5.js
421
- function md5cycle(x, k) {
422
- var a = x[0], b = x[1], c = x[2], d = x[3];
423
- a = ff(a, b, c, d, k[0], 7, -680876936);
424
- d = ff(d, a, b, c, k[1], 12, -389564586);
425
- c = ff(c, d, a, b, k[2], 17, 606105819);
426
- b = ff(b, c, d, a, k[3], 22, -1044525330);
427
- a = ff(a, b, c, d, k[4], 7, -176418897);
428
- d = ff(d, a, b, c, k[5], 12, 1200080426);
429
- c = ff(c, d, a, b, k[6], 17, -1473231341);
430
- b = ff(b, c, d, a, k[7], 22, -45705983);
431
- a = ff(a, b, c, d, k[8], 7, 1770035416);
432
- d = ff(d, a, b, c, k[9], 12, -1958414417);
433
- c = ff(c, d, a, b, k[10], 17, -42063);
434
- b = ff(b, c, d, a, k[11], 22, -1990404162);
435
- a = ff(a, b, c, d, k[12], 7, 1804603682);
436
- d = ff(d, a, b, c, k[13], 12, -40341101);
437
- c = ff(c, d, a, b, k[14], 17, -1502002290);
438
- b = ff(b, c, d, a, k[15], 22, 1236535329);
439
- a = gg(a, b, c, d, k[1], 5, -165796510);
440
- d = gg(d, a, b, c, k[6], 9, -1069501632);
441
- c = gg(c, d, a, b, k[11], 14, 643717713);
442
- b = gg(b, c, d, a, k[0], 20, -373897302);
443
- a = gg(a, b, c, d, k[5], 5, -701558691);
444
- d = gg(d, a, b, c, k[10], 9, 38016083);
445
- c = gg(c, d, a, b, k[15], 14, -660478335);
446
- b = gg(b, c, d, a, k[4], 20, -405537848);
447
- a = gg(a, b, c, d, k[9], 5, 568446438);
448
- d = gg(d, a, b, c, k[14], 9, -1019803690);
449
- c = gg(c, d, a, b, k[3], 14, -187363961);
450
- b = gg(b, c, d, a, k[8], 20, 1163531501);
451
- a = gg(a, b, c, d, k[13], 5, -1444681467);
452
- d = gg(d, a, b, c, k[2], 9, -51403784);
453
- c = gg(c, d, a, b, k[7], 14, 1735328473);
454
- b = gg(b, c, d, a, k[12], 20, -1926607734);
455
- a = hh(a, b, c, d, k[5], 4, -378558);
456
- d = hh(d, a, b, c, k[8], 11, -2022574463);
457
- c = hh(c, d, a, b, k[11], 16, 1839030562);
458
- b = hh(b, c, d, a, k[14], 23, -35309556);
459
- a = hh(a, b, c, d, k[1], 4, -1530992060);
460
- d = hh(d, a, b, c, k[4], 11, 1272893353);
461
- c = hh(c, d, a, b, k[7], 16, -155497632);
462
- b = hh(b, c, d, a, k[10], 23, -1094730640);
463
- a = hh(a, b, c, d, k[13], 4, 681279174);
464
- d = hh(d, a, b, c, k[0], 11, -358537222);
465
- c = hh(c, d, a, b, k[3], 16, -722521979);
466
- b = hh(b, c, d, a, k[6], 23, 76029189);
467
- a = hh(a, b, c, d, k[9], 4, -640364487);
468
- d = hh(d, a, b, c, k[12], 11, -421815835);
469
- c = hh(c, d, a, b, k[15], 16, 530742520);
470
- b = hh(b, c, d, a, k[2], 23, -995338651);
471
- a = ii(a, b, c, d, k[0], 6, -198630844);
472
- d = ii(d, a, b, c, k[7], 10, 1126891415);
473
- c = ii(c, d, a, b, k[14], 15, -1416354905);
474
- b = ii(b, c, d, a, k[5], 21, -57434055);
475
- a = ii(a, b, c, d, k[12], 6, 1700485571);
476
- d = ii(d, a, b, c, k[3], 10, -1894986606);
477
- c = ii(c, d, a, b, k[10], 15, -1051523);
478
- b = ii(b, c, d, a, k[1], 21, -2054922799);
479
- a = ii(a, b, c, d, k[8], 6, 1873313359);
480
- d = ii(d, a, b, c, k[15], 10, -30611744);
481
- c = ii(c, d, a, b, k[6], 15, -1560198380);
482
- b = ii(b, c, d, a, k[13], 21, 1309151649);
483
- a = ii(a, b, c, d, k[4], 6, -145523070);
484
- d = ii(d, a, b, c, k[11], 10, -1120210379);
485
- c = ii(c, d, a, b, k[2], 15, 718787259);
486
- b = ii(b, c, d, a, k[9], 21, -343485551);
487
- x[0] = add32(a, x[0]);
488
- x[1] = add32(b, x[1]);
489
- x[2] = add32(c, x[2]);
490
- x[3] = add32(d, x[3]);
491
- }
492
- function cmn(q, a, b, x, s, t) {
493
- a = add32(add32(a, q), add32(x, t));
494
- return add32(a << s | a >>> 32 - s, b);
495
- }
496
- function ff(a, b, c, d, x, s, t) {
497
- return cmn(b & c | ~b & d, a, b, x, s, t);
498
- }
499
- function gg(a, b, c, d, x, s, t) {
500
- return cmn(b & d | c & ~d, a, b, x, s, t);
501
- }
502
- function hh(a, b, c, d, x, s, t) {
503
- return cmn(b ^ c ^ d, a, b, x, s, t);
504
- }
505
- function ii(a, b, c, d, x, s, t) {
506
- return cmn(c ^ (b | ~d), a, b, x, s, t);
507
- }
508
- function md51(s) {
509
- var txt = "";
510
- var n = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i;
511
- for (i = 64;i <= s.length; i += 64) {
512
- md5cycle(state, md5blk(s.substring(i - 64, i)));
513
- }
514
- s = s.substring(i - 64);
515
- var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
516
- for (i = 0;i < s.length; i++)
517
- tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);
518
- tail[i >> 2] |= 128 << (i % 4 << 3);
519
- if (i > 55) {
520
- md5cycle(state, tail);
521
- for (i = 0;i < 16; i++)
522
- tail[i] = 0;
523
- }
524
- tail[14] = n * 8;
525
- md5cycle(state, tail);
526
- return state;
527
- }
528
- function md5blk(s) {
529
- var md5blks = [], i;
530
- for (i = 0;i < 64; i += 4) {
531
- md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
532
- }
533
- return md5blks;
534
- }
535
- function rhex(n) {
536
- var s = "", j = 0;
537
- for (;j < 4; j++)
538
- s += hex_chr[n >> j * 8 + 4 & 15] + hex_chr[n >> j * 8 & 15];
539
- return s;
540
- }
541
- function hex(x) {
542
- for (var i = 0;i < x.length; i++)
543
- x[i] = rhex(x[i]);
544
- return x.join("");
545
- }
546
- function add32(a, b) {
547
- return a + b & 4294967295;
548
- }
549
- function md5(s) {
550
- return hex(md51(s));
551
- }
552
- var hex_chr = "0123456789abcdef".split("");
553
-
554
- // src/html.ts
555
- function html(strings, ...values) {
556
- const content = [];
557
- if (values.length === 0) {
558
- content.push({ kind: "string_safe", value: strings.join("\n") });
559
- return new HSTemplate(content);
560
- }
561
- let i = 0;
562
- for (i = 0;i < values.length; i++) {
563
- content.push({ kind: "string_safe", value: strings[i] });
564
- let tValue = values[i] === undefined || values[i] === null || values[i] === "" ? "" : values[i];
565
- if (!Array.isArray(tValue)) {
566
- tValue = [tValue];
567
- }
568
- for (let j = 0;j < tValue.length; j++) {
569
- content.push({ kind: _typeOf(tValue[j]), value: tValue[j] });
570
- }
571
- }
572
- content.push({ kind: "string_safe", value: strings[i] });
573
- return new HSTemplate(content);
574
- }
575
- async function* _render(obj, promises = [], { js }) {
576
- let { kind, value } = obj;
577
- let id = randomId();
578
- if (!kind || !value) {
579
- kind = _typeOf(obj);
580
- value = obj;
581
- }
582
- if (value instanceof HSTemplate || value.__hsTemplate) {
583
- yield* renderToStream(value);
584
- } else if (typeof value.render !== "undefined") {
585
- value.id = id;
586
- yield await value.render();
587
- } else if (value === undefined || value === null) {
588
- yield "";
589
- } else {
590
- switch (kind) {
591
- case "string":
592
- yield import_escape_html.default(value);
593
- break;
594
- case "string_safe":
595
- yield value;
596
- break;
597
- case "array":
598
- yield* value;
599
- break;
600
- case "promise":
601
- const promise = value.then((v) => {
602
- return _render(v, promises, { js });
603
- });
604
- const pid = "async_" + id;
605
- promises.push({ id: pid, pending: true, promise });
606
- yield* renderToStream(html`<div id="${pid}">Loading...</div>`);
607
- break;
608
- case "function":
609
- const fns = renderFunctionToString(value);
610
- const fnId = "fn_" + md5(fns);
611
- if (!IS_CLIENT || !window.hyperspan._fn.has(fnId)) {
612
- js.push(`hyperspan.fn('${fnId}', ${fns});`);
613
- }
614
- yield `"hyperspan:${fnId}"`;
615
- break;
616
- case "json":
617
- yield "";
618
- break;
619
- case "number":
620
- yield String(value);
621
- break;
622
- case "object":
623
- if (typeof value.render === "function") {
624
- yield value.render();
625
- } else if (typeof value.toString === "function") {
626
- yield value.toString();
627
- } else {
628
- yield value;
629
- }
630
- break;
631
- case "generator":
632
- yield* value;
633
- break;
634
- case "date":
635
- yield value.toISOString();
636
- break;
637
- default:
638
- yield String(value);
639
- }
640
- }
641
- }
642
- async function* renderToStream(template) {
643
- let promises = [];
644
- let js = [];
645
- if (typeof template === "string") {
646
- return template;
647
- }
648
- for (let i = 0;i < template.content.length; i++) {
649
- yield* _render(template.content[i], promises, { js });
650
- }
651
- while (promises.length > 0) {
652
- const promisesToRun = promises.map((p) => p.promise.then((v) => {
653
- return { id: p.id, pending: false, value: v, promise: null };
654
- }));
655
- const result = await Promise.race(promisesToRun);
656
- yield* renderToStream(html`<template id="${result.id}_content">${result.value}</template>`);
657
- promises = promises.filter((p) => {
658
- return p.id !== result.id;
659
- });
660
- }
661
- if (js.length !== 0) {
662
- yield "<script>" + js.join("\n") + "</script>";
663
- }
664
- }
665
- async function renderToString(template) {
666
- let result = "";
667
- for await (const chunk of renderToStream(template)) {
668
- result += chunk;
669
- }
670
- return result;
671
- }
672
- function randomId() {
673
- return Math.random().toString(36).substring(2, 9);
674
- }
675
- function _typeOf(obj) {
676
- if (obj instanceof Promise)
677
- return "promise";
678
- if (obj instanceof Date)
679
- return "date";
680
- if (obj instanceof String)
681
- return "string";
682
- if (obj instanceof Number)
683
- return "number";
684
- if (obj instanceof Boolean)
685
- return "boolean";
686
- if (obj instanceof Function)
687
- return "function";
688
- if (Array.isArray(obj))
689
- return "array";
690
- if (Number.isNaN(obj))
691
- return "nan";
692
- if (obj === undefined)
693
- return "undefined";
694
- if (obj === null)
695
- return "null";
696
- if (isGenerator(obj))
697
- return "generator";
698
- if (isPlainObject(obj))
699
- return "json";
700
- return typeof obj;
701
- }
702
- function isGenerator(obj) {
703
- return obj && typeof obj.next == "function" && typeof obj.throw == "function";
704
- }
705
- function isPlainObject(val) {
706
- return Object == val.constructor;
707
- }
708
- function renderFunctionToString(fn) {
709
- let fns = fn.toString();
710
- const firstLine = fns.split("\n")[0];
711
- const isFatArrow = firstLine.includes("=>");
712
- const isAsync = firstLine.includes("async");
713
- const hasFunctionWord = firstLine.includes("function");
714
- if (isFatArrow) {
715
- fns = "function (...args) { return (" + fns + ")(..args); }";
716
- } else {
717
- if (!hasFunctionWord) {
718
- fns = "function " + fns;
719
- }
720
- }
721
- if (isAsync) {
722
- fns = "async " + fns.replace("async ", "");
723
- }
724
- return fns;
725
- }
726
- var IS_CLIENT = typeof window !== "undefined";
727
-
728
- class HSTemplate {
729
- __hsTemplate = true;
730
- content;
731
- constructor(content) {
732
- this.content = content;
733
- }
734
- }
735
- html.raw = (value) => {
736
- return new HSTemplate([{ kind: "string_safe", value }]);
737
- };
738
-
739
- // node_modules/isbot/index.mjs
740
- function getPattern() {
741
- if (pattern instanceof RegExp) {
742
- return pattern;
743
- }
744
- try {
745
- pattern = new RegExp(fullPattern, "i");
746
- } catch (error) {
747
- pattern = naivePattern;
748
- }
749
- return pattern;
750
- }
751
- function isbot(userAgent) {
752
- return Boolean(userAgent) && getPattern().test(userAgent);
753
- }
754
- var fullPattern = " daum[ /]| deusu/| yadirectfetcher|(?:^|[^g])news(?!sapphire)|(?<! (?:channel/|google/))google(?!(app|/google| pixel))|(?<! cu)bots?(?:\\b|_)|(?<!(?:lib))http|(?<![hg]m)score|@[a-z][\\w-]+\\.|\\(\\)|\\.com\\b|\\btime/|^<|^[\\w \\.\\-\\(?:\\):]+(?:/v?\\d+(?:\\.\\d+)?(?:\\.\\d{1,10})*?)?(?:,|$)|^[^ ]{50,}$|^\\d+\\b|^\\w*search\\b|^\\w+/[\\w\\(\\)]*$|^active|^ad muncher|^amaya|^avsdevicesdk/|^biglotron|^bot|^bw/|^clamav[ /]|^client/|^cobweb/|^custom|^ddg[_-]android|^discourse|^dispatch/\\d|^downcast/|^duckduckgo|^facebook|^getright/|^gozilla/|^hobbit|^hotzonu|^hwcdn/|^jeode/|^jetty/|^jigsaw|^microsoft bits|^movabletype|^mozilla/5\\.0\\s[a-z\\.-]+$|^mozilla/\\d\\.\\d \\(compatible;?\\)$|^mozilla/\\d\\.\\d \\w*$|^navermailapp|^netsurf|^offline|^owler|^php|^postman|^python|^rank|^read|^reed|^rest|^rss|^snapchat|^space bison|^svn|^swcd |^taringa|^thumbor/|^track|^valid|^w3c|^webbandit/|^webcopier|^wget|^whatsapp|^wordpress|^xenu link sleuth|^yahoo|^yandex|^zdm/\\d|^zoom marketplace/|^{{.*}}$|adscanner/|analyzer|archive|ask jeeves/teoma|bit\\.ly/|bluecoat drtr|browsex|burpcollaborator|capture|catch|check\\b|checker|chrome-lighthouse|chromeframe|classifier|cloudflare|convertify|crawl|cypress/|dareboost|datanyze|dejaclick|detect|dmbrowser|download|evc-batch/|exaleadcloudview|feed|firephp|functionize|gomezagent|headless|httrack|hubspot marketing grader|hydra|ibisbrowser|images|infrawatch|insight|inspect|iplabel|ips-agent|java(?!;)|jsjcw_scanner|library|linkcheck|mail\\.ru/|manager|measure|neustar wpm|node|nutch|offbyone|optimize|pageburst|pagespeed|parser|perl|phantomjs|pingdom|powermarks|preview|proxy|ptst[ /]\\d|reputation|resolver|retriever|rexx;|rigor|rss\\b|scanner\\.|scrape|server|sogou|sparkler/|speedcurve|spider|splash|statuscake|supercleaner|synapse|synthetic|tools|torrent|trace|transcoder|url|virtuoso|wappalyzer|webglance|webkit2png|whatcms/|zgrab";
755
- var naivePattern = /bot|crawl|http|lighthouse|scan|search|spider/i;
756
- var pattern;
757
-
758
- // src/app.ts
759
- var import_trek_router = __toESM(require_trek_router(), 1);
760
- var import_trek_middleware = __toESM(require_trek_middleware(), 1);
761
- var import_deepmerge = __toESM(require_deepmerge(), 1);
762
-
763
- // node_modules/@mjackson/headers/dist/lib/param-values.js
764
- function parseParams(input, delimiter = ";") {
765
- let regex = /(?:^|;)\s*([^=;\s]+)(\s*=\s*(?:"((?:[^"\\]|\\.)*)"|((?:[^;]|\\\;)+))?)?/g;
766
- if (delimiter === ",") {
767
- regex = /(?:^|,)\s*([^=,\s]+)(\s*=\s*(?:"((?:[^"\\]|\\.)*)"|((?:[^,]|\\\,)+))?)?/g;
768
- }
769
- let params = [];
770
- let match;
771
- while ((match = regex.exec(input)) !== null) {
772
- let key = match[1].trim();
773
- let value;
774
- if (match[2]) {
775
- value = (match[3] || match[4] || "").replace(/\\(.)/g, "$1").trim();
776
- }
777
- params.push([key, value]);
778
- }
779
- return params;
780
- }
781
- function quote(value) {
782
- if (value.includes('"') || value.includes(";") || value.includes(" ")) {
783
- return `"${value.replace(/"/g, '\\"')}"`;
784
- }
785
- return value;
786
- }
787
-
788
- // node_modules/@mjackson/headers/dist/lib/utils.js
789
- function capitalize(str) {
790
- return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
791
- }
792
- function isIterable(value) {
793
- return value != null && typeof value[Symbol.iterator] === "function";
794
- }
795
- function isValidDate(date) {
796
- return date instanceof Date && !isNaN(date.getTime());
797
- }
798
-
799
- // node_modules/@mjackson/headers/dist/lib/accept-language.js
800
- class AcceptLanguage {
801
- #map;
802
- constructor(init) {
803
- this.#map = new Map;
804
- if (init) {
805
- if (typeof init === "string") {
806
- let params = parseParams(init, ",");
807
- for (let [language, quality] of params) {
808
- if (typeof quality === "string") {
809
- language = language.slice(0, -2).trim();
810
- } else {
811
- quality = "1";
812
- }
813
- this.#map.set(language, Number(quality));
814
- }
815
- } else if (isIterable(init)) {
816
- for (let language of init) {
817
- let quality;
818
- if (Array.isArray(language)) {
819
- [language, quality] = language;
820
- }
821
- this.#map.set(language, quality ?? 1);
822
- }
823
- } else {
824
- for (let language in init) {
825
- if (Object.prototype.hasOwnProperty.call(init, language)) {
826
- this.#map.set(language, init[language] ?? 1);
827
- }
828
- }
829
- }
830
- this.#sort();
831
- }
832
- }
833
- #sort() {
834
- this.#map = new Map([...this.#map].sort(([, a], [, b]) => b - a));
835
- }
836
- get(language) {
837
- return this.#map.get(language);
838
- }
839
- set(language, quality = 1) {
840
- this.#map.set(language, quality);
841
- this.#sort();
842
- }
843
- delete(language) {
844
- return this.#map.delete(language);
845
- }
846
- has(language) {
847
- return this.#map.has(language);
848
- }
849
- clear() {
850
- this.#map.clear();
851
- }
852
- entries() {
853
- return this.#map.entries();
854
- }
855
- get languages() {
856
- return Array.from(this.#map.keys());
857
- }
858
- get qualities() {
859
- return Array.from(this.#map.values());
860
- }
861
- [Symbol.iterator]() {
862
- return this.entries();
863
- }
864
- forEach(callback, thisArg) {
865
- this.#map.forEach((quality, language, map) => callback(language, quality, map), thisArg);
866
- }
867
- get size() {
868
- return this.#map.size;
869
- }
870
- toString() {
871
- let pairs = [];
872
- for (let [language, quality] of this.#map) {
873
- pairs.push(`${language}${quality === 1 ? "" : `;q=${quality}`}`);
874
- }
875
- return pairs.join(",");
876
- }
877
- }
878
- // node_modules/@mjackson/headers/dist/lib/cache-control.js
879
- class CacheControl {
880
- maxAge;
881
- maxStale;
882
- minFresh;
883
- sMaxage;
884
- noCache;
885
- noStore;
886
- noTransform;
887
- onlyIfCached;
888
- mustRevalidate;
889
- proxyRevalidate;
890
- mustUnderstand;
891
- private;
892
- public;
893
- immutable;
894
- staleWhileRevalidate;
895
- staleIfError;
896
- constructor(init) {
897
- if (init) {
898
- if (typeof init === "string") {
899
- let params = parseParams(init, ",");
900
- if (params.length > 0) {
901
- for (let [name, value] of params) {
902
- switch (name) {
903
- case "max-age":
904
- this.maxAge = Number(value);
905
- break;
906
- case "max-stale":
907
- this.maxStale = Number(value);
908
- break;
909
- case "min-fresh":
910
- this.minFresh = Number(value);
911
- break;
912
- case "s-maxage":
913
- this.sMaxage = Number(value);
914
- break;
915
- case "no-cache":
916
- this.noCache = true;
917
- break;
918
- case "no-store":
919
- this.noStore = true;
920
- break;
921
- case "no-transform":
922
- this.noTransform = true;
923
- break;
924
- case "only-if-cached":
925
- this.onlyIfCached = true;
926
- break;
927
- case "must-revalidate":
928
- this.mustRevalidate = true;
929
- break;
930
- case "proxy-revalidate":
931
- this.proxyRevalidate = true;
932
- break;
933
- case "must-understand":
934
- this.mustUnderstand = true;
935
- break;
936
- case "private":
937
- this.private = true;
938
- break;
939
- case "public":
940
- this.public = true;
941
- break;
942
- case "immutable":
943
- this.immutable = true;
944
- break;
945
- case "stale-while-revalidate":
946
- this.staleWhileRevalidate = Number(value);
947
- break;
948
- case "stale-if-error":
949
- this.staleIfError = Number(value);
950
- break;
951
- }
952
- }
953
- }
954
- } else {
955
- this.maxAge = init.maxAge;
956
- this.maxStale = init.maxStale;
957
- this.minFresh = init.minFresh;
958
- this.sMaxage = init.sMaxage;
959
- this.noCache = init.noCache;
960
- this.noStore = init.noStore;
961
- this.noTransform = init.noTransform;
962
- this.onlyIfCached = init.onlyIfCached;
963
- this.mustRevalidate = init.mustRevalidate;
964
- this.proxyRevalidate = init.proxyRevalidate;
965
- this.mustUnderstand = init.mustUnderstand;
966
- this.private = init.private;
967
- this.public = init.public;
968
- this.immutable = init.immutable;
969
- this.staleWhileRevalidate = init.staleWhileRevalidate;
970
- this.staleIfError = init.staleIfError;
971
- }
972
- }
973
- }
974
- toString() {
975
- let parts = [];
976
- if (this.public) {
977
- parts.push("public");
978
- }
979
- if (this.private) {
980
- parts.push("private");
981
- }
982
- if (typeof this.maxAge === "number") {
983
- parts.push(`max-age=${this.maxAge}`);
984
- }
985
- if (typeof this.sMaxage === "number") {
986
- parts.push(`s-maxage=${this.sMaxage}`);
987
- }
988
- if (this.noCache) {
989
- parts.push("no-cache");
990
- }
991
- if (this.noStore) {
992
- parts.push("no-store");
993
- }
994
- if (this.noTransform) {
995
- parts.push("no-transform");
996
- }
997
- if (this.onlyIfCached) {
998
- parts.push("only-if-cached");
999
- }
1000
- if (this.mustRevalidate) {
1001
- parts.push("must-revalidate");
1002
- }
1003
- if (this.proxyRevalidate) {
1004
- parts.push("proxy-revalidate");
1005
- }
1006
- if (this.mustUnderstand) {
1007
- parts.push("must-understand");
1008
- }
1009
- if (this.immutable) {
1010
- parts.push("immutable");
1011
- }
1012
- if (typeof this.staleWhileRevalidate === "number") {
1013
- parts.push(`stale-while-revalidate=${this.staleWhileRevalidate}`);
1014
- }
1015
- if (typeof this.staleIfError === "number") {
1016
- parts.push(`stale-if-error=${this.staleIfError}`);
1017
- }
1018
- if (typeof this.maxStale === "number") {
1019
- parts.push(`max-stale=${this.maxStale}`);
1020
- }
1021
- if (typeof this.minFresh === "number") {
1022
- parts.push(`min-fresh=${this.minFresh}`);
1023
- }
1024
- return parts.join(", ");
1025
- }
1026
- }
1027
- // node_modules/@mjackson/headers/dist/lib/content-disposition.js
1028
- function decodeFilenameSplat(value) {
1029
- let match = value.match(/^([\w-]+)'([^']*)'(.+)$/);
1030
- if (!match)
1031
- return null;
1032
- let [, charset, , encodedFilename] = match;
1033
- let decodedFilename = percentDecode(encodedFilename);
1034
- try {
1035
- let decoder = new TextDecoder(charset);
1036
- let bytes = new Uint8Array(decodedFilename.split("").map((char) => char.charCodeAt(0)));
1037
- return decoder.decode(bytes);
1038
- } catch (error) {
1039
- console.warn(`Failed to decode filename from charset ${charset}:`, error);
1040
- return decodedFilename;
1041
- }
1042
- }
1043
- function percentDecode(value) {
1044
- return value.replace(/\+/g, " ").replace(/%([0-9A-Fa-f]{2})/g, (_, hex2) => {
1045
- return String.fromCharCode(parseInt(hex2, 16));
1046
- });
1047
- }
1048
-
1049
- class ContentDisposition {
1050
- filename;
1051
- filenameSplat;
1052
- name;
1053
- type;
1054
- constructor(init) {
1055
- if (init) {
1056
- if (typeof init === "string") {
1057
- let params = parseParams(init);
1058
- if (params.length > 0) {
1059
- this.type = params[0][0];
1060
- for (let [name, value] of params.slice(1)) {
1061
- if (name === "filename") {
1062
- this.filename = value;
1063
- } else if (name === "filename*") {
1064
- this.filenameSplat = value;
1065
- } else if (name === "name") {
1066
- this.name = value;
1067
- }
1068
- }
1069
- }
1070
- } else {
1071
- this.filename = init.filename;
1072
- this.filenameSplat = init.filenameSplat;
1073
- this.name = init.name;
1074
- this.type = init.type;
1075
- }
1076
- }
1077
- }
1078
- get preferredFilename() {
1079
- let filenameSplat = this.filenameSplat;
1080
- if (filenameSplat) {
1081
- let decodedFilename = decodeFilenameSplat(filenameSplat);
1082
- if (decodedFilename)
1083
- return decodedFilename;
1084
- }
1085
- return this.filename;
1086
- }
1087
- toString() {
1088
- if (!this.type) {
1089
- return "";
1090
- }
1091
- let parts = [this.type];
1092
- if (this.name) {
1093
- parts.push(`name=${quote(this.name)}`);
1094
- }
1095
- if (this.filename) {
1096
- parts.push(`filename=${quote(this.filename)}`);
1097
- }
1098
- if (this.filenameSplat) {
1099
- parts.push(`filename*=${quote(this.filenameSplat)}`);
1100
- }
1101
- return parts.join("; ");
1102
- }
1103
- }
1104
- // node_modules/@mjackson/headers/dist/lib/content-type.js
1105
- class ContentType {
1106
- boundary;
1107
- charset;
1108
- mediaType;
1109
- constructor(init) {
1110
- if (init) {
1111
- if (typeof init === "string") {
1112
- let params = parseParams(init);
1113
- if (params.length > 0) {
1114
- this.mediaType = params[0][0];
1115
- for (let [name, value] of params.slice(1)) {
1116
- if (name === "boundary") {
1117
- this.boundary = value;
1118
- } else if (name === "charset") {
1119
- this.charset = value;
1120
- }
1121
- }
1122
- }
1123
- } else {
1124
- this.boundary = init.boundary;
1125
- this.charset = init.charset;
1126
- this.mediaType = init.mediaType;
1127
- }
1128
- }
1129
- }
1130
- toString() {
1131
- if (!this.mediaType) {
1132
- return "";
1133
- }
1134
- let parts = [this.mediaType];
1135
- if (this.charset) {
1136
- parts.push(`charset=${quote(this.charset)}`);
1137
- }
1138
- if (this.boundary) {
1139
- parts.push(`boundary=${quote(this.boundary)}`);
1140
- }
1141
- return parts.join("; ");
1142
- }
1143
- }
1144
- // node_modules/@mjackson/headers/dist/lib/cookie.js
1145
- class Cookie {
1146
- #map;
1147
- constructor(init) {
1148
- this.#map = new Map;
1149
- if (init) {
1150
- if (typeof init === "string") {
1151
- let params = parseParams(init);
1152
- for (let [name, value] of params) {
1153
- this.#map.set(name, value || "");
1154
- }
1155
- } else if (isIterable(init)) {
1156
- for (let [name, value] of init) {
1157
- this.#map.set(name, value);
1158
- }
1159
- } else {
1160
- for (let name in init) {
1161
- if (Object.prototype.hasOwnProperty.call(init, name)) {
1162
- this.#map.set(name, init[name]);
1163
- }
1164
- }
1165
- }
1166
- }
1167
- }
1168
- get(name) {
1169
- return this.#map.get(name);
1170
- }
1171
- set(name, value) {
1172
- this.#map.set(name, value);
1173
- }
1174
- delete(name) {
1175
- return this.#map.delete(name);
1176
- }
1177
- has(name) {
1178
- return this.#map.has(name);
1179
- }
1180
- clear() {
1181
- this.#map.clear();
1182
- }
1183
- entries() {
1184
- return this.#map.entries();
1185
- }
1186
- names() {
1187
- return this.#map.keys();
1188
- }
1189
- values() {
1190
- return this.#map.values();
1191
- }
1192
- [Symbol.iterator]() {
1193
- return this.entries();
1194
- }
1195
- forEach(callback, thisArg) {
1196
- this.#map.forEach(callback, thisArg);
1197
- }
1198
- get size() {
1199
- return this.#map.size;
1200
- }
1201
- toString() {
1202
- let pairs = [];
1203
- for (let [name, value] of this.#map) {
1204
- pairs.push(`${name}=${quote(value)}`);
1205
- }
1206
- return pairs.join("; ");
1207
- }
1208
- }
1209
- // node_modules/@mjackson/headers/dist/lib/set-cookie.js
1210
- class SetCookie {
1211
- domain;
1212
- expires;
1213
- httpOnly;
1214
- maxAge;
1215
- name;
1216
- path;
1217
- sameSite;
1218
- secure;
1219
- value;
1220
- constructor(init) {
1221
- if (init) {
1222
- if (typeof init === "string") {
1223
- let params = parseParams(init);
1224
- if (params.length > 0) {
1225
- this.name = params[0][0];
1226
- this.value = params[0][1];
1227
- for (let [key, value] of params.slice(1)) {
1228
- switch (key.toLowerCase()) {
1229
- case "domain":
1230
- this.domain = value;
1231
- break;
1232
- case "expires": {
1233
- if (typeof value === "string") {
1234
- let v = new Date(value);
1235
- if (isValidDate(v))
1236
- this.expires = v;
1237
- }
1238
- break;
1239
- }
1240
- case "httponly":
1241
- this.httpOnly = true;
1242
- break;
1243
- case "max-age": {
1244
- if (typeof value === "string") {
1245
- let v = parseInt(value, 10);
1246
- if (!isNaN(v))
1247
- this.maxAge = v;
1248
- }
1249
- break;
1250
- }
1251
- case "path":
1252
- this.path = value;
1253
- break;
1254
- case "samesite":
1255
- if (typeof value === "string" && /strict|lax|none/i.test(value)) {
1256
- this.sameSite = capitalize(value);
1257
- }
1258
- break;
1259
- case "secure":
1260
- this.secure = true;
1261
- break;
1262
- }
1263
- }
1264
- }
1265
- } else {
1266
- this.domain = init.domain;
1267
- this.expires = init.expires;
1268
- this.httpOnly = init.httpOnly;
1269
- this.maxAge = init.maxAge;
1270
- this.name = init.name;
1271
- this.path = init.path;
1272
- this.sameSite = init.sameSite;
1273
- this.secure = init.secure;
1274
- this.value = init.value;
1275
- }
1276
- }
1277
- }
1278
- toString() {
1279
- if (!this.name) {
1280
- return "";
1281
- }
1282
- let parts = [`${this.name}=${quote(this.value || "")}`];
1283
- if (this.domain) {
1284
- parts.push(`Domain=${this.domain}`);
1285
- }
1286
- if (this.path) {
1287
- parts.push(`Path=${this.path}`);
1288
- }
1289
- if (this.expires) {
1290
- parts.push(`Expires=${this.expires.toUTCString()}`);
1291
- }
1292
- if (this.maxAge) {
1293
- parts.push(`Max-Age=${this.maxAge}`);
1294
- }
1295
- if (this.secure) {
1296
- parts.push("Secure");
1297
- }
1298
- if (this.httpOnly) {
1299
- parts.push("HttpOnly");
1300
- }
1301
- if (this.sameSite) {
1302
- parts.push(`SameSite=${this.sameSite}`);
1303
- }
1304
- return parts.join("; ");
1305
- }
1306
- }
1307
- // node_modules/@mjackson/headers/dist/lib/header-names.js
1308
- function canonicalHeaderName(name) {
1309
- return name.toLowerCase().split("-").map((word) => HeaderWordCasingExceptions[word] || word.charAt(0).toUpperCase() + word.slice(1)).join("-");
1310
- }
1311
- var HeaderWordCasingExceptions = {
1312
- ct: "CT",
1313
- etag: "ETag",
1314
- te: "TE",
1315
- www: "WWW",
1316
- x: "X",
1317
- xss: "XSS"
1318
- };
1319
-
1320
- // node_modules/@mjackson/headers/dist/lib/super-headers.js
1321
- var CRLF = "\r\n";
1322
- var SetCookieKey = "set-cookie";
1323
-
1324
- class SuperHeaders extends Headers {
1325
- #map;
1326
- #setCookieValues = [];
1327
- constructor(init) {
1328
- super();
1329
- this.#map = new Map;
1330
- if (init) {
1331
- if (typeof init === "string") {
1332
- let lines = init.split(CRLF);
1333
- for (let line of lines) {
1334
- let match = line.match(/^([^:]+):(.*)/);
1335
- if (match) {
1336
- this.append(match[1].trim(), match[2].trim());
1337
- }
1338
- }
1339
- } else if (isIterable(init)) {
1340
- for (let [name, value] of init) {
1341
- this.append(name, value);
1342
- }
1343
- } else if (typeof init === "object") {
1344
- for (let name in init) {
1345
- if (Object.prototype.hasOwnProperty.call(init, name)) {
1346
- let setter = Object.getOwnPropertyDescriptor(SuperHeaders.prototype, name)?.set;
1347
- if (setter) {
1348
- setter.call(this, init[name]);
1349
- } else {
1350
- this.append(name, init[name]);
1351
- }
1352
- }
1353
- }
1354
- }
1355
- }
1356
- }
1357
- append(name, value) {
1358
- let key = name.toLowerCase();
1359
- if (key === SetCookieKey) {
1360
- this.#setCookieValues.push(value);
1361
- } else {
1362
- let existingValue = this.#map.get(key);
1363
- this.#map.set(key, existingValue ? `${existingValue}, ${value}` : value);
1364
- }
1365
- }
1366
- delete(name) {
1367
- let key = name.toLowerCase();
1368
- if (key === SetCookieKey) {
1369
- this.#setCookieValues = [];
1370
- } else {
1371
- this.#map.delete(key);
1372
- }
1373
- }
1374
- get(name) {
1375
- let key = name.toLowerCase();
1376
- if (key === SetCookieKey) {
1377
- return this.#setCookieValues.map((value) => value.toString()).join(", ");
1378
- } else {
1379
- let value = this.#map.get(key);
1380
- if (typeof value === "string") {
1381
- return value;
1382
- } else if (value instanceof Date) {
1383
- return value.toUTCString();
1384
- } else if (value != null) {
1385
- return value.toString();
1386
- } else {
1387
- return null;
1388
- }
1389
- }
1390
- }
1391
- getSetCookie() {
1392
- return this.#setCookieValues.map((value) => value.toString());
1393
- }
1394
- has(name) {
1395
- let key = name.toLowerCase();
1396
- if (key === SetCookieKey) {
1397
- return this.#setCookieValues.length > 0;
1398
- } else {
1399
- return this.#map.has(key);
1400
- }
1401
- }
1402
- set(name, value) {
1403
- let key = name.toLowerCase();
1404
- if (key === SetCookieKey) {
1405
- this.#setCookieValues = [value];
1406
- } else {
1407
- this.#map.set(key, value);
1408
- }
1409
- }
1410
- *entries() {
1411
- for (let [key] of this.#map) {
1412
- let stringValue = this.get(key);
1413
- if (stringValue) {
1414
- yield [key, stringValue];
1415
- }
1416
- }
1417
- for (let value of this.#setCookieValues) {
1418
- let stringValue = value.toString();
1419
- if (stringValue) {
1420
- yield [SetCookieKey, stringValue];
1421
- }
1422
- }
1423
- }
1424
- *keys() {
1425
- for (let [key] of this) {
1426
- yield key;
1427
- }
1428
- }
1429
- *values() {
1430
- for (let [, value] of this) {
1431
- yield value;
1432
- }
1433
- }
1434
- [Symbol.iterator]() {
1435
- return this.entries();
1436
- }
1437
- forEach(callback, thisArg) {
1438
- for (let [key, value] of this) {
1439
- callback.call(thisArg, value, key, this);
1440
- }
1441
- }
1442
- toString() {
1443
- let lines = [];
1444
- for (let [key, value] of this) {
1445
- lines.push(`${canonicalHeaderName(key)}: ${value}`);
1446
- }
1447
- return lines.join(CRLF);
1448
- }
1449
- get acceptLanguage() {
1450
- return this.#getHeaderValue("accept-language", AcceptLanguage);
1451
- }
1452
- set acceptLanguage(value) {
1453
- this.#setHeaderValue("accept-language", AcceptLanguage, value);
1454
- }
1455
- get age() {
1456
- return this.#getNumberValue("age");
1457
- }
1458
- set age(value) {
1459
- this.#map.set("age", value);
1460
- }
1461
- get cacheControl() {
1462
- return this.#getHeaderValue("cache-control", CacheControl);
1463
- }
1464
- set cacheControl(value) {
1465
- this.#setHeaderValue("cache-control", CacheControl, value);
1466
- }
1467
- get contentDisposition() {
1468
- return this.#getHeaderValue("content-disposition", ContentDisposition);
1469
- }
1470
- set contentDisposition(value) {
1471
- this.#setHeaderValue("content-disposition", ContentDisposition, value);
1472
- }
1473
- get contentLength() {
1474
- return this.#getNumberValue("content-length");
1475
- }
1476
- set contentLength(value) {
1477
- this.#map.set("content-length", value);
1478
- }
1479
- get contentType() {
1480
- return this.#getHeaderValue("content-type", ContentType);
1481
- }
1482
- set contentType(value) {
1483
- this.#setHeaderValue("content-type", ContentType, value);
1484
- }
1485
- get cookie() {
1486
- return this.#getHeaderValue("cookie", Cookie);
1487
- }
1488
- set cookie(value) {
1489
- this.#setHeaderValue("cookie", Cookie, value);
1490
- }
1491
- get date() {
1492
- return this.#getDateValue("date");
1493
- }
1494
- set date(value) {
1495
- this.#map.set("date", value);
1496
- }
1497
- get expires() {
1498
- return this.#getDateValue("expires");
1499
- }
1500
- set expires(value) {
1501
- this.#map.set("expires", value);
1502
- }
1503
- get ifModifiedSince() {
1504
- return this.#getDateValue("if-modified-since");
1505
- }
1506
- set ifModifiedSince(value) {
1507
- this.#map.set("if-modified-since", value);
1508
- }
1509
- get ifUnmodifiedSince() {
1510
- return this.#getDateValue("if-unmodified-since");
1511
- }
1512
- set ifUnmodifiedSince(value) {
1513
- this.#map.set("if-unmodified-since", value);
1514
- }
1515
- get lastModified() {
1516
- return this.#getDateValue("last-modified");
1517
- }
1518
- set lastModified(value) {
1519
- this.#map.set("last-modified", value);
1520
- }
1521
- get setCookie() {
1522
- for (let i = 0;i < this.#setCookieValues.length; ++i) {
1523
- let value = this.#setCookieValues[i];
1524
- if (typeof value === "string") {
1525
- this.#setCookieValues[i] = new SetCookie(value);
1526
- }
1527
- }
1528
- return this.#setCookieValues;
1529
- }
1530
- set setCookie(values) {
1531
- if (typeof values === "string") {
1532
- this.#setCookieValues = [values];
1533
- } else {
1534
- this.#setCookieValues = values.map((value) => {
1535
- if (typeof value === "string" || value instanceof SetCookie) {
1536
- return value;
1537
- } else {
1538
- return new SetCookie(value);
1539
- }
1540
- });
1541
- }
1542
- }
1543
- #getDateValue(key) {
1544
- let value = this.#map.get(key);
1545
- if (value) {
1546
- if (typeof value === "string") {
1547
- let date = new Date(value);
1548
- if (isValidDate(date)) {
1549
- this.#map.set(key, date);
1550
- return date;
1551
- } else {
1552
- this.#map.delete(key);
1553
- }
1554
- } else if (value instanceof Date) {
1555
- return value;
1556
- } else {
1557
- this.#map.delete(key);
1558
- }
1559
- }
1560
- }
1561
- #getNumberValue(key) {
1562
- let value = this.#map.get(key);
1563
- if (value) {
1564
- if (typeof value === "string") {
1565
- let v = parseInt(value, 10);
1566
- if (!isNaN(v)) {
1567
- this.#map.set(key, v);
1568
- return v;
1569
- } else {
1570
- this.#map.delete(key);
1571
- }
1572
- } else if (typeof value === "number") {
1573
- return value;
1574
- } else {
1575
- this.#map.delete(key);
1576
- }
1577
- }
1578
- }
1579
- #getHeaderValue(key, ctor) {
1580
- let value = this.#map.get(key);
1581
- if (value) {
1582
- if (typeof value === "string") {
1583
- let headerValue = new ctor(value);
1584
- this.#map.set(key, headerValue);
1585
- return headerValue;
1586
- } else {
1587
- return value;
1588
- }
1589
- } else {
1590
- let headerValue = new ctor;
1591
- this.#map.set(key, headerValue);
1592
- return headerValue;
1593
- }
1594
- }
1595
- #setHeaderValue(key, ctor, value) {
1596
- if (typeof value === "string" || value instanceof ctor) {
1597
- this.#map.set(key, value);
1598
- } else {
1599
- this.#map.set(key, new ctor(value));
1600
- }
1601
- }
1602
- }
1603
- // src/app.ts
1604
- function normalizePath(urlPath) {
1605
- return (urlPath.endsWith("/") ? urlPath.substring(0, urlPath.length - 1) : urlPath).toLowerCase() || "/";
1606
- }
1607
- var mergeAll = import_deepmerge.default({ all: true });
1608
-
1609
- class HSRequestContext {
1610
- req;
1611
- locals;
1612
- headers;
1613
- route;
1614
- constructor(req, params = {}) {
1615
- this.req = req;
1616
- this.locals = {};
1617
- this.route = {
1618
- params,
1619
- query: new URL(req.url).searchParams
1620
- };
1621
- const allowHeaders = ["cookie"];
1622
- const reqHeaders = {};
1623
- for (let [name, value] of req.headers) {
1624
- if (allowHeaders.includes(name)) {
1625
- reqHeaders[name] = value;
1626
- }
1627
- }
1628
- this.headers = new SuperHeaders(reqHeaders);
1629
- }
1630
- resMerge(res) {
1631
- const cHeaders = {};
1632
- for (let [name, value] of this.headers) {
1633
- cHeaders[name] = value;
1634
- }
1635
- const newRes = new Response(res.body, mergeAll({ headers: cHeaders }, { headers: res.headers.toJSON() }, { status: res.status, statusText: res.statusText }));
1636
- return newRes;
1637
- }
1638
- html(content, options) {
1639
- return new Response(content, mergeAll({ headers: { "Content-Type": "text/html" } }, options));
1640
- }
1641
- json(content, options) {
1642
- return new Response(JSON.stringify(content), mergeAll({ headers: { "Content-Type": "application/json" } }, options));
1643
- }
1644
- notFound(msg = "Not found!") {
1645
- return this.html(msg, { status: 404 });
1646
- }
1647
- }
1648
-
1649
- class HSApp {
1650
- _router;
1651
- _mw;
1652
- _defaultRoute;
1653
- constructor() {
1654
- this._router = new import_trek_router.default;
1655
- this._mw = new import_trek_middleware.default;
1656
- this._defaultRoute = (c) => {
1657
- return c.notFound("Not found");
1658
- };
1659
- }
1660
- get(path, handler) {
1661
- return this._route("GET", path, handler);
1662
- }
1663
- post(path, handler) {
1664
- return this._route("POST", path, handler);
1665
- }
1666
- put(path, handler) {
1667
- return this._route("PUT", path, handler);
1668
- }
1669
- delete(path, handler) {
1670
- return this._route("DELETE", path, handler);
1671
- }
1672
- all(path, handler) {
1673
- return this.addRoute(["GET", "POST", "PUT", "PATCH", "DELETE"], path, handler);
1674
- }
1675
- addRoute(methods, path, handler) {
1676
- methods.forEach((method) => {
1677
- this._route(method, path, handler);
1678
- });
1679
- return this;
1680
- }
1681
- defaultRoute(handler) {
1682
- this._defaultRoute = handler;
1683
- }
1684
- _route(method, path, handler) {
1685
- this._router.add(method, path, handler);
1686
- return this;
1687
- }
1688
- async run(req) {
1689
- let response;
1690
- let url = new URL(req.url);
1691
- let urlPath = normalizePath(url.pathname);
1692
- if (urlPath !== url.pathname) {
1693
- url.pathname = urlPath;
1694
- return Response.redirect(url);
1695
- }
1696
- let result = this._router.find(req.method.toUpperCase(), urlPath);
1697
- let params = {};
1698
- if (result && result[0]) {
1699
- result[1].forEach((param) => params[param.name] = param.value);
1700
- const context2 = new HSRequestContext(req, params);
1701
- response = result[0](context2);
1702
- }
1703
- if (response) {
1704
- return response;
1705
- }
1706
- const context = new HSRequestContext(req);
1707
- return this._defaultRoute(context);
1708
- }
1709
- }
1710
-
1711
- // src/server.ts
1712
- function requestIsBot(req) {
1713
- const ua = req.headers.get("User-Agent");
1714
- return ua ? isbot(ua) : false;
1715
- }
1716
- async function runFileRoute(routeFile, context) {
1717
- const req = context.req;
1718
- const url = new URL(req.url);
1719
- const qs = url.searchParams;
1720
- const streamOpt = qs.get("__nostream") ? !Boolean(qs.get("__nostream")) : undefined;
1721
- const streamingEnabled = streamOpt !== undefined ? streamOpt : true;
1722
- const RouteModule = _routeCache[routeFile] || await import(routeFile);
1723
- if (IS_PROD) {
1724
- _routeCache[routeFile] = RouteModule;
1725
- }
1726
- const RouteComponent = RouteModule.default;
1727
- const reqMethod = req.method.toUpperCase();
1728
- const routeMiddleware = RouteModule.middleware || {};
1729
- const middlewareResult = {};
1730
- try {
1731
- if (Object.keys(routeMiddleware).length) {
1732
- for (const mKey in routeMiddleware) {
1733
- const mRes = await routeMiddleware[mKey](context);
1734
- if (mRes instanceof Response) {
1735
- return context.resMerge(mRes);
1736
- }
1737
- middlewareResult[mKey] = mRes;
1738
- }
1739
- }
1740
- if (RouteModule[reqMethod] !== undefined) {
1741
- return await runAPIRoute(RouteModule[reqMethod], context, middlewareResult);
1742
- }
1743
- const routeContent = await RouteComponent(context, middlewareResult);
1744
- if (routeContent instanceof Response) {
1745
- return context.resMerge(routeContent);
1746
- }
1747
- if (streamingEnabled && !requestIsBot(req)) {
1748
- return context.resMerge(new StreamResponse(renderToStream(routeContent)));
1749
- } else {
1750
- const output = await renderToString(routeContent);
1751
- return context.html(output);
1752
- }
1753
- } catch (e) {
1754
- console.error(e);
1755
- return await showErrorReponse(context, e);
1756
- }
1757
- }
1758
- async function runAPIRoute(routeFn, context, middlewareResult) {
1759
- try {
1760
- return await routeFn(context, middlewareResult);
1761
- } catch (err) {
1762
- const e = err;
1763
- console.error(e);
1764
- return context.json({
1765
- meta: { success: false },
1766
- data: {
1767
- message: e.message,
1768
- stack: IS_PROD ? undefined : e.stack?.split("\n")
1769
- }
1770
- }, { status: 500 });
1771
- }
1772
- }
1773
- async function showErrorReponse(context, err) {
1774
- const output = await renderToString(html`
1775
- <main>
1776
- <h1>Error</h1>
1777
- <pre>${err.message}</pre>
1778
- <pre>${!IS_PROD && err.stack ? err.stack.split("\n").slice(1).join("\n") : ""}</pre>
1779
- </main>
1780
- `);
1781
- return context.html(output, {
1782
- status: 500
1783
- });
1784
- }
1785
- async function buildRoutes(config) {
1786
- const routesDir = join(config.appDir, "routes");
1787
- const files = await readdir(routesDir, { recursive: true });
1788
- const routes = [];
1789
- for (const file of files) {
1790
- if (!file.includes(".") || basename(file).startsWith(".")) {
1791
- continue;
1792
- }
1793
- let route = "/" + file.replace(extname(file), "");
1794
- if (route.endsWith("index")) {
1795
- route = route === "index" ? "/" : route.substring(0, route.length - 6);
1796
- }
1797
- let params = [];
1798
- const dynamicPaths = ROUTE_SEGMENT.test(route);
1799
- if (dynamicPaths) {
1800
- params = [];
1801
- route = route.replace(ROUTE_SEGMENT, (match, p1, offset) => {
1802
- const paramName = match.replace(/[^a-zA-Z_\.]+/g, "");
1803
- if (match.includes("...")) {
1804
- params.push(paramName.replace("...", ""));
1805
- return "*";
1806
- } else {
1807
- params.push(paramName);
1808
- return ":" + paramName;
1809
- }
1810
- });
1811
- }
1812
- routes.push({
1813
- file: join("./", routesDir, file),
1814
- route: route || "/",
1815
- params
1816
- });
1817
- }
1818
- return routes;
1819
- }
1820
- async function createServer(config) {
1821
- await Promise.all([buildClientJS(), buildClientCSS()]);
1822
- const app = new HSApp;
1823
- app.defaultRoute(() => {
1824
- return new Response("Not... found?", { status: 404 });
1825
- });
1826
- config.beforeRoutesAdded && config.beforeRoutesAdded(app);
1827
- const fileRoutes = await buildRoutes(config);
1828
- const routeMap = [];
1829
- for (let i = 0;i < fileRoutes.length; i++) {
1830
- let route = fileRoutes[i];
1831
- const fullRouteFile = join(CWD, route.file);
1832
- const routePattern = normalizePath(route.route);
1833
- routeMap.push({ route: routePattern, file: route.file });
1834
- app.all(routePattern, async (context) => {
1835
- const matchedRoute = await runFileRoute(fullRouteFile, context);
1836
- if (matchedRoute) {
1837
- return matchedRoute;
1838
- }
1839
- return app._defaultRoute(context);
1840
- });
1841
- }
1842
- if (!IS_PROD) {
1843
- console.log("[Hyperspan] File system routes (in app/routes):");
1844
- console.table(routeMap);
1845
- }
1846
- config.afterRoutesAdded && config.afterRoutesAdded(app);
1847
- app.all("*", (context) => {
1848
- const req = context.req;
1849
- if (STATIC_FILE_MATCHER.test(req.url)) {
1850
- const filePath = config.staticFileRoot + new URL(req.url).pathname;
1851
- const file = Bun.file(filePath);
1852
- let headers = {};
1853
- if (IS_PROD) {
1854
- headers = {
1855
- "cache-control": "public, max-age=31557600"
1856
- };
1857
- }
1858
- return new Response(file, { headers });
1859
- }
1860
- return app._defaultRoute(context);
1861
- });
1862
- return app;
1863
- }
1864
- async function buildClientJS() {
1865
- const sourceFile = resolve(PWD, "../", "./src/clientjs/hyperspan-client.ts");
1866
- const output = await Bun.build({
1867
- entrypoints: [sourceFile],
1868
- outdir: `./public/_hs/js`,
1869
- naming: IS_PROD ? "[dir]/[name]-[hash].[ext]" : undefined,
1870
- minify: IS_PROD
1871
- });
1872
- clientJSFile = output.outputs[0].path.split("/").reverse()[0];
1873
- return clientJSFile;
1874
- }
1875
- async function buildClientCSS() {
1876
- if (clientCSSFile) {
1877
- return clientCSSFile;
1878
- }
1879
- const cssDir = "./public/_hs/css/";
1880
- const cssFiles = await readdir(cssDir);
1881
- for (const file of cssFiles) {
1882
- if (clientCSSFile || !file.endsWith(".css")) {
1883
- continue;
1884
- }
1885
- return clientCSSFile = file.replace(cssDir, "");
1886
- }
1887
- if (!clientCSSFile) {
1888
- throw new Error(`Unable to build CSS files from ${cssDir}`);
1889
- }
1890
- }
1891
- function createReadableStreamFromAsyncGenerator(output) {
1892
- const encoder = new TextEncoder;
1893
- return new ReadableStream({
1894
- async start(controller) {
1895
- while (true) {
1896
- const { done, value } = await output.next();
1897
- if (done) {
1898
- controller.close();
1899
- break;
1900
- }
1901
- controller.enqueue(encoder.encode(value));
1902
- }
1903
- }
1904
- });
1905
- }
1906
- function formRoute(handlerFn) {
1907
- return function _formRouteHandler(context) {
1908
- };
1909
- }
1910
- var IS_PROD = false;
1911
- var PWD = import.meta.dir;
1912
- var CWD = process.cwd();
1913
- var STATIC_FILE_MATCHER = /[^/\\&\?]+\.([a-zA-Z]+)$/;
1914
- var _routeCache = {};
1915
- var ROUTE_SEGMENT = /(\[[a-zA-Z_\.]+\])/g;
1916
- var clientJSFile;
1917
- var clientCSSFile;
1918
-
1919
- class StreamResponse {
1920
- constructor(iterator, options = {}) {
1921
- const stream = createReadableStreamFromAsyncGenerator(iterator);
1922
- return new Response(stream, {
1923
- status: 200,
1924
- headers: {
1925
- "Content-Type": "text/html",
1926
- "Transfer-Encoding": "chunked",
1927
- ...options?.headers ?? {}
1928
- },
1929
- ...options
1930
- });
1931
- }
1932
- }
1933
- export {
1934
- runFileRoute,
1935
- formRoute,
1936
- createServer,
1937
- createReadableStreamFromAsyncGenerator,
1938
- clientJSFile,
1939
- clientCSSFile,
1940
- buildRoutes,
1941
- buildClientJS,
1942
- buildClientCSS,
1943
- StreamResponse,
1944
- IS_PROD
1945
- };