@farm.js/core 0.1.16 → 0.1.18

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 (390) hide show
  1. package/dist/after.cjs +12 -225
  2. package/dist/agent-runtime.cjs +83 -2800
  3. package/dist/agent-runtime.d.mts +3 -3
  4. package/dist/agent-runtime.d.ts +3 -3
  5. package/dist/api/client.cjs +17 -4026
  6. package/dist/api/client.d.mts +3 -3
  7. package/dist/api/client.d.ts +3 -3
  8. package/dist/api/client.mjs +3 -3
  9. package/dist/api/route-manager.cjs +34 -4317
  10. package/dist/api/route-manager.d.mts +3 -3
  11. package/dist/api/route-manager.d.ts +3 -3
  12. package/dist/api/route-manager.mjs +5 -5
  13. package/dist/api/runtime.cjs +29 -2660
  14. package/dist/api/runtime.d.mts +3 -3
  15. package/dist/api/runtime.d.ts +3 -3
  16. package/dist/api/runtime.mjs +6 -3
  17. package/dist/{api-client-B-n3pm_Q.d.mts → api-client-Cx54IR5g.d.mts} +2 -2
  18. package/dist/{api-client-C0_NZEBl.d.ts → api-client-DykpaKcY.d.ts} +2 -2
  19. package/dist/api.cjs +88 -8361
  20. package/dist/api.d.mts +5 -5
  21. package/dist/api.d.ts +5 -5
  22. package/dist/api.mjs +8 -8
  23. package/dist/{app-AyjEsCBq.d.ts → app-BHY_10Lm.d.ts} +3 -3
  24. package/dist/{app-CYPHeOo_.d.mts → app-BMk0do23.d.mts} +3 -3
  25. package/dist/app-markdown.cjs +39 -280
  26. package/dist/app-markdown.d.mts +4 -4
  27. package/dist/app-markdown.d.ts +4 -4
  28. package/dist/app-markdown.mjs +3 -3
  29. package/dist/cache.cjs +38 -1526
  30. package/dist/cache.d.mts +11 -1
  31. package/dist/cache.d.ts +11 -1
  32. package/dist/cache.mjs +1 -1
  33. package/dist/chunk-22GUSVNJ.cjs +351 -0
  34. package/dist/chunk-2CQ74SP6.cjs +13 -0
  35. package/dist/chunk-2SJ4RQ6P.cjs +57 -0
  36. package/dist/chunk-3376ZTRC.cjs +1 -0
  37. package/dist/{chunk-IL5RWYK7.mjs → chunk-3XG26Z3J.mjs} +1 -1
  38. package/dist/{chunk-7HDZYYS4.mjs → chunk-4OOBRCJX.mjs} +27 -5
  39. package/dist/chunk-4PNUXIVU.cjs +472 -0
  40. package/dist/chunk-4PPEPOZZ.cjs +21 -0
  41. package/dist/chunk-4ZFL5GFN.cjs +520 -0
  42. package/dist/{chunk-B76DT5Y6.mjs → chunk-57J3Y7Y3.mjs} +1 -1
  43. package/dist/chunk-5OVTOKGH.cjs +65 -0
  44. package/dist/chunk-5QIKR7RR.cjs +224 -0
  45. package/dist/{chunk-MOQNHLTS.mjs → chunk-5QOEPUYE.mjs} +5 -2
  46. package/dist/{chunk-HKLRP3BN.mjs → chunk-5SPPCN5J.mjs} +1 -1
  47. package/dist/chunk-5ZSWG4UX.cjs +127 -0
  48. package/dist/chunk-62YJ2IEB.cjs +238 -0
  49. package/dist/chunk-6EODJYCX.cjs +183 -0
  50. package/dist/chunk-6EXBPJ24.cjs +434 -0
  51. package/dist/chunk-6QQDAAAZ.cjs +38 -0
  52. package/dist/chunk-6V4TDWEC.cjs +455 -0
  53. package/dist/{chunk-LUC2FAGW.mjs → chunk-6VQIKZZO.mjs} +1 -1
  54. package/dist/chunk-72ADZ6GQ.cjs +19 -0
  55. package/dist/chunk-75BRBIFP.cjs +172 -0
  56. package/dist/{chunk-7ZWL7XOU.mjs → chunk-76DG3LF3.mjs} +1 -1
  57. package/dist/chunk-7W3CPVXS.cjs +24 -0
  58. package/dist/chunk-A6WIQH5Z.cjs +31 -0
  59. package/dist/{chunk-EWDK36MM.mjs → chunk-A72YEUZ3.mjs} +1 -1
  60. package/dist/chunk-AFOD3LYZ.cjs +377 -0
  61. package/dist/chunk-AMDMVWMI.cjs +39 -0
  62. package/dist/chunk-AORPIPNB.cjs +552 -0
  63. package/dist/chunk-ARJWXNQL.cjs +256 -0
  64. package/dist/{chunk-ZHOIQC6U.mjs → chunk-ATERBVHQ.mjs} +2 -2
  65. package/dist/chunk-AWRISO2H.cjs +2199 -0
  66. package/dist/chunk-AYJR42WX.cjs +711 -0
  67. package/dist/chunk-B4CH33IG.cjs +644 -0
  68. package/dist/chunk-BIDYX3SL.cjs +91 -0
  69. package/dist/chunk-BSTRERPP.cjs +40 -0
  70. package/dist/chunk-BYODCJD6.cjs +663 -0
  71. package/dist/chunk-C3VRMB6H.cjs +85 -0
  72. package/dist/chunk-C5GUTBZK.cjs +173 -0
  73. package/dist/chunk-CIAGU2X4.cjs +337 -0
  74. package/dist/chunk-CMGMGHUZ.cjs +27 -0
  75. package/dist/chunk-CXP5U3RW.cjs +54 -0
  76. package/dist/chunk-D2ULAULS.cjs +166 -0
  77. package/dist/chunk-D7JTOLFK.cjs +285 -0
  78. package/dist/chunk-DVM4FKZL.cjs +169 -0
  79. package/dist/chunk-DYEJQTDN.cjs +49 -0
  80. package/dist/chunk-E2BMSZ2W.cjs +151 -0
  81. package/dist/chunk-E3UK5IIB.cjs +593 -0
  82. package/dist/chunk-EM6SBQKM.cjs +470 -0
  83. package/dist/{chunk-27JNCYEK.mjs → chunk-EN7WTEAY.mjs} +2 -2
  84. package/dist/{chunk-IGO2HEV7.mjs → chunk-F6SJAKFJ.mjs} +62 -28
  85. package/dist/{chunk-GSDIZACQ.mjs → chunk-FG5H2VCJ.mjs} +2 -2
  86. package/dist/chunk-FJSWYIR7.cjs +482 -0
  87. package/dist/chunk-FK6GO24V.cjs +54 -0
  88. package/dist/chunk-FXUUWYAX.cjs +654 -0
  89. package/dist/chunk-G3HRIVEY.cjs +395 -0
  90. package/dist/chunk-G643DQCH.cjs +13 -0
  91. package/dist/chunk-G7HXGLEC.cjs +175 -0
  92. package/dist/chunk-GDSHDTJ4.cjs +152 -0
  93. package/dist/chunk-GNEO2XOF.cjs +2040 -0
  94. package/dist/{chunk-NHHKW2T6.mjs → chunk-GYKJCFTS.mjs} +170 -52
  95. package/dist/chunk-H6G5INWM.cjs +1094 -0
  96. package/dist/chunk-HBTUGXHS.cjs +180 -0
  97. package/dist/chunk-HREOKQWT.cjs +45 -0
  98. package/dist/chunk-I4J452B7.cjs +435 -0
  99. package/dist/chunk-I57LW5VZ.cjs +94 -0
  100. package/dist/chunk-I7PUUDGY.cjs +389 -0
  101. package/dist/chunk-IAMRBF3Z.cjs +86 -0
  102. package/dist/chunk-IKNRN4VS.cjs +14214 -0
  103. package/dist/chunk-IQXFRNY2.cjs +169 -0
  104. package/dist/chunk-IXTFU4PL.cjs +2355 -0
  105. package/dist/chunk-J2OP5GG3.cjs +725 -0
  106. package/dist/chunk-J3LOGE4T.cjs +42 -0
  107. package/dist/chunk-J7FSKED3.cjs +93 -0
  108. package/dist/chunk-JDNHKPTD.cjs +22 -0
  109. package/dist/chunk-JSROZYYO.cjs +164 -0
  110. package/dist/chunk-K6FNHVDR.cjs +696 -0
  111. package/dist/chunk-KGZIORNL.cjs +43 -0
  112. package/dist/{chunk-LZK5CXDW.mjs → chunk-KLSSO6YD.mjs} +2 -2
  113. package/dist/{chunk-TYVVIQ5M.mjs → chunk-KPNVGRBL.mjs} +32 -25
  114. package/dist/chunk-KR6CKSXT.cjs +15 -0
  115. package/dist/chunk-KROWKCUH.cjs +185 -0
  116. package/dist/chunk-KVFPGF2M.cjs +46 -0
  117. package/dist/{chunk-KUO3GBPK.mjs → chunk-L6V3P73N.mjs} +1 -1
  118. package/dist/chunk-LCCBO7PJ.cjs +46 -0
  119. package/dist/chunk-LIUGYUX3.cjs +22 -0
  120. package/dist/chunk-LTNGXMQ6.cjs +55 -0
  121. package/dist/chunk-M2L4MYDQ.cjs +14 -0
  122. package/dist/chunk-MCJLA63J.cjs +1 -0
  123. package/dist/chunk-MKB2EGIR.cjs +148 -0
  124. package/dist/chunk-MQ3H6LT5.cjs +202 -0
  125. package/dist/chunk-MT763TDW.cjs +43 -0
  126. package/dist/chunk-MWSK6C4J.cjs +18 -0
  127. package/dist/chunk-MWWVKDW3.cjs +169 -0
  128. package/dist/{chunk-KTGFMHET.mjs → chunk-N6UROPT7.mjs} +1 -1
  129. package/dist/chunk-NO3WWW3N.cjs +192 -0
  130. package/dist/{chunk-NDD2YVGU.mjs → chunk-NRVGEI5I.mjs} +10 -3
  131. package/dist/chunk-NV3A5DXM.cjs +862 -0
  132. package/dist/chunk-NWOD6NIT.cjs +9 -0
  133. package/dist/chunk-NZKJGRB3.cjs +230 -0
  134. package/dist/chunk-OAVTUMJP.cjs +1496 -0
  135. package/dist/chunk-OHY2ZWUG.cjs +25 -0
  136. package/dist/chunk-OI6CMLWX.cjs +47 -0
  137. package/dist/chunk-OIEOCXKG.cjs +453 -0
  138. package/dist/chunk-OWOUTKIJ.cjs +558 -0
  139. package/dist/chunk-OX6O6WVA.cjs +74 -0
  140. package/dist/chunk-OXSIH4D6.cjs +476 -0
  141. package/dist/chunk-OYEUREB6.cjs +35 -0
  142. package/dist/chunk-PCOTGFSM.cjs +139 -0
  143. package/dist/chunk-PZYCPSCC.cjs +35 -0
  144. package/dist/chunk-QBK2AA4U.cjs +445 -0
  145. package/dist/chunk-QBPXNZGV.cjs +487 -0
  146. package/dist/{chunk-IXTEENRS.mjs → chunk-QGVJVSNX.mjs} +5 -5
  147. package/dist/chunk-QNPEUFHQ.cjs +27 -0
  148. package/dist/chunk-QZRVZSPN.cjs +236 -0
  149. package/dist/chunk-R5A5KNVX.cjs +20 -0
  150. package/dist/chunk-R5JIFR6B.cjs +42 -0
  151. package/dist/chunk-R6AIILII.cjs +193 -0
  152. package/dist/chunk-RG3ZOTG5.cjs +34 -0
  153. package/dist/chunk-ROUTX2E5.cjs +390 -0
  154. package/dist/chunk-RTHIVJ2G.cjs +54 -0
  155. package/dist/chunk-S3A45T7F.cjs +166 -0
  156. package/dist/chunk-S3JO3N4H.cjs +17 -0
  157. package/dist/chunk-SK35NQKK.cjs +27 -0
  158. package/dist/chunk-SU7MH53P.cjs +180 -0
  159. package/dist/chunk-SVRTJOUF.cjs +113 -0
  160. package/dist/chunk-SWN467MP.cjs +18 -0
  161. package/dist/{chunk-6SCB2MXB.mjs → chunk-SXHV42UQ.mjs} +16 -1
  162. package/dist/{chunk-OWTIOHON.mjs → chunk-SYGGPS4A.mjs} +2 -2
  163. package/dist/chunk-SYQ3MOWW.cjs +73 -0
  164. package/dist/chunk-T5CERMEH.cjs +417 -0
  165. package/dist/chunk-TFAXUHWX.cjs +206 -0
  166. package/dist/chunk-TIWHTW3Q.cjs +24 -0
  167. package/dist/chunk-TKJZFIML.cjs +20 -0
  168. package/dist/chunk-TKNSDBBN.cjs +193 -0
  169. package/dist/{chunk-NC333MFA.mjs → chunk-TSWW5BVH.mjs} +7 -4
  170. package/dist/chunk-TWGMSEHX.cjs +525 -0
  171. package/dist/chunk-TYQUSXUG.cjs +1357 -0
  172. package/dist/chunk-U4KT7QP3.cjs +23 -0
  173. package/dist/{chunk-LK6FGAQR.mjs → chunk-UDBJCUPA.mjs} +7 -4
  174. package/dist/chunk-UJ2C4ICS.cjs +277 -0
  175. package/dist/chunk-UN5GHC5V.cjs +10244 -0
  176. package/dist/chunk-UQZ4AYTH.cjs +168 -0
  177. package/dist/chunk-US2QVW3E.cjs +36 -0
  178. package/dist/{chunk-NUD6XBMO.mjs → chunk-UTBVHYS3.mjs} +2 -2
  179. package/dist/{chunk-76MNRHTS.mjs → chunk-UUYF3CHN.mjs} +2 -2
  180. package/dist/chunk-VB6UCX3V.cjs +421 -0
  181. package/dist/chunk-VEKFLAQM.cjs +300 -0
  182. package/dist/chunk-VQDBNVOO.cjs +14 -0
  183. package/dist/chunk-W4E7WMXE.cjs +71 -0
  184. package/dist/{chunk-VVTREAG5.mjs → chunk-WD4YXVLV.mjs} +11 -3
  185. package/dist/{chunk-UQZPTIML.mjs → chunk-WD5PNSOB.mjs} +2 -2
  186. package/dist/chunk-WJ3HK3LJ.cjs +1102 -0
  187. package/dist/chunk-WMAPPDMM.cjs +28 -0
  188. package/dist/chunk-WMOGFOUJ.cjs +223 -0
  189. package/dist/chunk-WPYFSQKK.cjs +37 -0
  190. package/dist/chunk-WZMNW2IW.cjs +1415 -0
  191. package/dist/chunk-XGC343EY.cjs +443 -0
  192. package/dist/{chunk-DPZUDPVJ.mjs → chunk-XP777LRD.mjs} +1 -1
  193. package/dist/chunk-XSKZORAS.cjs +727 -0
  194. package/dist/chunk-XWAWFQFS.cjs +82 -0
  195. package/dist/{chunk-KATQ6I56.mjs → chunk-XWAYMDLB.mjs} +1 -1
  196. package/dist/chunk-Y4YMF2NQ.cjs +460 -0
  197. package/dist/chunk-Y4YWHNKU.cjs +250 -0
  198. package/dist/chunk-Y53ZSFN6.cjs +504 -0
  199. package/dist/chunk-YA6LLTIJ.cjs +411 -0
  200. package/dist/chunk-YFPGHF5F.cjs +202 -0
  201. package/dist/chunk-YJRZR7VU.cjs +28 -0
  202. package/dist/chunk-YTAABQEV.cjs +1 -0
  203. package/dist/chunk-YX3DBN4M.cjs +18 -0
  204. package/dist/chunk-YZTASLPQ.cjs +64 -0
  205. package/dist/chunk-Z5HIWVDP.cjs +2173 -0
  206. package/dist/{chunk-Q3MDL7TM.mjs → chunk-ZCNJKLA2.mjs} +30 -11
  207. package/dist/chunk-ZEG3OPIB.cjs +93 -0
  208. package/dist/chunk-ZMN3H73H.cjs +155 -0
  209. package/dist/client/lifecycle.cjs +6 -35
  210. package/dist/{client-plugins-CqVtZi5X.d.ts → client-plugins-C089bQhN.d.ts} +2 -2
  211. package/dist/{client-plugins-CIPRtSsW.d.mts → client-plugins-JXXmZliS.d.mts} +2 -2
  212. package/dist/client-plugins.cjs +7 -448
  213. package/dist/client-plugins.d.mts +3 -3
  214. package/dist/client-plugins.d.ts +3 -3
  215. package/dist/client.cjs +171 -9774
  216. package/dist/client.d.mts +8 -8
  217. package/dist/client.d.ts +8 -8
  218. package/dist/client.mjs +6 -6
  219. package/dist/config.cjs +8 -36
  220. package/dist/config.d.mts +3 -3
  221. package/dist/config.d.ts +3 -3
  222. package/dist/cron.cjs +24 -491
  223. package/dist/cron.mjs +2 -2
  224. package/dist/deferred.cjs +26 -475
  225. package/dist/deployment.cjs +39 -210
  226. package/dist/devtools-OUIPHVV6.cjs +388 -0
  227. package/dist/{devtools-IU7LKZOH.mjs → devtools-UFVTMQX5.mjs} +7 -7
  228. package/dist/devtools-client-4WAPJY5L.cjs +254 -0
  229. package/dist/devtools-ui-5GBDIGMK.cjs +1296 -0
  230. package/dist/docs.cjs +46 -5649
  231. package/dist/docs.mjs +9 -9
  232. package/dist/{endpoint-kSAxE52R.d.ts → endpoint-1zA994xL.d.ts} +1 -1
  233. package/dist/{endpoint-Bu3XgeMK.d.mts → endpoint-DAc96i93.d.mts} +1 -1
  234. package/dist/env-types.cjs +5 -226
  235. package/dist/env.cjs +23 -306
  236. package/dist/env.d.mts +5 -3
  237. package/dist/env.d.ts +5 -3
  238. package/dist/env.mjs +2 -1
  239. package/dist/environment/vite.cjs +8 -372
  240. package/dist/environment.cjs +12 -94
  241. package/dist/font.cjs +13 -63
  242. package/dist/headers.cjs +7 -123
  243. package/dist/i18n/client.cjs +55 -294
  244. package/dist/i18n/index.cjs +22 -209
  245. package/dist/i18n/server.cjs +22 -745
  246. package/dist/image/server.cjs +13 -729
  247. package/dist/image/sharp.cjs +33 -171
  248. package/dist/image.cjs +41 -85
  249. package/dist/index.cjs +1151 -67862
  250. package/dist/index.d.mts +14 -14
  251. package/dist/index.d.ts +14 -14
  252. package/dist/index.mjs +34 -34
  253. package/dist/instrumentation.cjs +12 -138
  254. package/dist/integration-orm-55F7CII5.cjs +13 -0
  255. package/dist/integrations.cjs +55 -4090
  256. package/dist/integrations.d.mts +3 -3
  257. package/dist/integrations.d.ts +3 -3
  258. package/dist/internal/app-markdown-runtime.cjs +27 -224
  259. package/dist/internal/app-markdown-runtime.d.mts +3 -3
  260. package/dist/internal/app-markdown-runtime.d.ts +3 -3
  261. package/dist/internal/app-markdown-runtime.mjs +2 -2
  262. package/dist/internal/build-runtime.cjs +120 -52038
  263. package/dist/internal/build-runtime.d.mts +5 -5
  264. package/dist/internal/build-runtime.d.ts +5 -5
  265. package/dist/internal/build-runtime.mjs +23 -23
  266. package/dist/internal/cli-runtime.cjs +67 -13765
  267. package/dist/internal/cli-runtime.mjs +13 -13
  268. package/dist/internal/client-error-overlay.cjs +80 -733
  269. package/dist/internal/client-error-overlay.mjs +1 -1
  270. package/dist/internal/client-runtime.cjs +81 -913
  271. package/dist/internal/compression-runtime.cjs +8 -214
  272. package/dist/internal/compression-runtime.d.mts +3 -3
  273. package/dist/internal/compression-runtime.d.ts +3 -3
  274. package/dist/internal/config-runtime.cjs +42 -6535
  275. package/dist/internal/config-runtime.d.mts +4 -4
  276. package/dist/internal/config-runtime.d.ts +4 -4
  277. package/dist/internal/config-runtime.mjs +7 -7
  278. package/dist/internal/docs-precompiled-runtime.cjs +26 -46
  279. package/dist/internal/infra-analytics-runtime.cjs +10 -536
  280. package/dist/internal/isolated-boundary.cjs +14 -414
  281. package/dist/internal/metadata-image-runtime.cjs +7 -285
  282. package/dist/internal/product-telemetry-runtime.cjs +42 -97
  283. package/dist/internal/product-telemetry-runtime.mjs +1 -1
  284. package/dist/internal/production-node-env.cjs +6 -63
  285. package/dist/internal/production-runtime.cjs +418 -7073
  286. package/dist/internal/production-runtime.d.mts +9 -9
  287. package/dist/internal/production-runtime.d.ts +9 -9
  288. package/dist/internal/production-runtime.mjs +6 -6
  289. package/dist/internal/request-cookies.cjs +6 -54
  290. package/dist/json-ld.cjs +24 -50
  291. package/dist/layers-E4WPJNY5.cjs +17 -0
  292. package/dist/manager-G4B2IPYE.cjs +14 -0
  293. package/dist/markdown.cjs +21 -532
  294. package/dist/markdown.mjs +1 -1
  295. package/dist/{metadata-8g__AMPM.d.ts → metadata-BcNJP4fq.d.ts} +1 -1
  296. package/dist/{metadata-OMX6wFNf.d.mts → metadata-C1Z9vLbb.d.mts} +1 -1
  297. package/dist/middleware.cjs +36 -2988
  298. package/dist/middleware.d.mts +5 -5
  299. package/dist/middleware.d.ts +5 -5
  300. package/dist/middleware.mjs +4 -4
  301. package/dist/navigation.cjs +22 -2588
  302. package/dist/nitro-4I2MYLY2.cjs +652 -0
  303. package/dist/{nitro-3N4ZXRYM.mjs → nitro-CVZ36JM5.mjs} +4 -4
  304. package/dist/observability.cjs +22 -614
  305. package/dist/og.cjs +5 -28
  306. package/dist/plugin.cjs +106 -37291
  307. package/dist/plugin.d.mts +3 -3
  308. package/dist/plugin.d.ts +3 -3
  309. package/dist/plugin.mjs +19 -19
  310. package/dist/{production-runtime-W3M0eNDV.d.mts → production-runtime-jcrTlRTb.d.mts} +1 -1
  311. package/dist/{production-runtime-BJh7o6Cr.d.ts → production-runtime-oKmC0WU-.d.ts} +1 -1
  312. package/dist/query/client.cjs +113 -449
  313. package/dist/query/index.cjs +26 -288
  314. package/dist/query/parsers.cjs +23 -247
  315. package/dist/query/server.cjs +36 -298
  316. package/dist/{render-plan-io7pvDNc.d.mts → render-plan-BLIfc4jt.d.mts} +1 -1
  317. package/dist/{render-plan-Be4ZGTJP.d.ts → render-plan-DOB9cV-h.d.ts} +1 -1
  318. package/dist/renderer/react/client.cjs +9 -43
  319. package/dist/renderer/react/server.cjs +40 -103
  320. package/dist/renderer/react/vite.cjs +7 -29
  321. package/dist/renderer-client.cjs +126 -4261
  322. package/dist/renderer-client.d.mts +5 -5
  323. package/dist/renderer-client.d.ts +5 -5
  324. package/dist/renderer-client.mjs +3 -3
  325. package/dist/renderer.cjs +31 -249
  326. package/dist/{request-DZkHYQ89.d.mts → request-Cr53NRHr.d.mts} +1 -1
  327. package/dist/{request-G8JhKr4F.d.ts → request-Dt2gNuQD.d.ts} +1 -1
  328. package/dist/request.cjs +5 -68
  329. package/dist/request.d.mts +4 -4
  330. package/dist/request.d.ts +4 -4
  331. package/dist/{route-C_eLaFTZ.d.mts → route-B0XrsrFk.d.mts} +1 -1
  332. package/dist/{route-BxNJT447.d.ts → route-DOEpbyWZ.d.ts} +1 -1
  333. package/dist/{route-rendering-BcLLPJgN.d.ts → route-rendering-CWYd8Mv1.d.ts} +1 -1
  334. package/dist/{route-rendering-CbAKr1TY.d.mts → route-rendering-CeFBEAoZ.d.mts} +1 -1
  335. package/dist/router.cjs +11 -474
  336. package/dist/routes.cjs +42 -2424
  337. package/dist/routes.d.mts +4 -4
  338. package/dist/routes.d.ts +4 -4
  339. package/dist/routes.mjs +2 -2
  340. package/dist/schema-dev-notice-MXSZMVDG.cjs +56 -0
  341. package/dist/schema.cjs +6 -33
  342. package/dist/search-client-G3RICOFU.cjs +13 -0
  343. package/dist/server-action-security.cjs +25 -541
  344. package/dist/server-fn-client.cjs +6 -337
  345. package/dist/server-fn-client.d.mts +3 -3
  346. package/dist/server-fn-client.d.ts +3 -3
  347. package/dist/server-fn.cjs +32 -1799
  348. package/dist/server-fn.d.mts +1 -1
  349. package/dist/server-fn.d.ts +1 -1
  350. package/dist/server-fn.mjs +2 -2
  351. package/dist/server-plugins.cjs +15 -884
  352. package/dist/server-plugins.d.mts +4 -4
  353. package/dist/server-plugins.d.ts +4 -4
  354. package/dist/server-query-client.cjs +15 -1849
  355. package/dist/server-query-client.d.mts +1 -1
  356. package/dist/server-query-client.d.ts +1 -1
  357. package/dist/server-query-client.mjs +4 -4
  358. package/dist/server-query.cjs +16 -1796
  359. package/dist/server-query.d.mts +1 -1
  360. package/dist/server-query.d.ts +1 -1
  361. package/dist/server-query.mjs +3 -3
  362. package/dist/server.cjs +296 -44522
  363. package/dist/server.d.mts +9 -9
  364. package/dist/server.d.ts +9 -9
  365. package/dist/server.mjs +22 -22
  366. package/dist/{spa-router-BcS_4nqm.d.mts → spa-router-CQWiYGxS.d.mts} +2 -2
  367. package/dist/{spa-router-BzFBUJkn.d.ts → spa-router-Wjiw-8hB.d.ts} +2 -2
  368. package/dist/storage.cjs +57 -576
  369. package/dist/testing.cjs +92 -3148
  370. package/dist/testing.d.mts +3 -3
  371. package/dist/testing.d.ts +3 -3
  372. package/dist/testing.mjs +11 -7
  373. package/dist/theme/client.cjs +13 -108
  374. package/dist/theme/index.cjs +6 -68
  375. package/dist/theme/runtime.cjs +13 -78
  376. package/dist/theme/server.cjs +10 -179
  377. package/dist/{utils-C4yrAhNc.d.ts → utils-B0XJmG_b.d.ts} +1 -1
  378. package/dist/{utils-5kQP1mFR.d.mts → utils-uUxF0K0P.d.mts} +1 -1
  379. package/dist/version.cjs +4 -32
  380. package/dist/version.mjs +1 -1
  381. package/dist/vite.cjs +119 -37622
  382. package/dist/vite.d.mts +3 -3
  383. package/dist/vite.d.ts +3 -3
  384. package/dist/vite.mjs +19 -19
  385. package/dist/workflows.cjs +19 -1040
  386. package/dist/workflows.mjs +2 -2
  387. package/package.json +2 -2
  388. package/dist/{chunk-VO5SCWF5.mjs → chunk-BNGS6KJ6.mjs} +0 -0
  389. package/dist/{chunk-MUUZJLCI.mjs → chunk-EGJDUF4Q.mjs} +3 -3
  390. package/dist/{chunk-4L7SZOHZ.mjs → chunk-YHOCRI4H.mjs} +3 -3
