wrangler 0.0.0-e88a54e → 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 (222) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +161 -29
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5484 -21
  6. package/package.json +173 -143
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +4016 -2786
  10. package/src/__tests__/dev.test.tsx +1305 -483
  11. package/src/__tests__/generate.test.ts +91 -0
  12. package/src/__tests__/guess-worker-format.test.ts +75 -48
  13. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  14. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  15. package/src/__tests__/helpers/mock-bin.ts +20 -20
  16. package/src/__tests__/helpers/mock-cfetch.ts +182 -93
  17. package/src/__tests__/helpers/mock-console.ts +59 -32
  18. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  19. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +74 -0
  22. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  23. package/src/__tests__/helpers/mock-kv.ts +26 -26
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  25. package/src/__tests__/helpers/mock-process.ts +39 -0
  26. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  27. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  28. package/src/__tests__/helpers/run-in-tmp.ts +28 -22
  29. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  30. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  31. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  32. package/src/__tests__/https-options.test.ts +144 -108
  33. package/src/__tests__/index.test.ts +229 -975
  34. package/src/__tests__/init.test.ts +2170 -0
  35. package/src/__tests__/jest.setup.ts +122 -34
  36. package/src/__tests__/kv.test.ts +1376 -1087
  37. package/src/__tests__/logger.test.ts +141 -0
  38. package/src/__tests__/metrics.test.ts +450 -0
  39. package/src/__tests__/package-manager.test.ts +312 -165
  40. package/src/__tests__/pages.test.ts +1270 -39
  41. package/src/__tests__/parse.test.ts +253 -245
  42. package/src/__tests__/publish.test.ts +6878 -2627
  43. package/src/__tests__/pubsub.test.ts +367 -0
  44. package/src/__tests__/r2.test.ts +328 -190
  45. package/src/__tests__/route.test.ts +22 -22
  46. package/src/__tests__/secret.test.ts +474 -407
  47. package/src/__tests__/tail.test.ts +679 -441
  48. package/src/__tests__/test-old-node-version.js +31 -0
  49. package/src/__tests__/user.test.ts +155 -0
  50. package/src/__tests__/validate-dev-props.test.ts +56 -0
  51. package/src/__tests__/version.test.ts +35 -0
  52. package/src/__tests__/whoami.test.tsx +276 -87
  53. package/src/__tests__/worker-namespace.test.ts +329 -0
  54. package/src/abort.d.ts +3 -0
  55. package/src/api/dev.ts +93 -0
  56. package/src/api/index.ts +1 -0
  57. package/src/bundle-reporter.tsx +29 -0
  58. package/src/bundle.ts +441 -110
  59. package/src/cfetch/index.ts +83 -66
  60. package/src/cfetch/internal.ts +251 -92
  61. package/src/cli.ts +22 -14
  62. package/src/config/README.md +1 -1
  63. package/src/config/config.ts +224 -179
  64. package/src/config/diagnostics.ts +61 -61
  65. package/src/config/environment.ts +430 -311
  66. package/src/config/index.ts +227 -38
  67. package/src/config/validation-helpers.ts +414 -303
  68. package/src/config/validation.ts +1745 -973
  69. package/src/config-cache.ts +85 -0
  70. package/src/create-worker-preview.ts +209 -118
  71. package/src/create-worker-upload-form.ts +275 -201
  72. package/src/dev/dev-vars.ts +36 -0
  73. package/src/dev/dev.tsx +488 -307
  74. package/src/dev/local.tsx +427 -210
  75. package/src/dev/remote.tsx +407 -188
  76. package/src/dev/use-esbuild.ts +156 -78
  77. package/src/dev/validate-dev-props.ts +31 -0
  78. package/src/dev-registry.tsx +160 -0
  79. package/src/dev.tsx +696 -0
  80. package/src/dialogs.tsx +115 -57
  81. package/src/dispatch-namespace.ts +206 -0
  82. package/src/durable.ts +102 -0
  83. package/src/entry.ts +267 -147
  84. package/src/environment-variables.ts +25 -23
  85. package/src/errors.ts +11 -0
  86. package/src/faye-websocket.d.ts +6 -0
  87. package/src/generate.ts +131 -0
  88. package/src/git-client.ts +42 -0
  89. package/src/global-wrangler-config-path.ts +26 -0
  90. package/src/https-options.ts +85 -80
  91. package/src/index.tsx +2191 -2304
  92. package/src/init.ts +622 -0
  93. package/src/inspect.ts +687 -557
  94. package/src/intl-polyfill.d.ts +139 -0
  95. package/src/is-ci.ts +14 -0
  96. package/src/is-interactive.ts +12 -0
  97. package/src/kv.ts +353 -242
  98. package/src/logger.ts +73 -0
  99. package/src/metrics/index.ts +5 -0
  100. package/src/metrics/metrics-config.ts +239 -0
  101. package/src/metrics/metrics-dispatcher.ts +96 -0
  102. package/src/metrics/metrics-usage-headers.ts +24 -0
  103. package/src/metrics/send-event.ts +92 -0
  104. package/src/miniflare-cli/assets.ts +554 -0
  105. package/src/miniflare-cli/enum-keys.ts +8 -8
  106. package/src/miniflare-cli/index.ts +199 -29
  107. package/src/miniflare-cli/request-context.ts +40 -0
  108. package/src/module-collection.ts +213 -213
  109. package/src/open-in-browser.ts +8 -16
  110. package/src/package-manager.ts +183 -90
  111. package/src/pages/build.tsx +238 -0
  112. package/src/pages/constants.ts +12 -0
  113. package/src/pages/deployments.tsx +106 -0
  114. package/src/pages/dev.tsx +528 -0
  115. package/src/pages/errors.ts +22 -0
  116. package/src/pages/functions/buildPlugin.ts +109 -0
  117. package/src/pages/functions/buildWorker.ts +155 -0
  118. package/src/pages/functions/filepath-routing.test.ts +234 -0
  119. package/src/pages/functions/filepath-routing.ts +189 -0
  120. package/src/pages/functions/identifiers.ts +78 -0
  121. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  122. package/src/pages/functions/routes-consolidation.ts +73 -0
  123. package/src/pages/functions/routes-transformation.test.ts +271 -0
  124. package/src/pages/functions/routes-transformation.ts +122 -0
  125. package/src/pages/functions/routes.ts +151 -0
  126. package/src/pages/functions.tsx +96 -0
  127. package/src/pages/index.tsx +94 -0
  128. package/src/pages/projects.tsx +169 -0
  129. package/src/pages/publish.tsx +391 -0
  130. package/src/pages/types.ts +49 -0
  131. package/src/pages/upload.tsx +413 -0
  132. package/src/pages/utils.ts +12 -0
  133. package/src/parse.ts +224 -121
  134. package/src/paths.ts +6 -6
  135. package/src/preview.ts +31 -0
  136. package/src/proxy.ts +416 -370
  137. package/src/publish.ts +796 -321
  138. package/src/pubsub/index.ts +286 -0
  139. package/src/pubsub/pubsub-commands.tsx +623 -0
  140. package/src/r2.ts +100 -19
  141. package/src/selfsigned.d.ts +23 -23
  142. package/src/sites.tsx +281 -189
  143. package/src/tail/filters.ts +111 -109
  144. package/src/tail/index.ts +230 -217
  145. package/src/tail/printing.ts +92 -47
  146. package/src/update-check.ts +19 -0
  147. package/src/user/choose-account.tsx +69 -0
  148. package/src/user/env-vars.ts +46 -0
  149. package/src/user/generate-auth-url.ts +33 -0
  150. package/src/user/generate-random-state.ts +16 -0
  151. package/src/user/index.ts +3 -0
  152. package/src/user/user.tsx +1191 -0
  153. package/src/whoami.tsx +142 -42
  154. package/src/worker.ts +135 -94
  155. package/src/zones.ts +167 -0
  156. package/templates/checked-fetch.js +17 -0
  157. package/templates/first-party-worker-module-facade.ts +18 -0
  158. package/templates/format-dev-errors.ts +32 -0
  159. package/templates/gitignore +171 -0
  160. package/templates/new-worker-scheduled.js +17 -0
  161. package/templates/new-worker-scheduled.ts +32 -0
  162. package/templates/new-worker.js +3 -3
  163. package/templates/new-worker.ts +18 -3
  164. package/templates/no-op-worker.js +10 -0
  165. package/templates/pages-shim.ts +9 -0
  166. package/templates/pages-template-plugin.ts +167 -0
  167. package/templates/pages-template-worker.ts +172 -0
  168. package/templates/serve-static-assets.ts +63 -0
  169. package/templates/service-bindings-module-facade.js +54 -0
  170. package/templates/service-bindings-sw-facade.js +42 -0
  171. package/templates/tsconfig.json +95 -95
  172. package/wrangler-dist/cli.d.ts +338 -0
  173. package/wrangler-dist/cli.js +124611 -112403
  174. package/miniflare-dist/index.mjs.map +0 -7
  175. package/pages/functions/buildWorker.ts +0 -62
  176. package/pages/functions/filepath-routing.test.ts +0 -223
  177. package/pages/functions/filepath-routing.ts +0 -181
  178. package/pages/functions/identifiers.ts +0 -78
  179. package/pages/functions/routes.ts +0 -151
  180. package/pages/functions/template-worker.ts +0 -130
  181. package/src/__tests__/dev2.test.tsx +0 -154
  182. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  183. package/src/__tests__/logout.test.ts +0 -52
  184. package/src/__tests__/sentry.test.ts +0 -146
  185. package/src/pages.tsx +0 -1047
  186. package/src/reporting.ts +0 -131
  187. package/src/user.tsx +0 -1118
  188. package/templates/static-asset-facade.js +0 -47
  189. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  190. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  191. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  192. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  193. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  194. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  195. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  196. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  197. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  198. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  199. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  200. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  201. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  202. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  203. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  204. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  205. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  206. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  207. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  208. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  209. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  210. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  211. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  212. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  213. package/vendor/wrangler-mime/LICENSE +0 -21
  214. package/vendor/wrangler-mime/Mime.js +0 -97
  215. package/vendor/wrangler-mime/README.md +0 -187
  216. package/vendor/wrangler-mime/cli.js +0 -46
  217. package/vendor/wrangler-mime/index.js +0 -4
  218. package/vendor/wrangler-mime/lite.js +0 -4
  219. package/vendor/wrangler-mime/package.json +0 -52
  220. package/vendor/wrangler-mime/types/other.js +0 -1
  221. package/vendor/wrangler-mime/types/standard.js +0 -1
  222. package/wrangler-dist/cli.js.map +0 -7
