@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
@@ -1,2684 +1,53 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
20
2
 
21
- // src/api/runtime.ts
22
- var runtime_exports = {};
23
- __export(runtime_exports, {
24
- API_ROUTE_METHODS: () => API_ROUTE_METHODS,
25
- createEndpointFailureResponse: () => createEndpointFailureResponse,
26
- createStaticAPIRouteMatcherAtBasePath: () => createStaticAPIRouteMatcherAtBasePath,
27
- getAllowedAPIRouteMethods: () => getAllowedAPIRouteMethods,
28
- invokeAPIRouteEndpoint: () => invokeAPIRouteEndpoint,
29
- isFarmAPIPathname: () => isFarmAPIPathname,
30
- isWebResponse: () => isWebResponse,
31
- matchAPIRoute: () => matchAPIRoute,
32
- matchAPIRouteAtBasePath: () => matchAPIRouteAtBasePath,
33
- mergePluginAPIRoutes: () => mergePluginAPIRoutes,
34
- normalizeRouteResponse: () => normalizeRouteResponse,
35
- parseRouteSchema: () => parseRouteSchema,
36
- registerAPIRouteShape: () => registerAPIRouteShape,
37
- resolveAPIRouteEndpoint: () => resolveAPIRouteEndpoint
38
- });
39
- module.exports = __toCommonJS(runtime_exports);
40
3
 
41
- // src/server/request.ts
42
- var import_node_async_hooks = require("async_hooks");
43
- var import_node_stream = require("stream");
44
4
 
45
- // src/server/request-bridge.ts
46
- var CURRENT_REQUEST_RESOLVER_KEY = /* @__PURE__ */ Symbol.for("farm.currentRequestResolver");
47
- function getGlobalState() {
48
- return globalThis;
49
- }
50
- __name(getGlobalState, "getGlobalState");
51
- function _setCurrentRequestResolver(resolver) {
52
- getGlobalState()[CURRENT_REQUEST_RESOLVER_KEY] = resolver;
53
- }
54
- __name(_setCurrentRequestResolver, "_setCurrentRequestResolver");
55
5
 
56
- // src/server/request.ts
57
- var REQUEST_STORAGE_KEY = /* @__PURE__ */ Symbol.for("@farm.js/core/request-storage");
58
- function getRequestStore() {
59
- const runtime3 = globalThis;
60
- const existing = runtime3[REQUEST_STORAGE_KEY];
61
- if (existing instanceof import_node_async_hooks.AsyncLocalStorage) {
62
- return existing;
63
- }
64
- const storage = new import_node_async_hooks.AsyncLocalStorage();
65
- runtime3[REQUEST_STORAGE_KEY] = storage;
66
- return storage;
67
- }
68
- __name(getRequestStore, "getRequestStore");
69
- var requestStore = getRequestStore();
70
- _setCurrentRequestResolver(() => requestStore.getStore());
71
- async function _runWithCurrentRequest(request, fn) {
72
- return requestStore.run(request, fn);
73
- }
74
- __name(_runWithCurrentRequest, "_runWithCurrentRequest");
75
6
 
76
- // src/cache-invalidation.ts
77
- var FARM_CACHE_INVALIDATION_HEADER = "x-farm-cache-invalidations";
78
- var FARM_CACHE_INVALIDATION_STATE = /* @__PURE__ */ Symbol.for("farm.cacheInvalidationState");
79
- var globalState = globalThis;
80
- function getFarmCacheInvalidationState() {
81
- return globalState[FARM_CACHE_INVALIDATION_STATE] ?? (globalState[FARM_CACHE_INVALIDATION_STATE] = {
82
- listeners: /* @__PURE__ */ new Set(),
83
- taskListeners: /* @__PURE__ */ new Set()
84
- });
85
- }
86
- __name(getFarmCacheInvalidationState, "getFarmCacheInvalidationState");
87
- function warnFarmCacheListenerError(scope, error) {
88
- const detail = error instanceof Error ? error.stack ?? error.message : String(error);
89
- console.warn(`[farm:cache] ${scope} listener failed: ${detail}`);
90
- }
91
- __name(warnFarmCacheListenerError, "warnFarmCacheListenerError");
92
- function notifyFarmCacheInvalidation(key, source = "local") {
93
- if (typeof key !== "string" || key.length === 0) return;
94
- for (const listener of getFarmCacheInvalidationState().listeners) {
95
- try {
96
- listener(key, source);
97
- } catch (error) {
98
- warnFarmCacheListenerError("invalidation", error);
99
- }
100
- }
101
- }
102
- __name(notifyFarmCacheInvalidation, "notifyFarmCacheInvalidation");
103
- function notifyFarmCacheTask(task) {
104
- for (const listener of getFarmCacheInvalidationState().taskListeners) {
105
- try {
106
- listener(task);
107
- } catch (error) {
108
- warnFarmCacheListenerError("task", error);
109
- }
110
- }
111
- }
112
- __name(notifyFarmCacheTask, "notifyFarmCacheTask");
113
- function encodeFarmCacheInvalidations(keys) {
114
- const normalized = Array.from(
115
- new Set(keys.filter((key) => typeof key === "string" && key.length > 0))
116
- );
117
- if (normalized.length === 0) return null;
118
- return encodeURIComponent(JSON.stringify(normalized));
119
- }
120
- __name(encodeFarmCacheInvalidations, "encodeFarmCacheInvalidations");
121
- function decodeFarmCacheInvalidations(value) {
122
- if (!value) return [];
123
- try {
124
- const parsed = JSON.parse(decodeURIComponent(value));
125
- return Array.isArray(parsed) ? Array.from(
126
- new Set(parsed.filter((key) => typeof key === "string" && key.length > 0))
127
- ) : [];
128
- } catch {
129
- return [];
130
- }
131
- }
132
- __name(decodeFarmCacheInvalidations, "decodeFarmCacheInvalidations");
133
7
 
134
- // src/api/endpoint.ts
135
- var import_better_call = require("better-call");
136
8
 
137
- // src/tracing.ts
138
- var import_api = require("@opentelemetry/api");
139
- var FARM_TRACER_NAME = "@farm.js/core";
140
- var ALL_SPAN_KINDS = [
141
- "request",
142
- "render",
143
- "middleware",
144
- "api",
145
- "integration",
146
- "storage",
147
- "ppr",
148
- "build",
149
- "plugin"
150
- ];
151
- var DEFAULT_IGNORED_PATHS = [
152
- "/@vite/",
153
- "/@fs/",
154
- "/@id/",
155
- "/@react-refresh",
156
- "/node_modules/",
157
- "/__vite",
158
- "/.well-known/appspecific/"
159
- ];
160
- var FARM_REQUEST_METHOD_CONTEXT_KEY = (0, import_api.createContextKey)("@farm.js/core/request-method");
161
- var TRACING_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/tracing-runtime/v1");
162
- var runtime = globalThis;
163
- var tracingState = runtime[TRACING_RUNTIME] ?? (runtime[TRACING_RUNTIME] = normalizeFarmTracingConfig(false));
164
- function normalizeFarmTracingConfig(config) {
165
- if (!config) {
166
- return {
167
- enabled: false,
168
- spans: new Set(ALL_SPAN_KINDS),
169
- recordEvents: true,
170
- attributes: {},
171
- ignorePaths: DEFAULT_IGNORED_PATHS
172
- };
173
- }
174
- if (config === true) {
175
- return {
176
- enabled: true,
177
- spans: new Set(ALL_SPAN_KINDS),
178
- recordEvents: true,
179
- attributes: {},
180
- ignorePaths: DEFAULT_IGNORED_PATHS
181
- };
182
- }
183
- return {
184
- enabled: config.enabled ?? true,
185
- spans: new Set(config.spans ?? ALL_SPAN_KINDS),
186
- recordEvents: config.recordEvents ?? true,
187
- attributes: { ...config.attributes },
188
- ignorePaths: [...DEFAULT_IGNORED_PATHS, ...config.ignorePaths ?? []]
189
- };
190
- }
191
- __name(normalizeFarmTracingConfig, "normalizeFarmTracingConfig");
192
- function recordFarmEventTrace(event) {
193
- if (!tracingState.enabled) return void 0;
194
- const activeContext = import_api.context.active();
195
- const activeSpan = import_api.trace.getSpan(activeContext);
196
- const traceContext = getSpanTraceContext(activeSpan);
197
- if (activeSpan && traceContext) {
198
- if (event.type === "route.matched") {
199
- const method = activeContext.getValue(FARM_REQUEST_METHOD_CONTEXT_KEY) ?? "HTTP";
200
- activeSpan.updateName(`${method} ${event.route}`);
201
- activeSpan.setAttribute("http.route", event.route);
202
- activeSpan.setAttribute("farm.route", event.route);
203
- }
204
- if (tracingState.recordEvents) {
205
- activeSpan.addEvent(event.type, toEventAttributes(event), event.timestamp);
206
- }
207
- const error = event.type === "request.error" ? void 0 : getEventError(event);
208
- if (error !== void 0) {
209
- if (event.type === "render.error") {
210
- recordSpanException(activeSpan, error);
211
- } else {
212
- recordSpanError(activeSpan, error);
213
- }
214
- }
215
- }
216
- const completedTraceContext = recordCompletedEventSpan(event, activeContext);
217
- return traceContext ?? completedTraceContext;
218
- }
219
- __name(recordFarmEventTrace, "recordFarmEventTrace");
220
- function recordCompletedEventSpan(event, parentContext) {
221
- const descriptor = getCompletedSpanDescriptor(event);
222
- if (!descriptor || !tracingState.spans.has(descriptor.kind)) return void 0;
223
- const tracer = import_api.trace.getTracer(FARM_TRACER_NAME);
224
- const span = tracer.startSpan(
225
- descriptor.name,
226
- {
227
- kind: import_api.SpanKind.INTERNAL,
228
- startTime: event.timestamp - descriptor.durationMs,
229
- attributes: {
230
- ...tracingState.attributes,
231
- ...toEventAttributes(event),
232
- "farm.event.type": event.type
233
- }
234
- },
235
- parentContext
236
- );
237
- const status = "status" in event && typeof event.status === "number" ? event.status : void 0;
238
- if (status !== void 0) setResponseStatus(span, status);
239
- const error = getEventError(event);
240
- if (error !== void 0) recordSpanError(span, error);
241
- const traceContext = getSpanTraceContext(span);
242
- span.end(event.timestamp);
243
- return traceContext;
244
- }
245
- __name(recordCompletedEventSpan, "recordCompletedEventSpan");
246
- function getCompletedSpanDescriptor(event) {
247
- if (!("durationMs" in event) || typeof event.durationMs !== "number") return void 0;
248
- switch (event.type) {
249
- case "render.complete":
250
- return { kind: "render", name: `farm.render ${event.route}`, durationMs: event.durationMs };
251
- case "render.stream.shellReady":
252
- return {
253
- kind: "render",
254
- name: `farm.render.shell ${event.route}`,
255
- durationMs: event.durationMs
256
- };
257
- case "render.stream.complete":
258
- return {
259
- kind: "render",
260
- name: `farm.render.stream ${event.route}`,
261
- durationMs: event.durationMs
262
- };
263
- case "middleware.complete":
264
- return {
265
- kind: "middleware",
266
- name: `farm.middleware ${event.name ?? event.route ?? "anonymous"}`,
267
- durationMs: event.durationMs
268
- };
269
- case "api.request.complete":
270
- case "api.error":
271
- return {
272
- kind: "api",
273
- name: `farm.api ${event.method} ${event.route}`,
274
- durationMs: event.durationMs
275
- };
276
- case "integration.api.call.complete":
277
- return {
278
- kind: "integration",
279
- name: `farm.integration ${event.integration}.${event.operation}`,
280
- durationMs: event.durationMs
281
- };
282
- case "storage.query.complete":
283
- return {
284
- kind: "storage",
285
- name: `farm.storage ${event.operation}`,
286
- durationMs: event.durationMs
287
- };
288
- case "ppr.refresh.complete":
289
- return {
290
- kind: "ppr",
291
- name: `farm.ppr.refresh ${event.route}`,
292
- durationMs: event.durationMs
293
- };
294
- case "build.complete":
295
- return {
296
- kind: "build",
297
- name: `farm.build${event.target ? ` ${event.target}` : ""}`,
298
- durationMs: event.durationMs
299
- };
300
- case "plugin.hook.complete":
301
- return {
302
- kind: "plugin",
303
- name: `farm.plugin ${event.plugin}.${event.hook}`,
304
- durationMs: event.durationMs
305
- };
306
- default:
307
- return void 0;
308
- }
309
- }
310
- __name(getCompletedSpanDescriptor, "getCompletedSpanDescriptor");
311
- function hashFarmCacheKey(value) {
312
- let hash = 2166136261;
313
- for (let index = 0; index < value.length; index++) {
314
- hash ^= value.charCodeAt(index);
315
- hash = Math.imul(hash, 16777619);
316
- }
317
- return (hash >>> 0).toString(16).padStart(8, "0");
318
- }
319
- __name(hashFarmCacheKey, "hashFarmCacheKey");
320
- function toEventAttributes(event) {
321
- const attributes = {};
322
- const redactKey = typeof event.type === "string" && event.type.startsWith("cache.");
323
- for (const [key, value] of Object.entries(event)) {
324
- if (key === "timestamp" || key === "level" || key === "error" || key === "traceId" || key === "spanId" || key === "traceSampled" || value === void 0) {
325
- continue;
326
- }
327
- if (redactKey && key === "key" && typeof value === "string") {
328
- attributes["farm.key_hash"] = hashFarmCacheKey(value);
329
- continue;
330
- }
331
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
332
- attributes[`farm.${key}`] = value;
333
- } else if (Array.isArray(value)) {
334
- if (value.every((entry) => typeof entry === "string")) {
335
- attributes[`farm.${key}`] = value;
336
- } else if (value.every((entry) => typeof entry === "number")) {
337
- attributes[`farm.${key}`] = value;
338
- } else if (value.every((entry) => typeof entry === "boolean")) {
339
- attributes[`farm.${key}`] = value;
340
- }
341
- }
342
- }
343
- return attributes;
344
- }
345
- __name(toEventAttributes, "toEventAttributes");
346
- function getEventError(event) {
347
- return "error" in event ? event.error : void 0;
348
- }
349
- __name(getEventError, "getEventError");
350
- function recordSpanException(span, error) {
351
- const normalized = error instanceof Error ? error : new Error(String(error));
352
- span.recordException(normalized);
353
- return normalized;
354
- }
355
- __name(recordSpanException, "recordSpanException");
356
- function recordSpanError(span, error) {
357
- const normalized = recordSpanException(span, error);
358
- span.setStatus({ code: import_api.SpanStatusCode.ERROR, message: normalized.message });
359
- }
360
- __name(recordSpanError, "recordSpanError");
361
- function setResponseStatus(span, status) {
362
- span.setAttribute("http.response.status_code", status);
363
- if (status >= 500) {
364
- span.setStatus({ code: import_api.SpanStatusCode.ERROR });
365
- }
366
- }
367
- __name(setResponseStatus, "setResponseStatus");
368
- function getSpanTraceContext(span) {
369
- if (!span) return void 0;
370
- const spanContext = span.spanContext();
371
- if (!(0, import_api.isSpanContextValid)(spanContext)) return void 0;
372
- return {
373
- traceId: spanContext.traceId,
374
- spanId: spanContext.spanId,
375
- traceSampled: (spanContext.traceFlags & 1) === 1
376
- };
377
- }
378
- __name(getSpanTraceContext, "getSpanTraceContext");
379
9
 
