wrangler 0.0.0-e043479 → 0.0.0-e09abbc

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 (208) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +33 -14
  3. package/bin/wrangler.js +160 -28
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5354 -0
  6. package/package.json +166 -136
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +3942 -2178
  10. package/src/__tests__/dev.test.tsx +1191 -235
  11. package/src/__tests__/guess-worker-format.test.ts +76 -57
  12. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  13. package/src/__tests__/helpers/mock-account-id.ts +26 -22
  14. package/src/__tests__/helpers/mock-bin.ts +20 -20
  15. package/src/__tests__/helpers/mock-cfetch.ts +96 -92
  16. package/src/__tests__/helpers/mock-console.ts +59 -32
  17. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  18. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  19. package/src/__tests__/helpers/mock-istty.ts +74 -0
  20. package/src/__tests__/helpers/mock-kv.ts +28 -35
  21. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  22. package/src/__tests__/helpers/mock-process.ts +39 -0
  23. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  24. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  25. package/src/__tests__/helpers/run-in-tmp.ts +29 -20
  26. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  27. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  28. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  29. package/src/__tests__/https-options.test.ts +163 -0
  30. package/src/__tests__/index.test.ts +246 -850
  31. package/src/__tests__/init.test.ts +1992 -0
  32. package/src/__tests__/jest.setup.ts +85 -34
  33. package/src/__tests__/kv.test.ts +1402 -1139
  34. package/src/__tests__/logger.test.ts +141 -0
  35. package/src/__tests__/metrics.test.ts +445 -0
  36. package/src/__tests__/package-manager.test.ts +312 -165
  37. package/src/__tests__/pages.test.ts +1261 -0
  38. package/src/__tests__/parse.test.ts +253 -245
  39. package/src/__tests__/publish.test.ts +6611 -2079
  40. package/src/__tests__/pubsub.test.ts +367 -0
  41. package/src/__tests__/r2.test.ts +184 -149
  42. package/src/__tests__/route.test.ts +45 -0
  43. package/src/__tests__/secret.test.ts +474 -407
  44. package/src/__tests__/tail.test.ts +565 -431
  45. package/src/__tests__/test-old-node-version.js +31 -0
  46. package/src/__tests__/user.test.ts +143 -0
  47. package/src/__tests__/whoami.test.tsx +219 -75
  48. package/src/__tests__/worker-namespace.test.ts +327 -0
  49. package/src/abort.d.ts +3 -0
  50. package/src/api/dev.ts +86 -0
  51. package/src/api/index.ts +1 -0
  52. package/src/bundle-reporter.tsx +29 -0
  53. package/src/bundle.ts +196 -93
  54. package/src/cfetch/index.ts +83 -66
  55. package/src/cfetch/internal.ts +100 -84
  56. package/src/cli.ts +22 -14
  57. package/src/config/README.md +7 -7
  58. package/src/config/config.ts +223 -242
  59. package/src/config/diagnostics.ts +61 -61
  60. package/src/config/environment.ts +404 -256
  61. package/src/config/index.ts +218 -32
  62. package/src/config/validation-helpers.ts +436 -222
  63. package/src/config/validation.ts +1642 -907
  64. package/src/config-cache.ts +84 -0
  65. package/src/create-worker-preview.ts +255 -0
  66. package/src/create-worker-upload-form.ts +263 -0
  67. package/src/dev/dev-vars.ts +36 -0
  68. package/src/dev/dev.tsx +452 -0
  69. package/src/dev/local.tsx +373 -0
  70. package/src/dev/remote.tsx +386 -0
  71. package/src/dev/use-esbuild.ts +150 -0
  72. package/src/dev.tsx +576 -943
  73. package/src/dialogs.tsx +115 -57
  74. package/src/durable.ts +102 -0
  75. package/src/entry.ts +308 -37
  76. package/src/environment-variables.ts +25 -23
  77. package/src/errors.ts +11 -0
  78. package/src/faye-websocket.d.ts +6 -0
  79. package/src/generate.ts +33 -0
  80. package/src/git-client.ts +42 -0
  81. package/src/global-wrangler-config-path.ts +26 -0
  82. package/src/https-options.ts +127 -0
  83. package/src/index.tsx +1910 -2241
  84. package/src/init.ts +549 -0
  85. package/src/inspect.ts +603 -550
  86. package/src/intl-polyfill.d.ts +139 -0
  87. package/src/is-interactive.ts +12 -0
  88. package/src/kv.ts +430 -0
  89. package/src/logger.ts +73 -0
  90. package/src/metrics/index.ts +4 -0
  91. package/src/metrics/is-ci.ts +14 -0
  92. package/src/metrics/metrics-config.ts +239 -0
  93. package/src/metrics/metrics-dispatcher.ts +95 -0
  94. package/src/metrics/send-event.ts +92 -0
  95. package/src/miniflare-cli/README.md +30 -0
  96. package/src/miniflare-cli/assets.ts +543 -0
  97. package/src/miniflare-cli/enum-keys.ts +17 -0
  98. package/src/miniflare-cli/index.ts +85 -0
  99. package/src/miniflare-cli/request-context.ts +40 -0
  100. package/src/module-collection.ts +234 -146
  101. package/src/open-in-browser.ts +10 -6
  102. package/src/package-manager.ts +183 -90
  103. package/src/pages/build.tsx +204 -0
  104. package/src/pages/constants.ts +7 -0
  105. package/src/pages/deployments.tsx +106 -0
  106. package/src/pages/dev.tsx +401 -0
  107. package/src/pages/functions/buildPlugin.ts +105 -0
  108. package/src/pages/functions/buildWorker.ts +151 -0
  109. package/src/pages/functions/filepath-routing.test.ts +234 -0
  110. package/src/pages/functions/filepath-routing.ts +189 -0
  111. package/src/pages/functions/identifiers.ts +78 -0
  112. package/src/pages/functions/routes.ts +151 -0
  113. package/src/pages/index.tsx +84 -0
  114. package/src/pages/projects.tsx +163 -0
  115. package/src/pages/publish.tsx +338 -0
  116. package/src/pages/types.ts +40 -0
  117. package/src/pages/upload.tsx +396 -0
  118. package/src/pages/utils.ts +12 -0
  119. package/src/parse.ts +224 -121
  120. package/src/paths.ts +6 -6
  121. package/src/preview.ts +31 -0
  122. package/src/proxy.ts +413 -313
  123. package/src/publish.ts +773 -343
  124. package/src/pubsub/index.ts +286 -0
  125. package/src/pubsub/pubsub-commands.tsx +623 -0
  126. package/src/r2.ts +19 -19
  127. package/src/selfsigned.d.ts +29 -0
  128. package/src/sites.tsx +285 -151
  129. package/src/tail/filters.ts +108 -108
  130. package/src/tail/index.ts +217 -217
  131. package/src/tail/printing.ts +51 -46
  132. package/src/update-check.ts +19 -0
  133. package/src/user/choose-account.tsx +69 -0
  134. package/src/user/env-vars.ts +46 -0
  135. package/src/user/generate-auth-url.ts +33 -0
  136. package/src/user/generate-random-state.ts +16 -0
  137. package/src/user/index.ts +3 -0
  138. package/src/user/user.tsx +1171 -0
  139. package/src/whoami.tsx +63 -41
  140. package/src/worker-namespace.ts +206 -0
  141. package/src/worker.ts +191 -0
  142. package/src/zones.ts +76 -0
  143. package/templates/checked-fetch.js +17 -0
  144. package/templates/gitignore +171 -0
  145. package/templates/new-worker-scheduled.js +17 -0
  146. package/templates/new-worker-scheduled.ts +32 -0
  147. package/templates/new-worker.js +3 -3
  148. package/templates/new-worker.ts +18 -3
  149. package/templates/no-op-worker.js +10 -0
  150. package/templates/pages-shim.ts +9 -0
  151. package/templates/pages-template-plugin.ts +155 -0
  152. package/templates/pages-template-worker.ts +161 -0
  153. package/templates/static-asset-facade.js +38 -36
  154. package/templates/tsconfig.json +95 -95
  155. package/wrangler-dist/cli.d.ts +327 -0
  156. package/wrangler-dist/cli.js +94947 -111199
  157. package/pages/functions/buildWorker.ts +0 -62
  158. package/pages/functions/filepath-routing.test.ts +0 -123
  159. package/pages/functions/filepath-routing.ts +0 -178
  160. package/pages/functions/identifiers.ts +0 -78
  161. package/pages/functions/routes.ts +0 -151
  162. package/pages/functions/template-worker.ts +0 -130
  163. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  164. package/src/__tests__/helpers/mock-user.ts +0 -27
  165. package/src/__tests__/logout.test.ts +0 -50
  166. package/src/__tests__/sentry.test.ts +0 -146
  167. package/src/api/form_data.ts +0 -217
  168. package/src/api/preview.ts +0 -147
  169. package/src/api/worker.ts +0 -186
  170. package/src/guess-worker-format.ts +0 -68
  171. package/src/kv.tsx +0 -339
  172. package/src/pages.tsx +0 -1045
  173. package/src/reporting.ts +0 -115
  174. package/src/user.tsx +0 -1063
  175. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  176. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  177. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  178. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  179. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  180. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  181. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  182. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  183. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  184. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  185. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  186. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  187. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  188. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  189. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  190. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  191. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  192. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  193. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  194. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  195. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  196. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  197. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  198. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  199. package/vendor/wrangler-mime/LICENSE +0 -21
  200. package/vendor/wrangler-mime/Mime.js +0 -97
  201. package/vendor/wrangler-mime/README.md +0 -187
  202. package/vendor/wrangler-mime/cli.js +0 -46
  203. package/vendor/wrangler-mime/index.js +0 -4
  204. package/vendor/wrangler-mime/lite.js +0 -4
  205. package/vendor/wrangler-mime/package.json +0 -52
  206. package/vendor/wrangler-mime/types/other.js +0 -1
  207. package/vendor/wrangler-mime/types/standard.js +0 -1
  208. package/wrangler-dist/cli.js.map +0 -7
@@ -2,28 +2,41 @@ import path from "node:path";
2
2
  import TOML from "@iarna/toml";
3
3
  import { Diagnostics } from "./diagnostics";
4
4
  import {
5
- deprecated,
6
- experimental,
7
- hasProperty,
8
- inheritable,
9
- isBoolean,
10
- isObjectWith,
11
- isOneOf,
12
- isOptionalProperty,
13
- isRequiredProperty,
14
- isString,
15
- isStringArray,
16
- validateAdditionalProperties,
17
- notInheritable,
18
- validateOptionalProperty,
19
- validateOptionalTypedArray,
20
- validateRequiredProperty,
21
- validateTypedArray,
5
+ deprecated,
6
+ experimental,
7
+ hasProperty,
8
+ inheritable,
9
+ isBoolean,
10
+ isObjectWith,
11
+ isOneOf,
12
+ isOptionalProperty,
13
+ isRequiredProperty,
14
+ isString,
15
+ isStringArray,
16
+ validateAdditionalProperties,
17
+ notInheritable,
18
+ validateOptionalProperty,
19
+ validateOptionalTypedArray,
20
+ validateRequiredProperty,
21
+ validateTypedArray,
22
+ all,
23
+ isMutuallyExclusiveWith,
24
+ inheritableInLegacyEnvironments,
25
+ appendEnvName,
26
+ getBindingNames,
27
+ isValidName,
22
28
  } from "./validation-helpers";
23
- import type { Config, DeprecatedUpload, RawConfig } from "./config";
24
- import type { RawEnvironment, Environment, Rule } from "./environment";
29
+ import type { Config, DevConfig, RawConfig, RawDevConfig } from "./config";
30
+ import type {
31
+ RawEnvironment,
32
+ DeprecatedUpload,
33
+ Environment,
34
+ Rule,
35
+ } from "./environment";
25
36
  import type { ValidatorFn } from "./validation-helpers";
26
37
 
38
+ const ENGLISH = new Intl.ListFormat("en");
39
+
27
40
  /**
28
41
  * Validate the given `rawConfig` object that was loaded from `configPath`.
29
42
  *
@@ -33,821 +46,1368 @@ import type { ValidatorFn } from "./validation-helpers";
33
46
  * Any errors or warnings from the validation are available in the returned `diagnostics` object.
34
47
  */
