@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
@@ -15,7 +15,7 @@ import {
15
15
  urlPathFromCacheKey,
16
16
  } from "../cache/dev-loader.ts";
17
17
  import { currentInstance } from "../instance.ts";
18
- import type { ResolvedRoute } from "../router/types.ts";
18
+ import type { ResolvedRoute, ResolvedRoutesSource } from "../router/types.ts";
19
19
  import { devtoolsEventsSnapshot, devtoolsInstanceId, subscribeDevtoolsEventsAfter } from "./hub.ts";
20
20
 
21
21
  let clientSource: string | undefined;
@@ -128,7 +128,7 @@ function serializeEvent(event: DevtoolsSnapshot["events"][number]): string {
128
128
  }
129
129
 
130
130
  export function createDevtoolsPlugin(
131
- routes: ResolvedRoute[],
131
+ routesSource: ResolvedRoutesSource,
132
132
  syncStreamPath: string | undefined
133
133
  ): AnyElysia {
134
134
  let activeEventStreams = 0;
@@ -255,7 +255,9 @@ export function createDevtoolsPlugin(
255
255
  prefix: instance.prefix,
256
256
  },
257
257
  lastEventId: eventSnapshot.lastEventId,
258
- routes: routes.map(routeSnapshot),
258
+ routes: (typeof routesSource === "function" ? routesSource() : routesSource).map(
259
+ routeSnapshot
260
+ ),
259
261
  sync: {
260
262
  enabled: syncStreamPath !== undefined,
261
263
  streamPath: syncStreamPath ?? null,
@@ -45,12 +45,12 @@ let _defaultInstance: FurinInstance | null = null;
45
45
 
46
46
  export function createInstance(prefix: string, pagesDir: string): FurinInstance {
47
47
  return {
48
- prefix,
49
- pagesDir,
50
- syncStreamPath: undefined,
51
48
  buildId: "",
49
+ pagesDir,
50
+ prefix,
52
51
  registrationEpoch: 0,
53
52
  state: new Map(),
53
+ syncStreamPath: undefined,
54
54
  };
55
55
  }
56
56
 
@@ -1,3 +1,4 @@
1
+ import type { AnyElysia } from "elysia";
1
2
  import type { SsgCacheEntry } from "./cache/index.ts";
2
3
  import { __clearInstanceRegistry } from "./instance.ts";
3
4
 
@@ -23,6 +24,8 @@ export interface CompileContext {
23
24
  clientLogging?: boolean;
24
25
  embedded?: EmbeddedAppData;
25
26
  modules: Record<string, unknown>;
27
+ /** Elysia-native route tree generated for this mounted app. */
28
+ nativeRoutes?: AnyElysia;
26
29
  /** Mount prefix this app was built for (`""` = root). */
27
30
  prefix?: string;
28
31
  /** Root-level conventions discovered at compile time. */
@@ -0,0 +1,21 @@
1
+ import { initLogger, type LoggerConfig } from "evlog";
2
+
3
+ const FURIN_LOGGER_INITIALIZED = Symbol.for("@teyik0/furin/logger-initialized");
4
+
5
+ function loggerState(): typeof globalThis & { [key: symbol]: boolean | undefined } {
6
+ return globalThis as typeof globalThis & { [key: symbol]: boolean | undefined };
7
+ }
8
+
9
+ export function initializeFurinLogger(config: LoggerConfig): void {
10
+ const state = loggerState();
11
+ if (state[FURIN_LOGGER_INITIALIZED]) {
12
+ return;
13
+ }
14
+ initLogger(config);
15
+ state[FURIN_LOGGER_INITIALIZED] = true;
16
+ }
17
+
18
+ /** @internal */
19
+ export function resetFurinLoggerForTests(): void {
20
+ delete loggerState()[FURIN_LOGGER_INITIALIZED];
21
+ }
@@ -1,8 +1,6 @@
1
1
  // biome-ignore-all lint/performance/noAwaitInLoops: readable streams must be consumed sequentially
2
2
  import type { toCrossJSON } from "seroval";
3
- import { containsRscSource, serializeRouteFrames } from "../../shared/route-frame.ts";
4
3
  import { getSyncStreamPath } from "../sync/config.ts";
5
- import type { buildHeadInjection } from "./shell";
6
4
  import { safeJson } from "./shell";
7
5
 
8
6
  /**
@@ -105,45 +103,6 @@ export async function streamToString(stream: ReadableStream): Promise<string> {
105
103
  return html;
106
104
  }
107
105
 
108
- interface SplitTemplate {
109
- bodyPost: string;
110
- bodyPre: string;
111
- headPre: string;
112
- }
113
-
114
- export function splitTemplate(template: string): SplitTemplate {
115
- const [headPre, afterHead = ""] = template.split("<!--ssr-head-->");
116
- const [bodyPre, bodyPost = ""] = afterHead.split("<!--ssr-outlet-->");
117
- return { bodyPost, bodyPre, headPre } as SplitTemplate;
118
- }
119
-
120
- export function assembleHTML(
121
- template: string,
122
- headData: ReturnType<typeof buildHeadInjection>,
123
- reactHtml: string,
124
- data: Record<string, unknown> | undefined
125
- ): string {
126
- const { headPre, bodyPre, bodyPost } = splitTemplate(template);
127
-
128
- let dataScript = "";
129
- if (data !== undefined) {
130
- dataScript = containsRscSource(data)
131
- ? buildRouteFrameTemplate(serializeRouteFrames(data, undefined))
132
- : `<script id="__FURIN_DATA__" type="application/json">${safeJson(data)}</script>`;
133
- }
134
- const syncScript = buildSyncRuntimeScript();
135
- const runtimeScripts = `${syncScript}${dataScript}`;
136
-
137
- let injectedBodyPost = bodyPost;
138
- if (runtimeScripts) {
139
- injectedBodyPost = bodyPost.includes("</body>")
140
- ? bodyPost.replace("</body>", `${runtimeScripts}</body>`)
141
- : bodyPost + runtimeScripts;
142
- }
143
-
144
- return headPre + headData + bodyPre + reactHtml + injectedBodyPost;
145
- }
146
-
147
106
  export function buildRouteFrameTemplate(payload: string): string {
148
107
  const escaped = payload.replaceAll("&", "&amp;").replaceAll("<", "&lt;");
149
108
  return `<template id="__FURIN_ROUTE_FRAMES__">${escaped}</template>`;
@@ -0,0 +1,25 @@
1
+ import { createElement, type ReactNode } from "react";
2
+ import {
3
+ type DocumentAssets,
4
+ DocumentProvider,
5
+ type DocumentState,
6
+ } from "../../client/document.tsx";
7
+ import type { HeadOptions } from "../../client.ts";
8
+ import { getSyncStreamPath } from "../sync/config.ts";
9
+ import { safeJson } from "./shell.ts";
10
+
11
+ export function withDocumentState(
12
+ element: ReactNode,
13
+ assets: DocumentAssets,
14
+ head: HeadOptions | undefined,
15
+ data: object | undefined
16
+ ): ReactNode {
17
+ const syncStreamPath = getSyncStreamPath();
18
+ const state: DocumentState = {
19
+ assets,
20
+ dataJson: data === undefined ? undefined : safeJson(data),
21
+ head,
22
+ syncJson: syncStreamPath === undefined ? undefined : safeJson({ stream: syncStreamPath }),
23
+ };
24
+ return createElement(DocumentProvider, { value: state }, element);
25
+ }
@@ -4,7 +4,7 @@ import { DefaultErrorFallback, DefaultNotFoundFallback } from "../../client/defa
4
4
  import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
5
5
  import type { ErrorComponent } from "../../shared/error.ts";
6
6
  import type { FurinNotFoundError, NotFoundComponent } from "../../shared/not-found.ts";
7
- import type { ResolvedRoute, SegmentBoundary } from "../router/index.ts";
7
+ import type { ResolvedRoute, SegmentBoundary } from "../router/types.ts";
8
8
  import { IS_DEV } from "../runtime-env.ts";
9
9
 
10
10
  export function buildElement(
@@ -50,6 +50,18 @@ export function buildElement(
50
50
  return element;
51
51
  }
52
52
 
53
+ export function wrapRootLayout(
54
+ element: ReactNode,
55
+ data: Record<string, unknown>,
56
+ rootLayout: RuntimeRoute
57
+ ): ReactNode {
58
+ if (!rootLayout.layout) {
59
+ return element;
60
+ }
61
+ const RootLayoutComponent = rootLayout.layout;
62
+ return <RootLayoutComponent {...data}>{element}</RootLayoutComponent>;
63
+ }
64
+
53
65
  export function buildNotFoundElement(
54
66
  component: NotFoundComponent | undefined,
55
67
  error: FurinNotFoundError
@@ -21,6 +21,5 @@ export {
21
21
  renderSSR,
22
22
  renderToHTML,
23
23
  serializeLoaderDataNdjson,
24
- splitBeforeBodyClose,
25
24
  withSSRRouterContext,
26
25
  } from "./ssr.ts";
@@ -1,6 +1,7 @@
1
1
  import { AsyncResource } from "node:async_hooks";
2
2
  import type { Context } from "elysia";
3
- import { renderToReadableStream } from "react-dom/server";
3
+ import { createElement } from "react";
4
+ import { FurinDocumentFallback } from "../../client/document.tsx";
4
5
  import { isNotFoundError } from "../../shared/not-found.ts";
5
6
  import type { SearchRouteMetadata } from "../../shared/search-params.ts";
6
7
  import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
@@ -16,14 +17,14 @@ import type { ISRCacheEntry } from "../cache/isr-ssg.ts";
16
17
  import { pathWithRequestSearch } from "../cache/route-cache.ts";
17
18
  import { createLogger, useLogger } from "../context-logger.ts";
18
19
  import { currentInstance, withInstance } from "../instance.ts";
19
- import type { ResolvedRoute, RootLayout } from "../router/index.ts";
20
+ import type { ResolvedRoute, RootLayout } from "../router/types.ts";
20
21
  import {
21
- assembleHTML,
22
22
  injectSyncRuntimeScript,
23
23
  type LoaderContext,
24
24
  resolvePath,
25
25
  streamToString,
26
26
  } from "./assemble.ts";
27
+ import { withDocumentState } from "./document.tsx";
27
28
  import { runPublicLoaders } from "./loaders.ts";
28
29
  import {
29
30
  type PreparedRender,
@@ -102,7 +103,7 @@ async function renderISRNon200(
102
103
  renderStart: number,
103
104
  buildId: string | undefined
104
105
  ): Promise<string> {
105
- const { componentProps, element, headData, headers, template, status, notFoundError } = prepared;
106
+ const { assets, componentProps, element, headData, headers, status, notFoundError } = prepared;
106
107
  const fallbackProps: Record<string, unknown> = { ...componentProps };
107
108
  if (status === 404) {
108
109
  fallbackProps.__furinStatus = 404;
@@ -112,9 +113,15 @@ async function renderISRNon200(
112
113
  }
113
114
 
114
115
  const { stream: reactStream, shellError } = await renderElementWithShellFallback(
115
- element,
116
+ withDocumentState(element, assets, headData, fallbackProps),
116
117
  route.error ?? root.error,
117
- prepared.ssrContext
118
+ prepared.ssrContext,
119
+ (fallback, digest) =>
120
+ withDocumentState(createElement(FurinDocumentFallback, null, fallback), assets, headData, {
121
+ ...fallbackProps,
122
+ __furinError: { digest, status: 500 },
123
+ __furinStatus: 500,
124
+ })
118
125
  );
119
126
  let finalStatus = status;
120
127
  let finalDigest = errorDigest;
@@ -139,7 +146,7 @@ async function renderISRNon200(
139
146
 
140
147
  await reactStream.allReady;
141
148
  const reactHtml = await streamToString(reactStream);
142
- const html = assembleHTML(template, headData, reactHtml, fallbackProps);
149
+ const html = reactHtml;
143
150
  const generatedAt = Date.now();
144
151
 
145
152
  const renderMs = generatedAt - renderStart;
@@ -214,16 +221,30 @@ export async function handleISR(
214
221
  return prepared;
215
222
  }
216
223
 
217
- const { element, headData, headers, syncData, template, status, errorDigest } = prepared;
224
+ const { assets, element, headData, headers, syncData, status, errorDigest } = prepared;
218
225
 
219
226
  if (status !== 200) {
220
227
  return renderISRNon200(prepared, route, ctx, root, errorDigest, renderStart, buildId);
221
228
  }
222
229
 
223
- const stream = await renderToReadableStream(element);
230
+ const { shellError, stream } = await renderElementWithShellFallback(
231
+ withDocumentState(element, assets, headData, syncData),
232
+ route.error ?? root.error,
233
+ prepared.ssrContext,
234
+ (fallback, digest) =>
235
+ withDocumentState(createElement(FurinDocumentFallback, null, fallback), assets, headData, {
236
+ __furinError: { digest, status: 500 },
237
+ __furinStatus: 500,
238
+ })
239
+ );
240
+ if (shellError) {
241
+ prepared.status = 500;
242
+ prepared.errorDigest = shellError.digest;
243
+ return renderISRNon200(prepared, route, ctx, root, shellError.digest, renderStart, buildId);
244
+ }
224
245
  await stream.allReady;
225
246
  const reactHtml = await streamToString(stream);
226
- const html = assembleHTML(template, headData, reactHtml, syncData);
247
+ const html = reactHtml;
227
248
  const generatedAt = Date.now();
228
249
 
229
250
  useLogger().set({
@@ -1,12 +1,13 @@
1
1
  import type { Context } from "elysia";
2
2
  import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
3
- import { isDeferred, type RequestLoaderContext } from "../../client.ts";
3
+ import { isDeferred } from "../../client.ts";
4
+ import type { RequestLoaderContext } from "../../define-route.ts";
4
5
  import { isFurinRscRenderError } from "../../rsc/render-error.ts";
5
6
  import { computeErrorDigest } from "../../shared/digest.ts";
6
7
  import { type FurinNotFoundError, isNotFoundError } from "../../shared/not-found.ts";
7
8
  import { useLogger } from "../context-logger.ts";
8
9
  import { currentInstrumentationRequest, emitLoaderFinished } from "../devtools/instrumentation.ts";
9
- import type { ResolvedRoute } from "../router/index.ts";
10
+ import type { ResolvedRoute } from "../router/types.ts";
10
11
  import { IS_DEV } from "../runtime-env.ts";
11
12
 
12
13
  export type LoaderResult =
@@ -56,6 +57,12 @@ export type LoaderResult =
56
57
  */
57
58
  const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
58
59
  const FURIN_RESERVED_KEY_PREFIX = "__furin";
60
+ /**
61
+ * Loader data keys that the render pipeline overwrites with request-context
62
+ * values when assembling component props — a loader field with one of these
63
+ * names is silently dead on arrival.
64
+ */
65
+ const ROUTE_CTX_RESERVED_KEYS = new Set(["params", "query", "path"]);
59
66
 
60
67
  function assertPublicLoaderKey(key: string): void {
61
68
  if (key.startsWith(FURIN_RESERVED_KEY_PREFIX)) {
@@ -63,6 +70,11 @@ function assertPublicLoaderKey(key: string): void {
63
70
  `[furin] Loader data key "${key}" is reserved for framework metadata. Rename this field to avoid conflicts.`
64
71
  );
65
72
  }
73
+ if (ROUTE_CTX_RESERVED_KEYS.has(key)) {
74
+ throw new Error(
75
+ `[furin] Loader data key "${key}" is reserved: it is overwritten by the route context when component props are assembled. Rename this field to avoid conflicts.`
76
+ );
77
+ }
66
78
  }
67
79
 
68
80
  /**
@@ -458,10 +470,23 @@ async function runLoadersInternal(
458
470
  // field-accesses via createLoaderCtx still receive the rejection
459
471
  // instead of silently resolving to undefined. The real rejection is
460
472
  // re-thrown by the Promise.all below.
461
- accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
462
- ...acc,
463
- ...own,
464
- }));
473
+ accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => {
474
+ if (IS_DEV) {
475
+ // Flattened parent data means a deeper loader silently shadows an
476
+ // ancestor's field (deepest wins). Surface the collision instead.
477
+ for (const key of Object.keys(own)) {
478
+ if (Object.hasOwn(acc, key)) {
479
+ useLogger().warn(
480
+ `[furin] Loader data collision on "${key}" for ${ctx.path}: a deeper loader overwrites the value inherited from its layout chain (deepest wins).`
481
+ );
482
+ }
483
+ }
484
+ }
485
+ return {
486
+ ...acc,
487
+ ...own,
488
+ };
489
+ });
465
490
  accumulatedParentPromise.catch(() => {
466
491
  /* suppress unhandled-rejection warning */
467
492
  });
@@ -1,16 +1,23 @@
1
+ import { createElement } from "react";
1
2
  import { renderToReadableStream } from "react-dom/server";
3
+ import { type DocumentAssets, FurinDocumentFallback } from "../../client/document.tsx";
2
4
  import { normalizeHref, toLogical } from "../../client/router/link-utils.ts";
3
5
  import type { RouterContextValue } from "../../client/router/types.ts";
4
6
  import { FurinNotFoundError } from "../../shared/not-found.ts";
5
7
  import { useLogger } from "../context-logger.ts";
6
8
  import { currentInstance } from "../instance.ts";
7
- import type { RootLayout } from "../router/index.ts";
9
+ import type { RootLayout } from "../router/types.ts";
8
10
  import { IS_DEV } from "../runtime-env.ts";
9
- import { assembleHTML, streamToString } from "./assemble.ts";
10
- import { buildNotFoundElement } from "./element.tsx";
11
+ import { streamToString } from "./assemble.ts";
12
+ import { withDocumentState } from "./document.tsx";
13
+ import { buildNotFoundElement, wrapRootLayout } from "./element.tsx";
11
14
  import { generateIndexHtml } from "./shell.ts";
12
15
  import { withSSRRouterContext } from "./ssr.ts";
13
- import { getDevTemplate, getProductionTemplate } from "./template.ts";
16
+ import {
17
+ documentAssetsFromTemplate,
18
+ getDevDocumentAssets,
19
+ getProductionDocumentAssets,
20
+ } from "./template.ts";
14
21
 
15
22
  /**
16
23
  * Renders the root-level not-found component into a complete 404 HTML Response.
@@ -21,18 +28,18 @@ export async function renderRootNotFound(
21
28
  request: Request | undefined,
22
29
  listenerOrigin?: string
23
30
  ): Promise<Response> {
24
- const prodTemplate = getProductionTemplate();
25
- let template: string;
31
+ const productionAssets = getProductionDocumentAssets();
32
+ let assets: DocumentAssets;
26
33
  if (IS_DEV && listenerOrigin) {
27
34
  try {
28
- template = await getDevTemplate(listenerOrigin);
35
+ assets = await getDevDocumentAssets(listenerOrigin);
29
36
  } catch {
30
- template = generateIndexHtml();
37
+ assets = documentAssetsFromTemplate(generateIndexHtml());
31
38
  }
32
- } else if (prodTemplate === null) {
33
- template = generateIndexHtml();
39
+ } else if (productionAssets === null) {
40
+ assets = documentAssetsFromTemplate(generateIndexHtml());
34
41
  } else {
35
- template = prodTemplate;
42
+ assets = productionAssets;
36
43
  }
37
44
  const notFoundError = new FurinNotFoundError(undefined);
38
45
 
@@ -44,34 +51,43 @@ export async function renderRootNotFound(
44
51
  const notFoundContext: RouterContextValue = {
45
52
  basePath,
46
53
  currentHref: request ? normalizeHref(toLogical(new URL(request.url).pathname, basePath)) : "/",
47
- search: {},
48
- searchRoutes: [],
49
- navigate: (_href, _opts) => Promise.resolve(),
50
- prefetch: (_href, _opts) => {
54
+ defaultPreload: "intent",
55
+ defaultPreloadDelay: 50,
56
+ defaultPreloadStaleTime: 30_000,
57
+ invalidatePrefetch: (_path, _type) => {
51
58
  /* noop */
52
59
  },
