@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
@@ -1,4109 +1,74 @@
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);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
33
2
 
34
- // src/storage/index.ts
35
- var storage_exports = {};
36
- __export(storage_exports, {
37
- createFarmStorage: () => createFarmStorage,
38
- createStorageClient: () => createStorageClient,
39
- databaseStorage: () => databaseStorage,
40
- defineStorageClient: () => defineStorageClient,
41
- disposeStorage: () => disposeStorage,
42
- driverStorage: () => driverStorage,
43
- getStorage: () => getStorage,
44
- initStorage: () => initStorage,
45
- libsqlStorage: () => libsqlStorage,
46
- localStorage: () => localStorage,
47
- memoryStorage: () => memoryStorage,
48
- mongodbStorage: () => mongodbStorage,
49
- mysql2Storage: () => mysql2Storage,
50
- mysqlStorage: () => mysqlStorage,
51
- netlifyBlobsStorage: () => netlifyBlobsStorage,
52
- pgStorage: () => pgStorage,
53
- pgliteStorage: () => pgliteStorage,
54
- planetscaleStorage: () => planetscaleStorage,
55
- postgresStorage: () => postgresStorage,
56
- redisStorage: () => redisStorage,
57
- resolveStorageRuntimeClient: () => resolveStorageRuntimeClient,
58
- s3Storage: () => s3Storage,
59
- sqliteStorage: () => sqliteStorage,
60
- upstashStorage: () => upstashStorage,
61
- vercelBlobStorage: () => vercelBlobStorage,
62
- vercelKVStorage: () => vercelKVStorage
63
- });
64
- function createMemoryStorage() {
65
- return (0, import_unstorage.createStorage)({
66
- driver: (0, import_memory.default)()
67
- });
68
- }
69
- function readGlobalStorage() {
70
- return globalThis[GLOBAL_STORAGE_KEY];
71
- }
72
- function writeGlobalStorage(storage) {
73
- globalThis[GLOBAL_STORAGE_KEY] = storage;
74
- return storage;
75
- }
76
- function getActiveGlobalStorage() {
77
- const existing = readGlobalStorage();
78
- if (existing) {
79
- return existing;
80
- }
81
- return writeGlobalStorage(createMemoryStorage());
82
- }
83
- function normalizeMountKey(base) {
84
- return (base || "").trim().replace(/^[:/\\]+|[:/\\]+$/g, "").replace(/[\\/]+/g, ":");
85
- }
86
- function isDriverInstance(value) {
87
- return !!value && typeof value === "object" && typeof value.getItem === "function" && typeof value.getKeys === "function";
88
- }
89
- function isStorageInstance(value) {
90
- return !!value && typeof value === "object" && typeof value.mount === "function" && typeof value.getMount === "function";
91
- }
92
- function isStorageClient(value) {
93
- return !!value && typeof value === "object" && value.kind === "farm-storage-client" && typeof value.resolveDriver === "function" && typeof value.createStorage === "function";
94
- }
95
- function isDatabaseDriverName(name) {
96
- return name in DATABASE_CONNECTORS;
97
- }
98
- function extractDriverOptions(config) {
99
- const source = config;
100
- const {
101
- client: _client,
102
- driver: _driver,
103
- mounts: _mounts,
104
- options,
105
- tableName: _tableName,
106
- ...inlineOptions
107
- } = source;
108
- const hasInlineOptions = Object.keys(inlineOptions).length > 0;
109
- if (options && typeof options === "object" && !Array.isArray(options)) {
110
- return hasInlineOptions ? { ...inlineOptions, ...options } : options;
111
- }
112
- if (hasInlineOptions) {
113
- return inlineOptions;
114
- }
115
- return options;
116
- }
117
- async function loadBuiltinDriver(name, options) {
118
- const modulePath = import_unstorage.builtinDrivers[name];
119
- if (!modulePath) {
120
- throw new Error(`Unsupported storage driver "${name}".`);
121
- }
122
- const module2 = await loadModule(modulePath);
123
- return module2.default(options);
124
- }
125
- async function loadDatabaseDriver(config) {
126
- const connectorEntry = DATABASE_CONNECTORS[config.driver];
127
- const [{ createDatabase }, connectorModule, db0DriverModule] = await Promise.all([
128
- loadModule("db0"),
129
- connectorEntry.load(),
130
- loadModule("unstorage/drivers/db0")
131
- ]);
132
- const database = createDatabase(connectorModule.default(extractDriverOptions(config) || {}));
133
- const driver = db0DriverModule.default({
134
- database,
135
- tableName: config.tableName
136
- });
137
- return {
138
- ...driver,
139
- async dispose() {
140
- await database.dispose();
141
- }
142
- };
143
- }
144
- async function resolveDriver(config) {
145
- if (config && isStorageClient(config)) {
146
- return config.resolveDriver();
147
- }
148
- const driverInput = config?.driver ?? "memory";
149
- if (typeof driverInput === "function") {
150
- return await driverInput();
151
- }
152
- if (isDriverInstance(driverInput)) {
153
- return driverInput;
154
- }
155
- if (isDatabaseDriverName(driverInput)) {
156
- return loadDatabaseDriver(config);
157
- }
158
- if (driverInput === "local") {
159
- return loadBuiltinDriver("fs-lite", extractDriverOptions(config));
160
- }
161
- return loadBuiltinDriver(
162
- driverInput,
163
- extractDriverOptions(config)
164
- );
165
- }
166
- function createStorageClientFromResolver(resolveDriver2) {
167
- let driverPromise;
168
- let storagePromise;
169
- const ensureDriver = /* @__PURE__ */ __name(() => {
170
- if (driverPromise) return driverPromise;
171
- const pending = Promise.resolve().then(resolveDriver2);
172
- driverPromise = pending;
173
- void pending.catch(() => {
174
- if (driverPromise === pending) {
175
- driverPromise = void 0;
176
- storagePromise = void 0;
177
- }
178
- });
179
- return pending;
180
- }, "ensureDriver");
181
- const ensureStorage = /* @__PURE__ */ __name(() => {
182
- if (storagePromise) return storagePromise;
183
- const pending = ensureDriver().then(
184
- (driver) => (0, import_unstorage.createStorage)({
185
- driver
186
- })
187
- );
188
- storagePromise = pending;
189
- void pending.catch(() => {
190
- if (storagePromise === pending) storagePromise = void 0;
191
- });
192
- return pending;
193
- }, "ensureStorage");
194
- const target = {
195
- kind: "farm-storage-client",
196
- ready: ensureStorage,
197
- createStorage: ensureStorage,
198
- resolveDriver: ensureDriver
199
- };
200
- return new Proxy(target, {
201
- get(currentTarget, prop, receiver) {
202
- if (prop === "then") {
203
- return void 0;
204
- }
205
- if (Reflect.has(currentTarget, prop)) {
206
- return Reflect.get(currentTarget, prop, receiver);
207
- }
208
- return (...args) => ensureStorage().then(async (storage) => {
209
- const member = Reflect.get(storage, prop);
210
- if (typeof member !== "function") {
211
- return member;
212
- }
213
- const result = Reflect.apply(member, storage, args);
214
- if (prop === "dispose") {
215
- return Promise.resolve(result).finally(() => {
216
- storagePromise = void 0;
217
- driverPromise = void 0;
218
- });
219
- }
220
- return result;
221
- });
222
- }
223
- });
224
- }
225
- function defineStorageClient(resolveDriver2) {
226
- return createStorageClientFromResolver(resolveDriver2);
227
- }
228
- function createStorageClient(config) {
229
- return defineStorageClient(() => resolveDriver(config));
230
- }
231
- function driverStorage(driver) {
232
- return defineStorageClient(() => typeof driver === "function" ? driver() : driver);
233
- }
234
- function databaseStorage(database, options = {}) {
235
- return defineStorageClient(async () => {
236
- const db0DriverModule = await loadModule("unstorage/drivers/db0");
237
- const { dispose: _dispose, ...driver } = db0DriverModule.default({
238
- database,
239
- tableName: options.tableName
240
- });
241
- return driver;
242
- });
243
- }
244
- function memoryStorage() {
245
- return createStorageClient({ driver: "memory" });
246
- }
247
- function localStorage(options = {}) {
248
- return createStorageClient({
249
- driver: "local",
250
- ...options
251
- });
252
- }
253
- function sqliteStorage(options) {
254
- return createStorageClient({
255
- driver: "sqlite",
256
- ...options
257
- });
258
- }
259
- function mysqlStorage(options) {
260
- return createStorageClient({
261
- driver: "mysql",
262
- ...options
263
- });
264
- }
265
- function mysql2Storage(options) {
266
- return mysqlStorage(options);
267
- }
268
- function postgresStorage(options) {
269
- return createStorageClient({
270
- driver: "postgres",
271
- ...options
272
- });
273
- }
274
- function pgStorage(options) {
275
- return postgresStorage(options);
276
- }
277
- function pgliteStorage(options) {
278
- return createStorageClient({
279
- driver: "pglite",
280
- ...options
281
- });
282
- }
283
- function planetscaleStorage(options) {
284
- return createStorageClient({
285
- driver: "planetscale",
286
- ...options
287
- });
288
- }
289
- function libsqlStorage(options) {
290
- return createStorageClient({
291
- driver: "libsql",
292
- ...options
293
- });
294
- }
295
- function redisStorage(options) {
296
- return createStorageClient({
297
- driver: "redis",
298
- ...options
299
- });
300
- }
301
- function s3Storage(options) {
302
- return createStorageClient({
303
- driver: "s3",
304
- ...options
305
- });
306
- }
307
- function mongodbStorage(options) {
308
- return createStorageClient({
309
- driver: "mongodb",
310
- ...options
311
- });
312
- }
313
- function upstashStorage(options) {
314
- return createStorageClient({
315
- driver: "upstash",
316
- ...options
317
- });
318
- }
319
- function netlifyBlobsStorage(options) {
320
- return createStorageClient({
321
- driver: "netlify-blobs",
322
- ...options
323
- });
324
- }
325
- function vercelKVStorage(options) {
326
- return createStorageClient({
327
- driver: "vercel-kv",
328
- ...options
329
- });
330
- }
331
- function vercelBlobStorage(options) {
332
- return createStorageClient({
333
- driver: "vercel-blob",
334
- ...options
335
- });
336
- }
337
- async function mountNamespaces(storage, mounts) {
338
- if (!mounts) {
339
- return;
340
- }
341
- for (const [base, config] of Object.entries(mounts)) {
342
- storage.mount(normalizeMountKey(base), await resolveDriver(config));
343
- }
344
- }
345
- async function createFarmStorage(config = {}) {
346
- if (isStorageInstance(config)) {
347
- return config;
348
- }
349
- if (isStorageClient(config)) {
350
- return config.createStorage();
351
- }
352
- const rootConfig = isStorageClient(config.client) ? config.client : config;
353
- const storage = (0, import_unstorage.createStorage)({
354
- driver: await resolveDriver(rootConfig)
355
- });
356
- try {
357
- await mountNamespaces(storage, config.mounts);
358
- } catch (error) {
359
- await storage.dispose().catch(() => {
360
- });
361
- throw error;
362
- }
363
- return storage;
364
- }
365
- async function resolveStorageRuntimeClient(config) {
366
- if (!config || isStorageInstance(config) || isStorageClient(config)) {
367
- return void 0;
368
- }
369
- const client = config.client;
370
- if (!client || isStorageInstance(client) || isStorageClient(client)) {
371
- return void 0;
372
- }
373
- return typeof client === "function" ? await client() : client;
374
- }
375
- async function initStorage(config = {}) {
376
- globalStorage = getActiveGlobalStorage();
377
- const nextStorage = await createFarmStorage(config);
378
- const previousStorage = globalStorage;
379
- globalStorage = writeGlobalStorage(nextStorage);
380
- if (previousStorage !== nextStorage) {
381
- await previousStorage.dispose().catch(() => {
382
- });
383
- }
384
- return globalStorage;
385
- }
386
- function getStorage(namespace) {
387
- globalStorage = getActiveGlobalStorage();
388
- const base = normalizeMountKey(namespace);
389
- if (!base) {
390
- return globalStorage;
391
- }
392
- const namespaced = (0, import_unstorage.prefixStorage)(globalStorage, base);
393
- const store = globalStorage;
394
- const prefix = `${base}:`;
395
- const stripPrefix = /* @__PURE__ */ __name((key) => key.startsWith(prefix) ? key.slice(prefix.length) : key, "stripPrefix");
396
- const viewUnwatchers = /* @__PURE__ */ new Set();
397
- const releaseViewWatchers = /* @__PURE__ */ __name(async () => {
398
- const current = [...viewUnwatchers];
399
- viewUnwatchers.clear();
400
- await Promise.all(current.map((unwatch) => unwatch()));
401
- }, "releaseViewWatchers");
402
- return {
403
- ...namespaced,
404
- // Scope the wipe to the namespace instead of the whole storage, and keep
405
- // the caller's base so `clear("sessions")` cannot take unrelated keys with
406
- // it. Dropping the argument silently widens a targeted clear into a
407
- // namespace-wide delete.
408
- async clear(base2, opts) {
409
- const keys = await namespaced.getKeys(base2);
410
- await Promise.all(keys.map((key) => namespaced.removeItem(key, opts)));
411
- },
412
- async watch(callback) {
413
- const unwatch = await store.watch((event, key) => {
414
- if (key.startsWith(prefix)) callback(event, stripPrefix(key));
415
- });
416
- viewUnwatchers.add(unwatch);
417
- return async () => {
418
- viewUnwatchers.delete(unwatch);
419
- await unwatch();
420
- };
421
- },
422
- async unwatch() {
423
- await releaseViewWatchers();
424
- },
425
- async dispose() {
426
- await releaseViewWatchers();
427
- },
428
- getMount(key = "") {
429
- return store.getMount(prefix + key);
430
- },
431
- getMounts(base2 = "", options) {
432
- return store.getMounts(prefix + base2, options).map((mount) => ({ ...mount, base: stripPrefix(mount.base) }));
433
- }
434
- };
435
- }
436
- async function disposeStorage() {
437
- globalStorage = getActiveGlobalStorage();
438
- const previousStorage = globalStorage;
439
- globalStorage = writeGlobalStorage(createMemoryStorage());
440
- await previousStorage.dispose().catch(() => {
441
- });
442
- }
443
- var import_unstorage, import_memory, loadModule, DATABASE_CONNECTORS, GLOBAL_STORAGE_KEY, globalStorage;
444
- var init_storage = __esm({
445
- "src/storage/index.ts"() {
446
- "use strict";
447
- import_unstorage = require("unstorage");
448
- import_memory = __toESM(require("unstorage/drivers/memory"));
449
- loadModule = /* @__PURE__ */ __name((specifier) => import(
450
- /* @vite-ignore */
451
- specifier
452
- ), "loadModule");
453
- DATABASE_CONNECTORS = {
454
- sqlite: {
455
- connector: "node-sqlite",
456
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/node-sqlite"), "load")
457
- },
458
- "node-sqlite": {
459
- connector: "node-sqlite",
460
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/node-sqlite"), "load")
461
- },
462
- sqlite3: {
463
- connector: "sqlite3",
464
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/sqlite3"), "load")
465
- },
466
- "better-sqlite3": {
467
- connector: "better-sqlite3",
468
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/better-sqlite3"), "load")
469
- },
470
- postgres: {
471
- connector: "postgresql",
472
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/postgresql"), "load")
473
- },
474
- postgresql: {
475
- connector: "postgresql",
476
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/postgresql"), "load")
477
- },
478
- pg: {
479
- connector: "postgresql",
480
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/postgresql"), "load")
481
- },
482
- mysql: {
483
- connector: "mysql2",
484
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/mysql2"), "load")
485
- },
486
- mysql2: {
487
- connector: "mysql2",
488
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/mysql2"), "load")
489
- },
490
- pglite: {
491
- connector: "pglite",
492
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/pglite"), "load")
493
- },
494
- planetscale: {
495
- connector: "planetscale",
496
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/planetscale"), "load")
497
- },
498
- libsql: {
499
- connector: "libsql",
500
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/libsql/node"), "load")
501
- },
502
- "libsql-node": {
503
- connector: "libsql-node",
504
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/libsql/node"), "load")
505
- },
506
- "libsql-http": {
507
- connector: "libsql-http",
508
- load: /* @__PURE__ */ __name(() => loadModule("db0/connectors/libsql/http"), "load")
509
- }
510
- };
511
- __name(createMemoryStorage, "createMemoryStorage");
512
- GLOBAL_STORAGE_KEY = /* @__PURE__ */ Symbol.for("farmjs.storage.global");
513
- __name(readGlobalStorage, "readGlobalStorage");
514
- __name(writeGlobalStorage, "writeGlobalStorage");
515
- __name(getActiveGlobalStorage, "getActiveGlobalStorage");
516
- globalStorage = getActiveGlobalStorage();
517
- __name(normalizeMountKey, "normalizeMountKey");
518
- __name(isDriverInstance, "isDriverInstance");
519
- __name(isStorageInstance, "isStorageInstance");
520
- __name(isStorageClient, "isStorageClient");
521
- __name(isDatabaseDriverName, "isDatabaseDriverName");
522
- __name(extractDriverOptions, "extractDriverOptions");
523
- __name(loadBuiltinDriver, "loadBuiltinDriver");
524
- __name(loadDatabaseDriver, "loadDatabaseDriver");
525
- __name(resolveDriver, "resolveDriver");
526
- __name(createStorageClientFromResolver, "createStorageClientFromResolver");
527
- __name(defineStorageClient, "defineStorageClient");
528
- __name(createStorageClient, "createStorageClient");
529
- __name(driverStorage, "driverStorage");
530
- __name(databaseStorage, "databaseStorage");
531
- __name(memoryStorage, "memoryStorage");
532
- __name(localStorage, "localStorage");
533
- __name(sqliteStorage, "sqliteStorage");
534
- __name(mysqlStorage, "mysqlStorage");
535
- __name(mysql2Storage, "mysql2Storage");
536
- __name(postgresStorage, "postgresStorage");
537
- __name(pgStorage, "pgStorage");
538
- __name(pgliteStorage, "pgliteStorage");
539
- __name(planetscaleStorage, "planetscaleStorage");
540
- __name(libsqlStorage, "libsqlStorage");
541
- __name(redisStorage, "redisStorage");
542
- __name(s3Storage, "s3Storage");
543
- __name(mongodbStorage, "mongodbStorage");
544
- __name(upstashStorage, "upstashStorage");
545
- __name(netlifyBlobsStorage, "netlifyBlobsStorage");
546
- __name(vercelKVStorage, "vercelKVStorage");
547
- __name(vercelBlobStorage, "vercelBlobStorage");
548
- __name(mountNamespaces, "mountNamespaces");
549
- __name(createFarmStorage, "createFarmStorage");
550
- __name(resolveStorageRuntimeClient, "resolveStorageRuntimeClient");
551
- __name(initStorage, "initStorage");
552
- __name(getStorage, "getStorage");
553
- __name(disposeStorage, "disposeStorage");
554
- }
555
- });
556
3
 
557
- // src/schema-capabilities.ts
558
- function assertNoSchemaListField(field, fieldPath, target) {
559
- if (!field.list) {
560
- return;
561
- }
562
- throw new Error(
563
- `Schema field "${fieldPath}" declares list: true, but ${target} does not support list fields. Use type: "json" for an array value or model the values in a related table.`
564
- );
565
- }
566
- var init_schema_capabilities = __esm({
567
- "src/schema-capabilities.ts"() {
568
- "use strict";
569
- __name(assertNoSchemaListField, "assertNoSchemaListField");
570
- }
571
- });
572
4
 
573
- // src/schema-primary-key.ts
574
- function assertSupportedPrimaryKeyField(location, field) {
575
- if (!field.primaryKey || SUPPORTED_PRIMARY_KEY_TYPES.has(field.type)) {
576
- return;
577
- }
578
- throw new Error(
579
- `Schema primary-key field "${location}" uses unsupported type "${field.type}". Supported types are id, uuid, string, and integer.`
580
- );
581
- }
582
- var SUPPORTED_PRIMARY_KEY_TYPES;
583
- var init_schema_primary_key = __esm({
584
- "src/schema-primary-key.ts"() {
585
- "use strict";
586
- SUPPORTED_PRIMARY_KEY_TYPES = /* @__PURE__ */ new Set(["id", "uuid", "string", "integer"]);
587
- __name(assertSupportedPrimaryKeyField, "assertSupportedPrimaryKeyField");
588
- }
589
- });
590
5
 
591
- // src/schema-reference.ts
592
- function isDatabaseEnforcedReference(reference) {
593
- return reference.enforced === void 0 || reference.enforced === "db";
594
- }
595
- var init_schema_reference = __esm({
596
- "src/schema-reference.ts"() {
597
- "use strict";
598
- __name(isDatabaseEnforcedReference, "isDatabaseEnforcedReference");
599
- }
600
- });
601
6
 
