@teyik0/furin 0.7.0-alpha.3 → 0.9.0-alpha.0

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 (541) hide show
  1. package/README.md +38 -1
  2. package/dist/adapter/build.d.ts +9 -0
  3. package/dist/adapter/bun/app.d.ts +1 -0
  4. package/dist/adapter/bun/server.d.ts +1 -0
  5. package/dist/adapter/bun.d.ts +9 -3
  6. package/dist/adapter/package.d.ts +1 -0
  7. package/dist/adapter/prerender.d.ts +21 -0
  8. package/dist/adapter/runtime-build.d.ts +31 -14
  9. package/dist/adapter/server-bundle.d.ts +20 -0
  10. package/dist/adapter/static.d.ts +2 -2
  11. package/dist/adapter/types.d.ts +81 -0
  12. package/dist/adapter/vercel/bootstrap.d.ts +5 -0
  13. package/dist/adapter/vercel/data.d.ts +23 -0
  14. package/dist/adapter/vercel/handler.d.ts +10 -0
  15. package/dist/adapter/vercel.d.ts +13 -3
  16. package/dist/adapter/vercel.js +516 -0
  17. package/dist/build/bun-build.d.ts +4 -0
  18. package/dist/build/client.d.ts +2 -2
  19. package/dist/build/compile-entry.ts +1 -0
  20. package/dist/build/discover-mounts-process.d.ts +1 -0
  21. package/dist/build/discover-mounts.d.ts +6 -0
  22. package/dist/build/discover-pages-process.d.ts +1 -0
  23. package/dist/build/discover-pages.d.ts +11 -0
  24. package/dist/build/discovery-module.d.ts +3 -0
  25. package/dist/build/discovery-plugins.d.ts +34 -0
  26. package/dist/build/elysia-aot-worker.d.ts +4 -0
  27. package/dist/build/elysia-aot.d.ts +8 -2
  28. package/dist/build/entry-template.d.ts +14 -7
  29. package/dist/build/entry-template.ts +39 -19
  30. package/dist/build/hydrate.d.ts +17 -3
  31. package/dist/build/index.d.ts +7 -3
  32. package/dist/build/index.js +8852 -16175
  33. package/dist/build/preload-manifest.d.ts +2 -2
  34. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  35. package/dist/build/route-metadata.d.ts +31 -0
  36. package/dist/build/route-types.d.ts +8 -2
  37. package/dist/build/server-app-entry.d.ts +2 -2
  38. package/dist/build/shared.d.ts +5 -7
  39. package/dist/build/types.d.ts +27 -16
  40. package/dist/cache.js +117 -32
  41. package/dist/cli/config.d.ts +2 -2
  42. package/dist/cli/dev-worker.d.ts +1 -0
  43. package/dist/cli/dev-worker.ts +123 -0
  44. package/dist/cli/dev.d.ts +1 -0
  45. package/dist/cli/index.js +9104 -16086
  46. package/dist/client/browser-events-runtime.d.ts +2 -2
  47. package/dist/client/browser-events.d.ts +2 -0
  48. package/dist/client/chunks/client-k29262a4.js +59 -0
  49. package/dist/client/chunks/client-k88668k7.js +159 -0
  50. package/dist/client/chunks/client-rjhxgt64.js +1035 -0
  51. package/dist/client/chunks/client-xy6g38kx.js +317 -0
  52. package/dist/client/default-screens.d.ts +0 -11
  53. package/dist/client/define-route.d.ts +2 -1
  54. package/dist/client/dev-error-overlay.ts +18 -1
  55. package/dist/client/hmr.d.ts +1 -1
  56. package/dist/client/internal/runtime-types.d.ts +7 -1
  57. package/dist/client/link.d.ts +1 -0
  58. package/dist/client/link.js +1738 -4184
  59. package/dist/client/mutation.d.ts +5 -0
  60. package/dist/client/query-store.d.ts +22 -7
  61. package/dist/client/query.d.ts +6 -8
  62. package/dist/client/request-id.d.ts +1 -0
  63. package/dist/client/route-api.d.ts +4 -4
  64. package/dist/client/route-element.d.ts +51 -0
  65. package/dist/client/router/boundary-tree.d.ts +1 -9
  66. package/dist/client/router/cache-generation.d.ts +15 -0
  67. package/dist/client/router/context.d.ts +13 -2
  68. package/dist/client/router/fetch-observers.d.ts +9 -0
  69. package/dist/client/router/hmr-refresh.d.ts +12 -0
  70. package/dist/client/router/index.d.ts +5 -7
  71. package/dist/client/router/link-utils.d.ts +0 -2
  72. package/dist/client/router/navigation-controller.d.ts +78 -0
  73. package/dist/client/router/navigation.d.ts +1 -0
  74. package/dist/client/router/page-fetch.d.ts +38 -0
  75. package/dist/client/router/provider.d.ts +2 -3
  76. package/dist/client/router/search/index.d.ts +11 -4
  77. package/dist/client/router/search/index.js +60 -0
  78. package/dist/client/router/spa-response.d.ts +9 -26
  79. package/dist/client/router/transport.d.ts +4 -0
  80. package/dist/client/router/types.d.ts +120 -46
  81. package/dist/client/router/use-fetch-interception.d.ts +12 -0
  82. package/dist/client/router/use-history-sync.d.ts +7 -0
  83. package/dist/client/router/use-hmr-refresh.d.ts +8 -0
  84. package/dist/client/router/use-sync-stream.d.ts +16 -0
  85. package/dist/client/server-error.d.ts +4 -7
  86. package/dist/client/{router/sync-catch-up.d.ts → sync-catch-up.d.ts} +7 -4
  87. package/dist/client/sync-client.d.ts +74 -0
  88. package/dist/client/sync.d.ts +43 -30
  89. package/dist/client.d.ts +3 -1
  90. package/dist/client.js +775 -937
  91. package/dist/config.d.ts +17 -13
  92. package/dist/config.js +3 -31
  93. package/dist/define-route.d.ts +262 -517
  94. package/dist/devtools/protocol.d.ts +4 -3
  95. package/dist/furin.d.ts +42 -31
  96. package/dist/furin.js +21464 -19101
  97. package/dist/plugin/binding-scope.d.ts +15 -2
  98. package/dist/plugin/client-plugin.d.ts +19 -0
  99. package/dist/plugin/dead-code-elimination.d.ts +14 -3
  100. package/dist/plugin/dev-routes.d.ts +22 -0
  101. package/dist/plugin/hmr-data-signature.d.ts +3 -0
  102. package/dist/plugin/hmr-hook-signature.d.ts +9 -0
  103. package/dist/plugin/index.d.ts +1 -6
  104. package/dist/plugin/index.js +1757 -1218
  105. package/dist/plugin/module-bindings.d.ts +11 -0
  106. package/dist/plugin/module-transform.d.ts +29 -0
  107. package/dist/plugin/preflight.d.ts +8 -0
  108. package/dist/plugin/route-chains.d.ts +35 -0
  109. package/dist/plugin/route-config.d.ts +28 -0
  110. package/dist/plugin/route-modules.d.ts +35 -0
  111. package/dist/plugin/route-registry.d.ts +32 -0
  112. package/dist/plugin/route-tree.d.ts +43 -0
  113. package/dist/plugin/strip-server-stages.d.ts +10 -0
  114. package/dist/plugin/strip-server.d.ts +10 -0
  115. package/dist/plugin/transform-client-module.d.ts +3 -0
  116. package/dist/plugin/transform-client.d.ts +0 -2
  117. package/dist/plugin/transform-isomorphic.d.ts +3 -2
  118. package/dist/routes.d.ts +15 -5
  119. package/dist/rsc/build/client-references.d.ts +8 -0
  120. package/dist/rsc/build/discover.d.ts +7 -0
  121. package/dist/rsc/build/flight-loader.d.ts +1 -0
  122. package/dist/rsc/build/index.d.ts +8 -4
  123. package/dist/rsc/build/paths.d.ts +2 -0
  124. package/dist/rsc/bundled-client-codec.d.ts +1 -0
  125. package/dist/rsc/client-codec.d.ts +3 -0
  126. package/dist/rsc/client-references.d.ts +22 -0
  127. package/dist/rsc/server-client-codec.d.ts +1 -0
  128. package/dist/rsc/server-codec.js +3889 -2
  129. package/dist/rsc/slot-proxy.d.ts +11 -0
  130. package/dist/rsc/transport-benchmark.d.ts +2 -1
  131. package/dist/rsc-client.js +16 -164
  132. package/dist/rsc-server.d.ts +1 -5
  133. package/dist/rsc.d.ts +1 -5
  134. package/dist/rsc.js +233 -73
  135. package/dist/server/assets/client-dir.d.ts +1 -0
  136. package/dist/server/auto-invalidate/index.d.ts +2 -2
  137. package/dist/server/auto-invalidate/plugin.d.ts +21 -15
  138. package/dist/server/auto-invalidate/types.d.ts +0 -2
  139. package/dist/server/bounded-body.d.ts +6 -0
  140. package/dist/server/browser-events/plugin.d.ts +4 -1
  141. package/dist/server/browser-events/shutdown.d.ts +1 -1
  142. package/dist/server/cache/dev-loader.d.ts +6 -1
  143. package/dist/server/cache/index.d.ts +4 -9
  144. package/dist/server/cache/invalidation.d.ts +7 -2
  145. package/dist/server/cache/isr-ssg.d.ts +6 -1
  146. package/dist/server/cache/page-cache.d.ts +5 -0
  147. package/dist/server/cache/purger.d.ts +14 -4
  148. package/dist/server/cache/redis/index.d.ts +1 -34
  149. package/dist/server/cache/redis/index.js +51 -25
  150. package/dist/server/cache/redis/scripts.d.ts +1 -1
  151. package/dist/server/cache/route-cache.d.ts +18 -2
  152. package/dist/server/cache/runtime-cache.d.ts +7 -0
  153. package/dist/server/context-logger.d.ts +6 -1
  154. package/dist/server/dev/graph.d.ts +4 -3
  155. package/dist/server/dev/runtime.d.ts +4 -0
  156. package/dist/server/dev/runtime.production.d.ts +1 -0
  157. package/dist/server/dev/server-only-module.d.ts +5 -0
  158. package/dist/server/dev/stack-location.d.ts +9 -0
  159. package/dist/server/dev-page-imports.d.ts +42 -0
  160. package/dist/server/dev-page-plugin.d.ts +2 -49
  161. package/dist/server/devtools/instrumentation.d.ts +1 -3
  162. package/dist/server/devtools/instrumentation.production.d.ts +0 -2
  163. package/dist/server/devtools/request-context.d.ts +7 -0
  164. package/dist/server/evlog.d.ts +18 -6
  165. package/dist/server/instance.d.ts +52 -44
  166. package/dist/server/internal.d.ts +51 -14
  167. package/dist/server/internal.js +9852 -2088
  168. package/dist/server/lang-detect.d.ts +4 -4
  169. package/dist/server/logging/ingest-plugin.d.ts +31 -0
  170. package/dist/server/mode.d.ts +17 -0
  171. package/dist/server/prerender.d.ts +32 -0
  172. package/dist/server/prod/runtime.d.ts +5 -0
  173. package/dist/server/production-server.js +1000 -731
  174. package/dist/server/registrations.d.ts +14 -0
  175. package/dist/server/render/assemble.d.ts +0 -22
  176. package/dist/server/render/buffered-render.d.ts +20 -0
  177. package/dist/server/render/document-stream.d.ts +45 -0
  178. package/dist/server/render/document.d.ts +1 -1
  179. package/dist/server/render/element.d.ts +2 -5
  180. package/dist/server/render/index.d.ts +4 -5
  181. package/dist/server/render/index.ts +4 -21
  182. package/dist/server/render/isr-revalidation.d.ts +5 -0
  183. package/dist/server/render/isr-shared-cache.d.ts +23 -0
  184. package/dist/server/render/isr.d.ts +19 -1
  185. package/dist/server/render/loader-errors.d.ts +33 -0
  186. package/dist/server/render/loader-segments.d.ts +40 -0
  187. package/dist/server/render/loaders.d.ts +16 -32
  188. package/dist/server/render/mixed-cache.d.ts +2 -2
  189. package/dist/server/render/navigation-head.d.ts +13 -0
  190. package/dist/server/render/not-found-plugin.d.ts +18 -0
  191. package/dist/server/render/observe-loader.d.ts +1 -0
  192. package/dist/server/render/ppr-document.d.ts +1 -1
  193. package/dist/server/render/ppr-request.d.ts +0 -2
  194. package/dist/server/render/ppr-route.d.ts +13 -2
  195. package/dist/server/render/prepare-render.d.ts +57 -0
  196. package/dist/server/render/request-loaders.d.ts +19 -0
  197. package/dist/server/render/route-frame-transport.d.ts +7 -1
  198. package/dist/server/render/shell.d.ts +1 -1
  199. package/dist/server/render/shell.ts +1 -1
  200. package/dist/server/render/ssr-transport.d.ts +11 -0
  201. package/dist/server/render/ssr.d.ts +1 -116
  202. package/dist/server/render/static-params.d.ts +15 -0
  203. package/dist/server/router/discovery.d.ts +1 -0
  204. package/dist/server/router/dispatch.d.ts +96 -0
  205. package/dist/server/router/hmr.d.ts +14 -24
  206. package/dist/server/router/patterns.d.ts +15 -20
  207. package/dist/server/router/plugin.d.ts +26 -24
  208. package/dist/server/router/schemas.d.ts +6 -24
  209. package/dist/server/router/types.d.ts +0 -2
  210. package/dist/server/runtime-env.d.ts +6 -1
  211. package/dist/server/server-entry.d.ts +5 -0
  212. package/dist/server/server-entry.js +36 -0
  213. package/dist/server/static-export.d.ts +38 -0
  214. package/dist/server/static-export.js +10777 -0
  215. package/dist/server/sync/adapter.d.ts +13 -1
  216. package/dist/server/sync/atomic.d.ts +0 -2
  217. package/dist/server/sync/config.d.ts +7 -1
  218. package/dist/server/sync/connection.d.ts +13 -0
  219. package/dist/server/sync/drizzle/index.js +113 -68
  220. package/dist/server/sync/fingerprint.d.ts +0 -1
  221. package/dist/server/sync/index.d.ts +5 -6
  222. package/dist/server/sync/index.js +2763 -1320
  223. package/dist/server/sync/invalidate-sync.d.ts +14 -0
  224. package/dist/server/sync/local-client.d.ts +9 -0
  225. package/dist/server/sync/plugin.d.ts +18 -55
  226. package/dist/server/sync/postgres/execute.d.ts +2 -2
  227. package/dist/server/sync/postgres/index.d.ts +3 -1
  228. package/dist/server/sync/postgres/index.js +68 -37
  229. package/dist/server/sync/postgres/migration.sql +2 -0
  230. package/dist/server/sync/principal-journal.d.ts +11 -0
  231. package/dist/server/sync/prisma/index.js +74 -39
  232. package/dist/server/sync/queries.d.ts +57 -16
  233. package/dist/server/sync/redis/index.d.ts +2 -1
  234. package/dist/server/sync/redis/index.js +50 -5
  235. package/dist/server/sync/redis/scripts.d.ts +2 -1
  236. package/dist/server/sync/response.d.ts +3 -0
  237. package/dist/server/sync/runtime.d.ts +8 -1
  238. package/dist/server/sync/sqlite/index.d.ts +3 -1
  239. package/dist/server/sync/sqlite/index.js +59 -27
  240. package/dist/server/sync/stream.d.ts +32 -7
  241. package/dist/server/weak-registry.d.ts +9 -0
  242. package/dist/shared/await.d.ts +2 -1
  243. package/dist/shared/browser-events.d.ts +4 -0
  244. package/dist/shared/compact-json.d.ts +1 -0
  245. package/dist/shared/defer.d.ts +1 -1
  246. package/dist/shared/deferred-ndjson.d.ts +3 -2
  247. package/dist/shared/elysia-contract.d.ts +2 -0
  248. package/dist/shared/in-memory-apps.d.ts +7 -0
  249. package/dist/shared/invalidation-header.d.ts +13 -0
  250. package/dist/shared/navigation-data.d.ts +7 -0
  251. package/dist/shared/prefix.d.ts +11 -5
  252. package/dist/shared/route-frame.d.ts +3 -0
  253. package/dist/shared/route-map.d.ts +7 -0
  254. package/dist/shared/route-matches.d.ts +41 -0
  255. package/dist/shared/route-specificity.d.ts +2 -0
  256. package/dist/shared/search-params.d.ts +2 -3
  257. package/dist/shared/sync-query.d.ts +6 -13
  258. package/dist/shared/utils/ast-walk.d.ts +3 -11
  259. package/dist/sync-client.d.ts +3 -0
  260. package/dist/sync-client.js +1600 -0
  261. package/package.json +39 -23
  262. package/src/adapter/README.md +43 -15
  263. package/src/adapter/build.ts +270 -0
  264. package/src/adapter/bun/app.ts +5 -0
  265. package/src/adapter/bun/server.ts +14 -0
  266. package/src/adapter/bun.ts +104 -264
  267. package/src/adapter/furin-app.d.ts +15 -0
  268. package/src/adapter/package.ts +32 -27
  269. package/src/adapter/prerender.ts +97 -0
  270. package/src/adapter/runtime-build.ts +98 -102
  271. package/src/adapter/server-bundle.ts +110 -0
  272. package/src/adapter/static.ts +276 -260
  273. package/src/adapter/types.ts +89 -0
  274. package/src/adapter/vercel/bootstrap.ts +85 -0
  275. package/src/adapter/vercel/data.ts +21 -0
  276. package/src/adapter/vercel/handler.ts +132 -0
  277. package/src/adapter/vercel.ts +329 -659
  278. package/src/build/bun-build.ts +3 -0
  279. package/src/build/client.ts +27 -63
  280. package/src/build/compile-entry.ts +1 -0
  281. package/src/build/discover-mounts-process.ts +17 -0
  282. package/src/build/discover-mounts.ts +40 -0
  283. package/src/build/discover-pages-process.ts +151 -0
  284. package/src/build/discover-pages.ts +69 -0
  285. package/src/build/discovery-module.ts +70 -0
  286. package/src/build/discovery-plugins.ts +101 -0
  287. package/src/build/elysia-aot-worker.ts +92 -9
  288. package/src/build/elysia-aot.ts +164 -70
  289. package/src/build/entry-template.ts +39 -19
  290. package/src/build/hydrate.ts +131 -50
  291. package/src/build/index.ts +136 -132
  292. package/src/build/preload-manifest.ts +3 -3
  293. package/src/build/private-server-sourcemaps.ts +5 -0
  294. package/src/build/production-instrumentation.ts +22 -19
  295. package/src/build/route-metadata.ts +90 -0
  296. package/src/build/route-types.ts +93 -11
  297. package/src/build/server-app-entry.ts +4 -21
  298. package/src/build/shared.ts +15 -49
  299. package/src/build/types.ts +23 -20
  300. package/src/build/virtual-entry.ts +2 -4
  301. package/src/cli/config.ts +137 -6
  302. package/src/cli/dev-worker.ts +123 -0
  303. package/src/cli/dev.ts +91 -0
  304. package/src/cli/index.ts +82 -21
  305. package/src/cli/preview.ts +2 -1
  306. package/src/client/boundaries.tsx +5 -14
  307. package/src/client/browser-events-runtime.ts +97 -23
  308. package/src/client/browser-events.ts +8 -0
  309. package/src/client/default-screens.tsx +2 -2
  310. package/src/client/define-route.ts +3 -2
  311. package/src/client/dev-error-overlay.ts +18 -1
  312. package/src/client/hmr.ts +1 -1
  313. package/src/client/internal/runtime-types.ts +7 -1
  314. package/src/client/link.tsx +80 -43
  315. package/src/client/mutation.ts +98 -3
  316. package/src/client/query-store.ts +213 -31
  317. package/src/client/query.tsx +12 -29
  318. package/src/client/request-id.ts +10 -0
  319. package/src/client/route-api.tsx +6 -6
  320. package/src/client/route-element.tsx +155 -0
  321. package/src/client/router/boundary-tree.tsx +2 -93
  322. package/src/client/router/cache-generation.ts +37 -0
  323. package/src/client/router/context.ts +40 -4
  324. package/src/client/router/fetch-observers.ts +46 -0
  325. package/src/client/router/hmr-refresh.ts +50 -0
  326. package/src/client/router/index.ts +7 -29
  327. package/src/client/router/link-utils.ts +19 -31
  328. package/src/client/router/navigation-controller.ts +580 -0
  329. package/src/client/router/navigation.ts +3 -2
  330. package/src/client/router/optimistic.ts +2 -3
  331. package/src/client/router/page-fetch.ts +272 -0
  332. package/src/client/router/provider.tsx +227 -1079
  333. package/src/client/router/search/index.ts +38 -14
  334. package/src/client/router/spa-response.ts +19 -70
  335. package/src/client/router/transport.ts +23 -0
  336. package/src/client/router/types.ts +203 -61
  337. package/src/client/router/use-fetch-interception.ts +52 -0
  338. package/src/client/router/use-history-sync.ts +56 -0
  339. package/src/client/router/use-hmr-refresh.ts +51 -0
  340. package/src/client/router/use-sync-stream.ts +181 -0
  341. package/src/client/server-error.ts +2 -40
  342. package/src/client/sync-catch-up.ts +194 -0
  343. package/src/client/sync-client.ts +528 -0
  344. package/src/client/sync.ts +275 -378
  345. package/src/client.ts +10 -5
  346. package/src/config.ts +34 -49
  347. package/src/define-route.ts +487 -882
  348. package/src/devtools/devtools-element.js +10 -3
  349. package/src/devtools/protocol.ts +3 -3
  350. package/src/furin.ts +258 -1086
  351. package/src/plugin/binding-scope.ts +219 -94
  352. package/src/plugin/client-plugin.ts +145 -0
  353. package/src/plugin/dead-code-elimination.ts +390 -111
  354. package/src/plugin/dev-routes.ts +453 -0
  355. package/src/plugin/hmr-data-signature.ts +161 -0
  356. package/src/plugin/hmr-dependencies.ts +2 -4
  357. package/src/plugin/hmr-hook-signature.ts +252 -0
  358. package/src/plugin/index.ts +3 -96
  359. package/src/plugin/module-bindings.ts +216 -0
  360. package/src/plugin/module-transform.ts +63 -0
  361. package/src/plugin/preflight.ts +66 -0
  362. package/src/plugin/route-chains.ts +309 -0
  363. package/src/plugin/route-config.ts +451 -0
  364. package/src/plugin/route-modules.ts +209 -0
  365. package/src/plugin/route-registry.ts +362 -0
  366. package/src/plugin/route-tree.ts +248 -0
  367. package/src/plugin/strip-server-stages.ts +197 -0
  368. package/src/plugin/strip-server.ts +22 -0
  369. package/src/plugin/transform-client-module.ts +36 -31
  370. package/src/plugin/transform-client.ts +33 -1114
  371. package/src/plugin/transform-dev-page.ts +84 -92
  372. package/src/plugin/transform-isomorphic.ts +396 -185
  373. package/src/routes.ts +15 -5
  374. package/src/rsc/build/client-references.ts +267 -0
  375. package/src/rsc/build/discover.ts +226 -0
  376. package/src/rsc/build/flight-loader.ts +69 -0
  377. package/src/rsc/build/index.ts +59 -34
  378. package/src/rsc/build/paths.ts +7 -0
  379. package/src/rsc/bundled-client-codec.ts +4 -0
  380. package/src/rsc/client-codec.ts +12 -3
  381. package/src/rsc/client-references.ts +138 -0
  382. package/src/rsc/codec.ts +30 -21
  383. package/src/rsc/flight-drain.ts +6 -29
  384. package/src/rsc/react-server-dom-webpack.d.ts +1 -1
  385. package/src/rsc/server-client-codec.ts +14 -0
  386. package/src/rsc/server-codec.ts +5 -8
  387. package/src/rsc/slot-proxy.ts +34 -0
  388. package/src/rsc/transport-benchmark.ts +1 -1
  389. package/src/rsc-server.tsx +5 -23
  390. package/src/rsc.tsx +5 -29
  391. package/src/server/assets/client-dir.ts +110 -0
  392. package/src/server/assets/production.ts +1 -1
  393. package/src/server/auto-invalidate/index.ts +2 -7
  394. package/src/server/auto-invalidate/plugin.ts +43 -15
  395. package/src/server/auto-invalidate/registry.ts +6 -6
  396. package/src/server/auto-invalidate/runtime.ts +16 -98
  397. package/src/server/auto-invalidate/types.ts +0 -6
  398. package/src/server/bounded-body.ts +38 -0
  399. package/src/server/browser-events/plugin.ts +167 -26
  400. package/src/server/browser-events/shutdown.ts +28 -9
  401. package/src/server/cache/dev-loader.ts +30 -16
  402. package/src/server/cache/index.ts +2 -15
  403. package/src/server/cache/invalidation.ts +27 -46
  404. package/src/server/cache/isr-ssg.ts +6 -1
  405. package/src/server/cache/isr.ts +11 -11
  406. package/src/server/cache/page-cache-state.ts +2 -2
  407. package/src/server/cache/page-cache.ts +13 -9
  408. package/src/server/cache/purger.ts +64 -8
  409. package/src/server/cache/redis/index.ts +17 -27
  410. package/src/server/cache/redis/scripts.ts +21 -4
  411. package/src/server/cache/registry.ts +3 -3
  412. package/src/server/cache/route-cache.ts +47 -13
  413. package/src/server/cache/runtime-cache.ts +144 -24
  414. package/src/server/cache/ssg.ts +7 -5
  415. package/src/server/context-logger.ts +46 -8
  416. package/src/server/dev/diagnostics.ts +6 -56
  417. package/src/server/dev/error.ts +3 -34
  418. package/src/server/dev/graph.ts +35 -22
  419. package/src/server/dev/rewrite-module-specifiers.ts +16 -19
  420. package/src/server/dev/runtime.production.ts +4 -0
  421. package/src/server/dev/runtime.ts +404 -0
  422. package/src/server/dev/server-only-module.ts +23 -0
  423. package/src/server/dev/stack-location.ts +46 -0
  424. package/src/server/dev/symbolicate.ts +4 -3
  425. package/src/server/dev-page-imports.ts +185 -0
  426. package/src/server/dev-page-plugin.ts +57 -303
  427. package/src/server/devtools/hub.ts +3 -3
  428. package/src/server/devtools/instrumentation.production.ts +0 -8
  429. package/src/server/devtools/instrumentation.ts +6 -8
  430. package/src/server/devtools/plugin.ts +2 -1
  431. package/src/server/devtools/request-context.ts +67 -16
  432. package/src/server/evlog.ts +119 -55
  433. package/src/server/instance.ts +187 -138
  434. package/src/server/internal.ts +66 -62
  435. package/src/server/lang-detect.ts +31 -22
  436. package/src/server/logging/ingest-plugin.ts +117 -0
  437. package/src/server/mode.ts +19 -0
  438. package/src/server/prerender.ts +122 -0
  439. package/src/server/prod/runtime.ts +181 -0
  440. package/src/server/production-server.ts +43 -17
  441. package/src/server/registrations.ts +38 -0
  442. package/src/server/render/assemble.ts +5 -8
  443. package/src/server/render/buffered-render.ts +171 -0
  444. package/src/server/render/document-stream.ts +188 -0
  445. package/src/server/render/document.tsx +5 -3
  446. package/src/server/render/element.tsx +6 -73
  447. package/src/server/render/index.ts +4 -21
  448. package/src/server/render/isr-revalidation.ts +246 -0
  449. package/src/server/render/isr-shared-cache.ts +141 -0
  450. package/src/server/render/isr.ts +212 -516
  451. package/src/server/render/loader-errors.ts +183 -0
  452. package/src/server/render/loader-segments.ts +149 -0
  453. package/src/server/render/loaders.ts +126 -547
  454. package/src/server/render/mixed-cache.ts +28 -27
  455. package/src/server/render/navigation-head.ts +33 -0
  456. package/src/server/render/not-found-plugin.ts +31 -0
  457. package/src/server/render/not-found.ts +32 -8
  458. package/src/server/render/observe-loader.ts +46 -0
  459. package/src/server/render/ppr-document.ts +36 -14
  460. package/src/server/render/ppr-request.ts +2 -2
  461. package/src/server/render/ppr-route.ts +79 -18
  462. package/src/server/render/prepare-render.ts +251 -0
  463. package/src/server/render/request-loaders.ts +216 -0
  464. package/src/server/render/route-frame-transport.ts +41 -4
  465. package/src/server/render/shell.ts +1 -1
  466. package/src/server/render/ssg.ts +9 -20
  467. package/src/server/render/ssr-transport.ts +221 -0
  468. package/src/server/render/ssr.ts +95 -956
  469. package/src/server/render/static-params.ts +32 -0
  470. package/src/server/render/template.ts +7 -7
  471. package/src/server/router/discovery.ts +82 -159
  472. package/src/server/router/dispatch.ts +337 -0
  473. package/src/server/router/hmr.ts +177 -190
  474. package/src/server/router/patterns.ts +39 -65
  475. package/src/server/router/plugin.ts +234 -359
  476. package/src/server/router/schemas.ts +6 -39
  477. package/src/server/router/source-version.ts +5 -4
  478. package/src/server/router/types.ts +0 -2
  479. package/src/server/runtime-env.ts +6 -1
  480. package/src/server/server-entry.ts +39 -0
  481. package/src/server/static-export.ts +143 -0
  482. package/src/server/sync/adapter.ts +16 -1
  483. package/src/server/sync/atomic.ts +16 -36
  484. package/src/server/sync/config.ts +12 -14
  485. package/src/server/sync/connection.ts +71 -0
  486. package/src/server/sync/drizzle/index.ts +12 -20
  487. package/src/server/sync/fingerprint.ts +1 -1
  488. package/src/server/sync/index.ts +5 -10
  489. package/src/server/sync/invalidate-sync.ts +56 -0
  490. package/src/server/sync/local-client.ts +84 -0
  491. package/src/server/sync/mutation-handler.ts +6 -0
  492. package/src/server/sync/plugin.ts +193 -144
  493. package/src/server/sync/postgres/execute.ts +9 -1
  494. package/src/server/sync/postgres/index.ts +78 -39
  495. package/src/server/sync/postgres/migration.sql +2 -0
  496. package/src/server/sync/principal-journal.ts +78 -0
  497. package/src/server/sync/prisma/index.ts +1 -0
  498. package/src/server/sync/queries.ts +133 -40
  499. package/src/server/sync/query-context.ts +38 -5
  500. package/src/server/sync/redis/index.ts +38 -6
  501. package/src/server/sync/redis/scripts.ts +10 -1
  502. package/src/server/sync/response.ts +47 -67
  503. package/src/server/sync/runtime.ts +74 -19
  504. package/src/server/sync/sqlite/index.ts +96 -61
  505. package/src/server/sync/sqlite/migration.sql +1 -0
  506. package/src/server/sync/stream.ts +62 -29
  507. package/src/server/sync/validation.ts +1 -1
  508. package/src/server/weak-registry.ts +37 -0
  509. package/src/shared/await.tsx +2 -1
  510. package/src/shared/browser-events.ts +1 -1
  511. package/src/shared/compact-json.ts +1 -1
  512. package/src/shared/defer.ts +1 -1
  513. package/src/shared/deferred-ndjson.ts +142 -120
  514. package/src/shared/elysia-contract.ts +7 -0
  515. package/src/shared/error.ts +1 -4
  516. package/src/shared/in-memory-apps.ts +24 -0
  517. package/src/shared/invalidation-header.ts +38 -0
  518. package/src/shared/navigation-data.ts +29 -0
  519. package/src/shared/prefix.ts +42 -6
  520. package/src/shared/route-frame.ts +82 -26
  521. package/src/shared/route-map.ts +23 -39
  522. package/src/shared/route-matches.ts +59 -0
  523. package/src/shared/route-specificity.ts +28 -0
  524. package/src/shared/search-params.ts +6 -35
  525. package/src/shared/sync-query.ts +30 -23
  526. package/src/shared/utils/ast-walk.ts +9 -25
  527. package/src/shared/utils/index.ts +1 -1
  528. package/src/sync-client.ts +14 -0
  529. package/dist/build/scan-server.d.ts +0 -14
  530. package/dist/build/ssg-cache.d.ts +0 -18
  531. package/dist/plugin/route-config-autofix.d.ts +0 -31
  532. package/dist/plugin/routes.d.ts +0 -34
  533. package/dist/server/logger.d.ts +0 -4
  534. package/dist/server/router/hmr.production.d.ts +0 -7
  535. package/src/build/scan-server.ts +0 -112
  536. package/src/build/ssg-cache.ts +0 -126
  537. package/src/client/router/sync-catch-up.ts +0 -120
  538. package/src/plugin/route-config-autofix.ts +0 -1149
  539. package/src/plugin/routes.ts +0 -1140
  540. package/src/server/logger.ts +0 -21
  541. package/src/server/router/hmr.production.ts +0 -18
