@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,384 +1,384 @@
1
- import { type AnyElysia, type Context, Elysia, t } from "elysia";
2
- import type { AnySchema } from "elysia/types";
3
- import { toCrossJSON, toCrossJSONAsync } from "seroval";
4
- import { computeErrorDigest } from "../../shared/digest.ts";
5
- import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
6
- import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
7
- import { useLogger } from "../context-logger.ts";
8
- import { injectSyncRuntimeScript, resolvePath } from "../render/assemble.ts";
9
- import {
10
- handleISR,
11
- prerenderSSG,
12
- renderSSR,
13
- runLoaders,
14
- serializeDeferredRejection,
15
- } from "../render/index.ts";
16
- import { extractTitle } from "../render/shell.ts";
17
- import { IS_DEV } from "../runtime-env.ts";
18
- import { handleDevRequest } from "./hmr.ts";
19
- import { buildRouteMatcher } from "./patterns.ts";
20
- import {
21
- applySchemaDefaults,
22
- mergeRouteSchemas,
23
- parseDataEndpointPath,
24
- parseRouteQuery,
25
- } from "./schemas.ts";
26
- import type { ResolvedRoute, RootLayout } from "./types.ts";
27
-
28
- type SyntheticDataContext = Omit<Context, "params" | "query"> & {
29
- params: Record<string, string>;
30
- query: SearchParamsInput;
31
- };
32
-
33
- /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
34
- async function handleSSGRequest(
35
- route: ResolvedRoute,
36
- ctx: Context,
37
- root: RootLayout,
38
- buildId: string,
39
- searchRoutes: SearchRouteMetadata[] | undefined
40
- ): Promise<unknown> {
41
- const origin = new URL(ctx.request.url).origin;
42
- const entry = await prerenderSSG(route, ctx.params, root, origin, undefined, searchRoutes);
43
-
44
- // Loader issued a redirect — forward it directly to the client.
45
- if (entry instanceof Response) {
46
- return entry;
47
- }
48
-
49
- const resolvedPath = resolvePath(route.pattern, ctx.params ?? {});
50
-
51
- // ETag: "buildId:cachedAt" — unique per render cycle, changes after revalidatePath
52
- const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
53
- if (etag && ctx.request.headers.get("if-none-match") === etag) {
54
- ctx.set.status = 304;
55
- return;
56
- }
57
-
58
- ctx.set.headers["content-type"] = "text/html; charset=utf-8";
59
- // Browser: max-age=0 + must-revalidate → always validates via ETag (304 = free)
60
- // CDN: s-maxage=31536000 → cache for 1 year, purge via revalidatePath + purger
61
- ctx.set.headers["cache-control"] = "public, max-age=0, must-revalidate, s-maxage=31536000";
62
- if (etag) {
63
- ctx.set.headers.etag = etag;
64
- }
65
- ctx.set.headers["cache-tag"] = resolvedPath;
66
- return injectSyncRuntimeScript(entry.html);
67
- }
68
-
69
- export function createRoutePlugin(
70
- route: ResolvedRoute,
71
- root: RootLayout,
72
- buildId?: string,
73
- searchRoutes?: SearchRouteMetadata[]
74
- ): AnyElysia {
75
- const resolvedBuildId = buildId ?? "";
76
- const { pattern, routeChain } = route;
77
-
78
- const allParams = mergeRouteSchemas(routeChain, "params");
79
- const allQuery = mergeRouteSchemas(routeChain, "query");
80
-
81
- // Guard and handler MUST live in the same Elysia scope so that validation
82
- // (including default-filling) applies to the route handler's ctx.query.
83
- const plugin = new Elysia();
84
-
85
- if (allParams || allQuery) {
86
- plugin.guard({
87
- params: allParams as AnySchema,
88
- query: allQuery as AnySchema,
89
- });
90
- }
91
-
92
- plugin.get(pattern, (ctx) => {
93
- // Dev mode: re-imports page + layouts on every request via the
94
- // ?furin-server cache-buster, then dispatches into one of:
95
- // - renderDevISRWithLoaderCache (mode === "isr")
96
- // - renderDevSSGWithLoaderCache (mode === "ssg")
97
- // - renderSSR (otherwise)
98
- //
99
- // Only the LOADER OUTPUT is cached in dev — HTML is always re-assembled
100
- // fresh so the response always embeds the latest Bun client chunk URL.
101
- // This avoids the "infinite reload loop" footgun where a cached ISR/SSG
102
- // HTML response held an OLD chunk URL after Bun rebundled. The dev
103
- // cache is invalidated source-aware via `isDevLoaderCacheValid`
104
- // (mtime-checked dependency walk on every read).
105
- if (IS_DEV) {
106
- return handleDevRequest(route, ctx, root, searchRoutes);
107
- }
108
-
109
- if (route.mode === "ssg") {
110
- return handleSSGRequest(route, ctx, root, resolvedBuildId, searchRoutes);
111
- }
112
-
113
- if (route.mode === "isr") {
114
- ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
115
- return handleISR(route, ctx, root, resolvedBuildId, searchRoutes);
116
- }
117
-
118
- return renderSSR(route, ctx, root, undefined, searchRoutes);
119
- });
120
-
121
- return plugin;
122
- }
123
-
124
- /**
125
- * Elysia plugin that handles `GET /_furin/data?path=<logicalHref>`.
126
- *
127
- * Returns an NDJSON stream (one-line, v1) produced by `toCrossJSONAsync`:
128
- * Line 0 — CrossJSON serialisation of `{ ...syncData, ...deferredPromises }`
129
- *
130
- * The `deferredPromises` values are awaited by `toCrossJSONAsync` before
131
- * serialising, so the client receives all data resolved in one round-trip.
132
- * SPA navigation calls this endpoint via `parseDeferredNdjson` in
133
- * `router-provider.tsx`.
134
- *
135
- * Special fields emitted alongside data:
136
- * - `__furinStatus: 404` — when the loader called `notFound()`
137
- * - `__furinNotFound` — not-found payload
138
- * - `__furinRedirect` — logical path after a server-side redirect
139
- */
140
- export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
141
- const plugin = new Elysia();
142
- const matchRoute = buildRouteMatcher(routes);
143
-
144
- plugin.get(
145
- "/_furin/data",
146
- async (ctx) => {
147
- const rawPath = ctx.query.path;
148
- if (!rawPath || typeof rawPath !== "string") {
149
- return new Response("Missing required query param: path", { status: 400 });
150
- }
151
-
152
- const parsed = parseDataEndpointPath(rawPath);
153
- if (!parsed) {
154
- return new Response("Invalid path", { status: 400 });
155
- }
156
- const { url, pathname } = parsed;
157
-
158
- // Rewrite the request-scoped wide event so logs / drains report the
159
- // *logical* path the user navigated to (e.g. "/board/123/card/456")
160
- // instead of the technical "/_furin/data" transport URL. We set this
161
- // before the route-match check so 404s also surface the attempted path
162
- // — otherwise monitoring just sees "GET /_furin/data 404" with no clue.
163
- const wideEventLog = useLogger();
164
- wideEventLog.set({ path: rawPath });
165
-
166
- // Precompiled at plugin creation: route regexes are built once, sorted
167
- // most-specific first, then the hot path only executes regex matches.
168
- const matched = matchRoute(pathname);
169
-
170
- if (!matched) {
171
- return new Response("Route not found", { status: 404 });
172
- }
173
-
174
- // Now that we know the matched pattern, add it as a stable aggregation
175
- // key for drains (e.g. "p99 latency by route").
176
- wideEventLog.set({ routePattern: matched.route.pattern });
177
-
178
- // Build a synthetic Elysia-compatible context for the matched route.
179
- // Loaders receive request, params, query, set, headers, and cookie.
180
- // Build the synthetic URL from the parsed `pathname + search` only —
181
- // never from `rawPath` directly — so an attacker cannot smuggle a
182
- // foreign origin into `syntheticRequest.url`.
183
- const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
184
- const syntheticSet = { headers: {} as Record<string, string>, status: 200 as number };
185
- const syntheticCtx: SyntheticDataContext = {
186
- request: syntheticRequest,
187
- params: matched.params,
188
- query: Object.fromEntries(url.searchParams),
189
- set: syntheticSet,
190
- headers: ctx.headers,
191
- cookie: ctx.cookie,
192
- path: pathname,
193
- // Loader-emitted redirects flow through `runLoaders` → `result.type
194
- // === "redirect"` and are converted to NDJSON below. The Response we
195
- // return here only has to be detectable by that pipeline.
196
- redirect: (location: string, status?: number) =>
197
- new Response(null, { status: status ?? 302, headers: { location } }),
198
- // Synthetic `status` helper: numeric codes only. Callers that reach
199
- // this endpoint never dispatch a string-keyed status; rejecting them
200
- // is safer than coercing via `Number(code)` and silently producing
201
- // `NaN`.
202
- status: (code: number) => new Response(null, { status: code }),
203
- } as unknown as SyntheticDataContext;
204
-
205
- // Normalize params and query through the same merged schemas used by
206
- // createRoutePlugin so loaders see identical typed/defaulted inputs.
207
- const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
208
- const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
209
- const parsedQuery = await parseRouteQuery(url, mergedQuery);
210
- if (!parsedQuery.ok) {
211
- return Response.json(
212
- { errors: parsedQuery.errors, message: "Invalid query", type: "validation" },
213
- { status: 422 }
214
- );
215
- }
216
- syntheticCtx.params = applySchemaDefaults(
217
- mergedParams as Record<string, unknown> | undefined,
218
- syntheticCtx.params as Record<string, unknown>
219
- ) as Record<string, string>;
220
- syntheticCtx.query = parsedQuery.query as SearchParamsInput;
221
-
222
- const result = await runLoaders(matched.route, syntheticCtx as unknown as Context);
223
-
224
- // Keep the auto-invalidate registry in sync with whatever path was just
225
- // served, so subsequent `revalidateTag(...)` calls (e.g. from a mutation
226
- // afterHandle) can still find this URL by tag. Without this, a SPA-only
227
- // navigation path (which never goes through the full-HTML render that
228
- // also registers tags) would silently fall off the registry — the first
229
- // mutation invalidates and unregisters via the cache `onDelete` hook,
230
- // the next SPA fetch re-loads but does not re-register, and from then
231
- // on `revalidateTag` finds no path to invalidate.
232
- if (result.type === "data") {
233
- autoInvalidateRegistry.registerLoaderTags(pathname, matched.route.tags);
234
- }
235
-
236
- if (result.type === "redirect") {
237
- // Encode the redirect target as a special field for the client to follow
238
- const redirectUrl = new URL(
239
- result.response.headers.get("location") ?? "/",
240
- ctx.request.url
241
- );
242
- const serialized = await toCrossJSONAsync({
243
- __furinRedirect: redirectUrl.pathname + redirectUrl.search,
244
- });
245
- return new Response(`${JSON.stringify(serialized)}\n`, {
246
- headers: { "content-type": "application/x-ndjson" },
247
- });
248
- }
249
-
250
- if (result.type === "not-found") {
251
- const serialized = await toCrossJSONAsync({
252
- __furinStatus: 404,
253
- __furinNotFound: { message: result.error.message, data: result.error.data },
254
- });
255
- return new Response(`${JSON.stringify(serialized)}\n`, {
256
- status: 200,
257
- headers: { "content-type": "application/x-ndjson" },
258
- });
259
- }
260
-
261
- if (result.type === "error") {
262
- // Compute the digest server-side ONCE so:
263
- // 1. The HTTP response body carries it (client error UI displays the
264
- // same id the server logs).
265
- // 2. The server-log line below uses the SAME digest a user would see
266
- // on screen, enabling support correlation.
267
- // Recomputing client-side from a synthetic message + stack would yield
268
- // a different hash — see boundaries.tsx for the digest precedence.
269
- const digest = computeErrorDigest(result.error);
270
- const serialized = await toCrossJSONAsync({
271
- __furinError: {
272
- digest,
273
- message: result.message,
274
- status: result.status,
275
- },
276
- });
277
- return new Response(`${JSON.stringify(serialized)}\n`, {
278
- status: result.status,
279
- headers: { "content-type": "application/x-ndjson" },
280
- });
281
- }
282
-
283
- // Resolve the page title server-side: head() never runs in the browser,
284
- // so SPA navigation depends on the endpoint shipping it as __furinTitle.
285
- const syncDataWithTitle = withResolvedTitle(matched.route, result.syncData);
286
-
287
- if (result.deferredPromises) {
288
- return new Response(
289
- createDeferredNdjsonStream(syncDataWithTitle, result.deferredPromises),
290
- {
291
- // Loader headers first so custom headers survive; the NDJSON
292
- // content-type is framework-owned and must win — a loader cannot be
293
- // allowed to mislabel the data-endpoint payload.
294
- headers: {
295
- ...result.headers,
296
- "content-type": "application/x-ndjson",
297
- },
298
- }
299
- );
300
- }
301
-
302
- // No deferred fields: emit the single-line payload used by the legacy path.
303
- const serialized = await toCrossJSONAsync(syncDataWithTitle);
304
- return new Response(`${JSON.stringify(serialized)}\n`, {
305
- headers: {
306
- ...result.headers,
307
- "content-type": "application/x-ndjson",
308
- },
309
- });
310
- },
311
- {
312
- query: t.Object({ path: t.Optional(t.String()) }),
313
- }
314
- );
315
-
316
- return plugin;
317
- }
318
-
319
- /**
320
- * Runs the matched page's `head()` against the resolved sync data and, when it
321
- * yields a title, returns a copy of `syncData` carrying the reserved
322
- * `__furinTitle` field. `head()` never executes in the browser, so this is the
323
- * only channel through which SPA navigation can learn the new document title.
324
- *
325
- * Deferred fields are absent from `syncData` (they are still Promises), so a
326
- * `head()` that reads one sees `undefined` — titles should be derived from
327
- * synchronous loader data. A throwing `head()` is swallowed: a missing title
328
- * must never break the data response.
329
- */
330
- function withResolvedTitle(
331
- route: ResolvedRoute,
332
- syncData: Record<string, unknown>
333
- ): Record<string, unknown> {
334
- const head = route.page.head;
335
- if (!head) {
336
- return syncData;
337
- }
338
- let title: string | undefined;
339
- try {
340
- title = extractTitle(head(syncData).meta);
341
- } catch {
342
- return syncData;
343
- }
344
- if (title === undefined) {
345
- return syncData;
346
- }
347
- return { ...syncData, __furinTitle: title };
348
- }
349
-
350
- function createDeferredNdjsonStream(
351
- syncData: Record<string, unknown>,
352
- deferredPromises: Record<string, Promise<unknown>>
353
- ): ReadableStream<Uint8Array> {
354
- const enc = new TextEncoder();
355
- const entries = Object.entries(deferredPromises);
356
-
357
- return new ReadableStream<Uint8Array>({
358
- async start(controller) {
359
- const initial = toCrossJSON({
360
- ...syncData,
361
- __furinDeferredKeys: entries.map(([key]) => key),
362
- });
363
- controller.enqueue(enc.encode(`${JSON.stringify(initial)}\n`));
364
-
365
- await Promise.all(
366
- entries.map(async ([key, promise]) => {
367
- try {
368
- const value = await promise;
369
- controller.enqueue(
370
- enc.encode(
371
- `${JSON.stringify({ key, action: "resolve", value: toCrossJSON(value) })}\n`
372
- )
373
- );
374
- } catch (err) {
375
- const normalized = await serializeDeferredRejection(err);
376
- const value = toCrossJSON(normalized);
377
- controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "reject", value })}\n`));
378
- }
379
- })
380
- );
381
- controller.close();
382
- },
383
- });
384
- }
1
+ import { type AnyElysia, type Context, Elysia, t } from "elysia";
2
+ import type { AnySchema } from "elysia/types";
3
+ import { toCrossJSON, toCrossJSONAsync } from "seroval";
4
+ import { computeErrorDigest } from "../../shared/digest.ts";
5
+ import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
6
+ import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
7
+ import { useLogger } from "../context-logger.ts";
8
+ import { injectSyncRuntimeScript, resolvePath } from "../render/assemble.ts";
9
+ import {
10
+ handleISR,
11
+ prerenderSSG,
12
+ renderSSR,
13
+ runLoaders,
14
+ serializeDeferredRejection,
15
+ } from "../render/index.ts";
16
+ import { extractTitle } from "../render/shell.ts";
17
+ import { IS_DEV } from "../runtime-env.ts";
18
+ import { handleDevRequest } from "./hmr.ts";
19
+ import { buildRouteMatcher } from "./patterns.ts";
20
+ import {
21
+ applySchemaDefaults,
22
+ mergeRouteSchemas,
23
+ parseDataEndpointPath,
24
+ parseRouteQuery,
25
+ } from "./schemas.ts";
26
+ import type { ResolvedRoute, RootLayout } from "./types.ts";
27
+
28
+ type SyntheticDataContext = Omit<Context, "params" | "query"> & {
29
+ params: Record<string, string>;
30
+ query: SearchParamsInput;
31
+ };
32
+
33
+ /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
34
+ async function handleSSGRequest(
35
+ route: ResolvedRoute,
36
+ ctx: Context,
37
+ root: RootLayout,
38
+ buildId: string,
39
+ searchRoutes: SearchRouteMetadata[] | undefined
40
+ ): Promise<unknown> {
41
+ const origin = new URL(ctx.request.url).origin;
42
+ const entry = await prerenderSSG(route, ctx.params, root, origin, undefined, searchRoutes);
43
+
44
+ // Loader issued a redirect — forward it directly to the client.
45
+ if (entry instanceof Response) {
46
+ return entry;
47
+ }
48
+
49
+ const resolvedPath = resolvePath(route.pattern, ctx.params ?? {});
50
+
51
+ // ETag: "buildId:cachedAt" — unique per render cycle, changes after revalidatePath
52
+ const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
53
+ if (etag && ctx.request.headers.get("if-none-match") === etag) {
54
+ ctx.set.status = 304;
55
+ return;
56
+ }
57
+
58
+ ctx.set.headers["content-type"] = "text/html; charset=utf-8";
59
+ // Browser: max-age=0 + must-revalidate → always validates via ETag (304 = free)
60
+ // CDN: s-maxage=31536000 → cache for 1 year, purge via revalidatePath + purger
61
+ ctx.set.headers["cache-control"] = "public, max-age=0, must-revalidate, s-maxage=31536000";
62
+ if (etag) {
63
+ ctx.set.headers.etag = etag;
64
+ }
65
+ ctx.set.headers["cache-tag"] = resolvedPath;
66
+ return injectSyncRuntimeScript(entry.html);
67
+ }
68
+
69
+ export function createRoutePlugin(
70
+ route: ResolvedRoute,
71
+ root: RootLayout,
72
+ buildId?: string,
73
+ searchRoutes?: SearchRouteMetadata[]
74
+ ): AnyElysia {
75
+ const resolvedBuildId = buildId ?? "";
76
+ const { pattern, routeChain } = route;
77
+
78
+ const allParams = mergeRouteSchemas(routeChain, "params");
79
+ const allQuery = mergeRouteSchemas(routeChain, "query");
80
+
81
+ // Guard and handler MUST live in the same Elysia scope so that validation
82
+ // (including default-filling) applies to the route handler's ctx.query.
83
+ const plugin = new Elysia();
84
+
85
+ if (allParams || allQuery) {
86
+ plugin.guard({
87
+ params: allParams as AnySchema,
88
+ query: allQuery as AnySchema,
89
+ });
90
+ }
91
+
92
+ plugin.get(pattern, (ctx) => {
93
+ // Dev mode: re-imports page + layouts on every request via the
94
+ // ?furin-server cache-buster, then dispatches into one of:
95
+ // - renderDevISRWithLoaderCache (mode === "isr")
96
+ // - renderDevSSGWithLoaderCache (mode === "ssg")
97
+ // - renderSSR (otherwise)
98
+ //
99
+ // Only the LOADER OUTPUT is cached in dev — HTML is always re-assembled
100
+ // fresh so the response always embeds the latest Bun client chunk URL.
101
+ // This avoids the "infinite reload loop" footgun where a cached ISR/SSG
102
+ // HTML response held an OLD chunk URL after Bun rebundled. The dev
103
+ // cache is invalidated source-aware via `isDevLoaderCacheValid`
104
+ // (mtime-checked dependency walk on every read).
105
+ if (IS_DEV) {
106
+ return handleDevRequest(route, ctx, root, searchRoutes);
107
+ }
108
+
109
+ if (route.mode === "ssg") {
110
+ return handleSSGRequest(route, ctx, root, resolvedBuildId, searchRoutes);
111
+ }
112
+
113
+ if (route.mode === "isr") {
114
+ ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
115
+ return handleISR(route, ctx, root, resolvedBuildId, searchRoutes);
116
+ }
117
+
118
+ return renderSSR(route, ctx, root, undefined, searchRoutes);
119
+ });
120
+
121
+ return plugin;
122
+ }
123
+
124
+ /**
125
+ * Elysia plugin that handles `GET /_furin/data?path=<logicalHref>`.
126
+ *
127
+ * Returns an NDJSON stream (one-line, v1) produced by `toCrossJSONAsync`:
128
+ * Line 0 — CrossJSON serialisation of `{ ...syncData, ...deferredPromises }`
129
+ *
130
+ * The `deferredPromises` values are awaited by `toCrossJSONAsync` before
131
+ * serialising, so the client receives all data resolved in one round-trip.
132
+ * SPA navigation calls this endpoint via `parseDeferredNdjson` in
133
+ * `router-provider.tsx`.
134
+ *
135
+ * Special fields emitted alongside data:
136
+ * - `__furinStatus: 404` — when the loader called `notFound()`
137
+ * - `__furinNotFound` — not-found payload
138
+ * - `__furinRedirect` — logical path after a server-side redirect
139
+ */
140
+ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
141
+ const plugin = new Elysia();
142
+ const matchRoute = buildRouteMatcher(routes);
143
+
144
+ plugin.get(
145
+ "/_furin/data",
146
+ async (ctx) => {
147
+ const rawPath = ctx.query.path;
148
+ if (!rawPath || typeof rawPath !== "string") {
149
+ return new Response("Missing required query param: path", { status: 400 });
150
+ }
151
+
152
+ const parsed = parseDataEndpointPath(rawPath);
153
+ if (!parsed) {
154
+ return new Response("Invalid path", { status: 400 });
155
+ }
156
+ const { url, pathname } = parsed;
157
+
158
+ // Rewrite the request-scoped wide event so logs / drains report the
159
+ // *logical* path the user navigated to (e.g. "/board/123/card/456")
160
+ // instead of the technical "/_furin/data" transport URL. We set this
161
+ // before the route-match check so 404s also surface the attempted path
162
+ // — otherwise monitoring just sees "GET /_furin/data 404" with no clue.
163
+ const wideEventLog = useLogger();
164
+ wideEventLog.set({ path: rawPath });
165
+
166
+ // Precompiled at plugin creation: route regexes are built once, sorted
167
+ // most-specific first, then the hot path only executes regex matches.
168
+ const matched = matchRoute(pathname);
169
+
170
+ if (!matched) {
171
+ return new Response("Route not found", { status: 404 });
172
+ }
173
+
174
+ // Now that we know the matched pattern, add it as a stable aggregation
175
+ // key for drains (e.g. "p99 latency by route").
176
+ wideEventLog.set({ routePattern: matched.route.pattern });
177
+
178
+ // Build a synthetic Elysia-compatible context for the matched route.
179
+ // Loaders receive request, params, query, set, headers, and cookie.
180
+ // Build the synthetic URL from the parsed `pathname + search` only —
181
+ // never from `rawPath` directly — so an attacker cannot smuggle a
182
+ // foreign origin into `syntheticRequest.url`.
183
+ const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
184
+ const syntheticSet = { headers: {} as Record<string, string>, status: 200 as number };
185
+ const syntheticCtx: SyntheticDataContext = {
186
+ request: syntheticRequest,
187
+ params: matched.params,
188
+ query: Object.fromEntries(url.searchParams),
189
+ set: syntheticSet,
190
+ headers: ctx.headers,
191
+ cookie: ctx.cookie,
192
+ path: pathname,
193
+ // Loader-emitted redirects flow through `runLoaders` → `result.type
194
+ // === "redirect"` and are converted to NDJSON below. The Response we
195
+ // return here only has to be detectable by that pipeline.
196
+ redirect: (location: string, status?: number) =>
197
+ new Response(null, { status: status ?? 302, headers: { location } }),
198
+ // Synthetic `status` helper: numeric codes only. Callers that reach
199
+ // this endpoint never dispatch a string-keyed status; rejecting them
200
+ // is safer than coercing via `Number(code)` and silently producing
201
+ // `NaN`.
202
+ status: (code: number) => new Response(null, { status: code }),
203
+ } as unknown as SyntheticDataContext;
204
+
205
+ // Normalize params and query through the same merged schemas used by
206
+ // createRoutePlugin so loaders see identical typed/defaulted inputs.
207
+ const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
208
+ const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
209
+ const parsedQuery = await parseRouteQuery(url, mergedQuery);
210
+ if (!parsedQuery.ok) {
211
+ return Response.json(
212
+ { errors: parsedQuery.errors, message: "Invalid query", type: "validation" },
213
+ { status: 422 }
214
+ );
215
+ }
216
+ syntheticCtx.params = applySchemaDefaults(
217
+ mergedParams as Record<string, unknown> | undefined,
218
+ syntheticCtx.params as Record<string, unknown>
219
+ ) as Record<string, string>;
220
+ syntheticCtx.query = parsedQuery.query as SearchParamsInput;
221
+
222
+ const result = await runLoaders(matched.route, syntheticCtx as unknown as Context);
223
+
224
+ // Keep the auto-invalidate registry in sync with whatever path was just
225
+ // served, so subsequent `revalidateTag(...)` calls (e.g. from a mutation
226
+ // afterHandle) can still find this URL by tag. Without this, a SPA-only
227
+ // navigation path (which never goes through the full-HTML render that
228
+ // also registers tags) would silently fall off the registry — the first
229
+ // mutation invalidates and unregisters via the cache `onDelete` hook,
230
+ // the next SPA fetch re-loads but does not re-register, and from then
231
+ // on `revalidateTag` finds no path to invalidate.
232
+ if (result.type === "data") {
233
+ autoInvalidateRegistry.registerLoaderTags(pathname, matched.route.tags);
234
+ }
235
+
236
+ if (result.type === "redirect") {
237
+ // Encode the redirect target as a special field for the client to follow
238
+ const redirectUrl = new URL(
239
+ result.response.headers.get("location") ?? "/",
240
+ ctx.request.url
241
+ );
242
+ const serialized = await toCrossJSONAsync({
243
+ __furinRedirect: redirectUrl.pathname + redirectUrl.search,
244
+ });
245
+ return new Response(`${JSON.stringify(serialized)}\n`, {
246
+ headers: { "content-type": "application/x-ndjson" },
247
+ });
248
+ }
249
+
250
+ if (result.type === "not-found") {
251
+ const serialized = await toCrossJSONAsync({
252
+ __furinStatus: 404,
253
+ __furinNotFound: { message: result.error.message, data: result.error.data },
254
+ });
255
+ return new Response(`${JSON.stringify(serialized)}\n`, {
256
+ status: 200,
257
+ headers: { "content-type": "application/x-ndjson" },
258
+ });
259
+ }
260
+
261
+ if (result.type === "error") {
262
+ // Compute the digest server-side ONCE so:
263
+ // 1. The HTTP response body carries it (client error UI displays the
264
+ // same id the server logs).
265
+ // 2. The server-log line below uses the SAME digest a user would see
266
+ // on screen, enabling support correlation.
267
+ // Recomputing client-side from a synthetic message + stack would yield
268
+ // a different hash — see boundaries.tsx for the digest precedence.
269
+ const digest = computeErrorDigest(result.error);
270
+ const serialized = await toCrossJSONAsync({
271
+ __furinError: {
272
+ digest,
273
+ message: result.message,
274
+ status: result.status,
275
+ },
276
+ });
277
+ return new Response(`${JSON.stringify(serialized)}\n`, {
278
+ status: result.status,
279
+ headers: { "content-type": "application/x-ndjson" },
280
+ });
281
+ }
282
+
283
+ // Resolve the page title server-side: head() never runs in the browser,
284
+ // so SPA navigation depends on the endpoint shipping it as __furinTitle.
285
+ const syncDataWithTitle = withResolvedTitle(matched.route, result.syncData);
286
+
287
+ if (result.deferredPromises) {
288
+ return new Response(
289
+ createDeferredNdjsonStream(syncDataWithTitle, result.deferredPromises),
290
+ {
291
+ // Loader headers first so custom headers survive; the NDJSON
292
+ // content-type is framework-owned and must win — a loader cannot be
293
+ // allowed to mislabel the data-endpoint payload.
294
+ headers: {
295
+ ...result.headers,
296
+ "content-type": "application/x-ndjson",
297
+ },
298
+ }
299
+ );
300
+ }
301
+
302
+ // No deferred fields: emit the single-line payload used by the legacy path.
303
+ const serialized = await toCrossJSONAsync(syncDataWithTitle);
304
+ return new Response(`${JSON.stringify(serialized)}\n`, {
305
+ headers: {
306
+ ...result.headers,
307
+ "content-type": "application/x-ndjson",
308
+ },
309
+ });
310
+ },
311
+ {
312
+ query: t.Object({ path: t.Optional(t.String()) }),
313
+ }
314
+ );
315
+
316
+ return plugin;
317
+ }
318
+
319
+ /**
320
+ * Runs the matched page's `head()` against the resolved sync data and, when it
321
+ * yields a title, returns a copy of `syncData` carrying the reserved
322
+ * `__furinTitle` field. `head()` never executes in the browser, so this is the
323
+ * only channel through which SPA navigation can learn the new document title.
324
+ *
325
+ * Deferred fields are absent from `syncData` (they are still Promises), so a
326
+ * `head()` that reads one sees `undefined` — titles should be derived from
327
+ * synchronous loader data. A throwing `head()` is swallowed: a missing title
328
+ * must never break the data response.
329
+ */
330
+ function withResolvedTitle(
331
+ route: ResolvedRoute,
332
+ syncData: Record<string, unknown>
333
+ ): Record<string, unknown> {
334
+ const head = route.page.head;
335
+ if (!head) {
336
+ return syncData;
337
+ }
338
+ let title: string | undefined;
339
+ try {
340
+ title = extractTitle(head(syncData).meta);
341
+ } catch {
342
+ return syncData;
343
+ }
344
+ if (title === undefined) {
345
+ return syncData;
346
+ }
347
+ return { ...syncData, __furinTitle: title };
348
+ }
349
+
350
+ function createDeferredNdjsonStream(
351
+ syncData: Record<string, unknown>,
352
+ deferredPromises: Record<string, Promise<unknown>>
353
+ ): ReadableStream<Uint8Array> {
354
+ const enc = new TextEncoder();
355
+ const entries = Object.entries(deferredPromises);
356
+
357
+ return new ReadableStream<Uint8Array>({
358
+ async start(controller) {
359
+ const initial = toCrossJSON({
360
+ ...syncData,
361
+ __furinDeferredKeys: entries.map(([key]) => key),
362
+ });
363
+ controller.enqueue(enc.encode(`${JSON.stringify(initial)}\n`));
364
+
365
+ await Promise.all(
366
+ entries.map(async ([key, promise]) => {
367
+ try {
368
+ const value = await promise;
369
+ controller.enqueue(
370
+ enc.encode(
371
+ `${JSON.stringify({ key, action: "resolve", value: toCrossJSON(value) })}\n`
372
+ )
373
+ );
374
+ } catch (err) {
375
+ const normalized = await serializeDeferredRejection(err);
376
+ const value = toCrossJSON(normalized);
377
+ controller.enqueue(enc.encode(`${JSON.stringify({ key, action: "reject", value })}\n`));
378
+ }
379
+ })
380
+ );
381
+ controller.close();
382
+ },
383
+ });
384
+ }