602
- // src/schema-resolve.ts
603
- function resolveSchemaModels(ownerKey, schema) {
604
- const models = Object.fromEntries(
605
- Object.entries(schema.models).map(([modelKey, model]) => [modelKey, cloneSchemaModel(model)])
606
- );
607
- for (const [modelKey, extension] of Object.entries(schema.extend || {})) {
608
- const existing = models[modelKey];
609
- models[modelKey] = {
610
- ...existing || { fields: {} },
611
- ...extension.name ? { name: extension.name } : {},
612
- ...extension.description ? { description: extension.description } : {},
613
- fields: {
614
- ...existing?.fields,
615
- ...extension.fields
616
- },
617
- constraints: [...existing?.constraints || [], ...extension.constraints || []],
618
- meta: {
619
- ...existing?.meta,
620
- ...extension.meta
621
- }
622
- };
623
- }
624
- for (const [modelKey, override] of Object.entries(schema.override || {})) {
625
- const existing = models[modelKey];
626
- if (!existing) {
627
- throw new Error(
628
- `Schema override for "${ownerKey}.${modelKey}" is invalid because that model does not exist.`
629
- );
630
- }
631
- const fields = {
632
- ...existing.fields
633
- };
634
- for (const [fieldKey, fieldOverride] of Object.entries(override.fields || {})) {
635
- const existingField = fields[fieldKey];
636
- if (!existingField && !fieldOverride.type) {
637
- throw new Error(
638
- `Schema override for "${ownerKey}.${modelKey}.${fieldKey}" is missing a field type.`
639
- );
640
- }
641
- fields[fieldKey] = {
642
- ...existingField,
643
- ...fieldOverride
644
- };
645
- }
646
- models[modelKey] = {
647
- ...existing,
648
- ...override.name ? { name: override.name } : {},
649
- ...override.description ? { description: override.description } : {},
650
- fields,
651
- constraints: override.constraints || existing.constraints,
652
- meta: {
653
- ...existing.meta,
654
- ...override.meta
655
- }
656
- };
657
- }
658
- const resolvedModels = {};
659
- for (const [modelKey, model] of Object.entries(models)) {
660
- const modelName = model.name || modelKey;
661
- const fieldNames = /* @__PURE__ */ new Set();
662
- const resolvedFields = {};
663
- for (const [fieldKey, field] of Object.entries(model.fields)) {
664
- const fieldName = field.name || fieldKey;
665
- assertSupportedPrimaryKeyField(`${ownerKey}.${modelKey}.${fieldKey}`, field);
666
- if (fieldNames.has(fieldName)) {
667
- throw new Error(
668
- `Schema model "${ownerKey}.${modelKey}" contains duplicate field name "${fieldName}".`
669
- );
670
- }
671
- fieldNames.add(fieldName);
672
- resolvedFields[fieldKey] = {
673
- ...field,
674
- name: fieldName
675
- };
676
- }
677
- const primaryKeyFields = Object.entries(resolvedFields).filter(([, field]) => field.primaryKey).map(([fieldKey]) => fieldKey);
678
- if (primaryKeyFields.length > 1) {
679
- throw new Error(
680
- `Schema model "${ownerKey}.${modelKey}" defines multiple primary-key fields: ${primaryKeyFields.map((fieldKey) => `"${fieldKey}"`).join(", ")}. Composite primary keys are not supported.`
681
- );
682
- }
683
- for (const constraint of model.constraints || []) {
684
- for (const fieldKey of constraint.fields) {
685
- if (!Object.prototype.hasOwnProperty.call(resolvedFields, fieldKey)) {
686
- throw new Error(
687
- `Schema ${constraint.type} constraint on "${ownerKey}.${modelKey}" references missing field "${fieldKey}".`
688
- );
689
- }
690
- }
691
- }
692
- resolvedModels[modelKey] = {
693
- ...model,
694
- name: modelName,
695
- fields: resolvedFields
696
- };
697
- }
698
- for (const [modelKey, model] of Object.entries(resolvedModels)) {
699
- for (const [fieldKey, field] of Object.entries(model.fields)) {
700
- const reference = field.reference;
701
- if (!reference || !Object.prototype.hasOwnProperty.call(resolvedModels, reference.model)) {
702
- continue;
703
- }
704
- const referencedModel = resolvedModels[reference.model];
705
- if (!Object.prototype.hasOwnProperty.call(referencedModel.fields, reference.field)) {
706
- throw new Error(
707
- `Schema reference "${ownerKey}.${modelKey}.${fieldKey}" targets missing field "${ownerKey}.${reference.model}.${reference.field}".`
708
- );
709
- }
710
- }
711
- }
712
- return resolvedModels;
713
- }
714
- function cloneSchemaModel(model) {
715
- return {
716
- ...model,
717
- fields: Object.fromEntries(
718
- Object.entries(model.fields).map(([fieldKey, field]) => [fieldKey, { ...field }])
719
- ),
720
- constraints: model.constraints ? [...model.constraints] : void 0,
721
- meta: model.meta ? { ...model.meta } : void 0
722
- };
723
- }
724
- var init_schema_resolve = __esm({
725
- "src/schema-resolve.ts"() {
726
- "use strict";
727
- init_schema_primary_key();
728
- __name(resolveSchemaModels, "resolveSchemaModels");
729
- __name(cloneSchemaModel, "cloneSchemaModel");
730
- }
731
- });
732
7
 
733
- // src/integration-orm.ts
734
- var integration_orm_exports = {};
735
- __export(integration_orm_exports, {
736
- createIntegrationOrm: () => createIntegrationOrm,
737
- farmIntegrationSchemaToOrmSchema: () => farmIntegrationSchemaToOrmSchema,
738
- resolveIntegrationOrmRuntimeClient: () => resolveIntegrationOrmRuntimeClient
739
- });
740
- async function createIntegrationOrm(options) {
741
- const [schema, client] = await Promise.all([
742
- farmIntegrationSchemaToOrmSchema(options.schema),
743
- resolveIntegrationOrmRuntimeClient(options)
744
- ]);
745
- if (!client) {
746
- throw new Error(
747
- "Schema-backed integration storage requires a runtime client at farm.config storage.client."
748
- );
749
- }
750
- const { createOrmFromRuntime } = await import("@farming-labs/orm-runtime");
751
- return createOrmFromRuntime({
752
- schema,
753
- client
754
- });
755
- }
756
- async function resolveIntegrationOrmRuntimeClient(options) {
757
- if (options.client !== void 0) {
758
- return typeof options.client === "function" ? await options.client() : options.client;
759
- }
760
- return resolveStorageRuntimeClient(options.storage ?? options.config?.storage);
761
- }
762
- async function farmIntegrationSchemaToOrmSchema(schema) {
763
- for (const [modelKey, modelSchema] of Object.entries(schema.models)) {
764
- for (const [fieldKey, fieldSchema] of Object.entries(modelSchema.fields)) {
765
- assertNoSchemaListField(
766
- fieldSchema,
767
- `${modelKey}.${fieldKey}`,
768
- "the Farm integration runtime ORM"
769
- );
770
- }
771
- }
772
- const orm = await import("@farming-labs/orm");
773
- const models = {};
774
- const resolvedModels = resolveSchemaModels("integration", schema);
775
- for (const [modelKey, modelSchema] of Object.entries(resolvedModels)) {
776
- models[modelKey] = orm.model({
777
- table: modelSchema.name ?? modelKey,
778
- fields: createOrmModelFields(orm, modelKey, modelSchema),
779
- constraints: createOrmModelConstraints(modelSchema),
780
- description: modelSchema.description
781
- });
782
- }
783
- return orm.defineSchema(models);
784
- }
785
- function createOrmModelFields(orm, modelKey, modelSchema) {
786
- return Object.fromEntries(
787
- Object.entries(modelSchema.fields).map(([fieldKey, fieldSchema]) => [
788
- fieldKey,
789
- createOrmField(orm, modelKey, fieldKey, fieldSchema)
790
- ])
791
- );
792
- }
793
- function createOrmField(orm, modelKey, fieldKey, field) {
794
- assertSupportedPrimaryKeyField(`integration.${modelKey}.${fieldKey}`, field);
795
- let builder = createOrmFieldBuilder(orm, fieldKey, field);
796
- if (!field.primaryKey && field.unique) {
797
- builder = builder.unique();
798
- }
799
- if (!field.primaryKey && (field.nullable || field.required === false)) {
800
- builder = builder.nullable();
801
- }
802
- if (field.default !== void 0) {
803
- builder = field.type === "datetime" && field.default === "now" ? builder.defaultNow() : builder.default(field.default);
804
- }
805
- if (field.reference && isDatabaseEnforcedReference(field.reference)) {
806
- builder = builder.references(`${field.reference.model}.${field.reference.field}`);
807
- }
808
- if (field.name && field.name !== fieldKey) {
809
- builder = builder.map(field.name);
810
- }
811
- if (field.description) {
812
- builder = builder.describe(field.description);
813
- }
814
- return builder;
815
- }
816
- function createOrmFieldBuilder(orm, fieldKey, field) {
817
- if (field.primaryKey) {
818
- if (field.type === "integer") {
819
- return orm.id({ type: "integer" });
820
- }
821
- if (field.type === "string") {
822
- return new orm.FieldBuilder({
823
- kind: "id",
824
- nullable: false,
825
- unique: true,
826
- idType: "string"
827
- });
828
- }
829
- return orm.id();
830
- }
831
- switch (field.type) {
832
- case "id":
833
- case "uuid":
834
- return orm.string();
835
- case "string":
836
- case "text":
837
- return orm.string();
838
- case "boolean":
839
- return orm.boolean();
840
- case "integer":
841
- return orm.integer();
842
- case "number":
843
- return orm.decimal();
844
- case "datetime":
845
- return orm.datetime();
846
- case "json":
847
- return orm.json();
848
- case "enum": {
849
- if (!field.values?.length) {
850
- throw new Error(`Integration schema enum field "${fieldKey}" must define values.`);
851
- }
852
- return orm.enumeration(field.values);
853
- }
854
- default:
855
- throw new Error(
856
- `Unsupported integration schema field type "${field.type}" for "${fieldKey}".`
857
- );
858
- }
859
- }
860
- function createOrmModelConstraints(modelSchema) {
861
- const unique = [];
862
- const indexes = [];
863
- for (const constraint of modelSchema.constraints ?? []) {
864
- if (!constraint.fields.length) {
865
- continue;
866
- }
867
- const fields = constraint.fields;
868
- if (constraint.type === "unique") {
869
- unique.push(fields);
870
- } else {
871
- indexes.push(fields);
872
- }
873
- }
874
- return {
875
- unique,
876
- indexes
877
- };
878
- }
879
- var init_integration_orm = __esm({
880
- "src/integration-orm.ts"() {
881
- "use strict";
882
- init_schema_capabilities();
883
- init_schema_primary_key();
884
- init_schema_reference();
885
- init_schema_resolve();
886
- init_storage();
887
- __name(createIntegrationOrm, "createIntegrationOrm");
888
- __name(resolveIntegrationOrmRuntimeClient, "resolveIntegrationOrmRuntimeClient");
889
- __name(farmIntegrationSchemaToOrmSchema, "farmIntegrationSchemaToOrmSchema");
890
- __name(createOrmModelFields, "createOrmModelFields");
891
- __name(createOrmField, "createOrmField");
892
- __name(createOrmFieldBuilder, "createOrmFieldBuilder");
893
- __name(createOrmModelConstraints, "createOrmModelConstraints");
894
- }
895
- });
896
8
 
897
- // src/integrations.ts
898
- var integrations_exports = {};
899
- __export(integrations_exports, {
900
- FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY: () => FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY,
901
- FARM_INTEGRATION_SET_COOKIES_KEY: () => FARM_INTEGRATION_SET_COOKIES_KEY,
902
- api: () => api,
903
- createIntegrationRoute: () => createIntegrationRoute,
904
- defineIntegration: () => defineIntegration,
905
- defineIntegrationAPI: () => defineIntegrationAPI,
906
- defineIntegrationAPIOperation: () => defineIntegrationAPIOperation,
907
- defineIntegrationSchema: () => defineIntegrationSchema,
908
- describeIntegrationOriginRejection: () => describeIntegrationOriginRejection,
909
- dispatchIntegrationRequest: () => dispatchIntegrationRequest,
910
- dispatchIntegrationRequests: () => dispatchIntegrationRequests,
911
- forwardIntegrationSetCookies: () => forwardIntegrationSetCookies,
912
- getFarmIntegrationPluginOwner: () => getFarmIntegrationPluginOwner,
913
- getFarmIntegrationPluginServerRuntime: () => getFarmIntegrationPluginServerRuntime,
914
- getIntegrationDocumentNavigationMatchers: () => getIntegrationDocumentNavigationMatchers,
915
- getIntegrationProviders: () => getIntegrationProviders,
916
- getIntegrationSchemas: () => getIntegrationSchemas,
917
- getRegisteredIntegrationAPIManifest: () => getRegisteredIntegrationAPIManifest,
918
- getRegisteredIntegrationRuntime: () => getRegisteredIntegrationRuntime,
919
- getRegisteredIntegrationSchemas: () => getRegisteredIntegrationSchemas,
920
- getRegisteredIntegrations: () => getRegisteredIntegrations,
921
- integrationRoute: () => integrationRoute,
922
- isFarmIntegration: () => isFarmIntegration,
923
- isFarmIntegrationProviderComponentReference: () => isFarmIntegrationProviderComponentReference,
924
- matchIntegrationRoute: () => matchIntegrationRoute,
925
- matchRegisteredIntegrationRoute: () => matchRegisteredIntegrationRoute,
926
- resolveIntegrationAllowedOrigins: () => resolveIntegrationAllowedOrigins,
927
- resolveIntegrationPlugins: () => resolveIntegrationPlugins,
928
- validateIntegrationRequestOrigin: () => validateIntegrationRequestOrigin
929
- });
930
- module.exports = __toCommonJS(integrations_exports);
931
9
 
932
- // src/routing/specificity.ts
933
- var _AmbiguousRouteError = class _AmbiguousRouteError extends Error {
934
- constructor(message) {
935
- super(message);
936
- this.name = "AmbiguousRouteError";
937
- }
938
- };
939
- __name(_AmbiguousRouteError, "AmbiguousRouteError");
940
- var AmbiguousRouteError = _AmbiguousRouteError;
941
- var _NonTerminalCatchAllRouteError = class _NonTerminalCatchAllRouteError extends TypeError {
942
- constructor(message) {
943
- super(message);
944
- this.name = "NonTerminalCatchAllRouteError";
945
- }
946
- };
947
- __name(_NonTerminalCatchAllRouteError, "NonTerminalCatchAllRouteError");
948
- var NonTerminalCatchAllRouteError = _NonTerminalCatchAllRouteError;
949
- var _DuplicateRouteParameterError = class _DuplicateRouteParameterError extends AmbiguousRouteError {
950
- constructor(message) {
951
- super(message);
952
- this.name = "DuplicateRouteParameterError";
953
- }
954
- };
955
- __name(_DuplicateRouteParameterError, "DuplicateRouteParameterError");
956
- var DuplicateRouteParameterError = _DuplicateRouteParameterError;
957
- var _ReservedRouteParameterError = class _ReservedRouteParameterError extends AmbiguousRouteError {
958
- constructor(message) {
959
- super(message);
960
- this.name = "ReservedRouteParameterError";
961
- }
962
- };
963
- __name(_ReservedRouteParameterError, "ReservedRouteParameterError");
964
- var ReservedRouteParameterError = _ReservedRouteParameterError;
965
- var _BrowserUnstableRouteError = class _BrowserUnstableRouteError extends TypeError {
966
- constructor(message) {
967
- super(message);
968
- this.name = "BrowserUnstableRouteError";
969
- }
970
- };
971
- __name(_BrowserUnstableRouteError, "BrowserUnstableRouteError");
972
- var BrowserUnstableRouteError = _BrowserUnstableRouteError;
973
- var SEGMENT_RANK = {
974
- static: 4,
975
- dynamic: 3,
976
- "catch-all": 1,
977
- "optional-catch-all": 0
978
- };
979
- var ROUTE_END_RANK = 2;
980
- function compareRouteSpecificity(left, right) {
981
- const length = Math.max(left.length, right.length);
982
- for (let index = 0; index < length; index++) {
983
- const leftRank = index < left.length ? SEGMENT_RANK[left[index]] : ROUTE_END_RANK;
984
- const rightRank = index < right.length ? SEGMENT_RANK[right[index]] : ROUTE_END_RANK;
985
- if (leftRank !== rightRank) return rightRank - leftRank;
986
- }
987
- return 0;
988
- }
989
- __name(compareRouteSpecificity, "compareRouteSpecificity");
990
- var ROUTER_PARAMETER_NAME = "[A-Za-z0-9_$-]+";
991
- var PAGE_PARAMETER_PATTERN = /^(?:\[\[\.\.\.(.+)\]\]|\[\.\.\.(.+)\]|\[(.+)\])$/;
992
- var ROUTER_PARAMETER_PATTERN = /^(?:\[\[\.\.\.([A-Za-z0-9_$-]+)\]\]|\[\.\.\.([A-Za-z0-9_$-]+)\]|\[([A-Za-z0-9_$-]+)\]|:([A-Za-z0-9_$-]+)|\*([A-Za-z0-9_$-]+)\??)$/;
993
- var RESERVED_PARAMETER_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
994
- function assertBrowserStableRoutePath(pattern) {
995
- if (pattern.includes("\\") || hasControlCharacter(pattern)) {
996
- throw new BrowserUnstableRouteError(
997
- `Route path "${pattern}" cannot contain backslashes or control characters.`
998
- );
999
- }
1000
- for (const segment of pattern.split("/").filter(Boolean)) {
1001
- if (segment.startsWith("(") && segment.endsWith(")") || segment.startsWith("[") && segment.endsWith("]")) {
1002
- continue;
1003
- }
1004
- let decoded = segment;
1005
- try {
1006
- decoded = decodeURIComponent(segment);
1007
- } catch {
1008
- }
1009
- if (decoded === "." || decoded === ".." || decoded.includes("/") || decoded.includes("\\") || hasControlCharacter(decoded)) {
1010
- throw new BrowserUnstableRouteError(
1011
- `Route path "${pattern}" contains browser-unstable segment "${segment}".`
1012
- );
1013
- }
1014
- }
1015
- }
1016
- __name(assertBrowserStableRoutePath, "assertBrowserStableRoutePath");
1017
- function hasControlCharacter(value) {
1018
- return Array.from(value).some((character) => {
1019
- const code = character.charCodeAt(0);
1020
- return code <= 31 || code >= 127 && code <= 159;
1021
- });
1022
- }
1023
- __name(hasControlCharacter, "hasControlCharacter");
1024
- function assertUniqueRouteParameters(pattern, syntax = "page") {
1025
- const parameterPattern = syntax === "router" ? ROUTER_PARAMETER_PATTERN : PAGE_PARAMETER_PATTERN;
1026
- const names = /* @__PURE__ */ new Set();
1027
- for (const segment of splitRoutePattern(pattern, syntax)) {
1028
- const match = parameterPattern.exec(segment);
1029
- const name = match?.slice(1).find(Boolean);
1030
- if (!name) continue;
1031
- if (RESERVED_PARAMETER_NAMES.has(name)) {
1032
- throw new ReservedRouteParameterError(
1033
- `Route parameter "${name}" in route "${pattern}" is reserved. Use a different parameter name.`
1034
- );
1035
- }
1036
- if (names.has(name)) {
1037
- throw new DuplicateRouteParameterError(
1038
- `Duplicate route parameter "${name}" in route "${pattern}". Each dynamic segment must use a unique name.`
1039
- );
1040
- }
1041
- names.add(name);
1042
- }
1043
- }
1044
- __name(assertUniqueRouteParameters, "assertUniqueRouteParameters");
1045
- function splitRoutePattern(pattern, syntax) {
1046
- return pattern.replace(/\\/g, "/").split("/").filter(Boolean).filter(
1047
- (segment) => syntax === "api" ? true : !(segment.startsWith("(") && segment.endsWith(")"))
1048
- );
1049
- }
1050
- __name(splitRoutePattern, "splitRoutePattern");
1051
- function assertTerminalCatchAll(pattern, syntax = "page") {
1052
- const segments = splitRoutePattern(pattern, syntax);
1053
- const parameterName = syntax === "router" ? ROUTER_PARAMETER_NAME : ".+";
1054
- const catchAllPattern = new RegExp(
1055
- syntax === "router" ? `^(?:\\[\\[\\.\\.\\.${parameterName}\\]\\]|\\[\\.\\.\\.${parameterName}\\]|\\*${parameterName}\\??)$` : `^(?:\\[\\[\\.\\.\\.${parameterName}\\]\\]|\\[\\.\\.\\.${parameterName}\\])$`
1056
- );
1057
- const catchAllIndex = segments.findIndex((segment) => catchAllPattern.test(segment));
1058
- if (catchAllIndex >= 0 && catchAllIndex !== segments.length - 1) {
1059
- throw new NonTerminalCatchAllRouteError(
1060
- `Catch-all segment "${segments[catchAllIndex]}" must be the final segment in route "${pattern}".`
1061
- );
1062
- }
1063
- }
1064
- __name(assertTerminalCatchAll, "assertTerminalCatchAll");
1065
- function getRoutePatternSpecificity(pattern, syntax = "page") {
1066
- assertTerminalCatchAll(pattern, syntax);
1067
- return splitRoutePattern(pattern, syntax).map(
1068
- (segment) => getPatternSegmentSpecificity(segment, syntax)
1069
- );
1070
- }
1071
- __name(getRoutePatternSpecificity, "getRoutePatternSpecificity");
1072
- function getPatternSegmentSpecificity(segment, syntax) {
1073
- const parameterName = syntax === "router" ? ROUTER_PARAMETER_NAME : ".+";
1074
- const supportsColonAndStar = syntax === "router";
1075
- if (new RegExp(`^\\[\\[\\.\\.\\.${parameterName}\\]\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^\\*${parameterName}\\?$`).test(segment)) {
1076
- return "optional-catch-all";
1077
- }
1078
- if (new RegExp(`^\\[\\.\\.\\.${parameterName}\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^\\*${parameterName}$`).test(segment)) {
1079
- return "catch-all";
1080
- }
1081
- if (new RegExp(`^\\[${parameterName}\\]$`).test(segment) || supportsColonAndStar && new RegExp(`^:${parameterName}$`).test(segment)) {
1082
- return "dynamic";
1083
- }
1084
- return "static";
1085
- }
1086
- __name(getPatternSegmentSpecificity, "getPatternSegmentSpecificity");
1087
10
 
