wrangler 0.0.0-e2a26a0 → 0.0.0-e3e3243

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