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

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 (250) hide show
  1. package/dist/adapter/bun.d.ts +2 -18
  2. package/dist/adapter/package.d.ts +2 -2
  3. package/dist/adapter/runtime-build.d.ts +33 -0
  4. package/dist/adapter/vercel.d.ts +3 -0
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/compile-entry.d.ts +4 -3
  7. package/dist/build/compile-entry.ts +24 -69
  8. package/dist/build/entry-template.d.ts +8 -2
  9. package/dist/build/entry-template.ts +48 -11
  10. package/dist/build/index.d.ts +2 -2
  11. package/dist/build/index.js +11720 -7840
  12. package/dist/build/route-types.d.ts +2 -22
  13. package/dist/build/shared.d.ts +1 -1
  14. package/dist/build/ssg-cache.d.ts +14 -1
  15. package/dist/build/types.d.ts +26 -3
  16. package/dist/build/virtual-entry.d.ts +8 -0
  17. package/dist/cache.d.ts +5 -0
  18. package/dist/cache.js +97 -0
  19. package/dist/cli/index.js +11815 -7793
  20. package/dist/cli/preview.d.ts +7 -0
  21. package/dist/client/boundaries.d.ts +3 -0
  22. package/dist/client/browser-events-runtime.d.ts +2 -0
  23. package/dist/client/browser-events.d.ts +2 -0
  24. package/dist/client/define-route.d.ts +36 -0
  25. package/dist/client/dev-error-overlay.d.ts +1 -0
  26. package/dist/client/dev-error-overlay.ts +201 -0
  27. package/dist/client/document.d.ts +27 -0
  28. package/dist/client/hmr.d.ts +12 -0
  29. package/dist/client/internal/runtime-types.d.ts +3 -1
  30. package/dist/client/link.js +1392 -940
  31. package/dist/client/router/index.d.ts +1 -1
  32. package/dist/client/router/link-utils.d.ts +9 -0
  33. package/dist/client/router/provider.d.ts +1 -1
  34. package/dist/client/router/search/index.d.ts +3 -7
  35. package/dist/client/router/sync-catch-up.d.ts +1 -1
  36. package/dist/client/router/types.d.ts +40 -34
  37. package/dist/client.d.ts +4 -159
  38. package/dist/client.js +197 -21
  39. package/dist/config.d.ts +25 -8
  40. package/dist/config.js +15 -7
  41. package/dist/define-route.d.ts +1358 -0
  42. package/dist/devtools/protocol.d.ts +2 -2
  43. package/dist/furin.d.ts +18 -34
  44. package/dist/furin.js +16038 -9395
  45. package/dist/plugin/index.js +1401 -223
  46. package/dist/plugin/route-config-autofix.d.ts +31 -0
  47. package/dist/plugin/routes.d.ts +28 -0
  48. package/dist/routes.d.ts +6 -0
  49. package/dist/routes.js +1 -0
  50. package/dist/rsc/build/index.d.ts +6 -2
  51. package/dist/rsc.js +3 -3
  52. package/dist/server/browser-events/plugin.d.ts +11 -0
  53. package/dist/server/browser-events/types.d.ts +9 -0
  54. package/dist/server/cache/invalidation.d.ts +1 -2
  55. package/dist/server/cache/isr.d.ts +1 -0
  56. package/dist/server/cache/purger.d.ts +7 -0
  57. package/dist/server/cache/runtime-cache.d.ts +21 -0
  58. package/dist/server/dev/browser-events.d.ts +4 -0
  59. package/dist/server/dev/diagnostics.d.ts +39 -0
  60. package/dist/server/dev/error.d.ts +17 -0
  61. package/dist/server/dev/graph.d.ts +86 -0
  62. package/dist/server/dev/plugin.d.ts +9 -0
  63. package/dist/server/dev/request-security.d.ts +1 -0
  64. package/dist/server/dev/rewrite-module-specifiers.d.ts +7 -0
  65. package/dist/server/dev/runtime.production.d.ts +5 -0
  66. package/dist/server/dev/symbolicate.d.ts +11 -0
  67. package/dist/server/dev/transform-failure.d.ts +4 -0
  68. package/dist/server/dev-page-plugin.d.ts +7 -5
  69. package/dist/server/dev-page-plugin.production.d.ts +1 -0
  70. package/dist/server/devtools/hub.d.ts +3 -2
  71. package/dist/server/devtools/instrumentation.d.ts +2 -2
  72. package/dist/server/devtools/instrumentation.production.d.ts +2 -2
  73. package/dist/server/devtools/plugin.d.ts +2 -2
  74. package/dist/server/external-prerender.d.ts +2 -0
  75. package/dist/server/instance.d.ts +2 -2
  76. package/dist/server/internal.d.ts +17 -2
  77. package/dist/server/internal.js +436 -1
  78. package/dist/server/logger.d.ts +4 -0
  79. package/dist/server/render/assemble.d.ts +0 -9
  80. package/dist/server/render/document.d.ts +4 -0
  81. package/dist/server/render/element.d.ts +3 -1
  82. package/dist/server/render/index.d.ts +2 -2
  83. package/dist/server/render/index.ts +1 -2
  84. package/dist/server/render/isr.d.ts +1 -1
  85. package/dist/server/render/loaders.d.ts +1 -1
  86. package/dist/server/render/not-found.d.ts +1 -1
  87. package/dist/server/render/ppr-document.d.ts +21 -0
  88. package/dist/server/render/ppr-request.d.ts +26 -0
  89. package/dist/server/render/ppr-route.d.ts +4 -2
  90. package/dist/server/render/shell.ts +0 -12
  91. package/dist/server/render/ssg.d.ts +3 -1
  92. package/dist/server/render/ssr.d.ts +23 -11
  93. package/dist/server/render/template.d.ts +4 -0
  94. package/dist/server/router/defined-route.d.ts +24 -0
  95. package/dist/server/router/hmr.d.ts +16 -8
  96. package/dist/server/router/hmr.production.d.ts +2 -0
  97. package/dist/server/router/patterns.d.ts +7 -0
  98. package/dist/server/router/plugin.d.ts +6 -3
  99. package/dist/server/router/schema-merge.d.ts +2 -2
  100. package/dist/server/router/schemas.d.ts +5 -5
  101. package/dist/server/router/source-version.d.ts +2 -0
  102. package/dist/server/router/types.d.ts +1 -0
  103. package/dist/server/sync/adapter.d.ts +13 -0
  104. package/dist/server/sync/config.d.ts +5 -5
  105. package/dist/server/sync/index.d.ts +6 -6
  106. package/dist/server/sync/index.js +1115 -985
  107. package/dist/server/sync/notifier.d.ts +1 -0
  108. package/dist/server/sync/postgres/index.d.ts +12 -1
  109. package/dist/server/sync/postgres/index.js +101 -6
  110. package/dist/server/sync/postgres/migrate.js +3 -2
  111. package/dist/server/sync/stream.d.ts +4 -13
  112. package/dist/shared/await.d.ts +4 -5
  113. package/dist/shared/browser-events.d.ts +22 -0
  114. package/dist/shared/compact-json.d.ts +8 -0
  115. package/dist/shared/deferred-ndjson.d.ts +6 -5
  116. package/dist/shared/dev-diagnostics.d.ts +36 -0
  117. package/dist/shared/elysia-contract.d.ts +41 -0
  118. package/dist/shared/prefix.d.ts +2 -0
  119. package/dist/shared/route-map.d.ts +5 -0
  120. package/dist/shared/utils/index.d.ts +1 -3
  121. package/package.json +55 -43
  122. package/src/adapter/README.md +45 -0
  123. package/src/adapter/bun.ts +62 -265
  124. package/src/adapter/package.ts +34 -22
  125. package/src/adapter/runtime-build.ts +375 -0
  126. package/src/adapter/static.ts +83 -5
  127. package/src/adapter/vercel.ts +857 -0
  128. package/src/build/client.ts +58 -16
  129. package/src/build/compile-entry.ts +24 -69
  130. package/src/build/entry-template.ts +48 -11
  131. package/src/build/hydrate.ts +147 -37
  132. package/src/build/index.ts +21 -7
  133. package/src/build/production-instrumentation.ts +56 -4
  134. package/src/build/route-types.ts +19 -114
  135. package/src/build/shared.ts +3 -2
  136. package/src/build/ssg-cache.ts +99 -16
  137. package/src/build/types.ts +32 -3
  138. package/src/build/virtual-entry.ts +27 -0
  139. package/src/cache.ts +14 -0
  140. package/src/cli/config.ts +3 -3
  141. package/src/cli/index.ts +62 -10
  142. package/src/cli/preview.ts +90 -0
  143. package/src/client/boundaries.tsx +19 -2
  144. package/src/client/browser-events-runtime.ts +204 -0
  145. package/src/client/browser-events.ts +22 -0
  146. package/src/client/define-route.ts +38 -0
  147. package/src/client/dev-error-overlay.ts +201 -0
  148. package/src/client/document.tsx +162 -0
  149. package/src/client/hmr.ts +63 -0
  150. package/src/client/internal/runtime-types.ts +3 -1
  151. package/src/client/link.tsx +21 -6
  152. package/src/client/router/boundary-tree.tsx +4 -4
  153. package/src/client/router/index.ts +1 -0
  154. package/src/client/router/link-utils.ts +26 -0
  155. package/src/client/router/provider.tsx +190 -65
  156. package/src/client/router/search/index.ts +4 -12
  157. package/src/client/router/sync-catch-up.ts +3 -4
  158. package/src/client/router/types.ts +56 -30
  159. package/src/client.ts +14 -316
  160. package/src/config.ts +35 -10
  161. package/src/define-route.ts +972 -0
  162. package/src/devtools/devtools-element.js +67 -87
  163. package/src/devtools/protocol.ts +2 -2
  164. package/src/furin.ts +431 -101
  165. package/src/plugin/route-config-autofix.ts +1140 -0
  166. package/src/plugin/routes.ts +1061 -0
  167. package/src/plugin/transform-client.ts +776 -228
  168. package/src/plugin/transform-isomorphic.ts +1 -1
  169. package/src/react-dom-edge.d.ts +6 -0
  170. package/src/routes.ts +6 -0
  171. package/src/rsc/build/index.ts +16 -4
  172. package/src/server/auto-invalidate/registry.ts +2 -2
  173. package/src/server/auto-invalidate/runtime.ts +5 -2
  174. package/src/server/browser-events/plugin.ts +168 -0
  175. package/src/server/browser-events/types.ts +11 -0
  176. package/src/server/cache/dev-loader.ts +30 -29
  177. package/src/server/cache/invalidation.ts +13 -22
  178. package/src/server/cache/isr.ts +9 -0
  179. package/src/server/cache/purger.ts +41 -0
  180. package/src/server/cache/runtime-cache.ts +137 -0
  181. package/src/server/dev/browser-events.ts +54 -0
  182. package/src/server/dev/diagnostics.ts +297 -0
  183. package/src/server/dev/error.ts +148 -0
  184. package/src/server/dev/graph.ts +438 -0
  185. package/src/server/dev/plugin.ts +130 -0
  186. package/src/server/dev/request-security.ts +38 -0
  187. package/src/server/dev/rewrite-module-specifiers.ts +81 -0
  188. package/src/server/dev/runtime.production.ts +24 -0
  189. package/src/server/dev/symbolicate.ts +135 -0
  190. package/src/server/dev/transform-failure.ts +8 -0
  191. package/src/server/dev-page-plugin.production.ts +3 -0
  192. package/src/server/dev-page-plugin.ts +110 -52
  193. package/src/server/devtools/hub.ts +6 -5
  194. package/src/server/devtools/instrumentation.production.ts +3 -3
  195. package/src/server/devtools/instrumentation.ts +14 -8
  196. package/src/server/devtools/plugin.ts +12 -153
  197. package/src/server/external-prerender.ts +10 -0
  198. package/src/server/instance.ts +5 -5
  199. package/src/server/internal.ts +42 -2
  200. package/src/server/logger.ts +21 -0
  201. package/src/server/render/assemble.ts +4 -45
  202. package/src/server/render/document.tsx +34 -0
  203. package/src/server/render/element.tsx +31 -15
  204. package/src/server/render/index.ts +1 -2
  205. package/src/server/render/isr.ts +70 -24
  206. package/src/server/render/loaders.ts +43 -8
  207. package/src/server/render/not-found.ts +77 -29
  208. package/src/server/render/ppr-document.ts +239 -0
  209. package/src/server/render/ppr-request.ts +104 -0
  210. package/src/server/render/ppr-route.ts +153 -32
  211. package/src/server/render/shell.ts +0 -12
  212. package/src/server/render/ssg.ts +39 -21
  213. package/src/server/render/ssr.ts +429 -143
  214. package/src/server/render/template.ts +128 -2
  215. package/src/server/router/defined-route.ts +78 -0
  216. package/src/server/router/discovery.ts +129 -29
  217. package/src/server/router/hmr.production.ts +7 -0
  218. package/src/server/router/hmr.ts +177 -67
  219. package/src/server/router/patterns.ts +45 -13
  220. package/src/server/router/plugin.ts +184 -78
  221. package/src/server/router/schema-merge.ts +4 -14
  222. package/src/server/router/schemas.ts +11 -8
  223. package/src/server/router/source-version.ts +9 -0
  224. package/src/server/router/types.ts +2 -0
  225. package/src/server/sync/adapter.ts +13 -0
  226. package/src/server/sync/config.ts +12 -12
  227. package/src/server/sync/index.ts +8 -8
  228. package/src/server/sync/notifier.ts +1 -0
  229. package/src/server/sync/plugin.ts +4 -1
  230. package/src/server/sync/postgres/index.ts +111 -5
  231. package/src/server/sync/postgres/migrate.ts +3 -2
  232. package/src/server/sync/response.ts +14 -10
  233. package/src/server/sync/runtime.ts +12 -0
  234. package/src/server/sync/stream.ts +78 -113
  235. package/src/shared/await.tsx +4 -5
  236. package/src/shared/browser-events.ts +28 -0
  237. package/src/shared/compact-json.ts +77 -0
  238. package/src/shared/deferred-ndjson.ts +20 -6
  239. package/src/shared/dev-diagnostics.ts +44 -0
  240. package/src/shared/elysia-contract.ts +63 -0
  241. package/src/shared/prefix.ts +8 -0
  242. package/src/shared/route-map.ts +46 -0
  243. package/src/shared/utils/index.ts +2 -20
  244. package/dist/build/server-routes-entry.d.ts +0 -13
  245. package/dist/build/server-routes-entry.ts +0 -30
  246. package/dist/server/router/index.d.ts +0 -7
  247. package/dist/server/router/index.js +0 -27
  248. package/dist/server/router/index.ts +0 -28
  249. package/src/build/server-routes-entry.ts +0 -30
  250. package/src/server/router/index.ts +0 -28
