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