wrangler 0.0.0-ece06ea → 0.0.0-ecfbb0c

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