-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathcloudflare-node.ts
85 lines (71 loc) · 2.46 KB
/
cloudflare-node.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type {
InternalEvent,
InternalResult,
StreamCreator,
} from "types/open-next";
import type { Wrapper, WrapperHandler } from "types/overrides";
import { Writable } from "node:stream";
// Response with null body status (101, 204, 205, or 304) cannot have a body.
const NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
const handler: WrapperHandler<InternalEvent, InternalResult> =
async (handler, converter) =>
async (
request: Request,
env: Record<string, string>,
ctx: any,
): Promise<Response> => {
globalThis.process = process;
// Set the environment variables
// Cloudflare suggests to not override the process.env object but instead apply the values to it
for (const [key, value] of Object.entries(env)) {
if (typeof value === "string") {
process.env[key] = value;
}
}
const internalEvent = await converter.convertFrom(request);
const url = new URL(request.url);
const { promise: promiseResponse, resolve: resolveResponse } =
Promise.withResolvers<Response>();
const streamCreator: StreamCreator = {
writeHeaders(prelude: {
statusCode: number;
cookies: string[];
headers: Record<string, string>;
}): Writable {
const { statusCode, cookies, headers } = prelude;
const responseHeaders = new Headers(headers);
for (const cookie of cookies) {
responseHeaders.append("Set-Cookie", cookie);
}
// TODO(vicb): this is a workaround to make PPR work with `wrangler dev`
// See https://github.com/cloudflare/workers-sdk/issues/8004
if (url.hostname === "localhost") {
responseHeaders.set("Content-Encoding", "identity");
}
const { readable, writable } = new TransformStream({
transform(chunk, controller) {
controller.enqueue(Uint8Array.from(chunk.chunk ?? chunk));
},
});
const body = NULL_BODY_STATUSES.has(statusCode) ? null : readable;
const response = new Response(body, {
status: statusCode,
headers: responseHeaders,
});
resolveResponse(response);
return Writable.fromWeb(writable);
},
};
ctx.waitUntil(
handler(internalEvent, {
streamCreator,
waitUntil: ctx.waitUntil.bind(ctx),
}),
);
return promiseResponse;
};
export default {
wrapper: handler,
name: "cloudflare-node",
supportStreaming: true,
} satisfies Wrapper;