Refactoring about how proxy fetching happens

This commit is contained in:
Zef Hemel
2023-08-23 19:08:21 +02:00
parent 38a95d2382
commit 5a88254cde
18 changed files with 320 additions and 93 deletions
+29 -7
View File
@@ -1,15 +1,33 @@
import { init } from "https://esm.sh/v131/node_events.js";
import type {
ProxyFetchRequest,
ProxyFetchResponse,
} from "../../common/proxy_fetch.ts";
import { base64Decode } from "../../plugos/asset_bundle/base64.ts";
import {
base64Decode,
base64Encode,
} from "../../plugos/asset_bundle/base64.ts";
export function sandboxFetch(
url: string,
export async function sandboxFetch(
reqInfo: RequestInfo,
options?: ProxyFetchRequest,
): Promise<ProxyFetchResponse> {
if (typeof reqInfo !== "string") {
// Request as first argument, let's deconstruct it
// console.log("fetch", reqInfo);
options = {
method: reqInfo.method,
headers: Object.fromEntries(reqInfo.headers.entries()),
base64Body: reqInfo.body
? base64Encode(
new Uint8Array(await (new Response(reqInfo.body)).arrayBuffer()),
)
: undefined,
};
reqInfo = reqInfo.url;
}
// @ts-ignore: monkey patching fetch
return syscall("sandboxFetch.fetch", url, options);
return syscall("sandboxFetch.fetch", reqInfo, options);
}
export function monkeyPatchFetch() {
@@ -17,15 +35,19 @@ export function monkeyPatchFetch() {
globalThis.nativeFetch = globalThis.fetch;
// @ts-ignore: monkey patching fetch
globalThis.fetch = async function (
url: string,
reqInfo: RequestInfo,
init?: RequestInit,
): Promise<Response> {
const r = await sandboxFetch(
url,
reqInfo,
init && {
method: init.method,
headers: init.headers as Record<string, string>,
body: init.body as string,
base64Body: init.body
? base64Encode(
new Uint8Array(await (new Response(init.body)).arrayBuffer()),
)
: undefined,
},
);
return new Response(r.base64Body ? base64Decode(r.base64Body) : null, {