53
- invalidatePrefetch: (_path, _type) => {
60
+ isNavigating: false,
61
+ navigate: (_href, _opts) => Promise.resolve(),
62
+ prefetch: (_href, _opts) => {
54
63
  /* noop */
55
64
  },
56
65
  refresh: (_opts) => Promise.resolve(),
57
- isNavigating: false,
58
- defaultPreload: "intent",
59
- defaultPreloadDelay: 50,
60
- defaultPreloadStaleTime: 30_000,
66
+ search: {},
67
+ searchRoutes: [],
61
68
  };
62
69
 
63
70
  useLogger().set({
64
71
  furin: {
65
- render: "not-found",
66
72
  action: "catch_all",
67
73
  path: request ? new URL(request.url).pathname : "/",
74
+ render: "not-found",
68
75
  },
69
76
  });
70
77
 
78
+ const data = { __furinStatus: 404 };
71
79
  let reactStream: Awaited<ReturnType<typeof renderToReadableStream>>;
72
80
  try {
73
81
  reactStream = await renderToReadableStream(
74
- withSSRRouterContext(buildNotFoundElement(root.notFound, notFoundError), notFoundContext)
82
+ withDocumentState(
83
+ withSSRRouterContext(
84
+ wrapRootLayout(buildNotFoundElement(root.notFound, notFoundError), {}, root.route),
85
+ notFoundContext
86
+ ),
87
+ assets,
88
+ undefined,
89
+ data
90
+ )
75
91
  );
76
92
  } catch (renderError) {
77
93
  // The user's not-found component itself threw. Fall back to the built-in
@@ -79,21 +95,29 @@ export async function renderRootNotFound(
79
95
  // 404 page from logs and drains.
80
96
  useLogger().set({
81
97
  furin: {
82
- render: "not-found",
83
98
  action: "component_render_failed",
84
99
  error: renderError instanceof Error ? renderError.message : String(renderError),
100
+ render: "not-found",
85
101
  },
86
102
  });
87
103
  reactStream = await renderToReadableStream(
88
- withSSRRouterContext(buildNotFoundElement(undefined, notFoundError), notFoundContext)
104
+ withDocumentState(
105
+ createElement(
106
+ FurinDocumentFallback,
107
+ null,
108
+ withSSRRouterContext(buildNotFoundElement(undefined, notFoundError), notFoundContext)
109
+ ),
110
+ assets,
111
+ undefined,
112
+ data
113
+ )
89
114
  );
90
115
  }
91
116
  await reactStream.allReady;
92
- const reactHtml = await streamToString(reactStream);
93
- const html = assembleHTML(template, "", reactHtml, { __furinStatus: 404 });
117
+ const html = await streamToString(reactStream);
94
118
 
95
119
  return new Response(html, {
96
- status: 404,
97
120
  headers: { "Content-Type": "text/html; charset=utf-8" },
121
+ status: 404,
98
122
  });
99
123
  }