35
48
  export function normalizeAndValidateConfig(
36
- rawConfig: RawConfig,
37
- configPath: string | undefined
49
+ rawConfig: RawConfig,
50
+ configPath: string | undefined,
51
+ args: unknown
38
52
  ): {
39
- config: Config;
40
- diagnostics: Diagnostics;
53
+ config: Config;
54
+ diagnostics: Diagnostics;
41
55
  } {
42
- const diagnostics = new Diagnostics(
43
- `Processing ${
44
- configPath ? path.relative(process.cwd(), configPath) : "wrangler"
45
- } configuration:`
46
- );
47
-
48
- deprecated(
49
- diagnostics,
50
- rawConfig,
51
- "type",
52
- "DO NOT USE THIS. Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
53
- true
54
- );
55
-
56
- deprecated(
57
- diagnostics,
58
- rawConfig,
59
- "webpack_config",
60
- "DO NOT USE THIS. Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
61
- true
62
- );
63
-
64
- const { deprecatedUpload, ...build } = normalizeAndValidateBuild(
65
- diagnostics,
66
- rawConfig,
67
- rawConfig.build ?? {}
68
- );
69
-
70
- validateOptionalProperty(
71
- diagnostics,
72
- "",
73
- "legacy_env",
74
- rawConfig.legacy_env,
75
- "boolean"
76
- );
77
-
78
- // Process the top-level default environment configuration.
79
- const config: Config = {
80
- configPath,
81
- main: normalizeAndValidateMainField(
82
- diagnostics,
83
- configPath,
84
- rawConfig.main,
85
- deprecatedUpload
86
- ),
87
- // TODO: set the default to false to turn on service environments as the default
88
- legacy_env: rawConfig.legacy_env ?? true,
89
- ...normalizeAndValidateEnvironment(
90
- diagnostics,
91
- rawConfig,
92
- deprecatedUpload.rules
93
- ),
94
- env: {}, // Will be filled below by `normalizeAndValidateEnvironment()`.
95
- dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}),
96
- migrations: normalizeAndValidateMigrations(
97
- diagnostics,
98
- rawConfig.migrations ?? []
99
- ),
100
- site: normalizeAndValidateSite(diagnostics, rawConfig.site),
101
- wasm_modules: normalizeAndValidateModulePaths(
102
- diagnostics,
103
- configPath,
104
- "wasm_modules",
105
- rawConfig.wasm_modules
106
- ),
107
- text_blobs: normalizeAndValidateModulePaths(
108
- diagnostics,
109
- configPath,
110
- "text_blobs",
111
- rawConfig.text_blobs
112
- ),
113
- build,
114
- };
115
-
116
- // Process each of the specific environment configurations.
117
- if (rawConfig.env !== undefined) {
118
- for (const envName of Object.keys(rawConfig.env)) {
119
- const envDiagnostics = new Diagnostics(
120
- `"env.${envName}" environment configuration`
121
- );
122
- const environment = normalizeAndValidateEnvironment(
123
- envDiagnostics,
124
- rawConfig.env[envName] as RawEnvironment,
125
- deprecatedUpload.rules,
126
- envName,
127
- config,
128
- rawConfig
129
- );
130
- config.env[envName] = environment;
131
- diagnostics.addChild(envDiagnostics);
132
- }
133
- }
134
-
135
- validateAdditionalProperties(
136
- diagnostics,
137
- "top-level",
138
- Object.keys(rawConfig),
139
- Object.keys(config)
140
- );
141
-
142
- return { config, diagnostics };
56
+ const diagnostics = new Diagnostics(
57
+ `Processing ${
58
+ configPath ? path.relative(process.cwd(), configPath) : "wrangler"
59
+ } configuration:`
60
+ );
61
+
62
+ deprecated(
63
+ diagnostics,
64
+ rawConfig,
65
+ "miniflare",
66
+ "Wrangler does not use configuration in the `miniflare` section. Unless you are using Miniflare directly you can remove this section.",
67
+ true,
68
+ "😶 Ignored"
69
+ );
70
+
71
+ deprecated(
72
+ diagnostics,
73
+ rawConfig,
74
+ "type",
75
+ "Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
76
+ true,
77
+ "😶 Ignored"
78
+ );
79
+
80
+ deprecated(
81
+ diagnostics,
82
+ rawConfig,
83
+ "webpack_config",
84
+ "Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
85
+ true,
86
+ "😶 Ignored"
87
+ );
88
+
89
+ validateOptionalProperty(
90
+ diagnostics,
91
+ "",
92
+ "legacy_env",
93
+ rawConfig.legacy_env,
94
+ "boolean"
95
+ );
96
+
97
+ validateOptionalProperty(
98
+ diagnostics,
99
+ "",
100
+ "send_metrics",
101
+ rawConfig.send_metrics,
102
+ "boolean"
103
+ );
104
+
105
+ // TODO: set the default to false to turn on service environments as the default
106
+ const isLegacyEnv =
107
+ (args as { "legacy-env": boolean | undefined })["legacy-env"] ??
108
+ rawConfig.legacy_env ??
109
+ true;
110
+
111
+ // TODO: remove this once service environments goes GA.
112
+ if (!isLegacyEnv) {
113
+ diagnostics.warnings.push(
114
+ "Experimental: Service environments are in beta, and their behaviour is guaranteed to change in the future. DO NOT USE IN PRODUCTION."
115
+ );
116
+ }
117
+
118
+ const topLevelEnv = normalizeAndValidateEnvironment(
119
+ diagnostics,
120
+ configPath,
121
+ rawConfig
122
+ );
123
+
124
+ //TODO: find a better way to define the type of Args that can be passed to the normalizeAndValidateConfig()
125
+ const envName = (args as { env: string | undefined }).env;
126
+
127
+ let activeEnv = topLevelEnv;
128
+ if (envName !== undefined) {
129
+ const envDiagnostics = new Diagnostics(
130
+ `"env.${envName}" environment configuration`
131
+ );
132
+ const rawEnv = rawConfig.env?.[envName];
133
+ if (rawEnv !== undefined) {
134
+ activeEnv = normalizeAndValidateEnvironment(
135
+ envDiagnostics,
136
+ configPath,
137
+ rawEnv,
138
+ envName,
139
+ topLevelEnv,
140
+ isLegacyEnv,
141
+ rawConfig
142
+ );
143
+ diagnostics.addChild(envDiagnostics);
144
+ } else {
145
+ // An environment was specified, but no configuration for it was found.
146
+ // To cover any legacy environment cases, where the `envName` is used,
147
+ // Let's create a fake active environment with the specified `envName`.
148
+ activeEnv = normalizeAndValidateEnvironment(
149
+ envDiagnostics,
150
+ configPath,
151
+ {},
152
+ envName,
153
+ topLevelEnv,
154
+ isLegacyEnv,
155
+ rawConfig
156
+ );
157
+ const envNames = rawConfig.env
158
+ ? `The available configured environment names are: ${JSON.stringify(
159
+ Object.keys(rawConfig.env)
160
+ )}\n`
161
+ : "";
162
+ const message =
163
+ `No environment found in configuration with name "${envName}".\n` +
164
+ `Before using \`--env=${envName}\` there should be an equivalent environment section in the configuration.\n` +
165
+ `${envNames}\n` +
166
+ `Consider adding an environment configuration section to the wrangler.toml file:\n` +
167
+ "```\n[env." +
168
+ envName +
169
+ "]\n```\n";
170
+
171
+ if (envNames.length > 0) {
172
+ diagnostics.errors.push(message);
173
+ } else {
174
+ // Only warn (rather than error) if there are not actually any environments configured in wrangler.toml.
175
+ diagnostics.warnings.push(message);
176
+ }
177
+ }
178
+ }
179
+
180
+ // Process the top-level default environment configuration.
181
+ const config: Config = {
182
+ configPath,
183
+ legacy_env: isLegacyEnv,
184
+ send_metrics: rawConfig.send_metrics,
185
+ ...activeEnv,
186
+ dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}),
187
+ migrations: normalizeAndValidateMigrations(
188
+ diagnostics,
189
+ rawConfig.migrations ?? [],
190
+ activeEnv.durable_objects
191
+ ),
192
+ site: normalizeAndValidateSite(
193
+ diagnostics,
194
+ configPath,
195
+ rawConfig,
196
+ activeEnv.main
197
+ ),
198
+ assets: normalizeAndValidateAssets(diagnostics, configPath, rawConfig),
199
+ wasm_modules: normalizeAndValidateModulePaths(
200
+ diagnostics,
201
+ configPath,
202
+ "wasm_modules",
203
+ rawConfig.wasm_modules
204
+ ),
205
+ text_blobs: normalizeAndValidateModulePaths(
206
+ diagnostics,
207
+ configPath,
208
+ "text_blobs",
209
+ rawConfig.text_blobs
210
+ ),
211
+ data_blobs: normalizeAndValidateModulePaths(
212
+ diagnostics,
213
+ configPath,
214
+ "data_blobs",
215
+ rawConfig.data_blobs
216
+ ),
217
+ };
218
+
219
+ validateBindingsHaveUniqueNames(diagnostics, config);
220
+
221
+ validateAdditionalProperties(
222
+ diagnostics,
223
+ "top-level",
224
+ Object.keys(rawConfig),
225
+ [...Object.keys(config), "env"]
226
+ );
227
+
228
+ experimental(diagnostics, rawConfig, "assets");
229
+
230
+ return { config, diagnostics };
143
231
  }
144
232
 
145
233
  /**
146
234
  * Validate the `build` configuration and return the normalized values.
147
235
  */
148
236
  function normalizeAndValidateBuild(
149
- diagnostics: Diagnostics,
150
- rawConfig: RawConfig,
151
- rawBuild: Config["build"]
237
+ diagnostics: Diagnostics,
238
+ rawEnv: RawEnvironment,
239
+ rawBuild: Config["build"],
240
+ configPath: string | undefined
152
241
  ): Config["build"] & { deprecatedUpload: DeprecatedUpload } {
153
- const { command, cwd, watch_dir, upload, ...rest } = rawBuild;
154
- const deprecatedUpload: DeprecatedUpload = { ...upload };
155
- validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
156
-
157
- validateOptionalProperty(diagnostics, "build", "command", command, "string");
158
- validateOptionalProperty(diagnostics, "build", "cwd", cwd, "string");
159
- validateOptionalProperty(
160
- diagnostics,
161
- "build",
162
- "watch_dir",
163
- watch_dir,
164
- "string"
165
- );
166
-
167
- deprecated(
168
- diagnostics,
169
- rawConfig,
170
- "build.upload.format",
171
- "The format is inferred automatically from the code.",
172
- true
173
- );
174
-
175
- if (rawConfig.main !== undefined && rawBuild.upload?.main) {
176
- diagnostics.errors.push(
177
- `Don't define both the \`main\` and \`build.upload.main\` fields in your configuration.\n` +
178
- `They serve the same purpose: to point to the entry-point of your worker.\n` +
179
- `Delete the \`build.upload.main\` and \`build.upload.dir\` field from your config.`
180
- );
181
- } else {
182
- deprecated(
183
- diagnostics,
184
- rawConfig,
185
- "build.upload.main",
186
- `Delete the \`build.upload.main\` and \`build.upload.dir\` fields.\n` +
187
- `Then add the top level \`main\` field to your configuration file:\n` +
188
- `\`\`\`\n` +
189
- `main = "${path.join(
190
- rawBuild.upload?.dir ?? "./dist",
191
- rawBuild.upload?.main ?? "."
192
- )}"\n` +
193
- `\`\`\``,
194
- true
195
- );
196
-
197
- deprecated(
198
- diagnostics,
199
- rawConfig,
200
- "build.upload.dir",
201
- `Use the top level "main" field or a command-line argument to specify the entry-point for the Worker.`,
202
- true
203
- );
204
- }
205
-
206
- return { command, cwd, watch_dir, deprecatedUpload };
242
+ const { command, cwd, watch_dir = "./src", upload, ...rest } = rawBuild;
243
+ const deprecatedUpload: DeprecatedUpload = { ...upload };
244
+ validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
245
+
246
+ validateOptionalProperty(diagnostics, "build", "command", command, "string");
247
+ validateOptionalProperty(diagnostics, "build", "cwd", cwd, "string");
248
+ if (Array.isArray(watch_dir)) {
249
+ validateTypedArray(diagnostics, "build.watch_dir", watch_dir, "string");
250
+ } else {
251
+ validateOptionalProperty(
252
+ diagnostics,
253
+ "build",
254
+ "watch_dir",
255
+ watch_dir,
256
+ "string"
257
+ );
258
+ }
259
+
260
+ deprecated(
261
+ diagnostics,
262
+ rawEnv,
263
+ "build.upload.format",
264
+ "The format is inferred automatically from the code.",
265
+ true
266
+ );
267
+
268
+ if (rawEnv.main !== undefined && rawBuild.upload?.main) {
269
+ diagnostics.errors.push(
270
+ `Don't define both the \`main\` and \`build.upload.main\` fields in your configuration.\n` +
271
+ `They serve the same purpose: to point to the entry-point of your worker.\n` +
272
+ `Delete the \`build.upload.main\` and \`build.upload.dir\` field from your config.`
273
+ );
274
+ } else {
275
+ deprecated(
276
+ diagnostics,
277
+ rawEnv,
278
+ "build.upload.main",
279
+ `Delete the \`build.upload.main\` and \`build.upload.dir\` fields.\n` +
280
+ `Then add the top level \`main\` field to your configuration file:\n` +
281
+ `\`\`\`\n` +
282
+ `main = "${path.join(
283
+ rawBuild.upload?.dir ?? "./dist",
284
+ rawBuild.upload?.main ?? "."
285
+ )}"\n` +
286
+ `\`\`\``,
287
+ true
288
+ );
289
+
290
+ deprecated(
291
+ diagnostics,
292
+ rawEnv,
293
+ "build.upload.dir",
294
+ `Use the top level "main" field or a command-line argument to specify the entry-point for the Worker.`,
295
+ true
296
+ );
297
+ }
298
+
299
+ return {
300
+ command,
301
+ watch_dir:
302
+ // - `watch_dir` only matters when `command` is defined, so we apply
303
+ // a default only when `command` is defined
304
+ // - `configPath` will always be defined since `build` can only
305
+ // be configured in `wrangler.toml`, but who knows, that may
306
+ // change in the future, so we do a check anyway
307
+ command && configPath
308
+ ? Array.isArray(watch_dir)
309
+ ? watch_dir.map((dir) =>
310
+ path.relative(
311
+ process.cwd(),
312
+ path.join(path.dirname(configPath), `${dir}`)
313
+ )
314
+ )
315
+ : path.relative(
316
+ process.cwd(),
317
+ path.join(path.dirname(configPath), `${watch_dir}`)
318
+ )
319
+ : watch_dir,
320
+ cwd,
321
+ deprecatedUpload,
322
+ };
207
323
  }
