wrangler 0.0.0-e452a35 → 0.0.0-e4716cc87

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