@andrew_l/context 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +27 -0
- package/dist/index.cjs +205 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +151 -0
- package/dist/index.d.mts +151 -0
- package/dist/index.d.ts +151 -0
- package/dist/index.mjs +195 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Andrew L. <andrew.io.dev@gmail.com>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Description
|
|
2
|
+
|
|
3
|
+
Bind async context like vue composition api.
|
|
4
|
+
|
|
5
|
+
[Documentation](https://men232.github.io/toolkit/reference/@andrew_l/context/)
|
|
6
|
+
|
|
7
|
+
# Usage
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
import { delay } from '@andrew_l/toolkit';
|
|
11
|
+
import { withContext } from '@andrew_l/context';
|
|
12
|
+
|
|
13
|
+
const main = withContext(() => {
|
|
14
|
+
provide('user', { id: 1, name: 'Andrew' });
|
|
15
|
+
|
|
16
|
+
await delay(1000);
|
|
17
|
+
|
|
18
|
+
doCoolStaff();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const doCoolStaff = () => {
|
|
22
|
+
const user = inject('user');
|
|
23
|
+
console.log(user); // { id: 1, name: 'Andrew' }
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
main();
|
|
27
|
+
```
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const toolkit = require('@andrew_l/toolkit');
|
|
4
|
+
|
|
5
|
+
let idSec = 0;
|
|
6
|
+
let ALS;
|
|
7
|
+
let currentScope = null;
|
|
8
|
+
toolkit.catchError(async () => {
|
|
9
|
+
ALS = new (await import('node:async_hooks')).AsyncLocalStorage();
|
|
10
|
+
});
|
|
11
|
+
class Scope {
|
|
12
|
+
constructor(detached = false) {
|
|
13
|
+
this.detached = detached;
|
|
14
|
+
this.id = ++idSec;
|
|
15
|
+
if (!detached) {
|
|
16
|
+
this.parent = getCurrentScope();
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* @internal
|
|
21
|
+
*/
|
|
22
|
+
id;
|
|
23
|
+
/**
|
|
24
|
+
* @internal
|
|
25
|
+
*/
|
|
26
|
+
providers = /* @__PURE__ */ new Map();
|
|
27
|
+
/**
|
|
28
|
+
* @internal
|
|
29
|
+
*/
|
|
30
|
+
parent = null;
|
|
31
|
+
/**
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
34
|
+
cleanups = [];
|
|
35
|
+
/**
|
|
36
|
+
* @internal
|
|
37
|
+
*/
|
|
38
|
+
_activeRuns = 0;
|
|
39
|
+
run(fn) {
|
|
40
|
+
this._activeRuns++;
|
|
41
|
+
const onComplete = ([err, result]) => {
|
|
42
|
+
this._activeRuns--;
|
|
43
|
+
if (this._activeRuns === 0) {
|
|
44
|
+
this.stop();
|
|
45
|
+
}
|
|
46
|
+
if (err) {
|
|
47
|
+
throw err;
|
|
48
|
+
}
|
|
49
|
+
return result;
|
|
50
|
+
};
|
|
51
|
+
const r = runInScope(this, fn);
|
|
52
|
+
if (toolkit.isPromise(r)) {
|
|
53
|
+
return r.then(onComplete);
|
|
54
|
+
}
|
|
55
|
+
return onComplete(r);
|
|
56
|
+
}
|
|
57
|
+
stop() {
|
|
58
|
+
for (let i = 0, l = this.cleanups.length; i < l; i++) {
|
|
59
|
+
this.cleanups[i]();
|
|
60
|
+
}
|
|
61
|
+
this.cleanups.length = 0;
|
|
62
|
+
}
|
|
63
|
+
get active() {
|
|
64
|
+
return this._activeRuns > 0;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function createScope(detached) {
|
|
68
|
+
return new Scope(detached);
|
|
69
|
+
}
|
|
70
|
+
function getCurrentScope() {
|
|
71
|
+
if (ALS) {
|
|
72
|
+
return ALS.getStore() ?? null;
|
|
73
|
+
}
|
|
74
|
+
return currentScope;
|
|
75
|
+
}
|
|
76
|
+
function setCurrentScope(scope) {
|
|
77
|
+
if (ALS) {
|
|
78
|
+
ALS.enterWith(scope);
|
|
79
|
+
} else {
|
|
80
|
+
currentScope = scope;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function runInScope(scope, fn) {
|
|
84
|
+
if (ALS) {
|
|
85
|
+
return toolkit.catchError(() => ALS.run(scope, fn));
|
|
86
|
+
}
|
|
87
|
+
const prevScope = getCurrentScope();
|
|
88
|
+
const onComplete = ([err, result2]) => {
|
|
89
|
+
if (prevScope) {
|
|
90
|
+
setCurrentScope(prevScope);
|
|
91
|
+
} else {
|
|
92
|
+
unsetCurrentScope();
|
|
93
|
+
}
|
|
94
|
+
return [err, result2];
|
|
95
|
+
};
|
|
96
|
+
const result = toolkit.catchError(fn);
|
|
97
|
+
if (toolkit.isPromise(result)) {
|
|
98
|
+
return result.then(onComplete);
|
|
99
|
+
}
|
|
100
|
+
return onComplete(result);
|
|
101
|
+
}
|
|
102
|
+
const unsetCurrentScope = () => {
|
|
103
|
+
if (ALS) {
|
|
104
|
+
ALS.enterWith(null);
|
|
105
|
+
} else {
|
|
106
|
+
currentScope = null;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
function provide(key, value, enterWith) {
|
|
111
|
+
let currentScope = getCurrentScope();
|
|
112
|
+
if (!currentScope) {
|
|
113
|
+
if (enterWith) {
|
|
114
|
+
currentScope = new Scope();
|
|
115
|
+
setCurrentScope(currentScope);
|
|
116
|
+
} else {
|
|
117
|
+
console.warn(
|
|
118
|
+
`provide() is called when there is no active scope to be associated with.
|
|
119
|
+
` + toolkit.captureStackTrace(provide)
|
|
120
|
+
);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
currentScope.providers.set(key, value);
|
|
125
|
+
}
|
|
126
|
+
function inject(key, defaultValue) {
|
|
127
|
+
let currentScope = getCurrentScope();
|
|
128
|
+
if (!currentScope) {
|
|
129
|
+
console.warn(
|
|
130
|
+
`inject() is called when there is no active scope to be associated with.
|
|
131
|
+
` + toolkit.captureStackTrace(inject)
|
|
132
|
+
);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const handled = /* @__PURE__ */ new WeakSet();
|
|
136
|
+
let value;
|
|
137
|
+
do {
|
|
138
|
+
value = currentScope.providers.get(key);
|
|
139
|
+
handled.add(currentScope);
|
|
140
|
+
currentScope = currentScope.parent;
|
|
141
|
+
} while (currentScope && value === void 0 && !handled.has(currentScope));
|
|
142
|
+
if (value === void 0 && defaultValue !== void 0) {
|
|
143
|
+
value = toolkit.isFunction(defaultValue) ? defaultValue() : defaultValue;
|
|
144
|
+
}
|
|
145
|
+
return value;
|
|
146
|
+
}
|
|
147
|
+
function hasInjectionContext() {
|
|
148
|
+
return !!getCurrentScope();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function createContext(providerName, contextName) {
|
|
152
|
+
const symbolDescription = typeof providerName === "string" && !contextName ? `${providerName}Context` : contextName;
|
|
153
|
+
const injectionKey = Symbol(symbolDescription);
|
|
154
|
+
const injectContext = (fallback) => {
|
|
155
|
+
const context = inject(injectionKey, fallback);
|
|
156
|
+
if (context) return context;
|
|
157
|
+
if (context === null) return context;
|
|
158
|
+
throw new Error(
|
|
159
|
+
`Injection \`${injectionKey.toString()}\` not found. Must be used within ${Array.isArray(providerName) ? `one of the following providers: ${providerName.join(", ")}` : `\`${providerName}\``}`
|
|
160
|
+
);
|
|
161
|
+
};
|
|
162
|
+
const provideContext = (contextValue) => {
|
|
163
|
+
provide(injectionKey, contextValue);
|
|
164
|
+
return contextValue;
|
|
165
|
+
};
|
|
166
|
+
return [injectContext, provideContext];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function onScopeDispose(fn) {
|
|
170
|
+
const activeScope = getCurrentScope();
|
|
171
|
+
toolkit.assert.ok(
|
|
172
|
+
activeScope,
|
|
173
|
+
"onScopeDispose() is called when there is no active scope to be associated with." + toolkit.captureStackTrace(onScopeDispose)
|
|
174
|
+
);
|
|
175
|
+
activeScope.cleanups.push(fn);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function withContext(fn, detached = false) {
|
|
179
|
+
return function(...args) {
|
|
180
|
+
const scope = createScope(detached);
|
|
181
|
+
return scope.run(fn.bind(this, args));
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
function runWithContext(fn, isolated = false) {
|
|
185
|
+
return withContext(fn, isolated)();
|
|
186
|
+
}
|
|
187
|
+
function bindContext(fn) {
|
|
188
|
+
const activeScope = getCurrentScope();
|
|
189
|
+
toolkit.assert.ok(
|
|
190
|
+
activeScope,
|
|
191
|
+
"bindContext() is called when there is no active scope to be associated with."
|
|
192
|
+
);
|
|
193
|
+
return () => activeScope.run(fn);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
exports.bindContext = bindContext;
|
|
197
|
+
exports.createContext = createContext;
|
|
198
|
+
exports.getCurrentScope = getCurrentScope;
|
|
199
|
+
exports.hasInjectionContext = hasInjectionContext;
|
|
200
|
+
exports.inject = inject;
|
|
201
|
+
exports.onScopeDispose = onScopeDispose;
|
|
202
|
+
exports.provide = provide;
|
|
203
|
+
exports.runWithContext = runWithContext;
|
|
204
|
+
exports.withContext = withContext;
|
|
205
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/scope.ts","../src/hooks/provide.ts","../src/hooks/createContext.ts","../src/hooks/onScopeDispose.ts","../src/index.ts"],"sourcesContent":["import { type Awaitable, catchError, isPromise } from '@andrew_l/toolkit';\nimport type { AsyncLocalStorage } from 'node:async_hooks';\n\nlet idSec = 0;\nlet ALS: AsyncLocalStorage<Scope | null> | undefined;\nlet currentScope: Scope | null = null;\n\ncatchError(async () => {\n ALS = new (\n await import('node:async_hooks')\n ).AsyncLocalStorage<Scope | null>();\n});\n\nexport class Scope {\n /**\n * @internal\n */\n id: number;\n\n /**\n * @internal\n */\n providers = new Map<any, any>();\n\n /**\n * @internal\n */\n parent: Scope | null = null;\n\n /**\n * @internal\n */\n cleanups: (() => void)[] = [];\n\n /**\n * @internal\n */\n private _activeRuns: number = 0;\n\n constructor(public detached = false) {\n this.id = ++idSec;\n\n if (!detached) {\n this.parent = getCurrentScope();\n }\n }\n\n run<T>(fn: () => T): T {\n this._activeRuns++;\n\n const onComplete = ([err, result]: [Error | undefined, any]): T => {\n this._activeRuns--;\n\n if (this._activeRuns === 0) {\n this.stop();\n }\n\n if (err) {\n throw err;\n }\n\n return result;\n };\n\n const r = runInScope(this, fn);\n\n if (isPromise<any>(r)) {\n return r.then(onComplete) as T;\n }\n\n return onComplete(r);\n }\n\n stop() {\n for (let i = 0, l = this.cleanups.length; i < l; i++) {\n this.cleanups[i]();\n }\n\n this.cleanups.length = 0;\n }\n\n get active(): boolean {\n return this._activeRuns > 0;\n }\n}\n\n/**\n * @param detached - Can be used to create a \"detached\" scope.\n */\nexport function createScope(detached?: boolean): Scope {\n return new Scope(detached);\n}\n\n/**\n * @group Main\n */\nexport function getCurrentScope(): Scope | null {\n if (ALS) {\n return ALS.getStore() ?? null;\n }\n\n return currentScope;\n}\n\nexport function setCurrentScope(scope: Scope) {\n if (ALS) {\n ALS.enterWith(scope);\n } else {\n currentScope = scope;\n }\n}\n\nfunction runInScope<T>(\n scope: Scope,\n fn: () => T,\n): Awaitable<[Error | undefined, any]> {\n if (ALS) {\n return catchError(() => ALS!.run(scope, fn));\n }\n\n const prevScope = getCurrentScope();\n\n const onComplete = ([err, result]: [Error | undefined, any]): [\n Error | undefined,\n any,\n ] => {\n if (prevScope) {\n setCurrentScope(prevScope);\n } else {\n unsetCurrentScope();\n }\n\n return [err, result];\n };\n\n const result = catchError(fn);\n\n if (isPromise<any>(result)) {\n return result.then(onComplete);\n }\n\n return onComplete(result);\n}\n\nconst unsetCurrentScope = (): void => {\n if (ALS) {\n ALS.enterWith(null);\n } else {\n currentScope = null;\n }\n};\n","import { captureStackTrace, isFunction } from '@andrew_l/toolkit';\nimport { Scope, getCurrentScope, setCurrentScope } from '../scope';\n\nexport type ProvideKey = symbol | string | number | object;\nexport type ProvideValue<T = unknown> = T | undefined;\nexport type InjectionKey = symbol | string | number | object;\n\n/**\n * To provide data to a descendants\n * @param enterWith Enter into injection context (Experimental)\n * @group Main\n */\nexport function provide(key: ProvideKey, value: any, enterWith?: boolean) {\n let currentScope = getCurrentScope();\n\n if (!currentScope) {\n if (enterWith) {\n currentScope = new Scope();\n setCurrentScope(currentScope);\n } else {\n console.warn(\n `provide() is called when there is no active scope to be associated with.\\n` +\n captureStackTrace(provide),\n );\n return;\n }\n }\n\n currentScope.providers.set(key, value);\n}\n\n/**\n * Inject previously provided data\n * @group Main\n */\nexport function inject<T = any>(\n key: ProvideKey,\n defaultValue?: T | (() => T),\n): ProvideValue<T> {\n let currentScope = getCurrentScope();\n\n if (!currentScope) {\n console.warn(\n `inject() is called when there is no active scope to be associated with.\\n` +\n captureStackTrace(inject),\n );\n return;\n }\n\n const handled = new WeakSet();\n\n let value;\n\n do {\n value = currentScope!.providers.get(key);\n handled.add(currentScope!);\n currentScope = currentScope!.parent;\n } while (currentScope && value === undefined && !handled.has(currentScope));\n\n if (value === undefined && defaultValue !== undefined) {\n value = isFunction(defaultValue) ? defaultValue() : defaultValue;\n }\n\n return value;\n}\n\n/**\n * Returns true if `inject()` can be used without warning about being called in the wrong place.\n * @group Main\n */\nexport function hasInjectionContext() {\n return !!getCurrentScope();\n}\n","import { type InjectionKey, inject, provide } from './provide';\n\n/**\n * Wrapper around `provide/inject` function to simple usage.\n *\n * @param providerName - The name(s) of the providing the context.\n *\n * There are situations where context can come from multiple scopes. In such cases, you might need to give an array of names to provide your context, instead of just a single string.\n *\n * @param contextName The description for injection key symbol.\n *\n * @example\n * const [injectTraceId, provideTraceId] = createContext<string>('withContext');\n *\n * // this function will returns the same trace if for execution context\n * export const useTraceId = () => {\n * let traceId = injectTraceId(null);\n *\n * if (!traceId) {\n * traceId = uuidv4();\n * provideTraceId(traceId);\n * }\n *\n * return traceId;\n * };\n *\n * @group Main\n */\nexport function createContext<ContextValue>(\n providerName: string | string[],\n contextName?: string,\n) {\n const symbolDescription =\n typeof providerName === 'string' && !contextName\n ? `${providerName}Context`\n : contextName;\n\n const injectionKey: InjectionKey = Symbol(symbolDescription);\n\n /**\n * @param fallback The context value to return if the injection fails.\n *\n * @throws When context injection failed and no fallback is specified.\n * This happens when the scope injecting the context is not a child of the root scope providing the context.\n */\n const injectContext = <\n T extends ContextValue | null | undefined = ContextValue,\n >(\n fallback?: T | (() => T),\n ): T extends null ? ContextValue | null : ContextValue => {\n const context = inject(injectionKey, fallback);\n if (context) return context;\n\n if (context === null) return context as any;\n\n throw new Error(\n `Injection \\`${injectionKey.toString()}\\` not found. Must be used within ${\n Array.isArray(providerName)\n ? `one of the following providers: ${providerName.join(', ')}`\n : `\\`${providerName}\\``\n }`,\n );\n };\n\n const provideContext = (contextValue: ContextValue) => {\n provide(injectionKey, contextValue);\n return contextValue;\n };\n\n return [injectContext, provideContext] as const;\n}\n","import { assert, captureStackTrace } from '@andrew_l/toolkit';\nimport { getCurrentScope } from '../scope';\n\n/**\n * The callback will be invoked when the associated context completes.\n *\n * @example\n * const fn = withContext(() => {\n * onScopeDispose(() => {\n * console.log(2);\n * });\n *\n * console.log(1);\n * });\n *\n * fn();\n *\n * console.log(3);\n *\n * // 1\n * // 2\n * // 3\n *\n * @group Main\n */\nexport function onScopeDispose(fn: () => void) {\n const activeScope = getCurrentScope();\n\n assert.ok(\n activeScope,\n 'onScopeDispose() is called when there is no active scope to be associated with.' +\n captureStackTrace(onScopeDispose),\n );\n\n activeScope.cleanups.push(fn);\n}\n","import { type AnyFunction, assert } from '@andrew_l/toolkit';\nimport { createScope, getCurrentScope } from './scope';\n\nexport * from './hooks/createContext';\nexport * from './hooks/onScopeDispose';\nexport * from './hooks/provide';\nexport { getCurrentScope } from './scope';\n\n/**\n * Creates a function within the injection context and returns its result. Providers/injections are only accessible within the callback function.\n * @param isolated Do not inject parent providers into this context (Default: `false`)\n *\n * @example\n * const main = withContext(() => {\n * provide('user', { id: 1, name: 'Andrew' });\n * doCoolStaff();\n * });\n *\n * const doCoolStaff = () => {\n * const user = inject('user');\n * console.log(user); // { id: 1, name: 'Andrew' }\n * };\n *\n * main();\n *\n * @group Main\n */\nexport function withContext<T extends AnyFunction>(fn: T, detached = false): T {\n return function (this: any, ...args: any[]) {\n const scope = createScope(detached);\n return scope.run(fn.bind(this, args));\n } as T;\n}\n\n/**\n * Runs a function within the injection context and returns its result. Providers/injections are only accessible inside the callback function.\n * @param isolated Do not inject parent providers into this context (Default: `false`)\n * @group Main\n */\nexport function runWithContext<T = any>(fn: () => T, isolated = false): T {\n return withContext(fn, isolated)();\n}\n\n/**\n * Binds the current context to the provided function. Useful for creating callbacks with the current context, such as `setTimeout` or `EventEmitter` handlers.\n * @example\n * const main = withContext(() => {\n * provide(\"user\", { id: 1, name: \"Andrew\" });\n *\n * setInterval(bindContext(() => {\n * const user = inject(\"user\");\n * console.log(user); // { id: 1, name: 'Andrew' }\n * }));\n * });\n *\n * main();\n *\n * @group Main\n */\nexport function bindContext<T>(fn: () => T): () => T {\n const activeScope = getCurrentScope();\n\n assert.ok(\n activeScope,\n 'bindContext() is called when there is no active scope to be associated with.',\n );\n\n return () => activeScope.run(fn);\n}\n"],"names":["catchError","isPromise","result","captureStackTrace","isFunction","assert"],"mappings":";;;;AAGA,IAAI,KAAQ,GAAA,CAAA,CAAA;AACZ,IAAI,GAAA,CAAA;AACJ,IAAI,YAA6B,GAAA,IAAA,CAAA;AAEjCA,kBAAA,CAAW,YAAY;AACrB,EAAA,GAAA,GAAM,IACJ,CAAA,MAAM,OAAO,kBAAkB,GAC/B,iBAAgC,EAAA,CAAA;AACpC,CAAC,CAAA,CAAA;AAEM,MAAM,KAAM,CAAA;AAAA,EA0BjB,WAAA,CAAmB,WAAW,KAAO,EAAA;AAAlB,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA,CAAA;AACjB,IAAA,IAAA,CAAK,KAAK,EAAE,KAAA,CAAA;AAEZ,IAAA,IAAI,CAAC,QAAU,EAAA;AACb,MAAA,IAAA,CAAK,SAAS,eAAgB,EAAA,CAAA;AAAA,KAChC;AAAA,GACF;AAAA;AAAA;AAAA;AAAA,EA5BA,EAAA,CAAA;AAAA;AAAA;AAAA;AAAA,EAKA,SAAA,uBAAgB,GA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Ae,cAAc,CAAA,CAAA;AACvC;;AC7CO,SAAS,eAAe,EAAgB,EAAA;AAC7C,EAAA,MAAM,cAAc,eAAgB,EAAA,CAAA;AAEpC,EAAOC,cAAA,CAAA,EAAA;AAAA,IACL,WAAA;AAAA,IACA,iFAAA,GACEF,0BAAkB,cAAc,CAAA;AAAA,GACpC,CAAA;AAEA,EAAY,WAAA,CAAA,QAAA,CAAS,KAAK,EAAE,CAAA,CAAA;AAC9B;;ACRgB,SAAA,WAAA,CAAmC,EAAO,EAAA,QAAA,GAAW,KAAU,EAAA;AAC7E,EAAA,OAAO,YAAwB,IAAa,EAAA;AAC1C,IAAM,MAAA,KAAA,GAAQ,YAAY,QAAQ,CAAA,CAAA;AAClC,IAAA,OAAO,MAAM,GAAI,CAAA,EAAA,CAAG,IAAK,CAAA,IAAA,EAAM,IAAI,CAAC,CAAA,CAAA;AAAA,GACtC,CAAA;AACF,CAAA;AAOgB,SAAA,cAAA,CAAwB,EAAa,EAAA,QAAA,GAAW,KAAU,EAAA;AACxE,EAAO,OAAA,WAAA,CAAY,EAAI,EAAA,QAAQ,CAAE,EAAA,CAAA;AACnC,CAAA;AAkBO,SAAS,YAAe,EAAsB,EAAA;AACnD,EAAA,MAAM,cAAc,eAAgB,EAAA,CAAA;AAEpC,EAAOE,cAAA,CAAA,EAAA;AAAA,IACL,WAAA;AAAA,IACA,8EAAA;AAAA,GACF,CAAA;AAEA,EAAO,OAAA,MAAM,WAAY,CAAA,GAAA,CAAI,EAAE,CAAA,CAAA;AACjC;;;;;;;;;;;;"}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { AnyFunction } from '@andrew_l/toolkit';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Wrapper around `provide/inject` function to simple usage.
|
|
5
|
+
*
|
|
6
|
+
* @param providerName - The name(s) of the providing the context.
|
|
7
|
+
*
|
|
8
|
+
* There are situations where context can come from multiple scopes. In such cases, you might need to give an array of names to provide your context, instead of just a single string.
|
|
9
|
+
*
|
|
10
|
+
* @param contextName The description for injection key symbol.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* const [injectTraceId, provideTraceId] = createContext<string>('withContext');
|
|
14
|
+
*
|
|
15
|
+
* // this function will returns the same trace if for execution context
|
|
16
|
+
* export const useTraceId = () => {
|
|
17
|
+
* let traceId = injectTraceId(null);
|
|
18
|
+
*
|
|
19
|
+
* if (!traceId) {
|
|
20
|
+
* traceId = uuidv4();
|
|
21
|
+
* provideTraceId(traceId);
|
|
22
|
+
* }
|
|
23
|
+
*
|
|
24
|
+
* return traceId;
|
|
25
|
+
* };
|
|
26
|
+
*
|
|
27
|
+
* @group Main
|
|
28
|
+
*/
|
|
29
|
+
declare function createContext<ContextValue>(providerName: string | string[], contextName?: string): readonly [<T extends ContextValue | null | undefined = ContextValue>(fallback?: T | (() => T)) => T extends null ? ContextValue | null : ContextValue, (contextValue: ContextValue) => ContextValue];
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The callback will be invoked when the associated context completes.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* const fn = withContext(() => {
|
|
36
|
+
* onScopeDispose(() => {
|
|
37
|
+
* console.log(2);
|
|
38
|
+
* });
|
|
39
|
+
*
|
|
40
|
+
* console.log(1);
|
|
41
|
+
* });
|
|
42
|
+
*
|
|
43
|
+
* fn();
|
|
44
|
+
*
|
|
45
|
+
* console.log(3);
|
|
46
|
+
*
|
|
47
|
+
* // 1
|
|
48
|
+
* // 2
|
|
49
|
+
* // 3
|
|
50
|
+
*
|
|
51
|
+
* @group Main
|
|
52
|
+
*/
|
|
53
|
+
declare function onScopeDispose(fn: () => void): void;
|
|
54
|
+
|
|
55
|
+
type ProvideKey = symbol | string | number | object;
|
|
56
|
+
type ProvideValue<T = unknown> = T | undefined;
|
|
57
|
+
type InjectionKey = symbol | string | number | object;
|
|
58
|
+
/**
|
|
59
|
+
* To provide data to a descendants
|
|
60
|
+
* @param enterWith Enter into injection context (Experimental)
|
|
61
|
+
* @group Main
|
|
62
|
+
*/
|
|
63
|
+
declare function provide(key: ProvideKey, value: any, enterWith?: boolean): void;
|
|
64
|
+
/**
|
|
65
|
+
* Inject previously provided data
|
|
66
|
+
* @group Main
|
|
67
|
+
*/
|
|
68
|
+
declare function inject<T = any>(key: ProvideKey, defaultValue?: T | (() => T)): ProvideValue<T>;
|
|
69
|
+
/**
|
|
70
|
+
* Returns true if `inject()` can be used without warning about being called in the wrong place.
|
|
71
|
+
* @group Main
|
|
72
|
+
*/
|
|
73
|
+
declare function hasInjectionContext(): boolean;
|
|
74
|
+
|
|
75
|
+
declare class Scope {
|
|
76
|
+
detached: boolean;
|
|
77
|
+
/**
|
|
78
|
+
* @internal
|
|
79
|
+
*/
|
|
80
|
+
id: number;
|
|
81
|
+
/**
|
|
82
|
+
* @internal
|
|
83
|
+
*/
|
|
84
|
+
providers: Map<any, any>;
|
|
85
|
+
/**
|
|
86
|
+
* @internal
|
|
87
|
+
*/
|
|
88
|
+
parent: Scope | null;
|
|
89
|
+
/**
|
|
90
|
+
* @internal
|
|
91
|
+
*/
|
|
92
|
+
cleanups: (() => void)[];
|
|
93
|
+
/**
|
|
94
|
+
* @internal
|
|
95
|
+
*/
|
|
96
|
+
private _activeRuns;
|
|
97
|
+
constructor(detached?: boolean);
|
|
98
|
+
run<T>(fn: () => T): T;
|
|
99
|
+
stop(): void;
|
|
100
|
+
get active(): boolean;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* @group Main
|
|
104
|
+
*/
|
|
105
|
+
declare function getCurrentScope(): Scope | null;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Creates a function within the injection context and returns its result. Providers/injections are only accessible within the callback function.
|
|
109
|
+
* @param isolated Do not inject parent providers into this context (Default: `false`)
|
|
110
|
+
*
|
|
111
|
+
* @example
|
|
112
|
+
* const main = withContext(() => {
|
|
113
|
+
* provide('user', { id: 1, name: 'Andrew' });
|
|
114
|
+
* doCoolStaff();
|
|
115
|
+
* });
|
|
116
|
+
*
|
|
117
|
+
* const doCoolStaff = () => {
|
|
118
|
+
* const user = inject('user');
|
|
119
|
+
* console.log(user); // { id: 1, name: 'Andrew' }
|
|
120
|
+
* };
|
|
121
|
+
*
|
|
122
|
+
* main();
|
|
123
|
+
*
|
|
124
|
+
* @group Main
|
|
125
|
+
*/
|
|
126
|
+
declare function withContext<T extends AnyFunction>(fn: T, detached?: boolean): T;
|
|
127
|
+
/**
|
|
128
|
+
* Runs a function within the injection context and returns its result. Providers/injections are only accessible inside the callback function.
|
|
129
|
+
* @param isolated Do not inject parent providers into this context (Default: `false`)
|
|
130
|
+
* @group Main
|
|
131
|
+
*/
|
|
132
|
+
declare function runWithContext<T = any>(fn: () => T, isolated?: boolean): T;
|
|
133
|
+
/**
|
|
134
|
+
* Binds the current context to the provided function. Useful for creating callbacks with the current context, such as `setTimeout` or `EventEmitter` handlers.
|
|
135
|
+
* @example
|
|
136
|
+
* const main = withContext(() => {
|
|
137
|
+
* provide("user", { id: 1, name: "Andrew" });
|
|
138
|
+
*
|
|
139
|
+
* setInterval(bindContext(() => {
|
|
140
|
+
* const user = inject("user");
|
|
141
|
+
* console.log(user); // { id: 1, name: 'Andrew' }
|
|
142
|
+
* }));
|
|
143
|
+
* });
|
|
144
|
+
*
|
|
145
|
+
* main();
|
|
146
|
+
*
|
|
147
|
+
* @group Main
|
|
148
|
+
*/
|
|
149
|
+
declare function bindContext<T>(fn: () => T): () => T;
|
|
150
|
+
|
|
151
|
+
export { type InjectionKey, type ProvideKey, type ProvideValue, bindContext, createContext, getCurrentScope, hasInjectionContext, inject, onScopeDispose, provide, runWithContext, withContext };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { AnyFunction } from '@andrew_l/toolkit';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Wrapper around `provide/inject` function to simple usage.
|
|
5
|
+
*
|
|
6
|
+
* @param providerName - The name(s) of the providing the context.
|
|
7
|
+
*
|
|
8
|
+
* There are situations where context can come from multiple scopes. In such cases, you might need to give an array of names to provide your context, instead of just a single string.
|
|
9
|
+
*
|
|
10
|
+
* @param contextName The description for injection key symbol.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* const [injectTraceId, provideTraceId] = createContext<string>('withContext');
|
|
14
|
+
*
|
|
15
|
+
* // this function will returns the same trace if for execution context
|
|
16
|
+
* export const useTraceId = () => {
|
|
17
|
+
* let traceId = injectTraceId(null);
|
|
18
|
+
*
|
|
19
|
+
* if (!traceId) {
|
|
20
|
+
* traceId = uuidv4();
|
|
21
|
+
* provideTraceId(traceId);
|
|
22
|
+
* }
|
|
23
|
+
*
|
|
24
|
+
* return traceId;
|
|
25
|
+
* };
|
|
26
|
+
*
|
|
27
|
+
* @group Main
|
|
28
|
+
*/
|
|
29
|
+
declare function createContext<ContextValue>(providerName: string | string[], contextName?: string): readonly [<T extends ContextValue | null | undefined = ContextValue>(fallback?: T | (() => T)) => T extends null ? ContextValue | null : ContextValue, (contextValue: ContextValue) => ContextValue];
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The callback will be invoked when the associated context completes.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* const fn = withContext(() => {
|
|
36
|
+
* onScopeDispose(() => {
|
|
37
|
+
* console.log(2);
|
|
38
|
+
* });
|
|
39
|
+
*
|
|
40
|
+
* console.log(1);
|
|
41
|
+
* });
|
|
42
|
+
*
|
|
43
|
+
* fn();
|
|
44
|
+
*
|
|
45
|
+
* console.log(3);
|
|
46
|
+
*
|
|
47
|
+
* // 1
|
|
48
|
+
* // 2
|
|
49
|
+
* // 3
|
|
50
|
+
*
|
|
51
|
+
* @group Main
|
|
52
|
+
*/
|
|
53
|
+
declare function onScopeDispose(fn: () => void): void;
|
|
54
|
+
|
|
55
|
+
type ProvideKey = symbol | string | number | object;
|
|
56
|
+
type ProvideValue<T = unknown> = T | undefined;
|
|
57
|
+
type InjectionKey = symbol | string | number | object;
|
|
58
|
+
/**
|
|
59
|
+
* To provide data to a descendants
|
|
60
|
+
* @param enterWith Enter into injection context (Experimental)
|
|
61
|
+
* @group Main
|
|
62
|
+
*/
|
|
63
|
+
declare function provide(key: ProvideKey, value: any, enterWith?: boolean): void;
|
|
64
|
+
/**
|
|
65
|
+
* Inject previously provided data
|
|
66
|
+
* @group Main
|
|
67
|
+
*/
|
|
68
|
+
declare function inject<T = any>(key: ProvideKey, defaultValue?: T | (() => T)): ProvideValue<T>;
|
|
69
|
+
/**
|
|
70
|
+
* Returns true if `inject()` can be used without warning about being called in the wrong place.
|
|
71
|
+
* @group Main
|
|
72
|
+
*/
|
|
73
|
+
declare function hasInjectionContext(): boolean;
|
|
74
|
+
|
|
75
|
+
declare class Scope {
|
|
76
|
+
detached: boolean;
|
|
77
|
+
/**
|
|
78
|
+
* @internal
|
|
79
|
+
*/
|
|
80
|
+
id: number;
|
|
81
|
+
/**
|
|
82
|
+
* @internal
|
|
83
|
+
*/
|
|
84
|
+
providers: Map<any, any>;
|
|
85
|
+
/**
|
|
86
|
+
* @internal
|
|
87
|
+
*/
|
|
88
|
+
parent: Scope | null;
|
|
89
|
+
/**
|
|
90
|
+
* @internal
|
|
91
|
+
*/
|
|
92
|
+
cleanups: (() => void)[];
|
|
93
|
+
/**
|
|
94
|
+
* @internal
|
|
95
|
+
*/
|
|
96
|
+
private _activeRuns;
|
|
97
|
+
constructor(detached?: boolean);
|
|
98
|
+
run<T>(fn: () => T): T;
|
|
99
|
+
stop(): void;
|
|
100
|
+
get active(): boolean;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* @group Main
|
|
104
|
+
*/
|
|
105
|
+
declare function getCurrentScope(): Scope | null;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Creates a function within the injection context and returns its result. Providers/injections are only accessible within the callback function.
|
|
109
|
+
* @param isolated Do not inject parent providers into this context (Default: `false`)
|
|
110
|
+
*
|
|
111
|
+
* @example
|
|
112
|
+
* const main = withContext(() => {
|
|
113
|
+
* provide('user', { id: 1, name: 'Andrew' });
|
|
114
|
+
* doCoolStaff();
|
|
115
|
+
* });
|
|
116
|
+
*
|
|
117
|
+
* const doCoolStaff = () => {
|
|
118
|
+
* const user = inject('user');
|
|
119
|
+
* console.log(user); // { id: 1, name: 'Andrew' }
|
|
120
|
+
* };
|
|
121
|
+
*
|
|
122
|
+
* main();
|
|
123
|
+
*
|
|
124
|
+
* @group Main
|
|
125
|
+
*/
|
|
126
|
+
declare function withContext<T extends AnyFunction>(fn: T, detached?: boolean): T;
|
|
127
|
+
/**
|
|
128
|
+
* Runs a function within the injection context and returns its result. Providers/injections are only accessible inside the callback function.
|
|
129
|
+
* @param isolated Do not inject parent providers into this context (Default: `false`)
|
|
130
|
+
* @group Main
|
|
131
|
+
*/
|
|
132
|
+
declare function runWithContext<T = any>(fn: () => T, isolated?: boolean): T;
|
|
133
|
+
/**
|
|
134
|
+
* Binds the current context to the provided function. Useful for creating callbacks with the current context, such as `setTimeout` or `EventEmitter` handlers.
|
|
135
|
+
* @example
|
|
136
|
+
* const main = withContext(() => {
|
|
137
|
+
* provide("user", { id: 1, name: "Andrew" });
|
|
138
|
+
*
|
|
139
|
+
* setInterval(bindContext(() => {
|
|
140
|
+
* const user = inject("user");
|
|
141
|
+
* console.log(user); // { id: 1, name: 'Andrew' }
|
|
142
|
+
* }));
|
|
143
|
+
* });
|
|
144
|
+
*
|
|
145
|
+
* main();
|
|
146
|
+
*
|
|
147
|
+
* @group Main
|
|
148
|
+
*/
|
|
149
|
+
declare function bindContext<T>(fn: () => T): () => T;
|
|
150
|
+
|
|
151
|
+
export { type InjectionKey, type ProvideKey, type ProvideValue, bindContext, createContext, getCurrentScope, hasInjectionContext, inject, onScopeDispose, provide, runWithContext, withContext };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { AnyFunction } from '@andrew_l/toolkit';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Wrapper around `provide/inject` function to simple usage.
|
|
5
|
+
*
|
|
6
|
+
* @param providerName - The name(s) of the providing the context.
|
|
7
|
+
*
|
|
8
|
+
* There are situations where context can come from multiple scopes. In such cases, you might need to give an array of names to provide your context, instead of just a single string.
|
|
9
|
+
*
|
|
10
|
+
* @param contextName The description for injection key symbol.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* const [injectTraceId, provideTraceId] = createContext<string>('withContext');
|
|
14
|
+
*
|
|
15
|
+
* // this function will returns the same trace if for execution context
|
|
16
|
+
* export const useTraceId = () => {
|
|
17
|
+
* let traceId = injectTraceId(null);
|
|
18
|
+
*
|
|
19
|
+
* if (!traceId) {
|
|
20
|
+
* traceId = uuidv4();
|
|
21
|
+
* provideTraceId(traceId);
|
|
22
|
+
* }
|
|
23
|
+
*
|
|
24
|
+
* return traceId;
|
|
25
|
+
* };
|
|
26
|
+
*
|
|
27
|
+
* @group Main
|
|
28
|
+
*/
|
|
29
|
+
declare function createContext<ContextValue>(providerName: string | string[], contextName?: string): readonly [<T extends ContextValue | null | undefined = ContextValue>(fallback?: T | (() => T)) => T extends null ? ContextValue | null : ContextValue, (contextValue: ContextValue) => ContextValue];
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The callback will be invoked when the associated context completes.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* const fn = withContext(() => {
|
|
36
|
+
* onScopeDispose(() => {
|
|
37
|
+
* console.log(2);
|
|
38
|
+
* });
|
|
39
|
+
*
|
|
40
|
+
* console.log(1);
|
|
41
|
+
* });
|
|
42
|
+
*
|
|
43
|
+
* fn();
|
|
44
|
+
*
|
|
45
|
+
* console.log(3);
|
|
46
|
+
*
|
|
47
|
+
* // 1
|
|
48
|
+
* // 2
|
|
49
|
+
* // 3
|
|
50
|
+
*
|
|
51
|
+
* @group Main
|
|
52
|
+
*/
|
|
53
|
+
declare function onScopeDispose(fn: () => void): void;
|
|
54
|
+
|
|
55
|
+
type ProvideKey = symbol | string | number | object;
|
|
56
|
+
type ProvideValue<T = unknown> = T | undefined;
|
|
57
|
+
type InjectionKey = symbol | string | number | object;
|
|
58
|
+
/**
|
|
59
|
+
* To provide data to a descendants
|
|
60
|
+
* @param enterWith Enter into injection context (Experimental)
|
|
61
|
+
* @group Main
|
|
62
|
+
*/
|
|
63
|
+
declare function provide(key: ProvideKey, value: any, enterWith?: boolean): void;
|
|
64
|
+
/**
|
|
65
|
+
* Inject previously provided data
|
|
66
|
+
* @group Main
|
|
67
|
+
*/
|
|
68
|
+
declare function inject<T = any>(key: ProvideKey, defaultValue?: T | (() => T)): ProvideValue<T>;
|
|
69
|
+
/**
|
|
70
|
+
* Returns true if `inject()` can be used without warning about being called in the wrong place.
|
|
71
|
+
* @group Main
|
|
72
|
+
*/
|
|
73
|
+
declare function hasInjectionContext(): boolean;
|
|
74
|
+
|
|
75
|
+
declare class Scope {
|
|
76
|
+
detached: boolean;
|
|
77
|
+
/**
|
|
78
|
+
* @internal
|
|
79
|
+
*/
|
|
80
|
+
id: number;
|
|
81
|
+
/**
|
|
82
|
+
* @internal
|
|
83
|
+
*/
|
|
84
|
+
providers: Map<any, any>;
|
|
85
|
+
/**
|
|
86
|
+
* @internal
|
|
87
|
+
*/
|
|
88
|
+
parent: Scope | null;
|
|
89
|
+
/**
|
|
90
|
+
* @internal
|
|
91
|
+
*/
|
|
92
|
+
cleanups: (() => void)[];
|
|
93
|
+
/**
|
|
94
|
+
* @internal
|
|
95
|
+
*/
|
|
96
|
+
private _activeRuns;
|
|
97
|
+
constructor(detached?: boolean);
|
|
98
|
+
run<T>(fn: () => T): T;
|
|
99
|
+
stop(): void;
|
|
100
|
+
get active(): boolean;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* @group Main
|
|
104
|
+
*/
|
|
105
|
+
declare function getCurrentScope(): Scope | null;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Creates a function within the injection context and returns its result. Providers/injections are only accessible within the callback function.
|
|
109
|
+
* @param isolated Do not inject parent providers into this context (Default: `false`)
|
|
110
|
+
*
|
|
111
|
+
* @example
|
|
112
|
+
* const main = withContext(() => {
|
|
113
|
+
* provide('user', { id: 1, name: 'Andrew' });
|
|
114
|
+
* doCoolStaff();
|
|
115
|
+
* });
|
|
116
|
+
*
|
|
117
|
+
* const doCoolStaff = () => {
|
|
118
|
+
* const user = inject('user');
|
|
119
|
+
* console.log(user); // { id: 1, name: 'Andrew' }
|
|
120
|
+
* };
|
|
121
|
+
*
|
|
122
|
+
* main();
|
|
123
|
+
*
|
|
124
|
+
* @group Main
|
|
125
|
+
*/
|
|
126
|
+
declare function withContext<T extends AnyFunction>(fn: T, detached?: boolean): T;
|
|
127
|
+
/**
|
|
128
|
+
* Runs a function within the injection context and returns its result. Providers/injections are only accessible inside the callback function.
|
|
129
|
+
* @param isolated Do not inject parent providers into this context (Default: `false`)
|
|
130
|
+
* @group Main
|
|
131
|
+
*/
|
|
132
|
+
declare function runWithContext<T = any>(fn: () => T, isolated?: boolean): T;
|
|
133
|
+
/**
|
|
134
|
+
* Binds the current context to the provided function. Useful for creating callbacks with the current context, such as `setTimeout` or `EventEmitter` handlers.
|
|
135
|
+
* @example
|
|
136
|
+
* const main = withContext(() => {
|
|
137
|
+
* provide("user", { id: 1, name: "Andrew" });
|
|
138
|
+
*
|
|
139
|
+
* setInterval(bindContext(() => {
|
|
140
|
+
* const user = inject("user");
|
|
141
|
+
* console.log(user); // { id: 1, name: 'Andrew' }
|
|
142
|
+
* }));
|
|
143
|
+
* });
|
|
144
|
+
*
|
|
145
|
+
* main();
|
|
146
|
+
*
|
|
147
|
+
* @group Main
|
|
148
|
+
*/
|
|
149
|
+
declare function bindContext<T>(fn: () => T): () => T;
|
|
150
|
+
|
|
151
|
+
export { type InjectionKey, type ProvideKey, type ProvideValue, bindContext, createContext, getCurrentScope, hasInjectionContext, inject, onScopeDispose, provide, runWithContext, withContext };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { catchError, isPromise, captureStackTrace, isFunction, assert } from '@andrew_l/toolkit';
|
|
2
|
+
|
|
3
|
+
let idSec = 0;
|
|
4
|
+
let ALS;
|
|
5
|
+
let currentScope = null;
|
|
6
|
+
catchError(async () => {
|
|
7
|
+
ALS = new (await import('node:async_hooks')).AsyncLocalStorage();
|
|
8
|
+
});
|
|
9
|
+
class Scope {
|
|
10
|
+
constructor(detached = false) {
|
|
11
|
+
this.detached = detached;
|
|
12
|
+
this.id = ++idSec;
|
|
13
|
+
if (!detached) {
|
|
14
|
+
this.parent = getCurrentScope();
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* @internal
|
|
19
|
+
*/
|
|
20
|
+
id;
|
|
21
|
+
/**
|
|
22
|
+
* @internal
|
|
23
|
+
*/
|
|
24
|
+
providers = /* @__PURE__ */ new Map();
|
|
25
|
+
/**
|
|
26
|
+
* @internal
|
|
27
|
+
*/
|
|
28
|
+
parent = null;
|
|
29
|
+
/**
|
|
30
|
+
* @internal
|
|
31
|
+
*/
|
|
32
|
+
cleanups = [];
|
|
33
|
+
/**
|
|
34
|
+
* @internal
|
|
35
|
+
*/
|
|
36
|
+
_activeRuns = 0;
|
|
37
|
+
run(fn) {
|
|
38
|
+
this._activeRuns++;
|
|
39
|
+
const onComplete = ([err, result]) => {
|
|
40
|
+
this._activeRuns--;
|
|
41
|
+
if (this._activeRuns === 0) {
|
|
42
|
+
this.stop();
|
|
43
|
+
}
|
|
44
|
+
if (err) {
|
|
45
|
+
throw err;
|
|
46
|
+
}
|
|
47
|
+
return result;
|
|
48
|
+
};
|
|
49
|
+
const r = runInScope(this, fn);
|
|
50
|
+
if (isPromise(r)) {
|
|
51
|
+
return r.then(onComplete);
|
|
52
|
+
}
|
|
53
|
+
return onComplete(r);
|
|
54
|
+
}
|
|
55
|
+
stop() {
|
|
56
|
+
for (let i = 0, l = this.cleanups.length; i < l; i++) {
|
|
57
|
+
this.cleanups[i]();
|
|
58
|
+
}
|
|
59
|
+
this.cleanups.length = 0;
|
|
60
|
+
}
|
|
61
|
+
get active() {
|
|
62
|
+
return this._activeRuns > 0;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function createScope(detached) {
|
|
66
|
+
return new Scope(detached);
|
|
67
|
+
}
|
|
68
|
+
function getCurrentScope() {
|
|
69
|
+
if (ALS) {
|
|
70
|
+
return ALS.getStore() ?? null;
|
|
71
|
+
}
|
|
72
|
+
return currentScope;
|
|
73
|
+
}
|
|
74
|
+
function setCurrentScope(scope) {
|
|
75
|
+
if (ALS) {
|
|
76
|
+
ALS.enterWith(scope);
|
|
77
|
+
} else {
|
|
78
|
+
currentScope = scope;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function runInScope(scope, fn) {
|
|
82
|
+
if (ALS) {
|
|
83
|
+
return catchError(() => ALS.run(scope, fn));
|
|
84
|
+
}
|
|
85
|
+
const prevScope = getCurrentScope();
|
|
86
|
+
const onComplete = ([err, result2]) => {
|
|
87
|
+
if (prevScope) {
|
|
88
|
+
setCurrentScope(prevScope);
|
|
89
|
+
} else {
|
|
90
|
+
unsetCurrentScope();
|
|
91
|
+
}
|
|
92
|
+
return [err, result2];
|
|
93
|
+
};
|
|
94
|
+
const result = catchError(fn);
|
|
95
|
+
if (isPromise(result)) {
|
|
96
|
+
return result.then(onComplete);
|
|
97
|
+
}
|
|
98
|
+
return onComplete(result);
|
|
99
|
+
}
|
|
100
|
+
const unsetCurrentScope = () => {
|
|
101
|
+
if (ALS) {
|
|
102
|
+
ALS.enterWith(null);
|
|
103
|
+
} else {
|
|
104
|
+
currentScope = null;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
function provide(key, value, enterWith) {
|
|
109
|
+
let currentScope = getCurrentScope();
|
|
110
|
+
if (!currentScope) {
|
|
111
|
+
if (enterWith) {
|
|
112
|
+
currentScope = new Scope();
|
|
113
|
+
setCurrentScope(currentScope);
|
|
114
|
+
} else {
|
|
115
|
+
console.warn(
|
|
116
|
+
`provide() is called when there is no active scope to be associated with.
|
|
117
|
+
` + captureStackTrace(provide)
|
|
118
|
+
);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
currentScope.providers.set(key, value);
|
|
123
|
+
}
|
|
124
|
+
function inject(key, defaultValue) {
|
|
125
|
+
let currentScope = getCurrentScope();
|
|
126
|
+
if (!currentScope) {
|
|
127
|
+
console.warn(
|
|
128
|
+
`inject() is called when there is no active scope to be associated with.
|
|
129
|
+
` + captureStackTrace(inject)
|
|
130
|
+
);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const handled = /* @__PURE__ */ new WeakSet();
|
|
134
|
+
let value;
|
|
135
|
+
do {
|
|
136
|
+
value = currentScope.providers.get(key);
|
|
137
|
+
handled.add(currentScope);
|
|
138
|
+
currentScope = currentScope.parent;
|
|
139
|
+
} while (currentScope && value === void 0 && !handled.has(currentScope));
|
|
140
|
+
if (value === void 0 && defaultValue !== void 0) {
|
|
141
|
+
value = isFunction(defaultValue) ? defaultValue() : defaultValue;
|
|
142
|
+
}
|
|
143
|
+
return value;
|
|
144
|
+
}
|
|
145
|
+
function hasInjectionContext() {
|
|
146
|
+
return !!getCurrentScope();
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function createContext(providerName, contextName) {
|
|
150
|
+
const symbolDescription = typeof providerName === "string" && !contextName ? `${providerName}Context` : contextName;
|
|
151
|
+
const injectionKey = Symbol(symbolDescription);
|
|
152
|
+
const injectContext = (fallback) => {
|
|
153
|
+
const context = inject(injectionKey, fallback);
|
|
154
|
+
if (context) return context;
|
|
155
|
+
if (context === null) return context;
|
|
156
|
+
throw new Error(
|
|
157
|
+
`Injection \`${injectionKey.toString()}\` not found. Must be used within ${Array.isArray(providerName) ? `one of the following providers: ${providerName.join(", ")}` : `\`${providerName}\``}`
|
|
158
|
+
);
|
|
159
|
+
};
|
|
160
|
+
const provideContext = (contextValue) => {
|
|
161
|
+
provide(injectionKey, contextValue);
|
|
162
|
+
return contextValue;
|
|
163
|
+
};
|
|
164
|
+
return [injectContext, provideContext];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function onScopeDispose(fn) {
|
|
168
|
+
const activeScope = getCurrentScope();
|
|
169
|
+
assert.ok(
|
|
170
|
+
activeScope,
|
|
171
|
+
"onScopeDispose() is called when there is no active scope to be associated with." + captureStackTrace(onScopeDispose)
|
|
172
|
+
);
|
|
173
|
+
activeScope.cleanups.push(fn);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function withContext(fn, detached = false) {
|
|
177
|
+
return function(...args) {
|
|
178
|
+
const scope = createScope(detached);
|
|
179
|
+
return scope.run(fn.bind(this, args));
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function runWithContext(fn, isolated = false) {
|
|
183
|
+
return withContext(fn, isolated)();
|
|
184
|
+
}
|
|
185
|
+
function bindContext(fn) {
|
|
186
|
+
const activeScope = getCurrentScope();
|
|
187
|
+
assert.ok(
|
|
188
|
+
activeScope,
|
|
189
|
+
"bindContext() is called when there is no active scope to be associated with."
|
|
190
|
+
);
|
|
191
|
+
return () => activeScope.run(fn);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export { bindContext, createContext, getCurrentScope, hasInjectionContext, inject, onScopeDispose, provide, runWithContext, withContext };
|
|
195
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/scope.ts","../src/hooks/provide.ts","../src/hooks/createContext.ts","../src/hooks/onScopeDispose.ts","../src/index.ts"],"sourcesContent":["import { type Awaitable, catchError, isPromise } from '@andrew_l/toolkit';\nimport type { AsyncLocalStorage } from 'node:async_hooks';\n\nlet idSec = 0;\nlet ALS: AsyncLocalStorage<Scope | null> | undefined;\nlet currentScope: Scope | null = null;\n\ncatchError(async () => {\n ALS = new (\n await import('node:async_hooks')\n ).AsyncLocalStorage<Scope | null>();\n});\n\nexport class Scope {\n /**\n * @internal\n */\n id: number;\n\n /**\n * @internal\n */\n providers = new Map<any, any>();\n\n /**\n * @internal\n */\n parent: Scope | null = null;\n\n /**\n * @internal\n */\n cleanups: (() => void)[] = [];\n\n /**\n * @internal\n */\n private _activeRuns: number = 0;\n\n constructor(public detached = false) {\n this.id = ++idSec;\n\n if (!detached) {\n this.parent = getCurrentScope();\n }\n }\n\n run<T>(fn: () => T): T {\n this._activeRuns++;\n\n const onComplete = ([err, result]: [Error | undefined, any]): T => {\n this._activeRuns--;\n\n if (this._activeRuns === 0) {\n this.stop();\n }\n\n if (err) {\n throw err;\n }\n\n return result;\n };\n\n const r = runInScope(this, fn);\n\n if (isPromise<any>(r)) {\n return r.then(onComplete) as T;\n }\n\n return onComplete(r);\n }\n\n stop() {\n for (let i = 0, l = this.cleanups.length; i < l; i++) {\n this.cleanups[i]();\n }\n\n this.cleanups.length = 0;\n }\n\n get active(): boolean {\n return this._activeRuns > 0;\n }\n}\n\n/**\n * @param detached - Can be used to create a \"detached\" scope.\n */\nexport function createScope(detached?: boolean): Scope {\n return new Scope(detached);\n}\n\n/**\n * @group Main\n */\nexport function getCurrentScope(): Scope | null {\n if (ALS) {\n return ALS.getStore() ?? null;\n }\n\n return currentScope;\n}\n\nexport function setCurrentScope(scope: Scope) {\n if (ALS) {\n ALS.enterWith(scope);\n } else {\n currentScope = scope;\n }\n}\n\nfunction runInScope<T>(\n scope: Scope,\n fn: () => T,\n): Awaitable<[Error | undefined, any]> {\n if (ALS) {\n return catchError(() => ALS!.run(scope, fn));\n }\n\n const prevScope = getCurrentScope();\n\n const onComplete = ([err, result]: [Error | undefined, any]): [\n Error | undefined,\n any,\n ] => {\n if (prevScope) {\n setCurrentScope(prevScope);\n } else {\n unsetCurrentScope();\n }\n\n return [err, result];\n };\n\n const result = catchError(fn);\n\n if (isPromise<any>(result)) {\n return result.then(onComplete);\n }\n\n return onComplete(result);\n}\n\nconst unsetCurrentScope = (): void => {\n if (ALS) {\n ALS.enterWith(null);\n } else {\n currentScope = null;\n }\n};\n","import { captureStackTrace, isFunction } from '@andrew_l/toolkit';\nimport { Scope, getCurrentScope, setCurrentScope } from '../scope';\n\nexport type ProvideKey = symbol | string | number | object;\nexport type ProvideValue<T = unknown> = T | undefined;\nexport type InjectionKey = symbol | string | number | object;\n\n/**\n * To provide data to a descendants\n * @param enterWith Enter into injection context (Experimental)\n * @group Main\n */\nexport function provide(key: ProvideKey, value: any, enterWith?: boolean) {\n let currentScope = getCurrentScope();\n\n if (!currentScope) {\n if (enterWith) {\n currentScope = new Scope();\n setCurrentScope(currentScope);\n } else {\n console.warn(\n `provide() is called when there is no active scope to be associated with.\\n` +\n captureStackTrace(provide),\n );\n return;\n }\n }\n\n currentScope.providers.set(key, value);\n}\n\n/**\n * Inject previously provided data\n * @group Main\n */\nexport function inject<T = any>(\n key: ProvideKey,\n defaultValue?: T | (() => T),\n): ProvideValue<T> {\n let currentScope = getCurrentScope();\n\n if (!currentScope) {\n console.warn(\n `inject() is called when there is no active scope to be associated with.\\n` +\n captureStackTrace(inject),\n );\n return;\n }\n\n const handled = new WeakSet();\n\n let value;\n\n do {\n value = currentScope!.providers.get(key);\n handled.add(currentScope!);\n currentScope = currentScope!.parent;\n } while (currentScope && value === undefined && !handled.has(currentScope));\n\n if (value === undefined && defaultValue !== undefined) {\n value = isFunction(defaultValue) ? defaultValue() : defaultValue;\n }\n\n return value;\n}\n\n/**\n * Returns true if `inject()` can be used without warning about being called in the wrong place.\n * @group Main\n */\nexport function hasInjectionContext() {\n return !!getCurrentScope();\n}\n","import { type InjectionKey, inject, provide } from './provide';\n\n/**\n * Wrapper around `provide/inject` function to simple usage.\n *\n * @param providerName - The name(s) of the providing the context.\n *\n * There are situations where context can come from multiple scopes. In such cases, you might need to give an array of names to provide your context, instead of just a single string.\n *\n * @param contextName The description for injection key symbol.\n *\n * @example\n * const [injectTraceId, provideTraceId] = createContext<string>('withContext');\n *\n * // this function will returns the same trace if for execution context\n * export const useTraceId = () => {\n * let traceId = injectTraceId(null);\n *\n * if (!traceId) {\n * traceId = uuidv4();\n * provideTraceId(traceId);\n * }\n *\n * return traceId;\n * };\n *\n * @group Main\n */\nexport function createContext<ContextValue>(\n providerName: string | string[],\n contextName?: string,\n) {\n const symbolDescription =\n typeof providerName === 'string' && !contextName\n ? `${providerName}Context`\n : contextName;\n\n const injectionKey: InjectionKey = Symbol(symbolDescription);\n\n /**\n * @param fallback The context value to return if the injection fails.\n *\n * @throws When context injection failed and no fallback is specified.\n * This happens when the scope injecting the context is not a child of the root scope providing the context.\n */\n const injectContext = <\n T extends ContextValue | null | undefined = ContextValue,\n >(\n fallback?: T | (() => T),\n ): T extends null ? ContextValue | null : ContextValue => {\n const context = inject(injectionKey, fallback);\n if (context) return context;\n\n if (context === null) return context as any;\n\n throw new Error(\n `Injection \\`${injectionKey.toString()}\\` not found. Must be used within ${\n Array.isArray(providerName)\n ? `one of the following providers: ${providerName.join(', ')}`\n : `\\`${providerName}\\``\n }`,\n );\n };\n\n const provideContext = (contextValue: ContextValue) => {\n provide(injectionKey, contextValue);\n return contextValue;\n };\n\n return [injectContext, provideContext] as const;\n}\n","import { assert, captureStackTrace } from '@andrew_l/toolkit';\nimport { getCurrentScope } from '../scope';\n\n/**\n * The callback will be invoked when the associated context completes.\n *\n * @example\n * const fn = withContext(() => {\n * onScopeDispose(() => {\n * console.log(2);\n * });\n *\n * console.log(1);\n * });\n *\n * fn();\n *\n * console.log(3);\n *\n * // 1\n * // 2\n * // 3\n *\n * @group Main\n */\nexport function onScopeDispose(fn: () => void) {\n const activeScope = getCurrentScope();\n\n assert.ok(\n activeScope,\n 'onScopeDispose() is called when there is no active scope to be associated with.' +\n captureStackTrace(onScopeDispose),\n );\n\n activeScope.cleanups.push(fn);\n}\n","import { type AnyFunction, assert } from '@andrew_l/toolkit';\nimport { createScope, getCurrentScope } from './scope';\n\nexport * from './hooks/createContext';\nexport * from './hooks/onScopeDispose';\nexport * from './hooks/provide';\nexport { getCurrentScope } from './scope';\n\n/**\n * Creates a function within the injection context and returns its result. Providers/injections are only accessible within the callback function.\n * @param isolated Do not inject parent providers into this context (Default: `false`)\n *\n * @example\n * const main = withContext(() => {\n * provide('user', { id: 1, name: 'Andrew' });\n * doCoolStaff();\n * });\n *\n * const doCoolStaff = () => {\n * const user = inject('user');\n * console.log(user); // { id: 1, name: 'Andrew' }\n * };\n *\n * main();\n *\n * @group Main\n */\nexport function withContext<T extends AnyFunction>(fn: T, detached = false): T {\n return function (this: any, ...args: any[]) {\n const scope = createScope(detached);\n return scope.run(fn.bind(this, args));\n } as T;\n}\n\n/**\n * Runs a function within the injection context and returns its result. Providers/injections are only accessible inside the callback function.\n * @param isolated Do not inject parent providers into this context (Default: `false`)\n * @group Main\n */\nexport function runWithContext<T = any>(fn: () => T, isolated = false): T {\n return withContext(fn, isolated)();\n}\n\n/**\n * Binds the current context to the provided function. Useful for creating callbacks with the current context, such as `setTimeout` or `EventEmitter` handlers.\n * @example\n * const main = withContext(() => {\n * provide(\"user\", { id: 1, name: \"Andrew\" });\n *\n * setInterval(bindContext(() => {\n * const user = inject(\"user\");\n * console.log(user); // { id: 1, name: 'Andrew' }\n * }));\n * });\n *\n * main();\n *\n * @group Main\n */\nexport function bindContext<T>(fn: () => T): () => T {\n const activeScope = getCurrentScope();\n\n assert.ok(\n activeScope,\n 'bindContext() is called when there is no active scope to be associated with.',\n );\n\n return () => activeScope.run(fn);\n}\n"],"names":["result"],"mappings":";;AAGA,IAAI,KAAQ,GAAA,CAAA,CAAA;AACZ,IAAI,GAAA,CAAA;AACJ,IAAI,YAA6B,GAAA,IAAA,CAAA;AAEjC,UAAA,CAAW,YAAY;AACrB,EAAA,GAAA,GAAM,IACJ,CAAA,MAAM,OAAO,kBAAkB,GAC/B,iBAAgC,EAAA,CAAA;AACpC,CAAC,CAAA,CAAA;AAEM,MAAM,KAAM,CAAA;AAAA,EA0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AAI,EAAE,CAAA,CAAA;AACjC;;;;"}
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@andrew_l/context",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/men232/toolkit.git",
|
|
9
|
+
"directory": "packages/context"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": "./dist/index.mjs",
|
|
14
|
+
"require": "./dist/index.cjs"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"main": "./dist/index.cjs",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"files": [
|
|
20
|
+
"dist"
|
|
21
|
+
],
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"unbuild": "3.0.0-rc.11",
|
|
24
|
+
"@types/node": "^20.16.10",
|
|
25
|
+
"typescript": "~5.6.2",
|
|
26
|
+
"vitest": "^2.1.3"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@andrew_l/toolkit": "0.0.1"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "unbuild",
|
|
33
|
+
"test": "vitest run --typecheck",
|
|
34
|
+
"test:watch": "vitest watch --typecheck"
|
|
35
|
+
}
|
|
36
|
+
}
|