@teyik0/furin 0.1.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist/adapter/bun.d.ts +3 -0
  2. package/dist/adapter/static.d.ts +3 -0
  3. package/dist/build/client.d.ts +25 -0
  4. package/dist/build/compile-entry.d.ts +35 -0
  5. package/dist/build/entry-template.d.ts +26 -0
  6. package/dist/build/hydrate.d.ts +24 -0
  7. package/dist/build/index.d.ts +7 -0
  8. package/dist/build/index.js +4716 -0
  9. package/dist/build/route-types.d.ts +21 -0
  10. package/dist/build/scan-server.d.ts +8 -0
  11. package/dist/build/server-routes-entry.d.ts +35 -0
  12. package/dist/build/shared.d.ts +11 -0
  13. package/dist/build/types.d.ts +76 -0
  14. package/dist/cli/config.d.ts +9 -0
  15. package/dist/cli/index.d.ts +2 -0
  16. package/dist/cli/index.js +4751 -0
  17. package/dist/client.d.ts +195 -0
  18. package/dist/client.js +20 -0
  19. package/dist/config.d.ts +50 -0
  20. package/dist/config.js +28 -0
  21. package/dist/context-logger.d.ts +28 -0
  22. package/dist/dev-page-plugin.d.ts +109 -0
  23. package/dist/error.d.ts +23 -0
  24. package/dist/furin.d.ts +52 -0
  25. package/dist/furin.js +3948 -0
  26. package/dist/internal.d.ts +33 -0
  27. package/dist/link.d.ts +454 -0
  28. package/dist/link.js +1790 -0
  29. package/dist/not-found.d.ts +19 -0
  30. package/dist/plugin/index.d.ts +20 -0
  31. package/dist/plugin/index.js +1408 -0
  32. package/dist/plugin/transform-client.d.ts +9 -0
  33. package/dist/render/assemble.d.ts +15 -0
  34. package/dist/render/boundaries.d.ts +79 -0
  35. package/dist/render/cache.d.ts +96 -0
  36. package/dist/render/default-screens.d.ts +11 -0
  37. package/dist/render/digest.d.ts +16 -0
  38. package/dist/render/element.d.ts +8 -0
  39. package/dist/render/index.d.ts +53 -0
  40. package/dist/render/loaders.d.ts +21 -0
  41. package/dist/render/shell.d.ts +29 -0
  42. package/dist/render/template.d.ts +6 -0
  43. package/dist/router.d.ts +96 -0
  44. package/dist/router.js +2693 -0
  45. package/dist/runtime-env.d.ts +3 -0
  46. package/dist/utils.d.ts +6 -0
  47. package/package.json +77 -0
  48. package/src/adapter/README.md +13 -0
  49. package/src/adapter/bun.ts +239 -0
  50. package/src/adapter/static.ts +341 -0
  51. package/src/build/client.ts +153 -0
  52. package/src/build/compile-entry.ts +129 -0
  53. package/src/build/entry-template.ts +126 -0
  54. package/src/build/hydrate.ts +250 -0
  55. package/src/build/index.ts +151 -0
  56. package/src/build/route-types.ts +89 -0
  57. package/src/build/scan-server.ts +110 -0
  58. package/src/build/server-routes-entry.ts +55 -0
  59. package/src/build/shared.ts +78 -0
  60. package/src/build/types.ts +85 -0
  61. package/src/cli/config.ts +68 -0
  62. package/src/cli/index.ts +115 -0
  63. package/src/client.ts +278 -0
  64. package/src/config.ts +66 -0
  65. package/src/context-logger.ts +74 -0
  66. package/src/dev-page-plugin.ts +434 -0
  67. package/src/env.d.ts +49 -0
  68. package/src/error.ts +32 -0
  69. package/src/furin.ts +383 -0
  70. package/src/internal.ts +51 -0
  71. package/src/link.tsx +1578 -0
  72. package/src/not-found.ts +40 -0
  73. package/src/plugin/index.ts +80 -0
  74. package/src/plugin/transform-client.ts +372 -0
  75. package/src/render/assemble.ts +66 -0
  76. package/src/render/boundaries.tsx +176 -0
  77. package/src/render/cache.ts +251 -0
  78. package/src/render/default-screens.tsx +299 -0
  79. package/src/render/digest.ts +71 -0
  80. package/src/render/element.tsx +119 -0
  81. package/src/render/index.ts +867 -0
  82. package/src/render/loaders.ts +127 -0
  83. package/src/render/shell.ts +187 -0
  84. package/src/render/template.ts +55 -0
  85. package/src/router.ts +779 -0
  86. package/src/runtime-env.ts +6 -0
  87. package/src/utils.ts +68 -0
