wrangler 0.0.0-e3cab74 → 0.0.0-e452a35

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