@oxog/cachekeeper 1.0.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.
@@ -0,0 +1,35 @@
1
+ import { C as CacheConfig, a as CacheInstance } from './types-B0XHVTZf.js';
2
+ export { B as BatchSetEntry, t as CacheDump, d as CacheEntry, m as CacheEvent, n as CacheEventHandler, o as CacheEventMap, q as CacheNamespace, r as CachePlugin, p as CacheStats, b as CacheStrategy, l as ClearEvent, c as CustomStrategy, D as DeleteEvent, i as DeleteReason, k as EvictEvent, E as EvictionContext, j as ExpireEvent, G as GetOrSetOptions, H as HitEvent, s as MemoizeOptions, M as MissEvent, P as PruneEvent, f as Serializer, h as SetEvent, g as SetOptions, e as StorageAdapter, S as StorageType, U as Unsubscribe } from './types-B0XHVTZf.js';
3
+
4
+ /**
5
+ * Creates a new cache instance
6
+ */
7
+ declare function createCache<T = unknown>(config?: CacheConfig<T>): CacheInstance<T>;
8
+
9
+ /**
10
+ * Estimates the memory size of a value in bytes
11
+ */
12
+ declare function estimateSize(value: unknown): number;
13
+ /**
14
+ * Formats bytes to human-readable string
15
+ */
16
+ declare function formatBytes(bytes: number): string;
17
+
18
+ /**
19
+ * Returns current timestamp in milliseconds
20
+ */
21
+ declare function now(): number;
22
+ /**
23
+ * Checks if an entry is expired based on expiresAt timestamp
24
+ */
25
+ declare function isExpired(expiresAt: number | undefined): boolean;
26
+ /**
27
+ * Calculates remaining TTL from expiresAt
28
+ */
29
+ declare function getRemainingTTL(expiresAt: number | undefined): number | undefined;
30
+ /**
31
+ * Converts expiration timestamp to Date object
32
+ */
33
+ declare function getExpirationDate(expiresAt: number | undefined): Date | null;
34
+
35
+ export { CacheConfig, CacheInstance, createCache, estimateSize, formatBytes, getExpirationDate, getRemainingTTL, isExpired, now };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export{g as createCache,e as estimateSize,f as formatBytes,d as getExpirationDate,c as getRemainingTTL,b as isExpired,a as now}from'./chunk-CCPC3U3G.js';//# sourceMappingURL=index.js.map
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunk2NFW4LZU_cjs=require('./chunk-2NFW4LZU.cjs');var u="\0LZ\0";function p(n){if(n.length<100)return n;let r="",t=0;for(;t<n.length;){let e=n[t],o=1;for(;t+o<n.length&&n[t+o]===e&&o<255;)o++;o>3?r+=`${String.fromCharCode(o)}${e}`:r+=e.repeat(o),t+=o;}return r.length<n.length?u+r:n}function h(n){if(!n.startsWith(u))return n;let r=n.slice(u.length),t="",e=0;for(;e<r.length;)if(r[e]===""){let o=r.charCodeAt(e+1),s=r[e+2]??"";t+=s.repeat(o),e+=3;}else t+=r[e],e++;return t}function S(n={}){let r=n.threshold??1024;return {name:"compression",beforeSet(t,e,o){if(typeof e=="string"&&e.length>=r)return {value:p(e),options:o}},afterGet(t,e){return typeof e=="string"&&e.startsWith(u)?h(e):e},beforeSerialize(t){return typeof t=="string"&&t.length>=r?p(t):t},afterDeserialize(t){return typeof t=="string"&&t.startsWith(u)?h(t):t}}}var T={debug:0,info:1,warn:2,error:3};function b(n={}){let r=n.logger??console,t=T[n.level??"info"],e=n.prefix??"[Cache]",o=n.logValues??false,s=i=>T[i]>=t,c=(i,g,...f)=>{if(!s(i))return;let C=r[i];C(`${e} ${g}`,...f);};return {name:"logging",onInit(i){c("info","Cache initialized",{maxSize:i.maxSize});},onDestroy(i){c("info","Cache destroyed");},beforeGet(i){c("debug",`GET ${i}`);},afterGet(i,g){return g!==void 0?c("debug",`HIT ${i}`,o?{value:g}:void 0):c("debug",`MISS ${i}`),g},beforeSet(i,g,f){c("debug",`SET ${i}`,{...o?{value:g}:{},ttl:f?.ttl,tags:f?.tags});},afterSet(i,g){c("debug",`STORED ${i}`,{size:g.size,ttl:g.ttl,tags:g.tags});},beforeDelete(i){return c("debug",`DELETE ${i}`),true},afterDelete(i,g){c("debug",`DELETED ${i}`);}}}var a="\0ENC\0";function m(n,r){let t="";for(let e=0;e<n.length;e++){let o=e%r.length,s=n.charCodeAt(e)^r.charCodeAt(o);t+=String.fromCharCode(s);}return t}function P(n,r){return m(n,r)}function L(n){try{return typeof btoa<"u"?btoa(unescape(encodeURIComponent(n))):Buffer.from(n,"utf-8").toString("base64")}catch{return n}}function O(n){try{return typeof atob<"u"?decodeURIComponent(escape(atob(n))):Buffer.from(n,"base64").toString("utf-8")}catch{return n}}function l(n,r){let t=m(n,r),e=L(t);return a+e}function y(n,r){if(!n.startsWith(a))return n;let t=n.slice(a.length),e=O(t);return P(e,r)}function w(n){let r=n.key;if(!r||r.length<8)throw new Error("Encryption key must be at least 8 characters");return {name:"encryption",beforeSet(t,e,o){if(typeof e=="string")return {value:l(e,r),options:o};try{let s=JSON.stringify(e);return {value:l(s,r),options:o}}catch{return}},afterGet(t,e){if(typeof e!="string"||!e.startsWith(a))return e;let o=y(e,r);try{return JSON.parse(o)}catch{return o}},beforeSerialize(t){return typeof t=="string"?l(t,r):t},afterDeserialize(t){if(typeof t=="string"&&t.startsWith(a)){let e=y(t,r);try{return JSON.parse(e)}catch{return e}}return t}}}function x(n){let r=chunk2NFW4LZU_cjs.g({strategy:"lru",maxSize:n.l2.maxSize,ttl:n.l2.ttl,storage:n.l2.storage}),t=null;return {name:"tiered",onInit(e){t=e;},onDestroy(e){r.destroy(),t=null;},afterGet(e,o){if(o!==void 0)return o;let s=r.get(e);if(s!==void 0&&t)return t.set(e,s,{ttl:n.l1.ttl}),s},afterSet(e,o){r.set(e,o.value,{ttl:o.ttl??n.l2.ttl,tags:o.tags});},afterDelete(e,o){r.delete(e);}}}exports.compressionPlugin=S;exports.encryptionPlugin=w;exports.loggingPlugin=b;exports.tieredPlugin=x;//# sourceMappingURL=plugins.cjs.map
2
+ //# sourceMappingURL=plugins.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugins/compression.ts","../src/plugins/logging.ts","../src/plugins/encryption.ts","../src/plugins/tiered.ts"],"names":["COMPRESSION_MARKER","compress","input","output","i","char","count","decompress","compressed","compressionPlugin","options","threshold","_key","value","setOptions","LOG_LEVELS","loggingPlugin","logger","minLevel","prefix","logValues","shouldLog","level","log","message","args","logFn","cache","_cache","key","entry","_value","ENCRYPTION_MARKER","xorEncrypt","text","result","keyIndex","charCode","xorDecrypt","encrypted","toBase64","str","fromBase64","base64","encrypt","decrypt","encryptionPlugin","serialized","_getKey","decrypted","tieredPlugin","l2Cache","createCache","mainCache","l2Value"],"mappings":"mEAqBA,IAAMA,CAAAA,CAAqB,SAK3B,SAASC,CAAAA,CAASC,EAAuB,CACvC,GAAIA,CAAAA,CAAM,MAAA,CAAS,GAAA,CAAK,OAAOA,EAE/B,IAAIC,CAAAA,CAAS,GACTC,CAAAA,CAAI,CAAA,CAER,KAAOA,CAAAA,CAAIF,CAAAA,CAAM,MAAA,EAAQ,CACvB,IAAMG,CAAAA,CAAOH,EAAME,CAAC,CAAA,CAChBE,EAAQ,CAAA,CAEZ,KAAOF,EAAIE,CAAAA,CAAQJ,CAAAA,CAAM,MAAA,EAAUA,CAAAA,CAAME,CAAAA,CAAIE,CAAK,IAAMD,CAAAA,EAAQC,CAAAA,CAAQ,GAAA,EACtEA,CAAAA,EAAAA,CAGEA,CAAAA,CAAQ,CAAA,CACVH,GAAU,CAAA,CAAA,EAAS,MAAA,CAAO,YAAA,CAAaG,CAAK,CAAC,CAAA,EAAGD,CAAI,CAAA,CAAA,CAEpDF,CAAAA,EAAUE,EAAK,MAAA,CAAOC,CAAK,EAG7BF,CAAAA,EAAKE,EACP,CAGA,OAAIH,CAAAA,CAAO,MAAA,CAASD,EAAM,MAAA,CACjBF,CAAAA,CAAqBG,EAEvBD,CACT,CAKA,SAASK,CAAAA,CAAWL,CAAAA,CAAuB,CACzC,GAAI,CAACA,CAAAA,CAAM,WAAWF,CAAkB,CAAA,CACtC,OAAOE,CAAAA,CAGT,IAAMM,EAAaN,C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OpB,CAAAA,CAAQ,EAAA,CAAG,GAAA,CAC7B,IAAA,CAAMoB,CAAAA,CAAM,IACd,CAAC,EACH,CAAA,CAEA,WAAA,CAAYD,CAAAA,CAAaE,CAAAA,CAAiB,CAExCoB,EAAQ,MAAA,CAAOtB,CAAG,EACpB,CACF,CACF","file":"plugins.cjs","sourcesContent":["import type { CachePlugin, SetOptions } from '../types'\n\n/**\n * Compression plugin options\n */\nexport interface CompressionPluginOptions {\n /**\n * Minimum size in bytes before compression is applied\n * Default: 1024 (1KB)\n */\n threshold?: number\n\n /**\n * Compression algorithm to use\n * 'lz' uses LZ-based compression (built-in)\n */\n algorithm?: 'lz'\n}\n\n// Simple LZ-based compression implementation\n// This is a basic implementation for demonstration - in production you might want to use a library\nconst COMPRESSION_MARKER = '\\u0000LZ\\u0000'\n\n/**\n * Simple LZ compression (Run-Length Encoding variant)\n */\nfunction compress(input: string): string {\n if (input.length < 100) return input // Don't compress small strings\n\n let output = ''\n let i = 0\n\n while (i < input.length) {\n const char = input[i]!\n let count = 1\n\n while (i + count < input.length && input[i + count] === char && count < 255) {\n count++\n }\n\n if (count > 3) {\n output += `\\u0001${String.fromCharCode(count)}${char}`\n } else {\n output += char.repeat(count)\n }\n\n i += count\n }\n\n // Only use compressed version if it's actually smaller\n if (output.length < input.length) {\n return COMPRESSION_MARKER + output\n }\n return input\n}\n\n/**\n * Simple LZ decompression\n */\nfunction decompress(input: string): string {\n if (!input.startsWith(COMPRESSION_MARKER)) {\n return input\n }\n\n const compressed = input.slice(COMPRESSION_MARKER.length)\n let output = ''\n let i = 0\n\n while (i < compressed.length) {\n if (compressed[i] === '\\u0001') {\n const count = compressed.charCodeAt(i + 1)\n const char = compressed[i + 2] ?? ''\n output += char.repeat(count)\n i += 3\n } else {\n output += compressed[i]\n i++\n }\n }\n\n return output\n}\n\n/**\n * Creates a compression plugin for reducing cache storage size\n */\nexport function compressionPlugin<T = unknown>(\n options: CompressionPluginOptions = {}\n): CachePlugin<T> {\n const threshold = options.threshold ?? 1024\n\n return {\n name: 'compression',\n\n beforeSet(\n _key: string,\n value: T,\n setOptions?: SetOptions\n ): { value: T; options?: SetOptions } | void {\n // Only compress string values that exceed threshold\n if (typeof value === 'string' && value.length >= threshold) {\n const compressed = compress(value)\n return { value: compressed as unknown as T, options: setOptions }\n }\n return undefined\n },\n\n afterGet(_key: string, value: T | undefined): T | undefined {\n if (typeof value === 'string' && value.startsWith(COMPRESSION_MARKER)) {\n return decompress(value) as unknown as T\n }\n return value\n },\n\n beforeSerialize(value: T): T {\n if (typeof value === 'string' && value.length >= threshold) {\n return compress(value) as unknown as T\n }\n return value\n },\n\n afterDeserialize(value: T): T {\n if (typeof value === 'string' && value.startsWith(COMPRESSION_MARKER)) {\n return decompress(value) as unknown as T\n }\n return value\n },\n }\n}\n","import type { CachePlugin, CacheInstance, CacheEntry, SetOptions } from '../types'\n\n/**\n * Log levels\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/**\n * Logger interface\n */\nexport interface Logger {\n debug: (message: string, ...args: unknown[]) => void\n info: (message: string, ...args: unknown[]) => void\n warn: (message: string, ...args: unknown[]) => void\n error: (message: string, ...args: unknown[]) => void\n}\n\n/**\n * Logging plugin options\n */\nexport interface LoggingPluginOptions {\n /**\n * Logger instance (defaults to console)\n */\n logger?: Logger\n\n /**\n * Minimum log level to output\n * Default: 'info'\n */\n level?: LogLevel\n\n /**\n * Prefix for log messages\n * Default: '[Cache]'\n */\n prefix?: string\n\n /**\n * Whether to log values (may expose sensitive data)\n * Default: false\n */\n logValues?: boolean\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a logging plugin for cache debugging\n */\nexport function loggingPlugin<T = unknown>(\n options: LoggingPluginOptions = {}\n): CachePlugin<T> {\n const logger = options.logger ?? console\n const minLevel = LOG_LEVELS[options.level ?? 'info']\n const prefix = options.prefix ?? '[Cache]'\n const logValues = options.logValues ?? false\n\n const shouldLog = (level: LogLevel): boolean => {\n return LOG_LEVELS[level] >= minLevel\n }\n\n const log = (level: LogLevel, message: string, ...args: unknown[]): void => {\n if (!shouldLog(level)) return\n const logFn = logger[level]\n logFn(`${prefix} ${message}`, ...args)\n }\n\n return {\n name: 'logging',\n\n onInit(cache: CacheInstance<T>): void {\n log('info', 'Cache initialized', {\n maxSize: cache.maxSize,\n })\n },\n\n onDestroy(_cache: CacheInstance<T>): void {\n log('info', 'Cache destroyed')\n },\n\n beforeGet(key: string): void {\n log('debug', `GET ${key}`)\n },\n\n afterGet(key: string, value: T | undefined): T | undefined {\n if (value !== undefined) {\n log('debug', `HIT ${key}`, logValues ? { value } : undefined)\n } else {\n log('debug', `MISS ${key}`)\n }\n return value\n },\n\n beforeSet(\n key: string,\n value: T,\n setOptions?: SetOptions\n ): { value: T; options?: SetOptions } | void {\n log('debug', `SET ${key}`, {\n ...(logValues ? { value } : {}),\n ttl: setOptions?.ttl,\n tags: setOptions?.tags,\n })\n return undefined\n },\n\n afterSet(key: string, entry: CacheEntry<T>): void {\n log('debug', `STORED ${key}`, {\n size: entry.size,\n ttl: entry.ttl,\n tags: entry.tags,\n })\n },\n\n beforeDelete(key: string): boolean {\n log('debug', `DELETE ${key}`)\n return true\n },\n\n afterDelete(key: string, _value: T): void {\n log('debug', `DELETED ${key}`)\n },\n }\n}\n","import type { CachePlugin, SetOptions } from '../types'\n\n/**\n * Encryption plugin options\n */\nexport interface EncryptionPluginOptions {\n /**\n * Encryption key (must be 32 characters for AES-256)\n */\n key: string\n\n /**\n * Encryption algorithm\n * Default: 'aes-256-gcm' (simulated with XOR for browser compatibility)\n */\n algorithm?: 'aes-256-gcm'\n}\n\nconst ENCRYPTION_MARKER = '\\u0000ENC\\u0000'\n\n/**\n * Simple XOR encryption (for browser compatibility without Web Crypto complexity)\n * Note: This is a simplified implementation for demonstration.\n * For production use, consider using Web Crypto API or a proper encryption library.\n */\nfunction xorEncrypt(text: string, key: string): string {\n let result = ''\n for (let i = 0; i < text.length; i++) {\n const keyIndex = i % key.length\n const charCode = text.charCodeAt(i) ^ key.charCodeAt(keyIndex)\n result += String.fromCharCode(charCode)\n }\n return result\n}\n\nfunction xorDecrypt(encrypted: string, key: string): string {\n // XOR encryption is symmetric\n return xorEncrypt(encrypted, key)\n}\n\n/**\n * Converts string to base64 for safe storage\n */\nfunction toBase64(str: string): string {\n try {\n // Browser environment\n if (typeof btoa !== 'undefined') {\n return btoa(unescape(encodeURIComponent(str)))\n }\n // Node.js environment\n return Buffer.from(str, 'utf-8').toString('base64')\n } catch {\n return str\n }\n}\n\n/**\n * Converts base64 back to string\n */\nfunction fromBase64(base64: string): string {\n try {\n // Browser environment\n if (typeof atob !== 'undefined') {\n return decodeURIComponent(escape(atob(base64)))\n }\n // Node.js environment\n return Buffer.from(base64, 'base64').toString('utf-8')\n } catch {\n return base64\n }\n}\n\n/**\n * Encrypts a value\n */\nfunction encrypt(value: string, key: string): string {\n const encrypted = xorEncrypt(value, key)\n const base64 = toBase64(encrypted)\n return ENCRYPTION_MARKER + base64\n}\n\n/**\n * Decrypts a value\n */\nfunction decrypt(value: string, key: string): string {\n if (!value.startsWith(ENCRYPTION_MARKER)) {\n return value\n }\n\n const base64 = value.slice(ENCRYPTION_MARKER.length)\n const encrypted = fromBase64(base64)\n return xorDecrypt(encrypted, key)\n}\n\n/**\n * Creates an encryption plugin for securing cache values\n */\nexport function encryptionPlugin<T = unknown>(\n options: EncryptionPluginOptions\n): CachePlugin<T> {\n const key = options.key\n\n if (!key || key.length < 8) {\n throw new Error('Encryption key must be at least 8 characters')\n }\n\n return {\n name: 'encryption',\n\n beforeSet(\n _key: string,\n value: T,\n setOptions?: SetOptions\n ): { value: T; options?: SetOptions } | void {\n if (typeof value === 'string') {\n const encrypted = encrypt(value, key)\n return { value: encrypted as unknown as T, options: setOptions }\n }\n // For non-string values, serialize then encrypt\n try {\n const serialized = JSON.stringify(value)\n const encrypted = encrypt(serialized, key)\n return { value: encrypted as unknown as T, options: setOptions }\n } catch {\n return undefined\n }\n },\n\n afterGet(_getKey: string, value: T | undefined): T | undefined {\n if (typeof value !== 'string') return value\n if (!value.startsWith(ENCRYPTION_MARKER)) return value\n\n const decrypted = decrypt(value, key)\n\n // Try to parse as JSON\n try {\n return JSON.parse(decrypted) as T\n } catch {\n return decrypted as unknown as T\n }\n },\n\n beforeSerialize(value: T): T {\n if (typeof value === 'string') {\n return encrypt(value, key) as unknown as T\n }\n return value\n },\n\n afterDeserialize(value: T): T {\n if (typeof value === 'string' && value.startsWith(ENCRYPTION_MARKER)) {\n const decrypted = decrypt(value, key)\n try {\n return JSON.parse(decrypted) as T\n } catch {\n return decrypted as unknown as T\n }\n }\n return value\n },\n }\n}\n","import type { CachePlugin, CacheInstance, CacheEntry, StorageType } from '../types'\nimport { createCache } from '../core/cache'\n\n/**\n * Tier configuration\n */\nexport interface TierConfig {\n /**\n * Storage type for this tier\n */\n storage: StorageType\n\n /**\n * Maximum size for this tier\n */\n maxSize: number\n\n /**\n * Default TTL for this tier in milliseconds\n */\n ttl?: number\n}\n\n/**\n * Tiered cache plugin options\n */\nexport interface TieredPluginOptions {\n /**\n * L1 (fast) cache configuration\n */\n l1: TierConfig\n\n /**\n * L2 (slow but larger) cache configuration\n */\n l2: TierConfig\n}\n\n/**\n * Creates a tiered cache plugin for multi-level caching\n *\n * L1 is the fast cache (usually memory)\n * L2 is the slow cache (usually persistent storage)\n *\n * Get: L1 hit → return\n * Get: L1 miss → check L2 → promote to L1 → return\n * Set: Write to both L1 and L2\n */\nexport function tieredPlugin<T = unknown>(\n options: TieredPluginOptions\n): CachePlugin<T> {\n // Create L2 cache (L1 is the main cache this plugin is attached to)\n const l2Cache = createCache<T>({\n strategy: 'lru',\n maxSize: options.l2.maxSize,\n ttl: options.l2.ttl,\n storage: options.l2.storage,\n })\n\n // Keep reference to main cache (L1)\n let mainCache: CacheInstance<T> | null = null\n\n return {\n name: 'tiered',\n\n onInit(cache: CacheInstance<T>): void {\n mainCache = cache\n },\n\n onDestroy(_cache: CacheInstance<T>): void {\n l2Cache.destroy()\n mainCache = null\n },\n\n afterGet(key: string, value: T | undefined): T | undefined {\n // If L1 hit, return immediately\n if (value !== undefined) {\n return value\n }\n\n // L1 miss - check L2\n const l2Value = l2Cache.get(key)\n if (l2Value !== undefined && mainCache) {\n // Promote to L1\n mainCache.set(key, l2Value, {\n ttl: options.l1.ttl,\n })\n return l2Value\n }\n\n return undefined\n },\n\n afterSet(key: string, entry: CacheEntry<T>): void {\n // Write to L2 as well\n l2Cache.set(key, entry.value, {\n ttl: entry.ttl ?? options.l2.ttl,\n tags: entry.tags,\n })\n },\n\n afterDelete(key: string, _value: T): void {\n // Delete from L2 as well\n l2Cache.delete(key)\n },\n }\n}\n\n/**\n * Gets the L2 cache instance for inspection/management\n */\nexport function getL2Cache<T>(_plugin: CachePlugin<T>): CacheInstance<T> | null {\n // This is a workaround - in a real implementation you might want to expose this differently\n return null\n}\n"]}
@@ -0,0 +1,126 @@
1
+ import { r as CachePlugin, S as StorageType } from './types-B0XHVTZf.cjs';
2
+
3
+ /**
4
+ * Compression plugin options
5
+ */
6
+ interface CompressionPluginOptions {
7
+ /**
8
+ * Minimum size in bytes before compression is applied
9
+ * Default: 1024 (1KB)
10
+ */
11
+ threshold?: number;
12
+ /**
13
+ * Compression algorithm to use
14
+ * 'lz' uses LZ-based compression (built-in)
15
+ */
16
+ algorithm?: 'lz';
17
+ }
18
+ /**
19
+ * Creates a compression plugin for reducing cache storage size
20
+ */
21
+ declare function compressionPlugin<T = unknown>(options?: CompressionPluginOptions): CachePlugin<T>;
22
+
23
+ /**
24
+ * Log levels
25
+ */
26
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
27
+ /**
28
+ * Logger interface
29
+ */
30
+ interface Logger {
31
+ debug: (message: string, ...args: unknown[]) => void;
32
+ info: (message: string, ...args: unknown[]) => void;
33
+ warn: (message: string, ...args: unknown[]) => void;
34
+ error: (message: string, ...args: unknown[]) => void;
35
+ }
36
+ /**
37
+ * Logging plugin options
38
+ */
39
+ interface LoggingPluginOptions {
40
+ /**
41
+ * Logger instance (defaults to console)
42
+ */
43
+ logger?: Logger;
44
+ /**
45
+ * Minimum log level to output
46
+ * Default: 'info'
47
+ */
48
+ level?: LogLevel;
49
+ /**
50
+ * Prefix for log messages
51
+ * Default: '[Cache]'
52
+ */
53
+ prefix?: string;
54
+ /**
55
+ * Whether to log values (may expose sensitive data)
56
+ * Default: false
57
+ */
58
+ logValues?: boolean;
59
+ }
60
+ /**
61
+ * Creates a logging plugin for cache debugging
62
+ */
63
+ declare function loggingPlugin<T = unknown>(options?: LoggingPluginOptions): CachePlugin<T>;
64
+
65
+ /**
66
+ * Encryption plugin options
67
+ */
68
+ interface EncryptionPluginOptions {
69
+ /**
70
+ * Encryption key (must be 32 characters for AES-256)
71
+ */
72
+ key: string;
73
+ /**
74
+ * Encryption algorithm
75
+ * Default: 'aes-256-gcm' (simulated with XOR for browser compatibility)
76
+ */
77
+ algorithm?: 'aes-256-gcm';
78
+ }
79
+ /**
80
+ * Creates an encryption plugin for securing cache values
81
+ */
82
+ declare function encryptionPlugin<T = unknown>(options: EncryptionPluginOptions): CachePlugin<T>;
83
+
84
+ /**
85
+ * Tier configuration
86
+ */
87
+ interface TierConfig {
88
+ /**
89
+ * Storage type for this tier
90
+ */
91
+ storage: StorageType;
92
+ /**
93
+ * Maximum size for this tier
94
+ */
95
+ maxSize: number;
96
+ /**
97
+ * Default TTL for this tier in milliseconds
98
+ */
99
+ ttl?: number;
100
+ }
101
+ /**
102
+ * Tiered cache plugin options
103
+ */
104
+ interface TieredPluginOptions {
105
+ /**
106
+ * L1 (fast) cache configuration
107
+ */
108
+ l1: TierConfig;
109
+ /**
110
+ * L2 (slow but larger) cache configuration
111
+ */
112
+ l2: TierConfig;
113
+ }
114
+ /**
115
+ * Creates a tiered cache plugin for multi-level caching
116
+ *
117
+ * L1 is the fast cache (usually memory)
118
+ * L2 is the slow cache (usually persistent storage)
119
+ *
120
+ * Get: L1 hit → return
121
+ * Get: L1 miss → check L2 → promote to L1 → return
122
+ * Set: Write to both L1 and L2
123
+ */
124
+ declare function tieredPlugin<T = unknown>(options: TieredPluginOptions): CachePlugin<T>;
125
+
126
+ export { type CompressionPluginOptions, type EncryptionPluginOptions, type LogLevel, type Logger, type LoggingPluginOptions, type TierConfig, type TieredPluginOptions, compressionPlugin, encryptionPlugin, loggingPlugin, tieredPlugin };
@@ -0,0 +1,126 @@
1
+ import { r as CachePlugin, S as StorageType } from './types-B0XHVTZf.js';
2
+
3
+ /**
4
+ * Compression plugin options
5
+ */
6
+ interface CompressionPluginOptions {
7
+ /**
8
+ * Minimum size in bytes before compression is applied
9
+ * Default: 1024 (1KB)
10
+ */
11
+ threshold?: number;
12
+ /**
13
+ * Compression algorithm to use
14
+ * 'lz' uses LZ-based compression (built-in)
15
+ */
16
+ algorithm?: 'lz';
17
+ }
18
+ /**
19
+ * Creates a compression plugin for reducing cache storage size
20
+ */
21
+ declare function compressionPlugin<T = unknown>(options?: CompressionPluginOptions): CachePlugin<T>;
22
+
23
+ /**
24
+ * Log levels
25
+ */
26
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
27
+ /**
28
+ * Logger interface
29
+ */
30
+ interface Logger {
31
+ debug: (message: string, ...args: unknown[]) => void;
32
+ info: (message: string, ...args: unknown[]) => void;
33
+ warn: (message: string, ...args: unknown[]) => void;
34
+ error: (message: string, ...args: unknown[]) => void;
35
+ }
36
+ /**
37
+ * Logging plugin options
38
+ */
39
+ interface LoggingPluginOptions {
40
+ /**
41
+ * Logger instance (defaults to console)
42
+ */
43
+ logger?: Logger;
44
+ /**
45
+ * Minimum log level to output
46
+ * Default: 'info'
47
+ */
48
+ level?: LogLevel;
49
+ /**
50
+ * Prefix for log messages
51
+ * Default: '[Cache]'
52
+ */
53
+ prefix?: string;
54
+ /**
55
+ * Whether to log values (may expose sensitive data)
56
+ * Default: false
57
+ */
58
+ logValues?: boolean;
59
+ }
60
+ /**
61
+ * Creates a logging plugin for cache debugging
62
+ */
63
+ declare function loggingPlugin<T = unknown>(options?: LoggingPluginOptions): CachePlugin<T>;
64
+
65
+ /**
66
+ * Encryption plugin options
67
+ */
68
+ interface EncryptionPluginOptions {
69
+ /**
70
+ * Encryption key (must be 32 characters for AES-256)
71
+ */
72
+ key: string;
73
+ /**
74
+ * Encryption algorithm
75
+ * Default: 'aes-256-gcm' (simulated with XOR for browser compatibility)
76
+ */
77
+ algorithm?: 'aes-256-gcm';
78
+ }
79
+ /**
80
+ * Creates an encryption plugin for securing cache values
81
+ */
82
+ declare function encryptionPlugin<T = unknown>(options: EncryptionPluginOptions): CachePlugin<T>;
83
+
84
+ /**
85
+ * Tier configuration
86
+ */
87
+ interface TierConfig {
88
+ /**
89
+ * Storage type for this tier
90
+ */
91
+ storage: StorageType;
92
+ /**
93
+ * Maximum size for this tier
94
+ */
95
+ maxSize: number;
96
+ /**
97
+ * Default TTL for this tier in milliseconds
98
+ */
99
+ ttl?: number;
100
+ }
101
+ /**
102
+ * Tiered cache plugin options
103
+ */
104
+ interface TieredPluginOptions {
105
+ /**
106
+ * L1 (fast) cache configuration
107
+ */
108
+ l1: TierConfig;
109
+ /**
110
+ * L2 (slow but larger) cache configuration
111
+ */
112
+ l2: TierConfig;
113
+ }
114
+ /**
115
+ * Creates a tiered cache plugin for multi-level caching
116
+ *
117
+ * L1 is the fast cache (usually memory)
118
+ * L2 is the slow cache (usually persistent storage)
119
+ *
120
+ * Get: L1 hit → return
121
+ * Get: L1 miss → check L2 → promote to L1 → return
122
+ * Set: Write to both L1 and L2
123
+ */
124
+ declare function tieredPlugin<T = unknown>(options: TieredPluginOptions): CachePlugin<T>;
125
+
126
+ export { type CompressionPluginOptions, type EncryptionPluginOptions, type LogLevel, type Logger, type LoggingPluginOptions, type TierConfig, type TieredPluginOptions, compressionPlugin, encryptionPlugin, loggingPlugin, tieredPlugin };
@@ -0,0 +1,2 @@
1
+ import {g}from'./chunk-CCPC3U3G.js';var u="\0LZ\0";function p(n){if(n.length<100)return n;let r="",t=0;for(;t<n.length;){let e=n[t],o=1;for(;t+o<n.length&&n[t+o]===e&&o<255;)o++;o>3?r+=`${String.fromCharCode(o)}${e}`:r+=e.repeat(o),t+=o;}return r.length<n.length?u+r:n}function h(n){if(!n.startsWith(u))return n;let r=n.slice(u.length),t="",e=0;for(;e<r.length;)if(r[e]===""){let o=r.charCodeAt(e+1),s=r[e+2]??"";t+=s.repeat(o),e+=3;}else t+=r[e],e++;return t}function S(n={}){let r=n.threshold??1024;return {name:"compression",beforeSet(t,e,o){if(typeof e=="string"&&e.length>=r)return {value:p(e),options:o}},afterGet(t,e){return typeof e=="string"&&e.startsWith(u)?h(e):e},beforeSerialize(t){return typeof t=="string"&&t.length>=r?p(t):t},afterDeserialize(t){return typeof t=="string"&&t.startsWith(u)?h(t):t}}}var T={debug:0,info:1,warn:2,error:3};function b(n={}){let r=n.logger??console,t=T[n.level??"info"],e=n.prefix??"[Cache]",o=n.logValues??false,s=i=>T[i]>=t,c=(i,g,...f)=>{if(!s(i))return;let C=r[i];C(`${e} ${g}`,...f);};return {name:"logging",onInit(i){c("info","Cache initialized",{maxSize:i.maxSize});},onDestroy(i){c("info","Cache destroyed");},beforeGet(i){c("debug",`GET ${i}`);},afterGet(i,g){return g!==void 0?c("debug",`HIT ${i}`,o?{value:g}:void 0):c("debug",`MISS ${i}`),g},beforeSet(i,g,f){c("debug",`SET ${i}`,{...o?{value:g}:{},ttl:f?.ttl,tags:f?.tags});},afterSet(i,g){c("debug",`STORED ${i}`,{size:g.size,ttl:g.ttl,tags:g.tags});},beforeDelete(i){return c("debug",`DELETE ${i}`),true},afterDelete(i,g){c("debug",`DELETED ${i}`);}}}var a="\0ENC\0";function m(n,r){let t="";for(let e=0;e<n.length;e++){let o=e%r.length,s=n.charCodeAt(e)^r.charCodeAt(o);t+=String.fromCharCode(s);}return t}function P(n,r){return m(n,r)}function L(n){try{return typeof btoa<"u"?btoa(unescape(encodeURIComponent(n))):Buffer.from(n,"utf-8").toString("base64")}catch{return n}}function O(n){try{return typeof atob<"u"?decodeURIComponent(escape(atob(n))):Buffer.from(n,"base64").toString("utf-8")}catch{return n}}function l(n,r){let t=m(n,r),e=L(t);return a+e}function y(n,r){if(!n.startsWith(a))return n;let t=n.slice(a.length),e=O(t);return P(e,r)}function w(n){let r=n.key;if(!r||r.length<8)throw new Error("Encryption key must be at least 8 characters");return {name:"encryption",beforeSet(t,e,o){if(typeof e=="string")return {value:l(e,r),options:o};try{let s=JSON.stringify(e);return {value:l(s,r),options:o}}catch{return}},afterGet(t,e){if(typeof e!="string"||!e.startsWith(a))return e;let o=y(e,r);try{return JSON.parse(o)}catch{return o}},beforeSerialize(t){return typeof t=="string"?l(t,r):t},afterDeserialize(t){if(typeof t=="string"&&t.startsWith(a)){let e=y(t,r);try{return JSON.parse(e)}catch{return e}}return t}}}function x(n){let r=g({strategy:"lru",maxSize:n.l2.maxSize,ttl:n.l2.ttl,storage:n.l2.storage}),t=null;return {name:"tiered",onInit(e){t=e;},onDestroy(e){r.destroy(),t=null;},afterGet(e,o){if(o!==void 0)return o;let s=r.get(e);if(s!==void 0&&t)return t.set(e,s,{ttl:n.l1.ttl}),s},afterSet(e,o){r.set(e,o.value,{ttl:o.ttl??n.l2.ttl,tags:o.tags});},afterDelete(e,o){r.delete(e);}}}export{S as compressionPlugin,w as encryptionPlugin,b as loggingPlugin,x as tieredPlugin};//# sourceMappingURL=plugins.js.map
2
+ //# sourceMappingURL=plugins.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/plugins/compression.ts","../src/plugins/logging.ts","../src/plugins/encryption.ts","../src/plugins/tiered.ts"],"names":["COMPRESSION_MARKER","compress","input","output","i","char","count","decompress","compressed","compressionPlugin","options","threshold","_key","value","setOptions","LOG_LEVELS","loggingPlugin","logger","minLevel","prefix","logValues","shouldLog","level","log","message","args","logFn","cache","_cache","key","entry","_value","ENCRYPTION_MARKER","xorEncrypt","text","result","keyIndex","charCode","xorDecrypt","encrypted","toBase64","str","fromBase64","base64","encrypt","decrypt","encryptionPlugin","serialized","_getKey","decrypted","tieredPlugin","l2Cache","createCache","mainCache","l2Value"],"mappings":"oCAqBA,IAAMA,CAAAA,CAAqB,SAK3B,SAASC,CAAAA,CAASC,EAAuB,CACvC,GAAIA,CAAAA,CAAM,MAAA,CAAS,GAAA,CAAK,OAAOA,EAE/B,IAAIC,CAAAA,CAAS,GACTC,CAAAA,CAAI,CAAA,CAER,KAAOA,CAAAA,CAAIF,CAAAA,CAAM,MAAA,EAAQ,CACvB,IAAMG,CAAAA,CAAOH,EAAME,CAAC,CAAA,CAChBE,EAAQ,CAAA,CAEZ,KAAOF,EAAIE,CAAAA,CAAQJ,CAAAA,CAAM,MAAA,EAAUA,CAAAA,CAAME,CAAAA,CAAIE,CAAK,IAAMD,CAAAA,EAAQC,CAAAA,CAAQ,GAAA,EACtEA,CAAAA,EAAAA,CAGEA,CAAAA,CAAQ,CAAA,CACVH,GAAU,CAAA,CAAA,EAAS,MAAA,CAAO,YAAA,CAAaG,CAAK,CAAC,CAAA,EAAGD,CAAI,CAAA,CAAA,CAEpDF,CAAAA,EAAUE,EAAK,MAAA,CAAOC,CAAK,EAG7BF,CAAAA,EAAKE,EACP,CAGA,OAAIH,CAAAA,CAAO,MAAA,CAASD,EAAM,MAAA,CACjBF,CAAAA,CAAqBG,EAEvBD,CACT,CAKA,SAASK,CAAAA,CAAWL,CAAAA,CAAuB,CACzC,GAAI,CAACA,CAAAA,CAAM,WAAWF,CAAkB,CAAA,CACtC,OAAOE,CAAAA,CAGT,IAAMM,EAAaN,CAAAA,CAAM,KAAA,CAAMF,CAAAA,CAAmB,MAAM,CAAA,CACpDG,CAAAA,CAAS,GACTC,CAAAA,CAAI,CAAA,CAER,KAAOA,CAAAA,CAAII,CAAAA,CAAW,MAAA,EACpB,GAAIA,CAAAA,CAAWJ,CAAC,CAAA,GAAM,GAAA,CAAU,CAC9B,IAAME,EAAQE,CAAAA,CAAW,UAAA,C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n/**\n * Compression plugin options\n */\nexport interface CompressionPluginOptions {\n /**\n * Minimum size in bytes before compression is applied\n * Default: 1024 (1KB)\n */\n threshold?: number\n\n /**\n * Compression algorithm to use\n * 'lz' uses LZ-based compression (built-in)\n */\n algorithm?: 'lz'\n}\n\n// Simple LZ-based compression implementation\n// This is a basic implementation for demonstration - in production you might want to use a library\nconst COMPRESSION_MARKER = '\\u0000LZ\\u0000'\n\n/**\n * Simple LZ compression (Run-Length Encoding variant)\n */\nfunction compress(input: string): string {\n if (input.length < 100) return input // Don't compress small strings\n\n let output = ''\n let i = 0\n\n while (i < input.length) {\n const char = input[i]!\n let count = 1\n\n while (i + count < input.length && input[i + count] === char && count < 255) {\n count++\n }\n\n if (count > 3) {\n output += `\\u0001${String.fromCharCode(count)}${char}`\n } else {\n output += char.repeat(count)\n }\n\n i += count\n }\n\n // Only use compressed version if it's actually smaller\n if (output.length < input.length) {\n return COMPRESSION_MARKER + output\n }\n return input\n}\n\n/**\n * Simple LZ decompression\n */\nfunction decompress(input: string): string {\n if (!input.startsWith(COMPRESSION_MARKER)) {\n return input\n }\n\n const compressed = input.slice(COMPRESSION_MARKER.length)\n let output = ''\n let i = 0\n\n while (i < compressed.length) {\n if (compressed[i] === '\\u0001') {\n const count = compressed.charCodeAt(i + 1)\n const char = compressed[i + 2] ?? ''\n output += char.repeat(count)\n i += 3\n } else {\n output += compressed[i]\n i++\n }\n }\n\n return output\n}\n\n/**\n * Creates a compression plugin for reducing cache storage size\n */\nexport function compressionPlugin<T = unknown>(\n options: CompressionPluginOptions = {}\n): CachePlugin<T> {\n const threshold = options.threshold ?? 1024\n\n return {\n name: 'compression',\n\n beforeSet(\n _key: string,\n value: T,\n setOptions?: SetOptions\n ): { value: T; options?: SetOptions } | void {\n // Only compress string values that exceed threshold\n if (typeof value === 'string' && value.length >= threshold) {\n const compressed = compress(value)\n return { value: compressed as unknown as T, options: setOptions }\n }\n return undefined\n },\n\n afterGet(_key: string, value: T | undefined): T | undefined {\n if (typeof value === 'string' && value.startsWith(COMPRESSION_MARKER)) {\n return decompress(value) as unknown as T\n }\n return value\n },\n\n beforeSerialize(value: T): T {\n if (typeof value === 'string' && value.length >= threshold) {\n return compress(value) as unknown as T\n }\n return value\n },\n\n afterDeserialize(value: T): T {\n if (typeof value === 'string' && value.startsWith(COMPRESSION_MARKER)) {\n return decompress(value) as unknown as T\n }\n return value\n },\n }\n}\n","import type { CachePlugin, CacheInstance, CacheEntry, SetOptions } from '../types'\n\n/**\n * Log levels\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/**\n * Logger interface\n */\nexport interface Logger {\n debug: (message: string, ...args: unknown[]) => void\n info: (message: string, ...args: unknown[]) => void\n warn: (message: string, ...args: unknown[]) => void\n error: (message: string, ...args: unknown[]) => void\n}\n\n/**\n * Logging plugin options\n */\nexport interface LoggingPluginOptions {\n /**\n * Logger instance (defaults to console)\n */\n logger?: Logger\n\n /**\n * Minimum log level to output\n * Default: 'info'\n */\n level?: LogLevel\n\n /**\n * Prefix for log messages\n * Default: '[Cache]'\n */\n prefix?: string\n\n /**\n * Whether to log values (may expose sensitive data)\n * Default: false\n */\n logValues?: boolean\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a logging plugin for cache debugging\n */\nexport function loggingPlugin<T = unknown>(\n options: LoggingPluginOptions = {}\n): CachePlugin<T> {\n const logger = options.logger ?? console\n const minLevel = LOG_LEVELS[options.level ?? 'info']\n const prefix = options.prefix ?? '[Cache]'\n const logValues = options.logValues ?? false\n\n const shouldLog = (level: LogLevel): boolean => {\n return LOG_LEVELS[level] >= minLevel\n }\n\n const log = (level: LogLevel, message: string, ...args: unknown[]): void => {\n if (!shouldLog(level)) return\n const logFn = logger[level]\n logFn(`${prefix} ${message}`, ...args)\n }\n\n return {\n name: 'logging',\n\n onInit(cache: CacheInstance<T>): void {\n log('info', 'Cache initialized', {\n maxSize: cache.maxSize,\n })\n },\n\n onDestroy(_cache: CacheInstance<T>): void {\n log('info', 'Cache destroyed')\n },\n\n beforeGet(key: string): void {\n log('debug', `GET ${key}`)\n },\n\n afterGet(key: string, value: T | undefined): T | undefined {\n if (value !== undefined) {\n log('debug', `HIT ${key}`, logValues ? { value } : undefined)\n } else {\n log('debug', `MISS ${key}`)\n }\n return value\n },\n\n beforeSet(\n key: string,\n value: T,\n setOptions?: SetOptions\n ): { value: T; options?: SetOptions } | void {\n log('debug', `SET ${key}`, {\n ...(logValues ? { value } : {}),\n ttl: setOptions?.ttl,\n tags: setOptions?.tags,\n })\n return undefined\n },\n\n afterSet(key: string, entry: CacheEntry<T>): void {\n log('debug', `STORED ${key}`, {\n size: entry.size,\n ttl: entry.ttl,\n tags: entry.tags,\n })\n },\n\n beforeDelete(key: string): boolean {\n log('debug', `DELETE ${key}`)\n return true\n },\n\n afterDelete(key: string, _value: T): void {\n log('debug', `DELETED ${key}`)\n },\n }\n}\n","import type { CachePlugin, SetOptions } from '../types'\n\n/**\n * Encryption plugin options\n */\nexport interface EncryptionPluginOptions {\n /**\n * Encryption key (must be 32 characters for AES-256)\n */\n key: string\n\n /**\n * Encryption algorithm\n * Default: 'aes-256-gcm' (simulated with XOR for browser compatibility)\n */\n algorithm?: 'aes-256-gcm'\n}\n\nconst ENCRYPTION_MARKER = '\\u0000ENC\\u0000'\n\n/**\n * Simple XOR encryption (for browser compatibility without Web Crypto complexity)\n * Note: This is a simplified implementation for demonstration.\n * For production use, consider using Web Crypto API or a proper encryption library.\n */\nfunction xorEncrypt(text: string, key: string): string {\n let result = ''\n for (let i = 0; i < text.length; i++) {\n const keyIndex = i % key.length\n const charCode = text.charCodeAt(i) ^ key.charCodeAt(keyIndex)\n result += String.fromCharCode(charCode)\n }\n return result\n}\n\nfunction xorDecrypt(encrypted: string, key: string): string {\n // XOR encryption is symmetric\n return xorEncrypt(encrypted, key)\n}\n\n/**\n * Converts string to base64 for safe storage\n */\nfunction toBase64(str: string): string {\n try {\n // Browser environment\n if (typeof btoa !== 'undefined') {\n return btoa(unescape(encodeURIComponent(str)))\n }\n // Node.js environment\n return Buffer.from(str, 'utf-8').toString('base64')\n } catch {\n return str\n }\n}\n\n/**\n * Converts base64 back to string\n */\nfunction fromBase64(base64: string): string {\n try {\n // Browser environment\n if (typeof atob !== 'undefined') {\n return decodeURIComponent(escape(atob(base64)))\n }\n // Node.js environment\n return Buffer.from(base64, 'base64').toString('utf-8')\n } catch {\n return base64\n }\n}\n\n/**\n * Encrypts a value\n */\nfunction encrypt(value: string, key: string): string {\n const encrypted = xorEncrypt(value, key)\n const base64 = toBase64(encrypted)\n return ENCRYPTION_MARKER + base64\n}\n\n/**\n * Decrypts a value\n */\nfunction decrypt(value: string, key: string): string {\n if (!value.startsWith(ENCRYPTION_MARKER)) {\n return value\n }\n\n const base64 = value.slice(ENCRYPTION_MARKER.length)\n const encrypted = fromBase64(base64)\n return xorDecrypt(encrypted, key)\n}\n\n/**\n * Creates an encryption plugin for securing cache values\n */\nexport function encryptionPlugin<T = unknown>(\n options: EncryptionPluginOptions\n): CachePlugin<T> {\n const key = options.key\n\n if (!key || key.length < 8) {\n throw new Error('Encryption key must be at least 8 characters')\n }\n\n return {\n name: 'encryption',\n\n beforeSet(\n _key: string,\n value: T,\n setOptions?: SetOptions\n ): { value: T; options?: SetOptions } | void {\n if (typeof value === 'string') {\n const encrypted = encrypt(value, key)\n return { value: encrypted as unknown as T, options: setOptions }\n }\n // For non-string values, serialize then encrypt\n try {\n const serialized = JSON.stringify(value)\n const encrypted = encrypt(serialized, key)\n return { value: encrypted as unknown as T, options: setOptions }\n } catch {\n return undefined\n }\n },\n\n afterGet(_getKey: string, value: T | undefined): T | undefined {\n if (typeof value !== 'string') return value\n if (!value.startsWith(ENCRYPTION_MARKER)) return value\n\n const decrypted = decrypt(value, key)\n\n // Try to parse as JSON\n try {\n return JSON.parse(decrypted) as T\n } catch {\n return decrypted as unknown as T\n }\n },\n\n beforeSerialize(value: T): T {\n if (typeof value === 'string') {\n return encrypt(value, key) as unknown as T\n }\n return value\n },\n\n afterDeserialize(value: T): T {\n if (typeof value === 'string' && value.startsWith(ENCRYPTION_MARKER)) {\n const decrypted = decrypt(value, key)\n try {\n return JSON.parse(decrypted) as T\n } catch {\n return decrypted as unknown as T\n }\n }\n return value\n },\n }\n}\n","import type { CachePlugin, CacheInstance, CacheEntry, StorageType } from '../types'\nimport { createCache } from '../core/cache'\n\n/**\n * Tier configuration\n */\nexport interface TierConfig {\n /**\n * Storage type for this tier\n */\n storage: StorageType\n\n /**\n * Maximum size for this tier\n */\n maxSize: number\n\n /**\n * Default TTL for this tier in milliseconds\n */\n ttl?: number\n}\n\n/**\n * Tiered cache plugin options\n */\nexport interface TieredPluginOptions {\n /**\n * L1 (fast) cache configuration\n */\n l1: TierConfig\n\n /**\n * L2 (slow but larger) cache configuration\n */\n l2: TierConfig\n}\n\n/**\n * Creates a tiered cache plugin for multi-level caching\n *\n * L1 is the fast cache (usually memory)\n * L2 is the slow cache (usually persistent storage)\n *\n * Get: L1 hit → return\n * Get: L1 miss → check L2 → promote to L1 → return\n * Set: Write to both L1 and L2\n */\nexport function tieredPlugin<T = unknown>(\n options: TieredPluginOptions\n): CachePlugin<T> {\n // Create L2 cache (L1 is the main cache this plugin is attached to)\n const l2Cache = createCache<T>({\n strategy: 'lru',\n maxSize: options.l2.maxSize,\n ttl: options.l2.ttl,\n storage: options.l2.storage,\n })\n\n // Keep reference to main cache (L1)\n let mainCache: CacheInstance<T> | null = null\n\n return {\n name: 'tiered',\n\n onInit(cache: CacheInstance<T>): void {\n mainCache = cache\n },\n\n onDestroy(_cache: CacheInstance<T>): void {\n l2Cache.destroy()\n mainCache = null\n },\n\n afterGet(key: string, value: T | undefined): T | undefined {\n // If L1 hit, return immediately\n if (value !== undefined) {\n return value\n }\n\n // L1 miss - check L2\n const l2Value = l2Cache.get(key)\n if (l2Value !== undefined && mainCache) {\n // Promote to L1\n mainCache.set(key, l2Value, {\n ttl: options.l1.ttl,\n })\n return l2Value\n }\n\n return undefined\n },\n\n afterSet(key: string, entry: CacheEntry<T>): void {\n // Write to L2 as well\n l2Cache.set(key, entry.value, {\n ttl: entry.ttl ?? options.l2.ttl,\n tags: entry.tags,\n })\n },\n\n afterDelete(key: string, _value: T): void {\n // Delete from L2 as well\n l2Cache.delete(key)\n },\n }\n}\n\n/**\n * Gets the L2 cache instance for inspection/management\n */\nexport function getL2Cache<T>(_plugin: CachePlugin<T>): CacheInstance<T> | null {\n // This is a workaround - in a real implementation you might want to expose this differently\n return null\n}\n"]}
package/dist/react.cjs ADDED
@@ -0,0 +1,2 @@
1
+ 'use strict';var react=require('react'),jsxRuntime=require('react/jsx-runtime');var v=react.createContext(null);v.displayName="CacheContext";function D({cache:e,children:i}){return jsxRuntime.jsx(v.Provider,{value:e,children:i})}function c(){let e=react.useContext(v);if(!e)throw new Error("useCache must be used within a CacheProvider");return e}function O(e,i={}){let a=c(),{fetcher:t,ttl:o,staleTime:u,tags:T,enabled:w=true,onSuccess:C,onError:y}=i,[p,h]=react.useState(()=>({data:a.get(e),isLoading:false,isFetching:false,error:null})),d=react.useRef(true),l=react.useRef(false),f=react.useCallback(async()=>{if(!(!t||l.current)){l.current=true,h(r=>({...r,isLoading:r.data===void 0,isFetching:true}));try{let r=await Promise.resolve(t());if(!d.current)return;a.set(e,r,{ttl:o,tags:T,stale:u}),h({data:r,isLoading:!1,isFetching:!1,error:null}),C?.(r);}catch(r){if(!d.current)return;let m=r instanceof Error?r:new Error(String(r));h(n=>({...n,isLoading:false,isFetching:false,error:m})),y?.(m);}finally{l.current=false;}}},[a,e,t,o,u,T,C,y]),P=react.useCallback(async()=>{t&&await f();},[f,t]),S=react.useCallback(()=>{a.delete(e),h(r=>({...r,data:void 0}));},[a,e]);return react.useEffect(()=>(d.current=true,()=>{d.current=false;}),[]),react.useEffect(()=>{if(!w)return;let r=a.get(e);if(r!==void 0){h(m=>({...m,data:r})),a.isStale(e)&&f().catch(()=>{});return}t&&f().catch(()=>{});},[e,w,a,t,f]),{data:p.data,isLoading:p.isLoading,isCached:a.has(e),isStale:a.isStale(e),isFetching:p.isFetching,error:p.error,refresh:P,invalidate:S}}function F(e,i,a={}){let t=c(),{ttl:o,staleTime:u,revalidateOnFocus:T=false,revalidateOnReconnect:w=false,revalidateInterval:C,dedupingInterval:y=2e3,onSuccess:p,onError:h}=a,[d,l]=react.useState(()=>({data:t.get(e),error:null,isLoading:!t.has(e),isValidating:false})),f=react.useRef(true),P=react.useRef(0),S=react.useRef(false),r=react.useCallback(async()=>{let n=Date.now();if(!(n-P.current<y)&&!S.current){S.current=true,P.current=n,l(s=>({...s,isLoading:s.data===void 0,isValidating:true}));try{let s=await Promise.resolve(i());if(!f.current)return;t.set(e,s,{ttl:o,stale:u}),l({data:s,error:null,isLoading:!1,isValidating:!1}),p?.(s);}catch(s){if(!f.current)return;let g=s instanceof Error?s:new Error(String(s));l(I=>({...I,error:g,isLoading:false,isValidating:false})),h?.(g);}finally{S.current=false;}}},[t,e,i,o,u,y,p,h]),m=react.useCallback(async n=>{if(n===void 0){await r();return}if(typeof n=="function"){let s=n,g=t.get(e),I=s(g);t.set(e,I,{ttl:o,stale:u}),l(W=>({...W,data:I}));return}if(n instanceof Promise){let s=await n;t.set(e,s,{ttl:o,stale:u}),l(g=>({...g,data:s}));return}t.set(e,n,{ttl:o,stale:u}),l(s=>({...s,data:n}));},[t,e,o,u,r]);return react.useEffect(()=>(f.current=true,()=>{f.current=false;}),[]),react.useEffect(()=>{let n=t.get(e);n!==void 0?(l(s=>({...s,data:n,isLoading:false})),t.isStale(e)&&r().catch(()=>{})):r().catch(()=>{});},[e,t,r]),react.useEffect(()=>{if(!T)return;let n=()=>{(t.isStale(e)||!t.has(e))&&r().catch(()=>{});};if(typeof window<"u")return window.addEventListener("focus",n),()=>window.removeEventListener("focus",n)},[T,t,e,r]),react.useEffect(()=>{if(!w)return;let n=()=>{r().catch(()=>{});};if(typeof window<"u")return window.addEventListener("online",n),()=>window.removeEventListener("online",n)},[w,r]),react.useEffect(()=>{if(!C)return;let n=setInterval(()=>{r().catch(()=>{});},C);return ()=>clearInterval(n)},[C,r]),{data:d.data,error:d.error,isLoading:d.isLoading,isValidating:d.isValidating,mutate:m}}function Q(){let e=c(),i=react.useCallback(o=>{e.delete(o);},[e]),a=react.useCallback(o=>(e.invalidateByTag(o)),[e]),t=react.useCallback(()=>{e.clear();},[e]);return {invalidate:i,invalidateByTag:a,clear:t}}function N(e={}){let i=c(),{refreshInterval:a=0}=e,[t,o]=react.useState(()=>i.getStats());return react.useEffect(()=>{if(o(i.getStats()),!a)return;let u=setInterval(()=>{o(i.getStats());},a);return ()=>clearInterval(u)},[i,a]),t}function G(e){function i(a){let t=c();return jsxRuntime.jsx(e,{...a,cache:t})}return i.displayName=`withCache(${e.displayName??e.name??"Component"})`,i}exports.CacheContext=v;exports.CacheProvider=D;exports.useCache=c;exports.useCacheInvalidation=Q;exports.useCacheStats=N;exports.useCachedQuery=F;exports.useCachedValue=O;exports.withCache=G;//# sourceMappingURL=react.cjs.map
2
+ //# sourceMappingURL=react.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/react/context.ts","../src/adapters/react/provider.tsx","../src/adapters/react/hooks/useCache.ts","../src/adapters/react/hooks/useCachedValue.ts","../src/adapters/react/hooks/useCachedQuery.ts","../src/adapters/react/hooks/useCacheInvalidation.ts","../src/adapters/react/hooks/useCacheStats.ts","../src/adapters/react/hoc.tsx"],"names":["CacheContext","createContext","CacheProvider","cache","children","jsx","useCache","useContext","useCachedValue","key","options","fetcher","ttl","staleTime","tags","enabled","onSuccess","onError","state","setState","useState","mountedRef","useRef","fetchingRef","fetchData","useCallback","s","result","err","error","refresh","invalidate","useEffect","cached","useCachedQuery","revalidateOnFocus","revalidateOnReconnect","revalidateInterval","dedupingInterval","lastFetchRef","revalidate","now","mutate","data","fn","current","newData","resolved","handleFocus","handleOnline","interval","useCacheInvalidation","invalidateByTag","tag","clear","useCacheStats","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CAAItC,cAAAA,CAAqB,IAAMjB,CAAAA,CAAM,QAAA,EAAU,CAAA,CAErE,OAAA6B,eAAAA,CAAU,IAAM,CAKd,GAHA0B,EAASvD,CAAAA,CAAM,QAAA,EAAU,CAAA,CAGrB,CAACqD,CAAAA,CAAiB,OAGtB,IAAMN,CAAAA,CAAW,WAAA,CAAY,IAAM,CACjCQ,CAAAA,CAASvD,CAAAA,CAAM,QAAA,EAAU,EAC3B,CAAA,CAAGqD,CAAe,CAAA,CAElB,OAAO,IAAM,aAAA,CAAcN,CAAQ,CACrC,CAAA,CAAG,CAAC/C,CAAAA,CAAOqD,CAAe,CAAC,CAAA,CAEpBC,CACT,CC3BO,SAASE,CAAAA,CACdC,CAAAA,CACiD,CACjD,SAASC,CAAAA,CAAiBC,CAAAA,CAAyC,CACjE,IAAM3D,CAAAA,CAAQG,CAAAA,EAAY,CAC1B,OAAOD,cAAAA,CAACuD,EAAA,CAAkB,GAAIE,CAAAA,CAAa,KAAA,CAAO3D,CAAAA,CAAO,CAC3D,CAEA,OAAA0D,CAAAA,CAAiB,WAAA,CAAc,CAAA,UAAA,EAAaD,CAAAA,CAAiB,WAAA,EAAeA,CAAAA,CAAiB,IAAA,EAAQ,WAAW,IAEzGC,CACT","file":"react.cjs","sourcesContent":["import { createContext } from 'react'\nimport type { CacheInstance } from '../../types'\n\n/**\n * React context for cache instance\n */\nexport const CacheContext = createContext<CacheInstance<unknown> | null>(null)\n\nCacheContext.displayName = 'CacheContext'\n","import type { ReactNode } from 'react'\nimport { CacheContext } from './context'\nimport type { CacheInstance } from '../../types'\n\n/**\n * Props for CacheProvider component\n */\nexport interface CacheProviderProps<T = unknown> {\n /**\n * Cache instance to provide\n */\n cache: CacheInstance<T>\n\n /**\n * Child components\n */\n children: ReactNode\n}\n\n/**\n * Provider component for cache context\n *\n * @example\n * ```tsx\n * const cache = createCache({ strategy: 'lru', maxSize: 1000 })\n *\n * function App() {\n * return (\n * <CacheProvider cache={cache}>\n * <MyApp />\n * </CacheProvider>\n * )\n * }\n * ```\n */\nexport function CacheProvider<T = unknown>({\n cache,\n children,\n}: CacheProviderProps<T>): JSX.Element {\n return (\n <CacheContext.Provider value={cache as CacheInstance<unknown>}>\n {children}\n </CacheContext.Provider>\n )\n}\n","import { useContext } from 'react'\nimport { CacheContext } from '../context'\nimport type { CacheInstance } from '../../../types'\n\n/**\n * Hook to access the cache instance from context\n *\n * @throws Error if used outside CacheProvider\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const cache = useCache<MyDataType>()\n *\n * const handleSave = (data: MyDataType) => {\n * cache.set('my-key', data)\n * }\n *\n * const handleLoad = () => {\n * return cache.get('my-key')\n * }\n * }\n * ```\n */\nexport function useCache<T = unknown>(): CacheInstance<T> {\n const cache = useContext(CacheContext)\n\n if (!cache) {\n throw new Error('useCache must be used within a CacheProvider')\n }\n\n return cache as CacheInstance<T>\n}\n","import { useState, useEffect, useCallback, useRef } from 'react'\nimport { useCache } from './useCache'\nimport type { UseCachedValueOptions, UseCachedValueResult } from '../../../types'\n\n/**\n * Hook for caching a single value with optional fetcher\n *\n * @example\n * ```tsx\n * function UserProfile({ userId }: { userId: string }) {\n * const {\n * data: user,\n * isLoading,\n * isCached,\n * isStale,\n * error,\n * refresh,\n * } = useCachedValue<User>(`user:${userId}`, {\n * fetcher: () => fetchUser(userId),\n * ttl: 60000,\n * staleTime: 30000,\n * })\n *\n * if (isLoading && !isCached) {\n * return <Spinner />\n * }\n *\n * if (error) {\n * return <Error message={error.message} />\n * }\n *\n * return (\n * <div>\n * <h1>{user?.name}</h1>\n * {isStale && <Badge>Updating...</Badge>}\n * <button onClick={refresh}>Refresh</button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useCachedValue<T>(\n key: string,\n options: UseCachedValueOptions<T> = {}\n): UseCachedValueResult<T> {\n const cache = useCache<T>()\n const { fetcher, ttl, staleTime, tags, enabled = true, onSuccess, onError } = options\n\n const [state, setState] = useState<{\n data: T | undefined\n isLoading: boolean\n isFetching: boolean\n error: Error | null\n }>(() => ({\n data: cache.get(key),\n isLoading: false,\n isFetching: false,\n error: null,\n }))\n\n const mountedRef = useRef(true)\n const fetchingRef = useRef(false)\n\n const fetchData = useCallback(async () => {\n if (!fetcher || fetchingRef.current) return\n\n fetchingRef.current = true\n\n setState((s) => ({\n ...s,\n isLoading: s.data === undefined,\n isFetching: true,\n }))\n\n try {\n const result = await Promise.resolve(fetcher())\n\n if (!mountedRef.current) return\n\n cache.set(key, result, {\n ttl,\n tags,\n stale: staleTime,\n })\n\n setState({\n data: result,\n isLoading: false,\n isFetching: false,\n error: null,\n })\n\n onSuccess?.(result)\n } catch (err) {\n if (!mountedRef.current) return\n\n const error = err instanceof Error ? err : new Error(String(err))\n\n setState((s) => ({\n ...s,\n isLoading: false,\n isFetching: false,\n error,\n }))\n\n onError?.(error)\n } finally {\n fetchingRef.current = false\n }\n }, [cache, key, fetcher, ttl, staleTime, tags, onSuccess, onError])\n\n const refresh = useCallback(async () => {\n if (!fetcher) return\n await fetchData()\n }, [fetchData, fetcher])\n\n const invalidate = useCallback(() => {\n cache.delete(key)\n setState((s) => ({ ...s, data: undefined }))\n }, [cache, key])\n\n useEffect(() => {\n mountedRef.current = true\n return () => {\n mountedRef.current = false\n }\n }, [])\n\n useEffect(() => {\n if (!enabled) return\n\n // Check cache first\n const cached = cache.get(key)\n\n if (cached !== undefined) {\n setState((s) => ({ ...s, data: cached }))\n\n // If stale, fetch in background\n if (cache.isStale(key)) {\n fetchData().catch(() => {\n // Ignore background fetch errors\n })\n }\n return\n }\n\n // No cached data, fetch if fetcher is provided\n if (fetcher) {\n fetchData().catch(() => {\n // Error is handled in fetchData\n })\n }\n }, [key, enabled, cache, fetcher, fetchData])\n\n return {\n data: state.data,\n isLoading: state.isLoading,\n isCached: cache.has(key),\n isStale: cache.isStale(key),\n isFetching: state.isFetching,\n error: state.error,\n refresh,\n invalidate,\n }\n}\n","import { useState, useEffect, useCallback, useRef } from 'react'\nimport { useCache } from './useCache'\nimport type { UseCachedQueryOptions, UseCachedQueryResult } from '../../../types'\n\n/**\n * Hook for SWR-like data fetching with automatic revalidation\n *\n * @example\n * ```tsx\n * function Products() {\n * const {\n * data: products,\n * error,\n * isLoading,\n * isValidating,\n * mutate,\n * } = useCachedQuery<Product[]>('products', fetchProducts, {\n * ttl: 300000, // 5 min cache\n * staleTime: 60000, // Fresh for 1 min\n * revalidateOnFocus: true, // Refetch on window focus\n * revalidateOnReconnect: true, // Refetch on network reconnect\n * revalidateInterval: 30000, // Poll every 30s\n * })\n *\n * if (isLoading) return <Spinner />\n * if (error) return <Error error={error} />\n *\n * return (\n * <div>\n * {isValidating && <Badge>Updating...</Badge>}\n * <ProductList products={products} />\n * <button onClick={() => mutate()}>Refresh</button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useCachedQuery<T>(\n key: string,\n fetcher: () => T | Promise<T>,\n options: UseCachedQueryOptions<T> = {}\n): UseCachedQueryResult<T> {\n const cache = useCache<T>()\n const {\n ttl,\n staleTime,\n revalidateOnFocus = false,\n revalidateOnReconnect = false,\n revalidateInterval,\n dedupingInterval = 2000,\n onSuccess,\n onError,\n } = options\n\n const [state, setState] = useState<{\n data: T | undefined\n error: Error | null\n isLoading: boolean\n isValidating: boolean\n }>(() => ({\n data: cache.get(key),\n error: null,\n isLoading: !cache.has(key),\n isValidating: false,\n }))\n\n const mountedRef = useRef(true)\n const lastFetchRef = useRef(0)\n const fetchingRef = useRef(false)\n\n const revalidate = useCallback(async () => {\n const now = Date.now()\n\n // Deduping: don't fetch if we just fetched\n if (now - lastFetchRef.current < dedupingInterval) {\n return\n }\n\n // Don't fetch if already fetching\n if (fetchingRef.current) {\n return\n }\n\n fetchingRef.current = true\n lastFetchRef.current = now\n\n setState((s) => ({\n ...s,\n isLoading: s.data === undefined,\n isValidating: true,\n }))\n\n try {\n const result = await Promise.resolve(fetcher())\n\n if (!mountedRef.current) return\n\n cache.set(key, result, {\n ttl,\n stale: staleTime,\n })\n\n setState({\n data: result,\n error: null,\n isLoading: false,\n isValidating: false,\n })\n\n onSuccess?.(result)\n } catch (err) {\n if (!mountedRef.current) return\n\n const error = err instanceof Error ? err : new Error(String(err))\n\n setState((s) => ({\n ...s,\n error,\n isLoading: false,\n isValidating: false,\n }))\n\n onError?.(error)\n } finally {\n fetchingRef.current = false\n }\n }, [cache, key, fetcher, ttl, staleTime, dedupingInterval, onSuccess, onError])\n\n const mutate = useCallback(\n async (\n data?: T | Promise<T> | ((current: T | undefined) => T)\n ): Promise<void> => {\n if (data === undefined) {\n // Just revalidate\n await revalidate()\n return\n }\n\n // Handle function\n if (typeof data === 'function') {\n const fn = data as (current: T | undefined) => T\n const current = cache.get(key)\n const newData = fn(current)\n cache.set(key, newData, { ttl, stale: staleTime })\n setState((s) => ({ ...s, data: newData }))\n return\n }\n\n // Handle promise\n if (data instanceof Promise) {\n const resolved = await data\n cache.set(key, resolved, { ttl, stale: staleTime })\n setState((s) => ({ ...s, data: resolved }))\n return\n }\n\n // Handle direct value\n cache.set(key, data, { ttl, stale: staleTime })\n setState((s) => ({ ...s, data }))\n },\n [cache, key, ttl, staleTime, revalidate]\n )\n\n // Initial fetch\n useEffect(() => {\n mountedRef.current = true\n return () => {\n mountedRef.current = false\n }\n }, [])\n\n useEffect(() => {\n const cached = cache.get(key)\n\n if (cached !== undefined) {\n setState((s) => ({\n ...s,\n data: cached,\n isLoading: false,\n }))\n\n // Revalidate if stale\n if (cache.isStale(key)) {\n revalidate().catch(() => {\n // Error handled in revalidate\n })\n }\n } else {\n revalidate().catch(() => {\n // Error handled in revalidate\n })\n }\n }, [key, cache, revalidate])\n\n // Revalidate on focus\n useEffect(() => {\n if (!revalidateOnFocus) return\n\n const handleFocus = () => {\n if (cache.isStale(key) || !cache.has(key)) {\n revalidate().catch(() => {\n // Ignore\n })\n }\n }\n\n if (typeof window !== 'undefined') {\n window.addEventListener('focus', handleFocus)\n return () => window.removeEventListener('focus', handleFocus)\n }\n return undefined\n }, [revalidateOnFocus, cache, key, revalidate])\n\n // Revalidate on reconnect\n useEffect(() => {\n if (!revalidateOnReconnect) return\n\n const handleOnline = () => {\n revalidate().catch(() => {\n // Ignore\n })\n }\n\n if (typeof window !== 'undefined') {\n window.addEventListener('online', handleOnline)\n return () => window.removeEventListener('online', handleOnline)\n }\n return undefined\n }, [revalidateOnReconnect, revalidate])\n\n // Revalidate interval\n useEffect(() => {\n if (!revalidateInterval) return\n\n const interval = setInterval(() => {\n revalidate().catch(() => {\n // Ignore\n })\n }, revalidateInterval)\n\n return () => clearInterval(interval)\n }, [revalidateInterval, revalidate])\n\n return {\n data: state.data,\n error: state.error,\n isLoading: state.isLoading,\n isValidating: state.isValidating,\n mutate,\n }\n}\n","import { useCallback } from 'react'\nimport { useCache } from './useCache'\nimport type { UseCacheInvalidationResult } from '../../../types'\n\n/**\n * Hook for cache invalidation utilities\n *\n * @example\n * ```tsx\n * function AdminPanel() {\n * const { invalidate, invalidateByTag, clear } = useCacheInvalidation()\n *\n * return (\n * <div>\n * <button onClick={() => invalidate('user:1')}>\n * Invalidate User 1\n * </button>\n *\n * <button onClick={() => invalidateByTag('products')}>\n * Invalidate All Products\n * </button>\n *\n * <button onClick={() => clear()}>\n * Clear All Cache\n * </button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useCacheInvalidation(): UseCacheInvalidationResult {\n const cache = useCache()\n\n const invalidate = useCallback(\n (key: string) => {\n cache.delete(key)\n },\n [cache]\n )\n\n const invalidateByTag = useCallback(\n (tag: string | string[]): number => {\n if (Array.isArray(tag)) {\n return cache.invalidateByTag(tag)\n }\n return cache.invalidateByTag(tag)\n },\n [cache]\n )\n\n const clear = useCallback(() => {\n cache.clear()\n }, [cache])\n\n return {\n invalidate,\n invalidateByTag,\n clear,\n }\n}\n","import { useState, useEffect } from 'react'\nimport { useCache } from './useCache'\nimport type { CacheStats, UseCacheStatsOptions } from '../../../types'\n\n/**\n * Hook for real-time cache statistics\n *\n * @example\n * ```tsx\n * function CacheMonitor() {\n * const stats = useCacheStats({ refreshInterval: 1000 })\n *\n * return (\n * <div className=\"cache-monitor\">\n * <div>\n * <span>Hit Rate</span>\n * <span>{(stats.hitRate * 100).toFixed(1)}%</span>\n * </div>\n *\n * <div>\n * <span>Size</span>\n * <span>{stats.size} / {stats.maxSize}</span>\n * </div>\n *\n * <div>\n * <span>Memory</span>\n * <span>{formatBytes(stats.memoryUsage)}</span>\n * </div>\n * </div>\n * )\n * }\n * ```\n */\nexport function useCacheStats(options: UseCacheStatsOptions = {}): CacheStats {\n const cache = useCache()\n const { refreshInterval = 0 } = options\n\n const [stats, setStats] = useState<CacheStats>(() => cache.getStats())\n\n useEffect(() => {\n // Update stats immediately\n setStats(cache.getStats())\n\n // If no refresh interval, just update on mount\n if (!refreshInterval) return\n\n // Setup interval for real-time updates\n const interval = setInterval(() => {\n setStats(cache.getStats())\n }, refreshInterval)\n\n return () => clearInterval(interval)\n }, [cache, refreshInterval])\n\n return stats\n}\n","import type { ComponentType } from 'react'\nimport { useCache } from './hooks/useCache'\nimport type { CacheInstance } from '../../types'\n\n/**\n * Props injected by withCache HOC\n */\nexport interface WithCacheProps<T = unknown> {\n cache: CacheInstance<T>\n}\n\n/**\n * Higher-order component that injects cache instance as a prop\n *\n * @example\n * ```tsx\n * interface MyComponentProps extends WithCacheProps {\n * title: string\n * }\n *\n * function MyComponent({ cache, title }: MyComponentProps) {\n * const data = cache.get('my-key')\n * return <div>{title}: {data}</div>\n * }\n *\n * export default withCache(MyComponent)\n * ```\n */\nexport function withCache<P extends WithCacheProps<T>, T = unknown>(\n WrappedComponent: ComponentType<P>\n): ComponentType<Omit<P, keyof WithCacheProps<T>>> {\n function WithCacheWrapper(props: Omit<P, keyof WithCacheProps<T>>) {\n const cache = useCache<T>()\n return <WrappedComponent {...(props as P)} cache={cache} />\n }\n\n WithCacheWrapper.displayName = `withCache(${WrappedComponent.displayName ?? WrappedComponent.name ?? 'Component'})`\n\n return WithCacheWrapper\n}\n"]}