@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.14

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.
Files changed (58) hide show
  1. package/README.md +14 -232
  2. package/dist/await.d.ts +67 -0
  3. package/dist/build/index.js +2013 -191
  4. package/dist/cli/index.js +2007 -190
  5. package/dist/client.d.ts +33 -2
  6. package/dist/client.js +65 -1
  7. package/dist/deferred-ndjson.d.ts +32 -0
  8. package/dist/error.d.ts +14 -0
  9. package/dist/furin.d.ts +3 -0
  10. package/dist/furin.js +2684 -318
  11. package/dist/lang-detect.d.ts +5 -0
  12. package/dist/link.d.ts +1 -0
  13. package/dist/link.js +1453 -95
  14. package/dist/plugin/index.js +96 -25
  15. package/dist/plugin/transform-client.d.ts +2 -1
  16. package/dist/render/assemble.d.ts +32 -0
  17. package/dist/render/cache.d.ts +7 -0
  18. package/dist/render/element.d.ts +17 -1
  19. package/dist/render/index.d.ts +10 -1
  20. package/dist/render/index.ts +247 -44
  21. package/dist/render/loaders.d.ts +46 -3
  22. package/dist/render/shell.d.ts +16 -6
  23. package/dist/render/shell.ts +27 -12
  24. package/dist/router-provider.d.ts +86 -18
  25. package/dist/router.d.ts +63 -0
  26. package/dist/router.js +2768 -317
  27. package/dist/router.ts +543 -54
  28. package/dist/server-error.d.ts +12 -0
  29. package/dist/utils.d.ts +7 -0
  30. package/package.json +8 -7
  31. package/src/adapter/bun.ts +3 -3
  32. package/src/adapter/static.ts +73 -31
  33. package/src/await.tsx +175 -0
  34. package/src/build/client.ts +4 -8
  35. package/src/build/hydrate.ts +67 -1
  36. package/src/build/route-types.ts +5 -1
  37. package/src/build/scan-server.ts +6 -23
  38. package/src/client.ts +58 -1
  39. package/src/deferred-ndjson.ts +212 -0
  40. package/src/dev-page-plugin.ts +2 -0
  41. package/src/error.ts +18 -1
  42. package/src/furin.ts +12 -2
  43. package/src/lang-detect.ts +46 -0
  44. package/src/link.tsx +16 -3
  45. package/src/plugin/index.ts +7 -8
  46. package/src/plugin/transform-client.ts +108 -39
  47. package/src/render/assemble.ts +67 -0
  48. package/src/render/boundaries.tsx +23 -5
  49. package/src/render/cache.ts +7 -0
  50. package/src/render/default-screens.tsx +4 -11
  51. package/src/render/element.tsx +26 -3
  52. package/src/render/index.ts +247 -44
  53. package/src/render/loaders.ts +221 -18
  54. package/src/render/shell.ts +27 -12
  55. package/src/router-provider.tsx +414 -122
  56. package/src/router.ts +543 -54
  57. package/src/server-error.ts +47 -0
  58. package/src/utils.ts +31 -0
package/dist/router.js CHANGED
@@ -5,155 +5,1475 @@ import { readdir } from "fs/promises";
5
5
  import { join, parse } from "path";
6
6
  import { Elysia as Elysia2, t } from "elysia";
7
7
 
