@teyik0/furin 0.1.0-alpha.12 → 0.1.0-alpha.13

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/router.ts ADDED
@@ -0,0 +1,1034 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readdir } from "node:fs/promises";
3
+ import { join, parse } from "node:path";
4
+ import { type AnyElysia, type Context, Elysia, t } from "elysia";
5
+ import type { AnySchema } from "elysia/types";
6
+ import type { RuntimePage, RuntimeRoute } from "./client.ts";
7
+ import type { ErrorComponent } from "./error.ts";
8
+ import { type CompileContext, getCompileContext } from "./internal.ts";
9
+ import type { NotFoundComponent } from "./not-found.ts";
10
+ import { resolvePath } from "./render/assemble.ts";
11
+ import {
12
+ type DevLoaderCacheEntry,
13
+ getDevISRLoaderCache,
14
+ getDevSSGLoaderCache,
15
+ isDevLoaderCacheValid,
16
+ setDevISRLoaderCache,
17
+ setDevSSGLoaderCache,
18
+ } from "./render/dev-cache.ts";
19
+ import {
20
+ handleISR,
21
+ type LoaderResult,
22
+ prerenderSSG,
23
+ renderSSR,
24
+ runLoaders,
25
+ } from "./render/index.ts";
26
+ import { IS_DEV } from "./runtime-env.ts";
27
+ import {
28
+ collectRouteChainFromRoute,
29
+ isFurinPage,
30
+ isFurinRoute,
31
+ validateRouteChain,
32
+ } from "./utils.ts";
33
+
34
+ function isModuleNotFoundError(err: unknown): boolean {
35
+ if (!err || (typeof err !== "object" && typeof err !== "string")) {
36
+ return false;
37
+ }
38
+ const msg =
39
+ typeof err === "string"
40
+ ? err.toLowerCase()
41
+ : String((err as { message?: unknown }).message ?? "").toLowerCase();
42
+ const code = typeof err === "string" ? undefined : (err as { code?: string }).code;
43
+ return (
44
+ code === "ENOENT" ||
45
+ code === "ERR_MODULE_NOT_FOUND" ||
46
+ code === "MODULE_NOT_FOUND" ||
47
+ msg.includes("cannot find module") ||
48
+ msg.includes("module not found") ||
49
+ msg.includes("no such file or directory")
50
+ );
51
+ }
52
+
53
+ /**
54
+ * A single directory-scoped boundary declaration.
55
+ *
56
+ * Each entry represents ONE directory on the path from `pagesDir` to the page
57
+ * file. `error` / `notFound` hold the components defined IN THAT DIRECTORY
58
+ * only — never inherited from a parent. This 1:1 tie between directory and
59
+ * entry is what lets the render layer insert React error boundaries at the
60
+ * exact nesting level where the user authored them (Next.js app-router model).
61
+ */
62
+ export interface SegmentBoundary {
63
+ /** 0 = `pagesDir`; increments with each nested subdirectory. */
64
+ depth: number;
65
+ error?: ErrorComponent;
66
+ /**
67
+ * Absolute path to the `error.tsx` module, when present. Carried alongside
68
+ * the component so the client hydrate entry can emit a static `import`
69
+ * statement for each unique convention file — a component reference alone
70
+ * can't survive the server→client boundary.
71
+ */
72
+ errorPath?: string;
73
+ notFound?: NotFoundComponent;
74
+ /** Absolute path to the `not-found.tsx` module, when present. */
75
+ notFoundPath?: string;
76
+ /** Absolute directory path. */
77
+ path: string;
78
+ }
79
+
80
+ export interface ResolvedRoute {
81
+ error?: ErrorComponent;
82
+ isrCache?: { html: string; generatedAt: number; revalidate: number };
83
+ mode: "ssr" | "ssg" | "isr";
84
+ notFound?: NotFoundComponent;
85
+ page: RuntimePage;
86
+ path: string;
87
+ pattern: string;
88
+ routeChain: RuntimeRoute[];
89
+ /**
90
+ * Per-directory boundary chain, ordered shallow → deep. Only directories
91
+ * that DECLARE at least one of `error.tsx` / `not-found.tsx` are included;
92
+ * directories without conventions are skipped. Empty when no conventions
93
+ * exist anywhere in the path.
94
+ */
95
+ segmentBoundaries: SegmentBoundary[];
96
+ ssgHtml?: string;
97
+ }
98
+
99
+ export interface RootLayout {
100
+ error?: ErrorComponent;
101
+ errorPath?: string;
102
+ notFound?: NotFoundComponent;
103
+ notFoundPath?: string;
104
+ path: string;
105
+ route: RuntimeRoute;
106
+ }
107
+
108
+ export function loadProdRoutes(ctx: CompileContext): {
109
+ root: RootLayout;
110
+ routes: ResolvedRoute[];
111
+ } {
112
+ const rootMod = ctx.modules[ctx.rootPath] as Record<string, unknown>;
113
+ const rootExport = rootMod.route ?? rootMod.default;
114
+ if (!(rootExport && isFurinRoute(rootExport) && rootExport.layout)) {
115
+ throw new Error("[furin] root.tsx: createRoute() with layout not found in CompileContext.");
116
+ }
117
+
118
+ function resolveModuleComponent<T>(modPath: string | undefined): T | undefined {
119
+ if (!modPath) {
120
+ return;
121
+ }
122
+ const mod = ctx.modules[modPath] as { default?: T } | undefined;
123
+ return mod?.default;
124
+ }
125
+
126
+ const root: RootLayout = {
127
+ path: ctx.rootPath,
128
+ route: rootExport,
129
+ error: resolveModuleComponent(ctx.rootConventions?.errorPath),
130
+ notFound: resolveModuleComponent(ctx.rootConventions?.notFoundPath),
131
+ };
132
+
133
+ const routes: ResolvedRoute[] = [];
134
+ for (const { pattern, path, mode } of ctx.routes) {
135
+ const pageMod = ctx.modules[path] as { default: RuntimePage };
136
+ const page: RuntimePage = pageMod.default;
137
+ if (!isFurinPage(page)) {
138
+ throw new Error(`[furin] ${path}: invalid page module in CompileContext.`);
139
+ }
140
+ const routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
141
+ validateRouteChain(routeChain, root.route, path);
142
+ const meta = ctx.routeMetadata?.[path];
143
+ const boundaries = (meta?.segmentBoundaries ?? []).map((b) => ({
144
+ ...b,
145
+ error: resolveModuleComponent(b.errorPath),
146
+ notFound: resolveModuleComponent(b.notFoundPath),
147
+ })) as SegmentBoundary[];
148
+
149
+ const error = boundaries.findLast((b) => b.error)?.error;
150
+ const notFound = boundaries.findLast((b) => b.notFound)?.notFound;
151
+
152
+ // Note: In production we store only the nearest segment-level convention
153
+ // (error / notFound) and do NOT fall back to root.error / root.notFound here.
154
+ // The dev-mode resolveNearestConvention() does include the root fallback,
155
+ // and the render layer applies the runtime fallback (route.error ?? root.error)
156
+ // when building the React element tree. This asymmetry is intentional:
157
+ // loadProdRoutes records the static wiring so buildElement can place React
158
+ // boundaries at the correct nesting depth, while the runtime fallback ensures
159
+ // every route always has a safety-net component even if no boundary was
160
+ // declared at any segment level.
161
+
162
+ routes.push({
163
+ pattern,
164
+ page,
165
+ path,
166
+ routeChain,
167
+ mode,
168
+ segmentBoundaries: boundaries,
169
+ error,
170
+ notFound,
171
+ });
172
+ }
173
+
174
+ return { root, routes };
175
+ }
176
+
177
+ export async function scanPages(pagesDir: string): Promise<{
178
+ root: RootLayout;
179
+ routes: ResolvedRoute[];
180
+ }> {
181
+ const root = await scanRootLayout(pagesDir);
182
+ const routes = await scanPageFiles(pagesDir, root);
183
+ return { root, routes };
184
+ }
185
+
186
+ export async function scanRootLayout(pagesDir: string): Promise<RootLayout> {
187
+ const rootPath = `${pagesDir}/root.tsx`;
188
+ const ctx = getCompileContext();
189
+ if (!(existsSync(rootPath) || ctx?.modules[rootPath])) {
190
+ throw new Error("[furin] root.tsx: not found.");
191
+ }
192
+
193
+ const mod = (ctx?.modules[rootPath] ?? (await import(rootPath))) as Record<string, unknown>;
194
+ const rootExport = mod.route ?? mod.default;
195
+ if (!(rootExport && isFurinRoute(rootExport))) {
196
+ throw new Error("[furin] root.tsx: createRoute() export not found.");
197
+ }
198
+
199
+ if (!rootExport.layout) {
200
+ throw new Error("[furin] root.tsx: createRoute() has no layout.");
201
+ }
202
+
203
+ const notFoundEntry = await loadConventionComponent<NotFoundComponent>(pagesDir, "not-found");
204
+ const errorEntry = await loadConventionComponent<ErrorComponent>(pagesDir, "error");
205
+ return {
206
+ path: rootPath,
207
+ route: rootExport,
208
+ notFound: notFoundEntry?.component,
209
+ notFoundPath: notFoundEntry?.path,
210
+ error: errorEntry?.component,
211
+ errorPath: errorEntry?.path,
212
+ };
213
+ }
214
+
215
+ const CONVENTION_FILE_NAMES = ["not-found", "error"] as const;
216
+ const SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"] as const;
217
+
218
+ function isConventionFileName(name: string): boolean {
219
+ return (CONVENTION_FILE_NAMES as readonly string[]).includes(name);
220
+ }
221
+
222
+ function getSourceModuleCandidates(dir: string, name: string): string[] {
223
+ return SOURCE_MODULE_EXTENSIONS.map((ext) => `${dir}/${name}${ext}`);
224
+ }
225
+
226
+ /**
227
+ * Result of a convention-file lookup. The `path` is the absolute module path
228
+ * — callers that only care about the component discard it, but the hydrate
229
+ * emission pipeline needs it to generate static `import` statements.
230
+ */
231
+ interface ConventionLookup<T> {
232
+ component: T;
233
+ path: string;
234
+ }
235
+
236
+ async function loadConventionComponent<T>(
237
+ dir: string,
238
+ name: string
239
+ ): Promise<ConventionLookup<T> | undefined> {
240
+ const ctx = getCompileContext();
241
+ for (const filePath of getSourceModuleCandidates(dir, name)) {
242
+ if (existsSync(filePath) || ctx?.modules[filePath]) {
243
+ const mod = (ctx?.modules[filePath] ?? (await import(filePath))) as {
244
+ default?: T;
245
+ };
246
+ if (mod.default) {
247
+ return { component: mod.default, path: filePath };
248
+ }
249
+ }
250
+ }
251
+ return;
252
+ }
253
+
254
+ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<ResolvedRoute[]> {
255
+ const routes: ResolvedRoute[] = [];
256
+ const notFoundCache = new Map<string, ConventionLookup<NotFoundComponent> | undefined>();
257
+ const errorCache = new Map<string, ConventionLookup<ErrorComponent> | undefined>();
258
+
259
+ for (const absolutePath of await collectPageFilePaths(pagesDir)) {
260
+ if (
261
+ !(SOURCE_MODULE_EXTENSIONS as readonly string[]).some((ext) => absolutePath.endsWith(ext))
262
+ ) {
263
+ continue;
264
+ }
265
+
266
+ const relativePath = absolutePath.replace(`${pagesDir}/`, "");
267
+ const fileName = parse(relativePath).name;
268
+
269
+ // Skip root.tsx, convention files (not-found, error), and files starting with _
270
+ if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
271
+ continue;
272
+ }
273
+
274
+ const notFound = await resolveNearestConvention<NotFoundComponent>(
275
+ absolutePath,
276
+ pagesDir,
277
+ "not-found",
278
+ notFoundCache,
279
+ root.notFound
280
+ );
281
+
282
+ const errorComponent = await resolveNearestConvention<ErrorComponent>(
283
+ absolutePath,
284
+ pagesDir,
285
+ "error",
286
+ errorCache,
287
+ root.error
288
+ );
289
+
290
+ const segmentBoundaries = await collectSegmentBoundaries(
291
+ absolutePath,
292
+ pagesDir,
293
+ notFoundCache,
294
+ errorCache
295
+ );
296
+
297
+ if (IS_DEV) {
298
+ const devRoute = await buildDevRoute(absolutePath, relativePath, root);
299
+ devRoute.notFound = notFound;
300
+ devRoute.error = errorComponent;
301
+ devRoute.segmentBoundaries = segmentBoundaries;
302
+ routes.push(devRoute);
303
+ continue;
304
+ }
305
+
306
+ const ctx = getCompileContext();
307
+ const pageMod = (ctx?.modules[absolutePath] ?? (await import(absolutePath))) as {
308
+ default: RuntimePage;
309
+ };
310
+ const page: RuntimePage = pageMod.default;
311
+ if (!isFurinPage(page)) {
312
+ throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
313
+ }
314
+
315
+ const routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
316
+
317
+ validateRouteChain(routeChain, root.route, relativePath);
318
+
319
+ routes.push({
320
+ pattern: filePathToPattern(relativePath),
321
+ page,
322
+ path: absolutePath,
323
+ routeChain,
324
+ mode: resolveMode(page, routeChain),
325
+ notFound,
326
+ error: errorComponent,
327
+ segmentBoundaries,
328
+ });
329
+ }
330
+
331
+ return routes;
332
+ }
333
+
334
+ /**
335
+ * Walks every directory from `pagesDir` down to the directory containing
336
+ * `pageAbsolutePath` and records the OWN (not inherited) error.tsx /
337
+ * not-found.tsx declared there. Directories without any convention file are
338
+ * omitted so consumers can treat each entry as "a place where the user
339
+ * authored a boundary on purpose".
340
+ *
341
+ * Uses the shared per-directory caches so sibling pages don't re-import the
342
+ * same convention modules.
343
+ */
344
+ async function collectSegmentBoundaries(
345
+ pageAbsolutePath: string,
346
+ pagesDir: string,
347
+ notFoundCache: Map<string, ConventionLookup<NotFoundComponent> | undefined>,
348
+ errorCache: Map<string, ConventionLookup<ErrorComponent> | undefined>
349
+ ): Promise<SegmentBoundary[]> {
350
+ const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
351
+
352
+ // Accumulate directories from shallow → deep starting at pagesDir.
353
+ const dirs: string[] = [pagesDir];
354
+ if (pageDir.length > pagesDir.length) {
355
+ const relativeTail = pageDir.slice(pagesDir.length + 1); // skip leading "/"
356
+ const parts = relativeTail.split("/");
357
+ let acc = pagesDir;
358
+ for (const part of parts) {
359
+ acc = `${acc}/${part}`;
360
+ dirs.push(acc);
361
+ }
362
+ }
363
+
364
+ const boundaries: SegmentBoundary[] = [];
365
+ for (let depth = 0; depth < dirs.length; depth++) {
366
+ const dir = dirs[depth] as string;
367
+
368
+ if (!errorCache.has(dir)) {
369
+ errorCache.set(dir, await loadConventionComponent<ErrorComponent>(dir, "error"));
370
+ }
371
+ if (!notFoundCache.has(dir)) {
372
+ notFoundCache.set(dir, await loadConventionComponent<NotFoundComponent>(dir, "not-found"));
373
+ }
374
+
375
+ const errorEntry = errorCache.get(dir);
376
+ const notFoundEntry = notFoundCache.get(dir);
377
+ if (errorEntry || notFoundEntry) {
378
+ boundaries.push({
379
+ path: dir,
380
+ depth,
381
+ error: errorEntry?.component,
382
+ errorPath: errorEntry?.path,
383
+ notFound: notFoundEntry?.component,
384
+ notFoundPath: notFoundEntry?.path,
385
+ });
386
+ }
387
+ }
388
+
389
+ return boundaries;
390
+ }
391
+
392
+ async function resolveNearestConvention<T>(
393
+ pageAbsolutePath: string,
394
+ pagesDir: string,
395
+ conventionName: string,
396
+ cache: Map<string, ConventionLookup<T> | undefined>,
397
+ rootFallback: T | undefined
398
+ ): Promise<T | undefined> {
399
+ // Walk from the page's directory up to pagesDir looking for the convention file.
400
+ // Cached per directory so repeated scans for sibling pages don't re-import.
401
+ let dir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
402
+ while (dir.length >= pagesDir.length) {
403
+ if (!cache.has(dir)) {
404
+ cache.set(dir, await loadConventionComponent<T>(dir, conventionName));
405
+ }
406
+ const found = cache.get(dir);
407
+ if (found) {
408
+ return found.component;
409
+ }
410
+ if (dir === pagesDir) {
411
+ break;
412
+ }
413
+ dir = dir.slice(0, dir.lastIndexOf("/"));
414
+ }
415
+ return rootFallback;
416
+ }
417
+
418
+ async function buildDevRoute(
419
+ absolutePath: string,
420
+ relativePath: string,
421
+ root: RootLayout
422
+ ): Promise<ResolvedRoute> {
423
+ // Import via the virtual namespace (registerDevPagePlugin must be called first)
424
+ // so page files stay out of --hot's module graph. We still extract the route
425
+ // chain at startup for type generation, guards, and mode resolution — matching
426
+ // prod behavior exactly.
427
+ let page: RuntimePage | undefined;
428
+ let routeChain: RuntimeRoute[] = [];
429
+
430
+ try {
431
+ const pageMod = (await import(`${absolutePath}?furin-server&t=${Date.now()}`)) as {
432
+ default: RuntimePage;
433
+ };
434
+ if (isFurinPage(pageMod.default)) {
435
+ page = pageMod.default;
436
+ routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
437
+ validateRouteChain(routeChain, root.route, relativePath);
438
+ }
439
+ } catch {
440
+ // Page will be loaded on first request in createRoutePlugin as fallback
441
+ }
442
+
443
+ // Dev stub: a minimal RuntimePage that passes isFurinPage() but is never
444
+ // actually rendered — createRoutePlugin always re-imports from disk in dev mode.
445
+ const devStubPage: RuntimePage = {
446
+ __type: "FURIN_PAGE",
447
+ _route: { __type: "FURIN_ROUTE" },
448
+ component: () => null,
449
+ };
450
+
451
+ return {
452
+ pattern: filePathToPattern(relativePath),
453
+ path: absolutePath,
454
+ mode: page ? resolveMode(page, routeChain) : "ssr",
455
+ // Still lazily re-imported on each request in createRoutePlugin for fresh code
456
+ page: page ?? devStubPage,
457
+ routeChain,
458
+ // scanPageFiles() overwrites this with the real chain before the route
459
+ // is pushed — present here to satisfy the ResolvedRoute required shape.
460
+ segmentBoundaries: [],
461
+ };
462
+ }
463
+
464
+ // ── Query-default redirect ──────────────────────────────────────────────────
465
+ // Validator-agnostic: after Elysia applies defaults (TypeBox, Zod, Valibot…),
466
+ // compare the raw URL query keys with the resolved ctx.query keys. If ctx.query
467
+ // contains keys absent from the URL, defaults were applied → 302 redirect to
468
+ // the canonical URL so the address bar always reflects the actual app state.
469
+
470
+ /** @internal Exported for unit testing. */
471
+ export function queryDefaultRedirectHook({ request, query, status, set }: Context) {
472
+ const resolvedQuery = query as Record<string, unknown>;
473
+ const queryKeys = Object.keys(resolvedQuery);
474
+ if (queryKeys.length === 0) {
475
+ return;
476
+ }
477
+
478
+ const rawParams = new URL(request.url).searchParams;
479
+
480
+ let needsRedirect = false;
481
+ for (const key of queryKeys) {
482
+ if (!rawParams.has(key) && resolvedQuery[key] != null) {
483
+ needsRedirect = true;
484
+ break;
485
+ }
486
+ }
487
+ if (!needsRedirect) {
488
+ return;
489
+ }
490
+
491
+ const url = new URL(request.url);
492
+ for (const [k, v] of Object.entries(resolvedQuery)) {
493
+ if (v != null) {
494
+ url.searchParams.set(k, String(v));
495
+ }
496
+ }
497
+
498
+ set.headers.location = url.pathname + url.search;
499
+ return status("Found");
500
+ }
501
+
502
+ type RouteModuleImport = (specifier: string) => Promise<Record<string, unknown>>;
503
+
504
+ function collectIntermediateLayoutDirs(pagePath: string, rootPath: string): string[] {
505
+ const pageDir = pagePath.slice(0, pagePath.lastIndexOf("/"));
506
+ const pagesDir = rootPath.slice(0, rootPath.lastIndexOf("/"));
507
+ const layoutDirs: string[] = [];
508
+ let dir = pageDir;
509
+
510
+ while (dir.length > pagesDir.length) {
511
+ layoutDirs.unshift(dir);
512
+ dir = dir.slice(0, dir.lastIndexOf("/"));
513
+ }
514
+
515
+ return layoutDirs;
516
+ }
517
+
518
+ function isResolvedRouteModuleCandidate(
519
+ layoutPath: string,
520
+ imported: Record<string, unknown>,
521
+ ctx: CompileContext | null
522
+ ): boolean {
523
+ if (existsSync(layoutPath) || ctx?.modules[layoutPath]) {
524
+ return true;
525
+ }
526
+
527
+ return Object.keys(imported).length > 0;
528
+ }
529
+
530
+ async function importFreshRouteModuleCandidate(
531
+ layoutPath: string,
532
+ timestamp: number,
533
+ resolveImport: RouteModuleImport,
534
+ ctx: CompileContext | null
535
+ ): Promise<Record<string, unknown> | undefined> {
536
+ try {
537
+ const imported = await resolveImport(`${layoutPath}?furin-server&t=${timestamp}`);
538
+ if (!isResolvedRouteModuleCandidate(layoutPath, imported, ctx)) {
539
+ return;
540
+ }
541
+
542
+ return imported;
543
+ } catch (err) {
544
+ // Distinguish "this layout file does not exist" (legitimate skip) from
545
+ // "this layout file's transitive imports failed" (real bug to surface).
546
+ // If the layoutPath itself is on disk or registered in the compile ctx,
547
+ // a ModuleNotFoundError must come from a sub-import — re-throw it so
548
+ // the developer sees the actual broken import instead of a silently
549
+ // ignored layout chain.
550
+ const layoutFileIsKnown = existsSync(layoutPath) || Boolean(ctx?.modules[layoutPath]);
551
+ if (!layoutFileIsKnown && isModuleNotFoundError(err)) {
552
+ return;
553
+ }
554
+ throw err;
555
+ }
556
+ }
557
+
558
+ async function importFreshLayoutRouteModule(
559
+ layoutDir: string,
560
+ timestamp: number,
561
+ resolveImport: RouteModuleImport,
562
+ ctx: CompileContext | null
563
+ ): Promise<Record<string, unknown> | undefined> {
564
+ for (const layoutPath of getSourceModuleCandidates(layoutDir, "_route")) {
565
+ const freshMod = await importFreshRouteModuleCandidate(
566
+ layoutPath,
567
+ timestamp,
568
+ resolveImport,
569
+ ctx
570
+ );
571
+ if (freshMod) {
572
+ return freshMod;
573
+ }
574
+ }
575
+
576
+ return;
577
+ }
578
+
579
+ function patchRouteEntryFromFreshModule(
580
+ entry: RuntimeRoute | undefined,
581
+ freshMod: Record<string, unknown>
582
+ ): void {
583
+ const freshRoute = freshMod.route ?? freshMod.default;
584
+ if (!(entry && freshRoute && isFurinRoute(freshRoute))) {
585
+ return;
586
+ }
587
+
588
+ entry.layout = freshRoute.layout;
589
+ entry.loader = freshRoute.loader;
590
+ }
591
+
592
+ /**
593
+ * Re-imports intermediate layout _route.tsx files with cache-busting so that
594
+ * server-side renders reflect the latest code after an HMR edit. Bun's ESM
595
+ * cache keeps the original module alive, so we import via ?furin-server and
596
+ * patch the layout/loader references on the existing route-chain objects.
597
+ *
598
+ * The optional `importFn` parameter exists only for unit testing. In production
599
+ * it defaults to the real `import()`.
600
+ */
601
+ export async function refreshLayoutChain(
602
+ chain: RuntimeRoute[],
603
+ pagePath: string,
604
+ rootPath: string,
605
+ importFn: ((specifier: string) => Promise<Record<string, unknown>>) | undefined
606
+ ): Promise<void> {
607
+ const resolveImport: RouteModuleImport =
608
+ importFn ?? ((s: string) => import(s) as Promise<Record<string, unknown>>);
609
+ const ctx = getCompileContext();
610
+ const timestamp = Date.now();
611
+ const layoutDirs = collectIntermediateLayoutDirs(pagePath, rootPath);
612
+
613
+ // Track chainIdx independently rather than deriving it from layoutPaths
614
+ // index. Directories without a _route module produce import errors that are
615
+ // silently skipped, but those directories have no corresponding chain entry —
616
+ // so we must only advance chainIdx for directories whose _route module actually
617
+ // exists. A positional assumption (i = chainIdx - 1) drifts whenever
618
+ // isModuleNotFoundError is swallowed for a gap directory.
619
+ let chainIdx = 1; // chain[0] is the root
620
+ for (const layoutDir of layoutDirs) {
621
+ if (chainIdx >= chain.length) {
622
+ break;
623
+ }
624
+ const freshMod = await importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx);
625
+ if (!freshMod) {
626
+ // No _route module in this directory — no chain entry to match, so
627
+ // do NOT advance chainIdx. The next deeper layoutDir may correspond
628
+ // to the current chainIdx.
629
+ continue;
630
+ }
631
+
632
+ patchRouteEntryFromFreshModule(chain[chainIdx], freshMod);
633
+ // An _route module exists at this depth — advance chainIdx regardless of
634
+ // whether the export is currently a valid route (the chain entry was
635
+ // populated by the initial import and should be revisited on the next
636
+ // successful HMR cycle).
637
+ chainIdx++;
638
+ }
639
+ }
640
+
641
+ /** @internal Handles a request in dev mode — re-imports the page fresh on every request. */
642
+ async function handleDevRequest(
643
+ route: ResolvedRoute,
644
+ ctx: Context,
645
+ root: RootLayout
646
+ ): Promise<unknown> {
647
+ // Load the page via ?furin-server virtual namespace so it stays out of
648
+ // --hot's file watcher, then hand off to renderSSR which runs loaders,
649
+ // renders React to HTML, and injects __FURIN_DATA__.
650
+ try {
651
+ let currentRoot = root;
652
+ const rootMod = (await import(`${root.path}?furin-server&t=${Date.now()}`)) as Record<
653
+ string,
654
+ unknown
655
+ >;
656
+ const rootExport = rootMod.route ?? rootMod.default;
657
+ if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
658
+ // Preserve the RootLayout-level convention fields (error, notFound,
659
+ // errorPath, notFoundPath) populated by `scanRootLayout` from
660
+ // `pages/error.tsx` and `pages/not-found.tsx`. Replacing the whole
661
+ // RootLayout with just `{ path, route }` would silently drop these
662
+ // fallbacks — `route.error ?? root.error` would resolve to `undefined`
663
+ // in dev after the first request, making custom 404/500 screens
664
+ // disappear after a HMR refresh.
665
+ currentRoot = { ...currentRoot, route: rootExport };
666
+ }
667
+
668
+ const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
669
+ const page = pageMod.default;
670
+ if (page && isFurinPage(page)) {
671
+ const chain = collectRouteChainFromRoute(page._route as RuntimeRoute);
672
+ await refreshLayoutChain(chain, route.path, root.path, undefined);
673
+
674
+ // Patch chain[0] (the root) with the freshly-imported root's loader
675
+ // and layout. `refreshLayoutChain` deliberately starts at chainIdx=1
676
+ // because the root is already loaded separately above; without this
677
+ // patch, chain[0] points to whatever object `_route.parent` captured
678
+ // at _route's first evaluation — a STALE reference if Bun --hot
679
+ // re-evaluated root.tsx without propagating the re-evaluation to
680
+ // _route.tsx (the standard ESM behaviour). Mirroring the pattern
681
+ // used by patchRouteEntryFromFreshModule.
682
+ if (chain[0] && currentRoot.route) {
683
+ chain[0].layout = currentRoot.route.layout;
684
+ chain[0].loader = currentRoot.route.loader;
685
+ }
686
+
687
+ const refreshedRoute: ResolvedRoute = { ...route, page, routeChain: chain };
688
+
689
+ // Live ISR — the loader chain is short-circuited by the dev cache when
690
+ // a fresh entry exists. HTML re-assembles every time so the dev shell
691
+ // chunk URL is always current.
692
+ if (refreshedRoute.mode === "isr") {
693
+ return renderDevISRWithLoaderCache(refreshedRoute, ctx, currentRoot);
694
+ }
695
+
696
+ // Live SSG — same trick as Live ISR, but the cache entry is forever-fresh
697
+ // (revalidate: Infinity) so the loader runs ONCE per cache key until a
698
+ // source file in its dependency chain changes. This matches production
699
+ // SSG semantics ("loader runs once") in dev, instead of re-running the
700
+ // loader on every refresh — which would make expensive loaders (DB
701
+ // queries, MDX parsing, sitemap reads) painful in dev.
702
+ if (refreshedRoute.mode === "ssg") {
703
+ return renderDevSSGWithLoaderCache(refreshedRoute, ctx, currentRoot);
704
+ }
705
+
706
+ return renderSSR(refreshedRoute, ctx, currentRoot, undefined);
707
+ }
708
+ } catch (err) {
709
+ console.error(`[furin] Dev page load error for ${route.path}:`, err);
710
+ }
711
+ // Fallback: page couldn't load — return a clear error response rather than
712
+ // delegating to renderSSR with an undefined page.
713
+ return new Response(
714
+ `<!doctype html><html><body><h1>Page load error</h1><p>Could not load ${route.path}. Check the server console for details.</p></body></html>`,
715
+ { status: 500, headers: { "Content-Type": "text/html; charset=utf-8" } }
716
+ );
717
+ }
718
+
719
+ /**
720
+ * @internal Dev "Live ISR" — caches loader output, not assembled HTML. On a
721
+ * fresh cache hit the loader chain is skipped; the React render still runs so
722
+ * the response embeds the latest dev shell (chunk URL, HMR runtime, …). On
723
+ * miss, runs loaders normally and stores the merged data record.
724
+ */
725
+ async function renderDevISRWithLoaderCache(
726
+ route: ResolvedRoute,
727
+ ctx: Context,
728
+ root: RootLayout
729
+ ): Promise<Response> {
730
+ const cacheKey = `${root.path}:${resolvePath(route.pattern, ctx.params ?? {})}`;
731
+ const cached = getDevISRLoaderCache(cacheKey);
732
+
733
+ if (cached && isDevLoaderCacheValid(cached)) {
734
+ const precomputed: LoaderResult = {
735
+ type: "data",
736
+ data: cached.loaderData,
737
+ headers: cached.headers,
738
+ };
739
+ return renderSSR(route, ctx, root, precomputed);
740
+ }
741
+
742
+ const result = await runLoaders(route, ctx, root.route);
743
+ if (result.type === "data") {
744
+ const revalidate = route.page._route.revalidate ?? 60;
745
+ const entry: DevLoaderCacheEntry = {
746
+ dependencies: computeRouteDependencies(route.path, root.path),
747
+ generatedAt: Date.now(),
748
+ headers: result.headers,
749
+ loaderData: result.data,
750
+ mode: "isr",
751
+ revalidate,
752
+ };
753
+ setDevISRLoaderCache(cacheKey, entry);
754
+ }
755
+ return renderSSR(route, ctx, root, result);
756
+ }
757
+
758
+ /**
759
+ * @internal Dev "Live SSG" — same shape as `renderDevISRWithLoaderCache`, but
760
+ * the cached entry is tagged forever-fresh (`revalidate: Infinity`) so it
761
+ * survives indefinitely until source-aware invalidation drops it. This makes
762
+ * dev SSG behave like production SSG: the loader runs ONCE per cache key,
763
+ * not on every refresh.
764
+ */
765
+ async function renderDevSSGWithLoaderCache(
766
+ route: ResolvedRoute,
767
+ ctx: Context,
768
+ root: RootLayout
769
+ ): Promise<Response> {
770
+ const cacheKey = `${root.path}:${resolvePath(route.pattern, ctx.params ?? {})}`;
771
+ const cached = getDevSSGLoaderCache(cacheKey);
772
+
773
+ if (cached && isDevLoaderCacheValid(cached)) {
774
+ const precomputed: LoaderResult = {
775
+ type: "data",
776
+ data: cached.loaderData,
777
+ headers: cached.headers,
778
+ };
779
+ return renderSSR(route, ctx, root, precomputed);
780
+ }
781
+
782
+ const result = await runLoaders(route, ctx, root.route);
783
+ if (result.type === "data") {
784
+ const entry: DevLoaderCacheEntry = {
785
+ dependencies: computeRouteDependencies(route.path, root.path),
786
+ generatedAt: Date.now(),
787
+ headers: result.headers,
788
+ loaderData: result.data,
789
+ mode: "ssg",
790
+ // SSG entries are forever-fresh — only source-aware invalidation drops them.
791
+ revalidate: Number.POSITIVE_INFINITY,
792
+ };
793
+ setDevSSGLoaderCache(cacheKey, entry);
794
+ }
795
+ return renderSSR(route, ctx, root, result);
796
+ }
797
+
798
+ /**
799
+ * @internal Lists every source file whose contents can affect the render
800
+ * output for a given page: the page itself, every intermediate `_route.*`
801
+ * between the page and the pages root, and `root.tsx`.
802
+ *
803
+ * Only paths that EXIST on disk are returned. `isDevLoaderCacheValid` treats
804
+ * a `statSync` throw as "invalid" (conservative on missing files), so listing
805
+ * non-authored extension candidates here would force a permanent cache MISS
806
+ * for every nested route — silently disabling the dev ISR/SSG cache for any
807
+ * page in a subdirectory. Renames and deletions of TRACKED deps are still
808
+ * detected: the path that previously existed will then `statSync`-throw on
809
+ * the next read and yield the same conservative miss.
810
+ */
811
+ export function computeRouteDependencies(pagePath: string, rootPath: string): string[] {
812
+ const deps = [pagePath, rootPath];
813
+ for (const dir of collectIntermediateLayoutDirs(pagePath, rootPath)) {
814
+ for (const candidate of getSourceModuleCandidates(dir, "_route")) {
815
+ if (existsSync(candidate)) {
816
+ deps.push(candidate);
817
+ }
818
+ }
819
+ }
820
+ return deps;
821
+ }
822
+
823
+ /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
824
+ async function handleSSGRequest(
825
+ route: ResolvedRoute,
826
+ ctx: Context,
827
+ root: RootLayout,
828
+ buildId: string
829
+ ): Promise<unknown> {
830
+ const origin = new URL(ctx.request.url).origin;
831
+ const entry = await prerenderSSG(route, ctx.params, root, origin, undefined);
832
+
833
+ // Loader issued a redirect — forward it directly to the client.
834
+ if (entry instanceof Response) {
835
+ return entry;
836
+ }
837
+
838
+ const resolvedPath = resolvePath(route.pattern, ctx.params ?? {});
839
+
840
+ // ETag: "buildId:cachedAt" — unique per render cycle, changes after revalidatePath
841
+ const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
842
+ if (etag && ctx.request.headers.get("if-none-match") === etag) {
843
+ ctx.set.status = 304;
844
+ return;
845
+ }
846
+
847
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
848
+ // Browser: max-age=0 + must-revalidate → always validates via ETag (304 = free)
849
+ // CDN: s-maxage=31536000 → cache for 1 year, purge via revalidatePath + purger
850
+ ctx.set.headers["cache-control"] = "public, max-age=0, must-revalidate, s-maxage=31536000";
851
+ if (etag) {
852
+ ctx.set.headers.etag = etag;
853
+ }
854
+ ctx.set.headers["cache-tag"] = resolvedPath;
855
+ return entry.html;
856
+ }
857
+
858
+ // Standard structural keys on a TObject — everything else is a user-supplied option
859
+ // (e.g. additionalProperties, $id, description, title) and must be preserved.
860
+ const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
861
+
862
+ /**
863
+ * Merges TObject schemas from all routeChain entries for a given key.
864
+ * Properties are spread left-to-right (leaf wins on key conflict).
865
+ * Object-level options (additionalProperties, $id, description, …) are also
866
+ * merged with the same leaf-wins semantics so they are not silently dropped.
867
+ * Returns undefined when no entry in the chain defines the key.
868
+ *
869
+ * @internal Exported for unit testing.
870
+ */
871
+ export function mergeRouteSchemas(
872
+ routeChain: RuntimeRoute[],
873
+ key: "params" | "query"
874
+ ): AnySchema | undefined {
875
+ const schemas = routeChain.map((r) => r[key]).filter(Boolean) as Record<string, unknown>[];
876
+
877
+ if (schemas.length === 0) {
878
+ return;
879
+ }
880
+ if (schemas.length === 1) {
881
+ return schemas[0] as AnySchema;
882
+ }
883
+
884
+ const mergedProperties = Object.assign(
885
+ {},
886
+ ...schemas.map((s) => (s.properties as Record<string, unknown>) ?? {})
887
+ );
888
+
889
+ const mergedOptions = Object.assign(
890
+ {},
891
+ ...schemas.map((s) =>
892
+ Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))
893
+ )
894
+ );
895
+
896
+ return t.Object(mergedProperties, mergedOptions) as AnySchema;
897
+ }
898
+
899
+ export function createRoutePlugin(route: ResolvedRoute, root: RootLayout, buildId = ""): AnyElysia {
900
+ const { pattern, routeChain } = route;
901
+
902
+ const allParams = mergeRouteSchemas(routeChain, "params");
903
+ const allQuery = mergeRouteSchemas(routeChain, "query");
904
+ const hasQuerySchema = !!allQuery;
905
+
906
+ // Guard and handler MUST live in the same Elysia scope so that validation
907
+ // (including default-filling) applies to the route handler's ctx.query.
908
+ const plugin = new Elysia();
909
+
910
+ if (allParams || allQuery) {
911
+ plugin.guard({
912
+ params: allParams as AnySchema,
913
+ query: allQuery as AnySchema,
914
+ });
915
+ }
916
+
917
+ plugin.get(pattern, (ctx) => {
918
+ // Redirect when Elysia applied query defaults (validator-agnostic)
919
+ if (hasQuerySchema) {
920
+ const redirect = queryDefaultRedirectHook(ctx);
921
+ if (redirect) {
922
+ return redirect;
923
+ }
924
+ }
925
+
926
+ // Dev mode: re-imports page + layouts on every request via the
927
+ // ?furin-server cache-buster, then dispatches into one of:
928
+ // - renderDevISRWithLoaderCache (mode === "isr")
929
+ // - renderDevSSGWithLoaderCache (mode === "ssg")
930
+ // - renderSSR (otherwise)
931
+ //
932
+ // Only the LOADER OUTPUT is cached in dev — HTML is always re-assembled
933
+ // fresh so the response always embeds the latest Bun client chunk URL.
934
+ // This avoids the "infinite reload loop" footgun where a cached ISR/SSG
935
+ // HTML response held an OLD chunk URL after Bun rebundled. The dev
936
+ // cache is invalidated source-aware via `isDevLoaderCacheValid`
937
+ // (mtime-checked dependency walk on every read).
938
+ if (IS_DEV) {
939
+ return handleDevRequest(route, ctx, root);
940
+ }
941
+
942
+ if (route.mode === "ssg") {
943
+ return handleSSGRequest(route, ctx, root, buildId);
944
+ }
945
+
946
+ if (route.mode === "isr") {
947
+ ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
948
+ return handleISR(route, ctx, root, buildId);
949
+ }
950
+
951
+ return renderSSR(route, ctx, root, undefined);
952
+ });
953
+
954
+ return plugin;
955
+ }
956
+
957
+ async function collectPageFilePaths(dir: string): Promise<string[]> {
958
+ const files: string[] = [];
959
+
960
+ // Sort by name so route order is reproducible across platforms / restarts.
961
+ // readdir is hash-based on Linux ext4, alphabetical on macOS APFS — without
962
+ // this sort, two pages that compile to the same URL pattern would resolve
963
+ // non-deterministically depending on host. Sorting also makes the eventual
964
+ // "duplicate route pattern" error reproducible (always the same winner).
965
+ const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) =>
966
+ a.name.localeCompare(b.name)
967
+ );
968
+
969
+ for (const entry of entries) {
970
+ const absolutePath = join(dir, entry.name);
971
+
972
+ if (entry.isDirectory()) {
973
+ files.push(...(await collectPageFilePaths(absolutePath)));
974
+ continue;
975
+ }
976
+
977
+ if (entry.isFile()) {
978
+ files.push(absolutePath);
979
+ }
980
+ }
981
+
982
+ return files;
983
+ }
984
+
985
+ export function resolveMode(page: RuntimePage, routeChain: RuntimeRoute[]): "ssr" | "ssg" | "isr" {
986
+ const routeConfig = page._route;
987
+ const mode = routeConfig.mode ?? (page as { mode?: string }).mode;
988
+ const revalidate = routeConfig.revalidate ?? (page as { revalidate?: number }).revalidate;
989
+
990
+ if (mode) {
991
+ return mode as "ssr" | "ssg" | "isr";
992
+ }
993
+
994
+ const hasLoader = routeChain.some((r) => r.loader) || !!page.loader;
995
+
996
+ if (!hasLoader) {
997
+ return "ssg";
998
+ }
999
+
1000
+ if (typeof revalidate === "number" && revalidate >= 0) {
1001
+ return "isr";
1002
+ }
1003
+
1004
+ return "ssr";
1005
+ }
1006
+
1007
+ export function filePathToPattern(path: string): string {
1008
+ const parts = path.replaceAll("\\", "/").split("/");
1009
+ const segments: string[] = [];
1010
+
1011
+ for (const part of parts) {
1012
+ const name = parse(part).name;
1013
+
1014
+ if (name === "index") {
1015
+ continue;
1016
+ }
1017
+
1018
+ if (name.startsWith("[") && name.endsWith("]")) {
1019
+ const inner = name.slice(1, -1);
1020
+
1021
+ if (inner.startsWith("...")) {
1022
+ segments.push("*");
1023
+ continue;
1024
+ }
1025
+
1026
+ segments.push(`:${inner}`);
1027
+ continue;
1028
+ }
1029
+
1030
+ segments.push(name);
1031
+ }
1032
+
1033
+ return `/${segments.join("/")}`;
1034
+ }