wrangler 4.131.2 → 4.132.0
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/config-schema.json +20 -73
- package/package.json +23 -18
- package/templates/middleware/loader-sw.ts +52 -18
- package/wrangler-dist/cli.d.ts +14 -20
- package/wrangler-dist/cli.js +30592 -30323
- package/wrangler-dist/experimental-config.d.mts +3 -20
- package/wrangler-dist/experimental-config.d.mts.map +1 -1
- package/wrangler-dist/experimental-config.mjs +1 -5
- package/wrangler-dist/experimental-config.mjs.map +1 -1
- package/templates/__tests__/pages-dev-util.test.ts +0 -124
- package/templates/__tests__/tsconfig-sanity.ts +0 -12
- package/templates/__tests__/tsconfig.json +0 -8
- package/templates/facade.d.ts +0 -19
- package/templates/middleware/middleware-patch-console-prefix.d.ts +0 -3
- package/templates/new-worker-scheduled.js +0 -17
- package/templates/new-worker-scheduled.ts +0 -32
- package/templates/new-worker.js +0 -15
- package/templates/new-worker.ts +0 -33
- package/templates/startDevWorker/InspectorProxyWorker.ts +0 -713
- package/templates/startDevWorker/ProxyWorker.ts +0 -478
- package/templates/tsconfig-sanity.ts +0 -11
- package/templates/tsconfig.init.json +0 -22
- package/templates/tsconfig.json +0 -14
|
@@ -1,478 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
createDeferred,
|
|
3
|
-
type DeferredPromise,
|
|
4
|
-
isSameUserWorkerOrigin,
|
|
5
|
-
rewriteUrlInHeaderValue,
|
|
6
|
-
urlFromParts,
|
|
7
|
-
} from "../../src/api/startDevWorker/utils";
|
|
8
|
-
import type {
|
|
9
|
-
ProxyData,
|
|
10
|
-
ProxyWorkerIncomingRequestBody,
|
|
11
|
-
ProxyWorkerOutgoingRequestBody,
|
|
12
|
-
} from "../../src/api/startDevWorker/events";
|
|
13
|
-
|
|
14
|
-
interface Env {
|
|
15
|
-
PROXY_CONTROLLER: Fetcher;
|
|
16
|
-
PROXY_CONTROLLER_AUTH_SECRET: string;
|
|
17
|
-
DURABLE_OBJECT: DurableObjectNamespace;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
// request.cf.hostMetadata is verbose to type using the workers-types Request -- this allows us to have Request correctly typed in this scope
|
|
21
|
-
type Request = Parameters<
|
|
22
|
-
NonNullable<
|
|
23
|
-
ExportedHandler<Env, unknown, ProxyWorkerIncomingRequestBody>["fetch"]
|
|
24
|
-
>
|
|
25
|
-
>[0];
|
|
26
|
-
|
|
27
|
-
const LIVE_RELOAD_PROTOCOL = "WRANGLER_PROXYWORKER_LIVE_RELOAD_PROTOCOL";
|
|
28
|
-
const LIVE_RELOAD_PATHNAME = "/cdn-cgi/live-reload";
|
|
29
|
-
export default {
|
|
30
|
-
fetch(req, env) {
|
|
31
|
-
const singleton = env.DURABLE_OBJECT.idFromName("");
|
|
32
|
-
const inspectorProxy = env.DURABLE_OBJECT.get(singleton);
|
|
33
|
-
|
|
34
|
-
return inspectorProxy.fetch(req);
|
|
35
|
-
},
|
|
36
|
-
} as ExportedHandler<Env, unknown, ProxyWorkerIncomingRequestBody>;
|
|
37
|
-
|
|
38
|
-
export class ProxyWorker implements DurableObject {
|
|
39
|
-
constructor(
|
|
40
|
-
readonly state: DurableObjectState,
|
|
41
|
-
readonly env: Env
|
|
42
|
-
) {}
|
|
43
|
-
|
|
44
|
-
proxyData?: ProxyData;
|
|
45
|
-
requestQueue = new Map<Request, DeferredPromise<Response>>();
|
|
46
|
-
requestRetryQueue = new Map<Request, DeferredPromise<Response>>();
|
|
47
|
-
|
|
48
|
-
fetch(request: Request) {
|
|
49
|
-
if (isRequestForLiveReloadWebsocket(request)) {
|
|
50
|
-
// requests for live-reload websocket
|
|
51
|
-
|
|
52
|
-
return this.handleLiveReloadWebSocket(request);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
if (isRequestFromProxyController(request, this.env)) {
|
|
56
|
-
// requests from ProxyController
|
|
57
|
-
|
|
58
|
-
return this.processProxyControllerRequest(request);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// regular requests to be proxied
|
|
62
|
-
const deferred = createDeferred<Response>();
|
|
63
|
-
|
|
64
|
-
this.requestQueue.set(request, deferred);
|
|
65
|
-
this.processQueue();
|
|
66
|
-
|
|
67
|
-
return deferred.promise;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
handleLiveReloadWebSocket(request: Request) {
|
|
71
|
-
const { 0: response, 1: liveReload } = new WebSocketPair();
|
|
72
|
-
const websocketProtocol =
|
|
73
|
-
request.headers.get("Sec-WebSocket-Protocol") ?? "";
|
|
74
|
-
|
|
75
|
-
this.state.acceptWebSocket(liveReload, ["live-reload"]);
|
|
76
|
-
|
|
77
|
-
return new Response(null, {
|
|
78
|
-
status: 101,
|
|
79
|
-
webSocket: response,
|
|
80
|
-
headers: { "Sec-WebSocket-Protocol": websocketProtocol },
|
|
81
|
-
});
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
processProxyControllerRequest(request: Request) {
|
|
85
|
-
const event = request.cf?.hostMetadata;
|
|
86
|
-
switch (event?.type) {
|
|
87
|
-
case "pause":
|
|
88
|
-
this.proxyData = undefined;
|
|
89
|
-
break;
|
|
90
|
-
|
|
91
|
-
case "play":
|
|
92
|
-
this.proxyData = event.proxyData;
|
|
93
|
-
this.processQueue();
|
|
94
|
-
this.state
|
|
95
|
-
.getWebSockets("live-reload")
|
|
96
|
-
.forEach((ws) => ws.send("reload"));
|
|
97
|
-
|
|
98
|
-
break;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
return new Response(null, { status: 204 });
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* Process requests that are being retried first, then process newer requests.
|
|
106
|
-
* Requests that are being retried are, by definition, older than requests which haven't been processed yet.
|
|
107
|
-
* We don't need to be more accurate than this re ordering, since the requests are being fired off synchronously.
|
|
108
|
-
*/
|
|
109
|
-
*getOrderedQueue() {
|
|
110
|
-
yield* this.requestRetryQueue;
|
|
111
|
-
yield* this.requestQueue;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
processQueue() {
|
|
115
|
-
const { proxyData } = this; // store proxyData at the moment this function was called
|
|
116
|
-
if (proxyData === undefined) return;
|
|
117
|
-
|
|
118
|
-
for (const [request, deferredResponse] of this.getOrderedQueue()) {
|
|
119
|
-
this.requestRetryQueue.delete(request);
|
|
120
|
-
this.requestQueue.delete(request);
|
|
121
|
-
|
|
122
|
-
const outerUrl = new URL(request.url);
|
|
123
|
-
const headers = new Headers(request.headers);
|
|
124
|
-
|
|
125
|
-
// override url parts for proxying
|
|
126
|
-
const userWorkerUrl = new URL(request.url);
|
|
127
|
-
Object.assign(userWorkerUrl, proxyData.userWorkerUrl);
|
|
128
|
-
|
|
129
|
-
// set request.url in the UserWorker
|
|
130
|
-
const innerUrl = urlFromParts(
|
|
131
|
-
proxyData.userWorkerInnerUrlOverrides ?? {},
|
|
132
|
-
request.url
|
|
133
|
-
);
|
|
134
|
-
|
|
135
|
-
// rewrite requests to old miniflare paths
|
|
136
|
-
// because wrangler cannot have a breaking change
|
|
137
|
-
userWorkerUrl.pathname = rewriteLegacyMiniflarePath(
|
|
138
|
-
userWorkerUrl.pathname
|
|
139
|
-
);
|
|
140
|
-
innerUrl.pathname = rewriteLegacyMiniflarePath(innerUrl.pathname);
|
|
141
|
-
|
|
142
|
-
// Preserve client `Accept-Encoding`, rather than using Worker's default
|
|
143
|
-
// of `Accept-Encoding: br, gzip`
|
|
144
|
-
const encoding = request.cf?.clientAcceptEncoding;
|
|
145
|
-
if (encoding !== undefined) headers.set("Accept-Encoding", encoding);
|
|
146
|
-
|
|
147
|
-
rewriteUrlRelatedHeaders(headers, outerUrl, innerUrl);
|
|
148
|
-
|
|
149
|
-
// Set after `rewriteUrlRelatedHeaders` so that any occurrences of the
|
|
150
|
-
// outer host inside the URL's query string (e.g. `?redirect_uri=`)
|
|
151
|
-
// are preserved in `request.url` inside the user worker.
|
|
152
|
-
headers.set("MF-Original-URL", innerUrl.href);
|
|
153
|
-
|
|
154
|
-
// merge proxyData headers with the request headers
|
|
155
|
-
for (const [key, value] of Object.entries(proxyData.headers ?? {})) {
|
|
156
|
-
if (value === undefined) continue;
|
|
157
|
-
|
|
158
|
-
if (key.toLowerCase() === "cookie") {
|
|
159
|
-
const existing = request.headers.get("cookie") ?? "";
|
|
160
|
-
headers.set("cookie", `${existing};${value}`);
|
|
161
|
-
} else {
|
|
162
|
-
headers.set(key, value);
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/**
|
|
167
|
-
* Sends the request to the UserWorker and settles `deferredResponse`
|
|
168
|
-
* with the outcome — or requeues the request if the UserWorker is
|
|
169
|
-
* mid-reload. The promise chain is deliberately not awaited (`void`):
|
|
170
|
-
* we are in a loop and want to process the whole queue quickly +
|
|
171
|
-
* synchronously.
|
|
172
|
-
*
|
|
173
|
-
* A connection-level failure (the `fetch` itself rejects, so no
|
|
174
|
-
* response was received) on a same-origin GET/HEAD request is retried
|
|
175
|
-
* before being reported — see the rejection handler.
|
|
176
|
-
*
|
|
177
|
-
* Kept as a `const` arrow function: the handlers re-read
|
|
178
|
-
* `this.proxyData` across async boundaries to detect UserWorker
|
|
179
|
-
* reloads, so they need the ProxyWorker's lexical `this`.
|
|
180
|
-
*
|
|
181
|
-
* @param attempt the number of attempts that have already failed
|
|
182
|
-
* (`0` on the first try)
|
|
183
|
-
*/
|
|
184
|
-
const attemptUserWorkerFetch = (attempt = 0) =>
|
|
185
|
-
void fetch(userWorkerUrl, new Request(request, { headers }))
|
|
186
|
-
.then(
|
|
187
|
-
async (res) => {
|
|
188
|
-
if (attempt > 0) {
|
|
189
|
-
console.warn(
|
|
190
|
-
`ProxyWorker: ${request.method} ${request.url} recovered on attempt ${attempt + 1} after a dropped connection to the UserWorker`
|
|
191
|
-
);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
res = new Response(res.body, res);
|
|
195
|
-
rewriteUrlRelatedHeaders(res.headers, innerUrl, outerUrl);
|
|
196
|
-
|
|
197
|
-
await checkForPreviewTokenError(res, this.env, proxyData);
|
|
198
|
-
|
|
199
|
-
if (isHtmlResponse(res)) {
|
|
200
|
-
res = insertLiveReloadScript(request, res, this.env, proxyData);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
if (isSseResponse(res)) {
|
|
204
|
-
void sendMessageToProxyController(this.env, {
|
|
205
|
-
type: "sseResponseDetected",
|
|
206
|
-
});
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
deferredResponse.resolve(res);
|
|
210
|
-
},
|
|
211
|
-
(error: Error) => {
|
|
212
|
-
// the fetch itself rejected: a connection-level failure, and no
|
|
213
|
-
// response was received. Errors thrown while post-processing a
|
|
214
|
-
// received response skip this handler and land in the .catch
|
|
215
|
-
// below, so they are reported rather than retried and can never
|
|
216
|
-
// re-run the UserWorker's handler.
|
|
217
|
-
//
|
|
218
|
-
// When the UserWorker origin is unchanged (i.e. this is not a
|
|
219
|
-
// reload — see the same check in the .catch below), the failure
|
|
220
|
-
// is most commonly the UserWorker's HTTP server closing a reused
|
|
221
|
-
// keep-alive connection at the same moment this request was
|
|
222
|
-
// written to it (kj's client pool idleTimeout and server
|
|
223
|
-
// pipelineTimeout both default to 5s, so a connection idling ~5s
|
|
224
|
-
// races the close). Retrying bodyless requests draws a fresh
|
|
225
|
-
// connection and absorbs the race, mirroring the requeue in the
|
|
226
|
-
// .catch for reloads: retry immediately, then once more after
|
|
227
|
-
// 250ms (3 attempts in total).
|
|
228
|
-
if (
|
|
229
|
-
isSameUserWorkerOrigin(
|
|
230
|
-
userWorkerUrl,
|
|
231
|
-
this.proxyData?.userWorkerUrl
|
|
232
|
-
) &&
|
|
233
|
-
(request.method === "GET" || request.method === "HEAD") &&
|
|
234
|
-
attempt < 2
|
|
235
|
-
) {
|
|
236
|
-
setTimeout(
|
|
237
|
-
() => {
|
|
238
|
-
// the UserWorker may have started reloading while this
|
|
239
|
-
// retry was queued (even at 0ms — setTimeout defers to a
|
|
240
|
-
// later task). `proxyData` carries the destination AND the
|
|
241
|
-
// headers, so retrying with the captured one could reach
|
|
242
|
-
// the pre-reload Worker or send a stale preview token.
|
|
243
|
-
// Requeue instead and let the current proxyData rebuild it.
|
|
244
|
-
if (this.proxyData !== proxyData) {
|
|
245
|
-
this.requestRetryQueue.set(request, deferredResponse);
|
|
246
|
-
this.processQueue();
|
|
247
|
-
return;
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
attemptUserWorkerFetch(attempt + 1);
|
|
251
|
-
},
|
|
252
|
-
attempt === 0 ? 0 : 250
|
|
253
|
-
);
|
|
254
|
-
return;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
throw error;
|
|
258
|
-
}
|
|
259
|
-
)
|
|
260
|
-
.catch((error: Error) => {
|
|
261
|
-
// errors here are from response post-processing, or connection-
|
|
262
|
-
// level failures rethrown by the rejection handler above (a
|
|
263
|
-
// non-retriable method, or the retry budget was exhausted)
|
|
264
|
-
|
|
265
|
-
// we have crossed an async boundary, so proxyData may have changed
|
|
266
|
-
// if proxyData.userWorkerUrl has changed, it means there is a new downstream UserWorker
|
|
267
|
-
// and that this error is stale since it was for a request to the old UserWorker
|
|
268
|
-
// only report the error if the request still targets the current
|
|
269
|
-
// UserWorker. isSameUserWorkerOrigin compares origin (not href) so a
|
|
270
|
-
// genuine error on a non-root path isn't misread as a reload — see
|
|
271
|
-
// its docs.
|
|
272
|
-
if (
|
|
273
|
-
isSameUserWorkerOrigin(
|
|
274
|
-
userWorkerUrl,
|
|
275
|
-
this.proxyData?.userWorkerUrl
|
|
276
|
-
)
|
|
277
|
-
) {
|
|
278
|
-
const attemptsNote = ` (failed after ${attempt + 1} ${
|
|
279
|
-
attempt === 0 ? "attempt" : "attempts"
|
|
280
|
-
})`;
|
|
281
|
-
void sendMessageToProxyController(this.env, {
|
|
282
|
-
type: "error",
|
|
283
|
-
error: {
|
|
284
|
-
name: error.name,
|
|
285
|
-
message: `${request.method} ${request.url}${attemptsNote}: ${error.message}`,
|
|
286
|
-
stack: error.stack,
|
|
287
|
-
cause: error.cause,
|
|
288
|
-
},
|
|
289
|
-
});
|
|
290
|
-
|
|
291
|
-
deferredResponse.reject(error);
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
// if the request can be retried (subset of idempotent requests which have no body), requeue it
|
|
295
|
-
else if (request.method === "GET" || request.method === "HEAD") {
|
|
296
|
-
this.requestRetryQueue.set(request, deferredResponse);
|
|
297
|
-
// we would only end up here if the downstream UserWorker is chang*ing*
|
|
298
|
-
// i.e. we are in a `pause`d state and expecting a `play` message soon
|
|
299
|
-
// this request will be processed (retried) when the `play` message arrives
|
|
300
|
-
// for that reason, we do not need to call `this.processQueue` here
|
|
301
|
-
// (but, also, it can't hurt to call it since it bails when
|
|
302
|
-
// in a `pause`d state i.e. `this.proxyData` is undefined)
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
// if the request cannot be retried, respond with 503 Service Unavailable
|
|
306
|
-
// important to note, this is not an (unexpected) error -- it is an acceptable flow of local development
|
|
307
|
-
// it would be incorrect to retry non-idempotent requests
|
|
308
|
-
// and would require cloning all body streams to avoid stream reuse (which is inefficient but not out of the question in the future)
|
|
309
|
-
// this is a good enough UX for now since it solves the most common GET use-case
|
|
310
|
-
else {
|
|
311
|
-
deferredResponse.resolve(
|
|
312
|
-
new Response(
|
|
313
|
-
"Your worker restarted mid-request. Please try sending the request again. Only GET or HEAD requests are retried automatically.",
|
|
314
|
-
{
|
|
315
|
-
status: 503,
|
|
316
|
-
headers: { "Retry-After": "0" },
|
|
317
|
-
}
|
|
318
|
-
)
|
|
319
|
-
);
|
|
320
|
-
}
|
|
321
|
-
});
|
|
322
|
-
|
|
323
|
-
attemptUserWorkerFetch();
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
function isRequestFromProxyController(req: Request, env: Env): boolean {
|
|
329
|
-
return req.headers.get("Authorization") === env.PROXY_CONTROLLER_AUTH_SECRET;
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
// Miniflare v5 moved its internal endpoints under `/cdn-cgi/local/` (and
|
|
333
|
-
// `/__cf_local/` for endpoints that must remain reachable over tunnels). These
|
|
334
|
-
// map the pre-v5 paths onto their current equivalents.
|
|
335
|
-
const LEGACY_PATH_REWRITES: readonly [string, string][] = [
|
|
336
|
-
["/cdn-cgi/handler", "/cdn-cgi/local"],
|
|
337
|
-
["/cdn-cgi/mf/scheduled", "/cdn-cgi/local/scheduled"],
|
|
338
|
-
["/cdn-cgi/mf/stream", "/__cf_local/stream"],
|
|
339
|
-
["/cdn-cgi/mf/imagedelivery", "/__cf_local/imagedelivery"],
|
|
340
|
-
["/cdn-cgi/explorer", "/cdn-cgi/local/explorer"],
|
|
341
|
-
];
|
|
342
|
-
|
|
343
|
-
function rewriteLegacyMiniflarePath(pathname: string): string {
|
|
344
|
-
for (const [oldPrefix, newPrefix] of LEGACY_PATH_REWRITES) {
|
|
345
|
-
if (pathname === oldPrefix || pathname.startsWith(`${oldPrefix}/`)) {
|
|
346
|
-
return newPrefix + pathname.slice(oldPrefix.length);
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
return pathname;
|
|
350
|
-
}
|
|
351
|
-
function isHtmlResponse(res: Response): boolean {
|
|
352
|
-
return res.headers.get("content-type")?.startsWith("text/html") ?? false;
|
|
353
|
-
}
|
|
354
|
-
function isSseResponse(res: Response): boolean {
|
|
355
|
-
return (
|
|
356
|
-
res.headers.get("content-type")?.startsWith("text/event-stream") ?? false
|
|
357
|
-
);
|
|
358
|
-
}
|
|
359
|
-
function isRequestForLiveReloadWebsocket(req: Request): boolean {
|
|
360
|
-
if (new URL(req.url).pathname !== LIVE_RELOAD_PATHNAME) {
|
|
361
|
-
return false;
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
const websocketProtocol = req.headers.get("Sec-WebSocket-Protocol");
|
|
365
|
-
const isWebSocketUpgrade = req.headers.get("Upgrade") === "websocket";
|
|
366
|
-
|
|
367
|
-
return isWebSocketUpgrade && websocketProtocol === LIVE_RELOAD_PROTOCOL;
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
function sendMessageToProxyController(
|
|
371
|
-
env: Env,
|
|
372
|
-
message: ProxyWorkerOutgoingRequestBody
|
|
373
|
-
) {
|
|
374
|
-
return env.PROXY_CONTROLLER.fetch("http://dummy", {
|
|
375
|
-
method: "POST",
|
|
376
|
-
body: JSON.stringify(message),
|
|
377
|
-
});
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
async function checkForPreviewTokenError(
|
|
381
|
-
response: Response,
|
|
382
|
-
env: Env,
|
|
383
|
-
proxyData: ProxyData
|
|
384
|
-
) {
|
|
385
|
-
if (response.status !== 400) {
|
|
386
|
-
return;
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
// At this point HTMLRewriter tries to parse the compressed stream,
|
|
390
|
-
// so we clone and read the text instead.
|
|
391
|
-
const clone = response.clone();
|
|
392
|
-
const text = await clone.text();
|
|
393
|
-
// Naive string match should be good enough when combined with status code check.
|
|
394
|
-
// "Invalid Workers Preview configuration" is the HTML error returned when the
|
|
395
|
-
// preview token has expired. "error code: 1031" is a text/plain error returned
|
|
396
|
-
// by remote bindings (e.g. Workers AI) when their underlying session has timed out.
|
|
397
|
-
// Both indicate the preview session needs to be refreshed.
|
|
398
|
-
if (
|
|
399
|
-
text.includes("Invalid Workers Preview configuration") ||
|
|
400
|
-
text.includes("error code: 1031")
|
|
401
|
-
) {
|
|
402
|
-
void sendMessageToProxyController(env, {
|
|
403
|
-
type: "previewTokenExpired",
|
|
404
|
-
proxyData,
|
|
405
|
-
});
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
function insertLiveReloadScript(
|
|
410
|
-
request: Request,
|
|
411
|
-
response: Response,
|
|
412
|
-
env: Env,
|
|
413
|
-
proxyData: ProxyData
|
|
414
|
-
) {
|
|
415
|
-
const htmlRewriter = new HTMLRewriter();
|
|
416
|
-
|
|
417
|
-
htmlRewriter.onDocument({
|
|
418
|
-
end(end) {
|
|
419
|
-
// if liveReload enabled, append a script tag
|
|
420
|
-
// TODO: compare to existing nodejs implementation
|
|
421
|
-
if (proxyData.liveReload) {
|
|
422
|
-
const websocketUrl = new URL(request.url);
|
|
423
|
-
websocketUrl.protocol =
|
|
424
|
-
websocketUrl.protocol === "http:" ? "ws:" : "wss:";
|
|
425
|
-
|
|
426
|
-
end.append(liveReloadScript, { html: true });
|
|
427
|
-
}
|
|
428
|
-
},
|
|
429
|
-
});
|
|
430
|
-
|
|
431
|
-
return htmlRewriter.transform(response);
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
const liveReloadScript = `
|
|
435
|
-
<script defer type="application/javascript">
|
|
436
|
-
(function() {
|
|
437
|
-
var ws;
|
|
438
|
-
function recover() {
|
|
439
|
-
ws = null;
|
|
440
|
-
setTimeout(initLiveReload, 100);
|
|
441
|
-
}
|
|
442
|
-
function initLiveReload() {
|
|
443
|
-
if (ws) return;
|
|
444
|
-
var origin = (location.protocol === "http:" ? "ws://" : "wss://") + location.host;
|
|
445
|
-
ws = new WebSocket(origin + "${LIVE_RELOAD_PATHNAME}", "${LIVE_RELOAD_PROTOCOL}");
|
|
446
|
-
ws.onclose = recover;
|
|
447
|
-
ws.onerror = recover;
|
|
448
|
-
ws.onmessage = location.reload.bind(location);
|
|
449
|
-
}
|
|
450
|
-
initLiveReload();
|
|
451
|
-
})();
|
|
452
|
-
</script>
|
|
453
|
-
`;
|
|
454
|
-
|
|
455
|
-
/**
|
|
456
|
-
* Rewrite references to URLs in request/response headers.
|
|
457
|
-
*
|
|
458
|
-
* This function is used to map the URLs in headers like Origin and Access-Control-Allow-Origin
|
|
459
|
-
* so that this proxy is transparent to the Client Browser and User Worker.
|
|
460
|
-
*/
|
|
461
|
-
function rewriteUrlRelatedHeaders(headers: Headers, from: URL, to: URL) {
|
|
462
|
-
const setCookie = headers.getAll("Set-Cookie");
|
|
463
|
-
headers.delete("Set-Cookie");
|
|
464
|
-
headers.forEach((value, key) => {
|
|
465
|
-
if (typeof value === "string" && value.includes(from.host)) {
|
|
466
|
-
headers.set(key, rewriteUrlInHeaderValue(value, from, to));
|
|
467
|
-
}
|
|
468
|
-
});
|
|
469
|
-
for (const cookie of setCookie) {
|
|
470
|
-
headers.append(
|
|
471
|
-
"Set-Cookie",
|
|
472
|
-
cookie.replace(
|
|
473
|
-
new RegExp(`Domain=${from.hostname}($|;|,)`),
|
|
474
|
-
`Domain=${to.hostname}$1`
|
|
475
|
-
)
|
|
476
|
-
);
|
|
477
|
-
}
|
|
478
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
// @ts-nocheck `@types/node` should NOT be included
|
|
2
|
-
Buffer.from("test");
|
|
3
|
-
|
|
4
|
-
// @ts-expect-error `@types/jest` should NOT be included
|
|
5
|
-
test("test");
|
|
6
|
-
|
|
7
|
-
// `@cloudflare/workers-types` should be included
|
|
8
|
-
const _handler: ExportedHandler = {};
|
|
9
|
-
new HTMLRewriter();
|
|
10
|
-
|
|
11
|
-
export {};
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"target": "es2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
|
4
|
-
"lib": [
|
|
5
|
-
"es2021"
|
|
6
|
-
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
|
|
7
|
-
"jsx": "react-jsx" /* Specify what JSX code is generated. */,
|
|
8
|
-
"module": "ESNext" /* Specify what module code is generated. */,
|
|
9
|
-
"moduleResolution": "Bundler" /* Specify how TypeScript looks up a file from a given module specifier. */,
|
|
10
|
-
"types": [
|
|
11
|
-
"@cloudflare/workers-types"
|
|
12
|
-
] /* Specify type package names to be included without being referenced in a source file. */,
|
|
13
|
-
"resolveJsonModule": true /* Enable importing .json files */,
|
|
14
|
-
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
|
|
15
|
-
"noEmit": true /* Disable emitting files from a compilation. */,
|
|
16
|
-
"isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */,
|
|
17
|
-
"allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */,
|
|
18
|
-
"strict": true /* Enable all strict type-checking options. */,
|
|
19
|
-
"noUncheckedIndexedAccess": true,
|
|
20
|
-
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
|
21
|
-
}
|
|
22
|
-
}
|
package/templates/tsconfig.json
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"extends": "@cloudflare/workers-tsconfig/tsconfig.json",
|
|
3
|
-
"compilerOptions": {
|
|
4
|
-
"types": ["@cloudflare/workers-types"]
|
|
5
|
-
},
|
|
6
|
-
"include": ["**/*.ts"],
|
|
7
|
-
"exclude": [
|
|
8
|
-
"__tests__",
|
|
9
|
-
// Note: `startDevWorker` and `middleware` should also be included but some work is needed
|
|
10
|
-
// for that first (see: https://github.com/cloudflare/workers-sdk/issues/8303)
|
|
11
|
-
"startDevWorker",
|
|
12
|
-
"middleware"
|
|
13
|
-
]
|
|
14
|
-
}
|