2023-04-16 23:37:37 -04:00
|
|
|
interface FetchOptions {
|
|
|
|
cache?: string
|
|
|
|
}
|
|
|
|
|
|
|
|
const URL_RESOLVER = document.createElement('a');
|
|
|
|
|
|
|
|
// `fetch` with `file:` support
|
|
|
|
// Recent browsers seem to support `file` protocol under some conditions.
|
|
|
|
// Based on https://github.com/github/fetch/pull/92#issuecomment-174730593
|
|
|
|
// https://github.com/github/fetch/pull/92#issuecomment-512187452
|
|
|
|
export default async function fetchLocal(url: string, options?: FetchOptions) {
|
|
|
|
URL_RESOLVER.href = url;
|
|
|
|
|
|
|
|
const requestURL = URL_RESOLVER.href;
|
|
|
|
|
|
|
|
return new Promise<Response>((resolve, reject) => {
|
|
|
|
const xhr = new XMLHttpRequest;
|
|
|
|
|
|
|
|
xhr.onload = () => {
|
|
|
|
// `file` protocol has invalid OK status
|
|
|
|
let status = xhr.status;
|
|
|
|
if (requestURL.startsWith('file:') && status === 0) {
|
|
|
|
status = 200;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* eslint-disable-next-line compat/compat */
|
|
|
|
resolve(new Response(xhr.responseText, { status }));
|
|
|
|
};
|
|
|
|
|
|
|
|
xhr.onerror = () => {
|
|
|
|
reject(new TypeError('Local request failed'));
|
|
|
|
};
|
|
|
|
|
|
|
|
xhr.open('GET', url);
|
|
|
|
|
2023-07-06 13:39:48 -04:00
|
|
|
if (options?.cache) {
|
2023-04-16 23:37:37 -04:00
|
|
|
xhr.setRequestHeader('Cache-Control', options.cache);
|
|
|
|
}
|
|
|
|
|
|
|
|
xhr.send(null);
|
|
|
|
});
|
|
|
|
}
|