wrangler 0.0.0-ece06ea → 0.0.0-ed08df4

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