@teyik0/furin 0.2.0-alpha.5 → 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 (282) hide show
  1. package/README.md +2 -3
  2. package/dist/adapter/bun.d.ts +1 -1
  3. package/dist/adapter/static.d.ts +1 -1
  4. package/dist/build/bun-build.d.ts +3 -0
  5. package/dist/build/client.d.ts +2 -2
  6. package/dist/build/entry-template.d.ts +6 -0
  7. package/dist/build/entry-template.ts +20 -3
  8. package/dist/build/hydrate.d.ts +1 -1
  9. package/dist/build/index.d.ts +1 -1
  10. package/dist/build/index.js +9363 -5827
  11. package/dist/build/production-instrumentation.d.ts +1 -0
  12. package/dist/build/route-types.d.ts +3 -23
  13. package/dist/build/shared.d.ts +1 -1
  14. package/dist/build/ssg-cache.d.ts +1 -1
  15. package/dist/build/types.d.ts +2 -1
  16. package/dist/cli/index.js +9467 -5870
  17. package/dist/client/boundaries.d.ts +6 -4
  18. package/dist/client/define-route.d.ts +35 -0
  19. package/dist/client/document.d.ts +26 -0
  20. package/dist/client/hmr.d.ts +10 -0
  21. package/dist/client/internal/runtime-types.d.ts +32 -0
  22. package/dist/client/link.d.ts +2 -1
  23. package/dist/client/link.js +1884 -1227
  24. package/dist/client/router/boundary-tree.d.ts +1 -1
  25. package/dist/client/router/index.d.ts +2 -2
  26. package/dist/client/router/link-utils.d.ts +14 -1
  27. package/dist/client/router/search/index.d.ts +3 -7
  28. package/dist/client/router/sync-catch-up.d.ts +4 -4
  29. package/dist/client/router/types.d.ts +34 -26
  30. package/dist/client-only.d.ts +1 -0
  31. package/dist/client-only.js +1 -0
  32. package/dist/client.d.ts +11 -169
  33. package/dist/client.js +197 -36
  34. package/dist/config.d.ts +8 -8
  35. package/dist/config.js +10 -10
  36. package/dist/define-route.d.ts +1355 -0
  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 +24 -39
  40. package/dist/furin.js +14432 -7929
  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 +1708 -489
  45. package/dist/plugin/route-config-autofix.d.ts +31 -0
  46. package/dist/plugin/routes.d.ts +27 -0
  47. package/dist/plugin/transform-client.d.ts +0 -2
  48. package/dist/plugin/transform-isomorphic.d.ts +9 -0
  49. package/dist/routes.d.ts +6 -0
  50. package/dist/routes.js +1 -0
  51. package/dist/rsc/build/environment.d.ts +2 -0
  52. package/dist/rsc/build/index.d.ts +15 -0
  53. package/dist/rsc/client-codec.d.ts +1 -0
  54. package/dist/rsc/codec.d.ts +4 -0
  55. package/dist/rsc/flight-drain.d.ts +11 -0
  56. package/dist/rsc/render-error.d.ts +17 -0
  57. package/dist/rsc/server-codec.d.ts +2 -0
  58. package/dist/rsc/server-codec.js +24 -0
  59. package/dist/rsc/shared.d.ts +30 -0
  60. package/dist/rsc/symbols.d.ts +2 -0
  61. package/dist/rsc/transport-benchmark.d.ts +13 -0
  62. package/dist/rsc/version.d.ts +7 -0
  63. package/dist/rsc-client.d.ts +4 -0
  64. package/dist/rsc-client.js +166 -0
  65. package/dist/rsc-server.d.ts +11 -0
  66. package/dist/rsc.d.ts +11 -0
  67. package/dist/rsc.js +353 -0
  68. package/dist/server/cache/index.d.ts +2 -2
  69. package/dist/server/cache/invalidation.d.ts +2 -3
  70. package/dist/server/cache/isr-ssg.d.ts +5 -1
  71. package/dist/server/cache/isr.d.ts +9 -0
  72. package/dist/server/cache/route-cache.d.ts +10 -8
  73. package/dist/server/cache/store-view.d.ts +7 -7
  74. package/dist/server/dev-page-plugin.d.ts +11 -5
  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/internal.d.ts +5 -0
  81. package/dist/server/internal.js +3 -3
  82. package/dist/server/lang-detect.d.ts +1 -0
  83. package/dist/server/logger.d.ts +4 -0
  84. package/dist/server/render/assemble.d.ts +4 -9
  85. package/dist/server/render/document.d.ts +4 -0
  86. package/dist/server/render/element.d.ts +3 -2
  87. package/dist/server/render/index.d.ts +2 -2
  88. package/dist/server/render/index.ts +6 -3
  89. package/dist/server/render/isr.d.ts +1 -1
  90. package/dist/server/render/loaders.d.ts +9 -1
  91. package/dist/server/render/not-found.d.ts +2 -2
  92. package/dist/server/render/ppr-route.d.ts +8 -0
  93. package/dist/server/render/route-frame-transport.d.ts +2 -0
  94. package/dist/server/render/shell.ts +0 -1
  95. package/dist/server/render/ssg.d.ts +1 -1
  96. package/dist/server/render/ssr.d.ts +9 -9
  97. package/dist/server/render/template.d.ts +4 -0
  98. package/dist/server/router/defined-route.d.ts +24 -0
  99. package/dist/server/router/discovery.d.ts +1 -1
  100. package/dist/server/router/hmr.d.ts +17 -9
  101. package/dist/server/router/patterns.d.ts +7 -1
  102. package/dist/server/router/plugin.d.ts +8 -10
  103. package/dist/server/router/schema-merge.d.ts +3 -0
  104. package/dist/server/router/schemas.d.ts +14 -9
  105. package/dist/server/router/source-version.d.ts +2 -0
  106. package/dist/server/router/types.d.ts +2 -1
  107. package/dist/server/runtime-env.js +2 -2
  108. package/dist/server/sync/adapter.d.ts +45 -26
  109. package/dist/server/sync/config.d.ts +5 -9
  110. package/dist/server/sync/fingerprint.d.ts +2 -1
  111. package/dist/server/sync/index.d.ts +15 -4
  112. package/dist/server/sync/index.js +3023 -0
  113. package/dist/server/sync/notifier.d.ts +18 -0
  114. package/dist/server/sync/plugin.d.ts +53 -54
  115. package/dist/server/sync/postgres/index.d.ts +19 -0
  116. package/dist/server/sync/postgres/index.js +252 -0
  117. package/dist/server/sync/postgres/migrate.d.ts +2 -0
  118. package/dist/server/sync/postgres/migrate.js +17 -0
  119. package/dist/server/sync/postgres/migration.sql +66 -0
  120. package/dist/server/sync/redis/index.d.ts +30 -0
  121. package/dist/server/sync/redis/index.js +336 -0
  122. package/dist/server/sync/redis/scripts.d.ts +4 -0
  123. package/dist/server/sync/response.d.ts +10 -1
  124. package/dist/server/sync/runtime.d.ts +6 -0
  125. package/dist/server/sync/sqlite/index.d.ts +20 -0
  126. package/dist/server/sync/sqlite/index.js +250 -0
  127. package/dist/server/sync/stream.d.ts +12 -11
  128. package/dist/server-only.d.ts +1 -0
  129. package/dist/server-only.js +1 -0
  130. package/dist/shared/await.d.ts +6 -7
  131. package/dist/shared/elysia-contract.d.ts +41 -0
  132. package/dist/shared/parser.d.ts +2 -0
  133. package/dist/shared/route-frame.d.ts +49 -0
  134. package/dist/shared/route-map.d.ts +5 -0
  135. package/dist/shared/utils/index.d.ts +1 -3
  136. package/package.json +86 -41
  137. package/src/adapter/bun.ts +113 -36
  138. package/src/adapter/package.ts +23 -15
  139. package/src/adapter/static.ts +97 -50
  140. package/src/build/bun-build.ts +11 -0
  141. package/src/build/client.ts +41 -26
  142. package/src/build/entry-template.ts +20 -3
  143. package/src/build/hydrate.ts +128 -33
  144. package/src/build/index.ts +14 -2
  145. package/src/build/production-instrumentation.ts +14 -0
  146. package/src/build/route-types.ts +20 -116
  147. package/src/build/scan-server.ts +3 -2
  148. package/src/build/shared.ts +1 -1
  149. package/src/build/ssg-cache.ts +4 -2
  150. package/src/build/types.ts +2 -1
  151. package/src/cli/config.ts +3 -3
  152. package/src/cli/index.ts +58 -27
  153. package/src/client/boundaries.tsx +51 -19
  154. package/src/client/default-screens.tsx +4 -4
  155. package/src/client/define-route.ts +48 -0
  156. package/src/client/document.tsx +165 -0
  157. package/src/client/hmr.ts +40 -0
  158. package/src/client/internal/runtime-types.ts +33 -0
  159. package/src/client/link.tsx +51 -38
  160. package/src/client/router/boundary-tree.tsx +2 -2
  161. package/src/client/router/context.ts +13 -9
  162. package/src/client/router/index.ts +4 -0
  163. package/src/client/router/link-utils.ts +92 -3
  164. package/src/client/router/navigation.ts +9 -15
  165. package/src/client/router/provider.tsx +98 -53
  166. package/src/client/router/search/index.ts +9 -19
  167. package/src/client/router/search-store.ts +5 -1
  168. package/src/client/router/spa-response.ts +3 -4
  169. package/src/client/router/sync-catch-up.ts +9 -8
  170. package/src/client/router/types.ts +52 -26
  171. package/src/client/sync.ts +3 -2
  172. package/src/client-only.ts +1 -0
  173. package/src/client.ts +28 -283
  174. package/src/config.ts +10 -10
  175. package/src/define-route.ts +959 -0
  176. package/src/devtools/devtools-element.js +885 -0
  177. package/src/devtools/protocol.ts +139 -0
  178. package/src/furin.ts +475 -136
  179. package/src/isomorphic.ts +66 -0
  180. package/src/plugin/binding-scope.ts +158 -0
  181. package/src/plugin/dead-code-elimination.ts +202 -0
  182. package/src/plugin/index.ts +14 -18
  183. package/src/plugin/route-config-autofix.ts +1140 -0
  184. package/src/plugin/routes.ts +891 -0
  185. package/src/plugin/transform-client.ts +160 -330
  186. package/src/plugin/transform-isomorphic.ts +464 -0
  187. package/src/routes.ts +6 -0
  188. package/src/rsc/build/environment.ts +30 -0
  189. package/src/rsc/build/index.ts +94 -0
  190. package/src/rsc/client-codec.ts +11 -0
  191. package/src/rsc/codec.ts +85 -0
  192. package/src/rsc/flight-drain.ts +68 -0
  193. package/src/rsc/react-server-dom-webpack.d.ts +23 -0
  194. package/src/rsc/render-error.ts +120 -0
  195. package/src/rsc/server-codec.ts +25 -0
  196. package/src/rsc/shared.tsx +113 -0
  197. package/src/rsc/symbols.ts +2 -0
  198. package/src/rsc/transport-benchmark.ts +73 -0
  199. package/src/rsc/version.ts +57 -0
  200. package/src/rsc-client.ts +12 -0
  201. package/src/rsc-server.tsx +91 -0
  202. package/src/rsc.tsx +75 -0
  203. package/src/server/auto-invalidate/registry.ts +2 -2
  204. package/src/server/auto-invalidate/runtime.ts +32 -6
  205. package/src/server/cache/dev-loader.ts +70 -10
  206. package/src/server/cache/index.ts +7 -3
  207. package/src/server/cache/invalidation.ts +33 -15
  208. package/src/server/cache/isr-ssg.ts +12 -3
  209. package/src/server/cache/isr.ts +84 -9
  210. package/src/server/cache/route-cache.ts +49 -36
  211. package/src/server/cache/store-view.ts +7 -7
  212. package/src/server/context-logger.ts +7 -7
  213. package/src/server/dev-page-plugin.ts +38 -17
  214. package/src/server/devtools/hub.ts +64 -0
  215. package/src/server/devtools/instrumentation.production.ts +80 -0
  216. package/src/server/devtools/instrumentation.ts +72 -0
  217. package/src/server/devtools/plugin.ts +269 -0
  218. package/src/server/devtools/request-context.ts +76 -0
  219. package/src/server/instance.ts +4 -4
  220. package/src/server/internal.ts +5 -0
  221. package/src/server/lang-detect.ts +14 -10
  222. package/src/server/logger.ts +21 -0
  223. package/src/server/render/assemble.ts +58 -36
  224. package/src/server/render/document.tsx +25 -0
  225. package/src/server/render/element.tsx +24 -9
  226. package/src/server/render/index.ts +6 -3
  227. package/src/server/render/isr.ts +182 -117
  228. package/src/server/render/loaders.ts +289 -50
  229. package/src/server/render/not-found.ts +57 -38
  230. package/src/server/render/ppr-route.ts +146 -0
  231. package/src/server/render/route-frame-transport.ts +62 -0
  232. package/src/server/render/shell.ts +0 -1
  233. package/src/server/render/ssg.ts +7 -6
  234. package/src/server/render/ssr.ts +412 -166
  235. package/src/server/render/template.ts +93 -2
  236. package/src/server/router/defined-route.ts +110 -0
  237. package/src/server/router/discovery.ts +165 -48
  238. package/src/server/router/hmr.ts +126 -53
  239. package/src/server/router/patterns.ts +56 -27
  240. package/src/server/router/plugin.ts +210 -200
  241. package/src/server/router/schema-merge.ts +42 -0
  242. package/src/server/router/schemas.ts +61 -76
  243. package/src/server/router/source-version.ts +16 -0
  244. package/src/server/router/types.ts +3 -1
  245. package/src/server/sync/adapter.ts +44 -28
  246. package/src/server/sync/config.ts +9 -27
  247. package/src/server/sync/fingerprint.ts +8 -3
  248. package/src/server/sync/index.ts +37 -13
  249. package/src/server/sync/notifier.ts +109 -0
  250. package/src/server/sync/plugin.ts +184 -89
  251. package/src/server/sync/postgres/index.ts +301 -0
  252. package/src/server/sync/postgres/migrate.ts +16 -0
  253. package/src/server/sync/postgres/migration.sql +66 -0
  254. package/src/server/sync/redis/index.ts +342 -0
  255. package/src/server/sync/redis/scripts.ts +74 -0
  256. package/src/server/sync/response.ts +145 -16
  257. package/src/server/sync/runtime.ts +27 -0
  258. package/src/server/sync/sql.d.ts +4 -0
  259. package/src/server/sync/sqlite/index.ts +337 -0
  260. package/src/server/sync/sqlite/migration.sql +70 -0
  261. package/src/server/sync/stream.ts +137 -81
  262. package/src/server-only.ts +1 -0
  263. package/src/shared/await.tsx +10 -11
  264. package/src/shared/deferred-ndjson.ts +34 -6
  265. package/src/shared/digest.ts +2 -2
  266. package/src/shared/elysia-contract.ts +63 -0
  267. package/src/shared/parser.ts +5 -0
  268. package/src/shared/route-frame.ts +429 -0
  269. package/src/shared/route-map.ts +37 -0
  270. package/src/shared/search-params.ts +7 -7
  271. package/src/shared/utils/index.ts +6 -22
  272. package/dist/build/server-routes-entry.d.ts +0 -13
  273. package/dist/build/server-routes-entry.ts +0 -30
  274. package/dist/server/dev-inspector.d.ts +0 -89
  275. package/dist/server/router/index.d.ts +0 -6
  276. package/dist/server/router/index.js +0 -27
  277. package/dist/server/router/index.ts +0 -28
  278. package/dist/server/sync/memory-adapter.d.ts +0 -17
  279. package/src/build/server-routes-entry.ts +0 -30
  280. package/src/server/dev-inspector.ts +0 -60
  281. package/src/server/router/index.ts +0 -28
  282. package/src/server/sync/memory-adapter.ts +0 -196
