wrangler 0.0.0-fb43821 → 0.0.0-fb53fda

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