1088
- // src/utils/decode.ts
1089
- function decodeRouteSegment(segment) {
1090
- try {
1091
- return decodeURIComponent(segment);
1092
- } catch {
1093
- return segment;
1094
- }
1095
- }
1096
- __name(decodeRouteSegment, "decodeRouteSegment");
1097
- function canonicalizeRequestPathSegments(pathname) {
1098
- const segments = pathname.split("/").filter(Boolean);
1099
- if (!pathname.includes("%")) return segments;
1100
- return segments.map(decodeRouteSegment);
1101
- }
1102
- __name(canonicalizeRequestPathSegments, "canonicalizeRequestPathSegments");
1103
- function canonicalizeRequestPathname(pathname) {
1104
- const encoded = pathname.includes("%");
1105
- if (!encoded && !pathname.includes("//")) return pathname;
1106
- const collapsed = pathname.replace(/\/{2,}/g, "/");
1107
- if (!encoded) return collapsed;
1108
- return collapsed.split("/").map((segment) => {
1109
- const decoded = decodeRouteSegment(segment);
1110
- return decoded === segment ? segment : decoded.replace(/\//g, "%2F");
1111
- }).join("/");
1112
- }
1113
- __name(canonicalizeRequestPathname, "canonicalizeRequestPathname");
1114
11
 
1115
- // src/plugins/route-pattern.ts
1116
- function validateConfigRouteSource(source, field = "Config route source") {
1117
- if (typeof source !== "string" || source.length === 0) {
1118
- throw new TypeError(`${field} must be a non-empty pathname pattern.`);
1119
- }
1120
- if (source.trim() !== source) {
1121
- throw new Error(`${field} cannot contain leading or trailing whitespace.`);
1122
- }
1123
- if (!source.startsWith("/")) {
1124
- throw new Error(`${field} must start with "/".`);
1125
- }
1126
- if (source.includes("?") || source.includes("#")) {
1127
- throw new Error(`${field} must be a pathname without a query string or hash.`);
1128
- }
1129
- if (source.includes("\\") || Array.from(source).some((character) => {
1130
- const code = character.charCodeAt(0);
1131
- return code <= 31 || code >= 127 && code <= 159;
1132
- })) {
1133
- throw new Error(`${field} cannot contain backslashes or control characters.`);
1134
- }
1135
- assertBrowserStableRoutePath(source);
1136
- return source;
1137
- }
1138
- __name(validateConfigRouteSource, "validateConfigRouteSource");
1139
12
 
1140
- // src/schema.ts
1141
- function defineSchema(schema) {
1142
- return schema;
1143
- }
1144
- __name(defineSchema, "defineSchema");
1145
13
 
1146
- // src/request-origin.ts
1147
- function getRequestSourceOrigin(request) {
1148
- const origin = request.headers.get("origin")?.trim();
1149
- if (origin) {
1150
- return parseSourceOrigin(origin);
1151
- }
1152
- const referer = request.headers.get("referer")?.trim();
1153
- if (referer) {
1154
- return parseSourceOrigin(referer);
1155
- }
1156
- return { ok: true, origin: null };
1157
- }
1158
- __name(getRequestSourceOrigin, "getRequestSourceOrigin");
1159
- function parseSourceOrigin(value) {
1160
- if (value === "null") {
1161
- return { ok: false, reason: "opaque-origin" };
1162
- }
1163
- try {
1164
- const parsed = new URL(value);
1165
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1166
- return { ok: false, reason: "invalid-origin" };
1167
- }
1168
- return { ok: true, origin: parsed.origin };
1169
- } catch {
1170
- return { ok: false, reason: "invalid-origin" };
1171
- }
1172
- }
1173
- __name(parseSourceOrigin, "parseSourceOrigin");
1174
- function matchesHostHeader(sourceOrigin, request) {
1175
- const host = request.headers.get("host")?.trim().toLowerCase();
1176
- if (!host) return false;
1177
- try {
1178
- const source = new URL(sourceOrigin);
1179
- const target = new URL(request.url);
1180
- return source.protocol === target.protocol && source.host.toLowerCase() === host;
1181
- } catch {
1182
- return false;
1183
- }
1184
- }
1185
- __name(matchesHostHeader, "matchesHostHeader");
1186
- function matchesAllowedOrigin(sourceOrigin, pattern) {
1187
- const source = new URL(sourceOrigin);
1188
- if (!pattern.includes("*")) {
1189
- return pattern.includes("://") ? source.origin === pattern : source.host === pattern;
1190
- }
1191
- const schemeEnd = pattern.indexOf("://");
1192
- const scheme = schemeEnd === -1 ? null : pattern.slice(0, schemeEnd + 1);
1193
- const hostPattern = pattern.slice(schemeEnd === -1 ? 0 : schemeEnd + 3);
1194
- const [wildcardHost, port] = splitHostAndPort(hostPattern);
1195
- const baseHost = wildcardHost.slice(2);
1196
- if (scheme && source.protocol !== scheme) return false;
1197
- if (port && getEffectivePort(source) !== port) return false;
1198
- if (!port && source.port) return false;
1199
- return source.hostname.endsWith(`.${baseHost}`) && source.hostname !== baseHost;
1200
- }
1201
- __name(matchesAllowedOrigin, "matchesAllowedOrigin");
1202
- function normalizeAllowedOriginPattern(value, label) {
1203
- const pattern = value.trim().toLowerCase();
1204
- if (!pattern) {
1205
- throw new TypeError(`${label} cannot contain empty values`);
1206
- }
1207
- if (pattern.includes("*")) {
1208
- if (!/^(?:https?:\/\/)?\*\.[a-z0-9.-]+(?::\d+)?$/.test(pattern)) {
1209
- throw new TypeError(`Invalid ${label} pattern: ${JSON.stringify(value)}`);
1210
- }
1211
- return pattern;
1212
- }
1213
- if (pattern.includes("://")) {
1214
- let parsed;
1215
- try {
1216
- parsed = new URL(pattern);
1217
- } catch {
1218
- throw new TypeError(`Invalid ${label} value: ${JSON.stringify(value)}`);
1219
- }
1220
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash) {
1221
- throw new TypeError(`${label} must contain origins without paths: ${JSON.stringify(value)}`);
1222
- }
1223
- return parsed.origin;
1224
- }
1225
- if (/[/@?#]/.test(pattern)) {
1226
- throw new TypeError(`${label} must contain origins or hosts: ${JSON.stringify(value)}`);
1227
- }
1228
- try {
1229
- return new URL(`http://${pattern}`).host;
1230
- } catch {
1231
- throw new TypeError(`Invalid ${label} value: ${JSON.stringify(value)}`);
1232
- }
1233
- }
1234
- __name(normalizeAllowedOriginPattern, "normalizeAllowedOriginPattern");
1235
- function splitHostAndPort(value) {
1236
- const separator = value.lastIndexOf(":");
1237
- if (separator === -1) return [value, null];
1238
- return [value.slice(0, separator), value.slice(separator + 1)];
1239
- }
1240
- __name(splitHostAndPort, "splitHostAndPort");
1241
- function getEffectivePort(url) {
1242
- if (url.port) return url.port;
1243
- if (url.protocol === "https:") return "443";
1244
- if (url.protocol === "http:") return "80";
1245
- return "";
1246
- }
1247
- __name(getEffectivePort, "getEffectivePort");
1248
14
 
1249
- // src/integration-request-security.ts
1250
- function resolveIntegrationAllowedOrigins(values, label) {
1251
- return Object.freeze((values ?? []).map((value) => normalizeAllowedOriginPattern(value, label)));
1252
- }
1253
- __name(resolveIntegrationAllowedOrigins, "resolveIntegrationAllowedOrigins");
1254
- function validateIntegrationRequestOrigin(request, policy = {}) {
1255
- const allowedOrigins = policy.allowedOrigins ?? [];
1256
- const requireOriginMetadata = policy.requireOriginMetadata ?? true;
1257
- const fetchSite = request.headers.get("sec-fetch-site")?.trim().toLowerCase();
1258
- const source = getRequestSourceOrigin(request);
1259
- if (!source.ok) {
1260
- return { ok: false, reason: source.reason };
1261
- }
1262
- if (source.origin === null) {
1263
- if (fetchSite === "same-origin") {
1264
- return { ok: true };
1265
- }
1266
- if (requireOriginMetadata) {
1267
- return { ok: false, reason: fetchSite === "cross-site" ? "cross-site" : "missing-origin" };
1268
- }
1269
- return fetchSite === "cross-site" ? { ok: false, reason: "cross-site" } : { ok: true };
1270
- }
1271
- const requestUrl = new URL(request.url);
1272
- const matchesConfiguredOrigin = allowedOrigins.some(
1273
- (pattern) => matchesAllowedOrigin(source.origin, pattern)
1274
- );
1275
- const matchesRequest = source.origin === requestUrl.origin || matchesHostHeader(source.origin, request);
1276
- if (!matchesRequest && !matchesConfiguredOrigin) {
1277
- return { ok: false, reason: "cross-site" };
1278
- }
1279
- if (fetchSite === "cross-site" && !matchesConfiguredOrigin) {
1280
- return { ok: false, reason: "cross-site" };
1281
- }
1282
- return { ok: true };
1283
- }
1284
- __name(validateIntegrationRequestOrigin, "validateIntegrationRequestOrigin");
1285
- function describeIntegrationOriginRejection(reason) {
1286
- switch (reason) {
1287
- case "missing-origin":
1288
- return "Request is missing same-origin metadata.";
1289
- case "opaque-origin":
1290
- return "Opaque origins are not allowed.";
1291
- case "invalid-origin":
1292
- return "Invalid request origin.";
1293
- case "cross-site":
1294
- return "Cross-site request was rejected.";
1295
- }
1296
- }
1297
- __name(describeIntegrationOriginRejection, "describeIntegrationOriginRejection");
1298
15
 
1299
- // src/integration-api.ts
1300
- function defineIntegrationAPIOperation(operation2) {
1301
- return {
1302
- kind: "farm-integration-api-operation",
1303
- ...operation2
1304
- };
1305
- }
1306
- __name(defineIntegrationAPIOperation, "defineIntegrationAPIOperation");
1307
- function defineIntegrationAPI(api2) {
1308
- return api2;
1309
- }
1310
- __name(defineIntegrationAPI, "defineIntegrationAPI");
1311
- function operation(method, pathOrOptions, maybeOptions = {}) {
1312
- const hasExplicitPath = typeof pathOrOptions === "string";
1313
- const path = hasExplicitPath ? pathOrOptions : "";
1314
- const options = hasExplicitPath ? maybeOptions : {
1315
- ...maybeOptions,
1316
- ...pathOrOptions
1317
- };
1318
- return defineIntegrationAPIOperation({
1319
- path,
1320
- method,
1321
- __pathless: !hasExplicitPath,
1322
- ...options
1323
- });
1324
- }
1325
- __name(operation, "operation");
1326
- function get(pathOrOptions, maybeOptions = {}) {
1327
- return operation("GET", pathOrOptions, maybeOptions);
1328
- }
1329
- __name(get, "get");
1330
- function isOperation(value) {
1331
- return !!value && typeof value === "object" && value.kind === "farm-integration-api-operation";
1332
- }
1333
- __name(isOperation, "isOperation");
1334
- function bindRoutePath(path, api2) {
1335
- const entries = Object.entries(api2).map(([key, value]) => {
1336
- if (isOperation(value)) {
1337
- return [
1338
- key,
1339
- {
1340
- ...value,
1341
- path,
1342
- __pathless: false
1343
- }
1344
- ];
1345
- }
1346
- if (value && typeof value === "object") {
1347
- return [key, bindRoutePath(path, value)];
1348
- }
1349
- return [key, value];
1350
- });
1351
- return Object.fromEntries(entries);
1352
- }
1353
- __name(bindRoutePath, "bindRoutePath");
1354
- function route(path, definitionOrOperation, ...operations) {
1355
- if (isOperation(definitionOrOperation)) {
1356
- const allOperations = [definitionOrOperation, ...operations];
1357
- return Object.fromEntries(
1358
- allOperations.map((operation2) => [
1359
- operation2.method.toLowerCase(),
1360
- {
1361
- ...operation2,
1362
- path,
1363
- __pathless: false
1364
- }
1365
- ])
1366
- );
1367
- }
1368
- return bindRoutePath(path, definitionOrOperation);
1369
- }
1370
- __name(route, "route");
1371
- function normalizeRouteSegment(segment) {
1372
- if (!segment) {
1373
- return "index";
1374
- }
1375
- if (segment.startsWith("[...") && segment.endsWith("]")) {
1376
- return segment.slice(4, -1) || "index";
1377
- }
1378
- if (segment.startsWith("[") && segment.endsWith("]")) {
1379
- return segment.slice(1, -1) || "index";
1380
- }
1381
- const matcherIndex = segment.indexOf("(");
1382
- if (matcherIndex > 0) {
1383
- return segment.slice(0, matcherIndex);
1384
- }
1385
- return camelCaseRouteSegment(segment);
1386
- }
1387
- __name(normalizeRouteSegment, "normalizeRouteSegment");
1388
- function camelCaseRouteSegment(segment) {
1389
- return segment.replace(/-([a-zA-Z0-9])/g, (_match, value) => value.toUpperCase());
1390
- }
1391
- __name(camelCaseRouteSegment, "camelCaseRouteSegment");
1392
- function getRouteClientSegments(path) {
1393
- const segments = path.split("/").filter(Boolean);
1394
- if (segments.length === 0) {
1395
- return ["index"];
1396
- }
1397
- const stripped = segments[0] === "api" && segments.length > 2 ? segments.slice(2) : segments.length > 1 ? segments.slice(1) : [segments[segments.length - 1]];
1398
- return stripped.map(normalizeRouteSegment).filter(Boolean);
1399
- }
1400
- __name(getRouteClientSegments, "getRouteClientSegments");
1401
- function setRouteOperation(target, pathSegments, operation2) {
1402
- const [head, ...tail] = pathSegments;
1403
- if (!head) {
1404
- return;
1405
- }
1406
- if (tail.length === 0) {
1407
- const leaf = target[head] || {};
1408
- leaf[operation2.method.toLowerCase()] = {
1409
- ...operation2,
1410
- path: operation2.path,
1411
- __pathless: false
1412
- };
1413
- target[head] = leaf;
1414
- return;
1415
- }
1416
- const branch = target[head] || {};
1417
- target[head] = branch;
1418
- setRouteOperation(branch, tail, operation2);
1419
- }
1420
- __name(setRouteOperation, "setRouteOperation");
1421
- function fromRoutes(routes) {
1422
- const definition = {};
1423
- for (const route2 of routes) {
1424
- if (!isOperation(route2.__operation)) {
1425
- continue;
1426
- }
1427
- setRouteOperation(definition, getRouteClientSegments(route2.path), {
1428
- ...route2.__operation,
1429
- path: route2.path,
1430
- __pathless: false
1431
- });
1432
- }
1433
- return definition;
1434
- }
1435
- __name(fromRoutes, "fromRoutes");
1436
- var api = {
1437
- get,
1438
- route,
1439
- fromRoutes,
1440
- query(pathOrOptions, maybeOptions = {}) {
1441
- return operation("QUERY", pathOrOptions, {
1442
- bodyFormat: "json",
1443
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1444
- });
1445
- },
1446
- post(pathOrOptions, maybeOptions = {}) {
1447
- return operation("POST", pathOrOptions, {
1448
- bodyFormat: "json",
1449
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1450
- });
1451
- },
1452
- put(pathOrOptions, maybeOptions = {}) {
1453
- return operation("PUT", pathOrOptions, {
1454
- bodyFormat: "json",
1455
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1456
- });
1457
- },
1458
- patch(pathOrOptions, maybeOptions = {}) {
1459
- return operation("PATCH", pathOrOptions, {
1460
- bodyFormat: "json",
1461
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1462
- });
1463
- },
1464
- delete(pathOrOptions, maybeOptions = {}) {
1465
- return operation("DELETE", pathOrOptions, {
1466
- bodyFormat: "json",
1467
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1468
- });
1469
- },
1470
- options(pathOrOptions, maybeOptions = {}) {
1471
- return operation(
1472
- "OPTIONS",
1473
- pathOrOptions,
1474
- maybeOptions
1475
- );
1476
- },
1477
- head(pathOrOptions, maybeOptions = {}) {
1478
- return operation(
1479
- "HEAD",
1480
- pathOrOptions,
1481
- maybeOptions
1482
- );
1483
- },
1484
- form: {
1485
- query(pathOrOptions, maybeOptions = {}) {
1486
- return operation("QUERY", pathOrOptions, {
1487
- bodyFormat: "form",
1488
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1489
- });
1490
- },
1491
- post(pathOrOptions, maybeOptions = {}) {
1492
- return operation("POST", pathOrOptions, {
1493
- bodyFormat: "form",
1494
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1495
- });
1496
- },
1497
- put(pathOrOptions, maybeOptions = {}) {
1498
- return operation("PUT", pathOrOptions, {
1499
- bodyFormat: "form",
1500
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1501
- });
1502
- },
1503
- patch(pathOrOptions, maybeOptions = {}) {
1504
- return operation("PATCH", pathOrOptions, {
1505
- bodyFormat: "form",
1506
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1507
- });
1508
- },
1509
- delete(pathOrOptions, maybeOptions = {}) {
1510
- return operation("DELETE", pathOrOptions, {
1511
- bodyFormat: "form",
1512
- ...typeof pathOrOptions === "string" ? maybeOptions : pathOrOptions
1513
- });
1514
- }
1515
- }
1516
- };
1517
16
 
1518
- // src/plugin-integration-context.ts
1519
- var FARM_PLUGIN_INTEGRATION_CONTEXT = /* @__PURE__ */ Symbol.for("@farm.js/core/plugin-integration-context");
1520
- function setFarmPluginIntegrationContext(plugin, integration) {
1521
- Object.defineProperty(plugin, FARM_PLUGIN_INTEGRATION_CONTEXT, {
1522
- value: integration
1523
- });
1524
- }
1525
- __name(setFarmPluginIntegrationContext, "setFarmPluginIntegrationContext");
1526
17
 
