@webkrafters/react-observable-context 3.0.0 → 4.0.0-alpha.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.
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ exports["default"] = void 0;
6
+ var _lodash = _interopRequireDefault(require("lodash.clonedeep"));
7
+ var _lodash2 = _interopRequireDefault(require("lodash.isequal"));
8
+ var _lodash3 = _interopRequireDefault(require("lodash.isplainobject"));
9
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
10
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
11
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
12
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
13
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
14
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
15
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
16
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
17
+ /** @param {{[x:string]: any}} obj */
18
+ var isIndexBasedObj = function isIndexBasedObj(obj) {
19
+ return Object.keys(obj).every(function (k) {
20
+ var i = +k;
21
+ return Number.isInteger(i) && i > -1;
22
+ });
23
+ };
24
+ /**
25
  * Mutates its arguments
1
26
  *
2
27
  * @param {HasArrayRoot<K>|HasObjectRoot<K>} state
3
28
  * @param {HasArrayRoot<K>|HasObjectRoot<K>} newState
4
29
  * @param {K} stateKey
5
30
  * @param {Stats} stats
6
31
  * @template {KeyTypes} K
7
32
  */
33
+ function setAtomic(state, newState, stateKey, stats) {
34
+ if ((0, _lodash2["default"])(state[stateKey], newState[stateKey])) {
35
+ return;
36
+ }
37
+ var isPlainObjectNewState = (0, _lodash3["default"])(newState[stateKey]);
38
+ var isArrayNewState = Array.isArray(newState[stateKey]);
39
+ if (Array.isArray(state[stateKey])) {
40
+ if (isArrayNewState) {
41
+ return setArray(state, newState, stateKey, stats);
42
+ }
43
+ if (isPlainObjectNewState && isIndexBasedObj(newState[stateKey])) {
44
+ return setArrayIndex(state, newState, stateKey, stats);
45
+ }
46
+ }
47
+ if (isPlainObjectNewState && (0, _lodash3["default"])(state[stateKey])) {
48
+ return setPlainObject(state, newState, stateKey, stats);
49
+ }
50
+ stats.hasChanges = true;
51
+ state[stateKey] = isArrayNewState || isPlainObjectNewState ? (0, _lodash["default"])(newState[stateKey]) : newState[stateKey];
52
+ }
53
+ ;
54
+ /**
8
55
  * Mutates its arguments
9
56
  *
10
57
  * @param {HasArrayRoot<K>} state
11
58
  * @param {HasArrayRoot<K>} newState
12
59
  * @param {K} rootKey
13
60
  * @param {Stats} stats
14
61
  * @template {KeyTypes} K
15
62
  */
63
+ function setArray(state, newState, rootKey, stats) {
64
+ var nsLength = newState[rootKey].length;
65
+ if (state[rootKey].length !== nsLength) {
66
+ state[rootKey].length = nsLength;
67
+ stats.hasChanges = true;
68
+ }
69
+ for (var i = 0; i < nsLength; i++) {
70
+ setAtomic(state[rootKey], newState[rootKey], i, stats);
71
+ }
72
+ }
73
+ ;
74
+ /**
16
75
  * Mutates its arguments
17
76
  *
18
77
  * @param {HasArrayRoot<K>} state
19
78
  * @param {HasObjectRoot<K>} newState
20
79
  * @param {K} rootKey
21
80
  * @param {Stats} stats
22
81
  * @template {KeyTypes} K
23
82
  */
83
+ function setArrayIndex(state, newState, rootKey, stats) {
84
+ var incomingIndexes = Object.keys(newState[rootKey]).map(function (i) {
85
+ return +i;
86
+ });
87
+ var maxIncomingIndex = Math.max.apply(Math, _toConsumableArray(incomingIndexes));
88
+ if (maxIncomingIndex >= state[rootKey].length) {
89
+ state[rootKey].length = maxIncomingIndex + 1;
90
+ stats.hasChanges = true;
91
+ }
92
+ var _iterator = _createForOfIteratorHelper(incomingIndexes),
93
+ _step;
94
+ try {
95
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
96
+ var i = _step.value;
97
+ setAtomic(state[rootKey], newState[rootKey], i, stats);
98
+ }
99
+ } catch (err) {
100
+ _iterator.e(err);
101
+ } finally {
102
+ _iterator.f();
103
+ }
104
+ }
105
+ ;
106
+ /**
24
107
  * Mutates its arguments
25
108
  *
26
109
  * @param {HasObjectRoot<K>} state
27
110
  * @param {HasObjectRoot<K>} newState
28
111
  * @param {K} rootKey
29
112
  * @param {Stats} stats
30
113
  * @template {KeyTypes} K
31
114
  */
