@dr.pogodin/react-global-state 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","_useGlobalState","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","api","getGlobalState","getSsrContext","GlobalState","GlobalStateProvider","newAsyncDataEnvelope","SsrContext","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT } from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,oBAAA,GAAAC,uBAAA,CAAAF,OAAA;AAKA,IAAAG,WAAA,GAAAJ,sBAAA,CAAAC,OAAA;AAEA,IAAAI,mBAAA,GAAAL,sBAAA,CAAAC,OAAA;AAKA,IAAAK,aAAA,GAAAL,OAAA;AAWA,IAAAM,eAAA,GAAAP,sBAAA,CAAAC,OAAA;AAAwE,SAAAO,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAN,wBAAAM,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,CAAA,IAAAd,CAAA,oBAAAc,CAAA,OAAAC,cAAA,CAAAC,IAAA,CAAAhB,CAAA,EAAAc,CAAA,SAAAG,CAAA,GAAAP,CAAA,GAAAC,MAAA,CAAAE,wBAAA,CAAAb,CAAA,EAAAc,CAAA,UAAAG,CAAA,KAAAA,CAAA,CAAAV,GAAA,IAAAU,CAAA,CAAAC,GAAA,IAAAP,MAAA,CAAAC,cAAA,CAAAJ,CAAA,EAAAM,CAAA,EAAAG,CAAA,IAAAT,CAAA,CAAAM,CAAA,IAAAd,CAAA,CAAAc,CAAA,YAAAN,CAAA,CAAAH,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAe,GAAA,CAAAlB,CAAA,EAAAQ,CAAA,GAAAA,CAAA;AAyCxE,MAAMW,GAAG,GAAG;EACVC,cAAc,EAAdA,mCAAc;EACdC,aAAa,EAAbA,kCAAa;EACbC,WAAW,EAAXA,oBAAW;EACXC,mBAAmB,EAAnBA,4BAAmB;EACnBC,oBAAoB,EAApBA,kCAAoB;EACpBC,UAAU,EAAVA,mBAAU;EACVC,kBAAkB,EAAlBA,2BAAkB;EAClBC,YAAY,EAAZA,0BAAY;EACZC,cAAc,EAAdA;AACF,CAAC;AAEM,SAASC,mBAAmBA,CAAA,EAG/B;EACF,OAAOV,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["_GlobalState","_interopRequireDefault","require","_GlobalStateProvider","_interopRequireWildcard","_SsrContext","_useAsyncCollection","_useAsyncData","_useGlobalState","_getRequireWildcardCache","e","WeakMap","r","t","__esModule","default","has","get","n","__proto__","a","Object","defineProperty","getOwnPropertyDescriptor","u","hasOwnProperty","call","i","set","api","getGlobalState","getSsrContext","GlobalState","GlobalStateProvider","newAsyncDataEnvelope","SsrContext","useAsyncCollection","useAsyncData","useGlobalState","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT, AsyncCollectionT } from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,oBAAA,GAAAC,uBAAA,CAAAF,OAAA;AAKA,IAAAG,WAAA,GAAAJ,sBAAA,CAAAC,OAAA;AAEA,IAAAI,mBAAA,GAAAL,sBAAA,CAAAC,OAAA;AAKA,IAAAK,aAAA,GAAAL,OAAA;AAWA,IAAAM,eAAA,GAAAP,sBAAA,CAAAC,OAAA;AAAwE,SAAAO,yBAAAC,CAAA,6BAAAC,OAAA,mBAAAC,CAAA,OAAAD,OAAA,IAAAE,CAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,CAAA,WAAAA,CAAA,GAAAG,CAAA,GAAAD,CAAA,KAAAF,CAAA;AAAA,SAAAN,wBAAAM,CAAA,EAAAE,CAAA,SAAAA,CAAA,IAAAF,CAAA,IAAAA,CAAA,CAAAI,UAAA,SAAAJ,CAAA,eAAAA,CAAA,uBAAAA,CAAA,yBAAAA,CAAA,WAAAK,OAAA,EAAAL,CAAA,QAAAG,CAAA,GAAAJ,wBAAA,CAAAG,CAAA,OAAAC,CAAA,IAAAA,CAAA,CAAAG,GAAA,CAAAN,CAAA,UAAAG,CAAA,CAAAI,GAAA,CAAAP,CAAA,OAAAQ,CAAA,KAAAC,SAAA,UAAAC,CAAA,GAAAC,MAAA,CAAAC,cAAA,IAAAD,MAAA,CAAAE,wBAAA,WAAAC,CAAA,IAAAd,CAAA,oBAAAc,CAAA,OAAAC,cAAA,CAAAC,IAAA,CAAAhB,CAAA,EAAAc,CAAA,SAAAG,CAAA,GAAAP,CAAA,GAAAC,MAAA,CAAAE,wBAAA,CAAAb,CAAA,EAAAc,CAAA,UAAAG,CAAA,KAAAA,CAAA,CAAAV,GAAA,IAAAU,CAAA,CAAAC,GAAA,IAAAP,MAAA,CAAAC,cAAA,CAAAJ,CAAA,EAAAM,CAAA,EAAAG,CAAA,IAAAT,CAAA,CAAAM,CAAA,IAAAd,CAAA,CAAAc,CAAA,YAAAN,CAAA,CAAAH,OAAA,GAAAL,CAAA,EAAAG,CAAA,IAAAA,CAAA,CAAAe,GAAA,CAAAlB,CAAA,EAAAQ,CAAA,GAAAA,CAAA;AAyCxE,MAAMW,GAAG,GAAG;EACVC,cAAc,EAAdA,mCAAc;EACdC,aAAa,EAAbA,kCAAa;EACbC,WAAW,EAAXA,oBAAW;EACXC,mBAAmB,EAAnBA,4BAAmB;EACnBC,oBAAoB,EAApBA,kCAAoB;EACpBC,UAAU,EAAVA,mBAAU;EACVC,kBAAkB,EAAlBA,2BAAkB;EAClBC,YAAY,EAAZA,0BAAY;EACZC,cAAc,EAAdA;AACF,CAAC;AAEM,SAASC,mBAAmBA,CAAA,EAG/B;EACF,OAAOV,GAAG;AACZ","ignoreList":[]}
@@ -15,6 +15,120 @@ var _utils = require("./utils");
15
15
  * Loads and uses item(s) in an async collection.