208
324
 
209
325
  /**
210
326
  * Validate the `main` field and return the normalized values.
211
327
  */
212
328
  function normalizeAndValidateMainField(
213
- diagnostics: Diagnostics,
214
- configPath: string | undefined,
215
- rawMain: string | undefined,
216
- deprecatedUpload: { dir?: string; main?: string }
329
+ configPath: string | undefined,
330
+ rawMain: string | undefined,
331
+ deprecatedUpload: DeprecatedUpload | undefined
217
332
  ): string | undefined {
218
- const configDir = path.dirname(configPath ?? "wrangler.toml");
219
- if (rawMain !== undefined) {
220
- if (typeof rawMain === "string") {
221
- const directory = path.resolve(configDir);
222
- return path.resolve(directory, rawMain);
223
- } else {
224
- diagnostics.errors.push(
225
- `ERROR: "main" should be a string but got ${JSON.stringify(rawMain)}`
226
- );
227
- return;
228
- }
229
- } else if (deprecatedUpload.main !== undefined) {
230
- const directory = path.resolve(configDir, deprecatedUpload.dir || "./dist");
231
- return path.resolve(directory, deprecatedUpload.main);
232
- } else {
233
- return;
234
- }
333
+ const configDir = path.dirname(configPath ?? "wrangler.toml");
334
+ if (rawMain !== undefined) {
335
+ if (typeof rawMain === "string") {
336
+ const directory = path.resolve(configDir);
337
+ return path.resolve(directory, rawMain);
338
+ } else {
339
+ return rawMain;
340
+ }
341
+ } else if (deprecatedUpload?.main !== undefined) {
342
+ const directory = path.resolve(
343
+ configDir,
344
+ deprecatedUpload?.dir || "./dist"
345
+ );
346
+ return path.resolve(directory, deprecatedUpload.main);
347
+ } else {
348
+ return;
349
+ }
235
350
  }
236
351
 
237
352
  /**
238
353
  * Validate the `dev` configuration and return the normalized values.
239
354
  */
240
355
  function normalizeAndValidateDev(
241
- diagnostics: Diagnostics,
242
- rawDev: Config["dev"]
243
- ): Config["dev"] {
244
- const {
245
- ip = "127.0.0.1",
246
- port = 8787,
247
- local_protocol = "http",
248
- upstream_protocol = "https",
249
- host,
250
- ...rest
251
- } = rawDev;
252
- validateAdditionalProperties(diagnostics, "dev", Object.keys(rest), []);
253
-
254
- validateOptionalProperty(diagnostics, "dev", "ip", ip, "string");
255
- validateOptionalProperty(diagnostics, "dev", "port", port, "number");
256
- validateOptionalProperty(
257
- diagnostics,
258
- "dev",
259
- "local_protocol",
260
- local_protocol,
261
- "string"
262
- );
263
- validateOptionalProperty(
264
- diagnostics,
265
- "dev",
266
- "upstream_protocol",
267
- upstream_protocol,
268
- "string"
269
- );
270
- validateOptionalProperty(diagnostics, "dev", "host", host, "string");
271
- return { ip, port, local_protocol, upstream_protocol, host };
356
+ diagnostics: Diagnostics,
357
+ rawDev: RawDevConfig
358
+ ): DevConfig {
359
+ const {
360
+ ip = "localhost",
361
+ port,
362
+ local_protocol = "http",
363
+ upstream_protocol = "https",
364
+ host,
365
+ ...rest
366
+ } = rawDev;
367
+ validateAdditionalProperties(diagnostics, "dev", Object.keys(rest), []);
368
+
369
+ validateOptionalProperty(diagnostics, "dev", "ip", ip, "string");
370
+ validateOptionalProperty(diagnostics, "dev", "port", port, "number");
371
+ validateOptionalProperty(
372
+ diagnostics,
373
+ "dev",
374
+ "local_protocol",
375
+ local_protocol,
376
+ "string",
377
+ ["http", "https"]
378
+ );
379
+ validateOptionalProperty(
380
+ diagnostics,
381
+ "dev",
382
+ "upstream_protocol",
383
+ upstream_protocol,
384
+ "string",
385
+ ["http", "https"]
386
+ );
387
+ validateOptionalProperty(diagnostics, "dev", "host", host, "string");
388
+ return { ip, port, local_protocol, upstream_protocol, host };
272
389
  }
273
390
 
274
391
  /**
275
392
  * Validate the `migrations` configuration and return the normalized values.
276
393
  */
277
394
  function normalizeAndValidateMigrations(
278
- diagnostics: Diagnostics,
279
- rawMigrations: Config["migrations"]
395
+ diagnostics: Diagnostics,
396
+ rawMigrations: Config["migrations"],
397
+ durableObjects: Config["durable_objects"]
280
398
  ): Config["migrations"] {
281
- if (!Array.isArray(rawMigrations)) {
282
- diagnostics.errors.push(
283
- `The optional "migrations" field should be an array, but got ${JSON.stringify(
284
- rawMigrations
285
- )}`
286
- );
287
- return [];
288
- } else {
289
- for (let i = 0; i < rawMigrations.length; i++) {
290
- const migration = rawMigrations[i];
291
- validateRequiredProperty(
292
- diagnostics,
293
- `migrations[${i}]`,
294
- `tag`,
295
- migration.tag,
296
- "string"
297
- );
298
- validateOptionalTypedArray(
299
- diagnostics,
300
- `migrations[${i}].new_classes`,
301
- migration.new_classes,
302
- "string"
303
- );
304
- if (migration.renamed_classes !== undefined) {
305
- if (!Array.isArray(migration.renamed_classes)) {
306
- diagnostics.errors.push(
307
- `"migrations[${i}].renamed_classes" should be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
308
- migration.renamed_classes
309
- )}.`
310
- );
311
- } else if (
312
- migration.renamed_classes.some(
313
- (c) =>
314
- typeof c !== "object" ||
315
- !isRequiredProperty(c, "from", "string") ||
316
- !isRequiredProperty(c, "to", "string")
317
- )
318
- ) {
319
- diagnostics.errors.push(
320
- `"migrations[${i}].renamed_classes" should be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
321
- migration.renamed_classes
322
- )}.`
323
- );
324
- }
325
- }
326
- validateOptionalTypedArray(
327
- diagnostics,
328
- `migrations[${i}].deleted_classes`,
329
- migration.deleted_classes,
330
- "string"
331
- );
332
- }
333
- return rawMigrations;
334
- }
399
+ if (!Array.isArray(rawMigrations)) {
400
+ diagnostics.errors.push(
401
+ `The optional "migrations" field should be an array, but got ${JSON.stringify(
402
+ rawMigrations
403
+ )}`
404
+ );
405
+ return [];
406
+ } else {
407
+ for (let i = 0; i < rawMigrations.length; i++) {
408
+ const { tag, new_classes, renamed_classes, deleted_classes, ...rest } =
409
+ rawMigrations[i];
410
+
411
+ validateAdditionalProperties(
412
+ diagnostics,
413
+ "migrations",
414
+ Object.keys(rest),
415
+ []
416
+ );
417
+
418
+ validateRequiredProperty(
419
+ diagnostics,
420
+ `migrations[${i}]`,
421
+ `tag`,
422
+ tag,
423
+ "string"
424
+ );
425
+ validateOptionalTypedArray(
426
+ diagnostics,
427
+ `migrations[${i}].new_classes`,
428
+ new_classes,
429
+ "string"
430
+ );
431
+ if (renamed_classes !== undefined) {
432
+ if (!Array.isArray(renamed_classes)) {
433
+ diagnostics.errors.push(
434
+ `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
435
+ renamed_classes
436
+ )}.`
437
+ );
438
+ } else if (
439
+ renamed_classes.some(
440
+ (c) =>
441
+ typeof c !== "object" ||
442
+ !isRequiredProperty(c, "from", "string") ||
443
+ !isRequiredProperty(c, "to", "string")
444
+ )
445
+ ) {
446
+ diagnostics.errors.push(
447
+ `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
448
+ renamed_classes
449
+ )}.`
450
+ );
451
+ }
452
+ }
453
+ validateOptionalTypedArray(
454
+ diagnostics,
455
+ `migrations[${i}].deleted_classes`,
456
+ deleted_classes,
457
+ "string"
458
+ );
459
+ }
460
+
461
+ if (
462
+ Array.isArray(durableObjects?.bindings) &&
463
+ durableObjects.bindings.length > 0
464
+ ) {
465
+ // intrinsic [durable_objects] implies [migrations]
466
+ const exportedDurableObjects = (durableObjects.bindings || []).filter(
467
+ (binding) => !binding.script_name
468
+ );
469
+ if (exportedDurableObjects.length > 0 && rawMigrations.length === 0) {
470
+ if (
471
+ !exportedDurableObjects.some(
472
+ (exportedDurableObject) =>
473
+ typeof exportedDurableObject.class_name !== "string"
474
+ )
475
+ ) {
476
+ const durableObjectClassnames = exportedDurableObjects.map(
477
+ (durable) => durable.class_name
478
+ );
479
+
480
+ diagnostics.warnings.push(
481
+ `In wrangler.toml, you have configured [durable_objects] exported by this Worker (${durableObjectClassnames.join(
482
+ ", "
483
+ )}), but no [migrations] for them. This may not work as expected until you add a [migrations] section to your wrangler.toml. Add this configuration to your wrangler.toml:
484
+
485
+ \`\`\`
486
+ [[migrations]]
487
+ tag = "v1" # Should be unique for each entry
488
+ new_classes = [${durableObjectClassnames
489
+ .map((name) => `"${name}"`)
490
+ .join(", ")}]
491
+ \`\`\`
492
+
493
+ Refer to https://developers.cloudflare.com/workers/learning/using-durable-objects/#durable-object-migrations-in-wranglertoml for more details.`
494
+ );
495
+ }
496
+ }
497
+ }
498
+
499
+ return rawMigrations;
500
+ }
335
501
  }
336
502
 
337
503
  /**
338
504
  * Validate the `site` configuration and return the normalized values.
339
505
  */
