context 2.0.9 → 3.0.0-dev-040354

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 CHANGED
@@ -5,32 +5,86 @@ It allows you to keep reference for shared variables, and access them down in yo
5
5
 
6
6
  ## How Context Works?
7
7
 
8
- The way context works is quite simple. Creating a context initializes a closure with a context storage object. When you run your context call, it takes your values, and places them in the context storage object. When your function finishes running, the context is cleared.
9
-
10
- ![image](https://user-images.githubusercontent.com/11255103/137119151-6912d3f1-ab48-4c91-a426-76af8abc8c55.png)
8
+ The way context works is quite simple. Creating a context initializes a closure with a context storage object. When you run your context call, it takes your values, and places them in the context's closure. When your function finishes running, the context is cleared.
11
9
 
12
10
  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
11
 
14
12
  ## API Reference
15
13
 
16
- Context tries to mimic the behavior of Javascript scopes without actually being in the same scopes, and the API is built around context initialization, setting of values within the context and retrieving values.
14
+ ### Top Level Exports
15
+
16
+ The context package exports these two functions:
17
+
18
+ - `createContext`: Creates a new context.
19
+ - `createCascade`: Creates a new cascading context.
20
+
21
+ ## createContext()
22
+
23
+ Create context is the minimal implementation of context. It allows propagation of values down in your function call.
24
+
25
+ createContext takes a single argument - defaultContextValue. This value is used when not withing a running context.
26
+
27
+ ### Arguments
28
+
29
+ | Argument | Type | Optional? | Description |
30
+ | ------------------- | ----- | --------- | ------------------------------------------------------------ |
31
+ | defaultContextValue | `any` | Yes | The default value to use when not withing a running context. |
17
32
 
18
- ### createContext()
33
+ ### Returned object
19
34
 
20
- Context's default export, it creates a context singleton object that can later be referenced.
35
+ `createContext` returns an object containing the following functions:
36
+
37
+ - `use`: Returns the current context value, or the default value when not withing a running context.
38
+ - `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.
39
+ - `run`: Runs the context, passing the given value into the context.
40
+
41
+ **Note About Typescript Usage**
42
+ 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.
43
+
44
+ ### Usage Example
21
45
 
22
46
  ```js
23
- // ctx.js
24
- import { createContext } from 'context';
47
+ const context = createContext(0); // Create a context with a default value of 0.
25
48
 
26
- export default createContext(); // { run: ƒ, bind: ƒ, use: ƒ, useX: ƒ }
49
+ function myFunc() {
50
+ context.run(100, someOtherFunc); // Run the context with a value of 100.
51
+ }
52
+
53
+ function someOtherFunc() {
54
+ const number = context.use(); // Returns the value of the context.
55
+ }
27
56
  ```
28
57
 
29
- createContext also accepts an initialization function that's run every time ctx.run is called. It allows intercepting the context initialization and adding custom logic, or default values.
30
- 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.
58
+ ## createCascade()
59
+
60
+ `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.
61
+
62
+ `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.
63
+
64
+ ### Arguments
65
+
66
+ | Argument | Type | Optional? | Description |
67
+ | ----------- | ---------- | --------- | ------------------------------------------------------------ |
68
+ | initializer | `Function` | Yes | The initializer function to use when creating a new context. |
69
+
70
+ The initializer function can either return the the next context object. If null is returned itself, the initializer will take no effect.
71
+ The initializer receives the context object, and the parent context object, if present.
72
+
73
+ ### Returned object
74
+
75
+ `createCascade` returns an object containing the following functions:
76
+
77
+ - `use`: Returns the current context value.
78
+ - `useX`: Returns the current context, throws an error if not within a running context or the context is undefined.
79
+ - `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.
80
+ - `bind`: Binds a given function to the context. Allows for delayd execution of a function as if it was called within the context.
81
+
82
+ ### Usage Examples
83
+
84
+ #### Initializer Function
31
85
 
32
86
  ```js
33
- createContext((ctx, parentContext) => {
87
+ createCascade((ctx, parentContext) => {
34
88
  if (parentContext === null) {
35
89
  // we're at the top level
36
90
  // so let's add a default cart object
@@ -44,7 +98,7 @@ createContext((ctx, parentContext) => {
44
98
  });
45
99
  ```
46
100
 
47
- ### run()
101
+ #### run()
48
102
 
49
103
  Runs a callback function within the context. It takes an object referencing the data you want to store within your context, and a callback function to run.
50
104
 
@@ -117,6 +171,24 @@ function getProductData(productId) {
117
171
  }
118
172
  ```
119
173
 
174
+ ## Typescript Support
175
+
176
+ 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:
177
+
178
+ ```ts
179
+ const someContext = createContext<number>(0);
180
+
181
+ const someCascadeContext = createCascade<{
182
+ username: string;
183
+ firstName: string;
184
+ middleName?: string;
185
+ lastName: string;
186
+ age: number;
187
+ }>();
188
+ ```
189
+
190
+ This meakes sure that all the functions (`run`, `use`, `useX` and `bind`) will be aware of these types, and either accept them as inputs, or add them to the return value.
191
+
120
192
  ## Troubleshooting
121
193
 
122
194
  ### Working with async functions/promises
@@ -4,49 +4,55 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var vestUtils = require('vest-utils');
6
6
 
7
- // eslint-disable-next-line max-lines-per-function
8
- function createContext(init) {
9
- var storage = {};
7
+ function createContext(defaultContextValue) {
8
+ var contextValue = undefined;
10
9
  return {
11
- bind: bind,
12
10
  run: run,
13
11
  use: use,
14
12
  useX: useX
15
13
  };
14
+ function use() {
15
+ return vestUtils.defaultTo(contextValue, defaultContextValue);
16
+ }
16
17
  function useX(errorMessage) {
17
- var ctx = use();
18
- vestUtils.invariant(ctx, vestUtils.defaultTo(errorMessage, 'Context was used after it was closed'));
19
- return ctx;
18
+ var contextValue = use();
19
+ vestUtils.invariant(contextValue, vestUtils.defaultTo(errorMessage, 'Context was used after it was closed'));
20
+ return contextValue;
20
21
  }
21
- function run(ctxRef, fn) {
22
- var _a;
22
+ function run(value, cb) {
23
23
  var parentContext = use();
24
- var out = vestUtils.assign({}, parentContext ? parentContext : {}, (_a = vestUtils.optionalFunctionValue(init, ctxRef, parentContext)) !== null && _a !== void 0 ? _a : ctxRef);
25
- var ctx = set(Object.freeze(out));
26
- var res = fn(ctx);
27
- storage.ctx = parentContext;
24
+ contextValue = value;
25
+ var res = cb();
26
+ contextValue = parentContext;
28
27
  return res;
29
28
  }
30
- function bind(ctxRef, fn) {
31
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
32
- // @ts-ignore - this one's pretty hard to get right
33
- var returnedFn = function () {
29
+ }
30
+ function createCascade(init) {
31
+ var ctx = createContext();
32
+ return {
33
+ bind: bind,
34
+ run: run,
35
+ use: ctx.use,
36
+ useX: ctx.useX
37
+ };
38
+ function run(value, fn) {
39
+ var _a;
40
+ var parentContext = ctx.use();
41
+ var out = vestUtils.assign({}, parentContext ? parentContext : {}, (_a = vestUtils.optionalFunctionValue(init, value, parentContext)) !== null && _a !== void 0 ? _a : value);
42
+ return ctx.run(Object.freeze(out), fn);
43
+ }
44
+ function bind(value, fn) {
45
+ return function () {
34
46
  var runTimeArgs = [];
35
47
  for (var _i = 0; _i < arguments.length; _i++) {
36
48
  runTimeArgs[_i] = arguments[_i];
37
49
  }
38
- return run(ctxRef, function () {
50
+ return run(value, function () {
39
51
  return fn.apply(void 0, runTimeArgs);
40
52
  });
41
53
  };
42
- return returnedFn;
43
- }
44
- function use() {
45
- return storage.ctx;
46
- }
47
- function set(value) {
48
- return (storage.ctx = value);
49
54
  }
50
55
  }
51
56
 
57
+ exports.createCascade = createCascade;
52
58
  exports.createContext = createContext;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("vest-utils");exports.createContext=function(e){function n(n,o){var i,a=r();return n=t.assign({},a||{},null!==(i=t.optionalFunctionValue(e,n,a))&&void 0!==i?i:n),o=o(i=u.ctx=Object.freeze(n)),u.ctx=a,o}function r(){return u.ctx}var u={};return{bind:function(t,e){return function(){for(var r=[],u=0;u<arguments.length;u++)r[u]=arguments[u];return n(t,(function(){return e.apply(void 0,r)}))}},run:n,use:r,useX:function(e){var n=r();return t.invariant(n,t.defaultTo(e,"Context was used after it was closed")),n}}};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("vest-utils");function n(n){function r(){return e.defaultTo(t,n)}var t=void 0;return{run:function(e,n){var u=r();return t=e,e=n(),t=u,e},use:r,useX:function(n){var t=r();return e.invariant(t,e.defaultTo(n,"Context was used after it was closed")),t}}}exports.createCascade=function(r){function t(n,t){var o,a=u.use();return n=e.assign({},a||{},null!==(o=e.optionalFunctionValue(r,n,a))&&void 0!==o?o:n),u.run(Object.freeze(n),t)}var u=n();return{bind:function(e,n){return function(){for(var r=[],u=0;u<arguments.length;u++)r[u]=arguments[u];return t(e,(function(){return n.apply(void 0,r)}))}},run:t,use:u.use,useX:u.useX}},exports.createContext=n;
@@ -1,48 +1,53 @@
1
- import { invariant, defaultTo, assign, optionalFunctionValue } from 'vest-utils';
1
+ import { defaultTo, invariant, assign, optionalFunctionValue } from 'vest-utils';
2
2
 
3
- // eslint-disable-next-line max-lines-per-function
4
- function createContext(init) {
5
- var storage = {};
3
+ function createContext(defaultContextValue) {
4
+ var contextValue = undefined;
6
5
  return {
7
- bind: bind,
8
6
  run: run,
9
7
  use: use,
10
8
  useX: useX
11
9
  };
10
+ function use() {
11
+ return defaultTo(contextValue, defaultContextValue);
12
+ }
12
13
  function useX(errorMessage) {
13
- var ctx = use();
14
- invariant(ctx, defaultTo(errorMessage, 'Context was used after it was closed'));
15
- return ctx;
14
+ var contextValue = use();
15
+ invariant(contextValue, defaultTo(errorMessage, 'Context was used after it was closed'));
16
+ return contextValue;
16
17
  }
17
- function run(ctxRef, fn) {
18
- var _a;
18
+ function run(value, cb) {
19
19
  var parentContext = use();
20
- var out = assign({}, parentContext ? parentContext : {}, (_a = optionalFunctionValue(init, ctxRef, parentContext)) !== null && _a !== void 0 ? _a : ctxRef);
21
- var ctx = set(Object.freeze(out));
22
- var res = fn(ctx);
23
- storage.ctx = parentContext;
20
+ contextValue = value;
21
+ var res = cb();
22
+ contextValue = parentContext;
24
23
  return res;
25
24
  }
26
- function bind(ctxRef, fn) {
27
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
28
- // @ts-ignore - this one's pretty hard to get right
29
- var returnedFn = function () {
25
+ }
26
+ function createCascade(init) {
27
+ var ctx = createContext();
28
+ return {
29
+ bind: bind,
30
+ run: run,
31
+ use: ctx.use,
32
+ useX: ctx.useX
33
+ };
34
+ function run(value, fn) {
35
+ var _a;
36
+ var parentContext = ctx.use();
37
+ var out = assign({}, parentContext ? parentContext : {}, (_a = optionalFunctionValue(init, value, parentContext)) !== null && _a !== void 0 ? _a : value);
38
+ return ctx.run(Object.freeze(out), fn);
39
+ }
40
+ function bind(value, fn) {
41
+ return function () {
30
42
  var runTimeArgs = [];
31
43
  for (var _i = 0; _i < arguments.length; _i++) {
32
44
  runTimeArgs[_i] = arguments[_i];
33
45
  }
34
- return run(ctxRef, function () {
46
+ return run(value, function () {
35
47
  return fn.apply(void 0, runTimeArgs);
36
48
  });
37
49
  };
38
- return returnedFn;
39
- }
40
- function use() {
41
- return storage.ctx;
42
- }
43
- function set(value) {
44
- return (storage.ctx = value);
45
50
  }
46
51
  }
47
52
 
48
- export { createContext };
53
+ export { createCascade, createContext };
@@ -1 +1 @@
1
- import{invariant as t,defaultTo as n,assign as r,optionalFunctionValue as e}from"vest-utils";export function createContext(u){function o(t,n){var o,f=c();return t=r({},f||{},null!==(o=e(u,t,f))&&void 0!==o?o:t),n=n(o=i.ctx=Object.freeze(t)),i.ctx=f,n}function c(){return i.ctx}var i={};return{bind:function(t,n){return function(){for(var r=[],e=0;e<arguments.length;e++)r[e]=arguments[e];return o(t,(function(){return n.apply(void 0,r)}))}},run:o,use:c,useX:function(r){var e=c();return t(e,n(r,"Context was used after it was closed")),e}}}
1
+ import{defaultTo as n,invariant as r,assign as t,optionalFunctionValue as u}from"vest-utils";function e(t){function u(){return n(e,t)}var e=void 0;return{run:function(n,r){var t=u();return e=n,n=r(),e=t,n},use:u,useX:function(t){var e=u();return r(e,n(t,"Context was used after it was closed")),e}}}function o(n){function r(r,e){var i,s=o.use();return r=t({},s||{},null!==(i=u(n,r,s))&&void 0!==i?i:r),o.run(Object.freeze(r),e)}var o=e();return{bind:function(n,t){return function(){for(var u=[],e=0;e<arguments.length;e++)u[e]=arguments[e];return r(n,(function(){return t.apply(void 0,u)}))}},run:r,use:o.use,useX:o.useX}}export{o as createCascade,e as createContext};
@@ -4,51 +4,57 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.context = {}, global['vest-utils']));
5
5
  }(this, (function (exports, vestUtils) { 'use strict';
6
6
 
7
- // eslint-disable-next-line max-lines-per-function
8
- function createContext(init) {
9
- var storage = {};
7
+ function createContext(defaultContextValue) {
8
+ var contextValue = undefined;
10
9
  return {
11
- bind: bind,
12
10
  run: run,
13
11
  use: use,
14
12
  useX: useX
15
13
  };
14
+ function use() {
15
+ return vestUtils.defaultTo(contextValue, defaultContextValue);
16
+ }
16
17
  function useX(errorMessage) {
17
- var ctx = use();
18
- vestUtils.invariant(ctx, vestUtils.defaultTo(errorMessage, 'Context was used after it was closed'));
19
- return ctx;
18
+ var contextValue = use();
19
+ vestUtils.invariant(contextValue, vestUtils.defaultTo(errorMessage, 'Context was used after it was closed'));
20
+ return contextValue;
20
21
  }
21
- function run(ctxRef, fn) {
22
- var _a;
22
+ function run(value, cb) {
23
23
  var parentContext = use();
24
- var out = vestUtils.assign({}, parentContext ? parentContext : {}, (_a = vestUtils.optionalFunctionValue(init, ctxRef, parentContext)) !== null && _a !== void 0 ? _a : ctxRef);
25
- var ctx = set(Object.freeze(out));
26
- var res = fn(ctx);
27
- storage.ctx = parentContext;
24
+ contextValue = value;
25
+ var res = cb();
26
+ contextValue = parentContext;
28
27
  return res;
29
28
  }
30
- function bind(ctxRef, fn) {
31
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
32
- // @ts-ignore - this one's pretty hard to get right
33
- var returnedFn = function () {
29
+ }
30
+ function createCascade(init) {
31
+ var ctx = createContext();
32
+ return {
33
+ bind: bind,
34
+ run: run,
35
+ use: ctx.use,
36
+ useX: ctx.useX
37
+ };
38
+ function run(value, fn) {
39
+ var _a;
40
+ var parentContext = ctx.use();
41
+ var out = vestUtils.assign({}, parentContext ? parentContext : {}, (_a = vestUtils.optionalFunctionValue(init, value, parentContext)) !== null && _a !== void 0 ? _a : value);
42
+ return ctx.run(Object.freeze(out), fn);
43
+ }
44
+ function bind(value, fn) {
45
+ return function () {
34
46
  var runTimeArgs = [];
35
47
  for (var _i = 0; _i < arguments.length; _i++) {
36
48
  runTimeArgs[_i] = arguments[_i];
37
49
  }
38
- return run(ctxRef, function () {
50
+ return run(value, function () {
39
51
  return fn.apply(void 0, runTimeArgs);
40
52
  });
41
53
  };
42
- return returnedFn;
43
- }
44
- function use() {
45
- return storage.ctx;
46
- }
47
- function set(value) {
48
- return (storage.ctx = value);
49
54
  }
50
55
  }
51
56
 
57
+ exports.createCascade = createCascade;
52
58
  exports.createContext = createContext;
53
59
 
54
60
  Object.defineProperty(exports, '__esModule', { value: true });
@@ -1 +1 @@
1
- "use strict";!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vest-utils")):"function"==typeof define&&define.amd?define(["exports","vest-utils"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).context={},e["vest-utils"])}(this,(function(e,t){e.createContext=function(e){function n(n,i){var r,f=u();return n=t.assign({},f||{},null!==(r=t.optionalFunctionValue(e,n,f))&&void 0!==r?r:n),i=i(r=o.ctx=Object.freeze(n)),o.ctx=f,i}function u(){return o.ctx}var o={};return{bind:function(e,t){return function(){for(var u=[],o=0;o<arguments.length;o++)u[o]=arguments[o];return n(e,(function(){return t.apply(void 0,u)}))}},run:n,use:u,useX:function(e){var n=u();return t.invariant(n,t.defaultTo(e,"Context was used after it was closed")),n}}},Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ "use strict";!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("vest-utils")):"function"==typeof define&&define.amd?define(["exports","vest-utils"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).context={},e["vest-utils"])}(this,(function(e,t){function n(e){function n(){return t.defaultTo(u,e)}var u=void 0;return{run:function(e,t){var r=n();return u=e,e=t(),u=r,e},use:n,useX:function(e){var u=n();return t.invariant(u,t.defaultTo(e,"Context was used after it was closed")),u}}}e.createCascade=function(e){function u(n,u){var o,i=r.use();return n=t.assign({},i||{},null!==(o=t.optionalFunctionValue(e,n,i))&&void 0!==o?o:n),r.run(Object.freeze(n),u)}var r=n();return{bind:function(e,t){return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return u(e,(function(){return t.apply(void 0,n)}))}},run:u,use:r.use,useX:r.useX}},e.createContext=n,Object.defineProperty(e,"__esModule",{value:!0})}));
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.0.9",
2
+ "version": "3.0.0-dev-040354",
3
3
  "license": "MIT",
4
4
  "main": "./dist/cjs/context.js",
5
5
  "types": "./types/context.d.ts",
@@ -1,8 +1,15 @@
1
1
  type CB = (...args: any[]) => any;
2
- declare function createContext<T extends Record<string, unknown>>(init?: (ctxRef: Partial<T>, parentContext: T | void) => T | null): {
3
- run: <R>(ctxRef: Partial<T>, fn: (context: T) => R) => R;
4
- bind: <Fn extends CB>(ctxRef: Partial<T>, fn: Fn) => Fn;
5
- use: () => T | undefined;
2
+ declare function createContext<T extends unknown>(defaultContextValue?: T): CtxApi<T>;
3
+ declare function createCascade<T extends Record<string, unknown>>(init?: (value: Partial<T>, parentContext: T | void) => T | null): CtxCascadeApi<T>;
4
+ type ContextConsumptionApi<T> = {
5
+ use: () => T;
6
6
  useX: (errorMessage?: string) => T;
7
7
  };
8
- export { createContext };
8
+ type CtxApi<T> = ContextConsumptionApi<T> & {
9
+ run: <R>(value: T, cb: () => R) => R;
10
+ };
11
+ type CtxCascadeApi<T> = ContextConsumptionApi<T> & {
12
+ run: <R>(value: Partial<T>, fn: () => R) => R;
13
+ bind: <Fn extends CB>(value: Partial<T>, fn: Fn) => Fn;
14
+ };
15
+ export { createContext, createCascade, CtxApi, CtxCascadeApi };