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

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 (69) hide show
  1. package/README.md +14 -232
  2. package/dist/auto-invalidate/index.d.ts +4 -0
  3. package/dist/auto-invalidate/plugin.d.ts +38 -0
  4. package/dist/auto-invalidate/registry.d.ts +9 -0
  5. package/dist/auto-invalidate/runtime.d.ts +9 -0
  6. package/dist/auto-invalidate/types.d.ts +12 -0
  7. package/dist/await.d.ts +67 -0
  8. package/dist/build/index.js +2095 -185
  9. package/dist/cli/index.js +2070 -182
  10. package/dist/client.d.ts +51 -4
  11. package/dist/client.js +65 -1
  12. package/dist/deferred-ndjson.d.ts +32 -0
  13. package/dist/error.d.ts +14 -0
  14. package/dist/furin.d.ts +8 -0
  15. package/dist/furin.js +2927 -319
  16. package/dist/lang-detect.d.ts +5 -0
  17. package/dist/link.d.ts +1 -0
  18. package/dist/link.js +1453 -95
  19. package/dist/plugin/index.js +96 -25
  20. package/dist/plugin/transform-client.d.ts +2 -1
  21. package/dist/render/assemble.d.ts +32 -0
  22. package/dist/render/cache.d.ts +7 -0
  23. package/dist/render/element.d.ts +17 -1
  24. package/dist/render/index.d.ts +10 -1
  25. package/dist/render/index.ts +250 -44
  26. package/dist/render/loaders.d.ts +46 -3
  27. package/dist/render/shell.d.ts +16 -6
  28. package/dist/render/shell.ts +27 -12
  29. package/dist/router-provider.d.ts +86 -18
  30. package/dist/router.d.ts +66 -0
  31. package/dist/router.js +2909 -374
  32. package/dist/router.ts +586 -54
  33. package/dist/server-error.d.ts +12 -0
  34. package/dist/utils.d.ts +7 -0
  35. package/package.json +8 -7
  36. package/src/adapter/bun.ts +3 -3
  37. package/src/adapter/static.ts +73 -31
  38. package/src/auto-invalidate/index.ts +10 -0
  39. package/src/auto-invalidate/plugin.ts +25 -0
  40. package/src/auto-invalidate/registry.ts +60 -0
  41. package/src/auto-invalidate/runtime.ts +133 -0
  42. package/src/auto-invalidate/types.ts +16 -0
  43. package/src/await.tsx +175 -0
  44. package/src/build/client.ts +4 -8
  45. package/src/build/hydrate.ts +67 -1
  46. package/src/build/route-types.ts +29 -3
  47. package/src/build/scan-server.ts +6 -23
  48. package/src/client.ts +80 -3
  49. package/src/deferred-ndjson.ts +212 -0
  50. package/src/dev-page-plugin.ts +2 -0
  51. package/src/error.ts +18 -1
  52. package/src/furin.ts +19 -2
  53. package/src/lang-detect.ts +46 -0
  54. package/src/link.tsx +16 -3
  55. package/src/plugin/index.ts +7 -8
  56. package/src/plugin/transform-client.ts +108 -39
  57. package/src/render/assemble.ts +67 -0
  58. package/src/render/boundaries.tsx +23 -5
  59. package/src/render/cache.ts +14 -0
  60. package/src/render/default-screens.tsx +4 -11
  61. package/src/render/dev-cache.ts +5 -0
  62. package/src/render/element.tsx +26 -3
  63. package/src/render/index.ts +250 -44
  64. package/src/render/loaders.ts +219 -18
  65. package/src/render/shell.ts +27 -12
  66. package/src/router-provider.tsx +414 -122
  67. package/src/router.ts +586 -54
  68. package/src/server-error.ts +47 -0
  69. package/src/utils.ts +31 -0
package/dist/router.ts CHANGED
@@ -3,7 +3,13 @@ import { readdir } from "node:fs/promises";
3
3
  import { join, parse } from "node:path";
4
4
  import { type AnyElysia, type Context, Elysia, t } from "elysia";
5
5
  import type { AnySchema } from "elysia/types";
6
+ import { toCrossJSON, toCrossJSONAsync } from "seroval";
7
+ import { autoInvalidateRegistry } from "./auto-invalidate/registry.ts";
6
8
  import type { RuntimePage, RuntimeRoute } from "./client.ts";
9
+ // Use the project-local `useLogger` (not `evlog/elysia` directly) so the
10
+ // `/_furin/data` enrichment also works in synthetic render scopes (ISR/SSG)
11
+ // and falls back to a no-op outside any request — see context-logger.ts.
12
+ import { useLogger } from "./context-logger.ts";
7
13
  import type { ErrorComponent } from "./error.ts";
8
14
  import { type CompileContext, getCompileContext } from "./internal.ts";
9
15
  import type { NotFoundComponent } from "./not-found.ts";
@@ -16,18 +22,22 @@ import {
16
22
  setDevISRLoaderCache,
17
23
  setDevSSGLoaderCache,
18
24
  } from "./render/dev-cache.ts";
