wrangler 0.0.0-e61fba8 → 0.0.0-e640ed9d

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