340
506
  function normalizeAndValidateSite(
341
- diagnostics: Diagnostics,
342
- rawSite: Config["site"]
507
+ diagnostics: Diagnostics,
508
+ configPath: string | undefined,
509
+ rawConfig: RawConfig,
510
+ mainEntryPoint: string | undefined
343
511
  ): Config["site"] {
344
- if (rawSite !== undefined) {
345
- const {
346
- bucket,
347
- "entry-point": entryPoint,
348
- include = [],
349
- exclude = [],
350
- ...rest
351
- } = rawSite;
352
- validateAdditionalProperties(diagnostics, "site", Object.keys(rest), []);
353
- validateRequiredProperty(diagnostics, "site", "bucket", bucket, "string");
354
- validateOptionalProperty(
355
- diagnostics,
356
- "site",
357
- "entry_point",
358
- entryPoint,
359
- "string"
360
- );
361
- validateTypedArray(diagnostics, "sites.include", include, "string");
362
- validateTypedArray(diagnostics, "sites.exclude", exclude, "string");
363
- return { bucket, "entry-point": entryPoint, include, exclude };
364
- }
365
- return undefined;
512
+ if (rawConfig?.site !== undefined) {
513
+ const { bucket, include = [], exclude = [], ...rest } = rawConfig.site;
514
+
515
+ validateAdditionalProperties(diagnostics, "site", Object.keys(rest), [
516
+ "entry-point",
517
+ ]);
518
+ validateRequiredProperty(diagnostics, "site", "bucket", bucket, "string");
519
+ validateTypedArray(diagnostics, "sites.include", include, "string");
520
+ validateTypedArray(diagnostics, "sites.exclude", exclude, "string");
521
+ validateOptionalProperty(
522
+ diagnostics,
523
+ "site",
524
+ "entry-point",
525
+ rawConfig.site["entry-point"],
526
+ "string"
527
+ );
528
+
529
+ deprecated(
530
+ diagnostics,
531
+ rawConfig,
532
+ `site.entry-point`,
533
+ `Delete the \`site.entry-point\` field, then add the top level \`main\` field to your configuration file:\n` +
534
+ `\`\`\`\n` +
535
+ `main = "${path.join(
536
+ String(rawConfig.site["entry-point"]) || "workers-site",
537
+ path.extname(String(rawConfig.site["entry-point"]) || "workers-site")
538
+ ? ""
539
+ : "index.js"
540
+ )}"\n` +
541
+ `\`\`\``,
542
+ false,
543
+ undefined,
544
+ "warning"
545
+ );
546
+
547
+ let siteEntryPoint = rawConfig.site["entry-point"];
548
+
549
+ if (!mainEntryPoint && !siteEntryPoint) {
550
+ // this means that we're defaulting to "workers-site"
551
+ // so let's add the deprecation warning
552
+ diagnostics.warnings.push(
553
+ `Because you've defined a [site] configuration, we're defaulting to "workers-site" for the deprecated \`site.entry-point\`field.\n` +
554
+ `Add the top level \`main\` field to your configuration file:\n` +
555
+ `\`\`\`\n` +
556
+ `main = "workers-site/index.js"\n` +
557
+ `\`\`\``
558
+ );
559
+ siteEntryPoint = "workers-site";
560
+ } else if (mainEntryPoint && siteEntryPoint) {
561
+ diagnostics.errors.push(
562
+ `Don't define both the \`main\` and \`site.entry-point\` fields in your configuration.\n` +
563
+ `They serve the same purpose: to point to the entry-point of your worker.\n` +
564
+ `Delete the deprecated \`site.entry-point\` field from your config.`
565
+ );
566
+ }
567
+
568
+ if (configPath && siteEntryPoint) {
569
+ // rewrite the path to be relative to the working directory
570
+ siteEntryPoint = path.relative(
571
+ process.cwd(),
572
+ path.join(path.dirname(configPath), siteEntryPoint)
573
+ );
574
+ }
575
+
576
+ return {
577
+ bucket,
578
+ "entry-point": siteEntryPoint,
579
+ include,
580
+ exclude,
581
+ };
582
+ }
583
+ return undefined;
584
+ }
585
+
586
+ /**
587
+ * Validate the `assets` configuration and return normalized values.
588
+ */
589
+ function normalizeAndValidateAssets(
590
+ diagnostics: Diagnostics,
591
+ configPath: string | undefined,
592
+ rawConfig: RawConfig
593
+ ) {
594
+ if (
595
+ typeof rawConfig?.assets === "string" ||
596
+ rawConfig?.assets === undefined
597
+ ) {
598
+ return rawConfig?.assets;
599
+ }
600
+
601
+ const { bucket, include = [], exclude = [], ...rest } = rawConfig.assets;
602
+
603
+ validateAdditionalProperties(diagnostics, "assets", Object.keys(rest), []);
604
+ validateRequiredProperty(diagnostics, "assets", "bucket", bucket, "string");
605
+ validateTypedArray(diagnostics, "assets.include", include, "string");
606
+ validateTypedArray(diagnostics, "assets.exclude", exclude, "string");
607
+
608
+ return {
609
+ bucket,
610
+ include,
611
+ exclude,
612
+ };
366
613
  }
367
614
 
368
615
  /**
369
- * Map the paths of the `wasm_modules` or `text_blobs` configuration to be relative to the current working directory.
616
+ * Map the paths of the `wasm_modules`, `text_blobs` or `data_blobs` configuration to be relative to the current working directory.
370
617
  */
