@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,1894 +1,26 @@
1
- "use strict";
2
- "use client";
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});"use client";
21
2
 
22
- // src/server-query-client.ts
23
- var server_query_client_exports = {};
24
- __export(server_query_client_exports, {
25
- beginFarmServerQueryAction: () => beginFarmServerQueryAction,
26
- completeFarmServerQueryAction: () => completeFarmServerQueryAction,
27
- fetchServerQuery: () => fetchServerQuery,
28
- prefetchServerQuery: () => prefetchServerQuery,
29
- shouldApplyFarmServerQueryActionResult: () => shouldApplyFarmServerQueryActionResult,
30
- useServerQuery: () => useServerQuery
31
- });
32
- module.exports = __toCommonJS(server_query_client_exports);
33
- var import_react = require("react");
34
3
 
35
- // src/tracing.ts
36
- var import_api = require("@opentelemetry/api");
37
- var FARM_TRACER_NAME = "@farm.js/core";
38
- var ALL_SPAN_KINDS = [
39
- "request",
40
- "render",
41
- "middleware",
42
- "api",
43
- "integration",
44
- "storage",
45
- "ppr",
46
- "build",
47
- "plugin"
48
- ];
49
- var DEFAULT_IGNORED_PATHS = [
50
- "/@vite/",
51
- "/@fs/",
52
- "/@id/",
53
- "/@react-refresh",
54
- "/node_modules/",
55
- "/__vite",
56
- "/.well-known/appspecific/"
57
- ];
58
- var FARM_REQUEST_METHOD_CONTEXT_KEY = (0, import_api.createContextKey)("@farm.js/core/request-method");
59
- var TRACING_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/tracing-runtime/v1");
60
- var runtime = globalThis;
61
- var tracingState = runtime[TRACING_RUNTIME] ?? (runtime[TRACING_RUNTIME] = normalizeFarmTracingConfig(false));
62
- function normalizeFarmTracingConfig(config) {
63
- if (!config) {
64
- return {
65
- enabled: false,
66
- spans: new Set(ALL_SPAN_KINDS),
67
- recordEvents: true,
68
- attributes: {},
69
- ignorePaths: DEFAULT_IGNORED_PATHS
70
- };
71
- }
72
- if (config === true) {
73
- return {
74
- enabled: true,
75
- spans: new Set(ALL_SPAN_KINDS),
76
- recordEvents: true,
77
- attributes: {},
78
- ignorePaths: DEFAULT_IGNORED_PATHS
79
- };
80
- }
81
- return {
82
- enabled: config.enabled ?? true,
83
- spans: new Set(config.spans ?? ALL_SPAN_KINDS),
84
- recordEvents: config.recordEvents ?? true,
85
- attributes: { ...config.attributes },
86
- ignorePaths: [...DEFAULT_IGNORED_PATHS, ...config.ignorePaths ?? []]
87
- };
88
- }
89
- __name(normalizeFarmTracingConfig, "normalizeFarmTracingConfig");
90
- function recordFarmEventTrace(event) {
91
- if (!tracingState.enabled) return void 0;
92
- const activeContext = import_api.context.active();
93
- const activeSpan = import_api.trace.getSpan(activeContext);
94
- const traceContext = getSpanTraceContext(activeSpan);
95
- if (activeSpan && traceContext) {
96
- if (event.type === "route.matched") {
97
- const method = activeContext.getValue(FARM_REQUEST_METHOD_CONTEXT_KEY) ?? "HTTP";
98
- activeSpan.updateName(`${method} ${event.route}`);
99
- activeSpan.setAttribute("http.route", event.route);
100
- activeSpan.setAttribute("farm.route", event.route);
101
- }
102
- if (tracingState.recordEvents) {
103
- activeSpan.addEvent(event.type, toEventAttributes(event), event.timestamp);
104
- }
105
- const error = event.type === "request.error" ? void 0 : getEventError(event);
106
- if (error !== void 0) {
107
- if (event.type === "render.error") {
108
- recordSpanException(activeSpan, error);
109
- } else {
110
- recordSpanError(activeSpan, error);
111
- }
112
- }
113
- }
114
- const completedTraceContext = recordCompletedEventSpan(event, activeContext);
115
- return traceContext ?? completedTraceContext;
116
- }
117
- __name(recordFarmEventTrace, "recordFarmEventTrace");
118
- function recordCompletedEventSpan(event, parentContext) {
119
- const descriptor = getCompletedSpanDescriptor(event);
120
- if (!descriptor || !tracingState.spans.has(descriptor.kind)) return void 0;
121
- const tracer = import_api.trace.getTracer(FARM_TRACER_NAME);
122
- const span = tracer.startSpan(
123
- descriptor.name,
124
- {
125
- kind: import_api.SpanKind.INTERNAL,
126
- startTime: event.timestamp - descriptor.durationMs,
127
- attributes: {
128
- ...tracingState.attributes,
129
- ...toEventAttributes(event),
130
- "farm.event.type": event.type
131
- }
132
- },
133
- parentContext
134
- );
135
- const status = "status" in event && typeof event.status === "number" ? event.status : void 0;
136
- if (status !== void 0) setResponseStatus(span, status);
137
- const error = getEventError(event);
138
- if (error !== void 0) recordSpanError(span, error);
139
- const traceContext = getSpanTraceContext(span);
140
- span.end(event.timestamp);
141
- return traceContext;
142
- }
143
- __name(recordCompletedEventSpan, "recordCompletedEventSpan");
144
- function getCompletedSpanDescriptor(event) {
145
- if (!("durationMs" in event) || typeof event.durationMs !== "number") return void 0;
146
- switch (event.type) {
147
- case "render.complete":
148
- return { kind: "render", name: `farm.render ${event.route}`, durationMs: event.durationMs };
149
- case "render.stream.shellReady":
150
- return {
151
- kind: "render",
152
- name: `farm.render.shell ${event.route}`,
153
- durationMs: event.durationMs
154
- };
155
- case "render.stream.complete":
156
- return {
157
- kind: "render",
158
- name: `farm.render.stream ${event.route}`,
159
- durationMs: event.durationMs
160
- };
161
- case "middleware.complete":
162
- return {
163
- kind: "middleware",
164
- name: `farm.middleware ${event.name ?? event.route ?? "anonymous"}`,
165
- durationMs: event.durationMs
166
- };
167
- case "api.request.complete":
168
- case "api.error":
169
- return {
170
- kind: "api",
171
- name: `farm.api ${event.method} ${event.route}`,
172
- durationMs: event.durationMs
173
- };
174
- case "integration.api.call.complete":
175
- return {
176
- kind: "integration",
177
- name: `farm.integration ${event.integration}.${event.operation}`,
178
- durationMs: event.durationMs
179
- };
180
- case "storage.query.complete":
181
- return {
182
- kind: "storage",
183
- name: `farm.storage ${event.operation}`,
184
- durationMs: event.durationMs
185
- };
186
- case "ppr.refresh.complete":
187
- return {
188
- kind: "ppr",
189
- name: `farm.ppr.refresh ${event.route}`,
190
- durationMs: event.durationMs
191
- };
192
- case "build.complete":
193
- return {
194
- kind: "build",
195
- name: `farm.build${event.target ? ` ${event.target}` : ""}`,
196
- durationMs: event.durationMs
197
- };
198
- case "plugin.hook.complete":
199
- return {
200
- kind: "plugin",
201
- name: `farm.plugin ${event.plugin}.${event.hook}`,
202
- durationMs: event.durationMs
203
- };
204
- default:
205
- return void 0;
206
- }
207
- }
208
- __name(getCompletedSpanDescriptor, "getCompletedSpanDescriptor");
209
- function hashFarmCacheKey(value) {
210
- let hash = 2166136261;
211
- for (let index = 0; index < value.length; index++) {
212
- hash ^= value.charCodeAt(index);
213
- hash = Math.imul(hash, 16777619);
214
- }
215
- return (hash >>> 0).toString(16).padStart(8, "0");
216
- }
217
- __name(hashFarmCacheKey, "hashFarmCacheKey");
218
- function toEventAttributes(event) {
219
- const attributes = {};
220
- const redactKey = typeof event.type === "string" && event.type.startsWith("cache.");
221
- for (const [key, value] of Object.entries(event)) {
222
- if (key === "timestamp" || key === "level" || key === "error" || key === "traceId" || key === "spanId" || key === "traceSampled" || value === void 0) {
223
- continue;
224
- }
225
- if (redactKey && key === "key" && typeof value === "string") {
226
- attributes["farm.key_hash"] = hashFarmCacheKey(value);
227
- continue;
228
- }
229
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
230
- attributes[`farm.${key}`] = value;
231
- } else if (Array.isArray(value)) {
232
- if (value.every((entry) => typeof entry === "string")) {
233
- attributes[`farm.${key}`] = value;
234
- } else if (value.every((entry) => typeof entry === "number")) {
235
- attributes[`farm.${key}`] = value;
236
- } else if (value.every((entry) => typeof entry === "boolean")) {
237
- attributes[`farm.${key}`] = value;
238
- }
239
- }
240
- }
241
- return attributes;
242
- }
243
- __name(toEventAttributes, "toEventAttributes");
244
- function getEventError(event) {
245
- return "error" in event ? event.error : void 0;
246
- }
247
- __name(getEventError, "getEventError");
248
- function recordSpanException(span, error) {
249
- const normalized = error instanceof Error ? error : new Error(String(error));
250
- span.recordException(normalized);
251
- return normalized;
252
- }
253
- __name(recordSpanException, "recordSpanException");
254
- function recordSpanError(span, error) {
255
- const normalized = recordSpanException(span, error);
256
- span.setStatus({ code: import_api.SpanStatusCode.ERROR, message: normalized.message });
257
- }
258
- __name(recordSpanError, "recordSpanError");
259
- function setResponseStatus(span, status) {
260
- span.setAttribute("http.response.status_code", status);
261
- if (status >= 500) {
262
- span.setStatus({ code: import_api.SpanStatusCode.ERROR });
263
- }
264
- }
265
- __name(setResponseStatus, "setResponseStatus");
266
- function getSpanTraceContext(span) {
267
- if (!span) return void 0;
268
- const spanContext = span.spanContext();
269
- if (!(0, import_api.isSpanContextValid)(spanContext)) return void 0;
270
- return {
271
- traceId: spanContext.traceId,
272
- spanId: spanContext.spanId,
273
- traceSampled: (spanContext.traceFlags & 1) === 1
274
- };
275
- }
276
- __name(getSpanTraceContext, "getSpanTraceContext");
4
+ var _chunkC3VRMB6Hcjs = require('./chunk-C3VRMB6H.cjs');
277
5
 
