@teyik0/furin 0.2.0-alpha.3 → 0.2.0-alpha.5

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 (98) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +37 -33
  3. package/dist/adapter/bun.d.ts +17 -1
  4. package/dist/adapter/package.d.ts +26 -0
  5. package/dist/build/client.d.ts +1 -1
  6. package/dist/build/compile-entry.d.ts +3 -3
  7. package/dist/build/compile-entry.ts +114 -109
  8. package/dist/build/entry-template.d.ts +35 -9
  9. package/dist/build/entry-template.ts +206 -156
  10. package/dist/build/hydrate.d.ts +1 -1
  11. package/dist/build/index.js +643 -247
  12. package/dist/build/scan-server.d.ts +10 -4
  13. package/dist/build/server-routes-entry.d.ts +3 -3
  14. package/dist/build/server-routes-entry.ts +30 -36
  15. package/dist/build/ssg-cache.d.ts +1 -1
  16. package/dist/build/types.d.ts +36 -1
  17. package/dist/cli/config.d.ts +6 -1
  18. package/dist/cli/index.js +662 -260
  19. package/dist/client/link.js +163 -16
  20. package/dist/client/router/abort.d.ts +1 -0
  21. package/dist/client/router/sync-catch-up.d.ts +29 -0
  22. package/dist/config.d.ts +11 -2
  23. package/dist/config.js +5 -1
  24. package/dist/furin.d.ts +37 -19
  25. package/dist/furin.js +982 -378
  26. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  27. package/dist/server/cache/dev-loader.d.ts +3 -2
  28. package/dist/server/cache/invalidation.d.ts +19 -0
  29. package/dist/server/cache/isr.d.ts +6 -2
  30. package/dist/server/cache/registry.d.ts +3 -3
  31. package/dist/server/cache/ssg.d.ts +6 -2
  32. package/dist/server/cache/store-view.d.ts +11 -0
  33. package/dist/server/instance.d.ts +86 -0
  34. package/dist/server/internal.d.ts +16 -1
  35. package/dist/server/internal.js +72 -5
  36. package/dist/server/render/template.d.ts +3 -2
  37. package/dist/server/sync/adapter.d.ts +62 -0
  38. package/dist/server/sync/config.d.ts +11 -0
  39. package/dist/server/sync/fingerprint.d.ts +6 -0
  40. package/dist/server/sync/index.d.ts +2 -2
  41. package/dist/server/sync/memory-adapter.d.ts +17 -0
  42. package/dist/server/sync/plugin.d.ts +12 -195
  43. package/dist/server/sync/response.d.ts +4 -0
  44. package/dist/server/sync/stream.d.ts +24 -5
  45. package/dist/shared/prefix.d.ts +15 -0
  46. package/package.json +6 -1
  47. package/src/adapter/README.md +13 -13
  48. package/src/adapter/bun.ts +113 -50
  49. package/src/adapter/package.ts +206 -0
  50. package/src/build/client.ts +158 -152
  51. package/src/build/compile-entry.ts +114 -109
  52. package/src/build/entry-template.ts +206 -156
  53. package/src/build/hydrate.ts +342 -340
  54. package/src/build/index.ts +223 -152
  55. package/src/build/route-types.ts +145 -145
  56. package/src/build/scan-server.ts +111 -95
  57. package/src/build/server-routes-entry.ts +30 -36
  58. package/src/build/shared.ts +80 -80
  59. package/src/build/ssg-cache.ts +36 -32
  60. package/src/build/types.ts +125 -89
  61. package/src/cli/config.ts +9 -3
  62. package/src/cli/index.ts +21 -3
  63. package/src/client/router/abort.ts +5 -0
  64. package/src/client/router/link-utils.ts +184 -184
  65. package/src/client/router/provider.tsx +883 -804
  66. package/src/client/router/sync-catch-up.ts +113 -0
  67. package/src/client/router/types.ts +276 -276
  68. package/src/client/sync.ts +98 -98
  69. package/src/client.ts +369 -369
  70. package/src/config.ts +14 -1
  71. package/src/furin.ts +619 -465
  72. package/src/server/auto-invalidate/registry.ts +23 -1
  73. package/src/server/auto-invalidate/runtime.ts +159 -134
  74. package/src/server/cache/dev-loader.ts +77 -38
  75. package/src/server/cache/invalidation.ts +71 -30
  76. package/src/server/cache/isr.ts +20 -5
  77. package/src/server/cache/registry.ts +17 -20
  78. package/src/server/cache/ssg.ts +19 -4
  79. package/src/server/cache/store-view.ts +30 -0
  80. package/src/server/dev-page-plugin.ts +454 -454
  81. package/src/server/instance.ts +252 -0
  82. package/src/server/internal.ts +100 -5
  83. package/src/server/render/assemble.ts +160 -160
  84. package/src/server/render/isr.ts +323 -323
  85. package/src/server/render/not-found.ts +9 -3
  86. package/src/server/render/ssr.ts +603 -585
  87. package/src/server/render/template.ts +57 -24
  88. package/src/server/router/plugin.ts +384 -384
  89. package/src/server/sync/adapter.ts +65 -0
  90. package/src/server/sync/config.ts +60 -29
  91. package/src/server/sync/fingerprint.ts +44 -0
  92. package/src/server/sync/index.ts +15 -14
  93. package/src/server/sync/memory-adapter.ts +196 -0
  94. package/src/server/sync/plugin.ts +199 -108
  95. package/src/server/sync/response.ts +77 -0
  96. package/src/server/sync/stream.ts +162 -144
  97. package/src/shared/deferred-ndjson.ts +7 -0
  98. package/src/shared/prefix.ts +38 -0
