@farm.js/core 0.1.0-beta.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 (549) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +11 -0
  3. package/dist/after.cjs +227 -0
  4. package/dist/after.cjs.map +1 -0
  5. package/dist/after.d.mts +25 -0
  6. package/dist/after.d.ts +25 -0
  7. package/dist/after.mjs +14 -0
  8. package/dist/after.mjs.map +1 -0
  9. package/dist/agent-runtime.cjs +2379 -0
  10. package/dist/agent-runtime.cjs.map +1 -0
  11. package/dist/agent-runtime.d.mts +93 -0
  12. package/dist/agent-runtime.d.ts +93 -0
  13. package/dist/agent-runtime.mjs +479 -0
  14. package/dist/agent-runtime.mjs.map +1 -0
  15. package/dist/api/route-manager.cjs +1196 -0
  16. package/dist/api/route-manager.cjs.map +1 -0
  17. package/dist/api/route-manager.d.mts +64 -0
  18. package/dist/api/route-manager.d.ts +64 -0
  19. package/dist/api/route-manager.mjs +34 -0
  20. package/dist/api/route-manager.mjs.map +1 -0
  21. package/dist/api/runtime.cjs +272 -0
  22. package/dist/api/runtime.cjs.map +1 -0
  23. package/dist/api/runtime.d.mts +16 -0
  24. package/dist/api/runtime.d.ts +16 -0
  25. package/dist/api/runtime.mjs +16 -0
  26. package/dist/api/runtime.mjs.map +1 -0
  27. package/dist/api.cjs +3199 -0
  28. package/dist/api.cjs.map +1 -0
  29. package/dist/api.d.mts +190 -0
  30. package/dist/api.d.ts +190 -0
  31. package/dist/api.mjs +63 -0
  32. package/dist/api.mjs.map +1 -0
  33. package/dist/app-BiX4qb-d.d.mts +265 -0
  34. package/dist/app-CFRNJXP1.d.ts +265 -0
  35. package/dist/app-markdown.cjs +220 -0
  36. package/dist/app-markdown.cjs.map +1 -0
  37. package/dist/app-markdown.d.mts +21 -0
  38. package/dist/app-markdown.d.ts +21 -0
  39. package/dist/app-markdown.mjs +26 -0
  40. package/dist/app-markdown.mjs.map +1 -0
  41. package/dist/cache.cjs +543 -0
  42. package/dist/cache.cjs.map +1 -0
  43. package/dist/cache.d.mts +78 -0
  44. package/dist/cache.d.ts +78 -0
  45. package/dist/cache.mjs +38 -0
  46. package/dist/cache.mjs.map +1 -0
  47. package/dist/chunk-25D7G34K.mjs +142 -0
  48. package/dist/chunk-25D7G34K.mjs.map +1 -0
  49. package/dist/chunk-3QJO55ZF.mjs +3548 -0
  50. package/dist/chunk-3QJO55ZF.mjs.map +1 -0
  51. package/dist/chunk-3XNTL3FQ.mjs +452 -0
  52. package/dist/chunk-3XNTL3FQ.mjs.map +1 -0
  53. package/dist/chunk-44ZCFSKE.mjs +84 -0
  54. package/dist/chunk-44ZCFSKE.mjs.map +1 -0
  55. package/dist/chunk-4PTK6KT4.mjs +364 -0
  56. package/dist/chunk-4PTK6KT4.mjs.map +1 -0
  57. package/dist/chunk-4S3ORGFA.mjs +44 -0
  58. package/dist/chunk-4S3ORGFA.mjs.map +1 -0
  59. package/dist/chunk-5BY76U2M.mjs +1 -0
  60. package/dist/chunk-5BY76U2M.mjs.map +1 -0
  61. package/dist/chunk-5ZGPRGWV.mjs +136 -0
  62. package/dist/chunk-5ZGPRGWV.mjs.map +1 -0
  63. package/dist/chunk-6XDUHOEM.mjs +157 -0
  64. package/dist/chunk-6XDUHOEM.mjs.map +1 -0
  65. package/dist/chunk-74YTBPTY.mjs +450 -0
  66. package/dist/chunk-74YTBPTY.mjs.map +1 -0
  67. package/dist/chunk-7HO6AEOP.mjs +74 -0
  68. package/dist/chunk-7HO6AEOP.mjs.map +1 -0
  69. package/dist/chunk-7MABZJIM.mjs +29 -0
  70. package/dist/chunk-7MABZJIM.mjs.map +1 -0
  71. package/dist/chunk-7ZY5AIJO.mjs +161 -0
  72. package/dist/chunk-7ZY5AIJO.mjs.map +1 -0
  73. package/dist/chunk-AGS7UJ52.mjs +446 -0
  74. package/dist/chunk-AGS7UJ52.mjs.map +1 -0
  75. package/dist/chunk-AZ7YUVNR.mjs +65 -0
  76. package/dist/chunk-AZ7YUVNR.mjs.map +1 -0
  77. package/dist/chunk-B232I2GP.mjs +163 -0
  78. package/dist/chunk-B232I2GP.mjs.map +1 -0
  79. package/dist/chunk-B6N4ZB2H.mjs +718 -0
  80. package/dist/chunk-B6N4ZB2H.mjs.map +1 -0
  81. package/dist/chunk-BHG3LVHH.mjs +176 -0
  82. package/dist/chunk-BHG3LVHH.mjs.map +1 -0
  83. package/dist/chunk-C3DLZMBU.mjs +597 -0
  84. package/dist/chunk-C3DLZMBU.mjs.map +1 -0
  85. package/dist/chunk-CGILA3WO.mjs +14 -0
  86. package/dist/chunk-CGILA3WO.mjs.map +1 -0
  87. package/dist/chunk-CHFHNEMO.mjs +7088 -0
  88. package/dist/chunk-CHFHNEMO.mjs.map +1 -0
  89. package/dist/chunk-E2MPIBRE.mjs +149 -0
  90. package/dist/chunk-E2MPIBRE.mjs.map +1 -0
  91. package/dist/chunk-E6EPN5BT.mjs +203 -0
  92. package/dist/chunk-E6EPN5BT.mjs.map +1 -0
  93. package/dist/chunk-EVGBEZDF.mjs +215 -0
  94. package/dist/chunk-EVGBEZDF.mjs.map +1 -0
  95. package/dist/chunk-FQYDHKKU.mjs +128 -0
  96. package/dist/chunk-FQYDHKKU.mjs.map +1 -0
  97. package/dist/chunk-G3B5BRDY.mjs +5763 -0
  98. package/dist/chunk-G3B5BRDY.mjs.map +1 -0
  99. package/dist/chunk-GN72QAIH.mjs +146 -0
  100. package/dist/chunk-GN72QAIH.mjs.map +1 -0
  101. package/dist/chunk-GS6K5OCM.mjs +407 -0
  102. package/dist/chunk-GS6K5OCM.mjs.map +1 -0
  103. package/dist/chunk-GY2STC2S.mjs +180 -0
  104. package/dist/chunk-GY2STC2S.mjs.map +1 -0
  105. package/dist/chunk-GZP5W4K3.mjs +158 -0
  106. package/dist/chunk-GZP5W4K3.mjs.map +1 -0
  107. package/dist/chunk-H2FA2SBS.mjs +51 -0
  108. package/dist/chunk-H2FA2SBS.mjs.map +1 -0
  109. package/dist/chunk-HXP3ZSPC.mjs +211 -0
  110. package/dist/chunk-HXP3ZSPC.mjs.map +1 -0
  111. package/dist/chunk-ITN462YM.mjs +98 -0
  112. package/dist/chunk-ITN462YM.mjs.map +1 -0
  113. package/dist/chunk-J23HNLFY.mjs +72 -0
  114. package/dist/chunk-J23HNLFY.mjs.map +1 -0
  115. package/dist/chunk-J4FNJ5IU.mjs +179 -0
  116. package/dist/chunk-J4FNJ5IU.mjs.map +1 -0
  117. package/dist/chunk-JK25YEN6.mjs +219 -0
  118. package/dist/chunk-JK25YEN6.mjs.map +1 -0
  119. package/dist/chunk-JLWMCADZ.mjs +204 -0
  120. package/dist/chunk-JLWMCADZ.mjs.map +1 -0
  121. package/dist/chunk-JN3UU635.mjs +622 -0
  122. package/dist/chunk-JN3UU635.mjs.map +1 -0
  123. package/dist/chunk-K4667E2Q.mjs +1916 -0
  124. package/dist/chunk-K4667E2Q.mjs.map +1 -0
  125. package/dist/chunk-LGHEOHBU.mjs +218 -0
  126. package/dist/chunk-LGHEOHBU.mjs.map +1 -0
  127. package/dist/chunk-LLC7BNXW.mjs +275 -0
  128. package/dist/chunk-LLC7BNXW.mjs.map +1 -0
  129. package/dist/chunk-LM2YNO4U.mjs +24 -0
  130. package/dist/chunk-LM2YNO4U.mjs.map +1 -0
  131. package/dist/chunk-NNLCAVB6.mjs +391 -0
  132. package/dist/chunk-NNLCAVB6.mjs.map +1 -0
  133. package/dist/chunk-O3HADRW6.mjs +639 -0
  134. package/dist/chunk-O3HADRW6.mjs.map +1 -0
  135. package/dist/chunk-OYXO65LI.mjs +119 -0
  136. package/dist/chunk-OYXO65LI.mjs.map +1 -0
  137. package/dist/chunk-P7QDS5AT.mjs +191 -0
  138. package/dist/chunk-P7QDS5AT.mjs.map +1 -0
  139. package/dist/chunk-PRNYWD7K.mjs +599 -0
  140. package/dist/chunk-PRNYWD7K.mjs.map +1 -0
  141. package/dist/chunk-QF4PHCMA.mjs +422 -0
  142. package/dist/chunk-QF4PHCMA.mjs.map +1 -0
  143. package/dist/chunk-QFQRHRZS.mjs +1224 -0
  144. package/dist/chunk-QFQRHRZS.mjs.map +1 -0
  145. package/dist/chunk-QGOHVJ6J.mjs +63 -0
  146. package/dist/chunk-QGOHVJ6J.mjs.map +1 -0
  147. package/dist/chunk-QKVUNGAH.mjs +39 -0
  148. package/dist/chunk-QKVUNGAH.mjs.map +1 -0
  149. package/dist/chunk-QM6VV26B.mjs +149 -0
  150. package/dist/chunk-QM6VV26B.mjs.map +1 -0
  151. package/dist/chunk-RHIFZZUI.mjs +69 -0
  152. package/dist/chunk-RHIFZZUI.mjs.map +1 -0
  153. package/dist/chunk-RKI6TN3A.mjs +49 -0
  154. package/dist/chunk-RKI6TN3A.mjs.map +1 -0
  155. package/dist/chunk-RSKVYESE.mjs +187 -0
  156. package/dist/chunk-RSKVYESE.mjs.map +1 -0
  157. package/dist/chunk-S2XHZS7W.mjs +180 -0
  158. package/dist/chunk-S2XHZS7W.mjs.map +1 -0
  159. package/dist/chunk-SCFX4UTD.mjs +28 -0
  160. package/dist/chunk-SCFX4UTD.mjs.map +1 -0
  161. package/dist/chunk-SL6HTIOK.mjs +66 -0
  162. package/dist/chunk-SL6HTIOK.mjs.map +1 -0
  163. package/dist/chunk-SOU3Q3ZA.mjs +173 -0
  164. package/dist/chunk-SOU3Q3ZA.mjs.map +1 -0
  165. package/dist/chunk-SPBBQLXI.mjs +207 -0
  166. package/dist/chunk-SPBBQLXI.mjs.map +1 -0
  167. package/dist/chunk-SXZTEK3V.mjs +396 -0
  168. package/dist/chunk-SXZTEK3V.mjs.map +1 -0
  169. package/dist/chunk-T4QJQK76.mjs +459 -0
  170. package/dist/chunk-T4QJQK76.mjs.map +1 -0
  171. package/dist/chunk-TRORP7E4.mjs +41 -0
  172. package/dist/chunk-TRORP7E4.mjs.map +1 -0
  173. package/dist/chunk-TU4YJICB.mjs +728 -0
  174. package/dist/chunk-TU4YJICB.mjs.map +1 -0
  175. package/dist/chunk-TXCFGOHW.mjs +42 -0
  176. package/dist/chunk-TXCFGOHW.mjs.map +1 -0
  177. package/dist/chunk-UHE2TTLK.mjs +466 -0
  178. package/dist/chunk-UHE2TTLK.mjs.map +1 -0
  179. package/dist/chunk-UREJA4GZ.mjs +364 -0
  180. package/dist/chunk-UREJA4GZ.mjs.map +1 -0
  181. package/dist/chunk-USWZZUEH.mjs +25 -0
  182. package/dist/chunk-USWZZUEH.mjs.map +1 -0
  183. package/dist/chunk-UVCIEUJC.mjs +16 -0
  184. package/dist/chunk-UVCIEUJC.mjs.map +1 -0
  185. package/dist/chunk-V6WE6JSZ.mjs +352 -0
  186. package/dist/chunk-V6WE6JSZ.mjs.map +1 -0
  187. package/dist/chunk-V7RBCSDJ.mjs +170 -0
  188. package/dist/chunk-V7RBCSDJ.mjs.map +1 -0
  189. package/dist/chunk-VCANOYFI.mjs +588 -0
  190. package/dist/chunk-VCANOYFI.mjs.map +1 -0
  191. package/dist/chunk-WZ5QFROO.mjs +23 -0
  192. package/dist/chunk-WZ5QFROO.mjs.map +1 -0
  193. package/dist/chunk-Y2OJJD7R.mjs +543 -0
  194. package/dist/chunk-Y2OJJD7R.mjs.map +1 -0
  195. package/dist/chunk-Y7A27276.mjs +538 -0
  196. package/dist/chunk-Y7A27276.mjs.map +1 -0
  197. package/dist/chunk-YHU7SS6L.mjs +365 -0
  198. package/dist/chunk-YHU7SS6L.mjs.map +1 -0
  199. package/dist/chunk-ZBE6MLHL.mjs +230 -0
  200. package/dist/chunk-ZBE6MLHL.mjs.map +1 -0
  201. package/dist/chunk-ZJQNATYV.mjs +299 -0
  202. package/dist/chunk-ZJQNATYV.mjs.map +1 -0
  203. package/dist/client-D_yUjVhe.d.mts +402 -0
  204. package/dist/client-Dkc03WP8.d.ts +402 -0
  205. package/dist/client-cache-CIlyBlmx.d.ts +6 -0
  206. package/dist/client-cache-D-EZ7XVW.d.mts +6 -0
  207. package/dist/client-plugins-BZnpeTGA.d.ts +1848 -0
  208. package/dist/client-plugins-g4bzuCmo.d.mts +1848 -0
  209. package/dist/client-plugins.cjs +415 -0
  210. package/dist/client-plugins.cjs.map +1 -0
  211. package/dist/client-plugins.d.mts +21 -0
  212. package/dist/client-plugins.d.ts +21 -0
  213. package/dist/client-plugins.mjs +10 -0
  214. package/dist/client-plugins.mjs.map +1 -0
  215. package/dist/client.cjs +4571 -0
  216. package/dist/client.cjs.map +1 -0
  217. package/dist/client.d.mts +329 -0
  218. package/dist/client.d.ts +329 -0
  219. package/dist/client.mjs +103 -0
  220. package/dist/client.mjs.map +1 -0
  221. package/dist/config.cjs +38 -0
  222. package/dist/config.cjs.map +1 -0
  223. package/dist/config.d.mts +28 -0
  224. package/dist/config.d.ts +28 -0
  225. package/dist/config.mjs +10 -0
  226. package/dist/config.mjs.map +1 -0
  227. package/dist/cron.cjs +406 -0
  228. package/dist/cron.cjs.map +1 -0
  229. package/dist/cron.d.mts +78 -0
  230. package/dist/cron.d.ts +78 -0
  231. package/dist/cron.mjs +30 -0
  232. package/dist/cron.mjs.map +1 -0
  233. package/dist/deferred.cjs +438 -0
  234. package/dist/deferred.cjs.map +1 -0
  235. package/dist/deferred.d.mts +42 -0
  236. package/dist/deferred.d.ts +42 -0
  237. package/dist/deferred.mjs +28 -0
  238. package/dist/deferred.mjs.map +1 -0
  239. package/dist/deployment.cjs +199 -0
  240. package/dist/deployment.cjs.map +1 -0
  241. package/dist/deployment.d.mts +34 -0
  242. package/dist/deployment.d.ts +34 -0
  243. package/dist/deployment.mjs +38 -0
  244. package/dist/deployment.mjs.map +1 -0
  245. package/dist/devtools-AE4RVXCM.mjs +370 -0
  246. package/dist/devtools-AE4RVXCM.mjs.map +1 -0
  247. package/dist/devtools-client-6WPY2AQU.mjs +225 -0
  248. package/dist/devtools-client-6WPY2AQU.mjs.map +1 -0
  249. package/dist/devtools-ui-NJKFORTG.mjs +1349 -0
  250. package/dist/devtools-ui-NJKFORTG.mjs.map +1 -0
  251. package/dist/docs.cjs +5541 -0
  252. package/dist/docs.cjs.map +1 -0
  253. package/dist/docs.d.mts +69 -0
  254. package/dist/docs.d.ts +69 -0
  255. package/dist/docs.mjs +46 -0
  256. package/dist/docs.mjs.map +1 -0
  257. package/dist/env-types.cjs +223 -0
  258. package/dist/env-types.cjs.map +1 -0
  259. package/dist/env-types.d.mts +11 -0
  260. package/dist/env-types.d.ts +11 -0
  261. package/dist/env-types.mjs +9 -0
  262. package/dist/env-types.mjs.map +1 -0
  263. package/dist/env.cjs +215 -0
  264. package/dist/env.cjs.map +1 -0
  265. package/dist/env.d.mts +45 -0
  266. package/dist/env.d.ts +45 -0
  267. package/dist/env.mjs +22 -0
  268. package/dist/env.mjs.map +1 -0
  269. package/dist/environment/vite.cjs +374 -0
  270. package/dist/environment/vite.cjs.map +1 -0
  271. package/dist/environment/vite.d.mts +22 -0
  272. package/dist/environment/vite.d.ts +22 -0
  273. package/dist/environment/vite.mjs +10 -0
  274. package/dist/environment/vite.mjs.map +1 -0
  275. package/dist/environment.cjs +96 -0
  276. package/dist/environment.cjs.map +1 -0
  277. package/dist/environment.d.mts +18 -0
  278. package/dist/environment.d.ts +18 -0
  279. package/dist/environment.mjs +14 -0
  280. package/dist/environment.mjs.map +1 -0
  281. package/dist/headers.cjs +126 -0
  282. package/dist/headers.cjs.map +1 -0
  283. package/dist/headers.d.mts +22 -0
  284. package/dist/headers.d.ts +22 -0
  285. package/dist/headers.mjs +12 -0
  286. package/dist/headers.mjs.map +1 -0
  287. package/dist/i18n/client.cjs +283 -0
  288. package/dist/i18n/client.cjs.map +1 -0
  289. package/dist/i18n/client.d.mts +32 -0
  290. package/dist/i18n/client.d.ts +32 -0
  291. package/dist/i18n/client.mjs +121 -0
  292. package/dist/i18n/client.mjs.map +1 -0
  293. package/dist/i18n/index.cjs +130 -0
  294. package/dist/i18n/index.cjs.map +1 -0
  295. package/dist/i18n/index.d.mts +20 -0
  296. package/dist/i18n/index.d.ts +20 -0
  297. package/dist/i18n/index.mjs +22 -0
  298. package/dist/i18n/index.mjs.map +1 -0
  299. package/dist/i18n/server.cjs +637 -0
  300. package/dist/i18n/server.cjs.map +1 -0
  301. package/dist/i18n/server.d.mts +30 -0
  302. package/dist/i18n/server.d.ts +30 -0
  303. package/dist/i18n/server.mjs +32 -0
  304. package/dist/i18n/server.mjs.map +1 -0
  305. package/dist/image/server.cjs +477 -0
  306. package/dist/image/server.cjs.map +1 -0
  307. package/dist/image/server.d.mts +37 -0
  308. package/dist/image/server.d.ts +37 -0
  309. package/dist/image/server.mjs +16 -0
  310. package/dist/image/server.mjs.map +1 -0
  311. package/dist/image/sharp.cjs +135 -0
  312. package/dist/image/sharp.cjs.map +1 -0
  313. package/dist/image/sharp.d.mts +7 -0
  314. package/dist/image/sharp.d.ts +7 -0
  315. package/dist/image/sharp.mjs +75 -0
  316. package/dist/image/sharp.mjs.map +1 -0
  317. package/dist/image-config-Duob7wER.d.mts +50 -0
  318. package/dist/image-config-Duob7wER.d.ts +50 -0
  319. package/dist/image.cjs +209 -0
  320. package/dist/image.cjs.map +1 -0
  321. package/dist/image.d.mts +39 -0
  322. package/dist/image.d.ts +39 -0
  323. package/dist/image.mjs +165 -0
  324. package/dist/image.mjs.map +1 -0
  325. package/dist/index.cjs +39433 -0
  326. package/dist/index.cjs.map +1 -0
  327. package/dist/index.d.mts +451 -0
  328. package/dist/index.d.ts +451 -0
  329. package/dist/index.mjs +930 -0
  330. package/dist/index.mjs.map +1 -0
  331. package/dist/integration-api-CHT2OKAf.d.mts +93 -0
  332. package/dist/integration-api-CHT2OKAf.d.ts +93 -0
  333. package/dist/integration-orm-GQLGU66X.mjs +13 -0
  334. package/dist/integration-orm-GQLGU66X.mjs.map +1 -0
  335. package/dist/integrations.cjs +2820 -0
  336. package/dist/integrations.cjs.map +1 -0
  337. package/dist/integrations.d.mts +21 -0
  338. package/dist/integrations.d.ts +21 -0
  339. package/dist/integrations.mjs +51 -0
  340. package/dist/integrations.mjs.map +1 -0
  341. package/dist/internal/build-runtime.cjs +31340 -0
  342. package/dist/internal/build-runtime.cjs.map +1 -0
  343. package/dist/internal/build-runtime.d.mts +38 -0
  344. package/dist/internal/build-runtime.d.ts +38 -0
  345. package/dist/internal/build-runtime.mjs +73 -0
  346. package/dist/internal/build-runtime.mjs.map +1 -0
  347. package/dist/internal/client-runtime.cjs +579 -0
  348. package/dist/internal/client-runtime.cjs.map +1 -0
  349. package/dist/internal/client-runtime.d.mts +2 -0
  350. package/dist/internal/client-runtime.d.ts +2 -0
  351. package/dist/internal/client-runtime.mjs +12 -0
  352. package/dist/internal/client-runtime.mjs.map +1 -0
  353. package/dist/internal/config-runtime.cjs +4172 -0
  354. package/dist/internal/config-runtime.cjs.map +1 -0
  355. package/dist/internal/config-runtime.d.mts +38 -0
  356. package/dist/internal/config-runtime.d.ts +38 -0
  357. package/dist/internal/config-runtime.mjs +38 -0
  358. package/dist/internal/config-runtime.mjs.map +1 -0
  359. package/dist/internal/production-node-env.cjs +65 -0
  360. package/dist/internal/production-node-env.cjs.map +1 -0
  361. package/dist/internal/production-node-env.d.mts +12 -0
  362. package/dist/internal/production-node-env.d.ts +12 -0
  363. package/dist/internal/production-node-env.mjs +8 -0
  364. package/dist/internal/production-node-env.mjs.map +1 -0
  365. package/dist/internal/production-runtime.cjs +1896 -0
  366. package/dist/internal/production-runtime.cjs.map +1 -0
  367. package/dist/internal/production-runtime.d.mts +39 -0
  368. package/dist/internal/production-runtime.d.ts +39 -0
  369. package/dist/internal/production-runtime.mjs +79 -0
  370. package/dist/internal/production-runtime.mjs.map +1 -0
  371. package/dist/layers-VWVDTPUZ.mjs +16 -0
  372. package/dist/layers-VWVDTPUZ.mjs.map +1 -0
  373. package/dist/manager-THKFTOFE.mjs +10 -0
  374. package/dist/manager-THKFTOFE.mjs.map +1 -0
  375. package/dist/markdown.cjs +299 -0
  376. package/dist/markdown.cjs.map +1 -0
  377. package/dist/markdown.d.mts +43 -0
  378. package/dist/markdown.d.ts +43 -0
  379. package/dist/markdown.mjs +14 -0
  380. package/dist/markdown.mjs.map +1 -0
  381. package/dist/metadata-C9NZxMDW.d.mts +22 -0
  382. package/dist/metadata-DAXRaOHx.d.ts +22 -0
  383. package/dist/middleware.cjs +2148 -0
  384. package/dist/middleware.cjs.map +1 -0
  385. package/dist/middleware.d.mts +163 -0
  386. package/dist/middleware.d.ts +163 -0
  387. package/dist/middleware.mjs +49 -0
  388. package/dist/middleware.mjs.map +1 -0
  389. package/dist/navigation-errors-Dvwpzaer.d.mts +13 -0
  390. package/dist/navigation-errors-Dvwpzaer.d.ts +13 -0
  391. package/dist/navigation.cjs +1304 -0
  392. package/dist/navigation.cjs.map +1 -0
  393. package/dist/navigation.d.mts +14 -0
  394. package/dist/navigation.d.ts +14 -0
  395. package/dist/navigation.mjs +33 -0
  396. package/dist/navigation.mjs.map +1 -0
  397. package/dist/nitro-KME62MWG.mjs +691 -0
  398. package/dist/nitro-KME62MWG.mjs.map +1 -0
  399. package/dist/observability.cjs +186 -0
  400. package/dist/observability.cjs.map +1 -0
  401. package/dist/observability.d.mts +335 -0
  402. package/dist/observability.d.ts +335 -0
  403. package/dist/observability.mjs +16 -0
  404. package/dist/observability.mjs.map +1 -0
  405. package/dist/params-BALtrRim.d.ts +15 -0
  406. package/dist/params-ry-lxqmy.d.mts +15 -0
  407. package/dist/plugin-BJDf43dc.d.mts +165 -0
  408. package/dist/plugin-BJDf43dc.d.ts +165 -0
  409. package/dist/plugin.cjs +22285 -0
  410. package/dist/plugin.cjs.map +1 -0
  411. package/dist/plugin.d.mts +21 -0
  412. package/dist/plugin.d.ts +21 -0
  413. package/dist/plugin.mjs +60 -0
  414. package/dist/plugin.mjs.map +1 -0
  415. package/dist/production-runtime-C_B79w2P.d.mts +28 -0
  416. package/dist/production-runtime-DDEM1D2q.d.ts +28 -0
  417. package/dist/production-runtime-DRkCHUvJ.d.ts +79 -0
  418. package/dist/production-runtime-flrjp_nC.d.mts +79 -0
  419. package/dist/query/client.cjs +560 -0
  420. package/dist/query/client.cjs.map +1 -0
  421. package/dist/query/client.d.mts +61 -0
  422. package/dist/query/client.d.ts +61 -0
  423. package/dist/query/client.mjs +364 -0
  424. package/dist/query/client.mjs.map +1 -0
  425. package/dist/query/index.cjs +226 -0
  426. package/dist/query/index.cjs.map +1 -0
  427. package/dist/query/index.d.mts +90 -0
  428. package/dist/query/index.d.ts +90 -0
  429. package/dist/query/index.mjs +31 -0
  430. package/dist/query/index.mjs.map +1 -0
  431. package/dist/query/parsers.cjs +178 -0
  432. package/dist/query/parsers.cjs.map +1 -0
  433. package/dist/query/parsers.d.mts +25 -0
  434. package/dist/query/parsers.d.ts +25 -0
  435. package/dist/query/parsers.mjs +24 -0
  436. package/dist/query/parsers.mjs.map +1 -0
  437. package/dist/query/server.cjs +301 -0
  438. package/dist/query/server.cjs.map +1 -0
  439. package/dist/query/server.d.mts +55 -0
  440. package/dist/query/server.d.ts +55 -0
  441. package/dist/query/server.mjs +105 -0
  442. package/dist/query/server.mjs.map +1 -0
  443. package/dist/request-BrFBuc8G.d.mts +6 -0
  444. package/dist/request-BslSZIRz.d.ts +6 -0
  445. package/dist/request.cjs +71 -0
  446. package/dist/request.cjs.map +1 -0
  447. package/dist/request.d.mts +2 -0
  448. package/dist/request.d.ts +2 -0
  449. package/dist/request.mjs +9 -0
  450. package/dist/request.mjs.map +1 -0
  451. package/dist/resolver-C6iecsDV.d.ts +14 -0
  452. package/dist/resolver-DlOPpjkB.d.mts +14 -0
  453. package/dist/route-runtime-DoOHzCAD.d.mts +38 -0
  454. package/dist/route-runtime-DoOHzCAD.d.ts +38 -0
  455. package/dist/router.cjs +254 -0
  456. package/dist/router.cjs.map +1 -0
  457. package/dist/router.d.mts +36 -0
  458. package/dist/router.d.ts +36 -0
  459. package/dist/router.mjs +14 -0
  460. package/dist/router.mjs.map +1 -0
  461. package/dist/routes.cjs +1213 -0
  462. package/dist/routes.cjs.map +1 -0
  463. package/dist/routes.d.mts +224 -0
  464. package/dist/routes.d.ts +224 -0
  465. package/dist/routes.mjs +52 -0
  466. package/dist/routes.mjs.map +1 -0
  467. package/dist/runtime-B6GvwDS1.d.ts +27 -0
  468. package/dist/runtime-DeAAZ6gO.d.mts +27 -0
  469. package/dist/search-client-6OXIBNYQ.mjs +14 -0
  470. package/dist/search-client-6OXIBNYQ.mjs.map +1 -0
  471. package/dist/server-action-security.cjs +492 -0
  472. package/dist/server-action-security.cjs.map +1 -0
  473. package/dist/server-action-security.d.mts +42 -0
  474. package/dist/server-action-security.d.ts +42 -0
  475. package/dist/server-action-security.mjs +29 -0
  476. package/dist/server-action-security.mjs.map +1 -0
  477. package/dist/server-fn-client.cjs +180 -0
  478. package/dist/server-fn-client.cjs.map +1 -0
  479. package/dist/server-fn-client.d.mts +31 -0
  480. package/dist/server-fn-client.d.ts +31 -0
  481. package/dist/server-fn-client.mjs +9 -0
  482. package/dist/server-fn-client.mjs.map +1 -0
  483. package/dist/server-fn.cjs +284 -0
  484. package/dist/server-fn.cjs.map +1 -0
  485. package/dist/server-fn.d.mts +84 -0
  486. package/dist/server-fn.d.ts +84 -0
  487. package/dist/server-fn.mjs +17 -0
  488. package/dist/server-fn.mjs.map +1 -0
  489. package/dist/server-plugins.cjs +235 -0
  490. package/dist/server-plugins.cjs.map +1 -0
  491. package/dist/server-plugins.d.mts +54 -0
  492. package/dist/server-plugins.d.ts +54 -0
  493. package/dist/server-plugins.mjs +18 -0
  494. package/dist/server-plugins.mjs.map +1 -0
  495. package/dist/server-query-client.cjs +792 -0
  496. package/dist/server-query-client.cjs.map +1 -0
  497. package/dist/server-query-client.d.mts +50 -0
  498. package/dist/server-query-client.d.ts +50 -0
  499. package/dist/server-query-client.mjs +23 -0
  500. package/dist/server-query-client.mjs.map +1 -0
  501. package/dist/server-query.cjs +804 -0
  502. package/dist/server-query.cjs.map +1 -0
  503. package/dist/server-query.d.mts +36 -0
  504. package/dist/server-query.d.ts +36 -0
  505. package/dist/server-query.mjs +18 -0
  506. package/dist/server-query.mjs.map +1 -0
  507. package/dist/server.cjs +25739 -0
  508. package/dist/server.cjs.map +1 -0
  509. package/dist/server.d.mts +47 -0
  510. package/dist/server.d.ts +47 -0
  511. package/dist/server.mjs +511 -0
  512. package/dist/server.mjs.map +1 -0
  513. package/dist/storage.cjs +515 -0
  514. package/dist/storage.cjs.map +1 -0
  515. package/dist/storage.d.mts +52 -0
  516. package/dist/storage.d.ts +52 -0
  517. package/dist/storage.mjs +58 -0
  518. package/dist/storage.mjs.map +1 -0
  519. package/dist/testing.cjs +1882 -0
  520. package/dist/testing.cjs.map +1 -0
  521. package/dist/testing.d.mts +100 -0
  522. package/dist/testing.d.ts +100 -0
  523. package/dist/testing.mjs +324 -0
  524. package/dist/testing.mjs.map +1 -0
  525. package/dist/types-BH1lhg5G.d.mts +81 -0
  526. package/dist/types-BH1lhg5G.d.ts +81 -0
  527. package/dist/types-C9N-nk5R.d.mts +53 -0
  528. package/dist/types-C9N-nk5R.d.ts +53 -0
  529. package/dist/types-D1A6-XvH.d.mts +73 -0
  530. package/dist/types-D1A6-XvH.d.ts +73 -0
  531. package/dist/utils-DA1yo54_.d.ts +23 -0
  532. package/dist/utils-DOXXivjL.d.mts +23 -0
  533. package/dist/vite.cjs +22684 -0
  534. package/dist/vite.cjs.map +1 -0
  535. package/dist/vite.d.mts +21 -0
  536. package/dist/vite.d.ts +21 -0
  537. package/dist/vite.mjs +59 -0
  538. package/dist/vite.mjs.map +1 -0
  539. package/dist/workflows.cjs +586 -0
  540. package/dist/workflows.cjs.map +1 -0
  541. package/dist/workflows.d.mts +110 -0
  542. package/dist/workflows.d.ts +110 -0
  543. package/dist/workflows.mjs +32 -0
  544. package/dist/workflows.mjs.map +1 -0
  545. package/package.json +523 -0
  546. package/types/api.d.ts +88 -0
  547. package/types/client.d.ts +1171 -0
  548. package/types/index.d.ts +17 -0
  549. package/types/middleware.d.ts +266 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/env.ts","../src/request-context.ts","../src/app-markdown.ts","../src/markdown.ts","../src/workflows.ts","../src/cron.ts","../src/storage/index.ts","../src/route-runtime.ts","../src/route-rules.ts","../src/cache-invalidation.ts","../src/server-action-security.ts","../src/image-config.ts","../src/layers.ts","../src/integration-api.ts","../src/server/response.ts","../src/integration-orm.ts","../src/integrations.ts","../src/deployment.ts","../src/i18n/config.ts","../src/devtools-config.ts","../src/write-file-if-changed.ts","../src/type-generator.ts","../src/image-server.ts","../src/docs/last-modified.ts","../src/docs/pixel-border-css.ts","../src/docs/search-client.ts","../src/docs/handler.ts","../src/config-entry.ts","../src/config.ts","../src/docs/api.ts","../src/docs/index.ts","../src/openapi/generator.ts","../src/openapi/manager.ts","../src/devtools.ts","../src/devtools-ui.ts","../src/devtools-client.ts","../src/image-sharp.ts","../src/plugin.ts","../src/app.ts","../src/utils.ts","../src/observability.ts","../src/ssg.ts","../src/routes.ts","../src/cache.ts","../src/i18n/bridge.ts","../src/route-context.ts","../src/routes.server.ts","../src/routing/route-manager.ts","../src/utils/client-component.ts","../src/static-metadata-image.ts","../src/i18n/routing.ts","../src/server/renderer.ts","../src/middleware/server.ts","../src/server/request.ts","../src/server/request-bridge.ts","../src/client/router.ts","../src/deferred.ts","../src/client/spa-router.ts","../src/i18n/client-runtime.ts","../src/navigation-errors.ts","../src/metadata.ts","../src/i18n/server.ts","../src/i18n/runtime.ts","../src/i18n/catalog.ts","../src/i18n/resolver.ts","../src/default-styles.ts","../src/client-plugin-build.ts","../src/hmr.ts","../src/api/route-manager.ts","../src/api/runtime.ts","../src/middleware/manager.ts","../src/middleware/context.ts","../src/middleware/module.ts","../src/type-artifacts.ts","../src/routing/generate-route-types.ts","../src/env-types.ts","../src/image-types.ts","../src/i18n/type-generator.ts","../src/vite.ts","../src/after.ts","../src/image-vite.ts"],"sourcesContent":["export interface EnvSchema<TOutput = unknown> {\n parse(value: unknown): TOutput;\n}\n\nexport type EnvParser<TOutput = unknown> =\n | EnvSchema<TOutput>\n | ((value: string | undefined, context: { key: string; scope: \"server\" | \"public\" }) => TOutput);\n\nexport type EnvShape = Record<string, EnvParser<any>>;\n\nexport type InferEnvParser<TParser> =\n TParser extends EnvSchema<infer TOutput>\n ? TOutput\n : TParser extends (value: string | undefined, context: any) => infer TOutput\n ? TOutput\n : never;\n\nexport type InferEnvShape<TShape> = TShape extends EnvShape\n ? { [K in keyof TShape]: InferEnvParser<TShape[K]> }\n : {};\n\nexport interface FarmEnvConfig<\n TServer extends EnvShape = EnvShape,\n TPublic extends EnvShape = EnvShape,\n> {\n server?: TServer;\n public?: TPublic;\n}\n\nexport interface ResolvedFarmEnv<\n TServer extends Record<string, any> = Record<string, unknown>,\n TPublic extends Record<string, any> = Record<string, unknown>,\n> {\n server: TServer;\n public: TPublic;\n}\n\nexport type InferEnv<TConfig> =\n TConfig extends FarmEnvConfig<infer TServer, infer TPublic>\n ? ResolvedFarmEnv<InferEnvShape<TServer>, InferEnvShape<TPublic>>\n : ResolvedFarmEnv;\n\n/**\n * Augmented by generated src/farm-env.d.ts for project-specific autocomplete.\n */\nexport interface FarmEnvTypes {}\n\nexport type FarmServerEnv = FarmEnvTypes extends { server: infer TServer }\n ? TServer extends Record<string, any>\n ? TServer\n : Record<string, unknown>\n : Record<string, unknown>;\n\nexport type FarmPublicEnv = FarmEnvTypes extends { public: infer TPublic }\n ? TPublic extends Record<string, any>\n ? TPublic\n : Record<string, unknown>\n : Record<string, unknown>;\n\nexport type FarmTypedEnv = ResolvedFarmEnv<FarmServerEnv, FarmPublicEnv>;\n\ndeclare const __FARM_PUBLIC_ENV__: Record<string, unknown> | undefined;\ndeclare const __FARM_ENV__: ResolvedFarmEnv | undefined;\n\nconst FARM_ENV_SYMBOL = Symbol.for(\"farm.env\");\nconst farmEnvGlobal = globalThis as typeof globalThis & {\n [FARM_ENV_SYMBOL]?: ResolvedFarmEnv;\n};\nlet currentEnv: ResolvedFarmEnv = getInitialEnv();\n\nexport function resolveEnv<TConfig extends FarmEnvConfig<any, any> | undefined>(\n config: TConfig,\n source: Record<string, string | undefined> = getProcessEnv(),\n): InferEnv<NonNullable<TConfig>> {\n const resolved = {\n server: resolveEnvScope(config?.server, source, \"server\"),\n public: resolveEnvScope(config?.public, source, \"public\"),\n } as InferEnv<NonNullable<TConfig>>;\n\n return resolved;\n}\n\nexport function setEnv(env: ResolvedFarmEnv): void {\n currentEnv = normalizeResolvedEnv(env);\n if (typeof window === \"undefined\") {\n farmEnvGlobal[FARM_ENV_SYMBOL] = currentEnv;\n }\n}\n\nexport function getResolvedEnv<TEnv extends ResolvedFarmEnv = FarmTypedEnv>(): TEnv {\n return getCurrentEnv() as TEnv;\n}\n\nexport function getEnv<TServer extends Record<string, any> = FarmServerEnv>(): TServer;\nexport function getEnv<TKey extends Extract<keyof FarmServerEnv, string>>(\n key: TKey,\n): FarmServerEnv[TKey];\nexport function getEnv(key?: string): unknown {\n assertServerEnvAccess();\n if (key === undefined) {\n return getCurrentEnv().server;\n }\n\n return getCurrentEnv().server[key];\n}\n\nexport function getPublicEnv<TPublic extends Record<string, any> = FarmPublicEnv>(): TPublic;\nexport function getPublicEnv<TKey extends Extract<keyof FarmPublicEnv, string>>(\n key: TKey,\n): FarmPublicEnv[TKey];\nexport function getPublicEnv(key?: string): unknown {\n if (key === undefined) {\n return getCurrentEnv().public;\n }\n\n return getCurrentEnv().public[key];\n}\n\nexport const env = createEnvProxy(\"server\") as FarmServerEnv;\nexport const serverEnv = env;\nexport const publicEnv = createEnvProxy(\"public\") as FarmPublicEnv;\n\nfunction resolveEnvScope(\n shape: EnvShape | undefined,\n source: Record<string, string | undefined>,\n scope: \"server\" | \"public\",\n): Record<string, unknown> {\n if (!shape) {\n return {};\n }\n\n const resolved: Record<string, unknown> = {};\n\n for (const [key, parser] of Object.entries(shape)) {\n try {\n resolved[key] = parseEnvValue(parser, source[key], key, scope);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid ${scope} env \"${key}\": ${message}`);\n }\n }\n\n return resolved;\n}\n\nfunction parseEnvValue(\n parser: EnvParser<any>,\n value: string | undefined,\n key: string,\n scope: \"server\" | \"public\",\n): unknown {\n if (typeof parser === \"function\") {\n return parser(value, { key, scope });\n }\n\n if (parser && typeof parser.parse === \"function\") {\n return parser.parse(value);\n }\n\n throw new Error(\"expected a parser function or schema with parse()\");\n}\n\nfunction createEnvProxy(scope: \"server\" | \"public\"): Record<string, unknown> {\n return new Proxy(\n {},\n {\n get(_target, property) {\n if (typeof property === \"symbol\") {\n return undefined;\n }\n\n const env = getEnvScope(scope);\n return env[property];\n },\n ownKeys() {\n return Reflect.ownKeys(getEnvScope(scope));\n },\n getOwnPropertyDescriptor(_target, property) {\n const env = getEnvScope(scope);\n if (!(property in env)) {\n return undefined;\n }\n\n return {\n enumerable: true,\n configurable: true,\n value: env[property as keyof typeof env],\n };\n },\n has(_target, property) {\n return property in getEnvScope(scope);\n },\n },\n );\n}\n\nfunction getEnvScope(scope: \"server\" | \"public\"): Record<string, unknown> {\n if (scope === \"server\") {\n assertServerEnvAccess();\n }\n\n return getCurrentEnv()[scope] || {};\n}\n\nfunction assertServerEnvAccess(): void {\n if (typeof window !== \"undefined\") {\n throw new Error(\"Farm server env is not available in the browser. Use publicEnv.\");\n }\n}\n\nfunction getInitialEnv(): ResolvedFarmEnv {\n const injectedEnv = getInjectedEnv();\n if (injectedEnv) {\n return injectedEnv;\n }\n\n if (typeof window === \"undefined\" && farmEnvGlobal[FARM_ENV_SYMBOL]) {\n return normalizeResolvedEnv(farmEnvGlobal[FARM_ENV_SYMBOL]);\n }\n\n return {\n server: {},\n public: getInjectedPublicEnv(),\n };\n}\n\nfunction getCurrentEnv(): ResolvedFarmEnv {\n if (typeof window === \"undefined\" && farmEnvGlobal[FARM_ENV_SYMBOL]) {\n return farmEnvGlobal[FARM_ENV_SYMBOL];\n }\n\n return currentEnv;\n}\n\nfunction getInjectedEnv(): ResolvedFarmEnv | null {\n try {\n if (typeof __FARM_ENV__ !== \"undefined\" && __FARM_ENV__) {\n return normalizeResolvedEnv(__FARM_ENV__);\n }\n } catch {\n // The compile-time global is only defined in Farm server bundles.\n }\n\n return null;\n}\n\nfunction getInjectedPublicEnv(): Record<string, unknown> {\n try {\n if (typeof __FARM_PUBLIC_ENV__ !== \"undefined\" && __FARM_PUBLIC_ENV__) {\n return __FARM_PUBLIC_ENV__;\n }\n } catch {\n // The compile-time global is only defined in Farm browser bundles.\n }\n\n return {};\n}\n\nfunction normalizeResolvedEnv(env: ResolvedFarmEnv): ResolvedFarmEnv {\n return {\n server: isRecord(env.server) ? env.server : {},\n public: isRecord(env.public) ? env.public : {},\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction getProcessEnv(): Record<string, string | undefined> {\n if (typeof process !== \"undefined\" && process.env) {\n return process.env;\n }\n\n return {};\n}\n","type RequestContextCarrier = object;\n\nexport interface SetRequestContextOptions {\n exposeToPage?: boolean;\n}\n\nexport interface RequestContextSnapshotOptions {\n exposedOnly?: boolean;\n}\n\ninterface RequestContextBucket {\n privateData: Map<string, any>;\n exposedData: Map<string, any>;\n}\n\nconst REQUEST_CONTEXT_STORE_KEY = Symbol.for(\"farm.requestContextStore\");\n\ntype GlobalWithRequestContextStore = typeof globalThis & {\n [REQUEST_CONTEXT_STORE_KEY]?: WeakMap<RequestContextCarrier, RequestContextBucket>;\n};\n\nfunction getRequestContextStore() {\n const globalState = globalThis as GlobalWithRequestContextStore;\n if (!globalState[REQUEST_CONTEXT_STORE_KEY]) {\n globalState[REQUEST_CONTEXT_STORE_KEY] = new WeakMap<\n RequestContextCarrier,\n RequestContextBucket\n >();\n }\n\n return globalState[REQUEST_CONTEXT_STORE_KEY]!;\n}\n\nfunction getBucket(target: RequestContextCarrier): RequestContextBucket {\n const requestContextStore = getRequestContextStore();\n let bucket = requestContextStore.get(target);\n if (!bucket) {\n bucket = {\n privateData: new Map<string, any>(),\n exposedData: new Map<string, any>(),\n };\n requestContextStore.set(target, bucket);\n }\n return bucket;\n}\n\nexport function setRequestContext(\n target: RequestContextCarrier,\n key: string,\n value: any,\n options: SetRequestContextOptions = {},\n): void {\n const bucket = getBucket(target);\n bucket.privateData.set(key, value);\n if (options.exposeToPage) {\n bucket.exposedData.set(key, value);\n }\n}\n\nexport function getRequestContext<T = any>(\n target: RequestContextCarrier,\n key: string,\n): T | undefined {\n const requestContextStore = getRequestContextStore();\n const bucket = requestContextStore.get(target);\n return bucket?.privateData.get(key) as T | undefined;\n}\n\nexport function hasRequestContext(target: RequestContextCarrier, key: string): boolean {\n const requestContextStore = getRequestContextStore();\n const bucket = requestContextStore.get(target);\n return bucket?.privateData.has(key) ?? false;\n}\n\nexport function deleteRequestContext(target: RequestContextCarrier, key: string): boolean {\n const requestContextStore = getRequestContextStore();\n const bucket = requestContextStore.get(target);\n if (!bucket) return false;\n const removedPrivate = bucket.privateData.delete(key);\n bucket.exposedData.delete(key);\n return removedPrivate;\n}\n\nexport function clearRequestContext(target: RequestContextCarrier): void {\n const requestContextStore = getRequestContextStore();\n const bucket = requestContextStore.get(target);\n if (!bucket) return;\n bucket.privateData.clear();\n bucket.exposedData.clear();\n}\n\nexport function getRequestContextSnapshot(\n target: RequestContextCarrier,\n options: RequestContextSnapshotOptions = {},\n): Map<string, any> {\n const requestContextStore = getRequestContextStore();\n const bucket = requestContextStore.get(target);\n if (!bucket) return new Map<string, any>();\n if (options.exposedOnly) {\n return new Map(bucket.exposedData);\n }\n return new Map(bucket.privateData);\n}\n","import React from \"react\";\nimport { readFile } from \"fs/promises\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport type { Metadata, RouteModule } from \"./types\";\n\nexport type FarmMdxComponent = React.ComponentType<any> | keyof React.JSX.IntrinsicElements;\nexport type FarmMdxComponents = Record<string, FarmMdxComponent>;\n\nexport interface FarmMdxUserConfig {\n /**\n * Component map or module path that exports `components` or a default component map.\n * Relative paths resolve from the project root.\n */\n components?: string | FarmMdxComponents;\n /**\n * Serve source-authored markdown pages at `/route.md`.\n * Enabled by default for `page.md` and `page.mdx`.\n */\n markdownRoutes?: boolean;\n /**\n * Class name used for the wrapper around rendered markdown content.\n */\n className?: string;\n}\n\nexport interface FarmMdxResolvedConfig {\n components?: string | FarmMdxComponents;\n markdownRoutes: boolean;\n className: string;\n}\n\nexport interface FarmMarkdownPageSource {\n source: string;\n filePath: string;\n}\n\nexport interface FarmMarkdownPageModuleInput extends FarmMarkdownPageSource {\n components?: FarmMdxComponents;\n config?: FarmMdxResolvedConfig;\n}\n\nexport function resolveMdxConfig(config: FarmMdxUserConfig | undefined): FarmMdxResolvedConfig {\n return {\n components: config?.components,\n markdownRoutes: config?.markdownRoutes ?? true,\n className: config?.className ?? \"farm-markdown\",\n };\n}\n\nexport function isFarmMarkdownPageFile(filePath: string): boolean {\n return /(^|[/\\\\])page\\.mdx?$/i.test(filePath);\n}\n\nexport function normalizeFarmMarkdownRoutePath(pathname: string): string {\n const withoutExtension = pathname.replace(/\\.md$/i, \"\");\n const normalized = withoutExtension.startsWith(\"/\") ? withoutExtension : `/${withoutExtension}`;\n return normalized === \"/index\" ? \"/\" : normalized.replace(/\\/+$/g, \"\") || \"/\";\n}\n\nexport function parseMarkdownFrontmatter(source: string): {\n frontmatter: Record<string, string>;\n body: string;\n} {\n if (!source.startsWith(\"---\")) {\n return { frontmatter: {}, body: source };\n }\n\n const endIndex = source.indexOf(\"\\n---\", 3);\n if (endIndex === -1) {\n return { frontmatter: {}, body: source };\n }\n\n const frontmatterSource = source.slice(3, endIndex).trim();\n const closingFenceEnd = endIndex + \"\\n---\".length;\n const bodyStart =\n source.slice(closingFenceEnd, closingFenceEnd + 2) === \"\\r\\n\"\n ? closingFenceEnd + 2\n : source[closingFenceEnd] === \"\\n\"\n ? closingFenceEnd + 1\n : closingFenceEnd;\n const body = source.slice(bodyStart);\n const frontmatter: Record<string, string> = {};\n\n for (const line of frontmatterSource.split(/\\r?\\n/)) {\n const separator = line.indexOf(\":\");\n if (separator === -1) continue;\n const key = line.slice(0, separator).trim();\n const value = line\n .slice(separator + 1)\n .trim()\n .replace(/^[\"']|[\"']$/g, \"\");\n if (key && value) frontmatter[key] = value;\n }\n\n return { frontmatter, body };\n}\n\nexport function titleFromMarkdown(body: string, fallback?: string): string | undefined {\n return body.match(/^#\\s+(.+)$/m)?.[1]?.trim() || fallback;\n}\n\nexport function createMarkdownMetadata(\n source: string,\n filePath: string,\n): (Metadata & Record<string, any>) | undefined {\n const { frontmatter, body } = parseMarkdownFrontmatter(source);\n const routeTitle = titleFromMarkdown(body);\n const title = frontmatter.title || routeTitle;\n const description = frontmatter.description;\n\n if (!title && !description) {\n return undefined;\n }\n\n return {\n ...(title ? { title } : {}),\n ...(description ? { description } : {}),\n source: filePath,\n };\n}\n\nasync function evaluateMdxSource(source: string, filePath: string) {\n const [{ evaluate }, runtime, remarkGfmModule] = await Promise.all([\n import(\"@mdx-js/mdx\"),\n import(\"react/jsx-runtime\"),\n import(\"remark-gfm\"),\n ]);\n const remarkGfm = remarkGfmModule.default;\n\n return evaluate(source, {\n ...runtime,\n baseUrl: pathToFileURL(filePath),\n remarkPlugins: [remarkGfm],\n });\n}\n\nexport function createFarmMarkdownRouteModule(\n input: FarmMarkdownPageModuleInput,\n): RouteModule & { source: string } {\n const { body } = parseMarkdownFrontmatter(input.source);\n const components = input.components || {};\n const className = input.config?.className || \"farm-markdown\";\n let evaluatedPromise: Promise<{ default: React.ComponentType<any> }> | undefined;\n\n const loadContent = async () => {\n evaluatedPromise ??= evaluateMdxSource(body, input.filePath) as Promise<{\n default: React.ComponentType<any>;\n }>;\n return evaluatedPromise;\n };\n\n async function FarmMarkdownPage(props: any) {\n const evaluated = await loadContent();\n const MDXContent = evaluated.default;\n return React.createElement(\n \"article\",\n { className, \"data-farm-markdown-page\": \"\" },\n React.createElement(MDXContent, {\n ...props,\n components: {\n ...components,\n ...(props?.components || {}),\n },\n }),\n );\n }\n\n return {\n default: FarmMarkdownPage as unknown as RouteModule[\"default\"],\n metadata: createMarkdownMetadata(input.source, input.filePath),\n source: input.source,\n };\n}\n\nexport async function createFarmMarkdownRouteModuleFromFile(\n filePath: string,\n options: {\n components?: FarmMdxComponents;\n config?: FarmMdxResolvedConfig;\n } = {},\n) {\n const source = await readFile(filePath, \"utf8\");\n return createFarmMarkdownRouteModule({\n source,\n filePath,\n components: options.components,\n config: options.config,\n });\n}\n\nexport async function loadFarmMdxComponents(\n config: FarmMdxResolvedConfig | undefined,\n options: {\n root: string;\n loadModule?: (modulePath: string) => Promise<unknown>;\n },\n): Promise<FarmMdxComponents> {\n const configured = config?.components;\n if (!configured) {\n return {};\n }\n\n if (typeof configured !== \"string\") {\n return configured;\n }\n\n const modulePath = path.isAbsolute(configured) ? configured : path.join(options.root, configured);\n const mod = options.loadModule\n ? await options.loadModule(modulePath)\n : await import(pathToFileURL(modulePath).href);\n const maybeModule = mod as {\n components?: FarmMdxComponents;\n default?: FarmMdxComponents;\n };\n\n return maybeModule.components || maybeModule.default || {};\n}\n\nexport async function createFarmMarkdownSourceResponse(options: {\n request: Request;\n config?: FarmMdxResolvedConfig;\n resolveSource: (\n pathname: string,\n ) => Promise<FarmMarkdownPageSource | null> | FarmMarkdownPageSource | null;\n}): Promise<Response | null> {\n if (options.request.method !== \"GET\" && options.request.method !== \"HEAD\") {\n return null;\n }\n if (options.config?.markdownRoutes === false) {\n return null;\n }\n\n const url = new URL(options.request.url);\n if (!url.pathname.endsWith(\".md\")) {\n return null;\n }\n\n const targetPathname = normalizeFarmMarkdownRoutePath(url.pathname);\n const source = await options.resolveSource(targetPathname);\n if (!source) {\n return null;\n }\n\n return new Response(options.request.method === \"HEAD\" ? null : source.source, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/markdown; charset=utf-8\",\n \"Cache-Control\": \"public, s-maxage=60, stale-while-revalidate=300\",\n \"X-Farm-Markdown-Route\": targetPathname,\n \"X-Farm-Markdown-Source\": source.filePath,\n },\n });\n}\n","export type FarmMarkdownRouteInput =\n | string\n | {\n route: string;\n title?: string;\n cache?: number | false;\n };\n\nexport interface FarmMarkdownUserConfig {\n enabled?: boolean;\n expose?: boolean | FarmMarkdownRouteInput[];\n routes?: FarmMarkdownRouteInput[];\n cache?: number | false;\n includeMetadata?: boolean;\n}\n\nexport interface FarmMarkdownResolvedRoute {\n route: string;\n title?: string;\n cache?: number | false;\n}\n\nexport interface FarmMarkdownResolvedConfig {\n enabled: boolean;\n expose: true | FarmMarkdownResolvedRoute[];\n cache: number | false;\n includeMetadata: boolean;\n}\n\nexport interface FarmMarkdownMirrorTarget {\n pathname: string;\n route: FarmMarkdownResolvedRoute | null;\n}\n\nexport interface CreateMarkdownMirrorResponseOptions {\n request: Request;\n config?: FarmMarkdownResolvedConfig;\n routeExists?: (pathname: string) => boolean;\n renderPage: (request: Request) => Response | Promise<Response>;\n}\n\nexport function resolveMarkdownConfig(\n config: FarmMarkdownUserConfig | boolean | undefined,\n): FarmMarkdownResolvedConfig {\n if (config === false || config === undefined) {\n return {\n enabled: false,\n expose: [],\n cache: false,\n includeMetadata: true,\n };\n }\n\n if (config === true) {\n return {\n enabled: true,\n expose: true,\n cache: false,\n includeMetadata: true,\n };\n }\n\n const exposeInput = config.expose ?? config.routes ?? [];\n const expose =\n exposeInput === true\n ? true\n : Array.isArray(exposeInput)\n ? exposeInput.map(normalizeMarkdownRouteInput)\n : [];\n\n return {\n enabled: config.enabled !== false && (expose === true || expose.length > 0),\n expose,\n cache: config.cache ?? false,\n includeMetadata: config.includeMetadata ?? true,\n };\n}\n\nexport function resolveMarkdownMirrorTarget(\n config: FarmMarkdownResolvedConfig | undefined,\n pathname: string,\n): FarmMarkdownMirrorTarget | null {\n if (!config?.enabled || !pathname.endsWith(\".md\")) {\n return null;\n }\n\n const targetPathname = normalizeMarkdownRoute(pathname.slice(0, -\".md\".length) || \"/\");\n const route = findExposedMarkdownRoute(config, targetPathname);\n if (!route && config.expose !== true) {\n return null;\n }\n\n return {\n pathname: targetPathname,\n route,\n };\n}\n\nexport async function createMarkdownMirrorResponse(\n options: CreateMarkdownMirrorResponseOptions,\n): Promise<Response | null> {\n if (options.request.method !== \"GET\" && options.request.method !== \"HEAD\") {\n return null;\n }\n\n const requestUrl = new URL(options.request.url);\n const target = resolveMarkdownMirrorTarget(options.config, requestUrl.pathname);\n if (!target) {\n return null;\n }\n\n if (options.routeExists && !options.routeExists(target.pathname)) {\n return null;\n }\n\n const pageUrl = new URL(options.request.url);\n pageUrl.pathname = target.pathname;\n const headers = new Headers(options.request.headers);\n headers.set(\"accept\", \"text/html\");\n\n const pageResponse = await options.renderPage(\n new Request(pageUrl, {\n method: \"GET\",\n headers,\n }),\n );\n\n if (!isHtmlResponse(pageResponse)) {\n return null;\n }\n\n const html = await pageResponse.text();\n const markdown = htmlToMarkdown(html, {\n title: target.route?.title,\n includeMetadata: options.config?.includeMetadata ?? true,\n sourcePath: target.pathname,\n });\n const headersOut = new Headers({\n \"Content-Type\": \"text/markdown; charset=utf-8\",\n \"X-Farm-Markdown-Route\": target.pathname,\n });\n const cache = target.route?.cache ?? options.config?.cache ?? false;\n headersOut.set(\"Cache-Control\", createMarkdownCacheHeader(cache));\n\n return new Response(options.request.method === \"HEAD\" ? null : markdown, {\n status: pageResponse.status,\n headers: headersOut,\n });\n}\n\nexport function htmlToMarkdown(\n html: string,\n options: {\n title?: string;\n sourcePath?: string;\n includeMetadata?: boolean;\n } = {},\n): string {\n const title = options.title ?? extractHtmlTitle(html);\n let source = extractHtmlBody(html)\n .replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, \"\")\n .replace(/<style\\b[^>]*>[\\s\\S]*?<\\/style>/gi, \"\")\n .replace(/<noscript\\b[^>]*>[\\s\\S]*?<\\/noscript>/gi, \"\")\n .replace(/<!--[\\s\\S]*?-->/g, \"\");\n\n source = source.replace(/<pre\\b[^>]*><code\\b[^>]*>([\\s\\S]*?)<\\/code><\\/pre>/gi, (_, code) => {\n return `\\n\\n\\`\\`\\`\\n${decodeHtml(stripTags(code)).trim()}\\n\\`\\`\\`\\n\\n`;\n });\n source = source.replace(/<pre\\b[^>]*>([\\s\\S]*?)<\\/pre>/gi, (_, code) => {\n return `\\n\\n\\`\\`\\`\\n${decodeHtml(stripTags(code)).trim()}\\n\\`\\`\\`\\n\\n`;\n });\n source = source.replace(/<h([1-6])\\b[^>]*>([\\s\\S]*?)<\\/h\\1>/gi, (_, level, content) => {\n return `\\n\\n${\"#\".repeat(Number(level))} ${toInlineMarkdown(content).trim()}\\n\\n`;\n });\n source = source.replace(/<p\\b[^>]*>([\\s\\S]*?)<\\/p>/gi, (_, content) => {\n return `\\n\\n${toInlineMarkdown(content).trim()}\\n\\n`;\n });\n source = source.replace(/<blockquote\\b[^>]*>([\\s\\S]*?)<\\/blockquote>/gi, (_, content) => {\n const quote = htmlToMarkdown(content, { includeMetadata: false })\n .split(\"\\n\")\n .filter((line) => line.trim().length > 0)\n .map((line) => `> ${line}`)\n .join(\"\\n\");\n return `\\n\\n${quote}\\n\\n`;\n });\n source = source.replace(/<li\\b[^>]*>([\\s\\S]*?)<\\/li>/gi, (_, content) => {\n return `\\n- ${toInlineMarkdown(content).trim()}`;\n });\n source = source\n .replace(/<\\/?(ul|ol|main|section|article|header|footer|nav|aside|div)\\b[^>]*>/gi, \"\\n\")\n .replace(/<br\\s*\\/?>/gi, \"\\n\")\n .replace(/<hr\\s*\\/?>/gi, \"\\n\\n---\\n\\n\");\n\n let markdown = stripTags(source)\n .split(\"\\n\")\n .map((line) => line.replace(/[ \\t]+$/g, \"\"))\n .join(\"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trim();\n\n if (options.includeMetadata !== false) {\n const metadata: string[] = [];\n if (title && !markdown.startsWith(\"# \")) {\n metadata.push(`# ${title}`);\n }\n if (options.sourcePath) {\n metadata.push(`Source: ${options.sourcePath}`);\n }\n if (metadata.length) {\n markdown = `${metadata.join(\"\\n\\n\")}${markdown ? `\\n\\n${markdown}` : \"\"}`;\n }\n }\n\n return `${markdown}\\n`;\n}\n\nfunction normalizeMarkdownRouteInput(input: FarmMarkdownRouteInput): FarmMarkdownResolvedRoute {\n if (typeof input === \"string\") {\n return {\n route: normalizeMarkdownRoute(input),\n };\n }\n\n return {\n ...input,\n route: normalizeMarkdownRoute(input.route),\n };\n}\n\nfunction normalizeMarkdownRoute(route: string): string {\n const withoutMarkdownExtension = route.endsWith(\".md\") ? route.slice(0, -3) : route;\n const withSlash = withoutMarkdownExtension.startsWith(\"/\")\n ? withoutMarkdownExtension\n : `/${withoutMarkdownExtension}`;\n const normalized = withSlash.replace(/\\/+/g, \"/\").replace(/\\/$/g, \"\");\n return normalized === \"\" || normalized === \"/index\" ? \"/\" : normalized;\n}\n\nfunction findExposedMarkdownRoute(\n config: FarmMarkdownResolvedConfig,\n pathname: string,\n): FarmMarkdownResolvedRoute | null {\n if (config.expose === true) {\n return null;\n }\n\n return config.expose.find((route) => routeMatches(route.route, pathname)) ?? null;\n}\n\nfunction routeMatches(pattern: string, pathname: string): boolean {\n if (pattern === pathname) {\n return true;\n }\n\n const escaped = pattern\n .split(\"/\")\n .map((segment) => {\n if (/^\\[\\.\\.\\.[^\\]]+\\]$/.test(segment)) {\n return \".*\";\n }\n if (/^\\[[^\\]]+\\]$/.test(segment)) {\n return \"[^/]+\";\n }\n return segment.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n })\n .join(\"/\");\n\n return new RegExp(`^${escaped}$`).test(pathname);\n}\n\nfunction isHtmlResponse(response: Response): boolean {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n return contentType.includes(\"text/html\");\n}\n\nfunction createMarkdownCacheHeader(cache: number | false): string {\n if (cache === false || cache <= 0) {\n return \"no-store\";\n }\n\n return `public, max-age=${cache}, s-maxage=${cache}`;\n}\n\nfunction extractHtmlTitle(html: string): string | undefined {\n const match = html.match(/<title\\b[^>]*>([\\s\\S]*?)<\\/title>/i);\n return match ? decodeHtml(stripTags(match[1])).trim() : undefined;\n}\n\nfunction extractHtmlBody(html: string): string {\n const rootMatch = html.match(\n /<div\\b[^>]*id=[\"']root[\"'][^>]*>([\\s\\S]*?)<\\/div>\\s*(?:<script|<\\/body>|$)/i,\n );\n const bodyMatch = html.match(/<body\\b[^>]*>([\\s\\S]*?)<\\/body>/i);\n const body = rootMatch ? rootMatch[1] : bodyMatch ? bodyMatch[1] : html;\n return extractFirstElementContent(body, [\"main\", \"article\"]) ?? body;\n}\n\nfunction extractFirstElementContent(html: string, tagNames: string[]): string | undefined {\n for (const tagName of tagNames) {\n const match = html.match(new RegExp(`<${tagName}\\\\b[^>]*>([\\\\s\\\\S]*?)<\\\\/${tagName}>`, \"i\"));\n if (match) {\n return match[1];\n }\n }\n\n return undefined;\n}\n\nfunction toInlineMarkdown(html: string): string {\n let source = html\n .replace(/<a\\b[^>]*href=[\"']([^\"']+)[\"'][^>]*>([\\s\\S]*?)<\\/a>/gi, (_, href, text) => {\n const label: string = toInlineMarkdown(text).trim() || href;\n return `[${label}](${decodeHtml(href)})`;\n })\n .replace(\n /<img\\b[^>]*src=[\"']([^\"']+)[\"'][^>]*alt=[\"']([^\"']*)[\"'][^>]*\\/?>/gi,\n (_, src, alt) => {\n return `![${decodeHtml(alt)}](${decodeHtml(src)})`;\n },\n )\n .replace(/<strong\\b[^>]*>([\\s\\S]*?)<\\/strong>/gi, (_, content) => {\n return `**${toInlineMarkdown(content).trim()}**`;\n })\n .replace(/<b\\b[^>]*>([\\s\\S]*?)<\\/b>/gi, (_, content) => {\n return `**${toInlineMarkdown(content).trim()}**`;\n })\n .replace(/<em\\b[^>]*>([\\s\\S]*?)<\\/em>/gi, (_, content) => {\n return `_${toInlineMarkdown(content).trim()}_`;\n })\n .replace(/<i\\b[^>]*>([\\s\\S]*?)<\\/i>/gi, (_, content) => {\n return `_${toInlineMarkdown(content).trim()}_`;\n })\n .replace(/<code\\b[^>]*>([\\s\\S]*?)<\\/code>/gi, (_, content) => {\n return `\\`${decodeHtml(stripTags(content)).trim()}\\``;\n })\n .replace(/<br\\s*\\/?>/gi, \"\\n\");\n\n source = stripTags(source);\n return decodeHtml(source).replace(/\\s+/g, \" \");\n}\n\nfunction stripTags(input: string): string {\n return input.replace(/<[^>]+>/g, \"\");\n}\n\nfunction decodeHtml(input: string): string {\n return input\n .replace(/&nbsp;/g, \" \")\n .replace(/&amp;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(Number.parseInt(code, 16)))\n .replace(/&#(\\d+);/g, (_, code) => String.fromCodePoint(Number.parseInt(code, 10)));\n}\n","export type FarmWorkflowSchedule = string | string[];\n\nexport interface FarmWorkflowsUserConfig {\n /** Enable or disable Farm workflow discovery. Enabled by default. */\n enabled?: boolean;\n /** Directory or directories to scan for workflow modules. */\n dir?: string | string[];\n /** Alias for dir. */\n dirs?: string[];\n /** HTTP route used for manual and URL-based cron invocation. */\n route?: string;\n /** Environment variable that stores the optional runner secret. */\n secretEnv?: string;\n /** Inline runner secret. Prefer secretEnv for deployed apps. */\n secret?: string;\n}\n\nexport interface FarmWorkflowsResolvedConfig {\n enabled: boolean;\n dirs: string[];\n route: string;\n secretEnv: string;\n secret?: string;\n}\n\nexport interface FarmWorkflowLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n}\n\nexport interface FarmWorkflowRunContext<TPayload = unknown> {\n id: string;\n name: string;\n payload: TPayload;\n scheduledTime?: number | string;\n request?: Request;\n event?: unknown;\n env: Record<string, string | undefined>;\n data: Map<string, unknown>;\n log: FarmWorkflowLogger;\n}\n\nexport interface FarmWorkflowDefinition<TPayload = unknown, TResult = unknown> {\n kind?: \"farm-workflow\";\n id?: string;\n description?: string;\n schedule?: FarmWorkflowSchedule;\n timezone?: string;\n run: (ctx: FarmWorkflowRunContext<TPayload>) => TResult | Promise<TResult>;\n}\n\nexport interface FarmCronDefinition<TPayload = unknown, TResult = unknown>\n extends FarmWorkflowDefinition<TPayload, TResult> {\n schedule: FarmWorkflowSchedule;\n}\n\nexport interface FarmDiscoveredWorkflow {\n id: string;\n filePath: string;\n description?: string;\n schedule: string[];\n timezone?: string;\n routePath: string;\n}\n\nexport interface PreparedFarmWorkflows {\n workflows: FarmDiscoveredWorkflow[];\n tasks: Record<string, { handler: string; description: string }>;\n scheduledTasks: Record<string, string | string[]>;\n handlerPath?: string;\n manifestPath?: string;\n}\n\nexport interface FarmWorkflowHTTPHandlerOptions {\n workflows: FarmDiscoveredWorkflow[];\n config: FarmWorkflowsResolvedConfig;\n loadModule: (workflow: FarmDiscoveredWorkflow) => Promise<Record<string, any>>;\n}\n\nexport const DEFAULT_FARM_WORKFLOW_DIRS = [\"src/jobs\", \"src/workflows\", \"src/cron\"];\nexport const DEFAULT_FARM_WORKFLOW_ROUTE = \"/api/_farm/workflows\";\nexport const DEFAULT_FARM_WORKFLOW_SECRET_ENV = \"CRON_SECRET\";\n\nexport function defineWorkflow<const TPayload = unknown, TResult = unknown>(\n definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n return {\n ...definition,\n kind: \"farm-workflow\",\n };\n}\n\nexport function defineTask<const TPayload = unknown, TResult = unknown>(\n definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n return defineWorkflow(definition);\n}\n\n/**\n * @deprecated Configure `cron` in `farm.config.ts` and point it at an API route.\n */\nexport function defineCron<const TPayload = unknown, TResult = unknown>(\n definition: FarmCronDefinition<TPayload, TResult>,\n): FarmCronDefinition<TPayload, TResult> {\n return {\n ...definition,\n kind: \"farm-workflow\",\n };\n}\n\nexport function resolveWorkflowsConfig(\n workflows: FarmWorkflowsUserConfig | boolean | undefined,\n): FarmWorkflowsResolvedConfig {\n if (workflows === false) {\n return {\n enabled: false,\n dirs: [...DEFAULT_FARM_WORKFLOW_DIRS],\n route: DEFAULT_FARM_WORKFLOW_ROUTE,\n secretEnv: DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n };\n }\n\n const options = workflows && typeof workflows === \"object\" ? workflows : {};\n const dirs = normalizeWorkflowDirs(options);\n\n return {\n enabled: options.enabled ?? true,\n dirs,\n route: normalizeWorkflowRoute(options.route || DEFAULT_FARM_WORKFLOW_ROUTE),\n secretEnv: options.secretEnv || DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n secret: options.secret,\n };\n}\n\nexport async function discoverFarmWorkflows(\n config: { root?: string; workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean },\n options: {\n loadModule?: (filePath: string) => Promise<Record<string, any>>;\n } = {},\n): Promise<FarmDiscoveredWorkflow[]> {\n const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n ? config.workflows\n : resolveWorkflowsConfig(config.workflows);\n if (!workflowConfig.enabled) return [];\n\n const root = config.root || process.cwd();\n const files = await findWorkflowFiles(root, workflowConfig.dirs);\n const workflows: FarmDiscoveredWorkflow[] = [];\n const seenIds = new Map<string, string>();\n\n for (const filePath of files) {\n const module = options.loadModule\n ? await options.loadModule(filePath)\n : await loadWorkflowModule(filePath, root);\n const definition = resolveWorkflowDefinition(module);\n if (!definition) continue;\n\n const id = normalizeWorkflowId(definition.id || workflowIdFromFile(root, filePath));\n const previousPath = seenIds.get(id);\n if (previousPath) {\n throw new Error(\n `Duplicate Farm workflow id \"${id}\" found in ${relativePath(root, previousPath)} and ${relativePath(root, filePath)}.`,\n );\n }\n seenIds.set(id, filePath);\n\n workflows.push({\n id,\n filePath,\n description: definition.description,\n schedule: normalizeSchedule(definition.schedule),\n timezone: definition.timezone,\n routePath: joinRoute(workflowConfig.route, encodeURIComponent(id)),\n });\n }\n\n return workflows;\n}\n\nexport function createFarmWorkflowRequestHandler(options: FarmWorkflowHTTPHandlerOptions) {\n const workflowsById = new Map(options.workflows.map((workflow) => [workflow.id, workflow]));\n\n return async function handleFarmWorkflowRequest(request: Request): Promise<Response | null> {\n const url = new URL(request.url);\n const route = normalizeWorkflowRoute(options.config.route);\n if (url.pathname !== route && !url.pathname.startsWith(`${route}/`)) {\n return null;\n }\n\n if (url.pathname === route) {\n const secretError = verifyWorkflowSecret(request, options.config);\n if (secretError) return secretError;\n\n return Response.json({\n workflows: options.workflows.map(toWorkflowMetadata),\n });\n }\n\n const id = decodeURIComponent(url.pathname.slice(route.length + 1));\n const workflow = workflowsById.get(id);\n if (!workflow) {\n return Response.json({ error: `Workflow \"${id}\" was not found.` }, { status: 404 });\n }\n\n const secretError = verifyWorkflowSecret(request, options.config);\n if (secretError) return secretError;\n\n const payload = await readWorkflowPayload(request);\n const module = await options.loadModule(workflow);\n const result = await runFarmWorkflowModule(module, {\n id: workflow.id,\n name: workflow.id,\n payload,\n request,\n scheduledTime: readScheduledTime(payload),\n });\n\n return Response.json({\n id: workflow.id,\n ok: true,\n result: result ?? null,\n });\n };\n}\n\nexport async function runFarmWorkflowModule(\n module: Record<string, any>,\n context: {\n id: string;\n name?: string;\n payload?: unknown;\n scheduledTime?: number | string;\n request?: Request;\n event?: unknown;\n env?: Record<string, string | undefined>;\n },\n): Promise<unknown> {\n const definition = resolveWorkflowDefinition(module);\n if (!definition) {\n throw new Error(`Farm workflow \"${context.id}\" does not export a workflow definition.`);\n }\n\n return await definition.run({\n id: context.id,\n name: context.name || context.id,\n payload: context.payload,\n scheduledTime: context.scheduledTime,\n request: context.request,\n event: context.event,\n env: context.env || process.env,\n data: new Map<string, unknown>(),\n log: console,\n });\n}\n\nexport async function prepareFarmWorkflowsForNitro(\n config: { root?: string; distDir?: string; workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean },\n): Promise<PreparedFarmWorkflows> {\n const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n ? config.workflows\n : resolveWorkflowsConfig(config.workflows);\n const workflows = await discoverFarmWorkflows({\n root: config.root,\n workflows: workflowConfig,\n });\n\n if (workflows.length === 0) {\n return {\n workflows,\n tasks: {},\n scheduledTasks: {},\n };\n }\n\n const root = config.root || process.cwd();\n const distDir = config.distDir || \".farm\";\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const generatedDir = path.join(root, distDir, \".nitro\", \"farm-workflows\");\n await fs.mkdir(generatedDir, { recursive: true });\n\n const tasks: PreparedFarmWorkflows[\"tasks\"] = {};\n const scheduledTasks = createScheduledTasks(workflows);\n\n for (const workflow of workflows) {\n const wrapperPath = path.join(generatedDir, `${safeFileName(workflow.id)}.mjs`);\n await fs.writeFile(wrapperPath, createNitroTaskWrapper(workflow), \"utf8\");\n tasks[workflow.id] = {\n handler: wrapperPath,\n description: workflow.description || `Farm workflow ${workflow.id}`,\n };\n }\n\n const handlerPath = path.join(generatedDir, \"http-handler.mjs\");\n await fs.writeFile(handlerPath, createNitroWorkflowHTTPHandler(workflowConfig, workflows), \"utf8\");\n\n const manifestPath = path.join(generatedDir, \"manifest.json\");\n await fs.writeFile(\n manifestPath,\n JSON.stringify(\n {\n route: workflowConfig.route,\n secretEnv: workflowConfig.secretEnv,\n trigger: {\n method: \"GET\",\n authorization: `Bearer $${workflowConfig.secretEnv}`,\n },\n workflows: workflows.map(toWorkflowMetadata),\n },\n null,\n 2,\n ),\n \"utf8\",\n );\n\n return {\n workflows,\n tasks,\n scheduledTasks,\n handlerPath,\n manifestPath,\n };\n}\n\nexport function createFarmWorkflowVercelCrons(\n workflows: FarmDiscoveredWorkflow[],\n): Array<{ path: string; schedule: string }> {\n return workflows.flatMap((workflow) =>\n workflow.schedule.map((schedule) => ({\n path: workflow.routePath,\n schedule,\n })),\n );\n}\n\nexport function applyFarmWorkflowVercelCrons(\n vercelConfig: Record<string, any>,\n workflows: FarmDiscoveredWorkflow[],\n): Record<string, any> {\n const crons = createFarmWorkflowVercelCrons(workflows);\n if (crons.length === 0) return vercelConfig;\n\n const existingCrons = Array.isArray(vercelConfig.crons) ? vercelConfig.crons : [];\n const seen = new Set(existingCrons.map((cron) => `${cron.path}:${cron.schedule}`));\n const nextCrons = [...existingCrons];\n for (const cron of crons) {\n const key = `${cron.path}:${cron.schedule}`;\n if (seen.has(key)) continue;\n seen.add(key);\n nextCrons.push(cron);\n }\n return {\n ...vercelConfig,\n crons: nextCrons,\n };\n}\n\nfunction isResolvedWorkflowConfig(value: unknown): value is FarmWorkflowsResolvedConfig {\n return (\n !!value &&\n typeof value === \"object\" &&\n \"dirs\" in value &&\n Array.isArray((value as FarmWorkflowsResolvedConfig).dirs) &&\n typeof (value as FarmWorkflowsResolvedConfig).route === \"string\"\n );\n}\n\nfunction normalizeWorkflowDirs(options: FarmWorkflowsUserConfig): string[] {\n const rawDirs = options.dirs || (Array.isArray(options.dir) ? options.dir : options.dir ? [options.dir] : undefined);\n const dirs = rawDirs && rawDirs.length > 0 ? rawDirs : DEFAULT_FARM_WORKFLOW_DIRS;\n return [...new Set(dirs.map((dir) => trimSlashes(dir)).filter(Boolean))];\n}\n\nfunction normalizeWorkflowRoute(route: string): string {\n const trimmed = route.trim();\n if (!trimmed || trimmed === \"/\") return DEFAULT_FARM_WORKFLOW_ROUTE;\n return `/${trimSlashes(trimmed)}`;\n}\n\nfunction normalizeWorkflowId(id: string): string {\n const normalized = id\n .replace(/\\\\/g, \"/\")\n .replace(/\\.(tsx?|jsx?|mjs|cjs)$/, \"\")\n .replace(/\\/index$/, \"\")\n .replace(/[^a-zA-Z0-9._/-]+/g, \"-\")\n .replace(/^\\/+|\\/+$/g, \"\")\n .replace(/\\/+/g, \"/\");\n return normalized || \"workflow\";\n}\n\nfunction normalizeSchedule(schedule: FarmWorkflowSchedule | undefined): string[] {\n if (!schedule) return [];\n return (Array.isArray(schedule) ? schedule : [schedule]).map((value) => value.trim()).filter(Boolean);\n}\n\nfunction resolveWorkflowDefinition(\n module: Record<string, any>,\n): FarmWorkflowDefinition | FarmCronDefinition | null {\n const candidates = [\n module.default,\n module.workflow,\n module.cron,\n module.task,\n module.job,\n ];\n for (const candidate of candidates) {\n if (candidate && typeof candidate === \"object\" && typeof candidate.run === \"function\") {\n return candidate as FarmWorkflowDefinition;\n }\n }\n return null;\n}\n\nasync function findWorkflowFiles(root: string, dirs: string[]): Promise<string[]> {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const files: string[] = [];\n\n for (const dir of dirs) {\n const absoluteDir = path.isAbsolute(dir) ? dir : path.join(root, dir);\n if (!(await pathExists(absoluteDir))) continue;\n await walkWorkflowDir(absoluteDir, files);\n }\n\n return files.sort();\n}\n\nasync function walkWorkflowDir(dir: string, files: string[]): Promise<void> {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const filePath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n await walkWorkflowDir(filePath, files);\n continue;\n }\n if (isWorkflowFile(entry.name)) {\n files.push(filePath);\n }\n }\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n const fs = await import(\"fs/promises\");\n return fs\n .access(filePath)\n .then(() => true)\n .catch(() => false);\n}\n\nfunction isWorkflowFile(fileName: string): boolean {\n return /\\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(fileName) && !/\\.d\\.[cm]?ts$/.test(fileName);\n}\n\nasync function loadWorkflowModule(filePath: string, root: string): Promise<Record<string, any>> {\n const fs = await import(\"fs/promises\");\n const path = await import(\"path\");\n const { pathToFileURL } = await import(\"url\");\n const { build } = await import(\"esbuild\");\n const outDir = path.join(root, \".farm\", \".workflow-loader\");\n await fs.mkdir(outDir, { recursive: true });\n const outfile = path.join(\n outDir,\n `workflow-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n await build({\n absWorkingDir: root,\n entryPoints: [filePath],\n outfile,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: `node${process.versions.node.split(\".\")[0]}`,\n packages: \"external\",\n external: [\"@farm.js/core\", \"@farm.js/core/*\", \"nitro\", \"nitro/*\"],\n jsx: \"automatic\",\n logLevel: \"silent\",\n sourcemap: \"inline\",\n });\n\n try {\n return await import(/* @vite-ignore */ `${pathToFileURL(outfile).href}?t=${Date.now()}`);\n } finally {\n await fs.unlink(outfile).catch(() => undefined);\n }\n}\n\nfunction workflowIdFromFile(root: string, filePath: string): string {\n const normalizedRoot = root.replace(/\\\\/g, \"/\");\n const normalizedFile = filePath.replace(/\\\\/g, \"/\");\n const relative = normalizedFile.startsWith(`${normalizedRoot}/`)\n ? normalizedFile.slice(normalizedRoot.length + 1)\n : normalizedFile;\n return normalizeWorkflowId(\n relative\n .replace(/^src\\/(?:jobs|workflows|cron)\\//, \"\")\n .replace(/\\.(tsx?|jsx?|mjs|cjs)$/, \"\"),\n );\n}\n\nfunction createScheduledTasks(workflows: FarmDiscoveredWorkflow[]): Record<string, string | string[]> {\n const scheduleMap = new Map<string, string[]>();\n for (const workflow of workflows) {\n for (const schedule of workflow.schedule) {\n const taskIds = scheduleMap.get(schedule) || [];\n taskIds.push(workflow.id);\n scheduleMap.set(schedule, taskIds);\n }\n }\n\n return Object.fromEntries(\n [...scheduleMap.entries()].map(([schedule, taskIds]) => [\n schedule,\n taskIds.length === 1 ? taskIds[0] : taskIds,\n ]),\n );\n}\n\nfunction createNitroTaskWrapper(workflow: FarmDiscoveredWorkflow): string {\n const normalizedPath = workflow.filePath.replace(/\\\\/g, \"/\");\n return `\nimport { defineTask } from \"nitro/runtime\";\nimport { runFarmWorkflowModule } from \"@farm.js/core/workflows\";\nimport * as workflowModule from ${JSON.stringify(normalizedPath)};\n\nexport default defineTask({\n meta: {\n description: ${JSON.stringify(workflow.description || `Farm workflow ${workflow.id}`)}\n },\n async run(event) {\n const payload = event?.payload || {};\n const env = event?.context?.cloudflare?.env || event?.context?.env || process.env;\n return await runFarmWorkflowModule(workflowModule, {\n id: ${JSON.stringify(workflow.id)},\n name: event?.name || ${JSON.stringify(workflow.id)},\n payload,\n scheduledTime: payload.scheduledTime,\n request: event?.context?.request,\n event,\n env\n });\n }\n});\n`.trim();\n}\n\nfunction createNitroWorkflowHTTPHandler(\n config: FarmWorkflowsResolvedConfig,\n workflows: FarmDiscoveredWorkflow[],\n): string {\n return `\nimport { H3 } from \"h3\";\nimport { runTask } from \"nitro/runtime\";\n\nconst route = ${JSON.stringify(config.route)};\nconst secretEnv = ${JSON.stringify(config.secretEnv)};\nconst inlineSecret = ${JSON.stringify(config.secret || \"\")};\nconst workflows = ${JSON.stringify(workflows.map(toWorkflowMetadata))};\nconst workflowIds = new Set(workflows.map((workflow) => workflow.id));\n\nfunction json(value, status = 200) {\n return new Response(JSON.stringify(value), {\n status,\n headers: { \"content-type\": \"application/json\" }\n });\n}\n\nfunction getHeader(event, name) {\n return event.req.headers.get(name);\n}\n\nfunction getSecret() {\n return inlineSecret || process.env[secretEnv] || \"\";\n}\n\nfunction verifySecret(event) {\n const secret = getSecret();\n if (!secret) return null;\n const authorization = getHeader(event, \"authorization\") || \"\";\n const headerSecret = getHeader(event, \"x-farm-workflow-secret\") || \"\";\n const querySecret = event.url.searchParams.get(\"secret\") || \"\";\n const bearer = authorization.startsWith(\"Bearer \") ? authorization.slice(7) : \"\";\n if (headerSecret === secret || querySecret === secret || bearer === secret) return null;\n return json({ error: \"Unauthorized workflow request.\" }, 401);\n}\n\nasync function readPayload(event) {\n if (event.req.method === \"GET\" || event.req.method === \"HEAD\") {\n const payload = Object.fromEntries(event.url.searchParams.entries());\n delete payload.secret;\n return payload;\n }\n return await event.req.json().catch(() => ({}));\n}\n\nexport default new H3()\n .get(route, (event) => {\n const unauthorized = verifySecret(event);\n if (unauthorized) return unauthorized;\n return { workflows };\n })\n .all(route + \"/:id\", async (event) => {\n const id = decodeURIComponent(event.context.params?.id || \"\");\n if (!workflowIds.has(id)) {\n return json({ error: \"Workflow \" + id + \" was not found.\" }, 404);\n }\n\n const unauthorized = verifySecret(event);\n if (unauthorized) return unauthorized;\n\n const payload = await readPayload(event);\n const result = await runTask(id, {\n payload,\n context: {\n source: \"http\",\n request: event.req,\n route,\n url: event.url.href,\n method: event.req.method\n }\n });\n return {\n id,\n ok: true,\n result: result ?? null\n };\n });\n`.trim();\n}\n\nfunction toWorkflowMetadata(workflow: FarmDiscoveredWorkflow) {\n return {\n id: workflow.id,\n description: workflow.description || null,\n schedule: workflow.schedule,\n timezone: workflow.timezone || null,\n path: workflow.routePath,\n };\n}\n\nasync function readWorkflowPayload(request: Request): Promise<unknown> {\n const url = new URL(request.url);\n if (request.method === \"GET\" || request.method === \"HEAD\") {\n const payload = Object.fromEntries(url.searchParams.entries());\n delete payload.secret;\n return payload;\n }\n\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (contentType.includes(\"application/json\")) {\n return await request.json().catch(() => ({}));\n }\n\n const text = await request.text().catch(() => \"\");\n return text ? { text } : {};\n}\n\nfunction readScheduledTime(payload: unknown): number | string | undefined {\n return payload && typeof payload === \"object\" && \"scheduledTime\" in payload\n ? (payload as { scheduledTime?: number | string }).scheduledTime\n : undefined;\n}\n\nfunction verifyWorkflowSecret(\n request: Request,\n config: FarmWorkflowsResolvedConfig,\n): Response | null {\n const secret = config.secret || process.env[config.secretEnv] || \"\";\n if (!secret) return null;\n\n const url = new URL(request.url);\n const authorization = request.headers.get(\"authorization\") || \"\";\n const bearer = authorization.startsWith(\"Bearer \") ? authorization.slice(7) : \"\";\n const headerSecret = request.headers.get(\"x-farm-workflow-secret\") || \"\";\n const querySecret = url.searchParams.get(\"secret\") || \"\";\n if (bearer === secret || headerSecret === secret || querySecret === secret) return null;\n\n return Response.json({ error: \"Unauthorized workflow request.\" }, { status: 401 });\n}\n\nfunction joinRoute(...parts: string[]): string {\n return `/${parts.map((part) => trimSlashes(part)).filter(Boolean).join(\"/\")}`;\n}\n\nfunction trimSlashes(value: string): string {\n return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nfunction safeFileName(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"workflow\";\n}\n\nfunction relativePath(root: string, filePath: string): string {\n return filePath.replace(/\\\\/g, \"/\").replace(`${root.replace(/\\\\/g, \"/\")}/`, \"\");\n}\n","export type FarmCronSchedule = string | string[];\n\nexport interface FarmCronJobConfig {\n /** Portable five-field cron expression, or a list of expressions. */\n schedule: FarmCronSchedule;\n /** Farm API route invoked with GET when the schedule fires. */\n path: string;\n /** Human-readable purpose shown by local tooling and deployment manifests. */\n description?: string;\n /** Disable this schedule without removing its configuration. */\n enabled?: boolean;\n}\n\nexport type FarmCronUserConfig = Record<string, FarmCronJobConfig>;\n\nexport interface FarmCronJob {\n name: string;\n schedule: string[];\n path: string;\n description?: string;\n}\n\nexport interface FarmCronResolvedConfig {\n enabled: boolean;\n secretEnv: typeof DEFAULT_FARM_CRON_SECRET_ENV;\n jobs: FarmCronJob[];\n}\n\nexport interface PreparedFarmCron {\n jobs: FarmCronJob[];\n tasks: Record<string, { handler: string; description: string }>;\n scheduledTasks: Record<string, string | string[]>;\n manifestPath?: string;\n}\n\nexport interface FarmCronRouteOptions {\n /** Environment variable containing the bearer token. */\n secretEnv?: string;\n /** Inline token, primarily useful in tests. Environment variables are preferred. */\n secret?: string;\n /** Allow a production route without a secret. Defaults to false. */\n allowUnsecured?: boolean;\n}\n\nexport interface FarmCronCloudflareConfig {\n deployConfig: true;\n wrangler: {\n triggers: {\n crons: string[];\n };\n };\n}\n\nexport const DEFAULT_FARM_CRON_SECRET_ENV = \"CRON_SECRET\";\nexport const FARM_CRON_MANIFEST = \"cron-manifest.json\";\n\nconst CRON_FIELD_RANGES = [\n [0, 59, \"minute\"],\n [0, 23, \"hour\"],\n [1, 31, \"day of month\"],\n [1, 12, \"month\"],\n [0, 6, \"day of week\"],\n] as const;\n\nexport function resolveCronConfig(\n cron: FarmCronResolvedConfig | FarmCronUserConfig | false | undefined,\n): FarmCronResolvedConfig {\n if (isResolvedCronConfig(cron)) return cron;\n if (!cron) {\n return {\n enabled: false,\n secretEnv: DEFAULT_FARM_CRON_SECRET_ENV,\n jobs: [],\n };\n }\n\n const jobs: FarmCronJob[] = [];\n for (const [name, job] of Object.entries(cron)) {\n if (!job || typeof job !== \"object\" || Array.isArray(job)) {\n throw new TypeError(`Farm cron ${JSON.stringify(name)} must be a configuration object.`);\n }\n if (job.enabled === false) continue;\n jobs.push(normalizeCronJob(name, job));\n }\n\n return {\n enabled: jobs.length > 0,\n secretEnv: DEFAULT_FARM_CRON_SECRET_ENV,\n jobs,\n };\n}\n\nexport async function prepareFarmCronForNitro(config: {\n root?: string;\n distDir?: string;\n cron?: FarmCronResolvedConfig | FarmCronUserConfig | false;\n}): Promise<PreparedFarmCron> {\n const cron = isResolvedCronConfig(config.cron) ? config.cron : resolveCronConfig(config.cron);\n const root = config.root || process.cwd();\n const distDir = config.distDir || \".farm\";\n const fs = await import(\"node:fs/promises\");\n const path = await import(\"node:path\");\n const manifestPath = path.join(root, distDir, FARM_CRON_MANIFEST);\n const generatedDir = path.join(root, distDir, \".nitro\", \"farm-cron\");\n\n if (!cron.enabled) {\n await Promise.all([\n fs.rm(manifestPath, { force: true }),\n fs.rm(generatedDir, { recursive: true, force: true }),\n ]);\n return {\n jobs: [],\n tasks: {},\n scheduledTasks: {},\n };\n }\n\n await fs.rm(generatedDir, { recursive: true, force: true });\n await fs.mkdir(generatedDir, { recursive: true });\n\n const tasks: PreparedFarmCron[\"tasks\"] = {};\n for (const job of cron.jobs) {\n const taskName = getFarmCronTaskName(job.name);\n const wrapperPath = path.join(generatedDir, `${safeFileName(job.name)}.mjs`);\n await fs.writeFile(wrapperPath, createNitroCronTaskWrapper(job, cron.secretEnv), \"utf8\");\n tasks[taskName] = {\n handler: wrapperPath,\n description: job.description || `Farm cron ${job.name}`,\n };\n }\n\n const manifest = createFarmCronManifest(cron);\n await fs.mkdir(path.dirname(manifestPath), { recursive: true });\n await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`, \"utf8\");\n\n return {\n jobs: cron.jobs,\n tasks,\n scheduledTasks: createCronScheduledTasks(cron.jobs),\n manifestPath,\n };\n}\n\nexport function createFarmCronManifest(cron: FarmCronResolvedConfig) {\n return {\n schemaVersion: 1,\n secretEnv: cron.secretEnv,\n jobs: cron.jobs.map((job) => ({\n name: job.name,\n schedule: job.schedule,\n path: job.path,\n description: job.description || null,\n })),\n };\n}\n\nexport function createFarmCronVercelCrons(\n jobs: FarmCronJob[],\n): Array<{ path: string; schedule: string }> {\n return jobs.flatMap((job) =>\n job.schedule.map((schedule) => ({\n path: job.path,\n schedule,\n })),\n );\n}\n\nexport function applyFarmCronVercelCrons(\n vercelConfig: Record<string, any>,\n jobs: FarmCronJob[],\n): Record<string, any> {\n const existingCrons = Array.isArray(vercelConfig.crons) ? vercelConfig.crons : [];\n const seen = new Set(existingCrons.map((cron) => `${cron.path}:${cron.schedule}`));\n const crons = [...existingCrons];\n\n for (const cron of createFarmCronVercelCrons(jobs)) {\n const key = `${cron.path}:${cron.schedule}`;\n if (seen.has(key)) continue;\n seen.add(key);\n crons.push(cron);\n }\n\n return crons.length > 0 ? { ...vercelConfig, crons } : vercelConfig;\n}\n\nexport function createFarmCronCloudflareTriggers(jobs: FarmCronJob[]): string[] {\n return [...new Set(jobs.flatMap((job) => job.schedule))];\n}\n\nexport function createFarmCronCloudflareConfig(\n jobs: FarmCronJob[],\n): FarmCronCloudflareConfig | undefined {\n const crons = createFarmCronCloudflareTriggers(jobs);\n if (crons.length === 0) return undefined;\n\n return {\n deployConfig: true,\n wrangler: {\n triggers: { crons },\n },\n };\n}\n\nexport function mergeScheduledTasks(\n ...maps: Array<Record<string, string | string[]> | undefined>\n): Record<string, string | string[]> {\n const merged = new Map<string, string[]>();\n\n for (const map of maps) {\n for (const [schedule, taskNames] of Object.entries(map || {})) {\n const current = merged.get(schedule) || [];\n for (const taskName of Array.isArray(taskNames) ? taskNames : [taskNames]) {\n if (!current.includes(taskName)) current.push(taskName);\n }\n merged.set(schedule, current);\n }\n }\n\n return Object.fromEntries(\n [...merged].map(([schedule, taskNames]) => [\n schedule,\n taskNames.length === 1 ? taskNames[0] : taskNames,\n ]),\n );\n}\n\nexport function isCronRequestAuthorized(\n request: Request,\n options: FarmCronRouteOptions = {},\n): boolean {\n const secretEnv = options.secretEnv || DEFAULT_FARM_CRON_SECRET_ENV;\n const secret = options.secret || readEnvironmentValue(secretEnv);\n if (!secret) {\n return (\n options.allowUnsecured === true ||\n (!getFarmRuntimeBindings() && readEnvironmentValue(\"NODE_ENV\") !== \"production\")\n );\n }\n\n const authorization = request.headers.get(\"authorization\") || \"\";\n const bearer = authorization.startsWith(\"Bearer \") ? authorization.slice(7) : \"\";\n return bearer === secret || request.headers.get(\"x-farm-cron-secret\") === secret;\n}\n\nexport function cronRoute<TArgs extends unknown[], TResult>(\n handler: (request: Request, ...args: TArgs) => TResult,\n options: FarmCronRouteOptions = {},\n): (request: Request, ...args: TArgs) => TResult | Promise<Response> {\n return (request, ...args) => {\n if (!isCronRequestAuthorized(request, options)) {\n return Promise.resolve(\n Response.json({ error: \"Unauthorized cron request.\" }, { status: 401 }),\n );\n }\n return handler(request, ...args);\n };\n}\n\nfunction normalizeCronJob(name: string, job: FarmCronJobConfig): FarmCronJob {\n if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name)) {\n throw new TypeError(\n `Farm cron name ${JSON.stringify(name)} must start with a letter or number and contain only letters, numbers, dots, underscores, or hyphens.`,\n );\n }\n if (!job || typeof job !== \"object\" || Array.isArray(job)) {\n throw new TypeError(`Farm cron ${JSON.stringify(name)} must be a configuration object.`);\n }\n\n const path = normalizeCronPath(name, job.path);\n const rawSchedule = Array.isArray(job.schedule) ? job.schedule : [job.schedule];\n const schedule = [...new Set(rawSchedule.map((value) => normalizeCronExpression(name, value)))];\n if (schedule.length === 0) {\n throw new TypeError(`Farm cron ${JSON.stringify(name)} must define at least one schedule.`);\n }\n\n return {\n name,\n schedule,\n path,\n description: job.description?.trim() || undefined,\n };\n}\n\nfunction normalizeCronPath(name: string, value: unknown): string {\n if (typeof value !== \"string\" || !value.trim().startsWith(\"/\")) {\n throw new TypeError(`Farm cron ${JSON.stringify(name)} path must start with \"/\".`);\n }\n\n const path = value.trim();\n if (path.startsWith(\"//\") || path.includes(\"?\") || path.includes(\"#\")) {\n throw new TypeError(\n `Farm cron ${JSON.stringify(name)} path must be an application pathname without a host, query, or hash.`,\n );\n }\n return path.length > 1 ? path.replace(/\\/+$/, \"\") : path;\n}\n\nfunction normalizeCronExpression(name: string, value: unknown): string {\n if (typeof value !== \"string\") {\n throw new TypeError(`Farm cron ${JSON.stringify(name)} schedule must be a string.`);\n }\n\n const expression = value.trim().replace(/\\s+/g, \" \");\n const fields = expression.split(\" \");\n if (fields.length !== CRON_FIELD_RANGES.length) {\n throw new TypeError(\n `Farm cron ${JSON.stringify(name)} schedule ${JSON.stringify(expression)} must use five fields: minute hour day-of-month month day-of-week.`,\n );\n }\n\n fields.forEach((field, index) => {\n const [minimum, maximum, label] = CRON_FIELD_RANGES[index];\n validateCronField(name, expression, field, minimum, maximum, label);\n });\n if (fields[2] !== \"*\" && fields[4] !== \"*\") {\n throw new TypeError(\n `Farm cron ${JSON.stringify(name)} schedule ${JSON.stringify(expression)} cannot constrain both day-of-month and day-of-week.`,\n );\n }\n return expression;\n}\n\nfunction validateCronField(\n name: string,\n expression: string,\n field: string,\n minimum: number,\n maximum: number,\n label: string,\n): void {\n for (const segment of field.split(\",\")) {\n const [range, stepText, ...extra] = segment.split(\"/\");\n if (!range || extra.length > 0 || (stepText !== undefined && !isIntegerInRange(stepText, 1))) {\n throwInvalidCronField(name, expression, label);\n }\n\n if (range === \"*\") continue;\n const bounds = range.split(\"-\");\n if (bounds.length > 2 || !bounds.every((value) => isIntegerInRange(value, minimum, maximum))) {\n throwInvalidCronField(name, expression, label);\n }\n if (bounds.length === 2 && Number(bounds[0]) > Number(bounds[1])) {\n throwInvalidCronField(name, expression, label);\n }\n }\n}\n\nfunction isIntegerInRange(value: string, minimum: number, maximum = Number.MAX_SAFE_INTEGER) {\n if (!/^\\d+$/.test(value)) return false;\n const parsed = Number(value);\n return parsed >= minimum && parsed <= maximum;\n}\n\nfunction throwInvalidCronField(name: string, expression: string, label: string): never {\n throw new TypeError(\n `Farm cron ${JSON.stringify(name)} schedule ${JSON.stringify(expression)} has an invalid ${label} field.`,\n );\n}\n\nfunction isResolvedCronConfig(value: unknown): value is FarmCronResolvedConfig {\n return (\n !!value &&\n typeof value === \"object\" &&\n \"enabled\" in value &&\n typeof (value as FarmCronResolvedConfig).enabled === \"boolean\" &&\n \"jobs\" in value &&\n Array.isArray((value as FarmCronResolvedConfig).jobs) &&\n \"secretEnv\" in value\n );\n}\n\nfunction createCronScheduledTasks(jobs: FarmCronJob[]): Record<string, string | string[]> {\n const scheduledTasks: Record<string, string | string[]> = {};\n for (const job of jobs) {\n const taskName = getFarmCronTaskName(job.name);\n for (const schedule of job.schedule) {\n scheduledTasks[schedule] = mergeTaskNames(scheduledTasks[schedule], taskName);\n }\n }\n return scheduledTasks;\n}\n\nfunction mergeTaskNames(\n current: string | string[] | undefined,\n taskName: string,\n): string | string[] {\n if (!current) return taskName;\n const names = Array.isArray(current) ? current : [current];\n return names.includes(taskName) ? names : [...names, taskName];\n}\n\nfunction getFarmCronTaskName(name: string): string {\n return `farm:cron:${name}`;\n}\n\nfunction createNitroCronTaskWrapper(job: FarmCronJob, secretEnv: string): string {\n return `\nimport { defineTask, useNitroApp } from \"nitro/runtime\";\n\nconst name = ${JSON.stringify(job.name)};\nconst path = ${JSON.stringify(job.path)};\nconst secretEnv = ${JSON.stringify(secretEnv)};\n\nfunction readSecret(event) {\n const runtimeEnv = event?.context?.cloudflare?.env || event?.context?.env || {};\n return runtimeEnv[secretEnv] || (typeof process !== \"undefined\" ? process.env?.[secretEnv] : \"\") || \"\";\n}\n\nexport default defineTask({\n meta: {\n name: ${JSON.stringify(getFarmCronTaskName(job.name))},\n description: ${JSON.stringify(job.description || `Farm cron ${job.name}`)}\n },\n async run(event) {\n const headers = new Headers({\n \"x-farm-cron-name\": name,\n \"x-farm-cron-scheduled-at\": String(event?.payload?.scheduledTime || Date.now())\n });\n const secret = readSecret(event);\n if (secret) headers.set(\"authorization\", \"Bearer \" + secret);\n\n const response = await useNitroApp().fetch(path, { method: \"GET\", headers });\n const contentType = response.headers.get(\"content-type\") || \"\";\n const body = response.status === 204\n ? null\n : contentType.includes(\"application/json\")\n ? await response.json().catch(() => null)\n : await response.text();\n\n if (!response.ok) {\n const detail = typeof body === \"string\" ? body : JSON.stringify(body);\n throw new Error(\n \"Farm cron \" + JSON.stringify(name) + \" received \" + response.status +\n \" from \" + path + (detail ? \": \" + detail : \"\")\n );\n }\n\n return { result: body };\n }\n});\n`.trim();\n}\n\nfunction readEnvironmentValue(name: string): string | undefined {\n const runtimeValue = getFarmRuntimeBindings()?.[name];\n if (typeof runtimeValue === \"string\") return runtimeValue;\n return typeof process !== \"undefined\" ? process.env?.[name] : undefined;\n}\n\nfunction getFarmRuntimeBindings(): Record<string, unknown> | undefined {\n const runtimeBindings = (globalThis as typeof globalThis & {\n __env__?: Record<string, unknown>;\n }).__env__;\n return runtimeBindings && typeof runtimeBindings === \"object\" ? runtimeBindings : undefined;\n}\n\nfunction safeFileName(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"cron\";\n}\n","import { createStorage, prefixStorage, builtinDrivers, type BuiltinDriverName } from \"unstorage\";\nimport type { Driver, Storage } from \"unstorage\";\nimport type { Database } from \"db0\";\nimport memoryDriver from \"unstorage/drivers/memory\";\nimport type {\n FarmStorageClient,\n FarmStorageClientConfig,\n FarmStorageConfigObject,\n FarmStorageLocalDriverConfig,\n FarmStorageDatabaseConfig,\n FarmStorageDatabaseDriverMap,\n FarmStorageDatabaseDriverName,\n FarmStorageRuntimeClient,\n FarmStorageMountConfig,\n FarmStorageMounts,\n FarmStorageUserConfig,\n} from \"./types\";\n\nexport type {\n FarmStorageBuiltinDriverConfig,\n FarmStorageClient,\n FarmStorageClientConfig,\n FarmStorageConfigObject,\n FarmStorageCustomDriverConfig,\n FarmStorageDatabaseConfig,\n FarmStorageDatabaseDriverName,\n FarmStorageLocalDriverConfig,\n FarmStorageRuntimeClient,\n FarmStorageMountConfig,\n FarmStorageMounts,\n FarmStorageUserConfig,\n} from \"./types\";\nexport type {\n BuiltinDriverName,\n BuiltinDriverOptions,\n Driver,\n Storage,\n StorageMeta,\n StorageValue,\n TransactionOptions,\n} from \"unstorage\";\nexport type { ConnectorName, ConnectorOptions, Database } from \"db0\";\n\ntype DriverFactoryModule = {\n default: (options?: Record<string, any>) => Driver;\n};\n\ntype DriverResolver = () => Driver | Promise<Driver>;\ntype ModuleLoader = <T = any>(specifier: string) => Promise<T>;\n\nconst loadModule: ModuleLoader = (specifier) => import(/* @vite-ignore */ specifier);\n\nconst DATABASE_CONNECTORS: {\n [K in FarmStorageDatabaseDriverName]: {\n connector: FarmStorageDatabaseDriverMap[K];\n load: () => Promise<{ default: (options?: any) => any }>;\n };\n} = {\n sqlite: {\n connector: \"node-sqlite\",\n load: () => loadModule(\"db0/connectors/node-sqlite\"),\n },\n \"node-sqlite\": {\n connector: \"node-sqlite\",\n load: () => loadModule(\"db0/connectors/node-sqlite\"),\n },\n sqlite3: {\n connector: \"sqlite3\",\n load: () => loadModule(\"db0/connectors/sqlite3\"),\n },\n \"better-sqlite3\": {\n connector: \"better-sqlite3\",\n load: () => loadModule(\"db0/connectors/better-sqlite3\"),\n },\n postgres: {\n connector: \"postgresql\",\n load: () => loadModule(\"db0/connectors/postgresql\"),\n },\n postgresql: {\n connector: \"postgresql\",\n load: () => loadModule(\"db0/connectors/postgresql\"),\n },\n pg: {\n connector: \"postgresql\",\n load: () => loadModule(\"db0/connectors/postgresql\"),\n },\n mysql: {\n connector: \"mysql2\",\n load: () => loadModule(\"db0/connectors/mysql2\"),\n },\n mysql2: {\n connector: \"mysql2\",\n load: () => loadModule(\"db0/connectors/mysql2\"),\n },\n pglite: {\n connector: \"pglite\",\n load: () => loadModule(\"db0/connectors/pglite\"),\n },\n planetscale: {\n connector: \"planetscale\",\n load: () => loadModule(\"db0/connectors/planetscale\"),\n },\n libsql: {\n connector: \"libsql\",\n load: () => loadModule(\"db0/connectors/libsql/node\"),\n },\n \"libsql-node\": {\n connector: \"libsql-node\",\n load: () => loadModule(\"db0/connectors/libsql/node\"),\n },\n \"libsql-http\": {\n connector: \"libsql-http\",\n load: () => loadModule(\"db0/connectors/libsql/http\"),\n },\n};\n\nfunction createMemoryStorage(): Storage {\n return createStorage({\n driver: memoryDriver(),\n });\n}\n\nconst GLOBAL_STORAGE_KEY = Symbol.for(\"farmjs.storage.global\");\n\nfunction readGlobalStorage(): Storage | undefined {\n return (globalThis as unknown as Record<PropertyKey, Storage | undefined>)[GLOBAL_STORAGE_KEY];\n}\n\nfunction writeGlobalStorage(storage: Storage): Storage {\n (globalThis as unknown as Record<PropertyKey, Storage | undefined>)[GLOBAL_STORAGE_KEY] = storage;\n return storage;\n}\n\nfunction getActiveGlobalStorage(): Storage {\n const existing = readGlobalStorage();\n if (existing) {\n return existing;\n }\n return writeGlobalStorage(createMemoryStorage());\n}\n\nlet globalStorage = getActiveGlobalStorage();\n\nfunction normalizeMountKey(base?: string): string {\n return (base || \"\")\n .trim()\n .replace(/^[:/\\\\]+|[:/\\\\]+$/g, \"\")\n .replace(/[\\\\/]+/g, \":\");\n}\n\nfunction isDriverInstance(value: unknown): value is Driver {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as Driver).getItem === \"function\" &&\n typeof (value as Driver).getKeys === \"function\"\n );\n}\n\nfunction isStorageInstance(value: unknown): value is Storage {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as Storage).mount === \"function\" &&\n typeof (value as Storage).getMount === \"function\"\n );\n}\n\nfunction isStorageClient(value: unknown): value is FarmStorageClient {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as FarmStorageClient).kind === \"farm-storage-client\" &&\n typeof (value as FarmStorageClient).resolveDriver === \"function\" &&\n typeof (value as FarmStorageClient).createStorage === \"function\"\n );\n}\n\nfunction isDatabaseDriverName(name: string): name is FarmStorageDatabaseDriverName {\n return name in DATABASE_CONNECTORS;\n}\n\nfunction extractDriverOptions(config: FarmStorageClientConfig): Record<string, any> | undefined {\n const source = config as Record<string, any>;\n const {\n client: _client,\n driver: _driver,\n mounts: _mounts,\n options,\n tableName: _tableName,\n ...inlineOptions\n } = source;\n const hasInlineOptions = Object.keys(inlineOptions).length > 0;\n\n if (options && typeof options === \"object\" && !Array.isArray(options)) {\n return hasInlineOptions ? { ...inlineOptions, ...options } : options;\n }\n\n if (hasInlineOptions) {\n return inlineOptions;\n }\n\n return options;\n}\n\nasync function loadBuiltinDriver(\n name: BuiltinDriverName,\n options?: Record<string, any>,\n): Promise<Driver> {\n const modulePath = builtinDrivers[name];\n\n if (!modulePath) {\n throw new Error(`Unsupported storage driver \"${name}\".`);\n }\n\n const module = (await loadModule(modulePath)) as DriverFactoryModule;\n return module.default(options);\n}\n\nasync function loadDatabaseDriver(config: FarmStorageDatabaseConfig): Promise<Driver> {\n const connectorEntry = DATABASE_CONNECTORS[config.driver as FarmStorageDatabaseDriverName];\n const [{ createDatabase }, connectorModule, db0DriverModule] = await Promise.all([\n loadModule<typeof import(\"db0\")>(\"db0\"),\n connectorEntry.load(),\n loadModule<typeof import(\"unstorage/drivers/db0\")>(\"unstorage/drivers/db0\"),\n ]);\n\n const database = createDatabase(connectorModule.default(extractDriverOptions(config) || {}));\n return db0DriverModule.default({\n database,\n tableName: config.tableName,\n });\n}\n\nasync function resolveDriver(config?: FarmStorageMountConfig): Promise<Driver> {\n if (config && isStorageClient(config)) {\n return config.resolveDriver();\n }\n\n const driverInput = config?.driver ?? \"memory\";\n\n if (typeof driverInput === \"function\") {\n return await driverInput();\n }\n\n if (isDriverInstance(driverInput)) {\n return driverInput;\n }\n\n if (isDatabaseDriverName(driverInput)) {\n return loadDatabaseDriver(config as FarmStorageDatabaseConfig);\n }\n\n if (driverInput === \"local\") {\n return loadBuiltinDriver(\"fs-lite\", extractDriverOptions(config as FarmStorageMountConfig));\n }\n\n return loadBuiltinDriver(\n driverInput as BuiltinDriverName,\n extractDriverOptions(config as FarmStorageClientConfig),\n );\n}\n\nfunction createStorageClientFromResolver(resolveDriver: DriverResolver): FarmStorageClient {\n let driverPromise: Promise<Driver> | undefined;\n let storagePromise: Promise<Storage> | undefined;\n\n const ensureDriver = async () => {\n driverPromise ??= Promise.resolve(resolveDriver());\n return driverPromise;\n };\n\n const ensureStorage = async () => {\n storagePromise ??= ensureDriver().then((driver) =>\n createStorage({\n driver,\n }),\n );\n return storagePromise;\n };\n\n const target = {\n kind: \"farm-storage-client\" as const,\n ready: ensureStorage,\n createStorage: ensureStorage,\n resolveDriver: ensureDriver,\n };\n\n return new Proxy(target as FarmStorageClient, {\n get(currentTarget, prop, receiver) {\n if (prop === \"then\") {\n return undefined;\n }\n\n if (Reflect.has(currentTarget, prop)) {\n return Reflect.get(currentTarget, prop, receiver);\n }\n\n return (...args: any[]) =>\n ensureStorage().then(async (storage) => {\n const member = Reflect.get(storage as object, prop);\n\n if (typeof member !== \"function\") {\n return member;\n }\n\n const result = Reflect.apply(member, storage, args);\n\n if (prop === \"dispose\") {\n return Promise.resolve(result).finally(() => {\n storagePromise = undefined;\n });\n }\n\n return result;\n });\n },\n });\n}\n\nexport function defineStorageClient(resolveDriver: DriverResolver): FarmStorageClient {\n return createStorageClientFromResolver(resolveDriver);\n}\n\nexport function createStorageClient(config: FarmStorageClientConfig): FarmStorageClient {\n return defineStorageClient(() => resolveDriver(config));\n}\n\nexport function driverStorage(\n driver: Driver | (() => Driver | Promise<Driver>),\n): FarmStorageClient {\n return defineStorageClient(() => (typeof driver === \"function\" ? driver() : driver));\n}\n\nexport function databaseStorage(\n database: Database,\n options: { tableName?: string } = {},\n): FarmStorageClient {\n return defineStorageClient(async () => {\n const db0DriverModule =\n await loadModule<typeof import(\"unstorage/drivers/db0\")>(\"unstorage/drivers/db0\");\n return db0DriverModule.default({\n database,\n tableName: options.tableName,\n });\n });\n}\n\nexport function memoryStorage(): FarmStorageClient {\n return createStorageClient({ driver: \"memory\" });\n}\n\nexport function localStorage(options: Omit<FarmStorageLocalDriverConfig, \"driver\"> = {}) {\n return createStorageClient({\n driver: \"local\",\n ...options,\n });\n}\n\nexport function sqliteStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n return createStorageClient({\n driver: \"sqlite\",\n ...options,\n });\n}\n\nexport function mysqlStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n return createStorageClient({\n driver: \"mysql\",\n ...options,\n });\n}\n\nexport function mysql2Storage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n return mysqlStorage(options);\n}\n\nexport function postgresStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n return createStorageClient({\n driver: \"postgres\",\n ...options,\n });\n}\n\nexport function pgStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n return postgresStorage(options);\n}\n\nexport function pgliteStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n return createStorageClient({\n driver: \"pglite\",\n ...options,\n });\n}\n\nexport function planetscaleStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n return createStorageClient({\n driver: \"planetscale\",\n ...options,\n });\n}\n\nexport function libsqlStorage(options: Omit<FarmStorageDatabaseConfig, \"driver\">) {\n return createStorageClient({\n driver: \"libsql\",\n ...options,\n });\n}\n\nexport function redisStorage(\n options: Omit<Extract<FarmStorageClientConfig, { driver: \"redis\" }>, \"driver\">,\n) {\n return createStorageClient({\n driver: \"redis\",\n ...options,\n });\n}\n\nexport function s3Storage(\n options: Omit<Extract<FarmStorageClientConfig, { driver: \"s3\" }>, \"driver\">,\n) {\n return createStorageClient({\n driver: \"s3\",\n ...options,\n });\n}\n\nexport function mongodbStorage(\n options: Omit<Extract<FarmStorageClientConfig, { driver: \"mongodb\" }>, \"driver\">,\n) {\n return createStorageClient({\n driver: \"mongodb\",\n ...options,\n });\n}\n\nexport function upstashStorage(\n options: Omit<Extract<FarmStorageClientConfig, { driver: \"upstash\" }>, \"driver\">,\n) {\n return createStorageClient({\n driver: \"upstash\",\n ...options,\n });\n}\n\nexport function netlifyBlobsStorage(\n options: Omit<Extract<FarmStorageClientConfig, { driver: \"netlify-blobs\" }>, \"driver\">,\n) {\n return createStorageClient({\n driver: \"netlify-blobs\",\n ...options,\n });\n}\n\nexport function vercelKVStorage(\n options: Omit<Extract<FarmStorageClientConfig, { driver: \"vercel-kv\" }>, \"driver\">,\n) {\n return createStorageClient({\n driver: \"vercel-kv\",\n ...options,\n });\n}\n\nexport function vercelBlobStorage(\n options: Omit<Extract<FarmStorageClientConfig, { driver: \"vercel-blob\" }>, \"driver\">,\n) {\n return createStorageClient({\n driver: \"vercel-blob\",\n ...options,\n });\n}\n\nasync function mountNamespaces(storage: Storage, mounts?: FarmStorageMounts): Promise<void> {\n if (!mounts) {\n return;\n }\n\n for (const [base, config] of Object.entries(mounts)) {\n storage.mount(normalizeMountKey(base), await resolveDriver(config));\n }\n}\n\nexport async function createFarmStorage(config: FarmStorageUserConfig = {}): Promise<Storage> {\n if (isStorageInstance(config)) {\n return config;\n }\n\n if (isStorageClient(config)) {\n return config.createStorage();\n }\n\n const rootConfig = isStorageClient(config.client) ? config.client : config;\n const storage = createStorage({\n driver: await resolveDriver(rootConfig),\n });\n\n await mountNamespaces(storage, config.mounts);\n return storage;\n}\n\nexport async function resolveStorageRuntimeClient(\n config: FarmStorageUserConfig | undefined,\n): Promise<unknown | undefined> {\n if (!config || isStorageInstance(config) || isStorageClient(config)) {\n return undefined;\n }\n\n const client = config.client;\n if (!client || isStorageInstance(client) || isStorageClient(client)) {\n return undefined;\n }\n\n return typeof client === \"function\" ? await client() : client;\n}\n\nexport async function initStorage(config: FarmStorageUserConfig = {}): Promise<Storage> {\n globalStorage = getActiveGlobalStorage();\n const nextStorage = await createFarmStorage(config);\n const previousStorage = globalStorage;\n globalStorage = writeGlobalStorage(nextStorage);\n\n if (previousStorage !== nextStorage) {\n await previousStorage.dispose().catch(() => {});\n }\n\n return globalStorage;\n}\n\nexport function getStorage(namespace?: string): Storage {\n globalStorage = getActiveGlobalStorage();\n const base = normalizeMountKey(namespace);\n if (!base) {\n return globalStorage;\n }\n\n const namespaced = prefixStorage(globalStorage, base);\n return {\n ...namespaced,\n async clear() {\n const keys = await namespaced.getKeys();\n await Promise.all(keys.map((key) => namespaced.removeItem(key)));\n },\n } as Storage;\n}\n\nexport async function disposeStorage(): Promise<void> {\n globalStorage = getActiveGlobalStorage();\n const previousStorage = globalStorage;\n globalStorage = writeGlobalStorage(createMemoryStorage());\n await previousStorage.dispose().catch(() => {});\n}\n","export type FarmRouteRuntime = \"auto\" | \"node\" | \"edge\";\nexport type FarmRouteRegions = \"auto\" | readonly string[];\nexport type FarmRouteMaxDuration = \"auto\" | number;\n\n/** Portable execution controls shared by file, programmatic, and config routes. */\nexport interface FarmRouteRuntimeConfig {\n runtime?: FarmRouteRuntime;\n regions?: FarmRouteRegions;\n maxDuration?: FarmRouteMaxDuration;\n}\n\nexport interface ResolvedFarmRouteRuntimeConfig {\n runtime: FarmRouteRuntime;\n regions?: string[];\n maxDuration?: number;\n}\n\nexport type FarmRouteRuntimeEntryKind = \"page\" | \"api\" | \"rule\";\nexport type FarmRouteRenderingMode = \"static\" | \"dynamic\";\n\nexport interface FarmRouteRuntimeManifestEntry extends ResolvedFarmRouteRuntimeConfig {\n kind: FarmRouteRuntimeEntryKind;\n pattern: string;\n rendering: FarmRouteRenderingMode;\n source?: string;\n}\n\nexport interface FarmRouteRuntimeManifest {\n version: 1;\n routes: FarmRouteRuntimeManifestEntry[];\n}\n\nexport function normalizeFarmRouteRuntimeConfig(\n value: FarmRouteRuntimeConfig | null | undefined,\n source = \"Route configuration\",\n): FarmRouteRuntimeConfig {\n if (!value) return {};\n\n const normalized: FarmRouteRuntimeConfig = {};\n\n if (value.runtime !== undefined) {\n if (value.runtime !== \"auto\" && value.runtime !== \"node\" && value.runtime !== \"edge\") {\n throw new TypeError(`${source} runtime must be \"auto\", \"node\", or \"edge\"`);\n }\n normalized.runtime = value.runtime;\n }\n\n if (value.regions !== undefined) {\n if (value.regions === \"auto\") {\n normalized.regions = \"auto\";\n } else {\n if (!Array.isArray(value.regions) || value.regions.length === 0) {\n throw new TypeError(`${source} regions must be \"auto\" or a non-empty string array`);\n }\n\n const regions = Array.from(\n new Set(\n value.regions.map((region) => {\n if (\n typeof region !== \"string\" ||\n !region.trim() ||\n /[\\u0000-\\u001f\\u007f]/.test(region)\n ) {\n throw new TypeError(`${source} regions must contain non-empty region identifiers`);\n }\n return region.trim();\n }),\n ),\n );\n\n normalized.regions = regions;\n }\n }\n\n if (value.maxDuration !== undefined) {\n if (value.maxDuration === \"auto\") {\n normalized.maxDuration = \"auto\";\n } else if (\n typeof value.maxDuration !== \"number\" ||\n !Number.isInteger(value.maxDuration) ||\n value.maxDuration <= 0\n ) {\n throw new TypeError(`${source} maxDuration must be \"auto\" or a positive integer in seconds`);\n } else {\n normalized.maxDuration = value.maxDuration;\n }\n }\n\n return normalized;\n}\n\n/** Merge from lowest to highest precedence. Explicit \"auto\" values reset inherited hints. */\nexport function mergeFarmRouteRuntimeConfigs(\n ...configs: Array<FarmRouteRuntimeConfig | null | undefined>\n): FarmRouteRuntimeConfig {\n const merged: FarmRouteRuntimeConfig = {};\n\n for (const config of configs) {\n if (!config) continue;\n if (config.runtime !== undefined) merged.runtime = config.runtime;\n if (config.regions !== undefined) merged.regions = config.regions;\n if (config.maxDuration !== undefined) merged.maxDuration = config.maxDuration;\n }\n\n return merged;\n}\n\nexport function resolveFarmRouteRuntimeConfig(\n config: FarmRouteRuntimeConfig | null | undefined,\n source?: string,\n): ResolvedFarmRouteRuntimeConfig {\n const normalized = normalizeFarmRouteRuntimeConfig(config, source);\n\n return {\n runtime: normalized.runtime ?? \"auto\",\n ...(normalized.regions && normalized.regions !== \"auto\"\n ? { regions: [...normalized.regions] }\n : {}),\n ...(typeof normalized.maxDuration === \"number\" ? { maxDuration: normalized.maxDuration } : {}),\n };\n}\n\nexport function hasFarmRouteRuntimeControls(\n config: FarmRouteRuntimeConfig | null | undefined,\n): boolean {\n return Boolean(\n config &&\n (config.runtime !== undefined ||\n config.regions !== undefined ||\n config.maxDuration !== undefined),\n );\n}\n\nexport function getFarmRouteRuntimeConfig(value: unknown): FarmRouteRuntimeConfig {\n if (!value || typeof value !== \"object\") return {};\n const route = value as FarmRouteRuntimeConfig;\n return {\n ...(route.runtime !== undefined ? { runtime: route.runtime } : {}),\n ...(route.regions !== undefined ? { regions: route.regions } : {}),\n ...(route.maxDuration !== undefined ? { maxDuration: route.maxDuration } : {}),\n };\n}\n\nexport function createFarmRouteRuntimeKey(config: ResolvedFarmRouteRuntimeConfig): string {\n return JSON.stringify({\n runtime: config.runtime,\n regions: config.regions || null,\n maxDuration: config.maxDuration || null,\n });\n}\n\n/** Resolve matching route rules from broadest to most specific. */\nexport function resolveFarmRouteRuleRuntimeConfig(\n pathname: string,\n routeRules: Record<string, FarmRouteRuntimeConfig> | null | undefined,\n): FarmRouteRuntimeConfig {\n if (!routeRules) return {};\n\n const matches = Object.entries(routeRules)\n .filter(\n ([pattern, rule]) =>\n hasFarmRouteRuntimeControls(rule) && farmRouteRuleMatches(pattern, pathname),\n )\n .sort(([left], [right]) => compareFarmRouteRuleSpecificity(left, right));\n\n return mergeFarmRouteRuntimeConfigs(...matches.map(([, rule]) => rule));\n}\n\nexport function farmRouteRuleMatches(pattern: string, pathname: string): boolean {\n const normalizedPattern = normalizeRoutePattern(pattern);\n const normalizedPathname = normalizeRoutePattern(pathname);\n if (normalizedPattern === normalizedPathname) return true;\n\n const expression = normalizedPattern\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => {\n if (segment === \"**\") return \".*\";\n if (segment === \"*\") return \"[^/]+\";\n if (/^\\[\\[\\.\\.\\..+\\]\\]$/.test(segment)) return \".*\";\n if (/^\\[\\.\\.\\..+\\]$/.test(segment)) return \".+\";\n if (/^\\[.+\\]$/.test(segment) || /^:.+$/.test(segment)) return \"[^/]+\";\n return escapeRegExp(segment);\n })\n .join(\"/\");\n\n return new RegExp(`^/${expression}/?$`).test(normalizedPathname);\n}\n\nfunction compareFarmRouteRuleSpecificity(left: string, right: string): number {\n const leftScore = getFarmRouteRuleSpecificity(left);\n const rightScore = getFarmRouteRuleSpecificity(right);\n return leftScore - rightScore || left.localeCompare(right);\n}\n\nfunction getFarmRouteRuleSpecificity(pattern: string): number {\n return normalizeRoutePattern(pattern)\n .split(\"/\")\n .filter(Boolean)\n .reduce((score, segment) => {\n if (segment === \"**\" || /^\\[\\[\\.\\.\\./.test(segment)) return score + 1;\n if (segment === \"*\" || /^\\[\\.\\.\\./.test(segment)) return score + 10;\n if (/^\\[.+\\]$/.test(segment) || /^:.+$/.test(segment)) return score + 50;\n return score + 100;\n }, 0);\n}\n\nfunction normalizeRoutePattern(value: string): string {\n const withSlash = value.trim().startsWith(\"/\") ? value.trim() : `/${value.trim()}`;\n return withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import type { HeaderConfig, RedirectConfig } from \"./config\";\nimport type { FarmRouteRuntimeConfig } from \"./route-runtime\";\nimport { normalizeFarmRouteRuntimeConfig } from \"./route-runtime\";\n\nexport type FarmRouteRuleRenderMode = \"static\" | \"dynamic\";\n\nexport type FarmRouteRuleRedirect =\n | string\n | {\n to: string;\n statusCode?: number;\n permanent?: boolean;\n };\n\nexport type FarmRouteRuleCors =\n | boolean\n | {\n origin?: string;\n methods?: string | readonly string[];\n headers?: string | readonly string[];\n };\n\nexport interface FarmRouteRule extends FarmRouteRuntimeConfig {\n prerender?: boolean;\n render?: FarmRouteRuleRenderMode;\n ssr?: boolean;\n swr?: boolean | number;\n isr?: boolean | number;\n cors?: FarmRouteRuleCors;\n headers?: Record<string, string>;\n redirect?: FarmRouteRuleRedirect;\n}\n\nexport type FarmRouteRules = Record<string, FarmRouteRule>;\n\nexport function normalizeRouteRules(routeRules: FarmRouteRules | undefined): FarmRouteRules {\n if (!routeRules) return {};\n\n const normalized: FarmRouteRules = {};\n for (const [source, rule] of Object.entries(routeRules)) {\n if (!source || !rule) continue;\n const normalizedSource = normalizeRuleSource(source);\n normalized[normalizedSource] = {\n ...rule,\n ...normalizeFarmRouteRuntimeConfig(rule, `Route rule \"${normalizedSource}\"`),\n };\n }\n return normalized;\n}\n\nexport function routeRulesToRedirects(routeRules: FarmRouteRules): RedirectConfig[] {\n return Object.entries(routeRules)\n .filter((entry): entry is [string, FarmRouteRule & { redirect: FarmRouteRuleRedirect }] =>\n Boolean(entry[1].redirect),\n )\n .map(([source, rule]) => {\n const redirect = typeof rule.redirect === \"string\" ? { to: rule.redirect } : rule.redirect;\n return {\n source,\n destination: redirect.to,\n permanent: redirect.permanent,\n statusCode: redirect.statusCode ?? (redirect.permanent === true ? 308 : undefined),\n };\n });\n}\n\nexport function routeRulesToHeaders(routeRules: FarmRouteRules): HeaderConfig[] {\n const configs: HeaderConfig[] = [];\n\n for (const [source, rule] of Object.entries(routeRules)) {\n const headers = {\n ...normalizeCorsHeaders(rule.cors),\n ...(rule.headers || {}),\n };\n\n const entries = Object.entries(headers);\n if (entries.length === 0) continue;\n\n configs.push({\n source,\n headers: entries.map(([key, value]) => ({ key, value })),\n });\n }\n\n return configs;\n}\n\nexport function routeRulesToNitroRouteRules(routeRules: FarmRouteRules): Record<string, any> {\n const nitroRules: Record<string, any> = {};\n\n for (const [source, rule] of Object.entries(routeRules)) {\n const nitroRule: Record<string, any> = { ...rule };\n\n if (rule.render === \"static\") {\n nitroRule.prerender = true;\n } else if (rule.render === \"dynamic\") {\n nitroRule.prerender = false;\n }\n\n if (rule.redirect && typeof rule.redirect !== \"string\") {\n nitroRule.redirect = rule.redirect.to;\n if (rule.redirect.statusCode) {\n nitroRule.statusCode = rule.redirect.statusCode;\n }\n }\n\n if (rule.cors) {\n nitroRule.cors = true;\n nitroRule.headers = {\n ...normalizeCorsHeaders(rule.cors),\n ...(rule.headers || {}),\n };\n }\n\n delete nitroRule.render;\n delete nitroRule.runtime;\n delete nitroRule.regions;\n delete nitroRule.maxDuration;\n nitroRules[source] = nitroRule;\n }\n\n return nitroRules;\n}\n\nfunction normalizeCorsHeaders(cors: FarmRouteRuleCors | undefined): Record<string, string> {\n if (!cors) return {};\n\n if (cors === true) {\n return {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"*\",\n \"Access-Control-Allow-Headers\": \"*\",\n };\n }\n\n return {\n \"Access-Control-Allow-Origin\": cors.origin ?? \"*\",\n \"Access-Control-Allow-Methods\": normalizeList(cors.methods) ?? \"*\",\n \"Access-Control-Allow-Headers\": normalizeList(cors.headers) ?? \"*\",\n };\n}\n\nfunction normalizeList(value: string | readonly string[] | undefined): string | undefined {\n if (!value || typeof value === \"string\") return value;\n return value.join(\", \");\n}\n\nfunction normalizeRuleSource(source: string): string {\n const trimmed = source.trim();\n if (!trimmed) return \"/\";\n return trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n}\n","export type FarmCacheInvalidationListener = (key: string) => void;\n\ntype FarmCacheInvalidationState = {\n listeners: Set<FarmCacheInvalidationListener>;\n};\n\nconst FARM_CACHE_INVALIDATION_STATE = Symbol.for(\"farm.cacheInvalidationState\");\nconst globalState = globalThis as typeof globalThis & {\n [FARM_CACHE_INVALIDATION_STATE]?: FarmCacheInvalidationState;\n};\n\nfunction getFarmCacheInvalidationState(): FarmCacheInvalidationState {\n return (globalState[FARM_CACHE_INVALIDATION_STATE] ??= {\n listeners: new Set(),\n });\n}\n\nexport function notifyFarmCacheInvalidation(key: string): void {\n if (typeof key !== \"string\" || key.length === 0) return;\n\n for (const listener of getFarmCacheInvalidationState().listeners) {\n listener(key);\n }\n}\n\nexport function applyFarmCacheInvalidations(keys: unknown): void {\n if (!Array.isArray(keys)) return;\n\n for (const key of keys) {\n if (typeof key === \"string\") {\n notifyFarmCacheInvalidation(key);\n }\n }\n}\n\nexport function subscribeFarmCacheInvalidation(\n listener: FarmCacheInvalidationListener,\n): () => void {\n const state = getFarmCacheInvalidationState();\n state.listeners.add(listener);\n return () => state.listeners.delete(listener);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { subscribeFarmCacheInvalidation } from \"./cache-invalidation\";\n\nexport const DEFAULT_SERVER_ACTION_BODY_SIZE_LIMIT = 1_000_000;\n\nexport interface FarmServerActionsConfig {\n /** Additional trusted origins or host patterns, such as https://app.example.com. */\n allowedOrigins?: readonly string[];\n /** Maximum encoded request body size in bytes or as a size string such as \"1mb\". */\n bodySizeLimit?: number | string;\n}\n\nexport interface ResolvedFarmServerActionsConfig {\n allowedOrigins: readonly string[];\n bodySizeLimit: number;\n}\n\nexport type ServerActionRequestKind = \"javascript\" | \"form\";\n\nexport interface PreparedServerActionRequest {\n body: string | FormData;\n contentType: string;\n}\n\nexport type SanitizedServerActionError = {\n name: \"ServerActionError\";\n message: \"Server function failed\";\n};\n\ntype ServerActionRequestErrorCode =\n | \"BODY_TOO_LARGE\"\n | \"INVALID_ACTION_ID\"\n | \"INVALID_BODY\"\n | \"INVALID_CONTENT_LENGTH\"\n | \"INVALID_METHOD\"\n | \"INVALID_ORIGIN\"\n | \"MISSING_ORIGIN\"\n | \"UNSUPPORTED_CONTENT_TYPE\";\n\nexport class ServerActionRequestError extends Error {\n readonly code: ServerActionRequestErrorCode;\n readonly status: number;\n\n constructor(code: ServerActionRequestErrorCode, status: number, message: string) {\n super(message);\n this.name = \"ServerActionRequestError\";\n this.code = code;\n this.status = status;\n }\n}\n\ntype ServerActionExecutionContext = {\n request: Request;\n signal: AbortSignal;\n invalidations: Set<string>;\n};\n\nconst SERVER_ACTION_STORAGE_KEY = Symbol.for(\"farm.serverActionStorage\");\nconst FALLBACK_ABORT_CONTROLLER_KEY = Symbol.for(\"farm.serverActionFallbackAbortController\");\nconst FORM_ACTION_CONTENT_TYPES = new Set([\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\",\n]);\nconst JAVASCRIPT_ACTION_CONTENT_TYPES = new Set([\n \"application/octet-stream\",\n \"application/x-www-form-urlencoded\",\n \"multipart/form-data\",\n \"text/plain\",\n]);\n\ntype GlobalWithServerActionStorage = typeof globalThis & {\n [SERVER_ACTION_STORAGE_KEY]?: AsyncLocalStorage<ServerActionExecutionContext>;\n [FALLBACK_ABORT_CONTROLLER_KEY]?: AbortController;\n};\n\nexport function resolveServerActionsConfig(\n config: FarmServerActionsConfig | undefined,\n): ResolvedFarmServerActionsConfig {\n const allowedOrigins = (config?.allowedOrigins ?? []).map(normalizeAllowedOriginPattern);\n const bodySizeLimit = parseBodySizeLimit(\n config?.bodySizeLimit ?? DEFAULT_SERVER_ACTION_BODY_SIZE_LIMIT,\n );\n\n return Object.freeze({\n allowedOrigins: Object.freeze(allowedOrigins),\n bodySizeLimit,\n });\n}\n\nexport function validateServerActionRequest(\n request: Request,\n config: ResolvedFarmServerActionsConfig,\n): void {\n if (request.method.toUpperCase() !== \"POST\") {\n throw new ServerActionRequestError(\n \"INVALID_METHOD\",\n 405,\n \"Server actions only accept POST requests\",\n );\n }\n\n const requestUrl = new URL(request.url);\n const sourceOrigin = getRequestSourceOrigin(request);\n const fetchSite = request.headers.get(\"sec-fetch-site\")?.trim().toLowerCase();\n\n if (!sourceOrigin) {\n if (fetchSite !== \"same-origin\") {\n throw new ServerActionRequestError(\n \"MISSING_ORIGIN\",\n 403,\n \"Server action request is missing same-origin metadata\",\n );\n }\n return;\n }\n\n const matchesRequest =\n sourceOrigin === requestUrl.origin || matchesHostHeader(sourceOrigin, request);\n const matchesConfiguredOrigin = config.allowedOrigins.some((pattern) =>\n matchesAllowedOrigin(sourceOrigin, pattern),\n );\n\n if (!matchesRequest && !matchesConfiguredOrigin) {\n throw new ServerActionRequestError(\n \"INVALID_ORIGIN\",\n 403,\n \"Server action origin does not match the request origin\",\n );\n }\n\n if (fetchSite === \"cross-site\" && !matchesConfiguredOrigin) {\n throw new ServerActionRequestError(\n \"INVALID_ORIGIN\",\n 403,\n \"Cross-site server action request was rejected\",\n );\n }\n}\n\nexport async function prepareServerActionRequest(\n request: Request,\n config: ResolvedFarmServerActionsConfig,\n kind: ServerActionRequestKind,\n actionId?: string | null,\n): Promise<PreparedServerActionRequest> {\n validateServerActionRequest(request, config);\n\n if (kind === \"javascript\") {\n validateActionId(actionId);\n }\n\n const contentType = getSupportedContentType(request, kind);\n const bytes = await readBodyWithLimit(request, config.bodySizeLimit);\n\n if (kind === \"form\" || contentType === \"multipart/form-data\") {\n return {\n body: await parseFormData(request, bytes),\n contentType,\n };\n }\n\n return {\n body: new TextDecoder().decode(bytes),\n contentType,\n };\n}\n\nexport function createServerActionRequestErrorResponse(error: unknown): Response | null {\n if (!(error instanceof ServerActionRequestError)) {\n return null;\n }\n\n const headers = new Headers({\n \"cache-control\": \"no-store\",\n \"content-type\": \"text/plain; charset=utf-8\",\n \"x-content-type-options\": \"nosniff\",\n });\n if (error.status === 405) {\n headers.set(\"allow\", \"POST\");\n }\n\n return new Response(getPublicErrorMessage(error.status), {\n status: error.status,\n headers,\n });\n}\n\nexport function sanitizeServerActionError(_error: unknown): SanitizedServerActionError {\n return {\n name: \"ServerActionError\",\n message: \"Server function failed\",\n };\n}\n\nexport function runWithServerActionRequest<T>(\n request: Request,\n callback: () => T | Promise<T>,\n): T | Promise<T> {\n throwIfAborted(request.signal);\n return getServerActionStorage().run(\n {\n request,\n signal: request.signal,\n invalidations: new Set(),\n },\n callback,\n );\n}\n\nexport function getServerActionExecutionContext(): ServerActionExecutionContext | undefined {\n return getServerActionStorage().getStore();\n}\n\nexport function getServerActionSignal(): AbortSignal {\n return getServerActionExecutionContext()?.signal ?? getFallbackAbortController().signal;\n}\n\nexport function getServerActionInvalidations(): readonly string[] {\n return Array.from(getServerActionExecutionContext()?.invalidations ?? []);\n}\n\nsubscribeFarmCacheInvalidation((key) => {\n getServerActionExecutionContext()?.invalidations.add(key);\n});\n\nfunction getServerActionStorage(): AsyncLocalStorage<ServerActionExecutionContext> {\n const globalState = globalThis as GlobalWithServerActionStorage;\n if (!globalState[SERVER_ACTION_STORAGE_KEY]) {\n globalState[SERVER_ACTION_STORAGE_KEY] = new AsyncLocalStorage<ServerActionExecutionContext>();\n }\n return globalState[SERVER_ACTION_STORAGE_KEY]!;\n}\n\nfunction getFallbackAbortController(): AbortController {\n const globalState = globalThis as GlobalWithServerActionStorage;\n if (!globalState[FALLBACK_ABORT_CONTROLLER_KEY]) {\n globalState[FALLBACK_ABORT_CONTROLLER_KEY] = new AbortController();\n }\n return globalState[FALLBACK_ABORT_CONTROLLER_KEY]!;\n}\n\nfunction parseBodySizeLimit(value: number | string): number {\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(\"serverActions.bodySizeLimit must be a positive safe integer\");\n }\n return value;\n }\n\n const match = value\n .trim()\n .toLowerCase()\n .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)?$/);\n if (!match) {\n throw new TypeError(\n 'serverActions.bodySizeLimit must be bytes or a size string such as \"500kb\" or \"1mb\"',\n );\n }\n\n const amount = Number(match[1]);\n const unit = match[2] ?? \"b\";\n const multiplier: Record<string, number> = {\n b: 1,\n kb: 1_000,\n mb: 1_000_000,\n gb: 1_000_000_000,\n kib: 1_024,\n mib: 1_048_576,\n gib: 1_073_741_824,\n };\n const bytes = Math.floor(amount * multiplier[unit]);\n\n if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n throw new TypeError(\"serverActions.bodySizeLimit must resolve to a positive safe integer\");\n }\n\n return bytes;\n}\n\nfunction normalizeAllowedOriginPattern(value: string): string {\n const pattern = value.trim().toLowerCase();\n if (!pattern) {\n throw new TypeError(\"serverActions.allowedOrigins cannot contain empty values\");\n }\n\n if (pattern.includes(\"*\")) {\n if (!/^(?:https?:\\/\\/)?\\*\\.[a-z0-9.-]+(?::\\d+)?$/.test(pattern)) {\n throw new TypeError(`Invalid serverActions.allowedOrigins pattern: ${JSON.stringify(value)}`);\n }\n return pattern;\n }\n\n if (pattern.includes(\"://\")) {\n let parsed: URL;\n try {\n parsed = new URL(pattern);\n } catch {\n throw new TypeError(`Invalid serverActions.allowedOrigins value: ${JSON.stringify(value)}`);\n }\n\n if (\n (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n parsed.username ||\n parsed.password ||\n parsed.pathname !== \"/\" ||\n parsed.search ||\n parsed.hash\n ) {\n throw new TypeError(\n `serverActions.allowedOrigins must contain origins without paths: ${JSON.stringify(value)}`,\n );\n }\n return parsed.origin;\n }\n\n if (/[/@?#]/.test(pattern)) {\n throw new TypeError(\n `serverActions.allowedOrigins must contain origins or hosts: ${JSON.stringify(value)}`,\n );\n }\n\n try {\n return new URL(`http://${pattern}`).host;\n } catch {\n throw new TypeError(`Invalid serverActions.allowedOrigins value: ${JSON.stringify(value)}`);\n }\n}\n\nfunction getRequestSourceOrigin(request: Request): string | null {\n const origin = request.headers.get(\"origin\")?.trim();\n if (origin) {\n return parseSourceOrigin(origin);\n }\n\n const referer = request.headers.get(\"referer\")?.trim();\n if (referer) {\n return parseSourceOrigin(referer);\n }\n\n return null;\n}\n\nfunction parseSourceOrigin(value: string): string {\n if (value === \"null\") {\n throw new ServerActionRequestError(\"INVALID_ORIGIN\", 403, \"Opaque origins are not allowed\");\n }\n\n try {\n const parsed = new URL(value);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new Error(\"Unsupported protocol\");\n }\n return parsed.origin;\n } catch {\n throw new ServerActionRequestError(\"INVALID_ORIGIN\", 403, \"Invalid request origin\");\n }\n}\n\nfunction matchesHostHeader(sourceOrigin: string, request: Request): boolean {\n const host = request.headers.get(\"host\")?.trim().toLowerCase();\n if (!host) return false;\n\n try {\n const source = new URL(sourceOrigin);\n const target = new URL(request.url);\n return source.protocol === target.protocol && source.host.toLowerCase() === host;\n } catch {\n return false;\n }\n}\n\nfunction matchesAllowedOrigin(sourceOrigin: string, pattern: string): boolean {\n const source = new URL(sourceOrigin);\n if (!pattern.includes(\"*\")) {\n return pattern.includes(\"://\") ? source.origin === pattern : source.host === pattern;\n }\n\n const schemeEnd = pattern.indexOf(\"://\");\n const scheme = schemeEnd === -1 ? null : pattern.slice(0, schemeEnd + 1);\n const hostPattern = pattern.slice(schemeEnd === -1 ? 0 : schemeEnd + 3);\n const [wildcardHost, port] = splitHostAndPort(hostPattern);\n const baseHost = wildcardHost.slice(2);\n\n if (scheme && source.protocol !== scheme) return false;\n if (port && getEffectivePort(source) !== port) return false;\n if (!port && source.port) return false;\n\n return source.hostname.endsWith(`.${baseHost}`) && source.hostname !== baseHost;\n}\n\nfunction splitHostAndPort(value: string): [string, string | null] {\n const separator = value.lastIndexOf(\":\");\n if (separator === -1) return [value, null];\n return [value.slice(0, separator), value.slice(separator + 1)];\n}\n\nfunction getEffectivePort(url: URL): string {\n if (url.port) return url.port;\n if (url.protocol === \"https:\") return \"443\";\n if (url.protocol === \"http:\") return \"80\";\n return \"\";\n}\n\nfunction validateActionId(actionId?: string | null): asserts actionId is string {\n if (!actionId || actionId.length > 4096 || hasControlCharacters(actionId)) {\n throw new ServerActionRequestError(\"INVALID_ACTION_ID\", 400, \"Invalid server action id\");\n }\n}\n\nfunction hasControlCharacters(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index);\n if (code <= 31 || code === 127) return true;\n }\n return false;\n}\n\nfunction getSupportedContentType(request: Request, kind: ServerActionRequestKind): string {\n const header = request.headers.get(\"content-type\")?.trim().toLowerCase();\n const contentType = header?.split(\";\", 1)[0]?.trim() ?? \"\";\n const supported = kind === \"form\" ? FORM_ACTION_CONTENT_TYPES : JAVASCRIPT_ACTION_CONTENT_TYPES;\n\n if (!supported.has(contentType)) {\n throw new ServerActionRequestError(\n \"UNSUPPORTED_CONTENT_TYPE\",\n 415,\n \"Unsupported server action content type\",\n );\n }\n\n return contentType;\n}\n\nasync function readBodyWithLimit(request: Request, limit: number): Promise<Uint8Array> {\n const contentLength = request.headers.get(\"content-length\")?.trim();\n if (contentLength) {\n if (!/^\\d+$/.test(contentLength)) {\n throw new ServerActionRequestError(\n \"INVALID_CONTENT_LENGTH\",\n 400,\n \"Invalid content-length header\",\n );\n }\n if (Number(contentLength) > limit) {\n throw new ServerActionRequestError(\"BODY_TOO_LARGE\", 413, \"Server action body is too large\");\n }\n }\n\n throwIfAborted(request.signal);\n if (!request.body) return new Uint8Array();\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n const cancelBodyRead = () => {\n void reader.cancel(request.signal.reason).catch(() => {});\n };\n\n request.signal.addEventListener(\"abort\", cancelBodyRead, { once: true });\n\n try {\n while (true) {\n throwIfAborted(request.signal);\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n\n total += value.byteLength;\n if (total > limit) {\n await reader.cancel(\"Server action body is too large\");\n throw new ServerActionRequestError(\n \"BODY_TOO_LARGE\",\n 413,\n \"Server action body is too large\",\n );\n }\n chunks.push(value);\n }\n } catch (error) {\n if (request.signal.aborted) throwIfAborted(request.signal);\n throw error;\n } finally {\n request.signal.removeEventListener(\"abort\", cancelBodyRead);\n reader.releaseLock();\n }\n\n throwIfAborted(request.signal);\n const body = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n body.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return body;\n}\n\nasync function parseFormData(request: Request, bytes: Uint8Array): Promise<FormData> {\n const body = new ArrayBuffer(bytes.byteLength);\n new Uint8Array(body).set(bytes);\n const copy = new Request(request.url, {\n method: \"POST\",\n headers: request.headers,\n body,\n });\n\n try {\n return await copy.formData();\n } catch {\n throw new ServerActionRequestError(\"INVALID_BODY\", 400, \"Invalid server action form body\");\n }\n}\n\nfunction getPublicErrorMessage(status: number): string {\n switch (status) {\n case 400:\n return \"Bad Request\";\n case 403:\n return \"Forbidden\";\n case 405:\n return \"Method Not Allowed\";\n case 413:\n return \"Payload Too Large\";\n case 415:\n return \"Unsupported Media Type\";\n default:\n return \"Server Action Request Failed\";\n }\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (!signal.aborted) return;\n if (signal.reason !== undefined) throw signal.reason;\n throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","export const DEFAULT_FARM_IMAGE_PATH = \"/_farm/image\";\nexport const DEFAULT_FARM_IMAGE_DEVICE_SIZES = [\n 640, 750, 828, 1080, 1200, 1920, 2048, 3840,\n] as const;\nexport const DEFAULT_FARM_IMAGE_SIZES = [16, 32, 48, 64, 96, 128, 256, 384] as const;\nexport const DEFAULT_FARM_IMAGE_QUALITIES = [75] as const;\nexport const DEFAULT_FARM_IMAGE_FORMATS = [\"image/webp\"] as const;\n\nexport type FarmImageFormat = \"image/avif\" | \"image/webp\";\nexport type FarmImageProvider = \"auto\" | \"node\" | \"cloudflare\" | \"none\";\n\nexport interface FarmImageRemotePattern {\n protocol?: \"http\" | \"https\";\n hostname: string;\n port?: string;\n pathname?: string;\n search?: string;\n}\n\nexport interface FarmImageLocalPattern {\n pathname: string;\n search?: string;\n}\n\nexport interface FarmImageConfig {\n /** Runtime optimizer. Auto selects Cloudflare Images on Cloudflare and Sharp elsewhere. */\n provider?: FarmImageProvider;\n /** Public optimizer endpoint. */\n path?: string;\n /** @deprecated Prefer remotePatterns, which also restricts protocol, path, port, and query. */\n domains?: readonly string[];\n remotePatterns?: readonly FarmImageRemotePattern[];\n localPatterns?: readonly FarmImageLocalPattern[];\n deviceSizes?: readonly number[];\n imageSizes?: readonly number[];\n qualities?: readonly number[];\n formats?: readonly FarmImageFormat[];\n minimumCacheTTL?: number;\n maximumResponseBody?: number | string;\n maximumRedirects?: number;\n dangerouslyAllowSVG?: boolean;\n dangerouslyAllowLocalIP?: boolean;\n}\n\nexport interface ResolvedFarmImageConfig {\n provider: FarmImageProvider;\n path: string;\n domains: readonly string[];\n remotePatterns: readonly FarmImageRemotePattern[];\n localPatterns: readonly FarmImageLocalPattern[];\n deviceSizes: readonly number[];\n imageSizes: readonly number[];\n qualities: readonly number[];\n formats: readonly FarmImageFormat[];\n minimumCacheTTL: number;\n maximumResponseBody: number;\n maximumRedirects: number;\n dangerouslyAllowSVG: boolean;\n dangerouslyAllowLocalIP: boolean;\n}\n\nexport type PublicFarmImageConfig = Pick<\n ResolvedFarmImageConfig,\n \"provider\" | \"path\" | \"deviceSizes\" | \"imageSizes\" | \"qualities\" | \"formats\"\n>;\n\nconst SIZE_UNITS: Record<string, number> = {\n b: 1,\n kb: 1_000,\n mb: 1_000_000,\n gb: 1_000_000_000,\n kib: 1_024,\n mib: 1_048_576,\n gib: 1_073_741_824,\n};\n\nexport function resolveFarmImageConfig(\n config: FarmImageConfig | undefined,\n): ResolvedFarmImageConfig {\n const path = normalizeImagePath(config?.path ?? DEFAULT_FARM_IMAGE_PATH);\n const deviceSizes = normalizeIntegerList(\n config?.deviceSizes ?? DEFAULT_FARM_IMAGE_DEVICE_SIZES,\n \"images.deviceSizes\",\n );\n const imageSizes = normalizeIntegerList(\n config?.imageSizes ?? DEFAULT_FARM_IMAGE_SIZES,\n \"images.imageSizes\",\n );\n const qualities = normalizeIntegerList(\n config?.qualities ?? DEFAULT_FARM_IMAGE_QUALITIES,\n \"images.qualities\",\n 100,\n );\n const formats = [...new Set(config?.formats ?? DEFAULT_FARM_IMAGE_FORMATS)];\n\n if (formats.some((format) => format !== \"image/avif\" && format !== \"image/webp\")) {\n throw new TypeError('images.formats only supports \"image/avif\" and \"image/webp\"');\n }\n\n const minimumCacheTTL = normalizeNonNegativeInteger(\n config?.minimumCacheTTL ?? 60,\n \"images.minimumCacheTTL\",\n );\n const maximumRedirects = normalizeNonNegativeInteger(\n config?.maximumRedirects ?? 3,\n \"images.maximumRedirects\",\n );\n\n return Object.freeze({\n provider: config?.provider ?? \"auto\",\n path,\n domains: Object.freeze([\n ...new Set(\n (config?.domains ?? []).map((domain) => domain.trim().toLowerCase()).filter(Boolean),\n ),\n ]),\n remotePatterns: Object.freeze(\n (config?.remotePatterns ?? []).map((pattern) => normalizeRemotePattern(pattern)),\n ),\n localPatterns: Object.freeze(\n (config?.localPatterns ?? [{ pathname: \"/**\" }]).map((pattern) =>\n normalizeLocalPattern(pattern),\n ),\n ),\n deviceSizes: Object.freeze(deviceSizes),\n imageSizes: Object.freeze(imageSizes),\n qualities: Object.freeze(qualities),\n formats: Object.freeze(formats),\n minimumCacheTTL,\n maximumResponseBody: parseSize(\n config?.maximumResponseBody ?? \"10mb\",\n \"images.maximumResponseBody\",\n ),\n maximumRedirects,\n dangerouslyAllowSVG: config?.dangerouslyAllowSVG ?? false,\n dangerouslyAllowLocalIP: config?.dangerouslyAllowLocalIP ?? false,\n });\n}\n\nexport function getPublicFarmImageConfig(\n config: Pick<ResolvedFarmImageConfig, keyof PublicFarmImageConfig>,\n): PublicFarmImageConfig {\n return {\n provider: config.provider,\n path: config.path,\n deviceSizes: config.deviceSizes,\n imageSizes: config.imageSizes,\n qualities: config.qualities,\n formats: config.formats,\n };\n}\n\nfunction normalizeImagePath(value: string): string {\n const path = value.trim().replace(/\\/+$/, \"\") || \"/\";\n if (!path.startsWith(\"/\") || path.includes(\"?\") || path.includes(\"#\")) {\n throw new TypeError(\"images.path must be an absolute pathname without a query or hash\");\n }\n return path;\n}\n\nfunction normalizeIntegerList(values: readonly number[], name: string, max?: number): number[] {\n if (values.length === 0) {\n throw new TypeError(`${name} must contain at least one value`);\n }\n\n const normalized = [...new Set(values)].sort((left, right) => left - right);\n for (const value of normalized) {\n if (!Number.isSafeInteger(value) || value <= 0 || (max !== undefined && value > max)) {\n throw new TypeError(\n `${name} must contain positive integers${max ? ` no greater than ${max}` : \"\"}`,\n );\n }\n }\n return normalized;\n}\n\nfunction normalizeNonNegativeInteger(value: number, name: string): number {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new TypeError(`${name} must be a non-negative safe integer`);\n }\n return value;\n}\n\nfunction parseSize(value: number | string, name: string): number {\n if (typeof value === \"number\") {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`${name} must be a positive safe integer`);\n }\n return value;\n }\n\n const match = value\n .trim()\n .toLowerCase()\n .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)$/);\n if (!match) {\n throw new TypeError(`${name} must be bytes or a size string such as \"5mb\"`);\n }\n\n const bytes = Number(match[1]) * SIZE_UNITS[match[2]];\n if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n throw new TypeError(`${name} must resolve to a positive safe integer`);\n }\n return bytes;\n}\n\nfunction normalizeRemotePattern(pattern: FarmImageRemotePattern): FarmImageRemotePattern {\n const hostname = pattern.hostname.trim().toLowerCase();\n if (!hostname || hostname.includes(\"/\") || hostname.includes(\":\")) {\n throw new TypeError(\"images.remotePatterns[].hostname must be a hostname or wildcard hostname\");\n }\n if (pattern.pathname && !pattern.pathname.startsWith(\"/\")) {\n throw new TypeError(\"images.remotePatterns[].pathname must start with /\");\n }\n if (pattern.search && !pattern.search.startsWith(\"?\")) {\n throw new TypeError(\"images.remotePatterns[].search must start with ?\");\n }\n return Object.freeze({ ...pattern, hostname });\n}\n\nfunction normalizeLocalPattern(pattern: FarmImageLocalPattern): FarmImageLocalPattern {\n if (!pattern.pathname.startsWith(\"/\")) {\n throw new TypeError(\"images.localPatterns[].pathname must start with /\");\n }\n if (pattern.search && !pattern.search.startsWith(\"?\")) {\n throw new TypeError(\"images.localPatterns[].search must start with ?\");\n }\n return Object.freeze({ ...pattern });\n}\n","import { existsSync, readFileSync, realpathSync, statSync } from \"node:fs\";\nimport { mkdir, unlink } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\ntype EsbuildTransform = (typeof import(\"esbuild\"))[\"transform\"];\n\nexport type FarmLayerEntry = string;\n\nexport interface ResolvedFarmLayer {\n /** The value used in `extends`. */\n source: string;\n /** Stable name used by the `#layers/<name>` alias. */\n name: string;\n /** Absolute layer package or directory root. */\n root: string;\n /** Source directory relative to the layer root. */\n srcDir: string;\n /** Resolved layer config file when one exists. */\n configFile?: string;\n}\n\nexport interface FarmSourceRoot {\n name: string;\n root: string;\n srcDir: string;\n layer: boolean;\n}\n\nexport interface ResolveFarmLayersOptions {\n root: string;\n mode: \"development\" | \"production\";\n}\n\nexport interface FarmLayerResolution<TConfig extends Record<string, any>> {\n config: TConfig & {\n extends?: readonly FarmLayerEntry[];\n layers: ResolvedFarmLayer[];\n };\n layers: ResolvedFarmLayer[];\n}\n\nconst FARM_CORE_PACKAGE = \"@farm.js/core\";\nconst FARM_CONFIG_ENTRY = \"@farm.js/core/config\";\nconst FARM_CORE_REFERENCE_RE = /([\"'])@farm.js\\/core\\1/g;\nconst FARM_CONFIG_HELPER_IMPORT_RE =\n /(?:^|\\n)[\\t ]*import[\\t ]*\\{([^{}]*)\\}[\\t ]*from[\\t ]*([\"'])@farm.js\\/core\\2[\\t ]*;?[\\t ]*(?:\\n|$)/g;\nconst FARM_CONFIG_HELPER_SPECIFIER_RE =\n /^(?:defineConfig|defineFarmConfig)(?:\\s+as\\s+[$A-Z_a-z][$\\w]*)?$/;\n\nconst CONFIG_FILENAMES = [\n \"farm.config.ts\",\n \"farm.config.tsx\",\n \"farm.config.mts\",\n \"farm.config.cts\",\n \"farm.config.js\",\n \"farm.config.jsx\",\n \"farm.config.mjs\",\n \"farm.config.cjs\",\n \"config.ts\",\n \"config.tsx\",\n \"config.mts\",\n \"config.cts\",\n \"config.js\",\n \"config.jsx\",\n \"config.mjs\",\n \"config.cjs\",\n];\n\nconst LAYER_LOCAL_CONFIG_KEYS = new Set([\n \"root\",\n \"srcDir\",\n \"outDir\",\n \"distDir\",\n \"deploy\",\n \"output\",\n \"preset\",\n \"publicDir\",\n \"generateBuildId\",\n]);\n\ntype LoadedLayer = ResolvedFarmLayer & {\n config: Record<string, any>;\n};\n\nexport async function resolveFarmLayers<TConfig extends Record<string, any>>(\n projectConfig: TConfig,\n options: ResolveFarmLayersOptions,\n): Promise<FarmLayerResolution<TConfig>> {\n const projectRoot = path.resolve(options.root);\n const entries = normalizeLayerEntries(projectConfig.extends, \"project config\");\n\n if (entries.length === 0) {\n return {\n config: {\n ...projectConfig,\n layers: [],\n },\n layers: [],\n };\n }\n\n const loadedLayers: LoadedLayer[] = [];\n const visited = new Set<string>();\n const aliases = new Map<string, string>();\n\n const visit = async (\n source: string,\n ownerRoot: string,\n stack: Array<{ root: string; source: string }>,\n ): Promise<void> => {\n const resolvedSource = resolveLayerSource(source, ownerRoot);\n const cycleIndex = stack.findIndex((entry) => entry.root === resolvedSource.root);\n if (cycleIndex !== -1) {\n const cycle = [...stack.slice(cycleIndex).map((entry) => entry.source), source];\n throw new Error(`Farm layer cycle detected: ${cycle.join(\" -> \")}`);\n }\n if (visited.has(resolvedSource.root)) return;\n\n const configFile = findFarmConfigFile(resolvedSource.root, resolvedSource.configFile);\n const config = configFile\n ? await loadFarmConfigFile(configFile, {\n cacheRoot: projectRoot,\n root: resolvedSource.root,\n })\n : {};\n const nestedEntries = normalizeLayerEntries(config.extends, `layer ${JSON.stringify(source)}`);\n const nextStack = [...stack, { root: resolvedSource.root, source }];\n\n for (const nestedSource of nestedEntries) {\n await visit(nestedSource, resolvedSource.root, nextStack);\n }\n\n if (visited.has(resolvedSource.root)) return;\n\n const name = getLayerName(source, resolvedSource.root);\n const conflictingRoot = aliases.get(name);\n if (conflictingRoot && conflictingRoot !== resolvedSource.root) {\n throw new Error(\n `Farm layer alias \"#layers/${name}\" is ambiguous between ${conflictingRoot} and ${resolvedSource.root}`,\n );\n }\n aliases.set(name, resolvedSource.root);\n\n visited.add(resolvedSource.root);\n loadedLayers.push({\n source,\n name,\n root: resolvedSource.root,\n srcDir: normalizeLayerSrcDir(config.srcDir),\n configFile,\n config,\n });\n };\n\n for (const source of entries) {\n await visit(source, projectRoot, []);\n }\n\n let mergedConfig: Record<string, any> = {};\n for (const layer of loadedLayers) {\n mergedConfig = mergeFarmLayerConfig(mergedConfig, getLayerDefaults(layer.config));\n }\n mergedConfig = mergeFarmLayerConfig(mergedConfig, projectConfig);\n\n const layers = loadedLayers.map(({ config: _config, ...layer }) => layer);\n return {\n config: {\n ...mergedConfig,\n root: projectConfig.root,\n srcDir: projectConfig.srcDir,\n extends: projectConfig.extends,\n layers,\n } as unknown as FarmLayerResolution<TConfig>[\"config\"],\n layers,\n };\n}\n\nexport function getFarmSourceRoots(config: {\n root?: string;\n srcDir?: string;\n layers?: readonly ResolvedFarmLayer[];\n}): FarmSourceRoot[] {\n const roots: FarmSourceRoot[] = (config.layers ?? []).map((layer) => ({\n name: layer.name,\n root: layer.root,\n srcDir: layer.srcDir,\n layer: true,\n }));\n\n roots.push({\n name: \"project\",\n root: path.resolve(config.root || process.cwd()),\n srcDir: config.srcDir || \"src\",\n layer: false,\n });\n\n return roots;\n}\n\nexport function getFarmAppDirectories(config: {\n root?: string;\n srcDir?: string;\n layers?: readonly ResolvedFarmLayer[];\n}): string[] {\n return getFarmSourceRoots(config).map((source) => path.join(source.root, source.srcDir, \"app\"));\n}\n\nexport function getFarmLayerAliases(\n layers: readonly ResolvedFarmLayer[] | undefined,\n): Record<string, string> {\n return Object.fromEntries(\n (layers ?? []).map((layer) => [`#layers/${layer.name}`, path.join(layer.root, layer.srcDir)]),\n );\n}\n\nexport async function loadFarmConfigFile<TConfig = Record<string, any>>(\n configPath: string,\n options: { root: string; cacheRoot?: string },\n): Promise<TConfig> {\n const { build, transform } = await import(\"esbuild\");\n const cacheRoot = path.resolve(options.cacheRoot || options.root);\n const configCacheDir = path.join(cacheRoot, \".farm\", \".config-loader\");\n const configEntryChecks = new Map<string, Promise<boolean>>();\n await mkdir(configCacheDir, { recursive: true });\n\n const modulePath = path.join(\n configCacheDir,\n `farm-config-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n await build({\n absWorkingDir: path.resolve(options.root),\n entryPoints: [path.resolve(configPath)],\n outfile: modulePath,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: `node${process.versions.node.split(\".\")[0]}`,\n plugins: [\n {\n name: \"farm-config-package-resolution\",\n setup(pluginBuild) {\n pluginBuild.onResolve({ filter: /^@farm.js\\/core$/ }, async (args) => {\n if (\n args.pluginData?.farmConfigExternal ||\n args.kind !== \"import-statement\" ||\n !args.importer\n ) {\n return;\n }\n\n let configEntryCheck = configEntryChecks.get(args.importer);\n if (!configEntryCheck) {\n configEntryCheck = onlyImportsFarmConfigHelpers(args.importer, transform);\n configEntryChecks.set(args.importer, configEntryCheck);\n }\n if (!(await configEntryCheck)) return;\n\n const resolved = await pluginBuild.resolve(FARM_CONFIG_ENTRY, {\n importer: args.importer,\n kind: args.kind,\n namespace: args.namespace,\n resolveDir: args.resolveDir,\n pluginData: { farmConfigExternal: true },\n });\n if (resolved.errors.length > 0 || !resolved.path) return;\n\n return {\n path: resolved.path,\n external: true,\n warnings: resolved.warnings,\n };\n });\n\n pluginBuild.onResolve({ filter: /^[^./]/ }, async (args) => {\n if (args.pluginData?.farmConfigExternal) return;\n\n const resolved = await pluginBuild.resolve(args.path, {\n importer: args.importer,\n kind: args.kind,\n namespace: args.namespace,\n resolveDir: args.resolveDir,\n pluginData: { farmConfigExternal: true },\n });\n\n if (resolved.errors.length > 0 || !resolved.path) {\n return { path: args.path, external: true };\n }\n\n return {\n path: resolved.path,\n external: true,\n warnings: resolved.warnings,\n };\n });\n },\n },\n ],\n jsx: \"automatic\",\n logLevel: \"silent\",\n sourcemap: \"inline\",\n });\n\n const moduleUrl = `${pathToFileURL(modulePath).href}?t=${Date.now()}`;\n try {\n const loaded = await import(/* @vite-ignore */ moduleUrl);\n const config = loaded.default || loaded;\n if (!config || typeof config !== \"object\" || Array.isArray(config)) {\n throw new TypeError(`Farm config ${configPath} must export an object`);\n }\n return config as TConfig;\n } finally {\n await unlink(modulePath).catch(() => undefined);\n }\n}\n\nasync function onlyImportsFarmConfigHelpers(\n importer: string,\n transform: EsbuildTransform,\n): Promise<boolean> {\n try {\n const source = readFileSync(importer, \"utf8\");\n if (!source.includes(FARM_CORE_PACKAGE)) return false;\n\n const transformed = await transform(source, {\n format: \"esm\",\n jsx: \"automatic\",\n loader: getEsbuildLoader(importer),\n sourcefile: importer,\n });\n const references = [...transformed.code.matchAll(FARM_CORE_REFERENCE_RE)];\n if (references.length === 0) return false;\n\n const safeImportRanges: Array<{ start: number; end: number }> = [];\n for (const match of transformed.code.matchAll(FARM_CONFIG_HELPER_IMPORT_RE)) {\n const specifiers = match[1]\n .split(\",\")\n .map((specifier) => specifier.trim())\n .filter(Boolean);\n if (\n specifiers.length === 0 ||\n !specifiers.every((specifier) => FARM_CONFIG_HELPER_SPECIFIER_RE.test(specifier))\n ) {\n continue;\n }\n\n const start = match.index ?? 0;\n safeImportRanges.push({ start, end: start + match[0].length });\n }\n\n return references.every((reference) => {\n const index = reference.index ?? -1;\n return safeImportRanges.some((range) => index >= range.start && index < range.end);\n });\n } catch {\n // Unsupported syntax or non-file importers retain the existing package resolution path.\n return false;\n }\n}\n\nfunction getEsbuildLoader(file: string): \"js\" | \"jsx\" | \"ts\" | \"tsx\" {\n switch (path.extname(file)) {\n case \".ts\":\n case \".mts\":\n case \".cts\":\n return \"ts\";\n case \".tsx\":\n return \"tsx\";\n case \".jsx\":\n return \"jsx\";\n default:\n return \"js\";\n }\n}\n\nfunction normalizeLayerEntries(value: unknown, owner: string): string[] {\n if (value === undefined) return [];\n if (!Array.isArray(value)) {\n throw new TypeError(`${owner} \"extends\" must be an array of layer paths or package names`);\n }\n\n return value.map((entry, index) => {\n if (typeof entry !== \"string\" || entry.trim() === \"\") {\n throw new TypeError(`${owner} \"extends\" entry ${index} must be a non-empty string`);\n }\n return entry.trim();\n });\n}\n\nfunction resolveLayerSource(\n source: string,\n ownerRoot: string,\n): { root: string; configFile?: string } {\n if (isPathLayerSource(source)) {\n const target = source.startsWith(\"file:\")\n ? path.resolve(ownerRoot, source.slice(\"file:\".length))\n : path.resolve(ownerRoot, source);\n if (!existsSync(target)) {\n throw new Error(`Cannot resolve Farm layer ${JSON.stringify(source)} from ${ownerRoot}`);\n }\n\n const stats = statSync(target);\n const root = stats.isDirectory() ? target : path.dirname(target);\n return {\n root: normalizeRealPath(root),\n configFile: stats.isFile() ? normalizeRealPath(target) : undefined,\n };\n }\n\n const requireFromOwner = createRequire(path.join(ownerRoot, \"package.json\"));\n let packageJsonPath: string | undefined;\n try {\n packageJsonPath = requireFromOwner.resolve(`${source}/package.json`);\n } catch {\n // Packages with an exports map often hide package.json. Resolve their entry and walk upward.\n }\n\n if (packageJsonPath) {\n return { root: normalizeRealPath(path.dirname(packageJsonPath)) };\n }\n\n try {\n const entryPath = requireFromOwner.resolve(source);\n const packageRoot = findNearestPackageRoot(entryPath);\n if (packageRoot) return { root: normalizeRealPath(packageRoot) };\n } catch {\n // Use the common error below so local and package failures have the same shape.\n }\n\n throw new Error(`Cannot resolve Farm layer package ${JSON.stringify(source)} from ${ownerRoot}`);\n}\n\nfunction findNearestPackageRoot(entryPath: string): string | null {\n let current = statSync(entryPath).isDirectory() ? entryPath : path.dirname(entryPath);\n while (true) {\n if (existsSync(path.join(current, \"package.json\"))) return current;\n const parent = path.dirname(current);\n if (parent === current) return null;\n current = parent;\n }\n}\n\nfunction findFarmConfigFile(root: string, explicitPath?: string): string | undefined {\n if (explicitPath) return explicitPath;\n for (const fileName of CONFIG_FILENAMES) {\n const candidate = path.join(root, fileName);\n if (existsSync(candidate)) return candidate;\n }\n return undefined;\n}\n\nfunction getLayerName(source: string, root: string): string {\n if (!isPathLayerSource(source)) {\n const packageName = source.split(\"/\").filter(Boolean).pop();\n if (packageName) return sanitizeLayerName(packageName);\n }\n\n try {\n const packageJson = JSON.parse(readFileSync(path.join(root, \"package.json\"), \"utf8\"));\n if (typeof packageJson.name === \"string\") {\n return sanitizeLayerName(packageJson.name.split(\"/\").pop() || packageJson.name);\n }\n } catch {\n // A local layer does not need package metadata.\n }\n\n return sanitizeLayerName(path.basename(root));\n}\n\nfunction sanitizeLayerName(value: string): string {\n const name = value\n .trim()\n .replace(/[^a-zA-Z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n if (!name) throw new Error(`Cannot derive a name for Farm layer ${JSON.stringify(value)}`);\n return name;\n}\n\nfunction normalizeLayerSrcDir(value: unknown): string {\n if (value === undefined) return \"src\";\n if (typeof value !== \"string\" || value.trim() === \"\" || path.isAbsolute(value)) {\n throw new TypeError(\"A Farm layer srcDir must be a non-empty relative path\");\n }\n const normalized = path.normalize(value.trim());\n if (normalized === \"..\" || normalized.startsWith(`..${path.sep}`)) {\n throw new TypeError(\"A Farm layer srcDir cannot leave the layer root\");\n }\n return normalized;\n}\n\nfunction getLayerDefaults(config: Record<string, any>): Record<string, any> {\n return Object.fromEntries(\n Object.entries(config).filter(\n ([key, value]) =>\n key !== \"extends\" && value !== undefined && !LAYER_LOCAL_CONFIG_KEYS.has(key),\n ),\n );\n}\n\nfunction mergeFarmLayerConfig(\n base: Record<string, any>,\n override: Record<string, any>,\n): Record<string, any> {\n const output: Record<string, any> = { ...base };\n\n for (const [key, value] of Object.entries(override)) {\n if (value === undefined || key === \"layers\") continue;\n\n if (key === \"plugins\") {\n output[key] = [...toArray(output[key]), ...toArray(value)];\n continue;\n }\n\n if (key === \"middleware\" && output[key] !== undefined) {\n output[key] = [...toArray(output[key]), ...toArray(value)];\n continue;\n }\n\n if ((key === \"redirects\" || key === \"rewrites\" || key === \"headers\") && output[key]) {\n output[key] = mergeConfigListResolvers(output[key], value);\n continue;\n }\n\n if (isPlainObject(output[key]) && isPlainObject(value)) {\n output[key] = mergePlainObjects(output[key], value);\n continue;\n }\n\n output[key] = value;\n }\n\n return output;\n}\n\nfunction mergePlainObjects(base: Record<string, any>, override: Record<string, any>) {\n const output: Record<string, any> = { ...base };\n for (const [key, value] of Object.entries(override)) {\n if (value === undefined) continue;\n output[key] =\n isPlainObject(output[key]) && isPlainObject(value)\n ? mergePlainObjects(output[key], value)\n : value;\n }\n return output;\n}\n\nfunction mergeConfigListResolvers(base: unknown, override: unknown) {\n return async () => [...(await resolveConfigList(base)), ...(await resolveConfigList(override))];\n}\n\nasync function resolveConfigList(value: unknown): Promise<any[]> {\n const resolved = typeof value === \"function\" ? await value() : value;\n return toArray(resolved);\n}\n\nfunction toArray(value: unknown): any[] {\n if (value === undefined || value === null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, any> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isPathLayerSource(source: string): boolean {\n return (\n source.startsWith(\".\") ||\n source.startsWith(\"/\") ||\n source.startsWith(\"file:\") ||\n /^[a-zA-Z]:[\\\\/]/.test(source)\n );\n}\n\nfunction normalizeRealPath(value: string): string {\n return path.resolve(realpathSync(value));\n}\n","export type FarmIntegrationAPIMethod =\n | \"GET\"\n | \"POST\"\n | \"PUT\"\n | \"PATCH\"\n | \"DELETE\"\n | \"OPTIONS\"\n | \"HEAD\";\n\nexport type FarmIntegrationAPIBodyFormat = \"json\" | \"form\" | \"none\";\nexport type FarmIntegrationAPIResponseFormat = \"json\" | \"text\" | \"response\";\n\nexport interface FarmIntegrationAPIOperation<\n TBody = never,\n TQuery = never,\n TResponse = unknown,\n TServer extends boolean = false,\n TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n> {\n readonly kind: \"farm-integration-api-operation\";\n path: string;\n method: TMethod;\n bodyFormat?: FarmIntegrationAPIBodyFormat;\n responseFormat?: FarmIntegrationAPIResponseFormat;\n headers?: Record<string, string>;\n credentials?: RequestCredentials;\n isServer?: TServer;\n __pathless?: boolean;\n __types?: {\n body: TBody;\n query: TQuery;\n response: TResponse;\n };\n}\n\nexport type FarmIntegrationAPI = {\n [key: string]: FarmIntegrationAPI | FarmIntegrationAPIOperation<any, any, any, any, any>;\n};\n\nexport type FarmIntegrationRouteOperationCarrier<\n TPath extends string = string,\n TOperation extends FarmIntegrationAPIOperation<any, any, any, any, any> =\n FarmIntegrationAPIOperation<any, any, any, any, any>,\n> = {\n path: TPath;\n __operation: TOperation;\n};\n\ntype IntegrationAPIBuilderOptions<TServer extends boolean = false> = Omit<\n FarmIntegrationAPIOperation<any, any, any, TServer>,\n \"kind\" | \"method\" | \"path\" | \"__pathless\" | \"__types\"\n>;\n\nexport function defineIntegrationAPIOperation<\n TBody = never,\n TQuery = never,\n TResponse = unknown,\n TServer extends boolean = false,\n TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n>(\n operation: Omit<\n FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>,\n \"kind\" | \"__types\"\n >,\n): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod> {\n return {\n kind: \"farm-integration-api-operation\",\n ...operation,\n };\n}\n\nexport function defineIntegrationAPI<TAPI extends FarmIntegrationAPI>(api: TAPI): TAPI {\n return api;\n}\n\nfunction operation<\n TBody = never,\n TQuery = never,\n TResponse = unknown,\n TServer extends boolean = false,\n TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n>(\n method: TMethod,\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod> {\n const hasExplicitPath = typeof pathOrOptions === \"string\";\n const path = hasExplicitPath ? pathOrOptions : \"\";\n const options = (\n hasExplicitPath\n ? maybeOptions\n : {\n ...maybeOptions,\n ...pathOrOptions,\n }\n ) as IntegrationAPIBuilderOptions<TServer>;\n\n return defineIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>({\n path,\n method,\n __pathless: !hasExplicitPath,\n ...options,\n });\n}\n\nfunction get<TResponse = unknown, TServer extends boolean = false>(\n path: string,\n options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, never, TResponse, TServer, \"GET\">;\nfunction get<TQuery = never, TResponse = unknown, TServer extends boolean = false>(\n path: string,\n options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"GET\">;\nfunction get<TResponse = unknown, TServer extends boolean = false>(\n options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, never, TResponse, TServer, \"GET\">;\nfunction get<TQuery = never, TResponse = unknown, TServer extends boolean = false>(\n options?: IntegrationAPIBuilderOptions<TServer>,\n): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"GET\">;\nfunction get(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<boolean>,\n maybeOptions: IntegrationAPIBuilderOptions<boolean> = {} as IntegrationAPIBuilderOptions<boolean>,\n) {\n return operation<never, any, any, boolean>(\"GET\", pathOrOptions, maybeOptions);\n}\n\nfunction isOperation(value: unknown): value is FarmIntegrationAPIOperation<any, any, any, any> {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as FarmIntegrationAPIOperation<any, any, any, any>).kind ===\n \"farm-integration-api-operation\"\n );\n}\n\nfunction bindRoutePath<TAPI extends FarmIntegrationAPI>(path: string, api: TAPI): TAPI {\n const entries = Object.entries(api as Record<string, unknown>).map(([key, value]) => {\n if (isOperation(value)) {\n return [\n key,\n {\n ...value,\n path,\n __pathless: false,\n },\n ];\n }\n\n if (value && typeof value === \"object\") {\n return [key, bindRoutePath(path, value as FarmIntegrationAPI)];\n }\n\n return [key, value];\n });\n\n return Object.fromEntries(entries) as TAPI;\n}\n\ntype RouteOperationsToAPI<\n TOperations extends readonly FarmIntegrationAPIOperation<any, any, any, any, any>[],\n> = {\n [TMethod in Lowercase<TOperations[number][\"method\"] & string>]: Extract<\n TOperations[number],\n { method: Uppercase<TMethod> }\n >;\n};\n\ntype StripRouteClientPrefix<TPath extends string> = TPath extends `/api/${string}/${infer TRest}`\n ? TRest\n : TPath extends `/${string}/${infer TRest}`\n ? TRest\n : TPath extends `/${infer TRest}`\n ? TRest\n : TPath;\n\ntype NormalizeRouteSegment<TSegment extends string> = TSegment extends `[...${infer TName}]`\n ? TName\n : TSegment extends `[${infer TName}]`\n ? TName\n : TSegment extends `${infer TName}(${string}`\n ? TName\n : CamelCaseRouteSegment<TSegment>;\n\ntype CamelCaseRouteSegment<TSegment extends string> =\n TSegment extends `${infer THead}-${infer TTail}`\n ? `${THead}${Capitalize<CamelCaseRouteSegment<TTail>>}`\n : TSegment;\n\ntype RouteNamespaceFromPath<\n TPath extends string,\n TOperation extends FarmIntegrationAPIOperation<any, any, any, any, any>,\n> = TPath extends `${infer THead}/${infer TTail}`\n ? {\n [TKey in NormalizeRouteSegment<THead>]: RouteNamespaceFromPath<TTail, TOperation>;\n }\n : {\n [TKey in NormalizeRouteSegment<TPath>]: {\n [TMethod in Lowercase<TOperation[\"method\"] & string>]: TOperation;\n };\n };\n\ntype UnionToIntersection<TUnion> = (\n TUnion extends unknown ? (value: TUnion) => void : never\n) extends (value: infer TIntersection) => void\n ? TIntersection\n : never;\n\ntype ExpandRecursively<TValue> = TValue extends (...args: any[]) => any\n ? TValue\n : TValue extends object\n ? { [TKey in keyof TValue]: ExpandRecursively<TValue[TKey]> }\n : TValue;\n\ntype RoutesToAPI<TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[]> =\n ExpandRecursively<\n UnionToIntersection<\n TRoutes[number] extends FarmIntegrationRouteOperationCarrier<infer TPath, infer TOperation>\n ? RouteNamespaceFromPath<StripRouteClientPrefix<TPath>, TOperation>\n : never\n >\n >;\n\nexport type InferIntegrationAPIFromRoutes<\n TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[],\n> = RoutesToAPI<TRoutes>;\n\nfunction route<TAPI extends FarmIntegrationAPI>(path: string, definition: TAPI): TAPI;\nfunction route<TOperations extends readonly FarmIntegrationAPIOperation<any, any, any, any, any>[]>(\n path: string,\n ...operations: TOperations\n): RouteOperationsToAPI<TOperations>;\nfunction route(\n path: string,\n definitionOrOperation: FarmIntegrationAPI | FarmIntegrationAPIOperation<any, any, any, any, any>,\n ...operations: readonly FarmIntegrationAPIOperation<any, any, any, any, any>[]\n) {\n if (isOperation(definitionOrOperation)) {\n const allOperations = [definitionOrOperation, ...operations];\n return Object.fromEntries(\n allOperations.map((operation) => [\n operation.method.toLowerCase(),\n {\n ...operation,\n path,\n __pathless: false,\n },\n ]),\n );\n }\n\n return bindRoutePath(path, definitionOrOperation as FarmIntegrationAPI);\n}\n\nfunction normalizeRouteSegment(segment: string): string {\n if (!segment) {\n return \"index\";\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n return segment.slice(4, -1) || \"index\";\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n return segment.slice(1, -1) || \"index\";\n }\n\n const matcherIndex = segment.indexOf(\"(\");\n if (matcherIndex > 0) {\n return segment.slice(0, matcherIndex);\n }\n\n return camelCaseRouteSegment(segment);\n}\n\nfunction camelCaseRouteSegment(segment: string): string {\n return segment.replace(/-([a-zA-Z0-9])/g, (_match, value: string) => value.toUpperCase());\n}\n\nfunction getRouteClientSegments(path: string): string[] {\n const segments = path.split(\"/\").filter(Boolean);\n if (segments.length === 0) {\n return [\"index\"];\n }\n\n const stripped =\n segments[0] === \"api\" && segments.length > 2\n ? segments.slice(2)\n : segments.length > 1\n ? segments.slice(1)\n : [segments[segments.length - 1]];\n\n return stripped.map(normalizeRouteSegment).filter(Boolean);\n}\n\nfunction setRouteOperation(\n target: Record<string, unknown>,\n pathSegments: string[],\n operation: FarmIntegrationAPIOperation<any, any, any, any, any>,\n) {\n const [head, ...tail] = pathSegments;\n if (!head) {\n return;\n }\n\n if (tail.length === 0) {\n const leaf = ((target[head] as Record<string, unknown> | undefined) || {}) as Record<\n string,\n unknown\n >;\n leaf[operation.method.toLowerCase()] = {\n ...operation,\n path: operation.path,\n __pathless: false,\n };\n target[head] = leaf;\n return;\n }\n\n const branch = ((target[head] as Record<string, unknown> | undefined) || {}) as Record<\n string,\n unknown\n >;\n target[head] = branch;\n setRouteOperation(branch, tail, operation);\n}\n\nfunction fromRoutes<TRoutes extends readonly FarmIntegrationRouteOperationCarrier<string, any>[]>(\n routes: TRoutes,\n): RoutesToAPI<TRoutes> {\n const definition: Record<string, unknown> = {};\n\n for (const route of routes) {\n if (!isOperation(route.__operation)) {\n continue;\n }\n\n setRouteOperation(definition, getRouteClientSegments(route.path), {\n ...route.__operation,\n path: route.path,\n __pathless: false,\n });\n }\n\n return definition as RoutesToAPI<TRoutes>;\n}\n\nexport const api = {\n get,\n route,\n fromRoutes,\n post<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"POST\"> {\n return operation<TBody, TQuery, TResponse, TServer, \"POST\">(\"POST\", pathOrOptions, {\n bodyFormat: \"json\",\n ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n });\n },\n put<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PUT\"> {\n return operation<TBody, TQuery, TResponse, TServer, \"PUT\">(\"PUT\", pathOrOptions, {\n bodyFormat: \"json\",\n ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n });\n },\n patch<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PATCH\"> {\n return operation<TBody, TQuery, TResponse, TServer, \"PATCH\">(\"PATCH\", pathOrOptions, {\n bodyFormat: \"json\",\n ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n });\n },\n delete<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"DELETE\"> {\n return operation<TBody, TQuery, TResponse, TServer, \"DELETE\">(\"DELETE\", pathOrOptions, {\n bodyFormat: \"json\",\n ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n });\n },\n options<TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n ): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"OPTIONS\"> {\n return operation<never, TQuery, TResponse, TServer, \"OPTIONS\">(\n \"OPTIONS\",\n pathOrOptions,\n maybeOptions,\n );\n },\n head<TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n ): FarmIntegrationAPIOperation<never, TQuery, TResponse, TServer, \"HEAD\"> {\n return operation<never, TQuery, TResponse, TServer, \"HEAD\">(\n \"HEAD\",\n pathOrOptions,\n maybeOptions,\n );\n },\n form: {\n post<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"POST\"> {\n return operation<TBody, TQuery, TResponse, TServer, \"POST\">(\"POST\", pathOrOptions, {\n bodyFormat: \"form\",\n ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n });\n },\n put<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PUT\"> {\n return operation<TBody, TQuery, TResponse, TServer, \"PUT\">(\"PUT\", pathOrOptions, {\n bodyFormat: \"form\",\n ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n });\n },\n patch<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"PATCH\"> {\n return operation<TBody, TQuery, TResponse, TServer, \"PATCH\">(\"PATCH\", pathOrOptions, {\n bodyFormat: \"form\",\n ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n });\n },\n delete<TBody = never, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n pathOrOptions?: string | IntegrationAPIBuilderOptions<TServer>,\n maybeOptions: IntegrationAPIBuilderOptions<TServer> = {} as IntegrationAPIBuilderOptions<TServer>,\n ): FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, \"DELETE\"> {\n return operation<TBody, TQuery, TResponse, TServer, \"DELETE\">(\"DELETE\", pathOrOptions, {\n bodyFormat: \"form\",\n ...(typeof pathOrOptions === \"string\" ? maybeOptions : pathOrOptions),\n });\n },\n },\n};\n\nexport const endpoint = api;\n","import { once } from \"node:events\";\nimport type { ServerResponse } from \"node:http\";\n\nexport async function sendWebResponse(res: ServerResponse, response: Response): Promise<void> {\n res.statusCode = response.status;\n\n const responseHeaders = response.headers as Headers & {\n getSetCookie?: () => string[];\n };\n const setCookies = responseHeaders.getSetCookie?.() || [];\n if (setCookies.length > 0) {\n res.setHeader(\"Set-Cookie\", setCookies);\n }\n\n response.headers.forEach((value, key) => {\n if (key.toLowerCase() === \"set-cookie\" && setCookies.length > 0) {\n return;\n }\n res.setHeader(key, value);\n });\n\n if (!response.body) {\n res.end();\n return;\n }\n\n if (typeof res.write !== \"function\") {\n const body = await response.arrayBuffer();\n res.end(Buffer.from(body));\n return;\n }\n\n const reader = response.body.getReader();\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n if (!value || value.byteLength === 0) {\n continue;\n }\n\n if (!res.write(value)) {\n await once(res, \"drain\");\n }\n }\n\n res.end();\n } catch (error) {\n if (!res.writableEnded) {\n const responseError = error instanceof Error ? error : new Error(String(error));\n if (typeof res.destroy === \"function\") {\n res.destroy(responseError);\n } else {\n res.end();\n }\n }\n throw error;\n } finally {\n reader.releaseLock();\n }\n}\n","import type {\n AnyFieldBuilder,\n AnyModelDefinition,\n FieldBuilder,\n JsonValue,\n ModelDefinition,\n OrmClient,\n SchemaDefinition,\n SchemaModels,\n} from \"@farming-labs/orm\";\nimport type {\n FarmIntegrationSchema,\n FarmIntegrationSchemaField,\n FarmIntegrationSchemaModel,\n} from \"./integrations\";\nimport { resolveStorageRuntimeClient } from \"./storage\";\nimport type { FarmStorageUserConfig } from \"./storage/types\";\nimport type { FarmConfig } from \"./types\";\n\ntype RuntimeClientFactory<TClient> = () => TClient | Promise<TClient>;\n\nexport type FarmIntegrationOrmSchema = SchemaDefinition<Record<string, AnyModelDefinition>>;\n\nexport type FarmIntegrationOrmClient<TSchema extends FarmIntegrationOrmSchema> = OrmClient<TSchema>;\n\ntype FarmIntegrationOrmFieldKind<TField extends FarmIntegrationSchemaField> = TField[\"type\"] extends\n | \"id\"\n | \"uuid\"\n ? \"id\"\n : TField[\"type\"] extends \"text\"\n ? \"string\"\n : TField[\"type\"] extends \"number\"\n ? \"decimal\"\n : Extract<TField[\"type\"], \"string\" | \"boolean\" | \"integer\" | \"datetime\" | \"json\" | \"enum\">;\n\ntype FarmIntegrationOrmFieldNullable<TField extends FarmIntegrationSchemaField> = TField extends {\n nullable: true;\n}\n ? true\n : TField extends { required: false }\n ? true\n : false;\n\ntype FarmIntegrationOrmEnumValue<TField extends FarmIntegrationSchemaField> = TField extends {\n values: readonly (infer TValue extends string)[];\n}\n ? TValue\n : string;\n\ntype FarmIntegrationOrmFieldValue<TField extends FarmIntegrationSchemaField> =\n TField[\"type\"] extends \"id\" | \"uuid\" | \"string\" | \"text\"\n ? string\n : TField[\"type\"] extends \"boolean\"\n ? boolean\n : TField[\"type\"] extends \"integer\"\n ? number\n : TField[\"type\"] extends \"number\"\n ? string\n : TField[\"type\"] extends \"datetime\"\n ? Date\n : TField[\"type\"] extends \"json\"\n ? JsonValue\n : TField[\"type\"] extends \"enum\"\n ? FarmIntegrationOrmEnumValue<TField>\n : never;\n\nexport type InferFarmIntegrationOrmField<TField extends FarmIntegrationSchemaField> = FieldBuilder<\n FarmIntegrationOrmFieldKind<TField>,\n FarmIntegrationOrmFieldNullable<TField>,\n FarmIntegrationOrmFieldValue<TField>\n>;\n\nexport type InferFarmIntegrationOrmFields<TModel extends FarmIntegrationSchemaModel> = {\n [TFieldKey in keyof TModel[\"fields\"] & string]: InferFarmIntegrationOrmField<\n Extract<TModel[\"fields\"][TFieldKey], FarmIntegrationSchemaField>\n >;\n};\n\nexport type InferFarmIntegrationOrmSchema<TSchema extends FarmIntegrationSchema> =\n SchemaDefinition<{\n [TModelKey in keyof TSchema[\"models\"] & string]: ModelDefinition<\n InferFarmIntegrationOrmFields<\n Extract<TSchema[\"models\"][TModelKey], FarmIntegrationSchemaModel>\n >,\n {}\n >;\n }>;\n\nexport type InferFarmIntegrationOrmClient<TSchema extends FarmIntegrationSchema | undefined> =\n TSchema extends FarmIntegrationSchema ? OrmClient<InferFarmIntegrationOrmSchema<TSchema>> : never;\n\nexport interface CreateIntegrationOrmOptions<\n TClient = unknown,\n TSchema extends FarmIntegrationSchema = FarmIntegrationSchema,\n> {\n schema: TSchema;\n config?: Pick<FarmConfig, \"storage\">;\n storage?: FarmStorageUserConfig;\n client?: TClient | RuntimeClientFactory<TClient>;\n}\n\nexport async function createIntegrationOrm<\n TClient = unknown,\n TSchema extends FarmIntegrationSchema = FarmIntegrationSchema,\n>(\n options: CreateIntegrationOrmOptions<TClient, TSchema>,\n): Promise<InferFarmIntegrationOrmClient<TSchema>> {\n const [schema, client] = await Promise.all([\n farmIntegrationSchemaToOrmSchema(options.schema),\n resolveIntegrationOrmRuntimeClient(options),\n ]);\n\n if (!client) {\n throw new Error(\n \"Schema-backed integration storage requires a runtime client at farm.config storage.client.\",\n );\n }\n\n const { createOrmFromRuntime } = await import(\"@farming-labs/orm-runtime\");\n return createOrmFromRuntime({\n schema,\n client,\n }) as Promise<InferFarmIntegrationOrmClient<TSchema>>;\n}\n\nexport async function resolveIntegrationOrmRuntimeClient<TClient = unknown>(\n options: Omit<CreateIntegrationOrmOptions<TClient>, \"schema\">,\n): Promise<TClient | unknown | undefined> {\n if (options.client !== undefined) {\n return typeof options.client === \"function\"\n ? await (options.client as RuntimeClientFactory<TClient>)()\n : options.client;\n }\n\n return resolveStorageRuntimeClient(options.storage ?? options.config?.storage);\n}\n\nexport async function farmIntegrationSchemaToOrmSchema(\n schema: FarmIntegrationSchema,\n): Promise<FarmIntegrationOrmSchema> {\n const orm = await import(\"@farming-labs/orm\");\n const models: Record<string, AnyModelDefinition> = {};\n\n for (const [modelKey, modelSchema] of Object.entries(schema.models)) {\n models[modelKey] = orm.model({\n table: modelSchema.name ?? modelKey,\n fields: createOrmModelFields(orm, modelSchema),\n constraints: createOrmModelConstraints(modelSchema),\n description: modelSchema.description,\n }) as AnyModelDefinition;\n }\n\n return orm.defineSchema(models) as FarmIntegrationOrmSchema;\n}\n\nfunction createOrmModelFields(\n orm: typeof import(\"@farming-labs/orm\"),\n modelSchema: FarmIntegrationSchemaModel,\n): Record<string, AnyFieldBuilder> {\n return Object.fromEntries(\n Object.entries(modelSchema.fields).map(([fieldKey, fieldSchema]) => [\n fieldKey,\n createOrmField(orm, fieldKey, fieldSchema),\n ]),\n );\n}\n\nfunction createOrmField(\n orm: typeof import(\"@farming-labs/orm\"),\n fieldKey: string,\n field: FarmIntegrationSchemaField,\n): AnyFieldBuilder {\n let builder = createOrmFieldBuilder(orm, fieldKey, field) as AnyFieldBuilder;\n\n if (field.unique) {\n builder = builder.unique();\n }\n\n if (field.nullable || field.required === false) {\n builder = builder.nullable();\n }\n\n if (field.default !== undefined) {\n builder =\n field.type === \"datetime\" && field.default === \"now\"\n ? builder.defaultNow()\n : builder.default(field.default as never);\n }\n\n if (field.reference) {\n builder = builder.references(`${field.reference.model}.${field.reference.field}`);\n }\n\n if (field.name && field.name !== fieldKey) {\n builder = builder.map(field.name);\n }\n\n if (field.description) {\n builder = builder.describe(field.description);\n }\n\n return builder;\n}\n\nfunction createOrmFieldBuilder(\n orm: typeof import(\"@farming-labs/orm\"),\n fieldKey: string,\n field: FarmIntegrationSchemaField,\n): AnyFieldBuilder {\n switch (field.type) {\n case \"id\":\n case \"uuid\":\n return orm.id();\n case \"string\":\n case \"text\":\n return orm.string();\n case \"boolean\":\n return orm.boolean();\n case \"integer\":\n return orm.integer();\n case \"number\":\n return orm.decimal();\n case \"datetime\":\n return orm.datetime();\n case \"json\":\n return orm.json();\n case \"enum\": {\n if (!field.values?.length) {\n throw new Error(`Integration schema enum field \"${fieldKey}\" must define values.`);\n }\n\n return orm.enumeration(field.values as readonly [string, ...string[]]);\n }\n default:\n throw new Error(\n `Unsupported integration schema field type \"${field.type}\" for \"${fieldKey}\".`,\n );\n }\n}\n\nfunction createOrmModelConstraints(modelSchema: FarmIntegrationSchemaModel) {\n const unique: Array<readonly [string, ...string[]]> = [];\n const indexes: Array<readonly [string, ...string[]]> = [];\n\n for (const constraint of modelSchema.constraints ?? []) {\n if (!constraint.fields.length) {\n continue;\n }\n\n const fields = constraint.fields as readonly [string, ...string[]];\n if (constraint.type === \"unique\") {\n unique.push(fields);\n } else {\n indexes.push(fields);\n }\n }\n\n return {\n unique,\n indexes,\n };\n}\n\nexport type IntegrationOrmModelNames<TSchema extends FarmIntegrationOrmSchema> =\n keyof SchemaModels<TSchema> & string;\n","import type { ComponentType, ReactNode } from \"react\";\nimport { api as integrationApi, defineIntegrationAPIOperation } from \"./integration-api\";\nimport type {\n FarmIntegrationAPI,\n FarmIntegrationAPIBodyFormat,\n FarmIntegrationAPIMethod,\n FarmIntegrationAPIOperation,\n FarmIntegrationAPIResponseFormat,\n FarmIntegrationRouteOperationCarrier,\n InferIntegrationAPIFromRoutes,\n} from \"./integration-api\";\nimport type { InferFarmIntegrationOrmClient } from \"./integration-orm\";\nimport type { FarmPlugin, FarmPluginContext, FarmRequestStore } from \"./plugin\";\nimport {\n clearRequestContext,\n deleteRequestContext,\n getRequestContext,\n getRequestContextSnapshot,\n hasRequestContext,\n setRequestContext,\n} from \"./request-context\";\nimport { sendWebResponse } from \"./server/response\";\nimport type { FarmRequest } from \"./types\";\n\nexport { api, defineIntegrationAPI, defineIntegrationAPIOperation } from \"./integration-api\";\nexport type {\n FarmIntegrationAPI,\n FarmIntegrationAPIBodyFormat,\n FarmIntegrationAPIMethod,\n FarmIntegrationAPIOperation,\n FarmIntegrationAPIResponseFormat,\n} from \"./integration-api\";\n\nexport type FarmIntegrationCategory = \"auth\" | \"payment\" | \"monitoring\" | \"logging\" | (string & {});\n\n/** @deprecated Use FarmIntegrationCategory instead. */\nexport type FarmIntegrationSlot = FarmIntegrationCategory;\n\nexport type FarmIntegrationRouteParamValue = string | string[];\nexport type FarmIntegrationRouteParams = Record<string, FarmIntegrationRouteParamValue>;\nexport type FarmIntegrationRouteMethod =\n | FarmIntegrationAPIMethod\n | Lowercase<FarmIntegrationAPIMethod>\n | \"ALL\"\n | \"all\";\nexport type FarmIntegrationRouteInputSource = \"body\" | \"query\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport type FarmIntegrationValidationPathSegment =\n | PropertyKey\n | {\n readonly key: PropertyKey;\n };\n\nexport interface FarmIntegrationRouteInput<TBody = unknown, TQuery = unknown> {\n body?: TBody;\n query?: TQuery;\n}\n\nexport interface FarmIntegrationValidationIssue {\n source: FarmIntegrationRouteInputSource;\n path?: readonly (string | number)[];\n code?: string;\n message: string;\n}\n\nexport interface FarmIntegrationValidationErrorLike {\n issues?: readonly {\n path?: readonly FarmIntegrationValidationPathSegment[];\n code?: string;\n message?: string;\n }[];\n message?: string;\n}\n\nexport type FarmIntegrationValidationResult<TValue> =\n | {\n success: true;\n data: TValue;\n }\n | {\n success: false;\n error: FarmIntegrationValidationErrorLike;\n };\n\nexport type FarmIntegrationStandardValidationResult<TValue> =\n | {\n value: TValue;\n }\n | {\n issues: readonly {\n path?: readonly FarmIntegrationValidationPathSegment[];\n code?: string;\n message: string;\n }[];\n };\n\nexport interface FarmIntegrationInputSchema<TValue = unknown> {\n _output?: TValue;\n parse?(value: unknown): MaybePromise<TValue>;\n safeParse?(value: unknown): MaybePromise<FarmIntegrationValidationResult<TValue>>;\n safeParseAsync?(value: unknown): Promise<FarmIntegrationValidationResult<TValue>>;\n \"~standard\"?: {\n validate(value: unknown): MaybePromise<FarmIntegrationStandardValidationResult<TValue>>;\n types?: {\n output: TValue;\n };\n };\n}\n\nexport interface FarmIntegrationRouteInputSchemas<TBody = unknown, TQuery = unknown> {\n body?: FarmIntegrationInputSchema<TBody>;\n query?: FarmIntegrationInputSchema<TQuery>;\n}\n\n/** @deprecated Use `FarmRequestStore` and access it through `ctx.req`. */\nexport type FarmIntegrationRequestContextStore = FarmRequestStore;\n\nexport const FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY = \"farm.integration.internalDispatch\";\n\nexport type FarmIntegrationRouteDb<TSchema extends FarmIntegrationSchema | undefined> =\n InferFarmIntegrationOrmClient<TSchema>;\n\nexport interface FarmIntegrationRouteStorageArgs<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n getClient(): Promise<unknown | undefined>;\n getOrm(): Promise<FarmIntegrationRouteDb<TSchema>>;\n}\n\nexport interface FarmIntegrationRouteArgs<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n db: FarmIntegrationRouteDb<TSchema>;\n getDb(): Promise<FarmIntegrationRouteDb<TSchema>>;\n storage: FarmIntegrationRouteStorageArgs<TSchema>;\n}\n\nexport interface FarmIntegrationConfigContext<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n key: string;\n integration: FarmIntegration<TSchema, any>;\n appConfig: FarmPluginContext[\"config\"];\n /** Alias for appConfig. */\n config: FarmPluginContext[\"config\"];\n args: FarmIntegrationRouteArgs<TSchema>;\n env: Record<string, string | undefined>;\n isDev: boolean;\n isProd: boolean;\n}\n\nexport interface FarmIntegrationConfigDefinition<\n TConfig = unknown,\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n schema?: FarmIntegrationInputSchema<TConfig>;\n env?: Record<string, string | readonly string[]>;\n defaults?:\n | Partial<TConfig>\n | ((context: FarmIntegrationConfigContext<TSchema>) => MaybePromise<Partial<TConfig>>);\n input?:\n | Partial<TConfig>\n | ((context: FarmIntegrationConfigContext<TSchema>) => MaybePromise<Partial<TConfig>>);\n resolve?(\n context: FarmIntegrationConfigContext<TSchema>,\n ): MaybePromise<TConfig | Partial<TConfig> | undefined>;\n}\n\nexport type FarmIntegrationConfigInput<\n TConfig = unknown,\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = FarmIntegrationInputSchema<TConfig> | FarmIntegrationConfigDefinition<TConfig, TSchema>;\n\nexport type FarmIntegrationLifecycleLogLevel = \"info\" | \"warn\" | \"error\";\n\nexport interface FarmIntegrationLifecycleLogger {\n info(message: string, meta?: Record<string, unknown>): void;\n warn(message: string, meta?: Record<string, unknown>): void;\n error(message: string, meta?: Record<string, unknown>): void;\n}\n\nexport interface FarmIntegrationLifecycleContext<\n TConfig = unknown,\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationConfigContext<TSchema> {\n integration: FarmIntegration<TSchema, TConfig>;\n integrationConfig: TConfig;\n log: FarmIntegrationLifecycleLogger;\n reason?: string;\n cleanup(callback?: () => MaybePromise<void>): Promise<void>;\n}\n\nexport type FarmIntegrationLifecycleHook<\n TConfig = unknown,\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = (context: FarmIntegrationLifecycleContext<TConfig, TSchema>) => MaybePromise<void>;\n\n/**\n * Small per-call integration metadata. Values received over HTTP are\n * client-controlled and should be validated before authorization decisions.\n */\nexport type FarmIntegrationData = Record<string, unknown>;\n\nexport interface FarmIntegrationHandlerContext<\n TBody = unknown,\n TQuery = unknown,\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n request: Request;\n requestId: string;\n url: URL;\n pathname: string;\n method: string;\n params: FarmIntegrationRouteParams;\n input: FarmIntegrationRouteInput<TBody, TQuery>;\n args: FarmIntegrationRouteArgs<TSchema>;\n data: FarmIntegrationData;\n integration: {\n category: FarmIntegrationCategory;\n /** @deprecated Use category instead. */\n slot: FarmIntegrationCategory;\n type: string;\n instance: unknown;\n };\n route: {\n kind: \"route\" | \"middleware\";\n path: string;\n methods: readonly string[];\n };\n req: FarmRequestStore;\n /** @deprecated Use `req` instead. */\n requestContext: FarmRequestStore;\n config: FarmPluginContext[\"config\"];\n isDev: boolean;\n isProd: boolean;\n}\n\nexport interface FarmIntegrationRouteHookContext<\n TBody = unknown,\n TQuery = unknown,\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationHandlerContext<TBody, TQuery, TSchema> {\n response?: Response;\n}\n\nexport type FarmIntegrationRouteHook<\n TBody = unknown,\n TQuery = unknown,\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = {\n bivarianceHack(\n request: Request,\n context: FarmIntegrationRouteHookContext<TBody, TQuery, TSchema>,\n ): Promise<Response | void> | Response | void;\n}[\"bivarianceHack\"];\n\nexport interface FarmIntegrationRoute<\n TBody = unknown,\n TQuery = unknown,\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n path: string;\n method?: FarmIntegrationRouteMethod;\n methods?: readonly FarmIntegrationRouteMethod[];\n middleware?: readonly FarmIntegrationRouteMiddleware<TSchema>[];\n before?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n after?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n rawBody?: boolean;\n bodyFormat?: FarmIntegrationAPIBodyFormat;\n body?: FarmIntegrationInputSchema<TBody>;\n query?: FarmIntegrationInputSchema<TQuery>;\n input?: FarmIntegrationRouteInputSchemas<TBody, TQuery>;\n handler(\n request: Request,\n context: FarmIntegrationHandlerContext<TBody, TQuery, TSchema>,\n ): Promise<Response> | Response;\n}\n\nexport interface FarmTypedIntegrationRoute<\n TPath extends string = string,\n TBody = never,\n TQuery = never,\n TResponse = unknown,\n TServer extends boolean = false,\n TMethod extends FarmIntegrationAPIMethod = FarmIntegrationAPIMethod,\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationRoute<TBody, TQuery, TSchema> {\n path: TPath;\n method: TMethod;\n __operation: FarmIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>;\n}\n\nexport interface FarmIntegrationRouteMiddleware<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n handler(\n request: Request,\n context: FarmIntegrationHandlerContext<unknown, unknown, TSchema>,\n ): Promise<Response | void> | Response | void;\n}\n\nexport interface FarmIntegrationMiddleware<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n matcher?: string | string[];\n handler(\n request: Request,\n context: FarmIntegrationHandlerContext<unknown, unknown, TSchema>,\n ): Promise<Response | void> | Response | void;\n}\n\nexport interface FarmIntegrationProviderProps {\n children: ReactNode;\n}\n\nexport interface FarmIntegrationProvider {\n name: string;\n type: string;\n props?: Record<string, unknown>;\n component?: ComponentType<FarmIntegrationProviderProps>;\n}\n\nexport interface FarmIntegrationDocumentNavigation {\n matcher: string | readonly string[];\n}\n\nexport type FarmIntegrationSchemaFieldType =\n | \"id\"\n | \"uuid\"\n | \"string\"\n | \"text\"\n | \"boolean\"\n | \"integer\"\n | \"number\"\n | \"datetime\"\n | \"json\"\n | \"enum\";\n\nexport interface FarmIntegrationSchemaReference {\n model: string;\n field: string;\n relation?: \"belongsTo\" | \"hasOne\" | \"hasMany\";\n onDelete?: \"cascade\" | \"restrict\" | \"setNull\" | \"noAction\";\n enforced?: \"db\" | \"app\" | \"none\";\n}\n\nexport interface FarmIntegrationSchemaField {\n type: FarmIntegrationSchemaFieldType;\n name?: string;\n description?: string;\n required?: boolean;\n nullable?: boolean;\n primaryKey?: boolean;\n unique?: boolean;\n index?: boolean;\n list?: boolean;\n default?: unknown;\n values?: readonly string[];\n reference?: FarmIntegrationSchemaReference;\n meta?: Record<string, unknown>;\n}\n\nexport interface FarmIntegrationSchemaConstraint {\n type: \"unique\" | \"index\";\n fields: readonly string[];\n name?: string;\n meta?: Record<string, unknown>;\n}\n\nexport interface FarmIntegrationSchemaModel {\n name?: string;\n description?: string;\n fields: Record<string, FarmIntegrationSchemaField>;\n constraints?: readonly FarmIntegrationSchemaConstraint[];\n meta?: Record<string, unknown>;\n}\n\nexport interface FarmIntegrationSchemaModelExtension {\n name?: string;\n description?: string;\n fields?: Record<string, FarmIntegrationSchemaField>;\n constraints?: readonly FarmIntegrationSchemaConstraint[];\n meta?: Record<string, unknown>;\n}\n\nexport interface FarmIntegrationSchemaModelOverride {\n name?: string;\n description?: string;\n fields?: Record<string, Partial<FarmIntegrationSchemaField>>;\n constraints?: readonly FarmIntegrationSchemaConstraint[];\n meta?: Record<string, unknown>;\n}\n\nexport interface FarmIntegrationSchema {\n models: Record<string, FarmIntegrationSchemaModel>;\n meta?: Record<string, unknown>;\n extend?: Record<string, FarmIntegrationSchemaModelExtension>;\n override?: Record<string, FarmIntegrationSchemaModelOverride>;\n}\n\nexport function defineIntegrationSchema<TSchema extends FarmIntegrationSchema>(\n schema: TSchema,\n): TSchema {\n return schema;\n}\n\nexport type FarmIntegrationLogPhase =\n | \"registered\"\n | \"validate\"\n | \"setup\"\n | \"ready\"\n | \"dispose\"\n | \"request:start\"\n | \"request:end\"\n | \"request:error\";\n\nexport interface FarmIntegrationLogEvent {\n category: FarmIntegrationCategory;\n /** @deprecated Use category instead. */\n slot: FarmIntegrationCategory;\n type: string;\n phase: FarmIntegrationLogPhase;\n route?: {\n kind: \"route\" | \"middleware\";\n path: string;\n methods: readonly string[];\n };\n requestId?: string;\n request?: Request;\n response?: Response;\n error?: unknown;\n durationMs?: number;\n level?: FarmIntegrationLifecycleLogLevel;\n message?: string;\n meta?: Record<string, unknown>;\n context: Map<string, unknown>;\n}\n\nexport type FarmIntegrationLogger = (event: FarmIntegrationLogEvent) => void | Promise<void>;\n\nexport interface FarmIntegration<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n TConfig = unknown,\n> {\n readonly kind: \"farm-integration\";\n category: FarmIntegrationCategory;\n /** @deprecated Use category instead. */\n slot?: FarmIntegrationCategory;\n type: string;\n instance: unknown;\n /** Set to false when a platform adapter owns this integration's production routes. */\n serverRuntime?: boolean;\n api?: FarmIntegrationAPI;\n schema?: TSchema;\n config?: FarmIntegrationConfigInput<TConfig, TSchema>;\n validate?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n setup?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n ready?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n dispose?: FarmIntegrationLifecycleHook<TConfig, TSchema>;\n log?: FarmIntegrationLogger;\n routes?: readonly FarmIntegrationRoute<any, any, TSchema>[];\n endpoints?: FarmIntegrationEndpoints<TSchema>;\n middleware?: readonly FarmIntegrationMiddleware<TSchema>[];\n providers?: readonly FarmIntegrationProvider[];\n documentNavigations?: readonly FarmIntegrationDocumentNavigation[];\n plugins?: readonly FarmPlugin[];\n}\n\nexport type FarmIntegrationsUserConfig = Record<string, FarmIntegration<any, any> | undefined>;\n\nconst FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME = Symbol.for(\n \"@farm.js/core/integration-plugin-server-runtime\",\n);\n\n/** @internal Identifies lifecycle plugins owned by platform-managed integrations. */\nexport function getFarmIntegrationPluginServerRuntime(plugin: FarmPlugin): boolean | undefined {\n const value = (plugin as FarmPlugin & Record<symbol, unknown>)[\n FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME\n ];\n return typeof value === \"boolean\" ? value : undefined;\n}\n\ntype IntegrationRouteBuilderOptions<\n TBody,\n TQuery,\n TServer extends boolean,\n TSchema extends FarmIntegrationSchema | undefined,\n> = {\n middleware?: readonly FarmIntegrationRouteMiddleware<TSchema>[];\n before?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n after?: readonly FarmIntegrationRouteHook<TBody, TQuery, TSchema>[];\n rawBody?: boolean;\n headers?: Record<string, string>;\n credentials?: RequestCredentials;\n bodyFormat?: FarmIntegrationAPIBodyFormat;\n responseFormat?: FarmIntegrationAPIResponseFormat;\n isServer?: TServer;\n body?: FarmIntegrationInputSchema<TBody>;\n query?: FarmIntegrationInputSchema<TQuery>;\n input?: FarmIntegrationRouteInputSchemas<TBody, TQuery>;\n handler(\n request: Request,\n context: FarmIntegrationHandlerContext<TBody, TQuery, TSchema>,\n ): Promise<Response> | Response;\n};\n\nfunction defineTypedIntegrationRoute<\n TPath extends string,\n TBody,\n TQuery,\n TResponse,\n TServer extends boolean,\n TMethod extends FarmIntegrationAPIMethod,\n TSchema extends FarmIntegrationSchema | undefined,\n>(\n method: TMethod,\n path: TPath,\n input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, TMethod, TSchema> {\n return {\n path,\n method,\n middleware: input.middleware,\n before: input.before,\n after: input.after,\n rawBody: input.rawBody,\n bodyFormat: input.bodyFormat,\n input: normalizeIntegrationRouteInputSchemas(input),\n handler: input.handler,\n __operation: defineIntegrationAPIOperation<TBody, TQuery, TResponse, TServer, TMethod>({\n path,\n method,\n bodyFormat: input.bodyFormat,\n responseFormat: input.responseFormat,\n headers: input.headers,\n credentials: input.credentials,\n isServer: input.isServer,\n }),\n };\n}\n\nexport interface FarmIntegrationRouteFactory<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n get<TPath extends string, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n path: TPath,\n input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n ): FarmTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"GET\", TSchema>;\n post<\n TPath extends string,\n TBody = never,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(\n path: TPath,\n input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"POST\", TSchema>;\n put<\n TPath extends string,\n TBody = never,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(\n path: TPath,\n input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"PUT\", TSchema>;\n patch<\n TPath extends string,\n TBody = never,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(\n path: TPath,\n input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"PATCH\", TSchema>;\n delete<\n TPath extends string,\n TBody = never,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(\n path: TPath,\n input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>,\n ): FarmTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"DELETE\", TSchema>;\n options<\n TPath extends string,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(\n path: TPath,\n input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n ): FarmTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"OPTIONS\", TSchema>;\n head<TPath extends string, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n path: TPath,\n input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n ): FarmTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"HEAD\", TSchema>;\n}\n\nexport interface FarmIntegrationRoutesFactoryContext<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> {\n route: FarmIntegrationRouteFactory<TSchema>;\n integrationRoute: FarmIntegrationRouteFactory<TSchema>;\n}\n\nexport type FarmIntegrationRoutesFactory<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = (\n context: FarmIntegrationRoutesFactoryContext<TSchema>,\n) => readonly FarmIntegrationRoute<any, any, TSchema>[];\n\nexport type FarmIntegrationEndpointValue<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> =\n | FarmIntegrationRoute<any, any, TSchema>\n | readonly FarmIntegrationEndpointValue<TSchema>[]\n | {\n readonly [key: string]: FarmIntegrationEndpointValue<TSchema> | undefined;\n };\n\nexport type FarmIntegrationEndpoints<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = {\n readonly [key: string]: FarmIntegrationEndpointValue<TSchema> | undefined;\n};\n\nexport interface FarmIntegrationEndpointsFactoryContext<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> extends FarmIntegrationRoutesFactoryContext<TSchema> {\n endpoint: FarmIntegrationRouteFactory<TSchema>;\n}\n\nexport type FarmIntegrationEndpointsFactory<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = (context: FarmIntegrationEndpointsFactoryContext<TSchema>) => FarmIntegrationEndpoints<TSchema>;\n\nfunction createIntegrationRouteFactory<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n>(): FarmIntegrationRouteFactory<TSchema> {\n return {\n get<TPath extends string, TResponse = unknown, TQuery = never, TServer extends boolean = false>(\n path: TPath,\n input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n ) {\n return defineTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"GET\", TSchema>(\n \"GET\",\n path,\n input,\n );\n },\n post<\n TPath extends string,\n TBody = never,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n return defineTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"POST\", TSchema>(\n \"POST\",\n path,\n {\n bodyFormat: \"json\",\n ...input,\n },\n );\n },\n put<\n TPath extends string,\n TBody = never,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n return defineTypedIntegrationRoute<TPath, TBody, TQuery, TResponse, TServer, \"PUT\", TSchema>(\n \"PUT\",\n path,\n {\n bodyFormat: \"json\",\n ...input,\n },\n );\n },\n patch<\n TPath extends string,\n TBody = never,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n return defineTypedIntegrationRoute<\n TPath,\n TBody,\n TQuery,\n TResponse,\n TServer,\n \"PATCH\",\n TSchema\n >(\"PATCH\", path, {\n bodyFormat: \"json\",\n ...input,\n });\n },\n delete<\n TPath extends string,\n TBody = never,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(path: TPath, input: IntegrationRouteBuilderOptions<TBody, TQuery, TServer, TSchema>) {\n return defineTypedIntegrationRoute<\n TPath,\n TBody,\n TQuery,\n TResponse,\n TServer,\n \"DELETE\",\n TSchema\n >(\"DELETE\", path, {\n bodyFormat: \"json\",\n ...input,\n });\n },\n options<\n TPath extends string,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(\n path: TPath,\n input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n ) {\n return defineTypedIntegrationRoute<\n TPath,\n never,\n TQuery,\n TResponse,\n TServer,\n \"OPTIONS\",\n TSchema\n >(\"OPTIONS\", path, input);\n },\n head<\n TPath extends string,\n TResponse = unknown,\n TQuery = never,\n TServer extends boolean = false,\n >(\n path: TPath,\n input: Omit<IntegrationRouteBuilderOptions<never, TQuery, TServer, TSchema>, \"bodyFormat\">,\n ) {\n return defineTypedIntegrationRoute<TPath, never, TQuery, TResponse, TServer, \"HEAD\", TSchema>(\n \"HEAD\",\n path,\n input,\n );\n },\n };\n}\n\nexport function createIntegrationRoute<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n>(_schema?: TSchema): FarmIntegrationRouteFactory<TSchema> {\n return createIntegrationRouteFactory<TSchema>();\n}\n\nexport const integrationRoute = createIntegrationRouteFactory<undefined>();\n\ntype RegisteredIntegrationRuntime = {\n integration: FarmIntegration;\n config: FarmPluginContext[\"config\"];\n isDev: boolean;\n isProd: boolean;\n};\n\nconst INTEGRATION_RUNTIME_REGISTRY_KEY = Symbol.for(\"farm.integrationRuntimeRegistry\");\nconst INTEGRATION_REQUEST_DISPATCHER_KEY = Symbol.for(\"farm.integrationRequestDispatcher\");\n\ntype IntegrationRequestDispatcher = (\n runtime: RegisteredIntegrationRuntime,\n request: Request,\n options?: { currentRequest?: Request },\n) => Promise<Response | null>;\n\ntype GlobalWithIntegrationRuntimeRegistry = typeof globalThis & {\n [INTEGRATION_RUNTIME_REGISTRY_KEY]?: Map<string, RegisteredIntegrationRuntime>;\n [INTEGRATION_REQUEST_DISPATCHER_KEY]?: IntegrationRequestDispatcher;\n};\n\nfunction getIntegrationRuntimeRegistry() {\n const globalState = globalThis as GlobalWithIntegrationRuntimeRegistry;\n if (!globalState[INTEGRATION_RUNTIME_REGISTRY_KEY]) {\n globalState[INTEGRATION_RUNTIME_REGISTRY_KEY] = new Map<string, RegisteredIntegrationRuntime>();\n }\n\n return globalState[INTEGRATION_RUNTIME_REGISTRY_KEY]!;\n}\n\ntype FarmIntegrationRoutesInput<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = readonly FarmIntegrationRoute<any, any, TSchema>[] | FarmIntegrationRoutesFactory<TSchema>;\n\ntype FarmIntegrationEndpointsInput<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n> = FarmIntegrationEndpoints<TSchema> | FarmIntegrationEndpointsFactory<TSchema>;\n\ntype FarmIntegrationInput<\n TSchema extends FarmIntegrationSchema | undefined = FarmIntegrationSchema | undefined,\n TConfig = unknown,\n> = Omit<\n FarmIntegration<TSchema, TConfig>,\n \"kind\" | \"category\" | \"slot\" | \"config\" | \"routes\" | \"endpoints\"\n> & {\n config?: FarmIntegrationConfigInput<TConfig, TSchema>;\n routes?: FarmIntegrationRoutesInput<TSchema>;\n endpoints?: FarmIntegrationEndpointsInput<TSchema>;\n} & (\n | {\n category: FarmIntegrationCategory;\n slot?: FarmIntegrationCategory;\n }\n | {\n category?: FarmIntegrationCategory;\n slot: FarmIntegrationCategory;\n }\n );\n\ntype FarmIntegrationCategoryInput =\n | {\n category: FarmIntegrationCategory;\n slot?: FarmIntegrationCategory;\n }\n | {\n category?: FarmIntegrationCategory;\n slot: FarmIntegrationCategory;\n };\n\ntype FarmIntegrationShapeForInference = FarmIntegrationCategoryInput & {\n api?: FarmIntegrationAPI;\n schema?: FarmIntegrationSchema;\n config?: unknown;\n routes?: unknown;\n endpoints?: unknown;\n};\n\ntype ExtractIntegrationSchema<TIntegration> = TIntegration extends {\n schema: infer TSchema extends FarmIntegrationSchema;\n}\n ? TSchema\n : undefined;\n\ntype ResolveIntegrationRoutesInput<TRoutes, TSchema extends FarmIntegrationSchema | undefined> =\n TRoutes extends FarmIntegrationRoutesFactory<TSchema> ? ReturnType<TRoutes> : TRoutes;\n\ntype ResolveIntegrationEndpointsInput<\n TEndpoints,\n TSchema extends FarmIntegrationSchema | undefined,\n> =\n TEndpoints extends FarmIntegrationEndpointsFactory<TSchema> ? ReturnType<TEndpoints> : TEndpoints;\n\ntype ExtractIntegrationRoutesFromRoutesInput<\n TRoutes,\n TSchema extends FarmIntegrationSchema | undefined,\n> =\n ResolveIntegrationRoutesInput<TRoutes, TSchema> extends readonly (infer TRoute)[]\n ? TRoute\n : never;\n\ntype ExtractIntegrationRoutesFromEndpointValue<TValue> =\n TValue extends FarmIntegrationRouteOperationCarrier<string, any>\n ? TValue\n : TValue extends readonly (infer TItem)[]\n ? ExtractIntegrationRoutesFromEndpointValue<TItem>\n : TValue extends object\n ? ExtractIntegrationRoutesFromEndpointValue<TValue[keyof TValue]>\n : never;\n\ntype ExtractIntegrationRoutesFromEndpointsInput<\n TEndpoints,\n TSchema extends FarmIntegrationSchema | undefined,\n> = ExtractIntegrationRoutesFromEndpointValue<\n ResolveIntegrationEndpointsInput<TEndpoints, TSchema>\n>;\n\ntype ExtractIntegrationRouteUnion<TIntegration, TSchema extends FarmIntegrationSchema | undefined> =\n | (TIntegration extends { routes: infer TRoutes }\n ? ExtractIntegrationRoutesFromRoutesInput<TRoutes, TSchema>\n : never)\n | (TIntegration extends { endpoints: infer TEndpoints }\n ? ExtractIntegrationRoutesFromEndpointsInput<TEndpoints, TSchema>\n : never);\n\ntype ExtractDefinedIntegrationRoutes<\n TIntegration,\n TSchema extends FarmIntegrationSchema | undefined,\n> = [ExtractIntegrationRouteUnion<TIntegration, TSchema>] extends [never]\n ? undefined\n : readonly ExtractIntegrationRouteUnion<TIntegration, TSchema>[];\n\ntype ExtractDefinedIntegrationEndpoints<\n TIntegration,\n TSchema extends FarmIntegrationSchema | undefined,\n> = TIntegration extends { endpoints: infer TEndpoints }\n ? ResolveIntegrationEndpointsInput<TEndpoints, TSchema>\n : undefined;\n\ntype ExtractIntegrationAPIRoutes<\n TIntegration,\n TSchema extends FarmIntegrationSchema | undefined,\n> = Extract<\n ExtractIntegrationRouteUnion<TIntegration, TSchema>,\n FarmIntegrationRouteOperationCarrier<string, any>\n>;\n\ntype ExtractIntegrationCategory<TIntegration extends FarmIntegrationCategoryInput> =\n TIntegration extends {\n category: infer TCategory extends FarmIntegrationCategory;\n }\n ? TCategory\n : TIntegration extends { slot: infer TSlot extends FarmIntegrationCategory }\n ? TSlot\n : FarmIntegrationCategory;\n\ntype ExtractDerivedIntegrationAPI<\n TIntegration extends FarmIntegrationShapeForInference,\n TSchema extends FarmIntegrationSchema | undefined = ExtractIntegrationSchema<TIntegration>,\n> = TIntegration extends { api: infer TAPI extends FarmIntegrationAPI }\n ? TAPI\n : [ExtractIntegrationAPIRoutes<TIntegration, TSchema>] extends [never]\n ? FarmIntegrationAPI | undefined\n : InferIntegrationAPIFromRoutes<readonly ExtractIntegrationAPIRoutes<TIntegration, TSchema>[]>;\n\nexport type DefinedIntegration<\n TIntegration extends FarmIntegrationShapeForInference,\n TSchema extends FarmIntegrationSchema | undefined = ExtractIntegrationSchema<TIntegration>,\n> = Omit<TIntegration, \"kind\" | \"category\" | \"slot\" | \"api\" | \"routes\" | \"endpoints\"> & {\n readonly kind: \"farm-integration\";\n category: ExtractIntegrationCategory<TIntegration>;\n slot: ExtractIntegrationCategory<TIntegration>;\n routes: ExtractDefinedIntegrationRoutes<TIntegration, TSchema>;\n endpoints: ExtractDefinedIntegrationEndpoints<TIntegration, TSchema>;\n api: ExtractDerivedIntegrationAPI<TIntegration, TSchema>;\n};\n\nfunction isIntegrationEndpointRoute(value: unknown): value is FarmIntegrationRoute {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as { path?: unknown }).path === \"string\" &&\n typeof (value as { handler?: unknown }).handler === \"function\"\n );\n}\n\nfunction flattenIntegrationEndpoints(\n endpoints: FarmIntegrationEndpointValue | FarmIntegrationEndpoints | undefined,\n): FarmIntegrationRoute[] {\n if (!endpoints) {\n return [];\n }\n\n if (Array.isArray(endpoints)) {\n return endpoints.flatMap((endpoint) => flattenIntegrationEndpoints(endpoint));\n }\n\n if (isIntegrationEndpointRoute(endpoints)) {\n return [endpoints];\n }\n\n if (typeof endpoints === \"object\") {\n return Object.values(endpoints).flatMap((endpoint) => flattenIntegrationEndpoints(endpoint));\n }\n\n return [];\n}\n\nexport function defineIntegration<\n const TSchema extends FarmIntegrationSchema | undefined,\n const TConfig,\n TIntegration extends FarmIntegrationInput<TSchema, TConfig>,\n>(\n integration: TIntegration & FarmIntegrationInput<TSchema, TConfig>,\n): DefinedIntegration<TIntegration, TSchema>;\nexport function defineIntegration<\n const TSchema extends FarmIntegrationSchema | undefined,\n const TConfig,\n TIntegration extends FarmIntegrationInput<TSchema, TConfig>,\n>(\n integration: TIntegration & FarmIntegrationInput<TSchema, TConfig>,\n): DefinedIntegration<TIntegration, TSchema> {\n const category = integration.category ?? integration.slot;\n\n if (!category) {\n throw new Error(\"Integration category is required.\");\n }\n\n if (integration.category && integration.slot && integration.category !== integration.slot) {\n throw new Error(\"Integration category and slot must match when both are provided.\");\n }\n\n const routeFactory = createIntegrationRoute(integration.schema);\n const routes =\n typeof integration.routes === \"function\"\n ? integration.routes({\n route: routeFactory,\n integrationRoute: routeFactory,\n })\n : integration.routes;\n const endpoints =\n typeof integration.endpoints === \"function\"\n ? integration.endpoints({\n endpoint: routeFactory,\n route: routeFactory,\n integrationRoute: routeFactory,\n })\n : integration.endpoints;\n const endpointRoutes = flattenIntegrationEndpoints(endpoints);\n const allRoutes =\n routes?.length || endpointRoutes.length\n ? ([...(routes || []), ...endpointRoutes] as readonly FarmIntegrationRoute[])\n : undefined;\n\n const derivedApi =\n integration.api ||\n (allRoutes?.length\n ? integrationApi.fromRoutes(\n allRoutes as unknown as ReadonlyArray<{\n path: string;\n __operation: FarmIntegrationAPIOperation<any, any, any, any, any>;\n }>,\n )\n : undefined);\n\n return {\n kind: \"farm-integration\",\n ...integration,\n endpoints,\n routes: allRoutes,\n api: derivedApi,\n category,\n slot: category,\n } as unknown as DefinedIntegration<TIntegration, TSchema>;\n}\n\nexport function isFarmIntegration(value: unknown): value is FarmIntegration {\n return (\n !!value && typeof value === \"object\" && (value as FarmIntegration).kind === \"farm-integration\"\n );\n}\n\nexport function resolveIntegrationPlugins(\n integrations: FarmIntegrationsUserConfig | undefined,\n): FarmPlugin[] {\n if (!integrations) {\n return [];\n }\n\n const plugins: FarmPlugin[] = [];\n for (const [key, integration] of Object.entries(integrations)) {\n if (!integration || !isFarmIntegration(integration)) {\n continue;\n }\n\n plugins.push(createIntegrationPlugin(key, integration));\n\n if (integration.plugins?.length) {\n plugins.push(...integration.plugins);\n }\n }\n\n return plugins;\n}\n\nexport function getIntegrationProviders(\n integrations: FarmIntegrationsUserConfig | undefined,\n): Array<Pick<FarmIntegrationProvider, \"name\" | \"type\" | \"props\">> {\n if (!integrations) {\n return [];\n }\n\n const providers: Array<Pick<FarmIntegrationProvider, \"name\" | \"type\" | \"props\">> = [];\n for (const integration of Object.values(integrations)) {\n if (!integration || !isFarmIntegration(integration) || !integration.providers?.length) {\n continue;\n }\n\n for (const provider of integration.providers) {\n providers.push({\n name: provider.name,\n type: provider.type,\n props: provider.props,\n });\n }\n }\n\n return providers;\n}\n\nexport function getIntegrationDocumentNavigationMatchers(\n integrations: FarmIntegrationsUserConfig | undefined,\n): string[] {\n if (!integrations) {\n return [];\n }\n\n const matchers: string[] = [];\n for (const integration of Object.values(integrations)) {\n if (\n !integration ||\n !isFarmIntegration(integration) ||\n !integration.documentNavigations?.length\n ) {\n continue;\n }\n\n for (const navigation of integration.documentNavigations) {\n const items = Array.isArray(navigation.matcher) ? navigation.matcher : [navigation.matcher];\n\n for (const item of items) {\n matchers.push(item);\n }\n }\n }\n\n return matchers;\n}\n\nexport function getIntegrationSchemas(\n integrations: FarmIntegrationsUserConfig | undefined,\n): Record<string, FarmIntegrationSchema> {\n if (!integrations) {\n return {};\n }\n\n const schemaEntries = Object.entries(integrations)\n .map(([key, integration]) => {\n const schema = integration && isFarmIntegration(integration) ? integration.schema : undefined;\n return schema ? ([key, schema] as const) : null;\n })\n .filter((value): value is readonly [string, FarmIntegrationSchema] => value !== null);\n\n return Object.fromEntries(schemaEntries);\n}\n\nexport function getRegisteredIntegrationRuntime(\n key: string,\n): RegisteredIntegrationRuntime | undefined {\n return getIntegrationRuntimeRegistry().get(key);\n}\n\nexport function getRegisteredIntegrations(): Record<string, FarmIntegration> {\n return Object.fromEntries(\n Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime]) => [\n key,\n runtime.integration,\n ]),\n );\n}\n\nexport function getRegisteredIntegrationSchemas(): Record<string, FarmIntegrationSchema> {\n return getIntegrationSchemas(getRegisteredIntegrations());\n}\n\nexport function matchIntegrationRoute(\n integrations: FarmIntegrationsUserConfig | undefined,\n input: {\n pathname: string;\n method?: string;\n },\n): {\n key: string;\n integration: FarmIntegration;\n route: {\n path: string;\n methods: readonly string[];\n };\n params: FarmIntegrationRouteParams;\n} | null {\n if (!integrations) {\n return null;\n }\n\n for (const [key, integration] of Object.entries(integrations)) {\n if (!integration || !isFarmIntegration(integration)) {\n continue;\n }\n\n const routes = normalizeIntegrationRoutes(integration.routes || []);\n\n for (const route of routes) {\n if (!matchesMethod(route.methods, input.method)) {\n continue;\n }\n\n const params = extractPathParams(route.path, input.pathname);\n if (!params) {\n continue;\n }\n\n return {\n key,\n integration,\n route: {\n path: route.path,\n methods: route.methods,\n },\n params,\n };\n }\n }\n\n return null;\n}\n\nexport function matchRegisteredIntegrationRoute(input: { pathname: string; method?: string }): {\n key: string;\n integration: FarmIntegration;\n route: {\n path: string;\n methods: readonly string[];\n };\n params: FarmIntegrationRouteParams;\n} | null {\n return matchIntegrationRoute(getRegisteredIntegrations(), input);\n}\n\nfunction createClientSafeIntegrationAPI(\n api: FarmIntegrationAPI | undefined,\n): FarmIntegrationAPI | undefined {\n if (!api) {\n return undefined;\n }\n\n const entries = Object.entries(api as Record<string, unknown>).map(([key, value]) => {\n if (\n value &&\n typeof value === \"object\" &&\n (value as FarmIntegrationAPIOperation<any, any, any, any, any>).kind ===\n \"farm-integration-api-operation\"\n ) {\n const operation = value as FarmIntegrationAPIOperation<any, any, any, any, any>;\n return [\n key,\n defineIntegrationAPIOperation({\n path: operation.path,\n method: operation.method,\n bodyFormat: operation.bodyFormat,\n responseFormat: operation.responseFormat,\n credentials: operation.credentials,\n isServer: operation.isServer,\n }),\n ];\n }\n\n if (value && typeof value === \"object\") {\n return [key, createClientSafeIntegrationAPI(value as FarmIntegrationAPI)];\n }\n\n return [key, value];\n });\n\n return Object.fromEntries(entries) as FarmIntegrationAPI;\n}\n\nexport function getRegisteredIntegrationAPIManifest(): Record<string, FarmIntegrationAPI> {\n const manifestEntries = Object.entries(getRegisteredIntegrations())\n .map(([key, integration]) => {\n const api = createClientSafeIntegrationAPI(integration.api);\n return api ? ([key, api] as const) : null;\n })\n .filter((value): value is readonly [string, FarmIntegrationAPI] => value !== null);\n\n return Object.fromEntries(manifestEntries);\n}\n\ntype IntegrationLifecycleCleanup = () => MaybePromise<void>;\n\nfunction getIntegrationRuntimeEnv(): Record<string, string | undefined> {\n return typeof process !== \"undefined\" ? process.env : {};\n}\n\nfunction isIntegrationConfigDefinition(\n value: unknown,\n): value is FarmIntegrationConfigDefinition<unknown> {\n return (\n !!value &&\n typeof value === \"object\" &&\n (\"schema\" in value ||\n \"env\" in value ||\n \"defaults\" in value ||\n \"input\" in value ||\n \"resolve\" in value)\n );\n}\n\nfunction mergeIntegrationConfigValue(current: unknown, next: unknown): unknown {\n if (next === undefined) {\n return current;\n }\n\n if (isPlainIntegrationConfigObject(current) && isPlainIntegrationConfigObject(next)) {\n return {\n ...current,\n ...next,\n };\n }\n\n return next;\n}\n\nfunction isPlainIntegrationConfigObject(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nasync function resolveIntegrationConfigPart<TValue>(\n value: TValue | ((context: FarmIntegrationConfigContext) => MaybePromise<TValue>) | undefined,\n context: FarmIntegrationConfigContext,\n): Promise<TValue | undefined> {\n if (typeof value === \"function\") {\n return (value as (context: FarmIntegrationConfigContext) => MaybePromise<TValue>)(context);\n }\n\n return value;\n}\n\nfunction resolveIntegrationEnvConfig(\n env: Record<string, string | readonly string[]> | undefined,\n): Record<string, string> | undefined {\n if (!env) {\n return undefined;\n }\n\n const runtimeEnv = getIntegrationRuntimeEnv();\n const config: Record<string, string> = {};\n\n for (const [key, names] of Object.entries(env)) {\n const envNames = Array.isArray(names) ? names : [names];\n const value = envNames.map((name) => runtimeEnv[name]).find((entry) => entry !== undefined);\n if (value !== undefined) {\n config[key] = value;\n }\n }\n\n return config;\n}\n\nasync function parseIntegrationConfigSchema<TConfig>(\n integration: FarmIntegration<any, any>,\n schema: FarmIntegrationInputSchema<TConfig>,\n value: unknown,\n): Promise<TConfig> {\n const parser = schema.safeParseAsync || schema.safeParse;\n if (parser) {\n const result = await parser.call(schema, value);\n if (result.success) {\n return result.data;\n }\n\n throw createIntegrationConfigValidationError(integration, result.error);\n }\n\n if (schema[\"~standard\"]?.validate) {\n const result = await schema[\"~standard\"].validate(value);\n if (\"value\" in result) {\n return result.value;\n }\n\n throw createIntegrationConfigValidationError(integration, {\n issues: result.issues,\n });\n }\n\n if (schema.parse) {\n try {\n return await schema.parse(value);\n } catch (error) {\n throw createIntegrationConfigValidationError(\n integration,\n normalizeIntegrationValidationError(error),\n );\n }\n }\n\n throw new Error(\n `Integration \"${integration.type}\" config schema must expose safeParse, safeParseAsync, parse, or ~standard.validate.`,\n );\n}\n\nfunction createIntegrationConfigValidationError(\n integration: FarmIntegration<any, any>,\n error: FarmIntegrationValidationErrorLike,\n) {\n const issues =\n Array.isArray(error.issues) && error.issues.length > 0\n ? error.issues\n .map((issue) => {\n const normalizedPath = normalizeIntegrationValidationPath(issue.path);\n const path = normalizedPath.length ? `${normalizedPath.join(\".\")}: ` : \"\";\n return `${path}${issue.message || \"Invalid config\"}`;\n })\n .join(\"; \")\n : error.message || \"Invalid config\";\n\n return new Error(`Integration \"${integration.type}\" config validation failed: ${issues}`);\n}\n\nasync function resolveIntegrationConfig<TConfig>(\n integration: FarmIntegration<any, TConfig>,\n context: FarmIntegrationConfigContext,\n): Promise<TConfig> {\n const config = integration.config;\n if (!config) {\n return undefined as TConfig;\n }\n\n if (!isIntegrationConfigDefinition(config)) {\n return parseIntegrationConfigSchema(integration, config, {});\n }\n\n let value: unknown = {};\n value = mergeIntegrationConfigValue(\n value,\n await resolveIntegrationConfigPart(config.defaults, context),\n );\n value = mergeIntegrationConfigValue(value, resolveIntegrationEnvConfig(config.env));\n value = mergeIntegrationConfigValue(\n value,\n await resolveIntegrationConfigPart(config.input, context),\n );\n value = mergeIntegrationConfigValue(value, await config.resolve?.(context));\n\n return config.schema\n ? parseIntegrationConfigSchema(integration, config.schema, value)\n : (value as TConfig);\n}\n\nfunction createIntegrationLifecycleLogger(\n integration: FarmIntegration<any, any>,\n phase: FarmIntegrationLogPhase,\n): FarmIntegrationLifecycleLogger {\n const write = (\n level: FarmIntegrationLifecycleLogLevel,\n message: string,\n meta?: Record<string, unknown>,\n ) => {\n if (!integration.log) {\n return;\n }\n\n void Promise.resolve(\n integration.log({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase,\n level,\n message,\n meta,\n context: new Map(),\n }),\n ).catch(() => {});\n };\n\n return {\n info(message, meta) {\n write(\"info\", message, meta);\n },\n warn(message, meta) {\n write(\"warn\", message, meta);\n },\n error(message, meta) {\n write(\"error\", message, meta);\n },\n };\n}\n\nconst INTEGRATION_DATA_HEADER = \"x-farm-integration-data\";\nconst INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;\nconst BLOCKED_INTEGRATION_DATA_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nfunction isFarmIntegrationData(value: unknown): value is FarmIntegrationData {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isPlainIntegrationDataObject(value: unknown): value is Record<string, unknown> {\n if (!isFarmIntegrationData(value)) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction sanitizeIntegrationDataValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => sanitizeIntegrationDataValue(item));\n }\n\n if (!isPlainIntegrationDataObject(value)) {\n return value;\n }\n\n const sanitized: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {\n continue;\n }\n\n sanitized[key] = sanitizeIntegrationDataValue(item);\n }\n\n return sanitized;\n}\n\nfunction normalizeIntegrationData(value: FarmIntegrationData | undefined): FarmIntegrationData {\n if (!isFarmIntegrationData(value)) {\n return {};\n }\n\n const sanitized = sanitizeIntegrationDataValue(value);\n return isFarmIntegrationData(sanitized) ? sanitized : {};\n}\n\nfunction getIntegrationDataHeaderByteLength(value: string): number {\n return new TextEncoder().encode(value).byteLength;\n}\n\nfunction parseIntegrationDataHeader(request: Request): FarmIntegrationData {\n const raw = request.headers.get(INTEGRATION_DATA_HEADER);\n if (!raw) {\n return {};\n }\n\n if (getIntegrationDataHeaderByteLength(raw) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {\n return {};\n }\n\n try {\n const value = JSON.parse(raw);\n return normalizeIntegrationData(value);\n } catch {\n return {};\n }\n}\n\nfunction resolveIntegrationData(request: Request, data?: FarmIntegrationData): FarmIntegrationData {\n return {\n ...parseIntegrationDataHeader(request),\n ...normalizeIntegrationData(data),\n };\n}\n\nfunction createIntegrationPlugin(integrationKey: string, integration: FarmIntegration): FarmPlugin {\n const routes = normalizeIntegrationRoutes(integration.routes || []);\n const middleware = [...(integration.middleware || [])];\n const cleanupCallbacks: IntegrationLifecycleCleanup[] = [];\n let integrationConfigPromise: Promise<unknown> | undefined;\n\n const runCleanup = async () => {\n const callbacks = cleanupCallbacks.splice(0).reverse();\n for (const callback of callbacks) {\n await callback();\n }\n };\n\n const createLifecycleContext = async (\n context: FarmPluginContext,\n phase: FarmIntegrationLogPhase,\n options: { reason?: string } = {},\n ): Promise<FarmIntegrationLifecycleContext> => {\n const args = createIntegrationRouteArgs({\n integration,\n config: context.config,\n });\n const configContext: FarmIntegrationConfigContext = {\n key: integrationKey,\n integration,\n appConfig: context.config,\n config: context.config,\n args,\n env: getIntegrationRuntimeEnv(),\n isDev: context.isDev,\n isProd: context.isProd,\n };\n integrationConfigPromise ??= resolveIntegrationConfig(integration, configContext);\n\n return {\n ...configContext,\n integrationConfig: await integrationConfigPromise,\n log: createIntegrationLifecycleLogger(integration, phase),\n reason: options.reason,\n async cleanup(callback) {\n if (callback) {\n cleanupCallbacks.push(callback);\n return;\n }\n\n await runCleanup();\n },\n };\n };\n\n const plugin: FarmPlugin = {\n name: `farm:integration:${integration.category}:${integration.type}`,\n enforce: \"pre\",\n\n async init(context) {\n getIntegrationRuntimeRegistry().set(integrationKey, {\n integration,\n config: context.config,\n isDev: context.isDev,\n isProd: context.isProd,\n });\n\n await createLifecycleContext(context, \"validate\");\n\n if (integration.validate) {\n await integration.validate(await createLifecycleContext(context, \"validate\"));\n }\n\n if (integration.setup) {\n await integration.setup(await createLifecycleContext(context, \"setup\"));\n }\n\n if (!integration.log) {\n return;\n }\n\n for (const route of routes) {\n await integration.log({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"registered\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n context: new Map(),\n });\n }\n\n for (const entry of middleware) {\n await integration.log({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"registered\",\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n context: new Map(),\n });\n }\n },\n\n async ready(context) {\n if (integration.ready) {\n await integration.ready(await createLifecycleContext(context, \"ready\"));\n }\n },\n\n async shutdown(payload, context) {\n try {\n if (integration.dispose) {\n await integration.dispose(\n await createLifecycleContext(context, \"dispose\", {\n reason: payload.reason,\n }),\n );\n }\n } finally {\n await runCleanup();\n }\n },\n\n async beforeRequest(req, res, context) {\n const fullUrl = `http://${req.headers.host || \"localhost\"}${req.url || \"/\"}`;\n const url = new URL(fullUrl);\n const pathname = url.pathname;\n const requestId = getRequestId(req);\n let bodyLoaded = false;\n let requestBody: Buffer | undefined;\n\n const getRequestBody = async () => {\n if (!bodyLoaded) {\n bodyLoaded = true;\n if (req.method && req.method !== \"GET\" && req.method !== \"HEAD\") {\n requestBody = await readRequestBody(req);\n }\n }\n\n return requestBody;\n };\n\n const createHandlerRequest = async () => {\n return createWebRequest(req, fullUrl, await getRequestBody());\n };\n\n for (const entry of middleware) {\n const params = resolveMatcherParams(entry.matcher, pathname);\n if (!params) {\n continue;\n }\n\n const request = await createHandlerRequest();\n const handlerContext = createIntegrationHandlerContext({\n integration,\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n request,\n rawRequest: req,\n params,\n pathname,\n requestId,\n pluginContext: context,\n });\n const startedAt = Date.now();\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:start\",\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n request,\n requestId,\n context: handlerContext.req.snapshot(),\n });\n\n try {\n const response = await entry.handler(request, handlerContext);\n if (response) {\n await sendWebResponse(res, response);\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n request,\n response,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n return;\n }\n\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n request,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n } catch (error) {\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:error\",\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n request,\n requestId,\n durationMs: Date.now() - startedAt,\n error,\n context: handlerContext.req.snapshot(),\n });\n throw error;\n }\n }\n\n for (const route of routes) {\n const params = matchesMethod(route.methods, req.method)\n ? extractPathParams(route.path, pathname)\n : null;\n if (!params) {\n continue;\n }\n\n const request = await createHandlerRequest();\n const handlerContext = createIntegrationHandlerContext({\n integration,\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n rawRequest: req,\n params,\n pathname,\n requestId,\n pluginContext: context,\n });\n const startedAt = Date.now();\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:start\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n requestId,\n context: handlerContext.req.snapshot(),\n });\n\n try {\n const validation = await validateIntegrationRouteInput(route, request, url);\n if (!validation.success) {\n await sendWebResponse(res, validation.response);\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n response: validation.response,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n return;\n }\n handlerContext.input = validation.input;\n\n for (const middlewareEntry of route.middleware || []) {\n const middlewareResponse = await middlewareEntry.handler(request, handlerContext);\n if (middlewareResponse) {\n await sendWebResponse(res, middlewareResponse);\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n response: middlewareResponse,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n return;\n }\n }\n\n const beforeResponse = await runIntegrationRouteBeforeHooks(\n route,\n request,\n handlerContext,\n );\n if (beforeResponse) {\n const response = await runIntegrationRouteAfterHooks(\n route,\n request,\n handlerContext,\n beforeResponse,\n );\n await sendWebResponse(res, response);\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n response,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n return;\n }\n\n const handlerResponse = await route.handler(request, handlerContext);\n const response = await runIntegrationRouteAfterHooks(\n route,\n request,\n handlerContext,\n handlerResponse,\n );\n await sendWebResponse(res, response);\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n response,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n return;\n } catch (error) {\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:error\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n requestId,\n durationMs: Date.now() - startedAt,\n error,\n context: handlerContext.req.snapshot(),\n });\n throw error;\n }\n }\n },\n };\n\n Object.defineProperty(plugin, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME, {\n value: integration.serverRuntime !== false,\n });\n\n return plugin;\n}\n\nfunction createIntegrationHandlerContext(input: {\n integration: FarmIntegration;\n route: FarmIntegrationHandlerContext[\"route\"];\n request: Request;\n rawRequest: FarmRequest;\n params: FarmIntegrationRouteParams;\n pathname: string;\n requestId: string;\n pluginContext: FarmPluginContext;\n}): FarmIntegrationHandlerContext {\n const req = createIntegrationRequestContextStore(\n input.rawRequest,\n input.request,\n input.pluginContext,\n );\n\n return {\n request: input.request,\n requestId: input.requestId,\n url: new URL(input.request.url),\n pathname: input.pathname,\n method: input.request.method,\n params: input.params,\n input: {},\n args: createIntegrationRouteArgs({\n integration: input.integration,\n config: input.pluginContext.config,\n }),\n data: resolveIntegrationData(input.request),\n integration: {\n category: input.integration.category,\n slot: input.integration.category,\n type: input.integration.type,\n instance: input.integration.instance,\n },\n route: input.route,\n req,\n requestContext: req,\n config: input.pluginContext.config,\n isDev: input.pluginContext.isDev,\n isProd: input.pluginContext.isProd,\n };\n}\n\ntype NormalizedIntegrationRoute = Omit<FarmIntegrationRoute, \"method\" | \"methods\"> & {\n methods: readonly string[];\n __operation?: FarmIntegrationAPIOperation<any, any, any, any, any>;\n};\n\nfunction normalizeIntegrationRoutes(\n routes: readonly FarmIntegrationRoute[],\n): NormalizedIntegrationRoute[] {\n return routes.map((route) => ({\n ...route,\n methods: normalizeIntegrationRouteMethods(route),\n input: normalizeIntegrationRouteInputSchemas(route),\n }));\n}\n\nfunction normalizeIntegrationRouteMethods(route: Pick<FarmIntegrationRoute, \"method\" | \"methods\">) {\n const input =\n route.methods && route.methods.length > 0\n ? [...route.methods]\n : route.method\n ? [route.method]\n : [\"ALL\"];\n\n return input.map((method) => String(method).toUpperCase());\n}\n\nfunction normalizeIntegrationRouteInputSchemas<TBody, TQuery>(\n route: Pick<FarmIntegrationRoute<TBody, TQuery>, \"body\" | \"query\" | \"input\">,\n): FarmIntegrationRouteInputSchemas<TBody, TQuery> | undefined {\n const input: FarmIntegrationRouteInputSchemas<TBody, TQuery> = {\n ...route.input,\n };\n\n if (route.body) {\n input.body = route.body;\n }\n\n if (route.query) {\n input.query = route.query;\n }\n\n return input.body || input.query ? input : undefined;\n}\n\ntype IntegrationRouteInputValidationResult =\n | {\n success: true;\n input: FarmIntegrationRouteInput;\n }\n | {\n success: false;\n response: Response;\n };\n\nasync function validateIntegrationRouteInput(\n route: NormalizedIntegrationRoute,\n request: Request,\n url: URL,\n): Promise<IntegrationRouteInputValidationResult> {\n const schemas = route.input;\n if (!schemas?.body && !schemas?.query) {\n return {\n success: true,\n input: {},\n };\n }\n\n const input: FarmIntegrationRouteInput = {};\n const issues: FarmIntegrationValidationIssue[] = [];\n\n if (schemas.query) {\n const queryResult = await parseIntegrationInputSchema(\n \"query\",\n schemas.query,\n createQueryInput(url.searchParams),\n );\n if (queryResult.success) {\n input.query = queryResult.data;\n } else {\n issues.push(...queryResult.issues);\n }\n }\n\n if (schemas.body) {\n const bodyInput = await readIntegrationValidationBody(\n request,\n getIntegrationRouteBodyFormat(route),\n );\n\n if (bodyInput.success) {\n const bodyResult = await parseIntegrationInputSchema(\"body\", schemas.body, bodyInput.data);\n if (bodyResult.success) {\n input.body = bodyResult.data;\n } else {\n issues.push(...bodyResult.issues);\n }\n } else {\n issues.push(bodyInput.issue);\n }\n }\n\n if (issues.length > 0) {\n return {\n success: false,\n response: createIntegrationValidationResponse(issues),\n };\n }\n\n return {\n success: true,\n input,\n };\n}\n\nasync function parseIntegrationInputSchema<TValue>(\n source: FarmIntegrationRouteInputSource,\n schema: FarmIntegrationInputSchema<TValue>,\n value: unknown,\n): Promise<\n | {\n success: true;\n data: TValue;\n }\n | {\n success: false;\n issues: FarmIntegrationValidationIssue[];\n }\n> {\n const parser = schema.safeParseAsync || schema.safeParse;\n if (parser) {\n const result = await parser.call(schema, value);\n if (result.success) {\n return {\n success: true,\n data: result.data,\n };\n }\n\n return {\n success: false,\n issues: normalizeIntegrationValidationIssues(source, result.error),\n };\n }\n\n if (schema[\"~standard\"]?.validate) {\n const result = await schema[\"~standard\"].validate(value);\n if (\"value\" in result) {\n return {\n success: true,\n data: result.value,\n };\n }\n\n return {\n success: false,\n issues: normalizeIntegrationValidationIssues(source, {\n issues: result.issues,\n }),\n };\n }\n\n if (schema.parse) {\n try {\n return {\n success: true,\n data: await schema.parse(value),\n };\n } catch (error) {\n return {\n success: false,\n issues: normalizeIntegrationValidationIssues(\n source,\n normalizeIntegrationValidationError(error),\n ),\n };\n }\n }\n\n return {\n success: false,\n issues: [\n {\n source,\n message:\n \"Input schema must expose safeParse, safeParseAsync, parse, or ~standard.validate.\",\n },\n ],\n };\n}\n\nfunction createIntegrationValidationResponse(issues: readonly FarmIntegrationValidationIssue[]) {\n return Response.json(\n {\n error: \"Integration route input validation failed\",\n issues,\n },\n {\n status: 400,\n },\n );\n}\n\nfunction normalizeIntegrationValidationIssues(\n source: FarmIntegrationRouteInputSource,\n error: FarmIntegrationValidationErrorLike,\n): FarmIntegrationValidationIssue[] {\n if (Array.isArray(error.issues) && error.issues.length > 0) {\n return error.issues.map((issue) => ({\n source,\n path: normalizeIntegrationValidationPath(issue.path),\n code: issue.code,\n message: issue.message || \"Invalid input\",\n }));\n }\n\n return [\n {\n source,\n path: [],\n message: error.message || \"Invalid input\",\n },\n ];\n}\n\nfunction normalizeIntegrationValidationPath(\n path: readonly FarmIntegrationValidationPathSegment[] | undefined,\n): (string | number)[] {\n return (path || []).map((segment) => {\n const key =\n typeof segment === \"object\" && segment !== null && \"key\" in segment ? segment.key : segment;\n return typeof key === \"symbol\" ? key.description || key.toString() : key;\n });\n}\n\nfunction normalizeIntegrationValidationError(error: unknown): FarmIntegrationValidationErrorLike {\n if (error && typeof error === \"object\") {\n return error as FarmIntegrationValidationErrorLike;\n }\n\n return {\n message: error instanceof Error ? error.message : String(error || \"Invalid input\"),\n };\n}\n\nasync function readIntegrationValidationBody(\n request: Request,\n format: FarmIntegrationAPIBodyFormat,\n): Promise<\n | {\n success: true;\n data: unknown;\n }\n | {\n success: false;\n issue: FarmIntegrationValidationIssue;\n }\n> {\n if (request.method === \"GET\" || request.method === \"HEAD\" || format === \"none\") {\n return {\n success: true,\n data: undefined,\n };\n }\n\n try {\n if (format === \"form\") {\n return {\n success: true,\n data: createFormInput(await request.clone().formData()),\n };\n }\n\n const text = await request.clone().text();\n if (text.trim().length === 0) {\n return {\n success: true,\n data: undefined,\n };\n }\n\n return {\n success: true,\n data: JSON.parse(text),\n };\n } catch (error) {\n return {\n success: false,\n issue: {\n source: \"body\",\n path: [],\n message:\n format === \"json\"\n ? \"Expected a valid JSON request body.\"\n : error instanceof Error && error.message\n ? error.message\n : \"Could not parse request body.\",\n },\n };\n }\n}\n\nfunction getIntegrationRouteBodyFormat(route: NormalizedIntegrationRoute) {\n return route.bodyFormat || route.__operation?.bodyFormat || \"json\";\n}\n\nfunction createIntegrationRouteArgs(input: {\n integration: FarmIntegration;\n config: FarmPluginContext[\"config\"];\n}): FarmIntegrationRouteArgs {\n let clientPromise: Promise<unknown | undefined> | undefined;\n let ormPromise: Promise<unknown> | undefined;\n\n const getClient = () => {\n clientPromise ??= import(\"./storage\").then(({ resolveStorageRuntimeClient }) =>\n resolveStorageRuntimeClient(input.config.storage),\n );\n return clientPromise;\n };\n\n const getOrm = () => {\n if (!input.integration.schema) {\n throw new Error(\n `Integration \"${input.integration.type}\" does not define a schema for ctx.args.db.`,\n );\n }\n\n ormPromise ??= import(\"./integration-orm\").then(({ createIntegrationOrm }) =>\n createIntegrationOrm({\n schema: input.integration.schema!,\n config: input.config,\n }),\n );\n return ormPromise;\n };\n\n return {\n db: createLazyIntegrationOrmClient(getOrm) as never,\n getDb: getOrm as never,\n storage: {\n getClient,\n getOrm: getOrm as never,\n },\n };\n}\n\nfunction createLazyIntegrationOrmClient(resolveOrm: () => Promise<unknown>) {\n const modelProxyCache = new Map<PropertyKey, unknown>();\n\n return new Proxy(\n {},\n {\n get(_target, prop) {\n if (prop === \"then\") {\n return undefined;\n }\n\n if (prop === \"transaction\" || prop === \"batch\") {\n return async (...args: unknown[]) => {\n const orm = (await resolveOrm()) as Record<PropertyKey, unknown>;\n const member = orm[prop];\n if (typeof member !== \"function\") {\n throw new Error(`Integration ORM does not expose \"${String(prop)}\".`);\n }\n return member.apply(orm, args);\n };\n }\n\n if (prop === \"$driver\") {\n return undefined;\n }\n\n if (!modelProxyCache.has(prop)) {\n modelProxyCache.set(prop, createLazyIntegrationOrmModel(resolveOrm, prop));\n }\n\n return modelProxyCache.get(prop);\n },\n },\n );\n}\n\nfunction createLazyIntegrationOrmModel(resolveOrm: () => Promise<unknown>, modelName: PropertyKey) {\n return new Proxy(\n {},\n {\n get(_target, prop) {\n if (prop === \"then\") {\n return undefined;\n }\n\n return async (...args: unknown[]) => {\n const orm = (await resolveOrm()) as Record<PropertyKey, Record<PropertyKey, unknown>>;\n const model = orm[modelName];\n const member = model?.[prop];\n if (typeof member !== \"function\") {\n throw new Error(\n `Integration ORM model \"${String(modelName)}\" does not expose \"${String(prop)}\".`,\n );\n }\n return member.apply(model, args);\n };\n },\n },\n );\n}\n\nasync function runIntegrationRouteBeforeHooks(\n route: NormalizedIntegrationRoute,\n request: Request,\n context: FarmIntegrationHandlerContext,\n): Promise<Response | undefined> {\n const hookContext = context as FarmIntegrationRouteHookContext;\n hookContext.response = undefined;\n\n for (const hook of route.before || []) {\n const response = await hook(request, hookContext);\n if (response) {\n hookContext.response = response;\n return response;\n }\n\n if (hookContext.response) {\n return hookContext.response;\n }\n }\n\n return undefined;\n}\n\nasync function runIntegrationRouteAfterHooks(\n route: NormalizedIntegrationRoute,\n request: Request,\n context: FarmIntegrationHandlerContext,\n response: Response,\n): Promise<Response> {\n const hookContext = context as FarmIntegrationRouteHookContext;\n let currentResponse = response;\n\n for (const hook of route.after || []) {\n hookContext.response = currentResponse;\n const nextResponse = await hook(request, hookContext);\n currentResponse = nextResponse || hookContext.response || currentResponse;\n }\n\n hookContext.response = currentResponse;\n return currentResponse;\n}\n\nfunction createQueryInput(searchParams: URLSearchParams): Record<string, string | string[]> {\n const input: Record<string, string | string[]> = {};\n searchParams.forEach((value, key) => {\n const existing = input[key];\n if (existing === undefined) {\n input[key] = value;\n return;\n }\n\n input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];\n });\n return input;\n}\n\nfunction createFormInput(\n formData: FormData,\n): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n const input: Record<string, FormDataEntryValue | FormDataEntryValue[]> = {};\n formData.forEach((value, key) => {\n const existing = input[key];\n if (existing === undefined) {\n input[key] = value;\n return;\n }\n\n input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];\n });\n return input;\n}\n\nexport async function dispatchIntegrationRequest(\n runtime: RegisteredIntegrationRuntime,\n request: Request,\n options: {\n currentRequest?: Request;\n data?: FarmIntegrationData;\n internal?: boolean;\n } = {},\n): Promise<Response | null> {\n const integration = runtime.integration;\n const url = new URL(request.url);\n const pathname = url.pathname;\n const requestId =\n request.headers.get(\"x-request-id\") ||\n options.currentRequest?.headers.get(\"x-request-id\") ||\n String(Date.now());\n const routes = normalizeIntegrationRoutes(integration.routes || []);\n const middleware = [...(integration.middleware || [])];\n\n for (const entry of middleware) {\n const params = resolveMatcherParams(entry.matcher, pathname);\n if (!params) {\n continue;\n }\n\n const handlerContext = createServerIntegrationHandlerContext({\n runtime,\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n request,\n params,\n pathname,\n requestId,\n currentRequest: options.currentRequest,\n data: options.data,\n internal: options.internal === true,\n });\n const startedAt = Date.now();\n\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:start\",\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n request,\n requestId,\n context: handlerContext.req.snapshot(),\n });\n\n try {\n const response = await entry.handler(request, handlerContext);\n if (response) {\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n request,\n response,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n return response;\n }\n\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n request,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n } catch (error) {\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:error\",\n route: {\n kind: \"middleware\",\n path: normalizeMatcher(entry.matcher),\n methods: [\"ALL\"],\n },\n request,\n requestId,\n durationMs: Date.now() - startedAt,\n error,\n context: handlerContext.req.snapshot(),\n });\n throw error;\n }\n }\n\n for (const route of routes) {\n const params = matchesMethod(route.methods, request.method)\n ? extractPathParams(route.path, pathname)\n : null;\n if (!params) {\n continue;\n }\n\n const handlerContext = createServerIntegrationHandlerContext({\n runtime,\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n params,\n pathname,\n requestId,\n currentRequest: options.currentRequest,\n data: options.data,\n internal: options.internal === true,\n });\n const startedAt = Date.now();\n\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:start\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n requestId,\n context: handlerContext.req.snapshot(),\n });\n\n try {\n const validation = await validateIntegrationRouteInput(route, request, url);\n if (!validation.success) {\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n response: validation.response,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n return validation.response;\n }\n handlerContext.input = validation.input;\n\n for (const middlewareEntry of route.middleware || []) {\n const middlewareResponse = await middlewareEntry.handler(request, handlerContext);\n if (middlewareResponse) {\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n response: middlewareResponse,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n return middlewareResponse;\n }\n }\n\n const beforeResponse = await runIntegrationRouteBeforeHooks(route, request, handlerContext);\n if (beforeResponse) {\n const response = await runIntegrationRouteAfterHooks(\n route,\n request,\n handlerContext,\n beforeResponse,\n );\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n response,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n return response;\n }\n\n const handlerResponse = await route.handler(request, handlerContext);\n const response = await runIntegrationRouteAfterHooks(\n route,\n request,\n handlerContext,\n handlerResponse,\n );\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:end\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n response,\n requestId,\n durationMs: Date.now() - startedAt,\n context: handlerContext.req.snapshot(),\n });\n return response;\n } catch (error) {\n await integration.log?.({\n category: integration.category,\n slot: integration.category,\n type: integration.type,\n phase: \"request:error\",\n route: {\n kind: \"route\",\n path: route.path,\n methods: route.methods,\n },\n request,\n requestId,\n durationMs: Date.now() - startedAt,\n error,\n context: handlerContext.req.snapshot(),\n });\n throw error;\n }\n }\n\n return null;\n}\n\n(globalThis as GlobalWithIntegrationRuntimeRegistry)[INTEGRATION_REQUEST_DISPATCHER_KEY] =\n dispatchIntegrationRequest;\n\nfunction createIntegrationRequestContextStore(\n rawRequest: FarmRequest,\n request: Request,\n pluginContext: FarmPluginContext,\n): FarmIntegrationRequestContextStore {\n return {\n get(key) {\n const requestValue = pluginContext.requestContext.get(request, key);\n if (requestValue !== undefined) {\n return requestValue;\n }\n\n return pluginContext.requestContext.get(rawRequest, key);\n },\n set(key, value, options) {\n pluginContext.requestContext.set(rawRequest, key, value, options);\n pluginContext.requestContext.set(request, key, value, options);\n },\n has(key) {\n return (\n pluginContext.requestContext.has(request, key) ||\n pluginContext.requestContext.has(rawRequest, key)\n );\n },\n delete(key) {\n const deletedRequest = pluginContext.requestContext.delete(request, key);\n const deletedRaw = pluginContext.requestContext.delete(rawRequest, key);\n return deletedRequest || deletedRaw;\n },\n clear() {\n pluginContext.requestContext.clear(rawRequest);\n pluginContext.requestContext.clear(request);\n },\n snapshot(options) {\n const merged = pluginContext.requestContext.getAll(rawRequest, options);\n const requestSnapshot = pluginContext.requestContext.getAll(request, options);\n for (const [key, value] of requestSnapshot) {\n merged.set(key, value);\n }\n return merged;\n },\n };\n}\n\nfunction createServerIntegrationHandlerContext(input: {\n runtime: RegisteredIntegrationRuntime;\n route: FarmIntegrationHandlerContext[\"route\"];\n request: Request;\n params: FarmIntegrationRouteParams;\n pathname: string;\n requestId: string;\n currentRequest?: Request;\n data?: FarmIntegrationData;\n internal?: boolean;\n}): FarmIntegrationHandlerContext {\n const req = createServerIntegrationRequestContextStore(input.request, input.currentRequest);\n\n if (input.internal) {\n req.set(FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY, true);\n }\n\n return {\n request: input.request,\n requestId: input.requestId,\n url: new URL(input.request.url),\n pathname: input.pathname,\n method: input.request.method,\n params: input.params,\n input: {},\n args: createIntegrationRouteArgs({\n integration: input.runtime.integration,\n config: input.runtime.config,\n }),\n data: resolveIntegrationData(input.request, input.data),\n integration: {\n category: input.runtime.integration.category,\n slot: input.runtime.integration.category,\n type: input.runtime.integration.type,\n instance: input.runtime.integration.instance,\n },\n route: input.route,\n req,\n requestContext: req,\n config: input.runtime.config,\n isDev: input.runtime.isDev,\n isProd: input.runtime.isProd,\n };\n}\n\nfunction createServerIntegrationRequestContextStore(\n request: Request,\n currentRequest?: Request,\n): FarmIntegrationRequestContextStore {\n return {\n get(key) {\n const requestValue = getRequestContext(request, key);\n if (requestValue !== undefined) {\n return requestValue;\n }\n\n if (currentRequest) {\n return getRequestContext(currentRequest, key);\n }\n\n return undefined;\n },\n set(key, value, options) {\n setRequestContext(request, key, value, options);\n if (currentRequest) {\n setRequestContext(currentRequest, key, value, options);\n }\n },\n has(key) {\n return (\n hasRequestContext(request, key) ||\n (!!currentRequest && hasRequestContext(currentRequest, key))\n );\n },\n delete(key) {\n const deletedRequest = deleteRequestContext(request, key);\n const deletedCurrent = currentRequest ? deleteRequestContext(currentRequest, key) : false;\n return deletedRequest || deletedCurrent;\n },\n clear() {\n clearRequestContext(request);\n if (currentRequest) {\n clearRequestContext(currentRequest);\n }\n },\n snapshot(options) {\n const merged = currentRequest\n ? getRequestContextSnapshot(currentRequest, options)\n : new Map<string, unknown>();\n const requestSnapshot = getRequestContextSnapshot(request, options);\n for (const [key, value] of requestSnapshot) {\n merged.set(key, value);\n }\n return merged;\n },\n };\n}\n\nfunction createWebRequest(req: FarmRequest, fullUrl: string, body?: Buffer): Request {\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value == null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(key, item);\n }\n continue;\n }\n\n headers.set(key, value);\n }\n\n return new Request(fullUrl, {\n method: req.method,\n headers,\n body: body as BodyInit | undefined,\n });\n}\n\nfunction matchesMethod(methods: readonly string[], method: string | undefined): boolean {\n if (!method) {\n return false;\n }\n\n return methods.some((item) => item.toUpperCase() === method.toUpperCase());\n}\n\nfunction matchesMatcher(\n matcher: string | readonly string[] | undefined,\n pathname: string,\n): boolean {\n return resolveMatcherParams(matcher, pathname) !== null;\n}\n\nfunction resolveMatcherParams(\n matcher: string | readonly string[] | undefined,\n pathname: string,\n): FarmIntegrationRouteParams | null {\n if (!matcher) {\n return {};\n }\n\n const list = Array.isArray(matcher) ? matcher : [matcher];\n for (const item of list) {\n if (item === \"/(.*)\" || item === \"*\") {\n return {};\n }\n if (item.endsWith(\"(.*)\")) {\n const prefix = item.slice(0, -4);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n return {};\n }\n continue;\n }\n const params = extractPathParams(item, pathname);\n if (params) {\n return params;\n }\n }\n\n return null;\n}\n\nfunction matchesPath(pattern: string, pathname: string): boolean {\n return extractPathParams(pattern, pathname) !== null;\n}\n\nfunction extractPathParams(pattern: string, pathname: string): FarmIntegrationRouteParams | null {\n const routeSegments = splitPath(pattern);\n const pathSegments = splitPath(pathname);\n const params: FarmIntegrationRouteParams = {};\n\n let routeIndex = 0;\n let pathIndex = 0;\n\n while (routeIndex < routeSegments.length && pathIndex < pathSegments.length) {\n const routeSegment = routeSegments[routeIndex];\n const pathSegment = pathSegments[pathIndex];\n\n if (isCatchAllSegment(routeSegment)) {\n params[getSegmentParamName(routeSegment)] = pathSegments\n .slice(pathIndex)\n .map((segment) => decodeURIComponent(segment));\n return params;\n }\n\n if (isDynamicSegment(routeSegment)) {\n params[getSegmentParamName(routeSegment)] = decodeURIComponent(pathSegment);\n routeIndex += 1;\n pathIndex += 1;\n continue;\n }\n\n if (routeSegment !== pathSegment) {\n return null;\n }\n\n routeIndex += 1;\n pathIndex += 1;\n }\n\n if (routeIndex === routeSegments.length && pathIndex === pathSegments.length) {\n return params;\n }\n\n if (routeIndex === routeSegments.length - 1 && isCatchAllSegment(routeSegments[routeIndex])) {\n params[getSegmentParamName(routeSegments[routeIndex])] = [];\n return params;\n }\n\n return null;\n}\n\nfunction splitPath(value: string): string[] {\n return value.split(\"/\").filter(Boolean);\n}\n\nfunction isDynamicSegment(segment: string): boolean {\n return segment.startsWith(\"[\") && segment.endsWith(\"]\");\n}\n\nfunction isCatchAllSegment(segment: string): boolean {\n return segment.startsWith(\"[...\") && segment.endsWith(\"]\");\n}\n\nfunction getSegmentParamName(segment: string): string {\n if (isCatchAllSegment(segment)) {\n return segment.slice(4, -1);\n }\n\n return segment.slice(1, -1);\n}\n\nfunction getRequestId(req: FarmRequest): string {\n const headerValue = req.headers[\"x-request-id\"];\n if (Array.isArray(headerValue)) {\n return headerValue[0] || String(Date.now());\n }\n return headerValue || String(Date.now());\n}\n\nasync function readRequestBody(req: FarmRequest): Promise<Buffer> {\n return await new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk) => {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n });\n req.on(\"end\", () => {\n resolve(Buffer.concat(chunks));\n });\n req.on(\"error\", reject);\n });\n}\n\nfunction normalizeMatcher(matcher: string | readonly string[] | undefined): string {\n if (!matcher) {\n return \"/(.*)\";\n }\n return typeof matcher === \"string\" ? matcher : matcher.join(\", \");\n}\n","export const FARM_DEPLOYMENT_ID_HEADER = \"x-farm-deployment-id\";\nexport const FARM_DEPLOYMENT_MISMATCH_HEADER = \"x-farm-deployment-mismatch\";\nexport const FARM_DEPLOYMENT_COOKIE = \"__farm_deployment\";\nexport const FARM_DEPLOYMENT_MISMATCH_CODE = \"FARM_DEPLOYMENT_MISMATCH\";\nexport const FARM_DEPLOYMENT_MISMATCH_STATUS = 409;\n\nexport interface FarmDeploymentMismatch {\n clientDeploymentId: string;\n serverDeploymentId: string;\n}\n\nexport interface FarmDeploymentResponseOptions {\n setCookie?: boolean;\n cookiePath?: string;\n secureCookie?: boolean;\n}\n\nexport class FarmDeploymentMismatchError extends Error {\n readonly name = \"FarmDeploymentMismatchError\";\n readonly code = FARM_DEPLOYMENT_MISMATCH_CODE;\n readonly retryable = false;\n\n constructor(\n readonly clientDeploymentId: string,\n readonly serverDeploymentId: string,\n ) {\n super(\"The application was updated while this page was open. Refresh before trying again.\");\n }\n}\n\nexport function normalizeFarmDeploymentId(value: unknown): string {\n if (typeof value !== \"string\" || value.trim() === \"\") {\n throw new TypeError(\"Farm deploymentId must be a non-empty string\");\n }\n\n const normalized = value.trim();\n if (normalized.length > 200 || /[\\u0000-\\u001f\\u007f]/.test(normalized)) {\n throw new TypeError(\"Farm deploymentId must be at most 200 characters without control bytes\");\n }\n\n return normalized;\n}\n\nexport function createFarmDeploymentRequestHeaders(\n deploymentId: string | undefined,\n init?: HeadersInit,\n): Headers {\n const headers = new Headers(init);\n if (deploymentId) {\n headers.set(FARM_DEPLOYMENT_ID_HEADER, deploymentId);\n }\n return headers;\n}\n\nexport function getFarmRequestDeploymentId(\n request: Pick<Request, \"headers\" | \"method\">,\n): string | undefined {\n const headerValue = request.headers.get(FARM_DEPLOYMENT_ID_HEADER)?.trim();\n if (headerValue) return headerValue;\n\n if (isSafeRequestMethod(request.method)) return undefined;\n return readCookie(request.headers.get(\"cookie\"), FARM_DEPLOYMENT_COOKIE);\n}\n\nexport function getFarmDeploymentMismatch(\n request: Pick<Request, \"headers\" | \"method\">,\n serverDeploymentId: string | undefined,\n): FarmDeploymentMismatch | null {\n if (!serverDeploymentId) return null;\n\n const clientDeploymentId = getFarmRequestDeploymentId(request);\n if (!clientDeploymentId || clientDeploymentId === serverDeploymentId) return null;\n\n return { clientDeploymentId, serverDeploymentId };\n}\n\nexport function createFarmDeploymentMismatchResponse(mismatch: FarmDeploymentMismatch): Response {\n return new Response(\n JSON.stringify({\n error: FARM_DEPLOYMENT_MISMATCH_CODE,\n message: \"The application deployment changed. Refresh before retrying this request.\",\n }),\n {\n status: FARM_DEPLOYMENT_MISMATCH_STATUS,\n headers: {\n \"Cache-Control\": \"no-store\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n [FARM_DEPLOYMENT_ID_HEADER]: mismatch.serverDeploymentId,\n [FARM_DEPLOYMENT_MISMATCH_HEADER]: \"1\",\n },\n },\n );\n}\n\nexport function withFarmDeploymentResponse(\n response: Response,\n deploymentId: string | undefined,\n options: FarmDeploymentResponseOptions = {},\n): Response {\n if (!deploymentId) return response;\n\n const headers = new Headers(response.headers);\n headers.set(FARM_DEPLOYMENT_ID_HEADER, deploymentId);\n if (options.setCookie) {\n headers.append(\n \"Set-Cookie\",\n createFarmDeploymentCookie(\n deploymentId,\n options.cookiePath ?? \"/\",\n options.secureCookie ?? false,\n ),\n );\n }\n\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nexport function getFarmResponseDeploymentId(\n response: Pick<Response, \"headers\">,\n): string | undefined {\n return response.headers.get(FARM_DEPLOYMENT_ID_HEADER)?.trim() || undefined;\n}\n\nexport function isFarmDeploymentMismatchResponse(\n response: Pick<Response, \"headers\" | \"status\">,\n clientDeploymentId: string | undefined,\n): boolean {\n const serverDeploymentId = getFarmResponseDeploymentId(response);\n if (clientDeploymentId && serverDeploymentId && clientDeploymentId !== serverDeploymentId) {\n return true;\n }\n\n return (\n response.status === FARM_DEPLOYMENT_MISMATCH_STATUS &&\n response.headers.get(FARM_DEPLOYMENT_MISMATCH_HEADER) === \"1\"\n );\n}\n\nexport function createFarmDeploymentMismatchError(\n response: Pick<Response, \"headers\">,\n clientDeploymentId: string,\n): FarmDeploymentMismatchError {\n return new FarmDeploymentMismatchError(\n clientDeploymentId,\n getFarmResponseDeploymentId(response) || \"unknown\",\n );\n}\n\nexport function createFarmDeploymentCookie(\n deploymentId: string,\n path = \"/\",\n secure = false,\n): string {\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n return [\n `${FARM_DEPLOYMENT_COOKIE}=${encodeURIComponent(deploymentId)}`,\n `Path=${normalizedPath}`,\n \"HttpOnly\",\n \"SameSite=Lax\",\n secure ? \"Secure\" : \"\",\n ]\n .filter(Boolean)\n .join(\"; \");\n}\n\nfunction readCookie(cookieHeader: string | null, name: string): string | undefined {\n if (!cookieHeader) return undefined;\n\n for (const part of cookieHeader.split(\";\")) {\n const separator = part.indexOf(\"=\");\n if (separator === -1 || part.slice(0, separator).trim() !== name) continue;\n\n const value = part.slice(separator + 1).trim();\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n }\n\n return undefined;\n}\n\nfunction isSafeRequestMethod(method: string): boolean {\n return [\"GET\", \"HEAD\", \"OPTIONS\"].includes(method.toUpperCase());\n}\n","import path from \"node:path\";\nimport type {\n FarmI18nDetectionSignal,\n FarmI18nDirection,\n FarmI18nUserConfig,\n ResolvedFarmI18nConfig,\n} from \"./types\";\n\nexport const DEFAULT_FARM_I18N_COOKIE = \"farm_locale\";\nexport const DEFAULT_FARM_I18N_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;\n\nconst DEFAULT_DETECTION: readonly FarmI18nDetectionSignal[] = [\"url\", \"cookie\", \"accept-language\"];\n\nexport function resolveFarmI18nConfig(\n input: FarmI18nUserConfig | false | undefined,\n options: { root?: string; mode?: \"development\" | \"production\" } = {},\n): ResolvedFarmI18nConfig {\n const root = options.root || process.cwd();\n const strictByDefault = options.mode === \"production\";\n\n if (!input) {\n return {\n enabled: false,\n locales: [\"en\"],\n defaultLocale: \"en\",\n messages: path.join(root, \"src/messages\"),\n routing: \"none\",\n detection: [],\n fallbackLocale: \"en\",\n strict: strictByDefault,\n cookie: {\n name: DEFAULT_FARM_I18N_COOKIE,\n maxAge: DEFAULT_FARM_I18N_COOKIE_MAX_AGE,\n path: \"/\",\n sameSite: \"lax\",\n secure: options.mode === \"production\",\n },\n direction: {},\n };\n }\n\n if (!Array.isArray(input.locales) || input.locales.length === 0) {\n throw new Error(\"i18n.locales must contain at least one locale.\");\n }\n\n const locales = input.locales.map(canonicalizeLocale);\n if (new Set(locales).size !== locales.length) {\n throw new Error(\"i18n.locales must not contain duplicate locales.\");\n }\n\n const defaultLocale = canonicalizeLocale(input.defaultLocale);\n if (!locales.includes(defaultLocale)) {\n throw new Error(`i18n.defaultLocale \"${defaultLocale}\" must be included in i18n.locales.`);\n }\n\n const fallbackLocale = canonicalizeLocale(input.fallbackLocale || defaultLocale);\n if (!locales.includes(fallbackLocale)) {\n throw new Error(`i18n.fallbackLocale \"${fallbackLocale}\" must be included in i18n.locales.`);\n }\n\n const detection = resolveDetection(input);\n const direction: Record<string, FarmI18nDirection> = {};\n for (const [rawLocale, value] of Object.entries(input.direction || {})) {\n const locale = canonicalizeLocale(rawLocale);\n if (!locales.includes(locale)) {\n throw new Error(`i18n.direction contains unknown locale \"${rawLocale}\".`);\n }\n if (value !== \"ltr\" && value !== \"rtl\") {\n throw new Error(`i18n.direction.${rawLocale} must be \"ltr\" or \"rtl\".`);\n }\n direction[locale] = value;\n }\n\n return {\n enabled: true,\n locales,\n defaultLocale,\n messages: path.resolve(root, input.messages || \"src/messages\"),\n routing: input.routing || \"prefix-except-default\",\n detection,\n fallbackLocale,\n strict: input.strict ?? strictByDefault,\n cookie: {\n name: input.cookie?.name?.trim() || DEFAULT_FARM_I18N_COOKIE,\n maxAge: normalizePositiveInteger(\n input.cookie?.maxAge,\n DEFAULT_FARM_I18N_COOKIE_MAX_AGE,\n \"i18n.cookie.maxAge\",\n ),\n path: input.cookie?.path || \"/\",\n sameSite: input.cookie?.sameSite || \"lax\",\n secure: input.cookie?.secure ?? options.mode === \"production\",\n },\n direction,\n };\n}\n\nexport function resolveFarmI18nMessagePath(\n config: Pick<ResolvedFarmI18nConfig, \"messages\">,\n locale: string,\n): string {\n return config.messages.includes(\"{locale}\")\n ? config.messages.split(\"{locale}\").join(locale)\n : path.join(config.messages, `${locale}.json`);\n}\n\nexport function canonicalizeLocale(locale: string): string {\n if (!locale || typeof locale !== \"string\") {\n throw new Error(\"Farm i18n locales must be non-empty strings.\");\n }\n\n try {\n return Intl.getCanonicalLocales(locale)[0]!;\n } catch {\n throw new Error(`Invalid i18n locale \"${locale}\".`);\n }\n}\n\nfunction resolveDetection(input: FarmI18nUserConfig): readonly FarmI18nDetectionSignal[] {\n if (input.detection === false || input.localeDetection === false) {\n return [\"url\"];\n }\n\n const detection = input.detection || DEFAULT_DETECTION;\n const allowed = new Set<FarmI18nDetectionSignal>([\"url\", \"cookie\", \"accept-language\"]);\n const unique: FarmI18nDetectionSignal[] = [];\n\n for (const signal of detection) {\n if (!allowed.has(signal)) {\n throw new Error(`Unsupported i18n detection signal \"${signal}\".`);\n }\n if (!unique.includes(signal)) unique.push(signal);\n }\n\n return unique;\n}\n\nfunction normalizePositiveInteger(\n value: number | undefined,\n fallback: number,\n name: string,\n): number {\n if (value === undefined) return fallback;\n if (!Number.isInteger(value) || value < 0) {\n throw new Error(`${name} must be a positive integer.`);\n }\n return value;\n}\n","export const DEFAULT_FARM_DEVTOOLS_SHORTCUT = \"mod+shift+.\";\nexport const FARM_DEVTOOLS_PATH = \"/__farm/devtools\";\nexport const FARM_DEVTOOLS_LAUNCH_PARAM = \"__farm_devtools\";\n\nexport interface FarmDevtoolsConfig {\n /** Enable the development-only DevTools UI and runtime endpoints. */\n enabled?: boolean;\n /** Keyboard shortcut used to toggle DevTools, or false to disable the shortcut. */\n shortcut?: string | false;\n}\n\nexport type FarmDevtoolsUserConfig = boolean | FarmDevtoolsConfig;\n\nexport interface ResolvedFarmDevtoolsConfig {\n enabled: boolean;\n shortcut: string | false;\n}\n\nexport function resolveFarmDevtoolsConfig(\n config: FarmDevtoolsUserConfig | ResolvedFarmDevtoolsConfig | undefined,\n mode: \"development\" | \"production\" = \"development\",\n): ResolvedFarmDevtoolsConfig {\n if (mode !== \"development\" || config === false) {\n return { enabled: false, shortcut: false };\n }\n\n const options = config === true || config === undefined ? {} : config;\n const enabled = options.enabled ?? true;\n\n if (!enabled) {\n return { enabled: false, shortcut: false };\n }\n\n const shortcut =\n typeof options.shortcut === \"string\" && options.shortcut.trim()\n ? options.shortcut\n .toLowerCase()\n .split(\"+\")\n .map((part) => part.trim())\n .filter(Boolean)\n .join(\"+\")\n : options.shortcut === false\n ? false\n : DEFAULT_FARM_DEVTOOLS_SHORTCUT;\n\n return { enabled: true, shortcut };\n}\n","import { readFileSync, writeFileSync } from \"node:fs\";\n\nexport function writeFileIfChanged(filePath: string, content: string): boolean {\n try {\n if (readFileSync(filePath, \"utf8\") === content) {\n return false;\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n }\n\n writeFileSync(filePath, content, \"utf8\");\n return true;\n}\n","import { readFileSync, existsSync, readdirSync, mkdirSync } from \"fs\";\nimport { join, relative, dirname } from \"path\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\n\nexport interface APIRouteInfo {\n path: string;\n methods: string[];\n filePath: string;\n relativePath: string;\n}\n\nexport class APITypeGenerator {\n private appDirs: string[];\n\n constructor(appDir: string | readonly string[]) {\n this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n }\n\n /**\n * Scan all API route files and extract route information\n */\n scanAPIRoutes(): APIRouteInfo[] {\n const routes = new Map<string, APIRouteInfo>();\n\n for (const appDir of this.appDirs) {\n const apiDir = join(appDir, \"api\");\n if (!existsSync(apiDir)) continue;\n\n const discovered: APIRouteInfo[] = [];\n this.scanDirectory(apiDir, appDir, discovered);\n for (const route of discovered) {\n routes.set(route.path, route);\n }\n }\n\n return Array.from(routes.values()).sort((left, right) => left.path.localeCompare(right.path));\n }\n\n private scanDirectory(dir: string, appDir: string, routes: APIRouteInfo[], basePath = \"\") {\n const items = readdirSync(dir, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = join(dir, item.name);\n\n if (item.isDirectory()) {\n const newBasePath = basePath ? `${basePath}/${item.name}` : item.name;\n this.scanDirectory(fullPath, appDir, routes, newBasePath);\n } else if (/^route\\.(ts|tsx|js|jsx)$/.test(item.name)) {\n const routeInfo = this.extractRouteInfo(fullPath, appDir, basePath);\n if (routeInfo) {\n routes.push(routeInfo);\n }\n }\n }\n }\n\n private extractRouteInfo(\n filePath: string,\n appDir: string,\n basePath: string,\n ): APIRouteInfo | null {\n try {\n const content = readFileSync(filePath, \"utf-8\");\n const methods = this.extractExportedMethods(content);\n\n if (methods.length === 0) {\n return null;\n }\n\n const relativePath = relative(appDir, filePath);\n const apiPath = basePath ? `/api/${basePath}` : \"/api\";\n\n return {\n path: apiPath,\n methods,\n filePath,\n relativePath,\n };\n } catch (error) {\n console.warn(`Failed to read route file ${filePath}:`, error);\n return null;\n }\n }\n\n private extractExportedMethods(content: string): string[] {\n const methods: string[] = [];\n const httpMethods = [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\", \"HEAD\"];\n\n for (const method of httpMethods) {\n // Look for export const METHOD = or export { METHOD }\n const patterns = [\n new RegExp(`export\\\\s+const\\\\s+${method}\\\\s*=`, \"g\"),\n new RegExp(`export\\\\s+(?:async\\\\s+)?function\\\\s+${method}\\\\s*\\\\(`, \"g\"),\n new RegExp(`export\\\\s*{\\\\s*${method}\\\\s*}`, \"g\"),\n new RegExp(`export\\\\s*{\\\\s*${method}\\\\s*as\\\\s+\\\\w+\\\\s*}`, \"g\"),\n ];\n\n for (const pattern of patterns) {\n if (pattern.test(content)) {\n methods.push(method);\n break;\n }\n }\n }\n\n return methods;\n }\n\n /**\n * Generate TypeScript code for the API router\n */\n generateAPIRouter(routes: APIRouteInfo[], options: { outFile?: string } = {}): string {\n const imports: string[] = [];\n\n // Group routes by path to handle multiple methods\n const routeGroups = new Map<string, APIRouteInfo[]>();\n\n for (const route of routes) {\n const key = route.path;\n if (!routeGroups.has(key)) {\n routeGroups.set(key, []);\n }\n routeGroups.get(key)!.push(route);\n }\n\n // Build nested structure\n const nestedStructure: any = {};\n\n for (const [path, routeList] of routeGroups) {\n const route = routeList[0];\n const importPath = this.getRouteImportPath(route, options.outFile);\n const routeName = this.pathToRouteName(route.path);\n const cleanPath = path === \"/api\" ? \"\" : path.replace(/^\\/api\\//, \"\");\n const parts = cleanPath ? cleanPath.split(\"/\") : [];\n\n // Collect all methods for this route\n const allMethods = routeList.flatMap((r) => r.methods);\n\n // Generate imports\n for (const method of allMethods) {\n const importName = `${method}_${routeName}`;\n imports.push(\n `import type { ${method} as ${importName} } from ${JSON.stringify(importPath)};`,\n );\n }\n\n if (parts.length === 0) {\n for (const method of allMethods) {\n const importName = `${method}_${routeName}`;\n const methodName = method.toLowerCase();\n nestedStructure[methodName] = `typeof ${importName}`;\n }\n } else {\n // Build nested object\n let current = nestedStructure;\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (i === parts.length - 1) {\n // Last part - add methods\n current[part] = {};\n for (const method of allMethods) {\n const importName = `${method}_${routeName}`;\n const methodName = method.toLowerCase();\n current[part][methodName] = `typeof ${importName}`;\n }\n } else {\n // Intermediate part - create nested object\n if (!current[part]) {\n current[part] = {};\n }\n current = current[part];\n }\n }\n }\n }\n\n // Convert nested structure to TypeScript code\n const typeExports = this.structureToTypeString(nestedStructure, 1);\n\n return `/**\n * Auto-generated API router types\n * This file is automatically generated - do not edit manually\n *\n * This file contains only TypeScript types for the API client.\n * Runtime imports are used only at the type level.\n */\n\n${imports.join(\"\\n\")}\n\n// Type-only representation of your API routes\nexport type APIRouter = {\n${typeExports}\n};\n`;\n }\n\n private getRouteImportPath(route: APIRouteInfo, outFile?: string): string {\n if (!outFile) {\n return `../app/${route.relativePath.replace(/\\\\/g, \"/\").replace(/\\.(ts|tsx|js|jsx)$/, \"\")}`;\n }\n\n const relativeImport = relative(dirname(outFile), route.filePath)\n .replace(/\\\\/g, \"/\")\n .replace(/\\.(ts|tsx|js|jsx)$/, \"\");\n return relativeImport.startsWith(\".\") ? relativeImport : `./${relativeImport}`;\n }\n\n private pathToRouteName(path: string): string {\n return (path === \"/api\" ? \"root\" : path.replace(/^\\/api\\//, \"\"))\n .replace(/\\//g, \"_\")\n .replace(/[^a-zA-Z0-9_]/g, \"\");\n }\n\n private structureToTypeString(obj: any, indent: number): string {\n const spaces = \" \".repeat(indent);\n const lines: string[] = [];\n\n for (const [key, value] of Object.entries(obj)) {\n const propertyKey = this.toTypePropertyKey(key);\n\n if (typeof value === \"string\") {\n // It's a type reference\n lines.push(`${spaces}${propertyKey}: ${value};`);\n } else if (typeof value === \"object\") {\n // It's a nested object\n lines.push(`${spaces}${propertyKey}: {`);\n lines.push(this.structureToTypeString(value, indent + 1));\n lines.push(`${spaces}};`);\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n private toTypePropertyKey(key: string): string {\n return /^[$A-Z_][0-9A-Z_$]*$/i.test(key) ? key : JSON.stringify(key);\n }\n\n private getBaseExportName(path: string): string {\n const cleanPath = path.replace(/^\\/api\\//, \"\");\n\n if (cleanPath === \"\") {\n return \"api\";\n }\n\n // Convert path to nested structure\n // /api/auth/login -> ['auth', 'login']\n return cleanPath;\n }\n\n private getExportName(path: string, method: string): string {\n const cleanPath = path.replace(/^\\/api\\//, \"\");\n\n if (cleanPath === \"\") {\n return method.toLowerCase();\n }\n\n const parts = cleanPath.split(\"/\");\n if (parts.length === 1) {\n // For single-level paths like /api/hello, just use the path name\n return parts[0];\n }\n\n // For nested paths like /api/auth/login, create nested structure\n // This matches the expected API client usage: api.auth.login()\n return parts.join(\".\");\n }\n\n /**\n * Generate the API index file\n */\n generateAPIIndex(outputPath: string): void {\n const routes = this.scanAPIRoutes();\n const content = this.generateAPIRouter(routes);\n\n mkdirSync(dirname(outputPath), { recursive: true });\n writeFileIfChanged(outputPath, content);\n console.log(`✅ Generated API types for ${routes.length} routes`);\n }\n}\n","import type {\n FarmImageFormat,\n FarmImageLocalPattern,\n FarmImageRemotePattern,\n ResolvedFarmImageConfig,\n} from \"./image-config\";\n\nexport interface FarmImageTransformInput {\n source: Uint8Array;\n sourceUrl: URL;\n sourceType: string;\n width: number;\n quality: number;\n accept: string;\n formats: readonly FarmImageFormat[];\n signal: AbortSignal;\n}\n\nexport interface FarmImageTransformResult {\n body: Uint8Array;\n contentType: string;\n}\n\nexport type FarmImageTransformer = (\n input: FarmImageTransformInput,\n) => Promise<FarmImageTransformResult>;\n\nexport interface CreateFarmImageHandlerOptions {\n fetch?: typeof globalThis.fetch;\n transform: FarmImageTransformer;\n validateRemoteUrl?: (url: URL) => void | Promise<void>;\n onError?: (error: unknown, request: Request) => void;\n cacheEntries?: number;\n}\n\nexport type FarmImageHandler = (request: Request) => Promise<Response | null>;\n\ntype OptimizedImage = FarmImageTransformResult & {\n etag: string;\n cacheControl: string;\n expiresAt: number;\n};\n\ntype FarmImageRequestErrorCode =\n | \"BODY_TOO_LARGE\"\n | \"DISALLOWED_SOURCE\"\n | \"INVALID_METHOD\"\n | \"INVALID_PARAMETER\"\n | \"PRIVATE_SOURCE\"\n | \"TOO_MANY_REDIRECTS\"\n | \"UNSUPPORTED_IMAGE\";\n\nexport class FarmImageRequestError extends Error {\n readonly code: FarmImageRequestErrorCode;\n readonly status: number;\n\n constructor(code: FarmImageRequestErrorCode, status: number, message: string) {\n super(message);\n this.name = \"FarmImageRequestError\";\n this.code = code;\n this.status = status;\n }\n}\n\nexport function createFarmImageHandler(\n config: ResolvedFarmImageConfig,\n options: CreateFarmImageHandlerOptions,\n): FarmImageHandler {\n const fetcher = options.fetch ?? globalThis.fetch;\n const cache = new FarmImageMemoryCache(options.cacheEntries ?? 100);\n const allowedWidths = new Set([...config.deviceSizes, ...config.imageSizes]);\n const allowedQualities = new Set(config.qualities);\n\n return async function handleFarmImage(request): Promise<Response | null> {\n const requestUrl = new URL(request.url);\n if (requestUrl.pathname !== config.path) return null;\n\n try {\n if (config.provider === \"none\") {\n throw new FarmImageRequestError(\n \"DISALLOWED_SOURCE\",\n 404,\n \"The Farm image optimizer is disabled\",\n );\n }\n if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n throw new FarmImageRequestError(\n \"INVALID_METHOD\",\n 405,\n \"The Farm image optimizer only accepts GET and HEAD\",\n );\n }\n\n const sourceUrl = await resolveImageSourceUrl(requestUrl, config, options.validateRemoteUrl);\n const width = parseAllowedInteger(requestUrl.searchParams.get(\"w\"), allowedWidths, \"width\");\n const quality = parseAllowedInteger(\n requestUrl.searchParams.get(\"q\"),\n allowedQualities,\n \"quality\",\n );\n const accept = request.headers.get(\"accept\") ?? \"\";\n const cacheKey = `${sourceUrl.href}\\n${width}\\n${quality}\\n${accept}`;\n let optimized = cache.get(cacheKey);\n\n if (!optimized) {\n const fetchedSource = await fetchImageSource(\n sourceUrl,\n requestUrl.origin,\n config,\n fetcher,\n options.validateRemoteUrl,\n request.signal,\n );\n const source = await readResponseWithLimit(\n fetchedSource.response,\n config.maximumResponseBody,\n );\n const sourceType = detectImageContentType(source);\n validateSourceType(sourceType, config);\n throwIfAborted(request.signal);\n\n const result = await options.transform({\n source,\n sourceUrl: fetchedSource.url,\n sourceType,\n width,\n quality,\n accept,\n formats: config.formats,\n signal: request.signal,\n });\n throwIfAborted(request.signal);\n validateTransformedResult(result, config);\n\n optimized = {\n ...result,\n etag: createImageEtag(result.body),\n cacheControl: `public, max-age=${config.minimumCacheTTL}, stale-while-revalidate=${Math.max(\n config.minimumCacheTTL,\n 60,\n )}`,\n expiresAt: Date.now() + config.minimumCacheTTL * 1_000,\n };\n cache.set(cacheKey, optimized);\n }\n\n return createOptimizedImageResponse(request, optimized, config);\n } catch (error) {\n if (!(error instanceof FarmImageRequestError) && !isAbortError(error)) {\n options.onError?.(error, request);\n }\n return createFarmImageErrorResponse(error);\n }\n };\n}\n\nexport function createCloudflareImageTransformer(\n fetcher: typeof globalThis.fetch = globalThis.fetch,\n): FarmImageTransformer {\n return async ({ sourceUrl, width, quality, accept, formats, signal }) => {\n const format = selectOutputFormat(accept, formats);\n const response = await fetcher(sourceUrl, {\n signal,\n headers: { accept: \"image/*\" },\n cf: {\n image: {\n fit: \"scale-down\",\n width,\n quality,\n ...(format ? { format: format === \"image/avif\" ? \"avif\" : \"webp\" } : {}),\n },\n },\n } as RequestInit);\n\n if (!response.ok) {\n throw new FarmImageRequestError(\n \"UNSUPPORTED_IMAGE\",\n response.status === 404 ? 404 : 502,\n \"Cloudflare could not transform the source image\",\n );\n }\n\n const body = new Uint8Array(await response.arrayBuffer());\n return {\n body,\n contentType:\n normalizeImageContentType(response.headers.get(\"content-type\")) ||\n detectImageContentType(body),\n };\n };\n}\n\nexport function selectOutputFormat(\n accept: string,\n formats: readonly FarmImageFormat[],\n): FarmImageFormat | undefined {\n const normalizedAccept = accept.toLowerCase();\n return formats.find((format) => normalizedAccept.includes(format));\n}\n\nexport function isPrivateImageAddress(address: string): boolean {\n const value = address.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n if (value === \"::\" || value === \"::1\") return true;\n if (/^(?:fc|fd)[0-9a-f]{2}:/.test(value) || /^fe[89ab][0-9a-f]:/.test(value)) return true;\n if (value.startsWith(\"::ffff:\")) return isPrivateImageAddress(value.slice(7));\n\n const parts = value.split(\".\");\n if (parts.length !== 4 || parts.some((part) => !/^\\d{1,3}$/.test(part))) return false;\n const octets = parts.map(Number);\n if (octets.some((part) => part > 255)) return false;\n\n const [a, b] = octets;\n return (\n a === 0 ||\n a === 10 ||\n a === 127 ||\n (a === 100 && b >= 64 && b <= 127) ||\n (a === 169 && b === 254) ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && (b === 0 || b === 168)) ||\n (a === 198 && (b === 18 || b === 19)) ||\n a >= 224\n );\n}\n\nfunction parseAllowedInteger(\n raw: string | null,\n allowed: ReadonlySet<number>,\n name: string,\n): number {\n if (!raw || !/^\\d+$/.test(raw)) {\n throw new FarmImageRequestError(\n \"INVALID_PARAMETER\",\n 400,\n `Image ${name} must be an allowed integer`,\n );\n }\n const value = Number(raw);\n if (!allowed.has(value)) {\n throw new FarmImageRequestError(\"INVALID_PARAMETER\", 400, `Image ${name} is not configured`);\n }\n return value;\n}\n\nasync function resolveImageSourceUrl(\n requestUrl: URL,\n config: ResolvedFarmImageConfig,\n validateRemoteUrl: CreateFarmImageHandlerOptions[\"validateRemoteUrl\"],\n): Promise<URL> {\n const raw = requestUrl.searchParams.get(\"url\");\n if (!raw || raw.length > 4096 || raw.startsWith(\"//\")) {\n throw new FarmImageRequestError(\"INVALID_PARAMETER\", 400, \"Invalid image source URL\");\n }\n\n let sourceUrl: URL;\n try {\n sourceUrl = raw.startsWith(\"/\") ? new URL(raw, requestUrl.origin) : new URL(raw);\n } catch {\n throw new FarmImageRequestError(\"INVALID_PARAMETER\", 400, \"Invalid image source URL\");\n }\n\n await validateImageSourceUrl(sourceUrl, requestUrl.origin, config, validateRemoteUrl);\n return sourceUrl;\n}\n\nasync function validateImageSourceUrl(\n sourceUrl: URL,\n requestOrigin: string,\n config: ResolvedFarmImageConfig,\n validateRemoteUrl: CreateFarmImageHandlerOptions[\"validateRemoteUrl\"],\n): Promise<void> {\n if (sourceUrl.protocol !== \"http:\" && sourceUrl.protocol !== \"https:\") {\n throw new FarmImageRequestError(\"DISALLOWED_SOURCE\", 400, \"Unsupported image protocol\");\n }\n if (sourceUrl.username || sourceUrl.password || sourceUrl.hash) {\n throw new FarmImageRequestError(\"DISALLOWED_SOURCE\", 400, \"Unsafe image source URL\");\n }\n\n if (sourceUrl.origin === requestOrigin) {\n if (\n sourceUrl.pathname === config.path ||\n !matchesLocalPatterns(sourceUrl, config.localPatterns)\n ) {\n throw new FarmImageRequestError(\n \"DISALLOWED_SOURCE\",\n 400,\n \"Local image source is not allowed\",\n );\n }\n return;\n }\n\n if (!matchesRemoteSource(sourceUrl, config)) {\n throw new FarmImageRequestError(\"DISALLOWED_SOURCE\", 400, \"Remote image source is not allowed\");\n }\n if (!config.dangerouslyAllowLocalIP && isPrivateImageAddress(sourceUrl.hostname)) {\n throw new FarmImageRequestError(\"PRIVATE_SOURCE\", 400, \"Private image source is not allowed\");\n }\n if (!config.dangerouslyAllowLocalIP) {\n await validateRemoteUrl?.(sourceUrl);\n }\n}\n\nasync function fetchImageSource(\n initialUrl: URL,\n requestOrigin: string,\n config: ResolvedFarmImageConfig,\n fetcher: typeof globalThis.fetch,\n validateRemoteUrl: CreateFarmImageHandlerOptions[\"validateRemoteUrl\"],\n signal: AbortSignal,\n): Promise<{ response: Response; url: URL }> {\n let currentUrl = initialUrl;\n\n for (let redirectCount = 0; ; redirectCount += 1) {\n throwIfAborted(signal);\n const response = await fetcher(currentUrl, {\n method: \"GET\",\n redirect: \"manual\",\n signal,\n headers: {\n accept: \"image/avif,image/webp,image/*,*/*;q=0.8\",\n \"user-agent\": \"Farm.js Image Optimizer\",\n },\n });\n\n if (![301, 302, 303, 307, 308].includes(response.status)) {\n if (!response.ok) {\n throw new FarmImageRequestError(\n \"UNSUPPORTED_IMAGE\",\n response.status === 404 ? 404 : 502,\n \"Could not fetch source image\",\n );\n }\n return { response, url: currentUrl };\n }\n\n if (redirectCount >= config.maximumRedirects) {\n throw new FarmImageRequestError(\n \"TOO_MANY_REDIRECTS\",\n 400,\n \"Source image exceeded the redirect limit\",\n );\n }\n const location = response.headers.get(\"location\");\n if (!location) {\n throw new FarmImageRequestError(\"UNSUPPORTED_IMAGE\", 502, \"Invalid image redirect\");\n }\n currentUrl = new URL(location, currentUrl);\n await validateImageSourceUrl(currentUrl, requestOrigin, config, validateRemoteUrl);\n }\n}\n\nasync function readResponseWithLimit(response: Response, limit: number): Promise<Uint8Array> {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength && Number(contentLength) > limit) {\n throw new FarmImageRequestError(\"BODY_TOO_LARGE\", 413, \"Source image is too large\");\n }\n\n if (!response.body) return new Uint8Array();\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let byteLength = 0;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n byteLength += value.byteLength;\n if (byteLength > limit) {\n await reader.cancel();\n throw new FarmImageRequestError(\"BODY_TOO_LARGE\", 413, \"Source image is too large\");\n }\n chunks.push(value);\n }\n\n const result = new Uint8Array(byteLength);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return result;\n}\n\nfunction detectImageContentType(bytes: Uint8Array): string {\n if (\n bytes.length >= 8 &&\n bytes[0] === 0x89 &&\n bytes[1] === 0x50 &&\n bytes[2] === 0x4e &&\n bytes[3] === 0x47\n ) {\n return \"image/png\";\n }\n if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {\n return \"image/jpeg\";\n }\n if (bytes.length >= 6) {\n const signature = new TextDecoder().decode(bytes.slice(0, 6));\n if (signature === \"GIF87a\" || signature === \"GIF89a\") return \"image/gif\";\n }\n if (bytes.length >= 12) {\n const riff = new TextDecoder().decode(bytes.slice(0, 4));\n const webp = new TextDecoder().decode(bytes.slice(8, 12));\n if (riff === \"RIFF\" && webp === \"WEBP\") return \"image/webp\";\n const box = new TextDecoder().decode(bytes.slice(4, 12));\n if (box.startsWith(\"ftypavif\") || box.startsWith(\"ftypavis\")) return \"image/avif\";\n }\n\n const prefix = new TextDecoder().decode(bytes.slice(0, 512)).trimStart().toLowerCase();\n if (prefix.startsWith(\"<svg\") || (prefix.startsWith(\"<?xml\") && prefix.includes(\"<svg\"))) {\n return \"image/svg+xml\";\n }\n return \"\";\n}\n\nfunction validateSourceType(type: string, config: ResolvedFarmImageConfig): void {\n if (!type || (type === \"image/svg+xml\" && !config.dangerouslyAllowSVG)) {\n throw new FarmImageRequestError(\"UNSUPPORTED_IMAGE\", 415, \"Unsupported source image\");\n }\n}\n\nfunction validateTransformedResult(\n result: FarmImageTransformResult,\n config: ResolvedFarmImageConfig,\n): void {\n if (!(result.body instanceof Uint8Array) || result.body.byteLength === 0) {\n throw new Error(\"The image transformer returned an empty response\");\n }\n if (result.body.byteLength > config.maximumResponseBody) {\n throw new FarmImageRequestError(\"BODY_TOO_LARGE\", 413, \"Optimized image is too large\");\n }\n const contentType = normalizeImageContentType(result.contentType);\n if (!contentType || (contentType === \"image/svg+xml\" && !config.dangerouslyAllowSVG)) {\n throw new Error(\"The image transformer returned an unsupported content type\");\n }\n result.contentType = contentType;\n}\n\nfunction normalizeImageContentType(value: string | null): string {\n const type = value?.split(\";\", 1)[0].trim().toLowerCase() ?? \"\";\n return type.startsWith(\"image/\") ? type : \"\";\n}\n\nfunction matchesRemoteSource(url: URL, config: ResolvedFarmImageConfig): boolean {\n if (config.domains.includes(url.hostname.toLowerCase())) return true;\n return config.remotePatterns.some((pattern) => matchesRemotePattern(url, pattern));\n}\n\nfunction matchesRemotePattern(url: URL, pattern: FarmImageRemotePattern): boolean {\n return (\n (!pattern.protocol || url.protocol === `${pattern.protocol}:`) &&\n matchesHostname(url.hostname, pattern.hostname) &&\n (pattern.port === undefined || url.port === pattern.port) &&\n matchesGlob(url.pathname, pattern.pathname ?? \"/**\") &&\n (pattern.search === undefined || url.search === pattern.search)\n );\n}\n\nfunction matchesLocalPatterns(url: URL, patterns: readonly FarmImageLocalPattern[]): boolean {\n return patterns.some(\n (pattern) =>\n matchesGlob(url.pathname, pattern.pathname) &&\n (pattern.search === undefined || url.search === pattern.search),\n );\n}\n\nfunction matchesHostname(hostname: string, pattern: string): boolean {\n const normalizedHostname = hostname.toLowerCase();\n const normalizedPattern = pattern.toLowerCase();\n if (normalizedPattern.startsWith(\"**.\")) {\n const suffix = normalizedPattern.slice(3);\n return normalizedHostname === suffix || normalizedHostname.endsWith(`.${suffix}`);\n }\n if (normalizedPattern.startsWith(\"*.\")) {\n const suffix = normalizedPattern.slice(2);\n const prefix = normalizedHostname.slice(0, -(suffix.length + 1));\n return normalizedHostname.endsWith(`.${suffix}`) && !!prefix && !prefix.includes(\".\");\n }\n return normalizedHostname === normalizedPattern;\n}\n\nfunction matchesGlob(value: string, pattern: string): boolean {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const source = escaped.replace(/\\*\\*/g, \"\\0\").replace(/\\*/g, \"[^/]*\").replace(/\\0/g, \".*\");\n return new RegExp(`^${source}$`).test(value);\n}\n\nfunction createOptimizedImageResponse(\n request: Request,\n image: OptimizedImage,\n config: ResolvedFarmImageConfig,\n): Response {\n const headers = new Headers({\n \"cache-control\": image.cacheControl,\n \"content-type\": image.contentType,\n \"content-length\": String(image.body.byteLength),\n \"content-disposition\": \"inline\",\n etag: image.etag,\n vary: \"Accept\",\n \"x-content-type-options\": \"nosniff\",\n });\n if (image.contentType === \"image/svg+xml\" && config.dangerouslyAllowSVG) {\n headers.set(\"content-security-policy\", \"default-src 'none'; sandbox\");\n }\n if (request.headers.get(\"if-none-match\") === image.etag) {\n headers.delete(\"content-length\");\n return new Response(null, { status: 304, headers });\n }\n const body =\n request.method === \"HEAD\"\n ? null\n : image.body.buffer.slice(\n image.body.byteOffset,\n image.body.byteOffset + image.body.byteLength,\n );\n return new Response(body as ArrayBuffer | null, { status: 200, headers });\n}\n\nfunction createFarmImageErrorResponse(error: unknown): Response {\n const status =\n error instanceof FarmImageRequestError ? error.status : isAbortError(error) ? 499 : 500;\n const headers = new Headers({\n \"cache-control\": \"no-store\",\n \"content-type\": \"text/plain; charset=utf-8\",\n \"x-content-type-options\": \"nosniff\",\n });\n if (status === 405) headers.set(\"allow\", \"GET, HEAD\");\n\n const message =\n status === 400\n ? \"Invalid image request\"\n : status === 404\n ? \"Image not found\"\n : status === 405\n ? \"Method not allowed\"\n : status === 413\n ? \"Image is too large\"\n : status === 415\n ? \"Unsupported image\"\n : status === 499\n ? \"Image request cancelled\"\n : \"Image optimization failed\";\n return new Response(message, { status, headers });\n}\n\nfunction createImageEtag(bytes: Uint8Array): string {\n let hash = 0x811c9dc5;\n for (const byte of bytes) {\n hash ^= byte;\n hash = Math.imul(hash, 0x01000193);\n }\n return `W/\"farm-${bytes.byteLength.toString(16)}-${(hash >>> 0).toString(16)}\"`;\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n throw signal.reason instanceof Error\n ? signal.reason\n : new DOMException(\"The image request was aborted\", \"AbortError\");\n }\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof Error && error.name === \"AbortError\";\n}\n\nclass FarmImageMemoryCache {\n private readonly entries = new Map<string, OptimizedImage>();\n\n constructor(private readonly capacity: number) {}\n\n get(key: string): OptimizedImage | undefined {\n const value = this.entries.get(key);\n if (!value) return undefined;\n if (value.expiresAt <= Date.now()) {\n this.entries.delete(key);\n return undefined;\n }\n this.entries.delete(key);\n this.entries.set(key, value);\n return value;\n }\n\n set(key: string, value: OptimizedImage): void {\n if (this.capacity <= 0) return;\n this.entries.delete(key);\n this.entries.set(key, value);\n while (this.entries.size > this.capacity) {\n const oldestKey = this.entries.keys().next().value as string | undefined;\n if (oldestKey === undefined) break;\n this.entries.delete(oldestKey);\n }\n }\n}\n","import { execFileSync } from \"node:child_process\";\nimport { existsSync, readFileSync, readdirSync, realpathSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nexport const FARM_DOCS_LAST_MODIFIED_MANIFEST = \".farm-docs-last-modified.json\";\n\nexport interface FarmDocsLastModifiedManifest {\n version: 1;\n pages: Record<string, string>;\n}\n\nexport interface CreateFarmDocsLastModifiedManifestOptions {\n fallback?: \"mtime\" | \"now\";\n now?: Date;\n}\n\nconst COMMIT_MARKER = \"__FARM_DOCS_COMMIT__\";\nconst DOCS_FILE_EXTENSIONS = new Set([\".md\", \".mdx\"]);\nconst manifestCache = new Map<\n string,\n {\n signature: string;\n manifest: FarmDocsLastModifiedManifest;\n }\n>();\n\nfunction normalizeRelativePath(value: string): string {\n return value.replace(/\\\\/g, \"/\").replace(/^\\.\\/+/, \"\");\n}\n\nfunction resolveExistingPath(filePath: string): string {\n try {\n return realpathSync(filePath);\n } catch {\n return path.resolve(filePath);\n }\n}\n\nfunction isDocsSourceFile(filePath: string): boolean {\n return DOCS_FILE_EXTENSIONS.has(path.extname(filePath).toLowerCase());\n}\n\nfunction discoverDocsSourceFiles(contentDir: string): string[] {\n const files: string[] = [];\n\n const visit = (dir: string) => {\n for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>\n a.name.localeCompare(b.name),\n )) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n\n const absolutePath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n visit(absolutePath);\n } else if (entry.isFile() && isDocsSourceFile(absolutePath)) {\n files.push(absolutePath);\n }\n }\n };\n\n if (existsSync(contentDir)) visit(contentDir);\n return files;\n}\n\nfunction getGitLastModifiedDates(contentDir: string): Record<string, string> {\n try {\n const gitRoot = execFileSync(\"git\", [\"-C\", contentDir, \"rev-parse\", \"--show-toplevel\"], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n }).trim();\n if (!gitRoot) return {};\n\n const contentPathspec = normalizeRelativePath(path.relative(gitRoot, contentDir)) || \".\";\n const contentPrefix = contentPathspec === \".\" ? \"\" : `${contentPathspec}/`;\n const history = execFileSync(\n \"git\",\n [\n \"-C\",\n gitRoot,\n \"-c\",\n \"core.quotePath=false\",\n \"log\",\n `--format=${COMMIT_MARKER}%cI`,\n \"--name-only\",\n \"--\",\n contentPathspec,\n ],\n {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n maxBuffer: 32 * 1024 * 1024,\n },\n );\n\n const pages: Record<string, string> = {};\n let commitDate: string | undefined;\n\n for (const rawLine of history.split(/\\r?\\n/)) {\n const line = normalizeRelativePath(rawLine.trim());\n if (!line) continue;\n\n if (line.startsWith(COMMIT_MARKER)) {\n commitDate = line.slice(COMMIT_MARKER.length);\n continue;\n }\n if (!commitDate || (contentPrefix && !line.startsWith(contentPrefix))) continue;\n\n const relativePath = contentPrefix ? line.slice(contentPrefix.length) : line;\n if (isDocsSourceFile(relativePath) && !pages[relativePath]) {\n pages[relativePath] = commitDate;\n }\n }\n\n return pages;\n } catch {\n return {};\n }\n}\n\nfunction readManifest(contentDir: string): FarmDocsLastModifiedManifest | null {\n const manifestPath = path.join(contentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST);\n if (!existsSync(manifestPath)) return null;\n\n try {\n const parsed = JSON.parse(readFileSync(manifestPath, \"utf8\")) as Partial<\n FarmDocsLastModifiedManifest\n >;\n if (parsed.version !== 1 || !parsed.pages || typeof parsed.pages !== \"object\") return null;\n\n const pages = Object.fromEntries(\n Object.entries(parsed.pages).filter(\n (entry): entry is [string, string] =>\n typeof entry[1] === \"string\" && entry[1].length > 0,\n ),\n );\n return { version: 1, pages };\n } catch {\n return null;\n }\n}\n\nexport function createFarmDocsLastModifiedManifest(\n contentDir: string,\n options: CreateFarmDocsLastModifiedManifestOptions = {},\n): FarmDocsLastModifiedManifest {\n const resolvedContentDir = resolveExistingPath(contentDir);\n const gitDates = getGitLastModifiedDates(resolvedContentDir);\n const fallbackDate = (options.now ?? new Date()).toISOString();\n const pages: Record<string, string> = {};\n\n for (const sourcePath of discoverDocsSourceFiles(resolvedContentDir)) {\n const relativePath = normalizeRelativePath(path.relative(resolvedContentDir, sourcePath));\n pages[relativePath] =\n gitDates[relativePath] ||\n (options.fallback === \"now\" ? fallbackDate : statSync(sourcePath).mtime.toISOString());\n }\n\n return { version: 1, pages };\n}\n\nfunction getLastModifiedManifest(contentDir: string): FarmDocsLastModifiedManifest {\n const resolvedContentDir = resolveExistingPath(contentDir);\n const manifestPath = path.join(resolvedContentDir, FARM_DOCS_LAST_MODIFIED_MANIFEST);\n const manifestStat = existsSync(manifestPath) ? statSync(manifestPath) : null;\n const signature = manifestStat\n ? `file:${manifestStat.mtimeMs}:${manifestStat.size}`\n : \"generated\";\n const cached = manifestCache.get(resolvedContentDir);\n if (cached?.signature === signature) return cached.manifest;\n\n const manifest =\n readManifest(resolvedContentDir) ?? createFarmDocsLastModifiedManifest(resolvedContentDir);\n manifestCache.set(resolvedContentDir, { signature, manifest });\n return manifest;\n}\n\nexport function resolveFarmDocsPageLastModified(\n contentDir: string,\n sourcePath: string,\n frontmatter: Record<string, string>,\n): string {\n const configured =\n frontmatter.lastModified ||\n frontmatter.lastmod ||\n frontmatter.lastUpdated ||\n frontmatter.updatedAt;\n if (configured) return configured;\n\n const resolvedContentDir = resolveExistingPath(contentDir);\n const resolvedSourcePath = resolveExistingPath(sourcePath);\n const relativePath = normalizeRelativePath(path.relative(resolvedContentDir, resolvedSourcePath));\n const isInsideContentDir =\n relativePath !== \"..\" && !relativePath.startsWith(\"../\") && !path.isAbsolute(relativePath);\n\n if (isInsideContentDir) {\n const generated = getLastModifiedManifest(resolvedContentDir).pages[relativePath];\n if (generated) return generated;\n }\n\n return statSync(resolvedSourcePath).mtime.toISOString();\n}\n","export const farmDocsPixelBorderCss = String.raw`\n/* Farm docs pixel-border bridge.\n * This follows the local @farming-labs/docs pixel-border theme while covering\n * the frameworkless HTML emitted by the Farm docs runtime.\n */\n\n:root {\n --color-fd-background: #000;\n --color-fd-foreground: oklch(0.985 0.001 106.423);\n --color-fd-card: hsl(0 0% 4%);\n --color-fd-card-foreground: oklch(0.985 0.001 106.423);\n --color-fd-popover: hsl(0 0% 4%);\n --color-fd-popover-foreground: oklch(0.985 0.001 106.423);\n --color-fd-primary: oklch(0.985 0.001 106.423);\n --color-fd-primary-foreground: oklch(0.216 0.006 56.043);\n --color-fd-secondary: hsl(0 0% 8%);\n --color-fd-secondary-foreground: oklch(0.985 0.001 106.423);\n --color-fd-muted: hsl(0 0% 10%);\n --color-fd-muted-foreground: hsl(0 0% 55%);\n --color-fd-accent: hsl(0 0% 10%);\n --color-fd-accent-foreground: oklch(0.985 0.001 106.423);\n --color-fd-border: hsl(0 0% 15%);\n --color-fd-ring: hsl(0 0% 30%);\n --fd-pixel-modal-border: color-mix(\n in srgb,\n var(--color-fd-foreground) 10%,\n transparent\n );\n --fd-pixel-modal-shadow: color-mix(\n in srgb,\n var(--color-fd-foreground) 8%,\n transparent\n );\n --fd-nav-height: 44px;\n --fd-banner-height: 0px;\n --fd-tocnav-height: 0px;\n --scrollbar-thumb: var(--color-fd-border);\n --scrollbar-thumb-hover: var(--color-fd-ring);\n --scrollbar-track: transparent;\n --radius: 0px;\n --font-geist-sans: \"Geist Sans\";\n --font-geist-mono: \"Geist Mono\";\n}\n\n.dark {\n --color-fd-background: #000 !important;\n}\n\nhtml,\nbody,\n#nd-docs-layout {\n background-color: var(--color-fd-background) !important;\n}\n\n@font-face {\n font-family: \"Geist Sans\";\n font-display: block;\n font-style: normal;\n font-weight: 100 900;\n src:\n local(\"Geist Sans\"),\n url(\"/assets/Geist-Variable-CrgPqtmy.woff2\") format(\"woff2\"),\n url(\"/node_modules/geist/dist/fonts/geist-sans/Geist-Variable.woff2\") format(\"woff2\");\n}\n\n@font-face {\n font-family: \"Geist Mono\";\n font-display: block;\n font-style: normal;\n font-weight: 100 900;\n src:\n local(\"Geist Mono\"),\n url(\"/assets/GeistMono-Variable-BNLlm6Cd.woff2\") format(\"woff2\"),\n url(\"/node_modules/geist/dist/fonts/geist-mono/GeistMono-Variable.woff2\") format(\"woff2\");\n}\n\n* {\n scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);\n scrollbar-width: thin;\n}\n\nhtml {\n scroll-padding-top: calc(\n var(--fd-nav-height, 56px) + var(--fd-banner-height, 0px) + var(--fd-tocnav-height, 0px) + 24px\n );\n}\n\nbody {\n overscroll-behavior: none;\n}\n\nhtml[data-farm-docs-sidebar=\"open\"],\nhtml[data-farm-docs-sidebar=\"open\"] body {\n overflow: hidden;\n}\n\ncode:not(pre code) {\n overflow-wrap: break-word;\n word-break: break-word;\n}\n\n#nd-docs-layout,\n#nd-docs-layout * {\n border-radius: 0 !important;\n}\n\n.topbar {\n grid-column: 2 / -1;\n width: 100%;\n}\n\n.topbar-actions,\n.mobile-topbar-actions {\n display: flex;\n height: 100%;\n min-width: 0;\n align-items: stretch;\n margin-left: auto;\n}\n\n.mobile-topbar {\n display: none;\n}\n\n.sidebar-backdrop {\n display: none;\n}\n\n.fd-mobile-nav-btn {\n display: inline-flex;\n width: var(--fd-mobile-nav-height, 56px);\n height: 100%;\n flex: 0 0 var(--fd-mobile-nav-height, 56px);\n align-items: center;\n justify-content: center;\n border: 0;\n border-right: 1px solid var(--color-fd-border);\n background: transparent;\n color: var(--color-fd-foreground);\n cursor: pointer;\n padding: 0;\n}\n\n.fd-mobile-nav-btn svg {\n width: 19px;\n height: 19px;\n fill: none;\n stroke: currentColor;\n stroke-linecap: round;\n stroke-linejoin: round;\n stroke-width: 2;\n}\n\n.mobile-topbar-link {\n display: inline-flex;\n height: 100%;\n min-width: 0;\n align-items: center;\n color: var(--color-fd-muted-foreground);\n font-family: var(--fd-docs-font-mono);\n font-size: 12px;\n letter-spacing: 0.03em;\n text-decoration: none;\n text-transform: uppercase;\n}\n\n.mobile-topbar-link {\n border-left: 1px solid var(--color-fd-border);\n padding: 0 14px;\n}\n\n.sidebar-brand {\n justify-content: flex-start;\n}\n\n.sidebar-brand > a {\n display: inline-flex;\n min-width: 0;\n align-items: center;\n gap: 8px;\n overflow: hidden;\n flex: 0 0 auto;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.sidebar-brand-logo {\n width: 16px;\n height: 16px;\n flex: 0 0 16px;\n color: var(--color-fd-foreground);\n}\n\n.sidebar-brand-title {\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n.sidebar-brand-suffix {\n opacity: 0.52;\n}\n\n.sidebar-brand > span {\n flex: 0 0 auto;\n margin-left: auto;\n}\n\n.fd-docs-search-trigger {\n display: inline-flex;\n width: auto;\n min-width: 46px;\n height: 26px;\n flex: 1 1 auto;\n align-items: center;\n justify-content: center;\n gap: 6px;\n overflow: hidden;\n border: 1px solid var(--color-fd-border);\n background: color-mix(in srgb, var(--color-fd-foreground) 4%, transparent);\n color: var(--color-fd-muted-foreground);\n cursor: pointer;\n padding: 0 5px 0 7px;\n font-family: var(--fd-docs-font-mono);\n font-size: 10px;\n letter-spacing: 0;\n line-height: 1;\n text-transform: uppercase;\n transition:\n border-color 150ms ease,\n background-color 150ms ease,\n color 150ms ease;\n appearance: none;\n}\n\n.fd-docs-search-trigger:hover,\n.fd-docs-search-trigger:focus-visible,\n.fd-docs-search-trigger[aria-expanded=\"true\"] {\n border-color: color-mix(in srgb, var(--color-fd-foreground) 28%, transparent);\n background: color-mix(in srgb, var(--color-fd-foreground) 8%, transparent);\n color: var(--color-fd-foreground);\n}\n\n.fd-docs-search-trigger:focus-visible {\n outline: 1px solid var(--color-fd-foreground);\n outline-offset: 2px;\n}\n\n.fd-docs-search-trigger svg {\n width: 13px;\n height: 13px;\n flex: 0 0 13px;\n fill: none;\n stroke: currentColor;\n stroke-linecap: round;\n stroke-linejoin: round;\n stroke-width: 1.8;\n}\n\n.fd-docs-search-trigger kbd {\n display: inline-flex;\n min-width: 24px;\n min-height: 16px;\n flex: 0 0 auto;\n align-items: center;\n justify-content: center;\n gap: 2px;\n border: 1px solid var(--color-fd-border);\n background: var(--color-fd-background);\n padding: 1px 4px;\n color: currentColor;\n font-family: inherit;\n font-size: 9px;\n font-weight: 500;\n letter-spacing: 0;\n line-height: 1;\n}\n\n.topbar-actions .fd-docs-search-trigger,\n.mobile-topbar-actions .fd-docs-search-trigger {\n width: auto;\n min-width: 54px;\n height: 100%;\n flex: 0 0 auto;\n border: 0;\n border-left: 1px solid var(--color-fd-border);\n background: transparent;\n padding: 0 12px;\n}\n\n.topbar-actions .fd-docs-search-trigger:hover,\n.topbar-actions .fd-docs-search-trigger:focus-visible,\n.mobile-topbar-actions .fd-docs-search-trigger:hover,\n.mobile-topbar-actions .fd-docs-search-trigger:focus-visible {\n background: color-mix(in srgb, var(--color-fd-foreground) 6%, transparent);\n}\n\n.fd-toc {\n position: sticky;\n top: var(--fd-docs-row-1);\n grid-area: toc;\n display: flex;\n flex-direction: column;\n width: var(--fd-toc-width);\n height: calc(var(--fd-docs-height) - var(--fd-docs-row-1));\n padding: 3rem 1rem 0.5rem 0;\n}\n\n.fd-toc-inner {\n min-width: 0;\n}\n\n.fd-toc-title {\n display: inline-flex;\n align-items: center;\n margin: 0 0 1rem;\n color: var(--color-fd-muted-foreground);\n gap: 0.375rem;\n font-size: 0.875rem;\n font-weight: 400;\n line-height: 1.4;\n}\n\n.fd-toc-title svg {\n width: 1rem;\n height: 1rem;\n}\n\n.toc-scroll {\n overflow: auto;\n min-height: 0;\n padding: 0.75rem 0;\n scrollbar-width: none;\n}\n\n.toc-track {\n position: relative;\n}\n\n.toc-thumb {\n position: absolute;\n inset-block: 0;\n inset-inline-start: 0;\n width: 1px;\n background: var(--color-fd-primary);\n transition: clip-path 150ms ease;\n}\n\n.toc-links {\n display: flex;\n flex-direction: column;\n border-inline-start: 1px solid color-mix(in srgb, var(--color-fd-foreground) 10%, transparent);\n}\n\n.toc-link {\n display: block;\n padding: 0.375rem 0 0.375rem 0.75rem;\n color: var(--color-fd-muted-foreground);\n font-size: 0.875rem;\n line-height: 1.45;\n text-decoration: none;\n overflow-wrap: anywhere;\n transition: color 150ms ease;\n}\n\n.toc-link:first-child {\n padding-top: 0;\n}\n\n.toc-link:last-child {\n padding-bottom: 0;\n}\n\n.toc-link[data-depth=\"3\"] {\n padding-left: 1.5rem;\n font-size: 0.8125rem;\n}\n\n.toc-link[data-depth=\"4\"],\n.toc-link[data-depth=\"5\"],\n.toc-link[data-depth=\"6\"] {\n padding-left: 2rem;\n font-size: 0.8125rem;\n}\n\n.toc-link[data-active=\"true\"] {\n color: var(--color-fd-primary);\n}\n\n.toc-link:hover {\n color: var(--color-fd-accent-foreground);\n}\n\n.toc-empty {\n margin: 0;\n color: var(--color-fd-muted-foreground);\n font-size: 0.875rem;\n}\n\n.code-block {\n --fd-code-header-bg: color-mix(\n in srgb,\n var(--color-fd-foreground) 5%,\n var(--color-fd-background)\n );\n --fd-code-body-bg: color-mix(in srgb, var(--color-fd-foreground) 8%, var(--color-fd-background));\n width: 100%;\n min-width: 0;\n max-width: 100%;\n border: 1px solid var(--color-fd-border) !important;\n background: var(--fd-code-body-bg);\n box-shadow: 3px 3px 0 0 var(--color-fd-border) !important;\n}\n\n.code-block-header {\n min-height: 28px;\n padding: 3px 7px 3px 9px;\n}\n\n.code-block-title {\n font-size: 10px;\n line-height: 1.2;\n text-transform: lowercase;\n}\n\n.code-block pre {\n margin: 0;\n max-width: 100%;\n background: var(--fd-code-body-bg);\n}\n\n.code-block code {\n border: 0 !important;\n background: transparent !important;\n padding: 0 !important;\n}\n\n.fd-breadcrumb {\n display: flex;\n min-width: 0;\n align-items: center;\n gap: 0;\n margin: 0 0 0.5rem;\n color: var(--color-fd-muted-foreground);\n font-family: var(--fd-font-mono, var(--font-geist-mono, ui-monospace, monospace));\n font-size: 0.75rem;\n letter-spacing: 0.01em;\n line-height: 1.4;\n text-transform: uppercase;\n}\n\n.fd-breadcrumb-item {\n display: inline-flex;\n min-width: 0;\n align-items: center;\n}\n\n.fd-breadcrumb-link {\n color: inherit;\n font-family: var(--fd-font-mono, var(--font-geist-mono, ui-monospace, monospace));\n text-decoration: none;\n}\n\n.fd-breadcrumb-link:hover {\n color: var(--color-fd-foreground);\n}\n\n.fd-breadcrumb-parent {\n opacity: 0.6;\n font-weight: 400;\n}\n\n.fd-breadcrumb-sep {\n margin: 0 0.375rem;\n opacity: 0.4;\n font-size: 0.75rem;\n}\n\n.fd-breadcrumb-current {\n color: var(--color-fd-foreground);\n font-family: var(--fd-font-mono, var(--font-geist-mono, ui-monospace, monospace));\n font-weight: 500;\n}\n\n.fd-last-updated-inline,\n.fd-last-updated-footer {\n color: var(--color-fd-muted-foreground);\n font-family: var(--fd-docs-font-mono);\n font-size: 0.6875rem;\n line-height: 1.5;\n letter-spacing: 0.04em;\n text-transform: uppercase;\n}\n\n.fd-page-action-btn {\n border-radius: 0 !important;\n box-shadow: 2px 2px 0 0 var(--color-fd-border);\n font-family: var(--fd-docs-font-mono) !important;\n font-size: 0.75rem;\n letter-spacing: 0.03em;\n text-transform: uppercase;\n}\n\n.fd-page-action-btn .fd-page-action-check-icon {\n display: none;\n}\n\n.fd-page-action-btn[data-copied=\"true\"] .fd-page-action-copy-icon {\n display: none;\n}\n\n.fd-page-action-btn[data-copied=\"true\"] .fd-page-action-check-icon {\n display: block;\n}\n\n@media (max-width: 1020px) {\n :root {\n --fd-mobile-nav-height: 56px;\n --fd-sidebar-edge: 20px;\n --fd-sidebar-guide-x: 58px;\n --fd-sidebar-link-x: 88px;\n --fd-sidebar-sub-guide-x: calc(var(--fd-sidebar-link-x) + 7px);\n --fd-sidebar-sub-link-x: calc(var(--fd-sidebar-sub-guide-x) + 28px);\n }\n\n html {\n scroll-padding-top: calc(var(--fd-mobile-nav-height, 56px) + 24px);\n }\n\n body {\n overflow-x: hidden;\n }\n\n #nd-docs-layout {\n display: block !important;\n min-height: 100dvh;\n border-top: 0;\n padding-top: var(--fd-mobile-nav-height, 56px);\n }\n\n .mobile-topbar {\n position: fixed;\n inset: 0 0 auto;\n z-index: 80;\n display: flex;\n height: var(--fd-mobile-nav-height, 56px);\n align-items: stretch;\n border-bottom: 1px solid var(--color-fd-border);\n background: color-mix(in srgb, var(--color-fd-background) 94%, transparent);\n backdrop-filter: blur(12px);\n }\n\n .mobile-topbar a:hover,\n .fd-mobile-nav-btn:hover {\n color: var(--color-fd-foreground);\n }\n\n .topbar {\n display: none !important;\n }\n\n .omni-overlay {\n z-index: 100;\n }\n\n .omni-content {\n z-index: 101;\n }\n\n .sidebar-backdrop {\n position: fixed;\n inset: 0;\n z-index: 70;\n display: block;\n background: color-mix(in srgb, var(--color-fd-background) 72%, transparent);\n opacity: 0;\n pointer-events: none;\n transition: opacity 180ms ease;\n }\n\n #nd-docs-layout[data-sidebar-open=\"true\"] .sidebar-backdrop {\n opacity: 1;\n pointer-events: auto;\n }\n\n aside#nd-sidebar {\n position: fixed;\n inset: 0 auto 0 0;\n z-index: 90;\n width: min(342px, calc(100vw - 42px));\n height: 100dvh;\n max-height: none;\n overflow-y: auto;\n overscroll-behavior: contain;\n border-right: 1px solid var(--color-fd-border);\n border-bottom: 0;\n transform: translate3d(-100%, 0, 0);\n transition: transform 180ms ease;\n will-change: transform;\n }\n\n #nd-docs-layout[data-sidebar-open=\"true\"] aside#nd-sidebar {\n transform: translate3d(0, 0, 0);\n }\n\n main {\n padding: 34px 20px 64px;\n }\n\n article#nd-page {\n width: 100%;\n margin: 0;\n }\n\n #nd-docs-layout .fd-toc {\n display: none !important;\n }\n\n .prose h1 {\n font-size: 32px;\n letter-spacing: 0;\n line-height: 1.16;\n }\n\n .code-block {\n margin: 16px 0;\n box-shadow: 2px 2px 0 0 var(--color-fd-border) !important;\n }\n\n .code-block-header {\n min-height: 26px;\n padding: 2px 6px 2px 8px;\n }\n\n .code-copy-floating {\n top: 6px;\n right: 6px;\n }\n\n #nd-docs-layout figure.shiki.code-block pre,\n .code-block pre {\n padding: 12px 11px !important;\n font-size: 12px;\n line-height: 1.5;\n }\n\n .sh__line {\n min-height: 1.5em;\n }\n\n .fd-page-nav {\n grid-template-columns: 1fr !important;\n }\n\n .fd-page-nav-next {\n align-items: flex-start;\n text-align: left;\n }\n\n .mobile-topbar-actions .fd-docs-search-trigger {\n min-width: 44px;\n padding: 0 14px;\n }\n\n .mobile-topbar-actions .fd-docs-search-trigger kbd {\n display: none;\n }\n}\n\n@media (max-width: 640px) {\n .code-block-header {\n min-height: 22px;\n padding: 1px 4px 1px 7px;\n }\n\n .code-block-title {\n font-size: 9px;\n }\n\n .code-copy {\n width: 20px;\n height: 20px;\n }\n\n .code-copy svg {\n width: 12px;\n height: 12px;\n }\n\n .code-copy-floating {\n top: 5px;\n right: 5px;\n }\n\n #nd-docs-layout figure.shiki.code-block pre,\n .code-block pre {\n padding: 10px !important;\n font-size: 11px;\n line-height: 1.55;\n }\n\n .sh__line {\n min-height: 1.55em;\n }\n}\n\n/* Search styling mirrors @farming-labs/theme's shared Omni palette so Farm\n * matches the Next.js and other framework adapters pixel-for-pixel. The CSS\n * stays bundled because production adapters cannot resolve theme files from\n * node_modules at request time. */\n/* ═══════════════════════════════════════════════════════════════════\n * Omni Command Palette — core styles\n * Uses fumadocs CSS variables so it auto-adapts to every theme.\n * ═══════════════════════════════════════════════════════════════════ */\n\n@keyframes omni-fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n@keyframes omni-fade-out {\n from {\n opacity: 1;\n }\n to {\n opacity: 0;\n }\n}\n@keyframes omni-scale-in {\n from {\n opacity: 0;\n transform: translateX(-50%) scale(0.98) translateY(-6px);\n }\n to {\n opacity: 1;\n transform: translateX(-50%) scale(1) translateY(0);\n }\n}\n@keyframes omni-scale-out {\n from {\n opacity: 1;\n transform: translateX(-50%) scale(1) translateY(0);\n }\n to {\n opacity: 0;\n transform: translateX(-50%) scale(0.98) translateY(-6px);\n }\n}\n\n@keyframes omni-spin {\n from {\n transform: rotate(0deg);\n }\n to {\n transform: rotate(360deg);\n }\n}\n\n.omni-spin {\n animation: omni-spin 1s linear infinite;\n}\n\n.omni-overlay {\n position: fixed;\n inset: 0;\n z-index: 50;\n background: rgba(0, 0, 0, 0.2);\n backdrop-filter: blur(2px);\n animation: omni-fade-in 150ms ease-out;\n}\n\n.omni-content {\n --omni-content-top: clamp(5rem, 16vh, 7rem);\n position: fixed;\n z-index: 51;\n top: var(--omni-content-top);\n left: 50%;\n transform: translateX(-50%);\n display: flex;\n flex-direction: column;\n width: min(720px, calc(100% - 1rem));\n border-radius: 0.75rem;\n border: 1px solid color-mix(in srgb, var(--color-fd-border, #d4d4d4) 70%, transparent);\n background: var(--color-fd-popover, #fafafa);\n color: var(--color-fd-popover-foreground, var(--color-fd-foreground, #272727));\n font-family: var(--font-sans, system-ui, -apple-system, BlinkMacSystemFont, \"SF Pro Text\",\n ui-sans-serif, sans-serif);\n box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);\n outline: none;\n overscroll-behavior: contain;\n animation: omni-scale-in 200ms cubic-bezier(0.16, 1, 0.3, 1);\n}\n\n@media (max-width: 639px) {\n .omni-content {\n --omni-content-top: 1rem;\n top: var(--omni-content-top);\n width: calc(100% - 1rem);\n max-height: calc(100vh - 2rem);\n }\n}\n\n/* Header */\n.omni-header {\n border-bottom: 1px solid var(--color-fd-border, #262626);\n}\n.omni-search-row {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n padding: 0.75rem;\n}\n.omni-search-icon {\n color: var(--color-fd-muted-foreground, #a3a3a3);\n flex-shrink: 0;\n}\n.omni-search-icon svg {\n width: 1.25rem;\n height: 1.25rem;\n}\n.omni-search-input {\n width: 0;\n flex: 1;\n background: transparent;\n outline: none;\n font-size: 1.125rem;\n line-height: 1.75rem;\n color: var(--color-fd-popover-foreground, var(--color-fd-foreground, #272727));\n border: none;\n}\n.omni-search-input::placeholder {\n color: var(--color-fd-muted-foreground, #a3a3a3);\n}\n.omni-kbd {\n border-radius: 0.375rem;\n border: 1px solid var(--color-fd-border, #d4d4d4);\n background: transparent;\n padding: 0.375rem 0.5rem;\n font-size: 0.75rem;\n color: var(--color-fd-muted-foreground, #a3a3a3);\n font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,\n \"Liberation Mono\", \"Courier New\", monospace);\n line-height: 1rem;\n}\n.omni-close-btn {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 0.25rem;\n min-width: 2.5rem;\n border-radius: 0.375rem;\n border: 1px solid var(--color-fd-border, #d4d4d4);\n padding: 0.375rem 0.5rem;\n color: var(--color-fd-muted-foreground, #a3a3a3);\n font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,\n \"Liberation Mono\", \"Courier New\", monospace);\n font-size: 0.75rem;\n line-height: 1rem;\n font-weight: 500;\n transition:\n background 120ms,\n color 120ms;\n cursor: pointer;\n background: none;\n}\n.omni-close-btn:hover {\n color: var(--color-fd-accent-foreground, var(--color-fd-foreground, #171717));\n background: var(--color-fd-accent, #e5e5e5);\n}\n.omni-close-btn svg {\n display: none;\n}\n\n/* Body / listbox */\n.omni-body {\n flex: 1 1 auto;\n min-height: 0;\n max-height: min(540px, calc(100vh - var(--omni-content-top, 7rem) - 8rem));\n overflow: auto;\n overscroll-behavior: contain;\n padding: 0.5rem;\n}\n.omni-body::-webkit-scrollbar {\n width: 6px;\n}\n.omni-body::-webkit-scrollbar-track {\n background: transparent;\n}\n.omni-body::-webkit-scrollbar-thumb {\n background: var(--color-fd-muted, #262626);\n border-radius: 3px;\n}\n\n/* Loading */\n.omni-loading {\n display: flex;\n align-items: center;\n gap: 0.5rem;\n padding: 0.75rem 0.625rem;\n color: var(--color-fd-muted-foreground, #a3a3a3);\n font-size: 0.875rem;\n}\n\n/* Groups */\n.omni-group {\n padding: 0;\n}\n.omni-group-label {\n display: none;\n}\n.omni-group-items {\n display: flex;\n flex-direction: column;\n gap: 0.25rem;\n}\n\n/* Items */\n.omni-item {\n position: relative;\n display: block;\n width: 100%;\n flex-shrink: 0;\n border-radius: 0.5rem;\n padding: 0.75rem 0.875rem;\n text-align: left;\n font-size: 0.875rem;\n line-height: 1.25rem;\n cursor: pointer;\n border: none;\n background: transparent;\n color: var(--color-fd-foreground, #fafafa);\n transition: background 80ms;\n}\n.omni-item:hover,\n.omni-item-active {\n background: var(--color-fd-accent, rgba(209, 209, 209, 0.5));\n}\n.omni-item-active {\n color: var(--color-fd-accent-foreground, #171717);\n}\n.omni-item-disabled {\n opacity: 0.5;\n cursor: not-allowed;\n}\n\n.omni-item-icon {\n display: none;\n}\n.omni-item-active .omni-item-icon {\n color: var(--color-fd-accent-foreground, #fafafa);\n}\n.omni-item-text {\n min-width: 0;\n}\n.omni-item-label {\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--color-fd-popover-foreground, var(--color-fd-foreground, #272727));\n font-weight: 500;\n line-height: 1.35;\n}\n.omni-item-subtitle {\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n font-size: 0.75rem;\n line-height: 1rem;\n color: var(--color-fd-muted-foreground, #a3a3a3);\n opacity: 1;\n}\n.omni-item-active .omni-item-subtitle {\n color: var(--color-fd-muted-foreground, #737373);\n opacity: 1;\n}\n.omni-item-description {\n min-width: 0;\n overflow: hidden;\n display: -webkit-box;\n -webkit-line-clamp: 3;\n -webkit-box-orient: vertical;\n margin-top: 0.625rem;\n padding-left: 0.75rem;\n border-left: 1px solid color-mix(in srgb, var(--color-fd-border, #d4d4d4) 70%, transparent);\n color: color-mix(in srgb, var(--color-fd-popover-foreground, #272727) 82%, transparent);\n font-size: 0.875rem;\n line-height: 1.5rem;\n font-weight: 400;\n}\n.omni-item-badge {\n display: none;\n}\n.omni-item-ext {\n display: none;\n}\n.omni-item-ext:hover {\n color: var(--color-fd-foreground, #fafafa);\n background: var(--color-fd-muted, #262626);\n}\n.omni-item-shortcuts {\n display: none;\n align-items: center;\n gap: 0.25rem;\n font-size: 10px;\n color: var(--color-fd-muted-foreground, #a3a3a3);\n}\n@media (min-width: 640px) {\n .omni-item-shortcuts {\n display: flex;\n }\n}\n.omni-kbd-sm {\n border-radius: 0.25rem;\n background: var(--color-fd-muted, #262626);\n padding: 0.125rem 0.25rem;\n font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,\n \"Liberation Mono\", \"Courier New\", monospace);\n}\n.omni-item-chevron {\n display: none;\n}\n/* Highlight */\n.omni-highlight {\n border-radius: 0;\n background: transparent;\n padding: 0;\n color: var(--color-fd-primary, #ca8a04);\n text-decoration: underline;\n text-underline-offset: 2px;\n}\n\n/* Empty states */\n.omni-empty-group {\n padding: 0.5rem 0.75rem;\n font-size: 0.75rem;\n color: var(--color-fd-muted-foreground, #a3a3a3);\n}\n.omni-empty {\n padding: 1.5rem 0.75rem;\n text-align: center;\n font-size: 0.875rem;\n color: var(--color-fd-muted-foreground, #a3a3a3);\n}\n.omni-empty-icon {\n width: 2rem;\n height: 2rem;\n margin: 0 auto 0.5rem;\n display: flex;\n align-items: center;\n justify-content: center;\n border-radius: 9999px;\n background: var(--color-fd-muted, #262626);\n}\n\n/* Footer */\n.omni-footer {\n border-top: 1px solid var(--color-fd-border, #262626);\n background: color-mix(in srgb, var(--color-fd-secondary, #f5f5f5) 50%, transparent);\n}\n.omni-footer-inner {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 0.75rem;\n padding: 0.625rem 0.75rem;\n font-size: 0.75rem;\n color: var(--color-fd-muted-foreground, #a3a3a3);\n}\n.omni-footer-hints {\n display: flex;\n align-items: center;\n flex-wrap: wrap;\n gap: 0.75rem;\n}\n.omni-footer-hint {\n display: flex;\n align-items: center;\n gap: 0.25rem;\n white-space: nowrap;\n}\n.omni-footer-hint svg {\n box-sizing: border-box;\n width: 1.375rem;\n height: 1.375rem;\n padding: 0.25rem;\n border-radius: 0.375rem;\n border: 1px solid var(--color-fd-border, #d4d4d4);\n background: color-mix(in srgb, var(--color-fd-muted, #e5e5e5) 70%, transparent);\n color: var(--color-fd-muted-foreground, #737373);\n flex-shrink: 0;\n}\n.omni-footer-hint-desktop {\n display: none;\n}\n.omni-footer-filter {\n position: relative;\n display: inline-flex;\n align-items: center;\n gap: 0.5rem;\n margin-left: auto;\n white-space: nowrap;\n}\n@media (min-width: 640px) {\n .omni-footer-hint-desktop {\n display: flex;\n }\n}\n.omni-filter-label {\n color: var(--color-fd-muted-foreground, #a3a3a3);\n}\n.omni-filter-value {\n display: inline-flex;\n align-items: center;\n gap: 0.25rem;\n color: var(--color-fd-popover-foreground, var(--color-fd-foreground, #272727));\n}\n.omni-filter-button {\n display: inline-flex;\n align-items: center;\n gap: 0.25rem;\n border: 0;\n background: transparent;\n color: var(--color-fd-popover-foreground, var(--color-fd-foreground, #272727));\n font: inherit;\n cursor: pointer;\n padding: 0;\n}\n.omni-filter-button:hover {\n color: var(--color-fd-accent-foreground, var(--color-fd-foreground, #171717));\n}\n.omni-filter-menu {\n position: absolute;\n right: 0;\n bottom: calc(100% + 0.5rem);\n z-index: 1;\n width: 10rem;\n border: 1px solid var(--color-fd-border, #d4d4d4);\n border-radius: 0.5rem;\n background: var(--color-fd-popover, #fafafa);\n padding: 0.25rem;\n box-shadow: 0 16px 32px -20px rgba(0, 0, 0, 0.45);\n}\n.omni-filter-option {\n display: flex;\n width: 100%;\n align-items: center;\n border: 0;\n border-radius: 0.375rem;\n background: transparent;\n color: var(--color-fd-popover-foreground, var(--color-fd-foreground, #272727));\n cursor: pointer;\n font: inherit;\n padding: 0.5rem 0.625rem;\n text-align: left;\n}\n.omni-filter-option:hover,\n.omni-filter-option-active {\n background: var(--color-fd-accent, rgba(209, 209, 209, 0.5));\n}\n\n/* ─── Omni Command Palette (pixel-border theme) ─────────────────── */\n\n.omni-content {\n border-radius: 0 !important;\n border: 1px solid var(--fd-pixel-modal-border);\n box-shadow:\n 2px 2px 0 0 var(--fd-pixel-modal-shadow),\n 0 0 0 1px color-mix(in srgb, var(--color-fd-foreground) 3%, transparent);\n}\n\n.omni-item {\n border-radius: 0 !important;\n}\n\n.omni-kbd,\n.omni-kbd-sm {\n border-radius: 0 !important;\n border: 1px solid var(--color-fd-border, hsl(0 0% 15%));\n}\n\n.omni-close-btn {\n border-radius: 0 !important;\n}\n\n.omni-empty-icon {\n border-radius: 0 !important;\n}\n\n.omni-search-input {\n font-family: var(--fd-font-sans, system-ui, -apple-system, sans-serif);\n}\n\n.omni-group-label {\n font-family: var(--fd-font-mono, ui-monospace, monospace);\n letter-spacing: 0.08em;\n}\n\n.omni-footer-inner {\n font-family: var(--fd-font-mono, ui-monospace, monospace);\n}\n\n.omni-footer-hint svg {\n border-radius: 0 !important;\n}\n\n.omni-filter-menu,\n.omni-filter-option {\n border-radius: 0 !important;\n}\n\n.omni-highlight {\n background: color-mix(in srgb, var(--color-fd-primary, #6366f1) 25%, transparent);\n border-radius: 0 !important;\n}\n\n/* Farm's frameworkless topbar uses a compact search trigger. */\n.topbar-actions .fd-docs-search-trigger {\n width: 56px;\n min-width: 56px;\n justify-content: center;\n padding: 0 10px;\n}\n\n.topbar-actions .fd-docs-search-trigger kbd {\n min-width: 36px;\n height: 19px;\n min-height: 19px;\n flex: 0 0 auto;\n gap: 4px;\n border-color: color-mix(in srgb, var(--color-fd-foreground) 14%, transparent);\n background: color-mix(in srgb, var(--color-fd-foreground) 5%, transparent);\n padding: 0 5px;\n font-size: 9px;\n}\n\n/* Farm's mobile shell sits above the frameworkless docs canvas. Keep the\n * shared Omni palette above it without changing the cross-framework styling. */\n.omni-overlay {\n z-index: 100;\n}\n\n.omni-content {\n z-index: 101;\n}\n\n@media (max-width: 1023px) {\n .mobile-topbar-actions .fd-docs-search-trigger {\n width: 44px;\n min-width: 44px;\n justify-content: center;\n padding: 0;\n }\n\n .mobile-topbar-actions .fd-docs-search-trigger kbd {\n display: none;\n }\n}\n\n@media (prefers-reduced-motion: reduce) {\n .omni-overlay,\n .omni-content {\n animation: none;\n }\n}\n`;\n","import { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\n\nexport function isFarmDocsSearchEnabled(docs: FarmDocsResolvedConfig | undefined): boolean {\n if (!docs?.enabled) return false;\n\n const search = docs.config.search;\n if (search === false) return false;\n return !(search && typeof search === \"object\" && search.enabled === false);\n}\n\nexport function resolveFarmDocsSearchClientModule(root: string): string | undefined {\n try {\n const requireFromApp = createRequire(path.join(path.resolve(root), \"package.json\"));\n const themeEntry = requireFromApp.resolve(\"@farming-labs/theme\");\n const commandSearchModule = path.join(path.dirname(themeEntry), \"docs-command-search.mjs\");\n if (existsSync(commandSearchModule)) return commandSearchModule;\n } catch {\n // The public package entry remains a compatible fallback.\n }\n\n return undefined;\n}\n\nexport function generateFarmDocsSearchBootstrapRuntime(): string {\n return `(()=>{if(window.__farmDocsSearchBootstrap)return;window.__farmDocsSearchBootstrap=true;const queue=(trigger,event)=>{if(window.__FARM_DOCS_SEARCH_BRIDGE_ACTIVE__)return;event.preventDefault();event.stopPropagation();event.stopImmediatePropagation();window.__FARM_DOCS_SEARCH_PENDING__=trigger;window.__FARM_MOUNT_DOCS_SEARCH__?.()};document.addEventListener(\"click\",(event)=>{const target=event.target instanceof Element?event.target.closest(\"[data-search-full]\"):null;if(target)queue(\"button\",event)},true);document.addEventListener(\"keydown\",(event)=>{if((event.metaKey||event.ctrlKey)&&event.key.toLowerCase()===\"k\")queue(\"keyboard\",event)},true)})();`;\n}\n\nexport function generateFarmDocsSearchClientRuntime(enabled: boolean, moduleId?: string): string {\n if (!enabled || !moduleId) {\n return `\nfunction isFarmDocsSearchPage() {\n return false;\n}\n\nasync function mountFarmDocsSearch() {\n return false;\n}\n`;\n }\n\n return `\nlet farmDocsSearchRoot = null;\nlet farmDocsSearchContainer = null;\nlet farmDocsSearchModulePromise = null;\nlet farmDocsSearchPendingTrigger = window.__FARM_DOCS_SEARCH_PENDING__ === 'keyboard'\n ? 'keyboard'\n : window.__FARM_DOCS_SEARCH_PENDING__\n ? 'button'\n : null;\nlet farmDocsSearchReady = false;\n\nfunction isFarmDocsSearchPage() {\n return document.querySelector('[data-farm-docs-search-root]') instanceof HTMLElement;\n}\n\nfunction replayFarmDocsSearchOpen() {\n const pendingTrigger = farmDocsSearchPendingTrigger;\n farmDocsSearchPendingTrigger = null;\n window.__FARM_DOCS_SEARCH_PENDING__ = null;\n if (!pendingTrigger) return;\n\n queueMicrotask(() => {\n if (pendingTrigger === 'keyboard') {\n document.dispatchEvent(\n new KeyboardEvent('keydown', {\n key: 'k',\n metaKey: true,\n bubbles: true,\n cancelable: true,\n }),\n );\n } else {\n const trigger = document.querySelector('[data-search-full]');\n if (trigger instanceof HTMLElement) trigger.click();\n }\n });\n}\n\nfunction FarmDocsSearchBridge({ component, api }) {\n React.useEffect(() => {\n farmDocsSearchReady = true;\n replayFarmDocsSearchOpen();\n return () => {\n farmDocsSearchReady = false;\n };\n }, []);\n\n return React.createElement(component, { api });\n}\n\nfunction queueFarmDocsSearchOpen(trigger, event) {\n if (farmDocsSearchReady) return;\n event.preventDefault();\n event.stopPropagation();\n event.stopImmediatePropagation();\n farmDocsSearchPendingTrigger = trigger;\n window.__FARM_DOCS_SEARCH_PENDING__ = trigger;\n void mountFarmDocsSearch();\n}\n\ndocument.addEventListener(\n 'click',\n (event) => {\n const target = event.target instanceof Element\n ? event.target.closest('[data-search-full]')\n : null;\n if (target) queueFarmDocsSearchOpen('button', event);\n },\n true,\n);\n\ndocument.addEventListener(\n 'keydown',\n (event) => {\n if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {\n queueFarmDocsSearchOpen('keyboard', event);\n }\n },\n true,\n);\n\nwindow.__FARM_DOCS_SEARCH_BRIDGE_ACTIVE__ = true;\n\nasync function mountFarmDocsSearch() {\n const container = document.querySelector('[data-farm-docs-search-root]');\n if (!(container instanceof HTMLElement)) return false;\n if (farmDocsSearchContainer === container && farmDocsSearchRoot) return true;\n\n try {\n farmDocsSearchModulePromise ||= import(${JSON.stringify(moduleId)});\n const { DocsCommandSearch } = await farmDocsSearchModulePromise;\n if (!container.isConnected) return false;\n\n if (farmDocsSearchRoot) {\n farmDocsSearchReady = false;\n try {\n farmDocsSearchRoot.unmount();\n } catch {}\n }\n\n farmDocsSearchContainer = container;\n farmDocsSearchRoot = createRoot(container);\n farmDocsSearchRoot.render(\n React.createElement(FarmDocsSearchBridge, {\n component: DocsCommandSearch,\n api: container.dataset.api || '/api/docs',\n }),\n );\n return true;\n } catch (error) {\n farmDocsSearchModulePromise = null;\n console.error('[Farm.js] Could not load docs search:', error);\n return false;\n }\n}\n\nwindow.__FARM_MOUNT_DOCS_SEARCH__ = mountFarmDocsSearch;\n`;\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport {\n buildDocsAgentDiscoverySpec,\n buildDocsSitemapManifest,\n isDocsAgentDiscoveryRequest,\n isDocsAgentsRequest,\n isDocsSkillRequest,\n renderDocsAgentsDocument,\n renderDocsLlmsTxt,\n renderDocsMarkdownDocument,\n renderDocsRobotsTxt,\n renderDocsSitemapMarkdown,\n renderDocsSitemapXml,\n renderDocsSkillDocument,\n resolveDocsLlmsTxtFormat,\n resolveDocsRobotsRequest,\n resolveDocsSitemapRequest,\n type DocsLlmsTxtPageInput,\n type DocsMarkdownPage,\n type DocsSitemapPageInput,\n} from \"@farming-labs/docs\";\nimport { marked, Renderer } from \"marked\";\nimport { highlight } from \"sugar-high\";\nimport { resolveFarmDocsPageLastModified } from \"./last-modified\";\nimport { farmDocsPixelBorderCss } from \"./pixel-border-css\";\nimport { generateFarmDocsSearchBootstrapRuntime, isFarmDocsSearchEnabled } from \"./search-client\";\nimport type { FarmDocsResolvedConfig } from \"./types\";\n\nexport interface FarmDocsHandlerOptions {\n root: string;\n srcDir?: string;\n clientEntry?: string;\n}\n\nexport interface FarmDocsPage {\n slug: string;\n title: string;\n description?: string;\n section?: string;\n href: string;\n sourcePath: string;\n lastModified?: string;\n}\n\nexport interface LoadedFarmDocsPage extends FarmDocsPage {\n body: string;\n frontmatter: Record<string, string>;\n}\n\nconst DOCS_FILE_NAMES = [\"page.mdx\", \"page.md\", \"index.mdx\", \"index.md\"];\nconst DOCS_FILE_EXTENSIONS = [\".mdx\", \".md\"];\nconst FARM_DOCS_FALLBACK_FAVICON =\n \"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' fill='black'/%3E%3Cpath d='M7 8h18v3H10v5h12v3H10v5H7z' fill='white'/%3E%3C/svg%3E\";\nconst FARM_DOCS_FAVICON_FILES = [\"favicon.svg\", \"favicon.ico\", \"favicon.png\"];\n\nconst GEIST_SANS_FONT_URL = \"/assets/Geist-Variable-CrgPqtmy.woff2\";\nconst GEIST_MONO_FONT_URL = \"/assets/GeistMono-Variable-BNLlm6Cd.woff2\";\n\nfunction trimSlashes(value: string): string {\n return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\nfunction normalizeEntry(entry: string | undefined): string {\n if (!entry || entry === \"/\") return \"/\";\n return `/${trimSlashes(entry)}`;\n}\n\nfunction normalizeSlug(value: string): string {\n return trimSlashes(decodeURIComponent(value)).replace(/\\.(mdx?|markdown)$/i, \"\");\n}\n\nfunction resolveFarmDocsFavicon(\n docs: FarmDocsResolvedConfig | undefined,\n options: FarmDocsHandlerOptions,\n): string {\n const configuredFavicon = docs?.config.favicon;\n if (typeof configuredFavicon === \"string\" && configuredFavicon.trim()) {\n return configuredFavicon.trim();\n }\n\n const publicDir = path.join(path.resolve(options.root), \"public\");\n\n for (const fileName of FARM_DOCS_FAVICON_FILES) {\n const faviconPath = path.join(publicDir, fileName);\n if (existsSync(faviconPath) && statSync(faviconPath).isFile()) {\n return `/${fileName}`;\n }\n }\n\n return FARM_DOCS_FALLBACK_FAVICON;\n}\n\nfunction renderFarmDocsFaviconLink(faviconHref: string): string {\n const normalizedHref = faviconHref.split(/[?#]/, 1)[0]?.toLowerCase() || \"\";\n const type =\n normalizedHref.endsWith(\".svg\") || faviconHref.startsWith(\"data:image/svg+xml\")\n ? \"image/svg+xml\"\n : normalizedHref.endsWith(\".png\")\n ? \"image/png\"\n : normalizedHref.endsWith(\".ico\")\n ? \"image/x-icon\"\n : undefined;\n const metadata =\n type === \"image/svg+xml\" ? ' sizes=\"any\" type=\"image/svg+xml\"' : type ? ` type=\"${type}\"` : \"\";\n\n return `<link rel=\"icon\" href=\"${escapeAttribute(faviconHref)}\"${metadata}>`;\n}\n\nfunction renderFarmDocsBrandMark(): string {\n return `<svg class=\"sidebar-brand-logo\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\">\n <rect x=\"2\" y=\"2\" width=\"5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\"></rect>\n <path d=\"M9.75 2h11.5c.41 0 .75.34.75.75v3.5c0 .41-.34.75-.75.75H9.75A.75.75 0 0 1 9 6.25v-3.5c0-.41.34-.75.75-.75Zm9.75 1.62a.38.38 0 0 0-.38.38v1c0 .21.17.38.38.38h.75c.21 0 .38-.17.38-.38V4a.38.38 0 0 0-.38-.38h-.75Z\" fill=\"currentColor\"></path>\n <rect x=\"2\" y=\"9.5\" width=\"5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.64\"></rect>\n <rect x=\"9\" y=\"9.5\" width=\"13\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.64\"></rect>\n <rect x=\"2\" y=\"17\" width=\"5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.34\"></rect>\n <rect x=\"9\" y=\"17\" width=\"7.5\" height=\"5\" rx=\"0.75\" fill=\"currentColor\" opacity=\"0.34\"></rect>\n </svg>`;\n}\n\nfunction renderFarmDocsBrandTitle(navTitle: string): string {\n const suffix = navTitle.match(/\\.js$/i)?.[0];\n\n if (!suffix) {\n return `<span class=\"sidebar-brand-title\">${escapeHtml(navTitle)}</span>`;\n }\n\n const productName = navTitle.slice(0, -suffix.length);\n return `<span class=\"sidebar-brand-title\">${escapeHtml(productName)}<span class=\"sidebar-brand-suffix\">${escapeHtml(suffix)}</span></span>`;\n}\n\nfunction isSafeSegment(segment: string): boolean {\n return segment !== \"..\" && !segment.includes(\"/\") && !segment.includes(\"\\\\\");\n}\n\nfunction resolveInside(root: string, target: string): string | null {\n const resolvedRoot = path.resolve(root);\n const resolvedTarget = path.resolve(target);\n const relative = path.relative(resolvedRoot, resolvedTarget);\n if (relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative))) {\n return resolvedTarget;\n }\n return null;\n}\n\nexport function isFarmDocsRequest(docs: FarmDocsResolvedConfig | undefined, request: Request) {\n if (!docs?.enabled) return false;\n if (request.method !== \"GET\" && request.method !== \"HEAD\") return false;\n\n const pathname = new URL(request.url).pathname;\n const entry = normalizeEntry(docs.entry);\n if (entry === \"/\") return true;\n\n return pathname === entry || pathname === `${entry}.md` || pathname.startsWith(`${entry}/`);\n}\n\nexport function resolveFarmDocsContentDir(\n docs: FarmDocsResolvedConfig,\n options: FarmDocsHandlerOptions,\n): string {\n const root = path.resolve(options.root);\n const srcDir = options.srcDir || \"src\";\n const configuredContentDir = docs.contentDir || docs.config.contentDir;\n\n if (configuredContentDir) {\n return path.isAbsolute(configuredContentDir)\n ? configuredContentDir\n : path.join(root, configuredContentDir);\n }\n\n const entryDir = docs.config.entry || trimSlashes(docs.entry) || \"docs\";\n const appDocsDir = path.join(root, srcDir, \"app\", entryDir);\n if (existsSync(appDocsDir)) return appDocsDir;\n\n return path.join(root, entryDir);\n}\n\nexport function getFarmDocsRouteTypeEntries(docs: FarmDocsResolvedConfig | undefined): string[] {\n if (!docs?.enabled) return [];\n const entry = normalizeEntry(docs.entry);\n if (entry === \"/\") return [\"/\", \"/[...docs]\"];\n return [entry, `${entry}/[...docs]`];\n}\n\nexport function getFarmDocsDocumentNavigationMatchers(\n docs: FarmDocsResolvedConfig | undefined,\n): string[] {\n if (!docs?.enabled) return [];\n const entry = normalizeEntry(docs.entry);\n return [entry === \"/\" ? \"/(.*)\" : `${entry}(.*)`];\n}\n\nfunction getRequestSlug(docs: FarmDocsResolvedConfig, request: Request): string {\n const pathname = new URL(request.url).pathname;\n const entry = normalizeEntry(docs.entry);\n\n if (entry === \"/\") return normalizeSlug(pathname);\n if (pathname === entry || pathname === `${entry}.md`) return \"\";\n\n return normalizeSlug(pathname.slice(entry.length));\n}\n\nfunction findDocsPageFile(contentDir: string, slug: string): string | null {\n const segments = slug ? slug.split(\"/\").filter(Boolean) : [];\n if (!segments.every(isSafeSegment)) return null;\n\n const slugDir = path.join(contentDir, ...segments);\n const candidates =\n segments.length === 0\n ? DOCS_FILE_NAMES.map((filename) => path.join(contentDir, filename))\n : [\n ...DOCS_FILE_NAMES.map((filename) => path.join(slugDir, filename)),\n ...DOCS_FILE_EXTENSIONS.map((extension) => path.join(contentDir, `${slug}${extension}`)),\n ];\n\n for (const candidate of candidates) {\n const safePath = resolveInside(contentDir, candidate);\n if (safePath && existsSync(safePath) && statSync(safePath).isFile()) {\n return safePath;\n }\n }\n\n return null;\n}\n\nfunction parseFrontmatter(source: string): {\n frontmatter: Record<string, string>;\n body: string;\n} {\n if (!source.startsWith(\"---\")) {\n return { frontmatter: {}, body: source };\n }\n\n const endIndex = source.indexOf(\"\\n---\", 3);\n if (endIndex === -1) return { frontmatter: {}, body: source };\n\n const frontmatterSource = source.slice(3, endIndex).trim();\n const body = source.slice(source.indexOf(\"\\n\", endIndex + 1) + 1);\n const frontmatter: Record<string, string> = {};\n\n for (const line of frontmatterSource.split(/\\r?\\n/)) {\n const separator = line.indexOf(\":\");\n if (separator === -1) continue;\n const key = line.slice(0, separator).trim();\n const value = line\n .slice(separator + 1)\n .trim()\n .replace(/^[\"']|[\"']$/g, \"\");\n if (key && value) frontmatter[key] = value;\n }\n\n return { frontmatter, body };\n}\n\nfunction titleFromSlug(slug: string): string {\n const lastSegment = slug.split(\"/\").filter(Boolean).pop() || \"Docs\";\n return lastSegment\n .split(/[-_]/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \");\n}\n\nfunction titleFromMarkdown(body: string, fallback: string): string {\n const heading = body.match(/^#\\s+(.+)$/m)?.[1]?.trim();\n return heading || fallback;\n}\n\nexport function loadFarmDocsPage(\n contentDir: string,\n docs: FarmDocsResolvedConfig,\n slug: string,\n): LoadedFarmDocsPage | null {\n const sourcePath = findDocsPageFile(contentDir, slug);\n if (!sourcePath) return null;\n\n const source = readFileSync(sourcePath, \"utf8\");\n const { frontmatter, body } = parseFrontmatter(source);\n const title = frontmatter.title || titleFromMarkdown(body, titleFromSlug(slug));\n const href = createDocsHref(docs.entry, slug);\n\n return {\n slug,\n title,\n description: frontmatter.description,\n href,\n sourcePath,\n lastModified: resolveFarmDocsPageLastModified(contentDir, sourcePath, frontmatter),\n frontmatter,\n body,\n };\n}\n\nfunction createDocsHref(entry: string, slug: string): string {\n const normalizedEntry = normalizeEntry(entry);\n const normalizedSlug = trimSlashes(slug);\n if (normalizedEntry === \"/\") return normalizedSlug ? `/${normalizedSlug}` : \"/\";\n return normalizedSlug ? `${normalizedEntry}/${normalizedSlug}` : normalizedEntry;\n}\n\nfunction pathToSlug(contentDir: string, filePath: string): string | null {\n const relative = path.relative(contentDir, filePath).replace(/\\\\/g, \"/\");\n if (relative.startsWith(\"..\")) return null;\n\n const extension = path.extname(relative);\n if (!DOCS_FILE_EXTENSIONS.includes(extension)) return null;\n\n const withoutExtension = relative.slice(0, -extension.length);\n if (withoutExtension === \"page\" || withoutExtension === \"index\") return \"\";\n if (withoutExtension.endsWith(\"/page\") || withoutExtension.endsWith(\"/index\")) {\n return withoutExtension.replace(/\\/(page|index)$/, \"\");\n }\n return withoutExtension;\n}\n\nfunction loadPage(\n contentDir: string,\n docs: FarmDocsResolvedConfig,\n request: Request,\n): LoadedFarmDocsPage | null {\n return loadFarmDocsPage(contentDir, docs, getRequestSlug(docs, request));\n}\n\nexport function discoverFarmDocsPages(\n contentDir: string,\n docs: FarmDocsResolvedConfig,\n): FarmDocsPage[] {\n if (!existsSync(contentDir)) return [];\n\n const pages: FarmDocsPage[] = [];\n const visit = (dir: string) => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n const absolutePath = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n visit(absolutePath);\n continue;\n }\n if (!entry.isFile()) continue;\n\n const slug = pathToSlug(contentDir, absolutePath);\n if (slug === null) continue;\n\n const source = readFileSync(absolutePath, \"utf8\");\n const { frontmatter, body } = parseFrontmatter(source);\n pages.push({\n slug,\n title: frontmatter.title || titleFromMarkdown(body, titleFromSlug(slug)),\n description: frontmatter.description,\n section: frontmatter.section,\n href: createDocsHref(docs.entry, slug),\n sourcePath: absolutePath,\n lastModified: resolveFarmDocsPageLastModified(contentDir, absolutePath, frontmatter),\n });\n }\n };\n\n visit(contentDir);\n return pages.sort((a, b) => a.href.localeCompare(b.href));\n}\n\nexport function toFarmDocsMarkdownPage(page: LoadedFarmDocsPage): DocsMarkdownPage {\n const lastModified =\n page.lastModified || page.frontmatter.lastModified || page.frontmatter.lastmod;\n\n return {\n slug: page.slug,\n url: page.href,\n title: page.title,\n description: page.description,\n lastModified,\n lastmod: lastModified,\n content: page.body,\n rawContent: page.body,\n };\n}\n\nfunction getDocsTitle(docs: FarmDocsResolvedConfig): string {\n return typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n ? String((docs.config.nav as { title?: unknown }).title || \"Documentation\")\n : \"Documentation\";\n}\n\nfunction getDocsDescription(docs: FarmDocsResolvedConfig): string | undefined {\n return docs.config.metadata?.description;\n}\n\nfunction getLoadedDocsPages(\n contentDir: string,\n docs: FarmDocsResolvedConfig,\n): LoadedFarmDocsPage[] {\n return discoverFarmDocsPages(contentDir, docs)\n .map((page) => loadFarmDocsPage(contentDir, docs, page.slug))\n .filter((page): page is LoadedFarmDocsPage => Boolean(page));\n}\n\nfunction toDocsLlmsPage(page: LoadedFarmDocsPage): DocsLlmsTxtPageInput {\n return toFarmDocsMarkdownPage(page);\n}\n\nfunction toDocsSitemapPage(page: LoadedFarmDocsPage): DocsSitemapPageInput {\n return {\n ...toFarmDocsMarkdownPage(page),\n sourcePath: page.sourcePath,\n };\n}\n\ntype CopyMarkdownActionConfig = {\n format: \"markdown\" | \"text\";\n includeTitle: boolean;\n label: string;\n copiedLabel: string;\n};\n\ntype LastUpdatedDisplayConfig = {\n enabled: boolean;\n label: string;\n position: \"footer\" | \"below-title\";\n};\n\ntype ReadingTimeDisplayConfig = {\n wordsPerMinute: number;\n format: \"long\" | \"short\";\n includeCode: boolean;\n};\n\nfunction resolvePageActionsConfig(docs: FarmDocsResolvedConfig): Record<string, unknown> {\n return isObjectRecord(docs.config.pageActions) ? docs.config.pageActions : {};\n}\n\nfunction resolvePageActionsAlignment(docs: FarmDocsResolvedConfig): \"left\" | \"right\" {\n return resolvePageActionsConfig(docs).alignment === \"right\" ? \"right\" : \"left\";\n}\n\nfunction resolveCopyMarkdownActionConfig(\n docs: FarmDocsResolvedConfig,\n): CopyMarkdownActionConfig | null {\n const raw = resolvePageActionsConfig(docs).copyMarkdown;\n if (raw === undefined || raw === false) return null;\n\n const options = isObjectRecord(raw) ? raw : {};\n if (isObjectRecord(raw) && raw.enabled === false) return null;\n\n return {\n format: options.format === \"text\" ? \"text\" : \"markdown\",\n includeTitle: options.includeTitle === true,\n label: readString(options.label) ?? \"Copy page\",\n copiedLabel: readString(options.copiedLabel) ?? \"Copied!\",\n };\n}\n\nfunction resolveLastUpdatedDisplayConfig(docs: FarmDocsResolvedConfig): LastUpdatedDisplayConfig {\n const raw = docs.config.lastUpdated;\n const options = isObjectRecord(raw) ? raw : {};\n\n return {\n enabled: raw !== false && (!isObjectRecord(raw) || raw.enabled !== false),\n label: typeof options.label === \"string\" ? options.label : \"Last updated\",\n position: options.position === \"below-title\" ? \"below-title\" : \"footer\",\n };\n}\n\nfunction formatLastModifiedDate(value: string | undefined): string | undefined {\n if (!value) return undefined;\n\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) return value;\n\n return new Intl.DateTimeFormat(\"en\", {\n day: \"numeric\",\n month: \"long\",\n year: \"numeric\",\n }).format(date);\n}\n\nfunction renderLastUpdatedText(\n page: LoadedFarmDocsPage,\n docs: FarmDocsResolvedConfig,\n position: \"footer\" | \"below-title\",\n): string {\n const config = resolveLastUpdatedDisplayConfig(docs);\n const formatted = formatLastModifiedDate(page.lastModified);\n if (!config.enabled || config.position !== position || !formatted) return \"\";\n\n const time = `<time datetime=\"${escapeAttribute(page.lastModified || \"\")}\">${escapeHtml(formatted)}</time>`;\n const label = config.label.trim();\n return label ? `${escapeHtml(label)} ${time}` : time;\n}\n\nfunction resolveReadingTimeDisplayConfig(\n docs: FarmDocsResolvedConfig,\n): ReadingTimeDisplayConfig | null {\n const raw = docs.config.readingTime;\n if (raw === undefined || raw === false) return null;\n\n const options = isObjectRecord(raw) ? raw : {};\n if (isObjectRecord(raw) && options.enabled === false) return null;\n\n const wordsPerMinute =\n typeof options.wordsPerMinute === \"number\" && options.wordsPerMinute > 0\n ? options.wordsPerMinute\n : 220;\n\n return {\n wordsPerMinute,\n format: options.format === \"short\" ? \"short\" : \"long\",\n includeCode: options.includeCode === true,\n };\n}\n\nfunction countMarkdownWords(body: string, includeCode: boolean): number {\n const readable = (\n includeCode ? body : body.replace(/```[\\s\\S]*?```/g, \" \").replace(/`[^`]*`/g, \" \")\n )\n .replace(/!\\[[^\\]]*]\\([^)]*\\)/g, \" \")\n .replace(/\\[([^\\]]+)]\\([^)]*\\)/g, \"$1\")\n .replace(/<[^>]+>/g, \" \")\n .replace(/[#>*_~`|:-]/g, \" \");\n\n return readable.match(/[A-Za-z0-9]+(?:[-'][A-Za-z0-9]+)*/g)?.length ?? 0;\n}\n\nfunction renderReadingTimeMeta(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n const config = resolveReadingTimeDisplayConfig(docs);\n if (!config) return \"\";\n\n const words = countMarkdownWords(page.body, config.includeCode);\n const minutes = Math.max(1, Math.ceil(words / config.wordsPerMinute));\n const label = config.format === \"short\" ? `${minutes} min` : `${minutes} min read`;\n\n return `<div class=\"fd-page-meta not-prose\" data-page-reading-time>\n <span class=\"fd-page-meta-dot\" aria-hidden=\"true\">·</span>\n <span class=\"fd-page-meta-item\">${escapeHtml(label)}</span>\n</div>`;\n}\n\nfunction renderPixelPageActions(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n const copyMarkdown = resolveCopyMarkdownActionConfig(docs);\n if (!copyMarkdown) return \"\";\n\n const markdownUrl = `${page.href}.md`;\n const includeTitle = copyMarkdown.includeTitle ? \"true\" : \"false\";\n\n return `<div class=\"fd-page-actions\" data-page-actions data-actions-alignment=\"${resolvePageActionsAlignment(docs)}\">\n <button\n type=\"button\"\n class=\"fd-page-action-btn\"\n data-page-action=\"copy-markdown\"\n data-copied=\"false\"\n data-markdown-url=\"${escapeAttribute(markdownUrl)}\"\n data-copy-markdown-format=\"${copyMarkdown.format}\"\n data-copy-markdown-include-title=\"${includeTitle}\"\n data-copy-label=\"${escapeAttribute(copyMarkdown.label)}\"\n data-copied-label=\"${escapeAttribute(copyMarkdown.copiedLabel)}\"\n aria-label=\"${escapeAttribute(copyMarkdown.label)}\"\n title=\"${escapeAttribute(copyMarkdown.label)}\"\n >\n <svg class=\"fd-page-action-copy-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path></svg>\n <svg class=\"fd-page-action-check-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M20 6 9 17l-5-5\"></path></svg>\n <span data-page-action-label>${escapeHtml(copyMarkdown.label)}</span>\n </button>\n</div>`;\n}\n\nfunction renderBelowTitleMeta(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n const lastUpdated = renderLastUpdatedText(page, docs, \"below-title\");\n const actions = renderPixelPageActions(page, docs);\n const readingTime = renderReadingTimeMeta(page, docs);\n if (!lastUpdated && !actions && !readingTime) return \"\";\n\n return `<div class=\"fd-below-title-block not-prose\">\n ${lastUpdated ? `<p class=\"fd-last-updated-inline\">${lastUpdated}</p>` : \"\"}\n ${actions}\n ${readingTime}\n</div>`;\n}\n\nfunction renderMarkdownHtmlWithTitleMeta(\n page: LoadedFarmDocsPage,\n docs: FarmDocsResolvedConfig,\n): string {\n const html = renderMarkdownHtml(page.body);\n const meta = renderBelowTitleMeta(page, docs);\n if (!meta) return html;\n\n const withTitleMeta = html.replace(/(<h1\\b[\\s\\S]*?<\\/h1>)/, `$1\\n${meta}`);\n return withTitleMeta === html ? `${meta}\\n${html}` : withTitleMeta;\n}\n\nfunction renderPixelPageFooter(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n const lastUpdated = renderLastUpdatedText(page, docs, \"footer\");\n if (!lastUpdated) return \"\";\n\n return `<div class=\"not-prose fd-page-footer\">\n <span class=\"fd-last-updated-footer\">${lastUpdated}</span>\n</div>`;\n}\n\nfunction getDocsLlmsOptions(docs: FarmDocsResolvedConfig, request: Request) {\n const configured =\n typeof docs.config.llmsTxt === \"object\" && docs.config.llmsTxt !== null\n ? docs.config.llmsTxt\n : {};\n return {\n enabled: true,\n baseUrl: new URL(request.url).origin,\n siteTitle: getDocsTitle(docs),\n siteDescription: getDocsDescription(docs),\n ...configured,\n };\n}\n\nfunction getDocsDiscoveryOptions(docs: FarmDocsResolvedConfig, request: Request) {\n return {\n origin: new URL(request.url).origin,\n entry: docs.entry,\n i18n: null,\n search: docs.config.search ?? true,\n mcp: {\n enabled: false,\n route: \"/api/docs/mcp\",\n name: `${getDocsTitle(docs)} MCP`,\n version: \"1\",\n tools: {\n listDocs: false,\n listPages: false,\n readPage: false,\n searchDocs: false,\n getNavigation: false,\n getCodeExamples: false,\n getConfigSchema: false,\n },\n },\n feedback: undefined,\n llms: getDocsLlmsOptions(docs, request),\n sitemap: docs.config.sitemap ?? true,\n robots: docs.config.robots ?? true,\n openapi: undefined,\n markdown: {\n acceptHeader: true,\n signatureAgentHeader: true,\n },\n };\n}\n\nfunction createFarmDocsPublicResponse(\n contentDir: string,\n docs: FarmDocsResolvedConfig,\n request: Request,\n): Response | null {\n const url = new URL(request.url);\n const loadedPages = getLoadedDocsPages(contentDir, docs);\n const sitemapManifest = () =>\n buildDocsSitemapManifest({\n pages: loadedPages.map(toDocsSitemapPage),\n entry: docs.entry,\n siteTitle: getDocsTitle(docs),\n baseUrl: url.origin,\n });\n const textHeaders = (contentType: string) => ({\n \"Content-Type\": contentType,\n \"Cache-Control\": \"public, max-age=60\",\n });\n\n const llmsFormat = resolveDocsLlmsTxtFormat(url);\n if (llmsFormat) {\n const generated = renderDocsLlmsTxt(\n loadedPages.map(toDocsLlmsPage),\n getDocsLlmsOptions(docs, request),\n );\n return new Response(llmsFormat === \"llms-full\" ? generated.llmsFullTxt : generated.llmsTxt, {\n status: 200,\n headers: textHeaders(\"text/plain; charset=utf-8\"),\n });\n }\n\n const sitemapFormat = resolveDocsSitemapRequest(url, docs.config.sitemap ?? true);\n if (sitemapFormat === \"xml\") {\n return new Response(\n renderDocsSitemapXml(sitemapManifest(), {\n baseUrl: url.origin,\n includeLastmod: true,\n }),\n {\n status: 200,\n headers: textHeaders(\"application/xml; charset=utf-8\"),\n },\n );\n }\n if (sitemapFormat === \"markdown\") {\n return new Response(\n renderDocsSitemapMarkdown(sitemapManifest(), {\n includeDescriptions: true,\n }),\n {\n status: 200,\n headers: textHeaders(\"text/markdown; charset=utf-8\"),\n },\n );\n }\n\n if (resolveDocsRobotsRequest(url, docs.config.robots ?? true)) {\n return new Response(\n renderDocsRobotsTxt({\n entry: docs.entry,\n sitemap: docs.config.sitemap ?? true,\n robots: docs.config.robots ?? true,\n baseUrl: url.origin,\n }),\n {\n status: 200,\n headers: textHeaders(\"text/plain; charset=utf-8\"),\n },\n );\n }\n\n if (isDocsAgentDiscoveryRequest(url)) {\n const spec = buildDocsAgentDiscoverySpec(getDocsDiscoveryOptions(docs, request));\n const title = getDocsTitle(docs);\n return new Response(\n JSON.stringify({\n ...spec,\n name: title,\n site: {\n ...spec.site,\n title,\n description: getDocsDescription(docs),\n entry: docs.entry,\n },\n }),\n {\n status: 200,\n headers: textHeaders(\"application/json; charset=utf-8\"),\n },\n );\n }\n\n if (isDocsAgentsRequest(url)) {\n return new Response(\n `${renderDocsAgentsDocument(getDocsDiscoveryOptions(docs, request)).trim()}\\n`,\n {\n status: 200,\n headers: textHeaders(\"text/markdown; charset=utf-8\"),\n },\n );\n }\n\n if (isDocsSkillRequest(url)) {\n return new Response(\n `${renderDocsSkillDocument(getDocsDiscoveryOptions(docs, request)).trim()}\\n`,\n {\n status: 200,\n headers: textHeaders(\"text/markdown; charset=utf-8\"),\n },\n );\n }\n\n return null;\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\nfunction shouldReturnMarkdown(request: Request): boolean {\n const url = new URL(request.url);\n return (\n url.pathname.endsWith(\".md\") ||\n request.headers.get(\"accept\")?.includes(\"text/markdown\") === true ||\n request.headers.get(\"accept\")?.includes(\"text/plain\") === true\n );\n}\n\nfunction escapeAttribute(value: string): string {\n return escapeHtml(value).replace(/'/g, \"&#39;\");\n}\n\nfunction slugify(value: string): string {\n return value\n .toLowerCase()\n .replace(/<[^>]+>/g, \"\")\n .replace(/`([^`]+)`/g, \"$1\")\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\nfunction createSlugger() {\n const seen = new Map<string, number>();\n\n return (value: string) => {\n const base = slugify(value) || \"section\";\n const count = seen.get(base) || 0;\n seen.set(base, count + 1);\n return count === 0 ? base : `${base}-${count + 1}`;\n };\n}\n\nfunction stripHtml(value: string): string {\n return value.replace(/<[^>]+>/g, \"\");\n}\n\nfunction getCodeFence(line: string): { marker: \"`\" | \"~\"; length: number } | null {\n const match = /^(?: {0,3})(`{3,}|~{3,})/.exec(line);\n const value = match?.[1];\n if (!value) return null;\n return { marker: value[0] as \"`\" | \"~\", length: value.length };\n}\n\nfunction isClosingCodeFence(line: string, fence: { marker: \"`\" | \"~\"; length: number }): boolean {\n const trimmed = line.trim();\n return (\n trimmed.length >= fence.length && Array.from(trimmed).every((char) => char === fence.marker)\n );\n}\n\nfunction stripMdxRuntimeSyntax(body: string): string {\n const output: string[] = [];\n let fence: { marker: \"`\" | \"~\"; length: number } | null = null;\n\n for (const line of body.split(\"\\n\")) {\n const nextFence = getCodeFence(line);\n if (fence) {\n output.push(line);\n if (nextFence && nextFence.marker === fence.marker && isClosingCodeFence(line, fence)) {\n fence = null;\n }\n continue;\n }\n\n if (nextFence) {\n fence = nextFence;\n output.push(line);\n continue;\n }\n\n if (/^\\s*import\\s.+$/.test(line) || /^\\s*export\\s+(const|default)\\s.+$/.test(line)) {\n continue;\n }\n\n output.push(line);\n }\n\n return output.join(\"\\n\");\n}\n\nfunction unescapeHtml(value: string): string {\n return value\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&amp;/g, \"&\");\n}\n\nconst CODE_LANGUAGE_LABELS = new Set([\n \"bash\",\n \"cjs\",\n \"cmd\",\n \"console\",\n \"css\",\n \"html\",\n \"javascript\",\n \"js\",\n \"json\",\n \"jsx\",\n \"md\",\n \"mdx\",\n \"shell\",\n \"sh\",\n \"terminal\",\n \"text\",\n \"ts\",\n \"tsx\",\n \"txt\",\n \"typescript\",\n \"yaml\",\n \"yml\",\n \"zsh\",\n]);\n\nconst EXTENSIONLESS_CODE_FILENAMES = new Set([\n \"dockerfile\",\n \"makefile\",\n \"procfile\",\n \"readme\",\n \"license\",\n]);\n\nfunction isCodePathLabel(label: string): boolean {\n const trimmed = label.trim();\n if (!trimmed || /\\s/.test(trimmed)) return false;\n\n const lower = trimmed.toLowerCase();\n if (CODE_LANGUAGE_LABELS.has(lower)) return false;\n\n const fileName = trimmed.split(/[\\\\/]/).filter(Boolean).pop() || trimmed;\n const lowerFileName = fileName.toLowerCase();\n if (EXTENSIONLESS_CODE_FILENAMES.has(lowerFileName)) return true;\n if (fileName.startsWith(\".\") && fileName.length > 1) return true;\n\n return /\\.[a-z0-9][a-z0-9-]*$/i.test(fileName);\n}\n\nfunction parseCodeInfo(info: string | undefined): {\n language: string;\n label: string;\n hasExplicitLabel: boolean;\n} {\n const source = (info || \"\").trim();\n const language = source.match(/^\\S+/)?.[0] || \"text\";\n const explicitLabel = source\n .match(/\\b(?:title|filename|file|label|name)=[\"']([^\"']+)[\"']/)?.[1]\n ?.trim();\n return { language, label: explicitLabel || language, hasExplicitLabel: Boolean(explicitLabel) };\n}\n\nfunction getStandaloneCodeLabel(line: string): string | null {\n const trimmed = line.trim();\n const match = /^(?:\\*\\*([^*]+)\\*\\*|__([^_]+)__|`([^`]+)`)$/u.exec(trimmed);\n const label = match?.[1] || match?.[2] || match?.[3];\n return label?.trim() || null;\n}\n\nfunction hasCodeFenceTitle(info: string): boolean {\n return /\\b(?:title|filename|file|label|name)=[\"'][^\"']+[\"']/.test(info);\n}\n\nfunction escapeCodeFenceTitle(value: string): string {\n return value.replace(/\"/g, \"&quot;\");\n}\n\nfunction addTitleToCodeFence(line: string, title: string): string {\n const match = /^(\\s{0,3})(`{3,}|~{3,})(.*)$/u.exec(line);\n if (!match) return line;\n const [, indent, marker, infoSource] = match;\n const info = infoSource.trim();\n if (hasCodeFenceTitle(info)) return line;\n const suffix = `title=\"${escapeCodeFenceTitle(title)}\"`;\n return `${indent}${marker}${info ? `${info} ${suffix}` : `text ${suffix}`}`;\n}\n\nfunction attachCodeBlockLabels(body: string): string {\n const lines = body.split(\"\\n\");\n const output: string[] = [];\n let fence: { marker: \"`\" | \"~\"; length: number } | null = null;\n\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index] || \"\";\n const nextFence = getCodeFence(line);\n\n if (fence) {\n output.push(line);\n if (nextFence && nextFence.marker === fence.marker && isClosingCodeFence(line, fence)) {\n fence = null;\n }\n continue;\n }\n\n if (nextFence) {\n fence = nextFence;\n output.push(line);\n continue;\n }\n\n const label = getStandaloneCodeLabel(line);\n if (!label) {\n output.push(line);\n continue;\n }\n\n let fenceIndex = index + 1;\n while (fenceIndex < lines.length && (lines[fenceIndex] || \"\").trim() === \"\") {\n fenceIndex += 1;\n }\n\n const labeledFence = getCodeFence(lines[fenceIndex] || \"\");\n if (!labeledFence) {\n output.push(line);\n continue;\n }\n\n output.push(addTitleToCodeFence(lines[fenceIndex] || \"\", label));\n fence = labeledFence;\n index = fenceIndex;\n }\n\n return output.join(\"\\n\");\n}\n\nfunction highlightCodeBlock(code: string): string {\n return highlight(code.replace(/\\n$/, \"\")).replace(/<\\/span>\\n<span/g, \"</span><span\");\n}\n\nfunction renderCodeCopyButton(className = \"code-copy\"): string {\n return `<button class=\"${className}\" type=\"button\" data-copied=\"false\" aria-label=\"Copy code\" title=\"Copy code\" onclick=\"navigator.clipboard?.writeText(this.closest('figure').querySelector('code').innerText); this.dataset.copied='true'; this.setAttribute('aria-label','Copied'); this.title='Copied'; clearTimeout(this._copyTimer); this._copyTimer=setTimeout(() => { this.dataset.copied='false'; this.setAttribute('aria-label','Copy code'); this.title='Copy code'; }, 4500);\"><svg class=\"code-copy-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><rect x=\"9\" y=\"9\" width=\"13\" height=\"13\" rx=\"2\" ry=\"2\"></rect><path d=\"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1\"></path></svg><svg class=\"code-copy-check\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><path d=\"M20 6 9 17l-5-5\"></path></svg></button>`;\n}\n\nfunction renderMarkdownHtml(body: string): string {\n const slug = createSlugger();\n const renderer = new Renderer();\n\n renderer.heading = (text, level, raw) => {\n const id = slug(raw || stripHtml(text));\n return `<h${level} id=\"${escapeAttribute(id)}\"><a class=\"heading-anchor\" href=\"#${escapeAttribute(id)}\">${text}</a></h${level}>\\n`;\n };\n\n renderer.code = (code, infostring, escaped) => {\n const { language, label, hasExplicitLabel } = parseCodeInfo(infostring);\n const rawCode = escaped ? unescapeHtml(code) : code;\n const highlighted = highlightCodeBlock(rawCode);\n const shouldRenderHeader = hasExplicitLabel && isCodePathLabel(label);\n const header = shouldRenderHeader\n ? `<div class=\"code-block-header\">\n <span class=\"code-block-title\">${escapeHtml(label)}</span>\n ${renderCodeCopyButton()}\n </div>`\n : renderCodeCopyButton(\"code-copy code-copy-floating\");\n\n return `<figure class=\"shiki code-block ${shouldRenderHeader ? \"code-block-framed\" : \"code-block-plain\"}\" data-language=\"${escapeAttribute(language)}\">\n ${header}\n <pre><code class=\"sh-code language-${escapeAttribute(language)}\">${highlighted}</code></pre>\n</figure>\\n`;\n };\n\n renderer.table = (header, body) =>\n `<div class=\"fd-table-wrapper table-wrap relative overflow-auto prose-no-margin my-6\"><table><thead>${header}</thead><tbody>${body}</tbody></table></div>\\n`;\n\n renderer.blockquote = (quote) => `<blockquote>${quote}</blockquote>\\n`;\n renderer.codespan = (code) => `<code>${escapeHtml(code)}</code>`;\n\n renderer.link = (href, title, text) => {\n const safeHref = href || \"\";\n const titleAttribute = title ? ` title=\"${escapeAttribute(title)}\"` : \"\";\n return `<a href=\"${escapeAttribute(safeHref)}\"${titleAttribute}>${text}</a>`;\n };\n\n renderer.image = (href, title, text) => {\n const titleAttribute = title ? ` title=\"${escapeAttribute(title)}\"` : \"\";\n return `<img src=\"${escapeAttribute(href)}\" alt=\"${escapeAttribute(text)}\"${titleAttribute}>`;\n };\n\n const html = marked(attachCodeBlockLabels(stripMdxRuntimeSyntax(body)), {\n async: false,\n breaks: false,\n gfm: true,\n renderer,\n }) as string;\n\n return html.trim();\n}\n\ninterface TocItem {\n id: string;\n title: string;\n level: number;\n}\n\nfunction extractTocItems(body: string, depth: number): TocItem[] {\n const slug = createSlugger();\n const maxLevel = Math.max(2, Math.min(depth, 6));\n\n return body\n .split(/\\r?\\n/)\n .map((line) => line.match(/^(#{2,6})\\s+(.+)$/))\n .filter((match): match is RegExpMatchArray => Boolean(match))\n .map((match) => ({\n id: slug(match[2].trim()),\n title: match[2].trim(),\n level: match[1].length,\n }))\n .filter((item) => item.level <= maxLevel);\n}\n\nfunction getThemeUI(docs: FarmDocsResolvedConfig): Record<string, any> {\n const theme = docs.config.theme;\n return theme && typeof theme === \"object\" && \"ui\" in theme && typeof theme.ui === \"object\"\n ? (theme.ui as Record<string, any>)\n : {};\n}\n\nfunction getThemeName(docs: FarmDocsResolvedConfig): string {\n const theme = docs.config.theme;\n return theme && typeof theme === \"object\" && \"name\" in theme\n ? String((theme as { name?: unknown }).name || \"farm-docs\")\n : \"farm-docs\";\n}\n\nfunction getThemeLayoutValue(docs: FarmDocsResolvedConfig, key: string, fallback: number): number {\n const layout = getThemeUI(docs).layout;\n const value =\n layout && typeof layout === \"object\" ? (layout as Record<string, unknown>)[key] : undefined;\n return typeof value === \"number\" ? value : fallback;\n}\n\nfunction getThemeTocDepth(docs: FarmDocsResolvedConfig): number {\n const toc = getThemeUI(docs).layout?.toc;\n return toc && typeof toc === \"object\" && typeof toc.depth === \"number\" ? toc.depth : 3;\n}\n\nconst SIDEBAR_SECTION_ORDER = [\n \"Start\",\n \"Core\",\n \"Data and APIs\",\n \"Integrations\",\n \"Runtime\",\n \"Content\",\n \"Extending\",\n \"Reference\",\n];\n\nconst SIDEBAR_PAGE_ORDER = new Map(\n [\n \"\",\n \"getting-started\",\n \"project-structure\",\n \"configuration\",\n \"routing\",\n \"layouts\",\n \"server-rendering\",\n \"middleware\",\n \"query\",\n \"api-routes\",\n \"api-client\",\n \"storage\",\n \"integrations\",\n \"integrations/stripe\",\n \"integrations/autumn\",\n \"integrations/polar\",\n \"integrations/auth\",\n \"integrations/email\",\n \"integrations/jobs\",\n \"integrations/unkey\",\n \"integrations/ui-registry\",\n \"integrations/orm-storage\",\n \"cache-ppr\",\n \"observability\",\n \"deployment\",\n \"docs-engine\",\n \"markdown\",\n \"openapi\",\n \"plugins\",\n \"plugins/create-plugin\",\n \"cli\",\n \"examples\",\n \"reference\",\n ].map((slug, index) => [slug, index]),\n);\n\ntype SidebarNavigationItem = {\n label?: string;\n icon?: string;\n slug?: string;\n href?: string;\n children: SidebarNavigationItem[];\n};\n\nfunction isSidebarNavigationItem(\n value: SidebarNavigationItem | null,\n): value is SidebarNavigationItem {\n return value !== null;\n}\n\nfunction compareSidebarPages(a: FarmDocsPage, b: FarmDocsPage): number {\n const aOrder = SIDEBAR_PAGE_ORDER.get(a.slug) ?? 1000;\n const bOrder = SIDEBAR_PAGE_ORDER.get(b.slug) ?? 1000;\n return aOrder - bOrder || a.title.localeCompare(b.title);\n}\n\nfunction getSidebarSection(page: FarmDocsPage): string {\n if (page.section) return page.section;\n if (page.slug.startsWith(\"integrations/\")) return \"Integrations\";\n if (page.slug.startsWith(\"plugins/\")) return \"Extending\";\n return \"Reference\";\n}\n\nfunction sidebarIdFor(section: string): string {\n return `sidebar-${slugify(section)}`;\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction readString(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction readOptionalString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value.trim() : undefined;\n}\n\nfunction normalizeSidebarSlug(value: string): string {\n if (value === \"/\" || value === \".\") return \"\";\n return trimSlashes(value);\n}\n\nfunction getSidebarNavigation(docs: FarmDocsResolvedConfig): SidebarNavigationItem[] {\n const navigation = docs.config.navigation;\n if (!isObjectRecord(navigation) || !Array.isArray(navigation.sidebar)) return [];\n return navigation.sidebar.map(normalizeSidebarNavigationItem).filter(isSidebarNavigationItem);\n}\n\nfunction normalizeSidebarNavigationItem(value: unknown): SidebarNavigationItem | null {\n if (!isObjectRecord(value)) return null;\n\n const label = readString(value.label) ?? readString(value.title);\n const icon = readString(value.icon);\n const slug = readOptionalString(value.slug) ?? readOptionalString(value.path);\n const href = readString(value.href) ?? readString(value.url);\n const rawChildren = Array.isArray(value.children)\n ? value.children\n : Array.isArray(value.items)\n ? value.items\n : [];\n const children = rawChildren.map(normalizeSidebarNavigationItem).filter(isSidebarNavigationItem);\n\n if (!label && !slug && !href && children.length === 0) return null;\n return {\n ...(label ? { label } : {}),\n ...(icon ? { icon } : {}),\n ...(slug !== undefined ? { slug: normalizeSidebarSlug(slug) } : {}),\n ...(href ? { href } : {}),\n children,\n };\n}\n\nfunction createSidebarPageMaps(pages: FarmDocsPage[]) {\n return {\n bySlug: new Map(pages.map((page) => [page.slug, page])),\n byHref: new Map(pages.map((page) => [page.href, page])),\n };\n}\n\nfunction resolveConfiguredSidebarPage(\n item: SidebarNavigationItem,\n maps: ReturnType<typeof createSidebarPageMaps>,\n): FarmDocsPage | undefined {\n if (item.slug !== undefined) return maps.bySlug.get(item.slug);\n if (item.href) return maps.byHref.get(item.href);\n return undefined;\n}\n\nfunction getSidebarIconRegistry(docs: FarmDocsResolvedConfig): Record<string, unknown> {\n return isObjectRecord(docs.config.icons) ? docs.config.icons : {};\n}\n\nfunction renderConfiguredIconSvg(value: unknown): string {\n if (typeof value !== \"string\") return \"\";\n const icon = value.trim();\n if (!icon) return \"\";\n if (/^<svg[\\s>]/i.test(icon)) return icon;\n if (/^<(path|circle|rect|line|polyline|polygon|ellipse|g)\\b/i.test(icon)) {\n return `<svg viewBox=\"0 0 24 24\" focusable=\"false\">${icon}</svg>`;\n }\n return \"\";\n}\n\nfunction renderSidebarIcon(\n docs: FarmDocsResolvedConfig,\n icon: string | undefined,\n className = \"sidebar-icon\",\n): string {\n if (!icon) return \"\";\n const iconRegistry = getSidebarIconRegistry(docs);\n const configuredIcon = iconRegistry[icon] ?? icon;\n const svg = renderConfiguredIconSvg(configuredIcon);\n if (!svg) return \"\";\n return `<span class=\"${className}\" data-sidebar-icon=\"${escapeAttribute(icon)}\" aria-hidden=\"true\">${svg}</span>`;\n}\n\nfunction renderSidebarLabel(\n docs: FarmDocsResolvedConfig,\n icon: string | undefined,\n label: string,\n className: string,\n): string {\n return `<span class=\"${className}\">${renderSidebarIcon(docs, icon)}<span class=\"sidebar-label-text\">${escapeHtml(label)}</span></span>`;\n}\n\nfunction getSidebarPageLabel(item: FarmDocsPage, configured?: SidebarNavigationItem): string {\n if (configured?.label) return configured.label;\n if (item.slug === \"\") return \"Why?\";\n if (item.slug === \"integrations\") return \"Overview\";\n if (item.slug === \"integrations/ui-registry\") return \"UI Registry\";\n if (item.slug === \"integrations/orm-storage\") return \"ORM Storage\";\n if (item.slug.startsWith(\"integrations/\")) {\n return item.title.replace(/\\s+Integrations?$/i, \"\");\n }\n return item.title;\n}\n\nfunction renderSidebarLink(\n item: FarmDocsPage,\n activeHref: string,\n docs: FarmDocsResolvedConfig,\n configured?: SidebarNavigationItem,\n): string {\n const active = item.href === activeHref;\n return `<a data-active=\"${active ? \"true\" : \"false\"}\" href=\"${escapeAttribute(item.href)}\">${renderSidebarLabel(docs, configured?.icon, getSidebarPageLabel(item, configured), \"sidebar-link-label\")}</a>`;\n}\n\nfunction collectConfiguredSidebarPages(\n items: SidebarNavigationItem[],\n maps: ReturnType<typeof createSidebarPageMaps>,\n seen = new Set<string>(),\n): FarmDocsPage[] {\n const ordered: FarmDocsPage[] = [];\n for (const item of items) {\n const page = resolveConfiguredSidebarPage(item, maps);\n if (page && !seen.has(page.slug)) {\n seen.add(page.slug);\n ordered.push(page);\n }\n ordered.push(...collectConfiguredSidebarPages(item.children, maps, seen));\n }\n return ordered;\n}\n\nfunction getOrderedSidebarPages(\n pages: FarmDocsPage[],\n docs?: FarmDocsResolvedConfig,\n): FarmDocsPage[] {\n if (!docs) return [...pages].sort(compareSidebarPages);\n\n const maps = createSidebarPageMaps(pages);\n const configuredPages = collectConfiguredSidebarPages(getSidebarNavigation(docs), maps);\n if (configuredPages.length === 0) return [...pages].sort(compareSidebarPages);\n\n const configuredSlugs = new Set(configuredPages.map((page) => page.slug));\n const remainingPages = pages\n .filter((page) => !configuredSlugs.has(page.slug))\n .sort(compareSidebarPages);\n return [...configuredPages, ...remainingPages];\n}\n\nfunction renderExternalSidebarLink(\n item: SidebarNavigationItem,\n activeHref: string,\n docs: FarmDocsResolvedConfig,\n): string {\n if (!item.href || !item.label) return \"\";\n const active = item.href === activeHref;\n return `<a data-active=\"${active ? \"true\" : \"false\"}\" href=\"${escapeAttribute(item.href)}\">${renderSidebarLabel(docs, item.icon, item.label, \"sidebar-link-label\")}</a>`;\n}\n\nfunction renderConfiguredSidebarSubgroup(\n item: SidebarNavigationItem,\n childHtml: string,\n docs: FarmDocsResolvedConfig,\n): string {\n const label = item.label;\n if (!label) return childHtml;\n return `<div class=\"sidebar-subgroup\" data-sidebar-subgroup=\"${escapeAttribute(slugify(label))}\">\n <div class=\"sidebar-subgroup-title\">${renderSidebarLabel(docs, item.icon, label, \"sidebar-subgroup-label\")}</div>\n <div class=\"sidebar-subgroup-content\">\n${childHtml}\n </div>\n</div>`;\n}\n\nfunction renderConfiguredSidebarItems(\n items: SidebarNavigationItem[],\n maps: ReturnType<typeof createSidebarPageMaps>,\n activeHref: string,\n docs: FarmDocsResolvedConfig,\n): string {\n const renderedItems: string[] = [];\n for (const item of items) {\n const page = resolveConfiguredSidebarPage(item, maps);\n const childHtml = renderConfiguredSidebarItems(item.children, maps, activeHref, docs);\n\n if (item.children.length > 0) {\n renderedItems.push(renderConfiguredSidebarSubgroup(item, childHtml, docs));\n continue;\n }\n\n const linkHtml = page\n ? renderSidebarLink(page, activeHref, docs, item)\n : renderExternalSidebarLink(item, activeHref, docs);\n if (linkHtml) renderedItems.push(linkHtml);\n }\n return renderedItems.join(\"\\n\");\n}\n\nfunction renderConfiguredSidebarSection(\n section: SidebarNavigationItem,\n maps: ReturnType<typeof createSidebarPageMaps>,\n activeHref: string,\n docs: FarmDocsResolvedConfig,\n): string {\n const label = section.label || \"Docs\";\n const id = sidebarIdFor(label);\n const links = renderConfiguredSidebarItems(section.children, maps, activeHref, docs);\n return `<div class=\"sidebar-folder\" data-state=\"open\">\n <button class=\"text-fd-muted-foreground sidebar-folder-trigger\" type=\"button\" aria-controls=\"${escapeAttribute(id)}\" aria-expanded=\"true\">${renderSidebarLabel(docs, section.icon, label, \"sidebar-folder-label\")}</button>\n <div id=\"${escapeAttribute(id)}\" class=\"overflow-hidden sidebar-folder-content\" data-state=\"open\">\n${links}\n </div>\n</div>`;\n}\n\nfunction renderAutoSidebarSectionItems(\n items: FarmDocsPage[],\n activeHref: string,\n docs: FarmDocsResolvedConfig,\n): string {\n return [...items]\n .sort(compareSidebarPages)\n .map((item) => renderSidebarLink(item, activeHref, docs))\n .join(\"\\n\");\n}\n\nfunction renderPixelNavItems(\n pages: FarmDocsPage[],\n activeHref: string,\n docs: FarmDocsResolvedConfig,\n): string {\n const configuredSidebar = getSidebarNavigation(docs);\n if (configuredSidebar.length > 0) {\n const maps = createSidebarPageMaps(pages);\n const renderedSections = configuredSidebar\n .map((section) => {\n if (section.children.length > 0) {\n return renderConfiguredSidebarSection(section, maps, activeHref, docs);\n }\n const page = resolveConfiguredSidebarPage(section, maps);\n return page\n ? renderSidebarLink(page, activeHref, docs, section)\n : renderExternalSidebarLink(section, activeHref, docs);\n })\n .filter(Boolean)\n .join(\"\\n\");\n\n return `<div class=\"sidebar-scroll overscroll-contain\">\n <div class=\"sidebar-tree\">\n${renderedSections}\n </div>\n</div>`;\n }\n\n const groups = new Map<string, FarmDocsPage[]>();\n for (const item of pages) {\n const group = item.slug === \"\" ? \"Start\" : getSidebarSection(item);\n const entries = groups.get(group) ?? [];\n entries.push(item);\n groups.set(group, entries);\n }\n\n const renderedSections = Array.from(groups.entries())\n .sort(([a], [b]) => {\n const aOrder = SIDEBAR_SECTION_ORDER.indexOf(a);\n const bOrder = SIDEBAR_SECTION_ORDER.indexOf(b);\n return (aOrder === -1 ? 100 : aOrder) - (bOrder === -1 ? 100 : bOrder) || a.localeCompare(b);\n })\n .map(([section, items]) => {\n const id = sidebarIdFor(section);\n const links = renderAutoSidebarSectionItems(items, activeHref, docs);\n return `<div class=\"sidebar-folder\" data-state=\"open\">\n <button class=\"text-fd-muted-foreground sidebar-folder-trigger\" type=\"button\" aria-controls=\"${escapeAttribute(id)}\" aria-expanded=\"true\">${renderSidebarLabel(docs, undefined, section, \"sidebar-folder-label\")}</button>\n <div id=\"${escapeAttribute(id)}\" class=\"overflow-hidden sidebar-folder-content\" data-state=\"open\">\n${links}\n </div>\n</div>`;\n })\n .join(\"\\n\");\n\n return `<div class=\"sidebar-scroll overscroll-contain\">\n <div class=\"sidebar-tree\">\n${renderedSections}\n </div>\n</div>`;\n}\n\nfunction renderPixelPageNav(\n pages: FarmDocsPage[],\n activeHref: string,\n docs: FarmDocsResolvedConfig,\n): string {\n const orderedPages = getOrderedSidebarPages(pages, docs);\n const activeIndex = orderedPages.findIndex((item) => item.href === activeHref);\n if (activeIndex === -1) return \"\";\n\n const previous = orderedPages[activeIndex - 1];\n const next = orderedPages[activeIndex + 1];\n if (!previous && !next) return \"\";\n\n const renderChevron = (direction: \"prev\" | \"next\") =>\n `<svg width=\"14\" height=\"14\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><polyline points=\"${direction === \"prev\" ? \"15 18 9 12 15 6\" : \"9 18 15 12 9 6\"}\" /></svg>`;\n const renderCard = (item: FarmDocsPage, direction: \"prev\" | \"next\") =>\n `<a class=\"fd-page-nav-card fd-page-nav-${direction}\" href=\"${escapeAttribute(item.href)}\">\n <span class=\"fd-page-nav-title fd-page-nav-title-${direction}\">${direction === \"prev\" ? `${renderChevron(direction)}${escapeHtml(item.title)}` : `${escapeHtml(item.title)}${renderChevron(direction)}`}</span>\n <span class=\"fd-page-nav-description\">${direction === \"prev\" ? \"Previous Page\" : \"Next Page\"}</span>\n</a>`;\n\n return `<nav class=\"not-prose fd-page-nav\" aria-label=\"Page navigation\">\n ${previous ? renderCard(previous, \"prev\") : \"\"}\n ${next ? renderCard(next, \"next\") : \"\"}\n</nav>`;\n}\n\nfunction titleizePathSegment(value: string): string {\n return value.replace(/[-_]+/g, \" \").replace(/\\b\\w/g, (character) => character.toUpperCase());\n}\n\nfunction isBreadcrumbEnabled(docs: FarmDocsResolvedConfig): boolean {\n const breadcrumb = docs.config.breadcrumb;\n if (breadcrumb === false) return false;\n if (breadcrumb && typeof breadcrumb === \"object\" && \"enabled\" in breadcrumb) {\n return (breadcrumb as { enabled?: unknown }).enabled !== false;\n }\n return true;\n}\n\nfunction renderPixelBreadcrumb(page: LoadedFarmDocsPage, docs: FarmDocsResolvedConfig): string {\n if (!isBreadcrumbEnabled(docs)) return \"\";\n\n const segments = trimSlashes(page.slug).split(\"/\").filter(Boolean);\n if (segments.length < 2) return \"\";\n\n const parentSegments = segments.slice(0, -1);\n const parentSegment = parentSegments[parentSegments.length - 1];\n const currentSegment = segments[segments.length - 1];\n const entry = normalizeEntry(docs.entry);\n const parentPath = parentSegments.join(\"/\");\n const parentHref = entry === \"/\" ? `/${parentPath}` : `${entry}/${parentPath}`;\n\n return `<nav class=\"fd-breadcrumb\" aria-label=\"Breadcrumb\">\n <span class=\"fd-breadcrumb-item\">\n <a class=\"fd-breadcrumb-parent fd-breadcrumb-link\" href=\"${escapeAttribute(parentHref)}\">${escapeHtml(titleizePathSegment(parentSegment))}</a>\n </span>\n <span class=\"fd-breadcrumb-item\">\n <span class=\"fd-breadcrumb-sep\">/</span>\n <span class=\"fd-breadcrumb-current\">${escapeHtml(titleizePathSegment(currentSegment))}</span>\n </span>\n</nav>`;\n}\n\nfunction renderDocsSearchTrigger(showIcon = true): string {\n return `<button class=\"fd-docs-search-trigger\" type=\"button\" data-search-full=\"\" aria-label=\"Search documentation\" aria-haspopup=\"dialog\" aria-keyshortcuts=\"Meta+K Control+K\">\n ${showIcon ? '<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><circle cx=\"11\" cy=\"11\" r=\"7\"></circle><path d=\"m20 20-4-4\"></path></svg>' : \"\"}\n <kbd><span>⌘</span><span>K</span></kbd>\n</button>`;\n}\n\nfunction renderDocsSearchMount(clientEntry: string): string {\n return `<div id=\"farm-docs-search-root\" data-farm-docs-search-root data-api=\"/api/docs\"></div>\n <script type=\"module\" src=\"${escapeAttribute(clientEntry)}\"></script>`;\n}\n\nfunction renderDocsSearchBootstrapScript(): string {\n return `<script>${generateFarmDocsSearchBootstrapRuntime()}</script>`;\n}\n\nfunction renderPixelToc(items: TocItem[]): string {\n if (items.length === 0) return '<p class=\"toc-empty\">No sections</p>';\n return `<div class=\"toc-track\">\n <div class=\"toc-thumb\" data-toc-thumb style=\"clip-path: polygon(0 0px, 100% 0px, 100% 32px, 0 32px);\"></div>\n <div class=\"toc-links\">\n${items\n .map(\n (item) =>\n `<a class=\"toc-link\" data-active=\"${items[0] === item ? \"true\" : \"false\"}\" data-toc-item data-depth=\"${item.level}\" href=\"#${escapeAttribute(item.id)}\">${escapeHtml(item.title)}</a>`,\n )\n .join(\"\\n\")}\n </div>\n</div>`;\n}\n\nfunction renderDocsRuntimeScript(docs: FarmDocsResolvedConfig): string {\n const docsEntry = JSON.stringify(normalizeEntry(docs.entry));\n return `<script>(()=>{if(window.__farmDocsRuntime)return;window.__farmDocsRuntime=true;document.documentElement.dataset.farmDocsRuntime=\"true\";document.documentElement.dataset.farmDocsRuntimeId=Math.random().toString(36).slice(2);const docsEntry=${docsEntry};let cleanupToc=()=>{};let closeMobileSidebar=()=>{};const normalizePath=(path)=>path.length>1?path.replace(/\\\\/+$/,\"\"):path;const isDocsPath=(path)=>{const next=normalizePath(path);const entry=normalizePath(docsEntry);if(next.endsWith(\".md\"))return false;if(entry===\"/\")return true;return next===entry||next.startsWith(entry+\"/\")};const initToc=()=>{cleanupToc();const toc=document.getElementById(\"nd-toc\");if(!toc){cleanupToc=()=>{};return}const links=Array.from(toc.querySelectorAll(\"[data-toc-item]\"));const thumb=toc.querySelector(\"[data-toc-thumb]\");const pairs=links.map((link)=>{let id=link.hash.slice(1);try{id=decodeURIComponent(id)}catch{}return{link,heading:document.getElementById(id)}}).filter((item)=>item.heading);const setActive=(active)=>{for(const {link} of pairs)link.dataset.active=link===active.link?\"true\":\"false\";if(!thumb)return;const styles=getComputedStyle(active.link);const top=active.link.offsetTop+parseFloat(styles.paddingTop||\"0\");const bottom=active.link.offsetTop+active.link.clientHeight-parseFloat(styles.paddingBottom||\"0\");thumb.style.clipPath=\"polygon(0 \"+top+\"px,100% \"+top+\"px,100% \"+bottom+\"px,0 \"+bottom+\"px)\"};const update=()=>{if(pairs.length===0)return;const offset=Math.min(window.innerHeight*0.3,160);let active=pairs[0];for(const pair of pairs){if(pair.heading.getBoundingClientRect().top<=offset)active=pair;else break}setActive(active)};let frame=0;const schedule=()=>{if(frame)return;frame=requestAnimationFrame(()=>{frame=0;update()})};const onHashChange=()=>setTimeout(schedule,0);window.addEventListener(\"scroll\",schedule,{passive:true});window.addEventListener(\"resize\",schedule);window.addEventListener(\"hashchange\",onHashChange);cleanupToc=()=>{window.removeEventListener(\"scroll\",schedule);window.removeEventListener(\"resize\",schedule);window.removeEventListener(\"hashchange\",onHashChange);if(frame)cancelAnimationFrame(frame);frame=0};update()};const getSidebar=()=>document.getElementById(\"nd-sidebar\");const ensureActiveVisible=()=>{const sidebar=getSidebar();if(!sidebar)return;const active=sidebar.querySelector('a[data-active=\"true\"]');if(!(active instanceof HTMLElement))return;const activeRect=active.getBoundingClientRect();const sidebarRect=sidebar.getBoundingClientRect();if(activeRect.top<sidebarRect.top||activeRect.bottom>sidebarRect.bottom)sidebar.scrollTop+=activeRect.top-sidebarRect.top-(sidebar.clientHeight-activeRect.height)/2};const setSidebarActive=(path)=>{const sidebar=getSidebar();if(!sidebar)return;const current=normalizePath(path);for(const link of Array.from(sidebar.querySelectorAll(\"a[href]\"))){try{link.dataset.active=normalizePath(new URL(link.href,location.href).pathname)===current?\"true\":\"false\"}catch{}}ensureActiveVisible()};const initMobileSidebar=()=>{const layout=document.getElementById(\"nd-docs-layout\");const sidebar=getSidebar();const toggle=document.querySelector(\"[data-sidebar-toggle]\");const backdrop=document.querySelector(\"[data-sidebar-backdrop]\");if(!layout||!sidebar||!(toggle instanceof HTMLButtonElement))return;const setOpen=(open)=>{layout.dataset.sidebarOpen=open?\"true\":\"false\";document.documentElement.dataset.farmDocsSidebar=open?\"open\":\"closed\";toggle.setAttribute(\"aria-expanded\",open?\"true\":\"false\");toggle.setAttribute(\"aria-label\",open?\"Close menu\":\"Open menu\")};const toggleOpen=()=>setOpen(layout.dataset.sidebarOpen!==\"true\");closeMobileSidebar=()=>setOpen(false);toggle.addEventListener(\"click\",(event)=>{event.preventDefault();toggleOpen()});backdrop?.addEventListener(\"click\",()=>closeMobileSidebar());document.addEventListener(\"keydown\",(event)=>{if(event.key===\"Escape\")closeMobileSidebar()});sidebar.addEventListener(\"click\",(event)=>{const target=event.target instanceof Element?event.target.closest(\"a[href]\"):null;if(target)closeMobileSidebar()});closeMobileSidebar()};const initSidebarScroll=()=>{const sidebar=getSidebar();if(!sidebar)return;const key=\"farmdocs:sidebar-scroll:\"+location.origin;const getStorage=()=>{try{return window.sessionStorage}catch{return null}};const readSaved=()=>{try{const raw=getStorage()?.getItem(key);if(!raw)return null;const parsed=JSON.parse(raw);return parsed&&typeof parsed===\"object\"?parsed:null}catch{return null}};const save=(path=location.pathname)=>{try{getStorage()?.setItem(key,JSON.stringify({path,scrollTop:sidebar.scrollTop}))}catch{}};const saved=readSaved();if(saved?.path===location.pathname&&Number.isFinite(Number(saved.scrollTop)))sidebar.scrollTop=Number(saved.scrollTop);ensureActiveVisible();save();sidebar.addEventListener(\"scroll\",()=>save(),{passive:true});sidebar.addEventListener(\"click\",(event)=>{const target=event.target instanceof Element?event.target.closest(\"a[href]\"):null;if(!target)return;try{save(new URL(target.href,location.href).pathname)}catch{save()}});window.addEventListener(\"beforeunload\",()=>save())};let navigateController=null;const getPageKey=(root)=>{const article=root.getElementById(\"nd-page\");if(!article)return\"\";return article.querySelector(\"h1\")?.textContent?.trim()||article.textContent?.replace(/\\\\s+/g,\" \").trim().slice(0,160)||\"\"};const swapDocsPage=(html,url)=>{const nextDoc=new DOMParser().parseFromString(html,\"text/html\");const nextArticle=nextDoc.getElementById(\"nd-page\");const currentArticle=document.getElementById(\"nd-page\");if(!nextArticle||!currentArticle)return false;const nextKey=getPageKey(nextDoc);const importedArticle=document.importNode(nextArticle,true);currentArticle.replaceWith(importedArticle);const renderedArticle=document.getElementById(\"nd-page\");if(!renderedArticle||renderedArticle===currentArticle||(nextKey&&getPageKey(document)!==nextKey))return false;const nextToc=nextDoc.getElementById(\"nd-toc\");const currentToc=document.getElementById(\"nd-toc\");if(nextToc&&currentToc)currentToc.replaceWith(document.importNode(nextToc,true));if(nextDoc.title)document.title=nextDoc.title;const nextDescription=nextDoc.querySelector('meta[name=\"description\"]');const currentDescription=document.querySelector('meta[name=\"description\"]');if(nextDescription&&currentDescription)currentDescription.setAttribute(\"content\",nextDescription.getAttribute(\"content\")||\"\");setSidebarActive(url.pathname);initToc();closeMobileSidebar();return true};const navigateDocs=async(url,{replace=false,scroll=true}={})=>{if(!isDocsPath(url.pathname))return false;if(navigateController)navigateController.abort();const controller=new AbortController();navigateController=controller;document.documentElement.dataset.farmDocsNavigating=\"true\";try{const response=await fetch(url.href,{cache:\"no-store\",headers:{accept:\"text/html\",\"x-farm-docs-navigate\":\"1\"},signal:controller.signal});if(!response.ok||!((response.headers.get(\"content-type\")||\"\").includes(\"text/html\")))return false;const html=await response.text();if(!swapDocsPage(html,url))return false;if(replace)history.replaceState({farmDocs:true},\"\",url.href);else history.pushState({farmDocs:true},\"\",url.href);if(scroll){if(url.hash){let id=url.hash.slice(1);try{id=decodeURIComponent(id)}catch{}document.getElementById(id)?.scrollIntoView({block:\"start\"})}else window.scrollTo({top:0,left:0})}return true}catch(error){if(error?.name===\"AbortError\")return true;return false}finally{if(navigateController===controller){delete document.documentElement.dataset.farmDocsNavigating;navigateController=null}}};const initClientNavigation=()=>{document.addEventListener(\"click\",(event)=>{if(event.defaultPrevented||event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey)return;const target=event.target instanceof Element?event.target.closest(\"a[href]\"):null;if(!target||target.target||target.hasAttribute(\"download\"))return;let url;try{url=new URL(target.href,location.href)}catch{return}if(url.origin!==location.origin||!isDocsPath(url.pathname))return;if(normalizePath(url.pathname)===normalizePath(location.pathname)&&url.hash)return;event.preventDefault();navigateDocs(url).then((handled)=>{if(!handled)location.href=url.href})});window.addEventListener(\"popstate\",()=>{navigateDocs(new URL(location.href),{replace:true,scroll:false}).then((handled)=>{if(!handled)location.reload()})})};const init=()=>{initToc();initMobileSidebar();initSidebarScroll();initClientNavigation()};if(document.readyState===\"loading\")document.addEventListener(\"DOMContentLoaded\",init,{once:true});else init()})();</script>`;\n}\n\nfunction renderDocsPageActionsRuntimeScript(): string {\n return `<script>(()=>{if(window.__farmDocsPageActionsRuntime)return;window.__farmDocsPageActionsRuntime=true;const readArticleText=()=>{const article=document.getElementById(\"nd-page\");if(!article)return\"\";const clone=article.cloneNode(true);if(!(clone instanceof HTMLElement))return article.innerText||\"\";clone.querySelectorAll(\"[data-page-actions],.fd-page-footer,.fd-page-nav\").forEach((node)=>node.remove());return clone.innerText||\"\"};const withTitle=(content,format,includeTitle)=>{if(!includeTitle)return content;const title=document.querySelector(\"#nd-page h1\")?.textContent?.trim()||document.title.trim();if(!title)return content;const trimmed=content.trimStart();if(trimmed.startsWith(title)||trimmed.startsWith(\"# \"+title))return content;return format===\"markdown\"?\"# \"+title+\"\\\\n\\\\n\"+content:title+\"\\\\n\\\\n\"+content};const writeClipboard=async(text)=>{if(navigator.clipboard?.writeText){try{await navigator.clipboard.writeText(text);return}catch{}}const textarea=document.createElement(\"textarea\");textarea.value=text;textarea.setAttribute(\"readonly\",\"\");textarea.style.position=\"fixed\";textarea.style.opacity=\"0\";textarea.style.pointerEvents=\"none\";document.body.appendChild(textarea);textarea.select();document.execCommand(\"copy\");textarea.remove()};const markCopied=(button)=>{const label=button.querySelector(\"[data-page-action-label]\");button.dataset.copied=\"true\";button.setAttribute(\"aria-label\",button.dataset.copiedLabel||\"Copied!\");button.title=button.dataset.copiedLabel||\"Copied!\";if(label)label.textContent=button.dataset.copiedLabel||\"Copied!\";const previous=Number(button.dataset.copyTimeout||0);if(previous)clearTimeout(previous);button.dataset.copyTimeout=String(setTimeout(()=>{button.dataset.copied=\"false\";button.setAttribute(\"aria-label\",button.dataset.copyLabel||\"Copy page\");button.title=button.dataset.copyLabel||\"Copy page\";if(label)label.textContent=button.dataset.copyLabel||\"Copy page\";button.dataset.copyTimeout=\"0\"},4500))};document.addEventListener(\"click\",async(event)=>{const target=event.target instanceof Element?event.target.closest('[data-page-action=\"copy-markdown\"]'):null;if(!(target instanceof HTMLButtonElement))return;event.preventDefault();const format=target.dataset.copyMarkdownFormat===\"text\"?\"text\":\"markdown\";const includeTitle=target.dataset.copyMarkdownIncludeTitle===\"true\";let content=\"\";target.disabled=true;try{if(format===\"markdown\"&&target.dataset.markdownUrl){try{const response=await fetch(target.dataset.markdownUrl,{headers:{Accept:\"text/markdown\"}});if(response.ok)content=await response.text()}catch{}}if(!content)content=readArticleText();content=withTitle(content,format,includeTitle);if(content.trim()){await writeClipboard(content);markCopied(target)}}finally{target.disabled=false}})})();</script>`;\n}\n\nfunction renderDocsHashRuntimeScript(): string {\n return `<script>(()=>{if(window.__farmDocsHashRuntime)return;window.__farmDocsHashRuntime=true;const scrollToHash=()=>{if(!location.hash)return;let id=location.hash.slice(1);try{id=decodeURIComponent(id)}catch{}document.getElementById(id)?.scrollIntoView({block:\"start\"})};const schedule=()=>requestAnimationFrame(()=>requestAnimationFrame(scrollToHash));if(document.readyState===\"loading\")document.addEventListener(\"DOMContentLoaded\",schedule,{once:true});else schedule();window.addEventListener(\"load\",schedule,{once:true});window.addEventListener(\"hashchange\",schedule)})();</script>`;\n}\n\nfunction renderDocsRuntimeScripts(docs: FarmDocsResolvedConfig): string {\n return `${renderDocsRuntimeScript(docs)}\n${renderDocsHashRuntimeScript()}\n${renderDocsPageActionsRuntimeScript()}`;\n}\n\nconst themeCssCache = new Map<string, string>();\n\nfunction readCssWithImports(filePath: string, seen = new Set<string>()): string {\n const resolved = path.resolve(filePath);\n if (seen.has(resolved)) return \"\";\n seen.add(resolved);\n\n const source = readFileSync(resolved, \"utf8\");\n return source.replace(/@import\\s+[\"']([^\"']+)[\"'];?/g, (_match, importPath: string) => {\n try {\n const importedPath = importPath.startsWith(\".\")\n ? path.resolve(path.dirname(resolved), importPath)\n : createRequire(resolved).resolve(importPath);\n return readCssWithImports(importedPath, seen);\n } catch {\n return \"\";\n }\n });\n}\n\nfunction resolvePixelBorderThemeCss(options: FarmDocsHandlerOptions): string {\n const cacheKey = path.resolve(options.root);\n const cached = themeCssCache.get(cacheKey);\n if (cached !== undefined) return cached;\n\n try {\n const requireFromApp = createRequire(path.join(cacheKey, \"package.json\"));\n const themeCssPath = requireFromApp.resolve(\"@farming-labs/theme/pixel-border/css\");\n const requireFromTheme = createRequire(themeCssPath);\n const fumadocsCssPath = requireFromTheme.resolve(\"fumadocs-ui/style.css\");\n const css = `${readCssWithImports(fumadocsCssPath)}\\n${readCssWithImports(themeCssPath)}`;\n themeCssCache.set(cacheKey, css);\n return css;\n } catch {\n themeCssCache.set(cacheKey, \"\");\n return \"\";\n }\n}\n\nfunction renderFarmDocsBridgeCss(docs: FarmDocsResolvedConfig): string {\n const sidebarWidth = getThemeLayoutValue(docs, \"sidebarWidth\", 320);\n const contentWidth = getThemeLayoutValue(docs, \"contentWidth\", 860);\n\n return `\n @font-face { font-family: \"Geist Sans\"; src: local(\"Geist Sans\"), url(\"${GEIST_SANS_FONT_URL}\") format(\"woff2\"), url(\"/node_modules/geist/dist/fonts/geist-sans/Geist-Variable.woff2\") format(\"woff2\"); font-display: block; font-style: normal; font-weight: 100 900; }\n @font-face { font-family: \"Geist Mono\"; src: local(\"Geist Mono\"), url(\"${GEIST_MONO_FONT_URL}\") format(\"woff2\"), url(\"/node_modules/geist/dist/fonts/geist-mono/GeistMono-Variable.woff2\") format(\"woff2\"); font-display: block; font-style: normal; font-weight: 100 900; }\n :root { color-scheme: dark; --font-geist-sans: \"Geist Sans\"; --font-geist-mono: \"Geist Mono\"; --fd-sidebar-width: ${sidebarWidth}px; --fd-content-width: ${contentWidth}px; --fd-toc-width: 240px; --fd-docs-height: 100vh; --fd-docs-row-1: var(--fd-nav-height, 44px); --fd-docs-font-sans: var(--font-geist-sans, \"Geist Sans\", var(--font-sans, system-ui, -apple-system, sans-serif)); --fd-docs-font-mono: var(--font-geist-mono, \"Geist Mono\", var(--font-mono, ui-monospace, monospace)); --fd-font-sans: var(--fd-docs-font-sans); --fd-font-mono: var(--fd-docs-font-mono); --fd-pixel-rail-width: 12px; --fd-sidebar-edge: calc(var(--fd-pixel-rail-width) + 18px); --fd-sidebar-guide-x: calc(var(--fd-sidebar-edge) + 16px); --fd-sidebar-link-x: calc(var(--fd-sidebar-guide-x) + 22px); --fd-sidebar-sub-guide-x: calc(var(--fd-sidebar-link-x) + 7px); --fd-sidebar-sub-link-x: calc(var(--fd-sidebar-sub-guide-x) + 28px); --fd-sidebar-branch-gap: 0px; --fd-sidebar-nested-icon-gap: 0px; --fd-sidebar-line-color: color-mix(in srgb, var(--color-fd-border, hsl(0 0% 15%)) 88%, transparent); }\n * { box-sizing: border-box; }\n html { background: var(--color-fd-background, hsl(0 0% 2%)); scroll-padding-top: calc(var(--fd-nav-height, 44px) + 24px); }\n html[data-farm-docs-sidebar=\"open\"], html[data-farm-docs-sidebar=\"open\"] body { overflow: hidden; }\n body { margin: 0; min-height: 100vh; background: var(--color-fd-background, hsl(0 0% 2%)); color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); font-family: var(--fd-docs-font-sans); text-rendering: optimizeLegibility; }\n ::selection { background: var(--color-fd-foreground, #fff); color: var(--color-fd-background, #000); }\n a { color: inherit; }\n #nd-docs-layout { --fd-sidebar-col: var(--fd-sidebar-width); display: grid; grid-template: \"sidebar header header\" var(--fd-nav-height, 44px) \"sidebar main toc\" 1fr / var(--fd-sidebar-width) minmax(0, 1fr) var(--fd-toc-width) !important; min-height: 100vh; border-top: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background: var(--color-fd-background, hsl(0 0% 2%)); }\n #nd-docs-layout.grid { grid-template: \"sidebar header header\" var(--fd-nav-height, 44px) \"sidebar main toc\" 1fr / var(--fd-sidebar-width) minmax(0, 1fr) var(--fd-toc-width) !important; }\n #nd-docs-layout, #nd-docs-layout * { border-radius: 0 !important; }\n .topbar { position: sticky; top: 0; z-index: 20; grid-area: header; height: var(--fd-nav-height, 44px); display: flex; align-items: center; justify-content: flex-end; gap: 16px; border-bottom: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background: color-mix(in srgb, var(--color-fd-background, hsl(0 0% 2%)) 92%, transparent); backdrop-filter: blur(12px); padding: 0; font-family: var(--fd-docs-font-mono); font-size: 12px; letter-spacing: 0.03em; text-transform: uppercase; }\n .topbar a { text-decoration: none; color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); }\n .topbar a:hover { color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); }\n .topbar-actions, .mobile-topbar-actions { display: flex; height: 100%; min-width: 0; align-items: stretch; margin-left: auto; }\n .topbar-llms-link { display: inline-flex; height: 100%; align-items: center; border-left: 1px solid var(--color-fd-border, hsl(0 0% 15%)); padding: 0 22px; }\n .mobile-topbar { display: none; }\n .sidebar-backdrop { display: none; }\n .fd-mobile-nav-btn { display: inline-flex; width: var(--fd-mobile-nav-height, 56px); height: 100%; flex: 0 0 var(--fd-mobile-nav-height, 56px); align-items: center; justify-content: center; border: 0; border-right: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background: transparent; color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); cursor: pointer; padding: 0; appearance: none; }\n .fd-mobile-nav-btn svg { width: 19px; height: 19px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }\n .mobile-topbar-link { display: inline-flex; height: 100%; min-width: 0; align-items: center; color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); font-family: var(--fd-docs-font-mono); font-size: 12px; letter-spacing: 0.03em; text-decoration: none; text-transform: uppercase; }\n .mobile-topbar-link { border-left: 1px solid var(--color-fd-border, hsl(0 0% 15%)); padding: 0 14px; }\n #nd-docs-layout .fd-toc { position: sticky; top: var(--fd-docs-row-1); grid-area: toc; display: flex; width: var(--fd-toc-width); height: calc(var(--fd-docs-height) - var(--fd-docs-row-1)); max-height: calc(100vh - var(--fd-docs-row-1)); flex-direction: column; align-self: start; overflow: hidden; padding: 48px 16px 8px 0; }\n #nd-docs-layout .fd-toc-inner { display: flex; min-width: 0; min-height: 0; flex: 1 1 auto; flex-direction: column; }\n #nd-docs-layout .fd-toc-title { display: inline-flex; align-items: center; gap: 0.375rem; margin: 0 0 1rem; color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); font-family: var(--fd-docs-font-sans); font-size: 0.875rem; font-weight: 500; line-height: 1.4; }\n #nd-docs-layout .fd-toc-title svg { width: 1rem; height: 1rem; flex: 0 0 1rem; color: currentColor; }\n #nd-docs-layout .toc-scroll { min-height: 0; overflow: auto; padding: 0.75rem 0; scrollbar-width: none; }\n #nd-docs-layout .toc-scroll::-webkit-scrollbar { display: none; }\n #nd-docs-layout .toc-track { position: relative; min-width: 0; }\n #nd-docs-layout .toc-thumb { position: absolute; inset-block: 0; inset-inline-start: 0; width: 1px; background: var(--color-fd-primary, oklch(0.985 0.001 106.423)); transition: clip-path 150ms ease; }\n #nd-docs-layout .toc-links { display: flex; min-width: 0; flex-direction: column; border-inline-start: 1px solid color-mix(in srgb, var(--color-fd-foreground, #fff) 10%, transparent); }\n #nd-docs-layout .toc-link { display: block; min-width: 0; padding: 0.375rem 0 0.375rem 0.75rem; color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); font-size: 0.875rem; line-height: 1.45; text-decoration: none; overflow-wrap: anywhere; transition: color 150ms ease; }\n #nd-docs-layout .toc-link:first-child { padding-top: 0; }\n #nd-docs-layout .toc-link:last-child { padding-bottom: 0; }\n #nd-docs-layout .toc-link[data-depth=\"3\"] { padding-left: 1.5rem; font-size: 0.8125rem; }\n #nd-docs-layout .toc-link[data-depth=\"4\"], #nd-docs-layout .toc-link[data-depth=\"5\"], #nd-docs-layout .toc-link[data-depth=\"6\"] { padding-left: 2rem; font-size: 0.8125rem; }\n #nd-docs-layout .toc-link[data-active=\"true\"] { color: var(--color-fd-primary, oklch(0.985 0.001 106.423)); }\n #nd-docs-layout .toc-link:hover { color: var(--color-fd-accent-foreground, oklch(0.985 0.001 106.423)); }\n #nd-docs-layout .toc-empty { margin: 0; color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); font-size: 0.875rem; line-height: 1.5; }\n aside#nd-sidebar { position: sticky; top: 0; grid-area: sidebar; height: 100vh; overflow: auto; isolation: isolate; border-left: 1px solid var(--color-fd-border, hsl(0 0% 15%)); border-right: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background-color: var(--color-fd-background, hsl(0 0% 2%)); background-image: linear-gradient(var(--color-fd-border, hsl(0 0% 15%)), var(--color-fd-border, hsl(0 0% 15%))), linear-gradient(var(--color-fd-border, hsl(0 0% 15%)), var(--color-fd-border, hsl(0 0% 15%))), repeating-linear-gradient(-45deg, color-mix(in srgb, var(--color-fd-border, hsl(0 0% 15%)) 2%, transparent), color-mix(in srgb, var(--color-fd-foreground, #fff) 7%, transparent) 1px, transparent 1px, transparent 6px), repeating-linear-gradient(-45deg, color-mix(in srgb, var(--color-fd-border, hsl(0 0% 15%)) 2%, transparent), color-mix(in srgb, var(--color-fd-foreground, #fff) 7%, transparent) 1px, transparent 1px, transparent 6px); background-size: 1px 100%, 1px 100%, var(--fd-pixel-rail-width) 100%, var(--fd-pixel-rail-width) 100%; background-position: var(--fd-pixel-rail-width) 0, calc(100% - var(--fd-pixel-rail-width)) 0, left top, right top; background-repeat: repeat-y; padding: 0 var(--fd-sidebar-edge) 18px; }\n aside#nd-sidebar::before, aside#nd-sidebar::after { display: none; }\n aside#nd-sidebar > * { position: relative; z-index: 1; }\n .sidebar-brand { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: var(--fd-nav-height, 44px); margin: 0 calc(-1 * var(--fd-sidebar-edge)) 18px; border-top: 1px solid var(--color-fd-border, hsl(0 0% 15%)); border-bottom: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background: transparent; padding: 0 var(--fd-sidebar-edge); font-family: var(--fd-docs-font-mono); font-size: 12px; letter-spacing: 0.03em; text-transform: uppercase; }\n .sidebar-brand a { display: inline-flex; min-width: 0; align-items: center; gap: 8px; overflow: hidden; text-decoration: none; text-overflow: ellipsis; white-space: nowrap; }\n .sidebar-brand-logo { width: 16px; height: 16px; flex: 0 0 16px; color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); }\n .sidebar-brand-title { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .sidebar-brand-suffix { opacity: 0.52; }\n .sidebar-scroll { margin: 0 calc(-1 * var(--fd-sidebar-edge)); overflow: visible; }\n .sidebar-tree { margin-top: 0 !important; }\n .sidebar-tree > a[data-active], .sidebar-folder { border-top: 1px solid var(--color-fd-border, hsl(0 0% 15%)); }\n #nd-docs-layout aside#nd-sidebar .sidebar-tree > .sidebar-folder { margin-left: 0 !important; margin-right: 0 !important; padding: 0 !important; }\n .sidebar-tree > :last-child { border-bottom: 1px solid var(--color-fd-border, hsl(0 0% 15%)); }\n #nd-docs-layout aside#nd-sidebar .sidebar-tree a[data-active] { position: relative; display: flex; width: auto !important; min-width: 0; align-items: center; gap: 8px; margin: 0 !important; padding: 6px var(--fd-sidebar-edge) 6px var(--fd-sidebar-link-x) !important; color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); text-decoration: none; font-size: 13.5px !important; line-height: 1.45 !important; background: transparent !important; transition: color 150ms ease; }\n #nd-docs-layout aside#nd-sidebar .sidebar-tree > a[data-active] { padding-left: var(--fd-sidebar-edge) !important; padding-top: 12px !important; padding-bottom: 12px !important; }\n #nd-docs-layout aside#nd-sidebar .sidebar-subgroup-content a[data-active] { padding-left: var(--fd-sidebar-sub-link-x) !important; }\n .sidebar-tree a[data-active=\"true\"], .sidebar-tree a[data-active=\"true\"]:hover { color: var(--color-fd-primary, oklch(0.985 0.001 106.423)) !important; }\n .sidebar-tree a[data-active=\"false\"]:hover { color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)) !important; }\n .sidebar-icon { display: inline-flex; width: 14px; height: 14px; flex: 0 0 14px; color: currentColor; opacity: 0.72; }\n .sidebar-icon svg { width: 100%; height: 100%; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }\n .sidebar-icon[data-sidebar-icon^=\"brand-\"] svg { fill: currentColor; stroke: none; }\n .sidebar-icon[data-sidebar-icon^=\"brand-\"] svg * { stroke: none; }\n .sidebar-link-label, .sidebar-folder-label, .sidebar-subgroup-label { display: inline-flex; min-width: 0; align-items: center; gap: 8px; }\n .sidebar-folder-label .sidebar-icon { width: 13px; height: 13px; flex-basis: 13px; }\n .sidebar-subgroup-label .sidebar-icon { width: 14px; height: 14px; flex-basis: 14px; }\n .sidebar-label-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .sidebar-tree a[data-active=\"true\"] .sidebar-icon, .sidebar-tree a:hover .sidebar-icon { opacity: 1; }\n #nd-docs-layout aside#nd-sidebar .sidebar-folder-trigger { display: flex !important; width: 100% !important; min-width: 0; align-items: center; justify-content: flex-start; border: 0; border-bottom: 1px solid var(--color-fd-border, hsl(0 0% 15%)) !important; background: transparent !important; margin: 0 !important; transform: none !important; padding: 8px var(--fd-sidebar-edge) !important; color: var(--color-fd-muted-foreground, hsl(0 0% 55%)) !important; font-family: var(--fd-docs-font-sans); font-size: 12px !important; font-weight: 600; letter-spacing: 0 !important; text-align: left; text-transform: none; cursor: default; }\n .sidebar-folder-content { position: relative; padding: 8px 0; overflow: hidden; }\n .sidebar-folder-content::before { content: \"\"; position: absolute; left: var(--fd-sidebar-guide-x); top: 0; bottom: 0; width: 1px; background: var(--fd-sidebar-line-color); pointer-events: none; }\n .sidebar-folder-content > a[data-active]::after, .sidebar-subgroup-title::after, .sidebar-subgroup-content a[data-active]::after { content: \"\"; position: absolute; top: 50%; height: 1px; background: var(--fd-sidebar-line-color); transform: translateY(-50%); pointer-events: none; transition: background-color 150ms ease; }\n .sidebar-folder-content > a[data-active]::after { left: calc(var(--fd-sidebar-guide-x) + var(--fd-sidebar-branch-gap)); width: calc(var(--fd-sidebar-link-x) - var(--fd-sidebar-guide-x) - var(--fd-sidebar-branch-gap)); }\n .sidebar-subgroup-title::after { left: calc(var(--fd-sidebar-guide-x) + var(--fd-sidebar-branch-gap)); width: calc(var(--fd-sidebar-sub-guide-x) - var(--fd-sidebar-guide-x) - var(--fd-sidebar-branch-gap)); }\n .sidebar-folder-content > a[data-active=\"true\"]::after, .sidebar-subgroup-content a[data-active=\"true\"]::after { background: var(--color-fd-primary, oklch(0.985 0.001 106.423)); }\n .sidebar-subgroup { position: relative; padding: 2px 0 4px; }\n .sidebar-subgroup::before { content: \"\"; position: absolute; left: var(--fd-sidebar-sub-guide-x); top: 17px; bottom: 19px; width: 1px; background: var(--fd-sidebar-line-color); pointer-events: none; }\n .sidebar-subgroup-title { position: relative; display: flex; min-width: 0; align-items: center; margin: 0 !important; padding: 6px var(--fd-sidebar-edge) 6px var(--fd-sidebar-link-x); color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); font-size: 13.5px; font-weight: 400; line-height: 1.45; }\n .sidebar-subgroup-content { position: relative; padding: 0 0 4px; }\n .sidebar-subgroup-content a[data-active]::after { left: var(--fd-sidebar-sub-guide-x); width: calc(var(--fd-sidebar-sub-link-x) - var(--fd-sidebar-sub-guide-x) - var(--fd-sidebar-nested-icon-gap)); }\n main { grid-area: main; min-width: 0; padding: 46px 40px 80px; }\n article#nd-page { width: min(100%, var(--fd-content-width)); margin: 0 auto; }\n article#nd-page .fd-breadcrumb { display: flex; min-width: 0; align-items: center; gap: 0; margin: 0 0 0.5rem; color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); font-family: var(--fd-docs-font-mono); font-size: 0.75rem; line-height: 1.4; letter-spacing: 0.01em; text-transform: uppercase; }\n article#nd-page .fd-breadcrumb-item { display: inline-flex; min-width: 0; align-items: center; }\n article#nd-page .fd-breadcrumb-link { color: inherit; font-family: var(--fd-docs-font-mono); text-decoration: none; }\n article#nd-page .fd-breadcrumb-link:hover { color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); }\n article#nd-page .fd-breadcrumb-parent { opacity: 0.6; font-weight: 400; }\n article#nd-page .fd-breadcrumb-sep { margin: 0 0.375rem; opacity: 0.4; font-size: 0.75rem; }\n article#nd-page .fd-breadcrumb-current { color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); font-family: var(--fd-docs-font-mono); font-weight: 500; }\n .prose h1 { margin: 0 0 16px; font-size: 36px; line-height: 1.14; letter-spacing: -0.02em; }\n .prose h2 { margin: 44px 0 14px; border-top: 1px solid var(--color-fd-border, hsl(0 0% 15%)); padding-top: 26px; font-size: 24px; line-height: 1.24; letter-spacing: -0.01em; }\n .prose h3 { margin: 30px 0 12px; font-size: 20px; line-height: 1.3; letter-spacing: 0; }\n .prose h4, .prose h5, .prose h6 { margin: 24px 0 10px; letter-spacing: 0; }\n .heading-anchor { color: inherit; text-decoration: none; }\n .heading-anchor:hover { text-decoration: underline; text-underline-offset: 4px; }\n .prose p { margin: 14px 0; color: color-mix(in srgb, var(--color-fd-foreground, oklch(0.985 0.001 106.423)) 74%, transparent); font-size: 15.6px; line-height: 1.8; }\n .prose ul, .prose ol { margin: 16px 0; padding-left: 24px; color: color-mix(in srgb, var(--color-fd-foreground, oklch(0.985 0.001 106.423)) 78%, transparent); line-height: 1.75; }\n .prose li { margin: 6px 0; }\n .prose code:not(pre code) { border: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background: var(--color-fd-card, hsl(0 0% 4%)); padding: 1px 5px; font-family: var(--fd-docs-font-mono); font-size: 0.88em; overflow-wrap: break-word; word-break: break-word; }\n .sh-code { --sh-class: #e5c07b; --sh-identifier: #c8ccd4; --sh-string: #98c379; --sh-keyword: #c678dd; --sh-comment: #5c6370; --sh-property: #e06c75; --sh-sign: #c8ccd4; --sh-space: inherit; }\n .code-block { --fd-code-header-bg: color-mix(in srgb, var(--color-fd-foreground, #fff) 5%, var(--color-fd-background, #000)); --fd-code-body-bg: color-mix(in srgb, var(--color-fd-foreground, #fff) 8%, var(--color-fd-background, #000)); position: relative; width: 100%; min-width: 0; max-width: 100%; margin: 20px 0; overflow: hidden; border: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background: var(--color-fd-background, hsl(0 0% 2%)); box-shadow: 3px 3px 0 0 var(--color-fd-border, hsl(0 0% 15%)); font-family: var(--fd-docs-font-mono); }\n #nd-docs-layout figure.shiki.code-block { box-shadow: 3px 3px 0 0 var(--color-fd-border, hsl(0 0% 15%)) !important; }\n .code-block-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-width: 0; min-height: 30px; border-bottom: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background-color: var(--fd-code-header-bg); background-image: repeating-linear-gradient(-45deg, color-mix(in srgb, var(--color-fd-foreground, #fff) 7%, transparent), color-mix(in srgb, var(--color-fd-foreground, #fff) 7%, transparent) 1px, transparent 1px, transparent 6px); padding: 4px 8px 4px 10px; }\n .code-block-title { overflow: hidden; color: color-mix(in srgb, var(--color-fd-foreground, #fff) 50%, transparent); font-size: 10px; line-height: 1.2; text-overflow: ellipsis; text-transform: lowercase; white-space: nowrap; }\n .code-copy { display: inline-flex; align-items: center; justify-content: center; width: 22px; height: 22px; flex: 0 0 auto; border: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background: color-mix(in srgb, var(--color-fd-background, #000) 80%, transparent); color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); cursor: pointer; padding: 0; }\n .code-copy-floating { position: absolute; top: 8px; right: 8px; z-index: 2; opacity: 0.72; transition: opacity 150ms ease; }\n #nd-docs-layout figure.shiki.code-block > .code-copy-floating { opacity: 0.72; }\n .code-block-plain:hover .code-copy-floating, .code-block-plain:focus-within .code-copy-floating { opacity: 1; }\n .code-copy svg { width: 13px; height: 13px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }\n .code-copy .code-copy-check { display: none; }\n .code-copy[data-copied=\"true\"] .code-copy-icon { display: none; }\n .code-copy[data-copied=\"true\"] .code-copy-check { display: block; }\n .code-copy:hover { color: var(--color-fd-foreground, #fff); background: var(--color-fd-muted, hsl(0 0% 10%)); }\n .code-block pre { margin: 0; max-width: 100%; overflow-x: auto; border: 0; background: var(--fd-code-body-bg); padding: 18px 20px; color: var(--color-fd-foreground, #fff); font-family: var(--fd-docs-font-mono); font-size: 13px; line-height: 1.6; }\n #nd-docs-layout figure.shiki.code-block pre { padding: 18px 20px !important; }\n .code-block code { display: block; min-width: max-content; border: 0 !important; background: transparent !important; padding: 0 !important; font-family: inherit; white-space: normal; }\n .sh__line { display: block; min-height: 1.6em; white-space: pre; }\n blockquote { margin: 18px 0; border: 1px solid var(--color-fd-border, hsl(0 0% 15%)); border-left: 3px solid var(--color-fd-foreground, oklch(0.985 0.001 106.423)); background: var(--color-fd-card, hsl(0 0% 4%)); box-shadow: 3px 3px 0 0 var(--color-fd-border, hsl(0 0% 15%)); padding: 14px 16px; color: color-mix(in srgb, var(--color-fd-foreground, oklch(0.985 0.001 106.423)) 78%, transparent); }\n .fd-table-wrapper { margin: 24px 0; overflow-x: auto; }\n .fd-table-wrapper table { width: 100%; border: 1px solid var(--color-fd-border, hsl(0 0% 15%)); border-collapse: collapse; font-size: 14px; }\n .fd-table-wrapper th, .fd-table-wrapper td { border-color: var(--color-fd-border, hsl(0 0% 15%)); border-bottom: 1px solid var(--color-fd-border, hsl(0 0% 15%)); padding: 10px 12px; text-align: left; vertical-align: top; }\n .fd-table-wrapper th { background: var(--color-fd-muted, hsl(0 0% 10%)); color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); font-family: inherit; font-size: 13px; font-weight: 500; text-transform: none; }\n .fd-table-wrapper tr:last-child td { border-bottom: 0; }\n hr { border: 0; border-top: 1px solid var(--color-fd-border, hsl(0 0% 15%)); margin: 28px 0; }\n img { max-width: 100%; height: auto; border: 1px solid var(--color-fd-border, hsl(0 0% 15%)); }\n .fd-page-nav { display: grid; width: 100%; max-width: 100%; grid-template-columns: 1fr; gap: 16px; margin-top: 16px; border-top: 0; padding-top: 0; }\n .fd-page-nav:has(.fd-page-nav-prev):has(.fd-page-nav-next) { grid-template-columns: repeat(2, minmax(0, 1fr)); }\n #nd-docs-layout .fd-page-nav-card { display: flex; min-width: 0; min-height: 98px; flex-direction: column; justify-content: flex-start; gap: 8px; border: 1px solid var(--color-fd-border, hsl(0 0% 15%)); border-radius: 0 !important; background: transparent; padding: 16px; color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); text-decoration: none; transition: background-color 150ms ease, border-color 150ms ease; }\n .fd-page-nav-card:hover { border-color: var(--color-fd-border, hsl(0 0% 15%)); background: color-mix(in srgb, var(--color-fd-muted, hsl(0 0% 10%)) 80%, transparent); }\n .fd-page-nav-next { align-items: flex-end; text-align: right; }\n .fd-page-nav-title { display: inline-flex; max-width: 100%; min-height: 0; align-items: center; gap: 6px; overflow: hidden; color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); font-size: 0.875rem; font-weight: 500; line-height: 1.5; overflow-wrap: anywhere; }\n .fd-page-nav-title svg { width: 1rem; height: 1rem; flex-shrink: 0; }\n .fd-page-nav-description { display: block; max-width: 100%; min-height: 0; overflow: hidden; color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); font-size: 15.6px; font-weight: 400; line-height: 1.8; text-overflow: ellipsis; white-space: nowrap; }\n .fd-below-title-block { display: flex; flex-direction: column; align-items: flex-start; gap: 0.625rem; margin: 0 0 1.25rem; }\n .fd-page-actions { display: flex; width: 100%; align-items: center; gap: 0.5rem; }\n .fd-page-actions[data-actions-alignment=\"right\"] { justify-content: flex-end; }\n .fd-below-title-block .fd-page-actions { margin: 0; }\n .fd-page-meta { display: inline-flex; align-items: center; gap: 0.375rem; color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); font-size: 0.8125rem; line-height: 1.5; }\n .fd-page-meta-dot { color: color-mix(in srgb, var(--color-fd-muted-foreground, hsl(0 0% 55%)) 60%, transparent); }\n .fd-last-updated-inline, .fd-last-updated-footer { color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); font-family: var(--fd-docs-font-mono); font-size: 0.75rem; letter-spacing: 0.03em; line-height: 1.5; text-transform: uppercase; }\n #nd-docs-layout .fd-page-action-btn { display: inline-flex; min-height: 2.125rem; align-items: center; justify-content: center; gap: 0.5rem; border: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background: color-mix(in srgb, var(--color-fd-foreground, #fff) 5%, var(--color-fd-background, #000)); color: var(--color-fd-muted-foreground, hsl(0 0% 55%)); padding: 0 0.75rem; box-shadow: 2px 2px 0 0 var(--color-fd-border, hsl(0 0% 15%)); cursor: pointer; font-family: var(--fd-docs-font-mono) !important; font-size: 0.75rem; font-weight: 500; letter-spacing: 0.03em; line-height: 1; text-transform: uppercase; transition: background-color 150ms ease, color 150ms ease, border-color 150ms ease; appearance: none; }\n #nd-docs-layout .fd-page-action-btn:hover { border-color: color-mix(in srgb, var(--color-fd-foreground, #fff) 22%, transparent); background: color-mix(in srgb, var(--color-fd-foreground, #fff) 8%, var(--color-fd-background, #000)); color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); }\n #nd-docs-layout .fd-page-action-btn:disabled { cursor: wait; opacity: 0.72; }\n #nd-docs-layout .fd-page-action-btn svg { width: 14px; height: 14px; flex: 0 0 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }\n #nd-docs-layout .fd-page-action-btn .fd-page-action-check-icon { display: none; }\n #nd-docs-layout .fd-page-action-btn[data-copied=\"true\"] .fd-page-action-copy-icon { display: none; }\n #nd-docs-layout .fd-page-action-btn[data-copied=\"true\"] .fd-page-action-check-icon { display: block; }\n .fd-page-footer { display: flex; align-items: center; gap: 0.75rem 1rem; margin-top: 2rem; border-top: 1px solid var(--color-fd-border, hsl(0 0% 15%)); padding-top: 1rem; }\n .fd-page-footer .fd-last-updated-footer { margin-left: auto; }\n @media (max-width: 1020px) {\n :root { --fd-mobile-nav-height: 56px; --fd-sidebar-edge: 20px; --fd-sidebar-guide-x: 58px; --fd-sidebar-link-x: 88px; --fd-sidebar-sub-guide-x: calc(var(--fd-sidebar-link-x) + 7px); --fd-sidebar-sub-link-x: calc(var(--fd-sidebar-sub-guide-x) + 28px); }\n html { scroll-padding-top: calc(var(--fd-mobile-nav-height, 56px) + 24px); }\n body { overflow-x: hidden; }\n #nd-docs-layout { display: block !important; min-height: 100dvh; border-top: 0; padding-top: var(--fd-mobile-nav-height, 56px); }\n .mobile-topbar { position: fixed; inset: 0 0 auto 0; z-index: 80; display: flex; height: var(--fd-mobile-nav-height, 56px); align-items: stretch; border-bottom: 1px solid var(--color-fd-border, hsl(0 0% 15%)); background: color-mix(in srgb, var(--color-fd-background, hsl(0 0% 2%)) 94%, transparent); backdrop-filter: blur(12px); }\n .mobile-topbar a:hover, .fd-mobile-nav-btn:hover { color: var(--color-fd-foreground, oklch(0.985 0.001 106.423)); }\n .topbar { display: none !important; }\n .sidebar-backdrop { position: fixed; inset: 0; z-index: 70; display: block; background: color-mix(in srgb, var(--color-fd-background, #000) 72%, transparent); opacity: 0; pointer-events: none; transition: opacity 180ms ease; }\n #nd-docs-layout[data-sidebar-open=\"true\"] .sidebar-backdrop { opacity: 1; pointer-events: auto; }\n aside#nd-sidebar { position: fixed; inset: 0 auto 0 0; z-index: 90; width: min(342px, calc(100vw - 42px)); height: 100dvh; max-height: none; overflow-y: auto; overscroll-behavior: contain; border-right: 1px solid var(--color-fd-border, hsl(0 0% 15%)); border-bottom: 0; transform: translate3d(-100%, 0, 0); transition: transform 180ms ease; will-change: transform; }\n #nd-docs-layout[data-sidebar-open=\"true\"] aside#nd-sidebar { transform: translate3d(0, 0, 0); }\n aside#nd-sidebar::before, aside#nd-sidebar::after { display: none; }\n .sidebar-brand { min-height: var(--fd-nav-height, 44px); margin-top: 0; }\n main { padding: 34px 20px 64px; }\n article#nd-page { width: 100%; margin: 0; }\n #nd-docs-layout .fd-toc { display: none !important; }\n .prose h1 { font-size: 32px; line-height: 1.16; letter-spacing: 0; }\n .prose h2 { margin-top: 34px; padding-top: 22px; font-size: 23px; }\n .code-block { margin: 16px 0; box-shadow: 2px 2px 0 0 var(--color-fd-border, hsl(0 0% 15%)); }\n #nd-docs-layout figure.shiki.code-block { box-shadow: 2px 2px 0 0 var(--color-fd-border, hsl(0 0% 15%)) !important; }\n .code-block-header { min-height: 26px; padding: 2px 6px 2px 8px; }\n .code-copy-floating { top: 6px; right: 6px; }\n #nd-docs-layout figure.shiki.code-block pre, .code-block pre { padding: 12px 11px !important; font-size: 12px; line-height: 1.5; }\n .sh__line { min-height: 1.5em; }\n .fd-page-nav { grid-template-columns: 1fr !important; }\n .fd-page-nav-next { align-items: flex-start; text-align: left; }\n .fd-page-footer { align-items: flex-start; flex-direction: column; }\n .fd-page-footer .fd-last-updated-footer { margin-left: 0; }\n }\n @media (max-width: 640px) {\n .code-block-header { min-height: 22px; padding: 1px 4px 1px 7px; }\n .code-block-title { font-size: 9px; }\n .code-copy { width: 20px; height: 20px; }\n .code-copy svg { width: 12px; height: 12px; }\n .code-copy-floating { top: 5px; right: 5px; }\n #nd-docs-layout figure.shiki.code-block pre, .code-block pre { padding: 10px !important; font-size: 11px; line-height: 1.55; }\n .sh__line { min-height: 1.55em; }\n }\n${farmDocsPixelBorderCss}\n `;\n}\n\nfunction renderPixelDocsHtml(\n page: LoadedFarmDocsPage,\n pages: FarmDocsPage[],\n docs: FarmDocsResolvedConfig,\n themeCss: string,\n clientEntry: string,\n faviconHref: string,\n): string {\n const navTitle =\n typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n ? String((docs.config.nav as { title?: unknown }).title || \"Docs\")\n : \"Docs\";\n const description = page.description || docs.config.metadata?.description || \"\";\n const tocItems = extractTocItems(page.body, getThemeTocDepth(docs));\n const themeName = getThemeName(docs);\n const searchEnabled = isFarmDocsSearchEnabled(docs);\n\n return `<!DOCTYPE html>\n<html class=\"dark\" lang=\"en\" data-docs-theme=\"${escapeAttribute(themeName)}\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <meta name=\"generator\" content=\"@farming-labs/docs via Farm.js\">\n <title>${escapeHtml(page.title)}</title>\n ${renderFarmDocsFaviconLink(faviconHref)}\n <link rel=\"preload\" href=\"${GEIST_SANS_FONT_URL}\" as=\"font\" type=\"font/woff2\" crossorigin>\n <link rel=\"preload\" href=\"${GEIST_MONO_FONT_URL}\" as=\"font\" type=\"font/woff2\" crossorigin>\n ${description ? `<meta name=\"description\" content=\"${escapeHtml(description)}\">` : \"\"}\n <style>${themeCss}\n${renderFarmDocsBridgeCss(docs)}</style>\n ${searchEnabled ? renderDocsSearchBootstrapScript() : \"\"}\n</head>\n<body>\n <div id=\"nd-docs-layout\" class=\"grid\">\n <header class=\"mobile-topbar\" aria-label=\"Mobile docs navigation\">\n <button class=\"fd-mobile-nav-btn\" type=\"button\" data-sidebar-toggle aria-controls=\"nd-sidebar\" aria-expanded=\"false\" aria-label=\"Open menu\">\n <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\"><line x1=\"3\" y1=\"6\" x2=\"21\" y2=\"6\"></line><line x1=\"3\" y1=\"12\" x2=\"21\" y2=\"12\"></line><line x1=\"3\" y1=\"18\" x2=\"21\" y2=\"18\"></line></svg>\n </button>\n <div class=\"mobile-topbar-actions\">\n ${searchEnabled ? renderDocsSearchTrigger() : \"\"}\n <a class=\"mobile-topbar-link\" href=\"/llms.txt\">llms.txt</a>\n </div>\n </header>\n <div class=\"sidebar-backdrop\" data-sidebar-backdrop></div>\n <aside id=\"nd-sidebar\">\n <div class=\"sidebar-brand\">\n <a href=\"/\">${renderFarmDocsBrandMark()}${renderFarmDocsBrandTitle(navTitle)}</a>\n <span>/ docs</span>\n </div>\n ${renderPixelNavItems(pages, page.href, docs)}\n </aside>\n <header class=\"topbar\">\n <div class=\"topbar-actions\">\n ${searchEnabled ? renderDocsSearchTrigger(false) : \"\"}\n <a class=\"topbar-llms-link\" href=\"/llms.txt\">llms.txt</a>\n </div>\n </header>\n <main>\n <article id=\"nd-page\" class=\"prose\">\n ${renderPixelBreadcrumb(page, docs)}\n${renderMarkdownHtmlWithTitleMeta(page, docs)}\n ${renderPixelPageFooter(page, docs)}\n ${renderPixelPageNav(pages, page.href, docs)}\n </article>\n </main>\n <nav id=\"nd-toc\" class=\"fd-toc sticky top-(--fd-docs-row-1) h-[calc(var(--fd-docs-height)-var(--fd-docs-row-1))] flex flex-col [grid-area:toc] w-(--fd-toc-width) pt-12 pe-4 pb-2 max-xl:hidden\" data-toc aria-labelledby=\"toc-title\">\n <div class=\"fd-toc-inner\">\n <h3 id=\"toc-title\" class=\"fd-toc-title inline-flex items-center gap-1.5 text-sm text-fd-muted-foreground\"><svg class=\"size-4\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M4 7h16\"></path><path d=\"M4 12h16\"></path><path d=\"M4 17h16\"></path></svg>On this page</h3>\n <div class=\"toc-scroll\">\n ${renderPixelToc(tocItems)}\n </div>\n </div>\n </nav>\n </div>\n ${searchEnabled ? renderDocsSearchMount(clientEntry) : \"\"}\n ${renderDocsRuntimeScripts(docs)}\n</body>\n</html>`;\n}\n\nexport function createFarmDocsHandler(\n docs: FarmDocsResolvedConfig | undefined,\n options: FarmDocsHandlerOptions,\n) {\n const faviconHref = resolveFarmDocsFavicon(docs, options);\n\n return async function handleFarmDocsRequest(request: Request): Promise<Response | null> {\n if (!docs?.enabled || (request.method !== \"GET\" && request.method !== \"HEAD\")) return null;\n\n const contentDir = resolveFarmDocsContentDir(docs, options);\n const publicResponse = createFarmDocsPublicResponse(contentDir, docs, request);\n if (publicResponse) return publicResponse;\n\n if (!isFarmDocsRequest(docs, request)) return null;\n\n const page = loadPage(contentDir, docs, request);\n if (!page) return null;\n\n if (shouldReturnMarkdown(request)) {\n const origin = new URL(request.url).origin;\n return new Response(\n renderDocsMarkdownDocument(toFarmDocsMarkdownPage(page), {\n origin,\n llms: docs.config.llmsTxt ?? true,\n sitemap: docs.config.sitemap,\n }),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"text/markdown; charset=utf-8\",\n \"Cache-Control\": \"public, max-age=60\",\n },\n },\n );\n }\n\n return new Response(\n renderPixelDocsHtml(\n page,\n discoverFarmDocsPages(contentDir, docs),\n docs,\n resolvePixelBorderThemeCss(options),\n options.clientEntry || \"/farm-client.js\",\n faviconHref,\n ),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"text/html; charset=utf-8\",\n \"Cache-Control\": \"public, s-maxage=60, stale-while-revalidate=300\",\n },\n },\n );\n };\n}\n","import type { FarmUserConfig } from \"./config\";\n\n/** Define a Farm application config while preserving literal types. */\nexport function defineConfig<const TConfig extends FarmUserConfig>(config: TConfig): TConfig {\n return config;\n}\n\n/** @deprecated Use {@link defineConfig}. */\nexport const defineFarmConfig = defineConfig;\n\nexport type { FarmUserConfig };\n","import type {\n FarmConfig as BaseFarmConfig,\n FarmMigrationCommand,\n FarmMigrationsConfig,\n FarmMigrationsUserConfig,\n ResolvedFarmMigrationsConfig,\n} from \"./types\";\nimport type { DocsConfig } from \"@farming-labs/docs\";\nimport type { FarmDocsResolvedConfig, FarmDocsUserConfig } from \"./docs/types\";\nimport type { FarmIntegrationsUserConfig } from \"./integrations\";\nimport type { FarmMarkdownResolvedConfig, FarmMarkdownUserConfig } from \"./markdown\";\nimport type { FarmObservabilityUserConfig } from \"./observability\";\nimport type { FarmMiddlewareConfig } from \"./middleware/types\";\nimport type { FarmPlugin } from \"./plugin\";\nimport type { FarmWorkflowsResolvedConfig, FarmWorkflowsUserConfig } from \"./workflows\";\nimport type { FarmCronResolvedConfig, FarmCronUserConfig } from \"./cron\";\nimport type { FarmEnvConfig, ResolvedFarmEnv } from \"./env\";\nimport type { UserConfig as ViteUserConfig } from \"vite\";\nimport { resolveIntegrationPlugins } from \"./integrations\";\nimport { resolveMarkdownConfig } from \"./markdown\";\nimport { resolveWorkflowsConfig } from \"./workflows\";\nimport { resolveCronConfig } from \"./cron\";\nimport { resolveEnv, setEnv } from \"./env\";\nimport {\n resolveMdxConfig,\n type FarmMdxResolvedConfig,\n type FarmMdxUserConfig,\n} from \"./app-markdown\";\nimport {\n normalizeRouteRules,\n routeRulesToHeaders,\n routeRulesToRedirects,\n type FarmRouteRules,\n} from \"./route-rules\";\nimport {\n resolveServerActionsConfig,\n type FarmServerActionsConfig,\n type ResolvedFarmServerActionsConfig,\n} from \"./server-action-security\";\nimport {\n loadFarmConfigFile,\n resolveFarmLayers,\n type FarmLayerEntry,\n type ResolvedFarmLayer,\n} from \"./layers\";\nimport path from \"path\";\nimport { normalizeFarmDeploymentId } from \"./deployment\";\nimport { resolveFarmDevtoolsConfig, type ResolvedFarmDevtoolsConfig } from \"./devtools-config\";\nimport {\n resolveFarmImageConfig,\n type FarmImageConfig,\n type ResolvedFarmImageConfig,\n} from \"./image-config\";\nimport { resolveFarmI18nConfig } from \"./i18n/config\";\nimport type { FarmI18nUserConfig, ResolvedFarmI18nConfig } from \"./i18n/types\";\n\nconst FARM_RESOLVED_CUSTOM_CONTEXT = Symbol.for(\"farm.resolvedCustomContext\");\n\nexport type {\n FarmDocsConfigInput,\n FarmDocsNavigationConfig,\n FarmDocsResolvedConfig,\n FarmDocsSidebarItem,\n FarmDocsUserConfig,\n} from \"./docs/types\";\nexport type {\n FarmMarkdownResolvedConfig,\n FarmMarkdownRouteInput,\n FarmMarkdownUserConfig,\n} from \"./markdown\";\nexport type { FarmMdxComponents, FarmMdxResolvedConfig, FarmMdxUserConfig } from \"./app-markdown\";\nexport type {\n FarmMigrationCommand,\n FarmMigrationsConfig,\n FarmMigrationsUserConfig,\n ResolvedFarmMigrationsConfig,\n} from \"./types\";\nexport type { FarmWorkflowsResolvedConfig, FarmWorkflowsUserConfig } from \"./workflows\";\nexport type { FarmCronJobConfig, FarmCronResolvedConfig, FarmCronUserConfig } from \"./cron\";\nexport type {\n FarmRouteRule,\n FarmRouteRuleCors,\n FarmRouteRuleRedirect,\n FarmRouteRuleRenderMode,\n FarmRouteRules,\n} from \"./route-rules\";\nexport type {\n FarmServerActionsConfig,\n ResolvedFarmServerActionsConfig,\n} from \"./server-action-security\";\nexport type { FarmLayerEntry, ResolvedFarmLayer } from \"./layers\";\nexport type {\n FarmDevtoolsConfig,\n FarmDevtoolsUserConfig,\n ResolvedFarmDevtoolsConfig,\n} from \"./devtools-config\";\nexport type {\n FarmImageConfig,\n FarmImageFormat,\n FarmImageLocalPattern,\n FarmImageProvider,\n FarmImageRemotePattern,\n ResolvedFarmImageConfig,\n} from \"./image-config\";\nexport type {\n FarmI18nCookieConfig,\n FarmI18nDetectionSignal,\n FarmI18nDirection,\n FarmI18nRouting,\n FarmI18nUserConfig,\n ResolvedFarmI18nConfig,\n} from \"./i18n/types\";\n\nexport interface RedirectConfig {\n source: string;\n destination: string;\n permanent?: boolean;\n statusCode?: number;\n}\n\nexport interface HeaderConfig {\n source: string;\n headers: Array<{\n key: string;\n value: string;\n }>;\n}\n\nexport interface RewriteConfig {\n source: string;\n destination: string;\n}\n\n/** @deprecated Use FarmImageConfig. */\nexport type ImageConfig = FarmImageConfig;\n\n/** @deprecated Use FarmI18nUserConfig. */\nexport type I18nConfig = FarmI18nUserConfig;\n\nexport interface OpenAPIConfig {\n enabled?: boolean;\n route?: string;\n title?: string;\n description?: string;\n version?: string;\n servers?: Array<{\n url: string;\n description?: string;\n }>;\n contact?: {\n name?: string;\n email?: string;\n url?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n}\n\nexport type MiddlewareConfig = FarmMiddlewareConfig;\n\nexport interface NotFoundConfig {\n /** Path to a custom 404 page component (e.g., \"./src/app/not-found.tsx\") */\n component?: string;\n}\n\nexport type FarmDeployTarget = \"vercel\" | \"cloudflare\" | \"netlify\" | \"node\" | string;\n\nexport interface FarmDeployConfig {\n /**\n * Deployment platform. When present, Farm picks the matching Nitro preset and\n * output directory unless explicitly overridden.\n */\n target?: FarmDeployTarget;\n /** Nitro preset override. Usually inferred from target. */\n preset?: BaseFarmConfig[\"preset\"];\n /** Deployable output directory, relative to project root unless absolute. */\n outputDir?: string;\n /** Alias for outputDir for terser config. */\n output?: string;\n /** Cloudflare Pages project name used by `farm deploy --cloudflare`. */\n projectName?: string;\n vercel?: {\n outputDirectory?: string;\n buildCommand?: string;\n installCommand?: string;\n framework?: string | null;\n };\n cloudflare?: {\n outputDir?: string;\n projectName?: string;\n };\n netlify?: {\n outputDir?: string;\n site?: string;\n };\n}\n\nexport interface ResolvedFarmDeployConfig extends Omit<FarmDeployConfig, \"output\"> {\n target?: FarmDeployTarget;\n preset: BaseFarmConfig[\"preset\"];\n outputDir: string;\n}\n\nexport interface FarmUserConfig extends Omit<BaseFarmConfig, \"vite\" | \"docs\" | \"env\" | \"layers\"> {\n /** Reusable Farm directories or installed packages, applied from left to right. */\n extends?: readonly FarmLayerEntry[];\n plugins?: FarmPlugin[];\n integrations?: FarmIntegrationsUserConfig;\n migrations?: FarmMigrationsUserConfig;\n /** Map portable cron schedules to ordinary GET API routes. */\n cron?: FarmCronUserConfig | FarmCronResolvedConfig | false;\n workflows?: FarmWorkflowsUserConfig | boolean;\n preset?: BaseFarmConfig[\"preset\"];\n deploy?: FarmDeployConfig;\n docs?: FarmDocsUserConfig;\n md?: FarmMarkdownUserConfig | boolean;\n mdx?: FarmMdxUserConfig;\n observability?: FarmObservabilityUserConfig;\n\n trailingSlash?: boolean;\n redirects?: () => Promise<RedirectConfig[]> | RedirectConfig[];\n rewrites?: () => Promise<RewriteConfig[]> | RewriteConfig[];\n headers?: () => Promise<HeaderConfig[]> | HeaderConfig[];\n\n images?: ImageConfig;\n publicDir?: string;\n\n i18n?: FarmI18nUserConfig | false;\n openapi?: OpenAPIConfig;\n\n middleware?: FarmMiddlewareConfig;\n routeRules?: FarmRouteRules;\n context?: BaseFarmConfig[\"context\"];\n serverActions?: FarmServerActionsConfig;\n /** Build identifier used to detect and recover from deployment version skew. */\n deploymentId?: string;\n\n notFound?: NotFoundConfig;\n\n output?: \"standalone\" | \"static\" | \"export\";\n distDir?: string;\n generateBuildId?: () => string | Promise<string>;\n compress?: boolean;\n\n devIndicators?: {\n buildActivity?: boolean;\n buildActivityPosition?: \"bottom-right\" | \"bottom-left\" | \"top-right\" | \"top-left\";\n };\n\n serverRuntimeConfig?: Record<string, any>;\n publicRuntimeConfig?: Record<string, any>;\n\n env?: FarmEnvConfig<any, any>;\n\n typescript?: {\n tsconfigPath?: string;\n ignoreBuildErrors?: boolean;\n };\n\n vite?: ViteUserConfig | ((config: ViteUserConfig) => ViteUserConfig);\n\n [key: string]: any;\n}\n\nexport interface ResolvedFarmConfig extends Required<\n Omit<\n FarmUserConfig,\n | \"extends\"\n | \"plugins\"\n | \"vite\"\n | \"deploy\"\n | \"docs\"\n | \"md\"\n | \"mdx\"\n | \"migrations\"\n | \"cron\"\n | \"workflows\"\n | \"env\"\n | \"serverActions\"\n | \"devtools\"\n | \"images\"\n | \"i18n\"\n >\n> {\n /** @internal Tracks whether `context` came from user/layer config instead of the default noop. */\n [FARM_RESOLVED_CUSTOM_CONTEXT]?: boolean;\n extends: readonly FarmLayerEntry[];\n layers: ResolvedFarmLayer[];\n plugins: FarmPlugin[];\n vite: ViteUserConfig;\n deploy: ResolvedFarmDeployConfig;\n docs: FarmDocsResolvedConfig;\n md: FarmMarkdownResolvedConfig;\n mdx: FarmMdxResolvedConfig;\n migrations: ResolvedFarmMigrationsConfig;\n cron: FarmCronResolvedConfig;\n workflows: FarmWorkflowsResolvedConfig;\n env: ResolvedFarmEnv;\n serverActions: ResolvedFarmServerActionsConfig;\n devtools: ResolvedFarmDevtoolsConfig;\n images: ResolvedFarmImageConfig;\n i18n: ResolvedFarmI18nConfig;\n}\n\nexport function hasCustomFarmRouteContext(config: ResolvedFarmConfig): boolean {\n return config[FARM_RESOLVED_CUSTOM_CONTEXT] === true;\n}\n\nexport type FarmLayerConfig = Omit<\n FarmUserConfig,\n | \"root\"\n | \"outDir\"\n | \"distDir\"\n | \"deploy\"\n | \"output\"\n | \"preset\"\n | \"publicDir\"\n | \"generateBuildId\"\n | \"deploymentId\"\n>;\n\nexport { defineConfig, defineFarmConfig } from \"./config-entry\";\n\nexport function normalizeDeployTarget(target?: FarmDeployTarget): FarmDeployTarget | undefined {\n if (!target) return undefined;\n if (target === \"cloudflare-pages\" || target === \"cloudflare_pages\") return \"cloudflare\";\n if (target === \"node-server\" || target === \"nitro\") return \"node\";\n return target;\n}\n\nexport function getPresetForDeployTarget(\n target?: FarmDeployTarget,\n): BaseFarmConfig[\"preset\"] | undefined {\n switch (normalizeDeployTarget(target)) {\n case \"vercel\":\n return \"vercel\";\n case \"cloudflare\":\n return \"cloudflare-pages\";\n case \"netlify\":\n return \"netlify\";\n case \"node\":\n return \"node-server\";\n default:\n return undefined;\n }\n}\n\nexport function getDeployTargetForPreset(preset?: string): FarmDeployTarget | undefined {\n if (!preset) return undefined;\n if (preset === \"vercel\" || preset === \"vercel-edge\") return \"vercel\";\n if (preset === \"cloudflare\" || preset === \"cloudflare-pages\" || preset === \"cloudflare-module\") {\n return \"cloudflare\";\n }\n if (preset === \"netlify\" || preset === \"netlify-edge\") return \"netlify\";\n if (preset === \"node-server\") return \"node\";\n return undefined;\n}\n\nexport function getDefaultDeployOutputDir(\n target: FarmDeployTarget | undefined,\n preset: string | undefined,\n distDir: string,\n): string {\n const normalizedTarget = normalizeDeployTarget(target) || getDeployTargetForPreset(preset);\n if (normalizedTarget === \"vercel\") return \".vercel/output\";\n return `${distDir}/.output`;\n}\n\nexport function resolveDeployOutputPath(root: string, outputDir: string): string {\n return path.isAbsolute(outputDir) ? outputDir : path.join(root, outputDir);\n}\n\nexport function resolveDeployConfig(\n config: Pick<FarmUserConfig, \"deploy\" | \"preset\" | \"distDir\">,\n overrides: {\n target?: FarmDeployTarget;\n preset?: BaseFarmConfig[\"preset\"];\n outputDir?: string;\n } = {},\n): ResolvedFarmDeployConfig {\n const deploy = config.deploy || {};\n const distDir = config.distDir || \".farm\";\n const target = normalizeDeployTarget(overrides.target || deploy.target);\n const preset =\n overrides.preset ||\n deploy.preset ||\n config.preset ||\n getPresetForDeployTarget(target) ||\n \"node-server\";\n const resolvedTarget = target || getDeployTargetForPreset(preset);\n const platformOutput =\n resolvedTarget === \"vercel\"\n ? deploy.vercel?.outputDirectory\n : resolvedTarget === \"cloudflare\"\n ? deploy.cloudflare?.outputDir\n : resolvedTarget === \"netlify\"\n ? deploy.netlify?.outputDir\n : undefined;\n const outputDir =\n overrides.outputDir ||\n deploy.outputDir ||\n deploy.output ||\n platformOutput ||\n getDefaultDeployOutputDir(resolvedTarget, preset, distDir);\n\n return {\n ...deploy,\n target: resolvedTarget,\n preset,\n outputDir,\n };\n}\n\nexport function resolveMigrationsConfig(\n migrations: FarmMigrationsUserConfig | undefined,\n): ResolvedFarmMigrationsConfig {\n if (!migrations) return { commands: [] };\n if (Array.isArray(migrations)) return { commands: migrations };\n return { commands: migrations.commands || [] };\n}\n\nexport const DOCS_CONFIG_FILENAMES = [\n \"docs.config.ts\",\n \"docs.config.tsx\",\n \"docs.config.mts\",\n \"docs.config.cts\",\n \"docs.config.js\",\n \"docs.config.jsx\",\n \"docs.config.mjs\",\n \"docs.config.cjs\",\n \"docs.json\",\n];\n\nfunction normalizeDocsRoute(value: string | undefined, fallback = \"/docs\"): string {\n const raw = (value || fallback).trim();\n if (!raw || raw === \"/\") return \"/\";\n const normalized = raw\n .replace(/\\\\/g, \"/\")\n .replace(/\\/+/g, \"/\")\n .replace(/^\\/?/, \"/\")\n .replace(/\\/+$/, \"\");\n return normalized || \"/\";\n}\n\nfunction docsRouteToEntry(route: string): string {\n const entry = route.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n return entry || \"docs\";\n}\n\nfunction normalizeDocsContentDir(value: string | undefined): string | undefined {\n if (!value) return undefined;\n const normalized = value.replace(/\\\\/g, \"/\").replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n return normalized || undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction cloneSerializable(value: unknown, seen = new WeakSet<object>()): any {\n if (value === null) return null;\n\n const valueType = typeof value;\n if (valueType === \"string\" || valueType === \"number\" || valueType === \"boolean\") {\n return value;\n }\n if (valueType === \"undefined\" || valueType === \"function\" || valueType === \"symbol\") {\n return undefined;\n }\n if (Array.isArray(value)) {\n return value.map((item) => cloneSerializable(item, seen)).filter((item) => item !== undefined);\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (isRecord(value)) {\n if (seen.has(value)) return undefined;\n seen.add(value);\n\n const output: Record<string, any> = {};\n for (const [key, nestedValue] of Object.entries(value)) {\n const clonedValue = cloneSerializable(nestedValue, seen);\n if (clonedValue !== undefined) {\n output[key] = clonedValue;\n }\n }\n return output;\n }\n\n return undefined;\n}\n\nfunction sanitizeDocsConfig(config: Partial<DocsConfig>): Partial<DocsConfig> {\n return cloneSerializable(config) || {};\n}\n\nexport async function findDocsConfigPath(\n rootDir: string,\n configPath?: string,\n): Promise<string | undefined> {\n const { existsSync } = await import(\"fs\");\n const root = path.resolve(rootDir || process.cwd());\n\n if (configPath) {\n const resolvedPath = path.isAbsolute(configPath) ? configPath : path.join(root, configPath);\n if (!existsSync(resolvedPath)) {\n throw new Error(`Could not find docs config at ${configPath}.`);\n }\n return path.resolve(resolvedPath);\n }\n\n for (const filename of DOCS_CONFIG_FILENAMES) {\n const resolvedPath = path.join(root, filename);\n if (existsSync(resolvedPath)) {\n return resolvedPath;\n }\n }\n\n return undefined;\n}\n\nexport async function loadDocsConfig(\n rootDir: string,\n configPath?: string,\n): Promise<{ config: Partial<DocsConfig>; configPath: string } | undefined> {\n const fs = await import(\"fs/promises\");\n const { pathToFileURL } = await import(\"url\");\n const root = path.resolve(rootDir || process.cwd());\n const resolvedPath = await findDocsConfigPath(root, configPath);\n\n if (!resolvedPath) return undefined;\n\n try {\n if (resolvedPath.endsWith(\".json\")) {\n const content = await fs.readFile(resolvedPath, \"utf8\");\n return { config: JSON.parse(content), configPath: resolvedPath };\n }\n\n const { build } = await import(\"esbuild\");\n const configCacheDir = path.join(root, \".farm\", \".config-loader\");\n await fs.mkdir(configCacheDir, { recursive: true });\n const modulePath = path.join(\n configCacheDir,\n `docs-config-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n );\n\n await build({\n absWorkingDir: root,\n entryPoints: [resolvedPath],\n outfile: modulePath,\n bundle: true,\n format: \"esm\",\n platform: \"node\",\n target: `node${process.versions.node.split(\".\")[0]}`,\n packages: \"external\",\n jsx: \"automatic\",\n logLevel: \"silent\",\n sourcemap: \"inline\",\n });\n\n const moduleUrl = pathToFileURL(modulePath).href + `?t=${Date.now()}`;\n let importedConfig: any;\n\n try {\n importedConfig = await import(/* @vite-ignore */ moduleUrl);\n } finally {\n await fs.unlink(modulePath).catch(() => undefined);\n }\n\n return {\n config: importedConfig.default || importedConfig,\n configPath: resolvedPath,\n };\n } catch (error: any) {\n const relativePath = path.relative(root, resolvedPath) || resolvedPath;\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load docs config from ${relativePath}: ${message}`);\n }\n}\n\nexport async function resolveDocsConfig(\n userDocs: FarmDocsUserConfig | undefined,\n options: {\n root?: string;\n srcDir?: string;\n } = {},\n): Promise<FarmDocsResolvedConfig> {\n const root = options.root || process.cwd();\n\n if (userDocs === false) {\n return {\n enabled: false,\n entry: \"/docs\",\n config: { entry: \"docs\", docsPath: \"/docs\" },\n };\n }\n\n const docsOptions = isRecord(userDocs) ? userDocs : {};\n if (docsOptions.enabled === false) {\n return {\n enabled: false,\n entry: \"/docs\",\n config: { entry: \"docs\", docsPath: \"/docs\" },\n };\n }\n\n const loadedConfig = await loadDocsConfig(root, docsOptions.configPath);\n const hasExplicitDocsConfig = userDocs === true || isRecord(userDocs);\n\n if (!hasExplicitDocsConfig && !loadedConfig) {\n return {\n enabled: false,\n entry: \"/docs\",\n config: { entry: \"docs\", docsPath: \"/docs\" },\n };\n }\n\n const inlineDocsConfig = sanitizeDocsConfig(docsOptions.config || {});\n const directDocsConfig = sanitizeDocsConfig({\n ...docsOptions,\n enabled: undefined,\n config: undefined,\n configPath: undefined,\n } as Partial<DocsConfig>);\n const loadedDocsConfig = sanitizeDocsConfig(loadedConfig?.config || {});\n const mergedDocsConfig: Partial<DocsConfig> = {\n ...loadedDocsConfig,\n ...inlineDocsConfig,\n ...directDocsConfig,\n };\n\n const explicitRoute = typeof docsOptions.entry === \"string\" ? docsOptions.entry : undefined;\n const configuredDocsPath =\n typeof mergedDocsConfig.docsPath === \"string\" ? mergedDocsConfig.docsPath : undefined;\n const configuredEntry =\n typeof mergedDocsConfig.entry === \"string\" ? mergedDocsConfig.entry : undefined;\n const entryRoute = normalizeDocsRoute(\n configuredDocsPath || explicitRoute || (configuredEntry ? `/${configuredEntry}` : undefined),\n );\n const docsEntry =\n explicitRoute && explicitRoute.startsWith(\"/\")\n ? docsRouteToEntry(explicitRoute)\n : docsRouteToEntry(configuredEntry || entryRoute);\n const contentDir = normalizeDocsContentDir(docsOptions.contentDir || mergedDocsConfig.contentDir);\n\n return {\n enabled: true,\n entry: entryRoute,\n contentDir,\n configPath: loadedConfig?.configPath,\n config: {\n ...mergedDocsConfig,\n entry: docsEntry,\n docsPath: entryRoute,\n ...(contentDir ? { contentDir } : {}),\n },\n };\n}\n\nexport async function resolveConfig(\n userConfig: FarmUserConfig,\n mode: \"development\" | \"production\",\n): Promise<ResolvedFarmConfig> {\n const projectRoot = userConfig.root || process.cwd();\n const layerResolution = await resolveFarmLayers(userConfig, {\n root: projectRoot,\n mode,\n });\n userConfig = layerResolution.config;\n\n const redirects =\n typeof userConfig.redirects === \"function\"\n ? await userConfig.redirects()\n : userConfig.redirects || [];\n\n const rewrites =\n typeof userConfig.rewrites === \"function\"\n ? await userConfig.rewrites()\n : userConfig.rewrites || [];\n\n const headers =\n typeof userConfig.headers === \"function\"\n ? await userConfig.headers()\n : userConfig.headers || [];\n const routeRules = normalizeRouteRules(userConfig.routeRules);\n const routeRuleRedirects = routeRulesToRedirects(routeRules);\n const routeRuleHeaders = routeRulesToHeaders(routeRules);\n\n const deploy = resolveDeployConfig(userConfig);\n const root = userConfig.root || process.cwd();\n const srcDir = userConfig.srcDir || \"src\";\n const docs = await resolveDocsConfig(userConfig.docs, { root, srcDir });\n const md = resolveMarkdownConfig(userConfig.md);\n const mdx = resolveMdxConfig(userConfig.mdx);\n const env = resolveEnv(userConfig.env, process.env);\n setEnv(env);\n const generateBuildId = userConfig.generateBuildId || (() => `build-${Date.now()}`);\n const deploymentId = normalizeFarmDeploymentId(\n userConfig.deploymentId ||\n process.env.FARM_DEPLOYMENT_ID ||\n process.env.VERCEL_GIT_COMMIT_SHA ||\n process.env.CF_PAGES_COMMIT_SHA ||\n (mode === \"production\" ? await generateBuildId() : \"development\"),\n );\n\n const resolved: ResolvedFarmConfig = {\n [FARM_RESOLVED_CUSTOM_CONTEXT]: typeof userConfig.context === \"function\",\n root,\n srcDir,\n extends: userConfig.extends || [],\n layers: layerResolution.layers,\n outDir: userConfig.outDir || \"dist\",\n basePath: userConfig.basePath || \"/\",\n preset: deploy.preset || \"node-server\",\n deploy,\n docs,\n md,\n mdx,\n migrations: resolveMigrationsConfig(userConfig.migrations),\n cron: resolveCronConfig(userConfig.cron),\n workflows: resolveWorkflowsConfig(userConfig.workflows),\n observability: userConfig.observability ?? false,\n devtools: resolveFarmDevtoolsConfig(userConfig.devtools, mode),\n storage: userConfig.storage || {},\n suppressLintOnLink: userConfig.suppressLintOnLink ?? false,\n experimental: {\n serverComponents: false,\n serverActions: false,\n ...userConfig.experimental,\n },\n plugins: [...resolveIntegrationPlugins(userConfig.integrations), ...(userConfig.plugins || [])],\n integrations: userConfig.integrations || {},\n trailingSlash: userConfig.trailingSlash ?? false,\n redirects: () => [...redirects, ...routeRuleRedirects],\n rewrites: () => rewrites,\n headers: () => [...headers, ...routeRuleHeaders],\n routeRules,\n images: resolveFarmImageConfig(userConfig.images),\n publicDir: userConfig.publicDir || \"public\",\n i18n: resolveFarmI18nConfig(userConfig.i18n, { root, mode }),\n openapi: {\n enabled: false,\n route: \"/docs/reference\",\n title: \"API Documentation\",\n description: \"Auto-generated API documentation\",\n version: \"1.0.0\",\n servers: [{ url: \"http://localhost:3000\", description: \"Development server\" }],\n ...userConfig.openapi,\n },\n middleware: userConfig.middleware || {},\n notFound: userConfig.notFound || {},\n context: userConfig.context || (() => undefined),\n serverActions: resolveServerActionsConfig(userConfig.serverActions),\n deploymentId,\n output: userConfig.output || \"standalone\",\n distDir: userConfig.distDir || \".farm\",\n generateBuildId,\n compress: userConfig.compress ?? true,\n devIndicators: {\n buildActivity: true,\n buildActivityPosition: \"bottom-right\",\n ...userConfig.devIndicators,\n },\n serverRuntimeConfig: userConfig.serverRuntimeConfig || {},\n publicRuntimeConfig: userConfig.publicRuntimeConfig || {},\n env,\n typescript: {\n tsconfigPath: \"tsconfig.json\",\n ignoreBuildErrors: false,\n ...userConfig.typescript,\n },\n vite: typeof userConfig.vite === \"function\" ? userConfig.vite({}) : userConfig.vite || {},\n };\n\n return resolved;\n}\n\nexport async function loadConfig(\n rootDir?: string,\n configPath?: string,\n mode = process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n loadEnvironment?: (typeof import(\"vite\"))[\"loadEnv\"],\n): Promise<FarmUserConfig | undefined> {\n const { existsSync } = await import(\"fs\");\n const loadEnv = loadEnvironment || (await import(\"vite\")).loadEnv;\n\n const root = rootDir || process.cwd();\n const loadedEnv = loadEnv(mode, root, \"\");\n for (const [key, value] of Object.entries(loadedEnv)) {\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n const searchPaths = [\n configPath,\n \"farm.config.ts\",\n \"farm.config.mts\",\n \"farm.config.js\",\n \"farm.config.mjs\",\n \"config.ts\",\n \"config.mts\",\n \"config.js\",\n \"config.mjs\",\n ].filter(Boolean) as string[];\n\n for (const relativePath of searchPaths) {\n try {\n // Use path.join for proper path construction\n const absolutePath = relativePath.startsWith(\"/\")\n ? relativePath\n : path.join(root, relativePath);\n\n // Normalize the path to handle any issues\n const normalizedPath = path.resolve(absolutePath);\n\n // Check if file exists before trying to import\n if (!existsSync(normalizedPath)) {\n continue;\n }\n\n const loadedConfig = await loadFarmConfigFile<FarmUserConfig>(normalizedPath, { root });\n return loadedConfig.root === undefined ? { ...loadedConfig, root } : loadedConfig;\n } catch (error: any) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to load config from ${relativePath}: ${message}`);\n }\n }\n return undefined;\n}\n","import {\n buildDocsAgentDiscoverySpec,\n buildDocsConfigMap,\n buildDocsDiagnostics as buildFarmingDocsDiagnostics,\n buildDocsSitemapManifest,\n performDocsSearch,\n renderDocsAgentsDocument,\n renderDocsLlmsTxt,\n renderDocsMarkdownDocument,\n renderDocsRobotsTxt,\n renderDocsSitemapMarkdown,\n renderDocsSitemapXml,\n renderDocsSkillDocument,\n type DocsConfig,\n type DocsLlmsTxtPageInput,\n type DocsSearchSourcePage,\n type DocsSitemapPageInput,\n} from \"@farming-labs/docs\";\nimport { resolveDocsConfig } from \"../config\";\nimport type { FarmDocsResolvedConfig, FarmDocsUserConfig } from \"./types\";\nimport {\n discoverFarmDocsPages,\n type LoadedFarmDocsPage,\n loadFarmDocsPage,\n resolveFarmDocsContentDir,\n toFarmDocsMarkdownPage,\n} from \"./handler\";\n\nexport interface FarmDocsAPIOptions {\n rootDir?: string;\n root?: string;\n srcDir?: string;\n docs?: FarmDocsUserConfig | FarmDocsResolvedConfig;\n config?: Partial<DocsConfig>;\n configPath?: string;\n entry?: string;\n docsPath?: string;\n contentDir?: string;\n}\n\nexport interface FarmDocsCloudRouteOptions {\n locale?: string;\n publicBaseUrl?: string;\n}\n\nexport interface FarmDocsCloudServer {\n handleRequest(request: Request, options?: FarmDocsCloudRouteOptions): Promise<Response>;\n}\n\nexport type FarmDocsCloudIntegration =\n | FarmDocsCloudServer\n | (FarmDocsCloudRouteOptions & { docsCloud?: FarmDocsCloudServer });\n\nexport interface FarmDocsAPIRouteHandlers {\n GET(request: Request): Promise<Response>;\n POST(request: Request): Promise<Response>;\n}\n\nexport type FarmDocsAPIHandler = (request: Request) => Promise<Response | null>;\n\ninterface FarmDocsAPIContext {\n root: string;\n srcDir: string;\n docs: FarmDocsResolvedConfig;\n contentDir: string;\n}\n\ntype JsonRecord = Record<string, unknown>;\ntype DocsAPIPathTarget = {\n format?: string;\n slug?: string;\n};\ntype FarmDocsRuntimeConfig = {\n root?: string;\n srcDir?: string;\n docs?: FarmDocsResolvedConfig;\n};\n\ndeclare global {\n // Injected by Farm's generated server entry so route wrappers can stay zero-config.\n // eslint-disable-next-line no-var\n var __FARM_DOCS_RUNTIME_CONFIG__: FarmDocsRuntimeConfig | undefined;\n}\n\nfunction isRecord(value: unknown): value is JsonRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isResolvedDocsConfig(value: unknown): value is FarmDocsResolvedConfig {\n return (\n isRecord(value) &&\n typeof value.enabled === \"boolean\" &&\n typeof value.entry === \"string\" &&\n isRecord(value.config)\n );\n}\n\nexport function isFarmDocsAPIRequest(requestOrPathname: Request | string): boolean {\n const pathname =\n typeof requestOrPathname === \"string\"\n ? requestOrPathname\n : new URL(requestOrPathname.url).pathname;\n\n return pathname === \"/api/docs\" || pathname.startsWith(\"/api/docs/\");\n}\n\nfunction json(data: unknown, init: ResponseInit = {}): Response {\n const headers = new Headers(init.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n return new Response(JSON.stringify(data), { ...init, headers });\n}\n\nfunction text(content: string, contentType: string, init: ResponseInit = {}): Response {\n const headers = new Headers(init.headers);\n headers.set(\"Content-Type\", contentType);\n return new Response(content, { ...init, headers });\n}\n\nfunction normalizeAction(value: string | null | undefined): string | undefined {\n return value?.trim().toLowerCase().replace(/_/g, \"-\") || undefined;\n}\n\nfunction getDocsTitle(docs: FarmDocsResolvedConfig): string {\n return typeof docs.config.nav === \"object\" && docs.config.nav && \"title\" in docs.config.nav\n ? String((docs.config.nav as { title?: unknown }).title || \"Documentation\")\n : \"Documentation\";\n}\n\nfunction isDocsCloudServer(value: unknown): value is FarmDocsCloudServer {\n return isRecord(value) && typeof value.handleRequest === \"function\";\n}\n\nfunction resolveDocsCloudIntegration(\n integration?: FarmDocsCloudIntegration,\n): { docsCloud: FarmDocsCloudServer; routeOptions: FarmDocsCloudRouteOptions } | undefined {\n if (!integration) return undefined;\n\n if (isDocsCloudServer(integration)) {\n return { docsCloud: integration, routeOptions: {} };\n }\n\n if (!integration.docsCloud) return undefined;\n\n return {\n docsCloud: integration.docsCloud,\n routeOptions: {\n locale: integration.locale,\n publicBaseUrl: integration.publicBaseUrl,\n },\n };\n}\n\nfunction isDocsCloudGetRequest(request: Request): boolean {\n const url = new URL(request.url);\n const cloud = normalizeAction(url.searchParams.get(\"cloud\"));\n const action = normalizeAction(url.searchParams.get(\"action\"));\n const format = normalizeAction(url.searchParams.get(\"format\"));\n\n return (\n cloud === \"config\" ||\n cloud === \"public-config\" ||\n action === \"cloud-config\" ||\n action === \"docs-cloud-config\" ||\n format === \"cloud-config\" ||\n format === \"docs-cloud-config\"\n );\n}\n\nfunction isDocsCloudAction(action: string | undefined): boolean {\n return Boolean(\n action &&\n [\"analytics\", \"track\", \"track-event\", \"event\", \"ask-ai\", \"ai\", \"chat\", \"docs-cloud\"].includes(\n action,\n ),\n );\n}\n\nasync function readJson(request: Request): Promise<unknown> {\n try {\n return await request.clone().json();\n } catch {\n return undefined;\n }\n}\n\nasync function isDocsCloudPostRequest(request: Request): Promise<boolean> {\n const url = new URL(request.url);\n const cloud = normalizeAction(url.searchParams.get(\"cloud\"));\n const action = normalizeAction(url.searchParams.get(\"action\"));\n\n if (isDocsCloudAction(cloud) || isDocsCloudAction(action)) return true;\n\n const body = await readJson(request);\n if (!isRecord(body)) return false;\n\n const bodyAction = normalizeAction(typeof body.action === \"string\" ? body.action : undefined);\n if (isDocsCloudAction(bodyAction)) return true;\n\n if (typeof body.type === \"string\") return true;\n if (isRecord(body.event) && typeof body.event.type === \"string\") return true;\n if (isRecord(body.payload) && typeof body.payload.type === \"string\") return true;\n\n return false;\n}\n\nfunction normalizeDocsApiSlug(\n value: string | null | undefined,\n docs: FarmDocsResolvedConfig,\n): string {\n const entry = docs.entry.replace(/^\\/+|\\/+$/g, \"\");\n let slug = (value || \"\").trim().replace(/^\\/+|\\/+$/g, \"\");\n\n if (entry && slug === entry) return \"\";\n if (entry && slug.startsWith(`${entry}/`)) {\n slug = slug.slice(entry.length + 1);\n }\n\n return decodeURIComponent(slug).replace(/\\.(mdx?|markdown)$/i, \"\");\n}\n\nfunction getDocsAPIPathTarget(request: Request): DocsAPIPathTarget {\n const pathname = new URL(request.url).pathname.replace(/\\/+$/, \"\") || \"/\";\n const prefix = \"/api/docs\";\n\n if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) return {};\n\n const rawValue = pathname === prefix ? \"\" : pathname.slice(prefix.length + 1);\n const value = rawValue.replace(/^\\/+|\\/+$/g, \"\");\n const normalizedValue = normalizeAction(value);\n\n if (!value) return {};\n if (\n normalizedValue === \"agent\" ||\n normalizedValue === \"agent.json\" ||\n normalizedValue === \"agent/spec\"\n ) {\n return { format: \"agent-spec\" };\n }\n if (\n normalizedValue === \"agents\" ||\n normalizedValue === \"agents.md\" ||\n normalizedValue === \"agent.md\"\n ) {\n return { format: \"agents\" };\n }\n if (normalizedValue === \"skill\" || normalizedValue === \"skill.md\") return { format: \"skill\" };\n if (normalizedValue === \"llms.txt\") return { format: \"llms\" };\n if (normalizedValue === \"llms-full.txt\") return { format: \"llms-full\" };\n if (normalizedValue === \"sitemap.md\") return { format: \"sitemap-md\" };\n if (normalizedValue === \"sitemap.xml\") return { format: \"sitemap-xml\" };\n if (normalizedValue === \"robots.txt\") return { format: \"robots\" };\n if (/\\.(mdx?|markdown)$/i.test(value)) return { format: \"markdown\", slug: value };\n\n return { slug: value };\n}\n\nfunction getDocsAPIFormat(request: Request): string | undefined {\n const url = new URL(request.url);\n return (\n normalizeAction(url.searchParams.get(\"format\") || url.searchParams.get(\"type\")) ||\n getDocsAPIPathTarget(request).format\n );\n}\n\nfunction getDocsDescription(docs: FarmDocsResolvedConfig): string | undefined {\n return docs.config.metadata?.description;\n}\n\nfunction getLoadedDocsPages(context: FarmDocsAPIContext): LoadedFarmDocsPage[] {\n return discoverFarmDocsPages(context.contentDir, context.docs)\n .map((page) => loadFarmDocsPage(context.contentDir, context.docs, page.slug))\n .filter((page): page is LoadedFarmDocsPage => Boolean(page));\n}\n\nfunction toDocsSourcePage(page: LoadedFarmDocsPage): DocsSearchSourcePage {\n return {\n ...toFarmDocsMarkdownPage(page),\n sourcePath: page.sourcePath,\n };\n}\n\nfunction toDocsSitemapPage(page: LoadedFarmDocsPage): DocsSitemapPageInput {\n return {\n ...toFarmDocsMarkdownPage(page),\n sourcePath: page.sourcePath,\n };\n}\n\nfunction toDocsLlmsPage(page: LoadedFarmDocsPage): DocsLlmsTxtPageInput {\n return toFarmDocsMarkdownPage(page);\n}\n\nfunction getDocsLlmsOptions(context: FarmDocsAPIContext, request: Request) {\n const configured = isRecord(context.docs.config.llmsTxt) ? context.docs.config.llmsTxt : {};\n return {\n enabled: true,\n baseUrl: new URL(request.url).origin,\n siteTitle: getDocsTitle(context.docs),\n siteDescription: getDocsDescription(context.docs),\n ...configured,\n };\n}\n\nfunction getDocsDiscoveryOptions(context: FarmDocsAPIContext, request: Request) {\n const origin = new URL(request.url).origin;\n\n return {\n origin,\n entry: context.docs.entry,\n i18n: null,\n search: context.docs.config.search ?? true,\n mcp: {\n enabled: false,\n route: \"/api/docs/mcp\",\n name: `${getDocsTitle(context.docs)} MCP`,\n version: \"1\",\n tools: {\n listDocs: false,\n listPages: false,\n readPage: false,\n searchDocs: false,\n getNavigation: false,\n getCodeExamples: false,\n getConfigSchema: false,\n },\n },\n feedback: undefined,\n llms: getDocsLlmsOptions(context, request),\n sitemap: context.docs.config.sitemap ?? true,\n robots: context.docs.config.robots ?? true,\n openapi: context.docs.config.apiReference,\n markdown: {\n acceptHeader: true,\n signatureAgentHeader: true,\n },\n };\n}\n\nfunction buildSitemapManifest(context: FarmDocsAPIContext, request: Request) {\n const origin = new URL(request.url).origin;\n return buildDocsSitemapManifest({\n pages: getLoadedDocsPages(context).map(toDocsSitemapPage),\n entry: context.docs.entry,\n siteTitle: getDocsTitle(context.docs),\n baseUrl: origin,\n });\n}\n\nfunction renderLlmsTxt(context: FarmDocsAPIContext, request: Request, full: boolean): string {\n const generated = renderDocsLlmsTxt(\n getLoadedDocsPages(context).map(toDocsLlmsPage),\n getDocsLlmsOptions(context, request),\n );\n\n return full ? generated.llmsFullTxt : generated.llmsTxt;\n}\n\nfunction renderSkillDocument(context: FarmDocsAPIContext, request: Request): string {\n const farmAliases = [\n \"## Farm API Route Aliases\",\n \"\",\n \"- Search JSON: /api/docs?query=<term>\",\n \"- Config JSON: /api/docs?format=config\",\n \"- Markdown by query: /api/docs?format=markdown&path=<slug>\",\n \"- Markdown by path: /api/docs/<slug>.md\",\n \"- LLM summary: /api/docs?format=llms\",\n \"- Full LLM document: /api/docs?format=llms-full\",\n \"- Sitemap XML: /api/docs?format=sitemap-xml\",\n \"- Agent spec JSON: /api/docs/agent/spec\",\n ].join(\"\\n\");\n\n return `${renderDocsSkillDocument(getDocsDiscoveryOptions(context, request)).trim()}\\n\\n${farmAliases}\\n`;\n}\n\nfunction renderAgentsDocument(context: FarmDocsAPIContext, request: Request): string {\n return `${renderDocsAgentsDocument(getDocsDiscoveryOptions(context, request)).trim()}\\n`;\n}\n\nfunction buildAgentSpec(context: FarmDocsAPIContext, request: Request) {\n const url = new URL(request.url);\n const origin = url.origin;\n const pages = discoverFarmDocsPages(context.contentDir, context.docs);\n const spec = buildDocsAgentDiscoverySpec(getDocsDiscoveryOptions(context, request));\n const title = getDocsTitle(context.docs);\n\n return {\n ...spec,\n name: title,\n site: {\n ...spec.site,\n title,\n description: getDocsDescription(context.docs),\n entry: context.docs.entry,\n },\n entry: context.docs.entry,\n routes: {\n docs: `${origin}${context.docs.entry}`,\n config: `${origin}/api/docs?format=config`,\n search: `${origin}/api/docs?query=<term>`,\n markdown: `${origin}/api/docs/<slug>.md`,\n markdownQuery: `${origin}/api/docs?format=markdown&path=<slug>`,\n llms: `${origin}/api/docs?format=llms`,\n llmsFull: `${origin}/api/docs?format=llms-full`,\n sitemapXml: `${origin}/api/docs?format=sitemap-xml`,\n sitemapMarkdown: `${origin}/api/docs?format=sitemap-md`,\n robots: `${origin}/api/docs?format=robots`,\n skill: `${origin}/api/docs?format=skill`,\n agents: `${origin}/api/docs?format=agents`,\n agentSpec: `${origin}/api/docs/agent/spec`,\n },\n capabilities: {\n ...spec.capabilities,\n search: spec.capabilities.search,\n markdown: spec.capabilities.markdownRoutes,\n llms: spec.capabilities.llms,\n sitemap: spec.capabilities.sitemap,\n robots: spec.capabilities.robots,\n post: false,\n },\n pages,\n };\n}\n\nfunction buildDiagnostics(context: FarmDocsAPIContext) {\n const pages = discoverFarmDocsPages(context.contentDir, context.docs);\n const diagnostics = buildFarmingDocsDiagnostics(context.docs.config, {\n entry: context.docs.entry,\n mcp: {\n enabled: false,\n route: \"/api/docs/mcp\",\n name: `${getDocsTitle(context.docs)} MCP`,\n version: \"1\",\n tools: {\n listDocs: false,\n listPages: false,\n readPage: false,\n searchDocs: false,\n getNavigation: false,\n getCodeExamples: false,\n getConfigSchema: false,\n },\n },\n });\n\n return {\n ...diagnostics,\n enabled: context.docs.enabled,\n entry: context.docs.entry,\n root: context.root,\n srcDir: context.srcDir,\n contentDir: context.contentDir,\n configPath: context.docs.configPath || null,\n pageCount: pages.length,\n pages,\n };\n}\n\nasync function searchDocs(context: FarmDocsAPIContext, request: Request, query: string) {\n const loadedPages = getLoadedDocsPages(context);\n const sourcePages = loadedPages.map(toDocsSourcePage);\n const sourcePageByUrl = new Map(sourcePages.map((page) => [page.url, page]));\n const resultLimit =\n isRecord(context.docs.config.search) &&\n typeof context.docs.config.search.maxResults === \"number\"\n ? context.docs.config.search.maxResults\n : undefined;\n\n const results = await performDocsSearch({\n pages: sourcePages,\n query,\n search: context.docs.config.search ?? true,\n pathname: new URL(request.url).pathname,\n siteTitle: getDocsTitle(context.docs),\n limit: resultLimit,\n });\n\n return results.map((result) => {\n const pageUrl = result.url.split(\"#\")[0];\n const page = sourcePageByUrl.get(pageUrl);\n return {\n ...result,\n title: page?.title || result.content,\n href: page?.url || pageUrl,\n description: result.description || page?.description,\n };\n });\n}\n\nasync function resolveAPIContext(options: FarmDocsAPIOptions): Promise<FarmDocsAPIContext> {\n const runtimeConfig = globalThis.__FARM_DOCS_RUNTIME_CONFIG__;\n const root = options.rootDir || options.root || runtimeConfig?.root || process.cwd();\n const srcDir = options.srcDir || runtimeConfig?.srcDir || \"src\";\n const canUseRuntimeDocs =\n options.docs === undefined &&\n options.config === undefined &&\n options.configPath === undefined &&\n options.entry === undefined &&\n options.docsPath === undefined &&\n options.contentDir === undefined &&\n options.root === undefined &&\n options.rootDir === undefined &&\n options.srcDir === undefined;\n const docsInput =\n options.docs ??\n (canUseRuntimeDocs ? runtimeConfig?.docs : undefined) ??\n ({\n enabled: true,\n entry: options.entry,\n docsPath: options.docsPath,\n contentDir: options.contentDir,\n config: options.config,\n configPath: options.configPath,\n } satisfies Exclude<FarmDocsUserConfig, boolean>);\n const docs = isResolvedDocsConfig(docsInput)\n ? docsInput\n : await resolveDocsConfig(docsInput, { root, srcDir });\n\n return {\n root,\n srcDir,\n docs,\n contentDir: resolveFarmDocsContentDir(docs, { root, srcDir }),\n };\n}\n\nasync function handleDocsAPIGet(request: Request, context: FarmDocsAPIContext): Promise<Response> {\n if (!context.docs.enabled) {\n return json({ error: \"Docs are disabled\" }, { status: 404 });\n }\n\n const url = new URL(request.url);\n const format = getDocsAPIFormat(request);\n const pathTarget = getDocsAPIPathTarget(request);\n\n if (format === \"config\" || format === \"docs-config\") {\n return json({\n entry: context.docs.entry,\n contentDir: context.docs.contentDir || context.docs.config.contentDir || null,\n config: context.docs.config,\n map: buildDocsConfigMap(context.docs.config, {\n file: context.docs.configPath || \"farm.config.ts\",\n }),\n });\n }\n\n if (format === \"skill\")\n return text(renderSkillDocument(context, request), \"text/markdown; charset=utf-8\");\n if (format === \"agents\")\n return text(renderAgentsDocument(context, request), \"text/markdown; charset=utf-8\");\n if (format === \"agent\" || format === \"agent-spec\") return json(buildAgentSpec(context, request));\n if (format === \"diagnostics\") return json(buildDiagnostics(context));\n if (format === \"llms\")\n return text(renderLlmsTxt(context, request, false), \"text/plain; charset=utf-8\");\n if (format === \"llms-full\")\n return text(renderLlmsTxt(context, request, true), \"text/plain; charset=utf-8\");\n if (format === \"sitemap-md\") {\n return text(\n renderDocsSitemapMarkdown(buildSitemapManifest(context, request), {\n includeDescriptions: true,\n }),\n \"text/markdown; charset=utf-8\",\n );\n }\n if (format === \"sitemap-xml\" || format === \"sitemap\") {\n const origin = new URL(request.url).origin;\n return text(\n renderDocsSitemapXml(buildSitemapManifest(context, request), {\n baseUrl: origin,\n includeLastmod: true,\n }),\n \"application/xml; charset=utf-8\",\n );\n }\n if (format === \"robots\") {\n return text(\n renderDocsRobotsTxt({\n entry: context.docs.entry,\n sitemap: context.docs.config.sitemap ?? true,\n robots: context.docs.config.robots ?? true,\n baseUrl: new URL(request.url).origin,\n }),\n \"text/plain; charset=utf-8\",\n );\n }\n\n if (format === \"markdown\" || url.pathname.endsWith(\".md\")) {\n const pathParam = url.searchParams.get(\"path\") || url.searchParams.get(\"slug\");\n const slug = normalizeDocsApiSlug(pathParam ?? pathTarget.slug ?? \"\", context.docs);\n const page = loadFarmDocsPage(context.contentDir, context.docs, slug);\n if (!page) return text(\"Docs page not found\\n\", \"text/plain; charset=utf-8\", { status: 404 });\n return text(\n renderDocsMarkdownDocument(toFarmDocsMarkdownPage(page), {\n origin: new URL(request.url).origin,\n llms: getDocsLlmsOptions(context, request),\n sitemap: context.docs.config.sitemap,\n }),\n \"text/markdown; charset=utf-8\",\n );\n }\n\n const query = url.searchParams.get(\"query\") || url.searchParams.get(\"q\") || \"\";\n if (!query.trim()) return json([]);\n return json(await searchDocs(context, request, query));\n}\n\nexport function createDocsAPI(\n options: FarmDocsAPIOptions = {},\n cloudIntegration?: FarmDocsCloudIntegration,\n): FarmDocsAPIRouteHandlers {\n let contextPromise: Promise<FarmDocsAPIContext> | undefined;\n const getContext = () => {\n contextPromise ??= resolveAPIContext(options);\n return contextPromise;\n };\n const integration = resolveDocsCloudIntegration(cloudIntegration);\n\n return {\n async GET(request: Request) {\n if (integration && isDocsCloudGetRequest(request)) {\n return integration.docsCloud.handleRequest(request, integration.routeOptions);\n }\n\n return handleDocsAPIGet(request, await getContext());\n },\n async POST(request: Request) {\n if (integration && (await isDocsCloudPostRequest(request))) {\n return integration.docsCloud.handleRequest(request, integration.routeOptions);\n }\n\n return json(\n {\n error: \"AI is not enabled for this Farm docs API route yet.\",\n },\n { status: 501 },\n );\n },\n };\n}\n\nexport function createFarmDocsAPIHandler(\n options: FarmDocsAPIOptions = {},\n cloudIntegration?: FarmDocsCloudIntegration,\n): FarmDocsAPIHandler {\n const handlers = createDocsAPI(options, cloudIntegration);\n\n return async function handleFarmDocsAPIRequest(request: Request): Promise<Response | null> {\n if (!isFarmDocsAPIRequest(request)) return null;\n\n const method = request.method.toUpperCase();\n if (method === \"GET\" || method === \"HEAD\") {\n return handlers.GET(request);\n }\n if (method === \"POST\") {\n return handlers.POST(request);\n }\n\n return json(\n {\n error: \"Method Not Allowed\",\n },\n {\n status: 405,\n headers: {\n Allow: \"GET, HEAD, POST\",\n },\n },\n );\n };\n}\n","export {\n createFarmDocsHandler,\n discoverFarmDocsPages,\n getFarmDocsDocumentNavigationMatchers,\n getFarmDocsRouteTypeEntries,\n isFarmDocsRequest,\n loadFarmDocsPage,\n resolveFarmDocsContentDir,\n} from \"./handler\";\nexport { createDocsAPI, createFarmDocsAPIHandler, isFarmDocsAPIRequest } from \"./api\";\nexport type { FarmDocsHandlerOptions, FarmDocsPage, LoadedFarmDocsPage } from \"./handler\";\nexport type {\n FarmDocsAPIHandler,\n FarmDocsAPIOptions,\n FarmDocsAPIRouteHandlers,\n FarmDocsCloudIntegration,\n FarmDocsCloudRouteOptions,\n FarmDocsCloudServer,\n} from \"./api\";\nexport type {\n FarmDocsConfigInput,\n FarmDocsNavigationConfig,\n FarmDocsResolvedConfig,\n FarmDocsSidebarItem,\n FarmDocsUserConfig,\n} from \"./types\";\n","import type { OpenAPIConfig } from \"../config\";\nimport type { APIRouteInfo } from \"../type-generator\";\nimport * as z from \"zod\";\n\nexport interface OpenAPISpec {\n openapi: string;\n info: {\n title: string;\n description?: string;\n version: string;\n contact?: {\n name?: string;\n email?: string;\n url?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n };\n servers?: Array<{\n url: string;\n description?: string;\n }>;\n paths: Record<string, any>;\n components?: {\n schemas?: Record<string, any>;\n securitySchemes?: Record<string, any>;\n };\n}\n\ntype AllowedType = \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\nconst allowedType = new Set([\"string\", \"number\", \"boolean\", \"array\", \"object\"]);\n\nexport class OpenAPIGenerator {\n private config: OpenAPIConfig;\n private appDir: string;\n\n constructor(appDir: string, config: OpenAPIConfig) {\n this.appDir = appDir;\n this.config = config;\n }\n\n /**\n * Get type from Zod type\n */\n private getTypeFromZodType(zodType: z.ZodType<any>): AllowedType {\n const typeName = (zodType as any)._def?.typeName;\n if (typeName) {\n if (typeName === \"ZodString\") return \"string\";\n if (typeName === \"ZodNumber\") return \"number\";\n if (typeName === \"ZodBoolean\") return \"boolean\";\n if (typeName === \"ZodArray\") return \"array\";\n if (typeName === \"ZodObject\") return \"object\";\n }\n return \"string\";\n }\n\n /**\n * Process Zod type to OpenAPI schema\n */\n private processZodType(zodType: z.ZodType<any>): any {\n // Handle ZodOptional\n if (zodType instanceof z.ZodOptional) {\n const innerType = (zodType as any)._def.innerType;\n const innerSchema = this.processZodType(innerType);\n return {\n ...innerSchema,\n nullable: true,\n };\n }\n\n // Handle ZodObject\n if (zodType instanceof z.ZodObject) {\n const shape = (zodType as any).shape;\n if (shape) {\n const properties: Record<string, any> = {};\n const required: string[] = [];\n Object.entries(shape).forEach(([key, value]) => {\n if (value instanceof z.ZodType) {\n properties[key] = this.processZodType(value as z.ZodType<any>);\n if (!(value instanceof z.ZodOptional)) {\n required.push(key);\n }\n }\n });\n return {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n description: (zodType as any).description,\n };\n }\n }\n\n // Handle ZodArray\n if (zodType instanceof z.ZodArray) {\n const itemType = (zodType as any)._def.type;\n return {\n type: \"array\",\n items: this.processZodType(itemType),\n description: (zodType as any).description,\n };\n }\n\n // Handle ZodEnum\n if (zodType instanceof z.ZodEnum) {\n return {\n type: \"string\",\n enum: (zodType as any)._def.values,\n description: (zodType as any).description,\n };\n }\n\n // For primitive types\n const baseSchema: any = {\n type: this.getTypeFromZodType(zodType),\n description: (zodType as any).description,\n };\n\n // Add constraints if available\n if (\"minLength\" in zodType && (zodType as any).minLength) {\n baseSchema.minLength = (zodType as any).minLength;\n }\n if (\"maxLength\" in zodType && (zodType as any).maxLength) {\n baseSchema.maxLength = (zodType as any).maxLength;\n }\n if (\"min\" in zodType && (zodType as any).min !== undefined) {\n baseSchema.minimum = (zodType as any).min;\n }\n if (\"max\" in zodType && (zodType as any).max !== undefined) {\n baseSchema.maximum = (zodType as any).max;\n }\n\n return baseSchema;\n }\n\n /**\n * Generate standard error responses\n */\n private getStandardResponses(): Record<string, any> {\n return {\n \"200\": {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n description: \"Response data\",\n },\n },\n },\n },\n \"400\": {\n description: \"Bad Request. Usually due to missing parameters, or invalid parameters.\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: { type: \"string\" },\n error: { type: \"string\" },\n },\n required: [\"message\"],\n },\n },\n },\n },\n \"401\": {\n description: \"Unauthorized. Due to missing or invalid authentication.\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: { type: \"string\" },\n },\n required: [\"message\"],\n },\n },\n },\n },\n \"403\": {\n description:\n \"Forbidden. You do not have permission to access this resource or to perform this action.\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: { type: \"string\" },\n },\n },\n },\n },\n },\n \"404\": {\n description: \"Not Found. The requested resource was not found.\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: { type: \"string\" },\n },\n },\n },\n },\n },\n \"429\": {\n description: \"Too Many Requests. You have exceeded the rate limit. Try again later.\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: { type: \"string\" },\n },\n },\n },\n },\n },\n \"500\": {\n description:\n \"Internal Server Error. This is a problem with the server that you cannot fix.\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n message: { type: \"string\" },\n error: { type: \"string\" },\n },\n },\n },\n },\n },\n };\n }\n\n /**\n * Generate OpenAPI spec from API routes\n */\n async generateSpec(routes: APIRouteInfo[]): Promise<OpenAPISpec> {\n const spec: OpenAPISpec = {\n openapi: \"3.0.3\",\n info: {\n title: this.config.title || \"API Documentation\",\n description: this.config.description || \"Auto-generated API documentation\",\n version: this.config.version || \"1.0.0\",\n ...(this.config.contact && { contact: this.config.contact }),\n ...(this.config.license && { license: this.config.license }),\n },\n servers: this.config.servers || [\n { url: \"http://localhost:3000\", description: \"Development server\" },\n ],\n paths: {},\n components: {\n schemas: {},\n securitySchemes: {\n bearerAuth: {\n type: \"http\",\n scheme: \"bearer\",\n description: \"Bearer token authentication\",\n },\n apiKeyCookie: {\n type: \"apiKey\",\n in: \"cookie\",\n name: \"session\",\n description: \"API Key authentication via cookie\",\n },\n },\n },\n };\n\n // Group routes by path\n const routeGroups = new Map<string, APIRouteInfo[]>();\n for (const route of routes) {\n const key = route.path;\n if (!routeGroups.has(key)) {\n routeGroups.set(key, []);\n }\n routeGroups.get(key)!.push(route);\n }\n\n // Generate paths\n for (const [path, routeList] of routeGroups) {\n const openAPIPath = this.convertToOpenAPIPath(path);\n spec.paths[openAPIPath] = {};\n\n for (const route of routeList) {\n for (const method of route.methods) {\n const methodLower = method.toLowerCase();\n spec.paths[openAPIPath][methodLower] = await this.generateOperation(route, method);\n }\n }\n }\n\n return spec;\n }\n\n /**\n * Convert Farm.js API path to OpenAPI path format\n */\n private convertToOpenAPIPath(path: string): string {\n // Convert /api/auth/login to /auth/login\n return path.replace(/^\\/api/, \"\");\n }\n\n /**\n * Extract request body schema from endpoint\n */\n private async getRequestBody(route: APIRouteInfo, method: string): Promise<any> {\n if (![\"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(method)) {\n return undefined;\n }\n\n try {\n // Try to dynamically load the route module\n const modulePath = route.filePath;\n const routeModule = await import(/* @vite-ignore */ modulePath);\n\n // Get the method handler (GET, POST, etc.)\n const handler = routeModule[method];\n\n // Check for Farm.js endpoint format: handler.__types.body\n if (handler && handler.__types && handler.__types.body) {\n const bodySchema = handler.__types.body;\n\n if (bodySchema instanceof z.ZodObject || bodySchema instanceof z.ZodOptional) {\n const shape = (bodySchema as any).shape || (bodySchema as any)._def?.innerType?.shape;\n if (shape) {\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n Object.entries(shape).forEach(([key, value]) => {\n if (value instanceof z.ZodType) {\n properties[key] = this.processZodType(value as z.ZodType<any>);\n if (!(value instanceof z.ZodOptional)) {\n required.push(key);\n }\n }\n });\n return {\n required: bodySchema instanceof z.ZodOptional ? false : true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n },\n },\n },\n };\n }\n }\n }\n\n // Fallback: Check for better-call format: handler._type.body\n if (handler && handler._type && handler._type.body) {\n const bodySchema = handler._type.body;\n\n if (bodySchema instanceof z.ZodObject || bodySchema instanceof z.ZodOptional) {\n const shape = (bodySchema as any).shape || (bodySchema as any)._def?.innerType?.shape;\n if (shape) {\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n Object.entries(shape).forEach(([key, value]) => {\n if (value instanceof z.ZodType) {\n properties[key] = this.processZodType(value as z.ZodType<any>);\n if (!(value instanceof z.ZodOptional)) {\n required.push(key);\n }\n }\n });\n\n return {\n required: bodySchema instanceof z.ZodOptional ? false : true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n },\n },\n },\n };\n }\n }\n }\n } catch (error) {\n // If we can't load the module, return generic schema\n console.warn(`Could not extract schema from ${route.filePath}:`, error);\n }\n\n // Fallback to generic schema\n return {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n description: \"Request body\",\n },\n },\n },\n };\n }\n\n /**\n * Extract query parameters from endpoint\n */\n private async getParameters(route: APIRouteInfo, method: string): Promise<any[]> {\n const parameters: any[] = [];\n\n try {\n // Try to dynamically load the route module\n const modulePath = route.filePath;\n const routeModule = await import(/* @vite-ignore */ modulePath);\n\n // Get the method handler\n const handler = routeModule[method];\n\n // Check for Farm.js endpoint format: handler.__types.query\n if (handler && handler.__types && handler.__types.query) {\n const querySchema = handler.__types.query;\n\n if (querySchema instanceof z.ZodObject) {\n Object.entries((querySchema as any).shape).forEach(([key, value]) => {\n if (value instanceof z.ZodType) {\n parameters.push({\n name: key,\n in: \"query\",\n required: !(value instanceof z.ZodOptional),\n schema: this.processZodType(value as z.ZodType<any>),\n });\n }\n });\n }\n }\n\n // Fallback: Check for better-call format: handler._type.query\n if (handler && handler._type && handler._type.query) {\n const querySchema = handler._type.query;\n\n if (querySchema instanceof z.ZodObject) {\n Object.entries((querySchema as any).shape).forEach(([key, value]) => {\n if (value instanceof z.ZodType) {\n parameters.push({\n name: key,\n in: \"query\",\n required: !(value instanceof z.ZodOptional),\n schema: this.processZodType(value as z.ZodType<any>),\n });\n }\n });\n }\n }\n } catch (error) {\n console.warn(`Could not extract query params from ${route.filePath}:`, error);\n }\n\n return parameters;\n }\n\n /**\n * Generate OpenAPI operation from route info\n */\n private async generateOperation(route: APIRouteInfo, method: string): Promise<any> {\n const operation: any = {\n summary: this.generateSummary(route.path, method),\n description: this.generateDescription(route.path, method),\n operationId: this.generateOperationId(route.path, method),\n tags: this.generateTags(route.path),\n security: [{ bearerAuth: [] }, { apiKeyCookie: [] }],\n responses: this.getStandardResponses(),\n };\n\n // Add query parameters\n const parameters = await this.getParameters(route, method);\n if (parameters.length > 0) {\n operation.parameters = parameters;\n }\n\n // Add request body for POST, PUT, PATCH, DELETE\n if ([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"].includes(method)) {\n operation.requestBody = await this.getRequestBody(route, method);\n }\n\n return operation;\n }\n\n /**\n * Generate operation summary\n */\n private generateSummary(path: string, method: string): string {\n const cleanPath = path.replace(/^\\/api\\//, \"\");\n const pathParts = cleanPath.split(\"/\");\n const lastPart = pathParts[pathParts.length - 1];\n\n const action =\n method === \"GET\"\n ? \"Get\"\n : method === \"POST\"\n ? \"Create\"\n : method === \"PUT\"\n ? \"Update\"\n : method === \"DELETE\"\n ? \"Delete\"\n : method === \"PATCH\"\n ? \"Update\"\n : method;\n\n return `${action} ${lastPart}`;\n }\n\n /**\n * Generate operation description\n */\n private generateDescription(path: string, method: string): string {\n const cleanPath = path.replace(/^\\/api\\//, \"\");\n return `${method} ${cleanPath} endpoint`;\n }\n\n /**\n * Generate operation ID\n */\n private generateOperationId(path: string, method: string): string {\n const cleanPath = path.replace(/^\\/api\\//, \"\").replace(/\\//g, \"_\");\n return `${method.toLowerCase()}_${cleanPath}`;\n }\n\n /**\n * Generate tags for grouping operations\n */\n private generateTags(path: string): string[] {\n const cleanPath = path.replace(/^\\/api\\//, \"\");\n const pathParts = cleanPath.split(\"/\");\n\n if (pathParts.length > 1) {\n return [pathParts[0]]; // Use first part as tag\n }\n\n return [\"default\"];\n }\n\n /**\n * Generate OpenAPI spec file\n */\n async generateSpecFile(routes: APIRouteInfo[], outputPath: string): Promise<void> {\n const spec = await this.generateSpec(routes);\n const fs = require(\"fs\");\n const path = require(\"path\");\n\n // Ensure directory exists\n const dir = path.dirname(outputPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n // Write spec file\n fs.writeFileSync(outputPath, JSON.stringify(spec, null, 2));\n }\n}\n","import { OpenAPIGenerator } from \"./generator\";\nimport { APITypeGenerator } from \"../type-generator\";\nimport type { OpenAPIConfig } from \"../config\";\n\nexport class OpenAPIManager {\n private generator: OpenAPIGenerator;\n private apiTypeGenerator: APITypeGenerator;\n private config: OpenAPIConfig;\n private appDir: string;\n private specCache: any = null;\n\n constructor(appDir: string | readonly string[], config: OpenAPIConfig) {\n const appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n this.appDir = appDirs[appDirs.length - 1];\n this.config = config;\n this.generator = new OpenAPIGenerator(this.appDir, config);\n this.apiTypeGenerator = new APITypeGenerator(appDirs);\n }\n\n /**\n * Generate OpenAPI spec from API routes\n */\n async generateSpec(): Promise<any> {\n try {\n // Get API routes using the existing type generator\n const routes = this.apiTypeGenerator.scanAPIRoutes();\n\n // Generate OpenAPI spec (now async)\n const spec = await this.generator.generateSpec(routes);\n\n // Cache the spec\n this.specCache = spec;\n\n return spec;\n } catch (error) {\n console.error(\"Failed to generate OpenAPI spec:\", error);\n return null;\n }\n }\n\n /**\n * Get cached spec or generate new one\n */\n async getSpec(): Promise<any> {\n if (this.specCache) {\n return this.specCache;\n }\n\n return await this.generateSpec();\n }\n\n /**\n * Generate and save OpenAPI spec file\n */\n async generateSpecFile(): Promise<void> {\n try {\n const routes = this.apiTypeGenerator.scanAPIRoutes();\n const outputPath = `${this.appDir}/lib/openapi.spec.json`;\n\n await this.generator.generateSpecFile(routes, outputPath);\n console.log(\"✅ OpenAPI spec generated at:\", outputPath);\n } catch (error) {\n console.error(\"Failed to generate OpenAPI spec file:\", error);\n }\n }\n\n /**\n * Invalidate cache and regenerate spec\n */\n async invalidateCache(): Promise<void> {\n this.specCache = null;\n await this.generateSpec();\n }\n\n /**\n * Get the docs route handler\n */\n getDocsRouteHandler() {\n return async (req: any, res: any) => {\n try {\n const spec = await this.getSpec();\n\n if (!spec) {\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"text/html\");\n res.end(`\n <html>\n <body>\n <h1>Error</h1>\n <p>Failed to generate OpenAPI specification</p>\n </body>\n </html>\n `);\n return;\n }\n\n // Set headers for HTML response\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", \"text/html\");\n\n // Generate HTML with Scalar\n const html = this.generateDocsHTML(spec);\n res.end(html);\n } catch (error) {\n console.error(\"Error serving docs route:\", error);\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"text/html\");\n res.end(`\n <html>\n <body>\n <h1>Error</h1>\n <p>Failed to load API documentation</p>\n </body>\n </html>\n `);\n }\n };\n }\n\n /**\n * Generate HTML for docs route\n */\n private generateDocsHTML(spec: any): string {\n return `\n<!DOCTYPE html>\n<html>\n <head>\n <title>${this.config.title || \"API Documentation\"}</title>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <link rel=\"icon\" href=\"data:,\" />\n </head>\n <body>\n <script\n id=\"api-reference\"\n data-url=\"data:application/json;base64,${Buffer.from(JSON.stringify(spec)).toString(\"base64\")}\"\n ></script>\n <script src=\"https://cdn.jsdelivr.net/npm/@scalar/api-reference\"></script>\n </body>\n</html>\n `;\n }\n}\n","import path from \"node:path\";\nimport { getDeployTargetForPreset } from \"./config\";\nimport { resolveCronConfig, type FarmCronJob } from \"./cron\";\nimport {\n mergeFarmRouteRuntimeConfigs,\n resolveFarmRouteRuleRuntimeConfig,\n resolveFarmRouteRuntimeConfig,\n type ResolvedFarmRouteRuntimeConfig,\n} from \"./route-runtime\";\nimport type { FarmConfig } from \"./types\";\nimport type { FarmDiscoveredWorkflow } from \"./workflows\";\n\ntype RouteMapEntry = {\n pattern: string;\n modulePath: string;\n};\n\ntype RouteManagerLike = {\n getRoutes(): Map<string, RouteMapEntry>;\n getLayouts(): Map<string, RouteMapEntry>;\n getLoadings(): Map<string, RouteMapEntry>;\n getErrors(): Map<string, RouteMapEntry>;\n resolveRouteRuntimeConfig?(\n pattern: string,\n ): Promise<ResolvedFarmRouteRuntimeConfig> | ResolvedFarmRouteRuntimeConfig;\n};\n\ntype APIRouteManagerLike = {\n getRoutes(): Map<\n string,\n {\n path: string;\n filePath: string;\n methods: string[];\n runtime?: \"auto\" | \"node\" | \"edge\";\n regions?: \"auto\" | readonly string[];\n maxDuration?: \"auto\" | number;\n }\n >;\n};\n\ntype MiddlewareManagerLike = {\n getMiddlewares(): Array<{\n path: string;\n filePath: string;\n handlers: unknown[];\n source?: \"config\" | \"file\";\n }>;\n};\n\ntype IntegrationLike = {\n kind?: string;\n type?: string;\n category?: string;\n serverRuntime?: boolean;\n routes?: ReadonlyArray<{\n path: string;\n method?: string;\n methods?: readonly string[];\n }>;\n middleware?: readonly unknown[];\n providers?: readonly unknown[];\n schema?: {\n models?: Record<string, unknown>;\n };\n};\n\nexport type FarmDevtoolsRuntime = {\n runtime: \"auto\" | \"node\" | \"edge\";\n regions?: string[];\n maxDuration?: number;\n};\n\nexport type FarmDevtoolsDiagnostic = {\n severity: \"error\" | \"warning\" | \"info\";\n code: string;\n title: string;\n message: string;\n action?: string;\n};\n\nexport type FarmDevtoolsSnapshot = {\n generatedAt: string;\n health: \"ready\" | \"attention\" | \"error\";\n project: {\n name: string;\n root: string;\n srcDir: string;\n basePath: string;\n deploymentId: string;\n };\n deployment: {\n target: string;\n preset: string;\n outputDir?: string;\n };\n counts: {\n pages: number;\n layouts: number;\n loadingBoundaries: number;\n errorBoundaries: number;\n apiRoutes: number;\n middleware: number;\n integrations: number;\n storageMounts: number;\n cronJobs: number;\n workflows: number;\n layers: number;\n diagnostics: number;\n };\n routes: Array<{\n kind: \"page\" | \"layout\" | \"loading\" | \"error\";\n pattern: string;\n filePath: string;\n runtime?: FarmDevtoolsRuntime;\n }>;\n apiRoutes: Array<{\n path: string;\n methods: string[];\n filePath: string;\n runtime: FarmDevtoolsRuntime;\n }>;\n middleware: Array<{\n path: string;\n source: \"config\" | \"file\";\n filePath: string;\n handlerCount: number;\n }>;\n integrations: Array<{\n key: string;\n type: string;\n category: string;\n serverRuntime: boolean;\n routes: Array<{ path: string; methods: string[] }>;\n middlewareCount: number;\n providerCount: number;\n schemaModelCount: number;\n }>;\n storage: Array<{\n mount: string;\n driver: string;\n default: boolean;\n }>;\n cron: FarmCronJob[];\n workflows: Array<{\n id: string;\n filePath: string;\n routePath: string;\n schedule: string[];\n timezone?: string;\n }>;\n layers: Array<{\n name: string;\n source: string;\n srcDir: string;\n }>;\n environment: {\n server: string[];\n public: string[];\n };\n docs: {\n enabled: boolean;\n entry?: string;\n };\n features: {\n openapi: boolean;\n markdown: boolean;\n serverComponents: boolean;\n serverActions: boolean;\n optimizedBoundary: boolean;\n observability: boolean;\n };\n diagnostics: FarmDevtoolsDiagnostic[];\n};\n\nexport interface CreateFarmDevtoolsSnapshotInput {\n root: string;\n srcDir: string;\n routeManager: RouteManagerLike;\n apiRouteManager: APIRouteManagerLike;\n middlewareManager: MiddlewareManagerLike;\n config?: FarmConfig & { openapi?: { enabled?: boolean } };\n workflows?: readonly FarmDiscoveredWorkflow[];\n now?: () => Date;\n env?: Record<string, string | undefined>;\n}\n\nfunction normalizePath(value: string): string {\n return value.replace(/\\\\/g, \"/\");\n}\n\nfunction toProjectPath(root: string, filePath: string): string {\n const normalizedRoot = normalizePath(root).replace(/\\/$/, \"\");\n const normalizedFile = normalizePath(filePath);\n if (normalizedFile.startsWith(normalizedRoot + \"/\")) {\n return normalizedFile.slice(normalizedRoot.length + 1);\n }\n return normalizedFile;\n}\n\nfunction sortByPath<T extends { path?: string; pattern?: string }>(items: T[]): T[] {\n return [...items].sort((a, b) =>\n (a.path || a.pattern || \"\").localeCompare(b.path || b.pattern || \"\"),\n );\n}\n\nfunction toRuntime(value: ResolvedFarmRouteRuntimeConfig): FarmDevtoolsRuntime {\n return {\n runtime: value.runtime,\n ...(value.regions ? { regions: [...value.regions] } : {}),\n ...(value.maxDuration ? { maxDuration: value.maxDuration } : {}),\n };\n}\n\nasync function collectRoutes(\n root: string,\n kind: FarmDevtoolsSnapshot[\"routes\"][number][\"kind\"],\n routes: Map<string, RouteMapEntry>,\n routeManager: RouteManagerLike,\n diagnostics: FarmDevtoolsDiagnostic[],\n): Promise<FarmDevtoolsSnapshot[\"routes\"]> {\n return Promise.all(\n Array.from(routes.values()).map(async (route) => {\n let runtime: FarmDevtoolsRuntime | undefined;\n if (kind === \"page\" && routeManager.resolveRouteRuntimeConfig) {\n try {\n runtime = toRuntime(await routeManager.resolveRouteRuntimeConfig(route.pattern));\n } catch (error) {\n diagnostics.push({\n severity: \"warning\",\n code: \"ROUTE_RUNTIME_UNRESOLVED\",\n title: `Could not inspect ${route.pattern}`,\n message: error instanceof Error ? error.message : String(error),\n action: \"Check the route and inherited layout runtime exports.\",\n });\n }\n }\n\n return {\n kind,\n pattern: route.pattern,\n filePath: toProjectPath(root, route.modulePath),\n ...(runtime ? { runtime } : {}),\n };\n }),\n );\n}\n\nfunction collectIntegrations(integrations: FarmConfig[\"integrations\"] | undefined) {\n if (!integrations || typeof integrations !== \"object\") return [];\n\n return Object.entries(integrations)\n .filter((entry): entry is [string, NonNullable<(typeof entry)[1]>] => Boolean(entry[1]))\n .map(([key, value]) => {\n const integration = value as IntegrationLike;\n const routes = (integration.routes || []).map((route) => ({\n path: route.path,\n methods: [...(route.methods || (route.method ? [route.method] : [\"ALL\"]))]\n .map((method) => method.toUpperCase())\n .sort(),\n }));\n\n return {\n key,\n type: integration.type || key,\n category: integration.category || \"custom\",\n serverRuntime: integration.serverRuntime !== false,\n routes: sortByPath(routes),\n middlewareCount: integration.middleware?.length || 0,\n providerCount: integration.providers?.length || 0,\n schemaModelCount: Object.keys(integration.schema?.models || {}).length,\n };\n })\n .sort((a, b) => a.key.localeCompare(b.key));\n}\n\nfunction collectStorage(storage: FarmConfig[\"storage\"] | undefined): {\n entries: FarmDevtoolsSnapshot[\"storage\"];\n configured: boolean;\n} {\n if (!storage || typeof storage !== \"object\") {\n return {\n entries: [{ mount: \"root\", driver: \"memory\", default: true }],\n configured: false,\n };\n }\n\n const value = storage as Record<string, any>;\n if (value.kind === \"farm-storage-client\") {\n return {\n entries: [{ mount: \"root\", driver: \"storage client\", default: false }],\n configured: true,\n };\n }\n\n const configured = Object.keys(value).length > 0;\n const rootDriver = value.client\n ? describeStorageDriver(value.client)\n : describeStorageDriver(value.driver);\n const entries: FarmDevtoolsSnapshot[\"storage\"] = [\n {\n mount: \"root\",\n driver: rootDriver,\n default: !configured,\n },\n ];\n\n if (value.mounts && typeof value.mounts === \"object\") {\n for (const [mount, mountConfig] of Object.entries(value.mounts)) {\n entries.push({\n mount,\n driver: describeStorageDriver(mountConfig),\n default: false,\n });\n }\n }\n\n return {\n entries: entries.sort((a, b) => {\n if (a.mount === \"root\") return -1;\n if (b.mount === \"root\") return 1;\n return a.mount.localeCompare(b.mount);\n }),\n configured,\n };\n}\n\nfunction describeStorageDriver(value: unknown): string {\n if (!value) return \"memory\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"function\") return \"custom\";\n if (typeof value !== \"object\") return \"custom\";\n\n const record = value as Record<string, unknown>;\n if (record.kind === \"farm-storage-client\") return \"storage client\";\n if (typeof record.driver === \"string\") return record.driver;\n if (typeof record.driver === \"function\") return \"custom\";\n return \"custom\";\n}\n\nfunction featureEnabled(value: unknown): boolean {\n if (!value) return false;\n if (typeof value === \"object\" && \"enabled\" in value) {\n return (value as { enabled?: boolean }).enabled !== false;\n }\n return value !== false;\n}\n\nfunction collectEnvironmentKeys(config: FarmConfig | undefined) {\n const env = config?.env as\n | { server?: Record<string, unknown>; public?: Record<string, unknown> }\n | undefined;\n return {\n server: Object.keys(env?.server || {}).sort(),\n public: Object.keys(env?.public || {}).sort(),\n };\n}\n\nfunction resolveHealth(diagnostics: FarmDevtoolsDiagnostic[]): FarmDevtoolsSnapshot[\"health\"] {\n if (diagnostics.some((diagnostic) => diagnostic.severity === \"error\")) return \"error\";\n if (diagnostics.some((diagnostic) => diagnostic.severity === \"warning\")) return \"attention\";\n return \"ready\";\n}\n\nexport async function createFarmDevtoolsSnapshot(\n input: CreateFarmDevtoolsSnapshotInput,\n): Promise<FarmDevtoolsSnapshot> {\n const config = input.config || {};\n const diagnostics: FarmDevtoolsDiagnostic[] = [];\n const pageRoutes = await collectRoutes(\n input.root,\n \"page\",\n input.routeManager.getRoutes(),\n input.routeManager,\n diagnostics,\n );\n const layoutRoutes = await collectRoutes(\n input.root,\n \"layout\",\n input.routeManager.getLayouts(),\n input.routeManager,\n diagnostics,\n );\n const loadingRoutes = await collectRoutes(\n input.root,\n \"loading\",\n input.routeManager.getLoadings(),\n input.routeManager,\n diagnostics,\n );\n const errorRoutes = await collectRoutes(\n input.root,\n \"error\",\n input.routeManager.getErrors(),\n input.routeManager,\n diagnostics,\n );\n const apiRoutes = sortByPath(\n Array.from(input.apiRouteManager.getRoutes().values()).map((route) => {\n const runtime = resolveFarmRouteRuntimeConfig(\n mergeFarmRouteRuntimeConfigs(\n resolveFarmRouteRuleRuntimeConfig(route.path, config.routeRules),\n route,\n ),\n `API route \"${route.path}\"`,\n );\n return {\n path: route.path,\n methods: [...route.methods].sort(),\n filePath: toProjectPath(input.root, route.filePath),\n runtime: toRuntime(runtime),\n };\n }),\n );\n const middleware = sortByPath(\n input.middlewareManager.getMiddlewares().map((entry) => ({\n path: entry.path,\n source: entry.source || \"file\",\n filePath: toProjectPath(input.root, entry.filePath),\n handlerCount: entry.handlers.length,\n })),\n );\n const integrations = collectIntegrations(config.integrations);\n const storage = collectStorage(config.storage);\n const cron = resolveCronConfig(config.cron);\n const workflows = (input.workflows || [])\n .map((workflow) => ({\n id: workflow.id,\n filePath: toProjectPath(input.root, workflow.filePath),\n routePath: workflow.routePath,\n schedule: [...workflow.schedule],\n ...(workflow.timezone ? { timezone: workflow.timezone } : {}),\n }))\n .sort((a, b) => a.id.localeCompare(b.id));\n const layers = (config.layers || []).map((layer) => ({\n name: layer.name,\n source: layer.source,\n srcDir: layer.srcDir,\n }));\n const deploymentPreset = String(config.deploy?.preset || config.preset || \"node-server\");\n const deploymentTarget = String(\n config.deploy?.target || getDeployTargetForPreset(deploymentPreset) || \"node\",\n );\n const env = input.env || process.env;\n\n if (pageRoutes.length === 0) {\n diagnostics.push({\n severity: \"warning\",\n code: \"NO_PAGE_ROUTES\",\n title: \"No page routes found\",\n message: `Farm did not discover a page under ${input.srcDir}/app.`,\n action: `Add ${input.srcDir}/app/page.tsx or a programmatic page route.`,\n });\n }\n if (layoutRoutes.length === 0) {\n diagnostics.push({\n severity: \"warning\",\n code: \"ROOT_LAYOUT_MISSING\",\n title: \"Root layout is missing\",\n message: \"The application has no shared root layout.\",\n action: `Add ${input.srcDir}/app/layout.tsx for shared metadata and application chrome.`,\n });\n }\n\n const apiPaths = new Set(apiRoutes.map((route) => route.path));\n for (const job of cron.jobs) {\n if (!apiPaths.has(job.path)) {\n diagnostics.push({\n severity: \"warning\",\n code: \"CRON_ROUTE_MISSING\",\n title: `Cron route ${job.path} was not found`,\n message: `${job.name} is scheduled, but its GET API route is not registered.`,\n action: \"Add the target API route or update the cron path in farm.config.ts.\",\n });\n }\n }\n if (cron.jobs.length > 0 && !env[cron.secretEnv]) {\n diagnostics.push({\n severity: \"info\",\n code: \"CRON_SECRET_NOT_SET\",\n title: `${cron.secretEnv} is not set`,\n message: \"Local manual runs remain available, but production cron routes fail closed.\",\n action: `Set ${cron.secretEnv} in the deployment environment before production.`,\n });\n }\n if (\n storage.configured &&\n storage.entries[0]?.driver === \"memory\" &&\n [\"vercel\", \"cloudflare\", \"netlify\"].includes(deploymentTarget)\n ) {\n diagnostics.push({\n severity: \"warning\",\n code: \"EPHEMERAL_PRODUCTION_STORAGE\",\n title: \"Production storage is in memory\",\n message: `${deploymentTarget} instances do not preserve in-memory data across executions.`,\n action: \"Configure a durable storage driver or mount for production state.\",\n });\n }\n\n const environment = collectEnvironmentKeys(config);\n const docs = config.docs;\n const docsEnabled = featureEnabled(docs);\n const allRoutes = sortByPath([...pageRoutes, ...layoutRoutes, ...loadingRoutes, ...errorRoutes]);\n\n return {\n generatedAt: (input.now?.() || new Date()).toISOString(),\n health: resolveHealth(diagnostics),\n project: {\n name: path.basename(path.resolve(input.root)),\n root: input.root,\n srcDir: input.srcDir,\n basePath: config.basePath || \"/\",\n deploymentId: config.deploymentId || \"development\",\n },\n deployment: {\n target: deploymentTarget,\n preset: deploymentPreset,\n ...(config.deploy?.outputDir ? { outputDir: config.deploy.outputDir } : {}),\n },\n counts: {\n pages: pageRoutes.length,\n layouts: layoutRoutes.length,\n loadingBoundaries: loadingRoutes.length,\n errorBoundaries: errorRoutes.length,\n apiRoutes: apiRoutes.length,\n middleware: middleware.length,\n integrations: integrations.length,\n storageMounts: storage.entries.length,\n cronJobs: cron.jobs.length,\n workflows: workflows.length,\n layers: layers.length,\n diagnostics: diagnostics.length,\n },\n routes: allRoutes,\n apiRoutes,\n middleware,\n integrations,\n storage: storage.entries,\n cron: cron.jobs,\n workflows,\n layers,\n environment,\n docs: {\n enabled: docsEnabled,\n entry:\n docsEnabled && docs && typeof docs === \"object\" && \"entry\" in docs\n ? String(docs.entry)\n : undefined,\n },\n features: {\n openapi: Boolean(config.openapi?.enabled),\n markdown: featureEnabled(config.md),\n serverComponents: Boolean(config.experimental?.serverComponents),\n serverActions: Boolean(config.experimental?.serverActions),\n optimizedBoundary: Boolean(config.experimental?.optimizedBoundary),\n observability: featureEnabled(config.observability),\n },\n diagnostics,\n };\n}\n","import type { FarmDevtoolsDiagnostic, FarmDevtoolsRuntime, FarmDevtoolsSnapshot } from \"./devtools\";\n\ntype IconName =\n | \"activity\"\n | \"api\"\n | \"app\"\n | \"blocks\"\n | \"book\"\n | \"clock\"\n | \"chevron\"\n | \"close\"\n | \"copy\"\n | \"database\"\n | \"external\"\n | \"layers\"\n | \"overview\"\n | \"refresh\"\n | \"route\"\n | \"runtime\"\n | \"search\"\n | \"shield\"\n | \"terminal\";\n\nconst ICON_PATHS: Record<IconName, string> = {\n activity: '<path d=\"M22 12h-4l-3 9L9 3l-3 9H2\"/>',\n api: '<path d=\"M8 3H7a2 2 0 0 0-2 2v4a2 2 0 0 1-2 2 2 2 0 0 1 2 2v4a2 2 0 0 0 2 2h1\"/><path d=\"M16 3h1a2 2 0 0 1 2 2v4a2 2 0 0 0 2 2 2 2 0 0 0-2 2v4a2 2 0 0 1-2 2h-1\"/>',\n app: '<path d=\"M15 3h6v6\"/><path d=\"M10 14 21 3\"/><path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\"/>',\n blocks:\n '<rect width=\"7\" height=\"7\" x=\"3\" y=\"3\"/><rect width=\"7\" height=\"7\" x=\"14\" y=\"3\"/><rect width=\"7\" height=\"7\" x=\"14\" y=\"14\"/><rect width=\"7\" height=\"7\" x=\"3\" y=\"14\"/>',\n book: '<path d=\"M4 19.5A2.5 2.5 0 0 1 6.5 17H20\"/><path d=\"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z\"/>',\n clock: '<circle cx=\"12\" cy=\"12\" r=\"9\"/><path d=\"M12 7v5l3 2\"/>',\n chevron: '<path d=\"m9 18 6-6-6-6\"/>',\n close: '<path d=\"M18 6 6 18M6 6l12 12\"/>',\n copy: '<rect width=\"14\" height=\"14\" x=\"8\" y=\"8\"/><path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"/>',\n database:\n '<ellipse cx=\"12\" cy=\"5\" rx=\"9\" ry=\"3\"/><path d=\"M3 5v14c0 1.7 4 3 9 3s9-1.3 9-3V5\"/><path d=\"M3 12c0 1.7 4 3 9 3s9-1.3 9-3\"/>',\n external:\n '<path d=\"M15 3h6v6\"/><path d=\"M10 14 21 3\"/><path d=\"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6\"/>',\n layers:\n '<path d=\"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z\"/><path d=\"m22 12.5-9.17 4.17a2 2 0 0 1-1.66 0L2 12.5\"/><path d=\"m22 17.5-9.17 4.17a2 2 0 0 1-1.66 0L2 17.5\"/>',\n overview:\n '<rect width=\"7\" height=\"9\" x=\"3\" y=\"3\"/><rect width=\"7\" height=\"5\" x=\"14\" y=\"3\"/><rect width=\"7\" height=\"9\" x=\"14\" y=\"12\"/><rect width=\"7\" height=\"5\" x=\"3\" y=\"16\"/>',\n refresh:\n '<path d=\"M20 11a8.1 8.1 0 0 0-15.5-2M4 4v5h5\"/><path d=\"M4 13a8.1 8.1 0 0 0 15.5 2M20 20v-5h-5\"/>',\n route:\n '<circle cx=\"6\" cy=\"19\" r=\"3\"/><path d=\"M9 19h5.5a3.5 3.5 0 0 0 0-7h-5a3.5 3.5 0 0 1 0-7H18\"/><circle cx=\"18\" cy=\"5\" r=\"3\"/>',\n runtime:\n '<rect width=\"20\" height=\"14\" x=\"2\" y=\"3\"/><line x1=\"8\" x2=\"16\" y1=\"21\" y2=\"21\"/><line x1=\"12\" x2=\"12\" y1=\"17\" y2=\"21\"/>',\n search: '<circle cx=\"11\" cy=\"11\" r=\"8\"/><path d=\"m21 21-4.3-4.3\"/>',\n shield: '<path d=\"M20 13c0 5-3.5 7.5-8 9-4.5-1.5-8-4-8-9V5l8-3 8 3z\"/><path d=\"m9 12 2 2 4-4\"/>',\n terminal: '<polyline points=\"4 17 10 11 4 5\"/><line x1=\"12\" x2=\"20\" y1=\"19\" y2=\"19\"/>',\n};\n\nfunction icon(name: IconName, className = \"\"): string {\n return `<svg class=\"icon ${className}\" data-lucide=\"${name}\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">${ICON_PATHS[name]}</svg>`;\n}\n\nfunction escapeHtml(value: unknown): string {\n return String(value ?? \"\")\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\nfunction escapeAttribute(value: unknown): string {\n return escapeHtml(value).replace(/`/g, \"&#96;\");\n}\n\nfunction renderBadge(value: string, tone = \"neutral\"): string {\n return `<span class=\"badge badge-${tone}\">${escapeHtml(value)}</span>`;\n}\n\nfunction renderRuntime(runtime: FarmDevtoolsRuntime | undefined): string {\n if (!runtime) return '<span class=\"muted\">Inherited</span>';\n const details = [\n runtime.regions?.length ? runtime.regions.join(\", \") : null,\n runtime.maxDuration ? `${runtime.maxDuration}s` : null,\n ].filter(Boolean);\n return `<span class=\"runtime-value\">${renderBadge(runtime.runtime, runtime.runtime)}${\n details.length ? `<small>${escapeHtml(details.join(\" / \"))}</small>` : \"\"\n }</span>`;\n}\n\nfunction renderEmpty(title: string, detail: string): string {\n return `<div class=\"empty-state\">\n ${icon(\"activity\")}\n <strong>${escapeHtml(title)}</strong>\n <span>${escapeHtml(detail)}</span>\n </div>`;\n}\n\nfunction renderFilter(id: string, placeholder: string): string {\n return `<label class=\"filter-control\">\n ${icon(\"search\")}\n <span class=\"sr-only\">${escapeHtml(placeholder)}</span>\n <input type=\"search\" placeholder=\"${escapeAttribute(placeholder)}\" data-filter=\"${escapeAttribute(id)}\" autocomplete=\"off\">\n <kbd>/</kbd>\n </label>`;\n}\n\nfunction renderDiagnostics(diagnostics: FarmDevtoolsDiagnostic[]): string {\n if (diagnostics.length === 0) {\n return `<div class=\"diagnostic diagnostic-ready\">\n <span class=\"diagnostic-mark\">${icon(\"shield\")}</span>\n <div><strong>Framework checks passed</strong><p>Routes and configured systems are internally consistent.</p></div>\n ${renderBadge(\"ready\", \"ready\")}\n </div>`;\n }\n\n return diagnostics\n .map(\n (diagnostic) => `<article class=\"diagnostic diagnostic-${diagnostic.severity}\">\n <span class=\"diagnostic-mark\">${icon(\n diagnostic.severity === \"error\" ? \"activity\" : \"shield\",\n )}</span>\n <div>\n <span class=\"diagnostic-code\">${escapeHtml(diagnostic.code)}</span>\n <strong>${escapeHtml(diagnostic.title)}</strong>\n <p>${escapeHtml(diagnostic.message)}</p>\n ${diagnostic.action ? `<small>${escapeHtml(diagnostic.action)}</small>` : \"\"}\n </div>\n ${renderBadge(diagnostic.severity, diagnostic.severity)}\n </article>`,\n )\n .join(\"\");\n}\n\nfunction renderSystemRows(snapshot: FarmDevtoolsSnapshot): string {\n const rows = [\n [\"Integrations\", snapshot.counts.integrations, \"Configured product adapters\", \"blocks\"],\n [\"Storage\", snapshot.counts.storageMounts, \"Root driver and named mounts\", \"database\"],\n [\"Cron\", snapshot.counts.cronJobs, \"Portable scheduled API routes\", \"clock\"],\n [\"Workflows\", snapshot.counts.workflows, \"Discovered workflow modules\", \"activity\"],\n [\"Docs\", snapshot.docs.enabled ? \"On\" : \"Off\", snapshot.docs.entry || \"No docs route\", \"book\"],\n ] as const;\n\n return rows\n .map(\n ([label, value, detail, rowIcon]) => `<div class=\"system-row\">\n <span class=\"system-icon\">${icon(rowIcon)}</span>\n <div><strong>${escapeHtml(label)}</strong><small>${escapeHtml(detail)}</small></div>\n <span class=\"system-value\">${escapeHtml(value)}</span>\n </div>`,\n )\n .join(\"\");\n}\n\nfunction renderIntegrations(snapshot: FarmDevtoolsSnapshot): string {\n if (snapshot.integrations.length === 0) {\n return renderEmpty(\n \"No integrations configured\",\n \"Register product systems through farm.config.ts when the app needs them.\",\n );\n }\n\n return `<div class=\"table-scroll\"><table>\n <thead><tr><th>Registry key</th><th>Adapter</th><th>Routes</th><th>Runtime surface</th></tr></thead>\n <tbody>${snapshot.integrations\n .map(\n (integration) => `<tr>\n <td><code>${escapeHtml(integration.key)}</code><small class=\"cell-detail\">${escapeHtml(\n integration.category,\n )}</small></td>\n <td>${escapeHtml(integration.type)}</td>\n <td>${\n integration.routes.length\n ? integration.routes\n .map(\n (route) =>\n `<span class=\"route-operation\"><code>${escapeHtml(\n route.path,\n )}</code><small>${escapeHtml(route.methods.join(\", \"))}</small></span>`,\n )\n .join(\"\")\n : '<span class=\"muted\">No HTTP routes</span>'\n }</td>\n <td><span class=\"runtime-facts\">${renderBadge(\n integration.serverRuntime ? \"server\" : \"platform\",\n )}<span>${integration.middlewareCount} middleware</span><span>${\n integration.providerCount\n } providers</span><span>${integration.schemaModelCount} models</span></span></td>\n </tr>`,\n )\n .join(\"\")}</tbody>\n </table></div>`;\n}\n\nfunction renderMiddleware(snapshot: FarmDevtoolsSnapshot): string {\n if (snapshot.middleware.length === 0) {\n return renderEmpty(\"No middleware configured\", \"Requests currently enter routes directly.\");\n }\n return `<div class=\"table-scroll\"><table>\n <thead><tr><th>Path</th><th>Source</th><th>Handlers</th><th>File</th></tr></thead>\n <tbody>${snapshot.middleware\n .map(\n (entry) =>\n `<tr><td><code>${escapeHtml(entry.path)}</code></td><td>${renderBadge(\n entry.source,\n )}</td><td>${entry.handlerCount}</td><td class=\"file-cell\">${escapeHtml(\n entry.filePath,\n )}</td></tr>`,\n )\n .join(\"\")}</tbody>\n </table></div>`;\n}\n\nfunction renderStorage(snapshot: FarmDevtoolsSnapshot): string {\n return `<div class=\"table-scroll\"><table>\n <thead><tr><th>Mount</th><th>Driver</th><th>State</th></tr></thead>\n <tbody>${snapshot.storage\n .map(\n (entry) =>\n `<tr><td><code>${escapeHtml(entry.mount)}</code></td><td>${escapeHtml(\n entry.driver,\n )}</td><td>${renderBadge(entry.default ? \"default\" : \"configured\")}</td></tr>`,\n )\n .join(\"\")}</tbody>\n </table></div>`;\n}\n\nfunction renderCron(snapshot: FarmDevtoolsSnapshot): string {\n if (snapshot.cron.length === 0) {\n return renderEmpty(\n \"No cron routes configured\",\n \"Add named schedules under cron in farm.config.ts.\",\n );\n }\n return `<div class=\"table-scroll\"><table>\n <thead><tr><th>Name</th><th>Schedule (UTC)</th><th>Target</th></tr></thead>\n <tbody>${snapshot.cron\n .map(\n (job) =>\n `<tr><td><code>${escapeHtml(job.name)}</code></td><td>${job.schedule\n .map((schedule) => `<code class=\"schedule\">${escapeHtml(schedule)}</code>`)\n .join(\"\")}</td><td><code>${escapeHtml(job.path)}</code></td></tr>`,\n )\n .join(\"\")}</tbody>\n </table></div>`;\n}\n\nfunction renderWorkflows(snapshot: FarmDevtoolsSnapshot): string {\n if (snapshot.workflows.length === 0) {\n return renderEmpty(\n \"No workflows discovered\",\n \"Workflow directories are enabled but currently empty.\",\n );\n }\n return `<div class=\"table-scroll\"><table>\n <thead><tr><th>Workflow</th><th>Schedule</th><th>Endpoint</th><th>Source</th></tr></thead>\n <tbody>${snapshot.workflows\n .map(\n (workflow) =>\n `<tr><td><code>${escapeHtml(workflow.id)}</code></td><td>${\n workflow.schedule.length\n ? workflow.schedule.map((schedule) => `<code>${escapeHtml(schedule)}</code>`).join(\"\")\n : '<span class=\"muted\">Manual</span>'\n }</td><td><code>${escapeHtml(workflow.routePath)}</code></td><td class=\"file-cell\">${escapeHtml(\n workflow.filePath,\n )}</td></tr>`,\n )\n .join(\"\")}</tbody>\n </table></div>`;\n}\n\nfunction renderFeatureMatrix(snapshot: FarmDevtoolsSnapshot): string {\n const features = [\n [\"OpenAPI\", snapshot.features.openapi],\n [\"Markdown\", snapshot.features.markdown],\n [\"Server components\", snapshot.features.serverComponents],\n [\"Server actions\", snapshot.features.serverActions],\n [\"Optimized boundary\", snapshot.features.optimizedBoundary],\n [\"Observability\", snapshot.features.observability],\n ] as const;\n return `<div class=\"feature-matrix\">${features\n .map(\n ([label, enabled]) =>\n `<div><span>${escapeHtml(label)}</span>${renderBadge(\n enabled ? \"enabled\" : \"disabled\",\n enabled ? \"ready\" : \"neutral\",\n )}</div>`,\n )\n .join(\"\")}</div>`;\n}\n\nfunction renderEnvironment(snapshot: FarmDevtoolsSnapshot): string {\n const renderKeys = (keys: string[]) =>\n keys.length\n ? `<div class=\"key-list\">${keys.map((key) => `<code>${escapeHtml(key)}</code>`).join(\"\")}</div>`\n : '<span class=\"muted\">No validated keys</span>';\n return `<div class=\"environment-grid\">\n <div><span class=\"mini-label\">Server keys</span>${renderKeys(snapshot.environment.server)}</div>\n <div><span class=\"mini-label\">Public keys</span>${renderKeys(snapshot.environment.public)}</div>\n </div>`;\n}\n\nfunction renderLayers(snapshot: FarmDevtoolsSnapshot): string {\n if (snapshot.layers.length === 0) {\n return renderEmpty(\n \"No layers extended\",\n \"This project owns its complete route and config surface.\",\n );\n }\n return `<div class=\"layer-list\">${snapshot.layers\n .map(\n (layer) =>\n `<div><span>${icon(\"layers\")}<strong>${escapeHtml(\n layer.name,\n )}</strong></span><code>${escapeHtml(layer.source)}</code><small>${escapeHtml(\n layer.srcDir,\n )}</small></div>`,\n )\n .join(\"\")}</div>`;\n}\n\ntype InspectorEntry = {\n id: string;\n label: string;\n description: string;\n icon: IconName;\n value?: string | number;\n searchValue?: string;\n detailMeta?: string;\n content: string;\n};\n\nfunction renderPropertyList(entries: Array<[label: string, value: string]>): string {\n return `<dl class=\"property-list\">${entries\n .map(([label, value]) => `<div><dt>${escapeHtml(label)}</dt><dd>${value}</dd></div>`)\n .join(\"\")}</dl>`;\n}\n\nfunction renderDetailIntro(\n label: string,\n title: string,\n description: string,\n detailIcon: IconName,\n): string {\n return `<div class=\"detail-intro\">\n <span class=\"detail-icon\">${icon(detailIcon)}</span>\n <div><span class=\"mini-label\">${escapeHtml(label)}</span><h2>${escapeHtml(\n title,\n )}</h2><p>${escapeHtml(description)}</p></div>\n </div>`;\n}\n\nfunction renderInspector(\n scope: string,\n title: string,\n entries: InspectorEntry[],\n filterPlaceholder?: string,\n): string {\n if (entries.length === 0) {\n return `<div class=\"single-pane\">\n <header class=\"pane-header\"><strong>${escapeHtml(title)}</strong><span>0 items</span></header>\n ${renderEmpty(`No ${title.toLowerCase()} found`, \"Farm has no runtime data for this surface yet.\")}\n </div>`;\n }\n\n return `<div class=\"split-view\" data-inspector=\"${escapeAttribute(scope)}\">\n <section class=\"pane pane-list\">\n <header class=\"pane-header\"><strong>${escapeHtml(title)}</strong><span>${entries.length} ${\n entries.length === 1 ? \"item\" : \"items\"\n }</span></header>\n ${\n filterPlaceholder\n ? `<div class=\"pane-tools\">${renderFilter(scope, filterPlaceholder)}</div>`\n : \"\"\n }\n <div class=\"pane-scroll inspector-list\" data-filter-rows=\"${escapeAttribute(scope)}\">\n ${entries\n .map(\n (\n entry,\n index,\n ) => `<button type=\"button\" class=\"inspector-row\" data-detail-trigger=\"${escapeAttribute(\n scope,\n )}\" data-detail-id=\"${escapeAttribute(entry.id)}\" data-search-value=\"${escapeAttribute(\n entry.searchValue || `${entry.label} ${entry.description}`,\n )}\" aria-selected=\"${index === 0 ? \"true\" : \"false\"}\">\n <span class=\"inspector-row-copy\"><strong>${escapeHtml(\n entry.label,\n )}</strong><small>${escapeHtml(entry.description)}</small></span>\n ${entry.value === undefined ? \"\" : `<span class=\"inspector-row-value\">${escapeHtml(entry.value)}</span>`}\n </button>`,\n )\n .join(\"\")}\n <div class=\"filtered-empty\" data-filter-empty=\"${escapeAttribute(\n scope,\n )}\" hidden>No items match this filter.</div>\n </div>\n </section>\n <section class=\"pane pane-detail\">\n ${entries\n .map(\n (entry, index) => `<article class=\"detail-panel\" data-detail-panel=\"${escapeAttribute(\n scope,\n )}\" data-detail-id=\"${escapeAttribute(entry.id)}\"${index === 0 ? \"\" : \" hidden\"}>\n <header class=\"pane-header\"><strong>${escapeHtml(entry.label)}</strong><span>${escapeHtml(\n entry.detailMeta || entry.description,\n )}</span></header>\n <div class=\"detail-scroll\">${entry.content}</div>\n </article>`,\n )\n .join(\"\")}\n </section>\n </div>`;\n}\n\nfunction renderJson(value: unknown): string {\n return `<pre class=\"json-viewer\"><code>${escapeHtml(JSON.stringify(value, null, 2))}</code></pre>`;\n}\n\nfunction renderOverviewInspector(\n snapshot: FarmDevtoolsSnapshot,\n healthLabel: string,\n generatedTime: string,\n): string {\n const scheduledCount = snapshot.counts.cronJobs + snapshot.counts.workflows;\n return renderInspector(\"overview\", \"Project\", [\n {\n id: \"diagnostics\",\n label: \"Diagnostics\",\n description: \"Actionable framework checks\",\n icon: \"shield\",\n value: snapshot.counts.diagnostics,\n detailMeta: healthLabel,\n content: `${renderDetailIntro(\n \"Project health\",\n healthLabel,\n snapshot.diagnostics.length\n ? \"Farm found configuration details that deserve attention before production.\"\n : \"Routes and configured systems are internally consistent.\",\n \"shield\",\n )}<div class=\"detail-section\">${renderDiagnostics(snapshot.diagnostics)}</div>`,\n },\n {\n id: \"project\",\n label: snapshot.project.name,\n description: snapshot.project.root,\n icon: \"app\",\n value: snapshot.project.srcDir,\n detailMeta: \"Active project\",\n content: `${renderDetailIntro(\n \"Active project\",\n snapshot.project.name,\n \"The application currently resolved by the Farm development server.\",\n \"app\",\n )}${renderPropertyList([\n [\"Root\", `<code>${escapeHtml(snapshot.project.root)}</code>`],\n [\"Source directory\", `<code>${escapeHtml(snapshot.project.srcDir)}</code>`],\n [\"Base path\", `<code>${escapeHtml(snapshot.project.basePath)}</code>`],\n [\"Deployment ID\", `<code>${escapeHtml(snapshot.project.deploymentId)}</code>`],\n [\"Snapshot\", `<span class=\"mono\">${escapeHtml(generatedTime)}</span>`],\n ])}`,\n },\n {\n id: \"routes\",\n label: \"Route surface\",\n description: \"Pages, boundaries, and typed endpoints\",\n icon: \"route\",\n value: snapshot.counts.pages + snapshot.counts.apiRoutes,\n detailMeta: `${snapshot.counts.pages} pages / ${snapshot.counts.apiRoutes} API`,\n content: `${renderDetailIntro(\n \"Application routing\",\n `${snapshot.counts.pages + snapshot.counts.apiRoutes} registered routes`,\n \"Farm resolves page boundaries and server endpoints from the same application tree.\",\n \"route\",\n )}${renderPropertyList([\n [\"Pages\", `<strong>${snapshot.counts.pages}</strong>`],\n [\"Layouts\", `<strong>${snapshot.counts.layouts}</strong>`],\n [\"Loading boundaries\", `<strong>${snapshot.counts.loadingBoundaries}</strong>`],\n [\"Error boundaries\", `<strong>${snapshot.counts.errorBoundaries}</strong>`],\n [\"API routes\", `<strong>${snapshot.counts.apiRoutes}</strong>`],\n ])}`,\n },\n {\n id: \"systems\",\n label: \"Connected systems\",\n description: \"Integrations, storage, and request layers\",\n icon: \"blocks\",\n value: snapshot.counts.integrations,\n detailMeta: \"Configured surfaces\",\n content: `${renderDetailIntro(\n \"System map\",\n \"Application services\",\n \"Product integrations and framework services visible to the running application.\",\n \"blocks\",\n )}<div class=\"detail-section\">${renderSystemRows(snapshot)}</div>`,\n },\n {\n id: \"deployment\",\n label: \"Runtime\",\n description: `${snapshot.deployment.target} / ${snapshot.deployment.preset}`,\n icon: \"runtime\",\n value: scheduledCount,\n detailMeta: \"Deployment controls\",\n content: `${renderDetailIntro(\n \"Deployment runtime\",\n snapshot.deployment.target,\n \"The resolved deployment adapter, output contract, and enabled framework surfaces.\",\n \"runtime\",\n )}${renderPropertyList([\n [\"Target\", `<code>${escapeHtml(snapshot.deployment.target)}</code>`],\n [\"Nitro preset\", `<code>${escapeHtml(snapshot.deployment.preset)}</code>`],\n [\n \"Output\",\n `<code>${escapeHtml(snapshot.deployment.outputDir || \"Framework default\")}</code>`,\n ],\n [\"Scheduled work\", `<strong>${scheduledCount}</strong>`],\n ])}<div class=\"detail-section\">${renderFeatureMatrix(snapshot)}</div>`,\n },\n ]);\n}\n\nfunction renderRoutesInspector(snapshot: FarmDevtoolsSnapshot): string {\n return renderInspector(\n \"routes\",\n \"Routes\",\n snapshot.routes.map((route, index) => ({\n id: `route-${index}`,\n label: route.pattern,\n description: route.filePath,\n icon: \"route\",\n value: route.kind,\n searchValue: `${route.kind} ${route.pattern} ${route.filePath} ${\n route.runtime?.runtime || \"inherited\"\n }`,\n detailMeta: route.kind,\n content: `${renderDetailIntro(\n `${route.kind} route`,\n route.pattern,\n route.filePath,\n \"route\",\n )}${renderPropertyList([\n [\"Kind\", renderBadge(route.kind, route.kind)],\n [\"Pattern\", `<code>${escapeHtml(route.pattern)}</code>`],\n [\"Runtime\", renderRuntime(route.runtime)],\n [\"Source\", `<code>${escapeHtml(route.filePath)}</code>`],\n ])}`,\n })),\n \"Filter routes or files\",\n );\n}\n\nfunction renderApiInspector(snapshot: FarmDevtoolsSnapshot): string {\n return renderInspector(\n \"api\",\n \"API routes\",\n snapshot.apiRoutes.map((route, index) => ({\n id: `api-${index}`,\n label: route.path,\n description: route.filePath,\n icon: \"api\",\n value: route.methods.length,\n searchValue: `${route.path} ${route.methods.join(\" \")} ${route.filePath} ${\n route.runtime.runtime\n }`,\n detailMeta: route.methods.join(\" / \"),\n content: `${renderDetailIntro(\n \"Server endpoint\",\n route.path,\n route.filePath,\n \"api\",\n )}${renderPropertyList([\n [\n \"Methods\",\n `<span class=\"method-list\">${route.methods\n .map((method) => renderBadge(method, \"method\"))\n .join(\"\")}</span>`,\n ],\n [\"Runtime\", renderRuntime(route.runtime)],\n [\"Source\", `<code>${escapeHtml(route.filePath)}</code>`],\n ])}`,\n })),\n \"Filter endpoints or methods\",\n );\n}\n\nfunction renderSystemsInspector(snapshot: FarmDevtoolsSnapshot): string {\n return renderInspector(\"systems\", \"Systems\", [\n {\n id: \"integrations\",\n label: \"Integrations\",\n description: \"Configured product adapters\",\n icon: \"blocks\",\n value: snapshot.integrations.length,\n content: renderIntegrations(snapshot),\n },\n {\n id: \"middleware\",\n label: \"Middleware\",\n description: \"Request layers and source modules\",\n icon: \"shield\",\n value: snapshot.middleware.length,\n content: renderMiddleware(snapshot),\n },\n {\n id: \"storage\",\n label: \"Storage mounts\",\n description: \"Root driver and named namespaces\",\n icon: \"database\",\n value: snapshot.storage.length,\n content: renderStorage(snapshot),\n },\n {\n id: \"docs\",\n label: \"Documentation\",\n description: snapshot.docs.entry || \"No docs route\",\n icon: \"book\",\n value: snapshot.docs.enabled ? \"on\" : \"off\",\n content: `${renderDetailIntro(\n \"Documentation\",\n snapshot.docs.enabled ? \"Docs enabled\" : \"Docs disabled\",\n \"Farm can serve application documentation from the same development runtime.\",\n \"book\",\n )}${renderPropertyList([\n [\"State\", renderBadge(snapshot.docs.enabled ? \"enabled\" : \"disabled\")],\n [\"Entry\", `<code>${escapeHtml(snapshot.docs.entry || \"Not configured\")}</code>`],\n ])}`,\n },\n ]);\n}\n\nfunction renderRuntimeInspector(snapshot: FarmDevtoolsSnapshot): string {\n return renderInspector(\"runtime\", \"Runtime\", [\n {\n id: \"deployment\",\n label: \"Deployment\",\n description: `${snapshot.deployment.target} / ${snapshot.deployment.preset}`,\n icon: \"runtime\",\n content: `${renderDetailIntro(\n \"Deployment target\",\n snapshot.deployment.target,\n \"Resolved platform adapter and build output for this application.\",\n \"runtime\",\n )}${renderPropertyList([\n [\"Target\", `<code>${escapeHtml(snapshot.deployment.target)}</code>`],\n [\"Nitro preset\", `<code>${escapeHtml(snapshot.deployment.preset)}</code>`],\n [\n \"Output directory\",\n `<code>${escapeHtml(snapshot.deployment.outputDir || \"Framework default\")}</code>`,\n ],\n ])}`,\n },\n {\n id: \"cron\",\n label: \"Cron routes\",\n description: \"Portable scheduled API routes\",\n icon: \"clock\",\n value: snapshot.cron.length,\n content: renderCron(snapshot),\n },\n {\n id: \"workflows\",\n label: \"Workflows\",\n description: \"Discovered workflow modules\",\n icon: \"activity\",\n value: snapshot.workflows.length,\n content: renderWorkflows(snapshot),\n },\n {\n id: \"features\",\n label: \"Framework features\",\n description: \"Resolved configuration switches\",\n icon: \"blocks\",\n content: renderFeatureMatrix(snapshot),\n },\n {\n id: \"environment\",\n label: \"Environment\",\n description: \"Validated key names only\",\n icon: \"shield\",\n value: snapshot.environment.server.length + snapshot.environment.public.length,\n content: renderEnvironment(snapshot),\n },\n {\n id: \"layers\",\n label: \"Layers\",\n description: \"Extended source roots\",\n icon: \"layers\",\n value: snapshot.layers.length,\n content: renderLayers(snapshot),\n },\n ]);\n}\n\nfunction renderRawInspector(snapshot: FarmDevtoolsSnapshot): string {\n return renderInspector(\"raw\", \"Raw snapshot\", [\n {\n id: \"snapshot\",\n label: \"Snapshot\",\n description: \"Complete serialized runtime state\",\n icon: \"terminal\",\n content: renderJson(snapshot),\n },\n {\n id: \"routes\",\n label: \"Routes\",\n description: \"Pages and route boundaries\",\n icon: \"route\",\n value: snapshot.routes.length,\n content: renderJson(snapshot.routes),\n },\n {\n id: \"api\",\n label: \"API\",\n description: \"Typed server endpoints\",\n icon: \"api\",\n value: snapshot.apiRoutes.length,\n content: renderJson(snapshot.apiRoutes),\n },\n {\n id: \"systems\",\n label: \"Systems\",\n description: \"Integrations, middleware, and storage\",\n icon: \"blocks\",\n content: renderJson({\n integrations: snapshot.integrations,\n middleware: snapshot.middleware,\n storage: snapshot.storage,\n }),\n },\n {\n id: \"diagnostics\",\n label: \"Diagnostics\",\n description: \"Framework health findings\",\n icon: \"shield\",\n value: snapshot.diagnostics.length,\n content: renderJson(snapshot.diagnostics),\n },\n ]);\n}\n\nfunction renderNavigationItem(view: string, label: string): string {\n return `<button type=\"button\" class=\"nav-item\" data-view-trigger=\"${view}\" aria-selected=\"false\">\n <span>${escapeHtml(label)}</span>\n </button>`;\n}\n\nexport function renderFarmDevtoolsHtml(snapshot: FarmDevtoolsSnapshot): string {\n const healthLabel =\n snapshot.health === \"ready\" ? \"Ready\" : snapshot.health === \"error\" ? \"Error\" : \"Attention\";\n const generatedTime = new Date(snapshot.generatedAt).toLocaleTimeString(\"en-US\", {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n\n return `<!doctype html>\n<html lang=\"en\" class=\"devtools-frame\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <meta name=\"color-scheme\" content=\"dark\">\n <title>Farm Devtools - ${escapeHtml(snapshot.project.name)}</title>\n <style>\n :root {\n color-scheme: dark;\n --background: #000;\n --surface: #050505;\n --surface-raised: #090909;\n --foreground: #f5f5f5;\n --muted: #858585;\n --muted-strong: #a8a8a8;\n --line: rgb(255 255 255 / 0.12);\n --line-soft: rgb(255 255 255 / 0.065);\n --line-strong: rgb(255 255 255 / 0.22);\n --font-sans: \"Geist Sans\", Geist, Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n --font-mono: \"Geist Mono\", \"SFMono-Regular\", Consolas, \"Liberation Mono\", Menlo, monospace;\n }\n * { box-sizing: border-box; }\n html { min-width: 320px; min-height: 100%; background: var(--background); }\n body { min-height: 100vh; min-height: 100dvh; margin: 0; overflow: hidden; background: #030303; color: var(--foreground); font-family: var(--font-sans); font-size: 14px; letter-spacing: 0; text-rendering: optimizeLegibility; }\n button, input { color: inherit; font: inherit; letter-spacing: 0; }\n button, a { -webkit-tap-highlight-color: transparent; }\n button { cursor: pointer; }\n a { color: inherit; }\n [hidden] { display: none !important; }\n code, kbd, .badge, .mono, .mini-label, .metric-label, .metric-detail, .section-index, .diagnostic-code, th, .statusbar, .eyebrow { font-family: var(--font-mono); letter-spacing: 0; }\n .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }\n .icon { width: 16px; height: 16px; flex: 0 0 auto; }\n .stage { display: grid; min-height: 100vh; min-height: 100dvh; place-items: center; padding: 20px; }\n .shell { display: flex; width: min(1280px, 100%); height: min(780px, calc(100dvh - 40px)); min-height: 560px; min-width: 0; flex-direction: column; overflow: hidden; border: 1px solid var(--line-strong); background: var(--background); box-shadow: 0 24px 80px rgb(0 0 0 / 0.72); }\n .topbar { z-index: 30; display: flex; min-height: 42px; flex: 0 0 auto; align-items: stretch; border-bottom: 1px solid var(--line); background: var(--background); }\n .brand { display: flex; min-width: 170px; align-items: center; gap: 8px; padding: 0 12px; border-right: 1px solid var(--line); text-decoration: none; font-family: var(--font-mono); font-size: 10px; text-transform: uppercase; white-space: nowrap; }\n .brand-mark { display: grid; width: 18px; height: 18px; place-items: center; border: 1px solid var(--line-strong); color: #fff; font-family: var(--font-sans); font-size: 9px; font-weight: 650; }\n .brand-slash { color: #555; }\n .brand-product { color: var(--muted-strong); }\n .tabbar { display: flex; min-width: 0; flex: 1 1 auto; align-items: stretch; overflow-x: auto; scrollbar-width: none; }\n .tabbar::-webkit-scrollbar { display: none; }\n .nav-item { position: relative; display: flex; min-width: max-content; min-height: 41px; align-items: center; gap: 7px; padding: 0 11px; border: 0; background: transparent; color: var(--muted); font-family: var(--font-mono); font-size: 10px; text-transform: uppercase; transition: background-color 140ms ease-out, color 140ms ease-out; }\n .nav-item::after { position: absolute; right: 10px; bottom: -1px; left: 10px; height: 1px; background: transparent; content: \"\"; }\n .nav-item:hover, .nav-item:focus-visible { background: rgb(255 255 255 / 0.035); color: var(--foreground); outline: none; }\n .nav-item[aria-selected=\"true\"] { color: #fff; }\n .nav-item[aria-selected=\"true\"]::after { background: #fff; }\n .nav-item .icon { width: 13px; height: 13px; }\n .nav-item small { color: #666; font-size: 9px; font-weight: 400; }\n .topbar-meta { display: flex; flex: 0 0 auto; margin-left: auto; border-left: 1px solid var(--line); }\n .topbar-status { display: flex; min-width: max-content; align-items: center; gap: 7px; padding: 0 11px; color: var(--muted-strong); font-family: var(--font-mono); font-size: 9px; text-transform: uppercase; }\n .status-dot { width: 5px; height: 5px; background: #fff; box-shadow: 0 0 0 3px rgb(255 255 255 / 0.06); }\n .status-dot-attention { background: #909090; animation: status-pulse 1.8s ease-in-out infinite; }\n .status-dot-error { background: transparent; border: 1px solid #fff; }\n .topbar-actions { display: flex; }\n .action { display: inline-flex; width: 40px; min-height: 41px; align-items: center; justify-content: center; padding: 0; border: 0; border-left: 1px solid var(--line); background: transparent; color: var(--muted-strong); text-decoration: none; transition: background-color 140ms ease-out, color 140ms ease-out; }\n .action:hover, .action:focus-visible { background: #fff; color: #000; outline: none; }\n .action[data-copied=\"true\"] { background: #fff; color: #000; }\n .workspace { min-height: 0; flex: 1 1 auto; }\n .eyebrow { display: block; color: var(--muted); font-size: 9px; font-weight: 400; text-transform: uppercase; }\n .content { height: 100%; min-width: 0; }\n .view { height: 100%; min-width: 0; overflow: hidden; }\n .split-view { display: grid; height: 100%; min-height: 0; grid-template-columns: clamp(230px, 28%, 300px) minmax(0, 1fr); }\n .pane { min-width: 0; min-height: 0; overflow: hidden; background: var(--background); }\n .pane-list { display: flex; flex-direction: column; border-right: 1px solid var(--line); }\n .pane-detail { position: relative; }\n .pane-header { display: flex; min-height: 38px; align-items: center; justify-content: space-between; gap: 12px; padding: 0 12px; border-bottom: 1px solid var(--line); background: var(--surface); }\n .pane-header strong { overflow: hidden; font-size: 11px; font-weight: 520; text-overflow: ellipsis; white-space: nowrap; }\n .pane-header span { overflow: hidden; color: var(--muted); font-family: var(--font-mono); font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }\n .pane-tools { border-bottom: 1px solid var(--line); }\n .pane-tools .filter-control { width: 100%; min-height: 36px; border: 0; }\n .pane-scroll, .detail-scroll { min-height: 0; overflow: auto; overscroll-behavior: contain; }\n .pane-scroll { flex: 1 1 auto; }\n .inspector-list { scrollbar-width: thin; scrollbar-color: var(--line-strong) transparent; }\n .inspector-row { position: relative; display: grid; width: 100%; min-height: 54px; grid-template-columns: 24px minmax(0, 1fr) auto; align-items: center; gap: 9px; padding: 8px 11px; border: 0; border-bottom: 1px solid var(--line-soft); background: transparent; color: var(--muted); text-align: left; transition: background-color 120ms ease-out, color 120ms ease-out; }\n .inspector-row::before { position: absolute; inset: 0 auto 0 0; width: 1px; background: transparent; content: \"\"; }\n .inspector-row:hover, .inspector-row:focus-visible { background: rgb(255 255 255 / 0.035); color: var(--foreground); outline: none; }\n .inspector-row[aria-selected=\"true\"] { background: rgb(255 255 255 / 0.075); color: #fff; }\n .inspector-row[aria-selected=\"true\"]::before { background: #fff; }\n .inspector-row-icon { display: grid; color: var(--muted-strong); place-items: center; }\n .inspector-row-icon .icon { width: 14px; height: 14px; }\n .inspector-row-copy { min-width: 0; }\n .inspector-row-copy strong, .inspector-row-copy small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n .inspector-row-copy strong { color: inherit; font-size: 11px; font-weight: 520; }\n .inspector-row-copy small { margin-top: 3px; color: var(--muted); font-family: var(--font-mono); font-size: 9px; }\n .inspector-row-value { color: var(--muted-strong); font-family: var(--font-mono); font-size: 9px; text-transform: uppercase; }\n .detail-panel { display: flex; height: 100%; min-height: 0; flex-direction: column; }\n .detail-scroll { flex: 1 1 auto; }\n .detail-intro { display: grid; min-height: 132px; grid-template-columns: 34px minmax(0, 1fr); align-items: start; gap: 14px; padding: 22px; border-bottom: 1px solid var(--line); }\n .detail-icon { display: grid; width: 32px; height: 32px; border: 1px solid var(--line); color: var(--muted-strong); place-items: center; }\n .detail-icon .icon { width: 15px; height: 15px; }\n .detail-intro .mini-label { margin: 1px 0 8px; }\n .detail-intro h2 { margin: 0; overflow-wrap: anywhere; font-size: 20px; font-weight: 530; line-height: 1.2; }\n .detail-intro p { max-width: 680px; margin: 8px 0 0; color: var(--muted); font-size: 11px; line-height: 1.55; }\n .detail-section { border-top: 1px solid var(--line); }\n .detail-intro + .detail-section { border-top: 0; }\n .property-list { margin: 0; }\n .property-list > div { display: grid; min-height: 48px; grid-template-columns: minmax(120px, 0.32fr) minmax(0, 1fr); align-items: center; gap: 18px; padding: 9px 16px; border-bottom: 1px solid var(--line-soft); }\n .property-list dt { color: var(--muted); font-family: var(--font-mono); font-size: 9px; text-transform: uppercase; }\n .property-list dd { min-width: 0; margin: 0; overflow-wrap: anywhere; color: var(--muted-strong); font-size: 11px; }\n .property-list dd > code { color: var(--foreground); font-size: 10px; }\n .single-pane { height: 100%; min-height: 0; }\n .json-viewer { min-height: 100%; margin: 0; padding: 16px; overflow: auto; background: #000; color: var(--muted-strong); font-family: var(--font-mono); font-size: 10px; line-height: 1.65; tab-size: 2; white-space: pre-wrap; word-break: break-word; }\n .diagnostic { display: grid; grid-template-columns: 32px minmax(0, 1fr) auto; align-items: start; gap: 12px; min-height: 88px; padding: 16px 18px; border-bottom: 1px solid var(--line-soft); }\n .diagnostic:last-child { border-bottom: 0; }\n .diagnostic-mark { display: grid; width: 28px; height: 28px; place-items: center; border: 1px solid var(--line); color: var(--muted-strong); }\n .diagnostic-code { display: block; margin-bottom: 5px; color: var(--muted); font-size: 9px; }\n .diagnostic strong { display: block; font-size: 12px; font-weight: 540; }\n .diagnostic p { margin: 5px 0 0; color: var(--muted-strong); font-size: 11px; line-height: 1.5; }\n .diagnostic small { display: block; margin-top: 6px; color: var(--muted); font-size: 10px; line-height: 1.5; }\n .diagnostic-warning { box-shadow: inset 1px 0 var(--line-strong); }\n .system-row { display: grid; grid-template-columns: 32px minmax(0, 1fr) auto; min-height: 64px; align-items: center; gap: 10px; padding: 11px 16px; border-bottom: 1px solid var(--line-soft); }\n .system-row:last-child { border-bottom: 0; }\n .system-icon { display: grid; width: 28px; height: 28px; place-items: center; color: var(--muted-strong); }\n .system-row strong, .system-row small { display: block; }\n .system-row strong { font-size: 12px; font-weight: 520; }\n .system-row small { margin-top: 3px; overflow: hidden; color: var(--muted); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }\n .system-value { font-family: var(--font-mono); font-size: 11px; }\n .filter-control { display: flex; width: min(280px, 34vw); min-height: 34px; align-items: center; gap: 8px; padding: 0 9px; border: 1px solid var(--line); background: #000; color: var(--muted); }\n .filter-control:focus-within { border-color: var(--line-strong); color: #fff; }\n .filter-control input { min-width: 0; flex: 1; border: 0; outline: 0; background: transparent; color: var(--foreground); font-family: var(--font-mono); font-size: 10px; }\n .filter-control input::placeholder { color: #666; }\n .filter-control kbd { padding: 1px 5px; border: 1px solid var(--line); color: var(--muted); font-size: 9px; }\n .table-scroll { width: 100%; overflow-x: auto; }\n table { width: 100%; border-collapse: collapse; table-layout: auto; }\n th { height: 36px; padding: 0 16px; border-bottom: 1px solid var(--line); background: #030303; color: var(--muted); font-size: 9px; font-weight: 400; text-align: left; text-transform: uppercase; white-space: nowrap; }\n td { min-height: 48px; padding: 12px 16px; border-bottom: 1px solid var(--line-soft); color: var(--muted-strong); font-size: 11px; line-height: 1.55; vertical-align: top; }\n tr:last-child td { border-bottom: 0; }\n tbody tr { transition: background-color 120ms ease-out; }\n tbody tr:hover { background: rgb(255 255 255 / 0.035); }\n td code { color: var(--foreground); font-size: 10px; white-space: nowrap; }\n .file-cell { max-width: 420px; overflow: hidden; font-family: var(--font-mono); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }\n .badge { display: inline-flex; min-height: 20px; align-items: center; padding: 1px 6px; border: 1px solid var(--line); color: var(--muted-strong); font-size: 9px; font-weight: 400; text-transform: uppercase; white-space: nowrap; }\n .badge-ready, .badge-page, .badge-node { border-color: var(--line-strong); color: #fff; }\n .badge-warning, .badge-attention, .badge-edge { border-style: dashed; color: #fff; }\n .badge-error { background: #fff; color: #000; }\n .badge-method { min-width: 36px; justify-content: center; border-color: var(--line-soft); color: #d0d0d0; }\n .method-list, .runtime-value, .runtime-facts { display: flex; flex-wrap: wrap; align-items: center; gap: 5px; }\n .runtime-value small, .runtime-facts span { color: var(--muted); font-family: var(--font-mono); font-size: 9px; }\n .cell-detail { display: block; margin-top: 4px; color: var(--muted); font-family: var(--font-mono); font-size: 9px; }\n .route-operation { display: flex; align-items: center; justify-content: space-between; gap: 12px; }\n .route-operation + .route-operation { margin-top: 5px; }\n .route-operation small { color: var(--muted); font-family: var(--font-mono); font-size: 9px; white-space: nowrap; }\n .schedule { display: block; }\n .schedule + .schedule { margin-top: 4px; }\n .muted { color: var(--muted); }\n .empty-state { display: grid; min-height: 156px; place-items: center; align-content: center; gap: 7px; padding: 24px; color: var(--muted); text-align: center; }\n .empty-state strong { color: var(--muted-strong); font-size: 12px; font-weight: 520; }\n .empty-state span { max-width: 420px; font-size: 10px; line-height: 1.5; }\n .filtered-empty { padding: 24px; color: var(--muted); font-family: var(--font-mono); font-size: 10px; text-align: center; }\n .feature-matrix > div { display: flex; min-height: 45px; align-items: center; justify-content: space-between; gap: 16px; padding: 9px 16px; border-bottom: 1px solid var(--line-soft); }\n .feature-matrix > div:last-child { border-bottom: 0; }\n .feature-matrix span:first-child { font-size: 11px; }\n .environment-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); }\n .environment-grid > div { min-height: 128px; padding: 16px; }\n .environment-grid > div + div { border-left: 1px solid var(--line); }\n .mini-label { display: block; margin-bottom: 12px; color: var(--muted); font-size: 9px; text-transform: uppercase; }\n .key-list { display: flex; flex-wrap: wrap; gap: 6px; }\n .key-list code { padding: 4px 6px; border: 1px solid var(--line-soft); color: var(--muted-strong); font-size: 9px; }\n .layer-list > div { display: grid; grid-template-columns: minmax(120px, 0.7fr) minmax(0, 1fr) auto; min-height: 52px; align-items: center; gap: 14px; padding: 10px 16px; border-bottom: 1px solid var(--line-soft); }\n .layer-list > div:last-child { border-bottom: 0; }\n .layer-list span { display: flex; align-items: center; gap: 8px; }\n .layer-list strong { font-size: 11px; font-weight: 520; }\n .layer-list code, .layer-list small { color: var(--muted); font-size: 9px; }\n .statusbar { display: flex; min-height: 29px; flex: 0 0 auto; align-items: center; justify-content: space-between; gap: 16px; padding: 0 10px; border-top: 1px solid var(--line); background: var(--surface); color: var(--muted); font-size: 9px; text-transform: uppercase; }\n .statusbar span { display: flex; align-items: center; gap: 7px; }\n @keyframes status-pulse { 0%, 100% { opacity: 0.4; } 50% { opacity: 1; } }\n @media (max-width: 1100px) {\n .topbar-status { display: none; }\n }\n @media (max-width: 840px) {\n .stage { display: block; padding: 0; }\n .shell { width: 100%; height: 100dvh; min-height: 0; border: 0; }\n .topbar { flex-wrap: wrap; }\n .brand { min-width: auto; height: 40px; border-right: 0; }\n .brand-product, .brand-slash { display: none; }\n .tabbar { order: 3; width: 100%; flex-basis: 100%; border-top: 1px solid var(--line); }\n .topbar-meta { height: 40px; }\n .nav-item { min-height: 39px; }\n .split-view { grid-template-columns: 1fr; grid-template-rows: minmax(150px, 34%) minmax(0, 1fr); }\n .pane-list { border-right: 0; border-bottom: 1px solid var(--line); }\n .filter-control { width: 100%; }\n }\n @media (max-width: 560px) {\n .detail-intro { min-height: 112px; padding: 16px; }\n .detail-intro h2 { font-size: 17px; }\n .property-list > div { grid-template-columns: minmax(98px, 0.38fr) minmax(0, 1fr); gap: 12px; padding-inline: 12px; }\n .environment-grid { grid-template-columns: 1fr; }\n .environment-grid > div + div { border-top: 1px solid var(--line); border-left: 0; }\n .statusbar span:last-child { display: none; }\n }\n @media (prefers-reduced-motion: reduce) {\n html { scroll-behavior: auto; }\n *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; }\n }\n </style>\n <style data-assistant-ui-layout>\n :root {\n --background: #0a0a0a;\n --surface: #0a0a0a;\n --surface-raised: #111111;\n --foreground: #ededed;\n --muted: #929299;\n --muted-strong: #b4b4ba;\n --line: rgb(255 255 255 / 0.11);\n --line-soft: rgb(255 255 255 / 0.075);\n --line-strong: rgb(255 255 255 / 0.16);\n --accent: #1c1c1e;\n }\n html, body { width: 100%; height: 100%; background: #080808; }\n body { position: relative; min-height: 100dvh; overflow: hidden; font-size: 13px; }\n .stage {\n position: fixed;\n inset: 0;\n z-index: 2;\n display: grid;\n min-height: 0;\n padding: 20px;\n place-items: center;\n pointer-events: none;\n }\n .shell {\n width: min(960px, 92vw);\n height: min(560px, 80dvh);\n min-width: 0;\n min-height: 0;\n border: 1px solid var(--line-strong);\n border-radius: 12px;\n background: var(--background);\n box-shadow: 0 24px 80px rgb(0 0 0 / 0.72), 0 4px 18px rgb(0 0 0 / 0.45);\n pointer-events: auto;\n animation: devtools-window-in 180ms cubic-bezier(0.175, 0.885, 0.32, 1.08);\n }\n .topbar {\n min-height: 40px;\n height: 40px;\n align-items: center;\n justify-content: space-between;\n flex-wrap: nowrap;\n border-bottom-color: var(--line);\n background: var(--background);\n }\n .brand { display: none; }\n .tabbar {\n height: 100%;\n flex: 1 1 auto;\n align-items: stretch;\n order: initial;\n width: auto;\n flex-basis: auto;\n padding-inline-start: 8px;\n border-top: 0;\n }\n .nav-item {\n min-height: 39px;\n height: 39px;\n gap: 0;\n padding: 0 12px;\n border-radius: 0;\n color: var(--muted);\n font-family: var(--font-sans);\n font-size: 13px;\n font-weight: 500;\n text-transform: none;\n }\n .nav-item::after {\n right: 8px;\n bottom: -1px;\n left: 8px;\n height: 2px;\n border-radius: 999px;\n }\n .nav-item:hover, .nav-item:focus-visible { background: transparent; color: var(--foreground); }\n .nav-item[aria-selected=\"true\"] { color: var(--foreground); }\n .topbar-meta {\n height: 100%;\n align-items: center;\n gap: 8px;\n margin-left: 0;\n padding: 0 8px 0 4px;\n border-left: 0;\n }\n .project-select {\n display: inline-flex;\n height: 28px;\n min-width: 0;\n align-items: center;\n gap: 5px;\n padding: 0 9px;\n border: 1px solid var(--line);\n border-radius: 8px;\n color: var(--muted-strong);\n font-size: 12px;\n white-space: nowrap;\n }\n .project-select .icon { width: 12px; height: 12px; transform: rotate(90deg); }\n .topbar-status {\n min-width: max-content;\n gap: 6px;\n padding: 0;\n color: var(--muted);\n font-family: var(--font-sans);\n font-size: 11px;\n text-transform: none;\n }\n .status-dot {\n width: 6px;\n height: 6px;\n border: 0;\n border-radius: 999px;\n background: #2dd4bf;\n box-shadow: none;\n }\n .status-dot-attention { background: #f59e0b; animation: none; }\n .status-dot-error { background: #ef4444; }\n .close-action {\n display: inline-flex;\n width: 28px;\n height: 28px;\n flex: 0 0 auto;\n align-items: center;\n justify-content: center;\n padding: 0;\n border: 0;\n border-radius: 6px;\n background: transparent;\n color: var(--muted);\n text-decoration: none;\n transition: background-color 120ms ease-out, color 120ms ease-out;\n }\n .close-action:hover, .close-action:focus-visible { background: var(--accent); color: var(--foreground); outline: none; }\n .close-action .icon { width: 14px; height: 14px; }\n .workspace, .content, .view { min-height: 0; }\n .split-view {\n grid-template-columns: clamp(14rem, 28%, 18rem) minmax(0, 1fr);\n grid-template-rows: minmax(0, 1fr);\n }\n .pane { background: var(--background); }\n .pane-list { border-right: 1px solid var(--line); border-bottom: 0; }\n .pane-header {\n min-height: 32px;\n height: 32px;\n max-height: 32px;\n flex: 0 0 32px;\n padding: 0 12px;\n border-bottom-color: var(--line);\n background: var(--background);\n }\n .pane-header strong {\n color: var(--muted);\n font-size: 11px;\n font-weight: 400;\n line-height: 1;\n }\n .pane-header span {\n color: var(--muted);\n font-family: var(--font-sans);\n font-size: 10px;\n line-height: 1;\n }\n .pane-tools { border-bottom-color: var(--line); }\n .pane-tools .filter-control { min-height: 32px; height: 32px; }\n .filter-control {\n min-height: 32px;\n gap: 7px;\n padding: 0 10px;\n border-color: var(--line);\n border-radius: 0;\n background: var(--background);\n }\n .filter-control .icon { width: 13px; height: 13px; }\n .filter-control input { font-family: var(--font-sans); font-size: 11px; }\n .filter-control input::placeholder { color: var(--muted); }\n .filter-control kbd {\n padding: 1px 5px;\n border-color: var(--line);\n border-radius: 4px;\n color: var(--muted);\n font-size: 9px;\n }\n .inspector-row {\n min-height: 44px;\n grid-template-columns: minmax(0, 1fr) auto;\n gap: 8px;\n padding: 6px 11px 6px 12px;\n border: 0;\n border-left: 2px solid transparent;\n border-radius: 0;\n color: var(--muted-strong);\n }\n .inspector-row::before { display: none; }\n .inspector-row:hover, .inspector-row:focus-visible { background: rgb(255 255 255 / 0.035); color: var(--foreground); }\n .inspector-row[aria-selected=\"true\"] {\n border-left-color: var(--foreground);\n background: var(--accent);\n color: var(--foreground);\n }\n .inspector-row-copy strong { font-size: 12px; font-weight: 500; }\n .inspector-row-copy small {\n margin-top: 2px;\n color: var(--muted);\n font-family: var(--font-sans);\n font-size: 10px;\n }\n .inspector-row-value {\n padding: 2px 6px;\n border: 1px solid var(--line);\n border-radius: 999px;\n background: rgb(255 255 255 / 0.035);\n color: var(--muted);\n font-family: var(--font-sans);\n font-size: 9px;\n line-height: 1.2;\n text-transform: none;\n }\n .detail-intro {\n display: block;\n min-height: 0;\n padding: 12px;\n border-bottom-color: var(--line-soft);\n }\n .detail-icon { display: none; }\n .detail-intro .mini-label { margin: 0 0 8px; }\n .detail-intro h2 { font-size: 13px; font-weight: 500; line-height: 1.3; }\n .detail-intro p { margin-top: 6px; font-size: 11px; line-height: 1.5; }\n .detail-section, .detail-intro + .detail-section { border-top-color: var(--line); }\n .property-list > div {\n min-height: 36px;\n grid-template-columns: minmax(96px, 0.28fr) minmax(0, 1fr);\n gap: 14px;\n padding: 7px 12px;\n border-bottom-color: var(--line-soft);\n }\n .property-list dt { font-family: var(--font-sans); font-size: 10px; text-transform: none; }\n .property-list dd { color: var(--foreground); font-size: 11px; }\n .property-list dd > code { font-size: 10px; }\n .json-viewer {\n padding: 12px;\n background: var(--background);\n color: var(--muted-strong);\n font-size: 10px;\n line-height: 1.55;\n }\n .diagnostic {\n min-height: 68px;\n grid-template-columns: 24px minmax(0, 1fr) auto;\n gap: 10px;\n padding: 11px 12px;\n border-bottom-color: var(--line-soft);\n }\n .diagnostic-mark { width: 22px; height: 22px; border: 0; }\n .diagnostic-mark .icon { width: 13px; height: 13px; }\n .diagnostic-code { margin-bottom: 3px; font-size: 9px; }\n .diagnostic strong { font-size: 11px; font-weight: 500; }\n .diagnostic p { margin-top: 3px; font-size: 10px; line-height: 1.45; }\n .diagnostic small { margin-top: 4px; font-size: 9px; }\n .diagnostic-warning { box-shadow: none; }\n .system-row {\n min-height: 48px;\n grid-template-columns: 24px minmax(0, 1fr) auto;\n gap: 8px;\n padding: 8px 12px;\n border-bottom-color: var(--line-soft);\n }\n .system-icon { width: 20px; height: 20px; }\n .system-icon .icon { width: 13px; height: 13px; }\n .system-row strong { font-size: 11px; font-weight: 500; }\n .system-row small { margin-top: 2px; font-size: 10px; }\n .system-value { color: var(--muted); font-size: 10px; }\n table { font-size: 11px; }\n th {\n height: 32px;\n padding: 0 12px;\n background: var(--background);\n font-family: var(--font-sans);\n font-size: 10px;\n font-weight: 400;\n text-transform: none;\n }\n td { min-height: 40px; padding: 9px 12px; font-size: 10px; }\n td code, .file-cell { font-size: 9px; }\n .badge {\n min-height: 18px;\n padding: 1px 6px;\n border-radius: 999px;\n background: rgb(255 255 255 / 0.04);\n font-family: var(--font-sans);\n font-size: 9px;\n text-transform: none;\n }\n .badge-error { background: var(--foreground); color: var(--background); }\n .badge-warning, .badge-attention, .badge-edge { border-style: solid; }\n .empty-state { min-height: 100%; padding: 24px; gap: 6px; }\n .empty-state .icon { display: none; }\n .empty-state strong { font-size: 12px; font-weight: 400; }\n .empty-state span { font-size: 11px; }\n .feature-matrix > div { min-height: 36px; padding: 7px 12px; border-bottom-color: var(--line-soft); }\n .feature-matrix span:first-child { font-size: 11px; }\n .environment-grid > div { min-height: 104px; padding: 12px; }\n .mini-label { margin-bottom: 8px; font-family: var(--font-sans); font-size: 10px; text-transform: none; }\n .key-list code { border-radius: 4px; font-size: 9px; }\n .layer-list > div { min-height: 44px; padding: 8px 12px; border-bottom-color: var(--line-soft); }\n .layer-list strong { font-size: 11px; font-weight: 500; }\n .statusbar { display: none; }\n html.devtools-frame .stage { position: static; width: 100%; height: 100%; min-height: 100%; padding: 0; }\n html.devtools-frame .shell { width: 100%; height: 100%; border-radius: 12px; box-shadow: none; animation: none; }\n @keyframes devtools-window-in {\n from { opacity: 0; transform: scale(0.985) translateY(4px); }\n to { opacity: 1; transform: scale(1) translateY(0); }\n }\n @media (max-width: 700px) {\n .stage { display: grid; padding: 0; }\n .shell {\n width: 100%;\n height: 100%;\n min-height: 0;\n border: 1px solid var(--line-strong);\n border-radius: 10px;\n }\n .topbar { flex-wrap: nowrap; }\n .tabbar {\n order: initial;\n width: auto;\n flex-basis: auto;\n border-top: 0;\n padding-inline-start: 4px;\n }\n .topbar-meta { height: 40px; }\n .nav-item { min-height: 39px; height: 39px; padding-inline: 9px; }\n .split-view { grid-template-columns: 1fr; grid-template-rows: minmax(148px, 36%) minmax(0, 1fr); }\n .pane-list { border-right: 0; border-bottom: 1px solid var(--line); }\n }\n @media (max-width: 560px) {\n .project-select { display: none; }\n .topbar-status { display: none; }\n .topbar-meta { gap: 4px; padding-left: 0; }\n .status-label { display: none; }\n .detail-intro { min-height: 0; padding: 12px; }\n .detail-intro h2 { font-size: 13px; }\n .property-list > div { grid-template-columns: minmax(82px, 0.34fr) minmax(0, 1fr); gap: 10px; padding-inline: 10px; }\n }\n @media (prefers-reduced-motion: reduce) {\n .shell { animation: none; }\n }\n </style>\n</head>\n<body>\n <div class=\"stage\">\n <div class=\"shell\" role=\"dialog\" aria-modal=\"true\" aria-label=\"Farm.js DevTools\">\n <header class=\"topbar\">\n <nav class=\"tabbar\" aria-label=\"Devtools views\">\n ${renderNavigationItem(\"overview\", \"Overview\")}\n ${renderNavigationItem(\"routes\", \"Routes\")}\n ${renderNavigationItem(\"api\", \"API\")}\n ${renderNavigationItem(\"systems\", \"Systems\")}\n ${renderNavigationItem(\"runtime\", \"Runtime\")}\n ${renderNavigationItem(\"raw\", \"Raw\")}\n </nav>\n <div class=\"topbar-meta\">\n <span class=\"project-select\">${escapeHtml(snapshot.project.name)} ${icon(\n \"chevron\",\n )}</span>\n <span class=\"topbar-status\"><span class=\"status-dot\"></span><span class=\"status-label\">1 instance</span></span>\n <button class=\"close-action\" type=\"button\" data-close-devtools aria-label=\"Close DevTools\" title=\"Close DevTools\">${icon(\n \"close\",\n )}</button>\n </div>\n </header>\n <div class=\"workspace\">\n <main class=\"content\">\n <section class=\"view\" data-view-panel=\"overview\">${renderOverviewInspector(\n snapshot,\n healthLabel,\n generatedTime,\n )}</section>\n <section class=\"view\" data-view-panel=\"routes\" hidden>${renderRoutesInspector(\n snapshot,\n )}</section>\n <section class=\"view\" data-view-panel=\"api\" hidden>${renderApiInspector(\n snapshot,\n )}</section>\n <section class=\"view\" data-view-panel=\"systems\" hidden>${renderSystemsInspector(\n snapshot,\n )}</section>\n <section class=\"view\" data-view-panel=\"runtime\" hidden>${renderRuntimeInspector(\n snapshot,\n )}</section>\n <section class=\"view\" data-view-panel=\"raw\" hidden>${renderRawInspector(snapshot)}</section>\n </main>\n </div>\n </div>\n </div>\n <script>\n (() => {\n const embedded = window.parent !== window;\n const closeDevtools = () => {\n if (embedded && window.parent !== window) {\n window.parent.postMessage({ type: \"farm:devtools:close\" }, location.origin);\n return;\n }\n location.assign(\"/\");\n };\n document.querySelector(\"[data-close-devtools]\")?.addEventListener(\"click\", closeDevtools);\n document.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Escape\") {\n event.preventDefault();\n closeDevtools();\n return;\n }\n if (embedded && window.parent !== window) {\n window.parent.postMessage(\n {\n type: \"farm:devtools:keydown\",\n event: {\n key: event.key,\n code: event.code,\n altKey: event.altKey,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n repeat: event.repeat,\n },\n },\n location.origin,\n );\n }\n });\n\n const validViews = new Set([\"overview\", \"routes\", \"api\", \"systems\", \"runtime\", \"raw\"]);\n const triggers = Array.from(document.querySelectorAll(\"[data-view-trigger]\"));\n const panels = Array.from(document.querySelectorAll(\"[data-view-panel]\"));\n const selectView = (view, updateHash = true) => {\n const nextView = validViews.has(view) ? view : \"overview\";\n triggers.forEach((trigger) => {\n trigger.setAttribute(\"aria-selected\", String(trigger.dataset.viewTrigger === nextView));\n });\n panels.forEach((panel) => {\n panel.hidden = panel.dataset.viewPanel !== nextView;\n });\n if (updateHash) {\n history.replaceState(null, \"\", nextView === \"overview\" ? location.pathname : \"#\" + nextView);\n const activePanel = panels.find((panel) => panel.dataset.viewPanel === nextView);\n if (activePanel) activePanel.scrollTop = 0;\n }\n };\n triggers.forEach((trigger) => trigger.addEventListener(\"click\", () => selectView(trigger.dataset.viewTrigger)));\n window.addEventListener(\"hashchange\", () => selectView(location.hash.slice(1), false));\n selectView(location.hash.slice(1), false);\n\n document.querySelectorAll(\"[data-detail-trigger]\").forEach((trigger) => {\n trigger.addEventListener(\"click\", () => {\n const scope = trigger.dataset.detailTrigger;\n const id = trigger.dataset.detailId;\n document.querySelectorAll('[data-detail-trigger=\"' + scope + '\"]').forEach((row) => {\n row.setAttribute(\"aria-selected\", String(row.dataset.detailId === id));\n });\n document.querySelectorAll('[data-detail-panel=\"' + scope + '\"]').forEach((panel) => {\n panel.hidden = panel.dataset.detailId !== id;\n });\n });\n });\n\n document.querySelectorAll(\"[data-filter]\").forEach((input) => {\n input.addEventListener(\"input\", () => {\n const id = input.dataset.filter;\n const query = input.value.trim().toLowerCase();\n const rows = Array.from(document.querySelectorAll('[data-filter-rows=\"' + id + '\"] [data-search-value]'));\n let visible = 0;\n rows.forEach((row) => {\n const matches = !query || (row.dataset.searchValue || \"\").toLowerCase().includes(query);\n row.hidden = !matches;\n if (matches) visible += 1;\n });\n const selected = rows.find((row) => row.getAttribute(\"aria-selected\") === \"true\");\n if (selected?.hidden) rows.find((row) => !row.hidden)?.click();\n const empty = document.querySelector('[data-filter-empty=\"' + id + '\"]');\n if (empty) empty.hidden = visible !== 0;\n });\n });\n\n document.addEventListener(\"keydown\", (event) => {\n if (event.key !== \"/\" || event.metaKey || event.ctrlKey || event.altKey) return;\n const active = document.activeElement;\n if (active && (active.tagName === \"INPUT\" || active.tagName === \"TEXTAREA\")) return;\n const panel = document.querySelector(\"[data-view-panel]:not([hidden])\");\n const input = panel?.querySelector(\"[data-filter]\");\n if (input) {\n event.preventDefault();\n input.focus();\n }\n });\n\n document.querySelector(\"[data-refresh]\")?.addEventListener(\"click\", () => location.reload());\n document.querySelector(\"[data-copy-snapshot]\")?.addEventListener(\"click\", async (event) => {\n const button = event.currentTarget;\n const label = button.querySelector(\"[data-copy-label]\");\n try {\n const response = await fetch(\"/__farm/devtools.json\", { cache: \"no-store\" });\n const value = JSON.stringify(await response.json(), null, 2);\n if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(value);\n else {\n const textarea = document.createElement(\"textarea\");\n textarea.value = value;\n document.body.appendChild(textarea);\n textarea.select();\n document.execCommand(\"copy\");\n textarea.remove();\n }\n button.dataset.copied = \"true\";\n if (label) label.textContent = \"Copied\";\n setTimeout(() => {\n button.dataset.copied = \"false\";\n if (label) label.textContent = \"Copy JSON\";\n }, 1600);\n } catch {\n if (label) label.textContent = \"Copy failed\";\n }\n });\n })();\n </script>\n</body>\n</html>`;\n}\n","import {\n FARM_DEVTOOLS_LAUNCH_PARAM,\n FARM_DEVTOOLS_PATH,\n type ResolvedFarmDevtoolsConfig,\n} from \"./devtools-config\";\n\ntype ParsedShortcut = {\n key: string;\n alt: boolean;\n ctrl: boolean;\n meta: boolean;\n mod: boolean;\n shift: boolean;\n};\n\nfunction parseShortcut(shortcut: string): ParsedShortcut | null {\n const tokens = shortcut\n .toLowerCase()\n .split(\"+\")\n .map((token) => token.trim())\n .filter(Boolean);\n const key = tokens.find(\n (token) =>\n ![\n \"alt\",\n \"ctrl\",\n \"control\",\n \"meta\",\n \"cmd\",\n \"command\",\n \"mod\",\n \"shift\",\n ].includes(token),\n );\n\n if (!key) {\n return null;\n }\n\n return {\n key,\n alt: tokens.includes(\"alt\"),\n ctrl: tokens.includes(\"ctrl\") || tokens.includes(\"control\"),\n meta:\n tokens.includes(\"meta\") ||\n tokens.includes(\"cmd\") ||\n tokens.includes(\"command\"),\n mod: tokens.includes(\"mod\"),\n shift: tokens.includes(\"shift\"),\n };\n}\n\nexport function generateFarmDevtoolsClientRuntime(\n config: ResolvedFarmDevtoolsConfig,\n): string {\n if (!config.enabled) {\n return \"\";\n }\n\n const shortcut = config.shortcut ? parseShortcut(config.shortcut) : null;\n const overlayStyles = `\n #__farm_devtools_overlay__ {\n position: fixed;\n inset: 0;\n z-index: 2147483646;\n display: grid;\n place-items: center;\n padding: 20px;\n background: rgb(0 0 0 / 0);\n backdrop-filter: blur(0);\n opacity: 0;\n pointer-events: none;\n transition: background-color 150ms ease-out, backdrop-filter 150ms ease-out, opacity 150ms ease-out;\n }\n #__farm_devtools_overlay__[data-open=\"true\"] {\n background: rgb(0 0 0 / 0.12);\n backdrop-filter: blur(1px);\n opacity: 1;\n pointer-events: auto;\n }\n #__farm_devtools_overlay__ > iframe {\n display: block;\n width: min(960px, calc(100vw - 40px));\n height: min(560px, calc(100dvh - 40px));\n border: 0;\n border-radius: 12px;\n background: transparent;\n box-shadow: 0 24px 80px rgb(0 0 0 / 0.48), 0 4px 18px rgb(0 0 0 / 0.24);\n transform: scale(0.985) translateY(4px);\n transition: transform 150ms ease-out;\n }\n #__farm_devtools_overlay__[data-open=\"true\"] > iframe {\n transform: scale(1) translateY(0);\n }\n @media (max-width: 700px) {\n #__farm_devtools_overlay__ { padding: 8px; }\n #__farm_devtools_overlay__ > iframe {\n width: calc(100vw - 16px);\n height: calc(100dvh - 16px);\n border-radius: 10px;\n }\n }\n @media (prefers-reduced-motion: reduce) {\n #__farm_devtools_overlay__, #__farm_devtools_overlay__ > iframe { transition: none; }\n }\n `;\n\n return `\n(() => {\n const overlayId = \"__farm_devtools_overlay__\";\n const styleId = \"__farm_devtools_overlay_styles__\";\n const runtimeKey = \"__FARM_DEVTOOLS_RUNTIME__\";\n const launchParam = ${JSON.stringify(FARM_DEVTOOLS_LAUNCH_PARAM)};\n const devtoolsPath = ${JSON.stringify(FARM_DEVTOOLS_PATH)};\n const validViews = new Set([\"overview\", \"routes\", \"api\", \"systems\", \"runtime\", \"raw\"]);\n const shortcut = ${JSON.stringify(shortcut)};\n const isMac = /Mac|iPhone|iPad|iPod/.test(navigator.platform);\n let returnFocus = null;\n\n const matchesShortcut = (event) => {\n if (!shortcut || event.repeat) return false;\n const expectedCtrl = shortcut.ctrl || (shortcut.mod && !isMac);\n const expectedMeta = shortcut.meta || (shortcut.mod && isMac);\n if (\n Boolean(event.altKey) !== shortcut.alt ||\n Boolean(event.ctrlKey) !== expectedCtrl ||\n Boolean(event.metaKey) !== expectedMeta ||\n Boolean(event.shiftKey) !== shortcut.shift\n ) return false;\n\n if (shortcut.key === \".\" || shortcut.key === \"period\") return event.code === \"Period\";\n if (shortcut.key === \",\" || shortcut.key === \"comma\") return event.code === \"Comma\";\n if (shortcut.key === \"/\" || shortcut.key === \"slash\") return event.code === \"Slash\";\n return String(event.key || \"\").toLowerCase() === shortcut.key;\n };\n\n const ensureStyles = () => {\n if (document.getElementById(styleId)) return;\n const style = document.createElement(\"style\");\n style.id = styleId;\n style.textContent = ${JSON.stringify(overlayStyles)};\n document.head.appendChild(style);\n };\n\n const close = () => {\n const overlay = document.getElementById(overlayId);\n if (!overlay) return;\n const focusTarget = returnFocus;\n returnFocus = null;\n overlay.dataset.open = \"false\";\n window.setTimeout(() => {\n overlay.remove();\n focusTarget?.focus?.();\n }, 160);\n };\n\n const open = (view = \"overview\") => {\n if (document.getElementById(overlayId)) return;\n ensureStyles();\n returnFocus = document.activeElement;\n const overlay = document.createElement(\"div\");\n overlay.id = overlayId;\n overlay.setAttribute(\"aria-label\", \"Farm.js DevTools overlay\");\n const frame = document.createElement(\"iframe\");\n const resolvedView = validViews.has(view) ? view : \"overview\";\n frame.src = devtoolsPath + \"?embedded=1\" + (resolvedView === \"overview\" ? \"\" : \"#\" + resolvedView);\n frame.title = \"Farm.js DevTools\";\n frame.addEventListener(\"load\", () => frame.contentWindow?.focus(), { once: true });\n overlay.appendChild(frame);\n overlay.addEventListener(\"pointerdown\", (event) => {\n if (event.target === overlay) close();\n });\n document.body.appendChild(overlay);\n requestAnimationFrame(() => {\n overlay.dataset.open = \"true\";\n });\n };\n\n const toggle = () => {\n if (document.getElementById(overlayId)) close();\n else open();\n };\n\n const onKeydown = (event) => {\n if (event.key === \"Escape\" && document.getElementById(overlayId)) {\n event.preventDefault();\n close();\n return;\n }\n if (!matchesShortcut(event)) return;\n event.preventDefault();\n event.stopPropagation();\n toggle();\n };\n\n const onMessage = (event) => {\n if (event.origin !== location.origin) return;\n const frame = document.querySelector(\"#\" + overlayId + \" > iframe\");\n if (!frame || event.source !== frame.contentWindow) return;\n if (event.data?.type === \"farm:devtools:close\") close();\n if (event.data?.type === \"farm:devtools:keydown\" && matchesShortcut(event.data.event || {})) close();\n };\n\n window[runtimeKey]?.dispose?.();\n window.addEventListener(\"keydown\", onKeydown, true);\n window.addEventListener(\"message\", onMessage);\n window[runtimeKey] = {\n dispose() {\n window.removeEventListener(\"keydown\", onKeydown, true);\n window.removeEventListener(\"message\", onMessage);\n },\n };\n window.__FARM_DEVTOOLS__ = { open, close, toggle };\n\n const launchUrl = new URL(location.href);\n const launchRequest = launchUrl.searchParams.get(launchParam);\n if (launchRequest !== null) {\n const hashView = launchUrl.hash.slice(1);\n const launchView = validViews.has(launchRequest)\n ? launchRequest\n : validViews.has(hashView)\n ? hashView\n : \"overview\";\n launchUrl.searchParams.delete(launchParam);\n if (validViews.has(hashView)) launchUrl.hash = \"\";\n history.replaceState(\n history.state,\n \"\",\n launchUrl.pathname + launchUrl.search + launchUrl.hash,\n );\n const launch = () => requestAnimationFrame(() => open(launchView));\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", launch, { once: true });\n } else {\n launch();\n }\n }\n})();\n`;\n}\n","import type { ResolvedFarmImageConfig } from \"./image-config\";\nimport {\n FarmImageRequestError,\n isPrivateImageAddress,\n selectOutputFormat,\n type FarmImageTransformer,\n} from \"./image-server\";\n\nexport function createSharpImageTransformer(): FarmImageTransformer {\n return async ({ source, sourceType, width, quality, accept, formats, signal }) => {\n // Sharp is an optional native runtime. Load it only when an image request\n // actually needs a transform so disabled/unused image pipelines do not add\n // a startup dependency or native-module initialization cost.\n const { default: sharp } = await import(\"sharp\");\n throwIfAborted(signal);\n const outputFormat = selectOutputFormat(accept, formats);\n let pipeline = sharp(source, {\n animated: sourceType === \"image/gif\" || sourceType === \"image/webp\",\n failOn: \"warning\",\n limitInputPixels: 268_402_689,\n })\n .rotate()\n .resize({ width, fit: \"inside\", withoutEnlargement: true });\n\n if (outputFormat === \"image/avif\") {\n pipeline = pipeline.avif({ quality });\n } else if (outputFormat === \"image/webp\") {\n pipeline = pipeline.webp({ quality });\n } else if (sourceType === \"image/png\") {\n pipeline = pipeline.png();\n } else if (sourceType === \"image/gif\") {\n pipeline = pipeline.gif();\n } else {\n pipeline = pipeline.jpeg({ quality });\n }\n\n const body = await pipeline.toBuffer();\n throwIfAborted(signal);\n return {\n body,\n contentType: outputFormat ?? normalizeSharpSourceType(sourceType),\n };\n };\n}\n\nexport function createNodeImageUrlValidator(config: ResolvedFarmImageConfig) {\n return async function validateNodeImageUrl(url: URL): Promise<void> {\n if (config.dangerouslyAllowLocalIP) return;\n\n let addresses: Array<{ address: string; family: number }>;\n try {\n // DNS is only needed by remote image requests. Keeping it out of the\n // initial server module graph reduces normal page/API startup work.\n const { lookup } = await import(\"node:dns/promises\");\n addresses = await lookup(url.hostname, { all: true, verbatim: true });\n } catch {\n throw new FarmImageRequestError(\n \"PRIVATE_SOURCE\",\n 400,\n \"Could not safely resolve the image source\",\n );\n }\n if (addresses.length === 0 || addresses.some(({ address }) => isPrivateImageAddress(address))) {\n throw new FarmImageRequestError(\"PRIVATE_SOURCE\", 400, \"Private image source is not allowed\");\n }\n };\n}\n\nfunction normalizeSharpSourceType(sourceType: string): string {\n return sourceType === \"image/svg+xml\" ? \"image/png\" : sourceType;\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n throw signal.reason instanceof Error\n ? signal.reason\n : new DOMException(\"The image request was aborted\", \"AbortError\");\n }\n}\n","import type { FarmConfig, FarmRequest, FarmResponse } from \"./types\";\nimport type { ViteDevServer } from \"vite\";\nimport type { FarmClientPlugin } from \"./client/plugin\";\nimport { getResolvedEnv, type ResolvedFarmEnv } from \"./env\";\nimport {\n clearRequestContext,\n deleteRequestContext,\n getRequestContext,\n getRequestContextSnapshot,\n hasRequestContext,\n setRequestContext,\n} from \"./request-context\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport interface PluginRequestContext {\n set: (\n target: FarmRequest | Request,\n key: string,\n value: any,\n options?: { exposeToPage?: boolean },\n ) => void;\n get: <T = any>(target: FarmRequest | Request, key: string) => T | undefined;\n has: (target: FarmRequest | Request, key: string) => boolean;\n delete: (target: FarmRequest | Request, key: string) => boolean;\n clear: (target: FarmRequest | Request) => void;\n getAll: (target: FarmRequest | Request, options?: { exposedOnly?: boolean }) => Map<string, any>;\n}\n\nexport interface FarmRequestStore {\n set(key: string, value: unknown, options?: { exposeToPage?: boolean }): void;\n get<T = unknown>(key: string): T | undefined;\n has(key: string): boolean;\n delete(key: string): boolean;\n clear(): void;\n snapshot(options?: { exposedOnly?: boolean }): Map<string, unknown>;\n}\n\nexport interface FarmPluginContext {\n config: FarmConfig;\n viteServer?: ViteDevServer;\n isDev: boolean;\n isProd: boolean;\n /** @deprecated Use `ctx.req` inside request hooks. */\n requestContext: PluginRequestContext;\n}\n\nexport interface FarmRequestPluginContext extends FarmPluginContext {\n /** Request-scoped values for the current hook invocation. */\n readonly req: FarmRequestStore;\n}\n\nexport interface RouteDiscoveredPayload {\n kind: \"page\" | \"layout\";\n pattern: string;\n modulePath: string;\n}\n\nexport interface RoutesGeneratedPayload {\n routes: RouteDiscoveredPayload[];\n pageCount: number;\n layoutCount: number;\n}\n\nexport interface MiddlewareDiscoveredPayload {\n path: string;\n filePath: string;\n handlerCount: number;\n}\n\nexport interface APIRouteDiscoveredPayload {\n path: string;\n filePath: string;\n methods: string[];\n}\n\nexport interface RouteMatchPayload {\n pathname: string;\n method?: string;\n}\n\nexport interface RouteMatchResultPayload {\n pathname: string;\n matched: boolean;\n routePattern: string | null;\n params: Record<string, string>;\n layoutPatterns: string[];\n}\n\nexport interface RenderLifecyclePayload {\n pathname: string;\n method: string;\n routePattern: string | null;\n params: Record<string, string>;\n}\n\nexport interface APIHandlerLifecyclePayload {\n pathname: string;\n method: string;\n routePath?: string;\n}\n\nexport interface ErrorLifecyclePayload {\n phase: string;\n error: unknown;\n meta?: Record<string, unknown>;\n}\n\nexport interface HMRUpdatePayload {\n file: string;\n modules: string[];\n}\n\nexport interface BundleLifecyclePayload {\n root: string;\n preset: string;\n universal: boolean;\n distDir: string;\n outputDir?: string;\n}\n\nexport interface BundleResultPayload extends BundleLifecyclePayload {\n success: boolean;\n}\n\nexport interface NitroBuildLifecyclePayload {\n root: string;\n preset: string;\n distDir: string;\n outputDir: string;\n}\n\nexport interface ShutdownPayload {\n reason: string;\n}\n\nexport type FarmPluginRuntimeKind =\n | \"request\"\n | \"page\"\n | \"api\"\n | \"action\"\n | \"integration\"\n | \"docs\"\n | \"asset\"\n | (string & {});\n\nexport interface FarmPluginRouteRuntimePayload {\n pathname: string;\n pattern?: string | null;\n params?: Record<string, string>;\n}\n\nexport interface FarmPluginSetupContext extends FarmPluginContext {\n env: ResolvedFarmEnv;\n}\n\nexport interface FarmPluginStateContext<TState = unknown> extends FarmPluginContext {\n state: TState;\n}\n\nexport interface FarmPluginRuntimeBaseEvent<\n TState = unknown,\n> extends FarmPluginStateContext<TState> {\n request: Request;\n /** Request-scoped values shared by plugin hooks. */\n req: FarmRequestStore;\n kind: FarmPluginRuntimeKind;\n route?: FarmPluginRouteRuntimePayload;\n signal: AbortSignal;\n waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type FarmPluginRuntimeContextEvent<TState = unknown> = FarmPluginRuntimeBaseEvent<TState>;\n\nexport interface FarmPluginRuntimeBeforeEvent<\n TState = unknown,\n TRequestContext extends object = Record<string, unknown>,\n> extends FarmPluginRuntimeBaseEvent<TState> {\n ctx: Readonly<TRequestContext>;\n}\n\nexport interface FarmPluginRuntimeAfterEvent<\n TState = unknown,\n TRequestContext extends object = Record<string, unknown>,\n> extends FarmPluginRuntimeBeforeEvent<TState, TRequestContext> {\n response: Response;\n durationMs: number;\n}\n\nexport interface FarmPluginRuntimeErrorEvent<\n TState = unknown,\n TRequestContext extends object = Record<string, unknown>,\n> extends FarmPluginRuntimeBeforeEvent<TState, TRequestContext> {\n error: unknown;\n durationMs: number;\n}\n\nexport type FarmPluginRuntimeStartEvent<TState = unknown> = FarmPluginStateContext<TState>;\n\nexport interface FarmPluginRuntimeCloseEvent<TState = unknown>\n extends FarmPluginStateContext<TState>, ShutdownPayload {}\n\nexport interface FarmPluginRuntimeHooks<\n TState = unknown,\n TRequestContext extends object = Record<string, unknown>,\n> {\n start?(event: FarmPluginRuntimeStartEvent<TState>): MaybePromise<void>;\n context?(event: FarmPluginRuntimeContextEvent<TState>): MaybePromise<TRequestContext>;\n before?(\n event: FarmPluginRuntimeBeforeEvent<TState, TRequestContext>,\n ): MaybePromise<Request | Response | void>;\n after?(\n event: FarmPluginRuntimeAfterEvent<TState, TRequestContext>,\n ): MaybePromise<Response | void>;\n error?(event: FarmPluginRuntimeErrorEvent<TState, TRequestContext>): MaybePromise<void>;\n close?(event: FarmPluginRuntimeCloseEvent<TState>): MaybePromise<void>;\n}\n\nexport interface FarmPluginRuntimeRequestOptions {\n kind?: FarmPluginRuntimeKind;\n route?: FarmPluginRouteRuntimePayload;\n waitUntil?: (promise: Promise<unknown>) => void;\n}\n\nexport type FarmPluginRuntimeRequestHandler = (request: Request) => MaybePromise<Response>;\n\nexport interface FarmPluginRuntimeSession {\n request: Request;\n response?: Response;\n ctx: Readonly<Record<string, unknown>>;\n startedAt: number;\n options: FarmPluginRuntimeRequestOptions;\n waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type FarmPluginDiscoveredRoute =\n | RouteDiscoveredPayload\n | ({ kind: \"middleware\" } & MiddlewareDiscoveredPayload)\n | ({ kind: \"api\" } & APIRouteDiscoveredPayload);\n\nexport interface FarmPluginRouterHooks<TState = unknown> {\n discovered?(\n route: FarmPluginDiscoveredRoute,\n context: FarmPluginStateContext<TState>,\n ): MaybePromise<void>;\n generated?(\n routes: RoutesGeneratedPayload,\n context: FarmPluginStateContext<TState>,\n ): MaybePromise<void>;\n before?(route: RouteMatchPayload, context: FarmPluginStateContext<TState>): MaybePromise<void>;\n after?(\n result: RouteMatchResultPayload,\n context: FarmPluginStateContext<TState>,\n ): MaybePromise<void>;\n}\n\nexport interface FarmPluginRenderHooks<TState = unknown> {\n before?(\n render: RenderLifecyclePayload,\n context: FarmPluginStateContext<TState>,\n ): MaybePromise<void>;\n html?(\n html: string,\n render: RenderLifecyclePayload,\n context: FarmPluginStateContext<TState>,\n ): MaybePromise<string | void>;\n}\n\nexport interface FarmPluginBuildHooks<TState = unknown> {\n before?(\n bundle: BundleLifecyclePayload,\n context: FarmPluginStateContext<TState>,\n ): MaybePromise<void>;\n configure?(buildConfig: any, context: FarmPluginStateContext<TState>): MaybePromise<any>;\n after?(result: BundleResultPayload, context: FarmPluginStateContext<TState>): MaybePromise<void>;\n}\n\nexport interface FarmPluginDevHooks<TState = unknown> {\n server?(viteServer: ViteDevServer, context: FarmPluginStateContext<TState>): MaybePromise<void>;\n update?(update: HMRUpdatePayload, context: FarmPluginStateContext<TState>): MaybePromise<void>;\n}\n\nexport interface FarmPluginClientConfig<\n TState = unknown,\n TPublic = undefined,\n> extends FarmClientPlugin<TState, TPublic> {\n /** Explicitly public, JSON-safe data embedded in the browser bundle. */\n public?: TPublic;\n}\n\nexport interface FarmPlugin<\n TState = any,\n TRequestContext extends object = Record<string, unknown>,\n TClientState = any,\n TClientPublic = any,\n> {\n name: string;\n version?: string;\n enforce?: \"pre\" | \"post\";\n\n /** Transform Farm config before it is resolved. */\n configure?: (config: FarmConfig, context: FarmPluginContext) => MaybePromise<FarmConfig | void>;\n /** Initialize private plugin state once for this plugin manager. */\n setup?: (context: FarmPluginSetupContext) => MaybePromise<TState>;\n\n runtime?: FarmPluginRuntimeHooks<TState, TRequestContext>;\n router?: FarmPluginRouterHooks<TState>;\n render?: FarmPluginRenderHooks<TState>;\n build?: FarmPluginBuildHooks<TState>;\n dev?: FarmPluginDevHooks<TState>;\n /** Optional browser lifecycle for this logical plugin. */\n client?: FarmPluginClientConfig<TClientState, TClientPublic>;\n\n /** @deprecated Use `setup` instead. */\n init?: (context: FarmPluginContext) => void | Promise<void>;\n /** @deprecated Use `runtime.start` instead. */\n ready?: (context: FarmPluginContext) => void | Promise<void>;\n /** @deprecated Use `dev.server` instead. */\n devServerCreated?: (\n viteServer: ViteDevServer,\n context: FarmPluginContext,\n ) => void | Promise<void>;\n\n /** @deprecated Use `configure` instead. */\n config?: (config: FarmConfig, context: FarmPluginContext) => FarmConfig | Promise<FarmConfig>;\n configResolved?: (config: FarmConfig, context: FarmPluginContext) => void | Promise<void>;\n /** @deprecated Use `build.before` instead. */\n buildStart?: (context: FarmPluginContext) => void | Promise<void>;\n /** @deprecated Use `build.after` instead. */\n buildEnd?: (context: FarmPluginContext) => void | Promise<void>;\n\n /** @deprecated Use `router.discovered` instead. */\n routeDiscovered?: (\n route: RouteDiscoveredPayload,\n context: FarmPluginContext,\n ) => void | Promise<void>;\n /** @deprecated Use `router.generated` instead. */\n routesGenerated?: (\n routes: RoutesGeneratedPayload,\n context: FarmPluginContext,\n ) => void | Promise<void>;\n /** @deprecated Use `router.discovered` instead. */\n middlewareDiscovered?: (\n middleware: MiddlewareDiscoveredPayload,\n context: FarmPluginContext,\n ) => void | Promise<void>;\n /** @deprecated Use `router.discovered` instead. */\n apiRouteDiscovered?: (\n route: APIRouteDiscoveredPayload,\n context: FarmPluginContext,\n ) => void | Promise<void>;\n /** @deprecated Use `router.before` instead. */\n beforeRouteMatch?: (route: RouteMatchPayload, context: FarmPluginContext) => void | Promise<void>;\n /** @deprecated Use `router.after` instead. */\n afterRouteMatch?: (\n result: RouteMatchResultPayload,\n context: FarmPluginContext,\n ) => void | Promise<void>;\n /** @deprecated Use `render.before` instead. */\n beforeRender?: (\n render: RenderLifecyclePayload,\n context: FarmPluginContext,\n ) => void | Promise<void>;\n /** @deprecated Use `render.html` instead. */\n afterRender?: (\n html: string,\n render: RenderLifecyclePayload,\n context: FarmPluginContext,\n ) => string | Promise<string> | void | Promise<void>;\n /** @deprecated Use `runtime.before` instead. */\n beforeApiHandler?: (\n request: Request,\n api: APIHandlerLifecyclePayload,\n context: FarmRequestPluginContext,\n ) => Request | Promise<Request> | void | Promise<void>;\n /** @deprecated Use `runtime.after` instead. */\n afterApiHandler?: (\n response: Response,\n api: APIHandlerLifecyclePayload,\n context: FarmPluginContext,\n ) => Response | Promise<Response> | void | Promise<void>;\n onError?: (error: ErrorLifecyclePayload, context: FarmPluginContext) => void | Promise<void>;\n /** @deprecated Use `dev.update` instead. */\n hmrUpdate?: (update: HMRUpdatePayload, context: FarmPluginContext) => void | Promise<void>;\n /** @deprecated Use `build.before` instead. */\n beforeBundle?: (\n bundle: BundleLifecyclePayload,\n context: FarmPluginContext,\n ) => void | Promise<void>;\n /** @deprecated Use `build.after` instead. */\n afterBundle?: (result: BundleResultPayload, context: FarmPluginContext) => void | Promise<void>;\n /** @deprecated Use `build.configure` instead. */\n beforeNitroBuild?: (nitroConfig: any, context: FarmPluginContext) => any | Promise<any>;\n afterNitroBuild?: (\n payload: NitroBuildLifecyclePayload,\n context: FarmPluginContext,\n ) => void | Promise<void>;\n /** @deprecated Use `runtime.close` instead. */\n shutdown?: (payload: ShutdownPayload, context: FarmPluginContext) => void | Promise<void>;\n\n /** @deprecated Use the Web Request based `runtime.before` hook instead. */\n beforeRequest?: (\n req: FarmRequest,\n res: FarmResponse,\n context: FarmRequestPluginContext,\n ) => void | Promise<void>;\n /** @deprecated Use the Web Response based `runtime.after` hook instead. */\n afterResponse?: (\n req: FarmRequest,\n res: FarmResponse,\n context: FarmRequestPluginContext,\n ) => void | Promise<void>;\n\n // Transform hooks\n /** @deprecated Use `render.html` instead. */\n transformHTML?: (html: string, context: FarmPluginContext) => string | Promise<string>;\n /** @deprecated Use `render.before` or `render.html` instead. */\n transformPage?: (component: any, context: FarmPluginContext) => any | Promise<any>;\n}\n\nexport class PluginManager {\n private plugins: FarmPlugin[] = [];\n private hookPresence = new Map<keyof FarmPlugin, boolean>();\n private runtimeHookPresence = new Map<\"context\" | \"before\" | \"after\" | \"error\", boolean>();\n private context: FarmPluginContext;\n private pluginStates = new Map<FarmPlugin, unknown>();\n private setupComplete = false;\n private initialized = false;\n private runtimeReady = false;\n private runtimeClosed = false;\n private runtimeStartPromise?: Promise<void>;\n private runtimeClosePromise?: Promise<void>;\n private runtimeRequestContexts = new WeakMap<Request, Readonly<Record<string, unknown>>>();\n private failedRuntimeSessions = new WeakSet<FarmPluginRuntimeSession>();\n\n constructor(context: Omit<FarmPluginContext, \"requestContext\">) {\n this.context = {\n ...context,\n requestContext: {\n set(target, key, value, options) {\n setRequestContext(target as object, key, value, options);\n },\n get(target, key) {\n return getRequestContext(target as object, key);\n },\n has(target, key) {\n return hasRequestContext(target as object, key);\n },\n delete(target, key) {\n return deleteRequestContext(target as object, key);\n },\n clear(target) {\n clearRequestContext(target as object);\n },\n getAll(target, options) {\n return getRequestContextSnapshot(target as object, options);\n },\n },\n };\n }\n\n private createRequestHookContext(target: FarmRequest | Request): FarmRequestPluginContext {\n const requestContext = this.context.requestContext;\n\n return {\n ...this.context,\n req: {\n set(key, value, options) {\n requestContext.set(target, key, value, options);\n },\n get(key) {\n return requestContext.get(target, key);\n },\n has(key) {\n return requestContext.has(target, key);\n },\n delete(key) {\n return requestContext.delete(target, key);\n },\n clear() {\n requestContext.clear(target);\n },\n snapshot(options) {\n return requestContext.getAll(target, options);\n },\n },\n };\n }\n\n private copyRequestStore(source: FarmRequest | Request, target: FarmRequest | Request): void {\n const requestContext = this.context.requestContext;\n const values = requestContext.getAll(source);\n const exposed = requestContext.getAll(source, { exposedOnly: true });\n\n for (const [key, value] of values) {\n requestContext.set(target, key, value, {\n exposeToPage: exposed.has(key),\n });\n }\n }\n\n private copyRuntimeRequestContext(source: Request, target: Request): void {\n const runtimeContext = this.runtimeRequestContexts.get(source);\n if (runtimeContext) {\n this.runtimeRequestContexts.set(target, runtimeContext);\n }\n }\n\n private createRuntimeBaseEvent(\n plugin: FarmPlugin,\n request: Request,\n options: FarmPluginRuntimeRequestOptions,\n waitUntil: (promise: Promise<unknown>) => void,\n ): FarmPluginRuntimeBaseEvent {\n return {\n ...this.createStateHookContext(plugin),\n request,\n req: this.createRequestHookContext(request).req,\n kind: options.kind ?? \"request\",\n route: options.route,\n signal: request.signal,\n waitUntil,\n };\n }\n\n private async createRuntimeRequestContext(\n request: Request,\n options: FarmPluginRuntimeRequestOptions,\n waitUntil: (promise: Promise<unknown>) => void,\n ): Promise<Readonly<Record<string, unknown>>> {\n const values: Record<string, unknown> = {};\n const owners = new Map<string, string>();\n\n for (const plugin of this.getSortedPlugins()) {\n const createContext = plugin.runtime?.context;\n if (!createContext) continue;\n\n const result = await createContext(\n this.createRuntimeBaseEvent(plugin, request, options, waitUntil),\n );\n if (result === undefined) continue;\n if (!result || typeof result !== \"object\" || Array.isArray(result)) {\n throw new TypeError(`Farm plugin \"${plugin.name}\" runtime.context must return an object`);\n }\n\n for (const [key, value] of Object.entries(result)) {\n const owner = owners.get(key);\n if (owner) {\n throw new Error(\n `Farm plugin context key \"${key}\" from \"${plugin.name}\" conflicts with \"${owner}\"`,\n );\n }\n owners.set(key, plugin.name);\n values[key] = value;\n }\n }\n\n const runtimeContext = Object.freeze(values);\n this.runtimeRequestContexts.set(request, runtimeContext);\n return runtimeContext;\n }\n\n private async runRuntimeErrorHooks(\n request: Request,\n error: unknown,\n ctx: Readonly<Record<string, unknown>>,\n durationMs: number,\n options: FarmPluginRuntimeRequestOptions,\n waitUntil: (promise: Promise<unknown>) => void,\n ): Promise<void> {\n for (const plugin of this.getSortedPlugins()) {\n const onError = plugin.runtime?.error;\n if (!onError) continue;\n\n try {\n await onError({\n ...this.createRuntimeBaseEvent(plugin, request, options, waitUntil),\n ctx,\n error,\n durationMs,\n });\n } catch (hookError) {\n console.error(`Farm plugin \"${plugin.name}\" runtime.error failed:`, hookError);\n }\n }\n\n try {\n await this.runHookParallel(\"onError\", {\n phase: \"runtime\",\n error,\n meta: {\n kind: options.kind ?? \"request\",\n pathname: new URL(request.url).pathname,\n durationMs,\n },\n });\n } catch (hookError) {\n console.error(\"Farm plugin onError hook failed:\", hookError);\n }\n }\n\n private createStateHookContext(\n plugin: FarmPlugin,\n context: FarmPluginContext = this.context,\n ): FarmPluginStateContext {\n return {\n ...context,\n state: this.pluginStates.get(plugin),\n };\n }\n\n private getPluginHooks(\n plugin: FarmPlugin,\n hookName: keyof FarmPlugin,\n ): Array<(...args: any[]) => any> {\n const hooks: Array<(...args: any[]) => any> = [];\n const legacyHook = plugin[hookName];\n if (typeof legacyHook === \"function\") {\n hooks.push(legacyHook);\n }\n\n const withState = (context: FarmPluginContext) => this.createStateHookContext(plugin, context);\n\n switch (hookName) {\n case \"config\":\n if (plugin.configure) {\n hooks.push((config: FarmConfig, context: FarmPluginContext) =>\n plugin.configure?.(config, context),\n );\n }\n break;\n case \"ready\":\n if (plugin.runtime?.start) {\n hooks.push((context: FarmPluginContext) => plugin.runtime?.start?.(withState(context)));\n }\n break;\n case \"shutdown\":\n if (plugin.runtime?.close) {\n hooks.push((payload: ShutdownPayload, context: FarmPluginContext) =>\n plugin.runtime?.close?.({\n ...withState(context),\n reason: payload.reason,\n }),\n );\n }\n break;\n case \"routeDiscovered\":\n if (plugin.router?.discovered) {\n hooks.push((route: RouteDiscoveredPayload, context: FarmPluginContext) =>\n plugin.router?.discovered?.(route, withState(context)),\n );\n }\n break;\n case \"middlewareDiscovered\":\n if (plugin.router?.discovered) {\n hooks.push((route: MiddlewareDiscoveredPayload, context: FarmPluginContext) =>\n plugin.router?.discovered?.({ kind: \"middleware\", ...route }, withState(context)),\n );\n }\n break;\n case \"apiRouteDiscovered\":\n if (plugin.router?.discovered) {\n hooks.push((route: APIRouteDiscoveredPayload, context: FarmPluginContext) =>\n plugin.router?.discovered?.({ kind: \"api\", ...route }, withState(context)),\n );\n }\n break;\n case \"routesGenerated\":\n if (plugin.router?.generated) {\n hooks.push((routes: RoutesGeneratedPayload, context: FarmPluginContext) =>\n plugin.router?.generated?.(routes, withState(context)),\n );\n }\n break;\n case \"beforeRouteMatch\":\n if (plugin.router?.before) {\n hooks.push((route: RouteMatchPayload, context: FarmPluginContext) =>\n plugin.router?.before?.(route, withState(context)),\n );\n }\n break;\n case \"afterRouteMatch\":\n if (plugin.router?.after) {\n hooks.push((result: RouteMatchResultPayload, context: FarmPluginContext) =>\n plugin.router?.after?.(result, withState(context)),\n );\n }\n break;\n case \"beforeRender\":\n if (plugin.render?.before) {\n hooks.push((render: RenderLifecyclePayload, context: FarmPluginContext) =>\n plugin.render?.before?.(render, withState(context)),\n );\n }\n break;\n case \"afterRender\":\n if (plugin.render?.html) {\n hooks.push((html: string, render: RenderLifecyclePayload, context: FarmPluginContext) =>\n plugin.render?.html?.(html, render, withState(context)),\n );\n }\n break;\n case \"beforeBundle\":\n if (plugin.build?.before) {\n hooks.push((bundle: BundleLifecyclePayload, context: FarmPluginContext) =>\n plugin.build?.before?.(bundle, withState(context)),\n );\n }\n break;\n case \"beforeNitroBuild\":\n if (plugin.build?.configure) {\n hooks.push((buildConfig: any, context: FarmPluginContext) =>\n plugin.build?.configure?.(buildConfig, withState(context)),\n );\n }\n break;\n case \"afterBundle\":\n if (plugin.build?.after) {\n hooks.push((result: BundleResultPayload, context: FarmPluginContext) =>\n plugin.build?.after?.(result, withState(context)),\n );\n }\n break;\n case \"devServerCreated\":\n if (plugin.dev?.server) {\n hooks.push((server: ViteDevServer, context: FarmPluginContext) =>\n plugin.dev?.server?.(server, withState(context)),\n );\n }\n break;\n case \"hmrUpdate\":\n if (plugin.dev?.update) {\n hooks.push((update: HMRUpdatePayload, context: FarmPluginContext) =>\n plugin.dev?.update?.(update, withState(context)),\n );\n }\n break;\n }\n\n return hooks;\n }\n\n private getHookContext(hookName: keyof FarmPlugin, args: any[]): FarmPluginContext {\n if (\n hookName === \"beforeRequest\" ||\n hookName === \"afterResponse\" ||\n hookName === \"beforeApiHandler\"\n ) {\n const target = args[0];\n if (target && typeof target === \"object\") {\n return this.createRequestHookContext(target);\n }\n }\n\n return this.context;\n }\n\n addPlugin(plugin: FarmPlugin) {\n this.plugins.push(plugin);\n this.hookPresence.clear();\n this.runtimeHookPresence.clear();\n }\n\n addPlugins(plugins: FarmPlugin[]) {\n for (const plugin of plugins) {\n this.addPlugin(plugin);\n }\n }\n\n getPlugins(): FarmPlugin[] {\n return [...this.plugins];\n }\n\n getSortedPlugins(): FarmPlugin[] {\n const pre = this.plugins.filter((p) => p.enforce === \"pre\");\n const normal = this.plugins.filter((p) => !p.enforce);\n const post = this.plugins.filter((p) => p.enforce === \"post\");\n return [...pre, ...normal, ...post];\n }\n\n hasHook(hookName: keyof FarmPlugin): boolean {\n const cached = this.hookPresence.get(hookName);\n if (cached !== undefined) return cached;\n\n const present = this.plugins.some((plugin) => this.getPluginHooks(plugin, hookName).length > 0);\n this.hookPresence.set(hookName, present);\n return present;\n }\n\n hasRuntimeHook(hookName: \"context\" | \"before\" | \"after\" | \"error\"): boolean {\n const cached = this.runtimeHookPresence.get(hookName);\n if (cached !== undefined) return cached;\n\n const present = this.plugins.some((plugin) => typeof plugin.runtime?.[hookName] === \"function\");\n this.runtimeHookPresence.set(hookName, present);\n return present;\n }\n\n hasRuntimeRequestHooks(): boolean {\n return (\n this.hasRuntimeHook(\"context\") ||\n this.hasRuntimeHook(\"before\") ||\n this.hasRuntimeHook(\"after\") ||\n this.hasRuntimeHook(\"error\")\n );\n }\n\n copyRequestContext(source: FarmRequest | Request, target: FarmRequest | Request): void {\n this.copyRequestStore(source, target);\n if (source instanceof Request && target instanceof Request) {\n this.copyRuntimeRequestContext(source, target);\n }\n }\n\n async setupPlugins(): Promise<void> {\n if (this.setupComplete) return;\n\n for (const plugin of this.getSortedPlugins()) {\n if (!plugin.setup) continue;\n const state = await plugin.setup({\n ...this.context,\n env: getResolvedEnv(),\n });\n this.pluginStates.set(plugin, state);\n }\n\n this.setupComplete = true;\n }\n\n async startRuntime(): Promise<void> {\n if (this.runtimeReady) return;\n if (this.runtimeStartPromise) return this.runtimeStartPromise;\n\n this.runtimeStartPromise = (async () => {\n if (!this.initialized) {\n await this.runHookParallel(\"init\");\n }\n await this.setupPlugins();\n if (!this.runtimeReady) {\n await this.runHookParallel(\"ready\");\n }\n })();\n\n try {\n await this.runtimeStartPromise;\n } catch (error) {\n this.runtimeStartPromise = undefined;\n throw error;\n }\n }\n\n async closeRuntime(reason = \"runtime-closed\"): Promise<void> {\n if (this.runtimeClosed) return;\n if (this.runtimeClosePromise) return this.runtimeClosePromise;\n\n this.runtimeClosePromise = this.runHookParallel(\"shutdown\", {\n reason,\n }).then(() => undefined);\n try {\n await this.runtimeClosePromise;\n } catch (error) {\n this.runtimeClosePromise = undefined;\n throw error;\n }\n }\n\n async beginRuntimeRequest(\n request: Request,\n options: FarmPluginRuntimeRequestOptions = {},\n ): Promise<FarmPluginRuntimeSession> {\n await this.startRuntime();\n\n const startedAt = Date.now();\n const waitUntil = options.waitUntil\n ? (promise: Promise<unknown>) => options.waitUntil?.(Promise.resolve(promise))\n : (promise: Promise<unknown>) => {\n void Promise.resolve(promise).catch(() => {});\n };\n let activeRequest = request;\n let runtimeContext: Readonly<Record<string, unknown>> = Object.freeze({});\n\n try {\n runtimeContext = await this.createRuntimeRequestContext(activeRequest, options, waitUntil);\n\n let response: Response | undefined;\n for (const plugin of this.getSortedPlugins()) {\n const before = plugin.runtime?.before;\n if (!before) continue;\n\n const result = await before({\n ...this.createRuntimeBaseEvent(plugin, activeRequest, options, waitUntil),\n ctx: runtimeContext,\n });\n\n if (result instanceof Request) {\n this.copyRequestStore(activeRequest, result);\n this.copyRuntimeRequestContext(activeRequest, result);\n activeRequest = result;\n continue;\n }\n if (result instanceof Response) {\n response = result;\n break;\n }\n if (result !== undefined) {\n throw new TypeError(\n `Farm plugin \"${plugin.name}\" runtime.before must return a Request, Response, or undefined`,\n );\n }\n }\n\n return {\n request: activeRequest,\n response,\n ctx: runtimeContext,\n startedAt,\n options,\n waitUntil,\n };\n } catch (error) {\n await this.runRuntimeErrorHooks(\n activeRequest,\n error,\n runtimeContext,\n Date.now() - startedAt,\n options,\n waitUntil,\n );\n throw error;\n }\n }\n\n async endRuntimeRequest(\n session: FarmPluginRuntimeSession,\n initialResponse: Response,\n ): Promise<Response> {\n let response = initialResponse;\n\n try {\n for (const plugin of this.getSortedPlugins()) {\n const after = plugin.runtime?.after;\n if (!after) continue;\n\n const result = await after({\n ...this.createRuntimeBaseEvent(\n plugin,\n session.request,\n session.options,\n session.waitUntil,\n ),\n ctx: session.ctx,\n response,\n durationMs: Date.now() - session.startedAt,\n });\n if (result !== undefined) {\n if (!(result instanceof Response)) {\n throw new TypeError(\n `Farm plugin \"${plugin.name}\" runtime.after must return a Response or undefined`,\n );\n }\n response = result;\n }\n }\n\n return response;\n } catch (error) {\n await this.failRuntimeRequest(session, error);\n throw error;\n }\n }\n\n async failRuntimeRequest(session: FarmPluginRuntimeSession, error: unknown): Promise<void> {\n if (this.failedRuntimeSessions.has(session)) return;\n this.failedRuntimeSessions.add(session);\n await this.runRuntimeErrorHooks(\n session.request,\n error,\n session.ctx,\n Date.now() - session.startedAt,\n session.options,\n session.waitUntil,\n );\n }\n\n async runRuntimeRequest(\n request: Request,\n handler: FarmPluginRuntimeRequestHandler,\n options: FarmPluginRuntimeRequestOptions = {},\n ): Promise<Response> {\n const session = await this.beginRuntimeRequest(request, options);\n try {\n const response = session.response ?? (await handler(session.request));\n if (!(response instanceof Response)) {\n throw new TypeError(\"Farm plugin runtime handlers must return a Response\");\n }\n return await this.endRuntimeRequest(session, response);\n } catch (error) {\n await this.failRuntimeRequest(session, error);\n throw error;\n }\n }\n\n async runHook<K extends keyof FarmPlugin>(hookName: K, ...args: any[]): Promise<any> {\n const plugins = this.getSortedPlugins();\n\n for (const plugin of plugins) {\n for (const hook of this.getPluginHooks(plugin, hookName)) {\n const hookContext = this.getHookContext(hookName, args);\n const result = await (hook as any).apply(plugin, [...args, hookContext]);\n if (result !== undefined) {\n return result;\n }\n }\n }\n }\n\n async runHookSerial<K extends keyof FarmPlugin>(\n hookName: K,\n initialValue: any,\n ...args: any[]\n ): Promise<any> {\n const plugins = this.getSortedPlugins();\n let value = initialValue;\n\n for (const plugin of plugins) {\n for (const hook of this.getPluginHooks(plugin, hookName)) {\n const hookArgs = [value, ...args];\n const hookContext = this.getHookContext(hookName, hookArgs);\n const result = await (hook as any).apply(plugin, [...hookArgs, hookContext]);\n if (result !== undefined) {\n if (\n hookName === \"beforeApiHandler\" &&\n result !== value &&\n value &&\n result &&\n typeof value === \"object\" &&\n typeof result === \"object\"\n ) {\n this.copyRequestStore(value as FarmRequest | Request, result as FarmRequest | Request);\n }\n value = result;\n }\n }\n }\n\n return value;\n }\n\n async runHookParallel<K extends keyof FarmPlugin>(hookName: K, ...args: any[]): Promise<boolean> {\n const plugins = this.getSortedPlugins();\n\n // Run selected hooks sequentially for deterministic execution and short-circuiting.\n const sequentialHooks = new Set<keyof FarmPlugin>([\n \"ready\",\n \"shutdown\",\n \"beforeRequest\",\n \"afterResponse\",\n \"beforeApiHandler\",\n \"afterApiHandler\",\n \"beforeRouteMatch\",\n \"afterRouteMatch\",\n \"beforeRender\",\n \"afterRender\",\n ]);\n\n if (sequentialHooks.has(hookName)) {\n for (const plugin of plugins) {\n for (const hook of this.getPluginHooks(plugin, hookName)) {\n // Check if response is already sent (only for beforeRequest)\n if (hookName === \"beforeRequest\") {\n const res = args[1];\n if (res && res.writableEnded) {\n return true;\n }\n }\n\n const hookContext = this.getHookContext(hookName, args);\n await (hook as any).apply(plugin, [...args, hookContext]);\n\n // Check again after plugin execution (only for beforeRequest)\n if (hookName === \"beforeRequest\") {\n const res = args[1];\n if (res && res.writableEnded) {\n return true;\n }\n }\n }\n }\n } else {\n // Run other hooks in parallel\n const promises: Promise<any>[] = [];\n for (const plugin of plugins) {\n for (const hook of this.getPluginHooks(plugin, hookName)) {\n const hookContext = this.getHookContext(hookName, args);\n promises.push((hook as any).apply(plugin, [...args, hookContext]));\n }\n }\n await Promise.all(promises);\n }\n\n if (hookName === \"init\") this.initialized = true;\n if (hookName === \"ready\") this.runtimeReady = true;\n if (hookName === \"shutdown\") this.runtimeClosed = true;\n\n return false;\n }\n\n updateContext(updates: Partial<FarmPluginContext>) {\n this.context = {\n ...this.context,\n ...updates,\n requestContext: this.context.requestContext,\n };\n }\n}\n\nexport function definePlugin<\n TState = undefined,\n TRequestContext extends object = Record<string, never>,\n TClientState = unknown,\n TClientPublic = undefined,\n>(\n plugin: FarmPlugin<TState, TRequestContext, TClientState, TClientPublic>,\n): FarmPlugin<TState, TRequestContext, TClientState, TClientPublic> {\n return plugin;\n}\nexport { farmPlugin } from \"./vite\";\n","import type { FarmConfig } from \"./types\";\nimport type { FarmDocsResolvedConfig } from \"./docs/types\";\nimport type { FarmMarkdownResolvedConfig } from \"./markdown\";\nimport type { FarmMdxResolvedConfig } from \"./app-markdown\";\nimport { resolveMdxConfig } from \"./app-markdown\";\nimport { resolveMarkdownConfig } from \"./markdown\";\nimport { resolveWorkflowsConfig, type FarmWorkflowsResolvedConfig } from \"./workflows\";\nimport { resolveCronConfig, type FarmCronResolvedConfig } from \"./cron\";\nimport { resolveAppPath, fileExists, logger } from \"./utils\";\nimport { initStorage } from \"./storage\";\nimport { configureFarmObservability } from \"./observability\";\nimport { normalizeRouteRules } from \"./route-rules\";\nimport { resolveServerActionsConfig } from \"./server-action-security\";\nimport { resolveFarmImageConfig, type ResolvedFarmImageConfig } from \"./image-config\";\nimport { getFarmAppDirectories, getFarmSourceRoots } from \"./layers\";\nimport { RouteManager } from \"./routing/route-manager\";\nimport { ServerRenderer } from \"./server/renderer\";\nimport { findProgrammaticRouteFiles } from \"./routes.server\";\nimport path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport {\n resolveFarmDevtoolsConfig,\n type ResolvedFarmDevtoolsConfig,\n} from \"./devtools-config\";\nimport { resolveFarmI18nConfig } from \"./i18n/config\";\nimport {\n createFarmI18nRuntime,\n _setDefaultFarmI18nRuntime,\n type FarmI18nRuntime,\n} from \"./i18n/server\";\nimport type { ResolvedFarmI18nConfig } from \"./i18n/types\";\n\ntype NormalizedFarmConfig = Omit<Required<FarmConfig>, \"devtools\" | \"images\" | \"i18n\"> & {\n docs: FarmDocsResolvedConfig;\n md: FarmMarkdownResolvedConfig;\n mdx: FarmMdxResolvedConfig;\n cron: FarmCronResolvedConfig;\n workflows: FarmWorkflowsResolvedConfig;\n devtools: ResolvedFarmDevtoolsConfig;\n images: ResolvedFarmImageConfig;\n i18n: ResolvedFarmI18nConfig;\n};\n\nconst defaultDocsConfig: FarmDocsResolvedConfig = {\n enabled: false,\n entry: \"/docs\",\n config: { entry: \"docs\", docsPath: \"/docs\" },\n};\n\nfunction isResolvedDocsConfig(value: FarmConfig[\"docs\"]): value is FarmDocsResolvedConfig {\n return (\n !!value &&\n typeof value === \"object\" &&\n \"enabled\" in value &&\n \"entry\" in value &&\n \"config\" in value\n );\n}\n\nexport class FarmApp {\n private config: NormalizedFarmConfig;\n private routeManager: RouteManager;\n private serverRenderer: ServerRenderer;\n private i18nRuntime: FarmI18nRuntime;\n private viteServer?: ViteDevServer;\n\n constructor(config: FarmConfig = {}, viteServer?: ViteDevServer) {\n this.config = this.normalizeConfig(config);\n configureFarmObservability(this.config.observability);\n this.i18nRuntime = createFarmI18nRuntime(this.config.i18n);\n _setDefaultFarmI18nRuntime(this.i18nRuntime);\n this.viteServer = viteServer;\n this.routeManager = new RouteManager(this.config, viteServer);\n this.serverRenderer = new ServerRenderer(\n this.config,\n this.routeManager,\n this.i18nRuntime,\n );\n }\n\n async initialize(): Promise<void> {\n // Silent initialization unless verbose mode\n if (process.env.FARM_VERBOSE) {\n logger.info(\"Initializing Farm.js application...\");\n }\n\n await initStorage(this.config.storage);\n await this.i18nRuntime.initialize();\n\n // Verify app directory structure\n await this.verifyAppStructure();\n\n // Discover and register routes\n await this.routeManager.discoverRoutes();\n\n if (process.env.FARM_VERBOSE) {\n logger.success(\"Farm.js application initialized successfully!\");\n }\n }\n\n getRouteManager(): RouteManager {\n return this.routeManager;\n }\n\n getServerRenderer(): ServerRenderer {\n return this.serverRenderer;\n }\n\n getI18nRuntime(): FarmI18nRuntime {\n return this.i18nRuntime;\n }\n\n getConfig(): NormalizedFarmConfig {\n return this.config;\n }\n\n private normalizeConfig(config: FarmConfig): NormalizedFarmConfig {\n const root = config.root || process.cwd();\n\n return {\n root,\n srcDir: config.srcDir || \"src\",\n extends: config.extends || [],\n layers: [...(config.layers || [])],\n outDir: config.outDir || \"dist\",\n basePath: config.basePath || \"/\",\n preset: config.preset ?? \"node-server\",\n deploy: config.deploy || {},\n storage: config.storage || {},\n integrations: config.integrations || {},\n plugins: config.plugins || [],\n migrations: config.migrations || { commands: [] },\n cron: resolveCronConfig(config.cron),\n workflows: resolveWorkflowsConfig(config.workflows),\n middleware: config.middleware || {},\n routeRules: normalizeRouteRules(config.routeRules),\n context: config.context || (() => undefined),\n serverActions: resolveServerActionsConfig(config.serverActions),\n images: resolveFarmImageConfig(config.images),\n i18n: isResolvedI18nConfig(config.i18n)\n ? config.i18n\n : resolveFarmI18nConfig(config.i18n, {\n root,\n mode: process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n }),\n deploymentId: config.deploymentId || \"development\",\n docs: isResolvedDocsConfig(config.docs) ? config.docs : defaultDocsConfig,\n md: resolveMarkdownConfig(config.md),\n mdx: resolveMdxConfig(config.mdx),\n observability: config.observability ?? false,\n devtools: resolveFarmDevtoolsConfig(\n config.devtools,\n process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n ),\n env: config.env || { server: {}, public: {} },\n suppressLintOnLink: config.suppressLintOnLink ?? false,\n experimental: {\n serverComponents: config.experimental?.serverComponents ?? false,\n serverActions: config.experimental?.serverActions ?? false,\n ...config.experimental,\n },\n vite: config.vite || {},\n };\n }\n\n private async verifyAppStructure(): Promise<void> {\n const appDirs = getFarmAppDirectories(this.config);\n\n const hasAppDirectory = (await Promise.all(appDirs.map((appDir) => fileExists(appDir)))).some(\n Boolean,\n );\n\n if (!hasAppDirectory) {\n const routeFiles = getFarmSourceRoots(this.config).flatMap((source) =>\n findProgrammaticRouteFiles(source.root, source.srcDir),\n );\n if (routeFiles.length > 0) {\n return;\n }\n\n const appDir = resolveAppPath(this.config.root, this.config.srcDir, \"app\");\n throw new Error(\n `App directory not found at ${appDir}. ` +\n \"Please create a src/app directory or extend a Farm layer containing routes.\",\n );\n }\n\n const rootLayoutPaths = appDirs.flatMap((appDir) => [\n path.join(appDir, \"layout.tsx\"),\n path.join(appDir, \"layout.ts\"),\n path.join(appDir, \"layout.jsx\"),\n path.join(appDir, \"layout.js\"),\n ]);\n\n const hasRootLayout = await Promise.all(rootLayoutPaths.map((p) => fileExists(p))).then(\n (results) => results.some(Boolean),\n );\n\n if (!hasRootLayout) {\n logger.warn(\n \"No root layout found. Consider creating src/app/layout.tsx for consistent page structure.\",\n );\n }\n }\n}\n\nfunction isResolvedI18nConfig(value: FarmConfig[\"i18n\"]): value is ResolvedFarmI18nConfig {\n return Boolean(value && typeof value === \"object\" && \"enabled\" in value);\n}\n\nexport function createFarmApp(config?: FarmConfig, viteServer?: ViteDevServer): FarmApp {\n return new FarmApp(config, viteServer);\n}\n","import type { RouteSegment, ParsedRoute } from \"./types\";\nimport path from \"path\";\n\nexport function parseRoutePath(filePath: string): ParsedRoute {\n const segments: RouteSegment[] = [];\n const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n const pathParts = normalizedPath.split(\"/\").filter(Boolean);\n\n const fileName = pathParts.pop() || \"\";\n const fileType = getRouteType(fileName);\n\n for (const part of pathParts) {\n if (part.startsWith(\"[\") && part.endsWith(\"]\")) {\n let segment = part.slice(1, -1);\n const isDynamic = true;\n let isOptional = false;\n let isCatchAll = false;\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n isOptional = true;\n segment = segment.slice(1, -1);\n if (segment.startsWith(\"...\")) {\n segment = segment.slice(3);\n isCatchAll = true;\n }\n } else if (segment.startsWith(\"...\")) {\n segment = segment.slice(3);\n isCatchAll = true;\n }\n\n segments.push({ segment, isDynamic, isOptional, isCatchAll });\n } else {\n segments.push({\n segment: part,\n isDynamic: false,\n isOptional: false,\n isCatchAll: false,\n });\n }\n }\n\n return {\n segments,\n filePath: normalizedPath,\n type: fileType,\n };\n}\n\nfunction getRouteType(fileName: string): ParsedRoute[\"type\"] {\n const baseName = fileName.replace(/\\.(tsx?|jsx?|mdx?|markdown)$/, \"\");\n\n switch (baseName) {\n case \"page\":\n return \"page\";\n case \"layout\":\n return \"layout\";\n case \"loading\":\n return \"loading\";\n case \"error\":\n return \"error\";\n case \"not-found\":\n return \"not-found\";\n default:\n return \"page\";\n }\n}\n\nexport function segmentsToPattern(segments: RouteSegment[]): string {\n if (segments.length === 0) return \"/\";\n\n return (\n \"/\" +\n segments\n .map((segment) => {\n if (!segment.isDynamic) return segment.segment;\n\n if (segment.isCatchAll) {\n return segment.isOptional ? `*${segment.segment}?` : `*${segment.segment}`;\n }\n\n return `:${segment.segment}`;\n })\n .join(\"/\")\n );\n}\n\nexport function matchRoute(\n url: string,\n segments: RouteSegment[],\n): { params: Record<string, string>; matches: boolean } {\n const urlParts = url.split(\"/\").filter(Boolean);\n const params: Record<string, string> = {};\n if (segments.length === 0) {\n return { params, matches: urlParts.length === 0 };\n }\n\n let urlIndex = 0;\n let segmentIndex = 0;\n\n while (segmentIndex < segments.length && urlIndex <= urlParts.length) {\n const segment = segments[segmentIndex];\n\n if (!segment.isDynamic) {\n if (urlParts[urlIndex] !== segment.segment) {\n return { params: {}, matches: false };\n }\n urlIndex++;\n segmentIndex++;\n } else if (segment.isCatchAll) {\n const remainingParts = urlParts.slice(urlIndex);\n\n if (remainingParts.length === 0 && !segment.isOptional) {\n return { params: {}, matches: false };\n }\n\n params[segment.segment] = remainingParts.join(\"/\");\n urlIndex = urlParts.length;\n segmentIndex++;\n } else {\n if (urlIndex >= urlParts.length) {\n return { params: {}, matches: false };\n }\n\n params[segment.segment] = urlParts[urlIndex];\n urlIndex++;\n segmentIndex++;\n }\n }\n\n const matches = segmentIndex === segments.length && urlIndex === urlParts.length;\n\n return { params, matches };\n}\n\nexport function resolveAppPath(root: string, ...paths: string[]): string {\n return path.resolve(root, ...paths);\n}\n\nexport function toViteModuleId(filePath: string, root: string): string {\n if (!path.isAbsolute(filePath)) return filePath;\n\n const relativePath = path.relative(root, filePath);\n if (relativePath && !relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath)) {\n return `/${relativePath.split(path.sep).join(\"/\")}`;\n }\n\n const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n return normalizedPath.startsWith(\"/\") ? `/@fs${normalizedPath}` : `/@fs/${normalizedPath}`;\n}\n\nexport async function fileExists(filePath: string): Promise<boolean> {\n try {\n const fs = await import(\"fs/promises\");\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function globFiles(pattern: string, cwd: string): Promise<string[]> {\n const glob = await import(\"fast-glob\");\n return glob.default(pattern, { cwd, absolute: false });\n}\n\nexport function parseSearchParams(\n searchParams: URLSearchParams,\n): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = {};\n\n for (const [key, value] of searchParams.entries()) {\n if (key in result) {\n const existing = result[key];\n if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n result[key] = [existing, value];\n }\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\nexport const logger = {\n info: (message: string) => console.log(`[info] ${message}`),\n success: (message: string) => console.log(`[success] ${message}`),\n warn: (message: string) => console.warn(`⚠️ ${message}`),\n error: (message: string) => console.error(`❌ ${message}`),\n ready: (message: string) => console.log(`${message}`),\n event: (message: string) => console.log(` ${message}`),\n};\n","export type FarmEventLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface FarmEventBase {\n type: string;\n timestamp: number;\n level: FarmEventLevel;\n requestId?: string;\n route?: string;\n pathname?: string;\n}\n\nexport type FarmServerEvent =\n | (FarmEventBase & {\n type: \"server.start\";\n mode: \"dev\" | \"preview\" | \"production\";\n port?: number;\n })\n | (FarmEventBase & { type: \"server.ready\"; url?: string })\n | (FarmEventBase & { type: \"server.shutdown\"; reason?: string });\n\nexport type FarmRouteEvent =\n | (FarmEventBase & { type: \"route.discovered\"; route: string; filePath: string })\n | (FarmEventBase & {\n type: \"route.matched\";\n pathname: string;\n route: string;\n params?: Record<string, string>;\n })\n | (FarmEventBase & { type: \"route.notFound\"; pathname: string })\n | (FarmEventBase & { type: \"route.redirect\"; from: string; to: string; status?: number })\n | (FarmEventBase & { type: \"route.rewrite\"; from: string; to: string });\n\nexport type FarmRenderEvent =\n | (FarmEventBase & { type: \"render.start\"; route: string; pathname?: string })\n | (FarmEventBase & {\n type: \"render.complete\";\n route: string;\n durationMs: number;\n status?: number;\n })\n | (FarmEventBase & { type: \"render.error\"; route?: string; error: unknown })\n | (FarmEventBase & { type: \"render.stream.start\"; route: string })\n | (FarmEventBase & { type: \"render.stream.shellReady\"; route: string; durationMs: number })\n | (FarmEventBase & { type: \"render.stream.complete\"; route: string; durationMs: number });\n\nexport type FarmCacheEvent =\n | (FarmEventBase & {\n type: \"cache.hit\";\n key: string;\n route?: string;\n tags?: readonly string[];\n revalidate?: number | false;\n stale?: boolean;\n })\n | (FarmEventBase & { type: \"cache.miss\"; key: string; route?: string; reason?: string })\n | (FarmEventBase & {\n type: \"cache.set\";\n key: string;\n route?: string;\n tags?: readonly string[];\n revalidate?: number | false;\n })\n | (FarmEventBase & { type: \"cache.dedupe\"; key: string })\n | (FarmEventBase & { type: \"cache.bypass\"; key?: string; route?: string; reason: string })\n | (FarmEventBase & {\n type: \"cache.stale\";\n key: string;\n route?: string;\n tags?: readonly string[];\n revalidate?: number | false;\n })\n | (FarmEventBase & { type: \"cache.revalidatePath\"; path: string; count: number })\n | (FarmEventBase & {\n type: \"cache.revalidateTag\";\n tag: string;\n profile?: unknown;\n count: number;\n })\n | (FarmEventBase & { type: \"cache.updateTag\"; tag: string; count: number })\n | (FarmEventBase & {\n type: \"cache.invalidated\";\n key?: string;\n route?: string;\n tag?: string;\n reason?: string;\n count?: number;\n })\n | (FarmEventBase & { type: \"cache.delete\"; key: string; deleted: boolean })\n | (FarmEventBase & { type: \"cache.clear\"; count: number })\n | (FarmEventBase & {\n type: \"cache.error\";\n key?: string;\n operation: \"get\" | \"set\" | \"delete\" | \"revalidate\";\n error: unknown;\n });\n\nexport type FarmPPREvent =\n | (FarmEventBase & { type: \"ppr.shell.hit\"; route: string; key: string })\n | (FarmEventBase & { type: \"ppr.shell.miss\"; route: string; key: string })\n | (FarmEventBase & {\n type: \"ppr.shell.cached\";\n route: string;\n key: string;\n revalidate?: number;\n })\n | (FarmEventBase & { type: \"ppr.shell.bypass\"; route: string; reason: string })\n | (FarmEventBase & {\n type: \"ppr.shell.invalidated\";\n route: string;\n reason?: string;\n count?: number;\n })\n | (FarmEventBase & { type: \"ppr.suspense.holeDetected\"; route: string })\n | (FarmEventBase & { type: \"ppr.refresh.start\"; route: string })\n | (FarmEventBase & { type: \"ppr.refresh.complete\"; route: string; durationMs: number })\n | (FarmEventBase & { type: \"ppr.refresh.error\"; route: string; error: unknown });\n\nexport type FarmAPIEvent =\n | (FarmEventBase & { type: \"api.request.start\"; route: string; method: string })\n | (FarmEventBase & {\n type: \"api.request.complete\";\n route: string;\n method: string;\n status: number;\n durationMs: number;\n })\n | (FarmEventBase & {\n type: \"api.validation.failed\";\n route: string;\n method: string;\n issues?: unknown;\n })\n | (FarmEventBase & { type: \"api.error\"; route: string; method: string; error: unknown });\n\nexport type FarmIntegrationEvent =\n | (FarmEventBase & { type: \"integration.registered\"; name: string })\n | (FarmEventBase & { type: \"integration.config.validated\"; name: string })\n | (FarmEventBase & { type: \"integration.ready\"; name: string })\n | (FarmEventBase & { type: \"integration.disposed\"; name: string })\n | (FarmEventBase & {\n type: \"integration.api.call.start\";\n integration: string;\n operation: string;\n })\n | (FarmEventBase & {\n type: \"integration.api.call.complete\";\n integration: string;\n operation: string;\n durationMs: number;\n })\n | (FarmEventBase & {\n type: \"integration.api.call.error\";\n integration: string;\n operation: string;\n error: unknown;\n })\n | (FarmEventBase & { type: \"integration.webhook.received\"; integration: string; event?: string })\n | (FarmEventBase & { type: \"integration.webhook.verified\"; integration: string; event?: string })\n | (FarmEventBase & { type: \"integration.webhook.failed\"; integration: string; reason: string });\n\nexport type FarmMiddlewareEvent =\n | (FarmEventBase & { type: \"middleware.start\"; route?: string; name?: string })\n | (FarmEventBase & {\n type: \"middleware.complete\";\n route?: string;\n name?: string;\n durationMs: number;\n })\n | (FarmEventBase & {\n type: \"middleware.shortCircuit\";\n route?: string;\n name?: string;\n status?: number;\n })\n | (FarmEventBase & { type: \"middleware.error\"; route?: string; name?: string; error: unknown });\n\nexport type FarmStorageEvent =\n | (FarmEventBase & { type: \"storage.query.start\"; integration?: string; operation: string })\n | (FarmEventBase & {\n type: \"storage.query.complete\";\n integration?: string;\n operation: string;\n durationMs: number;\n })\n | (FarmEventBase & {\n type: \"storage.query.error\";\n integration?: string;\n operation: string;\n error: unknown;\n })\n | (FarmEventBase & { type: \"storage.schema.ready\"; integration?: string })\n | (FarmEventBase & { type: \"storage.schema.error\"; integration?: string; error: unknown });\n\nexport type FarmBuildEvent =\n | (FarmEventBase & { type: \"build.start\"; target?: string })\n | (FarmEventBase & { type: \"build.complete\"; target?: string; durationMs: number })\n | (FarmEventBase & { type: \"build.error\"; target?: string; error: unknown })\n | (FarmEventBase & { type: \"routes.generated\"; pageCount: number; apiCount?: number })\n | (FarmEventBase & { type: \"types.generated\"; filePath: string })\n | (FarmEventBase & { type: \"manifest.generated\"; routeCount: number });\n\nexport type FarmPluginEvent =\n | (FarmEventBase & { type: \"plugin.hook.start\"; plugin: string; hook: string })\n | (FarmEventBase & {\n type: \"plugin.hook.complete\";\n plugin: string;\n hook: string;\n durationMs: number;\n })\n | (FarmEventBase & { type: \"plugin.hook.error\"; plugin: string; hook: string; error: unknown });\n\nexport type FarmErrorEvent = FarmEventBase & {\n type: \"error\";\n source: string;\n error: unknown;\n route?: string;\n};\n\nexport type FarmEvent =\n | FarmServerEvent\n | FarmRouteEvent\n | FarmRenderEvent\n | FarmCacheEvent\n | FarmPPREvent\n | FarmAPIEvent\n | FarmIntegrationEvent\n | FarmMiddlewareEvent\n | FarmStorageEvent\n | FarmBuildEvent\n | FarmPluginEvent\n | FarmErrorEvent;\n\nexport type FarmEventType = FarmEvent[\"type\"];\nexport type FarmEventHandler = (event: FarmEvent) => void | Promise<void>;\n\nexport type FarmEventInput = FarmEvent extends infer T\n ? T extends FarmEvent\n ? Omit<T, \"timestamp\" | \"level\"> & Partial<Pick<T, \"timestamp\" | \"level\">>\n : never\n : never;\n\nexport type FarmObservabilityUserConfig =\n | boolean\n | {\n logs?: boolean;\n onEvent?: FarmEventHandler | readonly FarmEventHandler[];\n events?: readonly FarmEventType[];\n };\n\nexport interface FarmResolvedObservabilityConfig {\n logs: boolean;\n handlers: FarmEventHandler[];\n events?: Set<FarmEventType>;\n}\n\nconst runtimeHandlers = new Set<FarmEventHandler>();\nlet observabilityState: FarmResolvedObservabilityConfig = {\n logs: false,\n handlers: [],\n};\n\nexport function configureFarmObservability(config: FarmObservabilityUserConfig | undefined): void {\n observabilityState = normalizeFarmObservabilityConfig(config);\n}\n\nexport function normalizeFarmObservabilityConfig(\n config: FarmObservabilityUserConfig | undefined,\n): FarmResolvedObservabilityConfig {\n if (config === undefined || config === false) {\n return { logs: false, handlers: [] };\n }\n\n if (config === true) {\n return { logs: true, handlers: [] };\n }\n\n const handlers = config.onEvent\n ? Array.isArray(config.onEvent)\n ? [...config.onEvent]\n : [config.onEvent]\n : [];\n\n return {\n logs: config.logs ?? false,\n handlers,\n events: config.events ? new Set(config.events) : undefined,\n };\n}\n\nexport function onFarmEvent(handler: FarmEventHandler): () => void {\n runtimeHandlers.add(handler);\n return () => {\n runtimeHandlers.delete(handler);\n };\n}\n\nexport function resetFarmObservability(): void {\n runtimeHandlers.clear();\n observabilityState = {\n logs: false,\n handlers: [],\n };\n}\n\nexport function emitFarmEvent(input: FarmEventInput): FarmEvent {\n const event = {\n timestamp: Date.now(),\n level: inferFarmEventLevel(input.type),\n ...input,\n } as FarmEvent;\n\n if (!shouldEmitFarmEvent(event)) {\n return event;\n }\n\n if (observabilityState.logs) {\n logFarmEvent(event);\n }\n\n for (const handler of [...observabilityState.handlers, ...runtimeHandlers]) {\n try {\n Promise.resolve(handler(event)).catch((error) => {\n console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);\n });\n } catch (error) {\n console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);\n }\n }\n\n return event;\n}\n\nfunction shouldEmitFarmEvent(event: FarmEvent): boolean {\n if (\n !observabilityState.logs &&\n observabilityState.handlers.length === 0 &&\n runtimeHandlers.size === 0\n ) {\n return false;\n }\n\n if (observabilityState.events && !observabilityState.events.has(event.type)) {\n return false;\n }\n\n return true;\n}\n\nfunction inferFarmEventLevel(type: FarmEventType): FarmEventLevel {\n if (type === \"error\" || type.endsWith(\".error\") || type.endsWith(\".failed\")) {\n return \"error\";\n }\n if (\n type.endsWith(\".bypass\") ||\n type.endsWith(\".invalidated\") ||\n type.endsWith(\".stale\") ||\n type.endsWith(\".notFound\")\n ) {\n return \"warn\";\n }\n if (\n type.endsWith(\".hit\") ||\n type.endsWith(\".miss\") ||\n type.endsWith(\".start\") ||\n type.endsWith(\".shellReady\")\n ) {\n return \"debug\";\n }\n return \"info\";\n}\n\nfunction logFarmEvent(event: FarmEvent): void {\n const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;\n switch (event.level) {\n case \"error\":\n console.error(message);\n break;\n case \"warn\":\n console.warn(message);\n break;\n default:\n console.log(message);\n break;\n }\n}\n\nfunction formatFarmEventDetails(event: FarmEvent): string {\n const details: string[] = [];\n const record = event as unknown as Record<string, unknown>;\n\n for (const key of [\n \"route\",\n \"pathname\",\n \"method\",\n \"status\",\n \"key\",\n \"tag\",\n \"path\",\n \"reason\",\n \"durationMs\",\n \"integration\",\n \"operation\",\n \"plugin\",\n \"hook\",\n \"target\",\n \"count\",\n ]) {\n const value = record[key];\n if (value !== undefined) {\n details.push(`${key}=${formatDetailValue(value)}`);\n }\n }\n\n return details.length > 0 ? ` ${details.join(\" \")}` : \"\";\n}\n\nfunction formatDetailValue(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","/**\n * Farm.js SSG (Static Site Generation) Module\n *\n * Handles collection and pre-rendering of SSG pages at build time.\n *\n * SSR is the default - pages render on each request\n * SSG is opt-in via `export const ssg = true`, Next-compatible route\n * config exports, or a top-of-file rendering directive.\n *\n * @example\n * ```tsx\n * // SSG Page\n * export const ssg = true;\n * export default function AboutPage() {\n * return <h1>About</h1>;\n * }\n *\n * // SSG with ISR\n * export const ssg = true;\n * export const revalidate = 60;\n * export default async function ProductsPage() {\n * const products = await fetchProducts();\n * return <ProductList products={products} />;\n * }\n *\n * // Dynamic SSG\n * export const ssg = true;\n * export async function getStaticPaths() {\n * const posts = await fetchPosts();\n * return posts.map(post => ({ slug: post.slug }));\n * }\n * export default async function BlogPost({ params }) {\n * return <article>{params.slug}</article>;\n * }\n *\n * // Next-compatible route config\n * export const dynamic = \"force-static\";\n * export const revalidate = 60;\n *\n * // PPR/static-shell route\n * export const experimental_ppr = true;\n * export const revalidate = 60;\n *\n * // Directive config\n * \"use ssg; 60\";\n * export default function DocsPage() {\n * return <h1>Docs</h1>;\n * }\n * ```\n */\n\nimport { readFile } from \"fs/promises\";\nimport type {\n RouteModule,\n SSGPage,\n SSGCollectionResult,\n StaticPathParams,\n StaticPathPrimitive,\n} from \"./types\";\n\ninterface RouteEntry {\n path: string;\n filePath: string;\n isDynamic: boolean;\n pattern: string;\n}\n\nexport type RouteRenderingDynamic = NonNullable<RouteModule[\"dynamic\"]>;\n\nexport interface RouteRenderingConfig {\n ssg: boolean;\n ppr: boolean;\n revalidate?: number;\n dynamic?: RouteRenderingDynamic;\n directive?: string;\n}\n\ninterface DirectiveRenderingConfig {\n ssg: boolean;\n ppr: boolean;\n revalidate?: number;\n dynamic?: RouteRenderingDynamic;\n directive: string;\n}\n\nconst OPTIONAL_CATCH_ALL_SEGMENT = /^\\[\\[\\.\\.\\.([^\\]]+)\\]\\]$/;\nconst REQUIRED_CATCH_ALL_SEGMENT = /^\\[\\.\\.\\.([^\\]]+)\\]$/;\nconst REQUIRED_DYNAMIC_SEGMENT = /^\\[([^\\]]+)\\]$/;\n\n/**\n * Resolve route rendering from Farm exports, Next-compatible exports, and\n * top-of-file directives such as `\"use ssg\";` or `\"use ssg; 60\";`.\n */\nexport function resolveRouteRenderingConfig(\n mod: RouteModule | null | undefined,\n source?: string,\n): RouteRenderingConfig {\n const directiveConfig = parseRouteRenderingDirective(source);\n let ssg = directiveConfig?.ssg ?? false;\n let ppr = directiveConfig?.ppr ?? false;\n let revalidate = directiveConfig?.revalidate;\n const moduleDynamic = normalizeDynamicMode(mod?.dynamic);\n const dynamic = moduleDynamic ?? directiveConfig?.dynamic;\n const hasExplicitSsg = typeof mod?.ssg === \"boolean\";\n const hasExplicitPPR =\n typeof mod?.ppr === \"boolean\" || typeof mod?.experimental_ppr === \"boolean\";\n\n if (hasExplicitSsg) {\n ssg = mod!.ssg === true;\n }\n\n if (hasExplicitPPR) {\n ppr = mod?.ppr === true || mod?.experimental_ppr === true;\n }\n\n if (typeof mod?.revalidate === \"number\") {\n if (mod.revalidate > 0) {\n revalidate = mod.revalidate;\n if (!hasExplicitSsg && !ppr) {\n ssg = true;\n }\n } else {\n revalidate = undefined;\n if (!hasExplicitSsg) {\n ssg = false;\n }\n }\n } else if (mod?.revalidate === false) {\n revalidate = undefined;\n }\n\n if (moduleDynamic === \"force-static\" || moduleDynamic === \"error\") {\n ssg = true;\n ppr = false;\n } else if (moduleDynamic === \"force-dynamic\") {\n ssg = false;\n ppr = false;\n revalidate = undefined;\n }\n\n return {\n ssg,\n ppr: ssg ? false : ppr,\n revalidate: ssg || ppr ? revalidate : undefined,\n dynamic,\n directive: directiveConfig?.directive,\n };\n}\n\nexport async function resolveRouteRenderingConfigFromFile(\n mod: RouteModule | null | undefined,\n filePath: string,\n): Promise<RouteRenderingConfig> {\n const source = await readFile(filePath, \"utf8\").catch(() => undefined);\n return resolveRouteRenderingConfig(mod, source);\n}\n\nexport function parseRouteRenderingDirective(\n source: string | undefined,\n): DirectiveRenderingConfig | undefined {\n if (!source) {\n return undefined;\n }\n\n for (const directive of readDirectivePrologue(source)) {\n const config = parseKnownRenderingDirective(directive);\n if (config) {\n return config;\n }\n }\n\n return undefined;\n}\n\nfunction parseKnownRenderingDirective(directive: string): DirectiveRenderingConfig | undefined {\n const normalized = directive.trim().toLowerCase();\n const match = normalized.match(\n /^use\\s+(ssg|static|isr|ssr|dynamic|ppr)(?:\\s*[;:]\\s*(\\d+))?\\s*;?$/,\n );\n\n if (!match?.[1]) {\n return undefined;\n }\n\n const mode = match[1];\n const revalidate = match[2] ? Number(match[2]) : undefined;\n\n if (mode === \"ssr\" || mode === \"dynamic\") {\n return {\n ssg: false,\n ppr: false,\n dynamic: \"force-dynamic\",\n directive,\n };\n }\n\n if (mode === \"ppr\") {\n return {\n ssg: false,\n ppr: true,\n revalidate: typeof revalidate === \"number\" && revalidate > 0 ? revalidate : undefined,\n directive,\n };\n }\n\n return {\n ssg: true,\n ppr: false,\n dynamic: \"force-static\",\n revalidate: typeof revalidate === \"number\" && revalidate > 0 ? revalidate : undefined,\n directive,\n };\n}\n\nfunction normalizeDynamicMode(value: unknown): RouteRenderingDynamic | undefined {\n switch (value) {\n case \"auto\":\n case \"force-static\":\n case \"force-dynamic\":\n case \"error\":\n return value;\n default:\n return undefined;\n }\n}\n\nfunction readDirectivePrologue(source: string): string[] {\n const directives: string[] = [];\n let index = skipTrivia(source, 0);\n\n while (index < source.length) {\n const parsed = readStringStatement(source, index);\n if (!parsed) {\n break;\n }\n\n directives.push(parsed.value);\n index = skipTrivia(source, parsed.end);\n }\n\n return directives;\n}\n\nfunction skipTrivia(source: string, start: number): number {\n let index = start;\n\n while (index < source.length) {\n const char = source[index];\n\n if (char && /\\s/.test(char)) {\n index += 1;\n continue;\n }\n\n if (source.startsWith(\"//\", index)) {\n const nextLine = source.indexOf(\"\\n\", index + 2);\n index = nextLine === -1 ? source.length : nextLine + 1;\n continue;\n }\n\n if (source.startsWith(\"/*\", index)) {\n const end = source.indexOf(\"*/\", index + 2);\n index = end === -1 ? source.length : end + 2;\n continue;\n }\n\n break;\n }\n\n return index;\n}\n\nfunction readStringStatement(\n source: string,\n start: number,\n): { value: string; end: number } | undefined {\n const quote = source[start];\n if (quote !== '\"' && quote !== \"'\") {\n return undefined;\n }\n\n let value = \"\";\n let index = start + 1;\n\n while (index < source.length) {\n const char = source[index];\n if (char === \"\\\\\") {\n value += source.slice(index, index + 2);\n index += 2;\n continue;\n }\n\n if (char === quote) {\n index += 1;\n const semicolonIndex = skipHorizontalWhitespace(source, index);\n const end = source[semicolonIndex] === \";\" ? semicolonIndex + 1 : index;\n return { value, end };\n }\n\n value += char ?? \"\";\n index += 1;\n }\n\n return undefined;\n}\n\nfunction skipHorizontalWhitespace(source: string, start: number): number {\n let index = start;\n while (source[index] === \" \" || source[index] === \"\\t\" || source[index] === \"\\r\") {\n index += 1;\n }\n return index;\n}\n\n/**\n * Collect SSG pages from route modules\n *\n * Scans all routes and categorizes them into:\n * - SSG pages: Pre-rendered at build time\n * - SSR routes: Rendered on each request\n *\n * @param routes - Array of route entries\n * @param loadModule - Function to load a route module\n * @returns SSG pages and SSR routes\n */\nexport async function collectSSGPages(\n routes: RouteEntry[],\n loadModule: (filePath: string) => Promise<RouteModule>,\n): Promise<SSGCollectionResult> {\n const ssgPages: SSGPage[] = [];\n const ssrRoutes: string[] = [];\n\n for (const route of routes) {\n try {\n const mod = await loadModule(route.filePath);\n\n if (!mod) {\n ssrRoutes.push(route.path);\n continue;\n }\n\n const rendering = await resolveRouteRenderingConfigFromFile(mod, route.filePath);\n\n // Check if page is marked for SSG\n if (rendering.ssg) {\n if (route.isDynamic) {\n // Dynamic SSG route requires getStaticPaths\n const getStaticPaths = mod.getStaticPaths || mod.generateStaticParams;\n\n if (!getStaticPaths) {\n throw new Error(\n `Dynamic SSG route \"${route.path}\" requires getStaticPaths export. ` +\n `Add: export function getStaticPaths() { return [{ paramName: 'value' }]; }`,\n );\n }\n\n // Get all paths to pre-render\n const paths = await getStaticPaths();\n\n // Materialize every path before adding any of them. If one entry is\n // invalid, the outer error handler can safely fall the whole route\n // back to SSR without leaving a partial SSG manifest behind.\n const materializedPages = paths.map((params) => ({\n urlPath: materializeSSGRoutePath(route.path, params),\n filePath: route.filePath,\n params: normalizeStaticPathParams(params),\n revalidate: rendering.revalidate,\n }));\n\n ssgPages.push(...materializedPages);\n } else {\n // Static SSG page\n ssgPages.push({\n urlPath: route.path,\n filePath: route.filePath,\n params: {},\n revalidate: rendering.revalidate,\n });\n }\n } else {\n // SSR route (default)\n ssrRoutes.push(route.path);\n }\n } catch (error) {\n console.error(`Error processing route ${route.path}:`, error);\n // Fall back to SSR for problematic routes\n ssrRoutes.push(route.path);\n }\n }\n\n return { ssg: ssgPages, ssr: ssrRoutes };\n}\n\nfunction materializeSSGRoutePath(routePattern: string, params: StaticPathParams): string {\n const outputSegments: string[] = [];\n\n for (const segment of routePattern.split(\"/\")) {\n if (!segment) {\n continue;\n }\n\n const optionalCatchAll = segment.match(OPTIONAL_CATCH_ALL_SEGMENT);\n if (optionalCatchAll) {\n const parameterName = optionalCatchAll[1]!;\n const value = params[parameterName];\n const values = readCatchAllSegments(value, {\n optional: true,\n parameterName,\n routePattern,\n });\n outputSegments.push(...values.map(encodePathSegment));\n continue;\n }\n\n const requiredCatchAll = segment.match(REQUIRED_CATCH_ALL_SEGMENT);\n if (requiredCatchAll) {\n const parameterName = requiredCatchAll[1]!;\n const value = params[parameterName];\n const values = readCatchAllSegments(value, {\n optional: false,\n parameterName,\n routePattern,\n });\n outputSegments.push(...values.map(encodePathSegment));\n continue;\n }\n\n const requiredDynamic = segment.match(REQUIRED_DYNAMIC_SEGMENT);\n if (requiredDynamic) {\n const parameterName = requiredDynamic[1]!;\n const value = params[parameterName];\n if (isStaticPathArray(value)) {\n throw new Error(\n `Cannot materialize SSG route \"${routePattern}\": parameter \"${parameterName}\" ` +\n \"must be a scalar value; arrays are only supported for catch-all segments.\",\n );\n }\n if (isMissingPathValue(value)) {\n throw missingRequiredParameterError(routePattern, parameterName);\n }\n outputSegments.push(encodePathSegment(value));\n continue;\n }\n\n outputSegments.push(segment);\n }\n\n return outputSegments.length > 0 ? `/${outputSegments.join(\"/\")}` : \"/\";\n}\n\nfunction readCatchAllSegments(\n value: StaticPathParams[string] | undefined,\n options: {\n optional: boolean;\n parameterName: string;\n routePattern: string;\n },\n): StaticPathPrimitive[] {\n if (isMissingPathValue(value) || (isStaticPathArray(value) && value.length === 0)) {\n if (options.optional) {\n return [];\n }\n throw missingRequiredParameterError(options.routePattern, options.parameterName);\n }\n\n const segments = isStaticPathArray(value) ? [...value] : [value as StaticPathPrimitive];\n if (segments.some(isMissingPathValue)) {\n throw new Error(\n `Cannot materialize SSG route \"${options.routePattern}\": catch-all parameter ` +\n `\"${options.parameterName}\" contains an empty path segment.`,\n );\n }\n\n return segments;\n}\n\nfunction normalizeStaticPathParams(params: StaticPathParams): Record<string, string> {\n return Object.fromEntries(\n Object.entries(params).map(([key, value]) => [\n key,\n isStaticPathArray(value) ? value.map(String).join(\"/\") : String(value),\n ]),\n );\n}\n\nfunction isMissingPathValue(value: unknown): value is \"\" | null | undefined {\n return value === \"\" || value === null || typeof value === \"undefined\";\n}\n\nfunction isStaticPathArray(\n value: StaticPathParams[string] | undefined,\n): value is readonly StaticPathPrimitive[] {\n return Array.isArray(value);\n}\n\nfunction missingRequiredParameterError(routePattern: string, parameterName: string): Error {\n return new Error(\n `Cannot materialize SSG route \"${routePattern}\": required parameter ` +\n `\"${parameterName}\" is missing or empty.`,\n );\n}\n\nfunction encodePathSegment(value: StaticPathPrimitive): string {\n const encoded = encodeURIComponent(String(value)).replace(\n /[!'()*]/g,\n (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n\n // Dot-only URL segments are normalized as navigation by URL parsers and\n // filesystem joins. Pre-rendering them could therefore escape the intended\n // route directory or overwrite a parent artifact. They cannot faithfully be\n // represented as a static URL segment, so keep the route server-rendered.\n if (encoded === \".\" || encoded === \"..\") {\n throw new Error(\n `Cannot materialize SSG path segment \"${encoded}\": dot-only segments are unsafe to prerender.`,\n );\n }\n\n return encoded;\n}\n\n/**\n * Check if a route module is SSG\n */\nexport function isSSGModule(mod: RouteModule | null | undefined): boolean {\n return resolveRouteRenderingConfig(mod).ssg;\n}\n\n/**\n * Check if a route module has ISR (Incremental Static Regeneration)\n */\nexport function hasISR(mod: RouteModule | null | undefined): boolean {\n const rendering = resolveRouteRenderingConfig(mod);\n return rendering.ssg && typeof rendering.revalidate === \"number\" && rendering.revalidate > 0;\n}\n\n/**\n * Get revalidation interval for a module\n */\nexport function getRevalidateInterval(mod: RouteModule | null | undefined): number | undefined {\n return resolveRouteRenderingConfig(mod).revalidate;\n}\n\n/**\n * Check if a route module has PPR/static-shell caching enabled.\n */\nexport function hasPPR(mod: RouteModule | null | undefined): boolean {\n return resolveRouteRenderingConfig(mod).ppr;\n}\n\n/**\n * Generate SSG manifest for production builds\n */\nexport function generateSSGManifest(pages: SSGPage[]): string {\n return JSON.stringify(\n pages.map((page) => ({\n urlPath: page.urlPath,\n params: page.params,\n revalidate: page.revalidate,\n })),\n null,\n 2,\n );\n}\n\n/**\n * Check if a URL path matches an SSG page\n */\nexport function matchSSGPage(urlPath: string, ssgPages: SSGPage[]): SSGPage | undefined {\n const normalizedPath = urlPath === \"/\" ? \"/\" : urlPath.replace(/\\/$/, \"\");\n return ssgPages.find((page) => page.urlPath === normalizedPath);\n}\n","import { Suspense, createElement, type ComponentType } from \"react\";\nimport {\n createFarmCacheKey,\n createRouteDataCacheTag,\n getFarmDataCache,\n type FarmCacheOptions,\n type RouteDataCacheKey,\n} from \"./cache\";\nimport { getFarmRouteContext } from \"./route-context\";\nimport { normalizeFarmRouteRuntimeConfig, type FarmRouteRuntimeConfig } from \"./route-runtime\";\nimport type {\n FarmAppContext,\n LayoutProps,\n Metadata,\n PageProps,\n ParsedRoute,\n PluginContextProps,\n RouteModule,\n} from \"./types\";\n\nexport type ProgrammaticRouteRenderMode = \"static\" | \"dynamic\";\nexport type ProgrammaticRouteMethod =\n | \"GET\"\n | \"HEAD\"\n | \"POST\"\n | \"PUT\"\n | \"DELETE\"\n | \"PATCH\"\n | \"OPTIONS\";\n\nexport type ProgrammaticRoutePrimitive = string | number | boolean;\nexport type ProgrammaticStaticPathParams = Record<\n string,\n ProgrammaticRoutePrimitive | readonly ProgrammaticRoutePrimitive[]\n>;\nexport type ProgrammaticStaticPath =\n | string\n | readonly ProgrammaticRoutePrimitive[]\n | ProgrammaticStaticPathParams;\nexport type ProgrammaticStaticPaths = () =>\n | readonly ProgrammaticStaticPath[]\n | Promise<readonly ProgrammaticStaticPath[]>;\n\nexport interface ProgrammaticRouteSchema<TOutput = unknown> {\n parse(value: unknown): TOutput;\n}\n\nexport interface ProgrammaticRouteSearchOptions<TOutput = ProgrammaticRouteSearchFallback> {\n schema?: ProgrammaticRouteSchema<TOutput>;\n stripDefaults?: boolean | readonly string[];\n preserve?: readonly string[];\n temporary?: readonly string[];\n}\n\nexport type ProgrammaticRouteSearchConfig<TOutput = ProgrammaticRouteSearchFallback> =\n | ProgrammaticRouteSchema<TOutput>\n | ProgrammaticRouteSearchOptions<TOutput>;\n\nexport type InferProgrammaticRouteSchema<TSchema, TFallback> =\n TSchema extends ProgrammaticRouteSchema<infer TOutput> ? TOutput : TFallback;\n\nexport type InferProgrammaticRouteSearch<TSearch, TFallback> =\n TSearch extends ProgrammaticRouteSearchOptions<infer TOutput>\n ? TOutput\n : TSearch extends ProgrammaticRouteSchema<infer TOutput>\n ? TOutput\n : TFallback;\n\nexport type ProgrammaticRouteParamsFallback = Record<string, string>;\nexport type ProgrammaticRouteSearchFallback = Record<string, string | string[] | undefined>;\nexport type ProgrammaticRouteMaybePromise<T> = T | Promise<T>;\nexport type ProgrammaticRouteDataStaleTime =\n | number\n | false\n | `${number}ms`\n | `${number}s`\n | `${number}m`\n | `${number}h`;\nexport type ProgrammaticRouteContext = keyof FarmAppContext extends never\n ? unknown\n : FarmAppContext;\n\nexport type ProgrammaticRouteComponentProps<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TData = undefined,\n> = Omit<PageProps, \"params\" | \"searchParams\"> & {\n params: TParams;\n search: TSearch;\n searchParams: Promise<TSearch>;\n} & ([TData] extends [undefined] ? { data?: undefined } : { data: TData });\n\nexport type ProgrammaticRouteDataContext<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TContext = ProgrammaticRouteContext,\n> = Omit<ProgrammaticRouteComponentProps<TParams, TSearch>, \"context\" | \"data\"> & {\n context: TContext;\n pluginContext?: PluginContextProps;\n};\n\nexport type ProgrammaticRouteDataCacheContext<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TBefore = unknown,\n TContext = ProgrammaticRouteContext,\n> = ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n before: TBefore;\n};\n\nexport type ProgrammaticRouteGuardContext<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TContext = ProgrammaticRouteContext,\n> = ProgrammaticRouteDataContext<TParams, TSearch, TContext>;\n\nexport type ProgrammaticRouteGuard<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TContext = ProgrammaticRouteContext,\n> = (\n context: ProgrammaticRouteGuardContext<TParams, TSearch, TContext>,\n) => ProgrammaticRouteMaybePromise<void>;\n\nexport type ProgrammaticRouteErrorComponentProps<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n> = Partial<ProgrammaticRouteComponentProps<TParams, TSearch>> & {\n error: unknown;\n};\n\nexport type ProgrammaticRoutePendingComponentProps<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n> = Partial<ProgrammaticRouteComponentProps<TParams, TSearch>>;\n\nexport type ProgrammaticRouteDataCacheKeys<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TBefore = unknown,\n TContext = ProgrammaticRouteContext,\n> =\n | readonly string[]\n | ((\n context: ProgrammaticRouteDataCacheContext<TParams, TSearch, TBefore, TContext>,\n ) => ProgrammaticRouteMaybePromise<readonly string[]>);\n\nexport interface ProgrammaticRouteDataHooks<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TBefore = unknown,\n TData = unknown,\n TContext = ProgrammaticRouteContext,\n> {\n key?: (\n context: ProgrammaticRouteDataCacheContext<TParams, TSearch, NoInfer<TBefore>, TContext>,\n ) => ProgrammaticRouteMaybePromise<RouteDataCacheKey | null | undefined>;\n staleTime?: ProgrammaticRouteDataStaleTime;\n tags?: ProgrammaticRouteDataCacheKeys<TParams, TSearch, NoInfer<TBefore>, TContext>;\n paths?: ProgrammaticRouteDataCacheKeys<TParams, TSearch, NoInfer<TBefore>, TContext>;\n before?: (\n context: ProgrammaticRouteDataContext<TParams, TSearch, TContext>,\n ) => ProgrammaticRouteMaybePromise<TBefore>;\n main: (\n context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n before: NoInfer<TBefore>;\n },\n ) => ProgrammaticRouteMaybePromise<TData>;\n after?: (\n context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n before: NoInfer<TBefore>;\n data: NoInfer<TData>;\n },\n ) => ProgrammaticRouteMaybePromise<void>;\n}\n\nexport type InferProgrammaticRouteData<TDataHooks> = TDataHooks extends {\n main: (...args: any[]) => infer TResult;\n}\n ? Awaited<TResult>\n : undefined;\n\nexport interface ProgrammaticPageRoute<\n TParams = ProgrammaticRouteParamsFallback,\n TSearch = ProgrammaticRouteSearchFallback,\n TDataHooks extends ProgrammaticRouteDataHooks<TParams, TSearch, any, any, any> | undefined =\n | ProgrammaticRouteDataHooks<TParams, TSearch, any, any, any>\n | undefined,\n TContext = ProgrammaticRouteContext,\n> extends FarmRouteRuntimeConfig {\n kind: \"page\";\n path: string;\n component: ComponentType<any>;\n params?: ProgrammaticRouteSchema<TParams>;\n search?: ProgrammaticRouteSearchConfig<TSearch>;\n guard?: ProgrammaticRouteGuard<TParams, TSearch, TContext>;\n data?: TDataHooks;\n pending?: ComponentType<ProgrammaticRoutePendingComponentProps<TParams, TSearch>>;\n error?: ComponentType<ProgrammaticRouteErrorComponentProps<TParams, TSearch>>;\n notFound?: ComponentType<ProgrammaticRouteErrorComponentProps<TParams, TSearch>>;\n render?: ProgrammaticRouteRenderMode;\n staticPaths?: ProgrammaticStaticPaths;\n revalidate?: number | false;\n ppr?: boolean;\n metadata?: Metadata & Record<string, any>;\n generateMetadata?: RouteModule[\"generateMetadata\"];\n}\n\nexport interface ProgrammaticLayoutRoute extends FarmRouteRuntimeConfig {\n kind: \"layout\";\n path: string;\n component: ComponentType<LayoutProps>;\n metadata?: Metadata & Record<string, any>;\n generateMetadata?: (props: { params: Record<string, string> }) => Promise<Metadata> | Metadata;\n}\n\nexport type ProgrammaticApiRouteOptions = Partial<Record<ProgrammaticRouteMethod, any>> & {\n render?: ProgrammaticRouteRenderMode;\n} & FarmRouteRuntimeConfig;\n\nexport interface ProgrammaticApiRoute extends FarmRouteRuntimeConfig {\n kind: \"api\";\n path: string;\n methods: Partial<Record<ProgrammaticRouteMethod, any>>;\n render?: ProgrammaticRouteRenderMode;\n}\n\nexport interface ProgrammaticRedirectRoute {\n kind: \"redirect\";\n source: string;\n destination: string;\n permanent?: boolean;\n statusCode?: number;\n}\n\nexport type ProgrammaticRouteDefinition =\n | ProgrammaticPageRoute<any, any>\n | ProgrammaticLayoutRoute\n | ProgrammaticApiRoute\n | ProgrammaticRedirectRoute;\n\nexport interface ProgrammaticRouteManifest {\n readonly __farmRoutes: true;\n routes: ProgrammaticRouteDefinition[];\n}\n\nexport interface ProgrammaticRouteBuilder {\n page(\n path: string,\n options: Omit<ProgrammaticPageRoute<any, any>, \"kind\" | \"path\">,\n ): ProgrammaticPageRoute;\n layout(\n path: string,\n options: Omit<ProgrammaticLayoutRoute, \"kind\" | \"path\">,\n ): ProgrammaticLayoutRoute;\n api(path: string, options: ProgrammaticApiRouteOptions): ProgrammaticApiRoute;\n redirect(\n source: string,\n destination: string,\n options?: Omit<ProgrammaticRedirectRoute, \"kind\" | \"source\" | \"destination\">,\n ): ProgrammaticRedirectRoute;\n}\n\nexport type ProgrammaticRouteFactory = (\n builder: ProgrammaticRouteBuilder,\n) => readonly ProgrammaticRouteDefinition[];\n\ntype CreateRouteParams<TParamsSchema> = InferProgrammaticRouteSchema<\n TParamsSchema,\n ProgrammaticRouteParamsFallback\n>;\n\ntype CreateRouteSearch<TSearchConfig> = InferProgrammaticRouteSearch<\n TSearchConfig,\n ProgrammaticRouteSearchFallback\n>;\n\ntype CreateRouteSharedOptions<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n> = Omit<\n ProgrammaticPageRoute<CreateRouteParams<TParamsSchema>, CreateRouteSearch<TSearchConfig>>,\n \"kind\" | \"path\" | \"component\" | \"params\" | \"search\" | \"data\" | \"guard\"\n> & {\n params?: TParamsSchema;\n search?: TSearchConfig;\n guard?: ProgrammaticRouteGuard<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>\n >;\n};\n\ntype CreateRouteDataHooksWithBefore<\n TParams,\n TSearch,\n TBeforeResult,\n TMainResult,\n TContext = ProgrammaticRouteContext,\n> = Omit<\n ProgrammaticRouteDataHooks<\n TParams,\n TSearch,\n NoInfer<Awaited<TBeforeResult>>,\n NoInfer<Awaited<TMainResult>>,\n TContext\n >,\n \"before\" | \"main\"\n> & {\n before: (context: ProgrammaticRouteDataContext<TParams, TSearch, TContext>) => TBeforeResult;\n main: (\n context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n before: NoInfer<Awaited<TBeforeResult>>;\n },\n ) => TMainResult;\n};\n\ntype CreateRouteDataHooksWithoutBefore<\n TParams,\n TSearch,\n TMainResult,\n TContext = ProgrammaticRouteContext,\n> = Omit<\n ProgrammaticRouteDataHooks<TParams, TSearch, undefined, NoInfer<Awaited<TMainResult>>, TContext>,\n \"before\" | \"main\"\n> & {\n before?: undefined;\n main: (\n context: ProgrammaticRouteDataContext<TParams, TSearch, TContext> & {\n before: undefined;\n },\n ) => TMainResult;\n};\n\ntype CreateRouteOptionsWithBefore<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n TBefore,\n TData,\n> = CreateRouteSharedOptions<TParamsSchema, TSearchConfig> & {\n data: CreateRouteDataHooksWithBefore<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n TBefore,\n TData\n >;\n component: ComponentType<\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n NoInfer<Awaited<TData>>\n >\n >;\n};\n\ntype CreateRouteOptionsWithoutBefore<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n TData,\n> = CreateRouteSharedOptions<TParamsSchema, TSearchConfig> & {\n data: CreateRouteDataHooksWithoutBefore<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n TData\n >;\n component: ComponentType<\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n NoInfer<Awaited<TData>>\n >\n >;\n};\n\ntype CreateRouteOptionsWithoutData<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined,\n> = CreateRouteSharedOptions<TParamsSchema, TSearchConfig> & {\n data?: undefined;\n component: ComponentType<\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n undefined\n >\n >;\n};\n\ntype CreateRouteComponentOption<TComponent extends ComponentType<any>, TProps> = {\n component: TComponent;\n} & (TComponent extends ComponentType<TProps> ? unknown : { component: ComponentType<TProps> });\n\nexport type CreateRouteOptions<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n TBefore = unknown,\n TData = unknown,\n> =\n | CreateRouteOptionsWithBefore<TParamsSchema, TSearchConfig, TBefore, TData>\n | CreateRouteOptionsWithoutBefore<TParamsSchema, TSearchConfig, TData>\n | CreateRouteOptionsWithoutData<TParamsSchema, TSearchConfig>;\n\nconst FARM_ROUTES_BRAND = Symbol.for(\"farm.routes\");\nexport const PROGRAMMATIC_ROUTE_FILE_NAMES = [\n \"farm.route.ts\",\n \"farm.route.tsx\",\n \"farm.route.js\",\n \"farm.route.jsx\",\n \"farm.routes.ts\",\n \"farm.routes.tsx\",\n \"farm.routes.js\",\n \"farm.routes.jsx\",\n \"routes.ts\",\n \"routes.tsx\",\n \"routes.js\",\n \"routes.jsx\",\n];\n\nexport function defineRoutes(\n input: readonly ProgrammaticRouteDefinition[] | ProgrammaticRouteFactory,\n): ProgrammaticRouteManifest {\n const routes = typeof input === \"function\" ? input(routesBuilder) : input;\n const manifest = {\n __farmRoutes: true as const,\n routes: routes.map(normalizeProgrammaticRoute),\n };\n\n Object.defineProperty(manifest, FARM_ROUTES_BRAND, {\n value: true,\n enumerable: false,\n });\n\n return manifest;\n}\n\nexport const routesBuilder: ProgrammaticRouteBuilder = {\n page(path, options) {\n return normalizeProgrammaticRoute({\n kind: \"page\",\n path,\n ...options,\n }) as ProgrammaticPageRoute;\n },\n layout(path, options) {\n return normalizeProgrammaticRoute({\n kind: \"layout\",\n path,\n ...options,\n }) as ProgrammaticLayoutRoute;\n },\n api(path, options) {\n const { render, runtime, regions, maxDuration, ...methods } = options;\n return normalizeProgrammaticRoute({\n kind: \"api\",\n path,\n render,\n runtime,\n regions,\n maxDuration,\n methods: normalizeApiMethods(methods),\n }) as ProgrammaticApiRoute;\n },\n redirect(source, destination, options = {}) {\n return normalizeProgrammaticRoute({\n kind: \"redirect\",\n source,\n destination,\n ...options,\n }) as ProgrammaticRedirectRoute;\n },\n};\n\nexport const page = routesBuilder.page;\nexport const layout = routesBuilder.layout;\nexport const api = routesBuilder.api;\nexport const redirect = routesBuilder.redirect;\n\nexport interface ProgrammaticRouteSearchClientOptions {\n stripDefaults?: boolean | readonly string[];\n preserve?: readonly string[];\n temporary?: readonly string[];\n}\n\nexport interface ProgrammaticRouteSearchResolution<TSearch = unknown> {\n search: TSearch;\n canonicalPath?: string;\n}\n\nexport function getProgrammaticRouteSearchSchema<TSearch = unknown>(\n search: ProgrammaticRouteSearchConfig<TSearch> | undefined,\n): ProgrammaticRouteSchema<TSearch> | undefined {\n if (!search) return undefined;\n if (isProgrammaticRouteSchema(search)) return search;\n return search.schema;\n}\n\nexport function getProgrammaticRouteSearchClientOptions(\n search: ProgrammaticRouteSearchConfig<any> | undefined,\n): ProgrammaticRouteSearchClientOptions | undefined {\n if (!search || isProgrammaticRouteSchema(search)) return undefined;\n\n const options: ProgrammaticRouteSearchClientOptions = {};\n if (typeof search.stripDefaults !== \"undefined\") options.stripDefaults = search.stripDefaults;\n if (search.preserve?.length) options.preserve = [...search.preserve];\n if (search.temporary?.length) options.temporary = [...search.temporary];\n\n return Object.keys(options).length > 0 ? options : undefined;\n}\n\nfunction resolveProgrammaticRouteSearch<TSearch>(\n searchConfig: ProgrammaticRouteSearchConfig<TSearch> | undefined,\n rawSearch: ProgrammaticRouteSearchFallback,\n path: string,\n routePath: string,\n): ProgrammaticRouteSearchResolution<TSearch | ProgrammaticRouteSearchFallback> {\n const schema = getProgrammaticRouteSearchSchema(searchConfig);\n const search = parseProgrammaticSchema(schema, rawSearch, \"search\", routePath) as\n | TSearch\n | ProgrammaticRouteSearchFallback;\n const options = getProgrammaticRouteSearchOptions(searchConfig);\n const canonicalPath = resolveProgrammaticRouteCanonicalPath({\n options,\n schema,\n rawSearch,\n parsedSearch: search,\n path,\n });\n\n return { search, canonicalPath };\n}\n\nfunction getProgrammaticRouteSearchOptions(\n search: ProgrammaticRouteSearchConfig<any> | undefined,\n): ProgrammaticRouteSearchOptions<any> | undefined {\n if (!search || isProgrammaticRouteSchema(search)) return undefined;\n return search;\n}\n\nfunction isProgrammaticRouteSchema(value: unknown): value is ProgrammaticRouteSchema<any> {\n return !!value && typeof value === \"object\" && typeof (value as any).parse === \"function\";\n}\n\nfunction resolveProgrammaticRouteCanonicalPath(input: {\n options: ProgrammaticRouteSearchOptions<any> | undefined;\n schema: ProgrammaticRouteSchema<any> | undefined;\n rawSearch: ProgrammaticRouteSearchFallback;\n parsedSearch: unknown;\n path: string;\n}): string | undefined {\n const options = input.options;\n if (!options?.temporary?.length && !options?.stripDefaults) {\n return undefined;\n }\n\n const params = createSearchParams(input.rawSearch);\n const original = params.toString();\n\n for (const key of options.temporary || []) {\n params.delete(key);\n }\n\n if (options.stripDefaults) {\n const defaultSearch = parseDefaultSearch(input.schema);\n if (defaultSearch !== undefined) {\n const keys =\n options.stripDefaults === true\n ? Array.from(new Set(Array.from(params.keys())))\n : [...options.stripDefaults];\n\n for (const key of keys) {\n if (\n params.has(key) &&\n searchValuesEqual(\n readSearchValue(input.parsedSearch, key),\n readSearchValue(defaultSearch, key),\n )\n ) {\n params.delete(key);\n }\n }\n }\n }\n\n const next = params.toString();\n if (next === original) {\n return undefined;\n }\n\n return next ? `${input.path}?${next}` : input.path;\n}\n\nfunction createSearchParams(value: ProgrammaticRouteSearchFallback): URLSearchParams {\n const params = new URLSearchParams();\n\n for (const [key, item] of Object.entries(value)) {\n if (item == null) continue;\n const values = Array.isArray(item) ? item : [item];\n for (const entry of values) {\n if (entry != null) params.append(key, String(entry));\n }\n }\n\n return params;\n}\n\nfunction parseDefaultSearch(\n schema: ProgrammaticRouteSchema<any> | undefined,\n): Record<string, unknown> | undefined {\n if (!schema) return undefined;\n\n try {\n const value = schema.parse({});\n return value && typeof value === \"object\" ? (value as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction readSearchValue(value: unknown, key: string): unknown {\n return value && typeof value === \"object\" ? (value as Record<string, unknown>)[key] : undefined;\n}\n\nfunction searchValuesEqual(left: unknown, right: unknown): boolean {\n return (\n JSON.stringify(normalizeComparableValue(left)) ===\n JSON.stringify(normalizeComparableValue(right))\n );\n}\n\nfunction normalizeComparableValue(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(normalizeComparableValue);\n }\n if (value && typeof value === \"object\") {\n return Object.keys(value as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((output, key) => {\n output[key] = normalizeComparableValue((value as Record<string, unknown>)[key]);\n return output;\n }, {});\n }\n return value;\n}\n\nexport function createRoute<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n TBeforeResult = unknown,\n TMainResult = unknown,\n TComponent extends ComponentType<any> = ComponentType<any>,\n>(\n path: string,\n options: Omit<\n CreateRouteOptionsWithBefore<TParamsSchema, TSearchConfig, TBeforeResult, TMainResult>,\n \"component\"\n > &\n CreateRouteComponentOption<\n TComponent,\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n Awaited<TMainResult>\n >\n >,\n): ProgrammaticPageRoute<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n CreateRouteDataHooksWithBefore<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n TBeforeResult,\n TMainResult\n >\n>;\nexport function createRoute<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n TMainResult = unknown,\n TComponent extends ComponentType<any> = ComponentType<any>,\n>(\n path: string,\n options: Omit<\n CreateRouteOptionsWithoutBefore<TParamsSchema, TSearchConfig, TMainResult>,\n \"component\"\n > &\n CreateRouteComponentOption<\n TComponent,\n ProgrammaticRouteComponentProps<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n Awaited<TMainResult>\n >\n >,\n): ProgrammaticPageRoute<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n CreateRouteDataHooksWithoutBefore<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n TMainResult\n >\n>;\nexport function createRoute<\n TParamsSchema extends ProgrammaticRouteSchema<any> | undefined = undefined,\n TSearchConfig extends ProgrammaticRouteSearchConfig<any> | undefined = undefined,\n>(\n path: string,\n options: CreateRouteOptionsWithoutData<TParamsSchema, TSearchConfig>,\n): ProgrammaticPageRoute<\n CreateRouteParams<TParamsSchema>,\n CreateRouteSearch<TSearchConfig>,\n undefined\n>;\nexport function createRoute(path: string, options: any): any {\n return routesBuilder.page(path, options);\n}\n\nexport function isProgrammaticRoutesFileName(fileName: string): boolean {\n const normalized = fileName.replace(/\\\\/g, \"/\");\n const baseName = normalized.split(\"/\").pop() || normalized;\n return PROGRAMMATIC_ROUTE_FILE_NAMES.includes(baseName);\n}\n\nexport function getProgrammaticRouteManifest(\n mod: Record<string, any> | null | undefined,\n): ProgrammaticRouteManifest | null {\n if (!mod) return null;\n\n const candidates = [mod.default, mod.routes, mod.Route];\n for (const candidate of candidates) {\n if (isProgrammaticRouteManifest(candidate)) {\n return candidate;\n }\n if (isProgrammaticRouteDefinition(candidate)) {\n return defineRoutes([candidate]);\n }\n if (Array.isArray(candidate)) {\n return defineRoutes(candidate as ProgrammaticRouteDefinition[]);\n }\n }\n\n const routeDefinitions = Object.values(mod).filter(isProgrammaticRouteDefinition);\n if (routeDefinitions.length > 0) {\n return defineRoutes(routeDefinitions);\n }\n\n return null;\n}\n\nexport function isProgrammaticRouteManifest(value: unknown): value is ProgrammaticRouteManifest {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as ProgrammaticRouteManifest).__farmRoutes === true &&\n Array.isArray((value as ProgrammaticRouteManifest).routes)\n );\n}\n\nexport function isProgrammaticRouteDefinition(\n value: unknown,\n): value is ProgrammaticRouteDefinition {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n\n const kind = (value as { kind?: unknown }).kind;\n return kind === \"page\" || kind === \"layout\" || kind === \"api\" || kind === \"redirect\";\n}\n\nexport function createProgrammaticRouteModuleId(\n filePath: string,\n kind: \"page\" | \"layout\" | \"api\",\n routePath: string,\n): string {\n return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeRoutePath(routePath))}`;\n}\n\nexport function parseProgrammaticRouteModuleId(moduleId: string): {\n filePath: string;\n kind: \"page\" | \"layout\" | \"api\";\n routePath: string;\n} | null {\n const queryIndex = moduleId.indexOf(\"?\");\n if (queryIndex === -1) {\n return null;\n }\n\n const filePath = moduleId.slice(0, queryIndex);\n const params = new URLSearchParams(moduleId.slice(queryIndex + 1));\n const value = params.get(\"farm-route\");\n if (!value) {\n return null;\n }\n\n const separator = value.indexOf(\":\");\n if (separator === -1) {\n return null;\n }\n\n const kind = value.slice(0, separator);\n if (kind !== \"page\" && kind !== \"layout\" && kind !== \"api\") {\n return null;\n }\n\n return {\n filePath,\n kind,\n routePath: normalizeRoutePath(value.slice(separator + 1)),\n };\n}\n\nexport function parseProgrammaticRoutePath(\n routePath: string,\n type: ParsedRoute[\"type\"] = \"page\",\n): ParsedRoute {\n const fileName = type === \"layout\" ? \"layout.tsx\" : \"page.tsx\";\n const normalized = normalizeRoutePath(routePath);\n const filePath =\n normalized === \"/\" ? fileName : `${normalized.slice(1).replace(/\\/+$/, \"\")}/${fileName}`;\n\n return {\n filePath,\n type,\n segments: normalized === \"/\" ? [] : normalized.slice(1).split(\"/\").map(parseRouteSegment),\n };\n}\n\nexport function createRouteModuleFromProgrammaticPage(route: ProgrammaticPageRoute): RouteModule {\n const mod: RouteModule = {\n default: createProgrammaticPageComponent(route),\n ...normalizeFarmRouteRuntimeConfig(route, `Route \"${route.path}\"`),\n };\n\n if (route.params || route.search || route.guard || route.data) {\n (mod as any).__farmRouteSchemas = {\n params: route.params,\n search: getProgrammaticRouteSearchSchema(route.search),\n };\n (mod as any).__farmRouteSearch = getProgrammaticRouteSearchClientOptions(route.search);\n (mod as any).__farmRouteGuard = route.guard;\n (mod as any).__farmRouteData = route.data;\n (mod as any).__farmRouteParsesProps = true;\n (mod as any).__farmResolveRouteProps = (props: PageProps) =>\n resolveProgrammaticRouteProps(route, props);\n (mod as any).__farmResolveRouteCanonicalPath = (\n rawSearch: ProgrammaticRouteSearchFallback,\n path: string,\n ) => resolveProgrammaticRouteSearch(route.search, rawSearch, path, route.path).canonicalPath;\n }\n\n if (route.pending || route.error || route.notFound) {\n (mod as any).__farmRouteComponents = {\n pending: route.pending,\n error: route.error,\n notFound: route.notFound,\n };\n }\n\n if (route.render === \"static\" || route.staticPaths) {\n mod.ssg = true;\n mod.dynamic = \"force-static\";\n } else if (route.render === \"dynamic\") {\n mod.ssg = false;\n mod.dynamic = \"force-dynamic\";\n }\n\n if (typeof route.revalidate !== \"undefined\") {\n mod.revalidate = route.revalidate;\n }\n\n if (route.ppr) {\n mod.ppr = true;\n }\n\n if (route.metadata) {\n mod.metadata = route.metadata;\n }\n\n if (route.generateMetadata) {\n mod.generateMetadata = route.generateMetadata;\n }\n\n if (route.staticPaths) {\n mod.getStaticPaths = async () => normalizeStaticPaths(route.path, await route.staticPaths!());\n }\n\n return mod;\n}\n\nexport function createLayoutModuleFromProgrammaticLayout(route: ProgrammaticLayoutRoute) {\n return {\n default: route.component,\n ...normalizeFarmRouteRuntimeConfig(route, `Layout \"${route.path}\"`),\n metadata: route.metadata,\n generateMetadata: route.generateMetadata,\n };\n}\n\nexport function scanProgrammaticPagePaths(source: string): string[] {\n const paths = new Set<string>();\n const callRe = /\\b(?:page|createRoute)\\s*\\(\\s*([\"'`])([^\"'`]+)\\1/g;\n\n for (const match of source.matchAll(callRe)) {\n if (match[2]) {\n paths.add(normalizeRoutePath(match[2]));\n }\n }\n\n return Array.from(paths);\n}\n\nfunction createProgrammaticPageComponent(route: ProgrammaticPageRoute): ComponentType<PageProps> {\n if (\n !route.params &&\n !route.search &&\n !route.guard &&\n !route.data &&\n !route.pending &&\n !route.error &&\n !route.notFound\n ) {\n return route.component as ComponentType<PageProps>;\n }\n\n const Component = route.component;\n\n if (route.pending) {\n const PendingComponent = route.pending;\n const routePropsResources = new WeakMap<object, ProgrammaticRoutePropsResource>();\n const FarmProgrammaticPageContent = function FarmProgrammaticPageContent(props: PageProps) {\n try {\n const resolvedProps = readProgrammaticRouteProps(route, props, routePropsResources);\n return createElement(Component, stripProgrammaticRoutePropsMarker(resolvedProps));\n } catch (error) {\n if (isPromiseLike(error) || isProgrammaticRedirectSignal(error)) {\n throw error;\n }\n\n if (isProgrammaticNotFoundSignal(error) && route.notFound) {\n return createElement(route.notFound, createProgrammaticRouteErrorProps(error, props));\n }\n\n if (route.error) {\n return createElement(route.error, createProgrammaticRouteErrorProps(error, props));\n }\n\n throw error;\n }\n };\n const PageContent = FarmProgrammaticPageContent as unknown as ComponentType<PageProps>;\n const FarmProgrammaticPage = function FarmProgrammaticPage(props: PageProps) {\n return createElement(\n Suspense,\n {\n fallback: createElement(PendingComponent, createProgrammaticRoutePendingProps(props)),\n },\n createElement(PageContent, props),\n );\n };\n\n return FarmProgrammaticPage as unknown as ComponentType<PageProps>;\n }\n\n const FarmProgrammaticPageContent = async function FarmProgrammaticPageContent(props: PageProps) {\n try {\n const resolvedProps = isProgrammaticRoutePropsResolved(props)\n ? props\n : await resolveProgrammaticRouteProps(route, props);\n\n return createElement(Component, stripProgrammaticRoutePropsMarker(resolvedProps));\n } catch (error) {\n if (isProgrammaticRedirectSignal(error)) {\n throw error;\n }\n\n if (isProgrammaticNotFoundSignal(error) && route.notFound) {\n return createElement(route.notFound, createProgrammaticRouteErrorProps(error, props));\n }\n\n if (route.error) {\n return createElement(route.error, createProgrammaticRouteErrorProps(error, props));\n }\n\n throw error;\n }\n };\n\n return FarmProgrammaticPageContent as unknown as ComponentType<PageProps>;\n}\n\ntype ProgrammaticRoutePropsResource =\n | { status: \"pending\"; promise: Promise<Record<string, any>> }\n | { status: \"resolved\"; value: Record<string, any> }\n | { status: \"rejected\"; error: unknown };\n\nfunction readProgrammaticRouteProps(\n route: ProgrammaticPageRoute,\n props: PageProps,\n resources: WeakMap<object, ProgrammaticRoutePropsResource>,\n): Record<string, any> {\n if (isProgrammaticRoutePropsResolved(props)) {\n return props;\n }\n\n let resource = resources.get(props as object);\n if (!resource) {\n const deferredRouteProps = (props as any).__farmRoutePropsPromise;\n const promise = Promise.resolve<Record<string, any>>(\n isPromiseLike(deferredRouteProps)\n ? (deferredRouteProps as PromiseLike<Record<string, any>>)\n : resolveProgrammaticRouteProps(route, props),\n );\n resource = { status: \"pending\", promise };\n resources.set(props as object, resource);\n promise.then(\n (value) => resources.set(props as object, { status: \"resolved\", value }),\n (error) => resources.set(props as object, { status: \"rejected\", error }),\n );\n }\n\n if (resource.status === \"pending\") throw resource.promise;\n if (resource.status === \"rejected\") throw resource.error;\n return resource.value;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return Boolean(\n value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as PromiseLike<unknown>).then === \"function\",\n );\n}\n\nfunction createProgrammaticRoutePendingProps(\n props: PageProps,\n): ProgrammaticRoutePendingComponentProps {\n return {\n params: props.params,\n searchParams: props.searchParams,\n path: props.path,\n };\n}\n\nfunction createProgrammaticRouteErrorProps(\n error: unknown,\n props: PageProps,\n): ProgrammaticRouteErrorComponentProps {\n return {\n error,\n params: props.params,\n searchParams: props.searchParams,\n path: props.path,\n };\n}\n\nfunction isProgrammaticRedirectSignal(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const digest = (error as { digest?: unknown }).digest;\n return typeof digest === \"string\" && digest.startsWith(\"FARM_REDIRECT;\");\n}\n\nfunction isProgrammaticNotFoundSignal(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const digest = (error as { digest?: unknown }).digest;\n return digest === \"FARM_NOT_FOUND\";\n}\n\nasync function resolveProgrammaticRouteProps(\n route: ProgrammaticPageRoute,\n props: PageProps,\n): Promise<Record<string, any> & { __farmRoutePropsResolved: true }> {\n const rawSearch = await props.searchParams;\n const params = parseProgrammaticSchema(route.params, props.params, \"params\", route.path);\n const { search, canonicalPath } = resolveProgrammaticRouteSearch(\n route.search,\n rawSearch,\n props.path,\n route.path,\n );\n const routeContextValue = getFarmRouteContext(props);\n const pluginContext = props.context;\n const baseProps = {\n ...props,\n params,\n search,\n searchParams: Promise.resolve(search),\n };\n const routeContextProps = {\n ...baseProps,\n context: routeContextValue,\n pluginContext,\n };\n\n if (route.guard) {\n await route.guard(routeContextProps as any);\n }\n\n if (!route.data) {\n return markProgrammaticRoutePropsResolved(addCanonicalPath(baseProps, canonicalPath));\n }\n\n const before = route.data.before ? await route.data.before(routeContextProps as any) : undefined;\n const dataContext = {\n ...(routeContextProps as any),\n before,\n };\n const data = await resolveProgrammaticRouteData(route, route.data, dataContext);\n\n if (route.data.after) {\n await route.data.after({\n ...(routeContextProps as any),\n before,\n data,\n });\n }\n\n return markProgrammaticRoutePropsResolved({\n ...baseProps,\n data,\n ...(canonicalPath ? { __farmCanonicalPath: canonicalPath } : {}),\n });\n}\n\nasync function resolveProgrammaticRouteData(\n route: ProgrammaticPageRoute,\n dataHooks: ProgrammaticRouteDataHooks<any, any, any, any>,\n context: ProgrammaticRouteDataCacheContext<any, any, any>,\n): Promise<unknown> {\n if (!dataHooks?.key) {\n return dataHooks.main(context);\n }\n\n const routeDataKey = await dataHooks.key(context);\n if (routeDataKey == null) {\n return dataHooks.main(context);\n }\n\n const cacheKey = createFarmCacheKey([\"route-data\", routeDataKey]);\n const cacheOptions: FarmCacheOptions = {\n tags: [\n createRouteDataCacheTag(routeDataKey),\n ...(await resolveProgrammaticRouteDataKeys(dataHooks.tags, context)),\n ],\n paths: [\n ...(typeof context.path === \"string\" ? [context.path] : []),\n ...(await resolveProgrammaticRouteDataKeys(dataHooks.paths, context)),\n ],\n revalidate: normalizeProgrammaticRouteStaleTime(dataHooks.staleTime),\n };\n\n return getFarmDataCache().getOrSet(cacheKey, () => dataHooks.main(context), cacheOptions);\n}\n\nasync function resolveProgrammaticRouteDataKeys(\n input: ProgrammaticRouteDataCacheKeys<any, any, any> | undefined,\n context: ProgrammaticRouteDataCacheContext<any, any, any>,\n): Promise<readonly string[]> {\n if (!input) return [];\n const value = typeof input === \"function\" ? await input(context) : input;\n return value.filter((item) => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction normalizeProgrammaticRouteStaleTime(\n staleTime: ProgrammaticRouteDataStaleTime | undefined,\n): number | false | undefined {\n if (staleTime === undefined) return undefined;\n if (staleTime === false) return false;\n\n if (typeof staleTime === \"number\") {\n if (!Number.isFinite(staleTime) || staleTime <= 0) return undefined;\n return Math.max(1, Math.ceil(staleTime / 1000));\n }\n\n const match = staleTime.match(/^(\\d+(?:\\.\\d+)?)(ms|s|m|h)$/);\n if (!match) return undefined;\n\n const value = Number(match[1]);\n if (!Number.isFinite(value) || value <= 0) return undefined;\n\n const unit = match[2];\n const milliseconds =\n unit === \"ms\"\n ? value\n : unit === \"s\"\n ? value * 1000\n : unit === \"m\"\n ? value * 60000\n : value * 3600000;\n\n return Math.max(1, Math.ceil(milliseconds / 1000));\n}\n\nfunction isProgrammaticRoutePropsResolved(value: unknown): boolean {\n return !!value && typeof value === \"object\" && (value as any).__farmRoutePropsResolved === true;\n}\n\nfunction markProgrammaticRoutePropsResolved<T extends Record<string, any>>(\n props: T,\n): T & { __farmRoutePropsResolved: true } {\n return {\n ...props,\n __farmRoutePropsResolved: true,\n };\n}\n\nfunction addCanonicalPath<T extends Record<string, any>>(\n props: T,\n canonicalPath: string | undefined,\n): T {\n return canonicalPath ? ({ ...props, __farmCanonicalPath: canonicalPath } as T) : props;\n}\n\nfunction stripProgrammaticRoutePropsMarker<TProps>(props: TProps): TProps {\n if (!isProgrammaticRoutePropsResolved(props)) {\n return props;\n }\n\n const {\n __farmRoutePropsResolved,\n __farmCanonicalPath,\n __farmRoutePropsPromise,\n ...componentProps\n } = props as any;\n return componentProps;\n}\n\nfunction parseProgrammaticSchema<TFallback>(\n schema: ProgrammaticRouteSchema<any> | undefined,\n value: TFallback,\n label: string,\n routePath: string,\n): unknown {\n if (!schema) {\n return value;\n }\n\n try {\n return schema.parse(value);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n }\n}\n\nfunction normalizeProgrammaticRoute(\n route: ProgrammaticRouteDefinition,\n): ProgrammaticRouteDefinition {\n if (route.kind === \"redirect\") {\n return {\n ...route,\n source: normalizeRoutePath(route.source),\n };\n }\n\n if (route.kind === \"api\") {\n return {\n ...route,\n ...normalizeFarmRouteRuntimeConfig(route, `API route \"${route.path}\"`),\n path: normalizeRoutePath(route.path),\n methods: normalizeApiMethods(route.methods),\n };\n }\n\n return {\n ...route,\n ...normalizeFarmRouteRuntimeConfig(\n route,\n `${route.kind === \"layout\" ? \"Layout\" : \"Route\"} \"${route.path}\"`,\n ),\n path: normalizeRoutePath(route.path),\n };\n}\n\nfunction normalizeRoutePath(routePath: string): string {\n const withSlash = routePath.startsWith(\"/\") ? routePath : `/${routePath}`;\n const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\\/+$/, \"\") : withSlash;\n return withoutTrailing || \"/\";\n}\n\nfunction parseRouteSegment(segment: string): ParsedRoute[\"segments\"][number] {\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n let name = segment.slice(1, -1);\n let isOptional = false;\n let isCatchAll = false;\n\n if (name.startsWith(\"[\") && name.endsWith(\"]\")) {\n isOptional = true;\n name = name.slice(1, -1);\n }\n\n if (name.startsWith(\"...\")) {\n isCatchAll = true;\n name = name.slice(3);\n }\n\n return {\n segment: name,\n isDynamic: true,\n isOptional,\n isCatchAll,\n };\n }\n\n return {\n segment,\n isDynamic: false,\n isOptional: false,\n isCatchAll: false,\n };\n}\n\nfunction normalizeApiMethods(\n methods: Record<string, any>,\n): Partial<Record<ProgrammaticRouteMethod, any>> {\n const normalized: Partial<Record<ProgrammaticRouteMethod, any>> = {};\n\n for (const [method, handler] of Object.entries(methods)) {\n const normalizedMethod = method.toUpperCase() as ProgrammaticRouteMethod;\n if (handler && isProgrammaticRouteMethod(normalizedMethod)) {\n normalized[normalizedMethod] = handler;\n }\n }\n\n return normalized;\n}\n\nfunction isProgrammaticRouteMethod(method: string): method is ProgrammaticRouteMethod {\n return (\n method === \"GET\" ||\n method === \"HEAD\" ||\n method === \"POST\" ||\n method === \"PUT\" ||\n method === \"DELETE\" ||\n method === \"PATCH\" ||\n method === \"OPTIONS\"\n );\n}\n\nfunction normalizeStaticPaths(\n routePath: string,\n paths: readonly ProgrammaticStaticPath[],\n): Record<string, string>[] {\n const dynamicSegments = parseProgrammaticRoutePath(routePath).segments.filter(\n (segment) => segment.isDynamic,\n );\n\n return paths.map((entry) => {\n if (typeof entry === \"string\" || Array.isArray(entry)) {\n if (dynamicSegments.length !== 1) {\n throw new Error(\n `staticPaths for \"${routePath}\" must return objects when the route has ${dynamicSegments.length} dynamic params.`,\n );\n }\n\n const value = Array.isArray(entry) ? entry.join(\"/\") : entry;\n return { [dynamicSegments[0].segment]: String(value) };\n }\n\n return Object.fromEntries(\n Object.entries(entry).map(([key, value]) => [\n key,\n Array.isArray(value) ? value.map(String).join(\"/\") : String(value),\n ]),\n );\n });\n}\n","import { emitFarmEvent } from \"./observability\";\nimport { notifyFarmCacheInvalidation } from \"./cache-invalidation\";\nimport { getActiveFarmI18nSnapshot } from \"./i18n/bridge\";\n\nexport { applyFarmCacheInvalidations } from \"./cache-invalidation\";\n\nexport type RevalidateTagProfile =\n | \"max\"\n | \"default\"\n | \"seconds\"\n | \"minutes\"\n | \"hours\"\n | \"days\"\n | \"weeks\"\n | \"months\"\n | { expire?: number };\n\nexport interface FarmCacheOptions {\n /**\n * Tag cached data so it can be invalidated with revalidateTag/updateTag.\n */\n tags?: readonly string[];\n /**\n * Path tags let revalidatePath invalidate data tied to a route.\n */\n paths?: readonly string[];\n /**\n * Time in seconds before the entry becomes stale. False means no TTL.\n */\n revalidate?: number | false;\n}\n\nexport interface FarmCacheSetOptions extends FarmCacheOptions {\n createdAt?: number;\n}\n\nexport type RouteDataCacheKey = string | readonly unknown[];\n\nexport interface FarmCacheEntry<T = unknown> {\n key: string;\n value: T;\n tags: readonly string[];\n createdAt: number;\n createdVersion?: number;\n revalidate?: number | false;\n}\n\ninterface InternalFarmCacheEntry<T = unknown> {\n key: string;\n value: T;\n tags: Set<string>;\n createdAt: number;\n createdVersion: number;\n revalidate?: number | false;\n}\n\nexport interface GetFarmCacheEntryOptions {\n allowStale?: boolean;\n now?: number;\n}\n\ninterface FarmCacheStaleEntry {\n tags: Iterable<string>;\n createdAt: number;\n createdVersion?: number;\n revalidate?: number | false;\n}\n\nexport class FarmDataCache {\n private entries = new Map<string, InternalFarmCacheEntry>();\n private inflight = new Map<string, Promise<unknown>>();\n private invalidatedTagVersions = new Map<string, number>();\n private version = 0;\n\n get size(): number {\n return this.entries.size;\n }\n\n get<T>(key: string, options: GetFarmCacheEntryOptions = {}): T | undefined {\n return this.getEntry<T>(key, options)?.value;\n }\n\n getEntry<T = unknown>(\n key: string,\n options: GetFarmCacheEntryOptions = {},\n ): FarmCacheEntry<T> | undefined {\n const entry = this.entries.get(key) as InternalFarmCacheEntry<T> | undefined;\n if (!entry) {\n emitFarmEvent({ type: \"cache.miss\", key });\n return undefined;\n }\n\n const stale = this.isStale(entry, options.now);\n if (stale) {\n emitFarmEvent({\n type: \"cache.stale\",\n key,\n tags: Array.from(entry.tags),\n revalidate: entry.revalidate,\n });\n }\n\n if (!options.allowStale && stale) {\n emitFarmEvent({ type: \"cache.miss\", key, reason: \"stale\" });\n return undefined;\n }\n\n emitFarmEvent({\n type: \"cache.hit\",\n key,\n tags: Array.from(entry.tags),\n revalidate: entry.revalidate,\n stale,\n });\n\n return this.toPublicEntry(entry);\n }\n\n set<T>(key: string, value: T, options: FarmCacheSetOptions = {}): FarmCacheEntry<T> {\n const tags = new Set<string>();\n for (const tag of options.tags ?? []) {\n tags.add(normalizeCacheTag(tag));\n }\n for (const routePath of options.paths ?? []) {\n tags.add(createPathCacheTag(routePath));\n }\n\n const entry: InternalFarmCacheEntry<T> = {\n key,\n value,\n tags,\n createdAt: options.createdAt ?? Date.now(),\n createdVersion: ++this.version,\n revalidate: normalizeRevalidate(options.revalidate),\n };\n\n this.entries.set(key, entry);\n emitFarmEvent({\n type: \"cache.set\",\n key,\n tags: Array.from(tags),\n revalidate: entry.revalidate,\n });\n return this.toPublicEntry(entry);\n }\n\n delete(key: string): boolean {\n const deleted = this.entries.delete(key);\n emitFarmEvent({ type: \"cache.delete\", key, deleted });\n return deleted;\n }\n\n clear(): void {\n const count = this.entries.size;\n this.entries.clear();\n this.inflight.clear();\n this.invalidatedTagVersions.clear();\n this.version = 0;\n emitFarmEvent({ type: \"cache.clear\", count });\n }\n\n isStale(entry: FarmCacheStaleEntry, now = Date.now()): boolean {\n if (\n typeof entry.revalidate === \"number\" &&\n entry.revalidate > 0 &&\n now - entry.createdAt >= entry.revalidate * 1000\n ) {\n return true;\n }\n\n for (const tag of entry.tags) {\n const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));\n if (\n typeof invalidatedVersion === \"number\" &&\n typeof entry.createdVersion === \"number\" &&\n invalidatedVersion > entry.createdVersion\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n revalidateTag(\n tag: string,\n options: { source?: \"revalidateTag\" | \"updateTag\"; profile?: RevalidateTagProfile } = {},\n ): number {\n const normalized = normalizeCacheTag(tag);\n const count = this.invalidateTag(normalized);\n emitFarmEvent(\n options.source === \"updateTag\"\n ? { type: \"cache.updateTag\", tag: normalized, count }\n : { type: \"cache.revalidateTag\", tag: normalized, profile: options.profile, count },\n );\n return count;\n }\n\n revalidatePath(routePath: string): number {\n const normalizedPath = normalizeRevalidatePath(routePath);\n const pathTag = createPathCacheTag(normalizedPath);\n const pprCount = this.countEntriesForTags([pathTag, \"ppr\"]);\n const count = this.invalidateTag(pathTag);\n emitFarmEvent({ type: \"cache.revalidatePath\", path: normalizedPath, count });\n\n if (pprCount > 0) {\n emitFarmEvent({\n type: \"ppr.shell.invalidated\",\n route: normalizedPath,\n reason: \"revalidatePath\",\n count: pprCount,\n });\n }\n\n return count;\n }\n\n async getOrSet<T>(\n key: string,\n producer: () => Promise<T> | T,\n options: FarmCacheOptions = {},\n ): Promise<T> {\n const cached = this.getEntry<T>(key);\n if (cached) {\n return cached.value;\n }\n\n const inflight = this.inflight.get(key) as Promise<T> | undefined;\n if (inflight) {\n emitFarmEvent({ type: \"cache.dedupe\", key });\n return inflight;\n }\n\n const promise = Promise.resolve()\n .then(producer)\n .then((value) => {\n this.set(key, value, options);\n return value;\n })\n .catch((error) => {\n emitFarmEvent({ type: \"cache.error\", key, operation: \"set\", error });\n throw error;\n })\n .finally(() => {\n this.inflight.delete(key);\n });\n\n this.inflight.set(key, promise);\n return promise;\n }\n\n private countEntriesForTag(tag: string): number {\n let count = 0;\n for (const entry of this.entries.values()) {\n if (entry.tags.has(tag)) {\n count++;\n }\n }\n return count;\n }\n\n private countEntriesForTags(tags: readonly string[]): number {\n let count = 0;\n for (const entry of this.entries.values()) {\n if (tags.every((tag) => entry.tags.has(tag))) {\n count++;\n }\n }\n return count;\n }\n\n private invalidateTag(normalizedTag: string): number {\n this.invalidatedTagVersions.set(normalizedTag, ++this.version);\n return this.countEntriesForTag(normalizedTag);\n }\n\n private toPublicEntry<T>(entry: InternalFarmCacheEntry<T>): FarmCacheEntry<T> {\n return {\n key: entry.key,\n value: entry.value,\n tags: Array.from(entry.tags),\n createdAt: entry.createdAt,\n createdVersion: entry.createdVersion,\n revalidate: entry.revalidate,\n };\n }\n}\n\nconst FARM_DATA_CACHE_SYMBOL = Symbol.for(\"farm.dataCache\");\nconst farmDataCacheGlobal = globalThis as typeof globalThis & {\n [FARM_DATA_CACHE_SYMBOL]?: FarmDataCache;\n};\nconst sharedFarmDataCache = (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ??= new FarmDataCache());\nconst functionIds = new WeakMap<Function, number>();\nlet nextFunctionId = 0;\n\nexport function getFarmDataCache(): FarmDataCache {\n return sharedFarmDataCache;\n}\n\nexport function unstable_cache<Args extends unknown[], Result>(\n fn: (...args: Args) => Result | Promise<Result>,\n keyParts: readonly unknown[] = [],\n options: FarmCacheOptions = {},\n): (...args: Args) => Promise<Result> {\n return async (...args: Args): Promise<Result> => {\n const locale = getActiveFarmI18nSnapshot()?.locale;\n const key = createFarmCacheKey([\n \"unstable_cache\",\n getFunctionCacheIdentity(fn),\n locale ? [\"locale\", locale] : null,\n keyParts,\n args,\n ]);\n return getFarmDataCache().getOrSet<Result>(key, () => fn(...args), options);\n };\n}\n\nexport function revalidateTag(_tag: string, _profile?: RevalidateTagProfile): void {\n getFarmDataCache().revalidateTag(_tag, {\n source: \"revalidateTag\",\n profile: _profile,\n });\n}\n\nexport function updateTag(tag: string): void {\n getFarmDataCache().revalidateTag(tag, { source: \"updateTag\" });\n}\n\nexport function revalidatePath(routePath: string): void {\n getFarmDataCache().revalidatePath(routePath);\n}\n\nexport function invalidate(key: RouteDataCacheKey): void {\n const clientKey = createRouteDataCacheKey(key);\n getFarmDataCache().revalidateTag(createRouteDataCacheTag(key), { source: \"updateTag\" });\n notifyFarmCacheInvalidation(clientKey);\n}\n\nexport function invalidateRouteData(key: RouteDataCacheKey): void {\n invalidate(key);\n}\n\nexport function createPathCacheTag(routePath: string): string {\n return `path:${normalizeRevalidatePath(routePath)}`;\n}\n\nexport function createRouteDataCacheTag(key: RouteDataCacheKey): string {\n return `route-data:${createRouteDataCacheKey(key)}`;\n}\n\nexport function createRouteDataCacheKey(key: RouteDataCacheKey): string {\n return createFarmCacheKey(Array.isArray(key) ? key : [key]);\n}\n\nexport function normalizeRevalidatePath(routePath: string): string {\n if (typeof routePath !== \"string\") {\n throw new TypeError(\"revalidatePath expects a path string.\");\n }\n\n let normalized = routePath.trim();\n if (!normalized) {\n throw new Error(\"revalidatePath expects a non-empty path.\");\n }\n\n try {\n if (/^https?:\\/\\//.test(normalized)) {\n normalized = new URL(normalized).pathname;\n }\n } catch {\n // Keep the original path if URL parsing fails.\n }\n\n normalized = normalized.split(\"?\")[0] ?? normalized;\n normalized = normalized.startsWith(\"/\") ? normalized : `/${normalized}`;\n normalized = normalized.replace(/\\/{2,}/g, \"/\");\n if (normalized.length > 1) {\n normalized = normalized.replace(/\\/+$/, \"\");\n }\n return normalized || \"/\";\n}\n\nexport function createFarmCacheKey(parts: readonly unknown[]): string {\n return stableSerialize(parts);\n}\n\nfunction normalizeRevalidate(revalidate: number | false | undefined): number | false | undefined {\n if (revalidate === false || revalidate === undefined) {\n return revalidate;\n }\n if (!Number.isFinite(revalidate) || revalidate <= 0) {\n return undefined;\n }\n return revalidate;\n}\n\nfunction normalizeCacheTag(tag: string): string {\n if (typeof tag !== \"string\") {\n throw new TypeError(\"Cache tags must be strings.\");\n }\n const normalized = tag.trim();\n if (!normalized) {\n throw new Error(\"Cache tags cannot be empty.\");\n }\n return normalized;\n}\n\nfunction getFunctionCacheIdentity(fn: Function): string {\n if (fn.name) {\n return `name:${fn.name}`;\n }\n\n let id = functionIds.get(fn);\n if (!id) {\n id = ++nextFunctionId;\n functionIds.set(fn, id);\n }\n return `anonymous:${id}`;\n}\n\nfunction stableSerialize(value: unknown, seen = new WeakSet<object>()): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n\n const valueType = typeof value;\n if (valueType === \"string\") return JSON.stringify(value);\n if (valueType === \"number\" || valueType === \"boolean\" || valueType === \"bigint\") {\n return `${valueType}:${String(value)}`;\n }\n if (valueType === \"symbol\") {\n return `symbol:${String(value)}`;\n }\n if (valueType === \"function\") {\n return `function:${getFunctionCacheIdentity(value as Function)}`;\n }\n\n if (value instanceof Date) {\n return `date:${value.toISOString()}`;\n }\n if (value instanceof URL) {\n return `url:${value.toString()}`;\n }\n if (value instanceof RegExp) {\n return `regexp:${value.toString()}`;\n }\n\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableSerialize(item, seen)).join(\",\")}]`;\n }\n\n if (value && typeof value === \"object\") {\n if (seen.has(value)) {\n return \"[Circular]\";\n }\n seen.add(value);\n\n const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) =>\n a.localeCompare(b),\n );\n const serialized = entries\n .map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`)\n .join(\",\");\n\n seen.delete(value);\n return `{${serialized}}`;\n }\n\n return String(value);\n}\n","import type { FarmI18nClientSnapshot } from \"./types\";\n\ntype SnapshotResolver = () => FarmI18nClientSnapshot | undefined;\n\nconst FARM_I18N_SNAPSHOT_RESOLVER = Symbol.for(\"farm.i18n.snapshotResolver\");\ntype GlobalWithI18nResolver = typeof globalThis & {\n [FARM_I18N_SNAPSHOT_RESOLVER]?: SnapshotResolver;\n};\n\nexport function _setFarmI18nSnapshotResolver(resolver: SnapshotResolver | undefined): void {\n (globalThis as GlobalWithI18nResolver)[FARM_I18N_SNAPSHOT_RESOLVER] = resolver;\n}\n\nexport function getActiveFarmI18nSnapshot(): FarmI18nClientSnapshot | undefined {\n if (typeof window !== \"undefined\" && window.__FARM_I18N__) {\n return window.__FARM_I18N__;\n }\n return (globalThis as GlobalWithI18nResolver)[FARM_I18N_SNAPSHOT_RESOLVER]?.();\n}\n","import type { FarmConfig, FarmContextFactoryInput } from \"./types\";\n\nexport const FARM_ROUTE_CONTEXT_SYMBOL = Symbol.for(\"farm.routeContext\");\n\nexport type FarmRouteContextCarrier<TContext = unknown> = {\n [FARM_ROUTE_CONTEXT_SYMBOL]?: TContext;\n};\n\nexport async function resolveFarmRouteContext(\n config: Pick<FarmConfig, \"context\">,\n input: FarmContextFactoryInput,\n): Promise<unknown> {\n if (typeof config.context !== \"function\") {\n return undefined;\n }\n\n return config.context(input);\n}\n\nexport function withFarmRouteContext<TProps extends object, TContext>(\n props: TProps,\n context: TContext | undefined,\n): TProps & FarmRouteContextCarrier<TContext> {\n if (context === undefined) {\n return props as TProps & FarmRouteContextCarrier<TContext>;\n }\n\n Object.defineProperty(props, FARM_ROUTE_CONTEXT_SYMBOL, {\n value: context,\n enumerable: false,\n configurable: true,\n });\n\n return props as TProps & FarmRouteContextCarrier<TContext>;\n}\n\nexport function getFarmRouteContext<TContext = unknown>(props: unknown): TContext | undefined {\n if (!props || typeof props !== \"object\") {\n return undefined;\n }\n\n return (props as FarmRouteContextCarrier<TContext>)[FARM_ROUTE_CONTEXT_SYMBOL];\n}\n","import { existsSync, readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport {\n PROGRAMMATIC_ROUTE_FILE_NAMES,\n getProgrammaticRouteManifest,\n scanProgrammaticPagePaths,\n type ProgrammaticRouteManifest,\n} from \"./routes\";\n\nexport interface LoadedProgrammaticRouteManifest {\n filePath: string;\n manifest: ProgrammaticRouteManifest;\n}\n\nexport async function loadProgrammaticRouteManifests(options: {\n root: string;\n srcDir?: string;\n loadModule: (filePath: string) => Promise<Record<string, any>>;\n}): Promise<LoadedProgrammaticRouteManifest[]> {\n const manifests: LoadedProgrammaticRouteManifest[] = [];\n\n for (const filePath of findProgrammaticRouteFiles(options.root, options.srcDir)) {\n const mod = await options.loadModule(filePath);\n const manifest = getProgrammaticRouteManifest(mod);\n if (manifest) {\n manifests.push({ filePath, manifest });\n }\n }\n\n return manifests;\n}\n\nexport function findProgrammaticRouteFiles(root: string, srcDir = \"src\"): string[] {\n return findProgrammaticRouteFilesInDir(join(root, srcDir));\n}\n\nexport function findProgrammaticRouteFilesInDir(srcRoot: string): string[] {\n const files: string[] = [];\n\n for (const fileName of PROGRAMMATIC_ROUTE_FILE_NAMES) {\n const filePath = join(srcRoot, fileName);\n if (existsSync(filePath)) {\n files.push(filePath);\n }\n }\n\n return files;\n}\n\nexport async function discoverProgrammaticRoutePaths(\n root: string,\n srcDir = \"src\",\n): Promise<string[]> {\n const paths = new Set<string>();\n const files = new Set([\n ...findProgrammaticRouteFiles(root, srcDir),\n ...(await findProgrammaticRouteSourceFiles(join(root, srcDir))),\n ]);\n\n for (const filePath of files) {\n const source = readFileSync(filePath, \"utf8\");\n for (const routePath of scanProgrammaticPagePaths(source)) {\n paths.add(routePath);\n }\n }\n\n return Array.from(paths).sort();\n}\n\nasync function findProgrammaticRouteSourceFiles(srcRoot: string): Promise<string[]> {\n if (!existsSync(srcRoot)) {\n return [];\n }\n\n try {\n const glob = await import(\"fast-glob\");\n return await glob.default(\"**/*.{ts,tsx,js,jsx}\", {\n cwd: srcRoot,\n absolute: true,\n ignore: [\n \"**/*.d.ts\",\n \"**/node_modules/**\",\n \"**/.*/**\",\n \"farm-routes.d.ts\",\n \"farm-env.d.ts\",\n \"lib/api.generated.ts\",\n ],\n });\n } catch {\n return [];\n }\n}\n","import type {\n FarmConfig,\n ParsedRoute,\n RouteModule,\n LayoutModule,\n SSGCollectionResult,\n} from \"../types\";\nimport {\n parseRoutePath,\n matchRoute,\n resolveAppPath,\n globFiles,\n logger,\n toViteModuleId,\n} from \"../utils\";\nimport { collectSSGPages, resolveRouteRenderingConfigFromFile } from \"../ssg\";\nimport type {\n ProgrammaticPageRoute,\n ProgrammaticLayoutRoute,\n ProgrammaticRedirectRoute,\n ProgrammaticRouteSearchClientOptions,\n} from \"../routes\";\nimport {\n createLayoutModuleFromProgrammaticLayout,\n createProgrammaticRouteModuleId,\n createRouteModuleFromProgrammaticPage,\n getProgrammaticRouteSearchClientOptions,\n parseProgrammaticRoutePath,\n} from \"../routes\";\nimport { loadProgrammaticRouteManifests } from \"../routes.server\";\nimport {\n createFarmMarkdownRouteModuleFromFile,\n isFarmMarkdownPageFile,\n loadFarmMdxComponents,\n resolveMdxConfig,\n} from \"../app-markdown\";\nimport path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { getClientModuleMetadata } from \"../utils/client-component\";\nimport type { MetadataImageKind } from \"../metadata\";\nimport { getFarmSourceRoots, type FarmSourceRoot } from \"../layers\";\nimport {\n inspectStaticMetadataImage,\n isStaticMetadataImageFile,\n type StaticMetadataImageInfo,\n} from \"../static-metadata-image\";\nimport {\n getFarmRouteRuntimeConfig,\n mergeFarmRouteRuntimeConfigs,\n normalizeFarmRouteRuntimeConfig,\n resolveFarmRouteRuleRuntimeConfig,\n resolveFarmRouteRuntimeConfig,\n type ResolvedFarmRouteRuntimeConfig,\n} from \"../route-runtime\";\nimport {\n localizeFarmHref,\n localizeFarmPathname,\n resolveFarmLocalePath,\n stripFarmLocaleFromPathname,\n} from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\n\ninterface RouteEntry {\n route: ParsedRoute;\n modulePath: string;\n pattern: string;\n source?: \"file\" | \"programmatic\";\n sourceRoot: string;\n}\n\ninterface MetadataImageEntry extends RouteEntry {\n kind: MetadataImageKind;\n fileName: \"opengraph-image\" | \"twitter-image\";\n sourceType: \"module\" | \"static\";\n staticInfo?: StaticMetadataImageInfo;\n}\n\ninterface RedirectEntry {\n route: ParsedRoute;\n pattern: string;\n definition: ProgrammaticRedirectRoute;\n}\n\nfunction routeSpecificity(entry: RouteEntry): number {\n return entry.route.segments.reduce((score, segment) => {\n if (!segment.isDynamic) return score + 100;\n if (!segment.isCatchAll) return score + 50;\n return score + (segment.isOptional ? 5 : 10);\n }, entry.route.segments.length);\n}\n\n/**\n * Manages route discovery and matching for the Farm.js application\n */\nexport class RouteManager {\n private config: Required<FarmConfig>;\n private routes: Map<string, RouteEntry> = new Map();\n private layouts: Map<string, RouteEntry> = new Map();\n private loadings: Map<string, RouteEntry> = new Map();\n private errors: Map<string, RouteEntry> = new Map();\n private metadataImages: Map<string, MetadataImageEntry> = new Map();\n private redirects: Map<string, RedirectEntry> = new Map();\n private programmaticPages: Map<string, ProgrammaticPageRoute> = new Map();\n private programmaticLayouts: Map<string, ProgrammaticLayoutRoute> = new Map();\n private viteServer?: ViteDevServer;\n\n constructor(config: Required<FarmConfig>, viteServer?: ViteDevServer) {\n this.config = config;\n this.viteServer = viteServer;\n }\n\n /**\n * Discover all routes in the app directory\n */\n async discoverRoutes(): Promise<void> {\n this.routes.clear();\n this.layouts.clear();\n this.loadings.clear();\n this.errors.clear();\n this.metadataImages.clear();\n this.redirects.clear();\n this.programmaticPages.clear();\n this.programmaticLayouts.clear();\n\n for (const source of getFarmSourceRoots(this.config)) {\n await this.discoverFileRoutes(source);\n await this.discoverProgrammaticRoutes(source);\n }\n\n this.routes = new Map(\n Array.from(this.routes.entries()).sort(\n ([, left], [, right]) => routeSpecificity(right) - routeSpecificity(left),\n ),\n );\n\n // Silent discovery - only log if verbose mode enabled\n if (process.env.FARM_VERBOSE) {\n logger.info(`Discovered ${this.routes.size} pages and ${this.layouts.size} layouts`);\n }\n\n if (process.env.FARM_VERBOSE) {\n this.logRoutes();\n }\n }\n\n /**\n * Find matching route for a given URL path\n */\n matchRoute(pathname: string): {\n route: RouteEntry | null;\n params: Record<string, string>;\n layouts: RouteEntry[];\n } {\n // Remove trailing slash except for root\n const routePathname = this.toRoutePathname(pathname);\n const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n // Find matching page route\n let matchedRoute: RouteEntry | null = null;\n let params: Record<string, string> = {};\n\n for (const routeEntry of this.routes.values()) {\n const match = matchRoute(normalizedPath, routeEntry.route.segments);\n if (match.matches) {\n matchedRoute = routeEntry;\n params = match.params;\n break;\n }\n }\n\n // Find all matching layouts (from root to specific)\n const layouts = this.findMatchingLayouts(normalizedPath);\n\n return {\n route: matchedRoute,\n params,\n layouts,\n };\n }\n\n /**\n * Get all registered routes\n */\n getRoutes(): Map<string, RouteEntry> {\n return new Map(this.routes);\n }\n\n /**\n * Get all registered layouts\n */\n getLayouts(): Map<string, RouteEntry> {\n return new Map(this.layouts);\n }\n\n /** Resolve route rules, inherited layouts, and the page export in precedence order. */\n async resolveRouteRuntimeConfig(pattern: string): Promise<ResolvedFarmRouteRuntimeConfig> {\n const routeEntry = this.routes.get(pattern);\n if (!routeEntry) {\n throw new Error(`Cannot resolve runtime configuration for unknown route \"${pattern}\"`);\n }\n\n const inherited = resolveFarmRouteRuleRuntimeConfig(pattern, this.config.routeRules);\n const layouts = this.findMatchingLayouts(pattern);\n const layoutConfigs = [];\n\n for (const layout of layouts) {\n const layoutModule = await this.loadLayoutModule(layout.modulePath);\n layoutConfigs.push(\n normalizeFarmRouteRuntimeConfig(\n getFarmRouteRuntimeConfig(layoutModule),\n `Layout \"${layout.pattern}\"`,\n ),\n );\n }\n\n const routeModule = await this.loadRouteModule(routeEntry.modulePath);\n const routeConfig = normalizeFarmRouteRuntimeConfig(\n getFarmRouteRuntimeConfig(routeModule),\n `Route \"${pattern}\"`,\n );\n\n return resolveFarmRouteRuntimeConfig(\n mergeFarmRouteRuntimeConfigs(inherited, ...layoutConfigs, routeConfig),\n `Route \"${pattern}\"`,\n );\n }\n\n /**\n * Get all route-level loading boundaries.\n */\n getLoadings(): Map<string, RouteEntry> {\n return new Map(this.loadings);\n }\n\n /**\n * Get all route-level error boundaries.\n */\n getErrors(): Map<string, RouteEntry> {\n return new Map(this.errors);\n }\n\n getMetadataImages(): Map<string, MetadataImageEntry> {\n return new Map(this.metadataImages);\n }\n\n getRedirects(): ProgrammaticRedirectRoute[] {\n return Array.from(this.redirects.values()).map((entry) => entry.definition);\n }\n\n matchRedirect(pathname: string): {\n redirect: ProgrammaticRedirectRoute;\n destination: string;\n statusCode: number;\n params: Record<string, string>;\n } | null {\n const i18n = this.getI18nConfig();\n const localeMatch = i18n ? resolveFarmLocalePath(pathname, i18n) : undefined;\n const routePathname = localeMatch?.pathname || pathname;\n const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n\n for (const redirectEntry of this.redirects.values()) {\n const match = matchRoute(normalizedPath, redirectEntry.route.segments);\n if (!match.matches) continue;\n\n const statusCode =\n redirectEntry.definition.statusCode || (redirectEntry.definition.permanent ? 308 : 307);\n\n return {\n redirect: redirectEntry.definition,\n destination: this.localizeRedirectDestination(\n interpolateRedirectDestination(redirectEntry.definition.destination, match.params),\n localeMatch?.locale,\n ),\n statusCode,\n params: match.params,\n };\n }\n\n return null;\n }\n\n /**\n * Return the nearest matching loading boundary for a pathname.\n */\n getMatchingLoading(pathname: string): RouteEntry | null {\n return this.findNearestBoundary(this.toRoutePathname(pathname), this.loadings);\n }\n\n /**\n * Return the nearest matching error boundary for a pathname.\n */\n getMatchingError(pathname: string): RouteEntry | null {\n return this.findNearestBoundary(this.toRoutePathname(pathname), this.errors);\n }\n\n matchMetadataImage(pathname: string): {\n image: MetadataImageEntry;\n params: Record<string, string>;\n pagePath: string;\n } | null {\n const routePathname = this.toRoutePathname(pathname);\n const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n const suffix = getMetadataImageSuffix(normalizedPath);\n if (!suffix) return null;\n\n const pagePath = normalizedPath.slice(0, -suffix.fileName.length - 1) || \"/\";\n\n for (const imageEntry of this.metadataImages.values()) {\n if (imageEntry.kind !== suffix.kind) continue;\n\n const match = matchRoute(pagePath, imageEntry.route.segments);\n if (!match.matches) continue;\n\n return {\n image: imageEntry,\n params: match.params,\n pagePath,\n };\n }\n\n return null;\n }\n\n getMatchingMetadataImage(\n pathname: string,\n kind: MetadataImageKind,\n ): {\n image: MetadataImageEntry;\n params: Record<string, string>;\n } | null {\n const routePathname = this.toRoutePathname(pathname);\n const normalizedPath = routePathname === \"/\" ? \"/\" : routePathname.replace(/\\/$/, \"\");\n const pathSegments = normalizedPath.split(\"/\").filter(Boolean);\n let bestMatch: {\n image: MetadataImageEntry;\n params: Record<string, string>;\n } | null = null;\n\n for (const imageEntry of this.metadataImages.values()) {\n if (imageEntry.kind !== kind) continue;\n if (imageEntry.route.segments.length > pathSegments.length) continue;\n\n const candidatePath =\n imageEntry.route.segments.length === 0\n ? \"/\"\n : `/${pathSegments.slice(0, imageEntry.route.segments.length).join(\"/\")}`;\n const match = matchRoute(candidatePath, imageEntry.route.segments);\n if (!match.matches) continue;\n\n if (!bestMatch || imageEntry.route.segments.length > bestMatch.image.route.segments.length) {\n bestMatch = {\n image: imageEntry,\n params: match.params,\n };\n }\n }\n\n return bestMatch;\n }\n\n resolveMetadataImagePath(image: MetadataImageEntry, params: Record<string, string> = {}): string {\n const pagePath = routeSegmentsToPath(image.route.segments, params);\n const imagePath = pagePath === \"/\" ? `/${image.fileName}` : `${pagePath}/${image.fileName}`;\n return image.staticInfo ? `${imagePath}?v=${image.staticInfo.hash}` : imagePath;\n }\n\n /**\n * Generate a client-side route manifest for SPA navigation\n * This eliminates the need for server requests during navigation\n */\n generateClientManifest(projectRoot: string): {\n routes: Array<{\n pattern: string;\n modulePath: string;\n shouldHydrate: boolean;\n isClientComponent: boolean;\n search?: ProgrammaticRouteSearchClientOptions;\n segments: Array<{\n segment: string;\n isDynamic: boolean;\n isCatchAll?: boolean;\n isOptional?: boolean;\n }>;\n }>;\n layouts: Array<{\n pattern: string;\n modulePath: string;\n }>;\n } {\n const toUrlPath = (absolutePath: string) => {\n if (absolutePath === projectRoot || absolutePath.startsWith(`${projectRoot}${path.sep}`)) {\n return absolutePath.slice(projectRoot.length);\n }\n if (path.isAbsolute(absolutePath)) {\n const normalized = absolutePath.replace(/\\\\/g, \"/\");\n return normalized.startsWith(\"/\") ? `/@fs${normalized}` : `/@fs/${normalized}`;\n }\n return absolutePath;\n };\n\n const routes = Array.from(this.routes.values()).map((entry) => {\n const metadata = getClientModuleMetadata(entry.modulePath, projectRoot);\n const programmaticPage = this.programmaticPages.get(entry.modulePath);\n return {\n pattern: entry.pattern,\n modulePath: toUrlPath(entry.modulePath),\n shouldHydrate: metadata.shouldHydrate,\n isClientComponent: metadata.isClientComponent,\n search: getProgrammaticRouteSearchClientOptions(programmaticPage?.search),\n segments: entry.route.segments.map((seg) => ({\n segment: seg.segment,\n isDynamic: seg.isDynamic,\n isCatchAll: seg.isCatchAll,\n isOptional: seg.isOptional,\n })),\n };\n });\n\n const layouts = Array.from(this.layouts.values()).map((entry) => ({\n pattern: entry.pattern,\n modulePath: toUrlPath(entry.modulePath),\n }));\n\n return { routes, layouts };\n }\n\n /**\n * Load a route module dynamically\n */\n async loadRouteModule(modulePath: string): Promise<RouteModule> {\n try {\n const programmaticPage = this.programmaticPages.get(modulePath);\n if (programmaticPage) {\n return createRouteModuleFromProgrammaticPage(programmaticPage);\n }\n\n if (isFarmMarkdownPageFile(modulePath)) {\n const mdxConfig = resolveMdxConfig(this.config.mdx);\n const components = await loadFarmMdxComponents(mdxConfig, {\n root: this.config.root,\n loadModule: this.viteServer\n ? (componentModulePath) => this.viteServer!.ssrLoadModule(componentModulePath)\n : undefined,\n });\n return await createFarmMarkdownRouteModuleFromFile(modulePath, {\n components,\n config: mdxConfig,\n });\n }\n\n if (this.viteServer) {\n const module = await this.viteServer.ssrLoadModule(modulePath);\n return module as RouteModule;\n } else {\n const module = await import(/* @vite-ignore */ modulePath);\n return module as RouteModule;\n }\n } catch (error) {\n logger.error(`Failed to load route module: ${modulePath}`);\n throw error;\n }\n }\n\n /**\n * Load a layout module dynamically\n */\n async loadLayoutModule(modulePath: string): Promise<LayoutModule> {\n try {\n const programmaticLayout = this.programmaticLayouts.get(modulePath);\n if (programmaticLayout) {\n return createLayoutModuleFromProgrammaticLayout(programmaticLayout) as LayoutModule;\n }\n\n if (this.viteServer) {\n const module = await this.viteServer.ssrLoadModule(modulePath);\n return module as LayoutModule;\n } else {\n const module = await import(/* @vite-ignore */ modulePath);\n return module as LayoutModule;\n }\n } catch (error) {\n logger.error(`Failed to load layout module: ${modulePath}`);\n throw error;\n }\n }\n\n /**\n * Create a route pattern from parsed route\n */\n private createRoutePattern(route: ParsedRoute): string {\n if (route.segments.length === 0) return \"/\";\n\n return (\n \"/\" +\n route.segments\n .map((segment) => {\n if (!segment.isDynamic) return segment.segment;\n\n if (segment.isCatchAll) {\n return segment.isOptional ? `[[...${segment.segment}]]` : `[...${segment.segment}]`;\n }\n\n return `[${segment.segment}]`;\n })\n .join(\"/\")\n );\n }\n\n private async discoverFileRoutes(source: FarmSourceRoot): Promise<void> {\n const appDir = resolveAppPath(source.root, source.srcDir, \"app\");\n const pageFiles = await safeGlobFiles(\"**/page.{ts,tsx,js,jsx,md,mdx}\", appDir);\n const layoutFiles = await safeGlobFiles(\"**/layout.{ts,tsx,js,jsx}\", appDir);\n const loadingFiles = await safeGlobFiles(\"**/loading.{ts,tsx,js,jsx}\", appDir);\n const errorFiles = await safeGlobFiles(\"**/error.{ts,tsx,js,jsx}\", appDir);\n const metadataImageFiles = await safeGlobFiles(\n \"**/{opengraph-image,twitter-image}.{ts,tsx,js,jsx,png,jpg,jpeg,gif,webp}\",\n appDir,\n );\n\n for (const [kind, files, target] of [\n [\"page\", pageFiles, this.routes],\n [\"layout\", layoutFiles, this.layouts],\n [\"loading\", loadingFiles, this.loadings],\n [\"error\", errorFiles, this.errors],\n ] as const) {\n for (const file of files) {\n const route = parseRoutePath(file);\n const modulePath = path.join(appDir, file);\n const pattern = this.createRoutePattern(route);\n const existing = target.get(pattern);\n if (existing?.sourceRoot === source.root) {\n throw new Error(\n `Duplicate ${kind} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}.`,\n );\n }\n target.set(pattern, {\n route,\n modulePath,\n pattern,\n source: \"file\",\n sourceRoot: source.root,\n });\n }\n }\n\n for (const file of metadataImageFiles) {\n const fileBase = path.basename(file, path.extname(file));\n const kind: MetadataImageKind = fileBase === \"twitter-image\" ? \"twitter\" : \"opengraph\";\n const fileName = kind === \"twitter\" ? \"twitter-image\" : \"opengraph-image\";\n const route = parseRoutePath(file);\n const modulePath = path.join(appDir, file);\n const pattern = this.createRoutePattern(route);\n const key = `${kind}:${pattern}`;\n const existing = this.metadataImages.get(key);\n const sourceType = isStaticMetadataImageFile(file) ? \"static\" : \"module\";\n\n if (existing?.sourceRoot === source.root) {\n throw new Error(\n `Duplicate ${fileName} route \"${pattern}\". Found both ${existing.modulePath} and ${modulePath}. Keep only one static image or module per route segment.`,\n );\n }\n\n const staticInfo =\n sourceType === \"static\" ? await inspectStaticMetadataImage(modulePath) : undefined;\n\n this.metadataImages.set(key, {\n route,\n modulePath,\n pattern,\n kind,\n fileName,\n sourceType,\n staticInfo,\n source: \"file\",\n sourceRoot: source.root,\n });\n }\n }\n\n private async discoverProgrammaticRoutes(source: FarmSourceRoot): Promise<void> {\n const manifests = await loadProgrammaticRouteManifests({\n root: source.root,\n srcDir: source.srcDir,\n loadModule: (filePath) => this.loadProgrammaticRoutesModule(filePath),\n });\n\n for (const { filePath, manifest } of manifests) {\n for (const definition of manifest.routes) {\n if (definition.kind === \"page\") {\n const route = parseProgrammaticRoutePath(definition.path, \"page\");\n const pattern = this.createRoutePattern(route);\n const existing = this.routes.get(pattern);\n\n if (existing?.sourceRoot === source.root) {\n throw new Error(\n `Duplicate page route \"${pattern}\". Found both ${existing.modulePath} and programmatic route in ${filePath}.`,\n );\n }\n\n const modulePath = createProgrammaticRouteModuleId(filePath, \"page\", definition.path);\n this.programmaticPages.set(modulePath, definition);\n this.routes.set(pattern, {\n route,\n modulePath,\n pattern,\n source: \"programmatic\",\n sourceRoot: source.root,\n });\n }\n\n if (definition.kind === \"layout\") {\n const route = parseProgrammaticRoutePath(definition.path, \"layout\");\n const pattern = this.createRoutePattern(route);\n const existing = this.layouts.get(pattern);\n if (existing?.sourceRoot === source.root) {\n throw new Error(\n `Duplicate layout route \"${pattern}\". Found both ${existing.modulePath} and programmatic route in ${filePath}.`,\n );\n }\n const modulePath = createProgrammaticRouteModuleId(filePath, \"layout\", definition.path);\n this.programmaticLayouts.set(modulePath, definition);\n this.layouts.set(pattern, {\n route,\n modulePath,\n pattern,\n source: \"programmatic\",\n sourceRoot: source.root,\n });\n }\n\n if (definition.kind === \"redirect\") {\n const route = parseProgrammaticRoutePath(definition.source, \"page\");\n const pattern = this.createRoutePattern(route);\n this.redirects.set(pattern, {\n route,\n pattern,\n definition,\n });\n }\n }\n }\n }\n\n private async loadProgrammaticRoutesModule(filePath: string): Promise<Record<string, any>> {\n if (this.viteServer) {\n const viteRoot = this.viteServer.config?.root || this.config.root || process.cwd();\n return await this.viteServer.ssrLoadModule(toViteModuleId(filePath, viteRoot));\n }\n\n const fileUrl = `file://${filePath}`;\n return await import(/* @vite-ignore */ fileUrl);\n }\n\n /**\n * Find all layouts that should wrap a given path\n */\n private findMatchingLayouts(pathname: string): RouteEntry[] {\n const matchingLayouts: RouteEntry[] = [];\n const pathSegments = pathname.split(\"/\").filter(Boolean);\n\n const sortedLayouts = Array.from(this.layouts.values()).sort((a, b) => {\n return a.route.segments.length - b.route.segments.length;\n });\n\n for (const layoutEntry of sortedLayouts) {\n if (layoutEntry.route.segments.length > pathSegments.length) {\n continue;\n }\n\n let matches = true;\n for (let i = 0; i < layoutEntry.route.segments.length; i++) {\n const segment = layoutEntry.route.segments[i];\n if (!segment.isDynamic && segment.segment !== pathSegments[i]) {\n matches = false;\n break;\n }\n }\n\n if (matches) {\n matchingLayouts.push(layoutEntry);\n }\n }\n\n return matchingLayouts;\n }\n\n private findNearestBoundary(\n pathname: string,\n boundaries: Map<string, RouteEntry>,\n ): RouteEntry | null {\n const normalizedPath = pathname === \"/\" ? \"/\" : pathname.replace(/\\/$/, \"\");\n const pathSegments = normalizedPath.split(\"/\").filter(Boolean);\n let bestMatch: RouteEntry | null = null;\n\n for (const boundaryEntry of boundaries.values()) {\n if (boundaryEntry.route.segments.length > pathSegments.length) {\n continue;\n }\n\n let matches = true;\n for (let i = 0; i < boundaryEntry.route.segments.length; i++) {\n const segment = boundaryEntry.route.segments[i];\n const pathSegment = pathSegments[i];\n\n if (!pathSegment) {\n matches = false;\n break;\n }\n\n if (!segment.isDynamic && segment.segment !== pathSegment) {\n matches = false;\n break;\n }\n }\n\n if (!matches) {\n continue;\n }\n\n if (!bestMatch || boundaryEntry.route.segments.length > bestMatch.route.segments.length) {\n bestMatch = boundaryEntry;\n }\n }\n\n return bestMatch;\n }\n\n /**\n * Log discovered routes for debugging\n */\n private logRoutes(): void {\n if (this.routes.size > 0) {\n logger.info(\"Registered routes:\");\n for (const [pattern, entry] of this.routes) {\n console.log(` ${pattern} -> ${entry.modulePath}`);\n }\n }\n\n if (this.layouts.size > 0) {\n logger.info(\"Registered layouts:\");\n for (const [pattern, entry] of this.layouts) {\n console.log(` ${pattern} -> ${entry.modulePath}`);\n }\n }\n }\n\n /**\n * Collect SSG pages for static generation\n *\n * Returns all pages marked with `export const ssg = true` along with\n * their pre-computed paths (for dynamic routes using getStaticPaths)\n */\n async collectSSGPages(): Promise<SSGCollectionResult> {\n const routes = Array.from(this.routes.values()).map((entry) => ({\n path: entry.pattern,\n filePath: entry.modulePath,\n isDynamic: entry.route.segments.some((seg) => seg.isDynamic),\n pattern: entry.pattern,\n }));\n\n const result = await collectSSGPages(routes, (filePath) => this.loadRouteModule(filePath));\n const i18n = this.getI18nConfig();\n if (!i18n) {\n return result;\n }\n\n // A single static URL cannot safely vary by cookie or Accept-Language.\n // Keep locale-without-prefix pages dynamic so caches never pin one language.\n if (i18n.routing === \"none\") {\n return {\n ssg: [],\n ssr: Array.from(new Set([...result.ssr, ...result.ssg.map((page) => page.urlPath)])),\n };\n }\n\n return {\n ssg: result.ssg.flatMap((page) =>\n i18n.locales.map((locale) => ({\n ...page,\n urlPath: localizeFarmPathname(page.urlPath, locale, i18n),\n })),\n ),\n ssr: result.ssr.flatMap((routePath) =>\n i18n.locales.map((locale) => localizeFarmPathname(routePath, locale, i18n)),\n ),\n };\n }\n\n private toRoutePathname(pathname: string): string {\n const i18n = this.getI18nConfig();\n return i18n ? stripFarmLocaleFromPathname(pathname, i18n) : pathname;\n }\n\n private localizeRedirectDestination(destination: string, locale?: string): string {\n if (!locale || !destination.startsWith(\"/\") || destination.startsWith(\"//\")) {\n return destination;\n }\n const i18n = this.getI18nConfig();\n return i18n ? localizeFarmHref(destination, locale, i18n) : destination;\n }\n\n private getI18nConfig(): ResolvedFarmI18nConfig | undefined {\n const i18n = this.config.i18n;\n return i18n && typeof i18n === \"object\" && \"enabled\" in i18n && i18n.enabled ? i18n : undefined;\n }\n\n /**\n * Check if a route is SSG\n */\n async isRouteSSG(modulePath: string): Promise<boolean> {\n try {\n const mod = await this.loadRouteModule(modulePath);\n const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n return rendering.ssg;\n } catch {\n return false;\n }\n }\n\n /**\n * Check if a route has ISR (Incremental Static Regeneration)\n */\n async hasRouteISR(modulePath: string): Promise<boolean> {\n try {\n const mod = await this.loadRouteModule(modulePath);\n const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n return rendering.ssg && typeof rendering.revalidate === \"number\" && rendering.revalidate > 0;\n } catch {\n return false;\n }\n }\n\n /**\n * Get revalidation interval for a route\n */\n async getRouteRevalidateInterval(modulePath: string): Promise<number | undefined> {\n try {\n const mod = await this.loadRouteModule(modulePath);\n const rendering = await resolveRouteRenderingConfigFromFile(mod, modulePath);\n return rendering.revalidate;\n } catch {\n return undefined;\n }\n }\n}\n\nfunction interpolateRedirectDestination(\n destination: string,\n params: Record<string, string>,\n): string {\n let result = destination;\n\n for (const [key, value] of Object.entries(params)) {\n result = replaceAll(result, `[...${key}]`, value);\n result = replaceAll(result, `[[...${key}]]`, value);\n result = replaceAll(result, `[${key}]`, value);\n result = replaceAll(result, `:${key}*`, value);\n result = replaceAll(result, `:${key}`, value);\n }\n\n return result;\n}\n\nfunction getMetadataImageSuffix(pathname: string): {\n kind: MetadataImageKind;\n fileName: MetadataImageEntry[\"fileName\"];\n} | null {\n if (pathname === \"/opengraph-image\" || pathname.endsWith(\"/opengraph-image\")) {\n return { kind: \"opengraph\", fileName: \"opengraph-image\" };\n }\n\n if (pathname === \"/twitter-image\" || pathname.endsWith(\"/twitter-image\")) {\n return { kind: \"twitter\", fileName: \"twitter-image\" };\n }\n\n return null;\n}\n\nfunction routeSegmentsToPath(\n segments: ParsedRoute[\"segments\"],\n params: Record<string, string>,\n): string {\n if (segments.length === 0) return \"/\";\n\n const parts: string[] = [];\n for (const segment of segments) {\n if (!segment.isDynamic) {\n parts.push(segment.segment);\n continue;\n }\n\n const value = params[segment.segment];\n if (!value && segment.isOptional) continue;\n if (!value) {\n parts.push(`[${segment.segment}]`);\n continue;\n }\n\n parts.push(...value.split(\"/\").map((part) => encodeURIComponent(part)));\n }\n\n return `/${parts.join(\"/\")}`;\n}\n\nfunction replaceAll(input: string, search: string, replacement: string): string {\n return input.split(search).join(replacement);\n}\n\nasync function safeGlobFiles(pattern: string, cwd: string): Promise<string[]> {\n try {\n return await globFiles(pattern, cwd);\n } catch {\n return [];\n }\n}\n","import fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nfunction readIfExists(filePath: string): string | null {\n try {\n if (!filePath || !fs.existsSync(filePath)) {\n return null;\n }\n return fs.readFileSync(filePath, \"utf-8\");\n } catch {\n return null;\n }\n}\n\nexport function resolveModuleSourcePath(modulePath: string, root?: string): string | null {\n const candidates = new Set<string>();\n const withoutQuery = modulePath.split(\"?\")[0];\n\n if (modulePath) {\n candidates.add(modulePath);\n candidates.add(withoutQuery);\n\n if (modulePath.startsWith(\"file://\")) {\n try {\n candidates.add(fileURLToPath(modulePath));\n } catch {\n // ignore invalid file urls\n }\n }\n\n if (modulePath.startsWith(\"/@fs/\")) {\n candidates.add(modulePath.slice(4));\n }\n }\n\n if (root && modulePath) {\n const normalized = withoutQuery.replace(/^\\/+/, \"\");\n candidates.add(path.join(root, normalized));\n candidates.add(path.resolve(root, normalized));\n }\n\n if (withoutQuery?.startsWith(\"/src/\")) {\n const normalized = withoutQuery.replace(/^\\/+/, \"\");\n candidates.add(path.join(process.cwd(), normalized));\n candidates.add(path.resolve(process.cwd(), normalized));\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return null;\n}\n\nexport interface ClientModuleMetadata {\n isClientComponent: boolean;\n shouldHydrate: boolean;\n}\n\ninterface ParsedClientModuleMetadata {\n isClientComponent: boolean;\n hasHydrateExport: boolean;\n}\n\nconst RESOLVABLE_SOURCE_EXTENSIONS = [\n \".tsx\",\n \".ts\",\n \".jsx\",\n \".js\",\n \".mts\",\n \".mjs\",\n \".cts\",\n \".cjs\",\n] as const;\n\nexport function hasUseClientDirective(content: string | null): boolean {\n if (!content) {\n return false;\n }\n const normalized = content.trimStart();\n return normalized.startsWith(\"'use client'\") || normalized.startsWith('\"use client\"');\n}\n\nexport function hasHydrateExport(content: string | null): boolean {\n if (!content) {\n return false;\n }\n return (\n /\\bexport\\s+const\\s+hydrate\\s*=\\s*true\\b/.test(content) ||\n /\\bexport\\s*\\{\\s*hydrate\\s*\\}\\b/.test(content)\n );\n}\n\nexport function stripUseClientDirective(content: string): string {\n return content.replace(/^\\s*([\"'])use client\\1\\s*;?\\s*/, \"\");\n}\n\nfunction parseClientModuleMetadata(content: string | null): ParsedClientModuleMetadata {\n if (!content) {\n return {\n isClientComponent: false,\n hasHydrateExport: false,\n };\n }\n\n return {\n isClientComponent: hasUseClientDirective(content),\n hasHydrateExport: hasHydrateExport(content),\n };\n}\n\nexport function getClientModuleMetadata(modulePath: string, root?: string): ClientModuleMetadata {\n const resolvedPath = resolveModuleSourcePath(modulePath, root);\n return inspectClientModuleMetadata(resolvedPath, root, new Set());\n}\n\nexport function isClientComponentModule(modulePath: string, root?: string): boolean {\n return getClientModuleMetadata(modulePath, root).isClientComponent;\n}\n\nexport function shouldHydrateModule(modulePath: string, root?: string): boolean {\n return getClientModuleMetadata(modulePath, root).shouldHydrate;\n}\n\nfunction inspectClientModuleMetadata(\n resolvedPath: string | null,\n root: string | undefined,\n visited: Set<string>,\n): ClientModuleMetadata {\n if (!resolvedPath || visited.has(resolvedPath)) {\n return {\n isClientComponent: false,\n shouldHydrate: false,\n };\n }\n\n visited.add(resolvedPath);\n\n const content = readIfExists(resolvedPath);\n const parsed = parseClientModuleMetadata(content);\n if (parsed.isClientComponent) {\n return {\n isClientComponent: true,\n shouldHydrate: true,\n };\n }\n\n let importsClientBoundary = false;\n for (const specifier of getRelativeImportSpecifiers(content)) {\n const importedPath = resolveImportedModuleSourcePath(resolvedPath, specifier, root);\n const importedMetadata = inspectClientModuleMetadata(importedPath, root, visited);\n if (importedMetadata.isClientComponent || importedMetadata.shouldHydrate) {\n importsClientBoundary = true;\n break;\n }\n }\n\n return {\n isClientComponent: false,\n shouldHydrate: parsed.hasHydrateExport || importsClientBoundary,\n };\n}\n\nfunction getRelativeImportSpecifiers(content: string | null): string[] {\n if (!content) {\n return [];\n }\n\n const pattern =\n /(?:^|\\n)\\s*(?:import|export)\\s+(?:type\\s+)?(?:[^\"'`]+?\\s+from\\s+)?[\"']([^\"']+)[\"']/g;\n const matches = new Set<string>();\n for (const match of content.matchAll(pattern)) {\n const specifier = match[1];\n if (!specifier || (!specifier.startsWith(\".\") && !specifier.startsWith(\"/\"))) {\n continue;\n }\n matches.add(specifier);\n }\n return Array.from(matches);\n}\n\nfunction resolveImportedModuleSourcePath(\n importerPath: string,\n specifier: string,\n root?: string,\n): string | null {\n const candidates = new Set<string>();\n const basePath = specifier.startsWith(\".\")\n ? path.resolve(path.dirname(importerPath), specifier)\n : root\n ? path.resolve(root, specifier.replace(/^\\/+/, \"\"))\n : path.resolve(specifier);\n\n candidates.add(basePath);\n for (const extension of RESOLVABLE_SOURCE_EXTENSIONS) {\n candidates.add(`${basePath}${extension}`);\n candidates.add(path.join(basePath, `index${extension}`));\n }\n\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return null;\n}\n","import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { imageSize } from \"image-size\";\n\nexport const STATIC_METADATA_IMAGE_EXTENSIONS = [\"png\", \"jpg\", \"jpeg\", \"gif\", \"webp\"] as const;\n\nexport type StaticMetadataImageExtension = (typeof STATIC_METADATA_IMAGE_EXTENSIONS)[number];\n\nexport interface StaticMetadataImageInfo {\n extension: StaticMetadataImageExtension;\n contentType: string;\n width: number;\n height: number;\n alt?: string;\n hash: string;\n byteLength: number;\n}\n\nconst CONTENT_TYPES: Record<StaticMetadataImageExtension, string> = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n gif: \"image/gif\",\n webp: \"image/webp\",\n};\n\nexport function isStaticMetadataImageFile(filePath: string): boolean {\n return getStaticMetadataImageExtension(filePath) !== null;\n}\n\nexport async function inspectStaticMetadataImage(\n filePath: string,\n): Promise<StaticMetadataImageInfo> {\n const extension = getStaticMetadataImageExtension(filePath);\n if (!extension) {\n throw new Error(`Unsupported static metadata image: ${filePath}`);\n }\n\n const bytes = await readFile(filePath);\n let dimensions: ReturnType<typeof imageSize>;\n\n try {\n dimensions = imageSize(bytes);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(`Could not read metadata image ${filePath}: ${reason}`);\n }\n\n if (!dimensions.width || !dimensions.height) {\n throw new Error(`Could not determine metadata image dimensions for ${filePath}`);\n }\n\n const alt = await readAltText(filePath);\n\n return {\n extension,\n contentType: CONTENT_TYPES[extension],\n width: dimensions.width,\n height: dimensions.height,\n alt,\n hash: createHash(\"sha256\").update(bytes).digest(\"hex\").slice(0, 16),\n byteLength: bytes.byteLength,\n };\n}\n\nexport function getStaticMetadataImageAltPath(filePath: string): string {\n return path.join(\n path.dirname(filePath),\n `${path.basename(filePath, path.extname(filePath))}.alt.txt`,\n );\n}\n\nfunction getStaticMetadataImageExtension(filePath: string): StaticMetadataImageExtension | null {\n const extension = path.extname(filePath).slice(1).toLowerCase();\n return STATIC_METADATA_IMAGE_EXTENSIONS.includes(extension as StaticMetadataImageExtension)\n ? (extension as StaticMetadataImageExtension)\n : null;\n}\n\nasync function readAltText(filePath: string): Promise<string | undefined> {\n try {\n const value = (await readFile(getStaticMetadataImageAltPath(filePath), \"utf8\")).trim();\n return value || undefined;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return undefined;\n }\n throw error;\n }\n}\n","import type { FarmI18nDirection, FarmI18nRouting, ResolvedFarmI18nConfig } from \"./types\";\n\nexport interface FarmLocalePathConfig {\n locales: readonly string[];\n defaultLocale: string;\n routing: FarmI18nRouting;\n}\n\nexport interface FarmLocalePathMatch {\n locale?: string;\n pathname: string;\n explicit: boolean;\n}\n\nconst RTL_LANGUAGES = new Set([\n \"ar\",\n \"arc\",\n \"ckb\",\n \"dv\",\n \"fa\",\n \"he\",\n \"ku\",\n \"nqo\",\n \"ps\",\n \"sd\",\n \"syr\",\n \"ug\",\n \"ur\",\n \"yi\",\n]);\n\nexport function resolveFarmLocalePath(\n pathname: string,\n config: FarmLocalePathConfig,\n): FarmLocalePathMatch {\n const normalized = normalizePathname(pathname);\n if (config.routing === \"none\") {\n return { pathname: normalized, explicit: false };\n }\n\n const segments = normalized.split(\"/\").filter(Boolean);\n const firstSegment = segments[0];\n const locale = config.locales.find(\n (candidate) => candidate.toLowerCase() === firstSegment?.toLowerCase(),\n );\n if (!locale) {\n return { pathname: normalized, explicit: false };\n }\n\n const remaining = segments.slice(1);\n return {\n locale,\n pathname: remaining.length > 0 ? `/${remaining.join(\"/\")}` : \"/\",\n explicit: true,\n };\n}\n\nexport function stripFarmLocaleFromPathname(\n pathname: string,\n config: FarmLocalePathConfig,\n): string {\n return resolveFarmLocalePath(pathname, config).pathname;\n}\n\nexport function localizeFarmPathname(\n pathname: string,\n locale: string,\n config: FarmLocalePathConfig,\n): string {\n const internalPathname = resolveFarmLocalePath(pathname, config).pathname;\n if (config.routing === \"none\") return internalPathname;\n if (config.routing === \"prefix-except-default\" && locale === config.defaultLocale) {\n return internalPathname;\n }\n return internalPathname === \"/\" ? `/${locale}` : `/${locale}${internalPathname}`;\n}\n\nexport function localizeFarmHref(\n href: string,\n locale: string,\n config: FarmLocalePathConfig,\n): string {\n if (!href.startsWith(\"/\") || href.startsWith(\"//\")) return href;\n const url = new URL(href, \"http://farm.local\");\n url.pathname = localizeFarmPathname(url.pathname, locale, config);\n return `${url.pathname}${url.search}${url.hash}`;\n}\n\nexport function getFarmLocaleDirection(\n locale: string,\n direction: ResolvedFarmI18nConfig[\"direction\"] | undefined,\n): FarmI18nDirection {\n const configured = direction?.[locale];\n if (configured) return configured;\n const language = locale.split(\"-\")[0]?.toLowerCase() || locale.toLowerCase();\n return RTL_LANGUAGES.has(language) ? \"rtl\" : \"ltr\";\n}\n\nfunction normalizePathname(pathname: string): string {\n const withLeadingSlash = pathname.startsWith(\"/\") ? pathname : `/${pathname}`;\n if (withLeadingSlash === \"/\") return \"/\";\n return withLeadingSlash.replace(/\\/{2,}/g, \"/\").replace(/\\/$/, \"\") || \"/\";\n}\n","import React from \"react\";\nimport { renderToPipeableStream, renderToStaticMarkup } from \"react-dom/server\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type {\n FarmConfig,\n FarmRequest,\n FarmResponse,\n LoadingProps,\n PageProps,\n RouteModule,\n SSGPage,\n} from \"../types\";\nimport type { RouteManager } from \"../routing/route-manager\";\nimport { logger } from \"../utils\";\nimport { getClientModuleMetadata } from \"../utils/client-component\";\nimport { Writable } from \"stream\";\nimport {\n _clearCurrentMiddlewareContext,\n _clearCurrentMiddlewareData,\n _runWithMiddlewareContext,\n _runWithMiddlewareData,\n} from \"../middleware/server\";\nimport { getRequestContextSnapshot } from \"../request-context\";\nimport { matchSSGPage, resolveRouteRenderingConfigFromFile } from \"../ssg\";\nimport { getIntegrationProviders, getRegisteredIntegrationAPIManifest } from \"../integrations\";\nimport { _runWithCurrentRequest, createWebRequestFromFarmRequest } from \"./request\";\nimport { createFarmCacheKey, getFarmDataCache, normalizeRevalidatePath } from \"../cache\";\nimport { emitFarmEvent } from \"../observability\";\nimport { getFarmRedirectError, isFarmNotFoundError, isFarmRedirectError } from \"../navigation\";\nimport {\n addMetadataImageReference,\n mergeMetadata,\n renderMetadataHead,\n type FarmMetadataImageReference,\n type MetadataImageKind,\n} from \"../metadata\";\nimport { resolveFarmRouteContext, withFarmRouteContext } from \"../route-context\";\nimport { prepareDeferredData, snapshotDeferredData, type DeferredRecord } from \"../deferred\";\nimport { createFarmDeploymentCookie, FARM_DEPLOYMENT_ID_HEADER } from \"../deployment\";\nimport type { StaticMetadataImageInfo } from \"../static-metadata-image\";\nimport {\n _runWithFarmI18nRequest,\n getFarmI18nClientSnapshot,\n type FarmI18nClientSnapshot,\n type FarmI18nRuntime,\n} from \"../i18n/server\";\nimport { createFarmLocaleCookie, getFarmLocaleVaryHeaders } from \"../i18n/resolver\";\nimport { localizeFarmHref, localizeFarmPathname } from \"../i18n/routing\";\n\nlet cachedClerkProvider: {\n ClerkProvider: React.ComponentType<{ children?: React.ReactNode } & Record<string, unknown>>;\n} | null = null;\n\nconst importRuntimeModule = new Function(\"specifier\", \"return import(specifier);\") as (\n specifier: string,\n) => Promise<any>;\n\ninterface CachedSSGPage {\n html: string;\n document: boolean;\n}\n\ninterface CachedPPRShell {\n html: string;\n}\n\ninterface PPRShellCacheOptions {\n pathname: string;\n search: string;\n revalidate?: number;\n}\n\nfunction hasRequestHeader(req: FarmRequest, name: string): boolean {\n const value = req.headers[name.toLowerCase()];\n return Array.isArray(value) ? value.length > 0 : Boolean(value);\n}\n\nfunction serializeInlineValue(value: unknown): string {\n return JSON.stringify(value)\n .replace(/</g, \"\\\\u003c\")\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction escapeHtmlAttribute(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n}\n\nfunction appendResponseHeader(res: FarmResponse, name: string, value: string): void {\n const current = res.getHeader(name);\n if (current === undefined) {\n res.setHeader(name, value);\n } else if (Array.isArray(current)) {\n res.setHeader(name, [...current.map(String), value]);\n } else {\n res.setHeader(name, [String(current), value]);\n }\n}\n\nfunction appendResponseVary(res: FarmResponse, value: string): void {\n const current = res.getHeader(\"Vary\");\n const values = new Set(\n (Array.isArray(current) ? current.join(\",\") : String(current || \"\"))\n .split(\",\")\n .map((entry) => entry.trim())\n .filter(Boolean),\n );\n values.add(value);\n res.setHeader(\"Vary\", Array.from(values).join(\", \"));\n}\n\nfunction renderI18nAlternateLinks(requestPath: string, snapshot: FarmI18nClientSnapshot): string {\n if (snapshot.routing === \"none\") return \"\";\n const url = new URL(requestPath, \"http://farm.local\");\n const links = snapshot.locales.map((locale) => {\n const href = localizeFarmPathname(url.pathname, locale, snapshot);\n return `<link rel=\"alternate\" hreflang=\"${escapeHtmlAttribute(locale)}\" href=\"${escapeHtmlAttribute(href)}\">`;\n });\n links.push(\n `<link rel=\"alternate\" hreflang=\"x-default\" href=\"${escapeHtmlAttribute(\n localizeFarmPathname(url.pathname, snapshot.defaultLocale, snapshot),\n )}\">`,\n );\n return links.join(\"\");\n}\n\nfunction findPPRDynamicChunkIndex(chunk: string): number {\n const markerIndexes = [\n chunk.indexOf('id=\"S:'),\n chunk.indexOf(\"id='S:\"),\n chunk.indexOf(\"$RC(\"),\n chunk.indexOf(\"$RS(\"),\n chunk.indexOf(\"$RV(\"),\n chunk.indexOf(\"$RX(\"),\n ].filter((index) => index >= 0);\n\n if (markerIndexes.length === 0) {\n return -1;\n }\n\n const markerIndex = Math.min(...markerIndexes);\n const tagStart = chunk.lastIndexOf(\"<\", markerIndex);\n return tagStart >= 0 ? tagStart : markerIndex;\n}\n\nfunction createPPRRefreshScript(): string {\n return `<script>(function(){if(window.__FARM_PPR_REFRESHING__)return;window.__FARM_PPR_REFRESHING__=true;function replaceRoot(html){var doc=new DOMParser().parseFromString(html,\"text/html\");var next=doc.getElementById(\"root\");var current=document.getElementById(\"root\");if(!next||!current)return;current.innerHTML=next.innerHTML;}fetch(window.location.href,{credentials:\"same-origin\",headers:{\"x-farm-ppr-refresh\":\"1\"}}).then(function(response){return response.ok?response.text():null;}).then(function(html){if(html)replaceRoot(html);}).catch(function(){});})();</script>`;\n}\n\nfunction createPreHydrationClickQueueScript(): string {\n return `<script>(function(){if(window.__FARM_PREHYDRATION_CLICK_QUEUE__)return;var queue=[];window.__FARM_PREHYDRATION_CLICK_QUEUE__=queue;window.__FARM_HYDRATED__=false;document.documentElement.dataset.farmHydrated=\"false\";function isModified(event){return !!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}function closestQueuedTarget(target){while(target&&target!==document.documentElement){if(target.matches&&target.matches('button,[role=\"button\"],input[type=\"button\"],input[type=\"submit\"],input[type=\"reset\"]'))return target;target=target.parentElement}return null}document.addEventListener(\"click\",function(event){if(window.__FARM_HYDRATED__)return;if(event.defaultPrevented||event.button!==0||isModified(event))return;var target=closestQueuedTarget(event.target);if(!target||target.closest&&target.closest(\"a[href]\"))return;if(queue.some(function(item){return item.target===target}))return;queue.push({target:target,createdAt:Date.now()});event.preventDefault();event.stopImmediatePropagation()},true);})();</script>`;\n}\n\nfunction searchParamsToObject(\n searchParams: URLSearchParams,\n): Record<string, string | string[] | undefined> {\n const output: Record<string, string | string[] | undefined> = {};\n\n searchParams.forEach((value, key) => {\n const existing = output[key];\n if (existing) {\n if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n output[key] = [existing, value];\n }\n } else {\n output[key] = value;\n }\n });\n\n return output;\n}\n\nfunction createDocumentFooter(options: {\n suspenseRevealFallback: string;\n refreshPPR?: boolean;\n deferredHydrationScript?: string;\n}): string {\n return `</div>\n ${options.suspenseRevealFallback}\n ${options.refreshPPR ? createPPRRefreshScript() : \"\"}\n ${options.deferredHydrationScript || \"\"}\n <script type=\"module\" src=\"/@farm/client.js\"></script>\n</body>\n</html>`;\n}\n\nfunction createDeferredHydrationScript(records: readonly DeferredRecord[]): string {\n if (records.length === 0) return \"\";\n return `<script>window.__FARM_DEFERRED_DATA__=${serializeInlineValue(\n snapshotDeferredData(records),\n )};</script>`;\n}\n\nfunction toMiddlewareMap(input: unknown): Map<string, any> {\n if (input instanceof Map) {\n return new Map(input as Map<string, any>);\n }\n if (input && typeof input === \"object\") {\n return new Map(Object.entries(input as Record<string, any>));\n }\n return new Map<string, any>();\n}\n\nfunction isWebResponse(value: unknown): value is Response {\n return (\n typeof Response !== \"undefined\" &&\n value instanceof Response &&\n typeof value.arrayBuffer === \"function\"\n );\n}\n\nclass FarmRouteErrorBoundary extends React.Component<\n {\n Fallback: React.ComponentType<any>;\n fallbackProps: Record<string, any>;\n children: React.ReactNode;\n },\n { hasError: boolean; error: unknown }\n> {\n constructor(props: any) {\n super(props);\n this.state = { hasError: false, error: null };\n }\n\n static getDerivedStateFromError(error: unknown) {\n return { hasError: true, error };\n }\n\n render() {\n if (this.state.hasError) {\n const Fallback = this.props.Fallback;\n return React.createElement(Fallback, {\n ...this.props.fallbackProps,\n error: this.state.error,\n reset: () => this.setState({ hasError: false, error: null }),\n });\n }\n return this.props.children as React.ReactElement;\n }\n}\n\nasync function parseRouteModuleProps(\n routeModule: RouteModule,\n input: {\n props: PageProps;\n search: Record<string, string | string[] | undefined>;\n routePath: string;\n },\n): Promise<\n PageProps & {\n search: unknown;\n data?: unknown;\n __farmCanonicalPath?: string;\n __farmRoutePropsPromise?: Promise<Record<string, unknown>>;\n __farmRoutePropsResolved?: true;\n }\n> {\n const resolveRouteProps = (routeModule as any).__farmResolveRouteProps;\n if (typeof resolveRouteProps === \"function\") {\n // Resolve the top-level route state before starting the HTTP stream. It can\n // still return explicit defer() values for nested Suspense boundaries, but\n // redirects, notFound(), and failures must retain their real HTTP status.\n return await resolveRouteProps(input.props);\n }\n\n if ((routeModule as any).__farmRouteParsesProps) {\n return {\n ...input.props,\n search: input.search,\n };\n }\n\n const schemas = (routeModule as any).__farmRouteSchemas;\n const params = parseRouteModuleSchema(\n schemas?.params,\n input.props.params,\n \"params\",\n input.routePath,\n );\n const search = parseRouteModuleSchema(schemas?.search, input.search, \"search\", input.routePath);\n\n return {\n ...input.props,\n params: params as Record<string, string>,\n search,\n searchParams: Promise.resolve(search as Record<string, string | string[] | undefined>),\n };\n}\n\nfunction parseRouteModuleSchema(\n schema: { parse?: (value: unknown) => unknown } | undefined,\n value: unknown,\n label: string,\n routePath: string,\n): unknown {\n if (!schema || typeof schema.parse !== \"function\") {\n return value;\n }\n\n try {\n return schema.parse(value);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n }\n}\n\nfunction createRouteStateProps(input: {\n params: Record<string, string>;\n searchParamsObject: Record<string, string | string[] | undefined>;\n path: string;\n middlewareMap: Map<string, any>;\n pluginExposedContext: Map<string, any>;\n}): LoadingProps {\n return {\n params: input.params,\n search: input.searchParamsObject,\n searchParams: Promise.resolve(input.searchParamsObject),\n path: input.path,\n middleware: input.middlewareMap.size > 0 ? { data: input.middlewareMap } : undefined,\n context: input.pluginExposedContext.size > 0 ? { data: input.pluginExposedContext } : undefined,\n };\n}\n\nexport class ServerRenderer {\n private config: Required<FarmConfig>;\n private routeManager: RouteManager;\n private ssgManifest: SSGPage[] = [];\n private dataCache = getFarmDataCache();\n private i18nRuntime?: FarmI18nRuntime;\n\n constructor(\n config: Required<FarmConfig>,\n routeManager: RouteManager,\n i18nRuntime?: FarmI18nRuntime,\n ) {\n this.config = config;\n this.routeManager = routeManager;\n this.i18nRuntime = i18nRuntime;\n this.loadSSGManifest();\n }\n\n async runWithRequestContext<T>(request: Request, fn: () => T | Promise<T>): Promise<T> {\n return _runWithCurrentRequest(request, () =>\n this.i18nRuntime?.config.enabled\n ? _runWithFarmI18nRequest(this.i18nRuntime, request, fn, { redirect: false })\n : fn(),\n );\n }\n\n async resolveRouteContext(input: {\n request: Request;\n rawRequest?: FarmRequest;\n params: Record<string, string>;\n search: Record<string, string | string[] | undefined>;\n path: string;\n }): Promise<unknown> {\n return resolveFarmRouteContext(this.config, input);\n }\n\n /**\n * Load SSG manifest from build output\n */\n private loadSSGManifest(): void {\n try {\n const manifestPath = path.join(this.config.root, this.config.outDir, \"__ssg_manifest.json\");\n if (fs.existsSync(manifestPath)) {\n const content = fs.readFileSync(manifestPath, \"utf-8\");\n this.ssgManifest = JSON.parse(content);\n logger.info(`Loaded SSG manifest: ${this.ssgManifest.length} pages`);\n }\n } catch (error) {\n // No manifest in dev mode or first build\n }\n }\n\n /**\n * Check if a path should be served from SSG cache\n */\n private shouldServeSSG(pathname: string): SSGPage | null {\n const ssgPage = matchSSGPage(pathname, this.ssgManifest);\n if (!ssgPage) return null;\n\n const cached = this.getCachedSSGPage(pathname);\n if (cached && this.dataCache.isStale(cached)) {\n // Stale - needs revalidation (serve stale, regenerate in background)\n this.regenerateSSGPage(ssgPage);\n }\n\n return ssgPage;\n }\n\n private getSSGCacheKey(urlPath: string): string {\n return createFarmCacheKey([\"ssg\", normalizeRevalidatePath(urlPath)]);\n }\n\n private getPPRCacheKey(pathname: string, search = \"\"): string {\n return createFarmCacheKey([\"ppr\", normalizeRevalidatePath(pathname), search]);\n }\n\n private getCachedSSGPage(urlPath: string) {\n return this.dataCache.getEntry<CachedSSGPage>(this.getSSGCacheKey(urlPath), {\n allowStale: true,\n });\n }\n\n private cacheSSGPage(\n page: SSGPage,\n html: string,\n options: { document: boolean; createdAt?: number },\n ): void {\n this.dataCache.set(\n this.getSSGCacheKey(page.urlPath),\n { html, document: options.document },\n {\n createdAt: options.createdAt,\n paths: [page.urlPath],\n tags: [\"ssg\"],\n revalidate: page.revalidate ?? false,\n },\n );\n }\n\n private getCachedPPRShell(pathname: string, search: string) {\n return this.dataCache.getEntry<CachedPPRShell>(this.getPPRCacheKey(pathname, search));\n }\n\n private cachePPRShell(options: PPRShellCacheOptions, html: string): void {\n const key = this.getPPRCacheKey(options.pathname, options.search);\n this.dataCache.set(\n key,\n { html },\n {\n paths: [options.pathname],\n tags: [\"ppr\"],\n revalidate: options.revalidate ?? false,\n },\n );\n emitFarmEvent({\n type: \"ppr.shell.cached\",\n route: options.pathname,\n key,\n revalidate: options.revalidate,\n });\n }\n\n private getPPRShellBypassReason(\n req: FarmRequest,\n middlewareMap: Map<string, any>,\n middlewareContext: Map<string, any>,\n pluginExposedContext: Map<string, any>,\n ): string | undefined {\n const method = (req.method || \"GET\").toUpperCase();\n if (method !== \"GET\" && method !== \"HEAD\") {\n return \"method\";\n }\n\n if (req.headers.cookie) {\n return \"cookie\";\n }\n\n if (req.headers.authorization) {\n return \"authorization\";\n }\n\n if (hasRequestHeader(req, \"x-farm-ppr-refresh\")) {\n return \"refresh\";\n }\n\n if (middlewareMap.size > 0) {\n return \"middleware-data\";\n }\n\n if (middlewareContext.size > 0) {\n return \"middleware-context\";\n }\n\n if (pluginExposedContext.size > 0) {\n return \"plugin-context\";\n }\n\n return undefined;\n }\n\n private getPPRHeaders(status: \"hit\" | \"miss\" | \"bypass\", revalidate?: number) {\n const headers: Record<string, string> = {\n \"X-Farm-PPR\": status,\n };\n\n if (status === \"bypass\") {\n headers[\"Cache-Control\"] = \"private, no-store\";\n return headers;\n }\n\n if (typeof revalidate === \"number\" && revalidate > 0) {\n headers[\"Cache-Control\"] = `s-maxage=${revalidate}, stale-while-revalidate`;\n }\n\n return headers;\n }\n\n private serveCachedPPRShell(res: FarmResponse, shell: CachedPPRShell, revalidate?: number): void {\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n for (const [key, value] of Object.entries(this.getPPRHeaders(\"hit\", revalidate))) {\n res.setHeader(key, value);\n }\n res.write(shell.html);\n res.end();\n }\n\n /**\n * Regenerate an SSG page in the background (ISR)\n */\n private async regenerateSSGPage(page: SSGPage): Promise<void> {\n try {\n // This runs in the background - don't await\n setImmediate(async () => {\n try {\n const mod = await this.routeManager.loadRouteModule(page.filePath);\n if (!mod?.default) return;\n\n const { layouts } = this.routeManager.matchRoute(page.urlPath);\n const layoutModules = await Promise.all(\n layouts.map((l) => this.routeManager.loadLayoutModule(l.modulePath)),\n );\n\n const PageComponent = mod.default;\n const pageProps = {\n params: page.params,\n searchParams: Promise.resolve({}),\n path: page.urlPath,\n };\n\n let pageElement = React.createElement(\n PageComponent as React.ComponentType<unknown>,\n pageProps as React.Attributes,\n );\n\n for (let i = layoutModules.length - 1; i >= 0; i--) {\n const layoutModule = layoutModules[i];\n const LayoutComponent = layoutModule.default;\n pageElement = React.createElement(\n LayoutComponent as React.ComponentType<unknown>,\n {\n children: pageElement,\n params: page.params,\n } as React.Attributes,\n );\n }\n\n const { renderToString } = await import(\"react-dom/server\");\n const html = renderToString(await this.wrapWithIntegrationProviders(pageElement));\n\n this.cacheSSGPage(page, html, { document: false });\n\n logger.info(`ISR: Regenerated ${page.urlPath}`);\n } catch (error) {\n logger.error(`ISR regeneration failed for ${page.urlPath}: ${error}`);\n }\n });\n } catch (error) {\n logger.error(`ISR trigger failed: ${error}`);\n }\n }\n\n /**\n * Serve a pre-rendered SSG page\n */\n private async serveSSGPage(req: FarmRequest, res: FarmResponse, page: SSGPage): Promise<boolean> {\n // Check cache first (for ISR)\n const cached = this.getCachedSSGPage(page.urlPath);\n if (cached) {\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.setHeader(\"X-Farm-SSG\", \"cached\");\n if (page.revalidate) {\n res.setHeader(\"Cache-Control\", `s-maxage=${page.revalidate}, stale-while-revalidate`);\n }\n res.write(\n cached.value.document\n ? cached.value.html\n : this.createFullHTML(cached.value.html, false, page.urlPath),\n );\n res.end();\n return true;\n }\n\n // Try to read from file system (production)\n try {\n const htmlPath =\n page.urlPath === \"/\"\n ? path.join(this.config.root, this.config.outDir, \"client\", \"index.html\")\n : path.join(this.config.root, this.config.outDir, \"client\", page.urlPath + \".html\");\n\n if (fs.existsSync(htmlPath)) {\n const stat = fs.statSync(htmlPath);\n const html = fs.readFileSync(htmlPath, \"utf-8\");\n this.cacheSSGPage(page, html, { document: true, createdAt: stat.mtimeMs });\n const fileCacheEntry = this.getCachedSSGPage(page.urlPath);\n if (fileCacheEntry && this.dataCache.isStale(fileCacheEntry)) {\n this.regenerateSSGPage(page);\n }\n\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.setHeader(\"X-Farm-SSG\", \"file\");\n if (page.revalidate) {\n res.setHeader(\"Cache-Control\", `s-maxage=${page.revalidate}, stale-while-revalidate`);\n }\n res.write(html);\n res.end();\n return true;\n }\n } catch (error) {\n logger.error(`Failed to serve SSG page ${page.urlPath}: ${error}`);\n }\n\n return false;\n }\n\n async renderPage(req: FarmRequest, res: FarmResponse): Promise<void> {\n const request = createWebRequestFromFarmRequest(req);\n const runtime = this.i18nRuntime;\n\n if (runtime?.config.enabled) {\n const resolution = runtime.resolveRequest(request);\n const varyHeaders = getFarmLocaleVaryHeaders(runtime.config, resolution);\n for (const header of varyHeaders) appendResponseVary(res, header);\n if (resolution.persist) {\n appendResponseHeader(\n res,\n \"Set-Cookie\",\n createFarmLocaleCookie(resolution.locale, runtime.config),\n );\n }\n if (resolution.redirect && (request.method === \"GET\" || request.method === \"HEAD\")) {\n res.statusCode = 307;\n res.setHeader(\"Location\", resolution.redirect);\n if (varyHeaders.length > 0) res.setHeader(\"Cache-Control\", \"private, no-store\");\n res.end();\n return;\n }\n }\n\n return this.runWithRequestContext(request, () => this.renderPageInContext(req, res));\n }\n\n private async renderPageInContext(req: FarmRequest, res: FarmResponse): Promise<void> {\n const renderStartTime = Date.now();\n let pathname = \"/\";\n let params: Record<string, string> = {};\n let layouts: Array<{ modulePath: string }> = [];\n let searchParamsObject: Record<string, string | string[] | undefined> = {};\n let middlewareMap = new Map<string, any>();\n let middlewareContext = new Map<string, any>();\n let pluginExposedContext = new Map<string, any>();\n let errorBoundaryEntry: { modulePath: string } | null = null;\n let pprRefreshRoute: string | null = null;\n\n const completeRender = (status = res.statusCode || 200, route = pathname) => {\n emitFarmEvent({\n type: \"render.complete\",\n route,\n pathname,\n status,\n durationMs: Date.now() - renderStartTime,\n });\n };\n\n try {\n const url = new URL(req.url || \"/\", `http://${req.headers.host}`);\n pathname = url.pathname;\n emitFarmEvent({ type: \"render.start\", route: pathname, pathname });\n searchParamsObject = searchParamsToObject(url.searchParams);\n\n const metadataImageMatch = this.routeManager.matchMetadataImage(pathname);\n if (metadataImageMatch) {\n await this.renderMetadataImage(req, res, {\n pathname,\n searchParamsObject,\n ...metadataImageMatch,\n });\n completeRender(res.statusCode || 200, pathname);\n return;\n }\n\n this.applyDeploymentHeaders(req, res);\n\n // Check for pre-rendered SSG page first (production only)\n if (process.env.NODE_ENV === \"production\") {\n const ssgPage = this.shouldServeSSG(pathname);\n if (ssgPage) {\n const served = await this.serveSSGPage(req, res, ssgPage);\n if (served) {\n completeRender(res.statusCode || 200, ssgPage.urlPath);\n return;\n }\n }\n }\n\n // Match route\n const match = this.routeManager.matchRoute(pathname);\n const route = match.route;\n params = match.params;\n layouts = match.layouts;\n\n if (!route) {\n emitFarmEvent({ type: \"route.notFound\", pathname });\n await this.render404(req, res);\n completeRender(404);\n return;\n }\n\n emitFarmEvent({\n type: \"route.matched\",\n pathname,\n route: route.pattern,\n params,\n });\n\n const loadingBoundaryEntry = this.routeManager.getMatchingLoading(pathname);\n errorBoundaryEntry = this.routeManager.getMatchingError(pathname);\n\n middlewareMap = toMiddlewareMap((req as any).__FARM_MIDDLEWARE_DATA__);\n middlewareContext = toMiddlewareMap((req as any).__FARM_MIDDLEWARE_CONTEXT__);\n pluginExposedContext = getRequestContextSnapshot(req as object, { exposedOnly: true });\n const currentRequest = createWebRequestFromFarmRequest(req);\n const routeContext = await this.resolveRouteContext({\n request: currentRequest,\n rawRequest: req,\n params,\n search: searchParamsObject,\n path: pathname,\n });\n\n // Load route module\n const routeModule = await this.routeManager.loadRouteModule(route.modulePath);\n\n if (!routeModule.default) {\n throw new Error(`Route module ${route.modulePath} does not export a default component`);\n }\n\n // Create page props with searchParams as plain object and middleware data\n const rawPageProps: PageProps = withFarmRouteContext(\n {\n params,\n searchParams: Promise.resolve(searchParamsObject),\n path: pathname,\n middleware: middlewareMap.size > 0 ? { data: middlewareMap } : undefined,\n context: pluginExposedContext.size > 0 ? { data: pluginExposedContext } : undefined,\n } as PageProps & { search: unknown },\n routeContext,\n );\n const programmaticRouteComponents = (routeModule as any).__farmRouteComponents as\n | {\n error?: React.ComponentType<any>;\n notFound?: React.ComponentType<any>;\n }\n | undefined;\n let PageComponent = routeModule.default;\n let pageProps: PageProps & {\n search: unknown;\n data?: unknown;\n error?: unknown;\n __farmRoutePropsPromise?: Promise<Record<string, unknown>>;\n __farmRoutePropsResolved?: true;\n };\n\n try {\n pageProps = await parseRouteModuleProps(routeModule, {\n props: rawPageProps,\n search: searchParamsObject,\n routePath: route.pattern,\n });\n } catch (error) {\n if (isFarmRedirectError(error)) throw error;\n\n const routeStateProps = {\n ...rawPageProps,\n search: searchParamsObject,\n searchParams: Promise.resolve(searchParamsObject),\n error,\n };\n\n if (isFarmNotFoundError(error) && programmaticRouteComponents?.notFound) {\n res.statusCode = 404;\n PageComponent = programmaticRouteComponents.notFound;\n pageProps = routeStateProps;\n } else if (programmaticRouteComponents?.error) {\n res.statusCode = 500;\n PageComponent = programmaticRouteComponents.error;\n pageProps = routeStateProps;\n } else {\n throw error;\n }\n }\n\n const renderingConfig = await resolveRouteRenderingConfigFromFile(\n routeModule,\n route.modulePath,\n );\n const pprBypassReason = renderingConfig.ppr\n ? this.getPPRShellBypassReason(req, middlewareMap, middlewareContext, pluginExposedContext)\n : undefined;\n const canCachePPRShell = renderingConfig.ppr && !pprBypassReason;\n const pprShellOptions: PPRShellCacheOptions | undefined = canCachePPRShell\n ? {\n pathname,\n search: url.search,\n revalidate: renderingConfig.revalidate,\n }\n : undefined;\n\n if (renderingConfig.ppr && pprBypassReason) {\n emitFarmEvent({ type: \"ppr.shell.bypass\", route: pathname, reason: pprBypassReason });\n emitFarmEvent({ type: \"cache.bypass\", route: pathname, reason: pprBypassReason });\n\n if (pprBypassReason === \"refresh\") {\n pprRefreshRoute = pathname;\n emitFarmEvent({ type: \"ppr.refresh.start\", route: pathname });\n }\n }\n\n if (pprShellOptions) {\n const pprCacheKey = this.getPPRCacheKey(pathname, url.search);\n const cachedPPRShell = this.getCachedPPRShell(pathname, url.search);\n if (cachedPPRShell) {\n emitFarmEvent({ type: \"ppr.shell.hit\", route: pathname, key: pprCacheKey });\n this.serveCachedPPRShell(res, cachedPPRShell.value, renderingConfig.revalidate);\n completeRender(res.statusCode || 200, pathname);\n return;\n }\n emitFarmEvent({ type: \"ppr.shell.miss\", route: pathname, key: pprCacheKey });\n }\n\n let LoadingFallbackComponent: React.ComponentType<any> | null = null;\n if (loadingBoundaryEntry) {\n const loadingModule = await this.routeManager.loadRouteModule(\n loadingBoundaryEntry.modulePath,\n );\n if (loadingModule.default) {\n LoadingFallbackComponent = loadingModule.default;\n }\n }\n\n let ErrorFallbackComponent: React.ComponentType<any> | null = null;\n if (errorBoundaryEntry) {\n const errorModule = await this.routeManager.loadRouteModule(errorBoundaryEntry.modulePath);\n if (errorModule.default) {\n ErrorFallbackComponent = errorModule.default;\n }\n }\n\n // Build one fresh manifest per response and reuse its route metadata below.\n // This preserves immediate HMR visibility without scanning every route twice.\n const routeManifest = this.routeManager.generateClientManifest(this.config.root);\n const routeManifestEntry = routeManifest.routes.find(\n (entry) => entry.pattern === route.pattern,\n );\n const moduleMetadata =\n routeManifestEntry || getClientModuleMetadata(route.modulePath, this.config.root);\n const isClientComponent = moduleMetadata.isClientComponent;\n const shouldHydrate = moduleMetadata.shouldHydrate;\n\n (req as any).__FARM_PAGE_PATH__ = route.modulePath;\n (req as any).__FARM_ROUTE__ = pathname;\n (req as any).__FARM_IS_CLIENT_COMPONENT__ = isClientComponent;\n (req as any).__FARM_SHOULD_HYDRATE__ = shouldHydrate;\n (req as any).__FARM_LOADING_MODULE_PATH__ = loadingBoundaryEntry?.modulePath\n ? loadingBoundaryEntry.modulePath.substring(\n loadingBoundaryEntry.modulePath.indexOf(\"/src/app/\"),\n )\n : null;\n // Store pageProps for client-side hydration (serializable version - no Promises)\n (req as any).__FARM_PROPS__ = {\n params: pageProps.params,\n search: (pageProps as any).search,\n searchParams: (pageProps as any).search,\n ...(\"data\" in pageProps ? { data: (pageProps as any).data } : {}),\n ...((pageProps as any).__farmCanonicalPath\n ? { __farmCanonicalPath: (pageProps as any).__farmCanonicalPath }\n : {}),\n ...((pageProps as any).__farmRoutePropsResolved ? { __farmRoutePropsResolved: true } : {}),\n path: pathname,\n middleware:\n middlewareMap.size > 0\n ? {\n data: Object.fromEntries(middlewareMap),\n }\n : undefined,\n context:\n pluginExposedContext.size > 0\n ? {\n data: Object.fromEntries(pluginExposedContext),\n }\n : undefined,\n };\n\n // Load layout modules\n const layoutModules = await Promise.all(\n layouts.map((layout) => this.routeManager.loadLayoutModule(layout.modulePath)),\n );\n\n const mergedMetadata = await this.resolveRouteMetadata({\n layoutModules,\n routeModule,\n pageProps,\n pathname,\n });\n\n // Store metadata on request for renderWithSSR\n (req as any).__FARM_METADATA__ = mergedMetadata;\n\n // Get middleware data for AsyncLocalStorage\n const middlewareDataForContext = middlewareMap;\n\n await _runWithMiddlewareData(middlewareDataForContext, async () => {\n await _runWithMiddlewareContext(middlewareContext, async () => {\n await _runWithCurrentRequest(currentRequest, async () => {\n let pageElement = React.createElement(\n PageComponent as React.ComponentType<unknown>,\n pageProps as React.Attributes,\n );\n\n if (LoadingFallbackComponent) {\n const loadingFallback = React.createElement(LoadingFallbackComponent, {\n ...createRouteStateProps({\n params,\n searchParamsObject,\n path: pathname,\n middlewareMap,\n pluginExposedContext,\n }),\n } as React.Attributes);\n\n pageElement = React.createElement(\n React.Suspense,\n { fallback: loadingFallback },\n pageElement,\n );\n }\n\n // Wrap hydratable pages in a targeted container so the client can attach\n // without re-hydrating the surrounding layout shell.\n if (isClientComponent || shouldHydrate) {\n pageElement = React.createElement(\n \"div\",\n { id: \"__farm_page__\", \"data-farm-client\": \"true\" },\n pageElement,\n );\n }\n\n let wrappedElement: React.ReactElement = pageElement;\n for (let i = layoutModules.length - 1; i >= 0; i--) {\n const layoutModule = layoutModules[i];\n const LayoutComponent = layoutModule.default;\n wrappedElement = React.createElement(\n LayoutComponent as React.ComponentType<unknown>,\n {\n children: wrappedElement,\n params,\n } as React.Attributes,\n );\n }\n\n if (ErrorFallbackComponent) {\n wrappedElement = React.createElement(\n FarmRouteErrorBoundary,\n {\n Fallback: ErrorFallbackComponent,\n fallbackProps: {\n ...createRouteStateProps({\n params,\n searchParamsObject,\n path: pathname,\n middlewareMap,\n pluginExposedContext,\n }),\n },\n },\n wrappedElement,\n );\n }\n\n const integratedElement = await this.wrapWithIntegrationProviders(wrappedElement);\n const pprHeaders = renderingConfig.ppr\n ? this.getPPRHeaders(pprShellOptions ? \"miss\" : \"bypass\", renderingConfig.revalidate)\n : undefined;\n\n // Render with middleware data available\n await this.renderWithSSR(\n integratedElement,\n req,\n res,\n () => {\n _clearCurrentMiddlewareData();\n _clearCurrentMiddlewareContext();\n },\n {\n responseHeaders: pprHeaders,\n routeManifest,\n captureStaticShell: Boolean(pprShellOptions),\n observabilityRoute: pathname,\n onSuspenseHoleDetected: pprShellOptions\n ? () => emitFarmEvent({ type: \"ppr.suspense.holeDetected\", route: pathname })\n : undefined,\n onComplete:\n pprShellOptions && req.method !== \"HEAD\"\n ? (html) => this.cachePPRShell(pprShellOptions, html)\n : undefined,\n },\n );\n if (pprRefreshRoute) {\n emitFarmEvent({\n type: \"ppr.refresh.complete\",\n route: pprRefreshRoute,\n durationMs: Date.now() - renderStartTime,\n });\n }\n completeRender(res.statusCode || 200, pathname);\n });\n });\n });\n } catch (error) {\n if (isFarmRedirectError(error)) {\n const redirect = getFarmRedirectError(error)!;\n const snapshot = getFarmI18nClientSnapshot();\n const redirectUrl =\n snapshot && redirect.url.startsWith(\"/\") && !redirect.url.startsWith(\"//\")\n ? localizeFarmHref(redirect.url, snapshot.locale, snapshot)\n : redirect.url;\n emitFarmEvent({\n type: \"route.redirect\",\n from: pathname,\n to: redirectUrl,\n status: redirect.status,\n });\n if (!res.headersSent && !(res as any).writableEnded) {\n res.statusCode = redirect.status;\n res.setHeader(\"Location\", redirectUrl);\n res.end();\n } else if (!(res as any).writableEnded) {\n res.end();\n }\n completeRender(redirect.status, pathname);\n return;\n }\n\n if (isFarmNotFoundError(error)) {\n emitFarmEvent({ type: \"route.notFound\", pathname });\n if (!res.headersSent && !(res as any).writableEnded) {\n await this.render404(req, res);\n } else if (!(res as any).writableEnded) {\n res.end();\n }\n completeRender(404, pathname);\n return;\n }\n\n emitFarmEvent({ type: \"render.error\", route: pathname, error });\n if (pprRefreshRoute) {\n emitFarmEvent({ type: \"ppr.refresh.error\", route: pprRefreshRoute, error });\n }\n logger.error(`Error rendering page: ${error}`);\n\n if (res.headersSent || (res as any).writableEnded) {\n if (!(res as any).writableEnded) {\n res.end();\n }\n return;\n }\n\n if (errorBoundaryEntry) {\n const rendered = await this.renderRouteErrorBoundary(req, res, {\n pathname,\n params,\n layouts,\n searchParamsObject,\n middlewareMap,\n middlewareContext,\n pluginExposedContext,\n error,\n errorModulePath: errorBoundaryEntry.modulePath,\n });\n\n if (rendered) {\n return;\n }\n }\n\n await this.render500(req, res, error);\n }\n }\n\n private async wrapWithIntegrationProviders(\n element: React.ReactElement,\n ): Promise<React.ReactElement> {\n const providers = getIntegrationProviders(this.config.integrations);\n let wrapped = element;\n\n for (let i = providers.length - 1; i >= 0; i--) {\n const provider = providers[i];\n if (provider.type === \"clerk\") {\n if (!cachedClerkProvider) {\n cachedClerkProvider = await importRuntimeModule(\"@clerk/react\");\n }\n\n wrapped = React.createElement(\n cachedClerkProvider!.ClerkProvider,\n provider.props || {},\n wrapped,\n );\n }\n }\n\n return wrapped;\n }\n\n private async resolveRouteMetadata(options: {\n layoutModules: Array<Record<string, any>>;\n routeModule: RouteModule;\n pageProps: PageProps;\n pathname: string;\n }): Promise<Record<string, any>> {\n let metadata: Record<string, any> = {};\n\n for (const layoutModule of options.layoutModules) {\n metadata = mergeMetadata(metadata, layoutModule.metadata);\n if (typeof layoutModule.generateMetadata === \"function\") {\n metadata = mergeMetadata(\n metadata,\n await layoutModule.generateMetadata({ params: options.pageProps.params }),\n );\n }\n }\n\n metadata = mergeMetadata(metadata, (options.routeModule as any).metadata);\n if (typeof (options.routeModule as any).generateMetadata === \"function\") {\n metadata = mergeMetadata(\n metadata,\n await (options.routeModule as any).generateMetadata(options.pageProps),\n );\n }\n\n for (const kind of [\"opengraph\", \"twitter\"] as const) {\n const reference = await this.resolveMetadataImageReference(kind, options.pathname);\n if (reference) {\n metadata = addMetadataImageReference(metadata, reference);\n }\n }\n\n return metadata;\n }\n\n private async resolveMetadataImageReference(\n kind: MetadataImageKind,\n pathname: string,\n ): Promise<FarmMetadataImageReference | null> {\n const match = this.routeManager.getMatchingMetadataImage(pathname, kind);\n if (!match) return null;\n\n const rawHref = this.routeManager.resolveMetadataImagePath(match.image, match.params);\n const snapshot = getFarmI18nClientSnapshot();\n const href = snapshot ? localizeFarmHref(rawHref, snapshot.locale, snapshot) : rawHref;\n const reference: FarmMetadataImageReference = {\n kind,\n href,\n };\n\n if (match.image.sourceType === \"static\" && match.image.staticInfo) {\n return {\n ...reference,\n width: match.image.staticInfo.width,\n height: match.image.staticInfo.height,\n alt: match.image.staticInfo.alt,\n contentType: match.image.staticInfo.contentType,\n };\n }\n\n try {\n const imageModule = await this.routeManager.loadRouteModule(match.image.modulePath);\n const size = (imageModule as any).size;\n if (size && typeof size === \"object\") {\n reference.width = typeof size.width === \"number\" ? size.width : undefined;\n reference.height = typeof size.height === \"number\" ? size.height : undefined;\n }\n if (typeof (imageModule as any).alt === \"string\") {\n reference.alt = (imageModule as any).alt;\n }\n if (typeof (imageModule as any).contentType === \"string\") {\n reference.contentType = (imageModule as any).contentType;\n }\n } catch (error) {\n logger.warn(`Failed to read ${kind} image metadata for ${pathname}: ${error}`);\n }\n\n return reference;\n }\n\n private async renderMetadataImage(\n req: FarmRequest,\n res: FarmResponse,\n options: {\n pathname: string;\n pagePath: string;\n params: Record<string, string>;\n searchParamsObject: Record<string, string | string[] | undefined>;\n image: {\n modulePath: string;\n kind: MetadataImageKind;\n sourceType?: \"module\" | \"static\";\n staticInfo?: StaticMetadataImageInfo;\n };\n },\n ): Promise<void> {\n if (options.image.sourceType === \"static\") {\n if (!options.image.staticInfo) {\n throw new Error(`Static metadata image ${options.image.modulePath} is missing file info`);\n }\n await this.writeStaticMetadataImageResponse(req, res, {\n modulePath: options.image.modulePath,\n staticInfo: options.image.staticInfo,\n });\n return;\n }\n\n const imageModule = await this.routeManager.loadRouteModule(options.image.modulePath);\n if (!imageModule.default) {\n throw new Error(\n `Metadata image module ${options.image.modulePath} does not export a default component or handler`,\n );\n }\n\n const imageProps: PageProps = {\n params: options.params,\n searchParams: Promise.resolve(options.searchParamsObject),\n path: options.pagePath,\n };\n const handlerResult =\n typeof imageModule.default === \"function\"\n ? await (imageModule.default as any)(imageProps)\n : imageModule.default;\n\n await this.writeMetadataImageResponse(req, res, handlerResult, imageModule);\n }\n\n private async writeMetadataImageResponse(\n req: FarmRequest,\n res: FarmResponse,\n value: unknown,\n imageModule: RouteModule,\n ): Promise<void> {\n if (isWebResponse(value)) {\n res.statusCode = value.status;\n value.headers.forEach((headerValue, key) => {\n res.setHeader(key, headerValue);\n });\n\n if (req.method === \"HEAD\") {\n res.end();\n return;\n }\n\n const body = Buffer.from(await value.arrayBuffer());\n res.write(body);\n res.end();\n return;\n }\n\n const contentType = (imageModule as any).contentType || \"image/svg+xml; charset=utf-8\";\n let body: string | Buffer;\n\n if (typeof value === \"string\") {\n body = value;\n } else if (value instanceof ArrayBuffer) {\n body = Buffer.from(value);\n } else if (ArrayBuffer.isView(value)) {\n body = Buffer.from(value.buffer, value.byteOffset, value.byteLength);\n } else if (React.isValidElement(value)) {\n body = renderToStaticMarkup(value);\n } else {\n throw new Error(\"Metadata image must return a Response, string, bytes, or React element\");\n }\n\n res.statusCode = res.statusCode || 200;\n res.setHeader(\"Content-Type\", contentType);\n res.setHeader(\"Cache-Control\", \"public, max-age=0, must-revalidate\");\n if (req.method === \"HEAD\") {\n res.end();\n return;\n }\n res.write(body);\n res.end();\n }\n\n private async writeStaticMetadataImageResponse(\n req: FarmRequest,\n res: FarmResponse,\n image: { modulePath: string; staticInfo: StaticMetadataImageInfo },\n ): Promise<void> {\n const method = (req.method || \"GET\").toUpperCase();\n if (method !== \"GET\" && method !== \"HEAD\") {\n res.statusCode = 405;\n res.setHeader(\"Allow\", \"GET, HEAD\");\n res.end();\n return;\n }\n\n const etag = `\"${image.staticInfo.hash}\"`;\n const requestUrl = new URL(req.url || \"/\", `http://${req.headers.host || \"localhost\"}`);\n const isVersioned = requestUrl.searchParams.get(\"v\") === image.staticInfo.hash;\n\n res.setHeader(\"Content-Type\", image.staticInfo.contentType);\n res.setHeader(\"Content-Length\", image.staticInfo.byteLength);\n res.setHeader(\"ETag\", etag);\n res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n res.setHeader(\n \"Cache-Control\",\n isVersioned ? \"public, max-age=31536000, immutable\" : \"public, max-age=0, must-revalidate\",\n );\n\n if (req.headers[\"if-none-match\"] === etag) {\n res.statusCode = 304;\n res.end();\n return;\n }\n\n res.statusCode = res.statusCode || 200;\n if (method === \"HEAD\") {\n res.end();\n return;\n }\n\n res.write(await fs.promises.readFile(image.modulePath));\n res.end();\n }\n\n private async renderRouteErrorBoundary(\n req: FarmRequest,\n res: FarmResponse,\n options: {\n pathname: string;\n params: Record<string, string>;\n layouts: Array<{ modulePath: string }>;\n searchParamsObject: Record<string, string | string[] | undefined>;\n middlewareMap: Map<string, any>;\n middlewareContext: Map<string, any>;\n pluginExposedContext: Map<string, any>;\n error: unknown;\n errorModulePath: string;\n },\n ): Promise<boolean> {\n try {\n if (res.headersSent || (res as any).writableEnded) {\n if (!(res as any).writableEnded) {\n res.end();\n }\n return true;\n }\n\n const errorModule = await this.routeManager.loadRouteModule(options.errorModulePath);\n if (!errorModule.default) {\n return false;\n }\n\n const ErrorComponent = errorModule.default as React.ComponentType<unknown>;\n const errorElement = React.createElement(ErrorComponent, {\n ...createRouteStateProps({\n params: options.params,\n searchParamsObject: options.searchParamsObject,\n path: options.pathname,\n middlewareMap: options.middlewareMap,\n pluginExposedContext: options.pluginExposedContext,\n }),\n error: options.error,\n reset: () => {},\n } as React.Attributes);\n\n let wrapped: React.ReactElement = errorElement;\n const layoutModules = await Promise.all(\n options.layouts.map((layout) => this.routeManager.loadLayoutModule(layout.modulePath)),\n );\n for (let i = layoutModules.length - 1; i >= 0; i--) {\n const LayoutComponent = layoutModules[i].default;\n wrapped = React.createElement(\n LayoutComponent as React.ComponentType<unknown>,\n {\n children: wrapped,\n params: options.params,\n } as React.Attributes,\n );\n }\n\n const ReactDOMServer = await import(\"react-dom/server\");\n const html = await _runWithMiddlewareData(options.middlewareMap, () =>\n _runWithMiddlewareContext(options.middlewareContext, () =>\n ReactDOMServer.renderToString(wrapped),\n ),\n );\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.write(this.createFullHTML(html, false, options.pathname));\n res.end();\n return true;\n } catch (renderError) {\n logger.warn(`Failed to render route-level error boundary: ${renderError}`);\n return false;\n }\n }\n\n private async renderWithSSR(\n element: React.ReactElement,\n req: FarmRequest,\n res: FarmResponse,\n clearMiddlewareData?: () => void,\n options: {\n responseHeaders?: Record<string, string> | undefined;\n routeManifest?: ReturnType<RouteManager[\"generateClientManifest\"]>;\n onComplete?: (html: string) => void | Promise<void>;\n captureStaticShell?: boolean;\n observabilityRoute?: string;\n onSuspenseHoleDetected?: () => void;\n } = {},\n ): Promise<void> {\n return new Promise((resolve, reject) => {\n const streamStartTime = Date.now();\n const observabilityRoute =\n options.observabilityRoute || (req as any).__FARM_ROUTE__ || req.url || \"/\";\n const deploymentId = this.getDeploymentId();\n emitFarmEvent({ type: \"render.stream.start\", route: observabilityRoute });\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n for (const [key, value] of Object.entries(options.responseHeaders || {})) {\n res.setHeader(key, value);\n }\n\n const htmlParts: string[] = [];\n const staticShellParts: string[] | undefined = options.captureStaticShell ? [] : undefined;\n let staticShellClosed = false;\n let suspenseHoleEmitted = false;\n let didError = false;\n\n // Get the page path for client-side hydration\n const pagePath = (req as any).__FARM_PAGE_PATH__;\n const isClientComponent = (req as any).__FARM_IS_CLIENT_COMPONENT__ === true;\n const relativePath = pagePath\n ? pagePath.startsWith(this.config.root)\n ? pagePath.slice(this.config.root.length)\n : pagePath\n : \"/src/app/page.tsx\";\n\n // Generate manifest for client-side SPA navigation (TanStack Start pattern)\n // This manifest is inlined in HTML - no separate file or API endpoint\n const manifest =\n options.routeManifest ?? this.routeManager.generateClientManifest(this.config.root);\n\n // Convert to object format for client\n const clientManifest = {\n clientEntry: \"/@farm/client.js\",\n routes: {} as Record<string, any>,\n layouts: {} as Record<string, any>,\n sharedAssets: [{ tag: \"link\", attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" } }],\n };\n\n // Convert routes array to object keyed by pattern\n for (const routeEntry of manifest.routes) {\n clientManifest.routes[routeEntry.pattern] = {\n modulePath: routeEntry.modulePath,\n pattern: routeEntry.pattern,\n segments: routeEntry.segments,\n search: routeEntry.search,\n isClientComponent: routeEntry.isClientComponent,\n shouldHydrate: routeEntry.shouldHydrate,\n preloads: [routeEntry.modulePath],\n assets: [],\n };\n }\n\n // Convert layouts array to object\n for (const layoutEntry of manifest.layouts) {\n clientManifest.layouts[layoutEntry.pattern] = {\n modulePath: layoutEntry.modulePath,\n pattern: layoutEntry.pattern,\n preloads: [layoutEntry.modulePath],\n assets: [],\n };\n }\n\n // Inject page props, component info, and MANIFEST for client-side SPA\n // __FARM_MANIFEST__ contains the full route manifest (TanStack Start pattern)\n const deferredProps = prepareDeferredData((req as any).__FARM_PROPS__ || {});\n const propsScript = `<script>\nwindow.__FARM_PROPS__ = ${serializeInlineValue(deferredProps.data)};\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(deploymentId)};\nwindow.__FARM_PATH__ = ${JSON.stringify((req as any).__FARM_ROUTE__ || req.url || \"/\")};\nwindow.__FARM_IS_CLIENT__ = ${JSON.stringify(isClientComponent)};\nwindow.__FARM_SHOULD_HYDRATE__ = ${JSON.stringify((req as any).__FARM_SHOULD_HYDRATE__ === true)};\nwindow.__FARM_PAGE_MODULE__ = ${JSON.stringify(relativePath)};\nwindow.__FARM_LOADING_MODULE__ = ${JSON.stringify(\n (req as any).__FARM_LOADING_MODULE_PATH__ || null,\n )};\nwindow.__FARM_MANIFEST__ = ${JSON.stringify(clientManifest)};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${getFarmI18nClientSnapshot() ? `window.__FARM_I18N__ = ${serializeInlineValue(getFarmI18nClientSnapshot())};` : \"\"}\n</script>`;\n const hydrationClickQueueScript =\n isClientComponent || (req as any).__FARM_SHOULD_HYDRATE__ === true\n ? createPreHydrationClickQueueScript()\n : \"\";\n\n const {\n title,\n tags: metaTags,\n hasFavicon,\n } = renderMetadataHead((req as any).__FARM_METADATA__);\n const i18nSnapshot = getFarmI18nClientSnapshot();\n const i18nAlternateTags = i18nSnapshot\n ? renderI18nAlternateLinks((req as any).__FARM_ROUTE__ || req.url || \"/\", i18nSnapshot)\n : \"\";\n\n // React 19: ensure root is a single DOM node so streaming starts early (avoids Fragment delay)\n const streamRoot = React.createElement(\"div\", { style: { display: \"contents\" } }, element);\n const { pipe, abort } = renderToPipeableStream(streamRoot, {\n onShellReady() {\n const shellReadyMs = Date.now() - streamStartTime;\n emitFarmEvent({\n type: \"render.stream.shellReady\",\n route: observabilityRoute,\n durationMs: shellReadyMs,\n });\n if (process.env.FARM_VERBOSE) {\n console.log(`[FARM STREAM] onShellReady at ${shellReadyMs}ms`);\n }\n const shell = `<!DOCTYPE html>\n<html lang=\"${escapeHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n }>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(deploymentId)}\">\n ${hasFavicon ? \"\" : '<link rel=\"icon\" href=\"data:,\">'}\n <title>${title}</title>${metaTags}${i18nAlternateTags}\n <link rel=\"stylesheet\" href=\"/src/app/globals.css\" />\n <script type=\"module\" src=\"/@vite/client\"></script>\n ${propsScript}\n ${hydrationClickQueueScript}\n</head>\n<body class=\"\">\n <div id=\"root\">`;\n htmlParts.push(shell);\n staticShellParts?.push(shell);\n\n let firstChunk = true;\n const writableStream = new Writable({\n write(chunk, encoding, callback) {\n if (firstChunk && process.env.FARM_VERBOSE) {\n console.log(`[FARM STREAM] first pipe chunk at ${Date.now() - streamStartTime}ms`);\n firstChunk = false;\n }\n const chunkText = Buffer.isBuffer(chunk) ? chunk.toString() : String(chunk);\n htmlParts.push(chunkText);\n\n if (staticShellParts && !staticShellClosed) {\n const dynamicIndex = findPPRDynamicChunkIndex(chunkText);\n if (dynamicIndex >= 0) {\n if (dynamicIndex > 0) {\n staticShellParts.push(chunkText.slice(0, dynamicIndex));\n }\n staticShellClosed = true;\n if (!suspenseHoleEmitted) {\n suspenseHoleEmitted = true;\n options.onSuspenseHoleDetected?.();\n }\n } else {\n staticShellParts.push(chunkText);\n }\n }\n\n res.write(chunk, encoding, () => {\n if (typeof (res as any).flush === \"function\") (res as any).flush();\n callback();\n });\n },\n final(callback) {\n const suspenseRevealFallback = `<script>(function(){function moveFragment(srcId,placeholderId){var src=document.getElementById(srcId),ph=document.getElementById(placeholderId);if(!src||!ph||!ph.parentNode)return false;while(src.firstChild)ph.parentNode.insertBefore(src.firstChild,ph);ph.parentNode.removeChild(ph);if(src.parentNode)src.parentNode.removeChild(src);return true}function revealBoundary(boundaryId,sectionId){var boundary=document.getElementById(boundaryId),section=document.getElementById(sectionId);if(!boundary||!section||!boundary.parentNode)return false;var start=boundary.previousSibling;if(!start||start.nodeType!==8)return false;var parent=boundary.parentNode;var node=boundary;var depth=0;while(node){if(node.nodeType===8){var data=node.data;if(data===\"/$\"||data===\"/&\"){if(depth===0)break;depth--;}else if(data===\"$\"||data===\"$?\"||data===\"$~\"||data===\"$!\"||data===\"&\"){depth++;}}var next=node.nextSibling;parent.removeChild(node);node=next;}while(section.firstChild)parent.insertBefore(section.firstChild,node);if(section.parentNode)section.parentNode.removeChild(section);start.data=\"$\";return true}var tries=0;var timer=setInterval(function(){var changed=false;document.querySelectorAll('div[id^=\"S:\"]').forEach(function(section){var suffix=section.id.slice(2);changed=moveFragment('S:'+suffix,'P:'+suffix)||changed;});document.querySelectorAll('template[id^=\"B:\"]').forEach(function(boundary){var suffix=boundary.id.slice(2);changed=revealBoundary('B:'+suffix,'S:'+suffix)||changed;});tries++;if(tries>80||(!document.querySelector('template[id^=\"B:\"]')&&!document.querySelector('template[id^=\"P:\"]'))){clearInterval(timer);}},50);})();</script>`;\n const footer = createDocumentFooter({\n suspenseRevealFallback,\n deferredHydrationScript: createDeferredHydrationScript(deferredProps.records),\n });\n htmlParts.push(footer);\n res.write(footer);\n res.end();\n callback();\n if (clearMiddlewareData) {\n clearMiddlewareData();\n }\n if (!didError && options.onComplete) {\n if (staticShellParts) {\n staticShellParts.push(\n createDocumentFooter({\n suspenseRevealFallback,\n refreshPPR: staticShellClosed,\n }),\n );\n }\n\n const cachedHtml = staticShellParts\n ? staticShellParts.join(\"\")\n : htmlParts.join(\"\");\n Promise.resolve(options.onComplete(cachedHtml)).catch((error) => {\n logger.warn(`Failed to cache PPR shell: ${error}`);\n });\n }\n emitFarmEvent({\n type: \"render.stream.complete\",\n route: observabilityRoute,\n durationMs: Date.now() - streamStartTime,\n });\n resolve();\n },\n });\n\n // Queue the shell immediately, then start piping the Suspense stream.\n // Waiting for the write callback can delay the fallback until the whole\n // response is ready under some dev-server wrappers.\n res.write(shell);\n if (typeof (res as any).flush === \"function\") {\n (res as any).flush();\n }\n pipe(writableStream);\n },\n onShellError(error) {\n didError = true;\n if (!isFarmRedirectError(error) && !isFarmNotFoundError(error)) {\n logger.error(`SSR shell error: ${error}`);\n emitFarmEvent({ type: \"render.error\", route: observabilityRoute, error });\n }\n\n if (clearMiddlewareData) {\n clearMiddlewareData();\n }\n\n reject(error);\n },\n onError(error) {\n didError = true;\n if (!isFarmRedirectError(error) && !isFarmNotFoundError(error)) {\n logger.error(`SSR streaming error: ${error}`);\n emitFarmEvent({ type: \"render.error\", route: observabilityRoute, error });\n }\n },\n });\n });\n }\n\n private async render404(req: FarmRequest, res: FarmResponse): Promise<void> {\n res.statusCode = 404;\n\n const pathname = new URL(req.url || \"/\", `http://${req.headers.host || \"localhost\"}`).pathname;\n\n try {\n // Look for custom not-found page\n const appDir = path.join(this.config.root, this.config.srcDir, \"app\");\n const notFoundExtensions = [\".tsx\", \".jsx\", \".ts\", \".js\"];\n let notFoundPath: string | null = null;\n\n for (const ext of notFoundExtensions) {\n const checkPath = path.join(appDir, `not-found${ext}`);\n if (fs.existsSync(checkPath)) {\n notFoundPath = checkPath;\n break;\n }\n }\n\n if (notFoundPath) {\n // Use routeManager to load the module (uses Vite's ssrLoadModule in dev)\n const notFoundModule = await this.routeManager.loadRouteModule(notFoundPath);\n const NotFoundComponent = notFoundModule.default;\n\n if (NotFoundComponent) {\n // Look for root layout\n let LayoutComponent: React.ComponentType<unknown> | null = null;\n for (const ext of notFoundExtensions) {\n const layoutPath = path.join(appDir, `layout${ext}`);\n if (fs.existsSync(layoutPath)) {\n try {\n const layoutModule = await this.routeManager.loadLayoutModule(layoutPath);\n LayoutComponent = layoutModule.default as React.ComponentType<unknown>;\n } catch {\n // Layout import failed, continue without it\n }\n break;\n }\n }\n\n // Render the 404 page\n let element = React.createElement(\n NotFoundComponent as React.ComponentType<unknown>,\n { pathname } as React.Attributes,\n );\n\n // Wrap with layout if available\n if (LayoutComponent) {\n element = React.createElement(\n LayoutComponent as React.ComponentType<unknown>,\n { children: element } as React.Attributes,\n );\n }\n\n // Render to string\n const ReactDOMServer = await import(\"react-dom/server\");\n const content = ReactDOMServer.renderToString(element);\n\n const html = this.createFullHTML(content, false, pathname);\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.write(html);\n res.end();\n return;\n }\n }\n } catch (error) {\n logger.warn(`Failed to render custom 404 page: ${error}`);\n }\n\n // Fallback to default styled 404 page\n const defaultContent = `\n <div style=\"display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:100vh;font-family:system-ui,-apple-system,sans-serif;background:#f9fafb;padding:20px;text-align:center;\">\n <div style=\"background:white;border-radius:12px;padding:48px;box-shadow:0 4px 6px rgba(0,0,0,0.1);max-width:500px;width:100%;\">\n <h1 style=\"font-size:96px;font-weight:bold;color:#22c55e;margin:0 0 16px;line-height:1;\">404</h1>\n <h2 style=\"font-size:24px;font-weight:600;color:#1f2937;margin:0 0 16px;\">Page Not Found</h2>\n <p style=\"font-size:16px;color:#6b7280;margin:0 0 24px;\">\n The page <code style=\"background:#f3f4f6;padding:2px 6px;border-radius:4px;\">${pathname}</code> doesn't exist.\n </p>\n <a href=\"/\" style=\"display:inline-block;background:#22c55e;color:white;padding:12px 24px;border-radius:8px;text-decoration:none;font-weight:500;\">Go Home</a>\n </div>\n <p style=\"margin-top:24px;font-size:14px;color:#9ca3af;\">Powered by Farm.js</p>\n </div>\n `;\n\n const html = this.createFullHTML(defaultContent, false, pathname);\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.write(html);\n res.end();\n }\n\n private async render500(req: FarmRequest, res: FarmResponse, error: any): Promise<void> {\n if (res.headersSent || (res as any).writableEnded) {\n if (!(res as any).writableEnded) {\n res.end();\n }\n return;\n }\n\n res.statusCode = 500;\n\n const isDev = process.env.NODE_ENV === \"development\";\n const errorMessage = isDev ? error.stack || error.message : \"Internal Server Error\";\n\n const html = this.createFullHTML(\n `\n <h1>500 - Internal Server Error</h1>\n ${isDev ? `<pre>${errorMessage}</pre>` : \"\"}\n `,\n false,\n req.url || \"/\",\n );\n\n res.setHeader(\"Content-Type\", \"text/html; charset=utf-8\");\n res.write(html);\n res.end();\n }\n\n private createFullHTML(content: string, isClientComponent = false, requestPath = \"/\"): string {\n const i18nSnapshot = getFarmI18nClientSnapshot();\n const clientScript = isClientComponent\n ? ` <script type=\"module\" src=\"/@farm/client.js\"></script>`\n : \"\";\n const integrationManifestScript = `<script>\nwindow.__FARM_DEPLOYMENT_ID__ = ${serializeInlineValue(this.getDeploymentId())};\nwindow.__FARM_INTEGRATION_API_MANIFEST__ = ${JSON.stringify(getRegisteredIntegrationAPIManifest())};\n${i18nSnapshot ? `window.__FARM_I18N__ = ${serializeInlineValue(i18nSnapshot)};` : \"\"}\n</script>`;\n const alternateLinks = i18nSnapshot ? renderI18nAlternateLinks(requestPath, i18nSnapshot) : \"\";\n\n return `<!DOCTYPE html>\n<html lang=\"${escapeHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n }>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <meta name=\"farm-deployment-id\" content=\"${escapeHtmlAttribute(this.getDeploymentId())}\">\n <link rel=\"icon\" href=\"data:,\">\n <title>Farm.js App</title>${alternateLinks}\n <link rel=\"stylesheet\" href=\"/src/app/globals.css\" />\n <script type=\"module\" src=\"/@vite/client\"></script>\n ${integrationManifestScript}\n</head>\n<body class=\"\">\n <div id=\"root\">${content}</div>\n${clientScript}\n</body>\n</html>`;\n }\n\n private applyDeploymentHeaders(req: FarmRequest, res: FarmResponse): void {\n const deploymentId = this.getDeploymentId();\n res.setHeader(FARM_DEPLOYMENT_ID_HEADER, deploymentId);\n if ((req.method || \"GET\").toUpperCase() !== \"GET\") return;\n\n const forwardedProto = req.headers[\"x-forwarded-proto\"];\n const isSecure =\n (Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto)\n ?.split(\",\")[0]\n ?.trim() === \"https\" || Boolean((req.socket as any)?.encrypted);\n const cookie = createFarmDeploymentCookie(deploymentId, this.config.basePath || \"/\", isSecure);\n const existing = res.getHeader(\"Set-Cookie\");\n\n if (Array.isArray(existing)) {\n res.setHeader(\"Set-Cookie\", [...existing, cookie]);\n } else if (existing) {\n res.setHeader(\"Set-Cookie\", [String(existing), cookie]);\n } else {\n res.setHeader(\"Set-Cookie\", cookie);\n }\n }\n\n private getDeploymentId(): string {\n return this.config.deploymentId || \"development\";\n }\n}\n","/**\n * Server-side middleware utilities for accessing middleware data in pages\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport type { ReadonlyMiddlewareStore } from \"./types\";\n\ntype MiddlewareStoreInput = Record<string, any> | Map<string, any>;\nconst MIDDLEWARE_DATA_STORE_KEY = Symbol.for(\"farm.middlewareDataStore\");\nconst MIDDLEWARE_CONTEXT_STORE_KEY = Symbol.for(\"farm.middlewareContextStore\");\n\nfunction getGlobalMiddlewareStore(key: symbol): AsyncLocalStorage<Map<string, any>> {\n const state = globalThis as typeof globalThis & Record<symbol, unknown>;\n const existing = state[key];\n if (existing instanceof AsyncLocalStorage) {\n return existing as AsyncLocalStorage<Map<string, any>>;\n }\n\n const store = new AsyncLocalStorage<Map<string, any>>();\n state[key] = store;\n return store;\n}\n\nconst middlewareStore = getGlobalMiddlewareStore(MIDDLEWARE_DATA_STORE_KEY);\nconst middlewareContextStore = getGlobalMiddlewareStore(MIDDLEWARE_CONTEXT_STORE_KEY);\n\nfunction toMiddlewareMap(data: MiddlewareStoreInput): Map<string, any> {\n if (data instanceof Map) {\n return new Map(data);\n }\n return new Map(Object.entries(data));\n}\n\n/**\n * Internal: Set middleware data for the current request\n * This is called by the server renderer before rendering starts.\n * Prefer _runWithMiddlewareData for request-scoped async flows.\n */\nexport function _setCurrentMiddlewareData(data: MiddlewareStoreInput): void {\n middlewareStore.enterWith(toMiddlewareMap(data));\n}\n\n/**\n * Internal: Clear middleware data after request completes\n */\nexport function _clearCurrentMiddlewareData(): void {\n middlewareStore.enterWith(new Map());\n}\n\n/** Internal: Clear server-only middleware context after rendering. */\nexport function _clearCurrentMiddlewareContext(): void {\n middlewareContextStore.enterWith(new Map());\n}\n\n/**\n * Internal: Run code with middleware data available\n * This is called by the server renderer\n */\nexport async function _runWithMiddlewareData<T>(\n data: MiddlewareStoreInput,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return middlewareStore.run(toMiddlewareMap(data), fn);\n}\n\n/** Internal: Run code with server-only middleware context available. */\nexport async function _runWithMiddlewareContext<T>(\n context: MiddlewareStoreInput,\n fn: () => T | Promise<T>,\n): Promise<T> {\n return middlewareContextStore.run(toMiddlewareMap(context), fn);\n}\n\n/**\n * Get middleware data in a server component\n * No props needed - uses global storage!\n *\n * @example\n * ```tsx\n * import { getMiddlewareData } from 'farm/middleware';\n *\n * export default function Page() {\n * const data = getMiddlewareData(); // ← No props needed!\n * const user = data.get('user');\n * const demoInfo = data.get('demoInfo');\n *\n * return <div>Welcome {user?.name}</div>;\n * }\n * ```\n */\nexport function getMiddlewareData<T extends Record<string, any> = Record<string, any>>(): Map<\n keyof T,\n T[keyof T]\n> {\n return (middlewareStore.getStore() || new Map()) as Map<keyof T, T[keyof T]>;\n}\n\n/**\n * Get a specific value from middleware data (synchronous)\n * Uses AsyncLocalStorage for request scoping - no props needed.\n *\n * @example\n * ```tsx\n * import { getMiddlewareValue } from 'farm/middleware';\n *\n * export default function Page() {\n * const user = getMiddlewareValue<User>('user'); // ← No props needed!\n * const stats = getMiddlewareValue('dashboardStats');\n *\n * return <div>Welcome {user?.name}</div>;\n * }\n * ```\n */\nexport function getMiddlewareValue<T = any>(key: string): T | undefined {\n const data = getMiddlewareData();\n return data.get(key);\n}\n\n/**\n * Read server-only values set by route middleware for the current request.\n * The returned store is available to the matched page, layouts, and nested\n * Server Components, but is never added to hydration props.\n */\nexport function getMiddlewareContext<\n T extends Record<string, any> = Record<string, any>,\n>(): ReadonlyMiddlewareStore<T> {\n return (middlewareContextStore.getStore() || new Map()) as unknown as ReadonlyMiddlewareStore<T>;\n}\n\n/**\n * Type-safe middleware data accessor with type parameter\n *\n * @example\n * ```tsx\n * import { createMiddlewareAccessor } from 'farm/middleware/server';\n *\n * interface MiddlewareData {\n * user: { id: number; name: string };\n * dashboardStats: { views: number; clicks: number };\n * }\n *\n * const getData = createMiddlewareAccessor<MiddlewareData>();\n *\n * export default function Page() {\n * const data = getData();\n * const user = data.user; // Fully typed!\n * const stats = data.dashboardStats; // Fully typed!\n *\n * return <div>Welcome {user?.name}</div>;\n * }\n * ```\n */\nexport function createMiddlewareAccessor<T extends Record<string, any>>() {\n return (): Partial<T> => {\n const data = getMiddlewareData();\n const result: any = {};\n\n for (const [key, value] of data) {\n result[key] = value;\n }\n\n return result as Partial<T>;\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { FarmRequest } from \"../types\";\nimport { _setCurrentRequestResolver } from \"./request-bridge\";\n\nconst REQUEST_STORAGE_KEY = Symbol.for(\"@farm.js/core/request-storage\");\n\nfunction getRequestStore(): AsyncLocalStorage<Request> {\n const runtime = globalThis as typeof globalThis & Record<PropertyKey, unknown>;\n const existing = runtime[REQUEST_STORAGE_KEY];\n if (existing instanceof AsyncLocalStorage) {\n return existing as AsyncLocalStorage<Request>;\n }\n\n const storage = new AsyncLocalStorage<Request>();\n runtime[REQUEST_STORAGE_KEY] = storage;\n return storage;\n}\n\nconst requestStore = getRequestStore();\n\n_setCurrentRequestResolver(() => requestStore.getStore());\n\nexport function createWebRequestFromFarmRequest(req: FarmRequest): Request {\n const forwardedHost = req.headers[\"x-forwarded-host\"];\n const host = Array.isArray(forwardedHost)\n ? forwardedHost[0]\n : forwardedHost || req.headers.host || \"localhost\";\n const forwardedProto = req.headers[\"x-forwarded-proto\"];\n const proto = Array.isArray(forwardedProto) ? forwardedProto[0] : forwardedProto || \"http\";\n const fullUrl = new URL(req.url || \"/\", `${proto}://${host}`).toString();\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value == null) {\n continue;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(key, item);\n }\n continue;\n }\n\n headers.set(key, value);\n }\n\n return new Request(fullUrl, {\n method: req.method,\n headers,\n });\n}\n\nexport async function _runWithCurrentRequest<T>(\n request: Request,\n fn: () => Promise<T> | T,\n): Promise<T> {\n return requestStore.run(request, fn);\n}\n\nexport function getCurrentRequest(): Request {\n const request = requestStore.getStore();\n if (!request) {\n throw new Error(\n \"No current request is available. getCurrentRequest() can only be used during server rendering.\",\n );\n }\n\n return request;\n}\n","type CurrentRequestResolver = () => Request | undefined;\n\nconst CURRENT_REQUEST_RESOLVER_KEY = Symbol.for(\"farm.currentRequestResolver\");\n\ntype GlobalWithCurrentRequestResolver = typeof globalThis & {\n [CURRENT_REQUEST_RESOLVER_KEY]?: CurrentRequestResolver;\n};\n\nfunction getGlobalState(): GlobalWithCurrentRequestResolver {\n return globalThis as GlobalWithCurrentRequestResolver;\n}\n\nexport function _setCurrentRequestResolver(resolver: CurrentRequestResolver | undefined): void {\n getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY] = resolver;\n}\n\nexport function _resolveCurrentRequest(): Request | undefined {\n return getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY]?.();\n}\n","import { useEffect, useMemo, useRef, useState, type RefObject } from \"react\";\nimport { createFarmRouter, type FarmRouter, type FarmRouterRouteInput } from \"../router\";\nimport {\n getRouter as getSPARouter,\n readPageState,\n type FarmNavigationBlockerContext,\n type FarmNavigationState,\n} from \"./spa-router\";\nimport { getFarmI18nClientState } from \"../i18n/client-runtime\";\nimport { stripFarmLocaleFromPathname } from \"../i18n/routing\";\n\ninterface RouterState {\n pathname: string;\n searchParams: URLSearchParams;\n params: Record<string, string>;\n pageState: unknown;\n}\n\nexport interface UseRouterOptions {\n basePath?: string;\n routes?: FarmRouterRouteInput[];\n}\n\nexport interface UseBlockerOptions {\n when: boolean | ((context: FarmNavigationBlockerContext) => boolean);\n message?: string;\n shouldBlock?: (\n context: FarmNavigationBlockerContext,\n ) => boolean | Promise<boolean>;\n}\n\nexport interface UseBlockerReturn {\n active: boolean;\n}\n\n/**\n * Hook for accessing router state and navigation\n */\nexport function useRouter(options: UseRouterOptions = {}) {\n const basePath = options.basePath || \"\";\n const routes = options.routes;\n const routeKey =\n routes?.map((route) => (typeof route === \"string\" ? route : route.path)).join(\"\\n\") || \"\";\n const routeMatcher = useMemo(\n () => (routeKey ? createFarmRouter(routeKey.split(\"\\n\")) : null),\n [routeKey],\n );\n const [state, setState] = useState<RouterState>(() => {\n return readRouterState(basePath, routeMatcher);\n });\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n\n const handlePopState = () => {\n setState(readRouterState(basePath, routeMatcher));\n };\n\n handlePopState();\n window.addEventListener(\"popstate\", handlePopState);\n return () => window.removeEventListener(\"popstate\", handlePopState);\n }, [basePath, routeMatcher]);\n\n const push = (href: string) => {\n if (typeof window === \"undefined\") return;\n\n const url = href.startsWith(\"/\") ? basePath + href : href;\n window.history.pushState(null, \"\", url);\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n };\n\n const replace = (href: string) => {\n if (typeof window === \"undefined\") return;\n\n const url = href.startsWith(\"/\") ? basePath + href : href;\n window.history.replaceState(null, \"\", url);\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n };\n\n const pushState = <TState,>(pageState: TState, href?: string) => {\n if (typeof window === \"undefined\") return;\n getSPARouter().pushState(pageState, resolveClientHref(href, basePath));\n };\n\n const replaceState = <TState,>(pageState: TState, href?: string) => {\n if (typeof window === \"undefined\") return;\n getSPARouter().replaceState(pageState, resolveClientHref(href, basePath));\n };\n\n const back = () => {\n if (typeof window !== \"undefined\") {\n window.history.back();\n }\n };\n\n const forward = () => {\n if (typeof window !== \"undefined\") {\n window.history.forward();\n }\n };\n\n return {\n ...state,\n push,\n replace,\n pushState,\n replaceState,\n back,\n forward,\n };\n}\n\nexport function usePageState<TState = unknown>(): TState | null {\n const [state, setState] = useState<TState | null>(() => readPageState<TState>());\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n\n const handlePopState = () => {\n setState(readPageState<TState>());\n };\n\n handlePopState();\n window.addEventListener(\"popstate\", handlePopState);\n return () => window.removeEventListener(\"popstate\", handlePopState);\n }, []);\n\n return state;\n}\n\nexport function useNavigation(): FarmNavigationState {\n const [state, setState] = useState<FarmNavigationState>(() =>\n getSPARouter().getNavigationState(),\n );\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n return getSPARouter().subscribeNavigation(setState);\n }, []);\n\n return state;\n}\n\nexport function useBlocker(options: UseBlockerOptions): UseBlockerReturn {\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const active = Boolean(options.when);\n\n useEffect(() => {\n if (typeof window === \"undefined\" || !active) {\n return;\n }\n\n return getSPARouter().addBlocker(async (context) => {\n const current = optionsRef.current;\n const when =\n typeof current.when === \"function\" ? current.when(context) : current.when;\n\n if (!when) return false;\n\n if (current.shouldBlock && !(await current.shouldBlock(context))) {\n return false;\n }\n\n if (current.message && typeof window.confirm === \"function\") {\n return !window.confirm(current.message);\n }\n\n return true;\n });\n }, [active]);\n\n return { active };\n}\n\nexport function useScrollRestoration<TElement extends HTMLElement = HTMLElement>(\n key: string,\n): RefObject<TElement> {\n const ref = useRef<TElement>(null);\n\n useEffect(() => {\n const element = ref.current;\n if (!element) return;\n return getSPARouter().registerScrollElement(key, element);\n }, [key]);\n\n return ref;\n}\n\nfunction readRouterState(basePath: string, routeMatcher: FarmRouter | null): RouterState {\n if (typeof window === \"undefined\") {\n return {\n pathname: \"/\",\n searchParams: new URLSearchParams(),\n params: {},\n pageState: null,\n };\n }\n\n const url = new URL(window.location.href);\n const pathname = normalizeClientPathname(url.pathname, basePath);\n const i18n = getFarmI18nClientState();\n const routePathname = i18n ? stripFarmLocaleFromPathname(pathname, i18n) : pathname;\n return {\n pathname,\n searchParams: url.searchParams,\n params: routeMatcher?.match(routePathname)?.params || {},\n pageState: readPageState(),\n };\n}\n\nfunction normalizeClientPathname(pathname: string, basePath: string) {\n const normalizedBase = basePath.replace(/\\/+$/, \"\");\n const isUnderBase =\n normalizedBase && (pathname === normalizedBase || pathname.startsWith(`${normalizedBase}/`));\n const withoutBase = isUnderBase ? pathname.slice(normalizedBase.length) || \"/\" : pathname;\n return withoutBase || \"/\";\n}\n\nfunction resolveClientHref(href: string | undefined, basePath: string): string | undefined {\n if (!href) return undefined;\n return href.startsWith(\"/\") ? basePath + href : href;\n}\n","export const FARM_DEFERRED_CONTENT_TYPE = \"application/x-farm-deferred+json\";\nexport const FARM_DEFERRED_ERROR_CODE = \"FARM_DEFERRED_DATA_ERROR\";\nexport const FARM_DEFERRED_BRAND: unique symbol = Symbol.for(\n \"farm.deferred\",\n) as typeof FARM_DEFERRED_BRAND;\n\nconst FARM_DEFERRED_MARKER = \"$farmDeferred\";\n\ntype DeferredState<T = unknown> =\n | { status: \"pending\" }\n | { status: \"fulfilled\"; value: T }\n | { status: \"rejected\"; reason: unknown };\n\nexport interface Deferred<T> extends Promise<T> {\n readonly [FARM_DEFERRED_BRAND]: true;\n}\n\nexport interface PreparedDeferredData {\n data: unknown;\n records: readonly DeferredRecord[];\n}\n\nexport interface DeferredRecord {\n id: string;\n promise: Deferred<unknown>;\n}\n\nexport type DeferredSettlement =\n | { status: \"fulfilled\"; value: unknown }\n | { status: \"rejected\"; error: { code: typeof FARM_DEFERRED_ERROR_CODE; message: string } };\n\nexport type DeferredSettlements = Record<string, DeferredSettlement>;\n\nexport interface DeferredDataResponseOptions {\n onError?: (error: unknown, id: string) => void;\n}\n\nexport class DeferredDataError extends Error {\n readonly name = \"DeferredDataError\";\n readonly code = FARM_DEFERRED_ERROR_CODE;\n\n constructor(message = \"Deferred route data failed to load\") {\n super(message);\n }\n}\n\nconst deferredStates = new WeakMap<object, DeferredState>();\n\nexport function defer<T>(value: PromiseLike<T>): Deferred<Awaited<T>> {\n if (isDeferred(value)) {\n return value as Deferred<Awaited<T>>;\n }\n\n const promise = Promise.resolve(value) as Deferred<Awaited<T>>;\n Object.defineProperty(promise, FARM_DEFERRED_BRAND, {\n configurable: false,\n enumerable: false,\n value: true,\n writable: false,\n });\n deferredStates.set(promise, { status: \"pending\" });\n promise.then(\n (resolved) => deferredStates.set(promise, { status: \"fulfilled\", value: resolved }),\n (reason) => deferredStates.set(promise, { status: \"rejected\", reason }),\n );\n return promise;\n}\n\nexport function isDeferred<T = unknown>(value: unknown): value is Deferred<T> {\n return Boolean(\n value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n (value as Record<PropertyKey, unknown>)[FARM_DEFERRED_BRAND] === true,\n );\n}\n\nexport function prepareDeferredData(value: unknown): PreparedDeferredData {\n const context = createEncodingContext();\n return {\n data: encodeDeferredValue(value, context, new WeakSet()),\n records: context.records,\n };\n}\n\nexport function snapshotDeferredData(records: readonly DeferredRecord[]): DeferredSettlements {\n const context = createEncodingContext(records);\n const settlements: DeferredSettlements = {};\n\n for (let index = 0; index < context.records.length; index++) {\n const record = context.records[index]!;\n const state = readDeferredState(record.promise);\n\n if (state.status === \"fulfilled\") {\n try {\n settlements[record.id] = {\n status: \"fulfilled\",\n value: encodeDeferredValue(state.value, context, new WeakSet()),\n };\n } catch {\n settlements[record.id] = createRejectedSettlement();\n }\n } else {\n settlements[record.id] = createRejectedSettlement();\n }\n }\n\n return settlements;\n}\n\nexport function reviveDeferredData<T>(value: T, settlements: DeferredSettlements): T {\n return reviveDeferredValue(value, new Map(), settlements) as T;\n}\n\nexport function createDeferredDataResponse(\n value: unknown,\n init: ResponseInit = {},\n options: DeferredDataResponseOptions = {},\n): Response {\n const context = createEncodingContext();\n const data = encodeDeferredValue(value, context, new WeakSet());\n const headers = new Headers(init.headers);\n\n if (context.records.length === 0) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n return new Response(JSON.stringify(data), { ...init, headers });\n }\n\n headers.set(\"Content-Type\", `${FARM_DEFERRED_CONTENT_TYPE}; charset=utf-8`);\n headers.set(\"Cache-Control\", headers.get(\"Cache-Control\") || \"private, max-age=0\");\n const initialLine = encodeDeferredMessage({ type: \"data\", data });\n const encoder = new TextEncoder();\n let cancelled = false;\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(encoder.encode(initialLine));\n let pending = context.records.length;\n\n const finishRecord = () => {\n pending--;\n if (!cancelled && pending === 0) controller.close();\n };\n\n const schedule = (record: DeferredRecord) => {\n record.promise\n .then(\n (resolved) => {\n if (cancelled) return;\n try {\n const previousLength = context.records.length;\n const encoded = encodeDeferredValue(resolved, context, new WeakSet());\n const nestedRecords = context.records.slice(previousLength);\n pending += nestedRecords.length;\n controller.enqueue(\n encoder.encode(\n encodeDeferredMessage({ type: \"resolve\", id: record.id, data: encoded }),\n ),\n );\n for (const nestedRecord of nestedRecords) schedule(nestedRecord);\n } catch (error) {\n reportDeferredError(options, error, record.id);\n controller.enqueue(\n encoder.encode(\n encodeDeferredMessage({\n type: \"reject\",\n id: record.id,\n error: createDeferredPublicError(),\n }),\n ),\n );\n }\n },\n (error) => {\n if (cancelled) return;\n reportDeferredError(options, error, record.id);\n controller.enqueue(\n encoder.encode(\n encodeDeferredMessage({\n type: \"reject\",\n id: record.id,\n error: createDeferredPublicError(),\n }),\n ),\n );\n },\n )\n .finally(finishRecord);\n };\n\n const initialRecords = context.records.slice();\n for (const record of initialRecords) schedule(record);\n },\n cancel() {\n cancelled = true;\n },\n });\n\n return new Response(stream, { ...init, headers });\n}\n\nexport async function readDeferredDataResponse<T>(response: Response): Promise<T> {\n const contentType = response.headers.get(\"Content-Type\") || \"\";\n if (!contentType.toLowerCase().startsWith(FARM_DEFERRED_CONTENT_TYPE)) {\n return (await response.json()) as T;\n }\n if (!response.body) {\n throw new DeferredDataError(\"Deferred route data response has no body\");\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const controllers = new Map<string, ControlledDeferred>();\n let buffer = \"\";\n let complete = false;\n\n const readLine = async (): Promise<string | undefined> => {\n while (true) {\n const newline = buffer.indexOf(\"\\n\");\n if (newline >= 0) {\n const line = buffer.slice(0, newline);\n buffer = buffer.slice(newline + 1);\n return line;\n }\n if (complete) {\n if (!buffer) return undefined;\n const line = buffer;\n buffer = \"\";\n return line;\n }\n\n const chunk = await reader.read();\n complete = chunk.done;\n if (chunk.value) buffer += decoder.decode(chunk.value, { stream: !chunk.done });\n if (chunk.done) buffer += decoder.decode();\n }\n };\n\n const firstLine = await readLine();\n if (!firstLine) {\n reader.releaseLock();\n throw new DeferredDataError(\"Deferred route data response is empty\");\n }\n\n const initial = parseDeferredMessage(firstLine);\n if (initial.type !== \"data\") {\n reader.releaseLock();\n throw new DeferredDataError(\"Deferred route data response is invalid\");\n }\n const data = reviveDeferredValue(initial.data, controllers) as T;\n\n void (async () => {\n try {\n for (let line = await readLine(); line !== undefined; line = await readLine()) {\n if (!line) continue;\n const message = parseDeferredMessage(line);\n if (message.type === \"resolve\") {\n const controller = getControlledDeferred(message.id, controllers);\n controller.resolve(reviveDeferredValue(message.data, controllers));\n } else if (message.type === \"reject\") {\n getControlledDeferred(message.id, controllers).reject(\n new DeferredDataError(message.error?.message),\n );\n }\n }\n rejectPendingDeferred(controllers, \"Deferred route data stream ended before completion\");\n } catch {\n rejectPendingDeferred(controllers, \"Deferred route data stream could not be read\");\n } finally {\n reader.releaseLock();\n }\n })();\n\n return data;\n}\n\ninterface EncodingContext {\n records: DeferredRecord[];\n ids: Map<Deferred<unknown>, string>;\n nextId: number;\n}\n\ninterface ControlledDeferred {\n promise: Promise<unknown> & {\n status?: \"pending\" | \"fulfilled\" | \"rejected\";\n value?: unknown;\n reason?: unknown;\n };\n resolve(value: unknown): void;\n reject(error: unknown): void;\n}\n\nfunction createEncodingContext(records: readonly DeferredRecord[] = []): EncodingContext {\n return {\n records: [...records],\n ids: new Map(records.map((record) => [record.promise, record.id])),\n nextId: records.reduce((highest, record) => {\n const value = Number(record.id.replace(/^d/, \"\"));\n return Number.isFinite(value) ? Math.max(highest, value + 1) : highest;\n }, records.length),\n };\n}\n\nfunction encodeDeferredValue(\n value: unknown,\n context: EncodingContext,\n ancestors: WeakSet<object>,\n): unknown {\n if (isDeferred(value)) {\n let id = context.ids.get(value);\n if (!id) {\n id = `d${context.nextId++}`;\n context.ids.set(value, id);\n context.records.push({ id, promise: value as Deferred<unknown> });\n }\n return { [FARM_DEFERRED_MARKER]: id };\n }\n if (!value || typeof value !== \"object\") return value;\n if (Array.isArray(value)) {\n assertNotCircular(value, ancestors);\n const output = value.map((item) => encodeDeferredValue(item, context, ancestors));\n ancestors.delete(value);\n return output;\n }\n\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n\n assertNotCircular(value, ancestors);\n const output: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n output[key] = encodeDeferredValue(item, context, ancestors);\n }\n ancestors.delete(value);\n return output;\n}\n\nfunction reviveDeferredValue(\n value: unknown,\n controllers: Map<string, ControlledDeferred>,\n settlements?: DeferredSettlements,\n applyingSettlements = new Set<string>(),\n): unknown {\n if (isDeferredMarker(value)) {\n const id = value[FARM_DEFERRED_MARKER];\n const controller = getControlledDeferred(id, controllers);\n const settlement = settlements?.[id];\n if (settlement && controller.promise.status === \"pending\") {\n if (applyingSettlements.has(id)) return controller.promise;\n applyingSettlements.add(id);\n if (settlement.status === \"fulfilled\") {\n controller.resolve(\n reviveDeferredValue(settlement.value, controllers, settlements, applyingSettlements),\n );\n } else {\n controller.reject(new DeferredDataError(settlement.error.message));\n }\n applyingSettlements.delete(id);\n } else if (settlements && controller.promise.status === \"pending\") {\n controller.reject(new DeferredDataError(\"Deferred route data was not resolved\"));\n }\n return controller.promise;\n }\n if (Array.isArray(value)) {\n return value.map((item) =>\n reviveDeferredValue(item, controllers, settlements, applyingSettlements),\n );\n }\n if (!value || typeof value !== \"object\") return value;\n\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n const output: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value)) {\n output[key] = reviveDeferredValue(item, controllers, settlements, applyingSettlements);\n }\n return output;\n}\n\nfunction getControlledDeferred(\n id: string,\n controllers: Map<string, ControlledDeferred>,\n): ControlledDeferred {\n const existing = controllers.get(id);\n if (existing) return existing;\n\n let nativeResolve!: (value: unknown) => void;\n let nativeReject!: (error: unknown) => void;\n const promise = new Promise<unknown>((resolve, reject) => {\n nativeResolve = resolve;\n nativeReject = reject;\n }) as ControlledDeferred[\"promise\"];\n promise.status = \"pending\";\n promise.catch(() => undefined);\n\n const controlled: ControlledDeferred = {\n promise,\n resolve(value) {\n if (promise.status !== \"pending\") return;\n promise.status = \"fulfilled\";\n promise.value = value;\n nativeResolve(value);\n },\n reject(error) {\n if (promise.status !== \"pending\") return;\n promise.status = \"rejected\";\n promise.reason = error;\n nativeReject(error);\n },\n };\n controllers.set(id, controlled);\n return controlled;\n}\n\nfunction readDeferredState(promise: Deferred<unknown>): DeferredState {\n const tracked = deferredStates.get(promise);\n if (tracked && tracked.status !== \"pending\") return tracked;\n\n const reactState = promise as Deferred<unknown> & {\n status?: string;\n value?: unknown;\n reason?: unknown;\n };\n if (reactState.status === \"fulfilled\") {\n return { status: \"fulfilled\", value: reactState.value };\n }\n if (reactState.status === \"rejected\") {\n return { status: \"rejected\", reason: reactState.reason };\n }\n return tracked || { status: \"pending\" };\n}\n\nfunction isDeferredMarker(value: unknown): value is { [FARM_DEFERRED_MARKER]: string } {\n return Boolean(\n value &&\n typeof value === \"object\" &&\n Object.keys(value).length === 1 &&\n typeof (value as Record<string, unknown>)[FARM_DEFERRED_MARKER] === \"string\",\n );\n}\n\nfunction assertNotCircular(value: object, ancestors: WeakSet<object>): void {\n if (ancestors.has(value)) {\n throw new TypeError(\"Deferred route data must be JSON-serializable and cannot be circular\");\n }\n ancestors.add(value);\n}\n\nfunction createDeferredPublicError() {\n return {\n code: FARM_DEFERRED_ERROR_CODE,\n message: \"Deferred route data failed to load\",\n } as const;\n}\n\nfunction createRejectedSettlement(): DeferredSettlement {\n return { status: \"rejected\", error: createDeferredPublicError() };\n}\n\nfunction reportDeferredError(\n options: DeferredDataResponseOptions,\n error: unknown,\n id: string,\n): void {\n try {\n options.onError?.(error, id);\n } catch {\n // Error reporting must not break the response stream.\n }\n}\n\nfunction encodeDeferredMessage(message: Record<string, unknown>): string {\n return `${JSON.stringify(message)}\\n`;\n}\n\nfunction parseDeferredMessage(line: string): any {\n try {\n return JSON.parse(line);\n } catch {\n throw new DeferredDataError(\"Deferred route data response contains invalid JSON\");\n }\n}\n\nfunction rejectPendingDeferred(\n controllers: Map<string, ControlledDeferred>,\n message: string,\n): void {\n for (const controller of controllers.values()) {\n if (controller.promise.status === \"pending\") {\n controller.reject(new DeferredDataError(message));\n }\n }\n}\n","\"use client\";\n\nimport { readDeferredDataResponse } from \"../deferred\";\nimport {\n createFarmDeploymentMismatchError,\n createFarmDeploymentRequestHeaders,\n isFarmDeploymentMismatchResponse,\n} from \"../deployment\";\nimport type { FarmClientNavigationSession, FarmClientPluginManager } from \"./plugin\";\nimport { _hydrateFarmI18n, isFarmLocaleChangeHref } from \"../i18n/client-runtime\";\nimport type { FarmI18nClientSnapshot } from \"../i18n/types\";\n\n/**\n * Farm.js SPA Router\n *\n * Provides client-side navigation without full page reloads.\n * Features:\n * - Prefetch on viewport intersection\n * - Prefetch on hover\n * - Page caching\n * - History API integration\n * - Scroll restoration\n */\n\ninterface PageData {\n props: Record<string, any>;\n modulePath: string;\n canonicalPath?: string;\n isClientComponent?: boolean;\n shouldHydrate?: boolean;\n metadata?: {\n title?: string;\n description?: string;\n };\n layoutModules?: string[];\n i18n?: FarmI18nClientSnapshot;\n}\n\nexport interface RouterOptions {\n prefetchTimeout?: number;\n cacheMaxAge?: number;\n scrollRestoration?: boolean;\n shouldUseDocumentNavigation?: (pathname: string) => boolean;\n deploymentId?: string;\n}\n\ninterface CacheEntry {\n data: PageData;\n timestamp: number;\n}\n\nexport interface FarmNavigationBlockerContext {\n from: string;\n to: string;\n action: \"push\" | \"replace\" | \"pop\";\n}\n\nexport type FarmNavigationBlocker = (\n context: FarmNavigationBlockerContext,\n) => boolean | void | Promise<boolean | void>;\n\nexport type FarmViewTransitionMode = boolean | \"auto\";\n\nexport interface FarmNavigateOptions {\n replace?: boolean;\n scroll?: boolean;\n state?: unknown;\n viewTransition?: FarmViewTransitionMode;\n}\n\nexport interface FarmNavigationLocation {\n href: string;\n pathname: string;\n search: string;\n hash: string;\n}\n\nexport interface FarmNavigationState {\n state: \"idle\" | \"loading\";\n pending: boolean;\n from: string | null;\n to: FarmNavigationLocation | null;\n action: FarmNavigationBlockerContext[\"action\"] | null;\n startedAt: number | null;\n}\n\nexport type FarmNavigationListener = (state: FarmNavigationState) => void;\n\nconst FARM_PAGE_STATE_KEY = \"__farmPageState\";\nconst IDLE_NAVIGATION_STATE: FarmNavigationState = {\n state: \"idle\",\n pending: false,\n from: null,\n to: null,\n action: null,\n startedAt: null,\n};\n\n// Global router instance\nlet routerInstance: SPARouter | null = null;\n\nexport class SPARouter {\n private cache: Map<string, CacheEntry> = new Map();\n private prefetchingUrls: Set<string> = new Set();\n private observers: Map<Element, IntersectionObserver> = new Map();\n private blockers: Set<FarmNavigationBlocker> = new Set();\n private navigationListeners: Set<FarmNavigationListener> = new Set();\n private navigationState: FarmNavigationState = IDLE_NAVIGATION_STATE;\n private scrollElements: Map<string, HTMLElement> = new Map();\n private options: Required<Omit<RouterOptions, \"deploymentId\">> &\n Pick<RouterOptions, \"deploymentId\">;\n private onNavigate?: (data: PageData) => Promise<void>;\n private clientPlugins?: Pick<\n FarmClientPluginManager,\n | \"beginNavigation\"\n | \"markNavigationLoaded\"\n | \"resolveNavigation\"\n | \"scheduleNavigationRendered\"\n | \"failNavigation\"\n >;\n\n constructor(options: RouterOptions = {}) {\n this.options = {\n prefetchTimeout: options.prefetchTimeout ?? 100,\n cacheMaxAge: options.cacheMaxAge ?? 30000, // 30 seconds\n scrollRestoration: options.scrollRestoration ?? true,\n shouldUseDocumentNavigation: options.shouldUseDocumentNavigation ?? (() => false),\n deploymentId: options.deploymentId ?? readBrowserDeploymentId(),\n };\n\n if (typeof window !== \"undefined\") {\n // Listen for popstate (back/forward navigation)\n window.addEventListener(\"popstate\", this.handlePopState.bind(this));\n\n // Save scroll position before unload\n window.addEventListener(\"beforeunload\", (event) => {\n if (this.blockers.size > 0) {\n event.preventDefault();\n event.returnValue = \"\";\n }\n this.saveScrollPosition(window.location.pathname);\n });\n }\n }\n\n /**\n * Set the navigation handler that updates React\n */\n setNavigationHandler(handler: (data: PageData) => Promise<void>) {\n this.onNavigate = handler;\n }\n\n /**\n * Connect Farm's browser plugin lifecycle to SPA navigation.\n */\n setClientPluginManager(manager: FarmClientPluginManager) {\n this.clientPlugins = manager;\n }\n\n /**\n * Navigate to a new URL\n */\n async navigate(href: string, options: FarmNavigateOptions = {}): Promise<void> {\n const { replace = false, scroll = true, state, viewTransition = false } = options;\n\n // Parse the URL\n const url = new URL(href, window.location.origin);\n const pathname = url.pathname;\n const search = url.search;\n const fullPath = pathname + search;\n\n if (\n isFarmLocaleChangeHref(url.toString()) ||\n this.options.shouldUseDocumentNavigation(pathname)\n ) {\n if (replace) window.location.replace(url.toString());\n else window.location.assign(url.toString());\n return;\n }\n\n // Same page navigation - just update hash/scroll\n if (pathname === window.location.pathname && search === window.location.search) {\n if (url.hash) {\n window.location.hash = url.hash;\n }\n return;\n }\n\n const from = window.location.pathname + window.location.search;\n if (\n await this.shouldBlockNavigation({ from, to: fullPath, action: replace ? \"replace\" : \"push\" })\n ) {\n return;\n }\n\n // Save current scroll position\n if (this.options.scrollRestoration) {\n this.saveScrollPosition(window.location.pathname);\n }\n\n this.startNavigation({\n from,\n to: createNavigationLocation(url),\n action: replace ? \"replace\" : \"push\",\n });\n\n let clientNavigation: FarmClientNavigationSession | undefined;\n try {\n clientNavigation = await this.clientPlugins?.beginNavigation({\n from,\n to: url,\n action: replace ? \"replace\" : \"push\",\n });\n\n // Fetch page data (from cache or server)\n const pageData = await this.fetchPageData(fullPath);\n if (clientNavigation) {\n await this.clientPlugins?.markNavigationLoaded(clientNavigation, pageData);\n }\n\n if (pageData.isClientComponent === false) {\n this.finishNavigation();\n window.location.assign(pageData.canonicalPath || fullPath);\n return;\n }\n\n await this.runViewTransition(viewTransition, () =>\n this.commitNavigation({\n fullPath,\n pageData,\n pathname,\n replace,\n scroll,\n state,\n url,\n }),\n );\n\n if (clientNavigation) {\n await this.clientPlugins?.resolveNavigation(clientNavigation);\n void this.clientPlugins?.scheduleNavigationRendered(clientNavigation);\n }\n this.finishNavigation();\n } catch (error) {\n if (clientNavigation) {\n await this.clientPlugins?.failNavigation(clientNavigation, error);\n }\n this.finishNavigation();\n console.error(\"[Farm.js] Navigation error:\", error);\n // Fall back to full page navigation\n window.location.href = href;\n }\n }\n\n /**\n * Prefetch a URL\n */\n async prefetch(href: string): Promise<void> {\n if (isFarmLocaleChangeHref(href)) return;\n const url = new URL(href, window.location.origin);\n const fullPath = url.pathname + url.search;\n\n // Skip if already prefetching or cached\n if (this.prefetchingUrls.has(fullPath)) return;\n if (this.isCached(fullPath)) return;\n\n this.prefetchingUrls.add(fullPath);\n\n try {\n await this.fetchPageData(fullPath, false);\n } catch (error) {\n console.warn(\"[Farm.js] Prefetch failed:\", href, error);\n } finally {\n this.prefetchingUrls.delete(fullPath);\n }\n }\n\n /**\n * Observe an element for viewport intersection (prefetch when visible)\n */\n observeForPrefetch(element: HTMLAnchorElement): void {\n if (typeof IntersectionObserver === \"undefined\") return;\n\n const href = element.getAttribute(\"href\");\n if (!href || this.isExternalUrl(href)) return;\n\n const observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n // Delay prefetch slightly to avoid prefetching during scroll\n setTimeout(() => {\n this.prefetch(href);\n }, this.options.prefetchTimeout);\n\n // Stop observing after first intersection\n observer.unobserve(element);\n this.observers.delete(element);\n }\n }\n },\n { rootMargin: \"200px\" }, // Start prefetching when 200px from viewport\n );\n\n observer.observe(element);\n this.observers.set(element, observer);\n }\n\n /**\n * Stop observing an element\n */\n unobserveForPrefetch(element: HTMLAnchorElement): void {\n const observer = this.observers.get(element);\n if (observer) {\n observer.unobserve(element);\n this.observers.delete(element);\n }\n }\n\n addBlocker(blocker: FarmNavigationBlocker): () => void {\n this.blockers.add(blocker);\n return () => {\n this.blockers.delete(blocker);\n };\n }\n\n getNavigationState(): FarmNavigationState {\n return this.navigationState;\n }\n\n subscribeNavigation(listener: FarmNavigationListener): () => void {\n this.navigationListeners.add(listener);\n listener(this.navigationState);\n return () => {\n this.navigationListeners.delete(listener);\n };\n }\n\n registerScrollElement(key: string, element: HTMLElement): () => void {\n this.scrollElements.set(key, element);\n this.restoreScrollElement(window.location.pathname, key, element);\n return () => {\n if (this.scrollElements.get(key) === element) {\n this.scrollElements.delete(key);\n }\n };\n }\n\n pushState(state: unknown, href?: string): void {\n this.writePageState(\"push\", state, href);\n }\n\n replaceState(state: unknown, href?: string): void {\n this.writePageState(\"replace\", state, href);\n }\n\n private async commitNavigation(options: {\n fullPath: string;\n pageData: PageData;\n pathname: string;\n replace: boolean;\n scroll: boolean;\n state: unknown;\n url: URL;\n }): Promise<void> {\n const historyPath = options.pageData.canonicalPath || options.fullPath;\n const historyState = createHistoryState(historyPath, options.state);\n if (options.replace) {\n window.history.replaceState(historyState, \"\", historyPath);\n } else {\n window.history.pushState(historyState, \"\", historyPath);\n }\n\n if (options.pageData.metadata?.title) {\n document.title = options.pageData.metadata.title;\n }\n\n if (options.pageData.metadata?.description) {\n let metaDesc = document.querySelector('meta[name=\"description\"]');\n if (!metaDesc) {\n metaDesc = document.createElement(\"meta\");\n metaDesc.setAttribute(\"name\", \"description\");\n document.head.appendChild(metaDesc);\n }\n metaDesc.setAttribute(\"content\", options.pageData.metadata.description);\n }\n\n _hydrateFarmI18n(options.pageData.i18n);\n\n if (this.onNavigate) {\n await this.onNavigate(options.pageData);\n }\n\n if (options.scroll) {\n if (options.url.hash) {\n const element = document.querySelector(options.url.hash);\n if (element) {\n element.scrollIntoView();\n }\n } else {\n window.scrollTo(0, 0);\n }\n } else if (this.options.scrollRestoration) {\n this.restoreScrollPosition(options.pathname);\n }\n }\n\n private async runViewTransition(\n mode: FarmViewTransitionMode,\n callback: () => Promise<void>,\n ): Promise<void> {\n if (!mode || typeof document === \"undefined\") {\n await callback();\n return;\n }\n\n const startViewTransition = (document as any).startViewTransition;\n if (typeof startViewTransition !== \"function\") {\n await callback();\n return;\n }\n\n const transition = startViewTransition.call(document, () => callback());\n const updateDone = transition?.updateCallbackDone || transition?.ready;\n if (updateDone && typeof updateDone.then === \"function\") {\n await updateDone;\n }\n transition?.finished?.catch?.(() => undefined);\n }\n\n /**\n * Fetch page data from cache or server\n */\n private async fetchPageData(path: string, recover = true): Promise<PageData> {\n // Check cache first\n const cached = this.cache.get(path);\n if (cached && Date.now() - cached.timestamp < this.options.cacheMaxAge) {\n return cached.data;\n }\n\n // Fetch from server\n const response = await fetch(`/__farm/page-data?path=${encodeURIComponent(path)}`, {\n headers: createFarmDeploymentRequestHeaders(this.options.deploymentId, {\n Accept: \"application/x-farm-deferred+json, application/json\",\n \"X-Farm-SPA\": \"1\",\n }),\n });\n\n if (isFarmDeploymentMismatchResponse(response, this.options.deploymentId)) {\n const error = createFarmDeploymentMismatchError(\n response,\n this.options.deploymentId || \"unknown\",\n );\n dispatchDeploymentMismatch(error);\n if (recover) {\n window.location.assign(path);\n }\n throw error;\n }\n\n if (!response.ok) {\n throw new Error(`Failed to fetch page data: ${response.status}`);\n }\n\n const data = await readDeferredDataResponse<PageData>(response);\n\n // Cache the result\n this.cache.set(path, {\n data,\n timestamp: Date.now(),\n });\n\n return data;\n }\n\n /**\n * Handle browser back/forward navigation\n */\n private async handlePopState(event: PopStateEvent): Promise<void> {\n if (document.documentElement.dataset.farmDocsRuntime === \"true\") return;\n\n const path = window.location.pathname + window.location.search;\n\n if (\n await this.shouldBlockNavigation({\n from: event.state?.path || path,\n to: path,\n action: \"pop\",\n })\n ) {\n return;\n }\n\n this.startNavigation({\n from: event.state?.path || path,\n to: createNavigationLocation(new URL(window.location.href)),\n action: \"pop\",\n });\n\n let clientNavigation: FarmClientNavigationSession | undefined;\n try {\n clientNavigation = await this.clientPlugins?.beginNavigation({\n from: null,\n to: window.location.href,\n action: \"pop\",\n });\n const pageData = await this.fetchPageData(path);\n if (clientNavigation) {\n await this.clientPlugins?.markNavigationLoaded(clientNavigation, pageData);\n }\n\n // Update document title\n if (pageData.metadata?.title) {\n document.title = pageData.metadata.title;\n }\n\n _hydrateFarmI18n(pageData.i18n);\n\n // Call the navigation handler to update React\n if (this.onNavigate) {\n await this.onNavigate(pageData);\n }\n\n // Restore scroll position\n if (this.options.scrollRestoration) {\n this.restoreScrollPosition(window.location.pathname);\n }\n\n if (clientNavigation) {\n await this.clientPlugins?.resolveNavigation(clientNavigation);\n void this.clientPlugins?.scheduleNavigationRendered(clientNavigation);\n }\n this.finishNavigation();\n } catch (error) {\n if (clientNavigation) {\n await this.clientPlugins?.failNavigation(clientNavigation, error);\n }\n this.finishNavigation();\n console.error(\"[Farm.js] Popstate navigation error:\", error);\n // Reload the page as fallback\n window.location.reload();\n }\n }\n\n /**\n * Check if URL is cached\n */\n private isCached(path: string): boolean {\n const cached = this.cache.get(path);\n return cached !== undefined && Date.now() - cached.timestamp < this.options.cacheMaxAge;\n }\n\n /**\n * Check if URL is external\n */\n private isExternalUrl(href: string): boolean {\n return href.startsWith(\"http://\") || href.startsWith(\"https://\") || href.startsWith(\"//\");\n }\n\n private async shouldBlockNavigation(context: FarmNavigationBlockerContext): Promise<boolean> {\n for (const blocker of this.blockers) {\n if (await blocker(context)) {\n return true;\n }\n }\n return false;\n }\n\n private startNavigation(options: {\n from: string;\n to: FarmNavigationLocation;\n action: FarmNavigationBlockerContext[\"action\"];\n }): void {\n this.setNavigationState({\n state: \"loading\",\n pending: true,\n from: options.from,\n to: options.to,\n action: options.action,\n startedAt: Date.now(),\n });\n }\n\n private finishNavigation(): void {\n this.setNavigationState(IDLE_NAVIGATION_STATE);\n }\n\n private setNavigationState(state: FarmNavigationState): void {\n this.navigationState = state;\n for (const listener of this.navigationListeners) {\n listener(state);\n }\n }\n\n private writePageState(action: \"push\" | \"replace\", state: unknown, href?: string): void {\n if (typeof window === \"undefined\") return;\n\n const url = href ? new URL(href, window.location.origin).toString() : window.location.href;\n const nextState = createHistoryState(\n new URL(url).pathname + new URL(url).search,\n state,\n window.history.state,\n );\n\n if (action === \"replace\") {\n window.history.replaceState(nextState, \"\", url);\n } else {\n window.history.pushState(nextState, \"\", url);\n }\n\n window.dispatchEvent(new PopStateEvent(\"popstate\", { state: nextState }));\n }\n\n /**\n * Save scroll position for a path\n */\n private saveScrollPosition(path: string): void {\n try {\n sessionStorage.setItem(\n `farm-scroll-${path}`,\n JSON.stringify({ x: window.scrollX, y: window.scrollY }),\n );\n for (const [key, element] of this.scrollElements) {\n sessionStorage.setItem(\n getScrollElementStorageKey(path, key),\n JSON.stringify({ x: element.scrollLeft, y: element.scrollTop }),\n );\n }\n } catch {\n // Ignore storage errors\n }\n }\n\n /**\n * Restore scroll position for a path\n */\n private restoreScrollPosition(path: string): void {\n try {\n const saved = sessionStorage.getItem(`farm-scroll-${path}`);\n if (saved) {\n const { x, y } = JSON.parse(saved);\n setTimeout(() => window.scrollTo(x, y), 0);\n }\n for (const [key, element] of this.scrollElements) {\n this.restoreScrollElement(path, key, element);\n }\n } catch {\n // Ignore storage errors\n }\n }\n\n private restoreScrollElement(path: string, key: string, element: HTMLElement): void {\n try {\n const saved = sessionStorage.getItem(getScrollElementStorageKey(path, key));\n if (!saved) return;\n const { x, y } = JSON.parse(saved);\n setTimeout(() => {\n element.scrollLeft = x;\n element.scrollTop = y;\n }, 0);\n } catch {\n // Ignore storage errors\n }\n }\n\n /**\n * Clear the page cache\n */\n clearCache(): void {\n this.cache.clear();\n }\n}\n\nfunction readBrowserDeploymentId(): string | undefined {\n if (typeof window === \"undefined\") return undefined;\n\n const runtimeId = (window as Window & { __FARM_DEPLOYMENT_ID__?: unknown })\n .__FARM_DEPLOYMENT_ID__;\n if (typeof runtimeId === \"string\" && runtimeId) return runtimeId;\n\n return document.querySelector<HTMLMetaElement>('meta[name=\"farm-deployment-id\"]')?.content;\n}\n\nfunction dispatchDeploymentMismatch(error: Error): void {\n if (typeof window === \"undefined\" || typeof CustomEvent === \"undefined\") return;\n window.dispatchEvent(new CustomEvent(\"farm:deployment-mismatch\", { detail: error }));\n}\n\n/**\n * Get or create the global router instance\n */\nexport function getRouter(): SPARouter {\n if (typeof window === \"undefined\") {\n // Return a no-op router for SSR\n return new SPARouter();\n }\n\n const installedRouter = (window as any).__FARM_SPA_ROUTER__ as SPARouter | undefined;\n if (installedRouter) {\n routerInstance = installedRouter;\n return installedRouter;\n }\n\n if (!routerInstance) {\n routerInstance = new SPARouter();\n }\n\n return routerInstance;\n}\n\n/**\n * Navigate to a URL using the SPA router\n */\nexport function navigateTo(href: string, options?: FarmNavigateOptions): Promise<void> {\n return getRouter().navigate(href, options);\n}\n\n/**\n * Prefetch a URL\n */\nexport function prefetch(href: string): Promise<void> {\n return getRouter().prefetch(href);\n}\n\nexport function pushState(state: unknown, href?: string): void {\n getRouter().pushState(state, href);\n}\n\nexport function replaceState(state: unknown, href?: string): void {\n getRouter().replaceState(state, href);\n}\n\nexport function readPageState<TState = unknown>(): TState | null {\n if (typeof window === \"undefined\") return null;\n const state = window.history.state;\n if (!state || typeof state !== \"object\") return null;\n return ((state as Record<string, unknown>)[FARM_PAGE_STATE_KEY] as TState | undefined) ?? null;\n}\n\nfunction createHistoryState(path: string, pageState: unknown, currentState?: unknown) {\n const base =\n currentState && typeof currentState === \"object\" ? { ...(currentState as object) } : {};\n return {\n ...base,\n path,\n [FARM_PAGE_STATE_KEY]: pageState,\n };\n}\n\nfunction createNavigationLocation(url: URL): FarmNavigationLocation {\n return {\n href: url.href,\n pathname: url.pathname,\n search: url.search,\n hash: url.hash,\n };\n}\n\nfunction getScrollElementStorageKey(path: string, key: string): string {\n return `farm-scroll-${path}:${key}`;\n}\n","import IntlMessageFormat from \"intl-messageformat\";\nimport { getActiveFarmI18nSnapshot } from \"./bridge\";\nimport { localizeFarmHref, resolveFarmLocalePath } from \"./routing\";\nimport type {\n FarmI18nClientSnapshot,\n FarmI18nLocale,\n FarmI18nMessageArgs,\n FarmI18nMessageKey,\n FarmTranslator,\n} from \"./types\";\n\ntype Listener = () => void;\n\nconst listeners = new Set<Listener>();\nconst compiled = new Map<string, IntlMessageFormat>();\nlet currentSnapshot: FarmI18nClientSnapshot | undefined;\n\nexport function getFarmI18nClientState(): FarmI18nClientSnapshot | undefined {\n return currentSnapshot || getActiveFarmI18nSnapshot();\n}\n\nexport function subscribeFarmI18n(listener: Listener): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n}\n\nexport function _hydrateFarmI18n(snapshot: FarmI18nClientSnapshot | undefined): void {\n if (!snapshot) return;\n const changed = currentSnapshot?.locale !== snapshot.locale;\n currentSnapshot = snapshot;\n if (typeof window !== \"undefined\") window.__FARM_I18N__ = snapshot;\n if (typeof document !== \"undefined\") {\n document.documentElement.lang = snapshot.locale;\n document.documentElement.dir = snapshot.direction;\n }\n if (changed) compiled.clear();\n for (const listener of listeners) listener();\n}\n\nconst translate = (key: string, values?: Record<string, unknown>, rich = false): unknown => {\n const snapshot = requireSnapshot();\n const message = snapshot.messages[key];\n if (message === undefined) return key;\n const cacheKey = `${snapshot.locale}\\u0000${key}\\u0000${message}`;\n let formatter = compiled.get(cacheKey);\n if (!formatter) {\n formatter = new IntlMessageFormat(message, snapshot.locale);\n compiled.set(cacheKey, formatter);\n }\n const result = formatter.format(values as any);\n if (rich) return Array.isArray(result) && result.length === 1 ? result[0] : result;\n if (Array.isArray(result) && result.some((part) => typeof part !== \"string\")) {\n throw new Error(`Farm i18n message \"${key}\" contains rich content. Render it with t.rich().`);\n }\n return Array.isArray(result) ? result.join(\"\") : String(result);\n};\n\nexport const t = ((key: string, values?: Record<string, unknown>) =>\n translate(key, values)) as FarmTranslator;\nt.rich = (key: string, values?: Record<string, unknown>) => translate(key, values, true);\nt.raw = (key: string) => requireSnapshot().messages[key] ?? key;\nt.has = (key: string) => key in requireSnapshot().messages;\n\nexport function localizeActiveFarmHref(href: string, locale?: FarmI18nLocale): string {\n const snapshot = getFarmI18nClientState();\n if (!snapshot) return href;\n return localizeFarmHref(href, locale || snapshot.locale, snapshot);\n}\n\nexport function isFarmLocaleChangeHref(href: string): boolean {\n const snapshot = getFarmI18nClientState();\n if (!snapshot || typeof window === \"undefined\") return false;\n if (snapshot.routing === \"none\") return false;\n const target = new URL(href, window.location.origin);\n const match = resolveFarmLocalePath(target.pathname, snapshot);\n const targetLocale = match.locale || snapshot.defaultLocale;\n return targetLocale !== snapshot.locale;\n}\n\nexport function createFarmClientTranslator(): FarmTranslator {\n return (<TKey extends FarmI18nMessageKey>(key: TKey, ...args: FarmI18nMessageArgs<TKey>) =>\n t(key, ...args)) as FarmTranslator;\n}\n\nfunction requireSnapshot(): FarmI18nClientSnapshot {\n const snapshot = getFarmI18nClientState();\n if (!snapshot) {\n throw new Error(\"Farm i18n is not configured or has not been hydrated.\");\n }\n return snapshot;\n}\n","export type FarmRedirectStatus = 301 | 302 | 303 | 307 | 308;\n\nexport interface FarmRedirectSignal {\n url: string;\n status: FarmRedirectStatus;\n}\n\nconst REDIRECT_ERROR_CODE = \"FARM_REDIRECT\";\nconst NOT_FOUND_ERROR_CODE = \"FARM_NOT_FOUND\";\nconst REDIRECT_ERROR_SYMBOL = Symbol.for(\"farm.navigation.redirect\");\nconst NOT_FOUND_ERROR_SYMBOL = Symbol.for(\"farm.navigation.notFound\");\n\ntype FarmNavigationError = Error & {\n digest: string;\n [REDIRECT_ERROR_SYMBOL]?: FarmRedirectSignal;\n [NOT_FOUND_ERROR_SYMBOL]?: true;\n};\n\nexport function redirect(url: string, status: FarmRedirectStatus = 307): never {\n throw createRedirectError(url, status);\n}\n\nexport function permanentRedirect(url: string): never {\n redirect(url, 308);\n}\n\nexport function notFound(): never {\n const error = new Error(NOT_FOUND_ERROR_CODE) as FarmNavigationError;\n error.digest = NOT_FOUND_ERROR_CODE;\n error[NOT_FOUND_ERROR_SYMBOL] = true;\n throw error;\n}\n\nexport function isFarmRedirectError(error: unknown): boolean {\n return Boolean(getFarmRedirectError(error));\n}\n\nexport function getFarmRedirectError(error: unknown): FarmRedirectSignal | null {\n if (!error || typeof error !== \"object\") return null;\n const candidate = error as Partial<FarmNavigationError>;\n if (candidate[REDIRECT_ERROR_SYMBOL]) {\n return candidate[REDIRECT_ERROR_SYMBOL] as FarmRedirectSignal;\n }\n\n if (\n typeof candidate.digest === \"string\" &&\n candidate.digest.startsWith(`${REDIRECT_ERROR_CODE};`)\n ) {\n const [, status, ...urlParts] = candidate.digest.split(\";\");\n const parsedStatus = Number(status);\n if (isRedirectStatus(parsedStatus)) {\n return {\n status: parsedStatus,\n url: urlParts.join(\";\"),\n };\n }\n }\n\n return null;\n}\n\nexport function isFarmNotFoundError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const candidate = error as Partial<FarmNavigationError>;\n return Boolean(candidate[NOT_FOUND_ERROR_SYMBOL] || candidate.digest === NOT_FOUND_ERROR_CODE);\n}\n\nfunction createRedirectError(url: string, status: FarmRedirectStatus): FarmNavigationError {\n const error = new Error(`${REDIRECT_ERROR_CODE};${status};${url}`) as FarmNavigationError;\n error.digest = `${REDIRECT_ERROR_CODE};${status};${url}`;\n error[REDIRECT_ERROR_SYMBOL] = { url, status };\n return error;\n}\n\nfunction isRedirectStatus(status: number): status is FarmRedirectStatus {\n return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;\n}\n","import type { Metadata } from \"./types\";\n\nexport type MetadataImageKind = \"opengraph\" | \"twitter\";\n\nexport interface FarmMetadataImageReference {\n kind: MetadataImageKind;\n href: string;\n alt?: string;\n width?: number;\n height?: number;\n contentType?: string;\n}\n\nexport interface RenderedMetadataHead {\n title: string;\n tags: string;\n hasFavicon: boolean;\n}\n\ntype MetadataRecord = Metadata & Record<string, any>;\n\nexport function mergeMetadata(\n base: MetadataRecord | undefined,\n next: MetadataRecord | undefined,\n): MetadataRecord {\n if (!base) return next ? { ...next } : {};\n if (!next) return { ...base };\n\n return {\n ...base,\n ...next,\n openGraph: mergeNestedMetadata(base.openGraph, next.openGraph),\n twitter: mergeNestedMetadata(base.twitter, next.twitter),\n alternates: mergeNestedMetadata((base as any).alternates, (next as any).alternates),\n icons: mergeNestedMetadata((base as any).icons, (next as any).icons),\n };\n}\n\nexport function addMetadataImageReference(\n metadata: MetadataRecord,\n reference: FarmMetadataImageReference,\n): MetadataRecord {\n if (reference.kind === \"opengraph\") {\n const openGraph = { ...(metadata.openGraph || {}) };\n if (!hasMetadataImages(openGraph.images) && !hasMetadataImages((openGraph as any).image)) {\n openGraph.images = [\n {\n url: reference.href,\n width: reference.width,\n height: reference.height,\n alt: reference.alt,\n type: reference.contentType,\n },\n ];\n }\n\n return {\n ...metadata,\n openGraph,\n };\n }\n\n const twitter = { ...(metadata.twitter || {}) };\n if (!hasMetadataImages(twitter.images)) {\n twitter.images = [reference.href];\n twitter.card = twitter.card || \"summary_large_image\";\n }\n\n return {\n ...metadata,\n twitter,\n };\n}\n\nexport function renderMetadataHead(metadata: MetadataRecord | undefined): RenderedMetadataHead {\n const resolvedMetadata = metadata || {};\n const metadataBase = resolveMetadataBase(resolvedMetadata);\n const title = resolveMetadataTitle(resolvedMetadata.title) || \"Farm.js App\";\n const tags: string[] = [];\n\n appendMetaName(tags, \"description\", resolvedMetadata.description);\n appendMetaName(tags, \"keywords\", normalizeKeywords(resolvedMetadata.keywords));\n appendMetaName(tags, \"author\", (resolvedMetadata as any).author);\n\n if (Array.isArray(resolvedMetadata.authors)) {\n for (const author of resolvedMetadata.authors) {\n appendMetaName(tags, \"author\", author?.name);\n if (author?.url) {\n appendLink(tags, \"author\", resolveMetadataUrl(author.url, metadataBase));\n }\n }\n }\n\n appendMetaName(tags, \"creator\", resolvedMetadata.creator);\n appendMetaName(tags, \"publisher\", resolvedMetadata.publisher);\n appendMetaName(tags, \"robots\", normalizeRobots(resolvedMetadata.robots));\n\n const alternates = (resolvedMetadata as any).alternates;\n if (isRecord(alternates)) {\n appendLink(tags, \"canonical\", resolveMetadataUrl(alternates.canonical, metadataBase));\n\n if (isRecord(alternates.languages)) {\n for (const [language, href] of Object.entries(alternates.languages)) {\n appendLink(tags, \"alternate\", resolveMetadataUrl(href, metadataBase), {\n hreflang: language,\n });\n }\n }\n }\n\n const hasFavicon = appendIcons(tags, (resolvedMetadata as any).icons, metadataBase);\n\n if ((resolvedMetadata as any).manifest) {\n appendLink(\n tags,\n \"manifest\",\n resolveMetadataUrl((resolvedMetadata as any).manifest, metadataBase),\n );\n }\n\n appendOpenGraph(tags, resolvedMetadata.openGraph, metadataBase);\n appendTwitter(tags, resolvedMetadata.twitter, metadataBase);\n\n return {\n title: escapeText(title),\n tags: tags.length > 0 ? `\\n ${tags.join(\"\\n \")}` : \"\",\n hasFavicon,\n };\n}\n\nfunction mergeNestedMetadata(base: unknown, next: unknown): any {\n if (isRecord(base) && isRecord(next)) {\n return {\n ...base,\n ...next,\n };\n }\n\n return next ?? base;\n}\n\nfunction appendOpenGraph(tags: string[], openGraph: Metadata[\"openGraph\"], metadataBase?: string) {\n if (!isRecord(openGraph)) return;\n\n appendMetaProperty(tags, \"og:title\", openGraph.title);\n appendMetaProperty(tags, \"og:description\", openGraph.description);\n appendMetaProperty(tags, \"og:url\", resolveMetadataUrl(openGraph.url, metadataBase));\n appendMetaProperty(tags, \"og:site_name\", openGraph.siteName);\n appendMetaProperty(tags, \"og:type\", openGraph.type);\n appendMetaProperty(tags, \"og:locale\", (openGraph as any).locale);\n\n const images = normalizeMetadataImages(\n openGraph.images ?? (openGraph as any).image,\n metadataBase,\n );\n for (const image of images) {\n appendMetaProperty(tags, \"og:image\", image.url);\n appendMetaProperty(tags, \"og:image:width\", image.width);\n appendMetaProperty(tags, \"og:image:height\", image.height);\n appendMetaProperty(tags, \"og:image:alt\", image.alt);\n appendMetaProperty(tags, \"og:image:type\", image.type);\n }\n}\n\nfunction appendTwitter(tags: string[], twitter: Metadata[\"twitter\"], metadataBase?: string) {\n if (!isRecord(twitter)) return;\n\n appendMetaName(tags, \"twitter:card\", twitter.card);\n appendMetaName(tags, \"twitter:site\", twitter.site);\n appendMetaName(tags, \"twitter:creator\", twitter.creator);\n appendMetaName(tags, \"twitter:title\", twitter.title);\n appendMetaName(tags, \"twitter:description\", twitter.description);\n\n for (const image of normalizeMetadataImages(twitter.images, metadataBase)) {\n appendMetaName(tags, \"twitter:image\", image.url);\n appendMetaName(tags, \"twitter:image:alt\", image.alt);\n }\n}\n\nfunction appendIcons(tags: string[], icons: unknown, metadataBase?: string): boolean {\n if (!icons) return false;\n\n if (typeof icons === \"string\") {\n const initialTagCount = tags.length;\n appendLink(tags, \"icon\", resolveMetadataUrl(icons, metadataBase));\n return tags.length > initialTagCount;\n }\n\n if (!isRecord(icons)) return false;\n\n const initialTagCount = tags.length;\n appendIconList(tags, \"icon\", icons.icon, metadataBase);\n appendIconList(tags, \"shortcut icon\", icons.shortcut, metadataBase);\n const hasFavicon = tags.length > initialTagCount;\n appendIconList(tags, \"apple-touch-icon\", icons.apple, metadataBase);\n return hasFavicon;\n}\n\nfunction appendIconList(tags: string[], rel: string, value: unknown, metadataBase?: string) {\n for (const icon of normalizeArray(value)) {\n if (typeof icon === \"string\") {\n appendLink(tags, rel, resolveMetadataUrl(icon, metadataBase));\n continue;\n }\n\n if (!isRecord(icon)) continue;\n appendLink(tags, rel, resolveMetadataUrl(icon.url, metadataBase), {\n sizes: icon.sizes,\n type: icon.type,\n });\n }\n}\n\nfunction appendMetaName(tags: string[], name: string, content: unknown) {\n const normalized = normalizeContent(content);\n if (!normalized) return;\n tags.push(`<meta name=\"${escapeAttribute(name)}\" content=\"${escapeAttribute(normalized)}\">`);\n}\n\nfunction appendMetaProperty(tags: string[], property: string, content: unknown) {\n const normalized = normalizeContent(content);\n if (!normalized) return;\n tags.push(\n `<meta property=\"${escapeAttribute(property)}\" content=\"${escapeAttribute(normalized)}\">`,\n );\n}\n\nfunction appendLink(\n tags: string[],\n rel: string,\n href: unknown,\n attrs: Record<string, unknown> = {},\n) {\n const normalizedHref = normalizeContent(href);\n if (!normalizedHref) return;\n\n const attrText = Object.entries(attrs)\n .map(([key, value]) => {\n const normalized = normalizeContent(value);\n return normalized ? ` ${key}=\"${escapeAttribute(normalized)}\"` : \"\";\n })\n .join(\"\");\n\n tags.push(\n `<link rel=\"${escapeAttribute(rel)}\" href=\"${escapeAttribute(normalizedHref)}\"${attrText}>`,\n );\n}\n\nfunction normalizeMetadataImages(\n value: unknown,\n metadataBase?: string,\n): Array<{\n url: string;\n width?: number;\n height?: number;\n alt?: string;\n type?: string;\n}> {\n return normalizeArray(value)\n .map((item) => {\n if (typeof item === \"string\") {\n return { url: resolveMetadataUrl(item, metadataBase) || item };\n }\n\n if (!isRecord(item)) return null;\n const rawUrl = item.url || item.src;\n const url = resolveMetadataUrl(rawUrl, metadataBase);\n if (!url) return null;\n\n return {\n url,\n width: normalizeNumber(item.width),\n height: normalizeNumber(item.height),\n alt: typeof item.alt === \"string\" ? item.alt : undefined,\n type: typeof item.type === \"string\" ? item.type : undefined,\n };\n })\n .filter((item): item is NonNullable<typeof item> => item !== null);\n}\n\nfunction normalizeArray(value: unknown): unknown[] {\n if (value == null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nfunction hasMetadataImages(value: unknown): boolean {\n return normalizeMetadataImages(value).length > 0;\n}\n\nfunction resolveMetadataTitle(title: Metadata[\"title\"]): string | undefined {\n if (typeof title === \"string\") return title;\n if (isRecord(title)) {\n return normalizeContent(title.default);\n }\n return undefined;\n}\n\nfunction normalizeKeywords(keywords: Metadata[\"keywords\"]): string | undefined {\n if (Array.isArray(keywords)) return keywords.filter(Boolean).join(\", \");\n return keywords;\n}\n\nfunction normalizeRobots(robots: Metadata[\"robots\"]): string | undefined {\n if (typeof robots === \"string\") return robots;\n if (!isRecord(robots)) return undefined;\n\n const values: string[] = [];\n if (typeof robots.index === \"boolean\") values.push(robots.index ? \"index\" : \"noindex\");\n if (typeof robots.follow === \"boolean\") values.push(robots.follow ? \"follow\" : \"nofollow\");\n return values.join(\", \") || undefined;\n}\n\nfunction resolveMetadataBase(metadata: MetadataRecord): string | undefined {\n const base = metadata.metadataBase;\n if (!base) return undefined;\n return String(base);\n}\n\nfunction resolveMetadataUrl(value: unknown, metadataBase?: string): string | undefined {\n const normalized = normalizeContent(value);\n if (!normalized) return undefined;\n if (!metadataBase) return normalized;\n\n try {\n return new URL(normalized, metadataBase).toString();\n } catch {\n return normalized;\n }\n}\n\nfunction normalizeNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\") {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n}\n\nfunction normalizeContent(value: unknown): string | undefined {\n if (value == null) return undefined;\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n if (value instanceof URL) return value.toString();\n return undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, any> {\n return !!value && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction escapeText(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nfunction escapeAttribute(value: string): string {\n return escapeText(value).replace(/\"/g, \"&quot;\");\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { FarmLocaleResolution } from \"./resolver\";\nimport { _setFarmI18nSnapshotResolver } from \"./bridge\";\nimport { FarmI18nRuntime, createFarmI18nRuntime } from \"./runtime\";\nimport type {\n FarmI18nClientSnapshot,\n FarmI18nLocale,\n FarmI18nLocaleSource,\n FarmI18nMessageArgs,\n FarmI18nMessageKey,\n FarmTranslator,\n} from \"./types\";\n\ninterface FarmI18nRequestState {\n runtime: FarmI18nRuntime;\n resolution: FarmLocaleResolution;\n snapshot: FarmI18nClientSnapshot;\n}\n\ninterface FarmListFormatOptions {\n localeMatcher?: \"lookup\" | \"best fit\";\n type?: \"conjunction\" | \"disjunction\" | \"unit\";\n style?: \"long\" | \"short\" | \"narrow\";\n}\n\nconst FARM_I18N_REQUEST_STORE = Symbol.for(\"farm.i18n.requestStore\");\nconst FARM_I18N_DEFAULT_RUNTIME = Symbol.for(\"farm.i18n.defaultRuntime\");\n\ntype GlobalFarmI18nState = typeof globalThis & {\n [FARM_I18N_REQUEST_STORE]?: AsyncLocalStorage<FarmI18nRequestState>;\n [FARM_I18N_DEFAULT_RUNTIME]?: FarmI18nRuntime;\n};\n\nfunction getRequestStore(): AsyncLocalStorage<FarmI18nRequestState> {\n const state = globalThis as GlobalFarmI18nState;\n return (state[FARM_I18N_REQUEST_STORE] ??= new AsyncLocalStorage<FarmI18nRequestState>());\n}\n\nfunction getState(): FarmI18nRequestState {\n const state = getRequestStore().getStore();\n if (!state) {\n throw new Error(\n \"No Farm i18n request context is active. Use this API while rendering, inside an API route, or use createTranslator(locale).\",\n );\n }\n return state;\n}\n\nexport function _setDefaultFarmI18nRuntime(runtime: FarmI18nRuntime | undefined): void {\n (globalThis as GlobalFarmI18nState)[FARM_I18N_DEFAULT_RUNTIME] = runtime;\n}\n\nexport async function _runWithFarmI18nRequest<T>(\n runtime: FarmI18nRuntime,\n request: Request,\n fn: (resolution: FarmLocaleResolution) => T | Promise<T>,\n options: { redirect?: boolean } = {},\n): Promise<T> {\n const resolution = runtime.resolveRequest(request, options);\n const state: FarmI18nRequestState = {\n runtime,\n resolution,\n snapshot: runtime.getClientSnapshot(resolution),\n };\n return getRequestStore().run(state, () => fn(resolution));\n}\n\nexport async function runWithLocale<T>(\n locale: FarmI18nLocale,\n fn: () => T | Promise<T>,\n): Promise<T> {\n const runtime = getDefaultRuntime();\n assertLocale(runtime, locale);\n const resolution: FarmLocaleResolution = {\n locale,\n source: \"explicit\",\n pathname: \"/\",\n persist: false,\n };\n const state: FarmI18nRequestState = {\n runtime,\n resolution,\n snapshot: runtime.getClientSnapshot(resolution),\n };\n return getRequestStore().run(state, fn);\n}\n\nexport function getLocale(): FarmI18nLocale {\n return getState().resolution.locale as FarmI18nLocale;\n}\n\nexport function getLocaleSource(): FarmI18nLocaleSource {\n return getState().resolution.source;\n}\n\nexport const t = createTranslatorFromState(() => getState());\n\nexport function createTranslator(locale: FarmI18nLocale): FarmTranslator {\n const runtime = getDefaultRuntime();\n assertLocale(runtime, locale);\n return createTranslatorFromState(() => ({\n runtime,\n resolution: {\n locale,\n source: \"explicit\",\n pathname: \"/\",\n persist: false,\n },\n snapshot: runtime.getClientSnapshot({\n locale,\n source: \"explicit\",\n pathname: \"/\",\n persist: false,\n }),\n }));\n}\n\nexport function getFarmI18nClientSnapshot(): FarmI18nClientSnapshot | undefined {\n return getRequestStore().getStore()?.snapshot;\n}\n\nexport const format = {\n number(value: number, options?: Intl.NumberFormatOptions): string {\n return new Intl.NumberFormat(getLocale(), options).format(value);\n },\n currency(\n value: number,\n currency: string,\n options: Omit<Intl.NumberFormatOptions, \"style\" | \"currency\"> = {},\n ): string {\n return new Intl.NumberFormat(getLocale(), {\n ...options,\n style: \"currency\",\n currency,\n }).format(value);\n },\n date(value: Date | number, options?: Intl.DateTimeFormatOptions): string {\n return new Intl.DateTimeFormat(getLocale(), options).format(value);\n },\n relativeTime(\n value: number,\n unit: Intl.RelativeTimeFormatUnit,\n options?: Intl.RelativeTimeFormatOptions,\n ): string {\n return new Intl.RelativeTimeFormat(getLocale(), options).format(value, unit);\n },\n list(values: Iterable<string>, options?: FarmListFormatOptions): string {\n const ListFormat = (Intl as any).ListFormat;\n return new ListFormat(getLocale(), options).format(Array.from(values));\n },\n};\n\nfunction getDefaultRuntime(): FarmI18nRuntime {\n const runtime = (globalThis as GlobalFarmI18nState)[FARM_I18N_DEFAULT_RUNTIME];\n if (!runtime?.config.enabled) {\n throw new Error(\"Farm i18n is not configured for this application.\");\n }\n return runtime;\n}\n\nfunction assertLocale(runtime: FarmI18nRuntime, locale: string): void {\n if (!runtime.config.locales.includes(locale)) {\n throw new Error(`Unsupported Farm i18n locale \"${locale}\".`);\n }\n}\n\nfunction createTranslatorFromState(resolveState: () => FarmI18nRequestState): FarmTranslator {\n const translator = ((key: string, values?: Record<string, unknown>) => {\n const state = resolveState();\n return state.runtime.translate(state.resolution.locale, key, values);\n }) as FarmTranslator;\n translator.rich = (key: string, values?: Record<string, unknown>) => {\n const state = resolveState();\n return state.runtime.translateRich(state.resolution.locale, key, values);\n };\n translator.raw = (key: string) => {\n const state = resolveState();\n return state.runtime.getRawMessage(state.resolution.locale, key);\n };\n translator.has = (key: string) => {\n const state = resolveState();\n return state.runtime.hasMessage(state.resolution.locale, key);\n };\n return translator;\n}\n\n_setFarmI18nSnapshotResolver(() => getFarmI18nClientSnapshot());\n\nexport { FarmI18nRuntime, createFarmI18nRuntime };\nexport type { FarmI18nClientSnapshot, FarmI18nLocale, FarmI18nMessageArgs, FarmI18nMessageKey };\n","import IntlMessageFormat from \"intl-messageformat\";\nimport { readFarmI18nCatalogs } from \"./catalog\";\nimport { getFarmLocaleDirection } from \"./routing\";\nimport { resolveFarmLocaleRequest, type FarmLocaleResolution } from \"./resolver\";\nimport type { FarmI18nCatalogs, FarmI18nClientSnapshot, ResolvedFarmI18nConfig } from \"./types\";\n\nexport class FarmI18nRuntime {\n readonly config: ResolvedFarmI18nConfig;\n private catalogs: FarmI18nCatalogs;\n private compiled = new Map<string, IntlMessageFormat>();\n private warnedMissing = new Set<string>();\n\n constructor(config: ResolvedFarmI18nConfig, catalogs: FarmI18nCatalogs = {}) {\n this.config = config;\n this.catalogs = catalogs;\n }\n\n async initialize(): Promise<void> {\n if (!this.config.enabled) return;\n const bundle = await readFarmI18nCatalogs(this.config);\n this.replaceCatalogs(bundle.catalogs);\n }\n\n async reload(): Promise<void> {\n await this.initialize();\n }\n\n replaceCatalogs(catalogs: FarmI18nCatalogs): void {\n this.catalogs = catalogs;\n this.compiled.clear();\n this.warnedMissing.clear();\n }\n\n getCatalogs(): FarmI18nCatalogs {\n return Object.fromEntries(\n Object.entries(this.catalogs).map(([locale, catalog]) => [locale, { ...catalog }]),\n );\n }\n\n resolveRequest(request: Request, options: { redirect?: boolean } = {}): FarmLocaleResolution {\n return resolveFarmLocaleRequest(request, this.config, options);\n }\n\n translate(locale: string, key: string, values?: Record<string, unknown>): string {\n const result = this.formatMessage(locale, key, values);\n if (Array.isArray(result) && result.some((part) => typeof part !== \"string\")) {\n throw new Error(`Farm i18n message \"${key}\" contains rich content. Render it with t.rich().`);\n }\n return Array.isArray(result) ? result.join(\"\") : String(result);\n }\n\n translateRich(locale: string, key: string, values?: Record<string, unknown>): unknown {\n const result = this.formatMessage(locale, key, values);\n return Array.isArray(result) && result.length === 1 ? result[0] : result;\n }\n\n getRawMessage(locale: string, key: string): string {\n return this.resolveMessage(locale, key);\n }\n\n hasMessage(locale: string, key: string): boolean {\n return (\n (this.catalogs[locale]?.[key] ?? this.catalogs[this.config.fallbackLocale]?.[key]) !==\n undefined\n );\n }\n\n getClientSnapshot(resolution: FarmLocaleResolution): FarmI18nClientSnapshot {\n return {\n locale: resolution.locale,\n source: resolution.source,\n locales: this.config.locales,\n defaultLocale: this.config.defaultLocale,\n routing: this.config.routing,\n cookie: this.config.cookie,\n direction: getFarmLocaleDirection(resolution.locale, this.config.direction),\n messages: {\n ...(this.catalogs[this.config.fallbackLocale] || {}),\n ...(this.catalogs[resolution.locale] || {}),\n },\n };\n }\n\n private formatMessage(locale: string, key: string, values?: Record<string, unknown>): unknown {\n const message = this.resolveMessage(locale, key);\n const cacheKey = `${locale}\\u0000${key}\\u0000${message}`;\n let formatter = this.compiled.get(cacheKey);\n if (!formatter) {\n formatter = new IntlMessageFormat(message, locale);\n this.compiled.set(cacheKey, formatter);\n }\n return formatter.format(values as any);\n }\n\n private resolveMessage(locale: string, key: string): string {\n const message =\n this.catalogs[locale]?.[key] ?? this.catalogs[this.config.fallbackLocale]?.[key];\n if (message !== undefined) return message;\n if (this.config.strict) {\n throw new Error(`Missing Farm i18n message \"${key}\" for locale \"${locale}\".`);\n }\n const warningKey = `${locale}:${key}`;\n if (!this.warnedMissing.has(warningKey)) {\n this.warnedMissing.add(warningKey);\n console.warn(`[Farm.js] Missing i18n message \"${key}\" for locale \"${locale}\".`);\n }\n return key;\n }\n}\n\nexport function createFarmI18nRuntime(\n config: ResolvedFarmI18nConfig,\n catalogs?: FarmI18nCatalogs,\n): FarmI18nRuntime {\n return new FarmI18nRuntime(config, catalogs);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { TYPE, parse, type MessageFormatElement } from \"@formatjs/icu-messageformat-parser\";\nimport { resolveFarmI18nMessagePath } from \"./config\";\nimport type { FarmI18nCatalog, FarmI18nCatalogs, ResolvedFarmI18nConfig } from \"./types\";\n\nexport type FarmI18nArgumentKind = \"string\" | \"number\" | \"date\" | \"select\" | \"rich\";\nexport type FarmI18nMessageSignature = Record<string, FarmI18nArgumentKind>;\n\nexport interface FarmI18nCatalogBundle {\n catalogs: FarmI18nCatalogs;\n signatures: Record<string, FarmI18nMessageSignature>;\n}\n\nexport async function readFarmI18nCatalogs(\n config: ResolvedFarmI18nConfig,\n): Promise<FarmI18nCatalogBundle> {\n if (!config.enabled) {\n return { catalogs: {}, signatures: {} };\n }\n\n const catalogs: FarmI18nCatalogs = {};\n for (const locale of config.locales) {\n const filePath = resolveFarmI18nMessagePath(config, locale);\n let source: string;\n try {\n source = await readFile(filePath, \"utf8\");\n } catch (error) {\n throw new Error(\n `Unable to read Farm i18n catalog for \"${locale}\" at ${filePath}: ${messageOf(error)}`,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(source);\n } catch (error) {\n throw new Error(`Invalid JSON in Farm i18n catalog ${filePath}: ${messageOf(error)}`);\n }\n catalogs[locale] = flattenFarmI18nCatalog(parsed, filePath);\n }\n\n const reference = catalogs[config.defaultLocale] || {};\n const signatures: Record<string, FarmI18nMessageSignature> = {};\n for (const [key, message] of Object.entries(reference)) {\n signatures[key] = analyzeFarmI18nMessage(message, `${config.defaultLocale}:${key}`);\n }\n\n validateFarmI18nCatalogs(config, catalogs, signatures);\n return { catalogs, signatures };\n}\n\nexport function flattenFarmI18nCatalog(input: unknown, source = \"i18n catalog\"): FarmI18nCatalog {\n if (!isPlainObject(input)) {\n throw new Error(`${source} must contain a JSON object at its root.`);\n }\n\n const output: FarmI18nCatalog = {};\n const visit = (value: unknown, segments: string[]) => {\n if (typeof value === \"string\") {\n const key = segments.join(\".\");\n if (!key) throw new Error(`${source} contains an empty message key.`);\n if (key in output) throw new Error(`${source} contains duplicate message key \"${key}\".`);\n output[key] = value;\n return;\n }\n\n if (!isPlainObject(value)) {\n const key = segments.join(\".\") || \"<root>\";\n throw new Error(`${source} message \"${key}\" must be a string or nested object.`);\n }\n\n for (const [key, nested] of Object.entries(value)) {\n if (!key.trim()) throw new Error(`${source} contains an empty message key.`);\n visit(nested, [...segments, key]);\n }\n };\n\n visit(input, []);\n return output;\n}\n\nexport function analyzeFarmI18nMessage(\n message: string,\n label = \"message\",\n): FarmI18nMessageSignature {\n let ast: MessageFormatElement[];\n try {\n ast = parse(message, { captureLocation: false });\n } catch (error) {\n throw new Error(`Invalid ICU syntax in ${label}: ${messageOf(error)}`);\n }\n\n const signature: FarmI18nMessageSignature = {};\n collectArguments(ast, signature, label);\n return signature;\n}\n\nfunction validateFarmI18nCatalogs(\n config: ResolvedFarmI18nConfig,\n catalogs: FarmI18nCatalogs,\n signatures: Record<string, FarmI18nMessageSignature>,\n): void {\n const referenceKeys = Object.keys(catalogs[config.defaultLocale] || {}).sort();\n\n for (const locale of config.locales) {\n const catalog = catalogs[locale] || {};\n const localeKeys = Object.keys(catalog).sort();\n const missing = referenceKeys.filter((key) => !(key in catalog));\n const extra = localeKeys.filter((key) => !(key in signatures));\n\n if (config.strict && (missing.length > 0 || extra.length > 0)) {\n const details = [\n missing.length ? `missing: ${missing.join(\", \")}` : \"\",\n extra.length ? `extra: ${extra.join(\", \")}` : \"\",\n ]\n .filter(Boolean)\n .join(\"; \");\n throw new Error(\n `Farm i18n catalog \"${locale}\" does not match the default catalog (${details}).`,\n );\n }\n\n for (const [key, message] of Object.entries(catalog)) {\n const actual = analyzeFarmI18nMessage(message, `${locale}:${key}`);\n const expected = signatures[key];\n if (!expected || sameSignature(expected, actual)) continue;\n throw new Error(\n `Farm i18n message \"${key}\" in \"${locale}\" uses different variables than \"${config.defaultLocale}\".`,\n );\n }\n }\n}\n\nfunction collectArguments(\n elements: MessageFormatElement[],\n signature: FarmI18nMessageSignature,\n label: string,\n): void {\n for (const element of elements) {\n switch (element.type) {\n case TYPE.argument:\n addArgument(signature, element.value, \"string\", label);\n break;\n case TYPE.number:\n case TYPE.plural:\n addArgument(signature, element.value, \"number\", label);\n break;\n case TYPE.date:\n case TYPE.time:\n addArgument(signature, element.value, \"date\", label);\n break;\n case TYPE.select:\n addArgument(signature, element.value, \"select\", label);\n break;\n case TYPE.tag:\n addArgument(signature, element.value, \"rich\", label);\n collectArguments(element.children, signature, label);\n break;\n }\n\n if (element.type === TYPE.plural || element.type === TYPE.select) {\n for (const option of Object.values(element.options)) {\n collectArguments(option.value, signature, label);\n }\n }\n }\n}\n\nfunction addArgument(\n signature: FarmI18nMessageSignature,\n name: string,\n kind: FarmI18nArgumentKind,\n label: string,\n): void {\n const existing = signature[name];\n if (existing && existing !== kind) {\n throw new Error(`Farm i18n ${label} uses variable \"${name}\" as both ${existing} and ${kind}.`);\n }\n signature[name] = kind;\n}\n\nfunction sameSignature(\n expected: FarmI18nMessageSignature,\n actual: FarmI18nMessageSignature,\n): boolean {\n const expectedEntries = Object.entries(expected).sort(([a], [b]) => a.localeCompare(b));\n const actualEntries = Object.entries(actual).sort(([a], [b]) => a.localeCompare(b));\n return JSON.stringify(expectedEntries) === JSON.stringify(actualEntries);\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import { localizeFarmPathname, resolveFarmLocalePath } from \"./routing\";\nimport type { FarmI18nLocaleSource, ResolvedFarmI18nConfig } from \"./types\";\n\nexport interface FarmLocaleResolution {\n locale: string;\n source: FarmI18nLocaleSource;\n pathname: string;\n redirect?: string;\n persist: boolean;\n}\n\nexport function getFarmLocaleVaryHeaders(\n config: ResolvedFarmI18nConfig,\n resolution: FarmLocaleResolution,\n): string[] {\n if (!config.enabled || resolution.source === \"url\") return [];\n\n const headers: string[] = [];\n if (config.detection.includes(\"cookie\")) headers.push(\"Cookie\");\n if (config.detection.includes(\"accept-language\")) headers.push(\"Accept-Language\");\n return headers;\n}\n\nexport function resolveFarmLocaleRequest(\n request: Request,\n config: ResolvedFarmI18nConfig,\n options: { redirect?: boolean } = {},\n): FarmLocaleResolution {\n const url = new URL(request.url);\n if (!config.enabled) {\n return {\n locale: config.defaultLocale,\n source: \"default\",\n pathname: url.pathname,\n persist: false,\n };\n }\n\n const pathMatch = resolveFarmLocalePath(url.pathname, config);\n if (pathMatch.explicit && pathMatch.locale) {\n const canonicalPath = localizeFarmPathname(pathMatch.pathname, pathMatch.locale, config);\n const redirect =\n options.redirect !== false && canonicalPath !== url.pathname\n ? `${canonicalPath}${url.search}${url.hash}`\n : undefined;\n return {\n locale: pathMatch.locale,\n source: \"url\",\n pathname: pathMatch.pathname,\n redirect,\n // Locale-prefixed pages are canonical and can be cached publicly. Locale\n // switchers persist the same choice before navigating in the browser.\n persist: false,\n };\n }\n\n const detected = detectLocale(request, config);\n const shouldRedirect =\n options.redirect !== false &&\n !isInternalOrApiPath(url.pathname) &&\n config.routing !== \"none\" &&\n (config.routing === \"prefix-always\" || detected.locale !== config.defaultLocale);\n\n return {\n locale: detected.locale,\n source: detected.source,\n pathname: pathMatch.pathname,\n redirect: shouldRedirect\n ? `${localizeFarmPathname(pathMatch.pathname, detected.locale, config)}${url.search}${url.hash}`\n : undefined,\n persist: detected.source !== \"default\",\n };\n}\n\nexport function createFarmLocaleCookie(\n locale: string,\n config: Pick<ResolvedFarmI18nConfig, \"cookie\">,\n): string {\n const cookie = config.cookie;\n let value = `${encodeURIComponent(cookie.name)}=${encodeURIComponent(locale)}`;\n value += `; Max-Age=${cookie.maxAge}`;\n value += `; Path=${cookie.path}`;\n value += `; SameSite=${capitalize(cookie.sameSite)}`;\n if (cookie.secure) value += \"; Secure\";\n return value;\n}\n\nexport function matchFarmLocale(\n requested: string | null | undefined,\n locales: readonly string[],\n): string | undefined {\n if (!requested) return undefined;\n let canonical: string;\n try {\n canonical = Intl.getCanonicalLocales(requested)[0]!;\n } catch {\n return undefined;\n }\n\n const exact = locales.find((locale) => locale.toLowerCase() === canonical.toLowerCase());\n if (exact) return exact;\n\n const language = canonical.split(\"-\")[0]?.toLowerCase();\n return locales.find((locale) => locale.split(\"-\")[0]?.toLowerCase() === language);\n}\n\nfunction detectLocale(\n request: Request,\n config: ResolvedFarmI18nConfig,\n): { locale: string; source: FarmI18nLocaleSource } {\n for (const signal of config.detection) {\n if (signal === \"url\") continue;\n\n if (signal === \"cookie\") {\n const locale = matchFarmLocale(\n readCookie(request.headers.get(\"cookie\"), config.cookie.name),\n config.locales,\n );\n if (locale) return { locale, source: \"cookie\" };\n }\n\n if (signal === \"accept-language\") {\n const locale = resolveAcceptLanguage(request.headers.get(\"accept-language\"), config.locales);\n if (locale) return { locale, source: \"accept-language\" };\n }\n }\n\n return { locale: config.defaultLocale, source: \"default\" };\n}\n\nfunction resolveAcceptLanguage(\n header: string | null,\n locales: readonly string[],\n): string | undefined {\n if (!header) return undefined;\n const candidates = header\n .split(\",\")\n .map((entry, index) => {\n const [locale = \"\", ...parameters] = entry.trim().split(\";\");\n const qualityValue = parameters\n .map((parameter) => parameter.trim())\n .find((parameter) => parameter.startsWith(\"q=\"));\n const quality = qualityValue ? Number(qualityValue.slice(2)) : 1;\n return { locale, quality: Number.isFinite(quality) ? quality : 0, index };\n })\n .filter((candidate) => candidate.locale && candidate.locale !== \"*\" && candidate.quality > 0)\n .sort((a, b) => b.quality - a.quality || a.index - b.index);\n\n for (const candidate of candidates) {\n const locale = matchFarmLocale(candidate.locale, locales);\n if (locale) return locale;\n }\n return undefined;\n}\n\nfunction readCookie(header: string | null, name: string): string | undefined {\n if (!header) return undefined;\n for (const part of header.split(\";\")) {\n const separator = part.indexOf(\"=\");\n if (separator < 0) continue;\n let key: string;\n try {\n key = decodeURIComponent(part.slice(0, separator).trim());\n } catch {\n continue;\n }\n if (key !== name) continue;\n try {\n return decodeURIComponent(part.slice(separator + 1).trim());\n } catch {\n return part.slice(separator + 1).trim();\n }\n }\n return undefined;\n}\n\nfunction isInternalOrApiPath(pathname: string): boolean {\n return (\n pathname === \"/api\" ||\n pathname.startsWith(\"/api/\") ||\n pathname.startsWith(\"/__farm/\") ||\n pathname.startsWith(\"/_farm/\")\n );\n}\n\nfunction capitalize(value: string): string {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\n","// Tailwind v4 syntax (used with @tailwindcss/vite – no PostCSS or tailwind.config)\nexport const defaultGlobalCSS = `@import \"tailwindcss\";\n`;\n","import type { FarmClientPlugin } from \"./client/plugin\";\nimport type { FarmPlugin, FarmPluginClientConfig } from \"./plugin\";\n\nexport interface ResolvedFarmClientPlugin {\n name: string;\n version?: string;\n enforce?: \"pre\" | \"post\";\n definition: FarmClientPlugin;\n publicData?: unknown;\n}\n\nexport interface FarmClientPluginEntryCode {\n imports: string;\n registrations: string;\n plugins: ResolvedFarmClientPlugin[];\n}\n\nconst CLIENT_KEYS = [\n \"public\",\n \"setup\",\n \"hydration\",\n \"navigation\",\n \"error\",\n \"performance\",\n \"close\",\n] as const;\nconst HYDRATION_KEYS = [\"before\", \"after\"] as const;\nconst NAVIGATION_KEYS = [\"before\", \"loaded\", \"resolved\", \"rendered\", \"error\"] as const;\n\nexport function resolveFarmClientPlugins(\n plugins: readonly FarmPlugin[] | undefined,\n _root?: string,\n): ResolvedFarmClientPlugin[] {\n if (!plugins?.length) return [];\n\n return plugins.flatMap((plugin) => {\n if (!plugin.client) return [];\n assertClientLifecycle(plugin.client, plugin.name);\n assertPublicData(plugin.client.public, plugin.name);\n\n return [\n {\n name: plugin.name,\n version: plugin.version,\n enforce: plugin.enforce,\n definition: plugin.client,\n publicData: plugin.client.public,\n },\n ];\n });\n}\n\nexport function generateFarmClientPluginEntryCode(\n plugins: readonly FarmPlugin[] | undefined,\n root?: string,\n): FarmClientPluginEntryCode {\n const resolved = resolveFarmClientPlugins(plugins, root);\n const registrations = `[\n${resolved\n .map(\n (plugin) => ` {\n name: ${JSON.stringify(plugin.name)},\n version: ${serializeOptionalString(plugin.version)},\n enforce: ${serializeOptionalString(plugin.enforce)},\n definition: ${serializeClientLifecycle(plugin.definition, plugin.name)},\n public: ${serializePublicData(plugin.publicData)},\n }`,\n )\n .join(\",\\n\")}\n]`;\n\n return { imports: \"\", registrations, plugins: resolved };\n}\n\nfunction assertClientLifecycle(client: FarmPluginClientConfig, pluginName: string): void {\n assertLifecycleObject(client, pluginName, \"client\", CLIENT_KEYS);\n assertHook(client.setup, pluginName, \"client.setup\");\n assertHook(client.error, pluginName, \"client.error\");\n assertHook(client.performance, pluginName, \"client.performance\");\n assertHook(client.close, pluginName, \"client.close\");\n\n if (client.hydration !== undefined) {\n assertLifecycleObject(client.hydration, pluginName, \"client.hydration\", HYDRATION_KEYS);\n assertHook(client.hydration.before, pluginName, \"client.hydration.before\");\n assertHook(client.hydration.after, pluginName, \"client.hydration.after\");\n }\n\n if (client.navigation !== undefined) {\n assertLifecycleObject(client.navigation, pluginName, \"client.navigation\", NAVIGATION_KEYS);\n for (const key of NAVIGATION_KEYS) {\n assertHook(client.navigation[key], pluginName, `client.navigation.${key}`);\n }\n }\n}\n\nfunction assertLifecycleObject(\n value: unknown,\n pluginName: string,\n location: string,\n allowedKeys: readonly string[],\n): asserts value is Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be an object`);\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be a plain object`);\n }\n\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key === \"symbol\") {\n throw new TypeError(`Client plugin \"${pluginName}\" ${location} cannot contain symbol keys`);\n }\n if (!allowedKeys.includes(key)) {\n throw new TypeError(`Client plugin \"${pluginName}\" has an unknown ${location}.${key} option`);\n }\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor?.enumerable) {\n throw new TypeError(`Client plugin \"${pluginName}\" ${location}.${key} must be enumerable`);\n }\n if (!(\"value\" in descriptor)) {\n throw new TypeError(`Client plugin \"${pluginName}\" ${location}.${key} cannot be an accessor`);\n }\n }\n}\n\nfunction assertHook(value: unknown, pluginName: string, location: string): void {\n if (value === undefined) return;\n if (typeof value !== \"function\") {\n throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be a function`);\n }\n functionSource(value, pluginName, location);\n}\n\nfunction serializeClientLifecycle(definition: FarmClientPlugin, pluginName: string): string {\n const fields: string[] = [];\n pushHook(fields, \"setup\", definition.setup, pluginName, \"client.setup\", 2);\n pushHookGroup(fields, \"hydration\", definition.hydration, HYDRATION_KEYS, pluginName, 2);\n pushHookGroup(fields, \"navigation\", definition.navigation, NAVIGATION_KEYS, pluginName, 2);\n pushHook(fields, \"error\", definition.error, pluginName, \"client.error\", 2);\n pushHook(fields, \"performance\", definition.performance, pluginName, \"client.performance\", 2);\n pushHook(fields, \"close\", definition.close, pluginName, \"client.close\", 2);\n\n return fields.length ? `{\\n${fields.join(\",\\n\")}\\n }` : \"{}\";\n}\n\nfunction pushHookGroup(\n fields: string[],\n groupName: \"hydration\" | \"navigation\",\n group: Record<string, unknown> | undefined,\n keys: readonly string[],\n pluginName: string,\n indent: number,\n): void {\n if (!group) return;\n const hooks: string[] = [];\n for (const key of keys) {\n pushHook(hooks, key, group[key], pluginName, `client.${groupName}.${key}`, indent + 2);\n }\n fields.push(\n `${\" \".repeat(indent)}${JSON.stringify(groupName)}: {\\n${hooks.join(\",\\n\")}\\n${\" \".repeat(indent)}}`,\n );\n}\n\nfunction pushHook(\n fields: string[],\n key: string,\n hook: unknown,\n pluginName: string,\n location: string,\n indent: number,\n): void {\n if (hook === undefined) return;\n fields.push(\n `${\" \".repeat(indent)}${JSON.stringify(key)}: ${functionSource(hook, pluginName, location)}`,\n );\n}\n\nfunction functionSource(value: unknown, pluginName: string, location: string): string {\n if (typeof value !== \"function\") {\n throw new TypeError(`Client plugin \"${pluginName}\" ${location} must be a function`);\n }\n\n const source = Function.prototype.toString.call(value).trim();\n if (!source || source.includes(\"[native code]\")) {\n throw new TypeError(\n `Client plugin \"${pluginName}\" ${location} must be authored inline and cannot be native or bound`,\n );\n }\n\n if (/^(?:async\\s+)?function(?:\\s*\\*)?(?:\\s+|\\()/.test(source)) {\n return `(${source})`;\n }\n\n const method = source.match(/^(async\\s+)?(\\*\\s*)?[$A-Z_a-z][$\\w]*\\s*(\\([\\s\\S]*)$/);\n if (method) {\n const asyncPrefix = method[1] ?? \"\";\n const generator = method[2] ? \"*\" : \"\";\n return `(${asyncPrefix}function${generator}${method[3]})`;\n }\n\n if (source.includes(\"=>\")) return `(${source})`;\n\n throw new TypeError(\n `Client plugin \"${pluginName}\" ${location} must use a function, method, or arrow function`,\n );\n}\n\nfunction assertPublicData(value: unknown, pluginName: string): void {\n if (value === undefined) return;\n const seen = new WeakSet<object>();\n\n const visit = (current: unknown, pathSegments: string[]): void => {\n if (current === null || typeof current === \"string\" || typeof current === \"boolean\") {\n return;\n }\n if (typeof current === \"number\") {\n if (Number.isFinite(current)) return;\n throwPublicDataError(pluginName, pathSegments, \"must be a finite number\");\n }\n if (typeof current !== \"object\") {\n throwPublicDataError(pluginName, pathSegments, `cannot contain ${typeof current} values`);\n }\n if (seen.has(current)) {\n throwPublicDataError(pluginName, pathSegments, \"cannot contain circular references\");\n }\n seen.add(current);\n\n if (Array.isArray(current)) {\n for (let index = 0; index < current.length; index += 1) {\n if (!Object.prototype.hasOwnProperty.call(current, index)) {\n throwPublicDataError(\n pluginName,\n [...pathSegments, String(index)],\n \"cannot contain sparse array slots\",\n );\n }\n visit(current[index], [...pathSegments, String(index)]);\n }\n for (const key of Reflect.ownKeys(current)) {\n if (key === \"length\" || (typeof key === \"string\" && isArrayIndex(key))) continue;\n throwPublicDataError(\n pluginName,\n pathSegments,\n typeof key === \"symbol\"\n ? \"cannot contain symbol keys\"\n : `cannot contain non-index array property ${key}`,\n );\n }\n seen.delete(current);\n return;\n }\n\n const prototype = Object.getPrototypeOf(current);\n if (prototype !== Object.prototype && prototype !== null) {\n throwPublicDataError(pluginName, pathSegments, \"must contain only plain objects and arrays\");\n }\n for (const key of Reflect.ownKeys(current)) {\n if (typeof key === \"symbol\") {\n throwPublicDataError(pluginName, pathSegments, \"cannot contain symbol keys\");\n }\n const descriptor = Object.getOwnPropertyDescriptor(current, key);\n if (!descriptor?.enumerable) {\n throwPublicDataError(\n pluginName,\n [...pathSegments, key],\n \"cannot contain non-enumerable properties\",\n );\n }\n if (!(\"value\" in descriptor)) {\n throwPublicDataError(\n pluginName,\n [...pathSegments, key],\n \"cannot contain accessor properties\",\n );\n }\n visit(descriptor.value, [...pathSegments, key]);\n }\n seen.delete(current);\n };\n\n visit(value, []);\n}\n\nfunction throwPublicDataError(pluginName: string, pathSegments: string[], message: string): never {\n const location = pathSegments.length ? ` at client.public.${pathSegments.join(\".\")}` : \"\";\n throw new TypeError(`Client plugin \"${pluginName}\"${location} ${message}`);\n}\n\nfunction serializePublicData(value: unknown): string {\n if (value === undefined) return \"undefined\";\n return `JSON.parse(${JSON.stringify(JSON.stringify(value))})`;\n}\n\nfunction serializeOptionalString(value: string | undefined): string {\n return value === undefined ? \"undefined\" : JSON.stringify(value);\n}\n\nfunction isArrayIndex(key: string): boolean {\n const value = Number(key);\n return Number.isInteger(value) && value >= 0 && value < 4_294_967_295 && String(value) === key;\n}\n","import type { ViteDevServer, ModuleNode } from \"vite\";\nimport { logger } from \"./utils\";\n\nexport class HMRManager {\n private server: ViteDevServer;\n\n constructor(server: ViteDevServer) {\n this.server = server;\n }\n\n /**\n * Send HMR update to client\n */\n async send(payload: any) {\n this.server.ws.send(payload);\n }\n\n /**\n * Trigger full page reload\n */\n async reloadPage() {\n this.server.ws.send({\n type: \"full-reload\",\n path: \"*\",\n });\n }\n\n /**\n * Handle file change and trigger HMR\n */\n async handleFileChange(file: string) {\n const module = await this.server.moduleGraph.getModuleByUrl(file);\n\n if (!module) {\n return;\n }\n\n // Invalidate module\n this.server.moduleGraph.invalidateModule(module);\n\n // Get affected modules\n const affectedModules = this.getAffectedModules(module);\n\n if (affectedModules.size === 0) {\n return;\n }\n\n if (file.includes(\"/app/\") && (file.endsWith(\"page.tsx\") || file.endsWith(\"page.ts\"))) {\n await this.reloadPage();\n return;\n }\n\n if (file.includes(\"/app/\") && (file.endsWith(\"layout.tsx\") || file.endsWith(\"layout.ts\"))) {\n await this.reloadPage();\n return;\n }\n // Send update for other files\n this.send({\n type: \"update\",\n updates: Array.from(affectedModules).map((m) => ({\n type: m.type === \"css\" ? \"css-update\" : \"js-update\",\n path: m.url,\n acceptedPath: m.url,\n timestamp: Date.now(),\n })),\n });\n }\n\n /**\n * Get all affected modules in the dependency graph\n */\n private getAffectedModules(module: ModuleNode): Set<ModuleNode> {\n const affected = new Set<ModuleNode>();\n const seen = new Set<ModuleNode>();\n\n const traverse = (mod: ModuleNode) => {\n if (seen.has(mod)) return;\n seen.add(mod);\n affected.add(mod);\n\n // Traverse importers\n for (const importer of mod.importers) {\n if (!importer.isSelfAccepting) {\n traverse(importer);\n }\n }\n };\n\n traverse(module);\n return affected;\n }\n\n /**\n * Handle custom HMR events from client\n */\n onClientMessage(event: string, callback: (data: any) => void) {\n // Vite handles this via ws.on\n }\n}\n\n/**\n * Create HMR client code for injection\n */\nexport function createHMRClientCode(): string {\n return `\n// Farm.js HMR Client\nif (import.meta.hot) {\n // Accept HMR updates for this module\n import.meta.hot.accept((newModule) => {\n if (newModule) {\n // Module updated, trigger re-render\n window.location.reload();\n }\n });\n\n // Listen for custom Farm.js events\n import.meta.hot.on('farm:route-update', (data) => {\n console.log('Route updated:', data.path);\n window.location.reload();\n });\n\n // Handle CSS updates\n import.meta.hot.on('vite:beforeUpdate', () => {\n console.log('[Farm.js] HMR update incoming...');\n });\n\n import.meta.hot.on('vite:afterUpdate', () => {\n console.log('[Farm.js] HMR update applied ✓');\n });\n\n // Handle errors\n import.meta.hot.on('vite:error', (err) => {\n console.error('[Farm.js] HMR error:', err);\n });\n}\n`;\n}\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport { logger } from \"../utils\";\nimport {\n createProgrammaticRouteModuleId,\n getProgrammaticRouteManifest,\n type ProgrammaticApiRoute,\n} from \"../routes\";\nimport { findProgrammaticRouteFilesInDir } from \"../routes.server\";\nimport {\n getFarmRouteRuntimeConfig,\n normalizeFarmRouteRuntimeConfig,\n type FarmRouteRuntimeConfig,\n} from \"../route-runtime\";\nimport { _runWithFarmI18nRequest, type FarmI18nRuntime } from \"../i18n/server\";\nimport { invokeAPIRouteEndpoint, matchAPIRoute, type APIRouteMatch } from \"./runtime\";\n\nexport interface APIRoute extends FarmRouteRuntimeConfig {\n path: string;\n filePath: string;\n methods: string[];\n endpoints: Record<string, any>;\n}\n\nexport interface APIRouteManagerOptions {\n throwOnLoadError?: boolean;\n i18n?: FarmI18nRuntime;\n}\n\nexport const API_ROUTE_METHODS = [\n \"GET\",\n \"HEAD\",\n \"POST\",\n \"PUT\",\n \"DELETE\",\n \"PATCH\",\n \"OPTIONS\",\n] as const;\n\nexport class APIRouteManager {\n private routes: Map<string, APIRoute> = new Map();\n private viteServer?: ViteDevServer;\n private appDirs: string[];\n private throwOnLoadError: boolean;\n private i18n?: FarmI18nRuntime;\n\n constructor(\n appDir: string | readonly string[],\n viteServer?: ViteDevServer,\n options: APIRouteManagerOptions = {},\n ) {\n this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n this.viteServer = viteServer;\n this.throwOnLoadError = options.throwOnLoadError === true;\n this.i18n = options.i18n;\n }\n\n /**\n * Discover route.ts files in /app/api and explicit endpoints in root routes.ts\n */\n async discoverRoutes(): Promise<void> {\n this.routes.clear();\n\n for (const appDir of this.appDirs) {\n const apiDir = path.join(appDir, \"api\");\n let routeFiles: string[] = [];\n\n if (fs.existsSync(apiDir)) {\n routeFiles = this.findRouteFiles(apiDir);\n }\n\n for (const filePath of routeFiles) {\n await this.loadRoute(filePath, appDir);\n }\n\n await this.loadRootRoutes(appDir);\n await this.loadProgrammaticApiRoutes(appDir);\n }\n\n if (process.env.FARM_VERBOSE) {\n logger.success(`Discovered ${this.routes.size} API routes`);\n for (const [routePath, route] of this.routes) {\n logger.info(` ${route.methods.join(\", \")} ${routePath}`);\n }\n }\n }\n\n /**\n * Recursively find all route.ts files\n */\n private findRouteFiles(dir: string): string[] {\n const files: string[] = [];\n\n if (!fs.existsSync(dir)) {\n return files;\n }\n\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n\n if (entry.isDirectory()) {\n files.push(...this.findRouteFiles(fullPath));\n } else if (\n entry.name === \"route.ts\" ||\n entry.name === \"route.tsx\" ||\n entry.name === \"route.js\"\n ) {\n files.push(fullPath);\n }\n }\n\n return files;\n }\n\n /**\n * Load a route.ts file and extract HTTP method exports\n */\n private async loadRoute(filePath: string, appDir: string): Promise<void> {\n try {\n // Convert file path to API route path\n // /app/api/auth/login/route.ts -> /api/auth/login\n const apiDir = path.join(appDir, \"api\");\n const relativePath = path.relative(apiDir, path.dirname(filePath));\n const routePath = \"/api/\" + (relativePath === \".\" ? \"\" : relativePath.replace(/\\\\/g, \"/\"));\n\n const routeModule = await this.loadModule(filePath);\n\n const endpoints: Record<string, any> = {};\n const availableMethods: string[] = [];\n\n for (const method of API_ROUTE_METHODS) {\n if (routeModule[method]) {\n endpoints[method] = routeModule[method];\n availableMethods.push(method);\n }\n }\n\n if (availableMethods.length > 0) {\n const runtimeConfig = normalizeFarmRouteRuntimeConfig(\n getFarmRouteRuntimeConfig(routeModule),\n `API route \"${routePath}\"`,\n );\n this.routes.set(routePath, {\n path: routePath,\n filePath,\n methods: availableMethods,\n endpoints,\n ...runtimeConfig,\n });\n }\n } catch (error) {\n this.handleLoadError(`Error loading route ${filePath}`, error);\n }\n }\n\n /**\n * Load explicit-path endpoints from src/routes.ts-style files.\n */\n private async loadRootRoutes(appDir: string): Promise<void> {\n const routesFile = this.findRootRoutesFile(appDir);\n if (!routesFile) {\n return;\n }\n\n try {\n const routesModule = await this.loadModule(routesFile);\n\n for (const exportValue of Object.values(routesModule)) {\n const endpoint = exportValue as any;\n if (!endpoint?.__path) {\n continue;\n }\n\n const method = String(endpoint.__method || \"GET\").toUpperCase();\n this.addEndpoint(endpoint.__path, routesFile, method, endpoint);\n }\n } catch (error) {\n this.handleLoadError(`Error loading root API routes ${routesFile}`, error);\n }\n }\n\n private async loadProgrammaticApiRoutes(appDir: string): Promise<void> {\n const candidateRoots = [path.dirname(appDir), appDir];\n const routeFiles = Array.from(\n new Set(candidateRoots.flatMap((srcRoot) => findProgrammaticRouteFilesInDir(srcRoot))),\n );\n\n for (const routeFile of routeFiles) {\n try {\n const routesModule = await this.loadModule(routeFile);\n const manifest = getProgrammaticRouteManifest(routesModule);\n if (!manifest) continue;\n\n for (const definition of manifest.routes) {\n if (definition.kind !== \"api\") continue;\n this.addProgrammaticApiRoute(routeFile, definition);\n }\n } catch (error) {\n this.handleLoadError(`Error loading programmatic API routes ${routeFile}`, error);\n }\n }\n }\n\n private handleLoadError(message: string, error: unknown): void {\n logger.error(`${message}: ${error}`);\n if (this.throwOnLoadError) {\n throw error;\n }\n }\n\n private findRootRoutesFile(appDir: string): string | null {\n const routeNames = [\"routes.ts\", \"routes.tsx\", \"routes.js\"];\n const candidateDirs = [path.dirname(appDir), appDir];\n const seen = new Set<string>();\n\n for (const dir of candidateDirs) {\n for (const routeName of routeNames) {\n const routesFile = path.join(dir, routeName);\n if (seen.has(routesFile)) {\n continue;\n }\n seen.add(routesFile);\n\n if (fs.existsSync(routesFile)) {\n return routesFile;\n }\n }\n }\n\n return null;\n }\n\n private async loadModule(filePath: string): Promise<Record<string, unknown>> {\n if (this.viteServer) {\n return await this.viteServer.ssrLoadModule(filePath);\n }\n\n const fileUrl = `file://${filePath}`;\n return await import(/* @vite-ignore */ fileUrl);\n }\n\n private addEndpoint(\n routePath: string,\n filePath: string,\n method: string,\n endpoint: any,\n runtimeConfig: FarmRouteRuntimeConfig = {},\n ): void {\n const normalizedMethod = method.toUpperCase();\n const existingRoute = this.routes.get(routePath);\n\n if (existingRoute) {\n if (!existingRoute.methods.includes(normalizedMethod)) {\n existingRoute.methods.push(normalizedMethod);\n }\n existingRoute.endpoints[normalizedMethod] = endpoint;\n Object.assign(existingRoute, runtimeConfig);\n return;\n }\n\n this.routes.set(routePath, {\n path: routePath,\n filePath,\n methods: [normalizedMethod],\n endpoints: { [normalizedMethod]: endpoint },\n ...runtimeConfig,\n });\n }\n\n private addProgrammaticApiRoute(filePath: string, route: ProgrammaticApiRoute): void {\n const modulePath = createProgrammaticRouteModuleId(filePath, \"api\", route.path);\n const runtimeConfig = normalizeFarmRouteRuntimeConfig(route, `API route \"${route.path}\"`);\n for (const [method, endpoint] of Object.entries(route.methods)) {\n if (endpoint) {\n this.addEndpoint(route.path, modulePath, method, endpoint, runtimeConfig);\n }\n }\n }\n\n /**\n * Get the handler that directly invokes endpoint handlers\n */\n getHandler(): ((req: Request) => Promise<Response>) | null {\n if (this.routes.size === 0) {\n return null;\n }\n\n return async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const pathname = url.pathname;\n const method = request.method.toUpperCase();\n\n // Find matching route\n const match = matchAPIRoute(this.routes, pathname);\n if (!match) {\n return new Response(JSON.stringify({ error: \"Not Found\" }), {\n status: 404,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n\n // Check if method is supported\n const { route, params } = match;\n const endpoint = route.endpoints[method];\n if (!endpoint) {\n return new Response(JSON.stringify({ error: \"Method Not Allowed\" }), {\n status: 405,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n\n const invoke = async () => {\n try {\n return await invokeAPIRouteEndpoint(endpoint, request, params);\n } catch (error: any) {\n console.error(`[API Error] ${pathname}:`, error);\n return new Response(JSON.stringify({ error: \"Internal Server Error\" }), {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n };\n\n return this.i18n?.config.enabled\n ? _runWithFarmI18nRequest(this.i18n, request, invoke, {\n redirect: false,\n })\n : invoke();\n };\n }\n\n /**\n * Check if a path is an API route\n */\n isAPIRoute(pathname: string): boolean {\n return Boolean(this.matchRoute(pathname));\n }\n\n matchRoute(pathname: string): APIRouteMatch<APIRoute> | null {\n return matchAPIRoute(this.routes, pathname);\n }\n\n /**\n * Get all routes for client type generation\n */\n getRoutes(): Map<string, APIRoute> {\n return this.routes;\n }\n}\n\nexport {\n invokeAPIRouteEndpoint,\n isWebResponse,\n matchAPIRoute,\n normalizeRouteResponse,\n} from \"./runtime\";\nexport type { APIRouteMatch, APIRouteParams, APIRouteParamValue } from \"./runtime\";\n","import { _runWithCurrentRequest } from \"../server/request\";\n\nexport type APIRouteParamValue = string | string[];\nexport type APIRouteParams = Record<string, APIRouteParamValue>;\n\nexport interface APIRouteMatch<T extends { path: string }> {\n route: T;\n params: APIRouteParams;\n}\n\nexport function matchAPIRoute<T extends { path: string }>(\n routes: Map<string, T>,\n pathname: string,\n): APIRouteMatch<T> | null {\n const exactRoute = routes.get(pathname);\n if (exactRoute) {\n return { route: exactRoute, params: {} };\n }\n\n const normalizedPathname = normalizePathname(pathname);\n if (normalizedPathname !== pathname) {\n const normalizedRoute = routes.get(normalizedPathname);\n if (normalizedRoute) {\n return { route: normalizedRoute, params: {} };\n }\n }\n\n for (const route of routes.values()) {\n const params = matchRoutePath(route.path, pathname);\n if (params) {\n return { route, params };\n }\n }\n\n return null;\n}\n\nexport async function invokeAPIRouteEndpoint(\n endpoint: any,\n request: Request,\n params: APIRouteParams = {},\n): Promise<Response> {\n return _runWithCurrentRequest(request, () =>\n invokeAPIRouteEndpointInContext(endpoint, request, params),\n );\n}\n\nasync function invokeAPIRouteEndpointInContext(\n endpoint: any,\n request: Request,\n params: APIRouteParams,\n): Promise<Response> {\n const farmHandler = endpoint.__handler || (isFarmContextHandler(endpoint) ? endpoint : null);\n\n if (!farmHandler) {\n const result = await endpoint(request, {\n params: Promise.resolve(params),\n });\n return normalizeRouteResponse(result);\n }\n\n const url = new URL(request.url);\n const query: Record<string, string> = {};\n url.searchParams.forEach((value, key) => {\n query[key] = value;\n });\n\n let body: any = undefined;\n if (request.method.toUpperCase() !== \"GET\" && request.method.toUpperCase() !== \"HEAD\") {\n body = await readJSONBody(request);\n }\n\n const headers = Object.fromEntries(request.headers.entries());\n const types = endpoint.__types || {};\n\n const queryValidation = validateInput(types.query, query, \"Invalid query parameters\");\n if (queryValidation instanceof Response) {\n return queryValidation;\n }\n\n const bodyValidation = validateInput(types.body, body, \"Invalid request body\");\n if (bodyValidation instanceof Response) {\n return bodyValidation;\n }\n\n const headersValidation = validateInput(types.headers, headers, \"Invalid request headers\");\n if (headersValidation instanceof Response) {\n return headersValidation;\n }\n\n const result = await farmHandler({\n query: queryValidation,\n body: bodyValidation,\n headers: headersValidation,\n request,\n context: {},\n params,\n });\n\n return normalizeRouteResponse(result);\n}\n\nexport function normalizeRouteResponse(result: unknown): Response {\n if (isWebResponse(result)) {\n return result;\n }\n\n if (result === undefined) {\n return new Response(null, { status: 204 });\n }\n\n return new Response(JSON.stringify(result), {\n status: 200,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nexport function isWebResponse(value: unknown): value is Response {\n return (\n value instanceof Response ||\n (typeof value === \"object\" &&\n value !== null &&\n \"headers\" in value &&\n \"status\" in value &&\n typeof (value as Response).arrayBuffer === \"function\")\n );\n}\n\nfunction isFarmContextHandler(endpoint: unknown): boolean {\n if (typeof endpoint !== \"function\") {\n return false;\n }\n\n const source = Function.prototype.toString.call(endpoint).trim();\n const arrowMatch = source.match(/^(?:async\\s*)?(?:\\(([^)]*)\\)|([A-Za-z_$][\\w$]*))\\s*=>/);\n const functionMatch = source.match(/^(?:async\\s*)?function[^(]*\\(([^)]*)\\)/);\n const firstParameter = (arrowMatch?.[1] || arrowMatch?.[2] || functionMatch?.[1] || \"\")\n .split(\",\")[0]\n .trim();\n\n return firstParameter === \"ctx\" || firstParameter === \"context\" || firstParameter.startsWith(\"{\");\n}\n\nasync function readJSONBody(request: Request): Promise<unknown> {\n try {\n const text = await request.clone().text();\n if (text) {\n return JSON.parse(text);\n }\n } catch {\n // Body might not be JSON.\n }\n\n return undefined;\n}\n\nfunction validateInput(schema: any, value: unknown, error: string): unknown | Response {\n if (!schema || typeof schema.parse !== \"function\") {\n return value;\n }\n\n try {\n return schema.parse(value);\n } catch (validationError: any) {\n return new Response(\n JSON.stringify({\n error,\n details: validationError.errors || validationError.issues || validationError.message,\n }),\n {\n status: 400,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n}\n\nfunction matchRoutePath(routePath: string, pathname: string): APIRouteParams | null {\n const routeSegments = getPathSegments(routePath);\n const pathnameSegments = getPathSegments(pathname);\n const params: APIRouteParams = {};\n let pathIndex = 0;\n\n for (const routeSegment of routeSegments) {\n const dynamicSegment = parseDynamicSegment(routeSegment);\n\n if (dynamicSegment?.catchAll) {\n const remainingSegments = pathnameSegments.slice(pathIndex).map(decodePathSegment);\n if (remainingSegments.length === 0 && !dynamicSegment.optional) {\n return null;\n }\n if (remainingSegments.length > 0) {\n params[dynamicSegment.name] = remainingSegments;\n }\n pathIndex = pathnameSegments.length;\n continue;\n }\n\n const pathnameSegment = pathnameSegments[pathIndex];\n if (pathnameSegment === undefined) {\n return null;\n }\n\n if (dynamicSegment) {\n params[dynamicSegment.name] = decodePathSegment(pathnameSegment);\n pathIndex++;\n continue;\n }\n\n if (routeSegment !== pathnameSegment) {\n return null;\n }\n\n pathIndex++;\n }\n\n return pathIndex === pathnameSegments.length ? params : null;\n}\n\nfunction getPathSegments(pathname: string): string[] {\n return normalizePathname(pathname)\n .split(\"/\")\n .filter((segment) => segment.length > 0);\n}\n\nfunction normalizePathname(pathname: string): string {\n if (pathname.length > 1 && pathname.endsWith(\"/\")) {\n return pathname.replace(/\\/+$/, \"\");\n }\n\n return pathname;\n}\n\nfunction parseDynamicSegment(\n segment: string,\n): { name: string; catchAll: boolean; optional: boolean } | null {\n const optionalCatchAll = segment.match(/^\\[\\[\\.\\.\\.(.+)\\]\\]$/);\n if (optionalCatchAll?.[1]) {\n return { name: optionalCatchAll[1], catchAll: true, optional: true };\n }\n\n const catchAll = segment.match(/^\\[\\.\\.\\.(.+)\\]$/);\n if (catchAll?.[1]) {\n return { name: catchAll[1], catchAll: true, optional: false };\n }\n\n const dynamic = segment.match(/^\\[(.+)\\]$/);\n if (dynamic?.[1]) {\n return { name: dynamic[1], catchAll: false, optional: false };\n }\n\n return null;\n}\n\nfunction decodePathSegment(segment: string): string {\n try {\n return decodeURIComponent(segment);\n } catch {\n return segment;\n }\n}\n","/**\n * Middleware Manager\n *\n * Discovers and executes middleware files in the file system\n */\n\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { ViteDevServer } from \"vite\";\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport type {\n FarmMiddlewareConfig,\n MiddlewareFunction,\n MiddlewareMatcher,\n MiddlewareConfig,\n MiddlewareContext,\n MiddlewareResult,\n} from \"./types\";\nimport { createContext } from \"./context\";\nimport { normalizeMiddlewareModule } from \"./module\";\nimport { logger } from \"../utils\";\nimport { sendWebResponse } from \"../server/response\";\nimport { emitFarmEvent } from \"../observability\";\nimport { stripFarmLocaleFromPathname } from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\n\nexport interface DiscoveredMiddleware {\n path: string;\n filePath: string;\n handlers: MiddlewareFunction[];\n config?: MiddlewareConfig;\n source?: \"config\" | \"file\";\n}\n\nfunction isMiddlewareResponse(value: unknown): value is Response {\n return value instanceof Response;\n}\n\n/**\n * Middleware Manager - discovers and executes middleware\n */\nexport class MiddlewareManager {\n private middleware: DiscoveredMiddleware[] = [];\n private configMiddleware: DiscoveredMiddleware[] = [];\n private globalConfig?: MiddlewareConfig;\n private viteServer?: ViteDevServer;\n private appDirs: string[];\n private i18n?: ResolvedFarmI18nConfig;\n\n constructor(\n appDir: string | readonly string[],\n viteServer?: ViteDevServer,\n config?: FarmMiddlewareConfig,\n i18n?: ResolvedFarmI18nConfig,\n ) {\n this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir as string];\n this.viteServer = viteServer;\n this.i18n = i18n;\n this.configure(config);\n }\n\n configure(config?: FarmMiddlewareConfig): void {\n this.configMiddleware = [];\n this.globalConfig = undefined;\n\n if (!config) return;\n\n const entries = Array.isArray(config) ? config : [config];\n\n for (const [index, entry] of entries.entries()) {\n const handlers = this.getConfigHandlers(entry);\n const middlewareConfig = this.toMiddlewareConfig(entry);\n\n if (handlers.length === 0) {\n this.globalConfig = middlewareConfig;\n continue;\n }\n\n this.configMiddleware.push({\n path: \"/\",\n filePath: `farm.config.ts#middleware-${index}`,\n handlers,\n config: middlewareConfig,\n source: \"config\",\n });\n }\n }\n\n /**\n * Discover all middleware.ts files\n */\n async discover(): Promise<void> {\n const middlewareByPath = new Map<string, DiscoveredMiddleware>();\n for (const appDir of this.appDirs) {\n const discovered: DiscoveredMiddleware[] = [];\n await this.discoverInDirectory(appDir, \"/\", discovered);\n for (const middleware of discovered) {\n middlewareByPath.set(middleware.path, middleware);\n }\n }\n this.middleware = Array.from(middlewareByPath.values());\n\n // Sort by path depth (root first, then nested)\n this.middleware.sort((a, b) => {\n const depthA = a.path.split(\"/\").length;\n const depthB = b.path.split(\"/\").length;\n return depthA - depthB;\n });\n\n if (process.env.FARM_VERBOSE && this.middleware.length > 0) {\n logger.success(`Discovered ${this.middleware.length} middleware files`);\n for (const mw of this.middleware) {\n logger.info(` ${mw.path} (${mw.handlers.length} handlers)`);\n }\n }\n }\n\n /**\n * Recursively discover middleware files\n */\n private async discoverInDirectory(\n dir: string,\n routePath: string,\n discovered: DiscoveredMiddleware[],\n ): Promise<void> {\n if (!fs.existsSync(dir)) {\n return;\n }\n\n // Check for middleware.ts in current directory\n const middlewareFile = this.findMiddlewareFile(dir);\n if (middlewareFile) {\n const middleware = await this.loadMiddleware(middlewareFile, routePath);\n if (middleware) {\n discovered.push(middleware);\n }\n }\n\n // Recursively check subdirectories\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith(\".\") && !entry.name.startsWith(\"_\")) {\n const subPath = path.join(dir, entry.name);\n const subRoutePath = path.posix.join(routePath, entry.name);\n await this.discoverInDirectory(subPath, subRoutePath, discovered);\n }\n }\n }\n\n /**\n * Find middleware file in directory\n */\n private findMiddlewareFile(dir: string): string | null {\n const extensions = [\".ts\", \".tsx\", \".js\", \".jsx\"];\n for (const ext of extensions) {\n const filePath = path.join(dir, `middleware${ext}`);\n if (fs.existsSync(filePath)) {\n return filePath;\n }\n }\n return null;\n }\n\n /**\n * Load a middleware file\n */\n private async loadMiddleware(\n filePath: string,\n routePath: string,\n ): Promise<DiscoveredMiddleware | null> {\n try {\n // Load the module\n let module: any;\n if (this.viteServer) {\n module = await this.viteServer.ssrLoadModule(filePath);\n } else {\n const fileUrl = `file://${filePath}`;\n module = await import(/* @vite-ignore */ fileUrl);\n }\n\n const normalized = normalizeMiddlewareModule(module, routePath);\n if (!normalized) {\n logger.warn(\n `Middleware file ${filePath} must export a default handler or a named middleware handler`,\n );\n return null;\n }\n\n return {\n path: routePath,\n filePath,\n handlers: normalized.handlers,\n config: normalized.config,\n source: \"file\",\n };\n } catch (error) {\n logger.error(`Failed to load middleware ${filePath}: ${error}`);\n return null;\n }\n }\n\n /**\n * Execute middleware for a request\n */\n async execute(req: IncomingMessage, res: ServerResponse): Promise<boolean> {\n const url = new URL(req.url || \"/\", `http://${req.headers.host || \"localhost\"}`);\n const pathname = url.pathname;\n const routePathname = this.i18n?.enabled\n ? stripFarmLocaleFromPathname(pathname, this.i18n)\n : pathname;\n const method = req.method || \"GET\";\n const startTime = Date.now();\n\n let parentData: MiddlewareContext[\"parent\"] | undefined;\n let ctx = createContext(req, res, this.viteServer);\n\n if (this.globalConfig) {\n const globalMatch = this.matchesConfig(routePathname, this.globalConfig, ctx);\n if (!globalMatch.matched) {\n return false;\n }\n if (globalMatch.params) {\n ctx.params = { ...ctx.params, ...globalMatch.params };\n }\n }\n\n // Find applicable middleware (config entries first, then cascading files)\n const applicable: Array<{\n mw: DiscoveredMiddleware;\n routeMatch: { matched: boolean; params?: Record<string, string> };\n }> = [\n ...this.configMiddleware.map((mw) => ({ mw, routeMatch: { matched: true } })),\n ...this.middleware\n .map((mw) => ({ mw, routeMatch: this.matchRoutePath(routePathname, mw.path) }))\n .filter((entry) => entry.routeMatch.matched),\n ];\n\n if (applicable.length === 0) {\n return false; // No middleware to run\n }\n try {\n const pc = require(\"picocolors\");\n const middlewarePaths = applicable.map(({ mw }) => mw.path).join(\", \");\n const log = [\n pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n pc.dim(\"[\") + pc.bold(pc.magenta(\"MIDDLEWARE\")) + pc.dim(\"]\"),\n pc.dim(\"[\") + pc.bold(pc.white(method.padEnd(3))) + pc.dim(\"]\"),\n pc.gray(\"Executing middleware: \"),\n pc.gray(pathname),\n pc.dim(` (${(Date.now() - startTime).toFixed(2)}ms)`),\n ].join(\" \");\n console.log(log);\n } catch {\n console.log(\n `[FARM] [MIDDLEWARE] [${method}] Executing ${pathname} (${applicable.length} middleware)`,\n );\n }\n\n // Execute middleware in cascade order\n for (const entry of applicable) {\n // Check matcher configuration\n const { mw, routeMatch } = entry;\n const configMatch = mw.config\n ? this.matchesConfig(routePathname, mw.config, ctx)\n : { matched: true };\n if (!configMatch.matched) {\n continue;\n }\n if (routeMatch.params) {\n ctx.params = { ...ctx.params, ...routeMatch.params };\n }\n if (configMatch.params) {\n ctx.params = { ...ctx.params, ...configMatch.params };\n }\n\n // Create new context with parent data\n if (parentData) {\n ctx = createContext(req, res, this.viteServer, parentData);\n if (routeMatch.params) {\n ctx.params = { ...ctx.params, ...routeMatch.params };\n }\n if (configMatch.params) {\n ctx.params = { ...ctx.params, ...configMatch.params };\n }\n }\n\n const middlewareStartTime = Date.now();\n const middlewareEvent = {\n route: mw.path,\n pathname,\n name: mw.filePath,\n };\n emitFarmEvent({ type: \"middleware.start\", ...middlewareEvent });\n\n try {\n // Execute all handlers in this middleware\n let handlerIndex = 0;\n let returnedResponse: Response | undefined;\n const executeNext = async (): Promise<MiddlewareResult> => {\n if (handlerIndex < mw.handlers.length) {\n const handler = mw.handlers[handlerIndex++];\n const result = await handler(ctx, executeNext);\n if (isMiddlewareResponse(result)) {\n returnedResponse = result;\n return result;\n }\n }\n return returnedResponse;\n };\n\n const result = await executeNext();\n const response = isMiddlewareResponse(result) ? result : returnedResponse;\n if (response) {\n if (!res.headersSent && !res.writableEnded) {\n for (const [key, value] of ctx.headers) {\n try {\n res.setHeader(key, value);\n } catch (error) {}\n }\n }\n emitFarmEvent({\n type: \"middleware.shortCircuit\",\n ...middlewareEvent,\n status: response.status,\n });\n await sendWebResponse(res, response);\n return true;\n }\n\n // Check if response has been sent or handled by middleware helpers.\n if (ctx._handled || res.headersSent || res.writableEnded) {\n emitFarmEvent({\n type: \"middleware.shortCircuit\",\n ...middlewareEvent,\n status: res.statusCode,\n });\n return true;\n }\n\n emitFarmEvent({\n type: \"middleware.complete\",\n ...middlewareEvent,\n durationMs: Date.now() - middlewareStartTime,\n });\n } catch (error) {\n emitFarmEvent({\n type: \"middleware.error\",\n ...middlewareEvent,\n error,\n });\n throw error;\n }\n\n parentData = {\n data: new Map(ctx.data),\n locals: new Map(ctx.locals),\n headers: Object.fromEntries(ctx.headers),\n };\n }\n\n if (!res.headersSent && !res.writableEnded) {\n for (const [key, value] of ctx.headers) {\n try {\n res.setHeader(key, value);\n } catch (error) {}\n }\n }\n\n (req as any).__FARM_MIDDLEWARE_DATA__ = new Map(ctx.data);\n (req as any).__FARM_MIDDLEWARE_CONTEXT__ = new Map(ctx.locals);\n\n return false; // Continue to page rendering\n }\n\n /**\n * Check if pathname matches middleware config\n */\n private matchesConfig(\n pathname: string,\n config: MiddlewareConfig,\n ctx: MiddlewareContext,\n ): { matched: boolean; params?: Record<string, string> } {\n // Check exclusions\n if (config.exclude) {\n for (const pattern of config.exclude) {\n if (this.matchPattern(pattern, pathname).matched) {\n return { matched: false };\n }\n }\n }\n\n // Check matchers\n if (config.matcher) {\n for (const matcher of this.toMatcherList(config.matcher)) {\n if (typeof matcher === \"string\" || matcher instanceof RegExp) {\n const result = this.matchPattern(matcher, pathname);\n if (result.matched) {\n return result;\n }\n } else if (typeof matcher === \"function\") {\n return { matched: matcher(ctx) };\n }\n }\n return { matched: false };\n }\n\n return { matched: true };\n }\n\n /**\n * Match a pattern against pathname\n */\n private matchPattern(\n pattern: string | RegExp,\n pathname: string,\n ): { matched: boolean; params?: Record<string, string> } {\n if (pattern instanceof RegExp) {\n pattern.lastIndex = 0;\n const match = pattern.exec(pathname);\n return {\n matched: !!match,\n params: match?.groups ? { ...match.groups } : undefined,\n };\n }\n\n if (pattern === \"*\" || pattern === \"/(.*)\") {\n return { matched: true };\n }\n\n if (pattern.endsWith(\"(.*)\")) {\n const prefix = pattern.slice(0, -4);\n return { matched: pathname === prefix || pathname.startsWith(`${prefix}/`) };\n }\n\n const { regex, params } = this.compilePathPattern(pattern);\n const match = regex.exec(pathname);\n if (!match) {\n return { matched: false };\n }\n\n const values: Record<string, string> = {};\n params.forEach((param, index) => {\n values[param] = decodeURIComponent(match[index + 1] || \"\");\n });\n\n return {\n matched: true,\n params: Object.keys(values).length > 0 ? values : undefined,\n };\n }\n\n /**\n * Reload middleware (for HMR)\n */\n async reload(): Promise<void> {\n await this.discover();\n }\n\n getMiddlewares(): DiscoveredMiddleware[] {\n return [...this.configMiddleware, ...this.middleware];\n }\n\n hasMiddleware(): boolean {\n return this.configMiddleware.length > 0 || this.middleware.length > 0;\n }\n\n private matchRoutePath(\n pathname: string,\n middlewarePath: string,\n ): { matched: boolean; params?: Record<string, string> } {\n if (middlewarePath === \"/\") return { matched: true };\n\n const exactMatch = this.matchPattern(middlewarePath, pathname);\n if (exactMatch.matched) {\n return exactMatch;\n }\n\n const nestedMatch = this.matchPattern(`${middlewarePath}/:__farmRest*`, pathname);\n if (!nestedMatch.matched) {\n return { matched: false };\n }\n\n const params = { ...(nestedMatch.params || {}) };\n delete params.__farmRest;\n return {\n matched: true,\n params: Object.keys(params).length > 0 ? params : undefined,\n };\n }\n\n private toMatcherList(matcher: MiddlewareConfig[\"matcher\"]): MiddlewareMatcher[] {\n if (!matcher) return [];\n return Array.isArray(matcher) ? matcher : [matcher];\n }\n\n private getConfigHandlers(\n entry:\n | MiddlewareConfig\n | (MiddlewareConfig & {\n handler?: MiddlewareFunction;\n handlers?: MiddlewareFunction[];\n }),\n ): MiddlewareFunction[] {\n const handlers: MiddlewareFunction[] = [];\n if (\"handler\" in entry && typeof entry.handler === \"function\") {\n handlers.push(entry.handler);\n }\n if (\"handlers\" in entry && Array.isArray(entry.handlers)) {\n handlers.push(...entry.handlers.filter((handler) => typeof handler === \"function\"));\n }\n return handlers;\n }\n\n private toMiddlewareConfig(\n entry: MiddlewareConfig & {\n handler?: MiddlewareFunction;\n handlers?: MiddlewareFunction[];\n },\n ): MiddlewareConfig {\n const { matcher, exclude, runtime } = entry;\n return { matcher, exclude, runtime };\n }\n\n private compilePathPattern(pattern: string): { regex: RegExp; params: string[] } {\n const params: string[] = [];\n const segments = pattern.split(\"/\").filter(Boolean);\n\n if (segments.length === 0) {\n return { regex: /^\\/$/, params };\n }\n\n const parts = segments.map((segment) => {\n if (segment === \"**\") {\n return \"(?:/.*)?\";\n }\n\n if (segment === \"*\") {\n return \"/[^/]+\";\n }\n\n if (segment.startsWith(\":\")) {\n const { name, modifier } = this.parseColonParam(segment);\n params.push(name);\n\n if (modifier === \"*\") {\n return \"(?:/(.*))?\";\n }\n if (modifier === \"+\") {\n return \"/(.+)\";\n }\n return \"/([^/]+)\";\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n params.push(segment.slice(4, -1));\n return \"(?:/(.*))?\";\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n params.push(segment.slice(1, -1));\n return \"/([^/]+)\";\n }\n\n return `/${this.escapeRegex(segment).replace(/\\\\\\*/g, \"[^/]*\")}`;\n });\n\n return {\n regex: new RegExp(`^${parts.join(\"\")}$`),\n params,\n };\n }\n\n private parseColonParam(segment: string): { name: string; modifier?: string } {\n const raw = segment.slice(1);\n const last = raw[raw.length - 1];\n const modifier = last === \"*\" || last === \"+\" || last === \"?\" ? last : undefined;\n return {\n name: modifier ? raw.slice(0, -1) : raw,\n modifier,\n };\n }\n\n private escapeRegex(value: string): string {\n return value.replace(/[|\\\\{}()[\\]^$+?.]/g, \"\\\\$&\");\n }\n}\n","/**\n * Middleware Context Implementation\n */\n\nimport type { IncomingMessage, ServerResponse } from \"http\";\nimport type { ViteDevServer } from \"vite\";\nimport type { MiddlewareContext, CookieJar, CookieOptions } from \"./types\";\n\n/**\n * Parse cookies from Cookie header\n */\nfunction parseCookies(cookieHeader?: string): Record<string, string> {\n if (!cookieHeader) return {};\n\n return cookieHeader.split(\";\").reduce(\n (cookies, cookie) => {\n const [name, ...rest] = cookie.split(\"=\");\n const value = rest.join(\"=\").trim();\n if (name && value) {\n cookies[name.trim()] = decodeURIComponent(value);\n }\n return cookies;\n },\n {} as Record<string, string>,\n );\n}\n\n/**\n * Serialize a cookie\n */\nfunction serializeCookie(name: string, value: string, options: CookieOptions = {}): string {\n let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n\n if (options.maxAge) {\n cookie += `; Max-Age=${options.maxAge}`;\n }\n\n if (options.expires) {\n cookie += `; Expires=${options.expires.toUTCString()}`;\n }\n\n if (options.path) {\n cookie += `; Path=${options.path}`;\n } else {\n cookie += \"; Path=/\";\n }\n\n if (options.domain) {\n cookie += `; Domain=${options.domain}`;\n }\n\n if (options.secure) {\n cookie += \"; Secure\";\n }\n\n if (options.httpOnly) {\n cookie += \"; HttpOnly\";\n }\n\n if (options.sameSite) {\n cookie += `; SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`;\n }\n\n return cookie;\n}\n\n/**\n * Cookie Jar implementation\n */\nclass CookieJarImpl implements CookieJar {\n private cookies: Record<string, string>;\n private setCookies: string[] = [];\n\n constructor(\n private req: IncomingMessage,\n private res: ServerResponse,\n ) {\n this.cookies = parseCookies(req.headers.cookie);\n }\n\n get(name: string): string | undefined {\n return this.cookies[name];\n }\n\n set(name: string, value: string, options: CookieOptions = {}): void {\n this.cookies[name] = value;\n const cookieString = serializeCookie(name, value, options);\n this.setCookies.push(cookieString);\n\n // Update Set-Cookie header\n this.res.setHeader(\"Set-Cookie\", this.setCookies);\n }\n\n delete(name: string): void {\n delete this.cookies[name];\n const cookieString = serializeCookie(name, \"\", {\n maxAge: 0,\n expires: new Date(0),\n });\n this.setCookies.push(cookieString);\n this.res.setHeader(\"Set-Cookie\", this.setCookies);\n }\n\n getAll(): Record<string, string> {\n return { ...this.cookies };\n }\n}\n\n/**\n * Create a middleware context from request/response\n */\nexport function createContext(\n req: IncomingMessage,\n res: ServerResponse,\n viteServer?: ViteDevServer,\n parent?: MiddlewareContext[\"parent\"],\n): MiddlewareContext {\n const url = new URL(req.url || \"/\", `http://${req.headers.host || \"localhost\"}`);\n const headers = new Map<string, string>();\n const data = parent?.data ? new Map(parent.data) : new Map<string, any>();\n const locals = parent?.locals ? new Map(parent.locals) : new Map<string, any>();\n const cookies = new CookieJarImpl(req, res);\n\n // Copy existing headers\n Object.entries(req.headers).forEach(([key, value]) => {\n if (typeof value === \"string\") {\n headers.set(key, value);\n } else if (Array.isArray(value)) {\n headers.set(key, value.join(\", \"));\n }\n });\n\n if (parent?.headers) {\n for (const [key, value] of Object.entries(parent.headers)) {\n headers.set(key, value);\n }\n }\n\n let handled = false;\n\n const ctx: MiddlewareContext = {\n request: req,\n response: res,\n url,\n pathname: url.pathname,\n searchParams: url.searchParams,\n method: req.method || \"GET\",\n params: {},\n route: url.pathname,\n parent,\n vite: {\n isDev: process.env.NODE_ENV !== \"production\",\n hmr: !!viteServer?.hot,\n server: viteServer,\n },\n data,\n locals,\n headers,\n cookies,\n _handled: false,\n\n redirect(redirectUrl: string, status = 307): void {\n if (handled) {\n console.warn(\"Response already sent, cannot redirect\");\n return;\n }\n\n ctx._redirectUrl = redirectUrl;\n ctx._handled = true;\n handled = true;\n\n res.writeHead(status, {\n Location: redirectUrl,\n \"Content-Type\": \"text/plain\",\n });\n res.end(`Redirecting to ${redirectUrl}`);\n },\n\n rewrite(rewriteUrl: string): void {\n ctx._rewriteUrl = rewriteUrl;\n // Update the URL for downstream middleware\n const newUrl = new URL(rewriteUrl, `http://${req.headers.host || \"localhost\"}`);\n ctx.url = newUrl;\n ctx.pathname = newUrl.pathname;\n ctx.searchParams = newUrl.searchParams;\n // Update the original request URL\n req.url = rewriteUrl;\n },\n\n json(jsonData: any, status = 200): void {\n if (handled) {\n console.warn(\"Response already sent, cannot send JSON\");\n return;\n }\n\n ctx._handled = true;\n handled = true;\n\n res.writeHead(status, {\n \"Content-Type\": \"application/json\",\n });\n res.end(JSON.stringify(jsonData));\n },\n\n text(content: string, status = 200): void {\n if (handled) {\n console.warn(\"Response already sent, cannot send text\");\n return;\n }\n\n ctx._handled = true;\n handled = true;\n\n res.writeHead(status, {\n \"Content-Type\": \"text/plain\",\n });\n res.end(content);\n },\n\n html(content: string, status = 200): void {\n if (handled) {\n console.warn(\"Response already sent, cannot send HTML\");\n return;\n }\n\n ctx._handled = true;\n handled = true;\n\n res.writeHead(status, {\n \"Content-Type\": \"text/html\",\n });\n res.end(content);\n },\n };\n\n return ctx;\n}\n","import { createWebRequestFromFarmRequest } from \"../server/request\";\nimport type {\n MiddlewareConfig,\n MiddlewareContext,\n MiddlewareFunction,\n MiddlewareModule,\n MiddlewareStore,\n RequestMiddlewareContext,\n} from \"./types\";\n\nexport interface NormalizedMiddlewareModule {\n handlers: MiddlewareFunction[];\n config?: MiddlewareConfig;\n}\n\nfunction isWebRequest(request: unknown): request is Request {\n return typeof Request !== \"undefined\" && request instanceof Request;\n}\n\nfunction toWebRequest(ctx: MiddlewareContext): Request {\n if (isWebRequest(ctx.request)) {\n return ctx.request;\n }\n return createWebRequestFromFarmRequest(ctx.request);\n}\n\nfunction createRequestMiddlewareContext(\n ctx: MiddlewareContext,\n): RequestMiddlewareContext<Record<string, any>, Record<string, any>> {\n const context = {\n get url() {\n return ctx.url;\n },\n get pathname() {\n return ctx.pathname;\n },\n get searchParams() {\n return ctx.searchParams;\n },\n get method() {\n return ctx.method;\n },\n get params() {\n return ctx.params;\n },\n get route() {\n return ctx.route;\n },\n get locals() {\n return ctx.locals as MiddlewareStore<Record<string, any>>;\n },\n get data() {\n return ctx.data as MiddlewareStore<Record<string, any>>;\n },\n get headers() {\n return ctx.headers;\n },\n get cookies() {\n return ctx.cookies;\n },\n get(key: string) {\n return ctx.locals.get(key);\n },\n has(key: string) {\n return ctx.locals.has(key);\n },\n set(key: string, value: any) {\n ctx.locals.set(key, value);\n },\n delete(key: string) {\n return ctx.locals.delete(key);\n },\n redirect(url: string, status?: number) {\n ctx.redirect(url, status);\n },\n rewrite(url: string) {\n ctx.rewrite(url);\n },\n json(data: any, status?: number) {\n ctx.json(data, status);\n },\n text(content: string, status?: number) {\n ctx.text(content, status);\n },\n html(content: string, status?: number) {\n ctx.html(content, status);\n },\n } satisfies RequestMiddlewareContext;\n\n return context;\n}\n\n/**\n * Normalize the two supported middleware file styles to Farm's internal chain.\n */\nexport function normalizeMiddlewareModule(\n middlewareModule: MiddlewareModule | Record<string, any>,\n routePath: string,\n): NormalizedMiddlewareModule | null {\n const module = middlewareModule as MiddlewareModule;\n const defaultExport = module.default;\n const namedExport = module.middleware;\n const hasNamedExport = typeof namedExport === \"function\";\n\n if (namedExport !== undefined && !hasNamedExport) {\n throw new TypeError(\"The named middleware export must be a function\");\n }\n\n if (defaultExport && hasNamedExport) {\n throw new Error(\n \"A middleware file cannot export both a default handler and a named middleware handler\",\n );\n }\n\n if (hasNamedExport) {\n return {\n handlers: [\n async (ctx) => {\n return namedExport(toWebRequest(ctx), createRequestMiddlewareContext(ctx));\n },\n ],\n config: module.config,\n };\n }\n\n if (defaultExport && typeof defaultExport === \"object\" && \"build\" in defaultExport) {\n if (typeof (defaultExport as any).setBasePath === \"function\") {\n (defaultExport as any).setBasePath(routePath);\n }\n const built = (defaultExport as any).build();\n const handlers = Array.isArray(built?.handlers)\n ? built.handlers.filter((handler: unknown) => typeof handler === \"function\")\n : [];\n return handlers.length > 0\n ? {\n handlers,\n config: module.config || built?.config,\n }\n : null;\n }\n\n if (typeof defaultExport === \"function\") {\n return {\n handlers: [defaultExport as MiddlewareFunction],\n config: module.config,\n };\n }\n\n return null;\n}\n","import { mkdirSync } from \"fs\";\nimport { dirname, join, resolve } from \"path\";\nimport { APITypeGenerator, type APIRouteInfo } from \"./type-generator\";\nimport { generateRouteTypes, type GenerateRouteTypesOptions } from \"./routing/generate-route-types\";\nimport { generateEnvTypes } from \"./env-types\";\nimport { generateFarmImageTypes } from \"./image-types\";\nimport { generateFarmI18nTypes } from \"./i18n/type-generator\";\nimport type { ResolvedFarmI18nConfig } from \"./i18n/types\";\nimport { getFarmAppDirectories, getFarmSourceRoots, type ResolvedFarmLayer } from \"./layers\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\n\nexport { generateFarmI18nTypes };\n\nexport interface GenerateFarmTypeArtifactsOptions {\n root: string;\n srcDir?: string;\n extraRoutes?: string[];\n layers?: readonly ResolvedFarmLayer[];\n suppressLintOnLink?: boolean;\n routeTypesOutFile?: string;\n apiTypesOutFile?: string;\n envTypesOutFile?: string;\n imageTypesOutFile?: string;\n i18nTypesOutFile?: string;\n i18nConfig?: ResolvedFarmI18nConfig;\n routes?: boolean;\n api?: boolean;\n env?: boolean;\n images?: boolean;\n i18n?: boolean;\n}\n\nexport interface GenerateFarmTypeArtifactsResult {\n routeTypesPath?: string;\n apiTypesPath?: string;\n envTypesPath?: string;\n imageTypesPath?: string;\n i18nTypesPath?: string;\n apiRoutes: APIRouteInfo[];\n}\n\nexport async function generateFarmTypeArtifacts(\n options: GenerateFarmTypeArtifactsOptions,\n): Promise<GenerateFarmTypeArtifactsResult> {\n const root = resolve(options.root);\n const srcDir = options.srcDir || \"src\";\n const shouldGenerateRoutes = options.routes !== false;\n const shouldGenerateApi = options.api !== false;\n const shouldGenerateEnv = options.env !== false;\n const shouldGenerateImages = options.images !== false;\n const shouldGenerateI18n = options.i18n !== false && options.i18nConfig?.enabled;\n const sourceRoots = getFarmSourceRoots({ root, srcDir, layers: options.layers });\n const appDirs = getFarmAppDirectories({ root, srcDir, layers: options.layers });\n\n const result: GenerateFarmTypeArtifactsResult = {\n apiRoutes: [],\n };\n\n if (shouldGenerateRoutes) {\n const routeOptions: GenerateRouteTypesOptions = {\n root,\n srcDir,\n extraRoutes: options.extraRoutes || [],\n suppressLintOnLink: options.suppressLintOnLink,\n sourceRoots,\n };\n\n if (options.routeTypesOutFile) {\n routeOptions.outFile = options.routeTypesOutFile;\n }\n\n result.routeTypesPath = await generateRouteTypes(routeOptions);\n }\n\n if (shouldGenerateApi) {\n const generator = new APITypeGenerator(appDirs);\n const apiRoutes = generator.scanAPIRoutes();\n const apiTypesPath = options.apiTypesOutFile\n ? resolve(root, options.apiTypesOutFile)\n : join(root, srcDir, \"lib\", \"api.generated.ts\");\n const content = generator.generateAPIRouter(apiRoutes, { outFile: apiTypesPath });\n\n mkdirSync(dirname(apiTypesPath), { recursive: true });\n writeFileIfChanged(apiTypesPath, content);\n\n result.apiTypesPath = apiTypesPath;\n result.apiRoutes = apiRoutes;\n }\n\n if (shouldGenerateEnv) {\n result.envTypesPath = await generateEnvTypes({\n root,\n srcDir,\n outFile: options.envTypesOutFile,\n layerConfigPaths: (options.layers ?? [])\n .map((layer) => layer.configFile)\n .filter((configFile): configFile is string => Boolean(configFile)),\n });\n }\n\n if (shouldGenerateImages) {\n result.imageTypesPath = generateFarmImageTypes({\n root,\n srcDir,\n outFile: options.imageTypesOutFile,\n });\n }\n\n if (shouldGenerateI18n && options.i18nConfig) {\n result.i18nTypesPath = await generateFarmI18nTypes({\n root,\n srcDir,\n config: options.i18nConfig,\n outFile: options.i18nTypesOutFile,\n });\n }\n\n return result;\n}\n","import * as path from \"path\";\nimport * as fs from \"fs\";\nimport { parseRoutePath } from \"../utils\";\nimport type { ParsedRoute } from \"../types\";\nimport { discoverProgrammaticRoutePaths } from \"../routes.server\";\nimport type { FarmSourceRoot } from \"../layers\";\nimport { writeFileIfChanged } from \"../write-file-if-changed\";\n\nfunction routeSegmentsToTsTypeLiteral(segments: string[]): string {\n if (segments.length === 0) return '\"/\"';\n const hasDynamic = segments.some((s) => s.startsWith(\"[\"));\n if (!hasDynamic) return JSON.stringify(\"/\" + segments.join(\"/\"));\n const parts = segments.map((s) => {\n if (s.startsWith(\"[[...\") || s.startsWith(\"[...\")) return \"${string}\";\n if (s.startsWith(\"[\")) return \"${string}\";\n return s;\n });\n return \"`/\" + parts.join(\"/\") + \"`\";\n}\n\nfunction routePatternToTsTypeLiterals(pattern: string): string[] {\n if (pattern === \"/\") return ['\"/\"'];\n\n let variants: string[][] = [[]];\n for (const segment of pattern.slice(1).split(\"/\").filter(Boolean)) {\n if (segment.startsWith(\"[[...\") && segment.endsWith(\"]]\")) {\n variants = variants.flatMap((parts) => [parts, [...parts, segment]]);\n } else {\n variants = variants.map((parts) => [...parts, segment]);\n }\n }\n\n return variants.map(routeSegmentsToTsTypeLiteral);\n}\n\nfunction routePatternToRouteLiteral(pattern: string): string {\n return JSON.stringify(pattern);\n}\n\nfunction createRoutePattern(route: ParsedRoute): string {\n if (route.segments.length === 0) return \"/\";\n return (\n \"/\" +\n route.segments\n .map((seg) => {\n if (!seg.isDynamic) return seg.segment;\n if (seg.isCatchAll) return seg.isOptional ? `[[...${seg.segment}]]` : `[...${seg.segment}]`;\n return `[${seg.segment}]`;\n })\n .join(\"/\")\n );\n}\n\nexport interface GenerateRouteTypesOptions {\n root: string;\n srcDir?: string;\n outFile?: string;\n extraRoutes?: string[];\n /** Ordered layer roots followed by the project root. */\n sourceRoots?: readonly FarmSourceRoot[];\n /** When true, do not augment LinkDefaultRoute so Link href accepts any string (no route-type errors). */\n suppressLintOnLink?: boolean;\n}\n\nconst DEFAULT_OUT_FILE = \"farm-routes.d.ts\";\n\n/**\n * Scan app directory for page files, generate RoutePath union type,\n * and write a .d.ts file for typed Link href.\n */\nexport async function generateRouteTypes(options: GenerateRouteTypesOptions): Promise<string> {\n const {\n root,\n srcDir = \"src\",\n outFile = DEFAULT_OUT_FILE,\n extraRoutes = [],\n suppressLintOnLink = false,\n } = options;\n const sourceRoots = options.sourceRoots ?? [{ name: \"project\", root, srcDir, layer: false }];\n\n const outPath = path.join(root, srcDir, outFile);\n\n const patterns = new Set<string>();\n\n const glob = await import(\"fast-glob\");\n for (const source of sourceRoots) {\n const appDir = path.join(source.root, source.srcDir, \"app\");\n if (fs.existsSync(appDir)) {\n const pageFiles = await glob.default(\"**/page.{ts,tsx,js,jsx,md,mdx}\", {\n cwd: appDir,\n absolute: false,\n });\n\n for (const file of pageFiles) {\n const route = parseRoutePath(file);\n if (route.type === \"page\") {\n const pattern = createRoutePattern(route);\n patterns.add(pattern);\n }\n }\n }\n\n for (const route of await discoverProgrammaticRoutePaths(source.root, source.srcDir)) {\n patterns.add(route);\n }\n }\n\n for (const route of extraRoutes) {\n if (route.startsWith(\"/\")) {\n patterns.add(route);\n }\n }\n\n const sortedPatterns = Array.from(patterns).sort();\n const typeLiterals = Array.from(new Set(sortedPatterns.flatMap(routePatternToTsTypeLiterals)));\n const patternLiterals = sortedPatterns.map(routePatternToRouteLiteral);\n\n const routePathType = suppressLintOnLink\n ? \"string\"\n : typeLiterals.length\n ? typeLiterals.join(\" | \")\n : \"never\";\n const routePatternType = suppressLintOnLink\n ? \"string\"\n : patternLiterals.length\n ? patternLiterals.join(\" | \")\n : \"never\";\n const augmentationBlock = suppressLintOnLink\n ? \"\"\n : `\ndeclare module \"@farm.js/core/client\" {\n interface LinkDefaultRoute {\n _: import(\"./farm-routes\").RoutePath;\n pattern: import(\"./farm-routes\").RoutePattern;\n }\n}\n\ndeclare module \"@farm.js/core\" {\n interface LinkDefaultRoute {\n _: import(\"./farm-routes\").RoutePath;\n pattern: import(\"./farm-routes\").RoutePattern;\n }\n // Ensure root import (\"@farm.js/core\") uses the same typed Link signature as client entry.\n const Link: typeof import(\"@farm.js/core/client\").Link;\n}\n\n// Internal declaration path used by @farm.js/core root type re-exports.\ndeclare module \"@farm.js/core/dist/client.js\" {\n interface LinkDefaultRoute {\n _: import(\"./farm-routes\").RoutePath;\n pattern: import(\"./farm-routes\").RoutePattern;\n }\n}\n`;\n\n const content = `/**\n * Auto-generated route types from src/app.\n * Link href is typed automatically via module augmentation. Regenerated on dev start and when routes change.\n * Set suppressLintOnLink: true in farm.config.ts to accept any string on Link href.\n */\nexport type RoutePath = ${routePathType};\nexport type RoutePattern = ${routePatternType};${augmentationBlock}\n`;\n\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n writeFileIfChanged(outPath, content);\n\n return outPath;\n}\n","import * as fs from \"fs\";\nimport * as path from \"path\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\n\nexport interface GenerateEnvTypesOptions {\n root: string;\n srcDir?: string;\n outFile?: string;\n configPath?: string;\n /** Lower-priority layer config files, ordered before the project config. */\n layerConfigPaths?: readonly string[];\n}\n\nconst DEFAULT_OUT_FILE = \"farm-env.d.ts\";\nconst CONFIG_FILENAMES = [\n \"farm.config.ts\",\n \"farm.config.tsx\",\n \"farm.config.mts\",\n \"farm.config.cts\",\n \"farm.config.js\",\n \"farm.config.jsx\",\n \"farm.config.mjs\",\n \"farm.config.cjs\",\n \"config.ts\",\n \"config.tsx\",\n \"config.mts\",\n \"config.cts\",\n \"config.js\",\n \"config.jsx\",\n \"config.mjs\",\n \"config.cjs\",\n];\n\nexport async function generateEnvTypes(options: GenerateEnvTypesOptions): Promise<string> {\n const root = path.resolve(options.root);\n const srcDir = options.srcDir || \"src\";\n const outPath = path.join(root, srcDir, options.outFile || DEFAULT_OUT_FILE);\n const configPath = findConfigPath(root, options.configPath);\n const configPaths = [\n ...(options.layerConfigPaths ?? []).filter((value) => fs.existsSync(value)),\n ...(configPath ? [configPath] : []),\n ];\n const content =\n configPaths.length > 1\n ? createLayeredConfigBackedEnvTypes(outPath, configPaths)\n : configPaths.length === 1\n ? createConfigBackedEnvTypes(outPath, configPaths[0])\n : createEmptyEnvTypes();\n\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n writeFileIfChanged(outPath, content);\n\n return outPath;\n}\n\nfunction createLayeredConfigBackedEnvTypes(outPath: string, configPaths: string[]): string {\n const imports = configPaths\n .map(\n (configPath, index) =>\n `import type FarmConfig${index} from ${JSON.stringify(toTypeImportPath(outPath, configPath))};`,\n )\n .join(\"\\n\");\n const resolvedTypes = configPaths\n .map(\n (_configPath, index) => `\ntype FarmConfigEnv${index} = typeof FarmConfig${index} extends { env?: infer TEnv }\n ? NonNullable<TEnv>\n : never;\ntype FarmResolvedEnv${index} = [FarmConfigEnv${index}] extends [never]\n ? { server: {}; public: {} }\n : InferEnv<FarmConfigEnv${index}>;`,\n )\n .join(\"\\n\");\n const mergedTypes = configPaths\n .slice(1)\n .map(\n (_configPath, index) =>\n `type FarmMergedEnv${index + 1} = MergeFarmEnv<${index === 0 ? \"FarmResolvedEnv0\" : `FarmMergedEnv${index}`}, FarmResolvedEnv${index + 1}>;`,\n )\n .join(\"\\n\");\n const finalType = `FarmMergedEnv${configPaths.length - 1}`;\n\n return `/**\n * Auto-generated env types from Farm layers and farm.config.\n * Regenerated on dev start, build, and farm generate.\n */\n${imports}\nimport type { InferEnv } from \"@farm.js/core/env\";\n\ntype MergeFarmEnv<TBase, TOverride> = {\n server: Omit<TBase extends { server: infer T } ? T : {}, keyof (TOverride extends { server: infer T } ? T : {})> &\n (TOverride extends { server: infer T } ? T : {});\n public: Omit<TBase extends { public: infer T } ? T : {}, keyof (TOverride extends { public: infer T } ? T : {})> &\n (TOverride extends { public: infer T } ? T : {});\n};\n${resolvedTypes}\n${mergedTypes}\n\ntype FarmResolvedEnv = ${finalType};\n\ndeclare module \"@farm.js/core/env\" {\n interface FarmEnvTypes {\n server: FarmResolvedEnv[\"server\"];\n public: FarmResolvedEnv[\"public\"];\n }\n}\n\ndeclare module \"@farm.js/core\" {\n interface FarmEnvTypes {\n server: FarmResolvedEnv[\"server\"];\n public: FarmResolvedEnv[\"public\"];\n }\n}\n\nexport {};\n`;\n}\n\nfunction findConfigPath(root: string, configPath?: string): string | null {\n if (configPath) {\n const resolvedPath = path.isAbsolute(configPath) ? configPath : path.join(root, configPath);\n return fs.existsSync(resolvedPath) ? resolvedPath : null;\n }\n\n for (const filename of CONFIG_FILENAMES) {\n const resolvedPath = path.join(root, filename);\n if (fs.existsSync(resolvedPath)) {\n return resolvedPath;\n }\n }\n\n return null;\n}\n\nfunction createConfigBackedEnvTypes(outPath: string, configPath: string): string {\n const configImportPath = toTypeImportPath(outPath, configPath);\n\n return `/**\n * Auto-generated env types from farm.config.\n * Regenerated on dev start, build, and farm generate.\n */\nimport type FarmConfig from ${JSON.stringify(configImportPath)};\nimport type { InferEnv } from \"@farm.js/core/env\";\n\ntype FarmConfigEnv = typeof FarmConfig extends { env?: infer TEnv } ? NonNullable<TEnv> : never;\ntype FarmResolvedEnv = [FarmConfigEnv] extends [never]\n ? { server: {}; public: {} }\n : InferEnv<FarmConfigEnv>;\n\ndeclare module \"@farm.js/core/env\" {\n interface FarmEnvTypes {\n server: FarmResolvedEnv[\"server\"];\n public: FarmResolvedEnv[\"public\"];\n }\n}\n\ndeclare module \"@farm.js/core\" {\n interface FarmEnvTypes {\n server: FarmResolvedEnv[\"server\"];\n public: FarmResolvedEnv[\"public\"];\n }\n}\n\nexport {};\n`;\n}\n\nfunction createEmptyEnvTypes(): string {\n return `/**\n * Auto-generated env types from farm.config.\n * Regenerated on dev start, build, and farm generate.\n */\ndeclare module \"@farm.js/core/env\" {\n interface FarmEnvTypes {\n server: {};\n public: {};\n }\n}\n\ndeclare module \"@farm.js/core\" {\n interface FarmEnvTypes {\n server: {};\n public: {};\n }\n}\n\nexport {};\n`;\n}\n\nfunction toTypeImportPath(outPath: string, targetPath: string): string {\n const relativePath = path\n .relative(path.dirname(outPath), targetPath)\n .replace(/\\\\/g, \"/\")\n .replace(/\\.(tsx?|jsx?|mjs|cjs|mts|cts)$/, \"\");\n\n return relativePath.startsWith(\".\") ? relativePath : `./${relativePath}`;\n}\n","import { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { writeFileIfChanged } from \"./write-file-if-changed\";\n\nexport const FARM_STATIC_IMAGE_EXTENSIONS = [\"avif\", \"gif\", \"jpeg\", \"jpg\", \"png\", \"webp\"] as const;\n\nexport interface GenerateFarmImageTypesOptions {\n root: string;\n srcDir?: string;\n outFile?: string;\n}\n\nexport function generateFarmImageTypes(options: GenerateFarmImageTypesOptions): string {\n const outputPath = options.outFile\n ? path.resolve(options.root, options.outFile)\n : path.join(options.root, options.srcDir || \"src\", \"farm-images.d.ts\");\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileIfChanged(outputPath, createFarmImageTypeDeclarations());\n return outputPath;\n}\n\nexport function createFarmImageTypeDeclarations(): string {\n const modules = FARM_STATIC_IMAGE_EXTENSIONS.map(\n (extension) => `declare module \"*.${extension}\" {\n const image: import(\"@farm.js/core/image\").StaticImageData;\n export const src: string;\n export const width: number;\n export const height: number;\n export const blurDataURL: string | undefined;\n export default image;\n}`,\n );\n\n return `// Generated by Farm.js. Do not edit.\n${modules.join(\"\\n\\n\")}\n\ndeclare module \"*?url\" {\n const src: string;\n export default src;\n}\n`;\n}\n","import { mkdirSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport {\n readFarmI18nCatalogs,\n type FarmI18nArgumentKind,\n type FarmI18nMessageSignature,\n} from \"./catalog\";\nimport type { ResolvedFarmI18nConfig } from \"./types\";\nimport { writeFileIfChanged } from \"../write-file-if-changed\";\n\nexport interface GenerateFarmI18nTypesOptions {\n root: string;\n srcDir?: string;\n config: ResolvedFarmI18nConfig;\n outFile?: string;\n}\n\nexport async function generateFarmI18nTypes(\n options: GenerateFarmI18nTypesOptions,\n): Promise<string | undefined> {\n if (!options.config.enabled) return undefined;\n\n const { signatures } = await readFarmI18nCatalogs(options.config);\n const outFile = options.outFile\n ? resolve(options.root, options.outFile)\n : join(resolve(options.root), options.srcDir || \"src\", \"farm-i18n.d.ts\");\n const content = renderFarmI18nTypes(options.config.locales, signatures);\n\n mkdirSync(dirname(outFile), { recursive: true });\n writeFileIfChanged(outFile, content);\n return outFile;\n}\n\nexport function renderFarmI18nTypes(\n locales: readonly string[],\n signatures: Record<string, FarmI18nMessageSignature>,\n): string {\n const localeEntries = locales.map((locale) => ` ${JSON.stringify(locale)}: true;`);\n const messageEntries = Object.entries(signatures)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, signature]) => ` ${JSON.stringify(key)}: ${renderSignature(signature)};`);\n\n return `// Generated by Farm.js. Do not edit.\nimport \"@farm.js/core/i18n\";\n\ndeclare module \"@farm.js/core/i18n\" {\n interface FarmI18nLocaleRegistry {\n${localeEntries.join(\"\\n\")}\n }\n\n interface FarmI18nMessageRegistry {\n${messageEntries.join(\"\\n\")}\n }\n}\n\nexport {};\n`;\n}\n\nfunction renderSignature(signature: FarmI18nMessageSignature): string {\n const entries = Object.entries(signature).sort(([a], [b]) => a.localeCompare(b));\n if (entries.length === 0) return \"Record<never, never>\";\n return `{ ${entries\n .map(([name, kind]) => `${JSON.stringify(name)}: ${argumentType(kind)}`)\n .join(\"; \")} }`;\n}\n\nfunction argumentType(kind: FarmI18nArgumentKind): string {\n switch (kind) {\n case \"number\":\n return \"number\";\n case \"date\":\n return \"Date | number\";\n case \"rich\":\n return \"(chunks: unknown[]) => unknown\";\n case \"select\":\n case \"string\":\n return \"string\";\n }\n}\n","import type { ConfigEnv, Plugin, ViteDevServer, HmrContext } from \"vite\";\nimport type { FarmConfig } from \"./types\";\nimport { FarmApp } from \"./app\";\nimport { logger, toViteModuleId } from \"./utils\";\nimport { defaultGlobalCSS } from \"./default-styles\";\nimport type { FarmPlugin, FarmPluginRuntimeSession, PluginManager } from \"./plugin\";\nimport { generateFarmClientPluginEntryCode } from \"./client-plugin-build\";\nimport { HMRManager } from \"./hmr\";\nimport { APIRouteManager } from \"./api/route-manager\";\nimport type { OpenAPIManager } from \"./openapi/manager\";\nimport { MiddlewareManager } from \"./middleware/manager\";\nimport { generateFarmTypeArtifacts, type GenerateFarmTypeArtifactsOptions } from \"./type-artifacts\";\nimport {\n isProgrammaticRoutesFileName,\n parseProgrammaticRouteModuleId,\n scanProgrammaticPagePaths,\n} from \"./routes\";\nimport type { FarmDocsAPIHandler } from \"./docs\";\nimport { createMarkdownMirrorResponse } from \"./markdown\";\nimport { createFarmMarkdownSourceResponse, isFarmMarkdownPageFile } from \"./app-markdown\";\nimport { sendWebResponse } from \"./server/response\";\nimport {\n getClientModuleMetadata,\n hasUseClientDirective,\n stripUseClientDirective,\n} from \"./utils/client-component\";\nimport {\n dispatchIntegrationRequest,\n getIntegrationDocumentNavigationMatchers,\n getIntegrationProviders,\n matchIntegrationRoute,\n} from \"./integrations\";\nimport type { FarmDiscoveredWorkflow } from \"./workflows\";\nimport { resolveFarmRouteContext, withFarmRouteContext } from \"./route-context\";\nimport {\n FARM_DEVTOOLS_LAUNCH_PARAM,\n FARM_DEVTOOLS_PATH,\n resolveFarmDevtoolsConfig,\n} from \"./devtools-config\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport type { FarmUserConfig } from \"./config\";\nimport { getFarmAppDirectories, getFarmLayerAliases, getFarmSourceRoots } from \"./layers\";\nimport { farmEnvironmentFunctionsPlugin } from \"./environment-vite\";\nimport { createDeferredDataResponse } from \"./deferred\";\nimport { _withAfterNodeMiddleware } from \"./after\";\nimport {\n createFarmDeploymentMismatchResponse,\n FARM_DEPLOYMENT_ID_HEADER,\n getFarmDeploymentMismatch,\n} from \"./deployment\";\nimport { getPublicFarmImageConfig, resolveFarmImageConfig } from \"./image-config\";\nimport { farmImageImportsPlugin } from \"./image-vite\";\nimport { createFarmImageHandler, type FarmImageHandler } from \"./image-server\";\nimport { getFarmI18nClientSnapshot } from \"./i18n/server\";\nimport { localizeFarmPathname } from \"./i18n/routing\";\nimport type { FarmI18nClientSnapshot } from \"./i18n/types\";\n\ninterface FarmVitePluginOptions extends FarmConfig {\n openapi?: FarmUserConfig[\"openapi\"];\n images?: FarmUserConfig[\"images\"];\n}\n\ntype TypeArtifactSelection = Pick<\n GenerateFarmTypeArtifactsOptions,\n \"routes\" | \"api\" | \"env\" | \"images\" | \"i18n\"\n>;\n\nconst ALL_TYPE_ARTIFACTS: TypeArtifactSelection = {\n routes: true,\n api: true,\n env: true,\n images: true,\n i18n: true,\n};\n\nconst createEmptyTypeArtifactSelection = (): TypeArtifactSelection => ({\n routes: false,\n api: false,\n env: false,\n images: false,\n i18n: false,\n});\n\nconst FARM_I18N_CLIENT_BRIDGE_ID = \"\\0farm-i18n-client-bridge\";\nconst EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME = `\nfunction isFarmDocsSearchPage() {\n return false;\n}\n\nasync function mountFarmDocsSearch() {\n return false;\n}\n`;\n\nfunction loadFarmDocsDevRuntime() {\n return import(\"./docs\");\n}\n\nfunction loadFarmDocsSearchDevRuntime() {\n return import(\"./docs/search-client\");\n}\n\nfunction loadFarmOpenAPIDevRuntime() {\n return import(\"./openapi/manager\");\n}\n\nfunction loadFarmWorkflowsDevRuntime() {\n return import(\"./workflows\");\n}\n\nfunction loadFarmDevtoolsSnapshotRuntime() {\n return import(\"./devtools\");\n}\n\nfunction loadFarmDevtoolsUIRuntime() {\n return import(\"./devtools-ui\");\n}\n\nfunction loadFarmDevtoolsClientRuntime() {\n return import(\"./devtools-client\");\n}\n\nexport function farmI18nClientBridgePlugin(): Plugin {\n return {\n name: \"farm:i18n-client-bridge\",\n enforce: \"pre\",\n resolveId(id, _importer, options) {\n if (id === \"@farm.js/core/i18n/server\" && !options?.ssr) {\n return FARM_I18N_CLIENT_BRIDGE_ID;\n }\n return null;\n },\n load(id) {\n if (id !== FARM_I18N_CLIENT_BRIDGE_ID) return null;\n return 'export { createTranslator, format, getLocale, getLocaleSource, t } from \"@farm.js/core/i18n/client\";';\n },\n };\n}\n\nconst FARM_CONFIG_FILENAMES = new Set([\n \"farm.config.ts\",\n \"farm.config.tsx\",\n \"farm.config.mts\",\n \"farm.config.cts\",\n \"farm.config.js\",\n \"farm.config.jsx\",\n \"farm.config.mjs\",\n \"farm.config.cjs\",\n \"config.ts\",\n \"config.tsx\",\n \"config.mts\",\n \"config.cts\",\n \"config.js\",\n \"config.jsx\",\n \"config.mjs\",\n \"config.cjs\",\n]);\n\nfunction serializeFarmInlineValue(value: unknown): string {\n return JSON.stringify(value)\n .replace(/</g, \"\\\\u003c\")\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nfunction escapeFarmHtmlAttribute(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n}\n\nfunction renderFarmI18nStaticHead(\n requestPath: string,\n snapshot: FarmI18nClientSnapshot | undefined,\n): string {\n if (!snapshot) return \"\";\n const runtime = `<script>window.__FARM_I18N__ = ${serializeFarmInlineValue(snapshot)};</script>`;\n if (snapshot.routing === \"none\") return runtime;\n\n const links = snapshot.locales.map(\n (locale) =>\n `<link rel=\"alternate\" hreflang=\"${escapeFarmHtmlAttribute(locale)}\" href=\"${escapeFarmHtmlAttribute(\n localizeFarmPathname(requestPath, locale, snapshot),\n )}\">`,\n );\n links.push(\n `<link rel=\"alternate\" hreflang=\"x-default\" href=\"${escapeFarmHtmlAttribute(\n localizeFarmPathname(requestPath, snapshot.defaultLocale, snapshot),\n )}\">`,\n );\n return `${links.join(\"\")}${runtime}`;\n}\n\nfunction getPublicEnvDefine(config: FarmVitePluginOptions): Record<string, unknown> {\n const publicEnv = (config as any).env?.public;\n if (!isResolvedEnvScope(publicEnv)) {\n return {};\n }\n\n return publicEnv;\n}\n\nfunction createRequestFromNodeRequest(\n req: {\n method?: string;\n headers: Record<string, string | string[] | undefined>;\n },\n url: URL,\n): Request {\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else if (value !== undefined) {\n headers.set(key, value);\n }\n }\n\n return new Request(url.toString(), {\n method: req.method || \"GET\",\n headers,\n });\n}\n\nfunction applyWebRequestToNodeRequest(\n request: Request,\n req: {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n },\n): void {\n const url = new URL(request.url);\n req.method = request.method;\n req.url = `${url.pathname}${url.search}`;\n\n for (const key of Object.keys(req.headers)) {\n delete req.headers[key];\n }\n request.headers.forEach((value, key) => {\n req.headers[key] = value;\n });\n}\n\nfunction createHeadersFromNodeResponse(res: {\n getHeaders(): Record<string, string | number | string[] | undefined>;\n}): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(res.getHeaders())) {\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else if (value !== undefined) {\n headers.set(key, String(value));\n }\n }\n return headers;\n}\n\nfunction applyWebResponseToNodeResponse(\n response: Response,\n res: {\n statusCode: number;\n headersSent: boolean;\n getHeaderNames(): string[];\n removeHeader(name: string): void;\n setHeader(name: string, value: string): void;\n },\n): void {\n if (res.headersSent) return;\n\n res.statusCode = response.status;\n for (const name of res.getHeaderNames()) {\n res.removeHeader(name);\n }\n response.headers.forEach((value, key) => {\n res.setHeader(key, value);\n });\n}\n\nfunction getFullEnvDefine(config: FarmVitePluginOptions): {\n server: Record<string, unknown>;\n public: Record<string, unknown>;\n} {\n const env = (config as any).env;\n if (!env || typeof env !== \"object\") {\n return { server: {}, public: {} };\n }\n\n return {\n server: isResolvedEnvScope(env.server) ? env.server : {},\n public: isResolvedEnvScope(env.public) ? env.public : {},\n };\n}\n\nfunction getEnvDefines(\n config: FarmVitePluginOptions,\n configEnv?: ConfigEnv,\n): Record<string, string> {\n const defines: Record<string, string> = {\n __FARM_PUBLIC_ENV__: JSON.stringify(getPublicEnvDefine(config)),\n __FARM_IMAGE_CONFIG__: JSON.stringify(\n getPublicFarmImageConfig(resolveFarmImageConfig(config.images)),\n ),\n };\n\n if (configEnv?.isSsrBuild) {\n defines.__FARM_ENV__ = JSON.stringify(getFullEnvDefine(config));\n }\n\n return defines;\n}\n\nfunction isResolvedEnvScope(value: unknown): value is Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n\n return !Object.values(value).some(\n (entry) =>\n typeof entry === \"function\" ||\n (!!entry && typeof entry === \"object\" && typeof (entry as any).parse === \"function\"),\n );\n}\n\nfunction isPotentialProgrammaticRouteSourceFile(\n normalizedFile: string,\n srcDirSlug: string,\n): boolean {\n return (\n normalizedFile.startsWith(`${srcDirSlug}/`) &&\n /\\.(ts|tsx|js|jsx)$/.test(normalizedFile) &&\n !/\\.d\\.ts$/.test(normalizedFile) &&\n !normalizedFile.endsWith(\"/farm-routes.d.ts\") &&\n !normalizedFile.endsWith(\"/farm-env.d.ts\") &&\n !normalizedFile.endsWith(\"/lib/api.generated.ts\")\n );\n}\n\nfunction fileContainsProgrammaticPageRoute(file: string): boolean {\n if (!fs.existsSync(file)) {\n return false;\n }\n\n try {\n return scanProgrammaticPagePaths(fs.readFileSync(file, \"utf8\")).length > 0;\n } catch {\n return false;\n }\n}\n\ninterface FarmModuleAstNode {\n type: string;\n start: number;\n end: number;\n [key: string]: unknown;\n}\n\nexport function rewriteEarlySsrRelativeImports(options: {\n code: string;\n id: string;\n root: string;\n parse: (code: string) => FarmModuleAstNode;\n}): string | null {\n const cleanId = options.id.split(\"?\", 1)[0];\n if (!path.isAbsolute(cleanId) || cleanId.replace(/\\\\/g, \"/\").includes(\"/node_modules/\")) {\n return null;\n }\n\n const replacements: Array<{ start: number; end: number; code: string }> = [];\n let ast: FarmModuleAstNode;\n try {\n ast = options.parse(options.code);\n } catch {\n return null;\n }\n\n walkModuleAst(ast, (node) => {\n if (\n node.type !== \"ImportDeclaration\" &&\n node.type !== \"ExportNamedDeclaration\" &&\n node.type !== \"ExportAllDeclaration\" &&\n node.type !== \"ImportExpression\"\n ) {\n return;\n }\n\n const source = node.source;\n if (!isFarmModuleAstNode(source) || typeof source.value !== \"string\") return;\n if (!source.value.startsWith(\".\")) return;\n\n const suffixIndex = source.value.search(/[?#]/);\n const sourcePath = suffixIndex === -1 ? source.value : source.value.slice(0, suffixIndex);\n const suffix = suffixIndex === -1 ? \"\" : source.value.slice(suffixIndex);\n const resolvedPath = path.resolve(path.dirname(cleanId), sourcePath);\n\n replacements.push({\n start: source.start,\n end: source.end,\n code: JSON.stringify(`${toViteModuleId(resolvedPath, options.root)}${suffix}`),\n });\n });\n\n if (replacements.length === 0) return null;\n\n let output = options.code;\n for (const replacement of replacements.sort((left, right) => right.start - left.start)) {\n output = output.slice(0, replacement.start) + replacement.code + output.slice(replacement.end);\n }\n return output;\n}\n\nfunction walkModuleAst(node: FarmModuleAstNode, visit: (node: FarmModuleAstNode) => void): void {\n visit(node);\n\n for (const [key, value] of Object.entries(node)) {\n if (key === \"start\" || key === \"end\" || key === \"loc\" || key === \"range\") continue;\n if (isFarmModuleAstNode(value)) {\n walkModuleAst(value, visit);\n continue;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n if (isFarmModuleAstNode(item)) walkModuleAst(item, visit);\n }\n }\n }\n}\n\nfunction isFarmModuleAstNode(value: unknown): value is FarmModuleAstNode {\n return (\n !!value &&\n typeof value === \"object\" &&\n typeof (value as FarmModuleAstNode).type === \"string\" &&\n typeof (value as FarmModuleAstNode).start === \"number\" &&\n typeof (value as FarmModuleAstNode).end === \"number\"\n );\n}\n\nfunction isFarmConfigFile(file: string, root: string): boolean {\n const normalized = file.replace(/\\\\/g, \"/\");\n const rootSlug = root.replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n const relative = normalized.startsWith(`${rootSlug}/`)\n ? normalized.slice(rootSlug.length + 1)\n : normalized;\n\n return FARM_CONFIG_FILENAMES.has(relative);\n}\n\nexport function farmPlugin(\n options: FarmVitePluginOptions = {},\n initialPluginManager?: PluginManager,\n): Plugin {\n const imageImports = farmImageImportsPlugin();\n let farmApp: FarmApp;\n let server: ViteDevServer;\n let hmrManager: HMRManager;\n let apiRouteManager: APIRouteManager;\n let openAPIManager: OpenAPIManager | null = null;\n let middlewareManager: MiddlewareManager;\n let refreshRouteDiscovery: ((reason: string) => Promise<void>) | null = null;\n let workflowHandler: ((request: Request) => Promise<Response | null>) | null = null;\n const pluginManager: PluginManager | undefined = initialPluginManager;\n const logUpdate = (tag: \"PAGE\" | \"API\" | \"MIDDLEWARE\" | \"TYPE\", message: string) => {\n try {\n const pc = require(\"picocolors\");\n const log = [\n pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n pc.dim(\"[\") + pc.bold(pc.cyan(tag)) + pc.dim(\"]\"),\n pc.dim(\"[\") + pc.bold(pc.yellow(\"UPDATE\")) + pc.dim(\"]\"),\n pc.gray(message),\n ].join(\" \");\n console.log(log);\n } catch {\n console.log(`[FARM] [${tag}] [UPDATE] ${message}`);\n }\n };\n\n return {\n name: \"farm\",\n\n config(_userConfig, configEnv) {\n const layerAliases = getFarmLayerAliases(options.layers);\n const layerRoots = (options.layers ?? []).map((layer) => layer.root);\n return {\n define: getEnvDefines(options, configEnv),\n resolve: {\n alias: layerAliases,\n },\n ...(layerRoots.length\n ? {\n server: {\n fs: {\n allow: [path.resolve(options.root || process.cwd()), ...layerRoots],\n },\n },\n }\n : {}),\n };\n },\n\n async configResolved(config) {\n // Defer initialization until Vite server is available\n },\n\n async configureServer(viteServer) {\n server = viteServer;\n\n // Store the plugin manager passed during creation\n const pm = initialPluginManager;\n const emitPluginError = async (\n phase: string,\n error: unknown,\n meta?: Record<string, unknown>,\n ) => {\n if (!pm) return;\n try {\n await pm.runHookParallel(\"onError\", { phase, error, meta });\n } catch {\n // Ignore plugin error reporter failures\n }\n };\n\n farmApp = new FarmApp(\n {\n root: server.config.root,\n ...options,\n },\n server,\n );\n\n const globalsCSSPath = path.join(server.config.root, \"src/app/globals.css\");\n if (!fs.existsSync(globalsCSSPath)) {\n const appDir = path.join(server.config.root, \"src/app\");\n if (!fs.existsSync(appDir)) {\n fs.mkdirSync(appDir, { recursive: true });\n }\n fs.writeFileSync(globalsCSSPath, defaultGlobalCSS);\n }\n\n await farmApp.initialize();\n\n const farmConfig = farmApp.getConfig();\n let imageHandler: FarmImageHandler | null = null;\n if (farmConfig.images.provider !== \"none\") {\n const { createNodeImageUrlValidator, createSharpImageTransformer } =\n await import(\"./image-sharp\");\n imageHandler = createFarmImageHandler(farmConfig.images, {\n transform: createSharpImageTransformer(),\n validateRemoteUrl: createNodeImageUrlValidator(farmConfig.images),\n onError(error) {\n logger.error(\n `Image optimization failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n },\n });\n }\n const sourceRoots = getFarmSourceRoots(farmConfig);\n server.watcher.add(sourceRoots.map((source) => path.join(source.root, source.srcDir)));\n if (farmConfig.i18n.enabled) {\n server.watcher.add(\n farmConfig.i18n.messages.includes(\"{locale}\")\n ? path.dirname(farmConfig.i18n.messages)\n : farmConfig.i18n.messages,\n );\n }\n const workflowConfig = farmConfig.workflows;\n const farmDocsDevRuntime = farmConfig.docs.enabled ? await loadFarmDocsDevRuntime() : null;\n const getExtraRouteTypes = () => [\n ...(options.openapi?.enabled && options.openapi.route ? [options.openapi.route] : []),\n ...(farmDocsDevRuntime?.getFarmDocsRouteTypeEntries(farmConfig.docs) ?? []),\n ];\n const appDirSlugs = sourceRoots.map((source) =>\n path.join(source.root, source.srcDir, \"app\").replace(/\\\\/g, \"/\"),\n );\n const generateTypeArtifacts = async (\n reason: string,\n selection: TypeArtifactSelection = ALL_TYPE_ARTIFACTS,\n log = false,\n ) => {\n try {\n const result = await generateFarmTypeArtifacts({\n root: farmConfig.root,\n srcDir: farmConfig.srcDir,\n layers: farmConfig.layers,\n extraRoutes: getExtraRouteTypes(),\n suppressLintOnLink: farmConfig.suppressLintOnLink,\n i18nConfig: farmConfig.i18n,\n ...selection,\n });\n if (log) {\n const refreshed = [\n selection.routes !== false && \"route\",\n selection.api !== false && \"API\",\n selection.env !== false && \"env\",\n selection.images !== false && \"image\",\n selection.i18n !== false && farmConfig.i18n.enabled && \"i18n\",\n ].filter(Boolean);\n logUpdate(\n \"TYPE\",\n `${reason} - refreshed ${refreshed.join(\", \")} types${\n selection.api !== false\n ? ` (${result.apiRoutes.length} API route${result.apiRoutes.length === 1 ? \"\" : \"s\"})`\n : \"\"\n }`,\n );\n }\n if (openAPIManager) {\n await openAPIManager.invalidateCache();\n }\n } catch (e) {\n if (process.env.FARM_VERBOSE) {\n logger.warn(\"Type artifact generation failed: \" + (e as Error).message);\n }\n if (pm) {\n await emitPluginError(\"type-artifact-generation\", e, { reason });\n }\n }\n };\n await generateTypeArtifacts(\"startup\");\n\n const srcDirSlugs = sourceRoots.map((source) =>\n path.join(source.root, source.srcDir).replace(/\\\\/g, \"/\"),\n );\n const layerConfigFiles = new Set(\n farmConfig.layers\n .map((layer) => layer.configFile?.replace(/\\\\/g, \"/\"))\n .filter((file): file is string => Boolean(file)),\n );\n const isPageFile = (file: string) => {\n const normalized = file.replace(/\\\\/g, \"/\");\n return (\n appDirSlugs.some((appDir) => normalized.startsWith(`${appDir}/`)) &&\n /page\\.(ts|tsx|js|jsx|md|mdx)$/.test(normalized)\n );\n };\n const isApiRouteFile = (file: string) => {\n const normalized = file.replace(/\\\\/g, \"/\");\n return (\n appDirSlugs.some((appDir) => normalized.startsWith(`${appDir}/api/`)) &&\n /route\\.(ts|tsx|js|jsx)$/.test(normalized)\n );\n };\n const isProgrammaticRouteFile = (file: string) => {\n const normalized = file.replace(/\\\\/g, \"/\");\n return (\n srcDirSlugs.some((srcDir) => normalized.startsWith(`${srcDir}/`)) &&\n isProgrammaticRoutesFileName(normalized)\n );\n };\n const isProgrammaticRouteSourceFile = (file: string) => {\n const normalized = file.replace(/\\\\/g, \"/\");\n return srcDirSlugs.some((srcDir) =>\n isPotentialProgrammaticRouteSourceFile(normalized, srcDir),\n );\n };\n const isAppRuntimeFile = (file: string) => {\n const normalized = file.replace(/\\\\/g, \"/\");\n return (\n appDirSlugs.some((appDir) => normalized.startsWith(`${appDir}/`)) &&\n /\\/(?:page|layout|loading|error|middleware|route)\\.(?:ts|tsx|js|jsx|md|mdx)$|\\/(?:opengraph-image|twitter-image)(?:\\.(?:ts|tsx|js|jsx|png|jpg|jpeg|gif|webp)|\\.alt\\.txt)$/.test(\n normalized,\n )\n );\n };\n const isStaticMetadataImageFile = (file: string) =>\n /\\/(?:opengraph-image|twitter-image)(?:\\.(?:png|jpg|jpeg|gif|webp)|\\.alt\\.txt)$/.test(\n file.replace(/\\\\/g, \"/\"),\n );\n const isI18nCatalogFile = (file: string) =>\n farmConfig.i18n.enabled &&\n file\n .replace(/\\\\/g, \"/\")\n .startsWith(farmConfig.i18n.messages.replace(/\\\\/g, \"/\").replace(\"{locale}\", \"\"));\n let typeArtifactGenScheduled: ReturnType<typeof setTimeout> | null = null;\n let pendingTypeArtifacts = createEmptyTypeArtifactSelection();\n let pendingTypeArtifactReason = \"\";\n let routeRefreshScheduled: ReturnType<typeof setTimeout> | null = null;\n const scheduleTypeArtifactGen = (\n file: string,\n event: string,\n selection: TypeArtifactSelection,\n ) => {\n for (const [artifact, enabled] of Object.entries(selection)) {\n if (enabled) {\n pendingTypeArtifacts[artifact as keyof TypeArtifactSelection] = true;\n }\n }\n pendingTypeArtifactReason ||= `${event} ${file.split(\"/app/\")[1] || file}`;\n if (typeArtifactGenScheduled) return;\n typeArtifactGenScheduled = setTimeout(() => {\n typeArtifactGenScheduled = null;\n const artifacts = pendingTypeArtifacts;\n const reason = pendingTypeArtifactReason;\n pendingTypeArtifacts = createEmptyTypeArtifactSelection();\n pendingTypeArtifactReason = \"\";\n generateTypeArtifacts(reason, artifacts, true).catch(() => {});\n }, 100);\n };\n [\"add\", \"change\", \"unlink\"].forEach((ev) => {\n server.watcher.on(ev as \"add\", (file: string) => {\n const normalizedFile = file.replace(/\\\\/g, \"/\");\n const configChanged =\n isFarmConfigFile(file, farmConfig.root) || layerConfigFiles.has(normalizedFile);\n const programmaticRouteChanged =\n isProgrammaticRouteFile(file) ||\n (isProgrammaticRouteSourceFile(file) &&\n (ev === \"unlink\" || fileContainsProgrammaticPageRoute(file)));\n const typeArtifacts: TypeArtifactSelection = configChanged\n ? ALL_TYPE_ARTIFACTS\n : {\n routes: (ev !== \"change\" && isPageFile(file)) || programmaticRouteChanged,\n api: isApiRouteFile(file) || programmaticRouteChanged,\n env: false,\n images: false,\n i18n: isI18nCatalogFile(file),\n };\n if (Object.values(typeArtifacts).some(Boolean)) {\n scheduleTypeArtifactGen(file, ev, typeArtifacts);\n }\n if (isI18nCatalogFile(file)) {\n farmApp\n ?.getI18nRuntime()\n .reload()\n .then(() => server.ws.send({ type: \"full-reload\", path: \"*\" }))\n .catch((error) => logger.warn(`i18n catalog reload failed: ${error.message}`));\n }\n if (\n (ev !== \"change\" || isStaticMetadataImageFile(file)) &&\n (isAppRuntimeFile(file) ||\n isProgrammaticRouteFile(file) ||\n (isProgrammaticRouteSourceFile(file) &&\n (ev === \"unlink\" || fileContainsProgrammaticPageRoute(file)))) &&\n !routeRefreshScheduled\n ) {\n routeRefreshScheduled = setTimeout(() => {\n routeRefreshScheduled = null;\n Promise.all([\n refreshRouteDiscovery?.(`${ev} ${file}`),\n file.includes(\"middleware.\") ? middlewareManager?.reload() : undefined,\n ])\n .then(() => server.ws.send({ type: \"full-reload\", path: \"*\" }))\n .catch((error) => logger.warn(`Route refresh failed: ${error.message}`));\n }, 50);\n }\n });\n });\n\n // Initialize HMR manager\n hmrManager = new HMRManager(server);\n\n // Initialize API route manager\n const appDirs = getFarmAppDirectories(farmConfig);\n const routeManager = farmApp.getRouteManager();\n const discoveredRoutes: Array<{\n kind: \"page\" | \"layout\";\n pattern: string;\n modulePath: string;\n }> = [];\n for (const [pattern, entry] of routeManager.getRoutes()) {\n discoveredRoutes.push({\n kind: \"page\",\n pattern,\n modulePath: entry.modulePath,\n });\n }\n for (const [pattern, entry] of routeManager.getLayouts()) {\n discoveredRoutes.push({\n kind: \"layout\",\n pattern,\n modulePath: entry.modulePath,\n });\n }\n if (pm) {\n for (const route of discoveredRoutes) {\n await pm.runHookParallel(\"routeDiscovered\", route);\n }\n await pm.runHookParallel(\"routesGenerated\", {\n routes: discoveredRoutes,\n pageCount: discoveredRoutes.filter((r) => r.kind === \"page\").length,\n layoutCount: discoveredRoutes.filter((r) => r.kind === \"layout\").length,\n });\n }\n\n apiRouteManager = new APIRouteManager(appDirs, server, {\n i18n: farmApp.getI18nRuntime(),\n });\n await apiRouteManager.discoverRoutes();\n let discoveredWorkflows: FarmDiscoveredWorkflow[] = [];\n const hasWorkflowDirectory =\n workflowConfig.enabled &&\n workflowConfig.dirs.some((dir) =>\n fs.existsSync(path.isAbsolute(dir) ? dir : path.join(farmConfig.root, dir)),\n );\n if (hasWorkflowDirectory) {\n const { createFarmWorkflowRequestHandler, discoverFarmWorkflows } =\n await loadFarmWorkflowsDevRuntime();\n discoveredWorkflows = await discoverFarmWorkflows(\n { ...farmConfig, workflows: workflowConfig },\n {\n loadModule: async (filePath) =>\n server.ssrLoadModule(filePath) as Promise<Record<string, any>>,\n },\n );\n if (discoveredWorkflows.length > 0) {\n workflowHandler = createFarmWorkflowRequestHandler({\n workflows: discoveredWorkflows,\n config: workflowConfig,\n loadModule: async (workflow: FarmDiscoveredWorkflow) =>\n server.ssrLoadModule(workflow.filePath) as Promise<Record<string, any>>,\n });\n logger.success(`✅ Discovered ${discoveredWorkflows.length} Farm workflow task(s)`);\n }\n }\n if (pm) {\n for (const [, apiRoute] of apiRouteManager.getRoutes()) {\n await pm.runHookParallel(\"apiRouteDiscovered\", {\n path: apiRoute.path,\n filePath: apiRoute.filePath,\n methods: apiRoute.methods,\n });\n }\n }\n\n middlewareManager = new MiddlewareManager(\n appDirs,\n server,\n farmConfig.middleware,\n farmConfig.i18n,\n );\n await middlewareManager.discover();\n if (pm) {\n for (const middleware of middlewareManager.getMiddlewares()) {\n await pm.runHookParallel(\"middlewareDiscovered\", {\n path: middleware.path,\n filePath: middleware.filePath,\n handlerCount: middleware.handlers.length,\n });\n }\n }\n\n // Initialize OpenAPI manager if enabled\n if (options.openapi?.enabled) {\n const { OpenAPIManager } = await loadFarmOpenAPIDevRuntime();\n openAPIManager = new OpenAPIManager(appDirs, options.openapi);\n await openAPIManager.generateSpec();\n logger.success(\"✅ OpenAPI documentation enabled\");\n }\n\n refreshRouteDiscovery = async (reason: string) => {\n await routeManager.discoverRoutes();\n await apiRouteManager.discoverRoutes();\n const manifestModule = server.moduleGraph.getModuleById(\"/@farm/manifest\");\n if (manifestModule) {\n server.moduleGraph.invalidateModule(manifestModule);\n }\n if (openAPIManager) {\n await openAPIManager.invalidateCache();\n }\n if (process.env.FARM_VERBOSE) {\n logger.info(`Refreshed routes: ${reason}`);\n }\n };\n\n const farmDocsHandler = farmDocsDevRuntime\n ? farmDocsDevRuntime.createFarmDocsHandler(farmConfig.docs, {\n root: farmConfig.root,\n srcDir: farmConfig.srcDir,\n clientEntry: \"/@farm/client.js\",\n })\n : null;\n const farmDocsAPIHandler: FarmDocsAPIHandler | null = farmDocsDevRuntime\n ? farmDocsDevRuntime.createFarmDocsAPIHandler({\n rootDir: farmConfig.root,\n srcDir: farmConfig.srcDir,\n docs: farmConfig.docs,\n })\n : null;\n const farmDocsFontAssets = new Map<string, string>(\n farmDocsDevRuntime\n ? [\n [\n \"/assets/Geist-Variable-CrgPqtmy.woff2\",\n path.join(\n farmConfig.root,\n \"node_modules/geist/dist/fonts/geist-sans/Geist-Variable.woff2\",\n ),\n ],\n [\n \"/assets/GeistMono-Variable-BNLlm6Cd.woff2\",\n path.join(\n farmConfig.root,\n \"node_modules/geist/dist/fonts/geist-mono/GeistMono-Variable.woff2\",\n ),\n ],\n ]\n : [],\n );\n\n // Built-in terminal logging (always enabled in development, independent of logger plugin)\n const logRequest = (method: string, urlPath: string, tag: \"API\" | \"PAGE\") => {\n try {\n const pc = require(\"picocolors\");\n const log = [\n pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n pc.dim(\"[\") + pc.bold(pc.cyan(tag)) + pc.dim(\"]\"),\n pc.dim(\"[\") + pc.bold(pc.white(method.padEnd(3))) + pc.dim(\"]\"),\n tag === \"API\" ? pc.gray(\"Requesting \") : pc.gray(\"Loading \"),\n pc.gray(urlPath),\n ].join(\" \");\n console.log(log);\n } catch {\n console.log(`[FARM] [${tag}] [${method}] ${urlPath}`);\n }\n };\n\n const logResponse = (\n method: string,\n urlPath: string,\n status: number,\n duration: number,\n tag: \"API\" | \"PAGE\",\n ) => {\n // In dev, browsers can trigger bursts of identical requests (reload/prefetch).\n // Collapse near-identical page logs to keep terminal output readable.\n const now = Date.now();\n const dedupeKey = `${tag}:${method}:${urlPath}:${status}`;\n const dedupeWindowMs = 250;\n const last = (logResponse as any).__last as { key: string; ts: number } | undefined;\n if (tag === \"PAGE\" && last && last.key === dedupeKey && now - last.ts < dedupeWindowMs) {\n return;\n }\n (logResponse as any).__last = { key: dedupeKey, ts: now };\n\n try {\n const pc = require(\"picocolors\");\n let statusColor = pc.green;\n if (status >= 500) statusColor = pc.red;\n else if (status >= 400) statusColor = pc.yellow;\n else if (status >= 300) statusColor = pc.cyan;\n\n const log = [\n pc.dim(\"[\") + pc.bold(pc.blue(\"FARM\")) + pc.dim(\"]\"),\n pc.dim(\"[\") + pc.bold(pc.cyan(tag)) + pc.dim(\"]\"),\n pc.dim(\"[\") + pc.bold(pc.white(method.padEnd(3))) + pc.dim(\"]\"),\n pc.gray(urlPath),\n pc.dim(\"-\"),\n statusColor(status.toString()),\n pc.dim(`(${duration}ms)`),\n ].join(\" \");\n console.log(log);\n } catch {\n console.log(`[FARM] [${tag}] [${method}] ${urlPath} - ${status} (${duration}ms)`);\n }\n };\n\n // Register middleware directly (not in return function) to ensure it runs early\n server.middlewares.use(\n _withAfterNodeMiddleware(async (req, res, next) => {\n const requestUrl = req.url || \"/\";\n const requestMethod = req.method || \"GET\";\n const fullUrl = `http://${req.headers.host || \"localhost:3000\"}${requestUrl}`;\n const parsedRequestUrl = new URL(fullUrl);\n const requestPathname = parsedRequestUrl.pathname;\n const currentConfig = farmApp?.getConfig() ?? options;\n\n if (imageHandler && requestPathname === farmConfig.images.path) {\n const imageResponse = await imageHandler(\n createRequestFromNodeRequest(req, new URL(fullUrl)),\n );\n if (imageResponse) {\n await sendWebResponse(res, imageResponse);\n return;\n }\n }\n\n const farmDocsFontPath = farmDocsFontAssets.get(requestPathname);\n if (farmDocsFontPath && fs.existsSync(farmDocsFontPath)) {\n res.statusCode = 200;\n res.setHeader(\"Content-Type\", \"font/woff2\");\n res.setHeader(\"Cache-Control\", \"public, max-age=31536000, immutable\");\n fs.createReadStream(farmDocsFontPath).pipe(res);\n return;\n }\n\n if (\n requestMethod === \"GET\" &&\n (requestPathname === FARM_DEVTOOLS_PATH ||\n requestPathname === `${FARM_DEVTOOLS_PATH}.json`)\n ) {\n if (!farmConfig.devtools.enabled) {\n res.statusCode = 404;\n res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.end(\"Farm DevTools are disabled.\");\n return;\n }\n\n if (\n requestPathname === FARM_DEVTOOLS_PATH &&\n parsedRequestUrl.searchParams.get(\"embedded\") !== \"1\"\n ) {\n let launchUrl = new URL(farmConfig.basePath || \"/\", parsedRequestUrl.origin);\n const referrer = req.headers.referer;\n if (referrer) {\n try {\n const referrerUrl = new URL(referrer);\n if (\n referrerUrl.origin === parsedRequestUrl.origin &&\n !referrerUrl.pathname.startsWith(FARM_DEVTOOLS_PATH)\n ) {\n launchUrl = referrerUrl;\n }\n } catch {\n // Ignore malformed referrers and return to the application root.\n }\n }\n launchUrl.searchParams.set(FARM_DEVTOOLS_LAUNCH_PARAM, \"1\");\n res.statusCode = 302;\n res.setHeader(\n \"Location\",\n `${launchUrl.pathname}${launchUrl.search}${launchUrl.hash}`,\n );\n res.setHeader(\"Cache-Control\", \"no-store\");\n res.setHeader(\"Vary\", \"Referer\");\n res.end();\n return;\n }\n\n const { createFarmDevtoolsSnapshot } = await loadFarmDevtoolsSnapshotRuntime();\n const snapshot = await createFarmDevtoolsSnapshot({\n root: farmConfig.root,\n srcDir: farmConfig.srcDir,\n routeManager: farmApp.getRouteManager(),\n apiRouteManager,\n middlewareManager,\n config: {\n ...currentConfig,\n openapi: options.openapi,\n },\n workflows: discoveredWorkflows,\n });\n\n res.statusCode = 200;\n res.setHeader(\n \"Content-Type\",\n requestPathname.endsWith(\".json\")\n ? \"application/json; charset=utf-8\"\n : \"text/html; charset=utf-8\",\n );\n res.setHeader(\"Cache-Control\", \"no-store\");\n if (requestPathname.endsWith(\".json\")) {\n res.end(JSON.stringify(snapshot, null, 2));\n } else {\n const { renderFarmDevtoolsHtml } = await loadFarmDevtoolsUIRuntime();\n res.end(renderFarmDevtoolsHtml(snapshot));\n }\n return;\n }\n\n // Handle OpenAPI docs route\n if (openAPIManager && req.url === options.openapi?.route) {\n const docsHandler = openAPIManager.getDocsRouteHandler();\n return docsHandler(req, res);\n }\n\n const docsHeaders = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n docsHeaders.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n if (farmDocsHandler) {\n const docsResponse = await farmDocsHandler(\n new Request(fullUrl, {\n method: requestMethod,\n headers: docsHeaders,\n }),\n );\n if (docsResponse) {\n await sendWebResponse(res, docsResponse);\n return;\n }\n }\n\n const markdownSourceResponse = await createFarmMarkdownSourceResponse({\n request: new Request(fullUrl, {\n method: requestMethod,\n headers: docsHeaders,\n }),\n config: farmApp.getConfig().mdx,\n resolveSource: async (pathname) => {\n const match = farmApp.getRouteManager().matchRoute(pathname);\n if (!match.route || !isFarmMarkdownPageFile(match.route.modulePath)) {\n return null;\n }\n return {\n source: await fs.promises.readFile(match.route.modulePath, \"utf8\"),\n filePath: match.route.modulePath,\n };\n },\n });\n if (markdownSourceResponse) {\n await sendWebResponse(res, markdownSourceResponse);\n return;\n }\n\n const markdownResponse = await createMarkdownMirrorResponse({\n request: new Request(fullUrl, {\n method: requestMethod,\n headers: docsHeaders,\n }),\n config: farmApp.getConfig().md,\n routeExists: (pathname) =>\n Boolean(farmApp.getRouteManager().matchRoute(pathname).route),\n renderPage: async (request) => fetch(request),\n });\n if (markdownResponse) {\n await sendWebResponse(res, markdownResponse);\n return;\n }\n\n if (\n workflowHandler &&\n (requestPathname === workflowConfig.route ||\n requestPathname.startsWith(`${workflowConfig.route}/`))\n ) {\n let workflowBody: string | undefined;\n if (requestMethod !== \"GET\" && requestMethod !== \"HEAD\") {\n workflowBody = await new Promise<string>((resolve) => {\n let data = \"\";\n req.on(\"data\", (chunk) => {\n data += chunk;\n });\n req.on(\"end\", () => {\n resolve(data);\n });\n });\n }\n const workflowResponse = await workflowHandler(\n new Request(fullUrl, {\n method: requestMethod,\n headers: docsHeaders,\n body: workflowBody || undefined,\n }),\n );\n if (workflowResponse) {\n await sendWebResponse(res, workflowResponse);\n return;\n }\n }\n\n const configuredIntegrations = currentConfig.integrations;\n\n const tryConfiguredIntegrationRoute = async () => {\n const matchedRoute = matchIntegrationRoute(configuredIntegrations, {\n pathname: requestPathname,\n method: requestMethod,\n });\n\n if (!matchedRoute) {\n return false;\n }\n\n const startTime = Date.now();\n\n try {\n if (pm) {\n await pm.runHookParallel(\"beforeRequest\", req, res);\n }\n\n if (res.writableEnded) {\n const duration = Date.now() - startTime;\n logResponse(requestMethod, requestUrl, res.statusCode || 200, duration, \"API\");\n return true;\n }\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n\n let body: string | undefined;\n if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n body = await new Promise<string>((resolve) => {\n let data = \"\";\n req.on(\"data\", (chunk) => {\n data += chunk;\n });\n req.on(\"end\", () => {\n resolve(data);\n });\n });\n }\n\n const integrationRequest = new Request(fullUrl, {\n method: req.method,\n headers,\n body: body || undefined,\n });\n\n const dispatchIntegration = async (request: Request) => {\n const result = await dispatchIntegrationRequest(\n {\n integration: matchedRoute.integration,\n config: currentConfig,\n isDev: true,\n isProd: false,\n },\n request,\n );\n if (!result) {\n throw new Error(`Matched integration route did not return a response`);\n }\n return result;\n };\n const response = pm\n ? await pm.runRuntimeRequest(integrationRequest, dispatchIntegration, {\n kind: \"integration\",\n route: {\n pathname: requestPathname,\n pattern: matchedRoute.route.path,\n },\n })\n : await dispatchIntegration(integrationRequest);\n\n if (!response) {\n return false;\n }\n\n const duration = Date.now() - startTime;\n logResponse(requestMethod, requestUrl, response.status, duration, \"API\");\n\n await sendWebResponse(res, response);\n return true;\n } catch (error) {\n const duration = Date.now() - startTime;\n logResponse(requestMethod, requestUrl, 500, duration, \"API\");\n await emitPluginError(\"integration-handler\", error, {\n pathname: requestPathname,\n routePath: requestUrl,\n method: requestMethod,\n integration: matchedRoute.key,\n });\n logger.error(`Integration route error: ${error}`);\n if (!res.writableEnded) {\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Internal server error\" }));\n }\n return true;\n }\n };\n\n if (await tryConfiguredIntegrationRoute()) {\n return;\n }\n\n const redirectMatch = farmApp.getRouteManager().matchRedirect(requestPathname);\n if (redirectMatch) {\n res.statusCode = redirectMatch.statusCode;\n res.setHeader(\"Location\", redirectMatch.destination);\n res.end(`Redirecting to ${redirectMatch.destination}`);\n return;\n }\n\n // Handle API routes first\n const matchedApiRoute = apiRouteManager.matchRoute(requestPathname);\n const hasMatchedApiRoute = Boolean(matchedApiRoute);\n if (hasMatchedApiRoute || req.url?.startsWith(\"/api/\")) {\n const startTime = Date.now();\n const method = req.method || \"GET\";\n const urlPath = req.url || \"/\";\n const pathname = new URL(urlPath, `http://${req.headers.host || \"localhost:3000\"}`)\n .pathname;\n\n try {\n if (pm) {\n await pm.runHookParallel(\"beforeRequest\", req, res);\n }\n\n if (res.writableEnded) {\n const duration = Date.now() - startTime;\n logResponse(method, urlPath, res.statusCode || 200, duration, \"API\");\n return;\n }\n } catch (error) {\n await emitPluginError(\"before-request\", error, {\n urlPath,\n method,\n });\n logger.error(`Request hook error: ${error}`);\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Internal server error\" }));\n return;\n }\n\n const apiHandler = apiRouteManager.getHandler();\n const hasExplicitAPIRoute =\n hasMatchedApiRoute || Boolean(apiRouteManager.matchRoute(pathname));\n if (apiHandler && hasExplicitAPIRoute) {\n // Log API request\n // logRequest(method, urlPath, \"API\");\n\n try {\n // Convert Node.js request to Web Request\n const url = `http://${req.headers.host || \"localhost:3000\"}${req.url}`;\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n\n // Get body for POST/PUT/PATCH\n let body: string | undefined;\n if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n body = await new Promise<string>((resolve) => {\n let data = \"\";\n req.on(\"data\", (chunk) => {\n data += chunk;\n });\n req.on(\"end\", () => {\n resolve(data);\n });\n });\n }\n\n const request = new Request(url, {\n method: req.method,\n headers,\n body: body || undefined,\n });\n\n const apiLifecyclePayload = {\n pathname: new URL(url).pathname,\n method,\n routePath:\n apiRouteManager.matchRoute(new URL(url).pathname)?.route.path ||\n matchedApiRoute?.route.path ||\n urlPath,\n };\n const invokeAPIHandler = async (runtimeRequest: Request) => {\n const handledRequest: Request = pm\n ? await pm.runHookSerial(\n \"beforeApiHandler\",\n runtimeRequest,\n apiLifecyclePayload,\n )\n : runtimeRequest;\n\n const response = await apiHandler(handledRequest);\n return pm\n ? await pm.runHookSerial(\"afterApiHandler\", response, apiLifecyclePayload)\n : response;\n };\n const handledResponse: Response = pm\n ? await pm.runRuntimeRequest(request, invokeAPIHandler, {\n kind: \"api\",\n route: {\n pathname: apiLifecyclePayload.pathname,\n pattern: apiLifecyclePayload.routePath,\n },\n })\n : await invokeAPIHandler(request);\n\n const duration = Date.now() - startTime;\n logResponse(method, urlPath, handledResponse.status, duration, \"API\");\n\n // Send response\n await sendWebResponse(res, handledResponse);\n return;\n } catch (error) {\n await emitPluginError(\"api-handler\", error, {\n urlPath,\n method,\n });\n logger.error(`API route error: ${error}`);\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Internal server error\" }));\n return;\n }\n }\n\n if (farmDocsAPIHandler && farmDocsDevRuntime?.isFarmDocsAPIRequest(pathname)) {\n try {\n const url = `http://${req.headers.host || \"localhost:3000\"}${req.url}`;\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n\n let body: string | undefined;\n if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n body = await new Promise<string>((resolve) => {\n let data = \"\";\n req.on(\"data\", (chunk) => {\n data += chunk;\n });\n req.on(\"end\", () => {\n resolve(data);\n });\n });\n }\n\n const request = new Request(url, {\n method: req.method,\n headers,\n body: body || undefined,\n });\n\n const apiLifecyclePayload = {\n pathname,\n method,\n routePath: urlPath,\n };\n const invokeDocsAPIHandler = async (runtimeRequest: Request) => {\n const handledRequest: Request = pm\n ? await pm.runHookSerial(\n \"beforeApiHandler\",\n runtimeRequest,\n apiLifecyclePayload,\n )\n : runtimeRequest;\n const response = await farmDocsAPIHandler(handledRequest);\n if (!response) {\n return new Response(null, { status: 404 });\n }\n return pm\n ? await pm.runHookSerial(\"afterApiHandler\", response, apiLifecyclePayload)\n : response;\n };\n const docsResponse = pm\n ? await pm.runRuntimeRequest(request, invokeDocsAPIHandler, {\n kind: \"docs\",\n route: {\n pathname,\n pattern: apiLifecyclePayload.routePath,\n },\n })\n : await invokeDocsAPIHandler(request);\n if (docsResponse) {\n const duration = Date.now() - startTime;\n logResponse(method, urlPath, docsResponse.status, duration, \"API\");\n await sendWebResponse(res, docsResponse);\n return;\n }\n } catch (error) {\n await emitPluginError(\"docs-api-handler\", error, {\n urlPath,\n method,\n });\n logger.error(`Docs API route error: ${error}`);\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Internal server error\" }));\n return;\n }\n }\n\n const duration = Date.now() - startTime;\n logResponse(method, urlPath, 404, duration, \"API\");\n res.statusCode = 404;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"API route not found\", pathname }));\n return;\n }\n\n // Skip internal Vite requests\n if (\n req.url?.startsWith(\"/@\") ||\n req.url?.startsWith(\"/node_modules\") ||\n (requestPathname.includes(\".\") && !requestPathname.endsWith(\".html\"))\n ) {\n return next();\n }\n\n // Handle SPA page-data requests for client-side navigation\n if (req.url?.startsWith(\"/__farm/page-data\")) {\n const urlObj = new URL(req.url, `http://${req.headers.host || \"localhost:3000\"}`);\n const targetPath = urlObj.searchParams.get(\"path\") || \"/\";\n\n try {\n const request = createRequestFromNodeRequest(req, urlObj);\n const deploymentMismatch = getFarmDeploymentMismatch(\n request,\n farmConfig.deploymentId,\n );\n if (deploymentMismatch) {\n await sendWebResponse(\n res,\n createFarmDeploymentMismatchResponse(deploymentMismatch),\n );\n return;\n }\n\n const targetRequestUrl = new URL(targetPath, request.url);\n const targetRequest = new Request(targetRequestUrl, {\n method: \"GET\",\n headers: request.headers,\n });\n await farmApp.getServerRenderer().runWithRequestContext(targetRequest, async () => {\n const routeManager = farmApp.getRouteManager();\n if (pm) {\n await pm.runHookParallel(\"beforeRouteMatch\", {\n pathname: targetPath,\n method: req.method || \"GET\",\n });\n }\n const match = routeManager.matchRoute(targetPath);\n if (pm) {\n await pm.runHookParallel(\"afterRouteMatch\", {\n pathname: targetPath,\n matched: !!match?.route,\n routePattern: match?.route?.pattern || null,\n params: match?.params || {},\n layoutPatterns: (match?.layouts || []).map((l) => l.pattern),\n });\n }\n\n if (!match) {\n res.statusCode = 404;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Route not found\" }));\n return;\n }\n\n const { route, params, layouts } = match;\n\n // Check if route was found\n if (!route) {\n res.statusCode = 404;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(JSON.stringify({ error: \"Route not found\" }));\n return;\n }\n\n // Load route module to get metadata\n const routeModule = await routeManager.loadRouteModule(route.modulePath);\n\n const moduleMetadata = getClientModuleMetadata(\n route.modulePath,\n server.config.root,\n );\n const isClientComponent = moduleMetadata.isClientComponent;\n const shouldHydrate = moduleMetadata.shouldHydrate;\n\n // Collect metadata from layouts and page\n let mergedMetadata: Record<string, any> = {};\n const layoutModules = await Promise.all(\n layouts.map((layout) => routeManager.loadLayoutModule(layout.modulePath)),\n );\n\n for (const layoutModule of layoutModules) {\n if ((layoutModule as any).metadata) {\n mergedMetadata = {\n ...mergedMetadata,\n ...(layoutModule as any).metadata,\n };\n }\n }\n\n if ((routeModule as any).metadata) {\n mergedMetadata = {\n ...mergedMetadata,\n ...(routeModule as any).metadata,\n };\n }\n\n // Build search params\n const targetUrl = new URL(targetPath, \"http://localhost\");\n const searchParams: Record<string, string> = {};\n targetUrl.searchParams.forEach((value, key) => {\n searchParams[key] = value;\n });\n const routeContext = await resolveFarmRouteContext(farmApp.getConfig(), {\n request,\n params,\n search: searchParams,\n path: targetUrl.pathname,\n });\n const routeProps = await parseRouteModuleProps(routeModule as RouteModuleLike, {\n props: withFarmRouteContext(\n {\n params,\n searchParams: Promise.resolve(searchParams),\n path: targetUrl.pathname,\n },\n routeContext,\n ),\n search: searchParams,\n routePath: route.pattern,\n });\n\n // Convert absolute paths to URL paths (relative to project root)\n const projectRoot = server.config.root;\n const toUrlPath = (absolutePath: string) => {\n if (absolutePath.startsWith(projectRoot)) {\n return absolutePath.slice(projectRoot.length);\n }\n return absolutePath;\n };\n\n // Return page data for SPA navigation\n const pageData = {\n props: {\n params: routeProps.params,\n search: (routeProps as any).search,\n searchParams: (routeProps as any).search,\n ...(\"data\" in routeProps ? { data: (routeProps as any).data } : {}),\n ...((routeProps as any).__farmCanonicalPath\n ? {\n __farmCanonicalPath: (routeProps as any).__farmCanonicalPath,\n }\n : {}),\n ...((routeProps as any).__farmRoutePropsResolved\n ? { __farmRoutePropsResolved: true }\n : {}),\n },\n canonicalPath: (routeProps as any).__farmCanonicalPath,\n modulePath: toUrlPath(route.modulePath),\n isClientComponent,\n shouldHydrate,\n metadata: {\n title: mergedMetadata.title,\n description: mergedMetadata.description,\n },\n layoutModules: layouts.map((l) => toUrlPath(l.modulePath)),\n i18n: getFarmI18nClientSnapshot(),\n };\n\n await sendWebResponse(\n res,\n createDeferredDataResponse(\n pageData,\n {\n status: 200,\n headers: {\n \"Cache-Control\": \"private, max-age=0\",\n [FARM_DEPLOYMENT_ID_HEADER]: farmConfig.deploymentId,\n },\n },\n {\n onError(error, id) {\n logger.error(`Deferred route data ${id} failed: ${error}`);\n },\n },\n ),\n );\n return;\n });\n return;\n } catch (error) {\n await emitPluginError(\"page-data\", error, {\n path: targetPath,\n });\n console.error(\"[Farm.js] Page data error:\", error);\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"application/json\");\n res.end(\n JSON.stringify({\n error: \"Failed to load page data\",\n message: error instanceof Error ? error.message : \"Unknown error\",\n }),\n );\n return;\n }\n }\n\n const startTime = Date.now();\n const method = req.method || \"GET\";\n const urlPath = req.url || \"/\";\n const pathname = new URL(urlPath, `http://${req.headers.host || \"localhost:3000\"}`)\n .pathname;\n const routeManager = farmApp.getRouteManager();\n const hasBeforeRouteMatchHook = pm?.hasHook(\"beforeRouteMatch\") ?? false;\n const hasAfterRouteMatchHook = pm?.hasHook(\"afterRouteMatch\") ?? false;\n const hasBeforeRequestHook = pm?.hasHook(\"beforeRequest\") ?? false;\n const hasBeforeRenderHook = pm?.hasHook(\"beforeRender\") ?? false;\n const hasAfterResponseHook = pm?.hasHook(\"afterResponse\") ?? false;\n const hasHTMLTransformHook =\n (pm?.hasHook(\"transformHTML\") ?? false) || (pm?.hasHook(\"afterRender\") ?? false);\n const hasRuntimeRequestHooks = pm?.hasRuntimeRequestHooks() ?? false;\n const hasRuntimeAfterHook = pm?.hasRuntimeHook(\"after\") ?? false;\n\n if (pm && hasBeforeRouteMatchHook) {\n await pm.runHookParallel(\"beforeRouteMatch\", {\n pathname,\n method,\n });\n }\n const routeMatch = routeManager.matchRoute(pathname);\n if (pm && hasAfterRouteMatchHook) {\n await pm.runHookParallel(\"afterRouteMatch\", {\n pathname,\n matched: !!routeMatch?.route,\n routePattern: routeMatch?.route?.pattern || null,\n params: routeMatch?.params || {},\n layoutPatterns: (routeMatch?.layouts || []).map((l) => l.pattern),\n });\n }\n const renderPayload = {\n pathname,\n method,\n routePattern: routeMatch?.route?.pattern || null,\n params: routeMatch?.params || {},\n };\n let runtimeSession: FarmPluginRuntimeSession | undefined;\n if (pm && hasRuntimeRequestHooks) {\n try {\n runtimeSession = await pm.beginRuntimeRequest(\n createRequestFromNodeRequest(req, new URL(fullUrl)),\n {\n kind: \"page\",\n route: {\n pathname,\n pattern: renderPayload.routePattern,\n params: renderPayload.params,\n },\n },\n );\n pm.copyRequestContext(runtimeSession.request, req);\n applyWebRequestToNodeRequest(runtimeSession.request, req);\n\n if (runtimeSession.response) {\n const response = await pm.endRuntimeRequest(\n runtimeSession,\n runtimeSession.response,\n );\n await sendWebResponse(res, response);\n return;\n }\n } catch (error) {\n await emitPluginError(\"runtime-before\", error, { pathname });\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"text/plain; charset=utf-8\");\n res.end(\"Internal Server Error\");\n return;\n }\n }\n\n // logRequest(method, urlPath, \"PAGE\");\n\n try {\n if (middlewareManager?.hasMiddleware()) {\n const middlewareRequest = createRequestFromNodeRequest(req, new URL(fullUrl));\n const handled = await farmApp\n .getServerRenderer()\n .runWithRequestContext(middlewareRequest, () =>\n middlewareManager!.execute(req, res),\n );\n if (handled) {\n if (pm && runtimeSession) {\n pm.copyRequestContext(req, runtimeSession.request);\n await pm.endRuntimeRequest(\n runtimeSession,\n new Response(null, {\n status: res.statusCode || 200,\n headers: createHeadersFromNodeResponse(res),\n }),\n );\n }\n const duration = Date.now() - startTime;\n logResponse(method, urlPath, res.statusCode || 200, duration, \"PAGE\");\n return; // Middleware handled the response\n }\n }\n\n // Run beforeRequest hooks\n if (pm && hasBeforeRequestHook) {\n await pm.runHookParallel(\"beforeRequest\", req, res);\n }\n\n if (res.writableEnded) {\n if (pm && runtimeSession) {\n pm.copyRequestContext(req, runtimeSession.request);\n await pm.endRuntimeRequest(\n runtimeSession,\n new Response(null, {\n status: res.statusCode || 200,\n headers: createHeadersFromNodeResponse(res),\n }),\n );\n }\n // Log response if already ended\n const duration = Date.now() - startTime;\n logResponse(method, urlPath, res.statusCode || 200, duration, \"PAGE\");\n return;\n }\n\n // Only intercept streamed output when an installed plugin can\n // observe or replace the response. The default dev path can write\n // directly to Node without buffering and replaying the whole HTML.\n const shouldInterceptResponse = Boolean(\n pm &&\n (hasAfterResponseHook ||\n hasHTMLTransformHook ||\n (runtimeSession && hasRuntimeAfterHook)),\n );\n if (pm && shouldInterceptResponse) {\n const originalWrite = res.write.bind(res);\n const originalEnd = res.end.bind(res);\n let afterResponseCalled = false;\n const htmlChunks: Buffer[] = [];\n let didStreamHtml = false;\n const bufferPluginResponse = Boolean(\n hasHTMLTransformHook || (runtimeSession && hasRuntimeAfterHook),\n );\n\n res.write = ((chunk: any, ...args: any[]) => {\n const contentTypeHeader =\n res.getHeader(\"content-type\") || res.getHeader(\"Content-Type\");\n const contentType = typeof contentTypeHeader === \"string\" ? contentTypeHeader : \"\";\n const isHtmlResponse = contentType.includes(\"text/html\");\n\n if (isHtmlResponse && chunk !== undefined && chunk !== null) {\n const bufferChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));\n htmlChunks.push(bufferChunk);\n didStreamHtml = true;\n if (bufferPluginResponse) {\n const callback = args.find((arg) => typeof arg === \"function\");\n callback?.();\n return true;\n }\n const writeResult = originalWrite(chunk, ...args);\n if (typeof (res as any).flush === \"function\") {\n (res as any).flush();\n }\n return writeResult;\n }\n\n return originalWrite(chunk, ...args);\n }) as any;\n\n res.end = ((...args: any[]) => {\n if (!afterResponseCalled && pm) {\n afterResponseCalled = true;\n const duration = Date.now() - startTime;\n logResponse(method, urlPath, res.statusCode || 200, duration, \"PAGE\");\n const originalEndArgs = [...args];\n Promise.resolve()\n .then(async () => {\n const contentTypeHeader =\n res.getHeader(\"content-type\") || res.getHeader(\"Content-Type\");\n const contentType =\n typeof contentTypeHeader === \"string\" ? contentTypeHeader : \"\";\n const isHtmlResponse = contentType.includes(\"text/html\");\n if (isHtmlResponse) {\n const firstArg = args[0];\n if (typeof firstArg === \"string\" || Buffer.isBuffer(firstArg)) {\n const bufferChunk = Buffer.isBuffer(firstArg)\n ? firstArg\n : Buffer.from(firstArg, \"utf-8\");\n htmlChunks.push(bufferChunk);\n }\n\n const fullHtml = Buffer.concat(htmlChunks).toString(\"utf-8\");\n let html = fullHtml;\n if (!didStreamHtml || bufferPluginResponse) {\n html = await pm.runHookSerial(\"transformHTML\", html);\n html = await pm.runHookSerial(\"afterRender\", html, renderPayload);\n const callback =\n typeof originalEndArgs[originalEndArgs.length - 1] === \"function\"\n ? originalEndArgs[originalEndArgs.length - 1]\n : undefined;\n originalEndArgs.length = 0;\n originalEndArgs.push(html);\n if (callback) originalEndArgs.push(callback);\n } else {\n await pm.runHookSerial(\"transformHTML\", fullHtml);\n await pm.runHookSerial(\"afterRender\", fullHtml, renderPayload);\n }\n }\n\n if (runtimeSession) {\n pm.copyRequestContext(req, runtimeSession.request);\n const status = res.statusCode || 200;\n const canHaveBody =\n method !== \"HEAD\" && status !== 204 && status !== 205 && status !== 304;\n const firstArg = originalEndArgs[0];\n const responseBody = canHaveBody\n ? isHtmlResponse\n ? didStreamHtml && !bufferPluginResponse\n ? Buffer.concat(htmlChunks)\n : typeof firstArg === \"string\" || Buffer.isBuffer(firstArg)\n ? firstArg\n : undefined\n : typeof firstArg === \"string\" || Buffer.isBuffer(firstArg)\n ? firstArg\n : undefined\n : null;\n const runtimeResponse = await pm.endRuntimeRequest(\n runtimeSession,\n new Response(\n Buffer.isBuffer(responseBody)\n ? responseBody.toString(\"utf8\")\n : responseBody,\n {\n status,\n headers: createHeadersFromNodeResponse(res),\n },\n ),\n );\n applyWebResponseToNodeResponse(runtimeResponse, res);\n\n if (!didStreamHtml || bufferPluginResponse) {\n const callback =\n typeof originalEndArgs[originalEndArgs.length - 1] === \"function\"\n ? originalEndArgs[originalEndArgs.length - 1]\n : undefined;\n const body = runtimeResponse.body\n ? Buffer.from(await runtimeResponse.arrayBuffer())\n : undefined;\n originalEndArgs.length = 0;\n if (body) originalEndArgs.push(body);\n if (callback) originalEndArgs.push(callback);\n }\n }\n })\n .then(() =>\n hasAfterResponseHook\n ? pm.runHookParallel(\"afterResponse\", req, res)\n : undefined,\n )\n .then(() => {\n originalEnd(...originalEndArgs);\n })\n .catch((err) => {\n emitPluginError(\"response-end\", err, { pathname }).catch(() => {});\n console.error(\"Error in afterResponse hook:\", err);\n originalEnd(...originalEndArgs);\n });\n } else {\n originalEnd(...args);\n }\n }) as any;\n }\n\n // Note: __FARM_PROPS__ is set by the renderer with actual page props (params, searchParams)\n\n const renderer = farmApp.getServerRenderer();\n if (pm && hasBeforeRenderHook) {\n await pm.runHookParallel(\"beforeRender\", renderPayload);\n }\n await renderer.renderPage(req as any, res as any);\n if (!shouldInterceptResponse) {\n logResponse(method, urlPath, res.statusCode || 200, Date.now() - startTime, \"PAGE\");\n }\n } catch (error) {\n // Log error response\n const duration = Date.now() - startTime;\n logResponse(method, urlPath, 500, duration, \"PAGE\");\n if (pm && runtimeSession) {\n await pm.failRuntimeRequest(runtimeSession, error);\n }\n await emitPluginError(\"render-page\", error, { pathname });\n next(error);\n }\n }),\n );\n },\n\n async resolveId(id, importer, resolveOptions) {\n if (typeof imageImports.resolveId === \"function\") {\n const imageId = await imageImports.resolveId.call(this, id, importer, resolveOptions);\n if (imageId) return imageId;\n }\n\n if (parseProgrammaticRouteModuleId(id)) {\n return id;\n }\n\n if (id === \"/@farm/client\" || id === \"/@farm/client.js\") {\n return id;\n }\n\n if (id === \"/@farm/server\") {\n return id;\n }\n\n // Virtual manifest module - TanStack Start pattern\n if (id === \"virtual:farm-manifest\" || id === \"/@farm/manifest\") {\n return \"/@farm/manifest\";\n }\n },\n\n async load(id) {\n if (typeof imageImports.load === \"function\") {\n const imageModule = await imageImports.load.call(this, id);\n if (imageModule) return imageModule;\n }\n\n if (parseProgrammaticRouteModuleId(id)) {\n return generateProgrammaticRouteModule(id, server?.config.root || options.root);\n }\n\n if (id === \"/@farm/client\" || id === \"/@farm/client.js\") {\n const resolvedConfig = farmApp?.getConfig();\n const integrations = resolvedConfig?.integrations || options.integrations;\n const root = resolvedConfig?.root || server?.config.root || process.cwd();\n const docs = resolvedConfig?.docs;\n const devtools = resolvedConfig?.devtools ?? resolveFarmDevtoolsConfig(false, \"production\");\n const [docsRuntime, docsSearchRuntime, devtoolsClientRuntime] = await Promise.all([\n docs?.enabled ? loadFarmDocsDevRuntime() : null,\n docs?.enabled ? loadFarmDocsSearchDevRuntime() : null,\n devtools.enabled ? loadFarmDevtoolsClientRuntime() : null,\n ]);\n const docsSearchEnabled = docsSearchRuntime?.isFarmDocsSearchEnabled(docs) ?? false;\n const generatedDocsSearchRuntime = docsSearchRuntime\n ? docsSearchRuntime.generateFarmDocsSearchClientRuntime(\n docsSearchEnabled,\n docsSearchEnabled\n ? docsSearchRuntime.resolveFarmDocsSearchClientModule(root)\n : undefined,\n )\n : EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME;\n const generatedDevtoolsClientRuntime = devtoolsClientRuntime\n ? devtoolsClientRuntime.generateFarmDevtoolsClientRuntime(devtools)\n : \"\";\n\n return generateClientCode(\n getIntegrationProviders(integrations),\n [\n ...getIntegrationDocumentNavigationMatchers(integrations),\n ...(docsRuntime?.getFarmDocsDocumentNavigationMatchers(docs) ?? []),\n ],\n generatedDocsSearchRuntime,\n generatedDevtoolsClientRuntime,\n resolvedConfig?.plugins || [],\n root,\n );\n }\n\n if (id === \"/@farm/server\") {\n return generateServerCode();\n }\n\n // Virtual manifest module - TanStack Start pattern\n // Manifest is generated at build time and inlined\n if (id === \"/@farm/manifest\") {\n const routeManager = farmApp?.getRouteManager();\n if (!routeManager) {\n return `\nexport const getManifest = () => ({\n routes: {},\n layouts: {},\n clientEntry: \"/@farm/client.js\",\n sharedAssets: []\n});\n`;\n }\n\n const manifest = routeManager.generateClientManifest(server.config.root);\n\n // Convert to full manifest format\n const fullManifest = {\n clientEntry: \"/@farm/client.js\",\n routes: {} as Record<string, any>,\n layouts: {} as Record<string, any>,\n sharedAssets: [\n {\n tag: \"link\",\n attrs: { rel: \"stylesheet\", href: \"/src/app/globals.css\" },\n },\n ],\n };\n\n // Convert routes array to object keyed by pattern\n for (const route of manifest.routes) {\n const moduleMetadata = getClientModuleMetadata(route.modulePath, server.config.root);\n\n fullManifest.routes[route.pattern] = {\n modulePath: route.modulePath,\n pattern: route.pattern,\n segments: route.segments,\n search: route.search,\n isClientComponent: moduleMetadata.isClientComponent,\n shouldHydrate: moduleMetadata.shouldHydrate,\n preloads: [route.modulePath], // In dev, preload is just the module\n assets: [],\n };\n }\n\n // Convert layouts array to object keyed by pattern\n for (const layout of manifest.layouts) {\n fullManifest.layouts[layout.pattern] = {\n modulePath: layout.modulePath,\n pattern: layout.pattern,\n preloads: [layout.modulePath],\n assets: [],\n };\n }\n\n return `\n// Auto-generated manifest for SPA navigation (TanStack Start pattern)\n// This manifest is inlined in the server bundle - no file on disk\n// Client receives this via window.__FARM_MANIFEST__ in HTML\nexport const getManifest = () => (${JSON.stringify(fullManifest, null, 2)});\nexport const manifest = getManifest();\n`;\n }\n },\n\n async transform(code, id, transformOptions) {\n if (typeof imageImports.transform === \"function\") {\n const imageModule = await imageImports.transform.call(this, code, id, transformOptions);\n if (imageModule) return imageModule;\n }\n\n let transformedCode = code;\n let transformed = false;\n\n if (transformOptions?.ssr && server) {\n const rewrittenImports = rewriteEarlySsrRelativeImports({\n code: transformedCode,\n id,\n root: server.config.root,\n parse: (source) => this.parse(source) as unknown as FarmModuleAstNode,\n });\n if (rewrittenImports) {\n transformedCode = rewrittenImports;\n transformed = true;\n }\n }\n\n if (hasUseClientDirective(transformedCode)) {\n const moduleInfo = this.getModuleInfo(id);\n if (moduleInfo) {\n (moduleInfo as any).isClientComponent = true;\n }\n\n transformedCode = stripUseClientDirective(transformedCode);\n transformed = true;\n\n // Store client component for later injection\n if (!farmApp) {\n return {\n code: transformedCode,\n map: null,\n };\n }\n\n const clientComponents = (farmApp as any).__clientComponents__ || new Set();\n clientComponents.add(id);\n (farmApp as any).__clientComponents__ = clientComponents;\n\n // Add HMR support for client components\n // This ensures React re-renders when the component updates\n const hmrCode = `\nif (import.meta.hot) {\n import.meta.hot.accept((newModule) => {\n if (newModule && newModule.default && window.__FARM_REACT_ROOT__) {\n // Re-render with the new component\n const React = window.__FARM_REACT__;\n const props = window.__FARM_PROPS__ || {};\n const nextElement = React.createElement(newModule.default, props);\n const wrapProviders = window.__FARM_WRAP_PROVIDERS__;\n Promise.resolve(\n typeof wrapProviders === 'function' ? wrapProviders(nextElement) : nextElement\n ).then((wrappedElement) => {\n window.__FARM_REACT_ROOT__.render(wrappedElement);\n console.log('[Farm.js] ⚡ HMR update applied');\n });\n }\n });\n}\n`;\n return {\n code: transformedCode + \"\\n\" + hmrCode,\n map: null,\n };\n }\n\n return transformed ? { code: transformedCode, map: null } : null;\n },\n\n generateBundle(options, bundle) {\n const clientManifest = generateClientManifest(bundle);\n this.emitFile({\n type: \"asset\",\n fileName: \"farm-client-manifest.json\",\n source: JSON.stringify(clientManifest, null, 2),\n });\n },\n\n async closeBundle() {\n // SSG: Pre-render static pages at build time\n if (!farmApp) return;\n\n try {\n const routeManager = farmApp.getRouteManager();\n if (!routeManager) return;\n\n const { ssg: ssgPages, ssr: ssrRoutes } = await routeManager.collectSSGPages();\n\n if (ssgPages.length === 0) {\n logger.info(\"No SSG pages found - all pages will use SSR\");\n return;\n }\n\n logger.info(`Found ${ssgPages.length} SSG pages, ${ssrRoutes.length} SSR routes`);\n logger.info(\"Pre-rendering SSG pages...\");\n\n const outDir = path.join(server?.config.root || process.cwd(), options.outDir || \"dist\");\n const clientDir = path.join(outDir, \"client\");\n\n // Pre-render each SSG page\n for (const page of ssgPages) {\n try {\n const staticRequest = new Request(new URL(page.urlPath, \"http://farm.static\"));\n await farmApp.getServerRenderer().runWithRequestContext(staticRequest, async () => {\n // Load the route module\n const mod = await routeManager.loadRouteModule(page.filePath);\n if (!mod?.default) return;\n\n // Find matching layouts\n const { layouts } = routeManager.matchRoute(page.urlPath);\n const layoutModules = await Promise.all(\n layouts.map((l) => routeManager.loadLayoutModule(l.modulePath)),\n );\n\n // Render the page\n const React = await import(\"react\");\n const { renderToString } = await import(\"react-dom/server\");\n\n const PageComponent = mod.default;\n const pageProps = {\n params: page.params,\n searchParams: Promise.resolve({}),\n path: page.urlPath,\n };\n\n let pageElement = React.createElement(\n PageComponent as React.ComponentType<unknown>,\n pageProps as React.Attributes,\n );\n\n // Wrap with layouts\n for (let i = layoutModules.length - 1; i >= 0; i--) {\n const layoutModule = layoutModules[i];\n const LayoutComponent = layoutModule.default;\n pageElement = React.createElement(\n LayoutComponent as React.ComponentType<unknown>,\n {\n children: pageElement,\n params: page.params,\n } as React.Attributes,\n );\n }\n\n const html = renderToString(pageElement);\n\n // Generate full HTML with proper structure\n const i18nSnapshot = getFarmI18nClientSnapshot();\n const i18nHead = renderFarmI18nStaticHead(page.urlPath, i18nSnapshot);\n const fullHtml = `<!DOCTYPE html>\n<html lang=\"${escapeFarmHtmlAttribute(i18nSnapshot?.locale || \"en\")}\"${\n i18nSnapshot ? ` dir=\"${i18nSnapshot.direction}\"` : \"\"\n }>\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"icon\" href=\"data:,\">\n <link rel=\"stylesheet\" href=\"/assets/globals.css\">\n ${page.revalidate ? `<meta name=\"x-farm-revalidate\" content=\"${page.revalidate}\">` : \"\"}\n ${i18nHead}\n</head>\n<body>\n <div id=\"root\">${html}</div>\n <script type=\"module\" src=\"/assets/client.js\"></script>\n</body>\n</html>`;\n\n // Write to output directory\n const outputPath =\n page.urlPath === \"/\"\n ? path.join(clientDir, \"index.html\")\n : path.join(clientDir, page.urlPath + \".html\");\n\n fs.mkdirSync(path.dirname(outputPath), { recursive: true });\n fs.writeFileSync(outputPath, fullHtml);\n\n const revalidateInfo = page.revalidate ? ` (revalidate: ${page.revalidate}s)` : \"\";\n logger.success(` ✓ ${page.urlPath}${revalidateInfo}`);\n });\n } catch (error) {\n logger.error(` ✗ ${page.urlPath}: ${error}`);\n }\n }\n\n // Write SSG manifest for server to know which pages are pre-rendered\n const manifestPath = path.join(outDir, \"__ssg_manifest.json\");\n fs.writeFileSync(\n manifestPath,\n JSON.stringify(\n ssgPages.map((p) => ({\n urlPath: p.urlPath,\n params: p.params,\n revalidate: p.revalidate,\n })),\n null,\n 2,\n ),\n );\n\n logger.success(`SSG complete: ${ssgPages.length} pages pre-rendered`);\n } catch (error) {\n logger.error(`SSG build failed: ${error}`);\n }\n },\n\n async handleHotUpdate(ctx: HmrContext) {\n const { file, server, modules } = ctx;\n if (initialPluginManager) {\n try {\n await initialPluginManager.runHookParallel(\"hmrUpdate\", {\n file,\n modules: modules.map((m) => m.id || m.url || \"\").filter(Boolean),\n });\n } catch (error) {\n await initialPluginManager.runHookParallel(\"onError\", {\n phase: \"hmrUpdate\",\n error,\n meta: { file },\n });\n }\n }\n\n const currentFarmConfig = farmApp?.getConfig();\n const normalizedFile = file.replace(/\\\\/g, \"/\");\n const currentSrcRoot = currentFarmConfig\n ? getFarmSourceRoots(currentFarmConfig)\n .map((source) => path.join(source.root, source.srcDir).replace(/\\\\/g, \"/\"))\n .find((sourceRoot) => normalizedFile.startsWith(`${sourceRoot}/`)) || null\n : null;\n if (\n currentSrcRoot &&\n normalizedFile.startsWith(`${currentSrcRoot}/`) &&\n isProgrammaticRoutesFileName(normalizedFile)\n ) {\n logUpdate(\"PAGE\", `updated ${path.basename(file)}`);\n\n for (const mod of modules) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n await refreshRouteDiscovery?.(`updated ${file}`);\n\n server.ws.send({\n type: \"full-reload\",\n path: \"*\",\n });\n\n return [];\n }\n\n if (\n currentSrcRoot &&\n isPotentialProgrammaticRouteSourceFile(normalizedFile, currentSrcRoot) &&\n fileContainsProgrammaticPageRoute(file)\n ) {\n const shortPath = normalizedFile.slice(currentSrcRoot.length + 1);\n logUpdate(\"PAGE\", `updated ${shortPath}`);\n\n for (const mod of modules) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n await refreshRouteDiscovery?.(`updated ${file}`);\n\n server.ws.send({\n type: \"full-reload\",\n path: \"*\",\n });\n\n return [];\n }\n\n if (file.includes(\"/app/\")) {\n // Hot reload middleware changes\n if (file.includes(\"middleware.\")) {\n if (middlewareManager) {\n await middlewareManager.reload();\n logger.success(\"✅ Middleware reloaded!\");\n if (initialPluginManager) {\n for (const middleware of middlewareManager.getMiddlewares()) {\n await initialPluginManager.runHookParallel(\"middlewareDiscovered\", {\n path: middleware.path,\n filePath: middleware.filePath,\n handlerCount: middleware.handlers.length,\n });\n }\n }\n }\n\n return [];\n }\n\n if (file.includes(\"page.\") || file.includes(\"layout.\")) {\n const shortPath = file.split(\"/app/\")[1] || file;\n logUpdate(\"PAGE\", `updated ${shortPath}`);\n\n for (const mod of modules) {\n server.moduleGraph.invalidateModule(mod);\n }\n\n server.ws.send({\n type: \"full-reload\",\n path: \"*\",\n });\n\n return [];\n }\n }\n\n return modules;\n },\n };\n}\n\nfunction generateProgrammaticRouteModule(moduleId: string, root?: string): string {\n const parsed = parseProgrammaticRouteModuleId(moduleId);\n if (!parsed) {\n return \"\";\n }\n\n const routeFile = toProgrammaticRouteImportSpecifier(parsed.filePath, root);\n\n if (parsed.kind === \"api\") {\n return generateProgrammaticApiRouteModule(parsed.routePath, routeFile);\n }\n\n return `\nimport { createElement as __farmCreateElement } from \"react\";\nimport {\n createLayoutModuleFromProgrammaticLayout as __farmCreateLayoutRouteModule,\n createRouteModuleFromProgrammaticPage as __farmCreatePageRouteModule,\n} from \"@farm.js/core/routes\";\nimport * as __farmRoutesModule from ${JSON.stringify(routeFile)};\n\nconst __farmIsRouteDefinition = (value) => (\n value &&\n typeof value === \"object\" &&\n (\n value.kind === \"page\" ||\n value.kind === \"layout\" ||\n value.kind === \"api\" ||\n value.kind === \"redirect\"\n )\n);\nconst __farmRouteListFromCandidate = (candidate) => {\n if (Array.isArray(candidate)) return candidate;\n if (Array.isArray(candidate?.routes)) return candidate.routes;\n if (__farmIsRouteDefinition(candidate)) return [candidate];\n return [];\n};\nconst __farmGetRouteExport = (name) => Reflect.get(__farmRoutesModule, name);\nconst __farmRouteCandidates = [\n __farmGetRouteExport(\"default\"),\n __farmGetRouteExport(\"routes\"),\n __farmGetRouteExport(\"Route\"),\n];\nlet __farmRoutes = [];\nfor (const __farmCandidate of __farmRouteCandidates) {\n __farmRoutes = __farmRouteListFromCandidate(__farmCandidate);\n if (__farmRoutes.length > 0) break;\n}\n\nif (__farmRoutes.length === 0) {\n __farmRoutes = Object.values(__farmRoutesModule).filter(__farmIsRouteDefinition);\n}\nconst __farmNormalizeRoutePath = (routePath) => {\n const withSlash = routePath && routePath.startsWith(\"/\") ? routePath : \"/\" + (routePath || \"\");\n const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\\\\/+$/, \"\") : withSlash;\n return withoutTrailing || \"/\";\n};\nconst __farmRoute = __farmRoutes.find((route) => (\n route &&\n route.kind === ${JSON.stringify(parsed.kind)} &&\n __farmNormalizeRoutePath(route.path) === ${JSON.stringify(parsed.routePath)}\n));\n\nif (!__farmRoute) {\n throw new Error(${JSON.stringify(\n `Programmatic ${parsed.kind} route \"${parsed.routePath}\" was not found in ${routeFile}.`,\n )});\n}\n\nconst __farmRouteModule = __farmRoute.kind === \"layout\"\n ? __farmCreateLayoutRouteModule(__farmRoute)\n : __farmCreatePageRouteModule(__farmRoute);\n\nexport const metadata = __farmRouteModule.metadata;\nexport const generateMetadata = __farmRouteModule.generateMetadata;\nconst __farmIsSearchSchema = (value) => value && typeof value.parse === \"function\";\nconst __farmGetSearchSchema = (search) => __farmIsSearchSchema(search) ? search : search?.schema;\nconst __farmGetSearchOptions = (search) => __farmIsSearchSchema(search) ? undefined : search;\nconst __farmSearchSchema = __farmGetSearchSchema(__farmRoute.search);\nconst __farmSearchOptions = __farmGetSearchOptions(__farmRoute.search);\nexport const __farmRouteSchemas = __farmRouteModule.__farmRouteSchemas;\nexport const __farmRouteSearch = __farmRouteModule.__farmRouteSearch;\nexport const __farmRouteData = __farmRouteModule.__farmRouteData;\nexport const __farmRouteGuard = __farmRouteModule.__farmRouteGuard;\nexport const __farmRouteParsesProps = __farmRouteModule.__farmRouteParsesProps;\nexport const __farmRouteComponents = __farmRouteModule.__farmRouteComponents;\nexport const __farmResolveRouteCanonicalPath =\n __farmRouteModule.__farmResolveRouteCanonicalPath;\nexport const ssg = __farmRouteModule.ssg;\nexport const dynamic = __farmRouteModule.dynamic;\nexport const revalidate = __farmRouteModule.revalidate;\nexport const ppr = __farmRouteModule.ppr;\nexport const getStaticPaths = __farmRouteModule.getStaticPaths;\n\nconst __farmParseSchema = (schema, value, label) => {\n if (!schema || typeof schema.parse !== \"function\") {\n return value;\n }\n\n try {\n return schema.parse(value);\n } catch (error) {\n throw new Error(\"Invalid \" + label + \" for route \" + JSON.stringify(__farmRoute.path) + \": \" + (error?.message || String(error)));\n }\n};\n\nconst __farmMarkRoutePropsResolved = (props) => ({\n ...props,\n __farmRoutePropsResolved: true,\n});\n\nconst __farmAddCanonicalPath = (props, canonicalPath) => (\n canonicalPath ? { ...props, __farmCanonicalPath: canonicalPath } : props\n);\n\nconst __farmStripRoutePropsMarker = (props) => {\n if (!props || props.__farmRoutePropsResolved !== true) {\n return props;\n }\n\n const {\n __farmRoutePropsResolved,\n __farmCanonicalPath,\n __farmRoutePropsPromise,\n ...componentProps\n } = props;\n return componentProps;\n};\n\nconst __farmCreateSearchParams = (value) => {\n const params = new URLSearchParams();\n for (const [key, item] of Object.entries(value || {})) {\n if (item == null) continue;\n const values = Array.isArray(item) ? item : [item];\n for (const entry of values) {\n if (entry != null) params.append(key, String(entry));\n }\n }\n return params;\n};\n\nconst __farmComparable = (value) => {\n if (Array.isArray(value)) return value.map(__farmComparable);\n if (value && typeof value === \"object\") {\n return Object.keys(value).sort().reduce((output, key) => {\n output[key] = __farmComparable(value[key]);\n return output;\n }, {});\n }\n return value;\n};\n\nconst __farmEqual = (left, right) => (\n JSON.stringify(__farmComparable(left)) === JSON.stringify(__farmComparable(right))\n);\n\nconst __farmReadSearchValue = (value, key) => (\n value && typeof value === \"object\" ? value[key] : undefined\n);\n\nconst __farmParseDefaultSearch = () => {\n if (!__farmSearchSchema) return undefined;\n try {\n const value = __farmSearchSchema.parse({});\n return value && typeof value === \"object\" ? value : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst __farmResolveCanonicalPath = (rawSearch, parsedSearch, path) => {\n if (!__farmSearchOptions?.temporary?.length && !__farmSearchOptions?.stripDefaults) {\n return undefined;\n }\n\n const params = __farmCreateSearchParams(rawSearch);\n const original = params.toString();\n\n for (const key of __farmSearchOptions.temporary || []) {\n params.delete(key);\n }\n\n if (__farmSearchOptions.stripDefaults) {\n const defaults = __farmParseDefaultSearch();\n if (defaults) {\n const keys = __farmSearchOptions.stripDefaults === true\n ? Array.from(new Set(Array.from(params.keys())))\n : [...__farmSearchOptions.stripDefaults];\n for (const key of keys) {\n if (params.has(key) && __farmEqual(__farmReadSearchValue(parsedSearch, key), __farmReadSearchValue(defaults, key))) {\n params.delete(key);\n }\n }\n }\n }\n\n const next = params.toString();\n if (next === original) return undefined;\n return next ? path + \"?\" + next : path;\n};\n\nexport async function __farmResolveRouteProps(props) {\n return typeof __farmRouteModule.__farmResolveRouteProps === \"function\"\n ? __farmRouteModule.__farmResolveRouteProps(props)\n : props;\n}\n\nconst __farmNeedsPageWrapper = __farmRoute.kind === \"page\" && !!(\n __farmRoute.params ||\n __farmRoute.search ||\n __farmRoute.data\n);\n\nasync function __farmProgrammaticPage(props) {\n const deferredRouteProps = props?.__farmRoutePropsPromise;\n const resolvedProps = props?.__farmRoutePropsResolved === true\n ? props\n : deferredRouteProps && typeof deferredRouteProps.then === \"function\"\n ? await deferredRouteProps\n : await __farmResolveRouteProps(props);\n\n return __farmCreateElement(\n __farmRoute.component,\n __farmStripRoutePropsMarker(resolvedProps)\n );\n}\n\nexport default __farmRouteModule.default;\n`;\n}\n\nfunction generateProgrammaticApiRouteModule(routePath: string, routeFile: string): string {\n return `\nimport * as __farmRoutesModule from ${JSON.stringify(routeFile)};\n\nconst __farmIsRouteDefinition = (value) => (\n value && typeof value === \"object\" && (\n value.kind === \"page\" ||\n value.kind === \"layout\" ||\n value.kind === \"api\" ||\n value.kind === \"redirect\"\n )\n);\nconst __farmRouteListFromCandidate = (candidate) => {\n if (Array.isArray(candidate)) return candidate;\n if (Array.isArray(candidate?.routes)) return candidate.routes;\n if (__farmIsRouteDefinition(candidate)) return [candidate];\n return [];\n};\nconst __farmGetRouteExport = (name) => Reflect.get(__farmRoutesModule, name);\nconst __farmRouteCandidates = [\n __farmGetRouteExport(\"default\"),\n __farmGetRouteExport(\"routes\"),\n __farmGetRouteExport(\"Route\"),\n];\nlet __farmRoutes = [];\nfor (const __farmCandidate of __farmRouteCandidates) {\n __farmRoutes = __farmRouteListFromCandidate(__farmCandidate);\n if (__farmRoutes.length > 0) break;\n}\nif (__farmRoutes.length === 0) {\n __farmRoutes = Object.values(__farmRoutesModule).filter(__farmIsRouteDefinition);\n}\nconst __farmNormalizeRoutePath = (value) => {\n const withSlash = value && value.startsWith(\"/\") ? value : \"/\" + (value || \"\");\n return withSlash.length > 1 ? withSlash.replace(/\\\\/+$/, \"\") : withSlash;\n};\nconst __farmRoute = __farmRoutes.find((route) => (\n route?.kind === \"api\" &&\n __farmNormalizeRoutePath(route.path) === ${JSON.stringify(routePath)}\n));\n\nif (!__farmRoute) {\n throw new Error(${JSON.stringify(\n `Programmatic api route \"${routePath}\" was not found in ${routeFile}.`,\n )});\n}\n\nexport const GET = __farmRoute.methods.GET;\nexport const HEAD = __farmRoute.methods.HEAD;\nexport const POST = __farmRoute.methods.POST;\nexport const PUT = __farmRoute.methods.PUT;\nexport const DELETE = __farmRoute.methods.DELETE;\nexport const PATCH = __farmRoute.methods.PATCH;\nexport const OPTIONS = __farmRoute.methods.OPTIONS;\n`.trim();\n}\n\nfunction toProgrammaticRouteImportSpecifier(filePath: string, root?: string): string {\n if (root && filePath.startsWith(root)) {\n return filePath.slice(root.length) || \"/\";\n }\n\n return filePath;\n}\n\ntype RouteModuleLike = {\n __farmRouteParsesProps?: boolean;\n __farmResolveRouteProps?: (props: {\n params: Record<string, string>;\n searchParams: Promise<Record<string, string | string[] | undefined>>;\n path: string;\n [key: string]: unknown;\n }) => Promise<Record<string, unknown>>;\n __farmRouteSchemas?: {\n params?: { parse?: (value: unknown) => unknown };\n search?: { parse?: (value: unknown) => unknown };\n };\n};\n\nasync function parseRouteModuleProps(\n routeModule: RouteModuleLike,\n input: {\n props: {\n params: Record<string, string>;\n searchParams: Promise<Record<string, string | string[] | undefined>>;\n path: string;\n [key: string]: unknown;\n };\n search: Record<string, string | string[] | undefined>;\n routePath: string;\n },\n): Promise<Record<string, unknown>> {\n if (typeof routeModule.__farmResolveRouteProps === \"function\") {\n return await routeModule.__farmResolveRouteProps(input.props);\n }\n\n if (routeModule.__farmRouteParsesProps) {\n return {\n ...input.props,\n search: input.search,\n };\n }\n\n const schemas = routeModule.__farmRouteSchemas;\n const params = parseRouteModuleSchema(\n schemas?.params,\n input.props.params,\n \"params\",\n input.routePath,\n );\n const search = parseRouteModuleSchema(schemas?.search, input.search, \"search\", input.routePath);\n\n return {\n ...input.props,\n params,\n search,\n searchParams: Promise.resolve(search as Record<string, string | string[] | undefined>),\n };\n}\n\nfunction parseRouteModuleSchema(\n schema: { parse?: (value: unknown) => unknown } | undefined,\n value: unknown,\n label: string,\n routePath: string,\n): unknown {\n if (!schema || typeof schema.parse !== \"function\") {\n return value;\n }\n\n try {\n return schema.parse(value);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid ${label} for route \"${routePath}\": ${message}`);\n }\n}\n\nfunction generateClientCode(\n integrationProviders: Array<{\n name: string;\n type: string;\n props?: Record<string, unknown>;\n }> = [],\n documentNavigationMatchers: string[] = [],\n docsSearchClientRuntime = EMPTY_FARM_DOCS_SEARCH_CLIENT_RUNTIME,\n devtoolsClientRuntime = \"\",\n plugins: readonly FarmPlugin[] = [],\n root = process.cwd(),\n): string {\n const hasClerkProvider = integrationProviders.some((provider) => provider.type === \"clerk\");\n const providerImportBlock = hasClerkProvider\n ? `import { ClerkProvider } from '@clerk/react';`\n : \"\";\n const clientPluginEntry = generateFarmClientPluginEntryCode(plugins, root);\n\n return `\nimport React from 'react'\nimport { hydrateRoot, createRoot } from 'react-dom/client'\nimport { installChunkErrorRecovery, SPARouter } from '@farm.js/core/client'\nimport { createClientPluginManager } from '@farm.js/core/plugin/client'\nimport { reviveDeferredData } from '@farm.js/core/deferred'\nimport {\n createFarmDeploymentMismatchError,\n createFarmDeploymentRequestHeaders,\n isFarmDeploymentMismatchResponse,\n} from '@farm.js/core/deployment'\n${providerImportBlock}\n${clientPluginEntry.imports}\n${docsSearchClientRuntime}\n${devtoolsClientRuntime}\n\n// ⭐ Farm.js SPA Client Runtime (TanStack Start pattern)\n// Uses manifest-based chunk loading - NO HTML fetching!\n// Manifest is inlined in HTML via window.__FARM_MANIFEST__\n\n// Expose React for HMR\nwindow.__FARM_REACT__ = React;\nconst integrationProviders = ${JSON.stringify(integrationProviders)};\nconst integrationDocumentNavigationMatchers = ${JSON.stringify(documentNavigationMatchers)};\n\ninstallChunkErrorRecovery();\n\nlet reactRoot = null;\n\nfunction matchesDocumentNavigation(pathname) {\n return integrationDocumentNavigationMatchers.some((matcher) => {\n if (matcher === '/(.*)' || matcher === '*') {\n return true;\n }\n if (matcher.endsWith('(.*)')) {\n const prefix = matcher.slice(0, -4);\n return pathname === prefix || pathname.startsWith(prefix + '/');\n }\n return matcher === pathname;\n });\n}\n\nfunction wrapWithIntegrationProviders(element) {\n let wrapped = element;\n\n for (let i = integrationProviders.length - 1; i >= 0; i--) {\n const provider = integrationProviders[i];\n if (provider.type === 'clerk') {\n wrapped = React.createElement(ClerkProvider, provider.props || {}, wrapped);\n }\n }\n\n return wrapped;\n}\n\nwindow.__FARM_WRAP_PROVIDERS__ = wrapWithIntegrationProviders;\n\n// Get manifest from window (inlined by server in HTML)\n// Fallback to empty manifest if not available yet\nconst getManifest = () => window.__FARM_MANIFEST__ || { routes: {}, layouts: {}, clientEntry: '', sharedAssets: [] };\n\n// ====== CLIENT-SIDE ROUTE MATCHING ======\n// Matches URL to route using manifest (no server request!)\n\nfunction matchSegment(urlSegment, routeSegment) {\n if (!routeSegment.isDynamic) {\n return urlSegment === routeSegment.segment ? {} : null;\n }\n if (routeSegment.isCatchAll) {\n return { [routeSegment.segment]: urlSegment };\n }\n return { [routeSegment.segment]: urlSegment };\n}\n\nfunction matchRoute(pathname, routeSegments) {\n const normalizedPath = pathname === '/' ? '' : pathname.replace(/^\\\\//, '').replace(/\\\\/$/, '');\n const pathSegments = normalizedPath ? normalizedPath.split('/') : [];\n \n // Handle catch-all routes\n const hasCatchAll = routeSegments.some(s => s.isCatchAll);\n \n if (!hasCatchAll && pathSegments.length !== routeSegments.length) {\n return null;\n }\n \n const params = {};\n \n for (let i = 0; i < routeSegments.length; i++) {\n const routeSeg = routeSegments[i];\n const pathSeg = pathSegments[i];\n\n if (routeSeg.isCatchAll) {\n // Collect remaining segments\n params[routeSeg.segment] = pathSegments.slice(i).join('/');\n return params;\n }\n \n if (pathSeg === undefined) {\n if (routeSeg.isOptional) continue;\n return null;\n }\n \n const match = matchSegment(pathSeg, routeSeg);\n if (match === null) return null;\n Object.assign(params, match);\n }\n \n return params;\n}\n\nfunction findRoute(pathname) {\n const manifest = getManifest();\n const routes = Object.values(manifest.routes);\n \n for (const route of routes) {\n const params = matchRoute(pathname, route.segments);\n if (params !== null) {\n return { route, params };\n }\n }\n return null;\n}\n\nfunction findLayouts(pathname) {\n const manifest = getManifest();\n const layouts = Object.values(manifest.layouts);\n const normalizedPath = pathname === '/' ? '/' : pathname.replace(/\\\\/$/, '');\n const matchingLayouts = [];\n \n for (const layout of layouts) {\n // Root layout matches everything\n if (layout.pattern === '/') {\n matchingLayouts.push(layout);\n continue;\n }\n // Check if pathname starts with layout pattern\n if (normalizedPath.startsWith(layout.pattern) || \n normalizedPath === layout.pattern.replace(/\\\\/[^/]+$/, '')) {\n matchingLayouts.push(layout);\n }\n }\n \n return matchingLayouts.sort((a, b) => a.pattern.length - b.pattern.length);\n}\n\n// ====== SPA ROUTER ======\n// Client-side router - no server requests needed!\n\nclass LegacyManifestSPARouter {\n constructor() {\n this.moduleCache = new Map();\n this.prefetchingUrls = new Set();\n this.observers = new Map();\n \n if (typeof window !== 'undefined') {\n window.addEventListener('popstate', this.handlePopState.bind(this));\n }\n }\n\n setNavigationHandler(handler) {\n this.onNavigate = handler;\n }\n\n async navigate(href, options = {}) {\n const { replace = false, scroll = true } = options;\n const url = new URL(href, window.location.origin);\n const pathname = url.pathname;\n const search = url.search;\n const fullPath = pathname + search;\n\n if (matchesDocumentNavigation(pathname)) {\n if (replace) {\n window.location.replace(url.toString());\n } else {\n window.location.assign(url.toString());\n }\n return;\n }\n\n // Same page - just update hash\n if (pathname === window.location.pathname && search === window.location.search) {\n if (url.hash) window.location.hash = url.hash;\n return;\n }\n\n // Save scroll position\n this.saveScrollPosition(window.location.pathname);\n\n try {\n // CLIENT-SIDE route matching - no server request!\n const match = findRoute(pathname);\n if (!match) {\n console.warn('[Farm.js] Route not found:', pathname);\n window.location.href = href;\n return;\n }\n\n const { route, params } = match;\n\n // Parse search params\n const searchParams = {};\n url.searchParams.forEach((value, key) => {\n searchParams[key] = value;\n });\n\n // Build page data from manifest (no server request!)\n const pageData = {\n route: route, // Full route entry from manifest\n params,\n searchParams,\n layouts: findLayouts(pathname),\n };\n\n // Update URL\n if (replace) {\n window.history.replaceState({ path: fullPath }, '', fullPath);\n } else {\n window.history.pushState({ path: fullPath }, '', fullPath);\n }\n\n // Navigate using the handler\n if (this.onNavigate) {\n await this.onNavigate(pageData);\n }\n applyCanonicalPathFromProps(currentPageProps);\n\n // Handle scroll\n if (scroll) {\n if (url.hash) {\n const element = document.querySelector(url.hash);\n if (element) element.scrollIntoView();\n } else {\n window.scrollTo(0, 0);\n }\n }\n } catch (error) {\n console.error('[Farm.js] Navigation error:', error);\n window.location.href = href; // Fallback\n }\n }\n\n async prefetch(href) {\n // Prefetching disabled in dev mode to avoid Vite dep optimization issues\n // In production, assets are already bundled and prefetched via link tags\n if (import.meta.env?.DEV) return;\n \n const url = new URL(href, window.location.origin);\n const pathname = url.pathname;\n\n if (this.prefetchingUrls.has(pathname)) return;\n\n // Find route in manifest\n const match = findRoute(pathname);\n if (!match) return;\n\n // Only prefetch routes that will hydrate on the client.\n if (!match.route.isClientComponent && !match.route.shouldHydrate) return;\n\n const modulePath = match.route.modulePath;\n if (this.moduleCache.has(modulePath)) return;\n\n this.prefetchingUrls.add(pathname);\n try {\n // Prefetch by importing the module (Vite caches it)\n const module = await import(/* @vite-ignore */ modulePath);\n this.moduleCache.set(modulePath, module);\n pageModuleCache.set(modulePath, module);\n } catch (error) {\n // Silently fail for prefetch\n } finally {\n this.prefetchingUrls.delete(pathname);\n }\n }\n\n observeForPrefetch(element) {\n if (typeof IntersectionObserver === 'undefined') return;\n const href = element.getAttribute('href');\n if (!href || this.isExternalUrl(href)) return;\n\n const observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n if (entry.isIntersecting) {\n setTimeout(() => this.prefetch(href), 100);\n observer.unobserve(element);\n this.observers.delete(element);\n }\n }\n },\n { rootMargin: '200px' }\n );\n observer.observe(element);\n this.observers.set(element, observer);\n }\n\n unobserveForPrefetch(element) {\n const observer = this.observers.get(element);\n if (observer) {\n observer.unobserve(element);\n this.observers.delete(element);\n }\n }\n\n async handlePopState(event) {\n if (document.documentElement.dataset.farmDocsRuntime === 'true') return;\n\n const pathname = window.location.pathname;\n const search = window.location.search;\n \n try {\n // Client-side route matching for back/forward\n const match = findRoute(pathname);\n if (!match) {\n window.location.reload();\n return;\n }\n\n const { route, params } = match;\n const url = new URL(window.location.href);\n const searchParams = {};\n url.searchParams.forEach((value, key) => {\n searchParams[key] = value;\n });\n\n const pageData = {\n route: route,\n params,\n searchParams,\n layouts: findLayouts(pathname),\n };\n\n if (this.onNavigate) await this.onNavigate(pageData);\n this.restoreScrollPosition(pathname);\n } catch (error) {\n console.error('[Farm.js] Popstate error:', error);\n window.location.reload();\n }\n }\n\n isExternalUrl(href) {\n return href.startsWith('http://') || href.startsWith('https://') || href.startsWith('//');\n }\n\n saveScrollPosition(path) {\n try {\n sessionStorage.setItem('farm-scroll-' + path, JSON.stringify({ x: window.scrollX, y: window.scrollY }));\n } catch {}\n }\n\n restoreScrollPosition(path) {\n try {\n const saved = sessionStorage.getItem('farm-scroll-' + path);\n if (saved) {\n const { x, y } = JSON.parse(saved);\n setTimeout(() => window.scrollTo(x, y), 0);\n }\n } catch {}\n }\n}\n\n// Initialize the SPA router\nconst spaRouter = new SPARouter({\n shouldUseDocumentNavigation: matchesDocumentNavigation,\n});\nwindow.__FARM_SPA_ROUTER__ = spaRouter;\n\nconst farmClientRuntime = createClientPluginManager(\n ${clientPluginEntry.registrations},\n {\n router: spaRouter,\n isDev: import.meta.env?.DEV === true,\n isProd: import.meta.env?.PROD === true,\n deploymentId: window.__FARM_DEPLOYMENT_ID__,\n },\n);\nspaRouter.setClientPluginManager(farmClientRuntime);\nwindow.__FARM_CLIENT_RUNTIME__ = farmClientRuntime;\nvoid farmClientRuntime.start();\n\nif (import.meta.hot) {\n import.meta.hot.dispose(() => {\n void farmClientRuntime.close('hmr');\n });\n}\n\n// Cache for loaded page modules\nconst pageModuleCache = new Map();\n\n// Current page state for React rendering\nlet currentPageComponent = null;\nlet currentPageProps = {};\nlet appRoot = null;\n\n// Layout component reference (loaded once, reused across navigations)\nlet LayoutComponent = null;\n\n// Track if we've taken over rendering from SSR\nlet hasClientTakenOver = false;\n\nfunction normalizeServerProps(rawProps) {\n const props = rawProps && typeof rawProps === 'object' ? { ...rawProps } : {};\n if (props.middleware && props.middleware.data && !(props.middleware.data instanceof Map)) {\n props.middleware = { ...props.middleware, data: new Map(Object.entries(props.middleware.data)) };\n }\n if (props.context && props.context.data && !(props.context.data instanceof Map)) {\n props.context = { ...props.context, data: new Map(Object.entries(props.context.data)) };\n }\n return props;\n}\n\nfunction applyCanonicalPathFromProps(props) {\n const canonicalPath = props && typeof props.__farmCanonicalPath === 'string'\n ? props.__farmCanonicalPath\n : null;\n if (!canonicalPath) return;\n const currentPath = window.location.pathname + window.location.search;\n if (canonicalPath === currentPath) return;\n window.history.replaceState({ ...(window.history.state || {}), path: canonicalPath }, '', canonicalPath);\n}\n\nfunction replayPreHydrationClicks() {\n window.__FARM_HYDRATED__ = true;\n document.documentElement.dataset.farmHydrated = 'true';\n\n const queue = Array.isArray(window.__FARM_PREHYDRATION_CLICK_QUEUE__)\n ? window.__FARM_PREHYDRATION_CLICK_QUEUE__\n : [];\n if (queue.length === 0) return;\n\n const queuedClicks = queue.splice(0, queue.length);\n for (const queuedClick of queuedClicks) {\n const target = queuedClick?.target;\n if (!target || typeof target.click !== 'function') continue;\n if (target.isConnected === false) continue;\n setTimeout(() => target.click(), 0);\n }\n}\n\nasync function buildClientHydrationElement(PageComponent, pageProps) {\n let element = React.createElement(PageComponent, pageProps);\n const loadingModulePath = window.__FARM_LOADING_MODULE__;\n\n if (loadingModulePath) {\n try {\n const loadingModule = await import(/* @vite-ignore */ loadingModulePath);\n const LoadingComponent = loadingModule?.default;\n if (LoadingComponent) {\n const loadingFallback = React.createElement(LoadingComponent, {\n params: pageProps?.params || {},\n path: pageProps?.path || window.location.pathname,\n });\n element = React.createElement(React.Suspense, { fallback: loadingFallback }, element);\n }\n } catch (error) {\n console.warn('[Farm.js] Could not load loading boundary for hydration:', error);\n }\n }\n\n return element;\n}\n\nasync function ensureLayoutLoaded(layouts = []) {\n if (LayoutComponent || layouts.length === 0) {\n return LayoutComponent;\n }\n\n try {\n const rootLayout = layouts.find((layout) => layout.pattern === '/');\n if (rootLayout) {\n const layoutModule = await import(/* @vite-ignore */ rootLayout.modulePath);\n LayoutComponent = layoutModule.default;\n }\n } catch (error) {\n console.warn('[Farm.js] Could not load layout:', error);\n }\n\n return LayoutComponent;\n}\n\nfunction getCurrentSearchParams() {\n const searchParams = {};\n const url = new URL(window.location.href);\n url.searchParams.forEach((value, key) => {\n searchParams[key] = value;\n });\n return searchParams;\n}\n\nfunction parseClientRouteSchema(schema, value, label) {\n if (!schema || typeof schema.parse !== 'function') {\n return value;\n }\n\n try {\n return schema.parse(value);\n } catch (error) {\n throw new Error('Invalid route ' + label + ': ' + (error?.message || String(error)));\n }\n}\n\nasync function buildRouteComponentProps(pageModule, params, searchParams, path, existingProps) {\n if (existingProps?.__farmRoutePropsResolved === true) {\n const revivedProps = reviveDeferredData(\n existingProps,\n window.__FARM_DEFERRED_DATA__ || {},\n );\n window.__FARM_PROPS__ = revivedProps;\n return {\n ...revivedProps,\n searchParams: Promise.resolve(revivedProps.search ?? revivedProps.searchParams ?? {}),\n path: revivedProps.path || path,\n };\n }\n\n if (typeof pageModule?.__farmResolveRouteProps === 'function') {\n const rawProps = {\n ...(existingProps || {}),\n params,\n searchParams: Promise.resolve(searchParams),\n path,\n };\n // Keep top-level route errors inside the router's navigation transaction.\n // Explicit defer() values can still suspend nested UI after this resolves.\n return await pageModule.__farmResolveRouteProps(rawProps);\n }\n\n const schemas = pageModule?.__farmRouteSchemas;\n const parsedParams = parseClientRouteSchema(schemas?.params, params, 'params');\n const parsedSearch = parseClientRouteSchema(schemas?.search, searchParams, 'search');\n\n return {\n params: parsedParams,\n search: parsedSearch,\n searchParams: schemas ? Promise.resolve(parsedSearch) : parsedSearch,\n path,\n };\n}\n\nconst clientModuleHintCache = new Map();\n\nasync function moduleLooksClient(modulePath) {\n if (!modulePath) {\n return false;\n }\n\n if (clientModuleHintCache.has(modulePath)) {\n return clientModuleHintCache.get(modulePath);\n }\n\n try {\n const response = await fetch(modulePath, { headers: { Accept: \"text/javascript\" } });\n const source = await response.text();\n const looksClient = /[\"']use client[\"']/.test(source.slice(0, 256));\n const hasHydrateExport = /\\\\bexport\\\\s+const\\\\s+hydrate\\\\s*=\\\\s*true\\\\b/.test(source);\n const shouldHydrate = looksClient || hasHydrateExport;\n clientModuleHintCache.set(modulePath, shouldHydrate);\n return shouldHydrate;\n } catch (error) {\n clientModuleHintCache.set(modulePath, false);\n return false;\n }\n}\n\nasync function buildWrappedHydrationElement(PageComponent, pageProps, layouts = []) {\n await ensureLayoutLoaded(layouts);\n const pageElement = await buildClientHydrationElement(PageComponent, pageProps);\n const wrappedTree = LayoutComponent\n ? React.createElement(LayoutComponent, { children: pageElement })\n : pageElement;\n return wrapWithIntegrationProviders(wrappedTree);\n}\n\nasync function tryHydrateImportedPage(\n container,\n route,\n params,\n layouts,\n useHydrate = false,\n existingProps = null,\n) {\n const modulePath = route?.modulePath;\n if (!modulePath) {\n return false;\n }\n\n let pageModule = pageModuleCache.get(modulePath);\n if (!pageModule) {\n pageModule = await import(/* @vite-ignore */ modulePath);\n pageModuleCache.set(modulePath, pageModule);\n }\n\n const PageComponent = pageModule?.default;\n if (!PageComponent) {\n return false;\n }\n\n currentPageComponent = PageComponent;\n currentPageProps = await buildRouteComponentProps(\n pageModule,\n params,\n getCurrentSearchParams(),\n window.location.pathname,\n existingProps,\n );\n\n const wrappedElement = useHydrate && container?.id === '__farm_page__'\n ? wrapWithIntegrationProviders(\n await buildClientHydrationElement(PageComponent, currentPageProps),\n )\n : await buildWrappedHydrationElement(\n PageComponent,\n currentPageProps,\n layouts,\n );\n\n if (useHydrate) {\n try {\n reactRoot = hydrateRoot(container, wrappedElement);\n window.__FARM_REACT_ROOT__ = reactRoot;\n return true;\n } catch (error) {\n console.log('[Farm.js] Hydration mismatch, using createRoot');\n appRoot = createRoot(container);\n appRoot.render(wrappedElement);\n window.__FARM_REACT_ROOT__ = appRoot;\n hasClientTakenOver = true;\n return true;\n }\n }\n\n hasClientTakenOver = true;\n if (reactRoot) { try { reactRoot.unmount(); } catch (e) {} reactRoot = null; }\n if (appRoot) { try { appRoot.unmount(); } catch (e) {} appRoot = null; }\n appRoot = createRoot(container);\n window.__FARM_REACT_ROOT__ = appRoot;\n appRoot.render(wrappedElement);\n return true;\n}\n\n// ====== CHUNK-BASED NAVIGATION (TanStack Start pattern) ======\n// NO HTML fetching! Uses manifest to dynamically import page chunks\nasync function renderPage(pageData) {\n const container = document.getElementById('root');\n if (!container) return;\n\n const route = {\n modulePath: pageData.modulePath,\n isClientComponent: pageData.isClientComponent === true,\n shouldHydrate: pageData.shouldHydrate === true,\n };\n const params = pageData.props?.params || {};\n const layouts = (pageData.layoutModules || []).map((modulePath, index) => ({\n modulePath,\n pattern: index === 0 ? '/' : modulePath,\n }));\n const path = window.location.pathname + window.location.search;\n\n // Helper to fetch HTML and swap content, then re-hydrate if client component\n const fetchAndSwapHTML = async () => {\n console.log('[Farm.js] Fetching HTML for:', path);\n const deploymentId = window.__FARM_DEPLOYMENT_ID__;\n const response = await fetch(path, {\n headers: createFarmDeploymentRequestHeaders(deploymentId, { 'Accept': 'text/html' }),\n });\n if (isFarmDeploymentMismatchResponse(response, deploymentId)) {\n const error = createFarmDeploymentMismatchError(response, deploymentId || 'unknown');\n window.dispatchEvent(new CustomEvent('farm:deployment-mismatch', { detail: error }));\n window.location.assign(path);\n return false;\n }\n const html = await response.text();\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n const newRoot = doc.getElementById('root');\n\n const resetReactRoots = () => {\n if (appRoot) { try { appRoot.unmount(); } catch(e) {} appRoot = null; }\n if (reactRoot) { try { reactRoot.unmount(); } catch(e) {} reactRoot = null; }\n delete window.__FARM_REACT_ROOT__;\n hasClientTakenOver = false;\n };\n\n if (newRoot) {\n resetReactRoots();\n container.innerHTML = newRoot.innerHTML;\n const newTitle = doc.querySelector('title');\n if (newTitle) document.title = newTitle.textContent || document.title;\n \n const shouldHydrate =\n route.shouldHydrate === true ||\n route.isClientComponent ||\n await moduleLooksClient(route.modulePath);\n if (shouldHydrate) {\n try {\n const hydrationContainer = document.getElementById('__farm_page__') || container;\n await tryHydrateImportedPage(hydrationContainer, route, params, layouts, true);\n } catch (error) {\n // Keep the swapped server HTML when the page can only run on the server.\n }\n }\n \n console.log('[Farm.js] ⚡ HTML navigated to:', path);\n return true;\n }\n\n if (!doc.documentElement || !doc.body) return false;\n\n resetReactRoots();\n Array.from(document.documentElement.attributes).forEach(function(attr) {\n if (!doc.documentElement.hasAttribute(attr.name)) {\n document.documentElement.removeAttribute(attr.name);\n }\n });\n Array.from(doc.documentElement.attributes).forEach(function(attr) {\n document.documentElement.setAttribute(attr.name, attr.value);\n });\n\n document.head.innerHTML = doc.head ? doc.head.innerHTML : '';\n document.body.innerHTML = doc.body.innerHTML;\n delete window.__farmDocsRuntime;\n delete window.__farmDocsPageActionsRuntime;\n\n setTimeout(function() {\n Array.from(document.querySelectorAll('script')).forEach(function(script) {\n const freshScript = document.createElement('script');\n Array.from(script.attributes).forEach(function(attr) {\n freshScript.setAttribute(attr.name, attr.value);\n });\n freshScript.textContent = script.textContent || '';\n script.replaceWith(freshScript);\n });\n }, 0);\n\n console.log('[Farm.js] ⚡ Document navigated to:', path);\n return true;\n };\n\n try {\n const isDev = import.meta.env?.DEV;\n \n // For server components, always use HTML swap (they need server rendering)\n if (!route.isClientComponent) {\n await fetchAndSwapHTML();\n return;\n }\n \n // For client components in dev mode, try dynamic import first\n // If it fails due to server deps, fall back to full page navigation\n\n // Get module path from manifest (production only)\n const modulePath = route.modulePath;\n \n // Try to dynamically import the page module\n let pageModule;\n try {\n pageModule = pageModuleCache.get(modulePath);\n if (!pageModule) {\n pageModule = await import(/* @vite-ignore */ modulePath);\n pageModuleCache.set(modulePath, pageModule);\n }\n } catch (importError) {\n // Import failed (e.g., server deps) - fall back to full page navigation\n // This ensures proper hydration of client components\n console.warn('[Farm.js] Module import failed, using full navigation:', importError.message);\n window.location.href = path;\n return;\n }\n \n const PageComponent = pageModule.default;\n if (!PageComponent) {\n throw new Error('Page module has no default export: ' + modulePath);\n }\n \n // This is a client component (we already filtered out server components above)\n // Render directly with React - no HTML fetch needed!\n console.log('[Farm.js] ⚡ Chunk render:', modulePath);\n \n // Update metadata from module\n const metadata = pageModule.metadata;\n if (metadata?.title) document.title = metadata.title;\n if (metadata?.description) {\n let metaDesc = document.querySelector('meta[name=\"description\"]');\n if (!metaDesc) {\n metaDesc = document.createElement('meta');\n metaDesc.setAttribute('name', 'description');\n document.head.appendChild(metaDesc);\n }\n metaDesc.setAttribute('content', metadata.description);\n }\n \n // Update current page state\n currentPageComponent = PageComponent;\n currentPageProps = await buildRouteComponentProps(\n pageModule,\n params,\n getCurrentSearchParams(),\n path,\n pageData.props,\n );\n applyCanonicalPathFromProps(currentPageProps);\n\n const element = await buildWrappedHydrationElement(\n PageComponent,\n currentPageProps,\n layouts,\n );\n \n // On first SPA navigation, take over from SSR\n if (!hasClientTakenOver) {\n hasClientTakenOver = true;\n if (reactRoot) { try { reactRoot.unmount(); } catch(e) {} reactRoot = null; }\n if (appRoot) { try { appRoot.unmount(); } catch(e) {} appRoot = null; }\n appRoot = createRoot(container);\n window.__FARM_REACT_ROOT__ = appRoot;\n }\n \n if (!appRoot) {\n appRoot = createRoot(container);\n window.__FARM_REACT_ROOT__ = appRoot;\n }\n \n // Render!\n appRoot.render(element);\n console.log('[Farm.js] ⚡ Chunk navigated to:', path);\n } catch (error) {\n console.error('[Farm.js] Render error:', error);\n // Fallback to full navigation\n window.location.href = path;\n }\n}\n\n// Set up the navigation handler\nspaRouter.setNavigationHandler(renderPage);\n\nasync function hydrate() {\n if (isFarmDocsSearchPage()) {\n await mountFarmDocsSearch();\n return;\n }\n\n const rootContainer = document.getElementById('root')\n \n if (!rootContainer) {\n console.error('[Farm.js] Root container not found')\n return\n }\n\n try {\n // Pre-load layout for SPA navigation\n try {\n const layoutModule = await import(/* @vite-ignore */ '/src/app/layout.tsx');\n LayoutComponent = layoutModule.default;\n } catch (e) {\n console.warn('[Farm.js] Could not preload layout:', e);\n }\n\n // Check if this is a client component (set by SSR)\n const isClientComponent = window.__FARM_IS_CLIENT__ === true;\n const modulePath = window.__FARM_PAGE_MODULE__;\n\n if (!modulePath) {\n console.error('[Farm.js] No page module path found')\n return\n }\n\n let pageProps = normalizeServerProps(window.__FARM_PROPS__);\n applyCanonicalPathFromProps(pageProps);\n\n const shouldHydrate =\n window.__FARM_SHOULD_HYDRATE__ === true ||\n isClientComponent ||\n await moduleLooksClient(modulePath);\n if (!shouldHydrate) {\n console.log('[Farm.js] Server component - SPA router ready')\n return\n }\n\n // Get props - either from server-injected props or by matching the current URL\n if (!pageProps || !pageProps.params || Object.keys(pageProps.params).length === 0) {\n // Extract params from URL using manifest route matching (fallback)\n const pathname = window.location.pathname;\n const foundRoute = findRoute(pathname);\n pageProps = normalizeServerProps({\n params: foundRoute?.params || {},\n search: getCurrentSearchParams(),\n searchParams: getCurrentSearchParams(),\n path: pathname,\n });\n }\n currentPageProps = pageProps;\n\n const layouts = findLayouts(window.location.pathname);\n const pageContainer = shouldHydrate\n ? document.getElementById('__farm_page__') || rootContainer\n : rootContainer;\n\n if (!pageContainer) {\n console.log('[Farm.js] Server component - SPA router ready')\n return\n }\n\n const hydrationSession = await farmClientRuntime.beginHydration({\n container: pageContainer,\n mode: shouldHydrate ? 'hydrate' : 'render',\n });\n\n let hydrated = false;\n try {\n hydrated = await tryHydrateImportedPage(\n pageContainer,\n { modulePath },\n currentPageProps.params || {},\n layouts,\n shouldHydrate,\n currentPageProps,\n );\n await farmClientRuntime.completeHydration(hydrationSession);\n } catch (error) {\n await farmClientRuntime.failHydration(hydrationSession, error);\n throw error;\n }\n\n if (hydrated) {\n replayPreHydrationClicks();\n console.log('[Farm.js] ✅ Hydrated:', modulePath);\n return;\n }\n\n console.log('[Farm.js] Server component - SPA router ready')\n } catch (error) {\n console.error('[Farm.js] Hydration error:', error)\n }\n}\n\nif (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', hydrate)\n} else {\n hydrate()\n}\n\n// ====== EVENT DELEGATION FOR LINKS ======\n// This catches all link clicks even without React hydration\n// This is essential for server component pages where React doesn't hydrate\n\nfunction isModifierEvent(e) {\n return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);\n}\n\nfunction isExternalUrl(href) {\n return href.startsWith('http://') || href.startsWith('https://') || href.startsWith('//');\n}\n\ndocument.addEventListener('click', function(event) {\n if (document.documentElement.dataset.farmDocsRuntime === 'true') return;\n\n // Find the closest anchor element\n let target = event.target;\n while (target && target.tagName !== 'A') {\n target = target.parentElement;\n }\n \n if (!target || target.tagName !== 'A') return;\n \n const href = target.getAttribute('href');\n if (!href) return;\n \n // Don't intercept external links\n if (isExternalUrl(href)) return;\n \n // Don't intercept hash-only links\n if (href.startsWith('#')) return;\n \n // Don't intercept if target is set to open in new window\n const linkTarget = target.getAttribute('target');\n if (linkTarget && linkTarget !== '_self') return;\n \n // Don't intercept modifier clicks (Ctrl+Click = new tab)\n if (isModifierEvent(event)) return;\n \n // Don't intercept non-left clicks\n if (event.button !== 0) return;\n \n // Don't intercept if already prevented\n if (event.defaultPrevented) return;\n \n // Use SPA router\n event.preventDefault();\n const replace = target.hasAttribute('data-replace');\n const scroll = !target.hasAttribute('data-no-scroll');\n const viewTransitionValue = target.getAttribute('data-view-transition');\n const viewTransition = viewTransitionValue === 'auto'\n ? 'auto'\n : viewTransitionValue === 'true';\n \n spaRouter.navigate(href, { replace, scroll, viewTransition });\n}, true); // Use capture phase to handle before React\n\nif (import.meta.hot) {\n import.meta.hot.on('vite:beforeUpdate', () => {\n console.log('[Farm.js] ⚡ Update detected')\n // Clear module cache on HMR to pick up changes\n pageModuleCache.clear();\n })\n}\n\nconsole.log('[Farm.js] 🌱 SPA Router initialized');\n`;\n}\n\nfunction generateServerCode(): string {\n return `\nexport { FarmApp, createFarmApp } from './app'\nexport { ServerRenderer } from './server/renderer'\nexport { RouteManager } from './routing/route-manager'\nexport * from './types'\n`;\n}\n\nfunction generateClientManifest(bundle: any): Record<string, any> {\n const manifest: Record<string, any> = {};\n\n for (const [fileName, chunk] of Object.entries(bundle)) {\n if ((chunk as any).type === \"chunk\") {\n manifest[fileName] = {\n id: fileName,\n chunks: [fileName],\n name: (chunk as any).name || fileName,\n };\n }\n }\n\n return manifest;\n}\n\nexport async function defineConfig(config: FarmVitePluginOptions = {}) {\n const tailwindcss = (await import(\"@tailwindcss/vite\")).default;\n const appRoot = path.resolve(config.root || process.cwd());\n if (config.extends?.length) {\n const { config: layeredConfig } = await import(\"./layers\").then(({ resolveFarmLayers }) =>\n resolveFarmLayers(config, {\n root: appRoot,\n mode: process.env.NODE_ENV === \"production\" ? \"production\" : \"development\",\n }),\n );\n config = layeredConfig;\n }\n\n // Node.js built-in module stubs for browser\n const nodeBuiltinStubs: Record<string, string> = {\n \"node:string_decoder\":\n \"data:text/javascript,export class StringDecoder { write(buf) { return ''; } end() { return ''; } }; export default StringDecoder;\",\n \"node:buffer\":\n \"data:text/javascript,export const Buffer = { from: () => ({}), alloc: () => ({}), isBuffer: () => false }; export default { Buffer };\",\n \"node:stream\":\n \"data:text/javascript,export class Readable {}; export class Writable {}; export class Transform {}; export default { Readable, Writable, Transform };\",\n \"node:util\":\n \"data:text/javascript,export const promisify = (fn) => fn; export const inspect = (obj) => String(obj); export default { promisify, inspect };\",\n \"node:events\":\n \"data:text/javascript,export class EventEmitter { on() {} off() {} emit() {} }; export default EventEmitter;\",\n \"node:path\":\n \"data:text/javascript,export const join = (...args) => args.join('/'); export const resolve = (...args) => args.join('/'); export default { join, resolve };\",\n \"node:fs\": \"data:text/javascript,export default {};\",\n \"node:url\":\n \"data:text/javascript,export const URL = globalThis.URL; export const URLSearchParams = globalThis.URLSearchParams; export default { URL, URLSearchParams };\",\n \"node:crypto\":\n \"data:text/javascript,export const randomUUID = () => crypto.randomUUID(); export default { randomUUID };\",\n \"node:os\":\n \"data:text/javascript,export const platform = () => 'browser'; export const homedir = () => '/'; export default { platform, homedir };\",\n \"node:child_process\": \"data:text/javascript,export default {};\",\n \"node:http\": \"data:text/javascript,export default {};\",\n \"node:https\": \"data:text/javascript,export default {};\",\n \"node:net\": \"data:text/javascript,export default {};\",\n \"node:tls\": \"data:text/javascript,export default {};\",\n \"node:zlib\": \"data:text/javascript,export default {};\",\n \"node:async_hooks\":\n \"data:text/javascript,export const AsyncLocalStorage = class {}; export default { AsyncLocalStorage };\",\n \"node:worker_threads\": \"data:text/javascript,export default {};\",\n \"node:perf_hooks\":\n \"data:text/javascript,export const performance = globalThis.performance; export default { performance };\",\n string_decoder:\n \"data:text/javascript,export class StringDecoder { write(buf) { return ''; } end() { return ''; } }; export default StringDecoder;\",\n buffer:\n \"data:text/javascript,export const Buffer = { from: () => ({}), alloc: () => ({}), isBuffer: () => false }; export default { Buffer };\",\n stream:\n \"data:text/javascript,export class Readable {}; export class Writable {}; export class Transform {}; export default { Readable, Writable, Transform };\",\n util: \"data:text/javascript,export const promisify = (fn) => fn; export const inspect = (obj) => String(obj); export default { promisify, inspect };\",\n events:\n \"data:text/javascript,export class EventEmitter { on() {} off() {} emit() {} }; export default EventEmitter;\",\n path: \"data:text/javascript,export const join = (...args) => args.join('/'); export const resolve = (...args) => args.join('/'); export default { join, resolve };\",\n fs: \"data:text/javascript,export default {};\",\n url: \"data:text/javascript,export const URL = globalThis.URL; export const URLSearchParams = globalThis.URLSearchParams; export default { URL, URLSearchParams };\",\n crypto:\n \"data:text/javascript,export const randomUUID = () => crypto.randomUUID(); export default { randomUUID };\",\n os: \"data:text/javascript,export const platform = () => 'browser'; export const homedir = () => '/'; export default { platform, homedir };\",\n child_process: \"data:text/javascript,export default {};\",\n http: \"data:text/javascript,export default {};\",\n https: \"data:text/javascript,export default {};\",\n net: \"data:text/javascript,export default {};\",\n tls: \"data:text/javascript,export default {};\",\n zlib: \"data:text/javascript,export default {};\",\n async_hooks:\n \"data:text/javascript,export const AsyncLocalStorage = class {}; export default { AsyncLocalStorage };\",\n worker_threads: \"data:text/javascript,export default {};\",\n perf_hooks:\n \"data:text/javascript,export const performance = globalThis.performance; export default { performance };\",\n };\n\n // Plugin to intercept __vite-browser-external requests\n const viteBrowserExternalPlugin = {\n name: \"farm:browser-external-stub\",\n enforce: \"pre\" as const,\n resolveId(id: string) {\n // Handle Vite's browser external markers\n if (id.includes(\"__vite-browser-external:\")) {\n const moduleName = id.replace(/__vite-browser-external:/, \"\");\n const stub = nodeBuiltinStubs[moduleName];\n if (stub) return stub;\n // Generic stub for unknown node modules\n return \"data:text/javascript,export default {};\";\n }\n // Handle direct node: imports\n if (id.startsWith(\"node:\")) {\n const stub = nodeBuiltinStubs[id];\n if (stub) return stub;\n return \"data:text/javascript,export default {};\";\n }\n return null;\n },\n };\n\n // Custom logger to replace Vite's default logs with Farm.js branding\n const pc = await import(\"picocolors\").then((m) => m.default);\n let serverStarted = false;\n let startTime = Date.now();\n\n const farmLogger = {\n info: (msg: string) => {\n // Suppress ALL Vite startup messages - we print our own Farm.js branded output\n if (\n msg.includes(\"VITE\") ||\n msg.includes(\"vite\") ||\n msg.includes(\"ready in\") ||\n msg.includes(\"Local:\") ||\n msg.includes(\"Network:\") ||\n msg.includes(\"➜\") ||\n msg.includes(\"Port\") ||\n msg.includes(\"trying another\")\n ) {\n return;\n }\n // Pass through other info messages\n console.log(msg);\n },\n warn: (msg: string) => console.warn(pc.yellow(msg)),\n warnOnce: (msg: string) => console.warn(pc.yellow(msg)),\n error: (msg: string) => console.error(pc.red(msg)),\n clearScreen: () => {},\n hasErrorLogged: () => false,\n hasWarned: false,\n };\n\n // Plugin to print Farm.js branding after server starts\n const farmBrandingPlugin = {\n name: \"farm:branding\",\n enforce: \"pre\" as const,\n configureServer(server: ViteDevServer) {\n startTime = Date.now();\n\n const originalListen = server.listen.bind(server);\n server.listen = async (port?: number, ...args: any[]) => {\n const result = await originalListen(port, ...args);\n if (!serverStarted) {\n serverStarted = true;\n const elapsed = Date.now() - startTime;\n const address = server.httpServer?.address();\n const resolvedPort =\n typeof address === \"object\" && address\n ? address.port\n : server.config.server.port || port || 3000;\n const hostConfig = server.config.server.host;\n const isExposed = hostConfig === true || hostConfig === \"0.0.0.0\";\n\n console.log(\"\");\n console.log(\n ` ${pc.bold(pc.green(\"Farm.js\"))} ${pc.dim(\"v1.0.0\")} ${pc.dim(`ready in ${elapsed}ms`)}`,\n );\n console.log(\"\");\n console.log(\n ` ${pc.dim(\"➜\")} ${pc.bold(\"Local:\")} ${pc.cyan(`http://localhost:${resolvedPort}/`)}`,\n );\n if (isExposed) {\n // Get actual network address\n const os = require(\"os\");\n const interfaces = os.networkInterfaces();\n for (const name of Object.keys(interfaces)) {\n for (const iface of interfaces[name] || []) {\n if (iface.family === \"IPv4\" && !iface.internal) {\n console.log(\n ` ${pc.dim(\"➜\")} ${pc.bold(\"Network:\")} ${pc.cyan(`http://${iface.address}:${resolvedPort}/`)}`,\n );\n break;\n }\n }\n }\n } else {\n console.log(\n ` ${pc.dim(\"➜\")} ${pc.bold(\"Network:\")} ${pc.dim(\"use --host to expose\")}`,\n );\n }\n console.log(\"\");\n }\n return result;\n };\n },\n };\n\n return {\n plugins: [\n tailwindcss(),\n viteBrowserExternalPlugin,\n farmI18nClientBridgePlugin(),\n farmPlugin(config),\n farmEnvironmentFunctionsPlugin(),\n farmBrandingPlugin,\n ],\n customLogger: farmLogger,\n clearScreen: false,\n optimizeDeps: {\n include: [\n \"react\",\n \"react-dom\",\n \"react-dom/client\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ],\n // Exclude server-side packages from browser bundling\n exclude: [\n \"@farm.js/core/server\",\n \"@farm.js/core/api\",\n \"@farm.js/core/middleware\",\n \"@farm.js/core/config\",\n \"nitro\",\n \"h3\",\n \"vite\",\n \"esbuild\",\n \"rollup\",\n \"fsevents\",\n \"nf3\",\n \"better-call\",\n \"zod\",\n \"supports-color\",\n \"node-fetch\",\n \"consola\",\n \"mock-aws-s3\",\n \"aws-sdk\",\n \"nock\",\n ],\n },\n ssr: {\n noExternal: [\"farm\", \"@farm.js/core\"],\n // Externalize React to prevent multiple instances during SSR\n external: [\"react\", \"react-dom\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"],\n },\n resolve: {\n // Ensure single React instance across all modules (critical for hooks!)\n dedupe: [\"react\", \"react-dom\", \"react/jsx-runtime\", \"react/jsx-dev-runtime\"],\n // Stub out problematic server-only modules during dev mode\n alias: {\n ...getFarmLayerAliases(config.layers),\n \"@\": path.resolve(appRoot, \"src\"),\n // Nitro internals that should not be resolved in browser\n \"supports-color\":\n \"data:text/javascript,export default false; export const supportsColor = false; export const stdout = false; export const stderr = false;\",\n \"@poppinss/dumper\": \"data:text/javascript,export default {};\",\n \"@poppinss/dumper/html\":\n \"data:text/javascript,export const createScript = () => ''; export const createStyleSheet = () => '';\",\n \"consola/basic\":\n \"data:text/javascript,export default { log: console.log, info: console.info, warn: console.warn, error: console.error };\",\n youch:\n \"data:text/javascript,export default class Youch { toJSON() { return {}; } toHTML() { return ''; } };\",\n // Add all node stubs to alias as well\n ...nodeBuiltinStubs,\n },\n },\n define: {\n __FARM_DEV__: JSON.stringify(process.env.NODE_ENV === \"development\"),\n __FARM_PUBLIC_ENV__: JSON.stringify(getPublicEnvDefine(config)),\n },\n };\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nexport type AfterCallback = () => void | Promise<void>;\n\n/** Runtime hooks supplied by a deployment adapter. */\nexport interface FarmAfterPlatformContext {\n /** Keep a serverless invocation alive until the scheduled work settles. */\n waitUntil?: (promise: Promise<void>) => void;\n /** Register a callback that runs once the response has finished. */\n onResponseFinished?: (callback: () => void) => void;\n}\n\ninterface AfterTask {\n result: Promise<void>;\n start: () => void;\n}\n\ninterface AfterRequestState {\n completion: Promise<void>;\n finishResponse: () => void;\n phase: \"open\" | \"running\" | \"closed\";\n reportError: (error: unknown) => void;\n tasks: AfterTask[];\n}\n\nconst AFTER_STORAGE = Symbol.for(\"@farm.js/core/after-storage\");\n\nfunction getAfterStorage(): AsyncLocalStorage<AfterRequestState> {\n const runtime = globalThis as typeof globalThis & Record<PropertyKey, unknown>;\n const existing = runtime[AFTER_STORAGE];\n if (existing instanceof AsyncLocalStorage) {\n return existing as AsyncLocalStorage<AfterRequestState>;\n }\n\n const storage = new AsyncLocalStorage<AfterRequestState>();\n runtime[AFTER_STORAGE] = storage;\n return storage;\n}\n\nconst afterStorage = getAfterStorage();\n\nfunction defaultAfterErrorReporter(error: unknown): void {\n console.error(\"[Farm.js] after() callback failed:\", error);\n}\n\nfunction reportAfterError(state: AfterRequestState, error: unknown): void {\n try {\n state.reportError(error);\n } catch {\n // Error reporting must never interrupt the remaining post-response work.\n }\n}\n\nfunction createAfterRequestState(\n reportError: (error: unknown) => void = defaultAfterErrorReporter,\n): AfterRequestState {\n let resolveResponseFinished!: () => void;\n let responseFinished = false;\n const responseFinishedPromise = new Promise<void>((resolve) => {\n resolveResponseFinished = resolve;\n });\n\n const state: AfterRequestState = {\n completion: Promise.resolve(),\n finishResponse: () => {\n if (responseFinished) return;\n responseFinished = true;\n resolveResponseFinished();\n },\n phase: \"open\",\n reportError,\n tasks: [],\n };\n\n state.completion = responseFinishedPromise.then(() =>\n afterStorage.run(state, async () => {\n state.phase = \"running\";\n\n for (let index = 0; index < state.tasks.length; index++) {\n const task = state.tasks[index];\n task.start();\n try {\n await task.result;\n } catch (error) {\n reportAfterError(state, error);\n }\n }\n\n state.phase = \"closed\";\n }),\n );\n\n return state;\n}\n\nfunction registerPlatformLifetime(\n state: AfterRequestState,\n context: FarmAfterPlatformContext | undefined,\n): void {\n if (!context?.waitUntil) return;\n\n try {\n context.waitUntil(state.completion);\n } catch (error) {\n reportAfterError(state, error);\n }\n}\n\nfunction registerResponseFinishedHook(\n state: AfterRequestState,\n context: FarmAfterPlatformContext | undefined,\n): boolean {\n if (!context?.onResponseFinished) return false;\n\n try {\n context.onResponseFinished(state.finishResponse);\n return true;\n } catch (error) {\n reportAfterError(state, error);\n return false;\n }\n}\n\nfunction finishSoon(state: AfterRequestState): void {\n setTimeout(state.finishResponse, 0);\n}\n\nfunction wrapResponseBody(\n response: Response,\n request: Request,\n state: AfterRequestState,\n): Response {\n if (\n request.method === \"HEAD\" ||\n response.status < 200 ||\n response.status > 599 ||\n !response.body ||\n response.bodyUsed ||\n response.body.locked\n ) {\n finishSoon(state);\n return response;\n }\n\n const reader = response.body.getReader();\n let released = false;\n const releaseReader = () => {\n if (released) return;\n released = true;\n reader.releaseLock();\n };\n\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const chunk = await reader.read();\n if (chunk.done) {\n releaseReader();\n controller.close();\n finishSoon(state);\n return;\n }\n controller.enqueue(chunk.value);\n } catch (error) {\n releaseReader();\n controller.error(error);\n finishSoon(state);\n }\n },\n async cancel(reason) {\n try {\n await reader.cancel(reason);\n } finally {\n releaseReader();\n finishSoon(state);\n }\n },\n });\n\n return new Response(body, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n });\n}\n\n/**\n * Schedule non-blocking work for after the current response finishes.\n *\n * Callbacks run in registration order. A callback failure is reported without\n * changing the response or preventing later callbacks from running.\n */\nexport function after(callback: AfterCallback): void {\n if (typeof callback !== \"function\") {\n throw new TypeError(\"after() expects a callback function.\");\n }\n\n const state = afterStorage.getStore();\n if (!state) {\n throw new Error(\"after() can only be used while Farm is handling a server request.\");\n }\n if (state.phase === \"closed\") {\n throw new Error(\"after() cannot schedule work after the request lifecycle has completed.\");\n }\n\n let start!: () => void;\n const ready = new Promise<void>((resolve) => {\n start = resolve;\n });\n\n // Registering the continuation here preserves every request AsyncLocalStorage\n // context that is active at the after() call site.\n const result = ready.then(callback);\n state.tasks.push({ result, start });\n}\n\n/** @internal Run a Web Request handler inside Farm's post-response lifecycle. */\nexport async function _runWithAfterRequest(\n request: Request,\n handler: () => Response | Promise<Response>,\n context?: FarmAfterPlatformContext,\n): Promise<Response> {\n if (afterStorage.getStore()) {\n return await handler();\n }\n\n const state = createAfterRequestState();\n registerPlatformLifetime(state, context);\n const hasResponseHook = registerResponseFinishedHook(state, context);\n\n try {\n const response = await afterStorage.run(state, handler);\n return hasResponseHook ? response : wrapResponseBody(response, request, state);\n } catch (error) {\n if (!hasResponseHook) finishSoon(state);\n throw error;\n }\n}\n\n/** @internal Run a Node response handler inside Farm's post-response lifecycle. */\nexport async function _runWithAfterNodeResponse<T>(\n response: ServerResponse,\n handler: () => T | Promise<T>,\n context?: Pick<FarmAfterPlatformContext, \"waitUntil\">,\n): Promise<T> {\n if (afterStorage.getStore()) {\n return await handler();\n }\n\n const state = createAfterRequestState();\n let finished = false;\n const finish = () => {\n if (finished) return;\n finished = true;\n response.off(\"finish\", finish);\n response.off(\"close\", finish);\n state.finishResponse();\n };\n\n response.once(\"finish\", finish);\n response.once(\"close\", finish);\n if (response.writableEnded) finishSoon(state);\n registerPlatformLifetime(state, context);\n\n return await afterStorage.run(state, handler);\n}\n\n/** @internal Add Farm's post-response lifecycle to a Node middleware. */\nexport function _withAfterNodeMiddleware(\n handler: (\n request: IncomingMessage,\n response: ServerResponse,\n next: (error?: unknown) => void,\n ) => void | Promise<void>,\n): (\n request: IncomingMessage,\n response: ServerResponse,\n next: (error?: unknown) => void,\n) => Promise<void> {\n return async (request, response, next) => {\n await _runWithAfterNodeResponse(response, () => handler(request, response, next));\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { imageSize } from \"image-size\";\nimport type { Plugin } from \"vite\";\n\nconst FARM_IMAGE_ID_PREFIX = \"\\0farm:image:\";\nconst STATIC_IMAGE_RE = /\\.(?:avif|gif|jpe?g|png|webp)$/i;\nconst SCRIPT_IMPORTER_RE = /\\.(?:[cm]?[jt]sx?|mdx?)$/i;\n\nexport function farmImageImportsPlugin(): Plugin {\n return {\n name: \"farm-image-imports\",\n enforce: \"pre\",\n\n async resolveId(source, importer, options) {\n if (\n !importer ||\n source.includes(\"?\") ||\n !STATIC_IMAGE_RE.test(source) ||\n !SCRIPT_IMPORTER_RE.test(importer.split(\"?\", 1)[0])\n ) {\n return null;\n }\n\n const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n if (!resolved || resolved.external) return null;\n\n return `${FARM_IMAGE_ID_PREFIX}${encodeURIComponent(resolved.id.split(\"?\", 1)[0])}`;\n },\n\n async load(id) {\n if (!id.startsWith(FARM_IMAGE_ID_PREFIX)) return null;\n\n const filePath = decodeURIComponent(id.slice(FARM_IMAGE_ID_PREFIX.length));\n const assetRequest = `${filePath.replace(/\\\\/g, \"/\")}?url`;\n return createStaticImageModule(filePath, `import src from ${JSON.stringify(assetRequest)};`);\n },\n\n async transform(code, id) {\n const filePath = id.split(\"?\", 1)[0];\n if (id.includes(\"?\") || !STATIC_IMAGE_RE.test(filePath)) return null;\n\n const defaultExport = code.match(/^\\s*export\\s+default\\s+(.+?);?\\s*$/s)?.[1];\n if (!defaultExport) return null;\n return createStaticImageModule(filePath, `const src = ${defaultExport};`);\n },\n };\n}\n\nasync function createStaticImageModule(\n filePath: string,\n sourceDeclaration: string,\n): Promise<string> {\n const bytes = await readFile(filePath);\n const dimensions = imageSize(bytes);\n if (!dimensions.width || !dimensions.height) {\n throw new Error(`Could not determine image dimensions for ${filePath}`);\n }\n\n const blurDataURL = await createBlurDataURL(bytes);\n return [\n sourceDeclaration,\n `const image = ${JSON.stringify({\n width: dimensions.width,\n height: dimensions.height,\n ...(blurDataURL ? { blurDataURL } : {}),\n })};`,\n \"image.src = src;\",\n \"export { src };\",\n \"export const width = image.width;\",\n \"export const height = image.height;\",\n \"export const blurDataURL = image.blurDataURL;\",\n \"export default image;\",\n ].join(\"\\n\");\n}\n\nasync function createBlurDataURL(bytes: Buffer): Promise<string | undefined> {\n try {\n const { default: sharp } = await import(\"sharp\");\n const placeholder = await sharp(bytes)\n .rotate()\n .resize({ width: 8, height: 8, fit: \"inside\", withoutEnlargement: true })\n .webp({ quality: 35 })\n .toBuffer();\n return `data:image/webp;base64,${placeholder.toString(\"base64\")}`;\n } catch {\n return undefined;\n }\n}\n\nexport function isFarmStaticImageFile(filePath: string): boolean {\n return STATIC_IMAGE_RE.test(path.extname(filePath));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyFO,SAAS,iBAAoE;AAClF,SAAO,cAAc;AACvB;AAuEA,SAAS,eAAe,OAAqD;AAC3E,SAAO,IAAI;AAAA,IACT,CAAC;AAAA,IACD;AAAA,MACE,IAAI,SAAS,UAAU;AACrB,YAAI,OAAO,aAAa,UAAU;AAChC,iBAAO;AAAA,QACT;AAEA,cAAMA,OAAM,YAAY,KAAK;AAC7B,eAAOA,KAAI,QAAQ;AAAA,MACrB;AAAA,MACA,UAAU;AACR,eAAO,QAAQ,Q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M,KAAK,CAAC;AAClB,gBAAI,OAAO,IAAI,eAAe;AAC5B,qBAAO;AAAA,YACT;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,OAAO;AAEL,YAAMC,YAA2B,CAAC;AAClC,iBAAW,UAAU,SAAS;AAC5B,mBAAW,QAAQ,KAAK,eAAe,QAAQ,QAAQ,GAAG;AACxD,gBAAM,cAAc,KAAK,eAAe,UAAU,IAAI;AACtD,UAAAA,UAAS,KAAM,KAAa,MAAM,QAAQ,CAAC,GAAG,MAAM,WAAW,CAAC,CAAC;AAAA,QACnE;AAAA,MACF;AACA,YAAM,QAAQ,IAAIA,SAAQ;AAAA,IAC5B;AAEA,QAAI,aAAa,OAAQ,MAAK,cAAc;AAC5C,QAAI,aAAa,QAAS,MAAK,eAAe;AAC9C,QAAI,aAAa,WAAY,MAAK,gBAAgB;AAElD,WAAO;AAAA,EACT;AAAA,EAEA,cAAc,SAAqC;AACjD,SAAK,UAAU;AAAA,MACb,GAAG,KAAK;AAAA,MACR,GAAG;AAAA,MACH,gBAAgB,KAAK,QAAQ;AAAA,IAC/B;AAAA,EACF;AACF;AAtrB2B;AAApB,IAAM,gBAAN;AAwrBA,SAAS,aAMd,QACkE;AAClE,SAAO;AACT;AATgB;","names":["env","globalState","React","path","text","module","secretError","fs","path","pathToFileURL","relative","text","path","memoryDriver","module","resolveDriver","globalState","path","path","import_promises","path","globalState","api","text","resolveStorageRuntimeClient","createIntegrationOrm","response","path","path","import_node_path","import_node_fs","import_fs","import_path","relativePath","path","path","relativePath","import_node_fs","import_node_path","path","import_node_fs","import_node_module","import_node_path","trimSlashes","path","escapeAttribute","relative","DOCS_FILE_EXTENSIONS","titleFromMarkdown","page","text","body","layout","icon","renderedSections","import_node_fs","import_node_module","import_node_path","isRecord","existsSync","path","fs","pathToFileURL","relativePath","import_path","init_config","isRecord","isResolvedDocsConfig","getDocsTitle","getDocsDescription","getLoadedDocsPages","page","toDocsSitemapPage","toDocsLlmsPage","getDocsLlmsOptions","getDocsDiscoveryOptions","buildFarmingDocsDiagnostics","import_docs","init_config","path","fs","env","path","import_node_path","init_config","escapeHtml","escapeAttribute","throwIfAborted","import_path","path","relativePath","fs","import_promises","loadModule","page","import_react","path","path","FarmProgrammaticPageContent","FarmProgrammaticPage","import_path","import_path","import_fs","import_path","import_url","fs","path","path","fs","import_promises","import_node_path","path","layout","path","module","page","import_react","fs","path","import_node_async_hooks","import_react","output","IntlMessageFormat","isRecord","initialTagCount","icon","import_node_async_hooks","import_intl_messageformat","import_promises","redirect","readCookie","IntlMessageFormat","getRequestStore","t","getRequestStore","toMiddlewareMap","React","page","layout","redirect","body","resolve","relativePath","html","import_path","path","module","fs","path","normalizePathname","result","isWebResponse","text","relativePath","fs","path","module","module","result","match","import_fs","import_path","path","fs","fs","path","DEFAULT_OUT_FILE","relativePath","import_node_fs","import_node_path","path","import_node_fs","import_node_path","fs","path","import_node_async_hooks","resolve","import_promises","import_node_path","import_image_size","publicEnv","env","relative","createNodeImageUrlValidator","createSharpImageTransformer","isStaticMetadataImageFile","createFarmWorkflowRequestHandler","discoverFarmWorkflows","OpenAPIManager","createFarmDevtoolsSnapshot","renderFarmDevtoolsHtml","pathname","resolve","startTime","duration","method","urlPath","routeManager","layout","parseRouteModuleProps","isHtmlResponse","options","page","React","server","parseRouteModuleSchema","createContext","promises"]}