115
+ function setPlainObject(state, newState, rootKey, stats) {
116
+ set(state[rootKey], newState[rootKey], stats);
117
+ }
118
+ ;
119
+ /**
32
120
  * Mutates its arguments
33
121
  *
34
122
  * @param {HasObjectRoot} state
35
123
  * @param {HasObjectRoot} newState
36
124
  * @param {Stats} stats
37
125
  */
126
+ function set(state, newState, stats) {
127
+ for (var k in newState) {
128
+ setAtomic(state, newState, k, stats);
129
+ }
130
+ }
131
+ ;
132
+ /**
38
133
  * @param {T} state
39
134
  * @param {PartialState<T>} newState
40
135
  * @param {Listener<T>} [onStateChange]
41
136
  * @template {State} T
42
137
  */
138
+ function setState(state, newState, onStateChange) {
139
+ var stats = {
140
+ hasChanges: false
141
+ };
142
+ set(state, newState, stats);
143
+ stats.hasChanges && (onStateChange === null || onStateChange === void 0 ? void 0 : onStateChange(state));
144
+ }
145
+ ;
146
+ var _default = setState;
147
+ exports["default"] = _default;
@@ -0,0 +1 @@
1
+ export default Accessor;
2
  static "__#5@#NUM_INSTANCES": number;
1
3
  /**
2
4
  * @param {T} source State object reference from which the accessedPropertyPaths are to be selected.
3
5
  * @param {Array<string>} accessedPropertyPaths
4
6
  */
5
7
  constructor(source: T, accessedPropertyPaths: Array<string>);
6
8
  /** @type {boolean} */
7
9
  refreshDue: boolean;
8
10
  get numClients(): number;
9
11
  get id(): number;
10
12
  get paths(): string[];
11
13
  get value(): Readonly<import("../../types").PartialState<T>>;
12
14
  /** @param {string} clientId */
13
15
  addClient(clientId: string): void;
14
16
  hasClient(clientId: string): boolean;
15
17
  removeClient(clientId: string): boolean;
16
18
  /**
17
19
  * @param {{[propertyPath: string]: Atom}} atoms Curated slices of state currently requested
18
20
  * @returns {Readonly<PartialState<State>>}
19
21
  */
20
22
  refreshValue(atoms: {
21
23
  [propertyPath: string]: import("../atom").default;
22
24
  }): Readonly<PartialState<State>>;
23
25
  #private;
