@teyik0/furin 0.1.0-alpha.10

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 (87) hide show
  1. package/dist/adapter/bun.d.ts +3 -0
  2. package/dist/adapter/static.d.ts +3 -0
  3. package/dist/build/client.d.ts +25 -0
  4. package/dist/build/compile-entry.d.ts +35 -0
  5. package/dist/build/entry-template.d.ts +26 -0
  6. package/dist/build/hydrate.d.ts +24 -0
  7. package/dist/build/index.d.ts +7 -0
  8. package/dist/build/index.js +4716 -0
  9. package/dist/build/route-types.d.ts +21 -0
  10. package/dist/build/scan-server.d.ts +8 -0
  11. package/dist/build/server-routes-entry.d.ts +35 -0
  12. package/dist/build/shared.d.ts +11 -0
  13. package/dist/build/types.d.ts +76 -0
  14. package/dist/cli/config.d.ts +9 -0
  15. package/dist/cli/index.d.ts +2 -0
  16. package/dist/cli/index.js +4751 -0
  17. package/dist/client.d.ts +195 -0
  18. package/dist/client.js +20 -0
  19. package/dist/config.d.ts +50 -0
  20. package/dist/config.js +28 -0
  21. package/dist/context-logger.d.ts +28 -0
  22. package/dist/dev-page-plugin.d.ts +109 -0
  23. package/dist/error.d.ts +23 -0
  24. package/dist/furin.d.ts +52 -0
  25. package/dist/furin.js +3948 -0
  26. package/dist/internal.d.ts +33 -0
  27. package/dist/link.d.ts +454 -0
  28. package/dist/link.js +1790 -0
  29. package/dist/not-found.d.ts +19 -0
  30. package/dist/plugin/index.d.ts +20 -0
  31. package/dist/plugin/index.js +1408 -0
  32. package/dist/plugin/transform-client.d.ts +9 -0
  33. package/dist/render/assemble.d.ts +15 -0
  34. package/dist/render/boundaries.d.ts +79 -0
  35. package/dist/render/cache.d.ts +96 -0
  36. package/dist/render/default-screens.d.ts +11 -0
  37. package/dist/render/digest.d.ts +16 -0
  38. package/dist/render/element.d.ts +8 -0
  39. package/dist/render/index.d.ts +53 -0
  40. package/dist/render/loaders.d.ts +21 -0
  41. package/dist/render/shell.d.ts +29 -0
  42. package/dist/render/template.d.ts +6 -0
  43. package/dist/router.d.ts +96 -0
  44. package/dist/router.js +2693 -0
  45. package/dist/runtime-env.d.ts +3 -0
  46. package/dist/utils.d.ts +6 -0
  47. package/package.json +77 -0
  48. package/src/adapter/README.md +13 -0
  49. package/src/adapter/bun.ts +239 -0
  50. package/src/adapter/static.ts +341 -0
  51. package/src/build/client.ts +153 -0
  52. package/src/build/compile-entry.ts +129 -0
  53. package/src/build/entry-template.ts +126 -0
  54. package/src/build/hydrate.ts +250 -0
  55. package/src/build/index.ts +151 -0
  56. package/src/build/route-types.ts +89 -0
  57. package/src/build/scan-server.ts +110 -0
  58. package/src/build/server-routes-entry.ts +55 -0
  59. package/src/build/shared.ts +78 -0
  60. package/src/build/types.ts +85 -0
  61. package/src/cli/config.ts +68 -0
  62. package/src/cli/index.ts +115 -0
  63. package/src/client.ts +278 -0
  64. package/src/config.ts +66 -0
  65. package/src/context-logger.ts +74 -0
  66. package/src/dev-page-plugin.ts +434 -0
  67. package/src/env.d.ts +49 -0
  68. package/src/error.ts +32 -0
  69. package/src/furin.ts +383 -0
  70. package/src/internal.ts +51 -0
  71. package/src/link.tsx +1578 -0
  72. package/src/not-found.ts +40 -0
  73. package/src/plugin/index.ts +80 -0
  74. package/src/plugin/transform-client.ts +372 -0
  75. package/src/render/assemble.ts +66 -0
  76. package/src/render/boundaries.tsx +176 -0
  77. package/src/render/cache.ts +251 -0
  78. package/src/render/default-screens.tsx +299 -0
  79. package/src/render/digest.ts +71 -0
  80. package/src/render/element.tsx +119 -0
  81. package/src/render/index.ts +867 -0
  82. package/src/render/loaders.ts +127 -0
  83. package/src/render/shell.ts +187 -0
  84. package/src/render/template.ts +55 -0
  85. package/src/router.ts +779 -0
  86. package/src/runtime-env.ts +6 -0
  87. package/src/utils.ts +68 -0