278
- // src/observability.ts
279
- var OBSERVABILITY_RUNTIME = /* @__PURE__ */ Symbol.for("@farm.js/core/observability-runtime/v1");
280
- var runtime2 = globalThis;
281
- var shared = runtime2[OBSERVABILITY_RUNTIME] ?? (runtime2[OBSERVABILITY_RUNTIME] = {
282
- handlers: /* @__PURE__ */ new Set(),
283
- unfilteredHandlers: /* @__PURE__ */ new Set(),
284
- config: { logs: false, handlers: [], tracing: normalizeFarmTracingConfig(false) }
285
- });
286
- var runtimeHandlers = shared.handlers;
287
- var unfilteredRuntimeHandlers = shared.unfilteredHandlers;
288
- var observabilityState = shared.config;
289
- function emitFarmEvent(input) {
290
- const event = {
291
- timestamp: Date.now(),
292
- level: inferFarmEventLevel(input.type),
293
- ...input
294
- };
295
- const traceContext = recordFarmEventTrace(event);
296
- if (traceContext) {
297
- event.traceId = traceContext.traceId;
298
- event.spanId = traceContext.spanId;
299
- event.traceSampled = traceContext.traceSampled;
300
- }
301
- notifyFarmEventHandlers(event, unfilteredRuntimeHandlers);
302
- if (!shouldEmitFarmEvent(event)) return event;
303
- if (observabilityState.logs) {
304
- logFarmEvent(event);
305
- }
306
- notifyFarmEventHandlers(event, [...observabilityState.handlers, ...runtimeHandlers]);
307
- return event;
308
- }
309
- __name(emitFarmEvent, "emitFarmEvent");
310
- function notifyFarmEventHandlers(event, handlers) {
311
- for (const handler of handlers) {
312
- try {
313
- Promise.resolve(handler(event)).catch((error) => {
314
- console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
315
- });
316
- } catch (error) {
317
- console.warn(`[farm:observability] event handler failed: ${formatError(error)}`);
318
- }
319
- }
320
- }
321
- __name(notifyFarmEventHandlers, "notifyFarmEventHandlers");
322
- function shouldEmitFarmEvent(event) {
323
- if (!observabilityState.logs && observabilityState.handlers.length === 0 && runtimeHandlers.size === 0) {
324
- return false;
325
- }
326
- if (observabilityState.events && !observabilityState.events.has(event.type)) {
327
- return false;
328
- }
329
- return true;
330
- }
331
- __name(shouldEmitFarmEvent, "shouldEmitFarmEvent");
332
- function inferFarmEventLevel(type) {
333
- if (type === "error" || type.endsWith(".error") || type.endsWith(".failed")) {
334
- return "error";
335
- }
336
- if (type.endsWith(".bypass") || type.endsWith(".invalidated") || type.endsWith(".stale") || type.endsWith(".notFound")) {
337
- return "warn";
338
- }
339
- if (type.endsWith(".hit") || type.endsWith(".miss") || type.endsWith(".start") || type.endsWith(".shellReady")) {
340
- return "debug";
341
- }
342
- return "info";
343
- }
344
- __name(inferFarmEventLevel, "inferFarmEventLevel");
345
- function logFarmEvent(event) {
346
- const message = `[farm:${event.level}] ${event.type}${formatFarmEventDetails(event)}`;
347
- switch (event.level) {
348
- case "error":
349
- console.error(message);
350
- break;
351
- case "warn":
352
- console.warn(message);
353
- break;
354
- default:
355
- console.log(message);
356
- break;
357
- }
358
- }
359
- __name(logFarmEvent, "logFarmEvent");
360
- function formatFarmEventDetails(event) {
361
- const details = [];
362
- const record = event;
363
- for (const key of [
364
- "route",
365
- "pathname",
366
- "method",
367
- "status",
368
- "key",
369
- "tag",
370
- "path",
371
- "reason",
372
- "durationMs",
373
- "integration",
374
- "server",
375
- "tool",
376
- "outcome",
377
- "operation",
378
- "plugin",
379
- "hook",
380
- "target",
381
- "count"
382
- ]) {
383
- const value = record[key];
384
- if (value !== void 0) {
385
- details.push(`${key}=${formatDetailValue(value)}`);
386
- }
387
- }
388
- return details.length > 0 ? ` ${details.join(" ")}` : "";
389
- }
390
- __name(formatFarmEventDetails, "formatFarmEventDetails");
391
- function formatDetailValue(value) {
392
- if (typeof value === "string") {
393
- return value;
394
- }
395
- if (typeof value === "number" || typeof value === "boolean") {
396
- return String(value);
397
- }
398
- try {
399
- return JSON.stringify(value);
400
- } catch {
401
- return String(value);
402
- }
403
- }
404
- __name(formatDetailValue, "formatDetailValue");
405
- function formatError(error) {
406
- return error instanceof Error ? error.message : String(error);
407
- }
408
- __name(formatError, "formatError");
409
6
 
410
- // src/cache-invalidation.ts
411
- var FARM_CACHE_INVALIDATION_STATE = /* @__PURE__ */ Symbol.for("farm.cacheInvalidationState");
412
- var globalState = globalThis;
413
- function getFarmCacheInvalidationState() {
414
- return globalState[FARM_CACHE_INVALIDATION_STATE] ?? (globalState[FARM_CACHE_INVALIDATION_STATE] = {
415
- listeners: /* @__PURE__ */ new Set(),
416
- taskListeners: /* @__PURE__ */ new Set()
417
- });
418
- }
419
- __name(getFarmCacheInvalidationState, "getFarmCacheInvalidationState");
420
- function subscribeFarmCacheInvalidation(listener) {
421
- const state = getFarmCacheInvalidationState();
422
- state.listeners.add(listener);
423
- return () => state.listeners.delete(listener);
424
- }
425
- __name(subscribeFarmCacheInvalidation, "subscribeFarmCacheInvalidation");
426
7
 
427
- // src/cache-invalidation-stream.ts
428
- var MAX_BUFFERED_BYTES = 64 * 1024;
429
- var textEncoder = new TextEncoder();
430
8
 
