wrangler 0.0.0-e1c615f → 0.0.0-e1e2ee5c

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 (212) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +33 -14
  3. package/bin/wrangler.js +159 -27
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5354 -0
  6. package/package.json +166 -123
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +3950 -0
  10. package/src/__tests__/dev.test.tsx +1199 -62
  11. package/src/__tests__/guess-worker-format.test.ts +85 -0
  12. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  13. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  14. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  15. package/src/__tests__/helpers/mock-bin.ts +36 -0
  16. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  17. package/src/__tests__/helpers/mock-console.ts +97 -0
  18. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  19. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  20. package/src/__tests__/helpers/mock-istty.ts +74 -0
  21. package/src/__tests__/helpers/mock-kv.ts +33 -0
  22. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  23. package/src/__tests__/helpers/mock-process.ts +39 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  25. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +38 -0
  27. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  28. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +163 -0
  31. package/src/__tests__/index.test.ts +259 -284
  32. package/src/__tests__/init.test.ts +1992 -0
  33. package/src/__tests__/jest.setup.ts +108 -10
  34. package/src/__tests__/kv.test.ts +1459 -886
  35. package/src/__tests__/logger.test.ts +141 -0
  36. package/src/__tests__/metrics.test.ts +445 -0
  37. package/src/__tests__/package-manager.test.ts +353 -0
  38. package/src/__tests__/pages.test.ts +1261 -0
  39. package/src/__tests__/parse.test.ts +330 -0
  40. package/src/__tests__/publish.test.ts +6671 -0
  41. package/src/__tests__/pubsub.test.ts +367 -0
  42. package/src/__tests__/r2.test.ts +233 -0
  43. package/src/__tests__/route.test.ts +45 -0
  44. package/src/__tests__/secret.test.ts +492 -0
  45. package/src/__tests__/tail.test.ts +698 -0
  46. package/src/__tests__/test-old-node-version.js +31 -0
  47. package/src/__tests__/user.test.ts +143 -0
  48. package/src/__tests__/version.test.ts +35 -0
  49. package/src/__tests__/whoami.test.tsx +230 -0
  50. package/src/__tests__/worker-namespace.test.ts +327 -0
  51. package/src/abort.d.ts +3 -0
  52. package/src/api/dev.ts +86 -0
  53. package/src/api/index.ts +1 -0
  54. package/src/bundle-reporter.tsx +29 -0
  55. package/src/bundle.ts +236 -0
  56. package/src/cfetch/index.ts +88 -69
  57. package/src/cfetch/internal.ts +124 -44
  58. package/src/cli.ts +24 -6
  59. package/src/config/README.md +107 -0
  60. package/src/config/config.ts +251 -0
  61. package/src/config/diagnostics.ts +80 -0
  62. package/src/config/environment.ts +453 -0
  63. package/src/config/index.ts +238 -0
  64. package/src/config/validation-helpers.ts +584 -0
  65. package/src/config/validation.ts +1754 -0
  66. package/src/config-cache.ts +84 -0
  67. package/src/create-worker-preview.ts +255 -0
  68. package/src/create-worker-upload-form.ts +263 -0
  69. package/src/dev/dev-vars.ts +36 -0
  70. package/src/dev/dev.tsx +452 -0
  71. package/src/dev/local.tsx +373 -0
  72. package/src/dev/remote.tsx +386 -0
  73. package/src/dev/use-esbuild.ts +150 -0
  74. package/src/dev.tsx +581 -862
  75. package/src/dialogs.tsx +117 -59
  76. package/src/durable.ts +102 -0
  77. package/src/entry.ts +328 -0
  78. package/src/environment-variables.ts +35 -0
  79. package/src/errors.ts +11 -0
  80. package/src/faye-websocket.d.ts +6 -0
  81. package/src/generate.ts +33 -0
  82. package/src/git-client.ts +42 -0
  83. package/src/global-wrangler-config-path.ts +26 -0
  84. package/src/https-options.ts +127 -0
  85. package/src/index.tsx +1987 -1911
  86. package/src/init.ts +549 -0
  87. package/src/inspect.ts +662 -0
  88. package/src/intl-polyfill.d.ts +139 -0
  89. package/src/is-interactive.ts +12 -0
  90. package/src/kv.ts +430 -0
  91. package/src/logger.ts +73 -0
  92. package/src/metrics/index.ts +4 -0
  93. package/src/metrics/is-ci.ts +14 -0
  94. package/src/metrics/metrics-config.ts +239 -0
  95. package/src/metrics/metrics-dispatcher.ts +95 -0
  96. package/src/metrics/send-event.ts +92 -0
  97. package/src/miniflare-cli/README.md +30 -0
  98. package/src/miniflare-cli/assets.ts +543 -0
  99. package/src/miniflare-cli/enum-keys.ts +17 -0
  100. package/src/miniflare-cli/index.ts +85 -0
  101. package/src/miniflare-cli/request-context.ts +40 -0
  102. package/src/module-collection.ts +247 -53
  103. package/src/open-in-browser.ts +17 -0
  104. package/src/package-manager.ts +219 -0
  105. package/src/pages/build.tsx +204 -0
  106. package/src/pages/constants.ts +7 -0
  107. package/src/pages/deployments.tsx +106 -0
  108. package/src/pages/dev.tsx +401 -0
  109. package/src/pages/functions/buildPlugin.ts +105 -0
  110. package/src/pages/functions/buildWorker.ts +151 -0
  111. package/src/pages/functions/filepath-routing.test.ts +234 -0
  112. package/src/pages/functions/filepath-routing.ts +189 -0
  113. package/src/pages/functions/identifiers.ts +78 -0
  114. package/src/pages/functions/routes.ts +151 -0
  115. package/src/pages/index.tsx +84 -0
  116. package/src/pages/projects.tsx +163 -0
  117. package/src/pages/publish.tsx +338 -0
  118. package/src/pages/types.ts +40 -0
  119. package/src/pages/upload.tsx +396 -0
  120. package/src/pages/utils.ts +12 -0
  121. package/src/parse.ts +286 -0
  122. package/src/paths.ts +26 -0
  123. package/src/preview.ts +31 -0
  124. package/src/proxy.ts +464 -91
  125. package/src/publish.ts +780 -337
  126. package/src/pubsub/index.ts +286 -0
  127. package/src/pubsub/pubsub-commands.tsx +623 -0
  128. package/src/r2.ts +50 -0
  129. package/src/selfsigned.d.ts +29 -0
  130. package/src/sites.tsx +357 -99
  131. package/src/tail/filters.ts +279 -0
  132. package/src/tail/index.ts +299 -0
  133. package/src/tail/printing.ts +67 -0
  134. package/src/update-check.ts +19 -0
  135. package/src/user/choose-account.tsx +69 -0
  136. package/src/user/env-vars.ts +46 -0
  137. package/src/user/generate-auth-url.ts +33 -0
  138. package/src/user/generate-random-state.ts +16 -0
  139. package/src/user/index.ts +3 -0
  140. package/src/user/user.tsx +1171 -0
  141. package/src/whoami.tsx +91 -0
  142. package/src/worker-namespace.ts +206 -0
  143. package/src/worker.ts +191 -0
  144. package/src/zones.ts +76 -0
  145. package/templates/checked-fetch.js +17 -0
  146. package/templates/gitignore +171 -0
  147. package/templates/new-worker-scheduled.js +17 -0
  148. package/templates/new-worker-scheduled.ts +32 -0
  149. package/templates/new-worker.js +15 -0
  150. package/templates/new-worker.ts +30 -0
  151. package/templates/no-op-worker.js +10 -0
  152. package/templates/pages-shim.ts +9 -0
  153. package/templates/pages-template-plugin.ts +155 -0
  154. package/templates/pages-template-worker.ts +161 -0
  155. package/templates/static-asset-facade.js +49 -0
  156. package/templates/tsconfig.json +105 -0
  157. package/wrangler-dist/cli.d.ts +327 -0
  158. package/wrangler-dist/cli.js +112594 -112465
  159. package/pages/functions/buildWorker.ts +0 -57
  160. package/pages/functions/filepath-routing.test.ts +0 -39
  161. package/pages/functions/filepath-routing.ts +0 -221
  162. package/pages/functions/identifiers.ts +0 -78
  163. package/pages/functions/routes.ts +0 -158
  164. package/pages/functions/template-worker.ts +0 -137
  165. package/src/__tests__/mock-cfetch.ts +0 -171
  166. package/src/__tests__/mock-dialogs.ts +0 -65
  167. package/src/__tests__/run-in-tmp.ts +0 -19
  168. package/src/__tests__/run-wrangler.ts +0 -32
  169. package/src/api/form_data.ts +0 -131
  170. package/src/api/inspect.ts +0 -430
  171. package/src/api/preview.ts +0 -128
  172. package/src/api/worker.ts +0 -155
  173. package/src/config.ts +0 -131
  174. package/src/kv.tsx +0 -267
  175. package/src/pages.tsx +0 -968
  176. package/src/tail.tsx +0 -73
  177. package/src/user.tsx +0 -1022
  178. package/static-asset-facade.js +0 -47
  179. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  180. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  181. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  182. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  183. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  184. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  185. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  186. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  187. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  188. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  189. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  190. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  191. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  192. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  193. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  194. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  195. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  196. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  197. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  198. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  199. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  200. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  201. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  202. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  203. package/vendor/wrangler-mime/LICENSE +0 -21
  204. package/vendor/wrangler-mime/Mime.js +0 -97
  205. package/vendor/wrangler-mime/README.md +0 -187
  206. package/vendor/wrangler-mime/cli.js +0 -46
  207. package/vendor/wrangler-mime/index.js +0 -4
  208. package/vendor/wrangler-mime/lite.js +0 -4
  209. package/vendor/wrangler-mime/package.json +0 -52
  210. package/vendor/wrangler-mime/types/other.js +0 -1
  211. package/vendor/wrangler-mime/types/standard.js +0 -1
  212. package/wrangler-dist/cli.js.map +0 -7
