wrangler 0.0.0-ece06ea → 0.0.0-ed08df4

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 (121) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +34 -2
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +71 -36
  6. package/pages/functions/buildPlugin.ts +92 -0
  7. package/pages/functions/buildWorker.ts +138 -0
  8. package/pages/functions/filepath-routing.test.ts +234 -0
  9. package/pages/functions/filepath-routing.ts +189 -0
  10. package/pages/functions/identifiers.ts +78 -0
  11. package/pages/functions/routes.ts +156 -0
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +143 -0
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3125 -0
  16. package/src/__tests__/dev.test.tsx +829 -0
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  19. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  20. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  21. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  22. package/src/__tests__/helpers/mock-bin.ts +36 -0
  23. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  24. package/src/__tests__/helpers/mock-console.ts +87 -0
  25. package/src/__tests__/helpers/mock-dialogs.ts +90 -0
  26. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  27. package/src/__tests__/helpers/mock-istty.ts +27 -0
  28. package/src/__tests__/helpers/mock-kv.ts +33 -0
  29. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  31. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  32. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  33. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  34. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  35. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  36. package/src/__tests__/https-options.test.ts +130 -0
  37. package/src/__tests__/index.test.ts +221 -132
  38. package/src/__tests__/init.test.ts +1516 -0
  39. package/src/__tests__/jest.setup.ts +77 -0
  40. package/src/__tests__/kv.test.ts +1481 -0
  41. package/src/__tests__/logger.test.ts +115 -0
  42. package/src/__tests__/package-manager.test.ts +206 -0
  43. package/src/__tests__/pages.test.ts +327 -0
  44. package/src/__tests__/parse.test.ts +326 -0
  45. package/src/__tests__/publish.test.ts +4996 -0
  46. package/src/__tests__/r2.test.ts +210 -0
  47. package/src/__tests__/route.test.ts +45 -0
  48. package/src/__tests__/secret.test.ts +446 -0
  49. package/src/__tests__/tail.test.ts +690 -0
  50. package/src/__tests__/user.test.ts +131 -0
  51. package/src/__tests__/whoami.test.tsx +105 -0
  52. package/src/bundle.ts +169 -0
  53. package/src/cfetch/index.ts +104 -0
  54. package/src/cfetch/internal.ts +140 -0
  55. package/src/cli.ts +10 -7
  56. package/src/config/README.md +107 -0
  57. package/src/config/config.ts +234 -0
  58. package/src/config/diagnostics.ts +80 -0
  59. package/src/config/environment.ts +394 -0
  60. package/src/config/index.ts +63 -0
  61. package/src/config/validation-helpers.ts +575 -0
  62. package/src/config/validation.ts +1424 -0
  63. package/src/config-cache.ts +45 -0
  64. package/src/create-worker-preview.ts +175 -0
  65. package/src/create-worker-upload-form.ts +240 -0
  66. package/src/dev/dev-vars.ts +36 -0
  67. package/src/dev/dev.tsx +421 -0
  68. package/src/dev/local.tsx +312 -0
  69. package/src/dev/remote.tsx +213 -0
  70. package/src/dev/use-esbuild.ts +118 -0
  71. package/src/dialogs.tsx +22 -20
  72. package/src/entry.ts +322 -0
  73. package/src/environment-variables.ts +35 -0
  74. package/src/errors.ts +11 -0
  75. package/src/https-options.ts +123 -0
  76. package/src/index.tsx +1869 -1020
  77. package/src/inspect.ts +623 -0
  78. package/src/intl-polyfill.d.ts +139 -0
  79. package/src/kv.ts +344 -0
  80. package/src/logger.ts +66 -0
  81. package/src/miniflare-cli/README.md +30 -0
  82. package/src/miniflare-cli/enum-keys.ts +17 -0
  83. package/src/miniflare-cli/index.ts +41 -0
  84. package/src/miniflare-cli/request-context.ts +40 -0
  85. package/src/module-collection.ts +258 -0
  86. package/src/open-in-browser.ts +26 -0
  87. package/src/package-manager.ts +127 -0
  88. package/src/pages.tsx +1756 -218
  89. package/src/parse.ts +185 -0
  90. package/src/paths.ts +26 -0
  91. package/src/proxy.ts +449 -0
  92. package/src/publish.ts +377 -262
  93. package/src/r2.ts +50 -0
  94. package/src/selfsigned.d.ts +29 -0
  95. package/src/sites.tsx +237 -59
  96. package/src/tail/filters.ts +279 -0
  97. package/src/tail/index.ts +299 -0
  98. package/src/tail/printing.ts +67 -0
  99. package/src/update-check.ts +19 -0
  100. package/src/user.tsx +395 -221
  101. package/src/whoami.tsx +70 -0
  102. package/src/worker.ts +172 -0
  103. package/templates/gitignore +171 -0
  104. package/templates/new-worker.js +15 -0
  105. package/templates/new-worker.ts +15 -0
  106. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  107. package/templates/tsconfig.json +105 -0
  108. package/wrangler-dist/cli.js +108921 -132528
  109. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  110. package/src/__tests__/mock-cfetch.js +0 -46
  111. package/src/api/form_data.ts +0 -158
  112. package/src/api/inspect.ts +0 -441
  113. package/src/api/preview.ts +0 -123
  114. package/src/api/worker.ts +0 -161
  115. package/src/cfetch.ts +0 -72
  116. package/src/config.ts +0 -124
  117. package/src/dev.tsx +0 -736
  118. package/src/kv.tsx +0 -211
  119. package/src/tail.tsx +0 -71
  120. package/src/util/fetch.ts +0 -74
  121. package/wrangler-dist/cli.js.map +0 -7
