Skip to content

Realm handle multiple instances #6883

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking
changeKind: fix
packages:
- "@typespec/compiler"
---

Realm handle multiple instance of compiler loaded at once
17 changes: 16 additions & 1 deletion packages/compiler/src/experimental/realm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,5 +234,20 @@ export class Realm {
return this.#types;
}

static realmForType = new WeakMap<Type, Realm>();
static realmForType = singleton("Realm.realmForType", () => new WeakMap<Type, Realm>());
}

/**
* Create a singleton instance that is shared across the process.
* This is to have a true singleton even if multiple instance of the compiler/library are loaded.
* @param key - The key to use for the singleton.
* @param init - The function to call to create the singleton.
*/
function singleton<T>(key: string, init: () => T): T {
const sym = Symbol.for(key);
if (!(globalThis as any)[sym]) {
(globalThis as any)[sym] = init();
}

return (globalThis as any)[sym];
}
Loading