cacheable 2.0.0 → 2.0.2

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/dist/index.cjs CHANGED
@@ -1 +1,971 @@
1
- "use strict";var A=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var I=(u,t)=>{for(var i in t)A(u,i,{get:t[i],enumerable:!0})},G=(u,t,i,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of F(t))!B.call(u,s)&&s!==i&&A(u,s,{get:()=>t[s],enumerable:!(e=K(t,s))||e.enumerable});return u};var P=u=>G(A({},"__esModule",{value:!0}),u);var C={};I(C,{Cacheable:()=>w,CacheableEvents:()=>R,CacheableHooks:()=>E,CacheableMemory:()=>m.CacheableMemory,CacheableStats:()=>h.Stats,HashAlgorithm:()=>h.HashAlgorithm,Keyv:()=>T.Keyv,KeyvCacheableMemory:()=>m.KeyvCacheableMemory,KeyvHooks:()=>T.KeyvHooks,calculateTtlFromExpiration:()=>h.calculateTtlFromExpiration,createKeyv:()=>m.createKeyv,getCascadingTtl:()=>h.getCascadingTtl,getOrSet:()=>_.getOrSet,hash:()=>h.hash,shorthandToMilliseconds:()=>h.shorthandToMilliseconds,shorthandToTime:()=>h.shorthandToTime,wrap:()=>_.wrap,wrapSync:()=>_.wrapSync});module.exports=P(C);var g=require("@cacheable/memoize"),O=require("@cacheable/memory"),l=require("@cacheable/utils"),M=require("hookified"),f=require("keyv");var E=(o=>(o.BEFORE_SET="BEFORE_SET",o.AFTER_SET="AFTER_SET",o.BEFORE_SET_MANY="BEFORE_SET_MANY",o.AFTER_SET_MANY="AFTER_SET_MANY",o.BEFORE_GET="BEFORE_GET",o.AFTER_GET="AFTER_GET",o.BEFORE_GET_MANY="BEFORE_GET_MANY",o.AFTER_GET_MANY="AFTER_GET_MANY",o.BEFORE_SECONDARY_SETS_PRIMARY="BEFORE_SECONDARY_SETS_PRIMARY",o))(E||{}),R=(e=>(e.ERROR="error",e.CACHE_HIT="cache:hit",e.CACHE_MISS="cache:miss",e))(R||{});var _=require("@cacheable/memoize"),m=require("@cacheable/memory"),h=require("@cacheable/utils"),T=require("keyv"),w=class extends M.Hookified{_primary=(0,O.createKeyv)();_secondary;_nonBlocking=!1;_ttl;_stats=new l.Stats({enabled:!1});_namespace;_cacheId=Math.random().toString(36).slice(2);constructor(t){super(),t?.primary&&this.setPrimary(t.primary),t?.secondary&&this.setSecondary(t.secondary),t?.nonBlocking&&(this._nonBlocking=t.nonBlocking),t?.stats&&(this._stats.enabled=t.stats),t?.ttl&&this.setTtl(t.ttl),t?.cacheId&&(this._cacheId=t.cacheId),t?.namespace&&(this._namespace=t.namespace,this._primary.namespace=this.getNameSpace(),this._secondary&&(this._secondary.namespace=this.getNameSpace()))}get namespace(){return this._namespace}set namespace(t){this._namespace=t,this._primary.namespace=this.getNameSpace(),this._secondary&&(this._secondary.namespace=this.getNameSpace())}get stats(){return this._stats}get primary(){return this._primary}set primary(t){this._primary=t}get secondary(){return this._secondary}set secondary(t){this._secondary=t}get nonBlocking(){return this._nonBlocking}set nonBlocking(t){this._nonBlocking=t}get ttl(){return this._ttl}set ttl(t){this.setTtl(t)}get cacheId(){return this._cacheId}set cacheId(t){this._cacheId=t}setPrimary(t){this.isKeyvInstance(t)?this._primary=t:this._primary=new f.Keyv(t),this._primary.on("error",i=>{this.emit("error",i)})}setSecondary(t){this.isKeyvInstance(t)?this._secondary=t:this._secondary=new f.Keyv(t),this._secondary.on("error",i=>{this.emit("error",i)})}isKeyvInstance(t){return t instanceof f.Keyv?!0:["generateIterator","get","getMany","set","setMany","delete","deleteMany","has","hasMany","clear","disconnect","serialize","deserialize"].every(e=>typeof t[e]=="function")}getNameSpace(){return typeof this._namespace=="function"?this._namespace():this._namespace}async get(t,i){return(await this.getRaw(t,i))?.value}async getRaw(t,i){let e;try{await this.hook("BEFORE_GET",t),e=await this._primary.getRaw(t);let s;e?this.emit("cache:hit",{key:t,value:e.value,store:"primary"}):this.emit("cache:miss",{key:t,store:"primary"});let n=i?.nonBlocking??this._nonBlocking;if(!e&&this._secondary){let a;n?a=await this.processSecondaryForGetRawNonBlocking(this._primary,this._secondary,t):a=await this.processSecondaryForGetRaw(this._primary,this._secondary,t),a&&(e=a.result,s=a.ttl)}await this.hook("AFTER_GET",{key:t,result:e,ttl:s})}catch(s){this.emit("error",s)}return this.stats.enabled&&(e?this._stats.incrementHits():this._stats.incrementMisses(),this.stats.incrementGets()),e}async getManyRaw(t,i){let e=[];try{await this.hook("BEFORE_GET_MANY",t),e=await this._primary.getManyRaw(t);for(let[n,a]of t.entries())e[n]?this.emit("cache:hit",{key:a,value:e[n].value,store:"primary"}):this.emit("cache:miss",{key:a,store:"primary"});let s=i?.nonBlocking??this._nonBlocking;this._secondary&&(s?await this.processSecondaryForGetManyRawNonBlocking(this._primary,this._secondary,t,e):await this.processSecondaryForGetManyRaw(this._primary,this._secondary,t,e)),await this.hook("AFTER_GET_MANY",{keys:t,result:e})}catch(s){this.emit("error",s)}if(this.stats.enabled){for(let s of e)s?this._stats.incrementHits():this._stats.incrementMisses();this.stats.incrementGets()}return e}async getMany(t,i){return(await this.getManyRaw(t,i)).map(s=>s?.value)}async set(t,i,e){let s=!1,n=(0,l.shorthandToMilliseconds)(e??this._ttl);try{let a={key:t,value:i,ttl:n};await this.hook("BEFORE_SET",a);let r=[];if(r.push(this._primary.set(a.key,a.value,a.ttl)),this._secondary&&r.push(this._secondary.set(a.key,a.value,a.ttl)),this._nonBlocking){s=await Promise.race(r);for(let c of r)c.catch(o=>{this.emit("error",o)})}else s=(await Promise.all(r))[0];await this.hook("AFTER_SET",a)}catch(a){this.emit("error",a)}return this.stats.enabled&&(this.stats.incrementKSize(t),this.stats.incrementCount(),this.stats.incrementVSize(i),this.stats.incrementSets()),s}async setMany(t){let i=!1;try{await this.hook("BEFORE_SET_MANY",t),i=await this.setManyKeyv(this._primary,t),this._secondary&&(this._nonBlocking?this.setManyKeyv(this._secondary,t).catch(e=>{this.emit("error",e)}):await this.setManyKeyv(this._secondary,t)),await this.hook("AFTER_SET_MANY",t)}catch(e){this.emit("error",e)}if(this.stats.enabled)for(let e of t)this.stats.incrementKSize(e.key),this.stats.incrementCount(),this.stats.incrementVSize(e.value);return i}async take(t){let i=await this.get(t);return await this.delete(t),i}async takeMany(t){let i=await this.getMany(t);return await this.deleteMany(t),i}async has(t){let i=[];i.push(this._primary.has(t)),this._secondary&&i.push(this._secondary.has(t));let e=await Promise.all(i);for(let s of e)if(s)return!0;return!1}async hasMany(t){let i=await this.hasManyKeyv(this._primary,t),e=[];for(let[s,n]of t.entries())!i[s]&&this._secondary&&e.push(n);if(e.length>0&&this._secondary){let s=await this.hasManyKeyv(this._secondary,t);for(let[n,a]of t.entries())!i[n]&&s[n]&&(i[n]=s[n])}return i}async delete(t){let i=!1,e=[];if(this.stats.enabled){let s=await this._primary.get(t);s&&(this.stats.decreaseKSize(t),this.stats.decreaseVSize(s),this.stats.decreaseCount(),this.stats.incrementDeletes())}if(e.push(this._primary.delete(t)),this._secondary&&e.push(this._secondary.delete(t)),this.nonBlocking){i=await Promise.race(e);for(let s of e)s.catch(n=>{this.emit("error",n)})}else i=(await Promise.all(e))[0];return i}async deleteMany(t){if(this.stats.enabled){let e=await this._primary.get(t);for(let s of t)this.stats.decreaseKSize(s),this.stats.decreaseVSize(e),this.stats.decreaseCount(),this.stats.incrementDeletes()}let i=await this._primary.deleteMany(t);return this._secondary&&(this._nonBlocking?this._secondary.deleteMany(t).catch(e=>{this.emit("error",e)}):await this._secondary.deleteMany(t)),i}async clear(){let t=[];t.push(this._primary.clear()),this._secondary&&t.push(this._secondary.clear()),await(this._nonBlocking?Promise.race(t):Promise.all(t)),this.stats.enabled&&(this._stats.resetStoreValues(),this._stats.incrementClears())}async disconnect(){let t=[];t.push(this._primary.disconnect()),this._secondary&&t.push(this._secondary.disconnect()),await(this._nonBlocking?Promise.race(t):Promise.all(t))}wrap(t,i){let e={get:async n=>this.get(n),has:async n=>this.has(n),set:async(n,a,r)=>{await this.set(n,a,r)},on:(n,a)=>{this.on(n,a)},emit:(n,...a)=>this.emit(n,...a)},s={ttl:i?.ttl??this._ttl,keyPrefix:i?.keyPrefix,createKey:i?.createKey,cacheErrors:i?.cacheErrors,cache:e,cacheId:this._cacheId,serialize:i?.serialize};return(0,g.wrap)(t,s)}async getOrSet(t,i,e){let n={cache:{get:async a=>this.get(a),has:async a=>this.has(a),set:async(a,r,c)=>{await this.set(a,r,c)},on:(a,r)=>{this.on(a,r)},emit:(a,...r)=>this.emit(a,...r)},cacheId:this._cacheId,ttl:e?.ttl??this._ttl,cacheErrors:e?.cacheErrors,throwErrors:e?.throwErrors};return(0,g.getOrSet)(t,i,n)}hash(t,i=l.HashAlgorithm.SHA256){let e=Object.values(l.HashAlgorithm).includes(i)?i:l.HashAlgorithm.SHA256;return(0,l.hash)(t,{algorithm:e})}async setManyKeyv(t,i){let e=[];for(let s of i){let n=(0,l.shorthandToMilliseconds)(s.ttl??this._ttl);e.push({key:s.key,value:s.value,ttl:n})}return await t.setMany(e),!0}async hasManyKeyv(t,i){let e=[];for(let s of i)e.push(t.has(s));return Promise.all(e)}async processSecondaryForGetRaw(t,i,e){let s=await i.getRaw(e);if(s?.value){this.emit("cache:hit",{key:e,value:s.value,store:"secondary"});let n=(0,l.getCascadingTtl)(this._ttl,this._primary.ttl),a=s.expires??void 0,r=(0,l.calculateTtlFromExpiration)(n,a),c={key:e,value:s.value,ttl:r};return await this.hook("BEFORE_SECONDARY_SETS_PRIMARY",c),await t.set(c.key,c.value,c.ttl),{result:s,ttl:r}}else{this.emit("cache:miss",{key:e,store:"secondary"});return}}async processSecondaryForGetRawNonBlocking(t,i,e){let s=await i.getRaw(e);if(s?.value){this.emit("cache:hit",{key:e,value:s.value,store:"secondary"});let n=(0,l.getCascadingTtl)(this._ttl,this._primary.ttl),a=s.expires??void 0,r=(0,l.calculateTtlFromExpiration)(n,a),c={key:e,value:s.value,ttl:r};return this.hook("BEFORE_SECONDARY_SETS_PRIMARY",c).then(async()=>{await t.set(c.key,c.value,c.ttl)}).catch(o=>{this.emit("error",o)}),{result:s,ttl:r}}else{this.emit("cache:miss",{key:e,store:"secondary"});return}}async processSecondaryForGetManyRaw(t,i,e,s){let n=[];for(let[c,o]of e.entries())s[c]||n.push(o);let a=await i.getManyRaw(n),r=0;for await(let[c,o]of e.entries())if(!s[c]){let y=a[r];if(y&&y.value!==void 0){s[c]=y,this.emit("cache:hit",{key:o,value:y.value,store:"secondary"});let S=(0,l.getCascadingTtl)(this._ttl,this._primary.ttl),{expires:d}=y;d===null&&(d=void 0);let v=(0,l.calculateTtlFromExpiration)(S,d),p={key:o,value:y.value,ttl:v};await this.hook("BEFORE_SECONDARY_SETS_PRIMARY",p),await t.set(p.key,p.value,p.ttl)}else this.emit("cache:miss",{key:o,store:"secondary"});r++}}async processSecondaryForGetManyRawNonBlocking(t,i,e,s){let n=[];for(let[c,o]of e.entries())s[c]||n.push(o);let a=await i.getManyRaw(n),r=0;for await(let[c,o]of e.entries())if(!s[c]){let y=a[r];if(y&&y.value!==void 0){s[c]=y,this.emit("cache:hit",{key:o,value:y.value,store:"secondary"});let S=(0,l.getCascadingTtl)(this._ttl,this._primary.ttl),{expires:d}=y;d===null&&(d=void 0);let v=(0,l.calculateTtlFromExpiration)(S,d),p={key:o,value:y.value,ttl:v};this.hook("BEFORE_SECONDARY_SETS_PRIMARY",p).then(async()=>{await t.set(p.key,p.value,p.ttl)}).catch(b=>{this.emit("error",b)})}else this.emit("cache:miss",{key:o,store:"secondary"});r++}}setTtl(t){typeof t=="string"||t===void 0?this._ttl=t:t>0?this._ttl=t:this._ttl=void 0}};0&&(module.exports={Cacheable,CacheableEvents,CacheableHooks,CacheableMemory,CacheableStats,HashAlgorithm,Keyv,KeyvCacheableMemory,KeyvHooks,calculateTtlFromExpiration,createKeyv,getCascadingTtl,getOrSet,hash,shorthandToMilliseconds,shorthandToTime,wrap,wrapSync});
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Cacheable: () => Cacheable,
24
+ CacheableEvents: () => CacheableEvents,
25
+ CacheableHooks: () => CacheableHooks,
26
+ CacheableMemory: () => import_memory2.CacheableMemory,
27
+ CacheableStats: () => import_utils2.Stats,
28
+ HashAlgorithm: () => import_utils2.HashAlgorithm,
29
+ Keyv: () => import_keyv2.Keyv,
30
+ KeyvCacheableMemory: () => import_memory2.KeyvCacheableMemory,
31
+ KeyvHooks: () => import_keyv2.KeyvHooks,
32
+ calculateTtlFromExpiration: () => import_utils2.calculateTtlFromExpiration,
33
+ createKeyv: () => import_memory2.createKeyv,
34
+ getCascadingTtl: () => import_utils2.getCascadingTtl,
35
+ getOrSet: () => import_memoize2.getOrSet,
36
+ hash: () => import_utils2.hash,
37
+ shorthandToMilliseconds: () => import_utils2.shorthandToMilliseconds,
38
+ shorthandToTime: () => import_utils2.shorthandToTime,
39
+ wrap: () => import_memoize2.wrap,
40
+ wrapSync: () => import_memoize2.wrapSync
41
+ });
42
+ module.exports = __toCommonJS(index_exports);
43
+ var import_memoize = require("@cacheable/memoize");
44
+ var import_memory = require("@cacheable/memory");
45
+ var import_utils = require("@cacheable/utils");
46
+ var import_hookified = require("hookified");
47
+ var import_keyv = require("keyv");
48
+
49
+ // src/enums.ts
50
+ var CacheableHooks = /* @__PURE__ */ ((CacheableHooks2) => {
51
+ CacheableHooks2["BEFORE_SET"] = "BEFORE_SET";
52
+ CacheableHooks2["AFTER_SET"] = "AFTER_SET";
53
+ CacheableHooks2["BEFORE_SET_MANY"] = "BEFORE_SET_MANY";
54
+ CacheableHooks2["AFTER_SET_MANY"] = "AFTER_SET_MANY";
55
+ CacheableHooks2["BEFORE_GET"] = "BEFORE_GET";
56
+ CacheableHooks2["AFTER_GET"] = "AFTER_GET";
57
+ CacheableHooks2["BEFORE_GET_MANY"] = "BEFORE_GET_MANY";
58
+ CacheableHooks2["AFTER_GET_MANY"] = "AFTER_GET_MANY";
59
+ CacheableHooks2["BEFORE_SECONDARY_SETS_PRIMARY"] = "BEFORE_SECONDARY_SETS_PRIMARY";
60
+ return CacheableHooks2;
61
+ })(CacheableHooks || {});
62
+ var CacheableEvents = /* @__PURE__ */ ((CacheableEvents2) => {
63
+ CacheableEvents2["ERROR"] = "error";
64
+ CacheableEvents2["CACHE_HIT"] = "cache:hit";
65
+ CacheableEvents2["CACHE_MISS"] = "cache:miss";
66
+ return CacheableEvents2;
67
+ })(CacheableEvents || {});
68
+
69
+ // src/index.ts
70
+ var import_memoize2 = require("@cacheable/memoize");
71
+ var import_memory2 = require("@cacheable/memory");
72
+ var import_utils2 = require("@cacheable/utils");
73
+ var import_keyv2 = require("keyv");
74
+ var Cacheable = class extends import_hookified.Hookified {
75
+ _primary = (0, import_memory.createKeyv)();
76
+ _secondary;
77
+ _nonBlocking = false;
78
+ _ttl;
79
+ _stats = new import_utils.Stats({ enabled: false });
80
+ _namespace;
81
+ _cacheId = Math.random().toString(36).slice(2);
82
+ /**
83
+ * Creates a new cacheable instance
84
+ * @param {CacheableOptions} [options] The options for the cacheable instance
85
+ */
86
+ constructor(options) {
87
+ super();
88
+ if (options?.primary) {
89
+ this.setPrimary(options.primary);
90
+ }
91
+ if (options?.secondary) {
92
+ this.setSecondary(options.secondary);
93
+ }
94
+ if (options?.nonBlocking) {
95
+ this._nonBlocking = options.nonBlocking;
96
+ }
97
+ if (options?.stats) {
98
+ this._stats.enabled = options.stats;
99
+ }
100
+ if (options?.ttl) {
101
+ this.setTtl(options.ttl);
102
+ }
103
+ if (options?.cacheId) {
104
+ this._cacheId = options.cacheId;
105
+ }
106
+ if (options?.namespace) {
107
+ this._namespace = options.namespace;
108
+ this._primary.namespace = this.getNameSpace();
109
+ if (this._secondary) {
110
+ this._secondary.namespace = this.getNameSpace();
111
+ }
112
+ }
113
+ }
114
+ /**
115
+ * The namespace for the cacheable instance
116
+ * @returns {string | (() => string) | undefined} The namespace for the cacheable instance
117
+ */
118
+ get namespace() {
119
+ return this._namespace;
120
+ }
121
+ /**
122
+ * Sets the namespace for the cacheable instance
123
+ * @param {string | (() => string) | undefined} namespace The namespace for the cacheable instance
124
+ * @returns {void}
125
+ */
126
+ set namespace(namespace) {
127
+ this._namespace = namespace;
128
+ this._primary.namespace = this.getNameSpace();
129
+ if (this._secondary) {
130
+ this._secondary.namespace = this.getNameSpace();
131
+ }
132
+ }
133
+ /**
134
+ * The statistics for the cacheable instance
135
+ * @returns {CacheableStats} The statistics for the cacheable instance
136
+ */
137
+ get stats() {
138
+ return this._stats;
139
+ }
140
+ /**
141
+ * The primary store for the cacheable instance
142
+ * @returns {Keyv} The primary store for the cacheable instance
143
+ */
144
+ get primary() {
145
+ return this._primary;
146
+ }
147
+ /**
148
+ * Sets the primary store for the cacheable instance
149
+ * @param {Keyv} primary The primary store for the cacheable instance
150
+ */
151
+ set primary(primary) {
152
+ this._primary = primary;
153
+ }
154
+ /**
155
+ * The secondary store for the cacheable instance
156
+ * @returns {Keyv | undefined} The secondary store for the cacheable instance
157
+ */
158
+ get secondary() {
159
+ return this._secondary;
160
+ }
161
+ /**
162
+ * Sets the secondary store for the cacheable instance. If it is set to undefined then the secondary store is disabled.
163
+ * @param {Keyv | undefined} secondary The secondary store for the cacheable instance
164
+ * @returns {void}
165
+ */
166
+ set secondary(secondary) {
167
+ this._secondary = secondary;
168
+ }
169
+ /**
170
+ * Gets whether the secondary store is non-blocking mode. It is set to false by default.
171
+ * If it is set to true then the secondary store will not block the primary store.
172
+ *
173
+ * [Learn more about non-blocking mode](https://cacheable.org/docs/cacheable/#non-blocking-operations).
174
+ *
175
+ * @returns {boolean} Whether the cacheable instance is non-blocking
176
+ */
177
+ get nonBlocking() {
178
+ return this._nonBlocking;
179
+ }
180
+ /**
181
+ * Sets whether the secondary store is non-blocking mode. It is set to false by default.
182
+ * If it is set to true then the secondary store will not block the primary store.
183
+ *
184
+ * [Learn more about non-blocking mode](https://cacheable.org/docs/cacheable/#non-blocking-operations).
185
+ *
186
+ * @param {boolean} nonBlocking Whether the cacheable instance is non-blocking
187
+ * @returns {void}
188
+ */
189
+ set nonBlocking(nonBlocking) {
190
+ this._nonBlocking = nonBlocking;
191
+ }
192
+ /**
193
+ * The time-to-live for the cacheable instance and will be used as the default value.
194
+ * can be a number in milliseconds or a human-readable format such as `1s` for 1 second or `1h` for 1 hour
195
+ * or undefined if there is no time-to-live.
196
+ *
197
+ * [Learn more about time-to-live](https://cacheable.org/docs/cacheable/#shorthand-for-time-to-live-ttl).
198
+ *
199
+ * @returns {number | string | undefined} The time-to-live for the cacheable instance in milliseconds, human-readable format or undefined
200
+ * @example
201
+ * ```typescript
202
+ * const cacheable = new Cacheable({ ttl: '1h' });
203
+ * console.log(cacheable.ttl); // 1h
204
+ * ```
205
+ */
206
+ get ttl() {
207
+ return this._ttl;
208
+ }
209
+ /**
210
+ * Sets the time-to-live for the cacheable instance and will be used as the default value.
211
+ * If you set a number it is miliseconds, if you set a string it is a human-readable
212
+ * format such as `1s` for 1 second or `1h` for 1 hour. Setting undefined means that
213
+ * there is no time-to-live.
214
+ *
215
+ * [Learn more about time-to-live](https://cacheable.org/docs/cacheable/#shorthand-for-time-to-live-ttl).
216
+ *
217
+ * @param {number | string | undefined} ttl The time-to-live for the cacheable instance
218
+ * @example
219
+ * ```typescript
220
+ * const cacheable = new Cacheable();
221
+ * cacheable.ttl = '1h'; // Set the time-to-live to 1 hour
222
+ * ```
223
+ * or setting the time-to-live in milliseconds
224
+ * ```typescript
225
+ * const cacheable = new Cacheable();
226
+ * cacheable.ttl = 3600000; // Set the time-to-live to 1 hour
227
+ * ```
228
+ */
229
+ set ttl(ttl) {
230
+ this.setTtl(ttl);
231
+ }
232
+ /**
233
+ * The cacheId for the cacheable instance. This is primarily used for the wrap function to not have conflicts.
234
+ * If it is not set then it will be a random string that is generated
235
+ * @returns {string} The cacheId for the cacheable instance
236
+ */
237
+ get cacheId() {
238
+ return this._cacheId;
239
+ }
240
+ /**
241
+ * Sets the cacheId for the cacheable instance. This is primarily used for the wrap function to not have conflicts.
242
+ * If it is not set then it will be a random string that is generated
243
+ * @param {string} cacheId The cacheId for the cacheable instance
244
+ */
245
+ set cacheId(cacheId) {
246
+ this._cacheId = cacheId;
247
+ }
248
+ /**
249
+ * Sets the primary store for the cacheable instance
250
+ * @param {Keyv | KeyvStoreAdapter} primary The primary store for the cacheable instance
251
+ * @returns {void}
252
+ */
253
+ setPrimary(primary) {
254
+ if (this.isKeyvInstance(primary)) {
255
+ this._primary = primary;
256
+ } else {
257
+ this._primary = new import_keyv.Keyv(primary);
258
+ }
259
+ this._primary.on("error", (error) => {
260
+ this.emit("error" /* ERROR */, error);
261
+ });
262
+ }
263
+ /**
264
+ * Sets the secondary store for the cacheable instance. If it is set to undefined then the secondary store is disabled.
265
+ * @param {Keyv | KeyvStoreAdapter} secondary The secondary store for the cacheable instance
266
+ * @returns {void}
267
+ */
268
+ setSecondary(secondary) {
269
+ if (this.isKeyvInstance(secondary)) {
270
+ this._secondary = secondary;
271
+ } else {
272
+ this._secondary = new import_keyv.Keyv(secondary);
273
+ }
274
+ this._secondary.on("error", (error) => {
275
+ this.emit("error" /* ERROR */, error);
276
+ });
277
+ }
278
+ // biome-ignore lint/suspicious/noExplicitAny: type format
279
+ isKeyvInstance(keyv) {
280
+ if (keyv instanceof import_keyv.Keyv) {
281
+ return true;
282
+ }
283
+ const keyvMethods = [
284
+ "generateIterator",
285
+ "get",
286
+ "getMany",
287
+ "set",
288
+ "setMany",
289
+ "delete",
290
+ "deleteMany",
291
+ "has",
292
+ "hasMany",
293
+ "clear",
294
+ "disconnect",
295
+ "serialize",
296
+ "deserialize"
297
+ ];
298
+ return keyvMethods.every((method) => typeof keyv[method] === "function");
299
+ }
300
+ getNameSpace() {
301
+ if (typeof this._namespace === "function") {
302
+ return this._namespace();
303
+ }
304
+ return this._namespace;
305
+ }
306
+ /**
307
+ * Retrieves an entry from the cache.
308
+ *
309
+ * Checks the primary store first; if not found and a secondary store is configured,
310
+ * it will fetch from the secondary, repopulate the primary, and return the result.
311
+ *
312
+ * @typeParam T - The expected type of the stored value.
313
+ * @param {string} key - The cache key to retrieve.
314
+ * @param {GetOptions} - options such as to bypass `nonBlocking` for this call
315
+ * @returns {Promise<T | undefined>}
316
+ * A promise that resolves to the cached value if found, or `undefined`.
317
+ */
318
+ async get(key, options) {
319
+ const result = await this.getRaw(key, options);
320
+ return result?.value;
321
+ }
322
+ /**
323
+ * Retrieves the raw entry from the cache including metadata like expiration.
324
+ *
325
+ * Checks the primary store first; if not found and a secondary store is configured,
326
+ * it will fetch from the secondary, repopulate the primary, and return the result.
327
+ *
328
+ * @typeParam T - The expected type of the stored value.
329
+ * @param {string} key - The cache key to retrieve.
330
+ * @param {GetOptions} - options such as to bypass `nonBlocking` for this call
331
+ * @returns {Promise<StoredDataRaw<T>>}
332
+ * A promise that resolves to the full raw data object if found, or undefined.
333
+ */
334
+ async getRaw(key, options) {
335
+ let result;
336
+ try {
337
+ await this.hook("BEFORE_GET" /* BEFORE_GET */, key);
338
+ result = await this._primary.getRaw(key);
339
+ let ttl;
340
+ if (result) {
341
+ this.emit("cache:hit" /* CACHE_HIT */, {
342
+ key,
343
+ value: result.value,
344
+ store: "primary"
345
+ });
346
+ } else {
347
+ this.emit("cache:miss" /* CACHE_MISS */, { key, store: "primary" });
348
+ }
349
+ const nonBlocking = options?.nonBlocking ?? this._nonBlocking;
350
+ if (!result && this._secondary) {
351
+ let secondaryProcessResult;
352
+ if (nonBlocking) {
353
+ secondaryProcessResult = await this.processSecondaryForGetRawNonBlocking(
354
+ this._primary,
355
+ this._secondary,
356
+ key
357
+ );
358
+ } else {
359
+ secondaryProcessResult = await this.processSecondaryForGetRaw(
360
+ this._primary,
361
+ this._secondary,
362
+ key
363
+ );
364
+ }
365
+ if (secondaryProcessResult) {
366
+ result = secondaryProcessResult.result;
367
+ ttl = secondaryProcessResult.ttl;
368
+ }
369
+ }
370
+ await this.hook("AFTER_GET" /* AFTER_GET */, { key, result, ttl });
371
+ } catch (error) {
372
+ this.emit("error" /* ERROR */, error);
373
+ }
374
+ if (this.stats.enabled) {
375
+ if (result) {
376
+ this._stats.incrementHits();
377
+ } else {
378
+ this._stats.incrementMisses();
379
+ }
380
+ this.stats.incrementGets();
381
+ }
382
+ return result;
383
+ }
384
+ /**
385
+ * Retrieves multiple raw entries from the cache including metadata like expiration.
386
+ *
387
+ * Checks the primary store for each key; if a key is missing and a secondary store is configured,
388
+ * it will fetch from the secondary store, repopulate the primary store, and return the results.
389
+ *
390
+ * @typeParam T - The expected type of the stored values.
391
+ * @param {string[]} keys - The cache keys to retrieve.
392
+ * @param {GetOptions} - options such as to bypass `nonBlocking` on this call
393
+ * @returns {Promise<Array<StoredDataRaw<T>>>}
394
+ * A promise that resolves to an array of raw data objects.
395
+ */
396
+ async getManyRaw(keys, options) {
397
+ let result = [];
398
+ try {
399
+ await this.hook("BEFORE_GET_MANY" /* BEFORE_GET_MANY */, keys);
400
+ result = await this._primary.getManyRaw(keys);
401
+ for (const [i, key] of keys.entries()) {
402
+ if (result[i]) {
403
+ this.emit("cache:hit" /* CACHE_HIT */, {
404
+ key,
405
+ value: result[i].value,
406
+ store: "primary"
407
+ });
408
+ } else {
409
+ this.emit("cache:miss" /* CACHE_MISS */, { key, store: "primary" });
410
+ }
411
+ }
412
+ const nonBlocking = options?.nonBlocking ?? this._nonBlocking;
413
+ if (this._secondary) {
414
+ if (nonBlocking) {
415
+ await this.processSecondaryForGetManyRawNonBlocking(
416
+ this._primary,
417
+ this._secondary,
418
+ keys,
419
+ result
420
+ );
421
+ } else {
422
+ await this.processSecondaryForGetManyRaw(
423
+ this._primary,
424
+ this._secondary,
425
+ keys,
426
+ result
427
+ );
428
+ }
429
+ }
430
+ await this.hook("AFTER_GET_MANY" /* AFTER_GET_MANY */, { keys, result });
431
+ } catch (error) {
432
+ this.emit("error" /* ERROR */, error);
433
+ }
434
+ if (this.stats.enabled) {
435
+ for (const item of result) {
436
+ if (item) {
437
+ this._stats.incrementHits();
438
+ } else {
439
+ this._stats.incrementMisses();
440
+ }
441
+ }
442
+ this.stats.incrementGets();
443
+ }
444
+ return result;
445
+ }
446
+ /**
447
+ * Retrieves multiple entries from the cache.
448
+ * Checks the primary store for each key; if a key is missing and a secondary store is configured,
449
+ * it will fetch from the secondary store, repopulate the primary store, and return the results.
450
+ *
451
+ * @typeParam T - The expected type of the stored values.
452
+ * @param {string[]} keys - The cache keys to retrieve.
453
+ * @param {GetOptions} - options such as to bypass `nonBlocking` on this call
454
+ * @returns {Promise<Array<T | undefined>>}
455
+ * A promise that resolves to an array of cached values or `undefined` for misses.
456
+ */
457
+ async getMany(keys, options) {
458
+ const result = await this.getManyRaw(keys, options);
459
+ return result.map((item) => item?.value);
460
+ }
461
+ /**
462
+ * Sets the value of the key. If the secondary store is set then it will also set the value in the secondary store.
463
+ * @param {string} key the key to set the value of
464
+ * @param {T} value The value to set
465
+ * @param {number | string} [ttl] set a number it is miliseconds, set a string it is a human-readable
466
+ * format such as `1s` for 1 second or `1h` for 1 hour. Setting undefined means that it will use the default time-to-live.
467
+ * @returns {boolean} Whether the value was set
468
+ */
469
+ async set(key, value, ttl) {
470
+ let result = false;
471
+ const finalTtl = (0, import_utils.shorthandToMilliseconds)(ttl ?? this._ttl);
472
+ try {
473
+ const item = { key, value, ttl: finalTtl };
474
+ await this.hook("BEFORE_SET" /* BEFORE_SET */, item);
475
+ const promises = [];
476
+ promises.push(this._primary.set(item.key, item.value, item.ttl));
477
+ if (this._secondary) {
478
+ promises.push(this._secondary.set(item.key, item.value, item.ttl));
479
+ }
480
+ if (this._nonBlocking) {
481
+ result = await Promise.race(promises);
482
+ for (const promise of promises) {
483
+ promise.catch((error) => {
484
+ this.emit("error" /* ERROR */, error);
485
+ });
486
+ }
487
+ } else {
488
+ const results = await Promise.all(promises);
489
+ result = results[0];
490
+ }
491
+ await this.hook("AFTER_SET" /* AFTER_SET */, item);
492
+ } catch (error) {
493
+ this.emit("error" /* ERROR */, error);
494
+ }
495
+ if (this.stats.enabled) {
496
+ this.stats.incrementKSize(key);
497
+ this.stats.incrementCount();
498
+ this.stats.incrementVSize(value);
499
+ this.stats.incrementSets();
500
+ }
501
+ return result;
502
+ }
503
+ /**
504
+ * Sets the values of the keys. If the secondary store is set then it will also set the values in the secondary store.
505
+ * @param {CacheableItem[]} items The items to set
506
+ * @returns {boolean} Whether the values were set
507
+ */
508
+ async setMany(items) {
509
+ let result = false;
510
+ try {
511
+ await this.hook("BEFORE_SET_MANY" /* BEFORE_SET_MANY */, items);
512
+ result = await this.setManyKeyv(this._primary, items);
513
+ if (this._secondary) {
514
+ if (this._nonBlocking) {
515
+ this.setManyKeyv(this._secondary, items).catch((error) => {
516
+ this.emit("error" /* ERROR */, error);
517
+ });
518
+ } else {
519
+ await this.setManyKeyv(this._secondary, items);
520
+ }
521
+ }
522
+ await this.hook("AFTER_SET_MANY" /* AFTER_SET_MANY */, items);
523
+ } catch (error) {
524
+ this.emit("error" /* ERROR */, error);
525
+ }
526
+ if (this.stats.enabled) {
527
+ for (const item of items) {
528
+ this.stats.incrementKSize(item.key);
529
+ this.stats.incrementCount();
530
+ this.stats.incrementVSize(item.value);
531
+ }
532
+ }
533
+ return result;
534
+ }
535
+ /**
536
+ * Takes the value of the key and deletes the key. If the key does not exist then it will return undefined.
537
+ * @param {string} key The key to take the value of
538
+ * @returns {Promise<T | undefined>} The value of the key or undefined if the key does not exist
539
+ */
540
+ async take(key) {
541
+ const result = await this.get(key);
542
+ await this.delete(key);
543
+ return result;
544
+ }
545
+ /**
546
+ * Takes the values of the keys and deletes the keys. If the key does not exist then it will return undefined.
547
+ * @param {string[]} keys The keys to take the values of
548
+ * @returns {Promise<Array<T | undefined>>} The values of the keys or undefined if the key does not exist
549
+ */
550
+ async takeMany(keys) {
551
+ const result = await this.getMany(keys);
552
+ await this.deleteMany(keys);
553
+ return result;
554
+ }
555
+ /**
556
+ * Checks if the key exists in the primary store. If it does not exist then it will check the secondary store.
557
+ * @param {string} key The key to check
558
+ * @returns {Promise<boolean>} Whether the key exists
559
+ */
560
+ async has(key) {
561
+ const promises = [];
562
+ promises.push(this._primary.has(key));
563
+ if (this._secondary) {
564
+ promises.push(this._secondary.has(key));
565
+ }
566
+ const resultAll = await Promise.all(promises);
567
+ for (const result of resultAll) {
568
+ if (result) {
569
+ return true;
570
+ }
571
+ }
572
+ return false;
573
+ }
574
+ /**
575
+ * Checks if the keys exist in the primary store. If it does not exist then it will check the secondary store.
576
+ * @param {string[]} keys The keys to check
577
+ * @returns {Promise<boolean[]>} Whether the keys exist
578
+ */
579
+ async hasMany(keys) {
580
+ const result = await this.hasManyKeyv(this._primary, keys);
581
+ const missingKeys = [];
582
+ for (const [i, key] of keys.entries()) {
583
+ if (!result[i] && this._secondary) {
584
+ missingKeys.push(key);
585
+ }
586
+ }
587
+ if (missingKeys.length > 0 && this._secondary) {
588
+ const secondary = await this.hasManyKeyv(this._secondary, keys);
589
+ for (const [i, _key] of keys.entries()) {
590
+ if (!result[i] && secondary[i]) {
591
+ result[i] = secondary[i];
592
+ }
593
+ }
594
+ }
595
+ return result;
596
+ }
597
+ /**
598
+ * Deletes the key from the primary store. If the secondary store is set then it will also delete the key from the secondary store.
599
+ * @param {string} key The key to delete
600
+ * @returns {Promise<boolean>} Whether the key was deleted
601
+ */
602
+ async delete(key) {
603
+ let result = false;
604
+ const promises = [];
605
+ if (this.stats.enabled) {
606
+ const statResult = await this._primary.get(key);
607
+ if (statResult) {
608
+ this.stats.decreaseKSize(key);
609
+ this.stats.decreaseVSize(statResult);
610
+ this.stats.decreaseCount();
611
+ this.stats.incrementDeletes();
612
+ }
613
+ }
614
+ promises.push(this._primary.delete(key));
615
+ if (this._secondary) {
616
+ promises.push(this._secondary.delete(key));
617
+ }
618
+ if (this.nonBlocking) {
619
+ result = await Promise.race(promises);
620
+ for (const promise of promises) {
621
+ promise.catch((error) => {
622
+ this.emit("error" /* ERROR */, error);
623
+ });
624
+ }
625
+ } else {
626
+ const resultAll = await Promise.all(promises);
627
+ result = resultAll[0];
628
+ }
629
+ return result;
630
+ }
631
+ /**
632
+ * Deletes the keys from the primary store. If the secondary store is set then it will also delete the keys from the secondary store.
633
+ * @param {string[]} keys The keys to delete
634
+ * @returns {Promise<boolean>} Whether the keys were deleted
635
+ */
636
+ async deleteMany(keys) {
637
+ if (this.stats.enabled) {
638
+ const statResult = await this._primary.get(keys);
639
+ for (const key of keys) {
640
+ this.stats.decreaseKSize(key);
641
+ this.stats.decreaseVSize(statResult);
642
+ this.stats.decreaseCount();
643
+ this.stats.incrementDeletes();
644
+ }
645
+ }
646
+ const result = await this._primary.deleteMany(keys);
647
+ if (this._secondary) {
648
+ if (this._nonBlocking) {
649
+ this._secondary.deleteMany(keys).catch((error) => {
650
+ this.emit("error" /* ERROR */, error);
651
+ });
652
+ } else {
653
+ await this._secondary.deleteMany(keys);
654
+ }
655
+ }
656
+ return result;
657
+ }
658
+ /**
659
+ * Clears the primary store. If the secondary store is set then it will also clear the secondary store.
660
+ * @returns {Promise<void>}
661
+ */
662
+ async clear() {
663
+ const promises = [];
664
+ promises.push(this._primary.clear());
665
+ if (this._secondary) {
666
+ promises.push(this._secondary.clear());
667
+ }
668
+ await (this._nonBlocking ? Promise.race(promises) : Promise.all(promises));
669
+ if (this.stats.enabled) {
670
+ this._stats.resetStoreValues();
671
+ this._stats.incrementClears();
672
+ }
673
+ }
674
+ /**
675
+ * Disconnects the primary store. If the secondary store is set then it will also disconnect the secondary store.
676
+ * @returns {Promise<void>}
677
+ */
678
+ async disconnect() {
679
+ const promises = [];
680
+ promises.push(this._primary.disconnect());
681
+ if (this._secondary) {
682
+ promises.push(this._secondary.disconnect());
683
+ }
684
+ await (this._nonBlocking ? Promise.race(promises) : Promise.all(promises));
685
+ }
686
+ /**
687
+ * Wraps a function with caching
688
+ *
689
+ * [Learn more about wrapping functions](https://cacheable.org/docs/cacheable/#wrap--memoization-for-sync-and-async-functions).
690
+ * @param {Function} function_ The function to wrap
691
+ * @param {WrapOptions} [options] The options for the wrap function
692
+ * @returns {Function} The wrapped function
693
+ */
694
+ // biome-ignore lint/suspicious/noExplicitAny: type format
695
+ wrap(function_, options) {
696
+ const cacheAdapter = {
697
+ get: async (key) => this.get(key),
698
+ has: async (key) => this.has(key),
699
+ // biome-ignore lint/suspicious/noExplicitAny: CacheInstance requires any type
700
+ set: async (key, value, ttl) => {
701
+ await this.set(key, value, ttl);
702
+ },
703
+ /* c8 ignore start */
704
+ // biome-ignore lint/suspicious/noExplicitAny: CacheInstance interface
705
+ on: (event, listener) => {
706
+ this.on(event, listener);
707
+ },
708
+ /* c8 ignore stop */
709
+ // biome-ignore lint/suspicious/noExplicitAny: CacheInstance requires any type
710
+ emit: (event, ...args) => this.emit(event, ...args)
711
+ };
712
+ const wrapOptions = {
713
+ ttl: options?.ttl ?? this._ttl,
714
+ keyPrefix: options?.keyPrefix,
715
+ createKey: options?.createKey,
716
+ cacheErrors: options?.cacheErrors,
717
+ cache: cacheAdapter,
718
+ cacheId: this._cacheId,
719
+ serialize: options?.serialize
720
+ };
721
+ return (0, import_memoize.wrap)(function_, wrapOptions);
722
+ }
723
+ /**
724
+ * Retrieves the value associated with the given key from the cache. If the key is not found,
725
+ * invokes the provided function to calculate the value, stores it in the cache, and then returns it.
726
+ *
727
+ * @param {GetOrSetKey} key - The key to retrieve or set in the cache. This can also be a function that returns a string key.
728
+ * If a function is provided, it will be called with the cache options to generate the key.
729
+ * @param {() => Promise<T>} function_ - The asynchronous function that computes the value to be cached if the key does not exist.
730
+ * @param {GetOrSetFunctionOptions} [options] - Optional settings for caching, such as the time to live (TTL) or whether to cache errors.
731
+ * @return {Promise<T | undefined>} - A promise that resolves to the cached or newly computed value, or undefined if an error occurs and caching is not configured for errors.
732
+ */
733
+ async getOrSet(key, function_, options) {
734
+ const cacheAdapter = {
735
+ get: async (key2) => this.get(key2),
736
+ has: async (key2) => this.has(key2),
737
+ // biome-ignore lint/suspicious/noExplicitAny: CacheInstance requires any type
738
+ set: async (key2, value, ttl) => {
739
+ await this.set(key2, value, ttl);
740
+ },
741
+ /* c8 ignore start */
742
+ // biome-ignore lint/suspicious/noExplicitAny: CacheInstance interface
743
+ on: (event, listener) => {
744
+ this.on(event, listener);
745
+ },
746
+ /* c8 ignore stop */
747
+ // biome-ignore lint/suspicious/noExplicitAny: CacheInstance requires any type
748
+ emit: (event, ...args) => this.emit(event, ...args)
749
+ };
750
+ const getOrSetOptions = {
751
+ cache: cacheAdapter,
752
+ cacheId: this._cacheId,
753
+ ttl: options?.ttl ?? this._ttl,
754
+ cacheErrors: options?.cacheErrors,
755
+ throwErrors: options?.throwErrors
756
+ };
757
+ return (0, import_memoize.getOrSet)(key, function_, getOrSetOptions);
758
+ }
759
+ /**
760
+ * Will hash an object using the specified algorithm. The default algorithm is 'sha256'.
761
+ * @param {any} object the object to hash
762
+ * @param {string} algorithm the hash algorithm to use. The default is 'sha256'
763
+ * @returns {string} the hash of the object
764
+ */
765
+ hash(object, algorithm = import_utils.HashAlgorithm.SHA256) {
766
+ const validAlgorithm = Object.values(import_utils.HashAlgorithm).includes(algorithm) ? algorithm : import_utils.HashAlgorithm.SHA256;
767
+ return (0, import_utils.hash)(object, { algorithm: validAlgorithm });
768
+ }
769
+ async setManyKeyv(keyv, items) {
770
+ const entries = [];
771
+ for (const item of items) {
772
+ const finalTtl = (0, import_utils.shorthandToMilliseconds)(item.ttl ?? this._ttl);
773
+ entries.push({ key: item.key, value: item.value, ttl: finalTtl });
774
+ }
775
+ await keyv.setMany(entries);
776
+ return true;
777
+ }
778
+ async hasManyKeyv(keyv, keys) {
779
+ const promises = [];
780
+ for (const key of keys) {
781
+ promises.push(keyv.has(key));
782
+ }
783
+ return Promise.all(promises);
784
+ }
785
+ /**
786
+ * Processes a single key from secondary store for getRaw operation
787
+ * @param primary - the primary store to use
788
+ * @param secondary - the secondary store to use
789
+ * @param key - The key to retrieve from secondary store
790
+ * @returns Promise containing the result and TTL information
791
+ */
792
+ async processSecondaryForGetRaw(primary, secondary, key) {
793
+ const secondaryResult = await secondary.getRaw(key);
794
+ if (secondaryResult?.value) {
795
+ this.emit("cache:hit" /* CACHE_HIT */, {
796
+ key,
797
+ value: secondaryResult.value,
798
+ store: "secondary"
799
+ });
800
+ const cascadeTtl = (0, import_utils.getCascadingTtl)(this._ttl, this._primary.ttl);
801
+ const expires = secondaryResult.expires ?? void 0;
802
+ const ttl = (0, import_utils.calculateTtlFromExpiration)(cascadeTtl, expires);
803
+ const setItem = { key, value: secondaryResult.value, ttl };
804
+ await this.hook("BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */, setItem);
805
+ await primary.set(setItem.key, setItem.value, setItem.ttl);
806
+ return { result: secondaryResult, ttl };
807
+ } else {
808
+ this.emit("cache:miss" /* CACHE_MISS */, { key, store: "secondary" });
809
+ return void 0;
810
+ }
811
+ }
812
+ /**
813
+ * Processes a single key from secondary store for getRaw operation in non-blocking mode
814
+ * Non-blocking mode means we don't wait for secondary operations that update primary store
815
+ * @param primary - the primary store to use
816
+ * @param secondary - the secondary store to use
817
+ * @param key - The key to retrieve from secondary store
818
+ * @returns Promise containing the result and TTL information
819
+ */
820
+ async processSecondaryForGetRawNonBlocking(primary, secondary, key) {
821
+ const secondaryResult = await secondary.getRaw(key);
822
+ if (secondaryResult?.value) {
823
+ this.emit("cache:hit" /* CACHE_HIT */, {
824
+ key,
825
+ value: secondaryResult.value,
826
+ store: "secondary"
827
+ });
828
+ const cascadeTtl = (0, import_utils.getCascadingTtl)(this._ttl, this._primary.ttl);
829
+ const expires = secondaryResult.expires ?? void 0;
830
+ const ttl = (0, import_utils.calculateTtlFromExpiration)(cascadeTtl, expires);
831
+ const setItem = { key, value: secondaryResult.value, ttl };
832
+ this.hook("BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */, setItem).then(async () => {
833
+ await primary.set(setItem.key, setItem.value, setItem.ttl);
834
+ }).catch((error) => {
835
+ this.emit("error" /* ERROR */, error);
836
+ });
837
+ return { result: secondaryResult, ttl };
838
+ } else {
839
+ this.emit("cache:miss" /* CACHE_MISS */, { key, store: "secondary" });
840
+ return void 0;
841
+ }
842
+ }
843
+ /**
844
+ * Processes missing keys from secondary store for getManyRaw operation
845
+ * @param primary - the primary store to use
846
+ * @param secondary - the secondary store to use
847
+ * @param keys - The original array of keys requested
848
+ * @param result - The result array from primary store (will be modified)
849
+ * @returns Promise<void>
850
+ */
851
+ async processSecondaryForGetManyRaw(primary, secondary, keys, result) {
852
+ const missingKeys = [];
853
+ for (const [i, key] of keys.entries()) {
854
+ if (!result[i]) {
855
+ missingKeys.push(key);
856
+ }
857
+ }
858
+ const secondaryResults = await secondary.getManyRaw(missingKeys);
859
+ let secondaryIndex = 0;
860
+ for await (const [i, key] of keys.entries()) {
861
+ if (!result[i]) {
862
+ const secondaryResult = secondaryResults[secondaryIndex];
863
+ if (secondaryResult && secondaryResult.value !== void 0) {
864
+ result[i] = secondaryResult;
865
+ this.emit("cache:hit" /* CACHE_HIT */, {
866
+ key,
867
+ value: secondaryResult.value,
868
+ store: "secondary"
869
+ });
870
+ const cascadeTtl = (0, import_utils.getCascadingTtl)(this._ttl, this._primary.ttl);
871
+ let { expires } = secondaryResult;
872
+ if (expires === null) {
873
+ expires = void 0;
874
+ }
875
+ const ttl = (0, import_utils.calculateTtlFromExpiration)(cascadeTtl, expires);
876
+ const setItem = { key, value: secondaryResult.value, ttl };
877
+ await this.hook(
878
+ "BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */,
879
+ setItem
880
+ );
881
+ await primary.set(setItem.key, setItem.value, setItem.ttl);
882
+ } else {
883
+ this.emit("cache:miss" /* CACHE_MISS */, {
884
+ key,
885
+ store: "secondary"
886
+ });
887
+ }
888
+ secondaryIndex++;
889
+ }
890
+ }
891
+ }
892
+ /**
893
+ * Processes missing keys from secondary store for getManyRaw operation in non-blocking mode
894
+ * Non-blocking mode means we don't wait for secondary operations that update primary store
895
+ * @param secondary - the secondary store to use
896
+ * @param keys - The original array of keys requested
897
+ * @param result - The result array from primary store (will be modified)
898
+ * @returns Promise<void>
899
+ */
900
+ async processSecondaryForGetManyRawNonBlocking(primary, secondary, keys, result) {
901
+ const missingKeys = [];
902
+ for (const [i, key] of keys.entries()) {
903
+ if (!result[i]) {
904
+ missingKeys.push(key);
905
+ }
906
+ }
907
+ const secondaryResults = await secondary.getManyRaw(missingKeys);
908
+ let secondaryIndex = 0;
909
+ for await (const [i, key] of keys.entries()) {
910
+ if (!result[i]) {
911
+ const secondaryResult = secondaryResults[secondaryIndex];
912
+ if (secondaryResult && secondaryResult.value !== void 0) {
913
+ result[i] = secondaryResult;
914
+ this.emit("cache:hit" /* CACHE_HIT */, {
915
+ key,
916
+ value: secondaryResult.value,
917
+ store: "secondary"
918
+ });
919
+ const cascadeTtl = (0, import_utils.getCascadingTtl)(this._ttl, this._primary.ttl);
920
+ let { expires } = secondaryResult;
921
+ if (expires === null) {
922
+ expires = void 0;
923
+ }
924
+ const ttl = (0, import_utils.calculateTtlFromExpiration)(cascadeTtl, expires);
925
+ const setItem = { key, value: secondaryResult.value, ttl };
926
+ this.hook("BEFORE_SECONDARY_SETS_PRIMARY" /* BEFORE_SECONDARY_SETS_PRIMARY */, setItem).then(async () => {
927
+ await primary.set(setItem.key, setItem.value, setItem.ttl);
928
+ }).catch((error) => {
929
+ this.emit("error" /* ERROR */, error);
930
+ });
931
+ } else {
932
+ this.emit("cache:miss" /* CACHE_MISS */, {
933
+ key,
934
+ store: "secondary"
935
+ });
936
+ }
937
+ secondaryIndex++;
938
+ }
939
+ }
940
+ }
941
+ setTtl(ttl) {
942
+ if (typeof ttl === "string" || ttl === void 0) {
943
+ this._ttl = ttl;
944
+ } else if (ttl > 0) {
945
+ this._ttl = ttl;
946
+ } else {
947
+ this._ttl = void 0;
948
+ }
949
+ }
950
+ };
951
+ // Annotate the CommonJS export names for ESM import in node:
952
+ 0 && (module.exports = {
953
+ Cacheable,
954
+ CacheableEvents,
955
+ CacheableHooks,
956
+ CacheableMemory,
957
+ CacheableStats,
958
+ HashAlgorithm,
959
+ Keyv,
960
+ KeyvCacheableMemory,
961
+ KeyvHooks,
962
+ calculateTtlFromExpiration,
963
+ createKeyv,
964
+ getCascadingTtl,
965
+ getOrSet,
966
+ hash,
967
+ shorthandToMilliseconds,
968
+ shorthandToTime,
969
+ wrap,
970
+ wrapSync
971
+ });