8
- // src/internal.ts
9
- var _compileCtx = null;
10
- function getCompileContext() {
11
- return _compileCtx;
8
+ // ../../node_modules/.bun/seroval@1.5.4/node_modules/seroval/dist/esm/development/index.mjs
9
+ var ALL_ENABLED = 1 | 2 | 4 | 8 | 16 | 32;
10
+ var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
11
+ var SYM_HAS_INSTANCE = Symbol.hasInstance;
12
+ var SYM_IS_CONCAT_SPREADABLE = Symbol.isConcatSpreadable;
13
+ var SYM_ITERATOR = Symbol.iterator;
14
+ var SYM_MATCH = Symbol.match;
15
+ var SYM_MATCH_ALL = Symbol.matchAll;
16
+ var SYM_REPLACE = Symbol.replace;
17
+ var SYM_SEARCH = Symbol.search;
18
+ var SYM_SPECIES = Symbol.species;
19
+ var SYM_SPLIT = Symbol.split;
20
+ var SYM_TO_PRIMITIVE = Symbol.toPrimitive;
21
+ var SYM_TO_STRING_TAG = Symbol.toStringTag;
22
+ var SYM_UNSCOPABLES = Symbol.unscopables;
23
+ var INV_SYMBOL_REF = {
24
+ [SYM_ASYNC_ITERATOR]: 0,
25
+ [SYM_HAS_INSTANCE]: 1,
26
+ [SYM_IS_CONCAT_SPREADABLE]: 2,
27
+ [SYM_ITERATOR]: 3,
28
+ [SYM_MATCH]: 4,
29
+ [SYM_MATCH_ALL]: 5,
30
+ [SYM_REPLACE]: 6,
31
+ [SYM_SEARCH]: 7,
32
+ [SYM_SPECIES]: 8,
33
+ [SYM_SPLIT]: 9,
34
+ [SYM_TO_PRIMITIVE]: 10,
35
+ [SYM_TO_STRING_TAG]: 11,
36
+ [SYM_UNSCOPABLES]: 12
37
+ };
38
+ var NIL = undefined;
39
+ var CONSTANT_VAL = {
40
+ [2]: true,
41
+ [3]: false,
42
+ [1]: NIL,
43
+ [0]: null,
44
+ [4]: -0,
45
+ [5]: Number.POSITIVE_INFINITY,
46
+ [6]: Number.NEGATIVE_INFINITY,
47
+ [7]: Number.NaN
48
+ };
49
+ var ERROR_CONSTRUCTOR_STRING = {
50
+ [0]: "Error",
51
+ [1]: "EvalError",
52
+ [2]: "RangeError",
53
+ [3]: "ReferenceError",
54
+ [4]: "SyntaxError",
55
+ [5]: "TypeError",
56
+ [6]: "URIError"
57
+ };
58
+ function createSerovalNode(t, i, s, c, m, p, e, a, f, b, o, l) {
59
+ return {
60
+ t,
61
+ i,
62
+ s,
63
+ c,
64
+ m,
65
+ p,
66
+ e,
67
+ a,
68
+ f,
69
+ b,
70
+ o,
71
+ l
72
+ };
73
+ }
74
+ function createConstantNode(value) {
75
+ return createSerovalNode(2, NIL, value, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
76
+ }
77
+ var TRUE_NODE = /* @__PURE__ */ createConstantNode(2);
78
+ var FALSE_NODE = /* @__PURE__ */ createConstantNode(3);
79
+ var UNDEFINED_NODE = /* @__PURE__ */ createConstantNode(1);
80
+ var NULL_NODE = /* @__PURE__ */ createConstantNode(0);
81
+ var NEG_ZERO_NODE = /* @__PURE__ */ createConstantNode(4);
82
+ var INFINITY_NODE = /* @__PURE__ */ createConstantNode(5);
83
+ var NEG_INFINITY_NODE = /* @__PURE__ */ createConstantNode(6);
84
+ var NAN_NODE = /* @__PURE__ */ createConstantNode(7);
85
+ function serializeChar(str) {
86
+ switch (str) {
87
+ case '"':
88
+ return "\\\"";
89
+ case "\\":
90
+ return "\\\\";
91
+ case `
92
+ `:
93
+ return "\\n";
94
+ case "\r":
95
+ return "\\r";
96
+ case "\b":
97
+ return "\\b";
98
+ case "\t":
99
+ return "\\t";
100
+ case "\f":
101
+ return "\\f";
102
+ case "<":
103
+ return "\\x3C";
104
+ case "\u2028":
105
+ return "\\u2028";
106
+ case "\u2029":
107
+ return "\\u2029";
108
+ default:
109
+ return NIL;
110
+ }
111
+ }
112
+ function serializeString(str) {
113
+ let result = "";
114
+ let lastPos = 0;
115
+ let replacement;
116
+ for (let i = 0, len = str.length;i < len; i++) {
117
+ replacement = serializeChar(str[i]);
118
+ if (replacement) {
119
+ result += str.slice(lastPos, i) + replacement;
120
+ lastPos = i + 1;
121
+ }
122
+ }
123
+ if (lastPos === 0) {
124
+ result = str;
125
+ } else {
126
+ result += str.slice(lastPos);
127
+ }
128
+ return result;
129
+ }
130
+ var REFERENCES_KEY = "__SEROVAL_REFS__";
131
+ var GLOBAL_CONTEXT_REFERENCES = "$R";
132
+ var GLOBAL_CONTEXT_R = `self.${GLOBAL_CONTEXT_REFERENCES}`;
133
+ var REFERENCE = /* @__PURE__ */ new Map;
134
+ var INV_REFERENCE = /* @__PURE__ */ new Map;
135
+ function hasReferenceID(value) {
136
+ return REFERENCE.has(value);
137
+ }
138
+ function getReferenceID(value) {
139
+ if (hasReferenceID(value)) {
140
+ return REFERENCE.get(value);
141
+ }
142
+ throw new SerovalMissingReferenceError(value);
143
+ }
144
+ if (typeof globalThis !== "undefined") {
145
+ Object.defineProperty(globalThis, REFERENCES_KEY, {
146
+ value: INV_REFERENCE,
147
+ configurable: true,
148
+ writable: false,
149
+ enumerable: false
150
+ });
151
+ } else if (typeof window !== "undefined") {
152
+ Object.defineProperty(window, REFERENCES_KEY, {
153
+ value: INV_REFERENCE,
154
+ configurable: true,
155
+ writable: false,
156
+ enumerable: false
157
+ });
158
+ } else if (typeof self !== "undefined") {
159
+ Object.defineProperty(self, REFERENCES_KEY, {
160
+ value: INV_REFERENCE,
161
+ configurable: true,
162
+ writable: false,
163
+ enumerable: false
164
+ });
165
+ } else if (typeof global !== "undefined") {
166
+ Object.defineProperty(global, REFERENCES_KEY, {
167
+ value: INV_REFERENCE,
168
+ configurable: true,
169
+ writable: false,
170
+ enumerable: false
171
+ });
172
+ }
173
+ function getErrorConstructor(error) {
174
+ if (error instanceof EvalError) {
175
+ return 1;
176
+ }
177
+ if (error instanceof RangeError) {
178
+ return 2;
179
+ }
180
+ if (error instanceof ReferenceError) {
181
+ return 3;
182
+ }
183
+ if (error instanceof SyntaxError) {
184
+ return 4;
185
+ }
186
+ if (error instanceof TypeError) {
187
+ return 5;
188
+ }
189
+ if (error instanceof URIError) {
190
+ return 6;
191
+ }
192
+ return 0;
193
+ }
194
+ function getInitialErrorOptions(error) {
195
+ const construct = ERROR_CONSTRUCTOR_STRING[getErrorConstructor(error)];
196
+ if (error.name !== construct) {
197
+ return { name: error.name };
198
+ }
199
+ if (error.constructor.name !== construct) {
200
+ return { name: error.constructor.name };
201
+ }
202
+ return {};
203
+ }
204
+ function getErrorOptions(error, features) {
205
+ let options = getInitialErrorOptions(error);
206
+ const names = Object.getOwnPropertyNames(error);
207
+ for (let i = 0, len = names.length, name;i < len; i++) {
208
+ name = names[i];
209
+ if (name !== "name" && name !== "message") {
210
+ if (name === "stack") {
211
+ if (features & 4) {
212
+ options = options || {};
213
+ options[name] = error[name];
214
+ }
215
+ } else {
216
+ options = options || {};
217
+ options[name] = error[name];
218
+ }
219
+ }
220
+ }
221
+ return options;
222
+ }
223
+ function getObjectFlag(obj) {
224
+ if (Object.isFrozen(obj)) {
225
+ return 3;
226
+ }
227
+ if (Object.isSealed(obj)) {
228
+ return 2;
229
+ }
230
+ if (Object.isExtensible(obj)) {
231
+ return 0;
232
+ }
233
+ return 1;
234
+ }
235
+ function createNumberNode(value) {
236
+ switch (value) {
237
+ case Number.POSITIVE_INFINITY:
238
+ return INFINITY_NODE;
239
+ case Number.NEGATIVE_INFINITY:
240
+ return NEG_INFINITY_NODE;
241
+ }
242
+ if (value !== value) {
243
+ return NAN_NODE;
244
+ }
245
+ if (Object.is(value, -0)) {
246
+ return NEG_ZERO_NODE;
247
+ }
248
+ return createSerovalNode(0, NIL, value, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
249
+ }
250
+ function createStringNode(value) {
251
+ return createSerovalNode(1, NIL, serializeString(value), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
252
+ }
253
+ function createBigIntNode(current) {
254
+ return createSerovalNode(3, NIL, "" + current, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
255
+ }
256
+ function createIndexedValueNode(id) {
257
+ return createSerovalNode(4, id, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
258
+ }
259
+ function createDateNode(id, current) {
260
+ const timestamp = current.valueOf();
261
+ return createSerovalNode(5, id, timestamp !== timestamp ? "" : current.toISOString(), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
262
+ }
263
+ function createRegExpNode(id, current) {
264
+ return createSerovalNode(6, id, NIL, serializeString(current.source), current.flags, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
265
+ }
266
+ function createWKSymbolNode(id, current) {
267
+ return createSerovalNode(17, id, INV_SYMBOL_REF[current], NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
268
+ }
269
+ function createReferenceNode(id, ref) {
270
+ return createSerovalNode(18, id, serializeString(getReferenceID(ref)), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
271
+ }
272
+ function createPluginNode(id, tag, value) {
273
+ return createSerovalNode(25, id, value, serializeString(tag), NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
274
+ }
275
+ function createArrayNode(id, current, parsedItems) {
276
+ return createSerovalNode(9, id, NIL, NIL, NIL, NIL, NIL, parsedItems, NIL, NIL, getObjectFlag(current), NIL);
277
+ }
278
+ function createBoxedNode(id, boxed) {
279
+ return createSerovalNode(21, id, NIL, NIL, NIL, NIL, NIL, NIL, boxed, NIL, NIL, NIL);
280
+ }
281
+ function createTypedArrayNode(id, current, buffer) {
282
+ return createSerovalNode(15, id, NIL, current.constructor.name, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.length);
283
+ }
284
+ function createBigIntTypedArrayNode(id, current, buffer) {
285
+ return createSerovalNode(16, id, NIL, current.constructor.name, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.byteLength);
286
+ }
287
+ function createDataViewNode(id, current, buffer) {
288
+ return createSerovalNode(20, id, NIL, NIL, NIL, NIL, NIL, NIL, buffer, current.byteOffset, NIL, current.byteLength);
12
289
  }
290
+ function createErrorNode(id, current, options) {
291
+ return createSerovalNode(13, id, getErrorConstructor(current), NIL, serializeString(current.message), options, NIL, NIL, NIL, NIL, NIL, NIL);
292
+ }
293
+ function createAggregateErrorNode(id, current, options) {
294
+ return createSerovalNode(14, id, getErrorConstructor(current), NIL, serializeString(current.message), options, NIL, NIL, NIL, NIL, NIL, NIL);
295
+ }
296
+ function createSetNode(id, items) {
297
+ return createSerovalNode(7, id, NIL, NIL, NIL, NIL, NIL, items, NIL, NIL, NIL, NIL);
298
+ }
299
+ function createIteratorFactoryInstanceNode(factory, items) {
300
+ return createSerovalNode(28, NIL, NIL, NIL, NIL, NIL, NIL, [factory, items], NIL, NIL, NIL, NIL);
301
+ }
302
+ function createAsyncIteratorFactoryInstanceNode(factory, items) {
303
+ return createSerovalNode(30, NIL, NIL, NIL, NIL, NIL, NIL, [factory, items], NIL, NIL, NIL, NIL);
304
+ }
305
+ function createStreamConstructorNode(id, factory, sequence) {
306
+ return createSerovalNode(31, id, NIL, NIL, NIL, NIL, NIL, sequence, factory, NIL, NIL, NIL);
307
+ }
308
+ function createStreamNextNode(id, parsed) {
309
+ return createSerovalNode(32, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
310
+ }
311
+ function createStreamThrowNode(id, parsed) {
312
+ return createSerovalNode(33, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
313
+ }
314
+ function createStreamReturnNode(id, parsed) {
315
+ return createSerovalNode(34, id, NIL, NIL, NIL, NIL, NIL, NIL, parsed, NIL, NIL, NIL);
316
+ }
317
+ function createSequenceNode(id, sequence, throwAt, doneAt) {
318
+ return createSerovalNode(35, id, throwAt, NIL, NIL, NIL, NIL, sequence, NIL, NIL, NIL, doneAt);
319
+ }
320
+ var { toString: objectToString } = Object.prototype;
321
+ function getErrorMessageDev(type, cause) {
322
+ if (cause instanceof Error) {
323
+ return `Seroval caught an error during the ${type} process.
13
324
 
14
- // src/render/shell.ts
15
- function extractTitle(meta) {
16
- if (!meta) {
17
- return;
325
+ ${cause.name}
326
+ ${cause.message}
327
+
328
+ - For more information, please check the "cause" property of this error.
329
+ - If you believe this is an error in Seroval, please submit an issue at https://github.com/lxsmnsyc/seroval/issues/new`;
18
330
  }
19
- for (const entry of meta) {
20
- if ("title" in entry) {
21
- return entry.title;
331
+ return `Seroval caught an error during the ${type} process.
332
+
333
+ "${objectToString.call(cause)}"
334
+
335
+ For more information, please check the "cause" property of this error.`;
336
+ }
337
+ var getErrorMessage = (type, cause) => getErrorMessageDev(type, cause);
338
+ var SerovalError = class extends Error {
339
+ constructor(type, cause) {
340
+ super(getErrorMessage(type, cause));
341
+ this.cause = cause;
342
+ }
343
+ };
344
+ var SerovalParserError = class extends SerovalError {
345
+ constructor(cause) {
346
+ super("parsing", cause);
347
+ }
348
+ };
349
+ var SerovalUnsupportedTypeError = class extends Error {
350
+ constructor(value) {
351
+ super(`The value ${objectToString.call(value)} of type "${typeof value}" cannot be parsed/serialized.
352
+
353
+ There are few workarounds for this problem:
354
+ - Transform the value in a way that it can be serialized.
355
+ - If the reference is present on multiple runtimes (isomorphic), you can use the Reference API to map the references.`);
356
+ this.value = value;
357
+ }
358
+ };
359
+ var SerovalMissingReferenceError = class extends Error {
360
+ constructor(value) {
361
+ super('Missing reference for the value "' + objectToString.call(value) + '" of type "' + typeof value + '"');
362
+ this.value = value;
363
+ }
364
+ };
365
+ var SerovalDepthLimitError = class extends Error {
366
+ constructor(limit) {
367
+ super("Depth limit of " + limit + " reached");
368
+ }
369
+ };
370
+ var OpaqueReference = class {
371
+ constructor(value, replacement) {
372
+ this.value = value;
373
+ this.replacement = replacement;
374
+ }
375
+ };
376
+ var PROMISE_CONSTRUCTOR = () => {
377
+ const resolver = {
378
+ p: 0,
379
+ s: 0,
380
+ f: 0
381
+ };
382
+ resolver.p = new Promise((resolve, reject) => {
383
+ resolver.s = resolve;
384
+ resolver.f = reject;
385
+ });
386
+ return resolver;
387
+ };
388
+ var STREAM_CONSTRUCTOR = () => {
389
+ const buffer = [];
390
+ const listeners = [];
391
+ let alive = true;
392
+ let success = false;
393
+ let count = 0;
394
+ const flush = (value, mode, x) => {
395
+ for (x = 0;x < count; x++) {
396
+ if (listeners[x]) {
397
+ listeners[x][mode](value);
398
+ }
399
+ }
400
+ };
401
+ const up = (listener, x, z, current) => {
402
+ for (x = 0, z = buffer.length;x < z; x++) {
403
+ current = buffer[x];
404
+ if (!alive && x === z - 1) {
405
+ listener[success ? "return" : "throw"](current);
406
+ } else {
407
+ listener.next(current);
408
+ }
409
+ }
410
+ };
411
+ const on = (listener, temp) => {
412
+ if (alive) {
413
+ temp = count++;
414
+ listeners[temp] = listener;
415
+ }
416
+ up(listener);
417
+ return () => {
418
+ if (alive) {
419
+ listeners[temp] = listeners[count];
420
+ listeners[count--] = undefined;
421
+ }
422
+ };
423
+ };
424
+ return {
425
+ __SEROVAL_STREAM__: true,
426
+ on: (listener) => on(listener),
427
+ next: (value) => {
428
+ if (alive) {
429
+ buffer.push(value);
430
+ flush(value, "next");
431
+ }
432
+ },
433
+ throw: (value) => {
434
+ if (alive) {
435
+ buffer.push(value);
436
+ flush(value, "throw");
437
+ alive = false;
438
+ success = false;
439
+ listeners.length = 0;
440
+ }
441
+ },
442
+ return: (value) => {
443
+ if (alive) {
444
+ buffer.push(value);
445
+ flush(value, "return");
446
+ alive = false;
447
+ success = true;
448
+ listeners.length = 0;
449
+ }
450
+ }
451
+ };
452
+ };
453
+ var ITERATOR_CONSTRUCTOR = (symbol) => (sequence) => () => {
454
+ let index = 0;
455
+ const instance = {
456
+ [symbol]: () => instance,
457
+ next: () => {
458
+ if (index > sequence.d) {
459
+ return {
460
+ done: true,
461
+ value: undefined
462
+ };
463
+ }
464
+ const currentIndex = index++;
465
+ const data = sequence.v[currentIndex];
466
+ if (currentIndex === sequence.t) {
467
+ throw data;
468
+ }
469
+ return {
470
+ done: currentIndex === sequence.d,
471
+ value: data
472
+ };
473
+ }
474
+ };
475
+ return instance;
476
+ };
477
+ var ASYNC_ITERATOR_CONSTRUCTOR = (symbol, createPromise) => (stream) => () => {
478
+ let count = 0;
479
+ let doneAt = -1;
480
+ let isThrow = false;
481
+ const buffer = [];
482
+ const pending = [];
483
+ const finalize = (i = 0, len = pending.length) => {
484
+ for (;i < len; i++) {
485
+ pending[i].s({
486
+ done: true,
487
+ value: undefined
488
+ });
489
+ }
490
+ };
491
+ stream.on({
492
+ next: (value) => {
493
+ const temp = pending.shift();
494
+ if (temp) {
495
+ temp.s({ done: false, value });
496
+ }
497
+ buffer.push(value);
498
+ },
499
+ throw: (value) => {
500
+ const temp = pending.shift();
501
+ if (temp) {
502
+ temp.f(value);
503
+ }
504
+ finalize();
505
+ doneAt = buffer.length;
506
+ isThrow = true;
507
+ buffer.push(value);
508
+ },
509
+ return: (value) => {
510
+ const temp = pending.shift();
511
+ if (temp) {
512
+ temp.s({ done: true, value });
513
+ }
514
+ finalize();
515
+ doneAt = buffer.length;
516
+ buffer.push(value);
517
+ }
518
+ });
519
+ const instance = {
520
+ [symbol]: () => instance,
521
+ next: () => {
522
+ if (doneAt === -1) {
523
+ const index2 = count++;
524
+ if (index2 >= buffer.length) {
525
+ const temp = createPromise();
526
+ pending.push(temp);
527
+ return temp.p;
528
+ }
529
+ return {
530
+ done: false,
531
+ value: buffer[index2]
532
+ };
533
+ }
534
+ if (count > doneAt) {
535
+ return {
536
+ done: true,
537
+ value: undefined
538
+ };
539
+ }
540
+ const index = count++;
541
+ const value = buffer[index];
542
+ if (index !== doneAt) {
543
+ return {
544
+ done: false,
545
+ value
546
+ };
547
+ }
548
+ if (isThrow) {
549
+ throw value;
550
+ }
551
+ return {
552
+ done: true,
553
+ value
554
+ };
555
+ }
556
+ };
557
+ return instance;
558
+ };
559
+ function isSequence(value) {
560
+ return "__SEROVAL_SEQUENCE__" in value;
561
+ }
562
+ function createSequence(values, throwAt, doneAt) {
563
+ return {
564
+ __SEROVAL_SEQUENCE__: true,
565
+ v: values,
566
+ t: throwAt,
567
+ d: doneAt
568
+ };
569
+ }
570
+ function createSequenceFromIterable(source) {
571
+ const values = [];
572
+ let throwsAt = -1;
573
+ let doneAt = -1;
574
+ const iterator = source[SYM_ITERATOR]();
575
+ while (true) {
576
+ try {
577
+ const value = iterator.next();
578
+ values.push(value.value);
579
+ if (value.done) {
580
+ doneAt = values.length - 1;
581
+ break;
582
+ }
583
+ } catch (error) {
584
+ throwsAt = values.length;
585
+ values.push(error);
586
+ }
587
+ }
588
+ return createSequence(values, throwsAt, doneAt);
589
+ }
590
+ var createIterator = ITERATOR_CONSTRUCTOR(SYM_ITERATOR);
591
+ var ITERATOR = {};
592
+ var ASYNC_ITERATOR = {};
593
+ var SPECIAL_REFS = {
594
+ [0]: {},
595
+ [1]: {},
596
+ [2]: {},
597
+ [3]: {},
598
+ [4]: {},
599
+ [5]: {}
600
+ };
601
+ function isStream(value) {
602
+ return "__SEROVAL_STREAM__" in value;
603
+ }
604
+ function createStream() {
605
+ return STREAM_CONSTRUCTOR();
606
+ }
607
+ function createStreamFromAsyncIterable(iterable) {
608
+ const stream = createStream();
609
+ const iterator = iterable[SYM_ASYNC_ITERATOR]();
610
+ async function push() {
611
+ try {
612
+ const value = await iterator.next();
613
+ if (value.done) {
614
+ stream.return(value.value);
615
+ } else {
616
+ stream.next(value.value);
617
+ await push();
618
+ }
619
+ } catch (error) {
620
+ stream.throw(error);
621
+ }
622
+ }
623
+ push().catch(() => {});
624
+ return stream;
625
+ }
626
+ var createAsyncIterable = ASYNC_ITERATOR_CONSTRUCTOR(SYM_ASYNC_ITERATOR, PROMISE_CONSTRUCTOR);
627
+ async function promiseToResult(current) {
628
+ try {
629
+ return [1, await current];
630
+ } catch (e) {
631
+ return [0, e];
632
+ }
633
+ }
634
+ function createBaseParserContext(mode, options) {
635
+ return {
636
+ plugins: options.plugins,
637
+ mode,
638
+ marked: /* @__PURE__ */ new Set,
639
+ features: ALL_ENABLED ^ (options.disabledFeatures || 0),
640
+ refs: options.refs || /* @__PURE__ */ new Map,
641
+ depthLimit: options.depthLimit || 1000
642
+ };
643
+ }
644
+ function markParserRef(ctx, id) {
645
+ ctx.marked.add(id);
646
+ }
647
+ function createIndexForValue(ctx, current) {
648
+ const id = ctx.refs.size;
649
+ ctx.refs.set(current, id);
650
+ return id;
651
+ }
652
+ function getNodeForIndexedValue(ctx, current) {
653
+ const registeredId = ctx.refs.get(current);
654
+ if (registeredId != null) {
655
+ markParserRef(ctx, registeredId);
656
+ return {
657
+ type: 1,
658
+ value: createIndexedValueNode(registeredId)
659
+ };
660
+ }
661
+ return {
662
+ type: 0,
663
+ value: createIndexForValue(ctx, current)
664
+ };
665
+ }
666
+ function getReferenceNode(ctx, current) {
667
+ const indexed = getNodeForIndexedValue(ctx, current);
668
+ if (indexed.type === 1) {
669
+ return indexed;
670
+ }
671
+ if (hasReferenceID(current)) {
672
+ return {
673
+ type: 2,
674
+ value: createReferenceNode(indexed.value, current)
675
+ };
676
+ }
677
+ return indexed;
678
+ }
679
+ function parseWellKnownSymbol(ctx, current) {
680
+ const ref = getReferenceNode(ctx, current);
681
+ if (ref.type !== 0) {
682
+ return ref.value;
683
+ }
684
+ if (current in INV_SYMBOL_REF) {
685
+ return createWKSymbolNode(ref.value, current);
686
+ }
687
+ throw new SerovalUnsupportedTypeError(current);
688
+ }
689
+ function parseSpecialReference(ctx, ref) {
690
+ const result = getNodeForIndexedValue(ctx, SPECIAL_REFS[ref]);
691
+ if (result.type === 1) {
692
+ return result.value;
693
+ }
694
+ return createSerovalNode(26, result.value, ref, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL, NIL);
695
+ }
696
+ function parseIteratorFactory(ctx) {
697
+ const result = getNodeForIndexedValue(ctx, ITERATOR);
698
+ if (result.type === 1) {
699
+ return result.value;
700
+ }
701
+ return createSerovalNode(27, result.value, NIL, NIL, NIL, NIL, NIL, NIL, parseWellKnownSymbol(ctx, SYM_ITERATOR), NIL, NIL, NIL);
702
+ }
703
+ function parseAsyncIteratorFactory(ctx) {
704
+ const result = getNodeForIndexedValue(ctx, ASYNC_ITERATOR);
705
+ if (result.type === 1) {
706
+ return result.value;
707
+ }
708
+ return createSerovalNode(29, result.value, NIL, NIL, NIL, NIL, NIL, [
709
+ parseSpecialReference(ctx, 1),
710
+ parseWellKnownSymbol(ctx, SYM_ASYNC_ITERATOR)
711
+ ], NIL, NIL, NIL, NIL);
712
+ }
713
+ function createObjectNode(id, current, empty, record) {
714
+ return createSerovalNode(empty ? 11 : 10, id, NIL, NIL, NIL, record, NIL, NIL, NIL, NIL, getObjectFlag(current), NIL);
715
+ }
716
+ function createMapNode(ctx, id, k, v) {
717
+ return createSerovalNode(8, id, NIL, NIL, NIL, NIL, { k, v }, NIL, parseSpecialReference(ctx, 0), NIL, NIL, NIL);
718
+ }
719
+ function createPromiseConstructorNode(ctx, id, resolver) {
720
+ return createSerovalNode(22, id, resolver, NIL, NIL, NIL, NIL, NIL, parseSpecialReference(ctx, 1), NIL, NIL, NIL);
721
+ }
722
+ function createArrayBufferNode(ctx, id, current) {
723
+ const bytes = new Uint8Array(current);
724
+ let result = "";
725
+ for (let i = 0, len = bytes.length;i < len; i++) {
726
+ result += String.fromCharCode(bytes[i]);
727
+ }
728
+ return createSerovalNode(19, id, serializeString(btoa(result)), NIL, NIL, NIL, NIL, NIL, parseSpecialReference(ctx, 5), NIL, NIL, NIL);
729
+ }
730
+ function createAsyncParserContext(mode, options) {
731
+ return {
732
+ base: createBaseParserContext(mode, options),
733
+ child: undefined
734
+ };
735
+ }
736
+ var AsyncParsePluginContext = class {
737
+ constructor(_p, depth) {
738
+ this._p = _p;
739
+ this.depth = depth;
740
+ }
741
+ parse(current) {
742
+ return parseAsync(this._p, this.depth, current);
743
+ }
744
+ };
745
+ async function parseItems(ctx, depth, current) {
746
+ const nodes = [];
747
+ for (let i = 0, len = current.length;i < len; i++) {
748
+ if (i in current) {
749
+ nodes[i] = await parseAsync(ctx, depth, current[i]);
750
+ } else {
751
+ nodes[i] = 0;
752
+ }
753
+ }
754
+ return nodes;
755
+ }
756
+ async function parseArray(ctx, depth, id, current) {
757
+ return createArrayNode(id, current, await parseItems(ctx, depth, current));
758
+ }
759
+ async function parseProperties(ctx, depth, properties) {
760
+ const entries = Object.entries(properties);
761
+ const keyNodes = [];
762
+ const valueNodes = [];
763
+ for (let i = 0, len = entries.length;i < len; i++) {
764
+ keyNodes.push(serializeString(entries[i][0]));
765
+ valueNodes.push(await parseAsync(ctx, depth, entries[i][1]));
766
+ }
767
+ if (SYM_ITERATOR in properties) {
768
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
769
+ valueNodes.push(createIteratorFactoryInstanceNode(parseIteratorFactory(ctx.base), await parseAsync(ctx, depth, createSequenceFromIterable(properties))));
770
+ }
771
+ if (SYM_ASYNC_ITERATOR in properties) {
772
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
773
+ valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), await parseAsync(ctx, depth, createStreamFromAsyncIterable(properties))));
774
+ }
775
+ if (SYM_TO_STRING_TAG in properties) {
776
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
777
+ valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
778
+ }
779
+ if (SYM_IS_CONCAT_SPREADABLE in properties) {
780
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
781
+ valueNodes.push(properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE);
782
+ }
783
+ return {
784
+ k: keyNodes,
785
+ v: valueNodes
786
+ };
787
+ }
788
+ async function parsePlainObject(ctx, depth, id, current, empty) {
789
+ return createObjectNode(id, current, empty, await parseProperties(ctx, depth, current));
790
+ }
791
+ async function parseBoxed(ctx, depth, id, current) {
792
+ return createBoxedNode(id, await parseAsync(ctx, depth, current.valueOf()));
793
+ }
794
+ async function parseTypedArray(ctx, depth, id, current) {
795
+ return createTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
796
+ }
797
+ async function parseBigIntTypedArray(ctx, depth, id, current) {
798
+ return createBigIntTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
799
+ }
800
+ async function parseDataView(ctx, depth, id, current) {
801
+ return createDataViewNode(id, current, await parseAsync(ctx, depth, current.buffer));
802
+ }
803
+ async function parseError(ctx, depth, id, current) {
804
+ const options = getErrorOptions(current, ctx.base.features);
805
+ return createErrorNode(id, current, options ? await parseProperties(ctx, depth, options) : NIL);
806
+ }
807
+ async function parseAggregateError(ctx, depth, id, current) {
808
+ const options = getErrorOptions(current, ctx.base.features);
809
+ return createAggregateErrorNode(id, current, options ? await parseProperties(ctx, depth, options) : NIL);
810
+ }
811
+ async function parseMap(ctx, depth, id, current) {
812
+ const keyNodes = [];
813
+ const valueNodes = [];
814
+ for (const [key, value] of current.entries()) {
815
+ keyNodes.push(await parseAsync(ctx, depth, key));
816
+ valueNodes.push(await parseAsync(ctx, depth, value));
817
+ }
818
+ return createMapNode(ctx.base, id, keyNodes, valueNodes);
819
+ }
820
+ async function parseSet(ctx, depth, id, current) {
821
+ const items = [];
822
+ for (const item of current.keys()) {
823
+ items.push(await parseAsync(ctx, depth, item));
824
+ }
825
+ return createSetNode(id, items);
826
+ }
827
+ async function parsePlugin(ctx, depth, id, current) {
828
+ const currentPlugins = ctx.base.plugins;
829
+ if (currentPlugins) {
830
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
831
+ const plugin = currentPlugins[i];
832
+ if (plugin.parse.async && plugin.test(current)) {
833
+ return createPluginNode(id, plugin.tag, await plugin.parse.async(current, new AsyncParsePluginContext(ctx, depth), {
834
+ id
835
+ }));
836
+ }
837
+ }
838
+ }
839
+ return NIL;
840
+ }
841
+ async function parsePromise(ctx, depth, id, current) {
842
+ const [status, result] = await promiseToResult(current);
843
+ return createSerovalNode(12, id, status, NIL, NIL, NIL, NIL, NIL, await parseAsync(ctx, depth, result), NIL, NIL, NIL);
844
+ }
845
+ function parseStreamHandle(depth, id, current, resolve, reject) {
846
+ const sequence = [];
847
+ const cleanup = current.on({
848
+ next: (value) => {
849
+ markParserRef(this.base, id);
850
+ parseAsync(this, depth, value).then((data) => {
851
+ sequence.push(createStreamNextNode(id, data));
852
+ }, (data) => {
853
+ reject(data);
854
+ cleanup();
855
+ });
856
+ },
857
+ throw: (value) => {
858
+ markParserRef(this.base, id);
859
+ parseAsync(this, depth, value).then((data) => {
860
+ sequence.push(createStreamThrowNode(id, data));
861
+ resolve(sequence);
862
+ cleanup();
863
+ }, (data) => {
864
+ reject(data);
865
+ cleanup();
866
+ });
867
+ },
868
+ return: (value) => {
869
+ markParserRef(this.base, id);
870
+ parseAsync(this, depth, value).then((data) => {
871
+ sequence.push(createStreamReturnNode(id, data));
872
+ resolve(sequence);
873
+ cleanup();
874
+ }, (data) => {
875
+ reject(data);
876
+ cleanup();
877
+ });
878
+ }
879
+ });
880
+ }
881
+ async function parseStream(ctx, depth, id, current) {
882
+ return createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), await new Promise(parseStreamHandle.bind(ctx, depth, id, current)));
883
+ }
884
+ async function parseSequence(ctx, depth, id, current) {
885
+ const nodes = [];
886
+ for (let i = 0, len = current.v.length;i < len; i++) {
887
+ nodes[i] = await parseAsync(ctx, depth, current.v[i]);
888
+ }
889
+ return createSequenceNode(id, nodes, current.t, current.d);
890
+ }
891
+ async function parseObjectAsync(ctx, depth, id, current) {
892
+ if (Array.isArray(current)) {
893
+ return parseArray(ctx, depth, id, current);
894
+ }
895
+ if (isStream(current)) {
896
+ return parseStream(ctx, depth, id, current);
897
+ }
898
+ if (isSequence(current)) {
899
+ return parseSequence(ctx, depth, id, current);
900
+ }
901
+ const currentClass = current.constructor;
902
+ if (currentClass === OpaqueReference) {
903
+ return parseAsync(ctx, depth, current.replacement);
904
+ }
905
+ const parsed = await parsePlugin(ctx, depth, id, current);
906
+ if (parsed) {
907
+ return parsed;
908
+ }
909
+ switch (currentClass) {
910
+ case Object:
911
+ return parsePlainObject(ctx, depth, id, current, false);
912
+ case NIL:
913
+ return parsePlainObject(ctx, depth, id, current, true);
914
+ case Date:
915
+ return createDateNode(id, current);
916
+ case Error:
917
+ case EvalError:
918
+ case RangeError:
919
+ case ReferenceError:
920
+ case SyntaxError:
921
+ case TypeError:
922
+ case URIError:
923
+ return parseError(ctx, depth, id, current);
924
+ case Number:
925
+ case Boolean:
926
+ case String:
927
+ case BigInt:
928
+ return parseBoxed(ctx, depth, id, current);
929
+ case ArrayBuffer:
930
+ return createArrayBufferNode(ctx.base, id, current);
931
+ case Int8Array:
932
+ case Int16Array:
933
+ case Int32Array:
934
+ case Uint8Array:
935
+ case Uint16Array:
936
+ case Uint32Array:
937
+ case Uint8ClampedArray:
938
+ case Float32Array:
939
+ case Float64Array:
940
+ return parseTypedArray(ctx, depth, id, current);
941
+ case DataView:
942
+ return parseDataView(ctx, depth, id, current);
943
+ case Map:
944
+ return parseMap(ctx, depth, id, current);
945
+ case Set:
946
+ return parseSet(ctx, depth, id, current);
947
+ default:
948
+ break;
949
+ }
950
+ if (currentClass === Promise || current instanceof Promise) {
951
+ return parsePromise(ctx, depth, id, current);
952
+ }
953
+ const currentFeatures = ctx.base.features;
954
+ if (currentFeatures & 32 && currentClass === RegExp) {
955
+ return createRegExpNode(id, current);
956
+ }
957
+ if (currentFeatures & 16) {
958
+ switch (currentClass) {
959
+ case BigInt64Array:
960
+ case BigUint64Array:
961
+ return parseBigIntTypedArray(ctx, depth, id, current);
962
+ default:
963
+ break;
964
+ }
965
+ }
966
+ if (currentFeatures & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) {
967
+ return parseAggregateError(ctx, depth, id, current);
968
+ }
969
+ if (current instanceof Error) {
970
+ return parseError(ctx, depth, id, current);
971
+ }
972
+ if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) {
973
+ return parsePlainObject(ctx, depth, id, current, !!currentClass);
974
+ }
975
+ throw new SerovalUnsupportedTypeError(current);
976
+ }
977
+ async function parseFunctionAsync(ctx, depth, current) {
978
+ const ref = getReferenceNode(ctx.base, current);
979
+ if (ref.type !== 0) {
980
+ return ref.value;
981
+ }
982
+ const plugin = await parsePlugin(ctx, depth, ref.value, current);
983
+ if (plugin) {
984
+ return plugin;
985
+ }
986
+ throw new SerovalUnsupportedTypeError(current);
987
+ }
988
+ async function parseAsync(ctx, depth, current) {
989
+ switch (typeof current) {
990
+ case "boolean":
991
+ return current ? TRUE_NODE : FALSE_NODE;
992
+ case "undefined":
993
+ return UNDEFINED_NODE;
994
+ case "string":
995
+ return createStringNode(current);
996
+ case "number":
997
+ return createNumberNode(current);
998
+ case "bigint":
999
+ return createBigIntNode(current);
1000
+ case "object": {
1001
+ if (current) {
1002
+ const ref = getReferenceNode(ctx.base, current);
1003
+ return ref.type === 0 ? await parseObjectAsync(ctx, depth + 1, ref.value, current) : ref.value;
1004
+ }
1005
+ return NULL_NODE;
1006
+ }
1007
+ case "symbol":
1008
+ return parseWellKnownSymbol(ctx.base, current);
1009
+ case "function":
1010
+ return parseFunctionAsync(ctx, depth, current);
1011
+ default:
1012
+ throw new SerovalUnsupportedTypeError(current);
1013
+ }
1014
+ }
1015
+ async function parseTopAsync(ctx, current) {
1016
+ try {
1017
+ return await parseAsync(ctx, 0, current);
1018
+ } catch (error) {
1019
+ throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
1020
+ }
1021
+ }
1022
+ function dedupePlugins(deduped, plugins) {
1023
+ for (let i = 0, len = plugins.length;i < len; i++) {
1024
+ const current = plugins[i];
1025
+ if (!deduped.has(current)) {
1026
+ deduped.add(current);
1027
+ if (current.extends) {
1028
+ dedupePlugins(deduped, current.extends);
1029
+ }
1030
+ }
1031
+ }
1032
+ }
1033
+ function resolvePlugins(plugins) {
1034
+ if (plugins) {
1035
+ const deduped = /* @__PURE__ */ new Set;
1036
+ dedupePlugins(deduped, plugins);
1037
+ return [...deduped];
1038
+ }
1039
+ return;
1040
+ }
1041
+ var REF_START_CHARS = "hjkmoquxzABCDEFGHIJKLNPQRTUVWXYZ$_";
1042
+ var REF_START_CHARS_LEN = REF_START_CHARS.length;
1043
+ var REF_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
1044
+ var REF_CHARS_LEN = REF_CHARS.length;
1045
+ function createSyncParserContext(mode, options) {
1046
+ return {
1047
+ type: 1,
1048
+ base: createBaseParserContext(mode, options),
1049
+ child: NIL
1050
+ };
1051
+ }
1052
+ var SyncParsePluginContext = class {
1053
+ constructor(_p, depth) {
1054
+ this._p = _p;
1055
+ this.depth = depth;
1056
+ }
1057
+ parse(current) {
1058
+ return parseSOS(this._p, this.depth, current);
1059
+ }
1060
+ };
1061
+ var StreamParsePluginContext = class {
1062
+ constructor(_p, depth) {
1063
+ this._p = _p;
1064
+ this.depth = depth;
1065
+ }
1066
+ parse(current) {
1067
+ return parseSOS(this._p, this.depth, current);
1068
+ }
1069
+ parseWithError(current) {
1070
+ return parseWithError(this._p, this.depth, current);
1071
+ }
1072
+ isAlive() {
1073
+ return this._p.state.alive;
1074
+ }
1075
+ pushPendingState() {
1076
+ pushPendingState(this._p);
1077
+ }
1078
+ popPendingState() {
1079
+ popPendingState(this._p);
1080
+ }
1081
+ onParse(node) {
1082
+ onParse(this._p, node);
1083
+ }
1084
+ onError(error) {
1085
+ onError(this._p, error);
1086
+ }
1087
+ };
1088
+ function parseItems2(ctx, depth, current) {
1089
+ const nodes = [];
1090
+ for (let i = 0, len = current.length;i < len; i++) {
1091
+ if (i in current) {
1092
+ nodes[i] = parseSOS(ctx, depth, current[i]);
1093
+ } else {
1094
+ nodes[i] = 0;
1095
+ }
1096
+ }
1097
+ return nodes;
1098
+ }
1099
+ function parseArray2(ctx, depth, id, current) {
1100
+ return createArrayNode(id, current, parseItems2(ctx, depth, current));
1101
+ }
1102
+ function parseProperties2(ctx, depth, properties) {
1103
+ const entries = Object.entries(properties);
1104
+ const keyNodes = [];
1105
+ const valueNodes = [];
1106
+ for (let i = 0, len = entries.length;i < len; i++) {
1107
+ keyNodes.push(serializeString(entries[i][0]));
1108
+ valueNodes.push(parseSOS(ctx, depth, entries[i][1]));
1109
+ }
1110
+ if (SYM_ITERATOR in properties) {
1111
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ITERATOR));
1112
+ valueNodes.push(createIteratorFactoryInstanceNode(parseIteratorFactory(ctx.base), parseSOS(ctx, depth, createSequenceFromIterable(properties))));
1113
+ }
1114
+ if (SYM_ASYNC_ITERATOR in properties) {
1115
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
1116
+ valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), parseSOS(ctx, depth, ctx.type === 1 ? createStream() : createStreamFromAsyncIterable(properties))));
1117
+ }
1118
+ if (SYM_TO_STRING_TAG in properties) {
1119
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
1120
+ valueNodes.push(createStringNode(properties[SYM_TO_STRING_TAG]));
1121
+ }
1122
+ if (SYM_IS_CONCAT_SPREADABLE in properties) {
1123
+ keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_IS_CONCAT_SPREADABLE));
1124
+ valueNodes.push(properties[SYM_IS_CONCAT_SPREADABLE] ? TRUE_NODE : FALSE_NODE);
1125
+ }
1126
+ return {
1127
+ k: keyNodes,
1128
+ v: valueNodes
1129
+ };
1130
+ }
1131
+ function parsePlainObject2(ctx, depth, id, current, empty) {
1132
+ return createObjectNode(id, current, empty, parseProperties2(ctx, depth, current));
1133
+ }
1134
+ function parseBoxed2(ctx, depth, id, current) {
1135
+ return createBoxedNode(id, parseSOS(ctx, depth, current.valueOf()));
1136
+ }
1137
+ function parseTypedArray2(ctx, depth, id, current) {
1138
+ return createTypedArrayNode(id, current, parseSOS(ctx, depth, current.buffer));
1139
+ }
1140
+ function parseBigIntTypedArray2(ctx, depth, id, current) {
1141
+ return createBigIntTypedArrayNode(id, current, parseSOS(ctx, depth, current.buffer));
1142
+ }
1143
+ function parseDataView2(ctx, depth, id, current) {
1144
+ return createDataViewNode(id, current, parseSOS(ctx, depth, current.buffer));
1145
+ }
1146
+ function parseError2(ctx, depth, id, current) {
1147
+ const options = getErrorOptions(current, ctx.base.features);
1148
+ return createErrorNode(id, current, options ? parseProperties2(ctx, depth, options) : NIL);
1149
+ }
1150
+ function parseAggregateError2(ctx, depth, id, current) {
1151
+ const options = getErrorOptions(current, ctx.base.features);
1152
+ return createAggregateErrorNode(id, current, options ? parseProperties2(ctx, depth, options) : NIL);
1153
+ }
1154
+ function parseMap2(ctx, depth, id, current) {
1155
+ const keyNodes = [];
1156
+ const valueNodes = [];
1157
+ for (const [key, value] of current.entries()) {
1158
+ keyNodes.push(parseSOS(ctx, depth, key));
1159
+ valueNodes.push(parseSOS(ctx, depth, value));
1160
+ }
1161
+ return createMapNode(ctx.base, id, keyNodes, valueNodes);
1162
+ }
1163
+ function parseSet2(ctx, depth, id, current) {
1164
+ const items = [];
1165
+ for (const item of current.keys()) {
1166
+ items.push(parseSOS(ctx, depth, item));
1167
+ }
1168
+ return createSetNode(id, items);
1169
+ }
1170
+ function parseStream2(ctx, depth, id, current) {
1171
+ const result = createStreamConstructorNode(id, parseSpecialReference(ctx.base, 4), []);
1172
+ if (ctx.type === 1) {
1173
+ return result;
1174
+ }
1175
+ pushPendingState(ctx);
1176
+ current.on({
1177
+ next: (value) => {
1178
+ if (ctx.state.alive) {
1179
+ const parsed = parseWithError(ctx, depth, value);
1180
+ if (parsed) {
1181
+ onParse(ctx, createStreamNextNode(id, parsed));
1182
+ }
1183
+ }
1184
+ },
1185
+ throw: (value) => {
1186
+ if (ctx.state.alive) {
1187
+ const parsed = parseWithError(ctx, depth, value);
1188
+ if (parsed) {
1189
+ onParse(ctx, createStreamThrowNode(id, parsed));
1190
+ }
1191
+ }
1192
+ popPendingState(ctx);
1193
+ },
1194
+ return: (value) => {
1195
+ if (ctx.state.alive) {
1196
+ const parsed = parseWithError(ctx, depth, value);
1197
+ if (parsed) {
1198
+ onParse(ctx, createStreamReturnNode(id, parsed));
1199
+ }
1200
+ }
1201
+ popPendingState(ctx);
22
1202
  }
23
- }
24
- return;
25
- }
26
- function isMetaTag(entry) {
27
- return !(("title" in entry) || ("charSet" in entry) || ("script:ld+json" in entry) || ("tagName" in entry));
1203
+ });
1204
+ return result;
28
1205
  }
