wrangler 0.0.0-e043479 → 0.0.0-e09abbc

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