@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
@@ -1,7 +1,6 @@
1
1
  import { log } from "evlog";
2
2
  import type React from "react";
3
3
  import {
4
- createElement,
5
4
  useCallback,
6
5
  useEffect,
7
6
  useLayoutEffect,
@@ -10,112 +9,60 @@ import {
10
9
  useState,
11
10
  useSyncExternalStore,
12
11
  } from "react";
13
- import type { HeadOptions } from "../../client.ts";
14
- import { parseDeferredNdjson } from "../../shared/deferred-ndjson.ts";
15
12
  import { type DeferredQueryValue, projectDeferredQueryData } from "../../shared/query-bindings.ts";
13
+ import { findRouteFailure } from "../../shared/route-matches.ts";
16
14
  import type { SearchParamsInput } from "../../shared/search-params.ts";
17
- import { type QuerySeed, queryTag } from "../../shared/sync-query.ts";
18
- import { subscribeBrowserEvent } from "../browser-events.ts";
15
+ import type { QuerySeed } from "../../shared/sync-query.ts";
16
+ import { collectRouteChainFromRoute } from "../../shared/utils/index.ts";
17
+ import { setBrowserSyncAuthentication } from "../browser-events.ts";
19
18
  import { DocumentProvider, useDocumentState } from "../document.tsx";
20
19
  import { QueryStoreContext } from "../query.tsx";
21
20
  import { QueryStore } from "../query-store.ts";
22
- import { isAbortError } from "./abort.ts";
23
- import { buildPageElement, buildRouterTree } from "./boundary-tree.tsx";
21
+ import { resolveRouteElement } from "../route-element.tsx";
22
+ import { createInvalidationRefresh } from "../sync-catch-up.ts";
23
+ import { buildRouterTree } from "./boundary-tree.tsx";
24
+ import { RouterStoreContext } from "./context.ts";
24
25
  import {
25
- generateHistoryKey,
26
- getHistoryKey,
27
- isStaleDeployResponse,
28
- SCROLL_STORAGE_KEY,
29
- saveScrollPosition,
30
- } from "./history.ts";
31
- import {
32
- applyRevalidateEntries,
33
26
  applyRevalidateHeader,
34
- decodeHashFragment,
35
- isSameOriginFetchResult,
36
27
  normalizeHref,
37
28
  shouldAutoRefreshPath,
38
29
  shouldInterceptClick,
39
- shouldRefetch,
40
- stripHashFromHref,
41
30
  toLogical,
42
31
  } from "./link-utils.ts";
43
- import { createOptimisticRuntime, registerOptimisticRuntime, SYNC_REQUEST } from "./optimistic.ts";
44
- import { createSearchStore, SearchStoreContext } from "./search-store.ts";
45
- import {
46
- buildDataEndpoint,
47
- buildNotFoundPageElement,
48
- classifySpaResponse,
49
- detectStaticMode,
50
- parsePageResponse,
51
- } from "./spa-response.ts";
52
32
  import {
53
- createInvalidationRefresh,
54
- createSyncCatchUp,
55
- type SyncChangePagePayload,
56
- } from "./sync-catch-up.ts";
33
+ NavigationController,
34
+ type NavigationControllerConfig,
35
+ type NavigationSnapshot,
36
+ } from "./navigation-controller.ts";
37
+ import { createOptimisticRuntime, registerOptimisticRuntime } from "./optimistic.ts";
38
+ import { fetchPageState } from "./page-fetch.ts";
39
+ import { createSearchStore, SearchStoreContext } from "./search-store.ts";
40
+ import { detectStaticMode } from "./spa-response.ts";
57
41
  import type {
58
- CacheEntry,
42
+ ClientRoute,
59
43
  ClientSegmentBoundary,
60
- LoadedClientRoute,
61
44
  RouterProviderProps,
62
- RouterState,
45
+ RouterStore,
46
+ StableRouter,
63
47
  } from "./types.ts";
48
+ import { useFetchInterception } from "./use-fetch-interception.ts";
49
+ import { useHistorySync } from "./use-history-sync.ts";
50
+ import { useHmrRefresh } from "./use-hmr-refresh.ts";
51
+ import { useSyncStream } from "./use-sync-stream.ts";
64
52
 
65
53
  const EMPTY_SEARCH: SearchParamsInput = {};
66
54
 