package/dist/router.js ADDED
@@ -0,0 +1,2693 @@
1
+ // @bun
2
+ // src/router.ts
3
+ import { existsSync } from "fs";
4
+ import { readdir } from "fs/promises";
5
+ import { join, parse } from "path";
6
+ import { Elysia as Elysia2, t } from "elysia";
7
+
8
+ // src/internal.ts
9
+ var _compileCtx = null;
10
+ function getCompileContext() {
11
+ return _compileCtx;
12
+ }
13
+
14
+ // src/render/shell.ts
15
+ function extractTitle(meta) {
16
+ if (!meta) {
17
+ return;
18
+ }
19
+ for (const entry of meta) {
20
+ if ("title" in entry) {
21
+ return entry.title;
22
+ }
23
+ }
24
+ return;
25
+ }
26
+ function isMetaTag(entry) {
27
+ return !(("title" in entry) || ("charSet" in entry) || ("script:ld+json" in entry) || ("tagName" in entry));
28
+ }
29
+ function escapeHtml(str) {
30
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
31
+ }
32
+ function safeJson(value) {
33
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
34
+ }
35
+ function renderAttrs(obj) {
36
+ return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
37
+ }
38
+ function buildMetaParts(meta) {
39
+ const parts = [];
40
+ const title = extractTitle(meta);
41
+ if (title) {
42
+ parts.push(`<title>${escapeHtml(title)}</title>`);
43
+ }
44
+ for (const m of meta) {
45
+ if (isMetaTag(m)) {
46
+ parts.push(`<meta ${renderAttrs(m)} />`);
47
+ }
48
+ if ("script:ld+json" in m) {
49
+ parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
50
+ }
51
+ }
52
+ return parts;
53
+ }
54
+ function buildLinkParts(links) {
55
+ return links.map((link) => `<link ${renderAttrs(link)} />`);
56
+ }
57
+ function buildScriptParts(scripts) {
58
+ return scripts.map((script) => {
59
+ const { children, ...rest } = script;
60
+ const attrs = renderAttrs(rest);
61
+ if (children) {
62
+ return `<script ${attrs}>${children}</script>`;
63
+ }
64
+ return `<script ${attrs}></script>`;
65
+ });
66
+ }
67
+ function buildStyleParts(styles) {
68
+ return styles.map((style) => {
69
+ const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
70
+ return `<style${typeAttr}>${style.children}</style>`;
71
+ });
72
+ }
73
+ function buildHeadInjection(headData) {
74
+ const parts = [];
75
+ if (headData?.meta) {
76
+ parts.push(...buildMetaParts(headData.meta));
77
+ }
78
+ if (headData?.links) {
79
+ parts.push(...buildLinkParts(headData.links));
80
+ }
81
+ if (headData?.scripts) {
82
+ parts.push(...buildScriptParts(headData.scripts));
83
+ }
84
+ if (headData?.styles) {
85
+ parts.push(...buildStyleParts(headData.styles));
86
+ }
87
+ return parts.length > 0 ? `
88
+ ${parts.join(`
89
+ `)}
90
+ ` : "";
91
+ }
92
+ var THEME_INIT_SCRIPT = `<script>try{var __t=localStorage.getItem("furin-theme");` + `document.documentElement.classList.add(__t==="light"?"light":"dark")}` + `catch(e){document.documentElement.classList.add("dark")}</script>`;
93
+ function generateIndexHtml() {
94
+ return `<!DOCTYPE html>
95
+ <html lang="en">
96
+ <head>
97
+ <meta charset="UTF-8">
98
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
99
+ ${THEME_INIT_SCRIPT}
100
+ <!--ssr-head-->
101
+ </head>
102
+ <body>
103
+ <div id="root"><!--ssr-outlet--></div>
104
+ <script type="module" src="./_hydrate.tsx"></script>
105
+ </body>
106
+ </html>
107
+ `;
108
+ }
109
+
110
+ // src/render/assemble.ts
111
+ function resolvePath(pattern, params) {
112
+ let path = pattern;
113
+ for (const [key, val] of Object.entries(params ?? {})) {
114
+ path = path.replace(key === "*" ? "*" : `:${key}`, val);
115
+ }
116
+ return path;
117
+ }
118
+ async function streamToString(stream) {
119
+ const reader = stream.getReader();
120
+ const decoder = new TextDecoder;
121
+ let html = "";
122
+ for (;; ) {
123
+ const { done, value } = await reader.read();
124
+ if (done) {
125
+ break;
126
+ }
127
+ html += decoder.decode(value, { stream: true });
128
+ }
129
+ html += decoder.decode();
130
+ return html;
131
+ }
132
+ function splitTemplate(template) {
133
+ const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
134
+ const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
135
+ return { headPre, bodyPre, bodyPost };
136
+ }
137
+ function assembleHTML(template, headData, reactHtml, data) {
138
+ const { headPre, bodyPre, bodyPost } = splitTemplate(template);
139
+ const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
140
+ let injectedBodyPost = bodyPost;
141
+ if (dataScript) {
142
+ injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${dataScript}</body>`) : bodyPost + dataScript;
143
+ }
144
+ return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
145
+ }
146
+
147
+ // src/render/index.ts
148
+ import { createElement as createElement2 } from "react";
149
+ import { renderToReadableStream } from "react-dom/server";
150
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/utils.mjs
151
+ function formatDuration(ms) {
152
+ if (ms < 1000)
153
+ return `${Math.round(ms)}ms`;
154
+ return `${(ms / 1000).toFixed(2)}s`;
155
+ }
156
+ function isClient() {
157
+ return typeof window !== "undefined";
158
+ }
159
+ function isDev() {
160
+ if (typeof process !== "undefined")
161
+ return true;
162
+ if (typeof window !== "undefined")
163
+ return true;
164
+ return false;
165
+ }
166
+ function detectEnvironment() {
167
+ const env = typeof process !== "undefined" ? process.env : {};
168
+ const defaultEnvironment = isDev() ? "development" : "production";
169
+ return {
170
+ environment: env.NODE_ENV || defaultEnvironment,
171
+ service: env.SERVICE_NAME || "app",
172
+ version: env.APP_VERSION,
173
+ commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
174
+ region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
175
+ };
176
+ }
177
+ var LEVEL_ORDER = {
178
+ debug: 0,
179
+ info: 1,
180
+ warn: 2,
181
+ error: 3
182
+ };
183
+ function isLevelEnabled(level, minLevel) {
184
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
185
+ }
186
+ function getConsoleMethod(level) {
187
+ return level;
188
+ }
189
+ var colors = {
190
+ reset: "\x1B[0m",
191
+ bold: "\x1B[1m",
192
+ dim: "\x1B[2m",
193
+ red: "\x1B[31m",
194
+ green: "\x1B[32m",
195
+ yellow: "\x1B[33m",
196
+ blue: "\x1B[34m",
197
+ magenta: "\x1B[35m",
198
+ cyan: "\x1B[36m",
199
+ white: "\x1B[37m",
200
+ gray: "\x1B[90m"
201
+ };
202
+ var levelColorMap = {
203
+ error: colors.red,
204
+ warn: colors.yellow,
205
+ info: colors.cyan,
206
+ debug: colors.gray
207
+ };
208
+ function getLevelColor(level) {
209
+ return levelColorMap[level] ?? colors.white;
210
+ }
211
+ var cssColors = {
212
+ dim: "color: #6b7280",
213
+ red: "color: #ef4444; font-weight: bold",
214
+ green: "color: #22c55e",
215
+ yellow: "color: #f59e0b; font-weight: bold",
216
+ cyan: "color: #06b6d4; font-weight: bold",
217
+ gray: "color: #6b7280; font-weight: bold",
218
+ reset: "color: inherit; font-weight: normal"
219
+ };
220
+ var cssLevelColorMap = {
221
+ error: cssColors.red,
222
+ warn: cssColors.yellow,
223
+ info: cssColors.cyan,
224
+ debug: cssColors.gray
225
+ };
226
+ function getCssLevelColor(level) {
227
+ return cssLevelColorMap[level] ?? cssColors.reset;
228
+ }
229
+ function escapeFormatString(str) {
230
+ return str.replace(/%/g, "%%");
231
+ }
232
+ var patternCache = /* @__PURE__ */ new Map;
233
+ function matchesPattern(path, pattern) {
234
+ let regex = patternCache.get(pattern);
235
+ if (!regex) {
236
+ const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, "[^/]");
237
+ regex = new RegExp(`^${regexPattern}$`);
238
+ patternCache.set(pattern, regex);
239
+ }
240
+ return regex.test(path);
241
+ }
242
+
243
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/logger-DnobymUQ.mjs
244
+ var DEFAULT_REPLACEMENT = "[REDACTED]";
245
+ var builtinPatterns = {
246
+ creditCard: {
247
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
248
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
249
+ },
250
+ email: {
251
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
252
+ mask: (m) => {
253
+ if (m.indexOf("@") < 1)
254
+ return "***@***";
255
+ const tld = m.slice(m.lastIndexOf("."));
256
+ return `${m[0]}***@***${tld}`;
257
+ }
258
+ },
259
+ ipv4: {
260
+ 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,
261
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
262
+ },
263
+ phone: {
264
+ pattern: /(?:\+\d{1,3}[\s.-]?)?\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}\b/g,
265
+ mask: (m) => {
266
+ const digits = m.replace(/[^\d]/g, "");
267
+ if (m.startsWith("+") && digits.length > 4) {
268
+ const ccMatch = m.match(/^\+\d{1,3}/);
269
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
270
+ }
271
+ if (digits.length > 2)
272
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
273
+ return "***";
274
+ }
275
+ },
276
+ jwt: {
277
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
278
+ mask: () => "eyJ***.***"
279
+ },
280
+ bearer: {
281
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
282
+ mask: () => "Bearer ***"
283
+ },
284
+ iban: {
285
+ 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,
286
+ mask: (m) => {
287
+ const clean = m.replace(/[\s-]/g, "");
288
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
289
+ }
290
+ }
291
+ };
292
+ function resolveRedactConfig(input) {
293
+ if (input === undefined || input === false)
294
+ return;
295
+ if (input === true)
296
+ return { _maskers: allBuiltinMaskers() };
297
+ if (input.builtins === false)
298
+ return input;
299
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
300
+ return {
301
+ ...input,
302
+ _maskers: maskers
303
+ };
304
+ }
305
+ function allBuiltinMaskers() {
306
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
307
+ }
308
+ function cloneRegex(re) {
309
+ return new RegExp(re.source, re.flags);
310
+ }
311
+ function redactEvent(event, config) {
312
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
313
+ if (config.paths?.length)
314
+ for (const path of config.paths)
315
+ redactPath(event, path.split("."), replacement);
316
+ if (config._maskers?.length)
317
+ applyMaskersToTree(event, config._maskers);
318
+ if (config.patterns?.length)
319
+ redactPatterns(event, config.patterns, replacement);
320
+ }
321
+ function redactPath(obj, segments, replacement) {
322
+ let current = obj;
323
+ for (let i = 0;i < segments.length - 1; i++) {
324
+ if (current === null || current === undefined || typeof current !== "object")
325
+ return;
326
+ current = current[segments[i]];
327
+ }
328
+ if (current === null || current === undefined || typeof current !== "object")
329
+ return;
330
+ const leaf = segments[segments.length - 1];
331
+ if (leaf in current)
332
+ current[leaf] = replacement;
333
+ }
334
+ function redactPatterns(obj, patterns, replacement) {
335
+ if (obj === null || obj === undefined)
336
+ return;
337
+ if (Array.isArray(obj)) {
338
+ for (let i = 0;i < obj.length; i++)
339
+ if (typeof obj[i] === "string")
340
+ obj[i] = applyPatterns(obj[i], patterns, replacement);
341
+ else if (typeof obj[i] === "object")
342
+ redactPatterns(obj[i], patterns, replacement);
343
+ return;
344
+ }
345
+ if (typeof obj === "object") {
346
+ const record = obj;
347
+ for (const key in record) {
348
+ const val = record[key];
349
+ if (typeof val === "string")
350
+ record[key] = applyPatterns(val, patterns, replacement);
351
+ else if (typeof val === "object")
352
+ redactPatterns(val, patterns, replacement);
353
+ }
354
+ }
355
+ }
356
+ function applyPatterns(value, patterns, replacement) {
357
+ let result = value;
358
+ for (const pattern of patterns) {
359
+ pattern.lastIndex = 0;
360
+ result = result.replace(pattern, replacement);
361
+ }
362
+ return result;
363
+ }
364
+ function applyMaskersToTree(obj, maskers) {
365
+ if (obj === null || obj === undefined)
366
+ return;
367
+ if (Array.isArray(obj)) {
368
+ for (let i = 0;i < obj.length; i++)
369
+ if (typeof obj[i] === "string")
370
+ obj[i] = applyMaskers(obj[i], maskers);
371
+ else if (typeof obj[i] === "object")
372
+ applyMaskersToTree(obj[i], maskers);
373
+ return;
374
+ }
375
+ if (typeof obj === "object") {
376
+ const record = obj;
377
+ for (const key in record) {
378
+ const val = record[key];
379
+ if (typeof val === "string")
380
+ record[key] = applyMaskers(val, maskers);
381
+ else if (typeof val === "object")
382
+ applyMaskersToTree(val, maskers);
383
+ }
384
+ }
385
+ }
386
+ function applyMaskers(value, maskers) {
387
+ let result = value;
388
+ for (const [pattern, mask] of maskers) {
389
+ pattern.lastIndex = 0;
390
+ result = result.replace(pattern, mask);
391
+ }
392
+ return result;
393
+ }
394
+ function isPlainObject(val) {
395
+ return val !== null && typeof val === "object" && !Array.isArray(val);
396
+ }
397
+ var _tsDate = /* @__PURE__ */ new Date;
398
+ function isoNow() {
399
+ _tsDate.setTime(Date.now());
400
+ return _tsDate.toISOString();
401
+ }
402
+ 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).";
403
+ function warnPostEmit(method, detail) {
404
+ console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
405
+ }
406
+ function mergeInto(target, source) {
407
+ for (const key in source) {
408
+ const sourceVal = source[key];
409
+ if (sourceVal === undefined || sourceVal === null)
410
+ continue;
411
+ const targetVal = target[key];
412
+ if (isPlainObject(sourceVal) && isPlainObject(targetVal))
413
+ mergeInto(targetVal, sourceVal);
414
+ else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
415
+ target[key] = [...targetVal, ...sourceVal];
416
+ else
417
+ target[key] = sourceVal;
418
+ }
419
+ }
420
+ var globalEnv = {
421
+ service: "app",
422
+ environment: "development"
423
+ };
424
+ var globalPretty = isDev();
425
+ var globalSampling = {};
426
+ var globalStringify = true;
427
+ var globalDrain;
428
+ var globalRedact;
429
+ var globalEnabled = true;
430
+ var globalSilent = false;
431
+ var globalMinLevel = "debug";
432
+ function initLogger(config = {}) {
433
+ globalEnabled = config.enabled ?? true;
434
+ const detected = detectEnvironment();
435
+ globalEnv = {
436
+ service: config.env?.service ?? detected.service ?? "app",
437
+ environment: config.env?.environment ?? detected.environment ?? "development",
438
+ version: config.env?.version ?? detected.version,
439
+ commitHash: config.env?.commitHash ?? detected.commitHash,
440
+ region: config.env?.region ?? detected.region
441
+ };
442
+ globalPretty = config.pretty ?? isDev();
443
+ globalSampling = config.sampling ?? {};
444
+ globalStringify = config.stringify ?? true;
445
+ globalDrain = config.drain;
446
+ globalRedact = resolveRedactConfig(config.redact ?? !isDev());
447
+ globalSilent = config.silent ?? false;
448
+ globalMinLevel = config.minLevel ?? "debug";
449
+ if (globalSilent && !globalDrain && !config._suppressDrainWarning)
450
+ 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).");
451
+ }
452
+ function shouldSample(level) {
453
+ const { rates } = globalSampling;
454
+ if (!rates)
455
+ return true;
456
+ const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
457
+ if (percentage <= 0)
458
+ return false;
459
+ if (percentage >= 100)
460
+ return true;
461
+ return Math.random() * 100 < percentage;
462
+ }
463
+ function shouldKeep(ctx) {
464
+ const { keep } = globalSampling;
465
+ if (!keep?.length)
466
+ return false;
467
+ return keep.some((condition) => {
468
+ if (condition.status !== undefined && ctx.status !== undefined && ctx.status >= condition.status)
469
+ return true;
470
+ if (condition.duration !== undefined && ctx.duration !== undefined && ctx.duration >= condition.duration)
471
+ return true;
472
+ if (condition.path && ctx.path && matchesPattern(ctx.path, condition.path))
473
+ return true;
474
+ return false;
475
+ });
476
+ }
477
+ function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
478
+ if (!globalEnabled)
479
+ return null;
480
+ if (!ownsEvent) {
481
+ if (!isLevelEnabled(level, globalMinLevel))
482
+ return null;
483
+ if (!shouldSample(level))
484
+ return null;
485
+ }
486
+ let formatted;
487
+ if (ownsEvent) {
488
+ event.timestamp = isoNow();
489
+ event.level = level;
490
+ if (event.service === undefined)
491
+ event.service = globalEnv.service;
492
+ if (event.environment === undefined)
493
+ event.environment = globalEnv.environment;
494
+ if (globalEnv.version !== undefined && event.version === undefined)
495
+ event.version = globalEnv.version;
496
+ if (globalEnv.commitHash !== undefined && event.commitHash === undefined)
497
+ event.commitHash = globalEnv.commitHash;
498
+ if (globalEnv.region !== undefined && event.region === undefined)
499
+ event.region = globalEnv.region;
500
+ formatted = event;
501
+ } else
502
+ formatted = {
503
+ timestamp: isoNow(),
504
+ level,
505
+ ...globalEnv,
506
+ ...event
507
+ };
508
+ if (globalRedact)
509
+ redactEvent(formatted, globalRedact);
510
+ if (!globalSilent)
511
+ if (globalPretty)
512
+ prettyPrintWideEvent(formatted);
513
+ else if (globalStringify)
514
+ console[getConsoleMethod(level)](JSON.stringify(formatted));
515
+ else
516
+ console[getConsoleMethod(level)](formatted);
517
+ if (globalDrain && !deferDrain)
518
+ Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
519
+ console.error("[evlog] drain failed:", err);
520
+ });
521
+ return formatted;
522
+ }
523
+ function emitTaggedLog(level, tag, message) {
524
+ if (!globalEnabled)
525
+ return;
526
+ if (globalPretty && !globalSilent) {
527
+ if (!isLevelEnabled(level, globalMinLevel))
528
+ return;
529
+ if (!shouldSample(level))
530
+ return;
531
+ if (isClient()) {
532
+ const levelColor = getCssLevelColor(level);
533
+ const timestamp = isoNow().slice(11, 23);
534
+ console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
535
+ } else {
536
+ const color = getLevelColor(level);
537
+ const timestamp = isoNow().slice(11, 23);
538
+ console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
539
+ }
540
+ return;
541
+ }
542
+ emitWideEvent(level, {
543
+ tag,
544
+ message
545
+ });
546
+ }
547
+ function formatValue(value) {
548
+ if (value === null || value === undefined)
549
+ return String(value);
550
+ if (typeof value === "object") {
551
+ const pairs = [];
552
+ for (const [k, v] of Object.entries(value))
553
+ if (v !== undefined && v !== null)
554
+ if (typeof v === "object")
555
+ pairs.push(`${k}=${JSON.stringify(v)}`);
556
+ else
557
+ pairs.push(`${k}=${v}`);
558
+ return pairs.join(" ");
559
+ }
560
+ return String(value);
561
+ }
562
+ function formatCost(cost) {
563
+ if (cost < 0.01)
564
+ return `$${cost.toFixed(6)}`;
565
+ if (cost < 1)
566
+ return `$${cost.toFixed(4)}`;
567
+ return `$${cost.toFixed(2)}`;
568
+ }
569
+ function buildAIEntries(ai) {
570
+ const entries = [];
571
+ const headerParts = [];
572
+ if (ai.model) {
573
+ let m = String(ai.model);
574
+ if (ai.provider)
575
+ m += ` (${ai.provider})`;
576
+ headerParts.push(m);
577
+ }
578
+ if (ai.calls)
579
+ headerParts.push(`${ai.calls} call${ai.calls > 1 ? "s" : ""}`);
580
+ if (ai.steps && ai.steps > 1)
581
+ headerParts.push(`${ai.steps} steps`);
582
+ entries.push({
583
+ key: "ai",
584
+ value: headerParts.join(" \xB7 ")
585
+ });
586
+ const inputTokens = ai.inputTokens;
587
+ const outputTokens = ai.outputTokens;
588
+ const totalTokens = ai.totalTokens;
589
+ if (inputTokens !== undefined && outputTokens !== undefined) {
590
+ let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
591
+ if (totalTokens)
592
+ tokLine += ` (${totalTokens} total)`;
593
+ const extras = [];
594
+ if (ai.cacheReadTokens)
595
+ extras.push(`${ai.cacheReadTokens} cache read`);
596
+ if (ai.cacheWriteTokens)
597
+ extras.push(`${ai.cacheWriteTokens} cache write`);
598
+ if (ai.reasoningTokens)
599
+ extras.push(`${ai.reasoningTokens} reasoning`);
600
+ if (extras.length)
601
+ tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
602
+ entries.push({
603
+ key: "ai.tokens",
604
+ value: tokLine
605
+ });
606
+ }
607
+ const msFirst = ai.msToFirstChunk;
608
+ const msFinish = ai.msToFinish;
609
+ const tps = ai.tokensPerSecond;
610
+ if (msFirst !== undefined || msFinish !== undefined) {
611
+ const parts = [];
612
+ if (msFirst !== undefined)
613
+ parts.push(`${formatDuration(msFirst)} to first chunk`);
614
+ if (msFinish !== undefined)
615
+ parts.push(`${formatDuration(msFinish)} total`);
616
+ let streamLine = parts.join(" \u2192 ");
617
+ if (tps)
618
+ streamLine += ` \xB7 ${tps} tok/s`;
619
+ entries.push({
620
+ key: "ai.streaming",
621
+ value: streamLine
622
+ });
623
+ }
624
+ if (ai.estimatedCost !== undefined)
625
+ entries.push({
626
+ key: "ai.cost",
627
+ value: formatCost(ai.estimatedCost)
628
+ });
629
+ if (ai.totalDurationMs !== undefined)
630
+ entries.push({
631
+ key: "ai.totalDuration",
632
+ value: formatDuration(ai.totalDurationMs)
633
+ });
634
+ const toolCalls = ai.toolCalls;
635
+ const tools = ai.tools;
636
+ const hasInputs = toolCalls?.length ? typeof toolCalls[0] === "object" : false;
637
+ if (tools?.length) {
638
+ const children = tools.map((t, idx) => {
639
+ const mark = t.success ? "\u2713" : "\u2717";
640
+ let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
641
+ if (t.error)
642
+ line += ` ${t.error}`;
643
+ if (hasInputs && toolCalls && idx < toolCalls.length) {
644
+ const tc = toolCalls[idx];
645
+ const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
646
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
647
+ line += ` ${truncated}`;
648
+ }
649
+ return line;
650
+ });
651
+ entries.push({
652
+ key: "ai.tools",
653
+ value: "",
654
+ children
655
+ });
656
+ } else if (toolCalls?.length)
657
+ if (hasInputs) {
658
+ const children = toolCalls.map((tc) => {
659
+ const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
660
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
661
+ return `${tc.name}(${truncated})`;
662
+ });
663
+ entries.push({
664
+ key: "ai.tools",
665
+ value: "",
666
+ children
667
+ });
668
+ } else
669
+ entries.push({
670
+ key: "ai.tools",
671
+ value: toolCalls.join(", ")
672
+ });
673
+ const stepsUsage = ai.stepsUsage;
674
+ if (stepsUsage?.length) {
675
+ const allSameModel = stepsUsage.every((s) => s.model === stepsUsage[0].model);
676
+ const children = stepsUsage.map((s) => {
677
+ let line = `${allSameModel ? "" : `${s.model} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
678
+ const stepTools = s.toolCalls;
679
+ if (stepTools?.length)
680
+ line += ` [${stepTools.join(", ")}]`;
681
+ return line;
682
+ });
683
+ entries.push({
684
+ key: "ai.steps",
685
+ value: "",
686
+ children
687
+ });
688
+ } else if (ai.steps && ai.steps > 1)
689
+ entries.push({
690
+ key: "ai.steps",
691
+ value: String(ai.steps)
692
+ });
693
+ const embedding = ai.embedding;
694
+ if (embedding) {
695
+ const parts = [];
696
+ if (embedding.model)
697
+ parts.push(String(embedding.model));
698
+ parts.push(`${embedding.tokens} tokens`);
699
+ if (embedding.dimensions)
700
+ parts.push(`${embedding.dimensions}d`);
701
+ if (embedding.count)
702
+ parts.push(`${embedding.count} items`);
703
+ entries.push({
704
+ key: "ai.embedding",
705
+ value: parts.join(" \xB7 ")
706
+ });
707
+ }
708
+ if (ai.finishReason)
709
+ entries.push({
710
+ key: "ai.finishReason",
711
+ value: String(ai.finishReason)
712
+ });
713
+ if (ai.error)
714
+ entries.push({
715
+ key: "ai.error",
716
+ value: String(ai.error)
717
+ });
718
+ if (ai.responseId)
719
+ entries.push({
720
+ key: "ai.responseId",
721
+ value: String(ai.responseId)
722
+ });
723
+ return entries;
724
+ }
725
+ function prettyPrintWideEvent(event) {
726
+ const { timestamp, level, service, environment, version, ...rest } = event;
727
+ const ts = timestamp.slice(11, 23);
728
+ const browser = isClient();
729
+ const parts = [];
730
+ const styles = [];
731
+ if (browser) {
732
+ const lc = getCssLevelColor(level);
733
+ parts.push(`%c${ts}%c %c${level.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
734
+ styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
735
+ } else {
736
+ const lc = getLevelColor(level);
737
+ parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${level.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
738
+ }
739
+ if (rest.method && rest.path) {
740
+ parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
741
+ delete rest.method;
742
+ delete rest.path;
743
+ }
744
+ if (rest.status) {
745
+ const sc = browser ? rest.status >= 400 ? cssColors.red : cssColors.green : rest.status >= 400 ? colors.red : colors.green;
746
+ if (browser) {
747
+ parts.push(` %c${rest.status}%c`);
748
+ styles.push(sc, cssColors.reset);
749
+ } else
750
+ parts.push(` ${sc}${rest.status}${colors.reset}`);
751
+ delete rest.status;
752
+ }
753
+ if (rest.duration) {
754
+ if (browser) {
755
+ parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
756
+ styles.push(cssColors.dim, cssColors.reset);
757
+ } else
758
+ parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
759
+ delete rest.duration;
760
+ }
761
+ console.log(parts.join(""), ...styles);
762
+ const aiData = rest.ai;
763
+ if (aiData && typeof aiData === "object")
764
+ delete rest.ai;
765
+ const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
766
+ const aiEntries = aiData ? buildAIEntries(aiData) : [];
767
+ const allEntries = [...restEntries.map(([key, value]) => ({
768
+ key,
769
+ value: formatValue(value)
770
+ })), ...aiEntries];
771
+ for (let i = 0;i < allEntries.length; i++) {
772
+ const entry = allEntries[i];
773
+ const hasChildren = entry.children && entry.children.length > 0;
774
+ const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
775
+ if (browser) {
776
+ const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
777
+ console.log(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
778
+ } else {
779
+ const val = entry.value ? ` ${entry.value}` : "";
780
+ console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
781
+ }
782
+ if (hasChildren) {
783
+ const connector = i === allEntries.length - 1 ? " " : "\u2502";
784
+ for (let j = 0;j < entry.children.length; j++) {
785
+ const child = entry.children[j];
786
+ const childPrefix = j === entry.children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
787
+ if (browser)
788
+ console.log(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
789
+ else
790
+ console.log(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
791
+ }
792
+ }
793
+ }
794
+ }
795
+ function createLogMethod(level) {
796
+ return function logMethod(tagOrEvent, message) {
797
+ if (typeof tagOrEvent === "string" && message !== undefined)
798
+ emitTaggedLog(level, tagOrEvent, message);
799
+ else if (typeof tagOrEvent === "object")
800
+ emitWideEvent(level, tagOrEvent);
801
+ else
802
+ emitTaggedLog(level, "log", String(tagOrEvent));
803
+ };
804
+ }
805
+ var _log = {
806
+ info: createLogMethod("info"),
807
+ error: createLogMethod("error"),
808
+ warn: createLogMethod("warn"),
809
+ debug: createLogMethod("debug")
810
+ };
811
+ var noopLogger = {
812
+ set() {},
813
+ error() {},
814
+ info() {},
815
+ warn() {},
816
+ emit() {
817
+ return null;
818
+ },
819
+ getContext() {
820
+ return {};
821
+ }
822
+ };
823
+ function createLogger(initialContext = {}, internalOptions) {
824
+ if (!globalEnabled)
825
+ return noopLogger;
826
+ const deferDrain = internalOptions?._deferDrain ?? false;
827
+ const startTime = Date.now();
828
+ const context = { ...initialContext };
829
+ let hasError = false;
830
+ let hasWarn = false;
831
+ let emitted = false;
832
+ function addLog(level, message) {
833
+ if (!Array.isArray(context.requestLogs))
834
+ context.requestLogs = [];
835
+ context.requestLogs.push({
836
+ level,
837
+ message,
838
+ timestamp: isoNow()
839
+ });
840
+ }
841
+ return {
842
+ set(data) {
843
+ if (emitted) {
844
+ const keys = Object.keys(data);
845
+ warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
846
+ return;
847
+ }
848
+ mergeInto(context, data);
849
+ },
850
+ error(error, errorContext) {
851
+ if (emitted) {
852
+ warnPostEmit("log.error()", `Keys dropped: ${(errorContext ? [...Object.keys(errorContext), "error"] : ["error"]).join(", ")}.`);
853
+ return;
854
+ }
855
+ hasError = true;
856
+ const err = typeof error === "string" ? new Error(error) : error;
857
+ if (errorContext)
858
+ mergeInto(context, errorContext);
859
+ const errorObj = {
860
+ name: err.name,
861
+ message: err.message,
862
+ stack: err.stack
863
+ };
864
+ const errRecord = err;
865
+ for (const k of [
866
+ "status",
867
+ "statusText",
868
+ "statusCode",
869
+ "statusMessage",
870
+ "data",
871
+ "cause",
872
+ "internal"
873
+ ])
874
+ if (k in err)
875
+ errorObj[k] = errRecord[k];
876
+ if (isPlainObject(context.error))
877
+ mergeInto(context.error, errorObj);
878
+ else
879
+ context.error = errorObj;
880
+ },
881
+ info(message, infoContext) {
882
+ if (emitted) {
883
+ warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
884
+ return;
885
+ }
886
+ addLog("info", message);
887
+ if (infoContext) {
888
+ const { requestLogs: _, ...rest } = infoContext;
889
+ mergeInto(context, rest);
890
+ }
891
+ },
892
+ warn(message, warnContext) {
893
+ if (emitted) {
894
+ warnPostEmit("log.warn()", `Keys dropped: ${(warnContext ? ["message", ...Object.keys(warnContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
895
+ return;
896
+ }
897
+ hasWarn = true;
898
+ addLog("warn", message);
899
+ if (warnContext) {
900
+ const { requestLogs: _, ...rest } = warnContext;
901
+ mergeInto(context, rest);
902
+ }
903
+ },
904
+ emit(overrides) {
905
+ if (emitted) {
906
+ warnPostEmit("log.emit()", "Ignoring duplicate emit.");
907
+ return null;
908
+ }
909
+ const durationMs = Date.now() - startTime;
910
+ const level = hasError ? "error" : hasWarn ? "warn" : "info";
911
+ let forceKeep = false;
912
+ if (overrides?._forceKeep)
913
+ forceKeep = true;
914
+ else if (globalSampling.keep?.length)
915
+ forceKeep = shouldKeep({
916
+ status: overrides?.status ?? context.status,
917
+ duration: durationMs,
918
+ path: context.path,
919
+ method: context.method,
920
+ context
921
+ });
922
+ if (!forceKeep && !shouldSample(level)) {
923
+ emitted = true;
924
+ return null;
925
+ }
926
+ if (overrides) {
927
+ const obj = overrides;
928
+ for (const key in obj)
929
+ if (key !== "_forceKeep")
930
+ context[key] = obj[key];
931
+ }
932
+ context.duration = formatDuration(durationMs);
933
+ const wide = emitWideEvent(level, context, deferDrain, true);
934
+ emitted = true;
935
+ return wide;
936
+ },
937
+ getContext() {
938
+ return { ...context };
939
+ }
940
+ };
941
+ }
942
+ if (typeof __EVLOG_CONFIG__ !== "undefined")
943
+ initLogger(__EVLOG_CONFIG__);
944
+ // src/link.tsx
945
+ import {
946
+ createContext,
947
+ createElement,
948
+ useCallback,
949
+ useContext,
950
+ useEffect,
951
+ useMemo,
952
+ useRef,
953
+ useState
954
+ } from "react";
955
+
956
+ // src/render/boundaries.tsx
957
+ import { Component, Fragment } from "react";
958
+
959
+ // src/error.ts
960
+ function getPublicErrorMessage(error) {
961
+ const branded = error;
962
+ if (branded?.__furinBrand === "FURIN_NOT_FOUND") {
963
+ return error.message;
964
+ }
965
+ return "Something went wrong";
966
+ }
967
+
968
+ // src/not-found.ts
969
+ var NOT_FOUND_BRAND = "FURIN_NOT_FOUND";
970
+
971
+ class FurinNotFoundError extends Error {
972
+ __furinBrand = NOT_FOUND_BRAND;
973
+ data;
974
+ constructor(options) {
975
+ super(options?.message ?? "");
976
+ this.data = options?.data;
977
+ }
978
+ }
979
+ function isNotFoundError(err) {
980
+ return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
981
+ }
982
+
983
+ // src/render/default-screens.tsx
984
+ import { jsxDEV } from "react/jsx-dev-runtime";
985
+ var FONT_SANS = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
986
+ var FONT_MONO = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace';
987
+ var COLOR_BG = "#000000";
988
+ var COLOR_TEXT = "#ffffff";
989
+ var COLOR_TEXT_DIM = "rgba(255, 255, 255, 0.7)";
990
+ var COLOR_TEXT_MUTED = "rgba(255, 255, 255, 0.45)";
991
+ var COLOR_GRID = "rgba(255, 255, 255, 0.04)";
992
+ var COLOR_BRACKET = "rgba(255, 255, 255, 0.55)";
993
+ var COLOR_DANGER_DIM = "rgba(239, 68, 68, 0.6)";
994
+ var PAGE_STYLE = {
995
+ alignItems: "center",
996
+ backgroundColor: COLOR_BG,
997
+ backgroundImage: `
998
+ linear-gradient(${COLOR_GRID} 1px, transparent 1px),
999
+ linear-gradient(90deg, ${COLOR_GRID} 1px, transparent 1px)
1000
+ `,
1001
+ backgroundSize: "32px 32px, 32px 32px",
1002
+ boxSizing: "border-box",
1003
+ color: COLOR_TEXT,
1004
+ display: "flex",
1005
+ fontFamily: FONT_SANS,
1006
+ fontSize: "16px",
1007
+ justifyContent: "center",
1008
+ lineHeight: 1.5,
1009
+ margin: 0,
1010
+ minHeight: "100vh",
1011
+ padding: "32px",
1012
+ width: "100%"
1013
+ };
1014
+ var FRAME_STYLE = {
1015
+ boxSizing: "border-box",
1016
+ maxWidth: "880px",
1017
+ position: "relative",
1018
+ width: "100%"
1019
+ };
1020
+ var BRACKET_BASE = {
1021
+ height: "40px",
1022
+ position: "absolute",
1023
+ width: "40px"
1024
+ };
1025
+ function CornerBracket({ corner }) {
1026
+ const top = corner === "tl" || corner === "tr";
1027
+ const left = corner === "tl" || corner === "bl";
1028
+ const style = {
1029
+ ...BRACKET_BASE,
1030
+ [top ? "top" : "bottom"]: 0,
1031
+ [left ? "left" : "right"]: 0,
1032
+ [`border${top ? "Top" : "Bottom"}`]: `2px solid ${COLOR_BRACKET}`,
1033
+ [`border${left ? "Left" : "Right"}`]: `2px solid ${COLOR_BRACKET}`
1034
+ };
1035
+ return /* @__PURE__ */ jsxDEV("span", {
1036
+ "aria-hidden": "true",
1037
+ style
1038
+ }, undefined, false, undefined, this);
1039
+ }
1040
+ var CARD_STYLE = {
1041
+ boxSizing: "border-box",
1042
+ margin: "0 auto",
1043
+ maxWidth: "640px",
1044
+ padding: "64px 24px",
1045
+ textAlign: "center"
1046
+ };
1047
+ var BADGE_STYLE = {
1048
+ border: `1px solid ${COLOR_DANGER_DIM}`,
1049
+ color: COLOR_TEXT,
1050
+ display: "inline-block",
1051
+ fontFamily: FONT_SANS,
1052
+ fontSize: "32px",
1053
+ fontWeight: 600,
1054
+ letterSpacing: "0.08em",
1055
+ marginBottom: "16px",
1056
+ padding: "12px 36px"
1057
+ };
1058
+ var NOT_FOUND_BADGE_STYLE = {
1059
+ ...BADGE_STYLE,
1060
+ border: 0,
1061
+ padding: 0
1062
+ };
1063
+ var HEADING_STYLE = {
1064
+ color: COLOR_TEXT,
1065
+ fontFamily: FONT_SANS,
1066
+ fontSize: "24px",
1067
+ fontWeight: 600,
1068
+ margin: "0 0 24px 0"
1069
+ };
1070
+ var CODE_BOX_STYLE = {
1071
+ color: COLOR_TEXT_DIM,
1072
+ display: "inline-block",
1073
+ fontFamily: FONT_MONO,
1074
+ fontSize: "13px",
1075
+ letterSpacing: "0.02em",
1076
+ margin: "0 0 32px 0",
1077
+ padding: "8px 0"
1078
+ };
1079
+ var CODE_LABEL_STYLE = {
1080
+ color: COLOR_TEXT_MUTED,
1081
+ marginRight: "10px",
1082
+ textTransform: "uppercase"
1083
+ };
1084
+ var DESCRIPTION_WRAPPER_STYLE = {
1085
+ color: COLOR_TEXT_DIM,
1086
+ fontSize: "15px",
1087
+ margin: "0 auto 40px auto",
1088
+ maxWidth: "440px",
1089
+ padding: 0,
1090
+ textAlign: "center"
1091
+ };
1092
+ var ACTIONS_STYLE = {
1093
+ display: "flex",
1094
+ flexWrap: "wrap",
1095
+ gap: "16px",
1096
+ justifyContent: "center"
1097
+ };
1098
+ var BUTTON_BASE = {
1099
+ border: 0,
1100
+ cursor: "pointer",
1101
+ display: "inline-flex",
1102
+ fontFamily: FONT_SANS,
1103
+ fontSize: "14px",
1104
+ fontWeight: 500,
1105
+ lineHeight: 1,
1106
+ minWidth: "120px",
1107
+ padding: "10px 16px",
1108
+ textAlign: "center",
1109
+ textDecoration: "none",
1110
+ transition: "background-color 120ms ease, color 120ms ease, opacity 120ms ease",
1111
+ appearance: "none",
1112
+ alignItems: "center",
1113
+ justifyContent: "center",
1114
+ boxSizing: "border-box"
1115
+ };
1116
+ var BUTTON_PRIMARY = {
1117
+ ...BUTTON_BASE,
1118
+ backgroundColor: COLOR_TEXT,
1119
+ border: `1px solid ${COLOR_TEXT}`,
1120
+ boxShadow: "0 10px 24px rgba(255, 255, 255, 0.08)",
1121
+ color: COLOR_BG,
1122
+ fontWeight: 600
1123
+ };
1124
+ var BUTTON_SECONDARY = {
1125
+ ...BUTTON_BASE,
1126
+ backgroundColor: "transparent",
1127
+ border: "1px solid rgba(255, 255, 255, 0.22)",
1128
+ color: COLOR_TEXT_DIM
1129
+ };
1130
+ var DIVIDER_STYLE = {
1131
+ backgroundColor: "rgba(255, 255, 255, 0.12)",
1132
+ border: 0,
1133
+ height: "1px",
1134
+ margin: "0 0 40px 0",
1135
+ width: "100%"
1136
+ };
1137
+ var RESET_CSS = `
1138
+ html, body {
1139
+ margin: 0;
1140
+ padding: 0;
1141
+ background-color: ${COLOR_BG};
1142
+ overscroll-behavior: none;
1143
+ }
1144
+ `;
1145
+ function ScreenFrame({ badge, children }) {
1146
+ return /* @__PURE__ */ jsxDEV("div", {
1147
+ style: PAGE_STYLE,
1148
+ children: [
1149
+ /* @__PURE__ */ jsxDEV("style", {
1150
+ dangerouslySetInnerHTML: { __html: RESET_CSS }
1151
+ }, undefined, false, undefined, this),
1152
+ /* @__PURE__ */ jsxDEV("div", {
1153
+ style: FRAME_STYLE,
1154
+ children: [
1155
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
1156
+ corner: "tl"
1157
+ }, undefined, false, undefined, this),
1158
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
1159
+ corner: "tr"
1160
+ }, undefined, false, undefined, this),
1161
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
1162
+ corner: "bl"
1163
+ }, undefined, false, undefined, this),
1164
+ /* @__PURE__ */ jsxDEV(CornerBracket, {
1165
+ corner: "br"
1166
+ }, undefined, false, undefined, this),
1167
+ /* @__PURE__ */ jsxDEV("div", {
1168
+ style: CARD_STYLE,
1169
+ children: [
1170
+ badge,
1171
+ /* @__PURE__ */ jsxDEV("hr", {
1172
+ style: DIVIDER_STYLE
1173
+ }, undefined, false, undefined, this),
1174
+ children
1175
+ ]
1176
+ }, undefined, true, undefined, this)
1177
+ ]
1178
+ }, undefined, true, undefined, this)
1179
+ ]
1180
+ }, undefined, true, undefined, this);
1181
+ }
1182
+ function DefaultErrorScreen({ message, digest, reset }) {
1183
+ return /* @__PURE__ */ jsxDEV(ScreenFrame, {
1184
+ badge: /* @__PURE__ */ jsxDEV("div", {
1185
+ style: BADGE_STYLE,
1186
+ children: "500 \u2014 ERROR"
1187
+ }, undefined, false, undefined, this),
1188
+ children: [
1189
+ /* @__PURE__ */ jsxDEV("h1", {
1190
+ style: HEADING_STYLE,
1191
+ children: "Something went wrong"
1192
+ }, undefined, false, undefined, this),
1193
+ /* @__PURE__ */ jsxDEV("div", {
1194
+ style: CODE_BOX_STYLE,
1195
+ children: [
1196
+ /* @__PURE__ */ jsxDEV("span", {
1197
+ style: CODE_LABEL_STYLE,
1198
+ children: "CODE:"
1199
+ }, undefined, false, undefined, this),
1200
+ /* @__PURE__ */ jsxDEV("span", {
1201
+ children: digest
1202
+ }, undefined, false, undefined, this)
1203
+ ]
1204
+ }, undefined, true, undefined, this),
1205
+ /* @__PURE__ */ jsxDEV("p", {
1206
+ style: DESCRIPTION_WRAPPER_STYLE,
1207
+ children: message ? message : "We encountered an unexpected error. Please try again or return to the home page."
1208
+ }, undefined, false, undefined, this),
1209
+ /* @__PURE__ */ jsxDEV("div", {
1210
+ style: ACTIONS_STYLE,
1211
+ children: [
1212
+ /* @__PURE__ */ jsxDEV(Link, {
1213
+ style: BUTTON_PRIMARY,
1214
+ to: "/",
1215
+ children: "Go Home"
1216
+ }, undefined, false, undefined, this),
1217
+ /* @__PURE__ */ jsxDEV("button", {
1218
+ onClick: reset,
1219
+ style: BUTTON_SECONDARY,
1220
+ type: "button",
1221
+ children: "Try again"
1222
+ }, undefined, false, undefined, this)
1223
+ ]
1224
+ }, undefined, true, undefined, this)
1225
+ ]
1226
+ }, undefined, true, undefined, this);
1227
+ }
1228
+ function DefaultNotFoundScreen({ message }) {
1229
+ return /* @__PURE__ */ jsxDEV(ScreenFrame, {
1230
+ badge: /* @__PURE__ */ jsxDEV("div", {
1231
+ style: NOT_FOUND_BADGE_STYLE,
1232
+ children: "404 \u2014 NOT FOUND"
1233
+ }, undefined, false, undefined, this),
1234
+ children: [
1235
+ /* @__PURE__ */ jsxDEV("h1", {
1236
+ style: HEADING_STYLE,
1237
+ children: "This page does not exist"
1238
+ }, undefined, false, undefined, this),
1239
+ /* @__PURE__ */ jsxDEV("p", {
1240
+ style: DESCRIPTION_WRAPPER_STYLE,
1241
+ children: message ? message : "The page you are looking for could not be found. It may have been moved or removed."
1242
+ }, undefined, false, undefined, this),
1243
+ /* @__PURE__ */ jsxDEV("div", {
1244
+ style: ACTIONS_STYLE,
1245
+ children: /* @__PURE__ */ jsxDEV(Link, {
1246
+ style: BUTTON_PRIMARY,
1247
+ to: "/",
1248
+ children: "Go Home"
1249
+ }, undefined, false, undefined, this)
1250
+ }, undefined, false, undefined, this)
1251
+ ]
1252
+ }, undefined, true, undefined, this);
1253
+ }
1254
+
1255
+ // src/render/digest.ts
1256
+ function computeErrorDigest(err) {
1257
+ let message = "";
1258
+ let stack = "";
1259
+ if (err instanceof Error) {
1260
+ message = err.message;
1261
+ stack = err.stack ?? "";
1262
+ } else if (typeof err === "string") {
1263
+ message = err;
1264
+ } else {
1265
+ try {
1266
+ message = JSON.stringify(err) ?? String(err);
1267
+ } catch {
1268
+ message = String(err);
1269
+ }
1270
+ }
1271
+ const input = `${message}
1272
+ ${stack}`;
1273
+ const hash = cyrb53(input);
1274
+ const hex = hash.toString(16).padStart(14, "0");
1275
+ return hex.slice(0, 10);
1276
+ }
1277
+ function cyrb53(input) {
1278
+ let h1 = 3735928559;
1279
+ let h2 = 1103547991;
1280
+ for (let i = 0;i < input.length; i++) {
1281
+ const ch = input.charCodeAt(i);
1282
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1283
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1284
+ }
1285
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1286
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1287
+ return 4294967296 * (2097151 & h2) + (4294967295 & h1);
1288
+ }
1289
+
1290
+ // src/render/boundaries.tsx
1291
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
1292
+ var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV2(DefaultErrorScreen, {
1293
+ digest: error.digest,
1294
+ message: error.message,
1295
+ reset
1296
+ }, undefined, false, undefined, this);
1297
+ var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV2(DefaultNotFoundScreen, {
1298
+ message: error.message
1299
+ }, undefined, false, undefined, this);
1300
+ var SERVER_RESET_NOOP = () => {};
1301
+
1302
+ class FurinErrorBoundary extends Component {
1303
+ state = {
1304
+ digest: null,
1305
+ epoch: 0,
1306
+ error: null
1307
+ };
1308
+ static getDerivedStateFromError(error) {
1309
+ return { digest: computeErrorDigest(error), error };
1310
+ }
1311
+ componentDidUpdate(prevProps) {
1312
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
1313
+ this.reset();
1314
+ }
1315
+ }
1316
+ reset = () => {
1317
+ this.setState((s) => ({ digest: null, epoch: s.epoch + 1, error: null }), () => {
1318
+ this.props.onReset?.();
1319
+ });
1320
+ };
1321
+ render() {
1322
+ const { error, epoch, digest } = this.state;
1323
+ if (error) {
1324
+ if (isNotFoundError(error)) {
1325
+ throw error;
1326
+ }
1327
+ const Fallback = this.props.fallback ?? DefaultErrorFallback;
1328
+ const finalDigest = digest ?? this.props.digest ?? computeErrorDigest(error);
1329
+ const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
1330
+ return /* @__PURE__ */ jsxDEV2(Fallback, {
1331
+ error: { message, digest: finalDigest },
1332
+ reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
1333
+ }, undefined, false, undefined, this);
1334
+ }
1335
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
1336
+ children: this.props.children
1337
+ }, epoch, false, undefined, this);
1338
+ }
1339
+ }
1340
+
1341
+ class FurinNotFoundBoundary extends Component {
1342
+ state = { epoch: 0, error: null };
1343
+ static getDerivedStateFromError(error) {
1344
+ return { error };
1345
+ }
1346
+ componentDidUpdate(prevProps) {
1347
+ if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
1348
+ this.setState((s) => ({ error: null, epoch: s.epoch + 1 }));
1349
+ }
1350
+ }
1351
+ render() {
1352
+ const { error, epoch } = this.state;
1353
+ if (error) {
1354
+ if (!isNotFoundError(error)) {
1355
+ throw error;
1356
+ }
1357
+ const Fallback = this.props.fallback ?? DefaultNotFoundFallback;
1358
+ return /* @__PURE__ */ jsxDEV2(Fallback, {
1359
+ error: { message: error.message, data: error.data }
1360
+ }, undefined, false, undefined, this);
1361
+ }
1362
+ return /* @__PURE__ */ jsxDEV2(Fragment, {
1363
+ children: this.props.children
1364
+ }, epoch, false, undefined, this);
1365
+ }
1366
+ }
1367
+
1368
+ // src/link.tsx
1369
+ import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
1370
+ function buildHref(to, search, hash) {
1371
+ let url = to;
1372
+ if (search && Object.keys(search).length > 0) {
1373
+ const params = new URLSearchParams;
1374
+ for (const [k, v] of Object.entries(search)) {
1375
+ if (v != null) {
1376
+ params.set(k, String(v));
1377
+ }
1378
+ }
1379
+ const qs = params.toString();
1380
+ if (qs) {
1381
+ url += `?${qs}`;
1382
+ }
1383
+ }
1384
+ if (hash) {
1385
+ url += `#${hash}`;
1386
+ }
1387
+ return url;
1388
+ }
1389
+ var RouterContext = createContext(null);
1390
+ function useRouter() {
1391
+ return useContext(RouterContext) ?? {
1392
+ basePath: "",
1393
+ currentHref: "/",
1394
+ navigate: (href) => {
1395
+ window.location.href = href;
1396
+ return Promise.resolve();
1397
+ },
1398
+ prefetch: () => {},
1399
+ invalidatePrefetch: () => {},
1400
+ refresh: () => {
1401
+ window.location.reload();
1402
+ return Promise.resolve();
1403
+ },
1404
+ isNavigating: false,
1405
+ defaultPreload: "intent",
1406
+ defaultPreloadDelay: 50,
1407
+ defaultPreloadStaleTime: 30000
1408
+ };
1409
+ }
1410
+ function computeLinkView({
1411
+ to,
1412
+ search,
1413
+ hash,
1414
+ children,
1415
+ activeProps,
1416
+ inactiveProps
1417
+ }, router) {
1418
+ const logicalHref = buildHref(to, search, hash);
1419
+ const logicalHrefWithoutHash = buildHref(to, search, undefined);
1420
+ const href = router.basePath + logicalHref;
1421
+ const isActive = router.currentHref === logicalHrefWithoutHash;
1422
+ const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
1423
+ const extraProps = {
1424
+ ...inactiveProps && !isActive ? inactiveProps() : {},
1425
+ ...activeProps ? activeProps({ isActive }) : {}
1426
+ };
1427
+ return { logicalHref, href, isActive, resolvedChildren, extraProps };
1428
+ }
1429
+ function LinkInteractive({
1430
+ to,
1431
+ search,
1432
+ hash,
1433
+ preload,
1434
+ preloadDelay,
1435
+ preloadStaleTime,
1436
+ replace,
1437
+ disabled,
1438
+ resetScroll,
1439
+ activeProps,
1440
+ inactiveProps,
1441
+ onClick,
1442
+ onMouseEnter,
1443
+ onMouseLeave,
1444
+ onFocus,
1445
+ children,
1446
+ ...anchorProps
1447
+ }) {
1448
+ const router = useRouter();
1449
+ const anchorRef = useRef(null);
1450
+ const intentTimerRef = useRef(null);
1451
+ const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
1452
+ const effectivePreload = preload ?? router.defaultPreload;
1453
+ const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
1454
+ const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
1455
+ const triggerPrefetch = useCallback(() => {
1456
+ router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
1457
+ }, [router, logicalHref, effectiveStaleTime]);
1458
+ useEffect(() => {
1459
+ if (effectivePreload === "render") {
1460
+ triggerPrefetch();
1461
+ }
1462
+ }, [effectivePreload, triggerPrefetch]);
1463
+ useEffect(() => {
1464
+ if (effectivePreload !== "viewport" || !anchorRef.current) {
1465
+ return;
1466
+ }
1467
+ const observer = new IntersectionObserver(([entry]) => {
1468
+ if (entry?.isIntersecting) {
1469
+ triggerPrefetch();
1470
+ observer.disconnect();
1471
+ }
1472
+ }, { rootMargin: "200px" });
1473
+ observer.observe(anchorRef.current);
1474
+ return () => observer.disconnect();
1475
+ }, [effectivePreload, triggerPrefetch]);
1476
+ const isInternal = (url) => {
1477
+ try {
1478
+ return new URL(url, window.location.origin).origin === window.location.origin;
1479
+ } catch {
1480
+ return false;
1481
+ }
1482
+ };
1483
+ const handleClick = (e) => {
1484
+ onClick?.(e);
1485
+ if (e.defaultPrevented || disabled) {
1486
+ return;
1487
+ }
1488
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
1489
+ return;
1490
+ }
1491
+ if (anchorProps.target && anchorProps.target !== "_self") {
1492
+ return;
1493
+ }
1494
+ if (!isInternal(href)) {
1495
+ return;
1496
+ }
1497
+ e.preventDefault();
1498
+ router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
1499
+ };
1500
+ const handleMouseEnter = (e) => {
1501
+ onMouseEnter?.(e);
1502
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
1503
+ intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
1504
+ }
1505
+ };
1506
+ const handleMouseLeave = (e) => {
1507
+ onMouseLeave?.(e);
1508
+ if (intentTimerRef.current !== null) {
1509
+ clearTimeout(intentTimerRef.current);
1510
+ intentTimerRef.current = null;
1511
+ }
1512
+ };
1513
+ const handleFocus = (e) => {
1514
+ onFocus?.(e);
1515
+ if (!disabled && effectivePreload === "intent" && isInternal(href)) {
1516
+ triggerPrefetch();
1517
+ }
1518
+ };
1519
+ return createElement("a", {
1520
+ ref: anchorRef,
1521
+ href,
1522
+ onClick: handleClick,
1523
+ onMouseEnter: handleMouseEnter,
1524
+ onMouseLeave: handleMouseLeave,
1525
+ onFocus: handleFocus,
1526
+ ...isActive ? { "data-status": "active" } : {},
1527
+ ...anchorProps,
1528
+ ...extraProps,
1529
+ ...disabled ? { "aria-disabled": true } : {}
1530
+ }, resolvedChildren);
1531
+ }
1532
+ var SSR_FALLBACK_ROUTER = {
1533
+ basePath: "",
1534
+ currentHref: "/",
1535
+ navigate: () => Promise.resolve(),
1536
+ prefetch: () => {},
1537
+ invalidatePrefetch: () => {},
1538
+ refresh: () => Promise.resolve(),
1539
+ isNavigating: false,
1540
+ defaultPreload: "intent",
1541
+ defaultPreloadDelay: 50,
1542
+ defaultPreloadStaleTime: 30000
1543
+ };
1544
+ function renderLinkElement(props, router) {
1545
+ const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
1546
+ const {
1547
+ to: _to,
1548
+ search: _search,
1549
+ hash: _hash,
1550
+ children: _children,
1551
+ activeProps: _ap,
1552
+ inactiveProps: _ip,
1553
+ disabled,
1554
+ preload: _p,
1555
+ preloadDelay: _pd,
1556
+ preloadStaleTime: _ps,
1557
+ replace: _r,
1558
+ resetScroll: _rs,
1559
+ onClick: _oc,
1560
+ onMouseEnter: _ome,
1561
+ onMouseLeave: _oml,
1562
+ onFocus: _of,
1563
+ ...anchorProps
1564
+ } = props;
1565
+ return createElement("a", {
1566
+ href,
1567
+ ...isActive ? { "data-status": "active" } : {},
1568
+ ...anchorProps,
1569
+ ...extraProps,
1570
+ ...disabled ? { "aria-disabled": true } : {}
1571
+ }, resolvedChildren);
1572
+ }
1573
+ function Link(props) {
1574
+ if (typeof window === "undefined") {
1575
+ return createElement(RouterContext.Consumer, {
1576
+ children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
1577
+ });
1578
+ }
1579
+ return createElement(LinkInteractive, props);
1580
+ }
1581
+
1582
+ // src/render/cache.ts
1583
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
1584
+
1585
+ // src/context-logger.ts
1586
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
1587
+
1588
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
1589
+ import { AsyncLocalStorage } from "async_hooks";
1590
+ import { Elysia } from "elysia";
1591
+ var storage = new AsyncLocalStorage;
1592
+ var activeLoggers = /* @__PURE__ */ new WeakSet;
1593
+ function useLogger2() {
1594
+ const logger = storage.getStore();
1595
+ if (!logger || !activeLoggers.has(logger))
1596
+ throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
1597
+ return logger;
1598
+ }
1599
+
1600
+ // src/context-logger.ts
1601
+ var noopLogger2 = {
1602
+ set: () => {},
1603
+ error: () => {},
1604
+ info: () => {},
1605
+ warn: () => {},
1606
+ emit: () => null,
1607
+ getContext: () => ({}),
1608
+ fork: (_label, fn) => fn()
1609
+ };
1610
+ var syntheticRenderStorage = new AsyncLocalStorage2;
1611
+ function useLogger3() {
1612
+ try {
1613
+ return useLogger2();
1614
+ } catch {
1615
+ return syntheticRenderStorage.getStore() ?? noopLogger2;
1616
+ }
1617
+ }
1618
+ async function runInSyntheticRenderScope(fn, initialContext) {
1619
+ const logger = createLogger(initialContext);
1620
+ try {
1621
+ const result = await syntheticRenderStorage.run(logger, () => Promise.resolve(fn()));
1622
+ logger.emit();
1623
+ return result;
1624
+ } catch (err) {
1625
+ logger.error(err instanceof Error ? err : new Error(String(err)));
1626
+ logger.emit();
1627
+ throw err;
1628
+ }
1629
+ }
1630
+
1631
+ // src/render/cache.ts
1632
+ var MAX_ISR_CACHE_SIZE = 1000;
1633
+ var MAX_SSG_CACHE_SIZE = 1000;
1634
+ var isrCache = new Map;
1635
+ var ssgCache = new Map;
1636
+ function evictOldest(map, maxSize) {
1637
+ if (map.size > maxSize) {
1638
+ const oldest = map.keys().next().value;
1639
+ if (oldest !== undefined) {
1640
+ map.delete(oldest);
1641
+ }
1642
+ }
1643
+ }
1644
+ function getISRCache(key) {
1645
+ const entry = isrCache.get(key);
1646
+ if (entry !== undefined) {
1647
+ isrCache.delete(key);
1648
+ isrCache.set(key, entry);
1649
+ }
1650
+ return entry;
1651
+ }
1652
+ function getSSGCache(key) {
1653
+ const entry = ssgCache.get(key);
1654
+ if (entry !== undefined) {
1655
+ ssgCache.delete(key);
1656
+ ssgCache.set(key, entry);
1657
+ }
1658
+ return entry;
1659
+ }
1660
+ function setISRCache(key, entry) {
1661
+ isrCache.delete(key);
1662
+ isrCache.set(key, entry);
1663
+ evictOldest(isrCache, MAX_ISR_CACHE_SIZE);
1664
+ }
1665
+ function setSSGCache(key, entry) {
1666
+ ssgCache.delete(key);
1667
+ ssgCache.set(key, entry);
1668
+ evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
1669
+ }
1670
+ var _requestInvalidationScope = new AsyncLocalStorage3;
1671
+ var _globalPendingInvalidations = new Set;
1672
+
1673
+ // src/render/element.tsx
1674
+ import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
1675
+ function wrapInBoundaries(inner, segment) {
1676
+ if (!segment) {
1677
+ return inner;
1678
+ }
1679
+ let wrapped = inner;
1680
+ if (segment.notFound) {
1681
+ wrapped = /* @__PURE__ */ jsxDEV4(FurinNotFoundBoundary, {
1682
+ fallback: segment.notFound,
1683
+ children: wrapped
1684
+ }, undefined, false, undefined, this);
1685
+ }
1686
+ if (segment.error) {
1687
+ wrapped = /* @__PURE__ */ jsxDEV4(FurinErrorBoundary, {
1688
+ fallback: segment.error,
1689
+ children: wrapped
1690
+ }, undefined, false, undefined, this);
1691
+ }
1692
+ return wrapped;
1693
+ }
1694
+ function buildElement(route, data, rootLayout) {
1695
+ const Component2 = route.page.component;
1696
+ let element = /* @__PURE__ */ jsxDEV4(Component2, {
1697
+ ...data
1698
+ }, undefined, false, undefined, this);
1699
+ const byDepth = new Map;
1700
+ for (const segment of route.segmentBoundaries ?? []) {
1701
+ byDepth.set(segment.depth, segment);
1702
+ }
1703
+ for (let i = route.routeChain.length - 1;i >= 1; i--) {
1704
+ element = wrapInBoundaries(element, byDepth.get(i));
1705
+ const routeEntry = route.routeChain[i];
1706
+ if (routeEntry?.layout) {
1707
+ const Layout = routeEntry.layout;
1708
+ element = /* @__PURE__ */ jsxDEV4(Layout, {
1709
+ ...data,
1710
+ children: element
1711
+ }, undefined, false, undefined, this);
1712
+ }
1713
+ }
1714
+ element = wrapInBoundaries(element, byDepth.get(0));
1715
+ if (rootLayout.layout) {
1716
+ const RootLayoutComponent = rootLayout.layout;
1717
+ element = /* @__PURE__ */ jsxDEV4(RootLayoutComponent, {
1718
+ ...data,
1719
+ children: element
1720
+ }, undefined, false, undefined, this);
1721
+ }
1722
+ return element;
1723
+ }
1724
+ var DefaultNotFoundComponent = ({ error }) => /* @__PURE__ */ jsxDEV4(DefaultNotFoundScreen, {
1725
+ message: error.message
1726
+ }, undefined, false, undefined, this);
1727
+ function buildNotFoundElement(component, error) {
1728
+ const NotFound = component ?? DefaultNotFoundComponent;
1729
+ return /* @__PURE__ */ jsxDEV4(NotFound, {
1730
+ error: { message: error.message, data: error.data }
1731
+ }, undefined, false, undefined, this);
1732
+ }
1733
+ var DefaultErrorComponent = ({ error, reset }) => /* @__PURE__ */ jsxDEV4(DefaultErrorScreen, {
1734
+ digest: error.digest,
1735
+ message: error.message,
1736
+ reset
1737
+ }, undefined, false, undefined, this);
1738
+ function errorMessageOf(err) {
1739
+ if (err instanceof Error) {
1740
+ return err.message;
1741
+ }
1742
+ if (typeof err === "string") {
1743
+ return err;
1744
+ }
1745
+ return "";
1746
+ }
1747
+ var SERVER_RESET_NOOP2 = () => {};
1748
+ function buildErrorElement(component, error, digest) {
1749
+ const ErrorView = component ?? DefaultErrorComponent;
1750
+ const message = component ? errorMessageOf(error) : "An unexpected error occurred.";
1751
+ return /* @__PURE__ */ jsxDEV4(ErrorView, {
1752
+ error: { message, digest },
1753
+ reset: SERVER_RESET_NOOP2
1754
+ }, undefined, false, undefined, this);
1755
+ }
1756
+
1757
+ // src/render/loaders.ts
1758
+ function createLoaderCtx(ctx, accumulatedParentPromise) {
1759
+ const cache = new Map;
1760
+ return new Proxy(ctx, {
1761
+ get(target, prop) {
1762
+ if (typeof prop !== "string") {
1763
+ return Reflect.get(target, prop);
1764
+ }
1765
+ if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
1766
+ return Reflect.get(target, prop);
1767
+ }
1768
+ if (Object.hasOwn(target, prop)) {
1769
+ return target[prop];
1770
+ }
1771
+ let entry = cache.get(prop);
1772
+ if (!entry) {
1773
+ entry = accumulatedParentPromise.then((data) => data[prop]);
1774
+ cache.set(prop, entry);
1775
+ }
1776
+ return entry;
1777
+ }
1778
+ });
1779
+ }
1780
+ async function runLoaders(route, ctx, _rootLayout) {
1781
+ try {
1782
+ const ctxRecord = { ...ctx, log: useLogger3() };
1783
+ const loaderMap = new Map;
1784
+ let accumulatedParentPromise = Promise.resolve({});
1785
+ for (const r of route.routeChain) {
1786
+ const parentAccum = accumulatedParentPromise;
1787
+ if (r.loader) {
1788
+ const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
1789
+ const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
1790
+ loaderMap.set(r, loaderPromise);
1791
+ accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
1792
+ ...acc,
1793
+ ...own
1794
+ }));
1795
+ accumulatedParentPromise.catch(() => {});
1796
+ }
1797
+ }
1798
+ const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
1799
+ const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
1800
+ const results = await Promise.all([...loaderMap.values(), pagePromise]);
1801
+ const data = Object.assign({}, ...results);
1802
+ const headers = {};
1803
+ Object.assign(headers, ctx.set.headers);
1804
+ return { type: "data", data, headers };
1805
+ } catch (err) {
1806
+ if (isNotFoundError(err)) {
1807
+ const headers2 = {};
1808
+ Object.assign(headers2, ctx.set.headers);
1809
+ return { type: "not-found", error: err, headers: headers2 };
1810
+ }
1811
+ if (err instanceof Response) {
1812
+ return { type: "redirect", response: err };
1813
+ }
1814
+ const headers = {};
1815
+ Object.assign(headers, ctx.set.headers);
1816
+ return { type: "error", error: err, headers };
1817
+ }
1818
+ }
1819
+
1820
+ // src/render/template.ts
1821
+ import { readFileSync } from "fs";
1822
+ var _prodTemplatePath = null;
1823
+ var _prodTemplateContent = null;
1824
+ var _devTemplateCache = null;
1825
+ var DEV_TEMPLATE_TTL_MS = 1000;
1826
+ async function getDevTemplate(origin) {
1827
+ if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
1828
+ return _devTemplateCache.html;
1829
+ }
1830
+ const r = await fetch(`${origin}/_bun_hmr_entry`);
1831
+ if (!r.ok) {
1832
+ throw new Error(`/_bun_hmr_entry returned ${r.status}`);
1833
+ }
1834
+ const html = await r.text();
1835
+ _devTemplateCache = { html, ts: Date.now() };
1836
+ return html;
1837
+ }
1838
+ function getProductionTemplate() {
1839
+ if (_prodTemplateContent !== null) {
1840
+ return _prodTemplateContent;
1841
+ }
1842
+ if (!_prodTemplatePath) {
1843
+ return null;
1844
+ }
1845
+ try {
1846
+ _prodTemplateContent = readFileSync(_prodTemplatePath, "utf8");
1847
+ return _prodTemplateContent;
1848
+ } catch {
1849
+ return null;
1850
+ }
1851
+ }
1852
+ // src/runtime-env.ts
1853
+ var IS_DEV = true;
1854
+
1855
+ // src/render/index.ts
1856
+ function withSSRRouterContext(element, contextValue) {
1857
+ return createElement2(RouterContext.Provider, { value: contextValue }, element);
1858
+ }
1859
+ async function prepareRender(route, ctx, root, basePath, throwOnFailure) {
1860
+ const loaderStart = Date.now();
1861
+ const loaderResult = await runLoaders(route, ctx, root.route);
1862
+ const loader_ms = Date.now() - loaderStart;
1863
+ if (loaderResult.type === "redirect") {
1864
+ return loaderResult.response;
1865
+ }
1866
+ if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
1867
+ throw loaderResult.error;
1868
+ }
1869
+ const isNotFound = loaderResult.type === "not-found";
1870
+ const isError = loaderResult.type === "error";
1871
+ const isFallback = isNotFound || isError;
1872
+ const data = isFallback ? {} : loaderResult.data;
1873
+ const headers = loaderResult.headers;
1874
+ const componentProps = {
1875
+ ...data,
1876
+ params: ctx.params,
1877
+ query: ctx.query,
1878
+ path: ctx.path
1879
+ };
1880
+ const headData = isFallback ? "" : buildHeadInjection(route.page?.head?.(componentProps));
1881
+ const prodTemplate = getProductionTemplate();
1882
+ const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
1883
+ let element;
1884
+ let status = 200;
1885
+ let errorDigest;
1886
+ let notFoundError;
1887
+ if (loaderResult.type === "not-found") {
1888
+ element = buildNotFoundElement(route.notFound ?? root.notFound, loaderResult.error);
1889
+ status = 404;
1890
+ notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
1891
+ } else if (loaderResult.type === "error") {
1892
+ errorDigest = computeErrorDigest(loaderResult.error);
1893
+ element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest);
1894
+ status = 500;
1895
+ } else {
1896
+ element = buildElement(route, componentProps, root.route);
1897
+ }
1898
+ const ssrContext = {
1899
+ basePath: basePath ?? "",
1900
+ currentHref: ctx.path,
1901
+ navigate: () => Promise.resolve(),
1902
+ prefetch: () => {},
1903
+ invalidatePrefetch: () => {},
1904
+ refresh: () => Promise.resolve(),
1905
+ isNavigating: false,
1906
+ defaultPreload: "intent",
1907
+ defaultPreloadDelay: 50,
1908
+ defaultPreloadStaleTime: 30000
1909
+ };
1910
+ element = withSSRRouterContext(element, ssrContext);
1911
+ return {
1912
+ componentProps,
1913
+ element,
1914
+ errorDigest,
1915
+ headData,
1916
+ headers,
1917
+ loader_ms,
1918
+ notFoundError,
1919
+ ssrContext,
1920
+ status,
1921
+ template
1922
+ };
1923
+ }
1924
+ function renderForPath(route, params, root, origin, mode, basePath) {
1925
+ return runInSyntheticRenderScope(async () => {
1926
+ const resolvedPath = resolvePath(route.pattern, params);
1927
+ const ctx = {
1928
+ params,
1929
+ query: {},
1930
+ request: new Request(`${origin}${resolvedPath}`),
1931
+ headers: {},
1932
+ cookie: {},
1933
+ redirect: (url, status2) => new Response(null, { status: status2 ?? 302, headers: { Location: url } }),
1934
+ set: { headers: {} },
1935
+ path: resolvedPath
1936
+ };
1937
+ const prepared = await prepareRender(route, ctx, root, basePath, true);
1938
+ if (prepared instanceof Response) {
1939
+ return prepared;
1940
+ }
1941
+ useLogger3().set({
1942
+ furin: {
1943
+ render: mode,
1944
+ route: route.pattern,
1945
+ cache: mode === "isr" ? "revalidated" : "miss",
1946
+ loader_ms: prepared.loader_ms,
1947
+ ...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
1948
+ }
1949
+ });
1950
+ const { componentProps, element, headData, headers, status, template } = prepared;
1951
+ const stream = await renderToReadableStream(element);
1952
+ await stream.allReady;
1953
+ const reactHtml = await streamToString(stream);
1954
+ return {
1955
+ html: assembleHTML(template, headData, reactHtml, componentProps),
1956
+ headers,
1957
+ status
1958
+ };
1959
+ }, { route: route.pattern, render: mode });
1960
+ }
1961
+ async function prerenderSSG(route, params, root, origin, basePath) {
1962
+ const resolvedPath = resolvePath(route.pattern, params);
1963
+ const cached = getSSGCache(resolvedPath);
1964
+ if (cached && !IS_DEV) {
1965
+ return cached;
1966
+ }
1967
+ const renderResult = await renderForPath(route, params, root, origin, "ssg", basePath);
1968
+ if (renderResult instanceof Response) {
1969
+ return renderResult;
1970
+ }
1971
+ const result = renderResult;
1972
+ const entry = { html: result.html, cachedAt: Date.now(), status: result.status };
1973
+ if (!IS_DEV) {
1974
+ setSSGCache(resolvedPath, entry);
1975
+ }
1976
+ return entry;
1977
+ }
1978
+ async function renderSSR(route, ctx, root) {
1979
+ const prepared = await prepareRender(route, ctx, root, undefined, false);
1980
+ if (prepared instanceof Response) {
1981
+ return prepared;
1982
+ }
1983
+ useLogger3().set({
1984
+ furin: {
1985
+ render: route.mode,
1986
+ route: route.pattern,
1987
+ loader_ms: prepared.loader_ms,
1988
+ ...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
1989
+ }
1990
+ });
1991
+ const { componentProps, element, headData, headers, template } = prepared;
1992
+ const { headPre, bodyPre, bodyPost } = splitTemplate(template);
1993
+ let reactStream;
1994
+ let status = prepared.status;
1995
+ let shellErrored = false;
1996
+ let finalDigest = prepared.errorDigest;
1997
+ try {
1998
+ reactStream = await renderToReadableStream(element);
1999
+ } catch (shellError) {
2000
+ shellErrored = true;
2001
+ status = 500;
2002
+ finalDigest = computeErrorDigest(shellError);
2003
+ useLogger3().set({
2004
+ furin: { render: route.mode, route: route.pattern, digest: finalDigest, phase: "shell" }
2005
+ });
2006
+ try {
2007
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest), prepared.ssrContext));
2008
+ } catch {
2009
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest), prepared.ssrContext));
2010
+ }
2011
+ }
2012
+ const dataPayload = shellErrored ? {} : { ...componentProps };
2013
+ if (finalDigest) {
2014
+ dataPayload.__furinError = { digest: finalDigest };
2015
+ }
2016
+ if (status === 404 && !shellErrored) {
2017
+ dataPayload.__furinStatus = 404;
2018
+ if (prepared.notFoundError) {
2019
+ dataPayload.__furinNotFound = prepared.notFoundError;
2020
+ }
2021
+ }
2022
+ const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(dataPayload)}</script>`;
2023
+ const { readable, writable } = new TransformStream;
2024
+ const writer = writable.getWriter();
2025
+ const enc = new TextEncoder;
2026
+ (async () => {
2027
+ await writer.write(enc.encode(headPre + headData + bodyPre));
2028
+ const reader = reactStream.getReader();
2029
+ for (;; ) {
2030
+ const { done, value } = await reader.read();
2031
+ if (done) {
2032
+ break;
2033
+ }
2034
+ await writer.write(value);
2035
+ }
2036
+ await writer.write(enc.encode(dataScript + bodyPost));
2037
+ await writer.close();
2038
+ })().catch((err) => writer.abort(err));
2039
+ return new Response(readable, {
2040
+ status,
2041
+ headers: {
2042
+ "Content-Type": "text/html; charset=utf-8",
2043
+ "Cache-Control": "no-store, no-cache, must-revalidate",
2044
+ ...headers
2045
+ }
2046
+ });
2047
+ }
2048
+ function isrCacheControl(isFresh, revalidate) {
2049
+ const sMaxAge = isFresh ? revalidate : 0;
2050
+ return `public, max-age=0, must-revalidate, s-maxage=${sMaxAge}, stale-while-revalidate=${revalidate}`;
2051
+ }
2052
+ function serveISRCacheHit(cached, ctx, route, params, cacheKey, revalidate, root, buildId) {
2053
+ const isFresh = Date.now() - cached.generatedAt < revalidate * 1000;
2054
+ if (!isFresh) {
2055
+ revalidateInBackground(route, params, cacheKey, revalidate, root, ctx);
2056
+ }
2057
+ const etag = buildId ? `"${buildId}:${cached.generatedAt}"` : null;
2058
+ if (etag && ctx.request.headers.get("if-none-match") === etag) {
2059
+ ctx.set.status = 304;
2060
+ ctx.set.headers.etag = etag;
2061
+ ctx.set.headers["cache-control"] = isrCacheControl(isFresh, revalidate);
2062
+ return;
2063
+ }
2064
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
2065
+ ctx.set.headers["cache-control"] = isrCacheControl(isFresh, revalidate);
2066
+ if (etag) {
2067
+ ctx.set.headers.etag = etag;
2068
+ }
2069
+ useLogger3().set({
2070
+ furin: { render: "isr", route: route.pattern, cache: isFresh ? "hit" : "stale" }
2071
+ });
2072
+ return cached.html;
2073
+ }
2074
+ async function renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId) {
2075
+ const { componentProps, element, headData, template, status, notFoundError } = prepared;
2076
+ const fallbackProps = { ...componentProps };
2077
+ if (status === 404) {
2078
+ fallbackProps.__furinStatus = 404;
2079
+ if (notFoundError) {
2080
+ fallbackProps.__furinNotFound = notFoundError;
2081
+ }
2082
+ }
2083
+ let reactStream;
2084
+ let finalStatus = status;
2085
+ let finalDigest = errorDigest;
2086
+ try {
2087
+ reactStream = await renderToReadableStream(element);
2088
+ } catch (shellError) {
2089
+ finalStatus = 500;
2090
+ finalDigest = computeErrorDigest(shellError);
2091
+ useLogger3().set({
2092
+ furin: {
2093
+ render: "isr",
2094
+ route: route.pattern,
2095
+ cache: "miss",
2096
+ digest: finalDigest,
2097
+ phase: "shell"
2098
+ }
2099
+ });
2100
+ fallbackProps.__furinError = { digest: finalDigest };
2101
+ fallbackProps.__furinStatus = 500;
2102
+ try {
2103
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest), prepared.ssrContext));
2104
+ } catch {
2105
+ reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest), prepared.ssrContext));
2106
+ }
2107
+ }
2108
+ if (!fallbackProps.__furinError && errorDigest) {
2109
+ fallbackProps.__furinError = { digest: errorDigest };
2110
+ }
2111
+ await reactStream.allReady;
2112
+ const reactHtml = await streamToString(reactStream);
2113
+ const html = assembleHTML(template, headData, reactHtml, fallbackProps);
2114
+ const generatedAt = Date.now();
2115
+ const renderMs = generatedAt - renderStart;
2116
+ useLogger3().set({
2117
+ furin: {
2118
+ render: "isr",
2119
+ route: route.pattern,
2120
+ cache: "miss",
2121
+ render_ms: renderMs,
2122
+ ...finalDigest ? { digest: finalDigest } : {},
2123
+ status: finalStatus
2124
+ }
2125
+ });
2126
+ const etag = buildId ? `"${buildId}:${generatedAt}"` : null;
2127
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
2128
+ ctx.set.headers["cache-control"] = "no-store";
2129
+ if (etag) {
2130
+ ctx.set.headers.etag = etag;
2131
+ }
2132
+ ctx.set.status = finalStatus;
2133
+ return html;
2134
+ }
2135
+ async function handleISR(route, ctx, root, buildId = "") {
2136
+ const revalidate = route.page._route.revalidate ?? 60;
2137
+ const params = ctx.params ?? {};
2138
+ const cacheKey = resolvePath(route.pattern, params);
2139
+ const cached = getISRCache(cacheKey);
2140
+ if (cached && !IS_DEV) {
2141
+ return serveISRCacheHit(cached, ctx, route, params, cacheKey, revalidate, root, buildId);
2142
+ }
2143
+ const renderStart = Date.now();
2144
+ const prepared = await prepareRender(route, ctx, root, undefined, false);
2145
+ if (prepared instanceof Response) {
2146
+ return prepared;
2147
+ }
2148
+ const { componentProps, element, headData, template, status, errorDigest } = prepared;
2149
+ if (status !== 200) {
2150
+ return renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId);
2151
+ }
2152
+ const stream = await renderToReadableStream(element);
2153
+ await stream.allReady;
2154
+ const reactHtml = await streamToString(stream);
2155
+ const html = assembleHTML(template, headData, reactHtml, componentProps);
2156
+ const generatedAt = Date.now();
2157
+ useLogger3().set({
2158
+ furin: {
2159
+ render: "isr",
2160
+ route: route.pattern,
2161
+ cache: "miss",
2162
+ render_ms: generatedAt - renderStart
2163
+ }
2164
+ });
2165
+ if (!IS_DEV) {
2166
+ setISRCache(cacheKey, { html, generatedAt, revalidate });
2167
+ }
2168
+ const etag = buildId ? `"${buildId}:${generatedAt}"` : null;
2169
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
2170
+ ctx.set.headers["cache-control"] = isrCacheControl(true, revalidate);
2171
+ if (etag) {
2172
+ ctx.set.headers.etag = etag;
2173
+ }
2174
+ return html;
2175
+ }
2176
+ var pendingRevalidations = new Set;
2177
+ function revalidateInBackground(route, params, cacheKey, revalidate, root, originalCtx) {
2178
+ if (pendingRevalidations.has(cacheKey)) {
2179
+ const logger = createLogger({});
2180
+ logger.set({
2181
+ furin: {
2182
+ render: "isr",
2183
+ route: route.pattern,
2184
+ cache: "revalidation_skipped",
2185
+ reason: "already_in_flight"
2186
+ }
2187
+ });
2188
+ logger.emit();
2189
+ return;
2190
+ }
2191
+ pendingRevalidations.add(cacheKey);
2192
+ renderForPath(route, params, root, new URL(originalCtx.request.url).origin, "isr", undefined).then((result) => {
2193
+ if (result instanceof Response) {
2194
+ return;
2195
+ }
2196
+ setISRCache(cacheKey, {
2197
+ html: result.html,
2198
+ generatedAt: Date.now(),
2199
+ revalidate
2200
+ });
2201
+ }).catch((err) => {
2202
+ const logger = createLogger({});
2203
+ logger.set({
2204
+ furin: {
2205
+ render: "isr",
2206
+ route: route.pattern,
2207
+ cache: "revalidation_failed"
2208
+ }
2209
+ });
2210
+ logger.error(err instanceof Error ? err : new Error(String(err)));
2211
+ logger.emit();
2212
+ }).finally(() => {
2213
+ pendingRevalidations.delete(cacheKey);
2214
+ });
2215
+ }
2216
+
2217
+ // src/utils.ts
2218
+ function isFurinPage(value) {
2219
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
2220
+ }
2221
+ function isFurinRoute(value) {
2222
+ return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
2223
+ }
2224
+ function collectRouteChainFromRoute(route) {
2225
+ const chain = [];
2226
+ let current = route;
2227
+ while (current) {
2228
+ chain.unshift(current);
2229
+ current = current.parent;
2230
+ }
2231
+ return chain;
2232
+ }
2233
+ function hasCycle(route) {
2234
+ const visited = new Set;
2235
+ let current = route;
2236
+ while (current) {
2237
+ if (visited.has(current)) {
2238
+ return true;
2239
+ }
2240
+ visited.add(current);
2241
+ current = current.parent;
2242
+ }
2243
+ return false;
2244
+ }
2245
+ function validateRouteChain(chain, root, pagePath) {
2246
+ const hasRoot = chain.some((r) => r === root);
2247
+ if (!hasRoot) {
2248
+ const location = pagePath ? `in ${pagePath}` : "";
2249
+ throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
2250
+ }
2251
+ for (const route of chain) {
2252
+ if (hasCycle(route)) {
2253
+ throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
2254
+ }
2255
+ }
2256
+ }
2257
+
2258
+ // src/router.ts
2259
+ function isModuleNotFoundError(err) {
2260
+ if (!(err instanceof Error)) {
2261
+ return false;
2262
+ }
2263
+ const msg = err.message.toLowerCase();
2264
+ const code = err.code;
2265
+ return code === "ENOENT" || code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || msg.includes("cannot find module") || msg.includes("module not found") || msg.includes("no such file or directory");
2266
+ }
2267
+ function loadProdRoutes(ctx) {
2268
+ const rootMod = ctx.modules[ctx.rootPath];
2269
+ const rootExport = rootMod.route ?? rootMod.default;
2270
+ if (!(rootExport && isFurinRoute(rootExport) && rootExport.layout)) {
2271
+ throw new Error("[furin] root.tsx: createRoute() with layout not found in CompileContext.");
2272
+ }
2273
+ function resolveModuleComponent(modPath) {
2274
+ if (!modPath) {
2275
+ return;
2276
+ }
2277
+ const mod = ctx.modules[modPath];
2278
+ return mod?.default;
2279
+ }
2280
+ const root = {
2281
+ path: ctx.rootPath,
2282
+ route: rootExport,
2283
+ error: resolveModuleComponent(ctx.rootConventions?.errorPath),
2284
+ notFound: resolveModuleComponent(ctx.rootConventions?.notFoundPath)
2285
+ };
2286
+ const routes = [];
2287
+ for (const { pattern, path, mode } of ctx.routes) {
2288
+ const pageMod = ctx.modules[path];
2289
+ const page = pageMod.default;
2290
+ if (!isFurinPage(page)) {
2291
+ throw new Error(`[furin] ${path}: invalid page module in CompileContext.`);
2292
+ }
2293
+ const routeChain = collectRouteChainFromRoute(page._route);
2294
+ validateRouteChain(routeChain, root.route, path);
2295
+ const meta = ctx.routeMetadata?.[path];
2296
+ const boundaries = (meta?.segmentBoundaries ?? []).map((b) => ({
2297
+ ...b,
2298
+ error: resolveModuleComponent(b.errorPath),
2299
+ notFound: resolveModuleComponent(b.notFoundPath)
2300
+ }));
2301
+ const error = boundaries.findLast((b) => b.error)?.error;
2302
+ const notFound = boundaries.findLast((b) => b.notFound)?.notFound;
2303
+ routes.push({
2304
+ pattern,
2305
+ page,
2306
+ path,
2307
+ routeChain,
2308
+ mode,
2309
+ segmentBoundaries: boundaries,
2310
+ error,
2311
+ notFound
2312
+ });
2313
+ }
2314
+ return { root, routes };
2315
+ }
2316
+ async function scanPages(pagesDir) {
2317
+ const root = await scanRootLayout(pagesDir);
2318
+ const routes = await scanPageFiles(pagesDir, root);
2319
+ return { root, routes };
2320
+ }
2321
+ async function scanRootLayout(pagesDir) {
2322
+ const rootPath = `${pagesDir}/root.tsx`;
2323
+ const ctx = getCompileContext();
2324
+ if (!(existsSync(rootPath) || ctx?.modules[rootPath])) {
2325
+ throw new Error("[furin] root.tsx: not found.");
2326
+ }
2327
+ const mod = ctx?.modules[rootPath] ?? await import(rootPath);
2328
+ const rootExport = mod.route ?? mod.default;
2329
+ if (!(rootExport && isFurinRoute(rootExport))) {
2330
+ throw new Error("[furin] root.tsx: createRoute() export not found.");
2331
+ }
2332
+ if (!rootExport.layout) {
2333
+ throw new Error("[furin] root.tsx: createRoute() has no layout.");
2334
+ }
2335
+ const notFoundEntry = await loadConventionComponent(pagesDir, "not-found");
2336
+ const errorEntry = await loadConventionComponent(pagesDir, "error");
2337
+ return {
2338
+ path: rootPath,
2339
+ route: rootExport,
2340
+ notFound: notFoundEntry?.component,
2341
+ notFoundPath: notFoundEntry?.path,
2342
+ error: errorEntry?.component,
2343
+ errorPath: errorEntry?.path
2344
+ };
2345
+ }
2346
+ var CONVENTION_FILE_NAMES = ["not-found", "error"];
2347
+ function isConventionFileName(name) {
2348
+ return CONVENTION_FILE_NAMES.includes(name);
2349
+ }
2350
+ async function loadConventionComponent(dir, name) {
2351
+ const ctx = getCompileContext();
2352
+ for (const ext of [".tsx", ".ts", ".jsx", ".js"]) {
2353
+ const filePath = `${dir}/${name}${ext}`;
2354
+ if (existsSync(filePath) || ctx?.modules[filePath]) {
2355
+ const mod = ctx?.modules[filePath] ?? await import(filePath);
2356
+ if (mod.default) {
2357
+ return { component: mod.default, path: filePath };
2358
+ }
2359
+ }
2360
+ }
2361
+ return;
2362
+ }
2363
+ async function scanPageFiles(pagesDir, root) {
2364
+ const routes = [];
2365
+ const notFoundCache = new Map;
2366
+ const errorCache = new Map;
2367
+ for (const absolutePath of await collectPageFilePaths(pagesDir)) {
2368
+ if (![".tsx", ".ts", ".jsx", ".js"].some((ext) => absolutePath.endsWith(ext))) {
2369
+ continue;
2370
+ }
2371
+ const relativePath = absolutePath.replace(`${pagesDir}/`, "");
2372
+ const fileName = parse(relativePath).name;
2373
+ if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
2374
+ continue;
2375
+ }
2376
+ const notFound = await resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound);
2377
+ const errorComponent = await resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error);
2378
+ const segmentBoundaries = await collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache);
2379
+ if (IS_DEV) {
2380
+ const devRoute = await buildDevRoute(absolutePath, relativePath, root);
2381
+ devRoute.notFound = notFound;
2382
+ devRoute.error = errorComponent;
2383
+ devRoute.segmentBoundaries = segmentBoundaries;
2384
+ routes.push(devRoute);
2385
+ continue;
2386
+ }
2387
+ const ctx = getCompileContext();
2388
+ const pageMod = ctx?.modules[absolutePath] ?? await import(absolutePath);
2389
+ const page = pageMod.default;
2390
+ if (!isFurinPage(page)) {
2391
+ throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
2392
+ }
2393
+ const routeChain = collectRouteChainFromRoute(page._route);
2394
+ validateRouteChain(routeChain, root.route, relativePath);
2395
+ routes.push({
2396
+ pattern: filePathToPattern(relativePath),
2397
+ page,
2398
+ path: absolutePath,
2399
+ routeChain,
2400
+ mode: resolveMode(page, routeChain),
2401
+ notFound,
2402
+ error: errorComponent,
2403
+ segmentBoundaries
2404
+ });
2405
+ }
2406
+ return routes;
2407
+ }
2408
+ async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
2409
+ const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
2410
+ const dirs = [pagesDir];
2411
+ if (pageDir.length > pagesDir.length) {
2412
+ const relativeTail = pageDir.slice(pagesDir.length + 1);
2413
+ const parts = relativeTail.split("/");
2414
+ let acc = pagesDir;
2415
+ for (const part of parts) {
2416
+ acc = `${acc}/${part}`;
2417
+ dirs.push(acc);
2418
+ }
2419
+ }
2420
+ const boundaries = [];
2421
+ for (let depth = 0;depth < dirs.length; depth++) {
2422
+ const dir = dirs[depth];
2423
+ if (!errorCache.has(dir)) {
2424
+ errorCache.set(dir, await loadConventionComponent(dir, "error"));
2425
+ }
2426
+ if (!notFoundCache.has(dir)) {
2427
+ notFoundCache.set(dir, await loadConventionComponent(dir, "not-found"));
2428
+ }
2429
+ const errorEntry = errorCache.get(dir);
2430
+ const notFoundEntry = notFoundCache.get(dir);
2431
+ if (errorEntry || notFoundEntry) {
2432
+ boundaries.push({
2433
+ path: dir,
2434
+ depth,
2435
+ error: errorEntry?.component,
2436
+ errorPath: errorEntry?.path,
2437
+ notFound: notFoundEntry?.component,
2438
+ notFoundPath: notFoundEntry?.path
2439
+ });
2440
+ }
2441
+ }
2442
+ return boundaries;
2443
+ }
2444
+ async function resolveNearestConvention(pageAbsolutePath, pagesDir, conventionName, cache, rootFallback) {
2445
+ let dir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
2446
+ while (dir.length >= pagesDir.length) {
2447
+ if (!cache.has(dir)) {
2448
+ cache.set(dir, await loadConventionComponent(dir, conventionName));
2449
+ }
2450
+ const found = cache.get(dir);
2451
+ if (found) {
2452
+ return found.component;
2453
+ }
2454
+ if (dir === pagesDir) {
2455
+ break;
2456
+ }
2457
+ dir = dir.slice(0, dir.lastIndexOf("/"));
2458
+ }
2459
+ return rootFallback;
2460
+ }
2461
+ async function buildDevRoute(absolutePath, relativePath, root) {
2462
+ let page;
2463
+ let routeChain = [];
2464
+ try {
2465
+ const pageMod = await import(`${absolutePath}?furin-server&t=${Date.now()}`);
2466
+ if (isFurinPage(pageMod.default)) {
2467
+ page = pageMod.default;
2468
+ routeChain = collectRouteChainFromRoute(page._route);
2469
+ validateRouteChain(routeChain, root.route, relativePath);
2470
+ }
2471
+ } catch {}
2472
+ const devStubPage = {
2473
+ __type: "FURIN_PAGE",
2474
+ _route: { __type: "FURIN_ROUTE" },
2475
+ component: () => null
2476
+ };
2477
+ return {
2478
+ pattern: filePathToPattern(relativePath),
2479
+ path: absolutePath,
2480
+ mode: page ? resolveMode(page, routeChain) : "ssr",
2481
+ page: page ?? devStubPage,
2482
+ routeChain,
2483
+ segmentBoundaries: []
2484
+ };
2485
+ }
2486
+ function queryDefaultRedirectHook({ request, query, status, set }) {
2487
+ const resolvedQuery = query;
2488
+ const queryKeys = Object.keys(resolvedQuery);
2489
+ if (queryKeys.length === 0) {
2490
+ return;
2491
+ }
2492
+ const rawParams = new URL(request.url).searchParams;
2493
+ let needsRedirect = false;
2494
+ for (const key of queryKeys) {
2495
+ if (!rawParams.has(key) && resolvedQuery[key] != null) {
2496
+ needsRedirect = true;
2497
+ break;
2498
+ }
2499
+ }
2500
+ if (!needsRedirect) {
2501
+ return;
2502
+ }
2503
+ const url = new URL(request.url);
2504
+ for (const [k, v] of Object.entries(resolvedQuery)) {
2505
+ if (v != null) {
2506
+ url.searchParams.set(k, String(v));
2507
+ }
2508
+ }
2509
+ set.headers.location = url.pathname + url.search;
2510
+ return status("Found");
2511
+ }
2512
+ async function refreshLayoutChain(chain, pagePath, rootPath, importFn) {
2513
+ const resolveImport = importFn ?? ((s) => import(s));
2514
+ const pageDir = pagePath.slice(0, pagePath.lastIndexOf("/"));
2515
+ const pagesDir = rootPath.slice(0, rootPath.lastIndexOf("/"));
2516
+ const layoutPaths = [];
2517
+ let dir = pageDir;
2518
+ while (dir.length > pagesDir.length) {
2519
+ layoutPaths.unshift(`${dir}/_route.tsx`);
2520
+ dir = dir.slice(0, dir.lastIndexOf("/"));
2521
+ }
2522
+ let chainIdx = 1;
2523
+ for (const layoutPath of layoutPaths) {
2524
+ if (chainIdx >= chain.length) {
2525
+ break;
2526
+ }
2527
+ try {
2528
+ const freshMod = await resolveImport(`${layoutPath}?furin-server&t=${Date.now()}`);
2529
+ const freshRoute = freshMod.route ?? freshMod.default;
2530
+ if (freshRoute && isFurinRoute(freshRoute)) {
2531
+ const entry = chain[chainIdx];
2532
+ if (entry) {
2533
+ entry.layout = freshRoute.layout;
2534
+ entry.loader = freshRoute.loader;
2535
+ }
2536
+ }
2537
+ chainIdx++;
2538
+ } catch (err) {
2539
+ if (!isModuleNotFoundError(err)) {
2540
+ throw err;
2541
+ }
2542
+ }
2543
+ }
2544
+ }
2545
+ async function handleDevRequest(route, ctx, root) {
2546
+ try {
2547
+ let currentRoot = root;
2548
+ const rootMod = await import(`${root.path}?furin-server&t=${Date.now()}`);
2549
+ const rootExport = rootMod.route ?? rootMod.default;
2550
+ if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
2551
+ currentRoot = { path: root.path, route: rootExport };
2552
+ }
2553
+ const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
2554
+ const page = pageMod.default;
2555
+ if (page && isFurinPage(page)) {
2556
+ const chain = collectRouteChainFromRoute(page._route);
2557
+ await refreshLayoutChain(chain, route.path, root.path, undefined);
2558
+ return renderSSR({ ...route, page, routeChain: chain }, ctx, currentRoot);
2559
+ }
2560
+ } catch (err) {
2561
+ console.error(`[furin] Dev page load error for ${route.path}:`, err);
2562
+ }
2563
+ return new Response(`<!doctype html><html><body><h1>Page load error</h1><p>Could not load ${route.path}. Check the server console for details.</p></body></html>`, { status: 500, headers: { "Content-Type": "text/html; charset=utf-8" } });
2564
+ }
2565
+ async function handleSSGRequest(route, ctx, root, buildId) {
2566
+ const origin = new URL(ctx.request.url).origin;
2567
+ const entry = await prerenderSSG(route, ctx.params, root, origin, undefined);
2568
+ if (entry instanceof Response) {
2569
+ return entry;
2570
+ }
2571
+ const resolvedPath = resolvePath(route.pattern, ctx.params ?? {});
2572
+ const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
2573
+ if (etag && ctx.request.headers.get("if-none-match") === etag) {
2574
+ ctx.set.status = 304;
2575
+ return;
2576
+ }
2577
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
2578
+ ctx.set.headers["cache-control"] = "public, max-age=0, must-revalidate, s-maxage=31536000";
2579
+ if (etag) {
2580
+ ctx.set.headers.etag = etag;
2581
+ }
2582
+ ctx.set.headers["cache-tag"] = resolvedPath;
2583
+ return entry.html;
2584
+ }
2585
+ var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
2586
+ function mergeRouteSchemas(routeChain, key) {
2587
+ const schemas = routeChain.map((r) => r[key]).filter(Boolean);
2588
+ if (schemas.length === 0) {
2589
+ return;
2590
+ }
2591
+ if (schemas.length === 1) {
2592
+ return schemas[0];
2593
+ }
2594
+ const mergedProperties = Object.assign({}, ...schemas.map((s) => s.properties ?? {}));
2595
+ const mergedOptions = Object.assign({}, ...schemas.map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))));
2596
+ return t.Object(mergedProperties, mergedOptions);
2597
+ }
2598
+ function createRoutePlugin(route, root, buildId = "") {
2599
+ const { pattern, routeChain } = route;
2600
+ const allParams = mergeRouteSchemas(routeChain, "params");
2601
+ const allQuery = mergeRouteSchemas(routeChain, "query");
2602
+ const hasQuerySchema = !!allQuery;
2603
+ const plugin = new Elysia2;
2604
+ if (allParams || allQuery) {
2605
+ plugin.guard({
2606
+ params: allParams,
2607
+ query: allQuery
2608
+ });
2609
+ }
2610
+ plugin.get(pattern, (ctx) => {
2611
+ if (hasQuerySchema) {
2612
+ const redirect = queryDefaultRedirectHook(ctx);
2613
+ if (redirect) {
2614
+ return redirect;
2615
+ }
2616
+ }
2617
+ if (IS_DEV) {
2618
+ return handleDevRequest(route, ctx, root);
2619
+ }
2620
+ if (route.mode === "ssg") {
2621
+ return handleSSGRequest(route, ctx, root, buildId);
2622
+ }
2623
+ if (route.mode === "isr") {
2624
+ ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
2625
+ return handleISR(route, ctx, root, buildId);
2626
+ }
2627
+ return renderSSR(route, ctx, root);
2628
+ });
2629
+ return plugin;
2630
+ }
2631
+ async function collectPageFilePaths(dir) {
2632
+ const files = [];
2633
+ const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
2634
+ for (const entry of entries) {
2635
+ const absolutePath = join(dir, entry.name);
2636
+ if (entry.isDirectory()) {
2637
+ files.push(...await collectPageFilePaths(absolutePath));
2638
+ continue;
2639
+ }
2640
+ if (entry.isFile()) {
2641
+ files.push(absolutePath);
2642
+ }
2643
+ }
2644
+ return files;
2645
+ }
2646
+ function resolveMode(page, routeChain) {
2647
+ const routeConfig = page._route;
2648
+ const mode = routeConfig.mode ?? page.mode;
2649
+ const revalidate = routeConfig.revalidate ?? page.revalidate;
2650
+ if (mode) {
2651
+ return mode;
2652
+ }
2653
+ const hasLoader = routeChain.some((r) => r.loader) || !!page.loader;
2654
+ if (!hasLoader) {
2655
+ return "ssg";
2656
+ }
2657
+ if (typeof revalidate === "number" && revalidate >= 0) {
2658
+ return "isr";
2659
+ }
2660
+ return "ssr";
2661
+ }
2662
+ function filePathToPattern(path) {
2663
+ const parts = path.replaceAll("\\", "/").split("/");
2664
+ const segments = [];
2665
+ for (const part of parts) {
2666
+ const name = parse(part).name;
2667
+ if (name === "index") {
2668
+ continue;
2669
+ }
2670
+ if (name.startsWith("[") && name.endsWith("]")) {
2671
+ const inner = name.slice(1, -1);
2672
+ if (inner.startsWith("...")) {
2673
+ segments.push("*");
2674
+ continue;
2675
+ }
2676
+ segments.push(`:${inner}`);
2677
+ continue;
2678
+ }
2679
+ segments.push(name);
2680
+ }
2681
+ return `/${segments.join("/")}`;
2682
+ }
2683
+ export {
2684
+ scanRootLayout,
2685
+ scanPages,
2686
+ resolveMode,
2687
+ refreshLayoutChain,
2688
+ queryDefaultRedirectHook,
2689
+ mergeRouteSchemas,
2690
+ loadProdRoutes,
2691
+ filePathToPattern,
2692
+ createRoutePlugin
2693
+ };