wrangler 0.0.0-e95e5a0 → 0.0.0-e981d0be5

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 (184) hide show
  1. package/README.md +46 -34
  2. package/bin/wrangler.js +84 -39
  3. package/config-schema.json +2278 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +132 -99
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +2 -3
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +3 -3
  30. package/templates/new-worker.ts +22 -4
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +33 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +679 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +22 -0
  41. package/templates/tsconfig.json +13 -103
  42. package/templates/tsconfig.tsbuildinfo +1 -0
  43. package/wrangler-dist/InspectorProxyWorker.js +471 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +238 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +26693 -0
  48. package/wrangler-dist/cli.js +148512 -106990
  49. package/import_meta_url.js +0 -3
  50. package/miniflare-config-stubs/.env.empty +0 -0
  51. package/miniflare-config-stubs/package.empty.json +0 -1
  52. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  53. package/miniflare-dist/index.mjs +0 -4886
  54. package/pages/functions/buildPlugin.ts +0 -92
  55. package/pages/functions/buildWorker.ts +0 -138
  56. package/pages/functions/filepath-routing.test.ts +0 -234
  57. package/pages/functions/filepath-routing.ts +0 -189
  58. package/pages/functions/identifiers.ts +0 -78
  59. package/pages/functions/routes.ts +0 -156
  60. package/pages/functions/template-plugin.ts +0 -146
  61. package/pages/functions/template-worker.ts +0 -143
  62. package/src/__tests__/config-cache.test.ts +0 -36
  63. package/src/__tests__/configuration.test.ts +0 -3125
  64. package/src/__tests__/dev.test.tsx +0 -762
  65. package/src/__tests__/guess-worker-format.test.ts +0 -85
  66. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  67. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  68. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  69. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  70. package/src/__tests__/helpers/mock-bin.ts +0 -36
  71. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  72. package/src/__tests__/helpers/mock-console.ts +0 -87
  73. package/src/__tests__/helpers/mock-dialogs.ts +0 -90
  74. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  75. package/src/__tests__/helpers/mock-istty.ts +0 -27
  76. package/src/__tests__/helpers/mock-kv.ts +0 -33
  77. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  78. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  79. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  80. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  81. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  82. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  83. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  84. package/src/__tests__/https-options.test.ts +0 -130
  85. package/src/__tests__/index.test.ts +0 -249
  86. package/src/__tests__/init.test.ts +0 -1516
  87. package/src/__tests__/jest.setup.ts +0 -69
  88. package/src/__tests__/kv.test.ts +0 -1454
  89. package/src/__tests__/logger.test.ts +0 -115
  90. package/src/__tests__/package-manager.test.ts +0 -206
  91. package/src/__tests__/pages.test.ts +0 -329
  92. package/src/__tests__/parse.test.ts +0 -322
  93. package/src/__tests__/publish.test.ts +0 -4875
  94. package/src/__tests__/r2.test.ts +0 -214
  95. package/src/__tests__/route.test.ts +0 -45
  96. package/src/__tests__/secret.test.ts +0 -446
  97. package/src/__tests__/tail.test.ts +0 -690
  98. package/src/__tests__/user.test.ts +0 -131
  99. package/src/__tests__/whoami.test.tsx +0 -105
  100. package/src/bundle.ts +0 -169
  101. package/src/cfetch/index.ts +0 -104
  102. package/src/cfetch/internal.ts +0 -137
  103. package/src/cli.ts +0 -13
  104. package/src/config/README.md +0 -107
  105. package/src/config/config.ts +0 -234
  106. package/src/config/diagnostics.ts +0 -80
  107. package/src/config/environment.ts +0 -394
  108. package/src/config/index.ts +0 -63
  109. package/src/config/validation-helpers.ts +0 -575
  110. package/src/config/validation.ts +0 -1424
  111. package/src/config-cache.ts +0 -45
  112. package/src/create-worker-preview.ts +0 -175
  113. package/src/create-worker-upload-form.ts +0 -240
  114. package/src/dev/dev-vars.ts +0 -36
  115. package/src/dev/dev.tsx +0 -418
  116. package/src/dev/local.tsx +0 -312
  117. package/src/dev/remote.tsx +0 -213
  118. package/src/dev/use-esbuild.ts +0 -118
  119. package/src/dialogs.tsx +0 -87
  120. package/src/entry.ts +0 -267
  121. package/src/environment-variables.ts +0 -35
  122. package/src/errors.ts +0 -11
  123. package/src/https-options.ts +0 -123
  124. package/src/index.tsx +0 -2668
  125. package/src/inspect.ts +0 -623
  126. package/src/intl-polyfill.d.ts +0 -139
  127. package/src/kv.ts +0 -319
  128. package/src/logger.ts +0 -66
  129. package/src/miniflare-cli/README.md +0 -30
  130. package/src/miniflare-cli/enum-keys.ts +0 -17
  131. package/src/miniflare-cli/index.ts +0 -41
  132. package/src/miniflare-cli/request-context.ts +0 -40
  133. package/src/module-collection.ts +0 -258
  134. package/src/open-in-browser.ts +0 -26
  135. package/src/package-manager.ts +0 -127
  136. package/src/pages.tsx +0 -1866
  137. package/src/parse.ts +0 -183
  138. package/src/paths.ts +0 -26
  139. package/src/proxy.ts +0 -449
  140. package/src/publish.ts +0 -469
  141. package/src/r2.ts +0 -50
  142. package/src/selfsigned.d.ts +0 -29
  143. package/src/sites.tsx +0 -293
  144. package/src/tail/filters.ts +0 -279
  145. package/src/tail/index.ts +0 -299
  146. package/src/tail/printing.ts +0 -67
  147. package/src/update-check.ts +0 -19
  148. package/src/user.tsx +0 -1193
  149. package/src/whoami.tsx +0 -70
  150. package/src/worker.ts +0 -172
  151. package/templates/static-asset-facade.js +0 -47
  152. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  153. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  154. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  155. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  156. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  157. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  158. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  159. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  160. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  161. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  162. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  164. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  166. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  167. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  168. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  169. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  170. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  171. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  172. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  173. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  174. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  175. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  176. package/vendor/wrangler-mime/LICENSE +0 -21
  177. package/vendor/wrangler-mime/Mime.js +0 -97
  178. package/vendor/wrangler-mime/README.md +0 -187
  179. package/vendor/wrangler-mime/cli.js +0 -46
  180. package/vendor/wrangler-mime/index.js +0 -4
  181. package/vendor/wrangler-mime/lite.js +0 -4
  182. package/vendor/wrangler-mime/package.json +0 -52
  183. package/vendor/wrangler-mime/types/other.js +0 -1
  184. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/parse.ts DELETED
@@ -1,183 +0,0 @@
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
- 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 DELETED
@@ -1,26 +0,0 @@
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 DELETED
@@ -1,449 +0,0 @@
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
- }