380
- // src/observability.ts
381
- var OBSERVABILITY_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/observability-runtime/v1");
382
- var runtime2 = globalThis;
383
- var shared = runtime2[OBSERVABILITY_RUNTIME] ?? (runtime2[OBSERVABILITY_RUNTIME] = {
384
- handlers: /* @__PURE__ */ new Set(),
385
- unfilteredHandlers: /* @__PURE__ */ new Set(),
386
- config: { logs: false, handlers: [], tracing: normalizeFarmTracingConfig(false) }
387
- });
388
- var runtimeHandlers = shared.handlers;
389
- var unfilteredRuntimeHandlers = shared.unfilteredHandlers;
390
- var observabilityState = shared.config;
391
- function emitFarmEvent(input) {
392
- const event = {
393
- timestamp: Date.now(),
394
- level: inferFarmEventLevel(input.type),
395
- ...input
396
- };
397
- const traceContext = recordFarmEventTrace(event);
398
- if (traceContext) {
399
- event.traceId = traceContext.traceId;
400
- event.spanId = traceContext.spanId;
401
- event.traceSampled = traceContext.traceSampled;
402
- }
403
- notifyFarmEventHandlers(event, unfilteredRuntimeHandlers);
404
- if (!shouldEmitFarmEvent(event)) return event;
405
- if (observabilityState.logs) {
406
- logFarmEvent(event);
407
- }
408
- notifyFarmEventHandlers(event, [...observabilityState.handlers, ...runtimeHandlers]);
409
- return event;
410
- }
411
- __name(emitFarmEvent, "emitFarmEvent");
412
- function notifyFarmEventHandlers(event, handlers) {
413
- for (const handler of handlers) {
414
- try {
415
- Promise.resolve(handler(event)).catch((error) => {
416
- console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
417
- });
418
- } catch (error) {
419
- console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
420
- }
421
- }
422
- }
423
- __name(notifyFarmEventHandlers, "notifyFarmEventHandlers");
424
- function shouldEmitFarmEvent(event) {
425
- if (!observabilityState.logs && observabilityState.handlers.length === 0 && runtimeHandlers.size === 0) {
426
- return false;
427
- }
428
- if (observabilityState.events && !observabilityState.events.has(event.type)) {
429
- return false;
430
- }
431
- return true;
432
- }
433
- __name(shouldEmitFarmEvent, "shouldEmitFarmEvent");
434
- function inferFarmEventLevel(type) {
435
- if (type === "error" || type.endsWith(".error") || type.endsWith(".failed")) {
436
- return "error";
437
- }
438
- if (type.endsWith(".bypass") || type.endsWith(".invalidated") || type.endsWith(".stale") || type.endsWith(".notFound")) {
439
- return "warn";
440
- }
441
- if (type.endsWith(".hit") || type.endsWith(".miss") || type.endsWith(".start") || type.endsWith(".shellReady")) {
442
- return "debug";
443
- }
444
- return "info";
445
- }
446
- __name(inferFarmEventLevel, "inferFarmEventLevel");
447
- function logFarmEvent(event) {
448
- const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;
449
- switch (event.level) {
450
- case "error":
451
- console.error(message);
452
- break;
453
- case "warn":
454
- console.warn(message);
455
- break;
456
- default:
457
- console.log(message);
458
- break;
459
- }
460
- }
461
- __name(logFarmEvent, "logFarmEvent");
462
- function formatFarmEventDetails(event) {
463
- const details = [];
464
- const record = event;
465
- for (const key of [
466
- "route",
467
- "pathname",
468
- "method",
469
- "status",
470
- "key",
471
- "tag",
472
- "path",
473
- "reason",
474
- "durationMs",
475
- "integration",
476
- "server",
477
- "tool",
478
- "outcome",
479
- "operation",
480
- "plugin",
481
- "hook",
482
- "target",
483
- "count"
484
- ]) {
485
- const value = record[key];
486
- if (value !== void 0) {
487
- details.push(`${key}=${formatDetailValue(value)}`);
488
- }
489
- }
490
- return details.length > 0 ? ` ${details.join(" ")}` : "";
491
- }
492
- __name(formatFarmEventDetails, "formatFarmEventDetails");
493
- function formatDetailValue(value) {
494
- if (typeof value === "string") {
495
- return value;
496
- }
497
- if (typeof value === "number" || typeof value === "boolean") {
498
- return String(value);
499
- }
500
- try {
501
- return JSON.stringify(value);
502
- } catch {
503
- return String(value);
504
- }
505
- }
506
- __name(formatDetailValue, "formatDetailValue");
507
- function formatError(error) {
508
- return error instanceof Error ? error.message : String(error);
509
- }
510
- __name(formatError, "formatError");
511
10
 
512
- // src/cache-invalidation-stream.ts
513
- var MAX_BUFFERED_BYTES = 64 * 1024;
514
- var textEncoder = new TextEncoder();
515
11
 
