@teyik0/furin 0.3.0-alpha.1 → 0.4.0-alpha.1

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 (144) hide show
  1. package/dist/adapter/bun.d.ts +1 -1
  2. package/dist/build/client.d.ts +2 -2
  3. package/dist/build/entry-template.d.ts +4 -0
  4. package/dist/build/entry-template.ts +17 -3
  5. package/dist/build/index.d.ts +1 -1
  6. package/dist/build/index.js +8288 -6629
  7. package/dist/build/route-types.d.ts +2 -22
  8. package/dist/build/shared.d.ts +1 -1
  9. package/dist/build/ssg-cache.d.ts +1 -1
  10. package/dist/build/types.d.ts +1 -1
  11. package/dist/cli/index.js +7862 -6168
  12. package/dist/client/boundaries.d.ts +2 -0
  13. package/dist/client/define-route.d.ts +35 -0
  14. package/dist/client/document.d.ts +26 -0
  15. package/dist/client/hmr.d.ts +10 -0
  16. package/dist/client/internal/runtime-types.d.ts +3 -1
  17. package/dist/client/link.js +1177 -894
  18. package/dist/client/router/index.d.ts +1 -1
  19. package/dist/client/router/link-utils.d.ts +9 -0
  20. package/dist/client/router/search/index.d.ts +3 -7
  21. package/dist/client/router/types.d.ts +32 -24
  22. package/dist/client.d.ts +4 -159
  23. package/dist/client.js +183 -21
  24. package/dist/config.d.ts +8 -8
  25. package/dist/config.js +8 -8
  26. package/dist/define-route.d.ts +1355 -0
  27. package/dist/furin.d.ts +17 -33
  28. package/dist/furin.js +13444 -10301
  29. package/dist/plugin/index.js +953 -244
  30. package/dist/plugin/route-config-autofix.d.ts +31 -0
  31. package/dist/plugin/routes.d.ts +27 -0
  32. package/dist/routes.d.ts +6 -0
  33. package/dist/routes.js +1 -0
  34. package/dist/rsc/build/index.d.ts +1 -1
  35. package/dist/rsc.js +3 -3
  36. package/dist/server/dev-page-plugin.d.ts +7 -5
  37. package/dist/server/devtools/instrumentation.d.ts +2 -2
  38. package/dist/server/devtools/instrumentation.production.d.ts +2 -2
  39. package/dist/server/devtools/plugin.d.ts +2 -2
  40. package/dist/server/internal.d.ts +3 -0
  41. package/dist/server/logger.d.ts +4 -0
  42. package/dist/server/render/assemble.d.ts +0 -9
  43. package/dist/server/render/document.d.ts +4 -0
  44. package/dist/server/render/element.d.ts +2 -1
  45. package/dist/server/render/index.d.ts +1 -1
  46. package/dist/server/render/index.ts +0 -1
  47. package/dist/server/render/isr.d.ts +1 -1
  48. package/dist/server/render/loaders.d.ts +1 -1
  49. package/dist/server/render/not-found.d.ts +1 -1
  50. package/dist/server/render/ppr-route.d.ts +1 -1
  51. package/dist/server/render/ssg.d.ts +1 -1
  52. package/dist/server/render/ssr.d.ts +7 -6
  53. package/dist/server/render/template.d.ts +4 -0
  54. package/dist/server/router/defined-route.d.ts +24 -0
  55. package/dist/server/router/hmr.d.ts +16 -8
  56. package/dist/server/router/patterns.d.ts +6 -0
  57. package/dist/server/router/plugin.d.ts +4 -3
  58. package/dist/server/router/schema-merge.d.ts +2 -2
  59. package/dist/server/router/schemas.d.ts +5 -5
  60. package/dist/server/router/source-version.d.ts +2 -0
  61. package/dist/server/router/types.d.ts +1 -0
  62. package/dist/server/sync/index.js +961 -806
  63. package/dist/server/sync/postgres/migrate.js +3 -2
  64. package/dist/shared/await.d.ts +6 -7
  65. package/dist/shared/elysia-contract.d.ts +41 -0
  66. package/dist/shared/route-map.d.ts +5 -0
  67. package/dist/shared/utils/index.d.ts +1 -3
  68. package/package.json +44 -41
  69. package/src/adapter/bun.ts +42 -22
  70. package/src/adapter/package.ts +20 -14
  71. package/src/adapter/static.ts +4 -3
  72. package/src/build/client.ts +20 -3
  73. package/src/build/entry-template.ts +17 -3
  74. package/src/build/hydrate.ts +98 -28
  75. package/src/build/index.ts +2 -2
  76. package/src/build/route-types.ts +19 -114
  77. package/src/build/shared.ts +1 -1
  78. package/src/build/ssg-cache.ts +2 -5
  79. package/src/build/types.ts +1 -1
  80. package/src/cli/config.ts +3 -3
  81. package/src/cli/index.ts +7 -7
  82. package/src/client/boundaries.tsx +9 -1
  83. package/src/client/define-route.ts +48 -0
  84. package/src/client/document.tsx +165 -0
  85. package/src/client/hmr.ts +40 -0
  86. package/src/client/internal/runtime-types.ts +3 -1
  87. package/src/client/link.tsx +21 -6
  88. package/src/client/router/index.ts +1 -0
  89. package/src/client/router/link-utils.ts +26 -0
  90. package/src/client/router/provider.tsx +25 -2
  91. package/src/client/router/search/index.ts +4 -12
  92. package/src/client/router/types.ts +50 -24
  93. package/src/client.ts +14 -316
  94. package/src/config.ts +10 -10
  95. package/src/define-route.ts +959 -0
  96. package/src/devtools/devtools-element.js +11 -10
  97. package/src/furin.ts +303 -53
  98. package/src/plugin/route-config-autofix.ts +1140 -0
  99. package/src/plugin/routes.ts +891 -0
  100. package/src/plugin/transform-client.ts +132 -266
  101. package/src/plugin/transform-isomorphic.ts +1 -1
  102. package/src/routes.ts +6 -0
  103. package/src/rsc/build/index.ts +1 -1
  104. package/src/server/auto-invalidate/registry.ts +2 -2
  105. package/src/server/dev-page-plugin.ts +31 -12
  106. package/src/server/devtools/instrumentation.production.ts +2 -2
  107. package/src/server/devtools/instrumentation.ts +2 -2
  108. package/src/server/devtools/plugin.ts +5 -3
  109. package/src/server/instance.ts +3 -3
  110. package/src/server/internal.ts +3 -0
  111. package/src/server/logger.ts +21 -0
  112. package/src/server/render/assemble.ts +0 -41
  113. package/src/server/render/document.tsx +25 -0
  114. package/src/server/render/element.tsx +13 -1
  115. package/src/server/render/index.ts +0 -1
  116. package/src/server/render/isr.ts +31 -10
  117. package/src/server/render/loaders.ts +31 -6
  118. package/src/server/render/not-found.ts +51 -27
  119. package/src/server/render/ppr-route.ts +1 -1
  120. package/src/server/render/ssg.ts +1 -1
  121. package/src/server/render/ssr.ts +271 -113
  122. package/src/server/render/template.ts +91 -1
  123. package/src/server/router/defined-route.ts +110 -0
  124. package/src/server/router/discovery.ts +129 -29
  125. package/src/server/router/hmr.ts +111 -40
  126. package/src/server/router/patterns.ts +40 -12
  127. package/src/server/router/plugin.ts +63 -46
  128. package/src/server/router/schema-merge.ts +4 -14
  129. package/src/server/router/schemas.ts +11 -8
  130. package/src/server/router/source-version.ts +16 -0
  131. package/src/server/router/types.ts +2 -0
  132. package/src/server/sync/postgres/migrate.ts +3 -2
  133. package/src/server/sync/response.ts +14 -10
  134. package/src/shared/await.tsx +6 -7
  135. package/src/shared/elysia-contract.ts +63 -0
  136. package/src/shared/route-map.ts +37 -0
  137. package/src/shared/utils/index.ts +2 -20
  138. package/dist/build/server-routes-entry.d.ts +0 -13
  139. package/dist/build/server-routes-entry.ts +0 -30
  140. package/dist/server/router/index.d.ts +0 -7
  141. package/dist/server/router/index.js +0 -27
  142. package/dist/server/router/index.ts +0 -28
  143. package/src/build/server-routes-entry.ts +0 -30
  144. package/src/server/router/index.ts +0 -28
