Skip to content

Commit

Permalink
fix: prevent duplicate shimming
Browse files Browse the repository at this point in the history
  • Loading branch information
luwes committed Jun 27, 2023
1 parent d1e2d82 commit 2c654ff
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions src/js/utils/server-safe-globals.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,17 @@ class ResizeObserver {
observe() {}
}

const documentShim = {
createElement: function () {
return new globalThisShim.HTMLElement();
},
addEventListener() {},
removeEventListener() {},
};

const globalThisShim = {
ResizeObserver,
document: documentShim,
HTMLElement: class HTMLElement extends EventTarget {},
DocumentFragment: class DocumentFragment extends EventTarget {},
customElements: {
Expand All @@ -27,18 +36,13 @@ const globalThisShim = {
}
};

const documentShim = {
createElement: function () {
return new globalThisShim.HTMLElement();
},
addEventListener() {},
removeEventListener() {},
};

export const isServer =
typeof window === 'undefined' ||
typeof window.customElements === 'undefined';

const isShimmed = Object.keys(globalThisShim)
.every(key => key in globalThis);

/**
* @type { globalThis & {
* WebKitPlaybackTargetAvailabilityEvent?,
Expand Down Expand Up @@ -66,7 +70,7 @@ export const isServer =
* CastableVideoElement?
* } }
* */
export const GlobalThis = isServer ? globalThisShim : globalThis;
export const GlobalThis = isServer && !isShimmed ? globalThisShim : globalThis;

/**
* @type { document & { webkitExitFullscreen? } |
Expand All @@ -82,7 +86,7 @@ export const GlobalThis = isServer ? globalThisShim : globalThis;
* removeEventListener?,
* } }
*/
export const Document = isServer ? documentShim : window.document;
export const Document = isServer && !isShimmed ? documentShim : globalThis.document;

export {
GlobalThis as globalThis,
Expand Down

0 comments on commit 2c654ff

Please sign in to comment.