431
- // src/cache.ts
432
- var _FarmDataCache = class _FarmDataCache {
433
- constructor(config = {}) {
434
- this.entries = /* @__PURE__ */ new Map();
435
- this.inflight = /* @__PURE__ */ new Map();
436
- /** Local entries by tag, so tag counts and pruning never scan unrelated entries. */
437
- this.entriesByTag = /* @__PURE__ */ new Map();
438
- this.invalidatedTagVersions = /* @__PURE__ */ new Map();
439
- this.activeGenerations = /* @__PURE__ */ new Set();
440
- this.version = 0;
441
- this.generation = 0;
442
- this.namespace = "farm";
443
- this.local = true;
444
- this.maxEntries = 1024;
445
- this.lease = {
446
- enabled: true,
447
- ttlMs: 1e4,
448
- waitTimeoutMs: 1e4,
449
- pollIntervalMs: 25
450
- };
451
- this.configure(config);
452
- }
453
- configure(config = {}) {
454
- this.generation++;
455
- this.entries.clear();
456
- this.entriesByTag.clear();
457
- this.inflight.clear();
458
- this.invalidatedTagVersions.clear();
459
- this.activeGenerations.clear();
460
- this.version = 0;
461
- this.adapter = config.adapter;
462
- this.namespace = normalizeCacheNamespace(config.namespace || "farm");
463
- this.local = !config.adapter;
464
- this.maxEntries = normalizePositiveInteger(config.maxEntries, 1024, "cache.maxEntries");
465
- this.lease = config.lease === false ? { ...this.lease, enabled: false } : {
466
- enabled: true,
467
- ttlMs: normalizePositiveDuration(config.lease?.ttlMs, 1e4, "cache.lease.ttlMs"),
468
- waitTimeoutMs: normalizePositiveDuration(
469
- config.lease?.waitTimeoutMs,
470
- 1e4,
471
- "cache.lease.waitTimeoutMs"
472
- ),
473
- pollIntervalMs: normalizePositiveDuration(
474
- config.lease?.pollIntervalMs,
475
- 25,
476
- "cache.lease.pollIntervalMs"
477
- )
478
- };
479
- }
480
- get adapterName() {
481
- return this.adapter?.name || (this.adapter ? "custom" : "memory");
482
- }
483
- get hasAdapter() {
484
- return this.adapter !== void 0;
485
- }
486
- get size() {
487
- return this.entries.size;
488
- }
489
- get(key, options = {}) {
490
- return this.getEntry(key, options)?.value;
491
- }
492
- getEntry(key, options = {}) {
493
- const entry = this.entries.get(key);
494
- if (!entry) {
495
- emitFarmEvent({ type: "cache.miss", key });
496
- return void 0;
497
- }
498
- const stale = this.isStale(entry, options.now);
499
- if (stale) {
500
- emitFarmEvent({
501
- type: "cache.stale",
502
- key,
503
- tags: Array.from(entry.tags),
504
- revalidate: entry.revalidate
505
- });
506
- }
507
- if (!options.allowStale && stale) {
508
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
509
- return void 0;
510
- }
511
- this.touchEntry(key, entry);
512
- emitFarmEvent({
513
- type: "cache.hit",
514
- key,
515
- tags: Array.from(entry.tags),
516
- revalidate: entry.revalidate,
517
- stale
518
- });
519
- return this.toPublicEntry(entry);
520
- }
521
- async getEntryAsync(key, options = {}) {
522
- if (this.local) {
523
- const localEntry = this.getEntry(key, options);
524
- if (localEntry) return localEntry;
525
- }
526
- if (!this.adapter) {
527
- return this.local ? void 0 : this.getEntry(key, options);
528
- }
529
- const generation = this.generation;
530
- const adapter = this.adapter;
531
- const namespace = this.namespace;
532
- const entry = await adapter.get(`${namespace}:entry:${key}`);
533
- if (generation !== this.generation) return void 0;
534
- if (!entry) {
535
- emitFarmEvent({ type: "cache.miss", key });
536
- return void 0;
537
- }
538
- assertFarmCacheEntry(entry, key);
539
- const stale = await this.isAdapterEntryStale(entry, options.now, adapter, namespace);
540
- if (generation !== this.generation) return void 0;
541
- if (stale) {
542
- emitFarmEvent({
543
- type: "cache.stale",
544
- key,
545
- tags: [...entry.tags],
546
- revalidate: entry.revalidate
547
- });
548
- if (!options.allowStale) {
549
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
550
- return void 0;
551
- }
552
- }
553
- emitFarmEvent({
554
- type: "cache.hit",
555
- key,
556
- tags: [...entry.tags],
557
- revalidate: entry.revalidate,
558
- stale
559
- });
560
- if (this.local && !stale) {
561
- this.hydrateLocalEntry(entry);
562
- }
563
- return { ...entry, key };
564
- }
565
- set(key, value, options = {}) {
566
- const revalidate = normalizeRevalidate(options.revalidate);
567
- const tags = /* @__PURE__ */ new Set();
568
- for (const tag of options.tags ?? []) {
569
- tags.add(normalizeCacheTag(tag));
570
- }
571
- for (const routePath of options.paths ?? []) {
572
- tags.add(createPathCacheTag(routePath));
573
- }
574
- const entry = {
575
- key,
576
- value,
577
- tags,
578
- tagVersions: void 0,
579
- createdAt: options.createdAt ?? Date.now(),
580
- createdVersion: ++this.version,
581
- revalidate
582
- };
583
- this.storeLocalEntry(entry);
584
- emitFarmEvent({
585
- type: "cache.set",
586
- key,
587
- tags: Array.from(tags),
588
- revalidate: entry.revalidate
589
- });
590
- return this.toPublicEntry(entry);
591
- }
592
- async setAsync(key, value, options = {}, tagVersions) {
593
- return this.writeAsync(key, value, options, tagVersions);
594
- }
595
- async writeAsync(key, value, options, tagVersions, createdVersion) {
596
- const revalidate = normalizeRevalidate(options.revalidate);
597
- const tags = normalizeCacheOptionsTags(options);
598
- const capturedVersions = tagVersions ?? await this.getAdapterTagVersions(Array.from(tags.values()));
599
- const entry = {
600
- key,
601
- value,
602
- tags: Array.from(tags),
603
- tagVersions: capturedVersions,
604
- createdAt: options.createdAt ?? Date.now(),
605
- createdVersion: createdVersion ?? ++this.version,
606
- revalidate
607
- };
608
- if (this.local) {
609
- this.hydrateLocalEntry(entry);
610
- }
611
- if (this.adapter) {
612
- await this.adapter.set(this.createAdapterKey(key), entry);
613
- }
614
- emitFarmEvent({
615
- type: "cache.set",
616
- key,
617
- tags: [...entry.tags],
618
- revalidate: entry.revalidate
619
- });
620
- return entry;
621
- }
622
- delete(key) {
623
- const deleted = this.deleteLocalEntry(key);
624
- emitFarmEvent({ type: "cache.delete", key, deleted });
625
- return deleted;
626
- }
627
- async deleteAsync(key) {
628
- const deleted = this.deleteLocalEntry(key);
629
- if (this.adapter) {
630
- await this.adapter.delete(this.createAdapterKey(key));
631
- }
632
- emitFarmEvent({ type: "cache.delete", key, deleted: this.adapter ? true : deleted });
633
- return this.adapter ? true : deleted;
634
- }
635
- clear() {
636
- const count = this.entries.size;
637
- this.generation++;
638
- this.entries.clear();
639
- this.entriesByTag.clear();
640
- this.inflight.clear();
641
- this.invalidatedTagVersions.clear();
642
- this.activeGenerations.clear();
643
- this.version = 0;
644
- emitFarmEvent({ type: "cache.clear", count });
645
- }
646
- async clearAsync() {
647
- this.clear();
648
- await this.adapter?.clear?.();
649
- }
650
- isStale(entry, now = Date.now()) {
651
- if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
652
- return true;
653
- }
654
- for (const tag of entry.tags) {
655
- const invalidatedVersion = this.invalidatedTagVersions.get(normalizeCacheTag(tag));
656
- if (typeof invalidatedVersion === "number" && typeof entry.createdVersion === "number" && invalidatedVersion > entry.createdVersion) {
657
- return true;
658
- }
659
- }
660
- return false;
661
- }
662
- async isStaleAsync(entry, now = Date.now()) {
663
- if (this.adapter) {
664
- return this.isAdapterEntryStale(entry, now);
665
- }
666
- return this.isStale(entry, now);
667
- }
668
- revalidateTag(tag, options = {}) {
669
- const normalized = normalizeCacheTag(tag);
670
- const count = this.invalidateTag(normalized);
671
- emitFarmEvent(
672
- options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
673
- );
674
- return count;
675
- }
676
- async revalidateTagAsync(tag, options = {}) {
677
- const normalized = normalizeCacheTag(tag);
678
- const count = this.invalidateTag(normalized);
679
- await this.adapter?.invalidateTags?.([this.createAdapterTag(normalized)]);
680
- emitFarmEvent(
681
- options.source === "updateTag" ? { type: "cache.updateTag", tag: normalized, count } : { type: "cache.revalidateTag", tag: normalized, profile: options.profile, count }
682
- );
683
- return count;
684
- }
685
- revalidatePath(routePath) {
686
- const normalizedPath = normalizeRevalidatePath(routePath);
687
- const pathTag = createPathCacheTag(normalizedPath);
688
- const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
689
- const count = this.invalidateTag(pathTag);
690
- emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
691
- if (pprCount > 0) {
692
- emitFarmEvent({
693
- type: "ppr.shell.invalidated",
694
- route: normalizedPath,
695
- reason: "revalidatePath",
696
- count: pprCount
697
- });
698
- }
699
- return count;
700
- }
701
- async revalidatePathAsync(routePath) {
702
- const normalizedPath = normalizeRevalidatePath(routePath);
703
- const pathTag = createPathCacheTag(normalizedPath);
704
- const pprCount = this.countEntriesForTags([pathTag, "ppr"]);
705
- const count = this.invalidateTag(pathTag);
706
- await this.adapter?.invalidateTags?.([this.createAdapterTag(pathTag)]);
707
- emitFarmEvent({ type: "cache.revalidatePath", path: normalizedPath, count });
708
- if (pprCount > 0) {
709
- emitFarmEvent({
710
- type: "ppr.shell.invalidated",
711
- route: normalizedPath,
712
- reason: "revalidatePath",
713
- count: pprCount
714
- });
715
- }
716
- return count;
717
- }
718
- async getOrSet(key, producer, options = {}) {
719
- normalizeRevalidate(options.revalidate);
720
- const cached = await this.getEntryAsync(key);
721
- if (cached) {
722
- return cached.value;
723
- }
724
- const inflight = this.inflight.get(key);
725
- if (inflight && !this.wasInvalidatedSince(inflight.tags, inflight.startVersion)) {
726
- emitFarmEvent({ type: "cache.dedupe", key });
727
- return inflight.promise;
728
- }
729
- const tags = Array.from(normalizeCacheOptionsTags(options));
730
- const generation = this.generation;
731
- const startVersion = this.version;
732
- const promise = this.fillCacheEntry(key, producer, options, tags, generation).catch((error) => {
733
- emitFarmEvent({ type: "cache.error", key, operation: "set", error });
734
- throw error;
735
- }).finally(() => {
736
- if (this.inflight.get(key)?.promise === promise) {
737
- this.inflight.delete(key);
738
- }
739
- });
740
- this.inflight.set(key, { promise, tags, startVersion });
741
- return promise;
742
- }
743
- /** A fill that started before one of its tags was invalidated cannot satisfy later readers. */
744
- wasInvalidatedSince(tags, version) {
745
- for (const tag of tags) {
746
- const invalidatedVersion = this.invalidatedTagVersions.get(tag);
747
- if (invalidatedVersion !== void 0 && invalidatedVersion > version) return true;
748
- }
749
- return false;
750
- }
751
- async fillCacheEntry(key, producer, options, tags, generation) {
752
- const adapter = this.adapter;
753
- const namespace = this.namespace;
754
- const lease = { ...this.lease };
755
- const leaseKey = `${namespace}:lease:${key}`;
756
- let leaseToken;
757
- if (adapter?.acquireLease && adapter.releaseLease && lease.enabled) {
758
- leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
759
- if (!leaseToken) {
760
- const shared2 = await this.waitForAdapterEntry(
761
- key,
762
- adapter,
763
- namespace,
764
- lease,
765
- generation
766
- );
767
- if (shared2) {
768
- emitFarmEvent({ type: "cache.dedupe", key });
769
- return shared2.value;
770
- }
771
- if (generation === this.generation) {
772
- leaseToken = await adapter.acquireLease(leaseKey, lease.ttlMs);
773
- }
774
- }
775
- }
776
- const initialCreatedVersion = this.version;
777
- const activeGeneration = {
778
- tags: new Set(tags),
779
- createdVersion: initialCreatedVersion
780
- };
781
- this.activeGenerations.add(activeGeneration);
782
- try {
783
- const initialTagVersions = await this.getAdapterTagVersions(tags, adapter, namespace);
784
- const value = await producer();
785
- if (generation === this.generation) {
786
- await this.writeAsync(key, value, options, initialTagVersions, initialCreatedVersion);
787
- }
788
- return value;
789
- } finally {
790
- this.activeGenerations.delete(activeGeneration);
791
- this.pruneInvalidatedTagVersions(activeGeneration.tags);
792
- if (leaseToken && adapter?.releaseLease) {
793
- try {
794
- await adapter.releaseLease(leaseKey, leaseToken);
795
- } catch (error) {
796
- emitFarmEvent({ type: "cache.error", key, operation: "set", error });
797
- }
798
- }
799
- }
800
- }
801
- async waitForAdapterEntry(key, adapter, namespace, lease, generation) {
802
- const deadline = Date.now() + lease.waitTimeoutMs;
803
- while (Date.now() < deadline) {
804
- await delay(lease.pollIntervalMs);
805
- if (generation !== this.generation) return void 0;
806
- const entry = await adapter.get(`${namespace}:entry:${key}`);
807
- if (generation !== this.generation) return void 0;
808
- if (!entry) {
809
- emitFarmEvent({ type: "cache.miss", key });
810
- continue;
811
- }
812
- assertFarmCacheEntry(entry, key);
813
- const stale = await this.isAdapterEntryStale(entry, Date.now(), adapter, namespace);
814
- if (generation !== this.generation) return void 0;
815
- if (stale) {
816
- emitFarmEvent({
817
- type: "cache.stale",
818
- key,
819
- tags: [...entry.tags],
820
- revalidate: entry.revalidate
821
- });
822
- emitFarmEvent({ type: "cache.miss", key, reason: "stale" });
823
- } else {
824
- emitFarmEvent({
825
- type: "cache.hit",
826
- key,
827
- tags: [...entry.tags],
828
- revalidate: entry.revalidate,
829
- stale: false
830
- });
831
- return { ...entry, key };
832
- }
833
- }
834
- return void 0;
835
- }
836
- countEntriesForTags(tags) {
837
- let count = 0;
838
- for (const entry of this.entriesByTag.get(tags[0]) ?? []) {
839
- if (tags.every((tag) => entry.tags.has(tag))) {
840
- count++;
841
- }
842
- }
843
- return count;
844
- }
845
- invalidateTag(normalizedTag) {
846
- const count = this.entriesByTag.get(normalizedTag)?.size ?? 0;
847
- this.invalidatedTagVersions.delete(normalizedTag);
848
- this.invalidatedTagVersions.set(normalizedTag, ++this.version);
849
- this.pruneInvalidatedTagVersions([normalizedTag]);
850
- return count;
851
- }
852
- toPublicEntry(entry) {
853
- return {
854
- key: entry.key,
855
- value: entry.value,
856
- tags: Array.from(entry.tags),
857
- tagVersions: entry.tagVersions,
858
- createdAt: entry.createdAt,
859
- createdVersion: entry.createdVersion,
860
- revalidate: entry.revalidate
861
- };
862
- }
863
- hydrateLocalEntry(entry) {
864
- this.storeLocalEntry({
865
- key: entry.key,
866
- value: entry.value,
867
- tags: new Set(entry.tags.map(normalizeCacheTag)),
868
- tagVersions: entry.tagVersions,
869
- createdAt: entry.createdAt,
870
- createdVersion: entry.createdVersion ?? ++this.version,
871
- revalidate: normalizeRevalidate(entry.revalidate)
872
- });
873
- }
874
- touchEntry(key, entry) {
875
- this.entries.delete(key);
876
- this.entries.set(key, entry);
877
- }
878
- storeLocalEntry(entry) {
879
- const removed = [];
880
- const replaced = this.detachLocalEntry(entry.key);
881
- if (replaced) removed.push(replaced);
882
- this.entries.set(entry.key, entry);
883
- for (const tag of entry.tags) {
884
- let tagged = this.entriesByTag.get(tag);
885
- if (!tagged) this.entriesByTag.set(tag, tagged = /* @__PURE__ */ new Set());
886
- tagged.add(entry);
887
- }
888
- while (this.entries.size > this.maxEntries) {
889
- const oldestKey = this.entries.keys().next().value;
890
- if (oldestKey === void 0) break;
891
- removed.push(this.detachLocalEntry(oldestKey));
892
- }
893
- for (const removedEntry of removed) this.pruneInvalidatedTagVersions(removedEntry.tags);
894
- }
895
- deleteLocalEntry(key) {
896
- const entry = this.detachLocalEntry(key);
897
- if (!entry) return false;
898
- this.pruneInvalidatedTagVersions(entry.tags);
899
- return true;
900
- }
901
- detachLocalEntry(key) {
902
- const entry = this.entries.get(key);
903
- if (!entry) return void 0;
904
- this.entries.delete(key);
905
- for (const tag of entry.tags) {
906
- const tagged = this.entriesByTag.get(tag);
907
- if (!tagged) continue;
908
- tagged.delete(entry);
909
- if (tagged.size === 0) this.entriesByTag.delete(tag);
910
- }
911
- return entry;
912
- }
913
- /**
914
- * Drop invalidation versions that no local entry or active fill can be stale against.
915
- * Callers pass only the tags whose dependents just changed, so the cost is bounded by
916
- * the entries sharing those tags rather than by the whole cache.
917
- */
918
- pruneInvalidatedTagVersions(tags) {
919
- tags: for (const tag of tags) {
920
- const invalidatedVersion = this.invalidatedTagVersions.get(tag);
921
- if (invalidatedVersion === void 0) continue;
922
- for (const entry of this.entriesByTag.get(tag) ?? []) {
923
- if (entry.createdVersion < invalidatedVersion) continue tags;
924
- }
925
- for (const generation of this.activeGenerations) {
926
- if (generation.tags.has(tag) && generation.createdVersion < invalidatedVersion)
927
- continue tags;
928
- }
929
- this.invalidatedTagVersions.delete(tag);
930
- }
931
- }
932
- createAdapterKey(key) {
933
- return `${this.namespace}:entry:${key}`;
934
- }
935
- createAdapterTag(tag) {
936
- return `${this.namespace}:tag:${tag}`;
937
- }
938
- async getAdapterTagVersions(tags, adapter = this.adapter, namespace = this.namespace) {
939
- if (!adapter?.getTagVersions || tags.length === 0) return {};
940
- const normalized = tags.map(normalizeCacheTag);
941
- const physicalTags = normalized.map((tag) => `${namespace}:tag:${tag}`);
942
- const versions = await adapter.getTagVersions(physicalTags);
943
- return Object.fromEntries(
944
- normalized.map((tag, index) => [
945
- tag,
946
- normalizeAdapterVersion(versions[physicalTags[index]])
947
- ])
948
- );
949
- }
950
- async isAdapterEntryStale(entry, now = Date.now(), adapter = this.adapter, namespace = this.namespace) {
951
- if (typeof entry.revalidate === "number" && entry.revalidate >= 0 && now - entry.createdAt >= entry.revalidate * 1e3) {
952
- return true;
953
- }
954
- const currentVersions = await this.getAdapterTagVersions(entry.tags, adapter, namespace);
955
- for (const tag of entry.tags) {
956
- if (normalizeAdapterVersion(currentVersions[tag]) > normalizeAdapterVersion(entry.tagVersions?.[tag])) {
957
- return true;
958
- }
959
- }
960
- return false;
961
- }
962
- };
963
- __name(_FarmDataCache, "FarmDataCache");
964
- var FarmDataCache = _FarmDataCache;
965
- var FARM_DATA_CACHE_SYMBOL = /* @__PURE__ */ Symbol.for("farm.dataCache");
966
- var farmDataCacheGlobal = globalThis;
967
- var sharedFarmDataCache = farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] ?? (farmDataCacheGlobal[FARM_DATA_CACHE_SYMBOL] = new FarmDataCache());
968
- function createPathCacheTag(routePath) {
969
- return `path:${normalizeRevalidatePath(routePath)}`;
970
- }
971
- __name(createPathCacheTag, "createPathCacheTag");
972
- function normalizeRevalidatePath(routePath) {
973
- if (typeof routePath !== "string") {
974
- throw new TypeError("revalidatePath expects a path string.");
975
- }
976
- let normalized = routePath.trim();
977
- if (!normalized) {
978
- throw new Error("revalidatePath expects a non-empty path.");
979
- }
980
- try {
981
- if (/^https?:\/\//i.test(normalized)) {
982
- normalized = new URL(normalized).pathname;
983
- }
984
- } catch {
985
- }
986
- normalized = normalized.split(/[?#]/, 1)[0] ?? normalized;
987
- normalized = normalized.startsWith("/") ? normalized : `/${normalized}`;
988
- normalized = normalized.replace(/\/{2,}/g, "/");
989
- normalized = new URL(normalized, "http://farm.invalid").pathname;
990
- if (normalized.length > 1) {
991
- normalized = normalized.replace(/\/+$/, "");
992
- }
993
- return normalized || "/";
994
- }
995
- __name(normalizeRevalidatePath, "normalizeRevalidatePath");
996
- function createFarmCacheKey(parts) {
997
- return stableSerialize(parts);
998
- }
999
- __name(createFarmCacheKey, "createFarmCacheKey");
1000
- function normalizeRevalidate(revalidate) {
1001
- if (revalidate === false || revalidate === void 0) {
1002
- return revalidate;
1003
- }
1004
- if (!Number.isFinite(revalidate) || revalidate < 0) {
1005
- throw new TypeError("Cache revalidate must be false or a finite, non-negative number.");
1006
- }
1007
- return revalidate;
1008
- }
1009
- __name(normalizeRevalidate, "normalizeRevalidate");
1010
- function normalizeCacheTag(tag) {
1011
- if (typeof tag !== "string") {
1012
- throw new TypeError("Cache tags must be strings.");
1013
- }
1014
- const normalized = tag.trim();
1015
- if (!normalized) {
1016
- throw new Error("Cache tags cannot be empty.");
1017
- }
1018
- return normalized;
1019
- }
1020
- __name(normalizeCacheTag, "normalizeCacheTag");
1021
- function normalizeCacheNamespace(namespace) {
1022
- if (typeof namespace !== "string") {
1023
- throw new TypeError("Cache namespace must be a string.");
1024
- }
1025
- const normalized = namespace.trim().replace(/:+$/g, "");
1026
- if (!normalized) {
1027
- throw new Error("Cache namespace cannot be empty.");
1028
- }
1029
- return normalized;
1030
- }
1031
- __name(normalizeCacheNamespace, "normalizeCacheNamespace");
1032
- function normalizeAdapterVersion(value) {
1033
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
1034
- }
1035
- __name(normalizeAdapterVersion, "normalizeAdapterVersion");
1036
- function normalizePositiveDuration(value, fallback, name) {
1037
- if (value === void 0) return fallback;
1038
- if (!Number.isFinite(value) || value <= 0) {
1039
- throw new TypeError(`${name} must be a positive number of milliseconds.`);
1040
- }
1041
- return Math.floor(value);
1042
- }
1043
- __name(normalizePositiveDuration, "normalizePositiveDuration");
1044
- function normalizePositiveInteger(value, fallback, name) {
1045
- if (value === void 0) return fallback;
1046
- if (!Number.isSafeInteger(value) || value <= 0) {
1047
- throw new TypeError(`${name} must be a positive integer.`);
1048
- }
1049
- return value;
1050
- }
1051
- __name(normalizePositiveInteger, "normalizePositiveInteger");
1052
- function delay(ms) {
1053
- return new Promise((resolve) => setTimeout(resolve, ms));
1054
- }
1055
- __name(delay, "delay");
1056
- function normalizeCacheOptionsTags(options) {
1057
- const tags = /* @__PURE__ */ new Set();
1058
- for (const tag of options.tags ?? []) {
1059
- tags.add(normalizeCacheTag(tag));
1060
- }
1061
- for (const routePath of options.paths ?? []) {
1062
- tags.add(createPathCacheTag(routePath));
1063
- }
1064
- return tags;
1065
- }
1066
- __name(normalizeCacheOptionsTags, "normalizeCacheOptionsTags");
1067
- function assertFarmCacheEntry(entry, expectedKey) {
1068
- if (!entry || typeof entry !== "object" || entry.key !== expectedKey || !Array.isArray(entry.tags) || typeof entry.createdAt !== "number") {
1069
- throw new TypeError(
1070
- `Cache adapter returned an invalid entry for ${JSON.stringify(expectedKey)}.`
1071
- );
1072
- }
1073
- }
1074
- __name(assertFarmCacheEntry, "assertFarmCacheEntry");
1075
- function getFunctionCacheIdentity(fn) {
1076
- const name = fn.name || "anonymous";
1077
- return `${name}:${hashFunctionSource(String(fn))}`;
1078
- }
1079
- __name(getFunctionCacheIdentity, "getFunctionCacheIdentity");
1080
- function hashFunctionSource(source) {
1081
- let hash = 2166136261;
1082
- for (let index = 0; index < source.length; index++) {
1083
- hash ^= source.charCodeAt(index);
1084
- hash = Math.imul(hash, 16777619);
1085
- }
1086
- return (hash >>> 0).toString(36);
1087
- }
1088
- __name(hashFunctionSource, "hashFunctionSource");
1089
- function compareCodepoint(a, b) {
1090
- return a < b ? -1 : a > b ? 1 : 0;
1091
- }
1092
- __name(compareCodepoint, "compareCodepoint");
1093
- function serializeBinaryBytes(bytes) {
1094
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1095
- }
1096
- __name(serializeBinaryBytes, "serializeBinaryBytes");
1097
- function serializeCanonicalStringEntries(entries, seen) {
1098
- const valuesByKey = /* @__PURE__ */ new Map();
1099
- for (const [key, item] of entries) {
1100
- const values = valuesByKey.get(key);
1101
- if (values) values.push(item);
1102
- else valuesByKey.set(key, [item]);
1103
- }
1104
- return Array.from(valuesByKey.keys()).sort(compareCodepoint).flatMap(
1105
- (key) => valuesByKey.get(key).map((item) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`)
1106
- ).join(",");
1107
- }
1108
- __name(serializeCanonicalStringEntries, "serializeCanonicalStringEntries");
1109
- function isPlainCacheKeyObject(value) {
1110
- const prototype = Object.getPrototypeOf(value);
1111
- if (prototype === null) return true;
1112
- const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor")?.value;
1113
- return Object.getPrototypeOf(prototype) === null && typeof constructor === "function" && constructor.name === "Object";
1114
- }
1115
- __name(isPlainCacheKeyObject, "isPlainCacheKeyObject");
1116
- function getCacheKeyValueType(value) {
1117
- const prototype = Object.getPrototypeOf(value);
1118
- const constructor = prototype ? Object.getOwnPropertyDescriptor(prototype, "constructor")?.value : void 0;
1119
- if (typeof constructor === "function" && constructor.name) {
1120
- return constructor.name;
1121
- }
1122
- return Object.prototype.toString.call(value).slice(8, -1) || "object";
1123
- }
1124
- __name(getCacheKeyValueType, "getCacheKeyValueType");
1125
- function stableSerialize(value, seen = /* @__PURE__ */ new WeakSet()) {
1126
- if (value === null) return "null";
1127
- if (value === void 0) return "undefined";
1128
- const valueType = typeof value;
1129
- if (valueType === "string") return JSON.stringify(value);
1130
- if (valueType === "number" || valueType === "boolean" || valueType === "bigint") {
1131
- return `${valueType}:${String(value)}`;
1132
- }
1133
- if (valueType === "symbol") {
1134
- return `symbol:${String(value)}`;
1135
- }
1136
- if (valueType === "function") {
1137
- return `function:${getFunctionCacheIdentity(value)}`;
1138
- }
1139
- if (value instanceof Date) {
1140
- return Number.isNaN(value.getTime()) ? "date:invalid" : `date:${value.toISOString()}`;
1141
- }
1142
- if (value instanceof URL) {
1143
- return `url:${value.toString()}`;
1144
- }
1145
- if (value instanceof RegExp) {
1146
- return `regexp:${value.toString()}`;
1147
- }
1148
- if (value instanceof ArrayBuffer) {
1149
- return `arraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
1150
- }
1151
- if (typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer) {
1152
- return `sharedarraybuffer:${serializeBinaryBytes(new Uint8Array(value))}`;
1153
- }
1154
- if (ArrayBuffer.isView(value)) {
1155
- const viewType = Object.prototype.toString.call(value).slice(8, -1);
1156
- const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
1157
- return `binary:${viewType}:${serializeBinaryBytes(bytes)}`;
1158
- }
1159
- if (value && typeof value === "object") {
1160
- if (seen.has(value)) {
1161
- return "[Circular]";
1162
- }
1163
- seen.add(value);
1164
- if (Array.isArray(value)) {
1165
- const items = [];
1166
- for (let index = 0; index < value.length; index++) {
1167
- items.push(
1168
- Object.prototype.hasOwnProperty.call(value, index) ? stableSerialize(value[index], seen) : "[Hole]"
1169
- );
1170
- }
1171
- seen.delete(value);
1172
- return `[${items.join(",")}]`;
1173
- }
1174
- if (value instanceof Set) {
1175
- const items = Array.from(value, (item) => stableSerialize(item, seen)).sort(compareCodepoint);
1176
- seen.delete(value);
1177
- return `set:[${items.join(",")}]`;
1178
- }
1179
- if (value instanceof Map) {
1180
- const items = Array.from(
1181
- value,
1182
- ([key, item]) => `[${stableSerialize(key, seen)},${stableSerialize(item, seen)}]`
1183
- ).sort(compareCodepoint);
1184
- seen.delete(value);
1185
- return `map:[${items.join(",")}]`;
1186
- }
1187
- if (value instanceof URLSearchParams) {
1188
- const serialized2 = serializeCanonicalStringEntries(value, seen);
1189
- seen.delete(value);
1190
- return `urlsearchparams:[${serialized2}]`;
1191
- }
1192
- if (value instanceof Headers) {
1193
- const serialized2 = serializeCanonicalStringEntries(value, seen);
1194
- seen.delete(value);
1195
- return `headers:[${serialized2}]`;
1196
- }
1197
- if (!isPlainCacheKeyObject(value)) {
1198
- throw new TypeError(
1199
- `Cache keys do not support ${getCacheKeyValueType(value)} values. Convert the value to an explicit stable string or structured key before caching.`
1200
- );
1201
- }
1202
- const entries = Object.entries(value).sort(
1203
- ([a], [b]) => compareCodepoint(a, b)
1204
- );
1205
- const serialized = entries.map(([key, item]) => `${JSON.stringify(key)}:${stableSerialize(item, seen)}`).join(",");
1206
- seen.delete(value);
1207
- return `{${serialized}}`;
1208
- }
1209
- return String(value);
1210
- }
1211
- __name(stableSerialize, "stableSerialize");
1212
9
 
1213
- // src/client-cache.ts
1214
- var invalidationTrackers = /* @__PURE__ */ new WeakMap();
1215
- function trackFarmClientCacheInvalidations(cache) {
1216
- let trackers = invalidationTrackers.get(cache);
1217
- if (!trackers) {
1218
- trackers = /* @__PURE__ */ new Set();
1219
- invalidationTrackers.set(cache, trackers);
1220
- }
1221
- const keys = /* @__PURE__ */ new Set();
1222
- trackers.add(keys);
1223
- return {
1224
- has(key) {
1225
- const resolved = cache.resolveKey(key);
1226
- for (const invalidated of keys) {
1227
- if (cache.resolveKey(invalidated) === resolved) return true;
1228
- }
1229
- return false;
1230
- },
1231
- dispose() {
1232
- if (!trackers.delete(keys)) return;
1233
- keys.clear();
1234
- if (trackers.size === 0) invalidationTrackers.delete(cache);
1235
- }
1236
- };
1237
- }
1238
- __name(trackFarmClientCacheInvalidations, "trackFarmClientCacheInvalidations");
1239
- var cacheFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((unsubscribe) => unsubscribe()) : void 0;
1240
- var DEFAULT_GC_SWEEP_INTERVAL_MS = 3e4;
1241
- var _FarmClientDataCache = class _FarmClientDataCache {
1242
- constructor(options = {}) {
1243
- this.entries = /* @__PURE__ */ new Map();
1244
- this.aliases = /* @__PURE__ */ new Map();
1245
- this.aliasesByTarget = /* @__PURE__ */ new Map();
1246
- this.invalidatedAt = /* @__PURE__ */ new Map();
1247
- this.listeners = /* @__PURE__ */ new Map();
1248
- this.inflight = /* @__PURE__ */ new Map();
1249
- this.pendingMetadataSweeps = /* @__PURE__ */ new Set();
1250
- this.gcSweepIntervalMs = options.gcSweepIntervalMs ?? DEFAULT_GC_SWEEP_INTERVAL_MS;
1251
- if (options.subscribeToInvalidation !== false) {
1252
- if (typeof WeakRef === "function") {
1253
- const reference = new WeakRef(this);
1254
- const unsubscribe = _FarmClientDataCache.subscribeWeakCache(reference);
1255
- cacheFinalizer?.register(this, unsubscribe, reference);
1256
- this.unsubscribeInvalidation = unsubscribe;
1257
- } else {
1258
- this.unsubscribeInvalidation = subscribeFarmCacheInvalidation(
1259
- (key) => this.applyInvalidation(key, Date.now(), false)
1260
- );
1261
- }
1262
- }
1263
- }
1264
- // This closure must only capture a weak reference, never the cache itself.
1265
- static subscribeWeakCache(reference) {
1266
- const unsubscribe = subscribeFarmCacheInvalidation((key) => {
1267
- const cache = reference.deref();
1268
- if (cache) cache.applyInvalidation(key, Date.now(), false);
1269
- else dispose();
1270
- });
1271
- function dispose() {
1272
- unsubscribe();
1273
- cacheFinalizer?.unregister(reference);
1274
- }
1275
- __name(dispose, "dispose");
1276
- return dispose;
1277
- }
1278
- get size() {
1279
- return this.entries.size;
1280
- }
1281
- /** @internal Attach or detach the persistence engine's observation sink. */
1282
- attachPersistence(sink) {
1283
- this.persistence = sink;
1284
- }
1285
- resolveKey(key) {
1286
- let resolved = key;
1287
- const seen = /* @__PURE__ */ new Set();
1288
- while (this.aliases.has(resolved) && !seen.has(resolved)) {
1289
- seen.add(resolved);
1290
- resolved = this.aliases.get(resolved);
1291
- }
1292
- return resolved;
1293
- }
1294
- get(key, now = Date.now()) {
1295
- const resolved = this.resolveKey(key);
1296
- const entry = this.entries.get(resolved);
1297
- if (!entry) return void 0;
1298
- if (entry.gcAt !== void 0 && now >= entry.gcAt) {
1299
- if (entry.fetching) return void 0;
1300
- this.entries.delete(resolved);
1301
- this.persistence?.onDelete(resolved);
1302
- this.sweepEntryMetadata(/* @__PURE__ */ new Set([resolved]));
1303
- this.emit(resolved);
1304
- return void 0;
1305
- }
1306
- return entry;
1307
- }
1308
- set(key, entry) {
1309
- const resolved = this.resolveKey(key);
1310
- const invalidatedAt = this.invalidatedAt.get(resolved);
1311
- const nextEntry = invalidatedAt !== void 0 && invalidatedAt > entry.updatedAt ? { ...entry, staleAt: 0, invalidatedAt } : { ...entry, invalidatedAt: void 0 };
1312
- if (invalidatedAt === void 0 || entry.updatedAt >= invalidatedAt) {
1313
- this.invalidatedAt.delete(resolved);
1314
- }
1315
- this.entries.set(resolved, nextEntry);
1316
- this.pendingMetadataSweeps.delete(resolved);
1317
- if (nextEntry.gcAt !== void 0) this.scheduleGcSweep();
1318
- this.persistence?.onSet(resolved, nextEntry);
1319
- this.emit(resolved);
1320
- return this;
1321
- }
1322
- delete(key) {
1323
- const resolved = this.resolveKey(key);
1324
- const deleted = this.entries.delete(resolved);
1325
- this.inflight.delete(resolved);
1326
- if (deleted) this.persistence?.onDelete(resolved);
1327
- if (deleted || this.pendingMetadataSweeps.has(resolved)) {
1328
- this.sweepEntryMetadata(/* @__PURE__ */ new Set([resolved]));
1329
- }
1330
- this.emit(resolved);
1331
- return deleted;
1332
- }
1333
- clear() {
1334
- const keys = /* @__PURE__ */ new Set([...this.entries.keys(), ...this.listeners.keys()]);
1335
- this.entries.clear();
1336
- this.aliases.clear();
1337
- this.aliasesByTarget.clear();
1338
- this.invalidatedAt.clear();
1339
- this.inflight.clear();
1340
- this.pendingMetadataSweeps.clear();
1341
- this.persistence?.onClear();
1342
- for (const key of keys) this.emit(key);
1343
- }
1344
- dispose() {
1345
- this.unsubscribeInvalidation?.();
1346
- this.unsubscribeInvalidation = void 0;
1347
- if (this.gcTimer !== void 0) {
1348
- clearTimeout(this.gcTimer);
1349
- this.gcTimer = void 0;
1350
- }
1351
- this.clear();
1352
- }
1353
- isStale(key, now = Date.now()) {
1354
- const entry = this.get(key, now);
1355
- return !entry || entry.invalidatedAt !== void 0 || now >= entry.staleAt;
1356
- }
1357
- invalidate(key, now = Date.now()) {
1358
- this.applyInvalidation(key, now, true);
1359
- }
1360
- applyInvalidation(key, now, retainUnowned) {
1361
- const resolved = this.resolveKey(key);
1362
- for (const keys of invalidationTrackers.get(this) ?? []) keys.add(resolved);
1363
- const entry = this.entries.get(resolved);
1364
- const alreadyRetained = this.invalidatedAt.has(resolved);
1365
- if (retainUnowned || entry || alreadyRetained || this.hasMetadataOwner(resolved)) {
1366
- this.invalidatedAt.set(resolved, now);
1367
- if (!entry && !retainUnowned && !alreadyRetained) this.pendingMetadataSweeps.add(resolved);
1368
- }
1369
- if (entry) {
1370
- this.entries.set(resolved, {
1371
- ...entry,
1372
- staleAt: 0,
1373
- invalidatedAt: now
1374
- });
1375
- }
1376
- this.emit(resolved, "invalidate");
1377
- }
1378
- hasMetadataOwner(key) {
1379
- const related = /* @__PURE__ */ new Set([key]);
1380
- for (const target of related) {
1381
- if (this.listeners.has(target) || this.inflight.has(target)) return true;
1382
- for (const alias of this.aliasesByTarget.get(target) ?? []) related.add(alias);
1383
- }
1384
- return false;
1385
- }
1386
- alias(alias, key) {
1387
- const resolved = this.resolveKey(key);
1388
- if (alias === resolved) return;
1389
- const aliasEntry = this.entries.get(alias);
1390
- const aliasInvalidatedAt = this.invalidatedAt.get(alias) ?? aliasEntry?.invalidatedAt;
1391
- const resolvedInvalidatedAt = this.invalidatedAt.get(resolved);
1392
- if (aliasEntry && !this.entries.has(resolved)) {
1393
- this.entries.set(resolved, aliasEntry);
1394
- this.persistence?.onSet(resolved, aliasEntry);
1395
- }
1396
- if (this.entries.delete(alias)) this.persistence?.onDelete(alias);
1397
- this.invalidatedAt.delete(alias);
1398
- const invalidatedAt = [aliasInvalidatedAt, resolvedInvalidatedAt].reduce(
1399
- (latest, value) => value === void 0 ? latest : latest === void 0 ? value : Math.max(latest, value),
1400
- void 0
1401
- );
1402
- const resolvedEntry = this.entries.get(resolved);
1403
- if (invalidatedAt !== void 0 && (!resolvedEntry || invalidatedAt > resolvedEntry.updatedAt)) {
1404
- this.invalidatedAt.set(resolved, invalidatedAt);
1405
- if (resolvedEntry) {
1406
- this.entries.set(resolved, {
1407
- ...resolvedEntry,
1408
- staleAt: 0,
1409
- invalidatedAt
1410
- });
1411
- }
1412
- } else if (invalidatedAt !== void 0) {
1413
- this.invalidatedAt.delete(resolved);
1414
- if (resolvedEntry?.invalidatedAt !== void 0) {
1415
- this.entries.set(resolved, { ...resolvedEntry, invalidatedAt: void 0 });
1416
- }
1417
- }
1418
- const aliasInflight = this.inflight.get(alias);
1419
- if (aliasInflight && !this.inflight.has(resolved)) {
1420
- this.inflight.set(resolved, aliasInflight);
1421
- }
1422
- this.inflight.delete(alias);
1423
- if (this.pendingMetadataSweeps.delete(alias) && !this.entries.has(resolved)) {
1424
- this.pendingMetadataSweeps.add(resolved);
1425
- }
1426
- const previousTarget = this.aliases.get(alias);
1427
- if (previousTarget !== resolved) {
1428
- const previousResolved = previousTarget !== void 0 && this.pendingMetadataSweeps.size > 0 ? this.resolveKey(alias) : void 0;
1429
- this.removeAlias(alias);
1430
- this.aliases.set(alias, resolved);
1431
- let aliases = this.aliasesByTarget.get(resolved);
1432
- if (!aliases) this.aliasesByTarget.set(resolved, aliases = /* @__PURE__ */ new Set());
1433
- aliases.add(alias);
1434
- if (previousResolved !== void 0) this.sweepPendingEntryMetadata(previousResolved);
1435
- }
1436
- this.emit(alias);
1437
- this.emit(resolved, this.invalidatedAt.has(resolved) ? "invalidate" : void 0);
1438
- }
1439
- subscribe(key, listener) {
1440
- let listeners = this.listeners.get(key);
1441
- if (!listeners) {
1442
- listeners = /* @__PURE__ */ new Set();
1443
- this.listeners.set(key, listeners);
1444
- }
1445
- listeners.add(listener);
1446
- return () => {
1447
- listeners.delete(listener);
1448
- if (listeners.size === 0 && this.listeners.get(key) === listeners) {
1449
- this.listeners.delete(key);
1450
- this.sweepPendingEntryMetadata(key);
1451
- }
1452
- };
1453
- }
1454
- getInflight(key) {
1455
- return this.inflight.get(this.resolveKey(key));
1456
- }
1457
- setInflight(key, promise) {
1458
- this.inflight.set(this.resolveKey(key), promise);
1459
- }
1460
- deleteInflight(key) {
1461
- const resolved = this.resolveKey(key);
1462
- if (this.inflight.delete(resolved)) this.sweepPendingEntryMetadata(resolved);
1463
- }
1464
- scheduleGcSweep() {
1465
- if (this.gcSweepIntervalMs === false || this.gcTimer !== void 0) return;
1466
- const timer = setTimeout(() => {
1467
- this.gcTimer = void 0;
1468
- this.sweepExpiredEntries();
1469
- }, this.gcSweepIntervalMs);
1470
- timer.unref?.();
1471
- this.gcTimer = timer;
1472
- }
1473
- sweepExpiredEntries(now = Date.now()) {
1474
- const watched = /* @__PURE__ */ new Set();
1475
- for (const key of this.listeners.keys()) watched.add(this.resolveKey(key));
1476
- let remaining = false;
1477
- const swept = /* @__PURE__ */ new Set();
1478
- for (const [key, entry] of this.entries) {
1479
- if (entry.gcAt === void 0) continue;
1480
- if (now < entry.gcAt || entry.fetching || this.inflight.has(key) || watched.has(key)) {
1481
- remaining = true;
1482
- continue;
1483
- }
1484
- this.entries.delete(key);
1485
- this.persistence?.onDelete(key);
1486
- swept.add(key);
1487
- }
1488
- if (swept.size > 0) this.sweepEntryMetadata(swept);
1489
- if (remaining) this.scheduleGcSweep();
1490
- }
1491
- /**
1492
- * Entry eviction alone leaves the per-key metadata behind. `invalidatedAt`
1493
- * marks and provisional aliases are created per query invocation, so with
1494
- * dynamic keys they accumulate for the lifetime of the page even though the
1495
- * entries they describe are long gone.
1496
- */
1497
- sweepEntryMetadata(swept) {
1498
- const protectedKeys = /* @__PURE__ */ new Set();
1499
- for (const key of swept) if (this.hasMetadataOwner(key)) protectedKeys.add(key);
1500
- for (const key of swept) {
1501
- if (this.entries.has(key)) {
1502
- this.pendingMetadataSweeps.delete(key);
1503
- } else if (protectedKeys.has(key)) {
1504
- this.pendingMetadataSweeps.add(key);
1505
- } else {
1506
- this.pendingMetadataSweeps.delete(key);
1507
- this.invalidatedAt.delete(key);
1508
- }
1509
- }
1510
- const related = /* @__PURE__ */ new Set();
1511
- const targets = new Set(swept);
1512
- for (const target of targets) {
1513
- for (const alias of this.aliasesByTarget.get(target) ?? []) {
1514
- related.add(alias);
1515
- targets.add(alias);
1516
- }
1517
- }
1518
- const removable = [];
1519
- for (const alias of related) {
1520
- if (this.entries.has(alias) || this.listeners.has(alias) || this.inflight.has(alias))
1521
- continue;
1522
- const resolved = this.resolveKey(alias);
1523
- if (!swept.has(resolved)) continue;
1524
- if (this.entries.has(resolved) || protectedKeys.has(resolved)) continue;
1525
- removable.push(alias);
1526
- }
1527
- for (const alias of removable) {
1528
- this.removeAlias(alias);
1529
- this.invalidatedAt.delete(alias);
1530
- }
1531
- }
1532
- removeAlias(alias) {
1533
- const target = this.aliases.get(alias);
1534
- if (target === void 0) return;
1535
- this.aliases.delete(alias);
1536
- const aliases = this.aliasesByTarget.get(target);
1537
- aliases?.delete(alias);
1538
- if (aliases?.size === 0) this.aliasesByTarget.delete(target);
1539
- }
1540
- sweepPendingEntryMetadata(key) {
1541
- if (this.pendingMetadataSweeps.size === 0) return;
1542
- if (key !== void 0) {
1543
- const resolved = this.resolveKey(key);
1544
- if (this.pendingMetadataSweeps.has(resolved)) {
1545
- this.sweepEntryMetadata(/* @__PURE__ */ new Set([resolved]));
1546
- }
1547
- return;
1548
- }
1549
- this.sweepEntryMetadata(new Set(this.pendingMetadataSweeps));
1550
- }
1551
- emit(key, event) {
1552
- this.notifyListeners(key, event);
1553
- if (this.listeners.size === 0) return;
1554
- for (const [alias, target] of this.aliases) {
1555
- if (!this.listeners.has(alias)) continue;
1556
- if (this.resolveKey(target) === key) {
1557
- this.notifyListeners(alias, event);
1558
- }
1559
- }
1560
- }
1561
- notifyListeners(key, event) {
1562
- for (const listener of this.listeners.get(key) ?? []) {
1563
- try {
1564
- listener(event);
1565
- } catch (error) {
1566
- const detail = error instanceof Error ? error.stack ?? error.message : String(error);
1567
- console.warn(`[farm:client-cache] cache listener failed: ${detail}`);
1568
- }
1569
- }
1570
- }
1571
- };
1572
- __name(_FarmClientDataCache, "FarmClientDataCache");
1573
- var FarmClientDataCache = _FarmClientDataCache;
1574
- var FARM_CLIENT_DATA_CACHE = /* @__PURE__ */ Symbol.for("farm.clientDataCache");
1575
- var clientCacheGlobal = globalThis;
1576
- var sharedFarmClientDataCache = clientCacheGlobal[FARM_CLIENT_DATA_CACHE] ?? (clientCacheGlobal[FARM_CLIENT_DATA_CACHE] = new FarmClientDataCache());
1577
- function getFarmClientDataCache() {
1578
- return sharedFarmClientDataCache;
1579
- }
1580
- __name(getFarmClientDataCache, "getFarmClientDataCache");
1581
10
 
1582
- // src/client-revalidation.ts
1583
- function attachRevalidationListeners(refresh, options = {}) {
1584
- if (typeof window === "undefined") return () => {
1585
- };
1586
- const onFocus = options.refetchOnWindowFocus === false ? void 0 : refresh;
1587
- const onOnline = options.refetchOnReconnect === false ? void 0 : refresh;
1588
- if (onFocus) window.addEventListener("focus", onFocus);
1589
- if (onOnline) window.addEventListener("online", onOnline);
1590
- return () => {
1591
- if (onFocus) window.removeEventListener("focus", onFocus);
1592
- if (onOnline) window.removeEventListener("online", onOnline);
1593
- };
1594
- }
1595
- __name(attachRevalidationListeners, "attachRevalidationListeners");
11
+ var _chunkY4YWHNKUcjs = require('./chunk-Y4YWHNKU.cjs');
12
+ require('./chunk-I7PUUDGY.cjs');
13
+ require('./chunk-SK35NQKK.cjs');
14
+ require('./chunk-H6G5INWM.cjs');
15
+ require('./chunk-ZEG3OPIB.cjs');
16
+ require('./chunk-LIUGYUX3.cjs');
17
+ require('./chunk-E3UK5IIB.cjs');
18
+ require('./chunk-S3JO3N4H.cjs');
1596
19
 
1597
- // src/server-query-protocol.ts
1598
- var FARM_SERVER_QUERY_RESULT_VERSION = 1;
1599
- function isFarmServerQueryResult(value) {
1600
- if (!value || typeof value !== "object") return false;
1601
- const metadata = value.__farmServerQuery;
1602
- return metadata?.version === FARM_SERVER_QUERY_RESULT_VERSION && typeof metadata.key === "string" && (metadata.staleTime === false || typeof metadata.staleTime === "number") && typeof metadata.updatedAt === "number" && "data" in value;
1603
- }
1604
- __name(isFarmServerQueryResult, "isFarmServerQueryResult");
1605
20
 
1606
- // src/server-query-runtime.ts
1607
- var FARM_SERVER_QUERY_CLIENT_STATE = /* @__PURE__ */ Symbol.for("farm.serverQueryClientState");
1608
- var serverQueryClientGlobal = globalThis;
1609
- var serverQueryClientState = serverQueryClientGlobal[FARM_SERVER_QUERY_CLIENT_STATE] ?? (serverQueryClientGlobal[FARM_SERVER_QUERY_CLIENT_STATE] = {
1610
- functionIds: /* @__PURE__ */ new WeakMap(),
1611
- nextFunctionId: 0,
1612
- active: [],
1613
- latestOwners: /* @__PURE__ */ new Map(),
1614
- owners: /* @__PURE__ */ new Set()
1615
- });
1616
- serverQueryClientState.latestOwners ?? (serverQueryClientState.latestOwners = /* @__PURE__ */ new Map());
1617
- serverQueryClientState.owners ?? (serverQueryClientState.owners = /* @__PURE__ */ new Set());
1618
- function isServerQueryOwnerSuperseded(owner, key) {
1619
- const cache = getFarmClientDataCache();
1620
- const resolved = cache.resolveKey(key);
1621
- for (const superseded of owner.supersededKeys ?? []) {
1622
- if (cache.resolveKey(superseded) === resolved) return true;
1623
- }
1624
- return false;
1625
- }
1626
- __name(isServerQueryOwnerSuperseded, "isServerQueryOwnerSuperseded");
1627
- function claimServerQueryKey(owner, key) {
1628
- if (isServerQueryOwnerSuperseded(owner, key)) return false;
1629
- const resolved = getFarmClientDataCache().resolveKey(key);
1630
- for (const older of serverQueryClientState.owners) {
1631
- if (older === owner) break;
1632
- older.supersededKeys.add(resolved);
1633
- }
1634
- return true;
1635
- }
1636
- __name(claimServerQueryKey, "claimServerQueryKey");
1637
- var RAW_SERVER_QUERY_SYMBOL = /* @__PURE__ */ Symbol.for("farm.server-query");
1638
- function assertNotRawServerQueryInBrowser(query) {
1639
- if (typeof window === "undefined" || typeof document === "undefined") return;
1640
- if (!query?.[RAW_SERVER_QUERY_SYMBOL]) return;
1641
- throw new Error(
1642
- [
1643
- "useServerQuery received a raw server query implementation in the browser.",
1644
- "Server query handlers run only on the server. Enable the server-function transform (add @farm.js/plugin/rsc and set experimental.serverActions: true in farm.config.ts) so client imports become server references,",
1645
- "or call the query from server code / an API route (createAPIClient) instead."
1646
- ].join("\n")
1647
- );
1648
- }
1649
- __name(assertNotRawServerQueryInBrowser, "assertNotRawServerQueryInBrowser");
1650
- function beginFarmServerQueryAction(actionId, args) {
1651
- const active = serverQueryClientState.active.at(-1);
1652
- return {
1653
- actionId,
1654
- args,
1655
- provisionalKey: active?.provisionalKey,
1656
- owner: active?.owner
1657
- };
1658
- }
1659
- __name(beginFarmServerQueryAction, "beginFarmServerQueryAction");
1660
- function completeFarmServerQueryAction(invocation, value) {
1661
- if (!isFarmServerQueryResult(value)) return value;
1662
- const cache = getFarmClientDataCache();
1663
- const metadata = value.__farmServerQuery;
1664
- if (!shouldApplyFarmServerQueryActionResult(invocation)) {
1665
- return value.data;
1666
- }
1667
- if (invocation.provisionalKey) {
1668
- cache.alias(invocation.provisionalKey, metadata.key);
1669
- }
1670
- const owner = invocation.owner;
1671
- if (owner && serverQueryClientState.owners.has(owner) && !claimServerQueryKey(owner, metadata.key)) {
1672
- return value.data;
1673
- }
1674
- const invalidated = invocation.owner?.invalidations?.has(
1675
- metadata.key
1676
- );
1677
- cache.set(metadata.key, {
1678
- data: value.data,
1679
- updatedAt: metadata.updatedAt,
1680
- staleAt: invalidated ? 0 : metadata.staleTime === false ? Number.POSITIVE_INFINITY : metadata.updatedAt + metadata.staleTime,
1681
- status: "success",
1682
- error: null,
1683
- fetching: false,
1684
- persist: metadata.persist === true ? true : void 0
1685
- });
1686
- return value.data;
1687
- }
1688
- __name(completeFarmServerQueryAction, "completeFarmServerQueryAction");
1689
- function shouldApplyFarmServerQueryActionResult(invocation) {
1690
- if (!invocation.provisionalKey || !invocation.owner) return true;
1691
- return isCurrentServerQueryOwner(invocation.provisionalKey, invocation.owner);
1692
- }
1693
- __name(shouldApplyFarmServerQueryActionResult, "shouldApplyFarmServerQueryActionResult");
1694
- function isCurrentServerQueryOwner(provisionalKey, owner) {
1695
- return serverQueryClientState.latestOwners.get(provisionalKey) === owner && !isServerQueryOwnerSuperseded(owner, provisionalKey);
1696
- }
1697
- __name(isCurrentServerQueryOwner, "isCurrentServerQueryOwner");
1698
- function createServerQueryCallKey(query, input) {
1699
- let id = serverQueryClientState.functionIds.get(query);
1700
- if (!id) {
1701
- id = ++serverQueryClientState.nextFunctionId;
1702
- serverQueryClientState.functionIds.set(query, id);
1703
- }
1704
- return createFarmCacheKey(["server-query-call", id, input]);
1705
- }
1706
- __name(createServerQueryCallKey, "createServerQueryCallKey");
1707
- async function fetchServerQuery(query, input, options = {}) {
1708
- const cache = getFarmClientDataCache();
1709
- const provisionalKey = createServerQueryCallKey(query, input);
1710
- const entry = cache.get(provisionalKey);
1711
- const stale = cache.isStale(provisionalKey);
1712
- const inflight = cache.getInflight(provisionalKey);
1713
- if (!options.force && entry && stale && (entry.status !== "pending" || entry.updatedAt !== 0) && entry.status !== "error" && (options.swr ?? true)) {
1714
- if (!inflight) {
1715
- void executeServerQuery(query, input, provisionalKey, options).catch(() => void 0);
1716
- }
1717
- return entry.data;
1718
- }
1719
- if (inflight && !options.force) return inflight;
1720
- if (!options.force && entry && !stale && entry.status !== "error") return entry.data;
1721
- return executeServerQuery(query, input, provisionalKey, options);
1722
- }
1723
- __name(fetchServerQuery, "fetchServerQuery");
1724
- function prefetchServerQuery(query, input, options = {}) {
1725
- return fetchServerQuery(query, input, options);
1726
- }
1727
- __name(prefetchServerQuery, "prefetchServerQuery");
1728
- async function executeServerQuery(query, input, provisionalKey, options) {
1729
- assertNotRawServerQueryInBrowser(query);
1730
- const cache = getFarmClientDataCache();
1731
- const inflight = cache.getInflight(provisionalKey);
1732
- if (inflight && !options.force) return inflight;
1733
- const owner = {
1734
- invalidations: trackFarmClientCacheInvalidations(cache),
1735
- supersededKeys: /* @__PURE__ */ new Set()
1736
- };
1737
- serverQueryClientState.latestOwners.set(provisionalKey, owner);
1738
- serverQueryClientState.owners.add(owner);
1739
- claimServerQueryKey(owner, provisionalKey);
1740
- const previous = cache.get(provisionalKey);
1741
- cache.set(provisionalKey, {
1742
- data: previous?.data,
1743
- updatedAt: previous?.updatedAt ?? 0,
1744
- staleAt: previous?.staleAt ?? 0,
1745
- gcAt: previous?.gcAt,
1746
- invalidatedAt: previous?.invalidatedAt,
1747
- status: "pending",
1748
- error: null,
1749
- fetching: true
1750
- });
1751
- let promise;
1752
- promise = (async () => {
1753
- await Promise.resolve();
1754
- try {
1755
- serverQueryClientState.active.push({ provisionalKey, owner });
1756
- let pending;
1757
- try {
1758
- pending = query(input);
1759
- } finally {
1760
- serverQueryClientState.active.pop();
1761
- }
1762
- const data = await pending;
1763
- const transported = cache.get(provisionalKey);
1764
- if (isCurrentServerQueryOwner(provisionalKey, owner) && (!transported || transported.fetching)) {
1765
- const updatedAt = Date.now();
1766
- cache.set(provisionalKey, {
1767
- data,
1768
- updatedAt,
1769
- staleAt: owner.invalidations.has(provisionalKey) ? 0 : options.staleTime === false ? Number.POSITIVE_INFINITY : updatedAt + (options.staleTime ?? 0),
1770
- status: "success",
1771
- error: null,
1772
- fetching: false
1773
- });
1774
- }
1775
- return data;
1776
- } catch (cause) {
1777
- const error = normalizeServerQueryError(cause);
1778
- if (isCurrentServerQueryOwner(provisionalKey, owner)) {
1779
- const current = cache.get(provisionalKey);
1780
- cache.set(provisionalKey, {
1781
- data: current?.data,
1782
- updatedAt: current?.updatedAt ?? 0,
1783
- staleAt: current?.staleAt ?? 0,
1784
- gcAt: current?.gcAt,
1785
- invalidatedAt: current?.invalidatedAt,
1786
- status: "error",
1787
- error,
1788
- fetching: false
1789
- });
1790
- }
1791
- throw error;
1792
- } finally {
1793
- const invalidated = isCurrentServerQueryOwner(provisionalKey, owner) && owner.invalidations.has(provisionalKey);
1794
- owner.invalidations.dispose();
1795
- serverQueryClientState.owners.delete(owner);
1796
- owner.supersededKeys.clear();
1797
- if (cache.getInflight(provisionalKey) === promise) {
1798
- cache.deleteInflight(provisionalKey);
1799
- }
1800
- if (serverQueryClientState.latestOwners.get(provisionalKey) === owner) {
1801
- serverQueryClientState.latestOwners.delete(provisionalKey);
1802
- }
1803
- if (invalidated) cache.invalidate(provisionalKey);
1804
- }
1805
- })();
1806
- cache.setInflight(provisionalKey, promise);
1807
- return promise;
1808
- }
1809
- __name(executeServerQuery, "executeServerQuery");
1810
- function normalizeServerQueryError(cause) {
1811
- if (cause instanceof Error) return cause;
1812
- const error = new Error(typeof cause === "string" ? cause : "Server query failed");
1813
- error.cause = cause;
1814
- return error;
1815
- }
1816
- __name(normalizeServerQueryError, "normalizeServerQueryError");
1817
21
 
1818
- // src/server-query-client.ts
1819
- function useServerQuery(query, input, options = {}) {
1820
- const cache = getFarmClientDataCache();
1821
- const key = createServerQueryCallKey(query, input);
1822
- const inputRef = (0, import_react.useRef)(input);
1823
- const optionsRef = (0, import_react.useRef)(options);
1824
- const mountedKeyRef = (0, import_react.useRef)(void 0);
1825
- const pendingInvalidationRef = (0, import_react.useRef)(false);
1826
- inputRef.current = input;
1827
- optionsRef.current = options;
1828
- const subscribe = (0, import_react.useCallback)(
1829
- (listener) => cache.subscribe(key, (event) => {
1830
- if (event === "invalidate") pendingInvalidationRef.current = true;
1831
- else if (cache.get(key)?.fetching) {
1832
- pendingInvalidationRef.current = false;
1833
- }
1834
- listener();
1835
- }),
1836
- [cache, key]
1837
- );
1838
- const getSnapshot = (0, import_react.useCallback)(() => cache.get(key), [cache, key]);
1839
- const entry = (0, import_react.useSyncExternalStore)(subscribe, getSnapshot, () => void 0);
1840
- const run = (0, import_react.useCallback)(
1841
- (force = false) => {
1842
- pendingInvalidationRef.current = false;
1843
- return fetchServerQuery(query, inputRef.current, {
1844
- ...optionsRef.current,
1845
- force
1846
- });
1847
- },
1848
- [query]
1849
- );
1850
- (0, import_react.useEffect)(() => {
1851
- if (options.enabled === false) {
1852
- mountedKeyRef.current = void 0;
1853
- return;
1854
- }
1855
- const firstReadForKey = mountedKeyRef.current !== key;
1856
- if (firstReadForKey) mountedKeyRef.current = key;
1857
- if (firstReadForKey && (!entry || cache.isStale(key)) || pendingInvalidationRef.current && entry?.invalidatedAt !== void 0 && !entry.fetching) {
1858
- void run().catch(() => void 0);
1859
- }
1860
- }, [cache, entry, key, options.enabled, run]);
1861
- (0, import_react.useEffect)(() => {
1862
- if (options.enabled === false) return;
1863
- return attachRevalidationListeners(
1864
- () => {
1865
- if (cache.isStale(key)) void run().catch(() => void 0);
1866
- },
1867
- {
1868
- refetchOnWindowFocus: options.refetchOnWindowFocus,
1869
- refetchOnReconnect: options.refetchOnReconnect
1870
- }
1871
- );
1872
- }, [cache, key, options.enabled, options.refetchOnReconnect, options.refetchOnWindowFocus, run]);
1873
- const status = entry?.status ?? (entry ? "success" : "idle");
1874
- const fetching = entry?.fetching ?? false;
1875
- return {
1876
- data: entry?.data,
1877
- error: entry?.error ?? null,
1878
- status,
1879
- pending: status === "pending" && (entry?.updatedAt ?? 0) === 0,
1880
- fetching,
1881
- stale: cache.isStale(key),
1882
- refetch: /* @__PURE__ */ __name(() => run(true), "refetch")
1883
- };
1884
- }
1885
- __name(useServerQuery, "useServerQuery");
1886
- // Annotate the CommonJS export names for ESM import in node:
1887
- 0 && (module.exports = {
1888
- beginFarmServerQueryAction,
1889
- completeFarmServerQueryAction,
1890
- fetchServerQuery,
1891
- prefetchServerQuery,
1892
- shouldApplyFarmServerQueryActionResult,
1893
- useServerQuery
1894
- });
22
+
23
+
24
+
25
+
26
+ exports.beginFarmServerQueryAction = _chunkY4YWHNKUcjs.beginFarmServerQueryAction; exports.completeFarmServerQueryAction = _chunkY4YWHNKUcjs.completeFarmServerQueryAction; exports.fetchServerQuery = _chunkY4YWHNKUcjs.fetchServerQuery; exports.prefetchServerQuery = _chunkY4YWHNKUcjs.prefetchServerQuery; exports.shouldApplyFarmServerQueryActionResult = _chunkY4YWHNKUcjs.shouldApplyFarmServerQueryActionResult; exports.useServerQuery = _chunkC3VRMB6Hcjs.useServerQuery;