@dr.pogodin/react-global-state 0.24.0 → 0.25.0

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.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # MIT License
2
2
 
3
- _Copyright © 2019–2025, Dr. Sergey Pogodin_
3
+ _Copyright © 2019–2026, Dr. Sergey Pogodin_
4
4
  &mdash; <doc@pogodin.studio> (https://dr.pogodin.studio)
5
5
 
6
6
  Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -1,41 +1,33 @@
1
- function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }
2
- function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
3
- function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
4
- function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
5
- function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
6
1
  import { get, set, toPath } from 'lodash-es';
7
2
  import { cloneDeepForLog, isDebugMode } from "./utils.js";
8
3
  const ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';
9
- var _asyncDataAbortCallbacks = /*#__PURE__*/new WeakMap();
10
- var _dependencies = /*#__PURE__*/new WeakMap();
11
- var _initialState = /*#__PURE__*/new WeakMap();
12
- var _watchers = /*#__PURE__*/new WeakMap();
13
- var _nextNotifierId = /*#__PURE__*/new WeakMap();
14
- var _currentState = /*#__PURE__*/new WeakMap();
15
4
  export default class GlobalState {
5
+ ssrContext;
6
+ #asyncDataAbortCallbacks = new Map();
7
+ #dependencies = new Map();
8
+ #initialState;
9
+
10
+ // TODO: It is tempting to replace watchers here by
11
+ // Emitter from @dr.pogodin/js-utils, but we need to clone
12
+ // current watchers for emitting later, and this is not something
13
+ // Emitter supports right now.
14
+ #watchers = [];
15
+ #nextNotifierId;
16
+ #currentState;
17
+
16
18
  /**
17
19
  * Creates a new global state object.
18
20
  * @param initialState Intial global state content.
19
21
  * @param ssrContext Server-side rendering context.
20
22
  */
21
23
  constructor(initialState, ssrContext) {
22
- _classPrivateFieldInitSpec(this, _asyncDataAbortCallbacks, new Map());
23
- _classPrivateFieldInitSpec(this, _dependencies, new Map());
24
- _classPrivateFieldInitSpec(this, _initialState, void 0);
25
- // TODO: It is tempting to replace watchers here by
26
- // Emitter from @dr.pogodin/js-utils, but we need to clone
27
- // current watchers for emitting later, and this is not something
28
- // Emitter supports right now.
29
- _classPrivateFieldInitSpec(this, _watchers, []);
30
- _classPrivateFieldInitSpec(this, _nextNotifierId, void 0);
31
- _classPrivateFieldInitSpec(this, _currentState, void 0);
32
- _classPrivateFieldSet(_currentState, this, initialState);
33
- _classPrivateFieldSet(_initialState, this, initialState);
24
+ this.#currentState = initialState;
25
+ this.#initialState = initialState;
34
26
  if (ssrContext) {
35
27
  /* eslint-disable no-param-reassign */
36
28
  ssrContext.dirty = false;
37
29
  ssrContext.pending = [];
38
- ssrContext.state = _classPrivateFieldGet(_currentState, this);
30
+ ssrContext.state = this.#currentState;
39
31
  /* eslint-enable no-param-reassign */
40
32
 
41
33
  this.ssrContext = ssrContext;
@@ -56,7 +48,7 @@ export default class GlobalState {
56
48
  * just for the sake of testing the library.
57
49
  */
58
50
  get numAsyncDataAbortCallbacks() {
59
- return _classPrivateFieldGet(_asyncDataAbortCallbacks, this).size;
51
+ return this.#asyncDataAbortCallbacks.size;
60
52
  }
61
53
 
62
54
  /**
@@ -65,16 +57,15 @@ export default class GlobalState {
65
57
  * it drops the callback.
66
58
  */
67
59
  asyncDataLoadDone(opid, aborted) {
68
- var _classPrivateFieldGet2;
69
- if (aborted) (_classPrivateFieldGet2 = _classPrivateFieldGet(_asyncDataAbortCallbacks, this).get(opid)) === null || _classPrivateFieldGet2 === void 0 || _classPrivateFieldGet2();
70
- _classPrivateFieldGet(_asyncDataAbortCallbacks, this).delete(opid);
60
+ if (aborted) this.#asyncDataAbortCallbacks.get(opid)?.();
61
+ this.#asyncDataAbortCallbacks.delete(opid);
71
62
  }
72
63
 
73
64
  /**
74
65
  * Drops the record of dependencies, if any, for the given path.
75
66
  */
76
67
  dropDependencies(path) {
77
- _classPrivateFieldGet(_dependencies, this).delete(path);
68
+ this.#dependencies.delete(path);
78
69
  }
79
70
 
80
71
  /**
@@ -89,12 +80,12 @@ export default class GlobalState {
89
80
  * level in the logic?
90
81
  */
91
82
  hasChangedDependencies(path, deps) {
92
- const prevDeps = _classPrivateFieldGet(_dependencies, this).get(path);
93
- let changed = (prevDeps === null || prevDeps === void 0 ? void 0 : prevDeps.length) !== deps.length;
83
+ const prevDeps = this.#dependencies.get(path);
84
+ let changed = prevDeps?.length !== deps.length;
94
85
  for (let i = 0; !changed && i < deps.length; ++i) {
95
86
  changed = prevDeps[i] !== deps[i];
96
87
  }
97
- _classPrivateFieldGet(_dependencies, this).set(path, Object.freeze(deps));
88
+ this.#dependencies.set(path, Object.freeze(deps));
98
89
  return changed;
99
90
  }
100
91
 
@@ -104,11 +95,11 @@ export default class GlobalState {
104
95
  * @param opts.initialValue
105
96
  */
106
97
  getEntireState(opts) {
107
- let state = opts !== null && opts !== void 0 && opts.initialState ? _classPrivateFieldGet(_initialState, this) : _classPrivateFieldGet(_currentState, this);
108
- if (state !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined) return state;
98
+ let state = opts?.initialState ? this.#initialState : this.#currentState;
99
+ if (state !== undefined || opts?.initialValue === undefined) return state;
109
100
  const iv = opts.initialValue;
110
101
  state = typeof iv === 'function' ? iv() : iv;
111
- if (_classPrivateFieldGet(_currentState, this) === undefined) this.setEntireState(state);
102
+ if (this.#currentState === undefined) this.setEntireState(state);
112
103
  return state;
113
104
  }
114
105
 
@@ -120,20 +111,20 @@ export default class GlobalState {
120
111
  /* eslint-disable no-console */
121
112
  const p = typeof path === 'string' ? `"${path}"` : 'none (entire state update)';
122
113
  console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);
123
- console.log('New value:', cloneDeepForLog(value, path !== null && path !== void 0 ? path : ''));
124
- console.log('New state:', cloneDeepForLog(_classPrivateFieldGet(_currentState, this)));
114
+ console.log('New value:', cloneDeepForLog(value, path ?? ''));
115
+ console.log('New state:', cloneDeepForLog(this.#currentState));
125
116
  console.groupEnd();
126
117
  /* eslint-enable no-console */
127
118
  }
128
119
  if (this.ssrContext) {
129
120
  this.ssrContext.dirty = true;
130
- this.ssrContext.state = _classPrivateFieldGet(_currentState, this);
131
- } else if (!_classPrivateFieldGet(_nextNotifierId, this)) {
132
- _classPrivateFieldSet(_nextNotifierId, this, setTimeout(() => {
133
- _classPrivateFieldSet(_nextNotifierId, this, undefined);
134
- const watchers = [..._classPrivateFieldGet(_watchers, this)];
121
+ this.ssrContext.state = this.#currentState;
122
+ } else if (!this.#nextNotifierId) {
123
+ this.#nextNotifierId = setTimeout(() => {
124
+ this.#nextNotifierId = undefined;
125
+ const watchers = [...this.#watchers];
135
126
  for (const watcher of watchers) watcher();
136
- }));
127
+ });
137
128
  }
138
129
  }
139
130
 
@@ -142,7 +133,7 @@ export default class GlobalState {
142
133
  * the given operation ID. Throws if already registered.
143
134
  */
144
135
  setAsyncDataAbortCallback(opid, cb) {
145
- _classPrivateFieldGet(_asyncDataAbortCallbacks, this).set(opid, cb);
136
+ this.#asyncDataAbortCallbacks.set(opid, cb);
146
137
  }
147
138
 
148
139
  /**
@@ -150,8 +141,8 @@ export default class GlobalState {
150
141
  * @param value
151
142
  */
152
143
  setEntireState(value) {
153
- if (_classPrivateFieldGet(_currentState, this) !== value) {
154
- _classPrivateFieldSet(_currentState, this, value);
144
+ if (this.#currentState !== value) {
145
+ this.#currentState = value;
155
146
  this.notifyStateUpdate(null, value);
156
147
  }
157
148
  return value;
@@ -186,9 +177,9 @@ export default class GlobalState {
186
177
  const res = this.getEntireState(opts);
187
178
  return res;
188
179
  }
189
- const state = opts !== null && opts !== void 0 && opts.initialState ? _classPrivateFieldGet(_initialState, this) : _classPrivateFieldGet(_currentState, this);
180
+ const state = opts?.initialState ? this.#initialState : this.#currentState;
190
181
  let res = get(state, path);
191
- if (res !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined) return res;
182
+ if (res !== undefined || opts?.initialValue === undefined) return res;
192
183
  const iv = opts.initialValue;
193
184
  res = typeof iv === 'function' ? iv() : iv;
194
185
 
@@ -220,7 +211,7 @@ export default class GlobalState {
220
211
  // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
221
212
  if (value !== this.get(path)) {
222
213
  const root = {
223
- state: _classPrivateFieldGet(_currentState, this)
214
+ state: this.#currentState
224
215
  };
225
216
  let segIdx = 0;
226
217
 
@@ -248,7 +239,7 @@ export default class GlobalState {
248
239
  if (segIdx === pathSegments.length - 1) {
249
240
  pos[pathSegments[segIdx]] = value;
250
241
  }
251
- _classPrivateFieldSet(_currentState, this, root.state);
242
+ this.#currentState = root.state;
252
243
  this.notifyStateUpdate(path, value);
253
244
  }
254
245
  return value;
@@ -263,7 +254,7 @@ export default class GlobalState {
263
254
  */
264
255
  unWatch(callback) {
265
256
  if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
266
- const watchers = _classPrivateFieldGet(_watchers, this);
257
+ const watchers = this.#watchers;
267
258
  const pos = watchers.indexOf(callback);
268
259
  if (pos >= 0) {
269
260
  watchers[pos] = watchers[watchers.length - 1];
@@ -283,7 +274,7 @@ export default class GlobalState {
283
274
  */
284
275
  watch(callback) {
285
276
  if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
286
- const watchers = _classPrivateFieldGet(_watchers, this);
277
+ const watchers = this.#watchers;
287
278
  if (!watchers.includes(callback)) {
288
279
  watchers.push(callback);
289
280
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalState.js","names":[],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import { get, set, toPath } from 'lodash-es';\n\nimport type SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #asyncDataAbortCallbacks = new Map<string, () => void>();\n\n #dependencies = new Map<string, readonly unknown[]>();\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeepForLog(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Returns the number of currently registered async data abort callbacks,\n * just for the sake of testing the library.\n */\n get numAsyncDataAbortCallbacks(): number {\n return this.#asyncDataAbortCallbacks.size;\n }\n\n /**\n * If `aborted` is \"true\" and there is an abort callback registered for\n * the specified operation, it triggers the callback. Then, in any case,\n * it drops the callback.\n */\n asyncDataLoadDone(opid: string, aborted: boolean): void {\n if (aborted) this.#asyncDataAbortCallbacks.get(opid)?.();\n this.#asyncDataAbortCallbacks.delete(opid);\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string): void {\n this.#dependencies.delete(path);\n }\n\n /**\n * Checks if given `deps` are different from previously recorded ones for\n * the given `path`. If they are, `deps` are recorded as the new deps for\n * the `path`, and also the array is frozen, to prevent it from being\n * modified.\n *\n * TODO: This may not work as expected if path string is not normalized,\n * and the for the same path different alternative ways to spell it down\n * are used. We should normalize given path here, I guess, or on a higher\n * level in the logic?\n */\n hasChangedDependencies(path: string, deps: unknown[]): boolean {\n const prevDeps = this.#dependencies.get(path);\n let changed = prevDeps?.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies.set(path, Object.freeze(deps));\n return changed;\n }\n\n /**\n * Gets entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = typeof iv === 'function' ? (iv as () => StateT)() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeepForLog(value, path ?? ''));\n console.log('New state:', cloneDeepForLog(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = undefined;\n const watchers = [...this.#watchers];\n for (const watcher of watchers) watcher();\n });\n }\n }\n\n /**\n * Registers an abort callback for an async data retrieval operation with\n * the given operation ID. Throws if already registered.\n */\n setAsyncDataAbortCallback(opid: string, cb: () => void): void {\n this.#asyncDataAbortCallbacks.set(opid, cb);\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | LockT = LockT, ValueT = void>(\n path?: null | string,\n opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,\n ): TypeLock<Forced, void, ValueT>;\n\n get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {\n if (typeof path !== 'string') {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path) as ValueT;\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = typeof iv === 'function' ? (iv as () => ValueT)() : iv;\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (!opts.initialState || (this.get(path) as unknown) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | LockT = LockT, ValueT = never>(\n path: null | string | undefined,\n value: TypeLock<Forced, never, ValueT>,\n ): TypeLock<Forced, void, ValueT>;\n\n set(path: null | string | undefined, value: unknown): unknown {\n if (typeof path !== 'string') return this.setEntireState(value as StateT);\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n\n // TODO: It is not 100% correct, as `pos` can be an array, or any other\n // value as we travel through the state tree. To simplify the typing for\n // now, I guess, we can go with this record type, though.\n let pos: Record<string, unknown> = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx]!;\n\n // TODO: Revise: Typing is not quite correct here, but it works fine in the runtime.\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...(next as unknown[])];\n else if (typeof next === 'object') pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg] as Record<string, unknown>;\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]!] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT): void {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1]!;\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT): void {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (!watchers.includes(callback)) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":"AAAA,SAAS,GAAG,EAAE,GAAG,EAAE,MAAM,QAAQ,WAAW;AAAC,SAW3C,eAAe,EACf,WAAW;AAGb,MAAM,gBAAgB,GAAG,gDAAgD;AAOzE,eAAe,MAAM,WAAW,CAG9B;EACS,UAAU;EAEnB,CAAC,uBAAuB,GAAG,IAAI,GAAG,CAAqB,CAAC;EAExD,CAAC,YAAY,GAAG,IAAI,GAAG,CAA6B,CAAC;EAErD,CAAC,YAAY;;EAEb;EACA;EACA;EACA;EACA,CAAC,QAAQ,GAAgB,EAAE;EAE3B,CAAC,cAAc;EAEf,CAAC,YAAY;;EAEb;AACF;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AChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACE,KAAK,CAAC,QAAmB,EAAQ;IAC/B,IAAI,IAAI,CAAC,UAAU,EAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC;IAEtD,MAAM,QAAQ,GAAG,IAAI,CAAC,CAAC,QAAQ;IAC/B,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;MAChC,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC;IACzB;EACF;AACF","ignoreList":[]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["state"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import {\n type ReactNode,\n createContext,\n use,\n useState,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nimport type { ValueOrInitializerT } from './utils';\n\nconst Context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Returns the GlobalState object from the context. In most cases you should use\n * other hooks, like useGlobalState(), etc. to interact with the global state,\n * instead of accessing the GlobalState object directly.\n */\nexport function useGlobalStateObject<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n const globalState = use(Context);\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * Returns SSR context.\n * @param throwWithoutSsrContext - If _true_ (default), this hook will throw\n * if no SSR context is attached to the global state; set _false_ to not throw\n * in such case. In either case this hook will throw if the <GlobalStateProvider>\n * (hence the global state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent <GlobalStateProvider> in the rendered\n * React tree.\n * - If `throwWithoutSsrContext` is _true_ (default), and there is no SSR\n * context attached to the global state provided by <GlobalStateProvider>.\n */\nexport function useSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = useGlobalStateObject<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>;\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = (NewStateProps<StateT, SsrContextT> | {\n stateProxy: GlobalState<StateT, SsrContextT> | true;\n}) & {\n children?: ReactNode;\n};\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n): ReactNode => {\n type GST = GlobalState<StateT, SsrContextT>;\n\n const [localState, setLocalState] = useState<GST>();\n\n let state: GST;\n\n // Below we cast `rest.stateProxy` as \"boolean\" for safe backward\n // compatibility with plain JavaScript (as TypeScript typings only\n // permit \"true\" or GlobalState value; while legacy codebase may\n // pass in a boolean value here, occasionally equal \"false\").\n if ('stateProxy' in rest && (rest.stateProxy as boolean)) {\n if (localState) setLocalState(undefined);\n\n if (rest.stateProxy === true) {\n const gs = use(Context);\n if (!gs) throw Error('Missing GlobalStateProvider');\n state = gs as GlobalState<StateT, SsrContextT>;\n } else state = rest.stateProxy;\n } else if (localState) {\n state = localState;\n } else {\n const {\n initialState,\n ssrContext,\n } = rest as NewStateProps<StateT, SsrContextT>;\n\n state = new GlobalState(\n typeof initialState === 'function' ? (initialState as () => StateT)() : initialState,\n ssrContext,\n );\n\n setLocalState(state);\n }\n\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":";AAAA,SAEE,aAAa,EACb,GAAG,EACH,QAAQ,QACH,OAAO;AAAC,OAER,WAAW;AAAA;AAKlB,MAAM,OAAO,gBAAG,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,oBAAoB,GAGE;EACpC,MAAM,WAAW,GAAG,GAAG,CAAC,OAAO,CAAC;EAChC,IAAI,CAAC,WAAW,EAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAO,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO;EAGL,iCAA6B,KAA7B,SAA6B,GAA7B,IAA6B,GAA7B,EAA6B;EAE7B;IAAA;EAAA,IAAuB,oBAAoB,CAAoC,CAAC;EAChF,IAAI,CAAC,UAAoC,IAArC,sBAAqC;IACvC,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC;EAAC;EACzC,OACM,UAAU;AAAA;AAiBnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,mBAAmB,GAAG;EAAA;EAI1B;IAAA;IAAA;EAAA,MAAoE;EAIpE,oCAAoC,QAAQ,CAAM,CAAC;EAE/CA,GAAA;EAMJ,IAAI,YAAY,IAAI,IAAoC,IAA3B,IAAI,WAAuB;IACtD,IAAI,UAAU;MAAE,aAAa,CAAC,SAAS,CAAC;IAAA;IAExC,IAAI,IAAI,WAAW,KAAK,IAAI;MAC1B,WAAW,GAAG,CAAC,OAAO,CAAC;MACvB,IAAI,CAAC,EAAE;QAAE,MAAM,KAAK,CAAC,6BAA6B,CAAC;MAAC;MACpD,MAAAA,CAAA,CAAQ,EAAE;IAAL;MACA,MAAAA,CAAA,CAAQ,IAAI,WAAW;IAAlB;EAAmB;IAC1B,IAAI,UAAU;MACnB,MAAAA,CAAA,CAAQ,UAAU;IAAb;MAEL;QAAA;QAAA;MAAA,IAGI,IAAI;MAER,MAAAA,CAAA,CAAQA,GAAA,CAAI,WAAW,CACrB,OAAO,YAAY,KAAK,UAA4D,GAA9C,YAAY,CAAiC,CAAC,GAApF,YAAoF,EACpF,UACF,CAAC;MAED,aAAa,CAAC,KAAK,CAAC;IAAA;EACrB;EAAA;EAAA;IAEM,uBAAC,OAAO;MAAQA,KAAK,EAAL,KAAK;MAAA,UAAG;IAAQ,CAAU,CAAC;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA,OAA3C,EAA2C;AAAA,CACnD;AAED,eAAe,mBAAmB","ignoreList":[]}
@@ -0,0 +1,8 @@
1
+ export default class SsrContext {
2
+ dirty = false;
3
+ pending = [];
4
+ constructor(state) {
5
+ this.state = state;
6
+ }
7
+ }
8
+ //# sourceMappingURL=SsrContext.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SsrContext.js","names":[],"sources":["../../src/SsrContext.ts"],"sourcesContent":["export default class SsrContext<StateT> {\n dirty: boolean = false;\n\n pending: Array<Promise<void>> = [];\n\n constructor(public state?: StateT) { }\n}\n"],"mappings":"AAAA,eAAe,MAAM,UAAU,CAAS;EACtC,KAAK,GAAY,KAAK;EAEtB,OAAO,GAAyB,EAAE;EAElC,WAAW,CAAQ,KAAc,EAAE;IAAA,KAAhB,KAAc,GAAd,KAAc;EAAI;AACvC","ignoreList":[]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n useGlobalStateObject,\n useSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type LoadAsyncDataI,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type {\n AsyncCollectionLoaderT,\n AsyncCollectionReloaderT,\n AsyncCollectionT,\n} from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateI,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n useGlobalStateObject,\n useSsrContext,\n};\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n GlobalState: typeof GlobalState<StateT, SsrContextT>;\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;\n SsrContext: typeof SsrContext<StateT>;\n loadAsyncData: LoadAsyncDataI<StateT>;\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope;\n useAsyncCollection: UseAsyncCollectionI<StateT>;\n useAsyncData: UseAsyncDataI<StateT>;\n useGlobalState: UseGlobalStateI<StateT>;\n useGlobalStateObject: typeof useGlobalStateObject<StateT, SsrContextT>;\n useSsrContext: typeof useSsrContext<SsrContextT>;\n}\n\nconst api = {\n // TODO: I am puzzled, why ESLint eforces this sorting order as alphabetical?\n // Perhaps, we should tune something in its config settings, as it seems to mix\n // some extra sorting logic, which I am not sure I like.\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n useGlobalStateObject,\n useSsrContext,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): API<StateT, SsrContextT> {\n return api;\n}\n"],"mappings":"OAAO,WAAW;AAAA,OAEX,mBAAmB,IACxB,oBAAoB,EACpB,aAAa;AAAA,OAGR,UAAU;AAAA,OAEV,kBAAkB;AAAA,SAavB,aAAa,EACb,oBAAoB,EACpB,YAAY;AAAA,OAGP,cAAc;AAYrB,SAIE,WAAW,EACX,mBAAmB,EACnB,UAAU,EAOV,aAAa,EACb,oBAAoB,EACpB,kBAAkB,EAClB,YAAY,EACZ,cAAc,EACd,oBAAoB,EACpB,aAAa;;AAGf;;AAiBA,MAAM,GAAG,GAAG;EACV;EACA;EACA;EACA,WAAW;EACX,mBAAmB;EACnB,UAAU;EACV,aAAa;EACb,oBAAoB;EACpB,kBAAkB;EAClB,YAAY;EACZ,cAAc;EACd,oBAAoB;EACpB;AACF,CAAC;AAED,OAAO,SAAS,mBAAmB,GAGL;EAC5B,OAAO,GAAG;AACZ","ignoreList":[]}
@@ -91,11 +91,10 @@ function normalizeIds(idOrIds) {
91
91
  // and reused in both hooks.
92
92
  // eslint-disable-next-line complexity
93
93
  function useAsyncCollection(idOrIds, path, loader, options = {}) {
94
- var _options$maxage, _options$refreshAge, _options$garbageColle, _ref$current;
95
94
  const ids = normalizeIds(idOrIds);
96
- const maxage = (_options$maxage = options.maxage) !== null && _options$maxage !== void 0 ? _options$maxage : DEFAULT_MAXAGE;
97
- const refreshAge = (_options$refreshAge = options.refreshAge) !== null && _options$refreshAge !== void 0 ? _options$refreshAge : maxage;
98
- const garbageCollectAge = (_options$garbageColle = options.garbageCollectAge) !== null && _options$garbageColle !== void 0 ? _options$garbageColle : maxage;
95
+ const maxage = options.maxage ?? DEFAULT_MAXAGE;
96
+ const refreshAge = options.refreshAge ?? maxage;
97
+ const garbageCollectAge = options.garbageCollectAge ?? maxage;
99
98
  const globalState = useGlobalStateObject();
100
99
 
101
100
  // Server-side logic.
@@ -147,14 +146,12 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
147
146
  if (!disabled) {
148
147
  void (async () => {
149
148
  for (const id_0 of ids) {
150
- var _state2$timestamp;
151
149
  const itemPath_0 = path ? `${path}.${id_0}` : `${id_0}`;
152
150
  const state2 = globalState.get(itemPath_0);
153
151
  const {
154
152
  deps
155
153
  } = options;
156
- if (deps && globalState.hasChangedDependencies(itemPath_0, deps) || refreshAge < Date.now() - ((_state2$timestamp = state2 === null || state2 === void 0 ? void 0 : state2.timestamp) !== null && _state2$timestamp !== void 0 ? _state2$timestamp : 0) && (!(state2 !== null && state2 !== void 0 && state2.operationId) || state2.operationId.startsWith('S'))) {
157
- var _state2$data, _state2$timestamp2;
154
+ if (deps && globalState.hasChangedDependencies(itemPath_0, deps) || refreshAge < Date.now() - (state2?.timestamp ?? 0) && (!state2?.operationId || state2.operationId.startsWith('S'))) {
158
155
  if (!deps) globalState.dropDependencies(itemPath_0);
159
156
  await loadAsyncData(itemPath_0,
160
157
  // TODO: I guess, the loader is not correctly typed here -
@@ -162,8 +159,8 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
162
159
  // should be kept synchronous to not alter the sync logic.
163
160
  // eslint-disable-next-line @typescript-eslint/promise-function-async
164
161
  (old, ...args_0) => loader(id_0, old, ...args_0), globalState, {
165
- data: (_state2$data = state2 === null || state2 === void 0 ? void 0 : state2.data) !== null && _state2$data !== void 0 ? _state2$data : null,
166
- timestamp: (_state2$timestamp2 = state2 === null || state2 === void 0 ? void 0 : state2.timestamp) !== null && _state2$timestamp2 !== void 0 ? _state2$timestamp2 : 0
162
+ data: state2?.data ?? null,
163
+ timestamp: state2?.timestamp ?? 0
167
164
  });
168
165
  }
169
166
  }
@@ -172,7 +169,7 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
172
169
  });
173
170
  const [localState] = useGlobalState(path, {});
174
171
  const ref = useRef(null);
175
- (_ref$current = ref.current) !== null && _ref$current !== void 0 ? _ref$current : ref.current = {
172
+ ref.current ??= {
176
173
  globalState,
177
174
  ids,
178
175
  loader,
@@ -190,7 +187,7 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
190
187
  const reload = async customLoader => {
191
188
  const rc = ref.current;
192
189
  if (!rc) throw Error('Internal error');
193
- const localLoader = customLoader !== null && customLoader !== void 0 ? customLoader : rc.loader;
190
+ const localLoader = customLoader ?? rc.loader;
194
191
 
195
192
  // TODO: Revise - not sure all related typing is 100% correct,
196
193
  // thus let's keep this runtime assertion.
@@ -252,13 +249,12 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
252
249
  };
253
250
  });
254
251
  if (!Array.isArray(idOrIds)) {
255
- var _e_0$timestamp, _e_0$data;
256
252
  // TODO: Revise related typings!
257
253
  const e_0 = localState[idOrIds];
258
- const timestamp = (_e_0$timestamp = e_0 === null || e_0 === void 0 ? void 0 : e_0.timestamp) !== null && _e_0$timestamp !== void 0 ? _e_0$timestamp : 0;
254
+ const timestamp = e_0?.timestamp ?? 0;
259
255
  return {
260
- data: stale[idOrIds] ? null : (_e_0$data = e_0 === null || e_0 === void 0 ? void 0 : e_0.data) !== null && _e_0$data !== void 0 ? _e_0$data : null,
261
- loading: !!(e_0 !== null && e_0 !== void 0 && e_0.operationId),
256
+ data: stale[idOrIds] ? null : e_0?.data ?? null,
257
+ loading: !!e_0?.operationId,
262
258
  reload: stable.reloadSingle,
263
259
  set: stable.setSingle,
264
260
  timestamp
@@ -271,17 +267,16 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
271
267
  timestamp: Number.MAX_VALUE
272
268
  };
273
269
  for (const id_4 of ids) {
274
- var _e_1$timestamp, _e_1$data;
275
270
  // TODO: Revise related typing. Should `localState` have a more specific type?
276
271
  const e_1 = localState[id_4];
277
- const loading = !!(e_1 !== null && e_1 !== void 0 && e_1.operationId);
278
- const timestamp_0 = (_e_1$timestamp = e_1 === null || e_1 === void 0 ? void 0 : e_1.timestamp) !== null && _e_1$timestamp !== void 0 ? _e_1$timestamp : 0;
272
+ const loading = !!e_1?.operationId;
273
+ const timestamp_0 = e_1?.timestamp ?? 0;
279
274
  res.items[id_4] = {
280
- data: stale[id_4] ? null : (_e_1$data = e_1 === null || e_1 === void 0 ? void 0 : e_1.data) !== null && _e_1$data !== void 0 ? _e_1$data : null,
275
+ data: stale[id_4] ? null : e_1?.data ?? null,
281
276
  loading,
282
277
  timestamp: timestamp_0
283
278
  };
284
- res.loading || (res.loading = loading);
279
+ res.loading ||= loading;
285
280
  if (res.timestamp > timestamp_0) res.timestamp = timestamp_0;
286
281
  }
287
282
  return res;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncCollection.js","names":["id","itemPath","args","promiseOrVoid","customLoader","e","timestamp"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef, useState } from 'react';\n\nimport type GlobalState from './GlobalState';\nimport { useGlobalStateObject } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n DEFAULT_MAXAGE,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n loadAsyncData,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n areEqual,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = Partial<Record<IdT, AsyncDataEnvelopeT<DataT>>>;\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (id: IdT, oldData: DataT | null, meta: {\n abortSignal: AbortSignal;\n oldDataTimestamp: number;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void> | void;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: Record<IdT, CollectionItemT<DataT>>;\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype CurrentT<DataT, IdT extends number | string> = {\n globalState: GlobalState<unknown>;\n ids: IdT[];\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n path: null | string | undefined;\n};\n\ntype StableT<DataT, IdT extends number | string> = {\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n setSingle: (data: DataT | null) => void;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (const id of ids) {\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (const id of ids) {\n res.add(id.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (const [id, envelope] of entries) {\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n // Removes ID duplicates.\n const res = Array.from(new Set(idOrIds));\n\n // Ensures stable ID order.\n res.sort((a, b) => a.toString().localeCompare(b.toString()));\n\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT> | UseAsyncDataResT<DataT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\n// eslint-disable-next-line complexity\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncCollectionResT<DataT, IdT> | UseAsyncDataResT<DataT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = useGlobalStateObject();\n\n // Server-side logic.\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR) {\n const operationId: OperationIdT = `S${globalThis.crypto.randomUUID()}`;\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(\n itemPath,\n {\n initialValue: newAsyncDataEnvelope<DataT>(),\n },\n );\n if (!state.timestamp && !state.operationId) {\n const promiseOrVoid = loadAsyncData<ForceT, DataT>(\n itemPath,\n (...args):\n DataT | Promise<DataT | null> | null => loader(id, ...args),\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n operationId,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n }\n }\n\n const { disabled } = options;\n\n // Reference-counting & garbage collection.\n\n const idsString = JSON.stringify(ids);\n\n useEffect(() => {\n const localIds = JSON.parse(idsString) as IdT[];\n\n if (!disabled) gcOnWithhold(localIds, path, globalState);\n return () => {\n if (!disabled) {\n gcOnRelease(localIds, path, globalState, garbageCollectAge);\n }\n };\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n }, [\n disabled,\n garbageCollectAge,\n globalState,\n idsString,\n path,\n ]);\n\n // NOTE: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => {\n if (!disabled) {\n void (async () => {\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n await loadAsyncData<ForceT, DataT>(\n itemPath,\n // TODO: I guess, the loader is not correctly typed here -\n // it can be synchronous, and in that case the following method\n // should be kept synchronous to not alter the sync logic.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (old, ...args) => loader(id, old, ...args),\n globalState,\n {\n data: state2?.data ?? null,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n }\n });\n\n const [localState] = useGlobalState<\n ForceT, Record<string, AsyncDataEnvelopeT<DataT>>\n >(path, {});\n\n const ref = useRef<CurrentT<DataT, IdT>>(null);\n\n ref.current ??= {\n globalState,\n ids,\n loader,\n path,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n ids,\n loader,\n path,\n };\n }, [globalState, ids, loader, path]);\n\n const [stable] = useState<StableT<DataT, IdT>>(() => {\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const localLoader = customLoader ?? rc.loader;\n\n // TODO: Revise - not sure all related typing is 100% correct,\n // thus let's keep this runtime assertion.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!localLoader || !rc.globalState || !rc.ids) {\n throw Error('Internal error');\n }\n\n for (const id of rc.ids) {\n const itemPath = rc.path ? `${rc.path}.${id}` : `${id}`;\n\n const promiseOrVoid = loadAsyncData<ForceT, DataT>(\n itemPath,\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n rc.globalState,\n );\n\n if (promiseOrVoid instanceof Promise) await promiseOrVoid;\n }\n };\n\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const reloadSingle: AsyncDataReloaderT<DataT> = (customLoader) => reload(\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n customLoader && ((id, ...args) => customLoader(...args)),\n );\n\n const setSingle = (data: DataT | null) => {\n void reload(() => data);\n };\n\n return { reload, reloadSingle, setSingle };\n });\n\n const [stale, setStale] = useState({} as Record<IdT, boolean>);\n\n // TODO: Merge into the data-reloading effect above?\n useEffect(() => {\n const now = Date.now();\n const nowStale = {} as Record<IdT, boolean>;\n for (const [key, e] of Object.entries(localState)) {\n nowStale[key as IdT] = maxage < now - e.timestamp;\n }\n\n const id = areEqual(stale, nowStale) ? null : requestAnimationFrame(() => {\n setStale(nowStale);\n });\n\n return () => {\n if (id !== null) cancelAnimationFrame(id);\n };\n });\n\n if (!Array.isArray(idOrIds)) {\n // TODO: Revise related typings!\n const e = localState[idOrIds as string];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: stale[idOrIds] ? null : e?.data ?? null,\n loading: !!e?.operationId,\n reload: stable.reloadSingle,\n set: stable.setSingle,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: stable.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (const id of ids) {\n // TODO: Revise related typing. Should `localState` have a more specific type?\n const e = localState[id as string];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: stale[id] ? null : e?.data ?? null,\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>\n | UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAAS,SAAS,EAAE,MAAM,EAAE,QAAQ,QAAQ,OAAO;AAAC,SAG3C,oBAAoB;AAAA,SAK3B,cAAc,EAKd,aAAa,EACb,oBAAoB;AAAA,OAGf,cAAc;AAAA,SAMnB,QAAQ,EACR,WAAW;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,SAAS,IAAI,CAAC;IACnC,OAAO;MACL,IAAI,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,IAAI,GAAGA,GAAC,EAAE,IAAI,IAAI,IAAI;MAC7C,OAAO,EAAE,CAAC,CAACA,GAAC,EAAE,WAAW;MACzB,MAAM,EAAE,MAAM,CAAC,YAAY;MAC3B,GAAG,EAAE,MAAM,CAAC,SAAS;MACrB;IACF,CAAC;EACH;EAEA,MAAM,GAAuC,GAAG;IAC9C,KAAK,EAAE,CAAC,CAAwC;IAChD,OAAO,EAAE,KAAK;IACd,MAAM,EAAE,MAAM,CAAC,MAAM;IACrB,SAAS,EAAE,MAAM,CAAC;EACpB,CAAC;EAED,KAAK,MAAML,IAAE,IAAI,GAAG,EAAE;IACpB;IACA,MAAMK,GAAC,GAAG,UAAU,CAACL,IAAE,CAAW;IAClC,MAAM,OAAO,GAAG,CAAC,CAACK,GAAC,EAAE,WAAW;IAChC,MAAMC,WAAS,GAAGD,GAAC,EAAE,SAAS,IAAI,CAAC;IAEnC,GAAG,CAAC,KAAK,CAACL,IAAE,CAAC,GAAG;MACd,IAAI,EAAE,KAAK,CAACA,IAAE,CAAC,GAAG,IAAI,GAAGK,GAAC,EAAE,IAAI,IAAI,IAAI;MACxC,OAAO;MACP,SAAS,EAATC;IACF,CAAC;IACD,GAAG,CAAC,OAAO,KAAK,OAAO;IACvB,IAAI,GAAG,CAAC,SAAS,GAAGA,WAAS,EAAE,GAAG,CAAC,SAAS,GAAGA,WAAS;EAC1D;EAEA,OAAO,GAAG;AACZ;AAEA,eAAe,kBAAkB;;AAEjC","ignoreList":[]}
@@ -36,8 +36,8 @@ export function newAsyncDataEnvelope(initialData = null, {
36
36
  function setState(data, path, gs, prevState = gs.get(path)) {
37
37
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
38
38
  /* eslint-disable no-console */
39
- console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path !== null && path !== void 0 ? path : ''}"`);
40
- console.log('Data:', cloneDeepForLog(data, path !== null && path !== void 0 ? path : ''));
39
+ console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path ?? ''}"`);
40
+ console.log('Data:', cloneDeepForLog(data, path ?? ''));
41
41
  /* eslint-enable no-console */
42
42
  }
43
43
  gs.set(path, {
@@ -62,7 +62,7 @@ function finalizeLoad(data, path, gs, operationId) {
62
62
  // set up, thus it should be cleaned out here.
63
63
  gs.asyncDataLoadDone(operationId, false);
64
64
  const state = gs.get(path);
65
- if (operationId === (state === null || state === void 0 ? void 0 : state.operationId)) setState(data, path, gs, state);
65
+ if (operationId === state?.operationId) setState(data, path, gs, state);
66
66
  }
67
67
  /**
68
68
  * Executes the data loading operation.
@@ -86,7 +86,7 @@ export function loadAsyncData(path, loader, globalState, old,
86
86
  operationId = `C${globalThis.crypto.randomUUID()}`) {
87
87
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
88
88
  /* eslint-disable no-console */
89
- console.log(`ReactGlobalState: async data (re-)loading. Path: "${path !== null && path !== void 0 ? path : ''}"`);
89
+ console.log(`ReactGlobalState: async data (re-)loading. Path: "${path ?? ''}"`);
90
90
  /* eslint-enable no-console */
91
91
  }
92
92
  const operationIdPath = path ? `${path}.operationId` : 'operationId';
@@ -135,7 +135,6 @@ operationId = `C${globalThis.crypto.randomUUID()}`) {
135
135
  // as it is done inside useAsyncCollection().
136
136
 
137
137
  function useAsyncData(path, loader, t0) {
138
- var _options$maxage, _options$refreshAge, _options$garbageColle;
139
138
  const $ = _c(38);
140
139
  let t1;
141
140
  if ($[0] !== t0) {
@@ -146,9 +145,9 @@ function useAsyncData(path, loader, t0) {
146
145
  t1 = $[1];
147
146
  }
148
147
  const options = t1;
149
- const maxage = (_options$maxage = options.maxage) !== null && _options$maxage !== void 0 ? _options$maxage : DEFAULT_MAXAGE;
150
- const refreshAge = (_options$refreshAge = options.refreshAge) !== null && _options$refreshAge !== void 0 ? _options$refreshAge : maxage;
151
- const garbageCollectAge = (_options$garbageColle = options.garbageCollectAge) !== null && _options$garbageColle !== void 0 ? _options$garbageColle : maxage;
148
+ const maxage = options.maxage ?? DEFAULT_MAXAGE;
149
+ const refreshAge = options.refreshAge ?? maxage;
150
+ const garbageCollectAge = options.garbageCollectAge ?? maxage;
152
151
  const globalState = useGlobalStateObject();
153
152
  const state = globalState.get(path, {
154
153
  initialValue: newAsyncDataEnvelope()
@@ -189,7 +188,7 @@ function useAsyncData(path, loader, t0) {
189
188
  if ($[10] === Symbol.for("react.memo_cache_sentinel")) {
190
189
  t4 = () => ({
191
190
  reload: customLoader => {
192
- const localLoader = customLoader !== null && customLoader !== void 0 ? customLoader : heap.loader;
191
+ const localLoader = customLoader ?? heap.loader;
193
192
  return loadAsyncData(heap.path, localLoader, heap.globalState);
194
193
  },
195
194
  set: data => {
@@ -229,9 +228,9 @@ function useAsyncData(path, loader, t0) {
229
228
  const state2 = globalState.get(path);
230
229
  if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
231
230
  if (process.env.NODE_ENV !== "production" && isDebugMode()) {
232
- console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path !== null && path !== void 0 ? path : ""}`);
231
+ console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path ?? ""}`);
233
232
  }
234
- globalState.dropDependencies(path !== null && path !== void 0 ? path : "");
233
+ globalState.dropDependencies(path ?? "");
235
234
  globalState.set(path, {
236
235
  ...state2,
237
236
  data: null,
@@ -264,9 +263,9 @@ function useAsyncData(path, loader, t0) {
264
263
  const {
265
264
  deps
266
265
  } = options;
267
- if (deps && globalState.hasChangedDependencies(path !== null && path !== void 0 ? path : "", deps) || refreshAge < Date.now() - state2_0.timestamp && (!state2_0.operationId || state2_0.operationId.startsWith("S"))) {
266
+ if (deps && globalState.hasChangedDependencies(path ?? "", deps) || refreshAge < Date.now() - state2_0.timestamp && (!state2_0.operationId || state2_0.operationId.startsWith("S"))) {
268
267
  if (!deps) {
269
- globalState.dropDependencies(path !== null && path !== void 0 ? path : "");
268
+ globalState.dropDependencies(path ?? "");
270
269
  }
271
270
  loadAsyncData(path, loader, globalState, {
272
271
  data: state2_0.data,
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncData.js","names":["state2"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef, useState } from 'react';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { useGlobalStateObject } from './GlobalStateProvider';\n\nimport type SsrContext from './SsrContext';\n\nimport useGlobalState from './useGlobalState';\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\n// NOTE: Here, and below it is important whether a loader and related\n// (re-)loading handlers return a promise or a value, as returning promises\n// mean the async mode, in which related global state values are updated\n// asynchronously (the new value comes into effect in a next rendering cycle),\n// while returning a non-promise value means a synchronous mode, in which\n// related global state values are updated immediately, within the current\n// rendering cycle.\n\nexport type AsyncDataLoaderT<DataT>\n = (oldData: DataT | null, meta: {\n abortSignal: AbortSignal;\n oldDataTimestamp: number;\n }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n = (loader?: AsyncDataLoaderT<DataT>) => Promise<void> | void;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: DataT | null;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n set: (data: DataT | null) => void;\n timestamp: number;\n};\n\n/**\n * Writes data into the global state, and prints console messages in the debug\n * mode.\n */\nfunction setState<\n DataT,\n EnvT extends AsyncDataEnvelopeT<DataT>,\n>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n prevState: EnvT = gs.get<ForceT, EnvT>(path),\n) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path ?? ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n\n gs.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...prevState,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n}\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n gs.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = gs.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) setState(data, path, gs, state);\n}\n\nexport function loadAsyncData<\n StateT,\n PathT extends null | string | undefined,\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<StateT, SsrContext<StateT>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n): Promise<void> | void;\n\nexport function loadAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n): Promise<void> | void;\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nexport function loadAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${globalThis.crypto.randomUUID()}`,\n): Promise<void> | void {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path ?? ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const controller = new AbortController();\n globalState.setAsyncDataAbortCallback(operationId, () => {\n controller.abort();\n });\n\n const dataOrPromise = loader(definedOld.data, {\n abortSignal: controller.signal,\n oldDataTimestamp: definedOld.timestamp,\n });\n\n if (dataOrPromise instanceof Promise) {\n return dataOrPromise.then((data) => {\n finalizeLoad(data, path, globalState, operationId);\n }).finally(() => {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n });\n }\n\n finalizeLoad(dataOrPromise, path, globalState, operationId);\n return undefined;\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\n// TODO: Perhaps split the heap management to a dedicated hook,\n// as it is done inside useAsyncCollection().\ntype HeapT<DataT> = {\n // NOTE: These heap fields are necessary to make reload() and set() stable\n // functions.\n globalState: GlobalState<unknown>;\n loader: AsyncDataLoaderT<DataT>;\n path: null | string | undefined;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = useGlobalStateObject();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({\n globalState,\n loader,\n path,\n });\n\n useEffect(() => {\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n });\n\n // NOTE: State inititalizer function here helps to avoid ESLint warnings\n // about accessing references during the render.\n const [stable] = useState(() => ({\n reload: (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): Promise<void> | void => {\n const localLoader = customLoader ?? heap.loader;\n\n return loadAsyncData<ForceT, DataT>(\n heap.path,\n localLoader,\n heap.globalState,\n );\n },\n set: (data: DataT | null) => {\n setState(data, heap.path, heap.globalState);\n },\n }));\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = loadAsyncData<ForceT, DataT>(\n path,\n loader,\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n `S${globalThis.crypto.randomUUID()}`,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n\n const { disabled } = options;\n\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => {\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path ?? ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path ?? '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n }, [disabled, garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path ?? '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n\n void loadAsyncData<ForceT, DataT>(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n const [stale, setStale] = useState<boolean>(\n () => maxage < Date.now() - localState.timestamp,\n );\n\n // TODO: Merge into the data-reloading effect above?\n useEffect(() => {\n const nowStale = maxage < Date.now() - localState.timestamp;\n const id = stale === nowStale ? null : requestAnimationFrame(() => {\n setStale(nowStale);\n });\n\n return () => {\n if (id !== null) cancelAnimationFrame(id);\n };\n });\n\n return {\n data: stale ? null : localState.data,\n loading: !!localState.operationId,\n reload: stable.reload,\n set: stable.set,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoadAsyncDataI<StateT> {\n <\n PathT extends null | string | undefined,\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n >(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<StateT, SsrContext<StateT>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n ): Promise<void> | void;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n ): Promise<void> | void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";AAAA;AACA;AACA;;AAEA,SAAS,SAAS,EAAE,MAAM,EAAE,QAAQ,QAAQ,OAAO;AAEnD,SAAS,MAAM,QAAQ,sBAAsB;AAAC,SAGrC,oBAAoB;AAAA,OAItB,cAAc;AAAA,SAMnB,eAAe,EACf,W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B,qBAAqB,cAAc,CACjC,IAAI,EACJ,EACF,CAAC;EAAC;EAAA;IAGA,WAAM,MAAM,GAAG,IAAI,IAAI,CAAC,CAAC,GAAG,UAAU,UAAU;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EADlD,0BAA0B,QAAQ,CAChC,EACF,CAAC;EAAC;EAAA;IAGQ;MACR,iBAAiB,MAAM,GAAG,IAAI,IAAI,CAAC,CAAC,GAAG,UAAU,UAAU;MAC3D,WAAW,KAAK,KAAK,QAEnB,GAFS,IAET,GAFqC,qBAAqB,CAAC;QAC3D,QAAQ,CAAC,QAAQ,CAAC;MAAA,CACnB,CAAC;MAAC,OAEI;QACL,IAAI,EAAE,KAAK,IAAI;UAAE,oBAAoB,CAAC,EAAE,CAAC;QAAA;MAAC,CAC3C;IAAA,CACF;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EATD,SAAS,CAAC,GAST,CAAC;EAGM,iBAAK,GAAL,IAA8B,GAAf,UAAU,KAAK;EAC3B,aAAC,CAAC,UAAU,YAAY;EAAA;EAAA;IAF5B;MAAA,MACC,GAA8B;MAAA,SAC3B,GAAwB;MAAA,QACzB,MAAM,OAAO;MAAA,KAChB,MAAM,IAAI;MAAA,WACJ,UAAU;IACvB,CAAC;IAAA;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA,OANM,GAMN;AAAA;AAGH,SAAS,YAAY;;AAErB;;AAuBA","ignoreList":[]}
@@ -65,7 +65,6 @@ initialValue
65
65
  // TODO: Revise it later!
66
66
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
67
67
  ) {
68
- var _ref$current;
69
68
  const globalState = useGlobalStateObject();
70
69
  const ref = useRef(null);
71
70
  const [stable] = useState(() => {
@@ -75,10 +74,9 @@ initialValue
75
74
  if (!rc) throw Error('Internal error');
76
75
  const newState = typeof value === 'function' ? value(rc.globalState.get(rc.path)) : value;
77
76
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
78
- var _rc$path, _rc$path2;
79
77
  /* eslint-disable no-console */
80
- console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${(_rc$path = rc.path) !== null && _rc$path !== void 0 ? _rc$path : ''}`);
81
- console.log('New value:', cloneDeepForLog(newState, (_rc$path2 = rc.path) !== null && _rc$path2 !== void 0 ? _rc$path2 : ''));
78
+ console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path ?? ''}`);
79
+ console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));
82
80
  console.groupEnd();
83
81
  /* eslint-enable no-console */
84
82
  }
@@ -108,7 +106,7 @@ initialValue
108
106
  initialState: true,
109
107
  initialValue
110
108
  }));
111
- (_ref$current = ref.current) !== null && _ref$current !== void 0 ? _ref$current : ref.current = {
109
+ ref.current ??= {
112
110
  globalState,
113
111
  path,
114
112
  prevValue: value_0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useGlobalState.js","names":["value"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport {\n type Dispatch,\n type SetStateAction,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { useGlobalStateObject } from './GlobalStateProvider';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = Dispatch<SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype CurrentT = {\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n prevValue: unknown;\n};\n\ntype StableT = {\n emitter: Emitter<[]>;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>,\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>,\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initialValue?: ValueOrInitializerT<any>,\n\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): UseGlobalStateResT<any> {\n const globalState = useGlobalStateObject();\n\n const ref = useRef<CurrentT>(null);\n\n const [stable] = useState<StableT>(() => {\n const emitter = new Emitter();\n const setter = (value: unknown) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const newState = typeof value === 'function'\n ? (value as (x: unknown) => unknown)(\n rc.globalState.get<ForceT, unknown>(rc.path),\n ) : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc.path ?? ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set<ForceT, unknown>(rc.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc.prevValue) emitter.emit();\n };\n const subscribe = emitter.addListener.bind(emitter);\n return { emitter, setter, subscribe };\n });\n\n const value = useSyncExternalStore(\n stable.subscribe,\n () => globalState.get<ForceT, unknown>(path, { initialValue }),\n\n () => globalState.get<ForceT, unknown>(\n path,\n { initialState: true, initialValue },\n ),\n );\n\n ref.current ??= {\n globalState,\n path,\n prevValue: value,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n path,\n prevValue: ref.current!.prevValue,\n };\n\n const watcher = () => {\n const nextValue = globalState.get<ForceT, unknown>(path);\n if (ref.current!.prevValue !== nextValue) {\n ref.current!.prevValue = nextValue;\n stable.emitter.emit();\n }\n };\n\n globalState.watch(watcher);\n watcher();\n\n return () => {\n globalState.unWatch(watcher);\n };\n }, [globalState, stable.emitter, path]);\n\n return [value, stable.setter];\n}\n\nexport default useGlobalState;\n\n// TODO: Revise.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":"AAAA;;AAEA,SAGE,SAAS,EACT,MAAM,EACN,QAAQ,EACR,oBAAoB,QACf,OAAO;AAEd,SAAS,OAAO,QAAQ,sBAAsB;AAAC,SAGtC,oBAAoB;AAAA,SAQ3B,eAAe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K,EAAE,MAAM,CAAC,MAAM,CAAC;AAC/B;AAEA,eAAe,cAAc;;AAE7B;AACA","ignoreList":[]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","names":[],"sources":["../../src/utils.ts"],"sourcesContent":["import type { GetFieldType } from 'lodash';\nimport { cloneDeep } from 'lodash-es';\n\nimport type { ObjectKey } from '@dr.pogodin/js-utils';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\nexport declare const force: unique symbol;\nexport declare const lock: unique symbol;\n\nexport type ForceT = typeof force;\nexport type LockT = typeof lock;\n\nexport type TypeLock<\n Unlocked extends ForceT | LockT,\n\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents, @typescript-eslint/no-invalid-void-type\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = (() => ValueT) | ValueT;\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns\n * @ignore\n */\nexport function isDebugMode(): boolean {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch {\n return false;\n }\n}\n\nconst cloneDeepBailKeys = new Set<string>();\n\n/**\n * Deep-clones given value for logging purposes, or returns the value itself\n * if the previous clone attempt, with the same key, took more than 300ms\n * (to avoid situations when large payload in the global state slows down\n * development versions of the app due to the logging overhead).\n */\nexport function cloneDeepForLog<T>(value: T, key: string = ''): T {\n if (cloneDeepBailKeys.has(key)) {\n // eslint-disable-next-line no-console\n console.warn(`The logged value won't be clonned (key \"${key}\").`);\n return value;\n }\n\n const start = Date.now();\n const res = cloneDeep(value);\n const time = Date.now() - start;\n if (time > 300) {\n // eslint-disable-next-line no-console\n console.warn(`${time}ms spent to clone the logged value (key \"${key}\").`);\n cloneDeepBailKeys.add(key);\n }\n\n return res;\n}\n\nexport function areEqual<K extends ObjectKey>(\n a: Record<K, boolean>,\n b: Record<K, boolean>,\n): boolean {\n for (const [key, value] of Object.entries(a)) {\n if (b[key as K] !== value) return false;\n }\n for (const [key, value] of Object.entries(b)) {\n if (a[key as K] !== value) return false;\n }\n return true;\n}\n"],"mappings":"AACA,SAAS,SAAS,QAAQ,WAAW;;AAMrC;AACA;;AAiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAmBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,WAAW,GAAY;EACrC,IAAI;IACF,OAAO,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,IACvC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,wBAAwB;EAC7C,CAAC,CAAC,MAAM;IACN,OAAO,KAAK;EACd;AACF;AAEA,MAAM,iBAAiB,GAAG,IAAI,GAAG,CAAS,CAAC;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS,eAAe,CAAI,KAAQ,EAAE,GAAW,GAAG,EAAE,EAAK;EAChE,IAAI,iBAAiB,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;IAC9B;IACA,OAAO,CAAC,IAAI,CAAC,2CAA2C,GAAG,KAAK,CAAC;IACjE,OAAO,KAAK;EACd;EAEA,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;EACxB,MAAM,GAAG,GAAG,SAAS,CAAC,KAAK,CAAC;EAC5B,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,KAAK;EAC/B,IAAI,IAAI,GAAG,GAAG,EAAE;IACd;IACA,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,4CAA4C,GAAG,KAAK,CAAC;IACzE,iBAAiB,CAAC,GAAG,CAAC,GAAG,CAAC;EAC5B;EAEA,OAAO,GAAG;AACZ;AAEA,OAAO,SAAS,QAAQ,CACtB,CAAqB,EACrB,CAAqB,EACZ;EACT,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;IAC5C,IAAI,CAAC,CAAC,GAAG,CAAM,KAAK,KAAK,EAAE,OAAO,KAAK;EACzC;EACA,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE;IAC5C,IAAI,CAAC,CAAC,GAAG,CAAM,KAAK,KAAK,EAAE,OAAO,KAAK;EACzC;EACA,OAAO,IAAI;AACb","ignoreList":[]}
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@dr.pogodin/react-global-state",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "Hook-based global state for React",
5
- "main": "./build/code/index.js",
5
+ "main": "./build/logic/index.js",
6
6
  "types": "./build/types/index.d.ts",
7
7
  "exports": {
8
8
  "types": "./build/types/index.d.ts",
9
- "default": "./build/code/index.js"
9
+ "default": "./build/logic/index.js"
10
10
  },
11
11
  "scripts": {
12
- "build": "rimraf build && npm run build:types && npm run build:code",
13
- "build:code": "rimraf build/code && babel src -x .ts,.tsx --out-dir build/code --source-maps --config-file ./babel.module.config.js",
12
+ "build": "rimraf build && npm run build:types && npm run build:logic",
13
+ "build:logic": "rimraf build/logic && NODE_ENV=production babel src -x .ts,.tsx --out-dir build/logic --source-maps --config-file ./babel.build.config.js",
14
14
  "build:types": "rimraf build/types && tsc --project tsconfig.types.json",
15
15
  "jest": "npm run jest:types && npm run jest:logic",
16
16
  "jest:logic": "jest --config jest/config.json -w 1 --no-cache",
@@ -39,26 +39,26 @@
39
39
  "node": ">=22"
40
40
  },
41
41
  "dependencies": {
42
- "@babel/runtime": "^7.29.7",
43
- "@dr.pogodin/js-utils": "^0.1.8",
42
+ "@dr.pogodin/js-utils": "^0.2.0",
44
43
  "@types/lodash": "^4.17.24",
45
44
  "lodash-es": "^4.18.1"
46
45
  },
47
46
  "devDependencies": {
48
- "@babel/cli": "^7.29.7",
49
- "@babel/core": "^7.29.7",
50
- "@babel/node": "^7.29.7",
51
- "@babel/plugin-transform-runtime": "^7.29.7",
52
- "@babel/preset-env": "^7.29.7",
53
- "@babel/preset-react": "^7.29.7",
54
- "@babel/preset-typescript": "^7.29.7",
55
- "@dr.pogodin/eslint-configs": "^0.2.14",
47
+ "@babel/cli": "^8.0.4",
48
+ "@babel/core": "^8.0.1",
49
+ "@babel/node": "^8.0.1",
50
+ "@babel/preset-env": "^8.0.2",
51
+ "@babel/preset-react": "^8.0.1",
52
+ "@babel/preset-typescript": "^8.0.1",
53
+ "@dr.pogodin/babel-plugin-add-import-extension": "^2.1.0",
54
+ "@dr.pogodin/eslint-configs": "^0.3.0",
56
55
  "@jest/globals": "^30.4.1",
57
56
  "@testing-library/dom": "^10.4.1",
58
57
  "@testing-library/react": "^16.3.2",
59
58
  "@tsconfig/recommended": "^1.0.13",
60
59
  "@types/jest": "^30.0.0",
61
60
  "@types/lodash-es": "^4.17.12",
61
+ "@types/node": "^24.13.3",
62
62
  "@types/pretty": "^2.0.3",
63
63
  "@types/react": "^19.2.17",
64
64
  "@types/react-dom": "^19.2.3",
@@ -71,10 +71,11 @@
71
71
  "mockdate": "^3.0.5",
72
72
  "rimraf": "^6.1.3",
73
73
  "tstyche": "^7.2.1",
74
- "typescript": "^5.9.3"
74
+ "typescript": "^6.0.3"
75
75
  },
76
76
  "peerDependencies": {
77
77
  "react": "^19.2.7",
78
78
  "react-dom": "^19.2.7"
79
- }
79
+ },
80
+ "type": "module"
80
81
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"GlobalState.js","names":["get","set","toPath","cloneDeepForLog","isDebugMode","ERR_NO_SSR_WATCH","_asyncDataAbortCallbacks","WeakMap","_dependencies","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","Map","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","numAsyncDataAbortCallbacks","size","asyncDataLoadDone","opid","aborted","_classPrivateFieldGet2","delete","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","length","i","Object","freeze","getEntireState","opts","undefined","initialValue","iv","setEntireState","notifyStateUpdate","value","p","setTimeout","watchers","watcher","setAsyncDataAbortCallback","cb","res","root","segIdx","pos","pathSegments","seg","next","Array","isArray","slice","unWatch","callback","Error","indexOf","pop","watch","includes","push"],"sources":["../../src/GlobalState.ts"],"sourcesContent":["import { get, set, toPath } from 'lodash-es';\n\nimport type SsrContext from './SsrContext';\n\nimport {\n type CallbackT,\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nconst ERR_NO_SSR_WATCH = 'GlobalState must not be watched at server side';\n\ntype GetOptsT<T> = {\n initialState?: boolean;\n initialValue?: ValueOrInitializerT<T>;\n};\n\nexport default class GlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n readonly ssrContext?: SsrContextT;\n\n #asyncDataAbortCallbacks = new Map<string, () => void>();\n\n #dependencies = new Map<string, readonly unknown[]>();\n\n #initialState: StateT;\n\n // TODO: It is tempting to replace watchers here by\n // Emitter from @dr.pogodin/js-utils, but we need to clone\n // current watchers for emitting later, and this is not something\n // Emitter supports right now.\n #watchers: CallbackT[] = [];\n\n #nextNotifierId?: NodeJS.Timeout;\n\n #currentState: StateT;\n\n /**\n * Creates a new global state object.\n * @param initialState Intial global state content.\n * @param ssrContext Server-side rendering context.\n */\n constructor(\n initialState: StateT,\n ssrContext?: SsrContextT,\n ) {\n this.#currentState = initialState;\n this.#initialState = initialState;\n\n if (ssrContext) {\n /* eslint-disable no-param-reassign */\n ssrContext.dirty = false;\n ssrContext.pending = [];\n ssrContext.state = this.#currentState;\n /* eslint-enable no-param-reassign */\n\n this.ssrContext = ssrContext;\n }\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n let msg = 'New ReactGlobalState created';\n if (ssrContext) msg += ' (SSR mode)';\n console.groupCollapsed(msg);\n console.log('Initial state:', cloneDeepForLog(initialState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n }\n\n /**\n * Returns the number of currently registered async data abort callbacks,\n * just for the sake of testing the library.\n */\n get numAsyncDataAbortCallbacks(): number {\n return this.#asyncDataAbortCallbacks.size;\n }\n\n /**\n * If `aborted` is \"true\" and there is an abort callback registered for\n * the specified operation, it triggers the callback. Then, in any case,\n * it drops the callback.\n */\n asyncDataLoadDone(opid: string, aborted: boolean): void {\n if (aborted) this.#asyncDataAbortCallbacks.get(opid)?.();\n this.#asyncDataAbortCallbacks.delete(opid);\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string): void {\n this.#dependencies.delete(path);\n }\n\n /**\n * Checks if given `deps` are different from previously recorded ones for\n * the given `path`. If they are, `deps` are recorded as the new deps for\n * the `path`, and also the array is frozen, to prevent it from being\n * modified.\n *\n * TODO: This may not work as expected if path string is not normalized,\n * and the for the same path different alternative ways to spell it down\n * are used. We should normalize given path here, I guess, or on a higher\n * level in the logic?\n */\n hasChangedDependencies(path: string, deps: unknown[]): boolean {\n const prevDeps = this.#dependencies.get(path);\n let changed = prevDeps?.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies.set(path, Object.freeze(deps));\n return changed;\n }\n\n /**\n * Gets entire state, the same way as .get(null, opts) would do.\n * @param opts.initialState\n * @param opts.initialValue\n */\n getEntireState(opts?: GetOptsT<StateT>): StateT {\n let state = opts?.initialState ? this.#initialState : this.#currentState;\n if (state !== undefined || opts?.initialValue === undefined) return state;\n\n const iv = opts.initialValue;\n state = typeof iv === 'function' ? (iv as () => StateT)() : iv;\n if (this.#currentState === undefined) this.setEntireState(state);\n return state;\n }\n\n /**\n * Notifies all connected state watchers that a state update has happened.\n */\n private notifyStateUpdate(path: null | string | undefined, value: unknown) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n const p = typeof path === 'string'\n ? `\"${path}\"` : 'none (entire state update)';\n console.groupCollapsed(`ReactGlobalState update. Path: ${p}`);\n console.log('New value:', cloneDeepForLog(value, path ?? ''));\n console.log('New state:', cloneDeepForLog(this.#currentState));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n\n if (this.ssrContext) {\n this.ssrContext.dirty = true;\n this.ssrContext.state = this.#currentState;\n } else if (!this.#nextNotifierId) {\n this.#nextNotifierId = setTimeout(() => {\n this.#nextNotifierId = undefined;\n const watchers = [...this.#watchers];\n for (const watcher of watchers) watcher();\n });\n }\n }\n\n /**\n * Registers an abort callback for an async data retrieval operation with\n * the given operation ID. Throws if already registered.\n */\n setAsyncDataAbortCallback(opid: string, cb: () => void): void {\n this.#asyncDataAbortCallbacks.set(opid, cb);\n }\n\n /**\n * Sets entire state, the same way as .set(null, value) would do.\n * @param value\n */\n setEntireState(value: StateT): StateT {\n if (this.#currentState !== value) {\n this.#currentState = value;\n this.notifyStateUpdate(null, value);\n }\n return value;\n }\n\n /**\n * Gets current or initial value at the specified \"path\" of the global state.\n * @param path Dot-delimitered state path.\n * @param options Additional options.\n * @param options.initialState If \"true\" the value will be read\n * from the initial state instead of the current one.\n * @param options.initialValue If the value read from the \"path\" is\n * \"undefined\", this \"initialValue\" will be returned instead. In such case\n * \"initialValue\" will also be written to the \"path\" of the current global\n * state (no matter \"initialState\" flag), if \"undefined\" is stored there.\n * @return Retrieved value.\n */\n\n // .get() without arguments just falls back to .getEntireState().\n get(): StateT;\n\n // This variant attempts to automatically resolve and check the type of value\n // at the given path, as precise as the actual state and path types permit.\n // If the automatic path resolution is not possible, the ValueT fallsback\n // to `never` (or to `undefined` in some cases), effectively forbidding\n // to use this .get() variant.\n get<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, opts?: GetOptsT<ValueArgT>): ValueResT;\n\n // This variant is not callable by default (without generic arguments),\n // otherwise it allows to set the correct ValueT directly.\n get<Forced extends ForceT | LockT = LockT, ValueT = void>(\n path?: null | string,\n opts?: GetOptsT<TypeLock<Forced, never, ValueT>>,\n ): TypeLock<Forced, void, ValueT>;\n\n get<ValueT>(path?: null | string, opts?: GetOptsT<ValueT>): ValueT {\n if (typeof path !== 'string') {\n const res = this.getEntireState((opts as unknown) as GetOptsT<StateT>);\n return (res as unknown) as ValueT;\n }\n\n const state = opts?.initialState ? this.#initialState : this.#currentState;\n\n let res = get(state, path) as ValueT;\n if (res !== undefined || opts?.initialValue === undefined) return res;\n\n const iv = opts.initialValue;\n res = typeof iv === 'function' ? (iv as () => ValueT)() : iv;\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (!opts.initialState || (this.get(path) as unknown) === undefined) {\n this.set<ForceT, unknown>(path, res);\n }\n\n return res;\n }\n\n /**\n * Writes the `value` to given global state `path`.\n * @param path Dot-delimitered state path. If not given, entire\n * global state content is replaced by the `value`.\n * @param value The value.\n * @return Given `value` itself.\n */\n\n // This variant attempts automatic value type resolution & checking.\n set<\n PathT extends null | string | undefined,\n ValueArgT extends ValueAtPathT<StateT, PathT, never>,\n ValueResT extends ValueAtPathT<StateT, PathT, void>,\n >(path: PathT, value: ValueArgT): ValueResT;\n\n // This variant is disabled by default, otherwise allows to give\n // expected value type explicitly.\n set<Forced extends ForceT | LockT = LockT, ValueT = never>(\n path: null | string | undefined,\n value: TypeLock<Forced, never, ValueT>,\n ): TypeLock<Forced, void, ValueT>;\n\n set(path: null | string | undefined, value: unknown): unknown {\n if (typeof path !== 'string') return this.setEntireState(value as StateT);\n\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n if (value !== this.get(path)) {\n const root = { state: this.#currentState };\n let segIdx = 0;\n\n // TODO: It is not 100% correct, as `pos` can be an array, or any other\n // value as we travel through the state tree. To simplify the typing for\n // now, I guess, we can go with this record type, though.\n let pos: Record<string, unknown> = root;\n const pathSegments = toPath(`state.${path}`);\n for (; segIdx < pathSegments.length - 1; segIdx += 1) {\n const seg = pathSegments[segIdx]!;\n\n // TODO: Revise: Typing is not quite correct here, but it works fine in the runtime.\n const next = pos[seg];\n if (Array.isArray(next)) pos[seg] = [...(next as unknown[])];\n else if (typeof next === 'object') pos[seg] = { ...next };\n else {\n // We arrived to a state sub-segment, where the remaining part of\n // the update path does not exist yet. We rely on lodash's set()\n // function to create the remaining path, and set the value.\n set(pos, pathSegments.slice(segIdx), value);\n break;\n }\n pos = pos[seg] as Record<string, unknown>;\n }\n\n if (segIdx === pathSegments.length - 1) {\n pos[pathSegments[segIdx]!] = value;\n }\n\n this.#currentState = root.state;\n\n this.notifyStateUpdate(path, value);\n }\n return value;\n }\n\n /**\n * Unsubscribes `callback` from watching state updates; no operation if\n * `callback` is not subscribed to the state updates.\n * @param callback\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n unWatch(callback: CallbackT): void {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n const pos = watchers.indexOf(callback);\n if (pos >= 0) {\n watchers[pos] = watchers[watchers.length - 1]!;\n watchers.pop();\n }\n }\n\n /**\n * Subscribes `callback` to watch state updates; no operation if\n * `callback` is already subscribed to this state instance.\n * @param callback It will be called without any arguments every\n * time the state content changes (note, howhever, separate state updates can\n * be applied to the state at once, and watching callbacks will be called once\n * after such bulk update).\n * @throws if {@link SsrContext} is attached to the state instance: the state\n * watching functionality is intended for client-side (non-SSR) only.\n */\n watch(callback: CallbackT): void {\n if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);\n\n const watchers = this.#watchers;\n if (!watchers.includes(callback)) {\n watchers.push(callback);\n }\n }\n}\n"],"mappings":";;;;;AAAA,SAASA,GAAG,EAAEC,GAAG,EAAEC,MAAM,QAAQ,WAAW;AAAC,SAW3CC,eAAe,EACfC,WAAW;AAGb,MAAMC,gBAAgB,GAAG,gDAAgD;AAAC,IAAAC,wBAAA,oBAAAC,OAAA;AAAA,IAAAC,aAAA,oBAAAD,OAAA;AAAA,IAAAE,aAAA,oBAAAF,OAAA;AAAA,IAAAG,SAAA,oBAAAH,OAAA;AAAA,IAAAI,eAAA,oBAAAJ,OAAA;AAAA,IAAAK,aAAA,oBAAAL,OAAA;AAO1E,eAAe,MAAMM,WAAW,CAG9B;EAmBA;AACF;AACA;AACA;AACA;EACEC,WAAWA,CACTC,YAAoB,EACpBC,UAAwB,EACxB;IAxBFC,0BAAA,OAAAX,wBAAwB,EAAG,IAAIY,GAAG,CAAqB,CAAC;IAExDD,0BAAA,OAAAT,aAAa,EAAG,IAAIU,GAAG,CAA6B,CAAC;IAErDD,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IAC/B,IAAI,IAAI,CAAC1D,UAAU,EAAE,MAAM,IAAI2D,KAAK,CAACtE,gBAAgB,CAAC;IAEtD,MAAMsD,QAAQ,GAAGpC,qBAAA,CAAKb,SAAS,EAAd,IAAa,CAAC;IAC/B,IAAI,CAACiD,QAAQ,CAACoB,QAAQ,CAACL,QAAQ,CAAC,EAAE;MAChCf,QAAQ,CAACqB,IAAI,CAACN,QAAQ,CAAC;IACzB;EACF;AACF","ignoreList":[]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"GlobalStateProvider.js","names":["createContext","use","useState","GlobalState","jsx","_jsx","Context","useGlobalStateObject","globalState","Error","useSsrContext","t0","throwWithoutSsrContext","undefined","ssrContext","GlobalStateProvider","$","_c","children","rest","localState","setLocalState","state","stateProxy","gs","initialState","t1"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import {\n type ReactNode,\n createContext,\n use,\n useState,\n} from 'react';\n\nimport GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\n\nimport type { ValueOrInitializerT } from './utils';\n\nconst Context = createContext<GlobalState<unknown> | null>(null);\n\n/**\n * Returns the GlobalState object from the context. In most cases you should use\n * other hooks, like useGlobalState(), etc. to interact with the global state,\n * instead of accessing the GlobalState object directly.\n */\nexport function useGlobalStateObject<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n const globalState = use(Context);\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * Returns SSR context.\n * @param throwWithoutSsrContext - If _true_ (default), this hook will throw\n * if no SSR context is attached to the global state; set _false_ to not throw\n * in such case. In either case this hook will throw if the <GlobalStateProvider>\n * (hence the global state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent <GlobalStateProvider> in the rendered\n * React tree.\n * - If `throwWithoutSsrContext` is _true_ (default), and there is no SSR\n * context attached to the global state provided by <GlobalStateProvider>.\n */\nexport function useSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = useGlobalStateObject<SsrContextT['state'], SsrContextT>();\n if (!ssrContext && throwWithoutSsrContext) {\n throw new Error('No SSR context found');\n }\n return ssrContext;\n}\n\ntype NewStateProps<StateT, SsrContextT extends SsrContext<StateT>> = {\n initialState: ValueOrInitializerT<StateT>;\n ssrContext?: SsrContextT;\n};\n\ntype GlobalStateProviderProps<\n StateT,\n SsrContextT extends SsrContext<StateT>,\n> = (NewStateProps<StateT, SsrContextT> | {\n stateProxy: GlobalState<StateT, SsrContextT> | true;\n}) & {\n children?: ReactNode;\n};\n\n/**\n * Provides global state to its children.\n * @param prop.children Component children, which will be provided with\n * the global state, and rendered in place of the provider.\n * @param prop.initialState Initial content of the global state.\n * @param prop.ssrContext Server-side rendering (SSR) context.\n * @param prop.stateProxy This option is useful for code\n * splitting and SSR implementation:\n * - If `true`, this provider instance will fetch and reuse the global state\n * from a parent provider.\n * - If `GlobalState` instance, it will be used by this provider.\n * - If not given, a new `GlobalState` instance will be created and used.\n */\nconst GlobalStateProvider = <\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(\n { children, ...rest }: GlobalStateProviderProps<StateT, SsrContextT>,\n): ReactNode => {\n type GST = GlobalState<StateT, SsrContextT>;\n\n const [localState, setLocalState] = useState<GST>();\n\n let state: GST;\n\n // Below we cast `rest.stateProxy` as \"boolean\" for safe backward\n // compatibility with plain JavaScript (as TypeScript typings only\n // permit \"true\" or GlobalState value; while legacy codebase may\n // pass in a boolean value here, occasionally equal \"false\").\n if ('stateProxy' in rest && (rest.stateProxy as boolean)) {\n if (localState) setLocalState(undefined);\n\n if (rest.stateProxy === true) {\n const gs = use(Context);\n if (!gs) throw Error('Missing GlobalStateProvider');\n state = gs as GlobalState<StateT, SsrContextT>;\n } else state = rest.stateProxy;\n } else if (localState) {\n state = localState;\n } else {\n const {\n initialState,\n ssrContext,\n } = rest as NewStateProps<StateT, SsrContextT>;\n\n state = new GlobalState(\n typeof initialState === 'function' ? (initialState as () => StateT)() : initialState,\n ssrContext,\n );\n\n setLocalState(state);\n }\n\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":";AAAA,SAEEA,aAAa,EACbC,GAAG,EACHC,QAAQ,QACH,OAAO;AAAC,OAERC,WAAW;AAAA,SAAAC,GAAA,IAAAC,IAAA;AAKlB,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,oBAAoBA,CAAA,EAGE;EACpC,MAAMC,WAAW,GAAGP,GAAG,CAACK,OAAO,CAAC;EAChC,IAAI,CAACE,WAAW,EAAE,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOD,WAAW;AACpB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAAE,cAAAC,EAAA;EAGL,MAAAC,sBAAA,GAAAD,EAA6B,KAA7BE,SAA6B,GAA7B,IAA6B,GAA7BF,EAA6B;EAE7B;IAAAG;EAAA,IAAuBP,oBAAoB,CAAoC,CAAC;EAChF,IAAI,CAACO,UAAoC,IAArCF,sBAAqC;IACvC,MAAM,IAAIH,KAAK,CAAC,sBAAsB,CAAC;EAAC;EACzC,OACMK,UAAU;AAAA;AAiBnB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,mBAAmB,GAAGJ,EAAA;EAAA,MAAAK,CAAA,GAAAC,EAAA;EAI1B;IAAAC,QAAA;IAAA,GAAAC;EAAA,IAAAR,EAAoE;EAIpE,OAAAS,UAAA,EAAAC,aAAA,IAAoCnB,QAAQ,CAAM,CAAC;EAE/CoB,GAAA,CAAAA,KAAA;EAMJ,IAAI,YAAY,IAAIH,IAAoC,IAA3BA,IAAI,CAAAI,UAAuB;IACtD,IAAIH,UAAU;MAAEC,aAAa,CAACR,SAAS,CAAC;IAAA;IAExC,IAAIM,IAAI,CAAAI,UAAW,KAAK,IAAI;MAC1B,MAAAC,EAAA,GAAWvB,GAAG,CAACK,OAAO,CAAC;MACvB,IAAI,CAACkB,EAAE;QAAE,MAAMf,KAAK,CAAC,6BAA6B,CAAC;MAAC;MACpDa,KAAA,CAAAA,CAAA,CAAQE,EAAE;IAAL;MACAF,KAAA,CAAAA,CAAA,CAAQH,IAAI,CAAAI,UAAW;IAAlB;EAAmB;IAC1B,IAAIH,UAAU;MACnBE,KAAA,CAAAA,CAAA,CAAQF,UAAU;IAAb;MAEL;QAAAK,YAAA;QAAAX;MAAA,IAGIK,IAAI;MAERG,KAAA,CAAAA,CAAA,CAAQA,GAAA,CAAInB,WAAW,CACrB,OAAOsB,YAAY,KAAK,UAA4D,GAA9CA,YAAY,CAAiC,CAAC,GAApFA,YAAoF,EACpFX,UACF,CAAC;MAEDO,aAAa,CAACC,KAAK,CAAC;IAAA;EACrB;EAAA,IAAAI,EAAA;EAAA,IAAAV,CAAA,QAAAE,QAAA,IAAAF,CAAA,QAAAM,KAAA;IAEMI,EAAA,gBAAArB,IAAA,CAACC,OAAO;MAAQgB,KAAK,EAALA,KAAK;MAAAJ,QAAA,EAAGA;IAAQ,CAAU,CAAC;IAAAF,CAAA,MAAAE,QAAA;IAAAF,CAAA,MAAAM,KAAA;IAAAN,CAAA,MAAAU,EAAA;EAAA;IAAAA,EAAA,GAAAV,CAAA;EAAA;EAAA,OAA3CU,EAA2C;AAAA,CACnD;AAED,eAAeX,mBAAmB","ignoreList":[]}
@@ -1,9 +0,0 @@
1
- import _defineProperty from "@babel/runtime/helpers/defineProperty";
2
- export default class SsrContext {
3
- constructor(state) {
4
- _defineProperty(this, "dirty", false);
5
- _defineProperty(this, "pending", []);
6
- this.state = state;
7
- }
8
- }
9
- //# sourceMappingURL=SsrContext.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"SsrContext.js","names":["SsrContext","constructor","state","_defineProperty"],"sources":["../../src/SsrContext.ts"],"sourcesContent":["export default class SsrContext<StateT> {\n dirty: boolean = false;\n\n pending: Array<Promise<void>> = [];\n\n constructor(public state?: StateT) { }\n}\n"],"mappings":";AAAA,eAAe,MAAMA,UAAU,CAAS;EAKtCC,WAAWA,CAAQC,KAAc,EAAE;IAAAC,eAAA,gBAJlB,KAAK;IAAAA,eAAA,kBAEU,EAAE;IAAA,KAEfD,KAAc,GAAdA,KAAc;EAAI;AACvC","ignoreList":[]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","useGlobalStateObject","useSsrContext","SsrContext","useAsyncCollection","loadAsyncData","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n useGlobalStateObject,\n useSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type LoadAsyncDataI,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type {\n AsyncCollectionLoaderT,\n AsyncCollectionReloaderT,\n AsyncCollectionT,\n} from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n type UseGlobalStateI,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n useGlobalStateObject,\n useSsrContext,\n};\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n GlobalState: typeof GlobalState<StateT, SsrContextT>;\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;\n SsrContext: typeof SsrContext<StateT>;\n loadAsyncData: LoadAsyncDataI<StateT>;\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope;\n useAsyncCollection: UseAsyncCollectionI<StateT>;\n useAsyncData: UseAsyncDataI<StateT>;\n useGlobalState: UseGlobalStateI<StateT>;\n useGlobalStateObject: typeof useGlobalStateObject<StateT, SsrContextT>;\n useSsrContext: typeof useSsrContext<SsrContextT>;\n}\n\nconst api = {\n // TODO: I am puzzled, why ESLint eforces this sorting order as alphabetical?\n // Perhaps, we should tune something in its config settings, as it seems to mix\n // some extra sorting logic, which I am not sure I like.\n GlobalState,\n GlobalStateProvider,\n SsrContext,\n loadAsyncData,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n useGlobalStateObject,\n useSsrContext,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): API<StateT, SsrContextT> {\n return api;\n}\n"],"mappings":"OAAOA,WAAW;AAAA,OAEXC,mBAAmB,IACxBC,oBAAoB,EACpBC,aAAa;AAAA,OAGRC,UAAU;AAAA,OAEVC,kBAAkB;AAAA,SAavBC,aAAa,EACbC,oBAAoB,EACpBC,YAAY;AAAA,OAGPC,cAAc;AAYrB,SAIET,WAAW,EACXC,mBAAmB,EACnBG,UAAU,EAOVE,aAAa,EACbC,oBAAoB,EACpBF,kBAAkB,EAClBG,YAAY,EACZC,cAAc,EACdP,oBAAoB,EACpBC,aAAa;;AAGf;;AAiBA,MAAMO,GAAG,GAAG;EACV;EACA;EACA;EACAV,WAAW;EACXC,mBAAmB;EACnBG,UAAU;EACVE,aAAa;EACbC,oBAAoB;EACpBF,kBAAkB;EAClBG,YAAY;EACZC,cAAc;EACdP,oBAAoB;EACpBC;AACF,CAAC;AAED,OAAO,SAASQ,mBAAmBA,CAAA,EAGL;EAC5B,OAAOD,GAAG;AACZ","ignoreList":[]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","useState","useGlobalStateObject","DEFAULT_MAXAGE","loadAsyncData","newAsyncDataEnvelope","useGlobalState","areEqual","isDebugMode","gcOnWithhold","ids","path","gs","collection","get","id","envelope","numRefs","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","console","log","normalizeIds","idOrIds","Array","isArray","from","sort","a","b","localeCompare","useAsyncCollection","loader","options","_options$maxage","_options$refreshAge","_options$garbageColle","_ref$current","maxage","refreshAge","garbageCollectAge","globalState","ssrContext","disabled","noSSR","operationId","globalThis","crypto","randomUUID","itemPath","state","initialValue","promiseOrVoid","args","data","Promise","pending","push","idsString","JSON","stringify","localIds","parse","_state2$timestamp","state2","deps","hasChangedDependencies","startsWith","_state2$data","_state2$timestamp2","dropDependencies","old","localState","ref","current","stable","reload","customLoader","rc","Error","localLoader","oldData","meta","reloadSingle","setSingle","stale","setStale","nowStale","key","e","requestAnimationFrame","cancelAnimationFrame","_e_0$timestamp","_e_0$data","loading","items","Number","MAX_VALUE","_e_1$timestamp","_e_1$data"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef, useState } from 'react';\n\nimport type GlobalState from './GlobalState';\nimport { useGlobalStateObject } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n DEFAULT_MAXAGE,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n loadAsyncData,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n areEqual,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = Partial<Record<IdT, AsyncDataEnvelopeT<DataT>>>;\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (id: IdT, oldData: DataT | null, meta: {\n abortSignal: AbortSignal;\n oldDataTimestamp: number;\n}) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void> | void;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: Record<IdT, CollectionItemT<DataT>>;\n loading: boolean;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n timestamp: number;\n};\n\ntype CurrentT<DataT, IdT extends number | string> = {\n globalState: GlobalState<unknown>;\n ids: IdT[];\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n path: null | string | undefined;\n};\n\ntype StableT<DataT, IdT extends number | string> = {\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\n setSingle: (data: DataT | null) => void;\n};\n\n/**\n * GarbageCollector: the piece of logic executed on mounting of\n * an useAsyncCollection() hook, and on update of hook params, to update\n * the state according to the new param values. It increments by 1 `numRefs`\n * counters for the requested collection items.\n */\nfunction gcOnWithhold<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n) {\n const collection = { ...gs.get<ForceT, AsyncCollectionT>(path) };\n\n for (const id of ids) {\n let envelope = collection[id];\n if (envelope) envelope = { ...envelope, numRefs: 1 + envelope.numRefs };\n else envelope = newAsyncDataEnvelope<unknown>(null, { numRefs: 1 });\n collection[id] = envelope;\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction idsToStringSet<IdT extends number | string>(ids: IdT[]): Set<string> {\n const res = new Set<string>();\n for (const id of ids) {\n res.add(id.toString());\n }\n return res;\n}\n\n/**\n * GarbageCollector: the piece of logic executed on un-mounting of\n * an useAsyncCollection() hook, and on update of hook params, to clean-up\n * after the previous param values. It decrements by 1 `numRefs` counters\n * for previously requested collection items, and also drops from the state\n * stale records.\n */\nfunction gcOnRelease<IdT extends number | string>(\n ids: IdT[],\n path: null | string | undefined,\n gs: GlobalState<unknown>,\n gcAge: number,\n) {\n type EnvelopeT = AsyncDataEnvelopeT<unknown>;\n\n const entries = Object.entries<EnvelopeT | undefined>(\n gs.get<ForceT, AsyncCollectionT>(path),\n );\n\n const now = Date.now();\n const idSet = idsToStringSet(ids);\n const collection: AsyncCollectionT = {};\n for (const [id, envelope] of entries) {\n if (envelope) {\n const toBeReleased = idSet.has(id);\n\n let { numRefs } = envelope;\n if (toBeReleased) --numRefs;\n\n if (gcAge > now - envelope.timestamp || numRefs > 0) {\n collection[id as IdT] = toBeReleased\n ? { ...envelope, numRefs }\n : envelope;\n } else if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n // eslint-disable-next-line no-console\n console.log(\n `useAsyncCollection(): Garbage collected at the path \"${\n path}\", ID = ${id}`,\n );\n }\n }\n }\n\n gs.set<ForceT, AsyncCollectionT>(path, collection);\n}\n\nfunction normalizeIds<IdT extends number | string>(\n idOrIds: IdT | IdT[],\n): IdT[] {\n if (Array.isArray(idOrIds)) {\n // Removes ID duplicates.\n const res = Array.from(new Set(idOrIds));\n\n // Ensures stable ID order.\n res.sort((a, b) => a.toString().localeCompare(b.toString()));\n\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Resolves and stores at the given `path` of the global state elements of\n * an asynchronous data collection.\n */\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n>(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT>;\n\nfunction useAsyncCollection<\n StateT,\n PathT extends null | string | undefined,\n IdT extends number | string,\n\n DataT extends DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`> = DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>,\n>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncCollectionResT<DataT, IdT> | UseAsyncDataResT<DataT>;\n\n// TODO: This is largely similar to useAsyncData() logic, just more generic.\n// Perhaps, a bunch of logic blocks can be split into stand-alone functions,\n// and reused in both hooks.\n// eslint-disable-next-line complexity\nfunction useAsyncCollection<\n DataT,\n IdT extends number | string,\n>(\n idOrIds: IdT | IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncCollectionResT<DataT, IdT> | UseAsyncDataResT<DataT> {\n const ids = normalizeIds(idOrIds);\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n const globalState = useGlobalStateObject();\n\n // Server-side logic.\n if (globalState.ssrContext) {\n if (!options.disabled && !options.noSSR) {\n const operationId: OperationIdT = `S${globalThis.crypto.randomUUID()}`;\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(\n itemPath,\n {\n initialValue: newAsyncDataEnvelope<DataT>(),\n },\n );\n if (!state.timestamp && !state.operationId) {\n const promiseOrVoid = loadAsyncData<ForceT, DataT>(\n itemPath,\n (...args):\n DataT | Promise<DataT | null> | null => loader(id, ...args),\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n operationId,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n }\n }\n\n const { disabled } = options;\n\n // Reference-counting & garbage collection.\n\n const idsString = JSON.stringify(ids);\n\n useEffect(() => {\n const localIds = JSON.parse(idsString) as IdT[];\n\n if (!disabled) gcOnWithhold(localIds, path, globalState);\n return () => {\n if (!disabled) {\n gcOnRelease(localIds, path, globalState, garbageCollectAge);\n }\n };\n\n // `ids` are represented in the dependencies array by `idsHash` value,\n // as useEffect() hook requires a constant size of dependencies array.\n }, [\n disabled,\n garbageCollectAge,\n globalState,\n idsString,\n path,\n ]);\n\n // NOTE: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => {\n if (!disabled) {\n void (async () => {\n for (const id of ids) {\n const itemPath = path ? `${path}.${id}` : `${id}`;\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state2: EnvT = globalState.get<ForceT, EnvT>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - (state2?.timestamp ?? 0)\n && (!state2?.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n await loadAsyncData<ForceT, DataT>(\n itemPath,\n // TODO: I guess, the loader is not correctly typed here -\n // it can be synchronous, and in that case the following method\n // should be kept synchronous to not alter the sync logic.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (old, ...args) => loader(id, old, ...args),\n globalState,\n {\n data: state2?.data ?? null,\n timestamp: state2?.timestamp ?? 0,\n },\n );\n }\n }\n })();\n }\n });\n\n const [localState] = useGlobalState<\n ForceT, Record<string, AsyncDataEnvelopeT<DataT>>\n >(path, {});\n\n const ref = useRef<CurrentT<DataT, IdT>>(null);\n\n ref.current ??= {\n globalState,\n ids,\n loader,\n path,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n ids,\n loader,\n path,\n };\n }, [globalState, ids, loader, path]);\n\n const [stable] = useState<StableT<DataT, IdT>>(() => {\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const localLoader = customLoader ?? rc.loader;\n\n // TODO: Revise - not sure all related typing is 100% correct,\n // thus let's keep this runtime assertion.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!localLoader || !rc.globalState || !rc.ids) {\n throw Error('Internal error');\n }\n\n for (const id of rc.ids) {\n const itemPath = rc.path ? `${rc.path}.${id}` : `${id}`;\n\n const promiseOrVoid = loadAsyncData<ForceT, DataT>(\n itemPath,\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n rc.globalState,\n );\n\n if (promiseOrVoid instanceof Promise) await promiseOrVoid;\n }\n };\n\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const reloadSingle: AsyncDataReloaderT<DataT> = (customLoader) => reload(\n // TODO: Revise! Most probably we don't have fully correct loader\n // typing, as it may return either promise or value, and those two\n // cases call for different runtime behavior, which in turns only\n // happens if the outer function on the next line matches the same\n // async / sync signature.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n customLoader && ((id, ...args) => customLoader(...args)),\n );\n\n const setSingle = (data: DataT | null) => {\n void reload(() => data);\n };\n\n return { reload, reloadSingle, setSingle };\n });\n\n const [stale, setStale] = useState({} as Record<IdT, boolean>);\n\n // TODO: Merge into the data-reloading effect above?\n useEffect(() => {\n const now = Date.now();\n const nowStale = {} as Record<IdT, boolean>;\n for (const [key, e] of Object.entries(localState)) {\n nowStale[key as IdT] = maxage < now - e.timestamp;\n }\n\n const id = areEqual(stale, nowStale) ? null : requestAnimationFrame(() => {\n setStale(nowStale);\n });\n\n return () => {\n if (id !== null) cancelAnimationFrame(id);\n };\n });\n\n if (!Array.isArray(idOrIds)) {\n // TODO: Revise related typings!\n const e = localState[idOrIds as string];\n const timestamp = e?.timestamp ?? 0;\n return {\n data: stale[idOrIds] ? null : e?.data ?? null,\n loading: !!e?.operationId,\n reload: stable.reloadSingle,\n set: stable.setSingle,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: stable.reload,\n timestamp: Number.MAX_VALUE,\n };\n\n for (const id of ids) {\n // TODO: Revise related typing. Should `localState` have a more specific type?\n const e = localState[id as string];\n const loading = !!e?.operationId;\n const timestamp = e?.timestamp ?? 0;\n\n res.items[id] = {\n data: stale[id] ? null : e?.data ?? null,\n loading,\n timestamp,\n };\n res.loading ||= loading;\n if (res.timestamp > timestamp) res.timestamp = timestamp;\n }\n\n return res;\n}\n\nexport default useAsyncCollection;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncCollectionI<StateT> {\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT,\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT,\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n\n <\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n IdT extends number | string = number | string,\n >(\n id: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<TypeLock<Forced, void, DataT>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataT, IdT>;\n\n <PathT extends null | string | undefined, IdT extends number | string>(\n id: IdT | IdT[],\n path: PathT,\n loader: AsyncCollectionLoaderT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>\n | UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,OAAO;AAAC,SAG3CC,oBAAoB;AAAA,SAK3BC,cAAc,EAKdC,aAAa,EACbC,oBAAoB;AAAA,OAGfC,cAAc;AAAA,SAMnBC,QAAQ,EACRC,WAAW;AAkDb;AACA;AACA;AACA;AACA;AACA;AACA,SAASC,YAAYA,CACnBC,GAAU,EACVC,IAA+B,EAC/BC,EAAwB,EACxB;EACA,MAAMC,UAAU,GAAG;IAAE,GAAGD,EAAE,CAACE,GAAG,CAA2BH,IAAI;EAAE,CAAC;EAEhE,KAAK,MAAMI,EAAE,IAAIL,GAAG,EAAE;IACpB,IAAIM,QAAQ,GAAGH,UAAU,CAACE,EAAE,CAAC;IAC7B,IAAIC,QAAQ,EAAEA,QAAQ,GAAG;MAAE,GAAGA,QAAQ;MAAEC,OAAO,EAAE,CAAC,GAAGD,QAAQ,CAACC;IAAQ,CAAC,CAAC,KACnED,QAAQ,GAAGX,oBAAoB,CAAU,IAAI,EAAE;MAAEY,OAAO,EAAE;IAAE,CAAC,CAAC;IACnEJ,UAAU,CAACE,EAAE,CAAC,GAAGC,QAAQ;EAC3B;EAEAJ,EAAE,CAACM,GAAG,CAA2BP,IAAI,EAAEE,UAAU,CAAC;AACpD;AAEA,SAASM,cAAcA,CAA8BT,GAAU,EAAe;EAC5E,MAAMU,GAAG,GAAG,IAAIC,GAAG,CAAS,CAAC;EAC7B,KAAK,MAAMN,EAAE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AE5C,WAAW;IAChC,MAAM7B,WAAS,IAAAkF,cAAA,GAAGT,GAAC,aAADA,GAAC,uBAADA,GAAC,CAAEzE,SAAS,cAAAkF,cAAA,cAAAA,cAAA,GAAI,CAAC;IAEnC/F,GAAG,CAAC4F,KAAK,CAACjG,IAAE,CAAC,GAAG;MACdwD,IAAI,EAAE+B,KAAK,CAACvF,IAAE,CAAC,GAAG,IAAI,IAAAqG,SAAA,GAAGV,GAAC,aAADA,GAAC,uBAADA,GAAC,CAAEnC,IAAI,cAAA6C,SAAA,cAAAA,SAAA,GAAI,IAAI;MACxCL,OAAO;MACP9E,SAAS,EAATA;IACF,CAAC;IACDb,GAAG,CAAC2F,OAAO,KAAX3F,GAAG,CAAC2F,OAAO,GAAKA,OAAO;IACvB,IAAI3F,GAAG,CAACa,SAAS,GAAGA,WAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,WAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAEA,eAAe4B,kBAAkB;;AAEjC","ignoreList":[]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"useAsyncData.js","names":["useEffect","useRef","useState","MIN_MS","useGlobalStateObject","useGlobalState","cloneDeepForLog","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","setState","path","gs","prevState","get","process","env","NODE_ENV","console","groupCollapsed","log","set","Date","now","groupEnd","finalizeLoad","asyncDataLoadDone","state","loadAsyncData","loader","globalState","old","globalThis","crypto","randomUUID","operationIdPath","prevOperationId","definedOld","e","controller","AbortController","setAsyncDataAbortCallback","abort","dataOrPromise","abortSignal","signal","oldDataTimestamp","Promise","then","finally","undefined","useAsyncData","t0","_options$maxage","_options$refreshAge","_options$garbageColle","$","_c","t1","options","maxage","refreshAge","garbageCollectAge","initialValue","t2","current","heap","t3","t4","Symbol","for","reload","customLoader","localLoader","stable","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","t5","t6","numRefsPath","state2","dropDependencies","t7","state2_0","deps","hasChangedDependencies","startsWith","t8","localState","t9","stale","setStale","t10","nowStale","id","requestAnimationFrame","cancelAnimationFrame","t11","t12","t13","loading"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef, useState } from 'react';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { useGlobalStateObject } from './GlobalStateProvider';\n\nimport type SsrContext from './SsrContext';\n\nimport useGlobalState from './useGlobalState';\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.\n\n// NOTE: Here, and below it is important whether a loader and related\n// (re-)loading handlers return a promise or a value, as returning promises\n// mean the async mode, in which related global state values are updated\n// asynchronously (the new value comes into effect in a next rendering cycle),\n// while returning a non-promise value means a synchronous mode, in which\n// related global state values are updated immediately, within the current\n// rendering cycle.\n\nexport type AsyncDataLoaderT<DataT>\n = (oldData: DataT | null, meta: {\n abortSignal: AbortSignal;\n oldDataTimestamp: number;\n }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncDataReloaderT<DataT>\n = (loader?: AsyncDataLoaderT<DataT>) => Promise<void> | void;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: DataT | null;\n numRefs: number;\n operationId: string;\n timestamp: number;\n};\n\nexport type OperationIdT = `${'C' | 'S'}${string}`;\n\nexport function newAsyncDataEnvelope<DataT>(\n initialData: DataT | null = null,\n { numRefs = 0, timestamp = 0 } = {},\n): AsyncDataEnvelopeT<DataT> {\n return {\n data: initialData,\n numRefs,\n operationId: '',\n timestamp,\n };\n}\n\nexport type UseAsyncDataOptionsT = {\n deps?: unknown[];\n disabled?: boolean;\n garbageCollectAge?: number;\n maxage?: number;\n noSSR?: boolean;\n refreshAge?: number;\n};\n\nexport type UseAsyncDataResT<DataT> = {\n data: DataT | null;\n loading: boolean;\n reload: AsyncDataReloaderT<DataT>;\n set: (data: DataT | null) => void;\n timestamp: number;\n};\n\n/**\n * Writes data into the global state, and prints console messages in the debug\n * mode.\n */\nfunction setState<\n DataT,\n EnvT extends AsyncDataEnvelopeT<DataT>,\n>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n prevState: EnvT = gs.get<ForceT, EnvT>(path),\n) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path ?? ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n\n gs.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...prevState,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n}\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n gs.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = gs.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) setState(data, path, gs, state);\n}\n\nexport function loadAsyncData<\n StateT,\n PathT extends null | string | undefined,\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<StateT, SsrContext<StateT>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n): Promise<void> | void;\n\nexport function loadAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = unknown,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n): Promise<void> | void;\n\n/**\n * Executes the data loading operation.\n * @param path Data segment path inside the global state.\n * @param loader Data loader.\n * @param globalState The global state instance.\n * @param oldData Optional. Previously fetched data, currently stored in\n * the state, if already fetched by the caller; otherwise, they will be fetched\n * by the load() function itself.\n * @param opIdPrefix operationId prefix to use, which should be\n * 'C' at the client-side (default), or 'S' at the server-side (within SSR\n * context).\n * @return Resolves once the operation is done.\n * @ignore\n */\nexport function loadAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n\n // TODO: Should this parameter be just a binary flag (client or server),\n // and UUID always generated inside this function? Or do we need it in\n // the caller methods as well, in some cases (see useAsyncCollection()\n // use case as well).\n operationId: OperationIdT = `C${globalThis.crypto.randomUUID()}`,\n): Promise<void> | void {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState: async data (re-)loading. Path: \"${path ?? ''}\"`,\n );\n /* eslint-enable no-console */\n }\n\n const operationIdPath = path ? `${path}.operationId` : 'operationId';\n {\n const prevOperationId = globalState.get<ForceT, string>(operationIdPath);\n if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);\n }\n globalState.set<ForceT, string>(operationIdPath, operationId);\n\n let definedOld = old;\n if (!definedOld) {\n // TODO: Can we improve the typing, to avoid ForceT?\n const e = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path);\n definedOld = { data: e.data, timestamp: e.timestamp };\n }\n\n const controller = new AbortController();\n globalState.setAsyncDataAbortCallback(operationId, () => {\n controller.abort();\n });\n\n const dataOrPromise = loader(definedOld.data, {\n abortSignal: controller.signal,\n oldDataTimestamp: definedOld.timestamp,\n });\n\n if (dataOrPromise instanceof Promise) {\n return dataOrPromise.then((data) => {\n finalizeLoad(data, path, globalState, operationId);\n }).finally(() => {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n globalState.asyncDataLoadDone(operationId, false);\n });\n }\n\n finalizeLoad(dataOrPromise, path, globalState, operationId);\n return undefined;\n}\n\n/**\n * Resolves asynchronous data, and stores them at given `path` of global\n * state.\n */\n\nexport type DataInEnvelopeAtPathT<\n StateT,\n PathT extends null | string | undefined,\n> = Exclude<Extract<ValueAtPathT<StateT, PathT, void>, AsyncDataEnvelopeT<unknown>>['data'], null>;\n\n// TODO: Perhaps split the heap management to a dedicated hook,\n// as it is done inside useAsyncCollection().\ntype HeapT<DataT> = {\n // NOTE: These heap fields are necessary to make reload() and set() stable\n // functions.\n globalState: GlobalState<unknown>;\n loader: AsyncDataLoaderT<DataT>;\n path: null | string | undefined;\n};\n\nfunction useAsyncData<\n StateT,\n PathT extends null | string | undefined,\n\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n>(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<DataT>;\n\nfunction useAsyncData<\n Forced extends ForceT | LockT = LockT,\n DataT = void,\n>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n\nfunction useAsyncData<DataT>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<DataT>,\n options: UseAsyncDataOptionsT = {},\n): UseAsyncDataResT<DataT> {\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // Note: here we can't depend on useGlobalState() to init the initial value,\n // because that way we'll have issues with SSR (see details below).\n const globalState = useGlobalStateObject();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({\n globalState,\n loader,\n path,\n });\n\n useEffect(() => {\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n });\n\n // NOTE: State inititalizer function here helps to avoid ESLint warnings\n // about accessing references during the render.\n const [stable] = useState(() => ({\n reload: (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): Promise<void> | void => {\n const localLoader = customLoader ?? heap.loader;\n\n return loadAsyncData<ForceT, DataT>(\n heap.path,\n localLoader,\n heap.globalState,\n );\n },\n set: (data: DataT | null) => {\n setState(data, heap.path, heap.globalState);\n },\n }));\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = loadAsyncData<ForceT, DataT>(\n path,\n loader,\n globalState,\n {\n data: state.data,\n timestamp: state.timestamp,\n },\n `S${globalThis.crypto.randomUUID()}`,\n );\n\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n }\n\n const { disabled } = options;\n\n // This takes care about the client-side reference counting, and garbage\n // collection.\n //\n // Note: the Rules of Hook below are violated by conditional call to a hook,\n // but as the condition is actually server-side or client-side environment,\n // it is effectively non-conditional at the runtime.\n //\n // TODO: Though, maybe there is a way to refactor it into a cleaner code.\n // The same applies to other useEffect() hooks below.\n useEffect(() => {\n const numRefsPath = path ? `${path}.numRefs` : 'numRefs';\n if (!disabled) {\n const numRefs = globalState.get<ForceT, number>(numRefsPath);\n globalState.set<ForceT, number>(numRefsPath, numRefs + 1);\n }\n return () => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n );\n if (\n state2.numRefs === 1\n && garbageCollectAge < Date.now() - state2.timestamp\n ) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.log(\n `ReactGlobalState - useAsyncData garbage collected at path ${\n path ?? ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(path ?? '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n }, [disabled, garbageCollectAge, globalState, path]);\n\n // Note: a bunch of Rules of Hooks ignored belows because in our very\n // special case the otherwise wrong behavior is actually what we need.\n\n // Data loading and refreshing.\n useEffect(() => {\n if (!disabled) {\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path);\n\n const { deps } = options;\n if (\n // The hook is called with a list of dependencies, that mismatch\n // dependencies last used to retrieve the data at given path.\n (deps && globalState.hasChangedDependencies(path ?? '', deps))\n\n // Data at the path are stale, and are not being loaded.\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.startsWith('S'))\n )\n ) {\n if (!deps) globalState.dropDependencies(path ?? '');\n\n void loadAsyncData<ForceT, DataT>(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n const [stale, setStale] = useState<boolean>(\n () => maxage < Date.now() - localState.timestamp,\n );\n\n // TODO: Merge into the data-reloading effect above?\n useEffect(() => {\n const nowStale = maxage < Date.now() - localState.timestamp;\n const id = stale === nowStale ? null : requestAnimationFrame(() => {\n setStale(nowStale);\n });\n\n return () => {\n if (id !== null) cancelAnimationFrame(id);\n };\n });\n\n return {\n data: stale ? null : localState.data,\n loading: !!localState.operationId,\n reload: stable.reload,\n set: stable.set,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface LoadAsyncDataI<StateT> {\n <\n PathT extends null | string | undefined,\n DataT extends DataInEnvelopeAtPathT<\n StateT, PathT> = DataInEnvelopeAtPathT<StateT, PathT>,\n >(\n path: PathT,\n loader: AsyncDataLoaderT<DataT>,\n globalState: GlobalState<StateT, SsrContext<StateT>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n ): Promise<void> | void;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n globalState: GlobalState<unknown, SsrContext<unknown>>,\n old?: { data: DataT | null; timestamp: number },\n operationId?: OperationIdT,\n ): Promise<void> | void;\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseAsyncDataI<StateT> {\n <PathT extends null | string | undefined>(\n path: PathT,\n loader: AsyncDataLoaderT<DataInEnvelopeAtPathT<StateT, PathT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, PathT>>;\n\n <Forced extends ForceT | LockT = LockT, DataT = unknown>(\n path: null | string | undefined,\n loader: AsyncDataLoaderT<TypeLock<Forced, void, DataT>>,\n options?: UseAsyncDataOptionsT,\n ): UseAsyncDataResT<TypeLock<Forced, void, DataT>>;\n}\n"],"mappings":";AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,OAAO;AAEnD,SAASC,MAAM,QAAQ,sBAAsB;AAAC,SAGrCC,oBAAoB;AAAA,OAItBC,cAAc;AAAA,SAMnBC,eAAe,EACfC,WAAW;AAGb,OAAO,MAAMC,cAAc,GAAG,C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AA,OAAA8C,GAAA;IAAA9C,CAAA,OAAA+C,GAAA;EAAA;IAAAA,GAAA,GAAA/C,CAAA;EAAA;EAAA,OANM+C,GAMN;AAAA;AAGH,SAASpD,YAAY;;AAErB;;AAuBA","ignoreList":[]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"useGlobalState.js","names":["useEffect","useRef","useState","useSyncExternalStore","Emitter","useGlobalStateObject","cloneDeepForLog","isDebugMode","useGlobalState","path","initialValue","_ref$current","globalState","ref","stable","emitter","setter","value","rc","current","Error","newState","get","process","env","NODE_ENV","_rc$path","_rc$path2","console","groupCollapsed","log","groupEnd","set","prevValue","emit","subscribe","addListener","bind","initialState","watcher","nextValue","watch","unWatch"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport {\n type Dispatch,\n type SetStateAction,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { useGlobalStateObject } from './GlobalStateProvider';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = Dispatch<SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype CurrentT = {\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n prevValue: unknown;\n};\n\ntype StableT = {\n emitter: Emitter<[]>;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>,\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>,\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initialValue?: ValueOrInitializerT<any>,\n\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): UseGlobalStateResT<any> {\n const globalState = useGlobalStateObject();\n\n const ref = useRef<CurrentT>(null);\n\n const [stable] = useState<StableT>(() => {\n const emitter = new Emitter();\n const setter = (value: unknown) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const newState = typeof value === 'function'\n ? (value as (x: unknown) => unknown)(\n rc.globalState.get<ForceT, unknown>(rc.path),\n ) : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc.path ?? ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set<ForceT, unknown>(rc.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc.prevValue) emitter.emit();\n };\n const subscribe = emitter.addListener.bind(emitter);\n return { emitter, setter, subscribe };\n });\n\n const value = useSyncExternalStore(\n stable.subscribe,\n () => globalState.get<ForceT, unknown>(path, { initialValue }),\n\n () => globalState.get<ForceT, unknown>(\n path,\n { initialState: true, initialValue },\n ),\n );\n\n ref.current ??= {\n globalState,\n path,\n prevValue: value,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n path,\n prevValue: ref.current!.prevValue,\n };\n\n const watcher = () => {\n const nextValue = globalState.get<ForceT, unknown>(path);\n if (ref.current!.prevValue !== nextValue) {\n ref.current!.prevValue = nextValue;\n stable.emitter.emit();\n }\n };\n\n globalState.watch(watcher);\n watcher();\n\n return () => {\n globalState.unWatch(watcher);\n };\n }, [globalState, stable.emitter, path]);\n\n return [value, stable.setter];\n}\n\nexport default useGlobalState;\n\n// TODO: Revise.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":"AAAA;;AAEA,SAGEA,SAAS,EACTC,MAAM,EACNC,QAAQ,EACRC,oBAAoB,QACf,OAAO;AAEd,SAASC,OAAO,QAAQ,sBAAsB;AAAC,SAGtCC,oBAAoB;AAAA,SAQ3BC,eAAe,EACfC,WAAW;AAqBb;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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CAAC,CAAC;IAET,OAAO,MAAM;MACX3B,WAAW,CAAC8B,OAAO,CAACH,OAAO,CAAC;IAC9B,CAAC;EACH,CAAC,EAAE,CAAC3B,WAAW,EAAEE,MAAM,CAACC,OAAO,EAAEN,IAAI,CAAC,CAAC;EAEvC,OAAO,CAACQ,OAAK,EAAEH,MAAM,CAACE,MAAM,CAAC;AAC/B;AAEA,eAAeR,cAAc;;AAE7B;AACA","ignoreList":[]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","names":["cloneDeep","isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","cloneDeepBailKeys","Set","cloneDeepForLog","value","key","has","console","warn","start","Date","now","res","time","add","areEqual","a","b","Object","entries"],"sources":["../../src/utils.ts"],"sourcesContent":["import type { GetFieldType } from 'lodash';\nimport { cloneDeep } from 'lodash-es';\n\nimport type { ObjectKey } from '@dr.pogodin/js-utils';\n\nexport type CallbackT = () => void;\n\n// TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils\n// lib.\n\nexport declare const force: unique symbol;\nexport declare const lock: unique symbol;\n\nexport type ForceT = typeof force;\nexport type LockT = typeof lock;\n\nexport type TypeLock<\n Unlocked extends ForceT | LockT,\n\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents\n LockedT extends never | void,\n UnlockedT,\n> = Unlocked extends ForceT ? UnlockedT : LockedT;\n\n/**\n * Given the type of state, `StateT`, and the type of state path, `PathT`,\n * it evaluates the type of value at that path of the state, if it can be\n * evaluated from the path type (it is possible when `PathT` is a string\n * literal type, and `StateT` elements along this path have appropriate\n * types); otherwise it falls back to the specified `UnknownT` type,\n * which should be set either `never` (for input arguments), or `void`\n * (for return types) - `never` and `void` in those places forbid assignments,\n * and are not auto-inferred to more permissible types.\n *\n * BEWARE: When StateT is any the construct resolves to any for any string\n * paths.\n */\nexport type ValueAtPathT<\n StateT,\n PathT extends null | string | undefined,\n\n // TODO: Revise later.\n // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents, @typescript-eslint/no-invalid-void-type\n UnknownT extends never | undefined | void,\n> = unknown extends StateT\n ? UnknownT\n : string extends PathT\n ? UnknownT\n : PathT extends null | undefined\n ? StateT\n : GetFieldType<StateT, PathT> extends undefined\n ? UnknownT : GetFieldType<StateT, PathT>;\n\nexport type ValueOrInitializerT<ValueT> = (() => ValueT) | ValueT;\n\n/**\n * Returns 'true' if debug logging should be performed; 'false' otherwise.\n *\n * BEWARE: The actual safeguards for the debug logging still should read\n * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n * // Some debug logging\n * }\n * to ensure that debug code is stripped out by Webpack in production mode.\n *\n * @returns\n * @ignore\n */\nexport function isDebugMode(): boolean {\n try {\n return process.env.NODE_ENV !== 'production'\n && !!process.env.REACT_GLOBAL_STATE_DEBUG;\n } catch {\n return false;\n }\n}\n\nconst cloneDeepBailKeys = new Set<string>();\n\n/**\n * Deep-clones given value for logging purposes, or returns the value itself\n * if the previous clone attempt, with the same key, took more than 300ms\n * (to avoid situations when large payload in the global state slows down\n * development versions of the app due to the logging overhead).\n */\nexport function cloneDeepForLog<T>(value: T, key: string = ''): T {\n if (cloneDeepBailKeys.has(key)) {\n // eslint-disable-next-line no-console\n console.warn(`The logged value won't be clonned (key \"${key}\").`);\n return value;\n }\n\n const start = Date.now();\n const res = cloneDeep(value);\n const time = Date.now() - start;\n if (time > 300) {\n // eslint-disable-next-line no-console\n console.warn(`${time}ms spent to clone the logged value (key \"${key}\").`);\n cloneDeepBailKeys.add(key);\n }\n\n return res;\n}\n\nexport function areEqual<K extends ObjectKey>(\n a: Record<K, boolean>,\n b: Record<K, boolean>,\n): boolean {\n for (const [key, value] of Object.entries(a)) {\n if (b[key as K] !== value) return false;\n }\n for (const [key, value] of Object.entries(b)) {\n if (a[key as K] !== value) return false;\n }\n return true;\n}\n"],"mappings":"AACA,SAASA,SAAS,QAAQ,WAAW;;AAMrC;AACA;;AAiBA;AACA;AACA;AACA;AACA;AAC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ACC,GAAG,EAAED,KAAK,CAAC,IAAIc,MAAM,CAACC,OAAO,CAACF,CAAC,CAAC,EAAE;IAC5C,IAAID,CAAC,CAACX,GAAG,CAAM,KAAKD,KAAK,EAAE,OAAO,KAAK;EACzC;EACA,OAAO,IAAI;AACb","ignoreList":[]}
package/eslint.config.mjs DELETED
@@ -1,19 +0,0 @@
1
- /* eslint-disable import/no-extraneous-dependencies */
2
-
3
- import { defineConfig } from 'eslint/config';
4
- import eslintConfigs from '@dr.pogodin/eslint-configs';
5
-
6
- export default defineConfig([
7
- { ignores: [
8
- 'build/',
9
- 'docs/build/',
10
- 'docs/.docusaurus/',
11
- ] },
12
- eslintConfigs.configs.javascript,
13
- eslintConfigs.configs.typescript,
14
- eslintConfigs.configs.react,
15
- {
16
- extends: [eslintConfigs.configs.jest],
17
- files: ['__tests__/**'],
18
- },
19
- ]);
package/tsconfig.json DELETED
@@ -1,22 +0,0 @@
1
- {
2
- "extends": "@tsconfig/recommended",
3
-
4
- // TODO: This actually breaks VSCode code analysis inside ts-types. We should
5
- // do no exclusion here, but provide a different TS config file for Jest tests
6
- // to use.
7
- "exclude": ["__tests__/ts-types"],
8
-
9
- "compilerOptions": {
10
- "declaration": true,
11
- "jsx": "react-jsx",
12
- "module": "ESNext",
13
- "moduleResolution": "bundler",
14
- "noUncheckedIndexedAccess": true,
15
- "outDir": "build",
16
- "paths": {
17
- "*": ["./*"]
18
- },
19
- "types": ["node"],
20
- "verbatimModuleSyntax": true
21
- }
22
- }
@@ -1,14 +0,0 @@
1
- {
2
- "extends": "@tsconfig/recommended",
3
- "include": ["src", "types.d.ts"],
4
- "compilerOptions": {
5
- "declaration": true,
6
- "emitDeclarationOnly": true,
7
- "jsx": "react-jsx",
8
- "module": "ESNext",
9
- "moduleResolution": "Node",
10
- "outDir": "build/types",
11
- "strict": true,
12
- "verbatimModuleSyntax": true,
13
- }
14
- }
package/tstyche.json DELETED
@@ -1,6 +0,0 @@
1
- {
2
- "$schema": "https://tstyche.org/schemas/config.json",
3
- "checkDeclarationFiles": true,
4
- "checkSuppressedErrors": true,
5
- "testFileMatch": ["__tests__/**/*.{ts,tsx}"]
6
- }
File without changes
File without changes
File without changes