@@ -0,0 +1,4716 @@
1
+ // @bun
2
+ // src/build/index.ts
3
+ import { existsSync as existsSync9, writeFileSync as writeFileSync8 } from "fs";
4
+ import { join as join10, relative as relative4, resolve as resolve3 } from "path";
5
+
6
+ // src/adapter/bun.ts
7
+ import { existsSync as existsSync6, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
8
+ import { dirname as dirname2, join as join7, resolve } from "path";
9
+ import { fileURLToPath } from "url";
10
+
11
+ // src/build/client.ts
12
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
13
+ import { basename, join as join4 } from "path";
14
+
15
+ // ../../node_modules/.bun/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
16
+ var comma = 44;
17
+ var semicolon = 59;
18
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
19
+ var intToChar = new Uint8Array(64);
20
+ var charToInt = new Uint8Array(128);
21
+ for (let i = 0;i < chars.length; i++) {
22
+ const c = chars.charCodeAt(i);
23
+ intToChar[i] = c;
24
+ charToInt[c] = i;
25
+ }
26
+ function encodeInteger(builder, num, relative) {
27
+ let delta = num - relative;
28
+ delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
29
+ do {
30
+ let clamped = delta & 31;
31
+ delta >>>= 5;
32
+ if (delta > 0)
33
+ clamped |= 32;
34
+ builder.write(intToChar[clamped]);
35
+ } while (delta > 0);
36
+ return num;
37
+ }
38
+ var bufLength = 1024 * 16;
39
+ var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder : typeof Buffer !== "undefined" ? {
40
+ decode(buf) {
41
+ const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
42
+ return out.toString();
43
+ }
44
+ } : {
45
+ decode(buf) {
46
+ let out = "";
47
+ for (let i = 0;i < buf.length; i++) {
48
+ out += String.fromCharCode(buf[i]);
49
+ }
50
+ return out;
51
+ }
52
+ };
53
+ var StringWriter = class {
54
+ constructor() {
55
+ this.pos = 0;
56
+ this.out = "";
57
+ this.buffer = new Uint8Array(bufLength);
58
+ }
59
+ write(v) {
60
+ const { buffer } = this;
61
+ buffer[this.pos++] = v;
62
+ if (this.pos === bufLength) {
63
+ this.out += td.decode(buffer);
64
+ this.pos = 0;
65
+ }
66
+ }
67
+ flush() {
68
+ const { buffer, out, pos } = this;
69
+ return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
70
+ }
71
+ };
72
+ function encode(decoded) {
73
+ const writer = new StringWriter;
74
+ let sourcesIndex = 0;
75
+ let sourceLine = 0;
76
+ let sourceColumn = 0;
77
+ let namesIndex = 0;
78
+ for (let i = 0;i < decoded.length; i++) {
79
+ const line = decoded[i];
80
+ if (i > 0)
81
+ writer.write(semicolon);
82
+ if (line.length === 0)
83
+ continue;
84
+ let genColumn = 0;
85
+ for (let j = 0;j < line.length; j++) {
86
+ const segment = line[j];
87
+ if (j > 0)
88
+ writer.write(comma);
89
+ genColumn = encodeInteger(writer, segment[0], genColumn);
90
+ if (segment.length === 1)
91
+ continue;
92
+ sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
93
+ sourceLine = encodeInteger(writer, segment[2], sourceLine);
94
+ sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
95
+ if (segment.length === 4)
96
+ continue;
97
+ namesIndex = encodeInteger(writer, segment[4], namesIndex);
98
+ }
99
+ }
100
+ return writer.flush();
101
+ }
102
+
103
+ // ../../node_modules/.bun/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
104
+ class BitSet {
105
+ constructor(arg) {
106
+ this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
107
+ }
108
+ add(n) {
109
+ this.bits[n >> 5] |= 1 << (n & 31);
110
+ }
111
+ has(n) {
112
+ return !!(this.bits[n >> 5] & 1 << (n & 31));
113
+ }
114
+ }
115
+
116
+ class Chunk {
117
+ constructor(start, end, content) {
118
+ this.start = start;
119
+ this.end = end;
120
+ this.original = content;
121
+ this.intro = "";
122
+ this.outro = "";
123
+ this.content = content;
124
+ this.storeName = false;
125
+ this.edited = false;
126
+ {
127
+ this.previous = null;
128
+ this.next = null;
129
+ }
130
+ }
131
+ appendLeft(content) {
132
+ this.outro += content;
133
+ }
134
+ appendRight(content) {
135
+ this.intro = this.intro + content;
136
+ }
137
+ clone() {
138
+ const chunk = new Chunk(this.start, this.end, this.original);
139
+ chunk.intro = this.intro;
140
+ chunk.outro = this.outro;
141
+ chunk.content = this.content;
142
+ chunk.storeName = this.storeName;
143
+ chunk.edited = this.edited;
144
+ return chunk;
145
+ }
146
+ contains(index) {
147
+ return this.start < index && index < this.end;
148
+ }
149
+ eachNext(fn) {
150
+ let chunk = this;
151
+ while (chunk) {
152
+ fn(chunk);
153
+ chunk = chunk.next;
154
+ }
155
+ }
156
+ eachPrevious(fn) {
157
+ let chunk = this;
158
+ while (chunk) {
159
+ fn(chunk);
160
+ chunk = chunk.previous;
161
+ }
162
+ }
163
+ edit(content, storeName, contentOnly) {
164
+ this.content = content;
165
+ if (!contentOnly) {
166
+ this.intro = "";
167
+ this.outro = "";
168
+ }
169
+ this.storeName = storeName;
170
+ this.edited = true;
171
+ return this;
172
+ }
173
+ prependLeft(content) {
174
+ this.outro = content + this.outro;
175
+ }
176
+ prependRight(content) {
177
+ this.intro = content + this.intro;
178
+ }
179
+ reset() {
180
+ this.intro = "";
181
+ this.outro = "";
182
+ if (this.edited) {
183
+ this.content = this.original;
184
+ this.storeName = false;
185
+ this.edited = false;
186
+ }
187
+ }
188
+ split(index) {
189
+ const sliceIndex = index - this.start;
190
+ const originalBefore = this.original.slice(0, sliceIndex);
191
+ const originalAfter = this.original.slice(sliceIndex);
192
+ this.original = originalBefore;
193
+ const newChunk = new Chunk(index, this.end, originalAfter);
194
+ newChunk.outro = this.outro;
195
+ this.outro = "";
196
+ this.end = index;
197
+ if (this.edited) {
198
+ newChunk.edit("", false);
199
+ this.content = "";
200
+ } else {
201
+ this.content = originalBefore;
202
+ }
203
+ newChunk.next = this.next;
204
+ if (newChunk.next)
205
+ newChunk.next.previous = newChunk;
206
+ newChunk.previous = this;
207
+ this.next = newChunk;
208
+ return newChunk;
209
+ }
210
+ toString() {
211
+ return this.intro + this.content + this.outro;
212
+ }
213
+ trimEnd(rx) {
214
+ this.outro = this.outro.replace(rx, "");
215
+ if (this.outro.length)
216
+ return true;
217
+ const trimmed = this.content.replace(rx, "");
218
+ if (trimmed.length) {
219
+ if (trimmed !== this.content) {
220
+ this.split(this.start + trimmed.length).edit("", undefined, true);
221
+ if (this.edited) {
222
+ this.edit(trimmed, this.storeName, true);
223
+ }
224
+ }
225
+ return true;
226
+ } else {
227
+ this.edit("", undefined, true);
228
+ this.intro = this.intro.replace(rx, "");
229
+ if (this.intro.length)
230
+ return true;
231
+ }
232
+ }
233
+ trimStart(rx) {
234
+ this.intro = this.intro.replace(rx, "");
235
+ if (this.intro.length)
236
+ return true;
237
+ const trimmed = this.content.replace(rx, "");
238
+ if (trimmed.length) {
239
+ if (trimmed !== this.content) {
240
+ const newChunk = this.split(this.end - trimmed.length);
241
+ if (this.edited) {
242
+ newChunk.edit(trimmed, this.storeName, true);
243
+ }
244
+ this.edit("", undefined, true);
245
+ }
246
+ return true;
247
+ } else {
248
+ this.edit("", undefined, true);
249
+ this.outro = this.outro.replace(rx, "");
250
+ if (this.outro.length)
251
+ return true;
252
+ }
253
+ }
254
+ }
255
+ function getBtoa() {
256
+ if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
257
+ return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
258
+ } else if (typeof Buffer === "function") {
259
+ return (str) => Buffer.from(str, "utf-8").toString("base64");
260
+ } else {
261
+ return () => {
262
+ throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
263
+ };
264
+ }
265
+ }
266
+ var btoa = /* @__PURE__ */ getBtoa();
267
+
268
+ class SourceMap {
269
+ constructor(properties) {
270
+ this.version = 3;
271
+ this.file = properties.file;
272
+ this.sources = properties.sources;
273
+ this.sourcesContent = properties.sourcesContent;
274
+ this.names = properties.names;
275
+ this.mappings = encode(properties.mappings);
276
+ if (typeof properties.x_google_ignoreList !== "undefined") {
277
+ this.x_google_ignoreList = properties.x_google_ignoreList;
278
+ }
279
+ if (typeof properties.debugId !== "undefined") {
280
+ this.debugId = properties.debugId;
281
+ }
282
+ }
283
+ toString() {
284
+ return JSON.stringify(this);
285
+ }
286
+ toUrl() {
287
+ return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
288
+ }
289
+ }
290
+ function guessIndent(code) {
291
+ const lines = code.split(`
292
+ `);
293
+ const tabbed = lines.filter((line) => /^\t+/.test(line));
294
+ const spaced = lines.filter((line) => /^ {2,}/.test(line));
295
+ if (tabbed.length === 0 && spaced.length === 0) {
296
+ return null;
297
+ }
298
+ if (tabbed.length >= spaced.length) {
299
+ return "\t";
300
+ }
301
+ const min = spaced.reduce((previous, current) => {
302
+ const numSpaces = /^ +/.exec(current)[0].length;
303
+ return Math.min(numSpaces, previous);
304
+ }, Infinity);
305
+ return new Array(min + 1).join(" ");
306
+ }
307
+ function getRelativePath(from, to) {
308
+ const fromParts = from.split(/[/\\]/);
309
+ const toParts = to.split(/[/\\]/);
310
+ fromParts.pop();
311
+ while (fromParts[0] === toParts[0]) {
312
+ fromParts.shift();
313
+ toParts.shift();
314
+ }
315
+ if (fromParts.length) {
316
+ let i = fromParts.length;
317
+ while (i--)
318
+ fromParts[i] = "..";
319
+ }
320
+ return fromParts.concat(toParts).join("/");
321
+ }
322
+ var toString = Object.prototype.toString;
323
+ function isObject(thing) {
324
+ return toString.call(thing) === "[object Object]";
325
+ }
326
+ function getLocator(source) {
327
+ const originalLines = source.split(`
328
+ `);
329
+ const lineOffsets = [];
330
+ for (let i = 0, pos = 0;i < originalLines.length; i++) {
331
+ lineOffsets.push(pos);
332
+ pos += originalLines[i].length + 1;
333
+ }
334
+ return function locate(index) {
335
+ let i = 0;
336
+ let j = lineOffsets.length;
337
+ while (i < j) {
338
+ const m = i + j >> 1;
339
+ if (index < lineOffsets[m]) {
340
+ j = m;
341
+ } else {
342
+ i = m + 1;
343
+ }
344
+ }
345
+ const line = i - 1;
346
+ const column = index - lineOffsets[line];
347
+ return { line, column };
348
+ };
349
+ }
350
+ var wordRegex = /\w/;
351
+
352
+ class Mappings {
353
+ constructor(hires) {
354
+ this.hires = hires;
355
+ this.generatedCodeLine = 0;
356
+ this.generatedCodeColumn = 0;
357
+ this.raw = [];
358
+ this.rawSegments = this.raw[this.generatedCodeLine] = [];
359
+ this.pending = null;
360
+ }
361
+ addEdit(sourceIndex, content, loc, nameIndex) {
362
+ if (content.length) {
363
+ const contentLengthMinusOne = content.length - 1;
364
+ let contentLineEnd = content.indexOf(`
365
+ `, 0);
366
+ let previousContentLineEnd = -1;
367
+ while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
368
+ const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
369
+ if (nameIndex >= 0) {
370
+ segment2.push(nameIndex);
371
+ }
372
+ this.rawSegments.push(segment2);
373
+ this.generatedCodeLine += 1;
374
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
375
+ this.generatedCodeColumn = 0;
376
+ previousContentLineEnd = contentLineEnd;
377
+ contentLineEnd = content.indexOf(`
378
+ `, contentLineEnd + 1);
379
+ }
380
+ const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
381
+ if (nameIndex >= 0) {
382
+ segment.push(nameIndex);
383
+ }
384
+ this.rawSegments.push(segment);
385
+ this.advance(content.slice(previousContentLineEnd + 1));
386
+ } else if (this.pending) {
387
+ this.rawSegments.push(this.pending);
388
+ this.advance(content);
389
+ }
390
+ this.pending = null;
391
+ }
392
+ addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
393
+ let originalCharIndex = chunk.start;
394
+ let first = true;
395
+ let charInHiresBoundary = false;
396
+ while (originalCharIndex < chunk.end) {
397
+ if (original[originalCharIndex] === `
398
+ `) {
399
+ loc.line += 1;
400
+ loc.column = 0;
401
+ this.generatedCodeLine += 1;
402
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
403
+ this.generatedCodeColumn = 0;
404
+ first = true;
405
+ charInHiresBoundary = false;
406
+ } else {
407
+ if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
408
+ const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
409
+ if (this.hires === "boundary") {
410
+ if (wordRegex.test(original[originalCharIndex])) {
411
+ if (!charInHiresBoundary) {
412
+ this.rawSegments.push(segment);
413
+ charInHiresBoundary = true;
414
+ }
415
+ } else {
416
+ this.rawSegments.push(segment);
417
+ charInHiresBoundary = false;
418
+ }
419
+ } else {
420
+ this.rawSegments.push(segment);
421
+ }
422
+ }
423
+ loc.column += 1;
424
+ this.generatedCodeColumn += 1;
425
+ first = false;
426
+ }
427
+ originalCharIndex += 1;
428
+ }
429
+ this.pending = null;
430
+ }
431
+ advance(str) {
432
+ if (!str)
433
+ return;
434
+ const lines = str.split(`
435
+ `);
436
+ if (lines.length > 1) {
437
+ for (let i = 0;i < lines.length - 1; i++) {
438
+ this.generatedCodeLine++;
439
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
440
+ }
441
+ this.generatedCodeColumn = 0;
442
+ }
443
+ this.generatedCodeColumn += lines[lines.length - 1].length;
444
+ }
445
+ }
446
+ var n = `
447
+ `;
448
+ var warned = {
449
+ insertLeft: false,
450
+ insertRight: false,
451
+ storeName: false
452
+ };
453
+
454
+ class MagicString {
455
+ constructor(string, options = {}) {
456
+ const chunk = new Chunk(0, string.length, string);
457
+ Object.defineProperties(this, {
458
+ original: { writable: true, value: string },
459
+ outro: { writable: true, value: "" },
460
+ intro: { writable: true, value: "" },
461
+ firstChunk: { writable: true, value: chunk },
462
+ lastChunk: { writable: true, value: chunk },
463
+ lastSearchedChunk: { writable: true, value: chunk },
464
+ byStart: { writable: true, value: {} },
465
+ byEnd: { writable: true, value: {} },
466
+ filename: { writable: true, value: options.filename },
467
+ indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
468
+ sourcemapLocations: { writable: true, value: new BitSet },
469
+ storedNames: { writable: true, value: {} },
470
+ indentStr: { writable: true, value: undefined },
471
+ ignoreList: { writable: true, value: options.ignoreList },
472
+ offset: { writable: true, value: options.offset || 0 }
473
+ });
474
+ this.byStart[0] = chunk;
475
+ this.byEnd[string.length] = chunk;
476
+ }
477
+ addSourcemapLocation(char) {
478
+ this.sourcemapLocations.add(char);
479
+ }
480
+ append(content) {
481
+ if (typeof content !== "string")
482
+ throw new TypeError("outro content must be a string");
483
+ this.outro += content;
484
+ return this;
485
+ }
486
+ appendLeft(index, content) {
487
+ index = index + this.offset;
488
+ if (typeof content !== "string")
489
+ throw new TypeError("inserted content must be a string");
490
+ this._split(index);
491
+ const chunk = this.byEnd[index];
492
+ if (chunk) {
493
+ chunk.appendLeft(content);
494
+ } else {
495
+ this.intro += content;
496
+ }
497
+ return this;
498
+ }
499
+ appendRight(index, content) {
500
+ index = index + this.offset;
501
+ if (typeof content !== "string")
502
+ throw new TypeError("inserted content must be a string");
503
+ this._split(index);
504
+ const chunk = this.byStart[index];
505
+ if (chunk) {
506
+ chunk.appendRight(content);
507
+ } else {
508
+ this.outro += content;
509
+ }
510
+ return this;
511
+ }
512
+ clone() {
513
+ const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
514
+ let originalChunk = this.firstChunk;
515
+ let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
516
+ while (originalChunk) {
517
+ cloned.byStart[clonedChunk.start] = clonedChunk;
518
+ cloned.byEnd[clonedChunk.end] = clonedChunk;
519
+ const nextOriginalChunk = originalChunk.next;
520
+ const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
521
+ if (nextClonedChunk) {
522
+ clonedChunk.next = nextClonedChunk;
523
+ nextClonedChunk.previous = clonedChunk;
524
+ clonedChunk = nextClonedChunk;
525
+ }
526
+ originalChunk = nextOriginalChunk;
527
+ }
528
+ cloned.lastChunk = clonedChunk;
529
+ if (this.indentExclusionRanges) {
530
+ cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
531
+ }
532
+ cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
533
+ cloned.intro = this.intro;
534
+ cloned.outro = this.outro;
535
+ return cloned;
536
+ }
537
+ generateDecodedMap(options) {
538
+ options = options || {};
539
+ const sourceIndex = 0;
540
+ const names = Object.keys(this.storedNames);
541
+ const mappings = new Mappings(options.hires);
542
+ const locate = getLocator(this.original);
543
+ if (this.intro) {
544
+ mappings.advance(this.intro);
545
+ }
546
+ this.firstChunk.eachNext((chunk) => {
547
+ const loc = locate(chunk.start);
548
+ if (chunk.intro.length)
549
+ mappings.advance(chunk.intro);
550
+ if (chunk.edited) {
551
+ mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
552
+ } else {
553
+ mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
554
+ }
555
+ if (chunk.outro.length)
556
+ mappings.advance(chunk.outro);
557
+ });
558
+ if (this.outro) {
559
+ mappings.advance(this.outro);
560
+ }
561
+ return {
562
+ file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
563
+ sources: [
564
+ options.source ? getRelativePath(options.file || "", options.source) : options.file || ""
565
+ ],
566
+ sourcesContent: options.includeContent ? [this.original] : undefined,
567
+ names,
568
+ mappings: mappings.raw,
569
+ x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined
570
+ };
571
+ }
572
+ generateMap(options) {
573
+ return new SourceMap(this.generateDecodedMap(options));
574
+ }
575
+ _ensureindentStr() {
576
+ if (this.indentStr === undefined) {
577
+ this.indentStr = guessIndent(this.original);
578
+ }
579
+ }
580
+ _getRawIndentString() {
581
+ this._ensureindentStr();
582
+ return this.indentStr;
583
+ }
584
+ getIndentString() {
585
+ this._ensureindentStr();
586
+ return this.indentStr === null ? "\t" : this.indentStr;
587
+ }
588
+ indent(indentStr, options) {
589
+ const pattern = /^[^\r\n]/gm;
590
+ if (isObject(indentStr)) {
591
+ options = indentStr;
592
+ indentStr = undefined;
593
+ }
594
+ if (indentStr === undefined) {
595
+ this._ensureindentStr();
596
+ indentStr = this.indentStr || "\t";
597
+ }
598
+ if (indentStr === "")
599
+ return this;
600
+ options = options || {};
601
+ const isExcluded = {};
602
+ if (options.exclude) {
603
+ const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
604
+ exclusions.forEach((exclusion) => {
605
+ for (let i = exclusion[0];i < exclusion[1]; i += 1) {
606
+ isExcluded[i] = true;
607
+ }
608
+ });
609
+ }
610
+ let shouldIndentNextCharacter = options.indentStart !== false;
611
+ const replacer = (match) => {
612
+ if (shouldIndentNextCharacter)
613
+ return `${indentStr}${match}`;
614
+ shouldIndentNextCharacter = true;
615
+ return match;
616
+ };
617
+ this.intro = this.intro.replace(pattern, replacer);
618
+ let charIndex = 0;
619
+ let chunk = this.firstChunk;
620
+ while (chunk) {
621
+ const end = chunk.end;
622
+ if (chunk.edited) {
623
+ if (!isExcluded[charIndex]) {
624
+ chunk.content = chunk.content.replace(pattern, replacer);
625
+ if (chunk.content.length) {
626
+ shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === `
627
+ `;
628
+ }
629
+ }
630
+ } else {
631
+ charIndex = chunk.start;
632
+ while (charIndex < end) {
633
+ if (!isExcluded[charIndex]) {
634
+ const char = this.original[charIndex];
635
+ if (char === `
636
+ `) {
637
+ shouldIndentNextCharacter = true;
638
+ } else if (char !== "\r" && shouldIndentNextCharacter) {
639
+ shouldIndentNextCharacter = false;
640
+ if (charIndex === chunk.start) {
641
+ chunk.prependRight(indentStr);
642
+ } else {
643
+ this._splitChunk(chunk, charIndex);
644
+ chunk = chunk.next;
645
+ chunk.prependRight(indentStr);
646
+ }
647
+ }
648
+ }
649
+ charIndex += 1;
650
+ }
651
+ }
652
+ charIndex = chunk.end;
653
+ chunk = chunk.next;
654
+ }
655
+ this.outro = this.outro.replace(pattern, replacer);
656
+ return this;
657
+ }
658
+ insert() {
659
+ throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
660
+ }
661
+ insertLeft(index, content) {
662
+ if (!warned.insertLeft) {
663
+ console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
664
+ warned.insertLeft = true;
665
+ }
666
+ return this.appendLeft(index, content);
667
+ }
668
+ insertRight(index, content) {
669
+ if (!warned.insertRight) {
670
+ console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
671
+ warned.insertRight = true;
672
+ }
673
+ return this.prependRight(index, content);
674
+ }
675
+ move(start, end, index) {
676
+ start = start + this.offset;
677
+ end = end + this.offset;
678
+ index = index + this.offset;
679
+ if (index >= start && index <= end)
680
+ throw new Error("Cannot move a selection inside itself");
681
+ this._split(start);
682
+ this._split(end);
683
+ this._split(index);
684
+ const first = this.byStart[start];
685
+ const last = this.byEnd[end];
686
+ const oldLeft = first.previous;
687
+ const oldRight = last.next;
688
+ const newRight = this.byStart[index];
689
+ if (!newRight && last === this.lastChunk)
690
+ return this;
691
+ const newLeft = newRight ? newRight.previous : this.lastChunk;
692
+ if (oldLeft)
693
+ oldLeft.next = oldRight;
694
+ if (oldRight)
695
+ oldRight.previous = oldLeft;
696
+ if (newLeft)
697
+ newLeft.next = first;
698
+ if (newRight)
699
+ newRight.previous = last;
700
+ if (!first.previous)
701
+ this.firstChunk = last.next;
702
+ if (!last.next) {
703
+ this.lastChunk = first.previous;
704
+ this.lastChunk.next = null;
705
+ }
706
+ first.previous = newLeft;
707
+ last.next = newRight || null;
708
+ if (!newLeft)
709
+ this.firstChunk = first;
710
+ if (!newRight)
711
+ this.lastChunk = last;
712
+ return this;
713
+ }
714
+ overwrite(start, end, content, options) {
715
+ options = options || {};
716
+ return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
717
+ }
718
+ update(start, end, content, options) {
719
+ start = start + this.offset;
720
+ end = end + this.offset;
721
+ if (typeof content !== "string")
722
+ throw new TypeError("replacement content must be a string");
723
+ if (this.original.length !== 0) {
724
+ while (start < 0)
725
+ start += this.original.length;
726
+ while (end < 0)
727
+ end += this.original.length;
728
+ }
729
+ if (end > this.original.length)
730
+ throw new Error("end is out of bounds");
731
+ if (start === end)
732
+ throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");
733
+ this._split(start);
734
+ this._split(end);
735
+ if (options === true) {
736
+ if (!warned.storeName) {
737
+ console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
738
+ warned.storeName = true;
739
+ }
740
+ options = { storeName: true };
741
+ }
742
+ const storeName = options !== undefined ? options.storeName : false;
743
+ const overwrite = options !== undefined ? options.overwrite : false;
744
+ if (storeName) {
745
+ const original = this.original.slice(start, end);
746
+ Object.defineProperty(this.storedNames, original, {
747
+ writable: true,
748
+ value: true,
749
+ enumerable: true
750
+ });
751
+ }
752
+ const first = this.byStart[start];
753
+ const last = this.byEnd[end];
754
+ if (first) {
755
+ let chunk = first;
756
+ while (chunk !== last) {
757
+ if (chunk.next !== this.byStart[chunk.end]) {
758
+ throw new Error("Cannot overwrite across a split point");
759
+ }
760
+ chunk = chunk.next;
761
+ chunk.edit("", false);
762
+ }
763
+ first.edit(content, storeName, !overwrite);
764
+ } else {
765
+ const newChunk = new Chunk(start, end, "").edit(content, storeName);
766
+ last.next = newChunk;
767
+ newChunk.previous = last;
768
+ }
769
+ return this;
770
+ }
771
+ prepend(content) {
772
+ if (typeof content !== "string")
773
+ throw new TypeError("outro content must be a string");
774
+ this.intro = content + this.intro;
775
+ return this;
776
+ }
777
+ prependLeft(index, content) {
778
+ index = index + this.offset;
779
+ if (typeof content !== "string")
780
+ throw new TypeError("inserted content must be a string");
781
+ this._split(index);
782
+ const chunk = this.byEnd[index];
783
+ if (chunk) {
784
+ chunk.prependLeft(content);
785
+ } else {
786
+ this.intro = content + this.intro;
787
+ }
788
+ return this;
789
+ }
790
+ prependRight(index, content) {
791
+ index = index + this.offset;
792
+ if (typeof content !== "string")
793
+ throw new TypeError("inserted content must be a string");
794
+ this._split(index);
795
+ const chunk = this.byStart[index];
796
+ if (chunk) {
797
+ chunk.prependRight(content);
798
+ } else {
799
+ this.outro = content + this.outro;
800
+ }
801
+ return this;
802
+ }
803
+ remove(start, end) {
804
+ start = start + this.offset;
805
+ end = end + this.offset;
806
+ if (this.original.length !== 0) {
807
+ while (start < 0)
808
+ start += this.original.length;
809
+ while (end < 0)
810
+ end += this.original.length;
811
+ }
812
+ if (start === end)
813
+ return this;
814
+ if (start < 0 || end > this.original.length)
815
+ throw new Error("Character is out of bounds");
816
+ if (start > end)
817
+ throw new Error("end must be greater than start");
818
+ this._split(start);
819
+ this._split(end);
820
+ let chunk = this.byStart[start];
821
+ while (chunk) {
822
+ chunk.intro = "";
823
+ chunk.outro = "";
824
+ chunk.edit("");
825
+ chunk = end > chunk.end ? this.byStart[chunk.end] : null;
826
+ }
827
+ return this;
828
+ }
829
+ reset(start, end) {
830
+ start = start + this.offset;
831
+ end = end + this.offset;
832
+ if (this.original.length !== 0) {
833
+ while (start < 0)
834
+ start += this.original.length;
835
+ while (end < 0)
836
+ end += this.original.length;
837
+ }
838
+ if (start === end)
839
+ return this;
840
+ if (start < 0 || end > this.original.length)
841
+ throw new Error("Character is out of bounds");
842
+ if (start > end)
843
+ throw new Error("end must be greater than start");
844
+ this._split(start);
845
+ this._split(end);
846
+ let chunk = this.byStart[start];
847
+ while (chunk) {
848
+ chunk.reset();
849
+ chunk = end > chunk.end ? this.byStart[chunk.end] : null;
850
+ }
851
+ return this;
852
+ }
853
+ lastChar() {
854
+ if (this.outro.length)
855
+ return this.outro[this.outro.length - 1];
856
+ let chunk = this.lastChunk;
857
+ do {
858
+ if (chunk.outro.length)
859
+ return chunk.outro[chunk.outro.length - 1];
860
+ if (chunk.content.length)
861
+ return chunk.content[chunk.content.length - 1];
862
+ if (chunk.intro.length)
863
+ return chunk.intro[chunk.intro.length - 1];
864
+ } while (chunk = chunk.previous);
865
+ if (this.intro.length)
866
+ return this.intro[this.intro.length - 1];
867
+ return "";
868
+ }
869
+ lastLine() {
870
+ let lineIndex = this.outro.lastIndexOf(n);
871
+ if (lineIndex !== -1)
872
+ return this.outro.substr(lineIndex + 1);
873
+ let lineStr = this.outro;
874
+ let chunk = this.lastChunk;
875
+ do {
876
+ if (chunk.outro.length > 0) {
877
+ lineIndex = chunk.outro.lastIndexOf(n);
878
+ if (lineIndex !== -1)
879
+ return chunk.outro.substr(lineIndex + 1) + lineStr;
880
+ lineStr = chunk.outro + lineStr;
881
+ }
882
+ if (chunk.content.length > 0) {
883
+ lineIndex = chunk.content.lastIndexOf(n);
884
+ if (lineIndex !== -1)
885
+ return chunk.content.substr(lineIndex + 1) + lineStr;
886
+ lineStr = chunk.content + lineStr;
887
+ }
888
+ if (chunk.intro.length > 0) {
889
+ lineIndex = chunk.intro.lastIndexOf(n);
890
+ if (lineIndex !== -1)
891
+ return chunk.intro.substr(lineIndex + 1) + lineStr;
892
+ lineStr = chunk.intro + lineStr;
893
+ }
894
+ } while (chunk = chunk.previous);
895
+ lineIndex = this.intro.lastIndexOf(n);
896
+ if (lineIndex !== -1)
897
+ return this.intro.substr(lineIndex + 1) + lineStr;
898
+ return this.intro + lineStr;
899
+ }
900
+ slice(start = 0, end = this.original.length - this.offset) {
901
+ start = start + this.offset;
902
+ end = end + this.offset;
903
+ if (this.original.length !== 0) {
904
+ while (start < 0)
905
+ start += this.original.length;
906
+ while (end < 0)
907
+ end += this.original.length;
908
+ }
909
+ let result = "";
910
+ let chunk = this.firstChunk;
911
+ while (chunk && (chunk.start > start || chunk.end <= start)) {
912
+ if (chunk.start < end && chunk.end >= end) {
913
+ return result;
914
+ }
915
+ chunk = chunk.next;
916
+ }
917
+ if (chunk && chunk.edited && chunk.start !== start)
918
+ throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
919
+ const startChunk = chunk;
920
+ while (chunk) {
921
+ if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
922
+ result += chunk.intro;
923
+ }
924
+ const containsEnd = chunk.start < end && chunk.end >= end;
925
+ if (containsEnd && chunk.edited && chunk.end !== end)
926
+ throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
927
+ const sliceStart = startChunk === chunk ? start - chunk.start : 0;
928
+ const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
929
+ result += chunk.content.slice(sliceStart, sliceEnd);
930
+ if (chunk.outro && (!containsEnd || chunk.end === end)) {
931
+ result += chunk.outro;
932
+ }
933
+ if (containsEnd) {
934
+ break;
935
+ }
936
+ chunk = chunk.next;
937
+ }
938
+ return result;
939
+ }
940
+ snip(start, end) {
941
+ const clone = this.clone();
942
+ clone.remove(0, start);
943
+ clone.remove(end, clone.original.length);
944
+ return clone;
945
+ }
946
+ _split(index) {
947
+ if (this.byStart[index] || this.byEnd[index])
948
+ return;
949
+ let chunk = this.lastSearchedChunk;
950
+ let previousChunk = chunk;
951
+ const searchForward = index > chunk.end;
952
+ while (chunk) {
953
+ if (chunk.contains(index))
954
+ return this._splitChunk(chunk, index);
955
+ chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
956
+ if (chunk === previousChunk)
957
+ return;
958
+ previousChunk = chunk;
959
+ }
960
+ }
961
+ _splitChunk(chunk, index) {
962
+ if (chunk.edited && chunk.content.length) {
963
+ const loc = getLocator(this.original)(index);
964
+ throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`);
965
+ }
966
+ const newChunk = chunk.split(index);
967
+ this.byEnd[index] = chunk;
968
+ this.byStart[index] = newChunk;
969
+ this.byEnd[newChunk.end] = newChunk;
970
+ if (chunk === this.lastChunk)
971
+ this.lastChunk = newChunk;
972
+ this.lastSearchedChunk = chunk;
973
+ return true;
974
+ }
975
+ toString() {
976
+ let str = this.intro;
977
+ let chunk = this.firstChunk;
978
+ while (chunk) {
979
+ str += chunk.toString();
980
+ chunk = chunk.next;
981
+ }
982
+ return str + this.outro;
983
+ }
984
+ isEmpty() {
985
+ let chunk = this.firstChunk;
986
+ do {
987
+ if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
988
+ return false;
989
+ } while (chunk = chunk.next);
990
+ return true;
991
+ }
992
+ length() {
993
+ let chunk = this.firstChunk;
994
+ let length = 0;
995
+ do {
996
+ length += chunk.intro.length + chunk.content.length + chunk.outro.length;
997
+ } while (chunk = chunk.next);
998
+ return length;
999
+ }
1000
+ trimLines() {
1001
+ return this.trim("[\\r\\n]");
1002
+ }
1003
+ trim(charType) {
1004
+ return this.trimStart(charType).trimEnd(charType);
1005
+ }
1006
+ trimEndAborted(charType) {
1007
+ const rx = new RegExp((charType || "\\s") + "+$");
1008
+ this.outro = this.outro.replace(rx, "");
1009
+ if (this.outro.length)
1010
+ return true;
1011
+ let chunk = this.lastChunk;
1012
+ do {
1013
+ const end = chunk.end;
1014
+ const aborted = chunk.trimEnd(rx);
1015
+ if (chunk.end !== end) {
1016
+ if (this.lastChunk === chunk) {
1017
+ this.lastChunk = chunk.next;
1018
+ }
1019
+ this.byEnd[chunk.end] = chunk;
1020
+ this.byStart[chunk.next.start] = chunk.next;
1021
+ this.byEnd[chunk.next.end] = chunk.next;
1022
+ }
1023
+ if (aborted)
1024
+ return true;
1025
+ chunk = chunk.previous;
1026
+ } while (chunk);
1027
+ return false;
1028
+ }
1029
+ trimEnd(charType) {
1030
+ this.trimEndAborted(charType);
1031
+ return this;
1032
+ }
1033
+ trimStartAborted(charType) {
1034
+ const rx = new RegExp("^" + (charType || "\\s") + "+");
1035
+ this.intro = this.intro.replace(rx, "");
1036
+ if (this.intro.length)
1037
+ return true;
1038
+ let chunk = this.firstChunk;
1039
+ do {
1040
+ const end = chunk.end;
1041
+ const aborted = chunk.trimStart(rx);
1042
+ if (chunk.end !== end) {
1043
+ if (chunk === this.lastChunk)
1044
+ this.lastChunk = chunk.next;
1045
+ this.byEnd[chunk.end] = chunk;
1046
+ this.byStart[chunk.next.start] = chunk.next;
1047
+ this.byEnd[chunk.next.end] = chunk.next;
1048
+ }
1049
+ if (aborted)
1050
+ return true;
1051
+ chunk = chunk.next;
1052
+ } while (chunk);
1053
+ return false;
1054
+ }
1055
+ trimStart(charType) {
1056
+ this.trimStartAborted(charType);
1057
+ return this;
1058
+ }
1059
+ hasChanged() {
1060
+ return this.original !== this.toString();
1061
+ }
1062
+ _replaceRegexp(searchValue, replacement) {
1063
+ function getReplacement(match, str) {
1064
+ if (typeof replacement === "string") {
1065
+ return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1066
+ if (i === "$")
1067
+ return "$";
1068
+ if (i === "&")
1069
+ return match[0];
1070
+ const num = +i;
1071
+ if (num < match.length)
1072
+ return match[+i];
1073
+ return `$${i}`;
1074
+ });
1075
+ } else {
1076
+ return replacement(...match, match.index, str, match.groups);
1077
+ }
1078
+ }
1079
+ function matchAll(re, str) {
1080
+ let match;
1081
+ const matches = [];
1082
+ while (match = re.exec(str)) {
1083
+ matches.push(match);
1084
+ }
1085
+ return matches;
1086
+ }
1087
+ if (searchValue.global) {
1088
+ const matches = matchAll(searchValue, this.original);
1089
+ matches.forEach((match) => {
1090
+ if (match.index != null) {
1091
+ const replacement2 = getReplacement(match, this.original);
1092
+ if (replacement2 !== match[0]) {
1093
+ this.overwrite(match.index, match.index + match[0].length, replacement2);
1094
+ }
1095
+ }
1096
+ });
1097
+ } else {
1098
+ const match = this.original.match(searchValue);
1099
+ if (match && match.index != null) {
1100
+ const replacement2 = getReplacement(match, this.original);
1101
+ if (replacement2 !== match[0]) {
1102
+ this.overwrite(match.index, match.index + match[0].length, replacement2);
1103
+ }
1104
+ }
1105
+ }
1106
+ return this;
1107
+ }
1108
+ _replaceString(string, replacement) {
1109
+ const { original } = this;
1110
+ const index = original.indexOf(string);
1111
+ if (index !== -1) {
1112
+ if (typeof replacement === "function") {
1113
+ replacement = replacement(string, index, original);
1114
+ }
1115
+ if (string !== replacement) {
1116
+ this.overwrite(index, index + string.length, replacement);
1117
+ }
1118
+ }
1119
+ return this;
1120
+ }
1121
+ replace(searchValue, replacement) {
1122
+ if (typeof searchValue === "string") {
1123
+ return this._replaceString(searchValue, replacement);
1124
+ }
1125
+ return this._replaceRegexp(searchValue, replacement);
1126
+ }
1127
+ _replaceAllString(string, replacement) {
1128
+ const { original } = this;
1129
+ const stringLength = string.length;
1130
+ for (let index = original.indexOf(string);index !== -1; index = original.indexOf(string, index + stringLength)) {
1131
+ const previous = original.slice(index, index + stringLength);
1132
+ let _replacement = replacement;
1133
+ if (typeof replacement === "function") {
1134
+ _replacement = replacement(previous, index, original);
1135
+ }
1136
+ if (previous !== _replacement)
1137
+ this.overwrite(index, index + stringLength, _replacement);
1138
+ }
1139
+ return this;
1140
+ }
1141
+ replaceAll(searchValue, replacement) {
1142
+ if (typeof searchValue === "string") {
1143
+ return this._replaceAllString(searchValue, replacement);
1144
+ }
1145
+ if (!searchValue.global) {
1146
+ throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
1147
+ }
1148
+ return this._replaceRegexp(searchValue, replacement);
1149
+ }
1150
+ }
1151
+
1152
+ // src/plugin/transform-client.ts
1153
+ import { parseSync } from "oxc-parser";
1154
+ var bunTranspiler = new Bun.Transpiler({
1155
+ loader: "tsx",
1156
+ tsconfig: {
1157
+ compilerOptions: {
1158
+ jsx: "react",
1159
+ jsxFactory: "React.createElement",
1160
+ jsxFragmentFactory: "React.Fragment"
1161
+ }
1162
+ }
1163
+ });
1164
+ var SERVER_ONLY_PROPERTIES = new Set(["loader", "query", "params", "staticParams"]);
1165
+ function walk(node, visitor) {
1166
+ if (!node || typeof node !== "object") {
1167
+ return;
1168
+ }
1169
+ if (Array.isArray(node)) {
1170
+ for (const child of node) {
1171
+ walk(child, visitor);
1172
+ }
1173
+ return;
1174
+ }
1175
+ const n2 = node;
1176
+ if (typeof n2.type === "string") {
1177
+ visitor(n2);
1178
+ }
1179
+ for (const key of Object.keys(n2)) {
1180
+ if (key === "type" || key === "start" || key === "end") {
1181
+ continue;
1182
+ }
1183
+ walk(n2[key], visitor);
1184
+ }
1185
+ }
1186
+ function isCreateRouteCall(node) {
1187
+ return node.callee.type === "Identifier" && node.callee.name === "createRoute";
1188
+ }
1189
+ function isRoutePageCall(node) {
1190
+ const { callee } = node;
1191
+ if (callee.type === "Identifier" && callee.name === "page") {
1192
+ return true;
1193
+ }
1194
+ if (callee.type === "MemberExpression" && callee.property?.name === "page") {
1195
+ return true;
1196
+ }
1197
+ return false;
1198
+ }
1199
+ function isTargetCall(node) {
1200
+ return isCreateRouteCall(node) || isRoutePageCall(node);
1201
+ }
1202
+ function removeServerProperties(s, source, obj) {
1203
+ const toRemove = obj.properties.filter((p) => {
1204
+ if (p.type !== "Property") {
1205
+ return false;
1206
+ }
1207
+ const { key } = p;
1208
+ if (p.computed) {
1209
+ return false;
1210
+ }
1211
+ if (key.type === "Identifier" && typeof key.name === "string") {
1212
+ return SERVER_ONLY_PROPERTIES.has(key.name);
1213
+ }
1214
+ if (key.type === "Literal" && typeof key.value === "string") {
1215
+ return SERVER_ONLY_PROPERTIES.has(key.value);
1216
+ }
1217
+ return false;
1218
+ });
1219
+ if (toRemove.length === 0) {
1220
+ return false;
1221
+ }
1222
+ for (const prop of toRemove) {
1223
+ let removeEnd = prop.end;
1224
+ while (removeEnd < source.length && (source[removeEnd] === "," || source[removeEnd] === " " || source[removeEnd] === `
1225
+ ` || source[removeEnd] === "\r" || source[removeEnd] === "\t")) {
1226
+ if (source[removeEnd] === ",") {
1227
+ removeEnd++;
1228
+ break;
1229
+ }
1230
+ removeEnd++;
1231
+ }
1232
+ let removeStart = prop.start;
1233
+ while (removeStart > 0 && (source[removeStart - 1] === " " || source[removeStart - 1] === "\t")) {
1234
+ removeStart--;
1235
+ }
1236
+ if (removeStart > 0 && source[removeStart - 1] === `
1237
+ `) {
1238
+ removeStart--;
1239
+ if (removeStart > 0 && source[removeStart - 1] === "\r") {
1240
+ removeStart--;
1241
+ }
1242
+ }
1243
+ s.remove(removeStart, removeEnd);
1244
+ }
1245
+ return true;
1246
+ }
1247
+ function collectReferencedNames(program) {
1248
+ const refs = new Set;
1249
+ const excluded = new Set;
1250
+ for (const stmt of program.body ?? []) {
1251
+ if (stmt.type === "ImportDeclaration") {
1252
+ continue;
1253
+ }
1254
+ walk(stmt, (node) => {
1255
+ if (node.type === "Property" && !node.computed) {
1256
+ excluded.add(node.key);
1257
+ }
1258
+ if (node.type === "MemberExpression" && !node.computed) {
1259
+ excluded.add(node.property);
1260
+ }
1261
+ });
1262
+ }
1263
+ for (const stmt of program.body ?? []) {
1264
+ if (stmt.type === "ImportDeclaration") {
1265
+ continue;
1266
+ }
1267
+ walk(stmt, (node) => {
1268
+ if (excluded.has(node)) {
1269
+ return;
1270
+ }
1271
+ if (node.type === "Identifier" && typeof node.name === "string") {
1272
+ refs.add(node.name);
1273
+ }
1274
+ });
1275
+ }
1276
+ return refs;
1277
+ }
1278
+ function removeEntireImport(s, code, decl) {
1279
+ let removeEnd = decl.end;
1280
+ while (removeEnd < code.length && (code[removeEnd] === `
1281
+ ` || code[removeEnd] === "\r")) {
1282
+ removeEnd++;
1283
+ }
1284
+ s.remove(decl.start, removeEnd);
1285
+ }
1286
+ function removeUnusedSpecifiers(s, code, decl, refs) {
1287
+ const removedSpecs = decl.specifiers.filter((spec) => !refs.has(spec.local.name));
1288
+ for (const spec of removedSpecs) {
1289
+ let removeStart = spec.start;
1290
+ let removeEnd = spec.end;
1291
+ while (removeEnd < code.length && (code[removeEnd] === "," || code[removeEnd] === " ")) {
1292
+ removeEnd++;
1293
+ }
1294
+ if (!code.slice(spec.end, removeEnd).includes(",")) {
1295
+ while (removeStart > 0 && (code[removeStart - 1] === " " || code[removeStart - 1] === ",")) {
1296
+ removeStart--;
1297
+ }
1298
+ }
1299
+ s.remove(removeStart, removeEnd);
1300
+ }
1301
+ }
1302
+ function deadCodeElimination(s) {
1303
+ const code = s.toString();
1304
+ const { program, errors } = parseSync("dce.js", code);
1305
+ if (errors.length > 0) {
1306
+ console.error("[furin] DCE: failed to parse transformed output:", errors[0]?.message);
1307
+ return s;
1308
+ }
1309
+ const fresh = new MagicString(code);
1310
+ const programNode = program;
1311
+ const refs = collectReferencedNames(programNode);
1312
+ const body = programNode.body ?? [];
1313
+ for (let i = body.length - 1;i >= 0; i--) {
1314
+ const stmt = body[i];
1315
+ if (!stmt) {
1316
+ continue;
1317
+ }
1318
+ if (stmt.type !== "ImportDeclaration") {
1319
+ continue;
1320
+ }
1321
+ const decl = stmt;
1322
+ if (!decl.specifiers || decl.specifiers.length === 0) {
1323
+ continue;
1324
+ }
1325
+ const usedCount = decl.specifiers.filter((spec) => refs.has(spec.local.name)).length;
1326
+ if (usedCount === 0) {
1327
+ removeEntireImport(fresh, code, decl);
1328
+ } else if (usedCount < decl.specifiers.length) {
1329
+ removeUnusedSpecifiers(fresh, code, decl, refs);
1330
+ }
1331
+ }
1332
+ return fresh;
1333
+ }
1334
+ function removeServerExports(s, source, program) {
1335
+ let removedServerCode = false;
1336
+ walk(program, (node) => {
1337
+ if (node.type !== "CallExpression") {
1338
+ return;
1339
+ }
1340
+ const call = node;
1341
+ if (!isTargetCall(call)) {
1342
+ return;
1343
+ }
1344
+ const arg = call.arguments[0];
1345
+ if (!arg || arg.type !== "ObjectExpression") {
1346
+ return;
1347
+ }
1348
+ if (removeServerProperties(s, source, arg)) {
1349
+ removedServerCode = true;
1350
+ }
1351
+ });
1352
+ return removedServerCode;
1353
+ }
1354
+ function transformForClient(code, filename) {
1355
+ const plainJs = bunTranspiler.transformSync(code);
1356
+ const { program, errors } = parseSync(filename, plainJs);
1357
+ if (errors.length > 0) {
1358
+ throw new Error(`Failed to parse ${filename}: ${errors[0]?.message}`);
1359
+ }
1360
+ let s = new MagicString(plainJs);
1361
+ const removedServerCode = removeServerExports(s, plainJs, program);
1362
+ if (removedServerCode) {
1363
+ s = deadCodeElimination(s);
1364
+ }
1365
+ return {
1366
+ code: s.toString(),
1367
+ map: s.generateMap({ source: filename, includeContent: true }),
1368
+ removedServerCode
1369
+ };
1370
+ }
1371
+
1372
+ // src/build/hydrate.ts
1373
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
1374
+ import { join as join2 } from "path";
1375
+
1376
+ // src/render/shell.ts
1377
+ function extractTitle(meta) {
1378
+ if (!meta) {
1379
+ return;
1380
+ }
1381
+ for (const entry of meta) {
1382
+ if ("title" in entry) {
1383
+ return entry.title;
1384
+ }
1385
+ }
1386
+ return;
1387
+ }
1388
+ function isMetaTag(entry) {
1389
+ return !(("title" in entry) || ("charSet" in entry) || ("script:ld+json" in entry) || ("tagName" in entry));
1390
+ }
1391
+ function escapeHtml(str) {
1392
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
1393
+ }
1394
+ function safeJson(value) {
1395
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1396
+ }
1397
+ function renderAttrs(obj) {
1398
+ return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
1399
+ }
1400
+ function buildMetaParts(meta) {
1401
+ const parts = [];
1402
+ const title = extractTitle(meta);
1403
+ if (title) {
1404
+ parts.push(`<title>${escapeHtml(title)}</title>`);
1405
+ }
1406
+ for (const m of meta) {
1407
+ if (isMetaTag(m)) {
1408
+ parts.push(`<meta ${renderAttrs(m)} />`);
1409
+ }
1410
+ if ("script:ld+json" in m) {
1411
+ parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
1412
+ }
1413
+ }
1414
+ return parts;
1415
+ }
1416
+ function buildLinkParts(links) {
1417
+ return links.map((link) => `<link ${renderAttrs(link)} />`);
1418
+ }
1419
+ function buildScriptParts(scripts) {
1420
+ return scripts.map((script) => {
1421
+ const { children, ...rest } = script;
1422
+ const attrs = renderAttrs(rest);
1423
+ if (children) {
1424
+ return `<script ${attrs}>${children}</script>`;
1425
+ }
1426
+ return `<script ${attrs}></script>`;
1427
+ });
1428
+ }
1429
+ function buildStyleParts(styles) {
1430
+ return styles.map((style) => {
1431
+ const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
1432
+ return `<style${typeAttr}>${style.children}</style>`;
1433
+ });
1434
+ }
1435
+ function buildHeadInjection(headData) {
1436
+ const parts = [];
1437
+ if (headData?.meta) {
1438
+ parts.push(...buildMetaParts(headData.meta));
1439
+ }
1440
+ if (headData?.links) {
1441
+ parts.push(...buildLinkParts(headData.links));
1442
+ }
1443
+ if (headData?.scripts) {
1444
+ parts.push(...buildScriptParts(headData.scripts));
1445
+ }
1446
+ if (headData?.styles) {
1447
+ parts.push(...buildStyleParts(headData.styles));
1448
+ }
1449
+ return parts.length > 0 ? `
1450
+ ${parts.join(`
1451
+ `)}
1452
+ ` : "";
1453
+ }
1454
+ 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>`;
1455
+ function generateIndexHtml() {
1456
+ return `<!DOCTYPE html>
1457
+ <html lang="en">
1458
+ <head>
1459
+ <meta charset="UTF-8">
1460
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1461
+ ${THEME_INIT_SCRIPT}
1462
+ <!--ssr-head-->
1463
+ </head>
1464
+ <body>
1465
+ <div id="root"><!--ssr-outlet--></div>
1466
+ <script type="module" src="./_hydrate.tsx"></script>
1467
+ </body>
1468
+ </html>
1469
+ `;
1470
+ }
1471
+ function generateProdIndexHtml(entryChunk, cssChunks, buildId, faviconHref) {
1472
+ const cssLinks = cssChunks.map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`).join(`
1473
+ `);
1474
+ const scriptTag = `<script type="module" crossorigin src="${entryChunk}"></script>`;
1475
+ const buildIdMeta = buildId ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">
1476
+ ` : "";
1477
+ const faviconLink = faviconHref ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">
1478
+ ` : "";
1479
+ return `<!DOCTYPE html>
1480
+ <html lang="en">
1481
+ <head>
1482
+ <meta charset="UTF-8">
1483
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1484
+ ${THEME_INIT_SCRIPT}
1485
+ ${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}
1486
+ ` : ""} <!--ssr-head-->
1487
+ </head>
1488
+ <body>
1489
+ <div id="root"><!--ssr-outlet--></div>
1490
+ ${scriptTag}
1491
+ </body>
1492
+ </html>
1493
+ `;
1494
+ }
1495
+
1496
+ // src/build/route-types.ts
1497
+ import { existsSync, readFileSync, writeFileSync } from "fs";
1498
+ import { join } from "path";
1499
+ function patternToTypeString(pattern) {
1500
+ const t = pattern.replace(/:[^/]+/g, "${string}").replace(/\*/g, "${string}");
1501
+ return t.includes("${") ? `\`${t}\`` : `"${t}"`;
1502
+ }
1503
+ function schemaToTypeString(schema) {
1504
+ if (!schema || typeof schema !== "object") {
1505
+ return "unknown";
1506
+ }
1507
+ const s = schema;
1508
+ if (s.anyOf && Array.isArray(s.anyOf)) {
1509
+ const parts = s.anyOf.map(schemaToTypeString).filter((t) => t !== "null");
1510
+ return parts.join(" | ") || "unknown";
1511
+ }
1512
+ switch (s.type) {
1513
+ case "string":
1514
+ return "string";
1515
+ case "number":
1516
+ case "integer":
1517
+ return "number";
1518
+ case "boolean":
1519
+ return "boolean";
1520
+ case "null":
1521
+ return "null";
1522
+ case "object": {
1523
+ if (!s.properties || typeof s.properties !== "object") {
1524
+ return "Record<string, unknown>";
1525
+ }
1526
+ const required = new Set(Array.isArray(s.required) ? s.required : []);
1527
+ const props = Object.entries(s.properties).map(([k, v]) => `${k}${required.has(k) ? "" : "?"}: ${schemaToTypeString(v)}`).join("; ");
1528
+ return `{ ${props} }`;
1529
+ }
1530
+ default:
1531
+ return "unknown";
1532
+ }
1533
+ }
1534
+ function writeRouteTypes(routes, projectRoot) {
1535
+ const entries = routes.map((r) => {
1536
+ const typeKey = patternToTypeString(r.pattern);
1537
+ const isDynamic = typeKey.startsWith("`");
1538
+ const querySchema = r.routeChain?.find((rt) => rt.query)?.query;
1539
+ const searchType = querySchema ? schemaToTypeString(querySchema) : "never";
1540
+ return isDynamic ? ` [key: ${typeKey}]: { search?: ${searchType} }` : ` ${typeKey}: { search?: ${searchType} }`;
1541
+ });
1542
+ const content = `// Auto-generated by Furin. Do not edit manually.
1543
+ /// <reference types="@teyik0/furin/env" />
1544
+ import "@teyik0/furin/link";
1545
+
1546
+ declare module "@teyik0/furin/link" {
1547
+ interface RouteManifest {
1548
+ ${entries.join(`;
1549
+ `)};
1550
+ }
1551
+ }
1552
+ `;
1553
+ const typesPath = join(projectRoot, "furin-env.d.ts");
1554
+ const existing = existsSync(typesPath) ? readFileSync(typesPath, "utf8") : "";
1555
+ if (content !== existing) {
1556
+ writeFileSync(typesPath, content);
1557
+ }
1558
+ }
1559
+
1560
+ // src/build/hydrate.ts
1561
+ function generateHydrateEntry(routes, rootLayout, basePath) {
1562
+ const conventionIdents = new Map;
1563
+ const getIdent = (filePath) => {
1564
+ if (!filePath) {
1565
+ return;
1566
+ }
1567
+ const existing = conventionIdents.get(filePath);
1568
+ if (existing) {
1569
+ return existing;
1570
+ }
1571
+ const ident = `__furin_bnd_${conventionIdents.size}`;
1572
+ conventionIdents.set(filePath, ident);
1573
+ return ident;
1574
+ };
1575
+ const routeEntries = [];
1576
+ for (const route of routes) {
1577
+ const resolvedPage = route.path.replace(/\\/g, "/");
1578
+ const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
1579
+ const boundaryLiterals = [];
1580
+ for (const seg of route.segmentBoundaries ?? []) {
1581
+ const errorIdent = getIdent(seg.errorPath);
1582
+ const notFoundIdent = getIdent(seg.notFoundPath);
1583
+ if (!(errorIdent || notFoundIdent)) {
1584
+ continue;
1585
+ }
1586
+ const parts = [`depth: ${seg.depth}`];
1587
+ if (errorIdent) {
1588
+ parts.push(`error: ${errorIdent}`);
1589
+ }
1590
+ if (notFoundIdent) {
1591
+ parts.push(`notFound: ${notFoundIdent}`);
1592
+ }
1593
+ boundaryLiterals.push(`{ ${parts.join(", ")} }`);
1594
+ }
1595
+ const boundariesField = boundaryLiterals.length > 0 ? `, segmentBoundaries: [${boundaryLiterals.join(", ")}]` : "";
1596
+ routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}")${boundariesField} }`);
1597
+ }
1598
+ const conventionImportLines = [...conventionIdents.entries()].map(([filePath, ident]) => `import ${ident} from "${filePath.replace(/\\/g, "/")}";`).join(`
1599
+ `);
1600
+ const basePathLiteral = JSON.stringify(basePath);
1601
+ const pathnameExpr = basePath ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; return (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; })()` : "window.location.pathname";
1602
+ const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
1603
+ const basePathProp = basePath ? `
1604
+ basePath: ${basePathLiteral},` : "";
1605
+ const conventionImportsBlock = conventionImportLines ? `
1606
+ ${conventionImportLines}` : "";
1607
+ return `import { hydrateRoot, createRoot } from "react-dom/client";
1608
+ import { createElement } from "react";
1609
+ import { initLogger, log } from "evlog";
1610
+ import { createHttpLogDrain } from "evlog/http";
1611
+ import { RouterProvider } from "@teyik0/furin/link";
1612
+ import { route as root } from "${rootLayout.replace(/\\/g, "/")}";${conventionImportsBlock}
1613
+
1614
+ initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
1615
+
1616
+ const routes = [
1617
+ ${routeEntries.join(`,
1618
+ `)}
1619
+ ];
1620
+
1621
+ const pathname = ${pathnameExpr};
1622
+ const _match = routes.find((r) => r.regex.test(pathname));
1623
+
1624
+ // Parse the server-embedded loader payload up front. It carries:
1625
+ // - normal loader props under arbitrary keys,
1626
+ // - __furinError.digest when SSR caught an error,
1627
+ // - __furinStatus: 404 when the server rendered the catch-all not-found
1628
+ // (direct load to an unknown URL, emitted by renderRootNotFound) OR when
1629
+ // a matched loader threw notFound(). The latter still has a _match; the
1630
+ // former does not \u2014 so the two cases fork on _match below.
1631
+ const dataEl = document.getElementById("__FURIN_DATA__");
1632
+ const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
1633
+ const rootEl = document.getElementById("root") as HTMLElement;
1634
+
1635
+ // Eagerly load only the current page module for initial hydration.
1636
+ // All other pages are loaded on demand when the user navigates to them.
1637
+ // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
1638
+ // bundler to misidentify which chunk to reference as the entry in index.html.
1639
+ (async () => {
1640
+ let app;
1641
+ if (_match) {
1642
+ const _mod = await _match.load();
1643
+ const match = { ..._match, component: _mod.default.component, pageRoute: _mod.default._route };
1644
+
1645
+ const isNotFound = loaderData.__furinStatus === 404;
1646
+
1647
+ app = createElement(RouterProvider, {
1648
+ routes,
1649
+ root,
1650
+ initialMatch: match,
1651
+ initialData: loaderData,
1652
+ initialDigest: loaderData.__furinError?.digest,
1653
+ initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${basePathProp}
1654
+ } as any);
1655
+ } else if (loaderData.__furinStatus === 404) {
1656
+ // Direct load to an unknown URL. The server sent the root not-found UI
1657
+ // already rendered into the DOM. Mount RouterProvider with a null match
1658
+ // so the provider boots into its not-found branch, hydrating that exact
1659
+ // tree INSIDE a live RouterContext. Without this, Links in the 404 UI
1660
+ // (e.g. the default screen's "Go Home" button) hit the useRouter()
1661
+ // fallback that does a full window.location assignment \u2014 a jarring reload.
1662
+ // Strip the server-only signal keys before handing data to components.
1663
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = loaderData;
1664
+ app = createElement(RouterProvider, {
1665
+ routes,
1666
+ root,
1667
+ initialMatch: null,
1668
+ initialData: cleanData,
1669
+ initialDigest: loaderData.__furinError?.digest,
1670
+ initialNotFound: loaderData.__furinNotFound ?? {},${basePathProp}
1671
+ } as any);
1672
+ } else {
1673
+ // No match and no 404 signal \u2014 either the client bundle is out of sync
1674
+ // with the server (stale deploy) or the server returned something we
1675
+ // don't know how to hydrate. Bail loudly; the page stays static.
1676
+ log.error({ action: "hydrate_no_match", pathname });
1677
+ return;
1678
+ }
1679
+
1680
+ if (import.meta.hot) {
1681
+ // Dev mode \u2014 preserve root across HMR using a window global.
1682
+ // window is the only object that survives Bun's module re-evaluation.
1683
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
1684
+ const existingRoot = (window as any).__FURIN_ROOT__;
1685
+ if (existingRoot) {
1686
+ // Already mounted \u2014 reconciliation, NOT hydration. React Fast Refresh
1687
+ // patched the component in-place, now re-render with the new module.
1688
+ existingRoot.render(app);
1689
+ // The initialData embedded in the DOM is stale (from the original SSR).
1690
+ // Trigger a loader-data refresh so the component renders with fresh
1691
+ // server state, avoiding hydration mismatches after a _route.tsx edit.
1692
+ const hmrRefresh = (window as any).__FURIN_HMR_REFRESH__;
1693
+ if (hmrRefresh) {
1694
+ requestAnimationFrame(() => hmrRefresh());
1695
+ }
1696
+ } else if (rootEl.innerHTML.trim()) {
1697
+ // First load with SSR content \u2014 hydrateRoot renders on construction
1698
+ const root = hydrateRoot(rootEl, app);
1699
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
1700
+ (window as any).__FURIN_ROOT__ = root;
1701
+ } else {
1702
+ // First load without SSR content \u2014 createRoot requires explicit .render()
1703
+ const root = createRoot(rootEl);
1704
+ root.render(app);
1705
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
1706
+ (window as any).__FURIN_ROOT__ = root;
1707
+ }
1708
+ } else if (rootEl.innerHTML.trim()) {
1709
+ hydrateRoot(rootEl, app);
1710
+ } else {
1711
+ createRoot(rootEl).render(app);
1712
+ }
1713
+
1714
+ log.info({ action: "hydrate_complete", pathname });
1715
+ })().catch((err: unknown) => {
1716
+ log.error({ action: "hydrate_failed", pathname, error: String(err) });
1717
+ });
1718
+ `;
1719
+ }
1720
+ function writeDevFiles(routes, { outDir, rootLayout, basePath }, projectRoot) {
1721
+ if (!existsSync2(outDir)) {
1722
+ mkdirSync(outDir, { recursive: true });
1723
+ }
1724
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
1725
+ const hydratePath = join2(outDir, "_hydrate.tsx");
1726
+ const existingHydrate = existsSync2(hydratePath) ? readFileSync2(hydratePath, "utf8") : "";
1727
+ if (hydrateCode !== existingHydrate) {
1728
+ writeFileSync2(hydratePath, hydrateCode);
1729
+ }
1730
+ const indexHtml = generateIndexHtml();
1731
+ const indexPath = join2(outDir, "index.html");
1732
+ const existingIndex = existsSync2(indexPath) ? readFileSync2(indexPath, "utf8") : "";
1733
+ if (indexHtml !== existingIndex) {
1734
+ writeFileSync2(indexPath, indexHtml);
1735
+ }
1736
+ writeRouteTypes(routes, projectRoot);
1737
+ console.log("[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)");
1738
+ }
1739
+
1740
+ // src/build/shared.ts
1741
+ import { cpSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readdirSync, rmSync } from "fs";
1742
+ import { join as join3, relative } from "path";
1743
+ var CLIENT_MODULE_PATH = new URL(import.meta.resolve("@teyik0/furin/client")).pathname;
1744
+ var LINK_MODULE_PATH = new URL(import.meta.resolve("@teyik0/furin/link")).pathname;
1745
+ function ensureDir(path) {
1746
+ if (!existsSync3(path)) {
1747
+ mkdirSync2(path, { recursive: true });
1748
+ }
1749
+ }
1750
+ function toPosixPath(path) {
1751
+ return path.replace(/\\/g, "/");
1752
+ }
1753
+ function collectFilesRecursive(dir) {
1754
+ const files = [];
1755
+ const entries = readdirSync(dir, { withFileTypes: true });
1756
+ for (const entry of entries) {
1757
+ const absolutePath = join3(dir, entry.name);
1758
+ if (entry.isDirectory()) {
1759
+ files.push(...collectFilesRecursive(absolutePath));
1760
+ continue;
1761
+ }
1762
+ if (entry.isFile()) {
1763
+ files.push(absolutePath);
1764
+ }
1765
+ }
1766
+ return files.sort();
1767
+ }
1768
+ function copyDirRecursive(sourceDir, targetDir) {
1769
+ rmSync(targetDir, { force: true, recursive: true });
1770
+ cpSync(sourceDir, targetDir, { recursive: true });
1771
+ }
1772
+ function toBuildRouteManifestEntry(route, rootDir) {
1773
+ return {
1774
+ pattern: route.pattern,
1775
+ mode: route.mode,
1776
+ pagePath: toPosixPath(relative(rootDir, route.path)),
1777
+ hasLayout: route.routeChain.some((entry) => !!entry.layout),
1778
+ hasStaticParams: !!route.page?.staticParams,
1779
+ revalidate: route.page?._route.revalidate ?? null
1780
+ };
1781
+ }
1782
+ function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
1783
+ const targetDir = join3(buildRoot, target);
1784
+ return {
1785
+ buildId: "",
1786
+ generatedAt: new Date().toISOString(),
1787
+ targetDir: toPosixPath(relative(rootDir, targetDir)),
1788
+ clientDir: toPosixPath(relative(rootDir, join3(targetDir, "client"))),
1789
+ templatePath: toPosixPath(relative(rootDir, join3(targetDir, "client", "index.html"))),
1790
+ serverPath: null,
1791
+ serverEntry: serverEntry ? toPosixPath(relative(rootDir, serverEntry)) : null
1792
+ };
1793
+ }
1794
+
1795
+ // src/build/client.ts
1796
+ var TS_FILE_FILTER = /\.(tsx|ts)$/;
1797
+ var REACT_IMPORT_RE = /import\s+React\b/;
1798
+ async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath }) {
1799
+ const clientDir = join4(outDir, "client");
1800
+ if (!existsSync4(outDir)) {
1801
+ mkdirSync3(outDir, { recursive: true });
1802
+ }
1803
+ if (!existsSync4(clientDir)) {
1804
+ mkdirSync3(clientDir, { recursive: true });
1805
+ }
1806
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
1807
+ const hydratePath = join4(outDir, "_hydrate.tsx");
1808
+ writeFileSync3(hydratePath, hydrateCode);
1809
+ console.log("[furin] Building production client bundle\u2026");
1810
+ const transformPlugin = {
1811
+ name: "furin-transform-client",
1812
+ setup(build) {
1813
+ build.onLoad({ filter: TS_FILE_FILTER }, async (args) => {
1814
+ const { path } = args;
1815
+ if (path.includes("node_modules")) {
1816
+ return;
1817
+ }
1818
+ const code = await Bun.file(path).text();
1819
+ try {
1820
+ const result2 = transformForClient(code, path);
1821
+ let transformed = result2.code;
1822
+ if (transformed.includes("React.createElement") && !REACT_IMPORT_RE.test(transformed)) {
1823
+ transformed = `import React from "react";
1824
+ ${transformed}`;
1825
+ }
1826
+ transformed = transformed.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH));
1827
+ return {
1828
+ contents: transformed,
1829
+ loader: path.endsWith(".tsx") ? "tsx" : "ts"
1830
+ };
1831
+ } catch (error) {
1832
+ console.error(`[furin] Transform error for ${path}:`, error);
1833
+ return;
1834
+ }
1835
+ });
1836
+ }
1837
+ };
1838
+ const clientBuildConfig = {
1839
+ entrypoints: [hydratePath],
1840
+ outdir: clientDir,
1841
+ target: "browser",
1842
+ format: "esm",
1843
+ splitting: true,
1844
+ minify: true,
1845
+ sourcemap: "linked",
1846
+ naming: {
1847
+ entry: "[dir]/[name]-[hash].[ext]",
1848
+ chunk: "[name]-[hash].[ext]"
1849
+ },
1850
+ publicPath,
1851
+ plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
1852
+ alias: {
1853
+ "@teyik0/furin/client": CLIENT_MODULE_PATH,
1854
+ "@teyik0/furin/link": LINK_MODULE_PATH
1855
+ },
1856
+ define: {
1857
+ "process.env.NODE_ENV": JSON.stringify("production")
1858
+ }
1859
+ };
1860
+ const result = await Bun.build(clientBuildConfig);
1861
+ for (const output of result.outputs) {
1862
+ console.log(`[furin] ${output.path} (${(output.size / 1024).toFixed(1)} KB)`);
1863
+ }
1864
+ const entryOutput = result.outputs.find((o) => o.kind === "entry-point");
1865
+ const cssOutputs = result.outputs.filter((o) => o.path.endsWith(".css") && !o.path.endsWith(".css.map"));
1866
+ if (!entryOutput) {
1867
+ throw new Error("[furin] client build did not emit entry chunk");
1868
+ }
1869
+ let publicPrefix;
1870
+ if (publicPath === "") {
1871
+ publicPrefix = "";
1872
+ } else {
1873
+ publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
1874
+ }
1875
+ const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
1876
+ const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
1877
+ console.log("[furin] Production client build complete");
1878
+ return { entryChunk, cssChunks };
1879
+ }
1880
+
1881
+ // src/build/compile-entry.ts
1882
+ import { existsSync as existsSync5, writeFileSync as writeFileSync4 } from "fs";
1883
+ import { join as join5, relative as relative2 } from "path";
1884
+
1885
+ // src/build/entry-template.ts
1886
+ import { dirname } from "path";
1887
+ var _pkgSrcDir = dirname(new URL(import.meta.resolve("@teyik0/furin")).pathname);
1888
+ var INTERNAL_MODULE_PATH = `${_pkgSrcDir}/internal.ts`;
1889
+ var RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/runtime-env.ts`;
1890
+ function collectConventionPaths(rootConventions, routeMetadata) {
1891
+ const paths = [];
1892
+ if (rootConventions?.errorPath) {
1893
+ paths.push(rootConventions.errorPath);
1894
+ }
1895
+ if (rootConventions?.notFoundPath) {
1896
+ paths.push(rootConventions.notFoundPath);
1897
+ }
1898
+ if (routeMetadata) {
1899
+ for (const meta of Object.values(routeMetadata)) {
1900
+ for (const seg of meta.segmentBoundaries) {
1901
+ if (seg.errorPath) {
1902
+ paths.push(seg.errorPath);
1903
+ }
1904
+ if (seg.notFoundPath) {
1905
+ paths.push(seg.notFoundPath);
1906
+ }
1907
+ }
1908
+ }
1909
+ }
1910
+ return [...new Set(paths)];
1911
+ }
1912
+ function buildEntrySource(options) {
1913
+ const { buildId, headerComment, rootPath, routes, serverEntry, rootConventions, routeMetadata } = options;
1914
+ let { extraImports, extraContext } = options;
1915
+ if (extraImports === undefined) {
1916
+ extraImports = [];
1917
+ }
1918
+ if (extraContext === undefined) {
1919
+ extraContext = [];
1920
+ }
1921
+ const allModulePaths = [
1922
+ rootPath,
1923
+ ...routes.map((r) => r.path),
1924
+ ...collectConventionPaths(rootConventions, routeMetadata)
1925
+ ];
1926
+ const moduleImports = [];
1927
+ const moduleEntries = [];
1928
+ for (let i = 0;i < allModulePaths.length; i++) {
1929
+ const absPath = allModulePaths[i].replace(/\\/g, "/");
1930
+ const varName = `_mod${i}`;
1931
+ moduleImports.push(`import * as ${varName} from ${JSON.stringify(absPath)};`);
1932
+ moduleEntries.push(` ${JSON.stringify(absPath)}: ${varName},`);
1933
+ }
1934
+ const routeEntries = routes.map((r) => ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`);
1935
+ const rootConventionsLine = rootConventions ? ` rootConventions: ${JSON.stringify(rootConventions)},` : "";
1936
+ const routeMetadataLine = routeMetadata ? ` routeMetadata: ${JSON.stringify(routeMetadata)},` : "";
1937
+ const lines = [
1938
+ headerComment,
1939
+ `import { __setCompileContext } from ${JSON.stringify(INTERNAL_MODULE_PATH)};`,
1940
+ `import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`,
1941
+ ...moduleImports,
1942
+ ...extraImports.length > 0 ? ["", ...extraImports] : [],
1943
+ "",
1944
+ "// Force production mode \u2014 Bun may inline process.env.NODE_ENV at bundle time.",
1945
+ "__setDevMode(false);",
1946
+ 'process.env.NODE_ENV = "production";',
1947
+ "",
1948
+ "__setCompileContext({",
1949
+ ` buildId: ${JSON.stringify(buildId ?? "")},`,
1950
+ ` rootPath: ${JSON.stringify(rootPath.replace(/\\/g, "/"))},`,
1951
+ rootConventionsLine,
1952
+ " modules: {",
1953
+ ...moduleEntries,
1954
+ " },",
1955
+ " routes: [",
1956
+ ...routeEntries,
1957
+ " ],",
1958
+ routeMetadataLine,
1959
+ ...extraContext,
1960
+ "});",
1961
+ "",
1962
+ `await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
1963
+ ""
1964
+ ];
1965
+ return lines.join(`
1966
+ `);
1967
+ }
1968
+
1969
+ // src/build/compile-entry.ts
1970
+ function generateCompileEntry(options) {
1971
+ const {
1972
+ buildId,
1973
+ outDir,
1974
+ rootPath,
1975
+ routes,
1976
+ serverEntry,
1977
+ embed,
1978
+ publicDir,
1979
+ rootConventions,
1980
+ routeMetadata
1981
+ } = options;
1982
+ ensureDir(outDir);
1983
+ const assetImports = [];
1984
+ let embeddedBlock = [];
1985
+ if (embed) {
1986
+ if (!existsSync5(embed.clientDir)) {
1987
+ throw new Error(`[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`);
1988
+ }
1989
+ const clientFiles = collectFilesRecursive(embed.clientDir);
1990
+ const assetEntries = [];
1991
+ let templateVarName = null;
1992
+ let assetIndex = 0;
1993
+ for (const file of clientFiles) {
1994
+ const varName = `_asset${assetIndex++}`;
1995
+ const relPath = toPosixPath(relative2(outDir, file));
1996
+ const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
1997
+ assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
1998
+ const clientRelativePath = toPosixPath(relative2(embed.clientDir, file));
1999
+ if (clientRelativePath === "index.html") {
2000
+ templateVarName = varName;
2001
+ } else {
2002
+ assetEntries.push(` ${JSON.stringify(`/_client/${clientRelativePath}`)}: ${varName},`);
2003
+ }
2004
+ }
2005
+ if (templateVarName === null) {
2006
+ throw new Error(`[furin] Embed mode requires a client index.html at ${join5(embed.clientDir, "index.html")}. Run the client build first.`);
2007
+ }
2008
+ if (publicDir && existsSync5(publicDir)) {
2009
+ const publicFiles = collectFilesRecursive(publicDir);
2010
+ for (const file of publicFiles) {
2011
+ const varName = `_asset${assetIndex++}`;
2012
+ const relPath = toPosixPath(relative2(outDir, file));
2013
+ const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
2014
+ assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
2015
+ const publicRelativePath = toPosixPath(relative2(publicDir, file));
2016
+ assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
2017
+ }
2018
+ }
2019
+ embeddedBlock = [
2020
+ " embedded: {",
2021
+ ` template: ${templateVarName},`,
2022
+ " assets: {",
2023
+ ...assetEntries,
2024
+ " },",
2025
+ " },"
2026
+ ];
2027
+ }
2028
+ const source = buildEntrySource({
2029
+ buildId,
2030
+ headerComment: "// Auto-generated by furin compile \u2014 do not edit",
2031
+ rootPath,
2032
+ routes,
2033
+ serverEntry,
2034
+ extraImports: assetImports,
2035
+ extraContext: embeddedBlock,
2036
+ rootConventions,
2037
+ routeMetadata
2038
+ });
2039
+ const entryPath = join5(outDir, "_compile-entry.ts");
2040
+ writeFileSync4(entryPath, source);
2041
+ return entryPath;
2042
+ }
2043
+
2044
+ // src/build/server-routes-entry.ts
2045
+ import { writeFileSync as writeFileSync5 } from "fs";
2046
+ import { join as join6 } from "path";
2047
+ function generateServerRoutesEntry(options) {
2048
+ const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata } = options;
2049
+ ensureDir(outDir);
2050
+ const source = buildEntrySource({
2051
+ buildId,
2052
+ headerComment: "// Auto-generated by furin build \u2014 do not edit",
2053
+ rootPath,
2054
+ routes,
2055
+ serverEntry,
2056
+ rootConventions,
2057
+ routeMetadata
2058
+ });
2059
+ const entryPath = join6(outDir, "server.ts");
2060
+ writeFileSync5(entryPath, source);
2061
+ return entryPath;
2062
+ }
2063
+
2064
+ // src/adapter/bun.ts
2065
+ var _pkgSrcDir2 = dirname2(fileURLToPath(import.meta.resolve("@teyik0/furin")));
2066
+ var BUILD_ID_INPUT_PATHS = [
2067
+ `${_pkgSrcDir2}/build/compile-entry.ts`,
2068
+ `${_pkgSrcDir2}/build/entry-template.ts`,
2069
+ `${_pkgSrcDir2}/build/server-routes-entry.ts`,
2070
+ `${_pkgSrcDir2}/render/index.ts`,
2071
+ `${_pkgSrcDir2}/render/shell.ts`,
2072
+ `${_pkgSrcDir2}/router.ts`
2073
+ ];
2074
+ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serverEntry) {
2075
+ const fingerprintPaths = new Set([root.path, ...routes.map((route) => route.path)]);
2076
+ if (serverEntry) {
2077
+ fingerprintPaths.add(serverEntry);
2078
+ }
2079
+ if (root.errorPath) {
2080
+ fingerprintPaths.add(root.errorPath);
2081
+ }
2082
+ if (root.notFoundPath) {
2083
+ fingerprintPaths.add(root.notFoundPath);
2084
+ }
2085
+ for (const route of routes) {
2086
+ for (const segment of route.segmentBoundaries) {
2087
+ if (segment.errorPath) {
2088
+ fingerprintPaths.add(segment.errorPath);
2089
+ }
2090
+ if (segment.notFoundPath) {
2091
+ fingerprintPaths.add(segment.notFoundPath);
2092
+ }
2093
+ }
2094
+ }
2095
+ for (const path of BUILD_ID_INPUT_PATHS) {
2096
+ if (!existsSync6(path)) {
2097
+ console.warn(`[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
2098
+ }
2099
+ fingerprintPaths.add(path);
2100
+ }
2101
+ const fileParts = await Promise.all([...fingerprintPaths].sort().map(async (path) => {
2102
+ const content = existsSync6(path) ? await Bun.file(path).text() : "";
2103
+ return `${toPosixPath(path)}:${content}`;
2104
+ }));
2105
+ const routeParts = routes.map((route) => JSON.stringify({ mode: route.mode, path: toPosixPath(route.path), pattern: route.pattern })).sort();
2106
+ return [entryChunk, ...[...cssChunks].sort(), ...routeParts, ...fileParts].join(`
2107
+ `);
2108
+ }
2109
+ function buildCompileMetadata(root, routes) {
2110
+ const rootConventions = root.errorPath || root.notFoundPath ? {
2111
+ errorPath: root.errorPath ? toPosixPath(root.errorPath) : undefined,
2112
+ notFoundPath: root.notFoundPath ? toPosixPath(root.notFoundPath) : undefined
2113
+ } : undefined;
2114
+ const routeMetadata = {};
2115
+ for (const route of routes) {
2116
+ routeMetadata[toPosixPath(route.path)] = {
2117
+ segmentBoundaries: route.segmentBoundaries.map((b) => ({
2118
+ depth: b.depth,
2119
+ path: toPosixPath(b.path),
2120
+ errorPath: b.errorPath ? toPosixPath(b.errorPath) : undefined,
2121
+ notFoundPath: b.notFoundPath ? toPosixPath(b.notFoundPath) : undefined
2122
+ }))
2123
+ };
2124
+ }
2125
+ return { rootConventions, routeMetadata };
2126
+ }
2127
+ async function buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, options) {
2128
+ if (options.compile && !serverEntry) {
2129
+ throw new Error(`[furin] \`compile: "${options.compile}"\` requires a server entry point. ` + "Create src/server.ts or set `serverEntry` in your furin.config.ts.");
2130
+ }
2131
+ const target = "bun";
2132
+ const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
2133
+ const targetDir = resolve(rootDir, targetManifest.targetDir);
2134
+ rmSync2(targetDir, { force: true, recursive: true });
2135
+ ensureDir(targetDir);
2136
+ const { entryChunk, cssChunks } = await buildClient(routes, {
2137
+ outDir: targetDir,
2138
+ rootLayout: root.path,
2139
+ plugins: options.plugins,
2140
+ publicPath: "/_client/",
2141
+ basePath: ""
2142
+ });
2143
+ const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, root, serverEntry);
2144
+ const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
2145
+ targetManifest.buildId = buildId;
2146
+ const clientDir = join7(targetDir, "client");
2147
+ writeFileSync6(join7(clientDir, "index.html"), generateProdIndexHtml(entryChunk, cssChunks, buildId));
2148
+ const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
2149
+ const publicDir = existsSync6(join7(rootDir, "public")) ? join7(rootDir, "public") : undefined;
2150
+ const targetPublicDir = publicDir ? join7(targetDir, "public") : undefined;
2151
+ if (publicDir && targetPublicDir && options.compile !== "embed") {
2152
+ copyDirRecursive(publicDir, targetPublicDir);
2153
+ }
2154
+ const { rootConventions, routeMetadata } = buildCompileMetadata(root, routes);
2155
+ if (options.compile && serverEntry) {
2156
+ const clientDir2 = join7(targetDir, "client");
2157
+ const outfile = join7(targetDir, "server");
2158
+ const entryPath = generateCompileEntry({
2159
+ buildId,
2160
+ rootPath: root.path,
2161
+ routes: routeManifest,
2162
+ serverEntry,
2163
+ outDir: targetDir,
2164
+ embed: options.compile === "embed" ? { clientDir: clientDir2 } : undefined,
2165
+ publicDir,
2166
+ rootConventions,
2167
+ routeMetadata
2168
+ });
2169
+ await Bun.build({
2170
+ entrypoints: [entryPath],
2171
+ compile: { outfile },
2172
+ minify: true,
2173
+ sourcemap: "linked",
2174
+ define: { "process.env.NODE_ENV": JSON.stringify("production") },
2175
+ plugins: options.plugins
2176
+ });
2177
+ console.log(`[furin] Server binary: ${outfile}`);
2178
+ targetManifest.serverPath = toPosixPath(join7(targetManifest.targetDir, "server"));
2179
+ if (options.compile === "embed") {
2180
+ rmSync2(clientDir2, { force: true, recursive: true });
2181
+ targetManifest.clientDir = null;
2182
+ targetManifest.templatePath = null;
2183
+ }
2184
+ } else if (serverEntry) {
2185
+ const entryPath = generateServerRoutesEntry({
2186
+ buildId,
2187
+ rootPath: root.path,
2188
+ routes: routeManifest,
2189
+ serverEntry,
2190
+ outDir: targetDir,
2191
+ rootConventions,
2192
+ routeMetadata
2193
+ });
2194
+ await Bun.build({
2195
+ entrypoints: [entryPath],
2196
+ outdir: targetDir,
2197
+ target: "bun",
2198
+ minify: true,
2199
+ sourcemap: "linked",
2200
+ plugins: options.plugins
2201
+ });
2202
+ console.log(`[furin] Server bundle: ${toPosixPath(join7(targetManifest.targetDir, "server.js"))}`);
2203
+ targetManifest.serverPath = toPosixPath(join7(targetManifest.targetDir, "server.js"));
2204
+ }
2205
+ for (const file of [
2206
+ "_compile-entry.ts",
2207
+ "_compile-entry.js.map",
2208
+ "server.ts",
2209
+ "_hydrate.tsx"
2210
+ ]) {
2211
+ rmSync2(join7(targetDir, file), { force: true });
2212
+ }
2213
+ return targetManifest;
2214
+ }
2215
+
2216
+ // src/adapter/static.ts
2217
+ import { cpSync as cpSync2, existsSync as existsSync7, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
2218
+ import { dirname as dirname3, isAbsolute, join as join8, relative as relative3, resolve as resolve2, sep } from "path";
2219
+
2220
+ // src/render/assemble.ts
2221
+ function resolvePath(pattern, params) {
2222
+ let path = pattern;
2223
+ for (const [key, val] of Object.entries(params ?? {})) {
2224
+ path = path.replace(key === "*" ? "*" : `:${key}`, val);
2225
+ }
2226
+ return path;
2227
+ }
2228
+ async function streamToString(stream) {
2229
+ const reader = stream.getReader();
2230
+ const decoder = new TextDecoder;
2231
+ let html = "";
2232
+ for (;; ) {
2233
+ const { done, value } = await reader.read();
2234
+ if (done) {
2235
+ break;
2236
+ }
2237
+ html += decoder.decode(value, { stream: true });
2238
+ }
2239
+ html += decoder.decode();
2240
+ return html;
2241
+ }
2242
+ function splitTemplate(template) {
2243
+ const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
2244
+ const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
2245
+ return { headPre, bodyPre, bodyPost };
2246
+ }
2247
+ function assembleHTML(template, headData, reactHtml, data) {
2248
+ const { headPre, bodyPre, bodyPost } = splitTemplate(template);
2249
+ const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
2250
+ let injectedBodyPost = bodyPost;
2251
+ if (dataScript) {
2252
+ injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${dataScript}</body>`) : bodyPost + dataScript;
2253
+ }
2254
+ return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
2255
+ }
2256
+
2257
+ // src/render/index.ts
2258
+ import { createElement as createElement2 } from "react";
2259
+ import { renderToReadableStream } from "react-dom/server";
2260
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/utils.mjs
2261
+ function formatDuration(ms) {
2262
+ if (ms < 1000)
2263
+ return `${Math.round(ms)}ms`;
2264
+ return `${(ms / 1000).toFixed(2)}s`;
2265
+ }
2266
+ function isClient() {
2267
+ return typeof window !== "undefined";
2268
+ }
2269
+ function isDev() {
2270
+ if (typeof process !== "undefined")
2271
+ return true;
2272
+ if (typeof window !== "undefined")
2273
+ return true;
2274
+ return false;
2275
+ }
2276
+ function detectEnvironment() {
2277
+ const env = typeof process !== "undefined" ? process.env : {};
2278
+ const defaultEnvironment = isDev() ? "development" : "production";
2279
+ return {
2280
+ environment: env.NODE_ENV || defaultEnvironment,
2281
+ service: env.SERVICE_NAME || "app",
2282
+ version: env.APP_VERSION,
2283
+ commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
2284
+ region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
2285
+ };
2286
+ }
2287
+ var LEVEL_ORDER = {
2288
+ debug: 0,
2289
+ info: 1,
2290
+ warn: 2,
2291
+ error: 3
2292
+ };
2293
+ function isLevelEnabled(level, minLevel) {
2294
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
2295
+ }
2296
+ function getConsoleMethod(level) {
2297
+ return level;
2298
+ }
2299
+ var colors = {
2300
+ reset: "\x1B[0m",
2301
+ bold: "\x1B[1m",
2302
+ dim: "\x1B[2m",
2303
+ red: "\x1B[31m",
2304
+ green: "\x1B[32m",
2305
+ yellow: "\x1B[33m",
2306
+ blue: "\x1B[34m",
2307
+ magenta: "\x1B[35m",
2308
+ cyan: "\x1B[36m",
2309
+ white: "\x1B[37m",
2310
+ gray: "\x1B[90m"
2311
+ };
2312
+ var levelColorMap = {
2313
+ error: colors.red,
2314
+ warn: colors.yellow,
2315
+ info: colors.cyan,
2316
+ debug: colors.gray
2317
+ };
2318
+ function getLevelColor(level) {
2319
+ return levelColorMap[level] ?? colors.white;
2320
+ }
2321
+ var cssColors = {
2322
+ dim: "color: #6b7280",
2323
+ red: "color: #ef4444; font-weight: bold",
2324
+ green: "color: #22c55e",
2325
+ yellow: "color: #f59e0b; font-weight: bold",
2326
+ cyan: "color: #06b6d4; font-weight: bold",
2327
+ gray: "color: #6b7280; font-weight: bold",
2328
+ reset: "color: inherit; font-weight: normal"
2329
+ };
2330
+ var cssLevelColorMap = {
2331
+ error: cssColors.red,
2332
+ warn: cssColors.yellow,
2333
+ info: cssColors.cyan,
2334
+ debug: cssColors.gray
2335
+ };
2336
+ function getCssLevelColor(level) {
2337
+ return cssLevelColorMap[level] ?? cssColors.reset;
2338
+ }
2339
+ function escapeFormatString(str) {
2340
+ return str.replace(/%/g, "%%");
2341
+ }
2342
+ var patternCache = /* @__PURE__ */ new Map;
2343
+ function matchesPattern(path, pattern) {
2344
+ let regex = patternCache.get(pattern);
2345
+ if (!regex) {
2346
+ const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, "[^/]");
2347
+ regex = new RegExp(`^${regexPattern}$`);
2348
+ patternCache.set(pattern, regex);
2349
+ }
2350
+ return regex.test(path);
2351
+ }
2352
+
2353
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/logger-DnobymUQ.mjs
2354
+ var DEFAULT_REPLACEMENT = "[REDACTED]";
2355
+ var builtinPatterns = {
2356
+ creditCard: {
2357
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
2358
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
2359
+ },
2360
+ email: {
2361
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
2362
+ mask: (m) => {
2363
+ if (m.indexOf("@") < 1)
2364
+ return "***@***";
2365
+ const tld = m.slice(m.lastIndexOf("."));
2366
+ return `${m[0]}***@***${tld}`;
2367
+ }
2368
+ },
2369
+ ipv4: {
2370
+ pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
2371
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
2372
+ },
2373
+ phone: {
2374
+ pattern: /(?:\+\d{1,3}[\s.-]?)?\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}\b/g,
2375
+ mask: (m) => {
2376
+ const digits = m.replace(/[^\d]/g, "");
2377
+ if (m.startsWith("+") && digits.length > 4) {
2378
+ const ccMatch = m.match(/^\+\d{1,3}/);
2379
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
2380
+ }
2381
+ if (digits.length > 2)
2382
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
2383
+ return "***";
2384
+ }
2385
+ },
2386
+ jwt: {
2387
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
2388
+ mask: () => "eyJ***.***"
2389
+ },
2390
+ bearer: {
2391
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
2392
+ mask: () => "Bearer ***"
2393
+ },
2394
+ iban: {
2395
+ pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
2396
+ mask: (m) => {
2397
+ const clean = m.replace(/[\s-]/g, "");
2398
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
2399
+ }
2400
+ }
2401
+ };
2402
+ function resolveRedactConfig(input) {
2403
+ if (input === undefined || input === false)
2404
+ return;
2405
+ if (input === true)
2406
+ return { _maskers: allBuiltinMaskers() };
2407
+ if (input.builtins === false)
2408
+ return input;
2409
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
2410
+ return {
2411
+ ...input,
2412
+ _maskers: maskers
2413
+ };
2414
+ }
2415
+ function allBuiltinMaskers() {
2416
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
2417
+ }
2418
+ function cloneRegex(re) {
2419
+ return new RegExp(re.source, re.flags);
2420
+ }
2421
+ function redactEvent(event, config) {
2422
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
2423
+ if (config.paths?.length)
2424
+ for (const path of config.paths)
2425
+ redactPath(event, path.split("."), replacement);
2426
+ if (config._maskers?.length)
2427
+ applyMaskersToTree(event, config._maskers);
2428
+ if (config.patterns?.length)
2429
+ redactPatterns(event, config.patterns, replacement);
2430
+ }
2431
+ function redactPath(obj, segments, replacement) {
2432
+ let current = obj;
2433
+ for (let i = 0;i < segments.length - 1; i++) {
2434
+ if (current === null || current === undefined || typeof current !== "object")
2435
+ return;
2436
+ current = current[segments[i]];
2437
+ }
2438
+ if (current === null || current === undefined || typeof current !== "object")
2439
+ return;
2440
+ const leaf = segments[segments.length - 1];
2441
+ if (leaf in current)
2442
+ current[leaf] = replacement;
2443
+ }
2444
+ function redactPatterns(obj, patterns, replacement) {
2445
+ if (obj === null || obj === undefined)
2446
+ return;
2447
+ if (Array.isArray(obj)) {
2448
+ for (let i = 0;i < obj.length; i++)
2449
+ if (typeof obj[i] === "string")
2450
+ obj[i] = applyPatterns(obj[i], patterns, replacement);
2451
+ else if (typeof obj[i] === "object")
2452
+ redactPatterns(obj[i], patterns, replacement);
2453
+ return;
2454
+ }
2455
+ if (typeof obj === "object") {
2456
+ const record = obj;
2457
+ for (const key in record) {
2458
+ const val = record[key];
2459
+ if (typeof val === "string")
2460
+ record[key] = applyPatterns(val, patterns, replacement);
2461
+ else if (typeof val === "object")
2462
+ redactPatterns(val, patterns, replacement);
2463
+ }
2464
+ }
2465
+ }
2466
+ function applyPatterns(value, patterns, replacement) {
2467
+ let result = value;
2468
+ for (const pattern of patterns) {
2469
+ pattern.lastIndex = 0;
2470
+ result = result.replace(pattern, replacement);
2471
+ }
2472
+ return result;
2473
+ }
2474
+ function applyMaskersToTree(obj, maskers) {
2475
+ if (obj === null || obj === undefined)
2476
+ return;
2477
+ if (Array.isArray(obj)) {
2478
+ for (let i = 0;i < obj.length; i++)
2479
+ if (typeof obj[i] === "string")
2480
+ obj[i] = applyMaskers(obj[i], maskers);
2481
+ else if (typeof obj[i] === "object")
2482
+ applyMaskersToTree(obj[i], maskers);
2483
+ return;
2484
+ }
2485
+ if (typeof obj === "object") {
2486
+ const record = obj;
2487
+ for (const key in record) {
2488
+ const val = record[key];
2489
+ if (typeof val === "string")
2490
+ record[key] = applyMaskers(val, maskers);
2491
+ else if (typeof val === "object")
2492
+ applyMaskersToTree(val, maskers);
2493
+ }
2494
+ }
2495
+ }
2496
+ function applyMaskers(value, maskers) {
2497
+ let result = value;
2498
+ for (const [pattern, mask] of maskers) {
2499
+ pattern.lastIndex = 0;
2500
+ result = result.replace(pattern, mask);
2501
+ }
2502
+ return result;
2503
+ }
2504
+ function isPlainObject(val) {
2505
+ return val !== null && typeof val === "object" && !Array.isArray(val);
2506
+ }
2507
+ var _tsDate = /* @__PURE__ */ new Date;
2508
+ function isoNow() {
2509
+ _tsDate.setTime(Date.now());
2510
+ return _tsDate.toISOString();
2511
+ }
2512
+ var POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).";
2513
+ function warnPostEmit(method, detail) {
2514
+ console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
2515
+ }
2516
+ function mergeInto(target, source) {
2517
+ for (const key in source) {
2518
+ const sourceVal = source[key];
2519
+ if (sourceVal === undefined || sourceVal === null)
2520
+ continue;
2521
+ const targetVal = target[key];
2522
+ if (isPlainObject(sourceVal) && isPlainObject(targetVal))
2523
+ mergeInto(targetVal, sourceVal);
2524
+ else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
2525
+ target[key] = [...targetVal, ...sourceVal];
2526
+ else
2527
+ target[key] = sourceVal;
2528
+ }
2529
+ }
2530
+ var globalEnv = {
2531
+ service: "app",
2532
+ environment: "development"
2533
+ };
2534
+ var globalPretty = isDev();
2535
+ var globalSampling = {};
2536
+ var globalStringify = true;
2537
+ var globalDrain;
2538
+ var globalRedact;
2539
+ var globalEnabled = true;
2540
+ var globalSilent = false;
2541
+ var globalMinLevel = "debug";
2542
+ function initLogger(config = {}) {
2543
+ globalEnabled = config.enabled ?? true;
2544
+ const detected = detectEnvironment();
2545
+ globalEnv = {
2546
+ service: config.env?.service ?? detected.service ?? "app",
2547
+ environment: config.env?.environment ?? detected.environment ?? "development",
2548
+ version: config.env?.version ?? detected.version,
2549
+ commitHash: config.env?.commitHash ?? detected.commitHash,
2550
+ region: config.env?.region ?? detected.region
2551
+ };
2552
+ globalPretty = config.pretty ?? isDev();
2553
+ globalSampling = config.sampling ?? {};
2554
+ globalStringify = config.stringify ?? true;
2555
+ globalDrain = config.drain;
2556
+ globalRedact = resolveRedactConfig(config.redact ?? !isDev());
2557
+ globalSilent = config.silent ?? false;
2558
+ globalMinLevel = config.minLevel ?? "debug";
2559
+ if (globalSilent && !globalDrain && !config._suppressDrainWarning)
2560
+ 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).");
2561
+ }
2562
+ function shouldSample(level) {
2563
+ const { rates } = globalSampling;
2564
+ if (!rates)
2565
+ return true;
2566
+ const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
2567
+ if (percentage <= 0)
2568
+ return false;
2569
+ if (percentage >= 100)
2570
+ return true;
2571
+ return Math.random() * 100 < percentage;
2572
+ }
2573
+ function shouldKeep(ctx) {
2574
+ const { keep } = globalSampling;
2575
+ if (!keep?.length)
2576
+ return false;
2577
+ return keep.some((condition) => {
2578
+ if (condition.status !== undefined && ctx.status !== undefined && ctx.status >= condition.status)
2579
+ return true;
2580
+ if (condition.duration !== undefined && ctx.duration !== undefined && ctx.duration >= condition.duration)
2581
+ return true;
2582
+ if (condition.path && ctx.path && matchesPattern(ctx.path, condition.path))
2583
+ return true;
2584
+ return false;
2585
+ });
2586
+ }
2587
+ function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
2588
+ if (!globalEnabled)
2589
+ return null;
2590
+ if (!ownsEvent) {
2591
+ if (!isLevelEnabled(level, globalMinLevel))
2592
+ return null;
2593
+ if (!shouldSample(level))
2594
+ return null;
2595
+ }
2596
+ let formatted;
2597
+ if (ownsEvent) {
2598
+ event.timestamp = isoNow();
2599
+ event.level = level;
2600
+ if (event.service === undefined)
2601
+ event.service = globalEnv.service;
2602
+ if (event.environment === undefined)
2603
+ event.environment = globalEnv.environment;
2604
+ if (globalEnv.version !== undefined && event.version === undefined)
2605
+ event.version = globalEnv.version;
2606
+ if (globalEnv.commitHash !== undefined && event.commitHash === undefined)
2607
+ event.commitHash = globalEnv.commitHash;
2608
+ if (globalEnv.region !== undefined && event.region === undefined)
2609
+ event.region = globalEnv.region;
2610
+ formatted = event;
2611
+ } else
2612
+ formatted = {
2613
+ timestamp: isoNow(),
2614
+ level,
2615
+ ...globalEnv,
2616
+ ...event
2617
+ };
2618
+ if (globalRedact)
2619
+ redactEvent(formatted, globalRedact);
2620
+ if (!globalSilent)
2621
+ if (globalPretty)
2622
+ prettyPrintWideEvent(formatted);
2623
+ else if (globalStringify)
2624
+ console[getConsoleMethod(level)](JSON.stringify(formatted));
2625
+ else
2626
+ console[getConsoleMethod(level)](formatted);
2627
+ if (globalDrain && !deferDrain)
2628
+ Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
2629
+ console.error("[evlog] drain failed:", err);
2630
+ });
2631
+ return formatted;
2632
+ }
2633
+ function emitTaggedLog(level, tag, message) {
2634
+ if (!globalEnabled)
2635
+ return;
2636
+ if (globalPretty && !globalSilent) {
2637
+ if (!isLevelEnabled(level, globalMinLevel))
2638
+ return;
2639
+ if (!shouldSample(level))
2640
+ return;
2641
+ if (isClient()) {
2642
+ const levelColor = getCssLevelColor(level);
2643
+ const timestamp = isoNow().slice(11, 23);
2644
+ console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
2645
+ } else {
2646
+ const color = getLevelColor(level);
2647
+ const timestamp = isoNow().slice(11, 23);
2648
+ console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
2649
+ }
2650
+ return;
2651
+ }
2652
+ emitWideEvent(level, {
2653
+ tag,
2654
+ message
2655
+ });
2656
+ }
2657
+ function formatValue(value) {
2658
+ if (value === null || value === undefined)
2659
+ return String(value);
2660
+ if (typeof value === "object") {
2661
+ const pairs = [];
2662
+ for (const [k, v] of Object.entries(value))
2663
+ if (v !== undefined && v !== null)
2664
+ if (typeof v === "object")
2665
+ pairs.push(`${k}=${JSON.stringify(v)}`);
2666
+ else
2667
+ pairs.push(`${k}=${v}`);
2668
+ return pairs.join(" ");
2669
+ }
2670
+ return String(value);
2671
+ }
2672
+ function formatCost(cost) {
2673
+ if (cost < 0.01)
2674
+ return `$${cost.toFixed(6)}`;
2675
+ if (cost < 1)
2676
+ return `$${cost.toFixed(4)}`;
2677
+ return `$${cost.toFixed(2)}`;
2678
+ }
2679
+ function buildAIEntries(ai) {
2680
+ const entries = [];
2681
+ const headerParts = [];
2682
+ if (ai.model) {
2683
+ let m = String(ai.model);
2684
+ if (ai.provider)
2685
+ m += ` (${ai.provider})`;
2686
+ headerParts.push(m);
2687
+ }
2688
+ if (ai.calls)
2689
+ headerParts.push(`${ai.calls} call${ai.calls > 1 ? "s" : ""}`);
2690
+ if (ai.steps && ai.steps > 1)
2691
+ headerParts.push(`${ai.steps} steps`);
2692
+ entries.push({
2693
+ key: "ai",
2694
+ value: headerParts.join(" \xB7 ")
2695
+ });
2696
+ const inputTokens = ai.inputTokens;
2697
+ const outputTokens = ai.outputTokens;
2698
+ const totalTokens = ai.totalTokens;
2699
+ if (inputTokens !== undefined && outputTokens !== undefined) {
2700
+ let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
2701
+ if (totalTokens)
2702
+ tokLine += ` (${totalTokens} total)`;
2703
+ const extras = [];
2704
+ if (ai.cacheReadTokens)
2705
+ extras.push(`${ai.cacheReadTokens} cache read`);
2706
+ if (ai.cacheWriteTokens)
2707
+ extras.push(`${ai.cacheWriteTokens} cache write`);
2708
+ if (ai.reasoningTokens)
2709
+ extras.push(`${ai.reasoningTokens} reasoning`);
2710
+ if (extras.length)
2711
+ tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
2712
+ entries.push({
2713
+ key: "ai.tokens",
2714
+ value: tokLine
2715
+ });
2716
+ }
2717
+ const msFirst = ai.msToFirstChunk;
2718
+ const msFinish = ai.msToFinish;
2719
+ const tps = ai.tokensPerSecond;
2720
+ if (msFirst !== undefined || msFinish !== undefined) {
2721
+ const parts = [];
2722
+ if (msFirst !== undefined)
2723
+ parts.push(`${formatDuration(msFirst)} to first chunk`);
2724
+ if (msFinish !== undefined)
2725
+ parts.push(`${formatDuration(msFinish)} total`);
2726
+ let streamLine = parts.join(" \u2192 ");
2727
+ if (tps)
2728
+ streamLine += ` \xB7 ${tps} tok/s`;
2729
+ entries.push({
2730
+ key: "ai.streaming",
2731
+ value: streamLine
2732
+ });
2733
+ }
2734
+ if (ai.estimatedCost !== undefined)
2735
+ entries.push({
2736
+ key: "ai.cost",
2737
+ value: formatCost(ai.estimatedCost)
2738
+ });
2739
+ if (ai.totalDurationMs !== undefined)
2740
+ entries.push({
2741
+ key: "ai.totalDuration",
2742
+ value: formatDuration(ai.totalDurationMs)
2743
+ });
2744
+ const toolCalls = ai.toolCalls;
2745
+ const tools = ai.tools;
2746
+ const hasInputs = toolCalls?.length ? typeof toolCalls[0] === "object" : false;
2747
+ if (tools?.length) {
2748
+ const children = tools.map((t, idx) => {
2749
+ const mark = t.success ? "\u2713" : "\u2717";
2750
+ let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
2751
+ if (t.error)
2752
+ line += ` ${t.error}`;
2753
+ if (hasInputs && toolCalls && idx < toolCalls.length) {
2754
+ const tc = toolCalls[idx];
2755
+ const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
2756
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
2757
+ line += ` ${truncated}`;
2758
+ }
2759
+ return line;
2760
+ });
2761
+ entries.push({
2762
+ key: "ai.tools",
2763
+ value: "",
2764
+ children
2765
+ });
2766
+ } else if (toolCalls?.length)
2767
+ if (hasInputs) {
2768
+ const children = toolCalls.map((tc) => {
2769
+ const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
2770
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
2771
+ return `${tc.name}(${truncated})`;
2772
+ });
2773
+ entries.push({
2774
+ key: "ai.tools",
2775
+ value: "",
2776
+ children
2777
+ });
2778
+ } else
2779
+ entries.push({
2780
+ key: "ai.tools",
2781
+ value: toolCalls.join(", ")
2782
+ });
2783
+ const stepsUsage = ai.stepsUsage;
2784
+ if (stepsUsage?.length) {
2785
+ const allSameModel = stepsUsage.every((s) => s.model === stepsUsage[0].model);
2786
+ const children = stepsUsage.map((s) => {
2787
+ let line = `${allSameModel ? "" : `${s.model} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
2788
+ const stepTools = s.toolCalls;
2789
+ if (stepTools?.length)
2790
+ line += ` [${stepTools.join(", ")}]`;
2791
+ return line;
2792
+ });
2793
+ entries.push({
2794
+ key: "ai.steps",
2795
+ value: "",
2796
+ children
2797
+ });
2798
+ } else if (ai.steps && ai.steps > 1)
2799
+ entries.push({
2800
+ key: "ai.steps",
2801
+ value: String(ai.steps)
2802
+ });
2803
+ const embedding = ai.embedding;
2804
+ if (embedding) {
2805
+ const parts = [];
2806
+ if (embedding.model)
2807
+ parts.push(String(embedding.model));
2808
+ parts.push(`${embedding.tokens} tokens`);
2809
+ if (embedding.dimensions)
2810
+ parts.push(`${embedding.dimensions}d`);
2811
+ if (embedding.count)
2812
+ parts.push(`${embedding.count} items`);
2813
+ entries.push({
2814
+ key: "ai.embedding",
2815
+ value: parts.join(" \xB7 ")
2816
+ });
2817
+ }
2818
+ if (ai.finishReason)
2819
+ entries.push({
2820
+ key: "ai.finishReason",
2821
+ value: String(ai.finishReason)
2822
+ });
2823
+ if (ai.error)
2824
+ entries.push({
2825
+ key: "ai.error",
2826
+ value: String(ai.error)
2827
+ });
2828
+ if (ai.responseId)
2829
+ entries.push({
2830
+ key: "ai.responseId",
2831
+ value: String(ai.responseId)
2832
+ });
2833
+ return entries;
2834
+ }
2835
+ function prettyPrintWideEvent(event) {
2836
+ const { timestamp, level, service, environment, version, ...rest } = event;
2837
+ const ts = timestamp.slice(11, 23);
2838
+ const browser = isClient();
2839
+ const parts = [];
2840
+ const styles = [];
2841
+ if (browser) {
2842
+ const lc = getCssLevelColor(level);
2843
+ parts.push(`%c${ts}%c %c${level.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
2844
+ styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
2845
+ } else {
2846
+ const lc = getLevelColor(level);
2847
+ parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${level.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
2848
+ }
2849
+ if (rest.method && rest.path) {
2850
+ parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
2851
+ delete rest.method;
2852
+ delete rest.path;
2853
+ }
2854
+ if (rest.status) {
2855
+ const sc = browser ? rest.status >= 400 ? cssColors.red : cssColors.green : rest.status >= 400 ? colors.red : colors.green;
2856
+ if (browser) {
2857
+ parts.push(` %c${rest.status}%c`);
2858
+ styles.push(sc, cssColors.reset);
2859
+ } else
2860
+ parts.push(` ${sc}${rest.status}${colors.reset}`);
2861
+ delete rest.status;
2862
+ }
2863
+ if (rest.duration) {
2864
+ if (browser) {
2865
+ parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
2866
+ styles.push(cssColors.dim, cssColors.reset);
2867
+ } else
2868
+ parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
2869
+ delete rest.duration;
2870
+ }
2871
+ console.log(parts.join(""), ...styles);
2872
+ const aiData = rest.ai;
2873
+ if (aiData && typeof aiData === "object")
2874
+ delete rest.ai;
2875
+ const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
2876
+ const aiEntries = aiData ? buildAIEntries(aiData) : [];
2877
+ const allEntries = [...restEntries.map(([key, value]) => ({
2878
+ key,
2879
+ value: formatValue(value)
2880
+ })), ...aiEntries];
2881
+ for (let i = 0;i < allEntries.length; i++) {
2882
+ const entry = allEntries[i];
2883
+ const hasChildren = entry.children && entry.children.length > 0;
2884
+ const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
2885
+ if (browser) {
2886
+ const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
2887
+ console.log(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
2888
+ } else {
2889
+ const val = entry.value ? ` ${entry.value}` : "";
2890
+ console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
2891
+ }
2892
+ if (hasChildren) {
2893
+ const connector = i === allEntries.length - 1 ? " " : "\u2502";
2894
+ for (let j = 0;j < entry.children.length; j++) {
2895
+ const child = entry.children[j];
2896
+ const childPrefix = j === entry.children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
2897
+ if (browser)
2898
+ console.log(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
2899
+ else
2900
+ console.log(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
2901
+ }
2902
+ }
2903
+ }
2904
+ }
2905
+ function createLogMethod(level) {
2906
+ return function logMethod(tagOrEvent, message) {
2907
+ if (typeof tagOrEvent === "string" && message !== undefined)
2908
+ emitTaggedLog(level, tagOrEvent, message);
2909
+ else if (typeof tagOrEvent === "object")
2910
+ emitWideEvent(level, tagOrEvent);
2911
+ else
2912
+ emitTaggedLog(level, "log", String(tagOrEvent));
2913
+ };
2914
+ }
2915
+ var _log = {
2916
+ info: createLogMethod("info"),
2917
+ error: createLogMethod("error"),
2918
+ warn: createLogMethod("warn"),
2919
+ debug: createLogMethod("debug")
2920
+ };
2921
+ var noopLogger = {
2922
+ set() {},
2923
+ error() {},
2924
+ info() {},
2925
+ warn() {},
2926
+ emit() {
2927
+ return null;
2928
+ },
2929
+ getContext() {
2930
+ return {};
2931
+ }
2932
+ };
2933
+ function createLogger(initialContext = {}, internalOptions) {
2934
+ if (!globalEnabled)
2935
+ return noopLogger;
2936
+ const deferDrain = internalOptions?._deferDrain ?? false;
2937
+ const startTime = Date.now();
2938
+ const context = { ...initialContext };
2939
+ let hasError = false;
2940
+ let hasWarn = false;
2941
+ let emitted = false;
2942
+ function addLog(level, message) {
2943
+ if (!Array.isArray(context.requestLogs))
2944
+ context.requestLogs = [];
2945
+ context.requestLogs.push({
2946
+ level,
2947
+ message,
2948
+ timestamp: isoNow()
2949
+ });
2950
+ }
2951
+ return {
2952
+ set(data) {
2953
+ if (emitted) {
2954
+ const keys = Object.keys(data);
2955
+ warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
2956
+ return;
2957
+ }
2958
+ mergeInto(context, data);
2959
+ },
2960
+ error(error, errorContext) {
2961
+ if (emitted) {
2962
+ warnPostEmit("log.error()", `Keys dropped: ${(errorContext ? [...Object.keys(errorContext), "error"] : ["error"]).join(", ")}.`);
2963
+ return;
2964
+ }
2965
+ hasError = true;
2966
+ const err = typeof error === "string" ? new Error(error) : error;
2967
+ if (errorContext)
2968
+ mergeInto(context, errorContext);
2969
+ const errorObj = {
2970
+ name: err.name,
2971
+ message: err.message,
2972
+ stack: err.stack
2973
+ };
2974
+ const errRecord = err;
2975
+ for (const k of [
2976
+ "status",
2977
+ "statusText",
2978
+ "statusCode",
2979
+ "statusMessage",
2980
+ "data",
2981
+ "cause",
2982
+ "internal"
2983
+ ])
2984
+ if (k in err)
2985
+ errorObj[k] = errRecord[k];
2986
+ if (isPlainObject(context.error))
2987
+ mergeInto(context.error, errorObj);
2988
+ else
2989
+ context.error = errorObj;
2990
+ },
2991
+ info(message, infoContext) {
2992
+ if (emitted) {
2993
+ warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2994
+ return;
2995
+ }
2996
+ addLog("info", message);
2997
+ if (infoContext) {
2998
+ const { requestLogs: _, ...rest } = infoContext;
2999
+ mergeInto(context, rest);
3000
+ }
3001
+ },
3002
+ warn(message, warnContext) {
3003
+ if (emitted) {
3004
+ warnPostEmit("log.warn()", `Keys dropped: ${(warnContext ? ["message", ...Object.keys(warnContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
3005
+ return;
3006
+ }
3007
+ hasWarn = true;
3008
+ addLog("warn", message);
3009
+ if (warnContext) {
3010
+ const { requestLogs: _, ...rest } = warnContext;
3011
+ mergeInto(context, rest);
3012
+ }
3013
+ },
3014
+ emit(overrides) {
3015
+ if (emitted) {
3016
+ warnPostEmit("log.emit()", "Ignoring duplicate emit.");
3017
+ return null;
3018
+ }
3019
+ const durationMs = Date.now() - startTime;
3020
+ const level = hasError ? "error" : hasWarn ? "warn" : "info";
3021
+ let forceKeep = false;
3022
+ if (overrides?._forceKeep)
3023
+ forceKeep = true;
3024
+ else if (globalSampling.keep?.length)
3025
+ forceKeep = shouldKeep({
3026
+ status: overrides?.status ?? context.status,
3027
+ duration: durationMs,
3028
+ path: context.path,
3029
+ method: context.method,
3030
+ context
3031
+ });
3032
+ if (!forceKeep && !shouldSample(level)) {
3033
+ emitted = true;
3034
+ return null;
3035
+ }
3036
+ if (overrides) {
3037
+ const obj = overrides;
3038
+ for (const key in obj)
3039
+ if (key !== "_forceKeep")
3040
+ context[key] = obj[key];
3041
+ }
3042
+ context.duration = formatDuration(durationMs);
3043
+ const wide = emitWideEvent(level, context, deferDrain, true);
3044
+ emitted = true;
3045
+ return wide;
3046
+ },
3047
+ getContext() {
3048
+ return { ...context };
3049
+ }
3050
+ };
3051
+ }
3052
+ if (typeof __EVLOG_CONFIG__ !== "undefined")
3053
+ initLogger(__EVLOG_CONFIG__);
3054
+ // src/link.tsx
3055
+ import {
3056
+ createContext,
3057
+ createElement,
3058
+ useCallback,
3059
+ useContext,
3060
+ useEffect,
3061
+ useMemo,
3062
+ useRef,
3063
+ useState
3064
+ } from "react";
3065
+
3066
+ // src/render/boundaries.tsx
3067
+ import { Component, Fragment } from "react";
3068
+
3069
+ // src/error.ts
3070
+ function getPublicErrorMessage(error) {
3071
+ const branded = error;
3072
+ if (branded?.__furinBrand === "FURIN_NOT_FOUND") {
3073
+ return error.message;
3074
+ }
3075
+ return "Something went wrong";
3076
+ }
3077
+
3078
+ // src/not-found.ts
3079
+ var NOT_FOUND_BRAND = "FURIN_NOT_FOUND";
3080
+
3081
+ class FurinNotFoundError extends Error {
3082
+ __furinBrand = NOT_FOUND_BRAND;
3083
+ data;
3084
+ constructor(options) {
3085
+ super(options?.message ?? "");
3086
+ this.data = options?.data;
3087
+ }
3088
+ }
3089
+ function isNotFoundError(err) {
3090
+ return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
3091
+ }
3092
+
3093
+ // src/render/default-screens.tsx
3094
+ import { jsxDEV } from "react/jsx-dev-runtime";
3095
+ var FONT_SANS = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
3096
+ var FONT_MONO = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace';
3097
+ var COLOR_BG = "#000000";
3098
+ var COLOR_TEXT = "#ffffff";
3099
+ var COLOR_TEXT_DIM = "rgba(255, 255, 255, 0.7)";
3100
+ var COLOR_TEXT_MUTED = "rgba(255, 255, 255, 0.45)";
3101
+ var COLOR_GRID = "rgba(255, 255, 255, 0.04)";
3102
+ var COLOR_BRACKET = "rgba(255, 255, 255, 0.55)";
3103
+ var COLOR_DANGER_DIM = "rgba(239, 68, 68, 0.6)";
3104
+ var PAGE_STYLE = {
3105
+ alignItems: "center",
3106
+ backgroundColor: COLOR_BG,
3107
+ backgroundImage: `
3108
+ linear-gradient(${COLOR_GRID} 1px, transparent 1px),
3109
+ linear-gradient(90deg, ${COLOR_GRID} 1px, transparent 1px)
3110
+ `,
3111
+ backgroundSize: "32px 32px, 32px 32px",
3112
+ boxSizing: "border-box",
3113
+ color: COLOR_TEXT,
3114
+ display: "flex",
3115
+ fontFamily: FONT_SANS,
3116
+ fontSize: "16px",
3117
+ justifyContent: "center",
3118
+ lineHeight: 1.5,
3119
+ margin: 0,
3120
+ minHeight: "100vh",
3121
+ padding: "32px",
3122
+ width: "100%"
3123
+ };
3124
+ var FRAME_STYLE = {
3125
+ boxSizing: "border-box",
3126
+ maxWidth: "880px",
3127
+ position: "relative",
3128
+ width: "100%"
3129
+ };
3130
+ var BRACKET_BASE = {
3131
+ height: "40px",
3132
+ position: "absolute",
3133
+ width: "40px"
3134
+ };
3135
+ function CornerBracket({ corner }) {
3136
+ const top = corner === "tl" || corner === "tr";
3137
+ const left = corner === "tl" || corner === "bl";
3138
+ const style = {
3139
+ ...BRACKET_BASE,
3140
+ [top ? "top" : "bottom"]: 0,
3141
+ [left ? "left" : "right"]: 0,
3142
+ [`border${top ? "Top" : "Bottom"}`]: `2px solid ${COLOR_BRACKET}`,
3143
+ [`border${left ? "Left" : "Right"}`]: `2px solid ${COLOR_BRACKET}`
3144
+ };
3145
+ return /* @__PURE__ */ jsxDEV("span", {
3146
+ "aria-hidden": "true",
3147
+ style
3148
+ }, undefined, false, undefined, this);
3149
+ }
3150
+ var CARD_STYLE = {
3151
+ boxSizing: "border-box",
3152
+ margin: "0 auto",
3153
+ maxWidth: "640px",
3154
+ padding: "64px 24px",
3155
+ textAlign: "center"
3156
+ };
3157
+ var BADGE_STYLE = {
3158
+ border: `1px solid ${COLOR_DANGER_DIM}`,
3159
+ color: COLOR_TEXT,
3160
+ display: "inline-block",
3161
+ fontFamily: FONT_SANS,
3162
+ fontSize: "32px",
3163
+ fontWeight: 600,
3164
+ letterSpacing: "0.08em",
3165
+ marginBottom: "16px",
3166
+ padding: "12px 36px"
3167
+ };
3168
+ var NOT_FOUND_BADGE_STYLE = {
3169
+ ...BADGE_STYLE,
3170
+ border: 0,
3171
+ padding: 0
3172
+ };
3173
+ var HEADING_STYLE = {
3174
+ color: COLOR_TEXT,
3175
+ fontFamily: FONT_SANS,
3176
+ fontSize: "24px",
3177
+ fontWeight: 600,
3178
+ margin: "0 0 24px 0"
3179
+ };
3180
+ var CODE_BOX_STYLE = {
3181
+ color: COLOR_TEXT_DIM,
3182
+ display: "inline-block",
3183
+ fontFamily: FONT_MONO,
3184
+ fontSize: "13px",
3185
+ letterSpacing: "0.02em",
3186
+ margin: "0 0 32px 0",
3187
+ padding: "8px 0"
3188
+ };
3189
+ var CODE_LABEL_STYLE = {
3190
+ color: COLOR_TEXT_MUTED,
3191
+ marginRight: "10px",
3192
+ textTransform: "uppercase"
3193
+ };
3194
+ var DESCRIPTION_WRAPPER_STYLE = {
3195
+ color: COLOR_TEXT_DIM,
3196
+ fontSize: "15px",
3197
+ margin: "0 auto 40px auto",
3198
+ maxWidth: "440px",
3199
+ padding: 0,
3200
+ textAlign: "center"
3201
+ };
3202
+ var ACTIONS_STYLE = {
3203
+ display: "flex",
3204
+ flexWrap: "wrap",
3205
+ gap: "16px",
3206
+ justifyContent: "center"
3207
+ };
3208
+ var BUTTON_BASE = {
3209
+ border: 0,
3210
+ cursor: "pointer",
3211
+ display: "inline-flex",
3212
+ fontFamily: FONT_SANS,
3213
+ fontSize: "14px",
3214
+ fontWeight: 500,
3215
+ lineHeight: 1,
3216
+ minWidth: "120px",
3217
+ padding: "10px 16px",
3218
+ textAlign: "center",
3219
+ textDecoration: "none",
3220
+ transition: "background-color 120ms ease, color 120ms ease, opacity 120ms ease",
3221
+ appearance: "none",
3222
+ alignItems: "center",
3223
+ justifyContent: "center",
3224
+ boxSizing: "border-box"
3225
+ };
3226
+ var BUTTON_PRIMARY = {
3227
+ ...BUTTON_BASE,
3228
+ backgroundColor: COLOR_TEXT,
3229
+ border: `1px solid ${COLOR_TEXT}`,
3230
+ boxShadow: "0 10px 24px rgba(255, 255, 255, 0.08)",
3231
+ color: COLOR_BG,
3232
+ fontWeight: 600
3233
+ };
3234
+ var BUTTON_SECONDARY = {
3235
+ ...BUTTON_BASE,
3236
+ backgroundColor: "transparent",
3237
+ border: "1px solid rgba(255, 255, 255, 0.22)",
3238
+ color: COLOR_TEXT_DIM
3239
+ };
3240
+ var DIVIDER_STYLE = {
3241
+ backgroundColor: "rgba(255, 255, 255, 0.12)",
3242
+ border: 0,
3243
+ height: "1px",
3244
+ margin: "0 0 40px 0",
3245
+ width: "100%"
3246
+ };
3247
+ var RESET_CSS = `
3248
+ html, body {
3249
+ margin: 0;
3250
+ padding: 0;
3251
+ background-color: ${COLOR_BG};
3252
+ overscroll-behavior: none;
3253
+ }
3254
+ `;
3255
+ function ScreenFrame({ badge, children }) {
3256
+ return /* @__PURE__ */ jsxDEV("div", {
3257
+ style: PAGE_STYLE,
3258
+ children: [
3259
+ /* @__PURE__ */ jsxDEV("style", {
3260
+ dangerouslySetInnerHTML: { __html: RESET_CSS }
3261
+ }, undefined, false, undefined, this),
3262
+ /* @__PURE__ */ jsxDEV("div", {
3263
+ style: FRAME_STYLE,
3264
+ children: [
3265
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
3266
+ corner: "tl"
3267
+ }, undefined, false, undefined, this),
3268
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
3269
+ corner: "tr"
3270
+ }, undefined, false, undefined, this),
3271
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
3272
+ corner: "bl"
3273
+ }, undefined, false, undefined, this),
3274
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
3275
+ corner: "br"
3276
+ }, undefined, false, undefined, this),
3277
+ /* @__PURE__ */ jsxDEV("div", {
3278
+ style: CARD_STYLE,
3279
+ children: [
3280
+ badge,
3281
+ /* @__PURE__ */ jsxDEV("hr", {
3282
+ style: DIVIDER_STYLE
3283
+ }, undefined, false, undefined, this),
3284
+ children
3285
+ ]
3286
+ }, undefined, true, undefined, this)
3287
+ ]
3288
+ }, undefined, true, undefined, this)
3289
+ ]
3290
+ }, undefined, true, undefined, this);
3291
+ }
3292
+ function DefaultErrorScreen({ message, digest, reset }) {
3293
+ return /* @__PURE__ */ jsxDEV(ScreenFrame, {
3294
+ badge: /* @__PURE__ */ jsxDEV("div", {
3295
+ style: BADGE_STYLE,
3296
+ children: "500 \u2014 ERROR"
3297
+ }, undefined, false, undefined, this),
3298
+ children: [
3299
+ /* @__PURE__ */ jsxDEV("h1", {
3300
+ style: HEADING_STYLE,
3301
+ children: "Something went wrong"
3302
+ }, undefined, false, undefined, this),
3303
+ /* @__PURE__ */ jsxDEV("div", {
3304
+ style: CODE_BOX_STYLE,
3305
+ children: [
3306
+ /* @__PURE__ */ jsxDEV("span", {
3307
+ style: CODE_LABEL_STYLE,
3308
+ children: "CODE:"
3309
+ }, undefined, false, undefined, this),
3310
+ /* @__PURE__ */ jsxDEV("span", {
3311
+ children: digest
3312
+ }, undefined, false, undefined, this)
3313
+ ]
3314
+ }, undefined, true, undefined, this),
3315
+ /* @__PURE__ */ jsxDEV("p", {
3316
+ style: DESCRIPTION_WRAPPER_STYLE,
3317
+ children: message ? message : "We encountered an unexpected error. Please try again or return to the home page."
3318
+ }, undefined, false, undefined, this),
3319
+ /* @__PURE__ */ jsxDEV("div", {
3320
+ style: ACTIONS_STYLE,
3321
+ children: [
3322
+ /* @__PURE__ */ jsxDEV(Link, {
3323
+ style: BUTTON_PRIMARY,
3324
+ to: "/",
3325
+ children: "Go Home"
3326
+ }, undefined, false, undefined, this),
3327
+ /* @__PURE__ */ jsxDEV("button", {
3328
+ onClick: reset,
3329
+ style: BUTTON_SECONDARY,
3330
+ type: "button",
3331
+ children: "Try again"
3332
+ }, undefined, false, undefined, this)
3333
+ ]
3334
+ }, undefined, true, undefined, this)
3335
+ ]
3336
+ }, undefined, true, undefined, this);
3337
+ }
3338
+ function DefaultNotFoundScreen({ message }) {
3339
+ return /* @__PURE__ */ jsxDEV(ScreenFrame, {
3340
+ badge: /* @__PURE__ */ jsxDEV("div", {
3341
+ style: NOT_FOUND_BADGE_STYLE,
3342
+ children: "404 \u2014 NOT FOUND"
3343
+ }, undefined, false, undefined, this),
3344
+ children: [
3345
+ /* @__PURE__ */ jsxDEV("h1", {
3346
+ style: HEADING_STYLE,
3347
+ children: "This page does not exist"
3348
+ }, undefined, false, undefined, this),
3349
+ /* @__PURE__ */ jsxDEV("p", {
3350
+ style: DESCRIPTION_WRAPPER_STYLE,
3351
+ children: message ? message : "The page you are looking for could not be found. It may have been moved or removed."
3352
+ }, undefined, false, undefined, this),
3353
+ /* @__PURE__ */ jsxDEV("div", {
3354
+ style: ACTIONS_STYLE,
3355
+ children: /* @__PURE__ */ jsxDEV(Link, {
3356
+ style: BUTTON_PRIMARY,
3357
+ to: "/",
3358
+ children: "Go Home"
3359
+ }, undefined, false, undefined, this)
3360
+ }, undefined, false, undefined, this)
3361
+ ]
3362
+ }, undefined, true, undefined, this);
3363
+ }
3364
+
3365
+ // src/render/digest.ts
3366
+ function computeErrorDigest(err) {
3367
+ let message = "";
3368
+ let stack = "";
3369
+ if (err instanceof Error) {
3370
+ message = err.message;
3371
+ stack = err.stack ?? "";
3372
+ } else if (typeof err === "string") {
3373
+ message = err;
3374
+ } else {
3375
+ try {
3376
+ message = JSON.stringify(err) ?? String(err);
3377
+ } catch {
3378
+ message = String(err);
3379
+ }
3380
+ }
3381
+ const input = `${message}
3382
+ ${stack}`;
3383
+ const hash = cyrb53(input);
3384
+ const hex = hash.toString(16).padStart(14, "0");
3385
+ return hex.slice(0, 10);
3386
+ }
3387
+ function cyrb53(input) {
3388
+ let h1 = 3735928559;
3389
+ let h2 = 1103547991;
3390
+ for (let i = 0;i < input.length; i++) {
3391
+ const ch = input.charCodeAt(i);
3392
+ h1 = Math.imul(h1 ^ ch, 2654435761);
3393
+ h2 = Math.imul(h2 ^ ch, 1597334677);
3394
+ }
3395
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
3396
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
3397
+ return 4294967296 * (2097151 & h2) + (4294967295 & h1);
3398
+ }
3399
+
3400
+ // src/render/boundaries.tsx
3401
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
3402
+ var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV2(DefaultErrorScreen, {
3403
+ digest: error.digest,
3404
+ message: error.message,
3405
+ reset
3406
+ }, undefined, false, undefined, this);
3407
+ var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV2(DefaultNotFoundScreen, {
3408
+ message: error.message
3409
+ }, undefined, false, undefined, this);
3410
+ var SERVER_RESET_NOOP = () => {};
3411
+
3412
+ class FurinErrorBoundary extends Component {
3413
+ state = {
3414
+ digest: null,
3415
+ epoch: 0,
3416
+ error: null
3417
+ };
3418
+ static getDerivedStateFromError(error) {
3419
+ return { digest: computeErrorDigest(error), error };
3420
+ }
3421
+ componentDidUpdate(prevProps) {
3422
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
3423
+ this.reset();
3424
+ }
3425
+ }
3426
+ reset = () => {
3427
+ this.setState((s) => ({ digest: null, epoch: s.epoch + 1, error: null }), () => {
3428
+ this.props.onReset?.();
3429
+ });
3430
+ };
3431
+ render() {
3432
+ const { error, epoch, digest } = this.state;
3433
+ if (error) {
3434
+ if (isNotFoundError(error)) {
3435
+ throw error;
3436
+ }
3437
+ const Fallback = this.props.fallback ?? DefaultErrorFallback;
3438
+ const finalDigest = digest ?? this.props.digest ?? computeErrorDigest(error);
3439
+ const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
3440
+ return /* @__PURE__ */ jsxDEV2(Fallback, {
3441
+ error: { message, digest: finalDigest },
3442
+ reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
3443
+ }, undefined, false, undefined, this);
3444
+ }
3445
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
3446
+ children: this.props.children
3447
+ }, epoch, false, undefined, this);
3448
+ }
3449
+ }
3450
+
3451
+ class FurinNotFoundBoundary extends Component {
3452
+ state = { epoch: 0, error: null };
3453
+ static getDerivedStateFromError(error) {
3454
+ return { error };
3455
+ }
3456
+ componentDidUpdate(prevProps) {
3457
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
3458
+ this.setState((s) => ({ error: null, epoch: s.epoch + 1 }));
3459
+ }
3460
+ }
3461
+ render() {
3462
+ const { error, epoch } = this.state;
3463
+ if (error) {
3464
+ if (!isNotFoundError(error)) {
3465
+ throw error;
3466
+ }
3467
+ const Fallback = this.props.fallback ?? DefaultNotFoundFallback;
3468
+ return /* @__PURE__ */ jsxDEV2(Fallback, {
3469
+ error: { message: error.message, data: error.data }
3470
+ }, undefined, false, undefined, this);
3471
+ }
3472
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
3473
+ children: this.props.children
3474
+ }, epoch, false, undefined, this);
3475
+ }
3476
+ }
3477
+
3478
+ // src/link.tsx
3479
+ import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
3480
+ function buildHref(to, search, hash) {
3481
+ let url = to;
3482
+ if (search && Object.keys(search).length > 0) {
3483
+ const params = new URLSearchParams;
3484
+ for (const [k, v] of Object.entries(search)) {
3485
+ if (v != null) {
3486
+ params.set(k, String(v));
3487
+ }
3488
+ }
3489
+ const qs = params.toString();
3490
+ if (qs) {
3491
+ url += `?${qs}`;
3492
+ }
3493
+ }
3494
+ if (hash) {
3495
+ url += `#${hash}`;
3496
+ }
3497
+ return url;
3498
+ }
3499
+ var RouterContext = createContext(null);
3500
+ function useRouter() {
3501
+ return useContext(RouterContext) ?? {
3502
+ basePath: "",
3503
+ currentHref: "/",
3504
+ navigate: (href) => {
3505
+ window.location.href = href;
3506
+ return Promise.resolve();
3507
+ },
3508
+ prefetch: () => {},
3509
+ invalidatePrefetch: () => {},
3510
+ refresh: () => {
3511
+ window.location.reload();
3512
+ return Promise.resolve();
3513
+ },
3514
+ isNavigating: false,
3515
+ defaultPreload: "intent",
3516
+ defaultPreloadDelay: 50,
3517
+ defaultPreloadStaleTime: 30000
3518
+ };
3519
+ }
3520
+ function computeLinkView({
3521
+ to,
3522
+ search,
3523
+ hash,
3524
+ children,
3525
+ activeProps,
3526
+ inactiveProps
3527
+ }, router) {
3528
+ const logicalHref = buildHref(to, search, hash);
3529
+ const logicalHrefWithoutHash = buildHref(to, search, undefined);
3530
+ const href = router.basePath + logicalHref;
3531
+ const isActive = router.currentHref === logicalHrefWithoutHash;
3532
+ const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
3533
+ const extraProps = {
3534
+ ...inactiveProps && !isActive ? inactiveProps() : {},
3535
+ ...activeProps ? activeProps({ isActive }) : {}
3536
+ };
3537
+ return { logicalHref, href, isActive, resolvedChildren, extraProps };
3538
+ }
3539
+ function LinkInteractive({
3540
+ to,
3541
+ search,
3542
+ hash,
3543
+ preload,
3544
+ preloadDelay,
3545
+ preloadStaleTime,
3546
+ replace,
3547
+ disabled,
3548
+ resetScroll,
3549
+ activeProps,
3550
+ inactiveProps,
3551
+ onClick,
3552
+ onMouseEnter,
3553
+ onMouseLeave,
3554
+ onFocus,
3555
+ children,
3556
+ ...anchorProps
3557
+ }) {
3558
+ const router = useRouter();
3559
+ const anchorRef = useRef(null);
3560
+ const intentTimerRef = useRef(null);
3561
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
3562
+ const effectivePreload = preload ?? router.defaultPreload;
3563
+ const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
3564
+ const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
3565
+ const triggerPrefetch = useCallback(() => {
3566
+ router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
3567
+ }, [router, logicalHref, effectiveStaleTime]);
3568
+ useEffect(() => {
3569
+ if (effectivePreload === "render") {
3570
+ triggerPrefetch();
3571
+ }
3572
+ }, [effectivePreload, triggerPrefetch]);
3573
+ useEffect(() => {
3574
+ if (effectivePreload !== "viewport" || !anchorRef.current) {
3575
+ return;
3576
+ }
3577
+ const observer = new IntersectionObserver(([entry]) => {
3578
+ if (entry?.isIntersecting) {
3579
+ triggerPrefetch();
3580
+ observer.disconnect();
3581
+ }
3582
+ }, { rootMargin: "200px" });
3583
+ observer.observe(anchorRef.current);
3584
+ return () => observer.disconnect();
3585
+ }, [effectivePreload, triggerPrefetch]);
3586
+ const isInternal = (url) => {
3587
+ try {
3588
+ return new URL(url, window.location.origin).origin === window.location.origin;
3589
+ } catch {
3590
+ return false;
3591
+ }
3592
+ };
3593
+ const handleClick = (e) => {
3594
+ onClick?.(e);
3595
+ if (e.defaultPrevented || disabled) {
3596
+ return;
3597
+ }
3598
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
3599
+ return;
3600
+ }
3601
+ if (anchorProps.target && anchorProps.target !== "_self") {
3602
+ return;
3603
+ }
3604
+ if (!isInternal(href)) {
3605
+ return;
3606
+ }
3607
+ e.preventDefault();
3608
+ router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
3609
+ };
3610
+ const handleMouseEnter = (e) => {
3611
+ onMouseEnter?.(e);
3612
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3613
+ intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
3614
+ }
3615
+ };
3616
+ const handleMouseLeave = (e) => {
3617
+ onMouseLeave?.(e);
3618
+ if (intentTimerRef.current !== null) {
3619
+ clearTimeout(intentTimerRef.current);
3620
+ intentTimerRef.current = null;
3621
+ }
3622
+ };
3623
+ const handleFocus = (e) => {
3624
+ onFocus?.(e);
3625
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
3626
+ triggerPrefetch();
3627
+ }
3628
+ };
3629
+ return createElement("a", {
3630
+ ref: anchorRef,
3631
+ href,
3632
+ onClick: handleClick,
3633
+ onMouseEnter: handleMouseEnter,
3634
+ onMouseLeave: handleMouseLeave,
3635
+ onFocus: handleFocus,
3636
+ ...isActive ? { "data-status": "active" } : {},
3637
+ ...anchorProps,
3638
+ ...extraProps,
3639
+ ...disabled ? { "aria-disabled": true } : {}
3640
+ }, resolvedChildren);
3641
+ }
3642
+ var SSR_FALLBACK_ROUTER = {
3643
+ basePath: "",
3644
+ currentHref: "/",
3645
+ navigate: () => Promise.resolve(),
3646
+ prefetch: () => {},
3647
+ invalidatePrefetch: () => {},
3648
+ refresh: () => Promise.resolve(),
3649
+ isNavigating: false,
3650
+ defaultPreload: "intent",
3651
+ defaultPreloadDelay: 50,
3652
+ defaultPreloadStaleTime: 30000
3653
+ };
3654
+ function renderLinkElement(props, router) {
3655
+ const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
3656
+ const {
3657
+ to: _to,
3658
+ search: _search,
3659
+ hash: _hash,
3660
+ children: _children,
3661
+ activeProps: _ap,
3662
+ inactiveProps: _ip,
3663
+ disabled,
3664
+ preload: _p,
3665
+ preloadDelay: _pd,
3666
+ preloadStaleTime: _ps,
3667
+ replace: _r,
3668
+ resetScroll: _rs,
3669
+ onClick: _oc,
3670
+ onMouseEnter: _ome,
3671
+ onMouseLeave: _oml,
3672
+ onFocus: _of,
3673
+ ...anchorProps
3674
+ } = props;
3675
+ return createElement("a", {
3676
+ href,
3677
+ ...isActive ? { "data-status": "active" } : {},
3678
+ ...anchorProps,
3679
+ ...extraProps,
3680
+ ...disabled ? { "aria-disabled": true } : {}
3681
+ }, resolvedChildren);
3682
+ }
3683
+ function Link(props) {
3684
+ if (typeof window === "undefined") {
3685
+ return createElement(RouterContext.Consumer, {
3686
+ children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
3687
+ });
3688
+ }
3689
+ return createElement(LinkInteractive, props);
3690
+ }
3691
+
3692
+ // src/render/cache.ts
3693
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3694
+
3695
+ // src/context-logger.ts
3696
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3697
+
3698
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
3699
+ import { AsyncLocalStorage } from "async_hooks";
3700
+ import { Elysia } from "elysia";
3701
+ var storage = new AsyncLocalStorage;
3702
+ var activeLoggers = /* @__PURE__ */ new WeakSet;
3703
+ function useLogger2() {
3704
+ const logger = storage.getStore();
3705
+ if (!logger || !activeLoggers.has(logger))
3706
+ throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
3707
+ return logger;
3708
+ }
3709
+
3710
+ // src/context-logger.ts
3711
+ var noopLogger2 = {
3712
+ set: () => {},
3713
+ error: () => {},
3714
+ info: () => {},
3715
+ warn: () => {},
3716
+ emit: () => null,
3717
+ getContext: () => ({}),
3718
+ fork: (_label, fn) => fn()
3719
+ };
3720
+ var syntheticRenderStorage = new AsyncLocalStorage2;
3721
+ function useLogger3() {
3722
+ try {
3723
+ return useLogger2();
3724
+ } catch {
3725
+ return syntheticRenderStorage.getStore() ?? noopLogger2;
3726
+ }
3727
+ }
3728
+ async function runInSyntheticRenderScope(fn, initialContext) {
3729
+ const logger = createLogger(initialContext);
3730
+ try {
3731
+ const result = await syntheticRenderStorage.run(logger, () => Promise.resolve(fn()));
3732
+ logger.emit();
3733
+ return result;
3734
+ } catch (err) {
3735
+ logger.error(err instanceof Error ? err : new Error(String(err)));
3736
+ logger.emit();
3737
+ throw err;
3738
+ }
3739
+ }
3740
+
3741
+ // src/render/cache.ts
3742
+ var MAX_SSG_CACHE_SIZE = 1000;
3743
+ var isrCache = new Map;
3744
+ var ssgCache = new Map;
3745
+ function evictOldest(map, maxSize) {
3746
+ if (map.size > maxSize) {
3747
+ const oldest = map.keys().next().value;
3748
+ if (oldest !== undefined) {
3749
+ map.delete(oldest);
3750
+ }
3751
+ }
3752
+ }
3753
+ function getSSGCache(key) {
3754
+ const entry = ssgCache.get(key);
3755
+ if (entry !== undefined) {
3756
+ ssgCache.delete(key);
3757
+ ssgCache.set(key, entry);
3758
+ }
3759
+ return entry;
3760
+ }
3761
+ function setSSGCache(key, entry) {
3762
+ ssgCache.delete(key);
3763
+ ssgCache.set(key, entry);
3764
+ evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
3765
+ }
3766
+ var _requestInvalidationScope = new AsyncLocalStorage3;
3767
+ var _globalPendingInvalidations = new Set;
3768
+
3769
+ // src/render/element.tsx
3770
+ import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
3771
+ function wrapInBoundaries(inner, segment) {
3772
+ if (!segment) {
3773
+ return inner;
3774
+ }
3775
+ let wrapped = inner;
3776
+ if (segment.notFound) {
3777
+ wrapped = /* @__PURE__ */ jsxDEV4(FurinNotFoundBoundary, {
3778
+ fallback: segment.notFound,
3779
+ children: wrapped
3780
+ }, undefined, false, undefined, this);
3781
+ }
3782
+ if (segment.error) {
3783
+ wrapped = /* @__PURE__ */ jsxDEV4(FurinErrorBoundary, {
3784
+ fallback: segment.error,
3785
+ children: wrapped
3786
+ }, undefined, false, undefined, this);
3787
+ }
3788
+ return wrapped;
3789
+ }
3790
+ function buildElement(route, data, rootLayout) {
3791
+ const Component2 = route.page.component;
3792
+ let element = /* @__PURE__ */ jsxDEV4(Component2, {
3793
+ ...data
3794
+ }, undefined, false, undefined, this);
3795
+ const byDepth = new Map;
3796
+ for (const segment of route.segmentBoundaries ?? []) {
3797
+ byDepth.set(segment.depth, segment);
3798
+ }
3799
+ for (let i = route.routeChain.length - 1;i >= 1; i--) {
3800
+ element = wrapInBoundaries(element, byDepth.get(i));
3801
+ const routeEntry = route.routeChain[i];
3802
+ if (routeEntry?.layout) {
3803
+ const Layout = routeEntry.layout;
3804
+ element = /* @__PURE__ */ jsxDEV4(Layout, {
3805
+ ...data,
3806
+ children: element
3807
+ }, undefined, false, undefined, this);
3808
+ }
3809
+ }
3810
+ element = wrapInBoundaries(element, byDepth.get(0));
3811
+ if (rootLayout.layout) {
3812
+ const RootLayoutComponent = rootLayout.layout;
3813
+ element = /* @__PURE__ */ jsxDEV4(RootLayoutComponent, {
3814
+ ...data,
3815
+ children: element
3816
+ }, undefined, false, undefined, this);
3817
+ }
3818
+ return element;
3819
+ }
3820
+ var DefaultNotFoundComponent = ({ error }) => /* @__PURE__ */ jsxDEV4(DefaultNotFoundScreen, {
3821
+ message: error.message
3822
+ }, undefined, false, undefined, this);
3823
+ function buildNotFoundElement(component, error) {
3824
+ const NotFound = component ?? DefaultNotFoundComponent;
3825
+ return /* @__PURE__ */ jsxDEV4(NotFound, {
3826
+ error: { message: error.message, data: error.data }
3827
+ }, undefined, false, undefined, this);
3828
+ }
3829
+ var DefaultErrorComponent = ({ error, reset }) => /* @__PURE__ */ jsxDEV4(DefaultErrorScreen, {
3830
+ digest: error.digest,
3831
+ message: error.message,
3832
+ reset
3833
+ }, undefined, false, undefined, this);
3834
+ function errorMessageOf(err) {
3835
+ if (err instanceof Error) {
3836
+ return err.message;
3837
+ }
3838
+ if (typeof err === "string") {
3839
+ return err;
3840
+ }
3841
+ return "";
3842
+ }
3843
+ var SERVER_RESET_NOOP2 = () => {};
3844
+ function buildErrorElement(component, error, digest) {
3845
+ const ErrorView = component ?? DefaultErrorComponent;
3846
+ const message = component ? errorMessageOf(error) : "An unexpected error occurred.";
3847
+ return /* @__PURE__ */ jsxDEV4(ErrorView, {
3848
+ error: { message, digest },
3849
+ reset: SERVER_RESET_NOOP2
3850
+ }, undefined, false, undefined, this);
3851
+ }
3852
+
3853
+ // src/render/loaders.ts
3854
+ function createLoaderCtx(ctx, accumulatedParentPromise) {
3855
+ const cache = new Map;
3856
+ return new Proxy(ctx, {
3857
+ get(target, prop) {
3858
+ if (typeof prop !== "string") {
3859
+ return Reflect.get(target, prop);
3860
+ }
3861
+ if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
3862
+ return Reflect.get(target, prop);
3863
+ }
3864
+ if (Object.hasOwn(target, prop)) {
3865
+ return target[prop];
3866
+ }
3867
+ let entry = cache.get(prop);
3868
+ if (!entry) {
3869
+ entry = accumulatedParentPromise.then((data) => data[prop]);
3870
+ cache.set(prop, entry);
3871
+ }
3872
+ return entry;
3873
+ }
3874
+ });
3875
+ }
3876
+ async function runLoaders(route, ctx, _rootLayout) {
3877
+ try {
3878
+ const ctxRecord = { ...ctx, log: useLogger3() };
3879
+ const loaderMap = new Map;
3880
+ let accumulatedParentPromise = Promise.resolve({});
3881
+ for (const r of route.routeChain) {
3882
+ const parentAccum = accumulatedParentPromise;
3883
+ if (r.loader) {
3884
+ const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
3885
+ const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
3886
+ loaderMap.set(r, loaderPromise);
3887
+ accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
3888
+ ...acc,
3889
+ ...own
3890
+ }));
3891
+ accumulatedParentPromise.catch(() => {});
3892
+ }
3893
+ }
3894
+ const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
3895
+ const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
3896
+ const results = await Promise.all([...loaderMap.values(), pagePromise]);
3897
+ const data = Object.assign({}, ...results);
3898
+ const headers = {};
3899
+ Object.assign(headers, ctx.set.headers);
3900
+ return { type: "data", data, headers };
3901
+ } catch (err) {
3902
+ if (isNotFoundError(err)) {
3903
+ const headers2 = {};
3904
+ Object.assign(headers2, ctx.set.headers);
3905
+ return { type: "not-found", error: err, headers: headers2 };
3906
+ }
3907
+ if (err instanceof Response) {
3908
+ return { type: "redirect", response: err };
3909
+ }
3910
+ const headers = {};
3911
+ Object.assign(headers, ctx.set.headers);
3912
+ return { type: "error", error: err, headers };
3913
+ }
3914
+ }
3915
+
3916
+ // src/render/template.ts
3917
+ import { readFileSync as readFileSync3 } from "fs";
3918
+ var _prodTemplatePath = null;
3919
+ var _prodTemplateContent = null;
3920
+ var _devTemplateCache = null;
3921
+ var DEV_TEMPLATE_TTL_MS = 1000;
3922
+ async function getDevTemplate(origin) {
3923
+ if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
3924
+ return _devTemplateCache.html;
3925
+ }
3926
+ const r = await fetch(`${origin}/_bun_hmr_entry`);
3927
+ if (!r.ok) {
3928
+ throw new Error(`/_bun_hmr_entry returned ${r.status}`);
3929
+ }
3930
+ const html = await r.text();
3931
+ _devTemplateCache = { html, ts: Date.now() };
3932
+ return html;
3933
+ }
3934
+ function setProductionTemplateContent(content) {
3935
+ _prodTemplatePath = null;
3936
+ _prodTemplateContent = content;
3937
+ }
3938
+ function getProductionTemplate() {
3939
+ if (_prodTemplateContent !== null) {
3940
+ return _prodTemplateContent;
3941
+ }
3942
+ if (!_prodTemplatePath) {
3943
+ return null;
3944
+ }
3945
+ try {
3946
+ _prodTemplateContent = readFileSync3(_prodTemplatePath, "utf8");
3947
+ return _prodTemplateContent;
3948
+ } catch {
3949
+ return null;
3950
+ }
3951
+ }
3952
+ // src/runtime-env.ts
3953
+ var IS_DEV = true;
3954
+
3955
+ // src/render/index.ts
3956
+ function withSSRRouterContext(element, contextValue) {
3957
+ return createElement2(RouterContext.Provider, { value: contextValue }, element);
3958
+ }
3959
+ async function prepareRender(route, ctx, root, basePath, throwOnFailure) {
3960
+ const loaderStart = Date.now();
3961
+ const loaderResult = await runLoaders(route, ctx, root.route);
3962
+ const loader_ms = Date.now() - loaderStart;
3963
+ if (loaderResult.type === "redirect") {
3964
+ return loaderResult.response;
3965
+ }
3966
+ if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
3967
+ throw loaderResult.error;
3968
+ }
3969
+ const isNotFound = loaderResult.type === "not-found";
3970
+ const isError = loaderResult.type === "error";
3971
+ const isFallback = isNotFound || isError;
3972
+ const data = isFallback ? {} : loaderResult.data;
3973
+ const headers = loaderResult.headers;
3974
+ const componentProps = {
3975
+ ...data,
3976
+ params: ctx.params,
3977
+ query: ctx.query,
3978
+ path: ctx.path
3979
+ };
3980
+ const headData = isFallback ? "" : buildHeadInjection(route.page?.head?.(componentProps));
3981
+ const prodTemplate = getProductionTemplate();
3982
+ const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
3983
+ let element;
3984
+ let status = 200;
3985
+ let errorDigest;
3986
+ let notFoundError;
3987
+ if (loaderResult.type === "not-found") {
3988
+ element = buildNotFoundElement(route.notFound ?? root.notFound, loaderResult.error);
3989
+ status = 404;
3990
+ notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
3991
+ } else if (loaderResult.type === "error") {
3992
+ errorDigest = computeErrorDigest(loaderResult.error);
3993
+ element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest);
3994
+ status = 500;
3995
+ } else {
3996
+ element = buildElement(route, componentProps, root.route);
3997
+ }
3998
+ const ssrContext = {
3999
+ basePath: basePath ?? "",
4000
+ currentHref: ctx.path,
4001
+ navigate: () => Promise.resolve(),
4002
+ prefetch: () => {},
4003
+ invalidatePrefetch: () => {},
4004
+ refresh: () => Promise.resolve(),
4005
+ isNavigating: false,
4006
+ defaultPreload: "intent",
4007
+ defaultPreloadDelay: 50,
4008
+ defaultPreloadStaleTime: 30000
4009
+ };
4010
+ element = withSSRRouterContext(element, ssrContext);
4011
+ return {
4012
+ componentProps,
4013
+ element,
4014
+ errorDigest,
4015
+ headData,
4016
+ headers,
4017
+ loader_ms,
4018
+ notFoundError,
4019
+ ssrContext,
4020
+ status,
4021
+ template
4022
+ };
4023
+ }
4024
+ function renderForPath(route, params, root, origin, mode, basePath) {
4025
+ return runInSyntheticRenderScope(async () => {
4026
+ const resolvedPath = resolvePath(route.pattern, params);
4027
+ const ctx = {
4028
+ params,
4029
+ query: {},
4030
+ request: new Request(`${origin}${resolvedPath}`),
4031
+ headers: {},
4032
+ cookie: {},
4033
+ redirect: (url, status2) => new Response(null, { status: status2 ?? 302, headers: { Location: url } }),
4034
+ set: { headers: {} },
4035
+ path: resolvedPath
4036
+ };
4037
+ const prepared = await prepareRender(route, ctx, root, basePath, true);
4038
+ if (prepared instanceof Response) {
4039
+ return prepared;
4040
+ }
4041
+ useLogger3().set({
4042
+ furin: {
4043
+ render: mode,
4044
+ route: route.pattern,
4045
+ cache: mode === "isr" ? "revalidated" : "miss",
4046
+ loader_ms: prepared.loader_ms,
4047
+ ...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
4048
+ }
4049
+ });
4050
+ const { componentProps, element, headData, headers, status, template } = prepared;
4051
+ const stream = await renderToReadableStream(element);
4052
+ await stream.allReady;
4053
+ const reactHtml = await streamToString(stream);
4054
+ return {
4055
+ html: assembleHTML(template, headData, reactHtml, componentProps),
4056
+ headers,
4057
+ status
4058
+ };
4059
+ }, { route: route.pattern, render: mode });
4060
+ }
4061
+ async function prerenderSSG(route, params, root, origin, basePath) {
4062
+ const resolvedPath = resolvePath(route.pattern, params);
4063
+ const cached = getSSGCache(resolvedPath);
4064
+ if (cached && !IS_DEV) {
4065
+ return cached;
4066
+ }
4067
+ const renderResult = await renderForPath(route, params, root, origin, "ssg", basePath);
4068
+ if (renderResult instanceof Response) {
4069
+ return renderResult;
4070
+ }
4071
+ const result = renderResult;
4072
+ const entry = { html: result.html, cachedAt: Date.now(), status: result.status };
4073
+ if (!IS_DEV) {
4074
+ setSSGCache(resolvedPath, entry);
4075
+ }
4076
+ return entry;
4077
+ }
4078
+ var pendingRevalidations = new Set;
4079
+
4080
+ // src/adapter/static.ts
4081
+ var STATIC_CONCURRENCY = 4;
4082
+ var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
4083
+ var TRAILING_SLASHES_RE = /\/+$/;
4084
+ function pathToOutputFile(urlPath, outDir) {
4085
+ const normalizedOutDir = resolve2(outDir);
4086
+ if (urlPath === "/" || urlPath === "") {
4087
+ return join8(normalizedOutDir, "index.html");
4088
+ }
4089
+ const resolved = resolve2(normalizedOutDir, urlPath.slice(1), "index.html");
4090
+ if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
4091
+ throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
4092
+ }
4093
+ return resolved;
4094
+ }
4095
+ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath) {
4096
+ const urlPath = resolvePath(route.pattern, params);
4097
+ const outputFile = pathToOutputFile(urlPath, outDir);
4098
+ try {
4099
+ const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
4100
+ if (entry instanceof Response) {
4101
+ console.warn(`[furin] static: route "${route.pattern}" loader returned a redirect \u2014 skipping.`);
4102
+ return;
4103
+ }
4104
+ ensureDir(dirname3(outputFile));
4105
+ writeFileSync7(outputFile, entry.html);
4106
+ renderedRoutes.push(urlPath);
4107
+ console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(outputFile)}`);
4108
+ } catch (err) {
4109
+ console.error(`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`, err);
4110
+ skippedRoutes.push(urlPath);
4111
+ }
4112
+ }
4113
+ function collectSsgRoutes(routes, onSSR, skippedRoutes) {
4114
+ const nonSsg = routes.filter((r) => r.mode !== "ssg");
4115
+ if (nonSsg.length === 0) {
4116
+ return routes;
4117
+ }
4118
+ if (onSSR === "error") {
4119
+ const list = nonSsg.map((r) => ` \u2022 ${r.pattern} (mode: ${r.mode})`).join(`
4120
+ `);
4121
+ throw new Error(`[furin] Cannot produce a static export: the following routes are not SSG and cannot be pre-rendered.
4122
+ ` + `Either change their mode to "ssg", remove them, or set \`onSSR: "skip"\` in your static config.
4123
+
4124
+ ` + `${list}`);
4125
+ }
4126
+ for (const r of nonSsg) {
4127
+ console.warn(`[furin] static: skipping route "${r.pattern}" (mode=${r.mode}) \u2014 not statically exportable.`);
4128
+ skippedRoutes.push(r.pattern);
4129
+ }
4130
+ return routes.filter((r) => r.mode === "ssg");
4131
+ }
4132
+ async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath) {
4133
+ const tasks = [];
4134
+ for (const route of ssgRoutes) {
4135
+ if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
4136
+ tasks.push(() => prerenderAndWrite(route, {}, root, outDir, renderedRoutes, skippedRoutes, basePath));
4137
+ continue;
4138
+ }
4139
+ if (!route.page.staticParams) {
4140
+ console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
4141
+ skippedRoutes.push(route.pattern);
4142
+ continue;
4143
+ }
4144
+ try {
4145
+ const paramSets = await route.page.staticParams() ?? [];
4146
+ for (const params of paramSets) {
4147
+ tasks.push(() => prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
4148
+ }
4149
+ } catch (err) {
4150
+ console.error(`[furin] static: staticParams() failed for "${route.pattern}":`, err);
4151
+ skippedRoutes.push(route.pattern);
4152
+ }
4153
+ }
4154
+ return tasks;
4155
+ }
4156
+ async function runWithConcurrency(tasks, concurrency) {
4157
+ const queue = [...tasks];
4158
+ const workerCount = Math.min(concurrency, Math.max(queue.length, 1));
4159
+ await Promise.all(Array.from({ length: workerCount }, async () => {
4160
+ while (queue.length > 0) {
4161
+ await queue.shift()?.();
4162
+ }
4163
+ }));
4164
+ }
4165
+ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
4166
+ const staticConfig = options.staticConfig ?? {};
4167
+ const rawBasePath = staticConfig.basePath ?? "";
4168
+ let basePath;
4169
+ if (rawBasePath === "/" || rawBasePath === "") {
4170
+ basePath = "";
4171
+ } else if (rawBasePath.endsWith("/")) {
4172
+ basePath = rawBasePath.replace(TRAILING_SLASHES_RE, "");
4173
+ } else {
4174
+ basePath = rawBasePath;
4175
+ }
4176
+ if (basePath && !basePath.startsWith("/")) {
4177
+ throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
4178
+ }
4179
+ const outDir = resolve2(rootDir, staticConfig.outDir ?? "dist");
4180
+ const normalizedRoot = resolve2(rootDir);
4181
+ const normalizedBuildRoot = resolve2(buildRoot);
4182
+ if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === "/" || outDir === ".") {
4183
+ throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
4184
+ }
4185
+ function isOutsideOutDir(target) {
4186
+ const rel = relative3(outDir, target);
4187
+ return rel.startsWith("..") || isAbsolute(rel);
4188
+ }
4189
+ if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
4190
+ throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
4191
+ }
4192
+ const onSSR = staticConfig.onSSR ?? "error";
4193
+ const publicPath = basePath ? `${basePath}/_client/` : "/_client/";
4194
+ const renderedRoutes = [];
4195
+ const skippedRoutes = [];
4196
+ const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
4197
+ rmSync3(outDir, { force: true, recursive: true });
4198
+ ensureDir(outDir);
4199
+ const targetDir = join8(buildRoot, "static");
4200
+ rmSync3(targetDir, { force: true, recursive: true });
4201
+ ensureDir(targetDir);
4202
+ const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
4203
+ outDir: targetDir,
4204
+ rootLayout: root.path,
4205
+ plugins: options.plugins,
4206
+ publicPath,
4207
+ basePath
4208
+ });
4209
+ const publicFavicon = join8(rootDir, "public", "favicon.ico");
4210
+ const faviconHref = existsSync7(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
4211
+ const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref);
4212
+ setProductionTemplateContent(shellHtml);
4213
+ const publicSrcDir = join8(rootDir, "public");
4214
+ if (existsSync7(publicSrcDir)) {
4215
+ cpSync2(publicSrcDir, outDir, { recursive: true });
4216
+ }
4217
+ const clientSrcDir = join8(targetDir, "client");
4218
+ if (existsSync7(clientSrcDir)) {
4219
+ cpSync2(clientSrcDir, join8(outDir, "_client"), { recursive: true });
4220
+ }
4221
+ const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath);
4222
+ const afterQueueCount = skippedRoutes.length;
4223
+ await runWithConcurrency(tasks, STATIC_CONCURRENCY);
4224
+ if (onSSR === "error" && skippedRoutes.length > afterQueueCount) {
4225
+ const failed = skippedRoutes.slice(afterQueueCount);
4226
+ const list = failed.map((r) => ` \u2022 ${r}`).join(`
4227
+ `);
4228
+ throw new Error(`[furin] static: ${failed.length} route(s) failed to pre-render:
4229
+ ${list}
4230
+ ` + `Set \`onSSR: "skip"\` in your static config to suppress this error.`);
4231
+ }
4232
+ writeFileSync7(join8(outDir, "404.html"), shellHtml);
4233
+ console.log("[furin] static: wrote 404.html (SPA shell fallback)");
4234
+ rmSync3(targetDir, { force: true, recursive: true });
4235
+ console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
4236
+ return {
4237
+ basePath,
4238
+ generatedAt: new Date().toISOString(),
4239
+ outDir: toPosixPath(outDir),
4240
+ renderedRoutes,
4241
+ skippedRoutes
4242
+ };
4243
+ }
4244
+
4245
+ // src/config.ts
4246
+ import { t } from "elysia";
4247
+ var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
4248
+ var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
4249
+ var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
4250
+ var configSchema = t.Object({
4251
+ rootDir: t.Optional(t.String()),
4252
+ pagesDir: t.Optional(t.String()),
4253
+ serverEntry: t.Optional(t.String()),
4254
+ targets: t.Optional(t.Array(buildTargetSchema)),
4255
+ bun: t.Optional(t.Object({
4256
+ compile: t.Optional(compileTargetSchema)
4257
+ })),
4258
+ static: t.Optional(t.Object({
4259
+ basePath: t.Optional(t.String()),
4260
+ outDir: t.Optional(t.String()),
4261
+ onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")]))
4262
+ }))
4263
+ });
4264
+
4265
+ // src/router.ts
4266
+ import { existsSync as existsSync8 } from "fs";
4267
+ import { readdir } from "fs/promises";
4268
+ import { join as join9, parse } from "path";
4269
+ import { Elysia as Elysia2, t as t2 } from "elysia";
4270
+
4271
+ // src/internal.ts
4272
+ var _compileCtx = null;
4273
+ function getCompileContext() {
4274
+ return _compileCtx;
4275
+ }
4276
+
4277
+ // src/utils.ts
4278
+ function isFurinPage(value) {
4279
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
4280
+ }
4281
+ function isFurinRoute(value) {
4282
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
4283
+ }
4284
+ function collectRouteChainFromRoute(route) {
4285
+ const chain = [];
4286
+ let current = route;
4287
+ while (current) {
4288
+ chain.unshift(current);
4289
+ current = current.parent;
4290
+ }
4291
+ return chain;
4292
+ }
4293
+ function hasCycle(route) {
4294
+ const visited = new Set;
4295
+ let current = route;
4296
+ while (current) {
4297
+ if (visited.has(current)) {
4298
+ return true;
4299
+ }
4300
+ visited.add(current);
4301
+ current = current.parent;
4302
+ }
4303
+ return false;
4304
+ }
4305
+ function validateRouteChain(chain, root, pagePath) {
4306
+ const hasRoot = chain.some((r) => r === root);
4307
+ if (!hasRoot) {
4308
+ const location = pagePath ? `in ${pagePath}` : "";
4309
+ throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
4310
+ }
4311
+ for (const route of chain) {
4312
+ if (hasCycle(route)) {
4313
+ throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
4314
+ }
4315
+ }
4316
+ }
4317
+
4318
+ // src/router.ts
4319
+ async function scanPages(pagesDir) {
4320
+ const root = await scanRootLayout(pagesDir);
4321
+ const routes = await scanPageFiles(pagesDir, root);
4322
+ return { root, routes };
4323
+ }
4324
+ async function scanRootLayout(pagesDir) {
4325
+ const rootPath = `${pagesDir}/root.tsx`;
4326
+ const ctx = getCompileContext();
4327
+ if (!(existsSync8(rootPath) || ctx?.modules[rootPath])) {
4328
+ throw new Error("[furin] root.tsx: not found.");
4329
+ }
4330
+ const mod = ctx?.modules[rootPath] ?? await import(rootPath);
4331
+ const rootExport = mod.route ?? mod.default;
4332
+ if (!(rootExport && isFurinRoute(rootExport))) {
4333
+ throw new Error("[furin] root.tsx: createRoute() export not found.");
4334
+ }
4335
+ if (!rootExport.layout) {
4336
+ throw new Error("[furin] root.tsx: createRoute() has no layout.");
4337
+ }
4338
+ const notFoundEntry = await loadConventionComponent(pagesDir, "not-found");
4339
+ const errorEntry = await loadConventionComponent(pagesDir, "error");
4340
+ return {
4341
+ path: rootPath,
4342
+ route: rootExport,
4343
+ notFound: notFoundEntry?.component,
4344
+ notFoundPath: notFoundEntry?.path,
4345
+ error: errorEntry?.component,
4346
+ errorPath: errorEntry?.path
4347
+ };
4348
+ }
4349
+ var CONVENTION_FILE_NAMES = ["not-found", "error"];
4350
+ function isConventionFileName(name) {
4351
+ return CONVENTION_FILE_NAMES.includes(name);
4352
+ }
4353
+ async function loadConventionComponent(dir, name) {
4354
+ const ctx = getCompileContext();
4355
+ for (const ext of [".tsx", ".ts", ".jsx", ".js"]) {
4356
+ const filePath = `${dir}/${name}${ext}`;
4357
+ if (existsSync8(filePath) || ctx?.modules[filePath]) {
4358
+ const mod = ctx?.modules[filePath] ?? await import(filePath);
4359
+ if (mod.default) {
4360
+ return { component: mod.default, path: filePath };
4361
+ }
4362
+ }
4363
+ }
4364
+ return;
4365
+ }
4366
+ async function scanPageFiles(pagesDir, root) {
4367
+ const routes = [];
4368
+ const notFoundCache = new Map;
4369
+ const errorCache = new Map;
4370
+ for (const absolutePath of await collectPageFilePaths(pagesDir)) {
4371
+ if (![".tsx", ".ts", ".jsx", ".js"].some((ext) => absolutePath.endsWith(ext))) {
4372
+ continue;
4373
+ }
4374
+ const relativePath = absolutePath.replace(`${pagesDir}/`, "");
4375
+ const fileName = parse(relativePath).name;
4376
+ if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
4377
+ continue;
4378
+ }
4379
+ const notFound = await resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound);
4380
+ const errorComponent = await resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error);
4381
+ const segmentBoundaries = await collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache);
4382
+ if (IS_DEV) {
4383
+ const devRoute = await buildDevRoute(absolutePath, relativePath, root);
4384
+ devRoute.notFound = notFound;
4385
+ devRoute.error = errorComponent;
4386
+ devRoute.segmentBoundaries = segmentBoundaries;
4387
+ routes.push(devRoute);
4388
+ continue;
4389
+ }
4390
+ const ctx = getCompileContext();
4391
+ const pageMod = ctx?.modules[absolutePath] ?? await import(absolutePath);
4392
+ const page = pageMod.default;
4393
+ if (!isFurinPage(page)) {
4394
+ throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
4395
+ }
4396
+ const routeChain = collectRouteChainFromRoute(page._route);
4397
+ validateRouteChain(routeChain, root.route, relativePath);
4398
+ routes.push({
4399
+ pattern: filePathToPattern(relativePath),
4400
+ page,
4401
+ path: absolutePath,
4402
+ routeChain,
4403
+ mode: resolveMode(page, routeChain),
4404
+ notFound,
4405
+ error: errorComponent,
4406
+ segmentBoundaries
4407
+ });
4408
+ }
4409
+ return routes;
4410
+ }
4411
+ async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
4412
+ const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
4413
+ const dirs = [pagesDir];
4414
+ if (pageDir.length > pagesDir.length) {
4415
+ const relativeTail = pageDir.slice(pagesDir.length + 1);
4416
+ const parts = relativeTail.split("/");
4417
+ let acc = pagesDir;
4418
+ for (const part of parts) {
4419
+ acc = `${acc}/${part}`;
4420
+ dirs.push(acc);
4421
+ }
4422
+ }
4423
+ const boundaries = [];
4424
+ for (let depth = 0;depth < dirs.length; depth++) {
4425
+ const dir = dirs[depth];
4426
+ if (!errorCache.has(dir)) {
4427
+ errorCache.set(dir, await loadConventionComponent(dir, "error"));
4428
+ }
4429
+ if (!notFoundCache.has(dir)) {
4430
+ notFoundCache.set(dir, await loadConventionComponent(dir, "not-found"));
4431
+ }
4432
+ const errorEntry = errorCache.get(dir);
4433
+ const notFoundEntry = notFoundCache.get(dir);
4434
+ if (errorEntry || notFoundEntry) {
4435
+ boundaries.push({
4436
+ path: dir,
4437
+ depth,
4438
+ error: errorEntry?.component,
4439
+ errorPath: errorEntry?.path,
4440
+ notFound: notFoundEntry?.component,
4441
+ notFoundPath: notFoundEntry?.path
4442
+ });
4443
+ }
4444
+ }
4445
+ return boundaries;
4446
+ }
4447
+ async function resolveNearestConvention(pageAbsolutePath, pagesDir, conventionName, cache, rootFallback) {
4448
+ let dir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
4449
+ while (dir.length >= pagesDir.length) {
4450
+ if (!cache.has(dir)) {
4451
+ cache.set(dir, await loadConventionComponent(dir, conventionName));
4452
+ }
4453
+ const found = cache.get(dir);
4454
+ if (found) {
4455
+ return found.component;
4456
+ }
4457
+ if (dir === pagesDir) {
4458
+ break;
4459
+ }
4460
+ dir = dir.slice(0, dir.lastIndexOf("/"));
4461
+ }
4462
+ return rootFallback;
4463
+ }
4464
+ async function buildDevRoute(absolutePath, relativePath, root) {
4465
+ let page;
4466
+ let routeChain = [];
4467
+ try {
4468
+ const pageMod = await import(`${absolutePath}?furin-server&t=${Date.now()}`);
4469
+ if (isFurinPage(pageMod.default)) {
4470
+ page = pageMod.default;
4471
+ routeChain = collectRouteChainFromRoute(page._route);
4472
+ validateRouteChain(routeChain, root.route, relativePath);
4473
+ }
4474
+ } catch {}
4475
+ const devStubPage = {
4476
+ __type: "FURIN_PAGE",
4477
+ _route: { __type: "FURIN_ROUTE" },
4478
+ component: () => null
4479
+ };
4480
+ return {
4481
+ pattern: filePathToPattern(relativePath),
4482
+ path: absolutePath,
4483
+ mode: page ? resolveMode(page, routeChain) : "ssr",
4484
+ page: page ?? devStubPage,
4485
+ routeChain,
4486
+ segmentBoundaries: []
4487
+ };
4488
+ }
4489
+ var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
4490
+ async function collectPageFilePaths(dir) {
4491
+ const files = [];
4492
+ const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
4493
+ for (const entry of entries) {
4494
+ const absolutePath = join9(dir, entry.name);
4495
+ if (entry.isDirectory()) {
4496
+ files.push(...await collectPageFilePaths(absolutePath));
4497
+ continue;
4498
+ }
4499
+ if (entry.isFile()) {
4500
+ files.push(absolutePath);
4501
+ }
4502
+ }
4503
+ return files;
4504
+ }
4505
+ function resolveMode(page, routeChain) {
4506
+ const routeConfig = page._route;
4507
+ const mode = routeConfig.mode ?? page.mode;
4508
+ const revalidate = routeConfig.revalidate ?? page.revalidate;
4509
+ if (mode) {
4510
+ return mode;
4511
+ }
4512
+ const hasLoader = routeChain.some((r) => r.loader) || !!page.loader;
4513
+ if (!hasLoader) {
4514
+ return "ssg";
4515
+ }
4516
+ if (typeof revalidate === "number" && revalidate >= 0) {
4517
+ return "isr";
4518
+ }
4519
+ return "ssr";
4520
+ }
4521
+ function filePathToPattern(path) {
4522
+ const parts = path.replaceAll("\\", "/").split("/");
4523
+ const segments = [];
4524
+ for (const part of parts) {
4525
+ const name = parse(part).name;
4526
+ if (name === "index") {
4527
+ continue;
4528
+ }
4529
+ if (name.startsWith("[") && name.endsWith("]")) {
4530
+ const inner = name.slice(1, -1);
4531
+ if (inner.startsWith("...")) {
4532
+ segments.push("*");
4533
+ continue;
4534
+ }
4535
+ segments.push(`:${inner}`);
4536
+ continue;
4537
+ }
4538
+ segments.push(name);
4539
+ }
4540
+ return `/${segments.join("/")}`;
4541
+ }
4542
+
4543
+ // src/build/scan-server.ts
4544
+ import { readFileSync as readFileSync4 } from "fs";
4545
+ import { parseSync as parseSync2 } from "oxc-parser";
4546
+ function scanFurinInstances(serverEntryPath) {
4547
+ const code = readFileSync4(serverEntryPath, "utf8");
4548
+ const { program, errors } = parseSync2(serverEntryPath, code);
4549
+ if (errors.length > 0) {
4550
+ return [];
4551
+ }
4552
+ const results = [];
4553
+ walkNode(program, results);
4554
+ return results;
4555
+ }
4556
+ var SKIP_KEYS = new Set(["type", "start", "end"]);
4557
+ function checkFurinCall(node, out) {
4558
+ const callee = node.callee;
4559
+ const args = node.arguments;
4560
+ const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
4561
+ if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
4562
+ return;
4563
+ }
4564
+ const firstArg = args[0];
4565
+ if (firstArg?.type !== "ObjectExpression") {
4566
+ return;
4567
+ }
4568
+ const pagesDir = extractStringProperty(firstArg, "pagesDir");
4569
+ if (pagesDir !== null) {
4570
+ out.push(pagesDir);
4571
+ }
4572
+ }
4573
+ function walkChildren(node, out) {
4574
+ for (const key of Object.keys(node)) {
4575
+ if (SKIP_KEYS.has(key)) {
4576
+ continue;
4577
+ }
4578
+ const child = node[key];
4579
+ if (Array.isArray(child)) {
4580
+ for (const item of child) {
4581
+ if (item && typeof item === "object") {
4582
+ walkNode(item, out);
4583
+ }
4584
+ }
4585
+ } else if (child && typeof child === "object") {
4586
+ walkNode(child, out);
4587
+ }
4588
+ }
4589
+ }
4590
+ function walkNode(node, out) {
4591
+ if (!node || typeof node !== "object") {
4592
+ return;
4593
+ }
4594
+ if (node.type === "CallExpression") {
4595
+ checkFurinCall(node, out);
4596
+ }
4597
+ walkChildren(node, out);
4598
+ }
4599
+ function extractStringProperty(obj, propName) {
4600
+ const properties = obj.properties;
4601
+ if (!Array.isArray(properties)) {
4602
+ return null;
4603
+ }
4604
+ for (const prop of properties) {
4605
+ if (prop.type !== "Property") {
4606
+ continue;
4607
+ }
4608
+ const key = prop.key;
4609
+ const value = prop.value;
4610
+ const keyMatches = key.type === "Identifier" && key.name === propName || key.type === "Literal" && key.value === propName;
4611
+ if (!keyMatches) {
4612
+ continue;
4613
+ }
4614
+ if (value?.type === "Literal" && typeof value.value === "string") {
4615
+ return value.value;
4616
+ }
4617
+ return null;
4618
+ }
4619
+ return null;
4620
+ }
4621
+
4622
+ // src/build/index.ts
4623
+ var IMPLEMENTED_TARGETS = ["bun", "static"];
4624
+ var BUILD_OUTPUT_DIR = ".furin/build";
4625
+ function resolvePagesDirFromServer(serverEntry, rootDir) {
4626
+ if (!serverEntry) {
4627
+ return null;
4628
+ }
4629
+ const detected = scanFurinInstances(serverEntry);
4630
+ if (detected.length === 0) {
4631
+ return null;
4632
+ }
4633
+ return resolve3(rootDir, detected[0]);
4634
+ }
4635
+ async function buildApp(options) {
4636
+ const rootDir = resolve3(options.rootDir ?? process.cwd());
4637
+ const buildRoot = join10(rootDir, BUILD_OUTPUT_DIR);
4638
+ const serverEntry = (() => {
4639
+ if (options.target === "static") {
4640
+ return null;
4641
+ }
4642
+ if (options.serverEntry) {
4643
+ const resolved = resolve3(rootDir, options.serverEntry);
4644
+ if (existsSync9(resolved)) {
4645
+ return resolved;
4646
+ }
4647
+ }
4648
+ const entry = resolve3(rootDir, "src/server.ts");
4649
+ if (!existsSync9(entry)) {
4650
+ throw new Error("[furin] Entrypoint server.ts not found");
4651
+ }
4652
+ return entry;
4653
+ })();
4654
+ for (const plugin of options.plugins ?? []) {
4655
+ const { buildOnly, ...runtimePlugin } = plugin;
4656
+ if (buildOnly) {
4657
+ continue;
4658
+ }
4659
+ try {
4660
+ Bun.plugin(runtimePlugin);
4661
+ } catch (err) {
4662
+ console.debug("[furin] Skipped plugin at runtime:", err);
4663
+ }
4664
+ }
4665
+ const rawPagesDir = options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
4666
+ const pagesDir = resolve3(rootDir, rawPagesDir);
4667
+ const requestedTargets = options.target === "all" ? [...IMPLEMENTED_TARGETS] : [options.target].map((target) => {
4668
+ if (!BUILD_TARGETS.includes(target)) {
4669
+ throw new Error(`[furin] Unsupported build target "${target}"`);
4670
+ }
4671
+ return target;
4672
+ });
4673
+ const { root, routes } = await scanPages(pagesDir);
4674
+ ensureDir(buildRoot);
4675
+ const manifest = {
4676
+ version: 1,
4677
+ generatedAt: new Date().toISOString(),
4678
+ rootDir: toPosixPath(rootDir),
4679
+ pagesDir: toPosixPath(relative4(rootDir, pagesDir)),
4680
+ rootPath: toPosixPath(relative4(rootDir, root.path)),
4681
+ serverEntry: serverEntry ? toPosixPath(relative4(rootDir, serverEntry)) : null,
4682
+ routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
4683
+ targets: {}
4684
+ };
4685
+ for (const target of requestedTargets) {
4686
+ switch (target) {
4687
+ case "bun":
4688
+ manifest.targets.bun = await buildBunTarget(routes, rootDir, buildRoot, root, serverEntry, options);
4689
+ break;
4690
+ case "static":
4691
+ manifest.targets.static = await buildStaticTarget(routes, rootDir, buildRoot, root, options);
4692
+ break;
4693
+ case "node":
4694
+ case "vercel":
4695
+ case "cloudflare":
4696
+ throw new Error(`[furin] \`--target ${target}\` is planned but not implemented yet in this branch.`);
4697
+ default:
4698
+ throw new Error(`[furin] Unsupported build target "${target}"`);
4699
+ }
4700
+ }
4701
+ writeFileSync8(join10(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
4702
+ `);
4703
+ return {
4704
+ manifest,
4705
+ targets: manifest.targets
4706
+ };
4707
+ }
4708
+ export {
4709
+ writeRouteTypes,
4710
+ writeDevFiles,
4711
+ schemaToTypeString,
4712
+ patternToTypeString,
4713
+ buildClient,
4714
+ buildApp,
4715
+ BUILD_OUTPUT_DIR
4716
+ };