@@ -1,340 +1,342 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { generateIndexHtml } from "../server/render/shell.ts";
4
- import { mergeRouteSchemas } from "../server/router/index.ts";
5
- import { buildRouteRegex } from "../server/router/patterns.ts";
6
- import type { ResolvedRoute } from "../server/router/index.ts";
7
- import { collectSearchDefaults } from "../shared/search-params.ts";
8
- import { writeRouteTypes } from "./route-types";
9
- import type { BuildClientOptions } from "./types";
10
-
11
- /**
12
- * Generates the client hydration entry.
13
- *
14
- * Renders into <div id="root"> (the SSR outlet element) and retains the React
15
- * root across hot reloads via import.meta.hot.data.root so React Fast Refresh
16
- * applies in-place instead of remounting.
17
- *
18
- * @param routes - Resolved routes to include in the hydration manifest.
19
- * @param rootLayout - Absolute path to the root layout module.
20
- * @param basePath - Optional sub-path prefix for static deployments (e.g. "/furin").
21
- * When set, the generated code strips the prefix from `window.location.pathname`
22
- * before matching routes, and passes `basePath` to `RouterProvider` so SPA
23
- * navigation uses the correct physical URLs.
24
- */
25
- export function generateHydrateEntry(
26
- routes: ResolvedRoute[],
27
- rootLayout: string,
28
- basePath: string,
29
- clientLogging: boolean
30
- ): string {
31
- const getBoundaryIdent = (idents: Map<string, string>, filePath: string | undefined) => {
32
- if (!filePath) {
33
- return;
34
- }
35
- const existing = idents.get(filePath);
36
- if (existing) {
37
- return existing;
38
- }
39
- const ident = `__furin_bnd_${idents.size}`;
40
- idents.set(filePath, ident);
41
- return ident;
42
- };
43
-
44
- const routeEntries: string[] = [];
45
-
46
- for (const route of routes) {
47
- const resolvedPage = route.path.replace(/\\/g, "/");
48
- const regexPattern = buildRouteRegex(route.pattern).regex.source;
49
- const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain ?? [], "query"));
50
- const boundaryIdents = new Map<string, string>();
51
-
52
- // Emit one boundary literal per segment that actually carries a convention
53
- // file — segments that only declare one of the two are emitted with the
54
- // missing field omitted entirely (keeps the generated JS tidy).
55
- const boundaryLiterals: string[] = [];
56
- for (const seg of route.segmentBoundaries ?? []) {
57
- const errorIdent = getBoundaryIdent(boundaryIdents, seg.errorPath);
58
- const notFoundIdent = getBoundaryIdent(boundaryIdents, seg.notFoundPath);
59
- if (!(errorIdent || notFoundIdent)) {
60
- continue;
61
- }
62
- const parts = [`depth: ${seg.depth}`];
63
- if (errorIdent) {
64
- parts.push(`error: ${errorIdent}.default`);
65
- }
66
- if (notFoundIdent) {
67
- parts.push(`notFound: ${notFoundIdent}.default`);
68
- }
69
- boundaryLiterals.push(`{ ${parts.join(", ")} }`);
70
- }
71
-
72
- const lazyImports = [
73
- `import("${resolvedPage}")`,
74
- ...[...boundaryIdents.keys()].map((filePath) => `import("${filePath.replace(/\\/g, "/")}")`),
75
- ];
76
- const loadBody =
77
- boundaryLiterals.length > 0
78
- ? `Promise.all([${lazyImports.join(", ")}]).then(([__furin_page, ${[
79
- ...boundaryIdents.values(),
80
- ].join(", ")}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))`
81
- : `import("${resolvedPage}")`;
82
-
83
- const searchDefaultsEntry = searchDefaults
84
- ? `, searchDefaults: ${JSON.stringify(searchDefaults)}`
85
- : "";
86
- routeEntries.push(
87
- ` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`
88
- );
89
- }
90
-
91
- // basePath stripping: when deployed to a sub-path (e.g. /furin), strip the
92
- // prefix before route matching so patterns like /docs/routing still work.
93
- const basePathLiteral = JSON.stringify(basePath);
94
- // Strip basePath only when it matches on a path boundary (prevents "/furin" from
95
- // matching "/furinity/foo"). The boundary holds when the pathname ends exactly
96
- // at the prefix length OR the next character is "/".
97
- // Trailing slashes are also stripped so "/docs/routing/" matches the route
98
- // pattern "/docs/routing" — GitHub Pages and many static hosts append them.
99
- const pathnameExpr = basePath
100
- ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; const stripped = (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; return stripped === "/" ? "/" : stripped.replace(/\\/+$/, ""); })()`
101
- : `window.location.pathname.replace(/\\/+$/, "") || "/"`;
102
-
103
- // Log drain endpoint: prepend basePath so the request goes to the correct origin path.
104
- const logEndpoint = basePath
105
- ? `${JSON.stringify(basePath)} + "/_furin/ingest"`
106
- : `"/_furin/ingest"`;
107
-
108
- // Client-side HTTP draining is opt-in (config `clientLogging`). When disabled
109
- // we emit neither the hydrate-entry evlog imports nor initLogger, and define a
110
- // no-op `log` shim so the hydration body's log.* calls stay valid.
111
- const loggingImports = clientLogging
112
- ? 'import { initLogger, log } from "evlog";\nimport { createHttpLogDrain } from "evlog/http";\n'
113
- : "";
114
- const loggerSetup = clientLogging
115
- ? `initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });`
116
- : "const log = { error() {}, info() {} };";
117
-
118
- // RouterProvider receives basePath so navigate() / Link push physical paths.
119
- const routerProviderDefaults = `\n autoRefresh: true,\n basePath: ${basePathLiteral},\n defaultPreload: "intent",\n defaultPreloadDelay: 50,\n defaultPreloadStaleTime: 30000,\n prefetchCacheSize: 50,\n syncStream,`;
120
-
121
- return `import { hydrateRoot, createRoot } from "react-dom/client";
122
- import { createElement } from "react";
123
- ${loggingImports}import { RouterProvider } from "@teyik0/furin/link";
124
- import { fromCrossJSON } from "@teyik0/furin/link";
125
- import type { SerovalNode } from "seroval";
126
- import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
127
-
128
- ${loggerSetup}
129
-
130
- const routes = [
131
- ${routeEntries.join(",\n")}
132
- ];
133
-
134
- const pathname = ${pathnameExpr};
135
- const _match = routes.find((r) => r.regex.test(pathname));
136
-
137
- // Parse the server-embedded loader payload up front. It carries:
138
- // - normal loader props under arbitrary keys,
139
- // - __furinError.digest when SSR caught an error,
140
- // - __furinStatus: 404 when the server rendered the catch-all not-found
141
- // (direct load to an unknown URL, emitted by renderRootNotFound) OR when
142
- // a matched loader threw notFound(). The latter still has a _match; the
143
- // former does not — so the two cases fork on _match below.
144
- const dataEl = document.getElementById("__FURIN_DATA__");
145
- const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
146
- const syncEl = document.getElementById("__FURIN_SYNC__");
147
- const syncConfig = syncEl ? JSON.parse(syncEl.textContent || "{}") : {};
148
- const syncStream = typeof syncConfig.stream === "string" ? syncConfig.stream : undefined;
149
-
150
- // ── Deferred data hydration ─────────────────────────────────────────────────
151
- // window.__FURIN_DEFERRED__ is injected by the server when a loader returns
152
- // defer(). It carries:
153
- // - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
154
- // We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
155
- // components receive a proper resolved Promise instead of the raw CrossJSON node.
156
- // Sync loader fields live exclusively in __FURIN_DATA__ (read above).
157
- interface FurinDeferredRegistry {
158
- _chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
159
- _deferredKeys: string[];
160
- _resolvers: Record<string, {
161
- promise: Promise<unknown>;
162
- reject: (reason: unknown) => void;
163
- resolve: (value: unknown) => void;
164
- }>;
165
- getPromise: (key: string) => Promise<unknown>;
166
- reject: (key: string, chunk: SerovalNode) => void;
167
- resolve: (key: string, chunk: SerovalNode) => void;
168
- }
169
- const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
170
- .__FURIN_DEFERRED__;
171
- const deferredData: Record<string, Promise<unknown>> = {};
172
- if (__deferred && __deferred._chunks) {
173
- // Patch resolve/reject so any chunks that arrive AFTER this entry has run
174
- // settle immediately. The previous version stored late chunks in _chunks
175
- // when no resolver was registered yet, but the drain loop below only runs
176
- // ONCE at hydrate time — so any chunk landing after the drain would stay
177
- // orphaned and the corresponding Await would hang forever. Eagerly creating
178
- // the resolver via getPromise() fixes the race.
179
- __deferred.resolve = (key: string, chunk: SerovalNode) => {
180
- __deferred.getPromise(key);
181
- __deferred._resolvers[key].resolve(fromCrossJSON(chunk, {}));
182
- };
183
- __deferred.reject = (key: string, chunk: SerovalNode) => {
184
- __deferred.getPromise(key);
185
- __deferred._resolvers[key].reject(fromCrossJSON(chunk, {}));
186
- };
187
- for (const key of Object.keys(__deferred._chunks)) {
188
- const entry = __deferred._chunks[key] as { a: 0 | 1; v: SerovalNode };
189
- const p = __deferred.getPromise(key) as Promise<unknown>;
190
- const resolver = __deferred._resolvers[key];
191
- const value = fromCrossJSON(entry.v, {});
192
- if (entry.a === 0) {
193
- resolver.resolve(value);
194
- } else {
195
- resolver.reject(value);
196
- }
197
- deferredData[key] = p;
198
- }
199
- for (const key of __deferred._deferredKeys ?? []) {
200
- if (!(key in deferredData)) {
201
- deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
202
- }
203
- }
204
- // Keys that have a resolver (getPromise was called by <Await>) but no
205
- // chunk yet (the late <script> hasn't arrived) still need a Promise entry
206
- // so the hydration data record is complete.
207
- for (const key of Object.keys(__deferred._resolvers ?? {})) {
208
- if (!(key in deferredData)) {
209
- deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
210
- }
211
- }
212
- }
213
- const rootEl = document.getElementById("root") as HTMLElement;
214
-
215
- // Eagerly load only the current page module for initial hydration.
216
- // All other pages are loaded on demand when the user navigates to them.
217
- // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
218
- // bundler to misidentify which chunk to reference as the entry in index.html.
219
- (async () => {
220
- let app;
221
- if (_match) {
222
- const _mod = await _match.load();
223
- const match = {
224
- ..._match,
225
- component: _mod.default.component,
226
- pageRoute: _mod.default._route,
227
- segmentBoundaries: _mod.segmentBoundaries ?? _match.segmentBoundaries,
228
- };
229
-
230
- const isNotFound = loaderData.__furinStatus === 404;
231
-
232
- app = createElement(RouterProvider, {
233
- routes,
234
- root,
235
- initialMatch: match,
236
- initialData: { ...loaderData, ...deferredData },
237
- initialDigest: loaderData.__furinError?.digest,
238
- initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
239
- } as any);
240
- } else if (loaderData.__furinStatus === 404) {
241
- // Direct load to an unknown URL. The server sent the root not-found UI
242
- // already rendered into the DOM. Mount RouterProvider with a null match
243
- // so the provider boots into its not-found branch, hydrating that exact
244
- // tree INSIDE a live RouterContext. Without this, Links in the 404 UI
245
- // (e.g. the default screen's "Go Home" button) hit the useRouter()
246
- // fallback that does a full window.location assignment — a jarring reload.
247
- // Strip the server-only signal keys before handing data to components.
248
- const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = loaderData;
249
- app = createElement(RouterProvider, {
250
- routes,
251
- root,
252
- initialMatch: null,
253
- initialData: cleanData,
254
- initialDigest: loaderData.__furinError?.digest,
255
- initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
256
- } as any);
257
- } else {
258
- // No match and no 404 signal — either the client bundle is out of sync
259
- // with the server (stale deploy) or the server returned something we
260
- // don't know how to hydrate. Bail loudly; the page stays static.
261
- log.error({ action: "hydrate_no_match", pathname });
262
- return;
263
- }
264
-
265
- if (import.meta.hot) {
266
- // Dev mode — preserve root across HMR using a window global.
267
- // window is the only object that survives Bun's module re-evaluation.
268
- // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
269
- const existingRoot = (window as any).__FURIN_ROOT__;
270
- if (existingRoot) {
271
- // Already mounted — reconciliation, NOT hydration. React Fast Refresh
272
- // patched the component in-place, now re-render with the new module.
273
- existingRoot.render(app);
274
- // The initialData embedded in the DOM is stale (from the original SSR).
275
- // Trigger a loader-data refresh so the component renders with fresh
276
- // server state, avoiding hydration mismatches after a _route.tsx edit.
277
- const hmrRefresh = (window as any).__FURIN_HMR_REFRESH__;
278
- if (hmrRefresh) {
279
- requestAnimationFrame(() => hmrRefresh());
280
- }
281
- } else if (rootEl.innerHTML.trim()) {
282
- // First load with SSR content — hydrateRoot renders on construction
283
- const root = hydrateRoot(rootEl, app);
284
- // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
285
- (window as any).__FURIN_ROOT__ = root;
286
- } else {
287
- // First load without SSR content — createRoot requires explicit .render()
288
- const root = createRoot(rootEl);
289
- root.render(app);
290
- // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
291
- (window as any).__FURIN_ROOT__ = root;
292
- }
293
- } else if (rootEl.innerHTML.trim()) {
294
- hydrateRoot(rootEl, app);
295
- } else {
296
- createRoot(rootEl).render(app);
297
- }
298
-
299
- log.info({ action: "hydrate_complete", pathname });
300
- })().catch((err: unknown) => {
301
- log.error({ action: "hydrate_failed", pathname, error: String(err) });
302
- });
303
- `;
304
- }
305
-
306
- /**
307
- * Writes _hydrate.tsx + index.html to outDir for dev (Bun HMR) mode.
308
- *
309
- * Only rewrites a file when its content has actually changed so Bun's --hot
310
- * watcher does not trigger a spurious reload on every server restart.
311
- */
312
- export function writeDevFiles(
313
- routes: ResolvedRoute[],
314
- { outDir, rootLayout, basePath, clientLogging }: BuildClientOptions,
315
- projectRoot: string
316
- ): void {
317
- if (!existsSync(outDir)) {
318
- mkdirSync(outDir, { recursive: true });
319
- }
320
-
321
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
322
- const hydratePath = join(outDir, "_hydrate.tsx");
323
- const existingHydrate = existsSync(hydratePath) ? readFileSync(hydratePath, "utf8") : "";
324
- if (hydrateCode !== existingHydrate) {
325
- writeFileSync(hydratePath, hydrateCode);
326
- }
327
-
328
- const indexHtml = generateIndexHtml();
329
- const indexPath = join(outDir, "index.html");
330
- const existingIndex = existsSync(indexPath) ? readFileSync(indexPath, "utf8") : "";
331
- if (indexHtml !== existingIndex) {
332
- writeFileSync(indexPath, indexHtml);
333
- }
334
-
335
- writeRouteTypes(routes, projectRoot);
336
-
337
- console.log(
338
- "[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)"
339
- );
340
- }
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { generateIndexHtml } from "../server/render/shell.ts";
4
+ import { mergeRouteSchemas } from "../server/router/index.ts";
5
+ import { buildRouteRegex } from "../server/router/patterns.ts";
6
+ import type { ResolvedRoute } from "../server/router/index.ts";
7
+ import { collectSearchDefaults } from "../shared/search-params.ts";
8
+ import { writeRouteTypes } from "./route-types";
9
+ import type { BuildClientOptions } from "./types";
10
+
11
+ /**
12
+ * Generates the client hydration entry.
13
+ *
14
+ * Renders into <div id="root"> (the SSR outlet element) and retains the React
15
+ * root across hot reloads via import.meta.hot.data.root so React Fast Refresh
16
+ * applies in-place instead of remounting.
17
+ *
18
+ * @param routes - Resolved routes to include in the hydration manifest.
19
+ * @param rootLayout - Absolute path to the root layout module.
20
+ * @param basePath - Optional sub-path prefix for static deployments (e.g. "/furin").
21
+ * When set, the generated code strips the prefix from `window.location.pathname`
22
+ * before matching routes, and passes `basePath` to `RouterProvider` so SPA
23
+ * navigation uses the correct physical URLs.
24
+ */
25
+ export function generateHydrateEntry(
26
+ routes: ResolvedRoute[],
27
+ rootLayout: string,
28
+ basePath: string,
29
+ clientLogging: boolean
30
+ ): string {
31
+ const getBoundaryIdent = (idents: Map<string, string>, filePath: string | undefined) => {
32
+ if (!filePath) {
33
+ return;
34
+ }
35
+ const existing = idents.get(filePath);
36
+ if (existing) {
37
+ return existing;
38
+ }
39
+ const ident = `__furin_bnd_${idents.size}`;
40
+ idents.set(filePath, ident);
41
+ return ident;
42
+ };
43
+
44
+ const routeEntries: string[] = [];
45
+
46
+ for (const route of routes) {
47
+ const resolvedPage = route.path.replace(/\\/g, "/");
48
+ const regexPattern = buildRouteRegex(route.pattern).regex.source;
49
+ const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain ?? [], "query"));
50
+ const boundaryIdents = new Map<string, string>();
51
+
52
+ // Emit one boundary literal per segment that actually carries a convention
53
+ // file — segments that only declare one of the two are emitted with the
54
+ // missing field omitted entirely (keeps the generated JS tidy).
55
+ const boundaryLiterals: string[] = [];
56
+ for (const seg of route.segmentBoundaries ?? []) {
57
+ const errorIdent = getBoundaryIdent(boundaryIdents, seg.errorPath);
58
+ const notFoundIdent = getBoundaryIdent(boundaryIdents, seg.notFoundPath);
59
+ if (!(errorIdent || notFoundIdent)) {
60
+ continue;
61
+ }
62
+ const parts = [`depth: ${seg.depth}`];
63
+ if (errorIdent) {
64
+ parts.push(`error: ${errorIdent}.default`);
65
+ }
66
+ if (notFoundIdent) {
67
+ parts.push(`notFound: ${notFoundIdent}.default`);
68
+ }
69
+ boundaryLiterals.push(`{ ${parts.join(", ")} }`);
70
+ }
71
+
72
+ const lazyImports = [
73
+ `import("${resolvedPage}")`,
74
+ ...[...boundaryIdents.keys()].map((filePath) => `import("${filePath.replace(/\\/g, "/")}")`),
75
+ ];
76
+ const loadBody =
77
+ boundaryLiterals.length > 0
78
+ ? `Promise.all([${lazyImports.join(", ")}]).then(([__furin_page, ${[
79
+ ...boundaryIdents.values(),
80
+ ].join(", ")}]) => ({ default: __furin_page.default, segmentBoundaries: [${boundaryLiterals.join(", ")}] }))`
81
+ : `import("${resolvedPage}")`;
82
+
83
+ const searchDefaultsEntry = searchDefaults
84
+ ? `, searchDefaults: ${JSON.stringify(searchDefaults)}`
85
+ : "";
86
+ routeEntries.push(
87
+ ` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`
88
+ );
89
+ }
90
+
91
+ // basePath stripping: when deployed to a sub-path (e.g. /furin), strip the
92
+ // prefix before route matching so patterns like /docs/routing still work.
93
+ const basePathLiteral = JSON.stringify(basePath);
94
+ // Strip basePath only when it matches on a path boundary (prevents "/furin" from
95
+ // matching "/furinity/foo"). The boundary holds when the pathname ends exactly
96
+ // at the prefix length OR the next character is "/".
97
+ // Trailing slashes are also stripped so "/docs/routing/" matches the route
98
+ // pattern "/docs/routing" — GitHub Pages and many static hosts append them.
99
+ const pathnameExpr = basePath
100
+ ? `(() => { const p = window.location.pathname; const b = ${basePathLiteral}; const stripped = (p.startsWith(b) && (p.length === b.length || p[b.length] === "/")) ? p.slice(b.length) || "/" : p; return stripped === "/" ? "/" : stripped.replace(/\\/+$/, ""); })()`
101
+ : `window.location.pathname.replace(/\\/+$/, "") || "/"`;
102
+
103
+ // Log drain endpoint: prepend basePath so the request goes to the correct origin path.
104
+ const logEndpoint = basePath
105
+ ? `${JSON.stringify(basePath)} + "/_furin/ingest"`
106
+ : `"/_furin/ingest"`;
107
+
108
+ // Client-side HTTP draining is opt-in (config `clientLogging`). When disabled
109
+ // we emit neither the hydrate-entry evlog imports nor initLogger, and define a
110
+ // no-op `log` shim so the hydration body's log.* calls stay valid.
111
+ const loggingImports = clientLogging
112
+ ? 'import { initLogger, log } from "evlog";\nimport { createHttpLogDrain } from "evlog/http";\n'
113
+ : "";
114
+ const loggerSetup = clientLogging
115
+ ? `initLogger({ drain: createHttpLogDrain({ drain: { endpoint: ${logEndpoint} } }) });`
116
+ : "const log = { error() {}, info() {} };";
117
+
118
+ // RouterProvider receives basePath so navigate() / Link push physical paths.
119
+ const routerProviderDefaults = `\n autoRefresh: true,\n basePath: ${basePathLiteral},\n defaultPreload: "intent",\n defaultPreloadDelay: 50,\n defaultPreloadStaleTime: 30000,\n prefetchCacheSize: 50,\n syncStream,`;
120
+
121
+ return `import { hydrateRoot, createRoot } from "react-dom/client";
122
+ import { createElement } from "react";
123
+ ${loggingImports}import { RouterProvider } from "@teyik0/furin/link";
124
+ import { fromCrossJSON } from "@teyik0/furin/link";
125
+ import type { SerovalNode } from "seroval";
126
+ import { route as root } from "${rootLayout.replace(/\\/g, "/")}";
127
+
128
+ ${loggerSetup}
129
+
130
+ const routes = [
131
+ ${routeEntries.join(",\n")}
132
+ ];
133
+
134
+ const pathname = ${pathnameExpr};
135
+ const _match = routes.find((r) => r.regex.test(pathname));
136
+
137
+ // Parse the server-embedded loader payload up front. It carries:
138
+ // - normal loader props under arbitrary keys,
139
+ // - __furinError.digest when SSR caught an error,
140
+ // - __furinStatus: 404 when the server rendered the catch-all not-found
141
+ // (direct load to an unknown URL, emitted by renderRootNotFound) OR when
142
+ // a matched loader threw notFound(). The latter still has a _match; the
143
+ // former does not — so the two cases fork on _match below.
144
+ const dataEl = document.getElementById("__FURIN_DATA__");
145
+ const loaderData = dataEl ? JSON.parse(dataEl.textContent || "{}") : {};
146
+ const syncEl = document.getElementById("__FURIN_SYNC__");
147
+ const syncConfig = syncEl ? JSON.parse(syncEl.textContent || "{}") : {};
148
+ const syncStream = typeof syncConfig.stream === "string" ? syncConfig.stream : undefined;
149
+
150
+ // ── Deferred data hydration ─────────────────────────────────────────────────
151
+ // window.__FURIN_DEFERRED__ is injected by the server when a loader returns
152
+ // defer(). It carries:
153
+ // - _chunks: raw CrossJSON chunks keyed by field name (from late <script> tags)
154
+ // We deserialise each chunk with fromCrossJSON and create a Promise so <Await>
155
+ // components receive a proper resolved Promise instead of the raw CrossJSON node.
156
+ // Sync loader fields live exclusively in __FURIN_DATA__ (read above).
157
+ interface FurinDeferredRegistry {
158
+ _chunks: Record<string, { a: 0 | 1; v: SerovalNode }>;
159
+ _deferredKeys: string[];
160
+ _resolvers: Record<string, {
161
+ promise: Promise<unknown>;
162
+ reject: (reason: unknown) => void;
163
+ resolve: (value: unknown) => void;
164
+ }>;
165
+ getPromise: (key: string) => Promise<unknown>;
166
+ reject: (key: string, chunk: SerovalNode) => void;
167
+ resolve: (key: string, chunk: SerovalNode) => void;
168
+ }
169
+ const __deferred = (window as unknown as { __FURIN_DEFERRED__?: FurinDeferredRegistry })
170
+ .__FURIN_DEFERRED__;
171
+ const deferredData: Record<string, Promise<unknown>> = {};
172
+ if (__deferred && __deferred._chunks) {
173
+ // Patch resolve/reject so any chunks that arrive AFTER this entry has run
174
+ // settle immediately. The previous version stored late chunks in _chunks
175
+ // when no resolver was registered yet, but the drain loop below only runs
176
+ // ONCE at hydrate time — so any chunk landing after the drain would stay
177
+ // orphaned and the corresponding Await would hang forever. Eagerly creating
178
+ // the resolver via getPromise() fixes the race.
179
+ __deferred.resolve = (key: string, chunk: SerovalNode) => {
180
+ __deferred.getPromise(key);
181
+ __deferred._resolvers[key].resolve(fromCrossJSON(chunk, {}));
182
+ };
183
+ __deferred.reject = (key: string, chunk: SerovalNode) => {
184
+ __deferred.getPromise(key);
185
+ __deferred._resolvers[key].reject(fromCrossJSON(chunk, {}));
186
+ };
187
+ for (const key of Object.keys(__deferred._chunks)) {
188
+ const entry = __deferred._chunks[key] as { a: 0 | 1; v: SerovalNode };
189
+ const p = __deferred.getPromise(key) as Promise<unknown>;
190
+ const resolver = __deferred._resolvers[key];
191
+ const value = fromCrossJSON(entry.v, {});
192
+ if (entry.a === 0) {
193
+ resolver.resolve(value);
194
+ } else {
195
+ resolver.reject(value);
196
+ }
197
+ deferredData[key] = p;
198
+ }
199
+ for (const key of __deferred._deferredKeys ?? []) {
200
+ if (!(key in deferredData)) {
201
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
202
+ }
203
+ }
204
+ // Keys that have a resolver (getPromise was called by <Await>) but no
205
+ // chunk yet (the late <script> hasn't arrived) still need a Promise entry
206
+ // so the hydration data record is complete.
207
+ for (const key of Object.keys(__deferred._resolvers ?? {})) {
208
+ if (!(key in deferredData)) {
209
+ deferredData[key] = __deferred.getPromise(key) as Promise<unknown>;
210
+ }
211
+ }
212
+ }
213
+ const rootEl = document.getElementById("root") as HTMLElement;
214
+
215
+ // Eagerly load only the current page module for initial hydration.
216
+ // All other pages are loaded on demand when the user navigates to them.
217
+ // Wrapped in an async IIFE to avoid top-level await, which causes Bun's HTML
218
+ // bundler to misidentify which chunk to reference as the entry in index.html.
219
+ (async () => {
220
+ let app;
221
+ if (_match) {
222
+ const _mod = await _match.load();
223
+ const match = {
224
+ ..._match,
225
+ component: _mod.default.component,
226
+ pageRoute: _mod.default._route,
227
+ segmentBoundaries: _mod.segmentBoundaries ?? _match.segmentBoundaries,
228
+ };
229
+
230
+ const isNotFound = loaderData.__furinStatus === 404;
231
+
232
+ app = createElement(RouterProvider, {
233
+ routes,
234
+ root,
235
+ initialMatch: match,
236
+ initialData: { ...loaderData, ...deferredData },
237
+ initialDigest: loaderData.__furinError?.digest,
238
+ initialNotFound: isNotFound ? (loaderData.__furinNotFound ?? loaderData) : undefined,${routerProviderDefaults}
239
+ } as any);
240
+ } else if (loaderData.__furinStatus === 404) {
241
+ // Direct load to an unknown URL. The server sent the root not-found UI
242
+ // already rendered into the DOM. Mount RouterProvider with a null match
243
+ // so the provider boots into its not-found branch, hydrating that exact
244
+ // tree INSIDE a live RouterContext. Without this, Links in the 404 UI
245
+ // (e.g. the default screen's "Go Home" button) hit the useRouter()
246
+ // fallback that does a full window.location assignment — a jarring reload.
247
+ // Strip the server-only signal keys before handing data to components.
248
+ const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = loaderData;
249
+ app = createElement(RouterProvider, {
250
+ routes,
251
+ root,
252
+ initialMatch: null,
253
+ initialData: cleanData,
254
+ initialDigest: loaderData.__furinError?.digest,
255
+ initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
256
+ } as any);
257
+ } else {
258
+ // No match and no 404 signal — either the client bundle is out of sync
259
+ // with the server (stale deploy) or the server returned something we
260
+ // don't know how to hydrate. Bail loudly; the page stays static.
261
+ log.error({ action: "hydrate_no_match", pathname });
262
+ return;
263
+ }
264
+
265
+ if (import.meta.hot) {
266
+ // Dev mode — preserve root across HMR using a window global.
267
+ // window is the only object that survives Bun's module re-evaluation.
268
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
269
+ const existingRoot = (window as any).__FURIN_ROOT__;
270
+ if (existingRoot) {
271
+ // Already mounted — reconciliation, NOT hydration. React Fast Refresh
272
+ // patched the component in-place, now re-render with the new module.
273
+ existingRoot.render(app);
274
+ // The initialData embedded in the DOM is stale (from the original SSR).
275
+ // Trigger a loader-data refresh so the component renders with fresh
276
+ // server state, avoiding hydration mismatches after a _route.tsx edit.
277
+ const hmrRefresh = (window as any).__FURIN_HMR_REFRESH__;
278
+ if (hmrRefresh) {
279
+ requestAnimationFrame(() => hmrRefresh());
280
+ }
281
+ } else if (rootEl.innerHTML.trim()) {
282
+ // First load with SSR content — hydrateRoot renders on construction
283
+ const root = hydrateRoot(rootEl, app);
284
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
285
+ (window as any).__FURIN_ROOT__ = root;
286
+ } else {
287
+ // First load without SSR content — createRoot requires explicit .render()
288
+ const root = createRoot(rootEl);
289
+ root.render(app);
290
+ // biome-ignore lint/suspicious/noExplicitAny: dev-only HMR global
291
+ (window as any).__FURIN_ROOT__ = root;
292
+ }
293
+ } else if (rootEl.innerHTML.trim()) {
294
+ hydrateRoot(rootEl, app);
295
+ } else {
296
+ createRoot(rootEl).render(app);
297
+ }
298
+
299
+ log.info({ action: "hydrate_complete", pathname });
300
+ })().catch((err: unknown) => {
301
+ log.error({ action: "hydrate_failed", pathname, error: String(err) });
302
+ });
303
+ `;
304
+ }
305
+
306
+ /**
307
+ * Writes _hydrate.tsx + index.html to outDir for dev (Bun HMR) mode.
308
+ *
309
+ * Only rewrites a file when its content has actually changed so Bun's --hot
310
+ * watcher does not trigger a spurious reload on every server restart.
311
+ */
312
+ export function writeDevFiles(
313
+ routes: ResolvedRoute[],
314
+ { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }: BuildClientOptions,
315
+ projectRoot: string
316
+ ): void {
317
+ if (!existsSync(outDir)) {
318
+ mkdirSync(outDir, { recursive: true });
319
+ }
320
+
321
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
322
+ const hydratePath = join(outDir, "_hydrate.tsx");
323
+ const existingHydrate = existsSync(hydratePath) ? readFileSync(hydratePath, "utf8") : "";
324
+ if (hydrateCode !== existingHydrate) {
325
+ writeFileSync(hydratePath, hydrateCode);
326
+ }
327
+
328
+ const indexHtml = generateIndexHtml();
329
+ const indexPath = join(outDir, "index.html");
330
+ const existingIndex = existsSync(indexPath) ? readFileSync(indexPath, "utf8") : "";
331
+ if (indexHtml !== existingIndex) {
332
+ writeFileSync(indexPath, indexHtml);
333
+ }
334
+
335
+ if (!skipRouteTypes) {
336
+ writeRouteTypes(routes, projectRoot);
337
+ }
338
+
339
+ console.log(
340
+ "[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)"
341
+ );
342
+ }