Composition API pattern implementation for vanilla JavaScript libraries with context injection, async support, and namespace management.
npx @tessl/cli install tessl/npm-unctx@2.4.00
# unctx
1
2
**Composition API pattern implementation for vanilla JavaScript libraries with context injection, async support, and namespace management**
3
4
## Package Information
5
6
- **Name**: unctx
7
- **Type**: npm package
8
- **Language**: TypeScript/JavaScript
9
- **Latest Version**: 2.4.1
10
- **Installation**: `npm install unctx` or `yarn add unctx`
11
12
## Core Imports
13
14
```typescript
15
// ESM imports - Main context API
16
import {
17
createContext,
18
createNamespace,
19
getContext,
20
useContext,
21
withAsyncContext,
22
executeAsync,
23
defaultNamespace
24
} from "unctx";
25
26
// ESM imports - Build-time transformation (separate entry points)
27
import { unctxPlugin } from "unctx/plugin";
28
import { createTransformer } from "unctx/transform";
29
30
// CommonJS imports
31
const { createContext, createNamespace, getContext, useContext } = require("unctx");
32
```
33
34
## Basic Usage
35
36
```typescript
37
import { createContext } from "unctx";
38
39
// Create a typed context
40
const userContext = createContext<User>();
41
42
// Use context synchronously
43
userContext.call({ id: 1, name: "Alice" }, () => {
44
const user = userContext.use(); // { id: 1, name: "Alice" }
45
console.log(`Hello ${user.name}`);
46
});
47
48
// Use with namespace for version safety
49
import { useContext } from "unctx";
50
const useMyLibContext = useContext<MyData>("my-lib");
51
52
interface User {
53
id: number;
54
name: string;
55
}
56
```
57
58
## Architecture
59
60
unctx provides three main architectural components:
61
62
1. **Context Creation & Management** - Core context instances with typed injection
63
2. **Async Context Support** - Maintain context across async boundaries using AsyncLocalStorage or build-time transforms
64
3. **Namespace Management** - Global context registry to avoid version conflicts
65
4. **Build-time Transformation** - Babel/SWC plugins for automatic async context preservation
66
67
## Capabilities
68
69
### Context Creation & Management
70
Create and manage context instances with typed injection patterns.
71
72
```typescript { .api }
73
/**
74
* Creates a new context instance
75
*/
76
function createContext<T = any>(opts: ContextOptions): UseContext<T>;
77
78
interface UseContext<T> {
79
use(): T;
80
tryUse(): T | null;
81
set(instance?: T, replace?: boolean): void;
82
unset(): void;
83
call<R>(instance: T, callback: () => R): R;
84
callAsync<R>(instance: T, callback: () => R | Promise<R>): Promise<R>;
85
}
86
87
interface ContextOptions {
88
asyncContext?: boolean;
89
AsyncLocalStorage?: typeof AsyncLocalStorage;
90
}
91
```
92
93
[Context Creation & Management](./context-creation.md)
94
95
### Namespace Management
96
Global context registry system to avoid conflicts between library versions.
97
98
```typescript { .api }
99
/**
100
* Create a namespace for managing multiple contexts
101
*/
102
function createNamespace<T = any>(defaultOpts: ContextOptions): ContextNamespace;
103
104
/**
105
* Get context from default global namespace
106
*/
107
function getContext<T>(key: string, opts?: ContextOptions): UseContext<T>;
108
109
/**
110
* Get use function for named context
111
*/
112
function useContext<T>(key: string, opts?: ContextOptions): () => T;
113
114
interface ContextNamespace {
115
get<T>(key: string, opts?: ContextOptions): UseContext<T>;
116
}
117
```
118
119
[Namespace Management](./namespace-management.md)
120
121
### Async Context Support
122
Maintain context across async boundaries using AsyncLocalStorage or build-time transformation.
123
124
```typescript { .api }
125
/**
126
* Wrapper for async functions requiring context preservation
127
*/
128
function withAsyncContext<T>(fn: () => Promise<T>, transformed?: boolean): () => Promise<T>;
129
130
/**
131
* Execute async function with context restoration helpers
132
*/
133
function executeAsync<T>(fn: () => Promise<T>): [Promise<T>, () => void];
134
```
135
136
[Async Context Support](./async-context.md)
137
138
### Build-time Transformation
139
Universal bundler plugins for automatic async context transformation.
140
141
```typescript { .api }
142
/**
143
* Universal bundler plugin for async context transformation
144
*/
145
const unctxPlugin: {
146
rollup(): Plugin;
147
vite(): Plugin;
148
webpack(): Plugin;
149
};
150
151
/**
152
* Create AST transformer for async context preservation
153
*/
154
function createTransformer(options?: TransformerOptions): {
155
transform(code: string): { code: string; magicString: MagicString } | undefined;
156
shouldTransform(code: string): boolean;
157
};
158
159
interface TransformerOptions {
160
asyncFunctions?: string[];
161
helperModule?: string;
162
helperName?: string;
163
objectDefinitions?: Record<string, string[]>;
164
}
165
```
166
167
[Build-time Transformation](./build-plugins.md)
168
169
## Types
170
171
```typescript { .api }
172
interface UseContext<T> {
173
/**
174
* Get the current context. Throws if no context is set.
175
*/
176
use(): T;
177
178
/**
179
* Get the current context. Returns null when no context is set.
180
*/
181
tryUse(): T | null;
182
183
/**
184
* Set the context as Singleton Pattern.
185
*/
186
set(instance?: T, replace?: boolean): void;
187
188
/**
189
* Clear current context.
190
*/
191
unset(): void;
192
193
/**
194
* Execute a synchronous function with the provided context.
195
*/
196
call<R>(instance: T, callback: () => R): R;
197
198
/**
199
* Execute an asynchronous function with the provided context.
200
* Requires installing the transform plugin to work properly.
201
*/
202
callAsync<R>(instance: T, callback: () => R | Promise<R>): Promise<R>;
203
}
204
205
interface ContextOptions {
206
/**
207
* Enable async context support using AsyncLocalStorage
208
*/
209
asyncContext?: boolean;
210
211
/**
212
* AsyncLocalStorage implementation for async context
213
*/
214
AsyncLocalStorage?: typeof AsyncLocalStorage;
215
}
216
217
interface ContextNamespace {
218
/**
219
* Get or create a context by key
220
*/
221
get<T>(key: string, opts?: ContextOptions): UseContext<T>;
222
}
223
224
/**
225
* Default global namespace instance
226
* Used by getContext and useContext functions
227
*/
228
const defaultNamespace: ContextNamespace;
229
```