1527
- // src/request-context.ts
1528
- var REQUEST_CONTEXT_STORE_KEY = /* @__PURE__ */ Symbol.for("farm.requestContextStore");
1529
- function getRequestContextStore() {
1530
- const globalState = globalThis;
1531
- if (!globalState[REQUEST_CONTEXT_STORE_KEY]) {
1532
- globalState[REQUEST_CONTEXT_STORE_KEY] = /* @__PURE__ */ new WeakMap();
1533
- }
1534
- return globalState[REQUEST_CONTEXT_STORE_KEY];
1535
- }
1536
- __name(getRequestContextStore, "getRequestContextStore");
1537
- function getBucket(target) {
1538
- const requestContextStore = getRequestContextStore();
1539
- let bucket = requestContextStore.get(target);
1540
- if (!bucket) {
1541
- bucket = {
1542
- privateData: /* @__PURE__ */ new Map(),
1543
- exposedData: /* @__PURE__ */ new Map()
1544
- };
1545
- requestContextStore.set(target, bucket);
1546
- }
1547
- return bucket;
1548
- }
1549
- __name(getBucket, "getBucket");
1550
- function setRequestContext(target, key, value, options = {}) {
1551
- const bucket = getBucket(target);
1552
- bucket.privateData.set(key, value);
1553
- if (options.exposeToPage) {
1554
- bucket.exposedData.set(key, value);
1555
- }
1556
- }
1557
- __name(setRequestContext, "setRequestContext");
1558
- function getRequestContext(target, key) {
1559
- const requestContextStore = getRequestContextStore();
1560
- const bucket = requestContextStore.get(target);
1561
- return bucket?.privateData.get(key);
1562
- }
1563
- __name(getRequestContext, "getRequestContext");
1564
- function hasRequestContext(target, key) {
1565
- const requestContextStore = getRequestContextStore();
1566
- const bucket = requestContextStore.get(target);
1567
- return bucket?.privateData.has(key) ?? false;
1568
- }
1569
- __name(hasRequestContext, "hasRequestContext");
1570
- function deleteRequestContext(target, key) {
1571
- const requestContextStore = getRequestContextStore();
1572
- const bucket = requestContextStore.get(target);
1573
- if (!bucket) return false;
1574
- const removedPrivate = bucket.privateData.delete(key);
1575
- bucket.exposedData.delete(key);
1576
- return removedPrivate;
1577
- }
1578
- __name(deleteRequestContext, "deleteRequestContext");
1579
- function clearRequestContext(target) {
1580
- const requestContextStore = getRequestContextStore();
1581
- const bucket = requestContextStore.get(target);
1582
- if (!bucket) return;
1583
- bucket.privateData.clear();
1584
- bucket.exposedData.clear();
1585
- }
1586
- __name(clearRequestContext, "clearRequestContext");
1587
- function getRequestContextSnapshot(target, options = {}) {
1588
- const requestContextStore = getRequestContextStore();
1589
- const bucket = requestContextStore.get(target);
1590
- if (!bucket) return /* @__PURE__ */ new Map();
1591
- if (options.exposedOnly) {
1592
- return new Map(bucket.exposedData);
1593
- }
1594
- return new Map(bucket.privateData);
1595
- }
1596
- __name(getRequestContextSnapshot, "getRequestContextSnapshot");
1597
- function copyRequestContext(source, target) {
1598
- const bucket = getRequestContextStore().get(source);
1599
- if (!bucket || source === target) return;
1600
- for (const [key, value] of bucket.privateData) {
1601
- setRequestContext(target, key, value, { exposeToPage: bucket.exposedData.has(key) });
1602
- }
1603
- }
1604
- __name(copyRequestContext, "copyRequestContext");
1605
18
 
1606
- // src/server/response.ts
1607
- function watchResponseEvent(res, events) {
1608
- if (typeof res.once !== "function" || typeof res.removeListener !== "function") {
1609
- return null;
1610
- }
1611
- let settled = false;
1612
- const listeners = events.map(([event, value]) => {
1613
- const listener = /* @__PURE__ */ __name(() => {
1614
- if (settled) return;
1615
- settled = true;
1616
- dispose();
1617
- resolvePromise(value);
1618
- }, "listener");
1619
- return { event, listener };
1620
- });
1621
- let resolvePromise;
1622
- const promise = new Promise((resolve) => {
1623
- resolvePromise = resolve;
1624
- for (const { event, listener } of listeners) {
1625
- res.once(event, listener);
1626
- }
1627
- });
1628
- const dispose = /* @__PURE__ */ __name(() => {
1629
- for (const { event, listener } of listeners) {
1630
- res.removeListener(event, listener);
1631
- }
1632
- }, "dispose");
1633
- return { promise, dispose };
1634
- }
1635
- __name(watchResponseEvent, "watchResponseEvent");
1636
- async function waitForWritable(res) {
1637
- if (res.writableEnded || res.destroyed) {
1638
- return false;
1639
- }
1640
- const watcher = watchResponseEvent(res, [
1641
- ["drain", true],
1642
- ["close", false],
1643
- ["error", false]
1644
- ]);
1645
- if (!watcher) {
1646
- return false;
1647
- }
1648
- try {
1649
- return await watcher.promise;
1650
- } finally {
1651
- watcher.dispose();
1652
- }
1653
- }
1654
- __name(waitForWritable, "waitForWritable");
1655
- function splitSetCookieHeader(value) {
1656
- const cookies = [];
1657
- let start = 0;
1658
- for (let index = 0; index < value.length; index += 1) {
1659
- if (value[index] !== ",") continue;
1660
- let next = index + 1;
1661
- while (value[next] === " " || value[next] === " ") next += 1;
1662
- const equals = value.indexOf("=", next);
1663
- if (equals === -1) continue;
1664
- const separator = value.slice(next, equals);
1665
- if (separator.length === 0 || /[;,\s]/.test(separator)) continue;
1666
- cookies.push(value.slice(start, index).trim());
1667
- start = next;
1668
- index = next - 1;
1669
- }
1670
- cookies.push(value.slice(start).trim());
1671
- return cookies.filter(Boolean);
1672
- }
1673
- __name(splitSetCookieHeader, "splitSetCookieHeader");
1674
- function applyWebResponseHeaders(res, headers, options = {}) {
1675
- const responseHeaders = headers;
1676
- const rawSetCookies = responseHeaders.raw?.()["set-cookie"];
1677
- const setCookies = responseHeaders.getSetCookie?.() || rawSetCookies || [];
1678
- const existing = options.appendSetCookie && typeof res.getHeader === "function" ? res.getHeader("Set-Cookie") : void 0;
1679
- const existingCookies = Array.isArray(existing) ? existing.map(String) : existing === void 0 ? [] : [String(existing)];
1680
- let fallbackSetCookie = "";
1681
- headers.forEach((value, key) => {
1682
- if (key.toLowerCase() === "set-cookie") {
1683
- fallbackSetCookie = value;
1684
- return;
1685
- }
1686
- res.setHeader(key, value);
1687
- });
1688
- const cookies = setCookies.length > 0 ? setCookies : fallbackSetCookie ? splitSetCookieHeader(fallbackSetCookie) : [];
1689
- if (cookies.length > 0) {
1690
- res.setHeader("Set-Cookie", [...existingCookies, ...cookies]);
1691
- }
1692
- }
1693
- __name(applyWebResponseHeaders, "applyWebResponseHeaders");
1694
- async function sendWebResponse(res, response) {
1695
- res.statusCode = response.status;
1696
- applyWebResponseHeaders(res, response.headers, { appendSetCookie: true });
1697
- if (!response.body) {
1698
- res.end();
1699
- return;
1700
- }
1701
- if (typeof res.write !== "function") {
1702
- const body = await response.arrayBuffer();
1703
- res.end(Buffer.from(body));
1704
- return;
1705
- }
1706
- const reader = response.body.getReader();
1707
- const disconnectWatcher = watchResponseEvent(res, [
1708
- ["close", true],
1709
- ["error", true]
1710
- ]);
1711
- try {
1712
- while (true) {
1713
- if (res.destroyed) {
1714
- void reader.cancel().catch(() => {
1715
- });
1716
- return;
1717
- }
1718
- const read = reader.read().then((result) => ({ type: "read", result }));
1719
- const next = disconnectWatcher ? await Promise.race([
1720
- read,
1721
- disconnectWatcher.promise.then(() => ({ type: "disconnect" }))
1722
- ]) : await read;
1723
- if (next.type === "disconnect") {
1724
- void reader.cancel().catch(() => {
1725
- });
1726
- return;
1727
- }
1728
- const { done, value } = next.result;
1729
- if (done) {
1730
- break;
1731
- }
1732
- if (!value || value.byteLength === 0) {
1733
- continue;
1734
- }
1735
- if (!res.write(value)) {
1736
- if (!await waitForWritable(res)) {
1737
- void reader.cancel().catch(() => {
1738
- });
1739
- return;
1740
- }
1741
- }
1742
- }
1743
- res.end();
1744
- } catch (error) {
1745
- void reader.cancel(error).catch(() => {
1746
- });
1747
- if (!res.writableEnded) {
1748
- const responseError = error instanceof Error ? error : new Error(String(error));
1749
- if (typeof res.destroy === "function") {
1750
- res.destroy(responseError);
1751
- } else {
1752
- res.end();
1753
- }
1754
- }
1755
- throw error;
1756
- } finally {
1757
- disconnectWatcher?.dispose();
1758
- try {
1759
- reader.releaseLock();
1760
- } catch {
1761
- }
1762
- }
1763
- }
1764
- __name(sendWebResponse, "sendWebResponse");
1765
19
 
1766
- // src/server-http.ts
1767
- var DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT = 1e7;
1768
- var DEFAULT_FARM_SERVER_HEADERS_TIMEOUT = 6e4;
1769
- var DEFAULT_FARM_SERVER_REQUEST_TIMEOUT = 3e5;
1770
- var DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT = 5e3;
1771
- var DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT = 3e4;
1772
- var MAX_FARM_SERVER_TIMEOUT = 2147483647;
1773
- var _FarmRequestBodyError = class _FarmRequestBodyError extends Error {
1774
- constructor(code, status, message) {
1775
- super(message);
1776
- this.name = "FarmRequestBodyError";
1777
- this.code = code;
1778
- this.status = status;
1779
- }
1780
- };
1781
- __name(_FarmRequestBodyError, "FarmRequestBodyError");
1782
- var FarmRequestBodyError = _FarmRequestBodyError;
1783
- function resolveFarmServerConfig(config) {
1784
- const headersTimeout = parseFarmServerDuration(
1785
- config?.headersTimeout ?? DEFAULT_FARM_SERVER_HEADERS_TIMEOUT,
1786
- "server.headersTimeout"
1787
- );
1788
- const requestTimeout = parseFarmServerDuration(
1789
- config?.requestTimeout ?? DEFAULT_FARM_SERVER_REQUEST_TIMEOUT,
1790
- "server.requestTimeout"
1791
- );
1792
- if (headersTimeout > requestTimeout) {
1793
- throw new TypeError("server.headersTimeout must not exceed server.requestTimeout");
1794
- }
1795
- return Object.freeze({
1796
- bodySizeLimit: parseBodySizeLimit(
1797
- config?.bodySizeLimit ?? DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,
1798
- "server.bodySizeLimit"
1799
- ),
1800
- trustProxy: config?.trustProxy === true,
1801
- headersTimeout,
1802
- requestTimeout,
1803
- keepAliveTimeout: parseFarmServerDuration(
1804
- config?.keepAliveTimeout ?? DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT,
1805
- "server.keepAliveTimeout"
1806
- ),
1807
- gracefulShutdownTimeout: parseFarmServerDuration(
1808
- config?.gracefulShutdownTimeout ?? DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,
1809
- "server.gracefulShutdownTimeout"
1810
- ),
1811
- health: resolveFarmServerHealthConfig(config?.health)
1812
- });
1813
- }
1814
- __name(resolveFarmServerConfig, "resolveFarmServerConfig");
1815
- function parseFarmServerDuration(value, optionName = "duration") {
1816
- if (typeof value === "number") {
1817
- if (!Number.isSafeInteger(value) || value <= 0) {
1818
- throw new TypeError(`${optionName} must be a positive safe integer`);
1819
- }
1820
- if (value > MAX_FARM_SERVER_TIMEOUT) {
1821
- throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);
1822
- }
1823
- return value;
1824
- }
1825
- const match = value.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/);
1826
- if (!match) {
1827
- throw new TypeError(`${optionName} must be milliseconds or a duration such as "30s" or "2m"`);
1828
- }
1829
- const amount = Number(match[1]);
1830
- const unit = match[2];
1831
- const multiplier = unit === "ms" ? 1 : unit === "s" ? 1e3 : unit === "m" ? 6e4 : 36e5;
1832
- const milliseconds = Math.floor(amount * multiplier);
1833
- if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {
1834
- throw new TypeError(`${optionName} must resolve to a positive safe integer`);
1835
- }
1836
- if (milliseconds > MAX_FARM_SERVER_TIMEOUT) {
1837
- throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);
1838
- }
1839
- return milliseconds;
1840
- }
1841
- __name(parseFarmServerDuration, "parseFarmServerDuration");
1842
- function resolveFarmServerHealthConfig(config) {
1843
- if (config === false || config && "enabled" in config && config.enabled === false) {
1844
- return Object.freeze({
1845
- enabled: false,
1846
- livenessPath: "/_farm/health/live",
1847
- readinessPath: "/_farm/health/ready"
1848
- });
1849
- }
1850
- const livenessPath = normalizeHealthPath(
1851
- config?.livenessPath ?? "/_farm/health/live",
1852
- "server.health.livenessPath"
1853
- );
1854
- const readinessPath = normalizeHealthPath(
1855
- config?.readinessPath ?? "/_farm/health/ready",
1856
- "server.health.readinessPath"
1857
- );
1858
- if (livenessPath === readinessPath) {
1859
- throw new TypeError("server.health livenessPath and readinessPath must be different");
1860
- }
1861
- return Object.freeze({ enabled: true, livenessPath, readinessPath });
1862
- }
1863
- __name(resolveFarmServerHealthConfig, "resolveFarmServerHealthConfig");
1864
- function normalizeHealthPath(value, optionName) {
1865
- const path = value.trim();
1866
- if (!path.startsWith("/") || path.includes("?") || path.includes("#") || path.includes("*")) {
1867
- throw new TypeError(`${optionName} must be an absolute pathname without a query or wildcard`);
1868
- }
1869
- const normalized = path.length > 1 ? path.replace(/\/+$/, "") || "/" : path;
1870
- assertBrowserStableRoutePath(normalized);
1871
- return normalized;
1872
- }
1873
- __name(normalizeHealthPath, "normalizeHealthPath");
1874
- function parseBodySizeLimit(value, optionName = "bodySizeLimit") {
1875
- if (typeof value === "number") {
1876
- if (!Number.isSafeInteger(value) || value <= 0) {
1877
- throw new TypeError(`${optionName} must be a positive safe integer`);
1878
- }
1879
- return value;
1880
- }
1881
- const match = value.trim().toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|kib|mib|gib)?$/);
1882
- if (!match) {
1883
- throw new TypeError(`${optionName} must be bytes or a size string such as "500kb" or "10mb"`);
1884
- }
1885
- const amount = Number(match[1]);
1886
- const unit = match[2] ?? "b";
1887
- const multiplier = {
1888
- b: 1,
1889
- kb: 1e3,
1890
- mb: 1e6,
1891
- gb: 1e9,
1892
- kib: 1024,
1893
- mib: 1048576,
1894
- gib: 1073741824
1895
- };
1896
- const bytes = Math.floor(amount * multiplier[unit]);
1897
- if (!Number.isSafeInteger(bytes) || bytes <= 0) {
1898
- throw new TypeError(`${optionName} must resolve to a positive safe integer`);
1899
- }
1900
- return bytes;
1901
- }
1902
- __name(parseBodySizeLimit, "parseBodySizeLimit");
1903
- async function bufferFarmRequestBody(request, limit) {
1904
- if (request.method === "GET" || request.method === "HEAD" || request.body === null) {
1905
- return request;
1906
- }
1907
- const bytes = await readFarmRequestBody(request, limit);
1908
- const body = new Uint8Array(bytes.byteLength);
1909
- body.set(bytes);
1910
- const buffered = new Request(request, {
1911
- // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.
1912
- body: body.buffer
1913
- });
1914
- copyRequestContext(request, buffered);
1915
- return buffered;
1916
- }
1917
- __name(bufferFarmRequestBody, "bufferFarmRequestBody");
1918
- async function readFarmRequestBody(request, limit) {
1919
- try {
1920
- validateContentLength(request.headers.get("content-length"), limit);
1921
- } catch (error) {
1922
- void request.body?.cancel(error).catch(() => {
1923
- });
1924
- throw error;
1925
- }
1926
- throwIfAborted(request.signal);
1927
- if (!request.body) return new Uint8Array();
1928
- const reader = request.body.getReader();
1929
- const chunks = [];
1930
- let total = 0;
1931
- const cancelBodyRead = /* @__PURE__ */ __name(() => {
1932
- void reader.cancel(request.signal.reason).catch(() => {
1933
- });
1934
- }, "cancelBodyRead");
1935
- request.signal.addEventListener("abort", cancelBodyRead, { once: true });
1936
- try {
1937
- while (true) {
1938
- throwIfAborted(request.signal);
1939
- const { done, value } = await reader.read();
1940
- throwIfAborted(request.signal);
1941
- if (done) break;
1942
- if (!value) continue;
1943
- total += value.byteLength;
1944
- if (total > limit) {
1945
- const error = new FarmRequestBodyError("BODY_TOO_LARGE", 413, "Request body is too large");
1946
- void reader.cancel(error).catch(() => {
1947
- });
1948
- throw error;
1949
- }
1950
- chunks.push(value);
1951
- }
1952
- } catch (error) {
1953
- if (request.signal.aborted) throwIfAborted(request.signal);
1954
- throw error;
1955
- } finally {
1956
- request.signal.removeEventListener("abort", cancelBodyRead);
1957
- reader.releaseLock();
1958
- }
1959
- const body = new Uint8Array(total);
1960
- let offset = 0;
1961
- for (const chunk of chunks) {
1962
- body.set(chunk, offset);
1963
- offset += chunk.byteLength;
1964
- }
1965
- return body;
1966
- }
1967
- __name(readFarmRequestBody, "readFarmRequestBody");
1968
- async function readNodeRequestBody(request, limit) {
1969
- const rawContentLength = request.headers["content-length"];
1970
- const contentLength = Array.isArray(rawContentLength) ? rawContentLength[0] : rawContentLength;
1971
- try {
1972
- validateContentLength(contentLength, limit);
1973
- } catch (error) {
1974
- request.resume?.();
1975
- throw error;
1976
- }
1977
- return await new Promise((resolve, reject) => {
1978
- const chunks = [];
1979
- let total = 0;
1980
- let settled = false;
1981
- const cleanup = /* @__PURE__ */ __name(() => {
1982
- request.removeListener?.("data", onData);
1983
- request.removeListener?.("end", onEnd);
1984
- request.removeListener?.("error", onError);
1985
- }, "cleanup");
1986
- const rejectOnce = /* @__PURE__ */ __name((error) => {
1987
- if (settled) return;
1988
- settled = true;
1989
- cleanup();
1990
- request.resume?.();
1991
- reject(error);
1992
- }, "rejectOnce");
1993
- const onData = /* @__PURE__ */ __name((chunk) => {
1994
- const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1995
- total += bytes.byteLength;
1996
- if (total > limit) {
1997
- rejectOnce(new FarmRequestBodyError("BODY_TOO_LARGE", 413, "Request body is too large"));
1998
- return;
1999
- }
2000
- chunks.push(bytes);
2001
- }, "onData");
2002
- const onEnd = /* @__PURE__ */ __name(() => {
2003
- if (settled) return;
2004
- settled = true;
2005
- cleanup();
2006
- resolve(Buffer.concat(chunks, total));
2007
- }, "onEnd");
2008
- const onError = /* @__PURE__ */ __name((error) => rejectOnce(error), "onError");
2009
- request.on("data", onData);
2010
- request.on("end", onEnd);
2011
- request.on("error", onError);
2012
- });
2013
- }
2014
- __name(readNodeRequestBody, "readNodeRequestBody");
2015
- function createFarmRequestBodyErrorResponse(error) {
2016
- if (!(error instanceof FarmRequestBodyError)) return null;
2017
- return new Response(error.status === 413 ? "Payload Too Large" : "Bad Request", {
2018
- status: error.status,
2019
- headers: {
2020
- "cache-control": "no-store",
2021
- "content-type": "text/plain; charset=utf-8",
2022
- "x-content-type-options": "nosniff"
2023
- }
2024
- });
2025
- }
2026
- __name(createFarmRequestBodyErrorResponse, "createFarmRequestBodyErrorResponse");
2027
- function validateContentLength(value, limit) {
2028
- const contentLength = value?.trim();
2029
- if (!contentLength) return;
2030
- if (!/^\d+$/.test(contentLength)) {
2031
- throw new FarmRequestBodyError("INVALID_CONTENT_LENGTH", 400, "Invalid content-length header");
2032
- }
2033
- if (Number(contentLength) > limit) {
2034
- throw new FarmRequestBodyError("BODY_TOO_LARGE", 413, "Request body is too large");
2035
- }
2036
- }
2037
- __name(validateContentLength, "validateContentLength");
2038
- function throwIfAborted(signal) {
2039
- if (!signal.aborted) return;
2040
- if (signal.reason !== void 0) throw signal.reason;
2041
- throw new DOMException("The operation was aborted", "AbortError");
2042
- }
2043
- __name(throwIfAborted, "throwIfAborted");
2044
20
 