16
16
  */
17
17
 
18
+ /**
19
+ * GarbageCollector: the piece of logic executed on mounting of
20
+ * an useAsyncCollection() hook, and on update of hook params, to update
21
+ * the state according to the new param values. It increments by 1 `numRefs`
22
+ * counters for the requested collection items.
23
+ */
24
+ function gcOnWithhold(ids, path, gs) {
25
+ const collection = {
26
+ ...gs.get(path)
27
+ };
28
+ for (let i = 0; i < ids.length; ++i) {
29
+ const id = ids[i];
30
+ let envelope = collection[id];
31
+ if (envelope) envelope = {
32
+ ...envelope,
33
+ numRefs: 1 + envelope.numRefs
34
+ };else envelope = (0, _useAsyncData.newAsyncDataEnvelope)(null, {
35
+ numRefs: 1
36
+ });
37
+ collection[id] = envelope;
38
+ }
39
+ gs.set(path, collection);
40
+ }
41
+ function idsToStringSet(ids) {
42
+ const res = new Set();
43
+ for (let i = 0; i < ids.length; ++i) {
44
+ res.add(ids[i].toString());
45
+ }
46
+ return res;
47
+ }
48
+
49
+ /**
50
+ * GarbageCollector: the piece of logic executed on un-mounting of
51
+ * an useAsyncCollection() hook, and on update of hook params, to clean-up
52
+ * after the previous param values. It decrements by 1 `numRefs` counters
53
+ * for previously requested collection items, and also drops from the state
54
+ * stale records.
55
+ */
56
+ function gcOnRelease(ids, path, gs, gcAge) {
57
+ const entries = Object.entries(gs.get(path));
58
+ const now = Date.now();
59
+ const idSet = idsToStringSet(ids);
60
+ const collection = {};
61
+ for (let i = 0; i < entries.length; ++i) {
62
+ const [id, envelope] = entries[i];
63
+ if (envelope) {
64
+ const toBeReleased = idSet.has(id);
65
+ let {
66
+ numRefs
67
+ } = envelope;
68
+ if (toBeReleased) --numRefs;
69
+ if (gcAge > now - envelope.timestamp || numRefs > 0) {
70
+ collection[id] = toBeReleased ? {
71
+ ...envelope,
72
+ numRefs
73
+ } : envelope;
74
+ } else if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
75
+ // eslint-disable-next-line no-console
76
+ console.log(`useAsyncCollection(): Garbage collected at the path "${path}", ID = ${id}`);
77
+ }
78
+ }
79
+ }
80
+ gs.set(path, collection);
81
+ }
82
+ function normalizeIds(idOrIds) {
83
+ if (Array.isArray(idOrIds)) {
84
+ const res = [...idOrIds];
85
+ res.sort();
86
+ return res;
87
+ }
88
+ return [idOrIds];
89
+ }
90
+
91
+ /**
92
+ * Inits/updates, and returns the heap.
93
+ */
94
+ function useHeap(ids, path, loader, gs) {
95
+ const ref = (0, _react.useRef)();
96
+ let heap = ref.current;
97
+ if (heap) {
98
+ // Update.
99
+ heap.ids = ids;
100
+ heap.path = path;
101
+ heap.loader = loader;
102
+ heap.globalState = gs;
103
+ } else {
104
+ // Initialization.
105
+ const reload = async customLoader => {
106
+ const heap2 = ref.current;
107
+ const localLoader = customLoader || heap2.loader;
108
+ if (!localLoader || !heap2.globalState || !heap2.ids) {
109
+ throw Error('Internal error');
110
+ }
111
+ for (let i = 0; i < heap2.ids.length; ++i) {
112
+ const id = heap2.ids[i];
113
+ const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;
114
+
115
+ // eslint-disable-next-line no-await-in-loop
116
+ await (0, _useAsyncData.load)(itemPath, (oldData, meta) => localLoader(id, oldData, meta), heap2.globalState);
117
+ }
118
+ };
119
+ heap = {
120
+ globalState: gs,
121
+ ids,
122
+ path,
123
+ loader,
124
+ reload,
125
+ reloadSingle: customLoader => ref.current.reload(customLoader && ((id, ...args) => customLoader(...args)))
126
+ };
127
+ ref.current = heap;
128
+ }
129
+ return heap;
130
+ }
131
+
18
132
  /**
19
133
  * Resolves and stores at the given `path` of the global state elements of
20
134
  * an asynchronous data collection.
@@ -24,42 +138,12 @@ var _utils = require("./utils");
24
138
  // Perhaps, a bunch of logic blocks can be split into stand-alone functions,
25
139
  // and reused in both hooks.
26
140
  function useAsyncCollection(idOrIds, path, loader, options = {}) {
27
- const ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
141
+ const ids = normalizeIds(idOrIds);
28
142
  const maxage = options.maxage ?? _useAsyncData.DEFAULT_MAXAGE;
29
143
  const refreshAge = options.refreshAge ?? maxage;
30
144
  const garbageCollectAge = options.garbageCollectAge ?? maxage;
31
-
32
- // To avoid unnecessary work if consumer passes down the same IDs
33
- // in an unstable order.
34
- // TODO: Should we also filter out any duplicates? Or just assume consumer
35
- // knows what he is doing, and won't place duplicates into IDs array?e
36
- ids.sort();
37
145
  const globalState = (0, _GlobalStateProvider.getGlobalState)();
38
- const {
39
- current: heap
40
- } = (0, _react.useRef)({});
41
- heap.globalState = globalState;
42
- heap.ids = ids;
43
- heap.path = path;
44
- heap.loader = loader;
45
- if (!heap.reload) {
46
- heap.reload = async customLoader => {
47
- const localLoader = customLoader || heap.loader;
48
- if (!localLoader || !heap.globalState || !heap.ids) {
49
- throw Error('Internal error');
50
- }
51
- for (let i = 0; i < heap.ids.length; ++i) {
52
- const id = heap.ids[i];
53
- const itemPath = heap.path ? `${heap.path}.${id}` : `${id}`;
54
-
55
- // eslint-disable-next-line no-await-in-loop
56
- await (0, _useAsyncData.load)(itemPath, (oldData, meta) => localLoader(id, oldData, meta), heap.globalState);
57
- }
58
- };
59
- }
60
- if (!Array.isArray(idOrIds)) {
61
- heap.reloadD = customLoader => heap.reload(customLoader && ((id, ...args) => customLoader(...args)));
62
- }
146
+ const heap = useHeap(ids, path, loader, globalState);
63
147
 
64
148
  // Server-side logic.
65
149
  if (globalState.ssrContext && !options.noSSR) {
@@ -82,45 +166,19 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
82
166
  } else {
83
167
  // Reference-counting & garbage collection.
84
168
 
169
+ const idsHash = (0, _utils.hash)(ids);
170
+
85
171
  // TODO: Violation of rules of hooks is fine here,
86
172
  // but perhaps it can be refactored to avoid the need for it.
87
173
  (0, _react.useEffect)(() => {
88
174
  // eslint-disable-line react-hooks/rules-of-hooks
89
- for (let i = 0; i < ids.length; ++i) {
90
- const id = ids[i];
91
- const itemPath = path ? `${path}.${id}` : `${id}`;
92
- const state = globalState.get(itemPath, {
93
- initialValue: (0, _useAsyncData.newAsyncDataEnvelope)()
94
- });
95
- const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';
96
- globalState.set(numRefsPath, state.numRefs + 1);
97
- }
98
- return () => {
99
- for (let i = 0; i < ids.length; ++i) {
100
- const id = ids[i];
101
- const itemPath = path ? `${path}.${id}` : `${id}`;
102
- const state2 = globalState.get(itemPath);
103
- if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
104
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
105
- /* eslint-disable no-console */
106
- console.log(`ReactGlobalState - useAsyncCollection garbage collected at path ${itemPath || ''}`);
107
- /* eslint-enable no-console */
108
- }
109
- globalState.dropDependencies(itemPath || '');
110
- globalState.set(itemPath, {
111
- ...state2,
112
- data: null,
113
- numRefs: 0,
114
- timestamp: 0
115
- });
116
- } else {
117
- const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';
118
- globalState.set(numRefsPath, state2.numRefs - 1);
119
- }
120
- }
121
- };
175
+ gcOnWithhold(ids, path, globalState);
176
+ return () => gcOnRelease(ids, path, globalState, garbageCollectAge);
177
+
178
+ // `ids` are represented in the dependencies array by `idsHash` value,
179
+ // as useEffect() hook requires a constant size of dependencies array.
122
180
  // eslint-disable-next-line react-hooks/exhaustive-deps
