wrangler 0.0.0-e178d6fb → 0.0.0-e1c2f5b9

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 (239) hide show
  1. package/README.md +16 -2
  2. package/bin/wrangler.js +31 -11
  3. package/miniflare-dist/index.mjs +1340 -330
  4. package/package.json +40 -13
  5. package/src/__tests__/access.test.ts +25 -0
  6. package/src/__tests__/api-dev.test.ts +238 -0
  7. package/src/__tests__/api-devregistry.test.js +64 -0
  8. package/src/__tests__/api.test.ts +80 -0
  9. package/src/__tests__/configuration.test.ts +683 -470
  10. package/src/__tests__/d1.test.ts +123 -0
  11. package/src/__tests__/delete.test.ts +263 -0
  12. package/src/__tests__/deployments.test.ts +105 -0
  13. package/src/__tests__/dev.test.tsx +453 -70
  14. package/src/__tests__/dialogs.test.tsx +40 -0
  15. package/src/__tests__/generate.test.ts +235 -0
  16. package/src/__tests__/get-host-from-url.test.ts +16 -0
  17. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  18. package/src/__tests__/helpers/mock-cfetch.ts +92 -26
  19. package/src/__tests__/helpers/mock-console.ts +11 -2
  20. package/src/__tests__/helpers/mock-dialogs.ts +1 -1
  21. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  22. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  23. package/src/__tests__/helpers/mock-kv.ts +1 -1
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +74 -53
  25. package/src/__tests__/helpers/mock-process.ts +8 -13
  26. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  27. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  28. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  29. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  30. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  31. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  32. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  33. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  34. package/src/__tests__/helpers/msw/index.ts +21 -0
  35. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  36. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  37. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  38. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  39. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  40. package/src/__tests__/index.test.ts +103 -97
  41. package/src/__tests__/init.test.ts +1484 -382
  42. package/src/__tests__/jest.setup.ts +88 -5
  43. package/src/__tests__/kv.test.ts +655 -540
  44. package/src/__tests__/logout.test.ts +47 -0
  45. package/src/__tests__/metrics.test.ts +95 -45
  46. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  47. package/src/__tests__/middleware.test.ts +750 -0
  48. package/src/__tests__/pages-deployment-tail.test.ts +884 -0
  49. package/src/__tests__/pages.test.ts +1301 -119
  50. package/src/__tests__/paths.test.ts +39 -0
  51. package/src/__tests__/publish.test.ts +2266 -1180
  52. package/src/__tests__/pubsub.test.ts +211 -88
  53. package/src/__tests__/queues.test.ts +522 -0
  54. package/src/__tests__/r2.test.ts +363 -203
  55. package/src/__tests__/secret.test.ts +261 -59
  56. package/src/__tests__/tail.test.ts +352 -151
  57. package/src/__tests__/test-old-node-version.js +3 -3
  58. package/src/__tests__/tsconfig-sanity.ts +12 -0
  59. package/src/__tests__/tsconfig.json +8 -0
  60. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  61. package/src/__tests__/type-generation.test.ts +233 -0
  62. package/src/__tests__/user.test.ts +59 -73
  63. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  64. package/src/__tests__/validate-dev-props.test.ts +56 -0
  65. package/src/__tests__/whoami.test.tsx +114 -66
  66. package/src/__tests__/worker-namespace.test.ts +154 -155
  67. package/src/api/dev.ts +170 -38
  68. package/src/api/index.ts +1 -0
  69. package/src/bundle-reporter.tsx +41 -2
  70. package/src/bundle.ts +668 -81
  71. package/src/cfetch/index.ts +40 -3
  72. package/src/cfetch/internal.ts +144 -32
  73. package/src/cli.ts +4 -3
  74. package/src/config/config.ts +27 -3
  75. package/src/config/environment.ts +131 -7
  76. package/src/config/index.ts +128 -8
  77. package/src/config/validation-helpers.ts +19 -6
  78. package/src/config/validation.ts +411 -14
  79. package/src/config-cache.ts +3 -2
  80. package/src/create-worker-preview.ts +31 -6
  81. package/src/create-worker-upload-form.ts +84 -22
  82. package/src/d1/backups.tsx +223 -0
  83. package/src/d1/constants.ts +2 -0
  84. package/src/d1/create.tsx +63 -0
  85. package/src/d1/delete.tsx +56 -0
  86. package/src/d1/execute.tsx +352 -0
  87. package/src/d1/formatTimeAgo.ts +14 -0
  88. package/src/d1/index.ts +101 -0
  89. package/src/d1/list.tsx +48 -0
  90. package/src/d1/migrations/apply.tsx +196 -0
  91. package/src/d1/migrations/create.tsx +77 -0
  92. package/src/d1/migrations/helpers.ts +147 -0
  93. package/src/d1/migrations/index.tsx +3 -0
  94. package/src/d1/migrations/list.tsx +79 -0
  95. package/src/d1/migrations/options.ts +18 -0
  96. package/src/d1/options.ts +22 -0
  97. package/src/d1/types.tsx +24 -0
  98. package/src/d1/utils.ts +48 -0
  99. package/src/delete.ts +108 -0
  100. package/src/deployments.ts +83 -0
  101. package/src/deprecated/index.ts +145 -0
  102. package/src/dev/dev-vars.ts +11 -8
  103. package/src/dev/dev.tsx +220 -58
  104. package/src/dev/get-local-persistence-path.tsx +31 -0
  105. package/src/dev/local.tsx +740 -181
  106. package/src/dev/remote.tsx +340 -123
  107. package/src/dev/start-server.ts +543 -0
  108. package/src/dev/use-esbuild.ts +61 -7
  109. package/src/dev/validate-dev-props.ts +31 -0
  110. package/src/dev-registry.tsx +201 -0
  111. package/src/dev.tsx +614 -258
  112. package/src/dialogs.tsx +41 -8
  113. package/src/{worker-namespace.ts → dispatch-namespace.ts} +23 -22
  114. package/src/docs/index.ts +97 -0
  115. package/src/entry.ts +3 -2
  116. package/src/environment-variables/factory.ts +88 -0
  117. package/src/environment-variables/misc-variables.ts +30 -0
  118. package/src/generate/index.ts +300 -0
  119. package/src/git-client.ts +100 -7
  120. package/src/index.tsx +249 -1560
  121. package/src/init.ts +626 -150
  122. package/src/inspect.ts +137 -32
  123. package/src/{metrics/is-ci.ts → is-ci.ts} +0 -0
  124. package/src/is-interactive.ts +4 -0
  125. package/src/jest.d.ts +4 -0
  126. package/src/{kv.ts → kv/helpers.ts} +3 -3
  127. package/src/kv/index.ts +596 -0
  128. package/src/logger.ts +27 -8
  129. package/src/metrics/index.ts +1 -0
  130. package/src/metrics/metrics-config.ts +4 -4
  131. package/src/metrics/metrics-dispatcher.ts +1 -0
  132. package/src/metrics/metrics-usage-headers.ts +24 -0
  133. package/src/metrics/send-event.ts +13 -8
  134. package/src/miniflare-cli/assets.ts +172 -465
  135. package/src/miniflare-cli/index.ts +149 -24
  136. package/src/miniflare-cli/tsconfig.json +9 -0
  137. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  138. package/src/miniflare-cli/types.ts +11 -0
  139. package/src/module-collection.ts +12 -3
  140. package/src/pages/build.tsx +108 -42
  141. package/src/pages/constants.ts +11 -0
  142. package/src/pages/deployment-tails.tsx +284 -0
  143. package/src/pages/deployments.tsx +9 -31
  144. package/src/pages/dev.tsx +417 -108
  145. package/src/pages/errors.ts +66 -0
  146. package/src/pages/functions/buildPlugin.ts +86 -84
  147. package/src/pages/functions/buildWorker.ts +121 -106
  148. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  149. package/src/pages/functions/routes-consolidation.ts +73 -0
  150. package/src/pages/functions/routes-transformation.test.ts +282 -0
  151. package/src/pages/functions/routes-transformation.ts +115 -0
  152. package/src/pages/functions/routes-validation.test.ts +403 -0
  153. package/src/pages/functions/routes-validation.ts +202 -0
  154. package/src/pages/functions/tsconfig.json +8 -0
  155. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  156. package/src/pages/functions.tsx +82 -0
  157. package/src/pages/hash.tsx +13 -0
  158. package/src/pages/index.tsx +73 -55
  159. package/src/pages/projects.tsx +9 -3
  160. package/src/pages/prompt-select-project.tsx +31 -0
  161. package/src/pages/publish.tsx +183 -60
  162. package/src/pages/types.ts +1 -0
  163. package/src/pages/upload.tsx +107 -56
  164. package/src/pages/utils.ts +13 -2
  165. package/src/paths.ts +49 -4
  166. package/src/proxy.ts +375 -157
  167. package/src/publish/index.ts +270 -0
  168. package/src/{publish.ts → publish/publish.ts} +431 -188
  169. package/src/pubsub/pubsub-commands.tsx +4 -3
  170. package/src/queues/cli/commands/consumer/add.ts +71 -0
  171. package/src/queues/cli/commands/consumer/index.ts +22 -0
  172. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  173. package/src/queues/cli/commands/create.ts +25 -0
  174. package/src/queues/cli/commands/delete.ts +26 -0
  175. package/src/queues/cli/commands/index.ts +36 -0
  176. package/src/queues/cli/commands/list.ts +25 -0
  177. package/src/queues/client.ts +135 -0
  178. package/src/queues/utils.ts +18 -0
  179. package/src/r2/constants.ts +4 -0
  180. package/src/r2/helpers.ts +131 -0
  181. package/src/r2/index.ts +289 -0
  182. package/src/routes.ts +140 -0
  183. package/src/secret/index.ts +379 -0
  184. package/src/sites.tsx +3 -3
  185. package/src/tail/createTail.ts +379 -0
  186. package/src/tail/filters.ts +4 -6
  187. package/src/tail/index.ts +199 -284
  188. package/src/tail/printing.ts +43 -3
  189. package/src/tsconfig-sanity.ts +16 -0
  190. package/src/type-generation.ts +181 -0
  191. package/src/user/access.ts +68 -0
  192. package/src/user/auth-variables.ts +113 -0
  193. package/src/user/choose-account.tsx +1 -1
  194. package/src/user/index.ts +0 -1
  195. package/src/user/user.tsx +116 -49
  196. package/src/utils/collectKeyValues.ts +14 -0
  197. package/src/whoami.tsx +80 -2
  198. package/src/worker.ts +69 -9
  199. package/src/yargs-types.ts +24 -0
  200. package/src/zones.ts +124 -9
  201. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  202. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  203. package/templates/__tests__/tsconfig.json +8 -0
  204. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  205. package/templates/d1-beta-facade.js +205 -0
  206. package/templates/facade.d.ts +14 -0
  207. package/templates/first-party-worker-module-facade.ts +19 -0
  208. package/templates/format-dev-errors.ts +33 -0
  209. package/templates/init-tests/test-jest-new-worker.js +23 -0
  210. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  211. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  212. package/templates/middleware/common.ts +62 -0
  213. package/templates/middleware/loader-modules.ts +82 -0
  214. package/templates/middleware/loader-sw.ts +233 -0
  215. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  216. package/templates/middleware/middleware-pretty-error.ts +40 -0
  217. package/templates/middleware/middleware-scheduled.ts +15 -0
  218. package/templates/new-worker.js +1 -1
  219. package/templates/pages-dev-pipeline.ts +31 -0
  220. package/templates/pages-dev-util.ts +52 -0
  221. package/templates/pages-shim.ts +4 -1
  222. package/templates/pages-template-plugin.ts +21 -5
  223. package/templates/pages-template-worker.ts +37 -9
  224. package/templates/{static-asset-facade.js → serve-static-assets.ts} +23 -7
  225. package/templates/service-bindings-module-facade.js +54 -0
  226. package/templates/service-bindings-sw-facade.js +42 -0
  227. package/templates/tsconfig-sanity.ts +11 -0
  228. package/templates/tsconfig.init.json +106 -0
  229. package/templates/tsconfig.json +5 -102
  230. package/templates/tsconfig.tsbuildinfo +1 -0
  231. package/wrangler-dist/cli.d.ts +621 -42
  232. package/wrangler-dist/cli.js +144441 -102606
  233. package/src/environment-variables.ts +0 -35
  234. package/src/faye-websocket.d.ts +0 -6
  235. package/src/generate.ts +0 -33
  236. package/src/miniflare-cli/enum-keys.ts +0 -17
  237. package/src/preview.ts +0 -31
  238. package/src/r2.ts +0 -50
  239. package/src/user/env-vars.ts +0 -46
