@dr.pogodin/react-global-state 0.19.2 → 0.19.3

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.
@@ -79,7 +79,10 @@ function gcOnRelease(ids, path, gs, gcAge) {
79
79
  }
80
80
  function normalizeIds(idOrIds) {
81
81
  if (Array.isArray(idOrIds)) {
82
- const res = [...idOrIds];
82
+ // Removes ID duplicates.
83
+ const res = Array.from(new Set(idOrIds));
84
+
85
+ // Ensures stable ID order.
83
86
  res.sort((a, b) => a.toString().localeCompare(b.toString()));
84
87
  return res;
85
88
  }
@@ -166,26 +169,32 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
166
169
  const heap = useHeap(ids, path, loader, globalState);
167
170
 
168
171
  // Server-side logic.
169
- if (globalState.ssrContext && !options.noSSR) {
170
- const operationId = `S${(0, _uuid.v4)()}`;
171
- for (const id of ids) {
172
- const itemPath = path ? `${path}.${id}` : `${id}`;
173
- const state = globalState.get(itemPath, {
174
- initialValue: (0, _useAsyncData.newAsyncDataEnvelope)()
175
- });
176
- if (!state.timestamp && !state.operationId) {
177
- const promiseOrVoid = (0, _useAsyncData.load)(itemPath, (...args) => loader(id, ...args), globalState, {
178
- data: state.data,
179
- timestamp: state.timestamp
180
- }, operationId);
181
- if (promiseOrVoid instanceof Promise) {
182
- globalState.ssrContext.pending.push(promiseOrVoid);
172
+ if (globalState.ssrContext) {
173
+ if (!options.disabled && !options.noSSR) {
174
+ const operationId = `S${(0, _uuid.v4)()}`;
175
+ for (const id of ids) {
176
+ const itemPath = path ? `${path}.${id}` : `${id}`;
177
+ const state = globalState.get(itemPath, {
178
+ initialValue: (0, _useAsyncData.newAsyncDataEnvelope)()
179
+ });
180
+ if (!state.timestamp && !state.operationId) {
181
+ const promiseOrVoid = (0, _useAsyncData.load)(itemPath, (...args) => loader(id, ...args), globalState, {
182
+ data: state.data,
183
+ timestamp: state.timestamp
184
+ }, operationId);
185
+ if (promiseOrVoid instanceof Promise) {
186
+ globalState.ssrContext.pending.push(promiseOrVoid);
187
+ }
183
188
  }
184
189
  }
185
190
  }
186
191
 
187
192
  // Client-side logic.
188
193
  } else {
194
+ const {
195
+ disabled
196
+ } = options;
197
+
189
198
  // Reference-counting & garbage collection.
190
199
 
191
200
  const idsHash = (0, _utils.hash)(ids);
@@ -194,15 +203,15 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
194
203
  // but perhaps it can be refactored to avoid the need for it.
195
204
  (0, _react.useEffect)(() => {
196
205
  // eslint-disable-line react-hooks/rules-of-hooks
197
- gcOnWithhold(ids, path, globalState);
206
+ if (!disabled) gcOnWithhold(ids, path, globalState);
198
207
  return () => {
199
- gcOnRelease(ids, path, globalState, garbageCollectAge);
208
+ if (!disabled) gcOnRelease(ids, path, globalState, garbageCollectAge);
200
209
  };
201
210
 
202
211
  // `ids` are represented in the dependencies array by `idsHash` value,
203
212
  // as useEffect() hook requires a constant size of dependencies array.
204
213
  // eslint-disable-next-line react-hooks/exhaustive-deps
205
- }, [garbageCollectAge, globalState, idsHash, path]);
214
+ }, [disabled, garbageCollectAge, globalState, idsHash, path]);
206
215
 
207
216
  // NOTE: a bunch of Rules of Hooks ignored belows because in our very
208
217
  // special case the otherwise wrong behavior is actually what we need.
@@ -210,27 +219,29 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
210
219
  // Data loading and refreshing.
211
220
  (0, _react.useEffect)(() => {
212
221
  // eslint-disable-line react-hooks/rules-of-hooks
213
- void (async () => {
214
- for (const id of ids) {
215
- const itemPath = path ? `${path}.${id}` : `${id}`;
216
- const state2 = globalState.get(itemPath);
217
- const {
218
- deps
219
- } = options;
220
- if (deps && globalState.hasChangedDependencies(itemPath, deps) || refreshAge < Date.now() - (state2?.timestamp ?? 0) && (!state2?.operationId || state2.operationId.startsWith('S'))) {
221
- if (!deps) globalState.dropDependencies(itemPath);
222
- await (0, _useAsyncData.load)(itemPath,
223
- // TODO: I guess, the loader is not correctly typed here -
224
- // it can be synchronous, and in that case the following method
225
- // should be kept synchronous to not alter the sync logic.
226
- // eslint-disable-next-line @typescript-eslint/promise-function-async
227
- (old, ...args) => loader(id, old, ...args), globalState, {
228
- data: state2?.data,
229
- timestamp: state2?.timestamp ?? 0
230
- });
222
+ if (!disabled) {
223
+ void (async () => {
224
+ for (const id of ids) {
225
+ const itemPath = path ? `${path}.${id}` : `${id}`;
226
+ const state2 = globalState.get(itemPath);
227
+ const {
228
+ deps
229
+ } = options;
230
+ if (deps && globalState.hasChangedDependencies(itemPath, deps) || refreshAge < Date.now() - (state2?.timestamp ?? 0) && (!state2?.operationId || state2.operationId.startsWith('S'))) {
231
+ if (!deps) globalState.dropDependencies(itemPath);
232
+ await (0, _useAsyncData.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
+ (old, ...args) => loader(id, old, ...args), globalState, {
238
+ data: state2?.data,
239
+ timestamp: state2?.timestamp ?? 0
240
+ });
241
+ }
231
242
  }
232
- }
233
- })();
243
+ })();
244
+ }
234
245
  });
235
246
  }
236
247
  const [localState] = (0, _useGlobalState.default)(path, {});
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["_react","require","_uuid","_GlobalStateProvider","_useAsyncData","_useGlobalState","_interopRequireDefault","_utils","gcOnWithhold","ids","path","gs","collection","get","id","envelope","numRefs","newAsyncDataEnvelope","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","isDebugMode","console","log","normalizeIds","idOrIds","Array","isArray","sort","a","b","localeCompare","useHeap","loader","ref","useRef","undefined","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","promiseOrVoid","load","oldData","meta","Promise","reloadSingle","args","useAsyncCollection","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","getGlobalState","ssrContext","noSSR","operationId","uuid","state","initialValue","data","pending","push","idsHash","hash","useEffect","state2","deps","hasChangedDependencies","startsWith","dropDependencies","old","localState","useGlobalState","e","loading","items","Number","MAX_VALUE","_default","exports","default"],"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 | null) | Promise<DataT | null>;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | 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 const promiseOrVoid = 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 if (promiseOrVoid instanceof Promise) await promiseOrVoid;\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 const promiseOrVoid = load(\n itemPath,\n (...args):\n DataT | null | Promise<DataT | 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 // 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":";;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAGA,IAAAE,oBAAA,GAAAF,OAAA;AAEA,IAAAG,aAAA,GAAAH,OAAA;AAYA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAxBA;AACA;AACA;;AAgFA;AACA;AACA;AACA;AACA;AACA;AACA,SAASO,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,GAAG,IAAAE,kCAAoB,EAAU,IAAI,EAAE;MAAED,OAAO,EAAE;IAAE,CAAC,CAAC;IACnEJ,UAAU,CAACE,EAAE,CAAC,GAAGC,QAAQ;EAC3B;EAEAJ,EAAE,CAACO,GA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CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAAC,IAAAiF,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEclC,kBAAkB,EAEjC","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["_react","require","_uuid","_GlobalStateProvider","_useAsyncData","_useGlobalState","_interopRequireDefault","_utils","gcOnWithhold","ids","path","gs","collection","get","id","envelope","numRefs","newAsyncDataEnvelope","set","idsToStringSet","res","Set","add","toString","gcOnRelease","gcAge","entries","Object","now","Date","idSet","toBeReleased","has","timestamp","process","env","NODE_ENV","isDebugMode","console","log","normalizeIds","idOrIds","Array","isArray","from","sort","a","b","localeCompare","useHeap","loader","ref","useRef","undefined","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","promiseOrVoid","load","oldData","meta","Promise","reloadSingle","args","useAsyncCollection","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","getGlobalState","ssrContext","disabled","noSSR","operationId","uuid","state","initialValue","data","pending","push","idsHash","hash","useEffect","state2","deps","hasChangedDependencies","startsWith","dropDependencies","old","localState","useGlobalState","e","loading","items","Number","MAX_VALUE","_default","exports","default"],"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> = (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | 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 // 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 * 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 const promiseOrVoid = 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 if (promiseOrVoid instanceof Promise) await promiseOrVoid;\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) {\n if (!options.disabled && !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 const promiseOrVoid = load(\n itemPath,\n (...args):\n DataT | null | Promise<DataT | 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 // Client-side logic.\n } else {\n const { disabled } = options;\n\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 if (!disabled) gcOnWithhold(ids, path, globalState);\n return () => {\n if (!disabled) 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 disabled,\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 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 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\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":";;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,K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id","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","finalizeLoad","path","globalState","asyncDataLoadDone","state","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","set","Date","now","groupEnd","load","loader","old","uuid","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","undefined","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","useEffect","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport type GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\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: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => (DataT | null) | Promise<DataT | null>;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\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 timestamp: number;\n};\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n globalState: 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 globalState.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = globalState.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) {\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 globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\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}\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 load<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${uuid()}`,\n): void | Promise<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 dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\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\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\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 = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): void | Promise<void> => {\n const localLoader = customLoader ?? heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n } else {\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(() => { // eslint-disable-line react-hooks/rules-of-hooks\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(() => { // eslint-disable-line react-hooks/rules-of-hooks\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 void load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\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,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IACxCiD,MAAM,EAAEF,IAAI,CAACE,MAAM;IACnBnD,SAAS,EAAEmE,UAAU,CAACnE;EACxB,CAAC;AACH;;AAIA","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncData.js","names":["_react","require","_uuid","_jsUtils","_GlobalStateProvider","_useGlobalState","_interopRequireDefault","_utils","DEFAULT_MAXAGE","exports","MIN_MS","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","finalizeLoad","path","globalState","asyncDataLoadDone","state","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","set","Date","now","groupEnd","load","loader","old","uuid","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","undefined","useAsyncData","options","maxage","refreshAge","garbageCollectAge","getGlobalState","initialValue","current","heap","useRef","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","useEffect","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","localState","useGlobalState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport type GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\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: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\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 timestamp: number;\n};\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n globalState: 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 globalState.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = globalState.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) {\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 globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\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}\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 load<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${uuid()}`,\n): void | Promise<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 dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\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\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\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 = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): void | Promise<void> => {\n const localLoader = customLoader ?? heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n } else {\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(() => { // eslint-disable-line react-hooks/rules-of-hooks\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(() => { // eslint-disable-line react-hooks/rules-of-hooks\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 void load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\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":";;;;;;;;;;AAIA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAEA,IAAAE,QAAA,GAAAF,OAAA;AAEA,IAAAG,oBAAA,GAAAH,OAAA;AACA,IAAAI,eAAA,GAAAC,sBAAA,CAAAL,OAAA;AAEA,IAAAM,MAAA,GAAAN,OAAA;AAZA;AACA;AACA;;AAsBO,MAAMO,cAAc,GAAAC,OAAA,CAAAD,cAAA,GAAG,CAAC,GAAGE,eAAM,CAAC,CAAC;;AAE1C;AACA;AACA;AACA;AACA;AACA;AACA;;AAqBO,SAASC,oBAAoBA,CAClCC,WAAyB,GAAG,IAAI,EAChC;EAAEC,OAAO,GAAG,CAAC;EAAEC,SAAS,GAAG;AAAE,CAAC,GAAG,CAAC,CAAC,EACR;EAC3B,OAAO;IACLC,IAAI,EAAEH,WAAW;IACjBC,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAkBA,SAASG,YAAYA,CACnBF,IAAW,EACXG,IAA+B,EAC/BC,WAAsD,EACtDH,WAAyB,EACnB;EACN;EACA;EACA;EACA;EACA;EACA;EACA;EACAG,WAAW,CAACC,iBAAiB,CAACJ,WAAW,EAAE,KAAK,CAAC;EAGjD,MAAMK,KAAW,GAAGF,WAAW,CAACG,GAAG,CAAeJ,IAAI,CAAC;EAEvD,IAAIF,WAAW,KAAKK,KAAK,EAAEL,WAAW,EAAE;IACtC,IAAIO,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IAAI,IAAAC,kBAAW,EAAC,CAAC,EAAE;MAC1D;MACAC,O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CAACC,GAAG,CAAC,CAAC,GAAGgD,UAAU,CAACnE,SAAS,GAAG,IAAI,GAAGmE,UAAU,CAAClE,IAAI;IACzEoE,OAAO,EAAEC,OAAO,CAACH,UAAU,CAACjE,WAAW,CAAC;IACxCiD,MAAM,EAAEF,IAAI,CAACE,MAAM;IACnBnD,SAAS,EAAEmE,UAAU,CAACnE;EACxB,CAAC;AACH;;AAIA","ignoreList":[]}
@@ -36,8 +36,7 @@ export function getGlobalState() {
36
36
  * - If `throwWithoutSsrContext` is `true`, and there is no SSR context attached
37
37
  * to the global state provided by {@link &lt;GlobalStateProvider&gt;}.
38
38
  */
39
- export function getSsrContext() {
40
- let throwWithoutSsrContext = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
39
+ export function getSsrContext(throwWithoutSsrContext = true) {
41
40
  const {
42
41
  ssrContext
43
42
  } = getGlobalState();
@@ -59,11 +58,10 @@ export function getSsrContext() {
59
58
  * - If `GlobalState` instance, it will be used by this provider.
60
59
  * - If not given, a new `GlobalState` instance will be created and used.
61
60
  */
62
- const GlobalStateProvider = _ref => {
63
- let {
64
- children,
65
- ...rest
66
- } = _ref;
61
+ const GlobalStateProvider = ({
62
+ children,
63
+ ...rest
64
+ }) => {
67
65
  const localStateRef = useRef(undefined);
68
66
  let state;
69
67
  // TODO: Revise.
@@ -1 +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;EACA;EACA;EACA;EACA;EACA,MAAMC,WAAW,GAAGP,GAAG,CAACK,OAAO,CAAC;EAChC,IAAI,CAACE,WAAW,EAAE,MAAM,IAAIC,KAAK,CAAC,6BAA6B,CAAC;EAChE,OAAOD,WAAW;AACpB;;AAEA;AACA;AAC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C;AACpD,CAAC;AAED,eAAeF,mBAAmB","ignoreList":[]}
1
+ {"version":3,"file":"GlobalStateProvider.js","names":["isFunction","createContext","use","useRef","GlobalState","jsx","_jsx","Context","getGlobalState","globalState","Error","getSsrContext","throwWithoutSsrContext","ssrContext","GlobalStateProvider","children","rest","localStateRef","undefined","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,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M;QACJC,YAAY;QACZT;MACF,CAAC,GAAGG,IAA0C;MAC9CC,aAAa,CAACI,OAAO,GAAG,IAAIjB,WAAW,CACrCJ,UAAU,CAACsB,YAAY,CAAC,GAAGA,YAAY,CAAC,CAAC,GAAGA,YAAY,EACxDT,UACF,CAAC;IACH;IACAM,KAAK,GAAGF,aAAa,CAACI,OAAO;EAC/B;EACA,oBAAOf,IAAA,CAACC,OAAO;IAACgB,KAAK,EAAEJ,KAAM;IAAAJ,QAAA,EAAEA;EAAQ,CAAU,CAAC;AACpD,CAAC;AAED,eAAeD,mBAAmB","ignoreList":[]}
@@ -72,7 +72,10 @@ function gcOnRelease(ids, path, gs, gcAge) {
72
72
  }
73
73
  function normalizeIds(idOrIds) {
74
74
  if (Array.isArray(idOrIds)) {
75
- const res = [...idOrIds];
75
+ // Removes ID duplicates.
76
+ const res = Array.from(new Set(idOrIds));
77
+
78
+ // Ensures stable ID order.
76
79
  res.sort((a, b) => a.toString().localeCompare(b.toString()));
77
80
  return res;
78
81
  }
@@ -134,12 +137,7 @@ function useHeap(ids, path, loader, gs) {
134
137
  // happens if the outer function on the next line matches the same
135
138
  // async / sync signature.
136
139
  // eslint-disable-next-line @typescript-eslint/promise-function-async
137
- customLoader && function (id) {
138
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
139
- args[_key - 1] = arguments[_key];
140
- }
141
- return customLoader(...args);
142
- })
140
+ customLoader && ((id, ...args) => customLoader(...args)))
143
141
  };
144
142
  ref.current = heap;
145
143
  }
@@ -155,9 +153,8 @@ function useHeap(ids, path, loader, gs) {
155
153
  // Perhaps, a bunch of logic blocks can be split into stand-alone functions,
156
154
  // and reused in both hooks.
157
155
  // eslint-disable-next-line complexity
158
- function useAsyncCollection(idOrIds, path, loader) {
156
+ function useAsyncCollection(idOrIds, path, loader, options = {}) {
159
157
  var _options$maxage, _options$refreshAge, _options$garbageColle;
160
- let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
161
158
  const ids = normalizeIds(idOrIds);
162
159
  const maxage = (_options$maxage = options.maxage) !== null && _options$maxage !== void 0 ? _options$maxage : DEFAULT_MAXAGE;
163
160
  const refreshAge = (_options$refreshAge = options.refreshAge) !== null && _options$refreshAge !== void 0 ? _options$refreshAge : maxage;
@@ -166,31 +163,32 @@ function useAsyncCollection(idOrIds, path, loader) {
166
163
  const heap = useHeap(ids, path, loader, globalState);
167
164
 
168
165
  // Server-side logic.
169
- if (globalState.ssrContext && !options.noSSR) {
170
- const operationId = `S${uuid()}`;
171
- for (const id of ids) {
172
- const itemPath = path ? `${path}.${id}` : `${id}`;
173
- const state = globalState.get(itemPath, {
174
- initialValue: newAsyncDataEnvelope()
175
- });
176
- if (!state.timestamp && !state.operationId) {
177
- const promiseOrVoid = load(itemPath, function () {
178
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
179
- args[_key2] = arguments[_key2];
166
+ if (globalState.ssrContext) {
167
+ if (!options.disabled && !options.noSSR) {
168
+ const operationId = `S${uuid()}`;
169
+ for (const id of ids) {
170
+ const itemPath = path ? `${path}.${id}` : `${id}`;
171
+ const state = globalState.get(itemPath, {
172
+ initialValue: newAsyncDataEnvelope()
173
+ });
174
+ if (!state.timestamp && !state.operationId) {
175
+ const promiseOrVoid = load(itemPath, (...args) => loader(id, ...args), globalState, {
176
+ data: state.data,
177
+ timestamp: state.timestamp
178
+ }, operationId);
179
+ if (promiseOrVoid instanceof Promise) {
180
+ globalState.ssrContext.pending.push(promiseOrVoid);
180
181
  }
181
- return loader(id, ...args);
182
- }, globalState, {
183
- data: state.data,
184
- timestamp: state.timestamp
185
- }, operationId);
186
- if (promiseOrVoid instanceof Promise) {
187
- globalState.ssrContext.pending.push(promiseOrVoid);
188
182
  }
189
183
  }
190
184
  }
191
185
 
192
186
  // Client-side logic.
193
187
  } else {
188
+ const {
189
+ disabled
190
+ } = options;
191
+
194
192
  // Reference-counting & garbage collection.
195
193
 
196
194
  const idsHash = hash(ids);
@@ -199,15 +197,15 @@ function useAsyncCollection(idOrIds, path, loader) {
199
197
  // but perhaps it can be refactored to avoid the need for it.
200
198
  useEffect(() => {
201
199
  // eslint-disable-line react-hooks/rules-of-hooks
202
- gcOnWithhold(ids, path, globalState);
200
+ if (!disabled) gcOnWithhold(ids, path, globalState);
203
201
  return () => {
204
- gcOnRelease(ids, path, globalState, garbageCollectAge);
202
+ if (!disabled) gcOnRelease(ids, path, globalState, garbageCollectAge);
205
203
  };
206
204
 
207
205
  // `ids` are represented in the dependencies array by `idsHash` value,
208
206
  // as useEffect() hook requires a constant size of dependencies array.
209
207
  // eslint-disable-next-line react-hooks/exhaustive-deps
210
- }, [garbageCollectAge, globalState, idsHash, path]);
208
+ }, [disabled, garbageCollectAge, globalState, idsHash, path]);
211
209
 
212
210
  // NOTE: a bunch of Rules of Hooks ignored belows because in our very
213
211
  // special case the otherwise wrong behavior is actually what we need.
@@ -215,34 +213,31 @@ function useAsyncCollection(idOrIds, path, loader) {
215
213
  // Data loading and refreshing.
216
214
  useEffect(() => {
217
215
  // eslint-disable-line react-hooks/rules-of-hooks
218
- void (async () => {
219
- for (const id of ids) {
220
- var _state2$timestamp;
221
- const itemPath = path ? `${path}.${id}` : `${id}`;
222
- const state2 = globalState.get(itemPath);
223
- const {
224
- deps
225
- } = options;
226
- 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'))) {
227
- var _state2$timestamp2;
228
- if (!deps) globalState.dropDependencies(itemPath);
229
- await load(itemPath,
230
- // TODO: I guess, the loader is not correctly typed here -
231
- // it can be synchronous, and in that case the following method
232
- // should be kept synchronous to not alter the sync logic.
233
- // eslint-disable-next-line @typescript-eslint/promise-function-async
234
- function (old) {
235
- for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
236
- args[_key3 - 1] = arguments[_key3];
237
- }
238
- return loader(id, old, ...args);
239
- }, globalState, {
240
- data: state2 === null || state2 === void 0 ? void 0 : state2.data,
241
- timestamp: (_state2$timestamp2 = state2 === null || state2 === void 0 ? void 0 : state2.timestamp) !== null && _state2$timestamp2 !== void 0 ? _state2$timestamp2 : 0
242
- });
216
+ if (!disabled) {
217
+ void (async () => {
218
+ for (const id of ids) {
219
+ var _state2$timestamp;
220
+ const itemPath = path ? `${path}.${id}` : `${id}`;
221
+ const state2 = globalState.get(itemPath);
222
+ const {
223
+ deps
224
+ } = options;
225
+ 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'))) {
226
+ var _state2$timestamp2;
227
+ if (!deps) globalState.dropDependencies(itemPath);
228
+ await load(itemPath,
229
+ // TODO: I guess, the loader is not correctly typed here -
230
+ // it can be synchronous, and in that case the following method
231
+ // should be kept synchronous to not alter the sync logic.
232
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
233
+ (old, ...args) => loader(id, old, ...args), globalState, {
234
+ data: state2 === null || state2 === void 0 ? void 0 : state2.data,
235
+ timestamp: (_state2$timestamp2 = state2 === null || state2 === void 0 ? void 0 : state2.timestamp) !== null && _state2$timestamp2 !== void 0 ? _state2$timestamp2 : 0
236
+ });
237
+ }
243
238
  }
244
- }
245
- })();
239
+ })();
240
+ }
246
241
  });
247
242
  }
248
243
  const [localState] = useGlobalState(path, {});
@@ -1 +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","promiseOrVoid","oldData","meta","Promise","reloadSingle","_len","arguments","length","args","_key","useAsyncCollection","_options$maxage","_options$refreshAge","_options$garbageColle","options","maxage","refreshAge","garbageCollectAge","ssrContext","noSSR","operationId","state","initialValue","_len2","_key2","data","pending","push","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 | null) | Promise<DataT | null>;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | 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 const promiseOrVoid = 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 if (promiseOrVoid instanceof Promise) await promiseOrVoid;\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 const promiseOrVoid = load(\n itemPath,\n (...args):\n DataT | null | Promise<DataT | 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 // 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,oBAAoB;AAGtB,OAAOC,cAAc;AAErB,SAIEC,IAAI,EACJC,WAAW;AAqDb;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,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UAAU,CAACpF,EAAE,CAAW;IAClC,MAAMwF,OAAO,GAAG,CAAC,EAACD,CAAC,aAADA,CAAC,eAADA,CAAC,CAAEtB,WAAW;IAChC,MAAM/C,SAAS,IAAA0E,aAAA,GAAGL,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAErE,SAAS,cAAA0E,aAAA,cAAAA,aAAA,GAAI,CAAC;IAEnCvF,GAAG,CAACoF,KAAK,CAACzF,EAAE,CAAC,GAAG;MACdsE,IAAI,EAAEV,MAAM,GAAG9C,IAAI,CAACD,GAAG,CAAC,CAAC,GAAGK,SAAS,GAAG,IAAI,IAAA2E,QAAA,GAAGN,CAAC,aAADA,CAAC,uBAADA,CAAC,CAAEjB,IAAI,cAAAuB,QAAA,cAAAA,QAAA,GAAI,IAAI;MAC9DL,OAAO;MACPtE;IACF,CAAC;IACDb,GAAG,CAACmF,OAAO,KAAXnF,GAAG,CAACmF,OAAO,GAAKA,OAAO;IACvB,IAAInF,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAEA,eAAekD,kBAAkB;;AAEjC","ignoreList":[]}
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","from","sort","a","b","localeCompare","useHeap","loader","ref","undefined","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","promiseOrVoid","oldData","meta","Promise","reloadSingle","args","useAsyncCollection","options","_options$maxage","_options$refreshAge","_options$garbageColle","maxage","refreshAge","garbageCollectAge","ssrContext","disabled","noSSR","operationId","state","initialValue","data","pending","push","idsHash","_state2$timestamp","state2","deps","hasChangedDependencies","startsWith","_state2$timestamp2","dropDependencies","old","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> = (id: IdT, oldData: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | 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 // 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 * 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 const promiseOrVoid = 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 if (promiseOrVoid instanceof Promise) await promiseOrVoid;\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) {\n if (!options.disabled && !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 const promiseOrVoid = load(\n itemPath,\n (...args):\n DataT | null | Promise<DataT | 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 // Client-side logic.\n } else {\n const { disabled } = options;\n\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 if (!disabled) gcOnWithhold(ids, path, globalState);\n return () => {\n if (!disabled) 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 disabled,\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 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 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\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,oBAAoB;AAGtB,OAAOC,cAAc;AAErB,SAIEC,IAAI,EACJC,WAAW;AAoDb;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,C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ignoreList":[]}
@@ -18,12 +18,10 @@ export const DEFAULT_MAXAGE = 5 * MIN_MS; // 5 minutes.
18
18
  // related global state values are updated immediately, within the current
19
19
  // rendering cycle.
20
20
 
21
- export function newAsyncDataEnvelope() {
22
- let initialData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
23
- let {
24
- numRefs = 0,
25
- timestamp = 0
26
- } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
21
+ export function newAsyncDataEnvelope(initialData = null, {
22
+ numRefs = 0,
23
+ timestamp = 0
24
+ } = {}) {
27
25
  return {
28
26
  data: initialData,
29
27
  numRefs,
@@ -76,8 +74,12 @@ function finalizeLoad(data, path, globalState, operationId) {
76
74
  * @return Resolves once the operation is done.
77
75
  * @ignore
78
76
  */
79
- export function load(path, loader, globalState, old) {
80
- let operationId = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : `C${uuid()}`;
77
+ export function load(path, loader, globalState, old,
78
+ // TODO: Should this parameter be just a binary flag (client or server),
79
+ // and UUID always generated inside this function? Or do we need it in
80
+ // the caller methods as well, in some cases (see useAsyncCollection()
81
+ // use case as well).
82
+ operationId = `C${uuid()}`) {
81
83
  if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
82
84
  /* eslint-disable no-console */
83
85
  console.log(`ReactGlobalState: async data (re-)loading. Path: "${path !== null && path !== void 0 ? path : ''}"`);
@@ -132,9 +134,8 @@ export function load(path, loader, globalState, old) {
132
134
  * state.
133
135
  */
134
136
 
135
- function useAsyncData(path, loader) {
137
+ function useAsyncData(path, loader, options = {}) {
136
138
  var _options$maxage, _options$refreshAge, _options$garbageColle, _heap$reload;
137
- let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
138
139
  const maxage = (_options$maxage = options.maxage) !== null && _options$maxage !== void 0 ? _options$maxage : DEFAULT_MAXAGE;
139
140
  const refreshAge = (_options$refreshAge = options.refreshAge) !== null && _options$refreshAge !== void 0 ? _options$refreshAge : maxage;
140
141
  const garbageCollectAge = (_options$garbageColle = options.garbageCollectAge) !== null && _options$garbageColle !== void 0 ? _options$garbageColle : maxage;
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncData.js","names":["useEffect","useRef","v4","uuid","MIN_MS","getGlobalState","useGlobalState","cloneDeepForLog","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","arguments","length","undefined","numRefs","timestamp","data","operationId","finalizeLoad","path","globalState","asyncDataLoadDone","state","get","process","env","NODE_ENV","console","groupCollapsed","log","set","Date","now","groupEnd","load","loader","old","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","useAsyncData","_options$maxage","_options$refreshAge","_options$garbageColle","_heap$reload","options","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport type GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\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: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => (DataT | null) | Promise<DataT | null>;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\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 timestamp: number;\n};\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n globalState: 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 globalState.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = globalState.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) {\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 globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\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}\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 load<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${uuid()}`,\n): void | Promise<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 dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\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\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\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 = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): void | Promise<void> => {\n const localLoader = customLoader ?? heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n } else {\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(() => { // eslint-disable-line react-hooks/rules-of-hooks\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(() => { // eslint-disable-line react-hooks/rules-of-hooks\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 void load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\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,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,eAAe,EACfC,WAAW;AAMb,OAAO,MAAMC,cAAc,GAAG,CAAC,GAAGL,MAAM,CAAC,CAAC;;AAE1C;AACA;AACA;AACA;AACA;AACA;AACA;;AAqBA,OAAO,SAASM,oBAAoBA,CAAA,EAGP;EAAA,IAF3BC,WAAyB,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,IAAI;EAAA,IAChC;IAAEG,OAAO,GAAG,CAAC;IAAEC,SAAS,GAAG;EAAE,CAAC,GAAAJ,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAEnC,OAAO;IACLK,IAAI,EAAEN,WAAW;IACjBI,OAAO;IACPG,WAAW,EAAE,EAAE;IACfF;EACF,CAAC;AACH;AAkBA,SAASG,YAAYA,CACnBF,IAAW,EACXG,IAA+B,EAC/BC,WAAsD,EACtDH,WAAyB,EACnB;EACN;EACA;EACA;EACA;EACA;EACA;EACA;EACAG,WAAW,CAACC,iBAAiB,CAACJ,WAAW,EAAE,KAAK,CAAC;EAGjD,MAAMK,KAAW,GAAGF,WAAW,CAACG,GAAG,CAAeJ,IAAI,CAAC;EAEvD,IAAIF,WAAW,MAAKK,KAAK,aAALA,KAAK,uBAALA,KAAK,CAAEL,WAAW,GAAE;IACtC,IA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I,CAACC,GAAG,CAAC,CAAC,GAAG0C,MAAM,CAAC3D,SAAS,KACtC,CAAC2D,MAAM,CAACzD,WAAW,IAAIyD,MAAM,CAACzD,WAAW,CAAC6D,UAAU,CAAC,GAAG,CAAC,CAC9D,EACD;UACA,IAAI,CAACF,IAAI,EAAExD,WAAW,CAACuD,gBAAgB,CAACxD,IAAI,aAAJA,IAAI,cAAJA,IAAI,GAAI,EAAE,CAAC;UACnD,KAAKe,IAAI,CAACf,IAAI,EAAEgB,MAAM,EAAEf,WAAW,EAAE;YACnCJ,IAAI,EAAE0D,MAAM,CAAC1D,IAAI;YACjBD,SAAS,EAAE2D,MAAM,CAAC3D;UACpB,CAAC,CAAC;QACJ;MACF;IACF,CAAC,CAAC;EACJ;EAEA,MAAM,CAACgE,UAAU,CAAC,GAAG1E,cAAc,CACjCc,IAAI,EACJV,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLO,IAAI,EAAE0C,MAAM,GAAG3B,IAAI,CAACC,GAAG,CAAC,CAAC,GAAG+C,UAAU,CAAChE,SAAS,GAAG,IAAI,GAAGgE,UAAU,CAAC/D,IAAI;IACzEgE,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC9D,WAAW,CAAC;IACxC+C,MAAM,EAAED,IAAI,CAACC,MAAM;IACnBjD,SAAS,EAAEgE,UAAU,CAAChE;EACxB,CAAC;AACH;AAEA,SAASqC,YAAY;;AAErB","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncData.js","names":["useEffect","useRef","v4","uuid","MIN_MS","getGlobalState","useGlobalState","cloneDeepForLog","isDebugMode","DEFAULT_MAXAGE","newAsyncDataEnvelope","initialData","numRefs","timestamp","data","operationId","finalizeLoad","path","globalState","asyncDataLoadDone","state","get","process","env","NODE_ENV","console","groupCollapsed","log","set","Date","now","groupEnd","load","loader","old","operationIdPath","prevOperationId","definedOld","e","dataOrPromise","isAborted","opid","oldDataTimestamp","setAbortCallback","cb","Error","setAsyncDataAbortCallback","Promise","then","finally","undefined","useAsyncData","options","_options$maxage","_options$refreshAge","_options$garbageColle","_heap$reload","maxage","refreshAge","garbageCollectAge","initialValue","current","heap","reload","customLoader","localLoader","ssrContext","disabled","noSSR","promiseOrVoid","pending","push","numRefsPath","state2","dropDependencies","deps","hasChangedDependencies","startsWith","localState","loading","Boolean"],"sources":["../../src/useAsyncData.ts"],"sourcesContent":["/**\n * Loads and uses async data into the GlobalState path.\n */\n\nimport { useEffect, useRef } from 'react';\nimport { v4 as uuid } from 'uuid';\n\nimport { MIN_MS } from '@dr.pogodin/js-utils';\n\nimport { getGlobalState } from './GlobalStateProvider';\nimport useGlobalState from './useGlobalState';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nimport type GlobalState from './GlobalState';\nimport type SsrContext from './SsrContext';\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: null | DataT, meta: {\n isAborted: () => boolean;\n oldDataTimestamp: number;\n setAbortCallback: (cb: () => void) => void;\n}) => DataT | null | Promise<DataT | null>;\n\nexport type AsyncDataReloaderT<DataT>\n= (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;\n\nexport type AsyncDataEnvelopeT<DataT> = {\n data: null | DataT;\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 timestamp: number;\n};\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n globalState: 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 globalState.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = globalState.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) {\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 globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...state,\n data,\n operationId: '',\n timestamp: Date.now(),\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}\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 load<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${uuid()}`,\n): void | Promise<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 dataOrPromise = loader(definedOld.data, {\n isAborted: () => {\n // TODO: Can we improve the typing, to avoid ForceT?\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n return opid !== operationId;\n },\n oldDataTimestamp: definedOld.timestamp,\n setAbortCallback(cb: () => void) {\n const opid = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(path).operationId;\n if (opid !== operationId) {\n throw Error(`Operation #${operationId} has completed already`);\n }\n globalState.setAsyncDataAbortCallback(operationId, cb);\n },\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\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\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 = getGlobalState();\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n\n const { current: heap } = useRef<HeapT<DataT>>({});\n heap.globalState = globalState;\n heap.path = path;\n heap.loader = loader;\n\n heap.reload ??= (\n customLoader?: AsyncDataLoaderT<DataT>,\n ): void | Promise<void> => {\n const localLoader = customLoader ?? heap.loader;\n if (!localLoader || !heap.globalState) throw Error('Internal error');\n return load(heap.path, localLoader, heap.globalState);\n };\n\n if (globalState.ssrContext) {\n if (\n !options.disabled && !options.noSSR\n && !state.operationId && !state.timestamp\n ) {\n const promiseOrVoid = load(path, loader, globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, `S${uuid()}`);\n if (promiseOrVoid instanceof Promise) {\n globalState.ssrContext.pending.push(promiseOrVoid);\n }\n }\n } else {\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(() => { // eslint-disable-line react-hooks/rules-of-hooks\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(() => { // eslint-disable-line react-hooks/rules-of-hooks\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 void load(path, loader, globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n });\n }\n\n const [localState] = useGlobalState<ForceT, AsyncDataEnvelopeT<DataT>>(\n path,\n newAsyncDataEnvelope<DataT>(),\n );\n\n return {\n data: maxage < Date.now() - localState.timestamp ? null : localState.data,\n loading: Boolean(localState.operationId),\n reload: heap.reload,\n timestamp: localState.timestamp,\n };\n}\n\nexport { useAsyncData };\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,QAAQ,OAAO;AACzC,SAASC,EAAE,IAAIC,IAAI,QAAQ,MAAM;AAEjC,SAASC,MAAM,QAAQ,sBAAsB;AAE7C,SAASC,cAAc;AACvB,OAAOC,cAAc;AAErB,SAKEC,eAAe,EACfC,WAAW;AAMb,OAAO,MAAMC,cA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IACzEiE,OAAO,EAAEC,OAAO,CAACF,UAAU,CAAC/D,WAAW,CAAC;IACxCgD,MAAM,EAAED,IAAI,CAACC,MAAM;IACnBlD,SAAS,EAAEiE,UAAU,CAACjE;EACxB,CAAC;AACH;AAEA,SAASsC,YAAY;;AAErB","ignoreList":[]}
@@ -44,8 +44,7 @@ const cloneDeepBailKeys = new Set();
44
44
  * (to avoid situations when large payload in the global state slows down
45
45
  * development versions of the app due to the logging overhead).
46
46
  */
47
- export function cloneDeepForLog(value) {
48
- let key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
47
+ export function cloneDeepForLog(value, key = '') {
49
48
  if (cloneDeepBailKeys.has(key)) {
50
49
  // eslint-disable-next-line no-console
51
50
  console.warn(`The logged value won't be clonned (key "${key}").`);
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":["cloneDeep","isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","cloneDeepBailKeys","Set","cloneDeepForLog","value","key","arguments","length","undefined","has","console","warn","start","Date","now","res","time","add","escape","x","replace","toString","hash","items","map","join"],"sources":["../../src/utils.ts"],"sourcesContent":["import { type GetFieldType, cloneDeep } from 'lodash';\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\n/**\n * Converts given value to an escaped string. For now, we are good with the most\n * trivial escape logic:\n * - '%' characters are replaced by '%0' code pair;\n * - '/' characters are replaced by '%1' code pair.\n */\nexport function escape(x: number | string): string {\n return typeof x === 'string'\n ? x.replace(/%/g, '%0').replace(/\\//g, '%1')\n : x.toString();\n}\n\n/**\n * Hashes given string array. For our current needs we are fine to go with\n * the most trivial implementation, which probably should not be called \"hash\"\n * in the strict sense: we just escape each given string to not include '/'\n * characters, and then we join all those strings using '/' as the separator.\n */\nexport function hash(items: Array<number | string>): string {\n return items.map(escape).join('/');\n}\n"],"mappings":"AAAA,SAA4BA,SAAS,QAAQ,QAAQ;;AAIrD;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,SAASC,WAAWA,CAAA,EAAY;EACrC,IAAI;IACF,OAAOC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IACvC,CAAC,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB;EAC7C,CAAC,CAAC,MAAM;IACN,OAAO,KAAK;EACd;AACF;AAEA,MAAMC,iBAAiB,GAAG,IAAIC,GAAG,CAAS,CAAC;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,eAAeA,CAAIC,KAAQ,EAAuB;EAAA,IAArBC,GAAW,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,EAAE;EAC3D,IAAIL,iBAAiB,CAACQ,GAAG,CAACJ,GAAG,CAAC,EAAE;IAC9B;IACAK,OAAO,CAACC,IAAI,CAAC,2CAA2CN,GAAG,KAAK,CAAC;IACjE,OAAOD,KAAK;EACd;EAEA,MAAMQ,KAAK,GAAGC,IAAI,CAACC,GAAG,CAAC,CAAC;EACxB,MAAMC,GAAG,GAAGpB,SAAS,CAACS,KAAK,CAAC;EAC5B,MAAMY,IAAI,GAAGH,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGF,KAAK;EAC/B,IAAII,IAAI,GAAG,GAAG,EAAE;IACd;IACAN,OAAO,CAACC,IAAI,CAAC,GAAGK,IAAI,4CAA4CX,GAAG,KAAK,CAAC;IACzEJ,iBAAiB,CAACgB,GAAG,CAACZ,GAAG,CAAC;EAC5B;EAEA,OAAOU,GAAG;AACZ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASG,MAAMA,CAACC,CAAkB,EAAU;EACjD,OAAO,OAAOA,CAAC,KAAK,QAAQ,GACxBA,CAAC,CAACC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAACA,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,GAC1CD,CAAC,CAACE,QAAQ,CAAC,CAAC;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,IAAIA,CAACC,KAA6B,EAAU;EAC1D,OAAOA,KAAK,CAACC,GAAG,CAACN,MAAM,CAAC,CAACO,IAAI,CAAC,GAAG,CAAC;AACpC","ignoreList":[]}
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","escape","x","replace","toString","hash","items","map","join"],"sources":["../../src/utils.ts"],"sourcesContent":["import { type GetFieldType, cloneDeep } from 'lodash';\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\n/**\n * Converts given value to an escaped string. For now, we are good with the most\n * trivial escape logic:\n * - '%' characters are replaced by '%0' code pair;\n * - '/' characters are replaced by '%1' code pair.\n */\nexport function escape(x: number | string): string {\n return typeof x === 'string'\n ? x.replace(/%/g, '%0').replace(/\\//g, '%1')\n : x.toString();\n}\n\n/**\n * Hashes given string array. For our current needs we are fine to go with\n * the most trivial implementation, which probably should not be called \"hash\"\n * in the strict sense: we just escape each given string to not include '/'\n * characters, and then we join all those strings using '/' as the separator.\n */\nexport function hash(items: Array<number | string>): string {\n return items.map(escape).join('/');\n}\n"],"mappings":"AAAA,SAA4BA,SAAS,QAAQ,QAAQ;;AAIrD;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,SAASC,WAAWA,CAAA,EAAY;EACrC,IAAI;IACF,OAAOC,OAAO,CAACC,GAAG,CAACC,QAAQ,KAAK,YAAY,IACvC,CAAC,CAACF,OAAO,CAACC,GAAG,CAACE,wBAAwB;EAC7C,CAAC,CAAC,MAAM;IACN,OAAO,KAAK;EACd;AACF;AAEA,MAAMC,iBAAiB,GAAG,IAAIC,GAAG,CAAS,CAAC;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,eAAeA,CAAIC,KAAQ,EAAEC,GAAW,GAAG,EAAE,EAAK;EAChE,IAAIJ,iBAAiB,CAACK,GAAG,CAACD,GAAG,CAAC,EAAE;IAC9B;IACAE,OAAO,CAACC,IAAI,CAAC,2CAA2CH,GAAG,KAAK,CAAC;IACjE,OAAOD,KAAK;EACd;EAEA,MAAMK,KAAK,GAAGC,IAAI,CAACC,GAAG,CAAC,CAAC;EACxB,MAAMC,GAAG,GAAGjB,SAAS,CAACS,KAAK,CAAC;EAC5B,MAAMS,IAAI,GAAGH,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGF,KAAK;EAC/B,IAAII,IAAI,GAAG,GAAG,EAAE;IACd;IACAN,OAAO,CAACC,IAAI,CAAC,GAAGK,IAAI,4CAA4CR,GAAG,KAAK,CAAC;IACzEJ,iBAAiB,CAACa,GAAG,CAACT,GAAG,CAAC;EAC5B;EAEA,OAAOO,GAAG;AACZ;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASG,MAAMA,CAACC,CAAkB,EAAU;EACjD,OAAO,OAAOA,CAAC,KAAK,QAAQ,GACxBA,CAAC,CAACC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAACA,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,GAC1CD,CAAC,CAACE,QAAQ,CAAC,CAAC;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,IAAIA,CAACC,KAA6B,EAAU;EAC1D,OAAOA,KAAK,CAACC,GAAG,CAACN,MAAM,CAAC,CAACO,IAAI,CAAC,GAAG,CAAC;AACpC","ignoreList":[]}
@@ -8,7 +8,7 @@ export type AsyncCollectionLoaderT<DataT, IdT extends number | string = number |
8
8
  isAborted: () => boolean;
9
9
  oldDataTimestamp: number;
10
10
  setAbortCallback: (cb: () => void) => void;
11
- }) => (DataT | null) | Promise<DataT | null>;
11
+ }) => DataT | null | Promise<DataT | null>;
12
12
  export type AsyncCollectionReloaderT<DataT, IdT extends number | string = number | string> = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => void | Promise<void>;
13
13
  type CollectionItemT<DataT> = {
14
14
  data: DataT | null;
@@ -9,7 +9,7 @@ export type AsyncDataLoaderT<DataT> = (oldData: null | DataT, meta: {
9
9
  isAborted: () => boolean;
10
10
  oldDataTimestamp: number;
11
11
  setAbortCallback: (cb: () => void) => void;
12
- }) => (DataT | null) | Promise<DataT | null>;
12
+ }) => DataT | null | Promise<DataT | null>;
13
13
  export type AsyncDataReloaderT<DataT> = (loader?: AsyncDataLoaderT<DataT>) => void | Promise<void>;
14
14
  export type AsyncDataEnvelopeT<DataT> = {
15
15
  data: null | DataT;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dr.pogodin/react-global-state",
3
- "version": "0.19.2",
3
+ "version": "0.19.3",
4
4
  "description": "Hook-based global state for React",
5
5
  "main": "./build/code/index.js",
6
6
  "types": "./build/types/index.d.ts",
@@ -40,35 +40,35 @@
40
40
  "node": ">=18"
41
41
  },
42
42
  "dependencies": {
43
- "@babel/runtime": "^7.27.1",
44
- "@dr.pogodin/js-utils": "^0.0.18",
45
- "@types/lodash": "^4.17.16",
43
+ "@babel/runtime": "^7.27.6",
44
+ "@dr.pogodin/js-utils": "^0.1.0",
45
+ "@types/lodash": "^4.17.20",
46
46
  "lodash": "^4.17.21",
47
47
  "uuid": "^11.1.0"
48
48
  },
49
49
  "devDependencies": {
50
- "@babel/cli": "^7.27.2",
51
- "@babel/core": "^7.27.1",
52
- "@babel/node": "^7.27.1",
53
- "@babel/plugin-transform-runtime": "^7.27.1",
54
- "@babel/preset-env": "^7.27.2",
50
+ "@babel/cli": "^7.28.0",
51
+ "@babel/core": "^7.28.0",
52
+ "@babel/node": "^7.28.0",
53
+ "@babel/plugin-transform-runtime": "^7.28.0",
54
+ "@babel/preset-env": "^7.28.0",
55
55
  "@babel/preset-react": "^7.27.1",
56
56
  "@babel/preset-typescript": "^7.27.1",
57
- "@dr.pogodin/eslint-configs": "^0.0.6",
57
+ "@dr.pogodin/eslint-configs": "^0.0.9",
58
58
  "@testing-library/dom": "^10.4.0",
59
59
  "@testing-library/react": "^16.3.0",
60
- "@tsconfig/recommended": "^1.0.8",
61
- "@types/jest": "^29.5.14",
60
+ "@tsconfig/recommended": "^1.0.10",
61
+ "@types/jest": "^30.0.0",
62
62
  "@types/pretty": "^2.0.3",
63
- "@types/react": "^19.1.3",
64
- "@types/react-dom": "^19.1.3",
65
- "babel-jest": "^29.7.0",
63
+ "@types/react": "^19.1.8",
64
+ "@types/react-dom": "^19.1.6",
65
+ "babel-jest": "^30.0.4",
66
66
  "babel-plugin-module-resolver": "^5.0.2",
67
- "jest": "^29.7.0",
68
- "jest-environment-jsdom": "^29.7.0",
67
+ "jest": "^30.0.4",
68
+ "jest-environment-jsdom": "^30.0.4",
69
69
  "mockdate": "^3.0.5",
70
70
  "rimraf": "^6.0.1",
71
- "tstyche": "^3.5.0",
71
+ "tstyche": "^4.3.0",
72
72
  "typescript": "^5.8.3"
73
73
  },
74
74
  "peerDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
- "testFileMatch": [
3
- "__tests__/**/*.ts",
4
- "__tests__/**/*.tsx"
5
- ]
2
+ "$schema": "https://tstyche.org/schemas/config.json",
3
+ "checkSuppressedErrors": true,
4
+ "checkSourceFiles": false,
5
+ "testFileMatch": ["__tests__/**/*.{ts,tsx}"]
6
6
  }