@teyik0/furin 0.1.0-alpha.9 → 0.2.0-alpha.2

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 (130) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/package.json +61 -25
  4. package/src/adapter/bun.ts +90 -41
  5. package/src/adapter/static.ts +100 -40
  6. package/src/build/client.ts +13 -14
  7. package/src/build/compile-entry.ts +20 -14
  8. package/src/build/entry-template.ts +90 -8
  9. package/src/build/hydrate.ts +219 -36
  10. package/src/build/index.ts +10 -9
  11. package/src/build/route-types.ts +65 -9
  12. package/src/build/scan-server.ts +52 -67
  13. package/src/build/server-routes-entry.ts +7 -11
  14. package/src/build/shared.ts +2 -1
  15. package/src/build/ssg-cache.ts +32 -0
  16. package/src/build/types.ts +5 -1
  17. package/src/cli/index.ts +1 -0
  18. package/src/client/boundaries.tsx +259 -0
  19. package/src/client/default-screens.tsx +304 -0
  20. package/src/client/link.tsx +347 -0
  21. package/src/client/router/boundary-tree.tsx +116 -0
  22. package/src/client/router/context.ts +40 -0
  23. package/src/client/router/history.ts +41 -0
  24. package/src/client/router/index.ts +56 -0
  25. package/src/client/router/link-utils.ts +177 -0
  26. package/src/client/router/navigation.ts +61 -0
  27. package/src/client/router/provider.tsx +759 -0
  28. package/src/client/router/search/index.ts +99 -0
  29. package/src/client/router/search-store.ts +86 -0
  30. package/src/client/router/spa-response.ts +143 -0
  31. package/src/client/router/types.ts +271 -0
  32. package/src/client/server-error.ts +47 -0
  33. package/src/client.ts +80 -3
  34. package/src/config.ts +11 -3
  35. package/src/env.d.ts +1 -0
  36. package/src/furin.ts +114 -29
  37. package/src/plugin/index.ts +7 -8
  38. package/src/plugin/transform-client.ts +146 -120
  39. package/src/server/auto-invalidate/index.ts +10 -0
  40. package/src/server/auto-invalidate/plugin.ts +25 -0
  41. package/src/server/auto-invalidate/registry.ts +60 -0
  42. package/src/server/auto-invalidate/runtime.ts +133 -0
  43. package/src/server/auto-invalidate/types.ts +16 -0
  44. package/src/server/cache/dev-loader.ts +211 -0
  45. package/src/server/cache/index.ts +34 -0
  46. package/src/server/cache/invalidation.ts +111 -0
  47. package/src/server/cache/isr-ssg.ts +41 -0
  48. package/src/server/cache/isr.ts +17 -0
  49. package/src/server/cache/registry.ts +35 -0
  50. package/src/server/cache/route-cache.ts +124 -0
  51. package/src/server/cache/ssg.ts +15 -0
  52. package/src/{context-logger.ts → server/context-logger.ts} +5 -0
  53. package/src/server/dev-inspector.ts +60 -0
  54. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  55. package/src/{internal.ts → server/internal.ts} +17 -0
  56. package/src/server/lang-detect.ts +46 -0
  57. package/src/server/render/assemble.ts +133 -0
  58. package/src/server/render/element.tsx +113 -0
  59. package/src/server/render/index.ts +22 -0
  60. package/src/server/render/isr.ts +317 -0
  61. package/src/server/render/loaders.ts +328 -0
  62. package/src/server/render/not-found.ts +98 -0
  63. package/src/{render → server/render}/shell.ts +28 -13
  64. package/src/server/render/ssg.ts +148 -0
  65. package/src/server/render/ssr.ts +583 -0
  66. package/src/server/router/discovery.ts +474 -0
  67. package/src/server/router/hmr.ts +376 -0
  68. package/src/server/router/index.ts +28 -0
  69. package/src/server/router/patterns.ts +219 -0
  70. package/src/server/router/plugin.ts +384 -0
  71. package/src/server/router/schemas.ts +278 -0
  72. package/src/server/router/types.ts +59 -0
  73. package/src/shared/await.tsx +192 -0
  74. package/src/shared/deferred-ndjson.ts +244 -0
  75. package/src/shared/digest.ts +71 -0
  76. package/src/shared/error.ts +49 -0
  77. package/src/shared/not-found.ts +40 -0
  78. package/src/shared/search-params.ts +182 -0
  79. package/src/shared/utils/ast-walk.ts +51 -0
  80. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  81. package/dist/adapter/bun.d.ts +0 -3
  82. package/dist/adapter/static.d.ts +0 -3
  83. package/dist/build/client.d.ts +0 -25
  84. package/dist/build/compile-entry.d.ts +0 -23
  85. package/dist/build/entry-template.d.ts +0 -14
  86. package/dist/build/hydrate.d.ts +0 -24
  87. package/dist/build/index.d.ts +0 -7
  88. package/dist/build/index.js +0 -3727
  89. package/dist/build/route-types.d.ts +0 -21
  90. package/dist/build/scan-server.d.ts +0 -8
  91. package/dist/build/server-routes-entry.d.ts +0 -23
  92. package/dist/build/shared.d.ts +0 -11
  93. package/dist/build/types.d.ts +0 -76
  94. package/dist/cli/config.d.ts +0 -9
  95. package/dist/cli/index.d.ts +0 -2
  96. package/dist/cli/index.js +0 -3762
  97. package/dist/client.d.ts +0 -195
  98. package/dist/client.js +0 -20
  99. package/dist/config.d.ts +0 -47
  100. package/dist/config.js +0 -28
  101. package/dist/context-logger.d.ts +0 -26
  102. package/dist/dev-page-plugin.d.ts +0 -109
  103. package/dist/furin.d.ts +0 -34
  104. package/dist/furin.js +0 -2744
  105. package/dist/internal.d.ts +0 -19
  106. package/dist/link.d.ts +0 -245
  107. package/dist/link.js +0 -1232
  108. package/dist/plugin/index.d.ts +0 -20
  109. package/dist/plugin/index.js +0 -1408
  110. package/dist/plugin/transform-client.d.ts +0 -9
  111. package/dist/render/assemble.d.ts +0 -15
  112. package/dist/render/cache.d.ts +0 -95
  113. package/dist/render/element.d.ts +0 -4
  114. package/dist/render/index.d.ts +0 -27
  115. package/dist/render/loaders.d.ts +0 -12
  116. package/dist/render/shell.d.ts +0 -29
  117. package/dist/render/template.d.ts +0 -6
  118. package/dist/router.d.ts +0 -45
  119. package/dist/router.js +0 -1671
  120. package/dist/runtime-env.d.ts +0 -3
  121. package/dist/utils.d.ts +0 -6
  122. package/src/link.tsx +0 -1120
  123. package/src/render/assemble.ts +0 -66
  124. package/src/render/cache.ts +0 -241
  125. package/src/render/element.tsx +0 -28
  126. package/src/render/index.ts +0 -483
  127. package/src/render/loaders.ts +0 -117
  128. package/src/router.ts +0 -439
  129. /package/src/{render → server/render}/template.ts +0 -0
  130. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
