wrangler 0.0.0-e64812e → 0.0.0-e8e684c7

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