wrangler 0.0.0-e1c615f → 0.0.0-e3a458e

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