package/src/dev.tsx CHANGED
@@ -1,874 +1,593 @@
1
- import esbuild from "esbuild";
2
- import { readFile } from "fs/promises";
3
- import { existsSync } from "fs";
4
- import type { DirectoryResult } from "tmp-promise";
5
- import tmp from "tmp-promise";
6
- import type { CfPreviewToken } from "./api/preview";
7
- import { Box, Text, useApp, useInput } from "ink";
8
- import React, { useState, useEffect, useRef } from "react";
9
- import path from "path";
10
- import open from "open";
11
- import { DtInspector } from "./api/inspect";
12
- import type { CfModule } from "./api/worker";
13
- import { createWorker } from "./api/worker";
14
- import type { CfWorkerInit } from "./api/worker";
15
- import { spawn } from "child_process";
16
- import onExit from "signal-exit";
17
- import { syncAssets } from "./sites";
18
- import clipboardy from "clipboardy";
19
- import http from "node:http";
20
- import commandExists from "command-exists";
21
- import assert from "assert";
22
- import { getAPIToken } from "./user";
23
- import fetch from "node-fetch";
24
- import makeModuleCollector from "./module-collection";
25
- import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
26
- import { createHttpProxy } from "./proxy";
27
- import { execa } from "execa";
1
+ import path from "node:path";
28
2
  import { watch } from "chokidar";
