wrangler 0.0.0-e6733a3 → 0.0.0-e88a54e
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.
- package/bin/wrangler.js +2 -2
- package/miniflare-dist/index.mjs +79 -0
- package/miniflare-dist/index.mjs.map +7 -0
- package/package.json +35 -16
- package/pages/functions/buildWorker.ts +1 -1
- package/pages/functions/filepath-routing.test.ts +212 -28
- package/pages/functions/filepath-routing.ts +91 -131
- package/pages/functions/routes.ts +11 -18
- package/pages/functions/template-worker.ts +19 -33
- package/src/__tests__/configuration.test.ts +2796 -0
- package/src/__tests__/dev.test.tsx +488 -58
- package/src/__tests__/dev2.test.tsx +154 -0
- package/src/__tests__/guess-worker-format.test.ts +58 -0
- package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
- package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
- package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
- package/src/__tests__/helpers/mock-account-id.ts +48 -0
- package/src/__tests__/helpers/mock-bin.ts +36 -0
- package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +55 -19
- package/src/__tests__/helpers/mock-console.ts +70 -0
- package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
- package/src/__tests__/helpers/mock-kv.ts +33 -0
- package/src/__tests__/helpers/mock-stdin.ts +103 -0
- package/src/__tests__/helpers/mock-web-socket.ts +29 -0
- package/src/__tests__/helpers/run-in-tmp.ts +32 -0
- package/src/__tests__/helpers/run-wrangler.ts +16 -0
- package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
- package/src/__tests__/https-options.test.ts +127 -0
- package/src/__tests__/index.test.ts +779 -75
- package/src/__tests__/jest.setup.ts +53 -6
- package/src/__tests__/kv.test.ts +738 -454
- package/src/__tests__/logout.test.ts +52 -0
- package/src/__tests__/package-manager.test.ts +206 -0
- package/src/__tests__/pages.test.ts +44 -0
- package/src/__tests__/parse.test.ts +322 -0
- package/src/__tests__/publish.test.ts +2704 -0
- package/src/__tests__/r2.test.ts +198 -0
- package/src/__tests__/route.test.ts +45 -0
- package/src/__tests__/secret.test.ts +425 -0
- package/src/__tests__/sentry.test.ts +146 -0
- package/src/__tests__/tail.test.ts +564 -0
- package/src/__tests__/whoami.test.tsx +100 -0
- package/src/bundle.ts +142 -0
- package/src/cfetch/index.ts +21 -19
- package/src/cfetch/internal.ts +94 -24
- package/src/cli.ts +10 -0
- package/src/config/README.md +107 -0
- package/src/config/config.ts +218 -0
- package/src/config/diagnostics.ts +80 -0
- package/src/config/environment.ts +366 -0
- package/src/config/index.ts +62 -0
- package/src/config/validation-helpers.ts +486 -0
- package/src/config/validation.ts +1090 -0
- package/src/{api/preview.ts → create-worker-preview.ts} +61 -23
- package/src/create-worker-upload-form.ts +217 -0
- package/src/dev/dev.tsx +364 -0
- package/src/dev/local.tsx +232 -0
- package/src/dev/remote.tsx +203 -0
- package/src/dev/use-esbuild.ts +100 -0
- package/src/dialogs.tsx +2 -2
- package/src/entry.ts +208 -0
- package/src/environment-variables.ts +33 -0
- package/src/https-options.ts +122 -0
- package/src/index.tsx +1198 -799
- package/src/inspect.ts +159 -66
- package/src/{kv.tsx → kv.ts} +117 -65
- package/src/miniflare-cli/README.md +30 -0
- package/src/miniflare-cli/enum-keys.ts +17 -0
- package/src/miniflare-cli/index.ts +37 -0
- package/src/module-collection.ts +229 -35
- package/src/open-in-browser.ts +25 -0
- package/src/package-manager.ts +126 -0
- package/src/pages.tsx +58 -42
- package/src/parse.ts +183 -0
- package/src/paths.ts +26 -0
- package/src/proxy.ts +224 -78
- package/src/publish.ts +281 -292
- package/src/r2.ts +50 -0
- package/src/reporting.ts +131 -0
- package/src/selfsigned.d.ts +29 -0
- package/src/sites.tsx +224 -58
- package/src/tail/filters.ts +279 -0
- package/src/tail/index.ts +299 -0
- package/src/tail/printing.ts +62 -0
- package/src/user.tsx +273 -180
- package/src/whoami.tsx +69 -0
- package/src/{api/worker.ts → worker.ts} +45 -37
- package/templates/new-worker.js +15 -0
- package/templates/new-worker.ts +15 -0
- package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
- package/templates/tsconfig.json +105 -0
- package/wrangler-dist/cli.js +130612 -112486
- package/wrangler-dist/cli.js.map +3 -3
- package/src/__tests__/run-in-tmp.ts +0 -19
- package/src/__tests__/run-wrangler.ts +0 -32
- package/src/api/form_data.ts +0 -131
- package/src/config.ts +0 -487
- package/src/dev.tsx +0 -771
- package/src/tail.tsx +0 -73
package/src/parse.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
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): object {
|
|
79
|
+
try {
|
|
80
|
+
return TOML.parse(input);
|
|
81
|
+
} catch (err) {
|
|
82
|
+
const { name, message, line, col } = err as TomlError;
|
|
83
|
+
if (name !== TOML_ERROR_NAME) {
|
|
84
|
+
throw err;
|
|
85
|
+
}
|
|
86
|
+
const text = message.substring(0, message.lastIndexOf(TOML_ERROR_SUFFIX));
|
|
87
|
+
const lineText = input.split("\n")[line];
|
|
88
|
+
const location = {
|
|
89
|
+
lineText,
|
|
90
|
+
line: line + 1,
|
|
91
|
+
column: col - 1,
|
|
92
|
+
file,
|
|
93
|
+
fileText: input,
|
|
94
|
+
};
|
|
95
|
+
throw new ParseError({ text, location });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const JSON_ERROR_SUFFIX = " in JSON at position ";
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* A wrapper around `JSON.parse` that throws a `ParseError`.
|
|
103
|
+
*/
|
|
104
|
+
export function parseJSON(input: string, file?: string): any {
|
|
105
|
+
try {
|
|
106
|
+
return JSON.parse(input);
|
|
107
|
+
} catch (err) {
|
|
108
|
+
const { message } = err as Error;
|
|
109
|
+
const index = message.lastIndexOf(JSON_ERROR_SUFFIX);
|
|
110
|
+
if (index < 0) {
|
|
111
|
+
throw err;
|
|
112
|
+
}
|
|
113
|
+
const text = message.substring(0, index);
|
|
114
|
+
const position = parseInt(
|
|
115
|
+
message.substring(index + JSON_ERROR_SUFFIX.length)
|
|
116
|
+
);
|
|
117
|
+
const location = indexLocation({ file, fileText: input }, position);
|
|
118
|
+
throw new ParseError({ text, location });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Reads a file and parses it based on its type.
|
|
124
|
+
*/
|
|
125
|
+
export function readFileSync(file: string): string {
|
|
126
|
+
try {
|
|
127
|
+
return fs.readFileSync(file, { encoding: "utf-8" });
|
|
128
|
+
} catch (err) {
|
|
129
|
+
const { message } = err as Error;
|
|
130
|
+
throw new ParseError({
|
|
131
|
+
text: `Could not read file: ${file}`,
|
|
132
|
+
notes: [
|
|
133
|
+
{
|
|
134
|
+
text: message.replace(file, resolve(file)),
|
|
135
|
+
},
|
|
136
|
+
],
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Calculates the line and column location from an index.
|
|
143
|
+
*/
|
|
144
|
+
export function indexLocation(file: File, index: number): Location {
|
|
145
|
+
let lineText,
|
|
146
|
+
line = 0,
|
|
147
|
+
column = 0,
|
|
148
|
+
cursor = 0;
|
|
149
|
+
const { fileText = "" } = file;
|
|
150
|
+
for (const row of fileText.split("\n")) {
|
|
151
|
+
line++;
|
|
152
|
+
cursor += row.length + 1;
|
|
153
|
+
if (cursor >= index) {
|
|
154
|
+
lineText = row;
|
|
155
|
+
column = row.length - (cursor - index);
|
|
156
|
+
break;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return { lineText, line, column, ...file };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Guesses the line and column location of a search query.
|
|
164
|
+
*/
|
|
165
|
+
export function searchLocation(file: File, query: unknown): Location {
|
|
166
|
+
let lineText,
|
|
167
|
+
length,
|
|
168
|
+
line = 0,
|
|
169
|
+
column = 0;
|
|
170
|
+
const queryText = String(query);
|
|
171
|
+
const { fileText = "" } = file;
|
|
172
|
+
for (const content of fileText.split("\n")) {
|
|
173
|
+
line++;
|
|
174
|
+
const index = content.indexOf(queryText);
|
|
175
|
+
if (index >= 0) {
|
|
176
|
+
lineText = content;
|
|
177
|
+
column = index;
|
|
178
|
+
length = queryText.length;
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return { lineText, line, column, length, ...file };
|
|
183
|
+
}
|
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
CHANGED
|
@@ -1,17 +1,27 @@
|
|
|
1
|
+
import { createServer as createHttpServer } from "node:http";
|
|
1
2
|
import { connect } from "node:http2";
|
|
2
|
-
import
|
|
3
|
-
import
|
|
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 { reportError } from "./reporting";
|
|
9
|
+
import type { CfPreviewToken } from "./create-worker-preview";
|
|
4
10
|
import type {
|
|
5
11
|
IncomingHttpHeaders,
|
|
6
12
|
RequestListener,
|
|
7
13
|
IncomingMessage,
|
|
8
14
|
ServerResponse,
|
|
9
|
-
Server,
|
|
15
|
+
Server as HttpServer,
|
|
10
16
|
} from "node:http";
|
|
11
|
-
import
|
|
12
|
-
import
|
|
13
|
-
import type
|
|
14
|
-
|
|
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
|
+
}
|
|
15
25
|
|
|
16
26
|
/**
|
|
17
27
|
* `usePreviewServer` is a React hook that creates a local development
|
|
@@ -41,13 +51,17 @@ function addCfPreviewTokenHeader(
|
|
|
41
51
|
function rewriteRemoteHostToLocalHostInHeaders(
|
|
42
52
|
headers: IncomingHttpHeaders,
|
|
43
53
|
remoteHost: string,
|
|
44
|
-
localPort: number
|
|
54
|
+
localPort: number,
|
|
55
|
+
localProtocol: "https" | "http"
|
|
45
56
|
) {
|
|
46
57
|
for (const [name, value] of Object.entries(headers)) {
|
|
47
58
|
// Rewrite the remote host to the local host.
|
|
48
59
|
if (typeof value === "string" && value.includes(remoteHost)) {
|
|
49
60
|
headers[name] = value
|
|
50
|
-
.replaceAll(
|
|
61
|
+
.replaceAll(
|
|
62
|
+
`https://${remoteHost}`,
|
|
63
|
+
`${localProtocol}://localhost:${localPort}`
|
|
64
|
+
)
|
|
51
65
|
.replaceAll(remoteHost, `localhost:${localPort}`);
|
|
52
66
|
}
|
|
53
67
|
}
|
|
@@ -56,40 +70,33 @@ function rewriteRemoteHostToLocalHostInHeaders(
|
|
|
56
70
|
export function usePreviewServer({
|
|
57
71
|
previewToken,
|
|
58
72
|
publicRoot,
|
|
59
|
-
|
|
73
|
+
localProtocol,
|
|
74
|
+
localPort: port,
|
|
75
|
+
ip,
|
|
60
76
|
}: {
|
|
61
77
|
previewToken: CfPreviewToken | undefined;
|
|
62
78
|
publicRoot: undefined | string;
|
|
63
|
-
|
|
79
|
+
localProtocol: "https" | "http";
|
|
80
|
+
localPort: number;
|
|
81
|
+
ip: string;
|
|
64
82
|
}) {
|
|
65
83
|
/** Creates an HTTP/1 proxy that sends requests over HTTP/2. */
|
|
66
|
-
const proxyServer =
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
)
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
req.method,
|
|
83
|
-
req.url,
|
|
84
|
-
101,
|
|
85
|
-
"(WebSocket)"
|
|
86
|
-
);
|
|
87
|
-
})
|
|
88
|
-
.on("error", (err) => {
|
|
89
|
-
// log all connection errors
|
|
90
|
-
console.error(new Date().toLocaleTimeString(), err);
|
|
91
|
-
});
|
|
92
|
-
}
|
|
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
|
+
console.error("Failed to create proxy server.", err);
|
|
96
|
+
await reportError(err);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}, [proxyServer, localProtocol]);
|
|
93
100
|
|
|
94
101
|
/**
|
|
95
102
|
* When we're not connected / getting a fresh token on changes,
|
|
@@ -105,8 +112,21 @@ export function usePreviewServer({
|
|
|
105
112
|
{ request: IncomingMessage; response: ServerResponse }[]
|
|
106
113
|
>([]);
|
|
107
114
|
|
|
115
|
+
/**
|
|
116
|
+
* The session doesn't last forever, and will eventually drop
|
|
117
|
+
* (usually within 5-15 minutes). When that happens, we simply
|
|
118
|
+
* restart the effect, effectively restarting the server. We use
|
|
119
|
+
* a state sigil as an effect dependency to do so.
|
|
120
|
+
*/
|
|
121
|
+
const [retryServerSetupSigil, setRetryServerSetupSigil] = useState<number>(0);
|
|
122
|
+
function retryServerSetup() {
|
|
123
|
+
setRetryServerSetupSigil((x) => x + 1);
|
|
124
|
+
}
|
|
125
|
+
|
|
108
126
|
useEffect(() => {
|
|
109
|
-
|
|
127
|
+
if (proxyServer === undefined) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
110
130
|
|
|
111
131
|
// If we don't have a token, that means either we're just starting up,
|
|
112
132
|
// or we're refreshing the token.
|
|
@@ -119,8 +139,8 @@ export function usePreviewServer({
|
|
|
119
139
|
// store the stream in a buffer so we can replay it later
|
|
120
140
|
streamBufferRef.current.push({ stream, headers });
|
|
121
141
|
};
|
|
122
|
-
|
|
123
|
-
cleanupListeners.push(() =>
|
|
142
|
+
proxyServer.on("stream", bufferStream);
|
|
143
|
+
cleanupListeners.push(() => proxyServer.off("stream", bufferStream));
|
|
124
144
|
|
|
125
145
|
const bufferRequestResponse = (
|
|
126
146
|
request: IncomingMessage,
|
|
@@ -130,8 +150,10 @@ export function usePreviewServer({
|
|
|
130
150
|
requestResponseBufferRef.current.push({ request, response });
|
|
131
151
|
};
|
|
132
152
|
|
|
133
|
-
|
|
134
|
-
cleanupListeners.push(() =>
|
|
153
|
+
proxyServer.on("request", bufferRequestResponse);
|
|
154
|
+
cleanupListeners.push(() =>
|
|
155
|
+
proxyServer.off("request", bufferRequestResponse)
|
|
156
|
+
);
|
|
135
157
|
return () => {
|
|
136
158
|
cleanupListeners.forEach((cleanup) => cleanup());
|
|
137
159
|
};
|
|
@@ -146,26 +168,20 @@ export function usePreviewServer({
|
|
|
146
168
|
const remote = connect(`https://${previewToken.host}`);
|
|
147
169
|
cleanupListeners.push(() => remote.destroy());
|
|
148
170
|
|
|
171
|
+
// As mentioned above, the session may die at any point,
|
|
172
|
+
// so we need to restart the effect.
|
|
173
|
+
remote.on("close", retryServerSetup);
|
|
174
|
+
cleanupListeners.push(() => remote.off("close", retryServerSetup));
|
|
175
|
+
|
|
149
176
|
/** HTTP/2 -> HTTP/2 */
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
rewriteRemoteHostToLocalHostInHeaders(
|
|
159
|
-
responseHeaders,
|
|
160
|
-
previewToken.host,
|
|
161
|
-
port
|
|
162
|
-
);
|
|
163
|
-
stream.respond(responseHeaders);
|
|
164
|
-
request.pipe(stream, { end: true });
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
proxy.on("stream", handleStream);
|
|
168
|
-
cleanupListeners.push(() => proxy.off("stream", handleStream));
|
|
177
|
+
const handleStream = createStreamHandler(
|
|
178
|
+
previewToken,
|
|
179
|
+
remote,
|
|
180
|
+
port,
|
|
181
|
+
localProtocol
|
|
182
|
+
);
|
|
183
|
+
proxyServer.on("stream", handleStream);
|
|
184
|
+
cleanupListeners.push(() => proxyServer.off("stream", handleStream));
|
|
169
185
|
|
|
170
186
|
// flush and replay buffered streams
|
|
171
187
|
streamBufferRef.current.forEach((buffer) =>
|
|
@@ -194,11 +210,12 @@ export function usePreviewServer({
|
|
|
194
210
|
}
|
|
195
211
|
const request = message.pipe(remote.request(headers));
|
|
196
212
|
request.on("response", (responseHeaders) => {
|
|
197
|
-
const status = responseHeaders[":status"];
|
|
213
|
+
const status = responseHeaders[":status"] ?? 500;
|
|
198
214
|
rewriteRemoteHostToLocalHostInHeaders(
|
|
199
215
|
responseHeaders,
|
|
200
216
|
previewToken.host,
|
|
201
|
-
port
|
|
217
|
+
port,
|
|
218
|
+
localProtocol
|
|
202
219
|
);
|
|
203
220
|
for (const name of Object.keys(responseHeaders)) {
|
|
204
221
|
if (name.startsWith(":")) {
|
|
@@ -216,8 +233,10 @@ export function usePreviewServer({
|
|
|
216
233
|
? createHandleAssetsRequest(assetPath, handleRequest)
|
|
217
234
|
: handleRequest;
|
|
218
235
|
|
|
219
|
-
|
|
220
|
-
cleanupListeners.push(() =>
|
|
236
|
+
proxyServer.on("request", actualHandleRequest);
|
|
237
|
+
cleanupListeners.push(() =>
|
|
238
|
+
proxyServer.off("request", actualHandleRequest)
|
|
239
|
+
);
|
|
221
240
|
|
|
222
241
|
// flush and replay buffered requests
|
|
223
242
|
requestResponseBufferRef.current.forEach(({ request, response }) =>
|
|
@@ -234,38 +253,59 @@ export function usePreviewServer({
|
|
|
234
253
|
const { headers, url } = message;
|
|
235
254
|
addCfPreviewTokenHeader(headers, previewToken.value);
|
|
236
255
|
headers["host"] = previewToken.host;
|
|
237
|
-
const localWebsocket = new WebSocket(message, socket, body);
|
|
256
|
+
const localWebsocket = new WebSocket(message, socket, body) as IWebsocket;
|
|
238
257
|
// TODO(soon): Custom WebSocket protocol is not working?
|
|
239
258
|
const remoteWebsocketClient = new WebSocket.Client(
|
|
240
259
|
`wss://${previewToken.host}${url}`,
|
|
241
260
|
[],
|
|
242
261
|
{ headers }
|
|
243
|
-
);
|
|
262
|
+
) as IWebsocket;
|
|
244
263
|
localWebsocket.pipe(remoteWebsocketClient).pipe(localWebsocket);
|
|
245
264
|
// We close down websockets whenever we refresh the token.
|
|
246
265
|
cleanupListeners.push(() => {
|
|
247
|
-
localWebsocket.
|
|
248
|
-
remoteWebsocketClient.
|
|
266
|
+
localWebsocket.close();
|
|
267
|
+
remoteWebsocketClient.close();
|
|
249
268
|
});
|
|
250
269
|
};
|
|
251
|
-
|
|
252
|
-
cleanupListeners.push(() =>
|
|
270
|
+
proxyServer.on("upgrade", handleUpgrade);
|
|
271
|
+
cleanupListeners.push(() => proxyServer.off("upgrade", handleUpgrade));
|
|
253
272
|
|
|
254
273
|
return () => {
|
|
255
|
-
cleanupListeners.forEach((
|
|
274
|
+
cleanupListeners.forEach((cleanup) => cleanup());
|
|
256
275
|
};
|
|
257
|
-
}, [
|
|
276
|
+
}, [
|
|
277
|
+
previewToken,
|
|
278
|
+
publicRoot,
|
|
279
|
+
port,
|
|
280
|
+
localProtocol,
|
|
281
|
+
proxyServer,
|
|
282
|
+
// We use a state value as a sigil to trigger reconnecting the server.
|
|
283
|
+
// It's not used inside the effect, so react-hooks/exhaustive-deps
|
|
284
|
+
// doesn't complain if it's not included in the dependency array.
|
|
285
|
+
// But its presence is critical, so Do NOT remove it from the dependency list.
|
|
286
|
+
retryServerSetupSigil,
|
|
287
|
+
]);
|
|
258
288
|
|
|
259
289
|
// Start/stop the server whenever the
|
|
260
290
|
// containing component is mounted/unmounted.
|
|
261
291
|
useEffect(() => {
|
|
262
|
-
proxyServer
|
|
263
|
-
|
|
292
|
+
if (proxyServer === undefined) {
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 })
|
|
297
|
+
.then(() => {
|
|
298
|
+
proxyServer.listen(port, ip);
|
|
299
|
+
console.log(`⬣ Listening at ${localProtocol}://${ip}:${port}`);
|
|
300
|
+
})
|
|
301
|
+
.catch((err) => {
|
|
302
|
+
console.error(`⬣ Failed to start server: ${err}`);
|
|
303
|
+
});
|
|
264
304
|
|
|
265
305
|
return () => {
|
|
266
|
-
proxyServer.
|
|
306
|
+
proxyServer.close();
|
|
267
307
|
};
|
|
268
|
-
}, [port]);
|
|
308
|
+
}, [port, ip, proxyServer, localProtocol]);
|
|
269
309
|
}
|
|
270
310
|
|
|
271
311
|
function createHandleAssetsRequest(
|
|
@@ -292,3 +332,109 @@ const HTTP1_HEADERS = new Set([
|
|
|
292
332
|
"transfer-encoding",
|
|
293
333
|
"http2-settings",
|
|
294
334
|
]);
|
|
335
|
+
|
|
336
|
+
async function createProxyServer(
|
|
337
|
+
localProtocol: "https" | "http"
|
|
338
|
+
): Promise<HttpServer | HttpsServer> {
|
|
339
|
+
const server: HttpServer | HttpsServer =
|
|
340
|
+
localProtocol === "https"
|
|
341
|
+
? createHttpsServer(await getHttpsOptions())
|
|
342
|
+
: createHttpServer();
|
|
343
|
+
|
|
344
|
+
return server
|
|
345
|
+
.on("request", function (req, res) {
|
|
346
|
+
// log all requests
|
|
347
|
+
console.log(
|
|
348
|
+
new Date().toLocaleTimeString(),
|
|
349
|
+
req.method,
|
|
350
|
+
req.url,
|
|
351
|
+
res.statusCode
|
|
352
|
+
);
|
|
353
|
+
})
|
|
354
|
+
.on("upgrade", (req) => {
|
|
355
|
+
// log all websocket connections
|
|
356
|
+
console.log(
|
|
357
|
+
new Date().toLocaleTimeString(),
|
|
358
|
+
req.method,
|
|
359
|
+
req.url,
|
|
360
|
+
101,
|
|
361
|
+
"(WebSocket)"
|
|
362
|
+
);
|
|
363
|
+
})
|
|
364
|
+
.on("error", (err) => {
|
|
365
|
+
// log all connection errors
|
|
366
|
+
console.error(new Date().toLocaleTimeString(), err);
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function createStreamHandler(
|
|
371
|
+
previewToken: CfPreviewToken,
|
|
372
|
+
remote: ClientHttp2Session,
|
|
373
|
+
localPort: number,
|
|
374
|
+
localProtocol: "https" | "http"
|
|
375
|
+
) {
|
|
376
|
+
return function handleStream(
|
|
377
|
+
stream: ServerHttp2Stream,
|
|
378
|
+
headers: IncomingHttpHeaders
|
|
379
|
+
) {
|
|
380
|
+
addCfPreviewTokenHeader(headers, previewToken.value);
|
|
381
|
+
headers[":authority"] = previewToken.host;
|
|
382
|
+
const request = stream.pipe(remote.request(headers));
|
|
383
|
+
request.on("response", (responseHeaders: IncomingHttpHeaders) => {
|
|
384
|
+
rewriteRemoteHostToLocalHostInHeaders(
|
|
385
|
+
responseHeaders,
|
|
386
|
+
previewToken.host,
|
|
387
|
+
localPort,
|
|
388
|
+
localProtocol
|
|
389
|
+
);
|
|
390
|
+
stream.respond(responseHeaders);
|
|
391
|
+
request.pipe(stream, { end: true });
|
|
392
|
+
});
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* A helper function that waits for a port to be available.
|
|
398
|
+
*/
|
|
399
|
+
export async function waitForPortToBeAvailable(
|
|
400
|
+
port: number,
|
|
401
|
+
options: { retryPeriod: number; timeout: number }
|
|
402
|
+
): Promise<void> {
|
|
403
|
+
return new Promise((resolve, reject) => {
|
|
404
|
+
const timeout = setTimeout(() => {
|
|
405
|
+
doReject(new Error(`Timed out waiting for port ${port}`));
|
|
406
|
+
}, options.timeout);
|
|
407
|
+
|
|
408
|
+
const interval = setInterval(checkPort, options.retryPeriod);
|
|
409
|
+
checkPort();
|
|
410
|
+
|
|
411
|
+
function doResolve() {
|
|
412
|
+
clearTimeout(timeout);
|
|
413
|
+
clearInterval(interval);
|
|
414
|
+
resolve();
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function doReject(err: unknown) {
|
|
418
|
+
clearInterval(interval);
|
|
419
|
+
clearTimeout(timeout);
|
|
420
|
+
reject(err);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function checkPort() {
|
|
424
|
+
// Testing whether a port is 'available' involves simply
|
|
425
|
+
// trying to make a server listen on that port, and retrying
|
|
426
|
+
// until it succeeds.
|
|
427
|
+
const server = createHttpServer();
|
|
428
|
+
server.on("error", (err) => {
|
|
429
|
+
// @ts-expect-error non standard property on Error
|
|
430
|
+
if (err.code !== "EADDRINUSE") {
|
|
431
|
+
doReject(err);
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
server.listen(port, () => {
|
|
435
|
+
server.close();
|
|
436
|
+
doResolve();
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
}
|