package/src/furin.ts CHANGED
@@ -1,12 +1,19 @@
1
- import { existsSync } from "node:fs";
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, join, resolve } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { staticPlugin } from "@elysiajs/static";
5
5
  import { type AnyElysia, Elysia, file } from "elysia";
6
- import { type DrainContext, initLogger } from "evlog";
6
+ import type { DrainContext, LoggerConfig } from "evlog";
7
7
  import { type EvlogElysiaOptions, evlog } from "evlog/elysia";
8
+ import { FURIN_RENDER_DECORATOR, type FurinRouteDispatcher } from "./define-route.ts";
8
9
  import { consumePendingInvalidations } from "./server/cache/invalidation.ts";
9
10
  import { setSSGCache } from "./server/cache/ssg.ts";
11
+ import {
12
+ createInstrumentationPlugin,
13
+ instrumentationLoggerExclusions,
14
+ runWithRequestInstrumentation,
15
+ shouldInstrumentRequest,
16
+ } from "./server/devtools/instrumentation.ts";
10
17
  import {
11
18
  assertPrefixAvailable,
12
19
  createInstance,
@@ -21,23 +28,27 @@ import {
21
28
  } from "./server/instance.ts";
22
29
  import type { CompileContext, EmbeddedAppData } from "./server/internal.ts";
23
30
  import { getCompileContext } from "./server/internal.ts";
24
- import { renderRootNotFound, warmSSGCache } from "./server/render/index.ts";
31
+ import { initializeFurinLogger } from "./server/logger.ts";
32
+ import { renderRootNotFound } from "./server/render/not-found.ts";
33
+ import { warmSSGCache } from "./server/render/ssg.ts";
25
34
  import {
26
35
  setProductionTemplateContent,
27
36
  setProductionTemplatePath,
28
37
  } from "./server/render/template.ts";
38
+ import { loadProdRoutes } from "./server/router/discovery.ts";
39
+ import { invalidateStampedRouteModules } from "./server/router/hmr.ts";
40
+ import { buildRouteMatcher } from "./server/router/patterns.ts";
41
+ import { createDataEndpoint, renderResolvedRoute } from "./server/router/plugin.ts";
42
+ import { mergeRouteSchemas } from "./server/router/schema-merge.ts";
29
43
  import {
30
- createDataEndpoint,
31
- createRoutePlugin,
32
44
  createSearchRouteMetadata,
33
- loadProdRoutes,
34
- } from "./server/router/index.ts";
45
+ parseRouteParams,
46
+ parseRouteQuery,
47
+ } from "./server/router/schemas.ts";
48
+ import type { ResolvedRoute, RootLayout } from "./server/router/types.ts";
35
49
  import { IS_DEV } from "./server/runtime-env.ts";
