@teyik0/furin 0.7.0-alpha.2 → 0.8.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 (497) hide show
  1. package/README.md +1 -1
  2. package/dist/adapter/build.d.ts +9 -0
  3. package/dist/adapter/bun/server.d.ts +1 -0
  4. package/dist/adapter/bun.d.ts +7 -3
  5. package/dist/adapter/package.d.ts +1 -0
  6. package/dist/adapter/prerender.d.ts +21 -0
  7. package/dist/adapter/runtime-build.d.ts +24 -10
  8. package/dist/adapter/server-bundle.d.ts +20 -0
  9. package/dist/adapter/static.d.ts +2 -2
  10. package/dist/adapter/types.d.ts +81 -0
  11. package/dist/adapter/vercel/bootstrap.d.ts +5 -0
  12. package/dist/adapter/vercel/data.d.ts +23 -0
  13. package/dist/adapter/vercel/handler.d.ts +10 -0
  14. package/dist/adapter/vercel.d.ts +13 -3
  15. package/dist/adapter/vercel.js +516 -0
  16. package/dist/build/bun-build.d.ts +4 -0
  17. package/dist/build/compile-entry.ts +1 -0
  18. package/dist/build/discover-mounts-process.d.ts +1 -0
  19. package/dist/build/discover-mounts.d.ts +6 -0
  20. package/dist/build/elysia-aot-worker.d.ts +4 -0
  21. package/dist/build/elysia-aot.d.ts +7 -1
  22. package/dist/build/entry-template.d.ts +14 -7
  23. package/dist/build/entry-template.ts +33 -18
  24. package/dist/build/hydrate.d.ts +15 -2
  25. package/dist/build/index.d.ts +7 -3
  26. package/dist/build/index.js +8845 -15398
  27. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  28. package/dist/build/route-types.d.ts +8 -2
  29. package/dist/build/server-app-entry.d.ts +2 -2
  30. package/dist/build/shared.d.ts +3 -5
  31. package/dist/build/types.d.ts +16 -16
  32. package/dist/cache.js +117 -32
  33. package/dist/cli/config.d.ts +2 -2
  34. package/dist/cli/index.js +8956 -15272
  35. package/dist/client/chunks/client-brdfd773.js +852 -0
  36. package/dist/client/chunks/client-k29262a4.js +59 -0
  37. package/dist/client/chunks/client-k88668k7.js +159 -0
  38. package/dist/client/chunks/client-xy6g38kx.js +317 -0
  39. package/dist/client/default-screens.d.ts +0 -11
  40. package/dist/client/define-route.d.ts +2 -1
  41. package/dist/client/hmr.d.ts +1 -1
  42. package/dist/client/internal/runtime-types.d.ts +7 -1
  43. package/dist/client/link.d.ts +1 -0
  44. package/dist/client/link.js +1790 -4190
  45. package/dist/client/mutation.d.ts +5 -0
  46. package/dist/client/query-store.d.ts +17 -7
  47. package/dist/client/query.d.ts +6 -8
  48. package/dist/client/request-id.d.ts +1 -0
  49. package/dist/client/route-api.d.ts +4 -4
  50. package/dist/client/route-element.d.ts +51 -0
  51. package/dist/client/router/boundary-tree.d.ts +1 -9
  52. package/dist/client/router/cache-generation.d.ts +15 -0
  53. package/dist/client/router/context.d.ts +13 -2
  54. package/dist/client/router/fetch-observers.d.ts +9 -0
  55. package/dist/client/router/hmr-refresh.d.ts +12 -0
  56. package/dist/client/router/index.d.ts +5 -7
  57. package/dist/client/router/link-utils.d.ts +0 -2
  58. package/dist/client/router/navigation-controller.d.ts +76 -0
  59. package/dist/client/router/navigation.d.ts +1 -0
  60. package/dist/client/router/page-fetch.d.ts +38 -0
  61. package/dist/client/router/provider.d.ts +2 -3
  62. package/dist/client/router/search/index.d.ts +11 -4
  63. package/dist/client/router/search/index.js +60 -0
  64. package/dist/client/router/spa-response.d.ts +9 -26
  65. package/dist/client/router/sync-catch-up.d.ts +3 -2
  66. package/dist/client/router/transport.d.ts +4 -0
  67. package/dist/client/router/types.d.ts +120 -46
  68. package/dist/client/router/use-fetch-interception.d.ts +12 -0
  69. package/dist/client/router/use-history-sync.d.ts +7 -0
  70. package/dist/client/router/use-hmr-refresh.d.ts +8 -0
  71. package/dist/client/router/use-sync-stream.d.ts +16 -0
  72. package/dist/client/server-error.d.ts +4 -7
  73. package/dist/client/sync.d.ts +43 -30
  74. package/dist/client.d.ts +2 -1
  75. package/dist/client.js +279 -829
  76. package/dist/config.d.ts +11 -12
  77. package/dist/config.js +0 -30
  78. package/dist/define-route.d.ts +262 -517
  79. package/dist/devtools/protocol.d.ts +4 -3
  80. package/dist/furin.d.ts +41 -31
  81. package/dist/furin.js +20561 -18971
  82. package/dist/plugin/binding-scope.d.ts +15 -2
  83. package/dist/plugin/client-plugin.d.ts +19 -0
  84. package/dist/plugin/dead-code-elimination.d.ts +14 -3
  85. package/dist/plugin/dev-routes.d.ts +22 -0
  86. package/dist/plugin/hmr-data-signature.d.ts +3 -0
  87. package/dist/plugin/hmr-hook-signature.d.ts +9 -0
  88. package/dist/plugin/index.d.ts +1 -6
  89. package/dist/plugin/index.js +1753 -1214
  90. package/dist/plugin/module-bindings.d.ts +11 -0
  91. package/dist/plugin/module-transform.d.ts +29 -0
  92. package/dist/plugin/preflight.d.ts +8 -0
  93. package/dist/plugin/route-chains.d.ts +35 -0
  94. package/dist/plugin/route-config.d.ts +28 -0
  95. package/dist/plugin/route-modules.d.ts +35 -0
  96. package/dist/plugin/route-registry.d.ts +12 -0
  97. package/dist/plugin/route-tree.d.ts +43 -0
  98. package/dist/plugin/strip-server-stages.d.ts +10 -0
  99. package/dist/plugin/strip-server.d.ts +10 -0
  100. package/dist/plugin/transform-client-module.d.ts +3 -0
  101. package/dist/plugin/transform-client.d.ts +0 -2
  102. package/dist/plugin/transform-isomorphic.d.ts +3 -2
  103. package/dist/routes.d.ts +15 -5
  104. package/dist/rsc/build/client-references.d.ts +8 -0
  105. package/dist/rsc/build/discover.d.ts +7 -0
  106. package/dist/rsc/build/flight-loader.d.ts +1 -0
  107. package/dist/rsc/build/index.d.ts +4 -1
  108. package/dist/rsc/build/paths.d.ts +2 -0
  109. package/dist/rsc/bundled-client-codec.d.ts +1 -0
  110. package/dist/rsc/client-codec.d.ts +3 -0
  111. package/dist/rsc/client-references.d.ts +22 -0
  112. package/dist/rsc/server-client-codec.d.ts +1 -0
  113. package/dist/rsc/server-codec.js +3889 -2
  114. package/dist/rsc/slot-proxy.d.ts +11 -0
  115. package/dist/rsc/transport-benchmark.d.ts +2 -1
  116. package/dist/rsc-client.js +16 -164
  117. package/dist/rsc-server.d.ts +1 -5
  118. package/dist/rsc.d.ts +1 -5
  119. package/dist/rsc.js +233 -73
  120. package/dist/server/assets/client-dir.d.ts +1 -0
  121. package/dist/server/auto-invalidate/index.d.ts +2 -2
  122. package/dist/server/auto-invalidate/plugin.d.ts +21 -15
  123. package/dist/server/auto-invalidate/types.d.ts +0 -2
  124. package/dist/server/bounded-body.d.ts +6 -0
  125. package/dist/server/browser-events/plugin.d.ts +4 -1
  126. package/dist/server/browser-events/shutdown.d.ts +1 -1
  127. package/dist/server/cache/dev-loader.d.ts +6 -1
  128. package/dist/server/cache/index.d.ts +4 -9
  129. package/dist/server/cache/invalidation.d.ts +7 -2
  130. package/dist/server/cache/isr-ssg.d.ts +6 -1
  131. package/dist/server/cache/page-cache.d.ts +5 -0
  132. package/dist/server/cache/purger.d.ts +14 -4
  133. package/dist/server/cache/redis/index.d.ts +1 -34
  134. package/dist/server/cache/redis/index.js +51 -25
  135. package/dist/server/cache/redis/scripts.d.ts +1 -1
  136. package/dist/server/cache/route-cache.d.ts +18 -2
  137. package/dist/server/cache/runtime-cache.d.ts +7 -0
  138. package/dist/server/context-logger.d.ts +6 -1
  139. package/dist/server/dev/graph.d.ts +4 -3
  140. package/dist/server/dev/runtime.d.ts +4 -0
  141. package/dist/server/dev/runtime.production.d.ts +1 -0
  142. package/dist/server/dev/stack-location.d.ts +9 -0
  143. package/dist/server/dev-page-imports.d.ts +42 -0
  144. package/dist/server/dev-page-plugin.d.ts +2 -49
  145. package/dist/server/devtools/instrumentation.d.ts +1 -3
  146. package/dist/server/devtools/instrumentation.production.d.ts +0 -2
  147. package/dist/server/devtools/request-context.d.ts +7 -0
  148. package/dist/server/evlog.d.ts +18 -6
  149. package/dist/server/instance.d.ts +52 -44
  150. package/dist/server/internal.d.ts +51 -14
  151. package/dist/server/internal.js +9749 -2095
  152. package/dist/server/lang-detect.d.ts +4 -4
  153. package/dist/server/logger.d.ts +6 -0
  154. package/dist/server/logging/ingest-plugin.d.ts +32 -0
  155. package/dist/server/mode.d.ts +17 -0
  156. package/dist/server/prerender.d.ts +32 -0
  157. package/dist/server/prod/runtime.d.ts +5 -0
  158. package/dist/server/production-server.js +992 -726
  159. package/dist/server/registrations.d.ts +14 -0
  160. package/dist/server/render/assemble.d.ts +0 -22
  161. package/dist/server/render/buffered-render.d.ts +20 -0
  162. package/dist/server/render/document-stream.d.ts +45 -0
  163. package/dist/server/render/document.d.ts +1 -1
  164. package/dist/server/render/element.d.ts +2 -5
  165. package/dist/server/render/index.d.ts +4 -5
  166. package/dist/server/render/index.ts +4 -21
  167. package/dist/server/render/isr-revalidation.d.ts +5 -0
  168. package/dist/server/render/isr-shared-cache.d.ts +23 -0
  169. package/dist/server/render/isr.d.ts +19 -1
  170. package/dist/server/render/loader-errors.d.ts +33 -0
  171. package/dist/server/render/loader-segments.d.ts +40 -0
  172. package/dist/server/render/loaders.d.ts +16 -32
  173. package/dist/server/render/mixed-cache.d.ts +2 -2
  174. package/dist/server/render/navigation-head.d.ts +13 -0
  175. package/dist/server/render/not-found-plugin.d.ts +18 -0
  176. package/dist/server/render/observe-loader.d.ts +1 -0
  177. package/dist/server/render/ppr-document.d.ts +1 -1
  178. package/dist/server/render/ppr-request.d.ts +0 -2
  179. package/dist/server/render/ppr-route.d.ts +13 -2
  180. package/dist/server/render/prepare-render.d.ts +57 -0
  181. package/dist/server/render/request-loaders.d.ts +19 -0
  182. package/dist/server/render/route-frame-transport.d.ts +7 -1
  183. package/dist/server/render/shell.d.ts +1 -1
  184. package/dist/server/render/shell.ts +1 -1
  185. package/dist/server/render/ssr-transport.d.ts +11 -0
  186. package/dist/server/render/ssr.d.ts +1 -116
  187. package/dist/server/render/static-params.d.ts +15 -0
  188. package/dist/server/router/discovery.d.ts +1 -0
  189. package/dist/server/router/dispatch.d.ts +96 -0
  190. package/dist/server/router/hmr.d.ts +14 -24
  191. package/dist/server/router/patterns.d.ts +15 -20
  192. package/dist/server/router/plugin.d.ts +26 -24
  193. package/dist/server/router/schemas.d.ts +6 -24
  194. package/dist/server/router/types.d.ts +0 -2
  195. package/dist/server/runtime-env.d.ts +6 -1
  196. package/dist/server/static-export.d.ts +38 -0
  197. package/dist/server/static-export.js +10667 -0
  198. package/dist/server/sync/adapter.d.ts +11 -0
  199. package/dist/server/sync/atomic.d.ts +0 -2
  200. package/dist/server/sync/config.d.ts +0 -1
  201. package/dist/server/sync/drizzle/index.js +112 -68
  202. package/dist/server/sync/fingerprint.d.ts +0 -1
  203. package/dist/server/sync/index.d.ts +2 -6
  204. package/dist/server/sync/index.js +1690 -1365
  205. package/dist/server/sync/invalidate-sync.d.ts +10 -0
  206. package/dist/server/sync/plugin.d.ts +18 -55
  207. package/dist/server/sync/postgres/execute.d.ts +2 -2
  208. package/dist/server/sync/postgres/index.d.ts +3 -1
  209. package/dist/server/sync/postgres/index.js +68 -37
  210. package/dist/server/sync/postgres/migration.sql +2 -0
  211. package/dist/server/sync/principal-journal.d.ts +11 -0
  212. package/dist/server/sync/prisma/index.js +74 -39
  213. package/dist/server/sync/queries.d.ts +57 -16
  214. package/dist/server/sync/redis/index.d.ts +2 -1
  215. package/dist/server/sync/redis/index.js +49 -5
  216. package/dist/server/sync/redis/scripts.d.ts +2 -1
  217. package/dist/server/sync/response.d.ts +3 -0
  218. package/dist/server/sync/runtime.d.ts +5 -1
  219. package/dist/server/sync/sqlite/index.d.ts +3 -1
  220. package/dist/server/sync/sqlite/index.js +58 -27
  221. package/dist/server/sync/stream.d.ts +32 -7
  222. package/dist/server/weak-registry.d.ts +9 -0
  223. package/dist/shared/await.d.ts +2 -1
  224. package/dist/shared/compact-json.d.ts +1 -0
  225. package/dist/shared/defer.d.ts +1 -1
  226. package/dist/shared/deferred-ndjson.d.ts +3 -2
  227. package/dist/shared/elysia-contract.d.ts +2 -0
  228. package/dist/shared/in-memory-apps.d.ts +7 -0
  229. package/dist/shared/invalidation-header.d.ts +13 -0
  230. package/dist/shared/navigation-data.d.ts +7 -0
  231. package/dist/shared/prefix.d.ts +11 -5
  232. package/dist/shared/route-frame.d.ts +3 -0
  233. package/dist/shared/route-map.d.ts +7 -0
  234. package/dist/shared/route-matches.d.ts +41 -0
  235. package/dist/shared/route-specificity.d.ts +2 -0
  236. package/dist/shared/search-params.d.ts +2 -3
  237. package/dist/shared/sync-query.d.ts +6 -13
  238. package/dist/shared/utils/ast-walk.d.ts +3 -11
  239. package/package.json +32 -21
  240. package/src/adapter/README.md +37 -16
  241. package/src/adapter/build.ts +269 -0
  242. package/src/adapter/bun/server.ts +14 -0
  243. package/src/adapter/bun.ts +89 -265
  244. package/src/adapter/furin-app.d.ts +14 -0
  245. package/src/adapter/package.ts +31 -27
  246. package/src/adapter/prerender.ts +97 -0
  247. package/src/adapter/runtime-build.ts +83 -93
  248. package/src/adapter/server-bundle.ts +110 -0
  249. package/src/adapter/static.ts +259 -247
  250. package/src/adapter/types.ts +89 -0
  251. package/src/adapter/vercel/bootstrap.ts +85 -0
  252. package/src/adapter/vercel/data.ts +21 -0
  253. package/src/adapter/vercel/handler.ts +132 -0
  254. package/src/adapter/vercel.ts +333 -667
  255. package/src/build/bun-build.ts +3 -0
  256. package/src/build/client.ts +22 -60
  257. package/src/build/compile-entry.ts +1 -0
  258. package/src/build/discover-mounts-process.ts +13 -0
  259. package/src/build/discover-mounts.ts +40 -0
  260. package/src/build/elysia-aot-worker.ts +84 -2
  261. package/src/build/elysia-aot.ts +61 -2
  262. package/src/build/entry-template.ts +33 -18
  263. package/src/build/hydrate.ts +122 -44
  264. package/src/build/index.ts +156 -108
  265. package/src/build/private-server-sourcemaps.ts +5 -0
  266. package/src/build/production-instrumentation.ts +22 -19
  267. package/src/build/route-types.ts +93 -11
  268. package/src/build/server-app-entry.ts +4 -21
  269. package/src/build/shared.ts +9 -41
  270. package/src/build/types.ts +14 -20
  271. package/src/build/virtual-entry.ts +2 -4
  272. package/src/cli/config.ts +133 -6
  273. package/src/cli/index.ts +59 -21
  274. package/src/cli/preview.ts +2 -1
  275. package/src/client/boundaries.tsx +5 -14
  276. package/src/client/default-screens.tsx +2 -2
  277. package/src/client/define-route.ts +3 -2
  278. package/src/client/hmr.ts +1 -1
  279. package/src/client/internal/runtime-types.ts +7 -1
  280. package/src/client/link.tsx +80 -43
  281. package/src/client/mutation.ts +98 -3
  282. package/src/client/query-store.ts +160 -29
  283. package/src/client/query.tsx +12 -29
  284. package/src/client/request-id.ts +10 -0
  285. package/src/client/route-api.tsx +6 -6
  286. package/src/client/route-element.tsx +155 -0
  287. package/src/client/router/boundary-tree.tsx +2 -93
  288. package/src/client/router/cache-generation.ts +37 -0
  289. package/src/client/router/context.ts +40 -4
  290. package/src/client/router/fetch-observers.ts +46 -0
  291. package/src/client/router/hmr-refresh.ts +50 -0
  292. package/src/client/router/index.ts +7 -29
  293. package/src/client/router/link-utils.ts +19 -31
  294. package/src/client/router/navigation-controller.ts +547 -0
  295. package/src/client/router/navigation.ts +3 -2
  296. package/src/client/router/optimistic.ts +2 -3
  297. package/src/client/router/page-fetch.ts +272 -0
  298. package/src/client/router/provider.tsx +223 -1079
  299. package/src/client/router/search/index.ts +38 -14
  300. package/src/client/router/spa-response.ts +19 -70
  301. package/src/client/router/sync-catch-up.ts +65 -7
  302. package/src/client/router/transport.ts +23 -0
  303. package/src/client/router/types.ts +203 -61
  304. package/src/client/router/use-fetch-interception.ts +52 -0
  305. package/src/client/router/use-history-sync.ts +56 -0
  306. package/src/client/router/use-hmr-refresh.ts +51 -0
  307. package/src/client/router/use-sync-stream.ts +129 -0
  308. package/src/client/server-error.ts +2 -40
  309. package/src/client/sync.ts +268 -378
  310. package/src/client.ts +2 -7
  311. package/src/config.ts +23 -45
  312. package/src/define-route.ts +487 -882
  313. package/src/devtools/devtools-element.js +10 -3
  314. package/src/devtools/protocol.ts +3 -3
  315. package/src/furin.ts +253 -1086
  316. package/src/plugin/binding-scope.ts +219 -94
  317. package/src/plugin/client-plugin.ts +145 -0
  318. package/src/plugin/dead-code-elimination.ts +390 -111
  319. package/src/plugin/dev-routes.ts +453 -0
  320. package/src/plugin/hmr-data-signature.ts +161 -0
  321. package/src/plugin/hmr-dependencies.ts +2 -4
  322. package/src/plugin/hmr-hook-signature.ts +252 -0
  323. package/src/plugin/index.ts +3 -96
  324. package/src/plugin/module-bindings.ts +216 -0
  325. package/src/plugin/module-transform.ts +63 -0
  326. package/src/plugin/preflight.ts +66 -0
  327. package/src/plugin/route-chains.ts +309 -0
  328. package/src/plugin/route-config.ts +451 -0
  329. package/src/plugin/route-modules.ts +209 -0
  330. package/src/plugin/route-registry.ts +316 -0
  331. package/src/plugin/route-tree.ts +248 -0
  332. package/src/plugin/strip-server-stages.ts +197 -0
  333. package/src/plugin/strip-server.ts +22 -0
  334. package/src/plugin/transform-client-module.ts +36 -31
  335. package/src/plugin/transform-client.ts +33 -1114
  336. package/src/plugin/transform-dev-page.ts +84 -92
  337. package/src/plugin/transform-isomorphic.ts +396 -185
  338. package/src/routes.ts +15 -5
  339. package/src/rsc/build/client-references.ts +267 -0
  340. package/src/rsc/build/discover.ts +226 -0
  341. package/src/rsc/build/flight-loader.ts +69 -0
  342. package/src/rsc/build/index.ts +53 -31
  343. package/src/rsc/build/paths.ts +7 -0
  344. package/src/rsc/bundled-client-codec.ts +4 -0
  345. package/src/rsc/client-codec.ts +12 -3
  346. package/src/rsc/client-references.ts +138 -0
  347. package/src/rsc/codec.ts +30 -21
  348. package/src/rsc/flight-drain.ts +6 -29
  349. package/src/rsc/react-server-dom-webpack.d.ts +1 -1
  350. package/src/rsc/server-client-codec.ts +14 -0
  351. package/src/rsc/server-codec.ts +5 -8
  352. package/src/rsc/slot-proxy.ts +34 -0
  353. package/src/rsc/transport-benchmark.ts +1 -1
  354. package/src/rsc-server.tsx +5 -23
  355. package/src/rsc.tsx +5 -29
  356. package/src/server/assets/client-dir.ts +110 -0
  357. package/src/server/assets/production.ts +1 -1
  358. package/src/server/auto-invalidate/index.ts +2 -7
  359. package/src/server/auto-invalidate/plugin.ts +43 -15
  360. package/src/server/auto-invalidate/registry.ts +6 -6
  361. package/src/server/auto-invalidate/runtime.ts +16 -98
  362. package/src/server/auto-invalidate/types.ts +0 -6
  363. package/src/server/bounded-body.ts +38 -0
  364. package/src/server/browser-events/plugin.ts +109 -22
  365. package/src/server/browser-events/shutdown.ts +28 -9
  366. package/src/server/cache/dev-loader.ts +30 -16
  367. package/src/server/cache/index.ts +2 -15
  368. package/src/server/cache/invalidation.ts +27 -46
  369. package/src/server/cache/isr-ssg.ts +6 -1
  370. package/src/server/cache/isr.ts +11 -11
  371. package/src/server/cache/page-cache-state.ts +2 -2
  372. package/src/server/cache/page-cache.ts +13 -9
  373. package/src/server/cache/purger.ts +64 -8
  374. package/src/server/cache/redis/index.ts +17 -27
  375. package/src/server/cache/redis/scripts.ts +21 -4
  376. package/src/server/cache/registry.ts +3 -3
  377. package/src/server/cache/route-cache.ts +47 -13
  378. package/src/server/cache/runtime-cache.ts +144 -24
  379. package/src/server/cache/ssg.ts +7 -5
  380. package/src/server/context-logger.ts +46 -8
  381. package/src/server/dev/diagnostics.ts +6 -56
  382. package/src/server/dev/error.ts +3 -34
  383. package/src/server/dev/graph.ts +35 -22
  384. package/src/server/dev/rewrite-module-specifiers.ts +15 -19
  385. package/src/server/dev/runtime.production.ts +4 -0
  386. package/src/server/dev/runtime.ts +404 -0
  387. package/src/server/dev/stack-location.ts +46 -0
  388. package/src/server/dev-page-imports.ts +183 -0
  389. package/src/server/dev-page-plugin.ts +39 -302
  390. package/src/server/devtools/hub.ts +3 -3
  391. package/src/server/devtools/instrumentation.production.ts +0 -8
  392. package/src/server/devtools/instrumentation.ts +6 -8
  393. package/src/server/devtools/plugin.ts +2 -1
  394. package/src/server/devtools/request-context.ts +67 -16
  395. package/src/server/evlog.ts +119 -55
  396. package/src/server/instance.ts +187 -138
  397. package/src/server/internal.ts +66 -62
  398. package/src/server/lang-detect.ts +31 -22
  399. package/src/server/logger.ts +20 -7
  400. package/src/server/logging/ingest-plugin.ts +123 -0
  401. package/src/server/mode.ts +19 -0
  402. package/src/server/prerender.ts +122 -0
  403. package/src/server/prod/runtime.ts +181 -0
  404. package/src/server/production-server.ts +43 -17
  405. package/src/server/registrations.ts +38 -0
  406. package/src/server/render/assemble.ts +5 -8
  407. package/src/server/render/buffered-render.ts +171 -0
  408. package/src/server/render/document-stream.ts +188 -0
  409. package/src/server/render/document.tsx +5 -3
  410. package/src/server/render/element.tsx +6 -73
  411. package/src/server/render/index.ts +4 -21
  412. package/src/server/render/isr-revalidation.ts +246 -0
  413. package/src/server/render/isr-shared-cache.ts +141 -0
  414. package/src/server/render/isr.ts +212 -516
  415. package/src/server/render/loader-errors.ts +183 -0
  416. package/src/server/render/loader-segments.ts +149 -0
  417. package/src/server/render/loaders.ts +126 -547
  418. package/src/server/render/mixed-cache.ts +28 -27
  419. package/src/server/render/navigation-head.ts +33 -0
  420. package/src/server/render/not-found-plugin.ts +31 -0
  421. package/src/server/render/not-found.ts +32 -8
  422. package/src/server/render/observe-loader.ts +46 -0
  423. package/src/server/render/ppr-document.ts +36 -14
  424. package/src/server/render/ppr-request.ts +2 -2
  425. package/src/server/render/ppr-route.ts +79 -18
  426. package/src/server/render/prepare-render.ts +251 -0
  427. package/src/server/render/request-loaders.ts +216 -0
  428. package/src/server/render/route-frame-transport.ts +41 -4
  429. package/src/server/render/shell.ts +1 -1
  430. package/src/server/render/ssg.ts +9 -20
  431. package/src/server/render/ssr-transport.ts +221 -0
  432. package/src/server/render/ssr.ts +95 -956
  433. package/src/server/render/static-params.ts +32 -0
  434. package/src/server/render/template.ts +7 -7
  435. package/src/server/router/discovery.ts +82 -159
  436. package/src/server/router/dispatch.ts +337 -0
  437. package/src/server/router/hmr.ts +177 -190
  438. package/src/server/router/patterns.ts +39 -65
  439. package/src/server/router/plugin.ts +234 -359
  440. package/src/server/router/schemas.ts +6 -39
  441. package/src/server/router/source-version.ts +5 -4
  442. package/src/server/router/types.ts +0 -2
  443. package/src/server/runtime-env.ts +6 -1
  444. package/src/server/static-export.ts +143 -0
  445. package/src/server/sync/adapter.ts +11 -0
  446. package/src/server/sync/atomic.ts +16 -36
  447. package/src/server/sync/config.ts +6 -14
  448. package/src/server/sync/drizzle/index.ts +12 -20
  449. package/src/server/sync/fingerprint.ts +1 -1
  450. package/src/server/sync/index.ts +2 -10
  451. package/src/server/sync/invalidate-sync.ts +31 -0
  452. package/src/server/sync/mutation-handler.ts +12 -1
  453. package/src/server/sync/plugin.ts +171 -129
  454. package/src/server/sync/postgres/execute.ts +9 -1
  455. package/src/server/sync/postgres/index.ts +71 -39
  456. package/src/server/sync/postgres/migration.sql +2 -0
  457. package/src/server/sync/principal-journal.ts +78 -0
  458. package/src/server/sync/prisma/index.ts +1 -0
  459. package/src/server/sync/queries.ts +133 -40
  460. package/src/server/sync/query-context.ts +38 -5
  461. package/src/server/sync/redis/index.ts +34 -6
  462. package/src/server/sync/redis/scripts.ts +10 -1
  463. package/src/server/sync/response.ts +47 -67
  464. package/src/server/sync/runtime.ts +24 -7
  465. package/src/server/sync/sqlite/index.ts +92 -61
  466. package/src/server/sync/sqlite/migration.sql +1 -0
  467. package/src/server/sync/stream.ts +47 -26
  468. package/src/server/sync/validation.ts +1 -1
  469. package/src/server/weak-registry.ts +37 -0
  470. package/src/shared/await.tsx +2 -1
  471. package/src/shared/compact-json.ts +1 -1
  472. package/src/shared/defer.ts +1 -1
  473. package/src/shared/deferred-ndjson.ts +142 -120
  474. package/src/shared/elysia-contract.ts +7 -0
  475. package/src/shared/error.ts +1 -4
  476. package/src/shared/in-memory-apps.ts +24 -0
  477. package/src/shared/invalidation-header.ts +38 -0
  478. package/src/shared/navigation-data.ts +29 -0
  479. package/src/shared/prefix.ts +42 -6
  480. package/src/shared/route-frame.ts +82 -26
  481. package/src/shared/route-map.ts +23 -39
  482. package/src/shared/route-matches.ts +59 -0
  483. package/src/shared/route-specificity.ts +28 -0
  484. package/src/shared/search-params.ts +6 -35
  485. package/src/shared/sync-query.ts +30 -23
  486. package/src/shared/utils/ast-walk.ts +9 -25
  487. package/src/shared/utils/index.ts +1 -1
  488. package/dist/build/scan-server.d.ts +0 -14
  489. package/dist/build/ssg-cache.d.ts +0 -17
  490. package/dist/plugin/route-config-autofix.d.ts +0 -31
  491. package/dist/plugin/routes.d.ts +0 -34
  492. package/dist/server/router/hmr.production.d.ts +0 -7
  493. package/src/build/scan-server.ts +0 -112
  494. package/src/build/ssg-cache.ts +0 -124
  495. package/src/plugin/route-config-autofix.ts +0 -1149
  496. package/src/plugin/routes.ts +0 -1140
  497. package/src/server/router/hmr.production.ts +0 -18
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- // src/plugin/index.ts
3
- import { dirname as dirname3, isAbsolute as isAbsolute2, resolve as resolve2 } from "path";
2
+ // src/plugin/client-plugin.ts
3
+ import { dirname as dirname4, isAbsolute as isAbsolute2, resolve as resolve2 } from "path";
4
4
 
