wrangler 0.0.0-e22f9d7 → 0.0.0-e273e09
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/Cloudflare_CA.pem +18 -0
- package/README.md +27 -14
- package/bin/wrangler.js +48 -4
- package/miniflare-dist/index.mjs +4886 -0
- package/package.json +60 -31
- package/pages/functions/buildPlugin.ts +105 -0
- package/pages/functions/buildWorker.ts +93 -4
- package/pages/functions/filepath-routing.test.ts +223 -28
- package/pages/functions/filepath-routing.ts +100 -132
- package/pages/functions/routes.ts +16 -18
- package/pages/functions/template-plugin.ts +147 -0
- package/pages/functions/template-worker.ts +37 -38
- package/src/__tests__/config-cache.test.ts +36 -0
- package/src/__tests__/configuration.test.ts +3487 -0
- package/src/__tests__/dev.test.tsx +977 -61
- package/src/__tests__/guess-worker-format.test.ts +85 -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} +56 -16
- package/src/__tests__/helpers/mock-console.ts +87 -0
- package/src/__tests__/helpers/mock-dialogs.ts +130 -0
- package/src/__tests__/helpers/mock-http-server.ts +46 -0
- package/src/__tests__/helpers/mock-istty.ts +27 -0
- package/src/__tests__/helpers/mock-kv.ts +33 -0
- package/src/__tests__/helpers/mock-oauth-flow.ts +255 -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 +39 -0
- package/src/__tests__/helpers/run-wrangler.ts +16 -0
- package/src/__tests__/helpers/write-worker-source.ts +31 -0
- package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
- package/src/__tests__/https-options.test.ts +130 -0
- package/src/__tests__/index.test.ts +179 -209
- package/src/__tests__/init.test.ts +1637 -0
- package/src/__tests__/jest.setup.ts +61 -6
- package/src/__tests__/kv.test.ts +842 -472
- package/src/__tests__/logger.test.ts +115 -0
- package/src/__tests__/package-manager.test.ts +353 -0
- package/src/__tests__/pages.test.ts +754 -0
- package/src/__tests__/parse.test.ts +330 -0
- package/src/__tests__/publish.test.ts +5755 -0
- package/src/__tests__/r2.test.ts +233 -0
- package/src/__tests__/route.test.ts +45 -0
- package/src/__tests__/secret.test.ts +481 -0
- package/src/__tests__/tail.test.ts +690 -0
- package/src/__tests__/user.test.ts +131 -0
- package/src/__tests__/whoami.test.tsx +139 -0
- package/src/abort.d.ts +3 -0
- package/src/bundle.ts +197 -0
- package/src/cfetch/index.ts +40 -21
- package/src/cfetch/internal.ts +102 -29
- package/src/cli.ts +6 -2
- package/src/config/README.md +107 -0
- package/src/config/config.ts +234 -0
- package/src/config/diagnostics.ts +80 -0
- package/src/config/environment.ts +420 -0
- package/src/config/index.ts +225 -0
- package/src/config/validation-helpers.ts +584 -0
- package/src/config/validation.ts +1548 -0
- package/src/config-cache.ts +45 -0
- package/src/create-worker-preview.ts +185 -0
- package/src/create-worker-upload-form.ts +254 -0
- package/src/dev/dev-vars.ts +36 -0
- package/src/dev/dev.tsx +401 -0
- package/src/dev/local.tsx +326 -0
- package/src/dev/remote.tsx +237 -0
- package/src/dev/use-esbuild.ts +118 -0
- package/src/dialogs.tsx +66 -8
- package/src/durable.ts +102 -0
- package/src/entry.ts +322 -0
- package/src/environment-variables.ts +35 -0
- package/src/errors.ts +11 -0
- package/src/https-options.ts +123 -0
- package/src/index.tsx +1848 -976
- package/src/inspect.ts +156 -33
- package/src/intl-polyfill.d.ts +139 -0
- package/src/{kv.tsx → kv.ts} +199 -67
- package/src/logger.ts +66 -0
- package/src/miniflare-cli/README.md +30 -0
- package/src/miniflare-cli/enum-keys.ts +17 -0
- package/src/miniflare-cli/index.ts +41 -0
- package/src/miniflare-cli/request-context.ts +40 -0
- package/src/module-collection.ts +229 -35
- package/src/open-in-browser.ts +19 -0
- package/src/package-manager.ts +174 -0
- package/src/pages.tsx +1162 -100
- package/src/parse.ts +203 -0
- package/src/paths.ts +26 -0
- package/src/proxy.ts +227 -51
- package/src/publish.ts +633 -276
- package/src/r2.ts +50 -0
- package/src/selfsigned.d.ts +29 -0
- package/src/sites.tsx +270 -62
- package/src/tail/filters.ts +279 -0
- package/src/tail/index.ts +299 -0
- package/src/tail/printing.ts +67 -0
- package/src/update-check.ts +19 -0
- package/src/user.tsx +382 -195
- package/src/whoami.tsx +71 -0
- package/src/{api/worker.ts → worker.ts} +66 -40
- package/src/zones.ts +73 -0
- package/templates/gitignore +171 -0
- package/templates/new-worker-scheduled.js +17 -0
- package/templates/new-worker-scheduled.ts +32 -0
- package/templates/new-worker.js +15 -0
- package/templates/new-worker.ts +30 -0
- package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -5
- package/templates/tsconfig.json +105 -0
- package/wrangler-dist/cli.js +106332 -103741
- package/src/__tests__/mock-dialogs.ts +0 -65
- 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/api/preview.ts +0 -128
- package/src/config.ts +0 -487
- package/src/dev.tsx +0 -784
- package/src/tail.tsx +0 -73
- package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
- package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
- package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
- package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
- package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
- package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
- package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
- package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
- package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
- package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
- package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
- package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
- package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
- package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
- package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
- package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
- package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
- package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
- package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
- package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
- package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
- package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
- package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
- package/vendor/wrangler-mime/CHANGELOG.md +0 -289
- package/vendor/wrangler-mime/LICENSE +0 -21
- package/vendor/wrangler-mime/Mime.js +0 -97
- package/vendor/wrangler-mime/README.md +0 -187
- package/vendor/wrangler-mime/cli.js +0 -46
- package/vendor/wrangler-mime/index.js +0 -4
- package/vendor/wrangler-mime/lite.js +0 -4
- package/vendor/wrangler-mime/package.json +0 -52
- package/vendor/wrangler-mime/types/other.js +0 -1
- package/vendor/wrangler-mime/types/standard.js +0 -1
- package/wrangler-dist/cli.js.map +0 -7
package/src/parse.ts
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
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
|
+
import { logger } from "./logger";
|
|
6
|
+
|
|
7
|
+
export type Message = {
|
|
8
|
+
text: string;
|
|
9
|
+
location?: Location;
|
|
10
|
+
notes?: Message[];
|
|
11
|
+
kind?: "warning" | "error";
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export type Location = File & {
|
|
15
|
+
line: number;
|
|
16
|
+
column: number;
|
|
17
|
+
length?: number;
|
|
18
|
+
lineText?: string;
|
|
19
|
+
suggestion?: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type File = {
|
|
23
|
+
file?: string;
|
|
24
|
+
fileText?: string;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Formats a `Message` using esbuild's pretty-printing algorithm.
|
|
29
|
+
*/
|
|
30
|
+
export function formatMessage(
|
|
31
|
+
{ text, notes, location, kind = "error" }: Message,
|
|
32
|
+
color = true
|
|
33
|
+
): string {
|
|
34
|
+
const input = { text, notes, location };
|
|
35
|
+
delete input.location?.fileText;
|
|
36
|
+
for (const note of notes ?? []) {
|
|
37
|
+
delete note.location?.fileText;
|
|
38
|
+
}
|
|
39
|
+
const lines = formatMessagesSync([input], {
|
|
40
|
+
color,
|
|
41
|
+
kind: kind,
|
|
42
|
+
terminalWidth: logger.columns,
|
|
43
|
+
});
|
|
44
|
+
return lines.join("\n");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* An error that's thrown when something fails to parse.
|
|
49
|
+
*/
|
|
50
|
+
export class ParseError extends Error implements Message {
|
|
51
|
+
readonly text: string;
|
|
52
|
+
readonly notes: Message[];
|
|
53
|
+
readonly location?: Location;
|
|
54
|
+
readonly kind: "warning" | "error";
|
|
55
|
+
|
|
56
|
+
constructor({ text, notes, location, kind }: Message) {
|
|
57
|
+
super(text);
|
|
58
|
+
this.name = this.constructor.name;
|
|
59
|
+
this.text = text;
|
|
60
|
+
this.notes = notes ?? [];
|
|
61
|
+
this.location = location;
|
|
62
|
+
this.kind = kind ?? "error";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const TOML_ERROR_NAME = "TomlError";
|
|
67
|
+
const TOML_ERROR_SUFFIX = " at row ";
|
|
68
|
+
|
|
69
|
+
type TomlError = Error & {
|
|
70
|
+
line: number;
|
|
71
|
+
col: number;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* A wrapper around `TOML.parse` that throws a `ParseError`.
|
|
76
|
+
*/
|
|
77
|
+
export function parseTOML(input: string, file?: string): TOML.JsonMap | never {
|
|
78
|
+
try {
|
|
79
|
+
// Normalize CRLF to LF to avoid hitting https://github.com/iarna/iarna-toml/issues/33.
|
|
80
|
+
const normalizedInput = input.replace(/\r\n/g, "\n");
|
|
81
|
+
return TOML.parse(normalizedInput);
|
|
82
|
+
} catch (err) {
|
|
83
|
+
const { name, message, line, col } = err as TomlError;
|
|
84
|
+
if (name !== TOML_ERROR_NAME) {
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
const text = message.substring(0, message.lastIndexOf(TOML_ERROR_SUFFIX));
|
|
88
|
+
const lineText = input.split("\n")[line];
|
|
89
|
+
const location = {
|
|
90
|
+
lineText,
|
|
91
|
+
line: line + 1,
|
|
92
|
+
column: col - 1,
|
|
93
|
+
file,
|
|
94
|
+
fileText: input,
|
|
95
|
+
};
|
|
96
|
+
throw new ParseError({ text, location });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const JSON_ERROR_SUFFIX = " in JSON at position ";
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A minimal type describing a package.json file.
|
|
104
|
+
*/
|
|
105
|
+
export type PackageJSON = {
|
|
106
|
+
devDependencies?: Record<string, unknown>;
|
|
107
|
+
dependencies?: Record<string, unknown>;
|
|
108
|
+
scripts?: Record<string, unknown>;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* A typed version of `parseJSON()`.
|
|
113
|
+
*/
|
|
114
|
+
export function parsePackageJSON<T extends PackageJSON = PackageJSON>(
|
|
115
|
+
input: string,
|
|
116
|
+
file?: string
|
|
117
|
+
): T {
|
|
118
|
+
return parseJSON<T>(input, file);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* A wrapper around `JSON.parse` that throws a `ParseError`.
|
|
123
|
+
*/
|
|
124
|
+
export function parseJSON<T>(input: string, file?: string): T {
|
|
125
|
+
try {
|
|
126
|
+
return JSON.parse(input);
|
|
127
|
+
} catch (err) {
|
|
128
|
+
const { message } = err as Error;
|
|
129
|
+
const index = message.lastIndexOf(JSON_ERROR_SUFFIX);
|
|
130
|
+
if (index < 0) {
|
|
131
|
+
throw err;
|
|
132
|
+
}
|
|
133
|
+
const text = message.substring(0, index);
|
|
134
|
+
const position = parseInt(
|
|
135
|
+
message.substring(index + JSON_ERROR_SUFFIX.length)
|
|
136
|
+
);
|
|
137
|
+
const location = indexLocation({ file, fileText: input }, position);
|
|
138
|
+
throw new ParseError({ text, location });
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Reads a file and parses it based on its type.
|
|
144
|
+
*/
|
|
145
|
+
export function readFileSync(file: string): string {
|
|
146
|
+
try {
|
|
147
|
+
return fs.readFileSync(file, { encoding: "utf-8" });
|
|
148
|
+
} catch (err) {
|
|
149
|
+
const { message } = err as Error;
|
|
150
|
+
throw new ParseError({
|
|
151
|
+
text: `Could not read file: ${file}`,
|
|
152
|
+
notes: [
|
|
153
|
+
{
|
|
154
|
+
text: message.replace(file, resolve(file)),
|
|
155
|
+
},
|
|
156
|
+
],
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Calculates the line and column location from an index.
|
|
163
|
+
*/
|
|
164
|
+
export function indexLocation(file: File, index: number): Location {
|
|
165
|
+
let lineText,
|
|
166
|
+
line = 0,
|
|
167
|
+
column = 0,
|
|
168
|
+
cursor = 0;
|
|
169
|
+
const { fileText = "" } = file;
|
|
170
|
+
for (const row of fileText.split("\n")) {
|
|
171
|
+
line++;
|
|
172
|
+
cursor += row.length + 1;
|
|
173
|
+
if (cursor >= index) {
|
|
174
|
+
lineText = row;
|
|
175
|
+
column = row.length - (cursor - index);
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return { lineText, line, column, ...file };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Guesses the line and column location of a search query.
|
|
184
|
+
*/
|
|
185
|
+
export function searchLocation(file: File, query: unknown): Location {
|
|
186
|
+
let lineText,
|
|
187
|
+
length,
|
|
188
|
+
line = 0,
|
|
189
|
+
column = 0;
|
|
190
|
+
const queryText = String(query);
|
|
191
|
+
const { fileText = "" } = file;
|
|
192
|
+
for (const content of fileText.split("\n")) {
|
|
193
|
+
line++;
|
|
194
|
+
const index = content.indexOf(queryText);
|
|
195
|
+
if (index >= 0) {
|
|
196
|
+
lineText = content;
|
|
197
|
+
column = index;
|
|
198
|
+
length = queryText.length;
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return { lineText, line, column, length, ...file };
|
|
203
|
+
}
|
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,29 @@
|
|
|
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 { createHttpTerminator } from "http-terminator";
|
|
6
|
+
import { useEffect, useRef, useState } from "react";
|
|
7
|
+
import serveStatic from "serve-static";
|
|
8
|
+
import { getHttpsOptions } from "./https-options";
|
|
9
|
+
import { logger } from "./logger";
|
|
10
|
+
import type { CfPreviewToken } from "./create-worker-preview";
|
|
11
|
+
import type { HttpTerminator } from "http-terminator";
|
|
4
12
|
import type {
|
|
5
13
|
IncomingHttpHeaders,
|
|
6
14
|
RequestListener,
|
|
7
15
|
IncomingMessage,
|
|
8
16
|
ServerResponse,
|
|
9
|
-
Server,
|
|
17
|
+
Server as HttpServer,
|
|
10
18
|
} from "node:http";
|
|
11
|
-
import
|
|
12
|
-
import
|
|
13
|
-
import type
|
|
14
|
-
|
|
19
|
+
import type { ClientHttp2Session, ServerHttp2Stream } from "node:http2";
|
|
20
|
+
import type { Server as HttpsServer } from "node:https";
|
|
21
|
+
import type ws from "ws";
|
|
22
|
+
|
|
23
|
+
interface IWebsocket extends ws {
|
|
24
|
+
// Pipe implements .on("message", ...)
|
|
25
|
+
pipe<T>(fn: T): IWebsocket;
|
|
26
|
+
}
|
|
15
27
|
|
|
16
28
|
/**
|
|
17
29
|
* `usePreviewServer` is a React hook that creates a local development
|
|
@@ -41,30 +53,64 @@ function addCfPreviewTokenHeader(
|
|
|
41
53
|
function rewriteRemoteHostToLocalHostInHeaders(
|
|
42
54
|
headers: IncomingHttpHeaders,
|
|
43
55
|
remoteHost: string,
|
|
44
|
-
localPort: number
|
|
56
|
+
localPort: number,
|
|
57
|
+
localProtocol: "https" | "http"
|
|
45
58
|
) {
|
|
46
59
|
for (const [name, value] of Object.entries(headers)) {
|
|
47
60
|
// Rewrite the remote host to the local host.
|
|
48
61
|
if (typeof value === "string" && value.includes(remoteHost)) {
|
|
49
62
|
headers[name] = value
|
|
50
|
-
.replaceAll(
|
|
63
|
+
.replaceAll(
|
|
64
|
+
`https://${remoteHost}`,
|
|
65
|
+
`${localProtocol}://localhost:${localPort}`
|
|
66
|
+
)
|
|
51
67
|
.replaceAll(remoteHost, `localhost:${localPort}`);
|
|
52
68
|
}
|
|
53
69
|
}
|
|
54
70
|
}
|
|
55
71
|
|
|
72
|
+
type PreviewProxy = {
|
|
73
|
+
server: HttpServer | HttpsServer;
|
|
74
|
+
terminator: HttpTerminator;
|
|
75
|
+
};
|
|
76
|
+
|
|
56
77
|
export function usePreviewServer({
|
|
57
78
|
previewToken,
|
|
58
79
|
publicRoot,
|
|
59
|
-
|
|
80
|
+
localProtocol,
|
|
81
|
+
localPort: port,
|
|
82
|
+
ip,
|
|
60
83
|
}: {
|
|
61
84
|
previewToken: CfPreviewToken | undefined;
|
|
62
|
-
publicRoot:
|
|
63
|
-
|
|
85
|
+
publicRoot: string | undefined;
|
|
86
|
+
localProtocol: "https" | "http";
|
|
87
|
+
localPort: number;
|
|
88
|
+
ip: string;
|
|
64
89
|
}) {
|
|
65
90
|
/** Creates an HTTP/1 proxy that sends requests over HTTP/2. */
|
|
66
|
-
const
|
|
67
|
-
|
|
91
|
+
const [proxy, setProxy] = useState<PreviewProxy>();
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Create the instance of the local proxy server that will pass on
|
|
95
|
+
* requests to the preview worker.
|
|
96
|
+
*/
|
|
97
|
+
useEffect(() => {
|
|
98
|
+
if (proxy === undefined) {
|
|
99
|
+
createProxyServer(localProtocol)
|
|
100
|
+
.then((server) => {
|
|
101
|
+
setProxy({
|
|
102
|
+
server,
|
|
103
|
+
terminator: createHttpTerminator({
|
|
104
|
+
server,
|
|
105
|
+
gracefulTerminationTimeout: 0,
|
|
106
|
+
}),
|
|
107
|
+
});
|
|
108
|
+
})
|
|
109
|
+
.catch(async (err) => {
|
|
110
|
+
logger.error("Failed to create proxy server:", err);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}, [proxy, localProtocol]);
|
|
68
114
|
|
|
69
115
|
/**
|
|
70
116
|
* When we're not connected / getting a fresh token on changes,
|
|
@@ -80,7 +126,22 @@ export function usePreviewServer({
|
|
|
80
126
|
{ request: IncomingMessage; response: ServerResponse }[]
|
|
81
127
|
>([]);
|
|
82
128
|
|
|
129
|
+
/**
|
|
130
|
+
* The session doesn't last forever, and will eventually drop
|
|
131
|
+
* (usually within 5-15 minutes). When that happens, we simply
|
|
132
|
+
* restart the effect, effectively restarting the server. We use
|
|
133
|
+
* a state sigil as an effect dependency to do so.
|
|
134
|
+
*/
|
|
135
|
+
const [retryServerSetupSigil, setRetryServerSetupSigil] = useState<number>(0);
|
|
136
|
+
function retryServerSetup() {
|
|
137
|
+
setRetryServerSetupSigil((x) => x + 1);
|
|
138
|
+
}
|
|
139
|
+
|
|
83
140
|
useEffect(() => {
|
|
141
|
+
if (proxy === undefined) {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
84
145
|
// If we don't have a token, that means either we're just starting up,
|
|
85
146
|
// or we're refreshing the token.
|
|
86
147
|
if (!previewToken) {
|
|
@@ -92,8 +153,8 @@ export function usePreviewServer({
|
|
|
92
153
|
// store the stream in a buffer so we can replay it later
|
|
93
154
|
streamBufferRef.current.push({ stream, headers });
|
|
94
155
|
};
|
|
95
|
-
proxy.on("stream", bufferStream);
|
|
96
|
-
cleanupListeners.push(() => proxy.off("stream", bufferStream));
|
|
156
|
+
proxy.server.on("stream", bufferStream);
|
|
157
|
+
cleanupListeners.push(() => proxy.server.off("stream", bufferStream));
|
|
97
158
|
|
|
98
159
|
const bufferRequestResponse = (
|
|
99
160
|
request: IncomingMessage,
|
|
@@ -103,8 +164,10 @@ export function usePreviewServer({
|
|
|
103
164
|
requestResponseBufferRef.current.push({ request, response });
|
|
104
165
|
};
|
|
105
166
|
|
|
106
|
-
proxy.on("request", bufferRequestResponse);
|
|
107
|
-
cleanupListeners.push(() =>
|
|
167
|
+
proxy.server.on("request", bufferRequestResponse);
|
|
168
|
+
cleanupListeners.push(() =>
|
|
169
|
+
proxy.server.off("request", bufferRequestResponse)
|
|
170
|
+
);
|
|
108
171
|
return () => {
|
|
109
172
|
cleanupListeners.forEach((cleanup) => cleanup());
|
|
110
173
|
};
|
|
@@ -119,10 +182,20 @@ export function usePreviewServer({
|
|
|
119
182
|
const remote = connect(`https://${previewToken.host}`);
|
|
120
183
|
cleanupListeners.push(() => remote.destroy());
|
|
121
184
|
|
|
185
|
+
// As mentioned above, the session may die at any point,
|
|
186
|
+
// so we need to restart the effect.
|
|
187
|
+
remote.on("close", retryServerSetup);
|
|
188
|
+
cleanupListeners.push(() => remote.off("close", retryServerSetup));
|
|
189
|
+
|
|
122
190
|
/** HTTP/2 -> HTTP/2 */
|
|
123
|
-
const handleStream = createStreamHandler(
|
|
124
|
-
|
|
125
|
-
|
|
191
|
+
const handleStream = createStreamHandler(
|
|
192
|
+
previewToken,
|
|
193
|
+
remote,
|
|
194
|
+
port,
|
|
195
|
+
localProtocol
|
|
196
|
+
);
|
|
197
|
+
proxy.server.on("stream", handleStream);
|
|
198
|
+
cleanupListeners.push(() => proxy.server.off("stream", handleStream));
|
|
126
199
|
|
|
127
200
|
// flush and replay buffered streams
|
|
128
201
|
streamBufferRef.current.forEach((buffer) =>
|
|
@@ -152,10 +225,15 @@ export function usePreviewServer({
|
|
|
152
225
|
const request = message.pipe(remote.request(headers));
|
|
153
226
|
request.on("response", (responseHeaders) => {
|
|
154
227
|
const status = responseHeaders[":status"] ?? 500;
|
|
228
|
+
|
|
229
|
+
// log all requests to terminal
|
|
230
|
+
logger.log(new Date().toLocaleTimeString(), method, url, status);
|
|
231
|
+
|
|
155
232
|
rewriteRemoteHostToLocalHostInHeaders(
|
|
156
233
|
responseHeaders,
|
|
157
234
|
previewToken.host,
|
|
158
|
-
port
|
|
235
|
+
port,
|
|
236
|
+
localProtocol
|
|
159
237
|
);
|
|
160
238
|
for (const name of Object.keys(responseHeaders)) {
|
|
161
239
|
if (name.startsWith(":")) {
|
|
@@ -173,8 +251,10 @@ export function usePreviewServer({
|
|
|
173
251
|
? createHandleAssetsRequest(assetPath, handleRequest)
|
|
174
252
|
: handleRequest;
|
|
175
253
|
|
|
176
|
-
proxy.on("request", actualHandleRequest);
|
|
177
|
-
cleanupListeners.push(() =>
|
|
254
|
+
proxy.server.on("request", actualHandleRequest);
|
|
255
|
+
cleanupListeners.push(() =>
|
|
256
|
+
proxy.server.off("request", actualHandleRequest)
|
|
257
|
+
);
|
|
178
258
|
|
|
179
259
|
// flush and replay buffered requests
|
|
180
260
|
requestResponseBufferRef.current.forEach(({ request, response }) =>
|
|
@@ -191,38 +271,73 @@ export function usePreviewServer({
|
|
|
191
271
|
const { headers, url } = message;
|
|
192
272
|
addCfPreviewTokenHeader(headers, previewToken.value);
|
|
193
273
|
headers["host"] = previewToken.host;
|
|
194
|
-
const localWebsocket = new WebSocket(message, socket, body);
|
|
274
|
+
const localWebsocket = new WebSocket(message, socket, body) as IWebsocket;
|
|
195
275
|
// TODO(soon): Custom WebSocket protocol is not working?
|
|
196
276
|
const remoteWebsocketClient = new WebSocket.Client(
|
|
197
277
|
`wss://${previewToken.host}${url}`,
|
|
198
278
|
[],
|
|
199
279
|
{ headers }
|
|
200
|
-
);
|
|
280
|
+
) as IWebsocket;
|
|
201
281
|
localWebsocket.pipe(remoteWebsocketClient).pipe(localWebsocket);
|
|
202
282
|
// We close down websockets whenever we refresh the token.
|
|
203
283
|
cleanupListeners.push(() => {
|
|
204
|
-
localWebsocket.
|
|
205
|
-
remoteWebsocketClient.
|
|
284
|
+
localWebsocket.close();
|
|
285
|
+
remoteWebsocketClient.close();
|
|
206
286
|
});
|
|
207
287
|
};
|
|
208
|
-
proxy.on("upgrade", handleUpgrade);
|
|
209
|
-
cleanupListeners.push(() => proxy.off("upgrade", handleUpgrade));
|
|
288
|
+
proxy.server.on("upgrade", handleUpgrade);
|
|
289
|
+
cleanupListeners.push(() => proxy.server.off("upgrade", handleUpgrade));
|
|
210
290
|
|
|
211
291
|
return () => {
|
|
212
|
-
cleanupListeners.forEach((
|
|
292
|
+
cleanupListeners.forEach((cleanup) => cleanup());
|
|
213
293
|
};
|
|
214
|
-
}, [
|
|
294
|
+
}, [
|
|
295
|
+
previewToken,
|
|
296
|
+
publicRoot,
|
|
297
|
+
port,
|
|
298
|
+
localProtocol,
|
|
299
|
+
proxy,
|
|
300
|
+
// We use a state value as a sigil to trigger reconnecting the server.
|
|
301
|
+
// It's not used inside the effect, so react-hooks/exhaustive-deps
|
|
302
|
+
// doesn't complain if it's not included in the dependency array.
|
|
303
|
+
// But its presence is critical, so Do NOT remove it from the dependency list.
|
|
304
|
+
retryServerSetupSigil,
|
|
305
|
+
]);
|
|
215
306
|
|
|
216
307
|
// Start/stop the server whenever the
|
|
217
308
|
// containing component is mounted/unmounted.
|
|
218
309
|
useEffect(() => {
|
|
219
|
-
|
|
220
|
-
|
|
310
|
+
const abortController = new AbortController();
|
|
311
|
+
if (proxy === undefined) {
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
waitForPortToBeAvailable(port, {
|
|
316
|
+
retryPeriod: 200,
|
|
317
|
+
timeout: 2000,
|
|
318
|
+
abortSignal: abortController.signal,
|
|
319
|
+
})
|
|
320
|
+
.then(() => {
|
|
321
|
+
proxy.server.on("listening", () => {
|
|
322
|
+
logger.log(`⬣ Listening at ${localProtocol}://${ip}:${port}`);
|
|
323
|
+
});
|
|
324
|
+
proxy.server.listen(port, ip);
|
|
325
|
+
})
|
|
326
|
+
.catch((err) => {
|
|
327
|
+
if ((err as { code: string }).code !== "ABORT_ERR") {
|
|
328
|
+
logger.error(`Failed to start server: ${err}`);
|
|
329
|
+
}
|
|
330
|
+
});
|
|
221
331
|
|
|
222
332
|
return () => {
|
|
223
|
-
|
|
333
|
+
abortController.abort();
|
|
334
|
+
// Running `proxy.server.close()` does not close open connections, preventing the process from exiting.
|
|
335
|
+
// So we use this `terminator` to close all the connections and force the server to shutdown.
|
|
336
|
+
proxy.terminator
|
|
337
|
+
.terminate()
|
|
338
|
+
.catch(() => logger.error("Failed to terminate the proxy server."));
|
|
224
339
|
};
|
|
225
|
-
}, [port, proxy]);
|
|
340
|
+
}, [port, ip, proxy, localProtocol]);
|
|
226
341
|
}
|
|
227
342
|
|
|
228
343
|
function createHandleAssetsRequest(
|
|
@@ -250,20 +365,18 @@ const HTTP1_HEADERS = new Set([
|
|
|
250
365
|
"http2-settings",
|
|
251
366
|
]);
|
|
252
367
|
|
|
253
|
-
function createProxyServer(
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
);
|
|
263
|
-
})
|
|
368
|
+
async function createProxyServer(
|
|
369
|
+
localProtocol: "https" | "http"
|
|
370
|
+
): Promise<HttpServer | HttpsServer> {
|
|
371
|
+
const server: HttpServer | HttpsServer =
|
|
372
|
+
localProtocol === "https"
|
|
373
|
+
? createHttpsServer(await getHttpsOptions())
|
|
374
|
+
: createHttpServer();
|
|
375
|
+
|
|
376
|
+
return server
|
|
264
377
|
.on("upgrade", (req) => {
|
|
265
378
|
// log all websocket connections
|
|
266
|
-
|
|
379
|
+
logger.log(
|
|
267
380
|
new Date().toLocaleTimeString(),
|
|
268
381
|
req.method,
|
|
269
382
|
req.url,
|
|
@@ -273,14 +386,15 @@ function createProxyServer() {
|
|
|
273
386
|
})
|
|
274
387
|
.on("error", (err) => {
|
|
275
388
|
// log all connection errors
|
|
276
|
-
|
|
389
|
+
logger.error(new Date().toLocaleTimeString(), err);
|
|
277
390
|
});
|
|
278
391
|
}
|
|
279
392
|
|
|
280
393
|
function createStreamHandler(
|
|
281
394
|
previewToken: CfPreviewToken,
|
|
282
395
|
remote: ClientHttp2Session,
|
|
283
|
-
|
|
396
|
+
localPort: number,
|
|
397
|
+
localProtocol: "https" | "http"
|
|
284
398
|
) {
|
|
285
399
|
return function handleStream(
|
|
286
400
|
stream: ServerHttp2Stream,
|
|
@@ -293,10 +407,72 @@ function createStreamHandler(
|
|
|
293
407
|
rewriteRemoteHostToLocalHostInHeaders(
|
|
294
408
|
responseHeaders,
|
|
295
409
|
previewToken.host,
|
|
296
|
-
|
|
410
|
+
localPort,
|
|
411
|
+
localProtocol
|
|
297
412
|
);
|
|
298
413
|
stream.respond(responseHeaders);
|
|
299
414
|
request.pipe(stream, { end: true });
|
|
300
415
|
});
|
|
301
416
|
};
|
|
302
417
|
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* A helper function that waits for a port to be available.
|
|
421
|
+
*/
|
|
422
|
+
export async function waitForPortToBeAvailable(
|
|
423
|
+
port: number,
|
|
424
|
+
options: { retryPeriod: number; timeout: number; abortSignal: AbortSignal }
|
|
425
|
+
): Promise<void> {
|
|
426
|
+
return new Promise((resolve, reject) => {
|
|
427
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
428
|
+
options.abortSignal.addEventListener("abort", () => {
|
|
429
|
+
const abortError = new Error("waitForPortToBeAvailable() aborted");
|
|
430
|
+
(abortError as Error & { code: string }).code = "ABORT_ERR";
|
|
431
|
+
doReject(abortError);
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
const timeout = setTimeout(() => {
|
|
435
|
+
doReject(new Error(`Timed out waiting for port ${port}`));
|
|
436
|
+
}, options.timeout);
|
|
437
|
+
|
|
438
|
+
const interval = setInterval(checkPort, options.retryPeriod);
|
|
439
|
+
checkPort();
|
|
440
|
+
|
|
441
|
+
function doResolve() {
|
|
442
|
+
clearTimeout(timeout);
|
|
443
|
+
clearInterval(interval);
|
|
444
|
+
resolve();
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function doReject(err: unknown) {
|
|
448
|
+
clearInterval(interval);
|
|
449
|
+
clearTimeout(timeout);
|
|
450
|
+
reject(err);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function checkPort() {
|
|
454
|
+
// Testing whether a port is 'available' involves simply
|
|
455
|
+
// trying to make a server listen on that port, and retrying
|
|
456
|
+
// until it succeeds.
|
|
457
|
+
const server = createHttpServer();
|
|
458
|
+
const terminator = createHttpTerminator({
|
|
459
|
+
server,
|
|
460
|
+
gracefulTerminationTimeout: 0, // default 1000
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
server.on("error", (err) => {
|
|
464
|
+
// @ts-expect-error non standard property on Error
|
|
465
|
+
if (err.code !== "EADDRINUSE") {
|
|
466
|
+
doReject(err);
|
|
467
|
+
}
|
|
468
|
+
});
|
|
469
|
+
server.listen(port, () =>
|
|
470
|
+
terminator
|
|
471
|
+
.terminate()
|
|
472
|
+
.then(doResolve, () =>
|
|
473
|
+
logger.error("Failed to terminate the port checker.")
|
|
474
|
+
)
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
});
|
|
478
|
+
}
|