@teyik0/furin 0.2.0-alpha.4 → 0.3.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 (263) hide show
  1. package/README.md +2 -3
  2. package/dist/adapter/bun.d.ts +17 -1
  3. package/dist/adapter/package.d.ts +26 -0
  4. package/dist/adapter/static.d.ts +1 -1
  5. package/dist/build/bun-build.d.ts +3 -0
  6. package/dist/build/client.d.ts +1 -1
  7. package/dist/build/compile-entry.d.ts +3 -3
  8. package/dist/build/compile-entry.ts +88 -83
  9. package/dist/build/entry-template.d.ts +37 -9
  10. package/dist/build/entry-template.ts +109 -56
  11. package/dist/build/hydrate.d.ts +2 -2
  12. package/dist/build/index.js +6817 -4544
  13. package/dist/build/production-instrumentation.d.ts +1 -0
  14. package/dist/build/route-types.d.ts +1 -1
  15. package/dist/build/scan-server.d.ts +10 -4
  16. package/dist/build/server-routes-entry.d.ts +3 -3
  17. package/dist/build/server-routes-entry.ts +5 -11
  18. package/dist/build/ssg-cache.d.ts +1 -1
  19. package/dist/build/types.d.ts +37 -1
  20. package/dist/cli/config.d.ts +6 -1
  21. package/dist/cli/index.js +6854 -4549
  22. package/dist/client/boundaries.d.ts +4 -4
  23. package/dist/client/internal/runtime-types.d.ts +30 -0
  24. package/dist/client/link.d.ts +2 -1
  25. package/dist/client/link.js +712 -338
  26. package/dist/client/router/boundary-tree.d.ts +1 -1
  27. package/dist/client/router/index.d.ts +1 -1
  28. package/dist/client/router/link-utils.d.ts +5 -1
  29. package/dist/client/router/sync-catch-up.d.ts +4 -4
  30. package/dist/client/router/types.d.ts +2 -2
  31. package/dist/client-only.d.ts +1 -0
  32. package/dist/client-only.js +1 -0
  33. package/dist/client.d.ts +108 -111
  34. package/dist/client.js +16 -17
  35. package/dist/config.d.ts +11 -2
  36. package/dist/config.js +7 -3
  37. package/dist/devtools/devtools-element.d.ts +1 -0
  38. package/dist/devtools/protocol.d.ts +119 -0
  39. package/dist/furin.d.ts +40 -21
  40. package/dist/furin.js +7198 -3518
  41. package/dist/isomorphic.d.ts +18 -0
  42. package/dist/plugin/binding-scope.d.ts +2 -0
  43. package/dist/plugin/dead-code-elimination.d.ts +3 -0
  44. package/dist/plugin/index.js +933 -423
  45. package/dist/plugin/transform-client.d.ts +0 -2
  46. package/dist/plugin/transform-isomorphic.d.ts +9 -0
  47. package/dist/rsc/build/environment.d.ts +2 -0
  48. package/dist/rsc/build/index.d.ts +15 -0
  49. package/dist/rsc/client-codec.d.ts +1 -0
  50. package/dist/rsc/codec.d.ts +4 -0
  51. package/dist/rsc/flight-drain.d.ts +11 -0
  52. package/dist/rsc/render-error.d.ts +17 -0
  53. package/dist/rsc/server-codec.d.ts +2 -0
  54. package/dist/rsc/server-codec.js +24 -0
  55. package/dist/rsc/shared.d.ts +30 -0
  56. package/dist/rsc/symbols.d.ts +2 -0
  57. package/dist/rsc/transport-benchmark.d.ts +13 -0
  58. package/dist/rsc/version.d.ts +7 -0
  59. package/dist/rsc-client.d.ts +4 -0
  60. package/dist/rsc-client.js +166 -0
  61. package/dist/rsc-server.d.ts +11 -0
  62. package/dist/rsc.d.ts +11 -0
  63. package/dist/rsc.js +353 -0
  64. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  65. package/dist/server/cache/dev-loader.d.ts +3 -2
  66. package/dist/server/cache/index.d.ts +2 -2
  67. package/dist/server/cache/invalidation.d.ts +20 -2
  68. package/dist/server/cache/isr-ssg.d.ts +5 -1
  69. package/dist/server/cache/isr.d.ts +15 -2
  70. package/dist/server/cache/registry.d.ts +3 -3
  71. package/dist/server/cache/route-cache.d.ts +10 -8
  72. package/dist/server/cache/ssg.d.ts +6 -2
  73. package/dist/server/cache/store-view.d.ts +11 -0
  74. package/dist/server/dev-page-plugin.d.ts +4 -0
  75. package/dist/server/devtools/hub.d.ts +11 -0
  76. package/dist/server/devtools/instrumentation.d.ts +22 -0
  77. package/dist/server/devtools/instrumentation.production.d.ts +44 -0
  78. package/dist/server/devtools/plugin.d.ts +3 -0
  79. package/dist/server/devtools/request-context.d.ts +6 -0
  80. package/dist/server/instance.d.ts +86 -0
  81. package/dist/server/internal.d.ts +18 -1
  82. package/dist/server/internal.js +74 -7
  83. package/dist/server/lang-detect.d.ts +1 -0
  84. package/dist/server/render/assemble.d.ts +4 -0
  85. package/dist/server/render/element.d.ts +1 -1
  86. package/dist/server/render/index.d.ts +2 -2
  87. package/dist/server/render/index.ts +6 -2
  88. package/dist/server/render/loaders.d.ts +8 -0
  89. package/dist/server/render/not-found.d.ts +1 -1
  90. package/dist/server/render/ppr-route.d.ts +8 -0
  91. package/dist/server/render/route-frame-transport.d.ts +2 -0
  92. package/dist/server/render/shell.ts +0 -1
  93. package/dist/server/render/ssr.d.ts +2 -3
  94. package/dist/server/render/template.d.ts +3 -2
  95. package/dist/server/router/discovery.d.ts +1 -1
  96. package/dist/server/router/hmr.d.ts +1 -1
  97. package/dist/server/router/index.d.ts +2 -1
  98. package/dist/server/router/index.js +23 -23
  99. package/dist/server/router/index.ts +1 -1
  100. package/dist/server/router/patterns.d.ts +1 -1
  101. package/dist/server/router/plugin.d.ts +4 -7
  102. package/dist/server/router/schema-merge.d.ts +3 -0
  103. package/dist/server/router/schemas.d.ts +12 -7
  104. package/dist/server/router/types.d.ts +1 -1
  105. package/dist/server/runtime-env.js +2 -2
  106. package/dist/server/sync/adapter.d.ts +45 -26
  107. package/dist/server/sync/config.d.ts +9 -2
  108. package/dist/server/sync/fingerprint.d.ts +2 -1
  109. package/dist/server/sync/index.d.ts +15 -4
  110. package/dist/server/sync/index.js +2868 -0
  111. package/dist/server/sync/notifier.d.ts +18 -0
  112. package/dist/server/sync/plugin.d.ts +53 -54
  113. package/dist/server/sync/postgres/index.d.ts +19 -0
  114. package/dist/server/sync/postgres/index.js +252 -0
  115. package/dist/server/sync/postgres/migrate.d.ts +2 -0
  116. package/dist/server/sync/postgres/migrate.js +16 -0
  117. package/dist/server/sync/postgres/migration.sql +66 -0
  118. package/dist/server/sync/redis/index.d.ts +30 -0
  119. package/dist/server/sync/redis/index.js +336 -0
  120. package/dist/server/sync/redis/scripts.d.ts +4 -0
  121. package/dist/server/sync/response.d.ts +10 -1
  122. package/dist/server/sync/runtime.d.ts +6 -0
  123. package/dist/server/sync/sqlite/index.d.ts +20 -0
  124. package/dist/server/sync/sqlite/index.js +250 -0
  125. package/dist/server/sync/stream.d.ts +12 -4
  126. package/dist/server-only.d.ts +1 -0
  127. package/dist/server-only.js +1 -0
  128. package/dist/shared/parser.d.ts +2 -0
  129. package/dist/shared/prefix.d.ts +15 -0
  130. package/dist/shared/route-frame.d.ts +49 -0
  131. package/dist/shared/utils/index.d.ts +1 -1
  132. package/package.json +59 -12
  133. package/src/adapter/bun.ts +175 -55
  134. package/src/adapter/package.ts +208 -0
  135. package/src/adapter/static.ts +94 -48
  136. package/src/build/bun-build.ts +11 -0
  137. package/src/build/client.ts +31 -27
  138. package/src/build/compile-entry.ts +88 -83
  139. package/src/build/entry-template.ts +109 -56
  140. package/src/build/hydrate.ts +37 -10
  141. package/src/build/index.ts +111 -28
  142. package/src/build/production-instrumentation.ts +14 -0
  143. package/src/build/route-types.ts +7 -8
  144. package/src/build/scan-server.ts +26 -9
  145. package/src/build/server-routes-entry.ts +5 -11
  146. package/src/build/ssg-cache.ts +13 -4
  147. package/src/build/types.ts +38 -1
  148. package/src/cli/config.ts +9 -3
  149. package/src/cli/index.ts +73 -24
  150. package/src/client/boundaries.tsx +42 -18
  151. package/src/client/default-screens.tsx +4 -4
  152. package/src/client/internal/runtime-types.ts +31 -0
  153. package/src/client/link.tsx +35 -37
  154. package/src/client/router/boundary-tree.tsx +2 -2
  155. package/src/client/router/context.ts +13 -9
  156. package/src/client/router/index.ts +3 -0
  157. package/src/client/router/link-utils.ts +66 -3
  158. package/src/client/router/navigation.ts +9 -15
  159. package/src/client/router/provider.tsx +74 -52
  160. package/src/client/router/search/index.ts +5 -7
  161. package/src/client/router/search-store.ts +5 -1
  162. package/src/client/router/spa-response.ts +3 -4
  163. package/src/client/router/sync-catch-up.ts +9 -8
  164. package/src/client/router/types.ts +2 -2
  165. package/src/client/sync.ts +3 -2
  166. package/src/client-only.ts +1 -0
  167. package/src/client.ts +221 -174
  168. package/src/config.ts +14 -1
  169. package/src/devtools/devtools-element.js +884 -0
  170. package/src/devtools/protocol.ts +139 -0
  171. package/src/furin.ts +414 -171
  172. package/src/isomorphic.ts +66 -0
  173. package/src/plugin/binding-scope.ts +158 -0
  174. package/src/plugin/dead-code-elimination.ts +202 -0
  175. package/src/plugin/index.ts +14 -18
  176. package/src/plugin/transform-client.ts +237 -273
  177. package/src/plugin/transform-isomorphic.ts +464 -0
  178. package/src/rsc/build/environment.ts +30 -0
  179. package/src/rsc/build/index.ts +94 -0
  180. package/src/rsc/client-codec.ts +11 -0
  181. package/src/rsc/codec.ts +85 -0
  182. package/src/rsc/flight-drain.ts +68 -0
  183. package/src/rsc/react-server-dom-webpack.d.ts +23 -0
  184. package/src/rsc/render-error.ts +120 -0
  185. package/src/rsc/server-codec.ts +25 -0
  186. package/src/rsc/shared.tsx +113 -0
  187. package/src/rsc/symbols.ts +2 -0
  188. package/src/rsc/transport-benchmark.ts +73 -0
  189. package/src/rsc/version.ts +57 -0
  190. package/src/rsc-client.ts +12 -0
  191. package/src/rsc-server.tsx +91 -0
  192. package/src/rsc.tsx +75 -0
  193. package/src/server/auto-invalidate/registry.ts +23 -1
  194. package/src/server/auto-invalidate/runtime.ts +58 -7
  195. package/src/server/cache/dev-loader.ts +143 -44
  196. package/src/server/cache/index.ts +7 -3
  197. package/src/server/cache/invalidation.ts +100 -41
  198. package/src/server/cache/isr-ssg.ts +12 -3
  199. package/src/server/cache/isr.ts +95 -5
  200. package/src/server/cache/registry.ts +17 -20
  201. package/src/server/cache/route-cache.ts +49 -36
  202. package/src/server/cache/ssg.ts +19 -4
  203. package/src/server/cache/store-view.ts +30 -0
  204. package/src/server/context-logger.ts +7 -7
  205. package/src/server/dev-page-plugin.ts +8 -6
  206. package/src/server/devtools/hub.ts +64 -0
  207. package/src/server/devtools/instrumentation.production.ts +80 -0
  208. package/src/server/devtools/instrumentation.ts +72 -0
  209. package/src/server/devtools/plugin.ts +267 -0
  210. package/src/server/devtools/request-context.ts +76 -0
  211. package/src/server/instance.ts +252 -0
  212. package/src/server/internal.ts +102 -5
  213. package/src/server/lang-detect.ts +14 -10
  214. package/src/server/render/assemble.ts +73 -10
  215. package/src/server/render/element.tsx +11 -8
  216. package/src/server/render/index.ts +6 -2
  217. package/src/server/render/isr.ts +154 -110
  218. package/src/server/render/loaders.ts +259 -45
  219. package/src/server/render/not-found.ts +18 -17
  220. package/src/server/render/ppr-route.ts +146 -0
  221. package/src/server/render/route-frame-transport.ts +62 -0
  222. package/src/server/render/shell.ts +0 -1
  223. package/src/server/render/ssg.ts +6 -5
  224. package/src/server/render/ssr.ts +170 -70
  225. package/src/server/render/template.ts +59 -25
  226. package/src/server/router/discovery.ts +39 -22
  227. package/src/server/router/hmr.ts +15 -13
  228. package/src/server/router/index.ts +1 -1
  229. package/src/server/router/patterns.ts +16 -15
  230. package/src/server/router/plugin.ts +151 -158
  231. package/src/server/router/schema-merge.ts +52 -0
  232. package/src/server/router/schemas.ts +55 -73
  233. package/src/server/router/types.ts +1 -1
  234. package/src/server/sync/adapter.ts +44 -28
  235. package/src/server/sync/config.ts +22 -9
  236. package/src/server/sync/fingerprint.ts +8 -3
  237. package/src/server/sync/index.ts +37 -13
  238. package/src/server/sync/notifier.ts +109 -0
  239. package/src/server/sync/plugin.ts +184 -90
  240. package/src/server/sync/postgres/index.ts +301 -0
  241. package/src/server/sync/postgres/migrate.ts +15 -0
  242. package/src/server/sync/postgres/migration.sql +66 -0
  243. package/src/server/sync/redis/index.ts +342 -0
  244. package/src/server/sync/redis/scripts.ts +74 -0
  245. package/src/server/sync/response.ts +141 -16
  246. package/src/server/sync/runtime.ts +27 -0
  247. package/src/server/sync/sql.d.ts +4 -0
  248. package/src/server/sync/sqlite/index.ts +337 -0
  249. package/src/server/sync/sqlite/migration.sql +70 -0
  250. package/src/server/sync/stream.ts +136 -70
  251. package/src/server-only.ts +1 -0
  252. package/src/shared/await.tsx +4 -4
  253. package/src/shared/deferred-ndjson.ts +34 -6
  254. package/src/shared/digest.ts +2 -2
  255. package/src/shared/parser.ts +5 -0
  256. package/src/shared/prefix.ts +38 -0
  257. package/src/shared/route-frame.ts +429 -0
  258. package/src/shared/search-params.ts +7 -7
  259. package/src/shared/utils/index.ts +5 -3
  260. package/dist/server/dev-inspector.d.ts +0 -89
  261. package/dist/server/sync/memory-adapter.d.ts +0 -17
  262. package/src/server/dev-inspector.ts +0 -60
  263. package/src/server/sync/memory-adapter.ts +0 -196