package/src/dev.tsx CHANGED
@@ -1,34 +1,38 @@
1
1
  import path from "node:path";
2
+ import chalk from "chalk";
2
3
  import { watch } from "chokidar";
3
4
  import getPort from "get-port";
4
5
  import { render } from "ink";
5
6
  import React from "react";
6
- import { fetch } from "undici";
7
7
  import { findWranglerToml, printBindings, readConfig } from "./config";
8
8
  import Dev from "./dev/dev";
9
9
  import { getVarsForDev } from "./dev/dev-vars";
10
+ import { getLocalPersistencePath } from "./dev/get-local-persistence-path";
10
11
 
12
+ import { startDevServer } from "./dev/start-server";
11
13
  import { getEntry } from "./entry";
12
14
  import { logger } from "./logger";
13
15
  import * as metrics from "./metrics";
14
16
  import { getAssetPaths, getSiteAssetPaths } from "./sites";
15
- import { getAccountFromCache } from "./user";
16
- import { getZoneIdFromHost, getZoneForRoute, getHostFromRoute } from "./zones";
17
+ import { getAccountFromCache, loginOrRefreshIfRequired } from "./user";
18
+ import { collectKeyValues } from "./utils/collectKeyValues";
19
+ import { identifyD1BindingsAsBeta } from "./worker";
20
+ import { getHostFromRoute, getZoneForRoute, getZoneIdFromHost } from "./zones";
17
21
  import {
18
- printWranglerBanner,
19
- DEFAULT_LOCAL_PORT,
20
22
  type ConfigPath,
21
- getScriptName,
23
+ DEFAULT_INSPECTOR_PORT,
24
+ DEFAULT_LOCAL_PORT,
22
25
  getDevCompatibilityDate,
23
26
  getRules,
27
+ getScriptName,
24
28
  isLegacyEnv,
29
+ printWranglerBanner,
25
30
  } from "./index";
