@neezco/cache 0.2.0 → 0.3.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.
- package/CHANGELOG.md +14 -0
- package/dist/browser/index.d.ts +47 -10
- package/dist/browser/index.js +70 -37
- package/dist/browser/index.js.map +1 -1
- package/dist/node/index.cjs +70 -37
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.d.cts +47 -10
- package/dist/node/index.d.mts +47 -10
- package/dist/node/index.mjs +70 -37
- package/dist/node/index.mjs.map +1 -1
- package/docs/api-reference.md +33 -3
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
# [0.3.0](https://github.com/neezco/cache/compare/v0.2.1...v0.3.0) (2026-02-11)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
### Features
|
|
9
|
+
|
|
10
|
+
* enhance cache retrieval with metadata support in `get()` method ([eb198d6](https://github.com/neezco/cache/commit/eb198d66c9e1abda86c448fb81a35f14e376a79c)), closes [#17](https://github.com/neezco/cache/issues/17)
|
|
11
|
+
|
|
12
|
+
## [0.2.1](https://github.com/neezco/cache/compare/v0.2.0...v0.2.1) (2026-02-11)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
### Performance Improvements
|
|
16
|
+
|
|
17
|
+
* optimize cache entry validation by introducing pre-computed status handling ([bafb6a0](https://github.com/neezco/cache/commit/bafb6a024b0082a1b81f2d0e959c883df4136976))
|
|
18
|
+
|
|
5
19
|
# [0.2.0](https://github.com/neezco/cache/compare/v0.1.1...v0.2.0) (2026-02-09)
|
|
6
20
|
|
|
7
21
|
|
package/dist/browser/index.d.ts
CHANGED
|
@@ -100,6 +100,34 @@ interface InvalidateTagOptions {
|
|
|
100
100
|
asStale?: boolean;
|
|
101
101
|
[key: string]: unknown;
|
|
102
102
|
}
|
|
103
|
+
/**
|
|
104
|
+
* Status of a cache entry.
|
|
105
|
+
*/
|
|
106
|
+
declare enum ENTRY_STATUS {
|
|
107
|
+
/** The entry is fresh and valid. */
|
|
108
|
+
FRESH = "fresh",
|
|
109
|
+
/** The entry is stale but can still be served. */
|
|
110
|
+
STALE = "stale",
|
|
111
|
+
/** The entry has expired and is no longer valid. */
|
|
112
|
+
EXPIRED = "expired",
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Metadata returned when includeMetadata is enabled in get().
|
|
116
|
+
* Contains complete information about a cache entry including
|
|
117
|
+
* timing, status, and associated tags.
|
|
118
|
+
*/
|
|
119
|
+
interface EntryMetadata<T = unknown> {
|
|
120
|
+
/** The cached value. */
|
|
121
|
+
data: T;
|
|
122
|
+
/** Absolute timestamp when this entry becomes fully expired (in milliseconds). */
|
|
123
|
+
expirationTime: number;
|
|
124
|
+
/** Absolute timestamp when the stale window expires (in milliseconds). */
|
|
125
|
+
staleWindowExpiration: number;
|
|
126
|
+
/** Current status of the entry (fresh, stale, or expired). */
|
|
127
|
+
status: ENTRY_STATUS;
|
|
128
|
+
/** Tags associated with this entry, or null if no tags are set. */
|
|
129
|
+
tags: string[] | null;
|
|
130
|
+
}
|
|
103
131
|
//#endregion
|
|
104
132
|
//#region src/index.d.ts
|
|
105
133
|
/**
|
|
@@ -156,22 +184,31 @@ declare class LocalTtlCache {
|
|
|
156
184
|
* Returns the value if it exists and is not fully expired. If an entry is in the
|
|
157
185
|
* stale window (expired but still within staleWindow), the stale value is returned.
|
|
158
186
|
*
|
|
159
|
-
|
|
160
187
|
* @param key - The key to retrieve
|
|
161
|
-
* @
|
|
188
|
+
* @param options - Optional configuration object
|
|
189
|
+
* @param options.includeMetadata - If true, returns entry metadata (data, status, expirationTime, staleWindowExpiration, tags). Defaults to false
|
|
190
|
+
* @returns The cached value, or entry metadata if includeMetadata is true. Returns undefined if not found or expired
|
|
162
191
|
*
|
|
163
192
|
* @example
|
|
164
193
|
* ```typescript
|
|
165
|
-
*
|
|
194
|
+
* // Get value
|
|
195
|
+
* const user = cache.get("user:123");
|
|
196
|
+
*
|
|
197
|
+
* // Get with metadata
|
|
198
|
+
* const entry = cache.get("user:123", { includeMetadata: true });
|
|
199
|
+
* if (entry) {
|
|
200
|
+
* console.log(entry.data);
|
|
201
|
+
* console.log(entry.status);
|
|
202
|
+
* }
|
|
166
203
|
* ```
|
|
167
|
-
*
|
|
168
|
-
* @edge-cases
|
|
169
|
-
* - Returns `undefined` if the key doesn't exist
|
|
170
|
-
* - Returns `undefined` if the key has expired beyond the stale window
|
|
171
|
-
* - Returns the stale value if within the stale window
|
|
172
|
-
* - If `purgeStaleOnGet` is enabled, stale entries are deleted after being returned
|
|
173
204
|
*/
|
|
174
205
|
get<T = unknown>(key: string): T | undefined;
|
|
206
|
+
get<T = unknown>(key: string, options: {
|
|
207
|
+
includeMetadata: true;
|
|
208
|
+
}): EntryMetadata<T> | undefined;
|
|
209
|
+
get<T = unknown>(key: string, options: {
|
|
210
|
+
includeMetadata: false;
|
|
211
|
+
}): T | undefined;
|
|
175
212
|
/**
|
|
176
213
|
* Sets or updates a value in the cache.
|
|
177
214
|
*
|
|
@@ -296,5 +333,5 @@ declare class LocalTtlCache {
|
|
|
296
333
|
invalidateTag(tags: string | string[], options?: InvalidateTagOptions): void;
|
|
297
334
|
}
|
|
298
335
|
//#endregion
|
|
299
|
-
export { type CacheOptions, type InvalidateTagOptions, LocalTtlCache };
|
|
336
|
+
export { type CacheOptions, type EntryMetadata, type InvalidateTagOptions, LocalTtlCache };
|
|
300
337
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/browser/index.js
CHANGED
|
@@ -258,11 +258,18 @@ function computeEntryStatus(state, entry, now) {
|
|
|
258
258
|
* - It has not expired according to its own timestamps, and
|
|
259
259
|
* - No associated tag imposes a stricter stale or expired rule.
|
|
260
260
|
*
|
|
261
|
+
* `entry` can be either a {@link CacheEntry} or a pre-computed {@link ENTRY_STATUS}.
|
|
262
|
+
* Passing a pre-computed status avoids recalculating the entry status.
|
|
263
|
+
*
|
|
261
264
|
* @param state - The cache state containing tag metadata.
|
|
262
|
-
* @param entry - The cache entry being evaluated.
|
|
265
|
+
* @param entry - The cache entry or pre-computed status being evaluated.
|
|
266
|
+
* @param now - The current timestamp.
|
|
263
267
|
* @returns True if the entry is fresh.
|
|
264
268
|
*/
|
|
265
|
-
const isFresh = (state, entry, now) =>
|
|
269
|
+
const isFresh = (state, entry, now) => {
|
|
270
|
+
if (typeof entry === "string") return entry === ENTRY_STATUS.FRESH;
|
|
271
|
+
return computeEntryStatus(state, entry, now) === ENTRY_STATUS.FRESH;
|
|
272
|
+
};
|
|
266
273
|
/**
|
|
267
274
|
* Determines whether a cache entry is stale.
|
|
268
275
|
*
|
|
@@ -270,11 +277,18 @@ const isFresh = (state, entry, now) => computeEntryStatus(state, entry, now) ===
|
|
|
270
277
|
* - It has passed its TTL but is still within its stale window, or
|
|
271
278
|
* - A tag imposes a stale rule that applies to this entry.
|
|
272
279
|
*
|
|
280
|
+
* `entry` can be either a {@link CacheEntry} or a pre-computed {@link ENTRY_STATUS}.
|
|
281
|
+
* Passing a pre-computed status avoids recalculating the entry status.
|
|
282
|
+
*
|
|
273
283
|
* @param state - The cache state containing tag metadata.
|
|
274
|
-
* @param entry - The cache entry being evaluated.
|
|
284
|
+
* @param entry - The cache entry or pre-computed status being evaluated.
|
|
285
|
+
* @param now - The current timestamp.
|
|
275
286
|
* @returns True if the entry is stale.
|
|
276
287
|
*/
|
|
277
|
-
const isStale = (state, entry, now) =>
|
|
288
|
+
const isStale = (state, entry, now) => {
|
|
289
|
+
if (typeof entry === "string") return entry === ENTRY_STATUS.STALE;
|
|
290
|
+
return computeEntryStatus(state, entry, now) === ENTRY_STATUS.STALE;
|
|
291
|
+
};
|
|
278
292
|
/**
|
|
279
293
|
* Determines whether a cache entry is expired.
|
|
280
294
|
*
|
|
@@ -282,11 +296,18 @@ const isStale = (state, entry, now) => computeEntryStatus(state, entry, now) ===
|
|
|
282
296
|
* - It has exceeded both its TTL and stale TTL, or
|
|
283
297
|
* - A tag imposes an expiration rule that applies to this entry.
|
|
284
298
|
*
|
|
299
|
+
* `entry` can be either a {@link CacheEntry} or a pre-computed {@link ENTRY_STATUS}.
|
|
300
|
+
* Passing a pre-computed status avoids recalculating the entry status.
|
|
301
|
+
*
|
|
285
302
|
* @param state - The cache state containing tag metadata.
|
|
286
|
-
* @param entry - The cache entry being evaluated.
|
|
303
|
+
* @param entry - The cache entry or pre-computed status being evaluated.
|
|
304
|
+
* @param now - The current timestamp.
|
|
287
305
|
* @returns True if the entry is expired.
|
|
288
306
|
*/
|
|
289
|
-
const isExpired = (state, entry, now) =>
|
|
307
|
+
const isExpired = (state, entry, now) => {
|
|
308
|
+
if (typeof entry === "string") return entry === ENTRY_STATUS.EXPIRED;
|
|
309
|
+
return computeEntryStatus(state, entry, now) === ENTRY_STATUS.EXPIRED;
|
|
310
|
+
};
|
|
290
311
|
|
|
291
312
|
//#endregion
|
|
292
313
|
//#region src/sweep/sweep-once.ts
|
|
@@ -311,10 +332,11 @@ function _sweepOnce(state, _maxKeysPerBatch = MAX_KEYS_PER_BATCH) {
|
|
|
311
332
|
processed += 1;
|
|
312
333
|
const [key, entry] = next.value;
|
|
313
334
|
const now = Date.now();
|
|
314
|
-
|
|
335
|
+
const status = computeEntryStatus(state, entry, now);
|
|
336
|
+
if (isExpired(state, status, now)) {
|
|
315
337
|
deleteKey(state, key, DELETE_REASON.EXPIRED);
|
|
316
338
|
expiredCount += 1;
|
|
317
|
-
} else if (isStale(state,
|
|
339
|
+
} else if (isStale(state, status, now)) {
|
|
318
340
|
staleCount += 1;
|
|
319
341
|
if (state.purgeStaleOnSweep) deleteKey(state, key, DELETE_REASON.STALE);
|
|
320
342
|
}
|
|
@@ -477,21 +499,40 @@ const createCache = (options = {}) => {
|
|
|
477
499
|
//#endregion
|
|
478
500
|
//#region src/cache/get.ts
|
|
479
501
|
/**
|
|
480
|
-
*
|
|
502
|
+
* Internal function that retrieves a value from the cache with its status information.
|
|
503
|
+
* Returns a tuple containing the entry status and the complete cache entry.
|
|
504
|
+
*
|
|
481
505
|
* @param state - The cache state.
|
|
482
506
|
* @param key - The key to retrieve.
|
|
483
507
|
* @param now - Optional timestamp override (defaults to Date.now()).
|
|
484
|
-
* @returns
|
|
508
|
+
* @returns A tuple of [status, entry] if the entry is valid, or [null, undefined] if not found or expired.
|
|
509
|
+
*
|
|
510
|
+
* @internal
|
|
485
511
|
*/
|
|
486
|
-
const
|
|
512
|
+
const getWithStatus = (state, key, now = Date.now()) => {
|
|
487
513
|
const entry = state.store.get(key);
|
|
488
|
-
if (!entry) return void 0;
|
|
489
|
-
|
|
490
|
-
if (
|
|
514
|
+
if (!entry) return [null, void 0];
|
|
515
|
+
const status = computeEntryStatus(state, entry, now);
|
|
516
|
+
if (isFresh(state, status, now)) return [status, entry];
|
|
517
|
+
if (isStale(state, status, now)) {
|
|
491
518
|
if (state.purgeStaleOnGet) deleteKey(state, key, DELETE_REASON.STALE);
|
|
492
|
-
return entry
|
|
519
|
+
return [status, entry];
|
|
493
520
|
}
|
|
494
521
|
deleteKey(state, key, DELETE_REASON.EXPIRED);
|
|
522
|
+
return [status, void 0];
|
|
523
|
+
};
|
|
524
|
+
/**
|
|
525
|
+
* Retrieves a value from the cache if the entry is valid.
|
|
526
|
+
* @param state - The cache state.
|
|
527
|
+
* @param key - The key to retrieve.
|
|
528
|
+
* @param now - Optional timestamp override (defaults to Date.now()).
|
|
529
|
+
* @returns The cached value if valid, undefined otherwise.
|
|
530
|
+
*
|
|
531
|
+
* @internal
|
|
532
|
+
*/
|
|
533
|
+
const get = (state, key, now = Date.now()) => {
|
|
534
|
+
const [, entry] = getWithStatus(state, key, now);
|
|
535
|
+
return entry ? entry[1] : void 0;
|
|
495
536
|
};
|
|
496
537
|
|
|
497
538
|
//#endregion
|
|
@@ -639,28 +680,20 @@ var LocalTtlCache = class {
|
|
|
639
680
|
get size() {
|
|
640
681
|
return this.state.size;
|
|
641
682
|
}
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
*
|
|
657
|
-
* @edge-cases
|
|
658
|
-
* - Returns `undefined` if the key doesn't exist
|
|
659
|
-
* - Returns `undefined` if the key has expired beyond the stale window
|
|
660
|
-
* - Returns the stale value if within the stale window
|
|
661
|
-
* - If `purgeStaleOnGet` is enabled, stale entries are deleted after being returned
|
|
662
|
-
*/
|
|
663
|
-
get(key) {
|
|
683
|
+
get(key, options) {
|
|
684
|
+
if (options?.includeMetadata) {
|
|
685
|
+
const [status, entry] = getWithStatus(this.state, key);
|
|
686
|
+
if (!entry) return void 0;
|
|
687
|
+
const [timestamps, value, tags] = entry;
|
|
688
|
+
const [, expiresAt, staleExpiresAt] = timestamps;
|
|
689
|
+
return {
|
|
690
|
+
data: value,
|
|
691
|
+
expirationTime: expiresAt,
|
|
692
|
+
staleWindowExpiration: staleExpiresAt,
|
|
693
|
+
status,
|
|
694
|
+
tags
|
|
695
|
+
};
|
|
696
|
+
}
|
|
664
697
|
return get(this.state, key);
|
|
665
698
|
}
|
|
666
699
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/cache/clear.ts","../../src/defaults.ts","../../src/utils/start-monitor.ts","../../src/sweep/batchUpdateExpiredRatio.ts","../../src/sweep/select-instance-to-sweep.ts","../../src/cache/delete.ts","../../src/types.ts","../../src/utils/status-from-tags.ts","../../src/cache/validators.ts","../../src/sweep/sweep-once.ts","../../src/sweep/update-weight.ts","../../src/sweep/sweep.ts","../../src/cache/create-cache.ts","../../src/cache/get.ts","../../src/cache/has.ts","../../src/cache/invalidate-tag.ts","../../src/cache/set.ts","../../src/index.ts"],"sourcesContent":["import type { CacheState } from \"../types\";\n\n/**\n * Clears all entries from the cache without invoking callbacks.\n *\n * @note The `onDelete` callback is NOT invoked during a clear operation.\n * This is intentional to avoid unnecessary overhead when bulk-removing entries.\n *\n * @param state - The cache state.\n * @returns void\n */\nexport const clear = (state: CacheState): void => {\n state.store.clear();\n};\n","// Time Unit Constants\n// Base temporal units used throughout the caching system.\nconst ONE_SECOND: number = 1000;\nconst ONE_MINUTE: number = 60 * ONE_SECOND;\n\n/**\n * ===================================================================\n * Cache Entry Lifecycle\n * Default TTL and stale window settings for short-lived cache entries.\n * ===================================================================\n */\n\n/**\n * Default Time-To-Live in milliseconds for cache entries.\n * @default 1_800_000 (30 minutes)\n */\nexport const DEFAULT_TTL: number = 30 * ONE_MINUTE;\n\n/**\n * Default stale window in milliseconds after expiration.\n * Allows serving slightly outdated data while fetching fresh data.\n */\nexport const DEFAULT_STALE_WINDOW: number = 0 as const;\n\n/**\n * Maximum number of entries the cache can hold.\n * Beyond this limit, new entries are ignored.\n */\nexport const DEFAULT_MAX_SIZE: number = Infinity;\n\n/**\n * Default maximum memory size in MB the cache can use.\n * Beyond this limit, new entries are ignored.\n * @default Infinite (unlimited)\n */\nexport const DEFAULT_MAX_MEMORY_SIZE: number = Infinity;\n\n/**\n * ===================================================================\n * Sweep & Cleanup Operations\n * Parameters controlling how and when expired entries are removed.\n * ===================================================================\n */\n\n/**\n * Maximum number of keys to process in a single sweep batch.\n * Higher values = more aggressive cleanup, lower latency overhead.\n */\nexport const MAX_KEYS_PER_BATCH: number = 1000;\n\n/**\n * Minimal expired ratio enforced during sweeps.\n * Ensures control sweeps run above {@link EXPIRED_RATIO_MEMORY_THRESHOLD}.\n */\nexport const MINIMAL_EXPIRED_RATIO: number = 0.05;\n\n/**\n * Memory usage threshold (normalized 0–1) triggering control sweeps.\n * At or above this level, sweeping becomes more aggressive.\n */\nexport const EXPIRED_RATIO_MEMORY_THRESHOLD: number = 0.8;\n\n/**\n * Maximum allowed expired ratio when memory usage is low.\n * Upper bound for interpolation with MINIMAL_EXPIRED_RATIO.\n * Recommended range: `0.3 – 0.5` .\n */\nexport const DEFAULT_MAX_EXPIRED_RATIO: number = 0.4;\n\n/**\n * ===================================================================\n * Sweep Intervals & Timing\n * Frequency and time budgets for cleanup operations.\n * ===================================================================\n */\n\n/**\n * Optimal interval in milliseconds between sweeps.\n * Used when system load is minimal and metrics are available.\n */\nexport const OPTIMAL_SWEEP_INTERVAL: number = 2 * ONE_SECOND;\n\n/**\n * Worst-case interval in milliseconds between sweeps.\n * Used when system load is high or metrics unavailable.\n */\nexport const WORST_SWEEP_INTERVAL: number = 200;\n\n/**\n * Maximum time budget in milliseconds for sweep operations.\n * Prevents sweeping from consuming excessive CPU during high load.\n */\nexport const WORST_SWEEP_TIME_BUDGET: number = 40;\n\n/**\n * Optimal time budget in milliseconds for each sweep cycle.\n * Used when performance metrics are not available or unreliable.\n */\nexport const OPTIMAL_SWEEP_TIME_BUDGET_IF_NOTE_METRICS_AVAILABLE: number = 15;\n\n/**\n * ===================================================================\n * Memory Management\n * Process limits and memory-safe thresholds.\n * ===================================================================\n */\n\n/**\n * Default maximum process memory limit in megabytes.\n * Acts as fallback when environment detection is unavailable.\n * NOTE: Overridable via environment detection at runtime.\n */\nexport const DEFAULT_MAX_PROCESS_MEMORY_MB: number = 1024;\n\n/**\n * ===================================================================\n * System Utilization Weights\n * Balance how memory, CPU, and event-loop pressure influence sweep behavior.\n * Sum of all weights: 10 + 8.5 + 6.5 = 25\n * ===================================================================\n */\n\n/**\n * Weight applied to memory utilization in sweep calculations.\n * Higher weight = memory pressure has more influence on sweep aggressiveness.\n */\nexport const DEFAULT_MEMORY_WEIGHT: number = 10;\n\n/**\n * Weight applied to CPU utilization in sweep calculations.\n * Combined with event-loop weight to balance CPU-related pressure.\n */\nexport const DEFAULT_CPU_WEIGHT: number = 8.5;\n\n/**\n * Weight applied to event-loop utilization in sweep calculations.\n * Complements CPU weight to assess overall processing capacity.\n */\nexport const DEFAULT_LOOP_WEIGHT: number = 6.5;\n","import { DEFAULT_MAX_PROCESS_MEMORY_MB, WORST_SWEEP_INTERVAL } from \"../defaults\";\n\nimport { getProcessMemoryLimit } from \"./get-process-memory-limit\";\nimport {\n createMonitorObserver,\n type PerformanceMetrics,\n type ReturnCreateMonitor,\n} from \"./process-monitor\";\n\nlet _monitorInstance: ReturnCreateMonitor | null = null;\n\n/** Latest collected metrics from the monitor */\nexport let _metrics: PerformanceMetrics | null;\n\n/** Maximum memory limit for the monitor (in MB) */\nexport let maxMemoryLimit: number = DEFAULT_MAX_PROCESS_MEMORY_MB;\n\n/** Use 90% of the effective limit */\nexport const SAFE_MEMORY_LIMIT_RATIO = 0.9;\n\nexport function startMonitor(): void {\n if (__BROWSER__) {\n // Ignore monitor in browser environments\n return;\n }\n\n if (!_monitorInstance) {\n try {\n const processMemoryLimit = getProcessMemoryLimit();\n\n if (processMemoryLimit && processMemoryLimit > 0) {\n maxMemoryLimit = (processMemoryLimit / 1024 / 1024) * SAFE_MEMORY_LIMIT_RATIO;\n }\n } catch {\n // TODO: proper logger\n // Ignore errors and use default\n // console.log(\"error getProcessMemoryLimit:\", e);\n }\n\n _monitorInstance = createMonitorObserver({\n callback(metrics) {\n _metrics = metrics;\n },\n interval: WORST_SWEEP_INTERVAL,\n maxMemory: maxMemoryLimit, // 1 GB\n });\n\n _monitorInstance.start();\n }\n}\n","import { _instancesCache } from \"../cache/create-cache\";\n\n/**\n * Updates the expired ratio for each cache instance based on the collected ratios.\n * @param currentExpiredRatios - An array of arrays containing expired ratios for each cache instance.\n * @internal\n */\nexport function _batchUpdateExpiredRatio(currentExpiredRatios: number[][]): void {\n for (const inst of _instancesCache) {\n const ratios = currentExpiredRatios[inst._instanceIndexState];\n if (ratios && ratios.length > 0) {\n const avgRatio = ratios.reduce((sum, val) => sum + val, 0) / ratios.length;\n\n const alpha = 0.6; // NOTE: this must be alway higher than 0.5 to prioritize recent avgRatio\n inst._expiredRatio = inst._expiredRatio * (1 - alpha) + avgRatio * alpha;\n }\n }\n}\n","import { _instancesCache } from \"../cache/create-cache\";\nimport type { CacheState } from \"../types\";\n\n/**\n * Selects a cache instance to sweep based on sweep weights or round‑robin order.\n *\n * Two selection modes are supported:\n * - **Round‑robin mode**: If `totalSweepWeight` ≤ 0, instances are selected\n * deterministically in sequence using `batchSweep`. Once all instances\n * have been processed, returns `null`.\n * - **Weighted mode**: If sweep weights are available, performs a probabilistic\n * selection. Each instance’s `_sweepWeight` contributes proportionally to its\n * chance of being chosen.\n *\n * This function depends on `_updateWeightSweep` to maintain accurate sweep weights.\n *\n * @param totalSweepWeight - Sum of all sweep weights across instances.\n * @param batchSweep - Current batch index used for round‑robin selection.\n * @returns The selected `CacheState` instance, `null` if no instance remains,\n * or `undefined` if the cache is empty.\n */\nexport function _selectInstanceToSweep({\n totalSweepWeight,\n batchSweep,\n}: {\n totalSweepWeight: number;\n batchSweep: number;\n}): CacheState | null | undefined {\n // Default selection: initialize with the first instance in the cache list.\n // This acts as a fallback in case no weighted selection occurs.\n let instanceToSweep: CacheState | null | undefined = _instancesCache[0];\n\n if (totalSweepWeight <= 0) {\n // Case 1: No sweep weight assigned (all instances skipped or empty).\n // → Perform a deterministic round‑robin minimal sweep across all instances.\n // Each batch iteration selects the next instance in order.\n if (batchSweep > _instancesCache.length) {\n // If all instances have been processed in this cycle, no instance to sweep.\n instanceToSweep = null;\n }\n instanceToSweep = _instancesCache[batchSweep - 1] as CacheState;\n } else {\n // Case 2: Sweep weights are available.\n // → Perform a probabilistic selection based on relative sweep weights.\n // A random threshold is drawn in [0, totalSweepWeight].\n let threshold = Math.random() * totalSweepWeight;\n\n // Iterate through instances, subtracting each instance’s weight.\n // The first instance that reduces the threshold to ≤ 0 is selected.\n // This ensures that instances with higher weights have proportionally\n // higher probability of being chosen for sweeping.\n for (const inst of _instancesCache) {\n threshold -= inst._sweepWeight;\n if (threshold <= 0) {\n instanceToSweep = inst;\n break;\n }\n }\n }\n\n return instanceToSweep;\n}\n","import type { CacheState } from \"../types\";\n\nexport const enum DELETE_REASON {\n MANUAL = \"manual\",\n EXPIRED = \"expired\",\n STALE = \"stale\",\n}\n\n/**\n * Deletes a key from the cache.\n * @param state - The cache state.\n * @param key - The key.\n * @returns A boolean indicating whether the key was successfully deleted.\n */\nexport const deleteKey = (\n state: CacheState,\n key: string,\n reason: DELETE_REASON = DELETE_REASON.MANUAL,\n): boolean => {\n const onDelete = state.onDelete;\n const onExpire = state.onExpire;\n\n if (!onDelete && !onExpire) {\n return state.store.delete(key);\n }\n\n const entry = state.store.get(key);\n if (!entry) return false;\n\n state.store.delete(key);\n state.onDelete?.(key, entry[1], reason);\n if (reason !== DELETE_REASON.MANUAL) {\n state.onExpire?.(key, entry[1], reason);\n }\n\n return true;\n};\n","import type { DELETE_REASON } from \"./cache/delete\";\n\n/**\n * Base configuration shared between CacheOptions and CacheState.\n */\nexport interface CacheConfigBase {\n /**\n * Callback invoked when a key expires naturally.\n * @param key - The expired key.\n * @param value - The value associated with the expired key.\n * @param reason - The reason for deletion ('expired', or 'stale').\n */\n onExpire?: (\n key: string,\n value: unknown,\n reason: Exclude<DELETE_REASON, DELETE_REASON.MANUAL>,\n ) => void;\n\n /**\n * Callback invoked when a key is deleted, either manually or due to expiration.\n * @param key - The deleted key.\n * @param value - The value of the deleted key.\n * @param reason - The reason for deletion ('manual', 'expired', or 'stale').\n */\n onDelete?: (key: string, value: unknown, reason: DELETE_REASON) => void;\n\n /**\n * Default TTL (Time-To-Live) in milliseconds for entries without explicit TTL.\n * @default 1_800_000 (30 minutes)\n */\n defaultTtl: number;\n\n /**\n * Default stale window in milliseconds for entries that do not\n * specify their own `staleWindowMs`.\n *\n * This window determines how long an entry may continue to be\n * served as stale after it reaches its expiration time.\n *\n * The window is always relative to the entry’s own expiration\n * moment, regardless of whether that expiration comes from an\n * explicit `ttl` or from the cache’s default TTL.\n * @default null (No stale window)\n */\n defaultStaleWindow: number;\n\n /**\n * Maximum number of entries the cache can hold.\n * Beyond this limit, new entries are ignored.\n * @default Infinite (unlimited)\n */\n maxSize: number;\n\n /**\n * Maximum memory size in MB the cache can use.\n * Beyond this limit, new entries are ignored.\n * @default Infinite (unlimited)\n */\n maxMemorySize: number;\n\n /**\n * Controls how stale entries are handled when read from the cache.\n *\n * - true → stale entries are purged immediately after being returned.\n * - false → stale entries are retained after being returned.\n *\n * @default false\n */\n purgeStaleOnGet: boolean;\n\n /**\n * Controls how stale entries are handled during sweep operations.\n *\n * - true → stale entries are purged during sweeps.\n * - false → stale entries are retained during sweeps.\n *\n * @default false\n */\n purgeStaleOnSweep: boolean;\n\n /**\n * Whether to automatically start the sweep process when the cache is created.\n *\n * - true → sweep starts automatically.\n * - false → sweep does not start automatically, allowing manual control.\n *\n * @internal\n * @default true\n */\n _autoStartSweep: boolean;\n\n /**\n * Allowed expired ratio for the cache instance.\n */\n _maxAllowExpiredRatio: number;\n}\n\n/**\n * Public configuration options for the TTL cache.\n */\nexport type CacheOptions = Partial<CacheConfigBase>;\n\n/**\n * Options for `invalidateTag` operation. Kept intentionally extensible so\n * future flags can be added without breaking callers.\n */\nexport interface InvalidateTagOptions {\n /** If true, mark affected entries as stale instead of fully expired. */\n asStale?: boolean;\n\n // Allow additional option fields for forward-compatibility.\n [key: string]: unknown;\n}\n\n/**\n * Lifecycle timestamps stored in a Tuple:\n * - 0 → createdAt\n * - 1 → expiresAt\n * - 2 → staleExpiresAt\n */\nexport type EntryTimestamp = [\n /** createdAt: Absolute timestamp the entry was created (Date.now()). */\n number,\n\n /** expiresAt: Absolute timestamp when the entry becomes invalid (Date.now() + TTL). */\n number,\n\n /** staleExpiresAt: Absolute timestamp when the entry stops being stale (Date.now() + staleTTL). */\n number,\n];\n\n/**\n * Represents a single cache entry.\n */\nexport type CacheEntry = [\n EntryTimestamp,\n\n /** The stored value. */\n unknown,\n\n (\n /**\n * Optional list of tags associated with this entry.\n * Tags can be used for:\n * - Group invalidation (e.g., clearing all entries with a given tag)\n * - Namespacing or categorization\n * - Tracking dependencies\n *\n * If no tags are associated, this field is `null`.\n */\n string[] | null\n ),\n];\n\n/**\n * Status of a cache entry.\n */\nexport enum ENTRY_STATUS {\n /** The entry is fresh and valid. */\n FRESH = \"fresh\",\n /** The entry is stale but can still be served. */\n STALE = \"stale\",\n /** The entry has expired and is no longer valid. */\n EXPIRED = \"expired\",\n}\n\n/**\n * Internal state of the TTL cache.\n */\nexport interface CacheState extends CacheConfigBase {\n /** Map storing key-value entries. */\n store: Map<string, CacheEntry>;\n\n /** Current size */\n size: number;\n\n /** Iterator for sweeping keys. */\n _sweepIter: MapIterator<[string, CacheEntry]> | null;\n\n /** Index of this instance for sweep all. */\n _instanceIndexState: number;\n\n /** Expire ratio avg for instance */\n _expiredRatio: number;\n\n /** Sweep weight for instance, calculate based on size and _expiredRatio */\n _sweepWeight: number;\n\n /**\n * Tag invalidation state.\n * Each tag stores:\n * - 0 → moment when the tag was marked as expired (0 if never)\n * - 1 → moment when the tag was marked as stale (0 if never)\n *\n * These timestamps define whether a tag affects an entry based on\n * the entry's creation time. */\n _tags: Map<string, [number, number]>;\n}\n","import { ENTRY_STATUS, type CacheEntry, type CacheState } from \"../types\";\n\n/**\n * Computes the derived status of a cache entry based on its associated tags.\n *\n * Tags may impose stricter expiration or stale rules on the entry. Only tags\n * created at or after the entry's creation timestamp are considered relevant.\n *\n * Resolution rules:\n * - If any applicable tag marks the entry as expired, the status becomes `EXPIRED`.\n * - Otherwise, if any applicable tag marks it as stale, the status becomes `STALE`.\n * - If no tag imposes stricter rules, the entry remains `FRESH`.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry whose status is being evaluated.\n * @returns A tuple containing:\n * - The final {@link ENTRY_STATUS} imposed by tags.\n * - The earliest timestamp at which a tag marked the entry as stale\n * (or 0 if no tag imposed a stale rule).\n */\nexport function _statusFromTags(state: CacheState, entry: CacheEntry): [ENTRY_STATUS, number] {\n const entryCreatedAt = entry[0][0];\n\n // Tracks the earliest point in time when any tag marked this entry as stale.\n // Initialized to Infinity so that comparisons always pick the minimum.\n let earliestTagStaleInvalidation = Infinity;\n\n // Default assumption: entry is fresh unless tags override.\n let status = ENTRY_STATUS.FRESH;\n\n const tags = entry[2];\n if (tags) {\n for (const tag of tags) {\n const ts = state._tags.get(tag);\n if (!ts) continue;\n\n // Each tag provides two timestamps:\n // - tagExpiredAt: when the tag forces expiration\n // - tagStaleSinceAt: when the tag forces stale status\n const [tagExpiredAt, tagStaleSinceAt] = ts;\n\n // A tag can only override if it was created after the entry itself.\n if (tagExpiredAt >= entryCreatedAt) {\n status = ENTRY_STATUS.EXPIRED;\n break; // Expired overrides everything, no need to check further.\n }\n\n if (tagStaleSinceAt >= entryCreatedAt) {\n // Keep track of the earliest stale timestamp across all tags.\n if (tagStaleSinceAt < earliestTagStaleInvalidation) {\n earliestTagStaleInvalidation = tagStaleSinceAt;\n }\n status = ENTRY_STATUS.STALE;\n }\n }\n }\n\n // If no tag imposed stale, return 0 for the timestamp.\n return [status, status === ENTRY_STATUS.STALE ? earliestTagStaleInvalidation : 0];\n}\n","import { ENTRY_STATUS, type CacheEntry, type CacheState } from \"../types\";\nimport { _statusFromTags } from \"../utils/status-from-tags\";\n\n/**\n * Computes the final derived status of a cache entry by combining:\n *\n * - The entry's own expiration timestamps (TTL and stale TTL).\n * - Any stricter expiration or stale rules imposed by its associated tags.\n *\n * Precedence rules:\n * - `EXPIRED` overrides everything.\n * - `STALE` overrides `FRESH`.\n * - If neither the entry nor its tags impose stricter rules, the entry is `FRESH`.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry being evaluated.\n * @returns The final {@link ENTRY_STATUS} for the entry.\n */\nexport function computeEntryStatus(\n state: CacheState,\n entry: CacheEntry,\n\n /** @internal */\n now: number,\n): ENTRY_STATUS {\n const [__createdAt, expiresAt, staleExpiresAt] = entry[0];\n\n // 1. Status derived from tags\n const [tagStatus, earliestTagStaleInvalidation] = _statusFromTags(state, entry);\n if (tagStatus === ENTRY_STATUS.EXPIRED) return ENTRY_STATUS.EXPIRED;\n const windowStale = staleExpiresAt - expiresAt;\n if (\n tagStatus === ENTRY_STATUS.STALE &&\n staleExpiresAt > 0 &&\n now < earliestTagStaleInvalidation + windowStale\n ) {\n // A tag can mark the entry as stale only if the entry itself supports a stale window.\n // The tag's stale invalidation time is extended by the entry's stale window duration.\n // If \"now\" is still within that extended window, the entry is considered stale.\n return ENTRY_STATUS.STALE;\n }\n\n // 2. Status derived from entry timestamps\n if (now < expiresAt) {\n return ENTRY_STATUS.FRESH;\n }\n if (staleExpiresAt > 0 && now < staleExpiresAt) {\n return ENTRY_STATUS.STALE;\n }\n\n return ENTRY_STATUS.EXPIRED;\n}\n\n// ---------------------------------------------------------------------------\n// Entry status wrappers (semantic helpers built on top of computeEntryStatus)\n// ---------------------------------------------------------------------------\n/**\n * Determines whether a cache entry is fresh.\n *\n * A fresh entry is one whose final derived status is `FRESH`, meaning:\n * - It has not expired according to its own timestamps, and\n * - No associated tag imposes a stricter stale or expired rule.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry being evaluated.\n * @returns True if the entry is fresh.\n */\nexport const isFresh = (state: CacheState, entry: CacheEntry, now: number): boolean =>\n computeEntryStatus(state, entry, now) === ENTRY_STATUS.FRESH;\n\n/**\n * Determines whether a cache entry is stale.\n *\n * A stale entry is one whose final derived status is `STALE`, meaning:\n * - It has passed its TTL but is still within its stale window, or\n * - A tag imposes a stale rule that applies to this entry.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry being evaluated.\n * @returns True if the entry is stale.\n */\nexport const isStale = (\n state: CacheState,\n entry: CacheEntry,\n\n /** @internal */\n now: number,\n): boolean => computeEntryStatus(state, entry, now) === ENTRY_STATUS.STALE;\n\n/**\n * Determines whether a cache entry is expired.\n *\n * An expired entry is one whose final derived status is `EXPIRED`, meaning:\n * - It has exceeded both its TTL and stale TTL, or\n * - A tag imposes an expiration rule that applies to this entry.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry being evaluated.\n * @returns True if the entry is expired.\n */\nexport const isExpired = (\n state: CacheState,\n entry: CacheEntry,\n\n /** @internal */\n now: number,\n): boolean => computeEntryStatus(state, entry, now) === ENTRY_STATUS.EXPIRED;\n\n/**\n * Determines whether a cache entry is valid.\n *\n * A valid entry is one whose final derived status is either:\n * - `FRESH`, or\n * - `STALE` (still within its stale window).\n *\n * Expired entries are considered invalid.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry, or undefined/null if not found.\n * @returns True if the entry exists and is fresh or stale.\n */\nexport const isValid = (\n state: CacheState,\n entry?: CacheEntry | null,\n\n /** @internal */\n now: number = Date.now(),\n): boolean => {\n if (!entry) return false;\n const status = computeEntryStatus(state, entry, now);\n return status === ENTRY_STATUS.FRESH || status === ENTRY_STATUS.STALE;\n};\n","import { DELETE_REASON, deleteKey } from \"../cache/delete\";\nimport { isExpired, isStale } from \"../cache/validators\";\nimport { MAX_KEYS_PER_BATCH } from \"../defaults\";\nimport { type CacheState } from \"../types\";\n\n/**\n * Performs a single sweep operation on the cache to remove expired and optionally stale entries.\n * Uses a linear scan with a saved pointer to resume from the last processed key.\n * @param state - The cache state.\n * @param _maxKeysPerBatch - Maximum number of keys to process in this sweep.\n * @returns An object containing statistics about the sweep operation.\n */\nexport function _sweepOnce(\n state: CacheState,\n\n /**\n * Maximum number of keys to process in this sweep.\n * @default 1000\n */\n _maxKeysPerBatch: number = MAX_KEYS_PER_BATCH,\n): { processed: number; expiredCount: number; staleCount: number; ratio: number } {\n if (!state._sweepIter) {\n state._sweepIter = state.store.entries();\n }\n\n let processed = 0;\n let expiredCount = 0;\n let staleCount = 0;\n\n for (let i = 0; i < _maxKeysPerBatch; i++) {\n const next = state._sweepIter.next();\n\n if (next.done) {\n state._sweepIter = state.store.entries();\n break;\n }\n\n processed += 1;\n const [key, entry] = next.value;\n\n const now = Date.now();\n\n if (isExpired(state, entry, now)) {\n deleteKey(state, key, DELETE_REASON.EXPIRED);\n expiredCount += 1;\n } else if (isStale(state, entry, now)) {\n staleCount += 1;\n\n if (state.purgeStaleOnSweep) {\n deleteKey(state, key, DELETE_REASON.STALE);\n }\n }\n }\n\n const expiredStaleCount = state.purgeStaleOnSweep ? staleCount : 0;\n return {\n processed,\n expiredCount,\n staleCount,\n ratio: processed > 0 ? (expiredCount + expiredStaleCount) / processed : 0,\n };\n}\n","import { _instancesCache } from \"../cache/create-cache\";\nimport { MINIMAL_EXPIRED_RATIO } from \"../defaults\";\n\nimport { calculateOptimalMaxExpiredRatio } from \"./calculate-optimal-max-expired-ratio\";\n\n/**\n * Updates the sweep weight (`_sweepWeight`) for each cache instance.\n *\n * The sweep weight determines the probability that an instance will be selected\n * for a cleanup (sweep) process. It is calculated based on the store size and\n * the ratio of expired keys.\n *\n * This function complements (`_selectInstanceToSweep`), which is responsible\n * for selecting the correct instance based on the weights assigned here.\n *\n * ---\n *\n * ### Sweep systems:\n * 1. **Normal sweep**\n * - Runs whenever the percentage of expired keys exceeds the allowed threshold\n * calculated by `calculateOptimalMaxExpiredRatio`.\n * - It is the main cleanup mechanism and is applied proportionally to the\n * store size and the expired‑key ratio.\n *\n * 2. **Memory‑conditioned sweep (control)**\n * - Works exactly like the normal sweep, except it may run even when it\n * normally wouldn’t.\n * - Only activates under **high memory pressure**.\n * - Serves as an additional control mechanism to adjust weights, keep the\n * system updated, and help prevent memory overflows.\n *\n * 3. **Round‑robin sweep (minimal control)**\n * - Always runs, even if the expired ratio is low or memory usage does not\n * require it.\n * - Processes a very small number of keys per instance, much smaller than\n * the normal sweep.\n * - Its main purpose is to ensure that all instances receive at least a\n * periodic weight update and minimal expired‑key control.\n *\n * ---\n * #### Important notes:\n * - A minimum `MINIMAL_EXPIRED_RATIO` (e.g., 5%) is assumed to ensure that\n * control sweeps can always run under high‑memory scenarios.\n * - Even with a minimum ratio, the normal sweep and the memory‑conditioned sweep\n * may **skip execution** if memory usage allows it and the expired ratio is\n * below the optimal maximum.\n * - The round‑robin sweep is never skipped: it always runs with a very small,\n * almost imperceptible cost.\n *\n * @returns The total accumulated sweep weight across all cache instances.\n */\nexport function _updateWeightSweep(): number {\n let totalSweepWeight = 0;\n\n for (const instCache of _instancesCache) {\n if (instCache.store.size <= 0) {\n // Empty instance → no sweep weight needed, skip sweep for this instance.\n instCache._sweepWeight = 0;\n continue;\n }\n\n // Ensure a minimum expired ratio to allow control sweeps.\n // If the real ratio is higher than the minimum, use the real ratio.\n let expiredRatio = MINIMAL_EXPIRED_RATIO;\n if (instCache._expiredRatio > MINIMAL_EXPIRED_RATIO) {\n expiredRatio = instCache._expiredRatio;\n }\n\n if (!__BROWSER__) {\n // In non‑browser environments, compute an optimal maximum allowed ratio.\n const optimalMaxExpiredRatio = calculateOptimalMaxExpiredRatio(\n instCache._maxAllowExpiredRatio,\n );\n\n if (expiredRatio <= optimalMaxExpiredRatio) {\n // If memory usage allows it and the expired ratio is low,\n // this sweep can be skipped. The reduced round‑robin sweep will still run.\n instCache._sweepWeight = 0;\n continue;\n }\n }\n\n // Normal sweep: weight proportional to store size and expired ratio.\n instCache._sweepWeight = instCache.store.size * expiredRatio;\n totalSweepWeight += instCache._sweepWeight;\n }\n\n return totalSweepWeight;\n}\n","import { _instancesCache } from \"../cache/create-cache\";\nimport {\n MAX_KEYS_PER_BATCH,\n OPTIMAL_SWEEP_INTERVAL,\n OPTIMAL_SWEEP_TIME_BUDGET_IF_NOTE_METRICS_AVAILABLE,\n} from \"../defaults\";\nimport type { CacheState } from \"../types\";\nimport { _metrics } from \"../utils/start-monitor\";\n\nimport { _batchUpdateExpiredRatio } from \"./batchUpdateExpiredRatio\";\nimport { calculateOptimalSweepParams } from \"./calculate-optimal-sweep-params\";\nimport { _selectInstanceToSweep } from \"./select-instance-to-sweep\";\nimport { _sweepOnce } from \"./sweep-once\";\nimport { _updateWeightSweep } from \"./update-weight\";\n\n/**\n * Performs a sweep operation on the cache to remove expired and optionally stale entries.\n * Uses a linear scan with a saved pointer to resume from the last processed key.\n * @param state - The cache state.\n */\nexport const sweep = async (\n state: CacheState,\n\n /** @internal */\n utilities: SweepUtilities = {},\n): Promise<void> => {\n const {\n schedule = defaultSchedule,\n yieldFn = defaultYieldFn,\n now = Date.now(),\n runOnlyOne = false,\n } = utilities;\n const startTime = now;\n\n let sweepIntervalMs = OPTIMAL_SWEEP_INTERVAL;\n let sweepTimeBudgetMs = OPTIMAL_SWEEP_TIME_BUDGET_IF_NOTE_METRICS_AVAILABLE;\n if (!__BROWSER__ && _metrics) {\n ({ sweepIntervalMs, sweepTimeBudgetMs } = calculateOptimalSweepParams({ metrics: _metrics }));\n }\n\n const totalSweepWeight = _updateWeightSweep();\n const currentExpiredRatios: number[][] = [];\n\n // Reduce the maximum number of keys per batch only when no instance weights are available\n // and the sweep is running in minimal round‑robin control mode. In this case, execute the\n // smallest possible sweep (equivalent to one batch, but divided across instances).\n const maxKeysPerBatch =\n totalSweepWeight <= 0 ? MAX_KEYS_PER_BATCH / _instancesCache.length : MAX_KEYS_PER_BATCH;\n\n let batchSweep = 0;\n while (true) {\n batchSweep += 1;\n\n const instanceToSweep = _selectInstanceToSweep({ batchSweep, totalSweepWeight });\n if (!instanceToSweep) {\n // No instance to sweep\n break;\n }\n\n const { ratio } = _sweepOnce(instanceToSweep, maxKeysPerBatch);\n // Initialize or update `currentExpiredRatios` array for current ratios\n (currentExpiredRatios[instanceToSweep._instanceIndexState] ??= []).push(ratio);\n\n if (Date.now() - startTime > sweepTimeBudgetMs) {\n break;\n }\n\n await yieldFn();\n }\n\n _batchUpdateExpiredRatio(currentExpiredRatios);\n\n // Schedule next sweep\n if (!runOnlyOne) {\n schedule(() => void sweep(state, utilities), sweepIntervalMs);\n }\n};\n\n// Default utilities for scheduling and yielding --------------------------------\nconst defaultSchedule: scheduleType = (fn, ms) => {\n const t = setTimeout(fn, ms);\n if (typeof t.unref === \"function\") t.unref();\n};\nexport const defaultYieldFn: yieldFnType = () => new Promise(resolve => setImmediate(resolve));\n\n// Types for internal utilities -----------------------------------------------\ntype scheduleType = (fn: () => void, ms: number) => void;\ntype yieldFnType = () => Promise<void>;\ninterface SweepUtilities {\n /**\n * Default scheduling function using setTimeout.\n * This can be overridden for testing.\n * @internal\n */\n schedule?: scheduleType;\n\n /**\n * Default yielding function using setImmediate.\n * This can be overridden for testing.\n * @internal\n */\n yieldFn?: yieldFnType;\n\n /** Current timestamp for testing purposes. */\n now?: number;\n\n /**\n * If true, only run one sweep cycle.\n * @internal\n */\n runOnlyOne?: boolean;\n}\n","import {\n DEFAULT_MAX_EXPIRED_RATIO,\n DEFAULT_MAX_MEMORY_SIZE,\n DEFAULT_MAX_SIZE,\n DEFAULT_STALE_WINDOW,\n DEFAULT_TTL,\n} from \"../defaults\";\nimport { sweep } from \"../sweep/sweep\";\nimport type { CacheOptions, CacheState } from \"../types\";\nimport { startMonitor } from \"../utils/start-monitor\";\n\nlet _instanceCount = 0;\nconst INSTANCE_WARNING_THRESHOLD = 99;\nexport const _instancesCache: CacheState[] = [];\n\n/**\n * Resets the instance count for testing purposes.\n * This function is intended for use in tests to avoid instance limits.\n */\nexport const _resetInstanceCount = (): void => {\n _instanceCount = 0;\n};\n\nlet _initSweepScheduled = false;\n\n/**\n * Creates the initial state for the TTL cache.\n * @param options - Configuration options for the cache.\n * @returns The initial cache state.\n */\nexport const createCache = (options: CacheOptions = {}): CacheState => {\n const {\n onExpire,\n onDelete,\n defaultTtl = DEFAULT_TTL,\n maxSize = DEFAULT_MAX_SIZE,\n maxMemorySize = DEFAULT_MAX_MEMORY_SIZE,\n _maxAllowExpiredRatio = DEFAULT_MAX_EXPIRED_RATIO,\n defaultStaleWindow = DEFAULT_STALE_WINDOW,\n purgeStaleOnGet = false,\n purgeStaleOnSweep = false,\n _autoStartSweep = true,\n } = options;\n\n _instanceCount++;\n\n // NEXT: warn if internal parameters are touch by user\n\n if (_instanceCount > INSTANCE_WARNING_THRESHOLD) {\n // NEXT: Use a proper logging mechanism\n // NEXT: Create documentation for this\n console.warn(\n `Too many instances detected (${_instanceCount}). This may indicate a configuration issue; consider minimizing instance creation or grouping keys by expected expiration ranges. See the documentation: https://github.com/neezco/cache/docs/getting-started.md`,\n );\n }\n\n const state: CacheState = {\n store: new Map(),\n _sweepIter: null,\n get size() {\n return state.store.size;\n },\n onExpire,\n onDelete,\n maxSize,\n maxMemorySize,\n defaultTtl,\n defaultStaleWindow,\n purgeStaleOnGet,\n purgeStaleOnSweep,\n _maxAllowExpiredRatio,\n _autoStartSweep,\n _instanceIndexState: -1,\n _expiredRatio: 0,\n _sweepWeight: 0,\n _tags: new Map(),\n };\n\n state._instanceIndexState = _instancesCache.push(state) - 1;\n\n // Start the sweep process\n if (_autoStartSweep) {\n if (_initSweepScheduled) return state;\n _initSweepScheduled = true;\n void sweep(state);\n }\n\n startMonitor();\n\n return state;\n};\n","import type { CacheState } from \"../types\";\n\nimport { DELETE_REASON, deleteKey } from \"./delete\";\nimport { isFresh, isStale } from \"./validators\";\n\n/**\n * Retrieves a value from the cache if the entry is valid.\n * @param state - The cache state.\n * @param key - The key to retrieve.\n * @param now - Optional timestamp override (defaults to Date.now()).\n * @returns The cached value if valid, null otherwise.\n */\nexport const get = (state: CacheState, key: string, now: number = Date.now()): unknown => {\n const entry = state.store.get(key);\n\n if (!entry) return undefined;\n\n if (isFresh(state, entry, now)) return entry[1];\n\n if (isStale(state, entry, now)) {\n if (state.purgeStaleOnGet) {\n deleteKey(state, key, DELETE_REASON.STALE);\n }\n return entry[1];\n }\n\n // If it expired, always delete it\n deleteKey(state, key, DELETE_REASON.EXPIRED);\n\n return undefined;\n};\n","import type { CacheState } from \"../types\";\n\nimport { get } from \"./get\";\n\n/**\n * Checks if a key exists in the cache and is not expired.\n * @param state - The cache state.\n * @param key - The key to check.\n * @param now - Optional timestamp override (defaults to Date.now()).\n * @returns True if the key exists and is valid, false otherwise.\n */\nexport const has = (state: CacheState, key: string, now: number = Date.now()): boolean => {\n return get(state, key, now) !== undefined;\n};\n","import type { CacheState, InvalidateTagOptions } from \"../types\";\n\n/**\n * Invalidates one or more tags so that entries associated with them\n * become expired or stale from this moment onward.\n *\n * Semantics:\n * - Each tag maintains two timestamps in `state._tags`:\n * [expiredAt, staleSinceAt].\n * - Calling this function updates one of those timestamps to `_now`,\n * depending on whether the tag should force expiration or staleness.\n *\n * Rules:\n * - If `asStale` is false (default), the tag forces expiration:\n * entries created before `_now` will be considered expired.\n * - If `asStale` is true, the tag forces staleness:\n * entries created before `_now` will be considered stale,\n * but only if they support a stale window.\n *\n * Behavior:\n * - Each call replaces any previous invalidation timestamp for the tag.\n * - Entries created after `_now` are unaffected.\n *\n * @param state - The cache state containing tag metadata.\n * @param tags - A tag or list of tags to invalidate.\n * @param options.asStale - Whether the tag should mark entries as stale.\n */\nexport function invalidateTag(\n state: CacheState,\n tags: string | string[],\n options: InvalidateTagOptions = {},\n\n /** @internal */\n _now: number = Date.now(),\n): void {\n const tagList = Array.isArray(tags) ? tags : [tags];\n const asStale = options.asStale ?? false;\n\n for (const tag of tagList) {\n const currentTag = state._tags.get(tag);\n\n if (currentTag) {\n // Update existing tag timestamps:\n // index 0 = expiredAt, index 1 = staleSinceAt\n if (asStale) {\n currentTag[1] = _now;\n } else {\n currentTag[0] = _now;\n }\n } else {\n // Initialize new tag entry with appropriate timestamp.\n // If marking as stale, expiredAt = 0 and staleSinceAt = _now.\n // If marking as expired, expiredAt = _now and staleSinceAt = 0.\n state._tags.set(tag, [asStale ? 0 : _now, asStale ? _now : 0]);\n }\n }\n}\n","import type { CacheState, CacheEntry } from \"../types\";\nimport { _metrics } from \"../utils/start-monitor\";\n\n/**\n * Sets or updates a value in the cache with TTL and an optional stale window.\n *\n * @param state - The cache state.\n * @param input - Cache entry definition (key, value, ttl, staleWindow, tags).\n * @param now - Optional timestamp override used as the base time (defaults to Date.now()).\n * @returns True if the entry was created or updated, false if rejected due to limits or invalid input.\n *\n * @remarks\n * - `ttl` defines when the entry becomes expired.\n * - `staleWindow` defines how long the entry may still be served as stale\n * after the expiration moment (`now + ttl`).\n * - Returns false if value is `undefined` (entry ignored, existing value untouched).\n * - Returns false if new entry would exceed `maxSize` limit (existing keys always allowed).\n * - Returns false if new entry would exceed `maxMemorySize` limit (existing keys always allowed).\n * - Returns true if entry was set or updated (or if existing key was updated at limit).\n */\nexport const setOrUpdate = (\n state: CacheState,\n input: CacheSetOrUpdateInput,\n\n /** @internal */\n now: number = Date.now(),\n): boolean => {\n const { key, value, ttl: ttlInput, staleWindow: staleWindowInput, tags } = input;\n\n if (value === undefined) return false; // Ignore undefined values, leaving existing entry intact if it exists\n if (key == null) throw new Error(\"Missing key.\");\n if (state.size >= state.maxSize && !state.store.has(key)) {\n // Ignore new entries when max size is reached, but allow updates to existing keys\n return false;\n }\n if (\n !__BROWSER__ &&\n _metrics?.memory.total.rss &&\n _metrics?.memory.total.rss >= state.maxMemorySize * 1024 * 1024 &&\n !state.store.has(key)\n ) {\n // Ignore new entries when max memory size is reached, but allow updates to existing keys\n return false;\n }\n\n const ttl = ttlInput ?? state.defaultTtl;\n const staleWindow = staleWindowInput ?? state.defaultStaleWindow;\n\n const expiresAt = ttl > 0 ? now + ttl : Infinity;\n const entry: CacheEntry = [\n [\n now, // createdAt\n expiresAt, // expiresAt\n staleWindow > 0 ? expiresAt + staleWindow : 0, // staleExpiresAt (relative to expiration)\n ],\n value,\n typeof tags === \"string\" ? [tags] : Array.isArray(tags) ? tags : null,\n ];\n\n state.store.set(key, entry);\n return true;\n};\n\n/**\n * Input parameters for setting or updating a cache entry.\n */\nexport interface CacheSetOrUpdateInput {\n /**\n * Key under which the value will be stored.\n */\n key: string;\n\n /**\n * Value to be written to the cache.\n *\n * Considerations:\n * - Always overwrites any previous value, if one exists.\n * - `undefined` is ignored, leaving any previous value intact, if one exists.\n * - `null` is explicitly stored as a null value, replacing any previous value, if one exists.\n */\n value: unknown;\n\n /**\n * TTL (Time-To-Live) in milliseconds for this entry.\n */\n ttl?: number;\n\n /**\n * Optional stale window in milliseconds.\n *\n * Defines how long the entry may continue to be served as stale\n * after it has reached its expiration time.\n *\n * The window is always relative to the entry’s own expiration moment,\n * whether that expiration comes from an explicit `ttl` or from the\n * cache’s default TTL.\n *\n * If omitted, the cache-level default stale window is used.\n */\n staleWindow?: number;\n\n /**\n * Optional tags associated with this entry.\n */\n tags?: string | string[];\n}\n","import { clear } from \"./cache/clear\";\nimport { createCache } from \"./cache/create-cache\";\nimport { deleteKey } from \"./cache/delete\";\nimport { get } from \"./cache/get\";\nimport { has } from \"./cache/has\";\nimport { invalidateTag } from \"./cache/invalidate-tag\";\nimport { setOrUpdate } from \"./cache/set\";\nimport type { CacheOptions, CacheState, InvalidateTagOptions } from \"./types\";\n\nexport type { CacheOptions, InvalidateTagOptions } from \"./types\";\n\n/**\n * A TTL (Time-To-Live) cache implementation with support for expiration,\n * stale windows, tag-based invalidation, and automatic sweeping.\n *\n * Provides O(1) constant-time operations for all core methods.\n *\n * @example\n * ```typescript\n * const cache = new LocalTtlCache();\n * cache.set(\"user:123\", { name: \"Alice\" }, { ttl: 5 * 60 * 1000 });\n * const user = cache.get(\"user:123\"); // { name: \"Alice\" }\n * ```\n */\nexport class LocalTtlCache {\n private state: CacheState;\n\n /**\n * Creates a new cache instance.\n *\n * @param options - Configuration options for the cache (defaultTtl, defaultStaleWindow, maxSize, etc.)\n *\n * @example\n * ```typescript\n * const cache = new LocalTtlCache({\n * defaultTtl: 30 * 60 * 1000, // 30 minutes\n * defaultStaleWindow: 5 * 60 * 1000, // 5 minutes\n * maxSize: 500_000, // Maximum 500_000 entries\n * onExpire: (key, value) => console.log(`Expired: ${key}`),\n * onDelete: (key, value, reason) => console.log(`Deleted: ${key}, reason: ${reason}`),\n * });\n * ```\n */\n constructor(options?: CacheOptions) {\n this.state = createCache(options);\n }\n\n /**\n * Gets the current number of entries tracked by the cache.\n *\n * This value may include entries that are already expired but have not yet been\n * removed by the lazy cleanup system. Expired keys are cleaned only when it is\n * efficient to do so, so the count can temporarily be higher than the number of\n * actually valid (non‑expired) entries.\n *\n * @returns The number of entries currently stored (including entries pending cleanup)\n *\n * @example\n * ```typescript\n * console.log(cache.size); // e.g., 42\n * ```\n */\n get size(): number {\n return this.state.size;\n }\n\n /**\n * Retrieves a value from the cache.\n *\n * Returns the value if it exists and is not fully expired. If an entry is in the\n * stale window (expired but still within staleWindow), the stale value is returned.\n *\n\n * @param key - The key to retrieve\n * @returns The cached value if valid, undefined otherwise\n *\n * @example\n * ```typescript\n * const user = cache.get<{ name: string }>(\"user:123\");\n * ```\n *\n * @edge-cases\n * - Returns `undefined` if the key doesn't exist\n * - Returns `undefined` if the key has expired beyond the stale window\n * - Returns the stale value if within the stale window\n * - If `purgeStaleOnGet` is enabled, stale entries are deleted after being returned\n */\n get<T = unknown>(key: string): T | undefined {\n return get(this.state, key) as T | undefined;\n }\n\n /**\n * Sets or updates a value in the cache.\n *\n * If the key already exists, it will be completely replaced.\n *\n * @param key - The key under which to store the value\n * @param value - The value to cache (any type)\n * @param options - Optional configuration for this specific entry\n * @param options.ttl - Time-To-Live in milliseconds. Defaults to `defaultTtl`\n * @param options.staleWindow - How long to serve stale data after expiration (milliseconds)\n * @param options.tags - One or more tags for group invalidation\n * @returns True if the entry was set or updated, false if rejected due to limits or invalid input\n *\n * @example\n * ```typescript\n * const success = cache.set(\"user:123\", { name: \"Alice\" }, {\n * ttl: 5 * 60 * 1000,\n * staleWindow: 1 * 60 * 1000,\n * tags: \"user:123\",\n * });\n *\n * if (!success) {\n * console.log(\"Entry was rejected due to size or memory limits\");\n * }\n * ```\n *\n * @edge-cases\n * - Overwriting an existing key replaces it completely\n * - If `ttl` is 0 or Infinite, the entry never expires\n * - If `staleWindow` is larger than `ttl`, the entry can be served as stale longer than it was fresh\n * - Tags are optional; only necessary for group invalidation via `invalidateTag()`\n * - Returns `false` if value is `undefined` (existing value remains untouched)\n * - Returns `false` if new key would exceed [`maxSize`](./docs/configuration.md#maxsize-number) limit\n * - Returns `false` if new key would exceed [`maxMemorySize`](./docs/configuration.md#maxmemorysize-number) limit\n * - Updating existing keys always succeeds, even at limit\n */\n set(\n key: string,\n value: unknown,\n options?: {\n ttl?: number;\n staleWindow?: number;\n tags?: string | string[];\n },\n ): boolean {\n return setOrUpdate(this.state, {\n key,\n value,\n ttl: options?.ttl,\n staleWindow: options?.staleWindow,\n tags: options?.tags,\n });\n }\n\n /**\n * Deletes a specific key from the cache.\n *\n * @param key - The key to delete\n * @returns True if the key was deleted, false if it didn't exist\n *\n * @example\n * ```typescript\n * const wasDeleted = cache.delete(\"user:123\");\n * ```\n *\n * @edge-cases\n * - Triggers the `onDelete` callback with reason `'manual'`\n * - Does not trigger the `onExpire` callback\n * - Returns `false` if the key was already expired\n * - Deleting a non-existent key returns `false` without error\n */\n delete(key: string): boolean {\n return deleteKey(this.state, key);\n }\n\n /**\n * Checks if a key exists in the cache and is not fully expired.\n *\n * Returns true if the key exists and is either fresh or within the stale window.\n * Use this when you only need to check existence without retrieving the value.\n *\n * @param key - The key to check\n * @returns True if the key exists and is valid, false otherwise\n *\n * @example\n * ```typescript\n * if (cache.has(\"user:123\")) {\n * // Key exists (either fresh or stale)\n * }\n * ```\n *\n * @edge-cases\n * - Returns `false` if the key doesn't exist\n * - Returns `false` if the key has expired beyond the stale window\n * - Returns `true` if the key is in the stale window (still being served)\n * - Both `has()` and `get()` have O(1) complexity; prefer `get()` if you need the value\n */\n has(key: string): boolean {\n return has(this.state, key);\n }\n\n /**\n * Removes all entries from the cache at once.\n *\n * This is useful for resetting the cache or freeing memory when needed.\n * The `onDelete` callback is NOT invoked during clear (intentional optimization).\n *\n * @example\n * ```typescript\n * cache.clear(); // cache.size is now 0\n * ```\n *\n * @edge-cases\n * - The `onDelete` callback is NOT triggered during clear\n * - Clears both expired and fresh entries\n * - Resets `cache.size` to 0\n */\n clear(): void {\n // NEXT: optional supor for onClear callback?\n clear(this.state);\n }\n\n /**\n * Marks all entries with one or more tags as expired (or stale, if requested).\n *\n * If an entry has multiple tags, invalidating ANY of those tags will invalidate the entry.\n *\n * @param tags - A single tag (string) or array of tags to invalidate\n * @param asStale - If true, marks entries as stale instead of fully expired (still served from stale window)\n *\n * @example\n * ```typescript\n * // Invalidate a single tag\n * cache.invalidateTag(\"user:123\");\n *\n * // Invalidate multiple tags\n * cache.invalidateTag([\"user:123\", \"posts:456\"]);\n * ```\n *\n * @edge-cases\n * - Does not throw errors if a tag has no associated entries\n * - Invalidating a tag doesn't prevent new entries from being tagged with it later\n * - The `onDelete` callback is triggered with reason `'expired'` (even if `asStale` is true)\n */\n invalidateTag(tags: string | string[], options?: InvalidateTagOptions): void {\n invalidateTag(this.state, tags, options ?? {});\n }\n}\n"],"mappings":";;;;;;;;;;AAWA,MAAa,SAAS,UAA4B;AAChD,OAAM,MAAM,OAAO;;;;;ACVrB,MAAM,aAAqB;AAC3B,MAAM,aAAqB,KAAK;;;;;;;;;;;AAahC,MAAa,cAAsB,KAAK;;;;;AAMxC,MAAa,uBAA+B;;;;;AAM5C,MAAa,mBAA2B;;;;;;AAOxC,MAAa,0BAAkC;;;;;;;;;;;AAa/C,MAAa,qBAA6B;;;;;AAM1C,MAAa,wBAAgC;;;;;;AAa7C,MAAa,4BAAoC;;;;;;;;;;;AAajD,MAAa,yBAAiC,IAAI;;;;;AAkBlD,MAAa,sDAA8D;;;;AC9E3E,SAAgB,eAAqB;;;;;;;;;ACbrC,SAAgB,yBAAyB,sBAAwC;AAC/E,MAAK,MAAM,QAAQ,iBAAiB;EAClC,MAAM,SAAS,qBAAqB,KAAK;AACzC,MAAI,UAAU,OAAO,SAAS,GAAG;GAC/B,MAAM,WAAW,OAAO,QAAQ,KAAK,QAAQ,MAAM,KAAK,EAAE,GAAG,OAAO;GAEpE,MAAM,QAAQ;AACd,QAAK,gBAAgB,KAAK,iBAAiB,IAAI,SAAS,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;ACOzE,SAAgB,uBAAuB,EACrC,kBACA,cAIgC;CAGhC,IAAI,kBAAiD,gBAAgB;AAErE,KAAI,oBAAoB,GAAG;AAIzB,MAAI,aAAa,gBAAgB,OAE/B,mBAAkB;AAEpB,oBAAkB,gBAAgB,aAAa;QAC1C;EAIL,IAAI,YAA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Ae;AACjB,SAAO,KAAK,MAAM;;;;;;;;;;;;;;;;;;;;;;;CAwBpB,IAAiB,KAA4B;AAC3C,SAAO,IAAI,KAAK,OAAO,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuC7B,IACE,KACA,OACA,SAKS;AACT,SAAO,YAAY,KAAK,OAAO;GAC7B;GACA;GACA,KAAK,SAAS;GACd,aAAa,SAAS;GACtB,MAAM,SAAS;GAChB,CAAC;;;;;;;;;;;;;;;;;;;CAoBJ,OAAO,KAAsB;AAC3B,SAAO,UAAU,KAAK,OAAO,IAAI;;;;;;;;;;;;;;;;;;;;;;;;CAyBnC,IAAI,KAAsB;AACxB,SAAO,IAAI,KAAK,OAAO,IAAI;;;;;;;;;;;;;;;;;;CAmB7B,QAAc;AAEZ,QAAM,KAAK,MAAM;;;;;;;;;;;;;;;;;;;;;;;;CAyBnB,cAAc,MAAyB,SAAsC;AAC3E,gBAAc,KAAK,OAAO,MAAM,WAAW,EAAE,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/cache/clear.ts","../../src/defaults.ts","../../src/utils/start-monitor.ts","../../src/sweep/batchUpdateExpiredRatio.ts","../../src/sweep/select-instance-to-sweep.ts","../../src/cache/delete.ts","../../src/types.ts","../../src/utils/status-from-tags.ts","../../src/cache/validators.ts","../../src/sweep/sweep-once.ts","../../src/sweep/update-weight.ts","../../src/sweep/sweep.ts","../../src/cache/create-cache.ts","../../src/cache/get.ts","../../src/cache/has.ts","../../src/cache/invalidate-tag.ts","../../src/cache/set.ts","../../src/index.ts"],"sourcesContent":["import type { CacheState } from \"../types\";\n\n/**\n * Clears all entries from the cache without invoking callbacks.\n *\n * @note The `onDelete` callback is NOT invoked during a clear operation.\n * This is intentional to avoid unnecessary overhead when bulk-removing entries.\n *\n * @param state - The cache state.\n * @returns void\n */\nexport const clear = (state: CacheState): void => {\n state.store.clear();\n};\n","// Time Unit Constants\n// Base temporal units used throughout the caching system.\nconst ONE_SECOND: number = 1000;\nconst ONE_MINUTE: number = 60 * ONE_SECOND;\n\n/**\n * ===================================================================\n * Cache Entry Lifecycle\n * Default TTL and stale window settings for short-lived cache entries.\n * ===================================================================\n */\n\n/**\n * Default Time-To-Live in milliseconds for cache entries.\n * @default 1_800_000 (30 minutes)\n */\nexport const DEFAULT_TTL: number = 30 * ONE_MINUTE;\n\n/**\n * Default stale window in milliseconds after expiration.\n * Allows serving slightly outdated data while fetching fresh data.\n */\nexport const DEFAULT_STALE_WINDOW: number = 0 as const;\n\n/**\n * Maximum number of entries the cache can hold.\n * Beyond this limit, new entries are ignored.\n */\nexport const DEFAULT_MAX_SIZE: number = Infinity;\n\n/**\n * Default maximum memory size in MB the cache can use.\n * Beyond this limit, new entries are ignored.\n * @default Infinite (unlimited)\n */\nexport const DEFAULT_MAX_MEMORY_SIZE: number = Infinity;\n\n/**\n * ===================================================================\n * Sweep & Cleanup Operations\n * Parameters controlling how and when expired entries are removed.\n * ===================================================================\n */\n\n/**\n * Maximum number of keys to process in a single sweep batch.\n * Higher values = more aggressive cleanup, lower latency overhead.\n */\nexport const MAX_KEYS_PER_BATCH: number = 1000;\n\n/**\n * Minimal expired ratio enforced during sweeps.\n * Ensures control sweeps run above {@link EXPIRED_RATIO_MEMORY_THRESHOLD}.\n */\nexport const MINIMAL_EXPIRED_RATIO: number = 0.05;\n\n/**\n * Memory usage threshold (normalized 0–1) triggering control sweeps.\n * At or above this level, sweeping becomes more aggressive.\n */\nexport const EXPIRED_RATIO_MEMORY_THRESHOLD: number = 0.8;\n\n/**\n * Maximum allowed expired ratio when memory usage is low.\n * Upper bound for interpolation with MINIMAL_EXPIRED_RATIO.\n * Recommended range: `0.3 – 0.5` .\n */\nexport const DEFAULT_MAX_EXPIRED_RATIO: number = 0.4;\n\n/**\n * ===================================================================\n * Sweep Intervals & Timing\n * Frequency and time budgets for cleanup operations.\n * ===================================================================\n */\n\n/**\n * Optimal interval in milliseconds between sweeps.\n * Used when system load is minimal and metrics are available.\n */\nexport const OPTIMAL_SWEEP_INTERVAL: number = 2 * ONE_SECOND;\n\n/**\n * Worst-case interval in milliseconds between sweeps.\n * Used when system load is high or metrics unavailable.\n */\nexport const WORST_SWEEP_INTERVAL: number = 200;\n\n/**\n * Maximum time budget in milliseconds for sweep operations.\n * Prevents sweeping from consuming excessive CPU during high load.\n */\nexport const WORST_SWEEP_TIME_BUDGET: number = 40;\n\n/**\n * Optimal time budget in milliseconds for each sweep cycle.\n * Used when performance metrics are not available or unreliable.\n */\nexport const OPTIMAL_SWEEP_TIME_BUDGET_IF_NOTE_METRICS_AVAILABLE: number = 15;\n\n/**\n * ===================================================================\n * Memory Management\n * Process limits and memory-safe thresholds.\n * ===================================================================\n */\n\n/**\n * Default maximum process memory limit in megabytes.\n * Acts as fallback when environment detection is unavailable.\n * NOTE: Overridable via environment detection at runtime.\n */\nexport const DEFAULT_MAX_PROCESS_MEMORY_MB: number = 1024;\n\n/**\n * ===================================================================\n * System Utilization Weights\n * Balance how memory, CPU, and event-loop pressure influence sweep behavior.\n * Sum of all weights: 10 + 8.5 + 6.5 = 25\n * ===================================================================\n */\n\n/**\n * Weight applied to memory utilization in sweep calculations.\n * Higher weight = memory pressure has more influence on sweep aggressiveness.\n */\nexport const DEFAULT_MEMORY_WEIGHT: number = 10;\n\n/**\n * Weight applied to CPU utilization in sweep calculations.\n * Combined with event-loop weight to balance CPU-related pressure.\n */\nexport const DEFAULT_CPU_WEIGHT: number = 8.5;\n\n/**\n * Weight applied to event-loop utilization in sweep calculations.\n * Complements CPU weight to assess overall processing capacity.\n */\nexport const DEFAULT_LOOP_WEIGHT: number = 6.5;\n","import { DEFAULT_MAX_PROCESS_MEMORY_MB, WORST_SWEEP_INTERVAL } from \"../defaults\";\n\nimport { getProcessMemoryLimit } from \"./get-process-memory-limit\";\nimport {\n createMonitorObserver,\n type PerformanceMetrics,\n type ReturnCreateMonitor,\n} from \"./process-monitor\";\n\nlet _monitorInstance: ReturnCreateMonitor | null = null;\n\n/** Latest collected metrics from the monitor */\nexport let _metrics: PerformanceMetrics | null;\n\n/** Maximum memory limit for the monitor (in MB) */\nexport let maxMemoryLimit: number = DEFAULT_MAX_PROCESS_MEMORY_MB;\n\n/** Use 90% of the effective limit */\nexport const SAFE_MEMORY_LIMIT_RATIO = 0.9;\n\nexport function startMonitor(): void {\n if (__BROWSER__) {\n // Ignore monitor in browser environments\n return;\n }\n\n if (!_monitorInstance) {\n try {\n const processMemoryLimit = getProcessMemoryLimit();\n\n if (processMemoryLimit && processMemoryLimit > 0) {\n maxMemoryLimit = (processMemoryLimit / 1024 / 1024) * SAFE_MEMORY_LIMIT_RATIO;\n }\n } catch {\n // TODO: proper logger\n // Ignore errors and use default\n // console.log(\"error getProcessMemoryLimit:\", e);\n }\n\n _monitorInstance = createMonitorObserver({\n callback(metrics) {\n _metrics = metrics;\n },\n interval: WORST_SWEEP_INTERVAL,\n maxMemory: maxMemoryLimit, // 1 GB\n });\n\n _monitorInstance.start();\n }\n}\n","import { _instancesCache } from \"../cache/create-cache\";\n\n/**\n * Updates the expired ratio for each cache instance based on the collected ratios.\n * @param currentExpiredRatios - An array of arrays containing expired ratios for each cache instance.\n * @internal\n */\nexport function _batchUpdateExpiredRatio(currentExpiredRatios: number[][]): void {\n for (const inst of _instancesCache) {\n const ratios = currentExpiredRatios[inst._instanceIndexState];\n if (ratios && ratios.length > 0) {\n const avgRatio = ratios.reduce((sum, val) => sum + val, 0) / ratios.length;\n\n const alpha = 0.6; // NOTE: this must be alway higher than 0.5 to prioritize recent avgRatio\n inst._expiredRatio = inst._expiredRatio * (1 - alpha) + avgRatio * alpha;\n }\n }\n}\n","import { _instancesCache } from \"../cache/create-cache\";\nimport type { CacheState } from \"../types\";\n\n/**\n * Selects a cache instance to sweep based on sweep weights or round‑robin order.\n *\n * Two selection modes are supported:\n * - **Round‑robin mode**: If `totalSweepWeight` ≤ 0, instances are selected\n * deterministically in sequence using `batchSweep`. Once all instances\n * have been processed, returns `null`.\n * - **Weighted mode**: If sweep weights are available, performs a probabilistic\n * selection. Each instance’s `_sweepWeight` contributes proportionally to its\n * chance of being chosen.\n *\n * This function depends on `_updateWeightSweep` to maintain accurate sweep weights.\n *\n * @param totalSweepWeight - Sum of all sweep weights across instances.\n * @param batchSweep - Current batch index used for round‑robin selection.\n * @returns The selected `CacheState` instance, `null` if no instance remains,\n * or `undefined` if the cache is empty.\n */\nexport function _selectInstanceToSweep({\n totalSweepWeight,\n batchSweep,\n}: {\n totalSweepWeight: number;\n batchSweep: number;\n}): CacheState | null | undefined {\n // Default selection: initialize with the first instance in the cache list.\n // This acts as a fallback in case no weighted selection occurs.\n let instanceToSweep: CacheState | null | undefined = _instancesCache[0];\n\n if (totalSweepWeight <= 0) {\n // Case 1: No sweep weight assigned (all instances skipped or empty).\n // → Perform a deterministic round‑robin minimal sweep across all instances.\n // Each batch iteration selects the next instance in order.\n if (batchSweep > _instancesCache.length) {\n // If all instances have been processed in this cycle, no instance to sweep.\n instanceToSweep = null;\n }\n instanceToSweep = _instancesCache[batchSweep - 1] as CacheState;\n } else {\n // Case 2: Sweep weights are available.\n // → Perform a probabilistic selection based on relative sweep weights.\n // A random threshold is drawn in [0, totalSweepWeight].\n let threshold = Math.random() * totalSweepWeight;\n\n // Iterate through instances, subtracting each instance’s weight.\n // The first instance that reduces the threshold to ≤ 0 is selected.\n // This ensures that instances with higher weights have proportionally\n // higher probability of being chosen for sweeping.\n for (const inst of _instancesCache) {\n threshold -= inst._sweepWeight;\n if (threshold <= 0) {\n instanceToSweep = inst;\n break;\n }\n }\n }\n\n return instanceToSweep;\n}\n","import type { CacheState } from \"../types\";\n\nexport const enum DELETE_REASON {\n MANUAL = \"manual\",\n EXPIRED = \"expired\",\n STALE = \"stale\",\n}\n\n/**\n * Deletes a key from the cache.\n * @param state - The cache state.\n * @param key - The key.\n * @returns A boolean indicating whether the key was successfully deleted.\n */\nexport const deleteKey = (\n state: CacheState,\n key: string,\n reason: DELETE_REASON = DELETE_REASON.MANUAL,\n): boolean => {\n const onDelete = state.onDelete;\n const onExpire = state.onExpire;\n\n if (!onDelete && !onExpire) {\n return state.store.delete(key);\n }\n\n const entry = state.store.get(key);\n if (!entry) return false;\n\n state.store.delete(key);\n state.onDelete?.(key, entry[1], reason);\n if (reason !== DELETE_REASON.MANUAL) {\n state.onExpire?.(key, entry[1], reason);\n }\n\n return true;\n};\n","import type { DELETE_REASON } from \"./cache/delete\";\n\n/**\n * Base configuration shared between CacheOptions and CacheState.\n */\nexport interface CacheConfigBase {\n /**\n * Callback invoked when a key expires naturally.\n * @param key - The expired key.\n * @param value - The value associated with the expired key.\n * @param reason - The reason for deletion ('expired', or 'stale').\n */\n onExpire?: (\n key: string,\n value: unknown,\n reason: Exclude<DELETE_REASON, DELETE_REASON.MANUAL>,\n ) => void;\n\n /**\n * Callback invoked when a key is deleted, either manually or due to expiration.\n * @param key - The deleted key.\n * @param value - The value of the deleted key.\n * @param reason - The reason for deletion ('manual', 'expired', or 'stale').\n */\n onDelete?: (key: string, value: unknown, reason: DELETE_REASON) => void;\n\n /**\n * Default TTL (Time-To-Live) in milliseconds for entries without explicit TTL.\n * @default 1_800_000 (30 minutes)\n */\n defaultTtl: number;\n\n /**\n * Default stale window in milliseconds for entries that do not\n * specify their own `staleWindowMs`.\n *\n * This window determines how long an entry may continue to be\n * served as stale after it reaches its expiration time.\n *\n * The window is always relative to the entry’s own expiration\n * moment, regardless of whether that expiration comes from an\n * explicit `ttl` or from the cache’s default TTL.\n * @default null (No stale window)\n */\n defaultStaleWindow: number;\n\n /**\n * Maximum number of entries the cache can hold.\n * Beyond this limit, new entries are ignored.\n * @default Infinite (unlimited)\n */\n maxSize: number;\n\n /**\n * Maximum memory size in MB the cache can use.\n * Beyond this limit, new entries are ignored.\n * @default Infinite (unlimited)\n */\n maxMemorySize: number;\n\n /**\n * Controls how stale entries are handled when read from the cache.\n *\n * - true → stale entries are purged immediately after being returned.\n * - false → stale entries are retained after being returned.\n *\n * @default false\n */\n purgeStaleOnGet: boolean;\n\n /**\n * Controls how stale entries are handled during sweep operations.\n *\n * - true → stale entries are purged during sweeps.\n * - false → stale entries are retained during sweeps.\n *\n * @default false\n */\n purgeStaleOnSweep: boolean;\n\n /**\n * Whether to automatically start the sweep process when the cache is created.\n *\n * - true → sweep starts automatically.\n * - false → sweep does not start automatically, allowing manual control.\n *\n * @internal\n * @default true\n */\n _autoStartSweep: boolean;\n\n /**\n * Allowed expired ratio for the cache instance.\n */\n _maxAllowExpiredRatio: number;\n}\n\n/**\n * Public configuration options for the TTL cache.\n */\nexport type CacheOptions = Partial<CacheConfigBase>;\n\n/**\n * Options for `invalidateTag` operation. Kept intentionally extensible so\n * future flags can be added without breaking callers.\n */\nexport interface InvalidateTagOptions {\n /** If true, mark affected entries as stale instead of fully expired. */\n asStale?: boolean;\n\n // Allow additional option fields for forward-compatibility.\n [key: string]: unknown;\n}\n\n/**\n * Lifecycle timestamps stored in a Tuple:\n * - 0 → createdAt\n * - 1 → expiresAt\n * - 2 → staleExpiresAt\n */\nexport type EntryTimestamp = [\n /** createdAt: Absolute timestamp the entry was created (Date.now()). */\n number,\n\n /** expiresAt: Absolute timestamp when the entry becomes invalid (Date.now() + TTL). */\n number,\n\n /** staleExpiresAt: Absolute timestamp when the entry stops being stale (Date.now() + staleTTL). */\n number,\n];\n\n/**\n * Represents a single cache entry.\n */\nexport type CacheEntry = [\n EntryTimestamp,\n\n /** The stored value. */\n unknown,\n\n (\n /**\n * Optional list of tags associated with this entry.\n * Tags can be used for:\n * - Group invalidation (e.g., clearing all entries with a given tag)\n * - Namespacing or categorization\n * - Tracking dependencies\n *\n * If no tags are associated, this field is `null`.\n */\n string[] | null\n ),\n];\n\n/**\n * Status of a cache entry.\n */\nexport enum ENTRY_STATUS {\n /** The entry is fresh and valid. */\n FRESH = \"fresh\",\n /** The entry is stale but can still be served. */\n STALE = \"stale\",\n /** The entry has expired and is no longer valid. */\n EXPIRED = \"expired\",\n}\n\n/**\n * Metadata returned when includeMetadata is enabled in get().\n * Contains complete information about a cache entry including\n * timing, status, and associated tags.\n */\nexport interface EntryMetadata<T = unknown> {\n /** The cached value. */\n data: T;\n\n /** Absolute timestamp when this entry becomes fully expired (in milliseconds). */\n expirationTime: number;\n\n /** Absolute timestamp when the stale window expires (in milliseconds). */\n staleWindowExpiration: number;\n\n /** Current status of the entry (fresh, stale, or expired). */\n status: ENTRY_STATUS;\n\n /** Tags associated with this entry, or null if no tags are set. */\n tags: string[] | null;\n}\n\n/**\n * Internal state of the TTL cache.\n */\nexport interface CacheState extends CacheConfigBase {\n /** Map storing key-value entries. */\n store: Map<string, CacheEntry>;\n\n /** Current size */\n size: number;\n\n /** Iterator for sweeping keys. */\n _sweepIter: MapIterator<[string, CacheEntry]> | null;\n\n /** Index of this instance for sweep all. */\n _instanceIndexState: number;\n\n /** Expire ratio avg for instance */\n _expiredRatio: number;\n\n /** Sweep weight for instance, calculate based on size and _expiredRatio */\n _sweepWeight: number;\n\n /**\n * Tag invalidation state.\n * Each tag stores:\n * - 0 → moment when the tag was marked as expired (0 if never)\n * - 1 → moment when the tag was marked as stale (0 if never)\n *\n * These timestamps define whether a tag affects an entry based on\n * the entry's creation time. */\n _tags: Map<string, [number, number]>;\n}\n","import { ENTRY_STATUS, type CacheEntry, type CacheState } from \"../types\";\n\n/**\n * Computes the derived status of a cache entry based on its associated tags.\n *\n * Tags may impose stricter expiration or stale rules on the entry. Only tags\n * created at or after the entry's creation timestamp are considered relevant.\n *\n * Resolution rules:\n * - If any applicable tag marks the entry as expired, the status becomes `EXPIRED`.\n * - Otherwise, if any applicable tag marks it as stale, the status becomes `STALE`.\n * - If no tag imposes stricter rules, the entry remains `FRESH`.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry whose status is being evaluated.\n * @returns A tuple containing:\n * - The final {@link ENTRY_STATUS} imposed by tags.\n * - The earliest timestamp at which a tag marked the entry as stale\n * (or 0 if no tag imposed a stale rule).\n */\nexport function _statusFromTags(state: CacheState, entry: CacheEntry): [ENTRY_STATUS, number] {\n const entryCreatedAt = entry[0][0];\n\n // Tracks the earliest point in time when any tag marked this entry as stale.\n // Initialized to Infinity so that comparisons always pick the minimum.\n let earliestTagStaleInvalidation = Infinity;\n\n // Default assumption: entry is fresh unless tags override.\n let status = ENTRY_STATUS.FRESH;\n\n const tags = entry[2];\n if (tags) {\n for (const tag of tags) {\n const ts = state._tags.get(tag);\n if (!ts) continue;\n\n // Each tag provides two timestamps:\n // - tagExpiredAt: when the tag forces expiration\n // - tagStaleSinceAt: when the tag forces stale status\n const [tagExpiredAt, tagStaleSinceAt] = ts;\n\n // A tag can only override if it was created after the entry itself.\n if (tagExpiredAt >= entryCreatedAt) {\n status = ENTRY_STATUS.EXPIRED;\n break; // Expired overrides everything, no need to check further.\n }\n\n if (tagStaleSinceAt >= entryCreatedAt) {\n // Keep track of the earliest stale timestamp across all tags.\n if (tagStaleSinceAt < earliestTagStaleInvalidation) {\n earliestTagStaleInvalidation = tagStaleSinceAt;\n }\n status = ENTRY_STATUS.STALE;\n }\n }\n }\n\n // If no tag imposed stale, return 0 for the timestamp.\n return [status, status === ENTRY_STATUS.STALE ? earliestTagStaleInvalidation : 0];\n}\n","import { ENTRY_STATUS, type CacheEntry, type CacheState } from \"../types\";\nimport { _statusFromTags } from \"../utils/status-from-tags\";\n\n/**\n * Computes the final derived status of a cache entry by combining:\n *\n * - The entry's own expiration timestamps (TTL and stale TTL).\n * - Any stricter expiration or stale rules imposed by its associated tags.\n *\n * Precedence rules:\n * - `EXPIRED` overrides everything.\n * - `STALE` overrides `FRESH`.\n * - If neither the entry nor its tags impose stricter rules, the entry is `FRESH`.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry being evaluated.\n * @returns The final {@link ENTRY_STATUS} for the entry.\n */\nexport function computeEntryStatus(\n state: CacheState,\n entry: CacheEntry,\n\n /** @internal */\n now: number,\n): ENTRY_STATUS {\n const [__createdAt, expiresAt, staleExpiresAt] = entry[0];\n\n // 1. Status derived from tags\n const [tagStatus, earliestTagStaleInvalidation] = _statusFromTags(state, entry);\n if (tagStatus === ENTRY_STATUS.EXPIRED) return ENTRY_STATUS.EXPIRED;\n const windowStale = staleExpiresAt - expiresAt;\n if (\n tagStatus === ENTRY_STATUS.STALE &&\n staleExpiresAt > 0 &&\n now < earliestTagStaleInvalidation + windowStale\n ) {\n // A tag can mark the entry as stale only if the entry itself supports a stale window.\n // The tag's stale invalidation time is extended by the entry's stale window duration.\n // If \"now\" is still within that extended window, the entry is considered stale.\n return ENTRY_STATUS.STALE;\n }\n\n // 2. Status derived from entry timestamps\n if (now < expiresAt) {\n return ENTRY_STATUS.FRESH;\n }\n if (staleExpiresAt > 0 && now < staleExpiresAt) {\n return ENTRY_STATUS.STALE;\n }\n\n return ENTRY_STATUS.EXPIRED;\n}\n\n// ---------------------------------------------------------------------------\n// Entry status wrappers (semantic helpers built on top of computeEntryStatus)\n// ---------------------------------------------------------------------------\n/**\n * Determines whether a cache entry is fresh.\n *\n * A fresh entry is one whose final derived status is `FRESH`, meaning:\n * - It has not expired according to its own timestamps, and\n * - No associated tag imposes a stricter stale or expired rule.\n *\n * `entry` can be either a {@link CacheEntry} or a pre-computed {@link ENTRY_STATUS}.\n * Passing a pre-computed status avoids recalculating the entry status.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry or pre-computed status being evaluated.\n * @param now - The current timestamp.\n * @returns True if the entry is fresh.\n */\nexport const isFresh = (\n state: CacheState,\n entry: CacheEntry | ENTRY_STATUS,\n now: number,\n): boolean => {\n if (typeof entry === \"string\") {\n // If entry is already a pre-computed status (from tags), it's fresh only if that status is FRESH.\n return entry === ENTRY_STATUS.FRESH;\n }\n\n return computeEntryStatus(state, entry, now) === ENTRY_STATUS.FRESH;\n};\n/**\n * Determines whether a cache entry is stale.\n *\n * A stale entry is one whose final derived status is `STALE`, meaning:\n * - It has passed its TTL but is still within its stale window, or\n * - A tag imposes a stale rule that applies to this entry.\n *\n * `entry` can be either a {@link CacheEntry} or a pre-computed {@link ENTRY_STATUS}.\n * Passing a pre-computed status avoids recalculating the entry status.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry or pre-computed status being evaluated.\n * @param now - The current timestamp.\n * @returns True if the entry is stale.\n */\nexport const isStale = (\n state: CacheState,\n entry: CacheEntry | ENTRY_STATUS,\n\n /** @internal */\n now: number,\n): boolean => {\n if (typeof entry === \"string\") {\n // If entry is already a pre-computed status (from tags), it's stale only if that status is STALE.\n return entry === ENTRY_STATUS.STALE;\n }\n\n return computeEntryStatus(state, entry, now) === ENTRY_STATUS.STALE;\n};\n\n/**\n * Determines whether a cache entry is expired.\n *\n * An expired entry is one whose final derived status is `EXPIRED`, meaning:\n * - It has exceeded both its TTL and stale TTL, or\n * - A tag imposes an expiration rule that applies to this entry.\n *\n * `entry` can be either a {@link CacheEntry} or a pre-computed {@link ENTRY_STATUS}.\n * Passing a pre-computed status avoids recalculating the entry status.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry or pre-computed status being evaluated.\n * @param now - The current timestamp.\n * @returns True if the entry is expired.\n */\nexport const isExpired = (\n state: CacheState,\n entry: CacheEntry | ENTRY_STATUS,\n\n /** @internal */\n now: number,\n): boolean => {\n if (typeof entry === \"string\") {\n // If entry is already a pre-computed status (from tags), it's expired only if that status is EXPIRED.\n return entry === ENTRY_STATUS.EXPIRED;\n }\n\n return computeEntryStatus(state, entry, now) === ENTRY_STATUS.EXPIRED;\n};\n\n/**\n * Determines whether a cache entry is valid.\n *\n * A valid entry is one whose final derived status is either:\n * - `FRESH`, or\n * - `STALE` (still within its stale window).\n *\n * Expired entries are considered invalid.\n *\n * `entry` can be either a {@link CacheEntry} or a pre-computed {@link ENTRY_STATUS},\n * or undefined/null if the entry was not found. Passing a pre-computed status avoids\n * recalculating the entry status.\n *\n * @param state - The cache state containing tag metadata.\n * @param entry - The cache entry, pre-computed status, or undefined/null if not found.\n * @param now - The current timestamp (defaults to {@link Date.now}).\n * @returns True if the entry exists and is fresh or stale.\n */\nexport const isValid = (\n state: CacheState,\n entry?: CacheEntry | ENTRY_STATUS | null,\n\n /** @internal */\n now: number = Date.now(),\n): boolean => {\n if (!entry) return false;\n if (typeof entry === \"string\") {\n // If entry is already a pre-computed status (from tags), it's valid if it's FRESH or STALE.\n return entry === ENTRY_STATUS.FRESH || entry === ENTRY_STATUS.STALE;\n }\n\n const status = computeEntryStatus(state, entry, now);\n return status === ENTRY_STATUS.FRESH || status === ENTRY_STATUS.STALE;\n};\n","import { DELETE_REASON, deleteKey } from \"../cache/delete\";\nimport { computeEntryStatus, isExpired, isStale } from \"../cache/validators\";\nimport { MAX_KEYS_PER_BATCH } from \"../defaults\";\nimport { type CacheState } from \"../types\";\n\n/**\n * Performs a single sweep operation on the cache to remove expired and optionally stale entries.\n * Uses a linear scan with a saved pointer to resume from the last processed key.\n * @param state - The cache state.\n * @param _maxKeysPerBatch - Maximum number of keys to process in this sweep.\n * @returns An object containing statistics about the sweep operation.\n */\nexport function _sweepOnce(\n state: CacheState,\n\n /**\n * Maximum number of keys to process in this sweep.\n * @default 1000\n */\n _maxKeysPerBatch: number = MAX_KEYS_PER_BATCH,\n): { processed: number; expiredCount: number; staleCount: number; ratio: number } {\n if (!state._sweepIter) {\n state._sweepIter = state.store.entries();\n }\n\n let processed = 0;\n let expiredCount = 0;\n let staleCount = 0;\n\n for (let i = 0; i < _maxKeysPerBatch; i++) {\n const next = state._sweepIter.next();\n\n if (next.done) {\n state._sweepIter = state.store.entries();\n break;\n }\n\n processed += 1;\n const [key, entry] = next.value;\n\n const now = Date.now();\n\n const status = computeEntryStatus(state, entry, now);\n if (isExpired(state, status, now)) {\n deleteKey(state, key, DELETE_REASON.EXPIRED);\n expiredCount += 1;\n } else if (isStale(state, status, now)) {\n staleCount += 1;\n\n if (state.purgeStaleOnSweep) {\n deleteKey(state, key, DELETE_REASON.STALE);\n }\n }\n }\n\n const expiredStaleCount = state.purgeStaleOnSweep ? staleCount : 0;\n return {\n processed,\n expiredCount,\n staleCount,\n ratio: processed > 0 ? (expiredCount + expiredStaleCount) / processed : 0,\n };\n}\n","import { _instancesCache } from \"../cache/create-cache\";\nimport { MINIMAL_EXPIRED_RATIO } from \"../defaults\";\n\nimport { calculateOptimalMaxExpiredRatio } from \"./calculate-optimal-max-expired-ratio\";\n\n/**\n * Updates the sweep weight (`_sweepWeight`) for each cache instance.\n *\n * The sweep weight determines the probability that an instance will be selected\n * for a cleanup (sweep) process. It is calculated based on the store size and\n * the ratio of expired keys.\n *\n * This function complements (`_selectInstanceToSweep`), which is responsible\n * for selecting the correct instance based on the weights assigned here.\n *\n * ---\n *\n * ### Sweep systems:\n * 1. **Normal sweep**\n * - Runs whenever the percentage of expired keys exceeds the allowed threshold\n * calculated by `calculateOptimalMaxExpiredRatio`.\n * - It is the main cleanup mechanism and is applied proportionally to the\n * store size and the expired‑key ratio.\n *\n * 2. **Memory‑conditioned sweep (control)**\n * - Works exactly like the normal sweep, except it may run even when it\n * normally wouldn’t.\n * - Only activates under **high memory pressure**.\n * - Serves as an additional control mechanism to adjust weights, keep the\n * system updated, and help prevent memory overflows.\n *\n * 3. **Round‑robin sweep (minimal control)**\n * - Always runs, even if the expired ratio is low or memory usage does not\n * require it.\n * - Processes a very small number of keys per instance, much smaller than\n * the normal sweep.\n * - Its main purpose is to ensure that all instances receive at least a\n * periodic weight update and minimal expired‑key control.\n *\n * ---\n * #### Important notes:\n * - A minimum `MINIMAL_EXPIRED_RATIO` (e.g., 5%) is assumed to ensure that\n * control sweeps can always run under high‑memory scenarios.\n * - Even with a minimum ratio, the normal sweep and the memory‑conditioned sweep\n * may **skip execution** if memory usage allows it and the expired ratio is\n * below the optimal maximum.\n * - The round‑robin sweep is never skipped: it always runs with a very small,\n * almost imperceptible cost.\n *\n * @returns The total accumulated sweep weight across all cache instances.\n */\nexport function _updateWeightSweep(): number {\n let totalSweepWeight = 0;\n\n for (const instCache of _instancesCache) {\n if (instCache.store.size <= 0) {\n // Empty instance → no sweep weight needed, skip sweep for this instance.\n instCache._sweepWeight = 0;\n continue;\n }\n\n // Ensure a minimum expired ratio to allow control sweeps.\n // If the real ratio is higher than the minimum, use the real ratio.\n let expiredRatio = MINIMAL_EXPIRED_RATIO;\n if (instCache._expiredRatio > MINIMAL_EXPIRED_RATIO) {\n expiredRatio = instCache._expiredRatio;\n }\n\n if (!__BROWSER__) {\n // In non‑browser environments, compute an optimal maximum allowed ratio.\n const optimalMaxExpiredRatio = calculateOptimalMaxExpiredRatio(\n instCache._maxAllowExpiredRatio,\n );\n\n if (expiredRatio <= optimalMaxExpiredRatio) {\n // If memory usage allows it and the expired ratio is low,\n // this sweep can be skipped. The reduced round‑robin sweep will still run.\n instCache._sweepWeight = 0;\n continue;\n }\n }\n\n // Normal sweep: weight proportional to store size and expired ratio.\n instCache._sweepWeight = instCache.store.size * expiredRatio;\n totalSweepWeight += instCache._sweepWeight;\n }\n\n return totalSweepWeight;\n}\n","import { _instancesCache } from \"../cache/create-cache\";\nimport {\n MAX_KEYS_PER_BATCH,\n OPTIMAL_SWEEP_INTERVAL,\n OPTIMAL_SWEEP_TIME_BUDGET_IF_NOTE_METRICS_AVAILABLE,\n} from \"../defaults\";\nimport type { CacheState } from \"../types\";\nimport { _metrics } from \"../utils/start-monitor\";\n\nimport { _batchUpdateExpiredRatio } from \"./batchUpdateExpiredRatio\";\nimport { calculateOptimalSweepParams } from \"./calculate-optimal-sweep-params\";\nimport { _selectInstanceToSweep } from \"./select-instance-to-sweep\";\nimport { _sweepOnce } from \"./sweep-once\";\nimport { _updateWeightSweep } from \"./update-weight\";\n\n/**\n * Performs a sweep operation on the cache to remove expired and optionally stale entries.\n * Uses a linear scan with a saved pointer to resume from the last processed key.\n * @param state - The cache state.\n */\nexport const sweep = async (\n state: CacheState,\n\n /** @internal */\n utilities: SweepUtilities = {},\n): Promise<void> => {\n const {\n schedule = defaultSchedule,\n yieldFn = defaultYieldFn,\n now = Date.now(),\n runOnlyOne = false,\n } = utilities;\n const startTime = now;\n\n let sweepIntervalMs = OPTIMAL_SWEEP_INTERVAL;\n let sweepTimeBudgetMs = OPTIMAL_SWEEP_TIME_BUDGET_IF_NOTE_METRICS_AVAILABLE;\n if (!__BROWSER__ && _metrics) {\n ({ sweepIntervalMs, sweepTimeBudgetMs } = calculateOptimalSweepParams({ metrics: _metrics }));\n }\n\n const totalSweepWeight = _updateWeightSweep();\n const currentExpiredRatios: number[][] = [];\n\n // Reduce the maximum number of keys per batch only when no instance weights are available\n // and the sweep is running in minimal round‑robin control mode. In this case, execute the\n // smallest possible sweep (equivalent to one batch, but divided across instances).\n const maxKeysPerBatch =\n totalSweepWeight <= 0 ? MAX_KEYS_PER_BATCH / _instancesCache.length : MAX_KEYS_PER_BATCH;\n\n let batchSweep = 0;\n while (true) {\n batchSweep += 1;\n\n const instanceToSweep = _selectInstanceToSweep({ batchSweep, totalSweepWeight });\n if (!instanceToSweep) {\n // No instance to sweep\n break;\n }\n\n const { ratio } = _sweepOnce(instanceToSweep, maxKeysPerBatch);\n // Initialize or update `currentExpiredRatios` array for current ratios\n (currentExpiredRatios[instanceToSweep._instanceIndexState] ??= []).push(ratio);\n\n if (Date.now() - startTime > sweepTimeBudgetMs) {\n break;\n }\n\n await yieldFn();\n }\n\n _batchUpdateExpiredRatio(currentExpiredRatios);\n\n // Schedule next sweep\n if (!runOnlyOne) {\n schedule(() => void sweep(state, utilities), sweepIntervalMs);\n }\n};\n\n// Default utilities for scheduling and yielding --------------------------------\nconst defaultSchedule: scheduleType = (fn, ms) => {\n const t = setTimeout(fn, ms);\n if (typeof t.unref === \"function\") t.unref();\n};\nexport const defaultYieldFn: yieldFnType = () => new Promise(resolve => setImmediate(resolve));\n\n// Types for internal utilities -----------------------------------------------\ntype scheduleType = (fn: () => void, ms: number) => void;\ntype yieldFnType = () => Promise<void>;\ninterface SweepUtilities {\n /**\n * Default scheduling function using setTimeout.\n * This can be overridden for testing.\n * @internal\n */\n schedule?: scheduleType;\n\n /**\n * Default yielding function using setImmediate.\n * This can be overridden for testing.\n * @internal\n */\n yieldFn?: yieldFnType;\n\n /** Current timestamp for testing purposes. */\n now?: number;\n\n /**\n * If true, only run one sweep cycle.\n * @internal\n */\n runOnlyOne?: boolean;\n}\n","import {\n DEFAULT_MAX_EXPIRED_RATIO,\n DEFAULT_MAX_MEMORY_SIZE,\n DEFAULT_MAX_SIZE,\n DEFAULT_STALE_WINDOW,\n DEFAULT_TTL,\n} from \"../defaults\";\nimport { sweep } from \"../sweep/sweep\";\nimport type { CacheOptions, CacheState } from \"../types\";\nimport { startMonitor } from \"../utils/start-monitor\";\n\nlet _instanceCount = 0;\nconst INSTANCE_WARNING_THRESHOLD = 99;\nexport const _instancesCache: CacheState[] = [];\n\n/**\n * Resets the instance count for testing purposes.\n * This function is intended for use in tests to avoid instance limits.\n */\nexport const _resetInstanceCount = (): void => {\n _instanceCount = 0;\n};\n\nlet _initSweepScheduled = false;\n\n/**\n * Creates the initial state for the TTL cache.\n * @param options - Configuration options for the cache.\n * @returns The initial cache state.\n */\nexport const createCache = (options: CacheOptions = {}): CacheState => {\n const {\n onExpire,\n onDelete,\n defaultTtl = DEFAULT_TTL,\n maxSize = DEFAULT_MAX_SIZE,\n maxMemorySize = DEFAULT_MAX_MEMORY_SIZE,\n _maxAllowExpiredRatio = DEFAULT_MAX_EXPIRED_RATIO,\n defaultStaleWindow = DEFAULT_STALE_WINDOW,\n purgeStaleOnGet = false,\n purgeStaleOnSweep = false,\n _autoStartSweep = true,\n } = options;\n\n _instanceCount++;\n\n // NEXT: warn if internal parameters are touch by user\n\n if (_instanceCount > INSTANCE_WARNING_THRESHOLD) {\n // NEXT: Use a proper logging mechanism\n // NEXT: Create documentation for this\n console.warn(\n `Too many instances detected (${_instanceCount}). This may indicate a configuration issue; consider minimizing instance creation or grouping keys by expected expiration ranges. See the documentation: https://github.com/neezco/cache/docs/getting-started.md`,\n );\n }\n\n const state: CacheState = {\n store: new Map(),\n _sweepIter: null,\n get size() {\n return state.store.size;\n },\n onExpire,\n onDelete,\n maxSize,\n maxMemorySize,\n defaultTtl,\n defaultStaleWindow,\n purgeStaleOnGet,\n purgeStaleOnSweep,\n _maxAllowExpiredRatio,\n _autoStartSweep,\n _instanceIndexState: -1,\n _expiredRatio: 0,\n _sweepWeight: 0,\n _tags: new Map(),\n };\n\n state._instanceIndexState = _instancesCache.push(state) - 1;\n\n // Start the sweep process\n if (_autoStartSweep) {\n if (_initSweepScheduled) return state;\n _initSweepScheduled = true;\n void sweep(state);\n }\n\n startMonitor();\n\n return state;\n};\n","import type { CacheEntry, CacheState, ENTRY_STATUS } from \"../types\";\n\nimport { DELETE_REASON, deleteKey } from \"./delete\";\nimport { computeEntryStatus, isFresh, isStale } from \"./validators\";\n\n/**\n * Internal function that retrieves a value from the cache with its status information.\n * Returns a tuple containing the entry status and the complete cache entry.\n *\n * @param state - The cache state.\n * @param key - The key to retrieve.\n * @param now - Optional timestamp override (defaults to Date.now()).\n * @returns A tuple of [status, entry] if the entry is valid, or [null, undefined] if not found or expired.\n *\n * @internal\n */\nexport const getWithStatus = (\n state: CacheState,\n key: string,\n now: number = Date.now(),\n): [ENTRY_STATUS | null, CacheEntry | undefined] => {\n const entry = state.store.get(key);\n\n if (!entry) return [null, undefined];\n\n const status = computeEntryStatus(state, entry, now);\n\n if (isFresh(state, status, now)) return [status, entry];\n\n if (isStale(state, status, now)) {\n if (state.purgeStaleOnGet) {\n deleteKey(state, key, DELETE_REASON.STALE);\n }\n return [status, entry];\n }\n\n // If it expired, always delete it\n deleteKey(state, key, DELETE_REASON.EXPIRED);\n\n return [status, undefined];\n};\n\n/**\n * Retrieves a value from the cache if the entry is valid.\n * @param state - The cache state.\n * @param key - The key to retrieve.\n * @param now - Optional timestamp override (defaults to Date.now()).\n * @returns The cached value if valid, undefined otherwise.\n *\n * @internal\n */\nexport const get = (state: CacheState, key: string, now: number = Date.now()): unknown => {\n const [, entry] = getWithStatus(state, key, now);\n return entry ? entry[1] : undefined;\n};\n","import type { CacheState } from \"../types\";\n\nimport { get } from \"./get\";\n\n/**\n * Checks if a key exists in the cache and is not expired.\n * @param state - The cache state.\n * @param key - The key to check.\n * @param now - Optional timestamp override (defaults to Date.now()).\n * @returns True if the key exists and is valid, false otherwise.\n */\nexport const has = (state: CacheState, key: string, now: number = Date.now()): boolean => {\n return get(state, key, now) !== undefined;\n};\n","import type { CacheState, InvalidateTagOptions } from \"../types\";\n\n/**\n * Invalidates one or more tags so that entries associated with them\n * become expired or stale from this moment onward.\n *\n * Semantics:\n * - Each tag maintains two timestamps in `state._tags`:\n * [expiredAt, staleSinceAt].\n * - Calling this function updates one of those timestamps to `_now`,\n * depending on whether the tag should force expiration or staleness.\n *\n * Rules:\n * - If `asStale` is false (default), the tag forces expiration:\n * entries created before `_now` will be considered expired.\n * - If `asStale` is true, the tag forces staleness:\n * entries created before `_now` will be considered stale,\n * but only if they support a stale window.\n *\n * Behavior:\n * - Each call replaces any previous invalidation timestamp for the tag.\n * - Entries created after `_now` are unaffected.\n *\n * @param state - The cache state containing tag metadata.\n * @param tags - A tag or list of tags to invalidate.\n * @param options.asStale - Whether the tag should mark entries as stale.\n */\nexport function invalidateTag(\n state: CacheState,\n tags: string | string[],\n options: InvalidateTagOptions = {},\n\n /** @internal */\n _now: number = Date.now(),\n): void {\n const tagList = Array.isArray(tags) ? tags : [tags];\n const asStale = options.asStale ?? false;\n\n for (const tag of tagList) {\n const currentTag = state._tags.get(tag);\n\n if (currentTag) {\n // Update existing tag timestamps:\n // index 0 = expiredAt, index 1 = staleSinceAt\n if (asStale) {\n currentTag[1] = _now;\n } else {\n currentTag[0] = _now;\n }\n } else {\n // Initialize new tag entry with appropriate timestamp.\n // If marking as stale, expiredAt = 0 and staleSinceAt = _now.\n // If marking as expired, expiredAt = _now and staleSinceAt = 0.\n state._tags.set(tag, [asStale ? 0 : _now, asStale ? _now : 0]);\n }\n }\n}\n","import type { CacheState, CacheEntry } from \"../types\";\nimport { _metrics } from \"../utils/start-monitor\";\n\n/**\n * Sets or updates a value in the cache with TTL and an optional stale window.\n *\n * @param state - The cache state.\n * @param input - Cache entry definition (key, value, ttl, staleWindow, tags).\n * @param now - Optional timestamp override used as the base time (defaults to Date.now()).\n * @returns True if the entry was created or updated, false if rejected due to limits or invalid input.\n *\n * @remarks\n * - `ttl` defines when the entry becomes expired.\n * - `staleWindow` defines how long the entry may still be served as stale\n * after the expiration moment (`now + ttl`).\n * - Returns false if value is `undefined` (entry ignored, existing value untouched).\n * - Returns false if new entry would exceed `maxSize` limit (existing keys always allowed).\n * - Returns false if new entry would exceed `maxMemorySize` limit (existing keys always allowed).\n * - Returns true if entry was set or updated (or if existing key was updated at limit).\n */\nexport const setOrUpdate = (\n state: CacheState,\n input: CacheSetOrUpdateInput,\n\n /** @internal */\n now: number = Date.now(),\n): boolean => {\n const { key, value, ttl: ttlInput, staleWindow: staleWindowInput, tags } = input;\n\n if (value === undefined) return false; // Ignore undefined values, leaving existing entry intact if it exists\n if (key == null) throw new Error(\"Missing key.\");\n if (state.size >= state.maxSize && !state.store.has(key)) {\n // Ignore new entries when max size is reached, but allow updates to existing keys\n return false;\n }\n if (\n !__BROWSER__ &&\n _metrics?.memory.total.rss &&\n _metrics?.memory.total.rss >= state.maxMemorySize * 1024 * 1024 &&\n !state.store.has(key)\n ) {\n // Ignore new entries when max memory size is reached, but allow updates to existing keys\n return false;\n }\n\n const ttl = ttlInput ?? state.defaultTtl;\n const staleWindow = staleWindowInput ?? state.defaultStaleWindow;\n\n const expiresAt = ttl > 0 ? now + ttl : Infinity;\n const entry: CacheEntry = [\n [\n now, // createdAt\n expiresAt, // expiresAt\n staleWindow > 0 ? expiresAt + staleWindow : 0, // staleExpiresAt (relative to expiration)\n ],\n value,\n typeof tags === \"string\" ? [tags] : Array.isArray(tags) ? tags : null,\n ];\n\n state.store.set(key, entry);\n return true;\n};\n\n/**\n * Input parameters for setting or updating a cache entry.\n */\nexport interface CacheSetOrUpdateInput {\n /**\n * Key under which the value will be stored.\n */\n key: string;\n\n /**\n * Value to be written to the cache.\n *\n * Considerations:\n * - Always overwrites any previous value, if one exists.\n * - `undefined` is ignored, leaving any previous value intact, if one exists.\n * - `null` is explicitly stored as a null value, replacing any previous value, if one exists.\n */\n value: unknown;\n\n /**\n * TTL (Time-To-Live) in milliseconds for this entry.\n */\n ttl?: number;\n\n /**\n * Optional stale window in milliseconds.\n *\n * Defines how long the entry may continue to be served as stale\n * after it has reached its expiration time.\n *\n * The window is always relative to the entry’s own expiration moment,\n * whether that expiration comes from an explicit `ttl` or from the\n * cache’s default TTL.\n *\n * If omitted, the cache-level default stale window is used.\n */\n staleWindow?: number;\n\n /**\n * Optional tags associated with this entry.\n */\n tags?: string | string[];\n}\n","import { clear } from \"./cache/clear\";\nimport { createCache } from \"./cache/create-cache\";\nimport { deleteKey } from \"./cache/delete\";\nimport { get, getWithStatus } from \"./cache/get\";\nimport { has } from \"./cache/has\";\nimport { invalidateTag } from \"./cache/invalidate-tag\";\nimport { setOrUpdate } from \"./cache/set\";\nimport type { CacheOptions, CacheState, EntryMetadata, InvalidateTagOptions } from \"./types\";\n\nexport type { CacheOptions, InvalidateTagOptions, EntryMetadata } from \"./types\";\n\n/**\n * A TTL (Time-To-Live) cache implementation with support for expiration,\n * stale windows, tag-based invalidation, and automatic sweeping.\n *\n * Provides O(1) constant-time operations for all core methods.\n *\n * @example\n * ```typescript\n * const cache = new LocalTtlCache();\n * cache.set(\"user:123\", { name: \"Alice\" }, { ttl: 5 * 60 * 1000 });\n * const user = cache.get(\"user:123\"); // { name: \"Alice\" }\n * ```\n */\nexport class LocalTtlCache {\n private state: CacheState;\n\n /**\n * Creates a new cache instance.\n *\n * @param options - Configuration options for the cache (defaultTtl, defaultStaleWindow, maxSize, etc.)\n *\n * @example\n * ```typescript\n * const cache = new LocalTtlCache({\n * defaultTtl: 30 * 60 * 1000, // 30 minutes\n * defaultStaleWindow: 5 * 60 * 1000, // 5 minutes\n * maxSize: 500_000, // Maximum 500_000 entries\n * onExpire: (key, value) => console.log(`Expired: ${key}`),\n * onDelete: (key, value, reason) => console.log(`Deleted: ${key}, reason: ${reason}`),\n * });\n * ```\n */\n constructor(options?: CacheOptions) {\n this.state = createCache(options);\n }\n\n /**\n * Gets the current number of entries tracked by the cache.\n *\n * This value may include entries that are already expired but have not yet been\n * removed by the lazy cleanup system. Expired keys are cleaned only when it is\n * efficient to do so, so the count can temporarily be higher than the number of\n * actually valid (non‑expired) entries.\n *\n * @returns The number of entries currently stored (including entries pending cleanup)\n *\n * @example\n * ```typescript\n * console.log(cache.size); // e.g., 42\n * ```\n */\n get size(): number {\n return this.state.size;\n }\n\n /**\n * Retrieves a value from the cache.\n *\n * Returns the value if it exists and is not fully expired. If an entry is in the\n * stale window (expired but still within staleWindow), the stale value is returned.\n *\n * @param key - The key to retrieve\n * @param options - Optional configuration object\n * @param options.includeMetadata - If true, returns entry metadata (data, status, expirationTime, staleWindowExpiration, tags). Defaults to false\n * @returns The cached value, or entry metadata if includeMetadata is true. Returns undefined if not found or expired\n *\n * @example\n * ```typescript\n * // Get value\n * const user = cache.get(\"user:123\");\n *\n * // Get with metadata\n * const entry = cache.get(\"user:123\", { includeMetadata: true });\n * if (entry) {\n * console.log(entry.data);\n * console.log(entry.status);\n * }\n * ```\n */\n get<T = unknown>(key: string): T | undefined;\n get<T = unknown>(key: string, options: { includeMetadata: true }): EntryMetadata<T> | undefined;\n get<T = unknown>(key: string, options: { includeMetadata: false }): T | undefined;\n get<T = unknown>(\n key: string,\n options?: { includeMetadata?: boolean },\n ): T | undefined | EntryMetadata<T> {\n if (options?.includeMetadata) {\n const [status, entry] = getWithStatus(this.state, key);\n if (!entry) return undefined;\n\n const [timestamps, value, tags] = entry;\n const [, expiresAt, staleExpiresAt] = timestamps;\n\n return {\n data: value as T,\n expirationTime: expiresAt,\n staleWindowExpiration: staleExpiresAt,\n status,\n tags,\n } as EntryMetadata<T>;\n }\n\n return get(this.state, key) as T | undefined;\n }\n\n /**\n * Sets or updates a value in the cache.\n *\n * If the key already exists, it will be completely replaced.\n *\n * @param key - The key under which to store the value\n * @param value - The value to cache (any type)\n * @param options - Optional configuration for this specific entry\n * @param options.ttl - Time-To-Live in milliseconds. Defaults to `defaultTtl`\n * @param options.staleWindow - How long to serve stale data after expiration (milliseconds)\n * @param options.tags - One or more tags for group invalidation\n * @returns True if the entry was set or updated, false if rejected due to limits or invalid input\n *\n * @example\n * ```typescript\n * const success = cache.set(\"user:123\", { name: \"Alice\" }, {\n * ttl: 5 * 60 * 1000,\n * staleWindow: 1 * 60 * 1000,\n * tags: \"user:123\",\n * });\n *\n * if (!success) {\n * console.log(\"Entry was rejected due to size or memory limits\");\n * }\n * ```\n *\n * @edge-cases\n * - Overwriting an existing key replaces it completely\n * - If `ttl` is 0 or Infinite, the entry never expires\n * - If `staleWindow` is larger than `ttl`, the entry can be served as stale longer than it was fresh\n * - Tags are optional; only necessary for group invalidation via `invalidateTag()`\n * - Returns `false` if value is `undefined` (existing value remains untouched)\n * - Returns `false` if new key would exceed [`maxSize`](./docs/configuration.md#maxsize-number) limit\n * - Returns `false` if new key would exceed [`maxMemorySize`](./docs/configuration.md#maxmemorysize-number) limit\n * - Updating existing keys always succeeds, even at limit\n */\n set(\n key: string,\n value: unknown,\n options?: {\n ttl?: number;\n staleWindow?: number;\n tags?: string | string[];\n },\n ): boolean {\n return setOrUpdate(this.state, {\n key,\n value,\n ttl: options?.ttl,\n staleWindow: options?.staleWindow,\n tags: options?.tags,\n });\n }\n\n /**\n * Deletes a specific key from the cache.\n *\n * @param key - The key to delete\n * @returns True if the key was deleted, false if it didn't exist\n *\n * @example\n * ```typescript\n * const wasDeleted = cache.delete(\"user:123\");\n * ```\n *\n * @edge-cases\n * - Triggers the `onDelete` callback with reason `'manual'`\n * - Does not trigger the `onExpire` callback\n * - Returns `false` if the key was already expired\n * - Deleting a non-existent key returns `false` without error\n */\n delete(key: string): boolean {\n return deleteKey(this.state, key);\n }\n\n /**\n * Checks if a key exists in the cache and is not fully expired.\n *\n * Returns true if the key exists and is either fresh or within the stale window.\n * Use this when you only need to check existence without retrieving the value.\n *\n * @param key - The key to check\n * @returns True if the key exists and is valid, false otherwise\n *\n * @example\n * ```typescript\n * if (cache.has(\"user:123\")) {\n * // Key exists (either fresh or stale)\n * }\n * ```\n *\n * @edge-cases\n * - Returns `false` if the key doesn't exist\n * - Returns `false` if the key has expired beyond the stale window\n * - Returns `true` if the key is in the stale window (still being served)\n * - Both `has()` and `get()` have O(1) complexity; prefer `get()` if you need the value\n */\n has(key: string): boolean {\n return has(this.state, key);\n }\n\n /**\n * Removes all entries from the cache at once.\n *\n * This is useful for resetting the cache or freeing memory when needed.\n * The `onDelete` callback is NOT invoked during clear (intentional optimization).\n *\n * @example\n * ```typescript\n * cache.clear(); // cache.size is now 0\n * ```\n *\n * @edge-cases\n * - The `onDelete` callback is NOT triggered during clear\n * - Clears both expired and fresh entries\n * - Resets `cache.size` to 0\n */\n clear(): void {\n // NEXT: optional supor for onClear callback?\n clear(this.state);\n }\n\n /**\n * Marks all entries with one or more tags as expired (or stale, if requested).\n *\n * If an entry has multiple tags, invalidating ANY of those tags will invalidate the entry.\n *\n * @param tags - A single tag (string) or array of tags to invalidate\n * @param asStale - If true, marks entries as stale instead of fully expired (still served from stale window)\n *\n * @example\n * ```typescript\n * // Invalidate a single tag\n * cache.invalidateTag(\"user:123\");\n *\n * // Invalidate multiple tags\n * cache.invalidateTag([\"user:123\", \"posts:456\"]);\n * ```\n *\n * @edge-cases\n * - Does not throw errors if a tag has no associated entries\n * - Invalidating a tag doesn't prevent new entries from being tagged with it later\n * - The `onDelete` callback is triggered with reason `'expired'` (even if `asStale` is true)\n */\n invalidateTag(tags: string | string[], options?: InvalidateTagOptions): void {\n invalidateTag(this.state, tags, options ?? {});\n }\n}\n"],"mappings":";;;;;;;;;;AAWA,MAAa,SAAS,UAA4B;AAChD,OAAM,MAAM,OAAO;;;;;ACVrB,MAAM,aAAqB;AAC3B,MAAM,aAAqB,KAAK;;;;;;;;;;;AAahC,MAAa,cAAsB,KAAK;;;;;AAMxC,MAAa,uBA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