package/dist/testing.cjs CHANGED
@@ -1,3130 +1,71 @@
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 __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
- // If the importer is in node compatibility mode or this is not an ESM
26
- // file that has been converted to a CommonJS file using a Babel-
27
- // compatible transform (i.e. "__esModule" has not been set), then set
28
- // "default" to the CommonJS "module.exports" for node compatibility.
29
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
- mod
31
- ));
32
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
-
34
- // src/tracing.ts
35
- function normalizeFarmTracingConfig(config) {
36
- if (!config) {
37
- return {
38
- enabled: false,
39
- spans: new Set(ALL_SPAN_KINDS),
40
- recordEvents: true,
41
- attributes: {},
42
- ignorePaths: DEFAULT_IGNORED_PATHS
43
- };
44
- }
45
- if (config === true) {
46
- return {
47
- enabled: true,
48
- spans: new Set(ALL_SPAN_KINDS),
49
- recordEvents: true,
50
- attributes: {},
51
- ignorePaths: DEFAULT_IGNORED_PATHS
52
- };
53
- }
54
- return {
55
- enabled: config.enabled ?? true,
56
- spans: new Set(config.spans ?? ALL_SPAN_KINDS),
57
- recordEvents: config.recordEvents ?? true,
58
- attributes: { ...config.attributes },
59
- ignorePaths: [...DEFAULT_IGNORED_PATHS, ...config.ignorePaths ?? []]
60
- };
61
- }
62
- function recordFarmEventTrace(event) {
63
- if (!tracingState.enabled) return void 0;
64
- const activeContext = import_api.context.active();
65
- const activeSpan = import_api.trace.getSpan(activeContext);
66
- const traceContext = getSpanTraceContext(activeSpan);
67
- if (activeSpan && traceContext) {
68
- if (event.type === "route.matched") {
69
- const method = activeContext.getValue(FARM_REQUEST_METHOD_CONTEXT_KEY) ?? "HTTP";
70
- activeSpan.updateName(`${method} ${event.route}`);
71
- activeSpan.setAttribute("http.route", event.route);
72
- activeSpan.setAttribute("farm.route", event.route);
73
- }
74
- if (tracingState.recordEvents) {
75
- activeSpan.addEvent(event.type, toEventAttributes(event), event.timestamp);
76
- }
77
- const error = event.type === "request.error" ? void 0 : getEventError(event);
78
- if (error !== void 0) {
79
- if (event.type === "render.error") {
80
- recordSpanException(activeSpan, error);
81
- } else {
82
- recordSpanError(activeSpan, error);
83
- }
84
- }
85
- }
86
- const completedTraceContext = recordCompletedEventSpan(event, activeContext);
87
- return traceContext ?? completedTraceContext;
88
- }
89
- function recordCompletedEventSpan(event, parentContext) {
90
- const descriptor = getCompletedSpanDescriptor(event);
91
- if (!descriptor || !tracingState.spans.has(descriptor.kind)) return void 0;
92
- const tracer = import_api.trace.getTracer(FARM_TRACER_NAME);
93
- const span = tracer.startSpan(
94
- descriptor.name,
95
- {
96
- kind: import_api.SpanKind.INTERNAL,
97
- startTime: event.timestamp - descriptor.durationMs,
98
- attributes: {
99
- ...tracingState.attributes,
100
- ...toEventAttributes(event),
101
- "farm.event.type": event.type
102
- }
103
- },
104
- parentContext
105
- );
106
- const status = "status" in event && typeof event.status === "number" ? event.status : void 0;
107
- if (status !== void 0) setResponseStatus(span, status);
108
- const error = getEventError(event);
109
- if (error !== void 0) recordSpanError(span, error);
110
- const traceContext = getSpanTraceContext(span);
111
- span.end(event.timestamp);
112
- return traceContext;
113
- }
114
- function getCompletedSpanDescriptor(event) {
115
- if (!("durationMs" in event) || typeof event.durationMs !== "number") return void 0;
116
- switch (event.type) {
117
- case "render.complete":
118
- return { kind: "render", name: `farm.render ${event.route}`, durationMs: event.durationMs };
119
- case "render.stream.shellReady":
120
- return {
121
- kind: "render",
122
- name: `farm.render.shell ${event.route}`,
123
- durationMs: event.durationMs
124
- };
125
- case "render.stream.complete":
126
- return {
127
- kind: "render",
128
- name: `farm.render.stream ${event.route}`,
129
- durationMs: event.durationMs
130
- };
131
- case "middleware.complete":
132
- return {
133
- kind: "middleware",
134
- name: `farm.middleware ${event.name ?? event.route ?? "anonymous"}`,
135
- durationMs: event.durationMs
136
- };
137
- case "api.request.complete":
138
- case "api.error":
139
- return {
140
- kind: "api",
141
- name: `farm.api ${event.method} ${event.route}`,
142
- durationMs: event.durationMs
143
- };
144
- case "integration.api.call.complete":
145
- return {
146
- kind: "integration",
147
- name: `farm.integration ${event.integration}.${event.operation}`,
148
- durationMs: event.durationMs
149
- };
150
- case "storage.query.complete":
151
- return {
152
- kind: "storage",
153
- name: `farm.storage ${event.operation}`,
154
- durationMs: event.durationMs
155
- };
156
- case "ppr.refresh.complete":
157
- return {
158
- kind: "ppr",
159
- name: `farm.ppr.refresh ${event.route}`,
160
- durationMs: event.durationMs
161
- };
162
- case "build.complete":
163
- return {
164
- kind: "build",
165
- name: `farm.build${event.target ? ` ${event.target}` : ""}`,
166
- durationMs: event.durationMs
167
- };
168
- case "plugin.hook.complete":
169
- return {
170
- kind: "plugin",
171
- name: `farm.plugin ${event.plugin}.${event.hook}`,
172
- durationMs: event.durationMs
173
- };
174
- default:
175
- return void 0;
176
- }
177
- }
178
- function hashFarmCacheKey(value) {
179
- let hash = 2166136261;
180
- for (let index = 0; index < value.length; index++) {
181
- hash ^= value.charCodeAt(index);
182
- hash = Math.imul(hash, 16777619);
183
- }
184
- return (hash >>> 0).toString(16).padStart(8, "0");
185
- }
186
- function toEventAttributes(event) {
187
- const attributes = {};
188
- const redactKey = typeof event.type === "string" && event.type.startsWith("cache.");
189
- for (const [key, value] of Object.entries(event)) {
190
- if (key === "timestamp" || key === "level" || key === "error" || key === "traceId" || key === "spanId" || key === "traceSampled" || value === void 0) {
191
- continue;
192
- }
193
- if (redactKey && key === "key" && typeof value === "string") {
194
- attributes["farm.key_hash"] = hashFarmCacheKey(value);
195
- continue;
196
- }
197
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
198
- attributes[`farm.${key}`] = value;
199
- } else if (Array.isArray(value)) {
200
- if (value.every((entry) => typeof entry === "string")) {
201
- attributes[`farm.${key}`] = value;
202
- } else if (value.every((entry) => typeof entry === "number")) {
203
- attributes[`farm.${key}`] = value;
204
- } else if (value.every((entry) => typeof entry === "boolean")) {
205
- attributes[`farm.${key}`] = value;
206
- }
207
- }
208
- }
209
- return attributes;
210
- }
211
- function getEventError(event) {
212
- return "error" in event ? event.error : void 0;
213
- }
214
- function recordSpanException(span, error) {
215
- const normalized = error instanceof Error ? error : new Error(String(error));
216
- span.recordException(normalized);
217
- return normalized;
218
- }
219
- function recordSpanError(span, error) {
220
- const normalized = recordSpanException(span, error);
221
- span.setStatus({ code: import_api.SpanStatusCode.ERROR, message: normalized.message });
222
- }
223
- function setResponseStatus(span, status) {
224
- span.setAttribute("http.response.status_code", status);
225
- if (status >= 500) {
226
- span.setStatus({ code: import_api.SpanStatusCode.ERROR });
227
- }
228
- }
229
- function getSpanTraceContext(span) {
230
- if (!span) return void 0;
231
- const spanContext = span.spanContext();
232
- if (!(0, import_api.isSpanContextValid)(spanContext)) return void 0;
233
- return {
234
- traceId: spanContext.traceId,
235
- spanId: spanContext.spanId,
236
- traceSampled: (spanContext.traceFlags & 1) === 1
237
- };
238
- }
239
- var import_api, FARM_TRACER_NAME, ALL_SPAN_KINDS, DEFAULT_IGNORED_PATHS, FARM_REQUEST_METHOD_CONTEXT_KEY, TRACING_RUNTIME, runtime, tracingState;
240
- var init_tracing = __esm({
241
- "src/tracing.ts"() {
242
- "use strict";
243
- import_api = require("@opentelemetry/api");
244
- FARM_TRACER_NAME = "@farm.js/core";
245
- ALL_SPAN_KINDS = [
246
- "request",
247
- "render",
248
- "middleware",
249
- "api",
250
- "integration",
251
- "storage",
252
- "ppr",
253
- "build",
254
- "plugin"
255
- ];
256
- DEFAULT_IGNORED_PATHS = [
257
- "/@vite/",
258
- "/@fs/",
259
- "/@id/",
260
- "/@react-refresh",
261
- "/node_modules/",
262
- "/__vite",
263
- "/.well-known/appspecific/"
264
- ];
265
- FARM_REQUEST_METHOD_CONTEXT_KEY = (0, import_api.createContextKey)("@farm.js/core/request-method");
266
- TRACING_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/tracing-runtime/v1");
267
- runtime = globalThis;
268
- tracingState = runtime[TRACING_RUNTIME] ?? (runtime[TRACING_RUNTIME] = normalizeFarmTracingConfig(false));
269
- __name(normalizeFarmTracingConfig, "normalizeFarmTracingConfig");
270
- __name(recordFarmEventTrace, "recordFarmEventTrace");
271
- __name(recordCompletedEventSpan, "recordCompletedEventSpan");
272
- __name(getCompletedSpanDescriptor, "getCompletedSpanDescriptor");
273
- __name(hashFarmCacheKey, "hashFarmCacheKey");
274
- __name(toEventAttributes, "toEventAttributes");
275
- __name(getEventError, "getEventError");
276
- __name(recordSpanException, "recordSpanException");
277
- __name(recordSpanError, "recordSpanError");
278
- __name(setResponseStatus, "setResponseStatus");
279
- __name(getSpanTraceContext, "getSpanTraceContext");
280
- }
281
- });
282
-
283
- // src/observability.ts
284
- function emitFarmEvent(input) {
285
- const event = {
286
- timestamp: Date.now(),
287
- level: inferFarmEventLevel(input.type),
288
- ...input
289
- };
290
- const traceContext = recordFarmEventTrace(event);
291
- if (traceContext) {
292
- event.traceId = traceContext.traceId;
293
- event.spanId = traceContext.spanId;
294
- event.traceSampled = traceContext.traceSampled;
295
- }
296
- notifyFarmEventHandlers(event, unfilteredRuntimeHandlers);
297
- if (!shouldEmitFarmEvent(event)) return event;
298
- if (observabilityState.logs) {
299
- logFarmEvent(event);
300
- }
301
- notifyFarmEventHandlers(event, [...observabilityState.handlers, ...runtimeHandlers]);
302
- return event;
303
- }
304
- function notifyFarmEventHandlers(event, handlers) {
305
- for (const handler of handlers) {
306
- try {
307
- Promise.resolve(handler(event)).catch((error) => {
308
- console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
309
- });
310
- } catch (error) {
311
- console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
312
- }
313
- }
314
- }
315
- function shouldEmitFarmEvent(event) {
316
- if (!observabilityState.logs && observabilityState.handlers.length === 0 && runtimeHandlers.size === 0) {
317
- return false;
318
- }
319
- if (observabilityState.events && !observabilityState.events.has(event.type)) {
320
- return false;
321
- }
322
- return true;
323
- }
324
- function inferFarmEventLevel(type) {
325
- if (type === "error" || type.endsWith(".error") || type.endsWith(".failed")) {
326
- return "error";
327
- }
328
- if (type.endsWith(".bypass") || type.endsWith(".invalidated") || type.endsWith(".stale") || type.endsWith(".notFound")) {
329
- return "warn";
330
- }
331
- if (type.endsWith(".hit") || type.endsWith(".miss") || type.endsWith(".start") || type.endsWith(".shellReady")) {
332
- return "debug";
333
- }
334
- return "info";
335
- }
336
- function logFarmEvent(event) {
337
- const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;
338
- switch (event.level) {
339
- case "error":
340
- console.error(message);
341
- break;
342
- case "warn":
343
- console.warn(message);
344
- break;
345
- default:
346
- console.log(message);
347
- break;
348
- }
349
- }
350
- function formatFarmEventDetails(event) {
351
- const details = [];
352
- const record = event;
353
- for (const key of [
354
- "route",
355
- "pathname",
356
- "method",
357
- "status",
358
- "key",
359
- "tag",
360
- "path",
361
- "reason",
362
- "durationMs",
363
- "integration",
364
- "server",
365
- "tool",
366
- "outcome",
367
- "operation",
368
- "plugin",
369
- "hook",
370
- "target",
371
- "count"
372
- ]) {
373
- const value = record[key];
374
- if (value !== void 0) {
375
- details.push(`${key}=${formatDetailValue(value)}`);
376
- }
377
- }
378
- return details.length > 0 ? ` ${details.join(" ")}` : "";
379
- }
380
- function formatDetailValue(value) {
381
- if (typeof value === "string") {
382
- return value;
383
- }
384
- if (typeof value === "number" || typeof value === "boolean") {
385
- return String(value);
386
- }
387
- try {
388
- return JSON.stringify(value);
389
- } catch {
390
- return String(value);
391
- }
392
- }
393
- function formatError(error) {
394
- return error instanceof Error ? error.message : String(error);
395
- }
396
- var OBSERVABILITY_RUNTIME, runtime2, shared, runtimeHandlers, unfilteredRuntimeHandlers, observabilityState;
397
- var init_observability = __esm({
398
- "src/observability.ts"() {
399
- "use strict";
400
- init_tracing();
401
- OBSERVABILITY_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/observability-runtime/v1");
402
- runtime2 = globalThis;
403
- shared = runtime2[OBSERVABILITY_RUNTIME] ?? (runtime2[OBSERVABILITY_RUNTIME] = {
404
- handlers: /* @__PURE__ */ new Set(),
405
- unfilteredHandlers: /* @__PURE__ */ new Set(),
406
- config: { logs: false, handlers: [], tracing: normalizeFarmTracingConfig(false) }
407
- });
408
- runtimeHandlers = shared.handlers;
409
- unfilteredRuntimeHandlers = shared.unfilteredHandlers;
410
- observabilityState = shared.config;
411
- __name(emitFarmEvent, "emitFarmEvent");
412
- __name(notifyFarmEventHandlers, "notifyFarmEventHandlers");
413
- __name(shouldEmitFarmEvent, "shouldEmitFarmEvent");
414
- __name(inferFarmEventLevel, "inferFarmEventLevel");
415
- __name(logFarmEvent, "logFarmEvent");
416
- __name(formatFarmEventDetails, "formatFarmEventDetails");
417
- __name(formatDetailValue, "formatDetailValue");
418
- __name(formatError, "formatError");
419
- }
420
- });
421
-
422
- // src/cache-invalidation.ts
423
- function getFarmCacheInvalidationState() {
424
- return globalState[FARM_CACHE_INVALIDATION_STATE] ?? (globalState[FARM_CACHE_INVALIDATION_STATE] = {
425
- listeners: /* @__PURE__ */ new Set(),
426
- taskListeners: /* @__PURE__ */ new Set()
427
- });
428
- }
429
- function encodeFarmCacheInvalidations(keys) {
430
- const normalized = Array.from(
431
- new Set(keys.filter((key) => typeof key === "string" && key.length > 0))
432
- );
433
- if (normalized.length === 0) return null;
434
- return encodeURIComponent(JSON.stringify(normalized));
435
- }
436
- function decodeFarmCacheInvalidations(value) {
437
- if (!value) return [];
438
- try {
439
- const parsed = JSON.parse(decodeURIComponent(value));
440
- return Array.isArray(parsed) ? Array.from(
441
- new Set(parsed.filter((key) => typeof key === "string" && key.length > 0))
442
- ) : [];
443
- } catch {
444
- return [];
445
- }
446
- }
447
- function subscribeFarmCacheInvalidation(listener) {
448
- const state = getFarmCacheInvalidationState();
449
- state.listeners.add(listener);
450
- return () => state.listeners.delete(listener);
451
- }
452
- function subscribeFarmCacheTask(listener) {
453
- const state = getFarmCacheInvalidationState();
454
- state.taskListeners.add(listener);
455
- return () => state.taskListeners.delete(listener);
456
- }
457
- var FARM_CACHE_INVALIDATION_HEADER, FARM_CACHE_INVALIDATION_STATE, globalState;
458
- var init_cache_invalidation = __esm({
459
- "src/cache-invalidation.ts"() {
460
- "use strict";
461
- FARM_CACHE_INVALIDATION_HEADER = "x-farm-cache-invalidations";
462
- FARM_CACHE_INVALIDATION_STATE = /* @__PURE__ */ Symbol.for("farm.cacheInvalidationState");
463
- globalState = globalThis;
464
- __name(getFarmCacheInvalidationState, "getFarmCacheInvalidationState");
465
- __name(encodeFarmCacheInvalidations, "encodeFarmCacheInvalidations");
466
- __name(decodeFarmCacheInvalidations, "decodeFarmCacheInvalidations");
467
- __name(subscribeFarmCacheInvalidation, "subscribeFarmCacheInvalidation");
468
- __name(subscribeFarmCacheTask, "subscribeFarmCacheTask");
469
- }
470
- });
471
-
472
- // src/i18n/bridge.ts
473
- function _setFarmI18nSnapshotResolver(resolver) {
474
- globalThis[FARM_I18N_SNAPSHOT_RESOLVER] = resolver;
475
- }
476
- var FARM_I18N_SNAPSHOT_RESOLVER;
477
- var init_bridge = __esm({
478
- "src/i18n/bridge.ts"() {
479
- "use strict";
480
- FARM_I18N_SNAPSHOT_RESOLVER = /* @__PURE__ */ Symbol.for("farm.i18n.snapshotResolver");
481
- __name(_setFarmI18nSnapshotResolver, "_setFarmI18nSnapshotResolver");
482
- }
483
- });
484
-
485
- // src/cache-invalidation-stream.ts
486
- var MAX_BUFFERED_BYTES, textEncoder;
487
- var init_cache_invalidation_stream = __esm({
488
- "src/cache-invalidation-stream.ts"() {
489
- "use strict";
490
- init_cache_invalidation();
491
- MAX_BUFFERED_BYTES = 64 * 1024;
492
- textEncoder = new TextEncoder();
493
- }
494
- });
495
-
496
- // src/cache.ts
497
- function getFarmDataCache() {
498
- return sharedFarmDataCache;
499
- }
500
- function createPathCacheTag(routePath) {
501
- return `path:${normalizeRevalidatePath(routePath)}`;
502
- }
503
- function createRouteDataCacheTag(key) {
504
- return `route-data:${createRouteDataCacheKey(key)}`;
505
- }
506
- function createRouteDataCacheKey(key) {
507
- return createFarmCacheKey(Array.isArray(key) ? key : [key]);
508
- }
509
- function normalizeRevalidatePath(routePath) {
510
- if (typeof routePath !== "string") {
511
- throw new TypeError("revalidatePath expects a path string.");
512
- }
513
- let normalized = routePath.trim();
514
- if (!normalized) {
515
- throw new Error("revalidatePath expects a non-empty path.");
516
- }
517
- try {
518
- if (/^https?:\/\//i.test(normalized)) {
519
- normalized = new URL(normalized).pathname;
520
- }
521
- } catch {
522
- }
523
- normalized = normalized.split(/[?#]/, 1)[0] ?? normalized;
524
- normalized = normalized.startsWith("/") ? normalized : `/${normalized}`;
525
- normalized = normalized.replace(/\/{2,}/g, "/");
526
- normalized = new URL(normalized, "http://farm.invalid").pathname;
527
- if (normalized.length > 1) {
528
- normalized = normalized.replace(/\/+$/, "");
529
- }
530
- return normalized || "/";
531
- }
532
- function createFarmCacheKey(parts) {
533
- return stableSerialize(parts);
534
- }
535
- function normalizeRevalidate(revalidate) {
536
- if (revalidate === false || revalidate === void 0) {
537
- return revalidate;
538
- }
539
- if (!Number.isFinite(revalidate) || revalidate < 0) {
540
- throw new TypeError("Cache revalidate must be false or a finite, non-negative number.");
541
- }
542
- return revalidate;
543
- }
544
- function normalizeCacheTag(tag) {
545
- if (typeof tag !== "string") {
546
- throw new TypeError("Cache tags must be strings.");
547
- }
548
- const normalized = tag.trim();
549
- if (!normalized) {
550
- throw new Error("Cache tags cannot be empty.");
551
- }
552
- return normalized;
553
- }
554
- function normalizeCacheNamespace(namespace) {
555
- if (typeof namespace !== "string") {
556
- throw new TypeError("Cache namespace must be a string.");
557
- }
558
- const normalized = namespace.trim().replace(/:+$/g, "");
559
- if (!normalized) {
560
- throw new Error("Cache namespace cannot be empty.");
561
- }
562
- return normalized;
563
- }
564
- function normalizeAdapterVersion(value) {
565
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
566
- }
567
- function normalizePositiveDuration(value, fallback, name) {
568
- if (value === void 0) return fallback;
569
- if (!Number.isFinite(value) || value <= 0) {
570
- throw new TypeError(`${name} must be a positive number of milliseconds.`);
571
- }
572
- return Math.floor(value);
573
- }
574
- function normalizePositiveInteger(value, fallback, name) {
575
- if (value === void 0) return fallback;
576
- if (!Number.isSafeInteger(value) || value <= 0) {
577
- throw new TypeError(`${name} must be a positive integer.`);
578
- }
579
- return value;
580
- }
581
- function delay(ms) {
582
- return new Promise((resolve) => setTimeout(resolve, ms));
583
- }
584
- function normalizeCacheOptionsTags(options) {
585
- const tags = /* @__PURE__ */ new Set();
586
- for (const tag of options.tags ?? []) {
587
- tags.add(normalizeCacheTag(tag));
588
- }
589
- for (const routePath of options.paths ?? []) {
590
- tags.add(createPathCacheTag(routePath));
591
- }
592
- return tags;
593
- }
594
- function assertFarmCacheEntry(entry, expectedKey) {
595
- if (!entry || typeof entry !== "object" || entry.key !== expectedKey || !Array.isArray(entry.tags) || typeof entry.createdAt !== "number") {
596
- throw new TypeError(
597
- `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`
598
- );
599
- }
600
- }
601
- function getFunctionCacheIdentity(fn) {
602
- const name = fn.name || "anonymous";
603
- return `${name}:${hashFunctionSource(String(fn))}`;
604
- }
605
- function hashFunctionSource(source) {
606
- let hash = 2166136261;
607
- for (let index = 0; index < source.length; index++) {
608
- hash ^= source.charCodeAt(index);
609
- hash = Math.imul(hash, 16777619);
610
- }
611
- return (hash >>> 0).toString(36);
612
- }
613
- function compareCodepoint(a, b) {
614
- return a < b ? -1 : a > b ? 1 : 0;
615
- }
616
- function serializeBinaryBytes(bytes) {
617
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
618
- }
619
- function serializeCanonicalStringEntries(entries, seen) {
620
- const valuesByKey = /* @__PURE__ */ new Map();
621
- for (const [key, item] of entries) {
622
- const values = valuesByKey.get(key);
623
- if (values) values.push(item);
624
- else valuesByKey.set(key, [item]);
625
- }
626
- return Array.from(valuesByKey.keys()).sort(compareCodepoint).flatMap(
627
- (key) => valuesByKey.get(key).map((item) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`)
628
- ).join(",");
629
- }
630
- function isPlainCacheKeyObject(value) {
631
- const prototype = Object.getPrototypeOf(value);
632
- if (prototype === null) return true;
633
- const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
634
- return Object.getPrototypeOf(prototype) === null && typeof constructor === "function" && constructor.name === "Object";
635
- }
636
- function getCacheKeyValueType(value) {
637
- const prototype = Object.getPrototypeOf(value);
638
- const constructor = prototype ? Object.getOwnPropertyDescriptor(prototype, "constructor")?.value : void 0;
639
- if (typeof constructor === "function" && constructor.name) {
640
- return constructor.name;
641
- }
642
- return Object.prototype.toString.call(value).slice(8, -1) || "object";
643
- }
644
- function stableSerialize(value, seen = /* @__PURE__ */ new WeakSet()) {
645
- if (value === null) return "null";
646
- if (value === void 0) return "undefined";
647
- const valueType = typeof value;
648
- if (valueType === "string") return JSON.stringify(value);
649
- if (valueType === "number" || valueType === "boolean" || valueType === "bigint") {
650
- return `${valueType}:${String(value)}`;
651
- }
652
- if (valueType === "symbol") {
653
- return `symbol:${String(value)}`;
654
- }
655
- if (valueType === "function") {
656
- return `function:${getFunctionCacheIdentity(value)}`;
657
- }
658
- if (value instanceof Date) {
659
- return Number.isNaN(value.getTime()) ? "date:invalid" : `date:${value.toISOString()}`;
660
- }
661
- if (value instanceof URL) {
662
- return `url:${value.toString()}`;
663
- }
664
- if (value instanceof RegExp) {
665
- return `regexp:${value.toString()}`;
666
- }
667
- if (value instanceof ArrayBuffer) {
668
- return `arraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
669
- }
670
- if (typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer) {
671
- return `sharedarraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
672
- }
673
- if (ArrayBuffer.isView(value)) {
674
- const viewType = Object.prototype.toString.call(value).slice(8, -1);
675
- const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
676
- return `binary:${viewType}:${serializeBinaryBytes(bytes)}`;
677
- }
678
- if (value && typeof value === "object") {
679
- if (seen.has(value)) {
680
- return "[Circular]";
681
- }
682
- seen.add(value);
683
- if (Array.isArray(value)) {
684
- const items = [];
685
- for (let index = 0; index < value.length; index++) {
686
- items.push(
687
- Object.prototype.hasOwnProperty.call(value, index) ? stableSerialize(value[index], seen) : "[Hole]"
688
- );
689
- }
690
- seen.delete(value);
691
- return `[${items.join(",")}]`;
692
- }
693
- if (value instanceof Set) {
694
- const items = Array.from(value, (item) => stableSerialize(item, seen)).sort(compareCodepoint);
695
- seen.delete(value);
696
- return `set:[${items.join(",")}]`;
697
- }
698
- if (value instanceof Map) {
699
- const items = Array.from(
700
- value,
701
- ([key, item]) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`
702
- ).sort(compareCodepoint);
703
- seen.delete(value);
704
- return `map:[${items.join(",")}]`;
705
- }
706
- if (value instanceof URLSearchParams) {
707
- const serialized2 = serializeCanonicalStringEntries(value, seen);
708
- seen.delete(value);
709
- return `urlsearchparams:[${serialized2}]`;
710
- }
711
- if (value instanceof Headers) {
712
- const serialized2 = serializeCanonicalStringEntries(value, seen);
713
- seen.delete(value);
714
- return `headers:[${serialized2}]`;
715
- }
716
- if (!isPlainCacheKeyObject(value)) {
717
- throw new TypeError(
718
- `Cache keys do not support ${getCacheKeyValueType(value)} values. Convert the value to an explicit stable string or structured key before caching.`
719
- );
720
- }
721
- const entries = Object.entries(value).sort(
722
- ([a], [b]) => compareCodepoint(a, b)
723
- );
724
- const serialized = entries.map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`).join(",");
725
- seen.delete(value);
726
- return `{${serialized}}`;
727
- }
728
- return String(value);
729
- }
730
- var _FarmDataCache, FarmDataCache, FARM_DATA_CACHE_SYMBOL, farmDataCacheGlobal, sharedFarmDataCache;
731
- var init_cache = __esm({
732
- "src/cache.ts"() {
733
- "use strict";
734
- init_observability();
735
- init_cache_invalidation();
736
- init_bridge();
737
- init_cache_invalidation();
738
- init_cache_invalidation_stream();
739
- _FarmDataCache = class _FarmDataCache {
740
- constructor(config = {}) {
741
- this.entries = /* @__PURE__ */ new Map();
742
- this.inflight = /* @__PURE__ */ new Map();
743
- this.invalidatedTagVersions = /* @__PURE__ */ new Map();
744
- this.activeGenerations = /* @__PURE__ */ new Set();
745
- this.version = 0;
746
- this.generation = 0;
747
- this.namespace = "farm";
748
- this.local = true;
749
- this.maxEntries = 1024;
750
- this.lease = {
751
- enabled: true,
752
- ttlMs: 1e4,
753
- waitTimeoutMs: 1e4,
754
- pollIntervalMs: 25
755
- };
756
- this.configure(config);
757
- }
758
- configure(config = {}) {
759
- this.generation++;
760
- this.entries.clear();
761
- this.inflight.clear();
762
- this.invalidatedTagVersions.clear();
763
- this.activeGenerations.clear();
764
- this.version = 0;
765
- this.adapter = config.adapter;
766
- this.namespace = normalizeCacheNamespace(config.namespace || "farm");
767
- this.local = !config.adapter;
768
- this.maxEntries = normalizePositiveInteger(config.maxEntries, 1024, "cache.maxEntries");
769
- this.lease = config.lease === false ? { ...this.lease, enabled: false } : {
770
- enabled: true,
771
- ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 1e4, "cache.lease.ttlMs"),
772
- waitTimeoutMs: normalizePositiveDuration(
773
- config.lease?.waitTimeoutMs,
774
- 1e4,
775
- "cache.lease.waitTimeoutMs"
776
- ),
777
- pollIntervalMs: normalizePositiveDuration(
778
- config.lease?.pollIntervalMs,
779
- 25,
780
- "cache.lease.pollIntervalMs"
781
- )
782
- };
783
- }
784
- get adapterName() {
785
- return this.adapter?.name || (this.adapter ? "custom" : "memory");
786
- }
787
- get hasAdapter() {
788
- return this.adapter !== void 0;
789
- }
790
- get size() {
791
- return this.entries.size;
792
- }
793
- get(key, options = {}) {
794
- return this.getEntry(key, options)?.value;
795
- }
796
- getEntry(key, options = {}) {
797
- const entry = this.entries.get(key);
798
- if (!entry) {
799
- emitFarmEvent({ type: "cache.miss", key });
800
- return void 0;
801
- }
802
- const stale = this.isStale(entry, options.now);
803
- if (stale) {
804
- emitFarmEvent({
805
- type: "cache.stale",
806
- key,
807
- tags: Array.from(entry.tags),
808
- revalidate: entry.revalidate
809
- });
810
- }
811
- if (!options.allowStale && stale) {
812
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
813
- return void 0;
814
- }
815
- this.touchEntry(key, entry);
816
- emitFarmEvent({
817
- type: "cache.hit",
818
- key,
819
- tags: Array.from(entry.tags),
820
- revalidate: entry.revalidate,
821
- stale
822
- });
823
- return this.toPublicEntry(entry);
824
- }
825
- async getEntryAsync(key, options = {}) {
826
- if (this.local) {
827
- const localEntry = this.getEntry(key, options);
828
- if (localEntry) return localEntry;
829
- }
830
- if (!this.adapter) {
831
- return this.local ? void 0 : this.getEntry(key, options);
832
- }
833
- const generation = this.generation;
834
- const adapter = this.adapter;
835
- const namespace = this.namespace;
836
- const entry = await adapter.get(`${namespace}:entry:${key}`);
837
- if (generation !== this.generation) return void 0;
838
- if (!entry) {
839
- emitFarmEvent({ type: "cache.miss", key });
840
- return void 0;
841
- }
842
- assertFarmCacheEntry(entry, key);
843
- const stale = await this.isAdapterEntryStale(entry, options.now, adapter, namespace);
844
- if (generation !== this.generation) return void 0;
845
- if (stale) {
846
- emitFarmEvent({
847
- type: "cache.stale",
848
- key,
849
- tags: [...entry.tags],
850
- revalidate: entry.revalidate
851
- });
852
- if (!options.allowStale) {
853
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
854
- return void 0;
855
- }
856
- }
857
- emitFarmEvent({
858
- type: "cache.hit",
859
- key,
860
- tags: [...entry.tags],
861
- revalidate: entry.revalidate,
862
- stale
863
- });
864
- if (this.local && !stale) {
865
- this.hydrateLocalEntry(entry);
866
- }
867
- return { ...entry, key };
868
- }
869
- set(key, value, options = {}) {
870
- const revalidate = normalizeRevalidate(options.revalidate);
871
- const tags = /* @__PURE__ */ new Set();
872
- for (const tag of options.tags ?? []) {
873
- tags.add(normalizeCacheTag(tag));
874
- }
875
- for (const routePath of options.paths ?? []) {
876
- tags.add(createPathCacheTag(routePath));
877
- }
878
- const entry = {
879
- key,
880
- value,
881
- tags,
882
- tagVersions: void 0,
883
- createdAt: options.createdAt ?? Date.now(),
884
- createdVersion: ++this.version,
885
- revalidate
886
- };
887
- this.storeLocalEntry(entry);
888
- emitFarmEvent({
889
- type: "cache.set",
890
- key,
891
- tags: Array.from(tags),
892
- revalidate: entry.revalidate
893
- });
894
- return this.toPublicEntry(entry);
895
- }
896
- async setAsync(key, value, options = {}, tagVersions) {
897
- return this.writeAsync(key, value, options, tagVersions);
898
- }
899
- async writeAsync(key, value, options, tagVersions, createdVersion) {
900
- const revalidate = normalizeRevalidate(options.revalidate);
901
- const tags = normalizeCacheOptionsTags(options);
902
- const capturedVersions = tagVersions ?? await this.getAdapterTagVersions(Array.from(tags.values()));
903
- const entry = {
904
- key,
905
- value,
906
- tags: Array.from(tags),
907
- tagVersions: capturedVersions,
908
- createdAt: options.createdAt ?? Date.now(),
909
- createdVersion: createdVersion ?? ++this.version,
910
- revalidate
911
- };
912
- if (this.local) {
913
- this.hydrateLocalEntry(entry);
914
- }
915
- if (this.adapter) {
916
- await this.adapter.set(this.createAdapterKey(key), entry);
917
- }
918
- emitFarmEvent({
919
- type: "cache.set",
920
- key,
921
- tags: [...entry.tags],
922
- revalidate: entry.revalidate
923
- });
924
- return entry;
925
- }
926
- delete(key) {
927
- const deleted = this.entries.delete(key);
928
- if (deleted) this.pruneInvalidatedTagVersions();
929
- emitFarmEvent({ type: "cache.delete", key, deleted });
930
- return deleted;
931
- }
932
- async deleteAsync(key) {
933
- const deleted = this.entries.delete(key);
934
- if (deleted) this.pruneInvalidatedTagVersions();
935
- if (this.adapter) {
936
- await this.adapter.delete(this.createAdapterKey(key));
937
- }
938
- emitFarmEvent({ type: "cache.delete", key, deleted: this.adapter ? true : deleted });
939
- return this.adapter ? true : deleted;
940
- }
941
- clear() {
942
- const count = this.entries.size;
943
- this.generation++;
944
- this.entries.clear();
945
- this.inflight.clear();
946
- this.invalidatedTagVersions.clear();
947
- this.activeGenerations.clear();
948
- this.version = 0;
949
- emitFarmEvent({ type: "cache.clear", count });
950
- }
951
- async clearAsync() {
952
- this.clear();
953
- await this.adapter?.clear?.();
954
- }
955
- isStale(entry, now = Date.now()) {
956
- if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
957
- return true;
958
- }
959
- for (const tag of entry.tags) {
960
- const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));
961
- if (typeof invalidatedVersion === "number" && typeof entry.createdVersion === "number" && invalidatedVersion > entry.createdVersion) {
962
- return true;
963
- }
964
- }
965
- return false;
966
- }
967
- async isStaleAsync(entry, now = Date.now()) {
968
- if (this.adapter) {
969
- return this.isAdapterEntryStale(entry, now);
970
- }
971
- return this.isStale(entry, now);
972
- }
973
- revalidateTag(tag, options = {}) {
974
- const normalized = normalizeCacheTag(tag);
975
- const count = this.invalidateTag(normalized);
976
- emitFarmEvent(
977
- options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
978
- );
979
- return count;
980
- }
981
- async revalidateTagAsync(tag, options = {}) {
982
- const normalized = normalizeCacheTag(tag);
983
- const count = this.invalidateTag(normalized);
984
- await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);
985
- emitFarmEvent(
986
- options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
987
- );
988
- return count;
989
- }
990
- revalidatePath(routePath) {
991
- const normalizedPath = normalizeRevalidatePath(routePath);
992
- const pathTag = createPathCacheTag(normalizedPath);
993
- const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
994
- const count = this.invalidateTag(pathTag);
995
- emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
996
- if (pprCount > 0) {
997
- emitFarmEvent({
998
- type: "ppr.shell.invalidated",
999
- route: normalizedPath,
1000
- reason: "revalidatePath",
1001
- count: pprCount
1002
- });
1003
- }
1004
- return count;
1005
- }
1006
- async revalidatePathAsync(routePath) {
1007
- const normalizedPath = normalizeRevalidatePath(routePath);
1008
- const pathTag = createPathCacheTag(normalizedPath);
1009
- const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
1010
- const count = this.invalidateTag(pathTag);
1011
- await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);
1012
- emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
1013
- if (pprCount > 0) {
1014
- emitFarmEvent({
1015
- type: "ppr.shell.invalidated",
1016
- route: normalizedPath,
1017
- reason: "revalidatePath",
1018
- count: pprCount
1019
- });
1020
- }
1021
- return count;
1022
- }
1023
- async getOrSet(key, producer, options = {}) {
1024
- normalizeRevalidate(options.revalidate);
1025
- const cached = await this.getEntryAsync(key);
1026
- if (cached) {
1027
- return cached.value;
1028
- }
1029
- const inflight = this.inflight.get(key);
1030
- if (inflight) {
1031
- emitFarmEvent({ type: "cache.dedupe", key });
1032
- return inflight;
1033
- }
1034
- const tags = Array.from(normalizeCacheOptionsTags(options));
1035
- const generation = this.generation;
1036
- const promise = this.fillCacheEntry(key, producer, options, tags, generation).catch((error) => {
1037
- emitFarmEvent({ type: "cache.error", key, operation: "set", error });
1038
- throw error;
1039
- }).finally(() => {
1040
- if (this.inflight.get(key) === promise) {
1041
- this.inflight.delete(key);
1042
- }
1043
- });
1044
- this.inflight.set(key, promise);
1045
- return promise;
1046
- }
1047
- async fillCacheEntry(key, producer, options, tags, generation) {
1048
- const adapter = this.adapter;
1049
- const namespace = this.namespace;
1050
- const lease = { ...this.lease };
1051
- const leaseKey = `${namespace}:lease:${key}`;
1052
- let leaseToken;
1053
- if (adapter?.acquireLease && adapter.releaseLease && lease.enabled) {
1054
- leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
1055
- if (!leaseToken) {
1056
- const shared2 = await this.waitForAdapterEntry(
1057
- key,
1058
- adapter,
1059
- namespace,
1060
- lease,
1061
- generation
1062
- );
1063
- if (shared2) {
1064
- emitFarmEvent({ type: "cache.dedupe", key });
1065
- return shared2.value;
1066
- }
1067
- if (generation === this.generation) {
1068
- leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
1069
- }
1070
- }
1071
- }
1072
- const initialCreatedVersion = this.version;
1073
- const activeGeneration = {
1074
- tags: new Set(tags),
1075
- createdVersion: initialCreatedVersion
1076
- };
1077
- this.activeGenerations.add(activeGeneration);
1078
- try {
1079
- const initialTagVersions = await this.getAdapterTagVersions(tags, adapter, namespace);
1080
- const value = await producer();
1081
- if (generation === this.generation) {
1082
- await this.writeAsync(key, value, options, initialTagVersions, initialCreatedVersion);
1083
- }
1084
- return value;
1085
- } finally {
1086
- this.activeGenerations.delete(activeGeneration);
1087
- this.pruneInvalidatedTagVersions();
1088
- if (leaseToken && adapter?.releaseLease) {
1089
- try {
1090
- await adapter.releaseLease(leaseKey, leaseToken);
1091
- } catch (error) {
1092
- emitFarmEvent({ type: "cache.error", key, operation: "set", error });
1093
- }
1094
- }
1095
- }
1096
- }
1097
- async waitForAdapterEntry(key, adapter, namespace, lease, generation) {
1098
- const deadline = Date.now() + lease.waitTimeoutMs;
1099
- while (Date.now() < deadline) {
1100
- await delay(lease.pollIntervalMs);
1101
- if (generation !== this.generation) return void 0;
1102
- const entry = await adapter.get(`${namespace}:entry:${key}`);
1103
- if (generation !== this.generation) return void 0;
1104
- if (!entry) {
1105
- emitFarmEvent({ type: "cache.miss", key });
1106
- continue;
1107
- }
1108
- assertFarmCacheEntry(entry, key);
1109
- const stale = await this.isAdapterEntryStale(entry, Date.now(), adapter, namespace);
1110
- if (generation !== this.generation) return void 0;
1111
- if (stale) {
1112
- emitFarmEvent({
1113
- type: "cache.stale",
1114
- key,
1115
- tags: [...entry.tags],
1116
- revalidate: entry.revalidate
1117
- });
1118
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
1119
- } else {
1120
- emitFarmEvent({
1121
- type: "cache.hit",
1122
- key,
1123
- tags: [...entry.tags],
1124
- revalidate: entry.revalidate,
1125
- stale: false
1126
- });
1127
- return { ...entry, key };
1128
- }
1129
- }
1130
- return void 0;
1131
- }
1132
- countEntriesForTag(tag) {
1133
- let count = 0;
1134
- for (const entry of this.entries.values()) {
1135
- if (entry.tags.has(tag)) {
1136
- count++;
1137
- }
1138
- }
1139
- return count;
1140
- }
1141
- countEntriesForTags(tags) {
1142
- let count = 0;
1143
- for (const entry of this.entries.values()) {
1144
- if (tags.every((tag) => entry.tags.has(tag))) {
1145
- count++;
1146
- }
1147
- }
1148
- return count;
1149
- }
1150
- invalidateTag(normalizedTag) {
1151
- const count = this.countEntriesForTag(normalizedTag);
1152
- this.invalidatedTagVersions.delete(normalizedTag);
1153
- this.invalidatedTagVersions.set(normalizedTag, ++this.version);
1154
- this.pruneInvalidatedTagVersions();
1155
- return count;
1156
- }
1157
- toPublicEntry(entry) {
1158
- return {
1159
- key: entry.key,
1160
- value: entry.value,
1161
- tags: Array.from(entry.tags),
1162
- tagVersions: entry.tagVersions,
1163
- createdAt: entry.createdAt,
1164
- createdVersion: entry.createdVersion,
1165
- revalidate: entry.revalidate
1166
- };
1167
- }
1168
- hydrateLocalEntry(entry) {
1169
- this.storeLocalEntry({
1170
- key: entry.key,
1171
- value: entry.value,
1172
- tags: new Set(entry.tags.map(normalizeCacheTag)),
1173
- tagVersions: entry.tagVersions,
1174
- createdAt: entry.createdAt,
1175
- createdVersion: entry.createdVersion ?? ++this.version,
1176
- revalidate: normalizeRevalidate(entry.revalidate)
1177
- });
1178
- }
1179
- touchEntry(key, entry) {
1180
- this.entries.delete(key);
1181
- this.entries.set(key, entry);
1182
- }
1183
- storeLocalEntry(entry) {
1184
- this.entries.delete(entry.key);
1185
- this.entries.set(entry.key, entry);
1186
- while (this.entries.size > this.maxEntries) {
1187
- const oldestKey = this.entries.keys().next().value;
1188
- if (oldestKey === void 0) break;
1189
- this.entries.delete(oldestKey);
1190
- }
1191
- this.pruneInvalidatedTagVersions();
1192
- }
1193
- pruneInvalidatedTagVersions() {
1194
- tags: for (const [tag, invalidatedVersion] of this.invalidatedTagVersions) {
1195
- for (const entry of this.entries.values()) {
1196
- if (entry.tags.has(tag) && entry.createdVersion < invalidatedVersion) continue tags;
1197
- }
1198
- for (const generation of this.activeGenerations) {
1199
- if (generation.tags.has(tag) && generation.createdVersion < invalidatedVersion)
1200
- continue tags;
1201
- }
1202
- this.invalidatedTagVersions.delete(tag);
1203
- }
1204
- }
1205
- createAdapterKey(key) {
1206
- return `${this.namespace}:entry:${key}`;
1207
- }
1208
- createAdapterTag(tag) {
1209
- return `${this.namespace}:tag:${tag}`;
1210
- }
1211
- async getAdapterTagVersions(tags, adapter = this.adapter, namespace = this.namespace) {
1212
- if (!adapter?.getTagVersions || tags.length === 0) return {};
1213
- const normalized = tags.map(normalizeCacheTag);
1214
- const physicalTags = normalized.map((tag) => `${namespace}:tag:${tag}`);
1215
- const versions = await adapter.getTagVersions(physicalTags);
1216
- return Object.fromEntries(
1217
- normalized.map((tag, index) => [
1218
- tag,
1219
- normalizeAdapterVersion(versions[physicalTags[index]])
1220
- ])
1221
- );
1222
- }
1223
- async isAdapterEntryStale(entry, now = Date.now(), adapter = this.adapter, namespace = this.namespace) {
1224
- if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
1225
- return true;
1226
- }
1227
- const currentVersions = await this.getAdapterTagVersions(entry.tags, adapter, namespace);
1228
- for (const tag of entry.tags) {
1229
- if (normalizeAdapterVersion(currentVersions[tag]) > normalizeAdapterVersion(entry.tagVersions?.[tag])) {
1230
- return true;
1231
- }
1232
- }
1233
- return false;
1234
- }
1235
- };
1236
- __name(_FarmDataCache, "FarmDataCache");
1237
- FarmDataCache = _FarmDataCache;
1238
- FARM_DATA_CACHE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.dataCache");
1239
- farmDataCacheGlobal = globalThis;
1240
- sharedFarmDataCache = farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ?? (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] = new FarmDataCache());
1241
- __name(getFarmDataCache, "getFarmDataCache");
1242
- __name(createPathCacheTag, "createPathCacheTag");
1243
- __name(createRouteDataCacheTag, "createRouteDataCacheTag");
1244
- __name(createRouteDataCacheKey, "createRouteDataCacheKey");
1245
- __name(normalizeRevalidatePath, "normalizeRevalidatePath");
1246
- __name(createFarmCacheKey, "createFarmCacheKey");
1247
- __name(normalizeRevalidate, "normalizeRevalidate");
1248
- __name(normalizeCacheTag, "normalizeCacheTag");
1249
- __name(normalizeCacheNamespace, "normalizeCacheNamespace");
1250
- __name(normalizeAdapterVersion, "normalizeAdapterVersion");
1251
- __name(normalizePositiveDuration, "normalizePositiveDuration");
1252
- __name(normalizePositiveInteger, "normalizePositiveInteger");
1253
- __name(delay, "delay");
1254
- __name(normalizeCacheOptionsTags, "normalizeCacheOptionsTags");
1255
- __name(assertFarmCacheEntry, "assertFarmCacheEntry");
1256
- __name(getFunctionCacheIdentity, "getFunctionCacheIdentity");
1257
- __name(hashFunctionSource, "hashFunctionSource");
1258
- __name(compareCodepoint, "compareCodepoint");
1259
- __name(serializeBinaryBytes, "serializeBinaryBytes");
1260
- __name(serializeCanonicalStringEntries, "serializeCanonicalStringEntries");
1261
- __name(isPlainCacheKeyObject, "isPlainCacheKeyObject");
1262
- __name(getCacheKeyValueType, "getCacheKeyValueType");
1263
- __name(stableSerialize, "stableSerialize");
1264
- }
1265
- });
1266
-
1267
- // src/routing/specificity.ts
1268
- function compareRouteSpecificity(left, right) {
1269
- const length = Math.max(left.length, right.length);
1270
- for (let index = 0; index < length; index++) {
1271
- const leftRank = index < left.length ? SEGMENT_RANK[left[index]] : ROUTE_END_RANK;
1272
- const rightRank = index < right.length ? SEGMENT_RANK[right[index]] : ROUTE_END_RANK;
1273
- if (leftRank !== rightRank) return rightRank - leftRank;
1274
- }
1275
- return 0;
1276
- }
1277
- function assertBrowserStableRoutePath(pattern) {
1278
- if (pattern.includes("\\") || hasControlCharacter(pattern)) {
1279
- throw new BrowserUnstableRouteError(
1280
- `Route path "${pattern}" cannot contain backslashes or control characters.`
1281
- );
1282
- }
1283
- for (const segment of pattern.split("/").filter(Boolean)) {
1284
- if (segment.startsWith("(") && segment.endsWith(")") || segment.startsWith("[") && segment.endsWith("]")) {
1285
- continue;
1286
- }
1287
- let decoded = segment;
1288
- try {
1289
- decoded = decodeURIComponent(segment);
1290
- } catch {
1291
- }
1292
- if (decoded === "." || decoded === ".." || decoded.includes("/") || decoded.includes("\\") || hasControlCharacter(decoded)) {
1293
- throw new BrowserUnstableRouteError(
1294
- `Route path "${pattern}" contains browser-unstable segment "${segment}".`
1295
- );
1296
- }
1297
- }
1298
- }
1299
- function hasControlCharacter(value) {
1300
- return Array.from(value).some((character) => {
1301
- const code = character.charCodeAt(0);
1302
- return code <= 31 || code >= 127 && code <= 159;
1303
- });
1304
- }
1305
- function assertUniqueRouteParameters(pattern, syntax = "page") {
1306
- const parameterPattern = syntax === "router" ? ROUTER_PARAMETER_PATTERN : PAGE_PARAMETER_PATTERN;
1307
- const names = /* @__PURE__ */ new Set();
1308
- for (const segment of splitRoutePattern(pattern, syntax)) {
1309
- const match = parameterPattern.exec(segment);
1310
- const name = match?.slice(1).find(Boolean);
1311
- if (!name) continue;
1312
- if (RESERVED_PARAMETER_NAMES.has(name)) {
1313
- throw new ReservedRouteParameterError(
1314
- `Route parameter "${name}" in route "${pattern}" is reserved. Use a different parameter name.`
1315
- );
1316
- }
1317
- if (names.has(name)) {
1318
- throw new DuplicateRouteParameterError(
1319
- `Duplicate route parameter "${name}" in route "${pattern}". Each dynamic segment must use a unique name.`
1320
- );
1321
- }
1322
- names.add(name);
1323
- }
1324
- }
1325
- function splitRoutePattern(pattern, syntax) {
1326
- return pattern.replace(/\\/g, "/").split("/").filter(Boolean).filter(
1327
- (segment) => syntax === "api" ? true : !(segment.startsWith("(") && segment.endsWith(")"))
1328
- );
1329
- }
1330
- function assertTerminalCatchAll(pattern, syntax = "page") {
1331
- const segments = splitRoutePattern(pattern, syntax);
1332
- const parameterName = syntax === "router" ? ROUTER_PARAMETER_NAME : ".+";
1333
- const catchAllPattern = new RegExp(
1334
- syntax === "router" ? `^(?:\\[\\[\\.\\.\\.${parameterName}\\]\\]|\\[\\.\\.\\.${parameterName}\\]|\\*${parameterName}\\??)$` : `^(?:\\[\\[\\.\\.\\.${parameterName}\\]\\]|\\[\\.\\.\\.${parameterName}\\])$`
1335
- );
1336
- const catchAllIndex = segments.findIndex((segment) => catchAllPattern.test(segment));
1337
- if (catchAllIndex >= 0 && catchAllIndex !== segments.length - 1) {
1338
- throw new NonTerminalCatchAllRouteError(
1339
- `Catch-all segment "${segments[catchAllIndex]}" must be the final segment in route "${pattern}".`
1340
- );
1341
- }
1342
- }
1343
- var _AmbiguousRouteError, AmbiguousRouteError, _NonTerminalCatchAllRouteError, NonTerminalCatchAllRouteError, _DuplicateRouteParameterError, DuplicateRouteParameterError, _ReservedRouteParameterError, ReservedRouteParameterError, _BrowserUnstableRouteError, BrowserUnstableRouteError, SEGMENT_RANK, ROUTE_END_RANK, ROUTER_PARAMETER_NAME, PAGE_PARAMETER_PATTERN, ROUTER_PARAMETER_PATTERN, RESERVED_PARAMETER_NAMES;
1344
- var init_specificity = __esm({
1345
- "src/routing/specificity.ts"() {
1346
- "use strict";
1347
- _AmbiguousRouteError = class _AmbiguousRouteError extends Error {
1348
- constructor(message) {
1349
- super(message);
1350
- this.name = "AmbiguousRouteError";
1351
- }
1352
- };
1353
- __name(_AmbiguousRouteError, "AmbiguousRouteError");
1354
- AmbiguousRouteError = _AmbiguousRouteError;
1355
- _NonTerminalCatchAllRouteError = class _NonTerminalCatchAllRouteError extends TypeError {
1356
- constructor(message) {
1357
- super(message);
1358
- this.name = "NonTerminalCatchAllRouteError";
1359
- }
1360
- };
1361
- __name(_NonTerminalCatchAllRouteError, "NonTerminalCatchAllRouteError");
1362
- NonTerminalCatchAllRouteError = _NonTerminalCatchAllRouteError;
1363
- _DuplicateRouteParameterError = class _DuplicateRouteParameterError extends AmbiguousRouteError {
1364
- constructor(message) {
1365
- super(message);
1366
- this.name = "DuplicateRouteParameterError";
1367
- }
1368
- };
1369
- __name(_DuplicateRouteParameterError, "DuplicateRouteParameterError");
1370
- DuplicateRouteParameterError = _DuplicateRouteParameterError;
1371
- _ReservedRouteParameterError = class _ReservedRouteParameterError extends AmbiguousRouteError {
1372
- constructor(message) {
1373
- super(message);
1374
- this.name = "ReservedRouteParameterError";
1375
- }
1376
- };
1377
- __name(_ReservedRouteParameterError, "ReservedRouteParameterError");
1378
- ReservedRouteParameterError = _ReservedRouteParameterError;
1379
- _BrowserUnstableRouteError = class _BrowserUnstableRouteError extends TypeError {
1380
- constructor(message) {
1381
- super(message);
1382
- this.name = "BrowserUnstableRouteError";
1383
- }
1384
- };
1385
- __name(_BrowserUnstableRouteError, "BrowserUnstableRouteError");
1386
- BrowserUnstableRouteError = _BrowserUnstableRouteError;
1387
- SEGMENT_RANK = {
1388
- static: 4,
1389
- dynamic: 3,
1390
- "catch-all": 1,
1391
- "optional-catch-all": 0
1392
- };
1393
- ROUTE_END_RANK = 2;
1394
- __name(compareRouteSpecificity, "compareRouteSpecificity");
1395
- ROUTER_PARAMETER_NAME = "[A-Za-z0-9_$-]+";
1396
- PAGE_PARAMETER_PATTERN = /^(?:\[\[\.\.\.(.+)\]\]|\[\.\.\.(.+)\]|\[(.+)\])$/;
1397
- ROUTER_PARAMETER_PATTERN = /^(?:\[\[\.\.\.([A-Za-z0-9_$-]+)\]\]|\[\.\.\.([A-Za-z0-9_$-]+)\]|\[([A-Za-z0-9_$-]+)\]|:([A-Za-z0-9_$-]+)|\*([A-Za-z0-9_$-]+)\??)$/;
1398
- RESERVED_PARAMETER_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1399
- __name(assertBrowserStableRoutePath, "assertBrowserStableRoutePath");
1400
- __name(hasControlCharacter, "hasControlCharacter");
1401
- __name(assertUniqueRouteParameters, "assertUniqueRouteParameters");
1402
- __name(splitRoutePattern, "splitRoutePattern");
1403
- __name(assertTerminalCatchAll, "assertTerminalCatchAll");
1404
- }
1405
- });
1406
-
1407
- // src/route-call-scanner.ts
1408
- var init_route_call_scanner = __esm({
1409
- "src/route-call-scanner.ts"() {
1410
- "use strict";
1411
- }
1412
- });
1413
-
1414
- // src/routes-shared.ts
1415
- function parseProgrammaticRoutePath(routePath, type = "page") {
1416
- const fileName = type === "layout" ? "layout.tsx" : "page.tsx";
1417
- const normalized = normalizeProgrammaticRoutePath(routePath);
1418
- assertTerminalCatchAll(normalized);
1419
- assertUniqueRouteParameters(normalized);
1420
- const filePath = normalized === "/" ? fileName : `${normalized.slice(1).replace(/\/+$/, "")}/${fileName}`;
1421
- return {
1422
- filePath,
1423
- segments: normalized.split("/").filter(Boolean).filter((segment) => !(segment.startsWith("(") && segment.endsWith(")"))).map(parseRouteSegment),
1424
- type
1425
- };
1426
- }
1427
- function normalizeProgrammaticRoutePath(routePath) {
1428
- if (routePath.includes("?") || routePath.includes("#")) {
1429
- throw new TypeError(
1430
- `Programmatic route path "${routePath}" must be a pathname without a query string or hash.`
1431
- );
1432
- }
1433
- const withSlash = routePath.startsWith("/") ? routePath : `/${routePath}`;
1434
- const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
1435
- assertBrowserStableRoutePath(withoutTrailing);
1436
- return withoutTrailing || "/";
1437
- }
1438
- function parseRouteSegment(segment) {
1439
- if (segment.startsWith("[") && segment.endsWith("]")) {
1440
- let name = segment.slice(1, -1);
1441
- let isOptional = false;
1442
- let isCatchAll = false;
1443
- if (name.startsWith("[") && name.endsWith("]")) {
1444
- isOptional = true;
1445
- name = name.slice(1, -1);
1446
- }
1447
- if (name.startsWith("...")) {
1448
- isCatchAll = true;
1449
- name = name.slice(3);
1450
- }
1451
- return { segment: name, isDynamic: true, isOptional, isCatchAll };
1452
- }
1453
- return { segment, isDynamic: false, isOptional: false, isCatchAll: false };
1454
- }
1455
- var init_routes_shared = __esm({
1456
- "src/routes-shared.ts"() {
1457
- "use strict";
1458
- init_specificity();
1459
- init_route_call_scanner();
1460
- __name(parseProgrammaticRoutePath, "parseProgrammaticRoutePath");
1461
- __name(normalizeProgrammaticRoutePath, "normalizeProgrammaticRoutePath");
1462
- __name(parseRouteSegment, "parseRouteSegment");
1463
- }
1464
- });
1465
-
1466
- // src/route-runtime.ts
1467
- function normalizeFarmRouteRuntimeConfig(value, source = "Route configuration") {
1468
- if (!value) return {};
1469
- const normalized = {};
1470
- if (value.runtime !== void 0) {
1471
- if (value.runtime !== "auto" && value.runtime !== "node" && value.runtime !== "edge") {
1472
- throw new TypeError(`${source} runtime must be "auto", "node", or "edge"`);
1473
- }
1474
- normalized.runtime = value.runtime;
1475
- }
1476
- if (value.regions !== void 0) {
1477
- if (value.regions === "auto") {
1478
- normalized.regions = "auto";
1479
- } else {
1480
- if (!Array.isArray(value.regions) || value.regions.length === 0) {
1481
- throw new TypeError(`${source} regions must be "auto" or a non-empty string array`);
1482
- }
1483
- const regions = Array.from(
1484
- new Set(
1485
- value.regions.map((region) => {
1486
- if (typeof region !== "string" || !region.trim() || /[\u0000-\u001f\u007f]/.test(region)) {
1487
- throw new TypeError(`${source} regions must contain non-empty region identifiers`);
1488
- }
1489
- return region.trim();
1490
- })
1491
- )
1492
- );
1493
- normalized.regions = regions;
1494
- }
1495
- }
1496
- if (value.maxDuration !== void 0) {
1497
- if (value.maxDuration === "auto") {
1498
- normalized.maxDuration = "auto";
1499
- } else if (typeof value.maxDuration !== "number" || !Number.isInteger(value.maxDuration) || value.maxDuration <= 0) {
1500
- throw new TypeError(`${source} maxDuration must be "auto" or a positive integer in seconds`);
1501
- } else {
1502
- normalized.maxDuration = value.maxDuration;
1503
- }
1504
- }
1505
- return normalized;
1506
- }
1507
- var init_route_runtime = __esm({
1508
- "src/route-runtime.ts"() {
1509
- "use strict";
1510
- __name(normalizeFarmRouteRuntimeConfig, "normalizeFarmRouteRuntimeConfig");
1511
- }
1512
- });
1513
-
1514
- // src/route-context.ts
1515
- async function resolveFarmRouteContext(config, input) {
1516
- if (typeof config.context !== "function") {
1517
- return void 0;
1518
- }
1519
- return config.context(input);
1520
- }
1521
- function withFarmRouteContext(props, context2) {
1522
- if (context2 === void 0) {
1523
- return props;
1524
- }
1525
- Object.defineProperty(props, FARM_ROUTE_CONTEXT_SYMBOL, {
1526
- value: context2,
1527
- enumerable: false,
1528
- configurable: true
1529
- });
1530
- return props;
1531
- }
1532
- function getFarmRouteContext(props) {
1533
- if (!props || typeof props !== "object") {
1534
- return void 0;
1535
- }
1536
- return props[FARM_ROUTE_CONTEXT_SYMBOL];
1537
- }
1538
- var FARM_ROUTE_CONTEXT_SYMBOL;
1539
- var init_route_context = __esm({
1540
- "src/route-context.ts"() {
1541
- "use strict";
1542
- FARM_ROUTE_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("farm.routeContext");
1543
- __name(resolveFarmRouteContext, "resolveFarmRouteContext");
1544
- __name(withFarmRouteContext, "withFarmRouteContext");
1545
- __name(getFarmRouteContext, "getFarmRouteContext");
1546
- }
1547
- });
1548
-
1549
- // src/routes.ts
1550
- function getProgrammaticRouteSearchSchema(search) {
1551
- if (!search) return void 0;
1552
- if (isProgrammaticRouteSchema(search)) return search;
1553
- return search.schema;
1554
- }
1555
- function getProgrammaticRouteSearchClientOptions(search) {
1556
- if (!search || isProgrammaticRouteSchema(search)) return void 0;
1557
- const options = {};
1558
- if (typeof search.stripDefaults !== "undefined") options.stripDefaults = search.stripDefaults;
1559
- if (search.preserve?.length) options.preserve = [...search.preserve];
1560
- if (search.temporary?.length) options.temporary = [...search.temporary];
1561
- return Object.keys(options).length > 0 ? options : void 0;
1562
- }
1563
- function resolveProgrammaticRouteSearch(searchConfig, rawSearch, path2, routePath) {
1564
- const schema = getProgrammaticRouteSearchSchema(searchConfig);
1565
- const search = parseProgrammaticSchema(schema, rawSearch, "search", routePath);
1566
- const options = getProgrammaticRouteSearchOptions(searchConfig);
1567
- const canonicalPath = resolveProgrammaticRouteCanonicalPath({
1568
- options,
1569
- schema,
1570
- rawSearch,
1571
- parsedSearch: search,
1572
- path: path2
1573
- });
1574
- return { search, canonicalPath };
1575
- }
1576
- function getProgrammaticRouteSearchOptions(search) {
1577
- if (!search || isProgrammaticRouteSchema(search)) return void 0;
1578
- return search;
1579
- }
1580
- function isProgrammaticRouteSchema(value) {
1581
- return !!value && typeof value === "object" && typeof value.parse === "function";
1582
- }
1583
- function resolveProgrammaticRouteCanonicalPath(input) {
1584
- const options = input.options;
1585
- if (!options?.temporary?.length && !options?.stripDefaults) {
1586
- return void 0;
1587
- }
1588
- const params = createSearchParams(input.rawSearch);
1589
- const original = params.toString();
1590
- for (const key of options.temporary || []) {
1591
- params.delete(key);
1592
- }
1593
- if (options.stripDefaults) {
1594
- const defaultSearch = parseDefaultSearch(input.schema);
1595
- if (defaultSearch !== void 0) {
1596
- const keys = options.stripDefaults === true ? Array.from(new Set(Array.from(params.keys()))) : [...options.stripDefaults];
1597
- for (const key of keys) {
1598
- if (params.has(key) && searchValuesEqual(
1599
- readSearchValue(input.parsedSearch, key),
1600
- readSearchValue(defaultSearch, key)
1601
- )) {
1602
- params.delete(key);
1603
- }
1604
- }
1605
- }
1606
- }
1607
- const next = params.toString();
1608
- if (next === original) {
1609
- return void 0;
1610
- }
1611
- return next ? `${input.path}?${next}` : input.path;
1612
- }
1613
- function createSearchParams(value) {
1614
- const params = new URLSearchParams();
1615
- for (const [key, item] of Object.entries(value)) {
1616
- if (item == null) continue;
1617
- const values = Array.isArray(item) ? item : [item];
1618
- for (const entry of values) {
1619
- if (entry != null) params.append(key, String(entry));
1620
- }
1621
- }
1622
- return params;
1623
- }
1624
- function parseDefaultSearch(schema) {
1625
- if (!schema) return void 0;
1626
- try {
1627
- const value = schema.parse({});
1628
- return value && typeof value === "object" ? value : void 0;
1629
- } catch {
1630
- return void 0;
1631
- }
1632
- }
1633
- function readSearchValue(value, key) {
1634
- return value && typeof value === "object" ? value[key] : void 0;
1635
- }
1636
- function searchValuesEqual(left, right) {
1637
- return JSON.stringify(normalizeComparableValue(left)) === JSON.stringify(normalizeComparableValue(right));
1638
- }
1639
- function normalizeComparableValue(value) {
1640
- if (Array.isArray(value)) {
1641
- return value.map(normalizeComparableValue);
1642
- }
1643
- if (value && typeof value === "object") {
1644
- return Object.keys(value).sort().reduce((output, key) => {
1645
- output[key] = normalizeComparableValue(value[key]);
1646
- return output;
1647
- }, {});
1648
- }
1649
- return value;
1650
- }
1651
- function parseProgrammaticRoutePath2(routePath, type = "page") {
1652
- return parseProgrammaticRoutePath(routePath, type);
1653
- }
1654
- function createRouteModuleFromProgrammaticPage(route, rendererRuntime) {
1655
- const mod = {
1656
- default: createProgrammaticPageComponent(route, rendererRuntime),
1657
- ...normalizeFarmRouteRuntimeConfig(route, `Route "${route.path}"`)
1658
- };
1659
- if (route.params || route.search || route.guard || route.data) {
1660
- mod.__farmRouteSchemas = {
1661
- params: route.params,
1662
- search: getProgrammaticRouteSearchSchema(route.search)
1663
- };
1664
- mod.__farmRouteSearch = getProgrammaticRouteSearchClientOptions(route.search);
1665
- mod.__farmRouteGuard = route.guard;
1666
- mod.__farmRouteData = route.data;
1667
- mod.__farmRouteParsesProps = true;
1668
- mod.__farmResolveRouteProps = (props) => resolveProgrammaticRouteProps(route, props);
1669
- mod.__farmResolveRouteCanonicalPath = (rawSearch, path2) => resolveProgrammaticRouteSearch(route.search, rawSearch, path2, route.path).canonicalPath;
1670
- }
1671
- if (route.pending || route.error || route.notFound) {
1672
- mod.__farmRouteComponents = {
1673
- pending: route.pending,
1674
- error: route.error,
1675
- notFound: route.notFound
1676
- };
1677
- }
1678
- if (route.render === "static" || route.staticPaths) {
1679
- mod.ssg = true;
1680
- mod.dynamic = "force-static";
1681
- } else if (route.render === "dynamic") {
1682
- mod.ssg = false;
1683
- mod.dynamic = "force-dynamic";
1684
- }
1685
- if (typeof route.revalidate !== "undefined") {
1686
- mod.revalidate = route.revalidate;
1687
- }
1688
- if (route.ppr) {
1689
- mod.ppr = true;
1690
- }
1691
- if (route.metadata) {
1692
- mod.metadata = route.metadata;
1693
- }
1694
- if (route.generateMetadata) {
1695
- mod.generateMetadata = route.generateMetadata;
1696
- }
1697
- if (route.staticPaths) {
1698
- mod.getStaticPaths = async () => normalizeStaticPaths(route.path, await route.staticPaths());
1699
- }
1700
- return mod;
1701
- }
1702
- function createProgrammaticPageComponent(route, rendererRuntime) {
1703
- if (!route.params && !route.search && !route.guard && !route.data && !route.pending && !route.error && !route.notFound) {
1704
- return route.component;
1705
- }
1706
- const createElement2 = /* @__PURE__ */ __name((...args) => {
1707
- if (!rendererRuntime) {
1708
- throw new Error(
1709
- `Programmatic route "${route.path}" requires a FARMJS renderer runtime before it can render.`
1710
- );
1711
- }
1712
- return rendererRuntime.createElement(...args);
1713
- }, "createElement");
1714
- const Component = route.component;
1715
- if (route.pending) {
1716
- const PendingComponent = route.pending;
1717
- const routePropsResources = /* @__PURE__ */ new WeakMap();
1718
- const FarmProgrammaticPageContent2 = /* @__PURE__ */ __name(function FarmProgrammaticPageContent3(props) {
1719
- try {
1720
- const resolvedProps = readProgrammaticRouteProps(route, props, routePropsResources);
1721
- return createElement2(Component, stripProgrammaticRoutePropsMarker(resolvedProps));
1722
- } catch (error) {
1723
- if (isPromiseLike(error) || isProgrammaticRedirectSignal(error)) {
1724
- throw error;
1725
- }
1726
- if (isProgrammaticNotFoundSignal(error) && route.notFound) {
1727
- return createElement2(route.notFound, createProgrammaticRouteErrorProps(error, props));
1728
- }
1729
- if (route.error) {
1730
- return createElement2(route.error, createProgrammaticRouteErrorProps(error, props));
1731
- }
1732
- throw error;
1733
- }
1734
- }, "FarmProgrammaticPageContent");
1735
- const PageContent = FarmProgrammaticPageContent2;
1736
- const FarmProgrammaticPage = /* @__PURE__ */ __name(function FarmProgrammaticPage2(props) {
1737
- return createElement2(
1738
- rendererRuntime.Suspense,
1739
- {
1740
- fallback: createElement2(PendingComponent, createProgrammaticRoutePendingProps(props))
1741
- },
1742
- createElement2(PageContent, props)
1743
- );
1744
- }, "FarmProgrammaticPage");
1745
- return FarmProgrammaticPage;
1746
- }
1747
- const FarmProgrammaticPageContent = /* @__PURE__ */ __name(async function FarmProgrammaticPageContent2(props) {
1748
- try {
1749
- const resolvedProps = isProgrammaticRoutePropsResolved(props) ? props : await resolveProgrammaticRouteProps(route, props);
1750
- return createElement2(Component, stripProgrammaticRoutePropsMarker(resolvedProps));
1751
- } catch (error) {
1752
- if (isProgrammaticRedirectSignal(error)) {
1753
- throw error;
1754
- }
1755
- if (isProgrammaticNotFoundSignal(error) && route.notFound) {
1756
- return createElement2(route.notFound, createProgrammaticRouteErrorProps(error, props));
1757
- }
1758
- if (route.error) {
1759
- return createElement2(route.error, createProgrammaticRouteErrorProps(error, props));
1760
- }
1761
- throw error;
1762
- }
1763
- }, "FarmProgrammaticPageContent");
1764
- return FarmProgrammaticPageContent;
1765
- }
1766
- function readProgrammaticRouteProps(route, props, resources) {
1767
- if (isProgrammaticRoutePropsResolved(props)) {
1768
- return props;
1769
- }
1770
- let resource = resources.get(props);
1771
- if (!resource) {
1772
- const deferredRouteProps = props.__farmRoutePropsPromise;
1773
- const promise = Promise.resolve(
1774
- isPromiseLike(deferredRouteProps) ? deferredRouteProps : resolveProgrammaticRouteProps(route, props)
1775
- );
1776
- resource = { status: "pending", promise };
1777
- resources.set(props, resource);
1778
- promise.then(
1779
- (value) => resources.set(props, { status: "resolved", value }),
1780
- (error) => resources.set(props, { status: "rejected", error })
1781
- );
1782
- }
1783
- if (resource.status === "pending") throw resource.promise;
1784
- if (resource.status === "rejected") throw resource.error;
1785
- return resource.value;
1786
- }
1787
- function isPromiseLike(value) {
1788
- return Boolean(
1789
- value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function"
1790
- );
1791
- }
1792
- function createProgrammaticRoutePendingProps(props) {
1793
- return {
1794
- params: props.params,
1795
- searchParams: props.searchParams,
1796
- path: props.path
1797
- };
1798
- }
1799
- function createProgrammaticRouteErrorProps(error, props) {
1800
- return {
1801
- error,
1802
- params: props.params,
1803
- searchParams: props.searchParams,
1804
- path: props.path
1805
- };
1806
- }
1807
- function isProgrammaticRedirectSignal(error) {
1808
- if (!error || typeof error !== "object") return false;
1809
- const digest = error.digest;
1810
- return typeof digest === "string" && digest.startsWith("FARM_REDIRECT;");
1811
- }
1812
- function isProgrammaticNotFoundSignal(error) {
1813
- if (!error || typeof error !== "object") return false;
1814
- const digest = error.digest;
1815
- return digest === "FARM_NOT_FOUND";
1816
- }
1817
- async function resolveProgrammaticRouteProps(route, props) {
1818
- const rawSearch = await props.searchParams;
1819
- const params = parseProgrammaticSchema(route.params, props.params, "params", route.path);
1820
- const { search, canonicalPath } = resolveProgrammaticRouteSearch(
1821
- route.search,
1822
- rawSearch,
1823
- props.path,
1824
- route.path
1825
- );
1826
- const routeContextValue = getFarmRouteContext(props);
1827
- const pluginContext = props.context;
1828
- const baseProps = {
1829
- ...props,
1830
- params,
1831
- search,
1832
- searchParams: Promise.resolve(search)
1833
- };
1834
- const routeContextProps = {
1835
- ...baseProps,
1836
- context: routeContextValue,
1837
- pluginContext
1838
- };
1839
- if (route.guard) {
1840
- await route.guard(routeContextProps);
1841
- }
1842
- if (!route.data) {
1843
- return markProgrammaticRoutePropsResolved(addCanonicalPath(baseProps, canonicalPath));
1844
- }
1845
- const before = route.data.before ? await route.data.before(routeContextProps) : void 0;
1846
- const dataContext = {
1847
- ...routeContextProps,
1848
- before
1849
- };
1850
- const data = await resolveProgrammaticRouteData(route, route.data, dataContext);
1851
- if (route.data.after) {
1852
- await route.data.after({
1853
- ...routeContextProps,
1854
- before,
1855
- data
1856
- });
1857
- }
1858
- return markProgrammaticRoutePropsResolved({
1859
- ...baseProps,
1860
- data,
1861
- ...canonicalPath ? { __farmCanonicalPath: canonicalPath } : {}
1862
- });
1863
- }
1864
- async function resolveProgrammaticRouteData(route, dataHooks, context2) {
1865
- if (!dataHooks?.key) {
1866
- return dataHooks.main(context2);
1867
- }
1868
- const routeDataKey = await dataHooks.key(context2);
1869
- if (routeDataKey == null) {
1870
- return dataHooks.main(context2);
1871
- }
1872
- const cacheKey = createFarmCacheKey(["route-data", routeDataKey]);
1873
- const cacheOptions = {
1874
- tags: [
1875
- createRouteDataCacheTag(routeDataKey),
1876
- ...await resolveProgrammaticRouteDataKeys(dataHooks.tags, context2)
1877
- ],
1878
- paths: [
1879
- ...typeof context2.path === "string" ? [context2.path] : [],
1880
- ...await resolveProgrammaticRouteDataKeys(dataHooks.paths, context2)
1881
- ],
1882
- revalidate: normalizeProgrammaticRouteStaleTime(dataHooks.staleTime)
1883
- };
1884
- return getFarmDataCache().getOrSet(cacheKey, () => dataHooks.main(context2), cacheOptions);
1885
- }
1886
- async function resolveProgrammaticRouteDataKeys(input, context2) {
1887
- if (!input) return [];
1888
- const value = typeof input === "function" ? await input(context2) : input;
1889
- return value.filter((item) => typeof item === "string" && item.trim().length > 0);
1890
- }
1891
- function normalizeProgrammaticRouteStaleTime(staleTime) {
1892
- if (staleTime === void 0) return void 0;
1893
- if (staleTime === false) return false;
1894
- if (typeof staleTime === "number") {
1895
- if (!Number.isFinite(staleTime) || staleTime <= 0) return void 0;
1896
- return Math.max(1, Math.ceil(staleTime / 1e3));
1897
- }
1898
- const match = staleTime.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)$/);
1899
- if (!match) return void 0;
1900
- const value = Number(match[1]);
1901
- if (!Number.isFinite(value) || value <= 0) return void 0;
1902
- const unit = match[2];
1903
- const milliseconds = unit === "ms" ? value : unit === "s" ? value * 1e3 : unit === "m" ? value * 6e4 : value * 36e5;
1904
- return Math.max(1, Math.ceil(milliseconds / 1e3));
1905
- }
1906
- function isProgrammaticRoutePropsResolved(value) {
1907
- return !!value && typeof value === "object" && value.__farmRoutePropsResolved === true;
1908
- }
1909
- function markProgrammaticRoutePropsResolved(props) {
1910
- return {
1911
- ...props,
1912
- __farmRoutePropsResolved: true
1913
- };
1914
- }
1915
- function addCanonicalPath(props, canonicalPath) {
1916
- return canonicalPath ? { ...props, __farmCanonicalPath: canonicalPath } : props;
1917
- }
1918
- function stripProgrammaticRoutePropsMarker(props) {
1919
- if (!isProgrammaticRoutePropsResolved(props)) {
1920
- return props;
1921
- }
1922
- const {
1923
- __farmRoutePropsResolved,
1924
- __farmCanonicalPath,
1925
- __farmRoutePropsPromise,
1926
- ...componentProps
1927
- } = props;
1928
- return componentProps;
1929
- }
1930
- function parseProgrammaticSchema(schema, value, label, routePath) {
1931
- if (!schema) {
1932
- return value;
1933
- }
1934
- try {
1935
- return schema.parse(value);
1936
- } catch (error) {
1937
- const message = error instanceof Error ? error.message : String(error);
1938
- throw new Error(`Invalid ${label} for route "${routePath}": ${message}`);
1939
- }
1940
- }
1941
- function normalizeProgrammaticRoute(route) {
1942
- if (route.kind === "redirect") {
1943
- return {
1944
- ...route,
1945
- source: normalizeRoutePath(route.source)
1946
- };
1947
- }
1948
- if (route.kind === "api") {
1949
- return {
1950
- ...route,
1951
- ...normalizeFarmRouteRuntimeConfig(route, `API route "${route.path}"`),
1952
- path: normalizeRoutePath(route.path),
1953
- methods: normalizeApiMethods(route.methods)
1954
- };
1955
- }
1956
- const routeActions = route.kind === "page" ? normalizeProgrammaticRouteActions(route) : void 0;
1957
- return {
1958
- ...route,
1959
- ...routeActions,
1960
- ...normalizeFarmRouteRuntimeConfig(
1961
- route,
1962
- `${route.kind === "layout" ? "Layout" : "Route"} "${route.path}"`
1963
- ),
1964
- path: normalizeRoutePath(route.path)
1965
- };
1966
- }
1967
- function normalizeProgrammaticRouteActions(route) {
1968
- const entries = Object.entries(route.actions ?? {});
1969
- if (entries.length === 0) {
1970
- if (route.defaultAction !== void 0) {
1971
- throw new TypeError(
1972
- `Route "${route.path}" declares defaultAction without declaring any actions.`
1973
- );
1974
- }
1975
- return {};
1976
- }
1977
- for (const [name, action2] of entries) {
1978
- if (typeof action2 !== "function") {
1979
- throw new TypeError(`Route "${route.path}" action "${name}" must be a server function.`);
1980
- }
1981
- }
1982
- const defaultAction = route.defaultAction ?? entries[0][0];
1983
- const actions = Object.freeze({ ...route.actions });
1984
- const action = actions[defaultAction];
1985
- if (!action) {
1986
- throw new TypeError(
1987
- `Route "${route.path}" defaultAction "${defaultAction}" does not match a declared action.`
1988
- );
1989
- }
1990
- return {
1991
- actions,
1992
- defaultAction,
1993
- action
1994
- };
1995
- }
1996
- function normalizeRoutePath(routePath) {
1997
- const withSlash = routePath.startsWith("/") ? routePath : `/${routePath}`;
1998
- const withoutTrailing = withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
1999
- return withoutTrailing || "/";
2000
- }
2001
- function normalizeApiMethods(methods) {
2002
- const normalized = {};
2003
- for (const [method, handler] of Object.entries(methods)) {
2004
- const normalizedMethod = method.toUpperCase();
2005
- if (handler && isProgrammaticRouteMethod(normalizedMethod)) {
2006
- normalized[normalizedMethod] = handler;
2007
- }
2008
- }
2009
- return normalized;
2010
- }
2011
- function isProgrammaticRouteMethod(method) {
2012
- return method === "GET" || method === "HEAD" || method === "QUERY" || method === "POST" || method === "PUT" || method === "DELETE" || method === "PATCH" || method === "OPTIONS";
2013
- }
2014
- function normalizeStaticPaths(routePath, paths) {
2015
- const dynamicSegments = parseProgrammaticRoutePath2(routePath).segments.filter(
2016
- (segment) => segment.isDynamic
2017
- );
2018
- return paths.map((entry) => {
2019
- if (typeof entry === "string" || Array.isArray(entry)) {
2020
- if (dynamicSegments.length !== 1) {
2021
- throw new Error(
2022
- `staticPaths for "${routePath}" must return objects when the route has ${dynamicSegments.length} dynamic params.`
2023
- );
2024
- }
2025
- const value = Array.isArray(entry) ? entry.join("/") : entry;
2026
- return { [dynamicSegments[0].segment]: String(value) };
2027
- }
2028
- return Object.fromEntries(
2029
- Object.entries(entry).map(([key, value]) => [
2030
- key,
2031
- Array.isArray(value) ? value.map(String).join("/") : String(value)
2032
- ])
2033
- );
2034
- });
2035
- }
2036
- var routesBuilder, page, layout, api, redirect;
2037
- var init_routes = __esm({
2038
- "src/routes.ts"() {
2039
- "use strict";
2040
- init_cache();
2041
- init_route_context();
2042
- init_route_runtime();
2043
- init_routes_shared();
2044
- init_route_call_scanner();
2045
- routesBuilder = {
2046
- page(path2, options) {
2047
- return normalizeProgrammaticRoute({
2048
- kind: "page",
2049
- path: path2,
2050
- ...options
2051
- });
2052
- },
2053
- layout(path2, options) {
2054
- return normalizeProgrammaticRoute({
2055
- kind: "layout",
2056
- path: path2,
2057
- ...options
2058
- });
2059
- },
2060
- api(path2, options) {
2061
- const { render, runtime: runtime3, regions, maxDuration, ...methods } = options;
2062
- return normalizeProgrammaticRoute({
2063
- kind: "api",
2064
- path: path2,
2065
- render,
2066
- runtime: runtime3,
2067
- regions,
2068
- maxDuration,
2069
- methods: normalizeApiMethods(methods)
2070
- });
2071
- },
2072
- redirect(source, destination, options = {}) {
2073
- return normalizeProgrammaticRoute({
2074
- kind: "redirect",
2075
- source,
2076
- destination,
2077
- ...options
2078
- });
2079
- }
2080
- };
2081
- page = routesBuilder.page;
2082
- layout = routesBuilder.layout;
2083
- api = routesBuilder.api;
2084
- redirect = routesBuilder.redirect;
2085
- __name(getProgrammaticRouteSearchSchema, "getProgrammaticRouteSearchSchema");
2086
- __name(getProgrammaticRouteSearchClientOptions, "getProgrammaticRouteSearchClientOptions");
2087
- __name(resolveProgrammaticRouteSearch, "resolveProgrammaticRouteSearch");
2088
- __name(getProgrammaticRouteSearchOptions, "getProgrammaticRouteSearchOptions");
2089
- __name(isProgrammaticRouteSchema, "isProgrammaticRouteSchema");
2090
- __name(resolveProgrammaticRouteCanonicalPath, "resolveProgrammaticRouteCanonicalPath");
2091
- __name(createSearchParams, "createSearchParams");
2092
- __name(parseDefaultSearch, "parseDefaultSearch");
2093
- __name(readSearchValue, "readSearchValue");
2094
- __name(searchValuesEqual, "searchValuesEqual");
2095
- __name(normalizeComparableValue, "normalizeComparableValue");
2096
- __name(parseProgrammaticRoutePath2, "parseProgrammaticRoutePath");
2097
- __name(createRouteModuleFromProgrammaticPage, "createRouteModuleFromProgrammaticPage");
2098
- __name(createProgrammaticPageComponent, "createProgrammaticPageComponent");
2099
- __name(readProgrammaticRouteProps, "readProgrammaticRouteProps");
2100
- __name(isPromiseLike, "isPromiseLike");
2101
- __name(createProgrammaticRoutePendingProps, "createProgrammaticRoutePendingProps");
2102
- __name(createProgrammaticRouteErrorProps, "createProgrammaticRouteErrorProps");
2103
- __name(isProgrammaticRedirectSignal, "isProgrammaticRedirectSignal");
2104
- __name(isProgrammaticNotFoundSignal, "isProgrammaticNotFoundSignal");
2105
- __name(resolveProgrammaticRouteProps, "resolveProgrammaticRouteProps");
2106
- __name(resolveProgrammaticRouteData, "resolveProgrammaticRouteData");
2107
- __name(resolveProgrammaticRouteDataKeys, "resolveProgrammaticRouteDataKeys");
2108
- __name(normalizeProgrammaticRouteStaleTime, "normalizeProgrammaticRouteStaleTime");
2109
- __name(isProgrammaticRoutePropsResolved, "isProgrammaticRoutePropsResolved");
2110
- __name(markProgrammaticRoutePropsResolved, "markProgrammaticRoutePropsResolved");
2111
- __name(addCanonicalPath, "addCanonicalPath");
2112
- __name(stripProgrammaticRoutePropsMarker, "stripProgrammaticRoutePropsMarker");
2113
- __name(parseProgrammaticSchema, "parseProgrammaticSchema");
2114
- __name(normalizeProgrammaticRoute, "normalizeProgrammaticRoute");
2115
- __name(normalizeProgrammaticRouteActions, "normalizeProgrammaticRouteActions");
2116
- __name(normalizeRoutePath, "normalizeRoutePath");
2117
- __name(normalizeApiMethods, "normalizeApiMethods");
2118
- __name(isProgrammaticRouteMethod, "isProgrammaticRouteMethod");
2119
- __name(normalizeStaticPaths, "normalizeStaticPaths");
2120
- }
2121
- });
2122
-
2123
- // src/testing.ts
2124
- var testing_exports = {};
2125
- __export(testing_exports, {
2126
- createFarmTestHarness: () => createFarmTestHarness,
2127
- createTestRequest: () => createTestRequest
2128
- });
2129
- module.exports = __toCommonJS(testing_exports);
2130
- var import_react = require("react");
2131
-
2132
- // src/api/endpoint.ts
2133
- var import_better_call = require("better-call");
2134
- init_cache();
2135
- var _EndpointFailure = class _EndpointFailure extends Error {
2136
- constructor(code, data, options) {
2137
- super(options.message);
2138
- this.name = "EndpointFailure";
2139
- this.code = code;
2140
- this.data = data;
2141
- this.status = options.status;
2142
- }
2143
- };
2144
- __name(_EndpointFailure, "EndpointFailure");
2145
- var EndpointFailure = _EndpointFailure;
2146
- function isEndpointFailure(value) {
2147
- return value instanceof EndpointFailure;
2148
- }
2149
- __name(isEndpointFailure, "isEndpointFailure");
2150
- var EMPTY_ENDPOINT_MIDDLEWARE = Object.freeze([]);
2151
- var EMPTY_ENDPOINT_CONTEXT = Object.freeze(/* @__PURE__ */ Object.create(null));
2152
-
2153
- // src/api/route.ts
2154
- init_specificity();
2155
- var unavailablePluginLocalAPI = Object.freeze({
2156
- available: false,
2157
- get() {
2158
- return void 0;
2159
- },
2160
- list() {
2161
- return [];
2162
- }
2163
- });
2164
-
2165
- // src/server/request.ts
2166
- var import_node_async_hooks = require("async_hooks");
2167
- var import_node_stream = require("stream");
2168
-
2169
- // src/server/request-bridge.ts
2170
- var CURRENT_REQUEST_RESOLVER_KEY = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
2171
- function getGlobalState() {
2172
- return globalThis;
2173
- }
2174
- __name(getGlobalState, "getGlobalState");
2175
- function _setCurrentRequestResolver(resolver) {
2176
- getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY] = resolver;
2177
- }
2178
- __name(_setCurrentRequestResolver, "_setCurrentRequestResolver");
2179
-
2180
- // src/server/request.ts
2181
- var REQUEST_STORAGE_KEY = /* @__PURE__ */ Symbol.for("@farm.js/core/request-storage");
2182
- function getRequestStore() {
2183
- const runtime3 = globalThis;
2184
- const existing = runtime3[REQUEST_STORAGE_KEY];
2185
- if (existing instanceof import_node_async_hooks.AsyncLocalStorage) {
2186
- return existing;
2187
- }
2188
- const storage = new import_node_async_hooks.AsyncLocalStorage();
2189
- runtime3[REQUEST_STORAGE_KEY] = storage;
2190
- return storage;
2191
- }
2192
- __name(getRequestStore, "getRequestStore");
2193
- var requestStore = getRequestStore();
2194
- _setCurrentRequestResolver(() => requestStore.getStore());
2195
- async function _runWithCurrentRequest(request, fn) {
2196
- return requestStore.run(request, fn);
2197
- }
2198
- __name(_runWithCurrentRequest, "_runWithCurrentRequest");
2199
-
2200
- // src/api/runtime.ts
2201
- init_cache_invalidation();
2202
-
2203
- // src/server-http.ts
2204
- init_specificity();
2205
-
2206
- // src/request-context.ts
2207
- var REQUEST_CONTEXT_STORE_KEY = /* @__PURE__ */ Symbol.for("farm.requestContextStore");
2208
- function getRequestContextStore() {
2209
- const globalState2 = globalThis;
2210
- if (!globalState2[REQUEST_CONTEXT_STORE_KEY]) {
2211
- globalState2[REQUEST_CONTEXT_STORE_KEY] = /* @__PURE__ */ new WeakMap();
2212
- }
2213
- return globalState2[REQUEST_CONTEXT_STORE_KEY];
2214
- }
2215
- __name(getRequestContextStore, "getRequestContextStore");
2216
- function getBucket(target) {
2217
- const requestContextStore = getRequestContextStore();
2218
- let bucket = requestContextStore.get(target);
2219
- if (!bucket) {
2220
- bucket = {
2221
- privateData: /* @__PURE__ */ new Map(),
2222
- exposedData: /* @__PURE__ */ new Map()
2223
- };
2224
- requestContextStore.set(target, bucket);
2225
- }
2226
- return bucket;
2227
- }
2228
- __name(getBucket, "getBucket");
2229
- function setRequestContext(target, key, value, options = {}) {
2230
- const bucket = getBucket(target);
2231
- bucket.privateData.set(key, value);
2232
- if (options.exposeToPage) {
2233
- bucket.exposedData.set(key, value);
2234
- }
2235
- }
2236
- __name(setRequestContext, "setRequestContext");
2237
- function copyRequestContext(source, target) {
2238
- const bucket = getRequestContextStore().get(source);
2239
- if (!bucket || source === target) return;
2240
- for (const [key, value] of bucket.privateData) {
2241
- setRequestContext(target, key, value, { exposeToPage: bucket.exposedData.has(key) });
2242
- }
2243
- }
2244
- __name(copyRequestContext, "copyRequestContext");
2245
-
2246
- // src/server-http.ts
2247
- var DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT = 1e7;
2248
- var _FarmRequestBodyError = class _FarmRequestBodyError extends Error {
2249
- constructor(code, status, message) {
2250
- super(message);
2251
- this.name = "FarmRequestBodyError";
2252
- this.code = code;
2253
- this.status = status;
2254
- }
2255
- };
2256
- __name(_FarmRequestBodyError, "FarmRequestBodyError");
2257
- var FarmRequestBodyError = _FarmRequestBodyError;
2258
- async function bufferFarmRequestBody(request, limit) {
2259
- if (request.method === "GET" || request.method === "HEAD" || request.body === null) {
2260
- return request;
2261
- }
2262
- const bytes = await readFarmRequestBody(request, limit);
2263
- const body = new Uint8Array(bytes.byteLength);
2264
- body.set(bytes);
2265
- const buffered = new Request(request, {
2266
- // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.
2267
- body: body.buffer
2268
- });
2269
- copyRequestContext(request, buffered);
2270
- return buffered;
2271
- }
2272
- __name(bufferFarmRequestBody, "bufferFarmRequestBody");
2273
- async function readFarmRequestBody(request, limit) {
2274
- try {
2275
- validateContentLength(request.headers.get("content-length"), limit);
2276
- } catch (error) {
2277
- void request.body?.cancel(error).catch(() => {
2278
- });
2279
- throw error;
2280
- }
2281
- throwIfAborted(request.signal);
2282
- if (!request.body) return new Uint8Array();
2283
- const reader = request.body.getReader();
2284
- const chunks = [];
2285
- let total = 0;
2286
- const cancelBodyRead = /* @__PURE__ */ __name(() => {
2287
- void reader.cancel(request.signal.reason).catch(() => {
2288
- });
2289
- }, "cancelBodyRead");
2290
- request.signal.addEventListener("abort", cancelBodyRead, { once: true });
2291
- try {
2292
- while (true) {
2293
- throwIfAborted(request.signal);
2294
- const { done, value } = await reader.read();
2295
- throwIfAborted(request.signal);
2296
- if (done) break;
2297
- if (!value) continue;
2298
- total += value.byteLength;
2299
- if (total > limit) {
2300
- const error = new FarmRequestBodyError("BODY_TOO_LARGE", 413, "Request body is too large");
2301
- void reader.cancel(error).catch(() => {
2302
- });
2303
- throw error;
2304
- }
2305
- chunks.push(value);
2306
- }
2307
- } catch (error) {
2308
- if (request.signal.aborted) throwIfAborted(request.signal);
2309
- throw error;
2310
- } finally {
2311
- request.signal.removeEventListener("abort", cancelBodyRead);
2312
- reader.releaseLock();
2313
- }
2314
- const body = new Uint8Array(total);
2315
- let offset = 0;
2316
- for (const chunk of chunks) {
2317
- body.set(chunk, offset);
2318
- offset += chunk.byteLength;
2319
- }
2320
- return body;
2321
- }
2322
- __name(readFarmRequestBody, "readFarmRequestBody");
2323
- function createFarmRequestBodyErrorResponse(error) {
2324
- if (!(error instanceof FarmRequestBodyError)) return null;
2325
- return new Response(error.status === 413 ? "Payload Too Large" : "Bad Request", {
2326
- status: error.status,
2327
- headers: {
2328
- "cache-control": "no-store",
2329
- "content-type": "text/plain; charset=utf-8",
2330
- "x-content-type-options": "nosniff"
2331
- }
2332
- });
2333
- }
2334
- __name(createFarmRequestBodyErrorResponse, "createFarmRequestBodyErrorResponse");
2335
- function validateContentLength(value, limit) {
2336
- const contentLength = value?.trim();
2337
- if (!contentLength) return;
2338
- if (!/^\d+$/.test(contentLength)) {
2339
- throw new FarmRequestBodyError("INVALID_CONTENT_LENGTH", 400, "Invalid content-length header");
2340
- }
2341
- if (Number(contentLength) > limit) {
2342
- throw new FarmRequestBodyError("BODY_TOO_LARGE", 413, "Request body is too large");
2343
- }
2344
- }
2345
- __name(validateContentLength, "validateContentLength");
2346
- function throwIfAborted(signal) {
2347
- if (!signal.aborted) return;
2348
- if (signal.reason !== void 0) throw signal.reason;
2349
- throw new DOMException("The operation was aborted", "AbortError");
2350
- }
2351
- __name(throwIfAborted, "throwIfAborted");
2352
-
2353
- // src/api/route-schema.ts
2354
- async function parseRouteSchema(schema, value) {
2355
- if (schema.parseAsync) return schema.parseAsync(value);
2356
- if (schema["~standard"]) {
2357
- const result = await schema["~standard"].validate(value);
2358
- if (result.issues)
2359
- throw Object.assign(new Error("Validation failed"), { issues: result.issues });
2360
- return result.value;
2361
- }
2362
- if (schema.parse) return schema.parse(value);
2363
- throw new TypeError("Route validators must implement Standard Schema or parse().");
2364
- }
2365
- __name(parseRouteSchema, "parseRouteSchema");
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2366
2
 
2367
- // src/response-body.ts
2368
- function omitFarmResponseBody(response) {
2369
- if (response.body) {
2370
- void response.body.cancel().catch(() => void 0);
2371
- }
2372
- return new Response(null, {
2373
- status: response.status,
2374
- statusText: response.statusText,
2375
- headers: response.headers
2376
- });
2377
- }
2378
- __name(omitFarmResponseBody, "omitFarmResponseBody");
2379
-
2380
- // src/api/route-shape.ts
2381
- init_specificity();
2382
-
2383
- // src/api/route-pattern.ts
2384
- init_specificity();
2385
- var compiledEntries = /* @__PURE__ */ new WeakMap();
2386
- function matchAPIRoute(routes, pathname) {
2387
- const exactRoute = routes.get(pathname);
2388
- if (exactRoute) return { route: exactRoute, params: {} };
2389
- const normalizedPathname = normalizePathname(pathname);
2390
- if (normalizedPathname !== pathname) {
2391
- const normalizedRoute = routes.get(normalizedPathname);
2392
- if (normalizedRoute) return { route: normalizedRoute, params: {} };
2393
- }
2394
- const pathnameSegments = getPathSegments(normalizedPathname).map(decodePathSegment);
2395
- let bestMatch = null;
2396
- let bestSpecificity = null;
2397
- for (const route of routes.values()) {
2398
- const routePath = route.path;
2399
- let entry = compiledEntries.get(route);
2400
- if (!entry || entry.path !== routePath) {
2401
- entry = compileRouteEntry(routePath);
2402
- compiledEntries.set(route, entry);
2403
- }
2404
- const params = matchRouteEntry(entry, pathnameSegments);
2405
- if (!params) continue;
2406
- if (bestSpecificity === null || compareRouteSpecificity(entry.specificity, bestSpecificity) < 0) {
2407
- bestMatch = { route, params };
2408
- bestSpecificity = entry.specificity;
2409
- }
2410
- }
2411
- return bestMatch;
2412
- }
2413
- __name(matchAPIRoute, "matchAPIRoute");
2414
- function compileRouteEntry(path2) {
2415
- const segments = getPathSegments(path2).map((segment) => {
2416
- const dynamic = parseDynamicSegment(segment);
2417
- return dynamic ? { dynamic } : { value: decodePathSegment(segment) };
2418
- });
2419
- return {
2420
- path: path2,
2421
- segments,
2422
- specificity: segments.map((segment) => {
2423
- const dynamic = segment.dynamic;
2424
- if (!dynamic) return "static";
2425
- if (!dynamic.catchAll) return "dynamic";
2426
- return dynamic.optional ? "optional-catch-all" : "catch-all";
2427
- })
2428
- };
2429
- }
2430
- __name(compileRouteEntry, "compileRouteEntry");
2431
- function matchRouteEntry(entry, pathnameSegments) {
2432
- const params = {};
2433
- let pathIndex = 0;
2434
- for (const routeSegment of entry.segments) {
2435
- const dynamicSegment = routeSegment.dynamic;
2436
- if (dynamicSegment?.catchAll) {
2437
- const remainingSegments = pathnameSegments.slice(pathIndex);
2438
- if (remainingSegments.length === 0 && !dynamicSegment.optional) {
2439
- return null;
2440
- }
2441
- if (remainingSegments.length > 0) {
2442
- params[dynamicSegment.name] = remainingSegments;
2443
- }
2444
- pathIndex = pathnameSegments.length;
2445
- continue;
2446
- }
2447
- const pathnameSegment = pathnameSegments[pathIndex];
2448
- if (pathnameSegment === void 0) {
2449
- return null;
2450
- }
2451
- if (dynamicSegment) {
2452
- params[dynamicSegment.name] = pathnameSegment;
2453
- pathIndex++;
2454
- continue;
2455
- }
2456
- if (routeSegment.value !== pathnameSegment) {
2457
- return null;
2458
- }
2459
- pathIndex++;
2460
- }
2461
- return pathIndex === pathnameSegments.length ? params : null;
2462
- }
2463
- __name(matchRouteEntry, "matchRouteEntry");
2464
- function getPathSegments(pathname) {
2465
- return normalizePathname(pathname).split("/").filter((segment) => segment.length > 0);
2466
- }
2467
- __name(getPathSegments, "getPathSegments");
2468
- function normalizePathname(pathname) {
2469
- if (pathname.length > 1 && pathname.endsWith("/")) {
2470
- return pathname.replace(/\/+$/, "");
2471
- }
2472
- return pathname;
2473
- }
2474
- __name(normalizePathname, "normalizePathname");
2475
- function parseDynamicSegment(segment) {
2476
- const optionalCatchAll = segment.match(/^\[\[\.\.\.(.+)\]\]$/);
2477
- if (optionalCatchAll?.[1]) {
2478
- return { name: optionalCatchAll[1], catchAll: true, optional: true };
2479
- }
2480
- const catchAll = segment.match(/^\[\.\.\.(.+)\]$/);
2481
- if (catchAll?.[1]) {
2482
- return { name: catchAll[1], catchAll: true, optional: false };
2483
- }
2484
- const dynamic = segment.match(/^\[(.+)\]$/);
2485
- if (dynamic?.[1]) {
2486
- return { name: dynamic[1], catchAll: false, optional: false };
2487
- }
2488
- return null;
2489
- }
2490
- __name(parseDynamicSegment, "parseDynamicSegment");
2491
- function decodePathSegment(segment) {
2492
- try {
2493
- return decodeURIComponent(segment);
2494
- } catch {
2495
- return segment;
2496
- }
2497
- }
2498
- __name(decodePathSegment, "decodePathSegment");
3
+ var _chunkXSKZORAScjs = require('./chunk-XSKZORAS.cjs');
2499
4
 
2500
- // src/api/runtime.ts
2501
- async function invokeAPIRouteEndpoint(endpoint, request, params = {}, bodySizeLimit = DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT) {
2502
- try {
2503
- request = await bufferFarmRequestBody(request, bodySizeLimit);
2504
- } catch (error) {
2505
- const response2 = createFarmRequestBodyErrorResponse(error);
2506
- if (response2) return response2;
2507
- throw error;
2508
- }
2509
- const response = await _runWithCurrentRequest(
2510
- request,
2511
- () => invokeAPIRouteEndpointInContext(endpoint, request, params)
2512
- );
2513
- if (request.method.toUpperCase() !== "HEAD") {
2514
- return response;
2515
- }
2516
- return omitFarmResponseBody(response);
2517
- }
2518
- __name(invokeAPIRouteEndpoint, "invokeAPIRouteEndpoint");
2519
- async function invokeAPIRouteEndpointInContext(endpoint, request, params) {
2520
- const queryContentTypeError = validateQueryContentType(request);
2521
- if (queryContentTypeError) {
2522
- return queryContentTypeError;
2523
- }
2524
- const farmHandler = endpoint.__handler || null;
2525
- if (!farmHandler) {
2526
- const result = await endpoint(request, {
2527
- params: Promise.resolve(params)
2528
- });
2529
- return normalizeRouteResponse(result);
2530
- }
2531
- const url = new URL(request.url);
2532
- const query = {
2533
- ...searchParamsToObject(url.searchParams)
2534
- };
2535
- let body = void 0;
2536
- if (request.method.toUpperCase() !== "GET" && request.method.toUpperCase() !== "HEAD") {
2537
- const parsedBody = await readRequestBody(request);
2538
- if (parsedBody.error) return parsedBody.error;
2539
- body = parsedBody.body;
2540
- }
2541
- const headers = Object.fromEntries(request.headers.entries());
2542
- const types = endpoint.__types || {};
2543
- const queryValidation = await validateInput(types.query, query, "Invalid query parameters");
2544
- if (queryValidation instanceof Response) {
2545
- return queryValidation;
2546
- }
2547
- const bodyValidation = await validateInput(types.body, body, "Invalid request body");
2548
- if (bodyValidation instanceof Response) {
2549
- return bodyValidation;
2550
- }
2551
- const headersValidation = await validateInput(types.headers, headers, "Invalid request headers");
2552
- if (headersValidation instanceof Response) {
2553
- return headersValidation;
2554
- }
2555
- const paramsValidation = await validateInput(types.params, params, "Invalid route parameters");
2556
- if (paramsValidation instanceof Response) return paramsValidation;
2557
- const handlerContext = {
2558
- query: queryValidation,
2559
- body: bodyValidation,
2560
- headers: headersValidation,
2561
- request,
2562
- context: {},
2563
- params: paramsValidation
2564
- };
2565
- let execution;
2566
- try {
2567
- execution = typeof endpoint.__farmInvoke === "function" ? await endpoint.__farmInvoke(handlerContext) : {
2568
- result: await farmHandler(handlerContext),
2569
- context: handlerContext.context,
2570
- handlerExecuted: true,
2571
- invalidations: []
2572
- };
2573
- } catch (error) {
2574
- if (isEndpointFailure(error)) {
2575
- return createEndpointFailureResponse(error);
2576
- }
2577
- throw error;
2578
- }
2579
- if (execution.handlerExecuted && endpoint.__output && !isWebResponse(execution.result)) {
2580
- try {
2581
- execution.result = await parseRouteSchema(endpoint.__output, execution.result);
2582
- } catch {
2583
- throw new Error("API route returned a value that does not match its output schema.");
2584
- }
2585
- }
2586
- const response = normalizeRouteResponse(execution.result);
2587
- return attachEndpointInvalidations(response, execution.invalidations);
2588
- }
2589
- __name(invokeAPIRouteEndpointInContext, "invokeAPIRouteEndpointInContext");
2590
- function validateQueryContentType(request) {
2591
- if (request.method.toUpperCase() !== "QUERY" || request.headers.has("content-type")) {
2592
- return null;
2593
- }
2594
- return new Response(
2595
- JSON.stringify({
2596
- error: "Invalid QUERY request",
2597
- message: "QUERY requests must include a Content-Type header."
2598
- }),
2599
- {
2600
- status: 400,
2601
- headers: { "Content-Type": "application/json" }
2602
- }
2603
- );
2604
- }
2605
- __name(validateQueryContentType, "validateQueryContentType");
2606
- function normalizeRouteResponse(result) {
2607
- if (isWebResponse(result)) {
2608
- return result;
2609
- }
2610
- if (result === void 0) {
2611
- return new Response(null, { status: 204 });
2612
- }
2613
- let body;
2614
- try {
2615
- body = JSON.stringify(result);
2616
- } catch (error) {
2617
- const serializationError = new TypeError(
2618
- "API route result must be a JSON-serializable value or a Response."
2619
- );
2620
- serializationError.cause = error;
2621
- throw serializationError;
2622
- }
2623
- if (body === void 0) {
2624
- throw new TypeError("API route result must be a JSON-serializable value or a Response.");
2625
- }
2626
- return new Response(body, {
2627
- status: 200,
2628
- headers: { "Content-Type": "application/json" }
2629
- });
2630
- }
2631
- __name(normalizeRouteResponse, "normalizeRouteResponse");
2632
- function isWebResponse(value) {
2633
- return value instanceof Response || typeof value === "object" && value !== null && "headers" in value && "status" in value && typeof value.arrayBuffer === "function";
2634
- }
2635
- __name(isWebResponse, "isWebResponse");
2636
- function attachEndpointInvalidations(response, keys) {
2637
- const existing = decodeFarmCacheInvalidations(
2638
- response.headers.get(FARM_CACHE_INVALIDATION_HEADER)
2639
- );
2640
- const encoded = encodeFarmCacheInvalidations([...existing, ...keys]);
2641
- if (!encoded) return response;
2642
- const headers = new Headers(response.headers);
2643
- headers.set(FARM_CACHE_INVALIDATION_HEADER, encoded);
2644
- return new Response(response.body, {
2645
- status: response.status,
2646
- statusText: response.statusText,
2647
- headers
2648
- });
2649
- }
2650
- __name(attachEndpointInvalidations, "attachEndpointInvalidations");
2651
- function createEndpointFailureResponse(failure) {
2652
- return new Response(
2653
- JSON.stringify({
2654
- error: {
2655
- code: failure.code,
2656
- message: failure.message,
2657
- data: failure.data
2658
- }
2659
- }),
2660
- {
2661
- status: failure.status,
2662
- headers: {
2663
- "cache-control": "no-store",
2664
- "content-type": "application/json"
2665
- }
2666
- }
2667
- );
2668
- }
2669
- __name(createEndpointFailureResponse, "createEndpointFailureResponse");
2670
- async function readRequestBody(request) {
2671
- const contentType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
2672
- if (contentType === "multipart/form-data") {
2673
- try {
2674
- return { body: formDataToObject(await request.clone().formData()) };
2675
- } catch {
2676
- return invalidRequestBody("The request body is not valid multipart form data.");
2677
- }
2678
- }
2679
- let text;
2680
- try {
2681
- text = await request.clone().text();
2682
- } catch {
2683
- if (contentType === "application/json" || contentType?.endsWith("+json")) {
2684
- return invalidRequestBody("The request body is not valid JSON.");
2685
- }
2686
- if (contentType === "application/x-www-form-urlencoded") {
2687
- return invalidRequestBody("The request body is not valid URL-encoded form data.");
2688
- }
2689
- return { body: void 0 };
2690
- }
2691
- if (contentType === "application/json" || contentType?.endsWith("+json")) {
2692
- if (!text && request.method.toUpperCase() === "QUERY") {
2693
- return { body: void 0 };
2694
- }
2695
- try {
2696
- return { body: JSON.parse(text) };
2697
- } catch {
2698
- return invalidRequestBody("The request body is not valid JSON.");
2699
- }
2700
- }
2701
- if (contentType === "application/x-www-form-urlencoded") {
2702
- return { body: searchParamsToObject(new URLSearchParams(text)) };
2703
- }
2704
- if (!text) return { body: void 0 };
2705
- if (contentType === void 0) {
2706
- try {
2707
- return { body: JSON.parse(text) };
2708
- } catch {
2709
- return { body: void 0 };
2710
- }
2711
- }
2712
- return { body: void 0 };
2713
- }
2714
- __name(readRequestBody, "readRequestBody");
2715
- function invalidRequestBody(message) {
2716
- return {
2717
- error: new Response(
2718
- JSON.stringify({
2719
- error: "Invalid request body",
2720
- message
2721
- }),
2722
- {
2723
- status: 400,
2724
- headers: { "Content-Type": "application/json" }
2725
- }
2726
- )
2727
- };
2728
- }
2729
- __name(invalidRequestBody, "invalidRequestBody");
2730
- function formDataToObject(formData) {
2731
- return entriesToObject(formData.entries());
2732
- }
2733
- __name(formDataToObject, "formDataToObject");
2734
- function searchParamsToObject(searchParams) {
2735
- return entriesToObject(searchParams.entries());
2736
- }
2737
- __name(searchParamsToObject, "searchParamsToObject");
2738
- function entriesToObject(entries) {
2739
- const output = /* @__PURE__ */ Object.create(null);
2740
- for (const [key, value] of entries) {
2741
- if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
2742
- const current = output[key];
2743
- if (current === void 0) {
2744
- output[key] = value;
2745
- } else if (Array.isArray(current)) {
2746
- current.push(value);
2747
- } else {
2748
- output[key] = [current, value];
2749
- }
2750
- }
2751
- return output;
2752
- }
2753
- __name(entriesToObject, "entriesToObject");
2754
- async function validateInput(schema, value, error) {
2755
- if (!schema) return value;
2756
- try {
2757
- return await parseRouteSchema(schema, value);
2758
- } catch (validationError) {
2759
- return Response.json(
2760
- {
2761
- error,
2762
- details: (validationError.issues || validationError.errors || []).map((issue) => ({
2763
- path: issue.path,
2764
- message: issue.message,
2765
- code: issue.code
2766
- }))
2767
- },
2768
- { status: 400 }
2769
- );
2770
- }
2771
- }
2772
- __name(validateInput, "validateInput");
2773
5
 
2774
- // src/utils.ts
2775
- init_specificity();
2776
6
 
2777
- // src/search-params.ts
2778
- function searchParamsToObject2(searchParams) {
2779
- const output = {};
2780
- searchParams.forEach((value, key) => {
2781
- if (key === "__proto__" || key === "constructor" || key === "prototype") return;
2782
- const existing = Object.prototype.hasOwnProperty.call(output, key) ? output[key] : void 0;
2783
- if (existing !== void 0) {
2784
- if (Array.isArray(existing)) {
2785
- existing.push(value);
2786
- } else {
2787
- output[key] = [existing, value];
2788
- }
2789
- } else {
2790
- output[key] = value;
2791
- }
2792
- });
2793
- return output;
2794
- }
2795
- __name(searchParamsToObject2, "searchParamsToObject");
7
+ var _chunkSU7MH53Pcjs = require('./chunk-SU7MH53P.cjs');
8
+ require('./chunk-PCOTGFSM.cjs');
2796
9
 
2797
- // src/utils/file-module.ts
2798
- var import_node_url = require("url");
2799
10
 
2800
- // src/api/route-manager.ts
2801
- init_routes_shared();
11
+ var _chunkT5CERMEHcjs = require('./chunk-T5CERMEH.cjs');
2802
12
 
2803
- // src/routes.server.ts
2804
- init_routes_shared();
2805
13
 
2806
- // src/api/route-manager.ts
2807
- init_route_runtime();
2808
14
 
2809
- // src/i18n/server.ts
2810
- var import_node_async_hooks2 = require("async_hooks");
2811
- init_bridge();
15
+ var _chunk6QQDAAAZcjs = require('./chunk-6QQDAAAZ.cjs');
16
+ require('./chunk-SVRTJOUF.cjs');
17
+ require('./chunk-AFOD3LYZ.cjs');
18
+ require('./chunk-IAMRBF3Z.cjs');
19
+ require('./chunk-2CQ74SP6.cjs');
20
+ require('./chunk-UJ2C4ICS.cjs');
21
+ require('./chunk-IQXFRNY2.cjs');
2812
22
 
2813
- // src/i18n/runtime.ts
2814
- var import_intl_messageformat = __toESM(require("intl-messageformat"));
2815
23
 
2816
- // src/i18n/catalog.ts
2817
- var import_promises = require("fs/promises");
2818
- var import_icu_messageformat_parser = require("@formatjs/icu-messageformat-parser");
24
+ var _chunk4PNUXIVUcjs = require('./chunk-4PNUXIVU.cjs');
25
+ require('./chunk-WPYFSQKK.cjs');
26
+ require('./chunk-I4J452B7.cjs');
27
+ require('./chunk-WMAPPDMM.cjs');
28
+ require('./chunk-TKJZFIML.cjs');
29
+ require('./chunk-6V4TDWEC.cjs');
30
+ require('./chunk-MKB2EGIR.cjs');
31
+ require('./chunk-EM6SBQKM.cjs');
32
+ require('./chunk-VQDBNVOO.cjs');
33
+ require('./chunk-HBTUGXHS.cjs');
34
+ require('./chunk-5QIKR7RR.cjs');
2819
35
 
2820
- // src/i18n/config.ts
2821
- var import_node_path = __toESM(require("path"));
2822
- var DEFAULT_FARM_I18N_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
2823
36
 
2824
- // src/i18n/server.ts
2825
- var FARM_I18N_REQUEST_STORE = /* @__PURE__ */ Symbol.for("farm.i18n.requestStore");
2826
- function getRequestStore2() {
2827
- const state = globalThis;
2828
- return state[FARM_I18N_REQUEST_STORE] ?? (state[FARM_I18N_REQUEST_STORE] = new import_node_async_hooks2.AsyncLocalStorage());
2829
- }
2830
- __name(getRequestStore2, "getRequestStore");
2831
- function getState() {
2832
- const state = getRequestStore2().getStore();
2833
- if (!state) {
2834
- throw new Error(
2835
- "No Farm i18n request context is active. Use this API while rendering, inside an API route, or use createTranslator(locale)."
2836
- );
2837
- }
2838
- return state;
2839
- }
2840
- __name(getState, "getState");
2841
- var t = createTranslatorFromState(() => getState());
2842
- function getFarmI18nClientSnapshot() {
2843
- return getRequestStore2().getStore()?.snapshot;
2844
- }
2845
- __name(getFarmI18nClientSnapshot, "getFarmI18nClientSnapshot");
2846
- function createTranslatorFromState(resolveState) {
2847
- const translator = /* @__PURE__ */ __name(((key, values) => {
2848
- const state = resolveState();
2849
- return state.runtime.translate(state.resolution.locale, key, values);
2850
- }), "translator");
2851
- translator.rich = (key, values) => {
2852
- const state = resolveState();
2853
- return state.runtime.translateRich(state.resolution.locale, key, values);
2854
- };
2855
- translator.raw = (key) => {
2856
- const state = resolveState();
2857
- return state.runtime.getRawMessage(state.resolution.locale, key);
2858
- };
2859
- translator.has = (key) => {
2860
- const state = resolveState();
2861
- return state.runtime.hasMessage(state.resolution.locale, key);
2862
- };
2863
- return translator;
2864
- }
2865
- __name(createTranslatorFromState, "createTranslatorFromState");
2866
- _setFarmI18nSnapshotResolver(() => getFarmI18nClientSnapshot());
37
+ var _chunkQNPEUFHQcjs = require('./chunk-QNPEUFHQ.cjs');
2867
38
 
2868
- // src/api/route-manager.ts
2869
- init_specificity();
2870
39
 
2871
- // src/testing.ts
2872
- init_cache();
2873
- init_route_context();
2874
- init_routes();
40
+ var _chunkG7HXGLECcjs = require('./chunk-G7HXGLEC.cjs');
41
+ require('./chunk-ARJWXNQL.cjs');
42
+ require('./chunk-S3A45T7F.cjs');
43
+ require('./chunk-75BRBIFP.cjs');
2875
44
 
2876
- // src/router.ts
2877
- init_specificity();
2878
45
 
2879
- // src/routing/matcher.ts
2880
- init_specificity();
2881
- function parseRoutePattern(pattern) {
2882
- assertBrowserStableRoutePath(pattern);
2883
- assertTerminalCatchAll(pattern, "router");
2884
- assertUniqueRouteParameters(pattern, "router");
2885
- return splitRoutePattern2(pattern).filter((part) => !isRouteGroup(part)).map((part) => {
2886
- const optionalCatchAll = part.match(/^\[\[\.\.\.([A-Za-z0-9_$-]+)\]\]$/);
2887
- if (optionalCatchAll) {
2888
- return {
2889
- type: "dynamic",
2890
- name: optionalCatchAll[1],
2891
- catchAll: true,
2892
- optional: true
2893
- };
2894
- }
2895
- const catchAll = part.match(/^\[\.\.\.([A-Za-z0-9_$-]+)\]$/);
2896
- if (catchAll) {
2897
- return {
2898
- type: "dynamic",
2899
- name: catchAll[1],
2900
- catchAll: true,
2901
- optional: false
2902
- };
2903
- }
2904
- const dynamic = part.match(/^\[([A-Za-z0-9_$-]+)\]$/) || part.match(/^:([A-Za-z0-9_$-]+)$/);
2905
- if (dynamic) {
2906
- return {
2907
- type: "dynamic",
2908
- name: dynamic[1],
2909
- catchAll: false,
2910
- optional: false
2911
- };
2912
- }
2913
- const star = part.match(/^\*([A-Za-z0-9_$-]+)(\?)?$/);
2914
- if (star) {
2915
- return {
2916
- type: "dynamic",
2917
- name: star[1],
2918
- catchAll: true,
2919
- optional: !!star[2]
2920
- };
2921
- }
2922
- return {
2923
- type: "static",
2924
- value: decodePathSegment2(part)
2925
- };
2926
- });
2927
- }
2928
- __name(parseRoutePattern, "parseRoutePattern");
2929
- function matchSegmentParts(segments, parts, allowTrailingSegments = false) {
2930
- const params = {};
2931
- if (segments.length === 0) {
2932
- return parts.length === 0 ? params : null;
2933
- }
2934
- let pathIndex = 0;
2935
- for (const segment of segments) {
2936
- if (segment.type === "static") {
2937
- if (decodePathSegment2(parts[pathIndex] || "") !== segment.value) return null;
2938
- pathIndex++;
2939
- continue;
2940
- }
2941
- if (segment.catchAll) {
2942
- const remaining = parts.slice(pathIndex).map(decodePathSegment2);
2943
- if (remaining.length === 0 && !segment.optional) return null;
2944
- params[segment.name] = remaining.join("/");
2945
- pathIndex = parts.length;
2946
- continue;
2947
- }
2948
- const value = parts[pathIndex];
2949
- if (!value) return null;
2950
- params[segment.name] = decodePathSegment2(value);
2951
- pathIndex++;
2952
- }
2953
- return allowTrailingSegments || pathIndex === parts.length ? params : null;
2954
- }
2955
- __name(matchSegmentParts, "matchSegmentParts");
2956
- function normalizePathname2(value) {
2957
- const raw = value || "/";
2958
- let pathname = raw;
2959
- try {
2960
- pathname = new URL(raw, "http://farm.local").pathname;
2961
- } catch {
2962
- pathname = raw.split(/[?#]/, 1)[0] || "/";
2963
- }
2964
- pathname = pathname.replace(/\\/g, "/").replace(/\/+/g, "/");
2965
- if (!pathname.startsWith("/")) pathname = `/${pathname}`;
2966
- if (pathname.length > 1) pathname = pathname.replace(/\/+$/, "");
2967
- return pathname || "/";
2968
- }
2969
- __name(normalizePathname2, "normalizePathname");
2970
- function splitPathname(pathname) {
2971
- return splitNormalizedPathname(normalizePathname2(pathname));
2972
- }
2973
- __name(splitPathname, "splitPathname");
2974
- function splitNormalizedPathname(pathname) {
2975
- return pathname.split("/").filter(Boolean);
2976
- }
2977
- __name(splitNormalizedPathname, "splitNormalizedPathname");
2978
- function normalizeRoutePattern(value) {
2979
- let pathname = (value || "/").replace(/\\/g, "/").replace(/\/+/g, "/");
2980
- if (!pathname.startsWith("/")) pathname = `/${pathname}`;
2981
- if (pathname.length > 1) pathname = pathname.replace(/\/+$/, "");
2982
- return pathname || "/";
2983
- }
2984
- __name(normalizeRoutePattern, "normalizeRoutePattern");
2985
- function splitRoutePattern2(pattern) {
2986
- return normalizeRoutePattern(pattern).split("/").filter(Boolean);
2987
- }
2988
- __name(splitRoutePattern2, "splitRoutePattern");
2989
- function isRouteGroup(part) {
2990
- return part.startsWith("(") && part.endsWith(")");
2991
- }
2992
- __name(isRouteGroup, "isRouteGroup");
2993
- function decodePathSegment2(value) {
2994
- try {
2995
- return decodeURIComponent(value);
2996
- } catch {
2997
- return value;
2998
- }
2999
- }
3000
- __name(decodePathSegment2, "decodePathSegment");
46
+ var _chunkH6G5INWMcjs = require('./chunk-H6G5INWM.cjs');
47
+ require('./chunk-ZEG3OPIB.cjs');
48
+ require('./chunk-LIUGYUX3.cjs');
49
+ require('./chunk-E3UK5IIB.cjs');
50
+ require('./chunk-5ZSWG4UX.cjs');
51
+ require('./chunk-US2QVW3E.cjs');
52
+ require('./chunk-U4KT7QP3.cjs');
53
+ require('./chunk-BIDYX3SL.cjs');
54
+ require('./chunk-I57LW5VZ.cjs');
55
+ require('./chunk-NO3WWW3N.cjs');
3001
56
 
3002
- // src/router.ts
3003
- function matchFarmRoute(pattern, pathname) {
3004
- return matchSegments(parseRoutePattern(pattern), normalizePathname2(pathname));
3005
- }
3006
- __name(matchFarmRoute, "matchFarmRoute");
3007
- function buildFarmRoutePath(pattern, params = {}, options = {}) {
3008
- const parts = [];
3009
- for (const segment of parseRoutePattern(pattern)) {
3010
- if (segment.type === "static") {
3011
- parts.push(encodePathSegment(segment.value));
3012
- continue;
3013
- }
3014
- const value = params[segment.name];
3015
- const values = Array.isArray(value) ? value : value == null ? [] : [value];
3016
- if (values.length === 0) {
3017
- if (segment.optional) continue;
3018
- throw new Error(`Missing route param "${segment.name}" for ${pattern}.`);
3019
- }
3020
- if (!segment.catchAll && values.length > 1) {
3021
- throw new Error(`Route param "${segment.name}" for ${pattern} expects a single value.`);
3022
- }
3023
- const encodedValues = values.map((item) => {
3024
- const value2 = String(item);
3025
- if (!value2) {
3026
- throw new Error(
3027
- `Route param "${segment.name}" for ${pattern} cannot contain an empty path segment.`
3028
- );
3029
- }
3030
- return encodePathSegment(value2);
3031
- });
3032
- parts.push(...encodedValues);
3033
- }
3034
- let pathname = parts.length ? `/${parts.join("/")}` : "/";
3035
- if (options.trailingSlash && pathname !== "/") {
3036
- pathname = `${pathname}/`;
3037
- }
3038
- return appendQueryAndHash(pathname, options);
3039
- }
3040
- __name(buildFarmRoutePath, "buildFarmRoutePath");
3041
- function matchSegments(segments, pathname, allowTrailingSegments = false) {
3042
- return matchSegmentParts(segments, splitPathname(pathname), allowTrailingSegments);
3043
- }
3044
- __name(matchSegments, "matchSegments");
3045
- function encodePathSegment(value) {
3046
- return encodeURIComponent(value);
3047
- }
3048
- __name(encodePathSegment, "encodePathSegment");
3049
- function appendQueryAndHash(pathname, options) {
3050
- const search = createSearchParams2(options.query);
3051
- const hash = options.hash ? `#${options.hash.replace(/^#/, "")}` : "";
3052
- const query = search.toString();
3053
- return `${pathname}${query ? `?${query}` : ""}${hash}`;
3054
- }
3055
- __name(appendQueryAndHash, "appendQueryAndHash");
3056
- function createSearchParams2(query) {
3057
- if (query instanceof URLSearchParams) return query;
3058
- const search = new URLSearchParams();
3059
- if (!query) return search;
3060
- for (const [key, value] of Object.entries(query)) {
3061
- const values = Array.isArray(value) ? value : [value];
3062
- for (const item of values) {
3063
- if (item == null) continue;
3064
- search.append(key, String(item));
3065
- }
3066
- }
3067
- return search;
3068
- }
3069
- __name(createSearchParams2, "createSearchParams");
3070
57
 
3071
- // src/server-action-security.ts
3072
- var import_node_async_hooks3 = require("async_hooks");
3073
- init_cache_invalidation();
3074
- var SERVER_ACTION_STORAGE_KEY = /* @__PURE__ */ Symbol.for("farm.serverActionStorage");
3075
- async function runWithServerActionRequest(request, callback) {
3076
- throwIfAborted2(request.signal);
3077
- const context2 = {
3078
- request,
3079
- signal: request.signal,
3080
- invalidations: /* @__PURE__ */ new Set(),
3081
- cacheTasks: /* @__PURE__ */ new Set()
3082
- };
3083
- return getServerActionStorage().run(context2, async () => {
3084
- try {
3085
- const result = await callback();
3086
- await Promise.all(context2.cacheTasks);
3087
- return result;
3088
- } catch (error) {
3089
- await Promise.allSettled(context2.cacheTasks);
3090
- throw error;
3091
- }
3092
- });
3093
- }
3094
- __name(runWithServerActionRequest, "runWithServerActionRequest");
3095
- function getServerActionExecutionContext() {
3096
- return getServerActionStorage().getStore();
3097
- }
3098
- __name(getServerActionExecutionContext, "getServerActionExecutionContext");
3099
- subscribeFarmCacheInvalidation((key) => {
3100
- getServerActionExecutionContext()?.invalidations.add(key);
3101
- });
3102
- subscribeFarmCacheTask((task) => {
3103
- getServerActionExecutionContext()?.cacheTasks.add(task);
3104
- });
3105
- function getServerActionStorage() {
3106
- const globalState2 = globalThis;
3107
- if (!globalState2[SERVER_ACTION_STORAGE_KEY]) {
3108
- globalState2[SERVER_ACTION_STORAGE_KEY] = new import_node_async_hooks3.AsyncLocalStorage();
3109
- }
3110
- return globalState2[SERVER_ACTION_STORAGE_KEY];
3111
- }
3112
- __name(getServerActionStorage, "getServerActionStorage");
3113
- function throwIfAborted2(signal) {
3114
- if (!signal.aborted) return;
3115
- if (signal.reason !== void 0) throw signal.reason;
3116
- throw new DOMException("The operation was aborted", "AbortError");
3117
- }
3118
- __name(throwIfAborted2, "throwIfAborted");
58
+ var _chunkS3JO3N4Hcjs = require('./chunk-S3JO3N4H.cjs');
3119
59
 
3120
60
  // src/testing.ts
3121
- function createTestRequest(path2 = "/", options = {}) {
3122
- const url = resolveTestURL(path2, options.origin);
61
+ var _react = require('react');
62
+ function createTestRequest(path = "/", options = {}) {
63
+ const url = resolveTestURL(path, options.origin);
3123
64
  applyQuery(url.searchParams, options.query);
3124
65
  const headers = new Headers(options.headers);
3125
66
  applyCookies(headers, options.cookies);
3126
67
  const { body, hasBody } = resolveRequestBody(options, headers);
3127
- const method = (options.method ?? (hasBody ? "POST" : "GET")).toUpperCase();
68
+ const method = (_nullishCoalesce(options.method, () => ( (hasBody ? "POST" : "GET")))).toUpperCase();
3128
69
  if ((method === "GET" || method === "HEAD") && body != null) {
3129
70
  throw new TypeError(`Farm test requests cannot send a body with ${method}`);
3130
71
  }
@@ -3145,14 +86,14 @@ function createTestRequest(path2 = "/", options = {}) {
3145
86
  body
3146
87
  });
3147
88
  }
3148
- __name(createTestRequest, "createTestRequest");
89
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createTestRequest, "createTestRequest");
3149
90
  function createFarmTestHarness(options = {}) {
3150
91
  const origin = normalizeOrigin(options.origin);
3151
- const request = /* @__PURE__ */ __name((path2 = "/", requestOptions = {}) => createTestRequest(path2, mergeRequestDefaults(options, origin, requestOptions)), "request");
92
+ const request = /* @__PURE__ */ _chunkS3JO3N4Hcjs.__name.call(void 0, (path = "/", requestOptions = {}) => createTestRequest(path, mergeRequestDefaults(options, origin, requestOptions)), "request");
3152
93
  return {
3153
94
  request,
3154
95
  async route(route, routeOptions = {}) {
3155
- const requestPath = routeOptions.path ?? buildFarmRoutePath(route.path, routeOptions.params ?? {});
96
+ const requestPath = _nullishCoalesce(routeOptions.path, () => ( _chunkSU7MH53Pcjs.buildFarmRoutePath.call(void 0, route.path, _nullishCoalesce(routeOptions.params, () => ( {})))));
3156
97
  const routeRequest = request(requestPath, {
3157
98
  origin: routeOptions.origin,
3158
99
  headers: routeOptions.headers,
@@ -3162,8 +103,8 @@ function createFarmTestHarness(options = {}) {
3162
103
  });
3163
104
  const url = new URL(routeRequest.url);
3164
105
  const params = resolvePageParams(route.path, url.pathname, routeOptions.params);
3165
- const search = searchParamsToObject2(url.searchParams);
3166
- const routeContext = Object.prototype.hasOwnProperty.call(routeOptions, "context") ? routeOptions.context : await resolveFarmRouteContext(
106
+ const search = _chunkQNPEUFHQcjs.searchParamsToObject.call(void 0, url.searchParams);
107
+ const routeContext = Object.prototype.hasOwnProperty.call(routeOptions, "context") ? routeOptions.context : await _chunk6QQDAAAZcjs.resolveFarmRouteContext.call(void 0,
3167
108
  { context: options.context },
3168
109
  {
3169
110
  request: routeRequest,
@@ -3172,7 +113,7 @@ function createFarmTestHarness(options = {}) {
3172
113
  path: url.pathname
3173
114
  }
3174
115
  );
3175
- const rawProps = withFarmRouteContext(
116
+ const rawProps = _chunk6QQDAAAZcjs.withFarmRouteContext.call(void 0,
3176
117
  {
3177
118
  params,
3178
119
  searchParams: Promise.resolve(search),
@@ -3182,7 +123,7 @@ function createFarmTestHarness(options = {}) {
3182
123
  },
3183
124
  routeContext
3184
125
  );
3185
- const routeModule = createRouteModuleFromProgrammaticPage(route);
126
+ const routeModule = _chunkXSKZORAScjs.createRouteModuleFromProgrammaticPage.call(void 0, route);
3186
127
  const resolveProps = routeModule.__farmResolveRouteProps;
3187
128
  const resolvedProps = resolveProps ? await resolveProps(rawProps) : { ...rawProps, search, searchParams: Promise.resolve(search) };
3188
129
  const canonicalPath = readCanonicalPath(resolvedProps);
@@ -3192,15 +133,15 @@ function createFarmTestHarness(options = {}) {
3192
133
  module: routeModule,
3193
134
  request: routeRequest,
3194
135
  props: componentProps,
3195
- element: (0, import_react.createElement)(route.component, componentProps),
136
+ element: _react.createElement.call(void 0, route.component, componentProps),
3196
137
  canonicalPath
3197
138
  };
3198
139
  },
3199
140
  async api(route, apiOptions = {}) {
3200
- const requestPath = apiOptions.path ?? buildFarmRoutePath(route.path, apiOptions.params ?? {});
3201
- const method = apiOptions.method ?? getDefaultApiMethod(route);
141
+ const requestPath = _nullishCoalesce(apiOptions.path, () => ( _chunkSU7MH53Pcjs.buildFarmRoutePath.call(void 0, route.path, _nullishCoalesce(apiOptions.params, () => ( {})))));
142
+ const method = _nullishCoalesce(apiOptions.method, () => ( getDefaultApiMethod(route)));
3202
143
  const apiRequest = request(requestPath, omitApiControlOptions({ ...apiOptions, method }));
3203
- const match = matchAPIRoute(/* @__PURE__ */ new Map([[route.path, route]]), new URL(apiRequest.url).pathname);
144
+ const match = _chunkG7HXGLECcjs.matchAPIRoute.call(void 0, /* @__PURE__ */ new Map([[route.path, route]]), new URL(apiRequest.url).pathname);
3204
145
  if (!match) {
3205
146
  return jsonErrorResponse("Not Found", 404);
3206
147
  }
@@ -3212,10 +153,10 @@ function createFarmTestHarness(options = {}) {
3212
153
  },
3213
154
  async endpoint(endpoint, endpointOptions = {}) {
3214
155
  const endpointRecord = endpoint;
3215
- const endpointPath = endpointOptions.path ?? endpointRecord.__path ?? "/__farm/test/endpoint";
156
+ const endpointPath = _nullishCoalesce(_nullishCoalesce(endpointOptions.path, () => ( endpointRecord.__path)), () => ( "/__farm/test/endpoint"));
3216
157
  const endpointRequest = request(endpointPath, {
3217
158
  ...omitEndpointControlOptions(endpointOptions),
3218
- method: endpointOptions.method ?? endpointRecord.__method ?? "GET"
159
+ method: _nullishCoalesce(_nullishCoalesce(endpointOptions.method, () => ( endpointRecord.__method)), () => ( (hasRequestBody(endpointOptions) ? "POST" : "GET")))
3219
160
  });
3220
161
  return invokeTestEndpoint(
3221
162
  endpoint,
@@ -3226,34 +167,34 @@ function createFarmTestHarness(options = {}) {
3226
167
  },
3227
168
  async serverFn(serverFn, ...args) {
3228
169
  const [input, serverFnOptions = {}] = args;
3229
- const actionRequest = serverFnOptions.request ?? request(serverFnOptions.path ?? "/__farm/test/server-fn", {
170
+ const actionRequest = _nullishCoalesce(serverFnOptions.request, () => ( request(_nullishCoalesce(serverFnOptions.path, () => ( "/__farm/test/server-fn")), {
3230
171
  origin: serverFnOptions.origin,
3231
172
  headers: serverFnOptions.headers,
3232
173
  cookies: serverFnOptions.cookies,
3233
174
  signal: serverFnOptions.signal,
3234
175
  method: "POST"
3235
- });
3236
- return await runWithServerActionRequest(actionRequest, () => serverFn(input));
176
+ })));
177
+ return await _chunkT5CERMEHcjs.runWithServerActionRequest.call(void 0, actionRequest, () => serverFn(input));
3237
178
  },
3238
179
  clearCache() {
3239
- getFarmDataCache().clear();
180
+ _chunkH6G5INWMcjs.getFarmDataCache.call(void 0, ).clear();
3240
181
  }
3241
182
  };
3242
183
  }
3243
- __name(createFarmTestHarness, "createFarmTestHarness");
3244
- function resolveTestURL(path2, origin) {
3245
- const url = path2 instanceof URL ? new URL(path2) : new URL(path2, `${normalizeOrigin(origin)}/`);
184
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createFarmTestHarness, "createFarmTestHarness");
185
+ function resolveTestURL(path, origin) {
186
+ const url = path instanceof URL ? new URL(path) : new URL(path, `${normalizeOrigin(origin)}/`);
3246
187
  if (url.protocol !== "http:" && url.protocol !== "https:") {
3247
188
  throw new TypeError(`Farm test requests require an HTTP(S) URL, received ${url.protocol}`);
3248
189
  }
3249
190
  return url;
3250
191
  }
3251
- __name(resolveTestURL, "resolveTestURL");
192
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveTestURL, "resolveTestURL");
3252
193
  function normalizeOrigin(origin = "http://farm.test") {
3253
194
  let url;
3254
195
  try {
3255
196
  url = new URL(origin);
3256
- } catch {
197
+ } catch (e) {
3257
198
  throw new TypeError(`Invalid Farm test origin: ${JSON.stringify(origin)}`);
3258
199
  }
3259
200
  if (url.protocol !== "http:" && url.protocol !== "https:") {
@@ -3261,13 +202,13 @@ function normalizeOrigin(origin = "http://farm.test") {
3261
202
  }
3262
203
  return url.origin;
3263
204
  }
3264
- __name(normalizeOrigin, "normalizeOrigin");
205
+ _chunkS3JO3N4Hcjs.__name.call(void 0, normalizeOrigin, "normalizeOrigin");
3265
206
  function mergeRequestDefaults(harnessOptions, origin, requestOptions) {
3266
207
  const headers = new Headers(harnessOptions.headers);
3267
208
  new Headers(requestOptions.headers).forEach((value, key) => headers.set(key, value));
3268
209
  return {
3269
210
  ...requestOptions,
3270
- origin: requestOptions.origin ?? origin,
211
+ origin: _nullishCoalesce(requestOptions.origin, () => ( origin)),
3271
212
  headers,
3272
213
  cookies: {
3273
214
  ...harnessOptions.cookies,
@@ -3275,7 +216,7 @@ function mergeRequestDefaults(harnessOptions, origin, requestOptions) {
3275
216
  }
3276
217
  };
3277
218
  }
3278
- __name(mergeRequestDefaults, "mergeRequestDefaults");
219
+ _chunkS3JO3N4Hcjs.__name.call(void 0, mergeRequestDefaults, "mergeRequestDefaults");
3279
220
  function applyQuery(searchParams, query) {
3280
221
  if (!query) return;
3281
222
  if (query instanceof URLSearchParams) {
@@ -3297,14 +238,14 @@ function applyQuery(searchParams, query) {
3297
238
  }
3298
239
  }
3299
240
  }
3300
- __name(applyQuery, "applyQuery");
241
+ _chunkS3JO3N4Hcjs.__name.call(void 0, applyQuery, "applyQuery");
3301
242
  function applyCookies(headers, cookies) {
3302
243
  if (!cookies || Object.keys(cookies).length === 0) return;
3303
244
  const value = Object.entries(cookies).map(([name, cookieValue]) => `${encodeURIComponent(name)}=${encodeURIComponent(cookieValue)}`).join("; ");
3304
245
  const current = headers.get("cookie");
3305
246
  headers.set("cookie", current ? `${current}; ${value}` : value);
3306
247
  }
3307
- __name(applyCookies, "applyCookies");
248
+ _chunkS3JO3N4Hcjs.__name.call(void 0, applyCookies, "applyCookies");
3308
249
  function resolveRequestBody(options, headers) {
3309
250
  const sources = [
3310
251
  options.json !== void 0,
@@ -3323,11 +264,11 @@ function resolveRequestBody(options, headers) {
3323
264
  return { body: formData, hasBody: true };
3324
265
  }
3325
266
  return {
3326
- body: options.body ?? null,
267
+ body: _nullishCoalesce(options.body, () => ( null)),
3327
268
  hasBody: options.body !== void 0
3328
269
  };
3329
270
  }
3330
- __name(resolveRequestBody, "resolveRequestBody");
271
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolveRequestBody, "resolveRequestBody");
3331
272
  function createFormData(values) {
3332
273
  const formData = new FormData();
3333
274
  for (const [key, rawValue] of Object.entries(values)) {
@@ -3336,9 +277,9 @@ function createFormData(values) {
3336
277
  }
3337
278
  return formData;
3338
279
  }
3339
- __name(createFormData, "createFormData");
280
+ _chunkS3JO3N4Hcjs.__name.call(void 0, createFormData, "createFormData");
3340
281
  function resolvePageParams(pattern, pathname, explicitParams) {
3341
- const matchedParams = matchFarmRoute(pattern, pathname);
282
+ const matchedParams = _chunkSU7MH53Pcjs.matchFarmRoute.call(void 0, pattern, pathname);
3342
283
  if (!matchedParams) {
3343
284
  throw new Error(
3344
285
  `Path ${JSON.stringify(pathname)} does not match route ${JSON.stringify(pattern)}`
@@ -3352,46 +293,49 @@ function resolvePageParams(pattern, pathname, explicitParams) {
3352
293
  ])
3353
294
  );
3354
295
  }
3355
- __name(resolvePageParams, "resolvePageParams");
296
+ _chunkS3JO3N4Hcjs.__name.call(void 0, resolvePageParams, "resolvePageParams");
3356
297
  function readCanonicalPath(props) {
3357
298
  return typeof props.__farmCanonicalPath === "string" ? props.__farmCanonicalPath : void 0;
3358
299
  }
3359
- __name(readCanonicalPath, "readCanonicalPath");
300
+ _chunkS3JO3N4Hcjs.__name.call(void 0, readCanonicalPath, "readCanonicalPath");
3360
301
  function stripInternalRouteProps(props) {
3361
302
  const { __farmRoutePropsResolved, __farmCanonicalPath, ...componentProps } = props;
3362
303
  return componentProps;
3363
304
  }
3364
- __name(stripInternalRouteProps, "stripInternalRouteProps");
305
+ _chunkS3JO3N4Hcjs.__name.call(void 0, stripInternalRouteProps, "stripInternalRouteProps");
306
+ function hasRequestBody(options) {
307
+ return options.json !== void 0 || options.form !== void 0 || options.body != null;
308
+ }
309
+ _chunkS3JO3N4Hcjs.__name.call(void 0, hasRequestBody, "hasRequestBody");
3365
310
  function getDefaultApiMethod(route) {
3366
311
  if (route.methods.GET) return "GET";
3367
- return Object.keys(route.methods)[0] ?? "GET";
312
+ return _nullishCoalesce(Object.keys(route.methods)[0], () => ( "GET"));
3368
313
  }
3369
- __name(getDefaultApiMethod, "getDefaultApiMethod");
314
+ _chunkS3JO3N4Hcjs.__name.call(void 0, getDefaultApiMethod, "getDefaultApiMethod");
3370
315
  function omitApiControlOptions(options) {
3371
316
  const { path: _path, params: _params, throwOnError: _throwOnError, ...requestOptions } = options;
3372
317
  return requestOptions;
3373
318
  }
3374
- __name(omitApiControlOptions, "omitApiControlOptions");
319
+ _chunkS3JO3N4Hcjs.__name.call(void 0, omitApiControlOptions, "omitApiControlOptions");
3375
320
  function omitEndpointControlOptions(options) {
3376
321
  const { path: _path, params: _params, throwOnError: _throwOnError, ...requestOptions } = options;
3377
322
  return requestOptions;
3378
323
  }
3379
- __name(omitEndpointControlOptions, "omitEndpointControlOptions");
324
+ _chunkS3JO3N4Hcjs.__name.call(void 0, omitEndpointControlOptions, "omitEndpointControlOptions");
3380
325
  async function invokeTestEndpoint(endpoint, request, params = {}, throwOnError = false) {
3381
326
  try {
3382
- return await invokeAPIRouteEndpoint(endpoint, request, params);
327
+ return await _chunk4PNUXIVUcjs.invokeAPIRouteEndpoint.call(void 0, endpoint, request, params);
3383
328
  } catch (error) {
3384
329
  if (throwOnError) throw error;
3385
330
  return jsonErrorResponse(error instanceof Error ? error.message : "Internal Server Error", 500);
3386
331
  }
3387
332
  }
3388
- __name(invokeTestEndpoint, "invokeTestEndpoint");
333
+ _chunkS3JO3N4Hcjs.__name.call(void 0, invokeTestEndpoint, "invokeTestEndpoint");
3389
334
  function jsonErrorResponse(error, status) {
3390
335
  return Response.json({ error }, { status });
3391
336
  }
3392
- __name(jsonErrorResponse, "jsonErrorResponse");
3393
- // Annotate the CommonJS export names for ESM import in node:
3394
- 0 && (module.exports = {
3395
- createFarmTestHarness,
3396
- createTestRequest
3397
- });
337
+ _chunkS3JO3N4Hcjs.__name.call(void 0, jsonErrorResponse, "jsonErrorResponse");
338
+
339
+
340
+
341
+ exports.createFarmTestHarness = createFarmTestHarness; exports.createTestRequest = createTestRequest;