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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/package.json +61 -25
  4. package/src/adapter/bun.ts +90 -41
  5. package/src/adapter/static.ts +100 -40
  6. package/src/build/client.ts +13 -14
  7. package/src/build/compile-entry.ts +20 -14
  8. package/src/build/entry-template.ts +90 -8
  9. package/src/build/hydrate.ts +219 -36
  10. package/src/build/index.ts +10 -9
  11. package/src/build/route-types.ts +65 -9
  12. package/src/build/scan-server.ts +52 -67
  13. package/src/build/server-routes-entry.ts +7 -11
  14. package/src/build/shared.ts +2 -1
  15. package/src/build/ssg-cache.ts +32 -0
  16. package/src/build/types.ts +5 -1
  17. package/src/cli/index.ts +1 -0
  18. package/src/client/boundaries.tsx +259 -0
  19. package/src/client/default-screens.tsx +304 -0
  20. package/src/client/link.tsx +347 -0
  21. package/src/client/router/boundary-tree.tsx +116 -0
  22. package/src/client/router/context.ts +40 -0
  23. package/src/client/router/history.ts +41 -0
  24. package/src/client/router/index.ts +56 -0
  25. package/src/client/router/link-utils.ts +177 -0
  26. package/src/client/router/navigation.ts +61 -0
  27. package/src/client/router/provider.tsx +759 -0
  28. package/src/client/router/search/index.ts +99 -0
  29. package/src/client/router/search-store.ts +86 -0
  30. package/src/client/router/spa-response.ts +143 -0
  31. package/src/client/router/types.ts +271 -0
  32. package/src/client/server-error.ts +47 -0
  33. package/src/client.ts +80 -3
  34. package/src/config.ts +11 -3
  35. package/src/env.d.ts +1 -0
  36. package/src/furin.ts +114 -29
  37. package/src/plugin/index.ts +7 -8
  38. package/src/plugin/transform-client.ts +146 -120
  39. package/src/server/auto-invalidate/index.ts +10 -0
  40. package/src/server/auto-invalidate/plugin.ts +25 -0
  41. package/src/server/auto-invalidate/registry.ts +60 -0
  42. package/src/server/auto-invalidate/runtime.ts +133 -0
  43. package/src/server/auto-invalidate/types.ts +16 -0
  44. package/src/server/cache/dev-loader.ts +211 -0
  45. package/src/server/cache/index.ts +34 -0
  46. package/src/server/cache/invalidation.ts +111 -0
  47. package/src/server/cache/isr-ssg.ts +41 -0
  48. package/src/server/cache/isr.ts +17 -0
  49. package/src/server/cache/registry.ts +35 -0
  50. package/src/server/cache/route-cache.ts +124 -0
  51. package/src/server/cache/ssg.ts +15 -0
  52. package/src/{context-logger.ts → server/context-logger.ts} +5 -0
  53. package/src/server/dev-inspector.ts +60 -0
  54. package/src/{dev-page-plugin.ts → server/dev-page-plugin.ts} +15 -0
  55. package/src/{internal.ts → server/internal.ts} +17 -0
  56. package/src/server/lang-detect.ts +46 -0
  57. package/src/server/render/assemble.ts +133 -0
  58. package/src/server/render/element.tsx +113 -0
  59. package/src/server/render/index.ts +22 -0
  60. package/src/server/render/isr.ts +317 -0
  61. package/src/server/render/loaders.ts +328 -0
  62. package/src/server/render/not-found.ts +98 -0
  63. package/src/{render → server/render}/shell.ts +28 -13
  64. package/src/server/render/ssg.ts +148 -0
  65. package/src/server/render/ssr.ts +583 -0
  66. package/src/server/router/discovery.ts +474 -0
  67. package/src/server/router/hmr.ts +376 -0
  68. package/src/server/router/index.ts +28 -0
  69. package/src/server/router/patterns.ts +219 -0
  70. package/src/server/router/plugin.ts +384 -0
  71. package/src/server/router/schemas.ts +278 -0
  72. package/src/server/router/types.ts +59 -0
  73. package/src/shared/await.tsx +192 -0
  74. package/src/shared/deferred-ndjson.ts +244 -0
  75. package/src/shared/digest.ts +71 -0
  76. package/src/shared/error.ts +49 -0
  77. package/src/shared/not-found.ts +40 -0
  78. package/src/shared/search-params.ts +182 -0
  79. package/src/shared/utils/ast-walk.ts +51 -0
  80. package/src/{utils.ts → shared/utils/index.ts} +32 -1
  81. package/dist/adapter/bun.d.ts +0 -3
  82. package/dist/adapter/static.d.ts +0 -3
  83. package/dist/build/client.d.ts +0 -25
  84. package/dist/build/compile-entry.d.ts +0 -23
  85. package/dist/build/entry-template.d.ts +0 -14
  86. package/dist/build/hydrate.d.ts +0 -24
  87. package/dist/build/index.d.ts +0 -7
  88. package/dist/build/index.js +0 -3727
  89. package/dist/build/route-types.d.ts +0 -21
  90. package/dist/build/scan-server.d.ts +0 -8
  91. package/dist/build/server-routes-entry.d.ts +0 -23
  92. package/dist/build/shared.d.ts +0 -11
  93. package/dist/build/types.d.ts +0 -76
  94. package/dist/cli/config.d.ts +0 -9
  95. package/dist/cli/index.d.ts +0 -2
  96. package/dist/cli/index.js +0 -3762
  97. package/dist/client.d.ts +0 -195
  98. package/dist/client.js +0 -20
  99. package/dist/config.d.ts +0 -47
  100. package/dist/config.js +0 -28
  101. package/dist/context-logger.d.ts +0 -26
  102. package/dist/dev-page-plugin.d.ts +0 -109
  103. package/dist/furin.d.ts +0 -34
  104. package/dist/furin.js +0 -2744
  105. package/dist/internal.d.ts +0 -19
  106. package/dist/link.d.ts +0 -245
  107. package/dist/link.js +0 -1232
  108. package/dist/plugin/index.d.ts +0 -20
  109. package/dist/plugin/index.js +0 -1408
  110. package/dist/plugin/transform-client.d.ts +0 -9
  111. package/dist/render/assemble.d.ts +0 -15
  112. package/dist/render/cache.d.ts +0 -95
  113. package/dist/render/element.d.ts +0 -4
  114. package/dist/render/index.d.ts +0 -27
  115. package/dist/render/loaders.d.ts +0 -12
  116. package/dist/render/shell.d.ts +0 -29
  117. package/dist/render/template.d.ts +0 -6
  118. package/dist/router.d.ts +0 -45
  119. package/dist/router.js +0 -1671
  120. package/dist/runtime-env.d.ts +0 -3
  121. package/dist/utils.d.ts +0 -6
  122. package/src/link.tsx +0 -1120
  123. package/src/render/assemble.ts +0 -66
  124. package/src/render/cache.ts +0 -241
  125. package/src/render/element.tsx +0 -28
  126. package/src/render/index.ts +0 -483
  127. package/src/render/loaders.ts +0 -117
  128. package/src/router.ts +0 -439
  129. /package/src/{render → server/render}/template.ts +0 -0
  130. /package/src/{runtime-env.ts → server/runtime-env.ts} +0 -0