@@ -0,0 +1,258 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ exports["default"] = void 0;
6
+ var _lodash = _interopRequireDefault(require("lodash.clonedeep"));
7
+ var _lodash2 = _interopRequireDefault(require("lodash.isequal"));
8
+ var _lodash3 = _interopRequireDefault(require("lodash.isplainobject"));
9
+ var _lodash4 = _interopRequireDefault(require("lodash.set"));
10
+ var _constants = require("../../constants");
11
+ var _utils = require("../../utils");
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
13
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
14
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
16
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
17
+ function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
18
+ function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
19
+ function _classPrivateFieldGet(receiver, privateMap) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get"); return _classApplyDescriptorGet(receiver, descriptor); }
20
+ function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) { _classCheckPrivateStaticAccess(receiver, classConstructor); _classCheckPrivateStaticFieldDescriptor(descriptor, "set"); _classApplyDescriptorSet(receiver, descriptor, value); return value; }
21
+ function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) { _classCheckPrivateStaticAccess(receiver, classConstructor); _classCheckPrivateStaticFieldDescriptor(descriptor, "get"); return _classApplyDescriptorGet(receiver, descriptor); }
22
+ function _classCheckPrivateStaticFieldDescriptor(descriptor, action) { if (descriptor === undefined) { throw new TypeError("attempted to " + action + " private static field before its declaration"); } }
23
+ function _classCheckPrivateStaticAccess(receiver, classConstructor) { if (receiver !== classConstructor) { throw new TypeError("Private static access of wrong provenance"); } }
24
+ function _classApplyDescriptorGet(receiver, descriptor) { if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; }
25
+ function _classPrivateFieldSet(receiver, privateMap, value) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set"); _classApplyDescriptorSet(receiver, descriptor, value); return value; }
26
+ function _classExtractFieldDescriptor(receiver, privateMap, action) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to " + action + " private field on non-instance"); } return privateMap.get(receiver); }
27
+ function _classApplyDescriptorSet(receiver, descriptor, value) { if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { throw new TypeError("attempted to set read only private field"); } descriptor.value = value; } }
28
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
29
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
30
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
31
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
32
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
33
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
34
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
35
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
36
+ /**
37
  * Returns function that checks whether its argument is either the ancestorPath or its child/descendant
1
38
  *
2
39
  * @type {(ancestorPath?: string) => {contains: (path: string) => boolean}}
3
40
  */
41
+ var getPathTesterIn = function () {
42
+ var PATH_DELIMITERS = {
43
+ '.': null,
44
+ '[': null
45
+ };
46
+ return function () {
47
+ var ancestorPath = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
48
+ var ancestorPathLength = (ancestorPath === null || ancestorPath === void 0 ? void 0 : ancestorPath.length) || 0;
49
+ return {
50
+ contains: function contains(path) {
51
+ return ancestorPathLength && path.startsWith(ancestorPath) && (ancestorPathLength === path.length || path[ancestorPathLength] in PATH_DELIMITERS);
52
+ }
53
+ };
54
+ };
55
+ }();
56
+ /**
4
57
  * Merges `changes` into a `slice` of the state object.
5
58
  *
6
59
  * Advisory: Will undo the readonly xteristics of affected hierarchies within the `slice`.
7
60
  */