5
5
  // src/rsc/build/environment.ts
6
6
  import { fileURLToPath } from "url";
@@ -26,18 +26,75 @@ function environmentGuardPlugin(graph) {
26
26
  };
27
27
  }
28
28
 
29
+ // src/rsc/build/flight-loader.ts
30
+ import { readFileSync } from "fs";
31
+
32
+ // src/rsc/build/paths.ts
33
+ import { dirname, join } from "path";
34
+ import { fileURLToPath as fileURLToPath2 } from "url";
35
+ var SOURCE_DIR = dirname(fileURLToPath2(import.meta.resolve("@teyik0/furin/rsc")));
36
+ var CLIENT_REFERENCE_RUNTIME_PATH = join(SOURCE_DIR, "rsc/client-references.ts");
37
+ var BUNDLED_CLIENT_CODEC_PATH = join(SOURCE_DIR, "rsc/bundled-client-codec.ts");
38
+
39
+ // src/rsc/build/flight-loader.ts
40
+ var CLIENT_CODEC = /react-server-dom-webpack-client\.(?:edge|browser)\.(?:development|production)\.js$/;
41
+ var CODEC_EXPORT = /exports\.([\w$]+)\s*=/g;
42
+ var SERVER_CODEC = /react-server-dom-webpack-server\.(?:edge|browser|node)\.(?:development|production)\.js$/;
43
+ var REFERENCE_FIELD = /((?:[\w$]+\.)*[\w$]+)\.\$\$(typeof|id|async)\b/g;
44
+ function readReferenceFieldsThroughRegistry(source, path) {
45
+ const patched = source.replace(REFERENCE_FIELD, (_field, owner, name) => `__furinClientReference(${owner}).$$${name}`);
46
+ if (patched === source) {
47
+ throw new Error(`[furin/rsc] Unsupported Flight server codec: ${path}`);
48
+ }
49
+ return patched.replace('"use strict";', `"use strict";
50
+ var __furinClientReference = require(${JSON.stringify(CLIENT_REFERENCE_RUNTIME_PATH)}).clientReference;`);
51
+ }
52
+ function flightLoaderPlugin() {
53
+ return {
54
+ name: "furin-flight-module-loader",
55
+ setup(build) {
56
+ build.onResolve({ filter: /(?:^|\/)server-client-codec\.ts$/ }, () => ({
57
+ path: BUNDLED_CLIENT_CODEC_PATH
58
+ }));
59
+ build.onLoad({ filter: SERVER_CODEC }, ({ path }) => ({
60
+ contents: readReferenceFieldsThroughRegistry(readFileSync(path, "utf8"), path),
61
+ loader: "js"
62
+ }));
63
+ build.onLoad({ filter: CLIENT_CODEC }, ({ path }) => {
64
+ let source = readFileSync(path, "utf8");
65
+ if (path.endsWith(".development.js")) {
66
+ source = source.replace(/case "L":(\s+)id = response\[0\];/, `case "L":$1if (typeof window !== "undefined" && response[1] === "image" && response[2]?.imageSrcSet) break;
67
+ id = response[0];`);
68
+ }
69
+ const exports = path.endsWith(".production.js") ? source.replaceAll(CODEC_EXPORT, "export const $1 =") : `const furinCodecExports = {};
70
+ ${source.replaceAll("exports.", "furinCodecExports.")}
71
+ export const { createFromReadableStream, createFromFetch } = furinCodecExports;`;
72
+ return {
73
+ contents: `import { requireClientModule as __webpack_require__ } from ${JSON.stringify(CLIENT_REFERENCE_RUNTIME_PATH)};
74
+ ${exports}`,
75
+ loader: "js"
76
+ };
77
+ });
78
+ }
79
+ };
80
+ }
81
+
29
82
  // src/server/lang-detect.ts