29
- function escapeHtml(str) {
30
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
1206
+ function handlePromiseSuccess(id, depth, data) {
1207
+ if (this.state.alive) {
1208
+ const parsed = parseWithError(this, depth, data);
1209
+ if (parsed) {
1210
+ onParse(this, createSerovalNode(23, id, NIL, NIL, NIL, NIL, NIL, [
1211
+ parseSpecialReference(this.base, 2),
1212
+ parsed
1213
+ ], NIL, NIL, NIL, NIL));
1214
+ }
1215
+ popPendingState(this);
1216
+ }
31
1217
  }
32
- function safeJson(value) {
33
- return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1218
+ function handlePromiseFailure(id, depth, data) {
1219
+ if (this.state.alive) {
1220
+ const parsed = parseWithError(this, depth, data);
1221
+ if (parsed) {
1222
+ onParse(this, createSerovalNode(24, id, NIL, NIL, NIL, NIL, NIL, [
1223
+ parseSpecialReference(this.base, 3),
1224
+ parsed
1225
+ ], NIL, NIL, NIL, NIL));
1226
+ }
1227
+ }
1228
+ popPendingState(this);
34
1229
  }
35
- function renderAttrs(obj) {
36
- return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
1230
+ function parsePromise2(ctx, depth, id, current) {
1231
+ const resolver = createIndexForValue(ctx.base, {});
1232
+ if (ctx.type === 2) {
1233
+ pushPendingState(ctx);
1234
+ current.then(handlePromiseSuccess.bind(ctx, resolver, depth), handlePromiseFailure.bind(ctx, resolver, depth));
1235
+ }
1236
+ return createPromiseConstructorNode(ctx.base, id, resolver);
37
1237
  }
38
- function buildMetaParts(meta) {
39
- const parts = [];
40
- const title = extractTitle(meta);
41
- if (title) {
42
- parts.push(`<title>${escapeHtml(title)}</title>`);
1238
+ function parsePluginSync(ctx, depth, id, current, currentPlugins) {
1239
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
1240
+ const plugin = currentPlugins[i];
1241
+ if (plugin.parse.sync && plugin.test(current)) {
1242
+ return createPluginNode(id, plugin.tag, plugin.parse.sync(current, new SyncParsePluginContext(ctx, depth), {
1243
+ id
1244
+ }));
1245
+ }
43
1246
  }
44
- for (const m of meta) {
45
- if (isMetaTag(m)) {
46
- parts.push(`<meta ${renderAttrs(m)} />`);
1247
+ return NIL;
1248
+ }
1249
+ function parsePluginStream(ctx, depth, id, current, currentPlugins) {
1250
+ for (let i = 0, len = currentPlugins.length;i < len; i++) {
1251
+ const plugin = currentPlugins[i];
1252
+ if (plugin.parse.stream && plugin.test(current)) {
1253
+ return createPluginNode(id, plugin.tag, plugin.parse.stream(current, new StreamParsePluginContext(ctx, depth), {
1254
+ id
1255
+ }));
47
1256
  }
48
- if ("script:ld+json" in m) {
49
- parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
1257
+ }
1258
+ return NIL;
1259
+ }
1260
+ function parsePlugin2(ctx, depth, id, current) {
1261
+ const currentPlugins = ctx.base.plugins;
1262
+ if (currentPlugins) {
1263
+ return ctx.type === 1 ? parsePluginSync(ctx, depth, id, current, currentPlugins) : parsePluginStream(ctx, depth, id, current, currentPlugins);
1264
+ }
1265
+ return NIL;
1266
+ }
1267
+ function parseSequence2(ctx, depth, id, current) {
1268
+ const nodes = [];
1269
+ for (let i = 0, len = current.v.length;i < len; i++) {
1270
+ nodes[i] = parseSOS(ctx, depth, current.v[i]);
1271
+ }
1272
+ return createSequenceNode(id, nodes, current.t, current.d);
1273
+ }
1274
+ function parseObjectPhase2(ctx, depth, id, current, currentClass) {
1275
+ switch (currentClass) {
1276
+ case Object:
1277
+ return parsePlainObject2(ctx, depth, id, current, false);
1278
+ case NIL:
1279
+ return parsePlainObject2(ctx, depth, id, current, true);
1280
+ case Date:
1281
+ return createDateNode(id, current);
1282
+ case Error:
1283
+ case EvalError:
1284
+ case RangeError:
1285
+ case ReferenceError:
1286
+ case SyntaxError:
1287
+ case TypeError:
1288
+ case URIError:
1289
+ return parseError2(ctx, depth, id, current);
1290
+ case Number:
1291
+ case Boolean:
1292
+ case String:
1293
+ case BigInt:
1294
+ return parseBoxed2(ctx, depth, id, current);
1295
+ case ArrayBuffer:
1296
+ return createArrayBufferNode(ctx.base, id, current);
1297
+ case Int8Array:
1298
+ case Int16Array:
1299
+ case Int32Array:
1300
+ case Uint8Array:
1301
+ case Uint16Array:
1302
+ case Uint32Array:
1303
+ case Uint8ClampedArray:
1304
+ case Float32Array:
1305
+ case Float64Array:
1306
+ return parseTypedArray2(ctx, depth, id, current);
1307
+ case DataView:
1308
+ return parseDataView2(ctx, depth, id, current);
1309
+ case Map:
1310
+ return parseMap2(ctx, depth, id, current);
1311
+ case Set:
1312
+ return parseSet2(ctx, depth, id, current);
1313
+ default:
1314
+ break;
1315
+ }
1316
+ if (currentClass === Promise || current instanceof Promise) {
1317
+ return parsePromise2(ctx, depth, id, current);
1318
+ }
1319
+ const currentFeatures = ctx.base.features;
1320
+ if (currentFeatures & 32 && currentClass === RegExp) {
1321
+ return createRegExpNode(id, current);
1322
+ }
1323
+ if (currentFeatures & 16) {
1324
+ switch (currentClass) {
1325
+ case BigInt64Array:
1326
+ case BigUint64Array:
1327
+ return parseBigIntTypedArray2(ctx, depth, id, current);
1328
+ default:
1329
+ break;
50
1330
  }
51
1331
  }
52
- return parts;
53
- }
54
- function buildLinkParts(links) {
55
- return links.map((link) => `<link ${renderAttrs(link)} />`);
1332
+ if (currentFeatures & 1 && typeof AggregateError !== "undefined" && (currentClass === AggregateError || current instanceof AggregateError)) {
1333
+ return parseAggregateError2(ctx, depth, id, current);
1334
+ }
1335
+ if (current instanceof Error) {
1336
+ return parseError2(ctx, depth, id, current);
1337
+ }
1338
+ if (SYM_ITERATOR in current || SYM_ASYNC_ITERATOR in current) {
1339
+ return parsePlainObject2(ctx, depth, id, current, !!currentClass);
1340
+ }
1341
+ throw new SerovalUnsupportedTypeError(current);
56
1342
  }
57
- function buildScriptParts(scripts) {
58
- return scripts.map((script) => {
59
- const { children, ...rest } = script;
60
- const attrs = renderAttrs(rest);
61
- if (children) {
62
- return `<script ${attrs}>${children}</script>`;
63
- }
64
- return `<script ${attrs}></script>`;
65
- });
1343
+ function parseObject(ctx, depth, id, current) {
1344
+ if (Array.isArray(current)) {
1345
+ return parseArray2(ctx, depth, id, current);
1346
+ }
1347
+ if (isStream(current)) {
1348
+ return parseStream2(ctx, depth, id, current);
1349
+ }
1350
+ if (isSequence(current)) {
1351
+ return parseSequence2(ctx, depth, id, current);
1352
+ }
1353
+ const currentClass = current.constructor;
1354
+ if (currentClass === OpaqueReference) {
1355
+ return parseSOS(ctx, depth, current.replacement);
1356
+ }
1357
+ const parsed = parsePlugin2(ctx, depth, id, current);
1358
+ if (parsed) {
1359
+ return parsed;
1360
+ }
1361
+ return parseObjectPhase2(ctx, depth, id, current, currentClass);
66
1362
  }
67
- function buildStyleParts(styles) {
68
- return styles.map((style) => {
69
- const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
70
- return `<style${typeAttr}>${style.children}</style>`;
71
- });
1363
+ function parseFunction(ctx, depth, current) {
1364
+ const ref = getReferenceNode(ctx.base, current);
1365
+ if (ref.type !== 0) {
1366
+ return ref.value;
1367
+ }
1368
+ const plugin = parsePlugin2(ctx, depth, ref.value, current);
1369
+ if (plugin) {
1370
+ return plugin;
1371
+ }
1372
+ throw new SerovalUnsupportedTypeError(current);
72
1373
  }
73
- function buildHeadInjection(headData) {
74
- const parts = [];
75
- if (headData?.meta) {
76
- parts.push(...buildMetaParts(headData.meta));
1374
+ function parseSOS(ctx, depth, current) {
1375
+ if (depth >= ctx.base.depthLimit) {
1376
+ throw new SerovalDepthLimitError(ctx.base.depthLimit);
77
1377
  }
78
- if (headData?.links) {
79
- parts.push(...buildLinkParts(headData.links));
1378
+ switch (typeof current) {
1379
+ case "boolean":
1380
+ return current ? TRUE_NODE : FALSE_NODE;
1381
+ case "undefined":
1382
+ return UNDEFINED_NODE;
1383
+ case "string":
1384
+ return createStringNode(current);
1385
+ case "number":
1386
+ return createNumberNode(current);
1387
+ case "bigint":
1388
+ return createBigIntNode(current);
1389
+ case "object": {
1390
+ if (current) {
1391
+ const ref = getReferenceNode(ctx.base, current);
1392
+ return ref.type === 0 ? parseObject(ctx, depth + 1, ref.value, current) : ref.value;
1393
+ }
1394
+ return NULL_NODE;
1395
+ }
1396
+ case "symbol":
1397
+ return parseWellKnownSymbol(ctx.base, current);
1398
+ case "function": {
1399
+ return parseFunction(ctx, depth, current);
1400
+ }
1401
+ default:
1402
+ throw new SerovalUnsupportedTypeError(current);
80
1403
  }
81
- if (headData?.scripts) {
82
- parts.push(...buildScriptParts(headData.scripts));
1404
+ }
1405
+ function parseTop(ctx, current) {
1406
+ try {
1407
+ return parseSOS(ctx, 0, current);
1408
+ } catch (error) {
1409
+ throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
83
1410
  }
84
- if (headData?.styles) {
85
- parts.push(...buildStyleParts(headData.styles));
1411
+ }
1412
+ function onParse(ctx, node) {
1413
+ if (ctx.state.initial) {
1414
+ ctx.state.buffer.push(node);
1415
+ } else {
1416
+ onParseInternal(ctx, node, false);
86
1417
  }
87
- return parts.length > 0 ? `
88
- ${parts.join(`
89
- `)}
90
- ` : "";
91
1418
  }
92
- var THEME_INIT_SCRIPT = `<script>try{var __t=localStorage.getItem("furin-theme");` + `document.documentElement.classList.add(__t==="light"?"light":"dark")}` + `catch(e){document.documentElement.classList.add("dark")}</script>`;
93
- function generateIndexHtml() {
94
- return `<!DOCTYPE html>
95
- <html lang="en">
96
- <head>
97
- <meta charset="UTF-8">
98
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
99
- ${THEME_INIT_SCRIPT}
100
- <!--ssr-head-->
101
- </head>
102
- <body>
103
- <div id="root"><!--ssr-outlet--></div>
104
- <script type="module" src="./_hydrate.tsx"></script>
105
- </body>
106
- </html>
107
- `;
1419
+ function onError(ctx, error) {
1420
+ if (ctx.state.onError) {
1421
+ ctx.state.onError(error);
1422
+ } else {
1423
+ throw error instanceof SerovalParserError ? error : new SerovalParserError(error);
1424
+ }
108
1425
  }
109
-
110
- // src/render/assemble.ts
111
- function resolvePath(pattern, params) {
112
- let path = pattern;
113
- for (const [key, val] of Object.entries(params ?? {})) {
114
- path = path.replace(key === "*" ? "*" : `:${key}`, val);
1426
+ function onDone(ctx) {
1427
+ if (ctx.state.onDone) {
1428
+ ctx.state.onDone();
115
1429
  }
116
- return path;
117
1430
  }
118
- async function streamToString(stream) {
119
- const reader = stream.getReader();
120
- const decoder = new TextDecoder;
121
- let html = "";
122
- for (;; ) {
123
- const { done, value } = await reader.read();
124
- if (done) {
125
- break;
126
- }
127
- html += decoder.decode(value, { stream: true });
1431
+ function onParseInternal(ctx, node, initial) {
1432
+ try {
1433
+ ctx.state.onParse(node, initial);
1434
+ } catch (error) {
1435
+ onError(ctx, error);
128
1436
  }
129
- html += decoder.decode();
130
- return html;
131
1437
  }
132
- function splitTemplate(template) {
133
- const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
134
- const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
135
- return { headPre, bodyPre, bodyPost };
1438
+ function pushPendingState(ctx) {
1439
+ ctx.state.pending++;
136
1440
  }
137
- function assembleHTML(template, headData, reactHtml, data) {
138
- const { headPre, bodyPre, bodyPost } = splitTemplate(template);
139
- const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
140
- let injectedBodyPost = bodyPost;
141
- if (dataScript) {
142
- injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${dataScript}</body>`) : bodyPost + dataScript;
1441
+ function popPendingState(ctx) {
1442
+ if (--ctx.state.pending <= 0) {
1443
+ onDone(ctx);
143
1444
  }
144
- return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
145
1445
  }
146
-
147
- // src/render/dev-cache.ts
148
- import { statSync } from "fs";
149
-
150
- // src/render/cache.ts
151
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
1446
+ function parseWithError(ctx, depth, current) {
1447
+ try {
1448
+ return parseSOS(ctx, depth, current);
1449
+ } catch (err) {
1450
+ onError(ctx, err);
1451
+ return NIL;
1452
+ }
1453
+ }
1454
+ function toCrossJSON(source, options = {}) {
1455
+ const plugins = resolvePlugins(options.plugins);
1456
+ const ctx = createSyncParserContext(2, {
1457
+ plugins,
1458
+ disabledFeatures: options.disabledFeatures,
1459
+ refs: options.refs
1460
+ });
1461
+ return parseTop(ctx, source);
1462
+ }
1463
+ async function toCrossJSONAsync(source, options = {}) {
1464
+ const plugins = resolvePlugins(options.plugins);
1465
+ const ctx = createAsyncParserContext(2, {
1466
+ plugins,
1467
+ disabledFeatures: options.disabledFeatures,
1468
+ refs: options.refs
1469
+ });
1470
+ return await parseTopAsync(ctx, source);
1471
+ }
152
1472
 
153
1473
  // src/context-logger.ts
154
1474
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
155
1475
 
156
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/utils.mjs
1476
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/utils.mjs
157
1477
  function formatDuration(ms) {
158
1478
  if (ms < 1000)
159
1479
  return `${Math.round(ms)}ms`;
@@ -241,6 +1561,21 @@ function getCssLevelColor(level) {
241
1561
  function escapeFormatString(str) {
242
1562
  return str.replace(/%/g, "%%");
243
1563
  }
1564
+ var SENSITIVE_HEADERS = [
1565
+ "authorization",
1566
+ "cookie",
1567
+ "set-cookie",
1568
+ "x-api-key",
1569
+ "x-auth-token",
1570
+ "proxy-authorization"
1571
+ ];
1572
+ function filterSafeHeaders(headers) {
1573
+ const safeHeaders = {};
1574
+ for (const [key, value] of Object.entries(headers))
1575
+ if (!SENSITIVE_HEADERS.includes(key.toLowerCase()))
1576
+ safeHeaders[key] = value;
1577
+ return safeHeaders;
1578
+ }
244
1579
  var patternCache = /* @__PURE__ */ new Map;
245
1580
  function matchesPattern(path, pattern) {
246
1581
  let regex = patternCache.get(pattern);
@@ -252,7 +1587,25 @@ function matchesPattern(path, pattern) {
252
1587
  return regex.test(path);
253
1588
  }
254
1589
 
255
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/audit-DQoBo7Dl.mjs
1590
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/headers-CU-QqnYg.mjs
1591
+ function extractSafeHeaders(headers) {
1592
+ const raw = {};
1593
+ headers.forEach((value, key) => {
1594
+ raw[key] = value;
1595
+ });
1596
+ return filterSafeHeaders(raw);
1597
+ }
1598
+ function extractSafeNodeHeaders(headers) {
1599
+ const raw = {};
1600
+ for (const [key, value] of Object.entries(headers)) {
1601
+ if (value === undefined)
1602
+ continue;
1603
+ raw[key] = Array.isArray(value) ? value.join(", ") : value;
1604
+ }
1605
+ return filterSafeHeaders(raw);
1606
+ }
1607
+
1608
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/audit-pV5aLGP0.mjs
256
1609
  var DEFAULT_REPLACEMENT = "[REDACTED]";
257
1610
  var builtinPatterns = {
258
1611
  creditCard: {
@@ -403,6 +1756,117 @@ function applyMaskers(value, maskers) {
403
1756
  }
404
1757
  return result;
405
1758
  }
1759
+ function logPluginError(name, hook, err) {
1760
+ console.error(`[evlog/${name}] ${hook} failed:`, err);
1761
+ }
1762
+ function createPluginRunner(plugins = []) {
1763
+ const byName = /* @__PURE__ */ new Map;
1764
+ for (const plugin of plugins)
1765
+ byName.set(plugin.name, plugin);
1766
+ const list = Array.from(byName.values());
1767
+ return {
1768
+ plugins: list,
1769
+ hasEnrich: list.some((p) => typeof p.enrich === "function"),
1770
+ hasDrain: list.some((p) => typeof p.drain === "function"),
1771
+ hasKeep: list.some((p) => typeof p.keep === "function"),
1772
+ hasRequestLifecycle: list.some((p) => typeof p.onRequestStart === "function" || typeof p.onRequestFinish === "function"),
1773
+ hasClientLog: list.some((p) => typeof p.onClientLog === "function"),
1774
+ hasExtendLogger: list.some((p) => typeof p.extendLogger === "function"),
1775
+ applyExtendLogger(logger) {
1776
+ for (const plugin of list) {
1777
+ if (!plugin.extendLogger)
1778
+ continue;
1779
+ try {
1780
+ plugin.extendLogger(logger);
1781
+ } catch (err) {
1782
+ logPluginError(plugin.name, "extendLogger", err);
1783
+ }
1784
+ }
1785
+ },
1786
+ runOnRequestStart(ctx) {
1787
+ for (const plugin of list) {
1788
+ if (!plugin.onRequestStart)
1789
+ continue;
1790
+ try {
1791
+ plugin.onRequestStart(ctx);
1792
+ } catch (err) {
1793
+ logPluginError(plugin.name, "onRequestStart", err);
1794
+ }
1795
+ }
1796
+ },
1797
+ runOnRequestFinish(ctx) {
1798
+ for (const plugin of list) {
1799
+ if (!plugin.onRequestFinish)
1800
+ continue;
1801
+ try {
1802
+ plugin.onRequestFinish(ctx);
1803
+ } catch (err) {
1804
+ logPluginError(plugin.name, "onRequestFinish", err);
1805
+ }
1806
+ }
1807
+ },
1808
+ async runEnrich(ctx) {
1809
+ for (const plugin of list) {
1810
+ if (!plugin.enrich)
1811
+ continue;
1812
+ try {
1813
+ await plugin.enrich(ctx);
1814
+ } catch (err) {
1815
+ logPluginError(plugin.name, "enrich", err);
1816
+ }
1817
+ }
1818
+ },
1819
+ async runDrain(ctx) {
1820
+ const drains = list.filter((p) => typeof p.drain === "function");
1821
+ if (drains.length === 0)
1822
+ return;
1823
+ await Promise.allSettled(drains.map(async (plugin) => {
1824
+ try {
1825
+ await plugin.drain(ctx);
1826
+ } catch (err) {
1827
+ logPluginError(plugin.name, "drain", err);
1828
+ }
1829
+ }));
1830
+ },
1831
+ async runKeep(ctx) {
1832
+ for (const plugin of list) {
1833
+ if (!plugin.keep)
1834
+ continue;
1835
+ try {
1836
+ await plugin.keep(ctx);
1837
+ } catch (err) {
1838
+ logPluginError(plugin.name, "keep", err);
1839
+ }
1840
+ }
1841
+ },
1842
+ runOnClientLog(ctx) {
1843
+ for (const plugin of list) {
1844
+ if (!plugin.onClientLog)
1845
+ continue;
1846
+ try {
1847
+ plugin.onClientLog(ctx);
1848
+ } catch (err) {
1849
+ logPluginError(plugin.name, "onClientLog", err);
1850
+ }
1851
+ }
1852
+ },
1853
+ async runSetup(ctx) {
1854
+ for (const plugin of list) {
1855
+ if (!plugin.setup)
1856
+ continue;
1857
+ try {
1858
+ await plugin.setup(ctx);
1859
+ } catch (err) {
1860
+ logPluginError(plugin.name, "setup", err);
1861
+ }
1862
+ }
1863
+ }
1864
+ };
1865
+ }
1866
+ var emptyRunner = createPluginRunner([]);
1867
+ function getEmptyPluginRunner() {
1868
+ return emptyRunner;
1869
+ }
406
1870
  function isPlainObject(val) {
407
1871
  return val !== null && typeof val === "object" && !Array.isArray(val);
408
1872
  }
@@ -441,6 +1905,7 @@ var globalRedact;
441
1905
  var globalEnabled = true;
442
1906
  var globalSilent = false;
443
1907
  var globalMinLevel = "debug";
1908
+ var globalPluginRunner = getEmptyPluginRunner();
444
1909
  function initLogger(config = {}) {
445
1910
  globalEnabled = config.enabled ?? true;
446
1911
  const detected = detectEnvironment();
@@ -458,9 +1923,22 @@ function initLogger(config = {}) {
458
1923
  globalRedact = resolveRedactConfig(config.redact ?? !isDev());
459
1924
  globalSilent = config.silent ?? false;
460
1925
  globalMinLevel = config.minLevel ?? "debug";
461
- if (globalSilent && !globalDrain && !config._suppressDrainWarning)
1926
+ globalPluginRunner = config.plugins?.length ? createPluginRunner(config.plugins) : getEmptyPluginRunner();
1927
+ if (globalPluginRunner.plugins.length > 0)
1928
+ globalPluginRunner.runSetup({ env: { ...globalEnv } });
1929
+ const hasAnyDrain = !!globalDrain || globalPluginRunner.hasDrain;
1930
+ if (globalSilent && !hasAnyDrain && !config._suppressDrainWarning)
462
1931
  console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
463
1932
  }
1933
+ function getGlobalPluginRunner() {
1934
+ return globalPluginRunner;
1935
+ }
1936
+ function isEnabled() {
1937
+ return globalEnabled;
1938
+ }
1939
+ function getGlobalDrain() {
1940
+ return globalDrain;
1941
+ }
464
1942
  function shouldSample(level) {
465
1943
  const { rates } = globalSampling;
466
1944
  if (!rates)
@@ -528,12 +2006,20 @@ function emitWideEvent(level, event, options = {}) {
528
2006
  console[getConsoleMethod(level)](JSON.stringify(formatted));
529
2007
  else
530
2008
  console[getConsoleMethod(level)](formatted);
531
- if (globalDrain && !deferDrain) {
532
- const drainPromise = Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
533
- console.error("[evlog] drain failed:", err);
534
- });
535
- if (waitUntil)
536
- waitUntil(drainPromise);
2009
+ if (!deferDrain) {
2010
+ const drainPromises = [];
2011
+ if (globalDrain)
2012
+ drainPromises.push((async () => {
2013
+ try {
2014
+ await globalDrain({ event: formatted });
2015
+ } catch (err) {
2016
+ console.error("[evlog] drain failed:", err);
2017
+ }
2018
+ })());
2019
+ if (globalPluginRunner.hasDrain)
2020
+ drainPromises.push(globalPluginRunner.runDrain({ event: formatted }));
2021
+ if (drainPromises.length > 0 && waitUntil)
2022
+ waitUntil(Promise.all(drainPromises));
537
2023
  }
538
2024
  return formatted;
539
2025
  }
@@ -902,6 +2388,7 @@ function createLogger(initialContext = {}, internalOptions) {
902
2388
  };
903
2389
  const errRecord = err;
904
2390
  for (const k of [
2391
+ "code",
905
2392
  "status",
906
2393
  "statusText",
907
2394
  "statusCode",
@@ -984,6 +2471,20 @@ function createLogger(initialContext = {}, internalOptions) {
984
2471
  }
985
2472
  };
986
2473
  }
2474
+ function createRequestLogger(options = {}, internalOptions) {
2475
+ const { method, path, requestId, waitUntil: optionsWaitUntil } = options;
2476
+ const initial = {};
2477
+ if (method !== undefined)
2478
+ initial.method = method;
2479
+ if (path !== undefined)
2480
+ initial.path = path;
2481
+ if (requestId !== undefined)
2482
+ initial.requestId = requestId;
2483
+ return createLogger(initial, {
2484
+ ...internalOptions,
2485
+ waitUntil: internalOptions?.waitUntil ?? optionsWaitUntil
2486
+ });
2487
+ }
987
2488
  if (typeof __EVLOG_CONFIG__ !== "undefined")
988
2489
  initLogger(__EVLOG_CONFIG__);
989
2490
  function stableStringify(value) {
@@ -1024,51 +2525,357 @@ function computeIdempotencyKey(audit, timestamp) {
1024
2525
  }
1025
2526
  function buildAuditFields(input) {
1026
2527
  return {
1027
- action: input.action,
1028
- actor: input.actor,
1029
- target: input.target,
1030
- outcome: input.outcome ?? "success",
1031
- reason: input.reason,
1032
- changes: input.changes,
1033
- causationId: input.causationId,
1034
- correlationId: input.correlationId,
1035
- version: input.version ?? 1
2528
+ action: input.action,
2529
+ actor: input.actor,
2530
+ target: input.target,
2531
+ outcome: input.outcome ?? "success",
2532
+ reason: input.reason,
2533
+ changes: input.changes,
2534
+ causationId: input.causationId,
2535
+ correlationId: input.correlationId,
2536
+ version: input.version ?? 1
2537
+ };
2538
+ }
2539
+ function decorateAudit(audit, timestamp) {
2540
+ if (audit.idempotencyKey)
2541
+ return audit;
2542
+ return {
2543
+ ...audit,
2544
+ idempotencyKey: computeIdempotencyKey(audit, timestamp)
2545
+ };
2546
+ }
2547
+ function consumeAuditForceKeep(context) {
2548
+ if (context._auditForceKeep) {
2549
+ delete context._auditForceKeep;
2550
+ return true;
2551
+ }
2552
+ if (context.audit)
2553
+ return true;
2554
+ return false;
2555
+ }
2556
+ function finalizeAudit(event) {
2557
+ const a = event.audit;
2558
+ if (!a)
2559
+ return;
2560
+ event.audit = decorateAudit(a, String(event.timestamp));
2561
+ }
2562
+
2563
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/errors-BQgyQ9xe.mjs
2564
+ function extractErrorStatus(error) {
2565
+ if (error === null || typeof error !== "object")
2566
+ return 500;
2567
+ const raw = error.status ?? error.statusCode;
2568
+ const status = Number(raw);
2569
+ return Number.isFinite(status) ? status : 500;
2570
+ }
2571
+
2572
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/routes-CnIgYWf8.mjs
2573
+ function shouldLog(path, include, exclude) {
2574
+ if (exclude && exclude.length > 0) {
2575
+ if (exclude.some((pattern) => matchesPattern(path, pattern)))
2576
+ return false;
2577
+ }
2578
+ if (!include || include.length === 0)
2579
+ return true;
2580
+ return include.some((pattern) => matchesPattern(path, pattern));
2581
+ }
2582
+ function getServiceForPath(path, routes) {
2583
+ if (!routes)
2584
+ return;
2585
+ for (const [pattern, config] of Object.entries(routes))
2586
+ if (matchesPattern(path, pattern))
2587
+ return config.service;
2588
+ }
2589
+
2590
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/fork-8u_zFOJq.mjs
2591
+ var noopResult = {
2592
+ logger: {
2593
+ set() {},
2594
+ error() {},
2595
+ info() {},
2596
+ warn() {},
2597
+ emit() {
2598
+ return null;
2599
+ },
2600
+ getContext() {
2601
+ return {};
2602
+ }
2603
+ },
2604
+ finish: () => Promise.resolve(null),
2605
+ skipped: true
2606
+ };
2607
+ var runnerCache = /* @__PURE__ */ new WeakMap;
2608
+ function resolveMiddlewarePluginRunner(options) {
2609
+ const global2 = getGlobalPluginRunner();
2610
+ const local = options.plugins;
2611
+ if (!local || local.length === 0)
2612
+ return global2;
2613
+ const cached = runnerCache.get(local);
2614
+ if (cached && cached.global === global2)
2615
+ return cached.merged;
2616
+ const merged = /* @__PURE__ */ new Map;
2617
+ for (const plugin of global2.plugins)
2618
+ merged.set(plugin.name, plugin);
2619
+ for (const plugin of local)
2620
+ merged.set(plugin.name, plugin);
2621
+ if (merged.size === 0)
2622
+ return getEmptyPluginRunner();
2623
+ const runner = createPluginRunner(Array.from(merged.values()));
2624
+ runnerCache.set(local, {
2625
+ global: global2,
2626
+ merged: runner
2627
+ });
2628
+ return runner;
2629
+ }
2630
+ async function runEnrichAndDrain(emittedEvent, options, requestInfo, responseStatus, plugins) {
2631
+ const runner = plugins ?? resolveMiddlewarePluginRunner(options);
2632
+ const resolvedRedact = resolveRedactConfig(options.redact);
2633
+ if (resolvedRedact)
2634
+ redactEvent(emittedEvent, resolvedRedact);
2635
+ if (options.enrich || runner.hasEnrich) {
2636
+ const enrichCtx = {
2637
+ event: emittedEvent,
2638
+ request: requestInfo,
2639
+ headers: options.headers,
2640
+ response: { status: responseStatus }
2641
+ };
2642
+ if (options.enrich)
2643
+ try {
2644
+ await options.enrich(enrichCtx);
2645
+ } catch (err) {
2646
+ console.error("[evlog] enrich failed:", err);
2647
+ }
2648
+ if (runner.hasEnrich)
2649
+ await runner.runEnrich(enrichCtx);
2650
+ }
2651
+ const drain = options.drain ?? getGlobalDrain();
2652
+ const hasUserDrain = !!drain;
2653
+ const hasPluginDrain = runner.hasDrain;
2654
+ if (hasUserDrain || hasPluginDrain) {
2655
+ const drainCtx = {
2656
+ event: emittedEvent,
2657
+ request: requestInfo,
2658
+ headers: options.headers
2659
+ };
2660
+ const tasks = [];
2661
+ if (hasUserDrain)
2662
+ tasks.push((async () => {
2663
+ try {
2664
+ await drain(drainCtx);
2665
+ } catch (err) {
2666
+ console.error("[evlog] drain failed:", err);
2667
+ }
2668
+ })());
2669
+ if (hasPluginDrain)
2670
+ tasks.push(runner.runDrain(drainCtx));
2671
+ await Promise.all(tasks);
2672
+ }
2673
+ }
2674
+ function createMiddlewareLogger(options) {
2675
+ if (!isEnabled())
2676
+ return noopResult;
2677
+ const { method, path, requestId, include, exclude, routes, keep } = options;
2678
+ if (!shouldLog(path, include, exclude))
2679
+ return noopResult;
2680
+ const resolvedRequestId = requestId || crypto.randomUUID();
2681
+ const logger = createRequestLogger({
2682
+ method,
2683
+ path,
2684
+ requestId: resolvedRequestId
2685
+ }, { _deferDrain: true });
2686
+ const routeService = getServiceForPath(path, routes);
2687
+ if (routeService)
2688
+ logger.set({ service: routeService });
2689
+ const pluginRunner = resolveMiddlewarePluginRunner(options);
2690
+ if (pluginRunner.hasExtendLogger)
2691
+ pluginRunner.applyExtendLogger(logger);
2692
+ const startTime = Date.now();
2693
+ const requestInfo = {
2694
+ method,
2695
+ path,
2696
+ requestId: resolvedRequestId
2697
+ };
2698
+ if (pluginRunner.hasRequestLifecycle)
2699
+ pluginRunner.runOnRequestStart({
2700
+ logger,
2701
+ request: requestInfo,
2702
+ headers: options.headers
2703
+ });
2704
+ const finish = async (opts) => {
2705
+ const { status, error } = opts ?? {};
2706
+ if (error) {
2707
+ logger.error(error);
2708
+ const errorStatus = extractErrorStatus(error);
2709
+ logger.set({ status: errorStatus });
2710
+ } else if (status !== undefined)
2711
+ logger.set({ status });
2712
+ const durationMs = Date.now() - startTime;
2713
+ const resolvedStatus = error ? extractErrorStatus(error) : status ?? logger.getContext().status;
2714
+ const tailCtx = {
2715
+ status: resolvedStatus,
2716
+ duration: durationMs,
2717
+ path,
2718
+ method,
2719
+ context: logger.getContext(),
2720
+ shouldKeep: false
2721
+ };
2722
+ if (keep)
2723
+ await keep(tailCtx);
2724
+ if (pluginRunner.hasKeep)
2725
+ await pluginRunner.runKeep(tailCtx);
2726
+ const forceKeep = tailCtx.shouldKeep || shouldKeep(tailCtx);
2727
+ const emittedEvent = logger.emit({ _forceKeep: forceKeep });
2728
+ if (emittedEvent && (options.enrich || options.drain || pluginRunner.hasEnrich || pluginRunner.hasDrain || getGlobalDrain()))
2729
+ await runEnrichAndDrain(emittedEvent, options, requestInfo, resolvedStatus, pluginRunner);
2730
+ if (pluginRunner.hasRequestLifecycle)
2731
+ pluginRunner.runOnRequestFinish({
2732
+ logger,
2733
+ request: requestInfo,
2734
+ headers: options.headers,
2735
+ event: emittedEvent,
2736
+ status: resolvedStatus,
2737
+ durationMs,
2738
+ error
2739
+ });
2740
+ return emittedEvent;
2741
+ };
2742
+ return {
2743
+ logger,
2744
+ finish,
2745
+ skipped: false
1036
2746
  };
1037
2747
  }
1038
- function decorateAudit(audit, timestamp) {
1039
- if (audit.idempotencyKey)
1040
- return audit;
1041
- return {
1042
- ...audit,
1043
- idempotencyKey: computeIdempotencyKey(audit, timestamp)
2748
+ function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
2749
+ const log = parent;
2750
+ log.fork = (label, fn) => {
2751
+ forkBackgroundLogger({
2752
+ storage,
2753
+ parent,
2754
+ middlewareOptions,
2755
+ label,
2756
+ fn,
2757
+ lifecycle
2758
+ });
1044
2759
  };
1045
2760
  }
1046
- function consumeAuditForceKeep(context) {
1047
- if (context._auditForceKeep) {
1048
- delete context._auditForceKeep;
1049
- return true;
1050
- }
1051
- if (context.audit)
1052
- return true;
1053
- return false;
2761
+ function forkBackgroundLogger(options) {
2762
+ const { storage, parent, middlewareOptions, label, fn, lifecycle } = options;
2763
+ const parentCtx = parent.getContext();
2764
+ const parentRequestId = parentCtx.requestId;
2765
+ if (typeof parentRequestId !== "string" || parentRequestId.length === 0)
2766
+ throw new Error("[evlog] log.fork() requires the parent logger to have a requestId. Ensure the request was created by evlog middleware.");
2767
+ const method = String(parentCtx.method ?? middlewareOptions.method);
2768
+ const path = String(parentCtx.path ?? middlewareOptions.path);
2769
+ const child = createRequestLogger({
2770
+ method,
2771
+ path,
2772
+ requestId: crypto.randomUUID()
2773
+ }, { _deferDrain: true });
2774
+ child.set({
2775
+ operation: label,
2776
+ _parentRequestId: parentRequestId
2777
+ });
2778
+ const childRequestInfo = {
2779
+ method,
2780
+ path,
2781
+ requestId: child.getContext().requestId
2782
+ };
2783
+ storage.run(child, () => {
2784
+ lifecycle?.onChildEnter?.(child);
2785
+ Promise.resolve().then(() => fn()).then(async () => {
2786
+ const emittedEvent = child.emit();
2787
+ const ctxStatus = child.getContext().status;
2788
+ const status = emittedEvent?.status ?? (typeof ctxStatus === "number" ? ctxStatus : undefined);
2789
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2790
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2791
+ }).catch(async (err) => {
2792
+ const error = err instanceof Error ? err : new Error(String(err));
2793
+ child.error(error);
2794
+ child.set({ status: extractErrorStatus(error) });
2795
+ const emittedEvent = child.emit();
2796
+ const status = extractErrorStatus(error);
2797
+ if (emittedEvent && (middlewareOptions.enrich || middlewareOptions.drain || getGlobalDrain()))
2798
+ await runEnrichAndDrain(emittedEvent, middlewareOptions, childRequestInfo, status);
2799
+ }).finally(() => {
2800
+ lifecycle?.onChildExit?.(child);
2801
+ });
2802
+ });
1054
2803
  }
1055
- function finalizeAudit(event) {
1056
- const a = event.audit;
1057
- if (!a)
2804
+
2805
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/integration-DTZtjSqh.mjs
2806
+ function normalizeHeaders(headers) {
2807
+ if (!headers)
1058
2808
  return;
1059
- event.audit = decorateAudit(a, String(event.timestamp));
2809
+ if (typeof headers.forEach === "function" && typeof headers.get === "function")
2810
+ return extractSafeHeaders(headers);
2811
+ return extractSafeNodeHeaders(headers);
2812
+ }
2813
+ function defineFrameworkIntegration(spec) {
2814
+ return { start(ctx, options = {}) {
2815
+ const extracted = spec.extractRequest(ctx);
2816
+ const headers = normalizeHeaders(extracted.headers);
2817
+ const middlewareOptions = {
2818
+ method: extracted.method,
2819
+ path: extracted.path,
2820
+ requestId: extracted.requestId || crypto.randomUUID(),
2821
+ headers,
2822
+ ...options
2823
+ };
2824
+ const result = createMiddlewareLogger(middlewareOptions);
2825
+ if (!result.skipped) {
2826
+ if (spec.storage)
2827
+ attachForkToLogger(spec.storage, result.logger, middlewareOptions, spec.forkLifecycle);
2828
+ spec.attachLogger(ctx, result.logger);
2829
+ }
2830
+ const { storage } = spec;
2831
+ const runWith = async (fn) => {
2832
+ if (!storage || result.skipped)
2833
+ return await fn();
2834
+ return await storage.run(result.logger, fn);
2835
+ };
2836
+ return {
2837
+ ...result,
2838
+ middlewareOptions,
2839
+ runWith
2840
+ };
2841
+ } };
1060
2842
  }
1061
- // ../../node_modules/.bun/evlog@2.14.1+6b630eaba8c4f70c/node_modules/evlog/dist/elysia/index.mjs
2843
+
2844
+ // ../../node_modules/.bun/evlog@2.17.0+f5a9d28f69418da1/node_modules/evlog/dist/elysia/index.mjs
1062
2845
  import { AsyncLocalStorage } from "async_hooks";
1063
2846
  import { Elysia } from "elysia";
1064
2847
  var storage = new AsyncLocalStorage;
1065
2848
  var activeLoggers = /* @__PURE__ */ new WeakSet;
1066
- function useLogger2() {
2849
+ function useLogger() {
1067
2850
  const logger = storage.getStore();
1068
2851
  if (!logger || !activeLoggers.has(logger))
1069
2852
  throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
1070
2853
  return logger;
1071
2854
  }
2855
+ var integration = defineFrameworkIntegration({
2856
+ name: "elysia",
2857
+ extractRequest: ({ request, path, headers }) => ({
2858
+ method: request.method,
2859
+ path,
2860
+ headers,
2861
+ requestId: headers["x-request-id"]
2862
+ }),
2863
+ attachLogger: ({ request, path, headers }, logger) => {
2864
+ attachForkToLogger(storage, logger, {
2865
+ method: request.method,
2866
+ path,
2867
+ requestId: headers["x-request-id"]
2868
+ }, {
2869
+ onChildEnter: (child) => {
2870
+ activeLoggers.add(child);
2871
+ },
2872
+ onChildExit: (child) => {
2873
+ activeLoggers.delete(child);
2874
+ }
2875
+ });
2876
+ activeLoggers.add(logger);
2877
+ }
2878
+ });
1072
2879
 
1073
2880
  // src/context-logger.ts
1074
2881
  var noopLogger2 = {
@@ -1081,9 +2888,9 @@ var noopLogger2 = {
1081
2888
  fork: (_label, fn) => fn()
1082
2889
  };
1083
2890
  var syntheticRenderStorage = new AsyncLocalStorage2;
1084
- function useLogger3() {
2891
+ function useLogger2() {
1085
2892
  try {
1086
- return useLogger2();
2893
+ return useLogger();
1087
2894
  } catch {
1088
2895
  return syntheticRenderStorage.getStore() ?? noopLogger2;
1089
2896
  }
@@ -1101,6 +2908,186 @@ async function runInSyntheticRenderScope(fn, initialContext) {
1101
2908
  }
1102
2909
  }
1103
2910
 
2911
+ // src/internal.ts
2912
+ var _compileCtx = null;
2913
+ function getCompileContext() {
2914
+ return _compileCtx;
2915
+ }
2916
+
2917
+ // src/render/shell.ts
2918
+ function extractTitle(meta) {
2919
+ if (!meta) {
2920
+ return;
2921
+ }
2922
+ for (const entry of meta) {
2923
+ if ("title" in entry) {
2924
+ return entry.title;
2925
+ }
2926
+ }
2927
+ return;
2928
+ }
2929
+ function isMetaTag(entry) {
2930
+ return !(("title" in entry) || ("charSet" in entry) || ("script:ld+json" in entry) || ("tagName" in entry));
2931
+ }
2932
+ function escapeHtml(str) {
2933
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
2934
+ }
2935
+ function safeJson(value) {
2936
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
2937
+ }
2938
+ function renderAttrs(obj) {
2939
+ const parts = [];
2940
+ for (const [k, v] of Object.entries(obj)) {
2941
+ if (v !== undefined) {
2942
+ parts.push(`${k}="${escapeHtml(String(v))}"`);
2943
+ }
2944
+ }
2945
+ return parts.join(" ");
2946
+ }
2947
+ function buildMetaParts(meta) {
2948
+ const parts = [];
2949
+ const title = extractTitle(meta);
2950
+ if (title) {
2951
+ parts.push(`<title>${escapeHtml(title)}</title>`);
2952
+ }
2953
+ for (const m of meta) {
2954
+ if (isMetaTag(m)) {
2955
+ parts.push(`<meta ${renderAttrs(m)} />`);
2956
+ }
2957
+ if ("script:ld+json" in m) {
2958
+ parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
2959
+ }
2960
+ }
2961
+ return parts;
2962
+ }
2963
+ function buildLinkParts(links) {
2964
+ return links.map((link) => `<link ${renderAttrs(link)} />`);
2965
+ }
2966
+ function buildScriptParts(scripts) {
2967
+ return scripts.map((script) => {
2968
+ const { children, ...rest } = script;
2969
+ const attrs = renderAttrs(rest);
2970
+ if (children) {
2971
+ return `<script ${attrs}>${children}</script>`;
2972
+ }
2973
+ return `<script ${attrs}></script>`;
2974
+ });
2975
+ }
2976
+ function buildStyleParts(styles) {
2977
+ return styles.map((style) => {
2978
+ const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
2979
+ return `<style${typeAttr}>${style.children}</style>`;
2980
+ });
2981
+ }
2982
+ function buildHeadInjection(headData) {
2983
+ const parts = [];
2984
+ if (headData?.meta) {
2985
+ parts.push(...buildMetaParts(headData.meta));
2986
+ }
2987
+ if (headData?.links) {
2988
+ parts.push(...buildLinkParts(headData.links));
2989
+ }
2990
+ if (headData?.scripts) {
2991
+ parts.push(...buildScriptParts(headData.scripts));
2992
+ }
2993
+ if (headData?.styles) {
2994
+ parts.push(...buildStyleParts(headData.styles));
2995
+ }
2996
+ return parts.length > 0 ? `
2997
+ ${parts.join(`
2998
+ `)}
2999
+ ` : "";
3000
+ }
3001
+ var THEME_INIT_SCRIPT = `<script>try{var __t=localStorage.getItem("furin-theme");` + `document.documentElement.classList.add(__t==="light"?"light":"dark")}` + `catch(e){document.documentElement.classList.add("dark")}</script>`;
3002
+ function generateIndexHtml() {
3003
+ return `<!DOCTYPE html>
3004
+ <html lang="en">
3005
+ <head>
3006
+ <meta charset="UTF-8">
3007
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
3008
+ ${THEME_INIT_SCRIPT}
3009
+ <!--ssr-head-->
3010
+ </head>
3011
+ <body>
3012
+ <div id="root"><!--ssr-outlet--></div>
3013
+ <script type="module" src="./_hydrate.tsx"></script>
3014
+ </body>
3015
+ </html>
3016
+ `;
3017
+ }
3018
+
3019
+ // src/render/assemble.ts
3020
+ var FURIN_DEFERRED_GLOBAL = "__FURIN_DEFERRED__";
3021
+ function buildDeferredScript(deferredKeys) {
3022
+ const keysJson = safeJson(deferredKeys);
3023
+ return `<script id="${FURIN_DEFERRED_GLOBAL}">
3024
+ window.${FURIN_DEFERRED_GLOBAL} = {
3025
+ _deferredKeys: ${keysJson},
3026
+ _chunks: {},
3027
+ _resolvers: {},
3028
+ resolve(key, chunk) {
3029
+ this._chunks[key] = { a: 0, v: chunk };
3030
+ },
3031
+ reject(key, chunk) {
3032
+ this._chunks[key] = { a: 1, v: chunk };
3033
+ },
3034
+ getPromise(key) {
3035
+ if (!this._resolvers[key]) {
3036
+ var res, rej;
3037
+ var p = new Promise(function(resolve, reject) { res = resolve; rej = reject; });
3038
+ this._resolvers[key] = { resolve: res, reject: rej, promise: p };
3039
+ }
3040
+ return this._resolvers[key].promise;
3041
+ }
3042
+ };
3043
+ </script>`;
3044
+ }
3045
+ function buildDeferredResolution(key, chunk, action) {
3046
+ const chunkJson = safeJson(chunk);
3047
+ return `<script>window.${FURIN_DEFERRED_GLOBAL}.${action}(${safeJson(key)},${chunkJson})</script>`;
3048
+ }
3049
+ function resolvePath(pattern, params) {
3050
+ let path = pattern;
3051
+ for (const [key, val] of Object.entries(params ?? {})) {
3052
+ path = path.replace(key === "*" ? "*" : `:${key}`, val);
3053
+ }
3054
+ return path;
3055
+ }
3056
+ async function streamToString(stream) {
3057
+ const reader = stream.getReader();
3058
+ const decoder = new TextDecoder;
3059
+ let html = "";
3060
+ for (;; ) {
3061
+ const { done, value } = await reader.read();
3062
+ if (done) {
3063
+ break;
3064
+ }
3065
+ html += decoder.decode(value, { stream: true });
3066
+ }
3067
+ html += decoder.decode();
3068
+ return html;
3069
+ }
3070
+ function splitTemplate(template) {
3071
+ const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
3072
+ const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
3073
+ return { headPre, bodyPre, bodyPost };
3074
+ }
3075
+ function assembleHTML(template, headData, reactHtml, data) {
3076
+ const { headPre, bodyPre, bodyPost } = splitTemplate(template);
3077
+ const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
3078
+ let injectedBodyPost = bodyPost;
3079
+ if (dataScript) {
3080
+ injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${dataScript}</body>`) : bodyPost + dataScript;
3081
+ }
3082
+ return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
3083
+ }
3084
+
3085
+ // src/render/dev-cache.ts
3086
+ import { statSync } from "fs";
3087
+
3088
+ // src/render/cache.ts
3089
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3090
+
1104
3091
  // src/render/route-cache.ts
1105
3092
  function defaultPathFromKey(key) {
1106
3093
  return key;
@@ -1329,6 +3316,41 @@ function isDevLoaderCacheValid(entry) {
1329
3316
  return true;
1330
3317
  }
1331
3318
 
3319
+ // src/render/digest.ts
3320
+ function computeErrorDigest(err) {
3321
+ let message = "";
3322
+ let stack = "";
3323
+ if (err instanceof Error) {
3324
+ message = err.message;
3325
+ stack = err.stack ?? "";
3326
+ } else if (typeof err === "string") {
3327
+ message = err;
3328
+ } else {
3329
+ try {
3330
+ message = JSON.stringify(err) ?? String(err);
3331
+ } catch {
3332
+ message = String(err);
3333
+ }
3334
+ }
3335
+ const input = `${message}
3336
+ ${stack}`;
3337
+ const hash = cyrb53(input);
3338
+ const hex = hash.toString(16).padStart(14, "0");
3339
+ return hex.slice(0, 10);
3340
+ }
3341
+ function cyrb53(input) {
3342
+ let h1 = 3735928559;
3343
+ let h2 = 1103547991;
3344
+ for (let i = 0;i < input.length; i++) {
3345
+ const ch = input.charCodeAt(i);
3346
+ h1 = Math.imul(h1 ^ ch, 2654435761);
3347
+ h2 = Math.imul(h2 ^ ch, 1597334677);
3348
+ }
3349
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
3350
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
3351
+ return 4294967296 * (2097151 & h2) + (4294967295 & h1);
3352
+ }
3353
+
1332
3354
  // src/render/index.ts
1333
3355
  import { createElement as createElement3 } from "react";
1334
3356
  import { renderToReadableStream } from "react-dom/server";
@@ -1367,12 +3389,29 @@ import { Component, Fragment } from "react";
1367
3389
  // src/error.ts
1368
3390
  function getPublicErrorMessage(error) {
1369
3391
  const branded = error;
1370
- if (branded?.__furinBrand === "FURIN_NOT_FOUND") {
3392
+ if (branded?.__furinBrand === "FURIN_NOT_FOUND" || branded?.__furinBrand === "FURIN_SERVER_ERROR") {
1371
3393
  return error.message;
1372
3394
  }
1373
3395
  return "Something went wrong";
1374
3396
  }
1375
3397
 
3398
+ // src/server-error.ts
3399
+ var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
3400
+
3401
+ class FurinServerError extends Error {
3402
+ __furinBrand = SERVER_ERROR_BRAND;
3403
+ digest;
3404
+ status;
3405
+ constructor(args) {
3406
+ super(args.message);
3407
+ this.status = args.status;
3408
+ this.digest = args.digest;
3409
+ }
3410
+ }
3411
+ function isFurinServerError(err) {
3412
+ return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
3413
+ }
3414
+
1376
3415
  // src/link.tsx
1377
3416
  import { createElement, useCallback, useEffect, useRef } from "react";
1378
3417
  function computeLinkView({
@@ -1422,9 +3461,10 @@ function LinkInteractive({
1422
3461
  const effectivePreload = preload ?? router.defaultPreload;
1423
3462
  const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
1424
3463
  const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
3464
+ const { prefetch } = router;
1425
3465
  const triggerPrefetch = useCallback(() => {
1426
- router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
1427
- }, [router, logicalHref, effectiveStaleTime]);
3466
+ prefetch(logicalHref, { staleTime: effectiveStaleTime });
3467
+ }, [prefetch, logicalHref, effectiveStaleTime]);
1428
3468
  useEffect(() => {
1429
3469
  if (effectivePreload === "render") {
1430
3470
  triggerPrefetch();
@@ -1475,6 +3515,10 @@ function LinkInteractive({
1475
3515
  return;
1476
3516
  }
1477
3517
  e.preventDefault();
3518
+ if (typeof window !== "undefined" && router.navigate === SSR_FALLBACK_ROUTER.navigate) {
3519
+ window.location.href = href;
3520
+ return;
3521
+ }
1478
3522
  router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
1479
3523
  };
1480
3524
  const handleMouseEnter = (e) => {
@@ -1635,12 +3679,7 @@ var BADGE_STYLE = {
1635
3679
  fontWeight: 600,
1636
3680
  letterSpacing: "0.08em",
1637
3681
  marginBottom: "16px",
1638
- padding: "12px 36px"
1639
- };
1640
- var NOT_FOUND_BADGE_STYLE = {
1641
- ...BADGE_STYLE,
1642
- border: 0,
1643
- padding: 0
3682
+ padding: "12px 36px"
1644
3683
  };
1645
3684
  var HEADING_STYLE = {
1646
3685
  color: COLOR_TEXT,
@@ -1729,7 +3768,7 @@ function ScreenFrame({ badge, children }) {
1729
3768
  style: PAGE_STYLE,
1730
3769
  children: [
1731
3770
  /* @__PURE__ */ jsxDEV("style", {
1732
- dangerouslySetInnerHTML: { __html: RESET_CSS }
3771
+ children: RESET_CSS
1733
3772
  }, undefined, false, undefined, this),
1734
3773
  /* @__PURE__ */ jsxDEV("div", {
1735
3774
  style: FRAME_STYLE,
@@ -1810,7 +3849,7 @@ function DefaultErrorScreen({ message, digest, reset }) {
1810
3849
  function DefaultNotFoundScreen({ message }) {
1811
3850
  return /* @__PURE__ */ jsxDEV(ScreenFrame, {
1812
3851
  badge: /* @__PURE__ */ jsxDEV("div", {
1813
- style: NOT_FOUND_BADGE_STYLE,
3852
+ style: BADGE_STYLE,
1814
3853
  children: "404 \u2014 NOT FOUND"
1815
3854
  }, undefined, false, undefined, this),
1816
3855
  children: [
@@ -1834,41 +3873,6 @@ function DefaultNotFoundScreen({ message }) {
1834
3873
  }, undefined, true, undefined, this);
1835
3874
  }
1836
3875
 
1837
- // src/render/digest.ts
1838
- function computeErrorDigest(err) {
1839
- let message = "";
1840
- let stack = "";
1841
- if (err instanceof Error) {
1842
- message = err.message;
1843
- stack = err.stack ?? "";
1844
- } else if (typeof err === "string") {
1845
- message = err;
1846
- } else {
1847
- try {
1848
- message = JSON.stringify(err) ?? String(err);
1849
- } catch {
1850
- message = String(err);
1851
- }
1852
- }
1853
- const input = `${message}
1854
- ${stack}`;
1855
- const hash = cyrb53(input);
1856
- const hex = hash.toString(16).padStart(14, "0");
1857
- return hex.slice(0, 10);
1858
- }
1859
- function cyrb53(input) {
1860
- let h1 = 3735928559;
1861
- let h2 = 1103547991;
1862
- for (let i = 0;i < input.length; i++) {
1863
- const ch = input.charCodeAt(i);
1864
- h1 = Math.imul(h1 ^ ch, 2654435761);
1865
- h2 = Math.imul(h2 ^ ch, 1597334677);
1866
- }
1867
- h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1868
- h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1869
- return 4294967296 * (2097151 & h2) + (4294967295 & h1);
1870
- }
1871
-
1872
3876
  // src/render/boundaries.tsx
1873
3877
  import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
1874
3878
  var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV2(DefaultErrorScreen, {
@@ -1876,6 +3880,7 @@ var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV2(Default
1876
3880
  message: error.message,
1877
3881
  reset
1878
3882
  }, undefined, false, undefined, this);
3883
+ var DEFAULT_ERROR_STATUS = 500;
1879
3884
  var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV2(DefaultNotFoundScreen, {
1880
3885
  message: error.message
1881
3886
  }, undefined, false, undefined, this);
@@ -1907,10 +3912,12 @@ class FurinErrorBoundary extends Component {
1907
3912
  throw error;
1908
3913
  }
1909
3914
  const Fallback = this.props.fallback ?? DefaultErrorFallback;
1910
- const finalDigest = digest ?? this.props.digest ?? computeErrorDigest(error);
3915
+ const serverDigest = isFurinServerError(error) ? error.digest : undefined;
3916
+ const finalDigest = serverDigest ?? digest ?? this.props.digest ?? computeErrorDigest(error);
1911
3917
  const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
3918
+ const status = isFurinServerError(error) ? error.status : DEFAULT_ERROR_STATUS;
1912
3919
  return /* @__PURE__ */ jsxDEV2(Fallback, {
1913
- error: { message, digest: finalDigest },
3920
+ error: { message, digest: finalDigest, status },
1914
3921
  reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
1915
3922
  }, undefined, false, undefined, this);
1916
3923
  }
@@ -1999,6 +4006,65 @@ function normalizeHref(href) {
1999
4006
  return pathname + url.search + url.hash;
2000
4007
  }
2001
4008
 
4009
+ // src/utils.ts
4010
+ function isFurinPage(value) {
4011
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
4012
+ }
4013
+ function isFurinRoute(value) {
4014
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
4015
+ }
4016
+ function collectRouteChainFromRoute(route) {
4017
+ const chain = [];
4018
+ let current = route;
4019
+ while (current) {
4020
+ chain.unshift(current);
4021
+ current = current.parent;
4022
+ }
4023
+ return chain;
4024
+ }
4025
+ function hasCycle(route) {
4026
+ const visited = new Set;
4027
+ let current = route;
4028
+ while (current) {
4029
+ if (visited.has(current)) {
4030
+ return true;
4031
+ }
4032
+ visited.add(current);
4033
+ current = current.parent;
4034
+ }
4035
+ return false;
4036
+ }
4037
+ async function mapWithConcurrency(items, concurrency, fn) {
4038
+ if (items.length === 0) {
4039
+ return [];
4040
+ }
4041
+ const results = new Array(items.length);
4042
+ let cursor = 0;
4043
+ const workerCount = Math.min(Math.max(concurrency, 1), items.length);
4044
+ await Promise.all(Array.from({ length: workerCount }, async () => {
4045
+ while (true) {
4046
+ const index = cursor++;
4047
+ if (index >= items.length) {
4048
+ return;
4049
+ }
4050
+ results[index] = await fn(items[index], index);
4051
+ }
4052
+ }));
4053
+ return results;
4054
+ }
4055
+ function validateRouteChain(chain, root, pagePath) {
4056
+ const hasRoot = chain.some((r) => r === root);
4057
+ if (!hasRoot) {
4058
+ const location = pagePath ? `in ${pagePath}` : "";
4059
+ throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
4060
+ }
4061
+ for (const route of chain) {
4062
+ if (hasCycle(route)) {
4063
+ throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
4064
+ }
4065
+ }
4066
+ }
4067
+
2002
4068
  // src/render/element.tsx
2003
4069
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
2004
4070
  function wrapInBoundaries(inner, segment) {
@@ -2074,16 +4140,42 @@ function errorMessageOf(err) {
2074
4140
  return "";
2075
4141
  }
2076
4142
  var SERVER_RESET_NOOP2 = () => {};
2077
- function buildErrorElement(component, error, digest) {
4143
+ function buildErrorElement(component, error, digest, messageOverride, status) {
2078
4144
  const ErrorView = component ?? DefaultErrorComponent;
2079
- const message = component ? errorMessageOf(error) : "An unexpected error occurred.";
4145
+ let message;
4146
+ if (component) {
4147
+ message = messageOverride ?? errorMessageOf(error);
4148
+ } else {
4149
+ message = "An unexpected error occurred.";
4150
+ }
2080
4151
  return /* @__PURE__ */ jsxDEV4(ErrorView, {
2081
- error: { message, digest },
4152
+ error: { message, digest, status },
2082
4153
  reset: SERVER_RESET_NOOP2
2083
4154
  }, undefined, false, undefined, this);
2084
4155
  }
2085
4156
 
4157
+ // src/client.ts
4158
+ var DEFERRED_BRAND = "__isDeferred";
4159
+ function isDeferred(v) {
4160
+ return typeof v === "object" && v !== null && Object.hasOwn(v, DEFERRED_BRAND) && v[DEFERRED_BRAND] === true;
4161
+ }
4162
+
2086
4163
  // src/render/loaders.ts
4164
+ var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
4165
+ function isHttpRedirect(res) {
4166
+ return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
4167
+ }
4168
+ async function readResponseMessage(res) {
4169
+ if (res.body === null) {
4170
+ return res.statusText;
4171
+ }
4172
+ try {
4173
+ const body = await res.text();
4174
+ return body || res.statusText;
4175
+ } catch {
4176
+ return res.statusText;
4177
+ }
4178
+ }
2087
4179
  function createLoaderCtx(ctx, accumulatedParentPromise) {
2088
4180
  const cache = new Map;
2089
4181
  return new Proxy(ctx, {
@@ -2106,9 +4198,57 @@ function createLoaderCtx(ctx, accumulatedParentPromise) {
2106
4198
  }
2107
4199
  });
2108
4200
  }
2109
- async function runLoaders(route, ctx, _rootLayout) {
4201
+ function splitDeferredResult(pageResult, routeChainData) {
4202
+ const syncData = {};
4203
+ const deferredPromises = {};
4204
+ for (const [key, value] of Object.entries(routeChainData)) {
4205
+ syncData[key] = value;
4206
+ }
4207
+ for (const [key, value] of Object.entries(pageResult)) {
4208
+ if (key === "__isDeferred") {
4209
+ continue;
4210
+ }
4211
+ if (isPromiseLike(value)) {
4212
+ deferredPromises[key] = Promise.resolve(value);
4213
+ } else {
4214
+ syncData[key] = value;
4215
+ }
4216
+ }
4217
+ return {
4218
+ syncData,
4219
+ deferredPromises: Object.keys(deferredPromises).length > 0 ? deferredPromises : undefined
4220
+ };
4221
+ }
4222
+ function isPromiseLike(value) {
4223
+ return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
4224
+ }
4225
+ async function serializeDeferredRejection(err) {
4226
+ if (isNotFoundError(err)) {
4227
+ const wrapped = new Error(err.message);
4228
+ Object.assign(wrapped, { __furinBrand: "FURIN_NOT_FOUND", data: err.data });
4229
+ return wrapped;
4230
+ }
4231
+ if (err instanceof Response) {
4232
+ const body = await readResponseMessage(err);
4233
+ const wrapped = new Error(body || err.statusText || "Something went wrong");
4234
+ Object.assign(wrapped, { __furinStatus: err.status });
4235
+ return wrapped;
4236
+ }
4237
+ if (err instanceof Error) {
4238
+ return err;
4239
+ }
4240
+ return new Error(String(err));
4241
+ }
4242
+ function assertNoDeferredInRouteLoaders(routeResults) {
4243
+ for (const result of routeResults) {
4244
+ if (isDeferred(result)) {
4245
+ throw new Error("[furin] defer() is only supported in a page loader (route.page({ loader })). A route/layout loader returned a deferred object; move the deferred fields to the page loader, or `await` them in the route loader and return resolved values.");
4246
+ }
4247
+ }
4248
+ }
4249
+ async function runLoaders(route, ctx) {
2110
4250
  try {
2111
- const ctxRecord = { ...ctx, log: useLogger3() };
4251
+ const ctxRecord = { ...ctx, log: useLogger2() };
2112
4252
  const loaderMap = new Map;
2113
4253
  let accumulatedParentPromise = Promise.resolve({});
2114
4254
  for (const r of route.routeChain) {
@@ -2127,22 +4267,47 @@ async function runLoaders(route, ctx, _rootLayout) {
2127
4267
  const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
2128
4268
  const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
2129
4269
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
2130
- const data = Object.assign({}, ...results);
4270
+ const merged = Object.assign({}, ...results);
2131
4271
  const headers = {};
2132
4272
  Object.assign(headers, ctx.set.headers);
2133
- return { type: "data", data, headers };
4273
+ const routeOnlyResults = results.slice(0, loaderMap.size);
4274
+ const pageResult = results[loaderMap.size];
4275
+ assertNoDeferredInRouteLoaders(routeOnlyResults);
4276
+ const routeCtx = { params: ctx.params, query: ctx.query, path: ctx.path };
4277
+ if (isDeferred(pageResult)) {
4278
+ const routeMerged = Object.assign({}, ...routeOnlyResults);
4279
+ const { syncData, deferredPromises } = splitDeferredResult(pageResult, routeMerged);
4280
+ return { type: "data", syncData: { ...syncData, ...routeCtx }, deferredPromises, headers };
4281
+ }
4282
+ return {
4283
+ type: "data",
4284
+ syncData: { ...merged, ...routeCtx },
4285
+ deferredPromises: undefined,
4286
+ headers
4287
+ };
2134
4288
  } catch (err) {
4289
+ const headers = {};
4290
+ Object.assign(headers, ctx.set.headers);
2135
4291
  if (isNotFoundError(err)) {
2136
- const headers2 = {};
2137
- Object.assign(headers2, ctx.set.headers);
2138
- return { type: "not-found", error: err, headers: headers2 };
4292
+ return { type: "not-found", error: err, headers };
2139
4293
  }
2140
4294
  if (err instanceof Response) {
2141
- return { type: "redirect", response: err };
4295
+ if (isHttpRedirect(err)) {
4296
+ return { type: "redirect", response: err };
4297
+ }
4298
+ const isMalformedRedirect = REDIRECT_STATUSES.has(err.status);
4299
+ const status = isMalformedRedirect ? 500 : err.status;
4300
+ const body = await readResponseMessage(err);
4301
+ const message = body || "Something went wrong";
4302
+ return { type: "error", error: err, status, message, headers };
2142
4303
  }
2143
- const headers = {};
2144
- Object.assign(headers, ctx.set.headers);
2145
- return { type: "error", error: err, headers };
4304
+ return {
4305
+ type: "error",
4306
+ error: err,
4307
+ status: 500,
4308
+ message: "Something went wrong",
4309
+ headers
4310
+ };
2146
4311
  }
2147
4312
  }
2148
4313
 
@@ -2185,9 +4350,14 @@ var IS_DEV = true;
2185
4350
  function withSSRRouterContext(element, contextValue) {
2186
4351
  return createElement3(RouterContext.Provider, { value: contextValue }, element);
2187
4352
  }
4353
+ function assertDeferredModeAllowed(route, deferredPromises) {
4354
+ if (deferredPromises !== undefined && route.mode !== "ssr") {
4355
+ throw new Error(`[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` + "defer() streams data progressively and is only supported in SSR. " + "Return the data directly (await it inside the loader) or switch the route to SSR mode.");
4356
+ }
4357
+ }
2188
4358
  async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult) {
2189
4359
  const loaderStart = Date.now();
2190
- const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx, root.route);
4360
+ const loaderResult = precomputedLoaderResult ?? await runLoaders(route, ctx);
2191
4361
  const loader_ms = Date.now() - loaderStart;
2192
4362
  if (loaderResult.type === "redirect") {
2193
4363
  return loaderResult.response;
@@ -2198,10 +4368,13 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
2198
4368
  const isNotFound = loaderResult.type === "not-found";
2199
4369
  const isError = loaderResult.type === "error";
2200
4370
  const isFallback = isNotFound || isError;
2201
- const data = isFallback ? {} : loaderResult.data;
4371
+ const syncData = isFallback ? {} : loaderResult.syncData;
4372
+ const deferredPromises = !isFallback && loaderResult.type === "data" ? loaderResult.deferredPromises : undefined;
4373
+ assertDeferredModeAllowed(route, deferredPromises);
2202
4374
  const headers = loaderResult.headers;
2203
4375
  const componentProps = {
2204
- ...data,
4376
+ ...syncData,
4377
+ ...deferredPromises ?? {},
2205
4378
  params: ctx.params,
2206
4379
  query: ctx.query,
2207
4380
  path: ctx.path
@@ -2219,8 +4392,8 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
2219
4392
  notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
2220
4393
  } else if (loaderResult.type === "error") {
2221
4394
  errorDigest = computeErrorDigest(loaderResult.error);
2222
- element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest);
2223
- status = 500;
4395
+ element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest, loaderResult.message, loaderResult.status);
4396
+ status = loaderResult.status;
2224
4397
  } else {
2225
4398
  element = buildElement(route, componentProps, root.route);
2226
4399
  }
@@ -2239,12 +4412,14 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
2239
4412
  element = withSSRRouterContext(element, ssrContext);
2240
4413
  return {
2241
4414
  componentProps,
4415
+ deferredPromises,
2242
4416
  element,
2243
4417
  errorDigest,
2244
4418
  headData,
2245
4419
  headers,
2246
4420
  loader_ms,
2247
4421
  notFoundError,
4422
+ syncData,
2248
4423
  ssrContext,
2249
4424
  status,
2250
4425
  template
@@ -2267,7 +4442,7 @@ function renderForPath(route, params, root, origin, mode, basePath) {
2267
4442
  if (prepared instanceof Response) {
2268
4443
  return prepared;
2269
4444
  }
2270
- useLogger3().set({
4445
+ useLogger2().set({
2271
4446
  furin: {
2272
4447
  render: mode,
2273
4448
  route: route.pattern,
@@ -2276,17 +4451,27 @@ function renderForPath(route, params, root, origin, mode, basePath) {
2276
4451
  ...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
2277
4452
  }
2278
4453
  });
2279
- const { componentProps, element, headData, headers, status, template } = prepared;
4454
+ const { deferredPromises, element, headData, headers, status, syncData, template } = prepared;
2280
4455
  const stream = await renderToReadableStream(element);
2281
4456
  await stream.allReady;
2282
4457
  const reactHtml = await streamToString(stream);
2283
4458
  return {
2284
- html: assembleHTML(template, headData, reactHtml, componentProps),
4459
+ html: assembleHTML(template, headData, reactHtml, syncData),
2285
4460
  headers,
4461
+ ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
2286
4462
  status
2287
4463
  };
2288
4464
  }, { route: route.pattern, render: mode });
2289
4465
  }
4466
+ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
4467
+ const payload = {
4468
+ ...syncData,
4469
+ ...deferredPromises ?? {}
4470
+ };
4471
+ const serialized = await toCrossJSONAsync(payload);
4472
+ return `${JSON.stringify(serialized)}
4473
+ `;
4474
+ }
2290
4475
  async function prerenderSSG(route, params, root, origin, basePath) {
2291
4476
  const resolvedPath = resolvePath(route.pattern, params);
2292
4477
  const cached = getSSGCache(resolvedPath);
@@ -2298,7 +4483,12 @@ async function prerenderSSG(route, params, root, origin, basePath) {
2298
4483
  return renderResult;
2299
4484
  }
2300
4485
  const result = renderResult;
2301
- const entry = { html: result.html, cachedAt: Date.now(), status: result.status };
4486
+ const entry = {
4487
+ cachedAt: Date.now(),
4488
+ html: result.html,
4489
+ ndjson: result.ndjson,
4490
+ status: result.status
4491
+ };
2302
4492
  setSSGCache(resolvedPath, entry);
2303
4493
  return entry;
2304
4494
  }
@@ -2307,7 +4497,7 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2307
4497
  if (prepared instanceof Response) {
2308
4498
  return prepared;
2309
4499
  }
2310
- useLogger3().set({
4500
+ useLogger2().set({
2311
4501
  furin: {
2312
4502
  render: route.mode,
2313
4503
  route: route.pattern,
@@ -2315,7 +4505,7 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2315
4505
  ...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
2316
4506
  }
2317
4507
  });
2318
- const { componentProps, element, headData, headers, template } = prepared;
4508
+ const { deferredPromises, element, headData, headers, syncData, template } = prepared;
2319
4509
  const { headPre, bodyPre, bodyPost } = splitTemplate(template);
2320
4510
  let reactStream;
2321
4511
  let status = prepared.status;
@@ -2327,18 +4517,18 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2327
4517
  shellErrored = true;
2328
4518
  status = 500;
2329
4519
  finalDigest = computeErrorDigest(shellError);
2330
- useLogger3().set({
4520
+ useLogger2().set({
2331
4521
  furin: { render: route.mode, route: route.pattern, digest: finalDigest, phase: "shell" }
2332
4522
  });
2333
4523
  try {
2334
- reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest), prepared.ssrContext));
4524
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest, undefined, 500), prepared.ssrContext));
2335
4525
  } catch {
2336
- reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest), prepared.ssrContext));
4526
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest, undefined, 500), prepared.ssrContext));
2337
4527
  }
2338
4528
  }
2339
- const dataPayload = shellErrored ? {} : { ...componentProps };
4529
+ const dataPayload = shellErrored ? {} : { ...syncData };
2340
4530
  if (finalDigest) {
2341
- dataPayload.__furinError = { digest: finalDigest };
4531
+ dataPayload.__furinError = { digest: finalDigest, status };
2342
4532
  }
2343
4533
  if (status === 404 && !shellErrored) {
2344
4534
  dataPayload.__furinStatus = 404;
@@ -2346,12 +4536,18 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2346
4536
  dataPayload.__furinNotFound = prepared.notFoundError;
2347
4537
  }
2348
4538
  }
4539
+ if (dataPayload.__furinError !== undefined && dataPayload.__furinNotFound !== undefined) {
4540
+ throw new Error("[furin] internal invariant violated: __furinError and __furinNotFound were both set on the same SSR payload. Open a bug \u2014 these signals are mutually exclusive.");
4541
+ }
4542
+ const hasDeferred = !shellErrored && deferredPromises !== undefined;
4543
+ const deferredKeys = hasDeferred ? Object.keys(deferredPromises) : [];
4544
+ const deferredSetupScript = hasDeferred ? buildDeferredScript(deferredKeys) : "";
2349
4545
  const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(dataPayload)}</script>`;
2350
4546
  const { readable, writable } = new TransformStream;
2351
4547
  const writer = writable.getWriter();
2352
4548
  const enc = new TextEncoder;
2353
4549
  (async () => {
2354
- await writer.write(enc.encode(headPre + headData + bodyPre));
4550
+ await writer.write(enc.encode(headPre + headData + deferredSetupScript + bodyPre));
2355
4551
  const reader = reactStream.getReader();
2356
4552
  for (;; ) {
2357
4553
  const { done, value } = await reader.read();
@@ -2360,7 +4556,22 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2360
4556
  }
2361
4557
  await writer.write(value);
2362
4558
  }
2363
- await writer.write(enc.encode(dataScript + bodyPost));
4559
+ const [earlyBodyPost, finalBodyPost] = hasDeferred ? splitBeforeBodyClose(bodyPost) : ["", bodyPost];
4560
+ await writer.write(enc.encode(dataScript + earlyBodyPost));
4561
+ if (hasDeferred) {
4562
+ await Promise.all(Object.entries(deferredPromises).map(async ([key, promise]) => {
4563
+ try {
4564
+ const resolvedValue = await promise;
4565
+ const chunk = toCrossJSON(resolvedValue);
4566
+ await writer.write(enc.encode(buildDeferredResolution(key, chunk, "resolve")));
4567
+ } catch (err) {
4568
+ const normalized = await serializeDeferredRejection(err);
4569
+ const chunk = toCrossJSON(normalized);
4570
+ await writer.write(enc.encode(buildDeferredResolution(key, chunk, "reject")));
4571
+ }
4572
+ }));
4573
+ }
4574
+ await writer.write(enc.encode(finalBodyPost));
2364
4575
  await writer.close();
2365
4576
  })().catch((err) => writer.abort(err));
2366
4577
  return new Response(readable, {
@@ -2372,6 +4583,13 @@ async function renderSSR(route, ctx, root, precomputedLoaderResult) {
2372
4583
  }
2373
4584
  });
2374
4585
  }
4586
+ function splitBeforeBodyClose(bodyPost) {
4587
+ const index = bodyPost.toLowerCase().lastIndexOf("</body>");
4588
+ if (index === -1) {
4589
+ return [bodyPost, ""];
4590
+ }
4591
+ return [bodyPost.slice(0, index), bodyPost.slice(index)];
4592
+ }
2375
4593
  function isrCacheControl(isFresh, revalidate) {
2376
4594
  const sMaxAge = isFresh ? revalidate : 0;
2377
4595
  return `public, max-age=0, must-revalidate, s-maxage=${sMaxAge}, stale-while-revalidate=${revalidate}`;
@@ -2393,7 +4611,7 @@ function serveISRCacheHit(cached, ctx, route, params, cacheKey, revalidate, root
2393
4611
  if (etag) {
2394
4612
  ctx.set.headers.etag = etag;
2395
4613
  }
2396
- useLogger3().set({
4614
+ useLogger2().set({
2397
4615
  furin: { render: "isr", route: route.pattern, cache: isFresh ? "hit" : "stale" }
2398
4616
  });
2399
4617
  return cached.html;
@@ -2415,7 +4633,7 @@ async function renderISRNon200(prepared, route, ctx, root, errorDigest, renderSt
2415
4633
  } catch (shellError) {
2416
4634
  finalStatus = 500;
2417
4635
  finalDigest = computeErrorDigest(shellError);
2418
- useLogger3().set({
4636
+ useLogger2().set({
2419
4637
  furin: {
2420
4638
  render: "isr",
2421
4639
  route: route.pattern,
@@ -2424,23 +4642,23 @@ async function renderISRNon200(prepared, route, ctx, root, errorDigest, renderSt
2424
4642
  phase: "shell"
2425
4643
  }
2426
4644
  });
2427
- fallbackProps.__furinError = { digest: finalDigest };
4645
+ fallbackProps.__furinError = { digest: finalDigest, status: finalStatus };
2428
4646
  fallbackProps.__furinStatus = 500;
2429
4647
  try {
2430
- reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest), prepared.ssrContext));
4648
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest, undefined, 500), prepared.ssrContext));
2431
4649
  } catch {
2432
- reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest), prepared.ssrContext));
4650
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest, undefined, 500), prepared.ssrContext));
2433
4651
  }
2434
4652
  }
2435
4653
  if (!fallbackProps.__furinError && errorDigest) {
2436
- fallbackProps.__furinError = { digest: errorDigest };
4654
+ fallbackProps.__furinError = { digest: errorDigest, status };
2437
4655
  }
2438
4656
  await reactStream.allReady;
2439
4657
  const reactHtml = await streamToString(reactStream);
2440
4658
  const html = assembleHTML(template, headData, reactHtml, fallbackProps);
2441
4659
  const generatedAt = Date.now();
2442
4660
  const renderMs = generatedAt - renderStart;
2443
- useLogger3().set({
4661
+ useLogger2().set({
2444
4662
  furin: {
2445
4663
  render: "isr",
2446
4664
  route: route.pattern,
@@ -2472,16 +4690,16 @@ async function handleISR(route, ctx, root, buildId = "") {
2472
4690
  if (prepared instanceof Response) {
2473
4691
  return prepared;
2474
4692
  }
2475
- const { componentProps, element, headData, template, status, errorDigest } = prepared;
4693
+ const { element, headData, syncData, template, status, errorDigest } = prepared;
2476
4694
  if (status !== 200) {
2477
4695
  return renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId);
2478
4696
  }
2479
4697
  const stream = await renderToReadableStream(element);
2480
4698
  await stream.allReady;
2481
4699
  const reactHtml = await streamToString(stream);
2482
- const html = assembleHTML(template, headData, reactHtml, componentProps);
4700
+ const html = assembleHTML(template, headData, reactHtml, syncData);
2483
4701
  const generatedAt = Date.now();
2484
- useLogger3().set({
4702
+ useLogger2().set({
2485
4703
  furin: {
2486
4704
  render: "isr",
2487
4705
  route: route.pattern,
@@ -2539,47 +4757,6 @@ function revalidateInBackground(route, params, cacheKey, revalidate, root, origi
2539
4757
  });
2540
4758
  }
2541
4759
 
2542
- // src/utils.ts
2543
- function isFurinPage(value) {
2544
- return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
2545
- }
2546
- function isFurinRoute(value) {
2547
- return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
2548
- }
2549
- function collectRouteChainFromRoute(route) {
2550
- const chain = [];
2551
- let current = route;
2552
- while (current) {
2553
- chain.unshift(current);
2554
- current = current.parent;
2555
- }
2556
- return chain;
2557
- }
2558
- function hasCycle(route) {
2559
- const visited = new Set;
2560
- let current = route;
2561
- while (current) {
2562
- if (visited.has(current)) {
2563
- return true;
2564
- }
2565
- visited.add(current);
2566
- current = current.parent;
2567
- }
2568
- return false;
2569
- }
2570
- function validateRouteChain(chain, root, pagePath) {
2571
- const hasRoot = chain.some((r) => r === root);
2572
- if (!hasRoot) {
2573
- const location = pagePath ? `in ${pagePath}` : "";
2574
- throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
2575
- }
2576
- for (const route of chain) {
2577
- if (hasCycle(route)) {
2578
- throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
2579
- }
2580
- }
2581
- }
2582
-
2583
4760
  // src/router.ts
2584
4761
  function isModuleNotFoundError(err) {
2585
4762
  if (!err || typeof err !== "object" && typeof err !== "string") {
@@ -2657,8 +4834,10 @@ async function scanRootLayout(pagesDir) {
2657
4834
  if (!rootExport.layout) {
2658
4835
  throw new Error("[furin] root.tsx: createRoute() has no layout.");
2659
4836
  }
2660
- const notFoundEntry = await loadConventionComponent(pagesDir, "not-found");
2661
- const errorEntry = await loadConventionComponent(pagesDir, "error");
4837
+ const [notFoundEntry, errorEntry] = await Promise.all([
4838
+ loadConventionComponent(pagesDir, "not-found"),
4839
+ loadConventionComponent(pagesDir, "error")
4840
+ ]);
2662
4841
  return {
2663
4842
  path: rootPath,
2664
4843
  route: rootExport,
@@ -2701,9 +4880,11 @@ async function scanPageFiles(pagesDir, root) {
2701
4880
  if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
2702
4881
  continue;
2703
4882
  }
2704
- const notFound = await resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound);
2705
- const errorComponent = await resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error);
2706
- const segmentBoundaries = await collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache);
4883
+ const [notFound, errorComponent, segmentBoundaries] = await Promise.all([
4884
+ resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound),
4885
+ resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error),
4886
+ collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache)
4887
+ ]);
2707
4888
  if (IS_DEV) {
2708
4889
  const devRoute = await buildDevRoute(absolutePath, relativePath, root);
2709
4890
  devRoute.notFound = notFound;
@@ -2748,14 +4929,16 @@ async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCach
2748
4929
  const boundaries = [];
2749
4930
  for (let depth = 0;depth < dirs.length; depth++) {
2750
4931
  const dir = dirs[depth];
2751
- if (!errorCache.has(dir)) {
2752
- errorCache.set(dir, await loadConventionComponent(dir, "error"));
2753
- }
2754
- if (!notFoundCache.has(dir)) {
2755
- notFoundCache.set(dir, await loadConventionComponent(dir, "not-found"));
2756
- }
2757
- const errorEntry = errorCache.get(dir);
2758
- const notFoundEntry = notFoundCache.get(dir);
4932
+ const [errorEntry, notFoundEntry] = await Promise.all([
4933
+ errorCache.has(dir) ? Promise.resolve(errorCache.get(dir)) : loadConventionComponent(dir, "error").then((r) => {
4934
+ errorCache.set(dir, r);
4935
+ return r;
4936
+ }),
4937
+ notFoundCache.has(dir) ? Promise.resolve(notFoundCache.get(dir)) : loadConventionComponent(dir, "not-found").then((r) => {
4938
+ notFoundCache.set(dir, r);
4939
+ return r;
4940
+ })
4941
+ ]);
2759
4942
  if (errorEntry || notFoundEntry) {
2760
4943
  boundaries.push({
2761
4944
  path: dir,
@@ -2811,8 +4994,7 @@ async function buildDevRoute(absolutePath, relativePath, root) {
2811
4994
  segmentBoundaries: []
2812
4995
  };
2813
4996
  }
2814
- function queryDefaultRedirectHook({ request, query, status, set }) {
2815
- const resolvedQuery = query;
4997
+ function detectQueryDefaultRedirect(request, resolvedQuery) {
2816
4998
  const queryKeys = Object.keys(resolvedQuery);
2817
4999
  if (queryKeys.length === 0) {
2818
5000
  return;
@@ -2834,7 +5016,29 @@ function queryDefaultRedirectHook({ request, query, status, set }) {
2834
5016
  url.searchParams.set(k, String(v));
2835
5017
  }
2836
5018
  }
2837
- set.headers.location = url.pathname + url.search;
5019
+ return url.pathname + url.search;
5020
+ }
5021
+ function parseDataEndpointPath(rawPath) {
5022
+ if (rawPath.includes("://") || rawPath.startsWith("//")) {
5023
+ return;
5024
+ }
5025
+ let url;
5026
+ try {
5027
+ url = new URL(rawPath, "http://localhost");
5028
+ } catch {
5029
+ return;
5030
+ }
5031
+ if (url.origin !== "http://localhost") {
5032
+ return;
5033
+ }
5034
+ return { url, pathname: url.pathname };
5035
+ }
5036
+ function queryDefaultRedirectHook({ request, query, status, set }) {
5037
+ const location = detectQueryDefaultRedirect(request, query);
5038
+ if (!location) {
5039
+ return;
5040
+ }
5041
+ set.headers.location = location;
2838
5042
  return status("Found");
2839
5043
  }
2840
5044
  function collectIntermediateLayoutDirs(pagePath, rootPath) {
@@ -2891,12 +5095,12 @@ async function refreshLayoutChain(chain, pagePath, rootPath, importFn) {
2891
5095
  const ctx = getCompileContext();
2892
5096
  const timestamp = Date.now();
2893
5097
  const layoutDirs = collectIntermediateLayoutDirs(pagePath, rootPath);
5098
+ const freshMods = await Promise.all(layoutDirs.map((layoutDir) => importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx)));
2894
5099
  let chainIdx = 1;
2895
- for (const layoutDir of layoutDirs) {
5100
+ for (const freshMod of freshMods) {
2896
5101
  if (chainIdx >= chain.length) {
2897
5102
  break;
2898
5103
  }
2899
- const freshMod = await importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx);
2900
5104
  if (!freshMod) {
2901
5105
  continue;
2902
5106
  }
@@ -2904,6 +5108,14 @@ async function refreshLayoutChain(chain, pagePath, rootPath, importFn) {
2904
5108
  chainIdx++;
2905
5109
  }
2906
5110
  }
5111
+ function rebuildDevRoute(base, page, chain) {
5112
+ return {
5113
+ ...base,
5114
+ page,
5115
+ routeChain: chain,
5116
+ mode: resolveMode(page, chain)
5117
+ };
5118
+ }
2907
5119
  async function handleDevRequest(route, ctx, root) {
2908
5120
  try {
2909
5121
  let currentRoot = root;
@@ -2921,7 +5133,7 @@ async function handleDevRequest(route, ctx, root) {
2921
5133
  chain[0].layout = currentRoot.route.layout;
2922
5134
  chain[0].loader = currentRoot.route.loader;
2923
5135
  }
2924
- const refreshedRoute = { ...route, page, routeChain: chain };
5136
+ const refreshedRoute = rebuildDevRoute(route, page, chain);
2925
5137
  if (refreshedRoute.mode === "isr") {
2926
5138
  return renderDevISRWithLoaderCache(refreshedRoute, ctx, currentRoot);
2927
5139
  }
@@ -2941,19 +5153,20 @@ async function renderDevISRWithLoaderCache(route, ctx, root) {
2941
5153
  if (cached && isDevLoaderCacheValid(cached)) {
2942
5154
  const precomputed = {
2943
5155
  type: "data",
2944
- data: cached.loaderData,
5156
+ syncData: cached.loaderData,
5157
+ deferredPromises: undefined,
2945
5158
  headers: cached.headers
2946
5159
  };
2947
5160
  return renderSSR(route, ctx, root, precomputed);
2948
5161
  }
2949
- const result = await runLoaders(route, ctx, root.route);
5162
+ const result = await runLoaders(route, ctx);
2950
5163
  if (result.type === "data") {
2951
5164
  const revalidate = route.page._route.revalidate ?? 60;
2952
5165
  const entry = {
2953
5166
  dependencies: computeRouteDependencies(route.path, root.path),
2954
5167
  generatedAt: Date.now(),
2955
5168
  headers: result.headers,
2956
- loaderData: result.data,
5169
+ loaderData: result.syncData,
2957
5170
  mode: "isr",
2958
5171
  revalidate
2959
5172
  };
@@ -2967,18 +5180,19 @@ async function renderDevSSGWithLoaderCache(route, ctx, root) {
2967
5180
  if (cached && isDevLoaderCacheValid(cached)) {
2968
5181
  const precomputed = {
2969
5182
  type: "data",
2970
- data: cached.loaderData,
5183
+ syncData: cached.loaderData,
5184
+ deferredPromises: undefined,
2971
5185
  headers: cached.headers
2972
5186
  };
2973
5187
  return renderSSR(route, ctx, root, precomputed);
2974
5188
  }
2975
- const result = await runLoaders(route, ctx, root.route);
5189
+ const result = await runLoaders(route, ctx);
2976
5190
  if (result.type === "data") {
2977
5191
  const entry = {
2978
5192
  dependencies: computeRouteDependencies(route.path, root.path),
2979
5193
  generatedAt: Date.now(),
2980
5194
  headers: result.headers,
2981
- loaderData: result.data,
5195
+ loaderData: result.syncData,
2982
5196
  mode: "ssg",
2983
5197
  revalidate: Number.POSITIVE_INFINITY
2984
5198
  };
@@ -3019,7 +5233,7 @@ async function handleSSGRequest(route, ctx, root, buildId) {
3019
5233
  }
3020
5234
  var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
3021
5235
  function mergeRouteSchemas(routeChain, key) {
3022
- const schemas = routeChain.map((r) => r[key]).filter(Boolean);
5236
+ const schemas = routeChain.flatMap((r) => r[key] ? [r[key]] : []);
3023
5237
  if (schemas.length === 0) {
3024
5238
  return;
3025
5239
  }
@@ -3063,18 +5277,22 @@ function createRoutePlugin(route, root, buildId = "") {
3063
5277
  });
3064
5278
  return plugin;
3065
5279
  }
5280
+ var DIR_SCAN_CONCURRENCY = 8;
3066
5281
  async function collectPageFilePaths(dir) {
3067
5282
  const files = [];
3068
5283
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
3069
- for (const entry of entries) {
5284
+ const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
3070
5285
  const absolutePath = join(dir, entry.name);
3071
5286
  if (entry.isDirectory()) {
3072
- files.push(...await collectPageFilePaths(absolutePath));
3073
- continue;
5287
+ return await collectPageFilePaths(absolutePath);
3074
5288
  }
3075
5289
  if (entry.isFile()) {
3076
- files.push(absolutePath);
5290
+ return [absolutePath];
3077
5291
  }
5292
+ return [];
5293
+ });
5294
+ for (const chunk of resolved) {
5295
+ files.push(...chunk);
3078
5296
  }
3079
5297
  return files;
3080
5298
  }
@@ -3115,15 +5333,248 @@ function filePathToPattern(path) {
3115
5333
  }
3116
5334
  return `/${segments.join("/")}`;
3117
5335
  }
5336
+ var REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/;
5337
+ function escapeRegExpChar(ch) {
5338
+ return REGEX_META_CHARS_RE.test(ch) ? `\\${ch}` : ch;
5339
+ }
5340
+ function routeSpecificity(pattern) {
5341
+ let score = 0;
5342
+ for (const segment of pattern.split("/")) {
5343
+ if (segment.length === 0) {
5344
+ continue;
5345
+ }
5346
+ if (segment === "*") {
5347
+ score += 1;
5348
+ } else if (segment.startsWith(":")) {
5349
+ score += 2;
5350
+ } else {
5351
+ score += 3;
5352
+ }
5353
+ }
5354
+ return score;
5355
+ }
5356
+ function buildRouteRegex(pattern) {
5357
+ const paramNames = [];
5358
+ let source = "";
5359
+ let i = 0;
5360
+ while (i < pattern.length) {
5361
+ if (pattern[i] === ":") {
5362
+ const start = ++i;
5363
+ while (i < pattern.length && pattern[i] !== "/") {
5364
+ i++;
5365
+ }
5366
+ paramNames.push(pattern.slice(start, i));
5367
+ source += "([^/]+)";
5368
+ } else if (pattern[i] === "*") {
5369
+ paramNames.push("*");
5370
+ source += "(.*)";
5371
+ i++;
5372
+ } else {
5373
+ const ch = pattern[i];
5374
+ if (ch !== undefined) {
5375
+ source += escapeRegExpChar(ch);
5376
+ }
5377
+ i++;
5378
+ }
5379
+ }
5380
+ return { regex: new RegExp(`^${source}$`), paramNames };
5381
+ }
5382
+ function applySchemaDefaults(schema, values) {
5383
+ if (!schema || typeof schema !== "object") {
5384
+ return values;
5385
+ }
5386
+ const s = schema;
5387
+ if (s.type !== "object" || !s.properties || typeof s.properties !== "object") {
5388
+ return values;
5389
+ }
5390
+ const result = { ...values };
5391
+ const properties = s.properties;
5392
+ for (const [key, propSchema] of Object.entries(properties)) {
5393
+ if (!(key in result) && propSchema && typeof propSchema === "object" && "default" in propSchema) {
5394
+ result[key] = propSchema.default;
5395
+ }
5396
+ }
5397
+ return result;
5398
+ }
5399
+ function createDataEndpoint(routes) {
5400
+ const plugin = new Elysia2;
5401
+ plugin.get("/_furin/data", async (ctx) => {
5402
+ const rawPath = ctx.query.path;
5403
+ if (!rawPath || typeof rawPath !== "string") {
5404
+ return new Response("Missing required query param: path", { status: 400 });
5405
+ }
5406
+ const parsed = parseDataEndpointPath(rawPath);
5407
+ if (!parsed) {
5408
+ return new Response("Invalid path", { status: 400 });
5409
+ }
5410
+ const { url, pathname } = parsed;
5411
+ const wideEventLog = useLogger2();
5412
+ wideEventLog.set({ path: rawPath });
5413
+ const matched = routes.reduce((acc, route) => {
5414
+ const { regex, paramNames } = buildRouteRegex(route.pattern);
5415
+ const m = regex.exec(pathname);
5416
+ if (!m) {
5417
+ return acc;
5418
+ }
5419
+ const score = routeSpecificity(route.pattern);
5420
+ if (acc && acc.score >= score) {
5421
+ return acc;
5422
+ }
5423
+ const params = {};
5424
+ for (let i = 0;i < paramNames.length; i++) {
5425
+ const name = paramNames[i];
5426
+ if (name !== undefined) {
5427
+ params[name] = m[i + 1] ?? "";
5428
+ }
5429
+ }
5430
+ return { route, params, score };
5431
+ }, null);
5432
+ if (!matched) {
5433
+ return new Response("Route not found", { status: 404 });
5434
+ }
5435
+ wideEventLog.set({ routePattern: matched.route.pattern });
5436
+ const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
5437
+ const syntheticSet = { headers: {}, status: 200 };
5438
+ const syntheticCtx = {
5439
+ request: syntheticRequest,
5440
+ params: matched.params,
5441
+ query: Object.fromEntries(url.searchParams),
5442
+ set: syntheticSet,
5443
+ headers: ctx.headers,
5444
+ cookie: ctx.cookie,
5445
+ path: pathname,
5446
+ redirect: (location, status) => new Response(null, { status: status ?? 302, headers: { location } }),
5447
+ status: (code) => new Response(null, { status: code })
5448
+ };
5449
+ const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
5450
+ const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
5451
+ syntheticCtx.params = applySchemaDefaults(mergedParams, syntheticCtx.params);
5452
+ syntheticCtx.query = applySchemaDefaults(mergedQuery, syntheticCtx.query);
5453
+ if (mergedQuery) {
5454
+ const redirectLocation = detectQueryDefaultRedirect(syntheticRequest, syntheticCtx.query);
5455
+ if (redirectLocation) {
5456
+ const serialized2 = await toCrossJSONAsync({ __furinRedirect: redirectLocation });
5457
+ return new Response(`${JSON.stringify(serialized2)}
5458
+ `, {
5459
+ headers: { "content-type": "application/x-ndjson" }
5460
+ });
5461
+ }
5462
+ }
5463
+ const result = await runLoaders(matched.route, syntheticCtx);
5464
+ if (result.type === "redirect") {
5465
+ const redirectUrl = new URL(result.response.headers.get("location") ?? "/", ctx.request.url);
5466
+ const serialized2 = await toCrossJSONAsync({
5467
+ __furinRedirect: redirectUrl.pathname + redirectUrl.search
5468
+ });
5469
+ return new Response(`${JSON.stringify(serialized2)}
5470
+ `, {
5471
+ headers: { "content-type": "application/x-ndjson" }
5472
+ });
5473
+ }
5474
+ if (result.type === "not-found") {
5475
+ const serialized2 = await toCrossJSONAsync({
5476
+ __furinStatus: 404,
5477
+ __furinNotFound: { message: result.error.message, data: result.error.data }
5478
+ });
5479
+ return new Response(`${JSON.stringify(serialized2)}
5480
+ `, {
5481
+ status: 200,
5482
+ headers: { "content-type": "application/x-ndjson" }
5483
+ });
5484
+ }
5485
+ if (result.type === "error") {
5486
+ const digest = computeErrorDigest(result.error);
5487
+ const serialized2 = await toCrossJSONAsync({
5488
+ __furinError: {
5489
+ digest,
5490
+ message: result.message,
5491
+ status: result.status
5492
+ }
5493
+ });
5494
+ return new Response(`${JSON.stringify(serialized2)}
5495
+ `, {
5496
+ status: result.status,
5497
+ headers: { "content-type": "application/x-ndjson" }
5498
+ });
5499
+ }
5500
+ const syncDataWithTitle = withResolvedTitle(matched.route, result.syncData);
5501
+ if (result.deferredPromises) {
5502
+ return new Response(createDeferredNdjsonStream(syncDataWithTitle, result.deferredPromises), {
5503
+ headers: {
5504
+ "content-type": "application/x-ndjson",
5505
+ ...result.headers
5506
+ }
5507
+ });
5508
+ }
5509
+ const serialized = await toCrossJSONAsync(syncDataWithTitle);
5510
+ return new Response(`${JSON.stringify(serialized)}
5511
+ `, {
5512
+ headers: {
5513
+ "content-type": "application/x-ndjson",
5514
+ ...result.headers
5515
+ }
5516
+ });
5517
+ }, {
5518
+ query: t.Object({ path: t.Optional(t.String()) })
5519
+ });
5520
+ return plugin;
5521
+ }
5522
+ function withResolvedTitle(route, syncData) {
5523
+ const head = route.page.head;
5524
+ if (!head) {
5525
+ return syncData;
5526
+ }
5527
+ let title;
5528
+ try {
5529
+ title = extractTitle(head(syncData).meta);
5530
+ } catch {
5531
+ return syncData;
5532
+ }
5533
+ if (title === undefined) {
5534
+ return syncData;
5535
+ }
5536
+ return { ...syncData, __furinTitle: title };
5537
+ }
5538
+ function createDeferredNdjsonStream(syncData, deferredPromises) {
5539
+ const enc = new TextEncoder;
5540
+ const entries = Object.entries(deferredPromises);
5541
+ return new ReadableStream({
5542
+ async start(controller) {
5543
+ const initial = toCrossJSON({
5544
+ ...syncData,
5545
+ __furinDeferredKeys: entries.map(([key]) => key)
5546
+ });
5547
+ controller.enqueue(enc.encode(`${JSON.stringify(initial)}
5548
+ `));
5549
+ await Promise.all(entries.map(async ([key, promise]) => {
5550
+ try {
5551
+ const value = await promise;
5552
+ controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "resolve", value: toCrossJSON(value) })}
5553
+ `));
5554
+ } catch (err) {
5555
+ const normalized = await serializeDeferredRejection(err);
5556
+ const value = toCrossJSON(normalized);
5557
+ controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "reject", value })}
5558
+ `));
5559
+ }
5560
+ }));
5561
+ controller.close();
5562
+ }
5563
+ });
5564
+ }
3118
5565
  export {
3119
5566
  scanRootLayout,
3120
5567
  scanPages,
3121
5568
  resolveMode,
3122
5569
  refreshLayoutChain,
5570
+ rebuildDevRoute,
3123
5571
  queryDefaultRedirectHook,
5572
+ parseDataEndpointPath,
3124
5573
  mergeRouteSchemas,
3125
5574
  loadProdRoutes,
3126
5575
  filePathToPattern,
5576
+ detectQueryDefaultRedirect,
3127
5577
  createRoutePlugin,
5578
+ createDataEndpoint,
3128
5579
  computeRouteDependencies
3129
5580
  };