@dr.pogodin/react-global-state 0.20.0 → 0.21.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,273 +0,0 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.DEFAULT_MAXAGE = void 0;
8
- exports.load = load;
9
- exports.newAsyncDataEnvelope = newAsyncDataEnvelope;
10
- exports.useAsyncData = useAsyncData;
11
- var _react = require("react");
12
- var _uuid = require("uuid");
13
- var _jsUtils = require("@dr.pogodin/js-utils");
14
- var _GlobalStateProvider = require("./GlobalStateProvider");
15
- var _useGlobalState = _interopRequireDefault(require("./useGlobalState"));
16
- var _utils = require("./utils");
17
- /**
18
- * Loads and uses async data into the GlobalState path.
19
- */
20
-
21
- const DEFAULT_MAXAGE = exports.DEFAULT_MAXAGE = 5 * _jsUtils.MIN_MS; // 5 minutes.
22
-
23
- // NOTE: Here, and below it is important whether a loader and related
24
- // (re-)loading handlers return a promise or a value, as returning promises
25
- // mean the async mode, in which related global state values are updated
26
- // asynchronously (the new value comes into effect in a next rendering cycle),
27
- // while returning a non-promise value means a synchronous mode, in which
28
- // related global state values are updated immediately, within the current
29
- // rendering cycle.
30
-
31
- function newAsyncDataEnvelope(initialData = null, {
32
- numRefs = 0,
33
- timestamp = 0
34
- } = {}) {
35
- return {
36
- data: initialData,
37
- numRefs,
38
- operationId: '',
39
- timestamp
40
- };
41
- }
42
- /**
43
- * Writes data into the global state, and prints console messages in the debug
44
- * mode.
45
- */
46
- function setState(data, path, gs, prevState = gs.get(path)) {
47
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
48
- /* eslint-disable no-console */
49
- console.groupCollapsed(`ReactGlobalState: async data (re-)loaded. Path: "${path ?? ''}"`);
50
- console.log('Data:', (0, _utils.cloneDeepForLog)(data, path ?? ''));
51
- /* eslint-enable no-console */
52
- }
53
- gs.set(path, {
54
- ...prevState,
55
- data,
56
- operationId: '',
57
- timestamp: Date.now()
58
- });
59
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
60
- /* eslint-disable no-console */
61
- console.groupEnd();
62
- /* eslint-enable no-console */
63
- }
64
- }
65
- function finalizeLoad(data, path, gs, operationId) {
66
- // NOTE: We don't really mean that it hasn't been aborted,
67
- // the "false" flag rather says we don't need to trigger "on aborted"
68
- // callback for this operation, if any is registered - just drop it.
69
- //
70
- // Also, in the synchronous state update mode, we don't really need to set up
71
- // the abort callback at all (as there is no way to use it), but for now it is
72
- // set up, thus it should be cleaned out here.
73
- gs.asyncDataLoadDone(operationId, false);
74
- const state = gs.get(path);
75
- if (operationId === state?.operationId) setState(data, path, gs, state);
76
- }
77
-
78
- /**
79
- * Executes the data loading operation.
80
- * @param path Data segment path inside the global state.
81
- * @param loader Data loader.
82
- * @param globalState The global state instance.
83
- * @param oldData Optional. Previously fetched data, currently stored in
84
- * the state, if already fetched by the caller; otherwise, they will be fetched
85
- * by the load() function itself.
86
- * @param opIdPrefix operationId prefix to use, which should be
87
- * 'C' at the client-side (default), or 'S' at the server-side (within SSR
88
- * context).
89
- * @return Resolves once the operation is done.
90
- * @ignore
91
- */
92
- function load(path, loader, globalState, old,
93
- // TODO: Should this parameter be just a binary flag (client or server),
94
- // and UUID always generated inside this function? Or do we need it in
95
- // the caller methods as well, in some cases (see useAsyncCollection()
96
- // use case as well).
97
- operationId = `C${(0, _uuid.v4)()}`) {
98
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
99
- /* eslint-disable no-console */
100
- console.log(`ReactGlobalState: async data (re-)loading. Path: "${path ?? ''}"`);
101
- /* eslint-enable no-console */
102
- }
103
- const operationIdPath = path ? `${path}.operationId` : 'operationId';
104
- {
105
- const prevOperationId = globalState.get(operationIdPath);
106
- if (prevOperationId) globalState.asyncDataLoadDone(prevOperationId, true);
107
- }
108
- globalState.set(operationIdPath, operationId);
109
- let definedOld = old;
110
- if (!definedOld) {
111
- // TODO: Can we improve the typing, to avoid ForceT?
112
- const e = globalState.get(path);
113
- definedOld = {
114
- data: e.data,
115
- timestamp: e.timestamp
116
- };
117
- }
118
- const dataOrPromise = loader(definedOld.data, {
119
- isAborted: () => {
120
- // TODO: Can we improve the typing, to avoid ForceT?
121
- const opid = globalState.get(path).operationId;
122
- return opid !== operationId;
123
- },
124
- oldDataTimestamp: definedOld.timestamp,
125
- setAbortCallback(cb) {
126
- const opid = globalState.get(path).operationId;
127
- if (opid !== operationId) {
128
- throw Error(`Operation #${operationId} has completed already`);
129
- }
130
- globalState.setAsyncDataAbortCallback(operationId, cb);
131
- }
132
- });
133
- if (dataOrPromise instanceof Promise) {
134
- return dataOrPromise.then(data => {
135
- finalizeLoad(data, path, globalState, operationId);
136
- }).finally(() => {
137
- // NOTE: We don't really mean that it hasn't been aborted,
138
- // the "false" flag rather says we don't need to trigger "on aborted"
139
- // callback for this operation, if any is registered - just drop it.
140
- globalState.asyncDataLoadDone(operationId, false);
141
- });
142
- }
143
- finalizeLoad(dataOrPromise, path, globalState, operationId);
144
- return undefined;
145
- }
146
-
147
- /**
148
- * Resolves asynchronous data, and stores them at given `path` of global
149
- * state.
150
- */
151
-
152
- // TODO: Perhaps split the heap management to a dedicated hook,
153
- // as it is done inside useAsyncCollection().
154
-
155
- function useAsyncData(path, loader, options = {}) {
156
- const maxage = options.maxage ?? DEFAULT_MAXAGE;
157
- const refreshAge = options.refreshAge ?? maxage;
158
- const garbageCollectAge = options.garbageCollectAge ?? maxage;
159
-
160
- // Note: here we can't depend on useGlobalState() to init the initial value,
161
- // because that way we'll have issues with SSR (see details below).
162
- const globalState = (0, _GlobalStateProvider.getGlobalState)();
163
- const state = globalState.get(path, {
164
- initialValue: newAsyncDataEnvelope()
165
- });
166
- const {
167
- current: heap
168
- } = (0, _react.useRef)({});
169
- heap.globalState = globalState;
170
- heap.path = path;
171
- heap.loader = loader;
172
- heap.reload ??= customLoader => {
173
- const localLoader = customLoader ?? heap.loader;
174
- if (!localLoader || !heap.globalState) throw Error('Internal error');
175
- return load(heap.path, localLoader, heap.globalState);
176
- };
177
- heap.set ??= data => {
178
- if (!heap.globalState) throw Error('Internal error');
179
- setState(data, heap.path, heap.globalState);
180
- };
181
- if (globalState.ssrContext) {
182
- if (!options.disabled && !options.noSSR && !state.operationId && !state.timestamp) {
183
- const promiseOrVoid = load(path, loader, globalState, {
184
- data: state.data,
185
- timestamp: state.timestamp
186
- }, `S${(0, _uuid.v4)()}`);
187
- if (promiseOrVoid instanceof Promise) {
188
- globalState.ssrContext.pending.push(promiseOrVoid);
189
- }
190
- }
191
- } else {
192
- const {
193
- disabled
194
- } = options;
195
-
196
- // This takes care about the client-side reference counting, and garbage
197
- // collection.
198
- //
199
- // Note: the Rules of Hook below are violated by conditional call to a hook,
200
- // but as the condition is actually server-side or client-side environment,
201
- // it is effectively non-conditional at the runtime.
202
- //
203
- // TODO: Though, maybe there is a way to refactor it into a cleaner code.
204
- // The same applies to other useEffect() hooks below.
205
- (0, _react.useEffect)(() => {
206
- // eslint-disable-line react-hooks/rules-of-hooks
207
- const numRefsPath = path ? `${path}.numRefs` : 'numRefs';
208
- if (!disabled) {
209
- const numRefs = globalState.get(numRefsPath);
210
- globalState.set(numRefsPath, numRefs + 1);
211
- }
212
- return () => {
213
- if (!disabled) {
214
- const state2 = globalState.get(path);
215
- if (state2.numRefs === 1 && garbageCollectAge < Date.now() - state2.timestamp) {
216
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
217
- /* eslint-disable no-console */
218
- console.log(`ReactGlobalState - useAsyncData garbage collected at path ${path ?? ''}`);
219
- /* eslint-enable no-console */
220
- }
221
- globalState.dropDependencies(path ?? '');
222
- globalState.set(path, {
223
- ...state2,
224
- data: null,
225
- numRefs: 0,
226
- timestamp: 0
227
- });
228
- } else {
229
- globalState.set(numRefsPath, state2.numRefs - 1);
230
- }
231
- }
232
- };
233
- }, [disabled, garbageCollectAge, globalState, path]);
234
-
235
- // Note: a bunch of Rules of Hooks ignored belows because in our very
236
- // special case the otherwise wrong behavior is actually what we need.
237
-
238
- // Data loading and refreshing.
239
- (0, _react.useEffect)(() => {
240
- // eslint-disable-line react-hooks/rules-of-hooks
241
- if (!disabled) {
242
- const state2 = globalState.get(path);
243
- const {
244
- deps
245
- } = options;
246
- if (
247
- // The hook is called with a list of dependencies, that mismatch
248
- // dependencies last used to retrieve the data at given path.
249
- deps && globalState.hasChangedDependencies(path ?? '', deps)
250
-
251
- // Data at the path are stale, and are not being loaded.
252
- || refreshAge < Date.now() - state2.timestamp && (!state2.operationId || state2.operationId.startsWith('S'))) {
253
- if (!deps) globalState.dropDependencies(path ?? '');
254
- void load(path, loader, globalState, {
255
- data: state2.data,
256
- timestamp: state2.timestamp
257
- });
258
- }
259
- }
260
- });
261
- }
262
- const [localState] = (0, _useGlobalState.default)(path, newAsyncDataEnvelope());
263
- return {
264
- data: maxage < Date.now() - localState.timestamp ? null : localState.data,
265
- loading: Boolean(localState.operationId),
266
- reload: heap.reload,
267
- set: heap.set,
268
- timestamp: localState.timestamp
269
- };
270
- }
271
-
272
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
273
- //# sourceMappingURL=useAsyncData.js.map
@@ -1 +0,0 @@
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","setState","path","gs","prevState","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","set","Date","now","groupEnd","finalizeLoad","asyncDataLoadDone","state","load","loader","globalState","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 set: (data: DataT | null) => void;\n timestamp: number;\n};\n\n/**\n * Writes data into the global state, and prints console messages in the debug\n * mode.\n */\nfunction setState<\n DataT,\n EnvT extends AsyncDataEnvelopeT<DataT>,\n>(\n data: DataT,\n path: string | null | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n prevState: EnvT = gs.get<ForceT, EnvT>(path),\n) {\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState: async data (re-)loaded. Path: \"${\n path ?? ''\n }\"`,\n );\n console.log('Data:', cloneDeepForLog(data, path ?? ''));\n /* eslint-enable no-console */\n }\n\n gs.set<ForceT, AsyncDataEnvelopeT<DataT>>(path, {\n ...prevState,\n data,\n operationId: '',\n timestamp: Date.now(),\n });\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupEnd();\n /* eslint-enable no-console */\n }\n}\n\nfunction finalizeLoad<DataT>(\n data: DataT,\n path: null | string | undefined,\n gs: GlobalState<unknown, SsrContext<unknown>>,\n operationId: OperationIdT,\n): void {\n // NOTE: We don't really mean that it hasn't been aborted,\n // the \"false\" flag rather says we don't need to trigger \"on aborted\"\n // callback for this operation, if any is registered - just drop it.\n //\n // Also, in the synchronous state update mode, we don't really need to set up\n // the abort callback at all (as there is no way to use it), but for now it is\n // set up, thus it should be cleaned out here.\n gs.asyncDataLoadDone(operationId, false);\n\n type EnvT = AsyncDataEnvelopeT<DataT> | undefined;\n const state: EnvT = gs.get<ForceT, EnvT>(path);\n\n if (operationId === state?.operationId) setState(data, path, gs, state);\n}\n\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\n// TODO: Perhaps split the heap management to a dedicated hook,\n// as it is done inside useAsyncCollection().\ntype HeapT<DataT> = {\n // Note: these heap fields are necessary to make reload() a stable function.\n globalState?: GlobalState<unknown>;\n path?: null | string;\n loader?: AsyncDataLoaderT<DataT>;\n reload?: AsyncDataReloaderT<DataT>;\n set?: (data: DataT | null) => void;\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 heap.set ??= (data: DataT | null) => {\n if (!heap.globalState) throw Error('Internal error');\n setState(data, heap.path, 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 set: heap.set,\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: Async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,KAAKmB,IAAI,CAACnB,IAAI,EAAEoB,MAAM,EAAEC,WAAW,EAAE;YACnCxB,IAAI,EAAEgE,MAAM,CAAChE,IAAI;YACjBD,SAAS,EAAEiE,MAAM,CAACjE;UACpB,CAAC,CAAC;QACJ;MACF;IACF,CAAC,CAAC;EACJ;EAEA,MAAM,CAACsE,UAAU,CAAC,GAAG,IAAAC,uBAAc,EACjCnE,IAAI,EACJP,oBAAoB,CAAQ,CAC9B,CAAC;EAED,OAAO;IACLI,IAAI,EAAE6C,MAAM,GAAG7B,IAAI,CAACC,GAAG,CAAC,CAAC,GAAGoD,UAAU,CAACtE,SAAS,GAAG,IAAI,GAAGsE,UAAU,CAACrE,IAAI;IACzEuE,OAAO,EAAEC,OAAO,CAACH,UAAU,CAACpE,WAAW,CAAC;IACxCoD,MAAM,EAAEF,IAAI,CAACE,MAAM;IACnBtC,GAAG,EAAEoC,IAAI,CAACpC,GAAG;IACbhB,SAAS,EAAEsE,UAAU,CAACtE;EACxB,CAAC;AACH;;AAIA","ignoreList":[]}
@@ -1,148 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _lodash = require("lodash");
8
- var _react = require("react");
9
- var _jsUtils = require("@dr.pogodin/js-utils");
10
- var _GlobalStateProvider = require("./GlobalStateProvider");
11
- var _utils = require("./utils");
12
- // Hook for updates of global state.
13
-
14
- /**
15
- * The primary hook for interacting with the global state, modeled after
16
- * the standard React's
17
- * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).
18
- * It subscribes a component to a given `path` of global state, and provides
19
- * a function to update it. Each time the value at `path` changes, the hook
20
- * triggers re-render of its host component.
21
- *
22
- * **Note:**
23
- * - For performance, the library does not copy objects written to / read from
24
- * global state paths. You MUST NOT manually mutate returned state values,
25
- * or change objects already written into the global state, without explicitly
26
- * clonning them first yourself.
27
- * - State update notifications are asynchronous. When your code does multiple
28
- * global state updates in the same React rendering cycle, all state update
29
- * notifications are queued and dispatched together, after the current
30
- * rendering cycle. In other words, in any given rendering cycle the global
31
- * state values are "fixed", and all changes becomes visible at once in the
32
- * next triggered rendering pass.
33
- *
34
- * @param path Dot-delimitered state path. It can be undefined to
35
- * subscribe for entire state.
36
- *
37
- * Under-the-hood state values are read and written using `lodash`
38
- * [_.get()](https://lodash.com/docs/4.17.15#get) and
39
- * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe
40
- * to access state paths which have not been created before.
41
- * @param initialValue Initial value to set at the `path`, or its
42
- * factory:
43
- * - If a function is given, it will act similar to
44
- * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):
45
- * only if the value at `path` is `undefined`, the function will be executed,
46
- * and the value it returns will be written to the `path`.
47
- * - Otherwise, the given value itself will be written to the `path`,
48
- * if the current value at `path` is `undefined`.
49
- * @return It returs an array with two elements: `[value, setValue]`:
50
- *
51
- * - The `value` is the current value at given `path`.
52
- *
53
- * - The `setValue()` is setter function to write a new value to the `path`.
54
- *
55
- * Similar to the standard React's `useState()`, it supports
56
- * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):
57
- * if `setValue()` is called with a function as argument, that function will
58
- * be called and its return value will be written to `path`. Otherwise,
59
- * the argument of `setValue()` itself is written to `path`.
60
- *
61
- * Also, similar to the standard React's state setters, `setValue()` is
62
- * stable function: it does not change between component re-renders.
63
- */
64
-
65
- // "Enforced type overload"
66
-
67
- // "Entire state overload"
68
-
69
- // "State evaluation overload"
70
-
71
- function useGlobalState(path,
72
- // TODO: Revise it later!
73
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
74
- initialValue
75
-
76
- // TODO: Revise it later!
77
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
78
- ) {
79
- const globalState = (0, _GlobalStateProvider.getGlobalState)();
80
- const ref = (0, _react.useRef)(null);
81
- const [stable] = (0, _react.useState)(() => {
82
- const emitter = new _jsUtils.Emitter();
83
- const setter = value => {
84
- const rc = ref.current;
85
- if (!rc) throw Error('Internal error');
86
- const newState = (0, _lodash.isFunction)(value) ? value(rc.globalState.get(rc.path)) : value;
87
- if (process.env.NODE_ENV !== 'production' && (0, _utils.isDebugMode)()) {
88
- /* eslint-disable no-console */
89
- console.groupCollapsed(`ReactGlobalState - useGlobalState setter triggered for path ${rc.path ?? ''}`);
90
- console.log('New value:', (0, _utils.cloneDeepForLog)(newState, rc.path ?? ''));
91
- console.groupEnd();
92
- /* eslint-enable no-console */
93
- }
94
- rc.globalState.set(rc.path, newState);
95
-
96
- // NOTE: The regular global state's update notifications, automatically
97
- // triggered by the rc.globalState.set() call above, are batched, and
98
- // scheduled to fire asynchronosuly at a later time, which is problematic
99
- // for managed text inputs - if they have their value update delayed to
100
- // future render cycles, it will result in reset of their cursor position
101
- // to the value end. Calling the rc.emitter.emit() below causes a sooner
102
- // state update for the current component, thus working around the issue.
103
- // For additional details see the original issue:
104
- // https://github.com/birdofpreyru/react-global-state/issues/22
105
- if (newState !== rc.prevValue) emitter.emit();
106
- };
107
- const subscribe = emitter.addListener.bind(emitter);
108
- return {
109
- emitter,
110
- setter,
111
- subscribe
112
- };
113
- });
114
- const value = (0, _react.useSyncExternalStore)(stable.subscribe, () => globalState.get(path, {
115
- initialValue
116
- }), () => globalState.get(path, {
117
- initialState: true,
118
- initialValue
119
- }));
120
- ref.current ??= {
121
- globalState,
122
- path,
123
- prevValue: value
124
- };
125
- (0, _react.useEffect)(() => {
126
- ref.current = {
127
- globalState,
128
- path,
129
- prevValue: ref.current.prevValue
130
- };
131
- const watcher = () => {
132
- const nextValue = globalState.get(path);
133
- if (ref.current.prevValue !== nextValue) {
134
- ref.current.prevValue = nextValue;
135
- stable.emitter.emit();
136
- }
137
- };
138
- globalState.watch(watcher);
139
- watcher();
140
- return () => {
141
- globalState.unWatch(watcher);
142
- };
143
- }, [globalState, stable.emitter, path]);
144
- return [value, stable.setter];
145
- }
146
- var _default = exports.default = useGlobalState; // TODO: Revise.
147
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
148
- //# sourceMappingURL=useGlobalState.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useGlobalState.js","names":["_lodash","require","_react","_jsUtils","_GlobalStateProvider","_utils","useGlobalState","path","initialValue","globalState","getGlobalState","ref","useRef","stable","useState","emitter","Emitter","setter","value","rc","current","Error","newState","isFunction","get","process","env","NODE_ENV","isDebugMode","console","groupCollapsed","log","cloneDeepForLog","groupEnd","set","prevValue","emit","subscribe","addListener","bind","useSyncExternalStore","initialState","useEffect","watcher","nextValue","watch","unWatch","_default","exports","default"],"sources":["../../src/useGlobalState.ts"],"sourcesContent":["// Hook for updates of global state.\n\nimport { isFunction } from 'lodash';\n\nimport {\n type Dispatch,\n type SetStateAction,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\nimport { Emitter } from '@dr.pogodin/js-utils';\n\nimport type GlobalState from './GlobalState';\nimport { getGlobalState } from './GlobalStateProvider';\n\nimport {\n type ForceT,\n type LockT,\n type TypeLock,\n type ValueAtPathT,\n type ValueOrInitializerT,\n cloneDeepForLog,\n isDebugMode,\n} from './utils';\n\nexport type SetterT<T> = Dispatch<SetStateAction<T>>;\n\ntype ListenerT = () => void;\n\ntype CurrentT = {\n globalState: GlobalState<unknown>;\n path: null | string | undefined;\n prevValue: unknown;\n};\n\ntype StableT = {\n emitter: Emitter<[]>;\n setter: SetterT<unknown>;\n subscribe: (listener: ListenerT) => () => void;\n};\n\nexport type UseGlobalStateResT<T> = [T, SetterT<T>];\n\n/**\n * The primary hook for interacting with the global state, modeled after\n * the standard React's\n * [useState](https://reactjs.org/docs/hooks-reference.html#usestate).\n * It subscribes a component to a given `path` of global state, and provides\n * a function to update it. Each time the value at `path` changes, the hook\n * triggers re-render of its host component.\n *\n * **Note:**\n * - For performance, the library does not copy objects written to / read from\n * global state paths. You MUST NOT manually mutate returned state values,\n * or change objects already written into the global state, without explicitly\n * clonning them first yourself.\n * - State update notifications are asynchronous. When your code does multiple\n * global state updates in the same React rendering cycle, all state update\n * notifications are queued and dispatched together, after the current\n * rendering cycle. In other words, in any given rendering cycle the global\n * state values are \"fixed\", and all changes becomes visible at once in the\n * next triggered rendering pass.\n *\n * @param path Dot-delimitered state path. It can be undefined to\n * subscribe for entire state.\n *\n * Under-the-hood state values are read and written using `lodash`\n * [_.get()](https://lodash.com/docs/4.17.15#get) and\n * [_.set()](https://lodash.com/docs/4.17.15#set) methods, thus it is safe\n * to access state paths which have not been created before.\n * @param initialValue Initial value to set at the `path`, or its\n * factory:\n * - If a function is given, it will act similar to\n * [the lazy initial state of the standard React's useState()](https://reactjs.org/docs/hooks-reference.html#lazy-initial-state):\n * only if the value at `path` is `undefined`, the function will be executed,\n * and the value it returns will be written to the `path`.\n * - Otherwise, the given value itself will be written to the `path`,\n * if the current value at `path` is `undefined`.\n * @return It returs an array with two elements: `[value, setValue]`:\n *\n * - The `value` is the current value at given `path`.\n *\n * - The `setValue()` is setter function to write a new value to the `path`.\n *\n * Similar to the standard React's `useState()`, it supports\n * [functional value updates](https://reactjs.org/docs/hooks-reference.html#functional-updates):\n * if `setValue()` is called with a function as argument, that function will\n * be called and its return value will be written to `path`. Otherwise,\n * the argument of `setValue()` itself is written to `path`.\n *\n * Also, similar to the standard React's state setters, `setValue()` is\n * stable function: it does not change between component re-renders.\n */\n\n// \"Enforced type overload\"\nfunction useGlobalState<\n Forced extends ForceT | LockT = LockT,\n ValueT = void,\n>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n\n// \"Entire state overload\"\nfunction useGlobalState<StateT>(): UseGlobalStateResT<StateT>;\n\n// \"State evaluation overload\"\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\nfunction useGlobalState<\n StateT,\n PathT extends null | string | undefined,\n>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\nfunction useGlobalState(\n path?: null | string,\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initialValue?: ValueOrInitializerT<any>,\n\n // TODO: Revise it later!\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): UseGlobalStateResT<any> {\n const globalState = getGlobalState();\n\n const ref = useRef<CurrentT>(null);\n\n const [stable] = useState<StableT>(() => {\n const emitter = new Emitter();\n const setter = (value: unknown) => {\n const rc = ref.current;\n if (!rc) throw Error('Internal error');\n\n const newState = isFunction(value)\n ? value(rc.globalState.get(rc.path)) as unknown\n : value;\n\n if (process.env.NODE_ENV !== 'production' && isDebugMode()) {\n /* eslint-disable no-console */\n console.groupCollapsed(\n `ReactGlobalState - useGlobalState setter triggered for path ${\n rc.path ?? ''\n }`,\n );\n console.log('New value:', cloneDeepForLog(newState, rc.path ?? ''));\n console.groupEnd();\n /* eslint-enable no-console */\n }\n rc.globalState.set<ForceT, unknown>(rc.path, newState);\n\n // NOTE: The regular global state's update notifications, automatically\n // triggered by the rc.globalState.set() call above, are batched, and\n // scheduled to fire asynchronosuly at a later time, which is problematic\n // for managed text inputs - if they have their value update delayed to\n // future render cycles, it will result in reset of their cursor position\n // to the value end. Calling the rc.emitter.emit() below causes a sooner\n // state update for the current component, thus working around the issue.\n // For additional details see the original issue:\n // https://github.com/birdofpreyru/react-global-state/issues/22\n if (newState !== rc.prevValue) emitter.emit();\n };\n const subscribe = emitter.addListener.bind(emitter);\n return { emitter, setter, subscribe };\n });\n\n const value = useSyncExternalStore(\n stable.subscribe,\n () => globalState.get<ForceT, unknown>(path, { initialValue }),\n\n () => globalState.get<ForceT, unknown>(\n path,\n { initialState: true, initialValue },\n ),\n );\n\n ref.current ??= {\n globalState,\n path,\n prevValue: value,\n };\n\n useEffect(() => {\n ref.current = {\n globalState,\n path,\n prevValue: ref.current!.prevValue,\n };\n\n const watcher = () => {\n const nextValue = globalState.get<ForceT, unknown>(path);\n if (ref.current!.prevValue !== nextValue) {\n ref.current!.prevValue = nextValue;\n stable.emitter.emit();\n }\n };\n\n globalState.watch(watcher);\n watcher();\n\n return () => {\n globalState.unWatch(watcher);\n };\n }, [globalState, stable.emitter, path]);\n\n return [value, stable.setter];\n}\n\nexport default useGlobalState;\n\n// TODO: Revise.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface UseGlobalStateI<StateT> {\n (): UseGlobalStateResT<StateT>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue: ValueOrInitializerT<\n Exclude<ValueAtPathT<StateT, PathT, never>, undefined>>\n ): UseGlobalStateResT<Exclude<ValueAtPathT<StateT, PathT, void>, undefined>>;\n\n <PathT extends null | string | undefined>(\n path: PathT,\n initialValue?: ValueOrInitializerT<ValueAtPathT<StateT, PathT, never>>\n ): UseGlobalStateResT<ValueAtPathT<StateT, PathT, void>>;\n\n <Forced extends ForceT | LockT = LockT, ValueT = unknown>(\n path: null | string | undefined,\n initialValue?: ValueOrInitializerT<TypeLock<Forced, never, ValueT>>,\n ): UseGlobalStateResT<TypeLock<Forced, void, ValueT>>;\n}\n"],"mappings":";;;;;;AAEA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,MAAA,GAAAD,OAAA;AASA,IAAAE,QAAA,GAAAF,OAAA;AAGA,IAAAG,oBAAA,GAAAH,OAAA;AAEA,IAAAI,MAAA,GAAAJ,OAAA;AAlBA;;AA8CA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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AC;AAC/B;AAAC,IAAA8B,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEc3C,cAAc,EAE7B;AACA","ignoreList":[]}
@@ -1,91 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.cloneDeepForLog = cloneDeepForLog;
7
- exports.escape = escape;
8
- exports.hash = hash;
9
- exports.isDebugMode = isDebugMode;
10
- var _lodash = require("lodash");
11
- // TODO: This (ForceT, LockT, and TypeLock) probably should be moved to JS Utils
12
- // lib.
13
-
14
- /**
15
- * Given the type of state, `StateT`, and the type of state path, `PathT`,
16
- * it evaluates the type of value at that path of the state, if it can be
17
- * evaluated from the path type (it is possible when `PathT` is a string
18
- * literal type, and `StateT` elements along this path have appropriate
19
- * types); otherwise it falls back to the specified `UnknownT` type,
20
- * which should be set either `never` (for input arguments), or `void`
21
- * (for return types) - `never` and `void` in those places forbid assignments,
22
- * and are not auto-inferred to more permissible types.
23
- *
24
- * BEWARE: When StateT is any the construct resolves to any for any string
25
- * paths.
26
- */
27
-
28
- /**
29
- * Returns 'true' if debug logging should be performed; 'false' otherwise.
30
- *
31
- * BEWARE: The actual safeguards for the debug logging still should read
32
- * if (process.env.NODE_ENV !== 'production' && isDebugMode()) {
33
- * // Some debug logging
34
- * }
35
- * to ensure that debug code is stripped out by Webpack in production mode.
36
- *
37
- * @returns
38
- * @ignore
39
- */
40
- function isDebugMode() {
41
- try {
42
- return process.env.NODE_ENV !== 'production' && !!process.env.REACT_GLOBAL_STATE_DEBUG;
43
- } catch {
44
- return false;
45
- }
46
- }
47
- const cloneDeepBailKeys = new Set();
48
-
49
- /**
50
- * Deep-clones given value for logging purposes, or returns the value itself
51
- * if the previous clone attempt, with the same key, took more than 300ms
52
- * (to avoid situations when large payload in the global state slows down
53
- * development versions of the app due to the logging overhead).
54
- */
55
- function cloneDeepForLog(value, key = '') {
56
- if (cloneDeepBailKeys.has(key)) {
57
- // eslint-disable-next-line no-console
58
- console.warn(`The logged value won't be clonned (key "${key}").`);
59
- return value;
60
- }
61
- const start = Date.now();
62
- const res = (0, _lodash.cloneDeep)(value);
63
- const time = Date.now() - start;
64
- if (time > 300) {
65
- // eslint-disable-next-line no-console
66
- console.warn(`${time}ms spent to clone the logged value (key "${key}").`);
67
- cloneDeepBailKeys.add(key);
68
- }
69
- return res;
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
- }
91
- //# sourceMappingURL=utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","names":["_lodash","require","isDebugMode","process","env","NODE_ENV","REACT_GLOBAL_STATE_DEBUG","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\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,IAAAA,OAAA,GAAAC,OAAA;AAIA;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;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,MAAM;IACN,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;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,GAAG,IAAAC,iBAAS,EAACT,KAAK,CAAC;EAC5B,MAAMU,IAAI,GAAGJ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