@@ -1,35 +1,137 @@
1
1
  import { type AnyElysia, type Context, Elysia, t } from "elysia";
2
2
  import type { AnySchema } from "elysia/types";
3
- import { toCrossJSON, toCrossJSONAsync } from "seroval";
3
+ import { toCrossJSONAsync } from "seroval";
4
4
  import { computeErrorDigest } from "../../shared/digest.ts";
5
+ import { containsRscSource, serializeRouteFrames } from "../../shared/route-frame.ts";
5
6
  import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
6
- import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
7
7
  import { useLogger } from "../context-logger.ts";
8
+ import {
9
+ currentInstrumentationRequest,
10
+ emitPayloadSerialized,
11
+ } from "../devtools/instrumentation.ts";
8
12
  import { injectSyncRuntimeScript, resolvePath } from "../render/assemble.ts";
13
+ import { handleISR } from "../render/isr.ts";
9
14
  import {
10
- handleISR,
11
- prerenderSSG,
12
- renderSSR,
15
+ hasRequestLoader,
16
+ type LoaderResult,
13
17
  runLoaders,
14
- serializeDeferredRejection,
15
- } from "../render/index.ts";
18
+ runPublicLoaders,
19
+ withRequestLoaderData,
20
+ } from "../render/loaders.ts";
21
+ import { renderPprRoute } from "../render/ppr-route.ts";
22
+ import { createDeferredRouteFrameStream } from "../render/route-frame-transport.ts";
16
23
  import { extractTitle } from "../render/shell.ts";