@@ -2,36 +2,41 @@ import path from "node:path";
2
2
  import TOML from "@iarna/toml";
3
3
  import { Diagnostics } from "./diagnostics";
4
4
  import {
5
- deprecated,
6
- experimental,
7
- hasProperty,
8
- inheritable,
9
- isBoolean,
10
- isObjectWith,
11
- isOneOf,
12
- isOptionalProperty,
13
- isRequiredProperty,
14
- isString,
15
- isStringArray,
16
- validateAdditionalProperties,
17
- notInheritable,
18
- validateOptionalProperty,
19
- validateOptionalTypedArray,
20
- validateRequiredProperty,
21
- validateTypedArray,
22
- all,
23
- isMutuallyExclusiveWith,
24
- inheritableInLegacyEnvironments,
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,
25
28
  } from "./validation-helpers";
26
29
  import type { Config, DevConfig, RawConfig, RawDevConfig } from "./config";
27
30
  import type {
28
- RawEnvironment,
29
- DeprecatedUpload,
30
- Environment,
31
- Rule,
31
+ RawEnvironment,
32
+ DeprecatedUpload,
33
+ Environment,
34
+ Rule,
32
35
  } from "./environment";
33
36
  import type { ValidatorFn } from "./validation-helpers";
34
37
 
38
+ const ENGLISH = new Intl.ListFormat("en");
39
+
35
40
  /**
36
41
  * Validate the given `rawConfig` object that was loaded from `configPath`.
37
42
  *
@@ -41,882 +46,1469 @@ import type { ValidatorFn } from "./validation-helpers";
41
46
  * Any errors or warnings from the validation are available in the returned `diagnostics` object.
42
47
  */