package/src/furin.ts CHANGED
@@ -1,112 +1,43 @@
1
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import { basename, delimiter, dirname, join, resolve } from "node:path";
3
- import { fileURLToPath } from "node:url";
4
- import { staticPlugin } from "@elysia/static";
5
- import { type AnyElysia, Elysia, file, NotFound, problem } from "elysia";
6
- import type { DrainContext, LoggerConfig } from "evlog";
7
- import { FURIN_RENDER_DECORATOR, type FurinRouteDispatcher } from "./define-route.ts";
8
- import { createProductionAssetsPlugin } from "./server/assets/production.ts";
1
+ import { dirname, resolve } from "node:path";
2
+ import { type AnyElysia, Elysia, NotFound } from "elysia";
3
+ import type { RequestLogger } from "evlog";
4
+ import { FURIN_RENDER_DECORATOR, type FurinNativeRouteContext } from "./define-route.ts";
9
5
  import { consumePendingInvalidations } from "./server/cache/invalidation.ts";
10
6
  import type { PageCacheAdapter } from "./server/cache/page-cache.ts";
11
7
  import { setPageCacheAdapter } from "./server/cache/page-cache-state.ts";
12
- import { setSSGCache } from "./server/cache/ssg.ts";
13
- import { getLogger } from "./server/context-logger.ts";
14
- import type { DevelopmentRouteSnapshot, DevGraph } from "./server/dev/graph.ts";
15
8
  import {
16
- createInstrumentationPlugin,
17
- instrumentationLoggerExclusions,
18
- runWithRequestInstrumentation,
19
- shouldInstrumentRequest,
20
- } from "./server/devtools/instrumentation.ts";
21
- import { createFurinEvlog, type FurinEvlogOptions } from "./server/evlog.ts";
9
+ type CachePurger,
10
+ setInstanceCachePurger,
11
+ setInstanceCacheTagPurger,
12
+ } from "./server/cache/purger.ts";
22
13
  import {
23
- assertPrefixAvailable,
24
14
  createInstance,
25
15
  type FurinInstance,
26
- hasRequestScope,
27
- markTraffic,
28
16
  normalizePrefix,
29
17
  registerInstance,
30
- resolveInstanceByPath,
31
- runWithInstanceScope,
32
- withInstance,
18
+ unregisterInstance,
33
19
  } from "./server/instance.ts";
