@farm.js/core 0.1.17 → 0.1.19

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