43
48
  export function normalizeAndValidateConfig(
44
- rawConfig: RawConfig,
45
- configPath: string | undefined,
46
- envName: string | undefined
49
+ rawConfig: RawConfig,
50
+ configPath: string | undefined,
51
+ args: unknown
47
52
  ): {
48
- config: Config;
49
- diagnostics: Diagnostics;
53
+ config: Config;
54
+ diagnostics: Diagnostics;
50
55
  } {
51
- const diagnostics = new Diagnostics(
52
- `Processing ${
53
- configPath ? path.relative(process.cwd(), configPath) : "wrangler"
54
- } configuration:`
55
- );
56
-
57
- deprecated(
58
- diagnostics,
59
- rawConfig,
60
- "type",
61
- "DO NOT USE THIS. Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
62
- true
63
- );
64
-
65
- deprecated(
66
- diagnostics,
67
- rawConfig,
68
- "webpack_config",
69
- "DO NOT USE THIS. Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
70
- true
71
- );
72
-
73
- deprecated(
74
- diagnostics,
75
- rawConfig,
76
- `site.entry-point`,
77
- `The \`site.entry-point\` config field is no longer used.\nThe entry-point should be specified via the command line or the \`main\` config field.`,
78
- false,
79
- true
80
- );
81
-
82
- validateOptionalProperty(
83
- diagnostics,
84
- "",
85
- "legacy_env",
86
- rawConfig.legacy_env,
87
- "boolean"
88
- );
89
-
90
- // TODO: set the default to false to turn on service environments as the default
91
- const isLegacyEnv = rawConfig.legacy_env ?? true;
92
-
93
- const topLevelEnv = normalizeAndValidateEnvironment(
94
- diagnostics,
95
- configPath,
96
- rawConfig
97
- );
98
-
99
- let activeEnv = topLevelEnv;
100
- if (envName !== undefined) {
101
- const rawEnv = rawConfig.env?.[envName];
102
- if (rawEnv !== undefined) {
103
- const envDiagnostics = new Diagnostics(
104
- `"env.${envName}" environment configuration`
105
- );
106
- activeEnv = normalizeAndValidateEnvironment(
107
- envDiagnostics,
108
- configPath,
109
- rawEnv,
110
- envName,
111
- topLevelEnv,
112
- isLegacyEnv,
113
- rawConfig
114
- );
115
- diagnostics.addChild(envDiagnostics);
116
- } else {
117
- const envNames = rawConfig.env
118
- ? `The available configured environment names are: ${JSON.stringify(
119
- Object.keys(rawConfig.env)
120
- )}\n`
121
- : "";
122
- const message =
123
- `No environment found in configuration with name "${envName}".\n` +
124
- `Before using \`--env=${envName}\` there should be an equivalent environment section in the configuration.\n` +
125
- `${envNames}\n` +
126
- `Consider adding an environment configuration section to the wrangler.toml file:\n` +
127
- "```\n[env." +
128
- envName +
129
- "]\n```\n";
130
-
131
- if (envNames.length > 0) {
132
- diagnostics.errors.push(message);
133
- } else {
134
- // Only warn (rather than error) if there are not actually any environments configured in wrangler.toml.
135
- diagnostics.warnings.push(message);
136
- }
137
- }
138
- }
139
-
140
- // Process the top-level default environment configuration.
141
- const config: Config = {
142
- configPath,
143
- legacy_env: isLegacyEnv,
144
- ...activeEnv,
145
- dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}),
146
- migrations: normalizeAndValidateMigrations(
147
- diagnostics,
148
- rawConfig.migrations ?? []
149
- ),
150
- site: normalizeAndValidateSite(diagnostics, rawConfig.site),
151
- wasm_modules: normalizeAndValidateModulePaths(
152
- diagnostics,
153
- configPath,
154
- "wasm_modules",
155
- rawConfig.wasm_modules
156
- ),
157
- text_blobs: normalizeAndValidateModulePaths(
158
- diagnostics,
159
- configPath,
160
- "text_blobs",
161
- rawConfig.text_blobs
162
- ),
163
- };
164
-
165
- validateAdditionalProperties(
166
- diagnostics,
167
- "top-level",
168
- Object.keys(rawConfig),
169
- [...Object.keys(config), "env", "miniflare"]
170
- );
171
-
172
- 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 };
173
231
  }
174
232
 
175
233
  /**
176
234
  * Validate the `build` configuration and return the normalized values.
177
235
  */
178
236
  function normalizeAndValidateBuild(
179
- diagnostics: Diagnostics,
180
- rawEnv: RawEnvironment,
181
- rawBuild: Config["build"],
182
- configPath: string | undefined
237
+ diagnostics: Diagnostics,
238
+ rawEnv: RawEnvironment,
239
+ rawBuild: Config["build"],
240
+ configPath: string | undefined
183
241
  ): Config["build"] & { deprecatedUpload: DeprecatedUpload } {
184
- const { command, cwd, watch_dir, upload, ...rest } = rawBuild;
185
- const deprecatedUpload: DeprecatedUpload = { ...upload };
186
- validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
187
-
188
- validateOptionalProperty(diagnostics, "build", "command", command, "string");
189
- validateOptionalProperty(diagnostics, "build", "cwd", cwd, "string");
190
- validateOptionalProperty(
191
- diagnostics,
192
- "build",
193
- "watch_dir",
194
- watch_dir,
195
- "string"
196
- );
197
-
198
- deprecated(
199
- diagnostics,
200
- rawEnv,
201
- "build.upload.format",
202
- "The format is inferred automatically from the code.",
203
- true
204
- );
205
-
206
- if (rawEnv.main !== undefined && rawBuild.upload?.main) {
207
- diagnostics.errors.push(
208
- `Don't define both the \`main\` and \`build.upload.main\` fields in your configuration.\n` +
209
- `They serve the same purpose: to point to the entry-point of your worker.\n` +
210
- `Delete the \`build.upload.main\` and \`build.upload.dir\` field from your config.`
211
- );
212
- } else {
213
- deprecated(
214
- diagnostics,
215
- rawEnv,
216
- "build.upload.main",
217
- `Delete the \`build.upload.main\` and \`build.upload.dir\` fields.\n` +
218
- `Then add the top level \`main\` field to your configuration file:\n` +
219
- `\`\`\`\n` +
220
- `main = "${path.join(
221
- rawBuild.upload?.dir ?? "./dist",
222
- rawBuild.upload?.main ?? "."
223
- )}"\n` +
224
- `\`\`\``,
225
- true
226
- );
227
-
228
- deprecated(
229
- diagnostics,
230
- rawEnv,
231
- "build.upload.dir",
232
- `Use the top level "main" field or a command-line argument to specify the entry-point for the Worker.`,
233
- true
234
- );
235
- }
236
-
237
- return {
238
- command,
239
- watch_dir:
240
- // - `watch_dir` only matters when `command` is defined, so we apply
241
- // a default only when `command` is defined
242
- // - `configPath` will always be defined since `build` can only
243
- // be configured in `wrangler.toml`, but who knows, that may
244
- // change in the future, so we do a check anyway
245
- command
246
- ? configPath
247
- ? path.relative(
248
- process.cwd(),
249
- path.join(path.dirname(configPath), watch_dir || "./src")
250
- )
251
- : watch_dir || "./src"
252
- : watch_dir,
253
- cwd,
254
- deprecatedUpload,
255
- };
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
+ };
256
323
  }
