@teyik0/furin 0.1.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/bun.d.ts +3 -0
- package/dist/adapter/static.d.ts +3 -0
- package/dist/build/client.d.ts +25 -0
- package/dist/build/compile-entry.d.ts +35 -0
- package/dist/build/entry-template.d.ts +26 -0
- package/dist/build/hydrate.d.ts +24 -0
- package/dist/build/index.d.ts +7 -0
- package/dist/build/index.js +4716 -0
- package/dist/build/route-types.d.ts +21 -0
- package/dist/build/scan-server.d.ts +8 -0
- package/dist/build/server-routes-entry.d.ts +35 -0
- package/dist/build/shared.d.ts +11 -0
- package/dist/build/types.d.ts +76 -0
- package/dist/cli/config.d.ts +9 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +4751 -0
- package/dist/client.d.ts +195 -0
- package/dist/client.js +20 -0
- package/dist/config.d.ts +50 -0
- package/dist/config.js +28 -0
- package/dist/context-logger.d.ts +28 -0
- package/dist/dev-page-plugin.d.ts +109 -0
- package/dist/error.d.ts +23 -0
- package/dist/furin.d.ts +52 -0
- package/dist/furin.js +3948 -0
- package/dist/internal.d.ts +33 -0
- package/dist/link.d.ts +454 -0
- package/dist/link.js +1790 -0
- package/dist/not-found.d.ts +19 -0
- package/dist/plugin/index.d.ts +20 -0
- package/dist/plugin/index.js +1408 -0
- package/dist/plugin/transform-client.d.ts +9 -0
- package/dist/render/assemble.d.ts +15 -0
- package/dist/render/boundaries.d.ts +79 -0
- package/dist/render/cache.d.ts +96 -0
- package/dist/render/default-screens.d.ts +11 -0
- package/dist/render/digest.d.ts +16 -0
- package/dist/render/element.d.ts +8 -0
- package/dist/render/index.d.ts +53 -0
- package/dist/render/loaders.d.ts +21 -0
- package/dist/render/shell.d.ts +29 -0
- package/dist/render/template.d.ts +6 -0
- package/dist/router.d.ts +96 -0
- package/dist/router.js +2693 -0
- package/dist/runtime-env.d.ts +3 -0
- package/dist/utils.d.ts +6 -0
- package/package.json +77 -0
- package/src/adapter/README.md +13 -0
- package/src/adapter/bun.ts +239 -0
- package/src/adapter/static.ts +341 -0
- package/src/build/client.ts +153 -0
- package/src/build/compile-entry.ts +129 -0
- package/src/build/entry-template.ts +126 -0
- package/src/build/hydrate.ts +250 -0
- package/src/build/index.ts +151 -0
- package/src/build/route-types.ts +89 -0
- package/src/build/scan-server.ts +110 -0
- package/src/build/server-routes-entry.ts +55 -0
- package/src/build/shared.ts +78 -0
- package/src/build/types.ts +85 -0
- package/src/cli/config.ts +68 -0
- package/src/cli/index.ts +115 -0
- package/src/client.ts +278 -0
- package/src/config.ts +66 -0
- package/src/context-logger.ts +74 -0
- package/src/dev-page-plugin.ts +434 -0
- package/src/env.d.ts +49 -0
- package/src/error.ts +32 -0
- package/src/furin.ts +383 -0
- package/src/internal.ts +51 -0
- package/src/link.tsx +1578 -0
- package/src/not-found.ts +40 -0
- package/src/plugin/index.ts +80 -0
- package/src/plugin/transform-client.ts +372 -0
- package/src/render/assemble.ts +66 -0
- package/src/render/boundaries.tsx +176 -0
- package/src/render/cache.ts +251 -0
- package/src/render/default-screens.tsx +299 -0
- package/src/render/digest.ts +71 -0
- package/src/render/element.tsx +119 -0
- package/src/render/index.ts +867 -0
- package/src/render/loaders.ts +127 -0
- package/src/render/shell.ts +187 -0
- package/src/render/template.ts +55 -0
- package/src/router.ts +779 -0
- package/src/runtime-env.ts +6 -0
- package/src/utils.ts +68 -0
package/dist/furin.js
ADDED
|
@@ -0,0 +1,3948 @@
|
|
|
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/context-logger.ts
|
|
1125
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
1126
|
+
function useLogger3() {
|
|
1127
|
+
try {
|
|
1128
|
+
return useLogger2();
|
|
1129
|
+
} catch {
|
|
1130
|
+
return syntheticRenderStorage.getStore() ?? noopLogger2;
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
async function runInSyntheticRenderScope(fn, initialContext) {
|
|
1134
|
+
const logger = createLogger(initialContext);
|
|
1135
|
+
try {
|
|
1136
|
+
const result = await syntheticRenderStorage.run(logger, () => Promise.resolve(fn()));
|
|
1137
|
+
logger.emit();
|
|
1138
|
+
return result;
|
|
1139
|
+
} catch (err) {
|
|
1140
|
+
logger.error(err instanceof Error ? err : new Error(String(err)));
|
|
1141
|
+
logger.emit();
|
|
1142
|
+
throw err;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
var noopLogger2, syntheticRenderStorage;
|
|
1146
|
+
var init_context_logger = __esm(() => {
|
|
1147
|
+
init_dist();
|
|
1148
|
+
init_elysia();
|
|
1149
|
+
noopLogger2 = {
|
|
1150
|
+
set: () => {},
|
|
1151
|
+
error: () => {},
|
|
1152
|
+
info: () => {},
|
|
1153
|
+
warn: () => {},
|
|
1154
|
+
emit: () => null,
|
|
1155
|
+
getContext: () => ({}),
|
|
1156
|
+
fork: (_label, fn) => fn()
|
|
1157
|
+
};
|
|
1158
|
+
syntheticRenderStorage = new AsyncLocalStorage2;
|
|
1159
|
+
});
|
|
1160
|
+
|
|
1161
|
+
// src/render/cache.ts
|
|
1162
|
+
import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
|
|
1163
|
+
function evictOldest(map, maxSize) {
|
|
1164
|
+
if (map.size > maxSize) {
|
|
1165
|
+
const oldest = map.keys().next().value;
|
|
1166
|
+
if (oldest !== undefined) {
|
|
1167
|
+
map.delete(oldest);
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
function getISRCache(key) {
|
|
1172
|
+
const entry = isrCache.get(key);
|
|
1173
|
+
if (entry !== undefined) {
|
|
1174
|
+
isrCache.delete(key);
|
|
1175
|
+
isrCache.set(key, entry);
|
|
1176
|
+
}
|
|
1177
|
+
return entry;
|
|
1178
|
+
}
|
|
1179
|
+
function getSSGCache(key) {
|
|
1180
|
+
const entry = ssgCache.get(key);
|
|
1181
|
+
if (entry !== undefined) {
|
|
1182
|
+
ssgCache.delete(key);
|
|
1183
|
+
ssgCache.set(key, entry);
|
|
1184
|
+
}
|
|
1185
|
+
return entry;
|
|
1186
|
+
}
|
|
1187
|
+
function setISRCache(key, entry) {
|
|
1188
|
+
isrCache.delete(key);
|
|
1189
|
+
isrCache.set(key, entry);
|
|
1190
|
+
evictOldest(isrCache, MAX_ISR_CACHE_SIZE);
|
|
1191
|
+
}
|
|
1192
|
+
function setSSGCache(key, entry) {
|
|
1193
|
+
ssgCache.delete(key);
|
|
1194
|
+
ssgCache.set(key, entry);
|
|
1195
|
+
evictOldest(ssgCache, MAX_SSG_CACHE_SIZE);
|
|
1196
|
+
}
|
|
1197
|
+
function setBuildId(id) {
|
|
1198
|
+
_buildId = id;
|
|
1199
|
+
}
|
|
1200
|
+
function getBuildId() {
|
|
1201
|
+
return _buildId;
|
|
1202
|
+
}
|
|
1203
|
+
function _activeInvalidationSet() {
|
|
1204
|
+
return _requestInvalidationScope.getStore() ?? _globalPendingInvalidations;
|
|
1205
|
+
}
|
|
1206
|
+
function _runWithRequestInvalidationScope(fn) {
|
|
1207
|
+
return _requestInvalidationScope.run(new Set, fn);
|
|
1208
|
+
}
|
|
1209
|
+
function consumePendingInvalidations() {
|
|
1210
|
+
const set = _activeInvalidationSet();
|
|
1211
|
+
if (set.size === 0) {
|
|
1212
|
+
return [];
|
|
1213
|
+
}
|
|
1214
|
+
const paths = [...set];
|
|
1215
|
+
set.clear();
|
|
1216
|
+
return paths;
|
|
1217
|
+
}
|
|
1218
|
+
function setCachePurger(fn) {
|
|
1219
|
+
_cachePurger = fn;
|
|
1220
|
+
}
|
|
1221
|
+
function callCachePurger(paths) {
|
|
1222
|
+
if (!_cachePurger || paths.length === 0) {
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
1225
|
+
_cachePurger(paths).catch((err) => {
|
|
1226
|
+
const logger = createLogger({});
|
|
1227
|
+
logger.set({
|
|
1228
|
+
furin: {
|
|
1229
|
+
action: "cdn_purge_failed",
|
|
1230
|
+
paths
|
|
1231
|
+
}
|
|
1232
|
+
});
|
|
1233
|
+
logger.error(err instanceof Error ? err : new Error(String(err)));
|
|
1234
|
+
logger.emit();
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
function revalidatePath(path, type = "page") {
|
|
1238
|
+
_activeInvalidationSet().add(type === "layout" ? `${path}:layout` : path);
|
|
1239
|
+
let deleted = false;
|
|
1240
|
+
if (type === "page") {
|
|
1241
|
+
deleted = isrCache.delete(path) || deleted;
|
|
1242
|
+
deleted = ssgCache.delete(path) || deleted;
|
|
1243
|
+
callCachePurger([path]);
|
|
1244
|
+
return deleted;
|
|
1245
|
+
}
|
|
1246
|
+
const prefix = path === "/" || path.endsWith("/") ? path : `${path}/`;
|
|
1247
|
+
const purgedPaths = [];
|
|
1248
|
+
for (const key of isrCache.keys()) {
|
|
1249
|
+
if (key === path || key.startsWith(prefix)) {
|
|
1250
|
+
isrCache.delete(key);
|
|
1251
|
+
deleted = true;
|
|
1252
|
+
purgedPaths.push(key);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
for (const key of ssgCache.keys()) {
|
|
1256
|
+
if (key === path || key.startsWith(prefix)) {
|
|
1257
|
+
ssgCache.delete(key);
|
|
1258
|
+
deleted = true;
|
|
1259
|
+
if (!purgedPaths.includes(key)) {
|
|
1260
|
+
purgedPaths.push(key);
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
callCachePurger(purgedPaths.length > 0 ? purgedPaths : [path]);
|
|
1265
|
+
return deleted;
|
|
1266
|
+
}
|
|
1267
|
+
var MAX_ISR_CACHE_SIZE = 1000, MAX_SSG_CACHE_SIZE = 1000, isrCache, ssgCache, _buildId = "", _requestInvalidationScope, _globalPendingInvalidations, _cachePurger = null;
|
|
1268
|
+
var init_cache = __esm(() => {
|
|
1269
|
+
init_context_logger();
|
|
1270
|
+
isrCache = new Map;
|
|
1271
|
+
ssgCache = new Map;
|
|
1272
|
+
_requestInvalidationScope = new AsyncLocalStorage3;
|
|
1273
|
+
_globalPendingInvalidations = new Set;
|
|
1274
|
+
});
|
|
1275
|
+
|
|
1276
|
+
// src/error.ts
|
|
1277
|
+
function getPublicErrorMessage(error) {
|
|
1278
|
+
const branded = error;
|
|
1279
|
+
if (branded?.__furinBrand === "FURIN_NOT_FOUND") {
|
|
1280
|
+
return error.message;
|
|
1281
|
+
}
|
|
1282
|
+
return "Something went wrong";
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
// src/not-found.ts
|
|
1286
|
+
function notFound(options) {
|
|
1287
|
+
throw new FurinNotFoundError(options);
|
|
1288
|
+
}
|
|
1289
|
+
function isNotFoundError(err) {
|
|
1290
|
+
return err instanceof FurinNotFoundError || typeof err === "object" && err !== null && err.__furinBrand === NOT_FOUND_BRAND;
|
|
1291
|
+
}
|
|
1292
|
+
var NOT_FOUND_BRAND = "FURIN_NOT_FOUND", FurinNotFoundError;
|
|
1293
|
+
var init_not_found = __esm(() => {
|
|
1294
|
+
FurinNotFoundError = class FurinNotFoundError extends Error {
|
|
1295
|
+
__furinBrand = NOT_FOUND_BRAND;
|
|
1296
|
+
data;
|
|
1297
|
+
constructor(options) {
|
|
1298
|
+
super(options?.message ?? "");
|
|
1299
|
+
this.data = options?.data;
|
|
1300
|
+
}
|
|
1301
|
+
};
|
|
1302
|
+
});
|
|
1303
|
+
|
|
1304
|
+
// src/render/default-screens.tsx
|
|
1305
|
+
import { jsxDEV } from "react/jsx-dev-runtime";
|
|
1306
|
+
function CornerBracket({ corner }) {
|
|
1307
|
+
const top = corner === "tl" || corner === "tr";
|
|
1308
|
+
const left = corner === "tl" || corner === "bl";
|
|
1309
|
+
const style = {
|
|
1310
|
+
...BRACKET_BASE,
|
|
1311
|
+
[top ? "top" : "bottom"]: 0,
|
|
1312
|
+
[left ? "left" : "right"]: 0,
|
|
1313
|
+
[`border${top ? "Top" : "Bottom"}`]: `2px solid ${COLOR_BRACKET}`,
|
|
1314
|
+
[`border${left ? "Left" : "Right"}`]: `2px solid ${COLOR_BRACKET}`
|
|
1315
|
+
};
|
|
1316
|
+
return /* @__PURE__ */ jsxDEV("span", {
|
|
1317
|
+
"aria-hidden": "true",
|
|
1318
|
+
style
|
|
1319
|
+
}, undefined, false, undefined, this);
|
|
1320
|
+
}
|
|
1321
|
+
function ScreenFrame({ badge, children }) {
|
|
1322
|
+
return /* @__PURE__ */ jsxDEV("div", {
|
|
1323
|
+
style: PAGE_STYLE,
|
|
1324
|
+
children: [
|
|
1325
|
+
/* @__PURE__ */ jsxDEV("style", {
|
|
1326
|
+
dangerouslySetInnerHTML: { __html: RESET_CSS }
|
|
1327
|
+
}, undefined, false, undefined, this),
|
|
1328
|
+
/* @__PURE__ */ jsxDEV("div", {
|
|
1329
|
+
style: FRAME_STYLE,
|
|
1330
|
+
children: [
|
|
1331
|
+
/* @__PURE__ */ jsxDEV(CornerBracket, {
|
|
1332
|
+
corner: "tl"
|
|
1333
|
+
}, undefined, false, undefined, this),
|
|
1334
|
+
/* @__PURE__ */ jsxDEV(CornerBracket, {
|
|
1335
|
+
corner: "tr"
|
|
1336
|
+
}, undefined, false, undefined, this),
|
|
1337
|
+
/* @__PURE__ */ jsxDEV(CornerBracket, {
|
|
1338
|
+
corner: "bl"
|
|
1339
|
+
}, undefined, false, undefined, this),
|
|
1340
|
+
/* @__PURE__ */ jsxDEV(CornerBracket, {
|
|
1341
|
+
corner: "br"
|
|
1342
|
+
}, undefined, false, undefined, this),
|
|
1343
|
+
/* @__PURE__ */ jsxDEV("div", {
|
|
1344
|
+
style: CARD_STYLE,
|
|
1345
|
+
children: [
|
|
1346
|
+
badge,
|
|
1347
|
+
/* @__PURE__ */ jsxDEV("hr", {
|
|
1348
|
+
style: DIVIDER_STYLE
|
|
1349
|
+
}, undefined, false, undefined, this),
|
|
1350
|
+
children
|
|
1351
|
+
]
|
|
1352
|
+
}, undefined, true, undefined, this)
|
|
1353
|
+
]
|
|
1354
|
+
}, undefined, true, undefined, this)
|
|
1355
|
+
]
|
|
1356
|
+
}, undefined, true, undefined, this);
|
|
1357
|
+
}
|
|
1358
|
+
function DefaultErrorScreen({ message, digest, reset }) {
|
|
1359
|
+
return /* @__PURE__ */ jsxDEV(ScreenFrame, {
|
|
1360
|
+
badge: /* @__PURE__ */ jsxDEV("div", {
|
|
1361
|
+
style: BADGE_STYLE,
|
|
1362
|
+
children: "500 \u2014 ERROR"
|
|
1363
|
+
}, undefined, false, undefined, this),
|
|
1364
|
+
children: [
|
|
1365
|
+
/* @__PURE__ */ jsxDEV("h1", {
|
|
1366
|
+
style: HEADING_STYLE,
|
|
1367
|
+
children: "Something went wrong"
|
|
1368
|
+
}, undefined, false, undefined, this),
|
|
1369
|
+
/* @__PURE__ */ jsxDEV("div", {
|
|
1370
|
+
style: CODE_BOX_STYLE,
|
|
1371
|
+
children: [
|
|
1372
|
+
/* @__PURE__ */ jsxDEV("span", {
|
|
1373
|
+
style: CODE_LABEL_STYLE,
|
|
1374
|
+
children: "CODE:"
|
|
1375
|
+
}, undefined, false, undefined, this),
|
|
1376
|
+
/* @__PURE__ */ jsxDEV("span", {
|
|
1377
|
+
children: digest
|
|
1378
|
+
}, undefined, false, undefined, this)
|
|
1379
|
+
]
|
|
1380
|
+
}, undefined, true, undefined, this),
|
|
1381
|
+
/* @__PURE__ */ jsxDEV("p", {
|
|
1382
|
+
style: DESCRIPTION_WRAPPER_STYLE,
|
|
1383
|
+
children: message ? message : "We encountered an unexpected error. Please try again or return to the home page."
|
|
1384
|
+
}, undefined, false, undefined, this),
|
|
1385
|
+
/* @__PURE__ */ jsxDEV("div", {
|
|
1386
|
+
style: ACTIONS_STYLE,
|
|
1387
|
+
children: [
|
|
1388
|
+
/* @__PURE__ */ jsxDEV(Link, {
|
|
1389
|
+
style: BUTTON_PRIMARY,
|
|
1390
|
+
to: "/",
|
|
1391
|
+
children: "Go Home"
|
|
1392
|
+
}, undefined, false, undefined, this),
|
|
1393
|
+
/* @__PURE__ */ jsxDEV("button", {
|
|
1394
|
+
onClick: reset,
|
|
1395
|
+
style: BUTTON_SECONDARY,
|
|
1396
|
+
type: "button",
|
|
1397
|
+
children: "Try again"
|
|
1398
|
+
}, undefined, false, undefined, this)
|
|
1399
|
+
]
|
|
1400
|
+
}, undefined, true, undefined, this)
|
|
1401
|
+
]
|
|
1402
|
+
}, undefined, true, undefined, this);
|
|
1403
|
+
}
|
|
1404
|
+
function DefaultNotFoundScreen({ message }) {
|
|
1405
|
+
return /* @__PURE__ */ jsxDEV(ScreenFrame, {
|
|
1406
|
+
badge: /* @__PURE__ */ jsxDEV("div", {
|
|
1407
|
+
style: NOT_FOUND_BADGE_STYLE,
|
|
1408
|
+
children: "404 \u2014 NOT FOUND"
|
|
1409
|
+
}, undefined, false, undefined, this),
|
|
1410
|
+
children: [
|
|
1411
|
+
/* @__PURE__ */ jsxDEV("h1", {
|
|
1412
|
+
style: HEADING_STYLE,
|
|
1413
|
+
children: "This page does not exist"
|
|
1414
|
+
}, undefined, false, undefined, this),
|
|
1415
|
+
/* @__PURE__ */ jsxDEV("p", {
|
|
1416
|
+
style: DESCRIPTION_WRAPPER_STYLE,
|
|
1417
|
+
children: message ? message : "The page you are looking for could not be found. It may have been moved or removed."
|
|
1418
|
+
}, undefined, false, undefined, this),
|
|
1419
|
+
/* @__PURE__ */ jsxDEV("div", {
|
|
1420
|
+
style: ACTIONS_STYLE,
|
|
1421
|
+
children: /* @__PURE__ */ jsxDEV(Link, {
|
|
1422
|
+
style: BUTTON_PRIMARY,
|
|
1423
|
+
to: "/",
|
|
1424
|
+
children: "Go Home"
|
|
1425
|
+
}, undefined, false, undefined, this)
|
|
1426
|
+
}, undefined, false, undefined, this)
|
|
1427
|
+
]
|
|
1428
|
+
}, undefined, true, undefined, this);
|
|
1429
|
+
}
|
|
1430
|
+
var FONT_SANS = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif', FONT_MONO = 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace', COLOR_BG = "#000000", COLOR_TEXT = "#ffffff", COLOR_TEXT_DIM = "rgba(255, 255, 255, 0.7)", COLOR_TEXT_MUTED = "rgba(255, 255, 255, 0.45)", COLOR_GRID = "rgba(255, 255, 255, 0.04)", COLOR_BRACKET = "rgba(255, 255, 255, 0.55)", COLOR_DANGER_DIM = "rgba(239, 68, 68, 0.6)", PAGE_STYLE, FRAME_STYLE, BRACKET_BASE, CARD_STYLE, BADGE_STYLE, NOT_FOUND_BADGE_STYLE, HEADING_STYLE, CODE_BOX_STYLE, CODE_LABEL_STYLE, DESCRIPTION_WRAPPER_STYLE, ACTIONS_STYLE, BUTTON_BASE, BUTTON_PRIMARY, BUTTON_SECONDARY, DIVIDER_STYLE, RESET_CSS;
|
|
1431
|
+
var init_default_screens = __esm(() => {
|
|
1432
|
+
init_link();
|
|
1433
|
+
PAGE_STYLE = {
|
|
1434
|
+
alignItems: "center",
|
|
1435
|
+
backgroundColor: COLOR_BG,
|
|
1436
|
+
backgroundImage: `
|
|
1437
|
+
linear-gradient(${COLOR_GRID} 1px, transparent 1px),
|
|
1438
|
+
linear-gradient(90deg, ${COLOR_GRID} 1px, transparent 1px)
|
|
1439
|
+
`,
|
|
1440
|
+
backgroundSize: "32px 32px, 32px 32px",
|
|
1441
|
+
boxSizing: "border-box",
|
|
1442
|
+
color: COLOR_TEXT,
|
|
1443
|
+
display: "flex",
|
|
1444
|
+
fontFamily: FONT_SANS,
|
|
1445
|
+
fontSize: "16px",
|
|
1446
|
+
justifyContent: "center",
|
|
1447
|
+
lineHeight: 1.5,
|
|
1448
|
+
margin: 0,
|
|
1449
|
+
minHeight: "100vh",
|
|
1450
|
+
padding: "32px",
|
|
1451
|
+
width: "100%"
|
|
1452
|
+
};
|
|
1453
|
+
FRAME_STYLE = {
|
|
1454
|
+
boxSizing: "border-box",
|
|
1455
|
+
maxWidth: "880px",
|
|
1456
|
+
position: "relative",
|
|
1457
|
+
width: "100%"
|
|
1458
|
+
};
|
|
1459
|
+
BRACKET_BASE = {
|
|
1460
|
+
height: "40px",
|
|
1461
|
+
position: "absolute",
|
|
1462
|
+
width: "40px"
|
|
1463
|
+
};
|
|
1464
|
+
CARD_STYLE = {
|
|
1465
|
+
boxSizing: "border-box",
|
|
1466
|
+
margin: "0 auto",
|
|
1467
|
+
maxWidth: "640px",
|
|
1468
|
+
padding: "64px 24px",
|
|
1469
|
+
textAlign: "center"
|
|
1470
|
+
};
|
|
1471
|
+
BADGE_STYLE = {
|
|
1472
|
+
border: `1px solid ${COLOR_DANGER_DIM}`,
|
|
1473
|
+
color: COLOR_TEXT,
|
|
1474
|
+
display: "inline-block",
|
|
1475
|
+
fontFamily: FONT_SANS,
|
|
1476
|
+
fontSize: "32px",
|
|
1477
|
+
fontWeight: 600,
|
|
1478
|
+
letterSpacing: "0.08em",
|
|
1479
|
+
marginBottom: "16px",
|
|
1480
|
+
padding: "12px 36px"
|
|
1481
|
+
};
|
|
1482
|
+
NOT_FOUND_BADGE_STYLE = {
|
|
1483
|
+
...BADGE_STYLE,
|
|
1484
|
+
border: 0,
|
|
1485
|
+
padding: 0
|
|
1486
|
+
};
|
|
1487
|
+
HEADING_STYLE = {
|
|
1488
|
+
color: COLOR_TEXT,
|
|
1489
|
+
fontFamily: FONT_SANS,
|
|
1490
|
+
fontSize: "24px",
|
|
1491
|
+
fontWeight: 600,
|
|
1492
|
+
margin: "0 0 24px 0"
|
|
1493
|
+
};
|
|
1494
|
+
CODE_BOX_STYLE = {
|
|
1495
|
+
color: COLOR_TEXT_DIM,
|
|
1496
|
+
display: "inline-block",
|
|
1497
|
+
fontFamily: FONT_MONO,
|
|
1498
|
+
fontSize: "13px",
|
|
1499
|
+
letterSpacing: "0.02em",
|
|
1500
|
+
margin: "0 0 32px 0",
|
|
1501
|
+
padding: "8px 0"
|
|
1502
|
+
};
|
|
1503
|
+
CODE_LABEL_STYLE = {
|
|
1504
|
+
color: COLOR_TEXT_MUTED,
|
|
1505
|
+
marginRight: "10px",
|
|
1506
|
+
textTransform: "uppercase"
|
|
1507
|
+
};
|
|
1508
|
+
DESCRIPTION_WRAPPER_STYLE = {
|
|
1509
|
+
color: COLOR_TEXT_DIM,
|
|
1510
|
+
fontSize: "15px",
|
|
1511
|
+
margin: "0 auto 40px auto",
|
|
1512
|
+
maxWidth: "440px",
|
|
1513
|
+
padding: 0,
|
|
1514
|
+
textAlign: "center"
|
|
1515
|
+
};
|
|
1516
|
+
ACTIONS_STYLE = {
|
|
1517
|
+
display: "flex",
|
|
1518
|
+
flexWrap: "wrap",
|
|
1519
|
+
gap: "16px",
|
|
1520
|
+
justifyContent: "center"
|
|
1521
|
+
};
|
|
1522
|
+
BUTTON_BASE = {
|
|
1523
|
+
border: 0,
|
|
1524
|
+
cursor: "pointer",
|
|
1525
|
+
display: "inline-flex",
|
|
1526
|
+
fontFamily: FONT_SANS,
|
|
1527
|
+
fontSize: "14px",
|
|
1528
|
+
fontWeight: 500,
|
|
1529
|
+
lineHeight: 1,
|
|
1530
|
+
minWidth: "120px",
|
|
1531
|
+
padding: "10px 16px",
|
|
1532
|
+
textAlign: "center",
|
|
1533
|
+
textDecoration: "none",
|
|
1534
|
+
transition: "background-color 120ms ease, color 120ms ease, opacity 120ms ease",
|
|
1535
|
+
appearance: "none",
|
|
1536
|
+
alignItems: "center",
|
|
1537
|
+
justifyContent: "center",
|
|
1538
|
+
boxSizing: "border-box"
|
|
1539
|
+
};
|
|
1540
|
+
BUTTON_PRIMARY = {
|
|
1541
|
+
...BUTTON_BASE,
|
|
1542
|
+
backgroundColor: COLOR_TEXT,
|
|
1543
|
+
border: `1px solid ${COLOR_TEXT}`,
|
|
1544
|
+
boxShadow: "0 10px 24px rgba(255, 255, 255, 0.08)",
|
|
1545
|
+
color: COLOR_BG,
|
|
1546
|
+
fontWeight: 600
|
|
1547
|
+
};
|
|
1548
|
+
BUTTON_SECONDARY = {
|
|
1549
|
+
...BUTTON_BASE,
|
|
1550
|
+
backgroundColor: "transparent",
|
|
1551
|
+
border: "1px solid rgba(255, 255, 255, 0.22)",
|
|
1552
|
+
color: COLOR_TEXT_DIM
|
|
1553
|
+
};
|
|
1554
|
+
DIVIDER_STYLE = {
|
|
1555
|
+
backgroundColor: "rgba(255, 255, 255, 0.12)",
|
|
1556
|
+
border: 0,
|
|
1557
|
+
height: "1px",
|
|
1558
|
+
margin: "0 0 40px 0",
|
|
1559
|
+
width: "100%"
|
|
1560
|
+
};
|
|
1561
|
+
RESET_CSS = `
|
|
1562
|
+
html, body {
|
|
1563
|
+
margin: 0;
|
|
1564
|
+
padding: 0;
|
|
1565
|
+
background-color: ${COLOR_BG};
|
|
1566
|
+
overscroll-behavior: none;
|
|
1567
|
+
}
|
|
1568
|
+
`;
|
|
1569
|
+
});
|
|
1570
|
+
|
|
1571
|
+
// src/render/digest.ts
|
|
1572
|
+
function computeErrorDigest(err) {
|
|
1573
|
+
let message = "";
|
|
1574
|
+
let stack = "";
|
|
1575
|
+
if (err instanceof Error) {
|
|
1576
|
+
message = err.message;
|
|
1577
|
+
stack = err.stack ?? "";
|
|
1578
|
+
} else if (typeof err === "string") {
|
|
1579
|
+
message = err;
|
|
1580
|
+
} else {
|
|
1581
|
+
try {
|
|
1582
|
+
message = JSON.stringify(err) ?? String(err);
|
|
1583
|
+
} catch {
|
|
1584
|
+
message = String(err);
|
|
1585
|
+
}
|
|
1586
|
+
}
|
|
1587
|
+
const input = `${message}
|
|
1588
|
+
${stack}`;
|
|
1589
|
+
const hash = cyrb53(input);
|
|
1590
|
+
const hex = hash.toString(16).padStart(14, "0");
|
|
1591
|
+
return hex.slice(0, 10);
|
|
1592
|
+
}
|
|
1593
|
+
function cyrb53(input) {
|
|
1594
|
+
let h1 = 3735928559;
|
|
1595
|
+
let h2 = 1103547991;
|
|
1596
|
+
for (let i = 0;i < input.length; i++) {
|
|
1597
|
+
const ch = input.charCodeAt(i);
|
|
1598
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
1599
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
1600
|
+
}
|
|
1601
|
+
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
|
|
1602
|
+
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
|
|
1603
|
+
return 4294967296 * (2097151 & h2) + (4294967295 & h1);
|
|
1604
|
+
}
|
|
1605
|
+
|
|
1606
|
+
// src/render/boundaries.tsx
|
|
1607
|
+
import { Component, Fragment } from "react";
|
|
1608
|
+
import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
|
|
1609
|
+
var DefaultErrorFallback = ({ error, reset }) => /* @__PURE__ */ jsxDEV2(DefaultErrorScreen, {
|
|
1610
|
+
digest: error.digest,
|
|
1611
|
+
message: error.message,
|
|
1612
|
+
reset
|
|
1613
|
+
}, undefined, false, undefined, this), DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV2(DefaultNotFoundScreen, {
|
|
1614
|
+
message: error.message
|
|
1615
|
+
}, undefined, false, undefined, this), SERVER_RESET_NOOP = () => {}, FurinErrorBoundary, FurinNotFoundBoundary;
|
|
1616
|
+
var init_boundaries = __esm(() => {
|
|
1617
|
+
init_not_found();
|
|
1618
|
+
init_default_screens();
|
|
1619
|
+
FurinErrorBoundary = class FurinErrorBoundary extends Component {
|
|
1620
|
+
state = {
|
|
1621
|
+
digest: null,
|
|
1622
|
+
epoch: 0,
|
|
1623
|
+
error: null
|
|
1624
|
+
};
|
|
1625
|
+
static getDerivedStateFromError(error) {
|
|
1626
|
+
return { digest: computeErrorDigest(error), error };
|
|
1627
|
+
}
|
|
1628
|
+
componentDidUpdate(prevProps) {
|
|
1629
|
+
if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
|
|
1630
|
+
this.reset();
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
reset = () => {
|
|
1634
|
+
this.setState((s) => ({ digest: null, epoch: s.epoch + 1, error: null }), () => {
|
|
1635
|
+
this.props.onReset?.();
|
|
1636
|
+
});
|
|
1637
|
+
};
|
|
1638
|
+
render() {
|
|
1639
|
+
const { error, epoch, digest } = this.state;
|
|
1640
|
+
if (error) {
|
|
1641
|
+
if (isNotFoundError(error)) {
|
|
1642
|
+
throw error;
|
|
1643
|
+
}
|
|
1644
|
+
const Fallback = this.props.fallback ?? DefaultErrorFallback;
|
|
1645
|
+
const finalDigest = digest ?? this.props.digest ?? computeErrorDigest(error);
|
|
1646
|
+
const message = this.props.fallback ? error.message : getPublicErrorMessage(error);
|
|
1647
|
+
return /* @__PURE__ */ jsxDEV2(Fallback, {
|
|
1648
|
+
error: { message, digest: finalDigest },
|
|
1649
|
+
reset: typeof window === "undefined" ? SERVER_RESET_NOOP : this.reset
|
|
1650
|
+
}, undefined, false, undefined, this);
|
|
1651
|
+
}
|
|
1652
|
+
return /* @__PURE__ */ jsxDEV2(Fragment, {
|
|
1653
|
+
children: this.props.children
|
|
1654
|
+
}, epoch, false, undefined, this);
|
|
1655
|
+
}
|
|
1656
|
+
};
|
|
1657
|
+
FurinNotFoundBoundary = class FurinNotFoundBoundary extends Component {
|
|
1658
|
+
state = { epoch: 0, error: null };
|
|
1659
|
+
static getDerivedStateFromError(error) {
|
|
1660
|
+
return { error };
|
|
1661
|
+
}
|
|
1662
|
+
componentDidUpdate(prevProps) {
|
|
1663
|
+
if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
|
|
1664
|
+
this.setState((s) => ({ error: null, epoch: s.epoch + 1 }));
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
render() {
|
|
1668
|
+
const { error, epoch } = this.state;
|
|
1669
|
+
if (error) {
|
|
1670
|
+
if (!isNotFoundError(error)) {
|
|
1671
|
+
throw error;
|
|
1672
|
+
}
|
|
1673
|
+
const Fallback = this.props.fallback ?? DefaultNotFoundFallback;
|
|
1674
|
+
return /* @__PURE__ */ jsxDEV2(Fallback, {
|
|
1675
|
+
error: { message: error.message, data: error.data }
|
|
1676
|
+
}, undefined, false, undefined, this);
|
|
1677
|
+
}
|
|
1678
|
+
return /* @__PURE__ */ jsxDEV2(Fragment, {
|
|
1679
|
+
children: this.props.children
|
|
1680
|
+
}, epoch, false, undefined, this);
|
|
1681
|
+
}
|
|
1682
|
+
};
|
|
1683
|
+
});
|
|
1684
|
+
|
|
1685
|
+
// src/link.tsx
|
|
1686
|
+
import {
|
|
1687
|
+
createContext,
|
|
1688
|
+
createElement,
|
|
1689
|
+
useCallback,
|
|
1690
|
+
useContext,
|
|
1691
|
+
useEffect,
|
|
1692
|
+
useMemo,
|
|
1693
|
+
useRef,
|
|
1694
|
+
useState
|
|
1695
|
+
} from "react";
|
|
1696
|
+
import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
|
|
1697
|
+
function buildHref(to, search, hash) {
|
|
1698
|
+
let url = to;
|
|
1699
|
+
if (search && Object.keys(search).length > 0) {
|
|
1700
|
+
const params = new URLSearchParams;
|
|
1701
|
+
for (const [k, v] of Object.entries(search)) {
|
|
1702
|
+
if (v != null) {
|
|
1703
|
+
params.set(k, String(v));
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
const qs = params.toString();
|
|
1707
|
+
if (qs) {
|
|
1708
|
+
url += `?${qs}`;
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
if (hash) {
|
|
1712
|
+
url += `#${hash}`;
|
|
1713
|
+
}
|
|
1714
|
+
return url;
|
|
1715
|
+
}
|
|
1716
|
+
function useRouter() {
|
|
1717
|
+
return useContext(RouterContext) ?? {
|
|
1718
|
+
basePath: "",
|
|
1719
|
+
currentHref: "/",
|
|
1720
|
+
navigate: (href) => {
|
|
1721
|
+
window.location.href = href;
|
|
1722
|
+
return Promise.resolve();
|
|
1723
|
+
},
|
|
1724
|
+
prefetch: () => {},
|
|
1725
|
+
invalidatePrefetch: () => {},
|
|
1726
|
+
refresh: () => {
|
|
1727
|
+
window.location.reload();
|
|
1728
|
+
return Promise.resolve();
|
|
1729
|
+
},
|
|
1730
|
+
isNavigating: false,
|
|
1731
|
+
defaultPreload: "intent",
|
|
1732
|
+
defaultPreloadDelay: 50,
|
|
1733
|
+
defaultPreloadStaleTime: 30000
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
function computeLinkView({
|
|
1737
|
+
to,
|
|
1738
|
+
search,
|
|
1739
|
+
hash,
|
|
1740
|
+
children,
|
|
1741
|
+
activeProps,
|
|
1742
|
+
inactiveProps
|
|
1743
|
+
}, router) {
|
|
1744
|
+
const logicalHref = buildHref(to, search, hash);
|
|
1745
|
+
const logicalHrefWithoutHash = buildHref(to, search, undefined);
|
|
1746
|
+
const href = router.basePath + logicalHref;
|
|
1747
|
+
const isActive = router.currentHref === logicalHrefWithoutHash;
|
|
1748
|
+
const resolvedChildren = typeof children === "function" ? children({ isActive }) : children;
|
|
1749
|
+
const extraProps = {
|
|
1750
|
+
...inactiveProps && !isActive ? inactiveProps() : {},
|
|
1751
|
+
...activeProps ? activeProps({ isActive }) : {}
|
|
1752
|
+
};
|
|
1753
|
+
return { logicalHref, href, isActive, resolvedChildren, extraProps };
|
|
1754
|
+
}
|
|
1755
|
+
function LinkInteractive({
|
|
1756
|
+
to,
|
|
1757
|
+
search,
|
|
1758
|
+
hash,
|
|
1759
|
+
preload,
|
|
1760
|
+
preloadDelay,
|
|
1761
|
+
preloadStaleTime,
|
|
1762
|
+
replace,
|
|
1763
|
+
disabled,
|
|
1764
|
+
resetScroll,
|
|
1765
|
+
activeProps,
|
|
1766
|
+
inactiveProps,
|
|
1767
|
+
onClick,
|
|
1768
|
+
onMouseEnter,
|
|
1769
|
+
onMouseLeave,
|
|
1770
|
+
onFocus,
|
|
1771
|
+
children,
|
|
1772
|
+
...anchorProps
|
|
1773
|
+
}) {
|
|
1774
|
+
const router = useRouter();
|
|
1775
|
+
const anchorRef = useRef(null);
|
|
1776
|
+
const intentTimerRef = useRef(null);
|
|
1777
|
+
const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ to, search, hash, children, activeProps, inactiveProps }, router);
|
|
1778
|
+
const effectivePreload = preload ?? router.defaultPreload;
|
|
1779
|
+
const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
|
|
1780
|
+
const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
|
|
1781
|
+
const triggerPrefetch = useCallback(() => {
|
|
1782
|
+
router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
|
|
1783
|
+
}, [router, logicalHref, effectiveStaleTime]);
|
|
1784
|
+
useEffect(() => {
|
|
1785
|
+
if (effectivePreload === "render") {
|
|
1786
|
+
triggerPrefetch();
|
|
1787
|
+
}
|
|
1788
|
+
}, [effectivePreload, triggerPrefetch]);
|
|
1789
|
+
useEffect(() => {
|
|
1790
|
+
if (effectivePreload !== "viewport" || !anchorRef.current) {
|
|
1791
|
+
return;
|
|
1792
|
+
}
|
|
1793
|
+
const observer = new IntersectionObserver(([entry]) => {
|
|
1794
|
+
if (entry?.isIntersecting) {
|
|
1795
|
+
triggerPrefetch();
|
|
1796
|
+
observer.disconnect();
|
|
1797
|
+
}
|
|
1798
|
+
}, { rootMargin: "200px" });
|
|
1799
|
+
observer.observe(anchorRef.current);
|
|
1800
|
+
return () => observer.disconnect();
|
|
1801
|
+
}, [effectivePreload, triggerPrefetch]);
|
|
1802
|
+
const isInternal = (url) => {
|
|
1803
|
+
try {
|
|
1804
|
+
return new URL(url, window.location.origin).origin === window.location.origin;
|
|
1805
|
+
} catch {
|
|
1806
|
+
return false;
|
|
1807
|
+
}
|
|
1808
|
+
};
|
|
1809
|
+
const handleClick = (e) => {
|
|
1810
|
+
onClick?.(e);
|
|
1811
|
+
if (e.defaultPrevented || disabled) {
|
|
1812
|
+
return;
|
|
1813
|
+
}
|
|
1814
|
+
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
|
|
1815
|
+
return;
|
|
1816
|
+
}
|
|
1817
|
+
if (anchorProps.target && anchorProps.target !== "_self") {
|
|
1818
|
+
return;
|
|
1819
|
+
}
|
|
1820
|
+
if (!isInternal(href)) {
|
|
1821
|
+
return;
|
|
1822
|
+
}
|
|
1823
|
+
e.preventDefault();
|
|
1824
|
+
router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
|
|
1825
|
+
};
|
|
1826
|
+
const handleMouseEnter = (e) => {
|
|
1827
|
+
onMouseEnter?.(e);
|
|
1828
|
+
if (!disabled && effectivePreload === "intent" && isInternal(href)) {
|
|
1829
|
+
intentTimerRef.current = setTimeout(triggerPrefetch, effectiveDelay);
|
|
1830
|
+
}
|
|
1831
|
+
};
|
|
1832
|
+
const handleMouseLeave = (e) => {
|
|
1833
|
+
onMouseLeave?.(e);
|
|
1834
|
+
if (intentTimerRef.current !== null) {
|
|
1835
|
+
clearTimeout(intentTimerRef.current);
|
|
1836
|
+
intentTimerRef.current = null;
|
|
1837
|
+
}
|
|
1838
|
+
};
|
|
1839
|
+
const handleFocus = (e) => {
|
|
1840
|
+
onFocus?.(e);
|
|
1841
|
+
if (!disabled && effectivePreload === "intent" && isInternal(href)) {
|
|
1842
|
+
triggerPrefetch();
|
|
1843
|
+
}
|
|
1844
|
+
};
|
|
1845
|
+
return createElement("a", {
|
|
1846
|
+
ref: anchorRef,
|
|
1847
|
+
href,
|
|
1848
|
+
onClick: handleClick,
|
|
1849
|
+
onMouseEnter: handleMouseEnter,
|
|
1850
|
+
onMouseLeave: handleMouseLeave,
|
|
1851
|
+
onFocus: handleFocus,
|
|
1852
|
+
...isActive ? { "data-status": "active" } : {},
|
|
1853
|
+
...anchorProps,
|
|
1854
|
+
...extraProps,
|
|
1855
|
+
...disabled ? { "aria-disabled": true } : {}
|
|
1856
|
+
}, resolvedChildren);
|
|
1857
|
+
}
|
|
1858
|
+
function renderLinkElement(props, router) {
|
|
1859
|
+
const { href, isActive, resolvedChildren, extraProps } = computeLinkView(props, router);
|
|
1860
|
+
const {
|
|
1861
|
+
to: _to,
|
|
1862
|
+
search: _search,
|
|
1863
|
+
hash: _hash,
|
|
1864
|
+
children: _children,
|
|
1865
|
+
activeProps: _ap,
|
|
1866
|
+
inactiveProps: _ip,
|
|
1867
|
+
disabled,
|
|
1868
|
+
preload: _p,
|
|
1869
|
+
preloadDelay: _pd,
|
|
1870
|
+
preloadStaleTime: _ps,
|
|
1871
|
+
replace: _r,
|
|
1872
|
+
resetScroll: _rs,
|
|
1873
|
+
onClick: _oc,
|
|
1874
|
+
onMouseEnter: _ome,
|
|
1875
|
+
onMouseLeave: _oml,
|
|
1876
|
+
onFocus: _of,
|
|
1877
|
+
...anchorProps
|
|
1878
|
+
} = props;
|
|
1879
|
+
return createElement("a", {
|
|
1880
|
+
href,
|
|
1881
|
+
...isActive ? { "data-status": "active" } : {},
|
|
1882
|
+
...anchorProps,
|
|
1883
|
+
...extraProps,
|
|
1884
|
+
...disabled ? { "aria-disabled": true } : {}
|
|
1885
|
+
}, resolvedChildren);
|
|
1886
|
+
}
|
|
1887
|
+
function Link(props) {
|
|
1888
|
+
if (typeof window === "undefined") {
|
|
1889
|
+
return createElement(RouterContext.Consumer, {
|
|
1890
|
+
children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
|
|
1891
|
+
});
|
|
1892
|
+
}
|
|
1893
|
+
return createElement(LinkInteractive, props);
|
|
1894
|
+
}
|
|
1895
|
+
var RouterContext, SSR_FALLBACK_ROUTER;
|
|
1896
|
+
var init_link = __esm(() => {
|
|
1897
|
+
init_boundaries();
|
|
1898
|
+
init_default_screens();
|
|
1899
|
+
RouterContext = createContext(null);
|
|
1900
|
+
SSR_FALLBACK_ROUTER = {
|
|
1901
|
+
basePath: "",
|
|
1902
|
+
currentHref: "/",
|
|
1903
|
+
navigate: () => Promise.resolve(),
|
|
1904
|
+
prefetch: () => {},
|
|
1905
|
+
invalidatePrefetch: () => {},
|
|
1906
|
+
refresh: () => Promise.resolve(),
|
|
1907
|
+
isNavigating: false,
|
|
1908
|
+
defaultPreload: "intent",
|
|
1909
|
+
defaultPreloadDelay: 50,
|
|
1910
|
+
defaultPreloadStaleTime: 30000
|
|
1911
|
+
};
|
|
1912
|
+
});
|
|
1913
|
+
|
|
1914
|
+
// src/render/shell.ts
|
|
1915
|
+
function extractTitle(meta) {
|
|
1916
|
+
if (!meta) {
|
|
1917
|
+
return;
|
|
1918
|
+
}
|
|
1919
|
+
for (const entry of meta) {
|
|
1920
|
+
if ("title" in entry) {
|
|
1921
|
+
return entry.title;
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
return;
|
|
1925
|
+
}
|
|
1926
|
+
function isMetaTag(entry) {
|
|
1927
|
+
return !(("title" in entry) || ("charSet" in entry) || ("script:ld+json" in entry) || ("tagName" in entry));
|
|
1928
|
+
}
|
|
1929
|
+
function escapeHtml(str) {
|
|
1930
|
+
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
1931
|
+
}
|
|
1932
|
+
function safeJson(value) {
|
|
1933
|
+
return JSON.stringify(value).replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
1934
|
+
}
|
|
1935
|
+
function renderAttrs(obj) {
|
|
1936
|
+
return Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}="${escapeHtml(String(v))}"`).join(" ");
|
|
1937
|
+
}
|
|
1938
|
+
function buildMetaParts(meta) {
|
|
1939
|
+
const parts = [];
|
|
1940
|
+
const title = extractTitle(meta);
|
|
1941
|
+
if (title) {
|
|
1942
|
+
parts.push(`<title>${escapeHtml(title)}</title>`);
|
|
1943
|
+
}
|
|
1944
|
+
for (const m of meta) {
|
|
1945
|
+
if (isMetaTag(m)) {
|
|
1946
|
+
parts.push(`<meta ${renderAttrs(m)} />`);
|
|
1947
|
+
}
|
|
1948
|
+
if ("script:ld+json" in m) {
|
|
1949
|
+
parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
return parts;
|
|
1953
|
+
}
|
|
1954
|
+
function buildLinkParts(links) {
|
|
1955
|
+
return links.map((link) => `<link ${renderAttrs(link)} />`);
|
|
1956
|
+
}
|
|
1957
|
+
function buildScriptParts(scripts) {
|
|
1958
|
+
return scripts.map((script) => {
|
|
1959
|
+
const { children, ...rest } = script;
|
|
1960
|
+
const attrs = renderAttrs(rest);
|
|
1961
|
+
if (children) {
|
|
1962
|
+
return `<script ${attrs}>${children}</script>`;
|
|
1963
|
+
}
|
|
1964
|
+
return `<script ${attrs}></script>`;
|
|
1965
|
+
});
|
|
1966
|
+
}
|
|
1967
|
+
function buildStyleParts(styles) {
|
|
1968
|
+
return styles.map((style) => {
|
|
1969
|
+
const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
|
|
1970
|
+
return `<style${typeAttr}>${style.children}</style>`;
|
|
1971
|
+
});
|
|
1972
|
+
}
|
|
1973
|
+
function buildHeadInjection(headData) {
|
|
1974
|
+
const parts = [];
|
|
1975
|
+
if (headData?.meta) {
|
|
1976
|
+
parts.push(...buildMetaParts(headData.meta));
|
|
1977
|
+
}
|
|
1978
|
+
if (headData?.links) {
|
|
1979
|
+
parts.push(...buildLinkParts(headData.links));
|
|
1980
|
+
}
|
|
1981
|
+
if (headData?.scripts) {
|
|
1982
|
+
parts.push(...buildScriptParts(headData.scripts));
|
|
1983
|
+
}
|
|
1984
|
+
if (headData?.styles) {
|
|
1985
|
+
parts.push(...buildStyleParts(headData.styles));
|
|
1986
|
+
}
|
|
1987
|
+
return parts.length > 0 ? `
|
|
1988
|
+
${parts.join(`
|
|
1989
|
+
`)}
|
|
1990
|
+
` : "";
|
|
1991
|
+
}
|
|
1992
|
+
function generateIndexHtml() {
|
|
1993
|
+
return `<!DOCTYPE html>
|
|
1994
|
+
<html lang="en">
|
|
1995
|
+
<head>
|
|
1996
|
+
<meta charset="UTF-8">
|
|
1997
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1998
|
+
${THEME_INIT_SCRIPT}
|
|
1999
|
+
<!--ssr-head-->
|
|
2000
|
+
</head>
|
|
2001
|
+
<body>
|
|
2002
|
+
<div id="root"><!--ssr-outlet--></div>
|
|
2003
|
+
<script type="module" src="./_hydrate.tsx"></script>
|
|
2004
|
+
</body>
|
|
2005
|
+
</html>
|
|
2006
|
+
`;
|
|
2007
|
+
}
|
|
2008
|
+
var THEME_INIT_SCRIPT;
|
|
2009
|
+
var init_shell = __esm(() => {
|
|
2010
|
+
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>`;
|
|
2011
|
+
});
|
|
2012
|
+
|
|
2013
|
+
// src/render/assemble.ts
|
|
2014
|
+
function resolvePath(pattern, params) {
|
|
2015
|
+
let path = pattern;
|
|
2016
|
+
for (const [key, val] of Object.entries(params ?? {})) {
|
|
2017
|
+
path = path.replace(key === "*" ? "*" : `:${key}`, val);
|
|
2018
|
+
}
|
|
2019
|
+
return path;
|
|
2020
|
+
}
|
|
2021
|
+
async function streamToString(stream) {
|
|
2022
|
+
const reader = stream.getReader();
|
|
2023
|
+
const decoder = new TextDecoder;
|
|
2024
|
+
let html = "";
|
|
2025
|
+
for (;; ) {
|
|
2026
|
+
const { done, value } = await reader.read();
|
|
2027
|
+
if (done) {
|
|
2028
|
+
break;
|
|
2029
|
+
}
|
|
2030
|
+
html += decoder.decode(value, { stream: true });
|
|
2031
|
+
}
|
|
2032
|
+
html += decoder.decode();
|
|
2033
|
+
return html;
|
|
2034
|
+
}
|
|
2035
|
+
function splitTemplate(template) {
|
|
2036
|
+
const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
|
|
2037
|
+
const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
|
|
2038
|
+
return { headPre, bodyPre, bodyPost };
|
|
2039
|
+
}
|
|
2040
|
+
function assembleHTML(template, headData, reactHtml, data) {
|
|
2041
|
+
const { headPre, bodyPre, bodyPost } = splitTemplate(template);
|
|
2042
|
+
const dataScript = data ? `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>` : "";
|
|
2043
|
+
let injectedBodyPost = bodyPost;
|
|
2044
|
+
if (dataScript) {
|
|
2045
|
+
injectedBodyPost = bodyPost.includes("</body>") ? bodyPost.replace("</body>", `${dataScript}</body>`) : bodyPost + dataScript;
|
|
2046
|
+
}
|
|
2047
|
+
return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
|
|
2048
|
+
}
|
|
2049
|
+
var init_assemble = __esm(() => {
|
|
2050
|
+
init_shell();
|
|
2051
|
+
});
|
|
2052
|
+
|
|
2053
|
+
// src/render/element.tsx
|
|
2054
|
+
import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
|
|
2055
|
+
function wrapInBoundaries(inner, segment) {
|
|
2056
|
+
if (!segment) {
|
|
2057
|
+
return inner;
|
|
2058
|
+
}
|
|
2059
|
+
let wrapped = inner;
|
|
2060
|
+
if (segment.notFound) {
|
|
2061
|
+
wrapped = /* @__PURE__ */ jsxDEV4(FurinNotFoundBoundary, {
|
|
2062
|
+
fallback: segment.notFound,
|
|
2063
|
+
children: wrapped
|
|
2064
|
+
}, undefined, false, undefined, this);
|
|
2065
|
+
}
|
|
2066
|
+
if (segment.error) {
|
|
2067
|
+
wrapped = /* @__PURE__ */ jsxDEV4(FurinErrorBoundary, {
|
|
2068
|
+
fallback: segment.error,
|
|
2069
|
+
children: wrapped
|
|
2070
|
+
}, undefined, false, undefined, this);
|
|
2071
|
+
}
|
|
2072
|
+
return wrapped;
|
|
2073
|
+
}
|
|
2074
|
+
function buildElement(route, data, rootLayout) {
|
|
2075
|
+
const Component2 = route.page.component;
|
|
2076
|
+
let element = /* @__PURE__ */ jsxDEV4(Component2, {
|
|
2077
|
+
...data
|
|
2078
|
+
}, undefined, false, undefined, this);
|
|
2079
|
+
const byDepth = new Map;
|
|
2080
|
+
for (const segment of route.segmentBoundaries ?? []) {
|
|
2081
|
+
byDepth.set(segment.depth, segment);
|
|
2082
|
+
}
|
|
2083
|
+
for (let i = route.routeChain.length - 1;i >= 1; i--) {
|
|
2084
|
+
element = wrapInBoundaries(element, byDepth.get(i));
|
|
2085
|
+
const routeEntry = route.routeChain[i];
|
|
2086
|
+
if (routeEntry?.layout) {
|
|
2087
|
+
const Layout = routeEntry.layout;
|
|
2088
|
+
element = /* @__PURE__ */ jsxDEV4(Layout, {
|
|
2089
|
+
...data,
|
|
2090
|
+
children: element
|
|
2091
|
+
}, undefined, false, undefined, this);
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
element = wrapInBoundaries(element, byDepth.get(0));
|
|
2095
|
+
if (rootLayout.layout) {
|
|
2096
|
+
const RootLayoutComponent = rootLayout.layout;
|
|
2097
|
+
element = /* @__PURE__ */ jsxDEV4(RootLayoutComponent, {
|
|
2098
|
+
...data,
|
|
2099
|
+
children: element
|
|
2100
|
+
}, undefined, false, undefined, this);
|
|
2101
|
+
}
|
|
2102
|
+
return element;
|
|
2103
|
+
}
|
|
2104
|
+
function buildNotFoundElement(component, error) {
|
|
2105
|
+
const NotFound = component ?? DefaultNotFoundComponent;
|
|
2106
|
+
return /* @__PURE__ */ jsxDEV4(NotFound, {
|
|
2107
|
+
error: { message: error.message, data: error.data }
|
|
2108
|
+
}, undefined, false, undefined, this);
|
|
2109
|
+
}
|
|
2110
|
+
function errorMessageOf(err) {
|
|
2111
|
+
if (err instanceof Error) {
|
|
2112
|
+
return err.message;
|
|
2113
|
+
}
|
|
2114
|
+
if (typeof err === "string") {
|
|
2115
|
+
return err;
|
|
2116
|
+
}
|
|
2117
|
+
return "";
|
|
2118
|
+
}
|
|
2119
|
+
function buildErrorElement(component, error, digest) {
|
|
2120
|
+
const ErrorView = component ?? DefaultErrorComponent;
|
|
2121
|
+
const message = component ? errorMessageOf(error) : "An unexpected error occurred.";
|
|
2122
|
+
return /* @__PURE__ */ jsxDEV4(ErrorView, {
|
|
2123
|
+
error: { message, digest },
|
|
2124
|
+
reset: SERVER_RESET_NOOP2
|
|
2125
|
+
}, undefined, false, undefined, this);
|
|
2126
|
+
}
|
|
2127
|
+
var DefaultNotFoundComponent = ({ error }) => /* @__PURE__ */ jsxDEV4(DefaultNotFoundScreen, {
|
|
2128
|
+
message: error.message
|
|
2129
|
+
}, undefined, false, undefined, this), DefaultErrorComponent = ({ error, reset }) => /* @__PURE__ */ jsxDEV4(DefaultErrorScreen, {
|
|
2130
|
+
digest: error.digest,
|
|
2131
|
+
message: error.message,
|
|
2132
|
+
reset
|
|
2133
|
+
}, undefined, false, undefined, this), SERVER_RESET_NOOP2 = () => {};
|
|
2134
|
+
var init_element = __esm(() => {
|
|
2135
|
+
init_boundaries();
|
|
2136
|
+
init_default_screens();
|
|
2137
|
+
});
|
|
2138
|
+
|
|
2139
|
+
// src/render/loaders.ts
|
|
2140
|
+
function createLoaderCtx(ctx, accumulatedParentPromise) {
|
|
2141
|
+
const cache = new Map;
|
|
2142
|
+
return new Proxy(ctx, {
|
|
2143
|
+
get(target, prop) {
|
|
2144
|
+
if (typeof prop !== "string") {
|
|
2145
|
+
return Reflect.get(target, prop);
|
|
2146
|
+
}
|
|
2147
|
+
if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
|
|
2148
|
+
return Reflect.get(target, prop);
|
|
2149
|
+
}
|
|
2150
|
+
if (Object.hasOwn(target, prop)) {
|
|
2151
|
+
return target[prop];
|
|
2152
|
+
}
|
|
2153
|
+
let entry = cache.get(prop);
|
|
2154
|
+
if (!entry) {
|
|
2155
|
+
entry = accumulatedParentPromise.then((data) => data[prop]);
|
|
2156
|
+
cache.set(prop, entry);
|
|
2157
|
+
}
|
|
2158
|
+
return entry;
|
|
2159
|
+
}
|
|
2160
|
+
});
|
|
2161
|
+
}
|
|
2162
|
+
async function runLoaders(route, ctx, _rootLayout) {
|
|
2163
|
+
try {
|
|
2164
|
+
const ctxRecord = { ...ctx, log: useLogger3() };
|
|
2165
|
+
const loaderMap = new Map;
|
|
2166
|
+
let accumulatedParentPromise = Promise.resolve({});
|
|
2167
|
+
for (const r of route.routeChain) {
|
|
2168
|
+
const parentAccum = accumulatedParentPromise;
|
|
2169
|
+
if (r.loader) {
|
|
2170
|
+
const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
|
|
2171
|
+
const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
|
|
2172
|
+
loaderMap.set(r, loaderPromise);
|
|
2173
|
+
accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
|
|
2174
|
+
...acc,
|
|
2175
|
+
...own
|
|
2176
|
+
}));
|
|
2177
|
+
accumulatedParentPromise.catch(() => {});
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
|
|
2181
|
+
const pagePromise = route.page?.loader ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {}) : Promise.resolve({});
|
|
2182
|
+
const results = await Promise.all([...loaderMap.values(), pagePromise]);
|
|
2183
|
+
const data = Object.assign({}, ...results);
|
|
2184
|
+
const headers = {};
|
|
2185
|
+
Object.assign(headers, ctx.set.headers);
|
|
2186
|
+
return { type: "data", data, headers };
|
|
2187
|
+
} catch (err) {
|
|
2188
|
+
if (isNotFoundError(err)) {
|
|
2189
|
+
const headers2 = {};
|
|
2190
|
+
Object.assign(headers2, ctx.set.headers);
|
|
2191
|
+
return { type: "not-found", error: err, headers: headers2 };
|
|
2192
|
+
}
|
|
2193
|
+
if (err instanceof Response) {
|
|
2194
|
+
return { type: "redirect", response: err };
|
|
2195
|
+
}
|
|
2196
|
+
const headers = {};
|
|
2197
|
+
Object.assign(headers, ctx.set.headers);
|
|
2198
|
+
return { type: "error", error: err, headers };
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
var init_loaders = __esm(() => {
|
|
2202
|
+
init_context_logger();
|
|
2203
|
+
init_not_found();
|
|
2204
|
+
});
|
|
2205
|
+
|
|
2206
|
+
// src/render/template.ts
|
|
2207
|
+
import { readFileSync } from "fs";
|
|
2208
|
+
async function getDevTemplate(origin) {
|
|
2209
|
+
if (_devTemplateCache && Date.now() - _devTemplateCache.ts < DEV_TEMPLATE_TTL_MS) {
|
|
2210
|
+
return _devTemplateCache.html;
|
|
2211
|
+
}
|
|
2212
|
+
const r = await fetch(`${origin}/_bun_hmr_entry`);
|
|
2213
|
+
if (!r.ok) {
|
|
2214
|
+
throw new Error(`/_bun_hmr_entry returned ${r.status}`);
|
|
2215
|
+
}
|
|
2216
|
+
const html = await r.text();
|
|
2217
|
+
_devTemplateCache = { html, ts: Date.now() };
|
|
2218
|
+
return html;
|
|
2219
|
+
}
|
|
2220
|
+
function setProductionTemplatePath(path) {
|
|
2221
|
+
_prodTemplatePath = path;
|
|
2222
|
+
_prodTemplateContent = null;
|
|
2223
|
+
}
|
|
2224
|
+
function setProductionTemplateContent(content) {
|
|
2225
|
+
_prodTemplatePath = null;
|
|
2226
|
+
_prodTemplateContent = content;
|
|
2227
|
+
}
|
|
2228
|
+
function getProductionTemplate() {
|
|
2229
|
+
if (_prodTemplateContent !== null) {
|
|
2230
|
+
return _prodTemplateContent;
|
|
2231
|
+
}
|
|
2232
|
+
if (!_prodTemplatePath) {
|
|
2233
|
+
return null;
|
|
2234
|
+
}
|
|
2235
|
+
try {
|
|
2236
|
+
_prodTemplateContent = readFileSync(_prodTemplatePath, "utf8");
|
|
2237
|
+
return _prodTemplateContent;
|
|
2238
|
+
} catch {
|
|
2239
|
+
return null;
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
var _prodTemplatePath = null, _prodTemplateContent = null, _devTemplateCache = null, DEV_TEMPLATE_TTL_MS = 1000;
|
|
2243
|
+
var init_template = () => {};
|
|
2244
|
+
|
|
2245
|
+
// src/runtime-env.ts
|
|
2246
|
+
var IS_DEV = true;
|
|
2247
|
+
|
|
2248
|
+
// src/render/index.ts
|
|
2249
|
+
import { createElement as createElement2 } from "react";
|
|
2250
|
+
import { renderToReadableStream } from "react-dom/server";
|
|
2251
|
+
function withSSRRouterContext(element, contextValue) {
|
|
2252
|
+
return createElement2(RouterContext.Provider, { value: contextValue }, element);
|
|
2253
|
+
}
|
|
2254
|
+
async function prepareRender(route, ctx, root, basePath, throwOnFailure) {
|
|
2255
|
+
const loaderStart = Date.now();
|
|
2256
|
+
const loaderResult = await runLoaders(route, ctx, root.route);
|
|
2257
|
+
const loader_ms = Date.now() - loaderStart;
|
|
2258
|
+
if (loaderResult.type === "redirect") {
|
|
2259
|
+
return loaderResult.response;
|
|
2260
|
+
}
|
|
2261
|
+
if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
|
|
2262
|
+
throw loaderResult.error;
|
|
2263
|
+
}
|
|
2264
|
+
const isNotFound = loaderResult.type === "not-found";
|
|
2265
|
+
const isError = loaderResult.type === "error";
|
|
2266
|
+
const isFallback = isNotFound || isError;
|
|
2267
|
+
const data = isFallback ? {} : loaderResult.data;
|
|
2268
|
+
const headers = loaderResult.headers;
|
|
2269
|
+
const componentProps = {
|
|
2270
|
+
...data,
|
|
2271
|
+
params: ctx.params,
|
|
2272
|
+
query: ctx.query,
|
|
2273
|
+
path: ctx.path
|
|
2274
|
+
};
|
|
2275
|
+
const headData = isFallback ? "" : buildHeadInjection(route.page?.head?.(componentProps));
|
|
2276
|
+
const prodTemplate = getProductionTemplate();
|
|
2277
|
+
const template = prodTemplate ?? (IS_DEV ? await getDevTemplate(new URL(ctx.request.url).origin) : generateIndexHtml());
|
|
2278
|
+
let element;
|
|
2279
|
+
let status = 200;
|
|
2280
|
+
let errorDigest;
|
|
2281
|
+
let notFoundError;
|
|
2282
|
+
if (loaderResult.type === "not-found") {
|
|
2283
|
+
element = buildNotFoundElement(route.notFound ?? root.notFound, loaderResult.error);
|
|
2284
|
+
status = 404;
|
|
2285
|
+
notFoundError = { message: loaderResult.error.message, data: loaderResult.error.data };
|
|
2286
|
+
} else if (loaderResult.type === "error") {
|
|
2287
|
+
errorDigest = computeErrorDigest(loaderResult.error);
|
|
2288
|
+
element = buildErrorElement(route.error ?? root.error, loaderResult.error, errorDigest);
|
|
2289
|
+
status = 500;
|
|
2290
|
+
} else {
|
|
2291
|
+
element = buildElement(route, componentProps, root.route);
|
|
2292
|
+
}
|
|
2293
|
+
const ssrContext = {
|
|
2294
|
+
basePath: basePath ?? "",
|
|
2295
|
+
currentHref: ctx.path,
|
|
2296
|
+
navigate: () => Promise.resolve(),
|
|
2297
|
+
prefetch: () => {},
|
|
2298
|
+
invalidatePrefetch: () => {},
|
|
2299
|
+
refresh: () => Promise.resolve(),
|
|
2300
|
+
isNavigating: false,
|
|
2301
|
+
defaultPreload: "intent",
|
|
2302
|
+
defaultPreloadDelay: 50,
|
|
2303
|
+
defaultPreloadStaleTime: 30000
|
|
2304
|
+
};
|
|
2305
|
+
element = withSSRRouterContext(element, ssrContext);
|
|
2306
|
+
return {
|
|
2307
|
+
componentProps,
|
|
2308
|
+
element,
|
|
2309
|
+
errorDigest,
|
|
2310
|
+
headData,
|
|
2311
|
+
headers,
|
|
2312
|
+
loader_ms,
|
|
2313
|
+
notFoundError,
|
|
2314
|
+
ssrContext,
|
|
2315
|
+
status,
|
|
2316
|
+
template
|
|
2317
|
+
};
|
|
2318
|
+
}
|
|
2319
|
+
function renderForPath(route, params, root, origin, mode, basePath) {
|
|
2320
|
+
return runInSyntheticRenderScope(async () => {
|
|
2321
|
+
const resolvedPath = resolvePath(route.pattern, params);
|
|
2322
|
+
const ctx = {
|
|
2323
|
+
params,
|
|
2324
|
+
query: {},
|
|
2325
|
+
request: new Request(`${origin}${resolvedPath}`),
|
|
2326
|
+
headers: {},
|
|
2327
|
+
cookie: {},
|
|
2328
|
+
redirect: (url, status2) => new Response(null, { status: status2 ?? 302, headers: { Location: url } }),
|
|
2329
|
+
set: { headers: {} },
|
|
2330
|
+
path: resolvedPath
|
|
2331
|
+
};
|
|
2332
|
+
const prepared = await prepareRender(route, ctx, root, basePath, true);
|
|
2333
|
+
if (prepared instanceof Response) {
|
|
2334
|
+
return prepared;
|
|
2335
|
+
}
|
|
2336
|
+
useLogger3().set({
|
|
2337
|
+
furin: {
|
|
2338
|
+
render: mode,
|
|
2339
|
+
route: route.pattern,
|
|
2340
|
+
cache: mode === "isr" ? "revalidated" : "miss",
|
|
2341
|
+
loader_ms: prepared.loader_ms,
|
|
2342
|
+
...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
|
|
2343
|
+
}
|
|
2344
|
+
});
|
|
2345
|
+
const { componentProps, element, headData, headers, status, template } = prepared;
|
|
2346
|
+
const stream = await renderToReadableStream(element);
|
|
2347
|
+
await stream.allReady;
|
|
2348
|
+
const reactHtml = await streamToString(stream);
|
|
2349
|
+
return {
|
|
2350
|
+
html: assembleHTML(template, headData, reactHtml, componentProps),
|
|
2351
|
+
headers,
|
|
2352
|
+
status
|
|
2353
|
+
};
|
|
2354
|
+
}, { route: route.pattern, render: mode });
|
|
2355
|
+
}
|
|
2356
|
+
async function prerenderSSG(route, params, root, origin, basePath) {
|
|
2357
|
+
const resolvedPath = resolvePath(route.pattern, params);
|
|
2358
|
+
const cached = getSSGCache(resolvedPath);
|
|
2359
|
+
if (cached && !IS_DEV) {
|
|
2360
|
+
return cached;
|
|
2361
|
+
}
|
|
2362
|
+
const renderResult = await renderForPath(route, params, root, origin, "ssg", basePath);
|
|
2363
|
+
if (renderResult instanceof Response) {
|
|
2364
|
+
return renderResult;
|
|
2365
|
+
}
|
|
2366
|
+
const result = renderResult;
|
|
2367
|
+
const entry = { html: result.html, cachedAt: Date.now(), status: result.status };
|
|
2368
|
+
if (!IS_DEV) {
|
|
2369
|
+
setSSGCache(resolvedPath, entry);
|
|
2370
|
+
}
|
|
2371
|
+
return entry;
|
|
2372
|
+
}
|
|
2373
|
+
async function renderSSR(route, ctx, root) {
|
|
2374
|
+
const prepared = await prepareRender(route, ctx, root, undefined, false);
|
|
2375
|
+
if (prepared instanceof Response) {
|
|
2376
|
+
return prepared;
|
|
2377
|
+
}
|
|
2378
|
+
useLogger3().set({
|
|
2379
|
+
furin: {
|
|
2380
|
+
render: route.mode,
|
|
2381
|
+
route: route.pattern,
|
|
2382
|
+
loader_ms: prepared.loader_ms,
|
|
2383
|
+
...prepared.errorDigest ? { digest: prepared.errorDigest } : {}
|
|
2384
|
+
}
|
|
2385
|
+
});
|
|
2386
|
+
const { componentProps, element, headData, headers, template } = prepared;
|
|
2387
|
+
const { headPre, bodyPre, bodyPost } = splitTemplate(template);
|
|
2388
|
+
let reactStream;
|
|
2389
|
+
let status = prepared.status;
|
|
2390
|
+
let shellErrored = false;
|
|
2391
|
+
let finalDigest = prepared.errorDigest;
|
|
2392
|
+
try {
|
|
2393
|
+
reactStream = await renderToReadableStream(element);
|
|
2394
|
+
} catch (shellError) {
|
|
2395
|
+
shellErrored = true;
|
|
2396
|
+
status = 500;
|
|
2397
|
+
finalDigest = computeErrorDigest(shellError);
|
|
2398
|
+
useLogger3().set({
|
|
2399
|
+
furin: { render: route.mode, route: route.pattern, digest: finalDigest, phase: "shell" }
|
|
2400
|
+
});
|
|
2401
|
+
try {
|
|
2402
|
+
reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest), prepared.ssrContext));
|
|
2403
|
+
} catch {
|
|
2404
|
+
reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest), prepared.ssrContext));
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
const dataPayload = shellErrored ? {} : { ...componentProps };
|
|
2408
|
+
if (finalDigest) {
|
|
2409
|
+
dataPayload.__furinError = { digest: finalDigest };
|
|
2410
|
+
}
|
|
2411
|
+
if (status === 404 && !shellErrored) {
|
|
2412
|
+
dataPayload.__furinStatus = 404;
|
|
2413
|
+
if (prepared.notFoundError) {
|
|
2414
|
+
dataPayload.__furinNotFound = prepared.notFoundError;
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
const dataScript = `<script id="__FURIN_DATA__" type="application/json">${safeJson(dataPayload)}</script>`;
|
|
2418
|
+
const { readable, writable } = new TransformStream;
|
|
2419
|
+
const writer = writable.getWriter();
|
|
2420
|
+
const enc = new TextEncoder;
|
|
2421
|
+
(async () => {
|
|
2422
|
+
await writer.write(enc.encode(headPre + headData + bodyPre));
|
|
2423
|
+
const reader = reactStream.getReader();
|
|
2424
|
+
for (;; ) {
|
|
2425
|
+
const { done, value } = await reader.read();
|
|
2426
|
+
if (done) {
|
|
2427
|
+
break;
|
|
2428
|
+
}
|
|
2429
|
+
await writer.write(value);
|
|
2430
|
+
}
|
|
2431
|
+
await writer.write(enc.encode(dataScript + bodyPost));
|
|
2432
|
+
await writer.close();
|
|
2433
|
+
})().catch((err) => writer.abort(err));
|
|
2434
|
+
return new Response(readable, {
|
|
2435
|
+
status,
|
|
2436
|
+
headers: {
|
|
2437
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
2438
|
+
"Cache-Control": "no-store, no-cache, must-revalidate",
|
|
2439
|
+
...headers
|
|
2440
|
+
}
|
|
2441
|
+
});
|
|
2442
|
+
}
|
|
2443
|
+
async function renderRootNotFound(root, request) {
|
|
2444
|
+
const prodTemplate = getProductionTemplate();
|
|
2445
|
+
let template;
|
|
2446
|
+
if (prodTemplate !== null) {
|
|
2447
|
+
template = prodTemplate;
|
|
2448
|
+
} else if (IS_DEV && request !== undefined) {
|
|
2449
|
+
try {
|
|
2450
|
+
template = await getDevTemplate(new URL(request.url).origin);
|
|
2451
|
+
} catch (devTemplateErr) {
|
|
2452
|
+
useLogger3().set({
|
|
2453
|
+
furin: {
|
|
2454
|
+
render: "not-found",
|
|
2455
|
+
action: "dev_template_fallback",
|
|
2456
|
+
error: devTemplateErr instanceof Error ? devTemplateErr.message : String(devTemplateErr)
|
|
2457
|
+
}
|
|
2458
|
+
});
|
|
2459
|
+
template = generateIndexHtml();
|
|
2460
|
+
}
|
|
2461
|
+
} else {
|
|
2462
|
+
template = generateIndexHtml();
|
|
2463
|
+
}
|
|
2464
|
+
const notFoundError = new FurinNotFoundError(undefined);
|
|
2465
|
+
const notFoundContext = {
|
|
2466
|
+
basePath: "",
|
|
2467
|
+
currentHref: request ? new URL(request.url).pathname : "/",
|
|
2468
|
+
navigate: () => Promise.resolve(),
|
|
2469
|
+
prefetch: () => {},
|
|
2470
|
+
invalidatePrefetch: () => {},
|
|
2471
|
+
refresh: () => Promise.resolve(),
|
|
2472
|
+
isNavigating: false,
|
|
2473
|
+
defaultPreload: "intent",
|
|
2474
|
+
defaultPreloadDelay: 50,
|
|
2475
|
+
defaultPreloadStaleTime: 30000
|
|
2476
|
+
};
|
|
2477
|
+
useLogger3().set({
|
|
2478
|
+
furin: {
|
|
2479
|
+
render: "not-found",
|
|
2480
|
+
action: "catch_all",
|
|
2481
|
+
path: request ? new URL(request.url).pathname : "/"
|
|
2482
|
+
}
|
|
2483
|
+
});
|
|
2484
|
+
let reactStream;
|
|
2485
|
+
try {
|
|
2486
|
+
reactStream = await renderToReadableStream(withSSRRouterContext(buildNotFoundElement(root.notFound, notFoundError), notFoundContext));
|
|
2487
|
+
} catch {
|
|
2488
|
+
reactStream = await renderToReadableStream(withSSRRouterContext(buildNotFoundElement(undefined, notFoundError), notFoundContext));
|
|
2489
|
+
}
|
|
2490
|
+
await reactStream.allReady;
|
|
2491
|
+
const reactHtml = await streamToString(reactStream);
|
|
2492
|
+
const html = assembleHTML(template, "", reactHtml, { __furinStatus: 404 });
|
|
2493
|
+
return new Response(html, {
|
|
2494
|
+
status: 404,
|
|
2495
|
+
headers: { "Content-Type": "text/html; charset=utf-8" }
|
|
2496
|
+
});
|
|
2497
|
+
}
|
|
2498
|
+
function isrCacheControl(isFresh, revalidate) {
|
|
2499
|
+
const sMaxAge = isFresh ? revalidate : 0;
|
|
2500
|
+
return `public, max-age=0, must-revalidate, s-maxage=${sMaxAge}, stale-while-revalidate=${revalidate}`;
|
|
2501
|
+
}
|
|
2502
|
+
function serveISRCacheHit(cached, ctx, route, params, cacheKey, revalidate, root, buildId) {
|
|
2503
|
+
const isFresh = Date.now() - cached.generatedAt < revalidate * 1000;
|
|
2504
|
+
if (!isFresh) {
|
|
2505
|
+
revalidateInBackground(route, params, cacheKey, revalidate, root, ctx);
|
|
2506
|
+
}
|
|
2507
|
+
const etag = buildId ? `"${buildId}:${cached.generatedAt}"` : null;
|
|
2508
|
+
if (etag && ctx.request.headers.get("if-none-match") === etag) {
|
|
2509
|
+
ctx.set.status = 304;
|
|
2510
|
+
ctx.set.headers.etag = etag;
|
|
2511
|
+
ctx.set.headers["cache-control"] = isrCacheControl(isFresh, revalidate);
|
|
2512
|
+
return;
|
|
2513
|
+
}
|
|
2514
|
+
ctx.set.headers["content-type"] = "text/html; charset=utf-8";
|
|
2515
|
+
ctx.set.headers["cache-control"] = isrCacheControl(isFresh, revalidate);
|
|
2516
|
+
if (etag) {
|
|
2517
|
+
ctx.set.headers.etag = etag;
|
|
2518
|
+
}
|
|
2519
|
+
useLogger3().set({
|
|
2520
|
+
furin: { render: "isr", route: route.pattern, cache: isFresh ? "hit" : "stale" }
|
|
2521
|
+
});
|
|
2522
|
+
return cached.html;
|
|
2523
|
+
}
|
|
2524
|
+
async function renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId) {
|
|
2525
|
+
const { componentProps, element, headData, template, status, notFoundError } = prepared;
|
|
2526
|
+
const fallbackProps = { ...componentProps };
|
|
2527
|
+
if (status === 404) {
|
|
2528
|
+
fallbackProps.__furinStatus = 404;
|
|
2529
|
+
if (notFoundError) {
|
|
2530
|
+
fallbackProps.__furinNotFound = notFoundError;
|
|
2531
|
+
}
|
|
2532
|
+
}
|
|
2533
|
+
let reactStream;
|
|
2534
|
+
let finalStatus = status;
|
|
2535
|
+
let finalDigest = errorDigest;
|
|
2536
|
+
try {
|
|
2537
|
+
reactStream = await renderToReadableStream(element);
|
|
2538
|
+
} catch (shellError) {
|
|
2539
|
+
finalStatus = 500;
|
|
2540
|
+
finalDigest = computeErrorDigest(shellError);
|
|
2541
|
+
useLogger3().set({
|
|
2542
|
+
furin: {
|
|
2543
|
+
render: "isr",
|
|
2544
|
+
route: route.pattern,
|
|
2545
|
+
cache: "miss",
|
|
2546
|
+
digest: finalDigest,
|
|
2547
|
+
phase: "shell"
|
|
2548
|
+
}
|
|
2549
|
+
});
|
|
2550
|
+
fallbackProps.__furinError = { digest: finalDigest };
|
|
2551
|
+
fallbackProps.__furinStatus = 500;
|
|
2552
|
+
try {
|
|
2553
|
+
reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(route.error ?? root.error, shellError, finalDigest), prepared.ssrContext));
|
|
2554
|
+
} catch {
|
|
2555
|
+
reactStream = await renderToReadableStream(withSSRRouterContext(buildErrorElement(undefined, shellError, finalDigest), prepared.ssrContext));
|
|
2556
|
+
}
|
|
2557
|
+
}
|
|
2558
|
+
if (!fallbackProps.__furinError && errorDigest) {
|
|
2559
|
+
fallbackProps.__furinError = { digest: errorDigest };
|
|
2560
|
+
}
|
|
2561
|
+
await reactStream.allReady;
|
|
2562
|
+
const reactHtml = await streamToString(reactStream);
|
|
2563
|
+
const html = assembleHTML(template, headData, reactHtml, fallbackProps);
|
|
2564
|
+
const generatedAt = Date.now();
|
|
2565
|
+
const renderMs = generatedAt - renderStart;
|
|
2566
|
+
useLogger3().set({
|
|
2567
|
+
furin: {
|
|
2568
|
+
render: "isr",
|
|
2569
|
+
route: route.pattern,
|
|
2570
|
+
cache: "miss",
|
|
2571
|
+
render_ms: renderMs,
|
|
2572
|
+
...finalDigest ? { digest: finalDigest } : {},
|
|
2573
|
+
status: finalStatus
|
|
2574
|
+
}
|
|
2575
|
+
});
|
|
2576
|
+
const etag = buildId ? `"${buildId}:${generatedAt}"` : null;
|
|
2577
|
+
ctx.set.headers["content-type"] = "text/html; charset=utf-8";
|
|
2578
|
+
ctx.set.headers["cache-control"] = "no-store";
|
|
2579
|
+
if (etag) {
|
|
2580
|
+
ctx.set.headers.etag = etag;
|
|
2581
|
+
}
|
|
2582
|
+
ctx.set.status = finalStatus;
|
|
2583
|
+
return html;
|
|
2584
|
+
}
|
|
2585
|
+
async function handleISR(route, ctx, root, buildId = "") {
|
|
2586
|
+
const revalidate = route.page._route.revalidate ?? 60;
|
|
2587
|
+
const params = ctx.params ?? {};
|
|
2588
|
+
const cacheKey = resolvePath(route.pattern, params);
|
|
2589
|
+
const cached = getISRCache(cacheKey);
|
|
2590
|
+
if (cached && !IS_DEV) {
|
|
2591
|
+
return serveISRCacheHit(cached, ctx, route, params, cacheKey, revalidate, root, buildId);
|
|
2592
|
+
}
|
|
2593
|
+
const renderStart = Date.now();
|
|
2594
|
+
const prepared = await prepareRender(route, ctx, root, undefined, false);
|
|
2595
|
+
if (prepared instanceof Response) {
|
|
2596
|
+
return prepared;
|
|
2597
|
+
}
|
|
2598
|
+
const { componentProps, element, headData, template, status, errorDigest } = prepared;
|
|
2599
|
+
if (status !== 200) {
|
|
2600
|
+
return renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId);
|
|
2601
|
+
}
|
|
2602
|
+
const stream = await renderToReadableStream(element);
|
|
2603
|
+
await stream.allReady;
|
|
2604
|
+
const reactHtml = await streamToString(stream);
|
|
2605
|
+
const html = assembleHTML(template, headData, reactHtml, componentProps);
|
|
2606
|
+
const generatedAt = Date.now();
|
|
2607
|
+
useLogger3().set({
|
|
2608
|
+
furin: {
|
|
2609
|
+
render: "isr",
|
|
2610
|
+
route: route.pattern,
|
|
2611
|
+
cache: "miss",
|
|
2612
|
+
render_ms: generatedAt - renderStart
|
|
2613
|
+
}
|
|
2614
|
+
});
|
|
2615
|
+
if (!IS_DEV) {
|
|
2616
|
+
setISRCache(cacheKey, { html, generatedAt, revalidate });
|
|
2617
|
+
}
|
|
2618
|
+
const etag = buildId ? `"${buildId}:${generatedAt}"` : null;
|
|
2619
|
+
ctx.set.headers["content-type"] = "text/html; charset=utf-8";
|
|
2620
|
+
ctx.set.headers["cache-control"] = isrCacheControl(true, revalidate);
|
|
2621
|
+
if (etag) {
|
|
2622
|
+
ctx.set.headers.etag = etag;
|
|
2623
|
+
}
|
|
2624
|
+
return html;
|
|
2625
|
+
}
|
|
2626
|
+
async function warmSSGCache(routes, root, origin) {
|
|
2627
|
+
const targets = routes.filter((r) => r.mode === "ssg" && r.page.staticParams);
|
|
2628
|
+
const warmupLogger = createLogger({});
|
|
2629
|
+
warmupLogger.set({
|
|
2630
|
+
furin: {
|
|
2631
|
+
render: "ssg",
|
|
2632
|
+
action: "warmup",
|
|
2633
|
+
routes: targets.length
|
|
2634
|
+
}
|
|
2635
|
+
});
|
|
2636
|
+
warmupLogger.emit();
|
|
2637
|
+
const tasks = [];
|
|
2638
|
+
for (const route of targets) {
|
|
2639
|
+
let paramSets;
|
|
2640
|
+
try {
|
|
2641
|
+
paramSets = await route.page.staticParams?.() ?? [];
|
|
2642
|
+
} catch (err) {
|
|
2643
|
+
const errorLogger = createLogger({});
|
|
2644
|
+
errorLogger.set({
|
|
2645
|
+
furin: {
|
|
2646
|
+
render: "ssg",
|
|
2647
|
+
action: "warmup_failed",
|
|
2648
|
+
route: route.pattern
|
|
2649
|
+
}
|
|
2650
|
+
});
|
|
2651
|
+
errorLogger.error(err instanceof Error ? err : new Error(String(err)));
|
|
2652
|
+
errorLogger.emit();
|
|
2653
|
+
continue;
|
|
2654
|
+
}
|
|
2655
|
+
for (const params of paramSets) {
|
|
2656
|
+
tasks.push(async () => {
|
|
2657
|
+
try {
|
|
2658
|
+
await prerenderSSG(route, params, root, origin, undefined);
|
|
2659
|
+
} catch (err) {
|
|
2660
|
+
const errorLogger = createLogger({});
|
|
2661
|
+
errorLogger.set({
|
|
2662
|
+
furin: {
|
|
2663
|
+
render: "ssg",
|
|
2664
|
+
action: "prerender_failed",
|
|
2665
|
+
route: route.pattern
|
|
2666
|
+
}
|
|
2667
|
+
});
|
|
2668
|
+
errorLogger.error(err instanceof Error ? err : new Error(String(err)));
|
|
2669
|
+
errorLogger.emit();
|
|
2670
|
+
}
|
|
2671
|
+
});
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
if (tasks.length === 0) {
|
|
2675
|
+
return;
|
|
2676
|
+
}
|
|
2677
|
+
const queue = [...tasks];
|
|
2678
|
+
const workers = Array.from({ length: Math.min(SSG_WARM_CONCURRENCY, tasks.length) }, async () => {
|
|
2679
|
+
while (queue.length > 0) {
|
|
2680
|
+
await queue.shift()?.();
|
|
2681
|
+
}
|
|
2682
|
+
});
|
|
2683
|
+
await Promise.all(workers);
|
|
2684
|
+
}
|
|
2685
|
+
function revalidateInBackground(route, params, cacheKey, revalidate, root, originalCtx) {
|
|
2686
|
+
if (pendingRevalidations.has(cacheKey)) {
|
|
2687
|
+
const logger = createLogger({});
|
|
2688
|
+
logger.set({
|
|
2689
|
+
furin: {
|
|
2690
|
+
render: "isr",
|
|
2691
|
+
route: route.pattern,
|
|
2692
|
+
cache: "revalidation_skipped",
|
|
2693
|
+
reason: "already_in_flight"
|
|
2694
|
+
}
|
|
2695
|
+
});
|
|
2696
|
+
logger.emit();
|
|
2697
|
+
return;
|
|
2698
|
+
}
|
|
2699
|
+
pendingRevalidations.add(cacheKey);
|
|
2700
|
+
renderForPath(route, params, root, new URL(originalCtx.request.url).origin, "isr", undefined).then((result) => {
|
|
2701
|
+
if (result instanceof Response) {
|
|
2702
|
+
return;
|
|
2703
|
+
}
|
|
2704
|
+
setISRCache(cacheKey, {
|
|
2705
|
+
html: result.html,
|
|
2706
|
+
generatedAt: Date.now(),
|
|
2707
|
+
revalidate
|
|
2708
|
+
});
|
|
2709
|
+
}).catch((err) => {
|
|
2710
|
+
const logger = createLogger({});
|
|
2711
|
+
logger.set({
|
|
2712
|
+
furin: {
|
|
2713
|
+
render: "isr",
|
|
2714
|
+
route: route.pattern,
|
|
2715
|
+
cache: "revalidation_failed"
|
|
2716
|
+
}
|
|
2717
|
+
});
|
|
2718
|
+
logger.error(err instanceof Error ? err : new Error(String(err)));
|
|
2719
|
+
logger.emit();
|
|
2720
|
+
}).finally(() => {
|
|
2721
|
+
pendingRevalidations.delete(cacheKey);
|
|
2722
|
+
});
|
|
2723
|
+
}
|
|
2724
|
+
var SSG_WARM_CONCURRENCY = 4, pendingRevalidations;
|
|
2725
|
+
var init_render = __esm(() => {
|
|
2726
|
+
init_link();
|
|
2727
|
+
init_not_found();
|
|
2728
|
+
init_assemble();
|
|
2729
|
+
init_cache();
|
|
2730
|
+
init_element();
|
|
2731
|
+
init_loaders();
|
|
2732
|
+
init_shell();
|
|
2733
|
+
init_template();
|
|
2734
|
+
init_assemble();
|
|
2735
|
+
init_element();
|
|
2736
|
+
init_loaders();
|
|
2737
|
+
init_context_logger();
|
|
2738
|
+
init_shell();
|
|
2739
|
+
pendingRevalidations = new Set;
|
|
2740
|
+
});
|
|
2741
|
+
|
|
2742
|
+
// src/utils.ts
|
|
2743
|
+
function isFurinPage(value) {
|
|
2744
|
+
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_PAGE";
|
|
2745
|
+
}
|
|
2746
|
+
function isFurinRoute(value) {
|
|
2747
|
+
return typeof value === "object" && value !== null && "__type" in value && value.__type === "FURIN_ROUTE";
|
|
2748
|
+
}
|
|
2749
|
+
function collectRouteChainFromRoute(route) {
|
|
2750
|
+
const chain = [];
|
|
2751
|
+
let current = route;
|
|
2752
|
+
while (current) {
|
|
2753
|
+
chain.unshift(current);
|
|
2754
|
+
current = current.parent;
|
|
2755
|
+
}
|
|
2756
|
+
return chain;
|
|
2757
|
+
}
|
|
2758
|
+
function hasCycle(route) {
|
|
2759
|
+
const visited = new Set;
|
|
2760
|
+
let current = route;
|
|
2761
|
+
while (current) {
|
|
2762
|
+
if (visited.has(current)) {
|
|
2763
|
+
return true;
|
|
2764
|
+
}
|
|
2765
|
+
visited.add(current);
|
|
2766
|
+
current = current.parent;
|
|
2767
|
+
}
|
|
2768
|
+
return false;
|
|
2769
|
+
}
|
|
2770
|
+
function validateRouteChain(chain, root, pagePath) {
|
|
2771
|
+
const hasRoot = chain.some((r) => r === root);
|
|
2772
|
+
if (!hasRoot) {
|
|
2773
|
+
const location = pagePath ? `in ${pagePath}` : "";
|
|
2774
|
+
throw new Error(`[furin] Page ${location} must inherit from root route. ` + 'Add: import { route } from "./root"; and use route.page() or set parent: route');
|
|
2775
|
+
}
|
|
2776
|
+
for (const route of chain) {
|
|
2777
|
+
if (hasCycle(route)) {
|
|
2778
|
+
throw new Error("[furin] Cycle detected in route chain. A route cannot be its own ancestor.");
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
}
|
|
2782
|
+
|
|
2783
|
+
// src/router.ts
|
|
2784
|
+
var exports_router = {};
|
|
2785
|
+
__export(exports_router, {
|
|
2786
|
+
scanRootLayout: () => scanRootLayout,
|
|
2787
|
+
scanPages: () => scanPages,
|
|
2788
|
+
resolveMode: () => resolveMode,
|
|
2789
|
+
refreshLayoutChain: () => refreshLayoutChain,
|
|
2790
|
+
queryDefaultRedirectHook: () => queryDefaultRedirectHook,
|
|
2791
|
+
mergeRouteSchemas: () => mergeRouteSchemas,
|
|
2792
|
+
loadProdRoutes: () => loadProdRoutes,
|
|
2793
|
+
filePathToPattern: () => filePathToPattern,
|
|
2794
|
+
createRoutePlugin: () => createRoutePlugin
|
|
2795
|
+
});
|
|
2796
|
+
import { existsSync } from "fs";
|
|
2797
|
+
import { readdir } from "fs/promises";
|
|
2798
|
+
import { join, parse } from "path";
|
|
2799
|
+
import { Elysia as Elysia2, t } from "elysia";
|
|
2800
|
+
function isModuleNotFoundError(err) {
|
|
2801
|
+
if (!(err instanceof Error)) {
|
|
2802
|
+
return false;
|
|
2803
|
+
}
|
|
2804
|
+
const msg = err.message.toLowerCase();
|
|
2805
|
+
const code = err.code;
|
|
2806
|
+
return code === "ENOENT" || code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || msg.includes("cannot find module") || msg.includes("module not found") || msg.includes("no such file or directory");
|
|
2807
|
+
}
|
|
2808
|
+
function loadProdRoutes(ctx) {
|
|
2809
|
+
const rootMod = ctx.modules[ctx.rootPath];
|
|
2810
|
+
const rootExport = rootMod.route ?? rootMod.default;
|
|
2811
|
+
if (!(rootExport && isFurinRoute(rootExport) && rootExport.layout)) {
|
|
2812
|
+
throw new Error("[furin] root.tsx: createRoute() with layout not found in CompileContext.");
|
|
2813
|
+
}
|
|
2814
|
+
function resolveModuleComponent(modPath) {
|
|
2815
|
+
if (!modPath) {
|
|
2816
|
+
return;
|
|
2817
|
+
}
|
|
2818
|
+
const mod = ctx.modules[modPath];
|
|
2819
|
+
return mod?.default;
|
|
2820
|
+
}
|
|
2821
|
+
const root = {
|
|
2822
|
+
path: ctx.rootPath,
|
|
2823
|
+
route: rootExport,
|
|
2824
|
+
error: resolveModuleComponent(ctx.rootConventions?.errorPath),
|
|
2825
|
+
notFound: resolveModuleComponent(ctx.rootConventions?.notFoundPath)
|
|
2826
|
+
};
|
|
2827
|
+
const routes = [];
|
|
2828
|
+
for (const { pattern, path, mode } of ctx.routes) {
|
|
2829
|
+
const pageMod = ctx.modules[path];
|
|
2830
|
+
const page = pageMod.default;
|
|
2831
|
+
if (!isFurinPage(page)) {
|
|
2832
|
+
throw new Error(`[furin] ${path}: invalid page module in CompileContext.`);
|
|
2833
|
+
}
|
|
2834
|
+
const routeChain = collectRouteChainFromRoute(page._route);
|
|
2835
|
+
validateRouteChain(routeChain, root.route, path);
|
|
2836
|
+
const meta = ctx.routeMetadata?.[path];
|
|
2837
|
+
const boundaries = (meta?.segmentBoundaries ?? []).map((b) => ({
|
|
2838
|
+
...b,
|
|
2839
|
+
error: resolveModuleComponent(b.errorPath),
|
|
2840
|
+
notFound: resolveModuleComponent(b.notFoundPath)
|
|
2841
|
+
}));
|
|
2842
|
+
const error = boundaries.findLast((b) => b.error)?.error;
|
|
2843
|
+
const notFound2 = boundaries.findLast((b) => b.notFound)?.notFound;
|
|
2844
|
+
routes.push({
|
|
2845
|
+
pattern,
|
|
2846
|
+
page,
|
|
2847
|
+
path,
|
|
2848
|
+
routeChain,
|
|
2849
|
+
mode,
|
|
2850
|
+
segmentBoundaries: boundaries,
|
|
2851
|
+
error,
|
|
2852
|
+
notFound: notFound2
|
|
2853
|
+
});
|
|
2854
|
+
}
|
|
2855
|
+
return { root, routes };
|
|
2856
|
+
}
|
|
2857
|
+
async function scanPages(pagesDir) {
|
|
2858
|
+
const root = await scanRootLayout(pagesDir);
|
|
2859
|
+
const routes = await scanPageFiles(pagesDir, root);
|
|
2860
|
+
return { root, routes };
|
|
2861
|
+
}
|
|
2862
|
+
async function scanRootLayout(pagesDir) {
|
|
2863
|
+
const rootPath = `${pagesDir}/root.tsx`;
|
|
2864
|
+
const ctx = getCompileContext();
|
|
2865
|
+
if (!(existsSync(rootPath) || ctx?.modules[rootPath])) {
|
|
2866
|
+
throw new Error("[furin] root.tsx: not found.");
|
|
2867
|
+
}
|
|
2868
|
+
const mod = ctx?.modules[rootPath] ?? await import(rootPath);
|
|
2869
|
+
const rootExport = mod.route ?? mod.default;
|
|
2870
|
+
if (!(rootExport && isFurinRoute(rootExport))) {
|
|
2871
|
+
throw new Error("[furin] root.tsx: createRoute() export not found.");
|
|
2872
|
+
}
|
|
2873
|
+
if (!rootExport.layout) {
|
|
2874
|
+
throw new Error("[furin] root.tsx: createRoute() has no layout.");
|
|
2875
|
+
}
|
|
2876
|
+
const notFoundEntry = await loadConventionComponent(pagesDir, "not-found");
|
|
2877
|
+
const errorEntry = await loadConventionComponent(pagesDir, "error");
|
|
2878
|
+
return {
|
|
2879
|
+
path: rootPath,
|
|
2880
|
+
route: rootExport,
|
|
2881
|
+
notFound: notFoundEntry?.component,
|
|
2882
|
+
notFoundPath: notFoundEntry?.path,
|
|
2883
|
+
error: errorEntry?.component,
|
|
2884
|
+
errorPath: errorEntry?.path
|
|
2885
|
+
};
|
|
2886
|
+
}
|
|
2887
|
+
function isConventionFileName(name) {
|
|
2888
|
+
return CONVENTION_FILE_NAMES.includes(name);
|
|
2889
|
+
}
|
|
2890
|
+
async function loadConventionComponent(dir, name) {
|
|
2891
|
+
const ctx = getCompileContext();
|
|
2892
|
+
for (const ext of [".tsx", ".ts", ".jsx", ".js"]) {
|
|
2893
|
+
const filePath = `${dir}/${name}${ext}`;
|
|
2894
|
+
if (existsSync(filePath) || ctx?.modules[filePath]) {
|
|
2895
|
+
const mod = ctx?.modules[filePath] ?? await import(filePath);
|
|
2896
|
+
if (mod.default) {
|
|
2897
|
+
return { component: mod.default, path: filePath };
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2900
|
+
}
|
|
2901
|
+
return;
|
|
2902
|
+
}
|
|
2903
|
+
async function scanPageFiles(pagesDir, root) {
|
|
2904
|
+
const routes = [];
|
|
2905
|
+
const notFoundCache = new Map;
|
|
2906
|
+
const errorCache = new Map;
|
|
2907
|
+
for (const absolutePath of await collectPageFilePaths(pagesDir)) {
|
|
2908
|
+
if (![".tsx", ".ts", ".jsx", ".js"].some((ext) => absolutePath.endsWith(ext))) {
|
|
2909
|
+
continue;
|
|
2910
|
+
}
|
|
2911
|
+
const relativePath = absolutePath.replace(`${pagesDir}/`, "");
|
|
2912
|
+
const fileName = parse(relativePath).name;
|
|
2913
|
+
if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
|
|
2914
|
+
continue;
|
|
2915
|
+
}
|
|
2916
|
+
const notFound2 = await resolveNearestConvention(absolutePath, pagesDir, "not-found", notFoundCache, root.notFound);
|
|
2917
|
+
const errorComponent = await resolveNearestConvention(absolutePath, pagesDir, "error", errorCache, root.error);
|
|
2918
|
+
const segmentBoundaries = await collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache);
|
|
2919
|
+
if (IS_DEV) {
|
|
2920
|
+
const devRoute = await buildDevRoute(absolutePath, relativePath, root);
|
|
2921
|
+
devRoute.notFound = notFound2;
|
|
2922
|
+
devRoute.error = errorComponent;
|
|
2923
|
+
devRoute.segmentBoundaries = segmentBoundaries;
|
|
2924
|
+
routes.push(devRoute);
|
|
2925
|
+
continue;
|
|
2926
|
+
}
|
|
2927
|
+
const ctx = getCompileContext();
|
|
2928
|
+
const pageMod = ctx?.modules[absolutePath] ?? await import(absolutePath);
|
|
2929
|
+
const page = pageMod.default;
|
|
2930
|
+
if (!isFurinPage(page)) {
|
|
2931
|
+
throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
|
|
2932
|
+
}
|
|
2933
|
+
const routeChain = collectRouteChainFromRoute(page._route);
|
|
2934
|
+
validateRouteChain(routeChain, root.route, relativePath);
|
|
2935
|
+
routes.push({
|
|
2936
|
+
pattern: filePathToPattern(relativePath),
|
|
2937
|
+
page,
|
|
2938
|
+
path: absolutePath,
|
|
2939
|
+
routeChain,
|
|
2940
|
+
mode: resolveMode(page, routeChain),
|
|
2941
|
+
notFound: notFound2,
|
|
2942
|
+
error: errorComponent,
|
|
2943
|
+
segmentBoundaries
|
|
2944
|
+
});
|
|
2945
|
+
}
|
|
2946
|
+
return routes;
|
|
2947
|
+
}
|
|
2948
|
+
async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
|
|
2949
|
+
const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
|
|
2950
|
+
const dirs = [pagesDir];
|
|
2951
|
+
if (pageDir.length > pagesDir.length) {
|
|
2952
|
+
const relativeTail = pageDir.slice(pagesDir.length + 1);
|
|
2953
|
+
const parts = relativeTail.split("/");
|
|
2954
|
+
let acc = pagesDir;
|
|
2955
|
+
for (const part of parts) {
|
|
2956
|
+
acc = `${acc}/${part}`;
|
|
2957
|
+
dirs.push(acc);
|
|
2958
|
+
}
|
|
2959
|
+
}
|
|
2960
|
+
const boundaries = [];
|
|
2961
|
+
for (let depth = 0;depth < dirs.length; depth++) {
|
|
2962
|
+
const dir = dirs[depth];
|
|
2963
|
+
if (!errorCache.has(dir)) {
|
|
2964
|
+
errorCache.set(dir, await loadConventionComponent(dir, "error"));
|
|
2965
|
+
}
|
|
2966
|
+
if (!notFoundCache.has(dir)) {
|
|
2967
|
+
notFoundCache.set(dir, await loadConventionComponent(dir, "not-found"));
|
|
2968
|
+
}
|
|
2969
|
+
const errorEntry = errorCache.get(dir);
|
|
2970
|
+
const notFoundEntry = notFoundCache.get(dir);
|
|
2971
|
+
if (errorEntry || notFoundEntry) {
|
|
2972
|
+
boundaries.push({
|
|
2973
|
+
path: dir,
|
|
2974
|
+
depth,
|
|
2975
|
+
error: errorEntry?.component,
|
|
2976
|
+
errorPath: errorEntry?.path,
|
|
2977
|
+
notFound: notFoundEntry?.component,
|
|
2978
|
+
notFoundPath: notFoundEntry?.path
|
|
2979
|
+
});
|
|
2980
|
+
}
|
|
2981
|
+
}
|
|
2982
|
+
return boundaries;
|
|
2983
|
+
}
|
|
2984
|
+
async function resolveNearestConvention(pageAbsolutePath, pagesDir, conventionName, cache, rootFallback) {
|
|
2985
|
+
let dir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
|
|
2986
|
+
while (dir.length >= pagesDir.length) {
|
|
2987
|
+
if (!cache.has(dir)) {
|
|
2988
|
+
cache.set(dir, await loadConventionComponent(dir, conventionName));
|
|
2989
|
+
}
|
|
2990
|
+
const found = cache.get(dir);
|
|
2991
|
+
if (found) {
|
|
2992
|
+
return found.component;
|
|
2993
|
+
}
|
|
2994
|
+
if (dir === pagesDir) {
|
|
2995
|
+
break;
|
|
2996
|
+
}
|
|
2997
|
+
dir = dir.slice(0, dir.lastIndexOf("/"));
|
|
2998
|
+
}
|
|
2999
|
+
return rootFallback;
|
|
3000
|
+
}
|
|
3001
|
+
async function buildDevRoute(absolutePath, relativePath, root) {
|
|
3002
|
+
let page;
|
|
3003
|
+
let routeChain = [];
|
|
3004
|
+
try {
|
|
3005
|
+
const pageMod = await import(`${absolutePath}?furin-server&t=${Date.now()}`);
|
|
3006
|
+
if (isFurinPage(pageMod.default)) {
|
|
3007
|
+
page = pageMod.default;
|
|
3008
|
+
routeChain = collectRouteChainFromRoute(page._route);
|
|
3009
|
+
validateRouteChain(routeChain, root.route, relativePath);
|
|
3010
|
+
}
|
|
3011
|
+
} catch {}
|
|
3012
|
+
const devStubPage = {
|
|
3013
|
+
__type: "FURIN_PAGE",
|
|
3014
|
+
_route: { __type: "FURIN_ROUTE" },
|
|
3015
|
+
component: () => null
|
|
3016
|
+
};
|
|
3017
|
+
return {
|
|
3018
|
+
pattern: filePathToPattern(relativePath),
|
|
3019
|
+
path: absolutePath,
|
|
3020
|
+
mode: page ? resolveMode(page, routeChain) : "ssr",
|
|
3021
|
+
page: page ?? devStubPage,
|
|
3022
|
+
routeChain,
|
|
3023
|
+
segmentBoundaries: []
|
|
3024
|
+
};
|
|
3025
|
+
}
|
|
3026
|
+
function queryDefaultRedirectHook({ request, query, status, set }) {
|
|
3027
|
+
const resolvedQuery = query;
|
|
3028
|
+
const queryKeys = Object.keys(resolvedQuery);
|
|
3029
|
+
if (queryKeys.length === 0) {
|
|
3030
|
+
return;
|
|
3031
|
+
}
|
|
3032
|
+
const rawParams = new URL(request.url).searchParams;
|
|
3033
|
+
let needsRedirect = false;
|
|
3034
|
+
for (const key of queryKeys) {
|
|
3035
|
+
if (!rawParams.has(key) && resolvedQuery[key] != null) {
|
|
3036
|
+
needsRedirect = true;
|
|
3037
|
+
break;
|
|
3038
|
+
}
|
|
3039
|
+
}
|
|
3040
|
+
if (!needsRedirect) {
|
|
3041
|
+
return;
|
|
3042
|
+
}
|
|
3043
|
+
const url = new URL(request.url);
|
|
3044
|
+
for (const [k, v] of Object.entries(resolvedQuery)) {
|
|
3045
|
+
if (v != null) {
|
|
3046
|
+
url.searchParams.set(k, String(v));
|
|
3047
|
+
}
|
|
3048
|
+
}
|
|
3049
|
+
set.headers.location = url.pathname + url.search;
|
|
3050
|
+
return status("Found");
|
|
3051
|
+
}
|
|
3052
|
+
async function refreshLayoutChain(chain, pagePath, rootPath, importFn) {
|
|
3053
|
+
const resolveImport = importFn ?? ((s) => import(s));
|
|
3054
|
+
const pageDir = pagePath.slice(0, pagePath.lastIndexOf("/"));
|
|
3055
|
+
const pagesDir = rootPath.slice(0, rootPath.lastIndexOf("/"));
|
|
3056
|
+
const layoutPaths = [];
|
|
3057
|
+
let dir = pageDir;
|
|
3058
|
+
while (dir.length > pagesDir.length) {
|
|
3059
|
+
layoutPaths.unshift(`${dir}/_route.tsx`);
|
|
3060
|
+
dir = dir.slice(0, dir.lastIndexOf("/"));
|
|
3061
|
+
}
|
|
3062
|
+
let chainIdx = 1;
|
|
3063
|
+
for (const layoutPath of layoutPaths) {
|
|
3064
|
+
if (chainIdx >= chain.length) {
|
|
3065
|
+
break;
|
|
3066
|
+
}
|
|
3067
|
+
try {
|
|
3068
|
+
const freshMod = await resolveImport(`${layoutPath}?furin-server&t=${Date.now()}`);
|
|
3069
|
+
const freshRoute = freshMod.route ?? freshMod.default;
|
|
3070
|
+
if (freshRoute && isFurinRoute(freshRoute)) {
|
|
3071
|
+
const entry = chain[chainIdx];
|
|
3072
|
+
if (entry) {
|
|
3073
|
+
entry.layout = freshRoute.layout;
|
|
3074
|
+
entry.loader = freshRoute.loader;
|
|
3075
|
+
}
|
|
3076
|
+
}
|
|
3077
|
+
chainIdx++;
|
|
3078
|
+
} catch (err) {
|
|
3079
|
+
if (!isModuleNotFoundError(err)) {
|
|
3080
|
+
throw err;
|
|
3081
|
+
}
|
|
3082
|
+
}
|
|
3083
|
+
}
|
|
3084
|
+
}
|
|
3085
|
+
async function handleDevRequest(route, ctx, root) {
|
|
3086
|
+
try {
|
|
3087
|
+
let currentRoot = root;
|
|
3088
|
+
const rootMod = await import(`${root.path}?furin-server&t=${Date.now()}`);
|
|
3089
|
+
const rootExport = rootMod.route ?? rootMod.default;
|
|
3090
|
+
if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
|
|
3091
|
+
currentRoot = { path: root.path, route: rootExport };
|
|
3092
|
+
}
|
|
3093
|
+
const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
|
|
3094
|
+
const page = pageMod.default;
|
|
3095
|
+
if (page && isFurinPage(page)) {
|
|
3096
|
+
const chain = collectRouteChainFromRoute(page._route);
|
|
3097
|
+
await refreshLayoutChain(chain, route.path, root.path, undefined);
|
|
3098
|
+
return renderSSR({ ...route, page, routeChain: chain }, ctx, currentRoot);
|
|
3099
|
+
}
|
|
3100
|
+
} catch (err) {
|
|
3101
|
+
console.error(`[furin] Dev page load error for ${route.path}:`, err);
|
|
3102
|
+
}
|
|
3103
|
+
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" } });
|
|
3104
|
+
}
|
|
3105
|
+
async function handleSSGRequest(route, ctx, root, buildId) {
|
|
3106
|
+
const origin = new URL(ctx.request.url).origin;
|
|
3107
|
+
const entry = await prerenderSSG(route, ctx.params, root, origin, undefined);
|
|
3108
|
+
if (entry instanceof Response) {
|
|
3109
|
+
return entry;
|
|
3110
|
+
}
|
|
3111
|
+
const resolvedPath = resolvePath(route.pattern, ctx.params ?? {});
|
|
3112
|
+
const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
|
|
3113
|
+
if (etag && ctx.request.headers.get("if-none-match") === etag) {
|
|
3114
|
+
ctx.set.status = 304;
|
|
3115
|
+
return;
|
|
3116
|
+
}
|
|
3117
|
+
ctx.set.headers["content-type"] = "text/html; charset=utf-8";
|
|
3118
|
+
ctx.set.headers["cache-control"] = "public, max-age=0, must-revalidate, s-maxage=31536000";
|
|
3119
|
+
if (etag) {
|
|
3120
|
+
ctx.set.headers.etag = etag;
|
|
3121
|
+
}
|
|
3122
|
+
ctx.set.headers["cache-tag"] = resolvedPath;
|
|
3123
|
+
return entry.html;
|
|
3124
|
+
}
|
|
3125
|
+
function mergeRouteSchemas(routeChain, key) {
|
|
3126
|
+
const schemas = routeChain.map((r) => r[key]).filter(Boolean);
|
|
3127
|
+
if (schemas.length === 0) {
|
|
3128
|
+
return;
|
|
3129
|
+
}
|
|
3130
|
+
if (schemas.length === 1) {
|
|
3131
|
+
return schemas[0];
|
|
3132
|
+
}
|
|
3133
|
+
const mergedProperties = Object.assign({}, ...schemas.map((s) => s.properties ?? {}));
|
|
3134
|
+
const mergedOptions = Object.assign({}, ...schemas.map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))));
|
|
3135
|
+
return t.Object(mergedProperties, mergedOptions);
|
|
3136
|
+
}
|
|
3137
|
+
function createRoutePlugin(route, root, buildId = "") {
|
|
3138
|
+
const { pattern, routeChain } = route;
|
|
3139
|
+
const allParams = mergeRouteSchemas(routeChain, "params");
|
|
3140
|
+
const allQuery = mergeRouteSchemas(routeChain, "query");
|
|
3141
|
+
const hasQuerySchema = !!allQuery;
|
|
3142
|
+
const plugin = new Elysia2;
|
|
3143
|
+
if (allParams || allQuery) {
|
|
3144
|
+
plugin.guard({
|
|
3145
|
+
params: allParams,
|
|
3146
|
+
query: allQuery
|
|
3147
|
+
});
|
|
3148
|
+
}
|
|
3149
|
+
plugin.get(pattern, (ctx) => {
|
|
3150
|
+
if (hasQuerySchema) {
|
|
3151
|
+
const redirect = queryDefaultRedirectHook(ctx);
|
|
3152
|
+
if (redirect) {
|
|
3153
|
+
return redirect;
|
|
3154
|
+
}
|
|
3155
|
+
}
|
|
3156
|
+
if (IS_DEV) {
|
|
3157
|
+
return handleDevRequest(route, ctx, root);
|
|
3158
|
+
}
|
|
3159
|
+
if (route.mode === "ssg") {
|
|
3160
|
+
return handleSSGRequest(route, ctx, root, buildId);
|
|
3161
|
+
}
|
|
3162
|
+
if (route.mode === "isr") {
|
|
3163
|
+
ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
|
|
3164
|
+
return handleISR(route, ctx, root, buildId);
|
|
3165
|
+
}
|
|
3166
|
+
return renderSSR(route, ctx, root);
|
|
3167
|
+
});
|
|
3168
|
+
return plugin;
|
|
3169
|
+
}
|
|
3170
|
+
async function collectPageFilePaths(dir) {
|
|
3171
|
+
const files = [];
|
|
3172
|
+
const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
|
|
3173
|
+
for (const entry of entries) {
|
|
3174
|
+
const absolutePath = join(dir, entry.name);
|
|
3175
|
+
if (entry.isDirectory()) {
|
|
3176
|
+
files.push(...await collectPageFilePaths(absolutePath));
|
|
3177
|
+
continue;
|
|
3178
|
+
}
|
|
3179
|
+
if (entry.isFile()) {
|
|
3180
|
+
files.push(absolutePath);
|
|
3181
|
+
}
|
|
3182
|
+
}
|
|
3183
|
+
return files;
|
|
3184
|
+
}
|
|
3185
|
+
function resolveMode(page, routeChain) {
|
|
3186
|
+
const routeConfig = page._route;
|
|
3187
|
+
const mode = routeConfig.mode ?? page.mode;
|
|
3188
|
+
const revalidate = routeConfig.revalidate ?? page.revalidate;
|
|
3189
|
+
if (mode) {
|
|
3190
|
+
return mode;
|
|
3191
|
+
}
|
|
3192
|
+
const hasLoader = routeChain.some((r) => r.loader) || !!page.loader;
|
|
3193
|
+
if (!hasLoader) {
|
|
3194
|
+
return "ssg";
|
|
3195
|
+
}
|
|
3196
|
+
if (typeof revalidate === "number" && revalidate >= 0) {
|
|
3197
|
+
return "isr";
|
|
3198
|
+
}
|
|
3199
|
+
return "ssr";
|
|
3200
|
+
}
|
|
3201
|
+
function filePathToPattern(path) {
|
|
3202
|
+
const parts = path.replaceAll("\\", "/").split("/");
|
|
3203
|
+
const segments = [];
|
|
3204
|
+
for (const part of parts) {
|
|
3205
|
+
const name = parse(part).name;
|
|
3206
|
+
if (name === "index") {
|
|
3207
|
+
continue;
|
|
3208
|
+
}
|
|
3209
|
+
if (name.startsWith("[") && name.endsWith("]")) {
|
|
3210
|
+
const inner = name.slice(1, -1);
|
|
3211
|
+
if (inner.startsWith("...")) {
|
|
3212
|
+
segments.push("*");
|
|
3213
|
+
continue;
|
|
3214
|
+
}
|
|
3215
|
+
segments.push(`:${inner}`);
|
|
3216
|
+
continue;
|
|
3217
|
+
}
|
|
3218
|
+
segments.push(name);
|
|
3219
|
+
}
|
|
3220
|
+
return `/${segments.join("/")}`;
|
|
3221
|
+
}
|
|
3222
|
+
var CONVENTION_FILE_NAMES, TOBJECT_STRUCTURAL_KEYS;
|
|
3223
|
+
var init_router = __esm(() => {
|
|
3224
|
+
init_assemble();
|
|
3225
|
+
init_render();
|
|
3226
|
+
CONVENTION_FILE_NAMES = ["not-found", "error"];
|
|
3227
|
+
TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
|
|
3228
|
+
});
|
|
3229
|
+
|
|
3230
|
+
// src/dev-page-plugin.ts
|
|
3231
|
+
var exports_dev_page_plugin = {};
|
|
3232
|
+
__export(exports_dev_page_plugin, {
|
|
3233
|
+
rewriteSingletonImports: () => rewriteSingletonImports,
|
|
3234
|
+
rewriteRelativeImports: () => rewriteRelativeImports,
|
|
3235
|
+
rewriteBareImports: () => rewriteBareImports,
|
|
3236
|
+
registerDevPagePlugin: () => registerDevPagePlugin,
|
|
3237
|
+
injectJsxHelperImports: () => injectJsxHelperImports
|
|
3238
|
+
});
|
|
3239
|
+
import { dirname, resolve } from "path";
|
|
3240
|
+
import { fileURLToPath } from "url";
|
|
3241
|
+
function escapeRegExp(s) {
|
|
3242
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
3243
|
+
}
|
|
3244
|
+
function rewriteSingletonImports(source) {
|
|
3245
|
+
let result = source;
|
|
3246
|
+
for (const [pkg, absPath] of SINGLETON_PATHS) {
|
|
3247
|
+
const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(pkg)}["']`, "g");
|
|
3248
|
+
result = result.replace(re, (_, g1) => `${g1}"${absPath}"`);
|
|
3249
|
+
}
|
|
3250
|
+
return result;
|
|
3251
|
+
}
|
|
3252
|
+
function injectJsxHelperImports(transpiled) {
|
|
3253
|
+
const JSX_HELPER_RE = /\b(jsxDEV|jsxs|jsx|Fragment)_([0-9a-z]{8})\b/g;
|
|
3254
|
+
const devRuntime = new Map;
|
|
3255
|
+
const prodRuntime = new Map;
|
|
3256
|
+
for (const [, base, hash] of transpiled.matchAll(JSX_HELPER_RE)) {
|
|
3257
|
+
if (!(base && hash)) {
|
|
3258
|
+
continue;
|
|
3259
|
+
}
|
|
3260
|
+
const varName = `${base}_${hash}`;
|
|
3261
|
+
if (base === "jsxDEV" || base === "Fragment") {
|
|
3262
|
+
devRuntime.set(varName, base);
|
|
3263
|
+
} else {
|
|
3264
|
+
prodRuntime.set(varName, base);
|
|
3265
|
+
}
|
|
3266
|
+
}
|
|
3267
|
+
const lines = [];
|
|
3268
|
+
if (devRuntime.size > 0) {
|
|
3269
|
+
const absPath = SINGLETON_PATHS.get("react/jsx-dev-runtime");
|
|
3270
|
+
if (absPath) {
|
|
3271
|
+
const specifiers = [...devRuntime.entries()].map(([varName, exportName]) => `${exportName} as ${varName}`).join(", ");
|
|
3272
|
+
lines.push(`import { ${specifiers} } from "${absPath}";`);
|
|
3273
|
+
}
|
|
3274
|
+
}
|
|
3275
|
+
if (prodRuntime.size > 0) {
|
|
3276
|
+
const absPath = SINGLETON_PATHS.get("react/jsx-runtime");
|
|
3277
|
+
if (absPath) {
|
|
3278
|
+
const specifiers = [...prodRuntime.entries()].map(([varName, exportName]) => `${exportName} as ${varName}`).join(", ");
|
|
3279
|
+
lines.push(`import { ${specifiers} } from "${absPath}";`);
|
|
3280
|
+
}
|
|
3281
|
+
}
|
|
3282
|
+
if (lines.length === 0) {
|
|
3283
|
+
return transpiled;
|
|
3284
|
+
}
|
|
3285
|
+
return `${lines.join(`
|
|
3286
|
+
`)}
|
|
3287
|
+
${transpiled}`;
|
|
3288
|
+
}
|
|
3289
|
+
function rewriteRelativeImports(source, dir) {
|
|
3290
|
+
return source.replace(RELATIVE_SPECIFIER_RE, (match, relPath, offset) => {
|
|
3291
|
+
const lineStart = source.lastIndexOf(`
|
|
3292
|
+
`, offset - 1) + 1;
|
|
3293
|
+
const linePrefix = source.slice(lineStart, offset).trimStart();
|
|
3294
|
+
if (linePrefix.startsWith("//") || linePrefix.startsWith("*")) {
|
|
3295
|
+
return match;
|
|
3296
|
+
}
|
|
3297
|
+
const absPath = resolve(dir, relPath);
|
|
3298
|
+
const keyword = match.startsWith("import") ? "import" : "from";
|
|
3299
|
+
return `${keyword} "${absPath}"`;
|
|
3300
|
+
});
|
|
3301
|
+
}
|
|
3302
|
+
function rewriteBareImports(source, transpiled, dir) {
|
|
3303
|
+
const scanner = new Bun.Transpiler({ loader: "tsx" });
|
|
3304
|
+
let { imports } = scanner.scan(source);
|
|
3305
|
+
const seen = new Set;
|
|
3306
|
+
imports = imports.filter((imp) => {
|
|
3307
|
+
if (seen.has(imp.path)) {
|
|
3308
|
+
return false;
|
|
3309
|
+
}
|
|
3310
|
+
seen.add(imp.path);
|
|
3311
|
+
return true;
|
|
3312
|
+
});
|
|
3313
|
+
let result = transpiled;
|
|
3314
|
+
for (const imp of imports) {
|
|
3315
|
+
const spec = imp.path;
|
|
3316
|
+
if (spec.startsWith(".") || spec.startsWith("/") || spec.startsWith("file:")) {
|
|
3317
|
+
continue;
|
|
3318
|
+
}
|
|
3319
|
+
if (SINGLETON_PATHS.has(spec)) {
|
|
3320
|
+
continue;
|
|
3321
|
+
}
|
|
3322
|
+
let resolved;
|
|
3323
|
+
try {
|
|
3324
|
+
resolved = Bun.resolveSync(spec, dir);
|
|
3325
|
+
} catch {
|
|
3326
|
+
continue;
|
|
3327
|
+
}
|
|
3328
|
+
const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(spec)}["']`, "g");
|
|
3329
|
+
result = result.replace(re, (_, g1) => `${g1}"${resolved}"`);
|
|
3330
|
+
}
|
|
3331
|
+
return result;
|
|
3332
|
+
}
|
|
3333
|
+
function getSourceLoader(filePath) {
|
|
3334
|
+
if (filePath.endsWith(".tsx")) {
|
|
3335
|
+
return "tsx";
|
|
3336
|
+
}
|
|
3337
|
+
if (filePath.endsWith(".ts")) {
|
|
3338
|
+
return "ts";
|
|
3339
|
+
}
|
|
3340
|
+
if (filePath.endsWith(".jsx")) {
|
|
3341
|
+
return "jsx";
|
|
3342
|
+
}
|
|
3343
|
+
if (filePath.endsWith(".js")) {
|
|
3344
|
+
return "js";
|
|
3345
|
+
}
|
|
3346
|
+
return null;
|
|
3347
|
+
}
|
|
3348
|
+
function shouldSkipWorkspaceTransform(filePath) {
|
|
3349
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
3350
|
+
return normalized.includes("/.furin/");
|
|
3351
|
+
}
|
|
3352
|
+
function transformDevSource(raw, filePath, options) {
|
|
3353
|
+
const loader = getSourceLoader(filePath);
|
|
3354
|
+
if (!loader) {
|
|
3355
|
+
throw new Error(`[furin] Unsupported source loader for ${filePath}`);
|
|
3356
|
+
}
|
|
3357
|
+
const dir = dirname(filePath);
|
|
3358
|
+
const sourceForTranspile = options.rewriteRelativeImports ? rewriteRelativeImports(raw, dir) : raw;
|
|
3359
|
+
const transpiler = new Bun.Transpiler({ loader });
|
|
3360
|
+
const transpiled = transpiler.transformSync(sourceForTranspile, loader);
|
|
3361
|
+
let result = transpiled;
|
|
3362
|
+
if (options.rewriteBareImports) {
|
|
3363
|
+
result = rewriteBareImports(raw, result, dir);
|
|
3364
|
+
}
|
|
3365
|
+
result = rewriteSingletonImports(result);
|
|
3366
|
+
return injectJsxHelperImports(result);
|
|
3367
|
+
}
|
|
3368
|
+
function registerDevPagePlugin() {
|
|
3369
|
+
Bun.plugin({
|
|
3370
|
+
name: "furin-dev-page-loader",
|
|
3371
|
+
setup(build) {
|
|
3372
|
+
build.onResolve({ filter: FURIN_SERVER_FILTER }, (args) => {
|
|
3373
|
+
const tMatch = T_PARAM_RE.exec(args.path);
|
|
3374
|
+
const filePath = args.path.replace(STRIP_FURIN_SERVER_RE, "");
|
|
3375
|
+
const resolvedPath = tMatch ? `${filePath}?t=${tMatch[1]}` : filePath;
|
|
3376
|
+
return { path: resolvedPath, namespace: "furin-dev-page" };
|
|
3377
|
+
});
|
|
3378
|
+
build.onLoad({ filter: WORKSPACE_SOURCE_FILTER }, async (args) => {
|
|
3379
|
+
const raw = await Bun.file(args.path).text();
|
|
3380
|
+
const loader = getSourceLoader(args.path);
|
|
3381
|
+
if (!loader) {
|
|
3382
|
+
throw new Error(`[furin] Unsupported source loader for ${args.path}`);
|
|
3383
|
+
}
|
|
3384
|
+
if (shouldSkipWorkspaceTransform(args.path)) {
|
|
3385
|
+
return {
|
|
3386
|
+
contents: raw,
|
|
3387
|
+
loader
|
|
3388
|
+
};
|
|
3389
|
+
}
|
|
3390
|
+
const contents = transformDevSource(raw, args.path, {
|
|
3391
|
+
rewriteBareImports: false,
|
|
3392
|
+
rewriteRelativeImports: false
|
|
3393
|
+
});
|
|
3394
|
+
return {
|
|
3395
|
+
contents,
|
|
3396
|
+
loader: "js"
|
|
3397
|
+
};
|
|
3398
|
+
});
|
|
3399
|
+
build.onLoad({ namespace: "furin-dev-page", filter: ANY_FILTER }, async (args) => {
|
|
3400
|
+
const filePath = args.path.replace(STRIP_T_PARAM_RE, "");
|
|
3401
|
+
const raw = await Bun.file(filePath).text();
|
|
3402
|
+
const contents = transformDevSource(raw, filePath, {
|
|
3403
|
+
rewriteBareImports: true,
|
|
3404
|
+
rewriteRelativeImports: true
|
|
3405
|
+
});
|
|
3406
|
+
return {
|
|
3407
|
+
contents,
|
|
3408
|
+
loader: "js"
|
|
3409
|
+
};
|
|
3410
|
+
});
|
|
3411
|
+
}
|
|
3412
|
+
});
|
|
3413
|
+
}
|
|
3414
|
+
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;
|
|
3415
|
+
var init_dev_page_plugin = __esm(() => {
|
|
3416
|
+
FURIN_SERVER_FILTER = /\?furin-server(?:&t=\d+)?$/;
|
|
3417
|
+
ANY_FILTER = /.*/;
|
|
3418
|
+
WORKSPACE_SOURCE_FILTER = /^(?!.*(?:\/node_modules\/|\/\.bun\/))(?!.*\.(?:test|spec)\.[jt]sx?$).*\.[jt]sx?$/;
|
|
3419
|
+
T_PARAM_RE = /&t=(\d+)/;
|
|
3420
|
+
STRIP_FURIN_SERVER_RE = /\?furin-server.*$/;
|
|
3421
|
+
STRIP_T_PARAM_RE = /\?t=\d+$/;
|
|
3422
|
+
SINGLETON_PKGS = [
|
|
3423
|
+
"react",
|
|
3424
|
+
"react/jsx-runtime",
|
|
3425
|
+
"react/jsx-dev-runtime",
|
|
3426
|
+
"react-dom",
|
|
3427
|
+
"react-dom/server",
|
|
3428
|
+
"react-dom/client"
|
|
3429
|
+
];
|
|
3430
|
+
SINGLETON_PATHS = new Map;
|
|
3431
|
+
for (const pkg of SINGLETON_PKGS) {
|
|
3432
|
+
try {
|
|
3433
|
+
SINGLETON_PATHS.set(pkg, fileURLToPath(import.meta.resolve(pkg)));
|
|
3434
|
+
} catch {}
|
|
3435
|
+
}
|
|
3436
|
+
RELATIVE_SPECIFIER_RE = /(?:from|import)\s+["'](\.\.?\/[^"']+)["']/g;
|
|
3437
|
+
});
|
|
3438
|
+
|
|
3439
|
+
// src/build/route-types.ts
|
|
3440
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
3441
|
+
import { join as join2 } from "path";
|
|
3442
|
+
function patternToTypeString(pattern) {
|
|
3443
|
+
const t2 = pattern.replace(/:[^/]+/g, "${string}").replace(/\*/g, "${string}");
|
|
3444
|
+
return t2.includes("${") ? `\`${t2}\`` : `"${t2}"`;
|
|
3445
|
+
}
|
|
3446
|
+
function schemaToTypeString(schema) {
|
|
3447
|
+
if (!schema || typeof schema !== "object") {
|
|
3448
|
+
return "unknown";
|
|
3449
|
+
}
|
|
3450
|
+
const s = schema;
|
|
3451
|
+
if (s.anyOf && Array.isArray(s.anyOf)) {
|
|
3452
|
+
const parts = s.anyOf.map(schemaToTypeString).filter((t2) => t2 !== "null");
|
|
3453
|
+
return parts.join(" | ") || "unknown";
|
|
3454
|
+
}
|
|
3455
|
+
switch (s.type) {
|
|
3456
|
+
case "string":
|
|
3457
|
+
return "string";
|
|
3458
|
+
case "number":
|
|
3459
|
+
case "integer":
|
|
3460
|
+
return "number";
|
|
3461
|
+
case "boolean":
|
|
3462
|
+
return "boolean";
|
|
3463
|
+
case "null":
|
|
3464
|
+
return "null";
|
|
3465
|
+
case "object": {
|
|
3466
|
+
if (!s.properties || typeof s.properties !== "object") {
|
|
3467
|
+
return "Record<string, unknown>";
|
|
3468
|
+
}
|
|
3469
|
+
const required = new Set(Array.isArray(s.required) ? s.required : []);
|
|
3470
|
+
const props = Object.entries(s.properties).map(([k, v]) => `${k}${required.has(k) ? "" : "?"}: ${schemaToTypeString(v)}`).join("; ");
|
|
3471
|
+
return `{ ${props} }`;
|
|
3472
|
+
}
|
|
3473
|
+
default:
|
|
3474
|
+
return "unknown";
|
|
3475
|
+
}
|
|
3476
|
+
}
|
|
3477
|
+
function writeRouteTypes(routes, projectRoot) {
|
|
3478
|
+
const entries = routes.map((r) => {
|
|
3479
|
+
const typeKey = patternToTypeString(r.pattern);
|
|
3480
|
+
const isDynamic = typeKey.startsWith("`");
|
|
3481
|
+
const querySchema = r.routeChain?.find((rt) => rt.query)?.query;
|
|
3482
|
+
const searchType = querySchema ? schemaToTypeString(querySchema) : "never";
|
|
3483
|
+
return isDynamic ? ` [key: ${typeKey}]: { search?: ${searchType} }` : ` ${typeKey}: { search?: ${searchType} }`;
|
|
3484
|
+
});
|
|
3485
|
+
const content = `// Auto-generated by Furin. Do not edit manually.
|
|
3486
|
+
/// <reference types="@teyik0/furin/env" />
|
|
3487
|
+
import "@teyik0/furin/link";
|
|
3488
|
+
|
|
3489
|
+
declare module "@teyik0/furin/link" {
|
|
3490
|
+
interface RouteManifest {
|
|
3491
|
+
${entries.join(`;
|
|
3492
|
+
`)};
|
|
3493
|
+
}
|
|
3494
|
+
}
|
|
3495
|
+
`;
|
|
3496
|
+
const typesPath = join2(projectRoot, "furin-env.d.ts");
|
|
3497
|
+
const existing = existsSync2(typesPath) ? readFileSync2(typesPath, "utf8") : "";
|
|
3498
|
+
if (content !== existing) {
|
|
3499
|
+
writeFileSync(typesPath, content);
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
3502
|
+
var init_route_types = () => {};
|
|
3503
|
+
|
|
3504
|
+
// src/build/hydrate.ts
|
|
3505
|
+
var exports_hydrate = {};
|
|
3506
|
+
__export(exports_hydrate, {
|
|
3507
|
+
writeDevFiles: () => writeDevFiles,
|
|
3508
|
+
generateHydrateEntry: () => generateHydrateEntry
|
|
3509
|
+
});
|
|
3510
|
+
import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
|
|
3511
|
+
import { join as join3 } from "path";
|
|
3512
|
+
function generateHydrateEntry(routes, rootLayout, basePath) {
|
|
3513
|
+
const conventionIdents = new Map;
|
|
3514
|
+
const getIdent = (filePath) => {
|
|
3515
|
+
if (!filePath) {
|
|
3516
|
+
return;
|
|
3517
|
+
}
|
|
3518
|
+
const existing = conventionIdents.get(filePath);
|
|
3519
|
+
if (existing) {
|
|
3520
|
+
return existing;
|
|
3521
|
+
}
|
|
3522
|
+
const ident = `__furin_bnd_${conventionIdents.size}`;
|
|
3523
|
+
conventionIdents.set(filePath, ident);
|
|
3524
|
+
return ident;
|
|
3525
|
+
};
|
|
3526
|
+
const routeEntries = [];
|
|
3527
|
+
for (const route of routes) {
|
|
3528
|
+
const resolvedPage = route.path.replace(/\\/g, "/");
|
|
3529
|
+
const regexPattern = route.pattern.replace(/:[^/]+/g, "([^/]+)").replace(/\*/g, "(.*)");
|
|
3530
|
+
const boundaryLiterals = [];
|
|
3531
|
+
for (const seg of route.segmentBoundaries ?? []) {
|
|
3532
|
+
const errorIdent = getIdent(seg.errorPath);
|
|
3533
|
+
const notFoundIdent = getIdent(seg.notFoundPath);
|
|
3534
|
+
if (!(errorIdent || notFoundIdent)) {
|
|
3535
|
+
continue;
|
|
3536
|
+
}
|
|
3537
|
+
const parts = [`depth: ${seg.depth}`];
|
|
3538
|
+
if (errorIdent) {
|
|
3539
|
+
parts.push(`error: ${errorIdent}`);
|
|
3540
|
+
}
|
|
3541
|
+
if (notFoundIdent) {
|
|
3542
|
+
parts.push(`notFound: ${notFoundIdent}`);
|
|
3543
|
+
}
|
|
3544
|
+
boundaryLiterals.push(`{ ${parts.join(", ")} }`);
|
|
3545
|
+
}
|
|
3546
|
+
const boundariesField = boundaryLiterals.length > 0 ? `, segmentBoundaries: [${boundaryLiterals.join(", ")}]` : "";
|
|
3547
|
+
routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp("^${regexPattern}$"), load: () => import("${resolvedPage}")${boundariesField} }`);
|
|
3548
|
+
}
|
|
3549
|
+
const conventionImportLines = [...conventionIdents.entries()].map(([filePath, ident]) => `import ${ident} from "${filePath.replace(/\\/g, "/")}";`).join(`
|
|
3550
|
+
`);
|
|
3551
|
+
const basePathLiteral = JSON.stringify(basePath);
|
|
3552
|
+
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";
|
|
3553
|
+
const logEndpoint = basePath ? `${JSON.stringify(basePath)} + "/_furin/ingest"` : `"/_furin/ingest"`;
|
|
3554
|
+
const basePathProp = basePath ? `
|
|
3555
|
+
basePath: ${basePathLiteral},` : "";
|
|
3556
|
+
const conventionImportsBlock = conventionImportLines ? `
|
|
3557
|
+
${conventionImportLines}` : "";
|
|
3558
|
+
return `import { hydrateRoot, createRoot } from "react-dom/client";
|
|
3559
|
+
import { createElement } from "react";
|
|
3560
|
+
import { initLogger, log } from "evlog";
|
|
3561
|
+
import { createHttpLogDrain } from "evlog/http";
|
|
3562
|
+
import { RouterProvider } from "@teyik0/furin/link";
|
|
3563
|
+
import { route as root } from "${rootLayout.replace(/\\/g, "/")}";${conventionImportsBlock}
|
|
3564
|
+
|
|
3565
|
+
initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });
|
|
3566
|
+
|
|
3567
|
+
const routes = [
|
|
3568
|
+
${routeEntries.join(`,
|
|
3569
|
+
`)}
|
|
3570
|
+
];
|
|
3571
|
+
|
|
3572
|
+
const pathname = ${pathnameExpr};
|
|
3573
|
+
const _match = routes.find((r) => r.regex.test(pathname));
|
|
3574
|
+
|
|
3575
|
+
// Parse the server-embedded loader payload up front. It carries:
|
|
3576
|
+
// - normal loader props under arbitrary keys,
|
|
3577
|
+
// - __furinError.digest when SSR caught an error,
|
|
3578
|
+
// - __furinStatus: 404 when the server rendered the catch-all not-found
|
|
3579
|
+
// (direct load to an unknown URL, emitted by renderRootNotFound) OR when
|
|
3580
|
+
// a matched loader threw notFound(). The latter still has a _match; the
|
|
3581
|
+
// former does not \u2014 so the two cases fork on _match below.
|
|
3582
|
+
const dataEl = document.getElementById("__FURIN_DATA__");
|
|
3583
|
+
const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
|
|
3584
|
+
const rootEl = document.getElementById("root") as HTMLElement;
|
|
3585
|
+
|
|
3586
|
+
// Eagerly load only the current page module for initial hydration.
|
|
3587
|
+
// All other pages are loaded on demand when the user navigates to them.
|
|
3588
|
+
// Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
|
|
3589
|
+
// bundler to misidentify which chunk to reference as the entry in index.html.
|
|
3590
|
+
(async () => {
|
|
3591
|
+
let app;
|
|
3592
|
+
if (_match) {
|
|
3593
|
+
const _mod = await _match.load();
|
|
3594
|
+
const match = { ..._match, component: _mod.default.component, pageRoute: _mod.default._route };
|
|
3595
|
+
|
|
3596
|
+
const isNotFound = loaderData.__furinStatus === 404;
|
|
3597
|
+
|
|
3598
|
+
app = createElement(RouterProvider, {
|
|
3599
|
+
routes,
|
|
3600
|
+
root,
|
|
3601
|
+
initialMatch: match,
|
|
3602
|
+
initialData: loaderData,
|
|
3603
|
+
initialDigest: loaderData.__furinError?.digest,
|
|
3604
|
+
initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${basePathProp}
|
|
3605
|
+
} as any);
|
|
3606
|
+
} else if (loaderData.__furinStatus === 404) {
|
|
3607
|
+
// Direct load to an unknown URL. The server sent the root not-found UI
|
|
3608
|
+
// already rendered into the DOM. Mount RouterProvider with a null match
|
|
3609
|
+
// so the provider boots into its not-found branch, hydrating that exact
|
|
3610
|
+
// tree INSIDE a live RouterContext. Without this, Links in the 404 UI
|
|
3611
|
+
// (e.g. the default screen's "Go Home" button) hit the useRouter()
|
|
3612
|
+
// fallback that does a full window.location assignment \u2014 a jarring reload.
|
|
3613
|
+
// Strip the server-only signal keys before handing data to components.
|
|
3614
|
+
const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = loaderData;
|
|
3615
|
+
app = createElement(RouterProvider, {
|
|
3616
|
+
routes,
|
|
3617
|
+
root,
|
|
3618
|
+
initialMatch: null,
|
|
3619
|
+
initialData: cleanData,
|
|
3620
|
+
initialDigest: loaderData.__furinError?.digest,
|
|
3621
|
+
initialNotFound: loaderData.__furinNotFound ?? {},${basePathProp}
|
|
3622
|
+
} as any);
|
|
3623
|
+
} else {
|
|
3624
|
+
// No match and no 404 signal \u2014 either the client bundle is out of sync
|
|
3625
|
+
// with the server (stale deploy) or the server returned something we
|
|
3626
|
+
// don't know how to hydrate. Bail loudly; the page stays static.
|
|
3627
|
+
log.error({ action: "hydrate_no_match", pathname });
|
|
3628
|
+
return;
|
|
3629
|
+
}
|
|
3630
|
+
|
|
3631
|
+
if (import.meta.hot) {
|
|
3632
|
+
// Dev mode \u2014 preserve root across HMR using a window global.
|
|
3633
|
+
// window is the only object that survives Bun's module re-evaluation.
|
|
3634
|
+
// biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
|
|
3635
|
+
const existingRoot = (window as any).__FURIN_ROOT__;
|
|
3636
|
+
if (existingRoot) {
|
|
3637
|
+
// Already mounted \u2014 reconciliation, NOT hydration. React Fast Refresh
|
|
3638
|
+
// patched the component in-place, now re-render with the new module.
|
|
3639
|
+
existingRoot.render(app);
|
|
3640
|
+
// The initialData embedded in the DOM is stale (from the original SSR).
|
|
3641
|
+
// Trigger a loader-data refresh so the component renders with fresh
|
|
3642
|
+
// server state, avoiding hydration mismatches after a _route.tsx edit.
|
|
3643
|
+
const hmrRefresh = (window as any).__FURIN_HMR_REFRESH__;
|
|
3644
|
+
if (hmrRefresh) {
|
|
3645
|
+
requestAnimationFrame(() => hmrRefresh());
|
|
3646
|
+
}
|
|
3647
|
+
} else if (rootEl.innerHTML.trim()) {
|
|
3648
|
+
// First load with SSR content \u2014 hydrateRoot renders on construction
|
|
3649
|
+
const root = hydrateRoot(rootEl, app);
|
|
3650
|
+
// biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
|
|
3651
|
+
(window as any).__FURIN_ROOT__ = root;
|
|
3652
|
+
} else {
|
|
3653
|
+
// First load without SSR content \u2014 createRoot requires explicit .render()
|
|
3654
|
+
const root = createRoot(rootEl);
|
|
3655
|
+
root.render(app);
|
|
3656
|
+
// biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
|
|
3657
|
+
(window as any).__FURIN_ROOT__ = root;
|
|
3658
|
+
}
|
|
3659
|
+
} else if (rootEl.innerHTML.trim()) {
|
|
3660
|
+
hydrateRoot(rootEl, app);
|
|
3661
|
+
} else {
|
|
3662
|
+
createRoot(rootEl).render(app);
|
|
3663
|
+
}
|
|
3664
|
+
|
|
3665
|
+
log.info({ action: "hydrate_complete", pathname });
|
|
3666
|
+
})().catch((err: unknown) => {
|
|
3667
|
+
log.error({ action: "hydrate_failed", pathname, error: String(err) });
|
|
3668
|
+
});
|
|
3669
|
+
`;
|
|
3670
|
+
}
|
|
3671
|
+
function writeDevFiles(routes, { outDir, rootLayout, basePath }, projectRoot) {
|
|
3672
|
+
if (!existsSync3(outDir)) {
|
|
3673
|
+
mkdirSync(outDir, { recursive: true });
|
|
3674
|
+
}
|
|
3675
|
+
const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath);
|
|
3676
|
+
const hydratePath = join3(outDir, "_hydrate.tsx");
|
|
3677
|
+
const existingHydrate = existsSync3(hydratePath) ? readFileSync3(hydratePath, "utf8") : "";
|
|
3678
|
+
if (hydrateCode !== existingHydrate) {
|
|
3679
|
+
writeFileSync2(hydratePath, hydrateCode);
|
|
3680
|
+
}
|
|
3681
|
+
const indexHtml = generateIndexHtml();
|
|
3682
|
+
const indexPath = join3(outDir, "index.html");
|
|
3683
|
+
const existingIndex = existsSync3(indexPath) ? readFileSync3(indexPath, "utf8") : "";
|
|
3684
|
+
if (indexHtml !== existingIndex) {
|
|
3685
|
+
writeFileSync2(indexPath, indexHtml);
|
|
3686
|
+
}
|
|
3687
|
+
writeRouteTypes(routes, projectRoot);
|
|
3688
|
+
console.log("[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)");
|
|
3689
|
+
}
|
|
3690
|
+
var init_hydrate = __esm(() => {
|
|
3691
|
+
init_shell();
|
|
3692
|
+
init_route_types();
|
|
3693
|
+
});
|
|
3694
|
+
|
|
3695
|
+
// src/furin.ts
|
|
3696
|
+
init_dist();
|
|
3697
|
+
init_elysia();
|
|
3698
|
+
init_cache();
|
|
3699
|
+
init_render();
|
|
3700
|
+
init_template();
|
|
3701
|
+
init_router();
|
|
3702
|
+
init_not_found();
|
|
3703
|
+
init_cache();
|
|
3704
|
+
init_render();
|
|
3705
|
+
import { existsSync as existsSync4 } from "fs";
|
|
3706
|
+
import { basename, dirname as dirname2, join as join4, resolve as resolve2 } from "path";
|
|
3707
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
3708
|
+
import { staticPlugin } from "@elysiajs/static";
|
|
3709
|
+
import { Elysia as Elysia3, file } from "elysia";
|
|
3710
|
+
function resolveClientDirFromArgv() {
|
|
3711
|
+
return resolveClientDirFromEnv() ?? resolveClientDirFromModuleUrl() ?? resolveClientDirFromProcessArgs() ?? resolveFallbackClientDir();
|
|
3712
|
+
}
|
|
3713
|
+
function resolveClientDirFromEnv() {
|
|
3714
|
+
const envClientDir = process.env.FURIN_CLIENT_DIR;
|
|
3715
|
+
if (!envClientDir) {
|
|
3716
|
+
return null;
|
|
3717
|
+
}
|
|
3718
|
+
return envClientDir.startsWith("/") ? envClientDir : resolve2(process.cwd(), envClientDir);
|
|
3719
|
+
}
|
|
3720
|
+
function resolveClientDirFromModuleUrl() {
|
|
3721
|
+
try {
|
|
3722
|
+
const moduleUrl = new URL(import.meta.url);
|
|
3723
|
+
if (moduleUrl.protocol !== "file:") {
|
|
3724
|
+
return null;
|
|
3725
|
+
}
|
|
3726
|
+
const modulePath = fileURLToPath2(moduleUrl);
|
|
3727
|
+
if (modulePath.includes("/$bunfs/")) {
|
|
3728
|
+
return null;
|
|
3729
|
+
}
|
|
3730
|
+
const moduleClientDir = join4(dirname2(modulePath), "client");
|
|
3731
|
+
if (existsSync4(join4(moduleClientDir, "index.html"))) {
|
|
3732
|
+
return moduleClientDir;
|
|
3733
|
+
}
|
|
3734
|
+
} catch {}
|
|
3735
|
+
return null;
|
|
3736
|
+
}
|
|
3737
|
+
function resolveClientDirFromProcessArgs() {
|
|
3738
|
+
const candidates = [
|
|
3739
|
+
process.argv[1],
|
|
3740
|
+
process.argv[0],
|
|
3741
|
+
process.argv0,
|
|
3742
|
+
process.execPath
|
|
3743
|
+
].filter((value) => typeof value === "string" && value.length > 0);
|
|
3744
|
+
for (const candidate of candidates) {
|
|
3745
|
+
const resolved = resolveClientDirFromCandidate(candidate);
|
|
3746
|
+
if (resolved) {
|
|
3747
|
+
return resolved;
|
|
3748
|
+
}
|
|
3749
|
+
}
|
|
3750
|
+
return null;
|
|
3751
|
+
}
|
|
3752
|
+
function resolveClientDirFromCandidate(candidate) {
|
|
3753
|
+
const name = basename(candidate);
|
|
3754
|
+
if (name === "bun" || name === "node") {
|
|
3755
|
+
return null;
|
|
3756
|
+
}
|
|
3757
|
+
if (candidate.includes("/$bunfs/") || candidate.startsWith("bunfs:")) {
|
|
3758
|
+
return null;
|
|
3759
|
+
}
|
|
3760
|
+
const absolute = candidate.startsWith("/") ? candidate : resolve2(process.cwd(), candidate);
|
|
3761
|
+
if (existsSync4(absolute)) {
|
|
3762
|
+
return join4(dirname2(absolute), "client");
|
|
3763
|
+
}
|
|
3764
|
+
if (!candidate.includes("/")) {
|
|
3765
|
+
return resolveClientDirFromPath(candidate);
|
|
3766
|
+
}
|
|
3767
|
+
return null;
|
|
3768
|
+
}
|
|
3769
|
+
function resolveClientDirFromPath(candidate) {
|
|
3770
|
+
const pathEntries = process.env.PATH?.split(":") ?? [];
|
|
3771
|
+
for (const dir of pathEntries) {
|
|
3772
|
+
const fullPath = join4(dir, candidate);
|
|
3773
|
+
if (existsSync4(fullPath)) {
|
|
3774
|
+
return join4(dirname2(fullPath), "client");
|
|
3775
|
+
}
|
|
3776
|
+
}
|
|
3777
|
+
return null;
|
|
3778
|
+
}
|
|
3779
|
+
function resolveFallbackClientDir() {
|
|
3780
|
+
const defaultClientDir = resolve2(process.cwd(), ".furin/build/bun/client");
|
|
3781
|
+
if (existsSync4(join4(defaultClientDir, "index.html"))) {
|
|
3782
|
+
return defaultClientDir;
|
|
3783
|
+
}
|
|
3784
|
+
return join4(process.cwd(), "client");
|
|
3785
|
+
}
|
|
3786
|
+
async function setupProdTemplate(embedded, clientDir) {
|
|
3787
|
+
if (embedded) {
|
|
3788
|
+
if (!embedded.template) {
|
|
3789
|
+
throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
|
|
3790
|
+
}
|
|
3791
|
+
const html = await Bun.file(embedded.template).text();
|
|
3792
|
+
setProductionTemplateContent(html);
|
|
3793
|
+
return;
|
|
3794
|
+
}
|
|
3795
|
+
const templatePath = join4(clientDir, "index.html");
|
|
3796
|
+
if (!existsSync4(templatePath)) {
|
|
3797
|
+
throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
|
|
3798
|
+
}
|
|
3799
|
+
setProductionTemplatePath(templatePath);
|
|
3800
|
+
}
|
|
3801
|
+
function wrapWithRequestScope(app) {
|
|
3802
|
+
return app.wrap((handler, _request) => (ctx) => _runWithRequestInvalidationScope(() => handler(ctx)));
|
|
3803
|
+
}
|
|
3804
|
+
async function furin({
|
|
3805
|
+
pagesDir,
|
|
3806
|
+
logger
|
|
3807
|
+
}) {
|
|
3808
|
+
const { exclude: userExclude, ...evlogOptions } = logger ?? {};
|
|
3809
|
+
initLogger({ env: { service: "furin" } });
|
|
3810
|
+
const loggerPlugin = new Elysia3().use(evlog({
|
|
3811
|
+
...evlogOptions,
|
|
3812
|
+
exclude: [
|
|
3813
|
+
"/_client/**",
|
|
3814
|
+
"/public/**",
|
|
3815
|
+
"/favicon.ico",
|
|
3816
|
+
"/_furin/!(ingest)",
|
|
3817
|
+
"/_bun_hmr_entry/**",
|
|
3818
|
+
...userExclude ?? []
|
|
3819
|
+
]
|
|
3820
|
+
})).post("/_furin/ingest", ({ body, log, status }) => {
|
|
3821
|
+
if (!Array.isArray(body)) {
|
|
3822
|
+
return status("Bad Request");
|
|
3823
|
+
}
|
|
3824
|
+
const batch = body.slice(0, 100);
|
|
3825
|
+
for (const entry of batch) {
|
|
3826
|
+
if (!entry || typeof entry !== "object" || !("event" in entry)) {
|
|
3827
|
+
log.set({ msg: "[furin] ingest: skipping malformed entry" });
|
|
3828
|
+
continue;
|
|
3829
|
+
}
|
|
3830
|
+
const event = entry.event;
|
|
3831
|
+
if (!event || typeof event !== "object") {
|
|
3832
|
+
continue;
|
|
3833
|
+
}
|
|
3834
|
+
const {
|
|
3835
|
+
__proto__,
|
|
3836
|
+
constructor: _ctor,
|
|
3837
|
+
prototype,
|
|
3838
|
+
environment: _browserEnv,
|
|
3839
|
+
...safeEvent
|
|
3840
|
+
} = event;
|
|
3841
|
+
log.set({ ...safeEvent, service: "furin:browser" });
|
|
3842
|
+
}
|
|
3843
|
+
return status("No Content");
|
|
3844
|
+
}, { parse: "json" });
|
|
3845
|
+
const cwd = process.cwd();
|
|
3846
|
+
const ctx = getCompileContext();
|
|
3847
|
+
const resolvedPagesDir = ctx?.rootPath ? dirname2(ctx.rootPath) : resolve2(cwd, pagesDir ?? "src/pages");
|
|
3848
|
+
const instanceName = `furin-${resolvedPagesDir.replaceAll("\\", "/")}`;
|
|
3849
|
+
if (IS_DEV) {
|
|
3850
|
+
const furinDir = resolve2(cwd, ".furin");
|
|
3851
|
+
const { registerDevPagePlugin: registerDevPagePlugin2 } = await Promise.resolve().then(() => (init_dev_page_plugin(), exports_dev_page_plugin));
|
|
3852
|
+
registerDevPagePlugin2();
|
|
3853
|
+
const { scanPages: scanPages2 } = await Promise.resolve().then(() => (init_router(), exports_router));
|
|
3854
|
+
const { root: root2, routes: routes2 } = await scanPages2(resolvedPagesDir);
|
|
3855
|
+
const { writeDevFiles: writeDevFiles2 } = await Promise.resolve().then(() => (init_hydrate(), exports_hydrate));
|
|
3856
|
+
writeDevFiles2(routes2, { outDir: furinDir, rootLayout: root2.path, basePath: "", publicPath: "/_client/" }, cwd);
|
|
3857
|
+
const publicDir = resolve2(cwd, "public");
|
|
3858
|
+
const publicExists = existsSync4(publicDir);
|
|
3859
|
+
const devApp = new Elysia3({ name: instanceName, seed: resolvedPagesDir }).use(loggerPlugin).onError({ as: "global" }, async ({ code, request }) => {
|
|
3860
|
+
if (code === "NOT_FOUND") {
|
|
3861
|
+
return await renderRootNotFound(root2, request);
|
|
3862
|
+
}
|
|
3863
|
+
}).onAfterHandle({ as: "global" }, ({ set }) => {
|
|
3864
|
+
const pending = consumePendingInvalidations();
|
|
3865
|
+
if (pending.length > 0) {
|
|
3866
|
+
set.headers["x-furin-revalidate"] = pending.join(",");
|
|
3867
|
+
}
|
|
3868
|
+
}).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) => {
|
|
3869
|
+
for (const route of routes2) {
|
|
3870
|
+
app.use(createRoutePlugin(route, root2));
|
|
3871
|
+
}
|
|
3872
|
+
return app;
|
|
3873
|
+
});
|
|
3874
|
+
return wrapWithRequestScope(devApp);
|
|
3875
|
+
}
|
|
3876
|
+
if (!ctx) {
|
|
3877
|
+
throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
|
|
3878
|
+
}
|
|
3879
|
+
const { root, routes } = loadProdRoutes(ctx);
|
|
3880
|
+
const prodBuildId = ctx.buildId ?? "";
|
|
3881
|
+
setBuildId(prodBuildId);
|
|
3882
|
+
const embedded = ctx?.embedded;
|
|
3883
|
+
const clientDir = embedded ? "" : resolveClientDirFromArgv();
|
|
3884
|
+
await setupProdTemplate(embedded, clientDir);
|
|
3885
|
+
const prodApp = new Elysia3({ name: instanceName, seed: resolvedPagesDir }).use(loggerPlugin).onError({ as: "global" }, async ({ code, request }) => {
|
|
3886
|
+
if (code === "NOT_FOUND") {
|
|
3887
|
+
return await renderRootNotFound(root, request);
|
|
3888
|
+
}
|
|
3889
|
+
}).onAfterHandle({ as: "global" }, ({ path, set }) => {
|
|
3890
|
+
if (path.startsWith("/_client/")) {
|
|
3891
|
+
set.headers["cache-control"] = "public, max-age=31536000, immutable";
|
|
3892
|
+
}
|
|
3893
|
+
const pending = consumePendingInvalidations();
|
|
3894
|
+
if (pending.length > 0) {
|
|
3895
|
+
set.headers["x-furin-revalidate"] = pending.join(",");
|
|
3896
|
+
}
|
|
3897
|
+
const buildId = getBuildId();
|
|
3898
|
+
if (buildId) {
|
|
3899
|
+
set.headers["x-furin-build-id"] = buildId;
|
|
3900
|
+
}
|
|
3901
|
+
}).onStart(async ({ server }) => {
|
|
3902
|
+
const origin = server?.url?.origin ?? "http://localhost:3000";
|
|
3903
|
+
await warmSSGCache(routes, root, origin);
|
|
3904
|
+
}).use(await (async () => {
|
|
3905
|
+
if (embedded) {
|
|
3906
|
+
return new Elysia3().get("/favicon.ico", ({ status }) => {
|
|
3907
|
+
const asset = embedded.assets["/public/favicon.ico"];
|
|
3908
|
+
if (!asset) {
|
|
3909
|
+
return status("Not Found");
|
|
3910
|
+
}
|
|
3911
|
+
return Bun.file(asset);
|
|
3912
|
+
}).get("/_client/*", ({ params, status }) => {
|
|
3913
|
+
const asset = embedded.assets[`/_client/${params["*"]}`];
|
|
3914
|
+
if (!asset) {
|
|
3915
|
+
return status("Not Found");
|
|
3916
|
+
}
|
|
3917
|
+
return Bun.file(asset);
|
|
3918
|
+
}).get("/public/*", ({ params, status }) => {
|
|
3919
|
+
const asset = embedded.assets[`/public/${params["*"]}`];
|
|
3920
|
+
if (!asset) {
|
|
3921
|
+
return status("Not Found");
|
|
3922
|
+
}
|
|
3923
|
+
return Bun.file(asset);
|
|
3924
|
+
});
|
|
3925
|
+
}
|
|
3926
|
+
const publicDir = join4(dirname2(clientDir), "public");
|
|
3927
|
+
const app = new Elysia3;
|
|
3928
|
+
if (existsSync4(publicDir)) {
|
|
3929
|
+
app.get("/favicon.ico", file(join4(publicDir, "favicon.ico"))).use(await staticPlugin({ assets: publicDir, prefix: "/public" }));
|
|
3930
|
+
}
|
|
3931
|
+
app.use(await staticPlugin({ assets: clientDir, prefix: "/_client" }));
|
|
3932
|
+
return app;
|
|
3933
|
+
})()).use((app) => {
|
|
3934
|
+
for (const route of routes) {
|
|
3935
|
+
app.use(createRoutePlugin(route, root, prodBuildId));
|
|
3936
|
+
}
|
|
3937
|
+
return app;
|
|
3938
|
+
});
|
|
3939
|
+
return wrapWithRequestScope(prodApp);
|
|
3940
|
+
}
|
|
3941
|
+
export {
|
|
3942
|
+
setCachePurger,
|
|
3943
|
+
revalidatePath,
|
|
3944
|
+
renderRootNotFound,
|
|
3945
|
+
notFound,
|
|
3946
|
+
isNotFoundError,
|
|
3947
|
+
furin
|
|
3948
|
+
};
|