@worker-tools/location-polyfill
Version:
A Location polyfill for Cloudflare Workers.
42 lines (37 loc) • 1.34 kB
text/typescript
// deno-lint-ignore-file no-explicit-any no-explicit-any
// @ts-ignore: Deno doesn't know about WorkerLocation
class WorkerLocationPolyfill implements WorkerLocation {
constructor(href: string) { this.
get hash(): string { return '' }
get host(): string { return this.
get hostname(): string { return this.
get href(): string { return this.
get origin(): string { return this.
get pathname(): string { return '/' }
get port(): string { return this.
get protocol(): string { return this.
get search(): string { return '' }
toString(): string { return this.href }
}
function defineProperty(url: string, writable = false) {
Object.defineProperty(self, 'location', {
configurable: false,
enumerable: true,
writable,
value: new WorkerLocationPolyfill(url),
});
}
function polyfillLocation(event: Event): void {
// @ts-ignore: Deno doesn't know about FetchEvent
const _event = event as FetchEvent;
defineProperty(_event.request.url, true);
}
if (!('location' in self)) {
const envLoc = ((<any>self).WORKER_LOCATION) ?? ((<any>self).process?.env?.WORKER_LOCATION)
if (envLoc) {
defineProperty(envLoc);
} else {
self.addEventListener('fetch', polyfillLocation);
}
}