Skip to content

Commit

Permalink
Fixing fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
Pauan committed Jan 30, 2025
1 parent dcb529c commit 6aea6f7
Showing 1 changed file with 30 additions and 22 deletions.
52 changes: 30 additions & 22 deletions sdk/src/polyfill/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import $mime from "mime/lite";
const oldFetch = globalThis.fetch;


async function supportsFetch() {
let supports: Promise<boolean> | null = null;

async function checkFetch() {
try {
await oldFetch(new URL("file:"));
return true;
Expand All @@ -15,33 +17,39 @@ async function supportsFetch() {
}
}

async function supportsFetch(): Promise<boolean> {
if (supports === null) {
supports = checkFetch();
}

if (!(await supportsFetch())) {
// We always polyfill fetch because Node's fetch doesn't support file URLs.
(globalThis.fetch as any) = async function (resource: URL | RequestInfo, options: RequestInit | undefined): Promise<Response> {
const request = new Request(resource, options);
return await supports;
}

const url = new URL(request.url);

if (url.protocol === "file:") {
const readStream = $fs.createReadStream(url);
// We always polyfill fetch because Node's fetch doesn't support file URLs.
(globalThis.fetch as any) = async function (resource: URL | RequestInfo, options: RequestInit | undefined): Promise<Response> {
const request = new Request(resource, options);

const headers: HeadersInit = {};
const url = new URL(request.url);

const type = $mime.getType(url.pathname);
if (!(await supportsFetch()) && url.protocol === "file:") {
const readStream = $fs.createReadStream(url);

if (type) {
headers["Content-Type"] = type;
}
const headers: HeadersInit = {};

return new Response(readStream as any, {
status: 200,
statusText: "OK",
headers,
});
const type = $mime.getType(url.pathname);

} else {
return await oldFetch(request);
if (type) {
headers["Content-Type"] = type;
}
};
}

return new Response(readStream as any, {
status: 200,
statusText: "OK",
headers,
});

} else {
return await oldFetch(request);
}
};

0 comments on commit 6aea6f7

Please sign in to comment.