wrangler 0.0.0-e88a54e → 0.0.0-e8df68ee

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 (167) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +46 -15
  3. package/bin/wrangler.js +118 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +194 -143
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +23 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +172 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +127 -0
  17. package/templates/middleware/loader-sw.ts +228 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-d1-beta.ts +244 -0
  20. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  21. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  22. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +15 -0
  25. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  26. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +3 -3
  30. package/templates/new-worker.ts +22 -4
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +31 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +105 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/cli.d.ts +1726 -0
  41. package/wrangler-dist/cli.js +134048 -126481
  42. package/wrangler-dist/wasm-sync.wasm +0 -0
  43. package/import_meta_url.js +0 -3
  44. package/miniflare-config-stubs/.env.empty +0 -0
  45. package/miniflare-config-stubs/package.empty.json +0 -1
  46. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  47. package/miniflare-dist/index.mjs +0 -79
  48. package/miniflare-dist/index.mjs.map +0 -7
  49. package/pages/functions/buildWorker.ts +0 -62
  50. package/pages/functions/filepath-routing.test.ts +0 -223
  51. package/pages/functions/filepath-routing.ts +0 -181
  52. package/pages/functions/identifiers.ts +0 -78
  53. package/pages/functions/routes.ts +0 -151
  54. package/pages/functions/template-worker.ts +0 -130
  55. package/src/__tests__/configuration.test.ts +0 -2796
  56. package/src/__tests__/dev.test.tsx +0 -496
  57. package/src/__tests__/dev2.test.tsx +0 -154
  58. package/src/__tests__/guess-worker-format.test.ts +0 -58
  59. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  60. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  61. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  62. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  63. package/src/__tests__/helpers/mock-bin.ts +0 -36
  64. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  65. package/src/__tests__/helpers/mock-console.ts +0 -70
  66. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  67. package/src/__tests__/helpers/mock-kv.ts +0 -33
  68. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  69. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  70. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  71. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  72. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  73. package/src/__tests__/https-options.test.ts +0 -127
  74. package/src/__tests__/index.test.ts +0 -991
  75. package/src/__tests__/jest.setup.ts +0 -69
  76. package/src/__tests__/kv.test.ts +0 -1382
  77. package/src/__tests__/logout.test.ts +0 -52
  78. package/src/__tests__/package-manager.test.ts +0 -206
  79. package/src/__tests__/pages.test.ts +0 -44
  80. package/src/__tests__/parse.test.ts +0 -322
  81. package/src/__tests__/publish.test.ts +0 -2704
  82. package/src/__tests__/r2.test.ts +0 -198
  83. package/src/__tests__/route.test.ts +0 -45
  84. package/src/__tests__/secret.test.ts +0 -425
  85. package/src/__tests__/sentry.test.ts +0 -146
  86. package/src/__tests__/tail.test.ts +0 -564
  87. package/src/__tests__/whoami.test.tsx +0 -100
  88. package/src/bundle.ts +0 -142
  89. package/src/cfetch/index.ts +0 -104
  90. package/src/cfetch/internal.ts +0 -139
  91. package/src/cli.ts +0 -19
  92. package/src/config/README.md +0 -107
  93. package/src/config/config.ts +0 -218
  94. package/src/config/diagnostics.ts +0 -80
  95. package/src/config/environment.ts +0 -366
  96. package/src/config/index.ts +0 -62
  97. package/src/config/validation-helpers.ts +0 -486
  98. package/src/config/validation.ts +0 -1090
  99. package/src/create-worker-preview.ts +0 -166
  100. package/src/create-worker-upload-form.ts +0 -217
  101. package/src/dev/dev.tsx +0 -364
  102. package/src/dev/local.tsx +0 -232
  103. package/src/dev/remote.tsx +0 -203
  104. package/src/dev/use-esbuild.ts +0 -100
  105. package/src/dialogs.tsx +0 -77
  106. package/src/entry.ts +0 -208
  107. package/src/environment-variables.ts +0 -33
  108. package/src/https-options.ts +0 -122
  109. package/src/index.tsx +0 -2373
  110. package/src/inspect.ts +0 -617
  111. package/src/kv.ts +0 -319
  112. package/src/miniflare-cli/README.md +0 -30
  113. package/src/miniflare-cli/enum-keys.ts +0 -17
  114. package/src/miniflare-cli/index.ts +0 -37
  115. package/src/module-collection.ts +0 -258
  116. package/src/open-in-browser.ts +0 -25
  117. package/src/package-manager.ts +0 -126
  118. package/src/pages.tsx +0 -1047
  119. package/src/parse.ts +0 -183
  120. package/src/paths.ts +0 -26
  121. package/src/proxy.ts +0 -440
  122. package/src/publish.ts +0 -347
  123. package/src/r2.ts +0 -50
  124. package/src/reporting.ts +0 -131
  125. package/src/selfsigned.d.ts +0 -29
  126. package/src/sites.tsx +0 -280
  127. package/src/tail/filters.ts +0 -279
  128. package/src/tail/index.ts +0 -299
  129. package/src/tail/printing.ts +0 -62
  130. package/src/user.tsx +0 -1118
  131. package/src/whoami.tsx +0 -69
  132. package/src/worker.ts +0 -163
  133. package/templates/static-asset-facade.js +0 -47
  134. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  135. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  136. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  137. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  138. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  139. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  140. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  141. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  142. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  143. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  144. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  145. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  146. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  147. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  148. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  149. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  150. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  151. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  152. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  153. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  154. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  155. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  156. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  157. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  158. package/vendor/wrangler-mime/LICENSE +0 -21
  159. package/vendor/wrangler-mime/Mime.js +0 -97
  160. package/vendor/wrangler-mime/README.md +0 -187
  161. package/vendor/wrangler-mime/cli.js +0 -46
  162. package/vendor/wrangler-mime/index.js +0 -4
  163. package/vendor/wrangler-mime/lite.js +0 -4
  164. package/vendor/wrangler-mime/package.json +0 -52
  165. package/vendor/wrangler-mime/types/other.js +0 -1
  166. package/vendor/wrangler-mime/types/standard.js +0 -1
  167. package/wrangler-dist/cli.js.map +0 -7