371
618
  function normalizeAndValidateModulePaths(
372
- diagnostics: Diagnostics,
373
- configPath: string | undefined,
374
- field: "wasm_modules" | "text_blobs",
375
- rawMapping: Record<string, string> | undefined
619
+ diagnostics: Diagnostics,
620
+ configPath: string | undefined,
621
+ field: "wasm_modules" | "text_blobs" | "data_blobs",
622
+ rawMapping: Record<string, string> | undefined
376
623
  ): Record<string, string> | undefined {
377
- if (rawMapping === undefined) {
378
- return undefined;
379
- }
380
- const mapping: Record<string, string> = {};
381
- // Rewrite paths to be relative to the cwd, rather than the config path.
382
- for (const [name, filePath] of Object.entries(rawMapping)) {
383
- if (isString(diagnostics, `${field}['${name}']`, filePath, undefined)) {
384
- if (configPath) {
385
- mapping[name] = configPath
386
- ? path.relative(
387
- process.cwd(),
388
- path.join(path.dirname(configPath), filePath)
389
- )
390
- : filePath;
391
- }
392
- }
393
- }
394
- return mapping;
624
+ if (rawMapping === undefined) {
625
+ return undefined;
626
+ }
627
+ const mapping: Record<string, string> = {};
628
+ // Rewrite paths to be relative to the cwd, rather than the config path.
629
+ for (const [name, filePath] of Object.entries(rawMapping)) {
630
+ if (isString(diagnostics, `${field}['${name}']`, filePath, undefined)) {
631
+ if (configPath) {
632
+ mapping[name] = configPath
633
+ ? path.relative(
634
+ process.cwd(),
635
+ path.join(path.dirname(configPath), filePath)
636
+ )
637
+ : filePath;
638
+ }
639
+ }
640
+ }
641
+ return mapping;
642
+ }
643
+
644
+ /**
645
+ * Check whether a value has the shape of a route, which can be a string
646
+ * or an object that looks like {pattern: string, zone_id: string }
647
+ */
648
+ function isValidRouteValue(item: unknown): boolean {
649
+ if (!item) {
650
+ return false;
651
+ }
652
+ if (typeof item === "string") {
653
+ return true;
654
+ }
655
+ if (typeof item === "object") {
656
+ if (!hasProperty(item, "pattern") || typeof item.pattern !== "string") {
657
+ return false;
658
+ }
659
+
660
+ const otherKeys = Object.keys(item).length - 1; // minus one to subtract "pattern"
661
+
662
+ const hasZoneId =
663
+ hasProperty(item, "zone_id") && typeof item.zone_id === "string";
664
+ const hasZoneName =
665
+ hasProperty(item, "zone_name") && typeof item.zone_name === "string";
666
+ const hasCustomDomainFlag =
667
+ hasProperty(item, "custom_domain") &&
668
+ typeof item.custom_domain === "boolean";
669
+
670
+ if (otherKeys === 2 && hasCustomDomainFlag && (hasZoneId || hasZoneName)) {
671
+ return true;
672
+ } else if (
673
+ otherKeys === 1 &&
674
+ (hasZoneId || hasZoneName || hasCustomDomainFlag)
675
+ ) {
676
+ return true;
677
+ }
678
+ }
679
+ return false;
680
+ }
681
+
682
+ /**
683
+ * If account_id has been passed as an empty string, normalise it to undefined.
684
+ * This is to workaround older wrangler1-era templates that have account_id = '',
685
+ * which isn't a valid value anyway
686
+ */
687
+ function mutateEmptyStringAccountIDValue(
688
+ diagnostics: Diagnostics,
689
+ rawEnv: RawEnvironment
690
+ ) {
691
+ if (rawEnv.account_id === "") {
692
+ diagnostics.warnings.push(
693
+ `The "account_id" field in your configuration is an empty string and will be ignored.\n` +
694
+ `Please remove the "account_id" field from your configuration.`
695
+ );
696
+ rawEnv.account_id = undefined;
697
+ }
698
+ return rawEnv;
699
+ }
700
+
701
+ /**
702
+ * Normalize empty string to `undefined` by mutating rawEnv.route value.
703
+ * As part of backward compatibility with Wrangler1 converting empty string to `undefined`
704
+ */
705
+ function mutateEmptyStringRouteValue(
706
+ diagnostics: Diagnostics,
707
+ rawEnv: RawEnvironment
708
+ ): RawEnvironment {
709
+ if (rawEnv["route"] === "") {
710
+ diagnostics.warnings.push(
711
+ `The "route" field in your configuration is an empty string and will be ignored.\n` +
712
+ `Please remove the "route" field from your configuration.`
713
+ );
714
+ rawEnv["route"] = undefined;
715
+ }
716
+
717
+ return rawEnv;
718
+ }
719
+
720
+ /**
721
+ * Validate that the field is a route.
722
+ */
723
+ const isRoute: ValidatorFn = (diagnostics, field, value) => {
724
+ if (value !== undefined && !isValidRouteValue(value)) {
725
+ diagnostics.errors.push(
726
+ `Expected "${field}" to be either a string, or an object with shape { pattern, custom_domain, zone_id | zone_name }, but got ${JSON.stringify(
727
+ value
728
+ )}.`
729
+ );
730
+ return false;
731
+ }
732
+ return true;
733
+ };
734
+
735
+ /**
736
+ * Validate that the field is an array of routes.
737
+ */
738
+ const isRouteArray: ValidatorFn = (diagnostics, field, value) => {
739
+ if (value === undefined) {
740
+ return true;
741
+ }
742
+ if (!Array.isArray(value)) {
743
+ diagnostics.errors.push(
744
+ `Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
745
+ );
746
+ return false;
747
+ }
748
+ const invalidRoutes = [];
749
+ for (const item of value) {
750
+ if (!isValidRouteValue(item)) {
751
+ invalidRoutes.push(item);
752
+ }
753
+ }
754
+ if (invalidRoutes.length > 0) {
755
+ diagnostics.errors.push(
756
+ `Expected "${field}" to be an array of either strings or objects with the shape { pattern, custom_domain, zone_id | zone_name }, but these weren't valid: ${JSON.stringify(
757
+ invalidRoutes,
758
+ null,
759
+ 2
760
+ )}.`
761
+ );
762
+ }
763
+ return invalidRoutes.length === 0;
764
+ };
765
+
766
+ function normalizeAndValidateRoute(
767
+ diagnostics: Diagnostics,
768
+ topLevelEnv: Environment | undefined,
769
+ rawEnv: RawEnvironment
770
+ ): Config["route"] {
771
+ return inheritable(
772
+ diagnostics,
773
+ topLevelEnv,
774
+ mutateEmptyStringRouteValue(diagnostics, rawEnv),
775
+ "route",
776
+ isRoute,
777
+ undefined
778
+ );
779
+ }
780
+
781
+ function validateRoutes(
782
+ diagnostics: Diagnostics,
783
+ topLevelEnv: Environment | undefined,
784
+ rawEnv: RawEnvironment
785
+ ): Config["routes"] {
786
+ return inheritable(
787
+ diagnostics,
788
+ topLevelEnv,
789
+ rawEnv,
790
+ "routes",
791
+ all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
792
+ undefined
793
+ );
395
794
  }
396
795
 
397
796
  /**
398
797
  * Validate top-level environment configuration and return the normalized values.
399
798
  */
400
799
  function normalizeAndValidateEnvironment(
401
- diagnostics: Diagnostics,
402
- topLevelEnv: RawEnvironment,
403
- deprecatedRules: Environment["rules"] | undefined
800
+ diagnostics: Diagnostics,
801
+ configPath: string | undefined,
802
+ topLevelEnv: RawEnvironment
404
803
  ): Environment;
405
804
  /**
406
805
  * Validate the named environment configuration and return the normalized values.
407
806
  */
408
807
  function normalizeAndValidateEnvironment(
409
- diagnostics: Diagnostics,
410
- rawEnv: RawEnvironment,
411
- deprecatedRules: Environment["rules"] | undefined,
412
- envName: string,
413
- config: Config,
414
- rawConfig: RawConfig
808
+ diagnostics: Diagnostics,
809
+ configPath: string | undefined,
810
+ rawEnv: RawEnvironment,
811
+ envName: string,
812
+ topLevelEnv: Environment,
813
+ isLegacyEnv: boolean,
814
+ rawConfig: RawConfig
415
815
  ): Environment;
416
816
  function normalizeAndValidateEnvironment(
417
- diagnostics: Diagnostics,
418
- rawEnv: RawEnvironment,
419
- deprecatedRules: Environment["rules"] | undefined,
420
- envName = "top level",
421
- config?: Config | undefined,
422
- rawConfig?: RawConfig | undefined
817
+ diagnostics: Diagnostics,
818
+ configPath: string | undefined,
819
+ rawEnv: RawEnvironment,
820
+ envName = "top level",
821
+ topLevelEnv?: Environment | undefined,
822
+ isLegacyEnv?: boolean,
823
+ rawConfig?: RawConfig | undefined
423
824
  ): Environment {
424
- deprecated(
425
- diagnostics,
426
- rawEnv,
427
- "zone_id",
428
- "This is unnecessary since we can deduce this from routes directly.",
429
- false // We need to leave this in-place for the moment since `route` commands might use it.
430
- );
431
-
432
- // The field "experimental_services" doesn't exist anymore in the config, but we still want to error about any older usage.
433
- // TODO: remove this before GA.
434
- deprecated(
435
- diagnostics,
436
- rawEnv,
437
- "experimental_services",
438
- `The "experimental_services" field is no longer supported. Instead, use [[unsafe.bindings]] to enable experimental features. Add this to your wrangler.toml:\n` +
439
- "```\n" +
440
- TOML.stringify({
441
- unsafe: {
442
- bindings: (rawEnv?.experimental_services || []).map(
443
- (serviceDefinition) => {
444
- return {
445
- name: serviceDefinition.name,
446
- type: "service",
447
- service: serviceDefinition.service,
448
- environment: serviceDefinition.environment,
449
- };
450
- }
451
- ),
452
- },
453
- }) +
454
- "```",
455
- true
456
- );
457
-
458
- experimental(diagnostics, rawEnv, "unsafe");
459
-
460
- const route = inheritable(
461
- diagnostics,
462
- config,
463
- rawEnv,
464
- "route",
465
- isString,
466
- undefined
467
- );
468
- const routes = inheritable(
469
- diagnostics,
470
- config,
471
- rawEnv,
472
- "routes",
473
- isStringArray,
474
- undefined
475
- );
476
- const workers_dev = inheritable(
477
- diagnostics,
478
- config,
479
- rawEnv,
480
- "workers_dev",
481
- isBoolean,
482
- !(routes || route)
483
- );
484
-
485
- const environment: Environment = {
486
- // Inherited fields
487
- account_id: inheritable(
488
- diagnostics,
489
- config,
490
- rawEnv,
491
- "account_id",
492
- isString,
493
- undefined
494
- ),
495
- compatibility_date: inheritable(
496
- diagnostics,
497
- config,
498
- rawEnv,
499
- "compatibility_date",
500
- isString,
501
- undefined
502
- ),
503
- compatibility_flags: inheritable(
504
- diagnostics,
505
- config,
506
- rawEnv,
507
- "compatibility_flags",
508
- isStringArray,
509
- []
510
- ),
511
- jsx_factory: inheritable(
512
- diagnostics,
513
- config,
514
- rawEnv,
515
- "jsx_factory",
516
- isString,
517
- "React.createElement"
518
- ),
519
- jsx_fragment: inheritable(
520
- diagnostics,
521
- config,
522
- rawEnv,
523
- "jsx_fragment",
524
- isString,
525
- "React.Fragment"
526
- ),
527
- rules: validateAndNormalizeRules(
528
- diagnostics,
529
- config,
530
- rawEnv,
531
- deprecatedRules,
532
- envName
533
- ),
534
- name: inheritable(diagnostics, config, rawEnv, "name", isString, undefined),
535
- route,
536
- routes,
537
- triggers: inheritable(
538
- diagnostics,
539
- config,
540
- rawEnv,
541
- "triggers",
542
- isObjectWith("crons"),
543
- { crons: [] }
544
- ),
545
- usage_model: inheritable(
546
- diagnostics,
547
- config,
548
- rawEnv,
549
- "usage_model",
550
- isOneOf("bundled", "unbound"),
551
- undefined
552
- ),
553
- workers_dev,
554
- // Not inherited fields
555
- vars: notInheritable(
556
- diagnostics,
557
- config,
558
- rawConfig,
559
- rawEnv,
560
- envName,
561
- "vars",
562
- validateVars(envName),
563
- {}
564
- ),
565
- durable_objects: notInheritable(
566
- diagnostics,
567
- config,
568
- rawConfig,
569
- rawEnv,
570
- envName,
571
- "durable_objects",
572
- validateBindingsProperty(envName, validateDurableObjectBinding),
573
- {
574
- bindings: [],
575
- }
576
- ),
577
- kv_namespaces: notInheritable(
578
- diagnostics,
579
- config,
580
- rawConfig,
581
- rawEnv,
582
- envName,
583
- "kv_namespaces",
584
- validateBindingArray(envName, validateKVBinding),
585
- []
586
- ),
587
- r2_buckets: notInheritable(
588
- diagnostics,
589
- config,
590
- rawConfig,
591
- rawEnv,
592
- envName,
593
- "r2_buckets",
594
- validateBindingArray(envName, validateR2Binding),
595
- []
596
- ),
597
- unsafe: notInheritable(
598
- diagnostics,
599
- config,
600
- rawConfig,
601
- rawEnv,
602
- envName,
603
- "unsafe",
604
- validateBindingsProperty(envName, validateUnsafeBinding),
605
- {
606
- bindings: [],
607
- }
608
- ),
609
- zone_id: rawEnv.zone_id,
610
- };
611
-
612
- return environment;
825
+ deprecated(
826
+ diagnostics,
827
+ rawEnv,
828
+ "zone_id",
829
+ "This is unnecessary since we can deduce this from routes directly.",
830
+ false // We need to leave this in-place for the moment since `route` commands might use it.
831
+ );
832
+
833
+ // The field "experimental_services" doesn't exist anymore in the config, but we still want to error about any older usage.
834
+ deprecated(
835
+ diagnostics,
836
+ rawEnv,
837
+ "experimental_services",
838
+ `The "experimental_services" field is no longer supported. Simply rename the [experimental_services] field to [services].`,
839
+ true
840
+ );
841
+
842
+ experimental(diagnostics, rawEnv, "unsafe");
843
+ experimental(diagnostics, rawEnv, "services");
844
+ experimental(diagnostics, rawEnv, "worker_namespaces");
845
+
846
+ const route = normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv);
847
+
848
+ const account_id = inheritableInLegacyEnvironments(
849
+ diagnostics,
850
+ isLegacyEnv,
851
+ topLevelEnv,
852
+ mutateEmptyStringAccountIDValue(diagnostics, rawEnv),
853
+ "account_id",
854
+ isString,
855
+ undefined,
856
+ undefined
857
+ );
858
+
859
+ const routes = validateRoutes(diagnostics, topLevelEnv, rawEnv);
860
+
861
+ const workers_dev = inheritable(
862
+ diagnostics,
863
+ topLevelEnv,
864
+ rawEnv,
865
+ "workers_dev",
866
+ isBoolean,
867
+ undefined
868
+ );
869
+
870
+ const { deprecatedUpload, ...build } = normalizeAndValidateBuild(
871
+ diagnostics,
872
+ rawEnv,
873
+ rawEnv.build ?? topLevelEnv?.build ?? {},
874
+ configPath
875
+ );
876
+
877
+ const environment: Environment = {
878
+ // Inherited fields
879
+ account_id,
880
+ compatibility_date: inheritable(
881
+ diagnostics,
882
+ topLevelEnv,
883
+ rawEnv,
884
+ "compatibility_date",
885
+ isString,
886
+ undefined
887
+ ),
888
+ compatibility_flags: inheritable(
889
+ diagnostics,
890
+ topLevelEnv,
891
+ rawEnv,
892
+ "compatibility_flags",
893
+ isStringArray,
894
+ []
895
+ ),
896
+ jsx_factory: inheritable(
897
+ diagnostics,
898
+ topLevelEnv,
899
+ rawEnv,
900
+ "jsx_factory",
901
+ isString,
902
+ "React.createElement"
903
+ ),
904
+ jsx_fragment: inheritable(
905
+ diagnostics,
906
+ topLevelEnv,
907
+ rawEnv,
908
+ "jsx_fragment",
909
+ isString,
910
+ "React.Fragment"
911
+ ),
912
+ tsconfig: validateAndNormalizeTsconfig(
913
+ diagnostics,
914
+ topLevelEnv,
915
+ rawEnv,
916
+ configPath
917
+ ),
918
+ rules: validateAndNormalizeRules(
919
+ diagnostics,
920
+ topLevelEnv,
921
+ rawEnv,
922
+ deprecatedUpload?.rules,
923
+ envName
924
+ ),
925
+ name: inheritableInLegacyEnvironments(
926
+ diagnostics,
927
+ isLegacyEnv,
928
+ topLevelEnv,
929
+ rawEnv,
930
+ "name",
931
+ isValidName,
932
+ appendEnvName(envName),
933
+ undefined
934
+ ),
935
+ main: normalizeAndValidateMainField(
936
+ configPath,
937
+ inheritable(
938
+ diagnostics,
939
+ topLevelEnv,
940
+ rawEnv,
941
+ "main",
942
+ isString,
943
+ undefined
944
+ ),
945
+ deprecatedUpload
946
+ ),
947
+ route,
948
+ routes,
949
+ triggers: inheritable(
950
+ diagnostics,
951
+ topLevelEnv,
952
+ rawEnv,
953
+ "triggers",
954
+ isObjectWith("crons"),
955
+ { crons: [] }
956
+ ),
957
+ usage_model: inheritable(
958
+ diagnostics,
959
+ topLevelEnv,
960
+ rawEnv,
961
+ "usage_model",
962
+ isOneOf("bundled", "unbound"),
963
+ undefined
964
+ ),
965
+ build,
966
+ workers_dev,
967
+ // Not inherited fields
968
+ vars: notInheritable(
969
+ diagnostics,
970
+ topLevelEnv,
971
+ rawConfig,
972
+ rawEnv,
973
+ envName,
974
+ "vars",
975
+ validateVars(envName),
976
+ {}
977
+ ),
978
+ define: notInheritable(
979
+ diagnostics,
980
+ topLevelEnv,
981
+ rawConfig,
982
+ rawEnv,
983
+ envName,
984
+ "define",
985
+ validateDefines(envName),
986
+ {}
987
+ ),
988
+ durable_objects: notInheritable(
989
+ diagnostics,
990
+ topLevelEnv,
991
+ rawConfig,
992
+ rawEnv,
993
+ envName,
994
+ "durable_objects",
995
+ validateBindingsProperty(envName, validateDurableObjectBinding),
996
+ {
997
+ bindings: [],
998
+ }
999
+ ),
1000
+ kv_namespaces: notInheritable(
1001
+ diagnostics,
1002
+ topLevelEnv,
1003
+ rawConfig,
1004
+ rawEnv,
1005
+ envName,
1006
+ "kv_namespaces",
1007
+ validateBindingArray(envName, validateKVBinding),
1008
+ []
1009
+ ),
1010
+ r2_buckets: notInheritable(
1011
+ diagnostics,
1012
+ topLevelEnv,
1013
+ rawConfig,
1014
+ rawEnv,
1015
+ envName,
1016
+ "r2_buckets",
1017
+ validateBindingArray(envName, validateR2Binding),
1018
+ []
1019
+ ),
1020
+ services: notInheritable(
1021
+ diagnostics,
1022
+ topLevelEnv,
1023
+ rawConfig,
1024
+ rawEnv,
1025
+ envName,
1026
+ "services",
1027
+ validateBindingArray(envName, validateServiceBinding),
1028
+ []
1029
+ ),
1030
+ worker_namespaces: notInheritable(
1031
+ diagnostics,
1032
+ topLevelEnv,
1033
+ rawConfig,
1034
+ rawEnv,
1035
+ envName,
1036
+ "worker_namespaces",
1037
+ validateBindingArray(envName, validateWorkerNamespaceBinding),
1038
+ []
1039
+ ),
1040
+ unsafe: notInheritable(
1041
+ diagnostics,
1042
+ topLevelEnv,
1043
+ rawConfig,
1044
+ rawEnv,
1045
+ envName,
1046
+ "unsafe",
1047
+ validateBindingsProperty(envName, validateUnsafeBinding),
1048
+ {
1049
+ bindings: [],
1050
+ }
1051
+ ),
1052
+ zone_id: rawEnv.zone_id,
1053
+ no_bundle: inheritable(
1054
+ diagnostics,
1055
+ topLevelEnv,
1056
+ rawEnv,
1057
+ "no_bundle",
1058
+ isBoolean,
1059
+ undefined
1060
+ ),
1061
+ minify: inheritable(
1062
+ diagnostics,
1063
+ topLevelEnv,
1064
+ rawEnv,
1065
+ "minify",
1066
+ isBoolean,
1067
+ undefined
1068
+ ),
1069
+ node_compat: inheritable(
1070
+ diagnostics,
1071
+ topLevelEnv,
1072
+ rawEnv,
1073
+ "node_compat",
1074
+ isBoolean,
1075
+ undefined
1076
+ ),
1077
+ };
1078
+
1079
+ return environment;
1080
+ }
1081
+
1082
+ function validateAndNormalizeTsconfig(
1083
+ diagnostics: Diagnostics,
1084
+ topLevelEnv: Environment | undefined,
1085
+ rawEnv: RawEnvironment,
1086
+ configPath: string | undefined
1087
+ ) {
1088
+ const tsconfig = inheritable(
1089
+ diagnostics,
1090
+ topLevelEnv,
1091
+ rawEnv,
1092
+ "tsconfig",
1093
+ isString,
1094
+ undefined
1095
+ );
1096
+
1097
+ return configPath && tsconfig
1098
+ ? path.relative(
1099
+ process.cwd(),
1100
+ path.join(path.dirname(configPath), tsconfig)
1101
+ )
1102
+ : tsconfig;
613
1103
  }