29
-
30
- type CfScriptFormat = void | "modules" | "service-worker";
31
-
32
- export type DevProps = {
33
- name?: string;
34
- entry: string;
35
- port?: number;
36
- format: CfScriptFormat;
37
- accountId: void | string;
38
- initialMode: "local" | "remote";
39
- jsxFactory: void | string;
40
- jsxFragment: void | string;
41
- bindings: CfWorkerInit["bindings"];
42
- public: void | string;
43
- site: void | string;
44
- compatibilityDate: void | string;
45
- compatibilityFlags: void | string[];
46
- usageModel: void | "bundled" | "unbound";
47
- buildCommand: {
48
- command?: undefined | string;
49
- cwd?: undefined | string;
50
- watch_dir?: undefined | string;
51
- };
52
- };
53
-
54
- function Dev(props: DevProps): JSX.Element {
55
- if (props.public && props.format === "service-worker") {
56
- throw new Error(
57
- "You cannot use the service worker format with a `public` directory."
58
- );
59
- }
60
- const port = props.port || 8787;
61
- const apiToken = getAPIToken();
62
- const directory = useTmpDir();
63
-
64
- // if there isn't a build command, we just return the entry immediately
65
- // ideally there would be a conditional here, but the rules of hooks
66
- // kinda forbid that, so we thread the entry through useCustomBuild
67
- const entry = useCustomBuild(props.entry, props.buildCommand);
68
-
69
- const bundle = useEsbuild({
70
- entry,
71
- destination: directory,
72
- staticRoot: props.public,
73
- jsxFactory: props.jsxFactory,
74
- jsxFragment: props.jsxFragment,
75
- });
76
- if (bundle && bundle.type === "commonjs" && !props.format && props.public) {
77
- throw new Error(
78
- "You cannot use the service worker format with a `public` directory."
79
- );
80
- }
81
-
82
- // @ts-expect-error whack
83
- useDevtoolsRefresh(bundle?.id ?? 0);
84
-
85
- const toggles = useHotkeys(
86
- {
87
- local: props.initialMode === "local",
88
- tunnel: false,
89
- },
90
- port
91
- );
92
-
93
- useTunnel(toggles.tunnel);
94
-
95
- return (
96
- <>
97
- {toggles.local ? (
98
- <Local
99
- name={props.name}
100
- bundle={bundle}
101
- format={props.format}
102
- bindings={props.bindings}
103
- site={props.site}
104
- public={props.public}
105
- port={props.port}
106
- />
107
- ) : (
108
- <Remote
109
- name={props.name}
110
- bundle={bundle}
111
- format={props.format}
112
- accountId={props.accountId}
113
- apiToken={apiToken}
114
- bindings={props.bindings}
115
- site={props.site}
116
- public={props.public}
117
- port={props.port}
118
- compatibilityDate={props.compatibilityDate}
119
- compatibilityFlags={props.compatibilityFlags}
120
- usageModel={props.usageModel}
121
- />
122
- )}
123
- <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
124
- <Text>
125
- {`B to open a browser, D to open Devtools, S to ${
126
- toggles.tunnel ? "turn off" : "turn on"
127
- } (experimental) sharing, L to ${
128
- toggles.local ? "turn off" : "turn on"
129
- } local mode, X to exit`}
130
- </Text>
131
- </Box>
132
- </>
133
- );
134
- }
135
-
136
- function useDevtoolsRefresh(bundleId: number) {
137
- // TODO: this is a hack while we figure out
138
- // a better cleaner solution to get devtools to reconnect
139
- // without having to do a full refresh
140
- const ref = useRef();
141
- // @ts-expect-error whack
142
- ref.current = bundleId;
143
-
144
- useEffect(() => {
145
- const server = http.createServer((req, res) => {
146
- res.setHeader("Access-Control-Allow-Origin", "*");
147
- res.setHeader("Access-Control-Request-Method", "*");
148
- res.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET");
149
- res.setHeader("Access-Control-Allow-Headers", "*");
150
- if (req.method === "OPTIONS") {
151
- res.writeHead(200);
152
- res.end();
153
- return;
154
- }
155
- res.writeHead(200, { "Content-Type": "application/json" });
156
- res.end(JSON.stringify({ value: ref.current }));
157
- });
158
-
159
- server.listen(3142);
160
- return () => {
161
- server.close();
162
- };
163
- }, []);
164
- }
165
-
166
- function Remote(props: {
167
- name: void | string;
168
- bundle: EsbuildBundle | void;
169
- format: CfScriptFormat;
170
- public: void | string;
171
- site: void | string;
172
- port: number;
173
- accountId: void | string;
174
- apiToken: void | string;
175
- bindings: CfWorkerInit["bindings"];
176
- compatibilityDate: string | void;
177
- compatibilityFlags: void | string[];
178
- usageModel: void | "bundled" | "unbound";
179
- }) {
180
- assert(props.accountId, "accountId is required");
181
- assert(props.apiToken, "apiToken is required");
182
- const token = useWorker({
183
- name: props.name,
184
- bundle: props.bundle,
185
- format: props.format,
186
- modules: props.bundle ? props.bundle.modules : [],
187
- accountId: props.accountId,
188
- apiToken: props.apiToken,
189
- bindings: props.bindings,
190
- sitesFolder: props.site,
191
- port: props.port,
192
- compatibilityDate: props.compatibilityDate,
193
- compatibilityFlags: props.compatibilityFlags,
194
- usageModel: props.usageModel,
195
- });
196
-
197
- useProxy({ token, publicRoot: props.public, port: props.port });
198
-
199
- useInspector(token ? token.inspectorUrl.href : undefined);
200
- return null;
201
- }
202
- function Local(props: {
203
- name: void | string;
204
- bundle: EsbuildBundle | void;
205
- format: CfScriptFormat;
206
- bindings: CfWorkerInit["bindings"];
207
- public: void | string;
208
- site: void | string;
209
- port: number;
210
- }) {
211
- const { inspectorUrl } = useLocalWorker({
212
- name: props.name,
213
- bundle: props.bundle,
214
- format: props.format,
215
- bindings: props.bindings,
216
- port: props.port,
217
- });
218
- useInspector(inspectorUrl);
219
- return null;
220
- }
221
-
222
- function useLocalWorker(props: {
223
- name: void | string;
224
- bundle: EsbuildBundle | void;
225
- format: CfScriptFormat;
226
- bindings: CfWorkerInit["bindings"];
227
- port: number;
228
- }) {
229
- // TODO: pass vars via command line
230
- const { bundle, format, bindings, port } = props;
231
- const local = useRef<ReturnType<typeof spawn>>();
232
- const removeSignalExitListener = useRef<() => void>();
233
- const [inspectorUrl, setInspectorUrl] = useState<string | void>();
234
- useEffect(() => {
235
- async function startLocalWorker() {
236
- if (!bundle) return;
237
- if (format === "modules" && bundle.type === "commonjs") {
238
- console.error("⎔ Cannot use modules with a commonjs bundle.");
239
- // TODO: a much better error message here, with what to do next
240
- return;
241
- }
242
- if (format === "service-worker" && bundle.type !== "esm") {
243
- console.error("⎔ Cannot use service-worker with a esm bundle.");
244
- // TODO: a much better error message here, with what to do next
245
- return;
246
- }
247
-
248
- console.log("⎔ Starting a local server...");
249
- // TODO: just use execa for this
250
- local.current = spawn("node", [
251
- "--experimental-vm-modules",
252
- "--inspect",
253
- require.resolve("miniflare/cli"),
254
- bundle.path,
255
- "--watch",
256
- "--wrangler-config",
257
- path.join(__dirname, "../miniflare-config-stubs/wrangler.empty.toml"),
258
- "--env",
259
- path.join(__dirname, "../miniflare-config-stubs/.env.empty"),
260
- "--package",
261
- path.join(__dirname, "../miniflare-config-stubs/package.empty.json"),
262
- "--port",
263
- port.toString(),
264
- "--kv-persist",
265
- "--cache-persist",
266
- "--do-persist",
267
- ...Object.entries(bindings.vars || {}).flatMap(([key, value]) => {
268
- return ["--binding", `${key}=${value}`];
269
- }),
270
- ...(bindings.kv_namespaces || []).flatMap(({ binding }) => {
271
- return ["--kv", binding];
272
- }),
273
- ...(bindings.durable_objects?.bindings || []).flatMap(
274
- ({ name, class_name }) => {
275
- return ["--do", `${name}=${class_name}`];
276
- }
277
- ),
278
- "--modules",
279
- format ||
280
- (bundle.type === "esm" ? "modules" : "service-worker") === "modules"
281
- ? "true"
282
- : "false",
283
- ]);
284
- console.log(`⬣ Listening at http://localhost:${port}`);
285
-
286
- local.current.on("close", (code) => {
287
- if (code !== null) {
288
- console.log(`miniflare process exited with code ${code}`);
289
- }
290
- });
291
-
292
- local.current.stdout.on("data", (data: Buffer) => {
293
- console.log(`${data.toString()}`);
294
- });
295
-
296
- local.current.stderr.on("data", (data: Buffer) => {
297
- console.error(`${data.toString()}`);
298
- const matches =
299
- /Debugger listening on (ws:\/\/127\.0\.0\.1:9229\/[A-Za-z0-9-]+)/.exec(
300
- data.toString()
301
- );
302
- if (matches) {
303
- setInspectorUrl(matches[1]);
304
- }
305
- });
306
-
307
- local.current.on("exit", (code) => {
308
- if (code !== 0) {
309
- console.error(`miniflare process exited with code ${code}`);
310
- }
311
- });
312
-
313
- local.current.on("error", (error: Error) => {
314
- console.error(`miniflare process failed to spawn`);
315
- console.error(error);
316
- });
317
-
318
- removeSignalExitListener.current = onExit((_code, _signal) => {
319
- console.log("⎔ Shutting down local server.");
320
- local.current?.kill();
321
- local.current = undefined;
322
- });
323
- }
324
-
325
- startLocalWorker().catch((err) => {
326
- console.error("local worker:", err);
327
- });
328
-
329
- return () => {
330
- if (local.current) {
331
- console.log("⎔ Shutting down local server.");
332
- local.current?.kill();
333
- local.current = undefined;
334
- removeSignalExitListener.current && removeSignalExitListener.current();
335
- removeSignalExitListener.current = undefined;
336
- }
337
- };
338
- }, [
339
- bundle,
340
- format,
341
- port,
342
- bindings.durable_objects?.bindings,
343
- bindings.kv_namespaces,
344
- bindings.vars,
345
- ]);
346
- return { inspectorUrl };
3
+ import getPort from "get-port";
4
+ import { render } from "ink";
5
+ import React from "react";
6
+ import { fetch } from "undici";
7
+ import { findWranglerToml, printBindings, readConfig } from "./config";
8
+ import Dev from "./dev/dev";
9
+ import { getVarsForDev } from "./dev/dev-vars";
10
+
11
+ import { getEntry } from "./entry";
12
+ import { logger } from "./logger";
13
+ import * as metrics from "./metrics";
14
+ import { getAssetPaths, getSiteAssetPaths } from "./sites";
15
+ import { getAccountFromCache } from "./user";
16
+ import { getZoneIdFromHost, getZoneForRoute, getHostFromRoute } from "./zones";
17
+ import {
18
+ printWranglerBanner,
19
+ DEFAULT_LOCAL_PORT,
20
+ type ConfigPath,
21
+ getScriptName,
22
+ getDevCompatibilityDate,
23
+ getRules,
24
+ isLegacyEnv,
25
+ } from "./index";
26
+
27
+ import type { Config } from "./config";
28
+ import type { Route } from "./config/environment";
29
+ import type { EnablePagesAssetsServiceBindingOptions } from "./miniflare-cli";
30
+ import type { CfWorkerInit } from "./worker";
31
+ import type { RequestInit } from "undici";
32
+ import type { Argv, ArgumentsCamelCase } from "yargs";
33
+
34
+ interface DevArgs {
35
+ config?: string;
36
+ script?: string;
37
+ name?: string;
38
+ bundle?: boolean;
39
+ build?: boolean;
40
+ format?: string;
41
+ env?: string;
42
+ "compatibility-date"?: string;
43
+ "compatibility-flags"?: string[];
44
+ latest?: boolean;
45
+ ip?: string;
46
+ inspect?: boolean;
47
+ port?: number;
48
+ "inspector-port"?: number;
49
+ routes?: string[];
50
+ host?: string;
51
+ "local-protocol"?: "http" | "https";
52
+ "local-upstream"?: string | undefined;
53
+ "experimental-public"?: string;
54
+ public?: string;
55
+ assets?: string;
56
+ site?: string;
57
+ "site-include"?: string[];
58
+ "site-exclude"?: string[];
59
+ "upstream-protocol"?: "http" | "https";
60
+ "jsx-factory"?: string;
61
+ "jsx-fragment"?: string;
62
+ tsconfig?: string;
63
+ local?: boolean;
64
+ minify?: boolean;
65
+ "node-compat"?: boolean;
66
+ "experimental-enable-local-persistence"?: boolean;
67
+ "live-reload"?: boolean;
68
+ onReady?: () => void;
69
+ logLevel?: "none" | "error" | "log" | "warn" | "debug";
70
+ logPrefix?: string;
71
+ showInteractiveDevSession?: boolean;
347
72
  }
348
73
 
349
- function useTmpDir(): string | void {
350
- const [directory, setDirectory] = useState<DirectoryResult>();
351
- const handleError = useErrorHandler();
352
- useEffect(() => {
353
- let dir: DirectoryResult;
354
- async function create() {
355
- try {
356
- dir = await tmp.dir({ unsafeCleanup: true });
357
- setDirectory(dir);
358
- return;
359
- } catch (err) {
360
- console.error("failed to create tmp dir");
361
- throw err;
362
- }
363
- }
364
- create().catch((err) => {
365
- // we want to break here
366
- // we can't do much without a temp dir anyway
367
- handleError(err);
368
- });
369
- return () => {
370
- dir.cleanup().catch(() => {
371
- // extremely unlikely,
372
- // but it's 2021 after all
373
- console.error("failed to cleanup tmp dir");
374
- });
375
- };
376
- }, [handleError]);
377
- return directory?.path;
74
+ export function devOptions(yargs: Argv): Argv<DevArgs> {
75
+ return (
76
+ yargs
77
+ .positional("script", {
78
+ describe: "The path to an entry point for your worker",
79
+ type: "string",
80
+ })
81
+ .option("name", {
82
+ describe: "Name of the worker",
83
+ type: "string",
84
+ requiresArg: true,
85
+ })
86
+ // We want to have a --no-bundle flag, but yargs requires that
87
+ // we also have a --bundle flag (that it adds the --no to by itself)
88
+ // So we make a --bundle flag, but hide it, and then add a --no-bundle flag
89
+ // that's visible to the user but doesn't "do" anything.
90
+ .option("bundle", {
91
+ describe: "Run wrangler's compilation step before publishing",
92
+ type: "boolean",
93
+ hidden: true,
94
+ })
95
+ .option("no-bundle", {
96
+ describe: "Skip internal build steps and directly publish script",
97
+ type: "boolean",
98
+ default: false,
99
+ })
100
+ .option("format", {
101
+ choices: ["modules", "service-worker"] as const,
102
+ describe: "Choose an entry type",
103
+ deprecated: true,
104
+ })
105
+ .option("env", {
106
+ describe: "Perform on a specific environment",
107
+ type: "string",
108
+ requiresArg: true,
109
+ alias: "e",
110
+ })
111
+ .option("compatibility-date", {
112
+ describe: "Date to use for compatibility checks",
113
+ type: "string",
114
+ requiresArg: true,
115
+ })
116
+ .option("compatibility-flags", {
117
+ describe: "Flags to use for compatibility checks",
118
+ alias: "compatibility-flag",
119
+ type: "string",
120
+ requiresArg: true,
121
+ array: true,
122
+ })
123
+ .option("latest", {
124
+ describe: "Use the latest version of the worker runtime",
125
+ type: "boolean",
126
+ default: true,
127
+ })
128
+ .option("ip", {
129
+ describe: "IP address to listen on, defaults to `localhost`",
130
+ type: "string",
131
+ requiresArg: true,
132
+ })
133
+ .option("port", {
134
+ describe: "Port to listen on",
135
+ type: "number",
136
+ })
137
+ .option("inspector-port", {
138
+ describe: "Port for devtools to connect to",
139
+ type: "number",
140
+ })
141
+ .option("routes", {
142
+ describe: "Routes to upload",
143
+ alias: "route",
144
+ type: "string",
145
+ requiresArg: true,
146
+ array: true,
147
+ })
148
+ .option("host", {
149
+ type: "string",
150
+ requiresArg: true,
151
+ describe:
152
+ "Host to forward requests to, defaults to the zone of project",
153
+ })
154
+ .option("local-protocol", {
155
+ describe: "Protocol to listen to requests on, defaults to http.",
156
+ choices: ["http", "https"] as const,
157
+ })
158
+ .options("local-upstream", {
159
+ type: "string",
160
+ describe:
161
+ "Host to act as origin in local mode, defaults to dev.host or route",
162
+ })
163
+ .option("experimental-public", {
164
+ describe: "Static assets to be served",
165
+ type: "string",
166
+ requiresArg: true,
167
+ deprecated: true,
168
+ hidden: true,
169
+ })
170
+ .option("assets", {
171
+ describe: "Static assets to be served",
172
+ type: "string",
173
+ requiresArg: true,
174
+ })
175
+ .option("site", {
176
+ describe: "Root folder of static assets for Workers Sites",
177
+ type: "string",
178
+ requiresArg: true,
179
+ })
180
+ .option("site-include", {
181
+ describe:
182
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
183
+ type: "string",
184
+ requiresArg: true,
185
+ array: true,
186
+ })
187
+ .option("site-exclude", {
188
+ describe:
189
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
190
+ type: "string",
191
+ requiresArg: true,
192
+ array: true,
193
+ })
194
+ .option("upstream-protocol", {
195
+ describe: "Protocol to forward requests to host on, defaults to https.",
196
+ choices: ["http", "https"] as const,
197
+ })
198
+ .option("jsx-factory", {
199
+ describe: "The function that is called for each JSX element",
200
+ type: "string",
201
+ requiresArg: true,
202
+ })
203
+ .option("jsx-fragment", {
204
+ describe: "The function that is called for each JSX fragment",
205
+ type: "string",
206
+ requiresArg: true,
207
+ })
208
+ .option("tsconfig", {
209
+ describe: "Path to a custom tsconfig.json file",
210
+ type: "string",
211
+ requiresArg: true,
212
+ })
213
+ .option("local", {
214
+ alias: "l",
215
+ describe: "Run on my machine",
216
+ type: "boolean",
217
+ default: false, // I bet this will a point of contention. We'll revisit it.
218
+ })
219
+ .option("minify", {
220
+ describe: "Minify the script",
221
+ type: "boolean",
222
+ })
223
+ .option("node-compat", {
224
+ describe: "Enable node.js compatibility",
225
+ type: "boolean",
226
+ })
227
+ .option("experimental-enable-local-persistence", {
228
+ describe: "Enable persistence for this session (only for local mode)",
229
+ type: "boolean",
230
+ })
231
+ .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",
235
+ type: "boolean",
236
+ })
237
+ .option("inspect", {
238
+ describe: "Enable dev tools",
239
+ type: "boolean",
240
+ deprecated: true,
241
+ })
242
+ .option("legacy-env", {
243
+ type: "boolean",
244
+ describe: "Use legacy environments",
245
+ hidden: true,
246
+ })
247
+ );
378
248
  }