67
- function isRedirectState(state: RouterState | null): state is RouterState & { finalHref: string } {
68
- return Boolean(state?.finalHref && !state.match && !state.notFound);
69
- }
70
-
71
- function getHistoryStateObject(): object {
72
- const value = history.state;
73
- return value !== null && typeof value === "object" ? value : {};
74
- }
75
-
76
- interface PendingUserNavigationRef {
77
- current: Promise<void> | null;
78
- }
79
-
80
- interface HmrTransactionState {
81
- dataInvalidated: boolean;
82
- }
83
-
84
- function beginUserNavigation(ref: PendingUserNavigationRef): () => void {
85
- let resolveNavigation: () => void = () => undefined;
86
- const navigation = new Promise<void>((resolve) => {
87
- resolveNavigation = resolve;
88
- });
89
- ref.current = navigation;
90
- return () => {
91
- if (ref.current === navigation) {
92
- ref.current = null;
93
- }
94
- resolveNavigation();
95
- };
96
- }
97
-
98
- async function waitForUserNavigation(ref: PendingUserNavigationRef): Promise<void> {
99
- while (ref.current) {
100
- // biome-ignore lint/performance/noAwaitInLoops: superseded user navigations must settle in sequence before HMR may refresh the final URL
101
- await ref.current;
102
- }
103
- }
104
-
105
- export function setPrefetchCacheEntry(
106
- cache: Map<string, CacheEntry>,
107
- href: string,
108
- entry: CacheEntry,
109
- maxSize: number
110
- ): void {
111
- if (cache.has(href)) {
112
- cache.delete(href);
113
- }
114
- cache.set(href, entry);
115
- if (cache.size > maxSize) {
116
- const oldest = cache.keys().next().value;
117
- if (typeof oldest === "string") {
118
- cache.delete(oldest);
55
+ /**
56
+ * Root-owned boundary for the "no client route matched" 404 path. When an
57
+ * unknown URL is navigated to, the server's `renderRootNotFound` handles it —
58
+ * the root `not-found.tsx` (depth 0) is the correct component to render inline
59
+ * instead of doing a full-page reload.
60
+ */
61
+ function findRootBoundaries(routes: ClientRoute[]): ClientSegmentBoundary[] | undefined {
62
+ for (const route of routes) {
63
+ const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0 && b.isRoot !== false);
64
+ if (depth0) {
65
+ return [depth0];
119
66
  }
120
67
  }
121
68
  }
@@ -126,8 +73,6 @@ export function RouterProvider({
126
73
  initialMatch,
127
74
  initialData,
128
75
  initialDigest,
129
- initialError,
130
- initialNotFound,
131
76
  autoRefresh,
132
77
  basePath,
133
78
  defaultPreload,
@@ -147,29 +92,111 @@ export function RouterProvider({
147
92
  );
148
93
  return store;
149
94
  });
150
- // Initial state. When `initialMatch` is `null`, `initialNotFound` MUST be set —
151
- // the provider boots into the inline not-found UI.
152
- const [state, setState] = useState<RouterState>(() => ({
153
- data: Object.fromEntries(
154
- Object.entries(initialData).filter(([key]) => key !== "__furinQueries")
155
- ),
156
- querySeeds: initialData.__furinQueries as QuerySeed[] | undefined,
157
- hydrateQueries: queries.captureHydration(),
158
- error: initialError
159
- ? {
160
- ...initialError,
161
- message: initialError.message || "Something went wrong",
162
- }
163
- : undefined,
164
- head: initialDocumentState?.head,
165
- match: initialMatch,
166
- notFound: initialNotFound,
167
- }));
168
- const [boundaryResetVersion, setBoundaryResetVersion] = useState(0);
169
- const currentState = useRef(state);
95
+ // Initial snapshot. Like a navigation response, the payload's matches are
96
+ // the only source of the route failure. When `initialMatch` is `null`, they
97
+ // MUST carry a not-found match — the provider boots into the inline 404 UI.
98
+ const [initialSnapshot] = useState<NavigationSnapshot>(() => {
99
+ const failure = findRouteFailure(initialData);
100
+ return {
101
+ // The LOGICAL path (basePath stripped) so Link active-state detection works
102
+ // with route patterns that never include the basePath prefix.
103
+ href:
104
+ typeof window === "undefined"
105
+ ? "/"
106
+ : normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search,
107
+ isNavigating: false,
108
+ resetVersion: 0,
109
+ state: {
110
+ data: Object.fromEntries(
111
+ Object.entries(initialData).filter(([key]) => key !== "__furinQueries")
112
+ ),
113
+ querySeeds: initialData.__furinQueries as QuerySeed[] | undefined,
114
+ hydrateQueries: queries.captureHydration(),
115
+ error: failure?.status === "error" ? failure.error : undefined,
116
+ head: initialDocumentState?.head,
117
+ match: initialMatch,
118
+ notFound: failure?.status === "notFound" ? failure.error : undefined,
119
+ },
120
+ };
121
+ });
122
+ const optimisticSnapshot = useRef({
123
+ href: initialSnapshot.href,
124
+ loaded: initialSnapshot.state.match !== null,
125
+ pattern: initialSnapshot.state.match?.pattern,
126
+ });
127
+ const syncResponse = useRef<
128
+ ((response: Response | undefined, optimistic: boolean) => void) | undefined
129
+ >(undefined);
130
+ const [optimisticRuntime] = useState(() =>
131
+ createOptimisticRuntime({
132
+ basePath,
133
+ queries,
134
+ snapshot: () => optimisticSnapshot.current,
135
+ onResponse: (response, optimistic) => syncResponse.current?.(response, optimistic),
136
+ })
137
+ );
138
+ /**
139
+ * Cached at boot from `<meta name="furin-mode">`. Drives the SPA-nav data
140
+ * fetch URL: the page URL with `?_furin=data` for SSR/ISR/dev, per-route
141
+ * `__furin_data.ndjson` for static exports.
142
+ */
143
+ const [staticMode] = useState(detectStaticMode);
144
+ const rootBoundaries = useMemo(() => findRootBoundaries(routes), [routes]);
145
+ const navigationConfig = useMemo<NavigationControllerConfig>(
146
+ () => ({
147
+ basePath,
148
+ defaultStaleTime: defaultPreloadStaleTime,
149
+ fetchPage: ({ currentMatch, hmrRefresh, href, signal }) =>
150
+ fetchPageState(
151
+ {
152
+ basePath,
153
+ captureHydration: () => queries.captureHydration(),
154
+ currentMatch,
155
+ rootBoundaries,
156
+ routes,
157
+ staticMode,
158
+ },
159
+ href,
160
+ signal,
161
+ hmrRefresh
162
+ ),
163
+ maxCacheSize: prefetchCacheSize,
164
+ }),
165
+ [
166
+ basePath,
167
+ defaultPreloadStaleTime,
168
+ prefetchCacheSize,
169
+ queries,
170
+ rootBoundaries,
171
+ routes,
172
+ staticMode,
173
+ ]
174
+ );
175
+ const [controller] = useState(
176
+ () =>
177
+ new NavigationController({
178
+ config: navigationConfig,
179
+ initial: initialSnapshot,
180
+ optimistic: optimisticRuntime,
181
+ })
182
+ );
170
183
  useLayoutEffect(() => {
171
- currentState.current = state;
172
- }, [state]);
184
+ controller.configure(navigationConfig);
185
+ }, [controller, navigationConfig]);
186
+ const navigation = useSyncExternalStore(
187
+ controller.subscribe,
188
+ controller.getSnapshot,
189
+ controller.getSnapshot
190
+ );
191
+ const { href: currentHref, isNavigating, resetVersion: boundaryResetVersion, state } = navigation;
192
+ const { navigate, refresh, invalidatePath: invalidatePrefetch } = controller;
193
+ const prefetch = useCallback(
194
+ (href: string, opts: { staleTime?: number } | undefined) => {
195
+ controller.prefetch(href, opts?.staleTime);
196
+ },
197
+ [controller]
198
+ );
199
+
173
200
  useLayoutEffect(() => {
174
201
  state.hydrateQueries?.(
175
202
  state.querySeeds ?? [],
@@ -179,8 +206,7 @@ export function RouterProvider({
179
206
  const resolvedQueries = useRef(new WeakMap<Promise<unknown>, DeferredQueryValue>());
180
207
  const [deferredRevision, setDeferredRevision] = useState(0);
181
208
  useEffect(() => {
182
- const snapshot = currentState.current;
183
- const hydrated = new Set(snapshot.querySeeds?.map((seed) => seed.url));
209
+ const hydrated = new Set(state.querySeeds?.map((seed) => seed.url));
184
210
  let disposed = false;
185
211
  for (const promise of Object.values(state.data)) {
186
212
  if (!(promise instanceof Promise)) {
@@ -192,8 +218,8 @@ export function RouterProvider({
192
218
  return;
193
219
  }
194
220
  resolvedQueries.current.set(promise, { value });
195
- const seeds = (snapshot.querySeeds ?? []).filter((seed) => !hydrated.has(seed.url));
196
- snapshot.hydrateQueries?.(seeds, window.location.origin);
221
+ const seeds = (state.querySeeds ?? []).filter((seed) => !hydrated.has(seed.url));
222
+ state.hydrateQueries?.(seeds, window.location.origin);
197
223
  for (const seed of seeds) {
198
224
  hydrated.add(seed.url);
199
225
  }
@@ -205,21 +231,7 @@ export function RouterProvider({
205
231
  return () => {
206
232
  disposed = true;
207
233
  };
208
- }, [queries, state.data]);
209
- const [isNavigating, setIsNavigating] = useState(false);
210
- // currentHref stores the LOGICAL path (basePath stripped) so Link active-state
211
- // detection works with route patterns that never include the basePath prefix.
212
- const [currentHref, setCurrentHref] = useState<string>(() => {
213
- if (typeof window === "undefined") {
214
- return "/";
215
- }
216
- return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
217
- });
218
- const optimisticSnapshot = useRef({
219
- href: currentHref,
220
- loaded: state.match !== null,
221
- pattern: state.match?.pattern,
222
- });
234
+ }, [state.data, state.querySeeds, state.hydrateQueries]);
223
235
  useLayoutEffect(() => {
224
236
  optimisticSnapshot.current = {
225
237
  href: currentHref,
@@ -227,560 +239,11 @@ export function RouterProvider({
227
239
  pattern: state.match?.pattern,
228
240
  };
229
241
  }, [currentHref, state.match, state.error, state.notFound]);
230
- const syncResponse = useRef<
231
- ((response: Response | undefined, optimistic: boolean) => void) | undefined
232
- >(undefined);
233
- const [optimisticRuntime] = useState(() =>
234
- createOptimisticRuntime({
235
- basePath,
236
- queries,
237
- snapshot: () => optimisticSnapshot.current,
238
- onResponse: (response, optimistic) => syncResponse.current?.(response, optimistic),
239
- })
240
- );
241
242
  useSyncExternalStore(optimisticRuntime.subscribe, optimisticRuntime.revision, () => 0);
242
243
  const queryRevision = useSyncExternalStore(queries.subscribeAll, queries.revision, () => 0);
243
244
  useEffect(() => registerOptimisticRuntime(optimisticRuntime), [optimisticRuntime]);
244
- const snapshotVersions = useRef(new WeakMap<RouterState, number>());
245
- const prefetchCache = useRef(new Map<string, CacheEntry>());
246
- /** Monotonic counter to discard stale navigations (race condition guard). */
247
- const navVersion = useRef(0);
248
- /** Monotonic counter that supersedes only HMR transactions, not user navigation. */
249
- const hmrVersion = useRef(0);
250
- const hmrState = useRef<HmrTransactionState>({ dataInvalidated: false });
251
- const pendingUserNavigation = useRef<Promise<void> | null>(null);
252
- /**
253
- * AbortController for the current navigation. Cancelled when a newer
254
- * navigation starts so any in-flight `parseDeferredNdjson` releases its
255
- * pending deferred promises (resolvers reject with `AbortError`) and frees
256
- * the underlying stream reader.
257
- */
258
- const navAbortRef = useRef<AbortController | null>(null);
259
- /**
260
- * Deferred scroll instruction consumed by the layout effect tied to `currentHref`.
261
- * This replaces the fragile double-requestAnimationFrame pattern with a render-
262
- * synchronous scroll that fires immediately after React commits the new route.
263
- */
264
- const pendingScrollRef = useRef<
265
- { type: "restore"; key: string } | { type: "reset"; href: string } | null
266
- >(null);
267
- const renderedHistoryKey = useRef<string | undefined>(undefined);
268
- /**
269
- * Tracks the last successfully rendered match for use in the no-route 404 path.
270
- * `null` on the initial render when the URL didn't match any route and the
271
- * provider booted directly into the not-found state; flips to a real match as
272
- * soon as the user navigates away via `navigate()` or the back button.
273
- */
274
- const currentMatchRef = useRef<LoadedClientRoute | null>(initialMatch);
275
- /**
276
- * Cached at boot from `<meta name="furin-mode">`. Drives the SPA-nav data
277
- * fetch URL: runtime `/_furin/data` for SSR/ISR/dev, per-route
278
- * `__furin_data.ndjson` for static exports.
279
- */
280
- const [staticMode] = useState(detectStaticMode);
281
245
  const resolvedSearch = (state.data.query as SearchParamsInput | undefined) ?? EMPTY_SEARCH;
282
246
 
283
- /**
284
- * Root-owned boundary for the "no client route matched" 404
285
- * path. When an unknown URL is navigated to, the server's `renderRootNotFound`
286
- * handles it — the root `not-found.tsx` (depth 0) is the correct component to
287
- * render inline instead of doing a full-page reload.
288
- */
289
- const rootBoundaries = useMemo<ClientSegmentBoundary[] | undefined>(() => {
290
- for (const route of routes) {
291
- const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0 && b.isRoot !== false);
292
- if (depth0) {
293
- return [depth0];
294
- }
295
- }
296
- }, [routes]);
297
-
298
- /**
299
- * Resolves the RouterState when no client-side route matched the URL. The
300
- * server's `renderRootNotFound` produced the 404 HTML; we fetch the physical
301
- * URL to detect the `__furinStatus: 404` signal and render the 404 UI inline
302
- * (rather than triggering a jarring full-page reload).
303
- */
304
- const resolveNoMatchState = useCallback(
305
- async (physicalHref: string, signal: AbortSignal | undefined): Promise<RouterState | null> => {
306
- const res = await fetch(physicalHref, { signal });
307
- if (isStaleDeployResponse(res)) {
308
- return null;
309
- }
310
- const { data, finalHref, title } = await parsePageResponse(res, basePath);
311
- const kind = classifySpaResponse(res.status, data);
312
- if (kind.kind !== "not-found") {
313
- return null;
314
- }
315
- const { __furinStatus: _s, __furinNotFound: _n, ...cleanData } = data ?? {};
316
- return {
317
- data: cleanData,
318
- finalHref,
319
- match: currentMatchRef.current,
320
- notFound: kind.error,
321
- notFoundBoundaries: rootBoundaries,
322
- title,
323
- };
324
- },
325
- [basePath, rootBoundaries]
326
- );
327
-
328
- const fetchPageState = useCallback(
329
- async (
330
- rawLogicalHref: string,
331
- signal: AbortSignal | undefined,
332
- hmrRefresh: boolean
333
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — response shapes (redirect, stale-deploy, deferred) + abort-signal wiring require this depth
334
- ): Promise<RouterState | null> => {
335
- const hydrateQueries = queries.captureHydration();
336
- // Normalize trailing slashes so "/docs/routing/" matches the route
337
- // pattern "/docs/routing" — static hosts (GitHub Pages, Netlify) often
338
- // redirect to or serve URLs with a trailing slash.
339
- const logicalHref = normalizeHref(rawLogicalHref);
340
- try {
341
- // Physical href: what the browser/server actually receives.
342
- // For basePath deployments: fetch("/furin/docs/routing") not fetch("/docs/routing").
343
- const physicalHref = basePath + logicalHref;
344
- const url = new URL(physicalHref, window.location.origin);
345
- // Route matching always uses the LOGICAL pathname (basePath stripped).
346
- const logicalPathname = toLogical(url.pathname, basePath);
347
- const match = routes.find((r) => r.regex.test(logicalPathname));
348
- if (!match) {
349
- return await resolveNoMatchState(physicalHref, signal);
350
- }
351
-
352
- // ── NDJSON data endpoint + JS chunk load (parallel) ──────────────────
353
- const dataEndpoint = buildDataEndpoint(basePath, logicalHref, staticMode);
354
- const loadedModule = hmrRefresh ? Promise.resolve(undefined) : match.load();
355
- const [res, loadedMod] = await Promise.all([
356
- fetch(dataEndpoint, {
357
- headers: hmrRefresh ? { "x-furin-hmr-refresh": "1" } : undefined,
358
- redirect: "manual",
359
- signal,
360
- }),
361
- loadedModule,
362
- ]);
363
-
364
- // Stale-deploy detection: force a full page reload to pick up the new bundle.
365
- if (isStaleDeployResponse(res)) {
366
- return null;
367
- }
368
-
369
- const contentType = res.headers.get("content-type") ?? "";
370
- if (
371
- !(
372
- staticMode ||
373
- contentType.includes("application/x-ndjson") ||
374
- contentType.includes("application/x-furin-route")
375
- )
376
- ) {
377
- return null;
378
- }
379
-
380
- const body = res.body ?? new ReadableStream<Uint8Array>({ start: (c) => c.close() });
381
- let parsed: {
382
- syncData: Record<string, unknown>;
383
- deferredPromises: Record<string, Promise<unknown>>;
384
- };
385
- try {
386
- parsed = await parseDeferredNdjson(body, signal);
387
- } catch (parseErr) {
388
- log.warn({
389
- action: "navigate_server_error",
390
- error: String(parseErr),
391
- href: physicalHref,
392
- status: res.status,
393
- });
394
- return null;
395
- }
396
- const { syncData, deferredPromises } = parsed;
397
-
398
- // Special fields injected by the server into syncData:
399
- // __furinStatus — 404 signal
400
- // __furinNotFound — not-found payload
401
- // __furinRedirect — server-side redirect target (logical path)
402
- // __furinError — error sentinel (digest, message, status)
403
- // __furinTitle — document title resolved server-side from head()
404
- const {
405
- __furinHead,
406
- __furinStatus,
407
- __furinNotFound,
408
- __furinRedirect,
409
- __furinError,
410
- __furinTitle,
411
- __furinQueries,
412
- ...cleanSyncData
413
- } = syncData as {
414
- __furinStatus?: number;
415
- __furinNotFound?: { data?: unknown; message?: string };
416
- __furinRedirect?: string;
417
- __furinError?: { digest: string; message: string; status: number };
418
- __furinHead?: HeadOptions;
419
- __furinTitle?: string;
420
- __furinQueries?: QuerySeed[];
421
- [key: string]: unknown;
422
- };
423
-
424
- if (typeof __furinRedirect === "string") {
425
- const target = new URL(__furinRedirect, window.location.origin);
426
- const isLogicalPath =
427
- __furinRedirect.startsWith("/") && !__furinRedirect.startsWith("//");
428
- const withinMount =
429
- isLogicalPath ||
430
- basePath === "" ||
431
- target.pathname === basePath ||
432
- target.pathname.startsWith(`${basePath}/`);
433
- const targetPath = isLogicalPath ? target.pathname : toLogical(target.pathname, basePath);
434
- if (
435
- target.origin !== window.location.origin ||
436
- !withinMount ||
437
- !routes.some((route) => route.regex.test(targetPath))
438
- ) {
439
- return null;
440
- }
441
- return {
442
- data: {},
443
- finalHref: targetPath + target.search + target.hash,
444
- match: null,
445
- title: "",
446
- };
447
- }
448
-
449
- // Merge sync data + deferred Promises.
450
- const data = { ...cleanSyncData, ...deferredPromises };
451
-
452
- const title = typeof __furinTitle === "string" ? __furinTitle : "";
453
-
454
- const loadedMatch: LoadedClientRoute | null = loadedMod
455
- ? {
456
- ...match,
457
- component: loadedMod.default.component,
458
- pageRoute: loadedMod.default._route,
459
- segmentBoundaries: loadedMod.segmentBoundaries ?? match.segmentBoundaries,
460
- }
461
- : currentMatchRef.current;
462
- if (!loadedMatch) {
463
- return null;
464
- }
465
-
466
- // Loader threw a non-redirect Response (or an Error).
467
- if (__furinError) {
468
- return {
469
- data,
470
- error: __furinError,
471
- head: __furinHead,
472
- match: loadedMatch,
473
- title,
474
- };
475
- }
476
-
477
- // Non-2xx without sentinel and not 404 → opaque server error.
478
- if (!res.ok && res.status !== 404) {
479
- log.warn({ action: "navigate_server_error", href: physicalHref, status: res.status });
480
- return null;
481
- }
482
-
483
- if (__furinStatus === 404) {
484
- const notFound =
485
- __furinNotFound !== null && typeof __furinNotFound === "object"
486
- ? (__furinNotFound as { data?: unknown; message?: string })
487
- : {};
488
- return {
489
- data,
490
- head: __furinHead,
491
- match: loadedMatch,
492
- notFound,
493
- title,
494
- };
495
- }
496
-
497
- return {
498
- data,
499
- head: __furinHead,
500
- match: loadedMatch,
501
- querySeeds: __furinQueries,
502
- hydrateQueries,
503
- title,
504
- };
505
- } catch (err: unknown) {
506
- if (!isAbortError(err)) {
507
- log.error({
508
- action: "navigate_failed",
509
- error: String(err),
510
- href: basePath + logicalHref,
511
- });
512
- }
513
- return null;
514
- }
515
- },
516
- [routes, basePath, resolveNoMatchState, queries]
517
- );
518
-
519
- const fetchConfirmedPageState = useCallback(
520
- async (href: string, signal: AbortSignal | undefined, hmrRefresh: boolean) => {
521
- for (;;) {
522
- try {
523
- // biome-ignore lint/performance/noAwaitInLoops: a snapshot must be read after local writes settle.
524
- await optimisticRuntime.wait(href, signal);
525
- } catch (error) {
526
- if (signal?.aborted) {
527
- return null;
528
- }
529
- throw error;
530
- }
531
- const version = optimisticRuntime.revision(href);
532
- const snapshot = await fetchPageState(href, signal, hmrRefresh);
533
- if (optimisticRuntime.publishable(href, version)) {
534
- if (snapshot) {
535
- snapshotVersions.current.set(snapshot, version);
536
- }
537
- return snapshot;
538
- }
539
- }
540
- },
541
- [fetchPageState, optimisticRuntime]
542
- );
543
-
544
- const invalidatePrefetch = useCallback((path: string, type: "page" | "layout") => {
545
- const normalizedPath = normalizeHref(new URL(path, "http://furin.local").pathname);
546
- for (const key of [...prefetchCache.current.keys()]) {
547
- if (
548
- shouldAutoRefreshPath(normalizeHref(stripHashFromHref(key)), [
549
- { path: normalizedPath, type },
550
- ])
551
- ) {
552
- prefetchCache.current.delete(key);
553
- }
554
- }
555
- }, []);
556
-
557
- const prefetch = useCallback(
558
- (href: string, opts: { staleTime?: number } | undefined) => {
559
- const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
560
- const existing = prefetchCache.current.get(href);
561
- if (existing && !shouldRefetch(existing)) {
562
- return;
563
- }
564
- setPrefetchCacheEntry(
565
- prefetchCache.current,
566
- href,
567
- {
568
- createdAt: Date.now(),
569
- promise: fetchPageState(href, undefined, false),
570
- staleTime,
571
- },
572
- prefetchCacheSize
573
- );
574
- },
575
- [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
576
- );
577
-
578
- /** Loads the RouterState for a redirect target, respecting the nav version. */
579
- async function resolveRedirectState(
580
- redirectLogical: string,
581
- myVersion: number,
582
- signal: AbortSignal | undefined
583
- ): Promise<RouterState | null> {
584
- const cached = prefetchCache.current.get(redirectLogical);
585
- const useCached =
586
- cached !== undefined && !shouldRefetch(cached) && !optimisticRuntime.has(redirectLogical);
587
- let redirectState =
588
- useCached && cached
589
- ? await cached.promise
590
- : await fetchConfirmedPageState(redirectLogical, signal, false);
591
- if (navVersion.current !== myVersion) {
592
- return null;
593
- }
594
- if (
595
- useCached &&
596
- (isRedirectState(redirectState) ||
597
- (redirectState &&
598
- !optimisticRuntime.publishable(
599
- redirectLogical,
600
- snapshotVersions.current.get(redirectState) ??
601
- optimisticRuntime.revision(redirectLogical)
602
- )))
603
- ) {
604
- redirectState = await fetchConfirmedPageState(redirectLogical, signal, false);
605
- }
606
- return navVersion.current === myVersion ? redirectState : null;
607
- }
608
-
609
- async function followRedirects(
610
- initialState: RouterState,
611
- initialHref: string,
612
- myVersion: number,
613
- signal: AbortSignal | undefined
614
- ): Promise<{ href: string; state: RouterState } | null> {
615
- let redirectState = initialState;
616
- let href = initialHref;
617
- const visited = new Set([href]);
618
- for (let count = 0; isRedirectState(redirectState); count += 1) {
619
- href = normalizeHref(redirectState.finalHref);
620
- if (count >= 10 || visited.has(href)) {
621
- return null;
622
- }
623
- visited.add(href);
624
- // biome-ignore lint/performance/noAwaitInLoops: each redirect target depends on the previous response.
625
- const next = await resolveRedirectState(href, myVersion, signal);
626
- if (!next) {
627
- return null;
628
- }
629
- redirectState = next;
630
- }
631
- return { href, state: redirectState };
632
- }
633
-
634
- const navigate = useCallback(
635
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — redirect follow, history management, and scroll handling require this depth
636
- async function navigateTo(
637
- rawLogicalHref: string,
638
- opts:
639
- | {
640
- beforeCommit?: () => void;
641
- hmrRefresh?: boolean;
642
- replace?: boolean;
643
- resetScroll?: boolean;
644
- shouldCommit?: () => boolean;
645
- }
646
- | undefined
647
- ) {
648
- const logicalHref = normalizeHref(rawLogicalHref);
649
- const beforeCommit = opts?.beforeCommit;
650
- const finishUserNavigation =
651
- opts?.hmrRefresh === true ? undefined : beginUserNavigation(pendingUserNavigation);
652
- navVersion.current += 1;
653
- const myVersion = navVersion.current;
654
- navAbortRef.current?.abort();
655
- const navAbort = new AbortController();
656
- navAbortRef.current = navAbort;
657
- const navSignal = navAbort.signal;
658
- setIsNavigating(true);
659
- try {
660
- const cached = prefetchCache.current.get(logicalHref);
661
- const useCached =
662
- cached !== undefined && !shouldRefetch(cached) && !optimisticRuntime.has(logicalHref);
663
- let newState =
664
- useCached && cached
665
- ? await cached.promise
666
- : await fetchConfirmedPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
667
- const cachedRedirect =
668
- useCached &&
669
- (isRedirectState(newState) ||
670
- (newState &&
671
- !optimisticRuntime.publishable(
672
- logicalHref,
673
- snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(logicalHref)
674
- )));
675
- if (cachedRedirect) {
676
- newState = await fetchConfirmedPageState(
677
- logicalHref,
678
- navSignal,
679
- opts?.hmrRefresh === true
680
- );
681
- }
682
- if (navVersion.current !== myVersion || opts?.shouldCommit?.() === false) {
683
- return;
684
- }
685
- if (newState && (!useCached || cachedRedirect)) {
686
- setPrefetchCacheEntry(
687
- prefetchCache.current,
688
- logicalHref,
689
- {
690
- createdAt: Date.now(),
691
- promise: Promise.resolve(newState),
692
- staleTime: defaultPreloadStaleTime,
693
- },
694
- prefetchCacheSize
695
- );
696
- }
697
- if (!newState) {
698
- log.warn({
699
- action: "navigate_fallback",
700
- href: logicalHref,
701
- reason: "prefetch_returned_null",
702
- });
703
- window.location.href = basePath + logicalHref;
704
- return;
705
- }
706
-
707
- const resolved = await followRedirects(newState, logicalHref, myVersion, navSignal);
708
- if (navVersion.current !== myVersion) {
709
- return;
710
- }
711
- if (!resolved) {
712
- if (navVersion.current === myVersion) {
713
- window.location.href = basePath + logicalHref;
714
- }
715
- return;
716
- }
717
- newState = resolved.state;
718
-
719
- if (opts?.shouldCommit?.() === false) {
720
- return;
721
- }
722
- const publicationHref = newState.finalHref ?? resolved.href;
723
- if (
724
- !optimisticRuntime.publishable(
725
- publicationHref,
726
- snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(publicationHref)
727
- )
728
- ) {
729
- return;
730
- }
731
- if (!(newState.error || newState.notFound)) {
732
- optimisticRuntime.commit(publicationHref);
733
- }
734
- beforeCommit?.();
735
- const effectiveLogical = newState.finalHref ?? resolved.href;
736
- const physicalEffective = basePath + effectiveLogical;
737
- if (opts?.resetScroll ?? true) {
738
- pendingScrollRef.current = { href: physicalEffective, type: "reset" };
739
- }
740
- currentMatchRef.current = newState.match;
741
- if (!newState.error) {
742
- setBoundaryResetVersion((version) => version + 1);
743
- }
744
- setState(newState);
745
- if (newState.title) {
746
- document.title = newState.title;
747
- }
748
- if (opts?.replace) {
749
- window.history.replaceState(
750
- {
751
- ...getHistoryStateObject(),
752
- _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
753
- },
754
- "",
755
- physicalEffective
756
- );
757
- } else {
758
- const currentKey = renderedHistoryKey.current;
759
- if (currentKey) {
760
- saveScrollPosition(currentKey);
761
- }
762
- window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
763
- }
764
- renderedHistoryKey.current = getHistoryKey(history.state);
765
- const effectiveUrl = new URL(physicalEffective, window.location.origin);
766
- const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
767
- setCurrentHref(logicalPath + effectiveUrl.search);
768
- } finally {
769
- finishUserNavigation?.();
770
- if (navVersion.current === myVersion) {
771
- setIsNavigating(false);
772
- }
773
- }
774
- },
775
- [
776
- basePath,
777
- fetchConfirmedPageState,
778
- defaultPreloadStaleTime,
779
- prefetchCacheSize,
780
- optimisticRuntime,
781
- ]
782
- );
783
-
784
247
  const [searchStore] = useState(() =>
785
248
  createSearchStore({
786
249
  currentHref,
@@ -806,30 +269,6 @@ export function RouterProvider({
806
269
  searchStore.flush();
807
270
  }, [searchStore, searchSnapshot]);
808
271
 
809
- const refresh = useCallback(
810
- async (
811
- opts:
812
- | {
813
- beforeCommit?: () => void;
814
- hmrRefresh?: boolean;
815
- resetScroll?: boolean;
816
- shouldCommit?: () => boolean;
817
- }
818
- | undefined
819
- ) => {
820
- const logicalPath = toLogical(window.location.pathname, basePath);
821
- const logicalHref = logicalPath + window.location.search;
822
- invalidatePrefetch(logicalHref, "page");
823
- await navigate(logicalHref, {
824
- beforeCommit: opts?.beforeCommit,
825
- hmrRefresh: opts?.hmrRefresh,
826
- replace: true,
827
- resetScroll: opts?.resetScroll ?? false,
828
- shouldCommit: opts?.shouldCommit,
829
- });
830
- },
831
- [navigate, invalidatePrefetch, basePath]
832
- );
833
272
  const invalidationRefresh = useMemo(
834
273
  () =>
835
274
  createInvalidationRefresh({
@@ -837,11 +276,11 @@ export function RouterProvider({
837
276
  log.warn({ action: "sync_refresh_failed", error: String(error) });
838
277
  },
839
278
  refresh: async () => {
840
- await waitForUserNavigation(pendingUserNavigation);
841
- await refresh(undefined);
279
+ await controller.waitForUserNavigation();
280
+ await controller.refresh(undefined);
842
281
  },
843
282
  }),
844
- [refresh]
283
+ [controller]
845
284
  );
846
285
 
847
286
  useLayoutEffect(() => {
@@ -869,196 +308,8 @@ export function RouterProvider({
869
308
  };
870
309
  }, [autoRefresh, invalidatePrefetch, invalidationRefresh]);
871
310
 
872
- // Expose a transactional refresh to the HMR handler in _hydrate.tsx. The
873
- // callback swaps the hot component only after fresh data is ready and just
874
- // before setState publishes the complete router snapshot.
875
- useEffect(() => {
876
- if (typeof window !== "undefined") {
877
- // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
878
- (window as any).__FURIN_HMR_REFRESH__ = async (
879
- beforeCommit: (() => void) | undefined,
880
- dataChanged: boolean | undefined
881
- ) => {
882
- hmrVersion.current += 1;
883
- const myHmrVersion = hmrVersion.current;
884
- const shouldRefreshData = hmrState.current.dataInvalidated || dataChanged !== false;
885
- if (!shouldRefreshData) {
886
- beforeCommit?.();
887
- setState((current) => ({ ...current }));
888
- return;
889
- }
890
- hmrState.current.dataInvalidated = true;
891
- await waitForUserNavigation(pendingUserNavigation);
892
- if (hmrVersion.current !== myHmrVersion) {
893
- return;
894
- }
895
- let didCommit = false;
896
- await refresh({
897
- beforeCommit: () => {
898
- didCommit = true;
899
- beforeCommit?.();
900
- },
901
- hmrRefresh: true,
902
- shouldCommit: () => hmrVersion.current === myHmrVersion,
903
- });
904
- if (didCommit && hmrVersion.current === myHmrVersion) {
905
- hmrState.current.dataInvalidated = false;
906
- }
907
- };
908
- return () => {
909
- // biome-ignore lint/suspicious/noExplicitAny: dev-only window hook
910
- (window as any).__FURIN_HMR_REFRESH__ = undefined;
911
- };
912
- }
913
- }, [refresh]);
914
-
915
- const handlePopState = useCallback(() => {
916
- const finishUserNavigation = beginUserNavigation(pendingUserNavigation);
917
- if (renderedHistoryKey.current) {
918
- saveScrollPosition(renderedHistoryKey.current);
919
- }
920
- const destKey = getHistoryKey(history.state);
921
- const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
922
- const logicalHref = logicalPath + window.location.search;
923
- navVersion.current += 1;
924
- const myVersion = navVersion.current;
925
- navAbortRef.current?.abort();
926
- const navAbort = new AbortController();
927
- navAbortRef.current = navAbort;
928
- const navSignal = navAbort.signal;
929
- setIsNavigating(true);
930
-
931
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: popstate handler — cache check, redirect follow, and scroll restoration require this depth
932
- (async () => {
933
- try {
934
- const cached = prefetchCache.current.get(logicalHref);
935
- let newState: RouterState | null;
936
- if (cached && !shouldRefetch(cached) && !optimisticRuntime.has(logicalHref)) {
937
- newState = await cached.promise;
938
- if (
939
- isRedirectState(newState) ||
940
- (newState &&
941
- !optimisticRuntime.publishable(
942
- logicalHref,
943
- snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(logicalHref)
944
- ))
945
- ) {
946
- newState = await fetchConfirmedPageState(logicalHref, navSignal, false);
947
- }
948
- } else {
949
- newState = await fetchConfirmedPageState(logicalHref, navSignal, false);
950
- }
951
- if (navVersion.current !== myVersion) {
952
- return;
953
- }
954
- if (!newState) {
955
- log.warn({
956
- action: "popstate_fallback",
957
- href: logicalHref,
958
- reason: "fetchPageState_returned_null",
959
- });
960
- window.location.reload();
961
- return;
962
- }
963
-
964
- const resolved = await followRedirects(newState, logicalHref, myVersion, navSignal);
965
- if (navVersion.current !== myVersion) {
966
- return;
967
- }
968
- if (!resolved) {
969
- if (navVersion.current === myVersion) {
970
- window.location.reload();
971
- }
972
- return;
973
- }
974
- newState = resolved.state;
975
- const publicationHref = newState.finalHref ?? resolved.href;
976
- if (
977
- !optimisticRuntime.publishable(
978
- publicationHref,
979
- snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(publicationHref)
980
- )
981
- ) {
982
- return;
983
- }
984
- if (!(newState.error || newState.notFound)) {
985
- optimisticRuntime.commit(publicationHref);
986
- }
987
-
988
- currentMatchRef.current = newState.match;
989
- if (!newState.error) {
990
- setBoundaryResetVersion((version) => version + 1);
991
- }
992
- setState(newState);
993
- if (newState.title) {
994
- document.title = newState.title;
995
- }
996
- const effectiveLogical = newState.finalHref ?? resolved.href;
997
- if (effectiveLogical !== logicalHref) {
998
- window.history.replaceState(history.state, "", basePath + effectiveLogical);
999
- }
1000
- renderedHistoryKey.current = destKey;
1001
- setCurrentHref(normalizeHref(effectiveLogical));
1002
- if (destKey) {
1003
- pendingScrollRef.current = { key: destKey, type: "restore" };
1004
- } else {
1005
- window.scrollTo({ behavior: "instant", top: 0 });
1006
- }
1007
- } finally {
1008
- finishUserNavigation();
1009
- if (navVersion.current === myVersion) {
1010
- setIsNavigating(false);
1011
- }
1012
- }
1013
- })();
1014
- }, [fetchConfirmedPageState, basePath, optimisticRuntime]);
1015
-
1016
- // Disable native scroll restoration and assign a key to the initial history entry.
1017
- useEffect(() => {
1018
- history.scrollRestoration = "manual";
1019
- if (!getHistoryKey(history.state)) {
1020
- history.replaceState({ ...getHistoryStateObject(), _furinKey: generateHistoryKey() }, "");
1021
- }
1022
- renderedHistoryKey.current = getHistoryKey(history.state);
1023
- }, []);
1024
-
1025
- // Render-synchronous scroll restoration.
1026
- useLayoutEffect(() => {
1027
- const instruction = pendingScrollRef.current;
1028
- if (!instruction) {
1029
- return;
1030
- }
1031
- pendingScrollRef.current = null;
1032
-
1033
- if (instruction.type === "restore") {
1034
- try {
1035
- const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
1036
- const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
1037
- const y = positions[instruction.key] ?? 0;
1038
- window.scrollTo({ behavior: "instant", top: y });
1039
- } catch {
1040
- window.scrollTo({ behavior: "instant", top: 0 });
1041
- }
1042
- return;
1043
- }
1044
-
1045
- const destUrl = new URL(instruction.href, window.location.origin);
1046
- if (destUrl.hash) {
1047
- const id = decodeHashFragment(destUrl.hash.slice(1));
1048
- const element = document.getElementById(id);
1049
- if (element) {
1050
- element.scrollIntoView({ behavior: "instant", block: "start" });
1051
- }
1052
- } else {
1053
- window.scrollTo({ behavior: "instant", top: 0 });
1054
- }
1055
- }, [currentHref, state]);
1056
-
1057
- // Handle browser back/forward
1058
- useEffect(() => {
1059
- window.addEventListener("popstate", handlePopState);
1060
- return () => window.removeEventListener("popstate", handlePopState);
1061
- }, [handlePopState]);
311
+ useHmrRefresh(controller);
312
+ useHistorySync(controller, navigation);
1062
313
 
1063
314
  // Intercept clicks on native <a> tags so that internal links (including
1064
315
  // those rendered by MDX, CMS content, or third-party components) participate
@@ -1107,143 +358,13 @@ export function RouterProvider({
1107
358
  return () => document.removeEventListener("click", handler);
1108
359
  }, [navigate, basePath, routes]);
1109
360
 
1110
- // Intercept all window.fetch calls to auto-process X-Furin-Revalidate headers.
1111
- useEffect(() => {
1112
- if (typeof window === "undefined") {
1113
- return;
1114
- }
1115
- const originalFetch = window.fetch;
1116
- const wrapped = async (...args: Parameters<typeof fetch>): Promise<Response> => {
1117
- const response = await originalFetch.apply(window, args);
1118
- if (args[1] && SYNC_REQUEST in args[1]) {
1119
- return response;
1120
- }
1121
- if (!isSameOriginFetchResult(args[0], response.url, window.location.origin)) {
1122
- return response;
1123
- }
1124
- const invalidated: Array<{ path: string; type: "page" | "layout" }> = [];
1125
- applyRevalidateHeader(response.headers, (path, type) => {
1126
- const resolvedType = type ?? "page";
1127
- invalidatePrefetch(path, resolvedType);
1128
- invalidated.push({ path, type: resolvedType });
1129
- });
1130
- if (autoRefresh && invalidated.length > 0) {
1131
- const currentLogicalPath =
1132
- normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
1133
- if (shouldAutoRefreshPath(currentLogicalPath, invalidated)) {
1134
- // fire-and-forget: don't block the original fetch caller
1135
- invalidationRefresh.run();
1136
- }
1137
- }
1138
- return response;
1139
- };
1140
- // Copy static fetch methods so the patched value satisfies typeof fetch.
1141
- Object.assign(wrapped, originalFetch);
1142
- // biome-ignore lint/suspicious/noExplicitAny: Object.assign copies all static props but TS can't infer it
1143
- window.fetch = wrapped as any;
1144
- return () => {
1145
- window.fetch = originalFetch;
1146
- };
1147
- }, [invalidatePrefetch, invalidationRefresh, autoRefresh, basePath]);
1148
-
1149
- // Listen for sync cursor notifications and recover changes over HTTP.
1150
- // react-doctor-disable-next-line react-doctor/effect-needs-cleanup
1151
- useEffect(() => {
1152
- if (!syncPath || typeof window === "undefined") {
1153
- return;
1154
- }
1155
-
1156
- const changesUrl = syncPath.startsWith("/")
1157
- ? `${basePath}${syncPath}`
1158
- : `${basePath}/${syncPath}`;
1159
- let unsubscribe: (() => void) | undefined;
1160
- let disposed = false;
1161
- const applyInvalidations = (entries: readonly string[]) => {
1162
- if (disposed) {
1163
- return;
1164
- }
1165
- const invalidations: Array<{ path: string; type: "page" | "layout" }> = [];
1166
- applyRevalidateEntries(entries, (path, type) => {
1167
- const resolvedType = type ?? "page";
1168
- invalidatePrefetch(path, resolvedType);
1169
- invalidations.push({ path, type: resolvedType });
1170
- });
1171
-
1172
- if (autoRefresh && invalidations.length > 0) {
1173
- const currentLogicalPath =
1174
- normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
1175
- if (shouldAutoRefreshPath(currentLogicalPath, invalidations)) {
1176
- invalidationRefresh.run();
1177
- }
1178
- }
1179
- };
1180
- const catchUp = createSyncCatchUp({
1181
- fetchPage: async (after) => {
1182
- const url = new URL(`${changesUrl}/changes`, window.location.origin);
1183
- if (after !== undefined) {
1184
- url.searchParams.set("after", after);
1185
- }
1186
- const response = await window.fetch(url);
1187
- if (!response.ok) {
1188
- throw new Error(`Sync catch-up failed with status ${response.status}`);
1189
- }
1190
- return (await response.json()) as SyncChangePagePayload;
1191
- },
1192
- onInvalidations: applyInvalidations,
1193
- onReset: () => queries.invalidateAll(),
1194
- onQueries: (identities) => {
1195
- queries.invalidate(identities);
1196
- const tags = new Set(identities.map(queryTag));
1197
- const affected = (snapshot: RouterState) =>
1198
- snapshot.querySeeds?.some((seed) => tags.has(queryTag(seed.identity)));
1199
- for (const [href, entry] of prefetchCache.current) {
1200
- entry.promise
1201
- .then((snapshot) => {
1202
- if (snapshot && affected(snapshot) && prefetchCache.current.get(href) === entry) {
1203
- prefetchCache.current.delete(href);
1204
- }
1205
- })
1206
- .catch(() => undefined);
1207
- }
1208
- if (autoRefresh && affected(currentState.current)) {
1209
- invalidationRefresh.run();
1210
- }
1211
- },
1212
- });
1213
- const recover = () => {
1214
- if (disposed) {
1215
- return;
1216
- }
1217
- catchUp.catchUp().catch((error: unknown) => {
1218
- if (!disposed) {
1219
- log.warn({ action: "sync_catch_up_failed", error: String(error) });
1220
- }
1221
- });
1222
- };
1223
- const onSync = (event: { data: { cursor: string } }) => {
1224
- if (typeof event.data.cursor !== "string") {
1225
- log.warn({ action: "sync_invalid_event", event: "browser-events.sync" });
1226
- return;
1227
- }
1228
- catchUp.seed(event.data.cursor);
1229
- recover();
1230
- };
1231
- const connect = () => {
1232
- if (disposed || unsubscribe) {
1233
- return;
1234
- }
1235
- unsubscribe = subscribeBrowserEvent("sync", onSync);
1236
- if (!unsubscribe) {
1237
- log.warn({ action: "sync_transport_unavailable" });
1238
- }
1239
- };
1240
-
1241
- connect();
1242
- return () => {
1243
- disposed = true;
1244
- unsubscribe?.();
1245
- };
1246
- }, [syncPath, basePath, invalidatePrefetch, invalidationRefresh, autoRefresh, queries]);
361
+ useFetchInterception({
362
+ autoRefresh,
363
+ basePath,
364
+ invalidatePath: invalidatePrefetch,
365
+ invalidationRefresh,
366
+ });
367
+ useSyncStream({ autoRefresh, basePath, controller, invalidationRefresh, queries, syncPath });
1247
368
 
1248
369
  const queryData = useMemo(
1249
370
  () =>
@@ -1264,52 +385,79 @@ export function RouterProvider({
1264
385
  [queries, state.data, state.querySeeds, queryRevision, deferredRevision]
1265
386
  );
1266
387
  const renderedData = optimisticRuntime.project(queryData, currentHref);
1267
- let pageElement: React.ReactNode;
1268
- if (state.notFound || !state.match) {
1269
- const notFoundElement = buildNotFoundPageElement(
1270
- state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries,
1271
- state.notFound ?? {}
1272
- );
1273
- pageElement = root?.layout
1274
- ? createElement(root.layout as React.ElementType, renderedData, notFoundElement)
1275
- : notFoundElement;
1276
- } else {
1277
- pageElement = buildPageElement(
1278
- state.match,
1279
- root,
1280
- renderedData,
1281
- {
1282
- onReset: () => {
1283
- refresh(undefined).catch((err: unknown) => {
1284
- log.error({ action: "boundary_reset_failed", error: String(err) });
1285
- });
1286
- },
1287
- resetKey: `${currentHref}:${boundaryResetVersion}`,
1288
- },
1289
- state.error
1290
- );
388
+ const resetRoute = () => {
389
+ refresh(undefined).catch((err: unknown) => {
390
+ log.error({ action: "boundary_reset_failed", error: String(err) });
391
+ });
392
+ };
393
+ let chain = root ? [root] : [];
394
+ if (state.match) {
395
+ chain = collectRouteChainFromRoute(state.match.pageRoute);
1291
396
  }
397
+ const pageElement = resolveRouteElement({
398
+ boundaries: state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries ?? [],
399
+ boundaryOptions: {
400
+ onReset: resetRoute,
401
+ resetKey: `${currentHref}:${boundaryResetVersion}`,
402
+ },
403
+ chain,
404
+ data: renderedData,
405
+ page: state.match
406
+ ? { component: state.match.component, pattern: state.match.pattern }
407
+ : undefined,
408
+ reset: resetRoute,
409
+ rootBoundary: rootBoundaries?.[0],
410
+ });
1292
411
 
412
+ const stableRouter = useMemo<StableRouter>(
413
+ () => ({
414
+ basePath,
415
+ defaultPreload,
416
+ defaultPreloadDelay,
417
+ defaultPreloadStaleTime,
418
+ invalidatePrefetch,
419
+ navigate,
420
+ prefetch,
421
+ refresh: (options) => {
422
+ setBrowserSyncAuthentication(true);
423
+ return refresh(options);
424
+ },
425
+ searchRoutes: routes,
426
+ }),
427
+ [
428
+ basePath,
429
+ defaultPreload,
430
+ defaultPreloadDelay,
431
+ defaultPreloadStaleTime,
432
+ invalidatePrefetch,
433
+ navigate,
434
+ prefetch,
435
+ refresh,
436
+ routes,
437
+ ]
438
+ );
439
+ const routerStore = useMemo<RouterStore>(
440
+ () => ({
441
+ getCurrentHref: () => controller.getSnapshot().href,
442
+ router: stableRouter,
443
+ subscribe: controller.subscribe,
444
+ }),
445
+ [controller, stableRouter]
446
+ );
447
+ const routerContext = useMemo(
448
+ () => ({
449
+ ...stableRouter,
450
+ currentHref,
451
+ currentPattern: state.match?.pattern,
452
+ isNavigating,
453
+ search: resolvedSearch,
454
+ }),
455
+ [stableRouter, currentHref, state.match?.pattern, isNavigating, resolvedSearch]
456
+ );
1293
457
  const routerTree = (
1294
- <SearchStoreContext.Provider value={searchStore}>
1295
- {buildRouterTree(
1296
- {
1297
- basePath,
1298
- currentHref,
1299
- currentPattern: state.match?.pattern,
1300
- defaultPreload,
1301
- defaultPreloadDelay,
1302
- defaultPreloadStaleTime,
1303
- invalidatePrefetch,
1304
- isNavigating,
1305
- navigate,
1306
- prefetch,
1307
- refresh,
1308
- search: resolvedSearch,
1309
- searchRoutes: routes,
1310
- },
1311
- pageElement,
1312
- {
458
+ <RouterStoreContext.Provider value={routerStore}>
459
+ <SearchStoreContext.Provider value={searchStore}>
460
+ {buildRouterTree(routerContext, pageElement, {
1313
461
  digest: initialDigest,
1314
462
  document: initialDocumentState !== null,
1315
463
  onReset: () => {
@@ -1318,9 +466,9 @@ export function RouterProvider({
1318
466
  });
1319
467
  },
1320
468
  resetKey: `${currentHref}:${boundaryResetVersion}`,
1321
- }
1322
- )}
1323
- </SearchStoreContext.Provider>
469
+ })}
470
+ </SearchStoreContext.Provider>
471
+ </RouterStoreContext.Provider>
1324
472
  );
1325
473
  if (initialDocumentState === null) {
1326
474
  return <QueryStoreContext.Provider value={queries}>{routerTree}</QueryStoreContext.Provider>;