@farm.js/core 0.1.0-beta.6 → 0.1.0-beta.8

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 (447) hide show
  1. package/dist/after.cjs +227 -0
  2. package/dist/after.cjs.map +1 -0
  3. package/dist/after.d.mts +25 -0
  4. package/dist/after.d.ts +25 -0
  5. package/dist/after.mjs +14 -0
  6. package/dist/after.mjs.map +1 -0
  7. package/dist/agent-runtime.cjs +2379 -0
  8. package/dist/agent-runtime.cjs.map +1 -0
  9. package/dist/agent-runtime.d.mts +94 -0
  10. package/dist/agent-runtime.d.ts +94 -0
  11. package/dist/agent-runtime.mjs +479 -0
  12. package/dist/agent-runtime.mjs.map +1 -0
  13. package/dist/api/route-manager.d.mts +66 -0
  14. package/dist/api/route-manager.d.ts +66 -0
  15. package/dist/api/runtime.d.mts +3 -0
  16. package/dist/api/runtime.d.ts +3 -0
  17. package/dist/api.cjs +4100 -0
  18. package/dist/api.cjs.map +1 -0
  19. package/dist/api.d.mts +48 -0
  20. package/dist/api.d.ts +48 -0
  21. package/dist/api.mjs +93 -0
  22. package/dist/api.mjs.map +1 -0
  23. package/dist/app-BWtqQu3R.d.mts +302 -0
  24. package/dist/app-markdown.cjs +244 -0
  25. package/dist/app-markdown.cjs.map +1 -0
  26. package/dist/app-markdown.d.mts +22 -0
  27. package/dist/app-markdown.d.ts +22 -0
  28. package/dist/app-markdown.mjs +27 -0
  29. package/dist/app-markdown.mjs.map +1 -0
  30. package/dist/app-xltejvLY.d.ts +302 -0
  31. package/dist/cache.cjs +945 -0
  32. package/dist/cache.cjs.map +1 -0
  33. package/dist/cache.d.mts +192 -0
  34. package/dist/cache.d.ts +192 -0
  35. package/dist/cache.mjs +46 -0
  36. package/dist/cache.mjs.map +1 -0
  37. package/dist/chunk-2ED5Q2GH.mjs +422 -0
  38. package/dist/chunk-2ED5Q2GH.mjs.map +1 -0
  39. package/dist/chunk-32W4QEJP.mjs +158 -0
  40. package/dist/chunk-32W4QEJP.mjs.map +1 -0
  41. package/dist/chunk-3XNTL3FQ.mjs +452 -0
  42. package/dist/chunk-3XNTL3FQ.mjs.map +1 -0
  43. package/dist/chunk-44ZCFSKE.mjs +84 -0
  44. package/dist/chunk-44ZCFSKE.mjs.map +1 -0
  45. package/dist/chunk-4MGVSBRP.mjs +7787 -0
  46. package/dist/chunk-4MGVSBRP.mjs.map +1 -0
  47. package/dist/chunk-4S3ORGFA.mjs +44 -0
  48. package/dist/chunk-4S3ORGFA.mjs.map +1 -0
  49. package/dist/chunk-5BY76U2M.mjs +1 -0
  50. package/dist/chunk-5BY76U2M.mjs.map +1 -0
  51. package/dist/chunk-5ZGPRGWV.mjs +136 -0
  52. package/dist/chunk-5ZGPRGWV.mjs.map +1 -0
  53. package/dist/chunk-65A7QIKI.mjs +142 -0
  54. package/dist/chunk-65A7QIKI.mjs.map +1 -0
  55. package/dist/chunk-74YTBPTY.mjs +450 -0
  56. package/dist/chunk-74YTBPTY.mjs.map +1 -0
  57. package/dist/chunk-7FBJLMQH.mjs +338 -0
  58. package/dist/chunk-7FBJLMQH.mjs.map +1 -0
  59. package/dist/chunk-7HO6AEOP.mjs +74 -0
  60. package/dist/chunk-7HO6AEOP.mjs.map +1 -0
  61. package/dist/chunk-7MABZJIM.mjs +29 -0
  62. package/dist/chunk-7MABZJIM.mjs.map +1 -0
  63. package/dist/chunk-7N62DNSO.mjs +41 -0
  64. package/dist/chunk-7N62DNSO.mjs.map +1 -0
  65. package/dist/chunk-7ZY5AIJO.mjs +161 -0
  66. package/dist/chunk-7ZY5AIJO.mjs.map +1 -0
  67. package/dist/chunk-ALCLXXTY.mjs +187 -0
  68. package/dist/chunk-ALCLXXTY.mjs.map +1 -0
  69. package/dist/chunk-AZ7YUVNR.mjs +65 -0
  70. package/dist/chunk-AZ7YUVNR.mjs.map +1 -0
  71. package/dist/chunk-B232I2GP.mjs +163 -0
  72. package/dist/chunk-B232I2GP.mjs.map +1 -0
  73. package/dist/chunk-B4W3BNTL.mjs +483 -0
  74. package/dist/chunk-B4W3BNTL.mjs.map +1 -0
  75. package/dist/chunk-C2ROET2V.mjs +718 -0
  76. package/dist/chunk-C2ROET2V.mjs.map +1 -0
  77. package/dist/chunk-CGILA3WO.mjs +14 -0
  78. package/dist/chunk-CGILA3WO.mjs.map +1 -0
  79. package/dist/chunk-CGIXMLSY.mjs +184 -0
  80. package/dist/chunk-CGIXMLSY.mjs.map +1 -0
  81. package/dist/chunk-DJSGLHCN.mjs +597 -0
  82. package/dist/chunk-DJSGLHCN.mjs.map +1 -0
  83. package/dist/chunk-E2MPIBRE.mjs +149 -0
  84. package/dist/chunk-E2MPIBRE.mjs.map +1 -0
  85. package/dist/chunk-E6EPN5BT.mjs +203 -0
  86. package/dist/chunk-E6EPN5BT.mjs.map +1 -0
  87. package/dist/chunk-EI43C4RA.mjs +6277 -0
  88. package/dist/chunk-EI43C4RA.mjs.map +1 -0
  89. package/dist/chunk-EJ7T4TPB.mjs +622 -0
  90. package/dist/chunk-EJ7T4TPB.mjs.map +1 -0
  91. package/dist/chunk-FQYDHKKU.mjs +128 -0
  92. package/dist/chunk-FQYDHKKU.mjs.map +1 -0
  93. package/dist/chunk-FRPWCMMG.mjs +299 -0
  94. package/dist/chunk-FRPWCMMG.mjs.map +1 -0
  95. package/dist/chunk-GN72QAIH.mjs +146 -0
  96. package/dist/chunk-GN72QAIH.mjs.map +1 -0
  97. package/dist/chunk-GQVGIUSN.mjs +149 -0
  98. package/dist/chunk-GQVGIUSN.mjs.map +1 -0
  99. package/dist/chunk-GS6K5OCM.mjs +407 -0
  100. package/dist/chunk-GS6K5OCM.mjs.map +1 -0
  101. package/dist/chunk-GXASWWJU.mjs +364 -0
  102. package/dist/chunk-GXASWWJU.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-H2FA2SBS.mjs +51 -0
  106. package/dist/chunk-H2FA2SBS.mjs.map +1 -0
  107. package/dist/chunk-I4CUBGVF.mjs +93 -0
  108. package/dist/chunk-I4CUBGVF.mjs.map +1 -0
  109. package/dist/chunk-ITN462YM.mjs +98 -0
  110. package/dist/chunk-ITN462YM.mjs.map +1 -0
  111. package/dist/chunk-J23HNLFY.mjs +72 -0
  112. package/dist/chunk-J23HNLFY.mjs.map +1 -0
  113. package/dist/chunk-J4FNJ5IU.mjs +179 -0
  114. package/dist/chunk-J4FNJ5IU.mjs.map +1 -0
  115. package/dist/chunk-J5YWQVI5.mjs +211 -0
  116. package/dist/chunk-J5YWQVI5.mjs.map +1 -0
  117. package/dist/chunk-JDEOUK5V.mjs +427 -0
  118. package/dist/chunk-JDEOUK5V.mjs.map +1 -0
  119. package/dist/chunk-JK25YEN6.mjs +219 -0
  120. package/dist/chunk-JK25YEN6.mjs.map +1 -0
  121. package/dist/chunk-K4667E2Q.mjs +1916 -0
  122. package/dist/chunk-K4667E2Q.mjs.map +1 -0
  123. package/dist/chunk-LGHEOHBU.mjs +218 -0
  124. package/dist/chunk-LGHEOHBU.mjs.map +1 -0
  125. package/dist/chunk-LM2YNO4U.mjs +24 -0
  126. package/dist/chunk-LM2YNO4U.mjs.map +1 -0
  127. package/dist/chunk-ME4MO2RJ.mjs +3540 -0
  128. package/dist/chunk-ME4MO2RJ.mjs.map +1 -0
  129. package/dist/chunk-MIUW47JX.mjs +639 -0
  130. package/dist/chunk-MIUW47JX.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-P7QDS5AT.mjs +191 -0
  134. package/dist/chunk-P7QDS5AT.mjs.map +1 -0
  135. package/dist/chunk-PFE6GMNE.mjs +603 -0
  136. package/dist/chunk-PFE6GMNE.mjs.map +1 -0
  137. package/dist/chunk-QGOHVJ6J.mjs +63 -0
  138. package/dist/chunk-QGOHVJ6J.mjs.map +1 -0
  139. package/dist/chunk-QKVUNGAH.mjs +39 -0
  140. package/dist/chunk-QKVUNGAH.mjs.map +1 -0
  141. package/dist/chunk-QM746KUO.mjs +56 -0
  142. package/dist/chunk-QM746KUO.mjs.map +1 -0
  143. package/dist/chunk-QTZZ2ISQ.mjs +753 -0
  144. package/dist/chunk-QTZZ2ISQ.mjs.map +1 -0
  145. package/dist/chunk-RBRLLZL5.mjs +81 -0
  146. package/dist/chunk-RBRLLZL5.mjs.map +1 -0
  147. package/dist/chunk-RHIFZZUI.mjs +69 -0
  148. package/dist/chunk-RHIFZZUI.mjs.map +1 -0
  149. package/dist/chunk-RQ633A5I.mjs +187 -0
  150. package/dist/chunk-RQ633A5I.mjs.map +1 -0
  151. package/dist/chunk-SCFX4UTD.mjs +28 -0
  152. package/dist/chunk-SCFX4UTD.mjs.map +1 -0
  153. package/dist/chunk-SL6HTIOK.mjs +66 -0
  154. package/dist/chunk-SL6HTIOK.mjs.map +1 -0
  155. package/dist/chunk-SPBBQLXI.mjs +207 -0
  156. package/dist/chunk-SPBBQLXI.mjs.map +1 -0
  157. package/dist/chunk-SSA7THPX.mjs +10 -0
  158. package/dist/chunk-SSA7THPX.mjs.map +1 -0
  159. package/dist/chunk-T4QJQK76.mjs +459 -0
  160. package/dist/chunk-T4QJQK76.mjs.map +1 -0
  161. package/dist/chunk-TQAEEJB4.mjs +157 -0
  162. package/dist/chunk-TQAEEJB4.mjs.map +1 -0
  163. package/dist/chunk-UB5UOSHB.mjs +458 -0
  164. package/dist/chunk-UB5UOSHB.mjs.map +1 -0
  165. package/dist/chunk-USWZZUEH.mjs +25 -0
  166. package/dist/chunk-USWZZUEH.mjs.map +1 -0
  167. package/dist/chunk-UVCIEUJC.mjs +16 -0
  168. package/dist/chunk-UVCIEUJC.mjs.map +1 -0
  169. package/dist/chunk-UXUAWNO5.mjs +396 -0
  170. package/dist/chunk-UXUAWNO5.mjs.map +1 -0
  171. package/dist/chunk-V3XURYJO.mjs +756 -0
  172. package/dist/chunk-V3XURYJO.mjs.map +1 -0
  173. package/dist/chunk-V6WE6JSZ.mjs +352 -0
  174. package/dist/chunk-V6WE6JSZ.mjs.map +1 -0
  175. package/dist/chunk-V7RBCSDJ.mjs +170 -0
  176. package/dist/chunk-V7RBCSDJ.mjs.map +1 -0
  177. package/dist/chunk-VCANOYFI.mjs +588 -0
  178. package/dist/chunk-VCANOYFI.mjs.map +1 -0
  179. package/dist/chunk-VY2UYN5R.mjs +224 -0
  180. package/dist/chunk-VY2UYN5R.mjs.map +1 -0
  181. package/dist/chunk-W2CRQFF6.mjs +1352 -0
  182. package/dist/chunk-W2CRQFF6.mjs.map +1 -0
  183. package/dist/chunk-WDU6QXNK.mjs +872 -0
  184. package/dist/chunk-WDU6QXNK.mjs.map +1 -0
  185. package/dist/chunk-WZ5QFROO.mjs +23 -0
  186. package/dist/chunk-WZ5QFROO.mjs.map +1 -0
  187. package/dist/chunk-XIVV5IWN.mjs +541 -0
  188. package/dist/chunk-XIVV5IWN.mjs.map +1 -0
  189. package/dist/chunk-YW7OBE6Q.mjs +119 -0
  190. package/dist/chunk-YW7OBE6Q.mjs.map +1 -0
  191. package/dist/chunk-Z5CQMP54.mjs +365 -0
  192. package/dist/chunk-Z5CQMP54.mjs.map +1 -0
  193. package/dist/chunk-ZBE6MLHL.mjs +230 -0
  194. package/dist/chunk-ZBE6MLHL.mjs.map +1 -0
  195. package/dist/chunk-ZVWA4ZQ3.mjs +189 -0
  196. package/dist/chunk-ZVWA4ZQ3.mjs.map +1 -0
  197. package/dist/chunk-ZZ57EH5Z.mjs +173 -0
  198. package/dist/chunk-ZZ57EH5Z.mjs.map +1 -0
  199. package/dist/client-BT1mFQas.d.mts +447 -0
  200. package/dist/client-Nn0q4eO4.d.ts +447 -0
  201. package/dist/client-cache-CIlyBlmx.d.ts +6 -0
  202. package/dist/client-cache-D-EZ7XVW.d.mts +6 -0
  203. package/dist/client-plugins-BI2R6Eae.d.mts +1926 -0
  204. package/dist/client-plugins-DU9oMspX.d.ts +1926 -0
  205. package/dist/client-plugins.cjs +415 -0
  206. package/dist/client-plugins.cjs.map +1 -0
  207. package/dist/client-plugins.d.mts +22 -0
  208. package/dist/client-plugins.d.ts +22 -0
  209. package/dist/client-plugins.mjs +10 -0
  210. package/dist/client-plugins.mjs.map +1 -0
  211. package/dist/client.cjs +5402 -0
  212. package/dist/client.cjs.map +1 -0
  213. package/dist/client.d.mts +447 -0
  214. package/dist/client.d.ts +447 -0
  215. package/dist/client.mjs +110 -0
  216. package/dist/client.mjs.map +1 -0
  217. package/dist/config.cjs +38 -0
  218. package/dist/config.cjs.map +1 -0
  219. package/dist/config.d.mts +29 -0
  220. package/dist/config.d.ts +29 -0
  221. package/dist/config.mjs +10 -0
  222. package/dist/config.mjs.map +1 -0
  223. package/dist/cron.cjs +406 -0
  224. package/dist/cron.cjs.map +1 -0
  225. package/dist/cron.d.mts +78 -0
  226. package/dist/cron.d.ts +78 -0
  227. package/dist/cron.mjs +30 -0
  228. package/dist/cron.mjs.map +1 -0
  229. package/dist/deferred.cjs +438 -0
  230. package/dist/deferred.cjs.map +1 -0
  231. package/dist/deferred.d.mts +42 -0
  232. package/dist/deferred.d.ts +42 -0
  233. package/dist/deferred.mjs +28 -0
  234. package/dist/deferred.mjs.map +1 -0
  235. package/dist/deployment.cjs +199 -0
  236. package/dist/deployment.cjs.map +1 -0
  237. package/dist/deployment.d.mts +34 -0
  238. package/dist/deployment.d.ts +34 -0
  239. package/dist/deployment.mjs +38 -0
  240. package/dist/deployment.mjs.map +1 -0
  241. package/dist/devtools-REQTS3I7.mjs +371 -0
  242. package/dist/devtools-REQTS3I7.mjs.map +1 -0
  243. package/dist/devtools-client-3XRTBND5.mjs +216 -0
  244. package/dist/devtools-client-3XRTBND5.mjs.map +1 -0
  245. package/dist/devtools-ui-NJKFORTG.mjs +1349 -0
  246. package/dist/devtools-ui-NJKFORTG.mjs.map +1 -0
  247. package/dist/docs.cjs +5548 -0
  248. package/dist/docs.cjs.map +1 -0
  249. package/dist/docs.d.mts +69 -0
  250. package/dist/docs.d.ts +69 -0
  251. package/dist/docs.mjs +47 -0
  252. package/dist/docs.mjs.map +1 -0
  253. package/dist/env-types.cjs +232 -0
  254. package/dist/env-types.cjs.map +1 -0
  255. package/dist/env-types.d.mts +12 -0
  256. package/dist/env-types.d.ts +12 -0
  257. package/dist/env-types.mjs +11 -0
  258. package/dist/env-types.mjs.map +1 -0
  259. package/dist/env.cjs +215 -0
  260. package/dist/env.cjs.map +1 -0
  261. package/dist/env.d.mts +45 -0
  262. package/dist/env.d.ts +45 -0
  263. package/dist/env.mjs +22 -0
  264. package/dist/env.mjs.map +1 -0
  265. package/dist/environment/vite.d.mts +22 -0
  266. package/dist/environment/vite.d.ts +22 -0
  267. package/dist/environment.cjs +96 -0
  268. package/dist/environment.cjs.map +1 -0
  269. package/dist/environment.d.mts +18 -0
  270. package/dist/environment.d.ts +18 -0
  271. package/dist/environment.mjs +14 -0
  272. package/dist/environment.mjs.map +1 -0
  273. package/dist/headers.cjs +126 -0
  274. package/dist/headers.cjs.map +1 -0
  275. package/dist/headers.d.mts +22 -0
  276. package/dist/headers.d.ts +22 -0
  277. package/dist/headers.mjs +12 -0
  278. package/dist/headers.mjs.map +1 -0
  279. package/dist/i18n/client.d.mts +32 -0
  280. package/dist/i18n/client.d.ts +32 -0
  281. package/dist/i18n/index.d.mts +20 -0
  282. package/dist/i18n/index.d.ts +20 -0
  283. package/dist/i18n/server.d.mts +30 -0
  284. package/dist/i18n/server.d.ts +30 -0
  285. package/dist/image/server.d.mts +37 -0
  286. package/dist/image/server.d.ts +37 -0
  287. package/dist/image/sharp.d.mts +7 -0
  288. package/dist/image/sharp.d.ts +7 -0
  289. package/dist/image-config-Duob7wER.d.mts +50 -0
  290. package/dist/image-config-Duob7wER.d.ts +50 -0
  291. package/dist/image.cjs +209 -0
  292. package/dist/image.cjs.map +1 -0
  293. package/dist/image.d.mts +39 -0
  294. package/dist/image.d.ts +39 -0
  295. package/dist/image.mjs +165 -0
  296. package/dist/image.mjs.map +1 -0
  297. package/dist/index.cjs +42186 -0
  298. package/dist/index.cjs.map +1 -0
  299. package/dist/index.d.mts +454 -0
  300. package/dist/index.d.ts +454 -0
  301. package/dist/index.mjs +980 -0
  302. package/dist/index.mjs.map +1 -0
  303. package/dist/integration-api-CHT2OKAf.d.mts +93 -0
  304. package/dist/integration-api-CHT2OKAf.d.ts +93 -0
  305. package/dist/integration-orm-GQLGU66X.mjs +13 -0
  306. package/dist/integration-orm-GQLGU66X.mjs.map +1 -0
  307. package/dist/integrations.cjs +2820 -0
  308. package/dist/integrations.cjs.map +1 -0
  309. package/dist/integrations.d.mts +22 -0
  310. package/dist/integrations.d.ts +22 -0
  311. package/dist/integrations.mjs +51 -0
  312. package/dist/integrations.mjs.map +1 -0
  313. package/dist/internal/build-runtime.cjs +643 -322
  314. package/dist/internal/build-runtime.cjs.map +1 -1
  315. package/dist/internal/build-runtime.d.mts +39 -0
  316. package/dist/internal/build-runtime.d.ts +39 -0
  317. package/dist/internal/build-runtime.mjs +11 -10
  318. package/dist/internal/client-runtime.d.mts +2 -0
  319. package/dist/internal/client-runtime.d.ts +2 -0
  320. package/dist/internal/config-runtime.cjs +135 -39
  321. package/dist/internal/config-runtime.cjs.map +1 -1
  322. package/dist/internal/config-runtime.d.mts +39 -0
  323. package/dist/internal/config-runtime.d.ts +39 -0
  324. package/dist/internal/config-runtime.mjs +5 -4
  325. package/dist/internal/production-node-env.d.mts +12 -0
  326. package/dist/internal/production-node-env.d.ts +12 -0
  327. package/dist/internal/production-runtime.d.mts +39 -0
  328. package/dist/internal/production-runtime.d.ts +39 -0
  329. package/dist/layers-VWVDTPUZ.mjs +16 -0
  330. package/dist/layers-VWVDTPUZ.mjs.map +1 -0
  331. package/dist/manager-THKFTOFE.mjs +10 -0
  332. package/dist/manager-THKFTOFE.mjs.map +1 -0
  333. package/dist/markdown.cjs +364 -0
  334. package/dist/markdown.cjs.map +1 -0
  335. package/dist/markdown.d.mts +60 -0
  336. package/dist/markdown.d.ts +60 -0
  337. package/dist/markdown.mjs +18 -0
  338. package/dist/markdown.mjs.map +1 -0
  339. package/dist/metadata-Cm9ujH4I.d.ts +22 -0
  340. package/dist/metadata-DacXbnLA.d.mts +22 -0
  341. package/dist/middleware.cjs +2148 -0
  342. package/dist/middleware.cjs.map +1 -0
  343. package/dist/middleware.d.mts +164 -0
  344. package/dist/middleware.d.ts +164 -0
  345. package/dist/middleware.mjs +49 -0
  346. package/dist/middleware.mjs.map +1 -0
  347. package/dist/navigation-errors-Dvwpzaer.d.mts +13 -0
  348. package/dist/navigation-errors-Dvwpzaer.d.ts +13 -0
  349. package/dist/navigation.cjs +1329 -0
  350. package/dist/navigation.cjs.map +1 -0
  351. package/dist/navigation.d.mts +14 -0
  352. package/dist/navigation.d.ts +14 -0
  353. package/dist/navigation.mjs +33 -0
  354. package/dist/navigation.mjs.map +1 -0
  355. package/dist/nitro-QO5LV6QK.mjs +689 -0
  356. package/dist/nitro-QO5LV6QK.mjs.map +1 -0
  357. package/dist/observability.cjs +186 -0
  358. package/dist/observability.cjs.map +1 -0
  359. package/dist/observability.d.mts +335 -0
  360. package/dist/observability.d.ts +335 -0
  361. package/dist/observability.mjs +16 -0
  362. package/dist/observability.mjs.map +1 -0
  363. package/dist/params-BALtrRim.d.ts +15 -0
  364. package/dist/params-ry-lxqmy.d.mts +15 -0
  365. package/dist/plugin-BJDf43dc.d.mts +165 -0
  366. package/dist/plugin-BJDf43dc.d.ts +165 -0
  367. package/dist/plugin.cjs +23470 -0
  368. package/dist/plugin.cjs.map +1 -1
  369. package/dist/plugin.d.mts +22 -0
  370. package/dist/plugin.d.ts +22 -0
  371. package/dist/plugin.mjs +8 -7
  372. package/dist/production-runtime-4KKq1AVC.d.mts +79 -0
  373. package/dist/production-runtime-C_B79w2P.d.mts +28 -0
  374. package/dist/production-runtime-DDEM1D2q.d.ts +28 -0
  375. package/dist/production-runtime-DRsWDN2x.d.ts +79 -0
  376. package/dist/query/client.d.mts +61 -0
  377. package/dist/query/client.d.ts +61 -0
  378. package/dist/query/index.d.mts +90 -0
  379. package/dist/query/index.d.ts +90 -0
  380. package/dist/query/parsers.d.mts +25 -0
  381. package/dist/query/parsers.d.ts +25 -0
  382. package/dist/query/server.d.mts +55 -0
  383. package/dist/query/server.d.ts +55 -0
  384. package/dist/request-Dsq4kGW0.d.mts +6 -0
  385. package/dist/request-udtobOLv.d.ts +6 -0
  386. package/dist/request.d.mts +2 -0
  387. package/dist/request.d.ts +2 -0
  388. package/dist/resolver-DJqjLMg_.d.mts +14 -0
  389. package/dist/resolver-IH4RmPEl.d.ts +14 -0
  390. package/dist/route-runtime-DoOHzCAD.d.mts +38 -0
  391. package/dist/route-runtime-DoOHzCAD.d.ts +38 -0
  392. package/dist/router.d.mts +36 -0
  393. package/dist/router.d.ts +36 -0
  394. package/dist/routes.d.mts +224 -0
  395. package/dist/routes.d.ts +224 -0
  396. package/dist/runtime-9nQjVM7X.d.mts +206 -0
  397. package/dist/runtime-Cxpq6xZN.d.mts +27 -0
  398. package/dist/runtime-DgeS2skB.d.ts +206 -0
  399. package/dist/runtime-bv63eUiO.d.ts +27 -0
  400. package/dist/server-action-security.d.mts +43 -0
  401. package/dist/server-action-security.d.ts +43 -0
  402. package/dist/server-fn-client.d.mts +32 -0
  403. package/dist/server-fn-client.d.ts +32 -0
  404. package/dist/server-fn.d.mts +93 -0
  405. package/dist/server-fn.d.ts +93 -0
  406. package/dist/server-plugins.d.mts +55 -0
  407. package/dist/server-plugins.d.ts +55 -0
  408. package/dist/server-query-client.d.mts +50 -0
  409. package/dist/server-query-client.d.ts +50 -0
  410. package/dist/server-query.d.mts +36 -0
  411. package/dist/server-query.d.ts +36 -0
  412. package/dist/server.cjs +731 -447
  413. package/dist/server.cjs.map +1 -1
  414. package/dist/server.d.mts +48 -0
  415. package/dist/server.d.ts +48 -0
  416. package/dist/server.mjs +9 -8
  417. package/dist/server.mjs.map +1 -1
  418. package/dist/storage.d.mts +52 -0
  419. package/dist/storage.d.ts +52 -0
  420. package/dist/testing.d.mts +101 -0
  421. package/dist/testing.d.ts +101 -0
  422. package/dist/transport-BmbGTXA5.d.mts +49 -0
  423. package/dist/transport-BmbGTXA5.d.ts +49 -0
  424. package/dist/types-BMxWr97v.d.mts +81 -0
  425. package/dist/types-BMxWr97v.d.ts +81 -0
  426. package/dist/types-C9N-nk5R.d.mts +53 -0
  427. package/dist/types-C9N-nk5R.d.ts +53 -0
  428. package/dist/types-D1A6-XvH.d.mts +73 -0
  429. package/dist/types-D1A6-XvH.d.ts +73 -0
  430. package/dist/utils-B-cUHwoK.d.ts +23 -0
  431. package/dist/utils-Cm41AefV.d.mts +23 -0
  432. package/dist/version.cjs +1 -1
  433. package/dist/version.cjs.map +1 -1
  434. package/dist/version.d.mts +3 -0
  435. package/dist/version.d.ts +3 -0
  436. package/dist/version.mjs +1 -1
  437. package/dist/vite.cjs +682 -437
  438. package/dist/vite.cjs.map +1 -1
  439. package/dist/vite.d.mts +22 -0
  440. package/dist/vite.d.ts +22 -0
  441. package/dist/vite.mjs +6 -5
  442. package/dist/workflows.d.mts +110 -0
  443. package/dist/workflows.d.ts +110 -0
  444. package/package.json +3 -2
  445. package/types/client.d.ts +1 -1
  446. package/types/image.d.ts +4 -0
  447. package/types/images.d.ts +59 -0
