wrangler 0.0.0-fe5dcfd → 0.0.0-ff2e7cb

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