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
@@ -0,0 +1,145 @@
1
+ import { DeprecationError } from "../errors";
2
+ import { createCLIParser } from "../index";
3
+ import { logger } from "../logger";
4
+ import { formatMessage } from "../parse";
5
+ import type {
6
+ CommonYargsOptions,
7
+ YargsOptionsToInterface,
8
+ } from "../yargs-types";
9
+ import type { Argv, BuilderCallback } from "yargs";
10
+
11
+ export function buildOptions(yargs: Argv<CommonYargsOptions>) {
12
+ return yargs;
13
+ }
14
+ type BuildArgs = YargsOptionsToInterface<typeof buildOptions>;
15
+ export async function buildHandler(buildArgs: BuildArgs) {
16
+ // "[DEPRECATED] 🦀 Build your project (if applicable)",
17
+
18
+ const envFlag = buildArgs.env ? ` --env=${buildArgs.env}` : "";
19
+ logger.log(
20
+ formatMessage({
21
+ kind: "warning",
22
+ text: "Deprecation: `wrangler build` has been deprecated.",
23
+ notes: [
24
+ {
25
+ text: "Please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#build for more information.",
26
+ },
27
+ {
28
+ text: `Attempting to run \`wrangler publish --dry-run --outdir=dist${envFlag}\` for you instead:`,
29
+ },
30
+ ],
31
+ })
32
+ );
33
+
34
+ await createCLIParser([
35
+ "publish",
36
+ "--dry-run",
37
+ "--outdir=dist",
38
+ ...(buildArgs.env ? ["--env", buildArgs.env] : []),
39
+ ]).parse();
40
+ }
41
+
42
+ export const noOpOptions = () => {};
43
+ export const configHandler = () => {
44
+ // "🕵️ Authenticate Wrangler with a Cloudflare API Token",
45
+ throw new DeprecationError(
46
+ "`wrangler config` has been deprecated, please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#config for alternatives"
47
+ );
48
+ };
49
+
50
+ export function previewOptions(yargs: Argv<CommonYargsOptions>) {
51
+ return yargs
52
+ .positional("method", {
53
+ type: "string",
54
+ describe: "Type of request to preview your worker",
55
+ })
56
+ .positional("body", {
57
+ type: "string",
58
+ describe: "Body string to post to your preview worker request.",
59
+ })
60
+ .option("watch", {
61
+ default: true,
62
+ describe: "Enable live preview",
63
+ type: "boolean",
64
+ });
65
+ }
66
+
67
+ export function previewHandler() {
68
+ throw new DeprecationError(
69
+ "The `wrangler preview` command has been deprecated.\n" +
70
+ "Try using `wrangler dev` to to try out a worker during development.\n"
71
+ );
72
+ }
73
+
74
+ export const route: BuilderCallback<unknown, unknown> = (routeYargs: Argv) => {
75
+ return routeYargs
76
+ .command(
77
+ "list",
78
+ "List the routes associated with a zone",
79
+ (yargs) => {
80
+ return yargs
81
+ .option("zone", {
82
+ type: "string",
83
+ requiresArg: true,
84
+ describe: "Zone id",
85
+ })
86
+ .positional("zone", {
87
+ describe: "Zone id",
88
+ type: "string",
89
+ });
90
+ },
91
+ () => {
92
+ // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
93
+ const deprecationNotice = "`wrangler route list` has been deprecated.";
94
+ const futureRoutes =
95
+ "Refer to wrangler.toml for a list of routes the worker will be deployed to upon publishing.";
96
+ const presentRoutes =
97
+ "Refer to the Cloudflare Dashboard to see the routes this worker is currently running on.";
98
+ throw new DeprecationError(
99
+ `${deprecationNotice}\n${futureRoutes}\n${presentRoutes}`
100
+ );
101
+ }
102
+ )
103
+ .command(
104
+ "delete [id]",
105
+ "Delete a route associated with a zone",
106
+ (yargs) => {
107
+ return yargs
108
+ .positional("id", {
109
+ describe: "The hash of the route ID to delete.",
110
+ type: "string",
111
+ })
112
+ .option("zone", {
113
+ type: "string",
114
+ requiresArg: true,
115
+ describe: "zone id",
116
+ });
117
+ },
118
+ () => {
119
+ // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
120
+ const deprecationNotice =
121
+ "`wrangler route delete` has been deprecated.";
122
+ const shouldDo =
123
+ "Remove the unwanted route(s) from wrangler.toml and run `wrangler publish` to remove your worker from those routes.";
124
+ throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
125
+ }
126
+ );
127
+ };
128
+
129
+ export const routeHandler = () => {
130
+ // "[DEPRECATED]. Use wrangler.toml to manage routes.
131
+ const deprecationNotice = "`wrangler route` has been deprecated.";
132
+ const shouldDo =
133
+ "Please use wrangler.toml and/or `wrangler publish --routes` to modify routes";
134
+ throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
135
+ };
136
+
137
+ export const subdomainOptions = (yargs: Argv<CommonYargsOptions>) => {
138
+ return yargs.positional("name", { type: "string" });
139
+ };
140
+
141
+ export const subdomainHandler = () => {
142
+ throw new DeprecationError(
143
+ "`wrangler subdomain` has been deprecated, please refer to https://developers.cloudflare.com/workers/wrangler/migration/deprecations/#subdomain for alternatives"
144
+ );
145
+ };
@@ -1,6 +1,5 @@
1
- import * as fs from "node:fs";
2
1
  import * as path from "node:path";