36
- import {
37
- createSyncStreamPlugin,
38
- type FurinSyncOption,
39
- resolveSyncStreamPath,
40
- } from "./server/sync/index.ts";
50
+ import { type FurinSyncOption, resolveSyncStreamPath } from "./server/sync/config.ts";
51
+ import { createSyncStreamPlugin } from "./server/sync/stream.ts";
41
52
 
42
53
  // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
43
54
  export interface FurinCacheTags {}
@@ -47,8 +58,27 @@ export type CacheTag = keyof FurinCacheTags extends never ? string : keyof Furin
47
58
  import { clientDirNameForPrefix } from "./shared/prefix.ts";
48
59
 
49
60
  // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
61
+ export {
62
+ type DefineRouteConfig,
63
+ defineRootRoute,
64
+ defineRoute,
65
+ type RequestLoaderContext,
66
+ type RouteLoaderData,
67
+ type RouteParams,
68
+ } from "./define-route.ts";
69
+ export {
70
+ type ClientIsomorphicFn,
71
+ createIsomorphicFn,
72
+ type IsomorphicFn,
73
+ type IsomorphicFnBuilder,
74
+ type ServerIsomorphicFn,
75
+ } from "./isomorphic.ts";
50
76
  export { clientDirNameForPrefix } from "./shared/prefix.ts";