257
324
 
258
325
  /**
259
326
  * Validate the `main` field and return the normalized values.
260
327
  */
261
328
  function normalizeAndValidateMainField(
262
- configPath: string | undefined,
263
- rawMain: string | undefined,
264
- deprecatedUpload: DeprecatedUpload | undefined
329
+ configPath: string | undefined,
330
+ rawMain: string | undefined,
331
+ deprecatedUpload: DeprecatedUpload | undefined
265
332
  ): string | undefined {
266
- const configDir = path.dirname(configPath ?? "wrangler.toml");
267
- if (rawMain !== undefined) {
268
- if (typeof rawMain === "string") {
269
- const directory = path.resolve(configDir);
270
- return path.resolve(directory, rawMain);
271
- } else {
272
- return rawMain;
273
- }
274
- } else if (deprecatedUpload?.main !== undefined) {
275
- const directory = path.resolve(
276
- configDir,
277
- deprecatedUpload?.dir || "./dist"
278
- );
279
- return path.resolve(directory, deprecatedUpload.main);
280
- } else {
281
- return;
282
- }
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
+ }
283
350
  }
284
351
 
285
352
  /**
286
353
  * Validate the `dev` configuration and return the normalized values.
287
354
  */
288
355
  function normalizeAndValidateDev(
289
- diagnostics: Diagnostics,
290
- rawDev: RawDevConfig
356
+ diagnostics: Diagnostics,
357
+ rawDev: RawDevConfig
291
358
  ): DevConfig {
292
- const {
293
- ip = "localhost",
294
- port = 8787,
295
- local_protocol = "http",
296
- upstream_protocol = "https",
297
- host,
298
- ...rest
299
- } = rawDev;
300
- validateAdditionalProperties(diagnostics, "dev", Object.keys(rest), []);
301
-
302
- validateOptionalProperty(diagnostics, "dev", "ip", ip, "string");
303
- validateOptionalProperty(diagnostics, "dev", "port", port, "number");
304
- validateOptionalProperty(
305
- diagnostics,
306
- "dev",
307
- "local_protocol",
308
- local_protocol,
309
- "string",
310
- ["http", "https"]
311
- );
312
- validateOptionalProperty(
313
- diagnostics,
314
- "dev",
315
- "upstream_protocol",
316
- upstream_protocol,
317
- "string",
318
- ["http", "https"]
319
- );
320
- validateOptionalProperty(diagnostics, "dev", "host", host, "string");
321
- 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 };
322
397
  }
323
398
 
324
399
  /**
325
400
  * Validate the `migrations` configuration and return the normalized values.
326
401
  */
327
402
  function normalizeAndValidateMigrations(
328
- diagnostics: Diagnostics,
329
- rawMigrations: Config["migrations"]
403
+ diagnostics: Diagnostics,
404
+ rawMigrations: Config["migrations"],
405
+ durableObjects: Config["durable_objects"]
330
406
  ): Config["migrations"] {
331
- if (!Array.isArray(rawMigrations)) {
332
- diagnostics.errors.push(
333
- `The optional "migrations" field should be an array, but got ${JSON.stringify(
334
- rawMigrations
335
- )}`
336
- );
337
- return [];
338
- } else {
339
- for (let i = 0; i < rawMigrations.length; i++) {
340
- const migration = rawMigrations[i];
341
- validateRequiredProperty(
342
- diagnostics,
343
- `migrations[${i}]`,
344
- `tag`,
345
- migration.tag,
346
- "string"
347
- );
348
- validateOptionalTypedArray(
349
- diagnostics,
350
- `migrations[${i}].new_classes`,
351
- migration.new_classes,
352
- "string"
353
- );
354
- if (migration.renamed_classes !== undefined) {
355
- if (!Array.isArray(migration.renamed_classes)) {
356
- diagnostics.errors.push(
357
- `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
358
- migration.renamed_classes
359
- )}.`
360
- );
361
- } else if (
362
- migration.renamed_classes.some(
363
- (c) =>
364
- typeof c !== "object" ||
365
- !isRequiredProperty(c, "from", "string") ||
366
- !isRequiredProperty(c, "to", "string")
367
- )
368
- ) {
369
- diagnostics.errors.push(
370
- `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
371
- migration.renamed_classes
372
- )}.`
373
- );
374
- }
375
- }
376
- validateOptionalTypedArray(
377
- diagnostics,
378
- `migrations[${i}].deleted_classes`,
379
- migration.deleted_classes,
380
- "string"
381
- );
382
- }
383
- return rawMigrations;
384
- }
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:
492
+
493
+ \`\`\`
494
+ [[migrations]]
495
+ tag = "v1" # Should be unique for each entry
496
+ new_classes = [${durableObjectClassnames
497
+ .map((name) => `"${name}"`)
498
+ .join(", ")}]
499
+ \`\`\`
500
+
501
+ Refer to https://developers.cloudflare.com/workers/learning/using-durable-objects/#durable-object-migrations-in-wranglertoml for more details.`
502
+ );
503
+ }
504
+ }
505
+ }
506
+
507
+ return rawMigrations;
508
+ }
385
509
  }
386
510
 
387
511
  /**
388
512
  * Validate the `site` configuration and return the normalized values.
389
513
  */
390
514
  function normalizeAndValidateSite(
391
- diagnostics: Diagnostics,
392
- rawSite: Config["site"]
515
+ diagnostics: Diagnostics,
516
+ configPath: string | undefined,
517
+ rawConfig: RawConfig,
518
+ mainEntryPoint: string | undefined
393
519
  ): Config["site"] {
394
- if (rawSite !== undefined) {
395
- const { bucket, include = [], exclude = [], ...rest } = rawSite;
396
- validateAdditionalProperties(diagnostics, "site", Object.keys(rest), []);
397
- validateRequiredProperty(diagnostics, "site", "bucket", bucket, "string");
398
- validateTypedArray(diagnostics, "sites.include", include, "string");
399
- validateTypedArray(diagnostics, "sites.exclude", exclude, "string");
400
- return { bucket, include, exclude };
401
- }
402
- 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
+ };
403
664
  }