25
+ import { computeErrorDigest } from "./render/digest.ts";
19
26
  import {
20
27
  handleISR,
21
28
  type LoaderResult,
22
29
  prerenderSSG,
23
30
  renderSSR,
24
31
  runLoaders,
32
+ serializeDeferredRejection,
25
33
  } from "./render/index.ts";
34
+ import { extractTitle } from "./render/shell.ts";
26
35
  import { IS_DEV } from "./runtime-env.ts";
27
36
  import {
28
37
  collectRouteChainFromRoute,
29
38
  isFurinPage,
30
39
  isFurinRoute,
40
+ mapWithConcurrency,
31
41
  validateRouteChain,
32
42
  } from "./utils.ts";
33
43
 
@@ -94,6 +104,7 @@ export interface ResolvedRoute {
94
104
  */
95
105
  segmentBoundaries: SegmentBoundary[];
96
106
  ssgHtml?: string;
107
+ tags?: string[];
97
108
  }
98
109
 
99
110
  export interface RootLayout {
@@ -105,6 +116,23 @@ export interface RootLayout {
105
116
  route: RuntimeRoute;
106
117
  }
107
118
 
119
+ /** @internal Exported for unit testing. */
120
+ export function collectRouteTags(
121
+ routeChain: RuntimeRoute[],
122
+ page: Pick<RuntimePage, "tags"> | undefined
123
+ ): string[] | undefined {
124
+ const tags = new Set<string>();
125
+ for (const route of routeChain) {
126
+ for (const tag of route.tags ?? []) {
127
+ tags.add(tag);
128
+ }
129
+ }
130
+ for (const tag of page?.tags ?? []) {
131
+ tags.add(tag);
132
+ }
133
+ return tags.size > 0 ? [...tags] : undefined;
134
+ }
135
+
108
136
  export function loadProdRoutes(ctx: CompileContext): {
109
137
  root: RootLayout;
110
138
  routes: ResolvedRoute[];
@@ -168,6 +196,7 @@ export function loadProdRoutes(ctx: CompileContext): {
168
196
  segmentBoundaries: boundaries,
169
197
  error,
170
198
  notFound,
199
+ tags: collectRouteTags(routeChain, page),
171
200
  });
172
201
  }
173
202
 
@@ -200,8 +229,10 @@ export async function scanRootLayout(pagesDir: string): Promise<RootLayout> {
200
229
  throw new Error("[furin] root.tsx: createRoute() has no layout.");
201
230
  }
202
231
 
203
- const notFoundEntry = await loadConventionComponent<NotFoundComponent>(pagesDir, "not-found");
204
- const errorEntry = await loadConventionComponent<ErrorComponent>(pagesDir, "error");
232
+ const [notFoundEntry, errorEntry] = await Promise.all([
233
+ loadConventionComponent<NotFoundComponent>(pagesDir, "not-found"),
234
+ loadConventionComponent<ErrorComponent>(pagesDir, "error"),
235
+ ]);
205
236
  return {
206
237
  path: rootPath,
207
238
  route: rootExport,
@@ -271,28 +302,23 @@ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<Resolv
271
302
  continue;
272
303
  }
273
304
 
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
- );
305
+ const [notFound, errorComponent, segmentBoundaries] = await Promise.all([
306
+ resolveNearestConvention<NotFoundComponent>(
307
+ absolutePath,
308
+ pagesDir,
309
+ "not-found",
310
+ notFoundCache,
311
+ root.notFound
312
+ ),
313
+ resolveNearestConvention<ErrorComponent>(
314
+ absolutePath,
315
+ pagesDir,
316
+ "error",
317
+ errorCache,
318
+ root.error
319
+ ),
320
+ collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache),
321
+ ]);
296
322
 
297
323
  if (IS_DEV) {
298
324
  const devRoute = await buildDevRoute(absolutePath, relativePath, root);
@@ -325,6 +351,7 @@ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<Resolv
325
351
  notFound,
326
352
  error: errorComponent,
327
353
  segmentBoundaries,
354
+ tags: collectRouteTags(routeChain, page),
328
355
  });
329
356
  }
330
357
 