61
+ var mergeChanges = function () {
62
+ var matchCompositeType = function matchCompositeType(slice, changes) {
63
+ if (Array.isArray(slice) && Array.isArray(changes)) {
64
+ return Array;
65
+ }
66
+ if ((0, _lodash3["default"])(slice) && (0, _lodash3["default"])(changes)) {
67
+ return Object;
68
+ }
69
+ };
70
+ var doMergeAt = function doMergeAt(key, slice, changes) {
71
+ if ((0, _lodash2["default"])(slice[key], changes[key])) {
72
+ return;
73
+ }
74
+ if (Object.isFrozen(changes[key])) {
75
+ slice[key] = changes[key];
76
+ return;
77
+ }
78
+ if (Object.isFrozen(slice[key])) {
79
+ slice[key] = _objectSpread({}, slice[key]);
80
+ }
81
+ switch (matchCompositeType(slice[key], changes[key])) {
82
+ case Object:
83
+ runMerger(slice[key], changes[key]);
84
+ break;
85
+ case Array:
86
+ slice[key].length = changes[key].length;
87
+ runMerger(slice[key], changes[key]);
88
+ break;
89
+ default:
90
+ slice[key] = changes[key];
91
+ }
92
+ };
93
+ var runMerger = function runMerger(slice, changes) {
94
+ if ((0, _lodash3["default"])(changes)) {
95
+ for (var k in changes) {
96
+ doMergeAt(k, slice, changes);
97
+ }
98
+ } else if (Array.isArray(changes)) {
99
+ changes.forEach(function (_, c) {
100
+ return doMergeAt(c, slice, changes);
101
+ });
102
+ }
103
+ };
104
+ /**
8
105
  * @param {T} slice
9
106
  * @param {T} changes
10
107
  * @template {PartialState<State>} T
11
108
  */
109
+ var mergeChanges = function mergeChanges(slice, changes) {
110
+ !(0, _lodash2["default"])(slice, changes) && runMerger(slice, changes);
111
+ };
112
+ return mergeChanges;
113
+ }();
114
+ /** @type {(paths: Array<string>) => Array<string>} */
115
+ var arrangePaths = function arrangePaths(paths) {
116
+ if (paths.includes(_constants.DEFAULT_STATE_PATH)) {
117
+ return [_constants.DEFAULT_STATE_PATH];
118
+ }
119
+ /** @type {Array<string>} */
120
+ var arranged = [];
121
+ var group = getPathTesterIn();
122
+ var _iterator = _createForOfIteratorHelper((0, _lodash["default"])(paths).sort()),
123
+ _step;
124
+ try {
125
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
126
+ var path = _step.value;
127
+ if (group.contains(path)) {
128
+ continue;
129
+ }
130
+ group = getPathTesterIn(path);
131
+ arranged.push(path);
132
+ }
133
+ } catch (err) {
134
+ _iterator.e(err);
135
+ } finally {
136
+ _iterator.f();
137
+ }
138
+ return arranged;
139
+ };
140
+ /** @template {State} T */
141
+ var _clients = new WeakMap();
142
+ var _id = new WeakMap();
143
+ var _paths = new WeakMap();
144
+ var _source = new WeakMap();
145
+ var _value = new WeakMap();
146
+ var Accessor = function () {
147
+ /** @type {Set<string>} */
148
+ /** @type {number} */
149
+ /** @type {Array<string>} */
150
+ /** @type {T} */
151
+ /** @type {Readonly<PartialState<T>>} */
152
+ /**
12
153
  * @param {T} source State object reference from which the accessedPropertyPaths are to be selected.
13
154
  * @param {Array<string>} accessedPropertyPaths
14
155
  */
156
+ function Accessor(source, accessedPropertyPaths) {
157
+ var _Accessor$NUM_INSTANC, _Accessor$NUM_INSTANC2;
158
+ _classCallCheck(this, Accessor);
159
+ _classPrivateFieldInitSpec(this, _clients, {
160
+ writable: true,
161
+ value: void 0
162
+ });
163
+ _classPrivateFieldInitSpec(this, _id, {
164
+ writable: true,
165
+ value: void 0
166
+ });
167
+ _classPrivateFieldInitSpec(this, _paths, {
168
+ writable: true,
169
+ value: void 0
170
+ });
171
+ _classPrivateFieldInitSpec(this, _source, {
172
+ writable: true,
173
+ value: void 0
174
+ });
175
+ _classPrivateFieldInitSpec(this, _value, {
176
+ writable: true,
177
+ value: void 0
178
+ });
179
+ _classPrivateFieldSet(this, _clients, new Set());
180
+ _classPrivateFieldSet(this, _id, _classStaticPrivateFieldSpecSet(Accessor, Accessor, _NUM_INSTANCES, (_Accessor$NUM_INSTANC2 = _classStaticPrivateFieldSpecGet(Accessor, Accessor, _NUM_INSTANCES), ++_Accessor$NUM_INSTANC2)));
181
+ _classPrivateFieldSet(this, _paths, arrangePaths(accessedPropertyPaths));
182
+ /** @type {boolean} */
183
+ this.refreshDue = true;
184
+ _classPrivateFieldSet(this, _source, source);
185
+ _classPrivateFieldSet(this, _value, (0, _utils.makeReadonly)({}));
186
+ }
187
+ _createClass(Accessor, [{
188
+ key: "numClients",
189
+ get: function get() {
190
+ return _classPrivateFieldGet(this, _clients).size;
191
+ }
192
+ }, {
193
+ key: "id",
194
+ get: function get() {
195
+ return _classPrivateFieldGet(this, _id);
196
+ }
197
+ }, {
198
+ key: "paths",
199
+ get: function get() {
200
+ return _classPrivateFieldGet(this, _paths);
201
+ }
202
+ }, {
203
+ key: "value",
204
+ get: function get() {
205
+ return _classPrivateFieldGet(this, _value);
206
+ }
207
+ /** @param {string} clientId */
208
+ }, {
209
+ key: "addClient",
210
+ value: function addClient(clientId) {
211
+ _classPrivateFieldGet(this, _clients).add(clientId);
212
+ }
213
+ /** @type {(clientId: string) => boolean} */
214
+ }, {
215
+ key: "hasClient",
216
+ value: function hasClient(clientId) {
217
+ return _classPrivateFieldGet(this, _clients).has(clientId);
218
+ }
219
+ /** @type {(clientId: string) => boolean} */
220
+ }, {
221
+ key: "removeClient",
222
+ value: function removeClient(clientId) {
223
+ return _classPrivateFieldGet(this, _clients)["delete"](clientId);
224
+ }
225
+ /**
15
226
  * @param {{[propertyPath: string]: Atom}} atoms Curated slices of state currently requested
16
227
  * @returns {Readonly<PartialState<State>>}
17
228
  */
229
+ }, {
230
+ key: "refreshValue",
231
+ value: function refreshValue(atoms) {
232
+ if (!this.refreshDue) {
233
+ return _classPrivateFieldGet(this, _value);
234
+ }
235
+ this.refreshDue = false;
236
+ var value = _objectSpread({}, _classPrivateFieldGet(this, _value));
237
+ if (_classPrivateFieldGet(this, _paths)[0] === _constants.DEFAULT_STATE_PATH) {
238
+ for (var k in _classPrivateFieldGet(this, _source)) {
239
+ if (!(0, _lodash2["default"])(value[k], _classPrivateFieldGet(this, _source)[k])) {
240
+ value[k] = (0, _lodash["default"])(_classPrivateFieldGet(this, _source)[k]);
241
+ }
242
+ }
243
+ } else {
244
+ /** @type {PartialState<State>} */
245
+ var update = {};
246
+ var _iterator2 = _createForOfIteratorHelper(_classPrivateFieldGet(this, _paths)),
247
+ _step2;
248
+ try {
249
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
250
+ var p = _step2.value;
251
+ if (!(p in atoms)) {
252
+ continue;
253
+ }
254
+ var atom = atoms[p];
255
+ !atom.isConnected(_classPrivateFieldGet(this, _id)) && atom.connect(_classPrivateFieldGet(this, _id));
256
+ (0, _lodash4["default"])(update, p, atom.value);
257
+ }
258
+ } catch (err) {
259
+ _iterator2.e(err);
260
+ } finally {
261
+ _iterator2.f();
262
+ }
263
+ mergeChanges(value, update);
264
+ }
265
+ _classPrivateFieldSet(this, _value, (0, _utils.makeReadonly)(value));
266
+ return _classPrivateFieldGet(this, _value);
267
+ }
268
+ }]);
269
+ return Accessor;
270
+ }();
271
+ var _NUM_INSTANCES = {
272
+ writable: true,
273
+ value: 0
274
+ };
275
+ var _default = Accessor;
276
+ exports["default"] = _default;
@@ -0,0 +1 @@
1
+ export default AccessorCache;
2
  /** @param {T} origin State object reference from which slices stored in this cache are to be curated */