379
249
 
380
- function useCustomBuild(
381
- expectedEntry: string,
382
- props: {
383
- command?: undefined | string;
384
- cwd?: undefined | string;
385
- watch_dir?: undefined | string;
386
- }
387
- ): void | string {
388
- const [entry, setEntry] = useState<string | void>(
389
- // if there's no build command, just return the expected entry
390
- props.command ? null : expectedEntry
391
- );
392
- const { command, cwd, watch_dir } = props;
393
- useEffect(() => {
394
- if (!command) return;
395
- let cmd, interval;
396
- console.log("running:", command);
397
- const commandPieces = command.split(" ");
398
- cmd = execa(commandPieces[0], commandPieces.slice(1), {
399
- ...(cwd && { cwd }),
400
- stderr: "inherit",
401
- stdout: "inherit",
402
- });
403
- if (watch_dir) {
404
- watch(watch_dir, { persistent: true, ignoreInitial: true }).on(
405
- "all",
406
- (_event, _path) => {
407
- console.log(`The file ${path} changed, restarting build...`);
408
- cmd.kill();
409
- cmd = execa(commandPieces[0], commandPieces.slice(1), {
410
- ...(cwd && { cwd }),
411
- stderr: "inherit",
412
- stdout: "inherit",
413
- });
414
- }
415
- );
416
- }
417
-
418
- // check every so often whether `expectedEntry` exists
419
- // if it does, we're done
420
- const startedAt = Date.now();
421
- interval = setInterval(() => {
422
- if (existsSync(expectedEntry)) {
423
- clearInterval(interval);
424
- setEntry(expectedEntry);
425
- } else {
426
- const elapsed = Date.now() - startedAt;
427
- // timeout after 30 seconds of waiting
428
- if (elapsed > 1000 * 60 * 30) {
429
- console.error("⎔ Build timed out.");
430
- clearInterval(interval);
431
- cmd.kill();
432
- }
433
- }
434
- }, 200);
435
- // TODO: we could probably timeout here after a while
436
-
437
- return () => {
438
- if (cmd) {
439
- cmd.kill();
440
- cmd = undefined;
441
- }
442
- clearInterval(interval);
443
- interval = undefined;
444
- };
445
- }, [command, cwd, expectedEntry, watch_dir]);
446
- return entry;
250
+ export async function devHandler(args: ArgumentsCamelCase<DevArgs>) {
251
+ let watcher;
252
+ try {
253
+ const devInstance = await startDev(args);
254
+ watcher = devInstance.watcher;
255
+ const { waitUntilExit } = devInstance.devReactElement;
256
+ await waitUntilExit();
257
+ } finally {
258
+ await watcher?.close();
259
+ }
447
260
  }
448
261
 
449
- type EsbuildBundle = {
450
- id: number;
451
- path: string;
452
- entry: string;
453
- type: "esm" | "commonjs";
454
- exports: string[];
455
- modules: CfModule[];
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.
265
+ vars?: {
266
+ [key: string]: unknown;
267
+ };
268
+ kv?: {
269
+ binding: string;
270
+ id: string;
271
+ preview_id?: string;
272
+ }[];
273
+ durableObjects?: {
274
+ name: string;
275
+ class_name: string;
276
+ script_name?: string | undefined;
277
+ environment?: string | undefined;
278
+ }[];
279
+ forceLocal?: boolean;
280
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
456
281
  };
457
282
 
458
- function useEsbuild(props: {
459
- entry: void | string;
460
- destination: string | void;
461
- staticRoot: void | string;
462
- jsxFactory: string | void;
463
- jsxFragment: string | void;
464
- }): EsbuildBundle | void {
465
- const { entry, destination, staticRoot, jsxFactory, jsxFragment } = props;
466
- const [bundle, setBundle] = useState<EsbuildBundle>();
467
- useEffect(() => {
468
- let result: esbuild.BuildResult;
469
- async function build() {
470
- if (!destination || !entry) return;
471
- const moduleCollector = makeModuleCollector();
472
- result = await esbuild.build({
473
- entryPoints: [entry],
474
- bundle: true,
475
- outdir: destination,
476
- metafile: true,
477
- format: "esm",
478
- sourcemap: true,
479
- loader: {
480
- ".js": "jsx",
481
- },
482
- ...(jsxFactory && { jsxFactory }),
483
- ...(jsxFragment && { jsxFragment }),
484
- external: ["__STATIC_CONTENT_MANIFEST"],
485
- conditions: ["worker", "browser"],
486
- plugins: [moduleCollector.plugin],
487
- // TODO: import.meta.url
488
- watch: {
489
- async onRebuild(error) {
490
- if (error) console.error("watch build failed:", error);
491
- else {
492
- // nothing really changes here, so let's increment the id
493
- // to change the return object's identity
494
- setBundle((previousBundle) => ({
495
- ...previousBundle,
496
- id: previousBundle.id + 1,
497
- }));
498
- }
499
- },
500
- },
501
- });
502
-
503
- const chunks = Object.entries(result.metafile.outputs).find(
504
- ([_path, { entryPoint }]) => entryPoint === entry
505
- ); // assumedly only one entry point
506
-
507
- setBundle({
508
- id: 0,
509
- entry,
510
- path: chunks[0],
511
- type: chunks[1].exports.length > 0 ? "esm" : "commonjs",
512
- exports: chunks[1].exports,
513
- modules: moduleCollector.modules,
514
- });
515
- }
516
- build().catch((_err) => {
517
- // esbuild already logs errors to stderr
518
- // and we don't want to end the process
519
- // on build errors anyway
520
- // so this is a no-op error handler
521
- });
522
- return () => {
523
- result?.stop();
524
- };
525
- }, [entry, destination, staticRoot, jsxFactory, jsxFragment]);
526
- return bundle;
527
- }
528
-
529
- function useWorker(props: {
530
- name: void | string;
531
- bundle: EsbuildBundle | void;
532
- format: CfScriptFormat;
533
- modules: CfModule[];
534
- accountId: string;
535
- apiToken: string;
536
- bindings: CfWorkerInit["bindings"];
537
- sitesFolder: void | string;
538
- port: number;
539
- compatibilityDate: string | void;
540
- compatibilityFlags: string[] | void;
541
- usageModel: void | "bundled" | "unbound";
542
- }): CfPreviewToken | void {
543
- const {
544
- name,
545
- bundle,
546
- format,
547
- modules,
548
- accountId,
549
- apiToken,
550
- bindings,
551
- sitesFolder,
552
- compatibilityDate,
553
- compatibilityFlags,
554
- usageModel,
555
- port,
556
- } = props;
557
- const [token, setToken] = useState<CfPreviewToken>();
558
-
559
- // This is the most reliable way to detect whether
560
- // something's "happened" in our system; We make a ref and
561
- // mark it once we log our initial message. Refs are vars!
562
- const startedRef = useRef(false);
563
-
564
- useEffect(() => {
565
- async function start() {
566
- if (!bundle) return;
567
- if (format === "modules" && bundle.type === "commonjs") {
568
- console.error("⎔ Cannot use modules with a commonjs bundle.");
569
- // TODO: a much better error message here, with what to do next
570
- return;
571
- }
572
- if (format === "service-worker" && bundle.type !== "esm") {
573
- console.error("⎔ Cannot use service-worker with a esm bundle.");
574
- // TODO: a much better error message here, with what to do next
575
- return;
576
- }
577
-
578
- if (!startedRef.current) {
579
- console.log("⎔ Starting server...");
580
- startedRef.current = true;
581
- } else {
582
- console.log("⎔ Detected changes, restarting server...");
583
- }
584
-
585
- const assets = sitesFolder
586
- ? await syncAssets(
587
- accountId,
588
- path.basename(bundle.path),
589
- sitesFolder,
590
- true,
591
- undefined // TODO: env
592
- )
593
- : {
594
- manifest: undefined,
595
- namespace: undefined,
596
- }; // TODO: cancellable?
597
-
598
- const content = await readFile(bundle.path, "utf-8");
599
- const init: CfWorkerInit = {
600
- name,
601
- main: {
602
- name: path.basename(bundle.path),
603
- type: format || bundle.type === "esm" ? "esm" : "commonjs",
604
- content,
605
- },
606
- modules: modules.concat(
607
- assets.manifest
608
- ? {
609
- name: "__STATIC_CONTENT_MANIFEST",
610
- content: JSON.stringify(assets.manifest),
611
- type: "text",
612
- }
613
- : []
614
- ),
615
- bindings: {
616
- ...bindings,
617
- kv_namespaces: (bindings.kv_namespaces || []).concat(
618
- assets.namespace
619
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
620
- : []
621
- ),
622
- },
623
- migrations: undefined, // no migrations in dev
624
- compatibility_date: compatibilityDate,
625
- compatibility_flags: compatibilityFlags,
626
- usage_model: usageModel,
627
- };
628
- setToken(
629
- await createWorker(init, {
630
- accountId,
631
- apiToken,
632
- })
633
- );
634
- }
635
- start().catch((err) => {
636
- // we want to log the error, but not end the process
637
- // since it could recover after the developer fixes whatever's wrong
638
- console.error("remote worker:", err);
639
- });
640
- }, [
641
- name,
642
- bundle,
643
- format,
644
- accountId,
645
- apiToken,
646
- port,
647
- sitesFolder,
648
- compatibilityDate,
649
- compatibilityFlags,
650
- usageModel,
651
- bindings,
652
- modules,
653
- ]);
654
- return token;
655
- }
656
-
657
- function useProxy({
658
- token,
659
- publicRoot,
660
- port,
661
- }: {
662
- token: CfPreviewToken | void;
663
- publicRoot: void | string;
664
- port: number;
665
- }) {
666
- useEffect(() => {
667
- if (!token) return;
668
- // TODO(soon): since headers are added in callbacks, the server
669
- // does not need to restart when changes are made.
670
- const host = token.host;
671
- const proxy = createHttpProxy({
672
- host,
673
- assetPath: typeof publicRoot === "string" ? publicRoot : null,
674
- onRequest: (headers) => {
675
- headers["cf-workers-preview-token"] = token.value;
676
- },
677
- onResponse: (headers) => {
678
- for (const [name, value] of Object.entries(headers)) {
679
- // Rewrite the remote host to the local host.
680
- if (typeof value === "string" && value.includes(host)) {
681
- headers[name] = value
682
- .replaceAll(`https://${host}`, `http://localhost:${port}`)
683
- .replaceAll(host, `localhost:${port}`);
684
- }
685
- }
686
- },
687
- });
688
-
689
- console.log(`⬣ Listening at http://localhost:${port}`);
690
-
691
- const server = proxy.listen(port);
692
-
693
- // TODO(soon): refactor logging format into its own function
694
- proxy.on("request", function (req, res) {
695
- // log all requests
696
- console.log(
697
- new Date().toLocaleTimeString(),
698
- req.method,
699
- req.url,
700
- res.statusCode
701
- );
702
- });
703
- proxy.on("upgrade", (req) => {
704
- console.log(
705
- new Date().toLocaleTimeString(),
706
- req.method,
707
- req.url,
708
- 101,
709
- "(WebSocket)"
710
- );
711
- });
712
- proxy.on("error", (err) => {
713
- console.error(new Date().toLocaleTimeString(), err);
714
- });
715
-
716
- return () => {
717
- proxy.close();
718
- server.close();
719
- };
720
- }, [token, publicRoot, port]);
721
- }
722
-
723
- function useInspector(inspectorUrl: string | void) {
724
- useEffect(() => {
725
- if (!inspectorUrl) return;
726
-
727
- const inspector = new DtInspector(inspectorUrl);
728
- const abortController = inspector.proxyTo(9229);
729
- return () => {
730
- inspector.close();
731
- abortController.abort();
732
- };
733
- }, [inspectorUrl]);
734
- }
735
-
736
- function sleep(period: number) {
737
- return new Promise((resolve) => setTimeout(resolve, period));
738
- }
739
- const SLEEP_DURATION = 2000;
740
- // really need a first class api for this
741
- const hostNameRegex = /userHostname="(.*)"/g;
742
- async function findTunnelHostname() {
743
- let hostName: string;
744
- while (!hostName) {
745
- try {
746
- const resp = await fetch("http://localhost:8789/metrics");
747
- const data = await resp.text();
748
- const matches = Array.from(data.matchAll(hostNameRegex));
749
- hostName = matches[0][1];
750
- } catch (err) {
751
- await sleep(SLEEP_DURATION);
752
- }
753
- }
754
- return hostName;
755
- }
756
-
757
- function useTunnel(toggle: boolean) {
758
- const tunnel = useRef<ReturnType<typeof spawn>>();
759
- const removeSignalExitListener = useRef<() => void>();
760
- // TODO: test if cloudflared is available, if not
761
- // point them to a url where they can get docs to install it
762
- useEffect(() => {
763
- async function startTunnel() {
764
- if (toggle) {
765
- try {
766
- await commandExists("cloudflared");
767
- } catch (e) {
768
- console.error(
769
- "To share your worker on the internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
770
- );
771
- return;
772
- }
773
- console.log("⎔ Starting a tunnel...");
774
- tunnel.current = spawn("cloudflared", [
775
- "tunnel",
776
- "--url",
777
- "http://localhost:8787",
778
- "--metrics",
779
- "localhost:8789",
780
- ]);
781
-
782
- tunnel.current.on("close", (code) => {
783
- if (code !== 0) {
784
- console.log(`Tunnel process exited with code ${code}`);
785
- }
786
- });
787
-
788
- removeSignalExitListener.current = onExit((_code, _signal) => {
789
- console.log("⎔ Shutting down local tunnel.");
790
- tunnel.current?.kill();
791
- tunnel.current = undefined;
792
- });
793
-
794
- const hostName = await findTunnelHostname();
795
- await clipboardy.write(hostName);
796
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
797
- }
798
- }
799
-
800
- startTunnel().catch((err) => {
801
- console.error("tunnel:", err);
802
- });
803
-
804
- return () => {
805
- if (tunnel.current) {
806
- console.log("⎔ Shutting down tunnel.");
807
- tunnel.current?.kill();
808
- tunnel.current = undefined;
809
- removeSignalExitListener.current && removeSignalExitListener.current();
810
- removeSignalExitListener.current = undefined;
811
- }
812
- };
813
- }, [toggle]);
283
+ export async function startDev(args: StartDevOptions) {
284
+ let watcher: ReturnType<typeof watch> | undefined;
285
+ let rerender: (node: React.ReactNode) => void | undefined;
286
+ try {
287
+ 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;
290
+ }
291
+ await printWranglerBanner();
292
+
293
+ const configPath =
294
+ (args.config as ConfigPath) ||
295
+ ((args.script &&
296
+ findWranglerToml(path.dirname(args.script))) as ConfigPath);
297
+ 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
+
304
+ if (config.configPath) {
305
+ watcher = watch(config.configPath, {
306
+ persistent: true,
307
+ }).on("change", async (_event) => {
308
+ // TODO: Do we need to handle different `_event` types differently?
309
+ // e.g. what if the file is deleted, or added?
310
+ config = readConfig(configPath, args);
311
+ if (config.configPath) {
312
+ logger.log(`${path.basename(config.configPath)} changed...`);
313
+ rerender(await getDevReactElement(config));
314
+ }
315
+ });
316
+ }
317
+
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;
383
+
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);
480
+
481
+ // eslint-disable-next-line no-inner-declarations
482
+ 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
+ );
510
+
511
+ return (
512
+ <Dev
513
+ name={getScriptName({ name: args.name, env: args.env }, config)}
514
+ noBundle={!(args.bundle ?? !config.no_bundle)}
515
+ entry={entry}
516
+ env={args.env}
517
+ zone={zoneId}
518
+ host={host}
519
+ routes={routes}
520
+ rules={getRules(config)}
521
+ legacyEnv={isLegacyEnv(config)}
522
+ minify={args.minify ?? config.minify}
523
+ 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}
530
+ upstreamProtocol={upstreamProtocol}
531
+ localProtocol={args.localProtocol || config.dev.local_protocol}
532
+ localUpstream={args["local-upstream"] || host}
533
+ enableLocalPersistence={
534
+ args["experimental-enable-local-persistence"] || false
535
+ }
536
+ liveReload={args.liveReload || false}
537
+ accountId={config.account_id || getAccountFromCache()?.id}
538
+ 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)}
543
+ compatibilityDate={getDevCompatibilityDate(
544
+ config,
545
+ args["compatibility-date"]
546
+ )}
547
+ compatibilityFlags={
548
+ args["compatibility-flags"] || config.compatibility_flags
549
+ }
550
+ usageModel={config.usage_model}
551
+ bindings={bindings}
552
+ crons={config.triggers.crons}
553
+ logLevel={args.logLevel}
554
+ logPrefix={args.logPrefix}
555
+ onReady={args.onReady}
556
+ inspect={args.inspect ?? true}
557
+ showInteractiveDevSession={args.showInteractiveDevSession}
558
+ forceLocal={args.forceLocal}
559
+ enablePagesAssetsServiceBinding={args.enablePagesAssetsServiceBinding}
560
+ />
561
+ );
562
+ }
563
+ const devReactElement = render(await getDevReactElement(config));
564
+ rerender = devReactElement.rerender;
565
+ return {
566
+ devReactElement,
567
+ watcher,
568
+ stop: async () => {
569
+ devReactElement.unmount();
570
+ await watcher?.close();
571
+ },
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
+ };
580
+ } finally {
581
+ await watcher?.close();
582
+ }
814
583
  }