404
665
 
405
666
  /**
406
- * Map the paths of the `wasm_modules` or `text_blobs` configuration to be relative to the current working directory.
667
+ * Map the paths of the `wasm_modules`, `text_blobs` or `data_blobs` configuration to be relative to the current working directory.
407
668
  */
408
669
  function normalizeAndValidateModulePaths(
409
- diagnostics: Diagnostics,
410
- configPath: string | undefined,
411
- field: "wasm_modules" | "text_blobs",
412
- 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
413
674
  ): Record<string, string> | undefined {
414
- if (rawMapping === undefined) {
415
- return undefined;
416
- }
417
- const mapping: Record<string, string> = {};
418
- // Rewrite paths to be relative to the cwd, rather than the config path.
419
- for (const [name, filePath] of Object.entries(rawMapping)) {
420
- if (isString(diagnostics, `${field}['${name}']`, filePath, undefined)) {
421
- if (configPath) {
422
- mapping[name] = configPath
423
- ? path.relative(
424
- process.cwd(),
425
- path.join(path.dirname(configPath), filePath)
426
- )
427
- : filePath;
428
- }
429
- }
430
- }
431
- 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;
693
+ }
694
+
695
+ /**
696
+ * Check whether a value has the shape of a route, which can be a string
697
+ * or an object that looks like {pattern: string, zone_id: string }
698
+ */
699
+ function isValidRouteValue(item: unknown): boolean {
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;
769
+ }
770
+
771
+ /**
772
+ * Validate that the field is a route.
773
+ */
774
+ const isRoute: ValidatorFn = (diagnostics, field, value) => {
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;
784
+ };
785
+
786
+ /**
787
+ * Validate that the field is an array of routes.
788
+ */
789
+ const isRouteArray: ValidatorFn = (diagnostics, field, value) => {
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;
815
+ };
816
+
817
+ function normalizeAndValidateRoute(
818
+ diagnostics: Diagnostics,
819
+ topLevelEnv: Environment | undefined,
820
+ rawEnv: RawEnvironment
821
+ ): Config["route"] {
822
+ return inheritable(
823
+ diagnostics,
824
+ topLevelEnv,
825
+ mutateEmptyStringRouteValue(diagnostics, rawEnv),
826
+ "route",
827
+ isRoute,
828
+ undefined
829
+ );
830
+ }
831
+
832
+ function validateRoutes(
833
+ diagnostics: Diagnostics,
834
+ topLevelEnv: Environment | undefined,
835
+ rawEnv: RawEnvironment
836
+ ): Config["routes"] {
837
+ return inheritable(
838
+ diagnostics,
839
+ topLevelEnv,
840
+ rawEnv,
841
+ "routes",
842
+ all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
843
+ undefined
844
+ );
432
845
  }
433
846
 
434
847
  /**
435
848
  * Validate top-level environment configuration and return the normalized values.
436
849
  */
437
850
  function normalizeAndValidateEnvironment(
438
- diagnostics: Diagnostics,
439
- configPath: string | undefined,
440
- topLevelEnv: RawEnvironment
851
+ diagnostics: Diagnostics,
852
+ configPath: string | undefined,
853
+ topLevelEnv: RawEnvironment
441
854
  ): Environment;
442
855
  /**
443
856
  * Validate the named environment configuration and return the normalized values.
444
857
  */
445
858
  function normalizeAndValidateEnvironment(
446
- diagnostics: Diagnostics,
447
- configPath: string | undefined,
448
- rawEnv: RawEnvironment,
449
- envName: string,
450
- topLevelEnv: Environment,
451
- isLegacyEnv: boolean,
452
- rawConfig: RawConfig
859
+ diagnostics: Diagnostics,
860
+ configPath: string | undefined,
861
+ rawEnv: RawEnvironment,
862
+ envName: string,
863
+ topLevelEnv: Environment,
864
+ isLegacyEnv: boolean,
865
+ rawConfig: RawConfig
453
866
  ): Environment;