@@ -0,0 +1,474 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readdir } from "node:fs/promises";
3
+ import { join, parse } from "node:path";
4
+ import type { RuntimePage, RuntimeRoute } from "../../client.ts";
5
+ import type { ErrorComponent } from "../../shared/error.ts";
6
+ import type { NotFoundComponent } from "../../shared/not-found.ts";
7
+ import {
8
+ collectRouteChainFromRoute,
9
+ isFurinPage,
10
+ isFurinRoute,
11
+ mapWithConcurrency,
12
+ validateRouteChain,
13
+ } from "../../shared/utils/index.ts";
14
+ import { type CompileContext, getCompileContext } from "../internal.ts";
15
+ import { IS_DEV } from "../runtime-env.ts";
16
+ import { filePathToPattern, resolveMode } from "./patterns.ts";
17
+ import type { ResolvedRoute, RootLayout, SegmentBoundary } from "./types.ts";
18
+
19
+ export function isModuleNotFoundError(err: unknown): boolean {
20
+ if (!err || (typeof err !== "object" && typeof err !== "string")) {
21
+ return false;
22
+ }
23
+ const msg =
24
+ typeof err === "string"
25
+ ? err.toLowerCase()
26
+ : String((err as { message?: unknown }).message ?? "").toLowerCase();
27
+ const code = typeof err === "string" ? undefined : (err as { code?: string }).code;
28
+ return (
29
+ code === "ENOENT" ||
30
+ code === "ERR_MODULE_NOT_FOUND" ||
31
+ code === "MODULE_NOT_FOUND" ||
32
+ msg.includes("cannot find module") ||
33
+ msg.includes("module not found") ||
34
+ msg.includes("no such file or directory")
35
+ );
36
+ }
37
+
38
+ /** @internal Exported for unit testing. */
39
+ export function collectRouteTags(
40
+ routeChain: RuntimeRoute[],
41
+ page: Pick<RuntimePage, "tags"> | undefined
42
+ ): string[] | undefined {
43
+ const tags = new Set<string>();
44
+ for (const route of routeChain) {
45
+ for (const tag of route.tags ?? []) {
46
+ tags.add(tag);
47
+ }
48
+ }
49
+ for (const tag of page?.tags ?? []) {
50
+ tags.add(tag);
51
+ }
52
+ return tags.size > 0 ? [...tags] : undefined;
53
+ }
54
+
55
+ export function loadProdRoutes(ctx: CompileContext): {
56
+ root: RootLayout;
57
+ routes: ResolvedRoute[];
58
+ } {
59
+ const rootMod = ctx.modules[ctx.rootPath] as Record<string, unknown>;
60
+ const rootExport = rootMod.route ?? rootMod.default;
61
+ if (!(rootExport && isFurinRoute(rootExport) && rootExport.layout)) {
62
+ throw new Error("[furin] root.tsx: createRoute() with layout not found in CompileContext.");
63
+ }
64
+
65
+ function resolveModuleComponent<T>(modPath: string | undefined): T | undefined {
66
+ if (!modPath) {
67
+ return;
68
+ }
69
+ const mod = ctx.modules[modPath] as { default?: T } | undefined;
70
+ return mod?.default;
71
+ }
72
+
73
+ const root: RootLayout = {
74
+ path: ctx.rootPath,
75
+ route: rootExport,
76
+ error: resolveModuleComponent(ctx.rootConventions?.errorPath),
77
+ notFound: resolveModuleComponent(ctx.rootConventions?.notFoundPath),
78
+ };
79
+
80
+ const routes: ResolvedRoute[] = [];
81
+ for (const { pattern, path, mode } of ctx.routes) {
82
+ const pageMod = ctx.modules[path] as { default: RuntimePage };
83
+ const page: RuntimePage = pageMod.default;
84
+ if (!isFurinPage(page)) {
85
+ throw new Error(`[furin] ${path}: invalid page module in CompileContext.`);
86
+ }
87
+ const routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
88
+ validateRouteChain(routeChain, root.route, path);
89
+ const meta = ctx.routeMetadata?.[path];
90
+ const boundaries = (meta?.segmentBoundaries ?? []).map((b) => ({
91
+ ...b,
92
+ error: resolveModuleComponent(b.errorPath),
93
+ notFound: resolveModuleComponent(b.notFoundPath),
94
+ })) as SegmentBoundary[];
95
+
96
+ const error = boundaries.findLast((b) => b.error)?.error;
97
+ const notFound = boundaries.findLast((b) => b.notFound)?.notFound;
98
+
99
+ // Note: In production we store only the nearest segment-level convention
100
+ // (error / notFound) and do NOT fall back to root.error / root.notFound here.
101
+ // The dev-mode resolveNearestConvention() does include the root fallback,
102
+ // and the render layer applies the runtime fallback (route.error ?? root.error)
103
+ // when building the React element tree. This asymmetry is intentional:
104
+ // loadProdRoutes records the static wiring so buildElement can place React
105
+ // boundaries at the correct nesting depth, while the runtime fallback ensures
106
+ // every route always has a safety-net component even if no boundary was
107
+ // declared at any segment level.
108
+
109
+ routes.push({
110
+ pattern,
111
+ page,
112
+ path,
113
+ routeChain,
114
+ mode,
115
+ segmentBoundaries: boundaries,
116
+ error,
117
+ notFound,
118
+ tags: collectRouteTags(routeChain, page),
119
+ });
120
+ }
121
+
122
+ return { root, routes };
123
+ }
124
+
125
+ /**
126
+ * Normalises OS-native path separators to POSIX "/" so the slash-based path
127
+ * arithmetic in the scan (relative slicing, `lastIndexOf("/")`,
128
+ * `${pagesDir}/...`) works on Windows, where `node:path` join/resolve emit
129
+ * backslashes. `existsSync` and dynamic `import()` both accept forward slashes
130
+ * on Windows, so the normalised form is safe for filesystem and module access.
131
+ */
132
+ function toPosixPath(path: string): string {
133
+ return path.replaceAll("\\", "/");
134
+ }
135
+
136
+ function routeRelativePath(pagesDir: string, absolutePath: string): string {
137
+ const dir = toPosixPath(pagesDir).replace(/\/+$/g, "");
138
+ const path = toPosixPath(absolutePath);
139
+ return path.startsWith(`${dir}/`) ? path.slice(dir.length + 1) : path;
140
+ }
141
+
142
+ export async function scanPages(pagesDir: string): Promise<{
143
+ root: RootLayout;
144
+ routes: ResolvedRoute[];
145
+ }> {
146
+ // Normalise once at the entry point; scanRootLayout and scanPageFiles (plus
147
+ // every absolute path collectPageFilePaths yields) then operate purely on
148
+ // POSIX-separated paths.
149
+ const dir = toPosixPath(pagesDir);
150
+ const root = await scanRootLayout(dir);
151
+ const routes = await scanPageFiles(dir, root);
152
+ return { root, routes };
153
+ }
154
+
155
+ export async function scanRootLayout(pagesDir: string): Promise<RootLayout> {
156
+ const rootPath = `${pagesDir}/root.tsx`;
157
+ const ctx = getCompileContext();
158
+ if (!(existsSync(rootPath) || ctx?.modules[rootPath])) {
159
+ throw new Error("[furin] root.tsx: not found.");
160
+ }
161
+
162
+ const mod = (ctx?.modules[rootPath] ?? (await import(rootPath))) as Record<string, unknown>;
163
+ const rootExport = mod.route ?? mod.default;
164
+ if (!(rootExport && isFurinRoute(rootExport))) {
165
+ throw new Error("[furin] root.tsx: createRoute() export not found.");
166
+ }
167
+
168
+ if (!rootExport.layout) {
169
+ throw new Error("[furin] root.tsx: createRoute() has no layout.");
170
+ }
171
+
172
+ const [notFoundEntry, errorEntry] = await Promise.all([
173
+ loadConventionComponent<NotFoundComponent>(pagesDir, "not-found"),
174
+ loadConventionComponent<ErrorComponent>(pagesDir, "error"),
175
+ ]);
176
+ return {
177
+ path: rootPath,
178
+ route: rootExport,
179
+ notFound: notFoundEntry?.component,
180
+ notFoundPath: notFoundEntry?.path,
181
+ error: errorEntry?.component,
182
+ errorPath: errorEntry?.path,
183
+ };
184
+ }
185
+
186
+ const CONVENTION_FILE_NAMES = ["not-found", "error"] as const;
187
+ const SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"] as const;
188
+
189
+ function isConventionFileName(name: string): boolean {
190
+ return (CONVENTION_FILE_NAMES as readonly string[]).includes(name);
191
+ }
192
+
193
+ export function getSourceModuleCandidates(dir: string, name: string): string[] {
194
+ return SOURCE_MODULE_EXTENSIONS.map((ext) => `${dir}/${name}${ext}`);
195
+ }
196
+
197
+ /**
198
+ * Result of a convention-file lookup. The `path` is the absolute module path
199
+ * — callers that only care about the component discard it, but the hydrate
200
+ * emission pipeline needs it to generate static `import` statements.
201
+ */
202
+ interface ConventionLookup<T> {
203
+ component: T;
204
+ path: string;
205
+ }
206
+
207
+ async function loadConventionComponent<T>(
208
+ dir: string,
209
+ name: string
210
+ ): Promise<ConventionLookup<T> | undefined> {
211
+ const ctx = getCompileContext();
212
+ for (const filePath of getSourceModuleCandidates(dir, name)) {
213
+ if (existsSync(filePath) || ctx?.modules[filePath]) {
214
+ const mod = (ctx?.modules[filePath] ?? (await import(filePath))) as {
215
+ default?: T;
216
+ };
217
+ if (mod.default) {
218
+ return { component: mod.default, path: filePath };
219
+ }
220
+ }
221
+ }
222
+ return;
223
+ }
224
+
225
+ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<ResolvedRoute[]> {
226
+ const routes: ResolvedRoute[] = [];
227
+ const notFoundCache = new Map<string, ConventionLookup<NotFoundComponent> | undefined>();
228
+ const errorCache = new Map<string, ConventionLookup<ErrorComponent> | undefined>();
229
+
230
+ for (const absolutePath of await collectPageFilePaths(pagesDir)) {
231
+ if (
232
+ !(SOURCE_MODULE_EXTENSIONS as readonly string[]).some((ext) => absolutePath.endsWith(ext))
233
+ ) {
234
+ continue;
235
+ }
236
+
237
+ const relativePath = routeRelativePath(pagesDir, absolutePath);
238
+ const fileName = parse(relativePath).name;
239
+
240
+ // Skip root.tsx, convention files (not-found, error), and files starting with _
241
+ if (fileName.startsWith("_") || fileName === "root" || isConventionFileName(fileName)) {
242
+ continue;
243
+ }
244
+
245
+ const [notFound, errorComponent, segmentBoundaries] = await Promise.all([
246
+ resolveNearestConvention<NotFoundComponent>(
247
+ absolutePath,
248
+ pagesDir,
249
+ "not-found",
250
+ notFoundCache,
251
+ root.notFound
252
+ ),
253
+ resolveNearestConvention<ErrorComponent>(
254
+ absolutePath,
255
+ pagesDir,
256
+ "error",
257
+ errorCache,
258
+ root.error
259
+ ),
260
+ collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache),
261
+ ]);
262
+
263
+ if (IS_DEV) {
264
+ const devRoute = await buildDevRoute(absolutePath, relativePath, root);
265
+ devRoute.notFound = notFound;
266
+ devRoute.error = errorComponent;
267
+ devRoute.segmentBoundaries = segmentBoundaries;
268
+ routes.push(devRoute);
269
+ continue;
270
+ }
271
+
272
+ const ctx = getCompileContext();
273
+ const pageMod = (ctx?.modules[absolutePath] ?? (await import(absolutePath))) as {
274
+ default: RuntimePage;
275
+ };
276
+ const page: RuntimePage = pageMod.default;
277
+ if (!isFurinPage(page)) {
278
+ throw new Error(`[furin] ${relativePath}: no valid createRoute().page() export found`);
279
+ }
280
+
281
+ const routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
282
+
283
+ validateRouteChain(routeChain, root.route, relativePath);
284
+
285
+ routes.push({
286
+ pattern: filePathToPattern(relativePath),
287
+ page,
288
+ path: absolutePath,
289
+ routeChain,
290
+ mode: resolveMode(page, routeChain),
291
+ notFound,
292
+ error: errorComponent,
293
+ segmentBoundaries,
294
+ tags: collectRouteTags(routeChain, page),
295
+ });
296
+ }
297
+
298
+ return routes;
299
+ }
300
+
301
+ /**
302
+ * Walks every directory from `pagesDir` down to the directory containing
303
+ * `pageAbsolutePath` and records the OWN (not inherited) error.tsx /
304
+ * not-found.tsx declared there. Directories without any convention file are
305
+ * omitted so consumers can treat each entry as "a place where the user
306
+ * authored a boundary on purpose".
307
+ *
308
+ * Uses the shared per-directory caches so sibling pages don't re-import the
309
+ * same convention modules.
310
+ */
311
+ async function collectSegmentBoundaries(
312
+ pageAbsolutePath: string,
313
+ pagesDir: string,
314
+ notFoundCache: Map<string, ConventionLookup<NotFoundComponent> | undefined>,
315
+ errorCache: Map<string, ConventionLookup<ErrorComponent> | undefined>
316
+ ): Promise<SegmentBoundary[]> {
317
+ const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
318
+
319
+ // Accumulate directories from shallow → deep starting at pagesDir.
320
+ const dirs: string[] = [pagesDir];
321
+ if (pageDir.length > pagesDir.length) {
322
+ const relativeTail = pageDir.slice(pagesDir.length + 1); // skip leading "/"
323
+ const parts = relativeTail.split("/");
324
+ let acc = pagesDir;
325
+ for (const part of parts) {
326
+ acc = `${acc}/${part}`;
327
+ dirs.push(acc);
328
+ }
329
+ }
330
+
331
+ const boundaries: SegmentBoundary[] = [];
332
+ for (let depth = 0; depth < dirs.length; depth++) {
333
+ const dir = dirs[depth] as string;
334
+
335
+ const [errorEntry, notFoundEntry] = await Promise.all([
336
+ errorCache.has(dir)
337
+ ? Promise.resolve(errorCache.get(dir))
338
+ : loadConventionComponent<ErrorComponent>(dir, "error").then((r) => {
339
+ errorCache.set(dir, r);
340
+ return r;
341
+ }),
342
+ notFoundCache.has(dir)
343
+ ? Promise.resolve(notFoundCache.get(dir))
344
+ : loadConventionComponent<NotFoundComponent>(dir, "not-found").then((r) => {
345
+ notFoundCache.set(dir, r);
346
+ return r;
347
+ }),
348
+ ]);
349
+ if (errorEntry || notFoundEntry) {
350
+ boundaries.push({
351
+ path: dir,
352
+ depth,
353
+ error: errorEntry?.component,
354
+ errorPath: errorEntry?.path,
355
+ notFound: notFoundEntry?.component,
356
+ notFoundPath: notFoundEntry?.path,
357
+ });
358
+ }
359
+ }
360
+
361
+ return boundaries;
362
+ }
363
+
364
+ async function resolveNearestConvention<T>(
365
+ pageAbsolutePath: string,
366
+ pagesDir: string,
367
+ conventionName: string,
368
+ cache: Map<string, ConventionLookup<T> | undefined>,
369
+ rootFallback: T | undefined
370
+ ): Promise<T | undefined> {
371
+ // Walk from the page's directory up to pagesDir looking for the convention file.
372
+ // Cached per directory so repeated scans for sibling pages don't re-import.
373
+ let dir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
374
+ while (dir.length >= pagesDir.length) {
375
+ if (!cache.has(dir)) {
376
+ cache.set(dir, await loadConventionComponent<T>(dir, conventionName));
377
+ }
378
+ const found = cache.get(dir);
379
+ if (found) {
380
+ return found.component;
381
+ }
382
+ if (dir === pagesDir) {
383
+ break;
384
+ }
385
+ dir = dir.slice(0, dir.lastIndexOf("/"));
386
+ }
387
+ return rootFallback;
388
+ }
389
+
390
+ async function buildDevRoute(
391
+ absolutePath: string,
392
+ relativePath: string,
393
+ root: RootLayout
394
+ ): Promise<ResolvedRoute> {
395
+ // Import via the virtual namespace (registerDevPagePlugin must be called first)
396
+ // so page files stay out of --hot's module graph. We still extract the route
397
+ // chain at startup for type generation, guards, and mode resolution — matching
398
+ // prod behavior exactly.
399
+ let page: RuntimePage | undefined;
400
+ let routeChain: RuntimeRoute[] = [];
401
+
402
+ try {
403
+ const pageMod = (await import(`${absolutePath}?furin-server&t=${Date.now()}`)) as {
404
+ default: RuntimePage;
405
+ };
406
+ if (isFurinPage(pageMod.default)) {
407
+ page = pageMod.default;
408
+ routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
409
+ validateRouteChain(routeChain, root.route, relativePath);
410
+ }
411
+ } catch {
412
+ // Page will be loaded on first request in createRoutePlugin as fallback
413
+ }
414
+
415
+ // Dev stub: a minimal RuntimePage that passes isFurinPage() but is never
416
+ // actually rendered — createRoutePlugin always re-imports from disk in dev mode.
417
+ const devStubPage: RuntimePage = {
418
+ __type: "FURIN_PAGE",
419
+ _route: { __type: "FURIN_ROUTE" },
420
+ component: () => null,
421
+ };
422
+
423
+ return {
424
+ pattern: filePathToPattern(relativePath),
425
+ path: absolutePath,
426
+ mode: page ? resolveMode(page, routeChain) : "ssr",
427
+ // Still lazily re-imported on each request in createRoutePlugin for fresh code
428
+ page: page ?? devStubPage,
429
+ routeChain,
430
+ tags: collectRouteTags(routeChain, page),
431
+ // scanPageFiles() overwrites this with the real chain before the route
432
+ // is pushed — present here to satisfy the ResolvedRoute required shape.
433
+ segmentBoundaries: [],
434
+ };
435
+ }
436
+
437
+ /**
438
+ * Per-level cap on parallel directory traversals. Bounds peak in-flight
439
+ * `readdir` calls to roughly `DIR_SCAN_CONCURRENCY * tree-depth`, which keeps
440
+ * a wide flat pagesDir from opening thousands of FDs at once.
441
+ */
442
+ const DIR_SCAN_CONCURRENCY = 8;
443
+
444
+ async function collectPageFilePaths(dir: string): Promise<string[]> {
445
+ const files: string[] = [];
446
+
447
+ // Sort by name so route order is reproducible across platforms / restarts.
448
+ // readdir is hash-based on Linux ext4, alphabetical on macOS APFS — without
449
+ // this sort, two pages that compile to the same URL pattern would resolve
450
+ // non-deterministically depending on host. Sorting also makes the eventual
451
+ // "duplicate route pattern" error reproducible (always the same winner).
452
+ const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) =>
453
+ a.name.localeCompare(b.name)
454
+ );
455
+
456
+ // Walk subdirectories with bounded parallelism, then merge results in the
457
+ // original alphabetical entry order so the depth-first interleaving is
458
+ // preserved (file, then its sub-tree, then next file…).
459
+ const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
460
+ const absolutePath = toPosixPath(join(dir, entry.name));
461
+ if (entry.isDirectory()) {
462
+ return await collectPageFilePaths(absolutePath);
463
+ }
464
+ if (entry.isFile()) {
465
+ return [absolutePath];
466
+ }
467
+ return [];
468
+ });
469
+ for (const chunk of resolved) {
470
+ files.push(...chunk);
471
+ }
472
+
473
+ return files;
474
+ }