devflare 1.0.0-next.39 → 1.0.0-next.40

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 (277) hide show
  1. package/dist/_chunks/account-BtWcv3X9.js +462 -0
  2. package/dist/_chunks/account-resources-CsmVowJp.js +159 -0
  3. package/dist/_chunks/ai-CBEuLdoP.js +322 -0
  4. package/dist/_chunks/api-TzdliH-6.js +568 -0
  5. package/dist/_chunks/build-3T6O4uIg.js +24 -0
  6. package/dist/_chunks/build-artifacts-8TqBSQkG.js +483 -0
  7. package/dist/_chunks/cli-BTF1X4SG.js +1128 -0
  8. package/dist/_chunks/cloudflare-BaloqI3H.js +157 -0
  9. package/dist/_chunks/colors-DiK6wPJ5.js +13 -0
  10. package/dist/_chunks/command-utils-BsfkmTqh.js +45 -0
  11. package/dist/_chunks/compiler-uoyAQ8zW.js +424 -0
  12. package/dist/_chunks/config-D5u-bEkn.js +78 -0
  13. package/dist/_chunks/config-path-DCPto4XB.js +42 -0
  14. package/dist/_chunks/context-CX50Y2Kb.js +2250 -0
  15. package/dist/_chunks/decorators-QmV57ixr.js +19 -0
  16. package/dist/_chunks/dependencies-C2oxFjU_.js +57 -0
  17. package/dist/_chunks/deploy-DMTr6JeR.js +915 -0
  18. package/dist/_chunks/dev-CvRHmRFZ.js +3456 -0
  19. package/dist/_chunks/doctor-DIG8DoFU.js +219 -0
  20. package/dist/_chunks/durable-object-DMtH0XYX.js +234 -0
  21. package/dist/_chunks/env-S0_nMVz1.js +125 -0
  22. package/dist/_chunks/family-DXC5SdFK.js +143 -0
  23. package/dist/_chunks/generated-artifacts-dMJY4KAt.js +32 -0
  24. package/dist/_chunks/glob-CmQOvunB.js +56 -0
  25. package/dist/_chunks/init-3moXTgpb.js +165 -0
  26. package/dist/_chunks/loader-DLXO60RO.js +1153 -0
  27. package/dist/_chunks/local-dev-vars-CTSa-wvF.js +81 -0
  28. package/dist/_chunks/local-hyperdrive-CJ90j46O.js +119 -0
  29. package/dist/_chunks/local-media-bindings-DsAW4AMF.js +335 -0
  30. package/dist/_chunks/local-secrets-DMmEOygL.js +123 -0
  31. package/dist/_chunks/local-workflow-entrypoints-Wip3o1u8.js +90 -0
  32. package/dist/_chunks/login-BmnDzDlH.js +51 -0
  33. package/dist/_chunks/package-metadata-DAuCkyvK.js +39 -0
  34. package/dist/_chunks/preferences-BKp_7XJx.js +241 -0
  35. package/dist/_chunks/preview-BhqDmq8I.js +456 -0
  36. package/dist/_chunks/preview-registry-ClAbLTHH.js +1186 -0
  37. package/dist/_chunks/preview-resources-DdXj8LMM.js +358 -0
  38. package/dist/_chunks/previews-Dlr13x5M.js +1134 -0
  39. package/dist/_chunks/productions-D3AnOHac.js +411 -0
  40. package/dist/_chunks/ref-CYJNAAe_.js +178 -0
  41. package/dist/_chunks/remote-CZnP-HLJ.js +79 -0
  42. package/dist/_chunks/remote-config-D39BY9ji.js +132 -0
  43. package/dist/_chunks/resolve-package-Y84HB3Nt.js +133 -0
  44. package/dist/_chunks/rolldown-runtime-CvQ6eiug.js +14 -0
  45. package/dist/_chunks/routes-C3FqES2W.js +796 -0
  46. package/dist/_chunks/runtime-FvXvfuZ2.js +550 -0
  47. package/dist/_chunks/schema-normalization-DWVleVxo.js +477 -0
  48. package/dist/_chunks/secrets-70eN0Q6C.js +95 -0
  49. package/dist/_chunks/token-kguIDmej.js +333 -0
  50. package/dist/_chunks/tokens-iVcgNXi-.js +221 -0
  51. package/dist/_chunks/types-OrLbzv4I.js +476 -0
  52. package/dist/_chunks/ui-BUoZApvE.js +103 -0
  53. package/dist/_chunks/usage-BBTGzjon.js +272 -0
  54. package/dist/_chunks/vite-CsI0E-uV.js +1235 -0
  55. package/dist/_chunks/vite-utils-OVLMV605.js +183 -0
  56. package/dist/_chunks/worker-CS1jgNFE.js +410 -0
  57. package/dist/_chunks/worker-bundler-dTTnYU3n.js +458 -0
  58. package/dist/_chunks/worker-entrypoint-CQW77lG8.js +247 -0
  59. package/dist/_chunks/workerName-CFJsLZA-.js +23 -0
  60. package/dist/bridge/index.d.ts +6 -6
  61. package/dist/bridge/miniflare.d.ts +2 -2
  62. package/dist/bridge/proxy.d.ts +1 -1
  63. package/dist/bridge/v2/body-streams.d.ts +1 -1
  64. package/dist/bridge/v2/codec.d.ts +4 -4
  65. package/dist/bridge/v2/index.d.ts +10 -10
  66. package/dist/bridge/v2/serialization.d.ts +1 -1
  67. package/dist/bridge/v2/value-codec.d.ts +1 -1
  68. package/dist/bridge/v2/value-serialization.d.ts.map +1 -1
  69. package/dist/bridge/v2/ws-relay.d.ts +3 -3
  70. package/dist/browser-shim/index.d.ts +2 -2
  71. package/dist/browser.d.ts +70 -70
  72. package/dist/browser.js +74 -2462
  73. package/dist/bundler/do-bundler.d.ts +1 -1
  74. package/dist/bundler/index.d.ts +3 -3
  75. package/dist/bundler/rolldown-shared.d.ts +1 -1
  76. package/dist/bundler/worker-bundler.d.ts +1 -1
  77. package/dist/cli/build-manifest.d.ts +1 -1
  78. package/dist/cli/command-utils.d.ts +1 -1
  79. package/dist/cli/commands/account.d.ts +1 -1
  80. package/dist/cli/commands/ai.d.ts +1 -1
  81. package/dist/cli/commands/build-artifacts.d.ts +5 -5
  82. package/dist/cli/commands/build.d.ts +1 -1
  83. package/dist/cli/commands/config.d.ts +1 -1
  84. package/dist/cli/commands/deploy/prepare.d.ts +2 -2
  85. package/dist/cli/commands/deploy/runtime.d.ts +1 -1
  86. package/dist/cli/commands/deploy/verification.d.ts +1 -1
  87. package/dist/cli/commands/deploy.d.ts +1 -1
  88. package/dist/cli/commands/dev.d.ts +1 -1
  89. package/dist/cli/commands/doctor.d.ts +1 -1
  90. package/dist/cli/commands/init.d.ts +1 -1
  91. package/dist/cli/commands/login.d.ts +1 -1
  92. package/dist/cli/commands/previews-support/cleanup.d.ts +1 -1
  93. package/dist/cli/commands/previews-support/family.d.ts +3 -3
  94. package/dist/cli/commands/previews-support/render.d.ts +3 -3
  95. package/dist/cli/commands/previews-support/theme.d.ts +2 -2
  96. package/dist/cli/commands/previews-support/types.d.ts +2 -2
  97. package/dist/cli/commands/previews.d.ts +1 -1
  98. package/dist/cli/commands/productions.d.ts +1 -1
  99. package/dist/cli/commands/remote.d.ts +1 -1
  100. package/dist/cli/commands/secrets.d.ts +1 -1
  101. package/dist/cli/commands/token.d.ts +1 -1
  102. package/dist/cli/commands/type-generation/discovery.d.ts +2 -2
  103. package/dist/cli/commands/type-generation/generator.d.ts +3 -3
  104. package/dist/cli/commands/type-generation/models.d.ts +1 -1
  105. package/dist/cli/commands/types.d.ts +1 -1
  106. package/dist/cli/commands/worker.d.ts +1 -1
  107. package/dist/cli/deploy-strategy.d.ts +1 -1
  108. package/dist/cli/deploy-target.d.ts +1 -1
  109. package/dist/cli/help-pages/pages/account.d.ts +1 -1
  110. package/dist/cli/help-pages/pages/core.d.ts +1 -1
  111. package/dist/cli/help-pages/pages/index.d.ts +1 -1
  112. package/dist/cli/help-pages/pages/misc.d.ts +1 -1
  113. package/dist/cli/help-pages/pages/previews.d.ts +1 -1
  114. package/dist/cli/help-pages/pages/productions.d.ts +1 -1
  115. package/dist/cli/help-pages/render.d.ts +2 -2
  116. package/dist/cli/help-pages/shared.d.ts +1 -1
  117. package/dist/cli/help.d.ts +2 -2
  118. package/dist/cli/index.js +2 -1383
  119. package/dist/cli/preview-bindings.d.ts +3 -3
  120. package/dist/cli/preview.d.ts +1 -1
  121. package/dist/cli/wrangler-auth.d.ts +1 -1
  122. package/dist/cloudflare/account-core.d.ts +2 -2
  123. package/dist/cloudflare/account-resources.d.ts +2 -2
  124. package/dist/cloudflare/account-status.d.ts +1 -1
  125. package/dist/cloudflare/account-workers.d.ts +2 -2
  126. package/dist/cloudflare/account.d.ts +7 -7
  127. package/dist/cloudflare/auth.d.ts +1 -1
  128. package/dist/cloudflare/index.d.ts +13 -13
  129. package/dist/cloudflare/index.js +4 -59
  130. package/dist/cloudflare/kv-namespace.d.ts +1 -1
  131. package/dist/cloudflare/preview-registry-cache.d.ts +1 -1
  132. package/dist/cloudflare/preview-registry-inference.d.ts +2 -2
  133. package/dist/cloudflare/preview-registry-records.d.ts +3 -3
  134. package/dist/cloudflare/preview-registry-shape.d.ts +2 -2
  135. package/dist/cloudflare/preview-registry-store.d.ts +3 -3
  136. package/dist/cloudflare/preview-registry-transport.d.ts +2 -2
  137. package/dist/cloudflare/preview-registry-types.d.ts +2 -2
  138. package/dist/cloudflare/preview-registry.d.ts +5 -5
  139. package/dist/cloudflare/tokens.d.ts +2 -2
  140. package/dist/cloudflare/usage.d.ts +2 -2
  141. package/dist/config/binding-resolution-helpers.d.ts +1 -1
  142. package/dist/config/compiler/bindings.d.ts +2 -2
  143. package/dist/config/compiler/core-helpers.d.ts +2 -2
  144. package/dist/config/compiler/do-workers.d.ts +2 -2
  145. package/dist/config/compiler/paths.d.ts +1 -1
  146. package/dist/config/compiler.d.ts +6 -6
  147. package/dist/config/define.d.ts +2 -2
  148. package/dist/config/deploy-resources.d.ts +5 -5
  149. package/dist/config/env-vars.d.ts +1 -1
  150. package/dist/config/framework-providers.d.ts +1 -1
  151. package/dist/config/index.d.ts +12 -12
  152. package/dist/config/loader.d.ts +2 -2
  153. package/dist/config/local-dev-vars.d.ts +1 -1
  154. package/dist/config/preview-resources.d.ts +4 -4
  155. package/dist/config/preview.d.ts +1 -1
  156. package/dist/config/ref.d.ts +2 -2
  157. package/dist/config/resolve-phased.d.ts +4 -4
  158. package/dist/config/resolve.d.ts +1 -1
  159. package/dist/config/resource-resolution.d.ts +6 -6
  160. package/dist/config/schema-env.d.ts +20 -20
  161. package/dist/config/schema-normalization.d.ts +1 -1
  162. package/dist/config/schema-types-bindings.d.ts +4 -4
  163. package/dist/config/schema-types-build.d.ts +1 -1
  164. package/dist/config/schema-types.d.ts +7 -7
  165. package/dist/config/schema.d.ts +46 -46
  166. package/dist/config/service-bindings-validation.d.ts +1 -1
  167. package/dist/config-entry.d.ts +6 -6
  168. package/dist/config-entry.js +3 -8
  169. package/dist/decorators/index.d.ts +2 -2
  170. package/dist/decorators/index.js +2 -9
  171. package/dist/dev-server/d1-migrations.d.ts +1 -1
  172. package/dist/dev-server/dev-server-state.d.ts +6 -6
  173. package/dist/dev-server/gateway-script.d.ts +1 -1
  174. package/dist/dev-server/index.d.ts +1 -1
  175. package/dist/dev-server/miniflare-bindings.d.ts +1 -1
  176. package/dist/dev-server/miniflare-dev-config.d.ts +5 -5
  177. package/dist/dev-server/miniflare-worker-config.d.ts +3 -3
  178. package/dist/dev-server/server-startup-helpers.d.ts +6 -6
  179. package/dist/dev-server/worker-surface-paths.d.ts +2 -2
  180. package/dist/index.d.ts +8 -8
  181. package/dist/index.js +9 -22
  182. package/dist/runtime/context-events.d.ts +1 -1
  183. package/dist/runtime/context.d.ts +3 -3
  184. package/dist/runtime/exports.d.ts +2 -2
  185. package/dist/runtime/index.d.ts +10 -10
  186. package/dist/runtime/index.js +5 -57
  187. package/dist/runtime/middleware.d.ts +1 -1
  188. package/dist/runtime/router/index.d.ts +3 -3
  189. package/dist/runtime/validation.d.ts +1 -1
  190. package/dist/secrets/local-secrets.d.ts +1 -1
  191. package/dist/shims/local-media-bindings.d.ts +1 -1
  192. package/dist/sveltekit/index.d.ts +1 -1
  193. package/dist/sveltekit/index.js +327 -9
  194. package/dist/sveltekit/local-bindings.d.ts +1 -1
  195. package/dist/sveltekit/platform.d.ts +1 -1
  196. package/dist/test/binding-hints.d.ts +2 -2
  197. package/dist/test/cf.d.ts +19 -19
  198. package/dist/test/index.d.ts +18 -18
  199. package/dist/test/index.js +4495 -46
  200. package/dist/test/offline-bindings.d.ts +3 -3
  201. package/dist/test/resolve-service-bindings.d.ts +1 -1
  202. package/dist/test/simple-context-bindings.d.ts +1 -1
  203. package/dist/test/simple-context-durable-objects.d.ts +1 -1
  204. package/dist/test/simple-context-env.d.ts +2 -2
  205. package/dist/test/simple-context-handlers.d.ts +2 -2
  206. package/dist/test/simple-context-lifecycle.d.ts +2 -2
  207. package/dist/test/simple-context-mfconfig.d.ts +1 -1
  208. package/dist/test/simple-context-multi-worker.d.ts +2 -2
  209. package/dist/test/simple-context-runtime.d.ts +1 -1
  210. package/dist/test/simple-context-startup.d.ts +1 -1
  211. package/dist/test/simple-context.d.ts +1 -1
  212. package/dist/test/utilities/env.d.ts +3 -3
  213. package/dist/test/utilities.d.ts +10 -10
  214. package/dist/test/worker.d.ts +1 -1
  215. package/dist/transform/index.d.ts +2 -2
  216. package/dist/utils/send-email.js +163 -19
  217. package/dist/vite/config-file.d.ts +2 -2
  218. package/dist/vite/index.d.ts +3 -3
  219. package/dist/vite/index.js +2 -31
  220. package/dist/vite/plugin-config-hook.d.ts +1 -1
  221. package/dist/vite/plugin-context.d.ts +3 -3
  222. package/dist/vite/plugin-durable-objects.d.ts +2 -2
  223. package/dist/vite/plugin-programmatic.d.ts +1 -1
  224. package/dist/vite/plugin-service-bindings.d.ts +2 -2
  225. package/dist/vite/plugin.d.ts +3 -3
  226. package/dist/worker-entry/composed-worker.d.ts +1 -1
  227. package/dist/worker-entry/routes.d.ts +2 -2
  228. package/dist/worker-entry/surface-paths.d.ts +1 -1
  229. package/dist/workflows/local-workflow-entrypoints.d.ts +1 -1
  230. package/package.json +5 -3
  231. package/dist/account-4tgh03a8.js +0 -484
  232. package/dist/ai-r3zqmxan.js +0 -261
  233. package/dist/api-6z01z734.js +0 -33
  234. package/dist/build-kw625v84.js +0 -51
  235. package/dist/config-ghk2bxj3.js +0 -102
  236. package/dist/deploy-9kee65n9.js +0 -1062
  237. package/dist/dev-x8zr249a.js +0 -3569
  238. package/dist/doctor-0ng5qrr1.js +0 -258
  239. package/dist/durable-object-0ybmg08a.js +0 -13
  240. package/dist/index-04wh9bxx.js +0 -514
  241. package/dist/index-0cc05hzv.js +0 -74
  242. package/dist/index-2yv7w548.js +0 -185
  243. package/dist/index-37x76zdn.js +0 -4
  244. package/dist/index-3cpzsr47.js +0 -125
  245. package/dist/index-3t6rypgc.js +0 -13
  246. package/dist/index-4mmpccrb.js +0 -309
  247. package/dist/index-5dkjffqz.js +0 -25
  248. package/dist/index-5hy7jmv3.js +0 -890
  249. package/dist/index-627srx16.js +0 -45
  250. package/dist/index-7m557715.js +0 -283
  251. package/dist/index-a8pnvg3r.js +0 -52
  252. package/dist/index-aabgympv.js +0 -39
  253. package/dist/index-atwc3csp.js +0 -256
  254. package/dist/index-cv4cvrxe.js +0 -2046
  255. package/dist/index-h7r11y4a.js +0 -539
  256. package/dist/index-hvtd936d.js +0 -1229
  257. package/dist/index-kcp7y951.js +0 -136
  258. package/dist/index-maw0jjnn.js +0 -147
  259. package/dist/index-mek9msfv.js +0 -705
  260. package/dist/index-n4xkaymm.js +0 -236
  261. package/dist/index-nkk59p3y.js +0 -579
  262. package/dist/index-phcrvs6d.js +0 -342
  263. package/dist/index-se4kw8tm.js +0 -460
  264. package/dist/index-x8s9rwfh.js +0 -2020
  265. package/dist/index-y7w3x9p1.js +0 -18
  266. package/dist/index-z9gy8w6b.js +0 -57
  267. package/dist/index-zdd0d9qa.js +0 -199
  268. package/dist/init-tb8jqgvr.js +0 -180
  269. package/dist/login-4h1sfsed.js +0 -75
  270. package/dist/previews-qr7c5j8h.js +0 -1336
  271. package/dist/productions-xpmd6bw8.js +0 -505
  272. package/dist/remote-kqcvhnfx.js +0 -192
  273. package/dist/secrets-6wbdsdek.js +0 -89
  274. package/dist/token-yp1qa70y.js +0 -419
  275. package/dist/types-15yv4cj3.js +0 -701
  276. package/dist/worker-1yg72jxg.js +0 -510
  277. package/dist/worker-entrypoint-y8s9kdcx.js +0 -15