454
867
  function normalizeAndValidateEnvironment(
455
- diagnostics: Diagnostics,
456
- configPath: string | undefined,
457
- rawEnv: RawEnvironment,
458
- envName = "top level",
459
- topLevelEnv?: Environment | undefined,
460
- isLegacyEnv?: boolean,
461
- 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
462
875
  ): Environment {
463
- deprecated(
464
- diagnostics,
465
- rawEnv,
466
- "zone_id",
467
- "This is unnecessary since we can deduce this from routes directly.",
468
- false // We need to leave this in-place for the moment since `route` commands might use it.
469
- );
470
-
471
- // The field "experimental_services" doesn't exist anymore in the config, but we still want to error about any older usage.
472
- // TODO: remove this before GA.
473
- deprecated(
474
- diagnostics,
475
- rawEnv,
476
- "experimental_services",
477
- `The "experimental_services" field is no longer supported. Instead, use [[unsafe.bindings]] to enable experimental features. Add this to your wrangler.toml:\n` +
478
- "```\n" +
479
- TOML.stringify({
480
- unsafe: {
481
- bindings: (rawEnv?.experimental_services || []).map(
482
- (serviceDefinition) => {
483
- return {
484
- name: serviceDefinition.name,
485
- type: "service",
486
- service: serviceDefinition.service,
487
- environment: serviceDefinition.environment,
488
- };
489
- }
490
- ),
491
- },
492
- }) +
493
- "```",
494
- true
495
- );
496
-
497
- experimental(diagnostics, rawEnv, "unsafe");
498
-
499
- const route = inheritable(
500
- diagnostics,
501
- topLevelEnv,
502
- rawEnv,
503
- "route",
504
- isString,
505
- undefined
506
- );
507
- const routes = inheritable(
508
- diagnostics,
509
- topLevelEnv,
510
- rawEnv,
511
- "routes",
512
- all(isStringArray, isMutuallyExclusiveWith(rawEnv, "route")),
513
- undefined
514
- );
515
- const workers_dev = inheritable(
516
- diagnostics,
517
- topLevelEnv,
518
- rawEnv,
519
- "workers_dev",
520
- isBoolean,
521
- !(routes || route)
522
- );
523
-
524
- const { deprecatedUpload, ...build } = normalizeAndValidateBuild(
525
- diagnostics,
526
- rawEnv,
527
- rawEnv.build ?? topLevelEnv?.build ?? {},
528
- configPath
529
- );
530
-
531
- const environment: Environment = {
532
- // Inherited fields
533
- account_id: inheritable(
534
- diagnostics,
535
- topLevelEnv,
536
- rawEnv,
537
- "account_id",
538
- isString,
539
- undefined
540
- ),
541
- compatibility_date: inheritable(
542
- diagnostics,
543
- topLevelEnv,
544
- rawEnv,
545
- "compatibility_date",
546
- isString,
547
- undefined
548
- ),
549
- compatibility_flags: inheritable(
550
- diagnostics,
551
- topLevelEnv,
552
- rawEnv,
553
- "compatibility_flags",
554
- isStringArray,
555
- []
556
- ),
557
- jsx_factory: inheritable(
558
- diagnostics,
559
- topLevelEnv,
560
- rawEnv,
561
- "jsx_factory",
562
- isString,
563
- "React.createElement"
564
- ),
565
- jsx_fragment: inheritable(
566
- diagnostics,
567
- topLevelEnv,
568
- rawEnv,
569
- "jsx_fragment",
570
- isString,
571
- "React.Fragment"
572
- ),
573
- rules: validateAndNormalizeRules(
574
- diagnostics,
575
- topLevelEnv,
576
- rawEnv,
577
- deprecatedUpload?.rules,
578
- envName
579
- ),
580
- name: inheritableInLegacyEnvironments(
581
- diagnostics,
582
- isLegacyEnv,
583
- topLevelEnv,
584
- rawEnv,
585
- "name",
586
- isString,
587
- undefined
588
- ),
589
- main: normalizeAndValidateMainField(
590
- configPath,
591
- inheritable(
592
- diagnostics,
593
- topLevelEnv,
594
- rawEnv,
595
- "main",
596
- isString,
597
- undefined
598
- ),
599
- deprecatedUpload
600
- ),
601
- route,
602
- routes,
603
- triggers: inheritable(
604
- diagnostics,
605
- topLevelEnv,
606
- rawEnv,
607
- "triggers",
608
- isObjectWith("crons"),
609
- { crons: [] }
610
- ),
611
- usage_model: inheritable(
612
- diagnostics,
613
- topLevelEnv,
614
- rawEnv,
615
- "usage_model",
616
- isOneOf("bundled", "unbound"),
617
- undefined
618
- ),
619
- build,
620
- workers_dev,
621
- // Not inherited fields
622
- vars: notInheritable(
623
- diagnostics,
624
- topLevelEnv,
625
- rawConfig,
626
- rawEnv,
627
- envName,
628
- "vars",
629
- validateVars(envName),
630
- {}
631
- ),
632
- durable_objects: notInheritable(
633
- diagnostics,
634
- topLevelEnv,
635
- rawConfig,
636
- rawEnv,
637
- envName,
638
- "durable_objects",
639
- validateBindingsProperty(envName, validateDurableObjectBinding),
640
- {
641
- bindings: [],
642
- }
643
- ),
644
- kv_namespaces: notInheritable(
645
- diagnostics,
646
- topLevelEnv,
647
- rawConfig,
648
- rawEnv,
649
- envName,
650
- "kv_namespaces",
651
- validateBindingArray(envName, validateKVBinding),
652
- []
653
- ),
654
- r2_buckets: notInheritable(
655
- diagnostics,
656
- topLevelEnv,
657
- rawConfig,
658
- rawEnv,
659
- envName,
660
- "r2_buckets",
661
- validateBindingArray(envName, validateR2Binding),
662
- []
663
- ),
664
- unsafe: notInheritable(
665
- diagnostics,
666
- topLevelEnv,
667
- rawConfig,
668
- rawEnv,
669
- envName,
670
- "unsafe",
671
- validateBindingsProperty(envName, validateUnsafeBinding),
672
- {
673
- bindings: [],
674
- }
675
- ),
676
- zone_id: rawEnv.zone_id,
677
- };
678
-
679
- 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;
1157
+ }
1158
+
1159
+ function validateAndNormalizeTsconfig(
1160
+ diagnostics: Diagnostics,
1161
+ topLevelEnv: Environment | undefined,
1162
+ rawEnv: RawEnvironment,
1163
+ configPath: string | undefined
1164
+ ) {
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;
680
1180
  }
681
1181
 
682
1182
  const validateAndNormalizeRules = (
683
- diagnostics: Diagnostics,
684
- topLevelEnv: Environment | undefined,
685
- rawEnv: RawEnvironment,
686
- deprecatedRules: Rule[] | undefined,
687
- envName: string
1183
+ diagnostics: Diagnostics,
1184
+ topLevelEnv: Environment | undefined,
1185
+ rawEnv: RawEnvironment,
1186
+ deprecatedRules: Rule[] | undefined,
1187
+ envName: string
688
1188
  ): Rule[] => {
689
- if (topLevelEnv === undefined) {
690
- // Only create errors/warnings for the top-level environment
691
- if (rawEnv.rules && deprecatedRules) {
692
- diagnostics.errors.push(
693
- `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
694
- );
695
- } else if (deprecatedRules) {
696
- diagnostics.warnings.push(
697
- `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` +
698
- "```\n" +
699
- TOML.stringify({ rules: deprecatedRules }) +
700
- "```"
701
- );
702
- }
703
- }
704
-
705
- return inheritable(
706
- diagnostics,
707
- topLevelEnv,
708
- rawEnv,
709
- "rules",
710
- validateRules(envName),
711
- deprecatedRules ?? []
712
- );
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
+ );
713
1213
  };
714
1214
 
715
1215
  const validateRules =
716
- (envName: string): ValidatorFn =>
717
- (diagnostics, field, envValue, config) => {
718
- if (!envValue) {
719
- return true;
720
- }
721
- const fieldPath =
722
- config === undefined ? `${field}` : `env.${envName}.${field}`;
723
- if (!Array.isArray(envValue)) {
724
- diagnostics.errors.push(
725
- `The field "${fieldPath}" should be an array but got ${JSON.stringify(
726
- envValue
727
- )}.`
728
- );
729
- return false;
730
- }
731
-
732
- let isValid = true;
733
- for (let i = 0; i < envValue.length; i++) {
734
- isValid =
735
- validateRule(diagnostics, `${fieldPath}[${i}]`, envValue[i], config) &&
736
- isValid;
737
- }
738
- return isValid;
739
- };
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
+ };
740
1240
 