package/dist/api.cjs ADDED
@@ -0,0 +1,4100 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/api/index.ts
32
+ var api_exports = {};
33
+ __export(api_exports, {
34
+ APIClientError: () => APIClientError,
35
+ APIRouteManager: () => APIRouteManager,
36
+ API_ROUTE_METHODS: () => API_ROUTE_METHODS,
37
+ DELETE: () => DELETE,
38
+ EndpointFailure: () => EndpointFailure,
39
+ FARM_API_ROUTE_META_SYMBOL: () => FARM_API_ROUTE_META_SYMBOL,
40
+ FARM_API_ROUTE_REF_SYMBOL: () => FARM_API_ROUTE_REF_SYMBOL,
41
+ GET: () => GET,
42
+ HEAD: () => HEAD,
43
+ OPTIONS: () => OPTIONS,
44
+ PATCH: () => PATCH,
45
+ POST: () => POST,
46
+ PUT: () => PUT,
47
+ createAPIClient: () => createAPIClient,
48
+ createEndpoint: () => createEndpoint,
49
+ createServerAPIClient: () => createServerAPIClient,
50
+ farmApiPlugin: () => farmApiPlugin,
51
+ getAPIRouteRefMetadata: () => getAPIRouteRefMetadata,
52
+ invokeAPIRouteEndpoint: () => invokeAPIRouteEndpoint,
53
+ isAPIRouteRef: () => isAPIRouteRef,
54
+ isEndpointFailure: () => isEndpointFailure,
55
+ isFarmAPIStream: () => isFarmAPIStream,
56
+ isJSONStreamResponse: () => isJSONStreamResponse,
57
+ isMultipartSchema: () => isMultipartSchema,
58
+ isWebResponse: () => isWebResponse,
59
+ jsonStream: () => jsonStream,
60
+ matchAPIRoute: () => matchAPIRoute,
61
+ multipart: () => multipart,
62
+ normalizeRouteResponse: () => normalizeRouteResponse,
63
+ readJSONStream: () => readJSONStream,
64
+ toFormData: () => toFormData
65
+ });
66
+ module.exports = __toCommonJS(api_exports);
67
+
68
+ // src/api/endpoint.ts
69
+ var import_better_call = require("better-call");
70
+
71
+ // src/observability.ts
72
+ var runtimeHandlers = /* @__PURE__ */ new Set();
73
+ var observabilityState = {
74
+ logs: false,
75
+ handlers: []
76
+ };
77
+ function emitFarmEvent(input) {
78
+ const event = {
79
+ timestamp: Date.now(),
80
+ level: inferFarmEventLevel(input.type),
81
+ ...input
82
+ };
83
+ if (!shouldEmitFarmEvent(event)) {
84
+ return event;
85
+ }
86
+ if (observabilityState.logs) {
87
+ logFarmEvent(event);
88
+ }
89
+ for (const handler of [...observabilityState.handlers, ...runtimeHandlers]) {
90
+ try {
91
+ Promise.resolve(handler(event)).catch((error) => {
92
+ console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
93
+ });
94
+ } catch (error) {
95
+ console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
96
+ }
97
+ }
98
+ return event;
99
+ }
100
+ __name(emitFarmEvent, "emitFarmEvent");
101
+ function shouldEmitFarmEvent(event) {
102
+ if (!observabilityState.logs && observabilityState.handlers.length === 0 && runtimeHandlers.size === 0) {
103
+ return false;
104
+ }
105
+ if (observabilityState.events && !observabilityState.events.has(event.type)) {
106
+ return false;
107
+ }
108
+ return true;
109
+ }
110
+ __name(shouldEmitFarmEvent, "shouldEmitFarmEvent");
111
+ function inferFarmEventLevel(type) {
112
+ if (type === "error" || type.endsWith(".error") || type.endsWith(".failed")) {
113
+ return "error";
114
+ }
115
+ if (type.endsWith(".bypass") || type.endsWith(".invalidated") || type.endsWith(".stale") || type.endsWith(".notFound")) {
116
+ return "warn";
117
+ }
118
+ if (type.endsWith(".hit") || type.endsWith(".miss") || type.endsWith(".start") || type.endsWith(".shellReady")) {
119
+ return "debug";
120
+ }
121
+ return "info";
122
+ }
123
+ __name(inferFarmEventLevel, "inferFarmEventLevel");
124
+ function logFarmEvent(event) {
125
+ const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;
126
+ switch (event.level) {
127
+ case "error":
128
+ console.error(message);
129
+ break;
130
+ case "warn":
131
+ console.warn(message);
132
+ break;
133
+ default:
134
+ console.log(message);
135
+ break;
136
+ }
137
+ }
138
+ __name(logFarmEvent, "logFarmEvent");
139
+ function formatFarmEventDetails(event) {
140
+ const details = [];
141
+ const record = event;
142
+ for (const key of [
143
+ "route",
144
+ "pathname",
145
+ "method",
146
+ "status",
147
+ "key",
148
+ "tag",
149
+ "path",
150
+ "reason",
151
+ "durationMs",
152
+ "integration",
153
+ "operation",
154
+ "plugin",
155
+ "hook",
156
+ "target",
157
+ "count"
158
+ ]) {
159
+ const value = record[key];
160
+ if (value !== void 0) {
161
+ details.push(`${key}=${formatDetailValue(value)}`);
162
+ }
163
+ }
164
+ return details.length > 0 ? ` ${details.join(" ")}` : "";
165
+ }
166
+ __name(formatFarmEventDetails, "formatFarmEventDetails");
167
+ function formatDetailValue(value) {
168
+ if (typeof value === "string") {
169
+ return value;
170
+ }
171
+ if (typeof value === "number" || typeof value === "boolean") {
172
+ return String(value);
173
+ }
174
+ try {
175
+ return JSON.stringify(value);
176
+ } catch {
177
+ return String(value);
178
+ }
179
+ }
180
+ __name(formatDetailValue, "formatDetailValue");
181
+ function formatError(error) {
182
+ return error instanceof Error ? error.message : String(error);
183
+ }
184
+ __name(formatError, "formatError");
185
+
186
+ // src/cache-invalidation.ts
187
+ var FARM_CACHE_INVALIDATION_HEADER = "x-farm-cache-invalidations";
188
+ var FARM_CACHE_INVALIDATION_STATE = /* @__PURE__ */ Symbol.for("farm.cacheInvalidationState");
189
+ var globalState = globalThis;
190
+ function getFarmCacheInvalidationState() {
191
+ return globalState[FARM_CACHE_INVALIDATION_STATE] ?? (globalState[FARM_CACHE_INVALIDATION_STATE] = {
192
+ listeners: /* @__PURE__ */ new Set(),
193
+ taskListeners: /* @__PURE__ */ new Set()
194
+ });
195
+ }
196
+ __name(getFarmCacheInvalidationState, "getFarmCacheInvalidationState");
197
+ function notifyFarmCacheInvalidation(key) {
198
+ if (typeof key !== "string" || key.length === 0) return;
199
+ for (const listener of getFarmCacheInvalidationState().listeners) {
200
+ listener(key);
201
+ }
202
+ }
203
+ __name(notifyFarmCacheInvalidation, "notifyFarmCacheInvalidation");
204
+ function notifyFarmCacheTask(task) {
205
+ for (const listener of getFarmCacheInvalidationState().taskListeners) {
206
+ listener(task);
207
+ }
208
+ }
209
+ __name(notifyFarmCacheTask, "notifyFarmCacheTask");
210
+ function applyFarmCacheInvalidations(keys) {
211
+ if (!Array.isArray(keys)) return;
212
+ for (const key of keys) {
213
+ if (typeof key === "string") {
214
+ notifyFarmCacheInvalidation(key);
215
+ }
216
+ }
217
+ }
218
+ __name(applyFarmCacheInvalidations, "applyFarmCacheInvalidations");
219
+ function encodeFarmCacheInvalidations(keys) {
220
+ const normalized = Array.from(
221
+ new Set(keys.filter((key) => typeof key === "string" && key.length > 0))
222
+ );
223
+ if (normalized.length === 0) return null;
224
+ return encodeURIComponent(JSON.stringify(normalized));
225
+ }
226
+ __name(encodeFarmCacheInvalidations, "encodeFarmCacheInvalidations");
227
+ function decodeFarmCacheInvalidations(value) {
228
+ if (!value) return [];
229
+ try {
230
+ const parsed = JSON.parse(decodeURIComponent(value));
231
+ return Array.isArray(parsed) ? Array.from(
232
+ new Set(parsed.filter((key) => typeof key === "string" && key.length > 0))
233
+ ) : [];
234
+ } catch {
235
+ return [];
236
+ }
237
+ }
238
+ __name(decodeFarmCacheInvalidations, "decodeFarmCacheInvalidations");
239
+ function subscribeFarmCacheInvalidation(listener) {
240
+ const state = getFarmCacheInvalidationState();
241
+ state.listeners.add(listener);
242
+ return () => state.listeners.delete(listener);
243
+ }
244
+ __name(subscribeFarmCacheInvalidation, "subscribeFarmCacheInvalidation");
245
+
246
+ // src/i18n/bridge.ts
247
+ var FARM_I18N_SNAPSHOT_RESOLVER = /* @__PURE__ */ Symbol.for("farm.i18n.snapshotResolver");
248
+ function _setFarmI18nSnapshotResolver(resolver) {
249
+ globalThis[FARM_I18N_SNAPSHOT_RESOLVER] = resolver;
250
+ }
251
+ __name(_setFarmI18nSnapshotResolver, "_setFarmI18nSnapshotResolver");
252
+
253
+ // src/cache.ts
254
+ var _FarmDataCache = class _FarmDataCache {
255
+ constructor(config = {}) {
256
+ this.entries = /* @__PURE__ */ new Map();
257
+ this.inflight = /* @__PURE__ */ new Map();
258
+ this.invalidatedTagVersions = /* @__PURE__ */ new Map();
259
+ this.version = 0;
260
+ this.namespace = "farm";
261
+ this.local = true;
262
+ this.lease = {
263
+ enabled: true,
264
+ ttlMs: 1e4,
265
+ waitTimeoutMs: 1e4,
266
+ pollIntervalMs: 25
267
+ };
268
+ this.configure(config);
269
+ }
270
+ configure(config = {}) {
271
+ this.adapter = config.adapter;
272
+ this.namespace = normalizeCacheNamespace(config.namespace || "farm");
273
+ this.local = !config.adapter;
274
+ this.lease = config.lease === false ? { ...this.lease, enabled: false } : {
275
+ enabled: true,
276
+ ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 1e4, "cache.lease.ttlMs"),
277
+ waitTimeoutMs: normalizePositiveDuration(
278
+ config.lease?.waitTimeoutMs,
279
+ 1e4,
280
+ "cache.lease.waitTimeoutMs"
281
+ ),
282
+ pollIntervalMs: normalizePositiveDuration(
283
+ config.lease?.pollIntervalMs,
284
+ 25,
285
+ "cache.lease.pollIntervalMs"
286
+ )
287
+ };
288
+ if (!this.local) {
289
+ this.entries.clear();
290
+ this.inflight.clear();
291
+ this.invalidatedTagVersions.clear();
292
+ this.version = 0;
293
+ }
294
+ }
295
+ get adapterName() {
296
+ return this.adapter?.name || (this.adapter ? "custom" : "memory");
297
+ }
298
+ get hasAdapter() {
299
+ return this.adapter !== void 0;
300
+ }
301
+ get size() {
302
+ return this.entries.size;
303
+ }
304
+ get(key, options = {}) {
305
+ return this.getEntry(key, options)?.value;
306
+ }
307
+ getEntry(key, options = {}) {
308
+ const entry = this.entries.get(key);
309
+ if (!entry) {
310
+ emitFarmEvent({ type: "cache.miss", key });
311
+ return void 0;
312
+ }
313
+ const stale = this.isStale(entry, options.now);
314
+ if (stale) {
315
+ emitFarmEvent({
316
+ type: "cache.stale",
317
+ key,
318
+ tags: Array.from(entry.tags),
319
+ revalidate: entry.revalidate
320
+ });
321
+ }
322
+ if (!options.allowStale && stale) {
323
+ emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
324
+ return void 0;
325
+ }
326
+ emitFarmEvent({
327
+ type: "cache.hit",
328
+ key,
329
+ tags: Array.from(entry.tags),
330
+ revalidate: entry.revalidate,
331
+ stale
332
+ });
333
+ return this.toPublicEntry(entry);
334
+ }
335
+ async getEntryAsync(key, options = {}) {
336
+ if (this.local) {
337
+ const localEntry = this.getEntry(key, options);
338
+ if (localEntry) return localEntry;
339
+ }
340
+ if (!this.adapter) {
341
+ return this.local ? void 0 : this.getEntry(key, options);
342
+ }
343
+ const entry = await this.adapter.get(this.createAdapterKey(key));
344
+ if (!entry) {
345
+ emitFarmEvent({ type: "cache.miss", key });
346
+ return void 0;
347
+ }
348
+ assertFarmCacheEntry(entry, key);
349
+ const stale = await this.isAdapterEntryStale(entry, options.now);
350
+ if (stale) {
351
+ emitFarmEvent({
352
+ type: "cache.stale",
353
+ key,
354
+ tags: [...entry.tags],
355
+ revalidate: entry.revalidate
356
+ });
357
+ if (!options.allowStale) {
358
+ emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
359
+ return void 0;
360
+ }
361
+ }
362
+ emitFarmEvent({
363
+ type: "cache.hit",
364
+ key,
365
+ tags: [...entry.tags],
366
+ revalidate: entry.revalidate,
367
+ stale
368
+ });
369
+ if (this.local && !stale) {
370
+ this.hydrateLocalEntry(entry);
371
+ }
372
+ return { ...entry, key };
373
+ }
374
+ set(key, value, options = {}) {
375
+ const tags = /* @__PURE__ */ new Set();
376
+ for (const tag of options.tags ?? []) {
377
+ tags.add(normalizeCacheTag(tag));
378
+ }
379
+ for (const routePath of options.paths ?? []) {
380
+ tags.add(createPathCacheTag(routePath));
381
+ }
382
+ const entry = {
383
+ key,
384
+ value,
385
+ tags,
386
+ tagVersions: void 0,
387
+ createdAt: options.createdAt ?? Date.now(),
388
+ createdVersion: ++this.version,
389
+ revalidate: normalizeRevalidate(options.revalidate)
390
+ };
391
+ this.entries.set(key, entry);
392
+ emitFarmEvent({
393
+ type: "cache.set",
394
+ key,
395
+ tags: Array.from(tags),
396
+ revalidate: entry.revalidate
397
+ });
398
+ return this.toPublicEntry(entry);
399
+ }
400
+ async setAsync(key, value, options = {}, tagVersions) {
401
+ const tags = normalizeCacheOptionsTags(options);
402
+ const capturedVersions = tagVersions ?? await this.getAdapterTagVersions(Array.from(tags.values()));
403
+ const entry = {
404
+ key,
405
+ value,
406
+ tags: Array.from(tags),
407
+ tagVersions: capturedVersions,
408
+ createdAt: options.createdAt ?? Date.now(),
409
+ createdVersion: ++this.version,
410
+ revalidate: normalizeRevalidate(options.revalidate)
411
+ };
412
+ if (this.local) {
413
+ this.hydrateLocalEntry(entry);
414
+ }
415
+ if (this.adapter) {
416
+ await this.adapter.set(this.createAdapterKey(key), entry);
417
+ }
418
+ emitFarmEvent({
419
+ type: "cache.set",
420
+ key,
421
+ tags: [...entry.tags],
422
+ revalidate: entry.revalidate
423
+ });
424
+ return entry;
425
+ }
426
+ delete(key) {
427
+ const deleted = this.entries.delete(key);
428
+ emitFarmEvent({ type: "cache.delete", key, deleted });
429
+ return deleted;
430
+ }
431
+ async deleteAsync(key) {
432
+ const deleted = this.entries.delete(key);
433
+ if (this.adapter) {
434
+ await this.adapter.delete(this.createAdapterKey(key));
435
+ }
436
+ emitFarmEvent({ type: "cache.delete", key, deleted: this.adapter ? true : deleted });
437
+ return this.adapter ? true : deleted;
438
+ }
439
+ clear() {
440
+ const count = this.entries.size;
441
+ this.entries.clear();
442
+ this.inflight.clear();
443
+ this.invalidatedTagVersions.clear();
444
+ this.version = 0;
445
+ emitFarmEvent({ type: "cache.clear", count });
446
+ }
447
+ async clearAsync() {
448
+ this.clear();
449
+ await this.adapter?.clear?.();
450
+ }
451
+ isStale(entry, now = Date.now()) {
452
+ if (typeof entry.revalidate === "number" && entry.revalidate > 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
453
+ return true;
454
+ }
455
+ for (const tag of entry.tags) {
456
+ const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));
457
+ if (typeof invalidatedVersion === "number" && typeof entry.createdVersion === "number" && invalidatedVersion > entry.createdVersion) {
458
+ return true;
459
+ }
460
+ }
461
+ return false;
462
+ }
463
+ async isStaleAsync(entry, now = Date.now()) {
464
+ if (this.adapter) {
465
+ return this.isAdapterEntryStale(entry, now);
466
+ }
467
+ return this.isStale(entry, now);
468
+ }
469
+ revalidateTag(tag, options = {}) {
470
+ const normalized = normalizeCacheTag(tag);
471
+ const count = this.invalidateTag(normalized);
472
+ emitFarmEvent(
473
+ options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
474
+ );
475
+ return count;
476
+ }
477
+ async revalidateTagAsync(tag, options = {}) {
478
+ const normalized = normalizeCacheTag(tag);
479
+ const count = this.invalidateTag(normalized);
480
+ await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);
481
+ emitFarmEvent(
482
+ options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
483
+ );
484
+ return count;
485
+ }
486
+ revalidatePath(routePath) {
487
+ const normalizedPath = normalizeRevalidatePath(routePath);
488
+ const pathTag = createPathCacheTag(normalizedPath);
489
+ const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
490
+ const count = this.invalidateTag(pathTag);
491
+ emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
492
+ if (pprCount > 0) {
493
+ emitFarmEvent({
494
+ type: "ppr.shell.invalidated",
495
+ route: normalizedPath,
496
+ reason: "revalidatePath",
497
+ count: pprCount
498
+ });
499
+ }
500
+ return count;
501
+ }
502
+ async revalidatePathAsync(routePath) {
503
+ const normalizedPath = normalizeRevalidatePath(routePath);
504
+ const pathTag = createPathCacheTag(normalizedPath);
505
+ const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
506
+ const count = this.invalidateTag(pathTag);
507
+ await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);
508
+ emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
509
+ if (pprCount > 0) {
510
+ emitFarmEvent({
511
+ type: "ppr.shell.invalidated",
512
+ route: normalizedPath,
513
+ reason: "revalidatePath",
514
+ count: pprCount
515
+ });
516
+ }
517
+ return count;
518
+ }
519
+ async getOrSet(key, producer, options = {}) {
520
+ const cached = await this.getEntryAsync(key);
521
+ if (cached) {
522
+ return cached.value;
523
+ }
524
+ const inflight = this.inflight.get(key);
525
+ if (inflight) {
526
+ emitFarmEvent({ type: "cache.dedupe", key });
527
+ return inflight;
528
+ }
529
+ const tags = Array.from(normalizeCacheOptionsTags(options));
530
+ const promise = this.fillCacheEntry(key, producer, options, tags).catch((error) => {
531
+ emitFarmEvent({ type: "cache.error", key, operation: "set", error });
532
+ throw error;
533
+ }).finally(() => {
534
+ this.inflight.delete(key);
535
+ });
536
+ this.inflight.set(key, promise);
537
+ return promise;
538
+ }
539
+ async fillCacheEntry(key, producer, options, tags) {
540
+ const leaseKey = `${this.namespace}:lease:${key}`;
541
+ let leaseToken;
542
+ if (this.adapter?.acquireLease && this.adapter.releaseLease && this.lease.enabled) {
543
+ leaseToken = await this.adapter.acquireLease(leaseKey, this.lease.ttlMs);
544
+ if (!leaseToken) {
545
+ const shared = await this.waitForAdapterEntry(key);
546
+ if (shared) {
547
+ emitFarmEvent({ type: "cache.dedupe", key });
548
+ return shared.value;
549
+ }
550
+ leaseToken = await this.adapter.acquireLease(leaseKey, this.lease.ttlMs);
551
+ }
552
+ }
553
+ try {
554
+ const initialTagVersions = await this.getAdapterTagVersions(tags);
555
+ const value = await producer();
556
+ await this.setAsync(key, value, options, initialTagVersions);
557
+ return value;
558
+ } finally {
559
+ if (leaseToken && this.adapter?.releaseLease) {
560
+ await this.adapter.releaseLease(leaseKey, leaseToken);
561
+ }
562
+ }
563
+ }
564
+ async waitForAdapterEntry(key) {
565
+ const deadline = Date.now() + this.lease.waitTimeoutMs;
566
+ while (Date.now() < deadline) {
567
+ await delay(this.lease.pollIntervalMs);
568
+ const entry = await this.getEntryAsync(key);
569
+ if (entry) return entry;
570
+ }
571
+ return void 0;
572
+ }
573
+ countEntriesForTag(tag) {
574
+ let count = 0;
575
+ for (const entry of this.entries.values()) {
576
+ if (entry.tags.has(tag)) {
577
+ count++;
578
+ }
579
+ }
580
+ return count;
581
+ }
582
+ countEntriesForTags(tags) {
583
+ let count = 0;
584
+ for (const entry of this.entries.values()) {
585
+ if (tags.every((tag) => entry.tags.has(tag))) {
586
+ count++;
587
+ }
588
+ }
589
+ return count;
590
+ }
591
+ invalidateTag(normalizedTag) {
592
+ this.invalidatedTagVersions.set(normalizedTag, ++this.version);
593
+ return this.countEntriesForTag(normalizedTag);
594
+ }
595
+ toPublicEntry(entry) {
596
+ return {
597
+ key: entry.key,
598
+ value: entry.value,
599
+ tags: Array.from(entry.tags),
600
+ tagVersions: entry.tagVersions,
601
+ createdAt: entry.createdAt,
602
+ createdVersion: entry.createdVersion,
603
+ revalidate: entry.revalidate
604
+ };
605
+ }
606
+ hydrateLocalEntry(entry) {
607
+ this.entries.set(entry.key, {
608
+ key: entry.key,
609
+ value: entry.value,
610
+ tags: new Set(entry.tags.map(normalizeCacheTag)),
611
+ tagVersions: entry.tagVersions,
612
+ createdAt: entry.createdAt,
613
+ createdVersion: entry.createdVersion ?? ++this.version,
614
+ revalidate: normalizeRevalidate(entry.revalidate)
615
+ });
616
+ }
617
+ createAdapterKey(key) {
618
+ return `${this.namespace}:entry:${key}`;
619
+ }
620
+ createAdapterTag(tag) {
621
+ return `${this.namespace}:tag:${tag}`;
622
+ }
623
+ async getAdapterTagVersions(tags) {
624
+ if (!this.adapter?.getTagVersions || tags.length === 0) return {};
625
+ const normalized = tags.map(normalizeCacheTag);
626
+ const physicalTags = normalized.map((tag) => this.createAdapterTag(tag));
627
+ const versions = await this.adapter.getTagVersions(physicalTags);
628
+ return Object.fromEntries(
629
+ normalized.map((tag, index) => [
630
+ tag,
631
+ normalizeAdapterVersion(versions[physicalTags[index]])
632
+ ])
633
+ );
634
+ }
635
+ async isAdapterEntryStale(entry, now = Date.now()) {
636
+ if (typeof entry.revalidate === "number" && entry.revalidate > 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
637
+ return true;
638
+ }
639
+ const currentVersions = await this.getAdapterTagVersions(entry.tags);
640
+ for (const tag of entry.tags) {
641
+ if (normalizeAdapterVersion(currentVersions[tag]) > normalizeAdapterVersion(entry.tagVersions?.[tag])) {
642
+ return true;
643
+ }
644
+ }
645
+ return false;
646
+ }
647
+ };
648
+ __name(_FarmDataCache, "FarmDataCache");
649
+ var FarmDataCache = _FarmDataCache;
650
+ var FARM_DATA_CACHE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.dataCache");
651
+ var farmDataCacheGlobal = globalThis;
652
+ var sharedFarmDataCache = farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ?? (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] = new FarmDataCache());
653
+ var functionIds = /* @__PURE__ */ new WeakMap();
654
+ var nextFunctionId = 0;
655
+ function getFarmDataCache() {
656
+ return sharedFarmDataCache;
657
+ }
658
+ __name(getFarmDataCache, "getFarmDataCache");
659
+ function updateTag(tag) {
660
+ const cache = getFarmDataCache();
661
+ if (cache.hasAdapter) {
662
+ const task = cache.revalidateTagAsync(tag, { source: "updateTag" }).then(() => void 0);
663
+ notifyFarmCacheTask(task);
664
+ return task;
665
+ }
666
+ cache.revalidateTag(tag, { source: "updateTag" });
667
+ }
668
+ __name(updateTag, "updateTag");
669
+ function revalidatePath(routePath) {
670
+ const cache = getFarmDataCache();
671
+ if (cache.hasAdapter) {
672
+ const task = cache.revalidatePathAsync(routePath).then(() => void 0);
673
+ notifyFarmCacheTask(task);
674
+ return task;
675
+ }
676
+ cache.revalidatePath(routePath);
677
+ }
678
+ __name(revalidatePath, "revalidatePath");
679
+ function invalidate(key) {
680
+ const clientKey = createRouteDataCacheKey(key);
681
+ const task = updateTag(createRouteDataCacheTag(key));
682
+ notifyFarmCacheInvalidation(clientKey);
683
+ return task;
684
+ }
685
+ __name(invalidate, "invalidate");
686
+ async function applyFarmCacheInvalidationTargets(targets) {
687
+ if (!Array.isArray(targets)) {
688
+ throw new TypeError("Cache invalidations must resolve to an array of targets.");
689
+ }
690
+ const clientKeys = [];
691
+ for (const target of targets) {
692
+ assertFarmCacheInvalidationTarget(target);
693
+ if ("key" in target) {
694
+ await invalidate(target.key);
695
+ clientKeys.push(createRouteDataCacheKey(target.key));
696
+ } else if ("path" in target) {
697
+ await revalidatePath(target.path);
698
+ } else {
699
+ await updateTag(target.tag);
700
+ }
701
+ }
702
+ return Array.from(new Set(clientKeys));
703
+ }
704
+ __name(applyFarmCacheInvalidationTargets, "applyFarmCacheInvalidationTargets");
705
+ function createPathCacheTag(routePath) {
706
+ return `path:${normalizeRevalidatePath(routePath)}`;
707
+ }
708
+ __name(createPathCacheTag, "createPathCacheTag");
709
+ function createRouteDataCacheTag(key) {
710
+ return `route-data:${createRouteDataCacheKey(key)}`;
711
+ }
712
+ __name(createRouteDataCacheTag, "createRouteDataCacheTag");
713
+ function createRouteDataCacheKey(key) {
714
+ return createFarmCacheKey(Array.isArray(key) ? key : [key]);
715
+ }
716
+ __name(createRouteDataCacheKey, "createRouteDataCacheKey");
717
+ function normalizeRevalidatePath(routePath) {
718
+ if (typeof routePath !== "string") {
719
+ throw new TypeError("revalidatePath expects a path string.");
720
+ }
721
+ let normalized = routePath.trim();
722
+ if (!normalized) {
723
+ throw new Error("revalidatePath expects a non-empty path.");
724
+ }
725
+ try {
726
+ if (/^https?:\/\//.test(normalized)) {
727
+ normalized = new URL(normalized).pathname;
728
+ }
729
+ } catch {
730
+ }
731
+ normalized = normalized.split("?")[0] ?? normalized;
732
+ normalized = normalized.startsWith("/") ? normalized : `/${normalized}`;
733
+ normalized = normalized.replace(/\/{2,}/g, "/");
734
+ if (normalized.length > 1) {
735
+ normalized = normalized.replace(/\/+$/, "");
736
+ }
737
+ return normalized || "/";
738
+ }
739
+ __name(normalizeRevalidatePath, "normalizeRevalidatePath");
740
+ function createFarmCacheKey(parts) {
741
+ return stableSerialize(parts);
742
+ }
743
+ __name(createFarmCacheKey, "createFarmCacheKey");
744
+ function normalizeRevalidate(revalidate) {
745
+ if (revalidate === false || revalidate === void 0) {
746
+ return revalidate;
747
+ }
748
+ if (!Number.isFinite(revalidate) || revalidate <= 0) {
749
+ return void 0;
750
+ }
751
+ return revalidate;
752
+ }
753
+ __name(normalizeRevalidate, "normalizeRevalidate");
754
+ function normalizeCacheTag(tag) {
755
+ if (typeof tag !== "string") {
756
+ throw new TypeError("Cache tags must be strings.");
757
+ }
758
+ const normalized = tag.trim();
759
+ if (!normalized) {
760
+ throw new Error("Cache tags cannot be empty.");
761
+ }
762
+ return normalized;
763
+ }
764
+ __name(normalizeCacheTag, "normalizeCacheTag");
765
+ function normalizeCacheNamespace(namespace) {
766
+ if (typeof namespace !== "string") {
767
+ throw new TypeError("Cache namespace must be a string.");
768
+ }
769
+ const normalized = namespace.trim().replace(/:+$/g, "");
770
+ if (!normalized) {
771
+ throw new Error("Cache namespace cannot be empty.");
772
+ }
773
+ return normalized;
774
+ }
775
+ __name(normalizeCacheNamespace, "normalizeCacheNamespace");
776
+ function normalizeAdapterVersion(value) {
777
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
778
+ }
779
+ __name(normalizeAdapterVersion, "normalizeAdapterVersion");
780
+ function normalizePositiveDuration(value, fallback, name) {
781
+ if (value === void 0) return fallback;
782
+ if (!Number.isFinite(value) || value <= 0) {
783
+ throw new TypeError(`${name} must be a positive number of milliseconds.`);
784
+ }
785
+ return Math.floor(value);
786
+ }
787
+ __name(normalizePositiveDuration, "normalizePositiveDuration");
788
+ function delay(ms) {
789
+ return new Promise((resolve) => setTimeout(resolve, ms));
790
+ }
791
+ __name(delay, "delay");
792
+ function normalizeCacheOptionsTags(options) {
793
+ const tags = /* @__PURE__ */ new Set();
794
+ for (const tag of options.tags ?? []) {
795
+ tags.add(normalizeCacheTag(tag));
796
+ }
797
+ for (const routePath of options.paths ?? []) {
798
+ tags.add(createPathCacheTag(routePath));
799
+ }
800
+ return tags;
801
+ }
802
+ __name(normalizeCacheOptionsTags, "normalizeCacheOptionsTags");
803
+ function assertFarmCacheEntry(entry, expectedKey) {
804
+ if (!entry || typeof entry !== "object" || entry.key !== expectedKey || !Array.isArray(entry.tags) || typeof entry.createdAt !== "number") {
805
+ throw new TypeError(
806
+ `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`
807
+ );
808
+ }
809
+ }
810
+ __name(assertFarmCacheEntry, "assertFarmCacheEntry");
811
+ function assertFarmCacheInvalidationTarget(target) {
812
+ if (!target || typeof target !== "object") {
813
+ throw new TypeError("Cache invalidation targets must be { key }, { path }, or { tag }.");
814
+ }
815
+ if ("key" in target) {
816
+ const key = target.key;
817
+ if (typeof key === "string" || Array.isArray(key)) return;
818
+ } else if ("path" in target && typeof target.path === "string") {
819
+ return;
820
+ } else if ("tag" in target && typeof target.tag === "string") {
821
+ return;
822
+ }
823
+ throw new TypeError("Cache invalidation targets must contain a string/array key, path, or tag.");
824
+ }
825
+ __name(assertFarmCacheInvalidationTarget, "assertFarmCacheInvalidationTarget");
826
+ function getFunctionCacheIdentity(fn) {
827
+ if (fn.name) {
828
+ return `name:${fn.name}`;
829
+ }
830
+ let id = functionIds.get(fn);
831
+ if (!id) {
832
+ id = ++nextFunctionId;
833
+ functionIds.set(fn, id);
834
+ }
835
+ return `anonymous:${id}`;
836
+ }
837
+ __name(getFunctionCacheIdentity, "getFunctionCacheIdentity");
838
+ function stableSerialize(value, seen = /* @__PURE__ */ new WeakSet()) {
839
+ if (value === null) return "null";
840
+ if (value === void 0) return "undefined";
841
+ const valueType = typeof value;
842
+ if (valueType === "string") return JSON.stringify(value);
843
+ if (valueType === "number" || valueType === "boolean" || valueType === "bigint") {
844
+ return `${valueType}:${String(value)}`;
845
+ }
846
+ if (valueType === "symbol") {
847
+ return `symbol:${String(value)}`;
848
+ }
849
+ if (valueType === "function") {
850
+ return `function:${getFunctionCacheIdentity(value)}`;
851
+ }
852
+ if (value instanceof Date) {
853
+ return `date:${value.toISOString()}`;
854
+ }
855
+ if (value instanceof URL) {
856
+ return `url:${value.toString()}`;
857
+ }
858
+ if (value instanceof RegExp) {
859
+ return `regexp:${value.toString()}`;
860
+ }
861
+ if (Array.isArray(value)) {
862
+ return `[${value.map((item) => stableSerialize(item, seen)).join(",")}]`;
863
+ }
864
+ if (value && typeof value === "object") {
865
+ if (seen.has(value)) {
866
+ return "[Circular]";
867
+ }
868
+ seen.add(value);
869
+ const entries = Object.entries(value).sort(
870
+ ([a], [b]) => a.localeCompare(b)
871
+ );
872
+ const serialized = entries.map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`).join(",");
873
+ seen.delete(value);
874
+ return `{${serialized}}`;
875
+ }
876
+ return String(value);
877
+ }
878
+ __name(stableSerialize, "stableSerialize");
879
+
880
+ // src/api/transport.ts
881
+ function multipart(schema) {
882
+ if (!Object.isExtensible(schema) && !isMultipartSchema(schema)) {
883
+ throw new TypeError("multipart() requires an extensible schema object");
884
+ }
885
+ if (!isMultipartSchema(schema)) {
886
+ Object.defineProperty(schema, "__farmMultipartSchema", {
887
+ value: true,
888
+ configurable: false,
889
+ enumerable: false,
890
+ writable: false
891
+ });
892
+ }
893
+ return schema;
894
+ }
895
+ __name(multipart, "multipart");
896
+ function isMultipartSchema(value) {
897
+ return typeof value === "object" && value !== null && value.__farmMultipartSchema === true && typeof value.parse === "function";
898
+ }
899
+ __name(isMultipartSchema, "isMultipartSchema");
900
+ function toFormData(values) {
901
+ const formData = new FormData();
902
+ for (const [key, value] of Object.entries(values)) {
903
+ if (isUnsafeFormKey(key)) continue;
904
+ if (Array.isArray(value)) {
905
+ for (const entry of value) appendFormValue(formData, key, entry);
906
+ continue;
907
+ }
908
+ appendFormValue(formData, key, value);
909
+ }
910
+ return formData;
911
+ }
912
+ __name(toFormData, "toFormData");
913
+ function jsonStream(source, init = {}) {
914
+ const iterator = toAsyncIterator(source);
915
+ const encoder = new TextEncoder();
916
+ let finished = false;
917
+ const body = new ReadableStream(
918
+ {
919
+ async pull(controller) {
920
+ if (finished) return;
921
+ try {
922
+ const next = await iterator.next();
923
+ if (next.done) {
924
+ finished = true;
925
+ controller.close();
926
+ return;
927
+ }
928
+ controller.enqueue(encoder.encode(`${JSON.stringify(next.value)}
929
+ `));
930
+ } catch (error) {
931
+ finished = true;
932
+ controller.error(error);
933
+ }
934
+ },
935
+ async cancel(reason) {
936
+ finished = true;
937
+ await iterator.return?.(reason);
938
+ }
939
+ },
940
+ {
941
+ // Do not read the next application event until the response consumer
942
+ // requests another chunk.
943
+ highWaterMark: 0
944
+ }
945
+ );
946
+ const headers = new Headers(init.headers);
947
+ if (!headers.has("content-type")) {
948
+ headers.set("content-type", "application/x-ndjson; charset=utf-8");
949
+ }
950
+ headers.set("cache-control", headers.get("cache-control") ?? "no-store");
951
+ return new Response(body, {
952
+ ...init,
953
+ headers
954
+ });
955
+ }
956
+ __name(jsonStream, "jsonStream");
957
+ function isJSONStreamResponse(response) {
958
+ const contentType = response.headers?.get?.("content-type")?.toLowerCase() ?? "";
959
+ return contentType.includes("application/x-ndjson") || contentType.includes("application/ndjson");
960
+ }
961
+ __name(isJSONStreamResponse, "isJSONStreamResponse");
962
+ function readJSONStream(response) {
963
+ if (!response.body) {
964
+ throw new TypeError("Cannot read a JSON stream response without a body");
965
+ }
966
+ const reader = response.body.getReader();
967
+ const decoder = new TextDecoder();
968
+ let buffer = "";
969
+ let completed = false;
970
+ let claimed = false;
971
+ const iterator = {
972
+ async next() {
973
+ while (true) {
974
+ const lineEnd = buffer.indexOf("\n");
975
+ if (lineEnd >= 0) {
976
+ const line = buffer.slice(0, lineEnd).trim();
977
+ buffer = buffer.slice(lineEnd + 1);
978
+ if (!line) continue;
979
+ return { done: false, value: JSON.parse(line) };
980
+ }
981
+ if (completed) {
982
+ const line = buffer.trim();
983
+ buffer = "";
984
+ if (!line) return { done: true, value: void 0 };
985
+ return { done: false, value: JSON.parse(line) };
986
+ }
987
+ const chunk = await reader.read();
988
+ completed = chunk.done;
989
+ buffer += decoder.decode(chunk.value, { stream: !chunk.done });
990
+ }
991
+ },
992
+ async return() {
993
+ completed = true;
994
+ buffer = "";
995
+ await reader.cancel();
996
+ return { done: true, value: void 0 };
997
+ }
998
+ };
999
+ return {
1000
+ response,
1001
+ async cancel(reason) {
1002
+ completed = true;
1003
+ buffer = "";
1004
+ await reader.cancel(reason);
1005
+ },
1006
+ [Symbol.asyncIterator]() {
1007
+ if (claimed) {
1008
+ throw new TypeError("Farm API streams can only be consumed once");
1009
+ }
1010
+ claimed = true;
1011
+ return iterator;
1012
+ }
1013
+ };
1014
+ }
1015
+ __name(readJSONStream, "readJSONStream");
1016
+ function isFarmAPIStream(value) {
1017
+ return typeof value === "object" && value !== null && "response" in value && typeof value.cancel === "function" && typeof value[Symbol.asyncIterator] === "function";
1018
+ }
1019
+ __name(isFarmAPIStream, "isFarmAPIStream");
1020
+ function appendFormValue(formData, key, value) {
1021
+ if (value === void 0) return;
1022
+ if (value === null) {
1023
+ formData.append(key, "");
1024
+ return;
1025
+ }
1026
+ if (value instanceof Blob) {
1027
+ formData.append(key, value);
1028
+ return;
1029
+ }
1030
+ if (value instanceof Date) {
1031
+ formData.append(key, value.toISOString());
1032
+ return;
1033
+ }
1034
+ formData.append(key, String(value));
1035
+ }
1036
+ __name(appendFormValue, "appendFormValue");
1037
+ function isUnsafeFormKey(key) {
1038
+ return key === "__proto__" || key === "constructor" || key === "prototype";
1039
+ }
1040
+ __name(isUnsafeFormKey, "isUnsafeFormKey");
1041
+ function toAsyncIterator(source) {
1042
+ if (Symbol.asyncIterator in Object(source)) {
1043
+ return source[Symbol.asyncIterator]();
1044
+ }
1045
+ const iterator = source[Symbol.iterator]();
1046
+ return {
1047
+ next: /* @__PURE__ */ __name(async () => iterator.next(), "next"),
1048
+ return: iterator.return ? async (value) => iterator.return(value) : void 0
1049
+ };
1050
+ }
1051
+ __name(toAsyncIterator, "toAsyncIterator");
1052
+
1053
+ // src/api/endpoint.ts
1054
+ var _EndpointFailure = class _EndpointFailure extends Error {
1055
+ constructor(code, data, options) {
1056
+ super(options.message);
1057
+ this.name = "EndpointFailure";
1058
+ this.code = code;
1059
+ this.data = data;
1060
+ this.status = options.status;
1061
+ }
1062
+ };
1063
+ __name(_EndpointFailure, "EndpointFailure");
1064
+ var EndpointFailure = _EndpointFailure;
1065
+ function isEndpointFailure(value) {
1066
+ return value instanceof EndpointFailure;
1067
+ }
1068
+ __name(isEndpointFailure, "isEndpointFailure");
1069
+ function createEndpoint(pathOrOptions, optionsOrHandler, maybeHandler) {
1070
+ let path4;
1071
+ let options;
1072
+ let handler;
1073
+ if (typeof pathOrOptions === "string") {
1074
+ path4 = pathOrOptions;
1075
+ options = optionsOrHandler;
1076
+ handler = maybeHandler;
1077
+ } else {
1078
+ path4 = "";
1079
+ options = pathOrOptions;
1080
+ handler = optionsOrHandler;
1081
+ }
1082
+ if (typeof handler !== "function") {
1083
+ throw new TypeError("createEndpoint requires a handler function");
1084
+ }
1085
+ const middleware = normalizeEndpointMiddleware(options.middleware);
1086
+ const errors = normalizeEndpointErrors(options.errors);
1087
+ const fail = createEndpointFail(errors);
1088
+ const wrappedHandler = /* @__PURE__ */ __name((async (ctx) => {
1089
+ const execution = await runEndpointMiddleware(
1090
+ middleware,
1091
+ ctx,
1092
+ handler,
1093
+ fail,
1094
+ options.invalidates
1095
+ );
1096
+ return execution.result;
1097
+ }), "wrappedHandler");
1098
+ const {
1099
+ middleware: _middleware,
1100
+ errors: _errors,
1101
+ invalidates: _invalidates,
1102
+ ...betterCallOptions
1103
+ } = options;
1104
+ const endpoint = (0, import_better_call.createEndpoint)(
1105
+ path4 || "/__farm_auto_path__",
1106
+ betterCallOptions,
1107
+ wrappedHandler
1108
+ );
1109
+ endpoint.__path = path4 || void 0;
1110
+ endpoint.__method = options.method || "GET";
1111
+ endpoint.__autoPath = !path4;
1112
+ endpoint.__handler = wrappedHandler;
1113
+ endpoint.__farmInvoke = (ctx) => runEndpointMiddleware(middleware, ctx, handler, fail, options.invalidates);
1114
+ endpoint.__middleware = middleware;
1115
+ endpoint.__sourceHandler = handler;
1116
+ endpoint.__invalidates = options.invalidates;
1117
+ endpoint.__errors = errors;
1118
+ endpoint.__types = {
1119
+ body: options.body,
1120
+ inputBody: isMultipartSchema(options.body) ? "form-data" : options.body,
1121
+ query: options.query,
1122
+ headers: options.headers,
1123
+ response: null,
1124
+ errors
1125
+ };
1126
+ return endpoint;
1127
+ }
1128
+ __name(createEndpoint, "createEndpoint");
1129
+ var EMPTY_ENDPOINT_MIDDLEWARE = Object.freeze([]);
1130
+ var EMPTY_ENDPOINT_CONTEXT = Object.freeze(/* @__PURE__ */ Object.create(null));
1131
+ var UNSAFE_ENDPOINT_CONTEXT_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1132
+ function normalizeEndpointErrors(definitions) {
1133
+ if (definitions === void 0) return Object.freeze({});
1134
+ if (!isPlainEndpointContext(definitions)) {
1135
+ throw new TypeError("createEndpoint errors must be an object");
1136
+ }
1137
+ const normalized = /* @__PURE__ */ Object.create(null);
1138
+ for (const [code, definition] of Object.entries(definitions)) {
1139
+ if (!code.trim()) {
1140
+ throw new TypeError("Endpoint error codes cannot be empty");
1141
+ }
1142
+ if (!definition || typeof definition !== "object") {
1143
+ throw new TypeError(`Endpoint error "${code}" must be an object`);
1144
+ }
1145
+ if (!Number.isInteger(definition.status) || definition.status < 400 || definition.status > 599) {
1146
+ throw new TypeError(`Endpoint error "${code}" status must be an integer between 400 and 599`);
1147
+ }
1148
+ if (!definition.schema || typeof definition.schema.parse !== "function") {
1149
+ throw new TypeError(`Endpoint error "${code}" requires a schema with parse()`);
1150
+ }
1151
+ if (definition.message !== void 0 && typeof definition.message !== "string") {
1152
+ throw new TypeError(`Endpoint error "${code}" message must be a string`);
1153
+ }
1154
+ normalized[code] = Object.freeze({ ...definition });
1155
+ }
1156
+ return Object.freeze(normalized);
1157
+ }
1158
+ __name(normalizeEndpointErrors, "normalizeEndpointErrors");
1159
+ function createEndpointFail(definitions) {
1160
+ return ((code, data) => {
1161
+ const definition = definitions[code];
1162
+ if (!definition) {
1163
+ throw new TypeError(`Endpoint error "${code}" is not declared`);
1164
+ }
1165
+ const parsed = definition.schema.parse(data);
1166
+ throw new EndpointFailure(code, parsed, {
1167
+ status: definition.status,
1168
+ message: definition.message ?? "Request failed"
1169
+ });
1170
+ });
1171
+ }
1172
+ __name(createEndpointFail, "createEndpointFail");
1173
+ function normalizeEndpointMiddleware(middleware) {
1174
+ if (middleware === void 0) return EMPTY_ENDPOINT_MIDDLEWARE;
1175
+ if (!Array.isArray(middleware)) {
1176
+ throw new TypeError("createEndpoint middleware must be an array of functions");
1177
+ }
1178
+ const normalized = [...middleware];
1179
+ for (const entry of normalized) {
1180
+ if (typeof entry !== "function") {
1181
+ throw new TypeError("createEndpoint middleware entries must be functions");
1182
+ }
1183
+ }
1184
+ return Object.freeze(normalized);
1185
+ }
1186
+ __name(normalizeEndpointMiddleware, "normalizeEndpointMiddleware");
1187
+ async function runEndpointMiddleware(middleware, handlerContext, handler, fail, invalidations) {
1188
+ let context = createInitialEndpointContext(handlerContext.context);
1189
+ for (let index = 0; index < middleware.length; index++) {
1190
+ const result2 = await middleware[index]({ ...handlerContext, context });
1191
+ if (isEndpointResponse(result2)) {
1192
+ return {
1193
+ result: result2,
1194
+ context,
1195
+ handlerExecuted: false,
1196
+ invalidations: []
1197
+ };
1198
+ }
1199
+ if (result2 === false) {
1200
+ return {
1201
+ result: forbiddenEndpointResponse(),
1202
+ context,
1203
+ handlerExecuted: false,
1204
+ invalidations: []
1205
+ };
1206
+ }
1207
+ if (result2 === true) continue;
1208
+ if (!isPlainEndpointContext(result2)) {
1209
+ throw new TypeError(
1210
+ `Endpoint middleware ${index + 1} must return an object, true, false, or a Response`
1211
+ );
1212
+ }
1213
+ context = mergeEndpointContext(context, result2, index);
1214
+ }
1215
+ const result = await handler({ ...handlerContext, context, fail });
1216
+ return {
1217
+ result,
1218
+ context,
1219
+ handlerExecuted: true,
1220
+ invalidations: await applyEndpointInvalidations(
1221
+ invalidations,
1222
+ {
1223
+ ...handlerContext,
1224
+ context,
1225
+ result
1226
+ },
1227
+ result
1228
+ )
1229
+ };
1230
+ }
1231
+ __name(runEndpointMiddleware, "runEndpointMiddleware");
1232
+ async function applyEndpointInvalidations(declaration, context, result) {
1233
+ if (!declaration || isEndpointResponse(result) && result.status >= 400) {
1234
+ return [];
1235
+ }
1236
+ const targets = typeof declaration === "function" ? await declaration(context) : declaration;
1237
+ if (!Array.isArray(targets)) {
1238
+ throw new TypeError(
1239
+ "Endpoint invalidates must resolve to an array of { key }, { path }, or { tag } targets"
1240
+ );
1241
+ }
1242
+ return applyFarmCacheInvalidationTargets(targets);
1243
+ }
1244
+ __name(applyEndpointInvalidations, "applyEndpointInvalidations");
1245
+ function createInitialEndpointContext(value) {
1246
+ if (value === void 0 || value === null) return EMPTY_ENDPOINT_CONTEXT;
1247
+ if (!isPlainEndpointContext(value)) {
1248
+ throw new TypeError("Endpoint context must be a plain object");
1249
+ }
1250
+ return mergeEndpointContext(EMPTY_ENDPOINT_CONTEXT, value);
1251
+ }
1252
+ __name(createInitialEndpointContext, "createInitialEndpointContext");
1253
+ function mergeEndpointContext(current, added, middlewareIndex) {
1254
+ const next = Object.assign(/* @__PURE__ */ Object.create(null), current);
1255
+ for (const key of Reflect.ownKeys(added)) {
1256
+ if (!Object.prototype.propertyIsEnumerable.call(added, key)) continue;
1257
+ if (typeof key === "string" && UNSAFE_ENDPOINT_CONTEXT_KEYS.has(key)) {
1258
+ throw new TypeError(`Endpoint middleware cannot provide the unsafe context key "${key}"`);
1259
+ }
1260
+ if (Object.prototype.hasOwnProperty.call(current, key)) {
1261
+ const source = middlewareIndex === void 0 ? "Endpoint context" : `Endpoint middleware ${middlewareIndex + 1}`;
1262
+ throw new TypeError(`${source} cannot replace the existing context key "${String(key)}"`);
1263
+ }
1264
+ next[key] = added[key];
1265
+ }
1266
+ return Object.freeze(next);
1267
+ }
1268
+ __name(mergeEndpointContext, "mergeEndpointContext");
1269
+ function isPlainEndpointContext(value) {
1270
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1271
+ const prototype = Object.getPrototypeOf(value);
1272
+ return prototype === Object.prototype || prototype === null;
1273
+ }
1274
+ __name(isPlainEndpointContext, "isPlainEndpointContext");
1275
+ function isEndpointResponse(value) {
1276
+ return value instanceof Response || typeof value === "object" && value !== null && "headers" in value && "status" in value && typeof value.arrayBuffer === "function";
1277
+ }
1278
+ __name(isEndpointResponse, "isEndpointResponse");
1279
+ function forbiddenEndpointResponse() {
1280
+ return new Response(JSON.stringify({ error: "Forbidden" }), {
1281
+ status: 403,
1282
+ headers: { "Content-Type": "application/json" }
1283
+ });
1284
+ }
1285
+ __name(forbiddenEndpointResponse, "forbiddenEndpointResponse");
1286
+ function GET(...args) {
1287
+ if (args.length === 1) {
1288
+ return createEndpoint("", { method: "GET" }, args[0]);
1289
+ }
1290
+ return createEndpoint("", { ...args[0], method: "GET" }, args[1]);
1291
+ }
1292
+ __name(GET, "GET");
1293
+ function HEAD(...args) {
1294
+ if (args.length === 1) {
1295
+ return createEndpoint("", { method: "HEAD" }, args[0]);
1296
+ }
1297
+ return createEndpoint("", { ...args[0], method: "HEAD" }, args[1]);
1298
+ }
1299
+ __name(HEAD, "HEAD");
1300
+ function POST(...args) {
1301
+ if (args.length === 1) {
1302
+ return createEndpoint("", { method: "POST" }, args[0]);
1303
+ }
1304
+ return createEndpoint("", { ...args[0], method: "POST" }, args[1]);
1305
+ }
1306
+ __name(POST, "POST");
1307
+ function PUT(...args) {
1308
+ if (args.length === 1) {
1309
+ return createEndpoint("", { method: "PUT" }, args[0]);
1310
+ }
1311
+ return createEndpoint("", { ...args[0], method: "PUT" }, args[1]);
1312
+ }
1313
+ __name(PUT, "PUT");
1314
+ function DELETE(...args) {
1315
+ if (args.length === 1) {
1316
+ return createEndpoint("", { method: "DELETE" }, args[0]);
1317
+ }
1318
+ return createEndpoint("", { ...args[0], method: "DELETE" }, args[1]);
1319
+ }
1320
+ __name(DELETE, "DELETE");
1321
+ function PATCH(...args) {
1322
+ if (args.length === 1) {
1323
+ return createEndpoint("", { method: "PATCH" }, args[0]);
1324
+ }
1325
+ return createEndpoint("", { ...args[0], method: "PATCH" }, args[1]);
1326
+ }
1327
+ __name(PATCH, "PATCH");
1328
+ function OPTIONS(...args) {
1329
+ if (args.length === 1) {
1330
+ return createEndpoint("", { method: "OPTIONS" }, args[0]);
1331
+ }
1332
+ return createEndpoint("", { ...args[0], method: "OPTIONS" }, args[1]);
1333
+ }
1334
+ __name(OPTIONS, "OPTIONS");
1335
+
1336
+ // src/api/route-manager.ts
1337
+ var fs = __toESM(require("fs"));
1338
+ var path3 = __toESM(require("path"));
1339
+
1340
+ // src/utils.ts
1341
+ var import_path = __toESM(require("path"));
1342
+ function toViteModuleId(filePath, root) {
1343
+ if (!import_path.default.isAbsolute(filePath)) return filePath;
1344
+ const relativePath = import_path.default.relative(root, filePath);
1345
+ if (relativePath && !relativePath.startsWith("..") && !import_path.default.isAbsolute(relativePath)) {
1346
+ return `/${relativePath.split(import_path.default.sep).join("/")}`;
1347
+ }
1348
+ const normalizedPath = filePath.replace(/\\/g, "/");
1349
+ return normalizedPath.startsWith("/") ? `/@fs${normalizedPath}` : `/@fs/${normalizedPath}`;
1350
+ }
1351
+ __name(toViteModuleId, "toViteModuleId");
1352
+ var logger = {
1353
+ info: /* @__PURE__ */ __name((message) => console.log(`[info] ${message}`), "info"),
1354
+ success: /* @__PURE__ */ __name((message) => console.log(`[success] ${message}`), "success"),
1355
+ warn: /* @__PURE__ */ __name((message) => console.warn(`\u26A0\uFE0F ${message}`), "warn"),
1356
+ error: /* @__PURE__ */ __name((message) => console.error(`\u274C ${message}`), "error"),
1357
+ ready: /* @__PURE__ */ __name((message) => console.log(`${message}`), "ready"),
1358
+ event: /* @__PURE__ */ __name((message) => console.log(` ${message}`), "event")
1359
+ };
1360
+
1361
+ // src/routes.ts
1362
+ var import_react = require("react");
1363
+
1364
+ // src/route-runtime.ts
1365
+ function normalizeFarmRouteRuntimeConfig(value, source = "Route configuration") {
1366
+ if (!value) return {};
1367
+ const normalized = {};
1368
+ if (value.runtime !== void 0) {
1369
+ if (value.runtime !== "auto" && value.runtime !== "node" && value.runtime !== "edge") {
1370
+ throw new TypeError(`${source} runtime must be "auto", "node", or "edge"`);
1371
+ }
1372
+ normalized.runtime = value.runtime;
1373
+ }
1374
+ if (value.regions !== void 0) {
1375
+ if (value.regions === "auto") {
1376
+ normalized.regions = "auto";
1377
+ } else {
1378
+ if (!Array.isArray(value.regions) || value.regions.length === 0) {
1379
+ throw new TypeError(`${source} regions must be "auto" or a non-empty string array`);
1380
+ }
1381
+ const regions = Array.from(
1382
+ new Set(
1383
+ value.regions.map((region) => {
1384
+ if (typeof region !== "string" || !region.trim() || /[\u0000-\u001f\u007f]/.test(region)) {
1385
+ throw new TypeError(`${source} regions must contain non-empty region identifiers`);
1386
+ }
1387
+ return region.trim();
1388
+ })
1389
+ )
1390
+ );
1391
+ normalized.regions = regions;
1392
+ }
1393
+ }
1394
+ if (value.maxDuration !== void 0) {
1395
+ if (value.maxDuration === "auto") {
1396
+ normalized.maxDuration = "auto";
1397
+ } else if (typeof value.maxDuration !== "number" || !Number.isInteger(value.maxDuration) || value.maxDuration <= 0) {
1398
+ throw new TypeError(`${source} maxDuration must be "auto" or a positive integer in seconds`);
1399
+ } else {
1400
+ normalized.maxDuration = value.maxDuration;
1401
+ }
1402
+ }
1403
+ return normalized;
1404
+ }
1405
+ __name(normalizeFarmRouteRuntimeConfig, "normalizeFarmRouteRuntimeConfig");
1406
+ function getFarmRouteRuntimeConfig(value) {
1407
+ if (!value || typeof value !== "object") return {};
1408
+ const route = value;
1409
+ return {
1410
+ ...route.runtime !== void 0 ? { runtime: route.runtime } : {},
1411
+ ...route.regions !== void 0 ? { regions: route.regions } : {},
1412
+ ...route.maxDuration !== void 0 ? { maxDuration: route.maxDuration } : {}
1413
+ };
1414
+ }
1415
+ __name(getFarmRouteRuntimeConfig, "getFarmRouteRuntimeConfig");
1416
+
1417
+ // src/routes.ts
1418
+ var FARM_ROUTES_BRAND = /* @__PURE__ */ Symbol.for("farm.routes");
1419
+ var PROGRAMMATIC_ROUTE_FILE_NAMES = [
1420
+ "farm.route.ts",
1421
+ "farm.route.tsx",
1422
+ "farm.route.js",
1423
+ "farm.route.jsx",
1424
+ "farm.routes.ts",
1425
+ "farm.routes.tsx",
1426
+ "farm.routes.js",
1427
+ "farm.routes.jsx",
1428
+ "routes.ts",
1429
+ "routes.tsx",
1430
+ "routes.js",
1431
+ "routes.jsx"
1432
+ ];
1433
+ function defineRoutes(input) {
1434
+ const routes = typeof input === "function" ? input(routesBuilder) : input;
1435
+ const manifest = {
1436
+ __farmRoutes: true,
1437
+ routes: routes.map(normalizeProgrammaticRoute)
1438
+ };
1439
+ Object.defineProperty(manifest, FARM_ROUTES_BRAND, {
1440
+ value: true,
1441
+ enumerable: false
1442
+ });
1443
+ return manifest;
1444
+ }
1445
+ __name(defineRoutes, "defineRoutes");
1446
+ var routesBuilder = {
1447
+ page(path4, options) {
1448
+ return normalizeProgrammaticRoute({
1449
+ kind: "page",
1450
+ path: path4,
1451
+ ...options
1452
+ });
1453
+ },
1454
+ layout(path4, options) {
1455
+ return normalizeProgrammaticRoute({
1456
+ kind: "layout",
1457
+ path: path4,
1458
+ ...options
1459
+ });
1460
+ },
1461
+ api(path4, options) {
1462
+ const { render, runtime, regions, maxDuration, ...methods } = options;
1463
+ return normalizeProgrammaticRoute({
1464
+ kind: "api",
1465
+ path: path4,
1466
+ render,
1467
+ runtime,
1468
+ regions,
1469
+ maxDuration,
1470
+ methods: normalizeApiMethods(methods)
1471
+ });
1472
+ },
1473
+ redirect(source, destination, options = {}) {
1474
+ return normalizeProgrammaticRoute({
1475
+ kind: "redirect",
1476
+ source,
1477
+ destination,
1478
+ ...options
1479
+ });
1480
+ }
1481
+ };
1482
+ var page = routesBuilder.page;
1483
+ var layout = routesBuilder.layout;
1484
+ var api = routesBuilder.api;
1485
+ var redirect = routesBuilder.redirect;
1486
+ function isProgrammaticRoutesFileName(fileName) {
1487
+ const normalized = fileName.replace(/\\/g, "/");
1488
+ const baseName = normalized.split("/").pop() || normalized;
1489
+ return PROGRAMMATIC_ROUTE_FILE_NAMES.includes(baseName);
1490
+ }
1491
+ __name(isProgrammaticRoutesFileName, "isProgrammaticRoutesFileName");
1492
+ function getProgrammaticRouteManifest(mod) {
1493
+ if (!mod) return null;
1494
+ const candidates = [mod.default, mod.routes, mod.Route];
1495
+ for (const candidate of candidates) {
1496
+ if (isProgrammaticRouteManifest(candidate)) {
1497
+ return candidate;
1498
+ }
1499
+ if (isProgrammaticRouteDefinition(candidate)) {
1500
+ return defineRoutes([candidate]);
1501
+ }
1502
+ if (Array.isArray(candidate)) {
1503
+ return defineRoutes(candidate);
1504
+ }
1505
+ }
1506
+ const routeDefinitions = Object.values(mod).filter(isProgrammaticRouteDefinition);
1507
+ if (routeDefinitions.length > 0) {
1508
+ return defineRoutes(routeDefinitions);
1509
+ }
1510
+ return null;
1511
+ }
1512
+ __name(getProgrammaticRouteManifest, "getProgrammaticRouteManifest");
1513
+ function isProgrammaticRouteManifest(value) {
1514
+ return !!value && typeof value === "object" && value.__farmRoutes === true && Array.isArray(value.routes);
1515
+ }
1516
+ __name(isProgrammaticRouteManifest, "isProgrammaticRouteManifest");
1517
+ function isProgrammaticRouteDefinition(value) {
1518
+ if (!value || typeof value !== "object") {
1519
+ return false;
1520
+ }
1521
+ const kind = value.kind;
1522
+ return kind === "page" || kind === "layout" || kind === "api" || kind === "redirect";
1523
+ }
1524
+ __name(isProgrammaticRouteDefinition, "isProgrammaticRouteDefinition");
1525
+ function createProgrammaticRouteModuleId(filePath, kind, routePath) {
1526
+ return `${filePath}?farm-route=${kind}:${encodeURIComponent(normalizeRoutePath(routePath))}`;
1527
+ }
1528
+ __name(createProgrammaticRouteModuleId, "createProgrammaticRouteModuleId");
1529
+ function normalizeProgrammaticRoute(route) {
1530
+ if (route.kind === "redirect") {
1531
+ return {
1532
+ ...route,
1533
+ source: normalizeRoutePath(route.source)
1534
+ };
1535
+ }
1536
+ if (route.kind === "api") {
1537
+ return {
1538
+ ...route,
1539
+ ...normalizeFarmRouteRuntimeConfig(route, `API route "${route.path}"`),
1540
+ path: normalizeRoutePath(route.path),
1541
+ methods: normalizeApiMethods(route.methods)
1542
+ };
1543
+ }
1544
+ return {
1545
+ ...route,
1546
+ ...normalizeFarmRouteRuntimeConfig(
1547
+ route,
1548
+ `${route.kind === "layout" ? "Layout" : "Route"} "${route.path}"`
1549
+ ),
1550
+ path: normalizeRoutePath(route.path)
1551
+ };
1552
+ }
1553
+ __name(normalizeProgrammaticRoute, "normalizeProgrammaticRoute");
1554
+ function normalizeRoutePath(routePath) {
1555
+ const withSlash = routePath.startsWith("/") ? routePath : `/${routePath}`;
1556
+ const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
1557
+ return withoutTrailing || "/";
1558
+ }
1559
+ __name(normalizeRoutePath, "normalizeRoutePath");
1560
+ function normalizeApiMethods(methods) {
1561
+ const normalized = {};
1562
+ for (const [method, handler] of Object.entries(methods)) {
1563
+ const normalizedMethod = method.toUpperCase();
1564
+ if (handler && isProgrammaticRouteMethod(normalizedMethod)) {
1565
+ normalized[normalizedMethod] = handler;
1566
+ }
1567
+ }
1568
+ return normalized;
1569
+ }
1570
+ __name(normalizeApiMethods, "normalizeApiMethods");
1571
+ function isProgrammaticRouteMethod(method) {
1572
+ return method === "GET" || method === "HEAD" || method === "POST" || method === "PUT" || method === "DELETE" || method === "PATCH" || method === "OPTIONS";
1573
+ }
1574
+ __name(isProgrammaticRouteMethod, "isProgrammaticRouteMethod");
1575
+
1576
+ // src/routes.server.ts
1577
+ var import_fs = require("fs");
1578
+ var import_path2 = require("path");
1579
+ function findProgrammaticRouteFilesInDir(srcRoot) {
1580
+ const files = [];
1581
+ for (const fileName of PROGRAMMATIC_ROUTE_FILE_NAMES) {
1582
+ const filePath = (0, import_path2.join)(srcRoot, fileName);
1583
+ if ((0, import_fs.existsSync)(filePath)) {
1584
+ files.push(filePath);
1585
+ }
1586
+ }
1587
+ return files;
1588
+ }
1589
+ __name(findProgrammaticRouteFilesInDir, "findProgrammaticRouteFilesInDir");
1590
+
1591
+ // src/i18n/server.ts
1592
+ var import_node_async_hooks = require("async_hooks");
1593
+
1594
+ // src/i18n/runtime.ts
1595
+ var import_intl_messageformat = __toESM(require("intl-messageformat"));
1596
+
1597
+ // src/i18n/catalog.ts
1598
+ var import_promises = require("fs/promises");
1599
+ var import_icu_messageformat_parser = require("@formatjs/icu-messageformat-parser");
1600
+
1601
+ // src/i18n/config.ts
1602
+ var import_node_path = __toESM(require("path"));
1603
+ var DEFAULT_FARM_I18N_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
1604
+
1605
+ // src/i18n/server.ts
1606
+ var FARM_I18N_REQUEST_STORE = /* @__PURE__ */ Symbol.for("farm.i18n.requestStore");
1607
+ function getRequestStore() {
1608
+ const state = globalThis;
1609
+ return state[FARM_I18N_REQUEST_STORE] ?? (state[FARM_I18N_REQUEST_STORE] = new import_node_async_hooks.AsyncLocalStorage());
1610
+ }
1611
+ __name(getRequestStore, "getRequestStore");
1612
+ function getState() {
1613
+ const state = getRequestStore().getStore();
1614
+ if (!state) {
1615
+ throw new Error(
1616
+ "No Farm i18n request context is active. Use this API while rendering, inside an API route, or use createTranslator(locale)."
1617
+ );
1618
+ }
1619
+ return state;
1620
+ }
1621
+ __name(getState, "getState");
1622
+ async function _runWithFarmI18nRequest(runtime, request, fn, options = {}) {
1623
+ const resolution = runtime.resolveRequest(request, options);
1624
+ const state = {
1625
+ runtime,
1626
+ resolution,
1627
+ snapshot: runtime.getClientSnapshot(resolution)
1628
+ };
1629
+ return getRequestStore().run(state, () => fn(resolution));
1630
+ }
1631
+ __name(_runWithFarmI18nRequest, "_runWithFarmI18nRequest");
1632
+ var t = createTranslatorFromState(() => getState());
1633
+ function getFarmI18nClientSnapshot() {
1634
+ return getRequestStore().getStore()?.snapshot;
1635
+ }
1636
+ __name(getFarmI18nClientSnapshot, "getFarmI18nClientSnapshot");
1637
+ function createTranslatorFromState(resolveState) {
1638
+ const translator = /* @__PURE__ */ __name(((key, values) => {
1639
+ const state = resolveState();
1640
+ return state.runtime.translate(state.resolution.locale, key, values);
1641
+ }), "translator");
1642
+ translator.rich = (key, values) => {
1643
+ const state = resolveState();
1644
+ return state.runtime.translateRich(state.resolution.locale, key, values);
1645
+ };
1646
+ translator.raw = (key) => {
1647
+ const state = resolveState();
1648
+ return state.runtime.getRawMessage(state.resolution.locale, key);
1649
+ };
1650
+ translator.has = (key) => {
1651
+ const state = resolveState();
1652
+ return state.runtime.hasMessage(state.resolution.locale, key);
1653
+ };
1654
+ return translator;
1655
+ }
1656
+ __name(createTranslatorFromState, "createTranslatorFromState");
1657
+ _setFarmI18nSnapshotResolver(() => getFarmI18nClientSnapshot());
1658
+
1659
+ // src/server/request.ts
1660
+ var import_node_async_hooks2 = require("async_hooks");
1661
+
1662
+ // src/server/request-bridge.ts
1663
+ var CURRENT_REQUEST_RESOLVER_KEY = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
1664
+ function getGlobalState() {
1665
+ return globalThis;
1666
+ }
1667
+ __name(getGlobalState, "getGlobalState");
1668
+ function _setCurrentRequestResolver(resolver) {
1669
+ getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY] = resolver;
1670
+ }
1671
+ __name(_setCurrentRequestResolver, "_setCurrentRequestResolver");
1672
+
1673
+ // src/server/request.ts
1674
+ var REQUEST_STORAGE_KEY = /* @__PURE__ */ Symbol.for("@farm.js/core/request-storage");
1675
+ function getRequestStore2() {
1676
+ const runtime = globalThis;
1677
+ const existing = runtime[REQUEST_STORAGE_KEY];
1678
+ if (existing instanceof import_node_async_hooks2.AsyncLocalStorage) {
1679
+ return existing;
1680
+ }
1681
+ const storage = new import_node_async_hooks2.AsyncLocalStorage();
1682
+ runtime[REQUEST_STORAGE_KEY] = storage;
1683
+ return storage;
1684
+ }
1685
+ __name(getRequestStore2, "getRequestStore");
1686
+ var requestStore = getRequestStore2();
1687
+ _setCurrentRequestResolver(() => requestStore.getStore());
1688
+ async function _runWithCurrentRequest(request, fn) {
1689
+ return requestStore.run(request, fn);
1690
+ }
1691
+ __name(_runWithCurrentRequest, "_runWithCurrentRequest");
1692
+
1693
+ // src/api/runtime.ts
1694
+ function matchAPIRoute(routes, pathname) {
1695
+ const exactRoute = routes.get(pathname);
1696
+ if (exactRoute) {
1697
+ return { route: exactRoute, params: {} };
1698
+ }
1699
+ const normalizedPathname = normalizePathname(pathname);
1700
+ if (normalizedPathname !== pathname) {
1701
+ const normalizedRoute = routes.get(normalizedPathname);
1702
+ if (normalizedRoute) {
1703
+ return { route: normalizedRoute, params: {} };
1704
+ }
1705
+ }
1706
+ for (const route of routes.values()) {
1707
+ const params = matchRoutePath(route.path, pathname);
1708
+ if (params) {
1709
+ return { route, params };
1710
+ }
1711
+ }
1712
+ return null;
1713
+ }
1714
+ __name(matchAPIRoute, "matchAPIRoute");
1715
+ async function invokeAPIRouteEndpoint(endpoint, request, params = {}) {
1716
+ return _runWithCurrentRequest(
1717
+ request,
1718
+ () => invokeAPIRouteEndpointInContext(endpoint, request, params)
1719
+ );
1720
+ }
1721
+ __name(invokeAPIRouteEndpoint, "invokeAPIRouteEndpoint");
1722
+ async function invokeAPIRouteEndpointInContext(endpoint, request, params) {
1723
+ const farmHandler = endpoint.__handler || (isFarmContextHandler(endpoint) ? endpoint : null);
1724
+ if (!farmHandler) {
1725
+ const result = await endpoint(request, {
1726
+ params: Promise.resolve(params)
1727
+ });
1728
+ return normalizeRouteResponse(result);
1729
+ }
1730
+ const url = new URL(request.url);
1731
+ const query = {};
1732
+ url.searchParams.forEach((value, key) => {
1733
+ query[key] = value;
1734
+ });
1735
+ let body = void 0;
1736
+ if (request.method.toUpperCase() !== "GET" && request.method.toUpperCase() !== "HEAD") {
1737
+ body = await readRequestBody(request);
1738
+ }
1739
+ const headers = Object.fromEntries(request.headers.entries());
1740
+ const types = endpoint.__types || {};
1741
+ const queryValidation = validateInput(types.query, query, "Invalid query parameters");
1742
+ if (queryValidation instanceof Response) {
1743
+ return queryValidation;
1744
+ }
1745
+ const bodyValidation = validateInput(types.body, body, "Invalid request body");
1746
+ if (bodyValidation instanceof Response) {
1747
+ return bodyValidation;
1748
+ }
1749
+ const headersValidation = validateInput(types.headers, headers, "Invalid request headers");
1750
+ if (headersValidation instanceof Response) {
1751
+ return headersValidation;
1752
+ }
1753
+ const handlerContext = {
1754
+ query: queryValidation,
1755
+ body: bodyValidation,
1756
+ headers: headersValidation,
1757
+ request,
1758
+ context: {},
1759
+ params
1760
+ };
1761
+ let execution;
1762
+ try {
1763
+ execution = typeof endpoint.__farmInvoke === "function" ? await endpoint.__farmInvoke(handlerContext) : {
1764
+ result: await farmHandler(handlerContext),
1765
+ context: handlerContext.context,
1766
+ handlerExecuted: true,
1767
+ invalidations: []
1768
+ };
1769
+ } catch (error) {
1770
+ if (isEndpointFailure(error)) {
1771
+ return createEndpointFailureResponse(error);
1772
+ }
1773
+ throw error;
1774
+ }
1775
+ const response = normalizeRouteResponse(execution.result);
1776
+ return attachEndpointInvalidations(response, execution.invalidations);
1777
+ }
1778
+ __name(invokeAPIRouteEndpointInContext, "invokeAPIRouteEndpointInContext");
1779
+ function normalizeRouteResponse(result) {
1780
+ if (isWebResponse(result)) {
1781
+ return result;
1782
+ }
1783
+ if (result === void 0) {
1784
+ return new Response(null, { status: 204 });
1785
+ }
1786
+ return new Response(JSON.stringify(result), {
1787
+ status: 200,
1788
+ headers: { "Content-Type": "application/json" }
1789
+ });
1790
+ }
1791
+ __name(normalizeRouteResponse, "normalizeRouteResponse");
1792
+ function isWebResponse(value) {
1793
+ return value instanceof Response || typeof value === "object" && value !== null && "headers" in value && "status" in value && typeof value.arrayBuffer === "function";
1794
+ }
1795
+ __name(isWebResponse, "isWebResponse");
1796
+ function attachEndpointInvalidations(response, keys) {
1797
+ const existing = decodeFarmCacheInvalidations(
1798
+ response.headers.get(FARM_CACHE_INVALIDATION_HEADER)
1799
+ );
1800
+ const encoded = encodeFarmCacheInvalidations([...existing, ...keys]);
1801
+ if (!encoded) return response;
1802
+ const headers = new Headers(response.headers);
1803
+ headers.set(FARM_CACHE_INVALIDATION_HEADER, encoded);
1804
+ return new Response(response.body, {
1805
+ status: response.status,
1806
+ statusText: response.statusText,
1807
+ headers
1808
+ });
1809
+ }
1810
+ __name(attachEndpointInvalidations, "attachEndpointInvalidations");
1811
+ function createEndpointFailureResponse(failure) {
1812
+ return new Response(
1813
+ JSON.stringify({
1814
+ error: {
1815
+ code: failure.code,
1816
+ message: failure.message,
1817
+ data: failure.data
1818
+ }
1819
+ }),
1820
+ {
1821
+ status: failure.status,
1822
+ headers: {
1823
+ "cache-control": "no-store",
1824
+ "content-type": "application/json"
1825
+ }
1826
+ }
1827
+ );
1828
+ }
1829
+ __name(createEndpointFailureResponse, "createEndpointFailureResponse");
1830
+ function isFarmContextHandler(endpoint) {
1831
+ if (typeof endpoint !== "function") {
1832
+ return false;
1833
+ }
1834
+ const source = Function.prototype.toString.call(endpoint).trim();
1835
+ const arrowMatch = source.match(/^(?:async\s*)?(?:\(([^)]*)\)|([A-Za-z_$][\w$]*))\s*=>/);
1836
+ const functionMatch = source.match(/^(?:async\s*)?function[^(]*\(([^)]*)\)/);
1837
+ const firstParameter = (arrowMatch?.[1] || arrowMatch?.[2] || functionMatch?.[1] || "").split(",")[0].trim();
1838
+ return firstParameter === "ctx" || firstParameter === "context" || firstParameter.startsWith("{");
1839
+ }
1840
+ __name(isFarmContextHandler, "isFarmContextHandler");
1841
+ async function readRequestBody(request) {
1842
+ const contentType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
1843
+ try {
1844
+ if (contentType === "multipart/form-data") {
1845
+ return formDataToObject(await request.clone().formData());
1846
+ }
1847
+ const text = await request.clone().text();
1848
+ if (!text) return void 0;
1849
+ if (contentType === "application/x-www-form-urlencoded") {
1850
+ return searchParamsToObject(new URLSearchParams(text));
1851
+ }
1852
+ if (contentType === "application/json" || contentType?.endsWith("+json")) {
1853
+ return JSON.parse(text);
1854
+ }
1855
+ return JSON.parse(text);
1856
+ } catch {
1857
+ }
1858
+ return void 0;
1859
+ }
1860
+ __name(readRequestBody, "readRequestBody");
1861
+ function formDataToObject(formData) {
1862
+ return entriesToObject(formData.entries());
1863
+ }
1864
+ __name(formDataToObject, "formDataToObject");
1865
+ function searchParamsToObject(searchParams) {
1866
+ return entriesToObject(searchParams.entries());
1867
+ }
1868
+ __name(searchParamsToObject, "searchParamsToObject");
1869
+ function entriesToObject(entries) {
1870
+ const output = /* @__PURE__ */ Object.create(null);
1871
+ for (const [key, value] of entries) {
1872
+ if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
1873
+ const current = output[key];
1874
+ if (current === void 0) {
1875
+ output[key] = value;
1876
+ } else if (Array.isArray(current)) {
1877
+ current.push(value);
1878
+ } else {
1879
+ output[key] = [current, value];
1880
+ }
1881
+ }
1882
+ return output;
1883
+ }
1884
+ __name(entriesToObject, "entriesToObject");
1885
+ function validateInput(schema, value, error) {
1886
+ if (!schema || typeof schema.parse !== "function") {
1887
+ return value;
1888
+ }
1889
+ try {
1890
+ return schema.parse(value);
1891
+ } catch (validationError) {
1892
+ return new Response(
1893
+ JSON.stringify({
1894
+ error,
1895
+ details: validationError.errors || validationError.issues || validationError.message
1896
+ }),
1897
+ {
1898
+ status: 400,
1899
+ headers: { "Content-Type": "application/json" }
1900
+ }
1901
+ );
1902
+ }
1903
+ }
1904
+ __name(validateInput, "validateInput");
1905
+ function matchRoutePath(routePath, pathname) {
1906
+ const routeSegments = getPathSegments(routePath);
1907
+ const pathnameSegments = getPathSegments(pathname);
1908
+ const params = {};
1909
+ let pathIndex = 0;
1910
+ for (const routeSegment of routeSegments) {
1911
+ const dynamicSegment = parseDynamicSegment(routeSegment);
1912
+ if (dynamicSegment?.catchAll) {
1913
+ const remainingSegments = pathnameSegments.slice(pathIndex).map(decodePathSegment);
1914
+ if (remainingSegments.length === 0 && !dynamicSegment.optional) {
1915
+ return null;
1916
+ }
1917
+ if (remainingSegments.length > 0) {
1918
+ params[dynamicSegment.name] = remainingSegments;
1919
+ }
1920
+ pathIndex = pathnameSegments.length;
1921
+ continue;
1922
+ }
1923
+ const pathnameSegment = pathnameSegments[pathIndex];
1924
+ if (pathnameSegment === void 0) {
1925
+ return null;
1926
+ }
1927
+ if (dynamicSegment) {
1928
+ params[dynamicSegment.name] = decodePathSegment(pathnameSegment);
1929
+ pathIndex++;
1930
+ continue;
1931
+ }
1932
+ if (routeSegment !== pathnameSegment) {
1933
+ return null;
1934
+ }
1935
+ pathIndex++;
1936
+ }
1937
+ return pathIndex === pathnameSegments.length ? params : null;
1938
+ }
1939
+ __name(matchRoutePath, "matchRoutePath");
1940
+ function getPathSegments(pathname) {
1941
+ return normalizePathname(pathname).split("/").filter((segment) => segment.length > 0);
1942
+ }
1943
+ __name(getPathSegments, "getPathSegments");
1944
+ function normalizePathname(pathname) {
1945
+ if (pathname.length > 1 && pathname.endsWith("/")) {
1946
+ return pathname.replace(/\/+$/, "");
1947
+ }
1948
+ return pathname;
1949
+ }
1950
+ __name(normalizePathname, "normalizePathname");
1951
+ function parseDynamicSegment(segment) {
1952
+ const optionalCatchAll = segment.match(/^\[\[\.\.\.(.+)\]\]$/);
1953
+ if (optionalCatchAll?.[1]) {
1954
+ return { name: optionalCatchAll[1], catchAll: true, optional: true };
1955
+ }
1956
+ const catchAll = segment.match(/^\[\.\.\.(.+)\]$/);
1957
+ if (catchAll?.[1]) {
1958
+ return { name: catchAll[1], catchAll: true, optional: false };
1959
+ }
1960
+ const dynamic = segment.match(/^\[(.+)\]$/);
1961
+ if (dynamic?.[1]) {
1962
+ return { name: dynamic[1], catchAll: false, optional: false };
1963
+ }
1964
+ return null;
1965
+ }
1966
+ __name(parseDynamicSegment, "parseDynamicSegment");
1967
+ function decodePathSegment(segment) {
1968
+ try {
1969
+ return decodeURIComponent(segment);
1970
+ } catch {
1971
+ return segment;
1972
+ }
1973
+ }
1974
+ __name(decodePathSegment, "decodePathSegment");
1975
+
1976
+ // src/api/route-manager.ts
1977
+ var API_ROUTE_METHODS = [
1978
+ "GET",
1979
+ "HEAD",
1980
+ "POST",
1981
+ "PUT",
1982
+ "DELETE",
1983
+ "PATCH",
1984
+ "OPTIONS"
1985
+ ];
1986
+ var _APIRouteManager = class _APIRouteManager {
1987
+ constructor(appDir, viteServer, options = {}) {
1988
+ this.routes = /* @__PURE__ */ new Map();
1989
+ this.appDirs = Array.isArray(appDir) ? [...appDir] : [appDir];
1990
+ this.viteServer = viteServer;
1991
+ this.throwOnLoadError = options.throwOnLoadError === true;
1992
+ this.i18n = options.i18n;
1993
+ }
1994
+ /**
1995
+ * Discover route.ts files in /app/api and explicit endpoints in root routes.ts
1996
+ */
1997
+ async discoverRoutes() {
1998
+ this.routes.clear();
1999
+ for (const appDir of this.appDirs) {
2000
+ const apiDir = path3.join(appDir, "api");
2001
+ let routeFiles = [];
2002
+ if (fs.existsSync(apiDir)) {
2003
+ routeFiles = this.findRouteFiles(apiDir);
2004
+ }
2005
+ for (const filePath of routeFiles) {
2006
+ await this.loadRoute(filePath, appDir);
2007
+ }
2008
+ await this.loadRootRoutes(appDir);
2009
+ await this.loadProgrammaticApiRoutes(appDir);
2010
+ }
2011
+ if (process.env.FARM_VERBOSE) {
2012
+ logger.success(`Discovered ${this.routes.size} API routes`);
2013
+ for (const [routePath, route] of this.routes) {
2014
+ logger.info(` ${route.methods.join(", ")} ${routePath}`);
2015
+ }
2016
+ }
2017
+ }
2018
+ /**
2019
+ * Recursively find all route.ts files
2020
+ */
2021
+ findRouteFiles(dir) {
2022
+ const files = [];
2023
+ if (!fs.existsSync(dir)) {
2024
+ return files;
2025
+ }
2026
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
2027
+ for (const entry of entries) {
2028
+ const fullPath = path3.join(dir, entry.name);
2029
+ if (entry.isDirectory()) {
2030
+ files.push(...this.findRouteFiles(fullPath));
2031
+ } else if (entry.name === "route.ts" || entry.name === "route.tsx" || entry.name === "route.js") {
2032
+ files.push(fullPath);
2033
+ }
2034
+ }
2035
+ return files;
2036
+ }
2037
+ /**
2038
+ * Load a route.ts file and extract HTTP method exports
2039
+ */
2040
+ async loadRoute(filePath, appDir) {
2041
+ try {
2042
+ const apiDir = path3.join(appDir, "api");
2043
+ const relativePath = path3.relative(apiDir, path3.dirname(filePath));
2044
+ const routePath = "/api/" + (relativePath === "." ? "" : relativePath.replace(/\\/g, "/"));
2045
+ const routeModule = await this.loadModule(filePath);
2046
+ const endpoints = {};
2047
+ const availableMethods = [];
2048
+ for (const method of API_ROUTE_METHODS) {
2049
+ if (routeModule[method]) {
2050
+ endpoints[method] = routeModule[method];
2051
+ availableMethods.push(method);
2052
+ }
2053
+ }
2054
+ if (availableMethods.length > 0) {
2055
+ const runtimeConfig = normalizeFarmRouteRuntimeConfig(
2056
+ getFarmRouteRuntimeConfig(routeModule),
2057
+ `API route "${routePath}"`
2058
+ );
2059
+ this.routes.set(routePath, {
2060
+ path: routePath,
2061
+ filePath,
2062
+ methods: availableMethods,
2063
+ endpoints,
2064
+ ...runtimeConfig
2065
+ });
2066
+ }
2067
+ } catch (error) {
2068
+ this.handleLoadError(`Error loading route ${filePath}`, error);
2069
+ }
2070
+ }
2071
+ /**
2072
+ * Load explicit-path endpoints from src/routes.ts-style files.
2073
+ */
2074
+ async loadRootRoutes(appDir) {
2075
+ const routesFile = this.findRootRoutesFile(appDir);
2076
+ if (!routesFile) {
2077
+ return;
2078
+ }
2079
+ try {
2080
+ const routesModule = await this.loadModule(routesFile);
2081
+ for (const exportValue of Object.values(routesModule)) {
2082
+ const endpoint = exportValue;
2083
+ if (!endpoint?.__path) {
2084
+ continue;
2085
+ }
2086
+ const method = String(endpoint.__method || "GET").toUpperCase();
2087
+ this.addEndpoint(endpoint.__path, routesFile, method, endpoint);
2088
+ }
2089
+ } catch (error) {
2090
+ this.handleLoadError(`Error loading root API routes ${routesFile}`, error);
2091
+ }
2092
+ }
2093
+ async loadProgrammaticApiRoutes(appDir) {
2094
+ const candidateRoots = [path3.dirname(appDir), appDir];
2095
+ const routeFiles = Array.from(
2096
+ new Set(candidateRoots.flatMap((srcRoot) => findProgrammaticRouteFilesInDir(srcRoot)))
2097
+ );
2098
+ for (const routeFile of routeFiles) {
2099
+ try {
2100
+ const routesModule = await this.loadModule(routeFile);
2101
+ const manifest = getProgrammaticRouteManifest(routesModule);
2102
+ if (!manifest) continue;
2103
+ for (const definition of manifest.routes) {
2104
+ if (definition.kind !== "api") continue;
2105
+ this.addProgrammaticApiRoute(routeFile, definition);
2106
+ }
2107
+ } catch (error) {
2108
+ this.handleLoadError(`Error loading programmatic API routes ${routeFile}`, error);
2109
+ }
2110
+ }
2111
+ }
2112
+ handleLoadError(message, error) {
2113
+ logger.error(`${message}: ${error}`);
2114
+ if (this.throwOnLoadError) {
2115
+ throw error;
2116
+ }
2117
+ }
2118
+ findRootRoutesFile(appDir) {
2119
+ const routeNames = ["routes.ts", "routes.tsx", "routes.js"];
2120
+ const candidateDirs = [path3.dirname(appDir), appDir];
2121
+ const seen = /* @__PURE__ */ new Set();
2122
+ for (const dir of candidateDirs) {
2123
+ for (const routeName of routeNames) {
2124
+ const routesFile = path3.join(dir, routeName);
2125
+ if (seen.has(routesFile)) {
2126
+ continue;
2127
+ }
2128
+ seen.add(routesFile);
2129
+ if (fs.existsSync(routesFile)) {
2130
+ return routesFile;
2131
+ }
2132
+ }
2133
+ }
2134
+ return null;
2135
+ }
2136
+ async loadModule(filePath) {
2137
+ if (this.viteServer) {
2138
+ return await this.viteServer.ssrLoadModule(filePath);
2139
+ }
2140
+ const fileUrl = `file://${filePath}`;
2141
+ return await import(
2142
+ /* @vite-ignore */
2143
+ fileUrl
2144
+ );
2145
+ }
2146
+ addEndpoint(routePath, filePath, method, endpoint, runtimeConfig = {}) {
2147
+ const normalizedMethod = method.toUpperCase();
2148
+ const existingRoute = this.routes.get(routePath);
2149
+ if (existingRoute) {
2150
+ if (!existingRoute.methods.includes(normalizedMethod)) {
2151
+ existingRoute.methods.push(normalizedMethod);
2152
+ }
2153
+ existingRoute.endpoints[normalizedMethod] = endpoint;
2154
+ Object.assign(existingRoute, runtimeConfig);
2155
+ return;
2156
+ }
2157
+ this.routes.set(routePath, {
2158
+ path: routePath,
2159
+ filePath,
2160
+ methods: [normalizedMethod],
2161
+ endpoints: { [normalizedMethod]: endpoint },
2162
+ ...runtimeConfig
2163
+ });
2164
+ }
2165
+ addProgrammaticApiRoute(filePath, route) {
2166
+ const modulePath = createProgrammaticRouteModuleId(filePath, "api", route.path);
2167
+ const runtimeConfig = normalizeFarmRouteRuntimeConfig(route, `API route "${route.path}"`);
2168
+ for (const [method, endpoint] of Object.entries(route.methods)) {
2169
+ if (endpoint) {
2170
+ this.addEndpoint(route.path, modulePath, method, endpoint, runtimeConfig);
2171
+ }
2172
+ }
2173
+ }
2174
+ /**
2175
+ * Get the handler that directly invokes endpoint handlers
2176
+ */
2177
+ getHandler() {
2178
+ if (this.routes.size === 0) {
2179
+ return null;
2180
+ }
2181
+ return async (request) => {
2182
+ const url = new URL(request.url);
2183
+ const pathname = url.pathname;
2184
+ const method = request.method.toUpperCase();
2185
+ const match = matchAPIRoute(this.routes, pathname);
2186
+ if (!match) {
2187
+ return new Response(JSON.stringify({ error: "Not Found" }), {
2188
+ status: 404,
2189
+ headers: { "Content-Type": "application/json" }
2190
+ });
2191
+ }
2192
+ const { route, params } = match;
2193
+ const endpoint = route.endpoints[method];
2194
+ if (!endpoint) {
2195
+ return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
2196
+ status: 405,
2197
+ headers: { "Content-Type": "application/json" }
2198
+ });
2199
+ }
2200
+ const invoke = /* @__PURE__ */ __name(async () => {
2201
+ try {
2202
+ return await invokeAPIRouteEndpoint(endpoint, request, params);
2203
+ } catch (error) {
2204
+ console.error(`[API Error] ${pathname}:`, error);
2205
+ return new Response(JSON.stringify({ error: "Internal Server Error" }), {
2206
+ status: 500,
2207
+ headers: { "Content-Type": "application/json" }
2208
+ });
2209
+ }
2210
+ }, "invoke");
2211
+ return this.i18n?.config.enabled ? _runWithFarmI18nRequest(this.i18n, request, invoke, {
2212
+ redirect: false
2213
+ }) : invoke();
2214
+ };
2215
+ }
2216
+ /**
2217
+ * Check if a path is an API route
2218
+ */
2219
+ isAPIRoute(pathname) {
2220
+ return Boolean(this.matchRoute(pathname));
2221
+ }
2222
+ matchRoute(pathname) {
2223
+ return matchAPIRoute(this.routes, pathname);
2224
+ }
2225
+ /**
2226
+ * Get all routes for client type generation
2227
+ */
2228
+ getRoutes() {
2229
+ return this.routes;
2230
+ }
2231
+ };
2232
+ __name(_APIRouteManager, "APIRouteManager");
2233
+ var APIRouteManager = _APIRouteManager;
2234
+
2235
+ // src/integration-client.ts
2236
+ var _IntegrationClientError = class _IntegrationClientError extends Error {
2237
+ constructor(message, response, data) {
2238
+ super(message);
2239
+ this.name = "IntegrationClientError";
2240
+ this.status = response.status;
2241
+ this.response = response;
2242
+ this.data = data;
2243
+ }
2244
+ };
2245
+ __name(_IntegrationClientError, "IntegrationClientError");
2246
+ var IntegrationClientError = _IntegrationClientError;
2247
+ var INTEGRATION_RUNTIME_REGISTRY_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRuntimeRegistry");
2248
+ var CURRENT_REQUEST_RESOLVER_KEY2 = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
2249
+ var INTEGRATION_REQUEST_DISPATCHER_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRequestDispatcher");
2250
+ function isOperation(value) {
2251
+ return !!value && typeof value === "object" && value.kind === "farm-integration-api-operation";
2252
+ }
2253
+ __name(isOperation, "isOperation");
2254
+ function tryResolveSourceAPI(source) {
2255
+ if ("kind" in source && source.kind === "farm-integration") {
2256
+ if (!source.api) {
2257
+ return null;
2258
+ }
2259
+ return source.api;
2260
+ }
2261
+ return source;
2262
+ }
2263
+ __name(tryResolveSourceAPI, "tryResolveSourceAPI");
2264
+ function getIntegrationRuntimeRegistry() {
2265
+ const globalState2 = globalThis;
2266
+ return globalState2[INTEGRATION_RUNTIME_REGISTRY_KEY] || /* @__PURE__ */ new Map();
2267
+ }
2268
+ __name(getIntegrationRuntimeRegistry, "getIntegrationRuntimeRegistry");
2269
+ function getRegisteredIntegrationRuntimeLocal(key) {
2270
+ return getIntegrationRuntimeRegistry().get(key);
2271
+ }
2272
+ __name(getRegisteredIntegrationRuntimeLocal, "getRegisteredIntegrationRuntimeLocal");
2273
+ function getRegisteredIntegrationsLocal() {
2274
+ return Object.fromEntries(
2275
+ Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime]) => [
2276
+ key,
2277
+ runtime.integration
2278
+ ])
2279
+ );
2280
+ }
2281
+ __name(getRegisteredIntegrationsLocal, "getRegisteredIntegrationsLocal");
2282
+ function resolveCurrentRequestLocal() {
2283
+ const globalState2 = globalThis;
2284
+ return globalState2[CURRENT_REQUEST_RESOLVER_KEY2]?.();
2285
+ }
2286
+ __name(resolveCurrentRequestLocal, "resolveCurrentRequestLocal");
2287
+ function resolveIntegrationRequestDispatcherLocal() {
2288
+ const globalState2 = globalThis;
2289
+ return globalState2[INTEGRATION_REQUEST_DISPATCHER_KEY];
2290
+ }
2291
+ __name(resolveIntegrationRequestDispatcherLocal, "resolveIntegrationRequestDispatcherLocal");
2292
+ var INTEGRATION_DATA_HEADER = "x-farm-integration-data";
2293
+ var INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;
2294
+ var BLOCKED_INTEGRATION_DATA_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
2295
+ function isIntegrationClientData(value) {
2296
+ return !!value && typeof value === "object" && !Array.isArray(value);
2297
+ }
2298
+ __name(isIntegrationClientData, "isIntegrationClientData");
2299
+ function isPlainIntegrationDataObject(value) {
2300
+ if (!isIntegrationClientData(value)) {
2301
+ return false;
2302
+ }
2303
+ const prototype = Object.getPrototypeOf(value);
2304
+ return prototype === Object.prototype || prototype === null;
2305
+ }
2306
+ __name(isPlainIntegrationDataObject, "isPlainIntegrationDataObject");
2307
+ function sanitizeIntegrationClientDataValue(value) {
2308
+ if (Array.isArray(value)) {
2309
+ return value.map((item) => sanitizeIntegrationClientDataValue(item));
2310
+ }
2311
+ if (!isPlainIntegrationDataObject(value)) {
2312
+ return value;
2313
+ }
2314
+ const sanitized = {};
2315
+ for (const [key, item] of Object.entries(value)) {
2316
+ if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {
2317
+ continue;
2318
+ }
2319
+ sanitized[key] = sanitizeIntegrationClientDataValue(item);
2320
+ }
2321
+ return sanitized;
2322
+ }
2323
+ __name(sanitizeIntegrationClientDataValue, "sanitizeIntegrationClientDataValue");
2324
+ function normalizeIntegrationClientData(value) {
2325
+ if (!isIntegrationClientData(value)) {
2326
+ return void 0;
2327
+ }
2328
+ const sanitized = sanitizeIntegrationClientDataValue(value);
2329
+ return isIntegrationClientData(sanitized) && Object.keys(sanitized).length > 0 ? sanitized : void 0;
2330
+ }
2331
+ __name(normalizeIntegrationClientData, "normalizeIntegrationClientData");
2332
+ function getIntegrationDataHeaderByteLength(value) {
2333
+ return new TextEncoder().encode(value).byteLength;
2334
+ }
2335
+ __name(getIntegrationDataHeaderByteLength, "getIntegrationDataHeaderByteLength");
2336
+ function mergeIntegrationClientData(...values) {
2337
+ let merged;
2338
+ for (const value of values) {
2339
+ const data = normalizeIntegrationClientData(value);
2340
+ if (!data) {
2341
+ continue;
2342
+ }
2343
+ merged = {
2344
+ ...merged,
2345
+ ...data
2346
+ };
2347
+ }
2348
+ return merged && Object.keys(merged).length > 0 ? merged : void 0;
2349
+ }
2350
+ __name(mergeIntegrationClientData, "mergeIntegrationClientData");
2351
+ function serializeIntegrationClientData(data) {
2352
+ const serialized = JSON.stringify(data);
2353
+ if (getIntegrationDataHeaderByteLength(serialized) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {
2354
+ throw new Error(
2355
+ `Integration client data must be smaller than ${INTEGRATION_DATA_HEADER_MAX_LENGTH} bytes when sent over HTTP headers.`
2356
+ );
2357
+ }
2358
+ return serialized;
2359
+ }
2360
+ __name(serializeIntegrationClientData, "serializeIntegrationClientData");
2361
+ function appendIntegrationClientDataHeader(headers, data) {
2362
+ if (!data) {
2363
+ return;
2364
+ }
2365
+ headers.set(INTEGRATION_DATA_HEADER, serializeIntegrationClientData(data));
2366
+ }
2367
+ __name(appendIntegrationClientDataHeader, "appendIntegrationClientDataHeader");
2368
+ function resolveAutomaticClientNamespaces() {
2369
+ const globalState2 = globalThis;
2370
+ const manifest = globalState2.window?.__FARM_INTEGRATION_API_MANIFEST__ || globalState2.__FARM_INTEGRATION_API_MANIFEST__ || {};
2371
+ return Object.entries(manifest).map(([key, api2]) => [key, api2, api2]);
2372
+ }
2373
+ __name(resolveAutomaticClientNamespaces, "resolveAutomaticClientNamespaces");
2374
+ function resolveAutomaticServerNamespaces() {
2375
+ return Object.entries(getRegisteredIntegrationsLocal()).flatMap(([key, source]) => {
2376
+ const api2 = tryResolveSourceAPI(source);
2377
+ return api2 ? [[key, api2, source]] : [];
2378
+ });
2379
+ }
2380
+ __name(resolveAutomaticServerNamespaces, "resolveAutomaticServerNamespaces");
2381
+ function appendQuery(url, query) {
2382
+ if (!query) {
2383
+ return;
2384
+ }
2385
+ for (const [key, value] of Object.entries(query)) {
2386
+ if (value == null) {
2387
+ continue;
2388
+ }
2389
+ if (Array.isArray(value)) {
2390
+ for (const item of value) {
2391
+ if (item != null) {
2392
+ url.searchParams.append(key, String(item));
2393
+ }
2394
+ }
2395
+ continue;
2396
+ }
2397
+ url.searchParams.set(key, String(value));
2398
+ }
2399
+ }
2400
+ __name(appendQuery, "appendQuery");
2401
+ function appendHeaders(target, source) {
2402
+ if (!source) {
2403
+ return;
2404
+ }
2405
+ const headers = new Headers(source);
2406
+ headers.forEach((value, key) => {
2407
+ target.set(key, value);
2408
+ });
2409
+ }
2410
+ __name(appendHeaders, "appendHeaders");
2411
+ var DEFAULT_FORWARDED_HEADERS = [
2412
+ "authorization",
2413
+ "cookie",
2414
+ "x-client-ip",
2415
+ "x-forwarded-for",
2416
+ "x-forwarded-host",
2417
+ "x-forwarded-proto",
2418
+ "x-real-ip"
2419
+ ];
2420
+ function resolveRequestLike(request) {
2421
+ if (!request) {
2422
+ return void 0;
2423
+ }
2424
+ if (request instanceof Request) {
2425
+ return {
2426
+ url: request.url,
2427
+ headers: request.headers
2428
+ };
2429
+ }
2430
+ return {
2431
+ url: request.url,
2432
+ headers: request.headers ? new Headers(request.headers) : void 0
2433
+ };
2434
+ }
2435
+ __name(resolveRequestLike, "resolveRequestLike");
2436
+ function resolveServerBaseURL(explicitBaseURL, request) {
2437
+ if (explicitBaseURL) {
2438
+ return explicitBaseURL;
2439
+ }
2440
+ if (request?.url) {
2441
+ try {
2442
+ return new URL(request.url).origin;
2443
+ } catch {
2444
+ }
2445
+ }
2446
+ const headers = request?.headers;
2447
+ const host = headers?.get("x-forwarded-host") || headers?.get("host");
2448
+ if (host) {
2449
+ const proto = headers?.get("x-forwarded-proto") || "http";
2450
+ return `${proto}://${host}`;
2451
+ }
2452
+ return "http://localhost:3000";
2453
+ }
2454
+ __name(resolveServerBaseURL, "resolveServerBaseURL");
2455
+ function resolveForwardHeaders(request, forwardHeaders) {
2456
+ if (!request?.headers || forwardHeaders === false) {
2457
+ return new Headers();
2458
+ }
2459
+ const allowed = Array.isArray(forwardHeaders) && forwardHeaders.length > 0 ? new Set(forwardHeaders.map((item) => item.toLowerCase())) : new Set(DEFAULT_FORWARDED_HEADERS);
2460
+ const headers = new Headers();
2461
+ request.headers.forEach((value, key) => {
2462
+ if (allowed.has(key.toLowerCase())) {
2463
+ headers.set(key, value);
2464
+ }
2465
+ });
2466
+ return headers;
2467
+ }
2468
+ __name(resolveForwardHeaders, "resolveForwardHeaders");
2469
+ function createBody(format, body, headers) {
2470
+ if (body == null || format === "none") {
2471
+ return void 0;
2472
+ }
2473
+ if (format === "form") {
2474
+ if (body instanceof FormData || body instanceof URLSearchParams) {
2475
+ return body;
2476
+ }
2477
+ const form = new URLSearchParams();
2478
+ for (const [key, value] of Object.entries(body)) {
2479
+ if (value == null) {
2480
+ continue;
2481
+ }
2482
+ if (Array.isArray(value)) {
2483
+ for (const item of value) {
2484
+ if (item != null) {
2485
+ form.append(key, String(item));
2486
+ }
2487
+ }
2488
+ continue;
2489
+ }
2490
+ form.set(key, String(value));
2491
+ }
2492
+ headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
2493
+ return form;
2494
+ }
2495
+ headers.set("content-type", "application/json");
2496
+ return JSON.stringify(body);
2497
+ }
2498
+ __name(createBody, "createBody");
2499
+ async function parseResponseData(response) {
2500
+ if (response.status === 204 || response.status === 205) {
2501
+ return void 0;
2502
+ }
2503
+ const contentType = response.headers.get("content-type") || "";
2504
+ if (contentType.includes("application/json")) {
2505
+ return await response.json();
2506
+ }
2507
+ return await response.text();
2508
+ }
2509
+ __name(parseResponseData, "parseResponseData");
2510
+ async function safeParseResponseData(response) {
2511
+ try {
2512
+ return await parseResponseData(response);
2513
+ } catch {
2514
+ return void 0;
2515
+ }
2516
+ }
2517
+ __name(safeParseResponseData, "safeParseResponseData");
2518
+ function createResponseError(response, errorData) {
2519
+ const message = typeof errorData === "string" ? errorData : typeof errorData === "object" && errorData ? String(
2520
+ errorData.error || errorData.message || response.statusText
2521
+ ) : response.statusText || "Integration request failed.";
2522
+ return new IntegrationClientError(message, response, errorData);
2523
+ }
2524
+ __name(createResponseError, "createResponseError");
2525
+ function normalizeExecutionError(error) {
2526
+ if (error instanceof Error) {
2527
+ return error;
2528
+ }
2529
+ if (typeof error === "string" && error.length > 0) {
2530
+ return new Error(error);
2531
+ }
2532
+ return new Error("Integration request failed.");
2533
+ }
2534
+ __name(normalizeExecutionError, "normalizeExecutionError");
2535
+ async function finalizeOperationResponse(operation, response) {
2536
+ if (!response.ok) {
2537
+ const errorData = await safeParseResponseData(response);
2538
+ return {
2539
+ data: null,
2540
+ error: createResponseError(response, errorData)
2541
+ };
2542
+ }
2543
+ if (operation.responseFormat === "response") {
2544
+ return {
2545
+ data: response,
2546
+ error: null
2547
+ };
2548
+ }
2549
+ return {
2550
+ data: await parseResponseData(response),
2551
+ error: null
2552
+ };
2553
+ }
2554
+ __name(finalizeOperationResponse, "finalizeOperationResponse");
2555
+ async function executeClientOperation(operation, input, options, requestOptions) {
2556
+ try {
2557
+ if (!operation.path) {
2558
+ return {
2559
+ data: null,
2560
+ error: new Error(
2561
+ "Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... })."
2562
+ )
2563
+ };
2564
+ }
2565
+ const baseURL = options.baseURL || (typeof window !== "undefined" ? window.location.origin : "http://localhost:3000");
2566
+ const url = new URL(operation.path, baseURL);
2567
+ appendQuery(url, input.query);
2568
+ const headers = new Headers({
2569
+ "x-farm-integration-client": "1",
2570
+ ...options.headers,
2571
+ ...operation.headers,
2572
+ ...requestOptions?.headers
2573
+ });
2574
+ if (operation.responseFormat !== "response") {
2575
+ headers.set("accept", "application/json");
2576
+ }
2577
+ appendIntegrationClientDataHeader(
2578
+ headers,
2579
+ mergeIntegrationClientData(options.data, requestOptions?.data)
2580
+ );
2581
+ const response = await fetch(url.toString(), {
2582
+ method: operation.method,
2583
+ headers,
2584
+ body: createBody(operation.bodyFormat, input.body, headers),
2585
+ credentials: requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? "include",
2586
+ signal: requestOptions?.signal
2587
+ });
2588
+ if (!response.ok) {
2589
+ const errorData = await safeParseResponseData(response);
2590
+ return {
2591
+ data: null,
2592
+ error: createResponseError(response, errorData)
2593
+ };
2594
+ }
2595
+ if (operation.responseFormat === "response") {
2596
+ return {
2597
+ data: response,
2598
+ error: null
2599
+ };
2600
+ }
2601
+ return {
2602
+ data: await parseResponseData(response),
2603
+ error: null
2604
+ };
2605
+ } catch (error) {
2606
+ return {
2607
+ data: null,
2608
+ error: normalizeExecutionError(error)
2609
+ };
2610
+ }
2611
+ }
2612
+ __name(executeClientOperation, "executeClientOperation");
2613
+ async function executeServerOperation(operation, input, options, requestOptions, integrationKey, source) {
2614
+ try {
2615
+ if (!operation.path) {
2616
+ return {
2617
+ data: null,
2618
+ error: new Error(
2619
+ "Integration API operation path is missing. Pass a path to api.get/post/... or wrap pathless methods with api.route(path, { ... })."
2620
+ )
2621
+ };
2622
+ }
2623
+ const serverRequestOptions = requestOptions && ("request" in requestOptions || "baseURL" in requestOptions || "forwardHeaders" in requestOptions) ? requestOptions : void 0;
2624
+ const currentRequest = serverRequestOptions?.request instanceof Request ? serverRequestOptions.request : options.request instanceof Request ? options.request : resolveCurrentRequestLocal();
2625
+ const request = resolveRequestLike(
2626
+ serverRequestOptions?.request ?? options.request ?? currentRequest
2627
+ );
2628
+ const baseURL = resolveServerBaseURL(serverRequestOptions?.baseURL ?? options.baseURL, request);
2629
+ const url = new URL(operation.path, baseURL);
2630
+ appendQuery(url, input.query);
2631
+ const headers = new Headers();
2632
+ appendHeaders(
2633
+ headers,
2634
+ resolveForwardHeaders(
2635
+ request,
2636
+ serverRequestOptions?.forwardHeaders ?? options.forwardHeaders
2637
+ )
2638
+ );
2639
+ appendHeaders(headers, options.headers);
2640
+ appendHeaders(headers, operation.headers);
2641
+ appendHeaders(headers, requestOptions?.headers);
2642
+ headers.set("x-farm-integration-client", "1");
2643
+ if (operation.responseFormat !== "response") {
2644
+ headers.set("accept", "application/json");
2645
+ }
2646
+ const data = mergeIntegrationClientData(options.data, requestOptions?.data);
2647
+ if (integrationKey) {
2648
+ const runtime = "kind" in (source || {}) && source.kind === "farm-integration" ? getRegisteredIntegrationRuntimeLocal(integrationKey) || {
2649
+ integration: source,
2650
+ config: {},
2651
+ isDev: process.env.NODE_ENV !== "production",
2652
+ isProd: process.env.NODE_ENV === "production"
2653
+ } : getRegisteredIntegrationRuntimeLocal(integrationKey);
2654
+ if (runtime) {
2655
+ const dispatchIntegrationRequest = resolveIntegrationRequestDispatcherLocal();
2656
+ const directResponse = dispatchIntegrationRequest ? await dispatchIntegrationRequest(
2657
+ runtime,
2658
+ new Request(url.toString(), {
2659
+ method: operation.method,
2660
+ headers,
2661
+ body: createBody(operation.bodyFormat, input.body, headers)
2662
+ }),
2663
+ {
2664
+ currentRequest,
2665
+ data,
2666
+ internal: true
2667
+ }
2668
+ ) : null;
2669
+ if (directResponse) {
2670
+ return await finalizeOperationResponse(operation, directResponse);
2671
+ }
2672
+ }
2673
+ }
2674
+ appendIntegrationClientDataHeader(headers, data);
2675
+ const response = await fetch(url.toString(), {
2676
+ method: operation.method,
2677
+ headers,
2678
+ body: createBody(operation.bodyFormat, input.body, headers),
2679
+ credentials: requestOptions?.credentials ?? operation.credentials ?? options.credentials ?? "include",
2680
+ signal: requestOptions?.signal
2681
+ });
2682
+ return await finalizeOperationResponse(operation, response);
2683
+ } catch (error) {
2684
+ return {
2685
+ data: null,
2686
+ error: normalizeExecutionError(error)
2687
+ };
2688
+ }
2689
+ }
2690
+ __name(executeServerOperation, "executeServerOperation");
2691
+ function createAutomaticIntegrationAliases(isServer, options = {}) {
2692
+ const cache = isServer ? /* @__PURE__ */ new Map() : null;
2693
+ const integrationNamespaces = new Proxy(
2694
+ {},
2695
+ {
2696
+ get(_target, property) {
2697
+ if (typeof property !== "string") {
2698
+ return void 0;
2699
+ }
2700
+ if (property === "integrations") {
2701
+ return integrationNamespaces;
2702
+ }
2703
+ if (cache?.has(property)) {
2704
+ return cache.get(property);
2705
+ }
2706
+ const namespaces = isServer ? resolveAutomaticServerNamespaces() : resolveAutomaticClientNamespaces();
2707
+ const match = namespaces.find(([key]) => key === property);
2708
+ if (!match) {
2709
+ return void 0;
2710
+ }
2711
+ const namespace = isServer ? createServerNamespaceProxy(
2712
+ match[0],
2713
+ match[2],
2714
+ match[1],
2715
+ options
2716
+ ) : createNamespaceProxy(match[1], options);
2717
+ cache?.set(property, namespace);
2718
+ return namespace;
2719
+ }
2720
+ }
2721
+ );
2722
+ Object.defineProperty(integrationNamespaces, "integrations", {
2723
+ value: integrationNamespaces,
2724
+ enumerable: false,
2725
+ configurable: false,
2726
+ writable: false
2727
+ });
2728
+ return integrationNamespaces;
2729
+ }
2730
+ __name(createAutomaticIntegrationAliases, "createAutomaticIntegrationAliases");
2731
+ function integrationsClient(options = {}) {
2732
+ return createAutomaticIntegrationAliases(
2733
+ false,
2734
+ options
2735
+ );
2736
+ }
2737
+ __name(integrationsClient, "integrationsClient");
2738
+ function integrationsServer(options = {}) {
2739
+ return createAutomaticIntegrationAliases(true, {
2740
+ ...options,
2741
+ isServer: true
2742
+ });
2743
+ }
2744
+ __name(integrationsServer, "integrationsServer");
2745
+ function resolveSingleNamespaceOperation(api2) {
2746
+ const entries = Object.entries(api2);
2747
+ if (entries.length !== 1) {
2748
+ return null;
2749
+ }
2750
+ const [, value] = entries[0];
2751
+ return isOperation(value) ? value : null;
2752
+ }
2753
+ __name(resolveSingleNamespaceOperation, "resolveSingleNamespaceOperation");
2754
+ function createClientOperationCaller(operation, property, options) {
2755
+ if (operation.isServer === true) {
2756
+ return async () => {
2757
+ throw new Error(
2758
+ `Integration method "${property}" is registered with isServer: true and is only available from a server integration client.`
2759
+ );
2760
+ };
2761
+ }
2762
+ return async (input = {}, requestOptions) => {
2763
+ if (typeof window === "undefined") {
2764
+ throw new Error(
2765
+ "Client integration API cannot be called on the server. Pass { isServer: true } to createIntegrationClient(...) during server rendering, or provide { isServer: true, request } outside it."
2766
+ );
2767
+ }
2768
+ return executeClientOperation(operation, input, options, requestOptions);
2769
+ };
2770
+ }
2771
+ __name(createClientOperationCaller, "createClientOperationCaller");
2772
+ function createServerOperationCaller(operation, options, integrationKey, source) {
2773
+ return async (input = {}, requestOptions) => {
2774
+ if (typeof window !== "undefined") {
2775
+ throw new Error(
2776
+ "Server integration API cannot be called in the browser. Remove { isServer: true } and create a client integration API instead."
2777
+ );
2778
+ }
2779
+ return executeServerOperation(
2780
+ operation,
2781
+ input,
2782
+ options,
2783
+ requestOptions,
2784
+ integrationKey,
2785
+ source
2786
+ );
2787
+ };
2788
+ }
2789
+ __name(createServerOperationCaller, "createServerOperationCaller");
2790
+ function createNamespaceProxy(api2, options) {
2791
+ const cache = /* @__PURE__ */ new Map();
2792
+ const directOperation = resolveSingleNamespaceOperation(api2);
2793
+ const target = directOperation ? createClientOperationCaller(directOperation, directOperation.method.toLowerCase(), options) : {};
2794
+ return new Proxy(target, {
2795
+ get(targetObject, property, receiver) {
2796
+ if (typeof property !== "string") {
2797
+ return Reflect.get(targetObject, property, receiver);
2798
+ }
2799
+ if (cache.has(property)) {
2800
+ return cache.get(property);
2801
+ }
2802
+ const value = api2[property];
2803
+ if (!value) {
2804
+ return Reflect.get(targetObject, property, receiver);
2805
+ }
2806
+ if (isOperation(value)) {
2807
+ const caller = createClientOperationCaller(value, property, options);
2808
+ cache.set(property, caller);
2809
+ return caller;
2810
+ }
2811
+ const namespace = createNamespaceProxy(value, options);
2812
+ cache.set(property, namespace);
2813
+ return namespace;
2814
+ }
2815
+ });
2816
+ }
2817
+ __name(createNamespaceProxy, "createNamespaceProxy");
2818
+ function createServerNamespaceProxy(integrationKey, source, api2, options) {
2819
+ const cache = /* @__PURE__ */ new Map();
2820
+ const directOperation = resolveSingleNamespaceOperation(api2);
2821
+ const target = directOperation ? createServerOperationCaller(directOperation, options, integrationKey, source) : {};
2822
+ return new Proxy(target, {
2823
+ get(targetObject, property, receiver) {
2824
+ if (typeof property !== "string") {
2825
+ return Reflect.get(targetObject, property, receiver);
2826
+ }
2827
+ if (cache.has(property)) {
2828
+ return cache.get(property);
2829
+ }
2830
+ const value = api2[property];
2831
+ if (!value) {
2832
+ return Reflect.get(targetObject, property, receiver);
2833
+ }
2834
+ if (isOperation(value)) {
2835
+ const caller = createServerOperationCaller(value, options, integrationKey, source);
2836
+ cache.set(property, caller);
2837
+ return caller;
2838
+ }
2839
+ const namespace = createServerNamespaceProxy(
2840
+ integrationKey,
2841
+ source,
2842
+ value,
2843
+ options
2844
+ );
2845
+ cache.set(property, namespace);
2846
+ return namespace;
2847
+ }
2848
+ });
2849
+ }
2850
+ __name(createServerNamespaceProxy, "createServerNamespaceProxy");
2851
+
2852
+ // src/client-cache.ts
2853
+ var _FarmClientDataCache = class _FarmClientDataCache {
2854
+ constructor() {
2855
+ this.entries = /* @__PURE__ */ new Map();
2856
+ this.aliases = /* @__PURE__ */ new Map();
2857
+ this.invalidatedAt = /* @__PURE__ */ new Map();
2858
+ this.listeners = /* @__PURE__ */ new Map();
2859
+ this.inflight = /* @__PURE__ */ new Map();
2860
+ subscribeFarmCacheInvalidation((key) => this.invalidate(key));
2861
+ }
2862
+ get size() {
2863
+ return this.entries.size;
2864
+ }
2865
+ resolveKey(key) {
2866
+ let resolved = key;
2867
+ const seen = /* @__PURE__ */ new Set();
2868
+ while (this.aliases.has(resolved) && !seen.has(resolved)) {
2869
+ seen.add(resolved);
2870
+ resolved = this.aliases.get(resolved);
2871
+ }
2872
+ return resolved;
2873
+ }
2874
+ get(key, now = Date.now()) {
2875
+ const resolved = this.resolveKey(key);
2876
+ const entry = this.entries.get(resolved);
2877
+ if (!entry) return void 0;
2878
+ if (entry.gcAt !== void 0 && now >= entry.gcAt) {
2879
+ this.entries.delete(resolved);
2880
+ this.emit(resolved);
2881
+ return void 0;
2882
+ }
2883
+ return entry;
2884
+ }
2885
+ set(key, entry) {
2886
+ const resolved = this.resolveKey(key);
2887
+ const invalidatedAt = this.invalidatedAt.get(resolved);
2888
+ const nextEntry = invalidatedAt !== void 0 && invalidatedAt > entry.updatedAt ? { ...entry, staleAt: 0, invalidatedAt } : { ...entry, invalidatedAt: void 0 };
2889
+ if (invalidatedAt === void 0 || entry.updatedAt >= invalidatedAt) {
2890
+ this.invalidatedAt.delete(resolved);
2891
+ }
2892
+ this.entries.set(resolved, nextEntry);
2893
+ this.emit(resolved);
2894
+ return this;
2895
+ }
2896
+ delete(key) {
2897
+ const resolved = this.resolveKey(key);
2898
+ const deleted = this.entries.delete(resolved);
2899
+ this.inflight.delete(resolved);
2900
+ this.emit(resolved);
2901
+ return deleted;
2902
+ }
2903
+ clear() {
2904
+ const keys = /* @__PURE__ */ new Set([...this.entries.keys(), ...this.listeners.keys()]);
2905
+ this.entries.clear();
2906
+ this.aliases.clear();
2907
+ this.invalidatedAt.clear();
2908
+ this.inflight.clear();
2909
+ for (const key of keys) this.emit(key);
2910
+ }
2911
+ isStale(key, now = Date.now()) {
2912
+ const entry = this.get(key, now);
2913
+ return !entry || entry.invalidatedAt !== void 0 || now >= entry.staleAt;
2914
+ }
2915
+ invalidate(key, now = Date.now()) {
2916
+ const resolved = this.resolveKey(key);
2917
+ this.invalidatedAt.set(resolved, now);
2918
+ const entry = this.entries.get(resolved);
2919
+ if (entry) {
2920
+ this.entries.set(resolved, {
2921
+ ...entry,
2922
+ staleAt: 0,
2923
+ invalidatedAt: now
2924
+ });
2925
+ }
2926
+ this.emit(resolved);
2927
+ }
2928
+ alias(alias, key) {
2929
+ const resolved = this.resolveKey(key);
2930
+ if (alias === resolved) return;
2931
+ const aliasEntry = this.entries.get(alias);
2932
+ if (aliasEntry && !this.entries.has(resolved)) {
2933
+ this.entries.set(resolved, aliasEntry);
2934
+ }
2935
+ this.entries.delete(alias);
2936
+ const aliasInflight = this.inflight.get(alias);
2937
+ if (aliasInflight && !this.inflight.has(resolved)) {
2938
+ this.inflight.set(resolved, aliasInflight);
2939
+ }
2940
+ this.inflight.delete(alias);
2941
+ this.aliases.set(alias, resolved);
2942
+ this.emit(alias);
2943
+ this.emit(resolved);
2944
+ }
2945
+ subscribe(key, listener) {
2946
+ let listeners = this.listeners.get(key);
2947
+ if (!listeners) {
2948
+ listeners = /* @__PURE__ */ new Set();
2949
+ this.listeners.set(key, listeners);
2950
+ }
2951
+ listeners.add(listener);
2952
+ return () => {
2953
+ listeners.delete(listener);
2954
+ if (listeners.size === 0) this.listeners.delete(key);
2955
+ };
2956
+ }
2957
+ getInflight(key) {
2958
+ return this.inflight.get(this.resolveKey(key));
2959
+ }
2960
+ setInflight(key, promise) {
2961
+ this.inflight.set(this.resolveKey(key), promise);
2962
+ }
2963
+ deleteInflight(key) {
2964
+ this.inflight.delete(this.resolveKey(key));
2965
+ }
2966
+ emit(key) {
2967
+ this.notifyListeners(key);
2968
+ for (const [alias, target] of this.aliases) {
2969
+ if (this.resolveKey(target) === key) {
2970
+ this.notifyListeners(alias);
2971
+ }
2972
+ }
2973
+ }
2974
+ notifyListeners(key) {
2975
+ for (const listener of this.listeners.get(key) ?? []) {
2976
+ listener();
2977
+ }
2978
+ }
2979
+ };
2980
+ __name(_FarmClientDataCache, "FarmClientDataCache");
2981
+ var FarmClientDataCache = _FarmClientDataCache;
2982
+ var FARM_CLIENT_DATA_CACHE = /* @__PURE__ */ Symbol.for("farm.clientDataCache");
2983
+ var clientCacheGlobal = globalThis;
2984
+ var sharedFarmClientDataCache = clientCacheGlobal[FARM_CLIENT_DATA_CACHE] ?? (clientCacheGlobal[FARM_CLIENT_DATA_CACHE] = new FarmClientDataCache());
2985
+ function getFarmClientDataCache() {
2986
+ return sharedFarmClientDataCache;
2987
+ }
2988
+ __name(getFarmClientDataCache, "getFarmClientDataCache");
2989
+ function normalizeFarmClientCacheKey(key) {
2990
+ return typeof key === "string" ? key : createRouteDataCacheKey(key);
2991
+ }
2992
+ __name(normalizeFarmClientCacheKey, "normalizeFarmClientCacheKey");
2993
+
2994
+ // src/api/client.ts
2995
+ var FARM_API_ROUTE_REF_SYMBOL = /* @__PURE__ */ Symbol.for("farm.api.route-ref");
2996
+ var FARM_API_ROUTE_META_SYMBOL = /* @__PURE__ */ Symbol.for("farm.api.route-meta");
2997
+ var _APIClientError = class _APIClientError extends Error {
2998
+ constructor(code, data, options) {
2999
+ super(options.message);
3000
+ this.name = "APIClientError";
3001
+ this.code = code;
3002
+ this.data = data;
3003
+ this.status = options.status;
3004
+ this.response = options.response;
3005
+ }
3006
+ };
3007
+ __name(_APIClientError, "APIClientError");
3008
+ var APIClientError = _APIClientError;
3009
+ function createAPIClient(options = {}) {
3010
+ options ?? (options = {});
3011
+ const baseURL = options.baseURL || (typeof window !== "undefined" ? window.location.origin : "http://localhost:3000");
3012
+ const integrationOptions = options.integrations === false ? false : {
3013
+ baseURL: options.baseURL,
3014
+ headers: options.headers,
3015
+ credentials: options.credentials,
3016
+ ...typeof options.integrations === "object" ? options.integrations : {}
3017
+ };
3018
+ const rootAliases = integrationOptions === false ? void 0 : {
3019
+ integrations: integrationsClient(integrationOptions)
3020
+ };
3021
+ const cacheState = getFarmClientDataCache();
3022
+ const inflightState = /* @__PURE__ */ new Map();
3023
+ const routeMeta = /* @__PURE__ */ new WeakMap();
3024
+ let requestCounter = 0;
3025
+ const fetchClient = /* @__PURE__ */ __name(async (path4, requestOptions = {}) => {
3026
+ const url = new URL(path4, baseURL);
3027
+ if (requestOptions.query) {
3028
+ Object.entries(requestOptions.query).forEach(([key, value]) => {
3029
+ if (value !== void 0 && value !== null) {
3030
+ url.searchParams.set(key, String(value));
3031
+ }
3032
+ });
3033
+ }
3034
+ const headers = {
3035
+ "Content-Type": "application/json",
3036
+ ...options.headers,
3037
+ ...requestOptions.headers
3038
+ };
3039
+ const fetchOptions = {
3040
+ method: requestOptions.method || "GET",
3041
+ headers
3042
+ };
3043
+ if (requestOptions.body !== void 0) {
3044
+ if (isFormData(requestOptions.body)) {
3045
+ deleteHeader(headers, "content-type");
3046
+ fetchOptions.body = requestOptions.body;
3047
+ } else {
3048
+ fetchOptions.body = JSON.stringify(requestOptions.body);
3049
+ }
3050
+ }
3051
+ const response = await fetch(url.toString(), fetchOptions);
3052
+ applyFarmCacheInvalidations(
3053
+ decodeFarmCacheInvalidations(response.headers?.get?.(FARM_CACHE_INVALIDATION_HEADER))
3054
+ );
3055
+ let data = void 0;
3056
+ if (response.status !== 204 && response.status !== 205) {
3057
+ data = isJSONStreamResponse(response) ? readJSONStream(response) : await response.json();
3058
+ }
3059
+ return { response, data };
3060
+ }, "fetchClient");
3061
+ const request = /* @__PURE__ */ __name(async (path4, method, input = {}, clientOptions) => {
3062
+ const methodUpper = method.toUpperCase();
3063
+ const requestId = `${Date.now()}-${++requestCounter}`;
3064
+ const cacheOptions = clientOptions?.cache ? {
3065
+ ...options.cacheDefaults,
3066
+ ...clientOptions.cache
3067
+ } : void 0;
3068
+ const configuredCacheKey = clientOptions?.key ?? cacheOptions?.key;
3069
+ const cacheKey = normalizeFarmClientCacheKey(
3070
+ configuredCacheKey ?? buildCacheKey(methodUpper, path4, input, baseURL)
3071
+ );
3072
+ const now = Date.now();
3073
+ const emitStatus = /* @__PURE__ */ __name((phase, payload) => {
3074
+ clientOptions?.onStatus?.({
3075
+ phase,
3076
+ requestId,
3077
+ method: methodUpper,
3078
+ key: cacheKey,
3079
+ input,
3080
+ timestamp: Date.now(),
3081
+ ...payload
3082
+ });
3083
+ }, "emitStatus");
3084
+ const entry = getValidCacheEntry(cacheState, cacheKey, now);
3085
+ const policy = cacheOptions?.policy ?? (cacheOptions ? "cache-first" : "network-only");
3086
+ const staleTime = cacheOptions?.staleTime ?? 0;
3087
+ const isCacheEnabled = Boolean(cacheOptions) && methodUpper === "GET";
3088
+ const isStale = entry ? isEntryStale(entry, now) : true;
3089
+ const applyOptimisticUpdates = /* @__PURE__ */ __name(() => {
3090
+ if (!clientOptions?.optimistic?.update?.length) return [];
3091
+ const snapshots = [];
3092
+ for (const update of clientOptions.optimistic.update) {
3093
+ const [target, targetInput, updater] = update.length === 2 ? [update[0], void 0, update[1]] : [update[0], update[1], update[2]];
3094
+ const targetKey = resolveTargetKey(routeMeta, target, targetInput, baseURL);
3095
+ if (!targetKey) continue;
3096
+ const targetEntry = getValidCacheEntry(cacheState, targetKey, now);
3097
+ const previousEntry = targetEntry ? { ...targetEntry } : void 0;
3098
+ const previousData = targetEntry?.data;
3099
+ const nextData = updater(previousData);
3100
+ cacheState.set(targetKey, {
3101
+ data: nextData,
3102
+ updatedAt: now,
3103
+ staleAt: targetEntry?.staleAt ?? now + (cacheOptions?.staleTime ?? options.cacheDefaults?.staleTime ?? 0),
3104
+ gcAt: targetEntry?.gcAt ?? getGcAt(now, cacheOptions?.gcTime ?? options.cacheDefaults?.gcTime),
3105
+ invalidatedAt: targetEntry?.invalidatedAt
3106
+ });
3107
+ snapshots.push({ key: targetKey, entry: previousEntry });
3108
+ }
3109
+ return snapshots;
3110
+ }, "applyOptimisticUpdates");
3111
+ const rollbackOptimisticUpdates = /* @__PURE__ */ __name((snapshots) => {
3112
+ if (!clientOptions?.optimistic?.rollbackOnError) return;
3113
+ for (const snapshot of snapshots) {
3114
+ if (!snapshot.entry) {
3115
+ cacheState.delete(snapshot.key);
3116
+ continue;
3117
+ }
3118
+ cacheState.set(snapshot.key, { ...snapshot.entry });
3119
+ }
3120
+ }, "rollbackOptimisticUpdates");
3121
+ const executeNetwork = /* @__PURE__ */ __name(async (opts) => {
3122
+ const dedupeMs = cacheOptions?.dedupeMs ?? 0;
3123
+ const inflight = inflightState.get(cacheKey);
3124
+ const allowDedupe = isCacheEnabled && dedupeMs > 0;
3125
+ if (allowDedupe && inflight && now - inflight.startedAt < dedupeMs) {
3126
+ emitStatus("pending", { isBackground: opts?.isBackground, data: entry?.data });
3127
+ const result2 = await inflight.promise;
3128
+ if (result2.error) {
3129
+ emitStatus("error", { error: result2.error, isBackground: opts?.isBackground });
3130
+ if (opts?.callCallbacks !== false) {
3131
+ clientOptions?.onError?.(result2.error);
3132
+ }
3133
+ } else {
3134
+ emitStatus("success", { data: result2.data, isBackground: opts?.isBackground });
3135
+ if (opts?.callCallbacks !== false) {
3136
+ clientOptions?.onSuccess?.(result2.data);
3137
+ }
3138
+ }
3139
+ return result2;
3140
+ }
3141
+ emitStatus(opts?.isBackground ? "revalidating" : "pending", {
3142
+ isBackground: opts?.isBackground
3143
+ });
3144
+ const promise = (async () => {
3145
+ const maxRetries = Math.max(0, clientOptions?.retry?.count ?? 0);
3146
+ let attempt = 0;
3147
+ while (true) {
3148
+ clientOptions?.onRequest?.({
3149
+ requestId,
3150
+ method: methodUpper,
3151
+ key: cacheKey,
3152
+ path: path4,
3153
+ input,
3154
+ attempt,
3155
+ timestamp: Date.now()
3156
+ });
3157
+ try {
3158
+ const { response, data } = await fetchClient(path4, {
3159
+ ...input,
3160
+ method: methodUpper
3161
+ });
3162
+ const error = response.ok ? null : createResponseError2(response, data);
3163
+ const responseEvent = {
3164
+ requestId,
3165
+ method: methodUpper,
3166
+ key: cacheKey,
3167
+ path: path4,
3168
+ input,
3169
+ attempt,
3170
+ timestamp: Date.now(),
3171
+ response,
3172
+ data: response.ok ? data : void 0,
3173
+ error: error ?? void 0,
3174
+ ok: response.ok,
3175
+ status: response.status
3176
+ };
3177
+ clientOptions?.onResponse?.(response.ok ? data : void 0, error, responseEvent);
3178
+ if (!error) {
3179
+ return { data, error: null, key: cacheKey };
3180
+ }
3181
+ if (attempt >= maxRetries) {
3182
+ return { data: void 0, error, key: cacheKey };
3183
+ }
3184
+ } catch (err) {
3185
+ const error = normalizeError(err);
3186
+ const responseEvent = {
3187
+ requestId,
3188
+ method: methodUpper,
3189
+ key: cacheKey,
3190
+ path: path4,
3191
+ input,
3192
+ attempt,
3193
+ timestamp: Date.now(),
3194
+ error,
3195
+ ok: false
3196
+ };
3197
+ clientOptions?.onResponse?.(void 0, error, responseEvent);
3198
+ if (attempt >= maxRetries) {
3199
+ return { data: void 0, error, key: cacheKey };
3200
+ }
3201
+ }
3202
+ attempt += 1;
3203
+ const delay2 = typeof clientOptions?.retry?.delay === "function" ? clientOptions.retry.delay(attempt) : clientOptions?.retry?.delay ?? 0;
3204
+ if (delay2 > 0) {
3205
+ await new Promise((resolve) => setTimeout(resolve, delay2));
3206
+ }
3207
+ }
3208
+ })();
3209
+ inflightState.set(cacheKey, { promise, startedAt: now });
3210
+ try {
3211
+ const result2 = await promise;
3212
+ if (!result2.error && isCacheEnabled && !isFarmAPIStream(result2.data)) {
3213
+ const updatedAt = Date.now();
3214
+ cacheState.set(cacheKey, {
3215
+ data: result2.data,
3216
+ updatedAt,
3217
+ staleAt: updatedAt + staleTime,
3218
+ gcAt: getGcAt(updatedAt, cacheOptions?.gcTime),
3219
+ invalidatedAt: void 0
3220
+ });
3221
+ }
3222
+ if (result2.error) {
3223
+ emitStatus("error", { error: result2.error, isBackground: opts?.isBackground });
3224
+ if (opts?.callCallbacks !== false) {
3225
+ clientOptions?.onError?.(result2.error);
3226
+ }
3227
+ } else {
3228
+ emitStatus("success", { data: result2.data, isBackground: opts?.isBackground });
3229
+ if (opts?.callCallbacks !== false) {
3230
+ clientOptions?.onSuccess?.(result2.data);
3231
+ }
3232
+ }
3233
+ return result2;
3234
+ } finally {
3235
+ inflightState.delete(cacheKey);
3236
+ }
3237
+ }, "executeNetwork");
3238
+ const invalidateTargets = /* @__PURE__ */ __name(async () => {
3239
+ if (!clientOptions?.invalidate) return;
3240
+ const invalidateOptions = Array.isArray(clientOptions.invalidate) ? { targets: clientOptions.invalidate, refetch: false } : {
3241
+ targets: clientOptions.invalidate.targets,
3242
+ refetch: clientOptions.invalidate.refetch ?? false
3243
+ };
3244
+ for (const target of invalidateOptions.targets) {
3245
+ const targetKey = resolveTargetKey(routeMeta, target, void 0, baseURL);
3246
+ if (!targetKey) continue;
3247
+ const existing = cacheState.get(targetKey);
3248
+ if (existing) {
3249
+ cacheState.set(targetKey, {
3250
+ ...existing,
3251
+ staleAt: 0,
3252
+ invalidatedAt: Date.now()
3253
+ });
3254
+ }
3255
+ emitStatus("invalidated", { key: targetKey });
3256
+ if (invalidateOptions.refetch && existing && targetKey === cacheKey) {
3257
+ void executeNetwork({ isBackground: true, callCallbacks: false });
3258
+ }
3259
+ }
3260
+ }, "invalidateTargets");
3261
+ const optimisticSnapshots = applyOptimisticUpdates();
3262
+ if (isCacheEnabled) {
3263
+ if (entry && !isStale && policy !== "network-only") {
3264
+ emitStatus("success", { data: entry.data });
3265
+ clientOptions?.onSuccess?.(entry.data);
3266
+ clientOptions?.onSettled?.(entry.data, null);
3267
+ return { data: entry.data, error: null, key: cacheKey };
3268
+ }
3269
+ if (entry && isStale && policy === "stale-while-revalidate") {
3270
+ emitStatus("success", { data: entry.data });
3271
+ clientOptions?.onSuccess?.(entry.data);
3272
+ clientOptions?.onSettled?.(entry.data, null);
3273
+ void executeNetwork({ isBackground: true, callCallbacks: false });
3274
+ return { data: entry.data, error: null, key: cacheKey };
3275
+ }
3276
+ }
3277
+ const result = await executeNetwork();
3278
+ if (result.error) {
3279
+ rollbackOptimisticUpdates(optimisticSnapshots);
3280
+ }
3281
+ await invalidateTargets();
3282
+ clientOptions?.onSettled?.(result.data, result.error);
3283
+ return result;
3284
+ }, "request");
3285
+ return createNestedProxy(
3286
+ [],
3287
+ request,
3288
+ routeMeta,
3289
+ baseURL,
3290
+ options.baseURL === void 0,
3291
+ rootAliases
3292
+ );
3293
+ }
3294
+ __name(createAPIClient, "createAPIClient");
3295
+ function createNestedProxy(path4, client, routeMeta, baseURL, sameOrigin, rootAliases) {
3296
+ const target = /* @__PURE__ */ __name(() => {
3297
+ }, "target");
3298
+ const proxy = new Proxy(target, {
3299
+ // When accessing a property (api.hello)
3300
+ get(_target, prop) {
3301
+ if (prop === FARM_API_ROUTE_REF_SYMBOL) {
3302
+ return path4.length > 0;
3303
+ }
3304
+ if (prop === FARM_API_ROUTE_META_SYMBOL) {
3305
+ const metadata = resolveRouteMeta({ path: path4, baseURL });
3306
+ return Object.freeze({
3307
+ path: metadata.routePath,
3308
+ method: metadata.method,
3309
+ baseURL,
3310
+ sameOrigin
3311
+ });
3312
+ }
3313
+ if (path4.length === 0 && typeof prop === "string" && rootAliases && prop in rootAliases) {
3314
+ return rootAliases[prop];
3315
+ }
3316
+ if (typeof prop !== "string") {
3317
+ return Reflect.get(_target, prop);
3318
+ }
3319
+ return createNestedProxy(
3320
+ [...path4, prop],
3321
+ client,
3322
+ routeMeta,
3323
+ baseURL,
3324
+ sameOrigin,
3325
+ rootAliases
3326
+ );
3327
+ },
3328
+ // When calling as a function
3329
+ apply(_target, _thisArg, args) {
3330
+ const lastPart = path4[path4.length - 1];
3331
+ const httpMethods = ["get", "post", "put", "delete", "patch", "options", "head"];
3332
+ if (httpMethods.includes(lastPart)) {
3333
+ const routePath = "/api/" + path4.slice(0, -1).join("/");
3334
+ const method = lastPart.toUpperCase();
3335
+ const [options, clientOptions] = args;
3336
+ return client(routePath, method, options, clientOptions);
3337
+ } else {
3338
+ const routePath = "/api/" + path4.join("/");
3339
+ const [options, clientOptions] = args;
3340
+ return client(routePath, options?.method || "GET", options, clientOptions);
3341
+ }
3342
+ }
3343
+ });
3344
+ routeMeta.set(proxy, { path: [...path4], baseURL });
3345
+ return proxy;
3346
+ }
3347
+ __name(createNestedProxy, "createNestedProxy");
3348
+ function isAPIRouteRef(value) {
3349
+ return typeof value === "function" && value[FARM_API_ROUTE_REF_SYMBOL] === true;
3350
+ }
3351
+ __name(isAPIRouteRef, "isAPIRouteRef");
3352
+ function getAPIRouteRefMetadata(value) {
3353
+ if (!isAPIRouteRef(value)) return null;
3354
+ const metadata = value[FARM_API_ROUTE_META_SYMBOL];
3355
+ if (!metadata || typeof metadata !== "object") return null;
3356
+ const candidate = metadata;
3357
+ if (typeof candidate.path !== "string" || typeof candidate.method !== "string" || typeof candidate.baseURL !== "string" || typeof candidate.sameOrigin !== "boolean") {
3358
+ return null;
3359
+ }
3360
+ return {
3361
+ path: candidate.path,
3362
+ method: candidate.method,
3363
+ baseURL: candidate.baseURL,
3364
+ sameOrigin: candidate.sameOrigin
3365
+ };
3366
+ }
3367
+ __name(getAPIRouteRefMetadata, "getAPIRouteRefMetadata");
3368
+ function createServerAPIClient(endpoints, options = {}) {
3369
+ if (options.integrations === false || Object.prototype.hasOwnProperty.call(endpoints, "integrations")) {
3370
+ return endpoints;
3371
+ }
3372
+ Object.defineProperty(endpoints, "integrations", {
3373
+ get() {
3374
+ return integrationsServer(
3375
+ typeof options.integrations === "object" ? options.integrations : {}
3376
+ );
3377
+ },
3378
+ enumerable: false,
3379
+ configurable: true
3380
+ });
3381
+ return endpoints;
3382
+ }
3383
+ __name(createServerAPIClient, "createServerAPIClient");
3384
+ function buildCacheKey(method, path4, input, baseURL) {
3385
+ const keyInput = input && typeof input === "object" ? { query: input.query, body: input.body } : input;
3386
+ const url = new URL(path4, baseURL);
3387
+ return `${method}:${url.origin}${url.pathname}:${stableStringify(keyInput ?? {})}`;
3388
+ }
3389
+ __name(buildCacheKey, "buildCacheKey");
3390
+ function stableStringify(value) {
3391
+ if (value === null || value === void 0) return String(value);
3392
+ if (value instanceof Date) return value.toISOString();
3393
+ if (typeof value !== "object") return JSON.stringify(value);
3394
+ if (Array.isArray(value)) {
3395
+ return `[${value.map((item) => stableStringify(item)).join(",")}]`;
3396
+ }
3397
+ const keys = Object.keys(value).sort();
3398
+ const entries = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
3399
+ return `{${entries.join(",")}}`;
3400
+ }
3401
+ __name(stableStringify, "stableStringify");
3402
+ function getGcAt(now, gcTime) {
3403
+ if (gcTime === void 0) return void 0;
3404
+ if (!Number.isFinite(gcTime) || gcTime <= 0) return now;
3405
+ return now + gcTime;
3406
+ }
3407
+ __name(getGcAt, "getGcAt");
3408
+ function getValidCacheEntry(cacheState, key, now) {
3409
+ const entry = cacheState.get(key);
3410
+ if (!entry) return void 0;
3411
+ if (entry.gcAt !== void 0 && now >= entry.gcAt) {
3412
+ cacheState.delete(key);
3413
+ return void 0;
3414
+ }
3415
+ return entry;
3416
+ }
3417
+ __name(getValidCacheEntry, "getValidCacheEntry");
3418
+ function isEntryStale(entry, now) {
3419
+ if (entry.invalidatedAt !== void 0) return true;
3420
+ return now >= entry.staleAt;
3421
+ }
3422
+ __name(isEntryStale, "isEntryStale");
3423
+ function resolveTargetKey(routeMeta, target, input, baseURL = "http://localhost:3000") {
3424
+ if (!target) return null;
3425
+ if (typeof target === "string") return target;
3426
+ if (typeof target === "function") {
3427
+ const meta = routeMeta.get(target);
3428
+ if (!meta) return null;
3429
+ const { method, routePath } = resolveRouteMeta(meta);
3430
+ return buildCacheKey(method, routePath, input ?? {}, meta.baseURL);
3431
+ }
3432
+ if (Array.isArray(target)) {
3433
+ const [route, routeInput] = target;
3434
+ if (typeof route === "function") {
3435
+ return resolveTargetKey(routeMeta, route, routeInput, baseURL);
3436
+ }
3437
+ return normalizeFarmClientCacheKey(target);
3438
+ }
3439
+ if ("key" in target) return normalizeFarmClientCacheKey(target.key);
3440
+ if ("path" in target) {
3441
+ const method = target.method ?? "GET";
3442
+ return buildCacheKey(method, target.path, target.input ?? {}, baseURL);
3443
+ }
3444
+ return null;
3445
+ }
3446
+ __name(resolveTargetKey, "resolveTargetKey");
3447
+ function resolveRouteMeta(meta) {
3448
+ const httpMethods = ["get", "post", "put", "delete", "patch", "options", "head"];
3449
+ const lastPart = meta.path[meta.path.length - 1];
3450
+ if (lastPart && httpMethods.includes(lastPart)) {
3451
+ return {
3452
+ routePath: "/api/" + meta.path.slice(0, -1).join("/"),
3453
+ method: lastPart.toUpperCase()
3454
+ };
3455
+ }
3456
+ return {
3457
+ routePath: "/api/" + meta.path.join("/"),
3458
+ method: "GET"
3459
+ };
3460
+ }
3461
+ __name(resolveRouteMeta, "resolveRouteMeta");
3462
+ function normalizeError(error) {
3463
+ if (error instanceof APIClientError) return error;
3464
+ const normalized = new APIClientError("network_error", void 0, {
3465
+ status: 0,
3466
+ message: error instanceof Error ? error.message : typeof error === "string" ? error : "Network request failed"
3467
+ });
3468
+ normalized.cause = error;
3469
+ return normalized;
3470
+ }
3471
+ __name(normalizeError, "normalizeError");
3472
+ function isFormData(value) {
3473
+ return typeof value === "object" && value !== null && (typeof FormData !== "undefined" && value instanceof FormData || Object.prototype.toString.call(value) === "[object FormData]" && typeof value.entries === "function");
3474
+ }
3475
+ __name(isFormData, "isFormData");
3476
+ function deleteHeader(headers, name) {
3477
+ const normalized = name.toLowerCase();
3478
+ for (const key of Object.keys(headers)) {
3479
+ if (key.toLowerCase() === normalized) delete headers[key];
3480
+ }
3481
+ }
3482
+ __name(deleteHeader, "deleteHeader");
3483
+ function createResponseError2(response, data) {
3484
+ const expected = readEndpointErrorEnvelope(data);
3485
+ if (expected) {
3486
+ return new APIClientError(expected.code, expected.data, {
3487
+ status: response.status,
3488
+ message: expected.message,
3489
+ response
3490
+ });
3491
+ }
3492
+ return new APIClientError("http_error", data, {
3493
+ status: response.status,
3494
+ message: `HTTP ${response.status}: ${response.statusText}`,
3495
+ response
3496
+ });
3497
+ }
3498
+ __name(createResponseError2, "createResponseError");
3499
+ function readEndpointErrorEnvelope(data) {
3500
+ if (!data || typeof data !== "object") return null;
3501
+ const error = data.error;
3502
+ if (!error || typeof error !== "object") return null;
3503
+ const code = error.code;
3504
+ const message = error.message;
3505
+ if (typeof code !== "string" || typeof message !== "string") return null;
3506
+ return {
3507
+ code,
3508
+ message,
3509
+ data: error.data
3510
+ };
3511
+ }
3512
+ __name(readEndpointErrorEnvelope, "readEndpointErrorEnvelope");
3513
+
3514
+ // src/server/response.ts
3515
+ var import_node_events = require("events");
3516
+ async function sendWebResponse(res, response) {
3517
+ res.statusCode = response.status;
3518
+ const responseHeaders = response.headers;
3519
+ const setCookies = responseHeaders.getSetCookie?.() || [];
3520
+ if (setCookies.length > 0) {
3521
+ res.setHeader("Set-Cookie", setCookies);
3522
+ }
3523
+ response.headers.forEach((value, key) => {
3524
+ if (key.toLowerCase() === "set-cookie" && setCookies.length > 0) {
3525
+ return;
3526
+ }
3527
+ res.setHeader(key, value);
3528
+ });
3529
+ if (!response.body) {
3530
+ res.end();
3531
+ return;
3532
+ }
3533
+ if (typeof res.write !== "function") {
3534
+ const body = await response.arrayBuffer();
3535
+ res.end(Buffer.from(body));
3536
+ return;
3537
+ }
3538
+ const reader = response.body.getReader();
3539
+ try {
3540
+ while (true) {
3541
+ const { done, value } = await reader.read();
3542
+ if (done) {
3543
+ break;
3544
+ }
3545
+ if (!value || value.byteLength === 0) {
3546
+ continue;
3547
+ }
3548
+ if (!res.write(value)) {
3549
+ await (0, import_node_events.once)(res, "drain");
3550
+ }
3551
+ }
3552
+ res.end();
3553
+ } catch (error) {
3554
+ if (!res.writableEnded) {
3555
+ const responseError = error instanceof Error ? error : new Error(String(error));
3556
+ if (typeof res.destroy === "function") {
3557
+ res.destroy(responseError);
3558
+ } else {
3559
+ res.end();
3560
+ }
3561
+ }
3562
+ throw error;
3563
+ } finally {
3564
+ reader.releaseLock();
3565
+ }
3566
+ }
3567
+ __name(sendWebResponse, "sendWebResponse");
3568
+
3569
+ // src/after.ts
3570
+ var import_node_async_hooks3 = require("async_hooks");
3571
+ var AFTER_STORAGE = /* @__PURE__ */ Symbol.for("@farm.js/core/after-storage");
3572
+ function getAfterStorage() {
3573
+ const runtime = globalThis;
3574
+ const existing = runtime[AFTER_STORAGE];
3575
+ if (existing instanceof import_node_async_hooks3.AsyncLocalStorage) {
3576
+ return existing;
3577
+ }
3578
+ const storage = new import_node_async_hooks3.AsyncLocalStorage();
3579
+ runtime[AFTER_STORAGE] = storage;
3580
+ return storage;
3581
+ }
3582
+ __name(getAfterStorage, "getAfterStorage");
3583
+ var afterStorage = getAfterStorage();
3584
+ function defaultAfterErrorReporter(error) {
3585
+ console.error("[Farm.js] after() callback failed:", error);
3586
+ }
3587
+ __name(defaultAfterErrorReporter, "defaultAfterErrorReporter");
3588
+ function reportAfterError(state, error) {
3589
+ try {
3590
+ state.reportError(error);
3591
+ } catch {
3592
+ }
3593
+ }
3594
+ __name(reportAfterError, "reportAfterError");
3595
+ function createAfterRequestState(reportError = defaultAfterErrorReporter) {
3596
+ let resolveResponseFinished;
3597
+ let responseFinished = false;
3598
+ const responseFinishedPromise = new Promise((resolve) => {
3599
+ resolveResponseFinished = resolve;
3600
+ });
3601
+ const state = {
3602
+ completion: Promise.resolve(),
3603
+ finishResponse: /* @__PURE__ */ __name(() => {
3604
+ if (responseFinished) return;
3605
+ responseFinished = true;
3606
+ resolveResponseFinished();
3607
+ }, "finishResponse"),
3608
+ phase: "open",
3609
+ reportError,
3610
+ tasks: []
3611
+ };
3612
+ state.completion = responseFinishedPromise.then(
3613
+ () => afterStorage.run(state, async () => {
3614
+ state.phase = "running";
3615
+ for (let index = 0; index < state.tasks.length; index++) {
3616
+ const task = state.tasks[index];
3617
+ task.start();
3618
+ try {
3619
+ await task.result;
3620
+ } catch (error) {
3621
+ reportAfterError(state, error);
3622
+ }
3623
+ }
3624
+ state.phase = "closed";
3625
+ })
3626
+ );
3627
+ return state;
3628
+ }
3629
+ __name(createAfterRequestState, "createAfterRequestState");
3630
+ function registerPlatformLifetime(state, context) {
3631
+ if (!context?.waitUntil) return;
3632
+ try {
3633
+ context.waitUntil(state.completion);
3634
+ } catch (error) {
3635
+ reportAfterError(state, error);
3636
+ }
3637
+ }
3638
+ __name(registerPlatformLifetime, "registerPlatformLifetime");
3639
+ function finishSoon(state) {
3640
+ setTimeout(state.finishResponse, 0);
3641
+ }
3642
+ __name(finishSoon, "finishSoon");
3643
+ async function _runWithAfterNodeResponse(response, handler, context) {
3644
+ if (afterStorage.getStore()) {
3645
+ return await handler();
3646
+ }
3647
+ const state = createAfterRequestState();
3648
+ let finished = false;
3649
+ const finish = /* @__PURE__ */ __name(() => {
3650
+ if (finished) return;
3651
+ finished = true;
3652
+ response.off("finish", finish);
3653
+ response.off("close", finish);
3654
+ state.finishResponse();
3655
+ }, "finish");
3656
+ response.once("finish", finish);
3657
+ response.once("close", finish);
3658
+ if (response.writableEnded) finishSoon(state);
3659
+ registerPlatformLifetime(state, context);
3660
+ return await afterStorage.run(state, handler);
3661
+ }
3662
+ __name(_runWithAfterNodeResponse, "_runWithAfterNodeResponse");
3663
+ function _withAfterNodeMiddleware(handler) {
3664
+ return async (request, response, next) => {
3665
+ await _runWithAfterNodeResponse(response, () => handler(request, response, next));
3666
+ };
3667
+ }
3668
+ __name(_withAfterNodeMiddleware, "_withAfterNodeMiddleware");
3669
+
3670
+ // src/api/vite-plugin.ts
3671
+ function farmApiPlugin(options = {}) {
3672
+ const srcDir = options.srcDir ?? "src";
3673
+ const debug = options.debug ?? false;
3674
+ let apiRoutesCache = /* @__PURE__ */ new Map();
3675
+ let apiRouterHandler = null;
3676
+ let discoveryComplete = false;
3677
+ let discoveryPromise = null;
3678
+ const log = /* @__PURE__ */ __name((_message) => {
3679
+ }, "log");
3680
+ const logResponse = /* @__PURE__ */ __name((method, urlPath, status, duration) => {
3681
+ try {
3682
+ const pc = require("picocolors");
3683
+ let statusColor = pc.green;
3684
+ if (status >= 500) statusColor = pc.red;
3685
+ else if (status >= 400) statusColor = pc.yellow;
3686
+ else if (status >= 300) statusColor = pc.cyan;
3687
+ const logMsg = [
3688
+ pc.dim("[") + pc.bold(pc.blue("FARM")) + pc.dim("]"),
3689
+ pc.dim("[") + pc.bold(pc.cyan("API")) + pc.dim("]"),
3690
+ pc.dim("[") + pc.bold(pc.white(method.padEnd(3))) + pc.dim("]"),
3691
+ pc.gray(urlPath),
3692
+ pc.dim("-"),
3693
+ statusColor(status.toString()),
3694
+ pc.dim(`(${duration}ms)`)
3695
+ ].join(" ");
3696
+ console.log(logMsg);
3697
+ } catch {
3698
+ console.log(`[FARM] [API] [${method}] ${urlPath} - ${status} (${duration}ms)`);
3699
+ }
3700
+ }, "logResponse");
3701
+ const addEndpoint = /* @__PURE__ */ __name((routePath, filePath, method, endpoint) => {
3702
+ const normalizedMethod = method.toUpperCase();
3703
+ const existing = apiRoutesCache.get(routePath);
3704
+ if (existing) {
3705
+ if (!existing.methods.includes(normalizedMethod)) {
3706
+ existing.methods.push(normalizedMethod);
3707
+ }
3708
+ existing.endpoints[normalizedMethod] = endpoint;
3709
+ return;
3710
+ }
3711
+ apiRoutesCache.set(routePath, {
3712
+ path: routePath,
3713
+ filePath,
3714
+ methods: [normalizedMethod],
3715
+ endpoints: { [normalizedMethod]: endpoint }
3716
+ });
3717
+ }, "addEndpoint");
3718
+ const createRouter = /* @__PURE__ */ __name(async () => {
3719
+ const totalEndpoints = Array.from(apiRoutesCache.values()).reduce(
3720
+ (sum, route) => sum + route.methods.length,
3721
+ 0
3722
+ );
3723
+ apiRouterHandler = null;
3724
+ if (totalEndpoints > 0) {
3725
+ apiRouterHandler = /* @__PURE__ */ __name(async (request) => {
3726
+ const url = new URL(request.url);
3727
+ const method = request.method.toUpperCase();
3728
+ const pathname = url.pathname;
3729
+ const match = matchAPIRoute(apiRoutesCache, pathname);
3730
+ if (!match) {
3731
+ return new Response(JSON.stringify({ error: "Not Found" }), {
3732
+ status: 404,
3733
+ headers: { "Content-Type": "application/json" }
3734
+ });
3735
+ }
3736
+ const { route, params } = match;
3737
+ const endpoint = route.endpoints[method];
3738
+ if (!endpoint) {
3739
+ return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
3740
+ status: 405,
3741
+ headers: { "Content-Type": "application/json" }
3742
+ });
3743
+ }
3744
+ try {
3745
+ return await invokeAPIRouteEndpoint(endpoint, request, params);
3746
+ } catch (error) {
3747
+ return new Response(JSON.stringify({ error: error.message || "Internal Server Error" }), {
3748
+ status: 500,
3749
+ headers: { "Content-Type": "application/json" }
3750
+ });
3751
+ }
3752
+ }, "apiRouterHandler");
3753
+ log(`API router created with ${totalEndpoints} endpoints`);
3754
+ }
3755
+ }, "createRouter");
3756
+ return {
3757
+ name: "@farm.js/core:api",
3758
+ enforce: "pre",
3759
+ configureServer(server) {
3760
+ const discoverFileRoutes = /* @__PURE__ */ __name(async (apiDir) => {
3761
+ const fs2 = await import("fs");
3762
+ const path4 = await import("path");
3763
+ if (!fs2.existsSync(apiDir)) {
3764
+ log("No api directory found");
3765
+ return;
3766
+ }
3767
+ const findRouteFiles = /* @__PURE__ */ __name((dir) => {
3768
+ const files = [];
3769
+ if (!fs2.existsSync(dir)) return files;
3770
+ const entries = fs2.readdirSync(dir, { withFileTypes: true });
3771
+ for (const entry of entries) {
3772
+ const fullPath = path4.join(dir, entry.name);
3773
+ if (entry.isDirectory()) {
3774
+ files.push(...findRouteFiles(fullPath));
3775
+ } else if (entry.name === "route.ts" || entry.name === "route.tsx" || entry.name === "route.js") {
3776
+ files.push(fullPath);
3777
+ }
3778
+ }
3779
+ return files;
3780
+ }, "findRouteFiles");
3781
+ const routeFiles = findRouteFiles(apiDir);
3782
+ apiRoutesCache.clear();
3783
+ for (const filePath of routeFiles) {
3784
+ try {
3785
+ const relativePath = path4.relative(apiDir, path4.dirname(filePath));
3786
+ const routePath = "/api/" + (relativePath === "." ? "" : relativePath.replace(/\\/g, "/"));
3787
+ const routeModule = await server.ssrLoadModule(filePath);
3788
+ const endpoints = {};
3789
+ const availableMethods = [];
3790
+ for (const method of API_ROUTE_METHODS) {
3791
+ if (routeModule[method]) {
3792
+ availableMethods.push(method);
3793
+ endpoints[method] = routeModule[method];
3794
+ }
3795
+ }
3796
+ if (availableMethods.length > 0) {
3797
+ apiRoutesCache.set(routePath, {
3798
+ path: routePath,
3799
+ filePath,
3800
+ methods: availableMethods,
3801
+ endpoints
3802
+ });
3803
+ log(`API route discovered: ${availableMethods.join(", ")} ${routePath}`);
3804
+ }
3805
+ } catch (e) {
3806
+ log(`API route load failed at ${filePath}: ${e.message}`);
3807
+ }
3808
+ }
3809
+ }, "discoverFileRoutes");
3810
+ const discoverRootRoutes = /* @__PURE__ */ __name(async () => {
3811
+ const fs2 = await import("fs");
3812
+ const path4 = await import("path");
3813
+ const routesFiles = [
3814
+ path4.join(server.config.root, srcDir, "routes.ts"),
3815
+ path4.join(server.config.root, srcDir, "routes.tsx"),
3816
+ path4.join(server.config.root, srcDir, "routes.js")
3817
+ ];
3818
+ for (const routesFile of routesFiles) {
3819
+ if (fs2.existsSync(routesFile)) {
3820
+ try {
3821
+ const routesModule = await server.ssrLoadModule(routesFile);
3822
+ for (const [exportName, exportValue] of Object.entries(routesModule)) {
3823
+ const endpoint = exportValue;
3824
+ if (endpoint && endpoint.__path) {
3825
+ const routePath = endpoint.__path;
3826
+ const method = String(endpoint.__method || "GET").toUpperCase();
3827
+ addEndpoint(routePath, routesFile, method, endpoint);
3828
+ log(`Root route discovered: ${method} ${routePath}`);
3829
+ }
3830
+ }
3831
+ } catch (e) {
3832
+ log(`Root routes.ts load failed: ${e.message}`);
3833
+ }
3834
+ break;
3835
+ }
3836
+ }
3837
+ }, "discoverRootRoutes");
3838
+ const discoverProgrammaticRoutes = /* @__PURE__ */ __name(async () => {
3839
+ const path4 = await import("path");
3840
+ const srcRoot = path4.join(server.config.root, srcDir);
3841
+ const routeFiles = findProgrammaticRouteFilesInDir(srcRoot);
3842
+ for (const routeFile of routeFiles) {
3843
+ try {
3844
+ const routesModule = await server.ssrLoadModule(
3845
+ toViteModuleId(routeFile, server.config.root)
3846
+ );
3847
+ const manifest = getProgrammaticRouteManifest(routesModule);
3848
+ if (!manifest) continue;
3849
+ for (const definition of manifest.routes) {
3850
+ if (definition.kind !== "api") continue;
3851
+ for (const [method, endpoint] of Object.entries(definition.methods)) {
3852
+ if (endpoint) {
3853
+ addEndpoint(definition.path, routeFile, method, endpoint);
3854
+ log(`Programmatic route discovered: ${method} ${definition.path}`);
3855
+ }
3856
+ }
3857
+ }
3858
+ } catch (e) {
3859
+ log(`Programmatic routes file load failed at ${routeFile}: ${e.message}`);
3860
+ }
3861
+ }
3862
+ }, "discoverProgrammaticRoutes");
3863
+ const initializeDiscovery = /* @__PURE__ */ __name(async () => {
3864
+ const path4 = await import("path");
3865
+ const apiDir = path4.join(server.config.root, srcDir, "api");
3866
+ log(`Discovering API routes in: ${apiDir}`);
3867
+ await discoverFileRoutes(apiDir);
3868
+ await discoverRootRoutes();
3869
+ await discoverProgrammaticRoutes();
3870
+ await createRouter();
3871
+ discoveryComplete = true;
3872
+ log(`API discovery complete: ${apiRoutesCache.size} routes found`);
3873
+ }, "initializeDiscovery");
3874
+ discoveryPromise = initializeDiscovery().catch((e) => {
3875
+ console.error("[FARM] API discovery error:", e);
3876
+ });
3877
+ server.__farmApi__ = {
3878
+ getHandler: /* @__PURE__ */ __name(() => apiRouterHandler, "getHandler"),
3879
+ getRoutes: /* @__PURE__ */ __name(() => apiRoutesCache, "getRoutes"),
3880
+ isReady: /* @__PURE__ */ __name(() => discoveryComplete, "isReady"),
3881
+ waitForDiscovery: /* @__PURE__ */ __name(() => discoveryPromise, "waitForDiscovery")
3882
+ };
3883
+ return () => {
3884
+ server.middlewares.use(
3885
+ _withAfterNodeMiddleware(async (req, res, next) => {
3886
+ const url = req.url || "/";
3887
+ const pathname = url.split("?")[0];
3888
+ const method = req.method || "GET";
3889
+ if (discoveryPromise && !discoveryComplete) {
3890
+ await discoveryPromise;
3891
+ }
3892
+ if (!matchAPIRoute(apiRoutesCache, pathname)) {
3893
+ return next();
3894
+ }
3895
+ if (!apiRouterHandler) {
3896
+ return next();
3897
+ }
3898
+ const startTime = Date.now();
3899
+ try {
3900
+ const farmMiddleware = server.__farmMiddleware__;
3901
+ if (farmMiddleware) {
3902
+ await farmMiddleware.waitForDiscovery?.();
3903
+ const middlewareData = /* @__PURE__ */ new Map();
3904
+ const handled = await farmMiddleware.execute(req, res, pathname, middlewareData);
3905
+ if (handled) {
3906
+ const duration2 = Date.now() - startTime;
3907
+ logResponse(method, pathname, res.statusCode || 200, duration2);
3908
+ return;
3909
+ }
3910
+ }
3911
+ const fullUrl = `http://${req.headers.host || "localhost:3000"}${url}`;
3912
+ const headers = new Headers();
3913
+ for (const [key, value] of Object.entries(req.headers)) {
3914
+ if (value) {
3915
+ headers.set(key, Array.isArray(value) ? value.join(", ") : value);
3916
+ }
3917
+ }
3918
+ let body;
3919
+ if (method !== "GET" && method !== "HEAD") {
3920
+ body = await new Promise((resolve) => {
3921
+ let data = "";
3922
+ req.on("data", (chunk) => {
3923
+ data += chunk;
3924
+ });
3925
+ req.on("end", () => {
3926
+ resolve(data);
3927
+ });
3928
+ });
3929
+ }
3930
+ const request = new Request(fullUrl, {
3931
+ method,
3932
+ headers,
3933
+ body: body || void 0
3934
+ });
3935
+ const response = await apiRouterHandler(request);
3936
+ const duration = Date.now() - startTime;
3937
+ logResponse(method, pathname, response.status, duration);
3938
+ await sendWebResponse(res, response);
3939
+ } catch (error) {
3940
+ const duration = Date.now() - startTime;
3941
+ logResponse(method, pathname, 500, duration);
3942
+ console.error("[FARM] API error:", error);
3943
+ res.statusCode = 500;
3944
+ res.setHeader("Content-Type", "application/json");
3945
+ res.end(JSON.stringify({ error: "Internal server error" }));
3946
+ }
3947
+ })
3948
+ );
3949
+ };
3950
+ },
3951
+ async handleHotUpdate({ file, server, modules }) {
3952
+ const fileName = file.split("/").pop() || "";
3953
+ if (fileName === "routes.ts" || fileName === "routes.tsx" || fileName === "routes.js" || isProgrammaticRoutesFileName(fileName)) {
3954
+ log(`Root routes file updated: ${fileName}`);
3955
+ for (const mod of modules) {
3956
+ server.moduleGraph.invalidateModule(mod);
3957
+ }
3958
+ for (const [routePath, route] of apiRoutesCache) {
3959
+ if (route.filePath === file) {
3960
+ apiRoutesCache.delete(routePath);
3961
+ }
3962
+ }
3963
+ try {
3964
+ const routesModule = await server.ssrLoadModule(file);
3965
+ for (const [exportName, exportValue] of Object.entries(routesModule)) {
3966
+ const endpoint = exportValue;
3967
+ if (endpoint && endpoint.__path) {
3968
+ const routePath = endpoint.__path;
3969
+ const method = String(endpoint.__method || "GET").toUpperCase();
3970
+ addEndpoint(routePath, file, method, endpoint);
3971
+ log(`Root route reloaded: ${method} ${routePath}`);
3972
+ }
3973
+ }
3974
+ const manifest = getProgrammaticRouteManifest(routesModule);
3975
+ if (manifest) {
3976
+ for (const definition of manifest.routes) {
3977
+ if (definition.kind !== "api") continue;
3978
+ for (const [method, endpoint] of Object.entries(definition.methods)) {
3979
+ if (endpoint) {
3980
+ addEndpoint(definition.path, file, method, endpoint);
3981
+ log(`Programmatic route reloaded: ${method} ${definition.path}`);
3982
+ }
3983
+ }
3984
+ }
3985
+ }
3986
+ await createRouter();
3987
+ log(`API router recreated`);
3988
+ } catch (e) {
3989
+ log(`Root routes.ts HMR failed: ${e.message}`);
3990
+ }
3991
+ return [];
3992
+ }
3993
+ if (file.includes("/api/") && fileName.startsWith("route.")) {
3994
+ const shortPath = file.split("/api/")[1] || file;
3995
+ log(`API route updated: ${shortPath}`);
3996
+ for (const mod of modules) {
3997
+ server.moduleGraph.invalidateModule(mod);
3998
+ }
3999
+ let routePathToUpdate = null;
4000
+ for (const [routePath, route] of apiRoutesCache) {
4001
+ if (route.filePath === file) {
4002
+ routePathToUpdate = routePath;
4003
+ break;
4004
+ }
4005
+ }
4006
+ if (routePathToUpdate) {
4007
+ try {
4008
+ const routeModule = await server.ssrLoadModule(file);
4009
+ const endpoints = {};
4010
+ const availableMethods = [];
4011
+ for (const method of API_ROUTE_METHODS) {
4012
+ if (routeModule[method]) {
4013
+ availableMethods.push(method);
4014
+ endpoints[method] = routeModule[method];
4015
+ }
4016
+ }
4017
+ if (availableMethods.length > 0) {
4018
+ apiRoutesCache.set(routePathToUpdate, {
4019
+ path: routePathToUpdate,
4020
+ filePath: file,
4021
+ methods: availableMethods,
4022
+ endpoints
4023
+ });
4024
+ log(`API route reloaded: ${routePathToUpdate}`);
4025
+ await createRouter();
4026
+ log(`API router recreated`);
4027
+ }
4028
+ } catch (e) {
4029
+ log(`API route HMR failed: ${e.message}`);
4030
+ }
4031
+ } else {
4032
+ try {
4033
+ const path4 = await import("path");
4034
+ const apiDir = path4.join(server.config.root, srcDir, "api");
4035
+ const relativePath = path4.relative(apiDir, path4.dirname(file));
4036
+ const routePath = "/api/" + (relativePath === "." ? "" : relativePath.replace(/\\/g, "/"));
4037
+ const routeModule = await server.ssrLoadModule(file);
4038
+ const endpoints = {};
4039
+ const availableMethods = [];
4040
+ for (const method of API_ROUTE_METHODS) {
4041
+ if (routeModule[method]) {
4042
+ availableMethods.push(method);
4043
+ endpoints[method] = routeModule[method];
4044
+ }
4045
+ }
4046
+ if (availableMethods.length > 0) {
4047
+ apiRoutesCache.set(routePath, {
4048
+ path: routePath,
4049
+ filePath: file,
4050
+ methods: availableMethods,
4051
+ endpoints
4052
+ });
4053
+ log(`New API route discovered: ${routePath}`);
4054
+ await createRouter();
4055
+ }
4056
+ } catch (e) {
4057
+ log(`New API route load failed: ${e.message}`);
4058
+ }
4059
+ }
4060
+ return [];
4061
+ }
4062
+ }
4063
+ };
4064
+ }
4065
+ __name(farmApiPlugin, "farmApiPlugin");
4066
+ // Annotate the CommonJS export names for ESM import in node:
4067
+ 0 && (module.exports = {
4068
+ APIClientError,
4069
+ APIRouteManager,
4070
+ API_ROUTE_METHODS,
4071
+ DELETE,
4072
+ EndpointFailure,
4073
+ FARM_API_ROUTE_META_SYMBOL,
4074
+ FARM_API_ROUTE_REF_SYMBOL,
4075
+ GET,
4076
+ HEAD,
4077
+ OPTIONS,
4078
+ PATCH,
4079
+ POST,
4080
+ PUT,
4081
+ createAPIClient,
4082
+ createEndpoint,
4083
+ createServerAPIClient,
4084
+ farmApiPlugin,
4085
+ getAPIRouteRefMetadata,
4086
+ invokeAPIRouteEndpoint,
4087
+ isAPIRouteRef,
4088
+ isEndpointFailure,
4089
+ isFarmAPIStream,
4090
+ isJSONStreamResponse,
4091
+ isMultipartSchema,
4092
+ isWebResponse,
4093
+ jsonStream,
4094
+ matchAPIRoute,
4095
+ multipart,
4096
+ normalizeRouteResponse,
4097
+ readJSONStream,
4098
+ toFormData
4099
+ });
4100
+ //# sourceMappingURL=api.cjs.map