51
77
 
78
+ const MAX_BROWSER_INGEST_BYTES = 64 * 1024;
79
+ const MAX_BROWSER_INGEST_EVENTS = 100;
80
+ const DEV_ROUTE_TOPOLOGY_POLL_INTERVAL_MS = 100;
81
+
52
82
  function resolveClientDirFromArgv(prefix: string): string {
53
83
  const dirName = clientDirNameForPrefix(prefix);
54
84
  return (
@@ -176,72 +206,146 @@ async function setupProdTemplate(
176
206
  * browser `environment` which must not overwrite the server's); everything
177
207
  * else is forwarded as-is.
178
208
  */
179
- type FurinBrowserEvent = {
209
+ interface FurinBrowserEvent {
180
210
  __proto__?: unknown;
181
211
  constructor?: unknown;
182
- prototype?: unknown;
183
212
  environment?: unknown;
184
- } & Record<string, unknown>;
213
+ prototype?: unknown;
214
+ [key: string]: unknown;
215
+ }
216
+
217
+ type BrowserIngestRead =
218
+ | { body: unknown; kind: "ok" }
219
+ | { kind: "invalid" }
220
+ | { kind: "oversized" };
221
+
222
+ async function readBrowserIngest(request: Request): Promise<BrowserIngestRead> {
223
+ const contentLength = request.headers.get("content-length");
224
+ if (contentLength) {
225
+ const declaredBytes = Number(contentLength);
226
+ if (Number.isFinite(declaredBytes) && declaredBytes > MAX_BROWSER_INGEST_BYTES) {
227
+ await request.body?.cancel();
228
+ return { kind: "oversized" };
229
+ }
230
+ }
231
+ if (request.body === null) {
232
+ return { kind: "invalid" };
233
+ }
234
+ const reader = request.body.getReader();
235
+ const chunks: Uint8Array[] = [];
236
+ let total = 0;
237
+ try {
238
+ for (;;) {
239
+ // biome-ignore lint/performance/noAwaitInLoops: request body chunks must be read sequentially.
240
+ const { done, value } = await reader.read();
241
+ if (done) {
242
+ break;
243
+ }
244
+ total += value.byteLength;
245
+ if (total > MAX_BROWSER_INGEST_BYTES) {
246
+ await reader.cancel();
247
+ return { kind: "oversized" };
248
+ }
249
+ chunks.push(value);
250
+ }
251
+ } finally {
252
+ reader.releaseLock();
253
+ }
254
+ const bytes = new Uint8Array(total);
255
+ let offset = 0;
256
+ for (const chunk of chunks) {
257
+ bytes.set(chunk, offset);
258
+ offset += chunk.byteLength;
259
+ }
260
+ try {
261
+ return { body: JSON.parse(new TextDecoder().decode(bytes)), kind: "ok" };
262
+ } catch {
263
+ return { kind: "invalid" };
264
+ }
265
+ }
185
266
 
186
267
  /** Evlog wide-event plugin + browser log ingest endpoint for one instance. */
187
268
  function createLoggerPlugin(
188
269
  prefix: string,
189
270
  syncStreamPath: string | undefined,
190
- logger: EvlogElysiaOptions | undefined
271
+ logger: EvlogElysiaOptions | undefined,
272
+ clientLogging: boolean
191
273
  ): Elysia {
192
274
  const { exclude: userExclude, ...evlogOptions } = logger ?? {};
193
- return new Elysia()
194
- .use(
195
- evlog({
196
- ...evlogOptions,
197
- // Exclude patterns match the PHYSICAL request path — prefix them.
198
- exclude: [
199
- `${prefix}/_client/**`,
200
- `${prefix}/public/**`,
201
- `${prefix}/favicon.ico`,
202
- `${prefix}/_bun_hmr_entry/**`,
203
- ...(syncStreamPath ? [`${prefix}${syncStreamPath}`] : []),
204
- // Note: /_furin/data is logged with the *logical* path rewritten by
205
- // createDataEndpoint via useLogger().set({ path }), so SPA navigations
206
- // appear as "GET /board/123 200" — same shape as a normal SSR nav.
207
- // /_furin/ingest is kept loggable so browser-side events show up.
208
- // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
209
- // like `!(...)` matches nothing, so don't add patterns relying on it.
210
- ...(userExclude ?? []),
211
- ],
212
- })
213
- )
214
- .post(
215
- "/_furin/ingest",
216
- ({ body, log, status }) => {
217
- if (!Array.isArray(body)) {
218
- return status("Bad Request");
275
+ const app = new Elysia().use(
276
+ evlog({
277
+ ...evlogOptions,
278
+ // Exclude patterns match the PHYSICAL request path — prefix them.
279
+ exclude: [
280
+ `${prefix}/_client/**`,
281
+ `${prefix}/public/**`,
282
+ `${prefix}/favicon.ico`,
283
+ `${prefix}/_bun_hmr_entry/**`,
284
+ ...instrumentationLoggerExclusions(prefix),
285
+ ...(syncStreamPath ? [`${prefix}${syncStreamPath}`] : []),
286
+ // Note: /_furin/data is logged with the *logical* path rewritten by
287
+ // createDataEndpoint via useLogger().set({ path }), so SPA navigations
288
+ // appear as "GET /board/123 200" — same shape as a normal SSR nav.
289
+ // /_furin/ingest remains loggable when browser logging is explicitly
290
+ // enabled so browser-side events show up.
291
+ // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
292
+ // like `!(...)` matches nothing, so don't add patterns relying on it.
293
+ ...(userExclude ?? []),
294
+ ],
295
+ })
296
+ );
297
+
298
+ if (!clientLogging) {
299
+ return app as unknown as Elysia;
300
+ }
301
+
302
+ return app.post(
303
+ "/_furin/ingest",
304
+ async ({ log, request, status }) => {
305
+ const parsed = await readBrowserIngest(request);
306
+ if (parsed.kind === "oversized") {
307
+ return status(413);
308
+ }
309
+ if (parsed.kind === "invalid") {
310
+ return status("Bad Request");
311
+ }
312
+ const { body } = parsed;
313
+ if (!Array.isArray(body)) {
314
+ return status("Bad Request");
315
+ }
316
+ const batch = (body as DrainContext[]).slice(0, MAX_BROWSER_INGEST_EVENTS);
317
+ for (const entry of batch) {
318
+ if (!entry || typeof entry !== "object" || !("event" in entry)) {
319
+ log.set({ msg: "[furin] ingest: skipping malformed entry" });
320
+ continue;
219
321
  }
220
- // Cap batch size to prevent abuse
221
- const batch = (body as DrainContext[]).slice(0, 100);
222
- for (const entry of batch) {
223
- if (!entry || typeof entry !== "object" || !("event" in entry)) {
224
- log.set({ msg: "[furin] ingest: skipping malformed entry" });
225
- continue;
226
- }
227
- // Pick only safe, known fields from the event to prevent prototype pollution
228
- const event = entry.event as FurinBrowserEvent | undefined;
229
- if (!event || typeof event !== "object") {
230
- continue;
231
- }
232
- const {
233
- __proto__,
234
- constructor: _ctor,
235
- prototype,
236
- environment: _browserEnv,
237
- ...safeEvent
238
- } = event;
239
- log.set({ ...safeEvent, service: "furin:browser" });
322
+ // Pick only safe, known fields from the event to prevent prototype pollution
323
+ const event = entry.event as FurinBrowserEvent | undefined;
324
+ if (!event || typeof event !== "object") {
325
+ continue;
240
326
  }
241
- return status("No Content");
242
- },
243
- { parse: "json" }
244
- ) as unknown as Elysia;
327
+ const {
328
+ __proto__,
329
+ constructor: _ctor,
330
+ prototype,
331
+ environment: _browserEnv,
332
+ ...safeEvent
333
+ } = event;
334
+ log.set({ ...safeEvent, service: "furin:browser" });
335
+ }
336
+ return status("No Content");
337
+ },
338
+ { parse: "none" }
339
+ ) as unknown as Elysia;
340
+ }
341
+
342
+ function initializeLogger(logger: FurinLoggerOptions | undefined): EvlogElysiaOptions {
343
+ const { sampling, ...elysiaLoggerOptions } = logger ?? {};
344
+ initializeFurinLogger({
345
+ env: { service: "furin" },
346
+ ...(sampling ? { sampling } : {}),
347
+ });
348
+ return elysiaLoggerOptions;
245
349
  }
246
350
 
247
351
  /**
@@ -270,10 +374,116 @@ function wrapWithRequestScope(app: AnyElysia): Elysia {
270
374
  markTraffic();
271
375
  const req = request ?? (ctx as { request?: Request } | undefined)?.request;
272
376
  const pathname = req ? new URL(req.url).pathname : "/";
273
- return runWithInstanceScope(resolveInstanceByPath(pathname), () => handler(ctx));
377
+ const instance = resolveInstanceByPath(pathname);
378
+ return runWithInstanceScope(instance, () => {
379
+ if (!(req && shouldInstrumentRequest(pathname, instance.prefix))) {
380
+ return handler(ctx);
381
+ }
382
+ return runWithRequestInstrumentation(req, () => handler(ctx));
383
+ });
274
384
  });
275
385
  }
276
386
 
387
+ function createFurinPlugin(
388
+ app: AnyElysia,
389
+ prepareParent: ((parentApp: AnyElysia) => void) | undefined
390
+ ) {
391
+ const scopedApp = wrapWithRequestScope(app);
392
+ return <ParentApp extends AnyElysia>(parentApp: ParentApp) => {
393
+ prepareParent?.(parentApp);
394
+ return parentApp.use(scopedApp);
395
+ };
396
+ }
397
+
398
+ async function loadDevelopmentRoutes(resolvedPagesDir: string) {
399
+ const { scanPages } = await import("./server/router/discovery.ts");
400
+ return scanPages(resolvedPagesDir);
401
+ }
402
+
403
+ function createNativeRouteRenderer(
404
+ prefix: string,
405
+ routes: ResolvedRoute[],
406
+ root: RootLayout,
407
+ buildId: string,
408
+ searchRoutes: ReturnType<typeof createSearchRouteMetadata>
409
+ ): FurinRouteDispatcher {
410
+ const matchNativeRoute = buildRouteMatcher(routes);
411
+ return async (context) => {
412
+ const { request } = context;
413
+ const requestUrl = new URL(request.url);
414
+ const { pathname } = requestUrl;
415
+ const hasPrefix = prefix !== "" && (pathname === prefix || pathname.startsWith(`${prefix}/`));
416
+ const logicalPath = hasPrefix ? pathname.slice(prefix.length) : pathname;
417
+ const matched = matchNativeRoute(logicalPath || "/");
418
+ if (!matched) {
419
+ // Dev topology swap: the mounted Elysia route can outlive its source
420
+ // file (hot-remove). Render the root not-found page instead of failing.
421
+ const listenerOrigin = (context.server as { url?: { origin: string } } | undefined)?.url
422
+ ?.origin;
423
+ return renderRootNotFound(root, request, listenerOrigin);
424
+ }
425
+ const parsedParams = await parseRouteParams(
426
+ matched.params,
427
+ mergeRouteSchemas(matched.route.routeChain, "params")
428
+ );
429
+ if (!parsedParams.ok) {
430
+ return Response.json(
431
+ { errors: parsedParams.errors, message: "Invalid params", type: "validation" },
432
+ { status: 422 }
433
+ );
434
+ }
435
+ const parsedQuery = await parseRouteQuery(
436
+ requestUrl,
437
+ mergeRouteSchemas(matched.route.routeChain, "query")
438
+ );
439
+ if (!parsedQuery.ok) {
440
+ return Response.json(
441
+ { errors: parsedQuery.errors, message: "Invalid query", type: "validation" },
442
+ { status: 422 }
443
+ );
444
+ }
445
+ context.params = parsedParams.params;
446
+ context.query = parsedQuery.query;
447
+ return renderResolvedRoute(
448
+ matched.route,
449
+ context as unknown as Parameters<typeof renderResolvedRoute>[1],
450
+ root,
451
+ buildId,
452
+ searchRoutes
453
+ );
454
+ };
455
+ }
456
+
457
+ interface DevelopmentRouteSnapshot {
458
+ render: FurinRouteDispatcher;
459
+ root: RootLayout;
460
+ routes: ResolvedRoute[];
461
+ }
462
+
463
+ function createDevelopmentRouteSnapshot(
464
+ prefix: string,
465
+ root: RootLayout,
466
+ routes: ResolvedRoute[]
467
+ ): DevelopmentRouteSnapshot {
468
+ const searchRoutes = createSearchRouteMetadata(routes);
469
+ return {
470
+ render: createNativeRouteRenderer(prefix, routes, root, "", searchRoutes),
471
+ root,
472
+ routes,
473
+ };
474
+ }
475
+
476
+ const nativeRouteRenderers = new WeakMap<FurinInstance, FurinRouteDispatcher>();
477
+
478
+ function dispatchNativeRoute(context: Parameters<FurinRouteDispatcher>[0]): unknown {
479
+ const { pathname } = new URL(context.request.url);
480
+ const renderer = nativeRouteRenderers.get(resolveInstanceByPath(pathname));
481
+ if (!renderer) {
482
+ throw new Error(`[furin] No route renderer is registered for ${JSON.stringify(pathname)}`);
483
+ }
484
+ return renderer(context);
485
+ }
486
+
277
487
  function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
278
488
  if (!ctx.ssgCache) {
279
489
  return;
@@ -284,6 +494,8 @@ function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
284
494
  }
285
495
 
286
496
  /** Options for the {@link furin} plugin. */
497
+ export type FurinLoggerOptions = EvlogElysiaOptions & Pick<LoggerConfig, "sampling">;
498
+
287
499
  export interface FurinOptions {
288
500
  /**
289
501
  * Production only: explicit directory holding this app's built client
@@ -299,7 +511,7 @@ export interface FurinOptions {
299
511
  * and unaffected.
300
512
  */
301
513
  clientLogging?: boolean;
302
- logger?: EvlogElysiaOptions;
514
+ logger?: FurinLoggerOptions;
303
515
  pagesDir?: string;
304
516
  /**
305
517
  * Mount prefix for this app, e.g. `"/admin"`. All pages, framework
@@ -309,9 +521,9 @@ export interface FurinOptions {
309
521
  */
310
522
  prefix?: string;
311
523
  /**
312
- * Enables Furin's built-in sync event stream. The opinionated default mounts
313
- * Server-Sent Events at `/_furin/sync`; pass an object only for constrained
314
- * reverse-proxy deployments that need a custom internal path.
524
+ * Configures Furin's sync event stream with the required adapter. The
525
+ * optional `streamPath` defaults to `/_furin/sync`. Omit this option or pass
526
+ * `false` to disable sync.
315
527
  */
316
528
  sync?: FurinSyncOption;
317
529
  }
@@ -319,8 +531,9 @@ export interface FurinOptions {
319
531
  /**
320
532
  * Main Furin plugin.
321
533
  *
322
- * Returns a standalone Elysia instance (async function) so that routes are
323
- * properly registered in Elysia's router for SPA navigation to work.
534
+ * Returns an Elysia plugin function. Applying the function to the parent app
535
+ * before `listen()` lets development register Bun's native HTML bundle in the
536
+ * initial server options while preserving Elysia's route composition.
324
537
  *
325
538
  * ## Usage
326
539
  *
@@ -341,8 +554,7 @@ export async function furin({
341
554
  }: FurinOptions = {}) {
342
555
  const prefix = normalizePrefix(rawPrefix);
343
556
  const syncStreamPath = resolveSyncStreamPath(sync);
344
- initLogger({ env: { service: "furin" } });
345
- const loggerPlugin = createLoggerPlugin(prefix, syncStreamPath, logger);
557
+ const elysiaLoggerOptions = initializeLogger(logger);
346
558
 
347
559
  const cwd = process.cwd();
348
560
  // The pagesDir param drives which compile context this instance loads. In a
@@ -350,6 +562,12 @@ export async function furin({
350
562
  // lookup then falls back to the (stable) prefix, then to the sole context.
351
563
  const paramPagesDir = resolve(cwd, pagesDir ?? "src/pages");
352
564
  const ctx = getCompileContext(paramPagesDir, prefix);
565
+ const loggerPlugin = createLoggerPlugin(
566
+ prefix,
567
+ syncStreamPath,
568
+ elysiaLoggerOptions,
569
+ clientLogging === true || ctx?.clientLogging === true
570
+ );
353
571
  const resolvedPagesDir = ctx?.rootPath ? dirname(ctx.rootPath) : paramPagesDir;
354
572
 
355
573
  // Unique name per pagesDir to avoid Elysia's name-based plugin dedup.
@@ -374,46 +592,124 @@ export async function furin({
374
592
  // Lazy import — build pipeline has native deps not available in compiled binaries
375
593
  const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
376
594
  registerDevPagePlugin();
595
+ const {
596
+ registerDevRoutesPlugin,
597
+ registerDevRouteTopologyWatcher,
598
+ routeModuleSpecifier,
599
+ routeSourcePaths,
600
+ } = await import("./plugin/routes.ts");
601
+ const routeInstance = { pagesDir: resolvedPagesDir, prefix };
602
+ registerDevRoutesPlugin([routeInstance]);
603
+
604
+ // TanStack-style config auto-fix: verify each route file's `layout`
605
+ // reference against the file-system tree and rewrite missing/misplaced
606
+ // ones. Idempotent and content-diff safe — the watcher resynchronizes the
607
+ // route-file signature after a rewrite, so the auto-fix cannot loop.
608
+ const { fixRouteConfigLayout } = await import("./plugin/route-config-autofix.ts");
609
+ const applyRouteConfigAutofix = (): boolean => {
610
+ let changed = false;
611
+ const sourcePaths = [
612
+ join(resolvedPagesDir, "root.tsx"),
613
+ ...routeSourcePaths(routeInstance),
614
+ ].filter((sourcePath) => existsSync(sourcePath));
615
+ for (const sourcePath of sourcePaths) {
616
+ let source: string;
617
+ try {
618
+ source = readFileSync(sourcePath, "utf8");
619
+ } catch (error) {
620
+ console.warn(
621
+ `[furin] Could not read ${sourcePath} for route config autofix: ${error instanceof Error ? error.message : String(error)}`
622
+ );
623
+ continue;
624
+ }
625
+ const fixed = fixRouteConfigLayout(source, sourcePath, resolvedPagesDir);
626
+ if (fixed !== null && fixed !== source) {
627
+ writeFileSync(sourcePath, fixed);
628
+ changed = true;
629
+ }
630
+ }
631
+ return changed;
632
+ };
633
+ applyRouteConfigAutofix();
377
634
 
378
- const { createDevInspectorPlugin } = await import("./server/dev-inspector.ts");
379
-
380
- const { scanPages } = await import("./server/router/index.ts");
381
- const { root, routes } = await scanPages(resolvedPagesDir);
382
- const searchRoutes = createSearchRouteMetadata(routes);
635
+ const { furinShell: nativeRoutesApp } = (await import(routeModuleSpecifier(routeInstance))) as {
636
+ furinShell: AnyElysia;
637
+ };
638
+ const { root, routes } = await loadDevelopmentRoutes(resolvedPagesDir);
639
+ let currentSnapshot = createDevelopmentRouteSnapshot(prefix, root, routes);
640
+ nativeRouteRenderers.set(instance, (context) => currentSnapshot.render(context));
383
641
 
384
642
  const { writeDevFiles } = await import("./build/hydrate.ts");
385
- writeDevFiles(
386
- routes,
387
- {
388
- outDir: furinDir,
389
- rootLayout: root.path,
390
- basePath: prefix,
391
- publicPath: `${prefix}/_client/`,
392
- clientLogging: clientLogging ?? false,
393
- // furin-env.d.ts is one file at the project root — only the root
394
- // instance owns it, otherwise mounted apps clobber each other's types.
395
- skipRouteTypes: prefix !== "",
396
- },
397
- cwd
398
- );
399
-
643
+ const writeCurrentDevFiles = (snapshot: DevelopmentRouteSnapshot): void => {
644
+ writeDevFiles(
645
+ snapshot.routes,
646
+ {
647
+ basePath: prefix,
648
+ clientLogging: clientLogging ?? false,
649
+ outDir: furinDir,
650
+ publicPath: `${prefix}/_client/`,
651
+ rootLayout: snapshot.root.path,
652
+ // furin-env.d.ts is one file at the project root — only the root
653
+ // instance owns it, otherwise mounted apps clobber each other's types.
654
+ skipRouteTypes: prefix !== "",
655
+ },
656
+ cwd
657
+ );
658
+ };
659
+ writeCurrentDevFiles(currentSnapshot);
660
+ const refreshDevelopmentRoutes = async (): Promise<void> => {
661
+ invalidateStampedRouteModules();
662
+ const next = await loadDevelopmentRoutes(resolvedPagesDir);
663
+ const nextSnapshot = createDevelopmentRouteSnapshot(prefix, next.root, next.routes);
664
+ writeCurrentDevFiles(nextSnapshot);
665
+ currentSnapshot = nextSnapshot;
666
+ };
667
+ const devHtmlBundle = (await import(join(furinDir, "index.html"))).default;
400
668
  const publicDir = resolve(cwd, "public");
401
669
  const publicExists = existsSync(publicDir);
670
+ const hmrEntryPath = `${prefix}/_bun_hmr_entry`;
671
+ let routeTopologyWatcher: ReturnType<typeof registerDevRouteTopologyWatcher> | undefined;
402
672
 
403
673
  // Routes registered below are LOGICAL — Elysia's `prefix` makes them
404
674
  // physical when this plugin is merged into the parent app (child prefixes
405
675
  // like staticPlugin's compose underneath).
406
676
  const devApp = new Elysia({
407
677
  name: instanceName,
408
- seed: resolvedPagesDir,
409
678
  prefix: prefix || undefined,
679
+ seed: resolvedPagesDir,
410
680
  })
681
+ .onStart(() => {
682
+ routeTopologyWatcher = registerDevRouteTopologyWatcher({
683
+ instance: routeInstance,
684
+ onRouteFilesTouched: async () => {
685
+ applyRouteConfigAutofix();
686
+ await refreshDevelopmentRoutes();
687
+ },
688
+ onTopologyChange: async () => {
689
+ // Bun --hot cannot be triggered from generated artifacts (its
690
+ // watch graph is the entry's static imports), so topology changes
691
+ // are served by swapping the dispatcher's route matcher. Hot-added
692
+ // routes then resolve through the NOT_FOUND fallback below;
693
+ // removed routes 404 through the renderer's miss path.
694
+ applyRouteConfigAutofix();
695
+ await refreshDevelopmentRoutes();
696
+ },
697
+ pollIntervalMs: DEV_ROUTE_TOPOLOGY_POLL_INTERVAL_MS,
698
+ });
699
+ })
700
+ .onStop(() => {
701
+ routeTopologyWatcher?.close();
702
+ routeTopologyWatcher = undefined;
703
+ })
704
+ // Elysia 1.4.30 only preserves Bun's native HTMLBundle handler when the
705
+ // bundle is also present in serve.routes once request hooks are installed.
706
+ .use(await staticPlugin({ assets: furinDir, bunFullstack: true, prefix: "/_bun_hmr_entry" }))
411
707
  .use(loggerPlugin)
412
708
  // Local scope (default) — a global hook would leak onto sibling furin
413
709
  // instances mounted on the same parent app.
414
- .onError(async ({ code, request }) => {
710
+ .onError(async ({ code, request, server }) => {
415
711
  if (code === "NOT_FOUND") {
416
- return await renderRootNotFound(root, request);
712
+ return await renderRootNotFound(currentSnapshot.root, request, server?.url.origin);
417
713
  }
418
714
  })
419
715
  .onAfterHandle(({ set }) => {
@@ -423,7 +719,6 @@ export async function furin({
423
719
  set.headers["x-furin-revalidate"] = pending.join(",");
424
720
  }
425
721
  })
426
- .use(await staticPlugin({ assets: furinDir, prefix: "/_bun_hmr_entry", bunFullstack: true }))
427
722
  .use(
428
723
  publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia()
429
724
  )
@@ -433,22 +728,35 @@ export async function furin({
433
728
  ? file(join(publicDir, "favicon.ico"))
434
729
  : () => new Response(null, { status: 404 })
435
730
  )
436
- .use(createDevInspectorPlugin())
731
+ .use(createInstrumentationPlugin(() => currentSnapshot.routes, syncStreamPath))
732
+ .use(sync ? createSyncStreamPlugin(sync) : new Elysia())
733
+ .use(createDataEndpoint(() => currentSnapshot.routes))
734
+ .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
735
+ .use(nativeRoutesApp)
437
736
  .use(
438
- syncStreamPath
439
- ? createSyncStreamPlugin(syncStreamPath, `${prefix}${syncStreamPath}`)
440
- : new Elysia()
441
- )
442
- .use(createDataEndpoint(routes))
443
- .use((app) =>
444
- routes.reduce(
445
- (chain, route) => chain.use(createRoutePlugin(route, root, undefined, searchRoutes)),
446
- app
447
- )
448
- )
449
- .use(createNotFoundHandling(prefix, routes, root));
737
+ createNotFoundHandling(prefix, routes, root, async (notFoundContext) => {
738
+ // Dev topology: try the (watcher-refreshed) native renderer before
739
+ // the root not-found page, so hot-added routes are served without
740
+ // a restart. Instances outside this pathname's prefix are skipped.
741
+ const { pathname } = new URL(notFoundContext.request.url);
742
+ if (!nativeRouteRenderers.has(resolveInstanceByPath(pathname))) {
743
+ return;
744
+ }
745
+ return await dispatchNativeRoute(
746
+ notFoundContext as unknown as Parameters<FurinRouteDispatcher>[0]
747
+ );
748
+ })
749
+ );
450
750
  registerInstance(instance);
451
- return wrapWithRequestScope(devApp);
751
+ return createFurinPlugin(devApp, (parentApp) => {
752
+ parentApp.config.serve = {
753
+ ...parentApp.config.serve,
754
+ routes: {
755
+ ...parentApp.config.serve?.routes,
756
+ [hmrEntryPath]: devHtmlBundle,
757
+ },
758
+ };
759
+ });
452
760
  }
453
761
 
454
762
  // ── Production ──────────────────────────────────────────────────────────
@@ -458,6 +766,17 @@ export async function furin({
458
766
  const { root, routes } = loadProdRoutes(ctx);
459
767
  const searchRoutes = createSearchRouteMetadata(routes);
460
768
  const prodBuildId = ctx.buildId ?? "";
769
+ if (!ctx.nativeRoutes) {
770
+ throw new Error("[furin] Production build is missing the composed Elysia route app.");
771
+ }
772
+ const renderNativeRoute = createNativeRouteRenderer(
773
+ prefix,
774
+ routes,
775
+ root,
776
+ prodBuildId,
777
+ searchRoutes
778
+ );
779
+ nativeRouteRenderers.set(instance, renderNativeRoute);
461
780
  instance.buildId = prodBuildId;
462
781
  // Init-time writes target THIS instance explicitly — with several mounted
463
782
  // apps there is no ambient request scope to resolve it from.
@@ -472,15 +791,15 @@ export async function furin({
472
791
  const clientAssetPrefix = `${prefix}/_client/`;
473
792
  const prodApp = new Elysia({
474
793
  name: instanceName,
475
- seed: resolvedPagesDir,
476
794
  prefix: prefix || undefined,
795
+ seed: resolvedPagesDir,
477
796
  })
478
797
  .use(loggerPlugin)
479
798
  // Local scope (default) — a global hook would leak onto sibling furin
480
799
  // instances mounted on the same parent app.
481
- .onError(async ({ code, request }) => {
800
+ .onError(async ({ code, request, server }) => {
482
801
  if (code === "NOT_FOUND") {
483
- return await renderRootNotFound(root, request);
802
+ return await renderRootNotFound(root, request, server?.url.origin);
484
803
  }
485
804
  })
486
805
  .onAfterHandle(({ path, set }) => {
@@ -545,21 +864,13 @@ export async function furin({
545
864
  return app;
546
865
  })()
547
866
  )
548
- .use(
549
- syncStreamPath
550
- ? createSyncStreamPlugin(syncStreamPath, `${prefix}${syncStreamPath}`)
551
- : new Elysia()
552
- )
867
+ .use(sync ? createSyncStreamPlugin(sync) : new Elysia())
553
868
  .use(createDataEndpoint(routes))
554
- .use((app) =>
555
- routes.reduce(
556
- (chain, route) => chain.use(createRoutePlugin(route, root, prodBuildId, searchRoutes)),
557
- app
558
- )
559
- )
869
+ .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
870
+ .use(ctx.nativeRoutes)
560
871
  .use(createNotFoundHandling(prefix, routes, root));
561
872
  registerInstance(instance);
562
- return wrapWithRequestScope(prodApp);
873
+ return createFurinPlugin(prodApp, undefined);
563
874
  }
564
875
 
565
876
  /**
@@ -579,35 +890,63 @@ export async function furin({
579
890
  function createNotFoundHandling(
580
891
  prefix: string,
581
892
  routes: Array<{ pattern: string }>,
582
- root: Parameters<typeof renderRootNotFound>[0]
893
+ root: Parameters<typeof renderRootNotFound>[0],
894
+ tryNativeDispatch?: (context: { request: Request }) => Promise<unknown>
583
895
  ): Elysia {
584
896
  const app = new Elysia();
585
897
  if (prefix === "") {
586
- app.onError({ as: "global" }, async ({ code, request }) => {
587
- if (code === "NOT_FOUND") {
588
- return await renderRootNotFound(root, request);
898
+ app.onError({ as: "global" }, async (context) => {
899
+ if (context.code !== "NOT_FOUND") {
900
+ return;
901
+ }
902
+ // Dev topology: the native renderer is rebuilt by the watcher on route
903
+ // add/remove, so a hot-added route (no mounted Elysia route yet) can
904
+ // still be served here. `tryNativeDispatch` is undefined in production.
905
+ if (tryNativeDispatch) {
906
+ const rendered = await tryNativeDispatch(context);
907
+ if (rendered !== undefined && rendered !== null) {
908
+ return rendered;
909
+ }
589
910
  }
911
+ return await renderRootNotFound(root, context.request, context.server?.url.origin);
590
912
  });
591
913
  return app;
592
914
  }
593
915
  if (routes.some((route) => route.pattern === "/*")) {
594
916
  return app;
595
917
  }
596
- app.get("/*", ({ request }) => renderRootNotFound(root, request));
918
+ app.get("/*", async ({ request, server }) => {
919
+ if (tryNativeDispatch) {
920
+ const rendered = await tryNativeDispatch({ request });
921
+ if (rendered !== undefined && rendered !== null) {
922
+ return rendered;
923
+ }
924
+ }
925
+ return renderRootNotFound(root, request, server?.url.origin);
926
+ });
597
927
  return app;
598
928
  }
599
929
 
600
930
  export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
931
+ export { HeadContent, Scripts } from "./client/document.tsx";
601
932
  // ── Public API re-export ──────────────────────────────────────────────────────
602
933
  // biome-ignore-start lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
603
- export type { DeferredData, RuntimePage, RuntimeRoute } from "./client.ts";
934
+ export type { DeferredData } from "./client.ts";
604
935
  export { defer, isDeferred } from "./client.ts";
605
936
  export type { InvalidationInput, InvalidationRule } from "./server/auto-invalidate/index.ts";
606
937
  export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.ts";
607
938
  export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
608
939
  export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
609
- export type { ResolvedRoute, SegmentBoundary } from "./server/router/index.ts";
610
- export { furinSync, type SyncInput, type SyncRouteOption } from "./server/sync/index.ts";
940
+ export {
941
+ type FurinSyncOption,
942
+ type FurinSyncOptions,
943
+ furinSync,
944
+ type SyncAdapter,
945
+ type SyncInput,
946
+ type SyncNotifier,
947
+ type SyncRouteOption,
948
+ type SyncRuntimeOptions,
949
+ } from "./server/sync/index.ts";
611
950
  export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";
612
951
  export type { ErrorComponent, ErrorProps } from "./shared/error.ts";
613
952
  export type {