516
- // src/cache.ts
517
- var _FarmDataCache = class _FarmDataCache {
518
- constructor(config = {}) {
519
- this.entries = /* @__PURE__ */ new Map();
520
- this.inflight = /* @__PURE__ */ new Map();
521
- this.invalidatedTagVersions = /* @__PURE__ */ new Map();
522
- this.activeGenerations = /* @__PURE__ */ new Set();
523
- this.version = 0;
524
- this.generation = 0;
525
- this.namespace = "farm";
526
- this.local = true;
527
- this.maxEntries = 1024;
528
- this.lease = {
529
- enabled: true,
530
- ttlMs: 1e4,
531
- waitTimeoutMs: 1e4,
532
- pollIntervalMs: 25
533
- };
534
- this.configure(config);
535
- }
536
- configure(config = {}) {
537
- this.generation++;
538
- this.entries.clear();
539
- this.inflight.clear();
540
- this.invalidatedTagVersions.clear();
541
- this.activeGenerations.clear();
542
- this.version = 0;
543
- this.adapter = config.adapter;
544
- this.namespace = normalizeCacheNamespace(config.namespace || "farm");
545
- this.local = !config.adapter;
546
- this.maxEntries = normalizePositiveInteger(config.maxEntries, 1024, "cache.maxEntries");
547
- this.lease = config.lease === false ? { ...this.lease, enabled: false } : {
548
- enabled: true,
549
- ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 1e4, "cache.lease.ttlMs"),
550
- waitTimeoutMs: normalizePositiveDuration(
551
- config.lease?.waitTimeoutMs,
552
- 1e4,
553
- "cache.lease.waitTimeoutMs"
554
- ),
555
- pollIntervalMs: normalizePositiveDuration(
556
- config.lease?.pollIntervalMs,
557
- 25,
558
- "cache.lease.pollIntervalMs"
559
- )
560
- };
561
- }
562
- get adapterName() {
563
- return this.adapter?.name || (this.adapter ? "custom" : "memory");
564
- }
565
- get hasAdapter() {
566
- return this.adapter !== void 0;
567
- }
568
- get size() {
569
- return this.entries.size;
570
- }
571
- get(key, options = {}) {
572
- return this.getEntry(key, options)?.value;
573
- }
574
- getEntry(key, options = {}) {
575
- const entry = this.entries.get(key);
576
- if (!entry) {
577
- emitFarmEvent({ type: "cache.miss", key });
578
- return void 0;
579
- }
580
- const stale = this.isStale(entry, options.now);
581
- if (stale) {
582
- emitFarmEvent({
583
- type: "cache.stale",
584
- key,
585
- tags: Array.from(entry.tags),
586
- revalidate: entry.revalidate
587
- });
588
- }
589
- if (!options.allowStale && stale) {
590
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
591
- return void 0;
592
- }
593
- this.touchEntry(key, entry);
594
- emitFarmEvent({
595
- type: "cache.hit",
596
- key,
597
- tags: Array.from(entry.tags),
598
- revalidate: entry.revalidate,
599
- stale
600
- });
601
- return this.toPublicEntry(entry);
602
- }
603
- async getEntryAsync(key, options = {}) {
604
- if (this.local) {
605
- const localEntry = this.getEntry(key, options);
606
- if (localEntry) return localEntry;
607
- }
608
- if (!this.adapter) {
609
- return this.local ? void 0 : this.getEntry(key, options);
610
- }
611
- const generation = this.generation;
612
- const adapter = this.adapter;
613
- const namespace = this.namespace;
614
- const entry = await adapter.get(`${namespace}:entry:${key}`);
615
- if (generation !== this.generation) return void 0;
616
- if (!entry) {
617
- emitFarmEvent({ type: "cache.miss", key });
618
- return void 0;
619
- }
620
- assertFarmCacheEntry(entry, key);
621
- const stale = await this.isAdapterEntryStale(entry, options.now, adapter, namespace);
622
- if (generation !== this.generation) return void 0;
623
- if (stale) {
624
- emitFarmEvent({
625
- type: "cache.stale",
626
- key,
627
- tags: [...entry.tags],
628
- revalidate: entry.revalidate
629
- });
630
- if (!options.allowStale) {
631
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
632
- return void 0;
633
- }
634
- }
635
- emitFarmEvent({
636
- type: "cache.hit",
637
- key,
638
- tags: [...entry.tags],
639
- revalidate: entry.revalidate,
640
- stale
641
- });
642
- if (this.local && !stale) {
643
- this.hydrateLocalEntry(entry);
644
- }
645
- return { ...entry, key };
646
- }
647
- set(key, value, options = {}) {
648
- const revalidate = normalizeRevalidate(options.revalidate);
649
- const tags = /* @__PURE__ */ new Set();
650
- for (const tag of options.tags ?? []) {
651
- tags.add(normalizeCacheTag(tag));
652
- }
653
- for (const routePath of options.paths ?? []) {
654
- tags.add(createPathCacheTag(routePath));
655
- }
656
- const entry = {
657
- key,
658
- value,
659
- tags,
660
- tagVersions: void 0,
661
- createdAt: options.createdAt ?? Date.now(),
662
- createdVersion: ++this.version,
663
- revalidate
664
- };
665
- this.storeLocalEntry(entry);
666
- emitFarmEvent({
667
- type: "cache.set",
668
- key,
669
- tags: Array.from(tags),
670
- revalidate: entry.revalidate
671
- });
672
- return this.toPublicEntry(entry);
673
- }
674
- async setAsync(key, value, options = {}, tagVersions) {
675
- return this.writeAsync(key, value, options, tagVersions);
676
- }
677
- async writeAsync(key, value, options, tagVersions, createdVersion) {
678
- const revalidate = normalizeRevalidate(options.revalidate);
679
- const tags = normalizeCacheOptionsTags(options);
680
- const capturedVersions = tagVersions ?? await this.getAdapterTagVersions(Array.from(tags.values()));
681
- const entry = {
682
- key,
683
- value,
684
- tags: Array.from(tags),
685
- tagVersions: capturedVersions,
686
- createdAt: options.createdAt ?? Date.now(),
687
- createdVersion: createdVersion ?? ++this.version,
688
- revalidate
689
- };
690
- if (this.local) {
691
- this.hydrateLocalEntry(entry);
692
- }
693
- if (this.adapter) {
694
- await this.adapter.set(this.createAdapterKey(key), entry);
695
- }
696
- emitFarmEvent({
697
- type: "cache.set",
698
- key,
699
- tags: [...entry.tags],
700
- revalidate: entry.revalidate
701
- });
702
- return entry;
703
- }
704
- delete(key) {
705
- const deleted = this.entries.delete(key);
706
- if (deleted) this.pruneInvalidatedTagVersions();
707
- emitFarmEvent({ type: "cache.delete", key, deleted });
708
- return deleted;
709
- }
710
- async deleteAsync(key) {
711
- const deleted = this.entries.delete(key);
712
- if (deleted) this.pruneInvalidatedTagVersions();
713
- if (this.adapter) {
714
- await this.adapter.delete(this.createAdapterKey(key));
715
- }
716
- emitFarmEvent({ type: "cache.delete", key, deleted: this.adapter ? true : deleted });
717
- return this.adapter ? true : deleted;
718
- }
719
- clear() {
720
- const count = this.entries.size;
721
- this.generation++;
722
- this.entries.clear();
723
- this.inflight.clear();
724
- this.invalidatedTagVersions.clear();
725
- this.activeGenerations.clear();
726
- this.version = 0;
727
- emitFarmEvent({ type: "cache.clear", count });
728
- }
729
- async clearAsync() {
730
- this.clear();
731
- await this.adapter?.clear?.();
732
- }
733
- isStale(entry, now = Date.now()) {
734
- if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
735
- return true;
736
- }
737
- for (const tag of entry.tags) {
738
- const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));
739
- if (typeof invalidatedVersion === "number" && typeof entry.createdVersion === "number" && invalidatedVersion > entry.createdVersion) {
740
- return true;
741
- }
742
- }
743
- return false;
744
- }
745
- async isStaleAsync(entry, now = Date.now()) {
746
- if (this.adapter) {
747
- return this.isAdapterEntryStale(entry, now);
748
- }
749
- return this.isStale(entry, now);
750
- }
751
- revalidateTag(tag, options = {}) {
752
- const normalized = normalizeCacheTag(tag);
753
- const count = this.invalidateTag(normalized);
754
- emitFarmEvent(
755
- options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
756
- );
757
- return count;
758
- }
759
- async revalidateTagAsync(tag, options = {}) {
760
- const normalized = normalizeCacheTag(tag);
761
- const count = this.invalidateTag(normalized);
762
- await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);
763
- emitFarmEvent(
764
- options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
765
- );
766
- return count;
767
- }
768
- revalidatePath(routePath) {
769
- const normalizedPath = normalizeRevalidatePath(routePath);
770
- const pathTag = createPathCacheTag(normalizedPath);
771
- const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
772
- const count = this.invalidateTag(pathTag);
773
- emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
774
- if (pprCount > 0) {
775
- emitFarmEvent({
776
- type: "ppr.shell.invalidated",
777
- route: normalizedPath,
778
- reason: "revalidatePath",
779
- count: pprCount
780
- });
781
- }
782
- return count;
783
- }
784
- async revalidatePathAsync(routePath) {
785
- const normalizedPath = normalizeRevalidatePath(routePath);
786
- const pathTag = createPathCacheTag(normalizedPath);
787
- const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
788
- const count = this.invalidateTag(pathTag);
789
- await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);
790
- emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
791
- if (pprCount > 0) {
792
- emitFarmEvent({
793
- type: "ppr.shell.invalidated",
794
- route: normalizedPath,
795
- reason: "revalidatePath",
796
- count: pprCount
797
- });
798
- }
799
- return count;
800
- }
801
- async getOrSet(key, producer, options = {}) {
802
- normalizeRevalidate(options.revalidate);
803
- const cached = await this.getEntryAsync(key);
804
- if (cached) {
805
- return cached.value;
806
- }
807
- const inflight = this.inflight.get(key);
808
- if (inflight) {
809
- emitFarmEvent({ type: "cache.dedupe", key });
810
- return inflight;
811
- }
812
- const tags = Array.from(normalizeCacheOptionsTags(options));
813
- const generation = this.generation;
814
- const promise = this.fillCacheEntry(key, producer, options, tags, generation).catch((error) => {
815
- emitFarmEvent({ type: "cache.error", key, operation: "set", error });
816
- throw error;
817
- }).finally(() => {
818
- if (this.inflight.get(key) === promise) {
819
- this.inflight.delete(key);
820
- }
821
- });
822
- this.inflight.set(key, promise);
823
- return promise;
824
- }
825
- async fillCacheEntry(key, producer, options, tags, generation) {
826
- const adapter = this.adapter;
827
- const namespace = this.namespace;
828
- const lease = { ...this.lease };
829
- const leaseKey = `${namespace}:lease:${key}`;
830
- let leaseToken;
831
- if (adapter?.acquireLease && adapter.releaseLease && lease.enabled) {
832
- leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
833
- if (!leaseToken) {
834
- const shared2 = await this.waitForAdapterEntry(
835
- key,
836
- adapter,
837
- namespace,
838
- lease,
839
- generation
840
- );
841
- if (shared2) {
842
- emitFarmEvent({ type: "cache.dedupe", key });
843
- return shared2.value;
844
- }
845
- if (generation === this.generation) {
846
- leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
847
- }
848
- }
849
- }
850
- const initialCreatedVersion = this.version;
851
- const activeGeneration = {
852
- tags: new Set(tags),
853
- createdVersion: initialCreatedVersion
854
- };
855
- this.activeGenerations.add(activeGeneration);
856
- try {
857
- const initialTagVersions = await this.getAdapterTagVersions(tags, adapter, namespace);
858
- const value = await producer();
859
- if (generation === this.generation) {
860
- await this.writeAsync(key, value, options, initialTagVersions, initialCreatedVersion);
861
- }
862
- return value;
863
- } finally {
864
- this.activeGenerations.delete(activeGeneration);
865
- this.pruneInvalidatedTagVersions();
866
- if (leaseToken && adapter?.releaseLease) {
867
- try {
868
- await adapter.releaseLease(leaseKey, leaseToken);
869
- } catch (error) {
870
- emitFarmEvent({ type: "cache.error", key, operation: "set", error });
871
- }
872
- }
873
- }
874
- }
875
- async waitForAdapterEntry(key, adapter, namespace, lease, generation) {
876
- const deadline = Date.now() + lease.waitTimeoutMs;
877
- while (Date.now() < deadline) {
878
- await delay(lease.pollIntervalMs);
879
- if (generation !== this.generation) return void 0;
880
- const entry = await adapter.get(`${namespace}:entry:${key}`);
881
- if (generation !== this.generation) return void 0;
882
- if (!entry) {
883
- emitFarmEvent({ type: "cache.miss", key });
884
- continue;
885
- }
886
- assertFarmCacheEntry(entry, key);
887
- const stale = await this.isAdapterEntryStale(entry, Date.now(), adapter, namespace);
888
- if (generation !== this.generation) return void 0;
889
- if (stale) {
890
- emitFarmEvent({
891
- type: "cache.stale",
892
- key,
893
- tags: [...entry.tags],
894
- revalidate: entry.revalidate
895
- });
896
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
897
- } else {
898
- emitFarmEvent({
899
- type: "cache.hit",
900
- key,
901
- tags: [...entry.tags],
902
- revalidate: entry.revalidate,
903
- stale: false
904
- });
905
- return { ...entry, key };
906
- }
907
- }
908
- return void 0;
909
- }
910
- countEntriesForTag(tag) {
911
- let count = 0;
912
- for (const entry of this.entries.values()) {
913
- if (entry.tags.has(tag)) {
914
- count++;
915
- }
916
- }
917
- return count;
918
- }
919
- countEntriesForTags(tags) {
920
- let count = 0;
921
- for (const entry of this.entries.values()) {
922
- if (tags.every((tag) => entry.tags.has(tag))) {
923
- count++;
924
- }
925
- }
926
- return count;
927
- }
928
- invalidateTag(normalizedTag) {
929
- const count = this.countEntriesForTag(normalizedTag);
930
- this.invalidatedTagVersions.delete(normalizedTag);
931
- this.invalidatedTagVersions.set(normalizedTag, ++this.version);
932
- this.pruneInvalidatedTagVersions();
933
- return count;
934
- }
935
- toPublicEntry(entry) {
936
- return {
937
- key: entry.key,
938
- value: entry.value,
939
- tags: Array.from(entry.tags),
940
- tagVersions: entry.tagVersions,
941
- createdAt: entry.createdAt,
942
- createdVersion: entry.createdVersion,
943
- revalidate: entry.revalidate
944
- };
945
- }
946
- hydrateLocalEntry(entry) {
947
- this.storeLocalEntry({
948
- key: entry.key,
949
- value: entry.value,
950
- tags: new Set(entry.tags.map(normalizeCacheTag)),
951
- tagVersions: entry.tagVersions,
952
- createdAt: entry.createdAt,
953
- createdVersion: entry.createdVersion ?? ++this.version,
954
- revalidate: normalizeRevalidate(entry.revalidate)
955
- });
956
- }
957
- touchEntry(key, entry) {
958
- this.entries.delete(key);
959
- this.entries.set(key, entry);
960
- }
961
- storeLocalEntry(entry) {
962
- this.entries.delete(entry.key);
963
- this.entries.set(entry.key, entry);
964
- while (this.entries.size > this.maxEntries) {
965
- const oldestKey = this.entries.keys().next().value;
966
- if (oldestKey === void 0) break;
967
- this.entries.delete(oldestKey);
968
- }
969
- this.pruneInvalidatedTagVersions();
970
- }
971
- pruneInvalidatedTagVersions() {
972
- tags: for (const [tag, invalidatedVersion] of this.invalidatedTagVersions) {
973
- for (const entry of this.entries.values()) {
974
- if (entry.tags.has(tag) && entry.createdVersion < invalidatedVersion) continue tags;
975
- }
976
- for (const generation of this.activeGenerations) {
977
- if (generation.tags.has(tag) && generation.createdVersion < invalidatedVersion)
978
- continue tags;
979
- }
980
- this.invalidatedTagVersions.delete(tag);
981
- }
982
- }
983
- createAdapterKey(key) {
984
- return `${this.namespace}:entry:${key}`;
985
- }
986
- createAdapterTag(tag) {
987
- return `${this.namespace}:tag:${tag}`;
988
- }
989
- async getAdapterTagVersions(tags, adapter = this.adapter, namespace = this.namespace) {
990
- if (!adapter?.getTagVersions || tags.length === 0) return {};
991
- const normalized = tags.map(normalizeCacheTag);
992
- const physicalTags = normalized.map((tag) => `${namespace}:tag:${tag}`);
993
- const versions = await adapter.getTagVersions(physicalTags);
994
- return Object.fromEntries(
995
- normalized.map((tag, index) => [
996
- tag,
997
- normalizeAdapterVersion(versions[physicalTags[index]])
998
- ])
999
- );
1000
- }
1001
- async isAdapterEntryStale(entry, now = Date.now(), adapter = this.adapter, namespace = this.namespace) {
1002
- if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
1003
- return true;
1004
- }
1005
- const currentVersions = await this.getAdapterTagVersions(entry.tags, adapter, namespace);
1006
- for (const tag of entry.tags) {
1007
- if (normalizeAdapterVersion(currentVersions[tag]) > normalizeAdapterVersion(entry.tagVersions?.[tag])) {
1008
- return true;
1009
- }
1010
- }
1011
- return false;
1012
- }
1013
- };
1014
- __name(_FarmDataCache, "FarmDataCache");
1015
- var FarmDataCache = _FarmDataCache;
1016
- var FARM_DATA_CACHE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.dataCache");
1017
- var farmDataCacheGlobal = globalThis;
1018
- var sharedFarmDataCache = farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ?? (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] = new FarmDataCache());
1019
- function getFarmDataCache() {
1020
- return sharedFarmDataCache;
1021
- }
1022
- __name(getFarmDataCache, "getFarmDataCache");
1023
- function updateTag(tag) {
1024
- const cache = getFarmDataCache();
1025
- if (cache.hasAdapter) {
1026
- const task = cache.revalidateTagAsync(tag, { source: "updateTag" }).then(() => void 0);
1027
- notifyFarmCacheTask(task);
1028
- return task;
1029
- }
1030
- cache.revalidateTag(tag, { source: "updateTag" });
1031
- }
1032
- __name(updateTag, "updateTag");
1033
- function revalidatePath(routePath) {
1034
- const cache = getFarmDataCache();
1035
- if (cache.hasAdapter) {
1036
- const task = cache.revalidatePathAsync(routePath).then(() => void 0);
1037
- notifyFarmCacheTask(task);
1038
- return task;
1039
- }
1040
- cache.revalidatePath(routePath);
1041
- }
1042
- __name(revalidatePath, "revalidatePath");
1043
- function invalidate(key) {
1044
- const clientKey = createRouteDataCacheKey(key);
1045
- const task = updateTag(createRouteDataCacheTag(key));
1046
- notifyFarmCacheInvalidation(clientKey);
1047
- return task;
1048
- }
1049
- __name(invalidate, "invalidate");
1050
- async function applyFarmCacheInvalidationTargets(targets) {
1051
- if (!Array.isArray(targets)) {
1052
- throw new TypeError("Cache invalidations must resolve to an array of targets.");
1053
- }
1054
- const clientKeys = [];
1055
- for (const target of targets) {
1056
- assertFarmCacheInvalidationTarget(target);
1057
- if ("key" in target) {
1058
- await invalidate(target.key);
1059
- clientKeys.push(createRouteDataCacheKey(target.key));
1060
- } else if ("path" in target) {
1061
- await revalidatePath(target.path);
1062
- } else {
1063
- await updateTag(target.tag);
1064
- }
1065
- }
1066
- return Array.from(new Set(clientKeys));
1067
- }
1068
- __name(applyFarmCacheInvalidationTargets, "applyFarmCacheInvalidationTargets");
1069
- function createPathCacheTag(routePath) {
1070
- return `path:${normalizeRevalidatePath(routePath)}`;
1071
- }
1072
- __name(createPathCacheTag, "createPathCacheTag");
1073
- function createRouteDataCacheTag(key) {
1074
- return `route-data:${createRouteDataCacheKey(key)}`;
1075
- }
1076
- __name(createRouteDataCacheTag, "createRouteDataCacheTag");
1077
- function createRouteDataCacheKey(key) {
1078
- return createFarmCacheKey(Array.isArray(key) ? key : [key]);
1079
- }
1080
- __name(createRouteDataCacheKey, "createRouteDataCacheKey");
1081
- function normalizeRevalidatePath(routePath) {
1082
- if (typeof routePath !== "string") {
1083
- throw new TypeError("revalidatePath expects a path string.");
1084
- }
1085
- let normalized = routePath.trim();
1086
- if (!normalized) {
1087
- throw new Error("revalidatePath expects a non-empty path.");
1088
- }
1089
- try {
1090
- if (/^https?:\/\//i.test(normalized)) {
1091
- normalized = new URL(normalized).pathname;
1092
- }
1093
- } catch {
1094
- }
1095
- normalized = normalized.split(/[?#]/, 1)[0] ?? normalized;
1096
- normalized = normalized.startsWith("/") ? normalized : `/${normalized}`;
1097
- normalized = normalized.replace(/\/{2,}/g, "/");
1098
- normalized = new URL(normalized, "http://farm.invalid").pathname;
1099
- if (normalized.length > 1) {
1100
- normalized = normalized.replace(/\/+$/, "");
1101
- }
1102
- return normalized || "/";
1103
- }
1104
- __name(normalizeRevalidatePath, "normalizeRevalidatePath");
1105
- function createFarmCacheKey(parts) {
1106
- return stableSerialize(parts);
1107
- }
1108
- __name(createFarmCacheKey, "createFarmCacheKey");
1109
- function normalizeRevalidate(revalidate) {
1110
- if (revalidate === false || revalidate === void 0) {
1111
- return revalidate;
1112
- }
1113
- if (!Number.isFinite(revalidate) || revalidate < 0) {
1114
- throw new TypeError("Cache revalidate must be false or a finite, non-negative number.");
1115
- }
1116
- return revalidate;
1117
- }
1118
- __name(normalizeRevalidate, "normalizeRevalidate");
1119
- function normalizeCacheTag(tag) {
1120
- if (typeof tag !== "string") {
1121
- throw new TypeError("Cache tags must be strings.");
1122
- }
1123
- const normalized = tag.trim();
1124
- if (!normalized) {
1125
- throw new Error("Cache tags cannot be empty.");
1126
- }
1127
- return normalized;
1128
- }
1129
- __name(normalizeCacheTag, "normalizeCacheTag");
1130
- function normalizeCacheNamespace(namespace) {
1131
- if (typeof namespace !== "string") {
1132
- throw new TypeError("Cache namespace must be a string.");
1133
- }
1134
- const normalized = namespace.trim().replace(/:+$/g, "");
1135
- if (!normalized) {
1136
- throw new Error("Cache namespace cannot be empty.");
1137
- }
1138
- return normalized;
1139
- }
1140
- __name(normalizeCacheNamespace, "normalizeCacheNamespace");
1141
- function normalizeAdapterVersion(value) {
1142
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
1143
- }
1144
- __name(normalizeAdapterVersion, "normalizeAdapterVersion");
1145
- function normalizePositiveDuration(value, fallback, name) {
1146
- if (value === void 0) return fallback;
1147
- if (!Number.isFinite(value) || value <= 0) {
1148
- throw new TypeError(`${name} must be a positive number of milliseconds.`);
1149
- }
1150
- return Math.floor(value);
1151
- }
1152
- __name(normalizePositiveDuration, "normalizePositiveDuration");
1153
- function normalizePositiveInteger(value, fallback, name) {
1154
- if (value === void 0) return fallback;
1155
- if (!Number.isSafeInteger(value) || value <= 0) {
1156
- throw new TypeError(`${name} must be a positive integer.`);
1157
- }
1158
- return value;
1159
- }
1160
- __name(normalizePositiveInteger, "normalizePositiveInteger");
1161
- function delay(ms) {
1162
- return new Promise((resolve) => setTimeout(resolve, ms));
1163
- }
1164
- __name(delay, "delay");
1165
- function normalizeCacheOptionsTags(options) {
1166
- const tags = /* @__PURE__ */ new Set();
1167
- for (const tag of options.tags ?? []) {
1168
- tags.add(normalizeCacheTag(tag));
1169
- }
1170
- for (const routePath of options.paths ?? []) {
1171
- tags.add(createPathCacheTag(routePath));
1172
- }
1173
- return tags;
1174
- }
1175
- __name(normalizeCacheOptionsTags, "normalizeCacheOptionsTags");
1176
- function assertFarmCacheEntry(entry, expectedKey) {
1177
- if (!entry || typeof entry !== "object" || entry.key !== expectedKey || !Array.isArray(entry.tags) || typeof entry.createdAt !== "number") {
1178
- throw new TypeError(
1179
- `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`
1180
- );
1181
- }
1182
- }
1183
- __name(assertFarmCacheEntry, "assertFarmCacheEntry");
1184
- function assertFarmCacheInvalidationTarget(target) {
1185
- if (!target || typeof target !== "object") {
1186
- throw new TypeError("Cache invalidation targets must be { key }, { path }, or { tag }.");
1187
- }
1188
- if ("key" in target) {
1189
- const key = target.key;
1190
- if (typeof key === "string" || Array.isArray(key)) return;
1191
- } else if ("path" in target && typeof target.path === "string") {
1192
- return;
1193
- } else if ("tag" in target && typeof target.tag === "string") {
1194
- return;
1195
- }
1196
- throw new TypeError("Cache invalidation targets must contain a string/array key, path, or tag.");
1197
- }
1198
- __name(assertFarmCacheInvalidationTarget, "assertFarmCacheInvalidationTarget");
1199
- function getFunctionCacheIdentity(fn) {
1200
- const name = fn.name || "anonymous";
1201
- return `${name}:${hashFunctionSource(String(fn))}`;
1202
- }
1203
- __name(getFunctionCacheIdentity, "getFunctionCacheIdentity");
1204
- function hashFunctionSource(source) {
1205
- let hash = 2166136261;
1206
- for (let index = 0; index < source.length; index++) {
1207
- hash ^= source.charCodeAt(index);
1208
- hash = Math.imul(hash, 16777619);
1209
- }
1210
- return (hash >>> 0).toString(36);
1211
- }
1212
- __name(hashFunctionSource, "hashFunctionSource");
1213
- function compareCodepoint(a, b) {
1214
- return a < b ? -1 : a > b ? 1 : 0;
1215
- }
1216
- __name(compareCodepoint, "compareCodepoint");
1217
- function serializeBinaryBytes(bytes) {
1218
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1219
- }
1220
- __name(serializeBinaryBytes, "serializeBinaryBytes");
1221
- function serializeCanonicalStringEntries(entries, seen) {
1222
- const valuesByKey = /* @__PURE__ */ new Map();
1223
- for (const [key, item] of entries) {
1224
- const values = valuesByKey.get(key);
1225
- if (values) values.push(item);
1226
- else valuesByKey.set(key, [item]);
1227
- }
1228
- return Array.from(valuesByKey.keys()).sort(compareCodepoint).flatMap(
1229
- (key) => valuesByKey.get(key).map((item) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`)
1230
- ).join(",");
1231
- }
1232
- __name(serializeCanonicalStringEntries, "serializeCanonicalStringEntries");
1233
- function isPlainCacheKeyObject(value) {
1234
- const prototype = Object.getPrototypeOf(value);
1235
- if (prototype === null) return true;
1236
- const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
1237
- return Object.getPrototypeOf(prototype) === null && typeof constructor === "function" && constructor.name === "Object";
1238
- }
1239
- __name(isPlainCacheKeyObject, "isPlainCacheKeyObject");
1240
- function getCacheKeyValueType(value) {
1241
- const prototype = Object.getPrototypeOf(value);
1242
- const constructor = prototype ? Object.getOwnPropertyDescriptor(prototype, "constructor")?.value : void 0;
1243
- if (typeof constructor === "function" && constructor.name) {
1244
- return constructor.name;
1245
- }
1246
- return Object.prototype.toString.call(value).slice(8, -1) || "object";
1247
- }
1248
- __name(getCacheKeyValueType, "getCacheKeyValueType");
1249
- function stableSerialize(value, seen = /* @__PURE__ */ new WeakSet()) {
1250
- if (value === null) return "null";
1251
- if (value === void 0) return "undefined";
1252
- const valueType = typeof value;
1253
- if (valueType === "string") return JSON.stringify(value);
1254
- if (valueType === "number" || valueType === "boolean" || valueType === "bigint") {
1255
- return `${valueType}:${String(value)}`;
1256
- }
1257
- if (valueType === "symbol") {
1258
- return `symbol:${String(value)}`;
1259
- }
1260
- if (valueType === "function") {
1261
- return `function:${getFunctionCacheIdentity(value)}`;
1262
- }
1263
- if (value instanceof Date) {
1264
- return Number.isNaN(value.getTime()) ? "date:invalid" : `date:${value.toISOString()}`;
1265
- }
1266
- if (value instanceof URL) {
1267
- return `url:${value.toString()}`;
1268
- }
1269
- if (value instanceof RegExp) {
1270
- return `regexp:${value.toString()}`;
1271
- }
1272
- if (value instanceof ArrayBuffer) {
1273
- return `arraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
1274
- }
1275
- if (typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer) {
1276
- return `sharedarraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
1277
- }
1278
- if (ArrayBuffer.isView(value)) {
1279
- const viewType = Object.prototype.toString.call(value).slice(8, -1);
1280
- const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
1281
- return `binary:${viewType}:${serializeBinaryBytes(bytes)}`;
1282
- }
1283
- if (value && typeof value === "object") {
1284
- if (seen.has(value)) {
1285
- return "[Circular]";
1286
- }
1287
- seen.add(value);
1288
- if (Array.isArray(value)) {
1289
- const items = [];
1290
- for (let index = 0; index < value.length; index++) {
1291
- items.push(
1292
- Object.prototype.hasOwnProperty.call(value, index) ? stableSerialize(value[index], seen) : "[Hole]"
1293
- );
1294
- }
1295
- seen.delete(value);
1296
- return `[${items.join(",")}]`;
1297
- }
1298
- if (value instanceof Set) {
1299
- const items = Array.from(value, (item) => stableSerialize(item, seen)).sort(compareCodepoint);
1300
- seen.delete(value);
1301
- return `set:[${items.join(",")}]`;
1302
- }
1303
- if (value instanceof Map) {
1304
- const items = Array.from(
1305
- value,
1306
- ([key, item]) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`
1307
- ).sort(compareCodepoint);
1308
- seen.delete(value);
1309
- return `map:[${items.join(",")}]`;
1310
- }
1311
- if (value instanceof URLSearchParams) {
1312
- const serialized2 = serializeCanonicalStringEntries(value, seen);
1313
- seen.delete(value);
1314
- return `urlsearchparams:[${serialized2}]`;
1315
- }
1316
- if (value instanceof Headers) {
1317
- const serialized2 = serializeCanonicalStringEntries(value, seen);
1318
- seen.delete(value);
1319
- return `headers:[${serialized2}]`;
1320
- }
1321
- if (!isPlainCacheKeyObject(value)) {
1322
- throw new TypeError(
1323
- `Cache keys do not support ${getCacheKeyValueType(value)} values. Convert the value to an explicit stable string or structured key before caching.`
1324
- );
1325
- }
1326
- const entries = Object.entries(value).sort(
1327
- ([a], [b]) => compareCodepoint(a, b)
1328
- );
1329
- const serialized = entries.map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`).join(",");
1330
- seen.delete(value);
1331
- return `{${serialized}}`;
1332
- }
1333
- return String(value);
1334
- }
1335
- __name(stableSerialize, "stableSerialize");
1336
12
 
1337
- // src/api/transport.ts
1338
- function isMultipartSchema(value) {
1339
- return typeof value === "object" && value !== null && value.__farmMultipartSchema === true && typeof value.parse === "function";
1340
- }
1341
- __name(isMultipartSchema, "isMultipartSchema");
1342
13
 
1343
- // src/api/endpoint.ts
1344
- var _EndpointFailure = class _EndpointFailure extends Error {
1345
- constructor(code, data, options) {
1346
- super(options.message);
1347
- this.name = "EndpointFailure";
1348
- this.code = code;
1349
- this.data = data;
1350
- this.status = options.status;
1351
- }
1352
- };
1353
- __name(_EndpointFailure, "EndpointFailure");
1354
- var EndpointFailure = _EndpointFailure;
1355
- function isEndpointFailure(value) {
1356
- return value instanceof EndpointFailure;
1357
- }
1358
- __name(isEndpointFailure, "isEndpointFailure");
1359
- function createEndpoint(pathOrOptions, optionsOrHandler, maybeHandler) {
1360
- let path;
1361
- let options;
1362
- let handler;
1363
- if (typeof pathOrOptions === "function") {
1364
- path = "";
1365
- options = {};
1366
- handler = pathOrOptions;
1367
- } else if (typeof pathOrOptions === "string") {
1368
- path = pathOrOptions;
1369
- options = optionsOrHandler;
1370
- handler = maybeHandler;
1371
- } else {
1372
- path = "";
1373
- options = pathOrOptions;
1374
- handler = optionsOrHandler;
1375
- }
1376
- if (typeof handler !== "function") {
1377
- throw new TypeError("createEndpoint requires a handler function");
1378
- }
1379
- const middleware = normalizeEndpointMiddleware(options.middleware);
1380
- const errors = normalizeEndpointErrors(options.errors);
1381
- const error = createEndpointErrorHandler(errors);
1382
- const wrappedHandler = /* @__PURE__ */ __name((async (ctx) => {
1383
- const execution = await runEndpointMiddleware(
1384
- middleware,
1385
- ctx,
1386
- handler,
1387
- error,
1388
- options.invalidates
1389
- );
1390
- return execution.result;
1391
- }), "wrappedHandler");
1392
- const {
1393
- middleware: _middleware,
1394
- errors: _errors,
1395
- invalidates: _invalidates,
1396
- openapi: _openapi,
1397
- mcp: _mcp,
1398
- ...betterCallOptions
1399
- } = options;
1400
- const endpoint = (0, import_better_call.createEndpoint)(
1401
- path || "/__farm_auto_path__",
1402
- betterCallOptions,
1403
- wrappedHandler
1404
- );
1405
- endpoint.__path = path || void 0;
1406
- endpoint.__method = options.method || "GET";
1407
- endpoint.__autoPath = !path;
1408
- endpoint.__handler = wrappedHandler;
1409
- endpoint.__farmInvoke = (ctx) => runEndpointMiddleware(middleware, ctx, handler, error, options.invalidates);
1410
- endpoint.__middleware = middleware;
1411
- endpoint.__sourceHandler = handler;
1412
- endpoint.__invalidates = options.invalidates;
1413
- endpoint.__errors = errors;
1414
- endpoint.__openapi = options.openapi;
1415
- endpoint.__mcp = options.mcp;
1416
- endpoint.__types = {
1417
- body: options.body,
1418
- inputBody: isMultipartSchema(options.body) ? "form-data" : options.body,
1419
- query: options.query,
1420
- inputQuery: options.query,
1421
- headers: options.headers,
1422
- response: null,
1423
- errors
1424
- };
1425
- return endpoint;
1426
- }
1427
- __name(createEndpoint, "createEndpoint");
1428
- var EMPTY_ENDPOINT_MIDDLEWARE = Object.freeze([]);
1429
- var EMPTY_ENDPOINT_CONTEXT = Object.freeze(/* @__PURE__ */ Object.create(null));
1430
- var UNSAFE_ENDPOINT_CONTEXT_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1431
- function normalizeEndpointErrors(definitions) {
1432
- if (definitions === void 0) return Object.freeze({});
1433
- if (!isPlainEndpointContext(definitions)) {
1434
- throw new TypeError("createEndpoint errors must be an object");
1435
- }
1436
- const normalized = /* @__PURE__ */ Object.create(null);
1437
- for (const [code, definition] of Object.entries(definitions)) {
1438
- if (!code.trim()) {
1439
- throw new TypeError("Endpoint error codes cannot be empty");
1440
- }
1441
- if (!definition || typeof definition !== "object") {
1442
- throw new TypeError(`Endpoint error "${code}" must be an object`);
1443
- }
1444
- if (!Number.isInteger(definition.status) || definition.status < 400 || definition.status > 599) {
1445
- throw new TypeError(`Endpoint error "${code}" status must be an integer between 400 and 599`);
1446
- }
1447
- const dataSchema = resolveEndpointErrorSchema(definition);
1448
- if (!dataSchema || typeof dataSchema.parse !== "function") {
1449
- throw new TypeError(`Endpoint error "${code}" requires a data schema with parse()`);
1450
- }
1451
- if (definition.message !== void 0 && typeof definition.message !== "string") {
1452
- throw new TypeError(`Endpoint error "${code}" message must be a string`);
1453
- }
1454
- normalized[code] = Object.freeze({ ...definition });
1455
- }
1456
- return Object.freeze(normalized);
1457
- }
1458
- __name(normalizeEndpointErrors, "normalizeEndpointErrors");
1459
- function resolveEndpointErrorSchema(definition) {
1460
- if (definition.data && definition.schema) {
1461
- throw new TypeError("Endpoint errors cannot define both data and schema");
1462
- }
1463
- return definition.data ?? definition.schema;
1464
- }
1465
- __name(resolveEndpointErrorSchema, "resolveEndpointErrorSchema");
1466
- function createEndpointErrorHandler(definitions) {
1467
- return ((code, data) => {
1468
- const definition = definitions[code];
1469
- if (!definition) {
1470
- throw new TypeError(`Endpoint error "${code}" is not declared`);
1471
- }
1472
- const parsed = resolveEndpointErrorSchema(definition).parse(data);
1473
- throw new EndpointFailure(code, parsed, {
1474
- status: definition.status,
1475
- message: definition.message ?? "Request failed"
1476
- });
1477
- });
1478
- }
1479
- __name(createEndpointErrorHandler, "createEndpointErrorHandler");
1480
- function normalizeEndpointMiddleware(middleware) {
1481
- if (middleware === void 0) return EMPTY_ENDPOINT_MIDDLEWARE;
1482
- if (!Array.isArray(middleware)) {
1483
- throw new TypeError("createEndpoint middleware must be an array of functions");
1484
- }
1485
- const normalized = [...middleware];
1486
- for (const entry of normalized) {
1487
- if (typeof entry !== "function") {
1488
- throw new TypeError("createEndpoint middleware entries must be functions");
1489
- }
1490
- }
1491
- return Object.freeze(normalized);
1492
- }
1493
- __name(normalizeEndpointMiddleware, "normalizeEndpointMiddleware");
1494
- async function runEndpointMiddleware(middleware, handlerContext, handler, error, invalidations) {
1495
- let context2 = createInitialEndpointContext(handlerContext.context);
1496
- for (let index = 0; index < middleware.length; index++) {
1497
- const result2 = await middleware[index]({ ...handlerContext, context: context2 });
1498
- if (isEndpointResponse(result2)) {
1499
- return {
1500
- result: result2,
1501
- context: context2,
1502
- handlerExecuted: false,
1503
- invalidations: []
1504
- };
1505
- }
1506
- if (result2 === false) {
1507
- return {
1508
- result: forbiddenEndpointResponse(),
1509
- context: context2,
1510
- handlerExecuted: false,
1511
- invalidations: []
1512
- };
1513
- }
1514
- if (result2 === true) continue;
1515
- if (!isPlainEndpointContext(result2)) {
1516
- throw new TypeError(
1517
- `Endpoint middleware ${index + 1} must return an object, true, false, or a Response`
1518
- );
1519
- }
1520
- context2 = mergeEndpointContext(context2, result2, index);
1521
- }
1522
- const result = await handler({ ...handlerContext, context: context2, error, fail: error });
1523
- return {
1524
- result,
1525
- context: context2,
1526
- handlerExecuted: true,
1527
- invalidations: await applyEndpointInvalidations(
1528
- invalidations,
1529
- {
1530
- ...handlerContext,
1531
- context: context2,
1532
- result
1533
- },
1534
- result
1535
- )
1536
- };
1537
- }
1538
- __name(runEndpointMiddleware, "runEndpointMiddleware");
1539
- async function applyEndpointInvalidations(declaration, context2, result) {
1540
- if (!declaration || isEndpointResponse(result) && result.status >= 400) {
1541
- return [];
1542
- }
1543
- const targets = typeof declaration === "function" ? await declaration(context2) : declaration;
1544
- if (!Array.isArray(targets)) {
1545
- throw new TypeError(
1546
- "Endpoint invalidates must resolve to an array of { key }, { path }, or { tag } targets"
1547
- );
1548
- }
1549
- return applyFarmCacheInvalidationTargets(targets);
1550
- }
1551
- __name(applyEndpointInvalidations, "applyEndpointInvalidations");
1552
- function createInitialEndpointContext(value) {
1553
- if (value === void 0 || value === null) return EMPTY_ENDPOINT_CONTEXT;
1554
- if (!isPlainEndpointContext(value)) {
1555
- throw new TypeError("Endpoint context must be a plain object");
1556
- }
1557
- return mergeEndpointContext(EMPTY_ENDPOINT_CONTEXT, value);
1558
- }
1559
- __name(createInitialEndpointContext, "createInitialEndpointContext");
1560
- function mergeEndpointContext(current, added, middlewareIndex) {
1561
- const next = Object.assign(/* @__PURE__ */ Object.create(null), current);
1562
- for (const key of Reflect.ownKeys(added)) {
1563
- if (!Object.prototype.propertyIsEnumerable.call(added, key)) continue;
1564
- if (typeof key === "string" && UNSAFE_ENDPOINT_CONTEXT_KEYS.has(key)) {
1565
- throw new TypeError(`Endpoint middleware cannot provide the unsafe context key "${key}"`);
1566
- }
1567
- if (Object.prototype.hasOwnProperty.call(current, key)) {
1568
- const source = middlewareIndex === void 0 ? "Endpoint context" : `Endpoint middleware ${middlewareIndex + 1}`;
1569
- throw new TypeError(`${source} cannot replace the existing context key "${String(key)}"`);
1570
- }
1571
- next[key] = added[key];
1572
- }
1573
- return Object.freeze(next);
1574
- }
1575
- __name(mergeEndpointContext, "mergeEndpointContext");
1576
- function isPlainEndpointContext(value) {
1577
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
1578
- const prototype = Object.getPrototypeOf(value);
1579
- return prototype === Object.prototype || prototype === null;
1580
- }
1581
- __name(isPlainEndpointContext, "isPlainEndpointContext");
1582
- function isEndpointResponse(value) {
1583
- return value instanceof Response || typeof value === "object" && value !== null && "headers" in value && "status" in value && typeof value.arrayBuffer === "function";
1584
- }
1585
- __name(isEndpointResponse, "isEndpointResponse");
1586
- function forbiddenEndpointResponse() {
1587
- return new Response(JSON.stringify({ error: "Forbidden" }), {
1588
- status: 403,
1589
- headers: { "Content-Type": "application/json" }
1590
- });
1591
- }
1592
- __name(forbiddenEndpointResponse, "forbiddenEndpointResponse");
14
+ var _chunk4PNUXIVUcjs = require('../chunk-4PNUXIVU.cjs');
15
+ require('../chunk-WPYFSQKK.cjs');
1593
16
 
1594
- // src/routing/specificity.ts
1595
- var _AmbiguousRouteError = class _AmbiguousRouteError extends Error {
1596
- constructor(message) {
1597
- super(message);
1598
- this.name = "AmbiguousRouteError";
1599
- }
1600
- };
1601
- __name(_AmbiguousRouteError, "AmbiguousRouteError");
1602
- var AmbiguousRouteError = _AmbiguousRouteError;
1603
- var _NonTerminalCatchAllRouteError = class _NonTerminalCatchAllRouteError extends TypeError {
1604
- constructor(message) {
1605
- super(message);
1606
- this.name = "NonTerminalCatchAllRouteError";
1607
- }
1608
- };
1609
- __name(_NonTerminalCatchAllRouteError, "NonTerminalCatchAllRouteError");
1610
- var NonTerminalCatchAllRouteError = _NonTerminalCatchAllRouteError;
1611
- var _DuplicateRouteParameterError = class _DuplicateRouteParameterError extends AmbiguousRouteError {
1612
- constructor(message) {
1613
- super(message);
1614
- this.name = "DuplicateRouteParameterError";
1615
- }
1616
- };
1617
- __name(_DuplicateRouteParameterError, "DuplicateRouteParameterError");
1618
- var DuplicateRouteParameterError = _DuplicateRouteParameterError;
1619
- var _ReservedRouteParameterError = class _ReservedRouteParameterError extends AmbiguousRouteError {
1620
- constructor(message) {
1621
- super(message);
1622
- this.name = "ReservedRouteParameterError";
1623
- }
1624
- };
1625
- __name(_ReservedRouteParameterError, "ReservedRouteParameterError");
1626
- var ReservedRouteParameterError = _ReservedRouteParameterError;
1627
- var _BrowserUnstableRouteError = class _BrowserUnstableRouteError extends TypeError {
1628
- constructor(message) {
1629
- super(message);
1630
- this.name = "BrowserUnstableRouteError";
1631
- }
1632
- };
1633
- __name(_BrowserUnstableRouteError, "BrowserUnstableRouteError");
1634
- var BrowserUnstableRouteError = _BrowserUnstableRouteError;
1635
- var SEGMENT_RANK = {
1636
- static: 4,
1637
- dynamic: 3,
1638
- "catch-all": 1,
1639
- "optional-catch-all": 0
1640
- };
1641
- var ROUTE_END_RANK = 2;
1642
- function compareRouteSpecificity(left, right) {
1643
- const length = Math.max(left.length, right.length);
1644
- for (let index = 0; index < length; index++) {
1645
- const leftRank = index < left.length ? SEGMENT_RANK[left[index]] : ROUTE_END_RANK;
1646
- const rightRank = index < right.length ? SEGMENT_RANK[right[index]] : ROUTE_END_RANK;
1647
- if (leftRank !== rightRank) return rightRank - leftRank;
1648
- }
1649
- return 0;
1650
- }
1651
- __name(compareRouteSpecificity, "compareRouteSpecificity");
1652
- var ROUTER_PARAMETER_NAME = "[A-Za-z0-9_$-]+";
1653
- var PAGE_PARAMETER_PATTERN = /^(?:\[\[\.\.\.(.+)\]\]|\[\.\.\.(.+)\]|\[(.+)\])$/;
1654
- var ROUTER_PARAMETER_PATTERN = /^(?:\[\[\.\.\.([A-Za-z0-9_$-]+)\]\]|\[\.\.\.([A-Za-z0-9_$-]+)\]|\[([A-Za-z0-9_$-]+)\]|:([A-Za-z0-9_$-]+)|\*([A-Za-z0-9_$-]+)\??)$/;
1655
- var RESERVED_PARAMETER_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1656
- function assertBrowserStableRoutePath(pattern) {
1657
- if (pattern.includes("\\") || hasControlCharacter(pattern)) {
1658
- throw new BrowserUnstableRouteError(
1659
- `Route path "${pattern}" cannot contain backslashes or control characters.`
1660
- );
1661
- }
1662
- for (const segment of pattern.split("/").filter(Boolean)) {
1663
- if (segment.startsWith("(") && segment.endsWith(")") || segment.startsWith("[") && segment.endsWith("]")) {
1664
- continue;
1665
- }
1666
- let decoded = segment;
1667
- try {
1668
- decoded = decodeURIComponent(segment);
1669
- } catch {
1670
- }
1671
- if (decoded === "." || decoded === ".." || decoded.includes("/") || decoded.includes("\\") || hasControlCharacter(decoded)) {
1672
- throw new BrowserUnstableRouteError(
1673
- `Route path "${pattern}" contains browser-unstable segment "${segment}".`
1674
- );
1675
- }
1676
- }
1677
- }
1678
- __name(assertBrowserStableRoutePath, "assertBrowserStableRoutePath");
1679
- function hasControlCharacter(value) {
1680
- return Array.from(value).some((character) => {
1681
- const code = character.charCodeAt(0);
1682
- return code <= 31 || code >= 127 && code <= 159;
1683
- });
1684
- }
1685
- __name(hasControlCharacter, "hasControlCharacter");
1686
- function assertUniqueRouteParameters(pattern, syntax = "page") {
1687
- const parameterPattern = syntax === "router" ? ROUTER_PARAMETER_PATTERN : PAGE_PARAMETER_PATTERN;
1688
- const names = /* @__PURE__ */ new Set();
1689
- for (const segment of splitRoutePattern(pattern, syntax)) {
1690
- const match = parameterPattern.exec(segment);
1691
- const name = match?.slice(1).find(Boolean);
1692
- if (!name) continue;
1693
- if (RESERVED_PARAMETER_NAMES.has(name)) {
1694
- throw new ReservedRouteParameterError(
1695
- `Route parameter "${name}" in route "${pattern}" is reserved. Use a different parameter name.`
1696
- );
1697
- }
1698
- if (names.has(name)) {
1699
- throw new DuplicateRouteParameterError(
1700
- `Duplicate route parameter "${name}" in route "${pattern}". Each dynamic segment must use a unique name.`
1701
- );
1702
- }
1703
- names.add(name);
1704
- }
1705
- }
1706
- __name(assertUniqueRouteParameters, "assertUniqueRouteParameters");
1707
- function splitRoutePattern(pattern, syntax) {
1708
- return pattern.replace(/\\/g, "/").split("/").filter(Boolean).filter(
1709
- (segment) => syntax === "api" ? true : !(segment.startsWith("(") && segment.endsWith(")"))
1710
- );
1711
- }
1712
- __name(splitRoutePattern, "splitRoutePattern");
1713
- function assertTerminalCatchAll(pattern, syntax = "page") {
1714
- const segments = splitRoutePattern(pattern, syntax);
1715
- const parameterName = syntax === "router" ? ROUTER_PARAMETER_NAME : ".+";
1716
- const catchAllPattern = new RegExp(
1717
- syntax === "router" ? `^(?:\\[\\[\\.\\.\\.${parameterName}\\]\\]|\\[\\.\\.\\.${parameterName}\\]|\\*${parameterName}\\??)$` : `^(?:\\[\\[\\.\\.\\.${parameterName}\\]\\]|\\[\\.\\.\\.${parameterName}\\])$`
1718
- );
1719
- const catchAllIndex = segments.findIndex((segment) => catchAllPattern.test(segment));
1720
- if (catchAllIndex >= 0 && catchAllIndex !== segments.length - 1) {
1721
- throw new NonTerminalCatchAllRouteError(
1722
- `Catch-all segment "${segments[catchAllIndex]}" must be the final segment in route "${pattern}".`
1723
- );
1724
- }
1725
- }
1726
- __name(assertTerminalCatchAll, "assertTerminalCatchAll");
1727
- function getRoutePatternShape(pattern, syntax = "page") {
1728
- assertTerminalCatchAll(pattern, syntax);
1729
- const segments = splitRoutePattern(pattern, syntax).map((segment) => {
1730
- const specificity = getPatternSegmentSpecificity(segment, syntax);
1731
- if (specificity !== "static") return specificity;
1732
- try {
1733
- return `static:${decodeURIComponent(segment)}`;
1734
- } catch {
1735
- return `static:${segment}`;
1736
- }
1737
- });
1738
- return segments.length === 0 ? "/" : JSON.stringify(segments);
1739
- }
1740
- __name(getRoutePatternShape, "getRoutePatternShape");
1741
- function getPatternSegmentSpecificity(segment, syntax) {
1742
- const parameterName = syntax === "router" ? ROUTER_PARAMETER_NAME : ".+";
1743
- const supportsColonAndStar = syntax === "router";
1744
- if (new RegExp(`^\\[\\[\\.\\.\\.${parameterName}\\]\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^\\*${parameterName}\\?$`).test(segment)) {
1745
- return "optional-catch-all";
1746
- }
1747
- if (new RegExp(`^\\[\\.\\.\\.${parameterName}\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^\\*${parameterName}$`).test(segment)) {
1748
- return "catch-all";
1749
- }
1750
- if (new RegExp(`^\\[${parameterName}\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^:${parameterName}$`).test(segment)) {
1751
- return "dynamic";
1752
- }
1753
- return "static";
1754
- }
1755
- __name(getPatternSegmentSpecificity, "getPatternSegmentSpecificity");
1756
17
 
1757
- // src/request-context.ts
1758
- var REQUEST_CONTEXT_STORE_KEY = /* @__PURE__ */ Symbol.for("farm.requestContextStore");
1759
- function getRequestContextStore() {
1760
- const globalState2 = globalThis;
1761
- if (!globalState2[REQUEST_CONTEXT_STORE_KEY]) {
1762
- globalState2[REQUEST_CONTEXT_STORE_KEY] = /* @__PURE__ */ new WeakMap();
1763
- }
1764
- return globalState2[REQUEST_CONTEXT_STORE_KEY];
1765
- }
1766
- __name(getRequestContextStore, "getRequestContextStore");
1767
- function getBucket(target) {
1768
- const requestContextStore = getRequestContextStore();
1769
- let bucket = requestContextStore.get(target);
1770
- if (!bucket) {
1771
- bucket = {
1772
- privateData: /* @__PURE__ */ new Map(),
1773
- exposedData: /* @__PURE__ */ new Map()
1774
- };
1775
- requestContextStore.set(target, bucket);
1776
- }
1777
- return bucket;
1778
- }
1779
- __name(getBucket, "getBucket");
1780
- function setRequestContext(target, key, value, options = {}) {
1781
- const bucket = getBucket(target);
1782
- bucket.privateData.set(key, value);
1783
- if (options.exposeToPage) {
1784
- bucket.exposedData.set(key, value);
1785
- }
1786
- }
1787
- __name(setRequestContext, "setRequestContext");
1788
- function copyRequestContext(source, target) {
1789
- const bucket = getRequestContextStore().get(source);
1790
- if (!bucket || source === target) return;
1791
- for (const [key, value] of bucket.privateData) {
1792
- setRequestContext(target, key, value, { exposeToPage: bucket.exposedData.has(key) });
1793
- }
1794
- }
1795
- __name(copyRequestContext, "copyRequestContext");
18
+ var _chunkI4J452B7cjs = require('../chunk-I4J452B7.cjs');
1796
19
 
1797
- // src/server-http.ts
1798
- var DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT = 1e7;
1799
- var _FarmRequestBodyError = class _FarmRequestBodyError extends Error {
1800
- constructor(code, status, message) {
1801
- super(message);
1802
- this.name = "FarmRequestBodyError";
1803
- this.code = code;
1804
- this.status = status;
1805
- }
1806
- };
1807
- __name(_FarmRequestBodyError, "FarmRequestBodyError");
1808
- var FarmRequestBodyError = _FarmRequestBodyError;
1809
- async function bufferFarmRequestBody(request, limit) {
1810
- if (request.method === "GET" || request.method === "HEAD" || request.body === null) {
1811
- return request;
1812
- }
1813
- const bytes = await readFarmRequestBody(request, limit);
1814
- const body = new Uint8Array(bytes.byteLength);
1815
- body.set(bytes);
1816
- const buffered = new Request(request, {
1817
- // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.
1818
- body: body.buffer
1819
- });
1820
- copyRequestContext(request, buffered);
1821
- return buffered;
1822
- }
1823
- __name(bufferFarmRequestBody, "bufferFarmRequestBody");
1824
- async function readFarmRequestBody(request, limit) {
1825
- try {
1826
- validateContentLength(request.headers.get("content-length"), limit);
1827
- } catch (error) {
1828
- void request.body?.cancel(error).catch(() => {
1829
- });
1830
- throw error;
1831
- }
1832
- throwIfAborted(request.signal);
1833
- if (!request.body) return new Uint8Array();
1834
- const reader = request.body.getReader();
1835
- const chunks = [];
1836
- let total = 0;
1837
- const cancelBodyRead = /* @__PURE__ */ __name(() => {
1838
- void reader.cancel(request.signal.reason).catch(() => {
1839
- });
1840
- }, "cancelBodyRead");
1841
- request.signal.addEventListener("abort", cancelBodyRead, { once: true });
1842
- try {
1843
- while (true) {
1844
- throwIfAborted(request.signal);
1845
- const { done, value } = await reader.read();
1846
- throwIfAborted(request.signal);
1847
- if (done) break;
1848
- if (!value) continue;
1849
- total += value.byteLength;
1850
- if (total > limit) {
1851
- const error = new FarmRequestBodyError("BODY_TOO_LARGE", 413, "Request body is too large");
1852
- void reader.cancel(error).catch(() => {
1853
- });
1854
- throw error;
1855
- }
1856
- chunks.push(value);
1857
- }
1858
- } catch (error) {
1859
- if (request.signal.aborted) throwIfAborted(request.signal);
1860
- throw error;
1861
- } finally {
1862
- request.signal.removeEventListener("abort", cancelBodyRead);
1863
- reader.releaseLock();
1864
- }
1865
- const body = new Uint8Array(total);
1866
- let offset = 0;
1867
- for (const chunk of chunks) {
1868
- body.set(chunk, offset);
1869
- offset += chunk.byteLength;
1870
- }
1871
- return body;
1872
- }
1873
- __name(readFarmRequestBody, "readFarmRequestBody");
1874
- function createFarmRequestBodyErrorResponse(error) {
1875
- if (!(error instanceof FarmRequestBodyError)) return null;
1876
- return new Response(error.status === 413 ? "Payload Too Large" : "Bad Request", {
1877
- status: error.status,
1878
- headers: {
1879
- "cache-control": "no-store",
1880
- "content-type": "text/plain; charset=utf-8",
1881
- "x-content-type-options": "nosniff"
1882
- }
1883
- });
1884
- }
1885
- __name(createFarmRequestBodyErrorResponse, "createFarmRequestBodyErrorResponse");
1886
- function validateContentLength(value, limit) {
1887
- const contentLength = value?.trim();
1888
- if (!contentLength) return;
1889
- if (!/^\d+$/.test(contentLength)) {
1890
- throw new FarmRequestBodyError("INVALID_CONTENT_LENGTH", 400, "Invalid content-length header");
1891
- }
1892
- if (Number(contentLength) > limit) {
1893
- throw new FarmRequestBodyError("BODY_TOO_LARGE", 413, "Request body is too large");
1894
- }
1895
- }
1896
- __name(validateContentLength, "validateContentLength");
1897
- function throwIfAborted(signal) {
1898
- if (!signal.aborted) return;
1899
- if (signal.reason !== void 0) throw signal.reason;
1900
- throw new DOMException("The operation was aborted", "AbortError");
1901
- }
1902
- __name(throwIfAborted, "throwIfAborted");
1903
20
 
1904
- // src/api/config.ts
1905
- var DEFAULT_FARM_API_BASE_PATH = "/api";
1906
- function normalizeFarmAPIBasePath(value) {
1907
- const hasUnstableCharacters = /* @__PURE__ */ __name((candidate) => candidate.includes("\\") || Array.from(candidate).some((character) => {
1908
- const code = character.charCodeAt(0);
1909
- return code <= 31 || code >= 127 && code <= 159;
1910
- }), "hasUnstableCharacters");
1911
- if (hasUnstableCharacters(value)) {
1912
- throw new Error("Farm api.basePath cannot contain backslashes or control characters.");
1913
- }
1914
- const path = value.trim();
1915
- if (!path) {
1916
- throw new Error("Farm api.basePath cannot be empty.");
1917
- }
1918
- if (path.includes("?") || path.includes("#")) {
1919
- throw new Error("Farm api.basePath cannot contain a query string or hash.");
1920
- }
1921
- if (path.startsWith("//")) {
1922
- throw new Error('Farm api.basePath must be a pathname such as "/api", not a URL.');
1923
- }
1924
- for (const segment of path.split("/")) {
1925
- let decoded = segment;
1926
- try {
1927
- decoded = decodeURIComponent(segment);
1928
- } catch {
1929
- }
1930
- if (hasUnstableCharacters(decoded)) {
1931
- throw new Error("Farm api.basePath cannot contain backslashes or control characters.");
1932
- }
1933
- if (decoded.includes("/")) {
1934
- throw new Error("Farm api.basePath cannot contain percent-encoded path separators.");
1935
- }
1936
- if (decoded === "." || decoded === "..") {
1937
- throw new Error('Farm api.basePath cannot contain "." or ".." path segments.');
1938
- }
1939
- }
1940
- const normalized = `/${path.replace(/^\/+|\/+$/g, "")}`;
1941
- return normalized === "/" ? "/" : normalized;
1942
- }
1943
- __name(normalizeFarmAPIBasePath, "normalizeFarmAPIBasePath");
21
+ var _chunkWMAPPDMMcjs = require('../chunk-WMAPPDMM.cjs');
22
+ require('../chunk-TKJZFIML.cjs');
23
+ require('../chunk-EM6SBQKM.cjs');
1944
24
 
1945
- // src/api/server-path.ts
1946
- function resolveFarmAPICanonicalPathname(pathname, serverBasePath = DEFAULT_FARM_API_BASE_PATH) {
1947
- const basePath = normalizeFarmAPIBasePath(serverBasePath);
1948
- if (basePath === DEFAULT_FARM_API_BASE_PATH) return pathname;
1949
- if (basePath === "/") {
1950
- return pathname === "/" ? DEFAULT_FARM_API_BASE_PATH : `${DEFAULT_FARM_API_BASE_PATH}${pathname.startsWith("/") ? pathname : `/${pathname}`}`;
1951
- }
1952
- if (pathname === basePath) return DEFAULT_FARM_API_BASE_PATH;
1953
- if (pathname.startsWith(`${basePath}/`)) {
1954
- return `${DEFAULT_FARM_API_BASE_PATH}${pathname.slice(basePath.length)}`;
1955
- }
1956
- return pathname;
1957
- }
1958
- __name(resolveFarmAPICanonicalPathname, "resolveFarmAPICanonicalPathname");
1959
25
 
1960
- // src/api/route-schema.ts
1961
- async function parseRouteSchema(schema, value) {
1962
- if (schema.parseAsync) return schema.parseAsync(value);
1963
- if (schema["~standard"]) {
1964
- const result = await schema["~standard"].validate(value);
1965
- if (result.issues)
1966
- throw Object.assign(new Error("Validation failed"), { issues: result.issues });
1967
- return result.value;
1968
- }
1969
- if (schema.parse) return schema.parse(value);
1970
- throw new TypeError("Route validators must implement Standard Schema or parse().");
1971
- }
1972
- __name(parseRouteSchema, "parseRouteSchema");
26
+ var _chunkG7HXGLECcjs = require('../chunk-G7HXGLEC.cjs');
27
+ require('../chunk-ARJWXNQL.cjs');
28
+ require('../chunk-S3A45T7F.cjs');
29
+ require('../chunk-H6G5INWM.cjs');
30
+ require('../chunk-ZEG3OPIB.cjs');
31
+ require('../chunk-LIUGYUX3.cjs');
32
+ require('../chunk-E3UK5IIB.cjs');
33
+ require('../chunk-5ZSWG4UX.cjs');
34
+ require('../chunk-U4KT7QP3.cjs');
35
+ require('../chunk-NO3WWW3N.cjs');
36
+ require('../chunk-S3JO3N4H.cjs');
1973
37
 
1974
- // src/response-body.ts
1975
- function omitFarmResponseBody(response) {
1976
- if (response.body) {
1977
- void response.body.cancel().catch(() => void 0);
1978
- }
1979
- return new Response(null, {
1980
- status: response.status,
1981
- statusText: response.statusText,
1982
- headers: response.headers
1983
- });
1984
- }
1985
- __name(omitFarmResponseBody, "omitFarmResponseBody");
1986
38
 
1987
- // src/api/route-shape.ts
1988
- function registerAPIRouteShape(shapes, routePath, filePath, source) {
1989
- assertUniqueRouteParameters(routePath, "api");
1990
- const shape = getRoutePatternShape(routePath, "api");
1991
- const existing = shapes.get(shape);
1992
- const replacesPath = existing && existing.routePath !== routePath;
1993
- if (replacesPath && existing.source === source) {
1994
- throw new AmbiguousRouteError(
1995
- `Ambiguous API routes "${existing.routePath}" and "${routePath}" match the same URLs. Found ${existing.filePath} and ${filePath}. Keep only one route for this URL shape.`
1996
- );
1997
- }
1998
- shapes.set(shape, { routePath, source, filePath });
1999
- return replacesPath ? existing.routePath : void 0;
2000
- }
2001
- __name(registerAPIRouteShape, "registerAPIRouteShape");
2002
39
 
2003
- // src/api/route.ts
2004
- var unavailablePluginLocalAPI = Object.freeze({
2005
- available: false,
2006
- get() {
2007
- return void 0;
2008
- },
2009
- list() {
2010
- return [];
2011
- }
2012
- });
2013
- function createRouteFactory() {
2014
- return createRouteFactoryAt("");
2015
- }
2016
- __name(createRouteFactory, "createRouteFactory");
2017
- function createRouteFactoryAt(prefix) {
2018
- const factory = {
2019
- scope(child) {
2020
- return createRouteFactoryAt(joinRoutePath(prefix, child));
2021
- }
2022
- };
2023
- for (const method of [
2024
- "GET",
2025
- "HEAD",
2026
- "QUERY",
2027
- "POST",
2028
- "PUT",
2029
- "PATCH",
2030
- "DELETE",
2031
- "OPTIONS"
2032
- ]) {
2033
- factory[method.toLowerCase()] = (child, options) => {
2034
- const path = joinRoutePath(prefix, child);
2035
- const input = options.input ?? {};
2036
- const endpoint = createEndpoint(
2037
- path,
2038
- {
2039
- method,
2040
- body: input.body,
2041
- query: input.query,
2042
- headers: input.headers,
2043
- middleware: options.middleware,
2044
- mcp: options.mcp
2045
- },
2046
- (ctx) => options.handler(ctx.request, {
2047
- input: { body: ctx.body, query: ctx.query, headers: ctx.headers, params: ctx.params },
2048
- params: ctx.params,
2049
- context: ctx.context
2050
- })
2051
- );
2052
- endpoint.__types.params = input.params;
2053
- endpoint.__output = options.output;
2054
- return Object.freeze({ path, method, endpoint });
2055
- };
2056
- }
2057
- return Object.freeze(factory);
2058
- }
2059
- __name(createRouteFactoryAt, "createRouteFactoryAt");
2060
- function joinRoutePath(prefix, child) {
2061
- if (typeof child !== "string") throw new TypeError("Route paths must be strings.");
2062
- const path = child === "" ? prefix : `${prefix}/${child.replace(/^\//, "")}`;
2063
- if (!(path === "/api" || path.startsWith("/api/")) || /[?#]|\/\/|\/$/.test(path)) {
2064
- throw new TypeError(
2065
- `Plugin route "${path}" must be a canonical /api path without a query, hash, or empty segment.`
2066
- );
2067
- }
2068
- assertBrowserStableRoutePath(path);
2069
- assertUniqueRouteParameters(path, "api");
2070
- getRoutePatternShape(path, "api");
2071
- for (const segment of path.split("/")) {
2072
- if (["__proto__", "constructor", "prototype", "$params"].includes(segment)) {
2073
- throw new TypeError(`Route segment "${segment}" is reserved.`);
2074
- }
2075
- }
2076
- return path;
2077
- }
2078
- __name(joinRoutePath, "joinRoutePath");
2079
- function resolvePluginRoutes(plugins = [], context2 = {}) {
2080
- return plugins.flatMap((plugin) => {
2081
- if (!plugin.routes) return [];
2082
- const routes = plugin.routes({
2083
- route: createRouteFactory(),
2084
- api: context2.api ?? unavailablePluginLocalAPI
2085
- });
2086
- if (!Array.isArray(routes))
2087
- throw new TypeError(`Plugin "${plugin.name}" routes must return an array synchronously.`);
2088
- for (const route of routes) {
2089
- if (!route || joinRoutePath("", route.path) !== route.path || typeof route.endpoint !== "function" || !["GET", "HEAD", "QUERY", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"].includes(
2090
- route.method
2091
- )) {
2092
- throw new TypeError(`Plugin "${plugin.name}" returned an invalid API route.`);
2093
- }
2094
- }
2095
- return routes;
2096
- });
2097
- }
2098
- __name(resolvePluginRoutes, "resolvePluginRoutes");
2099
40
 
2100
- // src/api/plugin-route-runtime.ts
2101
- function mergePluginAPIRoutes(existing, plugins, expected, options = {}) {
2102
- const routes = /* @__PURE__ */ new Map();
2103
- const shapes = /* @__PURE__ */ new Map();
2104
- for (const route of existing) {
2105
- registerAPIRouteShape(shapes, route.path, route.filePath || route.path, "app");
2106
- routes.set(route.path, {
2107
- ...route,
2108
- filePath: route.filePath || "",
2109
- methods: [...route.methods],
2110
- endpoints: { ...route.endpoints }
2111
- });
2112
- }
2113
- const api = createPluginLocalAPI(existing, options.bodySizeLimit);
2114
- for (const definition of resolvePluginRoutes(plugins, { api })) {
2115
- registerAPIRouteShape(shapes, definition.path, `plugin:${definition.path}`, "app");
2116
- let route = routes.get(definition.path);
2117
- if (route?.methods.includes(definition.method)) {
2118
- throw new Error(
2119
- `Duplicate API route for ${definition.method} ${definition.path}. Plugin routes cannot override app or other plugin endpoints.`
2120
- );
2121
- }
2122
- if (!route) {
2123
- route = { path: definition.path, filePath: "", methods: [], endpoints: {} };
2124
- routes.set(definition.path, route);
2125
- }
2126
- route.methods.push(definition.method);
2127
- route.pluginMethods = [...route.pluginMethods ?? [], definition.method];
2128
- route.endpoints[definition.method] = definition.endpoint;
2129
- }
2130
- const result = [...routes.values()];
2131
- if (expected) {
2132
- const signature = /* @__PURE__ */ __name((entries) => entries.map(({ path, methods }) => `${path}:${[...methods].sort().join(",")}`).sort().join("\n"), "signature");
2133
- const actualSignature = signature(result);
2134
- const expectedSignature = signature(expected);
2135
- if (actualSignature !== expectedSignature) {
2136
- throw new Error(
2137
- `Plugin API routes changed between build and runtime. Route paths and methods must be stable across environments; rebuild the app.
2138
- Expected:
2139
- ${expectedSignature || "(none)"}
2140
- Received:
2141
- ${actualSignature || "(none)"}`
2142
- );
2143
- }
2144
- }
2145
- return result;
2146
- }
2147
- __name(mergePluginAPIRoutes, "mergePluginAPIRoutes");
2148
- function createPluginLocalAPI(routes, bodySizeLimit) {
2149
- const endpoints = /* @__PURE__ */ new Map();
2150
- for (const route of routes) {
2151
- for (const method of route.methods) {
2152
- const normalizedMethod = method.toUpperCase();
2153
- const endpoint = route.endpoints[normalizedMethod];
2154
- if (typeof endpoint !== "function") continue;
2155
- const descriptor = Object.freeze({
2156
- path: route.path,
2157
- method: normalizedMethod,
2158
- input: Object.freeze({
2159
- body: endpoint.__types?.body,
2160
- query: endpoint.__types?.query,
2161
- params: endpoint.__types?.params,
2162
- headers: endpoint.__types?.headers
2163
- }),
2164
- output: endpoint.__output,
2165
- mcp: endpoint.__mcp === true ? true : endpoint.__mcp ? Object.freeze({ ...endpoint.__mcp }) : void 0,
2166
- invoke(request, params = {}) {
2167
- return invokeAPIRouteEndpoint(endpoint, request, { ...params }, bodySizeLimit);
2168
- }
2169
- });
2170
- endpoints.set(`${normalizedMethod} ${route.path}`, descriptor);
2171
- }
2172
- }
2173
- const listedEndpoints = Object.freeze(Array.from(endpoints.values()));
2174
- return Object.freeze({
2175
- available: true,
2176
- get(method, path) {
2177
- return endpoints.get(`${method.toUpperCase()} ${path}`);
2178
- },
2179
- list() {
2180
- return listedEndpoints;
2181
- }
2182
- });
2183
- }
2184
- __name(createPluginLocalAPI, "createPluginLocalAPI");
2185
41
 
2186
- // src/api/route-pattern.ts
2187
- var compiledEntries = /* @__PURE__ */ new WeakMap();
2188
- function createStaticAPIRouteMatcher(routes) {
2189
- const table = new Map(routes.map((route) => [route.path, Object.freeze({ ...route })]));
2190
- const root = { children: /* @__PURE__ */ new Map(), candidates: [] };
2191
- let order = 0;
2192
- for (const route of table.values()) {
2193
- const compiled = compileRouteEntry(route.path);
2194
- let node = root;
2195
- for (const segment of compiled.segments) {
2196
- if (segment.dynamic) break;
2197
- let child = node.children.get(segment.value);
2198
- if (!child) {
2199
- child = { children: /* @__PURE__ */ new Map(), candidates: [] };
2200
- node.children.set(segment.value, child);
2201
- }
2202
- node = child;
2203
- }
2204
- node.candidates.push({ route, compiled, order: order++ });
2205
- }
2206
- return (pathname) => {
2207
- const exactRoute = table.get(pathname);
2208
- if (exactRoute) return { route: exactRoute, params: {} };
2209
- const normalizedPathname = normalizePathname(pathname);
2210
- if (normalizedPathname !== pathname) {
2211
- const normalizedRoute = table.get(normalizedPathname);
2212
- if (normalizedRoute) return { route: normalizedRoute, params: {} };
2213
- }
2214
- const segments = getPathSegments(normalizedPathname).map(decodePathSegment);
2215
- let best;
2216
- let bestMatch = null;
2217
- let node = root;
2218
- let depth = 0;
2219
- while (node) {
2220
- for (const candidate of node.candidates) {
2221
- const params = matchRouteEntry(candidate.compiled, segments);
2222
- if (!params) continue;
2223
- const comparison = best ? compareRouteSpecificity(candidate.compiled.specificity, best.compiled.specificity) : -1;
2224
- if (comparison < 0 || comparison === 0 && candidate.order < best.order) {
2225
- best = candidate;
2226
- bestMatch = { route: candidate.route, params };
2227
- }
2228
- }
2229
- node = depth < segments.length ? node.children.get(segments[depth++]) : void 0;
2230
- }
2231
- return bestMatch;
2232
- };
2233
- }
2234
- __name(createStaticAPIRouteMatcher, "createStaticAPIRouteMatcher");
2235
- function matchAPIRoute(routes, pathname) {
2236
- const exactRoute = routes.get(pathname);
2237
- if (exactRoute) return { route: exactRoute, params: {} };
2238
- const normalizedPathname = normalizePathname(pathname);
2239
- if (normalizedPathname !== pathname) {
2240
- const normalizedRoute = routes.get(normalizedPathname);
2241
- if (normalizedRoute) return { route: normalizedRoute, params: {} };
2242
- }
2243
- const pathnameSegments = getPathSegments(normalizedPathname).map(decodePathSegment);
2244
- let bestMatch = null;
2245
- let bestSpecificity = null;
2246
- for (const route of routes.values()) {
2247
- const routePath = route.path;
2248
- let entry = compiledEntries.get(route);
2249
- if (!entry || entry.path !== routePath) {
2250
- entry = compileRouteEntry(routePath);
2251
- compiledEntries.set(route, entry);
2252
- }
2253
- const params = matchRouteEntry(entry, pathnameSegments);
2254
- if (!params) continue;
2255
- if (bestSpecificity === null || compareRouteSpecificity(entry.specificity, bestSpecificity) < 0) {
2256
- bestMatch = { route, params };
2257
- bestSpecificity = entry.specificity;
2258
- }
2259
- }
2260
- return bestMatch;
2261
- }
2262
- __name(matchAPIRoute, "matchAPIRoute");
2263
- function compileRouteEntry(path) {
2264
- const segments = getPathSegments(path).map((segment) => {
2265
- const dynamic = parseDynamicSegment(segment);
2266
- return dynamic ? { dynamic } : { value: decodePathSegment(segment) };
2267
- });
2268
- return {
2269
- path,
2270
- segments,
2271
- specificity: segments.map((segment) => {
2272
- const dynamic = segment.dynamic;
2273
- if (!dynamic) return "static";
2274
- if (!dynamic.catchAll) return "dynamic";
2275
- return dynamic.optional ? "optional-catch-all" : "catch-all";
2276
- })
2277
- };
2278
- }
2279
- __name(compileRouteEntry, "compileRouteEntry");
2280
- function matchRouteEntry(entry, pathnameSegments) {
2281
- const params = {};
2282
- let pathIndex = 0;
2283
- for (const routeSegment of entry.segments) {
2284
- const dynamicSegment = routeSegment.dynamic;
2285
- if (dynamicSegment?.catchAll) {
2286
- const remainingSegments = pathnameSegments.slice(pathIndex);
2287
- if (remainingSegments.length === 0 && !dynamicSegment.optional) {
2288
- return null;
2289
- }
2290
- if (remainingSegments.length > 0) {
2291
- params[dynamicSegment.name] = remainingSegments;
2292
- }
2293
- pathIndex = pathnameSegments.length;
2294
- continue;
2295
- }
2296
- const pathnameSegment = pathnameSegments[pathIndex];
2297
- if (pathnameSegment === void 0) {
2298
- return null;
2299
- }
2300
- if (dynamicSegment) {
2301
- params[dynamicSegment.name] = pathnameSegment;
2302
- pathIndex++;
2303
- continue;
2304
- }
2305
- if (routeSegment.value !== pathnameSegment) {
2306
- return null;
2307
- }
2308
- pathIndex++;
2309
- }
2310
- return pathIndex === pathnameSegments.length ? params : null;
2311
- }
2312
- __name(matchRouteEntry, "matchRouteEntry");
2313
- function getPathSegments(pathname) {
2314
- return normalizePathname(pathname).split("/").filter((segment) => segment.length > 0);
2315
- }
2316
- __name(getPathSegments, "getPathSegments");
2317
- function normalizePathname(pathname) {
2318
- if (pathname.length > 1 && pathname.endsWith("/")) {
2319
- return pathname.replace(/\/+$/, "");
2320
- }
2321
- return pathname;
2322
- }
2323
- __name(normalizePathname, "normalizePathname");
2324
- function parseDynamicSegment(segment) {
2325
- const optionalCatchAll = segment.match(/^\[\[\.\.\.(.+)\]\]$/);
2326
- if (optionalCatchAll?.[1]) {
2327
- return { name: optionalCatchAll[1], catchAll: true, optional: true };
2328
- }
2329
- const catchAll = segment.match(/^\[\.\.\.(.+)\]$/);
2330
- if (catchAll?.[1]) {
2331
- return { name: catchAll[1], catchAll: true, optional: false };
2332
- }
2333
- const dynamic = segment.match(/^\[(.+)\]$/);
2334
- if (dynamic?.[1]) {
2335
- return { name: dynamic[1], catchAll: false, optional: false };
2336
- }
2337
- return null;
2338
- }
2339
- __name(parseDynamicSegment, "parseDynamicSegment");
2340
- function decodePathSegment(segment) {
2341
- try {
2342
- return decodeURIComponent(segment);
2343
- } catch {
2344
- return segment;
2345
- }
2346
- }
2347
- __name(decodePathSegment, "decodePathSegment");
2348
42
 
2349
- // src/api/runtime.ts
2350
- var API_ROUTE_METHODS = [
2351
- "GET",
2352
- "HEAD",
2353
- "QUERY",
2354
- "POST",
2355
- "PUT",
2356
- "DELETE",
2357
- "PATCH",
2358
- "OPTIONS"
2359
- ];
2360
- function resolveAPIRouteEndpoint(route, method) {
2361
- const normalizedMethod = method.toUpperCase();
2362
- return route.endpoints[normalizedMethod] ?? (normalizedMethod === "HEAD" ? route.endpoints.GET : void 0);
2363
- }
2364
- __name(resolveAPIRouteEndpoint, "resolveAPIRouteEndpoint");
2365
- function getAllowedAPIRouteMethods(route) {
2366
- const methods = [...route.methods];
2367
- const getIndex = methods.indexOf("GET");
2368
- if (getIndex >= 0 && !methods.includes("HEAD")) {
2369
- methods.splice(getIndex + 1, 0, "HEAD");
2370
- }
2371
- return methods;
2372
- }
2373
- __name(getAllowedAPIRouteMethods, "getAllowedAPIRouteMethods");
2374
- function matchAPIRouteAtBasePath(routes, pathname, serverBasePath = DEFAULT_FARM_API_BASE_PATH) {
2375
- const directMatch = matchAPIRoute(routes, pathname);
2376
- if (directMatch) return directMatch;
2377
- const canonicalPathname = resolveFarmAPICanonicalPathname(pathname, serverBasePath);
2378
- return canonicalPathname === pathname ? null : matchAPIRoute(routes, canonicalPathname);
2379
- }
2380
- __name(matchAPIRouteAtBasePath, "matchAPIRouteAtBasePath");
2381
- function createStaticAPIRouteMatcherAtBasePath(routes, serverBasePath = DEFAULT_FARM_API_BASE_PATH) {
2382
- const match = createStaticAPIRouteMatcher(routes);
2383
- return (pathname) => {
2384
- const directMatch = match(pathname);
2385
- if (directMatch) return directMatch;
2386
- const canonicalPathname = resolveFarmAPICanonicalPathname(pathname, serverBasePath);
2387
- return canonicalPathname === pathname ? null : match(canonicalPathname);
2388
- };
2389
- }
2390
- __name(createStaticAPIRouteMatcherAtBasePath, "createStaticAPIRouteMatcherAtBasePath");
2391
- function isFarmAPIPathname(pathname, serverBasePath = DEFAULT_FARM_API_BASE_PATH) {
2392
- const basePath = normalizeFarmAPIBasePath(serverBasePath);
2393
- return basePath !== "/" && (pathname === basePath || pathname.startsWith(`${basePath}/`));
2394
- }
2395
- __name(isFarmAPIPathname, "isFarmAPIPathname");
2396
- async function invokeAPIRouteEndpoint(endpoint, request, params = {}, bodySizeLimit = DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT) {
2397
- try {
2398
- request = await bufferFarmRequestBody(request, bodySizeLimit);
2399
- } catch (error) {
2400
- const response2 = createFarmRequestBodyErrorResponse(error);
2401
- if (response2) return response2;
2402
- throw error;
2403
- }
2404
- const response = await _runWithCurrentRequest(
2405
- request,
2406
- () => invokeAPIRouteEndpointInContext(endpoint, request, params)
2407
- );
2408
- if (request.method.toUpperCase() !== "HEAD") {
2409
- return response;
2410
- }
2411
- return omitFarmResponseBody(response);
2412
- }
2413
- __name(invokeAPIRouteEndpoint, "invokeAPIRouteEndpoint");
2414
- async function invokeAPIRouteEndpointInContext(endpoint, request, params) {
2415
- const queryContentTypeError = validateQueryContentType(request);
2416
- if (queryContentTypeError) {
2417
- return queryContentTypeError;
2418
- }
2419
- const farmHandler = endpoint.__handler || null;
2420
- if (!farmHandler) {
2421
- const result = await endpoint(request, {
2422
- params: Promise.resolve(params)
2423
- });
2424
- return normalizeRouteResponse(result);
2425
- }
2426
- const url = new URL(request.url);
2427
- const query = {
2428
- ...searchParamsToObject(url.searchParams)
2429
- };
2430
- let body = void 0;
2431
- if (request.method.toUpperCase() !== "GET" && request.method.toUpperCase() !== "HEAD") {
2432
- const parsedBody = await readRequestBody(request);
2433
- if (parsedBody.error) return parsedBody.error;
2434
- body = parsedBody.body;
2435
- }
2436
- const headers = Object.fromEntries(request.headers.entries());
2437
- const types = endpoint.__types || {};
2438
- const queryValidation = await validateInput(types.query, query, "Invalid query parameters");
2439
- if (queryValidation instanceof Response) {
2440
- return queryValidation;
2441
- }
2442
- const bodyValidation = await validateInput(types.body, body, "Invalid request body");
2443
- if (bodyValidation instanceof Response) {
2444
- return bodyValidation;
2445
- }
2446
- const headersValidation = await validateInput(types.headers, headers, "Invalid request headers");
2447
- if (headersValidation instanceof Response) {
2448
- return headersValidation;
2449
- }
2450
- const paramsValidation = await validateInput(types.params, params, "Invalid route parameters");
2451
- if (paramsValidation instanceof Response) return paramsValidation;
2452
- const handlerContext = {
2453
- query: queryValidation,
2454
- body: bodyValidation,
2455
- headers: headersValidation,
2456
- request,
2457
- context: {},
2458
- params: paramsValidation
2459
- };
2460
- let execution;
2461
- try {
2462
- execution = typeof endpoint.__farmInvoke === "function" ? await endpoint.__farmInvoke(handlerContext) : {
2463
- result: await farmHandler(handlerContext),
2464
- context: handlerContext.context,
2465
- handlerExecuted: true,
2466
- invalidations: []
2467
- };
2468
- } catch (error) {
2469
- if (isEndpointFailure(error)) {
2470
- return createEndpointFailureResponse(error);
2471
- }
2472
- throw error;
2473
- }
2474
- if (execution.handlerExecuted && endpoint.__output && !isWebResponse(execution.result)) {
2475
- try {
2476
- execution.result = await parseRouteSchema(endpoint.__output, execution.result);
2477
- } catch {
2478
- throw new Error("API route returned a value that does not match its output schema.");
2479
- }
2480
- }
2481
- const response = normalizeRouteResponse(execution.result);
2482
- return attachEndpointInvalidations(response, execution.invalidations);
2483
- }
2484
- __name(invokeAPIRouteEndpointInContext, "invokeAPIRouteEndpointInContext");
2485
- function validateQueryContentType(request) {
2486
- if (request.method.toUpperCase() !== "QUERY" || request.headers.has("content-type")) {
2487
- return null;
2488
- }
2489
- return new Response(
2490
- JSON.stringify({
2491
- error: "Invalid QUERY request",
2492
- message: "QUERY requests must include a Content-Type header."
2493
- }),
2494
- {
2495
- status: 400,
2496
- headers: { "Content-Type": "application/json" }
2497
- }
2498
- );
2499
- }
2500
- __name(validateQueryContentType, "validateQueryContentType");
2501
- function normalizeRouteResponse(result) {
2502
- if (isWebResponse(result)) {
2503
- return result;
2504
- }
2505
- if (result === void 0) {
2506
- return new Response(null, { status: 204 });
2507
- }
2508
- let body;
2509
- try {
2510
- body = JSON.stringify(result);
2511
- } catch (error) {
2512
- const serializationError = new TypeError(
2513
- "API route result must be a JSON-serializable value or a Response."
2514
- );
2515
- serializationError.cause = error;
2516
- throw serializationError;
2517
- }
2518
- if (body === void 0) {
2519
- throw new TypeError("API route result must be a JSON-serializable value or a Response.");
2520
- }
2521
- return new Response(body, {
2522
- status: 200,
2523
- headers: { "Content-Type": "application/json" }
2524
- });
2525
- }
2526
- __name(normalizeRouteResponse, "normalizeRouteResponse");
2527
- function isWebResponse(value) {
2528
- return value instanceof Response || typeof value === "object" && value !== null && "headers" in value && "status" in value && typeof value.arrayBuffer === "function";
2529
- }
2530
- __name(isWebResponse, "isWebResponse");
2531
- function attachEndpointInvalidations(response, keys) {
2532
- const existing = decodeFarmCacheInvalidations(
2533
- response.headers.get(FARM_CACHE_INVALIDATION_HEADER)
2534
- );
2535
- const encoded = encodeFarmCacheInvalidations([...existing, ...keys]);
2536
- if (!encoded) return response;
2537
- const headers = new Headers(response.headers);
2538
- headers.set(FARM_CACHE_INVALIDATION_HEADER, encoded);
2539
- return new Response(response.body, {
2540
- status: response.status,
2541
- statusText: response.statusText,
2542
- headers
2543
- });
2544
- }
2545
- __name(attachEndpointInvalidations, "attachEndpointInvalidations");
2546
- function createEndpointFailureResponse(failure) {
2547
- return new Response(
2548
- JSON.stringify({
2549
- error: {
2550
- code: failure.code,
2551
- message: failure.message,
2552
- data: failure.data
2553
- }
2554
- }),
2555
- {
2556
- status: failure.status,
2557
- headers: {
2558
- "cache-control": "no-store",
2559
- "content-type": "application/json"
2560
- }
2561
- }
2562
- );
2563
- }
2564
- __name(createEndpointFailureResponse, "createEndpointFailureResponse");
2565
- async function readRequestBody(request) {
2566
- const contentType = request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
2567
- if (contentType === "multipart/form-data") {
2568
- try {
2569
- return { body: formDataToObject(await request.clone().formData()) };
2570
- } catch {
2571
- return invalidRequestBody("The request body is not valid multipart form data.");
2572
- }
2573
- }
2574
- let text;
2575
- try {
2576
- text = await request.clone().text();
2577
- } catch {
2578
- if (contentType === "application/json" || contentType?.endsWith("+json")) {
2579
- return invalidRequestBody("The request body is not valid JSON.");
2580
- }
2581
- if (contentType === "application/x-www-form-urlencoded") {
2582
- return invalidRequestBody("The request body is not valid URL-encoded form data.");
2583
- }
2584
- return { body: void 0 };
2585
- }
2586
- if (contentType === "application/json" || contentType?.endsWith("+json")) {
2587
- if (!text && request.method.toUpperCase() === "QUERY") {
2588
- return { body: void 0 };
2589
- }
2590
- try {
2591
- return { body: JSON.parse(text) };
2592
- } catch {
2593
- return invalidRequestBody("The request body is not valid JSON.");
2594
- }
2595
- }
2596
- if (contentType === "application/x-www-form-urlencoded") {
2597
- return { body: searchParamsToObject(new URLSearchParams(text)) };
2598
- }
2599
- if (!text) return { body: void 0 };
2600
- if (contentType === void 0) {
2601
- try {
2602
- return { body: JSON.parse(text) };
2603
- } catch {
2604
- return { body: void 0 };
2605
- }
2606
- }
2607
- return { body: void 0 };
2608
- }
2609
- __name(readRequestBody, "readRequestBody");
2610
- function invalidRequestBody(message) {
2611
- return {
2612
- error: new Response(
2613
- JSON.stringify({
2614
- error: "Invalid request body",
2615
- message
2616
- }),
2617
- {
2618
- status: 400,
2619
- headers: { "Content-Type": "application/json" }
2620
- }
2621
- )
2622
- };
2623
- }
2624
- __name(invalidRequestBody, "invalidRequestBody");
2625
- function formDataToObject(formData) {
2626
- return entriesToObject(formData.entries());
2627
- }
2628
- __name(formDataToObject, "formDataToObject");
2629
- function searchParamsToObject(searchParams) {
2630
- return entriesToObject(searchParams.entries());
2631
- }
2632
- __name(searchParamsToObject, "searchParamsToObject");
2633
- function entriesToObject(entries) {
2634
- const output = /* @__PURE__ */ Object.create(null);
2635
- for (const [key, value] of entries) {
2636
- if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
2637
- const current = output[key];
2638
- if (current === void 0) {
2639
- output[key] = value;
2640
- } else if (Array.isArray(current)) {
2641
- current.push(value);
2642
- } else {
2643
- output[key] = [current, value];
2644
- }
2645
- }
2646
- return output;
2647
- }
2648
- __name(entriesToObject, "entriesToObject");
2649
- async function validateInput(schema, value, error) {
2650
- if (!schema) return value;
2651
- try {
2652
- return await parseRouteSchema(schema, value);
2653
- } catch (validationError) {
2654
- return Response.json(
2655
- {
2656
- error,
2657
- details: (validationError.issues || validationError.errors || []).map((issue) => ({
2658
- path: issue.path,
2659
- message: issue.message,
2660
- code: issue.code
2661
- }))
2662
- },
2663
- { status: 400 }
2664
- );
2665
- }
2666
- }
2667
- __name(validateInput, "validateInput");
2668
- // Annotate the CommonJS export names for ESM import in node:
2669
- 0 && (module.exports = {
2670
- API_ROUTE_METHODS,
2671
- createEndpointFailureResponse,
2672
- createStaticAPIRouteMatcherAtBasePath,
2673
- getAllowedAPIRouteMethods,
2674
- invokeAPIRouteEndpoint,
2675
- isFarmAPIPathname,
2676
- isWebResponse,
2677
- matchAPIRoute,
2678
- matchAPIRouteAtBasePath,
2679
- mergePluginAPIRoutes,
2680
- normalizeRouteResponse,
2681
- parseRouteSchema,
2682
- registerAPIRouteShape,
2683
- resolveAPIRouteEndpoint
2684
- });
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+ exports.API_ROUTE_METHODS = _chunk4PNUXIVUcjs.API_ROUTE_METHODS; exports.createEndpointFailureResponse = _chunk4PNUXIVUcjs.createEndpointFailureResponse; exports.createStaticAPIRouteMatcherAtBasePath = _chunk4PNUXIVUcjs.createStaticAPIRouteMatcherAtBasePath; exports.getAllowedAPIRouteMethods = _chunk4PNUXIVUcjs.getAllowedAPIRouteMethods; exports.invokeAPIRouteEndpoint = _chunk4PNUXIVUcjs.invokeAPIRouteEndpoint; exports.isEndpointFailure = _chunkI4J452B7cjs.isEndpointFailure; exports.isFarmAPIPathname = _chunk4PNUXIVUcjs.isFarmAPIPathname; exports.isWebResponse = _chunk4PNUXIVUcjs.isWebResponse; exports.matchAPIRoute = _chunkG7HXGLECcjs.matchAPIRoute; exports.matchAPIRouteAtBasePath = _chunk4PNUXIVUcjs.matchAPIRouteAtBasePath; exports.mergePluginAPIRoutes = _chunk4PNUXIVUcjs.mergePluginAPIRoutes; exports.normalizeRouteResponse = _chunk4PNUXIVUcjs.normalizeRouteResponse; exports.parseRouteSchema = _chunk4PNUXIVUcjs.parseRouteSchema; exports.registerAPIRouteShape = _chunkWMAPPDMMcjs.registerAPIRouteShape; exports.resolveAPIRouteEndpoint = _chunk4PNUXIVUcjs.resolveAPIRouteEndpoint;