24
+ import { prerenderSSG } from "../render/ssg.ts";
25
+ import { renderSSR } from "../render/ssr.ts";
17
26
  import { IS_DEV } from "../runtime-env.ts";
18
27
  import { handleDevRequest } from "./hmr.ts";
19
28
  import { buildRouteMatcher } from "./patterns.ts";
20
- import {
21
- applySchemaDefaults,
22
- mergeRouteSchemas,
23
- parseDataEndpointPath,
24
- parseRouteQuery,
25
- } from "./schemas.ts";
29
+ import { mergeRouteSchemas } from "./schema-merge.ts";
30
+ import { parseDataEndpointPath, parseRouteParams, parseRouteQuery } from "./schemas.ts";
26
31
  import type { ResolvedRoute, RootLayout } from "./types.ts";
27
32
 
33
+ interface DataRouteParamsInput {
34
+ [key: string]: unknown;
35
+ }
36
+
28
37
  type SyntheticDataContext = Omit<Context, "params" | "query"> & {
29
- params: Record<string, string>;
38
+ params: DataRouteParamsInput;
30
39
  query: SearchParamsInput;
31
40
  };
32
41
 
42
+ function emitSerializedPayload(body: string, kind: "route-data" | "rsc", requestUrl: string): void {
43
+ if (!IS_DEV) {
44
+ return;
45
+ }
46
+ const request = currentInstrumentationRequest();
47
+ if (request === undefined) {
48
+ return;
49
+ }
50
+ emitPayloadSerialized({
51
+ bytes: new TextEncoder().encode(body).byteLength,
52
+ kind,
53
+ operationId: request.operationId,
54
+ path: new URL(requestUrl).pathname,
55
+ requestId: request.requestId,
56
+ });
57
+ }
58
+
59
+ async function runDataEndpointLoaders(route: ResolvedRoute, ctx: Context): Promise<LoaderResult> {
60
+ if (route.mode !== "isr" && route.mode !== "ssg") {
61
+ return runLoaders(route, ctx);
62
+ }
63
+
64
+ const result = await runPublicLoaders(route, ctx);
65
+ if (result.type !== "data" || !hasRequestLoader(route)) {
66
+ return result;
67
+ }
68
+ return withRequestLoaderData(route, ctx, result);
69
+ }
70
+
71
+ async function createLoaderDataResponse(
72
+ result: LoaderResult,
73
+ route: ResolvedRoute,
74
+ requestUrl: string
75
+ ): Promise<Response> {
76
+ if (result.type === "redirect") {
77
+ const redirectUrl = new URL(result.response.headers.get("location") ?? "/", requestUrl);
78
+ const serialized = await toCrossJSONAsync({
79
+ __furinRedirect: redirectUrl.pathname + redirectUrl.search,
80
+ });
81
+ return new Response(`${JSON.stringify(serialized)}\n`, {
82
+ headers: { "content-type": "application/x-ndjson" },
83
+ });
84
+ }
85
+ if (result.type === "not-found") {
86
+ const serialized = await toCrossJSONAsync({
87
+ __furinNotFound: { data: result.error.data, message: result.error.message },
88
+ __furinStatus: 404,
89
+ });
90
+ return new Response(`${JSON.stringify(serialized)}\n`, {
91
+ headers: { "content-type": "application/x-ndjson" },
92
+ status: 200,
93
+ });
94
+ }
95
+ 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
+ });
107
+ }
108
+
109
+ const syncDataWithTitle = withResolvedTitle(route, result.syncData);
110
+ if (result.deferredPromises !== undefined) {
111
+ return new Response(
112
+ createDeferredRouteFrameStream(syncDataWithTitle, result.deferredPromises),
113
+ {
114
+ headers: {
115
+ ...result.headers,
116
+ "content-type": "application/x-furin-route",
117
+ },
118
+ }
119
+ );
120
+ }
121
+ const body = serializeRouteFrames(syncDataWithTitle, undefined);
122
+ emitSerializedPayload(
123
+ body,
124
+ containsRscSource(syncDataWithTitle) ? "rsc" : "route-data",
125
+ requestUrl
126
+ );
127
+ return new Response(body, {
128
+ headers: {
129
+ ...result.headers,
130
+ "content-type": "application/x-furin-route",
131
+ },
132
+ });
133
+ }
134
+
33
135
  /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
