@farm.js/core 0.1.17 → 0.1.18

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