https://github.com/kayahr/scope
Ownership scopes, cleanup callbacks, and typed scope-local values for TypeScript
https://github.com/kayahr/scope
browser cleanup context disposable dispose lifecycle nodejs ownership scope slot typescript
Last synced: 27 days ago
JSON representation
Ownership scopes, cleanup callbacks, and typed scope-local values for TypeScript
- Host: GitHub
- URL: https://github.com/kayahr/scope
- Owner: kayahr
- License: mit
- Created: 2026-04-15T18:57:55.000Z (about 1 month ago)
- Default Branch: main
- Last Pushed: 2026-04-16T07:58:56.000Z (about 1 month ago)
- Last Synced: 2026-04-16T09:38:13.366Z (about 1 month ago)
- Topics: browser, cleanup, context, disposable, dispose, lifecycle, nodejs, ownership, scope, slot, typescript
- Language: TypeScript
- Homepage: https://kayahr.github.io/scope/
- Size: 29.3 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/funding.yml
- License: LICENSE.md
Awesome Lists containing this project
README
# scope
[GitHub] | [NPM] | [API Doc]
Small, framework-independent ownership scopes for TypeScript.
`@kayahr/scope` provides disposable ownership scopes, cleanup registration, parent/child scope trees, and typed scope-local values.
## Installation
```bash
npm install @kayahr/scope
```
TypeScript consumers currently need a compatible `lib` configuration including `esnext.disposable`.
Runtimes without native `Symbol.dispose` need a polyfill before importing `@kayahr/scope`, for example from [core-js](https://www.npmjs.com/package/core-js):
```ts
import "core-js/proposals/explicit-resource-management";
```
## Basic Usage
Create a scope, activate it while constructing owned resources, and dispose it later as one unit:
```ts
import { createScope, onDispose } from "@kayahr/scope";
const scope = createScope();
scope.run(() => {
const interval = setInterval(() => {
console.log("tick");
}, 1000);
onDispose(() => {
clearInterval(interval);
});
});
// ...
scope.dispose();
```
`createScope()` creates a scope. Without an explicit parent, it uses the current active scope as parent, or the shared root scope when no scope is active. `createScope(scope => ...)` is shorthand for creating a scope and running a callback inside it. Only the synchronous execution of `scope.run(...)` or `createScope(scope => ...)` belongs to the scope. Work created after an `await` is outside that scope. If the callback returns a promise, that promise is returned as-is and is not awaited.
`getRootScope()` returns the shared root scope. It is not active by default, but scopes created without an active scope are attached to it. `resetRootScope()` clears the shared root scope without replacing it.
## Documentation
- [Scopes](doc/scopes.md)
- [Scope Slots](doc/slots.md)
[API Doc]: https://kayahr.github.io/scope/
[GitHub]: https://github.com/kayahr/scope
[NPM]: https://www.npmjs.com/package/@kayahr/scope