@@ -1,2020 +0,0 @@
1
- import {
2
- createD1Database,
3
- createKVNamespace,
4
- createQueue,
5
- createR2Bucket,
6
- getEffectiveAccountId,
7
- getPrimaryAccount,
8
- listD1Databases,
9
- listHyperdrives,
10
- listKVNamespaces,
11
- listQueues,
12
- listR2Buckets,
13
- listVectorizeIndexes
14
- } from "./index-h7r11y4a.js";
15
-
16
- // src/config/env-vars.ts
17
- import { existsSync } from "node:fs";
18
- import { readFile } from "node:fs/promises";
19
- import { dirname, resolve } from "pathe";
20
- var ENV_DESCRIPTOR_FLAG = "__devflareEnvDescriptor";
21
- function createDescriptor(state) {
22
- const descriptor = {
23
- [ENV_DESCRIPTOR_FLAG]: true,
24
- __state: state,
25
- optional() {
26
- return createDescriptor({
27
- ...state,
28
- optional: true
29
- });
30
- },
31
- parse(parser) {
32
- return createDescriptor({
33
- ...state,
34
- parser
35
- });
36
- },
37
- parser(parser) {
38
- return this.parse(parser);
39
- },
40
- default(value) {
41
- return createDescriptor({
42
- ...state,
43
- defaultValue: value,
44
- hasDefault: true,
45
- optional: false
46
- });
47
- },
48
- dev(value) {
49
- return createDescriptor({
50
- ...state,
51
- devValue: value,
52
- hasDevDefault: true
53
- });
54
- }
55
- };
56
- return descriptor;
57
- }
58
- function createEnvVarDescriptor(name) {
59
- return createDescriptor({
60
- name,
61
- optional: false,
62
- hasDefault: false,
63
- hasDevDefault: false
64
- });
65
- }
66
- var env = new Proxy({}, {
67
- get(_target, prop) {
68
- if (typeof prop !== "string") {
69
- return;
70
- }
71
- return createEnvVarDescriptor(prop);
72
- }
73
- });
74
- function isEnvVarDescriptor(value) {
75
- return Boolean(value && typeof value === "object" && value[ENV_DESCRIPTOR_FLAG] === true);
76
- }
77
- function parseEnvValue(rawValue) {
78
- const trimmed = rawValue.trim();
79
- const quote = trimmed[0];
80
- if ((quote === '"' || quote === "'" || quote === "`") && trimmed.endsWith(quote) && trimmed.length >= 2) {
81
- const inner = trimmed.slice(1, -1);
82
- if (quote !== '"') {
83
- return inner;
84
- }
85
- return inner.replace(/\\n/g, `
86
- `).replace(/\\r/g, "\r").replace(/\\t/g, "\t").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
87
- }
88
- return trimmed;
89
- }
90
- function parseDevflareEnvFile(contents) {
91
- const values = {};
92
- for (const line of contents.split(/\r?\n/)) {
93
- const trimmed = line.trim();
94
- if (!trimmed || trimmed.startsWith("#")) {
95
- continue;
96
- }
97
- const assignment = trimmed.startsWith("export ") ? trimmed.slice("export ".length).trimStart() : trimmed;
98
- const equalsIndex = assignment.indexOf("=");
99
- if (equalsIndex <= 0) {
100
- continue;
101
- }
102
- const key = assignment.slice(0, equalsIndex).trim();
103
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
104
- continue;
105
- }
106
- values[key] = parseEnvValue(assignment.slice(equalsIndex + 1));
107
- }
108
- return values;
109
- }
110
- function collectAncestorDirectories(startDir) {
111
- const directories = [];
112
- let current = resolve(startDir);
113
- while (true) {
114
- directories.push(current);
115
- const parent = dirname(current);
116
- if (parent === current) {
117
- break;
118
- }
119
- current = parent;
120
- }
121
- return directories.reverse();
122
- }
123
- function getDevflareDotenvPaths(startDir) {
124
- return collectAncestorDirectories(startDir).flatMap((directory) => [
125
- resolve(directory, ".env.dev"),
126
- resolve(directory, ".env")
127
- ]);
128
- }
129
- async function loadDevflareDotenv(startDir) {
130
- const values = {};
131
- const files = [];
132
- for (const filePath of getDevflareDotenvPaths(startDir)) {
133
- if (!existsSync(filePath)) {
134
- continue;
135
- }
136
- Object.assign(values, parseDevflareEnvFile(await readFile(filePath, "utf8")));
137
- files.push(filePath);
138
- }
139
- return { values, files };
140
- }
141
- async function loadDevflareDotenvIntoProcess(startDir) {
142
- const loaded = await loadDevflareDotenv(startDir);
143
- for (const [key, value] of Object.entries(loaded.values)) {
144
- if (process.env[key] === undefined) {
145
- process.env[key] = value;
146
- }
147
- }
148
- return loaded;
149
- }
150
- function formatMissingEnvTree(missing) {
151
- const root = {};
152
- for (const item of missing) {
153
- let current = root;
154
- for (const segment of item.path.slice(0, -1)) {
155
- const next = current[segment];
156
- if (!next || typeof next !== "object") {
157
- current[segment] = {};
158
- }
159
- current = current[segment];
160
- }
161
- current[item.path[item.path.length - 1] ?? item.name] = item.name;
162
- }
163
- const lines = [];
164
- const writeNode = (node, depth) => {
165
- const indent = "\t".repeat(depth);
166
- for (const [key, value] of Object.entries(node)) {
167
- if (value && typeof value === "object") {
168
- lines.push(`${indent}${key}:`);
169
- writeNode(value, depth + 1);
170
- } else {
171
- lines.push(`${indent}${key}: ${String(value)}`);
172
- }
173
- }
174
- };
175
- writeNode(root, 1);
176
- return lines.join(`
177
- `);
178
- }
179
-
180
- class EnvVarResolutionError extends Error {
181
- missing;
182
- mode;
183
- code = "ENV_VARS_MISSING";
184
- constructor(missing, mode) {
185
- super(["These environment variables are missing:", "", formatMissingEnvTree(missing)].join(`
186
- `));
187
- this.missing = missing;
188
- this.mode = mode;
189
- this.name = "EnvVarResolutionError";
190
- }
191
- }
192
-
193
- class EnvVarParseError extends Error {
194
- variableName;
195
- path;
196
- code = "ENV_VAR_PARSE_FAILED";
197
- constructor(variableName, path, cause) {
198
- super(`Could not parse environment variable ${variableName} for vars.${path.join(".")}.
199
- ` + `Parser error: ${cause instanceof Error ? cause.message : String(cause)}`);
200
- this.variableName = variableName;
201
- this.path = path;
202
- this.name = "EnvVarParseError";
203
- }
204
- }
205
- function isPlainObject(value) {
206
- if (!value || typeof value !== "object" || Array.isArray(value) || isEnvVarDescriptor(value)) {
207
- return false;
208
- }
209
- const prototype = Object.getPrototypeOf(value);
210
- return prototype === Object.prototype || prototype === null;
211
- }
212
- var OMIT_VALUE = Symbol("omit optional env var");
213
- function resolveDescriptorValue(descriptor, sources, path, mode, missing) {
214
- const state = descriptor.__state;
215
- const rawValue = sources[state.name];
216
- if (rawValue !== undefined) {
217
- try {
218
- return state.parser ? state.parser(rawValue) : rawValue;
219
- } catch (error) {
220
- throw new EnvVarParseError(state.name, path, error);
221
- }
222
- }
223
- if (mode === "dev" && state.hasDevDefault) {
224
- return state.devValue;
225
- }
226
- if (state.hasDefault) {
227
- return state.defaultValue;
228
- }
229
- if (state.optional) {
230
- return OMIT_VALUE;
231
- }
232
- missing.push({ path, name: state.name });
233
- return OMIT_VALUE;
234
- }
235
- function resolveVarValue(value, sources, path, mode, missing) {
236
- if (isEnvVarDescriptor(value)) {
237
- return resolveDescriptorValue(value, sources, path, mode, missing);
238
- }
239
- if (Array.isArray(value)) {
240
- return value.map((item, index) => resolveVarValue(item, sources, [...path, String(index)], mode, missing)).filter((item) => item !== OMIT_VALUE);
241
- }
242
- if (isPlainObject(value)) {
243
- const resolved = {};
244
- for (const [key, childValue] of Object.entries(value)) {
245
- const child = resolveVarValue(childValue, sources, [...path, key], mode, missing);
246
- if (child !== OMIT_VALUE) {
247
- resolved[key] = child;
248
- }
249
- }
250
- return resolved;
251
- }
252
- return value;
253
- }
254
- function resolveVarsObject(vars, sources, mode, missing) {
255
- if (!vars) {
256
- return vars;
257
- }
258
- const resolved = resolveVarValue(vars, sources, [], mode, missing);
259
- return resolved === OMIT_VALUE ? undefined : resolved;
260
- }
261
- async function resolveConfigEnvVars(config, options) {
262
- const startDir = options.configPath ? dirname(resolve(options.cwd, options.configPath)) : options.cwd;
263
- const dotenv = await loadDevflareDotenv(startDir);
264
- const sources = {
265
- ...dotenv.values,
266
- ...process.env
267
- };
268
- const missing = [];
269
- const vars = resolveVarsObject(config.vars, sources, options.mode, missing);
270
- if (missing.length > 0) {
271
- throw new EnvVarResolutionError(missing, options.mode);
272
- }
273
- return vars === config.vars ? config : {
274
- ...config,
275
- vars
276
- };
277
- }
278
-
279
- // src/config/schema-bindings.ts
280
- import { z } from "zod";
281
- var durableObjectBindingSchema = z.custom((val) => {
282
- if (typeof val === "string") {
283
- return true;
284
- }
285
- if (val && typeof val === "object" && "className" in val) {
286
- const obj = val;
287
- return typeof obj.className === "string";
288
- }
289
- return false;
290
- }, {
291
- message: "Expected string or { className: string, scriptName?: string }"
292
- });
293
- var queueConsumerSchema = z.object({
294
- queue: z.string(),
295
- maxBatchSize: z.number().optional(),
296
- maxBatchTimeout: z.number().optional(),
297
- maxRetries: z.number().optional(),
298
- deadLetterQueue: z.string().optional(),
299
- maxConcurrency: z.number().optional(),
300
- retryDelay: z.number().optional()
301
- });
302
- var queuesConfigSchema = z.object({
303
- producers: z.record(z.string(), z.string()).optional(),
304
- consumers: z.array(queueConsumerSchema).optional()
305
- });
306
- var rateLimitBindingSchema = z.object({
307
- namespaceId: z.string().regex(/^[1-9]\d*$/, "namespaceId must be a positive integer string"),
308
- simple: z.object({
309
- limit: z.number().int().positive(),
310
- period: z.union([z.literal(10), z.literal(60)])
311
- }).strict()
312
- }).strict();
313
- var versionMetadataBindingSchema = z.object({
314
- binding: z.string().min(1)
315
- }).strict();
316
- var workerLoaderBindingSchema = z.object({}).strict();
317
- var secretsStoreBindingSchema = z.union([
318
- z.string().min(1),
319
- z.object({
320
- storeId: z.string().min(1),
321
- secretName: z.string().min(1)
322
- }).strict()
323
- ]);
324
- var serviceBindingKeys = new Set(["service", "environment", "entrypoint", "__ref"]);
325
- function isServiceBindingValue(val) {
326
- if (typeof val !== "object" && typeof val !== "function" || val === null) {
327
- return false;
328
- }
329
- const obj = val;
330
- if (typeof obj.service !== "string" || obj.service.trim().length === 0) {
331
- return false;
332
- }
333
- if (obj.environment !== undefined && (typeof obj.environment !== "string" || obj.environment.trim().length === 0)) {
334
- return false;
335
- }
336
- if (obj.entrypoint !== undefined && (typeof obj.entrypoint !== "string" || obj.entrypoint.trim().length === 0)) {
337
- return false;
338
- }
339
- if (typeof val === "object") {
340
- for (const key of Object.keys(obj)) {
341
- if (!serviceBindingKeys.has(key)) {
342
- return false;
343
- }
344
- }
345
- }
346
- return true;
347
- }
348
- var serviceBindingSchema = z.custom(isServiceBindingValue, {
349
- message: "Expected service binding object with { service: string, environment?: string, entrypoint?: string } or ref().worker"
350
- });
351
- var aiBindingSchema = z.object({
352
- binding: z.string(),
353
- remote: z.boolean().optional(),
354
- staging: z.boolean().optional()
355
- }).strict();
356
- var aiSearchNamespaceBindingSchema = z.object({
357
- namespace: z.string().min(1),
358
- remote: z.boolean().optional()
359
- }).strict();
360
- var aiSearchInstanceBindingSchema = z.object({
361
- instanceName: z.string().min(1),
362
- remote: z.boolean().optional()
363
- }).strict();
364
- var vectorizeBindingSchema = z.object({
365
- indexName: z.string(),
366
- remote: z.boolean().optional()
367
- });
368
- var hyperdriveBindingByIdSchema = z.object({
369
- id: z.string(),
370
- localConnectionString: z.string().optional()
371
- }).strict();
372
- var hyperdriveBindingByNameSchema = z.object({
373
- name: z.string(),
374
- localConnectionString: z.string().optional(),
375
- previewFallback: z.literal("base").optional(),
376
- previewId: z.string().optional(),
377
- previewLocalConnectionString: z.string().optional()
378
- }).strict();
379
- var hyperdriveBindingSchema = z.union([
380
- z.string(),
381
- hyperdriveBindingByIdSchema,
382
- hyperdriveBindingByNameSchema
383
- ]);
384
- var SINGLE_BROWSER_BINDING_ERROR_MESSAGE = "Devflare currently supports exactly one browser binding because Wrangler only supports a single browser binding.";
385
- function formatBrowserBindingLimitMessage(bindingNames) {
386
- if (bindingNames.length <= 1) {
387
- return SINGLE_BROWSER_BINDING_ERROR_MESSAGE;
388
- }
389
- return `${SINGLE_BROWSER_BINDING_ERROR_MESSAGE} Configured bindings: ${bindingNames.join(", ")}`;
390
- }
391
- function getBrowserBindingNames(bindings) {
392
- return bindings ? Object.keys(bindings) : [];
393
- }
394
- var browserBindingValueSchema = z.union([
395
- z.string(),
396
- z.object({
397
- remote: z.boolean().optional()
398
- }).strict()
399
- ]);
400
- var browserBindingSchema = z.record(z.string(), browserBindingValueSchema).superRefine((bindings, ctx) => {
401
- const bindingNames = getBrowserBindingNames(bindings);
402
- if (bindingNames.length > 1) {
403
- ctx.addIssue({
404
- code: z.ZodIssueCode.custom,
405
- message: formatBrowserBindingLimitMessage(bindingNames)
406
- });
407
- }
408
- });
409
- var analyticsBindingSchema = z.object({
410
- dataset: z.string()
411
- });
412
- var sendEmailBindingSchema = z.object({
413
- destinationAddress: z.string().optional(),
414
- allowedDestinationAddresses: z.array(z.string()).optional(),
415
- allowedSenderAddresses: z.array(z.string()).optional()
416
- }).refine((binding) => {
417
- return !(binding.destinationAddress && binding.allowedDestinationAddresses);
418
- }, {
419
- message: "sendEmail bindings must use either destinationAddress or allowedDestinationAddresses, not both",
420
- path: ["allowedDestinationAddresses"]
421
- });
422
- var d1BindingByIdSchema = z.object({
423
- id: z.string()
424
- }).strict();
425
- var d1BindingByNameSchema = z.object({
426
- name: z.string()
427
- }).strict();
428
- var d1BindingSchema = z.union([z.string(), d1BindingByIdSchema, d1BindingByNameSchema]);
429
- var kvBindingByIdSchema = z.object({
430
- id: z.string()
431
- }).strict();
432
- var kvBindingByNameSchema = z.object({
433
- name: z.string()
434
- }).strict();
435
- var kvBindingSchema = z.union([z.string(), kvBindingByIdSchema, kvBindingByNameSchema]);
436
- var mtlsCertificateBindingByIdSchema = z.object({
437
- certificateId: z.string().min(1),
438
- remote: z.boolean().optional()
439
- }).strict();
440
- var mtlsCertificateBindingByWranglerIdSchema = z.object({
441
- certificate_id: z.string().min(1),
442
- remote: z.boolean().optional()
443
- }).strict();
444
- var mtlsCertificateBindingSchema = z.union([
445
- z.string().min(1),
446
- mtlsCertificateBindingByIdSchema,
447
- mtlsCertificateBindingByWranglerIdSchema
448
- ]);
449
- var dispatchNamespaceBindingSchema = z.union([
450
- z.string().min(1),
451
- z.object({
452
- namespace: z.string().min(1),
453
- outbound: z.object({
454
- service: z.string().min(1),
455
- environment: z.string().optional(),
456
- parameters: z.array(z.string()).optional()
457
- }).strict().optional(),
458
- remote: z.boolean().optional()
459
- }).strict()
460
- ]);
461
- var workflowBindingSchema = z.object({
462
- name: z.string().min(1),
463
- className: z.string().min(1),
464
- scriptName: z.string().min(1).optional(),
465
- remote: z.boolean().optional(),
466
- limits: z.object({
467
- steps: z.number().int().positive()
468
- }).strict().optional()
469
- }).strict();
470
- var pipelineBindingSchema = z.union([
471
- z.string().min(1),
472
- z.object({
473
- pipeline: z.string().min(1),
474
- remote: z.boolean().optional()
475
- }).strict()
476
- ]);
477
- var imagesBindingSchema = z.object({
478
- remote: z.boolean().optional()
479
- }).strict().or(z.literal(true));
480
- var mediaBindingSchema = z.object({
481
- remote: z.boolean().optional()
482
- }).strict().or(z.literal(true));
483
- var artifactsBindingSchema = z.union([
484
- z.string().min(1),
485
- z.object({
486
- namespace: z.string().min(1),
487
- remote: z.boolean().optional()
488
- }).strict()
489
- ]);
490
- var bindingsSchema = z.object({
491
- kv: z.record(z.string(), kvBindingSchema).optional(),
492
- d1: z.record(z.string(), d1BindingSchema).optional(),
493
- r2: z.record(z.string(), z.string()).optional(),
494
- durableObjects: z.record(z.string(), durableObjectBindingSchema).optional(),
495
- queues: queuesConfigSchema.optional(),
496
- rateLimits: z.record(z.string(), rateLimitBindingSchema).optional(),
497
- versionMetadata: versionMetadataBindingSchema.optional(),
498
- workerLoaders: z.record(z.string(), workerLoaderBindingSchema).optional(),
499
- secretsStore: z.record(z.string(), secretsStoreBindingSchema).optional(),
500
- services: z.record(z.string(), serviceBindingSchema).optional(),
501
- ai: aiBindingSchema.optional(),
502
- aiSearchNamespaces: z.record(z.string(), aiSearchNamespaceBindingSchema).optional(),
503
- aiSearch: z.record(z.string(), aiSearchInstanceBindingSchema).optional(),
504
- vectorize: z.record(z.string(), vectorizeBindingSchema).optional(),
505
- hyperdrive: z.record(z.string(), hyperdriveBindingSchema).optional(),
506
- browser: browserBindingSchema.optional(),
507
- analyticsEngine: z.record(z.string(), analyticsBindingSchema).optional(),
508
- sendEmail: z.record(z.string(), sendEmailBindingSchema).optional(),
509
- mtlsCertificates: z.record(z.string(), mtlsCertificateBindingSchema).optional(),
510
- dispatchNamespaces: z.record(z.string(), dispatchNamespaceBindingSchema).optional(),
511
- workflows: z.record(z.string(), workflowBindingSchema).optional(),
512
- pipelines: z.record(z.string(), pipelineBindingSchema).optional(),
513
- images: z.record(z.string(), imagesBindingSchema).optional().superRefine((bindings, ctx) => {
514
- if (!bindings || Object.keys(bindings).length <= 1) {
515
- return;
516
- }
517
- ctx.addIssue({
518
- code: z.ZodIssueCode.custom,
519
- message: "Wrangler currently supports one Images binding per Worker"
520
- });
521
- }),
522
- media: z.record(z.string(), mediaBindingSchema).optional().superRefine((bindings, ctx) => {
523
- if (!bindings || Object.keys(bindings).length <= 1) {
524
- return;
525
- }
526
- ctx.addIssue({
527
- code: z.ZodIssueCode.custom,
528
- message: "Wrangler currently supports one Media Transformations binding per Worker"
529
- });
530
- }),
531
- artifacts: z.record(z.string(), artifactsBindingSchema).optional()
532
- }).optional();
533
-
534
- // src/config/schema-normalization.ts
535
- function getSingleBrowserBindingName(bindings) {
536
- const bindingNames = getBrowserBindingNames(bindings);
537
- if (bindingNames.length === 0) {
538
- return;
539
- }
540
- return bindingNames[0];
541
- }
542
- function normalizeDOBinding(config) {
543
- if (typeof config === "string") {
544
- return { className: config, kind: "local" };
545
- }
546
- const scriptName = config.scriptName;
547
- const __ref = config.__ref;
548
- const kind = scriptName || __ref ? "cross-worker" : "local";
549
- return {
550
- className: config.className,
551
- scriptName,
552
- __ref,
553
- kind
554
- };
555
- }
556
- function normalizeD1Binding(config) {
557
- if (typeof config === "string") {
558
- return { name: config };
559
- }
560
- if ("id" in config) {
561
- return { databaseId: config.id };
562
- }
563
- return { name: config.name };
564
- }
565
- function normalizeKVBinding(config) {
566
- if (typeof config === "string") {
567
- return { name: config };
568
- }
569
- if ("id" in config) {
570
- return { namespaceId: config.id };
571
- }
572
- return { name: config.name };
573
- }
574
- function normalizeHyperdriveBinding(config) {
575
- if (typeof config === "string") {
576
- return { name: config };
577
- }
578
- const localConnectionString = "localConnectionString" in config ? config.localConnectionString : ("previewLocalConnectionString" in config) ? config.previewLocalConnectionString : undefined;
579
- if ("id" in config) {
580
- return {
581
- configurationId: config.id,
582
- ...localConnectionString && { localConnectionString }
583
- };
584
- }
585
- return {
586
- name: config.name,
587
- ...localConnectionString && { localConnectionString }
588
- };
589
- }
590
- function normalizeMtlsCertificateBinding(config) {
591
- if (typeof config === "string") {
592
- return { certificateId: config };
593
- }
594
- if ("certificateId" in config) {
595
- return {
596
- certificateId: config.certificateId,
597
- ...config.remote !== undefined && { remote: config.remote }
598
- };
599
- }
600
- return {
601
- certificateId: config.certificate_id,
602
- ...config.remote !== undefined && { remote: config.remote }
603
- };
604
- }
605
- function normalizeDispatchNamespaceBinding(config) {
606
- if (typeof config === "string") {
607
- return { namespace: config };
608
- }
609
- return {
610
- namespace: config.namespace,
611
- ...config.outbound && {
612
- outbound: {
613
- service: config.outbound.service,
614
- ...config.outbound.environment && { environment: config.outbound.environment },
615
- ...config.outbound.parameters && { parameters: config.outbound.parameters }
616
- }
617
- },
618
- ...config.remote !== undefined && { remote: config.remote }
619
- };
620
- }
621
- function normalizeWorkflowBinding(config) {
622
- return {
623
- name: config.name,
624
- className: config.className,
625
- ...config.scriptName && { scriptName: config.scriptName },
626
- ...config.remote !== undefined && { remote: config.remote },
627
- ...config.limits && {
628
- limits: {
629
- steps: config.limits.steps
630
- }
631
- }
632
- };
633
- }
634
- function normalizePipelineBinding(config) {
635
- if (typeof config === "string") {
636
- return { pipeline: config };
637
- }
638
- return {
639
- pipeline: config.pipeline,
640
- ...config.remote !== undefined && { remote: config.remote }
641
- };
642
- }
643
- function normalizeImagesBinding(binding, config) {
644
- if (config === true) {
645
- return { binding };
646
- }
647
- return {
648
- binding,
649
- ...config.remote !== undefined && { remote: config.remote }
650
- };
651
- }
652
- function normalizeMediaBinding(binding, config) {
653
- if (config === true) {
654
- return { binding };
655
- }
656
- return {
657
- binding,
658
- ...config.remote !== undefined && { remote: config.remote }
659
- };
660
- }
661
- function normalizeArtifactsBinding(config) {
662
- if (typeof config === "string") {
663
- return { namespace: config };
664
- }
665
- return {
666
- namespace: config.namespace,
667
- ...config.remote !== undefined && { remote: config.remote }
668
- };
669
- }
670
- function normalizeSecretsStoreBinding(config, defaultStoreId, bindingName = "unknown") {
671
- if (typeof config === "string") {
672
- if (!defaultStoreId) {
673
- throw new Error(`Secrets Store binding "${bindingName}" uses shorthand and requires top-level secretsStoreId.`);
674
- }
675
- return {
676
- storeId: defaultStoreId,
677
- secretName: config
678
- };
679
- }
680
- return {
681
- storeId: config.storeId,
682
- secretName: config.secretName
683
- };
684
- }
685
- function getLocalKVNamespaceIdentifier(config) {
686
- const normalized = normalizeKVBinding(config);
687
- return normalized.namespaceId ?? normalized.name ?? "";
688
- }
689
- function getLocalD1DatabaseIdentifier(config) {
690
- const normalized = normalizeD1Binding(config);
691
- return normalized.databaseId ?? normalized.name ?? "";
692
- }
693
-
694
- // src/config/schema.ts
695
- import { z as z5 } from "zod";
696
-
697
- // src/config/compatibility.ts
698
- var FORCED_COMPATIBILITY_FLAGS = ["nodejs_compat", "nodejs_als"];
699
- function normalizeCompatibilityFlags(flags = []) {
700
- return [...new Set([...FORCED_COMPATIBILITY_FLAGS, ...flags])];
701
- }
702
-
703
- // src/config/schema-build.ts
704
- import { z as z2 } from "zod";
705
- var rolldownOptionsSchema = z2.custom((value) => {
706
- return typeof value === "object" && value !== null && !Array.isArray(value);
707
- }, {
708
- message: "Expected Rolldown options object"
709
- });
710
- var rolldownConfigSchema = z2.object({
711
- target: z2.string().optional(),
712
- minify: z2.boolean().optional(),
713
- sourcemap: z2.boolean().optional(),
714
- options: rolldownOptionsSchema.optional()
715
- }).optional();
716
- var viteConfigSchema = z2.object({
717
- plugins: z2.array(z2.unknown()).optional()
718
- }).catchall(z2.unknown()).optional();
719
-
720
- // src/config/schema-env.ts
721
- import { z as z3 } from "zod";
722
- var envConfigSchema = z3.lazy(() => z3.object(rootConfigShape).omit({ accountId: true, wsRoutes: true }).partial().strict());
723
- var envConfigSchemaInner = envConfigSchema;
724
-
725
- // src/config/schema-runtime.ts
726
- import { z as z4 } from "zod";
727
- var dateRegex = /^\d{4}-\d{2}-\d{2}$/;
728
- var compatibilityDateSchema = z4.string().regex(dateRegex, {
729
- message: "Compatibility date must be in YYYY-MM-DD format"
730
- });
731
- var routesConfigSchema = z4.object({
732
- dir: z4.string(),
733
- prefix: z4.string().optional()
734
- });
735
- var filesSchema = z4.object({
736
- fetch: z4.union([z4.string(), z4.literal(false)]).optional(),
737
- queue: z4.union([z4.string(), z4.literal(false)]).optional(),
738
- scheduled: z4.union([z4.string(), z4.literal(false)]).optional(),
739
- email: z4.union([z4.string(), z4.literal(false)]).optional(),
740
- tail: z4.union([z4.string(), z4.literal(false)]).optional(),
741
- durableObjects: z4.union([z4.string(), z4.literal(false)]).optional(),
742
- entrypoints: z4.union([z4.string(), z4.literal(false)]).optional(),
743
- workflows: z4.union([z4.string(), z4.literal(false)]).optional(),
744
- routes: z4.union([routesConfigSchema, z4.literal(false)]).optional(),
745
- transport: z4.union([z4.string(), z4.null()]).optional()
746
- }).optional();
747
- var tailConsumerSchema = z4.union([
748
- z4.string().min(1),
749
- z4.object({
750
- service: z4.string().min(1),
751
- environment: z4.string().min(1).optional()
752
- }).strict()
753
- ]);
754
- var triggersSchema = z4.object({
755
- crons: z4.array(z4.string()).optional()
756
- }).optional();
757
- var previewsConfigSchema = z4.object({
758
- includeCrons: z4.boolean().optional().default(false)
759
- }).optional();
760
- var serverConfigSchema = z4.object({
761
- host: z4.string().min(1).optional(),
762
- port: z4.number().int().min(1).max(65535).optional()
763
- }).strict().optional();
764
- var secretConfigSchema = z4.object({
765
- required: z4.boolean().optional().default(true)
766
- });
767
- var routeConfigSchema = z4.object({
768
- pattern: z4.string(),
769
- zone_name: z4.string().optional(),
770
- zone_id: z4.string().optional(),
771
- custom_domain: z4.boolean().optional()
772
- }).superRefine((route, ctx) => {
773
- if (!route.custom_domain) {
774
- return;
775
- }
776
- if (route.pattern.includes("*")) {
777
- ctx.addIssue({
778
- code: z4.ZodIssueCode.custom,
779
- path: ["pattern"],
780
- message: "Wildcard operators (*) are not allowed in Custom Domains"
781
- });
782
- }
783
- if (route.pattern.includes("/")) {
784
- ctx.addIssue({
785
- code: z4.ZodIssueCode.custom,
786
- path: ["pattern"],
787
- message: "Paths are not allowed in Custom Domains"
788
- });
789
- }
790
- });
791
- var wsRouteConfigSchema = z4.object({
792
- pattern: z4.string(),
793
- doNamespace: z4.string(),
794
- idParam: z4.string().default("id"),
795
- forwardPath: z4.string().default("/websocket")
796
- });
797
- var assetsConfigSchema = z4.object({
798
- directory: z4.string(),
799
- binding: z4.string().optional(),
800
- html_handling: z4.enum(["auto-trailing-slash", "force-trailing-slash", "drop-trailing-slash", "none"]).optional(),
801
- not_found_handling: z4.enum(["single-page-application", "404-page", "none"]).optional(),
802
- run_worker_first: z4.union([z4.boolean(), z4.array(z4.string())]).optional()
803
- }).strict().optional();
804
- var smartPlacementSchema = z4.object({
805
- mode: z4.enum(["off", "smart"]),
806
- hint: z4.string().optional()
807
- }).strict().superRefine((placement, ctx) => {
808
- if (placement.hint !== undefined && placement.mode !== "smart") {
809
- ctx.addIssue({
810
- code: z4.ZodIssueCode.custom,
811
- path: ["hint"],
812
- message: "placement.hint can only be set when placement.mode is smart"
813
- });
814
- }
815
- });
816
- var targetedRegionPlacementSchema = z4.object({
817
- mode: z4.literal("targeted").optional(),
818
- region: z4.string().min(1)
819
- }).strict();
820
- var targetedHostPlacementSchema = z4.object({
821
- mode: z4.literal("targeted").optional(),
822
- host: z4.string().min(1)
823
- }).strict();
824
- var targetedHostnamePlacementSchema = z4.object({
825
- mode: z4.literal("targeted").optional(),
826
- hostname: z4.string().min(1)
827
- }).strict();
828
- var placementSchema = z4.union([
829
- smartPlacementSchema,
830
- targetedRegionPlacementSchema,
831
- targetedHostPlacementSchema,
832
- targetedHostnamePlacementSchema
833
- ]).optional();
834
- var samplingRateSchema = z4.number().min(0).max(1);
835
- var observabilityLogsSchema = z4.object({
836
- enabled: z4.boolean().optional(),
837
- head_sampling_rate: samplingRateSchema.optional(),
838
- invocation_logs: z4.boolean().optional(),
839
- persist: z4.boolean().optional(),
840
- destinations: z4.array(z4.string()).optional()
841
- }).strict();
842
- var observabilityTracesSchema = z4.object({
843
- enabled: z4.boolean().optional(),
844
- head_sampling_rate: samplingRateSchema.optional(),
845
- persist: z4.boolean().optional(),
846
- destinations: z4.array(z4.string()).optional()
847
- }).strict();
848
- var observabilitySchema = z4.object({
849
- enabled: z4.boolean().optional(),
850
- head_sampling_rate: samplingRateSchema.optional(),
851
- logs: observabilityLogsSchema.optional(),
852
- traces: observabilityTracesSchema.optional()
853
- }).strict().optional();
854
- var limitsSchema = z4.object({
855
- cpu_ms: z4.number().optional(),
856
- subrequests: z4.number().optional()
857
- }).strict().optional();
858
- var rolloutStepPercentageSchema = z4.union([
859
- z4.number().int().positive(),
860
- z4.array(z4.number().int().positive()).min(1)
861
- ]);
862
- var containerConfigSchema = z4.object({
863
- className: z4.string().min(1),
864
- image: z4.string().min(1),
865
- maxInstances: z4.number().int().positive().optional(),
866
- instanceType: z4.string().min(1).optional(),
867
- name: z4.string().min(1).optional(),
868
- imageBuildContext: z4.string().min(1).optional(),
869
- imageVars: z4.record(z4.string(), z4.string()).optional(),
870
- rolloutActiveGracePeriod: z4.number().int().nonnegative().optional(),
871
- rolloutStepPercentage: rolloutStepPercentageSchema.optional()
872
- }).strict();
873
- var containersConfigSchema = z4.array(containerConfigSchema).optional();
874
- var moduleRuleSchema = z4.object({
875
- type: z4.enum(["ESModule", "CommonJS", "CompiledWasm", "Text", "Data"]),
876
- globs: z4.array(z4.string()).min(1),
877
- fallthrough: z4.boolean().optional()
878
- }).strict();
879
- var moduleRulesSchema = z4.array(moduleRuleSchema).optional();
880
- var renamedClassMigrationSchema = z4.object({
881
- from: z4.string(),
882
- to: z4.string()
883
- }).strict();
884
- var migrationSchema = z4.object({
885
- tag: z4.string(),
886
- new_classes: z4.array(z4.string()).optional(),
887
- renamed_classes: z4.array(renamedClassMigrationSchema).optional(),
888
- deleted_classes: z4.array(z4.string()).optional(),
889
- new_sqlite_classes: z4.array(z4.string()).optional()
890
- }).strict();
891
- var wranglerConfigSchema = z4.object({
892
- passthrough: z4.record(z4.string(), z4.unknown()).optional()
893
- }).optional();
894
-
895
- // src/config/schema.ts
896
- function getCurrentDate() {
897
- const now = new Date;
898
- return now.toISOString().split("T")[0];
899
- }
900
- function getSecretsStoreShorthandBindings(config) {
901
- return Object.entries(config.bindings?.secretsStore ?? {}).filter(([, binding]) => typeof binding === "string").map(([bindingName]) => bindingName);
902
- }
903
- function addSecretsStoreShorthandIssues(ctx, config, pathPrefix = []) {
904
- if (config.secretsStoreId) {
905
- return;
906
- }
907
- for (const bindingName of getSecretsStoreShorthandBindings(config)) {
908
- ctx.addIssue({
909
- code: z5.ZodIssueCode.custom,
910
- path: [...pathPrefix, "bindings", "secretsStore", bindingName],
911
- message: `Secrets Store binding "${bindingName}" uses shorthand and requires top-level secretsStoreId.`
912
- });
913
- }
914
- }
915
- var varValueSchema = z5.lazy(() => z5.union([
916
- z5.string(),
917
- z5.number(),
918
- z5.boolean(),
919
- z5.null(),
920
- z5.custom(isEnvVarDescriptor),
921
- z5.array(varValueSchema),
922
- z5.record(z5.string(), varValueSchema)
923
- ]));
924
- var rootConfigShape = {
925
- name: z5.string({
926
- required_error: "Worker name is required"
927
- }),
928
- accountId: z5.string().optional(),
929
- secretsStoreId: z5.string().min(1).optional(),
930
- compatibilityDate: compatibilityDateSchema.optional().default(getCurrentDate),
931
- compatibilityFlags: z5.array(z5.string()).optional().transform((flags = []) => normalizeCompatibilityFlags(flags)),
932
- previews: previewsConfigSchema,
933
- server: serverConfigSchema,
934
- files: filesSchema,
935
- bindings: bindingsSchema,
936
- triggers: triggersSchema,
937
- rules: moduleRulesSchema,
938
- findAdditionalModules: z5.boolean().optional(),
939
- baseDir: z5.string().optional(),
940
- preserveFileNames: z5.boolean().optional(),
941
- logpush: z5.boolean().optional(),
942
- uploadSourceMaps: z5.boolean().optional(),
943
- keepVars: z5.boolean().optional(),
944
- tailConsumers: z5.array(tailConsumerSchema).optional(),
945
- vars: z5.record(z5.string(), varValueSchema).optional(),
946
- secrets: z5.record(z5.string(), secretConfigSchema).optional(),
947
- routes: z5.array(routeConfigSchema).optional(),
948
- wsRoutes: z5.array(wsRouteConfigSchema).optional(),
949
- assets: assetsConfigSchema,
950
- containers: containersConfigSchema,
951
- placement: placementSchema,
952
- limits: limitsSchema,
953
- observability: observabilitySchema,
954
- migrations: z5.array(migrationSchema).optional(),
955
- rolldown: rolldownConfigSchema,
956
- vite: viteConfigSchema,
957
- wrangler: wranglerConfigSchema
958
- };
959
- var canonicalConfigSchema = z5.object({
960
- ...rootConfigShape,
961
- env: z5.record(z5.string(), envConfigSchemaInner).optional()
962
- }).strict().superRefine((config, ctx) => {
963
- addSecretsStoreShorthandIssues(ctx, config);
964
- for (const [envName, envConfig] of Object.entries(config.env ?? {})) {
965
- addSecretsStoreShorthandIssues(ctx, {
966
- ...envConfig,
967
- secretsStoreId: envConfig.secretsStoreId ?? config.secretsStoreId
968
- }, ["env", envName]);
969
- }
970
- });
971
- var configSchema = canonicalConfigSchema;
972
-
973
- // src/config/preview.ts
974
- var PREVIEW_SCOPED_NAME_PREFIX = "__DEVFLARE_PREVIEW_SCOPE__:";
975
- function invalidPreviewScopedName(reason) {
976
- throw new Error(`Invalid Devflare preview-scoped value: ${reason}. Recreate it with preview.scope(...) instead of constructing preview markers manually.`);
977
- }
978
- function decodePreviewScopedName(value) {
979
- const payload = value.slice(PREVIEW_SCOPED_NAME_PREFIX.length);
980
- let parsed;
981
- try {
982
- parsed = JSON.parse(payload);
983
- } catch {
984
- invalidPreviewScopedName("the encoded payload is not valid JSON");
985
- }
986
- const baseName = typeof parsed.baseName === "string" ? parsed.baseName : "";
987
- if (!baseName.trim()) {
988
- invalidPreviewScopedName("the encoded payload is missing a non-empty baseName");
989
- }
990
- return {
991
- baseName,
992
- separator: typeof parsed.separator === "string" && parsed.separator.length > 0 ? parsed.separator : "-"
993
- };
994
- }
995
- function normalizePreviewFragment(rawValue) {
996
- let normalized = rawValue.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
997
- if (!normalized) {
998
- normalized = "preview";
999
- }
1000
- if (!/^[a-z]/.test(normalized)) {
1001
- normalized = `b-${normalized}`;
1002
- }
1003
- return normalized;
1004
- }
1005
- function getPreviewIdentifierFromEnv(env2) {
1006
- const explicitIdentifier = env2.DEVFLARE_PREVIEW_IDENTIFIER?.trim();
1007
- if (explicitIdentifier) {
1008
- return {
1009
- identifier: normalizePreviewFragment(explicitIdentifier),
1010
- source: "env-identifier"
1011
- };
1012
- }
1013
- const previewPr = env2.DEVFLARE_PREVIEW_PR?.trim();
1014
- if (previewPr) {
1015
- return {
1016
- identifier: normalizePreviewFragment(`pr-${previewPr}`),
1017
- source: "env-pr"
1018
- };
1019
- }
1020
- const previewBranch = env2.DEVFLARE_PREVIEW_BRANCH?.trim();
1021
- if (previewBranch) {
1022
- return {
1023
- identifier: normalizePreviewFragment(previewBranch),
1024
- source: "env-branch"
1025
- };
1026
- }
1027
- return {
1028
- identifier: undefined,
1029
- source: "none"
1030
- };
1031
- }
1032
- function resolvePreviewIdentifier(options = {}) {
1033
- if (options.identifier?.trim()) {
1034
- return {
1035
- identifier: normalizePreviewFragment(options.identifier),
1036
- source: "identifier"
1037
- };
1038
- }
1039
- const env2 = options.env ?? process.env;
1040
- const envIdentifier = getPreviewIdentifierFromEnv(env2);
1041
- if (envIdentifier.identifier) {
1042
- return envIdentifier;
1043
- }
1044
- return options.environment === "preview" ? {
1045
- identifier: "preview",
1046
- source: "environment"
1047
- } : {
1048
- identifier: undefined,
1049
- source: "none"
1050
- };
1051
- }
1052
- function mapRecordValues(record, mapper) {
1053
- return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, mapper(value)]));
1054
- }
1055
- function isPreviewScopedName(value) {
1056
- return typeof value === "string" && value.startsWith(PREVIEW_SCOPED_NAME_PREFIX);
1057
- }
1058
- function materializePreviewScopedString(value, options = {}) {
1059
- if (!isPreviewScopedName(value)) {
1060
- return value;
1061
- }
1062
- const scoped = decodePreviewScopedName(value);
1063
- const previewIdentifier = resolvePreviewIdentifier(options).identifier;
1064
- return previewIdentifier ? `${scoped.baseName}${scoped.separator}${previewIdentifier}` : scoped.baseName;
1065
- }
1066
- function materializePreviewScopedConfig(config, options = {}) {
1067
- if (!config.bindings) {
1068
- return config;
1069
- }
1070
- const bindings = config.bindings;
1071
- const hasPreviewIdentifier = Boolean(resolvePreviewIdentifier(options).identifier);
1072
- return {
1073
- ...config,
1074
- bindings: {
1075
- ...bindings,
1076
- ...bindings.kv ? {
1077
- kv: mapRecordValues(bindings.kv, (binding) => {
1078
- return typeof binding === "string" ? materializePreviewScopedString(binding, options) : binding;
1079
- })
1080
- } : {},
1081
- ...bindings.d1 ? {
1082
- d1: mapRecordValues(bindings.d1, (binding) => {
1083
- return typeof binding === "string" ? materializePreviewScopedString(binding, options) : binding;
1084
- })
1085
- } : {},
1086
- ...bindings.r2 ? {
1087
- r2: mapRecordValues(bindings.r2, (binding) => {
1088
- return materializePreviewScopedString(binding, options);
1089
- })
1090
- } : {},
1091
- ...bindings.queues ? {
1092
- queues: {
1093
- ...bindings.queues,
1094
- ...bindings.queues.producers ? {
1095
- producers: mapRecordValues(bindings.queues.producers, (queueName) => {
1096
- return materializePreviewScopedString(queueName, options);
1097
- })
1098
- } : {},
1099
- ...bindings.queues.consumers ? {
1100
- consumers: bindings.queues.consumers.map((consumer) => ({
1101
- ...consumer,
1102
- queue: materializePreviewScopedString(consumer.queue, options),
1103
- ...consumer.deadLetterQueue ? {
1104
- deadLetterQueue: materializePreviewScopedString(consumer.deadLetterQueue, options)
1105
- } : {}
1106
- }))
1107
- } : {}
1108
- }
1109
- } : {},
1110
- ...bindings.services ? {
1111
- services: mapRecordValues(bindings.services, (binding) => ({
1112
- ...binding,
1113
- service: materializePreviewScopedString(binding.service, options)
1114
- }))
1115
- } : {},
1116
- ...bindings.vectorize ? {
1117
- vectorize: mapRecordValues(bindings.vectorize, (binding) => ({
1118
- ...binding,
1119
- indexName: materializePreviewScopedString(binding.indexName, options)
1120
- }))
1121
- } : {},
1122
- ...bindings.hyperdrive ? {
1123
- hyperdrive: mapRecordValues(bindings.hyperdrive, (binding) => {
1124
- if (typeof binding === "string") {
1125
- return materializePreviewScopedString(binding, options);
1126
- }
1127
- if (binding && typeof binding === "object" && "name" in binding && typeof binding.name === "string") {
1128
- if (hasPreviewIdentifier && binding.previewId) {
1129
- return {
1130
- id: binding.previewId,
1131
- ...binding.localConnectionString && {
1132
- localConnectionString: binding.localConnectionString
1133
- },
1134
- ...!binding.localConnectionString && binding.previewLocalConnectionString && {
1135
- localConnectionString: binding.previewLocalConnectionString
1136
- }
1137
- };
1138
- }
1139
- return {
1140
- ...binding,
1141
- name: materializePreviewScopedString(binding.name, options)
1142
- };
1143
- }
1144
- return binding;
1145
- })
1146
- } : {},
1147
- ...bindings.browser ? {
1148
- browser: mapRecordValues(bindings.browser, (binding) => {
1149
- return typeof binding === "string" ? materializePreviewScopedString(binding, options) : binding;
1150
- })
1151
- } : {},
1152
- ...bindings.analyticsEngine ? {
1153
- analyticsEngine: mapRecordValues(bindings.analyticsEngine, (binding) => ({
1154
- ...binding,
1155
- dataset: materializePreviewScopedString(binding.dataset, options)
1156
- }))
1157
- } : {}
1158
- }
1159
- };
1160
- }
1161
-
1162
- // src/config/resolve.ts
1163
- function isPlainObject2(value) {
1164
- if (!value || typeof value !== "object" || Array.isArray(value)) {
1165
- return false;
1166
- }
1167
- const prototype = Object.getPrototypeOf(value);
1168
- return prototype === Object.prototype || prototype === null;
1169
- }
1170
- function mergeEnvironmentValue(base, override) {
1171
- if (override === undefined) {
1172
- return base;
1173
- }
1174
- if (Array.isArray(override)) {
1175
- return [...override];
1176
- }
1177
- if (isPlainObject2(override)) {
1178
- const baseObject = isPlainObject2(base) ? base : {};
1179
- const mergedObject = {
1180
- ...baseObject
1181
- };
1182
- for (const [key, value] of Object.entries(override)) {
1183
- mergedObject[key] = mergeEnvironmentValue(baseObject[key], value);
1184
- }
1185
- return mergedObject;
1186
- }
1187
- return override;
1188
- }
1189
- function withNormalizedCompatibilityFlags(config) {
1190
- return {
1191
- ...config,
1192
- compatibilityFlags: normalizeCompatibilityFlags(config.compatibilityFlags)
1193
- };
1194
- }
1195
- function mergeConfigForEnvironment(config, environment) {
1196
- if (!environment || !config.env?.[environment]) {
1197
- return withNormalizedCompatibilityFlags(config);
1198
- }
1199
- const mergedConfig = mergeEnvironmentValue(config, config.env[environment]);
1200
- return withNormalizedCompatibilityFlags(mergedConfig);
1201
- }
1202
- function resolveConfigForEnvironment(config, environment) {
1203
- const mergedConfig = mergeConfigForEnvironment(config, environment);
1204
- return materializePreviewScopedConfig(mergedConfig, {
1205
- environment
1206
- });
1207
- }
1208
-
1209
- // src/config/binding-resolution-helpers.ts
1210
- function normalizeKVNameBinding(bindingConfig) {
1211
- const normalized = normalizeKVBinding(bindingConfig);
1212
- return {
1213
- id: normalized.namespaceId,
1214
- name: normalized.name
1215
- };
1216
- }
1217
- function normalizeD1NameBinding(bindingConfig) {
1218
- const normalized = normalizeD1Binding(bindingConfig);
1219
- return {
1220
- id: normalized.databaseId,
1221
- name: normalized.name
1222
- };
1223
- }
1224
- function normalizeHyperdriveNameBinding(bindingConfig) {
1225
- const normalized = normalizeHyperdriveBinding(bindingConfig);
1226
- return {
1227
- id: normalized.configurationId,
1228
- name: normalized.name
1229
- };
1230
- }
1231
- function materializeIdBindings(bindings, resolveId) {
1232
- return Object.fromEntries(Object.entries(bindings).map(([bindingName, bindingConfig]) => {
1233
- return [bindingName, { id: resolveId(bindingConfig) }];
1234
- }));
1235
- }
1236
- function materializeHyperdriveIdBindings(bindings, idsByName) {
1237
- if (!bindings) {
1238
- return;
1239
- }
1240
- return Object.fromEntries(Object.entries(bindings).map(([bindingName, bindingConfig]) => {
1241
- const normalized = normalizeHyperdriveBinding(bindingConfig);
1242
- return [
1243
- bindingName,
1244
- {
1245
- id: normalized.configurationId ?? idsByName?.get(normalized.name ?? "") ?? normalized.name ?? "",
1246
- ...normalized.localConnectionString && {
1247
- localConnectionString: normalized.localConnectionString
1248
- }
1249
- }
1250
- ];
1251
- }));
1252
- }
1253
- function collectPendingNameBindings(bindings, normalizeBinding) {
1254
- if (!bindings) {
1255
- return [];
1256
- }
1257
- return Object.entries(bindings).map(([bindingName, bindingConfig]) => {
1258
- const normalized = normalizeBinding(bindingConfig);
1259
- return normalized.id ? null : {
1260
- bindingName,
1261
- resourceName: normalized.name ?? ""
1262
- };
1263
- }).filter((binding) => binding !== null);
1264
- }
1265
- function materializeResolvedNameBindings(bindings, normalizeBinding, idsByName) {
1266
- if (!bindings) {
1267
- return;
1268
- }
1269
- return materializeIdBindings(bindings, (bindingConfig) => {
1270
- const normalized = normalizeBinding(bindingConfig);
1271
- return normalized.id ?? idsByName.get(normalized.name ?? "") ?? "";
1272
- });
1273
- }
1274
- function withResolvedIdBindings(resolvedConfig, bindings) {
1275
- return {
1276
- ...resolvedConfig,
1277
- bindings: {
1278
- ...resolvedConfig.bindings,
1279
- ...bindings.kv ? { kv: bindings.kv } : {},
1280
- ...bindings.d1 ? { d1: bindings.d1 } : {},
1281
- ...bindings.hyperdrive ? { hyperdrive: bindings.hyperdrive } : {}
1282
- }
1283
- };
1284
- }
1285
- function formatMissingBindings(missing) {
1286
- return missing.map(({ bindingName, resourceName }) => `${bindingName} → ${resourceName}`).join(", ");
1287
- }
1288
-
1289
- // src/config/loader.ts
1290
- import { existsSync as existsSync2 } from "node:fs";
1291
- import { createRequire } from "node:module";
1292
- import { dirname as dirname2, join as join2, resolve as resolve2 } from "pathe";
1293
-
1294
- // src/config/framework-providers.ts
1295
- import { readFile as readFile2 } from "node:fs/promises";
1296
- import { join } from "pathe";
1297
- var SVELTE_CONFIG_FILES = [
1298
- "svelte.config.js",
1299
- "svelte.config.mjs",
1300
- "svelte.config.ts",
1301
- "svelte.config.cjs"
1302
- ];
1303
- async function readTextIfExists(path) {
1304
- try {
1305
- return await readFile2(path, "utf-8");
1306
- } catch {
1307
- return null;
1308
- }
1309
- }
1310
- async function readPackageDependencies(cwd) {
1311
- const packageJsonText = await readTextIfExists(join(cwd, "package.json"));
1312
- if (!packageJsonText) {
1313
- return null;
1314
- }
1315
- try {
1316
- const packageJson = JSON.parse(packageJsonText);
1317
- return {
1318
- ...packageJson.dependencies ?? {},
1319
- ...packageJson.devDependencies ?? {},
1320
- ...packageJson.peerDependencies ?? {}
1321
- };
1322
- } catch {
1323
- return null;
1324
- }
1325
- }
1326
- async function findFirstExistingTextFile(cwd, candidates) {
1327
- for (const candidate of candidates) {
1328
- const fileText = await readTextIfExists(join(cwd, candidate));
1329
- if (fileText !== null) {
1330
- return fileText;
1331
- }
1332
- }
1333
- return null;
1334
- }
1335
- var svelteKitCloudflareProvider = {
1336
- id: "sveltekit-cloudflare",
1337
- async resolve(context) {
1338
- const dependencies = await readPackageDependencies(context.cwd);
1339
- if (!dependencies?.["@sveltejs/kit"] || !dependencies["@sveltejs/adapter-cloudflare"]) {
1340
- return null;
1341
- }
1342
- const svelteConfigText = await findFirstExistingTextFile(context.cwd, SVELTE_CONFIG_FILES);
1343
- if (!svelteConfigText) {
1344
- return null;
1345
- }
1346
- if (!/@sveltejs\/adapter-cloudflare|adapter-cloudflare/.test(svelteConfigText)) {
1347
- return null;
1348
- }
1349
- return {
1350
- id: this.id,
1351
- config: {
1352
- files: {
1353
- fetch: ".adapter-cloudflare/_worker.js"
1354
- },
1355
- assets: {
1356
- binding: "ASSETS",
1357
- directory: ".adapter-cloudflare"
1358
- }
1359
- }
1360
- };
1361
- }
1362
- };
1363
- var frameworkProviders = [svelteKitCloudflareProvider];
1364
- function hasFrameworkInferenceGap(config) {
1365
- return config.files?.fetch === undefined || config.assets?.directory === undefined || config.assets?.binding === undefined;
1366
- }
1367
- function mergeInferredConfig(config, inferredConfig) {
1368
- const mergedFiles = inferredConfig.files ? {
1369
- ...inferredConfig.files,
1370
- ...config.files ?? {}
1371
- } : config.files;
1372
- const mergedAssets = inferredConfig.assets ? {
1373
- ...inferredConfig.assets,
1374
- ...config.assets ?? {}
1375
- } : config.assets;
1376
- return {
1377
- ...config,
1378
- ...mergedFiles && { files: mergedFiles },
1379
- ...mergedAssets && { assets: mergedAssets }
1380
- };
1381
- }
1382
- async function applyFrameworkConfigProviders(config, context) {
1383
- if (!hasFrameworkInferenceGap(config)) {
1384
- return config;
1385
- }
1386
- for (const provider of frameworkProviders) {
1387
- const resolution = await provider.resolve({
1388
- ...context,
1389
- config
1390
- });
1391
- if (!resolution) {
1392
- continue;
1393
- }
1394
- return mergeInferredConfig(config, resolution.config);
1395
- }
1396
- return config;
1397
- }
1398
-
1399
- // src/config/loader.ts
1400
- var CONFIG_FILES = [
1401
- "devflare.config.ts",
1402
- "devflare.config.mts",
1403
- "devflare.config.js",
1404
- "devflare.config.mjs"
1405
- ];
1406
- function resolveC12Module(cwd) {
1407
- const requireFromCwd = createRequire(join2(cwd, "__devflare__.cjs"));
1408
- try {
1409
- return requireFromCwd("c12");
1410
- } catch {
1411
- return createRequire(import.meta.url)("c12");
1412
- }
1413
- }
1414
- async function resolveConfigDotenvDirectory(cwd, configFile) {
1415
- const explicitConfigPath = resolve2(cwd, configFile);
1416
- if (existsSync2(explicitConfigPath)) {
1417
- return dirname2(explicitConfigPath);
1418
- }
1419
- const discoveredConfigPath = await resolveConfigPath(cwd);
1420
- return discoveredConfigPath ? dirname2(discoveredConfigPath) : cwd;
1421
- }
1422
- async function resolveConfigPath(cwd) {
1423
- for (const file of CONFIG_FILES) {
1424
- const path = join2(cwd, file);
1425
- if (existsSync2(path)) {
1426
- return path;
1427
- }
1428
- }
1429
- return;
1430
- }
1431
- async function loadConfig(options = {}) {
1432
- const cwd = resolve2(options.cwd ?? process.cwd());
1433
- const configFile = options.configFile ?? "devflare.config";
1434
- const { loadConfig: c12LoadConfig } = resolveC12Module(cwd);
1435
- await loadDevflareDotenvIntoProcess(await resolveConfigDotenvDirectory(cwd, configFile));
1436
- const { config, configFile: loadedFile } = await c12LoadConfig({
1437
- name: "devflare",
1438
- cwd,
1439
- configFile,
1440
- defaultConfig: undefined,
1441
- rcFile: false,
1442
- globalRc: false,
1443
- dotenv: false
1444
- });
1445
- if (!config || !loadedFile) {
1446
- throw new ConfigNotFoundError(cwd, configFile);
1447
- }
1448
- const result = configSchema.safeParse(config);
1449
- if (!result.success) {
1450
- throw new ConfigValidationError(result.error.issues, loadedFile);
1451
- }
1452
- return applyFrameworkConfigProviders(result.data, {
1453
- cwd,
1454
- configPath: loadedFile
1455
- });
1456
- }
1457
-
1458
- class ConfigNotFoundError extends Error {
1459
- cwd;
1460
- configFile;
1461
- code = "CONFIG_NOT_FOUND";
1462
- constructor(cwd, configFile) {
1463
- super(`Config file not found in ${cwd}.
1464
- ` + `Expected one of: ${CONFIG_FILES.join(", ")}
1465
- ` + `Run 'devflare init' to create a new config.`);
1466
- this.cwd = cwd;
1467
- this.configFile = configFile;
1468
- this.name = "ConfigNotFoundError";
1469
- }
1470
- }
1471
-
1472
- class ConfigValidationError extends Error {
1473
- issues;
1474
- configFile;
1475
- code = "CONFIG_VALIDATION_ERROR";
1476
- constructor(issues, configFile) {
1477
- const issueMessages = issues.map((i) => ` - ${i.path.join(".")}: ${i.message}`).join(`
1478
- `);
1479
- super(`Invalid config in ${configFile}:
1480
- ${issueMessages}`);
1481
- this.issues = issues;
1482
- this.configFile = configFile;
1483
- this.name = "ConfigValidationError";
1484
- }
1485
- }
1486
-
1487
- // src/config/resource-resolution.ts
1488
- var defaultCloudflareApi = {
1489
- getPrimaryAccount,
1490
- getEffectiveAccountId,
1491
- listKVNamespaces,
1492
- listD1Databases,
1493
- listHyperdrives
1494
- };
1495
-
1496
- class ConfigResourceResolutionError extends Error {
1497
- code = "CONFIG_RESOURCE_RESOLUTION_ERROR";
1498
- constructor(message, cause) {
1499
- super(message);
1500
- this.name = "ConfigResourceResolutionError";
1501
- if (cause !== undefined) {
1502
- this.cause = cause;
1503
- }
1504
- }
1505
- }
1506
- function resolveCloudflareApi(overrides) {
1507
- return {
1508
- ...defaultCloudflareApi,
1509
- ...overrides ?? {}
1510
- };
1511
- }
1512
- async function resolveLookupAccountId(config, options, cloudflareApi) {
1513
- const explicitAccountId = options.accountId ?? config.accountId;
1514
- if (explicitAccountId) {
1515
- return explicitAccountId;
1516
- }
1517
- let primaryAccount;
1518
- try {
1519
- primaryAccount = await cloudflareApi.getPrimaryAccount();
1520
- } catch (error) {
1521
- throw new ConfigResourceResolutionError("Could not resolve Cloudflare-backed resource names because Devflare could not read your Cloudflare accounts. Set accountId in devflare.config.ts, configure a workspace/global default account, or log in with Wrangler.", error);
1522
- }
1523
- if (!primaryAccount) {
1524
- throw new ConfigResourceResolutionError("Could not resolve Cloudflare-backed resource names because no Cloudflare account is available. Set accountId in devflare.config.ts, configure a workspace/global default account, or log in with Wrangler.");
1525
- }
1526
- try {
1527
- const { accountId } = await cloudflareApi.getEffectiveAccountId(primaryAccount.id);
1528
- return accountId;
1529
- } catch (error) {
1530
- throw new ConfigResourceResolutionError(`Could not determine the effective Cloudflare account for name-based resource resolution after selecting primary account ${primaryAccount.id}.`, error);
1531
- }
1532
- }
1533
- async function resolveResourceIdsByName(pendingBindings, options) {
1534
- if (pendingBindings.length === 0) {
1535
- return new Map;
1536
- }
1537
- let resources;
1538
- try {
1539
- resources = await options.listResources();
1540
- } catch (error) {
1541
- throw new ConfigResourceResolutionError(options.listFailureMessage, error);
1542
- }
1543
- const idsByName = new Map(resources.map((resource) => [resource.name, resource.id]));
1544
- const missingBindings = pendingBindings.filter(({ resourceName }) => {
1545
- return !idsByName.has(resourceName);
1546
- });
1547
- if (missingBindings.length > 0) {
1548
- throw new ConfigResourceResolutionError(options.missingFailureMessage(missingBindings));
1549
- }
1550
- return idsByName;
1551
- }
1552
- function resolveConfigForLocalRuntime(config, environment) {
1553
- const resolvedConfig = resolveConfigForEnvironment(config, environment);
1554
- const kvBindings = resolvedConfig.bindings?.kv;
1555
- const d1Bindings = resolvedConfig.bindings?.d1;
1556
- const hyperdriveBindings = resolvedConfig.bindings?.hyperdrive;
1557
- if (!kvBindings && !d1Bindings && !hyperdriveBindings) {
1558
- return brandAsLocalConfig(resolvedConfig);
1559
- }
1560
- const pendingKVNameBindings = collectPendingNameBindings(kvBindings, normalizeKVNameBinding);
1561
- return brandAsLocalConfig(withResolvedIdBindings(resolvedConfig, {
1562
- kv: kvBindings ? materializeIdBindings(kvBindings, getLocalKVNamespaceIdentifier) : undefined,
1563
- d1: d1Bindings ? materializeIdBindings(d1Bindings, getLocalD1DatabaseIdentifier) : undefined,
1564
- hyperdrive: materializeHyperdriveIdBindings(hyperdriveBindings)
1565
- }));
1566
- }
1567
- async function resolveMaterializedConfigResources(resolvedConfig, options = {}) {
1568
- const kvBindings = resolvedConfig.bindings?.kv;
1569
- const d1Bindings = resolvedConfig.bindings?.d1;
1570
- const hyperdriveBindings = resolvedConfig.bindings?.hyperdrive;
1571
- if (!kvBindings && !d1Bindings && !hyperdriveBindings) {
1572
- return brandAsDeployConfig(resolvedConfig);
1573
- }
1574
- const pendingKVNameBindings = collectPendingNameBindings(kvBindings, normalizeKVNameBinding);
1575
- const pendingD1NameBindings = collectPendingNameBindings(d1Bindings, normalizeD1NameBinding);
1576
- const pendingHyperdriveNameBindings = collectPendingNameBindings(hyperdriveBindings, normalizeHyperdriveNameBinding);
1577
- if (pendingKVNameBindings.length === 0 && pendingD1NameBindings.length === 0 && pendingHyperdriveNameBindings.length === 0) {
1578
- return brandAsDeployConfig(withResolvedIdBindings(resolvedConfig, {
1579
- kv: kvBindings ? materializeIdBindings(kvBindings, getLocalKVNamespaceIdentifier) : undefined,
1580
- d1: d1Bindings ? materializeIdBindings(d1Bindings, getLocalD1DatabaseIdentifier) : undefined,
1581
- hyperdrive: materializeHyperdriveIdBindings(hyperdriveBindings)
1582
- }));
1583
- }
1584
- const cloudflareApi = resolveCloudflareApi(options.cloudflare);
1585
- const accountId = await resolveLookupAccountId(resolvedConfig, options, cloudflareApi);
1586
- const namespaceIdsByName = await resolveResourceIdsByName(pendingKVNameBindings, {
1587
- listResources: async () => cloudflareApi.listKVNamespaces(accountId),
1588
- listFailureMessage: `Could not list KV namespaces for Cloudflare account ${accountId} while resolving name-based KV bindings.`,
1589
- missingFailureMessage: (missingBindings) => {
1590
- return `Could not find KV namespace(s) for ${formatMissingBindings(missingBindings)} in Cloudflare account ${accountId}.`;
1591
- }
1592
- });
1593
- const databaseIdsByName = await resolveResourceIdsByName(pendingD1NameBindings, {
1594
- listResources: async () => cloudflareApi.listD1Databases(accountId),
1595
- listFailureMessage: `Could not list D1 databases for Cloudflare account ${accountId} while resolving name-based D1 bindings.`,
1596
- missingFailureMessage: (missingBindings) => {
1597
- return `Could not find D1 database(s) for ${formatMissingBindings(missingBindings)} in Cloudflare account ${accountId}.`;
1598
- }
1599
- });
1600
- const hyperdriveIdsByName = await resolveResourceIdsByName(pendingHyperdriveNameBindings, {
1601
- listResources: async () => cloudflareApi.listHyperdrives(accountId),
1602
- listFailureMessage: `Could not list Hyperdrive configurations for Cloudflare account ${accountId} while resolving name-based Hyperdrive bindings.`,
1603
- missingFailureMessage: (missingBindings) => {
1604
- return `Could not find Hyperdrive configuration(s) for ${formatMissingBindings(missingBindings)} in Cloudflare account ${accountId}.`;
1605
- }
1606
- });
1607
- return brandAsDeployConfig(withResolvedIdBindings(resolvedConfig, {
1608
- kv: materializeResolvedNameBindings(kvBindings, normalizeKVNameBinding, namespaceIdsByName),
1609
- d1: materializeResolvedNameBindings(d1Bindings, normalizeD1NameBinding, databaseIdsByName),
1610
- hyperdrive: materializeHyperdriveIdBindings(hyperdriveBindings, hyperdriveIdsByName)
1611
- }));
1612
- }
1613
- async function resolveConfigResources(config, options = {}) {
1614
- return resolveResources(config, {
1615
- phase: "deploy",
1616
- environment: options.environment,
1617
- preview: {
1618
- environment: options.environment,
1619
- env: options.env,
1620
- identifier: options.identifier
1621
- },
1622
- accountId: options.accountId,
1623
- cloudflare: options.cloudflare
1624
- });
1625
- }
1626
- async function loadResolvedConfig(options = {}) {
1627
- const config = await loadConfig(options);
1628
- return resolveConfigResources(config, options);
1629
- }
1630
-
1631
- // src/config/resolve-phased.ts
1632
- function brandAsLocalConfig(config) {
1633
- return config;
1634
- }
1635
- function brandAsDeployConfig(config) {
1636
- return config;
1637
- }
1638
- async function resolveResources(config, options) {
1639
- const envMerged = mergeConfigForEnvironment(config, options.environment);
1640
- const previewMerged = materializePreviewScopedConfig(envMerged, {
1641
- environment: options.environment,
1642
- ...options.preview
1643
- });
1644
- switch (options.phase) {
1645
- case "build": {
1646
- return previewMerged;
1647
- }
1648
- case "local": {
1649
- const resolved = resolveConfigForLocalRuntime(previewMerged, undefined);
1650
- return resolved;
1651
- }
1652
- case "deploy": {
1653
- if (options.provision) {
1654
- const prepared = await prepareMaterializedConfigResourcesForDeploy(previewMerged, options.preparation ?? {
1655
- accountId: options.accountId,
1656
- cloudflare: options.cloudflare
1657
- });
1658
- return prepared.config;
1659
- }
1660
- const materialized = await resolveMaterializedConfigResources(previewMerged, {
1661
- accountId: options.accountId,
1662
- cloudflare: options.cloudflare
1663
- });
1664
- return materialized;
1665
- }
1666
- }
1667
- }
1668
-
1669
- // src/config/deploy-resources.ts
1670
- var defaultDeployResourcePreparationApi = {
1671
- getPrimaryAccount,
1672
- getEffectiveAccountId,
1673
- listKVNamespaces,
1674
- createKVNamespace,
1675
- listD1Databases,
1676
- createD1Database,
1677
- listR2Buckets,
1678
- createR2Bucket,
1679
- listQueues,
1680
- createQueue,
1681
- listHyperdrives,
1682
- listVectorizeIndexes
1683
- };
1684
- function createEmptyDeployResourceNames() {
1685
- return {
1686
- kv: [],
1687
- d1: [],
1688
- r2: [],
1689
- queues: [],
1690
- vectorize: [],
1691
- hyperdrive: []
1692
- };
1693
- }
1694
- function decorateOrphanError(err, created) {
1695
- const summaryParts = [];
1696
- if (created.kv.length > 0)
1697
- summaryParts.push(`KV: ${created.kv.join(", ")}`);
1698
- if (created.d1.length > 0)
1699
- summaryParts.push(`D1: ${created.d1.join(", ")}`);
1700
- if (created.hyperdrive.length > 0)
1701
- summaryParts.push(`Hyperdrive: ${created.hyperdrive.join(", ")}`);
1702
- if (created.r2.length > 0)
1703
- summaryParts.push(`R2: ${created.r2.join(", ")}`);
1704
- if (created.queues.length > 0)
1705
- summaryParts.push(`Queues: ${created.queues.join(", ")}`);
1706
- if (created.vectorize.length > 0)
1707
- summaryParts.push(`Vectorize: ${created.vectorize.join(", ")}`);
1708
- const base = err instanceof Error ? err : new Error(String(err));
1709
- if (summaryParts.length === 0)
1710
- return base;
1711
- const orphanFooter = `
1712
-
1713
- Deploy preparation failed AFTER provisioning the following Cloudflare resources, ` + `which were left in your account:
1714
- - ${summaryParts.join(`
1715
- - `)}
1716
- ` + `Re-run \`devflare deploy\` after fixing the error to reuse them, or delete them manually if abandoning the deploy.`;
1717
- const decorated = new Error(`${base.message}${orphanFooter}`);
1718
- if ("cause" in base && base.cause !== undefined) {
1719
- decorated.cause = base.cause;
1720
- } else {
1721
- decorated.cause = base;
1722
- }
1723
- return decorated;
1724
- }
1725
- function resolveDeployResourcePreparationApi(overrides) {
1726
- return {
1727
- ...defaultDeployResourcePreparationApi,
1728
- ...overrides ?? {}
1729
- };
1730
- }
1731
- function resolveUniqueNames(values) {
1732
- const names = new Set;
1733
- for (const value of values) {
1734
- const trimmed = value?.trim();
1735
- if (!trimmed) {
1736
- continue;
1737
- }
1738
- names.add(trimmed);
1739
- }
1740
- return [...names];
1741
- }
1742
- function collectQueueNames(config) {
1743
- const queues = config.bindings?.queues;
1744
- if (!queues) {
1745
- return [];
1746
- }
1747
- return resolveUniqueNames([
1748
- ...Object.values(queues.producers ?? {}),
1749
- ...(queues.consumers ?? []).flatMap((consumer) => [consumer.queue, consumer.deadLetterQueue])
1750
- ]);
1751
- }
1752
- function collectVectorizeIndexNames(config) {
1753
- return resolveUniqueNames(Object.values(config.bindings?.vectorize ?? {}).map((binding) => binding.indexName));
1754
- }
1755
- function resolveUniquePendingBindings(pendingBindings) {
1756
- return [...new Map(pendingBindings.map((binding) => [binding.resourceName, binding])).values()];
1757
- }
1758
- async function resolveLookupAccountId2(config, options, cloudflareApi) {
1759
- const envAccountId = typeof process !== "undefined" ? process.env?.CLOUDFLARE_ACCOUNT_ID?.trim() : undefined;
1760
- const explicitAccountId = options.accountId ?? config.accountId ?? (envAccountId || undefined);
1761
- if (explicitAccountId) {
1762
- return explicitAccountId;
1763
- }
1764
- let primaryAccount;
1765
- try {
1766
- primaryAccount = await cloudflareApi.getPrimaryAccount();
1767
- } catch (error) {
1768
- throw new ConfigResourceResolutionError("Could not prepare Cloudflare-backed deploy resources because Devflare could not read your Cloudflare accounts. Set accountId in devflare.config.ts, configure a workspace/global default account, or log in with Wrangler.", error);
1769
- }
1770
- if (!primaryAccount) {
1771
- throw new ConfigResourceResolutionError("Could not prepare Cloudflare-backed deploy resources because no Cloudflare account is available. Set accountId in devflare.config.ts, configure a workspace/global default account, or log in with Wrangler.");
1772
- }
1773
- try {
1774
- const { accountId } = await cloudflareApi.getEffectiveAccountId(primaryAccount.id);
1775
- return accountId;
1776
- } catch (error) {
1777
- throw new ConfigResourceResolutionError(`Could not determine the effective Cloudflare account for deploy-time resource preparation after selecting primary account ${primaryAccount.id}.`, error);
1778
- }
1779
- }
1780
- async function resolveOrCreateResourceIdsByName(pendingBindings, options) {
1781
- if (pendingBindings.length === 0) {
1782
- return {
1783
- idsByName: new Map,
1784
- created: [],
1785
- existing: []
1786
- };
1787
- }
1788
- let resources;
1789
- try {
1790
- resources = await options.listResources();
1791
- } catch (error) {
1792
- throw new ConfigResourceResolutionError(options.listFailureMessage, error);
1793
- }
1794
- const idsByName = new Map(resources.map((resource) => [resource.name, resource.id]));
1795
- const created = [];
1796
- const existing = resolveUniquePendingBindings(pendingBindings).filter(({ resourceName }) => idsByName.has(resourceName)).map(({ resourceName }) => resourceName);
1797
- const missingBindings = resolveUniquePendingBindings(pendingBindings).filter(({ resourceName }) => !idsByName.has(resourceName));
1798
- if (missingBindings.length === 0) {
1799
- return {
1800
- idsByName,
1801
- created,
1802
- existing
1803
- };
1804
- }
1805
- if (!options.createResource) {
1806
- throw new ConfigResourceResolutionError(options.missingFailureMessage(missingBindings));
1807
- }
1808
- for (const missingBinding of missingBindings) {
1809
- try {
1810
- const createdResource = await options.createResource(missingBinding.resourceName);
1811
- idsByName.set(createdResource.name, createdResource.id);
1812
- created.push(createdResource.name);
1813
- } catch (error) {
1814
- throw new ConfigResourceResolutionError(options.createFailureMessage?.(missingBinding.resourceName) ?? `Could not create Cloudflare resource "${missingBinding.resourceName}" during deploy preparation.`, error);
1815
- }
1816
- }
1817
- return {
1818
- idsByName,
1819
- created,
1820
- existing
1821
- };
1822
- }
1823
- async function ensureNamedResourcesExist(resourceNames, options) {
1824
- if (resourceNames.length === 0) {
1825
- return {
1826
- created: [],
1827
- existing: []
1828
- };
1829
- }
1830
- let resources;
1831
- try {
1832
- resources = await options.listResources();
1833
- } catch (error) {
1834
- throw new ConfigResourceResolutionError(options.listFailureMessage, error);
1835
- }
1836
- const existingNames = new Set(resources.map((resource) => resource.name));
1837
- const existing = resourceNames.filter((resourceName) => existingNames.has(resourceName));
1838
- const missingNames = resourceNames.filter((resourceName) => !existingNames.has(resourceName));
1839
- const created = [];
1840
- if (missingNames.length === 0) {
1841
- return {
1842
- created,
1843
- existing
1844
- };
1845
- }
1846
- if (!options.createResource) {
1847
- throw new ConfigResourceResolutionError(options.missingFailureMessage(missingNames));
1848
- }
1849
- for (const resourceName of missingNames) {
1850
- try {
1851
- const createdResource = await options.createResource(resourceName);
1852
- created.push(createdResource.name);
1853
- } catch (error) {
1854
- throw new ConfigResourceResolutionError(options.createFailureMessage?.(resourceName) ?? `Could not create Cloudflare resource "${resourceName}" during deploy preparation.`, error);
1855
- }
1856
- }
1857
- return {
1858
- created,
1859
- existing
1860
- };
1861
- }
1862
- async function prepareMaterializedConfigResourcesForDeploy(resolvedConfig, options = {}) {
1863
- const created = createEmptyDeployResourceNames();
1864
- const existing = createEmptyDeployResourceNames();
1865
- const warnings = [];
1866
- const kvBindings = resolvedConfig.bindings?.kv;
1867
- const d1Bindings = resolvedConfig.bindings?.d1;
1868
- const hyperdriveBindings = resolvedConfig.bindings?.hyperdrive;
1869
- const r2Names = resolveUniqueNames(Object.values(resolvedConfig.bindings?.r2 ?? {}));
1870
- const queueNames = collectQueueNames(resolvedConfig);
1871
- const vectorizeNames = collectVectorizeIndexNames(resolvedConfig);
1872
- if (!kvBindings && !d1Bindings && !hyperdriveBindings && r2Names.length === 0 && queueNames.length === 0 && vectorizeNames.length === 0) {
1873
- return {
1874
- config: brandAsDeployConfig(resolvedConfig),
1875
- created,
1876
- existing,
1877
- warnings
1878
- };
1879
- }
1880
- const pendingKVNameBindings = collectPendingNameBindings(kvBindings, normalizeKVNameBinding);
1881
- const pendingD1NameBindings = collectPendingNameBindings(d1Bindings, normalizeD1NameBinding);
1882
- const pendingHyperdriveNameBindings = collectPendingNameBindings(hyperdriveBindings, normalizeHyperdriveNameBinding);
1883
- if (pendingKVNameBindings.length === 0 && pendingD1NameBindings.length === 0 && pendingHyperdriveNameBindings.length === 0 && r2Names.length === 0 && queueNames.length === 0 && vectorizeNames.length === 0) {
1884
- return {
1885
- config: brandAsDeployConfig(withResolvedIdBindings(resolvedConfig, {
1886
- kv: kvBindings ? materializeIdBindings(kvBindings, getLocalKVNamespaceIdentifier) : undefined,
1887
- d1: d1Bindings ? materializeIdBindings(d1Bindings, getLocalD1DatabaseIdentifier) : undefined,
1888
- hyperdrive: materializeHyperdriveIdBindings(hyperdriveBindings)
1889
- })),
1890
- created,
1891
- existing,
1892
- warnings
1893
- };
1894
- }
1895
- const cloudflareApi = resolveDeployResourcePreparationApi(options.cloudflare);
1896
- const accountId = await resolveLookupAccountId2(resolvedConfig, options, cloudflareApi);
1897
- if (options.describeOnly) {
1898
- cloudflareApi.createKVNamespace = async (_acc, name) => ({
1899
- id: `<would-create:${name}>`,
1900
- name
1901
- });
1902
- cloudflareApi.createD1Database = async (_acc, name) => ({
1903
- id: `<would-create:${name}>`,
1904
- name,
1905
- version: "",
1906
- tableCount: 0,
1907
- sizeBytes: 0
1908
- });
1909
- cloudflareApi.createR2Bucket = async (_acc, name) => ({
1910
- name
1911
- });
1912
- cloudflareApi.createQueue = async (_acc, name) => ({
1913
- id: `<would-create:${name}>`,
1914
- name
1915
- });
1916
- }
1917
- try {
1918
- const hyperdriveIdsByName = await resolveOrCreateResourceIdsByName(pendingHyperdriveNameBindings, {
1919
- listResources: async () => cloudflareApi.listHyperdrives(accountId),
1920
- listFailureMessage: `Could not list Hyperdrive configurations for Cloudflare account ${accountId} while preparing deploy resources.`,
1921
- missingFailureMessage: (missingBindings) => {
1922
- return `Could not find Hyperdrive configuration(s) for ${formatMissingBindings(missingBindings)} in Cloudflare account ${accountId}. Cloudflare does not expose a create API that Devflare can use from only a binding name, so create the Hyperdrive config first or configure the binding with an explicit id.`;
1923
- }
1924
- });
1925
- created.hyperdrive.push(...hyperdriveIdsByName.created);
1926
- existing.hyperdrive.push(...hyperdriveIdsByName.existing);
1927
- const vectorizeState = await ensureNamedResourcesExist(vectorizeNames, {
1928
- listResources: async () => cloudflareApi.listVectorizeIndexes(accountId),
1929
- listFailureMessage: `Could not list Vectorize indexes for Cloudflare account ${accountId} while preparing deploy resources.`,
1930
- missingFailureMessage: (missingNames) => {
1931
- return `Could not find Vectorize index(es) ${missingNames.join(", ")} in Cloudflare account ${accountId}. Devflare can only auto-provision preview-scoped Vectorize indexes by cloning an existing base index; for normal deploys create the index first.`;
1932
- }
1933
- });
1934
- created.vectorize.push(...vectorizeState.created);
1935
- existing.vectorize.push(...vectorizeState.existing);
1936
- const namespaceIdsByName = await resolveOrCreateResourceIdsByName(pendingKVNameBindings, {
1937
- listResources: async () => cloudflareApi.listKVNamespaces(accountId),
1938
- createResource: async (resourceName) => cloudflareApi.createKVNamespace(accountId, resourceName),
1939
- listFailureMessage: `Could not list KV namespaces for Cloudflare account ${accountId} while preparing deploy resources.`,
1940
- missingFailureMessage: (missingBindings) => {
1941
- return `Could not find KV namespace(s) for ${formatMissingBindings(missingBindings)} in Cloudflare account ${accountId}.`;
1942
- },
1943
- createFailureMessage: (resourceName) => {
1944
- return `Could not create KV namespace "${resourceName}" in Cloudflare account ${accountId} during deploy preparation.`;
1945
- }
1946
- });
1947
- created.kv.push(...namespaceIdsByName.created);
1948
- existing.kv.push(...namespaceIdsByName.existing);
1949
- const databaseIdsByName = await resolveOrCreateResourceIdsByName(pendingD1NameBindings, {
1950
- listResources: async () => cloudflareApi.listD1Databases(accountId),
1951
- createResource: async (resourceName) => cloudflareApi.createD1Database(accountId, resourceName),
1952
- listFailureMessage: `Could not list D1 databases for Cloudflare account ${accountId} while preparing deploy resources.`,
1953
- missingFailureMessage: (missingBindings) => {
1954
- return `Could not find D1 database(s) for ${formatMissingBindings(missingBindings)} in Cloudflare account ${accountId}.`;
1955
- },
1956
- createFailureMessage: (resourceName) => {
1957
- return `Could not create D1 database "${resourceName}" in Cloudflare account ${accountId} during deploy preparation.`;
1958
- }
1959
- });
1960
- created.d1.push(...databaseIdsByName.created);
1961
- existing.d1.push(...databaseIdsByName.existing);
1962
- const r2State = await ensureNamedResourcesExist(r2Names, {
1963
- listResources: async () => cloudflareApi.listR2Buckets(accountId),
1964
- createResource: async (resourceName) => cloudflareApi.createR2Bucket(accountId, resourceName),
1965
- listFailureMessage: `Could not list R2 buckets for Cloudflare account ${accountId} while preparing deploy resources.`,
1966
- missingFailureMessage: (missingNames) => {
1967
- return `Could not find R2 bucket(s) ${missingNames.join(", ")} in Cloudflare account ${accountId}.`;
1968
- },
1969
- createFailureMessage: (resourceName) => {
1970
- return `Could not create R2 bucket "${resourceName}" in Cloudflare account ${accountId} during deploy preparation.`;
1971
- }
1972
- });
1973
- created.r2.push(...r2State.created);
1974
- existing.r2.push(...r2State.existing);
1975
- const queueState = await ensureNamedResourcesExist(queueNames, {
1976
- listResources: async () => cloudflareApi.listQueues(accountId),
1977
- createResource: async (resourceName) => cloudflareApi.createQueue(accountId, resourceName),
1978
- listFailureMessage: `Could not list Queues for Cloudflare account ${accountId} while preparing deploy resources.`,
1979
- missingFailureMessage: (missingNames) => {
1980
- return `Could not find Queue(s) ${missingNames.join(", ")} in Cloudflare account ${accountId}.`;
1981
- },
1982
- createFailureMessage: (resourceName) => {
1983
- return `Could not create Queue "${resourceName}" in Cloudflare account ${accountId} during deploy preparation.`;
1984
- }
1985
- });
1986
- created.queues.push(...queueState.created);
1987
- existing.queues.push(...queueState.existing);
1988
- const config = withResolvedIdBindings(resolvedConfig, {
1989
- kv: kvBindings ? pendingKVNameBindings.length > 0 ? materializeResolvedNameBindings(kvBindings, normalizeKVNameBinding, namespaceIdsByName.idsByName) : materializeIdBindings(kvBindings, getLocalKVNamespaceIdentifier) : undefined,
1990
- d1: d1Bindings ? pendingD1NameBindings.length > 0 ? materializeResolvedNameBindings(d1Bindings, normalizeD1NameBinding, databaseIdsByName.idsByName) : materializeIdBindings(d1Bindings, getLocalD1DatabaseIdentifier) : undefined,
1991
- hyperdrive: hyperdriveBindings ? pendingHyperdriveNameBindings.length > 0 ? materializeHyperdriveIdBindings(hyperdriveBindings, hyperdriveIdsByName.idsByName) : materializeHyperdriveIdBindings(hyperdriveBindings) : undefined
1992
- });
1993
- return {
1994
- config: brandAsDeployConfig(config),
1995
- created,
1996
- existing,
1997
- warnings
1998
- };
1999
- } catch (err) {
2000
- throw decorateOrphanError(err, created);
2001
- }
2002
- }
2003
- async function prepareConfigResourcesForDeploy(config, options = {}) {
2004
- const resolvedConfig = await resolveResources(config, {
2005
- phase: "build",
2006
- environment: options.environment,
2007
- preview: {
2008
- environment: options.environment,
2009
- env: options.env,
2010
- identifier: options.identifier
2011
- }
2012
- });
2013
- return prepareMaterializedConfigResourcesForDeploy(resolvedConfig, {
2014
- accountId: options.accountId,
2015
- cloudflare: options.cloudflare,
2016
- describeOnly: options.describeOnly
2017
- });
2018
- }
2019
-
2020
- export { getDevflareDotenvPaths, EnvVarResolutionError, resolveConfigEnvVars, normalizeCompatibilityFlags, browserBindingSchema, getSingleBrowserBindingName, normalizeDOBinding, normalizeD1Binding, normalizeKVBinding, normalizeHyperdriveBinding, normalizeMtlsCertificateBinding, normalizeDispatchNamespaceBinding, normalizeWorkflowBinding, normalizePipelineBinding, normalizeImagesBinding, normalizeMediaBinding, normalizeArtifactsBinding, normalizeSecretsStoreBinding, getLocalKVNamespaceIdentifier, getLocalD1DatabaseIdentifier, configSchema, resolvePreviewIdentifier, isPreviewScopedName, materializePreviewScopedString, materializePreviewScopedConfig, mergeConfigForEnvironment, resolveConfigForEnvironment, prepareConfigResourcesForDeploy, resolveResources, ConfigResourceResolutionError, loadResolvedConfig, resolveConfigPath, loadConfig, ConfigNotFoundError };