123
- }, [garbageCollectAge, globalState, path, ...ids]);
181
+ }, [garbageCollectAge, globalState, idsHash, path]);
124
182
 
125
183
  // NOTE: a bunch of Rules of Hooks ignored belows because in our very
126
184
  // special case the otherwise wrong behavior is actually what we need.
@@ -177,7 +235,7 @@ function useAsyncCollection(idOrIds, path, loader, options = {}) {
177
235
  return {
178
236
  data: maxage < Date.now() - timestamp ? null : e?.data ?? null,
179
237
  loading: !!e?.operationId,
180
- reload: heap.reloadD,
238
+ reload: heap.reloadSingle,
181
239
  timestamp
182
240
  };
183
241
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useAsyncCollection.js","names":["_react","require","_uuid","_GlobalStateProvider","_useAsyncData","_useGlobalState","_interopRequireDefault","_utils","useAsyncCollection","idOrIds","path","loader","options","ids","Array","isArray","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","sort","globalState","getGlobalState","current","heap","useRef","reload","customLoader","localLoader","Error","i","length","id","itemPath","load","oldData","meta","reloadD","args","ssrContext","noSSR","operationId","uuid","state","get","initialValue","newAsyncDataEnvelope","timestamp","pending","push","data","useEffect","numRefsPath","set","numRefs","state2","Date","now","process","env","NODE_ENV","isDebugMode","console","log","dropDependencies","loadTriggeredForIds","Set","deps","hasChangedDependencies","charAt","add","has","localState","useGlobalState","e","loading","res","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 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 isDebugMode,\n} from './utils';\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 }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: {\n [id in IdT]: CollectionItemT<DataT>;\n }\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;\n loader?: AsyncCollectionLoaderT<DataT, IdT>;\n reload?: AsyncCollectionReloaderT<DataT, IdT>;\n reloadD?: AsyncDataReloaderT<DataT>;\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}`> =\n 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}`> =\n 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\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.\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 = Array.isArray(idOrIds) ? idOrIds : [idOrIds];\n\n const maxage: number = options.maxage ?? DEFAULT_MAXAGE;\n const refreshAge: number = options.refreshAge ?? maxage;\n const garbageCollectAge: number = options.garbageCollectAge ?? maxage;\n\n // To avoid unnecessary work if consumer passes down the same IDs\n // in an unstable order.\n // TODO: Should we also filter out any duplicates? Or just assume consumer\n // knows what he is doing, and won't place duplicates into IDs array?e\n ids.sort();\n\n const globalState = getGlobalState();\n\n const { current: heap } = useRef<HeapT<DataT, IdT>>({});\n\n heap.globalState = globalState;\n heap.ids = ids;\n heap.path = path;\n heap.loader = loader;\n\n if (!heap.reload) {\n heap.reload = async (customLoader?: AsyncCollectionLoaderT<DataT, IdT>) => {\n const localLoader = customLoader || heap.loader;\n if (!localLoader || !heap.globalState || !heap.ids) {\n throw Error('Internal error');\n }\n\n for (let i = 0; i < heap.ids.length; ++i) {\n const id = heap.ids[i]!;\n const itemPath = heap.path ? `${heap.path}.${id}` : `${id}`;\n\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n heap.globalState,\n );\n }\n };\n }\n\n if (!Array.isArray(idOrIds)) {\n heap.reloadD = (customLoader) => heap.reload!(\n customLoader && ((id, ...args) => customLoader(...args)),\n );\n }\n\n // Server-side logic.\n if (globalState.ssrContext && !options.noSSR) {\n const operationId: OperationIdT = `S${uuid()}`;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, operationId),\n );\n }\n }\n\n // Client-side logic.\n } else {\n // Reference-counting & garbage collection.\n\n // 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 for (let i = 0; i < ids.length; ++i) {\n const id = ids[i];\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(\n itemPath,\n { initialValue: newAsyncDataEnvelope() },\n );\n\n const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';\n globalState.set<ForceT, number>(numRefsPath, state.numRefs + 1);\n }\n\n return () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i];\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>\n >(itemPath);\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 - useAsyncCollection garbage collected at path ${\n itemPath || ''\n }`,\n );\n /* eslint-enable no-console */\n }\n globalState.dropDependencies(itemPath || '');\n globalState.set<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n ...state2,\n data: null,\n numRefs: 0,\n timestamp: 0,\n });\n } else {\n const numRefsPath = itemPath ? `${itemPath}.numRefs` : 'numRefs';\n globalState.set<ForceT, number>(numRefsPath, state2.numRefs - 1);\n }\n }\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [garbageCollectAge, globalState, path, ...ids]);\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 const loadTriggeredForIds = new Set<IdT>();\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n (async () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n loadTriggeredForIds.add(id);\n // eslint-disable-next-line no-await-in-loop\n await load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n })();\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n (async () => {\n const { deps } = options;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n if (\n deps\n && globalState.hasChangedDependencies(itemPath || '', deps)\n && !loadTriggeredForIds.has(id)\n ) {\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: null | DataT, meta) => loader(id, oldData, meta),\n globalState,\n );\n }\n }\n })();\n\n // Here we need to default to empty array, so that this hook is re-evaluated\n // only when dependencies specified in options change, and it should not be\n // re-evaluated at all if no `deps` option is used.\n }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<\n ForceT, { [id: string]: AsyncDataEnvelopeT<DataT> }\n >(path, {});\n\n if (!Array.isArray(idOrIds)) {\n const e = localState[idOrIds];\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.reloadD!,\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 (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const e = localState[id];\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\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"],"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;;AA2EA;AACA;AACA;AACA;;AAoDA;AACA;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C,WAAW;IAChC,MAAMM,SAAS,GAAG2B,CAAC,EAAE3B,SAAS,IAAI,CAAC;IAEnC6B,GAAG,CAACC,KAAK,CAAC7C,EAAE,CAAC,GAAG;MACdkB,IAAI,EAAElC,MAAM,GAAGwC,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGV,SAAS,GAAG,IAAI,GAAI2B,CAAC,EAAExB,IAAI,IAAI,IAAK;MAChEyB,OAAO;MACP5B;IACF,CAAC;IACD6B,GAAG,CAACD,OAAO,KAAKA,OAAO;IACvB,IAAIC,GAAG,CAAC7B,SAAS,GAAGA,SAAS,EAAE6B,GAAG,CAAC7B,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAO6B,GAAG;AACZ;AAAC,IAAAI,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEc1E,kBAAkB","ignoreList":[]}
1
+ {"version":3,"file":"useAsyncCollection.js","names":["_react","require","_uuid","_GlobalStateProvider","_useAsyncData","_useGlobalState","_interopRequireDefault","_utils","gcOnWithhold","ids","path","gs","collection","get","i","length","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","useHeap","loader","ref","useRef","heap","current","globalState","reload","customLoader","heap2","localLoader","Error","itemPath","load","oldData","meta","reloadSingle","args","useAsyncCollection","options","maxage","DEFAULT_MAXAGE","refreshAge","garbageCollectAge","getGlobalState","ssrContext","noSSR","operationId","uuid","state","initialValue","pending","push","data","idsHash","hash","useEffect","loadTriggeredForIds","state2","deps","hasChangedDependencies","charAt","dropDependencies","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 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> = { [id in 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 }) => DataT | Promise<DataT | null> | null;\n\nexport type AsyncCollectionReloaderT<\n DataT,\n IdT extends number | string = number | string,\n>\n = (loader?: AsyncCollectionLoaderT<DataT, IdT>) => Promise<void>;\n\ntype CollectionItemT<DataT> = {\n data: DataT | null;\n loading: boolean;\n timestamp: number;\n};\n\nexport type UseAsyncCollectionResT<\n DataT,\n IdT extends number | string = number | string,\n> = {\n items: {\n [id in IdT]: CollectionItemT<DataT>;\n }\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 (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\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 (let i = 0; i < ids.length; ++i) {\n res.add(ids[i]!.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 (let i = 0; i < entries.length; ++i) {\n const [id, envelope] = entries[i]!;\n\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();\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>>();\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 if (!localLoader || !heap2.globalState || !heap2.ids) {\n throw Error('Internal error');\n }\n\n for (let i = 0; i < heap2.ids.length; ++i) {\n const id = heap2.ids[i]!;\n const itemPath = heap2.path ? `${heap2.path}.${id}` : `${id}`;\n\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: DataT | null, meta) => localLoader(id, oldData, meta),\n heap2.globalState,\n );\n }\n };\n heap = {\n globalState: gs,\n ids,\n path,\n loader,\n reload,\n reloadSingle: (customLoader) => ref.current!.reload(\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}`> =\n 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}`> =\n 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\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.\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 (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state = globalState.get<ForceT, AsyncDataEnvelopeT<DataT>>(itemPath, {\n initialValue: newAsyncDataEnvelope<DataT>(),\n });\n if (!state.timestamp && !state.operationId) {\n globalState.ssrContext.pending.push(\n load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state.data,\n timestamp: state.timestamp,\n }, operationId),\n );\n }\n }\n\n // Client-side logic.\n } else {\n // Reference-counting & garbage collection.\n\n const idsHash = hash(ids);\n\n // TODO: Violation of rules of hooks is fine here,\n // but perhaps it can be refactored to avoid the need for it.\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n gcOnWithhold(ids, path, globalState);\n return () => gcOnRelease(ids, path, globalState, garbageCollectAge);\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 const loadTriggeredForIds = new Set<IdT>();\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n (async () => {\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n const state2: AsyncDataEnvelopeT<DataT> = globalState.get<\n ForceT, AsyncDataEnvelopeT<DataT>>(itemPath);\n\n const { deps } = options;\n if (\n (deps && globalState.hasChangedDependencies(itemPath, deps))\n || (\n refreshAge < Date.now() - state2.timestamp\n && (!state2.operationId || state2.operationId.charAt(0) === 'S')\n )\n ) {\n if (!deps) globalState.dropDependencies(itemPath);\n loadTriggeredForIds.add(id);\n // eslint-disable-next-line no-await-in-loop\n await load(itemPath, (...args) => loader(id, ...args), globalState, {\n data: state2.data,\n timestamp: state2.timestamp,\n });\n }\n }\n })();\n });\n\n useEffect(() => { // eslint-disable-line react-hooks/rules-of-hooks\n (async () => {\n const { deps } = options;\n for (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const itemPath = path ? `${path}.${id}` : `${id}`;\n if (\n deps\n && globalState.hasChangedDependencies(itemPath || '', deps)\n && !loadTriggeredForIds.has(id)\n ) {\n // eslint-disable-next-line no-await-in-loop\n await load(\n itemPath,\n (oldData: null | DataT, meta) => loader(id, oldData, meta),\n globalState,\n );\n }\n }\n })();\n\n // Here we need to default to empty array, so that this hook is re-evaluated\n // only when dependencies specified in options change, and it should not be\n // re-evaluated at all if no `deps` option is used.\n }, options.deps || []); // eslint-disable-line react-hooks/exhaustive-deps\n }\n\n const [localState] = useGlobalState<\n ForceT, { [id: string]: AsyncDataEnvelopeT<DataT> }\n >(path, {});\n\n if (!Array.isArray(idOrIds)) {\n const e = localState[idOrIds];\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 (let i = 0; i < ids.length; ++i) {\n const id = ids[i]!;\n const e = localState[id];\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\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"],"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;;AAiFA;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,IAAII,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGL,GAAG,CAACM,MAAM,EAAE,EAAED,CAAC,EAAE;IACnC,MAAME,EAAE,GAAGP,GAAG,CAACK,CAAC,CAAE;IAClB,IAAIG,QAAQ,GAAGL,UAAU,CAACI,EAAE,CAAC;IAC7B,IAAIC,QAAQ,EAAEA,QAAQ,GAAG;MAAE,GAAGA,QAA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ACuE,OAAO,KAAKA,OAAO;IACvB,IAAIvE,GAAG,CAACa,SAAS,GAAGA,SAAS,EAAEb,GAAG,CAACa,SAAS,GAAGA,SAAS;EAC1D;EAEA,OAAOb,GAAG;AACZ;AAAC,IAAA2E,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEclC,kBAAkB","ignoreList":[]}
@@ -4,6 +4,8 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.cloneDeepForLog = cloneDeepForLog;
7
+ exports.escape = escape;
8
+ exports.hash = hash;
7
9
  exports.isDebugMode = isDebugMode;
