@dr.pogodin/react-global-state 0.18.0 → 0.19.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.
Files changed (57) hide show
  1. package/LICENSE.md +1 -1
  2. package/build/{module → code}/GlobalState.js +15 -5
  3. package/build/code/GlobalState.js.map +1 -0
  4. package/build/{module → code}/GlobalStateProvider.js +18 -18
  5. package/build/code/GlobalStateProvider.js.map +1 -0
  6. package/build/code/SsrContext.js.map +1 -0
  7. package/build/{module → code}/index.js +9 -3
  8. package/build/code/index.js.map +1 -0
  9. package/build/{module → code}/useAsyncCollection.js +60 -27
  10. package/build/code/useAsyncCollection.js.map +1 -0
  11. package/build/{module → code}/useAsyncData.js +19 -17
  12. package/build/code/useAsyncData.js.map +1 -0
  13. package/build/{module → code}/useGlobalState.js +25 -8
  14. package/build/code/useGlobalState.js.map +1 -0
  15. package/build/{module → code}/utils.js +1 -1
  16. package/build/code/utils.js.map +1 -0
  17. package/build/types/GlobalState.d.ts +2 -2
  18. package/build/types/GlobalStateProvider.d.ts +3 -3
  19. package/build/types/SsrContext.d.ts +3 -3
  20. package/build/types/useAsyncCollection.d.ts +4 -6
  21. package/build/types/useAsyncData.d.ts +2 -2
  22. package/build/types/utils.d.ts +2 -3
  23. package/eslint.config.mjs +19 -0
  24. package/package.json +25 -41
  25. package/build/common/GlobalState.js +0 -279
  26. package/build/common/GlobalState.js.map +0 -1
  27. package/build/common/GlobalStateProvider.js +0 -97
  28. package/build/common/GlobalStateProvider.js.map +0 -1
  29. package/build/common/SsrContext.js +0 -15
  30. package/build/common/SsrContext.js.map +0 -1
  31. package/build/common/index.js +0 -84
  32. package/build/common/index.js.map +0 -1
  33. package/build/common/useAsyncCollection.js +0 -242
  34. package/build/common/useAsyncCollection.js.map +0 -1
  35. package/build/common/useAsyncData.js +0 -233
  36. package/build/common/useAsyncData.js.map +0 -1
  37. package/build/common/useGlobalState.js +0 -134
  38. package/build/common/useGlobalState.js.map +0 -1
  39. package/build/common/utils.js +0 -91
  40. package/build/common/utils.js.map +0 -1
  41. package/build/module/GlobalState.js.map +0 -1
  42. package/build/module/GlobalStateProvider.js.map +0 -1
  43. package/build/module/SsrContext.js.map +0 -1
  44. package/build/module/index.js.map +0 -1
  45. package/build/module/useAsyncCollection.js.map +0 -1
  46. package/build/module/useAsyncData.js.map +0 -1
  47. package/build/module/useGlobalState.js.map +0 -1
  48. package/build/module/utils.js.map +0 -1
  49. package/src/GlobalState.ts +0 -342
  50. package/src/GlobalStateProvider.tsx +0 -117
  51. package/src/SsrContext.ts +0 -11
  52. package/src/index.ts +0 -84
  53. package/src/useAsyncCollection.ts +0 -471
  54. package/src/useAsyncData.ts +0 -362
  55. package/src/useGlobalState.ts +0 -225
  56. package/src/utils.ts +0 -116
  57. /package/build/{module → code}/SsrContext.js +0 -0
package/LICENSE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # MIT License
2
2
 
3
- _Copyright © 2019–2023, Dr. Sergey Pogodin_
3
+ _Copyright © 2019–2025, 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
@@ -132,9 +132,7 @@ export default class GlobalState {
132
132
  _classPrivateFieldSet(_nextNotifierId, this, setTimeout(() => {
133
133
  _classPrivateFieldSet(_nextNotifierId, this, undefined);
134
134
  const watchers = [..._classPrivateFieldGet(_watchers, this)];
135
- for (let i = 0; i < watchers.length; ++i) {
136
- watchers[i]();
137
- }
135
+ for (const watcher of watchers) watcher();
138
136
  }));
139
137
  }
140
138
  }
