wrangler 0.0.0-e151223 → 0.0.0-e1e2ee5c

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