83
+ var SCRIPT_FILE_FILTER = /\.(?:[cm]?[jt]s|[jt]sx)(?:\?.*)?$/;
84
+ var DECLARATION_FILE_RE = /\.d\.[cm]?ts$/;
85
+ var TYPESCRIPT_FILE_RE = /\.[cm]?ts$/;
30
86
  function detectLangFromPath(filePath) {
31
- if (filePath.endsWith(".d.ts")) {
87
+ const path = filePath.split("?")[0];
88
+ if (DECLARATION_FILE_RE.test(path)) {
32
89
  return "dts";
33
90
  }
34
- if (filePath.endsWith(".tsx")) {
91
+ if (path.endsWith(".tsx")) {
35
92
  return "tsx";
36
93
  }
37
- if (filePath.endsWith(".ts")) {
94
+ if (TYPESCRIPT_FILE_RE.test(path)) {
38
95
  return "ts";
39
96
  }
40
- if (filePath.endsWith(".jsx")) {
97
+ if (path.endsWith(".jsx")) {
41
98
  return "jsx";
42
99
  }
43
100
  return "js";
@@ -54,14 +111,23 @@ var TS_WRAPPER_TYPES = new Set([
54
111
  "TSInstantiationExpression",
55
112
  "ParenthesizedExpression"
56
113
  ]);
114
+ function isTSWrapper(node) {
115
+ return TS_WRAPPER_TYPES.has(node.type);
116
+ }
57
117
  function unwrapTSExpression(node) {
58
118
  let current = node;
59
- while (current && typeof current === "object" && TS_WRAPPER_TYPES.has(current.type) && current.expression && typeof current.expression === "object") {
119
+ while (isTSWrapper(current)) {
60
120
  current = current.expression;
61
121
  }
62
122
  return current;
63
123
  }
64
124
 
125
+ // src/shared/utils/ast-walk.ts
126
+ var SKIP_KEYS = new Set(["type", "start", "end", "comments"]);
127
+ function isNode(value) {
128
+ return "type" in value && typeof value.type === "string";
129
+ }
130
+
65
131
  // ../../node_modules/.bun/@jridgewell+sourcemap-codec@1.6.0/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
66
132
  var comma = 44;
67
133
  var semicolon = 59;
@@ -172,7 +238,7 @@ function encode(decoded) {
172
238
  return writer.flush();
173
239
  }
174
240
 
175
- // ../../node_modules/.bun/magic-string@1.4.2/node_modules/magic-string/dist/index.mjs
241
+ // ../../node_modules/.bun/magic-string@1.4.3/node_modules/magic-string/dist/index.mjs
176
242
  var BitSet = class BitSet {
177
243
  constructor(arg) {
178
244
  this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
@@ -1194,7 +1260,7 @@ var MagicString = class MagicString {
1194
1260
  if (chunk.next !== this.byStart.get(chunk.end))
1195
1261
  throw new MagicStringError("cannot overwrite across a split point");
1196
1262
  chunk = chunk.next;
1197
- chunk.edit("", false);
1263
+ chunk.edit("", false, !overwrite);
1198
1264
  }
1199
1265
  first.edit(content, storeName, !overwrite);
1200
1266
  } else {
@@ -1551,9 +1617,9 @@ var MagicString = class MagicString {
1551
1617
  if (replacement === match[0])
1552
1618
  return true;
1553
1619
  if (match[0].length === 0)
1554
- this.appendRight(match.index, replacement);
1620
+ this.appendRight(match.index - this.offset, replacement);
1555
1621
  else
1556
- this.overwrite(match.index, match.index + match[0].length, replacement);
1622
+ this.overwrite(match.index - this.offset, match.index + match[0].length - this.offset, replacement);
1557
1623
  return true;
1558
1624
  };
1559
1625
  if (searchValue.global) {
@@ -1585,9 +1651,9 @@ var MagicString = class MagicString {
1585
1651
  replacement = expandReplacement(replacement, string, index, original, [], undefined);
1586
1652
  if (string !== replacement) {
1587
1653
  if (string.length === 0)
1588
- this.appendRight(index, replacement);
1654
+ this.appendRight(index - this.offset, replacement);
1589
1655
  else
1590
- this.overwrite(index, index + string.length, replacement);
1656
+ this.overwrite(index - this.offset, index + string.length - this.offset, replacement);
1591
1657
  }
1592
1658
  break;
1593
1659
  }
@@ -1607,7 +1673,7 @@ var MagicString = class MagicString {
1607
1673
  continue;
1608
1674
  const _replacement = typeof replacement === "function" ? replacement("", index, original) : expandReplacement(replacement, "", index, original, [], undefined);
1609
1675
  if (_replacement !== "")
1610
- this.appendRight(index, _replacement);
1676
+ this.appendRight(index - this.offset, _replacement);
1611
1677
  }
1612
1678
  return this;
1613
1679
  }
@@ -1617,7 +1683,7 @@ var MagicString = class MagicString {
1617
1683
  const previous = original.slice(index, index + stringLength);
1618
1684
  const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : expandReplacement(replacement, previous, index, original, [], undefined);
1619
1685
  if (previous !== _replacement)
1620
- this.overwrite(index, index + stringLength, _replacement);
1686
+ this.overwrite(index - this.offset, index + stringLength - this.offset, _replacement);
1621
1687
  }
1622
1688
  return this;
1623
1689
  }
@@ -1629,6 +1695,341 @@ var MagicString = class MagicString {
1629
1695
  return this._replaceRegexp(searchValue, replacement);
1630
1696
  }
1631
1697
  };
1698
+
1699
+ // src/shared/parser.ts
1700
+ import { parse } from "yuku-parser";
1701
+ function parseSource(code, lang) {
1702
+ return parse(code, { lang, sourceType: "module" });
1703
+ }
1704
+
1705
+ // src/plugin/module-transform.ts
1706
+ function parseModule(code, filename) {
1707
+ const { diagnostics, program } = parseSource(code, detectLangFromPath(filename));
1708
+ const error = diagnostics.find((diagnostic) => diagnostic.severity === "error");
1709
+ if (error) {
1710
+ throw new Error(`Failed to parse ${filename}: ${error.message}`);
1711
+ }
1712
+ return { code, filename, program, removed: [], source: new MagicString(code) };
1713
+ }
1714
+ function isRemoved(node, removed) {
1715
+ return removed.some((range) => range.start <= node.start && node.end <= range.end);
1716
+ }
1717
+ function replaceRange(module, start, end, content) {
1718
+ const replacement = content + `
1719
+ `.repeat(module.source.original.slice(start, end).split(`
1720
+ `).length - 1);
1721
+ if (replacement === "") {
1722
+ module.source.remove(start, end);
1723
+ } else {
1724
+ module.source.overwrite(start, end, replacement);
1725
+ }
1726
+ module.removed.push({ end, start });
1727
+ }
1728
+ function removeRange(module, start, end) {
1729
+ replaceRange(module, start, end, "");
1730
+ }
1731
+
1732
+ // src/plugin/dead-code-elimination.ts
1733
+ var TYPE_SCOPE_NODES = new Set([
1734
+ "TSTypeAnnotation",
1735
+ "TSTypeParameterDeclaration",
1736
+ "TSTypeParameterInstantiation",
1737
+ "TSInterfaceDeclaration",
1738
+ "TSTypeAliasDeclaration",
1739
+ "TSTypePredicate",
1740
+ "TSClassImplements",
1741
+ "TSExpressionWithTypeArguments"
1742
+ ]);
1743
+ var TYPE_ASSERTION_NODES = new Set([
1744
+ "TSAsExpression",
1745
+ "TSSatisfiesExpression",
1746
+ "TSTypeAssertion"
1747
+ ]);
1748
+ var WALK_SKIPPED_KEYS = new Set(["type", "start", "end"]);
1749
+ function isTypeAssertion(node) {
1750
+ return TYPE_ASSERTION_NODES.has(node.type);
1751
+ }
1752
+ function excludeBindingIdentifiers(node, excluded) {
1753
+ if (!node) {
1754
+ return;
1755
+ }
1756
+ if (node.type === "Identifier") {
1757
+ excluded.add(node);
1758
+ } else if (node.type === "AssignmentPattern") {
1759
+ excludeBindingIdentifiers(node.left, excluded);
1760
+ } else if (node.type === "RestElement") {
1761
+ excludeBindingIdentifiers(node.argument, excluded);
1762
+ } else if (node.type === "ArrayPattern") {
1763
+ for (const element of node.elements) {
1764
+ excludeBindingIdentifiers(element, excluded);
1765
+ }
1766
+ } else if (node.type === "ObjectPattern") {
1767
+ for (const property of node.properties) {
1768
+ excludeBindingIdentifiers(property.type === "Property" ? property.value : property, excluded);
1769
+ }
1770
+ }
1771
+ }
1772
+ function excludeDeclaredIdentifiers(node, excluded) {
1773
+ if (node.type === "VariableDeclarator") {
1774
+ excludeBindingIdentifiers(node.id, excluded);
1775
+ } else if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") {
1776
+ excludeBindingIdentifiers(node.id, excluded);
1777
+ for (const parameter of node.params) {
1778
+ excludeBindingIdentifiers(parameter, excluded);
1779
+ }
1780
+ } else if (node.type === "ClassDeclaration" || node.type === "ClassExpression") {
1781
+ excludeBindingIdentifiers(node.id, excluded);
1782
+ } else if (node.type === "CatchClause") {
1783
+ excludeBindingIdentifiers(node.param, excluded);
1784
+ }
1785
+ }
1786
+ function collectReferences(value, removed, excluded, references) {
1787
+ if (!value || typeof value !== "object") {
1788
+ return;
1789
+ }
1790
+ if (Array.isArray(value)) {
1791
+ for (const item of value) {
1792
+ collectReferences(item, removed, excluded, references);
1793
+ }
1794
+ return;
1795
+ }
1796
+ if (!isNode(value) || excluded.has(value) || TYPE_SCOPE_NODES.has(value.type) || isRemoved(value, removed)) {
1797
+ return;
1798
+ }
1799
+ const node = value;
1800
+ if (node.type === "Property" && !node.computed) {
1801
+ excluded.add(node.key);
1802
+ }
1803
+ if (node.type === "MemberExpression" && !node.computed) {
1804
+ excluded.add(node.property);
1805
+ }
1806
+ if (node.type === "JSXAttribute") {
1807
+ excluded.add(node.name);
1808
+ }
1809
+ if (node.type === "JSXMemberExpression") {
1810
+ excluded.add(node.property);
1811
+ }
1812
+ if (isTypeAssertion(node)) {
1813
+ excluded.add(node.typeAnnotation);
1814
+ }
1815
+ excludeDeclaredIdentifiers(node, excluded);
1816
+ if (node.type === "Identifier" || node.type === "JSXIdentifier") {
1817
+ references.add(node.name);
1818
+ }
1819
+ for (const [key, child] of Object.entries(node)) {
1820
+ if (!WALK_SKIPPED_KEYS.has(key)) {
1821
+ collectReferences(child, removed, excluded, references);
1822
+ }
1823
+ }
1824
+ }
1825
+ function referencedNames(node, removed) {
1826
+ const references = new Set;
1827
+ collectReferences(node, removed, new Set, references);
1828
+ return references;
1829
+ }
1830
+ function collectPatternNames(node, names) {
1831
+ if (!node) {
1832
+ return;
1833
+ }
1834
+ if (node.type === "Identifier") {
1835
+ names.push(node.name);
1836
+ } else if (node.type === "AssignmentPattern") {
1837
+ collectPatternNames(node.left, names);
1838
+ } else if (node.type === "RestElement") {
1839
+ collectPatternNames(node.argument, names);
1840
+ } else if (node.type === "ArrayPattern") {
1841
+ for (const element of node.elements) {
1842
+ collectPatternNames(element, names);
1843
+ }
1844
+ } else if (node.type === "ObjectPattern") {
1845
+ for (const property of node.properties) {
1846
+ collectPatternNames(property.type === "Property" ? property.value : property, names);
1847
+ }
1848
+ }
1849
+ }
1850
+ function moduleUnits(program) {
1851
+ const units = [];
1852
+ for (const statement of program.body) {
1853
+ if (statement.type === "ImportDeclaration") {
1854
+ continue;
1855
+ }
1856
+ const exported = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration";
1857
+ const declaration = exported ? statement.declaration : statement;
1858
+ if (declaration?.type === "VariableDeclaration") {
1859
+ for (const declarator of declaration.declarations) {
1860
+ const names = [];
1861
+ collectPatternNames(declarator.id, names);
1862
+ units.push({ declaration, exported, names, node: declarator });
1863
+ }
1864
+ continue;
1865
+ }
1866
+ const id = declaration?.type === "FunctionDeclaration" ? declaration.id : null;
1867
+ units.push({
1868
+ declaration: null,
1869
+ exported,
1870
+ names: id ? [id.name] : [],
1871
+ node: statement
1872
+ });
1873
+ }
1874
+ return units;
1875
+ }
1876
+ function collectModuleReferences(program, removed) {
1877
+ const names = new Set;
1878
+ const units = moduleUnits(program).map((unit) => {
1879
+ const references = new Set;
1880
+ collectReferences(unit.node, removed, new Set, references);
1881
+ for (const name of references) {
1882
+ names.add(name);
1883
+ }
1884
+ return { ...unit, references };
1885
+ });
1886
+ return { names, units };
1887
+ }
1888
+ function referencedOutsideDeclaration(references, name) {
1889
+ return references.units.some((unit) => !unit.names.includes(name) && unit.references.has(name));
1890
+ }
1891
+ function isSideEffectFree(value) {
1892
+ if (!value) {
1893
+ return true;
1894
+ }
1895
+ const node = unwrapTSExpression(value);
1896
+ switch (node.type) {
1897
+ case "ArrowFunctionExpression":
1898
+ case "FunctionExpression":
1899
+ case "Identifier":
1900
+ case "Literal":
1901
+ return true;
1902
+ case "TemplateLiteral":
1903
+ return node.expressions.every(isSideEffectFree);
1904
+ case "ArrayExpression":
1905
+ return node.elements.every((element) => element === null || element.type !== "SpreadElement" && isSideEffectFree(element));
1906
+ case "ObjectExpression":
1907
+ return node.properties.every((property) => property.type === "Property" && (!property.computed || isSideEffectFree(property.key)) && isSideEffectFree(property.value));
1908
+ default:
1909
+ return false;
1910
+ }
1911
+ }
1912
+ function isPatternSideEffectFree(node) {
1913
+ if (!node) {
1914
+ return true;
1915
+ }
1916
+ switch (node.type) {
1917
+ case "AssignmentPattern":
1918
+ return isPatternSideEffectFree(node.left) && isSideEffectFree(node.right);
1919
+ case "RestElement":
1920
+ return isPatternSideEffectFree(node.argument);
1921
+ case "ArrayPattern":
1922
+ return node.elements.every(isPatternSideEffectFree);
1923
+ case "ObjectPattern":
1924
+ return node.properties.every((property) => property.type === "Property" ? (!property.computed || isSideEffectFree(property.key)) && isPatternSideEffectFree(property.value) : isPatternSideEffectFree(property));
1925
+ default:
1926
+ return true;
1927
+ }
1928
+ }
1929
+ function isDeadBinding(unit, after, state) {
1930
+ if (unit.exported || unit.names.length === 0 || unit.names.some((name) => state.retained.has(name) || referencedOutsideDeclaration(after, name))) {
1931
+ return false;
1932
+ }
1933
+ if (unit.names.some((name) => state.forced.has(name))) {
1934
+ return true;
1935
+ }
1936
+ return unit.names.some((name) => referencedOutsideDeclaration(state.before, name)) && (unit.declaration === null || unit.node.type === "VariableDeclarator" && isPatternSideEffectFree(unit.node.id) && isSideEffectFree(unit.node.init));
1937
+ }
1938
+ function removeDeclarator(module, declaration, node) {
1939
+ const declarators = declaration.declarations.filter((declarator) => declarator === node || !isRemoved(declarator, module.removed));
1940
+ if (declarators.length === 1) {
1941
+ removeRange(module, declaration.start, declaration.end);
1942
+ return;
1943
+ }
1944
+ const index = declarators.indexOf(node);
1945
+ const next = declarators[index + 1];
1946
+ if (next) {
1947
+ removeRange(module, node.start, next.start);
1948
+ return;
1949
+ }
1950
+ const previous = declarators[index - 1];
1951
+ if (previous) {
1952
+ removeRange(module, previous.end, node.end);
1953
+ }
1954
+ }
1955
+ function removeUnit(unit, state) {
1956
+ const { declaration, node } = unit;
1957
+ if (!declaration || node.type !== "VariableDeclarator") {
1958
+ removeRange(state, node.start, node.end);
1959
+ return;
1960
+ }
1961
+ removeDeclarator(state, declaration, node);
1962
+ }
1963
+ function pruneDeadBindings(state) {
1964
+ for (;; ) {
1965
+ const after = collectModuleReferences(state.program, state.removed);
1966
+ const dead = after.units.filter((unit) => !isRemoved(unit.node, state.removed) && isDeadBinding(unit, after, state));
1967
+ if (dead.length === 0) {
1968
+ return;
1969
+ }
1970
+ for (const unit of dead) {
1971
+ removeUnit(unit, state);
1972
+ }
1973
+ }
1974
+ }
1975
+ function preserveImportSideEffect(module, declaration) {
1976
+ replaceRange(module, declaration.start, declaration.end, `import ${module.source.slice(declaration.source.start, declaration.source.end)};`);
1977
+ }
1978
+ function removeUnusedSpecifiers(module, declaration, references) {
1979
+ const code = module.source.original;
1980
+ const removedSpecifiers = declaration.specifiers.filter((specifier) => !references.has(specifier.local.name));
1981
+ for (const specifier of removedSpecifiers) {
1982
+ let removeStart = specifier.start;
1983
+ let removeEnd = specifier.end;
1984
+ while (removeEnd < code.length && (code[removeEnd] === "," || code[removeEnd] === " ")) {
1985
+ removeEnd += 1;
1986
+ }
1987
+ if (!code.slice(specifier.end, removeEnd).includes(",")) {
1988
+ while (removeStart > 0 && (code[removeStart - 1] === " " || code[removeStart - 1] === ",")) {
1989
+ removeStart -= 1;
1990
+ }
1991
+ }
1992
+ removeRange(module, removeStart, removeEnd);
1993
+ }
1994
+ }
1995
+ function pruneDeadImports(state) {
1996
+ const references = collectModuleReferences(state.program, state.removed).names.union(state.retained);
1997
+ const { body } = state.program;
1998
+ for (let index = body.length - 1;index >= 0; index -= 1) {
1999
+ const statement = body[index];
2000
+ if (statement?.type !== "ImportDeclaration" || isRemoved(statement, state.removed)) {
2001
+ continue;
2002
+ }
2003
+ const declaration = statement;
2004
+ if (declaration.specifiers.length === 0) {
2005
+ continue;
2006
+ }
2007
+ const usedCount = declaration.specifiers.filter((specifier) => references.has(specifier.local.name)).length;
2008
+ if (usedCount === 0) {
2009
+ const typeOnly = declaration.importKind === "type" || declaration.specifiers.every((specifier) => specifier.type === "ImportSpecifier" && specifier.importKind === "type");
2010
+ const wasUsedBeforeTransform = declaration.specifiers.some((specifier) => state.before.names.has(specifier.local.name));
2011
+ if (typeOnly || wasUsedBeforeTransform) {
2012
+ removeRange(state, declaration.start, declaration.end);
2013
+ } else {
2014
+ preserveImportSideEffect(state, declaration);
2015
+ }
2016
+ } else if (usedCount < declaration.specifiers.length) {
2017
+ removeUnusedSpecifiers(state, declaration, references);
2018
+ }
2019
+ }
2020
+ }
2021
+ function pruneOrphanedCode(module, forced, retained) {
2022
+ const state = {
2023
+ before: collectModuleReferences(module.program, []),
2024
+ forced,
2025
+ program: module.program,
2026
+ removed: module.removed,
2027
+ retained,
2028
+ source: module.source
2029
+ };
2030
+ pruneDeadBindings(state);
2031
+ pruneDeadImports(state);
2032
+ }
1632
2033
  // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/aliases.js
1633
2034
  var ALIAS_GROUPS = {
1634
2035
  Expression: [
@@ -1785,74 +2186,6 @@ var ALIAS_GROUPS = {
1785
2186
  };
1786
2187
  var ALIAS_NAMES = Object.keys(ALIAS_GROUPS);
1787
2188
 
1788
- // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/context.js
1789
- class WalkContext {
1790
- _ancestors = [];
1791
- _node = null;
1792
- _key = null;
1793
- _list = null;
1794
- _frame = null;
1795
- _skip = false;
1796
- _stopped = false;
1797
- _removed = false;
1798
- _replacement = null;
1799
- state;
1800
- get node() {
1801
- return this._node;
1802
- }
1803
- get parent() {
1804
- const a = this._ancestors;
1805
- return a.length === 0 ? null : a[a.length - 1];
1806
- }
1807
- get key() {
1808
- return this._key;
1809
- }
1810
- get index() {
1811
- return this._list === null ? null : this._frame.i;
1812
- }
1813
- ancestors() {
1814
- return [...this._ancestors];
1815
- }
1816
- skip() {
1817
- this._skip = true;
1818
- }
1819
- stop() {
1820
- this._stopped = true;
1821
- }
1822
- replace(node) {
1823
- if (node === null || typeof node !== "object" || typeof node.type !== "string") {
1824
- throw new TypeError("replace: expected an AST node");
1825
- }
1826
- if (this.parent === null) {
1827
- throw new TypeError("replace: cannot replace the walk root");
1828
- }
1829
- if (node.start === 0 && node.end === 0) {
1830
- node.start = this.node.start;
1831
- node.end = this.node.end;
1832
- }
1833
- this._replacement = node;
1834
- }
1835
- remove() {
1836
- if (this.parent === null) {
1837
- throw new TypeError("remove: cannot remove the walk root");
1838
- }
1839
- this._removed = true;
1840
- }
1841
- insertBefore(node) {
1842
- this.#insert(node, 0);
1843
- this._frame.i++;
1844
- }
1845
- insertAfter(node) {
1846
- this.#insert(node, 1);
1847
- }
1848
- #insert(node, offset) {
1849
- if (this._list === null) {
1850
- throw new TypeError("insertBefore/insertAfter require a node in an array field");
1851
- }
1852
- this._list.splice(this._frame.i + offset, 0, node);
1853
- }
1854
- }
1855
-
1856
2189
  // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/generated.js
1857
2190
  var KEYS = Object.create(null);
1858
2191
  function ck(type, keys) {
@@ -2225,26 +2558,94 @@ var TYPES = [
2225
2558
  ];
2226
2559
  var NODE_TYPES = [...new Set(TYPES)];
2227
2560
 
2228
- // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/walk.js
2229
- function createDispatch(visitors) {
2230
- let enter = null;
2231
- let leave = null;
2232
- const concrete = new Map;
2233
- const add = (type, handler) => {
2234
- const hooks = typeof handler === "function" ? { enter: handler } : handler;
2235
- let entry = concrete.get(type);
2236
- if (entry === undefined) {
2237
- entry = { enter: [], leave: [] };
2238
- concrete.set(type, entry);
2239
- }
2240
- if (hooks.enter)
2241
- entry.enter.push(hooks.enter);
2242
- if (hooks.leave)
2243
- entry.leave.unshift(hooks.leave);
2244
- };
2245
- for (const [name, value] of Object.entries(visitors)) {
2246
- if (value == null)
2247
- continue;
2561
+ // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/context.js
2562
+ class WalkContext {
2563
+ _ancestors = [];
2564
+ _node = null;
2565
+ _key = null;
2566
+ _list = null;
2567
+ _frame = null;
2568
+ _skip = false;
2569
+ _stopped = false;
2570
+ _removed = false;
2571
+ _replacement = null;
2572
+ state;
2573
+ get node() {
2574
+ return this._node;
2575
+ }
2576
+ get parent() {
2577
+ const a = this._ancestors;
2578
+ return a.length === 0 ? null : a[a.length - 1];
2579
+ }
2580
+ get key() {
2581
+ return this._key;
2582
+ }
2583
+ get index() {
2584
+ return this._list === null ? null : this._frame.i;
2585
+ }
2586
+ ancestors() {
2587
+ return [...this._ancestors];
2588
+ }
2589
+ skip() {
2590
+ this._skip = true;
2591
+ }
2592
+ stop() {
2593
+ this._stopped = true;
2594
+ }
2595
+ replace(node) {
2596
+ if (node === null || typeof node !== "object" || typeof node.type !== "string") {
2597
+ throw new TypeError("replace: expected an AST node");
2598
+ }
2599
+ if (this.parent === null) {
2600
+ throw new TypeError("replace: cannot replace the walk root");
2601
+ }
2602
+ if (node.start === 0 && node.end === 0) {
2603
+ node.start = this.node.start;
2604
+ node.end = this.node.end;
2605
+ }
2606
+ this._replacement = node;
2607
+ }
2608
+ remove() {
2609
+ if (this.parent === null) {
2610
+ throw new TypeError("remove: cannot remove the walk root");
2611
+ }
2612
+ this._removed = true;
2613
+ }
2614
+ insertBefore(node) {
2615
+ this.#insert(node, 0);
2616
+ this._frame.i++;
2617
+ }
2618
+ insertAfter(node) {
2619
+ this.#insert(node, 1);
2620
+ }
2621
+ #insert(node, offset) {
2622
+ if (this._list === null) {
2623
+ throw new TypeError("insertBefore/insertAfter require a node in an array field");
2624
+ }
2625
+ this._list.splice(this._frame.i + offset, 0, node);
2626
+ }
2627
+ }
2628
+
2629
+ // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/walk.js
2630
+ function createDispatch(visitors) {
2631
+ let enter = null;
2632
+ let leave = null;
2633
+ const concrete = new Map;
2634
+ const add = (type, handler) => {
2635
+ const hooks = typeof handler === "function" ? { enter: handler } : handler;
2636
+ let entry = concrete.get(type);
2637
+ if (entry === undefined) {
2638
+ entry = { enter: [], leave: [] };
2639
+ concrete.set(type, entry);
2640
+ }
2641
+ if (hooks.enter)
2642
+ entry.enter.push(hooks.enter);
2643
+ if (hooks.leave)
2644
+ entry.leave.unshift(hooks.leave);
2645
+ };
2646
+ for (const [name, value] of Object.entries(visitors)) {
2647
+ if (value == null)
2648
+ continue;
2248
2649
  if (name === "enter")
2249
2650
  enter = value;
2250
2651
  else if (name === "leave")
@@ -2362,53 +2763,178 @@ function _walk(root, visitors, state, ctx) {
2362
2763
  return true;
2363
2764
  })(root, null, null, null);
2364
2765
  }
2365
- // src/shared/parser.ts
2366
- import { parse } from "yuku-parser";
2367
- function parseSource(code, lang) {
2368
- return parse(code, { lang, sourceType: "module" });
2369
- }
2370
2766
 
2767
+ // ../../node_modules/.bun/yuku-ast@0.12.0/node_modules/yuku-ast/dist/utils.js
2768
+ function literalValue(node) {
2769
+ if (node?.type !== "Literal")
2770
+ return;
2771
+ if ("bigint" in node)
2772
+ return BigInt(node.bigint);
2773
+ return node.value;
2774
+ }
2775
+ var WRAPPERS = new Set([
2776
+ "ParenthesizedExpression",
2777
+ "TSAsExpression",
2778
+ "TSSatisfiesExpression",
2779
+ "TSNonNullExpression",
2780
+ "TSTypeAssertion"
2781
+ ]);
2371
2782
  // src/plugin/binding-scope.ts
2783
+ function fluentChain(call, ancestors) {
2784
+ let chain = call;
2785
+ for (const parent of ancestors.toReversed()) {
2786
+ if (parent === chain) {
2787
+ continue;
2788
+ }
2789
+ if (parent.type === "MemberExpression" && parent.object === chain || parent.type === "CallExpression" && parent.callee === chain || unwrapTSExpression(parent) === chain) {
2790
+ chain = parent;
2791
+ } else {
2792
+ break;
2793
+ }
2794
+ }
2795
+ return unwrapTSExpression(chain);
2796
+ }
2797
+ function lexicalBindingScope(ancestors) {
2798
+ return ancestors.findLast((ancestor) => [
2799
+ "Program",
2800
+ "BlockStatement",
2801
+ "SwitchStatement",
2802
+ "ForStatement",
2803
+ "ForInStatement",
2804
+ "ForOfStatement",
2805
+ "StaticBlock"
2806
+ ].includes(ancestor.type));
2807
+ }
2808
+ function varBindingScope(ancestors) {
2809
+ return ancestors.findLast((ancestor, index) => {
2810
+ if (ancestor.type === "Program" || ancestor.type === "StaticBlock") {
2811
+ return true;
2812
+ }
2813
+ const parent = ancestors[index - 1];
2814
+ return ancestor.type === "BlockStatement" && !!parent && ["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"].includes(parent.type);
2815
+ });
2816
+ }
2817
+
2818
+ class FactoryBindings extends Set {
2819
+ aliases = new Map;
2820
+ namespaces;
2821
+ constructor(program, named, namespaces) {
2822
+ super(named);
2823
+ this.namespaces = namespaces;
2824
+ if (!this.hasImports) {
2825
+ return;
2826
+ }
2827
+ walk(program, {
2828
+ VariableDeclarator: (node, context) => {
2829
+ const ancestors = context.ancestors();
2830
+ const declaration = ancestors.at(-1);
2831
+ const kind = declaration?.type === "VariableDeclaration" ? declaration.kind : undefined;
2832
+ const scope = kind === "var" ? varBindingScope(ancestors) : lexicalBindingScope(ancestors);
2833
+ if (node.id.type === "Identifier" && node.init && scope) {
2834
+ const aliases = this.aliases.get(node.id.name) ?? [];
2835
+ aliases.push({
2836
+ ancestors,
2837
+ immutable: kind === "const",
2838
+ initializer: node.init,
2839
+ name: node.id.name,
2840
+ scope
2841
+ });
2842
+ this.aliases.set(node.id.name, aliases);
2843
+ }
2844
+ }
2845
+ });
2846
+ }
2847
+ get hasImports() {
2848
+ return this.size > 0 || this.namespaces.size > 0;
2849
+ }
2850
+ factoryName(expression, ancestors) {
2851
+ return this.size === 0 ? undefined : this.resolve(expression, ancestors, this, new Set);
2852
+ }
2853
+ namespaceName(expression, ancestors) {
2854
+ return this.namespaces.size === 0 ? undefined : this.resolve(expression, ancestors, this.namespaces, new Set);
2855
+ }
2856
+ resolve(expression, ancestors, imports, seen) {
2857
+ const node = unwrapTSExpression(expression);
2858
+ if (node.type !== "Identifier") {
2859
+ return;
2860
+ }
2861
+ if (imports.has(node.name) && !hasShadowingDeclaration(node.name, ancestors)) {
2862
+ return node.name;
2863
+ }
2864
+ let match;
2865
+ let sameScope = [];
2866
+ let scopeIndex = -1;
2867
+ const aliases = this.aliases.get(node.name);
2868
+ if (!aliases) {
2869
+ return;
2870
+ }
2871
+ for (const alias of aliases) {
2872
+ const index = ancestors.lastIndexOf(alias.scope);
2873
+ if (index > scopeIndex) {
2874
+ match = alias;
2875
+ scopeIndex = index;
2876
+ sameScope = [alias];
2877
+ } else if (index === scopeIndex && index >= 0) {
2878
+ sameScope.push(alias);
2879
+ }
2880
+ }
2881
+ if (!match || seen.has(match) || hasShadowingDeclaration(node.name, ancestors.slice(scopeIndex + 1))) {
2882
+ return;
2883
+ }
2884
+ if (sameScope.length > 1) {
2885
+ const factory = sameScope.some((alias) => !seen.has(alias) && this.resolve(alias.initializer, alias.ancestors, imports, new Set([...seen, alias])) !== undefined);
2886
+ if (factory) {
2887
+ throw new Error("[furin] Route factory aliases are ambiguous in the same scope.");
2888
+ }
2889
+ return;
2890
+ }
2891
+ seen.add(match);
2892
+ const name = this.resolve(match.initializer, match.ancestors, imports, seen);
2893
+ if (name && !match.immutable) {
2894
+ throw new Error("[furin] Route factory aliases must be immutable.");
2895
+ }
2896
+ return name;
2897
+ }
2898
+ }
2372
2899
  function bindingPatternHasName(pattern, name) {
2373
- if (!(pattern && typeof pattern === "object")) {
2900
+ if (!pattern) {
2374
2901
  return false;
2375
2902
  }
2376
- const node = pattern;
2377
- if (node.type === "Identifier") {
2378
- return node.name === name;
2903
+ if (pattern.type === "Identifier") {
2904
+ return pattern.name === name;
2379
2905
  }
2380
- if (node.type === "AssignmentPattern") {
2381
- return bindingPatternHasName(node.left, name);
2906
+ if (pattern.type === "AssignmentPattern") {
2907
+ return bindingPatternHasName(pattern.left, name);
2382
2908
  }
2383
- if (node.type === "RestElement") {
2384
- return bindingPatternHasName(node.argument, name);
2909
+ if (pattern.type === "RestElement") {
2910
+ return bindingPatternHasName(pattern.argument, name);
2385
2911
  }
2386
- if (node.type === "ArrayPattern") {
2387
- return Array.isArray(node.elements) && node.elements.some((element) => bindingPatternHasName(element, name));
2912
+ if (pattern.type === "ArrayPattern") {
2913
+ return pattern.elements.some((element) => bindingPatternHasName(element, name));
2388
2914
  }
2389
- if (node.type === "ObjectPattern") {
2390
- return Array.isArray(node.properties) && node.properties.some((property) => {
2391
- if (!(property && typeof property === "object")) {
2392
- return false;
2393
- }
2394
- const propertyNode = property;
2395
- return bindingPatternHasName(propertyNode.type === "Property" ? propertyNode.value : propertyNode.argument, name);
2396
- });
2915
+ if (pattern.type === "ObjectPattern") {
2916
+ return pattern.properties.some((property) => bindingPatternHasName(property.type === "Property" ? property.value : property.argument, name));
2397
2917
  }
2398
- if (node.type === "TSParameterProperty") {
2399
- return bindingPatternHasName(node.parameter, name);
2918
+ if (pattern.type === "TSParameterProperty") {
2919
+ return bindingPatternHasName(pattern.parameter, name);
2400
2920
  }
2401
2921
  return false;
2402
2922
  }
2403
2923
  function declarationHasName(node, name) {
2404
- if (node.type === "VariableDeclaration" && Array.isArray(node.declarations)) {
2405
- return node.declarations.some((declaration) => declaration && typeof declaration === "object" ? bindingPatternHasName(declaration.id, name) : false);
2924
+ if (node.type === "VariableDeclaration") {
2925
+ return node.declarations.some((declaration) => bindingPatternHasName(declaration.id, name));
2406
2926
  }
2407
2927
  if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
2408
2928
  return bindingPatternHasName(node.id, name);
2409
2929
  }
2410
2930
  return false;
2411
2931
  }
2932
+ var NESTED_VAR_SCOPES = new Set([
2933
+ "FunctionDeclaration",
2934
+ "FunctionExpression",
2935
+ "ArrowFunctionExpression",
2936
+ "StaticBlock"
2937
+ ]);
2412
2938
  function functionBodyHasVarName(value, name, root) {
2413
2939
  if (!value || typeof value !== "object") {
2414
2940
  return false;
@@ -2416,722 +2942,636 @@ function functionBodyHasVarName(value, name, root) {
2416
2942
  if (Array.isArray(value)) {
2417
2943
  return value.some((entry) => functionBodyHasVarName(entry, name, false));
2418
2944
  }
2419
- const node = value;
2420
- if (!root && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "StaticBlock")) {
2421
- return false;
2422
- }
2423
- if (node.type === "VariableDeclaration" && node.kind === "var" && Array.isArray(node.declarations) && node.declarations.some((declaration) => declaration && typeof declaration === "object" ? bindingPatternHasName(declaration.id, name) : false)) {
2424
- return true;
2945
+ if (isNode(value)) {
2946
+ if (!root && NESTED_VAR_SCOPES.has(value.type)) {
2947
+ return false;
2948
+ }
2949
+ if (value.type === "VariableDeclaration" && value.kind === "var" && value.declarations.some((declaration) => bindingPatternHasName(declaration.id, name))) {
2950
+ return true;
2951
+ }
2425
2952
  }
2426
- return Object.values(node).some((entry) => functionBodyHasVarName(entry, name, false));
2953
+ return Object.values(value).some((entry) => functionBodyHasVarName(entry, name, false));
2427
2954
  }
2428
2955
  function functionScopeHasName(scope, name) {
2429
2956
  if (scope.type !== "FunctionDeclaration" && scope.type !== "FunctionExpression" && scope.type !== "ArrowFunctionExpression") {
2430
2957
  return false;
2431
2958
  }
2432
- return Array.isArray(scope.params) && scope.params.some((parameter) => bindingPatternHasName(parameter, name)) || scope.type === "FunctionExpression" && bindingPatternHasName(scope.id, name) || functionBodyHasVarName(scope.body, name, true);
2959
+ return scope.params.some((parameter) => bindingPatternHasName(parameter, name)) || scope.type === "FunctionExpression" && bindingPatternHasName(scope.id, name) || functionBodyHasVarName(scope.body, name, true);
2433
2960
  }
2434
2961
  function blockScopeHasName(scope, name) {
2435
- return scope.type === "BlockStatement" && Array.isArray(scope.body) && scope.body.some((statement) => statement && typeof statement === "object" ? declarationHasName(statement, name) : false);
2962
+ return (scope.type === "BlockStatement" || scope.type === "StaticBlock") && scope.body.some((statement) => declarationHasName(statement, name));
2436
2963
  }
2437
2964
  function loopScopeHasName(scope, name) {
2438
- const declaration = scope.type === "ForStatement" ? scope.init : scope.left;
2439
- return (scope.type === "ForStatement" || scope.type === "ForInStatement" || scope.type === "ForOfStatement") && !!declaration && typeof declaration === "object" && declarationHasName(declaration, name);
2965
+ if (scope.type === "ForStatement") {
2966
+ return !!scope.init && declarationHasName(scope.init, name);
2967
+ }
2968
+ if (scope.type === "ForInStatement" || scope.type === "ForOfStatement") {
2969
+ return declarationHasName(scope.left, name);
2970
+ }
2971
+ return false;
2440
2972
  }
2441
2973
  function switchScopeHasName(scope, name) {
2442
- return scope.type === "SwitchStatement" && Array.isArray(scope.cases) && scope.cases.some((switchCase) => switchCase && typeof switchCase === "object" && Array.isArray(switchCase.consequent) && switchCase.consequent.some((statement) => statement && typeof statement === "object" && declarationHasName(statement, name)));
2974
+ return scope.type === "SwitchStatement" && scope.cases.some((switchCase) => switchCase.consequent.some((statement) => declarationHasName(statement, name)));
2443
2975
  }
2444
2976
  function hasShadowingDeclaration(name, ancestors) {
2445
- return ancestors.some((scope) => functionScopeHasName(scope, name) || scope.type === "CatchClause" && bindingPatternHasName(scope.param, name) || blockScopeHasName(scope, name) || loopScopeHasName(scope, name) || switchScopeHasName(scope, name));
2977
+ return ancestors.some((scope) => functionScopeHasName(scope, name) || scope.type === "ClassExpression" && bindingPatternHasName(scope.id, name) || scope.type === "CatchClause" && bindingPatternHasName(scope.param, name) || scope.type === "StaticBlock" && functionBodyHasVarName(scope.body, name, true) || blockScopeHasName(scope, name) || loopScopeHasName(scope, name) || switchScopeHasName(scope, name));
2446
2978
  }
2447
2979
 
2448
- // src/shared/utils/ast-walk.ts
2449
- var SKIP_KEYS = new Set(["type", "start", "end", "comments"]);
2450
- function isAstNode(value) {
2451
- if (!value || typeof value !== "object" || Array.isArray(value)) {
2452
- return false;
2980
+ // src/plugin/hmr-dependencies.ts
2981
+ import { readFileSync as readFileSync2 } from "fs";
2982
+ import { dirname as dirname2, isAbsolute, resolve } from "path";
2983
+ function hmrDependencySignature(imports, filename) {
2984
+ const routePath = resolve(filename);
2985
+ const visited = new Set;
2986
+ const hash = new Bun.CryptoHasher("sha256");
2987
+ const visit = (specifier, importer) => {
2988
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
2989
+ return true;
2990
+ }
2991
+ const path = Bun.resolveSync(specifier, dirname2(importer));
2992
+ if (path === routePath) {
2993
+ return false;
2994
+ }
2995
+ hash.update(JSON.stringify([specifier, path]));
2996
+ if (!isAbsolute(path) || path.replaceAll("\\", "/").includes("/node_modules/") || visited.has(path)) {
2997
+ return true;
2998
+ }
2999
+ visited.add(path);
3000
+ const source = readFileSync2(path, "utf8");
3001
+ hash.update(source);
3002
+ if (SCRIPT_FILE_FILTER.test(path)) {
3003
+ const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(path) });
3004
+ for (const dependency of transpiler.scanImports(source)) {
3005
+ if (!visit(dependency.path, path)) {
3006
+ return false;
3007
+ }
3008
+ }
3009
+ }
3010
+ return true;
3011
+ };
3012
+ try {
3013
+ for (const specifier of imports) {
3014
+ if (!visit(specifier, routePath)) {
3015
+ return;
3016
+ }
3017
+ }
3018
+ return hash.digest("hex");
3019
+ } catch {}
3020
+ }
3021
+
3022
+ // src/plugin/module-bindings.ts
3023
+ function importedName(specifier) {
3024
+ if (specifier.type !== "ImportSpecifier") {
3025
+ return null;
2453
3026
  }
2454
- const candidate = value;
2455
- return typeof candidate.type === "string";
3027
+ const { imported } = specifier;
3028
+ return imported.type === "Identifier" ? imported.name : imported.value;
3029
+ }
3030
+ function localName(specifier) {
3031
+ return specifier.local.name;
3032
+ }
3033
+ function unwrapped(node) {
3034
+ return node ? unwrapTSExpression(node) : null;
2456
3035
  }
2457
- function walkAST(node, visitor) {
2458
- if (!node || typeof node !== "object") {
3036
+ function collectBindingNames(pattern, names) {
3037
+ const node = unwrapped(pattern);
3038
+ if (!node) {
2459
3039
  return;
2460
3040
  }
2461
- if (Array.isArray(node)) {
2462
- for (const child of node) {
2463
- walkAST(child, visitor);
2464
- }
3041
+ if (node.type === "Identifier") {
3042
+ names.push(node.name);
2465
3043
  return;
2466
3044
  }
2467
- if (!isAstNode(node)) {
3045
+ if (node.type === "AssignmentPattern") {
3046
+ collectBindingNames(node.left, names);
2468
3047
  return;
2469
3048
  }
2470
- const n = node;
2471
- visitor(n);
2472
- for (const key of Object.keys(n)) {
2473
- if (SKIP_KEYS.has(key)) {
2474
- continue;
2475
- }
2476
- walkAST(n[key], visitor);
2477
- }
2478
- }
2479
-
2480
- // src/plugin/dead-code-elimination.ts
2481
- var TYPE_SCOPE_NODES = new Set([
2482
- "TSTypeAnnotation",
2483
- "TSTypeParameterDeclaration",
2484
- "TSTypeParameterInstantiation",
2485
- "TSInterfaceDeclaration",
2486
- "TSTypeAliasDeclaration",
2487
- "TSTypePredicate",
2488
- "TSClassImplements",
2489
- "TSExpressionWithTypeArguments"
2490
- ]);
2491
- function markTypeDescendants(node, excluded) {
2492
- if (!node || typeof node !== "object") {
3049
+ if (node.type === "RestElement") {
3050
+ collectBindingNames(node.argument, names);
2493
3051
  return;
2494
3052
  }
2495
- if (Array.isArray(node)) {
2496
- for (const item of node) {
2497
- markTypeDescendants(item, excluded);
3053
+ if (node.type === "ArrayPattern" && Array.isArray(node.elements)) {
3054
+ for (const element of node.elements) {
3055
+ collectBindingNames(element, names);
2498
3056
  }
2499
3057
  return;
2500
3058
  }
2501
- const astNode = node;
2502
- if (astNode.type === "Identifier" || astNode.type === "JSXIdentifier") {
2503
- excluded.add(astNode);
2504
- }
2505
- for (const key of Object.keys(astNode)) {
2506
- if (key === "type" || key === "start" || key === "end") {
2507
- continue;
3059
+ if (node.type === "ObjectPattern" && Array.isArray(node.properties)) {
3060
+ for (const property of node.properties) {
3061
+ collectBindingNames(property.type === "Property" ? property.value : property.argument, names);
2508
3062
  }
2509
- markTypeDescendants(astNode[key], excluded);
2510
3063
  }
2511
3064
  }
2512
- function excludeTypePositionIdentifiers(node, excluded) {
2513
- if (TYPE_SCOPE_NODES.has(node.type)) {
2514
- markTypeDescendants(node, excluded);
3065
+ function collectDeclarationBindings(declaration, declarations) {
3066
+ if (declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") {
3067
+ const identifier = unwrapped(declaration.id);
3068
+ if (identifier?.type === "Identifier") {
3069
+ declarations.set(identifier.name, declaration);
3070
+ }
2515
3071
  return;
2516
3072
  }
2517
- if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSTypeAssertion") {
2518
- markTypeDescendants(node.typeAnnotation, excluded);
3073
+ if (declaration?.type !== "VariableDeclaration" || !Array.isArray(declaration.declarations)) {
3074
+ return;
2519
3075
  }
2520
- }
2521
- function collectReferencedNames(program) {
2522
- const refs = new Set;
2523
- const excluded = new Set;
2524
- for (const statement of program.body) {
2525
- if (statement.type === "ImportDeclaration") {
2526
- continue;
3076
+ for (const item of declaration.declarations) {
3077
+ const names = [];
3078
+ collectBindingNames(item.id, names);
3079
+ for (const name of names) {
3080
+ declarations.set(name, item);
2527
3081
  }
2528
- walkAST(statement, (node) => {
2529
- if (node.type === "Property" && !node.computed) {
2530
- excluded.add(node.key);
2531
- }
2532
- if (node.type === "MemberExpression" && !node.computed) {
2533
- excluded.add(node.property);
2534
- }
2535
- if (node.type === "JSXAttribute") {
2536
- excluded.add(node.name);
2537
- }
2538
- if (node.type === "JSXMemberExpression") {
2539
- excluded.add(node.property);
2540
- }
2541
- excludeTypePositionIdentifiers(node, excluded);
2542
- });
2543
3082
  }
3083
+ }
3084
+ function collectModuleBindings(program) {
3085
+ const declarations = new Map;
3086
+ const imports = new Map;
2544
3087
  for (const statement of program.body) {
2545
- if (statement.type === "ImportDeclaration") {
3088
+ if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
3089
+ for (const specifier of statement.specifiers) {
3090
+ const local = localName(specifier);
3091
+ if (local) {
3092
+ imports.set(local, statement);
3093
+ }
3094
+ }
2546
3095
  continue;
2547
3096
  }
2548
- walkAST(statement, (node) => {
2549
- if (excluded.has(node)) {
2550
- return;
2551
- }
2552
- if ((node.type === "Identifier" || node.type === "JSXIdentifier") && typeof node.name === "string") {
2553
- refs.add(node.name);
2554
- }
2555
- });
3097
+ const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? unwrapped(statement.declaration) : statement;
3098
+ collectDeclarationBindings(declaration, declarations);
2556
3099
  }
2557
- return refs;
2558
- }
2559
- function preserveImportSideEffect(transformed, code, declaration) {
2560
- transformed.overwrite(declaration.start, declaration.end, `import ${code.slice(declaration.source.start, declaration.source.end)};`);
3100
+ return { declarations, imports };
2561
3101
  }
2562
- function removeEntireImport(transformed, code, declaration) {
2563
- let removeEnd = declaration.end;
2564
- while (removeEnd < code.length && (code[removeEnd] === `
2565
- ` || code[removeEnd] === "\r")) {
2566
- removeEnd += 1;
3102
+ function isBindingIdentifier(identifier, pattern) {
3103
+ const node = unwrapped(pattern);
3104
+ if (!node) {
3105
+ return false;
2567
3106
  }
2568
- transformed.remove(declaration.start, removeEnd);
2569
- }
2570
- function removeUnusedSpecifiers(transformed, code, declaration, refs) {
2571
- const removedSpecifiers = declaration.specifiers.filter((specifier) => !refs.has(specifier.local.name));
2572
- for (const specifier of removedSpecifiers) {
2573
- let removeStart = specifier.start;
2574
- let removeEnd = specifier.end;
2575
- while (removeEnd < code.length && (code[removeEnd] === "," || code[removeEnd] === " ")) {
2576
- removeEnd += 1;
2577
- }
2578
- if (!code.slice(specifier.end, removeEnd).includes(",")) {
2579
- while (removeStart > 0 && (code[removeStart - 1] === " " || code[removeStart - 1] === ",")) {
2580
- removeStart -= 1;
2581
- }
2582
- }
2583
- transformed.remove(removeStart, removeEnd);
3107
+ if (node.type === "Identifier") {
3108
+ return node.start === identifier.start && node.end === identifier.end;
3109
+ }
3110
+ if (node.type === "AssignmentPattern") {
3111
+ return isBindingIdentifier(identifier, node.left);
3112
+ }
3113
+ if (node.type === "RestElement") {
3114
+ return isBindingIdentifier(identifier, node.argument);
3115
+ }
3116
+ if (node.type === "ArrayPattern" && Array.isArray(node.elements)) {
3117
+ return node.elements.some((element) => isBindingIdentifier(identifier, element));
3118
+ }
3119
+ if (node.type === "ObjectPattern" && Array.isArray(node.properties)) {
3120
+ return node.properties.some((property) => isBindingIdentifier(identifier, property.type === "Property" ? property.value : property.argument));
2584
3121
  }
3122
+ return false;
2585
3123
  }
2586
- function deadCodeElimination(transformed, originalCode, lang) {
2587
- const code = transformed.toString();
2588
- const { program, diagnostics } = parseSource(code, lang);
2589
- const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
2590
- if (firstError) {
2591
- console.error("[furin] DCE: failed to parse transformed output:", firstError.message);
2592
- return transformed;
3124
+ function nodeContains(container, node) {
3125
+ if (Array.isArray(container)) {
3126
+ return container.some((entry) => nodeContains(entry, node));
2593
3127
  }
2594
- const pruned = new MagicString(code);
2595
- const refs = collectReferencedNames(program);
2596
- const originalParse = parseSource(originalCode, lang);
2597
- const originalRefs = originalParse.diagnostics.some((diagnostic) => diagnostic.severity === "error") ? refs : collectReferencedNames(originalParse.program);
2598
- for (let index = program.body.length - 1;index >= 0; index -= 1) {
2599
- const statement = program.body[index];
2600
- if (statement?.type !== "ImportDeclaration") {
2601
- continue;
2602
- }
2603
- const declaration = statement;
2604
- if (declaration.specifiers.length === 0) {
2605
- continue;
2606
- }
2607
- const usedCount = declaration.specifiers.filter((specifier) => refs.has(specifier.local.name)).length;
2608
- if (usedCount === 0) {
2609
- const typeOnly = declaration.importKind === "type" || declaration.specifiers.every((specifier) => specifier.importKind === "type");
2610
- const wasUsedBeforeTransform = declaration.specifiers.some((specifier) => originalRefs.has(specifier.local.name));
2611
- if (typeOnly || wasUsedBeforeTransform) {
2612
- removeEntireImport(pruned, code, declaration);
2613
- } else {
2614
- preserveImportSideEffect(pruned, code, declaration);
2615
- }
2616
- } else if (usedCount < declaration.specifiers.length) {
2617
- removeUnusedSpecifiers(pruned, code, declaration, refs);
2618
- }
3128
+ const containerNode = unwrapTSExpression(container);
3129
+ return containerNode.start <= node.start && node.end <= containerNode.end;
3130
+ }
3131
+ function typescriptRuntimeChildren(ancestor) {
3132
+ switch (ancestor.type) {
3133
+ case "TSAsExpression":
3134
+ case "TSInstantiationExpression":
3135
+ case "TSNonNullExpression":
3136
+ case "TSSatisfiesExpression":
3137
+ case "TSTypeAssertion":
3138
+ return [ancestor.expression];
3139
+ case "TSParameterProperty":
3140
+ return [ancestor.decorators, ancestor.parameter];
3141
+ default:
3142
+ return;
2619
3143
  }
2620
- return pruned;
2621
3144
  }
2622
-
2623
- // src/plugin/hmr-dependencies.ts
2624
- import { readFileSync } from "fs";
2625
- import { dirname, isAbsolute, resolve } from "path";
2626
- var SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
2627
- function hmrDependencySignature(imports, filename) {
2628
- const routePath = resolve(filename);
2629
- const visited = new Set;
2630
- const hash = new Bun.CryptoHasher("sha256");
2631
- const visit = (specifier, importer) => {
2632
- if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
2633
- return true;
2634
- }
2635
- const path = Bun.resolveSync(specifier, dirname(importer));
2636
- if (path === routePath) {
3145
+ function isTypePosition(node, ancestors) {
3146
+ return ancestors.some((ancestor) => {
3147
+ if (!ancestor.type.startsWith("TS")) {
2637
3148
  return false;
2638
3149
  }
2639
- hash.update(JSON.stringify([specifier, path]));
2640
- if (!isAbsolute(path) || path.replaceAll("\\", "/").includes("/node_modules/") || visited.has(path)) {
2641
- return true;
2642
- }
2643
- visited.add(path);
2644
- const source = readFileSync(path, "utf8");
2645
- hash.update(source);
2646
- if (SCRIPT_FILE.test(path)) {
2647
- const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(path) });
2648
- for (const dependency of transpiler.scanImports(source)) {
2649
- if (!visit(dependency.path, path)) {
2650
- return false;
2651
- }
2652
- }
3150
+ const runtimeChildren = typescriptRuntimeChildren(ancestor);
3151
+ if (runtimeChildren) {
3152
+ return !runtimeChildren.some((child) => nodeContains(child, node));
2653
3153
  }
2654
3154
  return true;
2655
- };
2656
- try {
2657
- for (const specifier of imports) {
2658
- if (!visit(specifier, routePath)) {
2659
- return;
2660
- }
2661
- }
2662
- return hash.digest("hex");
2663
- } catch {}
3155
+ });
2664
3156
  }
2665
-
2666
- // src/plugin/transform-client-module.ts
2667
- import { realpathSync } from "fs";
2668
- import { dirname as dirname2 } from "path";
2669
- var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
2670
- var SERVER_LOAD = '() => Promise.reject(new Error("[furin] clientModule() can only be loaded in the browser."))';
2671
- function clientModuleKey(modulePath) {
2672
- const realPath = realpathSync(modulePath).replaceAll("\\", "/");
2673
- return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
3157
+ function isNonReferenceKey(node, parent) {
3158
+ return Boolean(parent && (parent.type === "MemberExpression" && parent.computed !== true && parent.property === node || parent.type === "Property" && parent.computed !== true && parent.shorthand !== true && parent.key === node || (parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.computed !== true && parent.key === node || (parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement") && parent.label === node));
2674
3159
  }
2675
- function collectClientModuleBindings(program) {
2676
- const bindings = new Set;
2677
- for (const statement of program.body) {
2678
- if (statement.type !== "ImportDeclaration") {
2679
- continue;
3160
+ function isReferenceIdentifier(node, ancestors) {
3161
+ if (isTypePosition(node, ancestors) || isNonReferenceKey(node, ancestors.at(-1))) {
3162
+ return false;
3163
+ }
3164
+ for (const ancestor of ancestors) {
3165
+ if (ancestor.type === "VariableDeclarator" && isBindingIdentifier(node, ancestor.id) || (ancestor.type === "FunctionDeclaration" || ancestor.type === "FunctionExpression" || ancestor.type === "ArrowFunctionExpression") && (isBindingIdentifier(node, ancestor.id) || Array.isArray(ancestor.params) && ancestor.params.some((parameter) => isBindingIdentifier(node, parameter))) || ancestor.type === "ClassDeclaration" && isBindingIdentifier(node, ancestor.id) || ancestor.type === "CatchClause" && isBindingIdentifier(node, ancestor.param)) {
3166
+ return false;
2680
3167
  }
2681
- const declaration = statement;
2682
- if (declaration.importKind === "type" || !FURIN_CLIENT_MODULES.has(String(declaration.source.value))) {
2683
- continue;
3168
+ }
3169
+ return true;
3170
+ }
3171
+
3172
+ // src/plugin/hmr-data-signature.ts
3173
+ function walkWithAncestors(value, ancestors, visitor) {
3174
+ if (Array.isArray(value)) {
3175
+ for (const entry of value) {
3176
+ walkWithAncestors(entry, ancestors, visitor);
2684
3177
  }
2685
- for (const specifier of declaration.specifiers) {
2686
- const imported = specifier.imported;
2687
- const local = specifier.local;
2688
- if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imported?.name === "clientModule" && typeof local?.name === "string") {
2689
- bindings.add(local.name);
2690
- }
3178
+ return;
3179
+ }
3180
+ if (!value || typeof value !== "object" || !isNode(value)) {
3181
+ return;
3182
+ }
3183
+ const node = unwrapTSExpression(value);
3184
+ visitor(node, ancestors);
3185
+ const nextAncestors = [...ancestors, node];
3186
+ for (const [key, child] of Object.entries(node)) {
3187
+ if (key !== "type" && key !== "start" && key !== "end" && key !== "comments") {
3188
+ walkWithAncestors(child, nextAncestors, visitor);
2691
3189
  }
2692
3190
  }
2693
- return bindings;
2694
3191
  }
2695
- function dynamicImportSpecifier(loader) {
2696
- if (loader.type !== "ArrowFunctionExpression" || loader.params.length > 0) {
2697
- return null;
3192
+ function collectDependencyIdentifier(child, ancestors, trackImports, state) {
3193
+ if (child.type !== "Identifier" && child.type !== "JSXIdentifier") {
3194
+ return;
2698
3195
  }
2699
- const body = loader.body;
2700
- const source = body.type === "ImportExpression" ? body.source : null;
2701
- return source?.type === "Literal" && typeof source.value === "string" ? source.value : null;
2702
- }
2703
- function transformClientModules(source, filename, environment) {
2704
- if (!source.includes("clientModule")) {
2705
- return source;
3196
+ const parent = ancestors.at(-1);
3197
+ const jsxReference = child.type === "JSXIdentifier" && (parent?.type === "JSXOpeningElement" && parent.name === child && child.name[0] === child.name[0]?.toUpperCase() || parent?.type === "JSXMemberExpression" && parent.object === child);
3198
+ if (child.type === "JSXIdentifier" && !jsxReference || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
3199
+ return;
2706
3200
  }
2707
- const { program } = parseSource(source, detectLangFromPath(filename));
2708
- const bindings = collectClientModuleBindings(program);
2709
- if (bindings.size === 0) {
2710
- return source;
3201
+ const declaration = state.moduleBindings.declarations.get(child.name);
3202
+ if (!declaration) {
3203
+ const imported = state.moduleBindings.imports.get(child.name);
3204
+ if (trackImports && imported) {
3205
+ state.imports.add(imported);
3206
+ }
3207
+ return;
2711
3208
  }
2712
- const transformed = new MagicString(source);
2713
- walk(program, {
2714
- CallExpression(node, context) {
2715
- const call = node;
2716
- const [loader, ...rest] = call.arguments;
2717
- if (call.callee.type !== "Identifier" || !bindings.has(call.callee.name) || hasShadowingDeclaration(call.callee.name, context.ancestors()) || !loader || rest.length > 0) {
2718
- return;
2719
- }
2720
- const unwrapped = unwrapTSExpression(loader);
2721
- const specifier = dynamicImportSpecifier(unwrapped);
2722
- if (specifier === null) {
2723
- return;
2724
- }
2725
- let key;
2726
- try {
2727
- key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname2(filename))));
2728
- } catch (error) {
2729
- throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
2730
- }
2731
- if (environment === "client") {
2732
- transformed.appendLeft(loader.end, `, ${key}`);
2733
- } else {
2734
- transformed.overwrite(loader.start, loader.end, `${SERVER_LOAD}, ${key}`);
3209
+ const alreadyTracked = state.dependencies.has(declaration.start);
3210
+ if (!alreadyTracked) {
3211
+ state.dependencies.set(declaration.start, declaration);
3212
+ }
3213
+ if (trackImports) {
3214
+ if (state.importTrackedDependencies.has(declaration.start)) {
3215
+ return;
3216
+ }
3217
+ state.importTrackedDependencies.add(declaration.start);
3218
+ } else if (alreadyTracked) {
3219
+ return;
3220
+ }
3221
+ collectDependencies(declaration, trackImports, state);
3222
+ }
3223
+ function collectDependencies(node, trackImports, state) {
3224
+ walkWithAncestors(node, [], (child, ancestors) => {
3225
+ collectDependencyIdentifier(child, ancestors, trackImports, state);
3226
+ if (trackImports && child.type === "ImportExpression") {
3227
+ const source = unwrapped(child.source);
3228
+ const specifier = source?.type === "Literal" ? source.value : undefined;
3229
+ if (typeof specifier === "string") {
3230
+ state.dynamicImports.add(specifier);
2735
3231
  }
2736
3232
  }
2737
3233
  });
2738
- return transformed.toString();
2739
3234
  }
2740
-
2741
- // src/plugin/transform-isomorphic.ts
2742
- var FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
2743
- function importedName(specifier) {
2744
- const { imported } = specifier;
2745
- if (!(imported && typeof imported === "object")) {
2746
- return;
2747
- }
2748
- const node = imported;
2749
- if (node.type === "Identifier" && typeof node.name === "string") {
2750
- return node.name;
3235
+ function createHmrDataSignature(code, program, serverStages, filename) {
3236
+ const stageSources = [];
3237
+ const dependencyState = {
3238
+ dependencies: new Map,
3239
+ dynamicImports: new Set,
3240
+ imports: new Set,
3241
+ importTrackedDependencies: new Set,
3242
+ moduleBindings: collectModuleBindings(program)
3243
+ };
3244
+ for (const { call, object, property } of serverStages) {
3245
+ stageSources.push({
3246
+ source: code.slice(object.end, call.end),
3247
+ start: call.start
3248
+ });
3249
+ if (Array.isArray(call.arguments)) {
3250
+ for (const argument of call.arguments) {
3251
+ const argumentNode = unwrapped(argument);
3252
+ if (argumentNode) {
3253
+ collectDependencies(argumentNode, property.name !== "config", dependencyState);
3254
+ }
3255
+ }
3256
+ }
2751
3257
  }
2752
- if (node.type === "Literal" && typeof node.value === "string") {
2753
- return node.value;
3258
+ const dataSource = [
3259
+ ...stageSources,
3260
+ ...[...dependencyState.imports].map((imported) => ({
3261
+ source: code.slice(imported.start, imported.end),
3262
+ start: imported.start
3263
+ })),
3264
+ ...[...dependencyState.dependencies.values()].map((dependency) => ({
3265
+ source: code.slice(dependency.start, dependency.end),
3266
+ start: dependency.start
3267
+ }))
3268
+ ].sort((left, right) => left.start - right.start).map((entry) => entry.source).join(`
3269
+ `);
3270
+ const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
3271
+ if (dependencyState.imports.size === 0 && dependencyState.dynamicImports.size === 0) {
3272
+ return hash;
2754
3273
  }
3274
+ const dependencies = hmrDependencySignature(new Set([
3275
+ ...[...dependencyState.imports].map((imported) => imported.source.value),
3276
+ ...dependencyState.dynamicImports
3277
+ ]), filename);
3278
+ return dependencies === undefined ? `external:${hash}` : `imports:${hash}:${dependencies}`;
2755
3279
  }
2756
- function localName(specifier) {
2757
- const local = specifier.local;
2758
- return local?.type === "Identifier" && typeof local.name === "string" ? local.name : undefined;
3280
+
3281
+ // src/plugin/hmr-hook-signature.ts
3282
+ var REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
3283
+ var REACT_HOOK_NAME_RE = /^use[A-Z0-9]/;
3284
+ function calledHookName(call) {
3285
+ const callee = unwrapped(call.callee);
3286
+ if (callee?.type === "Identifier") {
3287
+ return REACT_HOOK_NAME_RE.test(callee.name) ? callee.name : null;
3288
+ }
3289
+ if (callee?.type === "MemberExpression" && callee.computed !== true) {
3290
+ const { property } = callee;
3291
+ if (property.type === "Identifier" && REACT_HOOK_NAME_RE.test(property.name)) {
3292
+ return property.name;
3293
+ }
3294
+ }
3295
+ return null;
2759
3296
  }
2760
- function addImportSpecifier(specifier, bindings) {
2761
- const local = localName(specifier);
2762
- if (!local) {
2763
- return;
3297
+ function namedFunction(declaration, name) {
3298
+ if (declaration.type === "FunctionDeclaration") {
3299
+ const identifier = unwrapped(declaration.id);
3300
+ return identifier?.type === "Identifier" && identifier.name === name ? declaration : null;
2764
3301
  }
2765
- if (specifier.type === "ImportNamespaceSpecifier") {
2766
- bindings.namespaces.add(local);
2767
- return;
3302
+ if (declaration.type === "VariableDeclaration" && Array.isArray(declaration.declarations)) {
3303
+ for (const item of declaration.declarations) {
3304
+ const identifier = unwrapped(item.id);
3305
+ const initializer = unwrapped(item.init);
3306
+ if (identifier?.type === "Identifier" && identifier.name === name && (initializer?.type === "ArrowFunctionExpression" || initializer?.type === "FunctionExpression")) {
3307
+ return initializer;
3308
+ }
3309
+ }
2768
3310
  }
2769
- if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && importedName(specifier) === "createIsomorphicFn") {
2770
- bindings.named.add(local);
3311
+ return null;
3312
+ }
3313
+ function localFunction(program, name) {
3314
+ for (const statement of program.body) {
3315
+ const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? unwrapped(statement.declaration) : statement;
3316
+ const component = declaration ? namedFunction(declaration, name) : null;
3317
+ if (component) {
3318
+ return component;
3319
+ }
2771
3320
  }
3321
+ return null;
2772
3322
  }
2773
- function collectBindings(program) {
3323
+ function isImportedBinding(program, name) {
3324
+ return program.body.some((statement) => statement.type === "ImportDeclaration" && statement.importKind !== "type" && statement.specifiers.some((specifier) => !(specifier.type === "ImportSpecifier" && specifier.importKind === "type") && localName(specifier) === name));
3325
+ }
3326
+ function collectReactWrapperBindings(program) {
2774
3327
  const bindings = {
2775
- named: new Set,
3328
+ members: new Set,
2776
3329
  namespaces: new Set
2777
3330
  };
2778
3331
  for (const statement of program.body) {
2779
- if (statement.type !== "ImportDeclaration") {
2780
- continue;
2781
- }
2782
- const declaration = statement;
2783
- if (declaration.importKind === "type" || !FURIN_MODULES.has(String(declaration.source.value))) {
3332
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== "react") {
2784
3333
  continue;
2785
3334
  }
2786
- for (const specifier of declaration.specifiers) {
2787
- addImportSpecifier(specifier, bindings);
3335
+ for (const specifier of statement.specifiers) {
3336
+ const local = localName(specifier);
3337
+ if (!local || specifier.type === "ImportSpecifier" && specifier.importKind === "type") {
3338
+ continue;
3339
+ }
3340
+ const imported = importedName(specifier);
3341
+ if (specifier.type === "ImportSpecifier" && imported && REACT_COMPONENT_WRAPPERS.has(imported)) {
3342
+ bindings.members.add(local);
3343
+ } else if (specifier.type === "ImportDefaultSpecifier" || specifier.type === "ImportNamespaceSpecifier" || specifier.type === "ImportSpecifier" && imported === "default") {
3344
+ bindings.namespaces.add(local);
3345
+ }
2788
3346
  }
2789
3347
  }
2790
3348
  return bindings;
2791
3349
  }
2792
- function isCreateIsomorphicCall(node, bindings, ancestors) {
2793
- if (node.type !== "CallExpression") {
2794
- return false;
2795
- }
2796
- const call = node;
2797
- if (call.callee.type === "Identifier" && typeof call.callee.name === "string" && bindings.named.has(call.callee.name) && !hasShadowingDeclaration(call.callee.name, ancestors)) {
2798
- return true;
2799
- }
2800
- const { callee } = call;
2801
- return callee.type === "MemberExpression" && !callee.computed && callee.object.type === "Identifier" && typeof callee.object.name === "string" && bindings.namespaces.has(callee.object.name) && !hasShadowingDeclaration(callee.object.name, ancestors) && callee.property.type === "Identifier" && callee.property.name === "createIsomorphicFn";
2802
- }
2803
- function environmentMethod(node) {
2804
- if (node.type !== "CallExpression") {
2805
- return;
3350
+ function wrappedComponentFunction(program, expression, bindings) {
3351
+ if (expression.type === "ArrowFunctionExpression" || expression.type === "FunctionExpression") {
3352
+ return expression;
2806
3353
  }
2807
- const call = node;
2808
- const { callee } = call;
2809
- if (callee.type !== "MemberExpression" || callee.computed || callee.property.type !== "Identifier") {
2810
- return;
3354
+ if (expression.type === "Identifier") {
3355
+ return localFunction(program, expression.name);
2811
3356
  }
2812
- return callee.property.name === "client" || callee.property.name === "server" ? callee.property.name : undefined;
2813
- }
2814
- function parseCandidate(source, filename, node, bindings, ancestors) {
2815
- let current = node;
2816
- let client;
2817
- let server;
2818
- for (;; ) {
2819
- const method = environmentMethod(current);
2820
- if (!method) {
2821
- break;
2822
- }
2823
- const call = current;
2824
- if (call.callee.type !== "MemberExpression") {
2825
- return null;
2826
- }
2827
- const [implementation] = call.arguments;
2828
- if (!implementation) {
2829
- return null;
2830
- }
2831
- const unwrappedImplementation = unwrapTSExpression(implementation);
2832
- if (unwrappedImplementation.type !== "ArrowFunctionExpression" && unwrappedImplementation.type !== "FunctionExpression" && unwrappedImplementation.type !== "Identifier") {
2833
- throw new Error(`[furin] ${filename}:${sourcePosition(source, implementation.start)} createIsomorphicFn().${method}() must receive a function.`);
2834
- }
2835
- if (method === "client") {
2836
- client = implementation;
2837
- } else {
2838
- server = implementation;
2839
- }
2840
- current = unwrapTSExpression(call.callee.object);
3357
+ if (expression.type !== "CallExpression") {
3358
+ return null;
2841
3359
  }
2842
- if (!isCreateIsomorphicCall(current, bindings, ancestors)) {
3360
+ const callee = unwrapped(expression.callee);
3361
+ const isNamedWrapper = callee?.type === "Identifier" && bindings.members.has(callee.name);
3362
+ const object = callee?.type === "MemberExpression" ? unwrapped(callee.object) : null;
3363
+ const property = callee?.type === "MemberExpression" ? unwrapped(callee.property) : null;
3364
+ const isNamespaceWrapper = callee?.type === "MemberExpression" && callee.computed !== true && object?.type === "Identifier" && bindings.namespaces.has(object.name) && property?.type === "Identifier" && REACT_COMPONENT_WRAPPERS.has(property.name);
3365
+ if (!(isNamedWrapper || isNamespaceWrapper)) {
2843
3366
  return null;
2844
3367
  }
2845
- return {
2846
- client,
2847
- end: node.end,
2848
- server,
2849
- start: node.start
2850
- };
2851
- }
2852
- function collectCandidates(source, filename, program, bindings) {
2853
- const candidates = [];
2854
- walk(program, {
2855
- CallExpression(node, context) {
2856
- const candidate = parseCandidate(source, filename, node, bindings, context.ancestors());
2857
- if (candidate) {
2858
- candidates.push(candidate);
2859
- }
2860
- }
2861
- });
2862
- return candidates.toSorted((left, right) => right.end - right.start - (left.end - left.start)).filter((candidate, index, all) => !all.slice(0, index).some((other) => other.start <= candidate.start && other.end >= candidate.end));
2863
- }
2864
- function sourcePosition(source, offset) {
2865
- const before = source.slice(0, offset);
2866
- const line = before.split(`
2867
- `).length;
2868
- const lastNewline = before.lastIndexOf(`
2869
- `);
2870
- return `${line}:${offset - lastNewline}`;
3368
+ const args = expression.arguments;
3369
+ const wrapped = Array.isArray(args) ? unwrapped(args[0]) : null;
3370
+ return wrapped ? wrappedComponentFunction(program, wrapped, bindings) : null;
2871
3371
  }
2872
- function lexicalBindingScope(ancestors) {
2873
- return ancestors.findLast((ancestor) => ancestor.type === "Program" || ancestor.type === "BlockStatement" || ancestor.type === "SwitchStatement" || ancestor.type === "ForStatement" || ancestor.type === "ForInStatement" || ancestor.type === "ForOfStatement" || ancestor.type === "StaticBlock");
3372
+ function importedMemberBinding(program, expression) {
3373
+ let object = expression.type === "MemberExpression" ? unwrapped(expression.object) : null;
3374
+ while (object?.type === "MemberExpression") {
3375
+ object = unwrapped(object.object);
3376
+ }
3377
+ return object?.type === "Identifier" && isImportedBinding(program, object.name) ? object.name : null;
2874
3378
  }
2875
- function varBindingScope(ancestors) {
2876
- return ancestors.findLast((ancestor, index) => {
2877
- if (ancestor.type === "Program" || ancestor.type === "StaticBlock") {
2878
- return true;
2879
- }
2880
- if (ancestor.type !== "BlockStatement") {
2881
- return false;
2882
- }
2883
- const parent = ancestors[index - 1];
2884
- return parent?.type === "FunctionDeclaration" || parent?.type === "FunctionExpression" || parent?.type === "ArrowFunctionExpression";
2885
- });
3379
+ function sourceText(code, node) {
3380
+ return node ? code.slice(node.start, node.end) : "";
2886
3381
  }
2887
- function collectBuilderBindings(program, bindings) {
2888
- const builders = [];
3382
+ function unusedIdentifier(program, preferred) {
3383
+ const identifiers = new Set;
2889
3384
  walk(program, {
2890
- VariableDeclarator(node, context) {
2891
- if (!(node.id && node.init && typeof node.id === "object" && typeof node.init === "object")) {
2892
- return;
2893
- }
2894
- const identifier = node.id;
2895
- const initializer = unwrapTSExpression(node.init);
2896
- const ancestors = context.ancestors();
2897
- const declaration = ancestors.at(-1);
2898
- const scope = declaration?.type === "VariableDeclaration" && declaration.kind === "var" ? varBindingScope(ancestors) : lexicalBindingScope(ancestors);
2899
- if (scope && identifier.type === "Identifier" && typeof identifier.name === "string" && isCreateIsomorphicCall(initializer, bindings, ancestors)) {
2900
- builders.push({ name: identifier.name, scope });
2901
- }
3385
+ Identifier(node) {
3386
+ identifiers.add(node.name);
2902
3387
  }
2903
3388
  });
2904
- return builders;
2905
- }
2906
- function hasVisibleBuilder(name, ancestors, builders) {
2907
- let scopeIndex = -1;
2908
- for (const builder of builders) {
2909
- if (builder.name === name) {
2910
- scopeIndex = Math.max(scopeIndex, ancestors.lastIndexOf(builder.scope));
2911
- }
2912
- }
2913
- return scopeIndex >= 0 && !hasShadowingDeclaration(name, ancestors.slice(scopeIndex + 1));
2914
- }
2915
- function assertNoSplitChains(source, filename, program, builders) {
2916
- if (builders.length === 0) {
2917
- return;
3389
+ if (!identifiers.has(preferred)) {
3390
+ return preferred;
2918
3391
  }
2919
- walk(program, {
2920
- MemberExpression(node, context) {
2921
- if (node.computed || node.object.type !== "Identifier" || typeof node.object.name !== "string" || !hasVisibleBuilder(node.object.name, context.ancestors(), builders) || node.property.type !== "Identifier" || node.property.name !== "server" && node.property.name !== "client") {
2922
- return;
2923
- }
2924
- throw new Error(`[furin] ${filename}:${sourcePosition(source, node.start)} createIsomorphicFn() must use one fluent chain.`);
2925
- }
2926
- });
2927
- }
2928
- function chainStartsWithCreateIsomorphicFn(expression, bindings, ancestors) {
2929
- let current = unwrapTSExpression(expression);
2930
- for (;; ) {
2931
- if (isCreateIsomorphicCall(current, bindings, ancestors)) {
2932
- return true;
2933
- }
2934
- if (current.type !== "CallExpression" || !environmentMethod(current)) {
2935
- return false;
2936
- }
2937
- const call = current;
2938
- if (call.callee.type !== "MemberExpression") {
2939
- return false;
2940
- }
2941
- current = unwrapTSExpression(call.callee.object);
3392
+ let suffix = 1;
3393
+ while (identifiers.has(`${preferred}_${suffix}`)) {
3394
+ suffix += 1;
2942
3395
  }
3396
+ return `${preferred}_${suffix}`;
2943
3397
  }
2944
- function assertStaticEnvironmentMethods(source, filename, program, bindings, builders) {
2945
- walk(program, {
2946
- MemberExpression(node, context) {
2947
- if (!node.computed || node.property.type !== "Literal") {
2948
- return;
2949
- }
2950
- if (node.property.value !== "server" && node.property.value !== "client") {
2951
- return;
3398
+ function hookCallsiteSignature(code, call, hookName, parent) {
3399
+ let key = parent?.type === "VariableDeclarator" ? sourceText(code, unwrapped(parent.id)) : "";
3400
+ const args = call.arguments;
3401
+ const stateArgument = Array.isArray(args) ? unwrapped(args[0]) : null;
3402
+ const reducerArgument = Array.isArray(args) ? unwrapped(args[1]) : null;
3403
+ if (hookName === "useState" && stateArgument) {
3404
+ key += `(${sourceText(code, stateArgument)})`;
3405
+ } else if (hookName === "useReducer" && reducerArgument) {
3406
+ key += `(${sourceText(code, reducerArgument)})`;
3407
+ }
3408
+ return `${hookName}{${key}}`;
3409
+ }
3410
+ function collectFunctionHookSignature(code, component) {
3411
+ const hooks = [];
3412
+ walk(component, {
3413
+ CallExpression(call, context) {
3414
+ const name = calledHookName(call);
3415
+ if (name) {
3416
+ hooks.push(hookCallsiteSignature(code, call, name, unwrapped(context.parent)));
2952
3417
  }
2953
- const ancestors = context.ancestors();
2954
- const splitBuilder = node.object.type === "Identifier" && typeof node.object.name === "string" && hasVisibleBuilder(node.object.name, ancestors, builders);
2955
- if (!(splitBuilder || chainStartsWithCreateIsomorphicFn(node.object, bindings, ancestors))) {
2956
- return;
3418
+ },
3419
+ Function(node, context) {
3420
+ if (node !== component) {
3421
+ context.skip();
2957
3422
  }
2958
- throw new Error(`[furin] ${filename}:${sourcePosition(source, node.start)} createIsomorphicFn() requires static .server() and .client() methods.`);
2959
3423
  }
2960
3424
  });
3425
+ return hooks;
2961
3426
  }
2962
- function transformIsomorphicFunctions(input, filename, environment) {
2963
- const lang = detectLangFromPath(filename);
2964
- if (lang === "dts") {
2965
- return { code: input, map: null, transformed: false };
3427
+ function collectClientHookSignature(code, program, componentExpression) {
3428
+ if (!componentExpression) {
3429
+ return null;
2966
3430
  }
2967
- const source = transformClientModules(input, filename, environment);
2968
- const clientModulesTransformed = source !== input;
2969
- const { program, diagnostics } = parseSource(source, lang);
2970
- const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
2971
- if (firstError) {
2972
- throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
3431
+ const wrappedComponent = wrappedComponentFunction(program, componentExpression, collectReactWrapperBindings(program));
3432
+ if (wrappedComponent) {
3433
+ return collectFunctionHookSignature(code, wrappedComponent);
2973
3434
  }
2974
- const bindings = collectBindings(program);
2975
- const builders = collectBuilderBindings(program, bindings);
2976
- assertStaticEnvironmentMethods(source, filename, program, bindings, builders);
2977
- assertNoSplitChains(source, filename, program, builders);
2978
- const candidates = collectCandidates(source, filename, program, bindings);
2979
- if (candidates.length === 0) {
2980
- return { code: source, map: null, transformed: clientModulesTransformed };
3435
+ if (componentExpression.type !== "Identifier") {
3436
+ if (importedMemberBinding(program, componentExpression)) {
3437
+ return {
3438
+ end: componentExpression.end,
3439
+ expression: sourceText(code, componentExpression),
3440
+ start: componentExpression.start
3441
+ };
3442
+ }
3443
+ return collectFunctionHookSignature(code, componentExpression);
2981
3444
  }
2982
- const transformed = new MagicString(source);
2983
- for (const candidate of candidates) {
2984
- const implementation = candidate[environment];
2985
- transformed.overwrite(candidate.start, candidate.end, implementation ? `(${source.slice(implementation.start, implementation.end)})` : "(() => undefined)");
3445
+ const component = localFunction(program, componentExpression.name);
3446
+ if (component) {
3447
+ return collectFunctionHookSignature(code, component);
2986
3448
  }
2987
- const pruned = deadCodeElimination(transformed, source, lang);
2988
- return {
2989
- code: pruned.toString(),
2990
- map: pruned.generateMap({ includeContent: true, source: filename }),
2991
- transformed: true
2992
- };
3449
+ return isImportedBinding(program, componentExpression.name) ? {
3450
+ end: componentExpression.end,
3451
+ expression: componentExpression.name,
3452
+ start: componentExpression.start
3453
+ } : "external";
2993
3454
  }
2994
3455
 
2995
- // src/plugin/transform-client.ts
2996
- var FURIN_CLIENT_MODULES2 = new Set(["@teyik0/furin/client", "furin/client"]);
3456
+ // src/plugin/route-chains.ts
3457
+ var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
2997
3458
  var FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
2998
- var REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
2999
3459
  var SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
3000
- var REACT_HOOK_NAME_RE = /^use[A-Z0-9]/;
3001
- var HMR_DATA_SIGNATURE = "furin.hmr.data-signature";
3002
- var HMR_SOURCE_SIGNATURE = "furin.hmr.source-signature";
3003
- var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
3004
- ["TSAsExpression", ["expression"]],
3005
- ["TSInstantiationExpression", ["expression"]],
3006
- ["TSNonNullExpression", ["expression"]],
3007
- ["TSParameterProperty", ["decorators", "parameter"]],
3008
- ["TSSatisfiesExpression", ["expression"]],
3009
- ["TSTypeAssertion", ["expression"]]
3010
- ]);
3011
3460
  function isFurinRouteModule(source) {
3012
- return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES2.has(source));
3013
- }
3014
- function importedName2(specifier) {
3015
- const { imported } = specifier;
3016
- if (!imported || typeof imported !== "object") {
3017
- return null;
3018
- }
3019
- const node = imported;
3020
- if (node.type === "Identifier" && typeof node.name === "string") {
3021
- return node.name;
3022
- }
3023
- if (node.type === "Literal" && typeof node.value === "string") {
3024
- return node.value;
3025
- }
3026
- return null;
3027
- }
3028
- function localName2(specifier) {
3029
- const { local } = specifier;
3030
- if (!local || typeof local !== "object") {
3031
- return null;
3032
- }
3033
- const node = local;
3034
- return node.type === "Identifier" && typeof node.name === "string" ? node.name : null;
3461
+ return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES.has(source));
3035
3462
  }
3036
- function collectDefineRouteBindings(program) {
3037
- const bindings = new Set;
3038
- for (const statement of program.body) {
3039
- if (statement.type !== "ImportDeclaration") {
3040
- continue;
3463
+ function collectFactorySpecifiers(declaration, bindings, namespaces) {
3464
+ for (const specifier of declaration.specifiers) {
3465
+ const namespace = localName(specifier);
3466
+ if (specifier.type === "ImportNamespaceSpecifier" && namespace) {
3467
+ namespaces.add(namespace);
3041
3468
  }
3042
- const declaration = statement;
3043
- if (declaration.importKind === "type") {
3469
+ if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") {
3044
3470
  continue;
3045
3471
  }
3046
- const source = declaration.source.value;
3047
- if (!isFurinRouteModule(source)) {
3472
+ const imported = importedName(specifier);
3473
+ if (imported !== "defineRoute" && imported !== "defineRootRoute") {
3048
3474
  continue;
3049
3475
  }
3050
- for (const specifier of declaration.specifiers) {
3051
- if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") {
3052
- continue;
3053
- }
3054
- const imported = importedName2(specifier);
3055
- if (imported !== "defineRoute" && imported !== "defineRootRoute") {
3056
- continue;
3057
- }
3058
- const local = localName2(specifier);
3059
- if (local) {
3060
- bindings.add(local);
3061
- }
3476
+ const local = localName(specifier);
3477
+ if (local) {
3478
+ bindings.add(local);
3062
3479
  }
3063
3480
  }
3064
- return bindings;
3065
3481
  }
3066
- function rewriteClientImports(source, program, bindings) {
3067
- let rewritten = false;
3482
+ function collectDefineRouteBindings(program) {
3483
+ const bindings = new Set;
3484
+ const namespaces = new Set;
3068
3485
  for (const statement of program.body) {
3069
3486
  if (statement.type !== "ImportDeclaration") {
3070
3487
  continue;
3071
3488
  }
3072
- const declaration = statement;
3073
- const moduleName = declaration.source.value;
3074
- if (typeof moduleName !== "string" || !FURIN_SERVER_MODULES.has(moduleName)) {
3075
- continue;
3076
- }
3077
- const importsClientValue = declaration.specifiers.some((specifier) => {
3078
- const local = localName2(specifier);
3079
- const imported = importedName2(specifier);
3080
- return local !== null && bindings.has(local) || imported === "HeadContent" || imported === "Scripts";
3081
- });
3082
- if (!importsClientValue) {
3083
- continue;
3489
+ if (statement.importKind !== "type" && isFurinRouteModule(statement.source.value)) {
3490
+ collectFactorySpecifiers(statement, bindings, namespaces);
3084
3491
  }
3085
- const clientModule = moduleName === "furin" ? "furin/client" : "@teyik0/furin/client";
3086
- source.update(declaration.source.start + 1, declaration.source.end - 1, clientModule);
3087
- rewritten = true;
3088
3492
  }
3089
- return rewritten;
3090
- }
3091
- function asAstNode(node) {
3092
- if (!node || typeof node !== "object" || !("type" in node)) {
3093
- return null;
3094
- }
3095
- return unwrapTSExpression(node);
3493
+ return new FactoryBindings(program, bindings, namespaces);
3096
3494
  }
3097
3495
  function chainRootIsDefineRoute(node, bindings, ancestors) {
3098
- let current = asAstNode(node);
3496
+ let current = unwrapped(node);
3099
3497
  while (current) {
3100
3498
  if (current.type === "MemberExpression") {
3101
- current = asAstNode(current.object);
3499
+ current = unwrapped(current.object);
3102
3500
  continue;
3103
3501
  }
3104
3502
  if (current.type === "CallExpression") {
3105
- current = asAstNode(current.callee);
3503
+ current = unwrapped(current.callee);
3106
3504
  continue;
3107
3505
  }
3108
- return current.type === "Identifier" && typeof current.name === "string" && bindings.has(current.name) && !hasShadowingDeclaration(current.name, ancestors);
3506
+ return current.type === "Identifier" && bindings.factoryName(current, ancestors) !== undefined;
3109
3507
  }
3110
3508
  return false;
3111
3509
  }
3510
+ function isLocalFactoryAlias(identifier, ancestors, filename) {
3511
+ const parent = ancestors.at(-1);
3512
+ if (parent?.type !== "VariableDeclarator" || unwrapped(parent.id)?.type !== "Identifier" || unwrapped(parent.init) !== identifier) {
3513
+ return false;
3514
+ }
3515
+ const declaration = ancestors.at(-2);
3516
+ if (declaration?.type !== "VariableDeclaration" || declaration.kind !== "const") {
3517
+ throw new Error(`[furin] ${filename}: route factory aliases must be immutable.`);
3518
+ }
3519
+ return ancestors.at(-3)?.type !== "ExportNamedDeclaration";
3520
+ }
3112
3521
  function assertCompleteRouteChains(program, bindings, filename) {
3113
- const namespaces = new Set;
3114
- for (const statement of program.body) {
3115
- if (statement.type !== "ImportDeclaration") {
3116
- continue;
3117
- }
3118
- const declaration = statement;
3119
- if (!isFurinRouteModule(declaration.source.value) || declaration.importKind === "type") {
3120
- continue;
3121
- }
3122
- for (const specifier of declaration.specifiers) {
3123
- const name = localName2(specifier);
3124
- if (name && specifier.type === "ImportNamespaceSpecifier") {
3125
- namespaces.add(name);
3126
- }
3127
- }
3522
+ if (!bindings.hasImports) {
3523
+ return;
3128
3524
  }
3129
3525
  walk(program, {
3526
+ CallExpression(call, context) {
3527
+ const callee = unwrapped(call.callee);
3528
+ const ancestors = context.ancestors();
3529
+ if (!callee || bindings.factoryName(callee, ancestors) === undefined) {
3530
+ return;
3531
+ }
3532
+ const chain = fluentChain(call, ancestors);
3533
+ const terminal = chain.type === "CallExpression" ? unwrapped(chain.callee) : null;
3534
+ const method = terminal?.type === "MemberExpression" ? unwrapped(terminal.property) : null;
3535
+ if (method?.type !== "Identifier" || method.name !== "page" && method.name !== "layout") {
3536
+ throw new Error(`[furin] ${filename}: route builders must use one fluent chain ending in .page() or .layout().`);
3537
+ }
3538
+ },
3539
+ Identifier(node, context) {
3540
+ const ancestors = context.ancestors();
3541
+ const identifier = node;
3542
+ if (ancestors.some((ancestor) => ancestor.type === "ImportDeclaration") || !isReferenceIdentifier(identifier, ancestors)) {
3543
+ return;
3544
+ }
3545
+ const factory = bindings.factoryName(identifier, ancestors);
3546
+ const namespace = bindings.namespaceName(identifier, ancestors);
3547
+ if (factory === undefined && namespace === undefined) {
3548
+ return;
3549
+ }
3550
+ let index = ancestors.length - 1;
3551
+ while (index >= 0 && unwrapped(ancestors[index]) === identifier) {
3552
+ index -= 1;
3553
+ }
3554
+ const parent = ancestors[index];
3555
+ if (namespace !== undefined && parent?.type === "MemberExpression" && unwrapped(parent.object) === identifier) {
3556
+ return;
3557
+ }
3558
+ if (factory !== undefined && parent?.type === "CallExpression" && unwrapped(parent.callee) === identifier) {
3559
+ return;
3560
+ }
3561
+ if (isLocalFactoryAlias(identifier, ancestors.slice(0, index + 1), filename)) {
3562
+ return;
3563
+ }
3564
+ if (namespace !== undefined) {
3565
+ throw new Error(`[furin] ${filename}: route builders require a named import.`);
3566
+ }
3567
+ throw new Error(`[furin] ${filename}: route factory aliases require static local bindings and cannot escape.`);
3568
+ },
3130
3569
  MemberExpression(node, context) {
3131
- const object = asAstNode(node.object);
3132
- const property = asAstNode(node.property);
3133
- const method = property?.type === "Identifier" ? property.name : property?.value;
3134
- if (object?.type === "Identifier" && typeof object.name === "string" && namespaces.has(object.name) && (method === "defineRoute" || method === "defineRootRoute") && !hasShadowingDeclaration(object.name, context.ancestors())) {
3570
+ const object = unwrapped(node.object);
3571
+ const property = unwrapped(node.property);
3572
+ const method = property?.type === "Identifier" ? property.name : literalValue(property);
3573
+ const dynamic = node.computed && property?.type !== "Literal";
3574
+ if (object?.type === "Identifier" && bindings.namespaceName(object, context.ancestors()) !== undefined && (dynamic || method === "defineRoute" || method === "defineRootRoute")) {
3135
3575
  throw new Error(`[furin] ${filename}: route builders require a named import.`);
3136
3576
  }
3137
3577
  if (node.computed && context.parent?.type === "CallExpression" && chainRootIsDefineRoute(node.object, bindings, context.ancestors())) {
@@ -3139,73 +3579,171 @@ function assertCompleteRouteChains(program, bindings, filename) {
3139
3579
  }
3140
3580
  },
3141
3581
  VariableDeclarator(node, context) {
3142
- const initializer = asAstNode(node.init);
3582
+ const initializer = unwrapped(node.init);
3143
3583
  if (!(initializer && chainRootIsDefineRoute(initializer, bindings, context.ancestors()))) {
3144
3584
  return;
3145
3585
  }
3146
- const callee = initializer.type === "CallExpression" ? asAstNode(initializer.callee) : null;
3147
- const method = callee?.type === "MemberExpression" ? asAstNode(callee.property) : null;
3586
+ if (initializer.type === "Identifier") {
3587
+ const declaration = context.ancestors().at(-1);
3588
+ if (declaration?.type !== "VariableDeclaration" || declaration.kind !== "const") {
3589
+ throw new Error(`[furin] ${filename}: route factory aliases must be immutable.`);
3590
+ }
3591
+ return;
3592
+ }
3593
+ const callee = initializer.type === "CallExpression" ? unwrapped(initializer.callee) : null;
3594
+ const method = callee?.type === "MemberExpression" ? unwrapped(callee.property) : null;
3148
3595
  if (method?.type !== "Identifier" || method.name !== "page" && method.name !== "layout") {
3149
3596
  throw new Error(`[furin] ${filename}: route builders must use one fluent chain ending in .page() or .layout().`);
3150
3597
  }
3151
3598
  }
3152
3599
  });
3153
3600
  }
3154
- function removeChainedServerCalls(source, program, bindings, configBindings, filename) {
3155
- let transformed = rewriteClientImports(source, program, bindings);
3156
- const { declarations } = collectModuleBindings(program);
3601
+ function exportedRouteChain(program, bindings) {
3602
+ for (const statement of program.body) {
3603
+ if (statement.type !== "ExportNamedDeclaration" || statement.declaration?.type !== "VariableDeclaration") {
3604
+ continue;
3605
+ }
3606
+ for (const declarator of statement.declaration.declarations) {
3607
+ const id = unwrapped(declarator.id);
3608
+ if (id?.type === "Identifier" && id.name === "route") {
3609
+ return routeChainOf(declarator.init, bindings, program);
3610
+ }
3611
+ }
3612
+ }
3613
+ }
3614
+ function routeChainOf(initializer, bindings, program) {
3615
+ const calls = [];
3616
+ let current = unwrapped(initializer);
3617
+ while (current?.type === "CallExpression") {
3618
+ const callee = unwrapped(current.callee);
3619
+ if (callee?.type !== "MemberExpression") {
3620
+ const factory = callee ? bindings.factoryName(callee, [program]) : undefined;
3621
+ return factory === undefined ? undefined : { calls, factory, head: current };
3622
+ }
3623
+ if (callee.computed || callee.property.type !== "Identifier") {
3624
+ return;
3625
+ }
3626
+ calls.push({ call: current, method: callee.property.name });
3627
+ current = unwrapped(callee.object);
3628
+ }
3629
+ }
3630
+ function analyzeRouteChains(program, bindings) {
3631
+ const chains = { component: null, serverStages: [] };
3632
+ if (bindings.size === 0) {
3633
+ return chains;
3634
+ }
3635
+ const [terminal] = exportedRouteChain(program, bindings)?.calls ?? [];
3636
+ if (terminal?.method === "page" || terminal?.method === "layout") {
3637
+ chains.component = unwrapped(terminal.call.arguments[0]);
3638
+ }
3157
3639
  walk(program, {
3158
3640
  CallExpression(call, context) {
3159
- const callee = asAstNode(call.callee);
3160
- if (callee?.type !== "MemberExpression" || callee.computed === true || !callee.property || typeof callee.property !== "object") {
3161
- return;
3162
- }
3163
- const property = callee.property;
3164
- if (property.type !== "Identifier" || typeof property.name !== "string" || !SERVER_ONLY_METHODS.has(property.name) || !chainRootIsDefineRoute(callee.object, bindings, context.ancestors())) {
3641
+ const callee = unwrapped(call.callee);
3642
+ if (callee?.type !== "MemberExpression" || callee.computed === true) {
3165
3643
  return;
3166
3644
  }
3167
- const object = asAstNode(callee.object);
3168
- if (!object) {
3645
+ const { property } = callee;
3646
+ if (property.type !== "Identifier") {
3169
3647
  return;
3170
3648
  }
3171
- if (property.name === "config" && Array.isArray(call.arguments)) {
3172
- const config = asAstNode(call.arguments[0]);
3173
- if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
3174
- collectConfigBindings(config, declarations, configBindings);
3175
- const remount = resolveRemountProperty(config, declarations, configBindings, new Set, filename);
3176
- if (remount) {
3177
- source.update(object.end, call.end, `.config({ ${source.original.slice(remount.start, remount.end)} })`);
3178
- transformed = true;
3179
- return;
3180
- }
3649
+ if (SERVER_ONLY_METHODS.has(property.name)) {
3650
+ const object = unwrapped(callee.object);
3651
+ if (object && chainRootIsDefineRoute(callee.object, bindings, context.ancestors())) {
3652
+ chains.serverStages.push({ call, object, property });
3181
3653
  }
3182
3654
  }
3183
- source.remove(object.end, call.end);
3184
- transformed = true;
3185
3655
  }
3186
3656
  });
3657
+ return chains;
3658
+ }
3659
+
3660
+ // src/plugin/strip-server-stages.ts
3661
+ function rewriteClientImports(source, program, bindings) {
3662
+ let rewritten = false;
3663
+ for (const statement of program.body) {
3664
+ if (statement.type !== "ImportDeclaration") {
3665
+ continue;
3666
+ }
3667
+ const declaration = statement;
3668
+ const moduleName = declaration.source.value;
3669
+ if (!FURIN_SERVER_MODULES.has(moduleName)) {
3670
+ continue;
3671
+ }
3672
+ const importsClientValue = declaration.specifiers.some((specifier) => {
3673
+ const imported = importedName(specifier);
3674
+ return bindings.has(localName(specifier)) || imported === "HeadContent" || imported === "Scripts";
3675
+ });
3676
+ if (!importsClientValue) {
3677
+ continue;
3678
+ }
3679
+ const clientModule = moduleName === "furin" ? "furin/client" : "@teyik0/furin/client";
3680
+ source.update(declaration.source.start + 1, declaration.source.end - 1, clientModule);
3681
+ rewritten = true;
3682
+ }
3683
+ return rewritten;
3684
+ }
3685
+ function memberAccessStart(source, object, property) {
3686
+ const accessGap = source.slice(object.end, property.start);
3687
+ const separator = accessGap.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, (comment) => " ".repeat(comment.length)).lastIndexOf(".");
3688
+ return object.end + separator - (accessGap[separator - 1] === "?" ? 1 : 0);
3689
+ }
3690
+ function stripServerStage(module, stripped, range, remount) {
3691
+ const { removed, source } = module;
3692
+ if (remount) {
3693
+ const policy = source.slice(remount.start, remount.end);
3694
+ for (const name of referencedNames(remount, removed)) {
3695
+ stripped.retained.add(name);
3696
+ }
3697
+ replaceRange(module, range.start, range.end, `.config({ ${policy} })`);
3698
+ } else {
3699
+ removeRange(module, range.start, range.end);
3700
+ }
3701
+ }
3702
+ function removeChainedServerCalls(module, bindings, chains, stripped) {
3703
+ const { filename, program, source } = module;
3704
+ let transformed = rewriteClientImports(source, program, bindings);
3705
+ const { declarations } = collectModuleBindings(program);
3706
+ for (const { call, object, property } of chains.serverStages) {
3707
+ if (isRemoved(call, module.removed)) {
3708
+ continue;
3709
+ }
3710
+ let remount = null;
3711
+ if (property.name === "config" && Array.isArray(call.arguments)) {
3712
+ const config = unwrapped(call.arguments[0]);
3713
+ if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
3714
+ collectConfigBindings(config, declarations, stripped.configBindings);
3715
+ remount = resolveRemountProperty(config, declarations, stripped.configBindings, new Set, filename);
3716
+ }
3717
+ }
3718
+ const accessStart = memberAccessStart(source.original, object, property);
3719
+ stripServerStage(module, stripped, { end: call.end, start: accessStart }, remount);
3720
+ transformed = true;
3721
+ }
3187
3722
  return transformed;
3188
3723
  }
3724
+ function declaredInitializer(declaration) {
3725
+ return declaration?.type === "VariableDeclarator" ? unwrapped(declaration.init) : null;
3726
+ }
3189
3727
  function collectConfigBindings(config, declarations, names) {
3190
- if (config?.type === "Identifier" && typeof config.name === "string" && !names.has(config.name)) {
3728
+ if (config?.type === "Identifier" && !names.has(config.name)) {
3191
3729
  names.add(config.name);
3192
3730
  const declaration = declarations.get(config.name);
3193
- collectConfigBindings(asAstNode(declaration?.init), declarations, names);
3731
+ collectConfigBindings(declaredInitializer(declaration), declarations, names);
3194
3732
  } else if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
3195
3733
  for (const property of config.properties) {
3196
- const entry = asAstNode(property);
3734
+ const entry = unwrapped(property);
3197
3735
  if (entry?.type === "SpreadElement") {
3198
- collectConfigBindings(asAstNode(entry.argument), declarations, names);
3736
+ collectConfigBindings(unwrapped(entry.argument), declarations, names);
3199
3737
  }
3200
3738
  }
3201
3739
  }
3202
3740
  }
3203
3741
  function resolveRemountProperty(config, declarations, configBindings, visiting, filename) {
3204
- if (config?.type === "Identifier" && typeof config.name === "string" && !visiting.has(config.name)) {
3742
+ if (config?.type === "Identifier" && !visiting.has(config.name)) {
3205
3743
  visiting.add(config.name);
3206
3744
  configBindings.add(config.name);
3207
3745
  const declaration = declarations.get(config.name);
3208
- const result = resolveRemountProperty(asAstNode(declaration?.init), declarations, configBindings, visiting, filename);
3746
+ const result = resolveRemountProperty(declaredInitializer(declaration), declarations, configBindings, visiting, filename);
3209
3747
  visiting.delete(config.name);
3210
3748
  return result;
3211
3749
  }
@@ -3213,14 +3751,14 @@ function resolveRemountProperty(config, declarations, configBindings, visiting,
3213
3751
  throw new Error(`[furin] ${filename}: route config spreads must resolve to local object literals; declare remountDeps after dynamic spreads.`);
3214
3752
  }
3215
3753
  for (let index = config.properties.length - 1;index >= 0; index -= 1) {
3216
- const entry = asAstNode(config.properties[index]);
3754
+ const entry = unwrapped(config.properties[index]);
3217
3755
  if (entry?.type === "SpreadElement") {
3218
- const remount = resolveRemountProperty(asAstNode(entry.argument), declarations, configBindings, visiting, filename);
3756
+ const remount = resolveRemountProperty(unwrapped(entry.argument), declarations, configBindings, visiting, filename);
3219
3757
  if (remount) {
3220
3758
  return remount;
3221
3759
  }
3222
3760
  } else if (entry?.type === "Property") {
3223
- const key = asAstNode(entry.key);
3761
+ const key = unwrapped(entry.key);
3224
3762
  if (key?.type === "Identifier" && entry.computed !== true && key.name === "remountDeps" || key?.type === "Literal" && key.value === "remountDeps") {
3225
3763
  return entry;
3226
3764
  }
@@ -3228,518 +3766,487 @@ function resolveRemountProperty(config, declarations, configBindings, visiting,
3228
3766
  }
3229
3767
  return null;
3230
3768
  }
3231
- function pruneUnusedConfigBindings(source, filename, names) {
3232
- let result = source;
3233
- let pruned = true;
3234
- while (pruned) {
3235
- pruned = false;
3236
- const code = result.toString();
3237
- const { program } = parseSource(code, detectLangFromPath(filename));
3238
- const references = new Set;
3239
- walkWithAncestors(program, [], (node, ancestors) => {
3240
- if (node.type === "Identifier" && typeof node.name === "string" && isReferenceIdentifier(node, ancestors)) {
3241
- references.add(node.name);
3769
+
3770
+ // src/plugin/transform-client-module.ts
3771
+ import { realpathSync } from "fs";
3772
+ import { dirname as dirname3 } from "path";
3773
+ var FURIN_CLIENT_MODULES2 = new Set(["@teyik0/furin/client", "furin/client"]);
3774
+ var SERVER_LOAD = '() => Promise.reject(new Error("[furin] clientModule() can only be loaded in the browser."))';
3775
+ function clientModuleKey(modulePath) {
3776
+ const realPath = realpathSync(modulePath).replaceAll("\\", "/");
3777
+ return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
3778
+ }
3779
+ function collectClientModuleBindings(program) {
3780
+ const bindings = new Set;
3781
+ for (const statement of program.body) {
3782
+ if (statement.type !== "ImportDeclaration") {
3783
+ continue;
3784
+ }
3785
+ if (statement.importKind === "type" || !FURIN_CLIENT_MODULES2.has(String(statement.source.value))) {
3786
+ continue;
3787
+ }
3788
+ for (const specifier of statement.specifiers) {
3789
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && specifier.imported.type === "Identifier" && specifier.imported.name === "clientModule") {
3790
+ bindings.add(specifier.local.name);
3791
+ }
3792
+ }
3793
+ }
3794
+ return bindings;
3795
+ }
3796
+ function dynamicImportSpecifier(loader) {
3797
+ if (loader.type !== "ArrowFunctionExpression" || loader.params.length > 0) {
3798
+ return null;
3799
+ }
3800
+ const { body } = loader;
3801
+ const source = body.type === "ImportExpression" ? body.source : null;
3802
+ return source?.type === "Literal" && typeof source.value === "string" ? source.value : null;
3803
+ }
3804
+ function rewriteClientModules(module, environment) {
3805
+ const { filename, program, source } = module;
3806
+ if (!module.code.includes("clientModule")) {
3807
+ return false;
3808
+ }
3809
+ const bindings = collectClientModuleBindings(program);
3810
+ if (bindings.size === 0) {
3811
+ return false;
3812
+ }
3813
+ let rewritten = false;
3814
+ walk(program, {
3815
+ CallExpression(call, context) {
3816
+ const [loader, ...rest] = call.arguments;
3817
+ if (call.callee.type !== "Identifier" || !bindings.has(call.callee.name) || hasShadowingDeclaration(call.callee.name, context.ancestors()) || !loader || rest.length > 0) {
3818
+ return;
3819
+ }
3820
+ const unwrapped = unwrapTSExpression(loader);
3821
+ const specifier = dynamicImportSpecifier(unwrapped);
3822
+ if (specifier === null) {
3823
+ return;
3242
3824
  }
3243
- });
3244
- result = new MagicString(code);
3245
- for (const statement of program.body) {
3246
- if (statement.type !== "VariableDeclaration") {
3247
- continue;
3825
+ let key;
3826
+ try {
3827
+ key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname3(filename))));
3828
+ } catch (error) {
3829
+ throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
3248
3830
  }
3249
- const retained = statement.declarations.filter((declaration) => declaration.id.type !== "Identifier" || !names.has(declaration.id.name) || references.has(declaration.id.name));
3250
- if (retained.length !== statement.declarations.length) {
3251
- result.update(statement.start, statement.end, retained.length ? `${statement.kind} ${retained.map((node) => code.slice(node.start, node.end)).join(", ")};` : "");
3252
- pruned = true;
3831
+ if (environment === "client") {
3832
+ source.appendLeft(loader.end, `, ${key}`);
3833
+ } else {
3834
+ replaceRange(module, loader.start, loader.end, `${SERVER_LOAD}, ${key}`);
3253
3835
  }
3836
+ rewritten = true;
3254
3837
  }
3255
- }
3256
- return result;
3838
+ });
3839
+ return rewritten;
3257
3840
  }
3258
- function collectBindingNames(pattern, names) {
3259
- const node = asAstNode(pattern);
3260
- if (!node) {
3261
- return;
3262
- }
3263
- if (node.type === "Identifier" && typeof node.name === "string") {
3264
- names.push(node.name);
3265
- return;
3266
- }
3267
- if (node.type === "AssignmentPattern") {
3268
- collectBindingNames(node.left, names);
3841
+
3842
+ // src/plugin/transform-isomorphic.ts
3843
+ var FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
3844
+ function importedName2(specifier) {
3845
+ const { imported } = specifier;
3846
+ return imported.type === "Identifier" ? imported.name : imported.value;
3847
+ }
3848
+ function addImportSpecifier(specifier, bindings) {
3849
+ const local = specifier.local.name;
3850
+ if (specifier.type === "ImportNamespaceSpecifier") {
3851
+ bindings.namespaces.add(local);
3269
3852
  return;
3270
3853
  }
3271
- if (node.type === "RestElement") {
3272
- collectBindingNames(node.argument, names);
3273
- return;
3854
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && importedName2(specifier) === "createIsomorphicFn") {
3855
+ bindings.named.add(local);
3274
3856
  }
3275
- if (node.type === "ArrayPattern" && Array.isArray(node.elements)) {
3276
- for (const element of node.elements) {
3277
- collectBindingNames(element, names);
3857
+ }
3858
+ function collectBindings(program) {
3859
+ const bindings = {
3860
+ constants: [],
3861
+ constantsByName: new Map,
3862
+ named: new Set,
3863
+ namespaces: new Set
3864
+ };
3865
+ for (const statement of program.body) {
3866
+ if (statement.type !== "ImportDeclaration") {
3867
+ continue;
3278
3868
  }
3279
- return;
3280
- }
3281
- if (node.type === "ObjectPattern" && Array.isArray(node.properties)) {
3282
- for (const property of node.properties) {
3283
- const propertyNode = asAstNode(property);
3284
- collectBindingNames(propertyNode?.type === "Property" ? propertyNode.value : propertyNode?.argument, names);
3869
+ if (statement.importKind === "type" || !FURIN_MODULES.has(statement.source.value)) {
3870
+ continue;
3285
3871
  }
3286
- }
3287
- }
3288
- function collectDeclarationBindings(declaration, declarations) {
3289
- if (declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") {
3290
- const identifier = asAstNode(declaration.id);
3291
- if (identifier?.type === "Identifier" && typeof identifier.name === "string") {
3292
- declarations.set(identifier.name, declaration);
3872
+ for (const specifier of statement.specifiers) {
3873
+ addImportSpecifier(specifier, bindings);
3293
3874
  }
3294
- return;
3295
3875
  }
3296
- if (declaration?.type !== "VariableDeclaration" || !Array.isArray(declaration.declarations)) {
3297
- return;
3876
+ if (bindings.named.size === 0 && bindings.namespaces.size === 0) {
3877
+ return bindings;
3298
3878
  }
3299
- for (const item of declaration.declarations) {
3300
- const names = [];
3301
- collectBindingNames(item.id, names);
3302
- for (const name of names) {
3303
- declarations.set(name, item);
3879
+ walk(program, {
3880
+ VariableDeclarator(node, context) {
3881
+ const ancestors = context.ancestors();
3882
+ const declaration = ancestors.at(-1);
3883
+ const scope = lexicalBindingScope(ancestors);
3884
+ if (declaration?.type !== "VariableDeclaration" || declaration.kind !== "const" || node.id.type !== "Identifier" || !node.init || !scope) {
3885
+ return;
3886
+ }
3887
+ const binding = {
3888
+ ancestors,
3889
+ declaration: node,
3890
+ initializer: node.init,
3891
+ name: node.id.name,
3892
+ scope,
3893
+ statement: declaration
3894
+ };
3895
+ bindings.constants.push(binding);
3896
+ const constants = bindings.constantsByName.get(binding.name) ?? [];
3897
+ constants.push(binding);
3898
+ bindings.constantsByName.set(binding.name, constants);
3304
3899
  }
3305
- }
3900
+ });
3901
+ return bindings;
3306
3902
  }
3307
- function collectModuleBindings(program) {
3308
- const declarations = new Map;
3309
- const imports = new Map;
3310
- for (const statement of program.body) {
3311
- if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
3312
- for (const specifier of statement.specifiers) {
3313
- const local = localName2(specifier);
3314
- if (local) {
3315
- imports.set(local, statement);
3316
- }
3317
- }
3318
- continue;
3903
+ function resolveConstant(name, bindings, ancestors) {
3904
+ let match;
3905
+ let scopeIndex = -1;
3906
+ const constants = bindings.constantsByName.get(name);
3907
+ if (!constants) {
3908
+ return;
3909
+ }
3910
+ for (const binding of constants) {
3911
+ const index = ancestors.lastIndexOf(binding.scope);
3912
+ if (index > scopeIndex) {
3913
+ match = binding;
3914
+ scopeIndex = index;
3319
3915
  }
3320
- const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? asAstNode(statement.declaration) : statement;
3321
- collectDeclarationBindings(declaration, declarations);
3322
3916
  }
3323
- return { declarations, imports };
3917
+ return match && !hasShadowingDeclaration(name, ancestors.slice(scopeIndex + 1)) ? match : undefined;
3324
3918
  }
3325
- function isBindingIdentifier(identifier, pattern) {
3326
- const node = asAstNode(pattern);
3327
- if (!node) {
3328
- return false;
3919
+ function resolveStaticString(expression, bindings, ancestors, seen) {
3920
+ const node = unwrapTSExpression(expression);
3921
+ if (node.type === "Literal" && typeof node.value === "string") {
3922
+ return node.value;
3329
3923
  }
3330
3924
  if (node.type === "Identifier") {
3331
- return node.start === identifier.start && node.end === identifier.end;
3332
- }
3333
- if (node.type === "AssignmentPattern") {
3334
- return isBindingIdentifier(identifier, node.left);
3335
- }
3336
- if (node.type === "RestElement") {
3337
- return isBindingIdentifier(identifier, node.argument);
3338
- }
3339
- if (node.type === "ArrayPattern" && Array.isArray(node.elements)) {
3340
- return node.elements.some((element) => isBindingIdentifier(identifier, element));
3341
- }
3342
- if (node.type === "ObjectPattern" && Array.isArray(node.properties)) {
3343
- return node.properties.some((property) => {
3344
- const propertyNode = asAstNode(property);
3345
- return isBindingIdentifier(identifier, propertyNode?.type === "Property" ? propertyNode.value : propertyNode?.argument);
3346
- });
3925
+ const binding = resolveConstant(node.name, bindings, ancestors);
3926
+ if (binding && !seen.has(binding)) {
3927
+ seen.add(binding);
3928
+ return resolveStaticString(binding.initializer, bindings, binding.ancestors, seen);
3929
+ }
3347
3930
  }
3348
- return false;
3349
3931
  }
3350
- function nodeContains(container, node) {
3351
- if (Array.isArray(container)) {
3352
- return container.some((entry) => nodeContains(entry, node));
3932
+ function isCreateIsomorphicCall(node, bindings, ancestors) {
3933
+ if (node.type !== "CallExpression") {
3934
+ return false;
3353
3935
  }
3354
- const containerNode = asAstNode(container);
3355
- return Boolean(containerNode && containerNode.start <= node.start && node.end <= containerNode.end);
3936
+ return isFactoryExpression(node.callee, bindings, ancestors, new Set);
3356
3937
  }
3357
- function isTypePosition(node, ancestors) {
3358
- return ancestors.some((ancestor) => {
3359
- if (!ancestor.type.startsWith("TS")) {
3360
- return false;
3361
- }
3362
- const runtimeChildren = TYPESCRIPT_RUNTIME_WRAPPERS.get(ancestor.type);
3363
- if (runtimeChildren) {
3364
- return !runtimeChildren.some((key) => nodeContains(ancestor[key], node));
3365
- }
3938
+ function isFactoryExpression(expression, bindings, ancestors, seen) {
3939
+ const callee = unwrapTSExpression(expression);
3940
+ if (callee.type === "Identifier" && bindings.named.has(callee.name) && !hasShadowingDeclaration(callee.name, ancestors)) {
3366
3941
  return true;
3367
- });
3368
- }
3369
- function isNonReferenceKey(node, parent) {
3370
- return Boolean(parent && (parent.type === "MemberExpression" && parent.computed !== true && parent.property === node || parent.type === "Property" && parent.computed !== true && parent.shorthand !== true && parent.key === node || (parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.computed !== true && parent.key === node || (parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement") && parent.label === node));
3371
- }
3372
- function isReferenceIdentifier(node, ancestors) {
3373
- if (isTypePosition(node, ancestors) || isNonReferenceKey(node, ancestors.at(-1))) {
3374
- return false;
3375
3942
  }
3376
- for (const ancestor of ancestors) {
3377
- if (ancestor.type === "VariableDeclarator" && isBindingIdentifier(node, ancestor.id) || (ancestor.type === "FunctionDeclaration" || ancestor.type === "FunctionExpression" || ancestor.type === "ArrowFunctionExpression") && (isBindingIdentifier(node, ancestor.id) || Array.isArray(ancestor.params) && ancestor.params.some((parameter) => isBindingIdentifier(node, parameter))) || ancestor.type === "ClassDeclaration" && isBindingIdentifier(node, ancestor.id) || ancestor.type === "CatchClause" && isBindingIdentifier(node, ancestor.param)) {
3378
- return false;
3943
+ if (callee.type === "Identifier") {
3944
+ const binding = resolveConstant(callee.name, bindings, ancestors);
3945
+ if (binding && !seen.has(binding)) {
3946
+ seen.add(binding);
3947
+ return isFactoryExpression(binding.initializer, bindings, binding.ancestors, seen);
3379
3948
  }
3380
3949
  }
3381
- return true;
3950
+ return callee.type === "MemberExpression" && callee.object.type === "Identifier" && bindings.namespaces.has(callee.object.name) && !hasShadowingDeclaration(callee.object.name, ancestors) && (callee.computed ? resolveStaticString(callee.property, bindings, ancestors, new Set) === "createIsomorphicFn" : callee.property.type === "Identifier" && callee.property.name === "createIsomorphicFn");
3382
3951
  }
3383
- function walkWithAncestors(value, ancestors, visitor) {
3384
- if (Array.isArray(value)) {
3385
- for (const entry of value) {
3386
- walkWithAncestors(entry, ancestors, visitor);
3387
- }
3952
+ function environmentMethod(node, bindings, ancestors) {
3953
+ if (node.type !== "CallExpression") {
3388
3954
  return;
3389
3955
  }
3390
- const node = asAstNode(value);
3391
- if (!node) {
3956
+ const { callee } = node;
3957
+ if (callee.type !== "MemberExpression") {
3392
3958
  return;
3393
3959
  }
3394
- visitor(node, ancestors);
3395
- const nextAncestors = [...ancestors, node];
3396
- for (const [key, child] of Object.entries(node)) {
3397
- if (key !== "type" && key !== "start" && key !== "end" && key !== "comments") {
3398
- walkWithAncestors(child, nextAncestors, visitor);
3399
- }
3960
+ let method;
3961
+ if (callee.computed) {
3962
+ method = resolveStaticString(callee.property, bindings, ancestors, new Set);
3963
+ } else if (callee.property.type === "Identifier") {
3964
+ method = callee.property.name;
3400
3965
  }
3966
+ return method === "client" || method === "server" ? method : undefined;
3401
3967
  }
3402
- function collectDependencyIdentifier(child, ancestors, trackImports, state) {
3403
- const parent = ancestors.at(-1);
3404
- const jsxReference = child.type === "JSXIdentifier" && (parent?.type === "JSXOpeningElement" && parent.name === child && typeof child.name === "string" && child.name[0] === child.name[0]?.toUpperCase() || parent?.type === "JSXMemberExpression" && parent.object === child);
3405
- if (!(child.type === "Identifier" || jsxReference) || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
3406
- return;
3407
- }
3408
- const declaration = state.moduleBindings.declarations.get(child.name);
3409
- if (!declaration) {
3410
- const imported = state.moduleBindings.imports.get(child.name);
3411
- if (trackImports && imported) {
3412
- state.imports.add(imported);
3968
+ function parseCandidate(source, filename, node, bindings, ancestors) {
3969
+ let current = node;
3970
+ let client;
3971
+ let server;
3972
+ for (;; ) {
3973
+ const method = environmentMethod(current, bindings, ancestors);
3974
+ if (!method || current.type !== "CallExpression") {
3975
+ break;
3413
3976
  }
3414
- return;
3415
- }
3416
- const alreadyTracked = state.dependencies.has(declaration.start);
3417
- if (!alreadyTracked) {
3418
- state.dependencies.set(declaration.start, declaration);
3419
- }
3420
- if (trackImports) {
3421
- if (state.importTrackedDependencies.has(declaration.start)) {
3422
- return;
3977
+ if (current.callee.type !== "MemberExpression") {
3978
+ return null;
3423
3979
  }
3424
- state.importTrackedDependencies.add(declaration.start);
3425
- } else if (alreadyTracked) {
3426
- return;
3980
+ const [implementation] = current.arguments;
3981
+ if (!implementation) {
3982
+ return null;
3983
+ }
3984
+ if (method === "client") {
3985
+ client ??= implementation;
3986
+ } else {
3987
+ server ??= implementation;
3988
+ }
3989
+ current = unwrapTSExpression(current.callee.object);
3427
3990
  }
3428
- collectDependencies(declaration, trackImports, state);
3429
- }
3430
- function collectDependencies(node, trackImports, state) {
3431
- walkWithAncestors(node, [], (child, ancestors) => {
3432
- collectDependencyIdentifier(child, ancestors, trackImports, state);
3433
- if (trackImports && child.type === "ImportExpression") {
3434
- const specifier = asAstNode(child.source)?.value;
3435
- if (typeof specifier === "string") {
3436
- state.dynamicImports.add(specifier);
3437
- }
3991
+ if (!isCreateIsomorphicCall(current, bindings, ancestors)) {
3992
+ return null;
3993
+ }
3994
+ for (const [method, implementation] of [
3995
+ ["client", client],
3996
+ ["server", server]
3997
+ ]) {
3998
+ if (!implementation) {
3999
+ continue;
3438
4000
  }
3439
- });
3440
- }
3441
- function createHmrDataSignature(code, program, bindings, filename) {
3442
- const serverStages = [];
3443
- const dependencyState = {
3444
- dependencies: new Map,
3445
- dynamicImports: new Set,
3446
- imports: new Set,
3447
- importTrackedDependencies: new Set,
3448
- moduleBindings: collectModuleBindings(program)
3449
- };
3450
- walk(program, {
3451
- CallExpression(call, context) {
3452
- const callee = asAstNode(call.callee);
3453
- if (callee?.type !== "MemberExpression" || callee.computed === true || !callee.property || typeof callee.property !== "object") {
3454
- return;
3455
- }
3456
- const property = callee.property;
3457
- if (property.type !== "Identifier" || typeof property.name !== "string" || !SERVER_ONLY_METHODS.has(property.name) || !chainRootIsDefineRoute(callee.object, bindings, context.ancestors())) {
3458
- return;
3459
- }
3460
- const object = asAstNode(callee.object);
3461
- if (!object) {
3462
- return;
3463
- }
3464
- serverStages.push({
3465
- source: code.slice(object.end, call.end),
3466
- start: call.start
3467
- });
3468
- if (Array.isArray(call.arguments)) {
3469
- for (const argument of call.arguments) {
3470
- const argumentNode = asAstNode(argument);
3471
- if (argumentNode) {
3472
- collectDependencies(argumentNode, property.name !== "config", dependencyState);
3473
- }
3474
- }
3475
- }
4001
+ const unwrapped = unwrapTSExpression(implementation);
4002
+ if (unwrapped.type !== "ArrowFunctionExpression" && unwrapped.type !== "FunctionExpression" && unwrapped.type !== "Identifier") {
4003
+ throw new Error(`[furin] ${filename}:${sourcePosition(source, implementation.start)} createIsomorphicFn().${method}() must receive a function.`);
3476
4004
  }
3477
- });
3478
- const dataSource = [
3479
- ...serverStages,
3480
- ...[...dependencyState.imports].map((imported) => ({
3481
- source: code.slice(imported.start, imported.end),
3482
- start: imported.start
3483
- })),
3484
- ...[...dependencyState.dependencies.values()].map((dependency) => ({
3485
- source: code.slice(dependency.start, dependency.end),
3486
- start: dependency.start
3487
- }))
3488
- ].sort((left, right) => left.start - right.start).map((entry) => entry.source).join(`
3489
- `);
3490
- const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
3491
- if (dependencyState.imports.size === 0 && dependencyState.dynamicImports.size === 0) {
3492
- return hash;
3493
4005
  }
3494
- const dependencies = hmrDependencySignature(new Set([
3495
- ...[...dependencyState.imports].map((imported) => imported.source.value),
3496
- ...dependencyState.dynamicImports
3497
- ]), filename);
3498
- return dependencies === undefined ? `external:${hash}` : `imports:${hash}:${dependencies}`;
4006
+ return {
4007
+ client,
4008
+ end: node.end,
4009
+ server,
4010
+ start: node.start
4011
+ };
3499
4012
  }
3500
- function calledHookName(call) {
3501
- const callee = asAstNode(call.callee);
3502
- if (callee?.type === "Identifier" && typeof callee.name === "string") {
3503
- return REACT_HOOK_NAME_RE.test(callee.name) ? callee.name : null;
3504
- }
3505
- if (callee?.type === "MemberExpression" && callee.computed !== true && callee.property && typeof callee.property === "object") {
3506
- const property = callee.property;
3507
- if (property.type === "Identifier" && typeof property.name === "string" && REACT_HOOK_NAME_RE.test(property.name)) {
3508
- return property.name;
4013
+ function collectCandidates(source, filename, program, bindings) {
4014
+ const candidates = [];
4015
+ walk(program, {
4016
+ CallExpression(node, context) {
4017
+ const candidate = parseCandidate(source, filename, node, bindings, context.ancestors());
4018
+ if (candidate) {
4019
+ candidates.push(candidate);
4020
+ }
3509
4021
  }
3510
- }
3511
- return null;
4022
+ });
4023
+ return candidates.toSorted((left, right) => left.start - right.start || right.end - left.end);
4024
+ }
4025
+ function sourcePosition(source, offset) {
4026
+ const before = source.slice(0, offset);
4027
+ const line = before.split(`
4028
+ `).length;
4029
+ const lastNewline = before.lastIndexOf(`
4030
+ `);
4031
+ return `${line}:${offset - lastNewline}`;
3512
4032
  }
3513
- function routeComponentExpression(program, bindings) {
3514
- let component = null;
4033
+ function collectBuilderBindings(program, bindings) {
4034
+ const builders = [];
3515
4035
  walk(program, {
3516
- CallExpression(call, context) {
3517
- const callee = asAstNode(call.callee);
3518
- if (callee?.type !== "MemberExpression" || callee.computed === true || !callee.property || typeof callee.property !== "object") {
4036
+ VariableDeclarator(node, context) {
4037
+ if (!node.init) {
3519
4038
  return;
3520
4039
  }
3521
- const property = callee.property;
4040
+ const identifier = node.id;
4041
+ const initializer = unwrapTSExpression(node.init);
3522
4042
  const ancestors = context.ancestors();
3523
- const routeDeclarator = ancestors.find((ancestor) => {
3524
- if (ancestor.type !== "VariableDeclarator") {
3525
- return false;
3526
- }
3527
- const identifier = asAstNode(ancestor.id);
3528
- return identifier?.type === "Identifier" && identifier.name === "route";
3529
- });
3530
- if (!(routeDeclarator && ancestors.some((ancestor) => ancestor.type === "ExportNamedDeclaration")) || property.type !== "Identifier" || property.name !== "page" && property.name !== "layout" || !chainRootIsDefineRoute(callee.object, bindings, ancestors)) {
3531
- return;
4043
+ const declaration = ancestors.at(-1);
4044
+ const scope = declaration?.type === "VariableDeclaration" && declaration.kind === "var" ? varBindingScope(ancestors) : lexicalBindingScope(ancestors);
4045
+ if (scope && identifier.type === "Identifier" && isCreateIsomorphicCall(initializer, bindings, ancestors)) {
4046
+ builders.push({ name: identifier.name, scope });
3532
4047
  }
3533
- const args = call.arguments;
3534
- component = Array.isArray(args) ? asAstNode(args[0]) : null;
3535
- context.stop();
3536
4048
  }
3537
4049
  });
3538
- return component;
4050
+ return builders;
3539
4051
  }
3540
- function namedFunction(declaration, name) {
3541
- if (declaration.type === "FunctionDeclaration") {
3542
- const identifier = asAstNode(declaration.id);
3543
- return identifier?.type === "Identifier" && identifier.name === name ? declaration : null;
4052
+ function hasVisibleBuilder(name, ancestors, builders) {
4053
+ let scopeIndex = -1;
4054
+ for (const builder of builders) {
4055
+ if (builder.name === name) {
4056
+ scopeIndex = Math.max(scopeIndex, ancestors.lastIndexOf(builder.scope));
4057
+ }
3544
4058
  }
3545
- if (declaration.type === "VariableDeclaration" && Array.isArray(declaration.declarations)) {
3546
- for (const item of declaration.declarations) {
3547
- const identifier = asAstNode(item.id);
3548
- const initializer = asAstNode(item.init);
3549
- if (identifier?.type === "Identifier" && identifier.name === name && (initializer?.type === "ArrowFunctionExpression" || initializer?.type === "FunctionExpression")) {
3550
- return initializer;
4059
+ return scopeIndex >= 0 && !hasShadowingDeclaration(name, ancestors.slice(scopeIndex + 1));
4060
+ }
4061
+ function assertNoSplitChains(source, filename, program, builders) {
4062
+ if (builders.length === 0) {
4063
+ return;
4064
+ }
4065
+ walk(program, {
4066
+ MemberExpression(node, context) {
4067
+ if (node.computed || node.object.type !== "Identifier" || !hasVisibleBuilder(node.object.name, context.ancestors(), builders) || node.property.type !== "Identifier" || node.property.name !== "server" && node.property.name !== "client") {
4068
+ return;
3551
4069
  }
4070
+ throw new Error(`[furin] ${filename}:${sourcePosition(source, node.start)} createIsomorphicFn() must use one fluent chain.`);
3552
4071
  }
3553
- }
3554
- return null;
4072
+ });
3555
4073
  }
3556
- function localFunction(program, name) {
3557
- for (const statement of program.body) {
3558
- const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? asAstNode(statement.declaration) : statement;
3559
- const component = declaration ? namedFunction(declaration, name) : null;
3560
- if (component) {
3561
- return component;
4074
+ function chainStartsWithCreateIsomorphicFn(expression, bindings, ancestors) {
4075
+ let current = unwrapTSExpression(expression);
4076
+ for (;; ) {
4077
+ if (isCreateIsomorphicCall(current, bindings, ancestors)) {
4078
+ return true;
4079
+ }
4080
+ if (current.type !== "CallExpression" || !environmentMethod(current, bindings, ancestors)) {
4081
+ return false;
4082
+ }
4083
+ if (current.callee.type !== "MemberExpression") {
4084
+ return false;
3562
4085
  }
4086
+ current = unwrapTSExpression(current.callee.object);
3563
4087
  }
3564
- return null;
3565
4088
  }
3566
- function isImportedBinding(program, name) {
3567
- return program.body.some((statement) => statement.type === "ImportDeclaration" && statement.importKind !== "type" && statement.specifiers.some((specifier) => specifier.importKind !== "type" && localName2(specifier) === name));
3568
- }
3569
- function collectReactWrapperBindings(program) {
3570
- const bindings = {
3571
- members: new Set,
3572
- namespaces: new Set
3573
- };
3574
- for (const statement of program.body) {
3575
- if (statement.type !== "ImportDeclaration" || statement.source.value !== "react") {
3576
- continue;
3577
- }
3578
- for (const specifier of statement.specifiers) {
3579
- const local = localName2(specifier);
3580
- if (!local || specifier.importKind === "type") {
3581
- continue;
4089
+ function assertStaticEnvironmentMethods(source, filename, program, bindings, builders) {
4090
+ walk(program, {
4091
+ MemberExpression(node, context) {
4092
+ if (!node.computed) {
4093
+ return;
3582
4094
  }
3583
- const imported = importedName2(specifier);
3584
- if (specifier.type === "ImportSpecifier" && imported && REACT_COMPONENT_WRAPPERS.has(imported)) {
3585
- bindings.members.add(local);
3586
- } else if (specifier.type === "ImportDefaultSpecifier" || specifier.type === "ImportNamespaceSpecifier" || specifier.type === "ImportSpecifier" && imported === "default") {
3587
- bindings.namespaces.add(local);
4095
+ const ancestors = context.ancestors();
4096
+ const splitBuilder = node.object.type === "Identifier" && hasVisibleBuilder(node.object.name, ancestors, builders);
4097
+ if (!(splitBuilder || chainStartsWithCreateIsomorphicFn(node.object, bindings, ancestors))) {
4098
+ return;
3588
4099
  }
4100
+ const method = resolveStaticString(node.property, bindings, ancestors, new Set);
4101
+ if (!splitBuilder && (method === "server" || method === "client")) {
4102
+ return;
4103
+ }
4104
+ throw new Error(`[furin] ${filename}:${sourcePosition(source, node.start)} createIsomorphicFn() requires static .server() and .client() methods.`);
3589
4105
  }
3590
- }
3591
- return bindings;
4106
+ });
3592
4107
  }
3593
- function wrappedComponentFunction(program, expression, bindings) {
3594
- if (expression.type === "ArrowFunctionExpression" || expression.type === "FunctionExpression") {
3595
- return expression;
3596
- }
3597
- if (expression.type === "Identifier" && typeof expression.name === "string") {
3598
- return localFunction(program, expression.name);
3599
- }
3600
- if (expression.type !== "CallExpression") {
3601
- return null;
3602
- }
3603
- const callee = asAstNode(expression.callee);
3604
- const isNamedWrapper = callee?.type === "Identifier" && typeof callee.name === "string" && bindings.members.has(callee.name);
3605
- const object = callee?.type === "MemberExpression" ? asAstNode(callee.object) : null;
3606
- const property = callee?.type === "MemberExpression" ? asAstNode(callee.property) : null;
3607
- const isNamespaceWrapper = callee?.type === "MemberExpression" && callee.computed !== true && object?.type === "Identifier" && typeof object.name === "string" && bindings.namespaces.has(object.name) && property?.type === "Identifier" && typeof property.name === "string" && REACT_COMPONENT_WRAPPERS.has(property.name);
3608
- if (!(isNamedWrapper || isNamespaceWrapper)) {
3609
- return null;
4108
+ function assertStaticNamespaceUse(node, bindings, ancestors, filename) {
4109
+ if (!(node.type === "Identifier" && bindings.namespaces.has(node.name) && !hasShadowingDeclaration(node.name, ancestors))) {
4110
+ return;
3610
4111
  }
3611
- const args = expression.arguments;
3612
- const wrapped = Array.isArray(args) ? asAstNode(args[0]) : null;
3613
- return wrapped ? wrappedComponentFunction(program, wrapped, bindings) : null;
3614
- }
3615
- function importedMemberBinding(program, expression) {
3616
- let object = expression.type === "MemberExpression" ? asAstNode(expression.object) : null;
3617
- while (object?.type === "MemberExpression") {
3618
- object = asAstNode(object.object);
4112
+ const parent = ancestors.at(-1);
4113
+ if (parent?.type === "MemberExpression" && parent.object === node && (!parent.computed || resolveStaticString(parent.property, bindings, ancestors, new Set) !== undefined)) {
4114
+ return;
3619
4115
  }
3620
- return object?.type === "Identifier" && typeof object.name === "string" && isImportedBinding(program, object.name) ? object.name : null;
3621
- }
3622
- function sourceText(code, node) {
3623
- return node ? code.slice(node.start, node.end) : "";
4116
+ throw new Error(`[furin] ${filename}: Furin namespace imports must use direct static member access so createIsomorphicFn can be compiled. Use a named import instead of escaping the namespace.`);
3624
4117
  }
3625
- function unusedIdentifier(program, preferred) {
3626
- const identifiers = new Set;
4118
+ function assertResolvedFactoryUses(program, bindings, filename) {
4119
+ const inspect = (node, ancestors) => {
4120
+ const parent = ancestors.at(-1);
4121
+ if (parent?.type === "ImportSpecifier" || parent?.type === "ImportNamespaceSpecifier" || parent?.type === "VariableDeclarator" && parent.id === node || parent?.type === "MemberExpression" && !parent.computed && parent.property === node || parent?.type === "Property" && !parent.computed && !parent.shorthand && parent.key === node || ancestors.some((ancestor) => ancestor.type === "TSTypeQuery" || ancestor.type === "TSTypeReference")) {
4122
+ return;
4123
+ }
4124
+ assertStaticNamespaceUse(node, bindings, ancestors, filename);
4125
+ if (!isFactoryExpression(node, bindings, ancestors, new Set)) {
4126
+ return;
4127
+ }
4128
+ let expression = node;
4129
+ let index = ancestors.length - 1;
4130
+ let wrapper = ancestors[index];
4131
+ while (wrapper && unwrapTSExpression(wrapper) === expression) {
4132
+ expression = wrapper;
4133
+ index -= 1;
4134
+ wrapper = ancestors[index];
4135
+ }
4136
+ const owner = ancestors[index];
4137
+ if (owner?.type === "CallExpression" && owner.callee === expression) {
4138
+ return;
4139
+ }
4140
+ const declaration = ancestors[index - 1];
4141
+ if (owner?.type === "VariableDeclarator" && owner.init === expression && owner.id.type === "Identifier" && declaration?.type === "VariableDeclaration" && declaration.kind === "const") {
4142
+ return;
4143
+ }
4144
+ throw new Error(`[furin] ${filename}: createIsomorphicFn references must stay in statically resolvable fluent chains or constant aliases.`);
4145
+ };
3627
4146
  walk(program, {
3628
- Identifier(node) {
3629
- identifiers.add(node.name);
4147
+ Identifier(node, context) {
4148
+ inspect(node, context.ancestors());
4149
+ },
4150
+ MemberExpression(node, context) {
4151
+ inspect(node, context.ancestors());
3630
4152
  }
3631
4153
  });
3632
- if (!identifiers.has(preferred)) {
3633
- return preferred;
3634
- }
3635
- let suffix = 1;
3636
- while (identifiers.has(`${preferred}_${suffix}`)) {
3637
- suffix += 1;
3638
- }
3639
- return `${preferred}_${suffix}`;
3640
4154
  }
3641
- function hookCallsiteSignature(code, call, hookName, parent) {
3642
- let key = parent?.type === "VariableDeclarator" ? sourceText(code, asAstNode(parent.id)) : "";
3643
- const args = call.arguments;
3644
- const stateArgument = Array.isArray(args) ? asAstNode(args[0]) : null;
3645
- const reducerArgument = Array.isArray(args) ? asAstNode(args[1]) : null;
3646
- if (hookName === "useState" && stateArgument) {
3647
- key += `(${sourceText(code, stateArgument)})`;
3648
- } else if (hookName === "useReducer" && reducerArgument) {
3649
- key += `(${sourceText(code, reducerArgument)})`;
4155
+ function contains(outer, inner) {
4156
+ return outer.start <= inner.start && inner.end <= outer.end;
4157
+ }
4158
+ function selectImplementations(module, candidates, environment) {
4159
+ const selected = [];
4160
+ for (const candidate of candidates) {
4161
+ const enclosing = selected.findLast((entry) => contains(entry.candidate, candidate));
4162
+ if (enclosing && !(enclosing.kept && contains(enclosing.kept, candidate))) {
4163
+ continue;
4164
+ }
4165
+ const implementation = candidate[environment];
4166
+ if (implementation) {
4167
+ replaceRange(module, candidate.start, implementation.start, "(");
4168
+ replaceRange(module, implementation.end, candidate.end, ")");
4169
+ } else {
4170
+ replaceRange(module, candidate.start, candidate.end, "(() => undefined)");
4171
+ }
4172
+ selected.push({ candidate, kept: implementation });
3650
4173
  }
3651
- return `${hookName}{${key}}`;
3652
4174
  }
3653
- function collectFunctionHookSignature(code, component) {
3654
- const hooks = [];
3655
- walk(component, {
3656
- CallExpression(call, context) {
3657
- const callNode = call;
3658
- const name = calledHookName(callNode);
3659
- if (name) {
3660
- hooks.push(hookCallsiteSignature(code, callNode, name, asAstNode(context.parent)));
3661
- }
3662
- },
3663
- Function(node, context) {
3664
- if (node !== component) {
3665
- context.skip();
4175
+ function pruneFactoryAliases(module, bindings) {
4176
+ const aliases = bindings.constants.filter((binding) => binding.ancestors.at(-2)?.type !== "ExportNamedDeclaration" && isFactoryExpression(binding.initializer, bindings, binding.ancestors, new Set));
4177
+ for (;; ) {
4178
+ const used = new Set;
4179
+ walk(module.program, {
4180
+ Identifier(node, context) {
4181
+ const ancestors = context.ancestors();
4182
+ const parent = ancestors.at(-1);
4183
+ if (isRemoved(node, module.removed) || parent?.type === "VariableDeclarator" && parent.id === node || parent?.type === "MemberExpression" && !parent.computed && parent.property === node || parent?.type === "Property" && !parent.computed && !parent.shorthand && parent.key === node) {
4184
+ return;
4185
+ }
4186
+ const binding = resolveConstant(node.name, bindings, ancestors);
4187
+ if (binding) {
4188
+ used.add(binding);
4189
+ }
3666
4190
  }
4191
+ });
4192
+ const unused = aliases.filter((binding) => !(used.has(binding) || isRemoved(binding.declaration, module.removed)));
4193
+ if (unused.length === 0) {
4194
+ return;
3667
4195
  }
3668
- });
3669
- return hooks;
3670
- }
3671
- function collectClientHookSignature(code, filename) {
3672
- const lang = detectLangFromPath(filename);
3673
- const { program } = parseSource(code, lang);
3674
- const componentExpression = routeComponentExpression(program, collectDefineRouteBindings(program));
3675
- if (!componentExpression) {
3676
- return null;
3677
- }
3678
- const wrappedComponent = wrappedComponentFunction(program, componentExpression, collectReactWrapperBindings(program));
3679
- if (wrappedComponent) {
3680
- return collectFunctionHookSignature(code, wrappedComponent);
3681
- }
3682
- if (componentExpression.type !== "Identifier" || typeof componentExpression.name !== "string") {
3683
- if (importedMemberBinding(program, componentExpression)) {
3684
- return {
3685
- end: componentExpression.end,
3686
- expression: sourceText(code, componentExpression),
3687
- start: componentExpression.start
3688
- };
4196
+ for (const binding of unused) {
4197
+ removeDeclarator(module, binding.statement, binding.declaration);
3689
4198
  }
3690
- return collectFunctionHookSignature(code, componentExpression);
3691
4199
  }
3692
- const component = localFunction(program, componentExpression.name);
3693
- if (component) {
3694
- return collectFunctionHookSignature(code, component);
4200
+ }
4201
+ function selectIsomorphicFunctions(module, environment) {
4202
+ const { code: source, filename, program } = module;
4203
+ const bindings = collectBindings(program);
4204
+ if (bindings.named.size === 0 && bindings.namespaces.size === 0) {
4205
+ return false;
3695
4206
  }
3696
- return isImportedBinding(program, componentExpression.name) ? {
3697
- end: componentExpression.end,
3698
- expression: componentExpression.name,
3699
- start: componentExpression.start
3700
- } : "external";
4207
+ assertResolvedFactoryUses(program, bindings, filename);
4208
+ const builders = collectBuilderBindings(program, bindings);
4209
+ assertStaticEnvironmentMethods(source, filename, program, bindings, builders);
4210
+ assertNoSplitChains(source, filename, program, builders);
4211
+ const candidates = collectCandidates(source, filename, program, bindings);
4212
+ if (candidates.length === 0) {
4213
+ return false;
4214
+ }
4215
+ selectImplementations(module, candidates, environment);
4216
+ pruneFactoryAliases(module, bindings);
4217
+ return true;
3701
4218
  }
4219
+
4220
+ // src/plugin/transform-client.ts
4221
+ var HMR_DATA_SIGNATURE = "furin.hmr.data-signature";
4222
+ var HMR_SOURCE_SIGNATURE = "furin.hmr.source-signature";
3702
4223
  function transformForClient(code, filename) {
3703
4224
  const lang = detectLangFromPath(filename);
3704
4225
  if (lang === "dts") {
3705
- return { code, map: null, removedServerCode: false };
4226
+ return { code, removedServerCode: false };
3706
4227
  }
3707
- const isomorphicResult = transformIsomorphicFunctions(code, filename, "client");
3708
- const clientSource = isomorphicResult.code;
3709
- const { diagnostics, program } = parseSource(clientSource, lang);
3710
- const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
3711
- if (firstError) {
3712
- throw new Error(`Failed to parse ${filename}: ${firstError.message}`);
3713
- }
3714
- let source = new MagicString(clientSource);
4228
+ const module = parseModule(code, filename);
4229
+ const { program, source } = module;
4230
+ const clientModules = rewriteClientModules(module, "client");
4231
+ const isomorphic = selectIsomorphicFunctions(module, "client");
3715
4232
  const routeBindings = collectDefineRouteBindings(program);
3716
4233
  assertCompleteRouteChains(program, routeBindings, filename);
3717
- const configBindings = new Set;
3718
- const removedRouteCode = removeChainedServerCalls(source, program, routeBindings, configBindings, filename);
3719
- const removedServerCode = isomorphicResult.transformed || removedRouteCode;
4234
+ const chains = analyzeRouteChains(program, routeBindings);
4235
+ const stripped = { configBindings: new Set, retained: new Set };
4236
+ const removedRouteCode = removeChainedServerCalls(module, routeBindings, chains, stripped);
4237
+ const removedServerCode = clientModules || isomorphic || removedRouteCode;
3720
4238
  if (removedServerCode) {
3721
- if (configBindings.size > 0) {
3722
- source = pruneUnusedConfigBindings(source, filename, configBindings);
3723
- }
3724
- source = deadCodeElimination(source, code, lang);
4239
+ pruneOrphanedCode(module, stripped.configBindings, stripped.retained);
3725
4240
  }
3726
- const transformedCode = source.toString();
3727
- let hookSignature = routeBindings.size > 0 ? collectClientHookSignature(transformedCode, filename) : null;
4241
+ let hookSignature = routeBindings.size > 0 ? collectClientHookSignature(code, program, chains.component) : null;
3728
4242
  if (hookSignature && typeof hookSignature === "object" && !Array.isArray(hookSignature)) {
3729
4243
  const createElementBinding = unusedIdentifier(program, "__furinCreateElement");
3730
- source = new MagicString(transformedCode);
3731
- source.prepend(`import { createElement as ${createElementBinding} } from "react";
3732
- `);
4244
+ source.prepend(`import { createElement as ${createElementBinding} } from "react"; `);
3733
4245
  source.update(hookSignature.start, hookSignature.end, `(import.meta.hot ? (props) => ${createElementBinding}(${hookSignature.expression}, props) : ${hookSignature.expression})`);
3734
4246
  hookSignature = [];
3735
4247
  }
3736
4248
  if (routeBindings.size > 0 && hookSignature !== null) {
3737
- const originalParse = parseSource(code, lang);
3738
- const originalError = originalParse.diagnostics.find((diagnostic) => diagnostic.severity === "error");
3739
- if (originalError) {
3740
- throw new Error(`Failed to parse ${filename}: ${originalError.message}`);
3741
- }
3742
- const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program), filename);
4249
+ const hmrDataSignature = createHmrDataSignature(code, program, chains.serverStages, filename);
3743
4250
  const signatureValue = Array.isArray(hookSignature) ? JSON.stringify(hookSignature) : 'route.component[Symbol.for("furin.hmr.hook-signature")] ?? [String(route.component)]';
3744
4251
  source.append(`
3745
4252
  if (import.meta.hot && route?.component) {
@@ -3779,75 +4286,107 @@ if (import.meta.hot && route?.component) {
3779
4286
  }
3780
4287
  `);
3781
4288
  }
3782
- return {
3783
- code: source.toString(),
3784
- map: source.generateMap({ includeContent: true, source: filename }),
3785
- removedServerCode
3786
- };
4289
+ return { code: source.toString(), removedServerCode };
3787
4290
  }
3788
4291
 
3789
- // src/plugin/index.ts
4292
+ // src/plugin/strip-server.ts
4293
+ var NODE_MODULES_SEGMENT = /[\\/]node_modules[\\/]/;
4294
+ function isPackageModule(path) {
4295
+ return NODE_MODULES_SEGMENT.test(path);
4296
+ }
4297
+ function stripServerCode(path, source) {
4298
+ return { contents: transformForClient(source, path).code, loader: detectLoaderFromPath(path) };
4299
+ }
4300
+
4301
+ // src/plugin/client-plugin.ts
3790
4302
  var ELYSIA_FILTER = /^elysia$/;
3791
4303
  var BUN_BUILTIN_FILTER = /^bun:/;
3792
4304
  var ANY_FILTER = /.*/;
3793
- var SCRIPT_FILE_FILTER = /\.(tsx?|jsx?)$/;
3794
4305
  var ELYSIA_STUB = `export const t = new Proxy({}, { get: () => (...args) => args[0] ?? {} });
3795
4306
  export class NotFoundError extends Error { constructor(m) { super(m); this.name = "NotFoundError"; } }
3796
4307
  export class ValidationError extends Error { constructor(m) { super(m); this.name = "ValidationError"; } }
3797
4308
  export default {};
3798
4309
  `;
3799
- var plugin = {
3800
- name: "furin-strip-server",
3801
- setup(build) {
3802
- environmentGuardPlugin("client").setup(build);
3803
- const topologyPaths = new Set;
3804
- const loadedSources = new Map;
3805
- build.onResolve({ filter: ELYSIA_FILTER }, () => ({
3806
- namespace: "furin-stubs",
3807
- path: "elysia-stub"
3808
- }));
3809
- build.onResolve({ filter: BUN_BUILTIN_FILTER }, () => ({
3810
- namespace: "furin-stubs",
3811
- path: "bun-builtin-stub"
3812
- }));
3813
- build.onLoad({ filter: ANY_FILTER, namespace: "furin-stubs" }, (args) => ({
3814
- contents: args.path === "elysia-stub" ? ELYSIA_STUB : "",
3815
- loader: "js"
3816
- }));
3817
- build.onLoad({ filter: SCRIPT_FILE_FILTER }, async (args) => {
3818
- if (args.path.includes("node_modules")) {
3819
- return;
3820
- }
3821
- let source;
3822
- try {
3823
- source = await Bun.file(args.path).text();
3824
- } catch (error) {
3825
- const loaded = loadedSources.get(args.path);
3826
- if (loaded?.isRouteModule && error instanceof Error && "code" in error && error.code === "ENOENT") {
3827
- return loaded;
4310
+ function trackHydrationTopology(filePath, source, topologyPaths) {
4311
+ const normalizedPath = filePath.replaceAll("\\", "/");
4312
+ if (!(normalizedPath.includes("/.furin/") && normalizedPath.endsWith("/_hydrate.tsx"))) {
4313
+ return;
4314
+ }
4315
+ const transpiler = new Bun.Transpiler({ loader: "tsx" });
4316
+ for (const imported of transpiler.scanImports(source)) {
4317
+ if (isAbsolute2(imported.path) || imported.path.startsWith(".")) {
4318
+ topologyPaths.add(resolve2(dirname4(filePath), imported.path.split("?")[0]));
4319
+ }
4320
+ }
4321
+ }
4322
+ function stripForMode(filePath, source, mode) {
4323
+ try {
4324
+ return stripServerCode(filePath, source);
4325
+ } catch (error) {
4326
+ if (mode === "build") {
4327
+ throw error;
4328
+ }
4329
+ const loader = detectLoaderFromPath(filePath);
4330
+ try {
4331
+ new Bun.Transpiler({ loader }).scan(source);
4332
+ } catch {
4333
+ return { contents: source, loader };
4334
+ }
4335
+ const message = error instanceof Error ? error.message : String(error);
4336
+ return { contents: `throw new Error(${JSON.stringify(message)});`, loader: "js" };
4337
+ }
4338
+ }
4339
+ function createClientStripPlugin({ mode }) {
4340
+ return {
4341
+ name: "furin-strip-server",
4342
+ setup(build) {
4343
+ flightLoaderPlugin().setup(build);
4344
+ environmentGuardPlugin("client").setup(build);
4345
+ const topologyPaths = new Set;
4346
+ const loadedSources = new Map;
4347
+ build.onResolve({ filter: ELYSIA_FILTER }, () => ({
4348
+ namespace: "furin-stubs",
4349
+ path: "elysia-stub"
4350
+ }));
4351
+ build.onResolve({ filter: BUN_BUILTIN_FILTER }, () => ({
4352
+ namespace: "furin-stubs",
4353
+ path: "bun-builtin-stub"
4354
+ }));
4355
+ build.onLoad({ filter: ANY_FILTER, namespace: "furin-stubs" }, (args) => ({
4356
+ contents: args.path === "elysia-stub" ? ELYSIA_STUB : "",
4357
+ loader: "js"
4358
+ }));
4359
+ build.onLoad({ filter: SCRIPT_FILE_FILTER }, async (args) => {
4360
+ const filePath = args.path.split("?")[0];
4361
+ if (isPackageModule(filePath)) {
4362
+ return;
3828
4363
  }
3829
- throw error;
3830
- }
3831
- const normalizedPath = args.path.replaceAll("\\", "/");
3832
- if (normalizedPath.includes("/.furin/") && normalizedPath.endsWith("/_hydrate.tsx")) {
3833
- const transpiler = new Bun.Transpiler({ loader: "tsx" });
3834
- for (const imported of transpiler.scanImports(source)) {
3835
- if (isAbsolute2(imported.path) || imported.path.startsWith(".")) {
3836
- topologyPaths.add(resolve2(dirname3(args.path), imported.path));
4364
+ let source;
4365
+ try {
4366
+ source = await Bun.file(filePath).text();
4367
+ } catch (error) {
4368
+ const loaded = loadedSources.get(filePath);
4369
+ if (loaded?.isRouteModule && error instanceof Error && "code" in error && error.code === "ENOENT") {
4370
+ return loaded;
3837
4371
  }
4372
+ throw error;
3838
4373
  }
3839
- }
3840
- const result = transformForClient(source, args.path);
3841
- const loaded = {
3842
- contents: result.code,
3843
- isRouteModule: topologyPaths.has(args.path),
3844
- loader: detectLoaderFromPath(args.path)
3845
- };
3846
- loadedSources.set(args.path, loaded);
3847
- return loaded;
3848
- });
3849
- }
3850
- };
4374
+ if (mode === "dev") {
4375
+ trackHydrationTopology(filePath, source, topologyPaths);
4376
+ }
4377
+ const loaded = {
4378
+ ...stripForMode(filePath, source, mode),
4379
+ isRouteModule: topologyPaths.has(filePath)
4380
+ };
4381
+ loadedSources.set(filePath, loaded);
4382
+ return loaded;
4383
+ });
4384
+ }
4385
+ };
4386
+ }
4387
+
4388
+ // src/plugin/index.ts
4389
+ var plugin = createClientStripPlugin({ mode: "dev" });
3851
4390
  var plugin_default = plugin;
3852
4391
  export {
3853
4392
  plugin_default as default