815
584
 
816
- type useHotkeysInitialState = {
817
- local: boolean;
818
- tunnel: boolean;
819
- };
820
- function useHotkeys(initial: useHotkeysInitialState, port: number) {
821
- // UGH, we should put port in context instead
822
- const [toggles, setToggles] = useState(initial);
823
- useInput(
824
- async (
825
- input,
826
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
827
- key
828
- ) => {
829
- switch (input) {
830
- case "b": // open browser
831
- await open(`http://localhost:${port}/`);
832
- break;
833
- case "d": // toggle inspector
834
- await open(
835
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:9229/ws`
836
- );
837
- break;
838
- case "s": // toggle tunnel
839
- setToggles((previousToggles) => ({
840
- ...previousToggles,
841
- tunnel: !previousToggles.tunnel,
842
- }));
843
- break;
844
- case "l": // toggle local
845
- setToggles((previousToggles) => ({
846
- ...previousToggles,
847
- local: !previousToggles.local,
848
- }));
849
- break;
850
- case "q": // shut down
851
- case "x": // shut down
852
- process.exit(0);
853
- break;
854
- default:
855
- // nothing?
856
- break;
857
- }
858
- }
859
- );
860
- return toggles;
861
- }
862
-
863
- function ErrorFallback(props: { error: Error }) {
864
- const { exit } = useApp();
865
- useEffect(() => exit(new Error()));
866
- return (
867
- <>
868
- <Text>Something went wrong:</Text>
869
- <Text>{props.error.message}</Text>
870
- </>
871
- );
585
+ /**
586
+ * Avoiding calling `getPort()` multiple times by memoizing the first result.
587
+ */
588
+ function memoizeGetPort(defaultPort: number) {
589
+ let portValue: number;
590
+ return async () => {
591
+ return portValue || (portValue = await getPort({ port: defaultPort }));
592
+ };
872
593
  }
873
-
874
- export default withErrorBoundary(Dev, { FallbackComponent: ErrorFallback });