2045
- // src/integrations.ts
2046
- var FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY = "farm.integration.internalDispatch";
2047
- var FARM_INTEGRATION_SET_COOKIES_KEY = "farm:integration:set-cookies";
2048
- function forwardIntegrationSetCookies(context, cookies) {
2049
- if (cookies.length === 0) return;
2050
- const existing = context.req.get(FARM_INTEGRATION_SET_COOKIES_KEY) ?? [];
2051
- context.req.set(FARM_INTEGRATION_SET_COOKIES_KEY, [...existing, ...cookies]);
2052
- }
2053
- __name(forwardIntegrationSetCookies, "forwardIntegrationSetCookies");
2054
- function takeForwardedIntegrationSetCookies(context) {
2055
- const cookies = context.req.get(FARM_INTEGRATION_SET_COOKIES_KEY);
2056
- if (cookies && cookies.length > 0) {
2057
- context.req.delete(FARM_INTEGRATION_SET_COOKIES_KEY);
2058
- return cookies;
2059
- }
2060
- if (cookies) {
2061
- context.req.delete(FARM_INTEGRATION_SET_COOKIES_KEY);
2062
- }
2063
- return [];
2064
- }
2065
- __name(takeForwardedIntegrationSetCookies, "takeForwardedIntegrationSetCookies");
2066
- function appendIntegrationForwardedCookies(response, cookies) {
2067
- if (cookies.length === 0) return response;
2068
- const headers = new Headers(response.headers);
2069
- for (const cookie of cookies) {
2070
- headers.append("set-cookie", cookie);
2071
- }
2072
- return new Response(response.body, {
2073
- status: response.status,
2074
- statusText: response.statusText,
2075
- headers
2076
- });
2077
- }
2078
- __name(appendIntegrationForwardedCookies, "appendIntegrationForwardedCookies");
2079
- var defineIntegrationSchema = defineSchema;
2080
- var FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME = /* @__PURE__ */ Symbol.for(
2081
- "@farm.js/core/integration-plugin-server-runtime"
2082
- );
2083
- var FARM_INTEGRATION_PLUGIN_OWNER = /* @__PURE__ */ Symbol.for("@farm.js/core/integration-plugin-owner");
2084
- function getFarmIntegrationPluginServerRuntime(plugin) {
2085
- const value = plugin[FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME];
2086
- return typeof value === "boolean" ? value : void 0;
2087
- }
2088
- __name(getFarmIntegrationPluginServerRuntime, "getFarmIntegrationPluginServerRuntime");
2089
- function getFarmIntegrationPluginOwner(plugin) {
2090
- const value = plugin[FARM_INTEGRATION_PLUGIN_OWNER];
2091
- return value && typeof value === "object" ? value : void 0;
2092
- }
2093
- __name(getFarmIntegrationPluginOwner, "getFarmIntegrationPluginOwner");
2094
- function defineTypedIntegrationRoute(method, path, input) {
2095
- return {
2096
- path,
2097
- method,
2098
- middleware: input.middleware,
2099
- before: input.before,
2100
- after: input.after,
2101
- rawBody: input.rawBody,
2102
- bodyFormat: input.bodyFormat,
2103
- input: normalizeIntegrationRouteInputSchemas(input),
2104
- handler: input.handler,
2105
- __operation: defineIntegrationAPIOperation({
2106
- path,
2107
- method,
2108
- bodyFormat: input.bodyFormat,
2109
- responseFormat: input.responseFormat,
2110
- headers: input.headers,
2111
- credentials: input.credentials,
2112
- isServer: input.isServer
2113
- })
2114
- };
2115
- }
2116
- __name(defineTypedIntegrationRoute, "defineTypedIntegrationRoute");
2117
- function createIntegrationRouteFactory() {
2118
- return {
2119
- get(path, input) {
2120
- return defineTypedIntegrationRoute(
2121
- "GET",
2122
- path,
2123
- input
2124
- );
2125
- },
2126
- post(path, input) {
2127
- return defineTypedIntegrationRoute(
2128
- "POST",
2129
- path,
2130
- {
2131
- bodyFormat: "json",
2132
- ...input
2133
- }
2134
- );
2135
- },
2136
- query(path, input) {
2137
- return defineTypedIntegrationRoute("QUERY", path, {
2138
- bodyFormat: "json",
2139
- ...input
2140
- });
2141
- },
2142
- put(path, input) {
2143
- return defineTypedIntegrationRoute(
2144
- "PUT",
2145
- path,
2146
- {
2147
- bodyFormat: "json",
2148
- ...input
2149
- }
2150
- );
2151
- },
2152
- patch(path, input) {
2153
- return defineTypedIntegrationRoute("PATCH", path, {
2154
- bodyFormat: "json",
2155
- ...input
2156
- });
2157
- },
2158
- delete(path, input) {
2159
- return defineTypedIntegrationRoute("DELETE", path, {
2160
- bodyFormat: "json",
2161
- ...input
2162
- });
2163
- },
2164
- options(path, input) {
2165
- return defineTypedIntegrationRoute("OPTIONS", path, input);
2166
- },
2167
- head(path, input) {
2168
- return defineTypedIntegrationRoute(
2169
- "HEAD",
2170
- path,
2171
- input
2172
- );
2173
- }
2174
- };
2175
- }
2176
- __name(createIntegrationRouteFactory, "createIntegrationRouteFactory");
2177
- function createIntegrationRoute(_schema) {
2178
- return createIntegrationRouteFactory();
2179
- }
2180
- __name(createIntegrationRoute, "createIntegrationRoute");
2181
- var integrationRoute = createIntegrationRouteFactory();
2182
- var INTEGRATION_RUNTIME_REGISTRY_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRuntimeRegistry");
2183
- var INTEGRATION_REQUEST_DISPATCHER_KEY = /* @__PURE__ */ Symbol.for("farm.integrationRequestDispatcher");
2184
- function getIntegrationRuntimeRegistry() {
2185
- const globalState = globalThis;
2186
- if (!globalState[INTEGRATION_RUNTIME_REGISTRY_KEY]) {
2187
- globalState[INTEGRATION_RUNTIME_REGISTRY_KEY] = /* @__PURE__ */ new Map();
2188
- }
2189
- return globalState[INTEGRATION_RUNTIME_REGISTRY_KEY];
2190
- }
2191
- __name(getIntegrationRuntimeRegistry, "getIntegrationRuntimeRegistry");
2192
- function isIntegrationEndpointRoute(value) {
2193
- return !!value && typeof value === "object" && typeof value.path === "string" && typeof value.handler === "function";
2194
- }
2195
- __name(isIntegrationEndpointRoute, "isIntegrationEndpointRoute");
2196
- function flattenIntegrationEndpoints(endpoints) {
2197
- if (!endpoints) {
2198
- return [];
2199
- }
2200
- if (Array.isArray(endpoints)) {
2201
- return endpoints.flatMap((endpoint) => flattenIntegrationEndpoints(endpoint));
2202
- }
2203
- if (isIntegrationEndpointRoute(endpoints)) {
2204
- return [endpoints];
2205
- }
2206
- if (typeof endpoints === "object") {
2207
- return Object.values(endpoints).flatMap((endpoint) => flattenIntegrationEndpoints(endpoint));
2208
- }
2209
- return [];
2210
- }
2211
- __name(flattenIntegrationEndpoints, "flattenIntegrationEndpoints");
2212
- function defineIntegration(integration) {
2213
- const category = integration.category ?? integration.slot;
2214
- if (!category) {
2215
- throw new Error("Integration category is required.");
2216
- }
2217
- if (integration.category && integration.slot && integration.category !== integration.slot) {
2218
- throw new Error("Integration category and slot must match when both are provided.");
2219
- }
2220
- const routeFactory = createIntegrationRoute(integration.schema);
2221
- const routes = typeof integration.routes === "function" ? integration.routes({
2222
- route: routeFactory,
2223
- integrationRoute: routeFactory
2224
- }) : integration.routes;
2225
- const endpoints = typeof integration.endpoints === "function" ? integration.endpoints({
2226
- endpoint: routeFactory,
2227
- route: routeFactory,
2228
- integrationRoute: routeFactory
2229
- }) : integration.endpoints;
2230
- const endpointRoutes = flattenIntegrationEndpoints(endpoints);
2231
- const allRoutes = routes?.length || endpointRoutes.length ? [...routes || [], ...endpointRoutes] : void 0;
2232
- for (const route2 of allRoutes || []) {
2233
- assertUniqueRouteParameters(route2.path, "api");
2234
- validateConfigRouteSource(route2.path, `Integration route "${route2.path}"`);
2235
- assertTerminalCatchAll(route2.path, "api");
2236
- }
2237
- const derivedApi = integration.api || (allRoutes?.length ? api.fromRoutes(
2238
- allRoutes
2239
- ) : void 0);
2240
- return {
2241
- kind: "farm-integration",
2242
- ...integration,
2243
- endpoints,
2244
- routes: allRoutes,
2245
- api: derivedApi,
2246
- category,
2247
- slot: category
2248
- };
2249
- }
2250
- __name(defineIntegration, "defineIntegration");
2251
- function isFarmIntegration(value) {
2252
- return !!value && typeof value === "object" && value.kind === "farm-integration";
2253
- }
2254
- __name(isFarmIntegration, "isFarmIntegration");
2255
- function resolveIntegrationPlugins(integrations) {
2256
- if (!integrations) {
2257
- return [];
2258
- }
2259
- const plugins = [];
2260
- for (const [key, integration] of Object.entries(integrations)) {
2261
- if (!integration || !isFarmIntegration(integration)) {
2262
- continue;
2263
- }
2264
- const owner = createIntegrationPluginOwner(key, integration, "lifecycle");
2265
- plugins.push(withIntegrationPluginOwner(createIntegrationPlugin(key, integration), owner));
2266
- plugins.push(...resolveIntegrationPluginContributions(key, integration));
2267
- }
2268
- return plugins;
2269
- }
2270
- __name(resolveIntegrationPlugins, "resolveIntegrationPlugins");
2271
- function resolveIntegrationPluginContributions(key, integration) {
2272
- const contributions = integration.plugins;
2273
- if (!contributions) return [];
2274
- if (!Array.isArray(contributions)) {
2275
- throw new TypeError(`Integration "${key}" plugins must be an array`);
2276
- }
2277
- const names = /* @__PURE__ */ new Set();
2278
- return contributions.map((plugin, index) => {
2279
- if (!plugin || typeof plugin !== "object" || typeof plugin.name !== "string") {
2280
- throw new TypeError(`Integration "${key}" plugin at index ${index} is invalid`);
2281
- }
2282
- const name = plugin.name.trim();
2283
- if (!name) {
2284
- throw new TypeError(`Integration "${key}" plugin at index ${index} requires a name`);
2285
- }
2286
- if (names.has(name)) {
2287
- throw new Error(`Integration "${key}" contributes duplicate plugin name "${name}"`);
2288
- }
2289
- names.add(name);
2290
- return withIntegrationPluginOwner(
2291
- plugin,
2292
- createIntegrationPluginOwner(key, integration, "contribution"),
2293
- createIntegrationPluginContext(key, integration)
2294
- );
2295
- });
2296
- }
2297
- __name(resolveIntegrationPluginContributions, "resolveIntegrationPluginContributions");
2298
- function createIntegrationPluginOwner(key, integration, source) {
2299
- return Object.freeze({
2300
- key,
2301
- category: integration.category,
2302
- type: integration.type,
2303
- source,
2304
- serverRuntime: integration.serverRuntime !== false
2305
- });
2306
- }
2307
- __name(createIntegrationPluginOwner, "createIntegrationPluginOwner");
2308
- function createIntegrationPluginContext(key, integration) {
2309
- return Object.freeze({
2310
- key,
2311
- category: integration.category,
2312
- type: integration.type,
2313
- instance: integration.instance,
2314
- serverRuntime: integration.serverRuntime !== false
2315
- });
2316
- }
2317
- __name(createIntegrationPluginContext, "createIntegrationPluginContext");
2318
- function withIntegrationPluginOwner(plugin, owner, integration) {
2319
- const descriptors = Object.getOwnPropertyDescriptors(plugin);
2320
- Reflect.deleteProperty(descriptors, FARM_INTEGRATION_PLUGIN_OWNER);
2321
- Reflect.deleteProperty(descriptors, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME);
2322
- const ownedPlugin = Object.create(Object.getPrototypeOf(plugin), descriptors);
2323
- Object.defineProperty(ownedPlugin, FARM_INTEGRATION_PLUGIN_OWNER, { value: owner });
2324
- Object.defineProperty(ownedPlugin, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME, {
2325
- value: owner.serverRuntime
2326
- });
2327
- if (integration) {
2328
- setFarmPluginIntegrationContext(ownedPlugin, integration);
2329
- }
2330
- return ownedPlugin;
2331
- }
2332
- __name(withIntegrationPluginOwner, "withIntegrationPluginOwner");
2333
- function getIntegrationProviders(integrations) {
2334
- if (!integrations) {
2335
- return [];
2336
- }
2337
- const providers = [];
2338
- for (const integration of Object.values(integrations)) {
2339
- if (!integration || !isFarmIntegration(integration) || !integration.providers?.length) {
2340
- continue;
2341
- }
2342
- for (const provider of integration.providers) {
2343
- providers.push({
2344
- name: provider.name,
2345
- type: provider.type,
2346
- props: provider.props,
2347
- supportsIsolatedHydration: provider.supportsIsolatedHydration,
2348
- component: provider.component
2349
- });
2350
- }
2351
- }
2352
- return providers;
2353
- }
2354
- __name(getIntegrationProviders, "getIntegrationProviders");
2355
- function isFarmIntegrationProviderComponentReference(value) {
2356
- return Boolean(
2357
- value && typeof value === "object" && "module" in value && typeof value.module === "string" && value.module.length > 0
2358
- );
2359
- }
2360
- __name(isFarmIntegrationProviderComponentReference, "isFarmIntegrationProviderComponentReference");
2361
- function getIntegrationDocumentNavigationMatchers(integrations) {
2362
- if (!integrations) {
2363
- return [];
2364
- }
2365
- const matchers = [];
2366
- for (const integration of Object.values(integrations)) {
2367
- if (!integration || !isFarmIntegration(integration) || !integration.documentNavigations?.length) {
2368
- continue;
2369
- }
2370
- for (const navigation of integration.documentNavigations) {
2371
- const items = Array.isArray(navigation.matcher) ? navigation.matcher : [navigation.matcher];
2372
- for (const item of items) {
2373
- matchers.push(item);
2374
- }
2375
- }
2376
- }
2377
- return matchers;
2378
- }
2379
- __name(getIntegrationDocumentNavigationMatchers, "getIntegrationDocumentNavigationMatchers");
2380
- function getIntegrationSchemas(integrations) {
2381
- if (!integrations) {
2382
- return {};
2383
- }
2384
- const schemaEntries = Object.entries(integrations).map(([key, integration]) => {
2385
- const schema = integration && isFarmIntegration(integration) ? integration.schema : void 0;
2386
- return schema ? [key, schema] : null;
2387
- }).filter((value) => value !== null);
2388
- return Object.fromEntries(schemaEntries);
2389
- }
2390
- __name(getIntegrationSchemas, "getIntegrationSchemas");
2391
- function getRegisteredIntegrationRuntime(key) {
2392
- return getIntegrationRuntimeRegistry().get(key);
2393
- }
2394
- __name(getRegisteredIntegrationRuntime, "getRegisteredIntegrationRuntime");
2395
- function getRegisteredIntegrations() {
2396
- return Object.fromEntries(
2397
- Array.from(getIntegrationRuntimeRegistry().entries()).map(([key, runtime]) => [
2398
- key,
2399
- runtime.integration
2400
- ])
2401
- );
2402
- }
2403
- __name(getRegisteredIntegrations, "getRegisteredIntegrations");
2404
- function getRegisteredIntegrationSchemas() {
2405
- return getIntegrationSchemas(getRegisteredIntegrations());
2406
- }
2407
- __name(getRegisteredIntegrationSchemas, "getRegisteredIntegrationSchemas");
2408
- function matchIntegrationRoute(integrations, input) {
2409
- if (!integrations) {
2410
- return null;
2411
- }
2412
- const method = normalizeIntegrationRequestMethod(input.method);
2413
- if (!method) {
2414
- return null;
2415
- }
2416
- const pathSegments = canonicalizeRequestPathSegments(input.pathname);
2417
- for (const [key, integration] of Object.entries(integrations)) {
2418
- if (!integration || !isFarmIntegration(integration)) {
2419
- continue;
2420
- }
2421
- const routes = normalizeIntegrationRoutes(integration.routes || []);
2422
- for (const route2 of routes) {
2423
- if (!matchesMethod(route2.methods, method)) {
2424
- continue;
2425
- }
2426
- const params = matchPathSegments(route2[INTEGRATION_ROUTE_SEGMENTS], pathSegments);
2427
- if (!params) {
2428
- continue;
2429
- }
2430
- return {
2431
- key,
2432
- integration,
2433
- route: {
2434
- path: route2.path,
2435
- methods: route2.methods
2436
- },
2437
- params
2438
- };
2439
- }
2440
- }
2441
- return null;
2442
- }
2443
- __name(matchIntegrationRoute, "matchIntegrationRoute");
2444
- function matchRegisteredIntegrationRoute(input) {
2445
- return matchIntegrationRoute(getRegisteredIntegrations(), input);
2446
- }
2447
- __name(matchRegisteredIntegrationRoute, "matchRegisteredIntegrationRoute");
2448
- function createClientSafeIntegrationAPI(api2) {
2449
- if (!api2) {
2450
- return void 0;
2451
- }
2452
- const entries = Object.entries(api2).map(([key, value]) => {
2453
- if (value && typeof value === "object" && value.kind === "farm-integration-api-operation") {
2454
- const operation2 = value;
2455
- return [
2456
- key,
2457
- defineIntegrationAPIOperation({
2458
- path: operation2.path,
2459
- method: operation2.method,
2460
- bodyFormat: operation2.bodyFormat,
2461
- responseFormat: operation2.responseFormat,
2462
- credentials: operation2.credentials,
2463
- isServer: operation2.isServer
2464
- })
2465
- ];
2466
- }
2467
- if (value && typeof value === "object") {
2468
- return [key, createClientSafeIntegrationAPI(value)];
2469
- }
2470
- return [key, value];
2471
- });
2472
- return Object.fromEntries(entries);
2473
- }
2474
- __name(createClientSafeIntegrationAPI, "createClientSafeIntegrationAPI");
2475
- function getRegisteredIntegrationAPIManifest() {
2476
- const manifestEntries = Object.entries(getRegisteredIntegrations()).map(([key, integration]) => {
2477
- const api2 = createClientSafeIntegrationAPI(integration.api);
2478
- return api2 ? [key, api2] : null;
2479
- }).filter((value) => value !== null);
2480
- return Object.fromEntries(manifestEntries);
2481
- }
2482
- __name(getRegisteredIntegrationAPIManifest, "getRegisteredIntegrationAPIManifest");
2483
- function getIntegrationRuntimeEnv() {
2484
- return typeof process !== "undefined" ? process.env : {};
2485
- }
2486
- __name(getIntegrationRuntimeEnv, "getIntegrationRuntimeEnv");
2487
- function isIntegrationConfigDefinition(value) {
2488
- return !!value && typeof value === "object" && ("schema" in value || "env" in value || "defaults" in value || "input" in value || "resolve" in value);
2489
- }
2490
- __name(isIntegrationConfigDefinition, "isIntegrationConfigDefinition");
2491
- function mergeIntegrationConfigValue(current, next) {
2492
- if (next === void 0) {
2493
- return current;
2494
- }
2495
- if (isPlainIntegrationConfigObject(current) && isPlainIntegrationConfigObject(next)) {
2496
- return {
2497
- ...current,
2498
- ...next
2499
- };
2500
- }
2501
- return next;
2502
- }
2503
- __name(mergeIntegrationConfigValue, "mergeIntegrationConfigValue");
2504
- function isPlainIntegrationConfigObject(value) {
2505
- return !!value && typeof value === "object" && !Array.isArray(value);
2506
- }
2507
- __name(isPlainIntegrationConfigObject, "isPlainIntegrationConfigObject");
2508
- async function resolveIntegrationConfigPart(value, context) {
2509
- if (typeof value === "function") {
2510
- return value(context);
2511
- }
2512
- return value;
2513
- }
2514
- __name(resolveIntegrationConfigPart, "resolveIntegrationConfigPart");
2515
- function resolveIntegrationEnvConfig(env) {
2516
- if (!env) {
2517
- return void 0;
2518
- }
2519
- const runtimeEnv = getIntegrationRuntimeEnv();
2520
- const config = {};
2521
- for (const [key, names] of Object.entries(env)) {
2522
- const envNames = Array.isArray(names) ? names : [names];
2523
- const value = envNames.map((name) => runtimeEnv[name]).find((entry) => entry !== void 0);
2524
- if (value !== void 0) {
2525
- config[key] = value;
2526
- }
2527
- }
2528
- return config;
2529
- }
2530
- __name(resolveIntegrationEnvConfig, "resolveIntegrationEnvConfig");
2531
- async function parseIntegrationConfigSchema(integration, schema, value) {
2532
- const parser = schema.safeParseAsync || schema.safeParse;
2533
- if (parser) {
2534
- const result = await parser.call(schema, value);
2535
- if (result.success) {
2536
- return result.data;
2537
- }
2538
- throw createIntegrationConfigValidationError(integration, result.error);
2539
- }
2540
- if (schema["~standard"]?.validate) {
2541
- const result = await schema["~standard"].validate(value);
2542
- if ("value" in result) {
2543
- return result.value;
2544
- }
2545
- throw createIntegrationConfigValidationError(integration, {
2546
- issues: result.issues
2547
- });
2548
- }
2549
- if (schema.parse) {
2550
- try {
2551
- return await schema.parse(value);
2552
- } catch (error) {
2553
- throw createIntegrationConfigValidationError(
2554
- integration,
2555
- normalizeIntegrationValidationError(error)
2556
- );
2557
- }
2558
- }
2559
- throw new Error(
2560
- `Integration "${integration.type}" config schema must expose safeParse, safeParseAsync, parse, or ~standard.validate.`
2561
- );
2562
- }
2563
- __name(parseIntegrationConfigSchema, "parseIntegrationConfigSchema");
2564
- function createIntegrationConfigValidationError(integration, error) {
2565
- const issues = Array.isArray(error.issues) && error.issues.length > 0 ? error.issues.map((issue) => {
2566
- const normalizedPath = normalizeIntegrationValidationPath(issue.path);
2567
- const path = normalizedPath.length ? `${normalizedPath.join(".")}: ` : "";
2568
- return `${path}${issue.message || "Invalid config"}`;
2569
- }).join("; ") : error.message || "Invalid config";
2570
- return new Error(`Integration "${integration.type}" config validation failed: ${issues}`);
2571
- }
2572
- __name(createIntegrationConfigValidationError, "createIntegrationConfigValidationError");
2573
- async function resolveIntegrationConfig(integration, context) {
2574
- const config = integration.config;
2575
- if (!config) {
2576
- return void 0;
2577
- }
2578
- if (!isIntegrationConfigDefinition(config)) {
2579
- return parseIntegrationConfigSchema(integration, config, {});
2580
- }
2581
- let value = {};
2582
- value = mergeIntegrationConfigValue(
2583
- value,
2584
- await resolveIntegrationConfigPart(config.defaults, context)
2585
- );
2586
- value = mergeIntegrationConfigValue(value, resolveIntegrationEnvConfig(config.env));
2587
- value = mergeIntegrationConfigValue(
2588
- value,
2589
- await resolveIntegrationConfigPart(config.input, context)
2590
- );
2591
- value = mergeIntegrationConfigValue(value, await config.resolve?.(context));
2592
- return config.schema ? parseIntegrationConfigSchema(integration, config.schema, value) : value;
2593
- }
2594
- __name(resolveIntegrationConfig, "resolveIntegrationConfig");
2595
- function createIntegrationLifecycleLogger(integration, phase) {
2596
- const write = /* @__PURE__ */ __name((level, message, meta) => {
2597
- if (!integration.log) {
2598
- return;
2599
- }
2600
- void Promise.resolve(
2601
- integration.log({
2602
- category: integration.category,
2603
- slot: integration.category,
2604
- type: integration.type,
2605
- phase,
2606
- level,
2607
- message,
2608
- meta,
2609
- context: /* @__PURE__ */ new Map()
2610
- })
2611
- ).catch(() => {
2612
- });
2613
- }, "write");
2614
- return {
2615
- info(message, meta) {
2616
- write("info", message, meta);
2617
- },
2618
- warn(message, meta) {
2619
- write("warn", message, meta);
2620
- },
2621
- error(message, meta) {
2622
- write("error", message, meta);
2623
- }
2624
- };
2625
- }
2626
- __name(createIntegrationLifecycleLogger, "createIntegrationLifecycleLogger");
2627
- async function emitIntegrationLog(integration, event) {
2628
- try {
2629
- await integration.log?.(event);
2630
- } catch {
2631
- }
2632
- }
2633
- __name(emitIntegrationLog, "emitIntegrationLog");
2634
- var INTEGRATION_DATA_HEADER = "x-farm-integration-data";
2635
- var INTEGRATION_DATA_HEADER_MAX_LENGTH = 16 * 1024;
2636
- var BLOCKED_INTEGRATION_DATA_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
2637
- function isFarmIntegrationData(value) {
2638
- return !!value && typeof value === "object" && !Array.isArray(value);
2639
- }
2640
- __name(isFarmIntegrationData, "isFarmIntegrationData");
2641
- function isPlainIntegrationDataObject(value) {
2642
- if (!isFarmIntegrationData(value)) {
2643
- return false;
2644
- }
2645
- const prototype = Object.getPrototypeOf(value);
2646
- return prototype === Object.prototype || prototype === null;
2647
- }
2648
- __name(isPlainIntegrationDataObject, "isPlainIntegrationDataObject");
2649
- function sanitizeIntegrationDataValue(value) {
2650
- if (Array.isArray(value)) {
2651
- return value.map((item) => sanitizeIntegrationDataValue(item));
2652
- }
2653
- if (!isPlainIntegrationDataObject(value)) {
2654
- return value;
2655
- }
2656
- const sanitized = {};
2657
- for (const [key, item] of Object.entries(value)) {
2658
- if (BLOCKED_INTEGRATION_DATA_KEYS.has(key)) {
2659
- continue;
2660
- }
2661
- sanitized[key] = sanitizeIntegrationDataValue(item);
2662
- }
2663
- return sanitized;
2664
- }
2665
- __name(sanitizeIntegrationDataValue, "sanitizeIntegrationDataValue");
2666
- function normalizeIntegrationData(value) {
2667
- if (!isFarmIntegrationData(value)) {
2668
- return {};
2669
- }
2670
- const sanitized = sanitizeIntegrationDataValue(value);
2671
- return isFarmIntegrationData(sanitized) ? sanitized : {};
2672
- }
2673
- __name(normalizeIntegrationData, "normalizeIntegrationData");
2674
- function getIntegrationDataHeaderByteLength(value) {
2675
- return new TextEncoder().encode(value).byteLength;
2676
- }
2677
- __name(getIntegrationDataHeaderByteLength, "getIntegrationDataHeaderByteLength");
2678
- function parseIntegrationDataHeader(request) {
2679
- const raw = request.headers.get(INTEGRATION_DATA_HEADER);
2680
- if (!raw) {
2681
- return {};
2682
- }
2683
- if (getIntegrationDataHeaderByteLength(raw) > INTEGRATION_DATA_HEADER_MAX_LENGTH) {
2684
- return {};
2685
- }
2686
- try {
2687
- const value = JSON.parse(raw);
2688
- return normalizeIntegrationData(value);
2689
- } catch {
2690
- return {};
2691
- }
2692
- }
2693
- __name(parseIntegrationDataHeader, "parseIntegrationDataHeader");
2694
- function resolveIntegrationData(request, data) {
2695
- return {
2696
- ...parseIntegrationDataHeader(request),
2697
- ...normalizeIntegrationData(data)
2698
- };
2699
- }
2700
- __name(resolveIntegrationData, "resolveIntegrationData");
2701
- function createIntegrationPlugin(integrationKey, integration) {
2702
- const routes = normalizeIntegrationRoutes(integration.routes || []);
2703
- const middleware = [...integration.middleware || []];
2704
- const cleanupCallbacks = [];
2705
- let integrationConfigPromise;
2706
- const runCleanup = /* @__PURE__ */ __name(async () => {
2707
- const callbacks = cleanupCallbacks.splice(0).reverse();
2708
- for (const callback of callbacks) {
2709
- await callback();
2710
- }
2711
- }, "runCleanup");
2712
- const createLifecycleContext = /* @__PURE__ */ __name(async (context, phase, options = {}) => {
2713
- const args = createIntegrationRouteArgs({
2714
- integration,
2715
- config: context.config
2716
- });
2717
- const configContext = {
2718
- key: integrationKey,
2719
- integration,
2720
- appConfig: context.config,
2721
- config: context.config,
2722
- args,
2723
- env: getIntegrationRuntimeEnv(),
2724
- isDev: context.isDev,
2725
- isProd: context.isProd
2726
- };
2727
- integrationConfigPromise ?? (integrationConfigPromise = resolveIntegrationConfig(integration, configContext));
2728
- return {
2729
- ...configContext,
2730
- integrationConfig: await integrationConfigPromise,
2731
- log: createIntegrationLifecycleLogger(integration, phase),
2732
- reason: options.reason,
2733
- async cleanup(callback) {
2734
- if (callback) {
2735
- cleanupCallbacks.push(callback);
2736
- return;
2737
- }
2738
- await runCleanup();
2739
- }
2740
- };
2741
- }, "createLifecycleContext");
2742
- const plugin = {
2743
- name: `farm:integration:${integration.category}:${integration.type}`,
2744
- enforce: "pre",
2745
- async init(context) {
2746
- getIntegrationRuntimeRegistry().set(integrationKey, {
2747
- integration,
2748
- config: context.config,
2749
- isDev: context.isDev,
2750
- isProd: context.isProd
2751
- });
2752
- await createLifecycleContext(context, "validate");
2753
- if (integration.validate) {
2754
- await integration.validate(await createLifecycleContext(context, "validate"));
2755
- }
2756
- if (integration.setup) {
2757
- await integration.setup(await createLifecycleContext(context, "setup"));
2758
- }
2759
- if (!integration.log) {
2760
- return;
2761
- }
2762
- for (const route2 of routes) {
2763
- await emitIntegrationLog(integration, {
2764
- category: integration.category,
2765
- slot: integration.category,
2766
- type: integration.type,
2767
- phase: "registered",
2768
- route: {
2769
- kind: "route",
2770
- path: route2.path,
2771
- methods: route2.methods
2772
- },
2773
- context: /* @__PURE__ */ new Map()
2774
- });
2775
- }
2776
- for (const entry of middleware) {
2777
- await emitIntegrationLog(integration, {
2778
- category: integration.category,
2779
- slot: integration.category,
2780
- type: integration.type,
2781
- phase: "registered",
2782
- route: {
2783
- kind: "middleware",
2784
- path: normalizeMatcher(entry.matcher),
2785
- methods: ["ALL"]
2786
- },
2787
- context: /* @__PURE__ */ new Map()
2788
- });
2789
- }
2790
- },
2791
- async ready(context) {
2792
- if (integration.ready) {
2793
- await integration.ready(await createLifecycleContext(context, "ready"));
2794
- }
2795
- },
2796
- async shutdown(payload, context) {
2797
- try {
2798
- if (integration.dispose) {
2799
- await integration.dispose(
2800
- await createLifecycleContext(context, "dispose", {
2801
- reason: payload.reason
2802
- })
2803
- );
2804
- }
2805
- } finally {
2806
- await runCleanup();
2807
- }
2808
- },
2809
- async beforeRequest(req, res, context) {
2810
- const fullUrl = `http://${req.headers.host || "localhost"}${req.url || "/"}`;
2811
- const url = new URL(fullUrl);
2812
- const pathname = url.pathname;
2813
- const pathSegments = canonicalizeRequestPathSegments(pathname);
2814
- const method = normalizeIntegrationRequestMethod(req.method);
2815
- const requestId = getRequestId(req);
2816
- let bodyLoaded = false;
2817
- let requestBody;
2818
- const getRequestBody = /* @__PURE__ */ __name(async () => {
2819
- if (!bodyLoaded) {
2820
- bodyLoaded = true;
2821
- if (req.method && req.method !== "GET" && req.method !== "HEAD") {
2822
- requestBody = await readNodeRequestBody(
2823
- req,
2824
- resolveFarmServerConfig(context.config.server).bodySizeLimit
2825
- );
2826
- }
2827
- }
2828
- return requestBody;
2829
- }, "getRequestBody");
2830
- const createHandlerRequest = /* @__PURE__ */ __name(async () => {
2831
- try {
2832
- return createWebRequest(req, fullUrl, await getRequestBody());
2833
- } catch (error) {
2834
- const response = createFarmRequestBodyErrorResponse(error);
2835
- if (!response) throw error;
2836
- await sendWebResponse(res, response);
2837
- return null;
2838
- }
2839
- }, "createHandlerRequest");
2840
- for (const entry of middleware) {
2841
- const params = resolveMatcherParams(entry.matcher, pathname);
2842
- if (!params) {
2843
- continue;
2844
- }
2845
- const request = await createHandlerRequest();
2846
- if (!request) return;
2847
- const handlerContext = createIntegrationHandlerContext({
2848
- integration,
2849
- route: {
2850
- kind: "middleware",
2851
- path: normalizeMatcher(entry.matcher),
2852
- methods: ["ALL"]
2853
- },
2854
- request,
2855
- rawRequest: req,
2856
- params,
2857
- pathname,
2858
- requestId,
2859
- pluginContext: context
2860
- });
2861
- const startedAt = Date.now();
2862
- await emitIntegrationLog(integration, {
2863
- category: integration.category,
2864
- slot: integration.category,
2865
- type: integration.type,
2866
- phase: "request:start",
2867
- route: {
2868
- kind: "middleware",
2869
- path: normalizeMatcher(entry.matcher),
2870
- methods: ["ALL"]
2871
- },
2872
- request,
2873
- requestId,
2874
- context: handlerContext.req.snapshot()
2875
- });
2876
- try {
2877
- const response = await entry.handler(request, handlerContext);
2878
- const forwardedCookies = takeForwardedIntegrationSetCookies(handlerContext);
2879
- if (forwardedCookies.length > 0) {
2880
- const setCookieHeaders = new Headers();
2881
- for (const cookie of forwardedCookies) {
2882
- setCookieHeaders.append("set-cookie", cookie);
2883
- }
2884
- applyWebResponseHeaders(res, setCookieHeaders, { appendSetCookie: true });
2885
- }
2886
- if (response) {
2887
- await sendWebResponse(res, response);
2888
- await emitIntegrationLog(integration, {
2889
- category: integration.category,
2890
- slot: integration.category,
2891
- type: integration.type,
2892
- phase: "request:end",
2893
- route: {
2894
- kind: "middleware",
2895
- path: normalizeMatcher(entry.matcher),
2896
- methods: ["ALL"]
2897
- },
2898
- request,
2899
- response,
2900
- requestId,
2901
- durationMs: Date.now() - startedAt,
2902
- context: handlerContext.req.snapshot()
2903
- });
2904
- return;
2905
- }
2906
- await emitIntegrationLog(integration, {
2907
- category: integration.category,
2908
- slot: integration.category,
2909
- type: integration.type,
2910
- phase: "request:end",
2911
- route: {
2912
- kind: "middleware",
2913
- path: normalizeMatcher(entry.matcher),
2914
- methods: ["ALL"]
2915
- },
2916
- request,
2917
- requestId,
2918
- durationMs: Date.now() - startedAt,
2919
- context: handlerContext.req.snapshot()
2920
- });
2921
- } catch (error) {
2922
- await emitIntegrationLog(integration, {
2923
- category: integration.category,
2924
- slot: integration.category,
2925
- type: integration.type,
2926
- phase: "request:error",
2927
- route: {
2928
- kind: "middleware",
2929
- path: normalizeMatcher(entry.matcher),
2930
- methods: ["ALL"]
2931
- },
2932
- request,
2933
- requestId,
2934
- durationMs: Date.now() - startedAt,
2935
- error,
2936
- context: handlerContext.req.snapshot()
2937
- });
2938
- throw error;
2939
- }
2940
- }
2941
- for (const route2 of routes) {
2942
- const params = method && matchesMethod(route2.methods, method) ? matchPathSegments(route2[INTEGRATION_ROUTE_SEGMENTS], pathSegments) : null;
2943
- if (!params) {
2944
- continue;
2945
- }
2946
- const request = await createHandlerRequest();
2947
- if (!request) return;
2948
- const handlerContext = createIntegrationHandlerContext({
2949
- integration,
2950
- route: {
2951
- kind: "route",
2952
- path: route2.path,
2953
- methods: route2.methods
2954
- },
2955
- request,
2956
- rawRequest: req,
2957
- params,
2958
- pathname,
2959
- requestId,
2960
- pluginContext: context
2961
- });
2962
- const startedAt = Date.now();
2963
- await emitIntegrationLog(integration, {
2964
- category: integration.category,
2965
- slot: integration.category,
2966
- type: integration.type,
2967
- phase: "request:start",
2968
- route: {
2969
- kind: "route",
2970
- path: route2.path,
2971
- methods: route2.methods
2972
- },
2973
- request,
2974
- requestId,
2975
- context: handlerContext.req.snapshot()
2976
- });
2977
- try {
2978
- const validation = await validateIntegrationRouteInput(route2, request, url);
2979
- if (!validation.success) {
2980
- await sendWebResponse(res, validation.response);
2981
- await emitIntegrationLog(integration, {
2982
- category: integration.category,
2983
- slot: integration.category,
2984
- type: integration.type,
2985
- phase: "request:end",
2986
- route: {
2987
- kind: "route",
2988
- path: route2.path,
2989
- methods: route2.methods
2990
- },
2991
- request,
2992
- response: validation.response,
2993
- requestId,
2994
- durationMs: Date.now() - startedAt,
2995
- context: handlerContext.req.snapshot()
2996
- });
2997
- return;
2998
- }
2999
- handlerContext.input = validation.input;
3000
- for (const middlewareEntry of route2.middleware || []) {
3001
- const middlewareResponse = await middlewareEntry.handler(request, handlerContext);
3002
- if (middlewareResponse) {
3003
- await sendWebResponse(res, middlewareResponse);
3004
- await emitIntegrationLog(integration, {
3005
- category: integration.category,
3006
- slot: integration.category,
3007
- type: integration.type,
3008
- phase: "request:end",
3009
- route: {
3010
- kind: "route",
3011
- path: route2.path,
3012
- methods: route2.methods
3013
- },
3014
- request,
3015
- response: middlewareResponse,
3016
- requestId,
3017
- durationMs: Date.now() - startedAt,
3018
- context: handlerContext.req.snapshot()
3019
- });
3020
- return;
3021
- }
3022
- }
3023
- const beforeResponse = await runIntegrationRouteBeforeHooks(
3024
- route2,
3025
- request,
3026
- handlerContext
3027
- );
3028
- if (beforeResponse) {
3029
- const response2 = await runIntegrationRouteAfterHooks(
3030
- route2,
3031
- request,
3032
- handlerContext,
3033
- beforeResponse
3034
- );
3035
- await sendWebResponse(res, response2);
3036
- await emitIntegrationLog(integration, {
3037
- category: integration.category,
3038
- slot: integration.category,
3039
- type: integration.type,
3040
- phase: "request:end",
3041
- route: {
3042
- kind: "route",
3043
- path: route2.path,
3044
- methods: route2.methods
3045
- },
3046
- request,
3047
- response: response2,
3048
- requestId,
3049
- durationMs: Date.now() - startedAt,
3050
- context: handlerContext.req.snapshot()
3051
- });
3052
- return;
3053
- }
3054
- const handlerResponse = await route2.handler(request, handlerContext);
3055
- const response = await runIntegrationRouteAfterHooks(
3056
- route2,
3057
- request,
3058
- handlerContext,
3059
- handlerResponse
3060
- );
3061
- await sendWebResponse(res, response);
3062
- await emitIntegrationLog(integration, {
3063
- category: integration.category,
3064
- slot: integration.category,
3065
- type: integration.type,
3066
- phase: "request:end",
3067
- route: {
3068
- kind: "route",
3069
- path: route2.path,
3070
- methods: route2.methods
3071
- },
3072
- request,
3073
- response,
3074
- requestId,
3075
- durationMs: Date.now() - startedAt,
3076
- context: handlerContext.req.snapshot()
3077
- });
3078
- return;
3079
- } catch (error) {
3080
- await emitIntegrationLog(integration, {
3081
- category: integration.category,
3082
- slot: integration.category,
3083
- type: integration.type,
3084
- phase: "request:error",
3085
- route: {
3086
- kind: "route",
3087
- path: route2.path,
3088
- methods: route2.methods
3089
- },
3090
- request,
3091
- requestId,
3092
- durationMs: Date.now() - startedAt,
3093
- error,
3094
- context: handlerContext.req.snapshot()
3095
- });
3096
- throw error;
3097
- }
3098
- }
3099
- }
3100
- };
3101
- Object.defineProperty(plugin, FARM_INTEGRATION_PLUGIN_SERVER_RUNTIME, {
3102
- value: integration.serverRuntime !== false
3103
- });
3104
- return plugin;
3105
- }
3106
- __name(createIntegrationPlugin, "createIntegrationPlugin");
3107
- function createIntegrationHandlerContext(input) {
3108
- const req = createIntegrationRequestContextStore(
3109
- input.rawRequest,
3110
- input.request,
3111
- input.pluginContext
3112
- );
3113
- return {
3114
- request: input.request,
3115
- requestId: input.requestId,
3116
- url: new URL(input.request.url),
3117
- pathname: input.pathname,
3118
- method: input.request.method,
3119
- params: input.params,
3120
- input: {},
3121
- args: createIntegrationRouteArgs({
3122
- integration: input.integration,
3123
- config: input.pluginContext.config
3124
- }),
3125
- data: resolveIntegrationData(input.request),
3126
- integration: {
3127
- category: input.integration.category,
3128
- slot: input.integration.category,
3129
- type: input.integration.type,
3130
- instance: input.integration.instance
3131
- },
3132
- route: input.route,
3133
- req,
3134
- requestContext: req,
3135
- config: input.pluginContext.config,
3136
- isDev: input.pluginContext.isDev,
3137
- isProd: input.pluginContext.isProd
3138
- };
3139
- }
3140
- __name(createIntegrationHandlerContext, "createIntegrationHandlerContext");
3141
- var INTEGRATION_ROUTE_SEGMENTS = /* @__PURE__ */ Symbol("farm.integrationRouteSegments");
3142
- var EMPTY_NORMALIZED_INTEGRATION_ROUTES = [];
3143
- var normalizedIntegrationRoutesCache = /* @__PURE__ */ new WeakMap();
3144
- function normalizeIntegrationRoutes(routes) {
3145
- if (routes.length === 0) {
3146
- return EMPTY_NORMALIZED_INTEGRATION_ROUTES;
3147
- }
3148
- const cached = normalizedIntegrationRoutesCache.get(routes);
3149
- if (cached) {
3150
- return cached;
3151
- }
3152
- const normalized = routes.map((route2, index) => {
3153
- assertUniqueRouteParameters(route2.path, "api");
3154
- return {
3155
- index,
3156
- route: {
3157
- ...route2,
3158
- methods: normalizeIntegrationRouteMethods(route2),
3159
- input: normalizeIntegrationRouteInputSchemas(route2),
3160
- [INTEGRATION_ROUTE_SEGMENTS]: splitPath(route2.path)
3161
- },
3162
- specificity: getRoutePatternSpecificity(route2.path, "api")
3163
- };
3164
- }).sort(
3165
- (left, right) => compareRouteSpecificity(left.specificity, right.specificity) || left.index - right.index
3166
- ).map(({ route: route2 }) => route2);
3167
- normalizedIntegrationRoutesCache.set(routes, normalized);
3168
- return normalized;
3169
- }
3170
- __name(normalizeIntegrationRoutes, "normalizeIntegrationRoutes");
3171
- function normalizeIntegrationRouteMethods(route2) {
3172
- const input = route2.methods && route2.methods.length > 0 ? [...route2.methods] : route2.method ? [route2.method] : ["ALL"];
3173
- return input.map((method) => String(method).toUpperCase());
3174
- }
3175
- __name(normalizeIntegrationRouteMethods, "normalizeIntegrationRouteMethods");
3176
- function normalizeIntegrationRouteInputSchemas(route2) {
3177
- const input = {
3178
- ...route2.input
3179
- };
3180
- if (route2.body) {
3181
- input.body = route2.body;
3182
- }
3183
- if (route2.query) {
3184
- input.query = route2.query;
3185
- }
3186
- return input.body || input.query ? input : void 0;
3187
- }
3188
- __name(normalizeIntegrationRouteInputSchemas, "normalizeIntegrationRouteInputSchemas");
3189
- async function validateIntegrationRouteInput(route2, request, url) {
3190
- if (request.method.toUpperCase() === "QUERY" && !request.headers.has("content-type")) {
3191
- return {
3192
- success: false,
3193
- response: Response.json(
3194
- {
3195
- error: "Invalid QUERY request",
3196
- message: "QUERY requests must include a Content-Type header."
3197
- },
3198
- { status: 400 }
3199
- )
3200
- };
3201
- }
3202
- const schemas = route2.input;
3203
- if (!schemas?.body && !schemas?.query) {
3204
- return {
3205
- success: true,
3206
- input: {}
3207
- };
3208
- }
3209
- const input = {};
3210
- const issues = [];
3211
- if (schemas.query) {
3212
- const queryResult = await parseIntegrationInputSchema(
3213
- "query",
3214
- schemas.query,
3215
- createQueryInput(url.searchParams)
3216
- );
3217
- if (queryResult.success) {
3218
- input.query = queryResult.data;
3219
- } else {
3220
- issues.push(...queryResult.issues);
3221
- }
3222
- }
3223
- if (schemas.body) {
3224
- const bodyInput = await readIntegrationValidationBody(
3225
- request,
3226
- getIntegrationRouteBodyFormat(route2)
3227
- );
3228
- if (bodyInput.success) {
3229
- const bodyResult = await parseIntegrationInputSchema("body", schemas.body, bodyInput.data);
3230
- if (bodyResult.success) {
3231
- input.body = bodyResult.data;
3232
- } else {
3233
- issues.push(...bodyResult.issues);
3234
- }
3235
- } else {
3236
- issues.push(bodyInput.issue);
3237
- }
3238
- }
3239
- if (issues.length > 0) {
3240
- return {
3241
- success: false,
3242
- response: createIntegrationValidationResponse(issues)
3243
- };
3244
- }
3245
- return {
3246
- success: true,
3247
- input
3248
- };
3249
- }
3250
- __name(validateIntegrationRouteInput, "validateIntegrationRouteInput");
3251
- async function parseIntegrationInputSchema(source, schema, value) {
3252
- const parser = schema.safeParseAsync || schema.safeParse;
3253
- if (parser) {
3254
- const result = await parser.call(schema, value);
3255
- if (result.success) {
3256
- return {
3257
- success: true,
3258
- data: result.data
3259
- };
3260
- }
3261
- return {
3262
- success: false,
3263
- issues: normalizeIntegrationValidationIssues(source, result.error)
3264
- };
3265
- }
3266
- if (schema["~standard"]?.validate) {
3267
- const result = await schema["~standard"].validate(value);
3268
- if ("value" in result) {
3269
- return {
3270
- success: true,
3271
- data: result.value
3272
- };
3273
- }
3274
- return {
3275
- success: false,
3276
- issues: normalizeIntegrationValidationIssues(source, {
3277
- issues: result.issues
3278
- })
3279
- };
3280
- }
3281
- if (schema.parse) {
3282
- try {
3283
- return {
3284
- success: true,
3285
- data: await schema.parse(value)
3286
- };
3287
- } catch (error) {
3288
- return {
3289
- success: false,
3290
- issues: normalizeIntegrationValidationIssues(
3291
- source,
3292
- normalizeIntegrationValidationError(error)
3293
- )
3294
- };
3295
- }
3296
- }
3297
- return {
3298
- success: false,
3299
- issues: [
3300
- {
3301
- source,
3302
- message: "Input schema must expose safeParse, safeParseAsync, parse, or ~standard.validate."
3303
- }
3304
- ]
3305
- };
3306
- }
3307
- __name(parseIntegrationInputSchema, "parseIntegrationInputSchema");
3308
- function createIntegrationValidationResponse(issues) {
3309
- return Response.json(
3310
- {
3311
- error: "Integration route input validation failed",
3312
- issues
3313
- },
3314
- {
3315
- status: 400
3316
- }
3317
- );
3318
- }
3319
- __name(createIntegrationValidationResponse, "createIntegrationValidationResponse");
3320
- function normalizeIntegrationValidationIssues(source, error) {
3321
- if (Array.isArray(error.issues) && error.issues.length > 0) {
3322
- return error.issues.map((issue) => ({
3323
- source,
3324
- path: normalizeIntegrationValidationPath(issue.path),
3325
- code: issue.code,
3326
- message: issue.message || "Invalid input"
3327
- }));
3328
- }
3329
- return [
3330
- {
3331
- source,
3332
- path: [],
3333
- message: error.message || "Invalid input"
3334
- }
3335
- ];
3336
- }
3337
- __name(normalizeIntegrationValidationIssues, "normalizeIntegrationValidationIssues");
3338
- function normalizeIntegrationValidationPath(path) {
3339
- return (path || []).map((segment) => {
3340
- const key = typeof segment === "object" && segment !== null && "key" in segment ? segment.key : segment;
3341
- return typeof key === "symbol" ? key.description || key.toString() : key;
3342
- });
3343
- }
3344
- __name(normalizeIntegrationValidationPath, "normalizeIntegrationValidationPath");
3345
- function normalizeIntegrationValidationError(error) {
3346
- if (error && typeof error === "object") {
3347
- return error;
3348
- }
3349
- return {
3350
- message: error instanceof Error ? error.message : String(error || "Invalid input")
3351
- };
3352
- }
3353
- __name(normalizeIntegrationValidationError, "normalizeIntegrationValidationError");
3354
- async function readIntegrationValidationBody(request, format) {
3355
- if (request.method === "GET" || request.method === "HEAD" || format === "none") {
3356
- return {
3357
- success: true,
3358
- data: void 0
3359
- };
3360
- }
3361
- try {
3362
- if (format === "form") {
3363
- return {
3364
- success: true,
3365
- data: createFormInput(await request.clone().formData())
3366
- };
3367
- }
3368
- const text = await request.clone().text();
3369
- if (text.trim().length === 0) {
3370
- return {
3371
- success: true,
3372
- data: void 0
3373
- };
3374
- }
3375
- return {
3376
- success: true,
3377
- data: JSON.parse(text)
3378
- };
3379
- } catch (error) {
3380
- return {
3381
- success: false,
3382
- issue: {
3383
- source: "body",
3384
- path: [],
3385
- message: format === "json" ? "Expected a valid JSON request body." : error instanceof Error && error.message ? error.message : "Could not parse request body."
3386
- }
3387
- };
3388
- }
3389
- }
3390
- __name(readIntegrationValidationBody, "readIntegrationValidationBody");
3391
- function getIntegrationRouteBodyFormat(route2) {
3392
- return route2.bodyFormat || route2.__operation?.bodyFormat || "json";
3393
- }
3394
- __name(getIntegrationRouteBodyFormat, "getIntegrationRouteBodyFormat");
3395
- function createIntegrationRouteArgs(input) {
3396
- let clientPromise;
3397
- let ormPromise;
3398
- const getClient = /* @__PURE__ */ __name(() => {
3399
- clientPromise ?? (clientPromise = Promise.resolve().then(() => (init_storage(), storage_exports)).then(
3400
- ({ resolveStorageRuntimeClient: resolveStorageRuntimeClient2 }) => resolveStorageRuntimeClient2(input.config.storage)
3401
- ));
3402
- return clientPromise;
3403
- }, "getClient");
3404
- const getOrm = /* @__PURE__ */ __name(() => {
3405
- if (!input.integration.schema) {
3406
- throw new Error(
3407
- `Integration "${input.integration.type}" does not define a schema for ctx.args.db.`
3408
- );
3409
- }
3410
- ormPromise ?? (ormPromise = Promise.resolve().then(() => (init_integration_orm(), integration_orm_exports)).then(
3411
- ({ createIntegrationOrm: createIntegrationOrm2 }) => createIntegrationOrm2({
3412
- schema: input.integration.schema,
3413
- config: input.config
3414
- })
3415
- ));
3416
- return ormPromise;
3417
- }, "getOrm");
3418
- return {
3419
- db: createLazyIntegrationOrmClient(getOrm),
3420
- getDb: getOrm,
3421
- storage: {
3422
- getClient,
3423
- getOrm
3424
- }
3425
- };
3426
- }
3427
- __name(createIntegrationRouteArgs, "createIntegrationRouteArgs");
3428
- function createLazyIntegrationOrmClient(resolveOrm) {
3429
- const modelProxyCache = /* @__PURE__ */ new Map();
3430
- return new Proxy(
3431
- {},
3432
- {
3433
- get(_target, prop) {
3434
- if (prop === "then") {
3435
- return void 0;
3436
- }
3437
- if (prop === "transaction" || prop === "batch") {
3438
- return async (...args) => {
3439
- const orm = await resolveOrm();
3440
- const member = orm[prop];
3441
- if (typeof member !== "function") {
3442
- throw new Error(`Integration ORM does not expose "${String(prop)}".`);
3443
- }
3444
- return member.apply(orm, args);
3445
- };
3446
- }
3447
- if (prop === "$driver") {
3448
- return void 0;
3449
- }
3450
- if (!modelProxyCache.has(prop)) {
3451
- modelProxyCache.set(prop, createLazyIntegrationOrmModel(resolveOrm, prop));
3452
- }
3453
- return modelProxyCache.get(prop);
3454
- }
3455
- }
3456
- );
3457
- }
3458
- __name(createLazyIntegrationOrmClient, "createLazyIntegrationOrmClient");
3459
- function createLazyIntegrationOrmModel(resolveOrm, modelName) {
3460
- return new Proxy(
3461
- {},
3462
- {
3463
- get(_target, prop) {
3464
- if (prop === "then") {
3465
- return void 0;
3466
- }
3467
- return async (...args) => {
3468
- const orm = await resolveOrm();
3469
- const model = orm[modelName];
3470
- const member = model?.[prop];
3471
- if (typeof member !== "function") {
3472
- throw new Error(
3473
- `Integration ORM model "${String(modelName)}" does not expose "${String(prop)}".`
3474
- );
3475
- }
3476
- return member.apply(model, args);
3477
- };
3478
- }
3479
- }
3480
- );
3481
- }
3482
- __name(createLazyIntegrationOrmModel, "createLazyIntegrationOrmModel");
3483
- async function runIntegrationRouteBeforeHooks(route2, request, context) {
3484
- const hookContext = context;
3485
- hookContext.response = void 0;
3486
- for (const hook of route2.before || []) {
3487
- const response = await hook(request, hookContext);
3488
- if (response) {
3489
- hookContext.response = response;
3490
- return response;
3491
- }
3492
- if (hookContext.response) {
3493
- return hookContext.response;
3494
- }
3495
- }
3496
- return void 0;
3497
- }
3498
- __name(runIntegrationRouteBeforeHooks, "runIntegrationRouteBeforeHooks");
3499
- async function runIntegrationRouteAfterHooks(route2, request, context, response) {
3500
- const hookContext = context;
3501
- let currentResponse = response;
3502
- for (const hook of route2.after || []) {
3503
- hookContext.response = currentResponse;
3504
- const nextResponse = await hook(request, hookContext);
3505
- currentResponse = nextResponse || hookContext.response || currentResponse;
3506
- }
3507
- hookContext.response = currentResponse;
3508
- return currentResponse;
3509
- }
3510
- __name(runIntegrationRouteAfterHooks, "runIntegrationRouteAfterHooks");
3511
- function createQueryInput(searchParams) {
3512
- const input = {};
3513
- searchParams.forEach((value, key) => {
3514
- if (key === "__proto__" || key === "constructor" || key === "prototype") return;
3515
- const existing = input[key];
3516
- if (existing === void 0) {
3517
- input[key] = value;
3518
- return;
3519
- }
3520
- input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];
3521
- });
3522
- return input;
3523
- }
3524
- __name(createQueryInput, "createQueryInput");
3525
- function createFormInput(formData) {
3526
- const input = {};
3527
- formData.forEach((value, key) => {
3528
- if (key === "__proto__" || key === "constructor" || key === "prototype") return;
3529
- const existing = input[key];
3530
- if (existing === void 0) {
3531
- input[key] = value;
3532
- return;
3533
- }
3534
- input[key] = Array.isArray(existing) ? [...existing, value] : [existing, value];
3535
- });
3536
- return input;
3537
- }
3538
- __name(createFormInput, "createFormInput");
3539
- async function dispatchIntegrationRequest(runtime, request, options = {}) {
3540
- try {
3541
- request = await bufferFarmRequestBody(
3542
- request,
3543
- resolveFarmServerConfig(runtime.config.server).bodySizeLimit
3544
- );
3545
- } catch (error) {
3546
- const response = createFarmRequestBodyErrorResponse(error);
3547
- if (response) return response;
3548
- throw error;
3549
- }
3550
- const integration = runtime.integration;
3551
- const url = new URL(request.url);
3552
- const pathname = url.pathname;
3553
- const requestId = request.headers.get("x-request-id") || options.currentRequest?.headers.get("x-request-id") || String(Date.now());
3554
- const routes = normalizeIntegrationRoutes(integration.routes || []);
3555
- const pathSegments = canonicalizeRequestPathSegments(pathname);
3556
- const method = normalizeIntegrationRequestMethod(request.method);
3557
- const middleware = [...integration.middleware || []];
3558
- const forwardedSetCookies = [];
3559
- for (const entry of middleware) {
3560
- const params = resolveMatcherParams(entry.matcher, pathname);
3561
- if (!params) {
3562
- continue;
3563
- }
3564
- const handlerContext = createServerIntegrationHandlerContext({
3565
- runtime,
3566
- route: {
3567
- kind: "middleware",
3568
- path: normalizeMatcher(entry.matcher),
3569
- methods: ["ALL"]
3570
- },
3571
- request,
3572
- params,
3573
- pathname,
3574
- requestId,
3575
- currentRequest: options.currentRequest,
3576
- data: options.data,
3577
- internal: options.internal === true
3578
- });
3579
- const startedAt = Date.now();
3580
- await emitIntegrationLog(integration, {
3581
- category: integration.category,
3582
- slot: integration.category,
3583
- type: integration.type,
3584
- phase: "request:start",
3585
- route: {
3586
- kind: "middleware",
3587
- path: normalizeMatcher(entry.matcher),
3588
- methods: ["ALL"]
3589
- },
3590
- request,
3591
- requestId,
3592
- context: handlerContext.req.snapshot()
3593
- });
3594
- try {
3595
- const response = await entry.handler(request, handlerContext);
3596
- forwardedSetCookies.push(...takeForwardedIntegrationSetCookies(handlerContext));
3597
- if (response) {
3598
- await emitIntegrationLog(integration, {
3599
- category: integration.category,
3600
- slot: integration.category,
3601
- type: integration.type,
3602
- phase: "request:end",
3603
- route: {
3604
- kind: "middleware",
3605
- path: normalizeMatcher(entry.matcher),
3606
- methods: ["ALL"]
3607
- },
3608
- request,
3609
- response,
3610
- requestId,
3611
- durationMs: Date.now() - startedAt,
3612
- context: handlerContext.req.snapshot()
3613
- });
3614
- return appendIntegrationForwardedCookies(response, forwardedSetCookies);
3615
- }
3616
- await emitIntegrationLog(integration, {
3617
- category: integration.category,
3618
- slot: integration.category,
3619
- type: integration.type,
3620
- phase: "request:end",
3621
- route: {
3622
- kind: "middleware",
3623
- path: normalizeMatcher(entry.matcher),
3624
- methods: ["ALL"]
3625
- },
3626
- request,
3627
- requestId,
3628
- durationMs: Date.now() - startedAt,
3629
- context: handlerContext.req.snapshot()
3630
- });
3631
- } catch (error) {
3632
- await emitIntegrationLog(integration, {
3633
- category: integration.category,
3634
- slot: integration.category,
3635
- type: integration.type,
3636
- phase: "request:error",
3637
- route: {
3638
- kind: "middleware",
3639
- path: normalizeMatcher(entry.matcher),
3640
- methods: ["ALL"]
3641
- },
3642
- request,
3643
- requestId,
3644
- durationMs: Date.now() - startedAt,
3645
- error,
3646
- context: handlerContext.req.snapshot()
3647
- });
3648
- throw error;
3649
- }
3650
- }
3651
- for (const route2 of routes) {
3652
- const params = method && matchesMethod(route2.methods, method) ? matchPathSegments(route2[INTEGRATION_ROUTE_SEGMENTS], pathSegments) : null;
3653
- if (!params) {
3654
- continue;
3655
- }
3656
- const handlerContext = createServerIntegrationHandlerContext({
3657
- runtime,
3658
- route: {
3659
- kind: "route",
3660
- path: route2.path,
3661
- methods: route2.methods
3662
- },
3663
- request,
3664
- params,
3665
- pathname,
3666
- requestId,
3667
- currentRequest: options.currentRequest,
3668
- data: options.data,
3669
- internal: options.internal === true
3670
- });
3671
- const startedAt = Date.now();
3672
- await emitIntegrationLog(integration, {
3673
- category: integration.category,
3674
- slot: integration.category,
3675
- type: integration.type,
3676
- phase: "request:start",
3677
- route: {
3678
- kind: "route",
3679
- path: route2.path,
3680
- methods: route2.methods
3681
- },
3682
- request,
3683
- requestId,
3684
- context: handlerContext.req.snapshot()
3685
- });
3686
- try {
3687
- const validation = await validateIntegrationRouteInput(route2, request, url);
3688
- if (!validation.success) {
3689
- await emitIntegrationLog(integration, {
3690
- category: integration.category,
3691
- slot: integration.category,
3692
- type: integration.type,
3693
- phase: "request:end",
3694
- route: {
3695
- kind: "route",
3696
- path: route2.path,
3697
- methods: route2.methods
3698
- },
3699
- request,
3700
- response: validation.response,
3701
- requestId,
3702
- durationMs: Date.now() - startedAt,
3703
- context: handlerContext.req.snapshot()
3704
- });
3705
- return appendIntegrationForwardedCookies(validation.response, forwardedSetCookies);
3706
- }
3707
- handlerContext.input = validation.input;
3708
- for (const middlewareEntry of route2.middleware || []) {
3709
- const middlewareResponse = await middlewareEntry.handler(request, handlerContext);
3710
- forwardedSetCookies.push(...takeForwardedIntegrationSetCookies(handlerContext));
3711
- if (middlewareResponse) {
3712
- await emitIntegrationLog(integration, {
3713
- category: integration.category,
3714
- slot: integration.category,
3715
- type: integration.type,
3716
- phase: "request:end",
3717
- route: {
3718
- kind: "route",
3719
- path: route2.path,
3720
- methods: route2.methods
3721
- },
3722
- request,
3723
- response: middlewareResponse,
3724
- requestId,
3725
- durationMs: Date.now() - startedAt,
3726
- context: handlerContext.req.snapshot()
3727
- });
3728
- return appendIntegrationForwardedCookies(middlewareResponse, forwardedSetCookies);
3729
- }
3730
- }
3731
- const beforeResponse = await runIntegrationRouteBeforeHooks(route2, request, handlerContext);
3732
- if (beforeResponse) {
3733
- const response2 = await runIntegrationRouteAfterHooks(
3734
- route2,
3735
- request,
3736
- handlerContext,
3737
- beforeResponse
3738
- );
3739
- await emitIntegrationLog(integration, {
3740
- category: integration.category,
3741
- slot: integration.category,
3742
- type: integration.type,
3743
- phase: "request:end",
3744
- route: {
3745
- kind: "route",
3746
- path: route2.path,
3747
- methods: route2.methods
3748
- },
3749
- request,
3750
- response: response2,
3751
- requestId,
3752
- durationMs: Date.now() - startedAt,
3753
- context: handlerContext.req.snapshot()
3754
- });
3755
- return appendIntegrationForwardedCookies(response2, forwardedSetCookies);
3756
- }
3757
- const handlerResponse = await route2.handler(request, handlerContext);
3758
- const response = await runIntegrationRouteAfterHooks(
3759
- route2,
3760
- request,
3761
- handlerContext,
3762
- handlerResponse
3763
- );
3764
- await emitIntegrationLog(integration, {
3765
- category: integration.category,
3766
- slot: integration.category,
3767
- type: integration.type,
3768
- phase: "request:end",
3769
- route: {
3770
- kind: "route",
3771
- path: route2.path,
3772
- methods: route2.methods
3773
- },
3774
- request,
3775
- response,
3776
- requestId,
3777
- durationMs: Date.now() - startedAt,
3778
- context: handlerContext.req.snapshot()
3779
- });
3780
- return appendIntegrationForwardedCookies(response, forwardedSetCookies);
3781
- } catch (error) {
3782
- await emitIntegrationLog(integration, {
3783
- category: integration.category,
3784
- slot: integration.category,
3785
- type: integration.type,
3786
- phase: "request:error",
3787
- route: {
3788
- kind: "route",
3789
- path: route2.path,
3790
- methods: route2.methods
3791
- },
3792
- request,
3793
- requestId,
3794
- durationMs: Date.now() - startedAt,
3795
- error,
3796
- context: handlerContext.req.snapshot()
3797
- });
3798
- throw error;
3799
- }
3800
- }
3801
- if (forwardedSetCookies.length > 0) {
3802
- options.onForwardedCookies?.(forwardedSetCookies);
3803
- }
3804
- return null;
3805
- }
3806
- __name(dispatchIntegrationRequest, "dispatchIntegrationRequest");
3807
- async function dispatchIntegrationRequests(integrations, runtime, request, options = {}) {
3808
- const setCookies = [];
3809
- if (!integrations) {
3810
- return { response: null, setCookies };
3811
- }
3812
- for (const integration of Object.values(integrations)) {
3813
- if (!integration || !isFarmIntegration(integration)) {
3814
- continue;
3815
- }
3816
- const hasMiddleware = (integration.middleware || []).length > 0;
3817
- const hasRoutes = normalizeIntegrationRoutes(integration.routes || []).length > 0;
3818
- if (!hasMiddleware && !hasRoutes) {
3819
- continue;
3820
- }
3821
- const response = await dispatchIntegrationRequest(
3822
- { ...runtime, integration },
3823
- // Each dispatch buffers the body it is given, so hand every integration
3824
- // its own clone rather than a Request another dispatch already read.
3825
- request.clone(),
3826
- {
3827
- currentRequest: options.currentRequest,
3828
- onForwardedCookies: /* @__PURE__ */ __name((cookies) => setCookies.push(...cookies), "onForwardedCookies")
3829
- }
3830
- );
3831
- if (response) {
3832
- return {
3833
- response: appendIntegrationForwardedCookies(response, setCookies),
3834
- setCookies: []
3835
- };
3836
- }
3837
- }
3838
- return { response: null, setCookies };
3839
- }
3840
- __name(dispatchIntegrationRequests, "dispatchIntegrationRequests");
3841
- globalThis[INTEGRATION_REQUEST_DISPATCHER_KEY] = dispatchIntegrationRequest;
3842
- function createIntegrationRequestContextStore(rawRequest, request, pluginContext) {
3843
- return {
3844
- get(key) {
3845
- const requestValue = pluginContext.requestContext.get(request, key);
3846
- if (requestValue !== void 0) {
3847
- return requestValue;
3848
- }
3849
- return pluginContext.requestContext.get(rawRequest, key);
3850
- },
3851
- set(key, value, options) {
3852
- pluginContext.requestContext.set(rawRequest, key, value, options);
3853
- pluginContext.requestContext.set(request, key, value, options);
3854
- },
3855
- has(key) {
3856
- return pluginContext.requestContext.has(request, key) || pluginContext.requestContext.has(rawRequest, key);
3857
- },
3858
- delete(key) {
3859
- const deletedRequest = pluginContext.requestContext.delete(request, key);
3860
- const deletedRaw = pluginContext.requestContext.delete(rawRequest, key);
3861
- return deletedRequest || deletedRaw;
3862
- },
3863
- clear() {
3864
- pluginContext.requestContext.clear(rawRequest);
3865
- pluginContext.requestContext.clear(request);
3866
- },
3867
- snapshot(options) {
3868
- const merged = pluginContext.requestContext.getAll(rawRequest, options);
3869
- const requestSnapshot = pluginContext.requestContext.getAll(request, options);
3870
- for (const [key, value] of requestSnapshot) {
3871
- merged.set(key, value);
3872
- }
3873
- return merged;
3874
- }
3875
- };
3876
- }
3877
- __name(createIntegrationRequestContextStore, "createIntegrationRequestContextStore");
3878
- function createServerIntegrationHandlerContext(input) {
3879
- const req = createServerIntegrationRequestContextStore(input.request, input.currentRequest);
3880
- if (input.internal) {
3881
- req.set(FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY, true);
3882
- }
3883
- return {
3884
- request: input.request,
3885
- requestId: input.requestId,
3886
- url: new URL(input.request.url),
3887
- pathname: input.pathname,
3888
- method: input.request.method,
3889
- params: input.params,
3890
- input: {},
3891
- args: createIntegrationRouteArgs({
3892
- integration: input.runtime.integration,
3893
- config: input.runtime.config
3894
- }),
3895
- data: resolveIntegrationData(input.request, input.data),
3896
- integration: {
3897
- category: input.runtime.integration.category,
3898
- slot: input.runtime.integration.category,
3899
- type: input.runtime.integration.type,
3900
- instance: input.runtime.integration.instance
3901
- },
3902
- route: input.route,
3903
- req,
3904
- requestContext: req,
3905
- config: input.runtime.config,
3906
- isDev: input.runtime.isDev,
3907
- isProd: input.runtime.isProd
3908
- };
3909
- }
3910
- __name(createServerIntegrationHandlerContext, "createServerIntegrationHandlerContext");
3911
- function createServerIntegrationRequestContextStore(request, currentRequest) {
3912
- return {
3913
- get(key) {
3914
- const requestValue = getRequestContext(request, key);
3915
- if (requestValue !== void 0) {
3916
- return requestValue;
3917
- }
3918
- if (currentRequest) {
3919
- return getRequestContext(currentRequest, key);
3920
- }
3921
- return void 0;
3922
- },
3923
- set(key, value, options) {
3924
- setRequestContext(request, key, value, options);
3925
- if (currentRequest) {
3926
- setRequestContext(currentRequest, key, value, options);
3927
- }
3928
- },
3929
- has(key) {
3930
- return hasRequestContext(request, key) || !!currentRequest && hasRequestContext(currentRequest, key);
3931
- },
3932
- delete(key) {
3933
- const deletedRequest = deleteRequestContext(request, key);
3934
- const deletedCurrent = currentRequest ? deleteRequestContext(currentRequest, key) : false;
3935
- return deletedRequest || deletedCurrent;
3936
- },
3937
- clear() {
3938
- clearRequestContext(request);
3939
- if (currentRequest) {
3940
- clearRequestContext(currentRequest);
3941
- }
3942
- },
3943
- snapshot(options) {
3944
- const merged = currentRequest ? getRequestContextSnapshot(currentRequest, options) : /* @__PURE__ */ new Map();
3945
- const requestSnapshot = getRequestContextSnapshot(request, options);
3946
- for (const [key, value] of requestSnapshot) {
3947
- merged.set(key, value);
3948
- }
3949
- return merged;
3950
- }
3951
- };
3952
- }
3953
- __name(createServerIntegrationRequestContextStore, "createServerIntegrationRequestContextStore");
3954
- function createWebRequest(req, fullUrl, body) {
3955
- const headers = new Headers();
3956
- for (const [key, value] of Object.entries(req.headers)) {
3957
- if (value == null) {
3958
- continue;
3959
- }
3960
- if (Array.isArray(value)) {
3961
- for (const item of value) {
3962
- headers.append(key, item);
3963
- }
3964
- continue;
3965
- }
3966
- headers.set(key, value);
3967
- }
3968
- return new Request(fullUrl, {
3969
- method: req.method,
3970
- headers,
3971
- body
3972
- });
3973
- }
3974
- __name(createWebRequest, "createWebRequest");
3975
- function normalizeIntegrationRequestMethod(method) {
3976
- return method ? method.toUpperCase() : void 0;
3977
- }
3978
- __name(normalizeIntegrationRequestMethod, "normalizeIntegrationRequestMethod");
3979
- function matchesMethod(methods, normalizedMethod) {
3980
- return methods.some((candidate) => candidate === "ALL" || candidate === normalizedMethod);
3981
- }
3982
- __name(matchesMethod, "matchesMethod");
3983
- function resolveMatcherParams(matcher, pathname) {
3984
- if (!matcher) {
3985
- return {};
3986
- }
3987
- const list = Array.isArray(matcher) ? matcher : [matcher];
3988
- let canonicalPathname;
3989
- let canonicalSegments;
3990
- for (const item of list) {
3991
- if (item === "/(.*)" || item === "*") {
3992
- return {};
3993
- }
3994
- if (item.endsWith("(.*)")) {
3995
- canonicalPathname ?? (canonicalPathname = canonicalizeRequestPathname(pathname));
3996
- const prefix = item.slice(0, -4);
3997
- if (canonicalPathname === prefix || canonicalPathname.startsWith(`${prefix}/`)) {
3998
- return {};
3999
- }
4000
- continue;
4001
- }
4002
- canonicalSegments ?? (canonicalSegments = canonicalizeRequestPathSegments(pathname));
4003
- const params = matchPathSegments(splitPath(item), canonicalSegments);
4004
- if (params) {
4005
- return params;
4006
- }
4007
- }
4008
- return null;
4009
- }
4010
- __name(resolveMatcherParams, "resolveMatcherParams");
4011
- function matchPathSegments(routeSegments, pathSegments) {
4012
- const params = {};
4013
- let routeIndex = 0;
4014
- let pathIndex = 0;
4015
- while (routeIndex < routeSegments.length && pathIndex < pathSegments.length) {
4016
- const routeSegment = routeSegments[routeIndex];
4017
- const pathSegment = pathSegments[pathIndex];
4018
- if (isCatchAllSegment(routeSegment)) {
4019
- params[getSegmentParamName(routeSegment)] = pathSegments.slice(pathIndex);
4020
- return params;
4021
- }
4022
- if (isDynamicSegment(routeSegment)) {
4023
- params[getSegmentParamName(routeSegment)] = pathSegment;
4024
- routeIndex += 1;
4025
- pathIndex += 1;
4026
- continue;
4027
- }
4028
- if (routeSegment !== pathSegment) {
4029
- return null;
4030
- }
4031
- routeIndex += 1;
4032
- pathIndex += 1;
4033
- }
4034
- if (routeIndex === routeSegments.length && pathIndex === pathSegments.length) {
4035
- return params;
4036
- }
4037
- if (routeIndex === routeSegments.length - 1 && isCatchAllSegment(routeSegments[routeIndex])) {
4038
- params[getSegmentParamName(routeSegments[routeIndex])] = [];
4039
- return params;
4040
- }
4041
- return null;
4042
- }
4043
- __name(matchPathSegments, "matchPathSegments");
4044
- function splitPath(value) {
4045
- return value.split("/").filter(Boolean);
4046
- }
4047
- __name(splitPath, "splitPath");
4048
- function isDynamicSegment(segment) {
4049
- return segment.startsWith("[") && segment.endsWith("]");
4050
- }
4051
- __name(isDynamicSegment, "isDynamicSegment");
4052
- function isCatchAllSegment(segment) {
4053
- return segment.startsWith("[...") && segment.endsWith("]");
4054
- }
4055
- __name(isCatchAllSegment, "isCatchAllSegment");
4056
- function getSegmentParamName(segment) {
4057
- if (isCatchAllSegment(segment)) {
4058
- return segment.slice(4, -1);
4059
- }
4060
- return segment.slice(1, -1);
4061
- }
4062
- __name(getSegmentParamName, "getSegmentParamName");
4063
- function getRequestId(req) {
4064
- const headerValue = req.headers["x-request-id"];
4065
- if (Array.isArray(headerValue)) {
4066
- return headerValue[0] || String(Date.now());
4067
- }
4068
- return headerValue || String(Date.now());
4069
- }
4070
- __name(getRequestId, "getRequestId");
4071
- function normalizeMatcher(matcher) {
4072
- if (!matcher) {
4073
- return "/(.*)";
4074
- }
4075
- return typeof matcher === "string" ? matcher : matcher.join(", ");
4076
- }
4077
- __name(normalizeMatcher, "normalizeMatcher");
4078
- // Annotate the CommonJS export names for ESM import in node:
4079
- 0 && (module.exports = {
4080
- FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY,
4081
- FARM_INTEGRATION_SET_COOKIES_KEY,
4082
- api,
4083
- createIntegrationRoute,
4084
- defineIntegration,
4085
- defineIntegrationAPI,
4086
- defineIntegrationAPIOperation,
4087
- defineIntegrationSchema,
4088
- describeIntegrationOriginRejection,
4089
- dispatchIntegrationRequest,
4090
- dispatchIntegrationRequests,
4091
- forwardIntegrationSetCookies,
4092
- getFarmIntegrationPluginOwner,
4093
- getFarmIntegrationPluginServerRuntime,
4094
- getIntegrationDocumentNavigationMatchers,
4095
- getIntegrationProviders,
4096
- getIntegrationSchemas,
4097
- getRegisteredIntegrationAPIManifest,
4098
- getRegisteredIntegrationRuntime,
4099
- getRegisteredIntegrationSchemas,
4100
- getRegisteredIntegrations,
4101
- integrationRoute,
4102
- isFarmIntegration,
4103
- isFarmIntegrationProviderComponentReference,
4104
- matchIntegrationRoute,
4105
- matchRegisteredIntegrationRoute,
4106
- resolveIntegrationAllowedOrigins,
4107
- resolveIntegrationPlugins,
4108
- validateIntegrationRequestOrigin
4109
- });
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+ var _chunkZ5HIWVDPcjs = require('./chunk-Z5HIWVDP.cjs');
29
+ require('./chunk-SVRTJOUF.cjs');
30
+ require('./chunk-G643DQCH.cjs');
31
+ require('./chunk-EM6SBQKM.cjs');
32
+ require('./chunk-UQZ4AYTH.cjs');
33
+
34
+
35
+
36
+
37
+ var _chunkNZKJGRB3cjs = require('./chunk-NZKJGRB3.cjs');
38
+ require('./chunk-DVM4FKZL.cjs');
39
+ require('./chunk-US2QVW3E.cjs');
40
+ require('./chunk-BIDYX3SL.cjs');
41
+ require('./chunk-I57LW5VZ.cjs');
42
+ require('./chunk-NO3WWW3N.cjs');
43
+ require('./chunk-S3JO3N4H.cjs');
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+ exports.FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY = _chunkZ5HIWVDPcjs.FARM_INTEGRATION_INTERNAL_DISPATCH_CONTEXT_KEY; exports.FARM_INTEGRATION_SET_COOKIES_KEY = _chunkZ5HIWVDPcjs.FARM_INTEGRATION_SET_COOKIES_KEY; exports.api = _chunkNZKJGRB3cjs.api; exports.createIntegrationRoute = _chunkZ5HIWVDPcjs.createIntegrationRoute; exports.defineIntegration = _chunkZ5HIWVDPcjs.defineIntegration; exports.defineIntegrationAPI = _chunkNZKJGRB3cjs.defineIntegrationAPI; exports.defineIntegrationAPIOperation = _chunkNZKJGRB3cjs.defineIntegrationAPIOperation; exports.defineIntegrationSchema = _chunkZ5HIWVDPcjs.defineIntegrationSchema; exports.describeIntegrationOriginRejection = _chunkZ5HIWVDPcjs.describeIntegrationOriginRejection; exports.dispatchIntegrationRequest = _chunkZ5HIWVDPcjs.dispatchIntegrationRequest; exports.dispatchIntegrationRequests = _chunkZ5HIWVDPcjs.dispatchIntegrationRequests; exports.forwardIntegrationSetCookies = _chunkZ5HIWVDPcjs.forwardIntegrationSetCookies; exports.getFarmIntegrationPluginOwner = _chunkZ5HIWVDPcjs.getFarmIntegrationPluginOwner; exports.getFarmIntegrationPluginServerRuntime = _chunkZ5HIWVDPcjs.getFarmIntegrationPluginServerRuntime; exports.getIntegrationDocumentNavigationMatchers = _chunkZ5HIWVDPcjs.getIntegrationDocumentNavigationMatchers; exports.getIntegrationProviders = _chunkZ5HIWVDPcjs.getIntegrationProviders; exports.getIntegrationSchemas = _chunkZ5HIWVDPcjs.getIntegrationSchemas; exports.getRegisteredIntegrationAPIManifest = _chunkZ5HIWVDPcjs.getRegisteredIntegrationAPIManifest; exports.getRegisteredIntegrationRuntime = _chunkZ5HIWVDPcjs.getRegisteredIntegrationRuntime; exports.getRegisteredIntegrationSchemas = _chunkZ5HIWVDPcjs.getRegisteredIntegrationSchemas; exports.getRegisteredIntegrations = _chunkZ5HIWVDPcjs.getRegisteredIntegrations; exports.integrationRoute = _chunkZ5HIWVDPcjs.integrationRoute; exports.isFarmIntegration = _chunkZ5HIWVDPcjs.isFarmIntegration; exports.isFarmIntegrationProviderComponentReference = _chunkZ5HIWVDPcjs.isFarmIntegrationProviderComponentReference; exports.matchIntegrationRoute = _chunkZ5HIWVDPcjs.matchIntegrationRoute; exports.matchRegisteredIntegrationRoute = _chunkZ5HIWVDPcjs.matchRegisteredIntegrationRoute; exports.resolveIntegrationAllowedOrigins = _chunkZ5HIWVDPcjs.resolveIntegrationAllowedOrigins; exports.resolveIntegrationPlugins = _chunkZ5HIWVDPcjs.resolveIntegrationPlugins; exports.validateIntegrationRequestOrigin = _chunkZ5HIWVDPcjs.validateIntegrationRequestOrigin;