Skip to content

Commit

Permalink
Fixes potential ReferenceError in Polyfills (#76)
Browse files Browse the repository at this point in the history
  • Loading branch information
adams85 authored Jan 3, 2023
1 parent 7e1c5ba commit d627118
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
25 changes: 23 additions & 2 deletions src/Polyfills.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,24 @@
const getGlobalObject = (() => {
let value: typeof globalThis | undefined;

return () => {
if (!value) {
value =
typeof globalThis === "object" && globalThis ? globalThis :
typeof self === "object" && self ? self :
typeof window === "object" && window ? window :
typeof global === "object" && global ? global :
typeof Function === "function" ? (Function('return this')()) :
null;

if (!value) {
throw new Error("Global object could not be determined.");
}
}
return value;
};
})();

export function setupPolyfills() {
// Object.values
if (typeof Object.values === "undefined") {
Expand All @@ -18,7 +39,7 @@ export function setupPolyfills() {
if (typeof WeakRef === "undefined") {
// There's no way to correctly polyfill WeakRef (https://stackoverflow.com/a/69971312/8656352),
// so we just polyfill its API (which means falling back on strong references in this case).
WeakRef = getWeakRefFallback();
getGlobalObject().WeakRef = getWeakRefStub();
}
}

Expand Down Expand Up @@ -59,7 +80,7 @@ export function ObjectFromEntriesPolyfill<T>(entries: Iterable<readonly [Propert
return result;
}

export function getWeakRefFallback<T extends object>(): WeakRefConstructor {
export function getWeakRefStub<T extends object>(): WeakRefConstructor {
type WeakRefImpl = WeakRef<T> & { target: T };

const WeakRef = function (this: WeakRefImpl, target: T) {
Expand Down
4 changes: 2 additions & 2 deletions test/PolyfillTests.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { assert, expect } from "chai";
import "mocha";
import { getWeakRefFallback, ObjectEntriesPolyfill, ObjectFromEntriesPolyfill, ObjectValuesPolyfill } from "../src/Polyfills";
import { getWeakRefStub, ObjectEntriesPolyfill, ObjectFromEntriesPolyfill, ObjectValuesPolyfill } from "../src/Polyfills";

describe("Polyfills", () => {
it("Object.values polyfill should work", () => {
Expand Down Expand Up @@ -36,7 +36,7 @@ describe("Polyfills", () => {
});

it("WeakRef API polyfill should work", () => {
const weakRefCtor = getWeakRefFallback();
const weakRefCtor = getWeakRefStub();

let obj: {} | null = {};
const objWeakRef = new weakRefCtor(obj);
Expand Down

0 comments on commit d627118

Please sign in to comment.