741
1241
  const validateRule: ValidatorFn = (diagnostics, field, value) => {
742
- if (typeof value !== "object" || value === null) {
743
- diagnostics.errors.push(
744
- `"${field}" should be an object but got ${JSON.stringify(value)}.`
745
- );
746
- return false;
747
- }
748
- // Rules must have a type string and glob string array, and optionally a fallthrough boolean.
749
- let isValid = true;
750
- const rule = value as Rule;
751
-
752
- if (
753
- !isRequiredProperty(rule, "type", "string", [
754
- "ESModule",
755
- "CommonJS",
756
- "CompiledWasm",
757
- "Text",
758
- "Data",
759
- ])
760
- ) {
761
- diagnostics.errors.push(
762
- `bindings should have a string "type" field, which contains one of "ESModule", "CommonJS", "CompiledWasm", "Text", or "Data".`
763
- );
764
- isValid = false;
765
- }
766
-
767
- isValid =
768
- validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") &&
769
- isValid;
770
-
771
- if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
772
- diagnostics.errors.push(
773
- `binding should, optionally, have a boolean "fallthrough" field.`
774
- );
775
- isValid = false;
776
- }
777
-
778
- 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;
779
1279
  };
780
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
+
781
1343
  const validateVars =
782
- (envName: string): ValidatorFn =>
783
- (diagnostics, field, value, config) => {
784
- let isValid = true;
785
- const fieldPath =
786
- config === undefined ? `${field}` : `env.${envName}.${field}`;
787
- const configVars = Object.keys(config?.vars ?? {});
788
- // If there are no top level vars then there is nothing to do here.
789
- if (configVars.length > 0) {
790
- if (typeof value !== "object" || value === null) {
791
- diagnostics.errors.push(
792
- `The field "${fieldPath}" should be an object but got ${JSON.stringify(
793
- value
794
- )}.\n`
795
- );
796
- isValid = false;
797
- } else {
798
- for (const varName of configVars) {
799
- if (!(varName in value)) {
800
- diagnostics.warnings.push(
801
- `"vars.${varName}" exists at the top level, but not on "${fieldPath}".\n` +
802
- `This is not what you probably want, since "vars" configuration is not inherited by environments.\n` +
803
- `Please add "vars.${varName}" to "env.${envName}".`
804
- );
805
- }
806
- }
807
- }
808
- }
809
- return isValid;
810
- };
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
+ };
811
1373
 
812
1374
  const validateBindingsProperty =
813
- (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
814
- (diagnostics, field, value, config) => {
815
- let isValid = true;
816
- const fieldPath =
817
- config === undefined ? `${field}` : `env.${envName}.${field}`;
818
-
819
- if (value !== undefined) {
820
- // Check the validity of the `value` as a bindings container.
821
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
822
- diagnostics.errors.push(
823
- `The field "${fieldPath}" should be an object but got ${JSON.stringify(
824
- value
825
- )}.`
826
- );
827
- isValid = false;
828
- } else if (!hasProperty(value, "bindings")) {
829
- diagnostics.errors.push(
830
- `The field "${fieldPath}" is missing the required "bindings" property.`
831
- );
832
- isValid = false;
833
- } else if (!Array.isArray(value.bindings)) {
834
- diagnostics.errors.push(
835
- `The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
836
- value.bindings
837
- )}.`
838
- );
839
- isValid = false;
840
- } else {
841
- for (let i = 0; i < value.bindings.length; i++) {
842
- const binding = value.bindings[i];
843
- const bindingDiagnostics = new Diagnostics(
844
- `"${fieldPath}.bindings[${i}]": ${JSON.stringify(binding)}`
845
- );
846
- isValid =
847
- validateBinding(
848
- bindingDiagnostics,
849
- `${fieldPath}.bindings[${i}]`,
850
- binding,
851
- config
852
- ) && isValid;
853
- diagnostics.addChild(bindingDiagnostics);
854
- }
855
- }
856
-
857
- const configBindingNames = getBindingNames(
858
- config?.[field as keyof Environment]
859
- );
860
- if (isValid && configBindingNames.length > 0) {
861
- // If there are top level bindings then check that they all appear in the environment.
862
- const envBindingNames = new Set(getBindingNames(value));
863
- const missingBindings = configBindingNames.filter(
864
- (name) => !envBindingNames.has(name)
865
- );
866
- if (missingBindings.length > 0) {
867
- diagnostics.warnings.push(
868
- `The following bindings are at the top level, but not on "env.${envName}".\n` +
869
- `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
870
- `Please add a binding for each to "${fieldPath}.bindings".` +
871
- missingBindings.map((name) => `- ${name}`).join("\n")
872
- );
873
- }
874
- }
875
- }
876
- return isValid;
877
- };
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}`;
878
1380
 
879
- /**
880
- * Get the names of the bindings collection in `value`.
881
- */
882
- const getBindingNames = (value: unknown): string[] =>
883
- ((value as { bindings: { name: string }[] })?.bindings ?? []).map(
884
- (binding) => binding.name
885
- );
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
+ };
886
1440
 
887
1441
  /**
888
1442
  * Check that the given field is a valid "durable_object" binding object.
889
1443
  */
890
1444
  const validateDurableObjectBinding: ValidatorFn = (
891
- diagnostics,
892
- field,
893
- value
1445
+ diagnostics,
1446
+ field,
1447
+ value
894
1448
  ) => {
895
- if (typeof value !== "object" || value === null) {
896
- diagnostics.errors.push(
897
- `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
898
- );
899
- return false;
900
- }
901
-
902
- // Durable Object bindings must have a name and class_name, and optionally a script_name.
903
- let isValid = true;
904
- if (!isRequiredProperty(value, "name", "string")) {
905
- diagnostics.errors.push(`binding should have a string "name" field.`);
906
- isValid = false;
907
- }
908
- if (!isRequiredProperty(value, "class_name", "string")) {
909
- diagnostics.errors.push(`binding should have a string "class_name" field.`);
910
- isValid = false;
911
- }
912
- if (!isOptionalProperty(value, "script_name", "string")) {
913
- diagnostics.errors.push(
914
- `binding should, optionally, have a string "script_name" field.`
915
- );
916
- isValid = false;
917
- }
918
-
919
- 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;
920
1512
  };
921
1513
 
922
1514
  /**
@@ -925,166 +1517,346 @@ const validateDurableObjectBinding: ValidatorFn = (
925
1517
  * TODO: further validation of known unsafe bindings.
926
1518
  */
927
1519
  const validateUnsafeBinding: ValidatorFn = (diagnostics, field, value) => {
928
- if (typeof value !== "object" || value === null) {
929
- diagnostics.errors.push(
930
- `Expected ${field} to be an object but got ${JSON.stringify(value)}.`
931
- );
932
- return false;
933
- }
934
-
935
- let isValid = true;
936
- // Unsafe bindings must have a name and type.
937
- if (!isRequiredProperty(value, "name", "string")) {
938
- diagnostics.errors.push(`binding should have a string "name" field.`);
939
- isValid = false;
940
- }
941
- if (isRequiredProperty(value, "type", "string")) {
942
- const safeBindings = [
943
- "plain_text",
944
- "json",
945
- "kv_namespace",
946
- "durable_object_namespace",
947
- ];
948
-
949
- if (safeBindings.includes(value.type)) {
950
- diagnostics.warnings.push(
951
- `The binding type "${value.type}" is directly supported by wrangler.\n` +
952
- `Consider migrating this unsafe binding to a format for '${value.type}' bindings that is supported by wrangler for optimal support.\n` +
953
- "For more details, see https://developers.cloudflare.com/workers/cli-wrangler/configuration"
954
- );
955
- }
956
- } else {
957
- diagnostics.errors.push(`binding should have a string "type" field.`);
958
- isValid = false;
959
- }
960
- 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;
961
1559
  };
962
1560
 
963
1561
  /**
964
1562
  * Check that the given environment field is a valid array of bindings.
965
1563
  */
966
1564
  const validateBindingArray =
967
- (envName: string, validateBinding: ValidatorFn): ValidatorFn =>
968
- (diagnostics, field, envValue, config) => {
969
- if (envValue === undefined) {
970
- return true;
971
- }
972
-
973
- const fieldPath =
974
- config === undefined ? `${field}` : `env.${envName}.${field}`;
975
- if (!Array.isArray(envValue)) {
976
- diagnostics.errors.push(
977
- `The field "${fieldPath}" should be an array but got ${JSON.stringify(
978
- envValue
979
- )}.`
980
- );
981
- return false;
982
- }
983
-
984
- let isValid = true;
985
- for (let i = 0; i < envValue.length; i++) {
986
- isValid =
987
- validateBinding(
988
- diagnostics,
989
- `${fieldPath}[${i}]`,
990
- envValue[i],
991
- config
992
- ) && isValid;
993
- }
994
- const configValue = config?.[field as keyof Environment] as {
995
- binding: unknown;
996
- }[];
997
- if (Array.isArray(configValue)) {
998
- const configBindingNames = configValue.map((value) => value.binding);
999
- // If there are no top level bindings then there is nothing to do here.
1000
- if (configBindingNames.length > 0) {
1001
- const envBindingNames = new Set(envValue.map((value) => value.binding));
1002
- for (const configBindingName of configBindingNames) {
1003
- if (!envBindingNames.has(configBindingName)) {
1004
- diagnostics.warnings.push(
1005
- `There is a ${field} binding with name "${configBindingName}" at the top level, but not on "env.${envName}".\n` +
1006
- `This is not what you probably want, since "${field}" configuration is not inherited by environments.\n` +
1007
- `Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bindings".`
1008
- );
1009
- }
1010
- }
1011
- }
1012
- }
1013
- return isValid;
1014
- };
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
+ };
1015
1613
 