614
1104
 
615
1105
  const validateAndNormalizeRules = (
616
- diagnostics: Diagnostics,
617
- config: Config | undefined,
618
- rawEnv: RawEnvironment,
619
- deprecatedRules: Rule[] | undefined,
620
- envName: string
1106
+ diagnostics: Diagnostics,
1107
+ topLevelEnv: Environment | undefined,
1108
+ rawEnv: RawEnvironment,
1109
+ deprecatedRules: Rule[] | undefined,
1110
+ envName: string
621
1111
  ): Rule[] => {
622
- if (config === undefined) {
623
- // Only create errors/warnings for the top-level environment
624
- if (rawEnv.rules && deprecatedRules) {
625
- diagnostics.errors.push(
626
- `ERROR: You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
627
- );
628
- } else if (deprecatedRules) {
629
- diagnostics.warnings.push(
630
- `DEPRECATION: The \`build.upload.rules\` config field is no longer used, the rules should be specified via the \`rules\` config field. Delete the \`build.upload\` field from the configuration file, and add this:\n` +
631
- "```\n" +
632
- TOML.stringify({ rules: deprecatedRules }) +
633
- "```"
634
- );
635
- }
636
- }
637
-
638
- return inheritable(
639
- diagnostics,
640
- config,
641
- rawEnv,
642
- "rules",
643
- validateRules(envName),
644
- deprecatedRules ?? []
645
- );
1112
+ if (topLevelEnv === undefined) {
1113
+ // Only create errors/warnings for the top-level environment
1114
+ if (rawEnv.rules && deprecatedRules) {
1115
+ diagnostics.errors.push(
1116
+ `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
1117
+ );
1118
+ } else if (deprecatedRules) {
1119
+ diagnostics.warnings.push(
1120
+ `Deprecation: The \`build.upload.rules\` config field is no longer used, the rules should be specified via the \`rules\` config field. Delete the \`build.upload\` field from the configuration file, and add this:\n` +
1121
+ "```\n" +
1122
+ TOML.stringify({ rules: deprecatedRules }) +
1123
+ "```"
1124
+ );
1125
+ }
1126
+ }
1127
+
1128
+ return inheritable(
1129
+ diagnostics,
1130
+ topLevelEnv,
1131
+ rawEnv,
1132
+ "rules",
1133
+ validateRules(envName),
1134
+ deprecatedRules ?? []
1135
+ );
646
1136
  };
647
1137
 
648
1138
  const validateRules =
649
- (envName: string): ValidatorFn =>
650
- (diagnostics, field, envValue, config) => {
651
- if (!envValue) {
652
- return true;
653
- }
654
- const fieldPath =
655
- config === undefined ? `${field}` : `env.${envName}.${field}`;
656
- if (!Array.isArray(envValue)) {
657
- diagnostics.errors.push(
658
- `The field "${fieldPath}" should be an array but got ${JSON.stringify(
659
- envValue
660
- )}.`
661
- );
662
- return false;
663
- }
664
-
665
- let isValid = true;
666
- for (let i = 0; i < envValue.length; i++) {
667
- isValid =
668
- validateRule(diagnostics, `${fieldPath}[${i}]`, envValue[i], config) &&
669
- isValid;
670
- }
671
- return isValid;
672
- };
1139
+ (envName: string): ValidatorFn =>
1140
+ (diagnostics, field, envValue, config) => {
1141
+ if (!envValue) {
1142
+ return true;
1143
+ }
1144
+ const fieldPath =
1145
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1146
+ if (!Array.isArray(envValue)) {
1147
+ diagnostics.errors.push(
1148
+ `The field "${fieldPath}" should be an array but got ${JSON.stringify(
1149
+ envValue
1150
+ )}.`
1151
+ );
1152
+ return false;
1153
+ }
1154
+
1155
+ let isValid = true;
1156
+ for (let i = 0; i < envValue.length; i++) {
1157
+ isValid =
1158
+ validateRule(diagnostics, `${fieldPath}[${i}]`, envValue[i], config) &&
1159
+ isValid;
1160
+ }
1161
+ return isValid;
1162
+ };
673
1163
 
674
1164
  const validateRule: ValidatorFn = (diagnostics, field, value) => {
675
- if (typeof value !== "object" || value === null) {
676
- diagnostics.errors.push(`ERROR: should be an object.`);
677
- return false;
678
- }
679
- // Rules must have a type string and glob string array, and optionally a fallthrough boolean.
680
- let isValid = true;
681
- const rule = value as Rule;
682
-
683
- if (
684
- !isRequiredProperty(rule, "type", "string", [
685
- "ESModule",
686
- "CommonJS",
687
- "CompiledWasm",
688
- "Text",
689
- "Data",
690
- ])
691
- ) {
692
- diagnostics.errors.push(
693
- `ERROR: bindings should have a string "type" field, which contains one of "ESModule", "CommonJS", "CompiledWasm", "Text", or "Data".`
694
- );
695
- isValid = false;
696
- }
697
-
698
- isValid =
699
- validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") &&
700
- isValid;
701
-
702
- if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
703
- diagnostics.errors.push(
704
- `ERROR: should, optionally, have a boolean "fallthrough" field.`
705
- );
706
- isValid = false;
707
- }
708
-
709
- return isValid;
1165
+ if (typeof value !== "object" || value === null) {
1166
+ diagnostics.errors.push(
1167
+ `"${field}" should be an object but got ${JSON.stringify(value)}.`
1168
+ );
1169
+ return false;
1170
+ }
1171
+ // Rules must have a type string and glob string array, and optionally a fallthrough boolean.
1172
+ let isValid = true;
1173
+ const rule = value as Rule;
1174
+
1175
+ if (
1176
+ !isRequiredProperty(rule, "type", "string", [
1177
+ "ESModule",
1178
+ "CommonJS",
1179
+ "CompiledWasm",
1180
+ "Text",
1181
+ "Data",
1182
+ ])
1183
+ ) {
1184
+ diagnostics.errors.push(
1185
+ `bindings should have a string "type" field, which contains one of "ESModule", "CommonJS", "CompiledWasm", "Text", or "Data".`
1186
+ );
1187
+ isValid = false;
1188
+ }
1189
+
1190
+ isValid =
1191
+ validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") &&
1192
+ isValid;
1193
+
1194
+ if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
1195
+ diagnostics.errors.push(
1196
+ `the field "fallthrough", when present, should be a boolean.`
1197
+ );
1198
+ isValid = false;
1199
+ }
1200
+
1201
+ return isValid;
710
1202
  };
711
1203
 
1204
+ const validateDefines =
1205
+ (envName: string): ValidatorFn =>
1206
+ (diagnostics, field, value, config) => {
1207
+ let isValid = true;
1208
+ const fieldPath =
1209
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1210
+
1211
+ if (typeof value === "object" && value !== null) {
1212
+ for (const varName in value) {
1213
+ // some casting here to appease typescript
1214
+ // even though the value might not match the type
1215
+ if (typeof (value as Record<string, string>)[varName] !== "string") {
1216
+ diagnostics.errors.push(
1217
+ `The field "${fieldPath}.${varName}" should be a string but got ${JSON.stringify(
1218
+ (value as Record<string, string>)[varName]
1219
+ )}.`
1220
+ );
1221
+ isValid = false;
1222
+ }
1223
+ }
1224
+ } else {
1225
+ if (value !== undefined) {
1226
+ diagnostics.errors.push(
1227
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1228
+ value
1229
+ )}.\n`
1230
+ );
1231
+ isValid = false;
1232
+ }
1233
+ }
1234
+
1235
+ const configDefines = Object.keys(config?.define ?? {});
1236
+
1237
+ // If there are no top level vars then there is nothing to do here.
1238
+ if (configDefines.length > 0) {
1239
+ if (typeof value === "object" && value !== null) {
1240
+ const configEnvDefines = config === undefined ? [] : Object.keys(value);
1241
+
1242
+ for (const varName of configDefines) {
1243
+ if (!(varName in value)) {
1244
+ diagnostics.warnings.push(
1245
+ `"define.${varName}" exists at the top level, but not on "${fieldPath}".\n` +
1246
+ `This is not what you probably want, since "define" configuration is not inherited by environments.\n` +
1247
+ `Please add "define.${varName}" to "env.${envName}".`
1248
+ );
1249
+ }
1250
+ }
1251
+ for (const varName of configEnvDefines) {
1252
+ if (!configDefines.includes(varName)) {
1253
+ diagnostics.warnings.push(
1254
+ `"${varName}" exists on "env.${envName}", but not on the top level.\n` +
1255
+ `This is not what you probably want, since "define" configuration within environments can only override existing top level "define" configuration\n` +
1256
+ `Please remove "${fieldPath}.${varName}", or add "define.${varName}".`
1257
+ );
1258
+ }
1259
+ }
1260
+ }
1261
+ }
1262
+
1263
+ return isValid;
1264
+ };
1265
+
712
1266
  const validateVars =
713
- (envName: string): ValidatorFn =>
714
- (diagnostics, field, value, config) => {
715
- let isValid = true;
716
- const fieldPath =
717
- config === undefined ? `${field}` : `env.${envName}.${field}`;
718
- const configVars = Object.keys(config?.vars ?? {});
719
- // If there are no top level vars then there is nothing to do here.
720
- if (configVars.length > 0) {
721
- if (typeof value !== "object" || value === null) {
722
- diagnostics.errors.push(
723
- `The field "${fieldPath}" should be an object but got ${JSON.stringify(
724
- value
725
- )}.\n`
726
- );
727
- isValid = false;
728
- } else {
729
- for (const varName of configVars) {
730
- if (!(varName in value)) {
731
- diagnostics.warnings.push(
732
- `"vars.${varName}" exists at the top level, but not on "${fieldPath}".\n` +
733
- `This is not what you probably want, since "vars" configuration is not inherited by environments.\n` +
734
- `Please add "vars.${varName}" to "env.${envName}".`
735
- );
736
- }
737
- }
738
- }
739
- }
740
- return isValid;
741
- };
1267
+ (envName: string): ValidatorFn =>
1268
+ (diagnostics, field, value, config) => {
1269
+ let isValid = true;
1270
+ const fieldPath =
1271
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1272
+ const configVars = Object.keys(config?.vars ?? {});
1273
+ // If there are no top level vars then there is nothing to do here.
1274
+ if (configVars.length > 0) {
1275
+ if (typeof value !== "object" || value === null) {
1276
+ diagnostics.errors.push(
1277
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1278
+ value
1279
+ )}.\n`
1280
+ );
1281
+ isValid = false;
1282
+ } else {
1283
+ for (const varName of configVars) {
1284
+ if (!(varName in value)) {
1285
+ diagnostics.warnings.push(
1286
+ `"vars.${varName}" exists at the top level, but not on "${fieldPath}".\n` +
1287
+ `This is not what you probably want, since "vars" configuration is not inherited by environments.\n` +
1288
+ `Please add "vars.${varName}" to "env.${envName}".`
1289
+ );
1290
+ }
1291
+ }
1292
+ }
1293
+ }
1294
+ return isValid;
1295
+ };
742
1296
 
743
1297
  const validateBindingsProperty =