34
- import type { CompileContext, EmbeddedAppData } from "./server/internal.ts";
35
- import { getCompileContext } from "./server/internal.ts";
36
- import { initializeFurinLogger } from "./server/logger.ts";
37
- import { renderRootNotFound } from "./server/render/not-found.ts";
38
- import { warmSSGCache } from "./server/render/ssg.ts";
20
+ import { type CompileContext, getCompileContext } from "./server/internal.ts";
21
+ import { createLoggerPlugin, type FurinLoggerOptions } from "./server/logging/ingest-plugin.ts";
22
+ import type { ModeOptions, ModeRuntime } from "./server/mode.ts";
23
+ import { createProdRuntime } from "./server/prod/runtime.ts";
24
+ import { recordFurinRegistration } from "./server/registrations.ts";
25
+ import { createNotFoundHandling } from "./server/render/not-found-plugin.ts";
39
26
  import {
40
- setProductionPreloadManifest,
41
- setProductionTemplateContent,
42
- setProductionTemplatePath,
43
- } from "./server/render/template.ts";
44
- import { loadProdRoutes } from "./server/router/discovery.ts";
45
- import { invalidateStampedRouteModules, resolveCurrentDevRoute } from "./server/router/hmr.ts";
46
- import { buildRouteMatcher } from "./server/router/patterns.ts";
47
- import {
48
- renderResolvedRoute,
49
- renderRouteData,
50
- serializeGuardRedirect,
51
- } from "./server/router/plugin.ts";
52
- import { mergeRouteSchemas } from "./server/router/schema-merge.ts";
53
- import {
54
- createSearchRouteMetadata,
55
- parseDataEndpointPath,
56
- parseRouteParams,
57
- parseRouteQuery,
58
- } from "./server/router/schemas.ts";
59
- import type { ResolvedRoute, RootLayout } from "./server/router/types.ts";
60
- import { IS_DEV } from "./server/runtime-env.ts";
27
+ createRequestScope,
28
+ dispatchNativeRoute,
29
+ renderNotFound,
30
+ } from "./server/router/dispatch.ts";
61
31
  import { type FurinSyncOption, resolveSyncPath } from "./server/sync/config.ts";
