wrangler 0.0.0-e9ab55a → 0.0.0-e9e9872

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