1
3
  constructor(origin: T);
2
4
  /**
3
5
  * Gets state slice from the cache matching the `propertyPaths`.\
4
6
  * If not found, creates a new entry for the client from source, and returns it.
5
7
  *
6
8
  * @param {string} clientId
7
9
  * @param {...string} propertyPaths
8
10
  * @return {Readonly<PartialState<T>>}
9
11
  */
10
12
  get(clientId: string, ...propertyPaths: string[]): Readonly<PartialState<T>>;
11
13
  /**
12
14
  * Unlinks a consumer from the cache: performing synchronized state cleanup
13
15
  *
14
16
  * @param {string} clientId
15
17
  */
16
18
  unlinkClient(clientId: string): void;
17
19
  /** Observes the origin state bearing ObservableContext store for state changes to update accessors. */
18
20
  watchSource(): void;
19
21
  #private;
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports["default"] = void 0;
7
+ var _lodash = _interopRequireDefault(require("lodash.get"));
8
+ var _lodash2 = _interopRequireDefault(require("lodash.isempty"));
9
+ var _lodash3 = _interopRequireDefault(require("lodash.isequal"));
10
+ var _constants = require("../../constants");
11
+ var _atom = _interopRequireDefault(require("../atom"));
12
+ var _accessor = _interopRequireDefault(require("../accessor"));
13
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
14
+ function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
15
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
16
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
17
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
18
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
19
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
20
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
21
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
22
+ function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); }
23
+ function _classPrivateFieldInitSpec(obj, privateMap, value) { _checkPrivateRedeclaration(obj, privateMap); privateMap.set(obj, value); }
24
+ function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
25
+ function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; }
26
+ function _classPrivateFieldGet(receiver, privateMap) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get"); return _classApplyDescriptorGet(receiver, descriptor); }
27
+ function _classApplyDescriptorGet(receiver, descriptor) { if (descriptor.get) { return descriptor.get.call(receiver); } return descriptor.value; }
28
+ function _classPrivateFieldSet(receiver, privateMap, value) { var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set"); _classApplyDescriptorSet(receiver, descriptor, value); return value; }
29
+ function _classExtractFieldDescriptor(receiver, privateMap, action) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to " + action + " private field on non-instance"); } return privateMap.get(receiver); }
30
+ function _classApplyDescriptorSet(receiver, descriptor, value) { if (descriptor.set) { descriptor.set.call(receiver, value); } else { if (!descriptor.writable) { throw new TypeError("attempted to set read only private field"); } descriptor.value = value; } }
31
+ var _accessors = new WeakMap();
32
+ var _atoms = new WeakMap();
33
+ var _origin = new WeakMap();
34
+ var _createAccessor = new WeakSet();
35
+ /** @template {State} T */
36
+ var AccessorCache = function () {
37
+ /** @type {{[propertyPaths: string]: Accessor<T>}} */
38
+ /** @type {{[propertyPath: string]: Atom}} */
39
+ /** @type {T} */
40
+ /** @param {T} origin State object reference from which slices stored in this cache are to be curated */
41
+ function AccessorCache(origin) {
42
+ _classCallCheck(this, AccessorCache);
43
+ _classPrivateMethodInitSpec(this, _createAccessor);
44
+ _classPrivateFieldInitSpec(this, _accessors, {
45
+ writable: true,
46
+ value: void 0
47
+ });
48
+ _classPrivateFieldInitSpec(this, _atoms, {
49
+ writable: true,
50
+ value: void 0
51
+ });
52
+ _classPrivateFieldInitSpec(this, _origin, {
53
+ writable: true,
54
+ value: void 0
55
+ });
56
+ _classPrivateFieldSet(this, _accessors, {});
57
+ _classPrivateFieldSet(this, _atoms, {});
58
+ _classPrivateFieldSet(this, _origin, origin);
59
+ }
60
+ /**
61
  * Add new cache entry
1
62
  *
2
63
  * @param {string} cacheKey
3
64
  * @param {Array<string>} propertyPaths
4
65
  * @return {Accessor<T>}
5
66
  */
67
+ _createClass(AccessorCache, [{
68
+ key: "get",
69
+ value:
70
+ /**
6
71
  * Gets state slice from the cache matching the `propertyPaths`.\
7
72
  * If not found, creates a new entry for the client from source, and returns it.
8
73
  *
9
74
  * @param {string} clientId
10
75
  * @param {...string} propertyPaths
11
76
  * @return {Readonly<PartialState<T>>}
12
77
  */
78
+ function get(clientId) {
79
+ for (var _len = arguments.length, propertyPaths = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
80
+ propertyPaths[_key - 1] = arguments[_key];
81
+ }
82
+ if ((0, _lodash2["default"])(propertyPaths)) {
83
+ propertyPaths = [_constants.DEFAULT_STATE_PATH];
84
+ }
85
+ var cacheKey = JSON.stringify(propertyPaths);
86
+ var accessor = cacheKey in _classPrivateFieldGet(this, _accessors) ? _classPrivateFieldGet(this, _accessors)[cacheKey] : _classPrivateMethodGet(this, _createAccessor, _createAccessor2).call(this, cacheKey, propertyPaths);
87
+ !accessor.hasClient(clientId) && accessor.addClient(clientId);
88
+ return accessor.refreshValue(_classPrivateFieldGet(this, _atoms));
89
+ }
90
+ /**
13
91
  * Unlinks a consumer from the cache: performing synchronized state cleanup
14
92
  *
15
93
  * @param {string} clientId
16
94
  */
95
+ }, {
96
+ key: "unlinkClient",
97
+ value: function unlinkClient(clientId) {
98
+ var accessors = _classPrivateFieldGet(this, _accessors);
99
+ var atoms = _classPrivateFieldGet(this, _atoms);
100
+ for (var k in accessors) {
101
+ var accessor = accessors[k];
102
+ if (!accessor.removeClient(clientId) || accessor.numClients) {
103
+ continue;
104
+ }
105
+ var _iterator = _createForOfIteratorHelper(accessor.paths),
106
+ _step;
107
+ try {
108
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
109
+ var p = _step.value;
110
+ if (p in atoms && atoms[p].disconnect(accessor.id) < 1) {
111
+ delete atoms[p];
112
+ }
113
+ }
114
+ } catch (err) {
115
+ _iterator.e(err);
116
+ } finally {
117
+ _iterator.f();
118
+ }
119
+ delete accessors[k];
120
+ }
121
+ }
122
+ /** Observes the origin state bearing ObservableContext store for state changes to update accessors. */
123
+ }, {
124
+ key: "watchSource",
125
+ value: function watchSource() {
126
+ var accessors = _classPrivateFieldGet(this, _accessors);
127
+ var atoms = _classPrivateFieldGet(this, _atoms);
128
+ var state = _classPrivateFieldGet(this, _origin);
129
+ var updatedPaths = {};
130
+ for (var path in atoms) {
131
+ var newAtomVal = (0, _lodash["default"])(state, path);
132
+ if ((0, _lodash3["default"])(newAtomVal, atoms[path].value)) {
133
+ continue;
134
+ }
135
+ atoms[path].setValue(newAtomVal);
136
+ updatedPaths[path] = true;
137
+ }
138
+ if ((0, _lodash2["default"])(updatedPaths)) {
139
+ for (var k in accessors) {
140
+ if (accessors[k].paths[0] === _constants.DEFAULT_STATE_PATH) {
141
+ accessors[k].refreshDue = true;
142
+ }
143
+ }
144
+ return;
145
+ }
146
+ for (var _k in accessors) {
147
+ if (accessors[_k].refreshDue) {
148
+ continue;
149
+ }
150
+ var accessorPaths = accessors[_k].paths;
151
+ accessors[_k].refreshDue = accessorPaths[0] === _constants.DEFAULT_STATE_PATH || accessorPaths.some(function (p) {
152
+ return p in updatedPaths;
153
+ });
154
+ }
155
+ }
156
+ }]);
157
+ return AccessorCache;
158
+ }();
159
+ function _createAccessor2(cacheKey, propertyPaths) {
160
+ var atoms = _classPrivateFieldGet(this, _atoms);
161
+ var accessor = new _accessor["default"](_classPrivateFieldGet(this, _origin), propertyPaths);
162
+ _classPrivateFieldGet(this, _accessors)[cacheKey] = accessor;
163
+ var _iterator2 = _createForOfIteratorHelper(accessor.paths),
164
+ _step2;
165
+ try {
166
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
167
+ var path = _step2.value;
168
+ if (path in atoms) {
169
+ continue;
170
+ }
171
+ atoms[path] = new _atom["default"]();
172
+ atoms[path].setValue((0, _lodash["default"])(_classPrivateFieldGet(this, _origin), path));
173
+ }
174
+ } catch (err) {
175
+ _iterator2.e(err);
176
+ } finally {
177
+ _iterator2.f();
178
+ }
179
+ return _classPrivateFieldGet(this, _accessors)[cacheKey];
180
+ }
181
+ var _default = AccessorCache;
182
+ exports["default"] = _default;