package/dist/cli/index.js DELETED
@@ -1,3762 +0,0 @@
1
- #!/usr/bin/env bun
2
- // @bun
3
-
4
- // src/cli/index.ts
5
- import { existsSync as existsSync9 } from "fs";
6
- import { resolve as resolve5 } from "path";
7
- import { parseArgs } from "util";
8
-
9
- // src/build/index.ts
10
- import { existsSync as existsSync7, writeFileSync as writeFileSync6 } from "fs";
11
- import { join as join8, relative as relative4, resolve as resolve3 } from "path";
12
-
13
- // src/adapter/bun.ts
14
- import { existsSync as existsSync4, rmSync as rmSync2, writeFileSync as writeFileSync4 } from "fs";
15
- import { dirname as dirname2, join as join5, resolve } from "path";
16
- import { fileURLToPath } from "url";
17
-
18
- // src/build/client.ts
19
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync } from "fs";
20
- import { basename, join as join2 } from "path";
21
-
22
- // ../../node_modules/.bun/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
23
- var comma = 44;
24
- var semicolon = 59;
25
- var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
26
- var intToChar = new Uint8Array(64);
27
- var charToInt = new Uint8Array(128);
28
- for (let i = 0;i < chars.length; i++) {
29
- const c = chars.charCodeAt(i);
30
- intToChar[i] = c;
31
- charToInt[c] = i;
32
- }
33
- function encodeInteger(builder, num, relative) {
34
- let delta = num - relative;
35
- delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
36
- do {
37
- let clamped = delta & 31;
38
- delta >>>= 5;
39
- if (delta > 0)
40
- clamped |= 32;
41
- builder.write(intToChar[clamped]);
42
- } while (delta > 0);
43
- return num;
44
- }
45
- var bufLength = 1024 * 16;
46
- var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder : typeof Buffer !== "undefined" ? {
47
- decode(buf) {
48
- const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
49
- return out.toString();
50
- }
51
- } : {
52
- decode(buf) {
53
- let out = "";
54
- for (let i = 0;i < buf.length; i++) {
55
- out += String.fromCharCode(buf[i]);
56
- }
57
- return out;
58
- }
59
- };
60
- var StringWriter = class {
61
- constructor() {
62
- this.pos = 0;
63
- this.out = "";
64
- this.buffer = new Uint8Array(bufLength);
65
- }
66
- write(v) {
67
- const { buffer } = this;
68
- buffer[this.pos++] = v;
69
- if (this.pos === bufLength) {
70
- this.out += td.decode(buffer);
71
- this.pos = 0;
72
- }
73
- }
74
- flush() {
75
- const { buffer, out, pos } = this;
76
- return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
77
- }
78
- };
79
- function encode(decoded) {
80
- const writer = new StringWriter;
81
- let sourcesIndex = 0;
82
- let sourceLine = 0;
83
- let sourceColumn = 0;
84
- let namesIndex = 0;
85
- for (let i = 0;i < decoded.length; i++) {
86
- const line = decoded[i];
87
- if (i > 0)
88
- writer.write(semicolon);
89
- if (line.length === 0)
90
- continue;
91
- let genColumn = 0;
92
- for (let j = 0;j < line.length; j++) {
93
- const segment = line[j];
94
- if (j > 0)
95
- writer.write(comma);
96
- genColumn = encodeInteger(writer, segment[0], genColumn);
97
- if (segment.length === 1)
98
- continue;
99
- sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
100
- sourceLine = encodeInteger(writer, segment[2], sourceLine);
101
- sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
102
- if (segment.length === 4)
103
- continue;
104
- namesIndex = encodeInteger(writer, segment[4], namesIndex);
105
- }
106
- }
107
- return writer.flush();
108
- }
109
-
110
- // ../../node_modules/.bun/magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs
111
- class BitSet {
112
- constructor(arg) {
113
- this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
114
- }
115
- add(n) {
116
- this.bits[n >> 5] |= 1 << (n & 31);
117
- }
118
- has(n) {
119
- return !!(this.bits[n >> 5] & 1 << (n & 31));
120
- }
121
- }
122
-
123
- class Chunk {
124
- constructor(start, end, content) {
125
- this.start = start;
126
- this.end = end;
127
- this.original = content;
128
- this.intro = "";
129
- this.outro = "";
130
- this.content = content;
131
- this.storeName = false;
132
- this.edited = false;
133
- {
134
- this.previous = null;
135
- this.next = null;
136
- }
137
- }
138
- appendLeft(content) {
139
- this.outro += content;
140
- }
141
- appendRight(content) {
142
- this.intro = this.intro + content;
143
- }
144
- clone() {
145
- const chunk = new Chunk(this.start, this.end, this.original);
146
- chunk.intro = this.intro;
147
- chunk.outro = this.outro;
148
- chunk.content = this.content;
149
- chunk.storeName = this.storeName;
150
- chunk.edited = this.edited;
151
- return chunk;
152
- }
153
- contains(index) {
154
- return this.start < index && index < this.end;
155
- }
156
- eachNext(fn) {
157
- let chunk = this;
158
- while (chunk) {
159
- fn(chunk);
160
- chunk = chunk.next;
161
- }
162
- }
163
- eachPrevious(fn) {
164
- let chunk = this;
165
- while (chunk) {
166
- fn(chunk);
167
- chunk = chunk.previous;
168
- }
169
- }
170
- edit(content, storeName, contentOnly) {
171
- this.content = content;
172
- if (!contentOnly) {
173
- this.intro = "";
174
- this.outro = "";
175
- }
176
- this.storeName = storeName;
177
- this.edited = true;
178
- return this;
179
- }
180
- prependLeft(content) {
181
- this.outro = content + this.outro;
182
- }
183
- prependRight(content) {
184
- this.intro = content + this.intro;
185
- }
186
- reset() {
187
- this.intro = "";
188
- this.outro = "";
189
- if (this.edited) {
190
- this.content = this.original;
191
- this.storeName = false;
192
- this.edited = false;
193
- }
194
- }
195
- split(index) {
196
- const sliceIndex = index - this.start;
197
- const originalBefore = this.original.slice(0, sliceIndex);
198
- const originalAfter = this.original.slice(sliceIndex);
199
- this.original = originalBefore;
200
- const newChunk = new Chunk(index, this.end, originalAfter);
201
- newChunk.outro = this.outro;
202
- this.outro = "";
203
- this.end = index;
204
- if (this.edited) {
205
- newChunk.edit("", false);
206
- this.content = "";
207
- } else {
208
- this.content = originalBefore;
209
- }
210
- newChunk.next = this.next;
211
- if (newChunk.next)
212
- newChunk.next.previous = newChunk;
213
- newChunk.previous = this;
214
- this.next = newChunk;
215
- return newChunk;
216
- }
217
- toString() {
218
- return this.intro + this.content + this.outro;
219
- }
220
- trimEnd(rx) {
221
- this.outro = this.outro.replace(rx, "");
222
- if (this.outro.length)
223
- return true;
224
- const trimmed = this.content.replace(rx, "");
225
- if (trimmed.length) {
226
- if (trimmed !== this.content) {
227
- this.split(this.start + trimmed.length).edit("", undefined, true);
228
- if (this.edited) {
229
- this.edit(trimmed, this.storeName, true);
230
- }
231
- }
232
- return true;
233
- } else {
234
- this.edit("", undefined, true);
235
- this.intro = this.intro.replace(rx, "");
236
- if (this.intro.length)
237
- return true;
238
- }
239
- }
240
- trimStart(rx) {
241
- this.intro = this.intro.replace(rx, "");
242
- if (this.intro.length)
243
- return true;
244
- const trimmed = this.content.replace(rx, "");
245
- if (trimmed.length) {
246
- if (trimmed !== this.content) {
247
- const newChunk = this.split(this.end - trimmed.length);
248
- if (this.edited) {
249
- newChunk.edit(trimmed, this.storeName, true);
250
- }
251
- this.edit("", undefined, true);
252
- }
253
- return true;
254
- } else {
255
- this.edit("", undefined, true);
256
- this.outro = this.outro.replace(rx, "");
257
- if (this.outro.length)
258
- return true;
259
- }
260
- }
261
- }
262
- function getBtoa() {
263
- if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
264
- return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
265
- } else if (typeof Buffer === "function") {
266
- return (str) => Buffer.from(str, "utf-8").toString("base64");
267
- } else {
268
- return () => {
269
- throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
270
- };
271
- }
272
- }
273
- var btoa = /* @__PURE__ */ getBtoa();
274
-
275
- class SourceMap {
276
- constructor(properties) {
277
- this.version = 3;
278
- this.file = properties.file;
279
- this.sources = properties.sources;
280
- this.sourcesContent = properties.sourcesContent;
281
- this.names = properties.names;
282
- this.mappings = encode(properties.mappings);
283
- if (typeof properties.x_google_ignoreList !== "undefined") {
284
- this.x_google_ignoreList = properties.x_google_ignoreList;
285
- }
286
- if (typeof properties.debugId !== "undefined") {
287
- this.debugId = properties.debugId;
288
- }
289
- }
290
- toString() {
291
- return JSON.stringify(this);
292
- }
293
- toUrl() {
294
- return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
295
- }
296
- }
297
- function guessIndent(code) {
298
- const lines = code.split(`
299
- `);
300
- const tabbed = lines.filter((line) => /^\t+/.test(line));
301
- const spaced = lines.filter((line) => /^ {2,}/.test(line));
302
- if (tabbed.length === 0 && spaced.length === 0) {
303
- return null;
304
- }
305
- if (tabbed.length >= spaced.length) {
306
- return "\t";
307
- }
308
- const min = spaced.reduce((previous, current) => {
309
- const numSpaces = /^ +/.exec(current)[0].length;
310
- return Math.min(numSpaces, previous);
311
- }, Infinity);
312
- return new Array(min + 1).join(" ");
313
- }
314
- function getRelativePath(from, to) {
315
- const fromParts = from.split(/[/\\]/);
316
- const toParts = to.split(/[/\\]/);
317
- fromParts.pop();
318
- while (fromParts[0] === toParts[0]) {
319
- fromParts.shift();
320
- toParts.shift();
321
- }
322
- if (fromParts.length) {
323
- let i = fromParts.length;
324
- while (i--)
325
- fromParts[i] = "..";
326
- }
327
- return fromParts.concat(toParts).join("/");
328
- }
329
- var toString = Object.prototype.toString;
330
- function isObject(thing) {
331
- return toString.call(thing) === "[object Object]";
332
- }
333
- function getLocator(source) {
334
- const originalLines = source.split(`
335
- `);
336
- const lineOffsets = [];
337
- for (let i = 0, pos = 0;i < originalLines.length; i++) {
338
- lineOffsets.push(pos);
339
- pos += originalLines[i].length + 1;
340
- }
341
- return function locate(index) {
342
- let i = 0;
343
- let j = lineOffsets.length;
344
- while (i < j) {
345
- const m = i + j >> 1;
346
- if (index < lineOffsets[m]) {
347
- j = m;
348
- } else {
349
- i = m + 1;
350
- }
351
- }
352
- const line = i - 1;
353
- const column = index - lineOffsets[line];
354
- return { line, column };
355
- };
356
- }
357
- var wordRegex = /\w/;
358
-
359
- class Mappings {
360
- constructor(hires) {
361
- this.hires = hires;
362
- this.generatedCodeLine = 0;
363
- this.generatedCodeColumn = 0;
364
- this.raw = [];
365
- this.rawSegments = this.raw[this.generatedCodeLine] = [];
366
- this.pending = null;
367
- }
368
- addEdit(sourceIndex, content, loc, nameIndex) {
369
- if (content.length) {
370
- const contentLengthMinusOne = content.length - 1;
371
- let contentLineEnd = content.indexOf(`
372
- `, 0);
373
- let previousContentLineEnd = -1;
374
- while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
375
- const segment2 = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
376
- if (nameIndex >= 0) {
377
- segment2.push(nameIndex);
378
- }
379
- this.rawSegments.push(segment2);
380
- this.generatedCodeLine += 1;
381
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
382
- this.generatedCodeColumn = 0;
383
- previousContentLineEnd = contentLineEnd;
384
- contentLineEnd = content.indexOf(`
385
- `, contentLineEnd + 1);
386
- }
387
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
388
- if (nameIndex >= 0) {
389
- segment.push(nameIndex);
390
- }
391
- this.rawSegments.push(segment);
392
- this.advance(content.slice(previousContentLineEnd + 1));
393
- } else if (this.pending) {
394
- this.rawSegments.push(this.pending);
395
- this.advance(content);
396
- }
397
- this.pending = null;
398
- }
399
- addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
400
- let originalCharIndex = chunk.start;
401
- let first = true;
402
- let charInHiresBoundary = false;
403
- while (originalCharIndex < chunk.end) {
404
- if (original[originalCharIndex] === `
405
- `) {
406
- loc.line += 1;
407
- loc.column = 0;
408
- this.generatedCodeLine += 1;
409
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
410
- this.generatedCodeColumn = 0;
411
- first = true;
412
- charInHiresBoundary = false;
413
- } else {
414
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
415
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
416
- if (this.hires === "boundary") {
417
- if (wordRegex.test(original[originalCharIndex])) {
418
- if (!charInHiresBoundary) {
419
- this.rawSegments.push(segment);
420
- charInHiresBoundary = true;
421
- }
422
- } else {
423
- this.rawSegments.push(segment);
424
- charInHiresBoundary = false;
425
- }
426
- } else {
427
- this.rawSegments.push(segment);
428
- }
429
- }
430
- loc.column += 1;
431
- this.generatedCodeColumn += 1;
432
- first = false;
433
- }
434
- originalCharIndex += 1;
435
- }
436
- this.pending = null;
437
- }
438
- advance(str) {
439
- if (!str)
440
- return;
441
- const lines = str.split(`
442
- `);
443
- if (lines.length > 1) {
444
- for (let i = 0;i < lines.length - 1; i++) {
445
- this.generatedCodeLine++;
446
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
447
- }
448
- this.generatedCodeColumn = 0;
449
- }
450
- this.generatedCodeColumn += lines[lines.length - 1].length;
451
- }
452
- }
453
- var n = `
454
- `;
455
- var warned = {
456
- insertLeft: false,
457
- insertRight: false,
458
- storeName: false
459
- };
460
-
461
- class MagicString {
462
- constructor(string, options = {}) {
463
- const chunk = new Chunk(0, string.length, string);
464
- Object.defineProperties(this, {
465
- original: { writable: true, value: string },
466
- outro: { writable: true, value: "" },
467
- intro: { writable: true, value: "" },
468
- firstChunk: { writable: true, value: chunk },
469
- lastChunk: { writable: true, value: chunk },
470
- lastSearchedChunk: { writable: true, value: chunk },
471
- byStart: { writable: true, value: {} },
472
- byEnd: { writable: true, value: {} },
473
- filename: { writable: true, value: options.filename },
474
- indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
475
- sourcemapLocations: { writable: true, value: new BitSet },
476
- storedNames: { writable: true, value: {} },
477
- indentStr: { writable: true, value: undefined },
478
- ignoreList: { writable: true, value: options.ignoreList },
479
- offset: { writable: true, value: options.offset || 0 }
480
- });
481
- this.byStart[0] = chunk;
482
- this.byEnd[string.length] = chunk;
483
- }
484
- addSourcemapLocation(char) {
485
- this.sourcemapLocations.add(char);
486
- }
487
- append(content) {
488
- if (typeof content !== "string")
489
- throw new TypeError("outro content must be a string");
490
- this.outro += content;
491
- return this;
492
- }
493
- appendLeft(index, content) {
494
- index = index + this.offset;
495
- if (typeof content !== "string")
496
- throw new TypeError("inserted content must be a string");
497
- this._split(index);
498
- const chunk = this.byEnd[index];
499
- if (chunk) {
500
- chunk.appendLeft(content);
501
- } else {
502
- this.intro += content;
503
- }
504
- return this;
505
- }
506
- appendRight(index, content) {
507
- index = index + this.offset;
508
- if (typeof content !== "string")
509
- throw new TypeError("inserted content must be a string");
510
- this._split(index);
511
- const chunk = this.byStart[index];
512
- if (chunk) {
513
- chunk.appendRight(content);
514
- } else {
515
- this.outro += content;
516
- }
517
- return this;
518
- }
519
- clone() {
520
- const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
521
- let originalChunk = this.firstChunk;
522
- let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
523
- while (originalChunk) {
524
- cloned.byStart[clonedChunk.start] = clonedChunk;
525
- cloned.byEnd[clonedChunk.end] = clonedChunk;
526
- const nextOriginalChunk = originalChunk.next;
527
- const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
528
- if (nextClonedChunk) {
529
- clonedChunk.next = nextClonedChunk;
530
- nextClonedChunk.previous = clonedChunk;
531
- clonedChunk = nextClonedChunk;
532
- }
533
- originalChunk = nextOriginalChunk;
534
- }
535
- cloned.lastChunk = clonedChunk;
536
- if (this.indentExclusionRanges) {
537
- cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
538
- }
539
- cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
540
- cloned.intro = this.intro;
541
- cloned.outro = this.outro;
542
- return cloned;
543
- }
544
- generateDecodedMap(options) {
545
- options = options || {};
546
- const sourceIndex = 0;
547
- const names = Object.keys(this.storedNames);
548
- const mappings = new Mappings(options.hires);
549
- const locate = getLocator(this.original);
550
- if (this.intro) {
551
- mappings.advance(this.intro);
552
- }
553
- this.firstChunk.eachNext((chunk) => {
554
- const loc = locate(chunk.start);
555
- if (chunk.intro.length)
556
- mappings.advance(chunk.intro);
557
- if (chunk.edited) {
558
- mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
559
- } else {
560
- mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
561
- }
562
- if (chunk.outro.length)
563
- mappings.advance(chunk.outro);
564
- });
565
- if (this.outro) {
566
- mappings.advance(this.outro);
567
- }
568
- return {
569
- file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
570
- sources: [
571
- options.source ? getRelativePath(options.file || "", options.source) : options.file || ""
572
- ],
573
- sourcesContent: options.includeContent ? [this.original] : undefined,
574
- names,
575
- mappings: mappings.raw,
576
- x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined
577
- };
578
- }
579
- generateMap(options) {
580
- return new SourceMap(this.generateDecodedMap(options));
581
- }
582
- _ensureindentStr() {
583
- if (this.indentStr === undefined) {
584
- this.indentStr = guessIndent(this.original);
585
- }
586
- }
587
- _getRawIndentString() {
588
- this._ensureindentStr();
589
- return this.indentStr;
590
- }
591
- getIndentString() {
592
- this._ensureindentStr();
593
- return this.indentStr === null ? "\t" : this.indentStr;
594
- }
595
- indent(indentStr, options) {
596
- const pattern = /^[^\r\n]/gm;
597
- if (isObject(indentStr)) {
598
- options = indentStr;
599
- indentStr = undefined;
600
- }
601
- if (indentStr === undefined) {
602
- this._ensureindentStr();
603
- indentStr = this.indentStr || "\t";
604
- }
605
- if (indentStr === "")
606
- return this;
607
- options = options || {};
608
- const isExcluded = {};
609
- if (options.exclude) {
610
- const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
611
- exclusions.forEach((exclusion) => {
612
- for (let i = exclusion[0];i < exclusion[1]; i += 1) {
613
- isExcluded[i] = true;
614
- }
615
- });
616
- }
617
- let shouldIndentNextCharacter = options.indentStart !== false;
618
- const replacer = (match) => {
619
- if (shouldIndentNextCharacter)
620
- return `${indentStr}${match}`;
621
- shouldIndentNextCharacter = true;
622
- return match;
623
- };
624
- this.intro = this.intro.replace(pattern, replacer);
625
- let charIndex = 0;
626
- let chunk = this.firstChunk;
627
- while (chunk) {
628
- const end = chunk.end;
629
- if (chunk.edited) {
630
- if (!isExcluded[charIndex]) {
631
- chunk.content = chunk.content.replace(pattern, replacer);
632
- if (chunk.content.length) {
633
- shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === `
634
- `;
635
- }
636
- }
637
- } else {
638
- charIndex = chunk.start;
639
- while (charIndex < end) {
640
- if (!isExcluded[charIndex]) {
641
- const char = this.original[charIndex];
642
- if (char === `
643
- `) {
644
- shouldIndentNextCharacter = true;
645
- } else if (char !== "\r" && shouldIndentNextCharacter) {
646
- shouldIndentNextCharacter = false;
647
- if (charIndex === chunk.start) {
648
- chunk.prependRight(indentStr);
649
- } else {
650
- this._splitChunk(chunk, charIndex);
651
- chunk = chunk.next;
652
- chunk.prependRight(indentStr);
653
- }
654
- }
655
- }
656
- charIndex += 1;
657
- }
658
- }
659
- charIndex = chunk.end;
660
- chunk = chunk.next;
661
- }
662
- this.outro = this.outro.replace(pattern, replacer);
663
- return this;
664
- }
665
- insert() {
666
- throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)");
667
- }
668
- insertLeft(index, content) {
669
- if (!warned.insertLeft) {
670
- console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");
671
- warned.insertLeft = true;
672
- }
673
- return this.appendLeft(index, content);
674
- }
675
- insertRight(index, content) {
676
- if (!warned.insertRight) {
677
- console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");
678
- warned.insertRight = true;
679
- }
680
- return this.prependRight(index, content);
681
- }
682
- move(start, end, index) {
683
- start = start + this.offset;
684
- end = end + this.offset;
685
- index = index + this.offset;
686
- if (index >= start && index <= end)
687
- throw new Error("Cannot move a selection inside itself");
688
- this._split(start);
689
- this._split(end);
690
- this._split(index);
691
- const first = this.byStart[start];
692
- const last = this.byEnd[end];
693
- const oldLeft = first.previous;
694
- const oldRight = last.next;
695
- const newRight = this.byStart[index];
696
- if (!newRight && last === this.lastChunk)
697
- return this;
698
- const newLeft = newRight ? newRight.previous : this.lastChunk;
699
- if (oldLeft)
700
- oldLeft.next = oldRight;
701
- if (oldRight)
702
- oldRight.previous = oldLeft;
703
- if (newLeft)
704
- newLeft.next = first;
705
- if (newRight)
706
- newRight.previous = last;
707
- if (!first.previous)
708
- this.firstChunk = last.next;
709
- if (!last.next) {
710
- this.lastChunk = first.previous;
711
- this.lastChunk.next = null;
712
- }
713
- first.previous = newLeft;
714
- last.next = newRight || null;
715
- if (!newLeft)
716
- this.firstChunk = first;
717
- if (!newRight)
718
- this.lastChunk = last;
719
- return this;
720
- }
721
- overwrite(start, end, content, options) {
722
- options = options || {};
723
- return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
724
- }
725
- update(start, end, content, options) {
726
- start = start + this.offset;
727
- end = end + this.offset;
728
- if (typeof content !== "string")
729
- throw new TypeError("replacement content must be a string");
730
- if (this.original.length !== 0) {
731
- while (start < 0)
732
- start += this.original.length;
733
- while (end < 0)
734
- end += this.original.length;
735
- }
736
- if (end > this.original.length)
737
- throw new Error("end is out of bounds");
738
- if (start === end)
739
- throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");
740
- this._split(start);
741
- this._split(end);
742
- if (options === true) {
743
- if (!warned.storeName) {
744
- console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");
745
- warned.storeName = true;
746
- }
747
- options = { storeName: true };
748
- }
749
- const storeName = options !== undefined ? options.storeName : false;
750
- const overwrite = options !== undefined ? options.overwrite : false;
751
- if (storeName) {
752
- const original = this.original.slice(start, end);
753
- Object.defineProperty(this.storedNames, original, {
754
- writable: true,
755
- value: true,
756
- enumerable: true
757
- });
758
- }
759
- const first = this.byStart[start];
760
- const last = this.byEnd[end];
761
- if (first) {
762
- let chunk = first;
763
- while (chunk !== last) {
764
- if (chunk.next !== this.byStart[chunk.end]) {
765
- throw new Error("Cannot overwrite across a split point");
766
- }
767
- chunk = chunk.next;
768
- chunk.edit("", false);
769
- }
770
- first.edit(content, storeName, !overwrite);
771
- } else {
772
- const newChunk = new Chunk(start, end, "").edit(content, storeName);
773
- last.next = newChunk;
774
- newChunk.previous = last;
775
- }
776
- return this;
777
- }
778
- prepend(content) {
779
- if (typeof content !== "string")
780
- throw new TypeError("outro content must be a string");
781
- this.intro = content + this.intro;
782
- return this;
783
- }
784
- prependLeft(index, content) {
785
- index = index + this.offset;
786
- if (typeof content !== "string")
787
- throw new TypeError("inserted content must be a string");
788
- this._split(index);
789
- const chunk = this.byEnd[index];
790
- if (chunk) {
791
- chunk.prependLeft(content);
792
- } else {
793
- this.intro = content + this.intro;
794
- }
795
- return this;
796
- }
797
- prependRight(index, content) {
798
- index = index + this.offset;
799
- if (typeof content !== "string")
800
- throw new TypeError("inserted content must be a string");
801
- this._split(index);
802
- const chunk = this.byStart[index];
803
- if (chunk) {
804
- chunk.prependRight(content);
805
- } else {
806
- this.outro = content + this.outro;
807
- }
808
- return this;
809
- }
810
- remove(start, end) {
811
- start = start + this.offset;
812
- end = end + this.offset;
813
- if (this.original.length !== 0) {
814
- while (start < 0)
815
- start += this.original.length;
816
- while (end < 0)
817
- end += this.original.length;
818
- }
819
- if (start === end)
820
- return this;
821
- if (start < 0 || end > this.original.length)
822
- throw new Error("Character is out of bounds");
823
- if (start > end)
824
- throw new Error("end must be greater than start");
825
- this._split(start);
826
- this._split(end);
827
- let chunk = this.byStart[start];
828
- while (chunk) {
829
- chunk.intro = "";
830
- chunk.outro = "";
831
- chunk.edit("");
832
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
833
- }
834
- return this;
835
- }
836
- reset(start, end) {
837
- start = start + this.offset;
838
- end = end + this.offset;
839
- if (this.original.length !== 0) {
840
- while (start < 0)
841
- start += this.original.length;
842
- while (end < 0)
843
- end += this.original.length;
844
- }
845
- if (start === end)
846
- return this;
847
- if (start < 0 || end > this.original.length)
848
- throw new Error("Character is out of bounds");
849
- if (start > end)
850
- throw new Error("end must be greater than start");
851
- this._split(start);
852
- this._split(end);
853
- let chunk = this.byStart[start];
854
- while (chunk) {
855
- chunk.reset();
856
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
857
- }
858
- return this;
859
- }
860
- lastChar() {
861
- if (this.outro.length)
862
- return this.outro[this.outro.length - 1];
863
- let chunk = this.lastChunk;
864
- do {
865
- if (chunk.outro.length)
866
- return chunk.outro[chunk.outro.length - 1];
867
- if (chunk.content.length)
868
- return chunk.content[chunk.content.length - 1];
869
- if (chunk.intro.length)
870
- return chunk.intro[chunk.intro.length - 1];
871
- } while (chunk = chunk.previous);
872
- if (this.intro.length)
873
- return this.intro[this.intro.length - 1];
874
- return "";
875
- }
876
- lastLine() {
877
- let lineIndex = this.outro.lastIndexOf(n);
878
- if (lineIndex !== -1)
879
- return this.outro.substr(lineIndex + 1);
880
- let lineStr = this.outro;
881
- let chunk = this.lastChunk;
882
- do {
883
- if (chunk.outro.length > 0) {
884
- lineIndex = chunk.outro.lastIndexOf(n);
885
- if (lineIndex !== -1)
886
- return chunk.outro.substr(lineIndex + 1) + lineStr;
887
- lineStr = chunk.outro + lineStr;
888
- }
889
- if (chunk.content.length > 0) {
890
- lineIndex = chunk.content.lastIndexOf(n);
891
- if (lineIndex !== -1)
892
- return chunk.content.substr(lineIndex + 1) + lineStr;
893
- lineStr = chunk.content + lineStr;
894
- }
895
- if (chunk.intro.length > 0) {
896
- lineIndex = chunk.intro.lastIndexOf(n);
897
- if (lineIndex !== -1)
898
- return chunk.intro.substr(lineIndex + 1) + lineStr;
899
- lineStr = chunk.intro + lineStr;
900
- }
901
- } while (chunk = chunk.previous);
902
- lineIndex = this.intro.lastIndexOf(n);
903
- if (lineIndex !== -1)
904
- return this.intro.substr(lineIndex + 1) + lineStr;
905
- return this.intro + lineStr;
906
- }
907
- slice(start = 0, end = this.original.length - this.offset) {
908
- start = start + this.offset;
909
- end = end + this.offset;
910
- if (this.original.length !== 0) {
911
- while (start < 0)
912
- start += this.original.length;
913
- while (end < 0)
914
- end += this.original.length;
915
- }
916
- let result = "";
917
- let chunk = this.firstChunk;
918
- while (chunk && (chunk.start > start || chunk.end <= start)) {
919
- if (chunk.start < end && chunk.end >= end) {
920
- return result;
921
- }
922
- chunk = chunk.next;
923
- }
924
- if (chunk && chunk.edited && chunk.start !== start)
925
- throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
926
- const startChunk = chunk;
927
- while (chunk) {
928
- if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
929
- result += chunk.intro;
930
- }
931
- const containsEnd = chunk.start < end && chunk.end >= end;
932
- if (containsEnd && chunk.edited && chunk.end !== end)
933
- throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
934
- const sliceStart = startChunk === chunk ? start - chunk.start : 0;
935
- const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
936
- result += chunk.content.slice(sliceStart, sliceEnd);
937
- if (chunk.outro && (!containsEnd || chunk.end === end)) {
938
- result += chunk.outro;
939
- }
940
- if (containsEnd) {
941
- break;
942
- }
943
- chunk = chunk.next;
944
- }
945
- return result;
946
- }
947
- snip(start, end) {
948
- const clone = this.clone();
949
- clone.remove(0, start);
950
- clone.remove(end, clone.original.length);
951
- return clone;
952
- }
953
- _split(index) {
954
- if (this.byStart[index] || this.byEnd[index])
955
- return;
956
- let chunk = this.lastSearchedChunk;
957
- let previousChunk = chunk;
958
- const searchForward = index > chunk.end;
959
- while (chunk) {
960
- if (chunk.contains(index))
961
- return this._splitChunk(chunk, index);
962
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
963
- if (chunk === previousChunk)
964
- return;
965
- previousChunk = chunk;
966
- }
967
- }
968
- _splitChunk(chunk, index) {
969
- if (chunk.edited && chunk.content.length) {
970
- const loc = getLocator(this.original)(index);
971
- throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`);
972
- }
973
- const newChunk = chunk.split(index);
974
- this.byEnd[index] = chunk;
975
- this.byStart[index] = newChunk;
976
- this.byEnd[newChunk.end] = newChunk;
977
- if (chunk === this.lastChunk)
978
- this.lastChunk = newChunk;
979
- this.lastSearchedChunk = chunk;
980
- return true;
981
- }
982
- toString() {
983
- let str = this.intro;
984
- let chunk = this.firstChunk;
985
- while (chunk) {
986
- str += chunk.toString();
987
- chunk = chunk.next;
988
- }
989
- return str + this.outro;
990
- }
991
- isEmpty() {
992
- let chunk = this.firstChunk;
993
- do {
994
- if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
995
- return false;
996
- } while (chunk = chunk.next);
997
- return true;
998
- }
999
- length() {
1000
- let chunk = this.firstChunk;
1001
- let length = 0;
1002
- do {
1003
- length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1004
- } while (chunk = chunk.next);
1005
- return length;
1006
- }
1007
- trimLines() {
1008
- return this.trim("[\\r\\n]");
1009
- }
1010
- trim(charType) {
1011
- return this.trimStart(charType).trimEnd(charType);
1012
- }
1013
- trimEndAborted(charType) {
1014
- const rx = new RegExp((charType || "\\s") + "+$");
1015
- this.outro = this.outro.replace(rx, "");
1016
- if (this.outro.length)
1017
- return true;
1018
- let chunk = this.lastChunk;
1019
- do {
1020
- const end = chunk.end;
1021
- const aborted = chunk.trimEnd(rx);
1022
- if (chunk.end !== end) {
1023
- if (this.lastChunk === chunk) {
1024
- this.lastChunk = chunk.next;
1025
- }
1026
- this.byEnd[chunk.end] = chunk;
1027
- this.byStart[chunk.next.start] = chunk.next;
1028
- this.byEnd[chunk.next.end] = chunk.next;
1029
- }
1030
- if (aborted)
1031
- return true;
1032
- chunk = chunk.previous;
1033
- } while (chunk);
1034
- return false;
1035
- }
1036
- trimEnd(charType) {
1037
- this.trimEndAborted(charType);
1038
- return this;
1039
- }
1040
- trimStartAborted(charType) {
1041
- const rx = new RegExp("^" + (charType || "\\s") + "+");
1042
- this.intro = this.intro.replace(rx, "");
1043
- if (this.intro.length)
1044
- return true;
1045
- let chunk = this.firstChunk;
1046
- do {
1047
- const end = chunk.end;
1048
- const aborted = chunk.trimStart(rx);
1049
- if (chunk.end !== end) {
1050
- if (chunk === this.lastChunk)
1051
- this.lastChunk = chunk.next;
1052
- this.byEnd[chunk.end] = chunk;
1053
- this.byStart[chunk.next.start] = chunk.next;
1054
- this.byEnd[chunk.next.end] = chunk.next;
1055
- }
1056
- if (aborted)
1057
- return true;
1058
- chunk = chunk.next;
1059
- } while (chunk);
1060
- return false;
1061
- }
1062
- trimStart(charType) {
1063
- this.trimStartAborted(charType);
1064
- return this;
1065
- }
1066
- hasChanged() {
1067
- return this.original !== this.toString();
1068
- }
1069
- _replaceRegexp(searchValue, replacement) {
1070
- function getReplacement(match, str) {
1071
- if (typeof replacement === "string") {
1072
- return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1073
- if (i === "$")
1074
- return "$";
1075
- if (i === "&")
1076
- return match[0];
1077
- const num = +i;
1078
- if (num < match.length)
1079
- return match[+i];
1080
- return `$${i}`;
1081
- });
1082
- } else {
1083
- return replacement(...match, match.index, str, match.groups);
1084
- }
1085
- }
1086
- function matchAll(re, str) {
1087
- let match;
1088
- const matches = [];
1089
- while (match = re.exec(str)) {
1090
- matches.push(match);
1091
- }
1092
- return matches;
1093
- }
1094
- if (searchValue.global) {
1095
- const matches = matchAll(searchValue, this.original);
1096
- matches.forEach((match) => {
1097
- if (match.index != null) {
1098
- const replacement2 = getReplacement(match, this.original);
1099
- if (replacement2 !== match[0]) {
1100
- this.overwrite(match.index, match.index + match[0].length, replacement2);
1101
- }
1102
- }
1103
- });
1104
- } else {
1105
- const match = this.original.match(searchValue);
1106
- if (match && match.index != null) {
1107
- const replacement2 = getReplacement(match, this.original);
1108
- if (replacement2 !== match[0]) {
1109
- this.overwrite(match.index, match.index + match[0].length, replacement2);
1110
- }
1111
- }
1112
- }
1113
- return this;
1114
- }
1115
- _replaceString(string, replacement) {
1116
- const { original } = this;
1117
- const index = original.indexOf(string);
1118
- if (index !== -1) {
1119
- if (typeof replacement === "function") {
1120
- replacement = replacement(string, index, original);
1121
- }
1122
- if (string !== replacement) {
1123
- this.overwrite(index, index + string.length, replacement);
1124
- }
1125
- }
1126
- return this;
1127
- }
1128
- replace(searchValue, replacement) {
1129
- if (typeof searchValue === "string") {
1130
- return this._replaceString(searchValue, replacement);
1131
- }
1132
- return this._replaceRegexp(searchValue, replacement);
1133
- }
1134
- _replaceAllString(string, replacement) {
1135
- const { original } = this;
1136
- const stringLength = string.length;
1137
- for (let index = original.indexOf(string);index !== -1; index = original.indexOf(string, index + stringLength)) {
1138
- const previous = original.slice(index, index + stringLength);
1139
- let _replacement = replacement;
1140
- if (typeof replacement === "function") {
1141
- _replacement = replacement(previous, index, original);
1142
- }
1143
- if (previous !== _replacement)
1144
- this.overwrite(index, index + stringLength, _replacement);
1145
- }
1146
- return this;
1147
- }
1148
- replaceAll(searchValue, replacement) {
1149
- if (typeof searchValue === "string") {
1150
- return this._replaceAllString(searchValue, replacement);
1151
- }
1152
- if (!searchValue.global) {
1153
- throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument");
1154
- }
1155
- return this._replaceRegexp(searchValue, replacement);
1156
- }
1157
- }
1158
-
1159
- // src/plugin/transform-client.ts
1160
- import { parseSync } from "oxc-parser";
1161
- var bunTranspiler = new Bun.Transpiler({
1162
- loader: "tsx",
1163
- tsconfig: {
1164
- compilerOptions: {
1165
- jsx: "react",
1166
- jsxFactory: "React.createElement",
1167
- jsxFragmentFactory: "React.Fragment"
1168
- }
1169
- }
1170
- });
1171
- var SERVER_ONLY_PROPERTIES = new Set(["loader", "query", "params", "staticParams"]);
1172
- function walk(node, visitor) {
1173
- if (!node || typeof node !== "object") {
1174
- return;
1175
- }
1176
- if (Array.isArray(node)) {
1177
- for (const child of node) {
1178
- walk(child, visitor);
1179
- }
1180
- return;
1181
- }
1182
- const n2 = node;
1183
- if (typeof n2.type === "string") {
1184
- visitor(n2);
1185
- }
1186
- for (const key of Object.keys(n2)) {
1187
- if (key === "type" || key === "start" || key === "end") {
1188
- continue;
1189
- }
1190
- walk(n2[key], visitor);
1191
- }
1192
- }
1193
- function isCreateRouteCall(node) {
1194
- return node.callee.type === "Identifier" && node.callee.name === "createRoute";
1195
- }
1196
- function isRoutePageCall(node) {
1197
- const { callee } = node;
1198
- if (callee.type === "Identifier" && callee.name === "page") {
1199
- return true;
1200
- }
1201
- if (callee.type === "MemberExpression" && callee.property?.name === "page") {
1202
- return true;
1203
- }
1204
- return false;
1205
- }
1206
- function isTargetCall(node) {
1207
- return isCreateRouteCall(node) || isRoutePageCall(node);
1208
- }
1209
- function removeServerProperties(s, source, obj) {
1210
- const toRemove = obj.properties.filter((p) => {
1211
- if (p.type !== "Property") {
1212
- return false;
1213
- }
1214
- const { key } = p;
1215
- if (p.computed) {
1216
- return false;
1217
- }
1218
- if (key.type === "Identifier" && typeof key.name === "string") {
1219
- return SERVER_ONLY_PROPERTIES.has(key.name);
1220
- }
1221
- if (key.type === "Literal" && typeof key.value === "string") {
1222
- return SERVER_ONLY_PROPERTIES.has(key.value);
1223
- }
1224
- return false;
1225
- });
1226
- if (toRemove.length === 0) {
1227
- return false;
1228
- }
1229
- for (const prop of toRemove) {
1230
- let removeEnd = prop.end;
1231
- while (removeEnd < source.length && (source[removeEnd] === "," || source[removeEnd] === " " || source[removeEnd] === `
1232
- ` || source[removeEnd] === "\r" || source[removeEnd] === "\t")) {
1233
- if (source[removeEnd] === ",") {
1234
- removeEnd++;
1235
- break;
1236
- }
1237
- removeEnd++;
1238
- }
1239
- let removeStart = prop.start;
1240
- while (removeStart > 0 && (source[removeStart - 1] === " " || source[removeStart - 1] === "\t")) {
1241
- removeStart--;
1242
- }
1243
- if (removeStart > 0 && source[removeStart - 1] === `
1244
- `) {
1245
- removeStart--;
1246
- if (removeStart > 0 && source[removeStart - 1] === "\r") {
1247
- removeStart--;
1248
- }
1249
- }
1250
- s.remove(removeStart, removeEnd);
1251
- }
1252
- return true;
1253
- }
1254
- function collectReferencedNames(program) {
1255
- const refs = new Set;
1256
- const excluded = new Set;
1257
- for (const stmt of program.body ?? []) {
1258
- if (stmt.type === "ImportDeclaration") {
1259
- continue;
1260
- }
1261
- walk(stmt, (node) => {
1262
- if (node.type === "Property" && !node.computed) {
1263
- excluded.add(node.key);
1264
- }
1265
- if (node.type === "MemberExpression" && !node.computed) {
1266
- excluded.add(node.property);
1267
- }
1268
- });
1269
- }
1270
- for (const stmt of program.body ?? []) {
1271
- if (stmt.type === "ImportDeclaration") {
1272
- continue;
1273
- }
1274
- walk(stmt, (node) => {
1275
- if (excluded.has(node)) {
1276
- return;
1277
- }
1278
- if (node.type === "Identifier" && typeof node.name === "string") {
1279
- refs.add(node.name);
1280
- }
1281
- });
1282
- }
1283
- return refs;
1284
- }
1285
- function removeEntireImport(s, code, decl) {
1286
- let removeEnd = decl.end;
1287
- while (removeEnd < code.length && (code[removeEnd] === `
1288
- ` || code[removeEnd] === "\r")) {
1289
- removeEnd++;
1290
- }
1291
- s.remove(decl.start, removeEnd);
1292
- }
1293
- function removeUnusedSpecifiers(s, code, decl, refs) {
1294
- const removedSpecs = decl.specifiers.filter((spec) => !refs.has(spec.local.name));
1295
- for (const spec of removedSpecs) {
1296
- let removeStart = spec.start;
1297
- let removeEnd = spec.end;
1298
- while (removeEnd < code.length && (code[removeEnd] === "," || code[removeEnd] === " ")) {
1299
- removeEnd++;
1300
- }
1301
- if (!code.slice(spec.end, removeEnd).includes(",")) {
1302
- while (removeStart > 0 && (code[removeStart - 1] === " " || code[removeStart - 1] === ",")) {
1303
- removeStart--;
1304
- }
1305
- }
1306
- s.remove(removeStart, removeEnd);
1307
- }
1308
- }
1309
- function deadCodeElimination(s) {
1310
- const code = s.toString();
1311
- const { program, errors } = parseSync("dce.js", code);
1312
- if (errors.length > 0) {
1313
- console.error("[furin] DCE: failed to parse transformed output:", errors[0]?.message);
1314
- return s;
1315
- }
1316
- const fresh = new MagicString(code);
1317
- const programNode = program;
1318
- const refs = collectReferencedNames(programNode);
1319
- const body = programNode.body ?? [];
1320
- for (let i = body.length - 1;i >= 0; i--) {
1321
- const stmt = body[i];
1322
- if (!stmt) {
1323
- continue;
1324
- }
1325
- if (stmt.type !== "ImportDeclaration") {
1326
- continue;
1327
- }
1328
- const decl = stmt;
1329
- if (!decl.specifiers || decl.specifiers.length === 0) {
1330
- continue;
1331
- }
1332
- const usedCount = decl.specifiers.filter((spec) => refs.has(spec.local.name)).length;
1333
- if (usedCount === 0) {
1334
- removeEntireImport(fresh, code, decl);
1335
- } else if (usedCount < decl.specifiers.length) {
1336
- removeUnusedSpecifiers(fresh, code, decl, refs);
1337
- }
1338
- }
1339
- return fresh;
1340
- }
1341
- function removeServerExports(s, source, program) {
1342
- let removedServerCode = false;
1343
- walk(program, (node) => {
1344
- if (node.type !== "CallExpression") {
1345
- return;
1346
- }
1347
- const call = node;
1348
- if (!isTargetCall(call)) {
1349
- return;
1350
- }
1351
- const arg = call.arguments[0];
1352
- if (!arg || arg.type !== "ObjectExpression") {
1353
- return;
1354
- }
1355
- if (removeServerProperties(s, source, arg)) {
1356
- removedServerCode = true;
1357
- }
1358
- });
1359
- return removedServerCode;
1360
- }
1361
- function transformForClient(code, filename) {
1362
- const plainJs = bunTranspiler.transformSync(code);
1363
- const { program, errors } = parseSync(filename, plainJs);
1364
- if (errors.length > 0) {
1365
- throw new Error(`Failed to parse ${filename}: ${errors[0]?.message}`);
1366
- }
1367
- let s = new MagicString(plainJs);
1368
- const removedServerCode = removeServerExports(s, plainJs, program);
1369
- if (removedServerCode) {
1370
- s = deadCodeElimination(s);
1371
- }
1372
- return {
1373
- code: s.toString(),
1374
- map: s.generateMap({ source: filename, includeContent: true }),
1375
- removedServerCode
1376
- };
1377
- }
1378
-
1379
- // src/render/shell.ts
1380
- function extractTitle(meta) {
1381
- if (!meta) {
1382
- return;
1383
- }
1384
- for (const entry of meta) {
1385
- if ("title" in entry) {
1386
- return entry.title;
1387
- }
1388
- }
1389
- return;
1390
- }
1391
- function isMetaTag(entry) {
1392
- return !(("title" in entry) || ("charSet" in entry) || ("script:ld+json" in entry) || ("tagName" in entry));
1393
- }
1394
- function escapeHtml(str) {
1395
- return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
1396
- }
1397
- function safeJson(value) {
1398
- return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1399
- }
1400
- function renderAttrs(obj) {
1401
- return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
1402
- }
1403
- function buildMetaParts(meta) {
1404
- const parts = [];
1405
- const title = extractTitle(meta);
1406
- if (title) {
1407
- parts.push(`<title>${escapeHtml(title)}</title>`);
1408
- }
1409
- for (const m of meta) {
1410
- if (isMetaTag(m)) {
1411
- parts.push(`<meta ${renderAttrs(m)} />`);
1412
- }
1413
- if ("script:ld+json" in m) {
1414
- parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
1415
- }
1416
- }
1417
- return parts;
1418
- }
1419
- function buildLinkParts(links) {
1420
- return links.map((link) => `<link ${renderAttrs(link)} />`);
1421
- }
1422
- function buildScriptParts(scripts) {
1423
- return scripts.map((script) => {
1424
- const { children, ...rest } = script;
1425
- const attrs = renderAttrs(rest);
1426
- if (children) {
1427
- return `<script ${attrs}>${children}</script>`;
1428
- }
1429
- return `<script ${attrs}></script>`;
1430
- });
1431
- }
1432
- function buildStyleParts(styles) {
1433
- return styles.map((style) => {
1434
- const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
1435
- return `<style${typeAttr}>${style.children}</style>`;
1436
- });
1437
- }
1438
- function buildHeadInjection(headData) {
1439
- const parts = [];
1440
- if (headData?.meta) {
1441
- parts.push(...buildMetaParts(headData.meta));
1442
- }
1443
- if (headData?.links) {
1444
- parts.push(...buildLinkParts(headData.links));
1445
- }
1446
- if (headData?.scripts) {
1447
- parts.push(...buildScriptParts(headData.scripts));
1448
- }
1449
- if (headData?.styles) {
1450
- parts.push(...buildStyleParts(headData.styles));
1451
- }
1452
- return parts.length > 0 ? `
1453
- ${parts.join(`
1454
- `)}
1455
- ` : "";
1456
- }
1457
- 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>`;
1458
- function generateIndexHtml() {
1459
- return `<!DOCTYPE html>
1460
- <html lang="en">
1461
- <head>
1462
- <meta charset="UTF-8">
1463
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
1464
- ${THEME_INIT_SCRIPT}
1465
- <!--ssr-head-->
1466
- </head>
1467
- <body>
1468
- <div id="root"><!--ssr-outlet--></div>
1469
- <script type="module" src="./_hydrate.tsx"></script>
1470
- </body>
1471
- </html>
1472
- `;
1473
- }
1474
- function generateProdIndexHtml(entryChunk, cssChunks, buildId, faviconHref) {
1475
- const cssLinks = cssChunks.map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`).join(`
1476
- `);
1477
- const scriptTag = `<script type="module" crossorigin src="${entryChunk}"></script>`;
1478
- const buildIdMeta = buildId ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">
1479
- ` : "";
1480
- const faviconLink = faviconHref ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">
1481
- ` : "";
1482
- return `<!DOCTYPE html>
1483
- <html lang="en">
1484
- <head>
1485
- <meta charset="UTF-8">
1486
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
1487
- ${THEME_INIT_SCRIPT}
1488
- ${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}
1489
- ` : ""} <!--ssr-head-->
1490
- </head>
1491
- <body>
1492
- <div id="root"><!--ssr-outlet--></div>
1493
- ${scriptTag}
1494
- </body>
1495
- </html>
1496
- `;
1497
- }
1498
-
1499
- // src/build/hydrate.ts
1500
- function generateHydrateEntry(routes, rootLayout, basePath) {
1501
- const routeEntries = [];
1502
- for (const route of routes) {
1503
- const resolvedPage = route.path.replace(/\\/g, "/");
1504
- const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
1505
- routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}") }`);
1506
- }
1507
- const basePathLiteral = JSON.stringify(basePath);
1508
- 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";
1509
- const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
1510
- const basePathProp = basePath ? `
1511
- basePath: ${basePathLiteral},` : "";
1512
- return `import { hydrateRoot, createRoot } from "react-dom/client";
1513
- import { createElement } from "react";
1514
- import { initLogger, log } from "evlog";
1515
- import { createHttpLogDrain } from "evlog/http";
1516
- import { RouterProvider } from "@teyik0/furin/link";
1517
- import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
1518
-
1519
- initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
1520
-
1521
- const routes = [
1522
- ${routeEntries.join(`,
1523
- `)}
1524
- ];
1525
-
1526
- const pathname = ${pathnameExpr};
1527
- const _match = routes.find((r) => r.regex.test(pathname));
1528
-
1529
- // Eagerly load only the current page module for initial hydration.
1530
- // All other pages are loaded on demand when the user navigates to them.
1531
- // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
1532
- // bundler to misidentify which chunk to reference as the entry in index.html.
1533
- (async () => {
1534
- if (_match) {
1535
- const _mod = await _match.load();
1536
- const match = { ..._match, component: _mod.default.component, pageRoute: _mod.default._route };
1537
-
1538
- const dataEl = document.getElementById("__FURIN_DATA__");
1539
- const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
1540
- const rootEl = document.getElementById("root") as HTMLElement;
1541
-
1542
- const app = createElement(RouterProvider, {
1543
- routes,
1544
- root,
1545
- initialMatch: match,
1546
- initialData: loaderData,${basePathProp}
1547
- } as any);
1548
-
1549
- if (import.meta.hot) {
1550
- if (import.meta.hot.data.root) {
1551
- // HMR re-render \u2014 update in place without remounting
1552
- import.meta.hot.data.root.render(app);
1553
- } else if (rootEl.innerHTML.trim()) {
1554
- // First load with SSR content \u2014 hydrateRoot renders on construction
1555
- import.meta.hot.data.root = hydrateRoot(rootEl, app);
1556
- } else {
1557
- // First load without SSR content \u2014 createRoot requires explicit .render()
1558
- const freshRoot = createRoot(rootEl);
1559
- freshRoot.render(app);
1560
- import.meta.hot.data.root = freshRoot;
1561
- }
1562
- } else if (rootEl.innerHTML.trim()) {
1563
- hydrateRoot(rootEl, app);
1564
- } else {
1565
- createRoot(rootEl).render(app);
1566
- }
1567
- log.info({ action: "hydrate_complete", pathname });
1568
- } else {
1569
- log.error({ action: "hydrate_no_match", pathname });
1570
- }
1571
- })().catch((err: unknown) => {
1572
- log.error({ action: "hydrate_failed", pathname, error: String(err) });
1573
- });
1574
- `;
1575
- }
1576
-
1577
- // src/build/shared.ts
1578
- import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from "fs";
1579
- import { join, relative } from "path";
1580
- var CLIENT_MODULE_PATH = new URL(import.meta.resolve("@teyik0/furin/client")).pathname;
1581
- var LINK_MODULE_PATH = new URL(import.meta.resolve("@teyik0/furin/link")).pathname;
1582
- function ensureDir(path) {
1583
- if (!existsSync(path)) {
1584
- mkdirSync(path, { recursive: true });
1585
- }
1586
- }
1587
- function toPosixPath(path) {
1588
- return path.replace(/\\/g, "/");
1589
- }
1590
- function collectFilesRecursive(dir) {
1591
- const files = [];
1592
- const entries = readdirSync(dir, { withFileTypes: true });
1593
- for (const entry of entries) {
1594
- const absolutePath = join(dir, entry.name);
1595
- if (entry.isDirectory()) {
1596
- files.push(...collectFilesRecursive(absolutePath));
1597
- continue;
1598
- }
1599
- if (entry.isFile()) {
1600
- files.push(absolutePath);
1601
- }
1602
- }
1603
- return files.sort();
1604
- }
1605
- function copyDirRecursive(sourceDir, targetDir) {
1606
- rmSync(targetDir, { force: true, recursive: true });
1607
- cpSync(sourceDir, targetDir, { recursive: true });
1608
- }
1609
- function toBuildRouteManifestEntry(route, rootDir) {
1610
- return {
1611
- pattern: route.pattern,
1612
- mode: route.mode,
1613
- pagePath: toPosixPath(relative(rootDir, route.path)),
1614
- hasLayout: route.routeChain.some((entry) => !!entry.layout),
1615
- hasStaticParams: !!route.page?.staticParams,
1616
- revalidate: route.page?._route.revalidate ?? null
1617
- };
1618
- }
1619
- function buildTargetManifest(rootDir, buildRoot, target, serverEntry) {
1620
- const targetDir = join(buildRoot, target);
1621
- return {
1622
- buildId: "",
1623
- generatedAt: new Date().toISOString(),
1624
- targetDir: toPosixPath(relative(rootDir, targetDir)),
1625
- clientDir: toPosixPath(relative(rootDir, join(targetDir, "client"))),
1626
- templatePath: toPosixPath(relative(rootDir, join(targetDir, "client", "index.html"))),
1627
- serverPath: null,
1628
- serverEntry: serverEntry ? toPosixPath(relative(rootDir, serverEntry)) : null
1629
- };
1630
- }
1631
-
1632
- // src/build/client.ts
1633
- var TS_FILE_FILTER = /\.(tsx|ts)$/;
1634
- var REACT_IMPORT_RE = /import\s+React\b/;
1635
- async function buildClient(routes, { outDir, rootLayout, plugins, publicPath, basePath }) {
1636
- const clientDir = join2(outDir, "client");
1637
- if (!existsSync2(outDir)) {
1638
- mkdirSync2(outDir, { recursive: true });
1639
- }
1640
- if (!existsSync2(clientDir)) {
1641
- mkdirSync2(clientDir, { recursive: true });
1642
- }
1643
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
1644
- const hydratePath = join2(outDir, "_hydrate.tsx");
1645
- writeFileSync(hydratePath, hydrateCode);
1646
- console.log("[furin] Building production client bundle\u2026");
1647
- const transformPlugin = {
1648
- name: "furin-transform-client",
1649
- setup(build) {
1650
- build.onLoad({ filter: TS_FILE_FILTER }, async (args) => {
1651
- const { path } = args;
1652
- if (path.includes("node_modules")) {
1653
- return;
1654
- }
1655
- const code = await Bun.file(path).text();
1656
- try {
1657
- const result2 = transformForClient(code, path);
1658
- let transformed = result2.code;
1659
- if (transformed.includes("React.createElement") && !REACT_IMPORT_RE.test(transformed)) {
1660
- transformed = `import React from "react";
1661
- ${transformed}`;
1662
- }
1663
- 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));
1664
- return {
1665
- contents: transformed,
1666
- loader: path.endsWith(".tsx") ? "tsx" : "ts"
1667
- };
1668
- } catch (error) {
1669
- console.error(`[furin] Transform error for ${path}:`, error);
1670
- return;
1671
- }
1672
- });
1673
- }
1674
- };
1675
- const clientBuildConfig = {
1676
- entrypoints: [hydratePath],
1677
- outdir: clientDir,
1678
- target: "browser",
1679
- format: "esm",
1680
- splitting: true,
1681
- minify: true,
1682
- sourcemap: "linked",
1683
- naming: {
1684
- entry: "[dir]/[name]-[hash].[ext]",
1685
- chunk: "[name]-[hash].[ext]"
1686
- },
1687
- publicPath,
1688
- plugins: plugins ? [...plugins, transformPlugin] : [transformPlugin],
1689
- alias: {
1690
- "@teyik0/furin/client": CLIENT_MODULE_PATH,
1691
- "@teyik0/furin/link": LINK_MODULE_PATH
1692
- },
1693
- define: {
1694
- "process.env.NODE_ENV": JSON.stringify("production")
1695
- }
1696
- };
1697
- const result = await Bun.build(clientBuildConfig);
1698
- for (const output of result.outputs) {
1699
- console.log(`[furin] ${output.path} (${(output.size / 1024).toFixed(1)} KB)`);
1700
- }
1701
- const entryOutput = result.outputs.find((o) => o.kind === "entry-point");
1702
- const cssOutputs = result.outputs.filter((o) => o.path.endsWith(".css") && !o.path.endsWith(".css.map"));
1703
- if (!entryOutput) {
1704
- throw new Error("[furin] client build did not emit entry chunk");
1705
- }
1706
- let publicPrefix;
1707
- if (publicPath === "") {
1708
- publicPrefix = "";
1709
- } else {
1710
- publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
1711
- }
1712
- const entryChunk = `${publicPrefix}${basename(entryOutput.path)}`;
1713
- const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename(o.path)}`);
1714
- console.log("[furin] Production client build complete");
1715
- return { entryChunk, cssChunks };
1716
- }
1717
-
1718
- // src/build/compile-entry.ts
1719
- import { existsSync as existsSync3, writeFileSync as writeFileSync2 } from "fs";
1720
- import { join as join3, relative as relative2 } from "path";
1721
-
1722
- // src/build/entry-template.ts
1723
- import { dirname } from "path";
1724
- var _pkgSrcDir = dirname(new URL(import.meta.resolve("@teyik0/furin")).pathname);
1725
- var INTERNAL_MODULE_PATH = `${_pkgSrcDir}/internal.ts`;
1726
- var RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/runtime-env.ts`;
1727
- function buildEntrySource(options) {
1728
- const { buildId, headerComment, rootPath, routes, serverEntry } = options;
1729
- let { extraImports, extraContext } = options;
1730
- if (extraImports === undefined) {
1731
- extraImports = [];
1732
- }
1733
- if (extraContext === undefined) {
1734
- extraContext = [];
1735
- }
1736
- const allModulePaths = [rootPath, ...routes.map((r) => r.path)];
1737
- const moduleImports = [];
1738
- const moduleEntries = [];
1739
- for (let i = 0;i < allModulePaths.length; i++) {
1740
- const absPath = allModulePaths[i].replace(/\\/g, "/");
1741
- const varName = `_mod${i}`;
1742
- moduleImports.push(`import * as ${varName} from ${JSON.stringify(absPath)};`);
1743
- moduleEntries.push(` ${JSON.stringify(absPath)}: ${varName},`);
1744
- }
1745
- const routeEntries = routes.map((r) => ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`);
1746
- const lines = [
1747
- headerComment,
1748
- `import { __setCompileContext } from ${JSON.stringify(INTERNAL_MODULE_PATH)};`,
1749
- `import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`,
1750
- ...moduleImports,
1751
- ...extraImports.length > 0 ? ["", ...extraImports] : [],
1752
- "",
1753
- "// Force production mode \u2014 Bun may inline process.env.NODE_ENV at bundle time.",
1754
- "__setDevMode(false);",
1755
- 'process.env.NODE_ENV = "production";',
1756
- "",
1757
- "__setCompileContext({",
1758
- ` buildId: ${JSON.stringify(buildId ?? "")},`,
1759
- ` rootPath: ${JSON.stringify(rootPath.replace(/\\/g, "/"))},`,
1760
- " modules: {",
1761
- ...moduleEntries,
1762
- " },",
1763
- " routes: [",
1764
- ...routeEntries,
1765
- " ],",
1766
- ...extraContext,
1767
- "});",
1768
- "",
1769
- `await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
1770
- ""
1771
- ];
1772
- return lines.join(`
1773
- `);
1774
- }
1775
-
1776
- // src/build/compile-entry.ts
1777
- function generateCompileEntry(options) {
1778
- const { buildId, outDir, rootPath, routes, serverEntry, embed, publicDir } = options;
1779
- ensureDir(outDir);
1780
- const assetImports = [];
1781
- let embeddedBlock = [];
1782
- if (embed) {
1783
- if (!existsSync3(embed.clientDir)) {
1784
- throw new Error(`[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`);
1785
- }
1786
- const clientFiles = collectFilesRecursive(embed.clientDir);
1787
- const assetEntries = [];
1788
- let templateVarName = null;
1789
- let assetIndex = 0;
1790
- for (const file of clientFiles) {
1791
- const varName = `_asset${assetIndex++}`;
1792
- const relPath = toPosixPath(relative2(outDir, file));
1793
- const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
1794
- assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
1795
- const clientRelativePath = toPosixPath(relative2(embed.clientDir, file));
1796
- if (clientRelativePath === "index.html") {
1797
- templateVarName = varName;
1798
- } else {
1799
- assetEntries.push(` ${JSON.stringify(`/_client/${clientRelativePath}`)}: ${varName},`);
1800
- }
1801
- }
1802
- if (templateVarName === null) {
1803
- throw new Error(`[furin] Embed mode requires a client index.html at ${join3(embed.clientDir, "index.html")}. Run the client build first.`);
1804
- }
1805
- if (publicDir && existsSync3(publicDir)) {
1806
- const publicFiles = collectFilesRecursive(publicDir);
1807
- for (const file of publicFiles) {
1808
- const varName = `_asset${assetIndex++}`;
1809
- const relPath = toPosixPath(relative2(outDir, file));
1810
- const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
1811
- assetImports.push(`import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`);
1812
- const publicRelativePath = toPosixPath(relative2(publicDir, file));
1813
- assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
1814
- }
1815
- }
1816
- embeddedBlock = [
1817
- " embedded: {",
1818
- ` template: ${templateVarName},`,
1819
- " assets: {",
1820
- ...assetEntries,
1821
- " },",
1822
- " },"
1823
- ];
1824
- }
1825
- const source = buildEntrySource({
1826
- buildId,
1827
- headerComment: "// Auto-generated by furin compile \u2014 do not edit",
1828
- rootPath,
1829
- routes,
1830
- serverEntry,
1831
- extraImports: assetImports,
1832
- extraContext: embeddedBlock
1833
- });
1834
- const entryPath = join3(outDir, "_compile-entry.ts");
1835
- writeFileSync2(entryPath, source);
1836
- return entryPath;
1837
- }
1838
-
1839
- // src/build/server-routes-entry.ts
1840
- import { writeFileSync as writeFileSync3 } from "fs";
1841
- import { join as join4 } from "path";
1842
- function generateServerRoutesEntry(options) {
1843
- const { buildId, outDir, rootPath, routes, serverEntry } = options;
1844
- ensureDir(outDir);
1845
- const source = buildEntrySource({
1846
- buildId,
1847
- headerComment: "// Auto-generated by furin build \u2014 do not edit",
1848
- rootPath,
1849
- routes,
1850
- serverEntry
1851
- });
1852
- const entryPath = join4(outDir, "server.ts");
1853
- writeFileSync3(entryPath, source);
1854
- return entryPath;
1855
- }
1856
-
1857
- // src/adapter/bun.ts
1858
- var _pkgSrcDir2 = dirname2(fileURLToPath(import.meta.resolve("@teyik0/furin")));
1859
- var BUILD_ID_INPUT_PATHS = [
1860
- `${_pkgSrcDir2}/build/compile-entry.ts`,
1861
- `${_pkgSrcDir2}/build/entry-template.ts`,
1862
- `${_pkgSrcDir2}/build/server-routes-entry.ts`,
1863
- `${_pkgSrcDir2}/render/index.ts`,
1864
- `${_pkgSrcDir2}/render/shell.ts`,
1865
- `${_pkgSrcDir2}/router.ts`
1866
- ];
1867
- async function createBuildFingerprint(entryChunk, cssChunks, routes, rootPath, serverEntry) {
1868
- const fingerprintPaths = new Set([rootPath, ...routes.map((route) => route.path)]);
1869
- if (serverEntry) {
1870
- fingerprintPaths.add(serverEntry);
1871
- }
1872
- for (const path of BUILD_ID_INPUT_PATHS) {
1873
- if (!existsSync4(path)) {
1874
- console.warn(`[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
1875
- }
1876
- fingerprintPaths.add(path);
1877
- }
1878
- const fileParts = await Promise.all([...fingerprintPaths].sort().map(async (path) => {
1879
- const content = existsSync4(path) ? await Bun.file(path).text() : "";
1880
- return `${toPosixPath(path)}:${content}`;
1881
- }));
1882
- const routeParts = routes.map((route) => JSON.stringify({ mode: route.mode, path: toPosixPath(route.path), pattern: route.pattern })).sort();
1883
- return [entryChunk, ...[...cssChunks].sort(), ...routeParts, ...fileParts].join(`
1884
- `);
1885
- }
1886
- async function buildBunTarget(routes, rootDir, buildRoot, rootPath, serverEntry, options) {
1887
- if (options.compile && !serverEntry) {
1888
- throw new Error(`[furin] \`compile: "${options.compile}"\` requires a server entry point. ` + "Create src/server.ts or set `serverEntry` in your furin.config.ts.");
1889
- }
1890
- const target = "bun";
1891
- const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
1892
- const targetDir = resolve(rootDir, targetManifest.targetDir);
1893
- rmSync2(targetDir, { force: true, recursive: true });
1894
- ensureDir(targetDir);
1895
- const { entryChunk, cssChunks } = await buildClient(routes, {
1896
- outDir: targetDir,
1897
- rootLayout: rootPath,
1898
- plugins: options.plugins,
1899
- publicPath: "/_client/",
1900
- basePath: ""
1901
- });
1902
- const buildFingerprint = await createBuildFingerprint(entryChunk, cssChunks, routes, rootPath, serverEntry);
1903
- const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
1904
- targetManifest.buildId = buildId;
1905
- const clientDir = join5(targetDir, "client");
1906
- writeFileSync4(join5(clientDir, "index.html"), generateProdIndexHtml(entryChunk, cssChunks, buildId));
1907
- const routeManifest = routes.map((r) => ({ pattern: r.pattern, path: r.path, mode: r.mode }));
1908
- const publicDir = existsSync4(join5(rootDir, "public")) ? join5(rootDir, "public") : undefined;
1909
- const targetPublicDir = publicDir ? join5(targetDir, "public") : undefined;
1910
- if (publicDir && targetPublicDir && options.compile !== "embed") {
1911
- copyDirRecursive(publicDir, targetPublicDir);
1912
- }
1913
- if (options.compile && serverEntry) {
1914
- const clientDir2 = join5(targetDir, "client");
1915
- const outfile = join5(targetDir, "server");
1916
- const entryPath = generateCompileEntry({
1917
- buildId,
1918
- rootPath,
1919
- routes: routeManifest,
1920
- serverEntry,
1921
- outDir: targetDir,
1922
- embed: options.compile === "embed" ? { clientDir: clientDir2 } : undefined,
1923
- publicDir
1924
- });
1925
- await Bun.build({
1926
- entrypoints: [entryPath],
1927
- compile: { outfile },
1928
- minify: true,
1929
- sourcemap: "linked",
1930
- define: { "process.env.NODE_ENV": JSON.stringify("production") },
1931
- plugins: options.plugins
1932
- });
1933
- if (process.platform === "darwin") {
1934
- Bun.spawnSync(["codesign", "--remove-signature", outfile]);
1935
- const sign = Bun.spawnSync(["codesign", "-f", "-s", "-", outfile]);
1936
- if (sign.exitCode !== 0) {
1937
- console.warn(`[furin] Warning: codesign failed (exit ${sign.exitCode}). ` + `The binary may be killed by Gatekeeper on macOS. Run manually:
1938
- ` + ` codesign --remove-signature ${outfile}
1939
- ` + ` codesign -f -s - ${outfile}`);
1940
- }
1941
- }
1942
- console.log(`[furin] Server binary: ${outfile}`);
1943
- targetManifest.serverPath = toPosixPath(join5(targetManifest.targetDir, "server"));
1944
- if (options.compile === "embed") {
1945
- rmSync2(clientDir2, { force: true, recursive: true });
1946
- targetManifest.clientDir = null;
1947
- targetManifest.templatePath = null;
1948
- }
1949
- } else if (serverEntry) {
1950
- const entryPath = generateServerRoutesEntry({
1951
- buildId,
1952
- rootPath,
1953
- routes: routeManifest,
1954
- serverEntry,
1955
- outDir: targetDir
1956
- });
1957
- await Bun.build({
1958
- entrypoints: [entryPath],
1959
- outdir: targetDir,
1960
- target: "bun",
1961
- minify: true,
1962
- sourcemap: "linked",
1963
- plugins: options.plugins
1964
- });
1965
- console.log(`[furin] Server bundle: ${toPosixPath(join5(targetManifest.targetDir, "server.js"))}`);
1966
- targetManifest.serverPath = toPosixPath(join5(targetManifest.targetDir, "server.js"));
1967
- }
1968
- for (const file of [
1969
- "_compile-entry.ts",
1970
- "_compile-entry.js.map",
1971
- "server.ts",
1972
- "_hydrate.tsx"
1973
- ]) {
1974
- rmSync2(join5(targetDir, file), { force: true });
1975
- }
1976
- return targetManifest;
1977
- }
1978
-
1979
- // src/adapter/static.ts
1980
- import { cpSync as cpSync2, existsSync as existsSync5, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "fs";
1981
- import { dirname as dirname3, isAbsolute, join as join6, relative as relative3, resolve as resolve2, sep } from "path";
1982
-
1983
- // src/render/assemble.ts
1984
- function resolvePath(pattern, params) {
1985
- let path = pattern;
1986
- for (const [key, val] of Object.entries(params ?? {})) {
1987
- path = path.replace(key === "*" ? "*" : `:${key}`, val);
1988
- }
1989
- return path;
1990
- }
1991
- async function streamToString(stream) {
1992
- const reader = stream.getReader();
1993
- const decoder = new TextDecoder;
1994
- let html = "";
1995
- for (;; ) {
1996
- const { done, value } = await reader.read();
1997
- if (done) {
1998
- break;
1999
- }
2000
- html += decoder.decode(value, { stream: true });
2001
- }
2002
- html += decoder.decode();
2003
- return html;
2004
- }
2005
- function splitTemplate(template) {
2006
- const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
2007
- const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
2008
- return { headPre, bodyPre, bodyPost };
2009
- }
2010
- function assembleHTML(template, headData, reactHtml, data) {
2011
- const { headPre, bodyPre, bodyPost } = splitTemplate(template);
2012
- const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
2013
- let injectedBodyPost = bodyPost;
2014
- if (dataScript) {
2015
- injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${dataScript}</body>`) : bodyPost + dataScript;
2016
- }
2017
- return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
2018
- }
2019
-
2020
- // src/render/index.ts
2021
- import { createElement as createElement2 } from "react";
2022
- import { renderToReadableStream } from "react-dom/server";
2023
- // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/utils.mjs
2024
- function formatDuration(ms) {
2025
- if (ms < 1000)
2026
- return `${Math.round(ms)}ms`;
2027
- return `${(ms / 1000).toFixed(2)}s`;
2028
- }
2029
- function isClient() {
2030
- return typeof window !== "undefined";
2031
- }
2032
- function isDev() {
2033
- if (typeof process !== "undefined")
2034
- return true;
2035
- if (typeof window !== "undefined")
2036
- return true;
2037
- return false;
2038
- }
2039
- function detectEnvironment() {
2040
- const env = typeof process !== "undefined" ? process.env : {};
2041
- const defaultEnvironment = isDev() ? "development" : "production";
2042
- return {
2043
- environment: env.NODE_ENV || defaultEnvironment,
2044
- service: env.SERVICE_NAME || "app",
2045
- version: env.APP_VERSION,
2046
- commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
2047
- region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
2048
- };
2049
- }
2050
- var LEVEL_ORDER = {
2051
- debug: 0,
2052
- info: 1,
2053
- warn: 2,
2054
- error: 3
2055
- };
2056
- function isLevelEnabled(level, minLevel) {
2057
- return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
2058
- }
2059
- function getConsoleMethod(level) {
2060
- return level;
2061
- }
2062
- var colors = {
2063
- reset: "\x1B[0m",
2064
- bold: "\x1B[1m",
2065
- dim: "\x1B[2m",
2066
- red: "\x1B[31m",
2067
- green: "\x1B[32m",
2068
- yellow: "\x1B[33m",
2069
- blue: "\x1B[34m",
2070
- magenta: "\x1B[35m",
2071
- cyan: "\x1B[36m",
2072
- white: "\x1B[37m",
2073
- gray: "\x1B[90m"
2074
- };
2075
- var levelColorMap = {
2076
- error: colors.red,
2077
- warn: colors.yellow,
2078
- info: colors.cyan,
2079
- debug: colors.gray
2080
- };
2081
- function getLevelColor(level) {
2082
- return levelColorMap[level] ?? colors.white;
2083
- }
2084
- var cssColors = {
2085
- dim: "color: #6b7280",
2086
- red: "color: #ef4444; font-weight: bold",
2087
- green: "color: #22c55e",
2088
- yellow: "color: #f59e0b; font-weight: bold",
2089
- cyan: "color: #06b6d4; font-weight: bold",
2090
- gray: "color: #6b7280; font-weight: bold",
2091
- reset: "color: inherit; font-weight: normal"
2092
- };
2093
- var cssLevelColorMap = {
2094
- error: cssColors.red,
2095
- warn: cssColors.yellow,
2096
- info: cssColors.cyan,
2097
- debug: cssColors.gray
2098
- };
2099
- function getCssLevelColor(level) {
2100
- return cssLevelColorMap[level] ?? cssColors.reset;
2101
- }
2102
- function escapeFormatString(str) {
2103
- return str.replace(/%/g, "%%");
2104
- }
2105
- var patternCache = /* @__PURE__ */ new Map;
2106
- function matchesPattern(path, pattern) {
2107
- let regex = patternCache.get(pattern);
2108
- if (!regex) {
2109
- const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, "[^/]");
2110
- regex = new RegExp(`^${regexPattern}$`);
2111
- patternCache.set(pattern, regex);
2112
- }
2113
- return regex.test(path);
2114
- }
2115
-
2116
- // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/logger-DnobymUQ.mjs
2117
- var DEFAULT_REPLACEMENT = "[REDACTED]";
2118
- var builtinPatterns = {
2119
- creditCard: {
2120
- pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
2121
- mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
2122
- },
2123
- email: {
2124
- pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
2125
- mask: (m) => {
2126
- if (m.indexOf("@") < 1)
2127
- return "***@***";
2128
- const tld = m.slice(m.lastIndexOf("."));
2129
- return `${m[0]}***@***${tld}`;
2130
- }
2131
- },
2132
- ipv4: {
2133
- 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,
2134
- mask: (m) => `***.***.***.${m.split(".").pop()}`
2135
- },
2136
- phone: {
2137
- pattern: /(?:\+\d{1,3}[\s.-]?)?\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}\b/g,
2138
- mask: (m) => {
2139
- const digits = m.replace(/[^\d]/g, "");
2140
- if (m.startsWith("+") && digits.length > 4) {
2141
- const ccMatch = m.match(/^\+\d{1,3}/);
2142
- return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
2143
- }
2144
- if (digits.length > 2)
2145
- return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
2146
- return "***";
2147
- }
2148
- },
2149
- jwt: {
2150
- pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
2151
- mask: () => "eyJ***.***"
2152
- },
2153
- bearer: {
2154
- pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
2155
- mask: () => "Bearer ***"
2156
- },
2157
- iban: {
2158
- 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,
2159
- mask: (m) => {
2160
- const clean = m.replace(/[\s-]/g, "");
2161
- return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
2162
- }
2163
- }
2164
- };
2165
- function resolveRedactConfig(input) {
2166
- if (input === undefined || input === false)
2167
- return;
2168
- if (input === true)
2169
- return { _maskers: allBuiltinMaskers() };
2170
- if (input.builtins === false)
2171
- return input;
2172
- const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
2173
- return {
2174
- ...input,
2175
- _maskers: maskers
2176
- };
2177
- }
2178
- function allBuiltinMaskers() {
2179
- return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
2180
- }
2181
- function cloneRegex(re) {
2182
- return new RegExp(re.source, re.flags);
2183
- }
2184
- function redactEvent(event, config) {
2185
- const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
2186
- if (config.paths?.length)
2187
- for (const path of config.paths)
2188
- redactPath(event, path.split("."), replacement);
2189
- if (config._maskers?.length)
2190
- applyMaskersToTree(event, config._maskers);
2191
- if (config.patterns?.length)
2192
- redactPatterns(event, config.patterns, replacement);
2193
- }
2194
- function redactPath(obj, segments, replacement) {
2195
- let current = obj;
2196
- for (let i = 0;i < segments.length - 1; i++) {
2197
- if (current === null || current === undefined || typeof current !== "object")
2198
- return;
2199
- current = current[segments[i]];
2200
- }
2201
- if (current === null || current === undefined || typeof current !== "object")
2202
- return;
2203
- const leaf = segments[segments.length - 1];
2204
- if (leaf in current)
2205
- current[leaf] = replacement;
2206
- }
2207
- function redactPatterns(obj, patterns, replacement) {
2208
- if (obj === null || obj === undefined)
2209
- return;
2210
- if (Array.isArray(obj)) {
2211
- for (let i = 0;i < obj.length; i++)
2212
- if (typeof obj[i] === "string")
2213
- obj[i] = applyPatterns(obj[i], patterns, replacement);
2214
- else if (typeof obj[i] === "object")
2215
- redactPatterns(obj[i], patterns, replacement);
2216
- return;
2217
- }
2218
- if (typeof obj === "object") {
2219
- const record = obj;
2220
- for (const key in record) {
2221
- const val = record[key];
2222
- if (typeof val === "string")
2223
- record[key] = applyPatterns(val, patterns, replacement);
2224
- else if (typeof val === "object")
2225
- redactPatterns(val, patterns, replacement);
2226
- }
2227
- }
2228
- }
2229
- function applyPatterns(value, patterns, replacement) {
2230
- let result = value;
2231
- for (const pattern of patterns) {
2232
- pattern.lastIndex = 0;
2233
- result = result.replace(pattern, replacement);
2234
- }
2235
- return result;
2236
- }
2237
- function applyMaskersToTree(obj, maskers) {
2238
- if (obj === null || obj === undefined)
2239
- return;
2240
- if (Array.isArray(obj)) {
2241
- for (let i = 0;i < obj.length; i++)
2242
- if (typeof obj[i] === "string")
2243
- obj[i] = applyMaskers(obj[i], maskers);
2244
- else if (typeof obj[i] === "object")
2245
- applyMaskersToTree(obj[i], maskers);
2246
- return;
2247
- }
2248
- if (typeof obj === "object") {
2249
- const record = obj;
2250
- for (const key in record) {
2251
- const val = record[key];
2252
- if (typeof val === "string")
2253
- record[key] = applyMaskers(val, maskers);
2254
- else if (typeof val === "object")
2255
- applyMaskersToTree(val, maskers);
2256
- }
2257
- }
2258
- }
2259
- function applyMaskers(value, maskers) {
2260
- let result = value;
2261
- for (const [pattern, mask] of maskers) {
2262
- pattern.lastIndex = 0;
2263
- result = result.replace(pattern, mask);
2264
- }
2265
- return result;
2266
- }
2267
- function isPlainObject(val) {
2268
- return val !== null && typeof val === "object" && !Array.isArray(val);
2269
- }
2270
- var _tsDate = /* @__PURE__ */ new Date;
2271
- function isoNow() {
2272
- _tsDate.setTime(Date.now());
2273
- return _tsDate.toISOString();
2274
- }
2275
- 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).";
2276
- function warnPostEmit(method, detail) {
2277
- console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
2278
- }
2279
- function mergeInto(target, source) {
2280
- for (const key in source) {
2281
- const sourceVal = source[key];
2282
- if (sourceVal === undefined || sourceVal === null)
2283
- continue;
2284
- const targetVal = target[key];
2285
- if (isPlainObject(sourceVal) && isPlainObject(targetVal))
2286
- mergeInto(targetVal, sourceVal);
2287
- else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
2288
- target[key] = [...targetVal, ...sourceVal];
2289
- else
2290
- target[key] = sourceVal;
2291
- }
2292
- }
2293
- var globalEnv = {
2294
- service: "app",
2295
- environment: "development"
2296
- };
2297
- var globalPretty = isDev();
2298
- var globalSampling = {};
2299
- var globalStringify = true;
2300
- var globalDrain;
2301
- var globalRedact;
2302
- var globalEnabled = true;
2303
- var globalSilent = false;
2304
- var globalMinLevel = "debug";
2305
- function initLogger(config = {}) {
2306
- globalEnabled = config.enabled ?? true;
2307
- const detected = detectEnvironment();
2308
- globalEnv = {
2309
- service: config.env?.service ?? detected.service ?? "app",
2310
- environment: config.env?.environment ?? detected.environment ?? "development",
2311
- version: config.env?.version ?? detected.version,
2312
- commitHash: config.env?.commitHash ?? detected.commitHash,
2313
- region: config.env?.region ?? detected.region
2314
- };
2315
- globalPretty = config.pretty ?? isDev();
2316
- globalSampling = config.sampling ?? {};
2317
- globalStringify = config.stringify ?? true;
2318
- globalDrain = config.drain;
2319
- globalRedact = resolveRedactConfig(config.redact ?? !isDev());
2320
- globalSilent = config.silent ?? false;
2321
- globalMinLevel = config.minLevel ?? "debug";
2322
- if (globalSilent && !globalDrain && !config._suppressDrainWarning)
2323
- 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).");
2324
- }
2325
- function shouldSample(level) {
2326
- const { rates } = globalSampling;
2327
- if (!rates)
2328
- return true;
2329
- const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
2330
- if (percentage <= 0)
2331
- return false;
2332
- if (percentage >= 100)
2333
- return true;
2334
- return Math.random() * 100 < percentage;
2335
- }
2336
- function shouldKeep(ctx) {
2337
- const { keep } = globalSampling;
2338
- if (!keep?.length)
2339
- return false;
2340
- return keep.some((condition) => {
2341
- if (condition.status !== undefined && ctx.status !== undefined && ctx.status >= condition.status)
2342
- return true;
2343
- if (condition.duration !== undefined && ctx.duration !== undefined && ctx.duration >= condition.duration)
2344
- return true;
2345
- if (condition.path && ctx.path && matchesPattern(ctx.path, condition.path))
2346
- return true;
2347
- return false;
2348
- });
2349
- }
2350
- function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
2351
- if (!globalEnabled)
2352
- return null;
2353
- if (!ownsEvent) {
2354
- if (!isLevelEnabled(level, globalMinLevel))
2355
- return null;
2356
- if (!shouldSample(level))
2357
- return null;
2358
- }
2359
- let formatted;
2360
- if (ownsEvent) {
2361
- event.timestamp = isoNow();
2362
- event.level = level;
2363
- if (event.service === undefined)
2364
- event.service = globalEnv.service;
2365
- if (event.environment === undefined)
2366
- event.environment = globalEnv.environment;
2367
- if (globalEnv.version !== undefined && event.version === undefined)
2368
- event.version = globalEnv.version;
2369
- if (globalEnv.commitHash !== undefined && event.commitHash === undefined)
2370
- event.commitHash = globalEnv.commitHash;
2371
- if (globalEnv.region !== undefined && event.region === undefined)
2372
- event.region = globalEnv.region;
2373
- formatted = event;
2374
- } else
2375
- formatted = {
2376
- timestamp: isoNow(),
2377
- level,
2378
- ...globalEnv,
2379
- ...event
2380
- };
2381
- if (globalRedact)
2382
- redactEvent(formatted, globalRedact);
2383
- if (!globalSilent)
2384
- if (globalPretty)
2385
- prettyPrintWideEvent(formatted);
2386
- else if (globalStringify)
2387
- console[getConsoleMethod(level)](JSON.stringify(formatted));
2388
- else
2389
- console[getConsoleMethod(level)](formatted);
2390
- if (globalDrain && !deferDrain)
2391
- Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
2392
- console.error("[evlog] drain failed:", err);
2393
- });
2394
- return formatted;
2395
- }
2396
- function emitTaggedLog(level, tag, message) {
2397
- if (!globalEnabled)
2398
- return;
2399
- if (globalPretty && !globalSilent) {
2400
- if (!isLevelEnabled(level, globalMinLevel))
2401
- return;
2402
- if (!shouldSample(level))
2403
- return;
2404
- if (isClient()) {
2405
- const levelColor = getCssLevelColor(level);
2406
- const timestamp = isoNow().slice(11, 23);
2407
- console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
2408
- } else {
2409
- const color = getLevelColor(level);
2410
- const timestamp = isoNow().slice(11, 23);
2411
- console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
2412
- }
2413
- return;
2414
- }
2415
- emitWideEvent(level, {
2416
- tag,
2417
- message
2418
- });
2419
- }
2420
- function formatValue(value) {
2421
- if (value === null || value === undefined)
2422
- return String(value);
2423
- if (typeof value === "object") {
2424
- const pairs = [];
2425
- for (const [k, v] of Object.entries(value))
2426
- if (v !== undefined && v !== null)
2427
- if (typeof v === "object")
2428
- pairs.push(`${k}=${JSON.stringify(v)}`);
2429
- else
2430
- pairs.push(`${k}=${v}`);
2431
- return pairs.join(" ");
2432
- }
2433
- return String(value);
2434
- }
2435
- function formatCost(cost) {
2436
- if (cost < 0.01)
2437
- return `$${cost.toFixed(6)}`;
2438
- if (cost < 1)
2439
- return `$${cost.toFixed(4)}`;
2440
- return `$${cost.toFixed(2)}`;
2441
- }
2442
- function buildAIEntries(ai) {
2443
- const entries = [];
2444
- const headerParts = [];
2445
- if (ai.model) {
2446
- let m = String(ai.model);
2447
- if (ai.provider)
2448
- m += ` (${ai.provider})`;
2449
- headerParts.push(m);
2450
- }
2451
- if (ai.calls)
2452
- headerParts.push(`${ai.calls} call${ai.calls > 1 ? "s" : ""}`);
2453
- if (ai.steps && ai.steps > 1)
2454
- headerParts.push(`${ai.steps} steps`);
2455
- entries.push({
2456
- key: "ai",
2457
- value: headerParts.join(" \xB7 ")
2458
- });
2459
- const inputTokens = ai.inputTokens;
2460
- const outputTokens = ai.outputTokens;
2461
- const totalTokens = ai.totalTokens;
2462
- if (inputTokens !== undefined && outputTokens !== undefined) {
2463
- let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
2464
- if (totalTokens)
2465
- tokLine += ` (${totalTokens} total)`;
2466
- const extras = [];
2467
- if (ai.cacheReadTokens)
2468
- extras.push(`${ai.cacheReadTokens} cache read`);
2469
- if (ai.cacheWriteTokens)
2470
- extras.push(`${ai.cacheWriteTokens} cache write`);
2471
- if (ai.reasoningTokens)
2472
- extras.push(`${ai.reasoningTokens} reasoning`);
2473
- if (extras.length)
2474
- tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
2475
- entries.push({
2476
- key: "ai.tokens",
2477
- value: tokLine
2478
- });
2479
- }
2480
- const msFirst = ai.msToFirstChunk;
2481
- const msFinish = ai.msToFinish;
2482
- const tps = ai.tokensPerSecond;
2483
- if (msFirst !== undefined || msFinish !== undefined) {
2484
- const parts = [];
2485
- if (msFirst !== undefined)
2486
- parts.push(`${formatDuration(msFirst)} to first chunk`);
2487
- if (msFinish !== undefined)
2488
- parts.push(`${formatDuration(msFinish)} total`);
2489
- let streamLine = parts.join(" \u2192 ");
2490
- if (tps)
2491
- streamLine += ` \xB7 ${tps} tok/s`;
2492
- entries.push({
2493
- key: "ai.streaming",
2494
- value: streamLine
2495
- });
2496
- }
2497
- if (ai.estimatedCost !== undefined)
2498
- entries.push({
2499
- key: "ai.cost",
2500
- value: formatCost(ai.estimatedCost)
2501
- });
2502
- if (ai.totalDurationMs !== undefined)
2503
- entries.push({
2504
- key: "ai.totalDuration",
2505
- value: formatDuration(ai.totalDurationMs)
2506
- });
2507
- const toolCalls = ai.toolCalls;
2508
- const tools = ai.tools;
2509
- const hasInputs = toolCalls?.length ? typeof toolCalls[0] === "object" : false;
2510
- if (tools?.length) {
2511
- const children = tools.map((t, idx) => {
2512
- const mark = t.success ? "\u2713" : "\u2717";
2513
- let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
2514
- if (t.error)
2515
- line += ` ${t.error}`;
2516
- if (hasInputs && toolCalls && idx < toolCalls.length) {
2517
- const tc = toolCalls[idx];
2518
- const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
2519
- const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
2520
- line += ` ${truncated}`;
2521
- }
2522
- return line;
2523
- });
2524
- entries.push({
2525
- key: "ai.tools",
2526
- value: "",
2527
- children
2528
- });
2529
- } else if (toolCalls?.length)
2530
- if (hasInputs) {
2531
- const children = toolCalls.map((tc) => {
2532
- const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
2533
- const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
2534
- return `${tc.name}(${truncated})`;
2535
- });
2536
- entries.push({
2537
- key: "ai.tools",
2538
- value: "",
2539
- children
2540
- });
2541
- } else
2542
- entries.push({
2543
- key: "ai.tools",
2544
- value: toolCalls.join(", ")
2545
- });
2546
- const stepsUsage = ai.stepsUsage;
2547
- if (stepsUsage?.length) {
2548
- const allSameModel = stepsUsage.every((s) => s.model === stepsUsage[0].model);
2549
- const children = stepsUsage.map((s) => {
2550
- let line = `${allSameModel ? "" : `${s.model} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
2551
- const stepTools = s.toolCalls;
2552
- if (stepTools?.length)
2553
- line += ` [${stepTools.join(", ")}]`;
2554
- return line;
2555
- });
2556
- entries.push({
2557
- key: "ai.steps",
2558
- value: "",
2559
- children
2560
- });
2561
- } else if (ai.steps && ai.steps > 1)
2562
- entries.push({
2563
- key: "ai.steps",
2564
- value: String(ai.steps)
2565
- });
2566
- const embedding = ai.embedding;
2567
- if (embedding) {
2568
- const parts = [];
2569
- if (embedding.model)
2570
- parts.push(String(embedding.model));
2571
- parts.push(`${embedding.tokens} tokens`);
2572
- if (embedding.dimensions)
2573
- parts.push(`${embedding.dimensions}d`);
2574
- if (embedding.count)
2575
- parts.push(`${embedding.count} items`);
2576
- entries.push({
2577
- key: "ai.embedding",
2578
- value: parts.join(" \xB7 ")
2579
- });
2580
- }
2581
- if (ai.finishReason)
2582
- entries.push({
2583
- key: "ai.finishReason",
2584
- value: String(ai.finishReason)
2585
- });
2586
- if (ai.error)
2587
- entries.push({
2588
- key: "ai.error",
2589
- value: String(ai.error)
2590
- });
2591
- if (ai.responseId)
2592
- entries.push({
2593
- key: "ai.responseId",
2594
- value: String(ai.responseId)
2595
- });
2596
- return entries;
2597
- }
2598
- function prettyPrintWideEvent(event) {
2599
- const { timestamp, level, service, environment, version, ...rest } = event;
2600
- const ts = timestamp.slice(11, 23);
2601
- const browser = isClient();
2602
- const parts = [];
2603
- const styles = [];
2604
- if (browser) {
2605
- const lc = getCssLevelColor(level);
2606
- parts.push(`%c${ts}%c %c${level.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
2607
- styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
2608
- } else {
2609
- const lc = getLevelColor(level);
2610
- parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${level.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
2611
- }
2612
- if (rest.method && rest.path) {
2613
- parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
2614
- delete rest.method;
2615
- delete rest.path;
2616
- }
2617
- if (rest.status) {
2618
- const sc = browser ? rest.status >= 400 ? cssColors.red : cssColors.green : rest.status >= 400 ? colors.red : colors.green;
2619
- if (browser) {
2620
- parts.push(` %c${rest.status}%c`);
2621
- styles.push(sc, cssColors.reset);
2622
- } else
2623
- parts.push(` ${sc}${rest.status}${colors.reset}`);
2624
- delete rest.status;
2625
- }
2626
- if (rest.duration) {
2627
- if (browser) {
2628
- parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
2629
- styles.push(cssColors.dim, cssColors.reset);
2630
- } else
2631
- parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
2632
- delete rest.duration;
2633
- }
2634
- console.log(parts.join(""), ...styles);
2635
- const aiData = rest.ai;
2636
- if (aiData && typeof aiData === "object")
2637
- delete rest.ai;
2638
- const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
2639
- const aiEntries = aiData ? buildAIEntries(aiData) : [];
2640
- const allEntries = [...restEntries.map(([key, value]) => ({
2641
- key,
2642
- value: formatValue(value)
2643
- })), ...aiEntries];
2644
- for (let i = 0;i < allEntries.length; i++) {
2645
- const entry = allEntries[i];
2646
- const hasChildren = entry.children && entry.children.length > 0;
2647
- const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
2648
- if (browser) {
2649
- const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
2650
- console.log(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
2651
- } else {
2652
- const val = entry.value ? ` ${entry.value}` : "";
2653
- console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
2654
- }
2655
- if (hasChildren) {
2656
- const connector = i === allEntries.length - 1 ? " " : "\u2502";
2657
- for (let j = 0;j < entry.children.length; j++) {
2658
- const child = entry.children[j];
2659
- const childPrefix = j === entry.children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
2660
- if (browser)
2661
- console.log(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
2662
- else
2663
- console.log(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
2664
- }
2665
- }
2666
- }
2667
- }
2668
- function createLogMethod(level) {
2669
- return function logMethod(tagOrEvent, message) {
2670
- if (typeof tagOrEvent === "string" && message !== undefined)
2671
- emitTaggedLog(level, tagOrEvent, message);
2672
- else if (typeof tagOrEvent === "object")
2673
- emitWideEvent(level, tagOrEvent);
2674
- else
2675
- emitTaggedLog(level, "log", String(tagOrEvent));
2676
- };
2677
- }
2678
- var _log = {
2679
- info: createLogMethod("info"),
2680
- error: createLogMethod("error"),
2681
- warn: createLogMethod("warn"),
2682
- debug: createLogMethod("debug")
2683
- };
2684
- var noopLogger = {
2685
- set() {},
2686
- error() {},
2687
- info() {},
2688
- warn() {},
2689
- emit() {
2690
- return null;
2691
- },
2692
- getContext() {
2693
- return {};
2694
- }
2695
- };
2696
- function createLogger(initialContext = {}, internalOptions) {
2697
- if (!globalEnabled)
2698
- return noopLogger;
2699
- const deferDrain = internalOptions?._deferDrain ?? false;
2700
- const startTime = Date.now();
2701
- const context = { ...initialContext };
2702
- let hasError = false;
2703
- let hasWarn = false;
2704
- let emitted = false;
2705
- function addLog(level, message) {
2706
- if (!Array.isArray(context.requestLogs))
2707
- context.requestLogs = [];
2708
- context.requestLogs.push({
2709
- level,
2710
- message,
2711
- timestamp: isoNow()
2712
- });
2713
- }
2714
- return {
2715
- set(data) {
2716
- if (emitted) {
2717
- const keys = Object.keys(data);
2718
- warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
2719
- return;
2720
- }
2721
- mergeInto(context, data);
2722
- },
2723
- error(error, errorContext) {
2724
- if (emitted) {
2725
- warnPostEmit("log.error()", `Keys dropped: ${(errorContext ? [...Object.keys(errorContext), "error"] : ["error"]).join(", ")}.`);
2726
- return;
2727
- }
2728
- hasError = true;
2729
- const err = typeof error === "string" ? new Error(error) : error;
2730
- if (errorContext)
2731
- mergeInto(context, errorContext);
2732
- const errorObj = {
2733
- name: err.name,
2734
- message: err.message,
2735
- stack: err.stack
2736
- };
2737
- const errRecord = err;
2738
- for (const k of [
2739
- "status",
2740
- "statusText",
2741
- "statusCode",
2742
- "statusMessage",
2743
- "data",
2744
- "cause",
2745
- "internal"
2746
- ])
2747
- if (k in err)
2748
- errorObj[k] = errRecord[k];
2749
- if (isPlainObject(context.error))
2750
- mergeInto(context.error, errorObj);
2751
- else
2752
- context.error = errorObj;
2753
- },
2754
- info(message, infoContext) {
2755
- if (emitted) {
2756
- warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2757
- return;
2758
- }
2759
- addLog("info", message);
2760
- if (infoContext) {
2761
- const { requestLogs: _, ...rest } = infoContext;
2762
- mergeInto(context, rest);
2763
- }
2764
- },
2765
- warn(message, warnContext) {
2766
- if (emitted) {
2767
- warnPostEmit("log.warn()", `Keys dropped: ${(warnContext ? ["message", ...Object.keys(warnContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
2768
- return;
2769
- }
2770
- hasWarn = true;
2771
- addLog("warn", message);
2772
- if (warnContext) {
2773
- const { requestLogs: _, ...rest } = warnContext;
2774
- mergeInto(context, rest);
2775
- }
2776
- },
2777
- emit(overrides) {
2778
- if (emitted) {
2779
- warnPostEmit("log.emit()", "Ignoring duplicate emit.");
2780
- return null;
2781
- }
2782
- const durationMs = Date.now() - startTime;
2783
- const level = hasError ? "error" : hasWarn ? "warn" : "info";
2784
- let forceKeep = false;
2785
- if (overrides?._forceKeep)
2786
- forceKeep = true;
2787
- else if (globalSampling.keep?.length)
2788
- forceKeep = shouldKeep({
2789
- status: overrides?.status ?? context.status,
2790
- duration: durationMs,
2791
- path: context.path,
2792
- method: context.method,
2793
- context
2794
- });
2795
- if (!forceKeep && !shouldSample(level)) {
2796
- emitted = true;
2797
- return null;
2798
- }
2799
- if (overrides) {
2800
- const obj = overrides;
2801
- for (const key in obj)
2802
- if (key !== "_forceKeep")
2803
- context[key] = obj[key];
2804
- }
2805
- context.duration = formatDuration(durationMs);
2806
- const wide = emitWideEvent(level, context, deferDrain, true);
2807
- emitted = true;
2808
- return wide;
2809
- },
2810
- getContext() {
2811
- return { ...context };
2812
- }
2813
- };
2814
- }
2815
- if (typeof __EVLOG_CONFIG__ !== "undefined")
2816
- initLogger(__EVLOG_CONFIG__);
2817
- // src/link.tsx
2818
- import {
2819
- createContext,
2820
- createElement,
2821
- useCallback,
2822
- useContext,
2823
- useEffect,
2824
- useRef,
2825
- useState
2826
- } from "react";
2827
- var RouterContext = createContext(null);
2828
-
2829
- // src/render/cache.ts
2830
- import { AsyncLocalStorage } from "async_hooks";
2831
- var MAX_SSG_CACHE_SIZE = 1000;
2832
- var isrCache = new Map;
2833
- var ssgCache = new Map;
2834
- function evictOldest(map, maxSize) {
2835
- if (map.size > maxSize) {
2836
- const oldest = map.keys().next().value;
2837
- if (oldest !== undefined) {
2838
- map.delete(oldest);
2839
- }
2840
- }
2841
- }
2842
- function getSSGCache(key) {
2843
- const entry = ssgCache.get(key);
2844
- if (entry !== undefined) {
2845
- ssgCache.delete(key);
2846
- ssgCache.set(key, entry);
2847
- }
2848
- return entry;
2849
- }
2850
- function setSSGCache(key, entry) {
2851
- ssgCache.delete(key);
2852
- ssgCache.set(key, entry);
2853
- evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
2854
- }
2855
- var _requestInvalidationScope = new AsyncLocalStorage;
2856
- var _globalPendingInvalidations = new Set;
2857
-
2858
- // src/render/element.tsx
2859
- import { jsxDEV } from "react/jsx-dev-runtime";
2860
- function buildElement(route, data, rootLayout) {
2861
- const Component = route.page.component;
2862
- let element = /* @__PURE__ */ jsxDEV(Component, {
2863
- ...data
2864
- }, undefined, false, undefined, this);
2865
- for (let i = route.routeChain.length - 1;i >= 1; i--) {
2866
- const routeEntry = route.routeChain[i];
2867
- if (routeEntry?.layout) {
2868
- const Layout = routeEntry.layout;
2869
- element = /* @__PURE__ */ jsxDEV(Layout, {
2870
- ...data,
2871
- children: element
2872
- }, undefined, false, undefined, this);
2873
- }
2874
- }
2875
- if (rootLayout.layout) {
2876
- const RootLayoutComponent = rootLayout.layout;
2877
- element = /* @__PURE__ */ jsxDEV(RootLayoutComponent, {
2878
- ...data,
2879
- children: element
2880
- }, undefined, false, undefined, this);
2881
- }
2882
- return element;
2883
- }
2884
-
2885
- // src/context-logger.ts
2886
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
2887
-
2888
- // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
2889
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
2890
- import { Elysia } from "elysia";
2891
- var storage = new AsyncLocalStorage2;
2892
- var activeLoggers = /* @__PURE__ */ new WeakSet;
2893
- function useLogger2() {
2894
- const logger = storage.getStore();
2895
- if (!logger || !activeLoggers.has(logger))
2896
- throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
2897
- return logger;
2898
- }
2899
-
2900
- // src/context-logger.ts
2901
- var noopLogger2 = {
2902
- set: () => {},
2903
- error: () => {},
2904
- info: () => {},
2905
- warn: () => {},
2906
- emit: () => null,
2907
- getContext: () => ({}),
2908
- fork: (_label, fn) => fn()
2909
- };
2910
- var syntheticRenderStorage = new AsyncLocalStorage3;
2911
- function useLogger3() {
2912
- try {
2913
- return useLogger2();
2914
- } catch {
2915
- return syntheticRenderStorage.getStore() ?? noopLogger2;
2916
- }
2917
- }
2918
- async function runInSyntheticRenderScope(fn, initialContext) {
2919
- const logger = createLogger(initialContext);
2920
- try {
2921
- const result = await syntheticRenderStorage.run(logger, () => Promise.resolve(fn()));
2922
- logger.emit();
2923
- return result;
2924
- } catch (err) {
2925
- logger.error(err instanceof Error ? err : new Error(String(err)));
2926
- logger.emit();
2927
- throw err;
2928
- }
2929
- }
2930
-
2931
- // src/render/loaders.ts
2932
- function createLoaderCtx(ctx, accumulatedParentPromise) {
2933
- const cache = new Map;
2934
- return new Proxy(ctx, {
2935
- get(target, prop) {
2936
- if (typeof prop !== "string") {
2937
- return Reflect.get(target, prop);
2938
- }
2939
- if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
2940
- return Reflect.get(target, prop);
2941
- }
2942
- if (Object.hasOwn(target, prop)) {
2943
- return target[prop];
2944
- }
2945
- let entry = cache.get(prop);
2946
- if (!entry) {
2947
- entry = accumulatedParentPromise.then((data) => data[prop]);
2948
- cache.set(prop, entry);
2949
- }
2950
- return entry;
2951
- }
2952
- });
2953
- }
2954
- async function runLoaders(route, ctx, _rootLayout) {
2955
- try {
2956
- const ctxRecord = { ...ctx, log: useLogger3() };
2957
- const loaderMap = new Map;
2958
- let accumulatedParentPromise = Promise.resolve({});
2959
- for (const r of route.routeChain) {
2960
- const parentAccum = accumulatedParentPromise;
2961
- if (r.loader) {
2962
- const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
2963
- const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
2964
- loaderMap.set(r, loaderPromise);
2965
- accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
2966
- ...acc,
2967
- ...own
2968
- }));
2969
- accumulatedParentPromise.catch(() => {});
2970
- }
2971
- }
2972
- const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
2973
- const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
2974
- const results = await Promise.all([...loaderMap.values(), pagePromise]);
2975
- const data = Object.assign({}, ...results);
2976
- const headers = {};
2977
- Object.assign(headers, ctx.set.headers);
2978
- return { type: "data", data, headers };
2979
- } catch (err) {
2980
- if (err instanceof Response) {
2981
- return { type: "redirect", response: err };
2982
- }
2983
- throw err;
2984
- }
2985
- }
2986
-
2987
- // src/render/template.ts
2988
- import { readFileSync } from "fs";
2989
- var _prodTemplatePath = null;
2990
- var _prodTemplateContent = null;
2991
- var _devTemplateCache = null;
2992
- var DEV_TEMPLATE_TTL_MS = 1000;
2993
- async function getDevTemplate(origin) {
2994
- if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
2995
- return _devTemplateCache.html;
2996
- }
2997
- const r = await fetch(`${origin}/_bun_hmr_entry`);
2998
- if (!r.ok) {
2999
- throw new Error(`/_bun_hmr_entry returned ${r.status}`);
3000
- }
3001
- const html = await r.text();
3002
- _devTemplateCache = { html, ts: Date.now() };
3003
- return html;
3004
- }
3005
- function setProductionTemplateContent(content) {
3006
- _prodTemplatePath = null;
3007
- _prodTemplateContent = content;
3008
- }
3009
- function getProductionTemplate() {
3010
- if (_prodTemplateContent !== null) {
3011
- return _prodTemplateContent;
3012
- }
3013
- if (!_prodTemplatePath) {
3014
- return null;
3015
- }
3016
- try {
3017
- _prodTemplateContent = readFileSync(_prodTemplatePath, "utf8");
3018
- return _prodTemplateContent;
3019
- } catch {
3020
- return null;
3021
- }
3022
- }
3023
- // src/runtime-env.ts
3024
- var IS_DEV = true;
3025
-
3026
- // src/render/index.ts
3027
- async function prepareRender(route, ctx, root, basePath) {
3028
- const loaderStart = Date.now();
3029
- const loaderResult = await runLoaders(route, ctx, root.route);
3030
- const loader_ms = Date.now() - loaderStart;
3031
- if (loaderResult.type === "redirect") {
3032
- return loaderResult.response;
3033
- }
3034
- const { data, headers } = loaderResult;
3035
- const componentProps = {
3036
- ...data,
3037
- params: ctx.params,
3038
- query: ctx.query,
3039
- path: ctx.path
3040
- };
3041
- const headData = buildHeadInjection(route.page?.head?.(componentProps));
3042
- const prodTemplate = getProductionTemplate();
3043
- const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
3044
- let element = buildElement(route, componentProps, root.route);
3045
- if (basePath !== undefined) {
3046
- const ssrContext = {
3047
- basePath,
3048
- currentHref: ctx.path,
3049
- navigate: () => Promise.resolve(),
3050
- prefetch: () => {},
3051
- invalidatePrefetch: () => {},
3052
- refresh: () => Promise.resolve(),
3053
- isNavigating: false,
3054
- defaultPreload: "intent",
3055
- defaultPreloadDelay: 50,
3056
- defaultPreloadStaleTime: 30000
3057
- };
3058
- element = createElement2(RouterContext.Provider, { value: ssrContext }, element);
3059
- }
3060
- return { componentProps, element, headData, headers, loader_ms, template };
3061
- }
3062
- async function renderForPath(route, params, root, origin, basePath) {
3063
- const resolvedPath = resolvePath(route.pattern, params);
3064
- const ctx = {
3065
- params,
3066
- query: {},
3067
- request: new Request(`${origin}${resolvedPath}`),
3068
- headers: {},
3069
- cookie: {},
3070
- redirect: (url, status = 302) => new Response(null, { status, headers: { Location: url } }),
3071
- set: { headers: {} },
3072
- path: resolvedPath
3073
- };
3074
- const prepared = await runInSyntheticRenderScope(() => prepareRender(route, ctx, root, basePath), { route: route.pattern });
3075
- if (prepared instanceof Response) {
3076
- throw prepared;
3077
- }
3078
- const { componentProps, element, headData, headers, template } = prepared;
3079
- const stream = await renderToReadableStream(element);
3080
- await stream.allReady;
3081
- const reactHtml = await streamToString(stream);
3082
- return {
3083
- html: assembleHTML(template, headData, reactHtml, componentProps),
3084
- headers
3085
- };
3086
- }
3087
- async function prerenderSSG(route, params, root, origin = "http://localhost:3000", basePath) {
3088
- const resolvedPath = resolvePath(route.pattern, params);
3089
- const cached = getSSGCache(resolvedPath);
3090
- if (cached && !IS_DEV) {
3091
- return cached;
3092
- }
3093
- let result;
3094
- try {
3095
- result = await renderForPath(route, params, root, origin, basePath);
3096
- } catch (err) {
3097
- if (err instanceof Response) {
3098
- return err;
3099
- }
3100
- throw err;
3101
- }
3102
- const entry = { html: result.html, cachedAt: Date.now() };
3103
- if (!IS_DEV) {
3104
- setSSGCache(resolvedPath, entry);
3105
- }
3106
- return entry;
3107
- }
3108
- var pendingRevalidations = new Set;
3109
-
3110
- // src/adapter/static.ts
3111
- var STATIC_CONCURRENCY = 4;
3112
- var DYNAMIC_SEGMENT_RE = /\/:[^/]+|\/\*/;
3113
- var TRAILING_SLASHES_RE = /\/+$/;
3114
- function pathToOutputFile(urlPath, outDir) {
3115
- const normalizedOutDir = resolve2(outDir);
3116
- if (urlPath === "/" || urlPath === "") {
3117
- return join6(normalizedOutDir, "index.html");
3118
- }
3119
- const resolved = resolve2(normalizedOutDir, urlPath.slice(1), "index.html");
3120
- if (!resolved.startsWith(`${normalizedOutDir}${sep}`)) {
3121
- throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
3122
- }
3123
- return resolved;
3124
- }
3125
- async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath) {
3126
- const urlPath = resolvePath(route.pattern, params);
3127
- const outputFile = pathToOutputFile(urlPath, outDir);
3128
- try {
3129
- const entry = await prerenderSSG(route, params, root, "http://localhost", basePath);
3130
- if (entry instanceof Response) {
3131
- console.warn(`[furin] static: route "${route.pattern}" loader returned a redirect \u2014 skipping.`);
3132
- return;
3133
- }
3134
- ensureDir(dirname3(outputFile));
3135
- writeFileSync5(outputFile, entry.html);
3136
- renderedRoutes.push(urlPath);
3137
- console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(outputFile)}`);
3138
- } catch (err) {
3139
- console.error(`[furin] static: prerender failed for "${route.pattern}" (params: ${JSON.stringify(params)}):`, err);
3140
- skippedRoutes.push(urlPath);
3141
- }
3142
- }
3143
- function collectSsgRoutes(routes, onSSR, skippedRoutes) {
3144
- const nonSsg = routes.filter((r) => r.mode !== "ssg");
3145
- if (nonSsg.length === 0) {
3146
- return routes;
3147
- }
3148
- if (onSSR === "error") {
3149
- const list = nonSsg.map((r) => ` \u2022 ${r.pattern} (mode: ${r.mode})`).join(`
3150
- `);
3151
- throw new Error(`[furin] Cannot produce a static export: the following routes are not SSG and cannot be pre-rendered.
3152
- ` + `Either change their mode to "ssg", remove them, or set \`onSSR: "skip"\` in your static config.
3153
-
3154
- ` + `${list}`);
3155
- }
3156
- for (const r of nonSsg) {
3157
- console.warn(`[furin] static: skipping route "${r.pattern}" (mode=${r.mode}) \u2014 not statically exportable.`);
3158
- skippedRoutes.push(r.pattern);
3159
- }
3160
- return routes.filter((r) => r.mode === "ssg");
3161
- }
3162
- async function buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath) {
3163
- const tasks = [];
3164
- for (const route of ssgRoutes) {
3165
- if (!DYNAMIC_SEGMENT_RE.test(route.pattern)) {
3166
- tasks.push(() => prerenderAndWrite(route, {}, root, outDir, renderedRoutes, skippedRoutes, basePath));
3167
- continue;
3168
- }
3169
- if (!route.page.staticParams) {
3170
- console.warn(`[furin] static: skipping dynamic route "${route.pattern}" \u2014 no staticParams() defined.`);
3171
- skippedRoutes.push(route.pattern);
3172
- continue;
3173
- }
3174
- try {
3175
- const paramSets = await route.page.staticParams() ?? [];
3176
- for (const params of paramSets) {
3177
- tasks.push(() => prerenderAndWrite(route, params, root, outDir, renderedRoutes, skippedRoutes, basePath));
3178
- }
3179
- } catch (err) {
3180
- console.error(`[furin] static: staticParams() failed for "${route.pattern}":`, err);
3181
- skippedRoutes.push(route.pattern);
3182
- }
3183
- }
3184
- return tasks;
3185
- }
3186
- async function runWithConcurrency(tasks, concurrency) {
3187
- const queue = [...tasks];
3188
- const workerCount = Math.min(concurrency, Math.max(queue.length, 1));
3189
- await Promise.all(Array.from({ length: workerCount }, async () => {
3190
- while (queue.length > 0) {
3191
- await queue.shift()?.();
3192
- }
3193
- }));
3194
- }
3195
- async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
3196
- const staticConfig = options.staticConfig ?? {};
3197
- const rawBasePath = staticConfig.basePath ?? "";
3198
- let basePath;
3199
- if (rawBasePath === "/" || rawBasePath === "") {
3200
- basePath = "";
3201
- } else if (rawBasePath.endsWith("/")) {
3202
- basePath = rawBasePath.replace(TRAILING_SLASHES_RE, "");
3203
- } else {
3204
- basePath = rawBasePath;
3205
- }
3206
- if (basePath && !basePath.startsWith("/")) {
3207
- throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
3208
- }
3209
- const outDir = resolve2(rootDir, staticConfig.outDir ?? "dist");
3210
- const normalizedRoot = resolve2(rootDir);
3211
- const normalizedBuildRoot = resolve2(buildRoot);
3212
- if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === "/" || outDir === ".") {
3213
- throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
3214
- }
3215
- function isOutsideOutDir(target) {
3216
- const rel = relative3(outDir, target);
3217
- return rel.startsWith("..") || isAbsolute(rel);
3218
- }
3219
- if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
3220
- throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
3221
- }
3222
- const onSSR = staticConfig.onSSR ?? "error";
3223
- const publicPath = basePath ? `${basePath}/_client/` : "/_client/";
3224
- const renderedRoutes = [];
3225
- const skippedRoutes = [];
3226
- const ssgRoutes = collectSsgRoutes(routes, onSSR, skippedRoutes);
3227
- rmSync3(outDir, { force: true, recursive: true });
3228
- ensureDir(outDir);
3229
- const targetDir = join6(buildRoot, "static");
3230
- rmSync3(targetDir, { force: true, recursive: true });
3231
- ensureDir(targetDir);
3232
- const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
3233
- outDir: targetDir,
3234
- rootLayout: root.path,
3235
- plugins: options.plugins,
3236
- publicPath,
3237
- basePath
3238
- });
3239
- const publicFavicon = join6(rootDir, "public", "favicon.ico");
3240
- const faviconHref = existsSync5(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
3241
- const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref);
3242
- setProductionTemplateContent(shellHtml);
3243
- const publicSrcDir = join6(rootDir, "public");
3244
- if (existsSync5(publicSrcDir)) {
3245
- cpSync2(publicSrcDir, outDir, { recursive: true });
3246
- }
3247
- const clientSrcDir = join6(targetDir, "client");
3248
- if (existsSync5(clientSrcDir)) {
3249
- cpSync2(clientSrcDir, join6(outDir, "_client"), { recursive: true });
3250
- }
3251
- const tasks = await buildTaskQueue(ssgRoutes, root, outDir, renderedRoutes, skippedRoutes, basePath);
3252
- const afterQueueCount = skippedRoutes.length;
3253
- await runWithConcurrency(tasks, STATIC_CONCURRENCY);
3254
- if (onSSR === "error" && skippedRoutes.length > afterQueueCount) {
3255
- const failed = skippedRoutes.slice(afterQueueCount);
3256
- const list = failed.map((r) => ` \u2022 ${r}`).join(`
3257
- `);
3258
- throw new Error(`[furin] static: ${failed.length} route(s) failed to pre-render:
3259
- ${list}
3260
- ` + `Set \`onSSR: "skip"\` in your static config to suppress this error.`);
3261
- }
3262
- writeFileSync5(join6(outDir, "404.html"), shellHtml);
3263
- console.log("[furin] static: wrote 404.html (SPA shell fallback)");
3264
- rmSync3(targetDir, { force: true, recursive: true });
3265
- console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
3266
- return {
3267
- basePath,
3268
- generatedAt: new Date().toISOString(),
3269
- outDir: toPosixPath(outDir),
3270
- renderedRoutes,
3271
- skippedRoutes
3272
- };
3273
- }
3274
-
3275
- // src/config.ts
3276
- import { t } from "elysia";
3277
- var BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"];
3278
- var buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
3279
- var compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
3280
- var configSchema = t.Object({
3281
- rootDir: t.Optional(t.String()),
3282
- pagesDir: t.Optional(t.String()),
3283
- serverEntry: t.Optional(t.String()),
3284
- targets: t.Optional(t.Array(buildTargetSchema)),
3285
- bun: t.Optional(t.Object({
3286
- compile: t.Optional(compileTargetSchema)
3287
- })),
3288
- static: t.Optional(t.Object({
3289
- basePath: t.Optional(t.String()),
3290
- outDir: t.Optional(t.String()),
3291
- onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")]))
3292
- }))
3293
- });
3294
-
3295
- // src/router.ts
3296
- import { existsSync as existsSync6 } from "fs";
3297
- import { readdir } from "fs/promises";
3298
- import { join as join7, parse } from "path";
3299
- import { Elysia as Elysia2, t as t2 } from "elysia";
3300
-
3301
- // src/internal.ts
3302
- var _compileCtx = null;
3303
- function getCompileContext() {
3304
- return _compileCtx;
3305
- }
3306
-
3307
- // src/utils.ts
3308
- function isFurinPage(value) {
3309
- return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
3310
- }
3311
- function isFurinRoute(value) {
3312
- return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
3313
- }
3314
- function collectRouteChainFromRoute(route) {
3315
- const chain = [];
3316
- let current = route;
3317
- while (current) {
3318
- chain.unshift(current);
3319
- current = current.parent;
3320
- }
3321
- return chain;
3322
- }
3323
- function hasCycle(route) {
3324
- const visited = new Set;
3325
- let current = route;
3326
- while (current) {
3327
- if (visited.has(current)) {
3328
- return true;
3329
- }
3330
- visited.add(current);
3331
- current = current.parent;
3332
- }
3333
- return false;
3334
- }
3335
- function validateRouteChain(chain, root, pagePath) {
3336
- const hasRoot = chain.some((r) => r === root);
3337
- if (!hasRoot) {
3338
- const location = pagePath ? `in ${pagePath}` : "";
3339
- throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
3340
- }
3341
- for (const route of chain) {
3342
- if (hasCycle(route)) {
3343
- throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
3344
- }
3345
- }
3346
- }
3347
-
3348
- // src/router.ts
3349
- async function scanPages(pagesDir) {
3350
- const root = await scanRootLayout(pagesDir);
3351
- const routes = await scanPageFiles(pagesDir, root);
3352
- return { root, routes };
3353
- }
3354
- async function scanRootLayout(pagesDir) {
3355
- const rootPath = `${pagesDir}/root.tsx`;
3356
- const ctx = getCompileContext();
3357
- if (!(existsSync6(rootPath) || ctx?.modules[rootPath])) {
3358
- throw new Error("[furin] root.tsx: not found.");
3359
- }
3360
- const mod = ctx?.modules[rootPath] ?? await import(rootPath);
3361
- const rootExport = mod.route ?? mod.default;
3362
- if (!(rootExport && isFurinRoute(rootExport))) {
3363
- throw new Error("[furin] root.tsx: createRoute() export not found.");
3364
- }
3365
- if (!rootExport.layout) {
3366
- throw new Error("[furin] root.tsx: createRoute() has no layout.");
3367
- }
3368
- return { path: rootPath, route: rootExport };
3369
- }
3370
- async function scanPageFiles(pagesDir, root) {
3371
- const routes = [];
3372
- for (const absolutePath of await collectPageFilePaths(pagesDir)) {
3373
- if (![".tsx", ".ts", ".jsx", ".js"].some((ext) => absolutePath.endsWith(ext))) {
3374
- continue;
3375
- }
3376
- const relativePath = absolutePath.replace(`${pagesDir}/`, "");
3377
- const fileName = parse(relativePath).name;
3378
- if (fileName.startsWith("_") || fileName === "root") {
3379
- continue;
3380
- }
3381
- if (IS_DEV) {
3382
- routes.push(await buildDevRoute(absolutePath, relativePath, root));
3383
- continue;
3384
- }
3385
- const ctx = getCompileContext();
3386
- const pageMod = ctx?.modules[absolutePath] ?? await import(absolutePath);
3387
- const page = pageMod.default;
3388
- if (!isFurinPage(page)) {
3389
- throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
3390
- }
3391
- const routeChain = collectRouteChainFromRoute(page._route);
3392
- validateRouteChain(routeChain, root.route, relativePath);
3393
- routes.push({
3394
- pattern: filePathToPattern(relativePath),
3395
- page,
3396
- path: absolutePath,
3397
- routeChain,
3398
- mode: resolveMode(page, routeChain)
3399
- });
3400
- }
3401
- return routes;
3402
- }
3403
- async function buildDevRoute(absolutePath, relativePath, root) {
3404
- let page;
3405
- let routeChain = [];
3406
- try {
3407
- const pageMod = await import(`${absolutePath}?furin-server&t=${Date.now()}`);
3408
- if (isFurinPage(pageMod.default)) {
3409
- page = pageMod.default;
3410
- routeChain = collectRouteChainFromRoute(page._route);
3411
- validateRouteChain(routeChain, root.route, relativePath);
3412
- }
3413
- } catch {}
3414
- const devStubPage = {
3415
- __type: "FURIN_PAGE",
3416
- _route: { __type: "FURIN_ROUTE" },
3417
- component: () => null
3418
- };
3419
- return {
3420
- pattern: filePathToPattern(relativePath),
3421
- path: absolutePath,
3422
- mode: page ? resolveMode(page, routeChain) : "ssr",
3423
- page: page ?? devStubPage,
3424
- routeChain
3425
- };
3426
- }
3427
- var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
3428
- async function collectPageFilePaths(dir) {
3429
- const files = [];
3430
- for (const entry of await readdir(dir, { withFileTypes: true })) {
3431
- const absolutePath = join7(dir, entry.name);
3432
- if (entry.isDirectory()) {
3433
- files.push(...await collectPageFilePaths(absolutePath));
3434
- continue;
3435
- }
3436
- if (entry.isFile()) {
3437
- files.push(absolutePath);
3438
- }
3439
- }
3440
- return files;
3441
- }
3442
- function resolveMode(page, routeChain) {
3443
- const routeConfig = page._route;
3444
- if (routeConfig.mode) {
3445
- return routeConfig.mode;
3446
- }
3447
- const hasLoader = routeChain.some((r) => r.loader) || !!page.loader;
3448
- if (!hasLoader) {
3449
- return "ssg";
3450
- }
3451
- if (routeConfig.revalidate && routeConfig.revalidate > 0) {
3452
- return "isr";
3453
- }
3454
- return "ssr";
3455
- }
3456
- function filePathToPattern(path) {
3457
- const parts = path.replaceAll("\\", "/").split("/");
3458
- const segments = [];
3459
- for (const part of parts) {
3460
- const name = parse(part).name;
3461
- if (name === "index") {
3462
- continue;
3463
- }
3464
- if (name.startsWith("[") && name.endsWith("]")) {
3465
- const inner = name.slice(1, -1);
3466
- if (inner.startsWith("...")) {
3467
- segments.push("*");
3468
- continue;
3469
- }
3470
- segments.push(`:${inner}`);
3471
- continue;
3472
- }
3473
- segments.push(name);
3474
- }
3475
- return `/${segments.join("/")}`;
3476
- }
3477
-
3478
- // src/build/scan-server.ts
3479
- import { readFileSync as readFileSync2 } from "fs";
3480
- import { parseSync as parseSync2 } from "oxc-parser";
3481
- function scanFurinInstances(serverEntryPath) {
3482
- const code = readFileSync2(serverEntryPath, "utf8");
3483
- const { program, errors } = parseSync2(serverEntryPath, code);
3484
- if (errors.length > 0) {
3485
- return [];
3486
- }
3487
- const results = [];
3488
- walkNode(program, results);
3489
- return results;
3490
- }
3491
- var SKIP_KEYS = new Set(["type", "start", "end"]);
3492
- function checkFurinCall(node, out) {
3493
- const callee = node.callee;
3494
- const args = node.arguments;
3495
- const isFurinCall = callee?.type === "Identifier" && callee.name === "furin";
3496
- if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
3497
- return;
3498
- }
3499
- const firstArg = args[0];
3500
- if (firstArg?.type !== "ObjectExpression") {
3501
- return;
3502
- }
3503
- const pagesDir = extractStringProperty(firstArg, "pagesDir");
3504
- if (pagesDir !== null) {
3505
- out.push(pagesDir);
3506
- }
3507
- }
3508
- function walkChildren(node, out) {
3509
- for (const key of Object.keys(node)) {
3510
- if (SKIP_KEYS.has(key)) {
3511
- continue;
3512
- }
3513
- const child = node[key];
3514
- if (Array.isArray(child)) {
3515
- for (const item of child) {
3516
- if (item && typeof item === "object") {
3517
- walkNode(item, out);
3518
- }
3519
- }
3520
- } else if (child && typeof child === "object") {
3521
- walkNode(child, out);
3522
- }
3523
- }
3524
- }
3525
- function walkNode(node, out) {
3526
- if (!node || typeof node !== "object") {
3527
- return;
3528
- }
3529
- if (node.type === "CallExpression") {
3530
- checkFurinCall(node, out);
3531
- }
3532
- walkChildren(node, out);
3533
- }
3534
- function extractStringProperty(obj, propName) {
3535
- const properties = obj.properties;
3536
- if (!Array.isArray(properties)) {
3537
- return null;
3538
- }
3539
- for (const prop of properties) {
3540
- if (prop.type !== "Property") {
3541
- continue;
3542
- }
3543
- const key = prop.key;
3544
- const value = prop.value;
3545
- const keyMatches = key.type === "Identifier" && key.name === propName || key.type === "Literal" && key.value === propName;
3546
- if (!keyMatches) {
3547
- continue;
3548
- }
3549
- if (value?.type === "Literal" && typeof value.value === "string") {
3550
- return value.value;
3551
- }
3552
- return null;
3553
- }
3554
- return null;
3555
- }
3556
-
3557
- // src/build/index.ts
3558
- var IMPLEMENTED_TARGETS = ["bun", "static"];
3559
- var BUILD_OUTPUT_DIR = ".furin/build";
3560
- function resolvePagesDirFromServer(serverEntry, rootDir) {
3561
- if (!serverEntry) {
3562
- return null;
3563
- }
3564
- const detected = scanFurinInstances(serverEntry);
3565
- if (detected.length === 0) {
3566
- return null;
3567
- }
3568
- return resolve3(rootDir, detected[0]);
3569
- }
3570
- async function buildApp(options) {
3571
- const rootDir = resolve3(options.rootDir ?? process.cwd());
3572
- const buildRoot = join8(rootDir, BUILD_OUTPUT_DIR);
3573
- const serverEntry = (() => {
3574
- if (options.target === "static") {
3575
- return null;
3576
- }
3577
- if (options.serverEntry) {
3578
- const resolved = resolve3(rootDir, options.serverEntry);
3579
- if (existsSync7(resolved)) {
3580
- return resolved;
3581
- }
3582
- }
3583
- const entry = resolve3(rootDir, "src/server.ts");
3584
- if (!existsSync7(entry)) {
3585
- throw new Error("[furin] Entrypoint server.ts not found");
3586
- }
3587
- return entry;
3588
- })();
3589
- for (const plugin of options.plugins ?? []) {
3590
- try {
3591
- Bun.plugin(plugin);
3592
- } catch (err) {
3593
- console.debug("[furin] Skipped build-only plugin at runtime:", err);
3594
- }
3595
- }
3596
- const rawPagesDir = options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
3597
- const pagesDir = resolve3(rootDir, rawPagesDir);
3598
- const requestedTargets = options.target === "all" ? [...IMPLEMENTED_TARGETS] : [options.target].map((target) => {
3599
- if (!BUILD_TARGETS.includes(target)) {
3600
- throw new Error(`[furin] Unsupported build target "${target}"`);
3601
- }
3602
- return target;
3603
- });
3604
- const { root, routes } = await scanPages(pagesDir);
3605
- ensureDir(buildRoot);
3606
- const manifest = {
3607
- version: 1,
3608
- generatedAt: new Date().toISOString(),
3609
- rootDir: toPosixPath(rootDir),
3610
- pagesDir: toPosixPath(relative4(rootDir, pagesDir)),
3611
- rootPath: toPosixPath(relative4(rootDir, root.path)),
3612
- serverEntry: serverEntry ? toPosixPath(relative4(rootDir, serverEntry)) : null,
3613
- routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
3614
- targets: {}
3615
- };
3616
- for (const target of requestedTargets) {
3617
- switch (target) {
3618
- case "bun":
3619
- manifest.targets.bun = await buildBunTarget(routes, rootDir, buildRoot, root.path, serverEntry, options);
3620
- break;
3621
- case "static":
3622
- manifest.targets.static = await buildStaticTarget(routes, rootDir, buildRoot, root, options);
3623
- break;
3624
- case "node":
3625
- case "vercel":
3626
- case "cloudflare":
3627
- throw new Error(`[furin] \`--target ${target}\` is planned but not implemented yet in this branch.`);
3628
- default:
3629
- throw new Error(`[furin] Unsupported build target "${target}"`);
3630
- }
3631
- }
3632
- writeFileSync6(join8(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
3633
- `);
3634
- return {
3635
- manifest,
3636
- targets: manifest.targets
3637
- };
3638
- }
3639
-
3640
- // src/cli/config.ts
3641
- import { existsSync as existsSync8 } from "fs";
3642
- import { resolve as resolve4 } from "path";
3643
- import { pathToFileURL } from "url";
3644
- import { TypeCompiler } from "elysia/type-system";
3645
- var compiledConfigSchema = TypeCompiler.Compile(configSchema);
3646
- var DEFAULT_CONFIG_FILENAMES = [
3647
- "furin.config.ts",
3648
- "furin.config.js",
3649
- "furin.config.mjs"
3650
- ];
3651
- async function loadCliConfig(cwd, explicitConfigPath) {
3652
- const rootDir = resolve4(cwd);
3653
- const configPath = explicitConfigPath ? resolve4(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve4(rootDir, filename)).find((path) => existsSync8(path));
3654
- if (!configPath) {
3655
- return {
3656
- configPath: null,
3657
- rootDir,
3658
- pagesDir: resolve4(rootDir, "src/pages")
3659
- };
3660
- }
3661
- const imported = await import(pathToFileURL(configPath).href);
3662
- const rawConfig = imported.default ?? imported;
3663
- const { plugins, ...configToValidate } = rawConfig;
3664
- if (plugins !== undefined && !Array.isArray(plugins)) {
3665
- throw new Error(`[furin] Invalid config at ${configPath}: "plugins" must be an array of BunPlugin objects`);
3666
- }
3667
- if (!compiledConfigSchema.Check(configToValidate)) {
3668
- const [firstError] = compiledConfigSchema.Errors(configToValidate);
3669
- throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.path ?? "/"})`);
3670
- }
3671
- const resolvedRootDir = resolve4(rootDir, configToValidate.rootDir ?? ".");
3672
- return {
3673
- ...configToValidate,
3674
- plugins,
3675
- configPath,
3676
- rootDir: resolvedRootDir,
3677
- pagesDir: resolve4(resolvedRootDir, configToValidate.pagesDir ?? "src/pages")
3678
- };
3679
- }
3680
-
3681
- // src/cli/index.ts
3682
- var argv = process.argv.slice(2);
3683
- var command = argv[0];
3684
- function log(msg) {
3685
- console.log(`\x1B[32m\u25C6\x1B[0m ${msg}`);
3686
- }
3687
- function bail(msg) {
3688
- console.error(`\x1B[31m\u2717\x1B[0m ${msg}`);
3689
- process.exit(1);
3690
- }
3691
- function resolveCompileMode(flag, configCompile) {
3692
- if (flag === "embed") {
3693
- return "embed";
3694
- }
3695
- if (flag === true || flag === "server") {
3696
- return "server";
3697
- }
3698
- if (flag !== undefined && flag !== false) {
3699
- bail(`Invalid compile mode "${flag}". Valid: --compile server or --compile embed`);
3700
- }
3701
- return configCompile;
3702
- }
3703
- if (command === "build") {
3704
- const { values: rawValues } = parseArgs({
3705
- args: argv.slice(1),
3706
- options: {
3707
- target: { type: "string" },
3708
- pagesDir: { type: "string" },
3709
- config: { type: "string" }
3710
- },
3711
- strict: false
3712
- });
3713
- const values = rawValues;
3714
- const buildArgv = argv.slice(1);
3715
- const compileIdx = buildArgv.indexOf("--compile");
3716
- let compileFlag;
3717
- if (compileIdx < 0) {
3718
- compileFlag = undefined;
3719
- } else {
3720
- const next = buildArgv[compileIdx + 1];
3721
- compileFlag = next && !next.startsWith("-") ? next : true;
3722
- }
3723
- const target = values.target ?? "bun";
3724
- if (target !== "all" && !BUILD_TARGETS.includes(target)) {
3725
- bail(`Unsupported build target "${target}". Valid: ${BUILD_TARGETS.join(", ")}, all`);
3726
- }
3727
- const config = await loadCliConfig(process.cwd(), values.config);
3728
- const isStaticTarget = target === "static";
3729
- const resolvedServerEntry = isStaticTarget ? undefined : (() => {
3730
- const entry = resolve5(config.rootDir, config.serverEntry ?? "src/server.ts");
3731
- if (!existsSync9(entry)) {
3732
- const expected = config.serverEntry ?? "src/server.ts";
3733
- throw new Error(`[furin] Entrypoint ${expected} not found`);
3734
- }
3735
- return entry;
3736
- })();
3737
- log(`Building Furin for ${target}\u2026`);
3738
- const result = await buildApp({
3739
- target,
3740
- compile: resolveCompileMode(compileFlag, config.bun?.compile),
3741
- rootDir: config.rootDir,
3742
- pagesDir: values.pagesDir ?? config.pagesDir,
3743
- serverEntry: resolvedServerEntry,
3744
- plugins: config.plugins,
3745
- staticConfig: config.static
3746
- });
3747
- const built = Object.keys(result.targets).join(", ") || "none";
3748
- log(`Done: ${built} \u2192 .furin/build`);
3749
- } else if (!command || command === "help") {
3750
- console.log(`Furin CLI
3751
-
3752
- USAGE furin build [options]
3753
-
3754
- OPTIONS
3755
- --target ${BUILD_TARGETS.join(" | ")} | all (default: bun)
3756
- --pagesDir Pages directory
3757
- --config Config file path
3758
- --compile server | embed Compile to binary: "server" keeps client on disk, "embed" is self-contained
3759
- `);
3760
- } else {
3761
- bail(`Unknown command "${command}". Run "furin help" for usage.`);
3762
- }