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

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