3
- import dotenv from "dotenv";
2
+ import { loadDotEnv } from "../config";
4
3
  import { logger } from "../logger";
5
4
  import type { Config } from "../config";
6
5
 
@@ -14,21 +13,25 @@ import type { Config } from "../config";
14
13
  * It is useful during development, to provide these types of variable locally.
15
14
  * When running `wrangler dev` we will look for a file called `.dev.vars`, situated
16
15
  * next to the `wrangler.toml` file (or in the current working directory if there is no
17
- * `wrangler.toml`).
16
+ * `wrangler.toml`). If the `--env <env>` option is set, we'll first look for
17
+ * `.dev.vars.<env>`.
18
18
  *
19
19
  * Any values in this file, formatted like a `dotenv` file, will add to or override `vars`
20
20
  * bindings provided in the `wrangler.toml`.
21
21
  */
22
- export function getVarsForDev(config: Config): Config["vars"] {
22
+ export function getVarsForDev(
23
+ config: Config,
24
+ env: string | undefined
25
+ ): Config["vars"] {
23
26
  const configDir = path.resolve(path.dirname(config.configPath ?? "."));
24
27
  const devVarsPath = path.resolve(configDir, ".dev.vars");
25
- if (fs.existsSync(devVarsPath)) {
26
- const devVarsRelativePath = path.relative(process.cwd(), devVarsPath);
28
+ const loaded = loadDotEnv(devVarsPath, env);
29
+ if (loaded !== undefined) {
30
+ const devVarsRelativePath = path.relative(process.cwd(), loaded.path);
27
31
  logger.log(`Using vars defined in ${devVarsRelativePath}`);
28
- const devVars = dotenv.parse(fs.readFileSync(devVarsPath, "utf8"));
29
32
  return {
30
33
  ...config.vars,
31
- ...devVars,
34
+ ...loaded.parsed,
32
35
  };
33
36
  } else {
34
37
  return config.vars;
package/src/dev/dev.tsx CHANGED
@@ -1,14 +1,21 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import * as path from "node:path";
3
+ import * as util from "node:util";
3
4
  import { watch } from "chokidar";
4
5
  import clipboardy from "clipboardy";
5
6
  import commandExists from "command-exists";
6
7
  import { Box, Text, useApp, useInput, useStdin } from "ink";
7
- import React, { useState, useEffect, useRef } from "react";
8
+ import React, { useState, useEffect, useRef, useMemo } from "react";
8
9
  import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
9
10
  import onExit from "signal-exit";
10
11
  import tmp from "tmp-promise";
11
12
  import { fetch } from "undici";
13
+ import {
14
+ getBoundRegisteredWorkers,
15
+ startWorkerRegistry,
16
+ stopWorkerRegistry,
17
+ unregisterWorker,
18
+ } from "../dev-registry";
12
19
  import { runCustomBuild } from "../entry";
13
20
  import { openInspector } from "../inspect";
14
21
  import { logger } from "../logger";
@@ -16,19 +23,98 @@ import openInBrowser from "../open-in-browser";
16
23
  import { Local } from "./local";
17
24
  import { Remote } from "./remote";
18
25
  import { useEsbuild } from "./use-esbuild";
26
+ import { validateDevProps } from "./validate-dev-props";
19
27
  import type { Config } from "../config";
20
28
  import type { Route } from "../config/environment";
29
+ import type { WorkerRegistry } from "../dev-registry";
21
30
  import type { Entry } from "../entry";
22
- import type { EnablePagesAssetsServiceBindingOptions } from "../miniflare-cli";
31
+ import type { EnablePagesAssetsServiceBindingOptions } from "../miniflare-cli/types";
23
32
  import type { AssetPaths } from "../sites";
24
33
  import type { CfWorkerInit } from "../worker";
25
34
 
35
+ /**
36
+ * This hooks establishes a connection with the dev registry,
37
+ * and periodically updates itself with details of workers currently
38
+ * running a dev session on this system.
39
+ */
40
+ function useDevRegistry(
41
+ name: string | undefined,
42
+ services: Config["services"] | undefined,
43
+ durableObjects: Config["durable_objects"] | undefined,
44
+ mode: "local" | "remote"
45
+ ): WorkerRegistry {
46
+ const [workers, setWorkers] = useState<WorkerRegistry>({});
47
+
48
+ useEffect(() => {
49
+ // Let's try to start registry
50
+ // TODO: we should probably call this in a loop
51
+ // in case the registry dies elsewhere
52
+ startWorkerRegistry().catch((err) => {
53
+ logger.error("failed to start worker registry", err);
54
+ });
55
+
56
+ const interval =
57
+ // TODO: enable this for remote mode as well
58
+ // https://github.com/cloudflare/wrangler2/issues/1182
59
+ mode === "local"
60
+ ? setInterval(() => {
61
+ getBoundRegisteredWorkers({
62
+ services,
63
+ durableObjects,
64
+ }).then(
65
+ (boundRegisteredWorkers: WorkerRegistry | undefined) => {
66
+ setWorkers((prevWorkers) => {
67
+ if (
68
+ !util.isDeepStrictEqual(boundRegisteredWorkers, prevWorkers)
69
+ ) {
70
+ return boundRegisteredWorkers || {};
71
+ }
72
+ return prevWorkers;
73
+ });
74
+ },
75
+ (err) => {
76
+ logger.warn("Failed to get worker definitions", err);
77
+ }
78
+ );
79
+ }, 300)
80
+ : undefined;
81
+
82
+ return () => {
83
+ interval && clearInterval(interval);
84
+ Promise.allSettled([
85
+ name ? unregisterWorker(name) : Promise.resolve(),
86
+ stopWorkerRegistry(),
87
+ ]).then(
88
+ ([unregisterResult, stopRegistryResult]) => {
89
+ if (unregisterResult.status === "rejected") {
90
+ logger.error(
91
+ "Failed to unregister worker",
92
+ unregisterResult.reason
93
+ );
94
+ }
95
+ if (stopRegistryResult.status === "rejected") {
96
+ logger.error(
97
+ "Failed to stop worker registry",
98
+ stopRegistryResult.reason
99
+ );
100
+ }
101
+ },
102
+ (err) => {
103
+ logger.error("Failed to clear dev registry effect", err);
104
+ }
105
+ );
106
+ };
107
+ }, [name, services, durableObjects, mode]);
108
+
109
+ return workers;
110
+ }
111
+
26
112
  export type DevProps = {
27
113
  name: string | undefined;
28
114
  noBundle: boolean;
29
115
  entry: Entry;
30
- port: number;
31
- ip: string;
116
+ initialPort: number;
117
+ initialIp: string;
32
118
  inspectorPort: number;
33
119
  rules: Config["rules"];
34
120
  accountId: string | undefined;
@@ -39,13 +125,15 @@ export type DevProps = {
39
125
  upstreamProtocol: "https" | "http";
40
126
  localProtocol: "https" | "http";
41
127
  localUpstream: string | undefined;
42
- enableLocalPersistence: boolean;
128
+ localPersistencePath: string | null;
43
129
  liveReload: boolean;
44
130
  bindings: CfWorkerInit["bindings"];
45
131
  define: Config["define"];
46
132
  crons: Config["triggers"]["crons"];
133
+ queueConsumers: Config["queues"]["consumers"];
47
134
  isWorkersSite: boolean;
48
135
  assetPaths: AssetPaths | undefined;
136
+ assetsConfig: Config["assets"];
49
137
  compatibilityDate: string;
50
138
  compatibilityFlags: string[] | undefined;
51
139
  usageModel: "bundled" | "unbound" | undefined;
@@ -58,42 +146,20 @@ export type DevProps = {
58
146
  host: string | undefined;
59
147
  routes: Route[] | undefined;
60
148
  inspect: boolean;
61
- logLevel: "none" | "error" | "log" | "warn" | "debug" | undefined;
62
149
  logPrefix?: string;
63
- onReady: (() => void) | undefined;
150
+ onReady: ((ip: string, port: number) => void) | undefined;
64
151
  showInteractiveDevSession: boolean | undefined;
65
152
  forceLocal: boolean | undefined;
66
153
  enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
154
+ firstPartyWorker: boolean | undefined;
155
+ sendMetrics: boolean | undefined;
156
+ testScheduled: boolean | undefined;
157
+ experimentalLocal: boolean | undefined;
158
+ experimentalLocalRemoteKv: boolean | undefined;
67
159
  };
68
160
 
69
161
  export function DevImplementation(props: DevProps): JSX.Element {
70
- if (
71
- !props.isWorkersSite &&
72
- props.assetPaths &&
73
- props.entry.format === "service-worker"
74
- ) {
75
- throw new Error(
76
- "You cannot use the service-worker format with an `assets` directory yet. For information on how to migrate to the module-worker format, see: https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/"
77
- );
78
- }
79
-
80
- if (props.bindings.wasm_modules && props.entry.format === "modules") {
81
- throw new Error(
82
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
83
- );
84
- }
85
-
86
- if (props.bindings.text_blobs && props.entry.format === "modules") {
87
- throw new Error(
88
- "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
89
- );
90
- }
91
-
92
- if (props.bindings.data_blobs && props.entry.format === "modules") {
93
- throw new Error(
94
- "You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
95
- );
96
- }
162
+ validateDevProps(props);
97
163
 
98
164
  // only load the UI if we're running in a supported environment
99
165
  const { isRawModeSupported } = useStdin();
@@ -105,25 +171,42 @@ export function DevImplementation(props: DevProps): JSX.Element {
105
171
  );
106
172
  }
107
173
 
174
+ // This is a nasty hack to allow `useHotkeys` and its "[b] open a browser" feature to read these values
175
+ // without triggering a re-render loop when `onReady()` updates them.
176
+ // The initially requested port can be different than what's actually used, if, for example, you request port 0.
177
+ let ip: string;
178
+ let port: number;
179
+
108
180
  function InteractiveDevSession(props: DevProps) {
109
181
  const toggles = useHotkeys({
110
182
  initial: {
111
183
  local: props.initialMode === "local",
112
184
  tunnel: false,
113
185
  },
114
- port: props.port,
115
- ip: props.ip,
116
186
  inspectorPort: props.inspectorPort,
117
187
  inspect: props.inspect,
118
188
  localProtocol: props.localProtocol,
119
189
  forceLocal: props.forceLocal,
120
190
  });
121
191
 
192
+ ip = props.initialIp;
193
+ port = props.initialPort;
194
+
122
195
  useTunnel(toggles.tunnel);
123
196
 
197
+ const onReady = (newIp: string, newPort: number) => {
198
+ if (newIp !== props.initialIp || newPort !== props.initialPort) {
199
+ ip = newIp;
200
+ port = newPort;
201
+ if (props.onReady) {
202
+ props.onReady(newIp, newPort);
203
+ }
204
+ }
205
+ };
206
+
124
207
  return (
125
208
  <>
126
- <DevSession {...props} local={toggles.local} />
209
+ <DevSession {...props} local={toggles.local} onReady={onReady} />
127
210
  <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
128
211
  <Text bold={true}>[b]</Text>
129
212
  <Text> open a browser, </Text>
@@ -150,12 +233,53 @@ function InteractiveDevSession(props: DevProps) {
150
233
 
151
234
  type DevSessionProps = DevProps & {
152
235
  local: boolean;
236
+ experimentalLocal?: boolean;
153
237
  };
154
238
 
155
239
  function DevSession(props: DevSessionProps) {
156
240
  useCustomBuild(props.entry, props.build);
157
241
 
158
242
  const directory = useTmpDir();
243
+ const handleError = useErrorHandler();
244
+
245
+ // Note: when D1 is out of beta, this (and all instances of `betaD1Shims`) can be removed.
246
+ // Additionally, useMemo is used so that new arrays aren't created on every render
247
+ // cause re-rendering further down.
248
+ const betaD1Shims = useMemo(
249
+ () => props.bindings.d1_databases?.map((db) => db.binding),
250
+ [props.bindings.d1_databases]
251
+ );
252
+ const everyD1BindingHasPreview = props.bindings.d1_databases?.every(
253
+ (binding) => binding.preview_database_id
254
+ );
255
+ if (
256
+ betaD1Shims &&
257
+ betaD1Shims.length > 0 &&
258
+ !(props.local || everyD1BindingHasPreview)
259
+ ) {
260
+ handleError(
261
+ new Error(
262
+ "D1 bindings require dev --local or preview_database_id for now"
263
+ )
264
+ );
265
+ }
266
+
267
+ // If we are using d1 bindings, and are not bundling the worker
268
+ // we should error here as the d1 shim won't be added
269
+ if (Array.isArray(betaD1Shims) && betaD1Shims.length > 0 && props.noBundle) {
270
+ handleError(
271
+ new Error(
272
+ "While in beta, you cannot use D1 bindings without bundling your worker. Please remove `no_bundle` from your wrangler.toml file or remove the `--no-bundle` flag to access D1 bindings."
273
+ )
274
+ );
275
+ }
276
+
277
+ const workerDefinitions = useDevRegistry(
278
+ props.name,
279
+ props.bindings.services,
280
+ props.bindings.durable_objects,
281
+ props.local ? "local" : "remote"
282
+ );
159
283
 
160
284
  const bundle = useEsbuild({
161
285
  entry: props.entry,
@@ -169,10 +293,47 @@ function DevSession(props: DevSessionProps) {
169
293
  tsconfig: props.tsconfig,
170
294
  minify: props.minify,
171
295
  nodeCompat: props.nodeCompat,
296
+ betaD1Shims,
172
297
  define: props.define,
173
298
  noBundle: props.noBundle,
299
+ assets: props.assetsConfig,
300
+ workerDefinitions,
301
+ services: props.bindings.services,
302
+ durableObjects: props.bindings.durable_objects || { bindings: [] },
303
+ firstPartyWorkerDevFacade: props.firstPartyWorker,
304
+ local: props.local,
305
+ // Enable the bundling to know whether we are using dev or publish
306
+ targetConsumer: "dev",
307
+ testScheduled: props.testScheduled ?? false,
308
+ experimentalLocal: props.experimentalLocal,
174
309
  });
175
310
 
311
+ // TODO(queues) support remote wrangler dev
312
+ if (
313
+ !props.local &&
314
+ (props.bindings.queues?.length || props.queueConsumers?.length)
315
+ ) {
316
+ logger.warn(
317
+ "Queues are currently in Beta and are not supported in wrangler dev remote mode."
318
+ );
319
+ }
320
+
321
+ const announceAndOnReady: typeof props.onReady = (finalIp, finalPort) => {
322
+ if (process.send) {
323
+ process.send(
324
+ JSON.stringify({
325
+ event: "DEV_SERVER_READY",
326
+ ip: finalIp,
327
+ port: finalPort,
328
+ })
329
+ );
330
+ }
331
+
332
+ if (props.onReady) {
333
+ props.onReady(finalIp, finalPort);
334
+ }
335
+ };
336
+
176
337
  return props.local ? (
177
338
  <Local
178
339
  name={props.name}
@@ -180,23 +341,27 @@ function DevSession(props: DevSessionProps) {
180
341
  format={props.entry.format}
181
342
  compatibilityDate={props.compatibilityDate}
182
343
  compatibilityFlags={props.compatibilityFlags}
344
+ usageModel={props.usageModel}
183
345
  bindings={props.bindings}
346
+ workerDefinitions={workerDefinitions}
184
347
  assetPaths={props.assetPaths}
185
- isWorkersSite={props.isWorkersSite}
186
- port={props.port}
187
- ip={props.ip}
348
+ initialPort={props.initialPort}
349
+ initialIp={props.initialIp}
188
350
  rules={props.rules}
189
351
  inspectorPort={props.inspectorPort}
190
- enableLocalPersistence={props.enableLocalPersistence}
352
+ localPersistencePath={props.localPersistencePath}
191
353
  liveReload={props.liveReload}
192
354
  crons={props.crons}
355
+ queueConsumers={props.queueConsumers}
193
356
  localProtocol={props.localProtocol}
194
357
  localUpstream={props.localUpstream}
195
- logLevel={props.logLevel}
196
358
  logPrefix={props.logPrefix}
197
359
  inspect={props.inspect}
198
- onReady={props.onReady}
360
+ onReady={announceAndOnReady}
199
361
  enablePagesAssetsServiceBinding={props.enablePagesAssetsServiceBinding}
362
+ experimentalLocal={props.experimentalLocal}
363
+ accountId={props.accountId}
364
+ experimentalLocalRemoteKv={props.experimentalLocalRemoteKv}
200
365
  />
201
366
  ) : (
202
367
  <Remote
@@ -207,8 +372,8 @@ function DevSession(props: DevSessionProps) {
207
372
  bindings={props.bindings}
208
373
  assetPaths={props.assetPaths}
209
374
  isWorkersSite={props.isWorkersSite}
210
- port={props.port}
211
- ip={props.ip}
375
+ port={props.initialPort}
376
+ ip={props.initialIp}
212
377
  localProtocol={props.localProtocol}
213
378
  inspectorPort={props.inspectorPort}
214
379
  // TODO: @threepointone #1167
@@ -222,7 +387,9 @@ function DevSession(props: DevSessionProps) {
222
387
  zone={props.zone}
223
388
  host={props.host}
224
389
  routes={props.routes}
225
- onReady={props.onReady}
390
+ onReady={announceAndOnReady}
391
+ sourceMapPath={bundle?.sourceMapPath}
392
+ sendMetrics={props.sendMetrics}
226
393
  />
227
394
  );
228
395
  }
@@ -274,7 +441,7 @@ function useCustomBuild(expectedEntry: Entry, build: Config["build"]): void {
274
441
  }
275
442
 
276
443
  return () => {
277
- watcher?.close();
444
+ void watcher?.close();
278
445
  };
279
446
  }, [build, expectedEntry]);
280
447
  }
@@ -369,25 +536,16 @@ type useHotkeysInitialState = {
369
536
  };
370
537
  function useHotkeys(props: {
371
538
  initial: useHotkeysInitialState;
372
- port: number;
373
- ip: string;
374
539
  inspectorPort: number;
375
540
  inspect: boolean;
376
541
  localProtocol: "http" | "https";
377
542
  forceLocal: boolean | undefined;
378
543
  }) {
379
- const {
380
- initial,
381
- port,
382
- ip,
383
- inspectorPort,
384
- inspect,
385
- localProtocol,
386
- forceLocal,
387
- } = props;
544
+ const { initial, inspectorPort, inspect, localProtocol, forceLocal } = props;
388
545
  // UGH, we should put port in context instead
389
546
  const [toggles, setToggles] = useState(initial);
390
547
  const { exit } = useApp();
548
+
391
549
  useInput(
392
550
  async (
393
551
  input,
@@ -404,6 +562,10 @@ function useHotkeys(props: {
404
562
  break;
405
563
  // open browser
406
564
  case "b": {
565
+ if (ip === "0.0.0.0") {
566
+ await openInBrowser(`${localProtocol}://127.0.0.1:${port}`);
567
+ return;
568
+ }
407
569
  await openInBrowser(`${localProtocol}://${ip}:${port}`);
408
570
  break;
409
571
  }
@@ -0,0 +1,31 @@
1
+ import path from "node:path";
2
+
3
+ export function getLocalPersistencePath(
4
+ persistTo: string | undefined,
5
+ doPersist: true,
6
+ configPath: string | undefined
7
+ ): string;
8
+
9
+ export function getLocalPersistencePath(
10
+ persistTo: string | undefined,
11
+ doPersist: boolean,
12
+ configPath: string | undefined
13
+ ): string | null;
14
+
15
+ export function getLocalPersistencePath(
16
+ persistTo: string | undefined,
17
+ doPersist: boolean,
18
+ configPath: string | undefined
19
+ ) {
20
+ return persistTo
21
+ ? // If path specified, always treat it as relative to cwd()
22
+ path.resolve(process.cwd(), persistTo)
23
+ : doPersist
24
+ ? // If just flagged on, treat it as relative to wrangler.toml,
25
+ // if one can be found, otherwise cwd()
26
+ path.resolve(
27
+ configPath ? path.dirname(configPath) : process.cwd(),
28
+ ".wrangler/state"
29
+ )
30
+ : null;
31
+ }