wrangler 0.0.0-e928f94 → 0.0.0-e95bea2

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 (100) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +46 -18
  3. package/pages/functions/buildWorker.ts +62 -0
  4. package/pages/functions/filepath-routing.test.ts +123 -0
  5. package/pages/functions/filepath-routing.ts +178 -0
  6. package/pages/functions/identifiers.ts +78 -0
  7. package/pages/functions/routes.ts +151 -0
  8. package/pages/functions/template-worker.ts +130 -0
  9. package/src/__tests__/configuration.test.ts +2217 -0
  10. package/src/__tests__/dev.test.tsx +405 -0
  11. package/src/__tests__/dev2.test.tsx +152 -0
  12. package/src/__tests__/guess-worker-format.test.ts +58 -0
  13. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  14. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  15. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  16. package/src/__tests__/helpers/mock-account-id.ts +44 -0
  17. package/src/__tests__/helpers/mock-bin.ts +36 -0
  18. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  19. package/src/__tests__/helpers/mock-console.ts +70 -0
  20. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  21. package/src/__tests__/helpers/mock-kv.ts +40 -0
  22. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  23. package/src/__tests__/helpers/mock-user.ts +27 -0
  24. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  25. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  26. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  27. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  28. package/src/__tests__/https-options.test.ts +127 -0
  29. package/src/__tests__/index.test.ts +957 -119
  30. package/src/__tests__/jest.setup.ts +69 -0
  31. package/src/__tests__/kv.test.ts +1408 -0
  32. package/src/__tests__/logout.test.ts +50 -0
  33. package/src/__tests__/package-manager.test.ts +206 -0
  34. package/src/__tests__/pages.test.ts +44 -0
  35. package/src/__tests__/parse.test.ts +322 -0
  36. package/src/__tests__/publish.test.ts +2453 -0
  37. package/src/__tests__/r2.test.ts +198 -0
  38. package/src/__tests__/route.test.ts +45 -0
  39. package/src/__tests__/secret.test.ts +425 -0
  40. package/src/__tests__/sentry.test.ts +146 -0
  41. package/src/__tests__/tail.test.ts +564 -0
  42. package/src/__tests__/whoami.test.tsx +86 -0
  43. package/src/bundle.ts +142 -0
  44. package/src/cfetch/index.ts +104 -0
  45. package/src/cfetch/internal.ts +135 -0
  46. package/src/cli.ts +16 -7
  47. package/src/config/README.md +107 -0
  48. package/src/config/config.ts +279 -0
  49. package/src/config/diagnostics.ts +80 -0
  50. package/src/config/environment.ts +305 -0
  51. package/src/config/index.ts +52 -0
  52. package/src/config/validation-helpers.ts +388 -0
  53. package/src/config/validation.ts +1027 -0
  54. package/src/{api/preview.ts → create-worker-preview.ts} +63 -25
  55. package/src/create-worker-upload-form.ts +217 -0
  56. package/src/dev/dev.tsx +357 -0
  57. package/src/dev/local.tsx +241 -0
  58. package/src/dev/remote.tsx +201 -0
  59. package/src/dev/use-esbuild.ts +100 -0
  60. package/src/dialogs.tsx +5 -13
  61. package/src/entry.ts +159 -0
  62. package/src/environment-variables.ts +33 -0
  63. package/src/https-options.ts +122 -0
  64. package/src/index.tsx +1374 -903
  65. package/src/inspect.ts +617 -0
  66. package/src/kv/index.tsx +339 -0
  67. package/src/module-collection.ts +215 -26
  68. package/src/open-in-browser.ts +25 -0
  69. package/src/package-manager.ts +126 -0
  70. package/src/pages.tsx +452 -250
  71. package/src/parse.ts +183 -0
  72. package/src/paths.ts +26 -0
  73. package/src/proxy.ts +438 -0
  74. package/src/publish.ts +300 -292
  75. package/src/r2.ts +50 -0
  76. package/src/reporting.ts +131 -0
  77. package/src/selfsigned.d.ts +29 -0
  78. package/src/sites.tsx +181 -58
  79. package/src/tail/filters.ts +279 -0
  80. package/src/tail/index.ts +299 -0
  81. package/src/tail/printing.ts +62 -0
  82. package/src/user.tsx +166 -130
  83. package/src/whoami.tsx +69 -0
  84. package/src/worker.ts +163 -0
  85. package/templates/new-worker.js +15 -0
  86. package/templates/new-worker.ts +15 -0
  87. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  88. package/templates/tsconfig.json +105 -0
  89. package/wrangler-dist/cli.js +131958 -115793
  90. package/wrangler-dist/cli.js.map +3 -3
  91. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  92. package/src/__tests__/mock-cfetch.js +0 -46
  93. package/src/api/form_data.ts +0 -141
  94. package/src/api/inspect.ts +0 -441
  95. package/src/api/worker.ts +0 -161
  96. package/src/cfetch.ts +0 -72
  97. package/src/config.ts +0 -122
  98. package/src/dev.tsx +0 -724
  99. package/src/kv.tsx +0 -211
  100. package/src/tail.tsx +0 -71
