ReadonlySet Seals Shared Allowlists
Expose ReadonlySet views across module boundaries to hide add, delete, and clear from callers while preserving lookup, iteration, and element covariance.
Code
type Scope = 'read' | 'write' | 'export';
function createScopeStore(initial: readonly Scope[]) {
const backing = new Set<Scope>(initial);
return {
grant(scope: Scope): void {
backing.add(scope);
},
// Callers receive ReadonlySet<Scope>: add/delete/clear are absent on the type
view(): ReadonlySet<Scope> {
return backing;
},
};
}
// ReadonlySet<T> is covariant in T, so ReadonlySet<Scope> fits ReadonlySet<string>
function hasAllRequired(granted: ReadonlySet<string>, required: readonly string[]): boolean {
return required.every((item) => granted.has(item));
}
const store = createScopeStore(['read']);
const snapshot = store.view();
console.log('before grant:', [...snapshot].join(','), 'can write:', hasAllRequired(snapshot, ['read', 'write']));
store.grant('write');
console.log('after grant:', snapshot.size, 'can write:', hasAllRequired(snapshot, ['read', 'write']));Output
Captured from a sandboxed run of this snippet in the build pipeline.
before grant: read can write: false
after grant: 2 can write: trueHow it works
Key operational steps happen within the callables createScopeStore and hasAllRequired.
The return value is newly constructed — inputs are never handed back.
What to watch for
- The only prerequisite is the language toolchain itself.
Putting it to use
Essential subroutine signature reads function createScopeStore(initial: readonly Scope[])
Expect labeled output — before grant:, after grant: — when the file runs.
Core lines
return required.every((item) => granted.has(item));
const backing = new Set<Scope>(initial);
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Does `createScopeStore` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `createScopeStore`, `hasAllRequired` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.