Skip to content

Commit

Permalink
fix: support duplicate installations (#50)
Browse files Browse the repository at this point in the history
  • Loading branch information
noomorph authored Oct 12, 2023
1 parent 24ba925 commit 1282b3e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
17 changes: 15 additions & 2 deletions src/realms/detect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,25 @@ export function isJestWorker(): boolean {
return 'JEST_WORKER_ID' in process.env;
}

export function injectRealmIntoSandbox(sandbox: any, realm: ProcessRealm): void {
export function injectRealmIntoSandbox(sandbox: any, realm: ProcessRealm): ProcessRealm {
sandbox.__JEST_METADATA__ = realm;
if (sandbox !== globalThis) {
sandbox.__JEST_METADATA_SANDBOX__ = true;
}

return realm;
}

export function getSandboxedRealm(): ProcessRealm | undefined {
return (global as any).__JEST_METADATA__;
const globalAny = globalThis as any;
const realm = globalAny.__JEST_METADATA__;
if (realm && !globalAny.__JEST_METADATA_SANDBOX__) {
console.warn(
'[jest-metadata] Detected duplicate jest-metadata package in the same process. This may lead to unexpected behavior.',
);
}

return realm;
}

export function getServerId(): string | undefined {
Expand Down
4 changes: 2 additions & 2 deletions src/realms/realm.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable @typescript-eslint/no-var-requires,node/no-missing-require */
// TODO: think about ESM support via dynamic import
import { getSandboxedRealm, isClient } from './detect';
import { getSandboxedRealm, injectRealmIntoSandbox, isClient } from './detect';
import type { ProcessRealm } from './ProcessRealm';

function createRealm(): ProcessRealm {
Expand All @@ -13,4 +13,4 @@ function createRealm(): ProcessRealm {
}
}

export default getSandboxedRealm() ?? createRealm();
export default getSandboxedRealm() ?? injectRealmIntoSandbox(globalThis, createRealm());

0 comments on commit 1282b3e

Please sign in to comment.