package/src/dev/dev.tsx DELETED
@@ -1,364 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { watch } from "chokidar";
3
- import clipboardy from "clipboardy";
4
- import commandExists from "command-exists";
5
- import { Box, Text, useApp, useInput } from "ink";
6
- import React, { useState, useEffect, useRef } from "react";
7
- import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
8
- import onExit from "signal-exit";
9
- import tmp from "tmp-promise";
10
- import { fetch } from "undici";
11
- import { runCustomBuild } from "../entry";
12
- import openInBrowser from "../open-in-browser";
13
- import { reportError } from "../reporting";
14
- import { getAPIToken } from "../user";
15
- import { Local } from "./local";
16
- import { Remote } from "./remote";
17
- import { useEsbuild } from "./use-esbuild";
18
- import type { Config } from "../config";
19
- import type { Entry } from "../entry";
20
- import type { AssetPaths } from "../sites";
21
- import type { CfWorkerInit } from "../worker";
22
-
23
- export type DevProps = {
24
- name?: string;
25
- entry: Entry;
26
- port?: number;
27
- ip: string;
28
- inspectorPort: number;
29
- rules: Config["rules"];
30
- accountId: undefined | string;
31
- initialMode: "local" | "remote";
32
- jsxFactory: undefined | string;
33
- jsxFragment: undefined | string;
34
- upstreamProtocol: "https" | "http";
35
- localProtocol: "https" | "http";
36
- enableLocalPersistence: boolean;
37
- bindings: CfWorkerInit["bindings"];
38
- public: undefined | string;
39
- assetPaths: undefined | AssetPaths;
40
- compatibilityDate: undefined | string;
41
- compatibilityFlags: undefined | string[];
42
- usageModel: undefined | "bundled" | "unbound";
43
- buildCommand: {
44
- command?: undefined | string;
45
- cwd?: undefined | string;
46
- watch_dir?: undefined | string;
47
- };
48
- env: string | undefined;
49
- legacyEnv: boolean;
50
- zone:
51
- | {
52
- id: string;
53
- host: string;
54
- }
55
- | undefined;
56
- };
57
-
58
- export function DevImplementation(props: DevProps): JSX.Element {
59
- const port = props.port ?? 8787;
60
- const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined;
61
- const directory = useTmpDir();
62
-
63
- useCustomBuild(props.entry, props.buildCommand);
64
-
65
- if (props.public && props.entry.format === "service-worker") {
66
- throw new Error(
67
- "You cannot use the service worker format with a `public` directory."
68
- );
69
- }
70
-
71
- if (props.bindings.wasm_modules && props.entry.format === "modules") {
72
- throw new Error(
73
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
74
- );
75
- }
76
-
77
- if (props.bindings.text_blobs && props.entry.format === "modules") {
78
- throw new Error(
79
- "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"
80
- );
81
- }
82
-
83
- const bundle = useEsbuild({
84
- entry: props.entry,
85
- destination: directory,
86
- staticRoot: props.public,
87
- jsxFactory: props.jsxFactory,
88
- rules: props.rules,
89
- jsxFragment: props.jsxFragment,
90
- serveAssetsFromWorker: !!props.public,
91
- });
92
-
93
- const toggles = useHotkeys(
94
- {
95
- local: props.initialMode === "local",
96
- tunnel: false,
97
- },
98
- port,
99
- props.ip,
100
- props.inspectorPort,
101
- props.localProtocol
102
- );
103
-
104
- useTunnel(toggles.tunnel);
105
-
106
- return (
107
- <>
108
- {toggles.local ? (
109
- <Local
110
- name={props.name}
111
- bundle={bundle}
112
- format={props.entry.format}
113
- compatibilityDate={props.compatibilityDate}
114
- compatibilityFlags={props.compatibilityFlags}
115
- bindings={props.bindings}
116
- assetPaths={props.assetPaths}
117
- public={props.public}
118
- port={port}
119
- ip={props.ip}
120
- rules={props.rules}
121
- inspectorPort={props.inspectorPort}
122
- enableLocalPersistence={props.enableLocalPersistence}
123
- />
124
- ) : (
125
- <Remote
126
- name={props.name}
127
- bundle={bundle}
128
- format={props.entry.format}
129
- accountId={props.accountId}
130
- apiToken={apiToken}
131
- bindings={props.bindings}
132
- assetPaths={props.assetPaths}
133
- public={props.public}
134
- port={port}
135
- ip={props.ip}
136
- localProtocol={props.localProtocol}
137
- inspectorPort={props.inspectorPort}
138
- compatibilityDate={props.compatibilityDate}
139
- compatibilityFlags={props.compatibilityFlags}
140
- usageModel={props.usageModel}
141
- env={props.env}
142
- legacyEnv={props.legacyEnv}
143
- zone={props.zone}
144
- />
145
- )}
146
- <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
147
- <Text>
148
- {`B to open a browser, D to open Devtools, L to ${
149
- toggles.local ? "turn off" : "turn on"
150
- } local mode, X to exit`}
151
- </Text>
152
- </Box>
153
- </>
154
- );
155
- }
156
-
157
- export interface DirectorySyncResult {
158
- name: string;
159
- removeCallback: () => void;
160
- }
161
-
162
- function useTmpDir(): string | undefined {
163
- const [directory, setDirectory] = useState<DirectorySyncResult>();
164
- const handleError = useErrorHandler();
165
- useEffect(() => {
166
- let dir: DirectorySyncResult | undefined;
167
- try {
168
- dir = tmp.dirSync({ unsafeCleanup: true });
169
- setDirectory(dir);
170
- return;
171
- } catch (err) {
172
- console.error("failed to create tmp dir");
173
- handleError(err);
174
- }
175
- return () => {
176
- dir?.removeCallback();
177
- };
178
- }, [handleError]);
179
- return directory?.name;
180
- }
181
-
182
- function useCustomBuild(
183
- expectedEntry: Entry,
184
- build: {
185
- command?: undefined | string;
186
- cwd?: undefined | string;
187
- watch_dir?: undefined | string;
188
- }
189
- ): void {
190
- useEffect(() => {
191
- if (!build.command) return;
192
- let watcher: ReturnType<typeof watch> | undefined;
193
- if (build.watch_dir) {
194
- watcher = watch(build.watch_dir, {
195
- persistent: true,
196
- ignoreInitial: true,
197
- }).on("all", (_event, filePath) => {
198
- //TODO: we should buffer requests to the proxy until this completes
199
- console.log(`The file ${filePath} changed, restarting build...`);
200
- runCustomBuild(expectedEntry.file, build).catch((err) => {
201
- console.error("Custom build failed:", err);
202
- });
203
- });
204
- }
205
-
206
- return () => {
207
- watcher?.close();
208
- };
209
- }, [build, expectedEntry.file]);
210
- }
211
-
212
- function sleep(period: number) {
213
- return new Promise((resolve) => setTimeout(resolve, period));
214
- }
215
- const SLEEP_DURATION = 2000;
216
- // really need a first class api for this
217
- const hostNameRegex = /userHostname="(.*)"/g;
218
- async function findTunnelHostname() {
219
- let hostName: string | undefined;
220
- while (!hostName) {
221
- try {
222
- const resp = await fetch("http://localhost:8789/metrics");
223
- const data = await resp.text();
224
- const matches = Array.from(data.matchAll(hostNameRegex));
225
- hostName = matches[0][1];
226
- } catch (err) {
227
- await sleep(SLEEP_DURATION);
228
- }
229
- }
230
- return hostName;
231
- }
232
-
233
- /**
234
- * Create a tunnel to the remote worker.
235
- * We've disabled this for now until we figure out a better user experience.
236
- */
237
- function useTunnel(toggle: boolean) {
238
- const tunnel = useRef<ReturnType<typeof spawn>>();
239
- const removeSignalExitListener = useRef<() => void>();
240
- // TODO: test if cloudflared is available, if not
241
- // point them to a url where they can get docs to install it
242
- useEffect(() => {
243
- async function startTunnel() {
244
- if (toggle) {
245
- try {
246
- await commandExists("cloudflared");
247
- } catch (e) {
248
- console.error(
249
- "To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
250
- );
251
- return;
252
- }
253
- console.log("⎔ Starting a tunnel...");
254
- tunnel.current = spawn("cloudflared", [
255
- "tunnel",
256
- "--url",
257
- "http://localhost:8787",
258
- "--metrics",
259
- "localhost:8789",
260
- ]);
261
-
262
- tunnel.current.on("close", (code) => {
263
- if (code) {
264
- console.log(`Tunnel process exited with code ${code}`);
265
- }
266
- });
267
-
268
- removeSignalExitListener.current = onExit((_code, _signal) => {
269
- console.log("⎔ Shutting down local tunnel.");
270
- tunnel.current?.kill();
271
- tunnel.current = undefined;
272
- });
273
-
274
- const hostName = await findTunnelHostname();
275
- await clipboardy.write(hostName);
276
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
277
- }
278
- }
279
-
280
- startTunnel().catch(async (err) => {
281
- console.error("tunnel:", err);
282
- await reportError(err);
283
- });
284
-
285
- return () => {
286
- if (tunnel.current) {
287
- console.log("⎔ Shutting down tunnel.");
288
- tunnel.current?.kill();
289
- tunnel.current = undefined;
290
- removeSignalExitListener.current && removeSignalExitListener.current();
291
- removeSignalExitListener.current = undefined;
292
- }
293
- };
294
- }, [toggle]);
295
- }
296
-
297
- type useHotkeysInitialState = {
298
- local: boolean;
299
- tunnel: boolean;
300
- };
301
- function useHotkeys(
302
- initial: useHotkeysInitialState,
303
- port: number,
304
- ip: string,
305
- inspectorPort: number,
306
- localProtocol: "http" | "https"
307
- ) {
308
- // UGH, we should put port in context instead
309
- const [toggles, setToggles] = useState(initial);
310
- useInput(
311
- async (
312
- input,
313
- // eslint-disable-next-line unused-imports/no-unused-vars
314
- key
315
- ) => {
316
- switch (input.toLowerCase()) {
317
- // open browser
318
- case "b": {
319
- await openInBrowser(`${localProtocol}://${ip}:${port}`);
320
- break;
321
- }
322
- // toggle inspector
323
- case "d": {
324
- await openInBrowser(
325
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:${inspectorPort}/ws`,
326
- { forceChromium: true }
327
- );
328
- break;
329
- }
330
- // toggle local
331
- case "l":
332
- setToggles((previousToggles) => ({
333
- ...previousToggles,
334
- local: !previousToggles.local,
335
- }));
336
- break;
337
- // shut down
338
- case "q":
339
- case "x":
340
- process.exit(0);
341
- break;
342
- default:
343
- // nothing?
344
- break;
345
- }
346
- }
347
- );
348
- return toggles;
349
- }
350
-
351
- function ErrorFallback(props: { error: Error }) {
352
- const { exit } = useApp();
353
- useEffect(() => exit(props.error));
354
- return (
355
- <>
356
- <Text>Something went wrong:</Text>
357
- <Text>{props.error.stack}</Text>
358
- </>
359
- );
360
- }
361
-
362
- export default withErrorBoundary(DevImplementation, {
363
- FallbackComponent: ErrorFallback,
364
- });
package/src/dev/local.tsx DELETED
@@ -1,232 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { realpathSync } from "node:fs";
3
- import { writeFile } from "node:fs/promises";
4
- import path from "node:path";
5
- import { useState, useEffect, useRef } from "react";
6
- import onExit from "signal-exit";
7
- import useInspector from "../inspect";
8
- import { DEFAULT_MODULE_RULES } from "../module-collection";
9
- import { waitForPortToBeAvailable } from "../proxy";
10
- import type { Config } from "../config";
11
- import type { AssetPaths } from "../sites";
12
- import type { CfWorkerInit, CfScriptFormat } from "../worker";
13
- import type { EsbuildBundle } from "./use-esbuild";
14
- import type { MiniflareOptions } from "miniflare";
15
-
16
- interface LocalProps {
17
- name: undefined | string;
18
- bundle: EsbuildBundle | undefined;
19
- format: CfScriptFormat | undefined;
20
- compatibilityDate: string | undefined;
21
- compatibilityFlags: undefined | string[];
22
- bindings: CfWorkerInit["bindings"];
23
- assetPaths: undefined | AssetPaths;
24
- public: undefined | string;
25
- port: number;
26
- ip: string;
27
- rules: Config["rules"];
28
- inspectorPort: number;
29
- enableLocalPersistence: boolean;
30
- }
31
-
32
- export function Local(props: LocalProps) {
33
- const { inspectorUrl } = useLocalWorker(props);
34
- useInspector({
35
- inspectorUrl,
36
- port: props.inspectorPort,
37
- logToTerminal: false,
38
- });
39
- return null;
40
- }
41
-
42
- function useLocalWorker({
43
- name: workerName,
44
- bundle,
45
- format,
46
- compatibilityDate,
47
- compatibilityFlags,
48
- bindings,
49
- assetPaths,
50
- public: publicDirectory,
51
- port,
52
- rules,
53
- enableLocalPersistence,
54
- ip,
55
- }: LocalProps) {
56
- // TODO: pass vars via command line
57
- const local = useRef<ReturnType<typeof spawn>>();
58
- const removeSignalExitListener = useRef<() => void>();
59
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
60
- useEffect(() => {
61
- async function startLocalWorker() {
62
- if (!bundle || !format) return;
63
-
64
- // port for the worker
65
- await waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 });
66
-
67
- if (publicDirectory) {
68
- throw new Error(
69
- '⎔ A "public" folder is not yet supported in local mode.'
70
- );
71
- }
72
-
73
- // In local mode, we want to copy all referenced modules into
74
- // the output bundle directory before starting up
75
- for (const module of bundle.modules) {
76
- await writeFile(
77
- path.join(path.dirname(bundle.path), module.name),
78
- module.content
79
- );
80
- }
81
-
82
- const scriptPath = realpathSync(bundle.path);
83
-
84
- const wasmBindings = { ...bindings.wasm_modules };
85
- if (format === "service-worker") {
86
- for (const { type, name } of bundle.modules) {
87
- if (type === "compiled-wasm") {
88
- // In service-worker format, .wasm modules are referenced by global identifiers,
89
- // so we convert it here.
90
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
91
- // characters with an underscore.
92
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
93
- wasmBindings[identifier] = name;
94
- }
95
- }
96
- }
97
-
98
- const options: MiniflareOptions = {
99
- name: workerName,
100
- port,
101
- scriptPath,
102
- host: ip,
103
- modules: format === "modules",
104
- modulesRules: (rules || [])
105
- .concat(DEFAULT_MODULE_RULES)
106
- .map(({ type, globs: include, fallthrough }) => ({
107
- type,
108
- include,
109
- fallthrough,
110
- })),
111
- compatibilityDate,
112
- compatibilityFlags,
113
- kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
114
- kvPersist: enableLocalPersistence,
115
- durableObjects: Object.fromEntries(
116
- (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
117
- (value) => [value.name, value.class_name]
118
- )
119
- ),
120
- durableObjectsPersist: enableLocalPersistence,
121
- cachePersist: enableLocalPersistence,
122
- sitePath: assetPaths?.assetDirectory
123
- ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
124
- : undefined,
125
- siteInclude: assetPaths?.includePatterns.length
126
- ? assetPaths?.includePatterns
127
- : undefined,
128
- siteExclude: assetPaths?.excludePatterns.length
129
- ? assetPaths.excludePatterns
130
- : undefined,
131
- bindings: bindings.vars,
132
- wasmBindings,
133
- sourceMap: true,
134
- logUnhandledRejections: true,
135
- };
136
-
137
- // The path to the Miniflare CLI assumes that this file is being run from
138
- // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
139
- // If either of those paths change this line needs updating.
140
- const miniflareCLIPath = path.resolve(
141
- __dirname,
142
- "../miniflare-dist/index.mjs"
143
- );
144
- const optionsArg = JSON.stringify(options, null);
145
-
146
- console.log("⎔ Starting a local server...");
147
- local.current = spawn(
148
- "node",
149
- [
150
- "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
151
- "--no-warnings", // hide annoying Node warnings
152
- "--inspect", // start Miniflare listening for a debugger to attach
153
- miniflareCLIPath,
154
- optionsArg,
155
- // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
156
- ],
157
- {
158
- cwd: path.dirname(scriptPath),
159
- }
160
- );
161
-
162
- local.current.on("close", (code) => {
163
- if (code) {
164
- console.log(`Miniflare process exited with code ${code}`);
165
- }
166
- });
167
-
168
- local.current.stdout?.on("data", (data: Buffer) => {
169
- console.log(`${data.toString()}`);
170
- });
171
-
172
- local.current.stderr?.on("data", (data: Buffer) => {
173
- console.error(`${data.toString()}`);
174
- const matches =
175
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
176
- data.toString()
177
- );
178
- if (matches) {
179
- setInspectorUrl(matches[1]);
180
- }
181
- });
182
-
183
- local.current.on("exit", (code) => {
184
- if (code) {
185
- console.error(`Miniflare process exited with code ${code}`);
186
- }
187
- });
188
-
189
- local.current.on("error", (error: Error) => {
190
- console.error(`Miniflare process failed to spawn`);
191
- console.error(error);
192
- });
193
-
194
- removeSignalExitListener.current = onExit((_code, _signal) => {
195
- console.log("⎔ Shutting down local server.");
196
- local.current?.kill();
197
- local.current = undefined;
198
- });
199
- }
200
-
201
- startLocalWorker().catch((err) => {
202
- console.error("local worker:", err);
203
- });
204
-
205
- return () => {
206
- if (local.current) {
207
- console.log("⎔ Shutting down local server.");
208
- local.current?.kill();
209
- local.current = undefined;
210
- removeSignalExitListener.current && removeSignalExitListener.current();
211
- removeSignalExitListener.current = undefined;
212
- }
213
- };
214
- }, [
215
- bundle,
216
- workerName,
217
- format,
218
- port,
219
- ip,
220
- bindings.durable_objects?.bindings,
221
- bindings.kv_namespaces,
222
- bindings.vars,
223
- compatibilityDate,
224
- compatibilityFlags,
225
- enableLocalPersistence,
226
- assetPaths,
227
- publicDirectory,
228
- rules,
229
- bindings.wasm_modules,
230
- ]);
231
- return { inspectorUrl };
232
- }