34
136
  async function handleSSGRequest(
35
137
  route: ResolvedRoute,
@@ -38,8 +140,8 @@ async function handleSSGRequest(
38
140
  buildId: string,
39
141
  searchRoutes: SearchRouteMetadata[] | undefined
40
142
  ): Promise<unknown> {
41
- const origin = new URL(ctx.request.url).origin;
42
- const entry = await prerenderSSG(route, ctx.params, root, origin, undefined, searchRoutes);
143
+ const { origin } = new URL(ctx.request.url);
144
+ const entry = await prerenderSSG(route, ctx.params ?? {}, root, origin, undefined, searchRoutes);
43
145
 
44
146
  // Loader issued a redirect — forward it directly to the client.
45
147
  if (entry instanceof Response) {
@@ -106,6 +208,10 @@ export function createRoutePlugin(
106
208
  return handleDevRequest(route, ctx, root, searchRoutes);
107
209
  }
108
210
 
211
+ if ((route.mode === "ssg" || route.mode === "isr") && hasRequestLoader(route)) {
212
+ return renderPprRoute(route, ctx, root, resolvedBuildId, searchRoutes);
213
+ }
214
+
109
215
  if (route.mode === "ssg") {
110
216
  return handleSSGRequest(route, ctx, root, resolvedBuildId, searchRoutes);
111
217
  }
@@ -124,13 +230,10 @@ export function createRoutePlugin(
124
230
  /**
125
231
  * Elysia plugin that handles `GET /_furin/data?path=<logicalHref>`.
126
232
  *
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`.
233
+ * Returns route-frame loader data for successful routes. Deferred routes stream
234
+ * the initial sync frame first, then append one frame batch per settled Promise.
235
+ * SPA navigation calls this endpoint via `parseDeferredNdjson`, which supports
236
+ * both route frames and legacy NDJSON sentinels.
134
237
  *
135
238
  * Special fields emitted alongside data:
136
239
  * - `__furinStatus: 404` — when the loader called `notFound()`
@@ -180,21 +283,25 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
180
283
  // Build the synthetic URL from the parsed `pathname + search` only —
181
284
  // never from `rawPath` directly — so an attacker cannot smuggle a
182
285
  // foreign origin into `syntheticRequest.url`.
183
- const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
286
+ // Forward the real request headers (cookies, auth) so loaders reading
287
+ // `request.headers` behave the same during SPA navigation as in SSR.
288
+ const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url), {
289
+ headers: ctx.request.headers,
290
+ });
184
291
  const syntheticSet = { headers: {} as Record<string, string>, status: 200 as number };
185
292
  const syntheticCtx: SyntheticDataContext = {
186
- request: syntheticRequest,
187
- params: matched.params,
188
- query: Object.fromEntries(url.searchParams),
189
- set: syntheticSet,
190
- headers: ctx.headers,
191
293
  cookie: ctx.cookie,
294
+ headers: ctx.headers,
295
+ params: matched.params,
192
296
  path: pathname,
297
+ query: Object.fromEntries(url.searchParams),
193
298
  // Loader-emitted redirects flow through `runLoaders` → `result.type
194
299
  // === "redirect"` and are converted to NDJSON below. The Response we
195
300
  // return here only has to be detectable by that pipeline.
196
301
  redirect: (location: string, status?: number) =>
197
- new Response(null, { status: status ?? 302, headers: { location } }),
302
+ new Response(null, { headers: { location }, status: status ?? 302 }),
303
+ request: syntheticRequest,
304
+ set: syntheticSet,
198
305
  // Synthetic `status` helper: numeric codes only. Callers that reach
199
306
  // this endpoint never dispatch a string-keyed status; rejecting them
200
307
  // is safer than coercing via `Number(code)` and silently producing
@@ -206,6 +313,13 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
206
313
  // createRoutePlugin so loaders see identical typed/defaulted inputs.
207
314
  const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
208
315
  const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
316
+ const parsedParams = await parseRouteParams(matched.params, mergedParams);
317
+ if (!parsedParams.ok) {
318
+ return Response.json(
319
+ { errors: parsedParams.errors, message: "Invalid params", type: "validation" },
320
+ { status: 422 }
321
+ );
322
+ }
209
323
  const parsedQuery = await parseRouteQuery(url, mergedQuery);
210
324
  if (!parsedQuery.ok) {
211
325
  return Response.json(
@@ -213,100 +327,15 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
213
327
  { status: 422 }
214
328
  );
215
329
  }
216
- syntheticCtx.params = applySchemaDefaults(
217
- mergedParams as Record<string, unknown> | undefined,
218
- syntheticCtx.params as Record<string, unknown>
219
- ) as Record<string, string>;
330
+ syntheticCtx.params = parsedParams.params;
220
331
  syntheticCtx.query = parsedQuery.query as SearchParamsInput;
221
332
 
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
- }
333
+ const result = await runDataEndpointLoaders(
334
+ matched.route,
335
+ syntheticCtx as unknown as Context
336
+ );
301
337
 
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
- });
338
+ return createLoaderDataResponse(result, matched.route, syntheticRequest.url);
310
339
  },
311
340
  {
312
341
  query: t.Object({ path: t.Optional(t.String()) }),
@@ -331,7 +360,7 @@ function withResolvedTitle(
331
360
  route: ResolvedRoute,
332
361
  syncData: Record<string, unknown>
333
362
  ): Record<string, unknown> {
334
- const head = route.page.head;
363
+ const { head } = route.page;
335
364
  if (!head) {
336
365
  return syncData;
337
366
  }
@@ -346,39 +375,3 @@ function withResolvedTitle(
346
375
  }
347
376
  return { ...syncData, __furinTitle: title };
348
377
  }
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
- }
@@ -0,0 +1,52 @@
1
+ import { t } from "elysia";
2
+ import type { AnySchema } from "elysia/types";
3
+ import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
4
+
5
+ interface SchemaObject {
6
+ [key: string]: unknown;
7
+ }
8
+
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
+ export function mergeRouteSchemas(
21
+ routeChain: RuntimeRoute[],
22
+ key: "params" | "query"
23
+ ): AnySchema | undefined {
24
+ const schemas = routeChain.flatMap((route) => (route[key] ? [route[key] as SchemaObject] : []));
25
+
26
+ if (schemas.length === 0) {
27
+ return;
28
+ }
29
+ if (schemas.length === 1) {
30
+ return schemas[0] as AnySchema;
31
+ }
32
+ if (schemas.some((schema) => !isTypeBoxObjectSchema(schema))) {
33
+ throw new Error(
34
+ `[furin] Merging ${key} schemas across the route chain requires TypeBox in V1. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`
35
+ );
36
+ }
37
+
38
+ const properties = Object.assign(
39
+ {},
40
+ ...schemas.map((schema) => schema.properties as SchemaObject)
41
+ );
42
+ const options = Object.assign(
43
+ {},
44
+ ...schemas.map((schema) =>
45
+ Object.fromEntries(
46
+ Object.entries(schema).filter(([name]) => !TOBJECT_STRUCTURAL_KEYS.has(name))
47
+ )
48
+ )
49
+ );
50
+
51
+ return t.Object(properties, options) as AnySchema;
52
+ }
@@ -1,8 +1,7 @@
1
- import { t } from "elysia";
2
1
  import { parseQueryFromURL, parseQueryStandardSchema } from "elysia/parse-query";
3
2
  import { getSchemaValidator } from "elysia/schema";
4
3
  import type { AnySchema } from "elysia/types";
5
- import type { RuntimeRoute } from "../../client.ts";
4
+ import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
6
5
  import {
7
6
  collectSearchDefaults,
8
7
  type SearchParamsInput,
@@ -10,6 +9,8 @@ import {
10
9
  } from "../../shared/search-params.ts";
11
10
  import { buildRouteRegex } from "./patterns.ts";
12
11
 
12
+ import { mergeRouteSchemas } from "./schema-merge.ts";
13
+
13
14
  interface UnknownObject {
14
15
  [key: string]: unknown;
15
16
  }
@@ -44,7 +45,7 @@ export function parseDataEndpointPath(rawPath: string): { url: URL; pathname: st
44
45
  if (url.origin !== "http://localhost") {
45
46
  return;
46
47
  }
47
- return { url, pathname: url.pathname };
48
+ return { pathname: url.pathname, url };
48
49
  }
49
50
 
50
51
  function isObjectSchema(schema: unknown): schema is UnknownObject {
@@ -129,103 +130,84 @@ export type ParseRouteQueryResult =
129
130
  | { ok: true; query: SearchParamsInput }
130
131
  | { errors: unknown; ok: false };
131
132
 
132
- /**
133
- * Parses and validates a logical route URL's search string for the synthetic
134
- * `/_furin/data` request path. This keeps SPA navigations aligned with the
135
- * Elysia guard used by the full SSR route.
136
- *
137
- * @internal Exported for unit testing.
138
- */
139
- export async function parseRouteQuery(
140
- url: URL,
141
- schema: AnySchema | undefined
142
- ): Promise<ParseRouteQueryResult> {
143
- if (!schema) {
144
- return { ok: true, query: parseQueryFromURL(url.search, 1) as SearchParamsInput };
145
- }
133
+ export type ParseRouteParamsResult =
134
+ | { ok: true; params: UnknownObject }
135
+ | { errors: unknown; ok: false };
146
136
 
137
+ type RouteInputValidationResult =
138
+ | { ok: true; value: UnknownObject }
139
+ | { errors: unknown; ok: false };
140
+
141
+ async function validateRouteInput(
142
+ input: UnknownObject,
143
+ schema: AnySchema
144
+ ): Promise<RouteInputValidationResult> {
147
145
  if (isStandardSchema(schema)) {
148
- const rawQuery = parseQueryStandardSchema(url.search, 1) as UnknownObject;
149
146
  const validator = getSchemaValidator(schema, { dynamic: true });
150
- const checked = await validator?.Check(rawQuery);
147
+ const checked = await validator?.Check(input);
151
148
  if (checked && typeof checked === "object" && "issues" in checked) {
152
149
  return { errors: checked.issues, ok: false };
153
150
  }
154
151
  if (checked && typeof checked === "object" && "value" in checked) {
155
- return { ok: true, query: checked.value as SearchParamsInput };
152
+ return { ok: true, value: checked.value as UnknownObject };
156
153
  }
157
- return { ok: true, query: rawQuery as SearchParamsInput };
154
+ return { ok: true, value: input };
158
155
  }
159
156
 
160
- const rawQuery = parseJsonQueryObjects(
161
- parseQueryFromURL(url.search, 1, collectQueryArrayKeys(schema)) as UnknownObject,
162
- collectQueryObjectKeys(schema)
163
- );
164
- const queryWithDefaults = applySchemaDefaults(schema as UnknownObject, rawQuery);
157
+ const inputWithDefaults = applySchemaDefaults(schema as UnknownObject, input);
165
158
  const validator = getSchemaValidator(schema, { coerce: true, dynamic: true });
166
- if (validator?.Check(queryWithDefaults) === false) {
167
- return { errors: [...(validator?.Errors(queryWithDefaults) ?? [])], ok: false };
159
+ if (validator?.Check(inputWithDefaults) === false) {
160
+ return { errors: [...(validator?.Errors(inputWithDefaults) ?? [])], ok: false };
168
161
  }
169
162
 
170
163
  return {
171
164
  ok: true,
172
- query: (validator?.parse(queryWithDefaults) ?? queryWithDefaults) as SearchParamsInput,
165
+ value: (validator?.parse(inputWithDefaults) ?? inputWithDefaults) as UnknownObject,
173
166
  };
174
167
  }
175
168
 
176
- // Standard structural keys on a TObject — everything else is a user-supplied option
177
- // (e.g. additionalProperties, $id, description, title) and must be preserved.
178
- const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
179
- const TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
169
+ /**
170
+ * Parses and validates a logical route URL's search string for the synthetic
171
+ * `/_furin/data` request path. This keeps SPA navigations aligned with the
172
+ * Elysia guard used by the full SSR route.
173
+ *
174
+ * @internal Exported for unit testing.
175
+ */
176
+ export async function parseRouteQuery(
177
+ url: URL,
178
+ schema: AnySchema | undefined
179
+ ): Promise<ParseRouteQueryResult> {
180
+ if (!schema) {
181
+ return { ok: true, query: parseQueryFromURL(url.search, 1) as SearchParamsInput };
182
+ }
180
183
 
181
- function isTypeBoxObjectSchema(schema: unknown): schema is UnknownObject {
182
- return (
183
- isObjectSchema(schema) &&
184
- (schema as UnknownObject & { [key: symbol]: unknown })[TYPEBOX_KIND] === "Object"
185
- );
184
+ const rawQuery = isStandardSchema(schema)
185
+ ? (parseQueryStandardSchema(url.search, 1) as UnknownObject)
186
+ : parseJsonQueryObjects(
187
+ parseQueryFromURL(url.search, 1, collectQueryArrayKeys(schema)) as UnknownObject,
188
+ collectQueryObjectKeys(schema)
189
+ );
190
+ const result = await validateRouteInput(rawQuery, schema);
191
+ return result.ok ? { ok: true, query: result.value as SearchParamsInput } : result;
186
192
  }
187
193
 
188
194
  /**
189
- * Merges TObject schemas from all routeChain entries for a given key.
190
- * Properties are spread left-to-right (leaf wins on key conflict).
191
- * Object-level options (additionalProperties, $id, description, …) are also
192
- * merged with the same leaf-wins semantics so they are not silently dropped.
193
- * Returns undefined when no entry in the chain defines the key.
195
+ * 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.
194
198
  *
195
199
  * @internal Exported for unit testing.
196
200
  */
197
- export function mergeRouteSchemas(
198
- routeChain: RuntimeRoute[],
199
- key: "params" | "query"
200
- ): AnySchema | undefined {
201
- const schemas = routeChain.flatMap((r) => (r[key] ? [r[key]] : [])) as Record<string, unknown>[];
202
-
203
- if (schemas.length === 0) {
204
- return;
205
- }
206
- if (schemas.length === 1) {
207
- return schemas[0] as AnySchema;
208
- }
209
-
210
- if (schemas.some((s) => !isTypeBoxObjectSchema(s))) {
211
- throw new Error(
212
- `[furin] Merging ${key} schemas across the route chain requires TypeBox in V1. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`
213
- );
201
+ export async function parseRouteParams(
202
+ params: UnknownObject,
203
+ schema: AnySchema | undefined
204
+ ): Promise<ParseRouteParamsResult> {
205
+ if (!schema) {
206
+ return { ok: true, params };
214
207
  }
215
208
 
216
- const mergedProperties = Object.assign(
217
- {},
218
- ...schemas.map((s) => (s.properties as Record<string, unknown>) ?? {})
219
- );
220
-
221
- const mergedOptions = Object.assign(
222
- {},
223
- ...schemas.map((s) =>
224
- Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))
225
- )
226
- );
227
-
228
- return t.Object(mergedProperties, mergedOptions) as AnySchema;
209
+ const result = await validateRouteInput(params, schema);
210
+ return result.ok ? { ok: true, params: result.value } : result;
229
211
  }
230
212
 
231
213
  export function createSearchRouteMetadata(
@@ -1,4 +1,4 @@
1
- import type { RuntimePage, RuntimeRoute } from "../../client.ts";
1
+ import type { RuntimePage, RuntimeRoute } from "../../client/internal/runtime-types.ts";
2
2
  import type { ErrorComponent } from "../../shared/error.ts";
3
3
  import type { NotFoundComponent } from "../../shared/not-found.ts";
4
4