@zajno/common 2.8.7 → 2.8.8

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.
@@ -0,0 +1,282 @@
1
+ import { DebounceProcessor } from '../../functions/debounce.js';
2
+ import { PromiseCacheCore } from './core.js';
3
+ const BATCHING_DELAY = 200;
4
+ /**
5
+ * Caches items by a key (string or another type) which are resolved by an async fetcher (`Promise`).
6
+ *
7
+ * Supports:
8
+ * - custom key adapter and parser for non-string keys.
9
+ * - direct manual cache manipulation.
10
+ * - batching of fetches.
11
+ * - auto-invalidation of cached items (time-based, callback-based, max items).
12
+ * - error tracking per key.
13
+ */
14
+ export class PromiseCache extends PromiseCacheCore {
15
+ fetcher;
16
+ _batch = null;
17
+ _invalidationConfig = null;
18
+ _onError = null;
19
+ /**
20
+ * Creates an instance of PromiseCache.
21
+ * @param fetcher Function to fetch data by key.
22
+ * @param keyAdapter Optional function to adapt non-string keys to strings.
23
+ * @param keyParser Optional function to parse string keys back to their original type.
24
+ */
25
+ constructor(fetcher, keyAdapter, keyParser) {
26
+ super(keyAdapter, keyParser);
27
+ this.fetcher = fetcher;
28
+ }
29
+ // ─── Configuration ───────────────────────────────────────────────────
30
+ /**
31
+ * Provide a fetcher function that takes multiple ids and returns multiple results at once. Will be called with a slight delay to allow multiple ids to be collected.
32
+ *
33
+ * Warning: resolved array should have the same order as the input array.
34
+ *
35
+ * When provided, effectively replaces the main fetcher; but in case of fail, fallbacks to the main fetcher.
36
+ */
37
+ useBatching(fetcher, delay = BATCHING_DELAY) {
38
+ this._batch = fetcher ? new DebounceProcessor(fetcher, delay) : null;
39
+ return this;
40
+ }
41
+ /**
42
+ * Enables auto-invalidation of cached items by time.
43
+ *
44
+ * This is a convenience wrapper around {@link useInvalidation}.
45
+ *
46
+ * @param ms Time in milliseconds after which the item will be considered invalid. If null, auto-invalidation is disabled.
47
+ * @param keepInstance If true, the cached item will not be removed during invalidation, but the old instance is kept. Defaults to false.
48
+ */
49
+ useInvalidationTime(ms, keepInstance = false) {
50
+ return this.useInvalidation(ms != null ? { expirationMs: ms, keepInstance } : null);
51
+ }
52
+ /**
53
+ * Configures advanced invalidation policy.
54
+ *
55
+ * The config object is stored as-is (not destructured), so getter-based fields will be re-evaluated on each access.
56
+ * This allows consumers to provide dynamic invalidation policies.
57
+ *
58
+ * @param config The invalidation configuration. See {@link InvalidationConfig} for details.
59
+ */
60
+ useInvalidation(config) {
61
+ this._invalidationConfig = config;
62
+ return this;
63
+ }
64
+ /**
65
+ * Sets an error callback that is called when a fetcher fails.
66
+ *
67
+ * @param callback The callback to call on error. Receives the original key and the raw error.
68
+ */
69
+ useOnError(callback) {
70
+ this._onError = callback;
71
+ return this;
72
+ }
73
+ // ─── Core implementation ─────────────────────────────────────────────
74
+ /**
75
+ * Returns a promise that resolves to the cached value of the item if loaded already, otherwise starts fetching and the promise will be resolved to the final value.
76
+ *
77
+ * Consequent calls will return the same promise until it resolves.
78
+ *
79
+ * @param id The id of the item.
80
+ * @returns A promise that resolves to the result, whether it's cached or freshly fetched.
81
+ */
82
+ get(id) {
83
+ const { item, key, isInvalid } = this._getCurrent(id);
84
+ // return cached item if it's not invalidated
85
+ if (item !== undefined && !isInvalid) {
86
+ this.logger.log(key, 'get: item resolved to', item, isInvalid ? '(invalidated)' : '');
87
+ return Promise.resolve(item);
88
+ }
89
+ let promise = this._fetchCache.get(key);
90
+ if (promise != null) {
91
+ this.logger.log(key, 'get: item resolved to <promise>');
92
+ return promise;
93
+ }
94
+ this.setStatus(key, true);
95
+ promise = this._doFetchAsync(id, key);
96
+ this.setPromise(key, promise);
97
+ return promise;
98
+ }
99
+ /** Clears the cache and resets the loading state. */
100
+ clear() {
101
+ this._batch?.clear();
102
+ super.clear();
103
+ }
104
+ // ─── Protected overrides ─────────────────────────────────────────────
105
+ _getCurrent(id) {
106
+ const key = this._pk(id);
107
+ const isInvalid = this.getIsInvalidated(key);
108
+ // make sure current item is hooked here from the cache (required by observers)
109
+ const item = this._itemsCache.get(key);
110
+ const keepInstance = !!this._invalidationConfig?.keepInstance;
111
+ if (isInvalid) {
112
+ this.logger.log(key, 'item is invalidated');
113
+ }
114
+ return {
115
+ item: (isInvalid && !keepInstance) ? undefined : item,
116
+ key,
117
+ isInvalid,
118
+ };
119
+ }
120
+ getIsInvalidated(key) {
121
+ const config = this._invalidationConfig;
122
+ if (!config) {
123
+ return false;
124
+ }
125
+ const ts = this._timestamps.get(key);
126
+ // Check time-based expiration
127
+ const expirationMs = config.expirationMs;
128
+ if (expirationMs != null && expirationMs > 0 && ts != null) {
129
+ if (Date.now() - ts > expirationMs) {
130
+ return true;
131
+ }
132
+ }
133
+ // Check callback-based invalidation
134
+ if (config.invalidationCheck) {
135
+ const value = this._itemsCache.get(key);
136
+ if (value !== undefined && config.invalidationCheck(key, value, ts ?? 0)) {
137
+ return true;
138
+ }
139
+ }
140
+ return false;
141
+ }
142
+ /** @override Stores the result for the specified key, enforcing max items. */
143
+ storeResult(key, res) {
144
+ this._enforceMaxItems(key);
145
+ super.storeResult(key, res);
146
+ }
147
+ // ─── Private ─────────────────────────────────────────────────────────
148
+ /**
149
+ * Fetches the item asynchronously.
150
+ * @param id The id of the item.
151
+ * @param key The cache key.
152
+ * @returns A promise that resolves to the fetched item.
153
+ */
154
+ async _doFetchAsync(id, key) {
155
+ let isInSameVersion = true;
156
+ try {
157
+ this.onBeforeFetch(key);
158
+ const v = this._version;
159
+ let res;
160
+ let fetchFailed = false;
161
+ try {
162
+ res = await this.tryFetchInBatch(id);
163
+ }
164
+ catch (err) {
165
+ this._handleError(id, err);
166
+ fetchFailed = true;
167
+ res = null;
168
+ }
169
+ if (v !== this._version) {
170
+ isInSameVersion = false;
171
+ // resolve with actual result but don't store it
172
+ return res;
173
+ }
174
+ if (this._fetchCache.get(key) != null) {
175
+ this.logger.log(key, 'item\'s <promise> resolved to', res);
176
+ res = this.prepareResult(res);
177
+ if (!fetchFailed) {
178
+ this.storeResult(key, res);
179
+ }
180
+ }
181
+ return res;
182
+ }
183
+ finally {
184
+ if (isInSameVersion) {
185
+ this.onFetchComplete(key);
186
+ }
187
+ else {
188
+ this.logger.log(key, 'skipping item\'s resolve due to version change ("clear()" has been called)');
189
+ }
190
+ }
191
+ }
192
+ /** Performs a fetch operation in batch mode if available, otherwise uses the regular fetch. Throws on error. */
193
+ async tryFetchInBatch(id) {
194
+ if (!this._batch) {
195
+ return this.fetcher(id);
196
+ }
197
+ const res = await this._batch.push(id)
198
+ .catch(err => {
199
+ this.logger.warn('batch fetch failed', id, err);
200
+ return null;
201
+ });
202
+ if (!res || !res.result || res.result[res.index] === undefined) {
203
+ // batch call failed or returned no result — fallback to the direct fetcher
204
+ return this.fetcher(id);
205
+ }
206
+ return res.result[res.index];
207
+ }
208
+ /** Handles a fetch error: stores it, logs it, and calls the onError callback. */
209
+ _handleError(id, err) {
210
+ const key = this._pk(id);
211
+ this._errorsMap.set(key, err);
212
+ this.logger.warn('fetcher failed', id, err);
213
+ if (this._onError) {
214
+ try {
215
+ this._onError(id, err);
216
+ }
217
+ catch {
218
+ // ignore errors in the callback
219
+ }
220
+ }
221
+ }
222
+ /**
223
+ * Enforces the max items limit by removing items to make room.
224
+ * Strategy: first removes invalid items, then oldest valid items.
225
+ * Items currently being fetched (in-flight) are not evicted.
226
+ *
227
+ * @param incomingKey The key of the item about to be stored (excluded from eviction).
228
+ */
229
+ _enforceMaxItems(incomingKey) {
230
+ const maxItems = this._invalidationConfig?.maxItems;
231
+ if (maxItems == null || maxItems <= 0) {
232
+ return;
233
+ }
234
+ // If we're under the limit, nothing to do
235
+ if (this._itemsCache.size < maxItems) {
236
+ return;
237
+ }
238
+ // Phase 1: Remove invalid items first (they're garbage anyway)
239
+ const invalidKeys = [];
240
+ for (const key of this._itemsCache.keys()) {
241
+ if (key === incomingKey)
242
+ continue;
243
+ if (this.getIsInvalidated(key)) {
244
+ invalidKeys.push(key);
245
+ }
246
+ }
247
+ for (const key of invalidKeys) {
248
+ this._set(key, undefined, undefined, undefined);
249
+ this._errorsMap.delete(key);
250
+ this._timestamps.delete(key);
251
+ if (this._itemsCache.size < maxItems) {
252
+ return;
253
+ }
254
+ }
255
+ // Phase 2: Remove oldest valid items (skip in-flight items)
256
+ while (this._itemsCache.size >= maxItems) {
257
+ let oldestKey = null;
258
+ let oldestTs = Infinity;
259
+ for (const [key, ts] of this._timestamps.entries()) {
260
+ // Don't evict the incoming key or items currently being fetched
261
+ if (key === incomingKey)
262
+ continue;
263
+ if (this._fetchCache.has(key))
264
+ continue;
265
+ if (ts < oldestTs) {
266
+ oldestTs = ts;
267
+ oldestKey = key;
268
+ }
269
+ }
270
+ if (oldestKey != null) {
271
+ this._set(oldestKey, undefined, undefined, undefined);
272
+ this._timestamps.delete(oldestKey);
273
+ this._errorsMap.delete(oldestKey);
274
+ }
275
+ else {
276
+ // No evictable items found (all are in-flight or incoming)
277
+ break;
278
+ }
279
+ }
280
+ }
281
+ }
282
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","sourceRoot":"","sources":["../../../../src/structures/promiseCache/cache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAG7C,MAAM,cAAc,GAAG,GAAG,CAAC;AAE3B;;;;;;;;;EASE;AACF,MAAM,OAAO,YAA4B,SAAQ,gBAAsB;IAa9C;IAXb,MAAM,GAAqC,IAAI,CAAC;IAChD,mBAAmB,GAAiC,IAAI,CAAC;IACzD,QAAQ,GAA4B,IAAI,CAAC;IAEjD;;;;;OAKG;IACH,YACqB,OAA8B,EAC/C,UAAuD,EACvD,SAAuD;QAEvD,KAAK,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;QAJZ,YAAO,GAAP,OAAO,CAAuB;IAKnD,CAAC;IAED,wEAAwE;IAExE;;;;;;MAME;IACF,WAAW,CAAC,OAAmC,EAAE,KAAK,GAA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AS,EAAE,SAAS,CAAC,CAAC;gBACtD,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;gBACnC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;YACtC,CAAC;iBAAM,CAAC;gBACJ,2DAA2D;gBAC3D,MAAM;YACV,CAAC;QACL,CAAC;IACL,CAAC;CACJ"}
@@ -0,0 +1,297 @@
1
+ import { Loggable } from '../../logger/loggable.js';
2
+ import { Model } from '../../models/Model.js';
3
+ /**
4
+ * Core base class for PromiseCache. Provides basic cache operations, hooks, and `pure_create*` methods.
5
+ *
6
+ * This class handles:
7
+ * - item storage and retrieval
8
+ * - loading state tracking
9
+ * - promise caching
10
+ * - error storage
11
+ * - timestamps for cached items
12
+ * - direct cache manipulation (invalidate, updateValueDirectly, clear)
13
+ * - keys iteration
14
+ *
15
+ * Subclasses are expected to implement fetching logic, invalidation policies, etc.
16
+ */
17
+ export class PromiseCacheCore extends Loggable {
18
+ keyAdapter;
19
+ keyParser;
20
+ /** Stores resolved items in map by id. */
21
+ _itemsCache;
22
+ /** Stores items loading state (loading or not) in map by id. */
23
+ _itemsStatus;
24
+ /** Stores items loading count. */
25
+ _loadingCount;
26
+ /** Stores items Promises state (if still loading) in map by id. */
27
+ _fetchCache;
28
+ /** Stores last errors by key. Observable-friendly via IMapModel. */
29
+ _errorsMap;
30
+ /** Stores items resolve timestamps (for expiration) in map by id. */
31
+ _timestamps = new Map();
32
+ _version = 0;
33
+ constructor(keyAdapter, keyParser) {
34
+ super();
35
+ this.keyAdapter = keyAdapter;
36
+ this.keyParser = keyParser;
37
+ this._loadingCount = this.pure_createLoadingCount();
38
+ this._itemsCache = this.pure_createItemsCache();
39
+ this._itemsStatus = this.pure_createItemsStatus();
40
+ this._fetchCache = this.pure_createFetchCache();
41
+ this._errorsMap = this.pure_createErrorsMap();
42
+ }
43
+ // ─── Counts ──────────────────────────────────────────────────────────
44
+ /** Returns the number of items currently being fetched. */
45
+ get loadingCount() { return this._loadingCount.value; }
46
+ /** Returns the number of cached items (resolved values). */
47
+ get cachedCount() { return this._itemsCache.size; }
48
+ /** Returns the number of in-flight promises (items currently being fetched). */
49
+ get promisesCount() { return this._fetchCache.size; }
50
+ /** Returns the number of cached items that are currently invalid (expired). */
51
+ get invalidCount() {
52
+ let count = 0;
53
+ for (const key of this._itemsCache.keys()) {
54
+ if (this.getIsInvalidated(key)) {
55
+ count++;
56
+ }
57
+ }
58
+ return count;
59
+ }
60
+ // ─── Pure factory methods (override for observability) ───────────────
61
+ /**
62
+ * @pure @const
63
+ * Creates a model for tracking the loading state. Override to inject own instance, e.g. for observability.
64
+ *
65
+ * Warning: as name indicates, this should be "pure"/"const" function, i.e. should not reference `this`/`super`.
66
+ */
67
+ pure_createLoadingCount() {
68
+ return new Model(0);
69
+ }
70
+ /**
71
+ * @pure @const
72
+ * Creates a map for caching resolved items by id. Override to inject own instance, e.g. for observability.
73
+ *
74
+ * Warning: as name indicates, this should be "pure"/"const" function, i.e. should not reference `this`/`super`.
75
+ */
76
+ pure_createItemsCache() {
77
+ return new Map();
78
+ }
79
+ /**
80
+ * @pure @const
81
+ * Creates a map for tracking the loading state of items by id. Override to inject own instance, e.g. for observability.
82
+ *
83
+ * Warning: as name indicates, this should be "pure"/"const" function, i.e. should not reference `this`/`super`.
84
+ */
85
+ pure_createItemsStatus() {
86
+ return new Map();
87
+ }
88
+ /**
89
+ * @pure @const
90
+ * Creates a map for caching promises of items by id. Override to inject own instance, e.g. for observability.
91
+ *
92
+ * Warning: as name indicates, this should be "pure"/"const" function, i.e. should not reference `this`/`super`.
93
+ */
94
+ pure_createFetchCache() {
95
+ return new Map();
96
+ }
97
+ /**
98
+ * @pure @const
99
+ * Creates a map for storing last errors by key. Override to inject own instance, e.g. for observability.
100
+ *
101
+ * Warning: as name indicates, this should be "pure"/"const" function, i.e. should not reference `this`/`super`.
102
+ */
103
+ pure_createErrorsMap() {
104
+ return new Map();
105
+ }
106
+ // ─── Key handling ────────────────────────────────────────────────────
107
+ _pk(k) {
108
+ if (k == null) {
109
+ throw new Error('PromiseCache: null keys are not supported');
110
+ }
111
+ if (typeof k === 'string') {
112
+ return k;
113
+ }
114
+ if (!this.keyAdapter) {
115
+ throw new Error('Provide key adapter for non-string keys');
116
+ }
117
+ return this.keyAdapter(k);
118
+ }
119
+ getLoggerName(name) {
120
+ return `[PromiseCache:${name || '?'}]`;
121
+ }
122
+ // ─── Public API: reading ─────────────────────────────────────────────
123
+ /**
124
+ * Returns a {@link DeferredGetter} object for a specified key.
125
+ *
126
+ * This can be used to access the current value, promise, loading state, and last error of the item.
127
+ */
128
+ getDeferred(key) {
129
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
130
+ const self = this;
131
+ return {
132
+ get current() { return self.getCurrent(key); },
133
+ get promise() { return self.get(key); },
134
+ get isLoading() { return self.getIsLoading(key); },
135
+ get error() { return self.getLastError(key); },
136
+ };
137
+ }
138
+ /**
139
+ * Returns the loading state of an item.
140
+ *
141
+ * @returns true if loading, false if loading completed, undefined if loading was not started yet.
142
+ */
143
+ getIsLoading(id) {
144
+ const key = this._pk(id);
145
+ const res = this._itemsStatus.get(key);
146
+ if (res) {
147
+ return res;
148
+ }
149
+ const isInvalid = this.getIsInvalidated(key);
150
+ return isInvalid ? undefined : res;
151
+ }
152
+ /**
153
+ * Returns whether the cached item for the specified key is valid (not expired and not invalidated by callback).
154
+ *
155
+ * @returns `true` if the item is cached and valid, `false` if the item is invalidated or not cached.
156
+ */
157
+ getIsValid(id) {
158
+ const key = this._pk(id);
159
+ if (!this._itemsCache.has(key)) {
160
+ return false;
161
+ }
162
+ return !this.getIsInvalidated(key);
163
+ }
164
+ /**
165
+ * Returns the last error that occurred during fetching for the specified key.
166
+ *
167
+ * @returns The raw error, or null if no error.
168
+ */
169
+ getLastError(id) {
170
+ const key = this._pk(id);
171
+ return this._errorsMap.get(key) ?? null;
172
+ }
173
+ /** Returns the current cached value, optionally triggering a fetch. */
174
+ getCurrent(id, initiateFetch = true) {
175
+ const { item, key } = this._getCurrent(id);
176
+ if (initiateFetch) {
177
+ this.get(id);
178
+ }
179
+ this.logger.log(key, 'getCurrent: returns', item);
180
+ return item;
181
+ }
182
+ /** Returns true if the item is cached or fetching was initiated. Does not initiate fetching. */
183
+ hasKey(id) {
184
+ const key = this._pk(id);
185
+ return this._itemsCache.get(key) !== undefined || this._itemsStatus.get(key) !== undefined;
186
+ }
187
+ keys(iterate = false) {
188
+ const iterator = this._itemsCache.keys();
189
+ return iterate
190
+ ? iterator
191
+ : Array.from(iterator);
192
+ }
193
+ keysParsed(iterate = false) {
194
+ const kp = this.keyParser;
195
+ if (!kp) {
196
+ return null;
197
+ }
198
+ const keysIterator = this.keys(true);
199
+ if (!iterate) {
200
+ return Array.from(keysIterator, key => kp(key));
201
+ }
202
+ return (function* () {
203
+ for (const key of keysIterator) {
204
+ yield kp(key);
205
+ }
206
+ })();
207
+ }
208
+ // ─── Public API: mutation ────────────────────────────────────────────
209
+ /** Instantly invalidates the cached item for the specified id, like it was never fetched/accessed. */
210
+ invalidate(id) {
211
+ const key = this._pk(id);
212
+ this._set(key, undefined, undefined, undefined);
213
+ this._errorsMap.delete(key);
214
+ this._timestamps.delete(key);
215
+ }
216
+ /** Updates the cached value for the specified id directly, like it was fetched already. */
217
+ updateValueDirectly(id, value) {
218
+ const key = this._pk(id);
219
+ this._set(key, value, undefined, undefined);
220
+ }
221
+ /**
222
+ * Iterates over all cached items and removes those that are invalid (expired).
223
+ *
224
+ * @returns The number of items that were removed.
225
+ */
226
+ sanitize() {
227
+ let removed = 0;
228
+ const keysToRemove = [];
229
+ for (const key of this._itemsCache.keys()) {
230
+ if (this.getIsInvalidated(key)) {
231
+ keysToRemove.push(key);
232
+ }
233
+ }
234
+ for (const key of keysToRemove) {
235
+ this._set(key, undefined, undefined, undefined);
236
+ this._errorsMap.delete(key);
237
+ this._timestamps.delete(key);
238
+ removed++;
239
+ }
240
+ return removed;
241
+ }
242
+ /** Clears the cache and resets the loading state. */
243
+ clear() {
244
+ ++this._version;
245
+ this._loadingCount.value = 0;
246
+ this._itemsCache.clear();
247
+ this._itemsStatus.clear();
248
+ this._fetchCache.clear();
249
+ this._errorsMap.clear();
250
+ this._timestamps.clear();
251
+ }
252
+ /** @internal updates all caches states at once. */
253
+ _set(key, item, promise, isLoading) {
254
+ PromiseCacheCore._setMapX(key, this._fetchCache, promise);
255
+ PromiseCacheCore._setMapX(key, this._itemsStatus, isLoading);
256
+ PromiseCacheCore._setMapX(key, this._itemsCache, item);
257
+ }
258
+ /** Updates the loading status for the specified key. Override to add a hook. */
259
+ setStatus(key, status) {
260
+ this.logger.log(key, 'status update:', status);
261
+ this._itemsStatus.set(key, status);
262
+ }
263
+ /** Updates the promise for the specified key. Override to add a hook. */
264
+ setPromise(key, promise) {
265
+ this._fetchCache.set(key, promise);
266
+ }
267
+ /** Stores the result for the specified key. Override to add a hook. */
268
+ storeResult(key, res) {
269
+ this._itemsCache.set(key, res);
270
+ this._timestamps.set(key, Date.now());
271
+ this._errorsMap.delete(key);
272
+ }
273
+ /** Hooks into the fetch process before it starts. */
274
+ onBeforeFetch(_key) {
275
+ this._loadingCount.value = this._loadingCount.value + 1;
276
+ }
277
+ /** Hooks into the fetch process after it completes. */
278
+ onFetchComplete(key) {
279
+ this._loadingCount.value = this._loadingCount.value - 1;
280
+ this._fetchCache.delete(key);
281
+ this._itemsStatus.set(key, false);
282
+ }
283
+ /** Hooks into the result preparation process, before it's stored into the cache. */
284
+ prepareResult(res) {
285
+ return res;
286
+ }
287
+ /** @internal Helper to set or delete a value in a map. */
288
+ static _setMapX(key, map, val) {
289
+ if (val === undefined) {
290
+ map.delete(key);
291
+ }
292
+ else {
293
+ map.set(key, val);
294
+ }
295
+ }
296
+ }
297
+ //# sourceMappingURL=core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.js","sourceRoot":"","sources":["../../../../src/structures/promiseCache/core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ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AAC;IAED,uEAAuE;IAC7D,WAAW,CAAC,GAAW,EAAE,GAAa;QAC5C,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QAC/B,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;QACtC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAChC,CAAC;IAED,qDAAqD;IAC3C,aAAa,CAAC,IAAY;QAChC,IAAI,CAAC,aAAa,CAAC,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,GAAG,CAAC,CAAC;IAC5D,CAAC;IAED,uDAAuD;IAC7C,eAAe,CAAC,GAAW;QACjC,IAAI,CAAC,aAAa,CAAC,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,GAAG,CAAC,CAAC;QACxD,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC7B,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC;IAED,oFAAoF;IAC1E,aAAa,CAAC,GAAa;QACjC,OAAO,GAAG,CAAC;IACf,CAAC;IAED,0DAA0D;IAChD,MAAM,CAAC,QAAQ,CAAI,GAAW,EAAE,GAAyB,EAAE,GAAM;QACvE,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;YACpB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACpB,CAAC;aAAM,CAAC;YACJ,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;QACtB,CAAC;IACL,CAAC;CACJ"}
@@ -0,0 +1,4 @@
1
+ export * from './core.js';
2
+ export * from './types.js';
3
+ export * from './cache.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/structures/promiseCache/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC"}
@@ -0,0 +1,12 @@
1
+ export var DeferredGetter;
2
+ (function (DeferredGetter) {
3
+ const _resolvedPromise = Promise.resolve(null);
4
+ /** Empty resolved value. */
5
+ DeferredGetter.Empty = {
6
+ get current() { return null; },
7
+ get promise() { return _resolvedPromise; },
8
+ get isLoading() { return false; },
9
+ get error() { return null; },
10
+ };
11
+ })(DeferredGetter || (DeferredGetter = {}));
12
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/structures/promiseCache/types.ts"],"names":[],"mappings":"AAgBA,MAAM,KAAW,cAAc,CAU9B;AAVD,WAAiB,cAAc;IAC3B,MAAM,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAO,IAAI,CAAC,CAAC;IAErD,4BAA4B;IACf,oBAAK,GAAG;QACjB,IAAI,OAAO,KAAW,OAAO,IAAI,CAAC,CAAC,CAAC;QACpC,IAAI,OAAO,KAAoB,OAAO,gBAAgB,CAAC,CAAC,CAAC;QACzD,IAAI,SAAS,KAAK,OAAO,KAAK,CAAC,CAAC,CAAC;QACjC,IAAI,KAAK,KAAK,OAAO,IAAI,CAAC,CAAC,CAAC;KACA,CAAC;AACrC,CAAC,EAVgB,cAAc,KAAd,cAAc,QAU9B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zajno/common",
3
- "version": "2.8.7",
3
+ "version": "2.8.8",
4
4
  "description": "Zajno's re-usable utilities for JS/TS projects",
5
5
  "private": false,
6
6
  "type": "module",
@@ -151,6 +151,12 @@
151
151
  "require": "./cjs/structures/path/utils/index.js",
152
152
  "default": "./cjs/structures/path/utils/index.js"
153
153
  },
154
+ "./structures/promiseCache": {
155
+ "types": "./types/structures/promiseCache/index.d.ts",
156
+ "import": "./esm/structures/promiseCache/index.js",
157
+ "require": "./cjs/structures/promiseCache/index.js",
158
+ "default": "./cjs/structures/promiseCache/index.js"
159
+ },
154
160
  "./types": {
155
161
  "types": "./types/types/index.d.ts",
156
162
  "import": "./esm/types/index.js",