package/src/parse.ts ADDED
@@ -0,0 +1,185 @@
1
+ import * as fs from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import TOML from "@iarna/toml";
4
+ import { formatMessagesSync } from "esbuild";
5
+
6
+ export type Message = {
7
+ text: string;
8
+ location?: Location;
9
+ notes?: Message[];
10
+ kind?: "warning" | "error";
11
+ };
12
+
13
+ export type Location = File & {
14
+ line: number;
15
+ column: number;
16
+ length?: number;
17
+ lineText?: string;
18
+ suggestion?: string;
19
+ };
20
+
21
+ export type File = {
22
+ file?: string;
23
+ fileText?: string;
24
+ };
25
+
26
+ /**
27
+ * Formats a `Message` using esbuild's pretty-printing algorithm.
28
+ */
29
+ export function formatMessage(
30
+ { text, notes, location, kind = "error" }: Message,
31
+ color = true
32
+ ): string {
33
+ const input = { text, notes, location };
34
+ delete input.location?.fileText;
35
+ for (const note of notes ?? []) {
36
+ delete note.location?.fileText;
37
+ }
38
+ const lines = formatMessagesSync([input], {
39
+ color,
40
+ kind: kind,
41
+ terminalWidth: process.stderr.columns,
42
+ });
43
+ return lines.join("\n");
44
+ }
45
+
46
+ /**
47
+ * An error that's thrown when something fails to parse.
48
+ */
49
+ export class ParseError extends Error implements Message {
50
+ readonly text: string;
51
+ readonly notes: Message[];
52
+ readonly location?: Location;
53
+ readonly kind: "warning" | "error";
54
+
55
+ constructor({ text, notes, location, kind }: Message) {
56
+ super(text);
57
+ this.name = this.constructor.name;
58
+ this.text = text;
59
+ this.notes = notes ?? [];
60
+ this.location = location;
61
+ this.kind = kind ?? "error";
62
+ }
63
+ }
64
+
65
+ /* eslint-disable @typescript-eslint/no-explicit-any */
66
+
67
+ const TOML_ERROR_NAME = "TomlError";
68
+ const TOML_ERROR_SUFFIX = " at row ";
69
+
70
+ type TomlError = Error & {
71
+ line: number;
72
+ col: number;
73
+ };
74
+
75
+ /**
76
+ * A wrapper around `TOML.parse` that throws a `ParseError`.
77
+ */
78
+ export function parseTOML(input: string, file?: string): TOML.JsonMap | never {
79
+ try {
80
+ // Normalize CRLF to LF to avoid hitting https://github.com/iarna/iarna-toml/issues/33.
81
+ const normalizedInput = input.replace(/\r\n$/g, "\n");
82
+ return TOML.parse(normalizedInput);
83
+ } catch (err) {
84
+ const { name, message, line, col } = err as TomlError;
85
+ if (name !== TOML_ERROR_NAME) {
86
+ throw err;
87
+ }
88
+ const text = message.substring(0, message.lastIndexOf(TOML_ERROR_SUFFIX));
89
+ const lineText = input.split("\n")[line];
90
+ const location = {
91
+ lineText,
92
+ line: line + 1,
93
+ column: col - 1,
94
+ file,
95
+ fileText: input,
96
+ };
97
+ throw new ParseError({ text, location });
98
+ }
99
+ }
100
+
101
+ const JSON_ERROR_SUFFIX = " in JSON at position ";
102
+
103
+ /**
104
+ * A wrapper around `JSON.parse` that throws a `ParseError`.
105
+ */
106
+ export function parseJSON(input: string, file?: string): any {
107
+ try {
108
+ return JSON.parse(input);
109
+ } catch (err) {
110
+ const { message } = err as Error;
111
+ const index = message.lastIndexOf(JSON_ERROR_SUFFIX);
112
+ if (index < 0) {
113
+ throw err;
114
+ }
115
+ const text = message.substring(0, index);
116
+ const position = parseInt(
117
+ message.substring(index + JSON_ERROR_SUFFIX.length)
118
+ );
119
+ const location = indexLocation({ file, fileText: input }, position);
120
+ throw new ParseError({ text, location });
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Reads a file and parses it based on its type.
126
+ */
127
+ export function readFileSync(file: string): string {
128
+ try {
129
+ return fs.readFileSync(file, { encoding: "utf-8" });
130
+ } catch (err) {
131
+ const { message } = err as Error;
132
+ throw new ParseError({
133
+ text: `Could not read file: ${file}`,
134
+ notes: [
135
+ {
136
+ text: message.replace(file, resolve(file)),
137
+ },
138
+ ],
139
+ });
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Calculates the line and column location from an index.
145
+ */
146
+ export function indexLocation(file: File, index: number): Location {
147
+ let lineText,
148
+ line = 0,
149
+ column = 0,
150
+ cursor = 0;
151
+ const { fileText = "" } = file;
152
+ for (const row of fileText.split("\n")) {
153
+ line++;
154
+ cursor += row.length + 1;
155
+ if (cursor >= index) {
156
+ lineText = row;
157
+ column = row.length - (cursor - index);
158
+ break;
159
+ }
160
+ }
161
+ return { lineText, line, column, ...file };
162
+ }
163
+
164
+ /**
165
+ * Guesses the line and column location of a search query.
166
+ */
167
+ export function searchLocation(file: File, query: unknown): Location {
168
+ let lineText,
169
+ length,
170
+ line = 0,
171
+ column = 0;
172
+ const queryText = String(query);
173
+ const { fileText = "" } = file;
174
+ for (const content of fileText.split("\n")) {
175
+ line++;
176
+ const index = content.indexOf(queryText);
177
+ if (index >= 0) {
178
+ lineText = content;
179
+ column = index;
180
+ length = queryText.length;
181
+ break;
182
+ }
183
+ }
184
+ return { lineText, line, column, length, ...file };
185
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { assert } from "console";
2
+
3
+ type DiscriminatedPath<Discriminator extends string> = string & {
4
+ _discriminator: Discriminator;
5
+ };
6
+
7
+ /**
8
+ * A branded string that expects to be URL compatible.
9
+ *
10
+ * Require this type when you want callers to ensure that they have converted file-path strings into URL-safe paths.
11
+ */
12
+ export type UrlPath = DiscriminatedPath<"UrlPath">;
13
+
14
+ /**
15
+ * Convert a file-path string to a URL-path string.
16
+ *
17
+ * Use this helper to convert a `string` to a `UrlPath` when it is not clear whether the string needs normalizing.
18
+ * Replaces all back-slashes with forward-slashes, and throws an error if the path contains a drive letter (e.g. `C:`).
19
+ */
20
+ export function toUrlPath(path: string): UrlPath {
21
+ assert(
22
+ !/^[a-z]:/i.test(path),
23
+ "Tried to convert a Windows file path with a drive to a URL path."
24
+ );
25
+ return path.replace(/\\/g, "/") as UrlPath;
26
+ }
package/src/proxy.ts ADDED
@@ -0,0 +1,449 @@
1
+ import { createServer as createHttpServer } from "node:http";
2
+ import { connect } from "node:http2";
3
+ import { createServer as createHttpsServer } from "node:https";
4
+ import WebSocket from "faye-websocket";
5
+ import { useEffect, useRef, useState } from "react";
6
+ import serveStatic from "serve-static";
7
+ import { getHttpsOptions } from "./https-options";
8
+ import { logger } from "./logger";
9
+ import type { CfPreviewToken } from "./create-worker-preview";
10
+ import type {
11
+ IncomingHttpHeaders,
12
+ RequestListener,
13
+ IncomingMessage,
14
+ ServerResponse,
15
+ Server as HttpServer,
16
+ } from "node:http";
17
+ import type { ClientHttp2Session, ServerHttp2Stream } from "node:http2";
18
+ import type { Server as HttpsServer } from "node:https";
19
+ import type ws from "ws";
20
+
21
+ interface IWebsocket extends ws {
22
+ // Pipe implements .on("message", ...)
23
+ pipe<T>(fn: T): IWebsocket;
24
+ }
25
+
26
+ /**
27
+ * `usePreviewServer` is a React hook that creates a local development
28
+ * server that can be used to develop a Worker.
29
+ *
30
+ * When we run `wrangler dev`, we start by uploading the compiled worker
31
+ * to the preview service, which responds with a preview token.
32
+ * (see `useWorker`/`createWorker` for details.)
33
+ * We can then use that token to connect to the preview server for a
34
+ * great local development experience. Further, as we change the worker,
35
+ * we can update the preview token transparently without having to restart
36
+ * the development server.
37
+ */
38
+
39
+ /** Rewrite request headers to add the preview token. */
40
+ function addCfPreviewTokenHeader(
41
+ headers: IncomingHttpHeaders,
42
+ previewTokenValue: string
43
+ ) {
44
+ headers["cf-workers-preview-token"] = previewTokenValue;
45
+ }
46
+
47
+ /**
48
+ * Rewrite references in request headers
49
+ * from the preview host to the local host.
50
+ */
51
+ function rewriteRemoteHostToLocalHostInHeaders(
52
+ headers: IncomingHttpHeaders,
53
+ remoteHost: string,
54
+ localPort: number,
55
+ localProtocol: "https" | "http"
56
+ ) {
57
+ for (const [name, value] of Object.entries(headers)) {
58
+ // Rewrite the remote host to the local host.
59
+ if (typeof value === "string" && value.includes(remoteHost)) {
60
+ headers[name] = value
61
+ .replaceAll(
62
+ `https://${remoteHost}`,
63
+ `${localProtocol}://localhost:${localPort}`
64
+ )
65
+ .replaceAll(remoteHost, `localhost:${localPort}`);
66
+ }
67
+ }
68
+ }
69
+
70
+ export function usePreviewServer({
71
+ previewToken,
72
+ publicRoot,
73
+ localProtocol,
74
+ localPort: port,
75
+ ip,
76
+ }: {
77
+ previewToken: CfPreviewToken | undefined;
78
+ publicRoot: string | undefined;
79
+ localProtocol: "https" | "http";
80
+ localPort: number;
81
+ ip: string;
82
+ }) {
83
+ /** Creates an HTTP/1 proxy that sends requests over HTTP/2. */
84
+ const [proxyServer, setProxyServer] = useState<HttpServer | HttpsServer>();
85
+
86
+ /**
87
+ * Create the instance of the local proxy server that will pass on
88
+ * requests to the preview worker.
89
+ */
90
+ useEffect(() => {
91
+ if (proxyServer === undefined) {
92
+ createProxyServer(localProtocol)
93
+ .then((proxy) => setProxyServer(proxy))
94
+ .catch(async (err) => {
95
+ logger.error("Failed to create proxy server:", err);
96
+ });
97
+ }
98
+ }, [proxyServer, localProtocol]);
99
+
100
+ /**
101
+ * When we're not connected / getting a fresh token on changes,
102
+ * we'd like to buffer streams/requests until we're connected.
103
+ * Once connected, we can flush the buffered streams/requests.
104
+ * streamBufferRef is used to buffer http/2 streams, while
105
+ * requestResponseBufferRef is used to buffer http/1 requests.
106
+ */
107
+ const streamBufferRef = useRef<
108
+ { stream: ServerHttp2Stream; headers: IncomingHttpHeaders }[]
109
+ >([]);
110
+ const requestResponseBufferRef = useRef<
111
+ { request: IncomingMessage; response: ServerResponse }[]
112
+ >([]);
113
+
114
+ /**
115
+ * The session doesn't last forever, and will eventually drop
116
+ * (usually within 5-15 minutes). When that happens, we simply
117
+ * restart the effect, effectively restarting the server. We use
118
+ * a state sigil as an effect dependency to do so.
119
+ */
120
+ const [retryServerSetupSigil, setRetryServerSetupSigil] = useState<number>(0);
121
+ function retryServerSetup() {
122
+ setRetryServerSetupSigil((x) => x + 1);
123
+ }
124
+
125
+ useEffect(() => {
126
+ if (proxyServer === undefined) {
127
+ return;
128
+ }
129
+
130
+ // If we don't have a token, that means either we're just starting up,
131
+ // or we're refreshing the token.
132
+ if (!previewToken) {
133
+ const cleanupListeners: (() => void)[] = [];
134
+ const bufferStream = (
135
+ stream: ServerHttp2Stream,
136
+ headers: IncomingHttpHeaders
137
+ ) => {
138
+ // store the stream in a buffer so we can replay it later
139
+ streamBufferRef.current.push({ stream, headers });
140
+ };
141
+ proxyServer.on("stream", bufferStream);
142
+ cleanupListeners.push(() => proxyServer.off("stream", bufferStream));
143
+
144
+ const bufferRequestResponse = (
145
+ request: IncomingMessage,
146
+ response: ServerResponse
147
+ ) => {
148
+ // store the request and response in a buffer so we can replay it later
149
+ requestResponseBufferRef.current.push({ request, response });
150
+ };
151
+
152
+ proxyServer.on("request", bufferRequestResponse);
153
+ cleanupListeners.push(() =>
154
+ proxyServer.off("request", bufferRequestResponse)
155
+ );
156
+ return () => {
157
+ cleanupListeners.forEach((cleanup) => cleanup());
158
+ };
159
+ }
160
+
161
+ // We have a token. Let's proxy requests to the preview end point.
162
+ const cleanupListeners: (() => void)[] = [];
163
+
164
+ const assetPath = typeof publicRoot === "string" ? publicRoot : null;
165
+
166
+ // create a ClientHttp2Session
167
+ const remote = connect(`https://${previewToken.host}`);
168
+ cleanupListeners.push(() => remote.destroy());
169
+
170
+ // As mentioned above, the session may die at any point,
171
+ // so we need to restart the effect.
172
+ remote.on("close", retryServerSetup);
173
+ cleanupListeners.push(() => remote.off("close", retryServerSetup));
174
+
175
+ /** HTTP/2 -> HTTP/2 */
176
+ const handleStream = createStreamHandler(
177
+ previewToken,
178
+ remote,
179
+ port,
180
+ localProtocol
181
+ );
182
+ proxyServer.on("stream", handleStream);
183
+ cleanupListeners.push(() => proxyServer.off("stream", handleStream));
184
+
185
+ // flush and replay buffered streams
186
+ streamBufferRef.current.forEach((buffer) =>
187
+ handleStream(buffer.stream, buffer.headers)
188
+ );
189
+ streamBufferRef.current = [];
190
+
191
+ /** HTTP/1 -> HTTP/2 */
192
+ const handleRequest: RequestListener = (
193
+ message: IncomingMessage,
194
+ response: ServerResponse
195
+ ) => {
196
+ const { httpVersionMajor, headers, method, url } = message;
197
+ if (httpVersionMajor >= 2) {
198
+ return; // Already handled by the "stream" event.
199
+ }
200
+ addCfPreviewTokenHeader(headers, previewToken.value);
201
+ headers[":method"] = method;
202
+ headers[":path"] = url;
203
+ headers[":authority"] = previewToken.host;
204
+ headers[":scheme"] = "https";
205
+ for (const name of Object.keys(headers)) {
206
+ if (HTTP1_HEADERS.has(name.toLowerCase())) {
207
+ delete headers[name];
208
+ }
209
+ }
210
+ const request = message.pipe(remote.request(headers));
211
+ request.on("response", (responseHeaders) => {
212
+ const status = responseHeaders[":status"] ?? 500;
213
+
214
+ // log all requests to terminal
215
+ logger.log(new Date().toLocaleTimeString(), method, url, status);
216
+
217
+ rewriteRemoteHostToLocalHostInHeaders(
218
+ responseHeaders,
219
+ previewToken.host,
220
+ port,
221
+ localProtocol
222
+ );
223
+ for (const name of Object.keys(responseHeaders)) {
224
+ if (name.startsWith(":")) {
225
+ delete responseHeaders[name];
226
+ }
227
+ }
228
+ response.writeHead(status, responseHeaders);
229
+ request.pipe(response, { end: true });
230
+ });
231
+ };
232
+
233
+ // If an asset path is defined, check the file system
234
+ // for a file first and serve if it exists.
235
+ const actualHandleRequest = assetPath
236
+ ? createHandleAssetsRequest(assetPath, handleRequest)
237
+ : handleRequest;
238
+
239
+ proxyServer.on("request", actualHandleRequest);
240
+ cleanupListeners.push(() =>
241
+ proxyServer.off("request", actualHandleRequest)
242
+ );
243
+
244
+ // flush and replay buffered requests
245
+ requestResponseBufferRef.current.forEach(({ request, response }) =>
246
+ actualHandleRequest(request, response)
247
+ );
248
+ requestResponseBufferRef.current = [];
249
+
250
+ /** HTTP/1 -> WebSocket (over HTTP/1) */
251
+ const handleUpgrade = (
252
+ message: IncomingMessage,
253
+ socket: WebSocket,
254
+ body: Buffer
255
+ ) => {
256
+ const { headers, url } = message;
257
+ addCfPreviewTokenHeader(headers, previewToken.value);
258
+ headers["host"] = previewToken.host;
259
+ const localWebsocket = new WebSocket(message, socket, body) as IWebsocket;
260
+ // TODO(soon): Custom WebSocket protocol is not working?
261
+ const remoteWebsocketClient = new WebSocket.Client(
262
+ `wss://${previewToken.host}${url}`,
263
+ [],
264
+ { headers }
265
+ ) as IWebsocket;
266
+ localWebsocket.pipe(remoteWebsocketClient).pipe(localWebsocket);
267
+ // We close down websockets whenever we refresh the token.
268
+ cleanupListeners.push(() => {
269
+ localWebsocket.close();
270
+ remoteWebsocketClient.close();
271
+ });
272
+ };
273
+ proxyServer.on("upgrade", handleUpgrade);
274
+ cleanupListeners.push(() => proxyServer.off("upgrade", handleUpgrade));
275
+
276
+ return () => {
277
+ cleanupListeners.forEach((cleanup) => cleanup());
278
+ };
279
+ }, [
280
+ previewToken,
281
+ publicRoot,
282
+ port,
283
+ localProtocol,
284
+ proxyServer,
285
+ // We use a state value as a sigil to trigger reconnecting the server.
286
+ // It's not used inside the effect, so react-hooks/exhaustive-deps
287
+ // doesn't complain if it's not included in the dependency array.
288
+ // But its presence is critical, so Do NOT remove it from the dependency list.
289
+ retryServerSetupSigil,
290
+ ]);
291
+
292
+ // Start/stop the server whenever the
293
+ // containing component is mounted/unmounted.
294
+ useEffect(() => {
295
+ const abortController = new AbortController();
296
+ if (proxyServer === undefined) {
297
+ return;
298
+ }
299
+
300
+ waitForPortToBeAvailable(port, {
301
+ retryPeriod: 200,
302
+ timeout: 2000,
303
+ abortSignal: abortController.signal,
304
+ })
305
+ .then(() => {
306
+ proxyServer.listen(port, ip);
307
+ logger.log(`⬣ Listening at ${localProtocol}://${ip}:${port}`);
308
+ })
309
+ .catch((err) => {
310
+ if ((err as { code: string }).code !== "ABORT_ERR") {
311
+ logger.error(`Failed to start server: ${err}`);
312
+ }
313
+ });
314
+
315
+ return () => {
316
+ proxyServer.close();
317
+ abortController.abort();
318
+ };
319
+ }, [port, ip, proxyServer, localProtocol]);
320
+ }
321
+
322
+ function createHandleAssetsRequest(
323
+ assetPath: string,
324
+ handleRequest: RequestListener
325
+ ) {
326
+ const handleAsset = serveStatic(assetPath, {
327
+ cacheControl: false,
328
+ });
329
+ return (request: IncomingMessage, response: ServerResponse) => {
330
+ handleAsset(request, response, () => {
331
+ handleRequest(request, response);
332
+ });
333
+ };
334
+ }
335
+
336
+ /** A Set of headers we want to remove from HTTP/1 requests. */
337
+ const HTTP1_HEADERS = new Set([
338
+ "host",
339
+ "connection",
340
+ "upgrade",
341
+ "keep-alive",
342
+ "proxy-connection",
343
+ "transfer-encoding",
344
+ "http2-settings",
345
+ ]);
346
+
347
+ async function createProxyServer(
348
+ localProtocol: "https" | "http"
349
+ ): Promise<HttpServer | HttpsServer> {
350
+ const server: HttpServer | HttpsServer =
351
+ localProtocol === "https"
352
+ ? createHttpsServer(await getHttpsOptions())
353
+ : createHttpServer();
354
+
355
+ return server
356
+ .on("upgrade", (req) => {
357
+ // log all websocket connections
358
+ logger.log(
359
+ new Date().toLocaleTimeString(),
360
+ req.method,
361
+ req.url,
362
+ 101,
363
+ "(WebSocket)"
364
+ );
365
+ })
366
+ .on("error", (err) => {
367
+ // log all connection errors
368
+ logger.error(new Date().toLocaleTimeString(), err);
369
+ });
370
+ }
371
+
372
+ function createStreamHandler(
373
+ previewToken: CfPreviewToken,
374
+ remote: ClientHttp2Session,
375
+ localPort: number,
376
+ localProtocol: "https" | "http"
377
+ ) {
378
+ return function handleStream(
379
+ stream: ServerHttp2Stream,
380
+ headers: IncomingHttpHeaders
381
+ ) {
382
+ addCfPreviewTokenHeader(headers, previewToken.value);
383
+ headers[":authority"] = previewToken.host;
384
+ const request = stream.pipe(remote.request(headers));
385
+ request.on("response", (responseHeaders: IncomingHttpHeaders) => {
386
+ rewriteRemoteHostToLocalHostInHeaders(
387
+ responseHeaders,
388
+ previewToken.host,
389
+ localPort,
390
+ localProtocol
391
+ );
392
+ stream.respond(responseHeaders);
393
+ request.pipe(stream, { end: true });
394
+ });
395
+ };
396
+ }
397
+
398
+ /**
399
+ * A helper function that waits for a port to be available.
400
+ */
401
+ export async function waitForPortToBeAvailable(
402
+ port: number,
403
+ options: { retryPeriod: number; timeout: number; abortSignal: AbortSignal }
404
+ ): Promise<void> {
405
+ return new Promise((resolve, reject) => {
406
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
407
+ (options.abortSignal as any).addEventListener("abort", () => {
408
+ const abortError = new Error("waitForPortToBeAvailable() aborted");
409
+ (abortError as Error & { code: string }).code = "ABORT_ERR";
410
+ doReject(abortError);
411
+ });
412
+
413
+ const timeout = setTimeout(() => {
414
+ doReject(new Error(`Timed out waiting for port ${port}`));
415
+ }, options.timeout);
416
+
417
+ const interval = setInterval(checkPort, options.retryPeriod);
418
+ checkPort();
419
+
420
+ function doResolve() {
421
+ clearTimeout(timeout);
422
+ clearInterval(interval);
423
+ resolve();
424
+ }
425
+
426
+ function doReject(err: unknown) {
427
+ clearInterval(interval);
428
+ clearTimeout(timeout);
429
+ reject(err);
430
+ }
431
+
432
+ function checkPort() {
433
+ // Testing whether a port is 'available' involves simply
434
+ // trying to make a server listen on that port, and retrying
435
+ // until it succeeds.
436
+ const server = createHttpServer();
437
+ server.on("error", (err) => {
438
+ // @ts-expect-error non standard property on Error
439
+ if (err.code !== "EADDRINUSE") {
440
+ doReject(err);
441
+ }
442
+ });
443
+ server.listen(port, () => {
444
+ server.close();
445
+ doResolve();
446
+ });
447
+ }
448
+ });
449
+ }