js: Allow passing credentials option to fetch [#397] (#644)

* js: Allow passing credentials option to fetch [#397]
* fix passing custom headers in case where remote archive is < 16 kB
* clean up `any` usage
This commit is contained in:
Brandon Liu
2026-02-27 11:09:11 -05:00
committed by GitHub
parent 9ff3871133
commit c1014a5cf8
4 changed files with 80 additions and 9 deletions

View File

@@ -345,14 +345,20 @@ export class FetchSource implements Source {
* This should be used instead of maplibre's [transformRequest](https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#example) for PMTiles archives.
*/
customHeaders: Headers;
credentials: "same-origin" | "include" | undefined;
/** @hidden */
mustReload: boolean;
/** @hidden */
chromeWindowsNoCache: boolean;
constructor(url: string, customHeaders: Headers = new Headers()) {
constructor(
url: string,
customHeaders: Headers = new Headers(),
credentials: "same-origin" | "include" | undefined = undefined
) {
this.url = url;
this.customHeaders = customHeaders;
this.credentials = credentials;
this.mustReload = false;
let userAgent = "";
if ("navigator" in globalThis) {
@@ -402,7 +408,7 @@ export class FetchSource implements Source {
// * it requires CORS configuration becasue If-Match is not a CORs-safelisted header
// CORs configuration should expose ETag.
// if any etag mismatch is detected, we need to ignore the browser cache
let cache: string | undefined;
let cache: "no-store" | "reload" | undefined;
if (this.mustReload) {
cache = "reload";
} else if (this.chromeWindowsNoCache) {
@@ -413,8 +419,8 @@ export class FetchSource implements Source {
signal: signal,
cache: cache,
headers: requestHeaders,
//biome-ignore lint: "cache" is incompatible between cloudflare workers and browser
} as any);
credentials: this.credentials,
});
// handle edge case where the archive is < 16384 kb total.
if (offset === 0 && resp.status === 416) {
@@ -423,12 +429,13 @@ export class FetchSource implements Source {
throw new Error("Missing content-length on 416 response");
}
const actualLength = +contentRange.substr(8);
requestHeaders.set("range", `bytes=0-${actualLength - 1}`);
resp = await fetch(this.url, {
signal: signal,
cache: "reload",
headers: { range: `bytes=0-${actualLength - 1}` },
//biome-ignore lint: "cache" is incompatible between cloudflare workers and browser
} as any);
headers: requestHeaders,
credentials: this.credentials,
});
}
// if it's a weak etag, it's not useful for us, so ignore it.