context 4.0.0 → 4.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/README.md +46 -181
- package/dist/context.cjs +64 -0
- package/dist/context.cjs.map +1 -0
- package/dist/context.mjs +63 -0
- package/dist/context.mjs.map +1 -0
- package/package.json +24 -32
- package/src/__tests__/__snapshots__/cascade.test.ts.snap +23 -0
- package/src/__tests__/cascade.test.ts +342 -0
- package/src/__tests__/context.test.ts +104 -0
- package/src/context.ts +100 -0
- package/types/context.d.cts +27 -0
- package/types/context.d.cts.map +1 -0
- package/types/context.d.mts +27 -0
- package/types/context.d.mts.map +1 -0
- package/types/context.d.ts +14 -10
- package/vitest.config.ts +21 -0
- package/dist/cjs/context.development.js +0 -69
- package/dist/cjs/context.js +0 -7
- package/dist/cjs/context.production.js +0 -1
- package/dist/cjs/package.json +0 -1
- package/dist/es/context.development.js +0 -64
- package/dist/es/context.production.js +0 -1
- package/dist/es/package.json +0 -1
- package/dist/umd/context.development.js +0 -73
- package/dist/umd/context.production.js +0 -1
- package/tsconfig.json +0 -13
- package/types/context.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -1,214 +1,79 @@
|
|
|
1
1
|
# Context 🪆
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Lightweight context propagation for JavaScript and TypeScript. Create a scoped storage object, run code inside it, and read the active value anywhere down the call stack - without depending on React.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
- `createContext(defaultValue?)` – simplest option with a single value per run.
|
|
6
|
+
- `createCascade(initializer?)` – merges parent and child context objects, ideal for layered data.
|
|
7
|
+
- `bind` – capture context for later execution (useful with async callbacks).
|
|
7
8
|
|
|
8
|
-
##
|
|
9
|
+
## Installation
|
|
9
10
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
The reason the context is cleared after its run is so that items can't override one another. Assume you have two running the same async function twice, and it writes to the context, expecting to read the value somewhere down the line. Now you have two competing consumers of this single resource, and one eventually get the wrong value since they both read from and write to the same place.
|
|
13
|
-
|
|
14
|
-
## API Reference
|
|
15
|
-
|
|
16
|
-
### Top Level Exports
|
|
17
|
-
|
|
18
|
-
The context package exports these two functions:
|
|
19
|
-
|
|
20
|
-
- `createContext`: Creates a new context.
|
|
21
|
-
- `createCascade`: Creates a new cascading context.
|
|
22
|
-
|
|
23
|
-
## createContext()
|
|
24
|
-
|
|
25
|
-
Create context is the minimal implementation of context. It allows propagation of values down in your function call.
|
|
26
|
-
|
|
27
|
-
createContext takes a single argument - defaultContextValue. This value is used when not withing a running context.
|
|
28
|
-
|
|
29
|
-
### Arguments
|
|
30
|
-
|
|
31
|
-
| Argument | Type | Optional? | Description |
|
|
32
|
-
| ------------------- | ----- | --------- | ------------------------------------------------------------ |
|
|
33
|
-
| defaultContextValue | `any` | Yes | The default value to use when not withing a running context. |
|
|
34
|
-
|
|
35
|
-
### Returned object
|
|
36
|
-
|
|
37
|
-
`createContext` returns an object containing the following functions:
|
|
38
|
-
|
|
39
|
-
- `use`: Returns the current context value, or the default value when not withing a running context.
|
|
40
|
-
- `useX`: Returns the current context, throws an error if not within a running context or the context is undefined. `useX` will throw even if a default value is provided.
|
|
41
|
-
- `run`: Runs the context, passing the given value into the context.
|
|
42
|
-
|
|
43
|
-
**Note About Typescript Usage**
|
|
44
|
-
For convenience, `use` assumes we're alwyas inside a context. If you want to have runtime safety, you can use `useX` instead to make sure you're excplicitly using a defined context.
|
|
45
|
-
|
|
46
|
-
### Usage Example
|
|
47
|
-
|
|
48
|
-
```js
|
|
49
|
-
const context = createContext(0); // Create a context with a default value of 0.
|
|
50
|
-
|
|
51
|
-
function myFunc() {
|
|
52
|
-
context.run(100, someOtherFunc); // Run the context with a value of 100.
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function someOtherFunc() {
|
|
56
|
-
const number = context.use(); // Returns the value of the context.
|
|
57
|
-
}
|
|
11
|
+
```bash
|
|
12
|
+
npm i context
|
|
58
13
|
```
|
|
59
14
|
|
|
60
|
-
##
|
|
61
|
-
|
|
62
|
-
`createCascade` is a more advanced version of `createContext` that allows you to create cascading contexts. It assumes the value is always an object, and when nesting context layers, it merges their values together.
|
|
63
|
-
|
|
64
|
-
`createCascade` does not take a default value, but an initializer function instead. This initializer is called on each `run` call, and it allows you to modify or augment the context value being passed down. The init function is passed the context object run was called with, and the parent context if it was called within a previously created context. The init function needs to return the desired context object.
|
|
65
|
-
|
|
66
|
-
### Arguments
|
|
15
|
+
## createContext
|
|
67
16
|
|
|
68
|
-
|
|
69
|
-
| ----------- | ---------- | --------- | ------------------------------------------------------------ |
|
|
70
|
-
| initializer | `Function` | Yes | The initializer function to use when creating a new context. |
|
|
71
|
-
|
|
72
|
-
The initializer function can either return the the next context object. If null is returned itself, the initializer will take no effect.
|
|
73
|
-
The initializer receives the context object, and the parent context object, if present.
|
|
74
|
-
|
|
75
|
-
### Returned object
|
|
76
|
-
|
|
77
|
-
`createCascade` returns an object containing the following functions:
|
|
78
|
-
|
|
79
|
-
- `use`: Returns the current context value.
|
|
80
|
-
- `useX`: Returns the current context, throws an error if not within a running context.
|
|
81
|
-
- `run`: Runs the context, passing the given value into the context. Merges the given value with the parent context if it exists, while not overriding the parent context.
|
|
82
|
-
- `bind`: Binds a given function to the context. Allows for delayd execution of a function as if it was called within the context.
|
|
83
|
-
|
|
84
|
-
### Usage Examples
|
|
85
|
-
|
|
86
|
-
#### Initializer Function
|
|
17
|
+
Create an isolated context with an optional default value used outside of a running scope.
|
|
87
18
|
|
|
88
19
|
```js
|
|
89
|
-
|
|
90
|
-
if (parentContext === null) {
|
|
91
|
-
// we're at the top level
|
|
92
|
-
// so let's add a default cart object
|
|
93
|
-
return Object.assign(ctx, {
|
|
94
|
-
cart: [],
|
|
95
|
-
});
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// we're in a sub context, so we already have those default values.
|
|
99
|
-
return ctx;
|
|
100
|
-
});
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
#### run()
|
|
20
|
+
import { createContext } from 'context';
|
|
104
21
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
```js
|
|
108
|
-
// myFunction.js
|
|
109
|
-
import ctx from './ctx';
|
|
110
|
-
import sayUsername from './sayUsername';
|
|
22
|
+
const requestContext = createContext({ requestId: undefined });
|
|
111
23
|
|
|
112
|
-
function
|
|
113
|
-
return
|
|
24
|
+
function handleRequest(requestId) {
|
|
25
|
+
return requestContext.run({ requestId }, () => {
|
|
26
|
+
logRequest();
|
|
27
|
+
return doWork();
|
|
28
|
+
});
|
|
114
29
|
}
|
|
115
|
-
```
|
|
116
|
-
|
|
117
|
-
If `run` is called within a different `run` call, the context values will be merged when the callback is run. When we exit our callback, the context will be reset to the values it had before the call.
|
|
118
|
-
|
|
119
|
-
### use() and useX()
|
|
120
30
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
- useX() returns the current object stored within the context, or throws an error if we're not within a `run` call.
|
|
125
|
-
- useX also takes an optional argument that will be used as the error message if the context is not found.
|
|
126
|
-
|
|
127
|
-
```js
|
|
128
|
-
// sayUsername.js
|
|
129
|
-
import ctx from './ctx';
|
|
130
|
-
|
|
131
|
-
function sayUsername() {
|
|
132
|
-
const context = ctx.use(); // { username: 'John Doe' }
|
|
133
|
-
|
|
134
|
-
if (!context) {
|
|
135
|
-
// we're not within a `run` call. This function was called outside of a running context.
|
|
136
|
-
return "Hey, I don't know you, and this is crazy!";
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
return `Hello, ${context.username}!`;
|
|
31
|
+
function logRequest() {
|
|
32
|
+
// Inside run → current context value
|
|
33
|
+
console.log(requestContext.use().requestId);
|
|
140
34
|
}
|
|
141
35
|
```
|
|
142
36
|
|
|
143
|
-
|
|
144
|
-
// handleCart.js
|
|
145
|
-
import ctx from './ctx';
|
|
37
|
+
**API:**
|
|
146
38
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
); // { cart: { items: [ 'foo', 'bar' ] } }
|
|
151
|
-
// This throws an error if we're not within a `run` call.
|
|
152
|
-
// You should catch this error and handle it somewhere above this function.
|
|
39
|
+
- `run(value, callback)` – activates the context for the callback. Nested runs temporarily override the value and restore it afterwards.
|
|
40
|
+
- `use()` – returns the current value or the default when no context is active.
|
|
41
|
+
- `useX(message?)` – like `use`, but throws if called outside of `run`, ignoring any default value.
|
|
153
42
|
|
|
154
|
-
|
|
155
|
-
}
|
|
156
|
-
```
|
|
157
|
-
|
|
158
|
-
### bind()
|
|
43
|
+
## createCascade
|
|
159
44
|
|
|
160
|
-
|
|
45
|
+
`createCascade` composes context objects instead of replacing them. Each `run` merges the current value with the parent context, so shared properties flow down while children can add or override keys.
|
|
161
46
|
|
|
162
47
|
```js
|
|
163
|
-
|
|
164
|
-
import ctx from './ctx';
|
|
48
|
+
import { createCascade } from 'context';
|
|
165
49
|
|
|
166
|
-
|
|
167
|
-
return ctx.bind({ productId }, handleProductData);
|
|
50
|
+
const userContext = createCascade();
|
|
168
51
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
52
|
+
userContext.run({ user: { id: 5, name: 'Ada' } }, () => {
|
|
53
|
+
// child run inherits id/name and adds role
|
|
54
|
+
userContext.run({ user: { role: 'admin' } }, () => {
|
|
55
|
+
const ctx = userContext.use();
|
|
56
|
+
// ctx.user => { id: 5, name: 'Ada', role: 'admin' }
|
|
172
57
|
});
|
|
173
|
-
}
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
## Typescript Support
|
|
177
|
-
|
|
178
|
-
both `createContext` and `createCascade` have full typescript support. To gain the full benefits of typescript within your context, it is best to annotate your context with its types:
|
|
179
|
-
|
|
180
|
-
```ts
|
|
181
|
-
const someContext = createContext<number>(0);
|
|
182
|
-
|
|
183
|
-
const someCascadeContext = createCascade<{
|
|
184
|
-
username: string;
|
|
185
|
-
firstName: string;
|
|
186
|
-
middleName?: string;
|
|
187
|
-
lastName: string;
|
|
188
|
-
age: number;
|
|
189
|
-
}>();
|
|
58
|
+
});
|
|
190
59
|
```
|
|
191
60
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
## Troubleshooting
|
|
195
|
-
|
|
196
|
-
### Working with async functions/promises
|
|
197
|
-
|
|
198
|
-
Working with context inside within async code may lead to unexpected results when we don't fully consider what's happening. Trying to call your context from the async part of your code will probably return `null` instead of your values.
|
|
61
|
+
**API additions:**
|
|
199
62
|
|
|
200
|
-
|
|
63
|
+
- `use()` / `useX(message?)` – return the merged object for the current layer.
|
|
64
|
+
- `run(value, callback)` – merges `value` into the parent context without passing arguments to `callback`.
|
|
65
|
+
- `bind(value, callback)` – returns a function that executes `callback` inside a context seeded with `value`, preserving arguments when invoked later.
|
|
201
66
|
|
|
202
|
-
|
|
67
|
+
## TypeScript
|
|
203
68
|
|
|
204
|
-
|
|
69
|
+
Both factories are fully typed. Annotate your contexts for stricter checks:
|
|
205
70
|
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
71
|
+
```ts
|
|
72
|
+
const settings = createContext<{ locale: string }>();
|
|
73
|
+
const session = createCascade<{ user?: { id: string } }>();
|
|
74
|
+
```
|
|
209
75
|
|
|
210
|
-
|
|
211
|
-
This is the most obvious and easiest to achieve, though not always what you need. The basic idea is that you take whatever you need from the context when it is still available to you.
|
|
76
|
+
## Notes
|
|
212
77
|
|
|
213
|
-
|
|
214
|
-
|
|
78
|
+
- Context is synchronous by design; reading it after an async boundary requires `bind` or wrapping the async call inside `run`.
|
|
79
|
+
- Each `run` call leaves the parent context untouched once the callback completes.
|
package/dist/context.cjs
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
let vest_utils = require("vest-utils");
|
|
2
|
+
|
|
3
|
+
//#region src/context.ts
|
|
4
|
+
const USEX_DEFAULT_ERROR_MESSAGE = "Not inside of a running context.";
|
|
5
|
+
const EMPTY_CONTEXT = Symbol();
|
|
6
|
+
/**
|
|
7
|
+
* Base context interface.
|
|
8
|
+
*/
|
|
9
|
+
function createContext(defaultContextValue) {
|
|
10
|
+
let contextValue = EMPTY_CONTEXT;
|
|
11
|
+
return {
|
|
12
|
+
run,
|
|
13
|
+
use,
|
|
14
|
+
useX
|
|
15
|
+
};
|
|
16
|
+
function use() {
|
|
17
|
+
return isInsideContext() ? contextValue : defaultContextValue;
|
|
18
|
+
}
|
|
19
|
+
function useX(errorMessage) {
|
|
20
|
+
(0, vest_utils.invariant)(isInsideContext(), (0, vest_utils.defaultTo)(errorMessage, USEX_DEFAULT_ERROR_MESSAGE));
|
|
21
|
+
return contextValue;
|
|
22
|
+
}
|
|
23
|
+
function run(value, cb) {
|
|
24
|
+
const parentContext = isInsideContext() ? use() : EMPTY_CONTEXT;
|
|
25
|
+
contextValue = value;
|
|
26
|
+
const res = cb();
|
|
27
|
+
contextValue = parentContext;
|
|
28
|
+
return res;
|
|
29
|
+
}
|
|
30
|
+
function isInsideContext() {
|
|
31
|
+
return contextValue !== EMPTY_CONTEXT;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Cascading context - another implementation of context, that assumes the context value is an object.
|
|
36
|
+
* When nesting context runs, the the values of the current layer merges with the layers above it.
|
|
37
|
+
*/
|
|
38
|
+
function createCascade(init) {
|
|
39
|
+
const ctx = createContext();
|
|
40
|
+
return {
|
|
41
|
+
bind,
|
|
42
|
+
run,
|
|
43
|
+
use: ctx.use,
|
|
44
|
+
useX: ctx.useX
|
|
45
|
+
};
|
|
46
|
+
function run(value, fn) {
|
|
47
|
+
const parentContext = ctx.use();
|
|
48
|
+
const initResult = (0, vest_utils.dynamicValue)(init, value, parentContext) ?? value;
|
|
49
|
+
const out = (0, vest_utils.assign)({}, parentContext ? parentContext : {}, initResult);
|
|
50
|
+
return ctx.run(Object.freeze(out), fn);
|
|
51
|
+
}
|
|
52
|
+
function bind(value, fn) {
|
|
53
|
+
return function(...runTimeArgs) {
|
|
54
|
+
return run(value, function() {
|
|
55
|
+
return fn(...runTimeArgs);
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
//#endregion
|
|
62
|
+
exports.createCascade = createCascade;
|
|
63
|
+
exports.createContext = createContext;
|
|
64
|
+
//# sourceMappingURL=context.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.cjs","names":["contextValue: T | symbol"],"sources":["../src/context.ts"],"sourcesContent":["import type { CB, Maybe } from 'vest-utils';\nimport {\n assign,\n defaultTo,\n invariant,\n dynamicValue,\n Nullable,\n} from 'vest-utils';\n\nconst USEX_DEFAULT_ERROR_MESSAGE = 'Not inside of a running context.';\nconst EMPTY_CONTEXT = Symbol();\n\n/**\n * Base context interface.\n */\nexport function createContext<T>(defaultContextValue?: T): CtxApi<T> {\n let contextValue: T | symbol = EMPTY_CONTEXT;\n\n return {\n run,\n use,\n useX,\n };\n\n function use(): T {\n return (isInsideContext() ? contextValue : defaultContextValue) as T;\n }\n\n function useX(errorMessage?: string): T {\n invariant(\n isInsideContext(),\n defaultTo(errorMessage, USEX_DEFAULT_ERROR_MESSAGE),\n );\n return contextValue as T;\n }\n\n function run<R>(value: T, cb: () => R): R {\n const parentContext = isInsideContext() ? use() : EMPTY_CONTEXT;\n\n contextValue = value;\n\n const res = cb();\n\n contextValue = parentContext;\n return res;\n }\n\n function isInsideContext(): boolean {\n return contextValue !== EMPTY_CONTEXT;\n }\n}\n\n/**\n * Cascading context - another implementation of context, that assumes the context value is an object.\n * When nesting context runs, the the values of the current layer merges with the layers above it.\n */\nexport function createCascade<T extends Record<string, unknown>>(\n init?: (value: Partial<T>, parentContext: Maybe<T>) => Nullable<T>,\n): CtxCascadeApi<T> {\n const ctx = createContext<T>();\n\n return {\n bind,\n run,\n use: ctx.use,\n useX: ctx.useX,\n };\n\n function run<R>(value: Partial<T>, fn: () => R): R {\n const parentContext = ctx.use();\n\n const initResult = dynamicValue(init, value, parentContext) ?? value;\n\n const out = assign({}, parentContext ? parentContext : {}, initResult) as T;\n\n return ctx.run(Object.freeze(out), fn) as R;\n }\n\n function bind<Fn extends CB>(value: Partial<T>, fn: Fn) {\n return function (...runTimeArgs: Parameters<Fn>) {\n return run<ReturnType<Fn>>(value, function () {\n return fn(...runTimeArgs);\n });\n } as Fn;\n }\n}\n\ntype ContextConsumptionApi<T> = {\n use: () => T;\n useX: (errorMessage?: string) => T;\n};\n\nexport type CtxApi<T> = ContextConsumptionApi<T> & {\n run: <R>(value: T, cb: () => R) => R;\n};\n\nexport type CtxCascadeApi<T> = ContextConsumptionApi<T> & {\n run: <R>(value: Partial<T>, fn: () => R) => R;\n bind: <Fn extends CB>(value: Partial<T>, fn: Fn) => Fn;\n};\n"],"mappings":";;;AASA,MAAM,6BAA6B;AACnC,MAAM,gBAAgB,QAAQ;;;;AAK9B,SAAgB,cAAiB,qBAAoC;CACnE,IAAIA,eAA2B;AAE/B,QAAO;EACL;EACA;EACA;EACD;CAED,SAAS,MAAS;AAChB,SAAQ,iBAAiB,GAAG,eAAe;;CAG7C,SAAS,KAAK,cAA0B;AACtC,4BACE,iBAAiB,4BACP,cAAc,2BAA2B,CACpD;AACD,SAAO;;CAGT,SAAS,IAAO,OAAU,IAAgB;EACxC,MAAM,gBAAgB,iBAAiB,GAAG,KAAK,GAAG;AAElD,iBAAe;EAEf,MAAM,MAAM,IAAI;AAEhB,iBAAe;AACf,SAAO;;CAGT,SAAS,kBAA2B;AAClC,SAAO,iBAAiB;;;;;;;AAQ5B,SAAgB,cACd,MACkB;CAClB,MAAM,MAAM,eAAkB;AAE9B,QAAO;EACL;EACA;EACA,KAAK,IAAI;EACT,MAAM,IAAI;EACX;CAED,SAAS,IAAO,OAAmB,IAAgB;EACjD,MAAM,gBAAgB,IAAI,KAAK;EAE/B,MAAM,0CAA0B,MAAM,OAAO,cAAc,IAAI;EAE/D,MAAM,6BAAa,EAAE,EAAE,gBAAgB,gBAAgB,EAAE,EAAE,WAAW;AAEtE,SAAO,IAAI,IAAI,OAAO,OAAO,IAAI,EAAE,GAAG;;CAGxC,SAAS,KAAoB,OAAmB,IAAQ;AACtD,SAAO,SAAU,GAAG,aAA6B;AAC/C,UAAO,IAAoB,OAAO,WAAY;AAC5C,WAAO,GAAG,GAAG,YAAY;KACzB"}
|
package/dist/context.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { assign, defaultTo, dynamicValue, invariant } from "vest-utils";
|
|
2
|
+
|
|
3
|
+
//#region src/context.ts
|
|
4
|
+
const USEX_DEFAULT_ERROR_MESSAGE = "Not inside of a running context.";
|
|
5
|
+
const EMPTY_CONTEXT = Symbol();
|
|
6
|
+
/**
|
|
7
|
+
* Base context interface.
|
|
8
|
+
*/
|
|
9
|
+
function createContext(defaultContextValue) {
|
|
10
|
+
let contextValue = EMPTY_CONTEXT;
|
|
11
|
+
return {
|
|
12
|
+
run,
|
|
13
|
+
use,
|
|
14
|
+
useX
|
|
15
|
+
};
|
|
16
|
+
function use() {
|
|
17
|
+
return isInsideContext() ? contextValue : defaultContextValue;
|
|
18
|
+
}
|
|
19
|
+
function useX(errorMessage) {
|
|
20
|
+
invariant(isInsideContext(), defaultTo(errorMessage, USEX_DEFAULT_ERROR_MESSAGE));
|
|
21
|
+
return contextValue;
|
|
22
|
+
}
|
|
23
|
+
function run(value, cb) {
|
|
24
|
+
const parentContext = isInsideContext() ? use() : EMPTY_CONTEXT;
|
|
25
|
+
contextValue = value;
|
|
26
|
+
const res = cb();
|
|
27
|
+
contextValue = parentContext;
|
|
28
|
+
return res;
|
|
29
|
+
}
|
|
30
|
+
function isInsideContext() {
|
|
31
|
+
return contextValue !== EMPTY_CONTEXT;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Cascading context - another implementation of context, that assumes the context value is an object.
|
|
36
|
+
* When nesting context runs, the the values of the current layer merges with the layers above it.
|
|
37
|
+
*/
|
|
38
|
+
function createCascade(init) {
|
|
39
|
+
const ctx = createContext();
|
|
40
|
+
return {
|
|
41
|
+
bind,
|
|
42
|
+
run,
|
|
43
|
+
use: ctx.use,
|
|
44
|
+
useX: ctx.useX
|
|
45
|
+
};
|
|
46
|
+
function run(value, fn) {
|
|
47
|
+
const parentContext = ctx.use();
|
|
48
|
+
const initResult = dynamicValue(init, value, parentContext) ?? value;
|
|
49
|
+
const out = assign({}, parentContext ? parentContext : {}, initResult);
|
|
50
|
+
return ctx.run(Object.freeze(out), fn);
|
|
51
|
+
}
|
|
52
|
+
function bind(value, fn) {
|
|
53
|
+
return function(...runTimeArgs) {
|
|
54
|
+
return run(value, function() {
|
|
55
|
+
return fn(...runTimeArgs);
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
//#endregion
|
|
62
|
+
export { createCascade, createContext };
|
|
63
|
+
//# sourceMappingURL=context.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.mjs","names":["contextValue: T | symbol"],"sources":["../src/context.ts"],"sourcesContent":["import type { CB, Maybe } from 'vest-utils';\nimport {\n assign,\n defaultTo,\n invariant,\n dynamicValue,\n Nullable,\n} from 'vest-utils';\n\nconst USEX_DEFAULT_ERROR_MESSAGE = 'Not inside of a running context.';\nconst EMPTY_CONTEXT = Symbol();\n\n/**\n * Base context interface.\n */\nexport function createContext<T>(defaultContextValue?: T): CtxApi<T> {\n let contextValue: T | symbol = EMPTY_CONTEXT;\n\n return {\n run,\n use,\n useX,\n };\n\n function use(): T {\n return (isInsideContext() ? contextValue : defaultContextValue) as T;\n }\n\n function useX(errorMessage?: string): T {\n invariant(\n isInsideContext(),\n defaultTo(errorMessage, USEX_DEFAULT_ERROR_MESSAGE),\n );\n return contextValue as T;\n }\n\n function run<R>(value: T, cb: () => R): R {\n const parentContext = isInsideContext() ? use() : EMPTY_CONTEXT;\n\n contextValue = value;\n\n const res = cb();\n\n contextValue = parentContext;\n return res;\n }\n\n function isInsideContext(): boolean {\n return contextValue !== EMPTY_CONTEXT;\n }\n}\n\n/**\n * Cascading context - another implementation of context, that assumes the context value is an object.\n * When nesting context runs, the the values of the current layer merges with the layers above it.\n */\nexport function createCascade<T extends Record<string, unknown>>(\n init?: (value: Partial<T>, parentContext: Maybe<T>) => Nullable<T>,\n): CtxCascadeApi<T> {\n const ctx = createContext<T>();\n\n return {\n bind,\n run,\n use: ctx.use,\n useX: ctx.useX,\n };\n\n function run<R>(value: Partial<T>, fn: () => R): R {\n const parentContext = ctx.use();\n\n const initResult = dynamicValue(init, value, parentContext) ?? value;\n\n const out = assign({}, parentContext ? parentContext : {}, initResult) as T;\n\n return ctx.run(Object.freeze(out), fn) as R;\n }\n\n function bind<Fn extends CB>(value: Partial<T>, fn: Fn) {\n return function (...runTimeArgs: Parameters<Fn>) {\n return run<ReturnType<Fn>>(value, function () {\n return fn(...runTimeArgs);\n });\n } as Fn;\n }\n}\n\ntype ContextConsumptionApi<T> = {\n use: () => T;\n useX: (errorMessage?: string) => T;\n};\n\nexport type CtxApi<T> = ContextConsumptionApi<T> & {\n run: <R>(value: T, cb: () => R) => R;\n};\n\nexport type CtxCascadeApi<T> = ContextConsumptionApi<T> & {\n run: <R>(value: Partial<T>, fn: () => R) => R;\n bind: <Fn extends CB>(value: Partial<T>, fn: Fn) => Fn;\n};\n"],"mappings":";;;AASA,MAAM,6BAA6B;AACnC,MAAM,gBAAgB,QAAQ;;;;AAK9B,SAAgB,cAAiB,qBAAoC;CACnE,IAAIA,eAA2B;AAE/B,QAAO;EACL;EACA;EACA;EACD;CAED,SAAS,MAAS;AAChB,SAAQ,iBAAiB,GAAG,eAAe;;CAG7C,SAAS,KAAK,cAA0B;AACtC,YACE,iBAAiB,EACjB,UAAU,cAAc,2BAA2B,CACpD;AACD,SAAO;;CAGT,SAAS,IAAO,OAAU,IAAgB;EACxC,MAAM,gBAAgB,iBAAiB,GAAG,KAAK,GAAG;AAElD,iBAAe;EAEf,MAAM,MAAM,IAAI;AAEhB,iBAAe;AACf,SAAO;;CAGT,SAAS,kBAA2B;AAClC,SAAO,iBAAiB;;;;;;;AAQ5B,SAAgB,cACd,MACkB;CAClB,MAAM,MAAM,eAAkB;AAE9B,QAAO;EACL;EACA;EACA,KAAK,IAAI;EACT,MAAM,IAAI;EACX;CAED,SAAS,IAAO,OAAmB,IAAgB;EACjD,MAAM,gBAAgB,IAAI,KAAK;EAE/B,MAAM,aAAa,aAAa,MAAM,OAAO,cAAc,IAAI;EAE/D,MAAM,MAAM,OAAO,EAAE,EAAE,gBAAgB,gBAAgB,EAAE,EAAE,WAAW;AAEtE,SAAO,IAAI,IAAI,OAAO,OAAO,IAAI,EAAE,GAAG;;CAGxC,SAAS,KAAoB,OAAmB,IAAQ;AACtD,SAAO,SAAU,GAAG,aAA6B;AAC/C,UAAO,IAAoB,OAAO,WAAY;AAC5C,WAAO,GAAG,GAAG,YAAY;KACzB"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "4.0.
|
|
2
|
+
"version": "4.0.1",
|
|
3
3
|
"license": "MIT",
|
|
4
|
-
"main": "./dist/
|
|
5
|
-
"types": "./types/context.d.
|
|
4
|
+
"main": "./dist/context.cjs",
|
|
5
|
+
"types": "./types/context.d.cts",
|
|
6
6
|
"name": "context",
|
|
7
7
|
"author": "ealush",
|
|
8
8
|
"scripts": {
|
|
@@ -11,41 +11,33 @@
|
|
|
11
11
|
"release": "vx release"
|
|
12
12
|
},
|
|
13
13
|
"dependencies": {
|
|
14
|
-
"vest-utils": "^
|
|
15
|
-
},
|
|
16
|
-
"module": "./dist/es/context.production.js",
|
|
17
|
-
"exports": {
|
|
18
|
-
".": {
|
|
19
|
-
"development": {
|
|
20
|
-
"types": "./types/context.d.ts",
|
|
21
|
-
"browser": "./dist/es/context.development.js",
|
|
22
|
-
"umd": "./dist/umd/context.development.js",
|
|
23
|
-
"import": "./dist/es/context.development.js",
|
|
24
|
-
"require": "./dist/cjs/context.development.js",
|
|
25
|
-
"node": "./dist/cjs/context.development.js",
|
|
26
|
-
"module": "./dist/es/context.development.js",
|
|
27
|
-
"default": "./dist/cjs/context.development.js"
|
|
28
|
-
},
|
|
29
|
-
"types": "./types/context.d.ts",
|
|
30
|
-
"browser": "./dist/es/context.production.js",
|
|
31
|
-
"umd": "./dist/umd/context.production.js",
|
|
32
|
-
"import": "./dist/es/context.production.js",
|
|
33
|
-
"require": "./dist/cjs/context.production.js",
|
|
34
|
-
"node": "./dist/cjs/context.production.js",
|
|
35
|
-
"module": "./dist/es/context.production.js",
|
|
36
|
-
"default": "./dist/cjs/context.production.js"
|
|
37
|
-
},
|
|
38
|
-
"./package.json": "./package.json",
|
|
39
|
-
"./*": "./*"
|
|
14
|
+
"vest-utils": "^2.0.1"
|
|
40
15
|
},
|
|
16
|
+
"module": "./dist/context.mjs",
|
|
41
17
|
"repository": {
|
|
42
18
|
"type": "git",
|
|
43
|
-
"url": "https://github.com/ealush/vest.git",
|
|
19
|
+
"url": "git+https://github.com/ealush/vest.git",
|
|
44
20
|
"directory": "packages/context"
|
|
45
21
|
},
|
|
46
22
|
"bugs": {
|
|
47
23
|
"url": "https://github.com/ealush/vest.git/issues"
|
|
48
24
|
},
|
|
49
|
-
"unpkg": "./dist/
|
|
50
|
-
"jsdelivr": "./dist/
|
|
25
|
+
"unpkg": "./dist/context.mjs",
|
|
26
|
+
"jsdelivr": "./dist/context.mjs",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./types/context.d.cts",
|
|
30
|
+
"require": "./dist/context.cjs",
|
|
31
|
+
"import": "./dist/context.mjs"
|
|
32
|
+
},
|
|
33
|
+
"./*": {
|
|
34
|
+
"types": "./types/context.d.cts",
|
|
35
|
+
"default": "./*"
|
|
36
|
+
},
|
|
37
|
+
"./package.json": "./package.json",
|
|
38
|
+
"./context": "./types/context.d.cts",
|
|
39
|
+
"./context.d.ts": "./types/context.d.ts",
|
|
40
|
+
"./types/*": "./types/*",
|
|
41
|
+
"./dist/*": "./dist/*"
|
|
42
|
+
}
|
|
51
43
|
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
|
2
|
+
|
|
3
|
+
exports[`Cascading Context > context.run > Should clear context after callback run 1`] = `
|
|
4
|
+
{
|
|
5
|
+
"a": 1,
|
|
6
|
+
}
|
|
7
|
+
`;
|
|
8
|
+
|
|
9
|
+
exports[`Cascading Context > context.run > Should clear context after callback run 2`] = `
|
|
10
|
+
{
|
|
11
|
+
"a": 1,
|
|
12
|
+
"b": 2,
|
|
13
|
+
}
|
|
14
|
+
`;
|
|
15
|
+
|
|
16
|
+
exports[`Cascading Context > createCascade > Should return all methods 1`] = `
|
|
17
|
+
{
|
|
18
|
+
"bind": [Function],
|
|
19
|
+
"run": [Function],
|
|
20
|
+
"use": [Function],
|
|
21
|
+
"useX": [Function],
|
|
22
|
+
}
|
|
23
|
+
`;
|