@@ -1,14 +1,17 @@
1
1
  import { type AnyElysia, type Context, Elysia, t } from "elysia";
2
- import type { AnySchema } from "elysia/types";
3
2
  import { toCrossJSONAsync } from "seroval";
3
+ import type { HeadOptions } from "../../client.ts";
4
4
  import { computeErrorDigest } from "../../shared/digest.ts";
5
- import { containsRscSource, serializeRouteFrames } from "../../shared/route-frame.ts";
5
+ import type { FurinSchema } from "../../shared/elysia-contract.ts";
6
+ import { containsRscSource } from "../../shared/route-frame.ts";
6
7
  import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
7
8
  import { useLogger } from "../context-logger.ts";
8
9
  import {
9
10
  currentInstrumentationRequest,
10
11
  emitPayloadSerialized,
11
12
  } from "../devtools/instrumentation.ts";
13
+ import { isExternalPrerenderRequest } from "../external-prerender.ts";
14
+ import { currentInstance } from "../instance.ts";
12
15
  import { injectSyncRuntimeScript, resolvePath } from "../render/assemble.ts";
13
16
  import { handleISR } from "../render/isr.ts";
14
17
  import {
@@ -18,17 +21,28 @@ import {
18
21
  runPublicLoaders,
19
22
  withRequestLoaderData,
20
23
  } from "../render/loaders.ts";
21
- import { renderPprRoute } from "../render/ppr-route.ts";
24
+ import { renderPprRoute, runPprPublicLoaders } from "../render/ppr-route.ts";
22
25
  import { createDeferredRouteFrameStream } from "../render/route-frame-transport.ts";
23
26
  import { extractTitle } from "../render/shell.ts";
24
- import { prerenderSSG } from "../render/ssg.ts";
25
- import { renderSSR } from "../render/ssr.ts";
27
+ import { prerenderRoute, prerenderSSG } from "../render/ssg.ts";
28
+ import { renderSSR, serializeLoaderDataNdjson } from "../render/ssr.ts";
26
29
  import { IS_DEV } from "../runtime-env.ts";
27
30
  import { handleDevRequest } from "./hmr.ts";
28
- import { buildRouteMatcher } from "./patterns.ts";
31
+ import { buildRouteMatcher, resolveRouteRevalidate } from "./patterns.ts";
29
32
  import { mergeRouteSchemas } from "./schema-merge.ts";
30
- import { parseDataEndpointPath, parseRouteParams, parseRouteQuery } from "./schemas.ts";
31
- import type { ResolvedRoute, RootLayout } from "./types.ts";
33
+ import {
34
+ createSearchRouteMetadata,
35
+ parseDataEndpointPath,
36
+ parseRouteParams,
37
+ parseRouteQuery,
38
+ } from "./schemas.ts";
39
+ import type { ResolvedRoute, ResolvedRoutesSource, RootLayout } from "./types.ts";
40
+
41
+ const MAX_NAVIGATION_HEAD_BYTES = 64 * 1024;
42
+
43
+ type DataResolvedRoutesSource =
44
+ | ResolvedRoutesSource
45
+ | ((request: Request) => Promise<ResolvedRoute[]>);
32
46
 
33
47
  interface DataRouteParamsInput {
34
48
  [key: string]: unknown;
@@ -39,6 +53,8 @@ type SyntheticDataContext = Omit<Context, "params" | "query"> & {
39
53
  query: SearchParamsInput;
40
54
  };
41
55
 
56
+ type RouteDataContext = Pick<SyntheticDataContext, "params" | "path" | "query">;
57
+
42
58
  function emitSerializedPayload(body: string, kind: "route-data" | "rsc", requestUrl: string): void {
43
59
  if (!IS_DEV) {
44
60
  return;
@@ -56,22 +72,30 @@ function emitSerializedPayload(body: string, kind: "route-data" | "rsc", request
56
72
  });
57
73
  }
58
74
 
59
- async function runDataEndpointLoaders(route: ResolvedRoute, ctx: Context): Promise<LoaderResult> {
75
+ async function runDataEndpointLoaders(
76
+ route: ResolvedRoute,
77
+ ctx: Context,
78
+ root: RootLayout | undefined,
79
+ searchRoutes: SearchRouteMetadata[]
80
+ ): Promise<LoaderResult> {
60
81
  if (route.mode !== "isr" && route.mode !== "ssg") {
61
82
  return runLoaders(route, ctx);
62
83
  }
63
84
 
64
- const result = await runPublicLoaders(route, ctx);
85
+ const result = hasRequestLoader(route)
86
+ ? await runPprPublicLoaders(route, ctx, currentInstance().buildId, root, searchRoutes)
87
+ : await runPublicLoaders(route, ctx);
65
88
  if (result.type !== "data" || !hasRequestLoader(route)) {
66
89
  return result;
67
90
  }
68
91
  return withRequestLoaderData(route, ctx, result);
69
92
  }
70
93
 
71
- async function createLoaderDataResponse(
94
+ async function serializeLoaderDataResponse(
72
95
  result: LoaderResult,
73
96
  route: ResolvedRoute,
74
- requestUrl: string
97
+ requestUrl: string,
98
+ routeContext: RouteDataContext
75
99
  ): Promise<Response> {
76
100
  if (result.type === "redirect") {
77
101
  const redirectUrl = new URL(result.response.headers.get("location") ?? "/", requestUrl);
@@ -93,20 +117,10 @@ async function createLoaderDataResponse(
93
117
  });
94
118
  }
95
119
  if (result.type === "error") {
96
- const serialized = await toCrossJSONAsync({
97
- __furinError: {
98
- digest: computeErrorDigest(result.error),
99
- message: result.message,
100
- status: result.status,
101
- },
102
- });
103
- return new Response(`${JSON.stringify(serialized)}\n`, {
104
- headers: { "content-type": "application/x-ndjson" },
105
- status: result.status,
106
- });
120
+ return createRouteDataErrorResponse(result.error, result.message, result.status, routeContext);
107
121
  }
108
122
 
109
- const syncDataWithTitle = withResolvedTitle(route, result.syncData);
123
+ const syncDataWithTitle = withResolvedHead(route, result.syncData);
110
124
  if (result.deferredPromises !== undefined) {
111
125
  return new Response(
112
126
  createDeferredRouteFrameStream(syncDataWithTitle, result.deferredPromises),
@@ -118,20 +132,81 @@ async function createLoaderDataResponse(
118
132
  }
119
133
  );
120
134
  }
121
- const body = serializeRouteFrames(syncDataWithTitle, undefined);
122
- emitSerializedPayload(
123
- body,
124
- containsRscSource(syncDataWithTitle) ? "rsc" : "route-data",
125
- requestUrl
126
- );
135
+ const hasRsc = containsRscSource(syncDataWithTitle);
136
+ const body = await serializeLoaderDataNdjson(syncDataWithTitle, undefined);
137
+ emitSerializedPayload(body, hasRsc ? "rsc" : "route-data", requestUrl);
127
138
  return new Response(body, {
128
139
  headers: {
129
140
  ...result.headers,
130
- "content-type": "application/x-furin-route",
141
+ "content-type": hasRsc ? "application/x-furin-route" : "application/x-ndjson",
131
142
  },
132
143
  });
133
144
  }
134
145
 
146
+ function navigationDataCacheControl(route: ResolvedRoute): string {
147
+ if (route.mode === "ssg") {
148
+ return "public, max-age=0, must-revalidate, s-maxage=31536000";
149
+ }
150
+ const revalidate = resolveRouteRevalidate(route.page) ?? 60;
151
+ return `public, max-age=0, s-maxage=${revalidate}, stale-while-revalidate=${revalidate}`;
152
+ }
153
+
154
+ function applyNavigationDataCache(
155
+ response: Response,
156
+ result: LoaderResult,
157
+ route: ResolvedRoute,
158
+ requestUrl: string
159
+ ): Response {
160
+ const cacheable =
161
+ !IS_DEV &&
162
+ (route.mode === "ssg" || route.mode === "isr") &&
163
+ !hasRequestLoader(route) &&
164
+ result.type === "data" &&
165
+ result.deferredPromises === undefined;
166
+ if (!cacheable) {
167
+ response.headers.set("cache-control", "private, no-store");
168
+ response.headers.delete("cache-tag");
169
+ return response;
170
+ }
171
+
172
+ const { pathname } = new URL(requestUrl);
173
+ response.headers.set("cache-tag", pathname);
174
+ response.headers.set("cache-control", navigationDataCacheControl(route));
175
+ return response;
176
+ }
177
+
178
+ async function createLoaderDataResponse(
179
+ result: LoaderResult,
180
+ route: ResolvedRoute,
181
+ requestUrl: string,
182
+ routeContext: RouteDataContext
183
+ ): Promise<Response> {
184
+ const response = await serializeLoaderDataResponse(result, route, requestUrl, routeContext);
185
+ return applyNavigationDataCache(response, result, route, requestUrl);
186
+ }
187
+
188
+ async function createRouteDataErrorResponse(
189
+ error: unknown,
190
+ message: string,
191
+ status: number,
192
+ routeContext: RouteDataContext | undefined
193
+ ): Promise<Response> {
194
+ const __furinError = { digest: computeErrorDigest(error), message, status };
195
+ const payload = routeContext
196
+ ? {
197
+ __furinError,
198
+ params: routeContext.params,
199
+ path: routeContext.path,
200
+ query: routeContext.query,
201
+ }
202
+ : { __furinError };
203
+ const serialized = await toCrossJSONAsync(payload);
204
+ return new Response(`${JSON.stringify(serialized)}\n`, {
205
+ headers: { "content-type": "application/x-ndjson" },
206
+ status,
207
+ });
208
+ }
209
+
135
210
  /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
136
211
  async function handleSSGRequest(
137
212
  route: ResolvedRoute,
@@ -141,14 +216,17 @@ async function handleSSGRequest(
141
216
  searchRoutes: SearchRouteMetadata[] | undefined
142
217
  ): Promise<unknown> {
143
218
  const { origin } = new URL(ctx.request.url);
144
- const entry = await prerenderSSG(route, ctx.params ?? {}, root, origin, undefined, searchRoutes);
219
+ const params = ctx.params ?? {};
220
+ const entry = isExternalPrerenderRequest(ctx.request)
221
+ ? await prerenderRoute(route, params, root, origin, "ssg", undefined, searchRoutes, ctx)
222
+ : await prerenderSSG(route, params, root, origin, undefined, searchRoutes);
145
223
 
146
224
  // Loader issued a redirect — forward it directly to the client.
147
225
  if (entry instanceof Response) {
148
226
  return entry;
149
227
  }
150
228
 
151
- const resolvedPath = resolvePath(route.pattern, ctx.params ?? {});
229
+ const resolvedPath = resolvePath(route.pattern, params);
152
230
 
153
231
  // ETag: "buildId:cachedAt" — unique per render cycle, changes after revalidatePath
154
232
  const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
@@ -186,45 +264,46 @@ export function createRoutePlugin(
186
264
 
187
265
  if (allParams || allQuery) {
188
266
  plugin.guard({
189
- params: allParams as AnySchema,
190
- query: allQuery as AnySchema,
267
+ params: allParams as FurinSchema,
268
+ query: allQuery as FurinSchema,
191
269
  });
192
270
  }
193
271
 
194
- plugin.get(pattern, (ctx) => {
195
- // Dev mode: re-imports page + layouts on every request via the
196
- // ?furin-server cache-buster, then dispatches into one of:
197
- // - renderDevISRWithLoaderCache (mode === "isr")
198
- // - renderDevSSGWithLoaderCache (mode === "ssg")
199
- // - renderSSR (otherwise)
200
- //
201
- // Only the LOADER OUTPUT is cached in dev — HTML is always re-assembled
202
- // fresh so the response always embeds the latest Bun client chunk URL.
203
- // This avoids the "infinite reload loop" footgun where a cached ISR/SSG
204
- // HTML response held an OLD chunk URL after Bun rebundled. The dev
205
- // cache is invalidated source-aware via `isDevLoaderCacheValid`
206
- // (mtime-checked dependency walk on every read).
207
- if (IS_DEV) {
208
- return handleDevRequest(route, ctx, root, searchRoutes);
209
- }
272
+ plugin.get(pattern, (ctx) =>
273
+ renderResolvedRoute(route, ctx, root, resolvedBuildId, searchRoutes)
274
+ );
210
275
 
211
- if ((route.mode === "ssg" || route.mode === "isr") && hasRequestLoader(route)) {
212
- return renderPprRoute(route, ctx, root, resolvedBuildId, searchRoutes);
213
- }
276
+ return plugin;
277
+ }
214
278
 
215
- if (route.mode === "ssg") {
216
- return handleSSGRequest(route, ctx, root, resolvedBuildId, searchRoutes);
217
- }
279
+ export function renderResolvedRoute(
280
+ route: ResolvedRoute,
281
+ ctx: Context,
282
+ root: RootLayout,
283
+ buildId: string,
284
+ searchRoutes: SearchRouteMetadata[] | undefined
285
+ ): unknown {
286
+ // Dev mode: re-imports page + layouts on every request via the
287
+ // ?furin-server cache-buster. Only loader output is cached in dev; HTML is
288
+ // always reassembled with the latest Bun client chunk URL.
289
+ if (IS_DEV) {
290
+ return handleDevRequest(route, ctx, root, searchRoutes);
291
+ }
218
292
 
219
- if (route.mode === "isr") {
220
- ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
221
- return handleISR(route, ctx, root, resolvedBuildId, searchRoutes);
222
- }
293
+ if ((route.mode === "ssg" || route.mode === "isr") && hasRequestLoader(route)) {
294
+ return renderPprRoute(route, ctx, root, buildId, searchRoutes);
295
+ }
223
296
 
224
- return renderSSR(route, ctx, root, undefined, searchRoutes);
225
- });
297
+ if (route.mode === "ssg") {
298
+ return handleSSGRequest(route, ctx, root, buildId, searchRoutes);
299
+ }
226
300
 
227
- return plugin;
301
+ if (route.mode === "isr") {
302
+ ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
303
+ return handleISR(route, ctx, root, buildId, searchRoutes);
304
+ }
305
+
306
+ return renderSSR(route, ctx, root, undefined, searchRoutes);
228
307
  }
229
308
 
230
309
  /**
@@ -240,9 +319,14 @@ export function createRoutePlugin(
240
319
  * - `__furinNotFound` — not-found payload
241
320
  * - `__furinRedirect` — logical path after a server-side redirect
242
321
  */
243
- export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
322
+ export function createDataEndpoint(
323
+ routesSource: DataResolvedRoutesSource,
324
+ root?: RootLayout
325
+ ): AnyElysia {
244
326
  const plugin = new Elysia();
245
- const matchRoute = buildRouteMatcher(routes);
327
+ let matchedRoutes = Array.isArray(routesSource) ? routesSource : [];
328
+ let matchRoute = buildRouteMatcher(matchedRoutes);
329
+ let searchRoutes = createSearchRouteMetadata(matchedRoutes);
246
330
 
247
331
  plugin.get(
248
332
  "/_furin/data",
@@ -266,8 +350,19 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
266
350
  const wideEventLog = useLogger();
267
351
  wideEventLog.set({ path: rawPath });
268
352
 
269
- // Precompiled at plugin creation: route regexes are built once, sorted
270
- // most-specific first, then the hot path only executes regex matches.
353
+ let currentRoutes: ResolvedRoute[];
354
+ try {
355
+ currentRoutes =
356
+ typeof routesSource === "function" ? await routesSource(ctx.request) : routesSource;
357
+ } catch (error) {
358
+ wideEventLog.error(error instanceof Error ? error : new Error(String(error)));
359
+ return createRouteDataErrorResponse(error, "Something went wrong", 500, undefined);
360
+ }
361
+ if (currentRoutes !== matchedRoutes) {
362
+ matchedRoutes = currentRoutes;
363
+ matchRoute = buildRouteMatcher(matchedRoutes);
364
+ searchRoutes = createSearchRouteMetadata(matchedRoutes);
365
+ }
271
366
  const matched = matchRoute(pathname);
272
367
 
273
368
  if (!matched) {
@@ -309,8 +404,8 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
309
404
  status: (code: number) => new Response(null, { status: code }),
310
405
  } as unknown as SyntheticDataContext;
311
406
 
312
- // Normalize params and query through the same merged schemas used by
313
- // createRoutePlugin so loaders see identical typed/defaulted inputs.
407
+ // Normalize params and query through the route chain schemas so SPA and
408
+ // document requests expose identical typed/defaulted inputs.
314
409
  const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
315
410
  const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
316
411
  const parsedParams = await parseRouteParams(matched.params, mergedParams);
@@ -332,10 +427,12 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
332
427
 
333
428
  const result = await runDataEndpointLoaders(
334
429
  matched.route,
335
- syntheticCtx as unknown as Context
430
+ syntheticCtx as unknown as Context,
431
+ root,
432
+ searchRoutes
336
433
  );
337
434
 
338
- return createLoaderDataResponse(result, matched.route, syntheticRequest.url);
435
+ return createLoaderDataResponse(result, matched.route, syntheticRequest.url, syntheticCtx);
339
436
  },
340
437
  {
341
438
  query: t.Object({ path: t.Optional(t.String()) }),
@@ -356,7 +453,7 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
356
453
  * synchronous loader data. A throwing `head()` is swallowed: a missing title
357
454
  * must never break the data response.
358
455
  */
359
- function withResolvedTitle(
456
+ function withResolvedHead(
360
457
  route: ResolvedRoute,
361
458
  syncData: Record<string, unknown>
362
459
  ): Record<string, unknown> {
@@ -364,14 +461,23 @@ function withResolvedTitle(
364
461
  if (!head) {
365
462
  return syncData;
366
463
  }
367
- let title: string | undefined;
464
+ let headOptions: HeadOptions;
368
465
  try {
369
- title = extractTitle(head(syncData).meta);
466
+ headOptions = head(syncData);
370
467
  } catch {
371
468
  return syncData;
372
469
  }
373
- if (title === undefined) {
374
- return syncData;
470
+ const title = extractTitle(headOptions.meta);
471
+ let includeHead = false;
472
+ try {
473
+ includeHead =
474
+ new TextEncoder().encode(JSON.stringify(headOptions)).byteLength <= MAX_NAVIGATION_HEAD_BYTES;
475
+ } catch {
476
+ // Invalid or cyclic metadata must not break an otherwise valid navigation.
375
477
  }
376
- return { ...syncData, __furinTitle: title };
478
+ return {
479
+ ...syncData,
480
+ ...(includeHead ? { __furinHead: headOptions } : {}),
481
+ ...(title === undefined ? {} : { __furinTitle: title }),
482
+ };
377
483
  }
@@ -1,33 +1,23 @@
1
1
  import { t } from "elysia";
2
- import type { AnySchema } from "elysia/types";
3
2
  import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
3
+ import { type FurinSchema, isTypeBoxObjectSchema } from "../../shared/elysia-contract.ts";
4
4
 
5
5
  interface SchemaObject {
6
6
  [key: string]: unknown;
7
7
  }
8
8
 
9
9
  const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
10
- const TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
11
-
12
- function isTypeBoxObjectSchema(schema: unknown): schema is SchemaObject {
13
- return (
14
- schema !== null &&
15
- typeof schema === "object" &&
16
- (schema as SchemaObject & { [key: symbol]: unknown })[TYPEBOX_KIND] === "Object"
17
- );
18
- }
19
-
20
10
  export function mergeRouteSchemas(
21
11
  routeChain: RuntimeRoute[],
22
12
  key: "params" | "query"
23
- ): AnySchema | undefined {
13
+ ): FurinSchema | undefined {
24
14
  const schemas = routeChain.flatMap((route) => (route[key] ? [route[key] as SchemaObject] : []));
25
15
 
26
16
  if (schemas.length === 0) {
27
17
  return;
28
18
  }
29
19
  if (schemas.length === 1) {
30
- return schemas[0] as AnySchema;
20
+ return schemas[0] as FurinSchema;
31
21
  }
32
22
  if (schemas.some((schema) => !isTypeBoxObjectSchema(schema))) {
33
23
  throw new Error(
@@ -48,5 +38,5 @@ export function mergeRouteSchemas(
48
38
  )
49
39
  );
50
40
 
51
- return t.Object(properties, options) as AnySchema;
41
+ return t.Object(properties, options) as FurinSchema;
52
42
  }
@@ -1,7 +1,10 @@
1
- import { parseQueryFromURL, parseQueryStandardSchema } from "elysia/parse-query";
2
- import { getSchemaValidator } from "elysia/schema";
3
- import type { AnySchema } from "elysia/types";
4
1
  import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
2
+ import {
3
+ type FurinSchema,
4
+ getSchemaValidator,
5
+ parseQueryFromURL,
6
+ parseQueryStandardSchema,
7
+ } from "../../shared/elysia-contract.ts";
5
8
  import {
6
9
  collectSearchDefaults,
7
10
  type SearchParamsInput,
@@ -140,7 +143,7 @@ type RouteInputValidationResult =
140
143
 
141
144
  async function validateRouteInput(
142
145
  input: UnknownObject,
143
- schema: AnySchema
146
+ schema: FurinSchema
144
147
  ): Promise<RouteInputValidationResult> {
145
148
  if (isStandardSchema(schema)) {
146
149
  const validator = getSchemaValidator(schema, { dynamic: true });
@@ -175,7 +178,7 @@ async function validateRouteInput(
175
178
  */
176
179
  export async function parseRouteQuery(
177
180
  url: URL,
178
- schema: AnySchema | undefined
181
+ schema: FurinSchema | undefined
179
182
  ): Promise<ParseRouteQueryResult> {
180
183
  if (!schema) {
181
184
  return { ok: true, query: parseQueryFromURL(url.search, 1) as SearchParamsInput };
@@ -193,14 +196,14 @@ export async function parseRouteQuery(
193
196
 
194
197
  /**
195
198
  * Validates and coerces path params for the synthetic `/_furin/data` request
196
- * path. This mirrors the params schema installed by createRoutePlugin's Elysia
197
- * guard so SPA loaders receive the same values as full SSR loaders.
199
+ * path. This mirrors the composed Elysia route schema so SPA loaders receive
200
+ * the same values as full SSR loaders.
198
201
  *
199
202
  * @internal Exported for unit testing.
200
203
  */
201
204
  export async function parseRouteParams(
202
205
  params: UnknownObject,
203
- schema: AnySchema | undefined
206
+ schema: FurinSchema | undefined
204
207
  ): Promise<ParseRouteParamsResult> {
205
208
  if (!schema) {
206
209
  return { ok: true, params };
@@ -0,0 +1,9 @@
1
+ import { devGraph } from "../dev/graph.ts";
2
+
3
+ export function routeModuleSourceVersion(path: string): string {
4
+ return devGraph(undefined).sourceVersion(path);
5
+ }
6
+
7
+ export function invalidateRouteModuleSourceVersions(): void {
8
+ devGraph(undefined).invalidateModules();
9
+ }
@@ -49,6 +49,8 @@ export interface ResolvedRoute {
49
49
  tags?: string[];
50
50
  }
51
51
 
52
+ export type ResolvedRoutesSource = ResolvedRoute[] | (() => ResolvedRoute[]);
53
+
52
54
  export interface RootLayout {
53
55
  error?: ErrorComponent;
54
56
  errorPath?: string;
@@ -58,6 +58,10 @@ export interface SyncAdapter {
58
58
  beginMutation: (input: BeginMutationInput) => Promise<BeginMutationResult>;
59
59
  completeMutation: (input: CompleteMutationInput) => Promise<CompleteMutationResult>;
60
60
  currentCursor: () => Promise<string>;
61
+ /**
62
+ * Identifies a notification channel published transactionally by completeMutation.
63
+ */
64
+ readonly notificationChannel?: string;
61
65
  readChanges: (input: ReadChangesInput) => Promise<ChangePage>;
62
66
  renewMutation: (lease: MutationLease) => Promise<"lost" | "renewed">;
63
67
  readonly scope: "distributed" | "host-local" | "process-local";
@@ -68,7 +72,16 @@ export interface SyncSubscription {
68
72
  }
69
73
 
70
74
  export interface SyncNotifier {
75
+ /**
76
+ * Matches a SyncAdapter channel when durable completion already publishes the wake-up.
77
+ */
78
+ readonly notificationChannel?: string;
71
79
  publish: (cursor: string) => Promise<void>;
80
+ /**
81
+ * Declares that the notifier independently recovers missed wake-ups, so the
82
+ * SSE coordinator does not need its compatibility safety poll.
83
+ */
84
+ readonly recovery?: "self";
72
85
  subscribe: (listener: (cursor: string) => void) => Promise<SyncSubscription>;
73
86
  }
74
87
 
@@ -2,39 +2,39 @@ import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { currentInstance } from "../instance.ts";
3
3
  import type { SyncRuntimeOptions } from "./adapter.ts";
4
4
 
5
- const SYNC_STREAM_DEFAULT_PATH = "/_furin/sync";
5
+ const SYNC_DEFAULT_PATH = "/_furin/sync";
6
6
 
7
7
  // Explicit override scope (tests, synthetic renders). When unset, the sync
8
- // stream path comes from the current furin instance.
9
- const requestSyncStreamPath = new AsyncLocalStorage<string | undefined>();
8
+ // path comes from the current furin instance.
9
+ const requestSyncPath = new AsyncLocalStorage<string | undefined>();
10
10
 
11
11
  export interface FurinSyncOptions extends SyncRuntimeOptions {
12
- streamPath?: string;
12
+ path?: string;
13
13
  }
14
14
 
15
15
  export type FurinSyncOption = FurinSyncOptions | false;
16
16
 
17
- export function resolveSyncStreamPath(sync: FurinSyncOption | undefined): string | undefined {
17
+ export function resolveSyncPath(sync: FurinSyncOption | undefined): string | undefined {
18
18
  if (!sync) {
19
19
  return;
20
20
  }
21
- return sync.streamPath ?? SYNC_STREAM_DEFAULT_PATH;
21
+ return sync.path ?? SYNC_DEFAULT_PATH;
22
22
  }
23
23
 
24
24
  /**
25
- * Logical (unprefixed) sync stream path for the current request — injected
25
+ * Logical (unprefixed) sync path for the current request — injected
26
26
  * into rendered HTML; the client prepends its own basePath before connecting.
27
27
  */
28
- export function getSyncStreamPath(): string | undefined {
29
- const override = requestSyncStreamPath.getStore();
28
+ export function getSyncPath(): string | undefined {
29
+ const override = requestSyncPath.getStore();
30
30
  if (override !== undefined) {
31
31
  return override;
32
32
  }
33
- return currentInstance().syncStreamPath;
33
+ return currentInstance().syncPath;
34
34
  }
35
35
 
36
- export function runWithSyncStreamPath<T>(path: string | undefined, fn: () => T): T {
37
- return requestSyncStreamPath.run(path, fn);
36
+ export function runWithSyncPath<T>(path: string | undefined, fn: () => T): T {
37
+ return requestSyncPath.run(path, fn);
38
38
  }
39
39
 
40
40
  export function syncRuntimeOptions(sync: FurinSyncOptions): SyncRuntimeOptions {
@@ -1,20 +1,20 @@
1
1
  // biome-ignore-all lint/performance/noBarrelFile: sync has a small public/internal surface
2
2
 
3
3
  import {
4
- getSyncStreamPath as getSyncStreamPathImplementation,
5
- resolveSyncStreamPath as resolveSyncStreamPathImplementation,
6
- runWithSyncStreamPath as runWithSyncStreamPathImplementation,
4
+ getSyncPath as getSyncPathImplementation,
5
+ resolveSyncPath as resolveSyncPathImplementation,
6
+ runWithSyncPath as runWithSyncPathImplementation,
7
7
  } from "./config.ts";
8
8
  import { PollingSyncNotifier as PollingSyncNotifierImplementation } from "./notifier.ts";
9
9
  import { furinSync as furinSyncImplementation } from "./plugin.ts";
10
- import { createSyncStreamPlugin as createSyncStreamPluginImplementation } from "./stream.ts";
10
+ import { createSyncChangesPlugin as createSyncChangesPluginImplementation } from "./stream.ts";
11
11
 
12
- export const createSyncStreamPlugin = createSyncStreamPluginImplementation;
12
+ export const createSyncChangesPlugin = createSyncChangesPluginImplementation;
13
13
  export const furinSync = furinSyncImplementation;
14
- export const getSyncStreamPath = getSyncStreamPathImplementation;
14
+ export const getSyncPath = getSyncPathImplementation;
15
15
  export const PollingSyncNotifier = PollingSyncNotifierImplementation;
16
- export const resolveSyncStreamPath = resolveSyncStreamPathImplementation;
17
- export const runWithSyncStreamPath = runWithSyncStreamPathImplementation;
16
+ export const resolveSyncPath = resolveSyncPathImplementation;
17
+ export const runWithSyncPath = runWithSyncPathImplementation;
18
18
 
19
19
  export type PollingSyncNotifier = PollingSyncNotifierImplementation;
20
20
 
@@ -5,6 +5,7 @@ interface ListenerSubscription {
5
5
  }
6
6
 
7
7
  export class PollingSyncNotifier implements SyncNotifier {
8
+ readonly recovery = "self" as const;
8
9
  private readonly adapter: SyncAdapter;
9
10
  private readonly intervalMs: number;
10
11
  private readonly listeners = new Set<ListenerSubscription>();
@@ -240,7 +240,10 @@ export function furinSync(options: SyncRuntimeOptions) {
240
240
  if (completion.kind === "lost") {
241
241
  return leaseLostResponse();
242
242
  }
243
- if (completion.cursor !== undefined) {
243
+ const notificationAlreadyPublished =
244
+ runtime.adapter.notificationChannel !== undefined &&
245
+ runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
246
+ if (completion.cursor !== undefined && !notificationAlreadyPublished) {
244
247
  runtime.notifier.publish(completion.cursor).catch(() => undefined);
245
248
  }
246
249
  if (result.kind === "unreplayable") {