744
- (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
745
- (diagnostics, field, value, config) => {
746
- let isValid = true;
747
- const fieldPath =
748
- config === undefined ? `${field}` : `env.${envName}.${field}`;
749
-
750
- if (value !== undefined) {
751
- // Check the validity of the `value` as a bindings container.
752
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
753
- diagnostics.errors.push(
754
- `The field "${fieldPath}" should be an object but got ${JSON.stringify(
755
- value
756
- )}.`
757
- );
758
- isValid = false;
759
- } else if (!hasProperty(value, "bindings")) {
760
- diagnostics.errors.push(
761
- `The field "${fieldPath}" is missing the required "bindings" property.`
762
- );
763
- isValid = false;
764
- } else if (!Array.isArray(value.bindings)) {
765
- diagnostics.errors.push(
766
- `The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
767
- value.bindings
768
- )}.`
769
- );
770
- isValid = false;
771
- } else {
772
- for (let i = 0; i < value.bindings.length; i++) {
773
- const binding = value.bindings[i];
774
- const bindingDiagnostics = new Diagnostics(
775
- `"${fieldPath}.bindings[${i}]": ${JSON.stringify(binding)}`
776
- );
777
- isValid =
778
- validateBinding(
779
- bindingDiagnostics,
780
- `${fieldPath}.bindings[${i}]`,
781
- binding,
782
- config
783
- ) && isValid;
784
- diagnostics.addChild(bindingDiagnostics);
785
- }
786
- }
787
-
788
- const configBindingNames = getBindingNames(
789
- config?.[field as keyof Environment]
790
- );
791
- if (isValid && configBindingNames.length > 0) {
792
- // If there are top level bindings then check that they all appear in the environment.
793
- const envBindingNames = new Set(getBindingNames(value));
794
- const missingBindings = configBindingNames.filter(
795
- (name) => !envBindingNames.has(name)
796
- );
797
- if (missingBindings.length > 0) {
798
- diagnostics.warnings.push(
799
- `The following bindings are at the top level, but not on "env.${envName}".\n` +
800
- `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
801
- `Please add a binding for each to "${fieldPath}.bindings".` +
802
- missingBindings.map((name) => `- ${name}`).join("\n")
803
- );
804
- }
805
- }
806
- }
807
- return isValid;
808
- };
1298
+ (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
1299
+ (diagnostics, field, value, config) => {
1300
+ let isValid = true;
1301
+ const fieldPath =
1302
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
809
1303
 
810
- /**
811
- * Get the names of the bindings collection in `value`.
812
- */
813
- const getBindingNames = (value: unknown): string[] =>
814
- ((value as { bindings: { name: string }[] })?.bindings ?? []).map(
815
- (binding) => binding.name
816
- );
1304
+ if (value !== undefined) {
1305
+ // Check the validity of the `value` as a bindings container.
1306
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1307
+ diagnostics.errors.push(
1308
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
1309
+ value
1310
+ )}.`
1311
+ );
1312
+ isValid = false;
1313
+ } else if (!hasProperty(value, "bindings")) {
1314
+ diagnostics.errors.push(
1315
+ `The field "${fieldPath}" is missing the required "bindings" property.`
1316
+ );
1317
+ isValid = false;
1318
+ } else if (!Array.isArray(value.bindings)) {
1319
+ diagnostics.errors.push(
1320
+ `The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
1321
+ value.bindings
1322
+ )}.`
1323
+ );
1324
+ isValid = false;
1325
+ } else {
1326
+ for (let i = 0; i < value.bindings.length; i++) {
1327
+ const binding = value.bindings[i];
1328
+ const bindingDiagnostics = new Diagnostics(
1329
+ `"${fieldPath}.bindings[${i}]": ${JSON.stringify(binding)}`
1330
+ );
1331
+ isValid =
1332
+ validateBinding(
1333
+ bindingDiagnostics,
1334
+ `${fieldPath}.bindings[${i}]`,
1335
+ binding,
1336
+ config
1337
+ ) && isValid;
1338
+ diagnostics.addChild(bindingDiagnostics);
1339
+ }
1340
+ }
1341
+
1342
+ const configBindingNames = getBindingNames(
1343
+ config?.[field as keyof Environment]
1344
+ );
1345
+ if (isValid && configBindingNames.length > 0) {
1346
+ // If there are top level bindings then check that they all appear in the environment.
1347
+ const envBindingNames = new Set(getBindingNames(value));
1348
+ const missingBindings = configBindingNames.filter(
1349
+ (name) => !envBindingNames.has(name)
1350
+ );
1351
+ if (missingBindings.length > 0) {
1352
+ diagnostics.warnings.push(
1353
+ `The following bindings are at the top level, but not on "env.${envName}".\n` +
1354
+ `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1355
+ `Please add a binding for each to "${fieldPath}.bindings":\n` +
1356
+ missingBindings.map((name) => `- ${name}`).join("\n")
1357
+ );
1358
+ }
1359
+ }
1360
+ }
1361
+ return isValid;
1362
+ };
817
1363
 
818
1364
  /**
819
1365
  * Check that the given field is a valid "durable_object" binding object.
820
1366
  */
821
1367
  const validateDurableObjectBinding: ValidatorFn = (
822
- diagnostics,
823
- _field,
824
- value
1368
+ diagnostics,
1369
+ field,
1370
+ value
825
1371
  ) => {
826
- if (typeof value !== "object" || value === null) {
827
- diagnostics.errors.push(`ERROR: should be an object.`);
828
- return false;
829
- }
830
-
831
- // Durable Object bindings must have a name and class_name, and optionally a script_name.
832
- let isValid = true;
833
- if (!isRequiredProperty(value, "name", "string")) {
834
- diagnostics.errors.push(
835
- `ERROR: bindings should have a string "name" field.`
836
- );
837
- isValid = false;
838
- }
839
- if (!isRequiredProperty(value, "class_name", "string")) {
840
- diagnostics.errors.push(`ERROR: should have a string "class_name" field.`);
841
- isValid = false;
842
- }
843
- if (!isOptionalProperty(value, "script_name", "string")) {
844
- diagnostics.errors.push(
845
- `ERROR: should, optionally, have a string "script_name" field.`
846
- );
847
- isValid = false;
848
- }
849
-
850
- return isValid;
1372
+ if (typeof value !== "object" || value === null) {
1373
+ diagnostics.errors.push(
1374
+ `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
1375
+ );
1376
+ return false;
1377
+ }
1378
+
1379
+ // Durable Object bindings must have a name and class_name, and optionally a script_name and an environment.
1380
+ let isValid = true;
1381
+ if (!isRequiredProperty(value, "name", "string")) {
1382
+ diagnostics.errors.push(`binding should have a string "name" field.`);
1383
+ isValid = false;
1384
+ }
1385
+ if (!isRequiredProperty(value, "class_name", "string")) {
1386
+ diagnostics.errors.push(`binding should have a string "class_name" field.`);
1387
+ isValid = false;
1388
+ }
1389
+ if (!isOptionalProperty(value, "script_name", "string")) {
1390
+ diagnostics.errors.push(
1391
+ `the field "script_name", when present, should be a string.`
1392
+ );
1393
+ isValid = false;
1394
+ }
1395
+ // environment requires a script_name
1396
+ if (!isOptionalProperty(value, "environment", "string")) {
1397
+ diagnostics.errors.push(
1398
+ `the field "environment", when present, should be a string.`
1399
+ );
1400
+ isValid = false;
1401
+ }
1402
+
1403
+ if ("environment" in value && !("script_name" in value)) {
1404
+ diagnostics.errors.push(
1405
+ `binding should have a "script_name" field if "environment" is present.`
1406
+ );
1407
+ isValid = false;
1408
+ }
1409
+
1410
+ return isValid;
851
1411
  };
852
1412
 
853
1413
  /**
@@ -855,165 +1415,340 @@ const validateDurableObjectBinding: ValidatorFn = (
855
1415
  *
856
1416
  * TODO: further validation of known unsafe bindings.
857
1417
  */
858
- const validateUnsafeBinding: ValidatorFn = (diagnostics, _field, value) => {
859
- if (typeof value !== "object" || value === null) {
860
- diagnostics.errors.push(`ERROR: should be an object.`);
861
- return false;
862
- }
863
-
864
- let isValid = true;
865
- // Unsafe bindings must have a name and type.
866
- if (!isRequiredProperty(value, "name", "string")) {
867
- diagnostics.errors.push(`ERROR: should have a string "name" field.`);
868
- isValid = false;
869
- }
870
- if (isRequiredProperty(value, "type", "string")) {
871
- const safeBindings = [
872
- "plain_text",
873
- "json",
874
- "kv_namespace",
875
- "durable_object_namespace",
876
- ];
877
-
878
- if (safeBindings.includes(value.type)) {
879
- diagnostics.warnings.push(
880
- `The binding type "${value.type}" is directly supported by wrangler.\n` +
881
- `Consider migrating this unsafe binding to a format for '${value.type}' bindings that is supported by wrangler for optimal support.\n` +
882
- "For more details, see https://developers.cloudflare.com/workers/cli-wrangler/configuration"
883
- );
884
- }
885
- } else {
886
- diagnostics.errors.push(`ERROR: should have a string "type" field.`);
887
- isValid = false;
888
- }
889
- return isValid;
1418
+ const validateUnsafeBinding: ValidatorFn = (diagnostics, field, value) => {
1419
+ if (typeof value !== "object" || value === null) {
1420
+ diagnostics.errors.push(
1421
+ `Expected ${field} to be an object but got ${JSON.stringify(value)}.`
1422
+ );
1423
+ return false;
1424
+ }
1425
+
1426
+ let isValid = true;
1427
+ // Unsafe bindings must have a name and type.
1428
+ if (!isRequiredProperty(value, "name", "string")) {
1429
+ diagnostics.errors.push(`binding should have a string "name" field.`);
1430
+ isValid = false;
1431
+ }
1432
+ if (isRequiredProperty(value, "type", "string")) {
1433
+ const safeBindings = [
1434
+ "plain_text",
1435
+ "json",
1436
+ "wasm_module",
1437
+ "data_blob",
1438
+ "text_blob",
1439
+ "kv_namespace",
1440
+ "durable_object_namespace",
1441
+ "r2_bucket",
1442
+ "service",
1443
+ ];
1444
+
1445
+ if (safeBindings.includes(value.type)) {
1446
+ diagnostics.warnings.push(
1447
+ `The binding type "${value.type}" is directly supported by wrangler.\n` +
1448
+ `Consider migrating this unsafe binding to a format for '${value.type}' bindings that is supported by wrangler for optimal support.\n` +
1449
+ "For more details, see https://developers.cloudflare.com/workers/cli-wrangler/configuration"
1450
+ );
1451
+ }
1452
+ } else {
1453
+ diagnostics.errors.push(`binding should have a string "type" field.`);
1454
+ isValid = false;
1455
+ }
1456
+ return isValid;
890
1457
  };
891
1458
 
892
1459
  /**
893
1460
  * Check that the given environment field is a valid array of bindings.
894
1461
  */
895
1462
  const validateBindingArray =
896
- (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
897
- (diagnostics, field, envValue, config) => {
898
- if (envValue === undefined) {
899
- return true;
900
- }
901
-
902
- const fieldPath =
903
- config === undefined ? `${field}` : `env.${envName}.${field}`;
904
- if (!Array.isArray(envValue)) {
905
- diagnostics.errors.push(
906
- `The field "${fieldPath}" should be an array but got ${JSON.stringify(
907
- envValue
908
- )}.`
909
- );
910
- return false;
911
- }
912
-
913
- let isValid = true;
914
- for (let i = 0; i < envValue.length; i++) {
915
- isValid =
916
- validateBinding(
917
- diagnostics,
918
- `${fieldPath}[${i}]`,
919
- envValue[i],
920
- config
921
- ) && isValid;
922
- }
923
- const configValue = config?.[field as keyof Environment] as {
924
- binding: unknown;
925
- }[];
926
- if (Array.isArray(configValue)) {
927
- const configBindingNames = configValue.map((value) => value.binding);
928
- // If there are no top level bindings then there is nothing to do here.
929
- if (configBindingNames.length > 0) {
930
- const envBindingNames = new Set(envValue.map((value) => value.binding));
931
- for (const configBindingName of configBindingNames) {
932
- if (!envBindingNames.has(configBindingName)) {
933
- diagnostics.warnings.push(
934
- `There is a ${field} binding with name "${configBindingName}" at the top level, but not on "env.${envName}".\n` +
935
- `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
936
- `Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bindings".`
937
- );
938
- }
939
- }
940
- }
941
- }
942
- return isValid;
943
- };
1463
+ (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
1464
+ (diagnostics, field, envValue, config) => {
1465
+ if (envValue === undefined) {
1466
+ return true;
1467
+ }
1468
+
1469
+ const fieldPath =
1470
+ config === undefined ? `${field}` : `env.${envName}.${field}`;
1471
+ if (!Array.isArray(envValue)) {
1472
+ diagnostics.errors.push(
1473
+ `The field "${fieldPath}" should be an array but got ${JSON.stringify(
1474
+ envValue
1475
+ )}.`
1476
+ );
1477
+ return false;
1478
+ }
1479
+
1480
+ let isValid = true;
1481
+ for (let i = 0; i < envValue.length; i++) {
1482
+ isValid =
1483
+ validateBinding(
1484
+ diagnostics,
1485
+ `${fieldPath}[${i}]`,
1486
+ envValue[i],
1487
+ config
1488
+ ) && isValid;
1489
+ }
1490
+ const configValue = config?.[field as keyof Environment] as {
1491
+ binding: unknown;
1492
+ }[];
1493
+ if (Array.isArray(configValue)) {
1494
+ const configBindingNames = configValue.map((value) => value.binding);
1495
+ // If there are no top level bindings then there is nothing to do here.
1496
+ if (configBindingNames.length > 0) {
1497
+ const envBindingNames = new Set(envValue.map((value) => value.binding));
1498
+ for (const configBindingName of configBindingNames) {
1499
+ if (!envBindingNames.has(configBindingName)) {
1500
+ diagnostics.warnings.push(
1501
+ `There is a ${field} binding with name "${configBindingName}" at the top level, but not on "env.${envName}".\n` +
1502
+ `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1503
+ `Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bindings".`
1504
+ );
1505
+ }
1506
+ }
1507
+ }
1508
+ }
1509
+ return isValid;
1510
+ };
944
1511
 
945
1512
  const validateKVBinding: ValidatorFn = (diagnostics, field, value) => {
946
- if (typeof value !== "object" || value === null) {
947
- diagnostics.errors.push(
948
- `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
949
- value
950
- )}`
951
- );
952
- return false;
953
- }
954
- let isValid = true;
955
- // KV bindings must have a binding and id.
956
- if (!isRequiredProperty(value, "binding", "string")) {
957
- diagnostics.errors.push(
958
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
959
- value
960
- )}.`
961
- );
962
- isValid = false;
963
- }
964
- if (!isRequiredProperty(value, "id", "string")) {
965
- diagnostics.errors.push(
966
- `"${field}" bindings should have a string "id" field but got ${JSON.stringify(
967
- value
968
- )}.`
969
- );
970
- isValid = false;
971
- }
972
- if (!isOptionalProperty(value, "preview_id", "string")) {
973
- diagnostics.errors.push(
974
- `"${field}" bindings should, optionally, have a string "preview_id" field but got ${JSON.stringify(
975
- value
976
- )}.`
977
- );
978
- isValid = false;
979
- }
980
- return isValid;
1513
+ if (typeof value !== "object" || value === null) {
1514
+ diagnostics.errors.push(
1515
+ `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
1516
+ value
1517
+ )}`
1518
+ );
1519
+ return false;
1520
+ }
1521
+ let isValid = true;
1522
+ // KV bindings must have a binding and id.
1523
+ if (!isRequiredProperty(value, "binding", "string")) {
1524
+ diagnostics.errors.push(
1525
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1526
+ value
1527
+ )}.`
1528
+ );
1529
+ isValid = false;
1530
+ }
1531
+ if (!isRequiredProperty(value, "id", "string")) {
1532
+ diagnostics.errors.push(
1533
+ `"${field}" bindings should have a string "id" field but got ${JSON.stringify(
1534
+ value
1535
+ )}.`
1536
+ );
1537
+ isValid = false;
1538
+ }
1539
+ if (!isOptionalProperty(value, "preview_id", "string")) {
1540
+ diagnostics.errors.push(
1541
+ `"${field}" bindings should, optionally, have a string "preview_id" field but got ${JSON.stringify(
1542
+ value
1543
+ )}.`
1544
+ );
1545
+ isValid = false;
1546
+ }
1547
+ return isValid;
981
1548
  };
982
1549
 
983
1550
  const validateR2Binding: ValidatorFn = (diagnostics, field, value) => {
984
- if (typeof value !== "object" || value === null) {
985
- diagnostics.errors.push(
986
- `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
987
- value
988
- )}`
989
- );
990
- return false;
991
- }
992
- let isValid = true;
993
- // R2 bindings must have a binding and bucket_name.
994
- if (!isRequiredProperty(value, "binding", "string")) {
995
- diagnostics.errors.push(
996
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
997
- value
998
- )}.`
999
- );
1000
- isValid = false;
1001
- }
1002
- if (!isRequiredProperty(value, "bucket_name", "string")) {
1003
- diagnostics.errors.push(
1004
- `"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
1005
- value
1006
- )}.`
1007
- );
1008
- isValid = false;
1009
- }
1010
- if (!isOptionalProperty(value, "preview_bucket_name", "string")) {
1011
- diagnostics.errors.push(
1012
- `"${field}" bindings should, optionally, have a string "preview_bucket_name" field but got ${JSON.stringify(
1013
- value
1014
- )}.`
1015
- );
1016
- isValid = false;
1017
- }
1018
- return isValid;
1551
+ if (typeof value !== "object" || value === null) {
1552
+ diagnostics.errors.push(
1553
+ `"r2_buckets" bindings should be objects, but got ${JSON.stringify(
1554
+ value
1555
+ )}`
1556
+ );
1557
+ return false;
1558
+ }
1559
+ let isValid = true;
1560
+ // R2 bindings must have a binding and bucket_name.
1561
+ if (!isRequiredProperty(value, "binding", "string")) {
1562
+ diagnostics.errors.push(
1563
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1564
+ value
1565
+ )}.`
1566
+ );
1567
+ isValid = false;
1568
+ }
1569
+ if (!isRequiredProperty(value, "bucket_name", "string")) {
1570
+ diagnostics.errors.push(
1571
+ `"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
1572
+ value
1573
+ )}.`
1574
+ );
1575
+ isValid = false;
1576
+ }
1577
+ if (!isOptionalProperty(value, "preview_bucket_name", "string")) {
1578
+ diagnostics.errors.push(
1579
+ `"${field}" bindings should, optionally, have a string "preview_bucket_name" field but got ${JSON.stringify(
1580
+ value
1581
+ )}.`
1582
+ );
1583
+ isValid = false;
1584
+ }
1585
+ return isValid;
1586
+ };
1587
+
1588
+ /**
1589
+ * Check that bindings whose names might conflict, don't.
1590
+ *
1591
+ * We don't want to have, for example, a KV namespace named "DATA"
1592
+ * and a Durable Object also named "DATA". Then it would be ambiguous
1593
+ * what exactly would live at `env.DATA` (or in the case of service-workers,
1594
+ * the `DATA` global).
1595
+ */
1596
+ const validateBindingsHaveUniqueNames = (
1597
+ diagnostics: Diagnostics,
1598
+ {
1599
+ durable_objects,
1600
+ kv_namespaces,
1601
+ r2_buckets,
1602
+ text_blobs,
1603
+ unsafe,
1604
+ vars,
1605
+ define,
1606
+ wasm_modules,
1607
+ data_blobs,
1608
+ }: Partial<Config>
1609
+ ): boolean => {
1610
+ let hasDuplicates = false;
1611
+
1612
+ const bindingsGroupedByType = {
1613
+ "Durable Object": getBindingNames(durable_objects),
1614
+ "KV Namespace": getBindingNames(kv_namespaces),
1615
+ "R2 Bucket": getBindingNames(r2_buckets),
1616
+ "Text Blob": getBindingNames(text_blobs),
1617
+ Unsafe: getBindingNames(unsafe),
1618
+ "Environment Variable": getBindingNames(vars),
1619
+ Definition: getBindingNames(define),
1620
+ "WASM Module": getBindingNames(wasm_modules),
1621
+ "Data Blob": getBindingNames(data_blobs),
1622
+ } as Record<string, string[]>;
1623
+
1624
+ const bindingsGroupedByName: Record<string, string[]> = {};
1625
+
1626
+ for (const bindingType in bindingsGroupedByType) {
1627
+ const bindingNames = bindingsGroupedByType[bindingType];
1628
+
1629
+ for (const bindingName of bindingNames) {
1630
+ if (!(bindingName in bindingsGroupedByName)) {
1631
+ bindingsGroupedByName[bindingName] = [];
1632
+ }
1633
+
1634
+ bindingsGroupedByName[bindingName].push(bindingType);
1635
+ }
1636
+ }
1637
+
1638
+ for (const bindingName in bindingsGroupedByName) {
1639
+ const bindingTypes = bindingsGroupedByName[bindingName];
1640
+ if (bindingTypes.length < 2) {
1641
+ // there's only one (or zero) binding(s) with this name, which is fine, actually
1642
+ continue;
1643
+ }
1644
+
1645
+ hasDuplicates = true;
1646
+
1647
+ // there's two types of duplicates we want to look for:
1648
+ // - bindings with the same name of the same type (e.g. two Durable Objects both named "OBJ")
1649
+ // - bindings with the same name of different types (a KV namespace and DO both named "DATA")
1650
+
1651
+ const sameType = bindingTypes
1652
+ // filter once to find duplicate binding types
1653
+ .filter((type, i) => bindingTypes.indexOf(type) !== i)
1654
+ // filter twice to only get _unique_ duplicate binding types
1655
+ .filter(
1656
+ (type, i, duplicateBindingTypes) =>
1657
+ duplicateBindingTypes.indexOf(type) === i
1658
+ );
1659
+
1660
+ const differentTypes = bindingTypes.filter(
1661
+ (type, i) => bindingTypes.indexOf(type) === i
1662
+ );
1663
+
1664
+ if (differentTypes.length > 1) {
1665
+ // we have multiple different types using the same name
1666
+ diagnostics.errors.push(
1667
+ `${bindingName} assigned to ${ENGLISH.format(differentTypes)} bindings.`
1668
+ );
1669
+ }
1670
+
1671
+ sameType.forEach((bindingType) => {
1672
+ diagnostics.errors.push(
1673
+ `${bindingName} assigned to multiple ${bindingType} bindings.`
1674
+ );
1675
+ });
1676
+ }
1677
+
1678
+ if (hasDuplicates) {
1679
+ const problem =
1680
+ "Bindings must have unique names, so that they can all be referenced in the worker.";
1681
+ const resolution = "Please change your bindings to have unique names.";
1682
+ diagnostics.errors.push(`${problem}\n${resolution}`);
1683
+ }
1684
+
1685
+ return !hasDuplicates;
1686
+ };
1687
+
1688
+ const validateServiceBinding: ValidatorFn = (diagnostics, field, value) => {
1689
+ if (typeof value !== "object" || value === null) {
1690
+ diagnostics.errors.push(
1691
+ `"services" bindings should be objects, but got ${JSON.stringify(value)}`
1692
+ );
1693
+ return false;
1694
+ }
1695
+ let isValid = true;
1696
+ // Service bindings must have a binding, service, and environment.
1697
+ if (!isRequiredProperty(value, "binding", "string")) {
1698
+ diagnostics.errors.push(
1699
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1700
+ value
1701
+ )}.`
1702
+ );
1703
+ isValid = false;
1704
+ }
1705
+ if (!isRequiredProperty(value, "service", "string")) {
1706
+ diagnostics.errors.push(
1707
+ `"${field}" bindings should have a string "service" field but got ${JSON.stringify(
1708
+ value
1709
+ )}.`
1710
+ );
1711
+ isValid = false;
1712
+ }
1713
+ if (!isOptionalProperty(value, "environment", "string")) {
1714
+ diagnostics.errors.push(
1715
+ `"${field}" bindings should have a string "environment" field but got ${JSON.stringify(
1716
+ value
1717
+ )}.`
1718
+ );
1719
+ isValid = false;
1720
+ }
1721
+ return isValid;
1722
+ };
1723
+
1724
+ const validateWorkerNamespaceBinding: ValidatorFn = (
1725
+ diagnostics,
1726
+ field,
1727
+ value
1728
+ ) => {
1729
+ if (typeof value !== "object" || value === null) {
1730
+ diagnostics.errors.push(
1731
+ `"${field}" binding should be objects, but got ${JSON.stringify(value)}`
1732
+ );
1733
+ return false;
1734
+ }
1735
+ let isValid = true;
1736
+ // Worker namespace bindings must have a binding, and a namespace.
1737
+ if (!isRequiredProperty(value, "binding", "string")) {
1738
+ diagnostics.errors.push(
1739
+ `"${field}" should have a string "binding" field but got ${JSON.stringify(
1740
+ value
1741
+ )}.`
1742
+ );
1743
+ isValid = false;
1744
+ }
1745
+ if (!isRequiredProperty(value, "namespace", "string")) {
1746
+ diagnostics.errors.push(
1747
+ `"${field}" should have a string "namespace" field but got ${JSON.stringify(
1748
+ value
1749
+ )}.`
1750
+ );
1751
+ isValid = false;
1752
+ }
1753
+ return isValid;
1019
1754
  };