@@ -1,7 +1,8 @@
1
- import cfetch from "../cfetch";
2
- import { toFormData } from "./form_data";
3
- import type { CfAccount, CfWorkerInit } from "./worker";
4
- import fetch from "node-fetch";
1
+ import { URL } from "node:url";
2
+ import { fetch } from "undici";
3
+ import { fetchResult } from "./cfetch";
4
+ import { createWorkerUploadForm } from "./create-worker-upload-form";
5
+ import type { CfAccount, CfWorkerContext, CfWorkerInit } from "./worker";
5
6
 
6
7
  /**
7
8
  * A preview mode.
@@ -54,13 +55,16 @@ export interface CfPreviewToken {
54
55
  /**
55
56
  * Generates a preview session token.
56
57
  */
57
- async function sessionToken(account: CfAccount): Promise<CfPreviewToken> {
58
- const { accountId, zoneId } = account;
59
- const initUrl = zoneId
60
- ? `/zones/${zoneId}/workers/edge-preview`
58
+ async function sessionToken(
59
+ account: CfAccount,
60
+ ctx: CfWorkerContext
61
+ ): Promise<CfPreviewToken> {
62
+ const { accountId } = account;
63
+ const initUrl = ctx.zone
64
+ ? `/zones/${ctx.zone.id}/workers/edge-preview`
61
65
  : `/accounts/${accountId}/workers/subdomain/edge-preview`;
62
66
 
63
- const { exchange_url } = await cfetch<{ exchange_url: string }>(initUrl);
67
+ const { exchange_url } = await fetchResult<{ exchange_url: string }>(initUrl);
64
68
  const { inspector_websocket, token } = (await (
65
69
  await fetch(exchange_url)
66
70
  ).json()) as { inspector_websocket: string; token: string };
@@ -89,26 +93,32 @@ function randomId(): string {
89
93
  /**
90
94
  * Creates a preview token.
91
95
  */
92
- export async function previewToken(
96
+ async function createPreviewToken(
93
97
  account: CfAccount,
94
- worker: CfWorkerInit
98
+ worker: CfWorkerInit,
99
+ ctx: CfWorkerContext
95
100
  ): Promise<CfPreviewToken> {
96
- const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(account);
101
+ const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(
102
+ account,
103
+ ctx
104
+ );
97
105
 
98
- const { accountId, zoneId } = account;
99
- const scriptId = zoneId ? randomId() : worker.name || host.split(".")[0];
100
- const url = `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
106
+ const { accountId } = account;
107
+ const scriptId = ctx.zone ? randomId() : worker.name || host.split(".")[0];
108
+ const url =
109
+ ctx.env && !ctx.legacyEnv
110
+ ? `/accounts/${accountId}/workers/services/${scriptId}/environments/${ctx.env}/edge-preview`
111
+ : `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
101
112
 
102
- const mode: CfPreviewMode = zoneId
103
- ? { routes: ["*/*"] }
113
+ const mode: CfPreviewMode = ctx.zone
114
+ ? { routes: ["*/*"] } // TODO: should we support routes here? how?
104
115
  : { workers_dev: true };
105
116
 
106
- const formData = toFormData(worker);
117
+ const formData = createWorkerUploadForm(worker);
107
118
  formData.set("wrangler-session-config", JSON.stringify(mode));
108
119
 
109
- const { preview_token } = await cfetch<{ preview_token: string }>(url, {
120
+ const { preview_token } = await fetchResult<{ preview_token: string }>(url, {
110
121
  method: "POST",
111
- // @ts-expect-error TODO: fix this
112
122
  body: formData,
113
123
  headers: {
114
124
  "cf-preview-upload-config-token": value,
@@ -117,12 +127,40 @@ export async function previewToken(
117
127
 
118
128
  return {
119
129
  value: preview_token,
120
- // TODO: verify this works with zoned workers
121
- host:
122
- worker.name && !zoneId
123
- ? `${worker.name}.${host.split(".").slice(1).join(".")}`
124
- : host,
130
+ host: ctx.zone
131
+ ? ctx.zone.host
132
+ : worker.name
133
+ ? `${
134
+ worker.name
135
+ // TODO: this should also probably have the env prefix
136
+ // but it doesn't appear to work yet, instead giving us the
137
+ // "There is nothing here yet" screen
138
+ // ctx.env && !ctx.legacyEnv
139
+ // ? `${ctx.env}.${worker.name}`
140
+ // : worker.name
141
+ }.${host.split(".").slice(1).join(".")}`
142
+ : host,
143
+
125
144
  inspectorUrl,
126
145
  prewarmUrl,
127
146
  };
128
147
  }
148
+
149
+ /**
150
+ * A stub to create a Cloudflare Worker preview.
151
+ *
152
+ * @example
153
+ * const {value, host} = await createWorker(init, acct);
154
+ */
155
+ export async function createWorkerPreview(
156
+ init: CfWorkerInit,
157
+ account: CfAccount,
158
+ ctx: CfWorkerContext
159
+ ): Promise<CfPreviewToken> {
160
+ const token = await createPreviewToken(account, init, ctx);
161
+ const response = await fetch(token.prewarmUrl.href, { method: "POST" });
162
+ if (!response.ok) {
163
+ // console.error("worker failed to prewarm: ", response.statusText);
164
+ }
165
+ return token;
166
+ }
@@ -0,0 +1,217 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { FormData, File } from "undici";
3
+ import type {
4
+ CfWorkerInit,
5
+ CfModuleType,
6
+ CfDurableObjectMigrations,
7
+ } from "./worker.js";
8
+
9
+ export function toMimeType(type: CfModuleType): string {
10
+ switch (type) {
11
+ case "esm":
12
+ return "application/javascript+module";
13
+ case "commonjs":
14
+ return "application/javascript";
15
+ case "compiled-wasm":
16
+ return "application/wasm";
17
+ case "buffer":
18
+ return "application/octet-stream";
19
+ case "text":
20
+ return "text/plain";
21
+ default:
22
+ throw new TypeError("Unsupported module: " + type);
23
+ }
24
+ }
25
+
26
+ export interface WorkerMetadata {
27
+ /** The name of the entry point module. Only exists when the worker is in the ES module format */
28
+ main_module?: string;
29
+ /** The name of the entry point module. Only exists when the worker is in the Service Worker format */
30
+ body_part?: string;
31
+ compatibility_date?: string;
32
+ compatibility_flags?: string[];
33
+ usage_model?: "bundled" | "unbound";
34
+ migrations?: CfDurableObjectMigrations;
35
+ bindings: (
36
+ | { type: "kv_namespace"; name: string; namespace_id: string }
37
+ | { type: "plain_text"; name: string; text: string }
38
+ | { type: "json"; name: string; json: unknown }
39
+ | { type: "wasm_module"; name: string; part: string }
40
+ | { type: "text_blob"; name: string; part: string }
41
+ | {
42
+ type: "durable_object_namespace";
43
+ name: string;
44
+ class_name: string;
45
+ script_name?: string;
46
+ }
47
+ | { type: "r2_bucket"; name: string; bucket_name: string }
48
+ )[];
49
+ }
50
+
51
+ /**
52
+ * Creates a `FormData` upload from a `CfWorkerInit`.
53
+ */
54
+ export function createWorkerUploadForm(worker: CfWorkerInit): FormData {
55
+ const formData = new FormData();
56
+ const {
57
+ main,
58
+ bindings,
59
+ migrations,
60
+ usage_model,
61
+ compatibility_date,
62
+ compatibility_flags,
63
+ } = worker;
64
+
65
+ let { modules } = worker;
66
+
67
+ const metadataBindings: WorkerMetadata["bindings"] = [];
68
+
69
+ bindings.kv_namespaces?.forEach(({ id, binding }) => {
70
+ metadataBindings.push({
71
+ name: binding,
72
+ type: "kv_namespace",
73
+ namespace_id: id,
74
+ });
75
+ });
76
+
77
+ bindings.durable_objects?.bindings.forEach(
78
+ ({ name, class_name, script_name }) => {
79
+ metadataBindings.push({
80
+ name,
81
+ type: "durable_object_namespace",
82
+ class_name: class_name,
83
+ ...(script_name && { script_name }),
84
+ });
85
+ }
86
+ );
87
+
88
+ bindings.r2_buckets?.forEach(({ binding, bucket_name }) => {
89
+ metadataBindings.push({
90
+ name: binding,
91
+ type: "r2_bucket",
92
+ bucket_name,
93
+ });
94
+ });
95
+
96
+ Object.entries(bindings.vars || {})?.forEach(([key, value]) => {
97
+ if (typeof value === "string") {
98
+ metadataBindings.push({ name: key, type: "plain_text", text: value });
99
+ } else {
100
+ metadataBindings.push({ name: key, type: "json", json: value });
101
+ }
102
+ });
103
+
104
+ for (const [name, filePath] of Object.entries(bindings.wasm_modules || {})) {
105
+ metadataBindings.push({
106
+ name,
107
+ type: "wasm_module",
108
+ part: name,
109
+ });
110
+
111
+ formData.set(
112
+ name,
113
+ new File([readFileSync(filePath)], filePath, {
114
+ type: "application/wasm",
115
+ })
116
+ );
117
+ }
118
+
119
+ for (const [name, filePath] of Object.entries(bindings.text_blobs || {})) {
120
+ metadataBindings.push({
121
+ name,
122
+ type: "text_blob",
123
+ part: name,
124
+ });
125
+
126
+ if (name !== "__STATIC_CONTENT_MANIFEST") {
127
+ formData.set(
128
+ name,
129
+ new File([readFileSync(filePath)], filePath, {
130
+ type: "text/plain",
131
+ })
132
+ );
133
+ }
134
+ }
135
+
136
+ if (main.type === "commonjs") {
137
+ // This is a service-worker format worker.
138
+ for (const module of Object.values([...(modules || [])])) {
139
+ if (module.name === "__STATIC_CONTENT_MANIFEST") {
140
+ // Add the manifest to the form data.
141
+ formData.set(
142
+ module.name,
143
+ new File([module.content], module.name, {
144
+ type: "text/plain",
145
+ })
146
+ );
147
+ // And then remove it from the modules collection
148
+ modules = modules?.filter((m) => m !== module);
149
+ } else if (module.type === "compiled-wasm" || module.type === "text") {
150
+ // Convert all wasm/text modules into `wasm_module`/`text_blob` bindings.
151
+ // The "name" of the module is a file path. We use it
152
+ // to instead be a "part" of the body, and a reference
153
+ // that we can use inside our source. This identifier has to be a valid
154
+ // JS identifier, so we replace all non alphanumeric characters
155
+ // with an underscore.
156
+ const name = module.name.replace(/[^a-zA-Z0-9_$]/g, "_");
157
+ metadataBindings.push({
158
+ name,
159
+ type: module.type === "compiled-wasm" ? "wasm_module" : "text_blob",
160
+ part: name,
161
+ });
162
+
163
+ // Add the module to the form data.
164
+ formData.set(
165
+ name,
166
+ new File([module.content], module.name, {
167
+ type:
168
+ module.type === "compiled-wasm"
169
+ ? "application/wasm"
170
+ : "text/plain",
171
+ })
172
+ );
173
+ // And then remove it from the modules collection
174
+ modules = modules?.filter((m) => m !== module);
175
+ } else if (module.type === "buffer") {
176
+ throw new Error(
177
+ 'The "buffer" module type is not yet supported in service worker format workers'
178
+ );
179
+ }
180
+ }
181
+ }
182
+
183
+ if (bindings.unsafe) {
184
+ // @ts-expect-error unsafe bindings don't need to match a specific type here
185
+ metadataBindings.push(...bindings.unsafe);
186
+ }
187
+
188
+ const metadata: WorkerMetadata = {
189
+ ...(main.type !== "commonjs"
190
+ ? { main_module: main.name }
191
+ : { body_part: main.name }),
192
+ bindings: metadataBindings,
193
+ ...(compatibility_date && { compatibility_date }),
194
+ ...(compatibility_flags && { compatibility_flags }),
195
+ ...(usage_model && { usage_model }),
196
+ ...(migrations && { migrations }),
197
+ };
198
+
199
+ formData.set("metadata", JSON.stringify(metadata));
200
+
201
+ if (main.type === "commonjs" && modules && modules.length > 0) {
202
+ throw new TypeError(
203
+ "More than one module can only be specified when type = 'esm'"
204
+ );
205
+ }
206
+
207
+ for (const module of [main].concat(modules || [])) {
208
+ formData.set(
209
+ module.name,
210
+ new File([module.content], module.name, {
211
+ type: toMimeType(module.type ?? main.type ?? "esm"),
212
+ })
213
+ );
214
+ }
215
+
216
+ return formData;
217
+ }
@@ -0,0 +1,357 @@
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
+ inspectorPort: number;
28
+ rules: Config["rules"];
29
+ accountId: undefined | string;
30
+ initialMode: "local" | "remote";
31
+ jsxFactory: undefined | string;
32
+ jsxFragment: undefined | string;
33
+ upstreamProtocol: "https" | "http";
34
+ localProtocol: "https" | "http";
35
+ enableLocalPersistence: boolean;
36
+ bindings: CfWorkerInit["bindings"];
37
+ public: undefined | string;
38
+ assetPaths: undefined | AssetPaths;
39
+ compatibilityDate: undefined | string;
40
+ compatibilityFlags: undefined | string[];
41
+ usageModel: undefined | "bundled" | "unbound";
42
+ buildCommand: {
43
+ command?: undefined | string;
44
+ cwd?: undefined | string;
45
+ watch_dir?: undefined | string;
46
+ };
47
+ env: string | undefined;
48
+ legacyEnv: boolean;
49
+ zone:
50
+ | {
51
+ id: string;
52
+ host: string;
53
+ }
54
+ | undefined;
55
+ };
56
+
57
+ export function DevImplementation(props: DevProps): JSX.Element {
58
+ const port = props.port ?? 8787;
59
+ const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined;
60
+ const directory = useTmpDir();
61
+
62
+ useCustomBuild(props.entry, props.buildCommand);
63
+
64
+ if (props.public && props.entry.format === "service-worker") {
65
+ throw new Error(
66
+ "You cannot use the service worker format with a `public` directory."
67
+ );
68
+ }
69
+
70
+ if (props.bindings.wasm_modules && props.entry.format === "modules") {
71
+ throw new Error(
72
+ "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
73
+ );
74
+ }
75
+
76
+ if (props.bindings.text_blobs && props.entry.format === "modules") {
77
+ throw new Error(
78
+ "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"
79
+ );
80
+ }
81
+
82
+ const bundle = useEsbuild({
83
+ entry: props.entry,
84
+ destination: directory,
85
+ staticRoot: props.public,
86
+ jsxFactory: props.jsxFactory,
87
+ rules: props.rules,
88
+ jsxFragment: props.jsxFragment,
89
+ serveAssetsFromWorker: !!props.public,
90
+ });
91
+
92
+ const toggles = useHotkeys(
93
+ {
94
+ local: props.initialMode === "local",
95
+ tunnel: false,
96
+ },
97
+ port,
98
+ props.inspectorPort,
99
+ props.localProtocol
100
+ );
101
+
102
+ useTunnel(toggles.tunnel);
103
+
104
+ return (
105
+ <>
106
+ {toggles.local ? (
107
+ <Local
108
+ name={props.name}
109
+ bundle={bundle}
110
+ format={props.entry.format}
111
+ bindings={props.bindings}
112
+ assetPaths={props.assetPaths}
113
+ public={props.public}
114
+ port={port}
115
+ rules={props.rules}
116
+ inspectorPort={props.inspectorPort}
117
+ enableLocalPersistence={props.enableLocalPersistence}
118
+ />
119
+ ) : (
120
+ <Remote
121
+ name={props.name}
122
+ bundle={bundle}
123
+ format={props.entry.format}
124
+ accountId={props.accountId}
125
+ apiToken={apiToken}
126
+ bindings={props.bindings}
127
+ assetPaths={props.assetPaths}
128
+ public={props.public}
129
+ port={port}
130
+ localProtocol={props.localProtocol}
131
+ inspectorPort={props.inspectorPort}
132
+ compatibilityDate={props.compatibilityDate}
133
+ compatibilityFlags={props.compatibilityFlags}
134
+ usageModel={props.usageModel}
135
+ env={props.env}
136
+ legacyEnv={props.legacyEnv}
137
+ zone={props.zone}
138
+ />
139
+ )}
140
+ <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
141
+ <Text>
142
+ {`B to open a browser, D to open Devtools, L to ${
143
+ toggles.local ? "turn off" : "turn on"
144
+ } local mode, X to exit`}
145
+ </Text>
146
+ </Box>
147
+ </>
148
+ );
149
+ }
150
+
151
+ export interface DirectorySyncResult {
152
+ name: string;
153
+ removeCallback: () => void;
154
+ }
155
+
156
+ function useTmpDir(): string | undefined {
157
+ const [directory, setDirectory] = useState<DirectorySyncResult>();
158
+ const handleError = useErrorHandler();
159
+ useEffect(() => {
160
+ let dir: DirectorySyncResult | undefined;
161
+ try {
162
+ dir = tmp.dirSync({ unsafeCleanup: true });
163
+ setDirectory(dir);
164
+ return;
165
+ } catch (err) {
166
+ console.error("failed to create tmp dir");
167
+ handleError(err);
168
+ }
169
+ return () => {
170
+ dir?.removeCallback();
171
+ };
172
+ }, [handleError]);
173
+ return directory?.name;
174
+ }
175
+
176
+ function useCustomBuild(
177
+ expectedEntry: Entry,
178
+ build: {
179
+ command?: undefined | string;
180
+ cwd?: undefined | string;
181
+ watch_dir?: undefined | string;
182
+ }
183
+ ): void {
184
+ useEffect(() => {
185
+ if (!build.command) return;
186
+ let watcher: ReturnType<typeof watch> | undefined;
187
+ if (build.watch_dir) {
188
+ watcher = watch(build.watch_dir, {
189
+ persistent: true,
190
+ ignoreInitial: true,
191
+ }).on("all", (_event, filePath) => {
192
+ //TODO: we should buffer requests to the proxy until this completes
193
+ console.log(`The file ${filePath} changed, restarting build...`);
194
+ runCustomBuild(expectedEntry.file, build).catch((err) => {
195
+ console.error("Custom build failed:", err);
196
+ });
197
+ });
198
+ }
199
+
200
+ return () => {
201
+ watcher?.close();
202
+ };
203
+ }, [build, expectedEntry.file]);
204
+ }
205
+
206
+ function sleep(period: number) {
207
+ return new Promise((resolve) => setTimeout(resolve, period));
208
+ }
209
+ const SLEEP_DURATION = 2000;
210
+ // really need a first class api for this
211
+ const hostNameRegex = /userHostname="(.*)"/g;
212
+ async function findTunnelHostname() {
213
+ let hostName: string | undefined;
214
+ while (!hostName) {
215
+ try {
216
+ const resp = await fetch("http://localhost:8789/metrics");
217
+ const data = await resp.text();
218
+ const matches = Array.from(data.matchAll(hostNameRegex));
219
+ hostName = matches[0][1];
220
+ } catch (err) {
221
+ await sleep(SLEEP_DURATION);
222
+ }
223
+ }
224
+ return hostName;
225
+ }
226
+
227
+ /**
228
+ * Create a tunnel to the remote worker.
229
+ * We've disabled this for now until we figure out a better user experience.
230
+ */
231
+ function useTunnel(toggle: boolean) {
232
+ const tunnel = useRef<ReturnType<typeof spawn>>();
233
+ const removeSignalExitListener = useRef<() => void>();
234
+ // TODO: test if cloudflared is available, if not
235
+ // point them to a url where they can get docs to install it
236
+ useEffect(() => {
237
+ async function startTunnel() {
238
+ if (toggle) {
239
+ try {
240
+ await commandExists("cloudflared");
241
+ } catch (e) {
242
+ console.error(
243
+ "To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
244
+ );
245
+ return;
246
+ }
247
+ console.log("⎔ Starting a tunnel...");
248
+ tunnel.current = spawn("cloudflared", [
249
+ "tunnel",
250
+ "--url",
251
+ "http://localhost:8787",
252
+ "--metrics",
253
+ "localhost:8789",
254
+ ]);
255
+
256
+ tunnel.current.on("close", (code) => {
257
+ if (code) {
258
+ console.log(`Tunnel process exited with code ${code}`);
259
+ }
260
+ });
261
+
262
+ removeSignalExitListener.current = onExit((_code, _signal) => {
263
+ console.log("⎔ Shutting down local tunnel.");
264
+ tunnel.current?.kill();
265
+ tunnel.current = undefined;
266
+ });
267
+
268
+ const hostName = await findTunnelHostname();
269
+ await clipboardy.write(hostName);
270
+ console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
271
+ }
272
+ }
273
+
274
+ startTunnel().catch(async (err) => {
275
+ console.error("tunnel:", err);
276
+ await reportError(err);
277
+ });
278
+
279
+ return () => {
280
+ if (tunnel.current) {
281
+ console.log("⎔ Shutting down tunnel.");
282
+ tunnel.current?.kill();
283
+ tunnel.current = undefined;
284
+ removeSignalExitListener.current && removeSignalExitListener.current();
285
+ removeSignalExitListener.current = undefined;
286
+ }
287
+ };
288
+ }, [toggle]);
289
+ }
290
+
291
+ type useHotkeysInitialState = {
292
+ local: boolean;
293
+ tunnel: boolean;
294
+ };
295
+ function useHotkeys(
296
+ initial: useHotkeysInitialState,
297
+ port: number,
298
+ inspectorPort: number,
299
+ localProtocol: "http" | "https"
300
+ ) {
301
+ // UGH, we should put port in context instead
302
+ const [toggles, setToggles] = useState(initial);
303
+ useInput(
304
+ async (
305
+ input,
306
+ // eslint-disable-next-line unused-imports/no-unused-vars
307
+ key
308
+ ) => {
309
+ switch (input.toLowerCase()) {
310
+ // open browser
311
+ case "b": {
312
+ await openInBrowser(`${localProtocol}://localhost:${port}`);
313
+ break;
314
+ }
315
+ // toggle inspector
316
+ case "d": {
317
+ await openInBrowser(
318
+ `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:${inspectorPort}/ws`,
319
+ { forceChromium: true }
320
+ );
321
+ break;
322
+ }
323
+ // toggle local
324
+ case "l":
325
+ setToggles((previousToggles) => ({
326
+ ...previousToggles,
327
+ local: !previousToggles.local,
328
+ }));
329
+ break;
330
+ // shut down
331
+ case "q":
332
+ case "x":
333
+ process.exit(0);
334
+ break;
335
+ default:
336
+ // nothing?
337
+ break;
338
+ }
339
+ }
340
+ );
341
+ return toggles;
342
+ }
343
+
344
+ function ErrorFallback(props: { error: Error }) {
345
+ const { exit } = useApp();
346
+ useEffect(() => exit(props.error));
347
+ return (
348
+ <>
349
+ <Text>Something went wrong:</Text>
350
+ <Text>{props.error.stack}</Text>
351
+ </>
352
+ );
353
+ }
354
+
355
+ export default withErrorBoundary(DevImplementation, {
356
+ FallbackComponent: ErrorFallback,
357
+ });