26
-
27
- import type { Config } from "./config";
31
+ import type { Config, Environment } from "./config";
28
32
  import type { Route } from "./config/environment";
29
- import type { EnablePagesAssetsServiceBindingOptions } from "./miniflare-cli";
33
+ import type { EnablePagesAssetsServiceBindingOptions } from "./miniflare-cli/types";
30
34
  import type { CfWorkerInit } from "./worker";
31
- import type { RequestInit } from "undici";
35
+ import type { CommonYargsOptions } from "./yargs-types";
32
36
  import type { Argv, ArgumentsCamelCase } from "yargs";
33
37
 
34
38
  interface DevArgs {
@@ -61,17 +65,24 @@ interface DevArgs {
61
65
  "jsx-fragment"?: string;
62
66
  tsconfig?: string;
63
67
  local?: boolean;
68
+ "experimental-local"?: boolean;
69
+ "experimental-local-remote-kv"?: boolean;
64
70
  minify?: boolean;
71
+ var?: string[];
72
+ define?: string[];
65
73
  "node-compat"?: boolean;
66
74
  "experimental-enable-local-persistence"?: boolean;
75
+ persist?: boolean;
76
+ "persist-to"?: string;
67
77
  "live-reload"?: boolean;
68
- onReady?: () => void;
69
- logLevel?: "none" | "error" | "log" | "warn" | "debug";
78
+ onReady?: (ip: string, port: number) => void;
79
+ logLevel?: "none" | "info" | "error" | "log" | "warn" | "debug";
70
80
  logPrefix?: string;
71
81
  showInteractiveDevSession?: boolean;
82
+ "test-scheduled"?: boolean;
72
83
  }
73
84
 
74
- export function devOptions(yargs: Argv): Argv<DevArgs> {
85
+ export function devOptions(yargs: Argv<CommonYargsOptions>): Argv<DevArgs> {
75
86
  return (
76
87
  yargs
77
88
  .positional("script", {
@@ -100,14 +111,9 @@ export function devOptions(yargs: Argv): Argv<DevArgs> {
100
111
  .option("format", {
101
112
  choices: ["modules", "service-worker"] as const,
102
113
  describe: "Choose an entry type",
114
+ hidden: true,
103
115
  deprecated: true,
104
116
  })
105
- .option("env", {
106
- describe: "Perform on a specific environment",
107
- type: "string",
108
- requiresArg: true,
109
- alias: "e",
110
- })
111
117
  .option("compatibility-date", {
112
118
  describe: "Date to use for compatibility checks",
113
119
  type: "string",
@@ -126,9 +132,8 @@ export function devOptions(yargs: Argv): Argv<DevArgs> {
126
132
  default: true,
127
133
  })
128
134
  .option("ip", {
129
- describe: "IP address to listen on, defaults to `localhost`",
135
+ describe: "IP address to listen on",
130
136
  type: "string",
131
- requiresArg: true,
132
137
  })
133
138
  .option("port", {
134
139
  describe: "Port to listen on",
@@ -195,6 +200,19 @@ export function devOptions(yargs: Argv): Argv<DevArgs> {
195
200
  describe: "Protocol to forward requests to host on, defaults to https.",
196
201
  choices: ["http", "https"] as const,
197
202
  })
203
+ .option("var", {
204
+ describe:
205
+ "A key-value pair to be injected into the script as a variable",
206
+ type: "string",
207
+ requiresArg: true,
208
+ array: true,
209
+ })
210
+ .option("define", {
211
+ describe: "A key-value pair to be substituted in the script",
212
+ type: "string",
213
+ requiresArg: true,
214
+ array: true,
215
+ })
198
216
  .option("jsx-factory", {
199
217
  describe: "The function that is called for each JSX element",
200
218
  type: "string",
@@ -216,6 +234,34 @@ export function devOptions(yargs: Argv): Argv<DevArgs> {
216
234
  type: "boolean",
217
235
  default: false, // I bet this will a point of contention. We'll revisit it.
218
236
  })
237
+ .option("experimental-local", {
238
+ describe: "Run on my machine using the Cloudflare Workers runtime",
239
+ type: "boolean",
240
+ default: false,
241
+ })
242
+ .option("experimental-local-remote-kv", {
243
+ describe:
244
+ "Read/write KV data from/to real namespaces on the Cloudflare network",
245
+ type: "boolean",
246
+ default: false,
247
+ })
248
+ .check((argv) => {
249
+ if (argv.local && argv["experimental-local"]) {
250
+ throw new Error(
251
+ "--local and --experimental-local are mutually exclusive. " +
252
+ "Please enable one or the other."
253
+ );
254
+ }
255
+ if (
256
+ argv["experimental-local-remote-kv"] &&
257
+ !argv["experimental-local"]
258
+ ) {
259
+ throw new Error(
260
+ "--experimental-local-remote-kv requires --experimental-local to be enabled."
261
+ );
262
+ }
263
+ return true;
264
+ })
219
265
  .option("minify", {
220
266
  describe: "Minify the script",
221
267
  type: "boolean",
@@ -225,29 +271,72 @@ export function devOptions(yargs: Argv): Argv<DevArgs> {
225
271
  type: "boolean",
226
272
  })
227
273
  .option("experimental-enable-local-persistence", {
228
- describe: "Enable persistence for this session (only for local mode)",
274
+ describe:
275
+ "Enable persistence for local mode (deprecated, use --persist)",
229
276
  type: "boolean",
277
+ deprecated: true,
278
+ hidden: true,
279
+ })
280
+ .option("persist", {
281
+ describe:
282
+ "Enable persistence for local mode, using default path: .wrangler/state",
283
+ type: "boolean",
284
+ })
285
+ .option("persist-to", {
286
+ describe:
287
+ "Specify directory to use for local persistence (implies --persist)",
288
+ type: "string",
289
+ requiresArg: true,
230
290
  })
231
291
  .option("live-reload", {
232
- // TODO: Add back in once we have remote `--live-reload`
233
- hidden: true,
234
- // describe: "Auto reload HTML pages when change is detected",
292
+ describe:
293
+ "Auto reload HTML pages when change is detected in local mode",
235
294
  type: "boolean",
236
295
  })
296
+ .check((argv) => {
297
+ const local = argv["local"] || argv["experimental-local"];
298
+ if (argv["live-reload"] && !local) {
299
+ throw new Error(
300
+ "--live-reload is only supported in local mode. " +
301
+ "Please enable either --local or --experimental-local."
302
+ );
303
+ }
304
+ return true;
305
+ })
237
306
  .option("inspect", {
238
307
  describe: "Enable dev tools",
239
308
  type: "boolean",
240
309
  deprecated: true,
310
+ hidden: true,
241
311
  })
242
312
  .option("legacy-env", {
243
313
  type: "boolean",
244
314
  describe: "Use legacy environments",
245
315
  hidden: true,
246
316
  })
317
+ .option("test-scheduled", {
318
+ describe: "Test scheduled events by visiting /__scheduled in browser",
319
+ type: "boolean",
320
+ default: false,
321
+ })
322
+ .option("log-level", {
323
+ choices: ["debug", "info", "log", "warn", "error", "none"] as const,
324
+ describe: "Specify logging level",
325
+ default: "log",
326
+ })
247
327
  );
248
328
  }
249
329
 
250
330
  export async function devHandler(args: ArgumentsCamelCase<DevArgs>) {
331
+ if (!(args.local || args.experimentalLocal)) {
332
+ const isLoggedIn = await loginOrRefreshIfRequired();
333
+ if (!isLoggedIn) {
334
+ throw new Error(
335
+ "You must be logged in to use wrangler dev in remote mode. Try logging in, or run wrangler dev --local."
336
+ );
337
+ }
338
+ }
339
+
251
340
  let watcher;
252
341
  try {
253
342
  const devInstance = await startDev(args);
@@ -259,9 +348,7 @@ export async function devHandler(args: ArgumentsCamelCase<DevArgs>) {
259
348
  }
260
349
  }
261
350
 
262
- type StartDevOptions = ArgumentsCamelCase<DevArgs> & {
263
- // These options can be passed in directly when called with the `wrangler.dev()` API.
264
- // They aren't exposed as CLI arguments.
351
+ export type AdditionalDevProps = {
265
352
  vars?: {
266
353
  [key: string]: unknown;
267
354
  };
@@ -276,30 +363,47 @@ type StartDevOptions = ArgumentsCamelCase<DevArgs> & {
276
363
  script_name?: string | undefined;
277
364
  environment?: string | undefined;
278
365
  }[];
279
- forceLocal?: boolean;
280
- enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
366
+ r2?: {
367
+ binding: string;
368
+ bucket_name: string;
369
+ preview_bucket_name?: string;
370
+ }[];
371
+ d1Databases?: Environment["d1_databases"];
281
372
  };
282
373
 
374
+ type StartDevOptions = ArgumentsCamelCase<DevArgs> &
375
+ // These options can be passed in directly when called with the `wrangler.dev()` API.
376
+ // They aren't exposed as CLI arguments.
377
+ AdditionalDevProps & {
378
+ forceLocal?: boolean;
379
+ disableDevRegistry?: boolean;
380
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
381
+ };
382
+
283
383
  export async function startDev(args: StartDevOptions) {
284
384
  let watcher: ReturnType<typeof watch> | undefined;
285
385
  let rerender: (node: React.ReactNode) => void | undefined;
286
386
  try {
287
387
  if (args.logLevel) {
288
- // we don't define a "none" logLevel, so "error" will do for now.
289
- logger.loggerLevel = args.logLevel === "none" ? "error" : args.logLevel;
388
+ logger.loggerLevel = args.logLevel;
290
389
  }
291
390
  await printWranglerBanner();
292
391
 
392
+ if (args.local && process.platform !== "win32") {
393
+ logger.info(
394
+ chalk.magenta(
395
+ `Want to try out the next version of local mode using the open-source Workers runtime?\nSwitch out --local for ${chalk.bold(
396
+ "--experimental-local"
397
+ )} and let us know what you think at https://discord.gg/cloudflaredev !`
398
+ )
399
+ );
400
+ }
401
+
293
402
  const configPath =
294
403
  (args.config as ConfigPath) ||
295
404
  ((args.script &&
296
405
  findWranglerToml(path.dirname(args.script))) as ConfigPath);
297
406
  let config = readConfig(configPath, args);
298
- await metrics.sendMetricsEvent(
299
- "run dev",
300
- { local: args.local },
301
- { sendMetrics: config.send_metrics, offline: args.local }
302
- );
303
407
 
304
408
  if (config.configPath) {
305
409
  watcher = watch(config.configPath, {
@@ -315,273 +419,247 @@ export async function startDev(args: StartDevOptions) {
315
419
  });
316
420
  }
317
421
 
318
- const entry = await getEntry(
319
- { assets: args.assets, script: args.script },
320
- config,
321
- "dev"
322
- );
323
-
324
- if (config.services && config.services.length > 0) {
325
- logger.warn(
326
- `This worker is bound to live services: ${config.services
327
- .map(
328
- (service) =>
329
- `${service.binding} (${service.service}${
330
- service.environment ? `@${service.environment}` : ""
331
- })`
332
- )
333
- .join(", ")}`
334
- );
335
- }
336
-
337
- if (args.inspect) {
338
- //devtools are enabled by default, but we still need to disable them if the caller doesn't want them
339
- logger.warn(
340
- "Passing --inspect is unnecessary, now you can always connect to devtools."
341
- );
342
- }
343
-
344
- if (args["experimental-public"]) {
345
- throw new Error(
346
- "The --experimental-public field has been renamed to --assets"
347
- );
348
- }
349
-
350
- if (args.public) {
351
- throw new Error("The --public field has been renamed to --assets");
352
- }
353
-
354
- if ((args.assets || config.assets) && (args.site || config.site)) {
355
- throw new Error(
356
- "Cannot use Assets and Workers Sites in the same Worker."
357
- );
358
- }
359
-
360
- if (args.assets) {
361
- logger.warn(
362
- "The --assets argument is experimental and may change or break at any time"
363
- );
364
- }
365
-
366
- const upstreamProtocol =
367
- args["upstream-protocol"] || config.dev.upstream_protocol;
368
- if (upstreamProtocol === "http") {
369
- logger.warn(
370
- "Setting upstream-protocol to http is not currently implemented.\n" +
371
- "If this is required in your project, please add your use case to the following issue:\n" +
372
- "https://github.com/cloudflare/wrangler2/issues/583."
373
- );
374
- }
375
-
376
- // TODO: if worker_dev = false and no routes, then error (only for dev)
377
-
378
- // Compute zone info from the `host` and `route` args and config;
379
- let host = args.host || config.dev.host;
380
- let zoneId: string | undefined;
381
- const routes: Route[] | undefined =
382
- args.routes || (config.route && [config.route]) || config.routes;
422
+ const {
423
+ entry,
424
+ nodeCompat,
425
+ upstreamProtocol,
426
+ zoneId,
427
+ host,
428
+ routes,
429
+ getLocalPort,
430
+ getInspectorPort,
431
+ cliDefines,
432
+ localPersistencePath,
433
+ } = await validateDevServerSettings(args, config);
383
434
 
384
- if (args.forceLocal) {
385
- args.local = true;
386
- }
387
-
388
- if (!args.local) {
389
- if (host) {
390
- zoneId = await getZoneIdFromHost(host);
391
- }
392
- if (!zoneId && routes) {
393
- const firstRoute = routes[0];
394
- const zone = await getZoneForRoute(firstRoute);
395
- if (zone) {
396
- zoneId = zone.id;
397
- host = zone.host;
398
- }
399
- }
400
- } else if (!host) {
401
- if (routes) {
402
- const firstRoute = routes[0];
403
- host = getHostFromRoute(firstRoute);
404
- }
405
- }
406
-
407
- const nodeCompat = args.nodeCompat ?? config.node_compat;
408
- if (nodeCompat) {
409
- logger.warn(
410
- "Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
411
- );
412
- }
413
-
414
- // eslint-disable-next-line no-inner-declarations
415
- async function getBindings(
416
- configParam: Config
417
- ): Promise<CfWorkerInit["bindings"]> {
418
- return {
419
- kv_namespaces: [
420
- ...(configParam.kv_namespaces || []).map(
421
- ({ binding, preview_id, id: _id }) => {
422
- // In `dev`, we make folks use a separate kv namespace called
423
- // `preview_id` instead of `id` so that they don't
424
- // break production data. So here we check that a `preview_id`
425
- // has actually been configured.
426
- // This whole block of code will be obsoleted in the future
427
- // when we have copy-on-write for previews on edge workers.
428
- if (!preview_id) {
429
- // TODO: This error has to be a _lot_ better, ideally just asking
430
- // to create a preview namespace for the user automatically
431
- throw new Error(
432
- `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
433
- ); // Ugh, I really don't like this message very much
434
- }
435
- return {
436
- binding,
437
- id: preview_id,
438
- };
439
- }
440
- ),
441
- ...(args.kv || []),
442
- ],
443
- // Use a copy of combinedVars since we're modifying it later
444
- vars: {
445
- ...getVarsForDev(configParam),
446
- ...args.vars,
447
- },
448
- wasm_modules: configParam.wasm_modules,
449
- text_blobs: configParam.text_blobs,
450
- data_blobs: configParam.data_blobs,
451
- durable_objects: {
452
- bindings: [
453
- ...(configParam.durable_objects || { bindings: [] }).bindings,
454
- ...(args.durableObjects || []),
455
- ],
456
- },
457
- r2_buckets: configParam.r2_buckets?.map(
458
- ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
459
- // same idea as kv namespace preview id,
460
- // same copy-on-write TODO
461
- if (!preview_bucket_name) {
462
- throw new Error(
463
- `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
464
- );
465
- }
466
- return {
467
- binding,
468
- bucket_name: preview_bucket_name,
469
- };
470
- }
471
- ),
472
- worker_namespaces: configParam.worker_namespaces,
473
- services: configParam.services,
474
- unsafe: configParam.unsafe?.bindings,
475
- };
476
- }
477
-
478
- const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
479
- const getInspectorPort = memoizeGetPort(9229);
435
+ await metrics.sendMetricsEvent(
436
+ "run dev",
437
+ {
438
+ local: args.local,
439
+ usesTypeScript: /\.tsx?$/.test(entry.file),
440
+ },
441
+ { sendMetrics: config.send_metrics, offline: args.local }
442
+ );
480
443
 
481
444
  // eslint-disable-next-line no-inner-declarations
482
445
  async function getDevReactElement(configParam: Config) {
483
- // now log all available bindings into the terminal
484
- const bindings = await getBindings(configParam);
485
- // mask anything that was overridden in .dev.vars
486
- // so that we don't log potential secrets into the terminal
487
- const maskedVars = { ...bindings.vars };
488
- for (const key of Object.keys(maskedVars)) {
489
- if (maskedVars[key] !== configParam.vars[key]) {
490
- // This means it was overridden in .dev.vars
491
- // so let's mask it
492
- maskedVars[key] = "(hidden)";
493
- }
494
- }
495
-
496
- printBindings({
497
- ...bindings,
498
- vars: maskedVars,
499
- });
500
-
501
- const assetPaths =
502
- args.assets || config.assets
503
- ? getAssetPaths(config, args.assets)
504
- : getSiteAssetPaths(
505
- config,
506
- args.site,
507
- args.siteInclude,
508
- args.siteExclude
509
- );
446
+ const { assetPaths, bindings } = getBindingsAndAssetPaths(
447
+ args,
448
+ configParam
449
+ );
510
450
 
511
451
  return (
512
452
  <Dev
513
- name={getScriptName({ name: args.name, env: args.env }, config)}
514
- noBundle={!(args.bundle ?? !config.no_bundle)}
453
+ name={getScriptName({ name: args.name, env: args.env }, configParam)}
454
+ noBundle={!(args.bundle ?? !configParam.no_bundle)}
515
455
  entry={entry}
516
456
  env={args.env}
517
457
  zone={zoneId}
518
458
  host={host}
519
459
  routes={routes}
520
- rules={getRules(config)}
521
- legacyEnv={isLegacyEnv(config)}
522
- minify={args.minify ?? config.minify}
460
+ rules={getRules(configParam)}
461
+ legacyEnv={isLegacyEnv(configParam)}
462
+ minify={args.minify ?? configParam.minify}
523
463
  nodeCompat={nodeCompat}
524
- build={config.build || {}}
525
- define={config.define}
526
- initialMode={args.local ? "local" : "remote"}
527
- jsxFactory={args["jsx-factory"] || config.jsx_factory}
528
- jsxFragment={args["jsx-fragment"] || config.jsx_fragment}
529
- tsconfig={args.tsconfig ?? config.tsconfig}
464
+ build={configParam.build || {}}
465
+ define={{ ...configParam.define, ...cliDefines }}
466
+ initialMode={
467
+ args.local || args.experimentalLocal ? "local" : "remote"
468
+ }
469
+ jsxFactory={args["jsx-factory"] || configParam.jsx_factory}
470
+ jsxFragment={args["jsx-fragment"] || configParam.jsx_fragment}
471
+ tsconfig={args.tsconfig ?? configParam.tsconfig}
530
472
  upstreamProtocol={upstreamProtocol}
531
- localProtocol={args.localProtocol || config.dev.local_protocol}
473
+ localProtocol={args.localProtocol || configParam.dev.local_protocol}
532
474
  localUpstream={args["local-upstream"] || host}
533
- enableLocalPersistence={
534
- args["experimental-enable-local-persistence"] || false
535
- }
475
+ localPersistencePath={localPersistencePath}
536
476
  liveReload={args.liveReload || false}
537
- accountId={config.account_id || getAccountFromCache()?.id}
477
+ accountId={configParam.account_id || getAccountFromCache()?.id}
538
478
  assetPaths={assetPaths}
539
- port={args.port || config.dev.port || (await getLocalPort())}
540
- ip={args.ip || config.dev.ip}
541
- inspectorPort={args["inspector-port"] ?? (await getInspectorPort())}
542
- isWorkersSite={Boolean(args.site || config.site)}
479
+ assetsConfig={configParam.assets}
480
+ initialPort={
481
+ args.port ?? configParam.dev.port ?? (await getLocalPort())
482
+ }
483
+ initialIp={args.ip || configParam.dev.ip}
484
+ inspectorPort={
485
+ args.inspectorPort ??
486
+ configParam.dev.inspector_port ??
487
+ (await getInspectorPort())
488
+ }
489
+ isWorkersSite={Boolean(args.site || configParam.site)}
543
490
  compatibilityDate={getDevCompatibilityDate(
544
- config,
545
- args["compatibility-date"]
491
+ configParam,
492
+ args.compatibilityDate
546
493
  )}
547
494
  compatibilityFlags={
548
- args["compatibility-flags"] || config.compatibility_flags
495
+ args.compatibilityFlags || configParam.compatibility_flags
549
496
  }
550
- usageModel={config.usage_model}
497
+ usageModel={configParam.usage_model}
551
498
  bindings={bindings}
552
- crons={config.triggers.crons}
553
- logLevel={args.logLevel}
499
+ crons={configParam.triggers.crons}
500
+ queueConsumers={configParam.queues.consumers}
554
501
  logPrefix={args.logPrefix}
555
502
  onReady={args.onReady}
556
503
  inspect={args.inspect ?? true}
557
504
  showInteractiveDevSession={args.showInteractiveDevSession}
558
505
  forceLocal={args.forceLocal}
559
506
  enablePagesAssetsServiceBinding={args.enablePagesAssetsServiceBinding}
507
+ firstPartyWorker={configParam.first_party_worker}
508
+ sendMetrics={configParam.send_metrics}
509
+ testScheduled={args["test-scheduled"]}
510
+ experimentalLocal={args.experimentalLocal}
511
+ experimentalLocalRemoteKv={args.experimentalLocalRemoteKv}
560
512
  />
561
513
  );
562
514
  }
563
515
  const devReactElement = render(await getDevReactElement(config));
516
+
517
+ // In the bootstrapper script `bin/wrangler.js`, we open an IPC channel, so
518
+ // IPC messages from this process are propagated through the bootstrapper.
519
+ // Normally, Node's SIGINT handler would close this for us, but interactive
520
+ // mode enables raw mode on stdin which disables the built-in handler. The
521
+ // following line disconnects from the IPC channel when we press `x` or
522
+ // CTRL-C in interactive mode, ensuring no open handles, and allowing for a
523
+ // clean exit. Note, if we called `stop()` using the dev API, we don't want
524
+ // to disconnect here, as the user may still need IPC. We also don't want
525
+ // to disconnect if this file was imported in Jest (not the case with E2E
526
+ // tests), as that would stop communication with the test runner.
527
+ let apiStopped = false;
528
+ void devReactElement.waitUntilExit().then(() => {
529
+ if (!apiStopped && typeof jest === "undefined") process.disconnect?.();
530
+ });
531
+
564
532
  rerender = devReactElement.rerender;
565
533
  return {
566
534
  devReactElement,
567
535
  watcher,
568
536
  stop: async () => {
537
+ apiStopped = true;
569
538
  devReactElement.unmount();
570
539
  await watcher?.close();
571
540
  },
572
- fetch: async (init?: RequestInit) => {
573
- //TODO: we are not guaranteed to be assigned this port, we should fix this ASAP
574
- const port = args.port || config.dev.port || (await getLocalPort());
575
- const address = args.ip || config.dev.ip || "localhost";
576
-
577
- return await fetch(`http://${address}:${port}/`, init);
578
- },
579
541
  };
580
542
  } finally {
581
543
  await watcher?.close();
582
544
  }
583
545
  }
584
546
 
547
+ export async function startApiDev(args: StartDevOptions) {
548
+ if (args.logLevel) {
549
+ logger.loggerLevel = args.logLevel;
550
+ }
551
+ await printWranglerBanner();
552
+
553
+ const configPath =
554
+ (args.config as ConfigPath) ||
555
+ ((args.script &&
556
+ findWranglerToml(path.dirname(args.script))) as ConfigPath);
557
+ const config = readConfig(configPath, args);
558
+
559
+ const {
560
+ entry,
561
+ nodeCompat,
562
+ upstreamProtocol,
563
+ zoneId,
564
+ host,
565
+ routes,
566
+ getLocalPort,
567
+ getInspectorPort,
568
+ cliDefines,
569
+ localPersistencePath,
570
+ } = await validateDevServerSettings(args, config);
571
+
572
+ await metrics.sendMetricsEvent(
573
+ "run dev (api)",
574
+ { local: args.local },
575
+ { sendMetrics: config.send_metrics, offline: args.local }
576
+ );
577
+
578
+ // eslint-disable-next-line no-inner-declarations
579
+ async function getDevServer(configParam: Config) {
580
+ const { assetPaths, bindings } = getBindingsAndAssetPaths(
581
+ args,
582
+ configParam
583
+ );
584
+
585
+ //if args.bundle is on, don't disable bundling
586
+ //if there's no args.bundle, and configParam.no_bundle is on, disable bundling
587
+ //otherwise, enable bundling
588
+ const enableBundling = args.bundle ?? !configParam.no_bundle;
589
+ return await startDevServer({
590
+ name: getScriptName({ name: args.name, env: args.env }, configParam),
591
+ noBundle: !enableBundling,
592
+ entry: entry,
593
+ env: args.env,
594
+ zone: zoneId,
595
+ host: host,
596
+ routes: routes,
597
+ rules: getRules(configParam),
598
+ legacyEnv: isLegacyEnv(configParam),
599
+ minify: args.minify ?? configParam.minify,
600
+ nodeCompat: nodeCompat,
601
+ build: configParam.build || {},
602
+ define: { ...config.define, ...cliDefines },
603
+ initialMode: args.local ? "local" : "remote",
604
+ jsxFactory: args["jsx-factory"] || configParam.jsx_factory,
605
+ jsxFragment: args["jsx-fragment"] || configParam.jsx_fragment,
606
+ tsconfig: args.tsconfig ?? configParam.tsconfig,
607
+ upstreamProtocol: upstreamProtocol,
608
+ localProtocol: args.localProtocol || configParam.dev.local_protocol,
609
+ localUpstream: args["local-upstream"] || host,
610
+ localPersistencePath,
611
+ liveReload: args.liveReload || false,
612
+ accountId: configParam.account_id || getAccountFromCache()?.id,
613
+ assetPaths: assetPaths,
614
+ assetsConfig: configParam.assets,
615
+ //port can be 0, which means to use a random port
616
+ initialPort: args.port ?? configParam.dev.port ?? (await getLocalPort()),
617
+ initialIp: args.ip || configParam.dev.ip,
618
+ inspectorPort:
619
+ args["inspector-port"] ??
620
+ configParam.dev.inspector_port ??
621
+ (await getInspectorPort()),
622
+ isWorkersSite: Boolean(args.site || configParam.site),
623
+ compatibilityDate: getDevCompatibilityDate(
624
+ config,
625
+ // Only `compatibilityDate` will be set when using `unstable_dev`
626
+ args["compatibility-date"] ?? args.compatibilityDate
627
+ ),
628
+ compatibilityFlags:
629
+ args["compatibility-flags"] ??
630
+ args.compatibilityFlags ??
631
+ configParam.compatibility_flags,
632
+ usageModel: configParam.usage_model,
633
+ bindings: bindings,
634
+ crons: configParam.triggers.crons,
635
+ queueConsumers: configParam.queues.consumers,
636
+ logPrefix: args.logPrefix,
637
+ onReady: args.onReady,
638
+ inspect: args.inspect ?? true,
639
+ showInteractiveDevSession: args.showInteractiveDevSession,
640
+ forceLocal: args.forceLocal,
641
+ enablePagesAssetsServiceBinding: args.enablePagesAssetsServiceBinding,
642
+ local: args.local ?? true,
643
+ firstPartyWorker: configParam.first_party_worker,
644
+ sendMetrics: configParam.send_metrics,
645
+ testScheduled: args.testScheduled,
646
+ experimentalLocal: args.experimentalLocal,
647
+ experimentalLocalRemoteKv: args.experimentalLocalRemoteKv,
648
+ disableDevRegistry: args.disableDevRegistry ?? false,
649
+ });
650
+ }
651
+
652
+ const devServer = await getDevServer(config);
653
+ if (!devServer) {
654
+ throw logger.error("Failed to start dev server.");
655
+ }
656
+
657
+ return {
658
+ stop: async () => {
659
+ await devServer.stop();
660
+ },
661
+ };
662
+ }
585
663
  /**
586
664
  * Avoiding calling `getPort()` multiple times by memoizing the first result.
587
665
  */
@@ -591,3 +669,281 @@ function memoizeGetPort(defaultPort: number) {
591
669
  return portValue || (portValue = await getPort({ port: defaultPort }));
592
670
  };
593
671
  }
672
+ /**
673
+ * mask anything that was overridden in .dev.vars
674
+ * so that we don't log potential secrets into the terminal
675
+ */
676
+ function maskVars(bindings: CfWorkerInit["bindings"], configParam: Config) {
677
+ const maskedVars = { ...bindings.vars };
678
+ for (const key of Object.keys(maskedVars)) {
679
+ if (maskedVars[key] !== configParam.vars[key]) {
680
+ // This means it was overridden in .dev.vars
681
+ // so let's mask it
682
+ maskedVars[key] = "(hidden)";
683
+ }
684
+ }
685
+ return maskedVars;
686
+ }
687
+
688
+ async function getZoneIdHostAndRoutes(args: StartDevOptions, config: Config) {
689
+ // TODO: if worker_dev = false and no routes, then error (only for dev)
690
+ // Compute zone info from the `host` and `route` args and config;
691
+ let host = args.host || config.dev.host;
692
+ let zoneId: string | undefined;
693
+ const routes: Route[] | undefined =
694
+ args.routes || (config.route && [config.route]) || config.routes;
695
+
696
+ if (args.forceLocal) {
697
+ args.local = true;
698
+ }
699
+
700
+ if (!args.local) {
701
+ if (host) {
702
+ zoneId = await getZoneIdFromHost(host);
703
+ }
704
+ if (!zoneId && routes) {
705
+ const firstRoute = routes[0];
706
+ const zone = await getZoneForRoute(firstRoute);
707
+ if (zone) {
708
+ zoneId = zone.id;
709
+ host = zone.host;
710
+ }
711
+ }
712
+ } else if (!host) {
713
+ if (routes) {
714
+ const firstRoute = routes[0];
715
+ host = getHostFromRoute(firstRoute);
716
+ }
717
+ }
718
+ return { host, routes, zoneId };
719
+ }
720
+
721
+ async function validateDevServerSettings(
722
+ args: StartDevOptions,
723
+ config: Config
724
+ ) {
725
+ const entry = await getEntry(
726
+ { assets: args.assets, script: args.script },
727
+ config,
728
+ "dev"
729
+ );
730
+
731
+ const { zoneId, host, routes } = await getZoneIdHostAndRoutes(args, config);
732
+ const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
733
+ const getInspectorPort = memoizeGetPort(DEFAULT_INSPECTOR_PORT);
734
+
735
+ if (config.services && config.services.length > 0) {
736
+ logger.warn(
737
+ `This worker is bound to live services: ${config.services
738
+ .map(
739
+ (service) =>
740
+ `${service.binding} (${service.service}${
741
+ service.environment ? `@${service.environment}` : ""
742
+ })`
743
+ )
744
+ .join(", ")}`
745
+ );
746
+ }
747
+
748
+ if (args.inspect) {
749
+ //devtools are enabled by default, but we still need to disable them if the caller doesn't want them
750
+ logger.warn(
751
+ "Passing --inspect is unnecessary, now you can always connect to devtools."
752
+ );
753
+ }
754
+
755
+ if (args["experimental-public"]) {
756
+ throw new Error(
757
+ "The --experimental-public field has been renamed to --assets"
758
+ );
759
+ }
760
+
761
+ if (args.public) {
762
+ throw new Error("The --public field has been renamed to --assets");
763
+ }
764
+
765
+ if ((args.assets || config.assets) && (args.site || config.site)) {
766
+ throw new Error("Cannot use Assets and Workers Sites in the same Worker.");
767
+ }
768
+
769
+ if (args.assets) {
770
+ logger.warn(
771
+ "The --assets argument is experimental and may change or break at any time"
772
+ );
773
+ }
774
+ const upstreamProtocol =
775
+ args["upstream-protocol"] || config.dev.upstream_protocol;
776
+ if (upstreamProtocol === "http") {
777
+ logger.warn(
778
+ "Setting upstream-protocol to http is not currently implemented.\n" +
779
+ "If this is required in your project, please add your use case to the following issue:\n" +
780
+ "https://github.com/cloudflare/wrangler2/issues/583."
781
+ );
782
+ }
783
+ const nodeCompat = args.nodeCompat ?? config.node_compat;
784
+ if (nodeCompat) {
785
+ logger.warn(
786
+ "Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
787
+ );
788
+ }
789
+
790
+ if (args.experimentalEnableLocalPersistence) {
791
+ logger.warn(
792
+ `--experimental-enable-local-persistence is deprecated.\n` +
793
+ `Move any existing data to .wrangler/state and use --persist, or\n` +
794
+ `use --persist-to=./wrangler-local-state to keep using the old path.`
795
+ );
796
+ }
797
+
798
+ const localPersistencePath = getLocalPersistencePath(
799
+ args.persistTo,
800
+ Boolean(args.persist),
801
+ config.configPath
802
+ );
803
+
804
+ const cliDefines = collectKeyValues(args.define);
805
+
806
+ return {
807
+ entry,
808
+ upstreamProtocol,
809
+ nodeCompat,
810
+ getLocalPort,
811
+ getInspectorPort,
812
+ zoneId,
813
+ host,
814
+ routes,
815
+ cliDefines,
816
+ localPersistencePath,
817
+ };
818
+ }
819
+
820
+ function getBindingsAndAssetPaths(args: StartDevOptions, configParam: Config) {
821
+ const cliVars = collectKeyValues(args.var);
822
+
823
+ // now log all available bindings into the terminal
824
+ const bindings = getBindings(configParam, args.env, args.local ?? false, {
825
+ kv: args.kv,
826
+ vars: { ...args.vars, ...cliVars },
827
+ durableObjects: args.durableObjects,
828
+ r2: args.r2,
829
+ d1Databases: args.d1Databases,
830
+ });
831
+
832
+ const maskedVars = maskVars(bindings, configParam);
833
+
834
+ printBindings({
835
+ ...bindings,
836
+ vars: maskedVars,
837
+ });
838
+
839
+ const assetPaths =
840
+ args.assets || configParam.assets
841
+ ? getAssetPaths(configParam, args.assets)
842
+ : getSiteAssetPaths(
843
+ configParam,
844
+ args.site,
845
+ args.siteInclude,
846
+ args.siteExclude
847
+ );
848
+ return { assetPaths, bindings };
849
+ }
850
+
851
+ function getBindings(
852
+ configParam: Config,
853
+ env: string | undefined,
854
+ local: boolean,
855
+ args: AdditionalDevProps
856
+ ): CfWorkerInit["bindings"] {
857
+ const bindings = {
858
+ kv_namespaces: [
859
+ ...(configParam.kv_namespaces || []).map(
860
+ ({ binding, preview_id, id: _id }) => {
861
+ // In `dev`, we make folks use a separate kv namespace called
862
+ // `preview_id` instead of `id` so that they don't
863
+ // break production data. So here we check that a `preview_id`
864
+ // has actually been configured.
865
+ // This whole block of code will be obsoleted in the future
866
+ // when we have copy-on-write for previews on edge workers.
867
+ if (!preview_id) {
868
+ // TODO: This error has to be a _lot_ better, ideally just asking
869
+ // to create a preview namespace for the user automatically
870
+ throw new Error(
871
+ `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
872
+ ); // Ugh, I really don't like this message very much
873
+ }
874
+ return {
875
+ binding,
876
+ id: preview_id,
877
+ };
878
+ }
879
+ ),
880
+ ...(args.kv || []),
881
+ ],
882
+ // Use a copy of combinedVars since we're modifying it later
883
+ vars: {
884
+ ...getVarsForDev(configParam, env),
885
+ ...args.vars,
886
+ },
887
+ wasm_modules: configParam.wasm_modules,
888
+ text_blobs: configParam.text_blobs,
889
+ data_blobs: configParam.data_blobs,
890
+ durable_objects: {
891
+ bindings: [
892
+ ...(configParam.durable_objects || { bindings: [] }).bindings,
893
+ ...(args.durableObjects || []),
894
+ ],
895
+ },
896
+ queues: [
897
+ ...(configParam.queues.producers || []).map((queue) => {
898
+ return { binding: queue.binding, queue_name: queue.queue };
899
+ }),
900
+ ],
901
+ r2_buckets: [
902
+ ...(configParam.r2_buckets?.map(
903
+ ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
904
+ // same idea as kv namespace preview id,
905
+ // same copy-on-write TODO
906
+ if (!preview_bucket_name) {
907
+ throw new Error(
908
+ `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
909
+ );
910
+ }
911
+ return {
912
+ binding,
913
+ bucket_name: preview_bucket_name,
914
+ };
915
+ }
916
+ ) || []),
917
+ ...(args.r2 || []),
918
+ ],
919
+ dispatch_namespaces: configParam.dispatch_namespaces,
920
+ services: configParam.services,
921
+ analytics_engine_datasets: configParam.analytics_engine_datasets,
922
+ unsafe: configParam.unsafe?.bindings,
923
+ logfwdr: configParam.logfwdr,
924
+ d1_databases: identifyD1BindingsAsBeta([
925
+ ...(configParam.d1_databases ?? []).map((d1Db) => {
926
+ //in local dev, bindings don't matter
927
+ if (local) {
928
+ return {
929
+ ...d1Db,
930
+ database_id: "local",
931
+ };
932
+ }
933
+ if (!d1Db.preview_database_id) {
934
+ throw new Error(
935
+ `In development, you should use a separate D1 database than the one you'd use in production. Please create a new D1 database with "wrangler d1 create <name>" and add its id as preview_database_id to the d1_database "${d1Db.binding}" in your wrangler.toml`
936
+ );
937
+ }
938
+
939
+ return {
940
+ ...d1Db,
941
+ database_id: d1Db.preview_database_id,
942
+ };
943
+ }),
944
+ ...(args.d1Databases || []),
945
+ ]),
946
+ };
947
+
948
+ return bindings;
949
+ }