@@ -3,7 +3,7 @@ import { existsSync } from "node:fs";
3
3
  import type { Context } from "elysia";
4
4
  import type { RuntimePage, RuntimeRoute } from "../../client/internal/runtime-types.ts";
5
5
  import type { SearchRouteMetadata } from "../../shared/search-params.ts";
6
- import { collectRouteChainFromRoute, isFurinPage, isFurinRoute } from "../../shared/utils/index.ts";
6
+ import { collectRouteChainFromRoute } from "../../shared/utils/index.ts";
7
7
  import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
8
8
  import {
9
9
  type DevLoaderCacheEntry,
@@ -18,12 +18,74 @@ import { type CompileContext, getCompileContext } from "../internal.ts";
18
18
  import { resolvePath } from "../render/assemble.ts";
19
19
  import { type LoaderResult, runLoaders } from "../render/loaders.ts";
20
20
  import { renderSSR } from "../render/ssr.ts";
21
+ import { adaptDefinedLayout, adaptDefinedPage, isDefinedRouteTerminal } from "./defined-route.ts";
21
22
  import { collectRouteTags, getSourceModuleCandidates, isModuleNotFoundError } from "./discovery.ts";
22
23
  import { collectIntermediateLayoutDirs, resolveMode } from "./patterns.ts";
24
+ import { invalidateRouteModuleSourceVersions, routeModuleSourceVersion } from "./source-version.ts";
23
25
  import type { ResolvedRoute, RootLayout } from "./types.ts";
24
26
 
25
27
  type RouteModuleImport = (specifier: string) => Promise<Record<string, unknown>>;
26
28
 
29
+ interface DevRouteModuleCacheEntry {
30
+ module: Promise<Record<string, unknown>>;
31
+ stamp: string;
32
+ }
33
+
34
+ const routeModuleImport: RouteModuleImport = (specifier) =>
35
+ import(specifier) as Promise<Record<string, unknown>>;
36
+ const runtimeDevRouteModuleCache = new Map<string, DevRouteModuleCacheEntry>();
37
+ const devRouteModuleCaches = new WeakMap<
38
+ RouteModuleImport,
39
+ Map<string, DevRouteModuleCacheEntry>
40
+ >();
41
+
42
+ /**
43
+ * Reuses one virtual ESM module per source version. A timestamp generated on
44
+ * every request leaks module-registry entries because Bun cannot release old
45
+ * module identities; the source stamp preserves HMR freshness without
46
+ * request-proportional growth. Promise caching also deduplicates concurrent
47
+ * requests for the same edited version.
48
+ */
49
+ export async function importStampedRouteModule(
50
+ path: string,
51
+ resolveImport: RouteModuleImport
52
+ ): Promise<Record<string, unknown>> {
53
+ let cache = runtimeDevRouteModuleCache;
54
+ if (resolveImport !== routeModuleImport) {
55
+ const resolverCache = devRouteModuleCaches.get(resolveImport);
56
+ if (resolverCache) {
57
+ cache = resolverCache;
58
+ } else {
59
+ cache = new Map();
60
+ devRouteModuleCaches.set(resolveImport, cache);
61
+ }
62
+ }
63
+ const stamp = routeModuleSourceVersion(path);
64
+ const cached = cache.get(path);
65
+ if (cached?.stamp === stamp) {
66
+ return cached.module;
67
+ }
68
+
69
+ const entry: DevRouteModuleCacheEntry = {
70
+ module: resolveImport(`${path}?furin-server&t=${stamp}`),
71
+ stamp,
72
+ };
73
+ cache.set(path, entry);
74
+ try {
75
+ return await entry.module;
76
+ } catch (error) {
77
+ if (cache.get(path) === entry) {
78
+ cache.delete(path);
79
+ }
80
+ throw error;
81
+ }
82
+ }
83
+
84
+ export function invalidateStampedRouteModules(): void {
85
+ invalidateRouteModuleSourceVersions();
86
+ runtimeDevRouteModuleCache.clear();
87
+ }
88
+
27
89
  function isResolvedRouteModuleCandidate(
28
90
  layoutPath: string,
29
91
  imported: Record<string, unknown>,
@@ -38,12 +100,17 @@ function isResolvedRouteModuleCandidate(
38
100
 
39
101
  export async function importFreshRouteModuleCandidate(
40
102
  layoutPath: string,
41
- timestamp: number,
42
103
  resolveImport: RouteModuleImport,
43
104
  ctx: CompileContext | null
44
105
  ): Promise<Record<string, unknown> | undefined> {
106
+ if (
107
+ resolveImport === routeModuleImport &&
108
+ !(existsSync(layoutPath) || ctx?.modules[layoutPath])
109
+ ) {
110
+ return;
111
+ }
45
112
  try {
46
- const imported = await resolveImport(`${layoutPath}?furin-server&t=${timestamp}`);
113
+ const imported = await importStampedRouteModule(layoutPath, resolveImport);
47
114
  if (!isResolvedRouteModuleCandidate(layoutPath, imported, ctx)) {
48
115
  return;
49
116
  }
@@ -66,17 +133,11 @@ export async function importFreshRouteModuleCandidate(
66
133
 
67
134
  async function importFreshLayoutRouteModule(
68
135
  layoutDir: string,
69
- timestamp: number,
70
136
  resolveImport: RouteModuleImport,
71
137
  ctx: CompileContext | null
72
138
  ): Promise<Record<string, unknown> | undefined> {
73
139
  for (const layoutPath of getSourceModuleCandidates(layoutDir, "_route")) {
74
- const freshMod = await importFreshRouteModuleCandidate(
75
- layoutPath,
76
- timestamp,
77
- resolveImport,
78
- ctx
79
- );
140
+ const freshMod = await importFreshRouteModuleCandidate(layoutPath, resolveImport, ctx);
80
141
  if (freshMod) {
81
142
  return freshMod;
82
143
  }
@@ -87,20 +148,28 @@ function patchRouteEntryFromFreshModule(
87
148
  entry: RuntimeRoute | undefined,
88
149
  freshMod: Record<string, unknown>
89
150
  ): void {
90
- const freshRoute = freshMod.route ?? freshMod.default;
91
- if (!(entry && freshRoute && isFurinRoute(freshRoute))) {
151
+ const freshRoute = freshMod.route;
152
+ if (!(entry && freshRoute)) {
92
153
  return;
93
154
  }
94
155
 
95
- entry.layout = freshRoute.layout;
96
- entry.loader = freshRoute.loader;
156
+ if (isDefinedRouteTerminal(freshRoute) && typeof freshRoute.layout === "function") {
157
+ const adapted = adaptDefinedLayout(freshRoute, entry.parent);
158
+ entry.layout = adapted.layout;
159
+ entry.loader = adapted.loader;
160
+ entry.mode = adapted.mode;
161
+ entry.params = adapted.params;
162
+ entry.query = adapted.query;
163
+ entry.requestLoader = adapted.requestLoader;
164
+ entry.revalidate = adapted.revalidate;
165
+ entry.tags = adapted.tags;
166
+ }
97
167
  }
98
168
 
99
169
  /**
100
- * Re-imports intermediate layout _route.tsx files with cache-busting so that
101
- * server-side renders reflect the latest code after an HMR edit. Bun's ESM
102
- * cache keeps the original module alive, so we import via ?furin-server and
103
- * patch the layout/loader references on the existing route-chain objects.
170
+ * Re-imports edited intermediate layout _route.tsx files with a versioned
171
+ * module identity, then patches the layout/loader references on the existing
172
+ * route-chain objects.
104
173
  *
105
174
  * The optional `importFn` parameter exists only for unit testing. In production
106
175
  * it defaults to the real `import()`.
@@ -111,10 +180,8 @@ export async function refreshLayoutChain(
111
180
  rootPath: string,
112
181
  importFn: ((specifier: string) => Promise<Record<string, unknown>>) | undefined
113
182
  ): Promise<void> {
114
- const resolveImport: RouteModuleImport =
115
- importFn ?? ((s: string) => import(s) as Promise<Record<string, unknown>>);
183
+ const resolveImport = importFn ?? routeModuleImport;
116
184
  const ctx = getCompileContext();
117
- const timestamp = Date.now();
118
185
  const layoutDirs = collectIntermediateLayoutDirs(pagePath, rootPath);
119
186
 
120
187
  // Track chainIdx independently rather than deriving it from layoutPaths
@@ -127,9 +194,7 @@ export async function refreshLayoutChain(
127
194
  // Imports are parallelised for speed; patching stays sequential so the
128
195
  // chainIdx-to-layoutDir positional mapping remains deterministic.
129
196
  const freshMods = await Promise.all(
130
- layoutDirs.map((layoutDir) =>
131
- importFreshLayoutRouteModule(layoutDir, timestamp, resolveImport, ctx)
132
- )
197
+ layoutDirs.map((layoutDir) => importFreshLayoutRouteModule(layoutDir, resolveImport, ctx))
133
198
  );
134
199
  let chainIdx = 1; // chain[0] is the root
135
200
  for (const freshMod of freshMods) {
@@ -157,8 +222,8 @@ export async function refreshLayoutChain(
157
222
  * `mode` reflects the CURRENT contents of the page module — not the value
158
223
  * captured at scan time.
159
224
  *
160
- * In dev, `handleDevRequest` re-imports the page on every request to pick up
161
- * source edits via the `?furin-server&t=<ts>` cache-buster. Without this
225
+ * In dev, `handleDevRequest` resolves the current versioned page module on
226
+ * every request. Without this
162
227
  * function the spread `{ ...route, page, chain }` would carry over the stale
163
228
  * `route.mode` resolved at startup, so toggling `revalidate` or removing a
164
229
  * loader in source would not retake effect until a server restart.
@@ -181,7 +246,7 @@ export function rebuildDevRoute(
181
246
  };
182
247
  }
183
248
 
184
- /** @internal Handles a request in dev mode — re-imports the page fresh on every request. */
249
+ /** @internal Handles a request in dev mode using the current source-version modules. */
185
250
  export async function handleDevRequest(
186
251
  route: ResolvedRoute,
187
252
  ctx: Context,
@@ -193,12 +258,9 @@ export async function handleDevRequest(
193
258
  // renders React to HTML, and injects __FURIN_DATA__.
194
259
  try {
195
260
  let currentRoot = root;
196
- const rootMod = (await import(`${root.path}?furin-server&t=${Date.now()}`)) as Record<
197
- string,
198
- unknown
199
- >;
200
- const rootExport = rootMod.route ?? rootMod.default;
201
- if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
261
+ const rootMod = await importStampedRouteModule(root.path, routeModuleImport);
262
+ const rootExport = rootMod.route;
263
+ if (isDefinedRouteTerminal(rootExport) && typeof rootExport.layout === "function") {
202
264
  // Preserve the RootLayout-level convention fields (error, notFound,
203
265
  // errorPath, notFoundPath) populated by `scanRootLayout` from
204
266
  // `pages/error.tsx` and `pages/not-found.tsx`. Replacing the whole
@@ -206,15 +268,24 @@ export async function handleDevRequest(
206
268
  // fallbacks — `route.error ?? root.error` would resolve to `undefined`
207
269
  // in dev after the first request, making custom 404/500 screens
208
270
  // disappear after a HMR refresh.
209
- currentRoot = { ...currentRoot, route: rootExport };
271
+ currentRoot = {
272
+ ...currentRoot,
273
+ route: adaptDefinedLayout(rootExport, undefined, root.path),
274
+ };
210
275
  }
211
276
 
212
- const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
213
- const page = pageMod.default;
214
- if (page && isFurinPage(page)) {
215
- const chain = collectRouteChainFromRoute(page._route as RuntimeRoute);
216
- await refreshLayoutChain(chain, route.path, root.path, undefined);
217
-
277
+ const pageMod = await importStampedRouteModule(route.path, routeModuleImport);
278
+ let page: RuntimePage | undefined;
279
+ let chain: RuntimeRoute[] | undefined;
280
+ if (isDefinedRouteTerminal(pageMod.route) && typeof pageMod.route.page === "function") {
281
+ const currentChain = route.routeChain;
282
+ await refreshLayoutChain(currentChain, route.path, root.path, undefined);
283
+ const parent = currentChain.at(-2) ?? currentRoot.route;
284
+ const adaptedPage = adaptDefinedPage(pageMod.route, parent);
285
+ page = adaptedPage;
286
+ chain = collectRouteChainFromRoute(adaptedPage._route);
287
+ }
288
+ if (page && chain) {
218
289
  // Patch chain[0] (the root) with the freshly-imported root's loader
219
290
  // and layout. `refreshLayoutChain` deliberately starts at chainIdx=1
220
291
  // because the root is already loaded separately above; without this
@@ -42,6 +42,41 @@ export function resolveMode(page: RuntimePage, routeChain: RuntimeRoute[]): "ssr
42
42
  return "ssr";
43
43
  }
44
44
 
45
+ const DYNAMIC_PARAMETER_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
46
+
47
+ export interface DynamicRouteSegment {
48
+ catchAll: boolean;
49
+ name: string;
50
+ }
51
+
52
+ export function parseDynamicRouteSegment(
53
+ segment: string,
54
+ sourcePath: string | undefined
55
+ ): DynamicRouteSegment | undefined {
56
+ if (!(segment.startsWith("[") && segment.endsWith("]"))) {
57
+ return;
58
+ }
59
+ const inner = segment.slice(1, -1);
60
+ const catchAll = inner.startsWith("...");
61
+ const name = catchAll ? inner.slice(3) : inner;
62
+ if (!DYNAMIC_PARAMETER_NAME_RE.test(name)) {
63
+ throw new Error(
64
+ `[furin] Invalid dynamic parameter ${JSON.stringify(name)} in ${JSON.stringify(
65
+ sourcePath ?? segment
66
+ )}. Parameter names must match ${DYNAMIC_PARAMETER_NAME_RE}.`
67
+ );
68
+ }
69
+ return { catchAll, name };
70
+ }
71
+
72
+ export function routeSegmentToPattern(segment: string): string {
73
+ const dynamic = parseDynamicRouteSegment(segment, undefined);
74
+ if (!dynamic) {
75
+ return segment;
76
+ }
77
+ return dynamic.catchAll ? "*" : `:${dynamic.name}`;
78
+ }
79
+
45
80
  export function filePathToPattern(path: string): string {
46
81
  const parts = path.replaceAll("\\", "/").split("/");
47
82
  const segments: string[] = [];
@@ -65,19 +100,12 @@ export function filePathToPattern(path: string): string {
65
100
  continue;
66
101
  }
67
102
 
68
- if (name.startsWith("[") && name.endsWith("]")) {
69
- const inner = name.slice(1, -1);
70
-
71
- if (inner.startsWith("...")) {
72
- segments.push("*");
73
- continue;
74
- }
75
-
76
- segments.push(`:${inner}`);
77
- continue;
103
+ const dynamic = parseDynamicRouteSegment(name, path);
104
+ if (dynamic) {
105
+ segments.push(dynamic.catchAll ? "*" : `:${dynamic.name}`);
106
+ } else {
107
+ segments.push(name);
78
108
  }
79
-
80
- segments.push(name);
81
109
  }
82
110
 
83
111
  return `/${segments.join("/")}`;
@@ -1,7 +1,8 @@
1
1
  import { type AnyElysia, type Context, Elysia, t } from "elysia";
2
- import type { AnySchema } from "elysia/types";
3
2
  import { toCrossJSONAsync } from "seroval";
3
+ import type { HeadOptions } from "../../client.ts";
4
4
  import { computeErrorDigest } from "../../shared/digest.ts";
5
+ import type { FurinSchema } from "../../shared/elysia-contract.ts";
5
6
  import { containsRscSource, serializeRouteFrames } from "../../shared/route-frame.ts";
6
7
  import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
7
8
  import { useLogger } from "../context-logger.ts";
@@ -28,7 +29,9 @@ import { handleDevRequest } from "./hmr.ts";
28
29
  import { buildRouteMatcher } from "./patterns.ts";
29
30
  import { mergeRouteSchemas } from "./schema-merge.ts";
30
31
  import { parseDataEndpointPath, parseRouteParams, parseRouteQuery } from "./schemas.ts";
31
- import type { ResolvedRoute, RootLayout } from "./types.ts";
32
+ import type { ResolvedRoute, ResolvedRoutesSource, RootLayout } from "./types.ts";
33
+
34
+ const MAX_NAVIGATION_HEAD_BYTES = 64 * 1024;
32
35
 
33
36
  interface DataRouteParamsInput {
34
37
  [key: string]: unknown;
@@ -106,7 +109,7 @@ async function createLoaderDataResponse(
106
109
  });
107
110
  }
108
111
 
109
- const syncDataWithTitle = withResolvedTitle(route, result.syncData);
112
+ const syncDataWithTitle = withResolvedHead(route, result.syncData);
110
113
  if (result.deferredPromises !== undefined) {
111
114
  return new Response(
112
115
  createDeferredRouteFrameStream(syncDataWithTitle, result.deferredPromises),
@@ -186,45 +189,46 @@ export function createRoutePlugin(
186
189
 
187
190
  if (allParams || allQuery) {
188
191
  plugin.guard({
189
- params: allParams as AnySchema,
190
- query: allQuery as AnySchema,
192
+ params: allParams as FurinSchema,
193
+ query: allQuery as FurinSchema,
191
194
  });
192
195
  }
193
196
 
194
- plugin.get(pattern, (ctx) => {
195
- // Dev mode: re-imports page + layouts on every request via the
196
- // ?furin-server cache-buster, then dispatches into one of:
197
- // - renderDevISRWithLoaderCache (mode === "isr")
198
- // - renderDevSSGWithLoaderCache (mode === "ssg")
199
- // - renderSSR (otherwise)
200
- //
201
- // Only the LOADER OUTPUT is cached in dev — HTML is always re-assembled
202
- // fresh so the response always embeds the latest Bun client chunk URL.
203
- // This avoids the "infinite reload loop" footgun where a cached ISR/SSG
204
- // HTML response held an OLD chunk URL after Bun rebundled. The dev
205
- // cache is invalidated source-aware via `isDevLoaderCacheValid`
206
- // (mtime-checked dependency walk on every read).
207
- if (IS_DEV) {
208
- return handleDevRequest(route, ctx, root, searchRoutes);
209
- }
197
+ plugin.get(pattern, (ctx) =>
198
+ renderResolvedRoute(route, ctx, root, resolvedBuildId, searchRoutes)
199
+ );
210
200
 
211
- if ((route.mode === "ssg" || route.mode === "isr") && hasRequestLoader(route)) {
212
- return renderPprRoute(route, ctx, root, resolvedBuildId, searchRoutes);
213
- }
201
+ return plugin;
202
+ }
214
203
 
215
- if (route.mode === "ssg") {
216
- return handleSSGRequest(route, ctx, root, resolvedBuildId, searchRoutes);
217
- }
204
+ export function renderResolvedRoute(
205
+ route: ResolvedRoute,
206
+ ctx: Context,
207
+ root: RootLayout,
208
+ buildId: string,
209
+ searchRoutes: SearchRouteMetadata[] | undefined
210
+ ): unknown {
211
+ // Dev mode: re-imports page + layouts on every request via the
212
+ // ?furin-server cache-buster. Only loader output is cached in dev; HTML is
213
+ // always reassembled with the latest Bun client chunk URL.
214
+ if (IS_DEV) {
215
+ return handleDevRequest(route, ctx, root, searchRoutes);
216
+ }
218
217
 
219
- if (route.mode === "isr") {
220
- ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
221
- return handleISR(route, ctx, root, resolvedBuildId, searchRoutes);
222
- }
218
+ if ((route.mode === "ssg" || route.mode === "isr") && hasRequestLoader(route)) {
219
+ return renderPprRoute(route, ctx, root, buildId, searchRoutes);
220
+ }
223
221
 
224
- return renderSSR(route, ctx, root, undefined, searchRoutes);
225
- });
222
+ if (route.mode === "ssg") {
223
+ return handleSSGRequest(route, ctx, root, buildId, searchRoutes);
224
+ }
226
225
 
227
- return plugin;
226
+ if (route.mode === "isr") {
227
+ ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
228
+ return handleISR(route, ctx, root, buildId, searchRoutes);
229
+ }
230
+
231
+ return renderSSR(route, ctx, root, undefined, searchRoutes);
228
232
  }
229
233
 
230
234
  /**
@@ -240,9 +244,10 @@ export function createRoutePlugin(
240
244
  * - `__furinNotFound` — not-found payload
241
245
  * - `__furinRedirect` — logical path after a server-side redirect
242
246
  */
243
- export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
247
+ export function createDataEndpoint(routesSource: ResolvedRoutesSource): AnyElysia {
244
248
  const plugin = new Elysia();
245
- const matchRoute = buildRouteMatcher(routes);
249
+ let matchedRoutes = typeof routesSource === "function" ? routesSource() : routesSource;
250
+ let matchRoute = buildRouteMatcher(matchedRoutes);
246
251
 
247
252
  plugin.get(
248
253
  "/_furin/data",
@@ -266,8 +271,11 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
266
271
  const wideEventLog = useLogger();
267
272
  wideEventLog.set({ path: rawPath });
268
273
 
269
- // Precompiled at plugin creation: route regexes are built once, sorted
270
- // most-specific first, then the hot path only executes regex matches.
274
+ const currentRoutes = typeof routesSource === "function" ? routesSource() : routesSource;
275
+ if (currentRoutes !== matchedRoutes) {
276
+ matchedRoutes = currentRoutes;
277
+ matchRoute = buildRouteMatcher(matchedRoutes);
278
+ }
271
279
  const matched = matchRoute(pathname);
272
280
 
273
281
  if (!matched) {
@@ -309,8 +317,8 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
309
317
  status: (code: number) => new Response(null, { status: code }),
310
318
  } as unknown as SyntheticDataContext;
311
319
 
312
- // Normalize params and query through the same merged schemas used by
313
- // createRoutePlugin so loaders see identical typed/defaulted inputs.
320
+ // Normalize params and query through the route chain schemas so SPA and
321
+ // document requests expose identical typed/defaulted inputs.
314
322
  const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
315
323
  const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
316
324
  const parsedParams = await parseRouteParams(matched.params, mergedParams);
@@ -356,7 +364,7 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
356
364
  * synchronous loader data. A throwing `head()` is swallowed: a missing title
357
365
  * must never break the data response.
358
366
  */
359
- function withResolvedTitle(
367
+ function withResolvedHead(
360
368
  route: ResolvedRoute,
361
369
  syncData: Record<string, unknown>
362
370
  ): Record<string, unknown> {
@@ -364,14 +372,23 @@ function withResolvedTitle(
364
372
  if (!head) {
365
373
  return syncData;
366
374
  }
367
- let title: string | undefined;
375
+ let headOptions: HeadOptions;
368
376
  try {
369
- title = extractTitle(head(syncData).meta);
377
+ headOptions = head(syncData);
370
378
  } catch {
371
379
  return syncData;
372
380
  }
373
- if (title === undefined) {
374
- return syncData;
381
+ const title = extractTitle(headOptions.meta);
382
+ let includeHead = false;
383
+ try {
384
+ includeHead =
385
+ new TextEncoder().encode(JSON.stringify(headOptions)).byteLength <= MAX_NAVIGATION_HEAD_BYTES;
386
+ } catch {
387
+ // Invalid or cyclic metadata must not break an otherwise valid navigation.
375
388
  }
376
- return { ...syncData, __furinTitle: title };
389
+ return {
390
+ ...syncData,
391
+ ...(includeHead ? { __furinHead: headOptions } : {}),
392
+ ...(title === undefined ? {} : { __furinTitle: title }),
393
+ };
377
394
  }
@@ -1,33 +1,23 @@
1
1
  import { t } from "elysia";
2
- import type { AnySchema } from "elysia/types";
3
2
  import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
3
+ import { type FurinSchema, isTypeBoxObjectSchema } from "../../shared/elysia-contract.ts";
4
4
 
5
5
  interface SchemaObject {
6
6
  [key: string]: unknown;
7
7
  }
8
8
 
9
9
  const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
10
- const TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
11
-
12
- function isTypeBoxObjectSchema(schema: unknown): schema is SchemaObject {
13
- return (
14
- schema !== null &&
15
- typeof schema === "object" &&
16
- (schema as SchemaObject & { [key: symbol]: unknown })[TYPEBOX_KIND] === "Object"
17
- );
18
- }
19
-
20
10
  export function mergeRouteSchemas(
21
11
  routeChain: RuntimeRoute[],
22
12
  key: "params" | "query"
23
- ): AnySchema | undefined {
13
+ ): FurinSchema | undefined {
24
14
  const schemas = routeChain.flatMap((route) => (route[key] ? [route[key] as SchemaObject] : []));
25
15
 
26
16
  if (schemas.length === 0) {
27
17
  return;
28
18
  }
29
19
  if (schemas.length === 1) {
30
- return schemas[0] as AnySchema;
20
+ return schemas[0] as FurinSchema;
31
21
  }
32
22
  if (schemas.some((schema) => !isTypeBoxObjectSchema(schema))) {
33
23
  throw new Error(
@@ -48,5 +38,5 @@ export function mergeRouteSchemas(
48
38
  )
49
39
  );
50
40
 
51
- return t.Object(properties, options) as AnySchema;
41
+ return t.Object(properties, options) as FurinSchema;
52
42
  }
@@ -1,7 +1,10 @@
1
- import { parseQueryFromURL, parseQueryStandardSchema } from "elysia/parse-query";
2
- import { getSchemaValidator } from "elysia/schema";
3
- import type { AnySchema } from "elysia/types";
4
1
  import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
2
+ import {
3
+ type FurinSchema,
4
+ getSchemaValidator,
5
+ parseQueryFromURL,
6
+ parseQueryStandardSchema,
7
+ } from "../../shared/elysia-contract.ts";
5
8
  import {
6
9
  collectSearchDefaults,
7
10
  type SearchParamsInput,
@@ -140,7 +143,7 @@ type RouteInputValidationResult =
140
143
 
141
144
  async function validateRouteInput(
142
145
  input: UnknownObject,
143
- schema: AnySchema
146
+ schema: FurinSchema
144
147
  ): Promise<RouteInputValidationResult> {
145
148
  if (isStandardSchema(schema)) {
146
149
  const validator = getSchemaValidator(schema, { dynamic: true });
@@ -175,7 +178,7 @@ async function validateRouteInput(
175
178
  */
176
179
  export async function parseRouteQuery(
177
180
  url: URL,
178
- schema: AnySchema | undefined
181
+ schema: FurinSchema | undefined
179
182
  ): Promise<ParseRouteQueryResult> {
180
183
  if (!schema) {
181
184
  return { ok: true, query: parseQueryFromURL(url.search, 1) as SearchParamsInput };
@@ -193,14 +196,14 @@ export async function parseRouteQuery(
193
196
 
194
197
  /**
195
198
  * Validates and coerces path params for the synthetic `/_furin/data` request
196
- * path. This mirrors the params schema installed by createRoutePlugin's Elysia
197
- * guard so SPA loaders receive the same values as full SSR loaders.
199
+ * path. This mirrors the composed Elysia route schema so SPA loaders receive
200
+ * the same values as full SSR loaders.
198
201
  *
199
202
  * @internal Exported for unit testing.
200
203
  */
201
204
  export async function parseRouteParams(
202
205
  params: UnknownObject,
203
- schema: AnySchema | undefined
206
+ schema: FurinSchema | undefined
204
207
  ): Promise<ParseRouteParamsResult> {
205
208
  if (!schema) {
206
209
  return { ok: true, params };
@@ -0,0 +1,16 @@
1
+ import { statSync } from "node:fs";
2
+
3
+ let routeModuleGeneration = 0;
4
+
5
+ export function routeModuleSourceVersion(path: string): string {
6
+ try {
7
+ const stats = statSync(path, { bigint: true });
8
+ return Bun.hash(`${stats.mtimeNs}:${stats.size}:${routeModuleGeneration}`).toString();
9
+ } catch {
10
+ return Bun.hash(`missing:${routeModuleGeneration}`).toString();
11
+ }
12
+ }
13
+
14
+ export function invalidateRouteModuleSourceVersions(): void {
15
+ routeModuleGeneration += 1;
16
+ }
@@ -49,6 +49,8 @@ export interface ResolvedRoute {
49
49
  tags?: string[];
50
50
  }
51
51
 
52
+ export type ResolvedRoutesSource = ResolvedRoute[] | (() => ResolvedRoute[]);
53
+
52
54
  export interface RootLayout {
53
55
  error?: ErrorComponent;
54
56
  errorPath?: string;
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env bun
2
+ import { fileURLToPath } from "node:url";
2
3
  import { SQL } from "bun";
3
4
 
4
5
  const databaseUrl = process.env.FURIN_SYNC_POSTGRES_URL;
@@ -8,8 +9,8 @@ if (databaseUrl === undefined || databaseUrl.length === 0) {
8
9
 
9
10
  const sql = new SQL(databaseUrl);
10
11
  try {
11
- const migration = await Bun.file(new URL("./migration.sql", import.meta.url)).text();
12
- await sql.unsafe(migration);
12
+ const migrationUrl = new URL("./migration.sql", import.meta.url);
13
+ await sql.file(fileURLToPath(migrationUrl));
13
14
  } finally {
14
15
  await sql.close();
15
16
  }
@@ -132,11 +132,13 @@ export function mergeStoredResponseHeaders(
132
132
  storedResponse: StoredResponse,
133
133
  headers: Context["set"]["headers"]
134
134
  ): StoredResponse {
135
- const merged = new Headers(
136
- storedResponse.headers
137
- .filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase()))
138
- .map(([name, value]) => [name, value] as [string, string])
139
- );
135
+ const headerEntries: [string, string][] = [];
136
+ for (const [name, value] of storedResponse.headers) {
137
+ if (!NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
138
+ headerEntries.push([name, value]);
139
+ }
140
+ }
141
+ const merged = new Headers(headerEntries);
140
142
  for (const [name, value] of Object.entries(headers)) {
141
143
  if (value !== undefined && !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
142
144
  merged.delete(name);
@@ -191,12 +193,14 @@ export function replayResponse(stored: StoredResponse): Response {
191
193
  stored.status === 204 || stored.status === 205 || stored.status === 304
192
194
  ? null
193
195
  : stored.body.slice();
196
+ const headerEntries: [string, string][] = [];
197
+ for (const [name, value] of stored.headers) {
198
+ if (!NON_REPLAYABLE_HEADERS.has(name.toLowerCase())) {
199
+ headerEntries.push([name, value]);
200
+ }
201
+ }
194
202
  return new Response(body, {
195
- headers: new Headers(
196
- stored.headers
197
- .filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase()))
198
- .map(([name, value]) => [name, value] as [string, string])
199
- ),
203
+ headers: new Headers(headerEntries),
200
204
  status: stored.status,
201
205
  });
202
206
  }