1016
1614
  const validateKVBinding: ValidatorFn = (diagnostics, field, value) => {
1017
- if (typeof value !== "object" || value === null) {
1018
- diagnostics.errors.push(
1019
- `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
1020
- value
1021
- )}`
1022
- );
1023
- return false;
1024
- }
1025
- let isValid = true;
1026
- // KV bindings must have a binding and id.
1027
- if (!isRequiredProperty(value, "binding", "string")) {
1028
- diagnostics.errors.push(
1029
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1030
- value
1031
- )}.`
1032
- );
1033
- isValid = false;
1034
- }
1035
- if (!isRequiredProperty(value, "id", "string")) {
1036
- diagnostics.errors.push(
1037
- `"${field}" bindings should have a string "id" field but got ${JSON.stringify(
1038
- value
1039
- )}.`
1040
- );
1041
- isValid = false;
1042
- }
1043
- if (!isOptionalProperty(value, "preview_id", "string")) {
1044
- diagnostics.errors.push(
1045
- `"${field}" bindings should, optionally, have a string "preview_id" field but got ${JSON.stringify(
1046
- value
1047
- )}.`
1048
- );
1049
- isValid = false;
1050
- }
1051
- 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;
1052
1653
  };
1053
1654
 
1054
1655
  const validateR2Binding: ValidatorFn = (diagnostics, field, value) => {
1055
- if (typeof value !== "object" || value === null) {
1056
- diagnostics.errors.push(
1057
- `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
1058
- value
1059
- )}`
1060
- );
1061
- return false;
1062
- }
1063
- let isValid = true;
1064
- // R2 bindings must have a binding and bucket_name.
1065
- if (!isRequiredProperty(value, "binding", "string")) {
1066
- diagnostics.errors.push(
1067
- `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
1068
- value
1069
- )}.`
1070
- );
1071
- isValid = false;
1072
- }
1073
- if (!isRequiredProperty(value, "bucket_name", "string")) {
1074
- diagnostics.errors.push(
1075
- `"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
1076
- value
1077
- )}.`
1078
- );
1079
- isValid = false;
1080
- }
1081
- if (!isOptionalProperty(value, "preview_bucket_name", "string")) {
1082
- diagnostics.errors.push(
1083
- `"${field}" bindings should, optionally, have a string "preview_bucket_name" field but got ${JSON.stringify(
1084
- value
1085
- )}.`
1086
- );
1087
- isValid = false;
1088
- }
1089
- 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;
1694
+ };
1695
+
1696
+ /**
1697
+ * Check that bindings whose names might conflict, don't.
1698
+ *
1699
+ * We don't want to have, for example, a KV namespace named "DATA"
1700
+ * and a Durable Object also named "DATA". Then it would be ambiguous
1701
+ * what exactly would live at `env.DATA` (or in the case of service-workers,
1702
+ * the `DATA` global).
1703
+ */
1704
+ const validateBindingsHaveUniqueNames = (
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>
1717
+ ): boolean => {
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;
1794
+ };
1795
+
1796
+ const validateServiceBinding: ValidatorFn = (diagnostics, field, value) => {
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;
1090
1862
  };