@@ -365,15 +392,20 @@ async function collectSegmentBoundaries(
365
392
  for (let depth = 0; depth < dirs.length; depth++) {
366
393
  const dir = dirs[depth] as string;
367
394
 
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);
395
+ const [errorEntry, notFoundEntry] = await Promise.all([
396
+ errorCache.has(dir)
397
+ ? Promise.resolve(errorCache.get(dir))
398
+ : loadConventionComponent<ErrorComponent>(dir, "error").then((r) => {
399
+ errorCache.set(dir, r);
400
+ return r;
401
+ }),
402
+ notFoundCache.has(dir)
403
+ ? Promise.resolve(notFoundCache.get(dir))
404
+ : loadConventionComponent<NotFoundComponent>(dir, "not-found").then((r) => {
405
+ notFoundCache.set(dir, r);
406
+ return r;
407
+ }),
408
+ ]);
377
409
  if (errorEntry || notFoundEntry) {
378
410
  boundaries.push({
379
411
  path: dir,
@@ -455,6 +487,7 @@ async function buildDevRoute(
455
487
  // Still lazily re-imported on each request in createRoutePlugin for fresh code
456
488
  page: page ?? devStubPage,
457
489
  routeChain,
490
+ tags: collectRouteTags(routeChain, page),
458
491
  // scanPageFiles() overwrites this with the real chain before the route
459
492
  // is pushed — present here to satisfy the ResolvedRoute required shape.
460
493
  segmentBoundaries: [],
@@ -467,16 +500,28 @@ async function buildDevRoute(
467
500
  // contains keys absent from the URL, defaults were applied → 302 redirect to
468
501
  // the canonical URL so the address bar always reflects the actual app state.
469
502
 
470
- /** @internal Exported for unit testing. */
471
- export function queryDefaultRedirectHook({ request, query, status, set }: Context) {
472
- const resolvedQuery = query as Record<string, unknown>;
503
+ /**
504
+ * Detects whether a validator filled in default query values that the original
505
+ * URL did not carry, and returns the canonical `pathname + search` to redirect
506
+ * to — or `undefined` when the URL already reflects the resolved query.
507
+ *
508
+ * Pure helper extracted from `queryDefaultRedirectHook` so the `/_furin/data`
509
+ * NDJSON endpoint can detect the same condition without going through
510
+ * Elysia's `status()` shim (which only emits HTTP 302s, unparseable by the
511
+ * SPA client).
512
+ *
513
+ * @internal Exported for unit testing.
514
+ */
515
+ export function detectQueryDefaultRedirect(
516
+ request: Request,
517
+ resolvedQuery: Record<string, unknown>
518
+ ): string | undefined {
473
519
  const queryKeys = Object.keys(resolvedQuery);
474
520
  if (queryKeys.length === 0) {
475
521
  return;
476
522
  }
477
523
 
478
524
  const rawParams = new URL(request.url).searchParams;
479
-
480
525
  let needsRedirect = false;
481
526
  for (const key of queryKeys) {
482
527
  if (!rawParams.has(key) && resolvedQuery[key] != null) {
@@ -494,8 +539,45 @@ export function queryDefaultRedirectHook({ request, query, status, set }: Contex
494
539
  url.searchParams.set(k, String(v));
495
540
  }
496
541
  }
542
+ return url.pathname + url.search;
543
+ }
544
+
545
+ /**
546
+ * Parses the `?path=` argument of `/_furin/data`, rejecting absolute /
547
+ * protocol-relative inputs that would let a caller smuggle a foreign origin
548
+ * into the synthetic loader request.
549
+ *
550
+ * Returns `{ url, pathname }` on success, or `undefined` when the input is
551
+ * unsafe (the caller should reply 400). `new URL(rawPath, base)` ignores the
552
+ * base when `rawPath` is itself absolute, so without these prefix and origin
553
+ * checks a value like `https://evil.com/foo` would propagate to
554
+ * `syntheticRequest.url`.
555
+ *
556
+ * @internal Exported for unit testing.
557
+ */
558
+ export function parseDataEndpointPath(rawPath: string): { url: URL; pathname: string } | undefined {
559
+ if (rawPath.includes("://") || rawPath.startsWith("//")) {
560
+ return;
561
+ }
562
+ let url: URL;
563
+ try {
564
+ url = new URL(rawPath, "http://localhost");
565
+ } catch {
566
+ return;
567
+ }
568
+ if (url.origin !== "http://localhost") {
569
+ return;
570
+ }
571
+ return { url, pathname: url.pathname };
572
+ }
497
573
 
498
- set.headers.location = url.pathname + url.search;
574
+ /** @internal Exported for unit testing. */
575
+ export function queryDefaultRedirectHook({ request, query, status, set }: Context) {
576
+ const location = detectQueryDefaultRedirect(request, query as Record<string, unknown>);
577
+ if (!location) {
578
+ return;
579
+ }
580
+ set.headers.location = location;
499
581
  return status("Found");
500
582
  }
501
583
 
@@ -616,12 +698,19 @@ export async function refreshLayoutChain(
616
698
  // so we must only advance chainIdx for directories whose _route module actually
617
699
  // exists. A positional assumption (i = chainIdx - 1) drifts whenever
618
700
  // isModuleNotFoundError is swallowed for a gap directory.
701
+ //
702
+ // Imports are parallelised for speed; patching stays sequential so the
703
+ // chainIdx-to-layoutDir positional mapping remains deterministic.
704
+ const freshMods = await Promise.all(
705
+ layoutDirs.map((layoutDir) =>
706
+ importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx)
707
+ )
708
+ );
619
709
  let chainIdx = 1; // chain[0] is the root
620
- for (const layoutDir of layoutDirs) {
710
+ for (const freshMod of freshMods) {
621
711
  if (chainIdx >= chain.length) {
622
712
  break;
623
713
  }
624
- const freshMod = await importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx);
625
714
  if (!freshMod) {
626
715
  // No _route module in this directory — no chain entry to match, so
627
716
  // do NOT advance chainIdx. The next deeper layoutDir may correspond
@@ -638,6 +727,35 @@ export async function refreshLayoutChain(
638
727
  }
639
728
  }
640
729
 
730
+ /**
731
+ * Rebuilds a `ResolvedRoute` from freshly-imported `page` and `chain` so that
732
+ * `mode` reflects the CURRENT contents of the page module — not the value
733
+ * captured at scan time.
734
+ *
735
+ * In dev, `handleDevRequest` re-imports the page on every request to pick up
736
+ * source edits via the `?furin-server&t=<ts>` cache-buster. Without this
737
+ * function the spread `{ ...route, page, chain }` would carry over the stale
738
+ * `route.mode` resolved at startup, so toggling `revalidate` or removing a
739
+ * loader in source would not retake effect until a server restart.
740
+ *
741
+ * Only `mode` is recomputed: it is the only field DERIVED from page+chain.
742
+ * Structural fields (`pattern`, `path`, `segmentBoundaries`, `error`,
743
+ * `notFound`) are scan-time invariants in dev and are preserved as-is.
744
+ */
745
+ export function rebuildDevRoute(
746
+ base: ResolvedRoute,
747
+ page: RuntimePage,
748
+ chain: RuntimeRoute[]
749
+ ): ResolvedRoute {
750
+ return {
751
+ ...base,
752
+ page,
753
+ routeChain: chain,
754
+ mode: resolveMode(page, chain),
755
+ tags: collectRouteTags(chain, page),
756
+ };
757
+ }
758
+
641
759
  /** @internal Handles a request in dev mode — re-imports the page fresh on every request. */
642
760
  async function handleDevRequest(
643
761
  route: ResolvedRoute,
@@ -684,7 +802,7 @@ async function handleDevRequest(
684
802
  chain[0].loader = currentRoot.route.loader;
685
803
  }
686
804
 
687
- const refreshedRoute: ResolvedRoute = { ...route, page, routeChain: chain };
805
+ const refreshedRoute = rebuildDevRoute(route, page, chain);
688
806
 
689
807
  // Live ISR — the loader chain is short-circuited by the dev cache when
690
808
  // a fresh entry exists. HTML re-assembles every time so the dev shell
@@ -733,24 +851,29 @@ async function renderDevISRWithLoaderCache(
733
851
  if (cached && isDevLoaderCacheValid(cached)) {
734
852
  const precomputed: LoaderResult = {
735
853
  type: "data",
736
- data: cached.loaderData,
854
+ syncData: cached.loaderData,
855
+ deferredPromises: undefined,
737
856
  headers: cached.headers,
738
857
  };
739
858
  return renderSSR(route, ctx, root, precomputed);
740
859
  }
741
860
 
742
- const result = await runLoaders(route, ctx, root.route);
861
+ const result = await runLoaders(route, ctx);
743
862
  if (result.type === "data") {
744
863
  const revalidate = route.page._route.revalidate ?? 60;
745
864
  const entry: DevLoaderCacheEntry = {
746
865
  dependencies: computeRouteDependencies(route.path, root.path),
747
866
  generatedAt: Date.now(),
748
867
  headers: result.headers,
749
- loaderData: result.data,
868
+ loaderData: result.syncData,
750
869
  mode: "isr",
751
870
  revalidate,
752
871
  };
753
872
  setDevISRLoaderCache(cacheKey, entry);
873
+ autoInvalidateRegistry.registerLoaderTags(
874
+ resolvePath(route.pattern, ctx.params ?? {}),
875
+ route.tags
876
+ );
754
877
  }
755
878
  return renderSSR(route, ctx, root, result);
756
879
  }
@@ -773,24 +896,29 @@ async function renderDevSSGWithLoaderCache(
773
896
  if (cached && isDevLoaderCacheValid(cached)) {
774
897
  const precomputed: LoaderResult = {
775
898
  type: "data",
776
- data: cached.loaderData,
899
+ syncData: cached.loaderData,
900
+ deferredPromises: undefined,
777
901
  headers: cached.headers,
778
902
  };
779
903
  return renderSSR(route, ctx, root, precomputed);
780
904
  }
781
905
 
782
- const result = await runLoaders(route, ctx, root.route);
906
+ const result = await runLoaders(route, ctx);
783
907
  if (result.type === "data") {
784
908
  const entry: DevLoaderCacheEntry = {
785
909
  dependencies: computeRouteDependencies(route.path, root.path),
786
910
  generatedAt: Date.now(),
787
911
  headers: result.headers,
788
- loaderData: result.data,
912
+ loaderData: result.syncData,
789
913
  mode: "ssg",
790
914
  // SSG entries are forever-fresh — only source-aware invalidation drops them.
791
915
  revalidate: Number.POSITIVE_INFINITY,
792
916
  };
793
917
  setDevSSGLoaderCache(cacheKey, entry);
918
+ autoInvalidateRegistry.registerLoaderTags(
919
+ resolvePath(route.pattern, ctx.params ?? {}),
920
+ route.tags
921
+ );
794
922
  }
795
923
  return renderSSR(route, ctx, root, result);
796
924
  }
@@ -872,7 +1000,7 @@ export function mergeRouteSchemas(
872
1000
  routeChain: RuntimeRoute[],
873
1001
  key: "params" | "query"
874
1002
  ): AnySchema | undefined {
875
- const schemas = routeChain.map((r) => r[key]).filter(Boolean) as Record<string, unknown>[];
1003
+ const schemas = routeChain.flatMap((r) => (r[key] ? [r[key]] : [])) as Record<string, unknown>[];
876
1004
 
877
1005
  if (schemas.length === 0) {
878
1006
  return;
@@ -954,6 +1082,13 @@ export function createRoutePlugin(route: ResolvedRoute, root: RootLayout, buildI
954
1082
  return plugin;
955
1083
  }
956
1084
 
1085
+ /**
1086
+ * Per-level cap on parallel directory traversals. Bounds peak in-flight
1087
+ * `readdir` calls to roughly `DIR_SCAN_CONCURRENCY * tree-depth`, which keeps
1088
+ * a wide flat pagesDir from opening thousands of FDs at once.
1089
+ */
1090
+ const DIR_SCAN_CONCURRENCY = 8;
1091
+
957
1092
  async function collectPageFilePaths(dir: string): Promise<string[]> {
958
1093
  const files: string[] = [];
959
1094
 
@@ -966,17 +1101,21 @@ async function collectPageFilePaths(dir: string): Promise<string[]> {
966
1101
  a.name.localeCompare(b.name)
967
1102
  );
968
1103
 
969
- for (const entry of entries) {
1104
+ // Walk subdirectories with bounded parallelism, then merge results in the
1105
+ // original alphabetical entry order so the depth-first interleaving is
1106
+ // preserved (file, then its sub-tree, then next file…).
1107
+ const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
970
1108
  const absolutePath = join(dir, entry.name);
971
-
972
1109
  if (entry.isDirectory()) {
973
- files.push(...(await collectPageFilePaths(absolutePath)));
974
- continue;
1110
+ return await collectPageFilePaths(absolutePath);
975
1111
  }
976
-
977
1112
  if (entry.isFile()) {
978
- files.push(absolutePath);
1113
+ return [absolutePath];
979
1114
  }
1115
+ return [];
1116
+ });
1117
+ for (const chunk of resolved) {
1118
+ files.push(...chunk);
980
1119
  }
981
1120
 
982
1121
  return files;
@@ -1032,3 +1171,396 @@ export function filePathToPattern(path: string): string {
1032
1171
 
1033
1172
  return `/${segments.join("/")}`;
1034
1173
  }
1174
+
1175
+ // ── /_furin/data endpoint ──────────────────────────────────────────────────────
1176
+
1177
+ const REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/;
1178
+
1179
+ function escapeRegExpChar(ch: string): string {
1180
+ return REGEX_META_CHARS_RE.test(ch) ? `\\${ch}` : ch;
1181
+ }
1182
+
1183
+ /**
1184
+ * Scores how specific a route pattern is so the `/_furin/data` matcher can
1185
+ * prefer a static route over a dynamic sibling that also matches. Per segment:
1186
+ * a literal segment outranks a `:param`, which outranks a `*` wildcard.
1187
+ */
1188
+ function routeSpecificity(pattern: string): number {
1189
+ let score = 0;
1190
+ for (const segment of pattern.split("/")) {
1191
+ if (segment.length === 0) {
1192
+ continue;
1193
+ }
1194
+ if (segment === "*") {
1195
+ score += 1;
1196
+ } else if (segment.startsWith(":")) {
1197
+ score += 2;
1198
+ } else {
1199
+ score += 3;
1200
+ }
1201
+ }
1202
+ return score;
1203
+ }
1204
+
1205
+ /**
1206
+ * Builds a regex from a route pattern, extracts named capture groups for
1207
+ * each `:param` segment, and returns `{ regex, paramNames }`.
1208
+ *
1209
+ * Literal characters (e.g. dots in filenames like `v1.0`) are escaped so
1210
+ * they are matched exactly rather than interpreted as regex syntax.
1211
+ */
1212
+ function buildRouteRegex(pattern: string): { regex: RegExp; paramNames: string[] } {
1213
+ const paramNames: string[] = [];
1214
+ let source = "";
1215
+ let i = 0;
1216
+ while (i < pattern.length) {
1217
+ if (pattern[i] === ":") {
1218
+ const start = ++i;
1219
+ while (i < pattern.length && pattern[i] !== "/") {
1220
+ i++;
1221
+ }
1222
+ paramNames.push(pattern.slice(start, i));
1223
+ source += "([^/]+)";
1224
+ } else if (pattern[i] === "*") {
1225
+ paramNames.push("*");
1226
+ source += "(.*)";
1227
+ i++;
1228
+ } else {
1229
+ const ch = pattern[i];
1230
+ if (ch !== undefined) {
1231
+ source += escapeRegExpChar(ch);
1232
+ }
1233
+ i++;
1234
+ }
1235
+ }
1236
+ return { regex: new RegExp(`^${source}$`), paramNames };
1237
+ }
1238
+
1239
+ /**
1240
+ * Applies top-level `default` values from a TypeBox TObject schema to a
1241
+ * values record. Used in the `/_furin/data` endpoint so loaders see the same
1242
+ * defaulted query objects that the SSR path produces via Elysia's guard.
1243
+ */
1244
+ function applySchemaDefaults(
1245
+ schema: Record<string, unknown> | undefined,
1246
+ values: Record<string, unknown>
1247
+ ): Record<string, unknown> {
1248
+ if (!schema || typeof schema !== "object") {
1249
+ return values;
1250
+ }
1251
+ const s = schema as Record<string, unknown>;
1252
+ if (s.type !== "object" || !s.properties || typeof s.properties !== "object") {
1253
+ return values;
1254
+ }
1255
+ const result = { ...values };
1256
+ const properties = s.properties as Record<string, Record<string, unknown>>;
1257
+ for (const [key, propSchema] of Object.entries(properties)) {
1258
+ if (
1259
+ !(key in result) &&
1260
+ propSchema &&
1261
+ typeof propSchema === "object" &&
1262
+ "default" in propSchema
1263
+ ) {
1264
+ result[key] = propSchema.default;
1265
+ }
1266
+ }
1267
+ return result;
1268
+ }
1269
+
1270
+ /**
1271
+ * Elysia plugin that handles `GET /_furin/data?path=<logicalHref>`.
1272
+ *
1273
+ * Returns an NDJSON stream (one-line, v1) produced by `toCrossJSONAsync`:
1274
+ * Line 0 — CrossJSON serialisation of `{ ...syncData, ...deferredPromises }`
1275
+ *
1276
+ * The `deferredPromises` values are awaited by `toCrossJSONAsync` before
1277
+ * serialising, so the client receives all data resolved in one round-trip.
1278
+ * SPA navigation calls this endpoint via `parseDeferredNdjson` in
1279
+ * `router-provider.tsx`.
1280
+ *
1281
+ * Special fields emitted alongside data:
1282
+ * - `__furinStatus: 404` — when the loader called `notFound()`
1283
+ * - `__furinNotFound` — not-found payload
1284
+ * - `__furinRedirect` — logical path after a server-side redirect
1285
+ */
1286
+ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
1287
+ const plugin = new Elysia();
1288
+
1289
+ plugin.get(
1290
+ "/_furin/data",
1291
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: data endpoint handler validates path, resolves loaders, handles deferred/SPA/ISR modes — each branch is a distinct protocol case; splitting would spread context across many functions
1292
+ async (ctx) => {
1293
+ const rawPath = ctx.query.path;
1294
+ if (!rawPath || typeof rawPath !== "string") {
1295
+ return new Response("Missing required query param: path", { status: 400 });
1296
+ }
1297
+
1298
+ const parsed = parseDataEndpointPath(rawPath);
1299
+ if (!parsed) {
1300
+ return new Response("Invalid path", { status: 400 });
1301
+ }
1302
+ const { url, pathname } = parsed;
1303
+
1304
+ // Rewrite the request-scoped wide event so logs / drains report the
1305
+ // *logical* path the user navigated to (e.g. "/board/123/card/456")
1306
+ // instead of the technical "/_furin/data" transport URL. We set this
1307
+ // before the route-match check so 404s also surface the attempted path
1308
+ // — otherwise monitoring just sees "GET /_furin/data 404" with no clue.
1309
+ const wideEventLog = useLogger();
1310
+ wideEventLog.set({ path: rawPath });
1311
+
1312
+ // Find the MOST SPECIFIC matching route. A first-match scan would let a
1313
+ // dynamic route (`/users/:id`) shadow a static sibling (`/users/new`)
1314
+ // whenever it is scanned first — and `[id]` sorts before `new`, so it
1315
+ // is. Score each match (static segment > :param > wildcard) and keep the
1316
+ // highest, mirroring the precedence Elysia's router applies on the SSR path.
1317
+ const matched = routes.reduce<{
1318
+ route: ResolvedRoute;
1319
+ params: Record<string, string>;
1320
+ score: number;
1321
+ } | null>((acc, route) => {
1322
+ const { regex, paramNames } = buildRouteRegex(route.pattern);
1323
+ const m = regex.exec(pathname);
1324
+ if (!m) {
1325
+ return acc;
1326
+ }
1327
+ const score = routeSpecificity(route.pattern);
1328
+ if (acc && acc.score >= score) {
1329
+ return acc;
1330
+ }
1331
+ const params: Record<string, string> = {};
1332
+ for (let i = 0; i < paramNames.length; i++) {
1333
+ const name = paramNames[i];
1334
+ if (name !== undefined) {
1335
+ params[name] = m[i + 1] ?? "";
1336
+ }
1337
+ }
1338
+ return { route, params, score };
1339
+ }, null);
1340
+
1341
+ if (!matched) {
1342
+ return new Response("Route not found", { status: 404 });
1343
+ }
1344
+
1345
+ // Now that we know the matched pattern, add it as a stable aggregation
1346
+ // key for drains (e.g. "p99 latency by route").
1347
+ wideEventLog.set({ routePattern: matched.route.pattern });
1348
+
1349
+ // Build a synthetic Elysia-compatible context for the matched route.
1350
+ // Loaders receive request, params, query, set, headers, and cookie.
1351
+ // Build the synthetic URL from the parsed `pathname + search` only —
1352
+ // never from `rawPath` directly — so an attacker cannot smuggle a
1353
+ // foreign origin into `syntheticRequest.url`.
1354
+ const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
1355
+ const syntheticSet = { headers: {} as Record<string, string>, status: 200 as number };
1356
+ const syntheticCtx = {
1357
+ request: syntheticRequest,
1358
+ params: matched.params,
1359
+ query: Object.fromEntries(url.searchParams),
1360
+ set: syntheticSet,
1361
+ headers: ctx.headers,
1362
+ cookie: ctx.cookie,
1363
+ path: pathname,
1364
+ // Loader-emitted redirects flow through `runLoaders` → `result.type
1365
+ // === "redirect"` and are converted to NDJSON below. The Response we
1366
+ // return here only has to be detectable by that pipeline.
1367
+ redirect: (location: string, status?: number) =>
1368
+ new Response(null, { status: status ?? 302, headers: { location } }),
1369
+ // Synthetic `status` helper: numeric codes only. Callers that reach
1370
+ // this endpoint never dispatch a string-keyed status; rejecting them
1371
+ // is safer than coercing via `Number(code)` and silently producing
1372
+ // `NaN`. Query-default redirects no longer flow through this helper —
1373
+ // they are detected via `detectQueryDefaultRedirect` below.
1374
+ status: (code: number) => new Response(null, { status: code }),
1375
+ } as unknown as Context;
1376
+
1377
+ // Normalize params and query through the same merged schemas used by
1378
+ // createRoutePlugin so loaders see identical typed/defaulted inputs.
1379
+ const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
1380
+ const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
1381
+ syntheticCtx.params = applySchemaDefaults(
1382
+ mergedParams as Record<string, unknown> | undefined,
1383
+ syntheticCtx.params as Record<string, unknown>
1384
+ ) as Record<string, string>;
1385
+ syntheticCtx.query = applySchemaDefaults(
1386
+ mergedQuery as Record<string, unknown> | undefined,
1387
+ syntheticCtx.query as Record<string, unknown>
1388
+ ) as Record<string, string>;
1389
+
1390
+ // Query-default redirect: detect via the pure helper so we can emit the
1391
+ // NDJSON `__furinRedirect` sentinel (the SPA client cannot parse a real
1392
+ // HTTP 302 — it never sees one because `parseDeferredNdjson` reads the
1393
+ // body, not the redirect chain).
1394
+ if (mergedQuery) {
1395
+ const redirectLocation = detectQueryDefaultRedirect(
1396
+ syntheticRequest,
1397
+ syntheticCtx.query as Record<string, unknown>
1398
+ );
1399
+ if (redirectLocation) {
1400
+ const serialized = await toCrossJSONAsync({ __furinRedirect: redirectLocation });
1401
+ return new Response(`${JSON.stringify(serialized)}\n`, {
1402
+ headers: { "content-type": "application/x-ndjson" },
1403
+ });
1404
+ }
1405
+ }
1406
+
1407
+ const result = await runLoaders(matched.route, syntheticCtx);
1408
+
1409
+ // Keep the auto-invalidate registry in sync with whatever path was just
1410
+ // served, so subsequent `revalidateTag(...)` calls (e.g. from a mutation
1411
+ // afterHandle) can still find this URL by tag. Without this, a SPA-only
1412
+ // navigation path (which never goes through the full-HTML render that
1413
+ // also registers tags) would silently fall off the registry — the first
1414
+ // mutation invalidates and unregisters via the cache `onDelete` hook,
1415
+ // the next SPA fetch re-loads but does not re-register, and from then
1416
+ // on `revalidateTag` finds no path to invalidate.
1417
+ if (result.type === "data") {
1418
+ autoInvalidateRegistry.registerLoaderTags(pathname, matched.route.tags);
1419
+ }
1420
+
1421
+ if (result.type === "redirect") {
1422
+ // Encode the redirect target as a special field for the client to follow
1423
+ const redirectUrl = new URL(
1424
+ result.response.headers.get("location") ?? "/",
1425
+ ctx.request.url
1426
+ );
1427
+ const serialized = await toCrossJSONAsync({
1428
+ __furinRedirect: redirectUrl.pathname + redirectUrl.search,
1429
+ });
1430
+ return new Response(`${JSON.stringify(serialized)}\n`, {
1431
+ headers: { "content-type": "application/x-ndjson" },
1432
+ });
1433
+ }
1434
+
1435
+ if (result.type === "not-found") {
1436
+ const serialized = await toCrossJSONAsync({
1437
+ __furinStatus: 404,
1438
+ __furinNotFound: { message: result.error.message, data: result.error.data },
1439
+ });
1440
+ return new Response(`${JSON.stringify(serialized)}\n`, {
1441
+ status: 200,
1442
+ headers: { "content-type": "application/x-ndjson" },
1443
+ });
1444
+ }
1445
+
1446
+ if (result.type === "error") {
1447
+ // Compute the digest server-side ONCE so:
1448
+ // 1. The HTTP response body carries it (client error UI displays the
1449
+ // same id the server logs).
1450
+ // 2. The server-log line below uses the SAME digest a user would see
1451
+ // on screen, enabling support correlation.
1452
+ // Recomputing client-side from a synthetic message + stack would yield
1453
+ // a different hash — see boundaries.tsx for the digest precedence.
1454
+ const digest = computeErrorDigest(result.error);
1455
+ const serialized = await toCrossJSONAsync({
1456
+ __furinError: {
1457
+ digest,
1458
+ message: result.message,
1459
+ status: result.status,
1460
+ },
1461
+ });
1462
+ return new Response(`${JSON.stringify(serialized)}\n`, {
1463
+ status: result.status,
1464
+ headers: { "content-type": "application/x-ndjson" },
1465
+ });
1466
+ }
1467
+
1468
+ // Resolve the page title server-side: head() never runs in the browser,
1469
+ // so SPA navigation depends on the endpoint shipping it as __furinTitle.
1470
+ const syncDataWithTitle = withResolvedTitle(matched.route, result.syncData);
1471
+
1472
+ if (result.deferredPromises) {
1473
+ return new Response(
1474
+ createDeferredNdjsonStream(syncDataWithTitle, result.deferredPromises),
1475
+ {
1476
+ headers: {
1477
+ "content-type": "application/x-ndjson",
1478
+ ...result.headers,
1479
+ },
1480
+ }
1481
+ );
1482
+ }
1483
+
1484
+ // No deferred fields: emit the single-line payload used by the legacy path.
1485
+ const serialized = await toCrossJSONAsync(syncDataWithTitle);
1486
+ return new Response(`${JSON.stringify(serialized)}\n`, {
1487
+ headers: {
1488
+ "content-type": "application/x-ndjson",
1489
+ ...result.headers,
1490
+ },
1491
+ });
1492
+ },
1493
+ {
1494
+ query: t.Object({ path: t.Optional(t.String()) }),
1495
+ }
1496
+ );
1497
+
1498
+ return plugin;
1499
+ }
1500
+
1501
+ /**
1502
+ * Runs the matched page's `head()` against the resolved sync data and, when it
1503
+ * yields a title, returns a copy of `syncData` carrying the reserved
1504
+ * `__furinTitle` field. `head()` never executes in the browser, so this is the
1505
+ * only channel through which SPA navigation can learn the new document title.
1506
+ *
1507
+ * Deferred fields are absent from `syncData` (they are still Promises), so a
1508
+ * `head()` that reads one sees `undefined` — titles should be derived from
1509
+ * synchronous loader data. A throwing `head()` is swallowed: a missing title
1510
+ * must never break the data response.
1511
+ */
1512
+ function withResolvedTitle(
1513
+ route: ResolvedRoute,
1514
+ syncData: Record<string, unknown>
1515
+ ): Record<string, unknown> {
1516
+ const head = route.page.head;
1517
+ if (!head) {
1518
+ return syncData;
1519
+ }
1520
+ let title: string | undefined;
1521
+ try {
1522
+ title = extractTitle(head(syncData).meta);
1523
+ } catch {
1524
+ return syncData;
1525
+ }
1526
+ if (title === undefined) {
1527
+ return syncData;
1528
+ }
1529
+ return { ...syncData, __furinTitle: title };
1530
+ }
1531
+
1532
+ function createDeferredNdjsonStream(
1533
+ syncData: Record<string, unknown>,
1534
+ deferredPromises: Record<string, Promise<unknown>>
1535
+ ): ReadableStream<Uint8Array> {
1536
+ const enc = new TextEncoder();
1537
+ const entries = Object.entries(deferredPromises);
1538
+
1539
+ return new ReadableStream<Uint8Array>({
1540
+ async start(controller) {
1541
+ const initial = toCrossJSON({
1542
+ ...syncData,
1543
+ __furinDeferredKeys: entries.map(([key]) => key),
1544
+ });
1545
+ controller.enqueue(enc.encode(`${JSON.stringify(initial)}\n`));
1546
+
1547
+ await Promise.all(
1548
+ entries.map(async ([key, promise]) => {
1549
+ try {
1550
+ const value = await promise;
1551
+ controller.enqueue(
1552
+ enc.encode(
1553
+ `${JSON.stringify({ key, action: "resolve", value: toCrossJSON(value) })}\n`
1554
+ )
1555
+ );
1556
+ } catch (err) {
1557
+ const normalized = await serializeDeferredRejection(err);
1558
+ const value = toCrossJSON(normalized);
1559
+ controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "reject", value })}\n`));
1560
+ }
1561
+ })
1562
+ );
1563
+ controller.close();
1564
+ },
1565
+ });
1566
+ }