@@ -4,7 +4,7 @@ import { autoInvalidateRegistry, getAutoInvalidateRegistry } from "../auto-inval
4
4
  import { registerCacheInvalidator } from "../cache/registry.ts";
5
5
  import { type Cache, createRouteCache, type RevalidateType } from "../cache/route-cache.ts";
6
6
  import { allStateBuckets, currentInstance, type FurinInstance } from "../instance.ts";
7
- import type { ResolvedRoute, RootLayout } from "../router/index.ts";
7
+ import type { ResolvedRoute, RootLayout } from "../router/types.ts";
8
8
  import { resolvePath } from "./assemble.ts";
9
9
  import { type LoaderResult, runPublicLoaders, withRequestLoaderData } from "./loaders.ts";
10
10
  import { renderSSR } from "./ssr.ts";
@@ -4,7 +4,7 @@ import { mapWithConcurrency } from "../../shared/utils/index.ts";
4
4
  import type { SsgCacheEntry } from "../cache/isr-ssg.ts";
5
5
  import { getSSGCache, setSSGCache } from "../cache/ssg.ts";
6
6
  import { createLogger } from "../context-logger.ts";
7
- import type { ResolvedRoute, RootLayout } from "../router/index.ts";
7
+ import type { ResolvedRoute, RootLayout } from "../router/types.ts";
8
8
  import { resolvePath } from "./assemble.ts";
9
9
  import { renderForPath } from "./ssr.ts";
10
10