62
32
  import { bindSyncValidation } from "./server/sync/validation.ts";
63
- import { physicalPath } from "./shared/prefix.ts";
33
+ import { serializeInvalidationPaths } from "./shared/invalidation-header.ts";
34
+ import { assertOnePagesDirPerMount } from "./shared/prefix.ts";
64
35
 
65
36
  // biome-ignore lint/suspicious/noEmptyInterface: intentionally augmentable via furin-env.d.ts
66
37
  export interface FurinCacheTags {}
67
38
 
68
39
  export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
69
40
 
70
- async function createProductionBrowserEventsPlugin(
71
- sync: FurinSyncOption | undefined,
72
- deploymentTarget: "vercel" | undefined
73
- ): Promise<AnyElysia> {
74
- if (!sync) {
75
- return new Elysia();
76
- }
77
- const browserEvents = await import("./server/browser-events/plugin.ts");
78
- // Vercel invokes app.handle(Request), so Elysia's Bun.Server WebSocket upgrade is unavailable.
79
- return deploymentTarget === "vercel"
80
- ? browserEvents.createSseBrowserEventsPlugin({ sync })
81
- : browserEvents.createBrowserEventsPlugin({ sync });
82
- }
83
-
84
- function repairedDevelopmentRoutes(
85
- snapshot: DevelopmentRouteSnapshot,
86
- changedSources: readonly string[],
87
- graph: DevGraph<DevelopmentRouteSnapshot | null>
88
- ): { patterns: ReadonlySet<string>; root: boolean } {
89
- const patterns = new Set<string>();
90
- for (const route of snapshot.routes) {
91
- if (
92
- changedSources.some(
93
- (sourcePath) => route.path === sourcePath || graph.dependsOn(route.path, sourcePath)
94
- )
95
- ) {
96
- patterns.add(route.pattern);
97
- }
98
- }
99
- return {
100
- patterns,
101
- root: changedSources.some(
102
- (sourcePath) =>
103
- snapshot.root.path === sourcePath || graph.dependsOn(snapshot.root.path, sourcePath)
104
- ),
105
- };
106
- }
107
-
108
- import { clientDirNameForPrefix } from "./shared/prefix.ts";
109
-
110
41
  // biome-ignore lint/performance/noBarrelFile: furin.ts is the public package entry