@@ -193,7 +191,10 @@ export default class GlobalState {
193
191
  if (res !== undefined || (opts === null || opts === void 0 ? void 0 : opts.initialValue) === undefined) return res;
194
192
  const iv = opts.initialValue;
195
193
  res = isFunction(iv) ? iv() : iv;
196
- if (!(opts !== null && opts !== void 0 && opts.initialState) || this.get(path) === undefined) {
194
+
195
+ // TODO: Revise.
196
+ // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
197
+ if (!opts.initialState || this.get(path) === undefined) {
197
198
  this.set(path, res);
198
199
  }
199
200
  return res;
@@ -214,15 +215,24 @@ export default class GlobalState {
214
215
 
215
216
  set(path, value) {
216
217
  if (isNil(path)) return this.setEntireState(value);
218
+
219
+ // TODO: Revise.
220
+ // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression
217
221
  if (value !== this.get(path)) {
218
222
  const root = {
219
223
  state: _classPrivateFieldGet(_currentState, this)
220
224
  };
221
225
  let segIdx = 0;
226
+
227
+ // TODO: It is not 100% correct, as `pos` can be an array, or any other
228
+ // value as we travel through the state tree. To simplify the typing for
229
+ // now, I guess, we can go with this record type, though.
222
230
  let pos = root;
223
231
  const pathSegments = toPath(`state.${path}`);
224
232
  for (; segIdx < pathSegments.length - 1; segIdx += 1) {
225
233
  const seg = pathSegments[segIdx];
234
+
235
+ // TODO: Revise: Typing is not quite correct here, but it works fine in the runtime.
226
236
  const next = pos[seg];
227
237
  if (Array.isArray(next)) pos[seg] = [...next];else if (isObject(next)) pos[seg] = {
228
238
  ...next
@@ -274,7 +284,7 @@ export default class GlobalState {
274
284
  watch(callback) {
275
285
  if (this.ssrContext) throw new Error(ERR_NO_SSR_WATCH);
276
286
  const watchers = _classPrivateFieldGet(_watchers, this);
277
- if (watchers.indexOf(callback) < 0) {
287
+ if (!watchers.includes(callback)) {
278
288
  watchers.push(callback);
279
289
  }
280
290
  }
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalState.js","names":["get","isFunction","isObject","isNil","set","toPath","cloneDeepForLog","isDebugMode","ERR_NO_SSR_WATCH","_asyncDataAbortCallbacks","WeakMap","_dependencies","_initialState","_watchers","_nextNotifierId","_currentState","GlobalState","constructor","initialState","ssrContext","_classPrivateFieldInitSpec","_classPrivateFieldSet","dirty","pending","state","_classPrivateFieldGet","process","env","NODE_ENV","msg","console","groupCollapsed","log","groupEnd","numAsyncDataAbortCallbacks","Object","keys","length","asyncDataLoadDone","opid","aborted","_classPrivateFieldGet2","_classPrivateFieldGet3","call","dropDependencies","path","hasChangedDependencies","deps","prevDeps","changed","i","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 {\n get,\n isFunction,\n isObject,\n isNil,\n set,\n toPath,\n} from 'lodash';\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: Record<string, () => void> = {};\n\n #dependencies: Record<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 Object.keys(this.#asyncDataAbortCallbacks).length;\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[opid]?.();\n delete this.#asyncDataAbortCallbacks[opid];\n }\n\n /**\n * Drops the record of dependencies, if any, for the given path.\n */\n dropDependencies(path: string): void {\n delete this.#dependencies[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[path];\n let changed = !prevDeps || prevDeps.length !== deps.length;\n for (let i = 0; !changed && i < deps.length; ++i) {\n changed = prevDeps![i] !== deps[i];\n }\n this.#dependencies[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 = isFunction(iv) ? iv() : 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[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 (isNil(path)) {\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 = isFunction(iv) ? iv() : 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 (isNil(path)) 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 (isObject(next)) 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,SACEA,GAAG,EACHC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,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AACA;EACEiB,OAAOA,CAACC,QAAmB,EAAQ;IACjC,IAAI,IAAI,CAAC1D,UAAU,EAAE,MAAM,IAAI2D,KAAK,CAACtE,gBAAgB,CAAC;IAEtD,MAAMsD,QAAQ,GAAGrC,qBAAA,CAAKZ,SAAS,EAAd,IAAa,CAAC;IAC/B,MAAMwD,GAAG,GAAGP,QAAQ,CAACiB,OAAO,CAACF,QAAQ,CAAC;IACtC,IAAIR,GAAG,IAAI,CAAC,EAAE;MACZP,QAAQ,CAACO,GAAG,CAAC,GAAGP,QAAQ,CAACA,QAAQ,CAACzB,MAAM,GAAG,CAAC,CAAE;MAC9CyB,QAAQ,CAACkB,GAAG,CAAC,CAAC;IAChB;EACF;;EAEA;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACEC,KAAKA,CAACJ,QAAmB,EAAQ;IAC/B,IAAI,IAAI,CAAC1D,UAAU,EAAE,MAAM,IAAI2D,KAAK,CAACtE,gBAAgB,CAAC;IAEtD,MAAMsD,QAAQ,GAAGrC,qBAAA,CAAKZ,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":[]}
@@ -11,14 +11,13 @@ const Context = /*#__PURE__*/createContext(null);
11
11
  * @return
12
12
  */
13
13
  export function getGlobalState() {
14
- // Here Rules of Hooks are violated because "getGlobalState()" does not follow
15
- // convention that hook names should start with use... This is intentional in
16
- // our case, as getGlobalState() hook is intended for advance scenarious,
17
- // while the normal interaction with the global state should happen via
18
- // another hook, useGlobalState().
19
- /* eslint-disable react-hooks/rules-of-hooks */
14
+ // TODO: Think about it: on one hand we on purpose called this function
15
+ // as getGlobalState(), so that ppl looking for the state hook prefer using
16
+ // useGlobalState(), while this getGlobalState() is reserved for nieche cases;
17
+ // on the other hand, perhaps we can rename it into useSomething, to both
18
+ // follow conventions, and to keep stuff clearly named at the same time.
19
+ // eslint-disable-next-line react-hooks/rules-of-hooks
20
20
  const globalState = use(Context);
21
- /* eslint-enable react-hooks/rules-of-hooks */
22
21
  if (!globalState) throw new Error('Missing GlobalStateProvider');
23
22
  return globalState;
24
23
  }
@@ -65,24 +64,25 @@ const GlobalStateProvider = _ref => {
65
64
  children,
66
65
  ...rest
67
66
  } = _ref;
68
- const state = useRef(undefined);
69
- if (!state.current) {
70
- // NOTE: The last part of condition, "&& rest.stateProxy", is needed for
71
- // graceful compatibility with JavaScript - if "undefined" stateProxy value
72
- // is given, we want to follow the second branch, which creates a new
73
- // GlobalState with whatever intiialState given.
74
- if ('stateProxy' in rest && rest.stateProxy) {
75
- if (rest.stateProxy === true) state.current = getGlobalState();else state.current = rest.stateProxy;
76
- } else {
67
+ const localStateRef = useRef(undefined);
68
+ let state;
69
+ // TODO: Revise.
70
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
71
+ if ('stateProxy' in rest && rest.stateProxy) {
72
+ localStateRef.current = undefined;
73
+ state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;
74
+ } else {
75
+ if (!localStateRef.current) {
77
76
  const {
78
77
  initialState,
79
78
  ssrContext
80
79
  } = rest;
81
- state.current = new GlobalState(isFunction(initialState) ? initialState() : initialState, ssrContext);
80
+ localStateRef.current = new GlobalState(isFunction(initialState) ? initialState() : initialState, ssrContext);
82
81
  }
82
+ state = localStateRef.current;
83
83
  }
84
84
  return /*#__PURE__*/_jsx(Context, {
85
- value: state.current,
85
+ value: state,
86
86
  children: children
87
87
  });
88
88
  };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","use","useRef","GlobalState","jsx","_jsx","Context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","arguments","length","undefined","ssrContext","GlobalStateProvider","_ref","children","rest","localStateRef","state","stateProxy","current","initialState","value"],"sources":["../../src/GlobalStateProvider.tsx"],"sourcesContent":["import { isFunction } from 'lodash';\n\nimport {\n type ReactNode,\n createContext,\n use,\n useRef,\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 * Gets {@link GlobalState} instance from the context. In most cases\n * you should use {@link useGlobalState}, and other hooks to interact with\n * the global state, instead of accessing it directly.\n * @return\n */\nexport function getGlobalState<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): GlobalState<StateT, SsrContextT> {\n // TODO: Think about it: on one hand we on purpose called this function\n // as getGlobalState(), so that ppl looking for the state hook prefer using\n // useGlobalState(), while this getGlobalState() is reserved for nieche cases;\n // on the other hand, perhaps we can rename it into useSomething, to both\n // follow conventions, and to keep stuff clearly named at the same time.\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const globalState = use(Context);\n if (!globalState) throw new Error('Missing GlobalStateProvider');\n return globalState as GlobalState<StateT, SsrContextT>;\n}\n\n/**\n * @category Hooks\n * @desc Gets SSR context.\n * @param throwWithoutSsrContext If `true` (default),\n * this hook will throw if no SSR context is attached to the global state;\n * set `false` to not throw in such case. In either case the hook will throw\n * if the {@link &lt;GlobalStateProvider&gt;} (hence the state) is missing.\n * @returns SSR context.\n * @throws\n * - If current component has no parent {@link &lt;GlobalStateProvider&gt;}\n * in the rendered React tree.\n * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached\n * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.\n */\nexport function getSsrContext<\n SsrContextT extends SsrContext<unknown>,\n>(\n throwWithoutSsrContext = true,\n): SsrContextT | undefined {\n const { ssrContext } = getGlobalState<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> = {\n children?: ReactNode;\n} & (NewStateProps<StateT, SsrContextT> | {\n stateProxy: true | GlobalState<StateT, SsrContextT>;\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 const localStateRef = useRef<GST>(undefined);\n let state: GST;\n // TODO: Revise.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if ('stateProxy' in rest && rest.stateProxy) {\n localStateRef.current = undefined;\n state = rest.stateProxy === true ? getGlobalState() : rest.stateProxy;\n } else {\n if (!localStateRef.current) {\n const {\n initialState,\n ssrContext,\n } = rest as NewStateProps<StateT, SsrContextT>;\n localStateRef.current = new GlobalState(\n isFunction(initialState) ? initialState() : initialState,\n ssrContext,\n );\n }\n state = localStateRef.current;\n }\n return <Context value={state}>{children}</Context>;\n};\n\nexport default GlobalStateProvider;\n"],"mappings":"AAAA,SAASA,UAAU,QAAQ,QAAQ;AAEnC,SAEEC,aAAa,EACbC,GAAG,EACHC,MAAM,QACD,OAAO;AAEd,OAAOC,WAAW;AAAsB,SAAAC,GAAA,IAAAC,IAAA;AAKxC,MAAMC,OAAO,gBAAGN,aAAa,CAA8B,IAAI,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASO,cAAcA,CAAA,EAGQ;EACpC;EACA;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GAAGA,YAAY,EACxDT,UACF,CAAC;IACH;IACAM,KAAK,GAAGD,aAAa,CAACG,OAAO;EAC/B;EACA,oBAAOlB,IAAA,CAACC,OAAO;IAACmB,KAAK,EAAEJ,KAAM;IAAAH,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAED,eAAeF,mBAAmB","ignoreList":[]}
@@ -0,0 +1 @@
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":[]}
@@ -5,13 +5,19 @@ import useAsyncCollection from "./useAsyncCollection";
5
5
  import { newAsyncDataEnvelope, useAsyncData } from "./useAsyncData";
6
6
  import useGlobalState from "./useGlobalState";
7
7
  export { getGlobalState, getSsrContext, GlobalState, GlobalStateProvider, newAsyncDataEnvelope, SsrContext, useAsyncCollection, useAsyncData, useGlobalState };
8
+
9
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
10
+
8
11
  const api = {
9
- getGlobalState,
10
- getSsrContext,
12
+ // TODO: I am puzzled, why ESLint eforces this sorting order as alphabetical?
13
+ // Perhaps, we should tune something in its config settings, as it seems to mix
14
+ // some extra sorting logic, which I am not sure I like.
11
15
  GlobalState,
12
16
  GlobalStateProvider,
13
- newAsyncDataEnvelope,
14
17
  SsrContext,
18
+ getGlobalState,
19
+ getSsrContext,
20
+ newAsyncDataEnvelope,
15
21
  useAsyncCollection,
16
22
  useAsyncData,
17
23
  useGlobalState
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\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 UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT, AsyncCollectionT } 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 type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\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 getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>;\n GlobalState: typeof GlobalState<StateT, SsrContextT>;\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>;\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope;\n SsrContext: typeof SsrContext<StateT>;\n useAsyncCollection: UseAsyncCollectionI<StateT>;\n useAsyncData: UseAsyncDataI<StateT>;\n useGlobalState: UseGlobalStateI<StateT>;\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 getGlobalState,\n getSsrContext,\n newAsyncDataEnvelope,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>(): API<StateT, SsrContextT> {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"AAAA,OAAOA,WAAW;AAElB,OAAOC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAGf,OAAOC,UAAU;AAEjB,OAAOC,kBAAkB;AAKzB,SAOEC,oBAAoB,EACpBC,YAAY;AAGd,OAAOC,cAAc;AAQrB,SAOEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBK,oBAAoB,EACpBF,UAAU,EACVC,kBAAkB,EAClBE,YAAY,EACZC,cAAc;;AAGhB;;AAgBA,MAAMC,GAAG,GAAG;EACV;EACA;EACA;EACAT,WAAW;EACXC,mBAAmB;EACnBG,UAAU;EACVF,cAAc;EACdC,aAAa;EACbG,oBAAoB;EACpBD,kBAAkB;EAClBE,YAAY;EACZC;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAGL;EAC5B,OAAOD,GAAG;AACZ","ignoreList":[]}
@@ -18,8 +18,7 @@ function gcOnWithhold(ids, path, gs) {
18
18
  const collection = {
19
19
  ...gs.get(path)
20
20
  };
21
- for (let i = 0; i < ids.length; ++i) {
22
- const id = ids[i];
21
+ for (const id of ids) {
23
22
  let envelope = collection[id];
24
23
  if (envelope) envelope = {
25
24
  ...envelope,
@@ -33,8 +32,8 @@ function gcOnWithhold(ids, path, gs) {
33
32
  }
34
33
  function idsToStringSet(ids) {
35
34
  const res = new Set();
36
- for (let i = 0; i < ids.length; ++i) {
37
- res.add(ids[i].toString());
35
+ for (const id of ids) {
36
+ res.add(id.toString());
38
37
  }
39
38
  return res;
40
39
  }
@@ -51,8 +50,7 @@ function gcOnRelease(ids, path, gs, gcAge) {
51
50
  const now = Date.now();
52
51
  const idSet = idsToStringSet(ids);
53
52
  const collection = {};
54
- for (let i = 0; i < entries.length; ++i) {
55
- const [id, envelope] = entries[i];
53
+ for (const [id, envelope] of entries) {
56
54
  if (envelope) {
57
55
  const toBeReleased = idSet.has(id);
58
56
  let {
@@ -75,7 +73,7 @@ function gcOnRelease(ids, path, gs, gcAge) {
75
73
  function normalizeIds(idOrIds) {
76
74
  if (Array.isArray(idOrIds)) {
77
75
  const res = [...idOrIds];
78
- res.sort();
76
+ res.sort((a, b) => a.toString().localeCompare(b.toString()));
79
77
  return res;
80
78
  }
81
79
  return [idOrIds];
@@ -97,25 +95,45 @@ function useHeap(ids, path, loader, gs) {
97
95
  // Initialization.
98
96
  const reload = async customLoader => {
99
97
  const heap2 = ref.current;
100
- const localLoader = customLoader || heap2.loader;
98
+ const localLoader = customLoader !== null && customLoader !== void 0 ? customLoader : heap2.loader;
99
+ // TODO: Revise - not sure all related typing is 100% correct,
100
+ // thus let's keep this runtime assertion.
101
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
101
102
  if (!localLoader || !heap2.globalState || !heap2.ids) {
102
103
  throw Error('Internal error');
103
104
  }
104
- for (let i = 0; i < heap2.ids.length; ++i) {
105
- const id = heap2.ids[i];
105
+ for (const id of heap2.ids) {
106
106
  const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;
107
-
108
- // eslint-disable-next-line no-await-in-loop
109
- await load(itemPath, (oldData, meta) => localLoader(id, oldData, meta), heap2.globalState);
107
+ await load(itemPath,
108
+ // TODO: Revise! Most probably we don't have fully correct loader
109
+ // typing, as it may return either promise or value, and those two
110
+ // cases call for different runtime behavior, which in turns only
111
+ // happens if the outer function on the next line matches the same
112
+ // async / sync signature.
113
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
114
+ (oldData, meta) => localLoader(id, oldData, meta), heap2.globalState);
110
115
  }
111
116
  };
112
117
  heap = {
113
118
  globalState: gs,
114
119
  ids,
115
- path,
116
120
  loader,
121
+ path,
117
122
  reload,
118
- reloadSingle: customLoader => ref.current.reload(customLoader && function (id) {
123
+ // TODO: Revise! Most probably we don't have fully correct loader
124
+ // typing, as it may return either promise or value, and those two
125
+ // cases call for different runtime behavior, which in turns only
126
+ // happens if the outer function on the next line matches the same
127
+ // async / sync signature.
128
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
129
+ reloadSingle: customLoader => ref.current.reload(
130
+ // TODO: Revise! Most probably we don't have fully correct loader
131
+ // typing, as it may return either promise or value, and those two
132
+ // cases call for different runtime behavior, which in turns only
133
+ // happens if the outer function on the next line matches the same
134
+ // async / sync signature.
135
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
136
+ customLoader && function (id) {
119
137
  for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
120
138
  args[_key - 1] = arguments[_key];
121
139
  }
@@ -135,6 +153,7 @@ function useHeap(ids, path, loader, gs) {
135
153
  // TODO: This is largely similar to useAsyncData() logic, just more generic.
136
154
  // Perhaps, a bunch of logic blocks can be split into stand-alone functions,
137
155
  // and reused in both hooks.
156
+ // eslint-disable-next-line complexity
138
157
  function useAsyncCollection(idOrIds, path, loader) {
139
158
  var _options$maxage, _options$refreshAge, _options$garbageColle;
140
159
  let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
@@ -148,14 +167,20 @@ function useAsyncCollection(idOrIds, path, loader) {
148
167
  // Server-side logic.
149
168
  if (globalState.ssrContext && !options.noSSR) {
150
169
  const operationId = `S${uuid()}`;
151
- for (let i = 0; i < ids.length; ++i) {
152
- const id = ids[i];
170
+ for (const id of ids) {
153
171
  const itemPath = path ? `${path}.${id}` : `${id}`;
154
172
  const state = globalState.get(itemPath, {
155
173
  initialValue: newAsyncDataEnvelope()
156
174
  });
157
175
  if (!state.timestamp && !state.operationId) {
158
- globalState.ssrContext.pending.push(load(itemPath, function () {
176
+ globalState.ssrContext.pending.push(
177
+ // TODO: Revise! Most probably we don't have fully correct loader
178
+ // typing, as it may return either promise or value, and those two
179
+ // cases call for different runtime behavior, which in turns only
180
+ // happens if the outer function on the next line matches the same
181
+ // async / sync signature.
182
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
183
+ load(itemPath, function () {
159
184
  for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
160
185
  args[_key2] = arguments[_key2];
161
186
  }
@@ -178,7 +203,9 @@ function useAsyncCollection(idOrIds, path, loader) {
178
203
  useEffect(() => {
179
204
  // eslint-disable-line react-hooks/rules-of-hooks
180
205
  gcOnWithhold(ids, path, globalState);
181
- return () => gcOnRelease(ids, path, globalState, garbageCollectAge);
206
+ return () => {
207
+ gcOnRelease(ids, path, globalState, garbageCollectAge);
208
+ };
182
209
 
183
210
  // `ids` are represented in the dependencies array by `idsHash` value,
184
211
  // as useEffect() hook requires a constant size of dependencies array.
@@ -191,20 +218,23 @@ function useAsyncCollection(idOrIds, path, loader) {
191
218
  // Data loading and refreshing.
192
219
  useEffect(() => {
193
220
  // eslint-disable-line react-hooks/rules-of-hooks
194
- (async () => {
195
- for (let i = 0; i < ids.length; ++i) {
221
+ void (async () => {
222
+ for (const id of ids) {
196
223
  var _state2$timestamp;
197
- const id = ids[i];
198
224
  const itemPath = path ? `${path}.${id}` : `${id}`;
199
225
  const state2 = globalState.get(itemPath);
200
226
  const {
201
227
  deps
202
228
  } = options;
203
- if (deps && globalState.hasChangedDependencies(itemPath, 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.charAt(0) === 'S')) {
229
+ if (deps && globalState.hasChangedDependencies(itemPath, 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'))) {
204
230
  var _state2$timestamp2;
205
231
  if (!deps) globalState.dropDependencies(itemPath);
206
- // eslint-disable-next-line no-await-in-loop
207
- await load(itemPath, function (old) {
232
+ await load(itemPath,
233
+ // TODO: I guess, the loader is not correctly typed here -
234
+ // it can be synchronous, and in that case the following method
235
+ // should be kept synchronous to not alter the sync logic.
236
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
237
+ function (old) {
208
238
  for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
209
239
  args[_key3 - 1] = arguments[_key3];
210
240
  }
@@ -221,6 +251,7 @@ function useAsyncCollection(idOrIds, path, loader) {
221
251
  const [localState] = useGlobalState(path, {});
222
252
  if (!Array.isArray(idOrIds)) {
223
253
  var _e$timestamp, _e$data;
254
+ // TODO: Revise related typings!
224
255
  const e = localState[idOrIds];
225
256
  const timestamp = (_e$timestamp = e === null || e === void 0 ? void 0 : e.timestamp) !== null && _e$timestamp !== void 0 ? _e$timestamp : 0;
226
257
  return {
@@ -236,9 +267,9 @@ function useAsyncCollection(idOrIds, path, loader) {
236
267
  reload: heap.reload,
237
268
  timestamp: Number.MAX_VALUE
238
269
  };
239
- for (let i = 0; i < ids.length; ++i) {
270
+ for (const id of ids) {
240
271
  var _e$timestamp2, _e$data2;
241
- const id = ids[i];
272
+ // TODO: Revise related typing. Should `localState` have a more specific type?
242
273
  const e = localState[id];
243
274
  const loading = !!(e !== null && e !== void 0 && e.operationId);
244
275
  const timestamp = (_e$timestamp2 = e === null || e === void 0 ? void 0 : e.timestamp) !== null && _e$timestamp2 !== void 0 ? _e$timestamp2 : 0;
@@ -253,4 +284,6 @@ function useAsyncCollection(idOrIds, path, loader) {
253
284
  return res;
254
285
  }
255
286
  export default useAsyncCollection;
287
+
288
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
256
289
  //# sourceMappingURL=useAsyncCollection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAsyncCollection.js","names":["useEffect","useRef","v4","uuid","getGlobalState","DEFAULT_MAXAGE","load","newAsyncDataEnvelope","useGlobalState","hash","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","sort","a","b","localeCompare","useHeap","loader","ref","undefined","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","oldData","meta","reloadSingle","_len","arguments","length","args","_key","useAsyncCollection","_options$maxage","_options$refreshAge","_options$garbageColle","options","maxage","refreshAge","garbageCollectAge","ssrContext","noSSR","operationId","state","initialValue","pending","push","_len2","_key2","data","idsHash","_state2$timestamp","state2","deps","hasChangedDependencies","startsWith","_state2$timestamp2","dropDependencies","old","_len3","_key3","localState","_e$timestamp","_e$data","e","loading","items","Number","MAX_VALUE","_e$timestamp2","_e$data2"],"sources":["../../src/useAsyncCollection.ts"],"sourcesContent":["/**\n * Loads and uses item(s) in an async collection.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataReloaderT,\n type DataInEnvelopeAtPathT,\n type OperationIdT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n DEFAULT_MAXAGE,\n load,\n newAsyncDataEnvelope,\n} from './useAsyncData';\n\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n hash,\n isDebugMode,\n} from './utils';\n\nexport type AsyncCollectionT<\n DataT = unknown,\n IdT extends number | string = number | string,\n> = Record<IdT, AsyncDataEnvelopeT<DataT>>;\n\nexport type AsyncCollectionLoaderT<\n DataT,\n IdT extends number | string = number | string,\n> =\n (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<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 HeapT<\n DataT,\n IdT extends number | string,\n> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState: GlobalState<unknown>;\n ids: IdT[];\n path: null | string | undefined;\n loader: AsyncCollectionLoaderT<DataT, IdT>;\n reload: AsyncCollectionReloaderT<DataT, IdT>;\n reloadSingle: AsyncDataReloaderT<DataT>;\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 const res = [...idOrIds];\n res.sort((a, b) => a.toString().localeCompare(b.toString()));\n return res;\n }\n return [idOrIds];\n}\n\n/**\n * Inits/updates, and returns the heap.\n */\nfunction useHeap<\n DataT,\n IdT extends number | string,\n>(\n ids: IdT[],\n path: null | string | undefined,\n loader: AsyncCollectionLoaderT<DataT, IdT>,\n gs: GlobalState<unknown>,\n): HeapT<DataT, IdT> {\n const ref = useRef<HeapT<DataT, IdT>>(undefined);\n\n let heap = ref.current;\n\n if (heap) {\n // Update.\n heap.ids = ids;\n heap.path = path;\n heap.loader = loader;\n heap.globalState = gs;\n } else {\n // Initialization.\n const reload = async (\n customLoader?: AsyncCollectionLoaderT<DataT, IdT>,\n ) => {\n const heap2 = ref.current!;\n\n const localLoader = customLoader ?? heap2.loader;\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 || !heap2.globalState || !heap2.ids) {\n throw Error('Internal error');\n }\n\n for (const id of heap2.ids) {\n const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;\n\n await load(\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 heap2.globalState,\n );\n }\n };\n heap = {\n globalState: gs,\n ids,\n loader,\n path,\n 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 reloadSingle: (customLoader) => ref.current!.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 ref.current = heap;\n }\n\n return heap;\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): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT>;\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): UseAsyncDataResT<DataT> | UseAsyncCollectionResT<DataT, IdT> {\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 = getGlobalState();\n\n const heap = useHeap(ids, path, loader, globalState);\n\n // Server-side logic.\n if (globalState.ssrContext && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\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 globalState.ssrContext.pending.push(\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 load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, operationId),\n );\n }\n }\n\n // Client-side logic.\n } else {\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n gcOnWithhold(ids, path, globalState);\n return () => {\n gcOnRelease(ids, path, globalState, garbageCollectAge);\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 // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n garbageCollectAge,\n globalState,\n idsHash,\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(() => { // eslint-disable-line react-hooks/rules-of-hooks\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 load(\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 as DataT, ...args),\n globalState,\n {\n data: state2?.data,\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 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: maxage < Date.now() - timestamp ? null : e?.data ?? null,\n loading: !!e?.operationId,\n reload: heap.reloadSingle,\n timestamp,\n };\n }\n\n const res: UseAsyncCollectionResT<DataT, IdT> = {\n items: {} as Record<IdT, CollectionItemT<DataT>>,\n loading: false,\n reload: heap.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: maxage < Date.now() - timestamp ? 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 ): UseAsyncDataResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>>\n | UseAsyncCollectionResT<DataInEnvelopeAtPathT<StateT, `${PathT}.${IdT}`>, IdT>;\n}\n"],"mappings":"AAAA;AACA;AACA;;AAEA,SAASA,SAAS,EAAEC,MAAM,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAGjC,SAASC,cAAc;AAEvB,SAOEC,cAAc,EACdC,IAAI,EACJC,oB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sE,MAAM,CAACC;EACpB,CAAC;EAED,KAAK,MAAMzF,EAAE,IAAIL,GAAG,EAAE;IAAA,IAAA+F,aAAA,EAAAC,QAAA;IACpB;IACA,MAAMN,CAAC,GAAGH,UAAU,CAAClF,EAAE,CAAW;IAClC,MAAMsF,OAAO,GAAG,CAAC,EAACD,CAAC,aAADA,CAAC,eAADA,CAAC,CAAEtB,WAAW;IAChC,MAAM7C,SAAS,IAAAwE,aAAA,GAAGL,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAEnE,SAAS,cAAAwE,aAAA,cAAAA,aAAA,GAAI,CAAC;IAEnCrF,GAAG,CAACkF,KAAK,CAACvF,EAAE,CAAC,GAAG;MACdsE,IAAI,EAAEZ,MAAM,GAAG5C,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,IAAAyE,QAAA,GAAGN,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAEf,IAAI,cAAAqB,QAAA,cAAAA,QAAA,GAAI,IAAI;MAC9DL,OAAO;MACPpE;IACF,CAAC;IACDb,GAAG,CAACiF,OAAO,KAAXjF,GAAG,CAACiF,OAAO,GAAKA,OAAO;IACvB,IAAIjF,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAEA,eAAegD,kBAAkB;;AAEjC","ignoreList":[]}
@@ -41,7 +41,7 @@ export async function load(path, loader, globalState, old) {
41
41
  let operationId = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : `C${uuid()}`;
42
42
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
43
43
  /* eslint-disable no-console */
44
- console.log(`ReactGlobalState: async data (re-)loading. Path: "${path || ''}"`);
44
+ console.log(`ReactGlobalState: async data (re-)loading. Path: "${path !== null && path !== void 0 ? path : ''}"`);
45
45
  /* eslint-enable no-console */
46
46
  }
47
47
  const operationIdPath = path ? `${path}.operationId` : 'operationId';
@@ -87,7 +87,7 @@ export async function load(path, loader, globalState, old) {
87
87
  if (operationId === (state === null || state === void 0 ? void 0 : state.operationId)) {
88
88
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
89
89
  /* eslint-disable no-console */
90
- console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path || ''}"`);
90
+ console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path !== null && path !== void 0 ? path : ''}"`);
91
91
  console.log('Data:', cloneDeepForLog(data, path !== null && path !== void 0 ? path : ''));
92
92
  /* eslint-enable no-console */
93
93
  }
@@ -111,7 +111,7 @@ export async function load(path, loader, globalState, old) {
111
111
  */
112
112
 
113
113
  function useAsyncData(path, loader) {
114
- var _options$maxage, _options$refreshAge, _options$garbageColle;
114
+ var _options$maxage, _options$refreshAge, _options$garbageColle, _heap$reload;
115
115
  let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
116
116
  const maxage = (_options$maxage = options.maxage) !== null && _options$maxage !== void 0 ? _options$maxage : DEFAULT_MAXAGE;
117
117
  const refreshAge = (_options$refreshAge = options.refreshAge) !== null && _options$refreshAge !== void 0 ? _options$refreshAge : maxage;
@@ -129,13 +129,11 @@ function useAsyncData(path, loader) {
129
129
  heap.globalState = globalState;
130
130
  heap.path = path;
131
131
  heap.loader = loader;
132
- if (!heap.reload) {
133
- heap.reload = customLoader => {
134
- const localLoader = customLoader || heap.loader;
135
- if (!localLoader || !heap.globalState) throw Error('Internal error');
136
- return load(heap.path, localLoader, heap.globalState);
137
- };
138
- }
132
+ (_heap$reload = heap.reload) !== null && _heap$reload !== void 0 ? _heap$reload : heap.reload = async customLoader => {
133
+ const localLoader = customLoader !== null && customLoader !== void 0 ? customLoader : heap.loader;
134
+ if (!localLoader || !heap.globalState) throw Error('Internal error');
135
+ return load(heap.path, localLoader, heap.globalState);
136
+ };
139
137
  if (globalState.ssrContext) {
140
138
  if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {
141
139
  globalState.ssrContext.pending.push(load(path, loader, globalState, {
@@ -170,17 +168,19 @@ function useAsyncData(path, loader) {
170
168
  if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
171
169
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
172
170
  /* eslint-disable no-console */
173
- console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path || ''}`);
171
+ console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path !== null && path !== void 0 ? path : ''}`);
174
172
  /* eslint-enable no-console */
175
173
  }
176
- globalState.dropDependencies(path || '');
174
+ globalState.dropDependencies(path !== null && path !== void 0 ? path : '');
177
175
  globalState.set(path, {
178
176
  ...state2,
179
177
  data: null,
180
178
  numRefs: 0,
181
179
  timestamp: 0
182
180
  });
183
- } else globalState.set(numRefsPath, state2.numRefs - 1);
181
+ } else {
182
+ globalState.set(numRefsPath, state2.numRefs - 1);
183
+ }
184
184
  }
185
185
  };
186
186
  }, [disabled, garbageCollectAge, globalState, path]);
@@ -199,12 +199,12 @@ function useAsyncData(path, loader) {
199
199
  if (
200
200
  // The hook is called with a list of dependencies, that mismatch
201
201
  // dependencies last used to retrieve the data at given path.
202
- deps && globalState.hasChangedDependencies(path || '', deps)
202
+ deps && globalState.hasChangedDependencies(path !== null && path !== void 0 ? path : '', deps)
203
203
 
204
204
  // Data at the path are stale, and are not being loaded.
205
- || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.charAt(0) === 'S')) {
206
- if (!deps) globalState.dropDependencies(path || '');
207
- load(path, loader, globalState, {
205
+ || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.startsWith('S'))) {
206
+ if (!deps) globalState.dropDependencies(path !== null && path !== void 0 ? path : '');
207
+ void load(path, loader, globalState, {
208
208
  data: state2.data,
209
209
  timestamp: state2.timestamp
210
210
  });
@@ -221,4 +221,6 @@ function useAsyncData(path, loader) {
221
221
  };
222
222
  }
223
223
  export { useAsyncData };
224
+
225
+ // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
224
226
  //# sourceMappingURL=useAsyncData.js.map