8
10
  var _lodash = require("lodash");
9
11
  // TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils
@@ -52,6 +54,7 @@ const cloneDeepBailKeys = new Set();
52
54
  */
53
55
  function cloneDeepForLog(value, key = '') {
54
56
  if (cloneDeepBailKeys.has(key)) {
57
+ // eslint-disable-next-line no-console
55
58
  console.warn(`The logged value won't be clonned (key "${key}").`);
56
59
  return value;
57
60
  }
@@ -59,9 +62,30 @@ function cloneDeepForLog(value, key = '') {
59
62
  const res = (0, _lodash.cloneDeep)(value);
60
63
  const time = Date.now() - start;
61
64
  if (time > 300) {
65
+ // eslint-disable-next-line no-console
62
66
  console.warn(`${time}ms spent to clone the logged value (key "${key}").`);
63
67
  cloneDeepBailKeys.add(key);
64
68
  }
65
69
  return res;
66
70
  }
71
+
72
+ /**
73
+ * Converts given value to an escaped string. For now, we are good with the most
74
+ * trivial escape logic:
75
+ * - '%' characters are replaced by '%0' code pair;
76
+ * - '/' characters are replaced by '%1' code pair.
77
+ */
78
+ function escape(x) {
79
+ return typeof x === 'string' ? x.replace(/%/g, '%0').replace(/\//g, '%1') : x.toString();
80
+ }
81
+
82
+ /**
83
+ * Hashes given string array. For our current needs we are fine to go with
84
+ * the most trivial implementation, which probably should not be called "hash"
85
+ * in the strict sense: we just escape each given string to not include '/'
86
+ * characters, and then we join all those strings using '/' as the separator.
87
+ */
88
+ function hash(items) {
89
+ return items.map(escape).join('/');
90
+ }
67
91
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","names":["_lodash","require","isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error","cloneDeepBailKeys","Set","cloneDeepForLog","value","key","has","console","warn","start","Date","now","res","cloneDeep","time","add"],"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\ndeclare const force: unique symbol;\ndeclare 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 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 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 (error) {\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 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 console.warn(`${time}ms spent to clone the logged value (key \"${key}\").`);\n cloneDeepBailKeys.add(key);\n }\n\n return res;\n}\n"],"mappings":";;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAIA;AACA;;AAcA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,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,OAAOC,KAAK,EAAE;IACd,OAAO,KAAK;EACd;AACF;AAEA,MAAMC,iBAAiB,GAAG,IAAIC,GAAG,CAAS,CAAC;;AAE3C;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,eAAeA,CAAIC,KAAQ,EAAEC,GAAW,GAAG,EAAE,EAAK;EAChE,IAAIJ,iBAAiB,CAACK,GAAG,CAACD,GAAG,CAAC,EAAE;IAC9BE,OAAO,CAACC,IAAI,CAAC,2CAA2CH,GAAG,KAAK,CAAC;IACjE,OAAOD,KAAK;EACd;EAEA,MAAMK,KAAK,GAAGC,IAAI,CAACC,GAAG,CAAC,CAAC;EACxB,MAAMC,GAAG,GAAG,IAAAC,iBAAS,EAACT,KAAK,CAAC;EAC5B,MAAMU,IAAI,GAAGJ,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGF,KAAK;EAC/B,IAAIK,IAAI,GAAG,GAAG,EAAE;IACdP,OAAO,CAACC,IAAI,CAAC,GAAGM,IAAI,4CAA4CT,GAAG,KAAK,CAAC;IACzEJ,iBAAiB,CAACc,GAAG,CAACV,GAAG,CAAC;EAC5B;EAEA,OAAOO,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"utils.js","names":["_lodash","require","isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","error","cloneDeepBailKeys","Set","cloneDeepForLog","value","key","has","console","warn","start","Date","now","res","cloneDeep","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\ndeclare const force: unique symbol;\ndeclare 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 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 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 (error) {\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"],"mapp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AC,CAACA,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,GAC1CD,CAAC,CAACE,QAAQ,CAAC,CAAC;AAClB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,SAASC,IAAIA,CAACC,KAA6B,EAAU;EAC1D,OAAOA,KAAK,CAACC,GAAG,CAACN,MAAM,CAAC,CAACO,IAAI,CAAC,GAAG,CAAC;AACpC","ignoreList":[]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT } from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"AAAA,OAAOA,WAAW;AAElB,OAAOC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAGf,OAAOC,UAAU;AAEjB,OAAOC,kBAAkB;AAKzB,SAOEC,oBAAoB,EACpBC,YAAY;AAGd,OAAOC,cAAc;AAQrB,SAOEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBK,oBAAoB,EACpBF,UAAU,EACVC,kBAAkB,EAClBE,YAAY,EACZC,cAAc;AAkBhB,MAAMC,GAAG,GAAG;EACVP,cAAc;EACdC,aAAa;EACbH,WAAW;EACXC,mBAAmB;EACnBK,oBAAoB;EACpBF,UAAU;EACVC,kBAAkB;EAClBE,YAAY;EACZC;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAG/B;EACF,OAAOD,GAAG;AACZ","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["GlobalState","GlobalStateProvider","getGlobalState","getSsrContext","SsrContext","useAsyncCollection","newAsyncDataEnvelope","useAsyncData","useGlobalState","api","withGlobalStateType"],"sources":["../../src/index.ts"],"sourcesContent":["import GlobalState from './GlobalState';\n\nimport GlobalStateProvider, {\n getGlobalState,\n getSsrContext,\n} from './GlobalStateProvider';\n\nimport SsrContext from './SsrContext';\n\nimport useAsyncCollection, {\n type UseAsyncCollectionI,\n type UseAsyncCollectionResT,\n} from './useAsyncCollection';\n\nimport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncDataI,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n newAsyncDataEnvelope,\n useAsyncData,\n} from './useAsyncData';\n\nimport useGlobalState, { type UseGlobalStateI } from './useGlobalState';\n\nexport type { AsyncCollectionLoaderT, AsyncCollectionT } from './useAsyncCollection';\n\nexport type { SetterT, UseGlobalStateResT } from './useGlobalState';\n\nexport type { ForceT, ValueOrInitializerT } from './utils';\n\nexport {\n type AsyncDataEnvelopeT,\n type AsyncDataLoaderT,\n type AsyncDataReloaderT,\n type UseAsyncCollectionResT,\n type UseAsyncDataOptionsT,\n type UseAsyncDataResT,\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\ninterface API<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n> {\n getGlobalState: typeof getGlobalState<StateT, SsrContextT>;\n getSsrContext: typeof getSsrContext<SsrContextT>,\n GlobalState: typeof GlobalState<StateT, SsrContextT>,\n GlobalStateProvider: typeof GlobalStateProvider<StateT, SsrContextT>,\n newAsyncDataEnvelope: typeof newAsyncDataEnvelope,\n SsrContext: typeof SsrContext<StateT>,\n useAsyncCollection: UseAsyncCollectionI<StateT>,\n useAsyncData: UseAsyncDataI<StateT>,\n useGlobalState: UseGlobalStateI<StateT>,\n}\n\nconst api = {\n getGlobalState,\n getSsrContext,\n GlobalState,\n GlobalStateProvider,\n newAsyncDataEnvelope,\n SsrContext,\n useAsyncCollection,\n useAsyncData,\n useGlobalState,\n};\n\nexport function withGlobalStateType<\n StateT,\n SsrContextT extends SsrContext<StateT> = SsrContext<StateT>,\n>() {\n return api as API<StateT, SsrContextT>;\n}\n"],"mappings":"AAAA,OAAOA,WAAW;AAElB,OAAOC,mBAAmB,IACxBC,cAAc,EACdC,aAAa;AAGf,OAAOC,UAAU;AAEjB,OAAOC,kBAAkB;AAKzB,SAOEC,oBAAoB,EACpBC,YAAY;AAGd,OAAOC,cAAc;AAQrB,SAOEN,cAAc,EACdC,aAAa,EACbH,WAAW,EACXC,mBAAmB,EACnBK,oBAAoB,EACpBF,UAAU,EACVC,kBAAkB,EAClBE,YAAY,EACZC,cAAc;AAkBhB,MAAMC,GAAG,GAAG;EACVP,cAAc;EACdC,aAAa;EACbH,WAAW;EACXC,mBAAmB;EACnBK,oBAAoB;EACpBF,UAAU;EACVC,kBAAkB;EAClBE,YAAY;EACZC;AACF,CAAC;AAED,OAAO,SAASE,mBAAmBA,CAAA,EAG/B;EACF,OAAOD,GAAG;AACZ","ignoreList":[]}