111
42
  export {
112
43
  type DefineRouteConfig,
@@ -123,553 +54,55 @@ export {
123
54
  type IsomorphicFnBuilder,
124
55
  type ServerIsomorphicFn,
125
56
  } from "./isomorphic.ts";
57
+ export type { FurinLoggerOptions } from "./server/logging/ingest-plugin.ts";
58
+ export { isFurinPageRequest } from "./server/router/dispatch.ts";
126
59
  export { type FurinCspOptions, furinCsp } from "./server/security/csp.ts";
127
- export { clientDirNameForPrefix } from "./shared/prefix.ts";
128
-
129
- const MAX_BROWSER_INGEST_BYTES = 64 * 1024;
130
- const MAX_BROWSER_INGEST_EVENTS = 100;
131
- function resolveClientDirFromArgv(prefix: string): string {
132
- const dirName = clientDirNameForPrefix(prefix);
133
- return (
134
- resolveClientDirFromEnv(dirName) ??
135
- resolveClientDirFromModuleUrl(dirName) ??
136
- resolveClientDirFromProcessArgs(dirName) ??
137
- resolveFallbackClientDir(dirName)
138
- );
139
- }
140
-
141
- function resolveClientDirFromEnv(dirName: string): string | null {
142
- const envClientDir = process.env.FURIN_CLIENT_DIR;
143
- if (!envClientDir) {
144
- return null;
145
- }
146
- const base = envClientDir.startsWith("/") ? envClientDir : resolve(process.cwd(), envClientDir);
147
- // FURIN_CLIENT_DIR points at the ROOT instance's client dir; sibling
148
- // instances live next to it under their own dir name.
149
- return dirName === "client" ? base : join(dirname(base), dirName);
150
- }
151
-
152
- function resolveClientDirFromModuleUrl(dirName: string): string | null {
153
- try {
154
- const moduleUrl = new URL(import.meta.url);
155
- if (moduleUrl.protocol !== "file:") {
156
- return null;
157
- }
158
- const modulePath = fileURLToPath(moduleUrl);
159
- if (modulePath.includes("/$bunfs/")) {
160
- return null;
161
- }
162
- const moduleClientDir = join(dirname(modulePath), dirName);
163
- if (existsSync(join(moduleClientDir, "index.html"))) {
164
- return moduleClientDir;
165
- }
166
- } catch {
167
- // ignore, fallback to argv-based resolution
168
- }
169
- return null;
170
- }
171
-
172
- function resolveClientDirFromProcessArgs(dirName: string): string | null {
173
- const candidates = [
174
- process.argv[1],
175
- process.argv[0],
176
- (process as { argv0?: string }).argv0,
177
- process.execPath,
178
- ].filter((value): value is string => typeof value === "string" && value.length > 0);
179
-
180
- for (const candidate of candidates) {
181
- const resolved = resolveClientDirFromCandidate(candidate, dirName);
182
- if (resolved) {
183
- return resolved;
184
- }
185
- }
186
-
187
- return null;
188
- }
189
-
190
- function resolveClientDirFromCandidate(candidate: string, dirName: string): string | null {
191
- const name = basename(candidate);
192
- if (name === "bun" || name === "node") {
193
- return null;
194
- }
195
- if (candidate.includes("/$bunfs/") || candidate.startsWith("bunfs:")) {
196
- return null;
197
- }
198
-
199
- const absolute = candidate.startsWith("/") ? candidate : resolve(process.cwd(), candidate);
200
- if (existsSync(absolute)) {
201
- const clientDir = join(dirname(absolute), dirName);
202
- if (existsSync(join(clientDir, "index.html"))) {
203
- return clientDir;
204
- }
205
- }
206
-
207
- if (!candidate.includes("/")) {
208
- return resolveClientDirFromPath(candidate, dirName);
209
- }
210
-
211
- return null;
212
- }
213
-
214
- function resolveClientDirFromPath(candidate: string, dirName: string): string | null {
215
- const pathEntries = process.env.PATH?.split(delimiter) ?? [];
216
- for (const dir of pathEntries) {
217
- const fullPath = join(dir, candidate);
218
- if (existsSync(fullPath)) {
219
- const clientDir = join(dirname(fullPath), dirName);
220
- if (existsSync(join(clientDir, "index.html"))) {
221
- return clientDir;
222
- }
223
- }
224
- }
225
- return null;
226
- }
227
-
228
- function resolveFallbackClientDir(dirName: string): string {
229
- const defaultClientDir = resolve(process.cwd(), ".furin/build/bun", dirName);
230
- if (existsSync(join(defaultClientDir, "index.html"))) {
231
- return defaultClientDir;
232
- }
233
-
234
- return join(process.cwd(), dirName);
235
- }
236
-
237
- async function setupProdTemplate(
238
- embedded: EmbeddedAppData | undefined,
239
- clientDir: string,
240
- instance: FurinInstance
241
- ): Promise<void> {
242
- if (embedded) {
243
- const templatePath = join(embedded.clientDir, "index.html");
244
- if (!existsSync(templatePath)) {
245
- throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
246
- }
247
- const html = await Bun.file(templatePath).text();
248
- setProductionTemplateContent(html, instance);
249
- return;
250
- }
251
-
252
- const templatePath = join(clientDir, "index.html");
253
- if (!existsSync(templatePath)) {
254
- throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
255
- }
256
- setProductionTemplatePath(templatePath, instance);
257
- }
258
-
259
- async function setupCompiledTemplate(
260
- ctx: CompileContext,
261
- embedded: EmbeddedAppData | undefined,
262
- clientDir: string,
263
- instance: FurinInstance
264
- ): Promise<void> {
265
- if (ctx.preloadManifest) {
266
- setProductionPreloadManifest(ctx.preloadManifest, instance);
267
- }
268
- if (ctx.templateHtml === undefined) {
269
- await setupProdTemplate(embedded, clientDir, instance);
270
- return;
271
- }
272
- setProductionTemplateContent(ctx.templateHtml, instance);
273
- }
274
-
275
- /**
276
- * Shape of one browser-submitted log event. The named keys are the dangerous
277
- * ones stripped before `log.set` (prototype-pollution vectors, plus the
278
- * browser `environment` which must not overwrite the server's); everything
279
- * else is forwarded as-is.
280
- */
281
- interface FurinBrowserEvent {
282
- __proto__?: unknown;
283
- constructor?: unknown;
284
- environment?: unknown;
285
- prototype?: unknown;
286
- [key: string]: unknown;
287
- }
288
-
289
- type BrowserIngestRead =
290
- | { body: unknown; kind: "ok" }
291
- | { kind: "invalid" }
292
- | { kind: "oversized" };
293
-
294
- async function readBrowserIngest(request: Request): Promise<BrowserIngestRead> {
295
- const contentLength = request.headers.get("content-length");
296
- if (contentLength) {
297
- const declaredBytes = Number(contentLength);
298
- if (Number.isFinite(declaredBytes) && declaredBytes > MAX_BROWSER_INGEST_BYTES) {
299
- await request.body?.cancel();
300
- return { kind: "oversized" };
301
- }
302
- }
303
- if (request.body === null) {
304
- return { kind: "invalid" };
305
- }
306
- const reader = request.body.getReader();
307
- const chunks: Uint8Array[] = [];
308
- let total = 0;
309
- try {
310
- for (;;) {
311
- // biome-ignore lint/performance/noAwaitInLoops: request body chunks must be read sequentially.
312
- const { done, value } = await reader.read();
313
- if (done) {
314
- break;
315
- }
316
- total += value.byteLength;
317
- if (total > MAX_BROWSER_INGEST_BYTES) {
318
- await reader.cancel();
319
- return { kind: "oversized" };
320
- }
321
- chunks.push(value);
322
- }
323
- } finally {
324
- reader.releaseLock();
325
- }
326
- const bytes = new Uint8Array(total);
327
- let offset = 0;
328
- for (const chunk of chunks) {
329
- bytes.set(chunk, offset);
330
- offset += chunk.byteLength;
331
- }
332
- try {
333
- return { body: JSON.parse(new TextDecoder().decode(bytes)), kind: "ok" };
334
- } catch {
335
- return { kind: "invalid" };
336
- }
337
- }
338
-
339
- /** Evlog wide-event plugin + browser log ingest endpoint for one instance. */
340
- function createLoggerPlugin(
341
- prefix: string,
342
- syncPath: string | undefined,
343
- logger: FurinEvlogOptions | undefined,
344
- clientLogging: boolean
345
- ) {
346
- const { exclude: userExclude, ...evlogOptions } = logger ?? {};
347
- const app = new Elysia().use(
348
- createFurinEvlog({
349
- ...evlogOptions,
350
- // Exclude patterns match the PHYSICAL request path — prefix them.
351
- exclude: [
352
- `${prefix}/_client/**`,
353
- `${prefix}/public/**`,
354
- `${prefix}/favicon.ico`,
355
- `${prefix}/_bun_hmr_entry/**`,
356
- ...instrumentationLoggerExclusions(prefix),
357
- ...(syncPath ? [`${prefix}${syncPath}/**`] : []),
358
- // Note: /_furin/data is logged with the logical page path, so SPA navigations
359
- // appear as "GET /board/123 200" — same shape as a normal SSR nav.
360
- // /_furin/ingest remains loggable when browser logging is explicitly
361
- // enabled so browser-side events show up.
362
- // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
363
- // like `!(...)` matches nothing, so don't add patterns relying on it.
364
- ...(userExclude ?? []),
365
- ],
366
- })
367
- );
368
-
369
- if (!clientLogging) {
370
- return app;
371
- }
372
-
373
- return app.post("/_furin/ingest", { parse: "none" }, async ({ log, request, status }) => {
374
- const parsed = await readBrowserIngest(request);
375
- if (parsed.kind === "oversized") {
376
- return problem(413, { detail: "Browser event payload exceeds 64 KiB." });
377
- }
378
- if (parsed.kind === "invalid") {
379
- return problem("Bad Request", { detail: "Browser event payload must be valid JSON." });
380
- }
381
- const { body } = parsed;
382
- if (!Array.isArray(body)) {
383
- return problem("Bad Request", { detail: "Browser event payload must be a JSON array." });
384
- }
385
- const batch = (body as DrainContext[]).slice(0, MAX_BROWSER_INGEST_EVENTS);
386
- for (const entry of batch) {
387
- if (!entry || typeof entry !== "object" || !("event" in entry)) {
388
- log.set({ msg: "[furin] ingest: skipping malformed entry" });
389
- continue;
390
- }
391
- // Pick only safe, known fields from the event to prevent prototype pollution
392
- const event = entry.event as FurinBrowserEvent | undefined;
393
- if (!event || typeof event !== "object") {
394
- continue;
395
- }
396
- const {
397
- __proto__,
398
- constructor: _ctor,
399
- prototype,
400
- environment: _browserEnv,
401
- ...safeEvent
402
- } = event;
403
- log.set({ ...safeEvent, service: "furin:browser" });
404
- }
405
- return status("No Content");
406
- }) as unknown as Elysia;
407
- }
408
-
409
- function initializeLogger(logger: FurinLoggerOptions | undefined): FurinEvlogOptions {
410
- const { sampling, ...elysiaLoggerOptions } = logger ?? {};
411
- initializeFurinLogger({
412
- env: { service: "furin" },
413
- ...(sampling ? { sampling } : {}),
414
- });
415
- return elysiaLoggerOptions;
416
- }
417
-
418
- /**
419
- * Registers a HigherOrderFunction on the Elysia instance so that every request
420
- * runs inside a fresh instance-bound `AsyncLocalStorage` scope. This isolates
421
- * `pendingInvalidations` per request AND binds the request to the furin
422
- * instance that owns its path, so render/cache code resolves the right
423
- * per-instance state (build ID, template, caches, sync path).
424
- *
425
- * Uses `app.wrap()` (Elysia HigherOrderFunction) instead of mutating
426
- * `app.handle`, because handle mutations are lost when the Furin plugin is
427
- * `.use()`-d by a parent Elysia instance. HigherOrderFunctions survive the
428
- * plugin merge and wrap the entire composed `map` handler.
429
- *
430
- * IMPORTANT — multi-instance: HigherOrderFunctions apply to the WHOLE parent
431
- * app, so with N mounted furin instances all N wraps run stacked on every
432
- * request. The scope guard makes the wrap idempotent (first one wins) and the
433
- * owning instance is resolved from the request PATH, never from this
434
- * closure — which wrap executes first is therefore irrelevant.
435
- */
436
- const navigationDataRequests = new WeakSet<Request>();
437
- const navigationDataRefreshers = new WeakMap<FurinInstance, () => Promise<void>>();
438
- const navigationDataMatchers = new WeakMap<FurinInstance, (path: string) => boolean>();
439
-
440
- /** Whether a request targets a registered page in the specified Furin mount. */
441
- export function isFurinPageRequest(request: Request, prefix: string): boolean {
442
- if (request.method !== "GET") {
443
- return false;
444
- }
445
- const url = new URL(request.url);
446
- const { pathname } = url;
447
- const mountPrefix = normalizePrefix(prefix);
448
- const instance = resolveInstanceByPath(pathname);
449
- if (instance.prefix !== mountPrefix) {
450
- return false;
451
- }
452
- const path = pathname.slice(mountPrefix.length) || "/";
453
- if (path === "/_furin/data") {
454
- const dataPath = parseDataEndpointPath(url.searchParams.get("path") ?? "");
455
- return (
456
- dataPath !== undefined && (navigationDataMatchers.get(instance)?.(dataPath.pathname) ?? false)
457
- );
458
- }
459
- if (
460
- path.startsWith("/_client/") ||
461
- path.startsWith("/_furin/") ||
462
- path.startsWith("/_bun_hmr_entry") ||
463
- path.startsWith("/public/") ||
464
- path === "/favicon.ico"
465
- ) {
466
- return false;
467
- }
468
- return navigationDataMatchers.get(instance)?.(path) ?? false;
469
- }
470
60
 
471
- function rewriteNavigationDataRequest(
472
- request: Request,
473
- instance: FurinInstance
474
- ): Request | Response {
475
- const url = new URL(request.url);
476
- if (request.method !== "GET" || url.pathname !== `${instance.prefix}/_furin/data`) {
477
- return request;
478
- }
479
- const rawPath = url.searchParams.get("path");
480
- if (!rawPath) {
481
- return new Response("Missing required query param: path", { status: 400 });
482
- }
483
- const parsed = parseDataEndpointPath(rawPath);
484
- if (!parsed) {
485
- return new Response("Invalid path", { status: 400 });
486
- }
487
- if (!navigationDataMatchers.get(instance)?.(parsed.pathname)) {
488
- return new Response("Not Found", { status: 404 });
489
- }
490
- url.pathname = physicalPath(instance.prefix, parsed.pathname);
491
- url.search = parsed.url.search;
492
- const rewritten = new Request(url, request);
493
- navigationDataRequests.add(rewritten);
494
- return rewritten;
495
- }
496
-
497
- function wrapWithRequestScope(app: AnyElysia): Elysia {
498
- return app.wrap((fetch) => (request, ...rest) => {
499
- if (hasRequestScope()) {
500
- return fetch(request, ...rest);
501
- }
502
- markTraffic();
503
- const { pathname } = new URL(request.url);
504
- const instance = resolveInstanceByPath(pathname);
505
- return runWithInstanceScope(instance, () => {
506
- const dispatch = () => {
507
- const rewritten = rewriteNavigationDataRequest(request, instance);
508
- if (rewritten instanceof Response) {
509
- return rewritten;
510
- }
511
- const response = shouldInstrumentRequest(pathname, instance.prefix)
512
- ? runWithRequestInstrumentation(request, () => fetch(rewritten, ...rest))
513
- : fetch(rewritten, ...rest);
514
- if (rewritten === request) {
515
- return response;
516
- }
517
- return Promise.resolve(response).then((resolved) =>
518
- resolved.status >= 300 && resolved.status < 400
519
- ? serializeGuardRedirect(resolved, request)
520
- : resolved
521
- );
522
- };
523
- const dataPath =
524
- pathname === `${instance.prefix}/_furin/data`
525
- ? parseDataEndpointPath(new URL(request.url).searchParams.get("path") ?? "")
526
- : undefined;
527
- const refresh =
528
- pathname === `${instance.prefix}/_furin/data` &&
529
- request.method === "GET" &&
530
- dataPath !== undefined &&
531
- navigationDataMatchers.get(instance)?.(dataPath.pathname) === true &&
532
- request.headers.get("x-furin-hmr-refresh") === "1"
533
- ? navigationDataRefreshers.get(instance)
534
- : undefined;
535
- return refresh ? refresh().then(dispatch) : dispatch();
536
- });
537
- });
538
- }
539
-
540
- function createFurinPlugin(app: AnyElysia, hmrPrefix: string | undefined, hasSync: boolean) {
541
- const scopedApp = wrapWithRequestScope(app);
542
- return <ParentApp extends AnyElysia>(parentApp: ParentApp) => {
543
- if (hasSync) {
544
- bindSyncValidation(parentApp);
545
- }
546
- const mounted = parentApp.use(scopedApp);
547
- if (hmrPrefix !== undefined) {
548
- const parentConfig = Reflect.get(parentApp, "~config") as { prefix?: string } | undefined;
549
- const entryPath = `${parentConfig?.prefix ?? ""}${hmrPrefix}/_bun_hmr_entry`;
550
- const routes = Reflect.get(mounted, "~routes") as
551
- | [string, string, unknown, unknown, unknown, unknown, unknown?][]
552
- | undefined;
553
- for (const route of routes ?? []) {
554
- if (
555
- route[0] === "GET" &&
556
- (route[1] === entryPath || route[1] === `${entryPath}/index.html`)
557
- ) {
558
- // Bun serves these HTML bundles natively; inherited Elysia hooks cannot run.
559
- route[6] = undefined;
560
- }
561
- }
562
- }
563
- return mounted;
564
- };
565
- }
566
-
567
- async function loadDevelopmentRoutes(resolvedPagesDir: string) {
568
- const { scanPages } = await import("./server/router/discovery.ts");
569
- return scanPages(resolvedPagesDir);
570
- }
571
-
572
- function createNativeRouteRenderer(
573
- prefix: string,
574
- routes: ResolvedRoute[],
575
- root: RootLayout,
576
- buildId: string,
577
- searchRoutes: ReturnType<typeof createSearchRouteMetadata>
578
- ): FurinRouteDispatcher {
579
- const matchNativeRoute = buildRouteMatcher(routes);
580
- return async (context) => {
581
- const { request } = context;
582
- const requestUrl = new URL(request.url);
583
- const { pathname } = requestUrl;
584
- const hasPrefix = prefix !== "" && (pathname === prefix || pathname.startsWith(`${prefix}/`));
585
- const logicalPath = hasPrefix ? pathname.slice(prefix.length) : pathname;
586
- const matched = matchNativeRoute(logicalPath || "/");
587
- if (!matched || (IS_DEV && !existsSync(matched.route.path))) {
588
- // Dev topology swap: the mounted Elysia route can outlive its source
589
- // file (hot-remove). Render the root not-found page instead of failing.
590
- const listenerOrigin = (context.server as { url?: { origin: string } } | undefined)?.url
591
- ?.origin;
592
- return renderRootNotFound(root, request, listenerOrigin);
593
- }
594
- const parsedParams = await parseRouteParams(
595
- matched.params,
596
- mergeRouteSchemas(matched.route.routeChain, "params")
597
- );
598
- if (!parsedParams.ok) {
599
- return problem(422, { detail: "Invalid params", errors: parsedParams.errors });
600
- }
601
- const parsedQuery = await parseRouteQuery(
602
- requestUrl,
603
- mergeRouteSchemas(matched.route.routeChain, "query")
604
- );
605
- if (!parsedQuery.ok) {
606
- return problem(422, { detail: "Invalid query", errors: parsedQuery.errors });
607
- }
608
- context.params = parsedParams.params;
609
- context.query = parsedQuery.query;
610
- if (navigationDataRequests.has(request)) {
611
- getLogger().set({
612
- path: logicalPath + requestUrl.search,
613
- routePattern: matched.route.pattern,
614
- });
615
- const current = IS_DEV
616
- ? await resolveCurrentDevRoute(matched.route, root)
617
- : { root, route: matched.route };
618
- return renderRouteData(
619
- current.route,
620
- context as unknown as Parameters<typeof renderRouteData>[1],
621
- current.root,
622
- searchRoutes,
623
- logicalPath + requestUrl.search
624
- );
625
- }
626
- return renderResolvedRoute(
627
- matched.route,
628
- context as unknown as Parameters<typeof renderResolvedRoute>[1],
629
- root,
630
- buildId,
631
- searchRoutes
632
- );
633
- };
634
- }
635
-
636
- function createDevelopmentRouteSnapshot(
637
- prefix: string,
638
- root: RootLayout,
639
- routes: ResolvedRoute[]
640
- ): DevelopmentRouteSnapshot {
641
- const searchRoutes = createSearchRouteMetadata(routes);
642
- return {
643
- render: createNativeRouteRenderer(prefix, routes, root, "", searchRoutes),
644
- root,
645
- routes,
646
- };
647
- }
648
-
649
- const nativeRouteRenderers = new WeakMap<FurinInstance, FurinRouteDispatcher>();
650
-
651
- function dispatchNativeRoute(context: Parameters<FurinRouteDispatcher>[0]): unknown {
652
- const { pathname } = new URL(context.request.url);
653
- const renderer = nativeRouteRenderers.get(resolveInstanceByPath(pathname));
654
- if (!renderer) {
655
- throw new Error(`[furin] No route renderer is registered for ${JSON.stringify(pathname)}`);
656
- }
657
- return renderer(context);
658
- }
659
-
660
- function hydrateSSGCacheFromCompileContext(ctx: CompileContext): void {
661
- if (!ctx.ssgCache) {
662
- return;
663
- }
664
- for (const [path, entry] of Object.entries(ctx.ssgCache)) {
665
- setSSGCache(path, entry);
666
- }
667
- }
61
+ // Read the parent's generics through Elysia's `~` carriers: inferring them from
62
+ // the invariant class collapses function-valued macros to `never`. Scope has
63
+ // no carrier, so it alone is inferred.
64
+ type FurinApplication<App extends AnyElysia> =
65
+ App extends Elysia<
66
+ App["~Prefix"],
67
+ infer Scope,
68
+ App["~Singleton"],
69
+ App["~Definitions"],
70
+ App["~Metadata"],
71
+ App["~Routes"],
72
+ App["~Ephemeral"],
73
+ App["~Volatile"]
74
+ >
75
+ ? Elysia<
76
+ App["~Prefix"],
77
+ Scope,
78
+ {
79
+ decorator: App["~Singleton"]["decorator"];
80
+ derive: App["~Singleton"]["derive"] & { log: RequestLogger };
81
+ store: App["~Singleton"]["store"];
82
+ },
83
+ App["~Definitions"],
84
+ App["~Metadata"],
85
+ App["~Routes"],
86
+ App["~Ephemeral"],
87
+ App["~Volatile"]
88
+ >
89
+ : never;
668
90
 
669
91
  /** Options for the {@link furin} plugin. */
670
- export type FurinLoggerOptions = FurinEvlogOptions & Pick<LoggerConfig, "sampling">;
671
-
672
92
  export interface FurinOptions {
93
+ /**
94
+ * CDN purge hook for this app. Receives the physical (prefixed) paths that
95
+ * `revalidatePath()` and `revalidateTag()` invalidate. Takes precedence over
96
+ * the process-wide `setCachePurger()`.
97
+ */
98
+ cachePurger?: CachePurger;
99
+ /**
100
+ * CDN purge hook for this app's semantic cache tags. Receives the tags passed
101
+ * to `revalidateTag()`. Takes precedence over the tag purger installed by
102
+ * the deployment adapter (e.g. Vercel). Runtimes sharing one purger get a
103
+ * single call per `revalidateTag()`.
104
+ */
105
+ cacheTagPurger?: CachePurger;
673
106
  /**
674
107
  * Production only: explicit directory holding this app's built client
675
108
  * assets (chunks + index.html template). Packaged furin apps pass their own
@@ -684,6 +117,7 @@ export interface FurinOptions {
684
117
  * and unaffected.
685
118
  */
686
119
  clientLogging?: boolean;
120
+ /** Request logging options. Configure global evlog settings with `initLogger()` in the application. */
687
121
  logger?: FurinLoggerOptions;
688
122
  /**
689
123
  * Cache for public page artifacts. Use a distributed adapter when several
@@ -693,10 +127,14 @@ export interface FurinOptions {
693
127
  pageCache?: PageCacheAdapter;
694
128
  pagesDir?: string;
695
129
  /**
696
- * Mount prefix for this app, e.g. `"/admin"`. All pages, framework
697
- * endpoints (`/_furin/*`) and client assets (`/_client/*`) are served under
698
- * it, and the client bundle is built with the matching basePath. Defaults
699
- * to `""` (root). Mounting two furin instances on the same prefix throws.
130
+ * Full physical mount path of this app, e.g. `"/admin"`. All pages,
131
+ * framework endpoints (`/_furin/*`) and client assets (`/_client/*`) are
132
+ * served under it, and the client bundle is built with it as basePath.
133
+ * Defaults to `""` (root). Mount Furin on an Elysia instance without a
134
+ * prefix: under `new Elysia({ prefix: "/outer" })`, declare
135
+ * `furin({ prefix: "/outer/admin" })` on an unprefixed child instead.
136
+ * Mounting two furin instances on the same prefix, or one pagesDir under
137
+ * two prefixes, throws.
700
138
  */
701
139
  prefix?: string;
702
140
  /**
@@ -712,9 +150,9 @@ function configurePageCache(
712
150
  ctx: CompileContext | null,
713
151
  pageCache: PageCacheAdapter | undefined
714
152
  ): void {
715
- if (pageCache !== undefined && ctx?.deploymentTarget === "vercel") {
153
+ if (pageCache !== undefined && ctx?.adapter?.capabilities.publicCache === "platform") {
716
154
  throw new Error(
717
- "[furin] pageCache cannot be configured with the Vercel target. Vercel owns SSG, ISR, and PPR public caching."
155
+ `[furin] pageCache cannot be configured with the ${JSON.stringify(ctx.adapter.name)} adapter: its platform caches public SSG, ISR, and PPR pages.`
718
156
  );
719
157
  }
720
158
  if (pageCache !== undefined) {
@@ -722,495 +160,229 @@ function configurePageCache(
722
160
  }
723
161
  }
724
162
 
725
- /**
726
- * Main Furin plugin.
727
- *
728
- * Returns an Elysia plugin function. Applying the function to the parent app
729
- * before `listen()` lets development register Bun's native HTML bundle in the
730
- * initial server options while preserving Elysia's route composition.
731
- *
732
- * ## Usage
733
- *
734
- * ```ts
735
- * new Elysia()
736
- * .use(await furin({ pagesDir: "./src/pages" }))
737
- * .use(await furin({ pagesDir: "./src/admin", prefix: "/admin" }))
738
- * .listen(3000)
739
- * ```
740
- */
741
- export async function furin({
742
- pagesDir,
743
- prefix: rawPrefix,
744
- clientDir: explicitClientDir,
745
- logger,
746
- clientLogging,
747
- pageCache,
748
- sync,
749
- }: FurinOptions = {}) {
750
- const prefix = normalizePrefix(rawPrefix);
751
- const syncPath = resolveSyncPath(sync);
752
- const elysiaLoggerOptions = initializeLogger(logger);
163
+ /** Runtimes started by each composed application, by prefix. */
164
+ const startedRuntimes = new WeakMap<AnyElysia, Map<string, FurinInstance>>();
165
+
166
+ function assertMountedPrefix(instance: FurinInstance, app: AnyElysia, owner: AnyElysia): void {
167
+ const anchor = app.routes.find((route) => typeof route.handler === "function");
168
+ const mounted =
169
+ anchor &&
170
+ owner.routes.find(
171
+ (route) =>
172
+ route.method === anchor.method &&
173
+ route.handler === anchor.handler &&
174
+ route.path.endsWith(anchor.path)
175
+ );
176
+ if (!(anchor && mounted) || mounted.path === anchor.path) {
177
+ return;
178
+ }
179
+ const found = normalizePrefix(
180
+ `${mounted.path.slice(0, mounted.path.length - anchor.path.length)}${instance.prefix}`
181
+ );
182
+ throw new Error(
183
+ `[furin] furin({ prefix: ${JSON.stringify(instance.prefix)} }) is served at ${JSON.stringify(found)}. The prefix is build-time configuration (the client bundle is built for it), so it must be the full physical path: when mounting under a prefixed parent, repeat the parent prefix in furin({ prefix: ${JSON.stringify(found)} }) and mount Furin on an Elysia instance without a prefix.`
184
+ );
185
+ }
753
186
 
187
+ /** The application currently serving each runtime. */
188
+ const servingOwners = new WeakMap<FurinInstance, AnyElysia>();
189
+
190
+ function trackStartedRuntime(instance: FurinInstance, owner: AnyElysia): void {
191
+ const serving = servingOwners.get(instance);
192
+ if (serving && serving !== owner) {
193
+ throw new Error(
194
+ "[furin] This furin() runtime is already served by another Elysia application. Each plugin owns one runtime (caches, build ID, watchers): call furin() again for each application."
195
+ );
196
+ }
197
+ servingOwners.set(instance, owner);
198
+ const runtimes = startedRuntimes.get(owner) ?? new Map<string, FurinInstance>();
199
+ startedRuntimes.set(owner, runtimes);
200
+ const existing = runtimes.get(instance.prefix);
201
+ if (existing && existing !== instance) {
202
+ throw new Error(
203
+ `[furin] prefix "${instance.prefix || "/"}" is already mounted by pagesDir "${existing.pagesDir}" (attempted to mount "${instance.pagesDir}"). Give each furin() instance a unique prefix.`
204
+ );
205
+ }
206
+ assertOnePagesDirPerMount([...runtimes.values(), instance]);
207
+ runtimes.set(instance.prefix, instance);
208
+ }
209
+
210
+ async function createFurinApp(options: FurinOptions): Promise<{
211
+ app: AnyElysia;
212
+ hasSync: boolean;
213
+ instance: FurinInstance;
214
+ }> {
215
+ const {
216
+ cachePurger,
217
+ cacheTagPurger,
218
+ clientDir,
219
+ clientLogging,
220
+ logger,
221
+ pageCache,
222
+ pagesDir,
223
+ sync,
224
+ } = options;
225
+ const prefix = normalizePrefix(options.prefix);
754
226
  const cwd = process.cwd();
755
- // The pagesDir param drives which compile context this instance loads. In a
756
- // deployed binary the cwd-resolved path may miss the build-time key — the
757
- // lookup then falls back to the (stable) prefix, then to the sole context.
227
+ // In a deployed binary the cwd-resolved pagesDir may differ from the build
228
+ // machine's; the compile context is found by the (stable) declared prefix.
758
229
  const paramPagesDir = resolve(cwd, pagesDir ?? "src/pages");
759
230
  const ctx = getCompileContext(paramPagesDir, prefix);
760
- const loggerPlugin = createLoggerPlugin(
761
- prefix,
762
- syncPath,
763
- elysiaLoggerOptions,
764
- clientLogging === true || ctx?.clientLogging === true
765
- );
766
231
  const resolvedPagesDir = ctx?.rootPath ? dirname(ctx.rootPath) : paramPagesDir;
767
-
768
- // Unique name per pagesDir to avoid Elysia's name-based plugin dedup.
769
- const instanceName = `furin-${prefix}-${resolvedPagesDir.replaceAll("\\", "/")}`;
770
-
771
- // Same prefix + different pagesDir is a mount collision — fail fast, but
772
- // only REGISTER right before returning so a failed mount leaves no stale
773
- // registration behind. All per-app runtime state (build ID, caches,
774
- // template, sync path) hangs off this object; requests are bound to it by
775
- // path in wrapWithRequestScope.
776
232
  const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
777
- assertPrefixAvailable(prefix, normalizedPagesDir);
233
+
234
+ // All per-app runtime state (build ID, caches, template, sync path) hangs
235
+ // off this object; the plugin's closures bind requests to it.
778
236
  const instance = createInstance(prefix, normalizedPagesDir);
779
- instance.syncPath = syncPath;
237
+ instance.syncPath = resolveSyncPath(sync);
238
+ const loggerPlugin = createLoggerPlugin(
239
+ instance,
240
+ logger,
241
+ clientLogging === true || ctx?.clientLogging === true
242
+ );
780
243
  configurePageCache(instance, ctx, pageCache);
244
+ setInstanceCachePurger(instance, cachePurger);
245
+ setInstanceCacheTagPurger(instance, cacheTagPurger);
246
+ registerInstance(instance);
781
247
 
782
- // ── Dev: Bun native HMR ────────────────────────────────────────────────
783
- if (IS_DEV) {
784
- // Each instance gets its own generated-files dir so two mounted apps do
785
- // not overwrite each other's hydrate entry (root keeps plain `.furin`).
786
- const instanceSlug = prefix === "" ? "" : prefix.slice(1).replaceAll("/", "__");
787
- const furinDir = resolve(cwd, ".furin", instanceSlug);
788
- // Lazy import — build pipeline has native deps not available in compiled binaries
789
- const { devDiagnosticStore, publishDevDiagnostic } = await import(
790
- "./server/dev/diagnostics.ts"
791
- );
792
- const { devGraph } = await import("./server/dev/graph.ts");
793
- const { createDevDiagnosticPlugin } = await import("./server/dev/plugin.ts");
794
- const { createDevelopmentBrowserEventSources } = await import("./server/dev/browser-events.ts");
795
- const { registerDevPagePlugin } = await import("./server/dev-page-plugin.ts");
796
- registerDevPagePlugin();
797
- const {
798
- registerDevRoutesPlugin,
799
- registerDevRouteTopologyWatcher,
800
- routeModuleSpecifier,
801
- routeSourcePaths,
802
- } = await import("./plugin/routes.ts");
803
- const routeInstance = { pagesDir: resolvedPagesDir, prefix };
804
- registerDevRoutesPlugin([routeInstance]);
805
-
806
- // TanStack-style config auto-fix: verify each route file's `layout`
807
- // reference against the file-system tree and rewrite missing/misplaced
808
- // ones. Idempotent and content-diff safe — the watcher resynchronizes the
809
- // route-file signature after a rewrite, so the auto-fix cannot loop.
810
- const { fixRouteConfigLayout } = await import("./plugin/route-config-autofix.ts");
811
- const applyRouteConfigAutofix = (): boolean => {
812
- let changed = false;
813
- const sourcePaths = [
814
- join(resolvedPagesDir, "root.tsx"),
815
- ...routeSourcePaths(routeInstance),
816
- ].filter((sourcePath) => existsSync(sourcePath));
817
- for (const sourcePath of sourcePaths) {
818
- let source: string;
819
- try {
820
- source = readFileSync(sourcePath, "utf8");
821
- } catch (error) {
822
- console.warn(
823
- `[furin] Could not read ${sourcePath} for route config autofix: ${error instanceof Error ? error.message : String(error)}`
824
- );
825
- continue;
826
- }
827
- const fixed = fixRouteConfigLayout(source, sourcePath, resolvedPagesDir);
828
- if (fixed !== null && fixed !== source) {
829
- writeFileSync(sourcePath, fixed);
830
- changed = true;
831
- }
832
- }
833
- return changed;
834
- };
835
- applyRouteConfigAutofix();
836
-
837
- const graph = devGraph(instance);
838
- const { nativeRoutesApp, root, routes } = await withInstance(instance, async () => {
839
- const { furinShell } = (await import(routeModuleSpecifier(routeInstance))) as {
840
- furinShell: AnyElysia;
841
- };
842
- const loaded = await loadDevelopmentRoutes(resolvedPagesDir);
843
- return { nativeRoutesApp: furinShell, ...loaded };
844
- });
845
- const initialSnapshot = createDevelopmentRouteSnapshot(prefix, root, routes);
846
- const currentSnapshot = (): DevelopmentRouteSnapshot => graph.snapshot ?? initialSnapshot;
847
- nativeRouteRenderers.set(instance, (context) => currentSnapshot().render(context));
848
- let matchNavigationData = buildRouteMatcher(initialSnapshot.routes);
849
- navigationDataMatchers.set(instance, (path) => matchNavigationData(path) !== null);
850
-
851
- const { writeDevFiles } = await import("./build/hydrate.ts");
852
- const { getHmrDataSignature } = await import("./plugin/transform-client.ts");
853
- let serverSourceVersion = 0;
854
- let serverDataSignatures = new Map<string, string>();
855
- let serverSourcePaths: string | undefined;
856
- const writeCurrentDevFiles = (
857
- snapshot: DevelopmentRouteSnapshot,
858
- changedSources: readonly string[]
859
- ): void => {
860
- const paths = [
861
- ...new Set([
862
- snapshot.root.path,
863
- ...snapshot.routes.flatMap((route) => [
864
- route.path,
865
- ...route.routeChain.flatMap((entry) => (entry.sourcePath ? [entry.sourcePath] : [])),
866
- ]),
867
- ]),
868
- ].toSorted();
869
- const nextPaths = JSON.stringify(paths);
870
- const nextSignatures = new Map(
871
- paths.map((path) => {
872
- let signature: string;
873
- try {
874
- signature = getHmrDataSignature(readFileSync(path, "utf8"), path);
875
- if (signature.startsWith("external:")) {
876
- signature = graph.sourceVersion(path);
877
- }
878
- } catch {
879
- // A broken route still needs a client entry for its diagnostic.
880
- signature = graph.sourceVersion(path);
248
+ const { development } = instance;
249
+ const modeOptions: ModeOptions = {
250
+ clientLogging,
251
+ requestHooks: (runtimeApp) =>
252
+ (runtimeApp as Elysia)
253
+ .use(loggerPlugin)
254
+ // Local scope keeps hooks isolated from sibling Furin mounts.
255
+ .onError(NotFound, (context) =>
256
+ renderNotFound(instance, context as unknown as FurinNativeRouteContext)
257
+ )
258
+ .onAfterHandle(({ set }) => {
259
+ const pending = consumePendingInvalidations();
260
+ if (pending.length > 0) {
261
+ set.headers["x-furin-revalidate"] = serializeInvalidationPaths(pending);
881
262
  }
882
- return [path, signature] as const;
883
- })
884
- );
885
- // Route additions/removals already update the native client manifest.
886
- // Rebase their signature without issuing a second data invalidation.
887
- const changedPaths = new Set(changedSources);
888
- const importsChanged = paths.some(
889
- (path) =>
890
- !changedPaths.has(path) && serverDataSignatures.get(path) !== nextSignatures.get(path)
891
- );
892
- if (importsChanged && serverSourcePaths === nextPaths) {
893
- serverSourceVersion += 1;
894
- }
895
- serverSourcePaths = nextPaths;
896
- serverDataSignatures = nextSignatures;
897
- writeDevFiles(
898
- snapshot.routes,
899
- {
900
- basePath: prefix,
901
- clientLogging: clientLogging ?? false,
902
- outDir: furinDir,
903
- publicPath: `${prefix}/_client/`,
904
- rootLayout: snapshot.root.path,
905
- // furin-env.d.ts is one file at the project root — only the root
906
- // instance owns it, otherwise mounted apps clobber each other's types.
907
- skipRouteTypes: prefix !== "",
908
- },
909
- cwd,
910
- String(serverSourceVersion)
911
- );
912
- };
913
- writeCurrentDevFiles(initialSnapshot, []);
914
- graph.commit(initialSnapshot);
915
- const hmrEntry = (await import(join(furinDir, "index.html"))).default;
916
- const refreshDevelopmentRoutes = (changedSources: readonly string[]): Promise<void> =>
917
- withInstance(instance, async () => {
918
- invalidateStampedRouteModules();
919
- try {
920
- const previousSnapshot = currentSnapshot();
921
- const repaired = repairedDevelopmentRoutes(previousSnapshot, changedSources, graph);
922
- const next = await loadDevelopmentRoutes(resolvedPagesDir);
923
- // Retain tags only for routes whose current module could not be loaded.
924
- const nextRoutes = next.routes.map((route) =>
925
- route.routeChain.length > 0
926
- ? route
927
- : {
928
- ...route,
929
- tags: previousSnapshot.routes.find((previous) => previous.path === route.path)
930
- ?.tags,
931
- }
932
- );
933
- const nextSnapshot = createDevelopmentRouteSnapshot(prefix, next.root, nextRoutes);
934
- writeCurrentDevFiles(nextSnapshot, changedSources);
935
- graph.commit(nextSnapshot);
936
- matchNavigationData = buildRouteMatcher(nextSnapshot.routes);
937
- const diagnostics = devDiagnosticStore(instance);
938
- if (repaired.root) {
939
- diagnostics.markReady("*");
263
+ if (!development && instance.buildId) {
264
+ set.headers["x-furin-build-id"] = instance.buildId;
940
265
  }
941
- for (const pattern of repaired.patterns) {
942
- if (diagnostics.markReady(pattern)) {
943
- break;
944
- }
945
- }
946
- } catch (error) {
947
- publishDevDiagnostic(error, {
948
- entryPath: join(resolvedPagesDir, "root.tsx"),
949
- phase: "import",
950
- route: "*",
951
- });
952
- throw error;
953
- }
954
- });
955
- const publicDir = resolve(cwd, "public");
956
- const publicExists = existsSync(publicDir);
957
- let routeTopologyWatcher: ReturnType<typeof registerDevRouteTopologyWatcher> | undefined;
958
- navigationDataRefreshers.set(instance, async () => {
959
- await routeTopologyWatcher?.refresh();
960
- });
961
-
962
- // Routes registered below are LOGICAL — Elysia's `prefix` makes them
963
- // physical when this plugin is merged into the parent app (child prefixes
964
- // like staticPlugin's compose underneath).
965
- const devApp = new Elysia({
966
- name: instanceName,
967
- prefix: prefix || undefined,
968
- seed: resolvedPagesDir,
969
- })
970
- .setup(() => {
971
- routeTopologyWatcher = registerDevRouteTopologyWatcher({
972
- instance: routeInstance,
973
- onRouteFilesTouched: async (sourcePaths) => {
974
- applyRouteConfigAutofix();
975
- await refreshDevelopmentRoutes(sourcePaths);
976
- },
977
- onSourceError: (error, sourcePath) => {
978
- const route = currentSnapshot().routes.find((candidate) =>
979
- graph.dependsOn(candidate.path, sourcePath)
980
- );
981
- withInstance(instance, () =>
982
- publishDevDiagnostic(error, {
983
- entryPath: route?.path ?? sourcePath,
984
- phase: "transform",
985
- route: route?.pattern ?? "*",
986
- })
987
- );
988
- },
989
- onTopologyChange: async (sourcePaths) => {
990
- // Bun --hot cannot be triggered from generated artifacts (its
991
- // watch graph is the entry's static imports), so topology changes
992
- // are served by swapping the dispatcher's route matcher. Hot-added
993
- // routes then resolve through the NOT_FOUND fallback below;
994
- // removed routes 404 through the renderer's miss path.
995
- applyRouteConfigAutofix();
996
- await refreshDevelopmentRoutes(sourcePaths);
997
- },
998
- });
999
- })
1000
- .cleanup(() => {
1001
- routeTopologyWatcher?.close();
1002
- routeTopologyWatcher = undefined;
1003
- navigationDataRefreshers.delete(instance);
1004
- navigationDataMatchers.delete(instance);
1005
- })
1006
- .get("/_bun_hmr_entry/index.html", hmrEntry)
1007
- .get("/_bun_hmr_entry", hmrEntry)
1008
- .use(loggerPlugin)
1009
- // Local scope (default) — a global hook would leak onto sibling furin
1010
- // instances mounted on the same parent app.
1011
- .error(NotFound, async ({ request, server }) =>
1012
- renderRootNotFound(currentSnapshot().root, request, server?.url.origin)
1013
- )
1014
- .afterHandle(({ set }) => {
1015
- // Forward pending revalidation paths so the client can bust its prefetch cache
1016
- const pending = consumePendingInvalidations();
1017
- if (pending.length > 0) {
1018
- set.headers["x-furin-revalidate"] = pending.join(",");
1019
- }
1020
- })
1021
- .use(
1022
- publicExists ? await staticPlugin({ assets: publicDir, prefix: "/public" }) : new Elysia()
1023
- )
1024
- .get(
1025
- "/favicon.ico",
1026
- publicExists
1027
- ? file(join(publicDir, "favicon.ico"))
1028
- : () => new Response(null, { status: 404 })
1029
- )
1030
- .use(
1031
- (await import("./server/browser-events/plugin.ts")).createBrowserEventsPlugin({
1032
- sources: createDevelopmentBrowserEventSources(instance, devDiagnosticStore(instance)),
1033
- sync: sync || undefined,
1034
- })
1035
- )
1036
- .use(
1037
- createDevDiagnosticPlugin(devDiagnosticStore(instance), instance, async () => {
1038
- await routeTopologyWatcher?.refresh();
1039
- })
1040
- )
1041
- .use(createInstrumentationPlugin(() => currentSnapshot().routes, syncPath))
1042
- .use(
1043
- sync
1044
- ? (await import("./server/sync/stream.ts")).createSyncChangesPlugin(sync)
1045
- : new Elysia()
266
+ }),
267
+ sync: sync || undefined,
268
+ };
269
+ const mode: ModeRuntime = development
270
+ ? await (await import("./server/dev/runtime.ts")).createDevRuntime(
271
+ instance,
272
+ resolvedPagesDir,
273
+ modeOptions
1046
274
  )
1047
- .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
1048
- .use(nativeRoutesApp)
1049
- .use(
1050
- createNotFoundHandling(prefix, routes, root, async (notFoundContext) => {
1051
- // Dev topology: try the (watcher-refreshed) native renderer before
1052
- // the root not-found page, so hot-added routes are served without
1053
- // a restart. Instances outside this pathname's prefix are skipped.
1054
- const { pathname } = new URL(notFoundContext.request.url);
1055
- if (!nativeRouteRenderers.has(resolveInstanceByPath(pathname))) {
1056
- return;
1057
- }
1058
- return await dispatchNativeRoute(
1059
- notFoundContext as unknown as Parameters<FurinRouteDispatcher>[0]
1060
- );
1061
- })
1062
- );
1063
- registerInstance(instance);
1064
- return createFurinPlugin(devApp, prefix, Boolean(sync));
1065
- }
275
+ : await createProdRuntime(instance, ctx, clientDir, modeOptions);
1066
276
 
1067
- // ── Production ──────────────────────────────────────────────────────────
1068
- if (!ctx) {
1069
- throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
1070
- }
1071
- const { root, routes } = loadProdRoutes(ctx);
1072
- const searchRoutes = createSearchRouteMetadata(routes);
1073
- const prodBuildId = ctx.buildId ?? "";
1074
- if (!ctx.nativeRoutes) {
1075
- throw new Error("[furin] Production build is missing the composed Elysia route app.");
1076
- }
1077
- const renderNativeRoute = createNativeRouteRenderer(
1078
- prefix,
1079
- routes,
1080
- root,
1081
- prodBuildId,
1082
- searchRoutes
1083
- );
1084
- nativeRouteRenderers.set(instance, renderNativeRoute);
1085
- const matchNavigationData = buildRouteMatcher(routes);
1086
- navigationDataMatchers.set(instance, (path) => matchNavigationData(path) !== null);
1087
- instance.buildId = prodBuildId;
1088
- // Init-time writes target THIS instance explicitly — with several mounted
1089
- // apps there is no ambient request scope to resolve it from.
1090
- withInstance(instance, () => {
1091
- hydrateSSGCacheFromCompileContext(ctx);
1092
- });
1093
-
1094
- const embedded = ctx?.embedded;
1095
- const clientDir =
1096
- embedded?.clientDir ?? explicitClientDir ?? ctx.clientDir ?? resolveClientDirFromArgv(prefix);
1097
- await setupCompiledTemplate(ctx, embedded, clientDir, instance);
1098
-
1099
- const prodApp = new Elysia({
1100
- name: instanceName,
277
+ // Unique name per pagesDir to avoid Elysia's name-based plugin dedup.
278
+ const app: AnyElysia = new Elysia({
279
+ name: `furin-${prefix}-${normalizedPagesDir}`,
1101
280
  prefix: prefix || undefined,
1102
281
  seed: resolvedPagesDir,
1103
282
  })
1104
- .use(loggerPlugin)
1105
- // Local scope (default) — a global hook would leak onto sibling furin
1106
- // instances mounted on the same parent app.
1107
- .error(NotFound, async ({ request, server }) =>
1108
- renderRootNotFound(root, request, server?.url.origin)
1109
- )
1110
- .afterHandle(({ set }) => {
1111
- // Forward pending revalidation paths so the client can bust its prefetch cache
1112
- const pending = consumePendingInvalidations();
1113
- if (pending.length > 0) {
1114
- set.headers["x-furin-revalidate"] = pending.join(",");
1115
- }
1116
- // Tell the client the current build ID so it can detect stale deploys
1117
- if (instance.buildId) {
1118
- set.headers["x-furin-build-id"] = instance.buildId;
1119
- }
283
+ .wrap(createRequestScope(instance))
284
+ .onStart((owner) => {
285
+ assertMountedPrefix(instance, app, owner);
286
+ trackStartedRuntime(instance, owner);
1120
287
  })
1121
- .setup(async ({ server }) => {
1122
- if (ctx.ssgCache) {
1123
- return;
288
+ .onStop((owner) => {
289
+ startedRuntimes.get(owner)?.delete(instance.prefix);
290
+ if (servingOwners.get(instance) === owner) {
291
+ servingOwners.delete(instance);
292
+ unregisterInstance(instance);
1124
293
  }
1125
- const origin = server?.url?.origin ?? "http://localhost:3000";
1126
- // Synthetic (non-request) renders — bind them to this instance so the
1127
- // render pipeline resolves its template/caches, not a sibling's.
1128
- await withInstance(instance, () => warmSSGCache(routes, root, origin, searchRoutes));
1129
294
  })
1130
- .use(await createProductionAssetsPlugin(ctx, embedded, clientDir))
1131
- .use(await createProductionBrowserEventsPlugin(sync, ctx?.deploymentTarget))
295
+ .use(mode.plugins)
1132
296
  .use(
1133
- sync ? (await import("./server/sync/stream.ts")).createSyncChangesPlugin(sync) : new Elysia()
297
+ sync
298
+ ? (await import("./server/sync/stream.ts")).createRuntimeSyncChangesPlugin(
299
+ sync,
300
+ development
301
+ )
302
+ : new Elysia()
1134
303
  )
1135
304
  .decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute)
1136
- .use(ctx.nativeRoutes)
1137
- .use(createNotFoundHandling(prefix, routes, root));
1138
- registerInstance(instance);
1139
- return createFurinPlugin(prodApp, undefined, Boolean(sync));
305
+ .use(mode.nativeRoutes)
306
+ .use(createNotFoundHandling(instance));
307
+ return { app, hasSync: Boolean(sync), instance };
1140
308
  }
1141
309
 
310
+ /** Parent applications and the prefixes their Furin plugins claim. */
311
+ const mountedPrefixes = new WeakMap<AnyElysia, Map<string, FurinInstance>>();
312
+
1142
313
  /**
1143
- * 404 handling per mount position:
314
+ * Main Furin plugin.
315
+ *
316
+ * Returns an Elysia plugin function for exactly one application. Applying the
317
+ * function to the parent app before `listen()` lets development register
318
+ * Bun's native HTML bundle in the initial server options while preserving
319
+ * Elysia's route composition.
320
+ *
321
+ * ## Usage
1144
322
  *
1145
- * - ROOT instance (`prefix === ""`): a global `NotFound` handler owns the root
1146
- * scope, and a parent `.error()`
1147
- * registered BEFORE `.use(furin)` still wins (documented escape hatch for
1148
- * JSON API 404s).
1149
- * - PREFIXED instance: a global hook would leak onto sibling apps, and a
1150
- * local one never sees unmatched paths (they belong to no route). Instead
1151
- * the instance registers a lowest-priority catch-all under its own prefix;
1152
- * the router prefers every more-specific route, so this only fires for
1153
- * paths no page matched. Skipped when the app defines its own `[...rest]`
1154
- * catch-all page.
323
+ * ```ts
324
+ * new Elysia()
325
+ * .use(await furin({ pagesDir: "./src/pages" }))
326
+ * .use(await furin({ pagesDir: "./src/admin", prefix: "/admin" }))
327
+ * .listen(3000)
328
+ * ```
1155
329
  */
1156
- function createNotFoundHandling(
1157
- prefix: string,
1158
- routes: Array<{ pattern: string }>,
1159
- root: Parameters<typeof renderRootNotFound>[0],
1160
- tryNativeDispatch?: (context: { request: Request }) => Promise<unknown>
1161
- ): Elysia {
1162
- const app = new Elysia();
1163
- const dispatch =
1164
- tryNativeDispatch ??
1165
- (routes.some((route) => route.pattern === "/*")
1166
- ? async (context: { request: Request }): Promise<unknown> => {
1167
- if (context.request.method !== "GET") {
1168
- return;
1169
- }
1170
- return await dispatchNativeRoute(context as Parameters<FurinRouteDispatcher>[0]);
1171
- }
1172
- : undefined);
1173
- if (prefix === "") {
1174
- app.error("global", NotFound, async (context) => {
1175
- // Dev topology: the native renderer is rebuilt by the watcher on route
1176
- // add/remove, so a hot-added route (no mounted Elysia route yet) can
1177
- // still be served here. Production also renders root catch-all pages here.
1178
- if (dispatch) {
1179
- const rendered = await dispatch(context);
1180
- if (rendered !== undefined && rendered !== null) {
1181
- return rendered;
1182
- }
1183
- }
1184
- return await renderRootNotFound(root, context.request, context.server?.url.origin);
1185
- });
1186
- return app;
1187
- }
1188
- app.get("/*", async (context) => {
1189
- if (dispatch) {
1190
- const rendered = await dispatch(context);
1191
- if (rendered !== undefined && rendered !== null) {
1192
- return rendered;
1193
- }
330
+ export async function furin(options?: FurinOptions) {
331
+ const registration = {
332
+ pagesDir: options?.pagesDir ?? "src/pages",
333
+ prefix: normalizePrefix(options?.prefix),
334
+ };
335
+ if (recordFurinRegistration(registration)) {
336
+ // The build only discovers mounts: no runtime, nothing to mount.
337
+ return <ParentApp extends AnyElysia>(parentApp: ParentApp) =>
338
+ parentApp as unknown as FurinApplication<ParentApp>;
339
+ }
340
+ const { app, hasSync, instance } = await createFurinApp(options ?? {});
341
+ let mounted = false;
342
+ return <ParentApp extends AnyElysia>(parentApp: ParentApp): FurinApplication<ParentApp> => {
343
+ if (mounted) {
344
+ throw new Error(
345
+ "[furin] This furin() plugin is already mounted. Each plugin owns one runtime (caches, build ID, watchers): call furin() again for each application."
346
+ );
347
+ }
348
+ const prefixes = mountedPrefixes.get(parentApp) ?? new Map<string, FurinInstance>();
349
+ const existing = prefixes.get(instance.prefix);
350
+ if (existing) {
351
+ throw new Error(
352
+ `[furin] prefix "${instance.prefix || "/"}" is already mounted by pagesDir "${existing.pagesDir}" (attempted to mount "${instance.pagesDir}"). Give each furin() instance a unique prefix.`
353
+ );
1194
354
  }
1195
- return renderRootNotFound(root, context.request, context.server?.url.origin);
1196
- });
1197
- return app;
355
+ assertOnePagesDirPerMount([...prefixes.values(), instance]);
356
+ mounted = true;
357
+ prefixes.set(instance.prefix, instance);
358
+ mountedPrefixes.set(parentApp, prefixes);
359
+ if (hasSync) {
360
+ bindSyncValidation(parentApp);
361
+ }
362
+ // The mounted evlog plugin contributes only log; preserve the parent's
363
+ // native route, schema and macro types instead of merging AnyElysia.
364
+ return parentApp.use(app) as unknown as FurinApplication<ParentApp>;
365
+ };
1198
366
  }
1199
367
 
1200
368
  export { FurinErrorBoundary, FurinNotFoundBoundary } from "./client/boundaries.tsx";
1201
369
  export { HeadContent, Scripts } from "./client/document.tsx";
370
+ export type { Register } from "./routes.ts";
1202
371
  export type { InvalidationInput, InvalidationRule } from "./server/auto-invalidate/index.ts";
1203
372
  export { furinInvalidate, revalidateTag } from "./server/auto-invalidate/index.ts";
1204
373
  export { revalidatePath, setCachePurger } from "./server/cache/invalidation.ts";
1205
- export { buildElement, buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
374
+ export { buildErrorElement, renderRootNotFound } from "./server/render/index.ts";
1206
375
  export {
376
+ createLocalSyncClient,
1207
377
  type FurinSyncOption,
1208
378
  type FurinSyncOptions,
1209
379
  furinSync,
380
+ invalidateSync,
381
+ type LocalSyncClientOptions,
1210
382
  type SyncAdapter,
1211
- type SyncInput,
383
+ type SyncConnectionLease,
384
+ type SyncInvalidationOptions,
1212
385
  type SyncNotifier,
1213
- type SyncRouteOption,
1214
386
  type SyncRuntimeOptions,
1215
387
  } from "./server/sync/index.ts";
1216
388
  export { Await, useAsyncError, useAsyncValue } from "./shared/await.tsx";